diff --git a/.agents/skills/treeland-build/SKILL.md b/.agents/skills/treeland-build/SKILL.md new file mode 100644 index 0000000000..99a2c8fe4a --- /dev/null +++ b/.agents/skills/treeland-build/SKILL.md @@ -0,0 +1,113 @@ +--- +name: treeland-build +description: "配置、编译与安装 treeland:CMake preset 与构建选项、依赖、安装前缀与安装去向、常见构建失败。在 configure/build/install treeland、调整 CMake 选项(`WITH_SUBMODULE_WAYLIB`、`BUILD_TREELAND_PROTOCOL_TESTS`、`BUILD_TREELAND_DEBUG`、`ADDRESS_SANITIZER`、`DISABLE_XWAYLAND`、`TREELAND_INSTALL_DEV`)、排查 `TreelandProtocols` 找不到、产物装到 `/usr/local` 与 unit 混装、`-Werror` 编译失败时使用。" +--- + +# 构建与安装 + +> **铁律**:装到系统时 `-DCMAKE_INSTALL_PREFIX=/usr` 必须在 **configure** 阶段给。systemd unit 目录由 pkg-config 直接解析成绝对路径(`/usr/lib/systemd/system`、`/usr/lib/systemd/user`),**不受前缀影响**;不给 `/usr` 就会出现二进制装到 `/usr/local/bin`、unit 却落在 `/usr/lib/systemd/system` 的混装。`cmake --install --prefix` 也改不动这些绝对路径。 + +## 前置依赖 +- CMake ≥ 3.25(`cmake_minimum_required(VERSION 3.25.0)`) +- C++20、C23;GCC 或 Clang +- Ninja(`CMakePresets.json` 里的 preset 都用它) +- pkg-config +- Qt ≥ 6.8(Core/Gui/Qml/Quick/QuickControls2/RemoteObjects/Network/DBus/Test…)、Dtk6、wlroots 0.20、外部 CMake 包 `TreelandProtocols` +- DDM ≥ 0.5.0(`find_package(DDM 0.5.0 REQUIRED COMPONENTS Common)`,在 `src/CMakeLists.txt`);`DISABLE_DDM=ON` 时不要求。系统里残留低版本 DDM 会直接在 configure 阶段报版本不兼容 +- 完整清单以 `debian/control` 为准;`apt build-dep .` 一次装齐 + +## 配置 +preset 只固定生成器与 `binaryDir`(`${sourceDir}/build`),**没有** `CMAKE_BUILD_TYPE`,也没有安装前缀,所以这两项要用 `-D` 补上;`-D` 可以和 `--preset` 同时用。 + +```bash +# 日常开发:对齐 CI 的 -Wall -Wextra -Werror,提前发现会挂 CI 的告警 +cmake --preset ci -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX=/usr + +# 调试运行(断点、符号、treeland-debug 开箱可用) +cmake --preset default -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX=/usr + +# 只想编译不装到系统 +cmake --preset default -DCMAKE_BUILD_TYPE=Debug +``` + +| preset | 生成器 | 说明 | +|--------|--------|------| +| `default` | Ninja | 默认配置 | +| `clang` | Ninja | 用 clang/clang++ | +| `ci` | Ninja | 加 `-Wall -Wextra -Werror`(另带两个 `-Wno-*`),CI 同款 | +| `ci-clang` | Ninja | clang + `-Werror` | + +`CMAKE_BUILD_TYPE=Debug` 的副作用(细节见 `treeland-debug` skill): + +- 定义 `TREELAND_DEBUG_DEV_BUILD`:socket 名变成 `org.deepin.dde.treeland.debug-dev`,`treeland-debug` 免 polkit 提权 +- 不传 `CMAKE_BUILD_TYPE` 时既不是 Debug 也不是 Release,上面这个宏都不会定义 + +调试 Remote Object 的开关是 `remoteDebug`(默认关,用 `treeland-debug debug on` 打开);**Debug 构建不看这个开关,始终开启**(socket 名带 `-dev`),所以 dev 实例里不需要也不应该去改它。 + +## 常用配置选项 +| 选项 | 默认 | 说明 | +|------|------|------| +| `WITH_SUBMODULE_WAYLIB` | `ON` | `ON` 用仓库内的 `waylib/` 源码;`OFF` 用系统已安装的 waylib | +| `BUILD_TREELAND_PROTOCOL_TESTS` | `ON` | `tests/protocols/` 整棵树的开关 | +| `BUILD_TREELAND_DEBUG` | `ON` | `treeland-debug` 客户端(定义在 `tools/treeland-debug/CMakeLists.txt`) | +| `ADDRESS_SANITIZER` | `OFF` | 加 `-fsanitize=address`;报告去向由 `ASAN_OPTIONS` 决定,本地直跑在 stderr,通过 `treeland.service` 启动才写到 `/tmp/treeland-asan*` | +| `BUILD_TREELAND_EXAMPLES` | `OFF` | 示例客户端 | +| `TREELAND_INSTALL_DEV` | `OFF` | 装开发文件(头文件、CMake config、`.so` 链接) | +| `DISABLE_DDM` | `OFF` | 关掉 DDM 与 greeter | +| `DISABLE_XWAYLAND` | `OFF` | 关闭 Treeland/waylib 的 Xwayland 路径,并覆盖 wlroots 的有效 `WLROOTS_XWAYLAND` 为 `OFF`;不构建 Xwayland helper、xwindow-control 模块及其测试 | +| `EXT_SESSION_LOCK_V1` | `ON` | 用 ext-session-lock 作为 DDM 之外的锁屏方案 | +| `USE_BUILD_TREE_WALLPAPER_FACTORY` | `OFF` | 直接用构建树里的 wallpaper factory | + +使用系统 Waylib(`WITH_SUBMODULE_WAYLIB=OFF`)时,若其没有 Xwayland 支持,必须同时设置 `DISABLE_XWAYLAND=ON`;配置阶段会编译探测系统头文件,提前拒绝特性不匹配的组合。探测失败的其他原因见 CMake configure 日志。 + +直接覆盖安装时,从启用 Xwayland 切换到禁用会清理本项目先前安装的 Xwayland user units、wants 链接和 drop-in;清理遵守 `DESTDIR`,不会删除 `/etc` 中的用户覆盖配置。安装后需重新加载对应的 systemd user manager(`systemctl --user daemon-reload`);当前已启动的 helper 会在会话重启后退出。 + +`WITH_SUBMODULE_WAYLIB` 的名字是历史遗留:`waylib/` 是直接提交在本仓库里的源码,不是 git submodule(没有 `.gitmodules`),`git clone --recursive` 对它是空操作。 + +## 构建 +```bash +cmake --build build +cmake --build build --parallel $(nproc) +cmake --build build --target treeland # 只编主程序 +cmake --build build --target treeland-debug # 只编调试客户端 +``` + +`cmake --build` 自动调用底层生成器;`--parallel` 是 CMake 内置参数,不需要区分 Ninja/Make。 + +## 安装 +```bash +sudo cmake --install build # 全量 +sudo cmake --install build --component treeland-debug # 只装调试客户端 +DESTDIR=/tmp/stage cmake --install build # 打包/沙箱,不碰系统 +``` + +安装去向(`CMAKE_INSTALL_PREFIX=/usr` 时): + +| 内容 | 路径(`CMAKE_INSTALL_PREFIX=/usr`) | +|------|------| +| `treeland`、`treeland.sh` | `/usr/bin` | +| `treeland-sd`、`treeland-xwayland`、`treeland-screensaver`、`treeland-session-helper` | `/usr/libexec` | +| `libtreeland`、插件 | `${CMAKE_INSTALL_LIBDIR}`(Debian 上为 `/usr/lib/`)、`${CMAKE_INSTALL_LIBDIR}/treeland/plugins` | +| systemd system unit(`treeland.service`) | `/usr/lib/systemd/system`(pkg-config 绝对路径) | +| systemd user unit(session-helper、screensaver) | `/usr/lib/systemd/user`(pkg-config 绝对路径) | +| 系统配置 | `/etc/treeland`(`CMAKE_INSTALL_FULL_SYSCONFDIR` 绝对路径) | +| DConfig 描述文件 | `/usr/share/dsg/configs/org.deepin.dde.treeland` | +| polkit 策略、D-Bus 策略 | `/usr/share/polkit-1/actions`、`/usr/share/dbus-1/system.d` | +| wayland-sessions | `/usr/share/wayland-sessions` | + +`TREELAND_INSTALL_DEV=OFF`(默认)时 `libtreeland` 不装 `.so` 链接、头文件与 CMake config;需要给别人链接才开它。 + +systemd unit 目录和 `/etc/treeland` 在 configure 阶段就被解析成绝对路径,`cmake --install --prefix` 改不动它们 —— 这就是铁律的由来。 + +装完 systemd unit 后: + +```bash +sudo systemctl daemon-reload +``` + +## 常见问题 +1. `find_package(TreelandProtocols)` 失败:它不会被自动发现,必须装包,或用 `-DTreelandProtocols_DIR=` 指向它的 CMake 配置目录。CMake 按 `/usr/local` → `/usr` 的顺序搜索,`/usr/local` 下残留的旧 config 会遮蔽 `/usr` 下的正确版本;此时清掉缓存项重新 configure(`cmake -S . -B build -U TreelandProtocols_DIR`)。 +2. 装完发现二进制在 `/usr/local/bin` 而 unit 在 `/usr/lib/systemd/system`:前缀给晚了。systemd 目录是 pkg-config 的绝对路径,跟前缀无关,重来一次 configure(见铁律)。 +3. 新增目录或改了 `CMakeLists.txt` 后新 target 不出现:重新 configure;正常的 `cmake --build` 会自动触发 CMake 重新生成,但新增 target 的 IDE 缓存或直接指定新 target 的构建入口可能仍需手动 configure。 +4. `-Werror` 报错但不确定是不是自己引入的:`cmake --preset ci` 复现;只用 `default` 编译会漏掉这类告警。 +5. 运行的是刚装的版本还是构建树里的版本:构建树里跑 `./build/src/treeland.sh`,装好的走 `treeland.sh`,两者调试 socket 与日志去向不同,见 `treeland-debug` skill。 diff --git a/.agents/skills/treeland-dconfig/SKILL.md b/.agents/skills/treeland-dconfig/SKILL.md new file mode 100644 index 0000000000..de41466bce --- /dev/null +++ b/.agents/skills/treeland-dconfig/SKILL.md @@ -0,0 +1,307 @@ +--- +name: treeland-dconfig +description: "新增、修改、评审与调试 treeland 的 DConfig 配置:描述文件字段、配置作用域与 subpath、生成的配置封装类、异步初始化、override 与序列号演进、运行时 dde-dconfig 检查。在改动 `misc/dconfig/*.json`、`dtk_add_config_to_cpp` 生成的类(`TreelandConfig`、`TreelandUserConfig`、`AnimationConfig`、`OutputConfig`、`SeatUserDConfig`、`AppConfig`)、把设置迁入 DConfig、排查配置读不到或不生效时使用。" +--- + +# Treeland DConfig 配置 + +> **铁律**:用户业务对象通过构造时注入的固定配置访问设置,不查询 Session 或活动用户。Session/DesktopEnvironment 组装边界负责解析配置与按用户名 subpath 隔离的 provider;仅共享运行时的活动桌面兼容入口使用 `WaylandServer::config()`(动画开关为该入口上的 `WaylandServer::animationConfig()`)。不要因为全局模式以 `dde` 运行就把用户偏好写进 `TreelandConfig`。显示模式、主屏、复制/单屏配置为系统级;各 Session 的窗口、协议资源和专属区域仍独立。 + +## 范围 +本 skill 用于由 Desktop Spec Group 配置元数据描述、并通过 DTK DConfig 生成的 C++ 封装类消费的 treeland 配置。 + +主要仓库位置: + +- `misc/dconfig/*.json` +- `misc/dconfig/CMakeLists.txt` +- `src/CMakeLists.txt` 中的 `dtk_add_config_to_cpp(...)` 调用 +- `build/src/` 下的生成头文件,例如 `build/src/treelandconfig.hpp`、`build/src/treelanduserconfig.hpp`、`build/src/outputconfig.hpp`、`build/src/seatuserconfig.hpp`、`build/src/appconfig.hpp` +- `src/` 下的消费方 + +规范参考: + +- Desktop Spec Group《配置文件规范》:`https://desktopspec.org/unstable/%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E8%A7%84%E8%8C%83.html`。 +- 该规范处于 `unstable`,需要确认精确细节时以线上当前版本为准。本 skill 依据 1.0 版(2023.09.01 修订)编写。 + +## 目标 +让 DConfig 改动同时满足 Desktop Spec Group 元数据格式与 treeland 的生成封装用法: + +- JSON 描述文件合法且兼容 +- 正确的生成 C++ 类暴露类型化 getter、setter 与变更信号 +- 读写运行时值之前先处理异步初始化 +- 公开设置在非大版本升级间保持兼容 +- 安装与构建集成保持同步 + +## Treeland 运行模式 +treeland 有两种运行模式,DConfig 归属必须同时考虑两者: + +- 用户模式:用户登录后启动 treeland,行为类似普通窗口管理器,以该用户身份运行。 +- 全局模式:首选模式。单个 treeland 进程管理所有用户,用户切换不重启合成器,进程以 `dde` 用户运行。 + +由于存在全局模式,**绝不要**用 treeland 进程的 uid 推断目标用户的设置。按归属划分: + +- 全局配置:与当前登录用户无关的进程/合成器策略。通过 `WaylandServer::globalConfig()` 与 `TreelandConfig` 访问。 +- 用户配置:跟随当前选中/登录用户的设置。通过 `WaylandServer::config()` 与 `TreelandUserConfig` 访问;`DConfigManager` 在 `UserModel::currentUserNameChanged` 触发时解析缓存对象;`WaylandServer` 替换当前配置指针并发出 `configChanged()`。 + +`DConfigManager` 持有生成的配置对象。在 `WaylandServer::WaylandServer` 中,桌面侧观察 `DConfigManager::initialUserConfig()` 与 `DConfigManager::globalConfig()`。 + +`DConfigManager` 解析用户与 seat 配置对象,并等待两者都初始化完成;用户切换后丢弃过期的完成通知。`initializeActiveUserConfig()` 观察用户变化;`stopActiveUserConfig()` 在桌面销毁时解绑桌面侧监听。其 `configReady` 信号驱动 `WaylandServer::applyCurrentUserConfig`,后者在当前指针变化时发出 `configChanged()`,更新个性化用户 id,并同步光标、输入、壁纸与工作区设置。`WaylandServer::config()` 与 `WaylandServer::globalConfig()` 直接暴露这些配置对象。DesktopEnvironment 所属的 Workspace、WallpaperManager、InputManager 和 SessionOutputManager 使用构造时注入的固定配置或配置 provider;`WaylandServer::config()` 仅作当前桌面的兼容入口,而不是后台用户对象的配置来源。用户级设置不使用 `m_globalConfig`;配置对象由 `DConfigManager` 复用,不由 `WaylandServer` 自己重建。 + +## 描述文件格式 +DConfig 描述文件是 JSON 元数据文件。treeland 中它们位于 `misc/dconfig/`,顶层结构如下: + +```json +{ + "magic": "dsg.config.meta", + "version": "1.0", + "contents": { + "keyName": { + "value": true, + "serial": 0, + "flags": ["global"], + "name": "Display Name", + "name[zh_CN]": "中文名称", + "description": "What this setting controls", + "description[zh_CN]": "此配置项的用途", + "permissions": "readwrite", + "visibility": "public" + } + } +} +``` + +顶层规则: + +- 描述文件的 `magic` 恒为 `dsg.config.meta`。 +- `version` 使用规范的 `major.minor` 格式;treeland 当前为 `1.0`。 +- `contents` 是扁平对象,不要嵌套配置项。 +- 配置项顺序无语义,便于评审时把相关设置放在一起。 + +## 选择文件 +先确定该设置属于合成器全局还是当前用户所有。全局模式下这取决于语义归属,而不是 treeland 进程的 uid。 + +按归属与查找方式选择描述文件: + +- `org.deepin.dde.treeland.json` → 不随当前用户变化的合成器全局设置;生成 `TreelandConfig` / `treelandconfig.hpp`;通常通过 `WaylandServer::globalConfig()` 访问。 +- `org.deepin.dde.treeland.user.json` → 当前用户会话、个性化、工作区、光标、主题等设置;生成 `TreelandUserConfig` / `treelanduserconfig.hpp`;通过 `WaylandServer::config()` 访问,用户切换时从 DConfigManager 缓存中选取。 +- `org.deepin.dde.treeland.animation.json` → 当前用户的动画开关;生成 `AnimationConfig` / `animationconfig.hpp`;由 `DConfigManager::animationConfig(userName)` 缓存,通过 `WaylandServer::animationConfig()` 访问并监听 `animationConfigChanged()`。键名直接用 `windowOpen`、`workspaceSwitch` 等效果名,不重复 `AnimationEnabled`。初始化完成前使用默认启用状态,初始化完成或用户切换时重新绑定并刷新效果。 +- `org.deepin.dde.treeland.output.json` → 按 output 的设置;生成 `OutputConfig` / `outputconfig.hpp`;当前代码使用 `OutputConfig::createByName(...)` 和 `/`,保存系统级物理身份、分辨率、刷新率、缩放、位置、旋转、颜色等参数。所有 Session 注入同一个 output 配置对象,不增加用户名 subpath。 +- `org.deepin.dde.treeland.user.seat.json` → 当前用户的输入/seat 设置;生成 `SeatUserDConfig` / `seatuserconfig.hpp`;每个 Session 持有独立 InputManager,固定读取所属用户名的 seat 配置;活动 manager 才连接硬件应用路径。`keyboardNumLock` 也位于该用户 seat 配置;旧全局键保留兼容,但新输入管理路径不再读写它。 +- `org.deepin.dde.treeland.app.json` → 按应用的设置;生成 `AppConfig` / `appconfig.hpp`;`WindowConfigStore` 使用 subpath `"/" + appId`。 + +新增描述文件前,先确认上述某个作用域已经合适。确实需要新文件时,按下面“新增描述文件”一节执行。 + +默认选择指引: + +- 设置在选定任何用户之前就影响合成器基础设施 → 用 `TreelandConfig`。 +- 用户期望设置跟随其账户跨登录/切换 → 用 `TreelandUserConfig` 或 `SeatUserDConfig`。 +- 系统显示模式(主屏、单屏、复制组)→ 用 `TreelandConfig`;每块物理输出参数 → 用共享 `OutputConfig`。 +- SessionOutput 只隔离窗口、LayerSurface 和专属区域,不能为用户切换恢复一套显示参数。 +- 设置绑定应用 id → 用 `AppConfig`。 +- 不要因为全局模式以 `dde` 运行就把用户偏好塞进 `TreelandConfig`。 + +## 配置项字段 +每个 treeland 配置项都应包含: + +- `value`:默认值。使用常规 JSON 类型。该类型决定生成的 C++ 访问器类型。 +- `serial`:单调递增整数,新键通常为 `0`。 +- `flags`:数组。用户级设置用 `[]`。treeland 在全局模式下以 `dde` 用户运行,用户隔离靠描述文件名加 `"/" + userName` subpath,而不是进程 uid,因此这里不需要 `global`。规范对 `global` 的定义是“读写时忽略用户身份,所有用户拿到同一份数据”;只有当某项在所有用户间确实完全相同时才加,且绝不用它替代 subpath。需要禁止 OEM/域管覆盖时用 `["nooverride"]`。 +- `name` 与 `name[zh_CN]`:简短的用户可见名称。 +- `description` 与 `description[zh_CN]`:运维含义、有效范围、枚举值、单位与副作用。 +- `permissions`:`readonly` 或 `readwrite`。 +- `visibility`:`private` 或 `public`。 + +`flags` 选择对照: + +| 场景 | `flags` | +| --- | --- | +| 用户级设置 | `[]`,靠 `"/" + userName` subpath 区分用户 | +| 所有用户共享同一份数据 | `["global"]` | +| 不允许 OEM/域管覆盖 | `["nooverride"]`(可与其他标记组合) | + +规范中的兼容性规则: + +- `public` 设置属于外部 API。兼容版本中不得删除,也不得改变其含义、`permissions`、`visibility` 或 `flags`。 +- `public` 键仅修改 `value`、`name` 或 `description` 不构成兼容性破坏。 +- `private` 设置是 treeland 内部实现,可以更自由地演进。 +- 当含义、校验或初始化语义变化、需要让旧存储值失效时,递增 `serial`。 +- 省略 `serial` 时忽略存储值的 serial 校验。treeland 中保持显式 `serial`。 + +## 命名 +键名使用小驼峰,因为 `dtk_add_config_to_cpp` 会据此生成小驼峰 getter 与 Pascal 风格变更信号: + +- 键 `quickSwitchTimeout` → getter `quickSwitchTimeout()`、setter `setQuickSwitchTimeout(...)`、信号 `quickSwitchTimeoutChanged` +- 键 `keyboardNumLock` → getter `keyboardNumLock()`、setter `setKeyboardNumLock(...)` + +除非周边协议或库名已在用缩写,否则避免缩写。单位不明显时把单位写进键名,例如 `prelaunchSplashTimeoutMs`。 + +## 取值与描述 +选择在任何运行时服务就绪前都有效的默认值。 + +对受约束的值,把约束同时写进中英文描述: + +- 数值范围与单位,例如毫秒、像素、开尔文,或 `-1.0` 到 `1.0` +- 枚举取值及其含义 +- `0`、空字符串或 `false` 是否有特殊行为 +- 该设置是仅启动时读取还是实时生效 + +如果消费方 C++ 路径也需要防御非法运行时值,不要只用文字描述校验规则。当非法 DConfig 值会影响合成器行为时,在消费边界补充或复用校验。 + +## 生成的 C++ 集成 +treeland 在 `src/CMakeLists.txt` 中用 `dtk_add_config_to_cpp(...)` 生成类型化封装。 + +使用已有描述文件时: + +1. 在 `.cpp` 消费方 include 生成头文件,尽量避免放进 public 头文件。需要在 Qt 属性中使用该类型的头文件用 `Q_MOC_INCLUDE`。 +2. 使用生成的 getter、setter 与变更信号,不要直接写裸键名字符串。 +3. 设置需要实时生效时连接变更信号。 +4. 若设置在启动阶段读取,处理 DConfig 异步初始化。 +5. 通过 `WaylandServer::config()` 监听当前用户设置时,记住该对象会在用户切换时被替换。连接 `WaylandServer::configChanged()` 并在新的 `TreelandUserConfig` 对象上重新连接各键信号。`WaylandServer::globalConfig()` 是 `CONSTANT`;`WaylandServer::config()` 不是。 + +新代码直接使用当前 DTK API: + +```cpp + if (config->isInitializeSucceeded()) { + applyConfig(); + } else { + connect(config, + &TreelandConfig::configInitializeSucceed, + this, + [this] { applyConfig(); }); + } +``` + +既有代码可能仍保留为兼容旧 DTK 而写的 `#if *_DCONFIG_FILE_VERSION_MINOR > 0` 分支(调用已废弃的 `isInitializeSucceed()`)。不要把该模式复制到新代码。除非任务本身就要改动那段代码,也不要仅为删除它而产生无关改动。 + +除非周边代码已有明确回退且行为是有意为之,否则不要从未初始化的配置对象读取、写入或发出协议状态。 + +## 生成头文件事实 +不要在源码树里搜索生成的配置头文件,它们由 CMake/dconfig2cpp 生成到 `build/src/`。 +执行 `cmake --preset default` 后直接读生成文件,例如 `build/src/treelanduserconfig.hpp`。 + +生成头文件呈现的 API 与约定、`create(...)`/`createByName(...)` 的完整签名见 +[references/generated-cpp.md](references/generated-cpp.md)。日常要记住的四条: + +- 每个键有 `Q_PROPERTY`(getter、setter、`*Changed` 信号、`reset*`)和键名宏。 +- 初始化是异步的:用 `isInitializeSucceeded()` 或 `configInitializeSucceed(DConfig *)`, + 不要用已废弃的 `isInitializeSucceed()`。 +- 已废弃 API 兼容分支只出现在既有代码里,新代码不要复制。 + +- 类同时发出具体的 `keyChanged()` 信号与通用的 `valueChanged(const QString &key, const QVariant &value)`。 + +## 新增描述文件 +优先扩展已有描述文件。确实需要新的 DConfig 描述文件时: + +1. 按标准 `dsg.config.meta` 结构新增 `misc/dconfig/org.deepin.dde.treeland..json`。 +2. 把该文件加入 `misc/dconfig/CMakeLists.txt`,使安装输出落在 `${CMAKE_INSTALL_DATADIR}/dsg/configs/org.deepin.dde.treeland`。配置后用 `build/misc/dconfig/cmake_install.cmake` 确认。 +3. 在 `src/CMakeLists.txt` 增加 `dtk_add_config_to_cpp(...)` 块: + + ```cmake + dtk_add_config_to_cpp( + NEW_SCOPE_CONFIG + "${PROJECT_SOURCE_DIR}/misc/dconfig/org.deepin.dde.treeland..json" + OUTPUT_FILE_NAME "config.hpp" + CLASS_NAME "Config" + ) + ``` + +4. 把生成的变量(例如 `${NEW_SCOPE_CONFIG}`)加入 `qt_add_qml_module(libtreeland SOURCES ...)` 列表。这一步是必需的,否则生成头文件不参与 target sources,moc/autogen 看不到该 `QObject` 类。 +5. 执行 `cmake --preset default` 重新生成头文件。 +6. 检查 `build/src/config.hpp`(不是源码树),确认: + - `Q_CLASSINFO("DConfigFileName", "...")` + - `Q_CLASSINFO("DConfigFileVersion", "1.0")` + - 版本/键宏 + - `Q_PROPERTY` 类型 + - `create(...)` / `createByName(...)` 签名 + - `configInitializeSucceed` / `configInitializeFailed` 信号 +7. 使用生成头文件与异步初始化模式新增 C++ 消费方。 + +## 作用域与 subpath 用法 +Desktop Spec 支持 `subpath` 查找。treeland 中保持既有构造方式: + +- 按邻近代码同样的方式使用 `create(...)` / `createByName(...)` +- 保持按应用、按 output 的查找名与 subpath 和既有消费方一致 +- 未经确认描述文件安装与回退行为,不要自创新的 subpath 方案 + +规范中描述文件查找可以沿父 subpath 回退,但带 subpath 的运行时存储缓存不回退。处理按 output、按应用的设置时要记住这一差异。 + +当前 treeland 的 subpath 模式: + +- 当前用户配置:`"/" + currentUserName` +- 用户选定前的初始/默认用户配置:`"/dde"` +- seat 用户配置:`"/" + userName + "/" + seatName`(`DConfigManager::userSeatConfig(...)`,由固定 Session 的 `InputManager::seatUserConfig(...)` 进入) +- 系统 output 配置:`"/" + outputName`,保存硬件 UUID 和显示参数;旧 `//outputs/` 路径不再读取或写入 +- 应用配置:`"/" + appId` + +QML 与 C++ 的实时监听要注意 `WaylandServer` 上的实际属性: + +```cpp +Q_PROPERTY(TreelandUserConfig* config READ config NOTIFY configChanged FINAL) +Q_PROPERTY(TreelandConfig* globalConfig READ globalConfig CONSTANT FINAL) +``` + +这意味着 `WaylandServer.config` 会在当前用户变化时改变,而 `WaylandServer.globalConfig` 恒定。仅使用活动桌面兼容入口的 QML 绑定通过 `WaylandServer.config` 随 `configChanged()` 重新求值;从该入口保存指针或连接信号的 C++ 代码也必须重新订阅。 + +属于固定 Desktop 的窗口和组件使用注入的 `DesktopEnvironment::config()`(`CONSTANT`,成员为 `TreelandUserConfig *const`),不监听 `WaylandServer::configChanged()`。例如 `SurfaceWrapper` 在 `setSession()` 后订阅所属 Desktop 的半径变化;活动用户切换不能改变已有窗口的配置归属。不要把活动配置入口的重绑要求套用到这些对象上。 + +## override 与可变性 +规范允许 override 文件修改 `value` 与 `permissions`,除非该项带 `nooverride`。 + +对 treeland 的含义: + +- 代码必须容忍 `permissions: readonly`;setter 可能失败或被忽略,取决于 DConfig 实现。 +- 该状态可用时,UI 或协议写入路径不应展示可写控件。 +- 不得被 OEM/域管策略覆盖的不变量使用 `nooverride`。 +- 不要用 `global` 标志来区分用户。用户级描述文件保持 `flags: []` 并依赖 `"/" + userName` subpath;`global` 会让存储忽略用户身份。 + +## 评审清单 +评审 DConfig 改动时逐项确认: + +1. 描述文件有 `magic: "dsg.config.meta"`、`version: "1.0"`,且 `contents` 扁平。 +2. 新键放在与其生命周期、作用域匹配的描述文件中。 +3. 每个配置项都有 `value`、显式 `serial`、`flags`、`name`、`name[zh_CN]`、`description`、`description[zh_CN]`、`permissions`、`visibility`。 +4. `public` 键没有通过改变含义、`permissions`、`visibility` 或 `flags` 破坏兼容性。 +5. 需要让旧存储值失效时递增了 `serial`。 +6. 默认值的 JSON 类型与预期的生成 C++ 类型、消费方假设一致。 +7. 描述中写明了范围、单位、枚举值与特殊值。 +8. 该设置在用户模式与全局模式下行为都正确。 +9. 用户级设置走当前用户配置/subpath 路径,没有被错误地只存到 `dde` 进程用户名下。 +10. 消费方 include 了正确的生成头文件并使用生成的类型化访问器。 +11. 启动阶段读取等待了 DConfig 初始化,或沿用了既有的有意回退模式。 +12. 需要实时生效的设置连接了生成的 `*Changed` 信号。 +13. 新描述文件已从 `misc/dconfig/CMakeLists.txt` 安装,并通过 `dtk_add_config_to_cpp(...)` 接入。 +14. 已构建或至少已 configure,使生成头文件反映新增键。 + +## 验证 +改动涉及生成封装或消费方时,优先用仓库标准命令: + +```bash +cmake --preset default +cmake --build --preset default +ctest --test-dir build --output-on-failure +``` + +仅改描述文件时,另外执行: + +```bash +python3 -m json.tool misc/dconfig/.json >/dev/null +``` + +若构建耗时过高,至少执行 `cmake --preset default` 并检查 `build/src/` 中的生成头文件,确认访问器、setter、信号、创建 helper、class info 与版本宏名称。 + +## 用 dde-dconfig 调试 +`dde-dconfig` 读取的是**已安装**的配置元数据;只改源码树里的 `misc/dconfig/*.json` 不够,先安装项目(描述文件由 `misc/dconfig/CMakeLists.txt` 装到 `${CMAKE_INSTALL_DATADIR}/dsg/configs/org.deepin.dde.treeland`)。 + +最常用的三条: + +```bash +dde-dconfig get -a org.deepin.dde.treeland -r org.deepin.dde.treeland -k +dde-dconfig set -a org.deepin.dde.treeland -r org.deepin.dde.treeland -k -v +dde-dconfig watch -a org.deepin.dde.treeland -r org.deepin.dde.treeland.user -s / -k +``` + +参数映射(`-a`/`-r`/`-s`/`-k`/`-v`/`-u`)、按 output/app/seat 作用域的完整命令、`-m` 元数据查询与取值注意事项见 [references/dde-dconfig.md](references/dde-dconfig.md)。 + +## 参考文件 +- [references/generated-cpp.md](references/generated-cpp.md) —— 生成头文件的类结构、键访问器、版本宏与 `create(...)`/`createByName(...)` 签名。 +- [references/dde-dconfig.md](references/dde-dconfig.md) —— `dde-dconfig` 命令行参数映射与各作用域的完整命令。 diff --git a/.agents/skills/treeland-dconfig/references/dde-dconfig.md b/.agents/skills/treeland-dconfig/references/dde-dconfig.md new file mode 100644 index 0000000000..416589fb12 --- /dev/null +++ b/.agents/skills/treeland-dconfig/references/dde-dconfig.md @@ -0,0 +1,63 @@ +# 用 dde-dconfig 调试 + +由 `SKILL.md` 按需加载:需要手动读写运行时 DConfig 值、检查元数据、或验证实时信号时读本文件。 + +DConfig 描述文件安装之后,用 `dde-dconfig` 做手动运行时检查。该 CLI 读取已安装的配置元数据;只改源码树里的 `misc/dconfig/*.json` 不够。先安装项目或以其他方式把描述文件装到 DSG 配置位置,通常由 `misc/dconfig/CMakeLists.txt` 安装到: + +```text +${CMAKE_INSTALL_DATADIR}/dsg/configs/org.deepin.dde.treeland +``` + +treeland 的参数映射: + +- `-a org.deepin.dde.treeland`:treeland DConfig 封装使用的 app id。 +- `-r `:描述文件/配置 id,通常是描述文件名去掉 `.json`。 +- `-s `:当前用户、output 或应用作用域配置的 subpath。 +- `-k `:配置键。 +- `-v `:`set` 使用的值。 +- `-u `:需要时针对特定用户的配置操作。 + +常用命令: + +```bash +# 列出已安装的可配置 app/resource/subpath 条目 +dde-dconfig list + +# 列出合成器全局 TreelandConfig 的键 +dde-dconfig get -a org.deepin.dde.treeland -r org.deepin.dde.treeland + +# 读写合成器全局键 +dde-dconfig get -a org.deepin.dde.treeland -r org.deepin.dde.treeland -k showOtherUserOption +dde-dconfig set -a org.deepin.dde.treeland -r org.deepin.dde.treeland -k showOtherUserOption -v true + +# 读取当前用户 TreelandUserConfig 的键 +dde-dconfig get -a org.deepin.dde.treeland -r org.deepin.dde.treeland.user -s /rewine -k windowThemeType + +# 读取按应用 AppConfig 的键 +dde-dconfig get -a org.deepin.dde.treeland -r org.deepin.dde.treeland.app -s /deepin-screen-recorder -k enablePrelaunchSplash + +# 重置单个键;省略 -k 则重置该配置文件的所有缓存值 +dde-dconfig reset -a org.deepin.dde.treeland -r org.deepin.dde.treeland -k showOtherUserOption + +# 验证实时信号处理时监听某个键 +dde-dconfig watch -a org.deepin.dde.treeland -r org.deepin.dde.treeland.user -s /rewine -k windowThemeType +``` + +查看元数据用带 `-m` 的 `get`: + +```bash +dde-dconfig get -a org.deepin.dde.treeland -r org.deepin.dde.treeland -k showOtherUserOption -m permissions +dde-dconfig get -a org.deepin.dde.treeland -r org.deepin.dde.treeland -k showOtherUserOption -m visibility +dde-dconfig get -a org.deepin.dde.treeland -r org.deepin.dde.treeland -k showOtherUserOption -m isDefaultValue +dde-dconfig get -a org.deepin.dde.treeland -r org.deepin.dde.treeland -k showOtherUserOption -m name -l zh_CN +``` + +说明: + +- 值由 `dde-dconfig` 解析;使用 JSON 风格取值(`true`、`false`、数字,必要时用带引号的字符串)。不要写 `ture` 这类拼写错误,即使某个本地工具版本看起来会强制接受。 +- `-r org.deepin.dde.treeland` 对应 `TreelandConfig`。 +- `-r org.deepin.dde.treeland.user -s /` 对应 `WaylandServer::config()` 使用的当前用户 subpath 模式。 +- `-r org.deepin.dde.treeland.user.seat -s //` 对应 `SeatUserDConfig`。 +- `-r org.deepin.dde.treeland.output -s /` 对应 `OutputConfig`。 +- `-r org.deepin.dde.treeland.app -s /` 对应 `WindowConfigStore` / `AppConfig`。 +- `watch` 用于检查生成的 `*Changed` 信号与 `WaylandServer.config` 重连行为是否正确接通。 diff --git a/.agents/skills/treeland-dconfig/references/generated-cpp.md b/.agents/skills/treeland-dconfig/references/generated-cpp.md new file mode 100644 index 0000000000..1454ef9fb7 --- /dev/null +++ b/.agents/skills/treeland-dconfig/references/generated-cpp.md @@ -0,0 +1,43 @@ +# 生成的 DConfig C++ 封装 + +本文件记录 `dtk_add_config_to_cpp` / `dconfig2cpp` 生成的头文件长什么样、能依赖哪些 API。 +结论以 `build/src/` 下的实际生成文件为准;这里只是让你不用每次重新推导。 + +不要在源码树里搜索生成的配置头文件,它们由 CMake/dconfig2cpp 生成到 `build/src/`。 + +执行 `cmake --preset default` 后直接检查生成头文件,例如: + +```bash +sed -n '1,260p' build/src/treelanduserconfig.hpp +``` + +当前生成头文件呈现这些 API 与约定: + +- 头文件注释记录 `dconfig2cpp` 命令行、输出路径、类名、源 JSON、JSON 版本与工具版本。 +- include guard/类宏前缀由 `CLASS_NAME` 推导,例如 `TREELANDUSERCONFIG_DCONFIG_FILE_VERSION_MAJOR` 与 `TREELANDUSERCONFIG_DCONFIG_FILE_VERSION_MINOR`。 +- 生成的 `*_DCONFIG_FILE_VERSION_MINOR` 宏反映生成器 API 兼容性;即使 `Q_CLASSINFO("DConfigFileVersion", "1.0")` 来自 JSON 描述文件,当前生成头文件也把它定义为 `1`。新代码不需要旧 DTK 兼容分支。 +- 每个键生成 `#define _DCONFIG_FILE_`。 +- 每个键生成带 getter、setter、`*Changed` 信号与 `reset*` 方法的 `Q_PROPERTY`。 +- JSON 整数生成为 `qlonglong`;JSON 浮点生成为 `double`;字符串为 `QString`;布尔为 `bool`。 +- 类提供 `keyList()`、`isDefaultValue(key)`、按键的 `*IsDefaultValue()`、`config()`、`isInitializeSucceeded()`、已废弃的 `isInitializeSucceed()`、`isInitializeFailed()`、`isInitializing()`。 +- 类同时发出具体的 `keyChanged()` 信号与通用的 `valueChanged(const QString &key, const QVariant &value)`。 +- setter 先更新缓存的属性存储,再在底层 `DConfig` 对象存在时异步调用 `DConfig::setValue(...)`。 +- 初始化在 `DTK_CORE_NAMESPACE::DConfig::globalThread()` 上异步进行。构造函数发出 `configInitializeSucceed(DConfig *)` 或 `configInitializeFailed()`。 + +每个类生成的创建 helper: + +```cpp +static ClassName *create(const QString &appId = {}, + const QString &subpath = {}, + QObject *parent = nullptr, + QThread *thread = DTK_CORE_NAMESPACE::DConfig::globalThread()); + +static ClassName *createByName(const QString &name, + const QString &appId = {}, + const QString &subpath = {}, + QObject *parent = nullptr, + QThread *thread = DTK_CORE_NAMESPACE::DConfig::globalThread()); +``` + +生成的描述文件名已足够时用 `create(...)`;现有 treeland 代码显式传入描述文件名与 app id 时(用户、output、seat 配置路径)用 `createByName(...)`。 + diff --git a/.agents/skills/treeland-debug/SKILL.md b/.agents/skills/treeland-debug/SKILL.md new file mode 100644 index 0000000000..1a8cf9e4bc --- /dev/null +++ b/.agents/skills/treeland-debug/SKILL.md @@ -0,0 +1,192 @@ +--- +name: treeland-debug +description: "检查和操控运行中的 treeland 合成器,用于定位窗口、焦点、输入、输出、渲染与卡死问题:窗口树与单窗口详情、客户端清单、空闲与空闲抑制来源、快捷键、输入注入、截图、QtQuick 场景树、实时视图,以及调试 socket 的访问权限和 Qt 日志分类。在调试/复现 treeland 运行时问题、读写 remoteDebug 开关、连接调试 socket、按 treeland 与 waylib 的日志分类读日志时使用。" +--- + +# Treeland 调试 + +> **铁律**:先用 `treeland-debug` 读到实时状态再改代码;不要只凭日志或猜测改行为。 + +已退出进程的崩溃可先依据用户提供的 core/backtrace 和对应源码定位;若无法访问故障机器或没有 `treeland-debug`,应明确记录限制,不必为获取实时状态重启服务或注入事件。用户要求不编译时,不执行下文的构建验证,并说明未完成运行时验证。 + +## 范围 +本 skill 说明如何检查与控制**运行中**的 treeland 合成器来定位问题。问题可在运行时观察到时使用(窗口状态不对、焦点/激活异常、输入不落地、输出缺失或黑屏、崩溃、卡死、性能问题)。构建/安装见 `treeland-build`;日志改动见 `treeland-logging`;DConfig 见 `treeland-dconfig`;协议见协议类 skill。 + +主要仓库位置: + +- `src/core/` —— 生命周期、QML 引擎胶水、`WaylandServer`(`src/core/waylandserver.cpp`)。 +- `src/surface/` —— surface/window 封装、状态、可见性、几何(`surfacewrapper.cpp`)。 +- `src/seat/`、`src/input/` —— seat 与输入;桌面启动与协议组装在 `src/core/waylandserver.*`。 +- `src/workspace/` —— workspace 模型与切换。 +- `src/output/`、`src/modules/output-manager/` —— output 与布局。 +- `src/idle/` —— 空闲通知与空闲抑制。 +- `src/session/` —— 会话、用户切换与 per-session 资源。 +- `src/modules/` —— 功能模块(compositor-action、input-manager、shortcut、dde-shell 等)。 +- `src/plugins/`(lockscreen、multitaskview)—— 插件与功能集成。 +- `src/common/treelandlogging.*` —— 集中式日志分类。 +- `waylib/` —— 底层 wlroots+QtQuick 合成器框架(output 对应 `QQuickWindow`,surface 对应 `QQuickItem`)。 +- `3rdparty/wlroots/` —— 内联的 wlroots(通过 `` 使用原始 C API)。 +- `tools/treeland-debug/` —— 检查/控制运行中合成器的 CLI;`tools/treeland-debug/README.md` 是该工具自己的完整文档。 + +## 运行环境 +treeland 既可作为 Release 服务运行,也可作为开发中的构建运行: + +- **全局模式**(首选,DDM 场景):单进程管理所有用户;以 **`dde`** 用户身份由 systemd **system** 单元 `treeland.service` 启动(`User=dde`,安装在 `SYSTEMD_SYSTEM_UNIT_DIR`),总线名 `org.deepin.Compositor1`,`ExecStart=.../treeland.sh --lockscreen`。该单元还设置 `LIBSEAT_BACKEND=seatd`、`SEATD_SOCK=/run/dde-seatd.sock` 与 `XDG_RUNTIME_DIR=%t/treeland`(见 `misc/systemd/treeland.service.in`)。 +- **用户模式**:按用户启动(启动器导出 `TREELAND_RUN_MODE=user`,见 `misc/wayland-sessions/treeland-user-wrapper.in`),行为类似普通窗口管理器。 +- **开发(dev)构建、嵌套运行**:正在开发的版本通常**不是**已安装的发行版,而是从工作树构建、作为**当前用户身份**的独立进程,嵌套在已有 Wayland 或 X11 会话里。见下一节。 + +调试 socket 的位置、权限与提权边界完全由构建类型决定(Release / Debug / 会话模式各一套),详见 [references/access.md](references/access.md)。先记住两条:Release 构建的 socket 只有 root 能连,`treeland-debug` 会自动走 `pkexec`;Debug 构建的 dev socket 仅所属 UID 可连、不需要 polkit。 + +## 调试开发(dev)构建 +当问题出在当前正在开发的版本上,你以当前用户身份把该构建作为独立进程、嵌套在已有 Wayland 或 X11 会话里运行: + +```bash +# 在构建树中,嵌套于已有 Wayland 会话 +WLR_BACKENDS=wayland ./build/src/treeland.sh +# 嵌套于已有 X11 会话 +WLR_BACKENDS=x11 ./build/src/treeland.sh +``` + +`treeland.sh` 包装 `treeland`:先以 `--try-exec` 探测,输出里出现 `failed to create dri2 screen` 时就以 `WLR_RENDERER=pixman` 软件渲染重跑(与 service 行为一致)。 + +- **debug source**:Release 构建默认关闭(会话级运行时不默认暴露窗口内容与输入注入),先 `treeland-debug debug on` 打开;**Debug 构建始终开启、不看开关**,直接跑 `treeland-debug` 即可。 +- **不需要 `sudo -u dde`**:以**当前用户**运行 `treeland-debug`,与实例处于同一会话;dev socket 仅当前 UID 可访问。 +- **日志进终端,不进 journalctl**:treeland 的 stdout/stderr(Qt 分类日志)落在你启动它的地方。在该进程环境里设置 `QT_LOGGING_RULES`;Release 构建可传 `--console-log` 强制开启控制台日志(Debug 构建总是输出到控制台)。 +- **与全局服务无 socket 冲突**:Debug 构建使用独立的 `-dev` socket 名,并对并发实例自动加数字后缀,因此嵌套 dev 实例与全局 `treeland.service` 可以共存 —— 不必停掉后者。 + +## 启用 debug source(第一步) +`remoteDebug` 是调试功能的总开关,**Release 构建里默认关闭**,Debug 构建里则被忽略(始终开启):开关打开时 Treeland 就会发布调试 socket,谁连上来就给谁提供 `WindowTree` 远程对象。 + +- 连不上时先看 stderr:`treeland-debug` 会提示"没有发布调试 socket",此时要么开关没开,要么 Treeland 没在运行。 +- 开关归属合成器运行用户:DConfig 的应用级键按用户分开存储,Treeland 只读自己运行用户的那一个,所以要用该用户身份(global 模式下是 `dde`)由 root 以 `dde-dconfig -u ` 写入。`treeland-debug debug on|off` 已经封装了这一步:它从运行中的合成器查出该 uid,必要时自己走 `pkexec` 提权。 +- 远程源是个无状态薄壳:窗口树、截图、场景树都在每次调用时现场采集。唯一的会话级资源是输入事件捕获 —— 只在客户端轮询 `getEvents()` 时挂上 `eventFilter` 与环形缓冲,空闲后自动拆掉。所以没人连时除了那条 socket 没有别的开销;要彻底禁止调试就把开关关掉(socket 也随之消失)。 + +```bash +# 打开调试(默认是关),必要时会通过 polkit 提权 +treeland-debug debug on +# 关回去 / 只看当前状态 +treeland-debug debug off +treeland-debug debug +``` + +等价的底层命令(root 身份,`` 为合成器运行用户): + +```bash +dde-dconfig -u set -a org.deepin.dde.treeland -r org.deepin.dde.treeland -k remoteDebug -v true +``` + +切换 `remoteDebug` **立即生效** —— remote source 会在运行时被创建或销毁,无需重启(合成器运行时监听 `remoteDebugChanged`)。`treeland-debug` 连接的是构建类型对应的调试 socket,remote object 名为 `WindowTree`。 + +## 快速上手 +```bash +# remoteDebug 是总开关、Release 默认关闭,普通命令不会改它:先 treeland-debug debug on +# (Debug 构建不看开关、始终开启,dev 实例直接跑即可) +# 连不上时会提示"没有发布调试 socket" —— 那就是开关没开或 treeland 没在运行 + +# 检查 —— Release 构建会通过 polkit 自动提权到 root;Debug 构建以当前用户运行 +treeland-debug tree +treeland-debug --json windows +treeland-debug clients +treeland-debug idle # 空闲时长与空闲抑制来源 + +# 控制 +treeland-debug activate dde-file-manager +treeland-debug maximize 93824992268800 +treeland-debug close dde-file-manager + +# 注入输入 +treeland-debug event key Return tap +treeland-debug event button left click + +# 截图 +treeland-debug screenshot output DP-1 /tmp/ss.png # 语法:screenshot output [name] [file] +treeland-debug screenshot window 93824992268800 +``` + +命令全集、每个检查命令的 `--json` 字段、输出约定、`listen`/MCP 接口与事件类型编号见 [references/cli.md](references/cli.md)(`treeland-debug --help` 是命令清单的权威来源)。 + +## 诊断流程 +从症状出发,选最小可靠的检查手段。先复现,再逐层隔离(treeland vs waylib vs wlroots vs 客户端)。 + +**窗口状态不对(最大/最小/全屏/平铺、几何、可见性):** +1. `treeland-debug --json windows` —— 读取目标窗口(按 `appId` 匹配)的 `state`、`visible`、`active`、`minimized`、`geometry`、`outputs`、`frames`、`damage`。 +2. `treeland-debug tree` —— 确认窗口所在的 layer/workspace。 +3. `treeland-debug window ` —— 完整单窗口视图:region、SSD 矩形、`Frames`、`Damage`、`Frame pacing`,末尾一条可直接贴进报告的 `-geometry WxH+X+Y`。 +4. `treeland-debug scene ` —— 布局看着对但渲染不对时,检查 QtQuick 场景(菜单/弹窗/装饰)。 +5. 与日志交叉验证:`QT_LOGGING_RULES='treeland.surface.debug=true;treeland.workspace.debug=true'`。 + +**窗口不在任何 output 上(`Output`/`Outputs` 为 `(none)`):** +1. `treeland-debug window ` —— 看 `Last leave`(哪个 output、离开时它是否 enabled、是否把该 output 的窗口列表清空)与 `Last outputs update`(上次重新计算 outputs 的原因、参与计算/启用/自动模式的 output 数量)。这两行就是回答"为什么它现在不在任何 output 上"的证据。 +2. `treeland-debug --json windows` 里的 `outputs`/`framePacingOutput` 对比 `tree` 中的 output 是否存在。 +3. 相关分类:`treeland.output`、`treeland.surface`。 + +**焦点 / 激活不对:** +1. `treeland-debug --json windows` —— 检查 `active`;`treeland-debug cursor` 的 `window:` 字段即光标下的窗口(键盘焦点只暴露在 HTTP/WS):`treeland-debug listen --host 127.0.0.1 --port 8080` 后 `curl -s 127.0.0.1:8080/api/focused`。 +2. `treeland-debug activate ` 后复查。 +3. 相关分类:`treeland.seat`、`treeland.popup.focus`、`treeland.activation`。 + +**快捷键不生效 / 想知道谁绑了什么:** +1. `treeland-debug shortcuts` —— 看当前注册的绑定(只有客户端通过 `treeland_shortcut_manager_v3` 绑定过才有内容,空列表通常意味着没有 shell 绑定)。 +2. `treeland-debug events` —— 边操作边看:`shortcut-registered`/`shortcut-unregistered`(重新登录或重启 shell 会先把旧绑定都注销再重注册)与 `shortcut-triggered`(按键触发带 `[press|release|repeat]`,`target` 是**按键触发那一刻**的键盘聚焦窗口 —— 动作执行前采样,所以切工作区/任务切换不会报成目标窗口;swipe/hold 手势带 `(gesture)` 且 `target` 为 0)。 +3. 相关分类:`treeland.shortcut`。 + +**输入不落地 / 目标不对:** +1. `treeland-debug move-cursor ` 后 `treeland-debug event button left click`;`treeland-debug event key Return tap`。 +2. 用 `windows`(`ACTIVE` 列)确认键盘/指针焦点 —— 键盘事件发往键盘聚焦的 surface,指针按键发往光标下的 surface。 +3. 输入区域不对时看 `window ` 的 `Input region`(surface 局部坐标的 box 列表):未设置(`NULL`)的输入区域按协议是**无穷大**,打印出来是覆盖整面的一个 box;为空则要么是客户端显式提交了空 region(完全不接受输入),要么是 surface 还没提交过 buffer。出现多个小块通常是客户端只为命中区设了输入区域(如标题栏、按钮)。`Opaque region` 为空只表示客户端没有声明不透明区域(默认值),不要读成窗口透明,也不要和"不接收输入"混。 +4. 相关分类:`treeland.input`、`treeland.seat`、`waylib.input.pointer`、`waylib.seat`。检查 seatd:`sudo journalctl -u dde-seatd -f`,以及 `LIBSEAT_BACKEND=seatd`/`SEATD_SOCK=/run/dde-seatd.sock` 是否已设置(见 `misc/systemd/treeland.service.in`)。 + +**输出黑屏 / 缺失 / 分辨率不对:** +1. `treeland-debug tree` —— 确认 output 存在;`treeland-debug --json windows` 按 output 查看。 +2. `treeland-debug screenshot output ` 看合成器实际渲染了什么。 +3. 相关分类:`treeland.output`、`waylib.output`、`waylib.output.drm`。硬件渲染失败时 `treeland.sh` 的 pixman 回退会生效。 + +**崩溃 / 卡死:** +1. 检查服务状态与重启日志:`sudo journalctl -u treeland.service -n 200 --no-pager`(Qt 日志通过 journal appender 直接写入;标准错误的捕获见"读日志")。 +2. 若启用了 ASAN:经 `treeland.service` 启动时日志写到 `/tmp/treeland-asan*` 文件而不是 journalctl(`ASAN_OPTIONS` 在 `misc/systemd/treeland.service.in` 里设);本地直接跑则仍在 stderr。 +3. 用 `treeland-debug`(注入事件、activate/close 窗口)以最小步骤复现,并记录崩溃前最后几个动作。 +4. 卡死时用 `top`/`clients` 看是否有客户端卡住,必要时 gdb attach(`sudo gdb -p `)。 + +**怀疑客户端问题:** 用 `treeland-debug clients` 查客户端 pid;确认它确实在与合成器通信(`windows` 存在、`frames` 在递增)。冻结的客户端会表现为 `frames` 不再推进。 + +## 读日志 +treeland 使用 Qt 日志分类,全部集中在 `src/common/treelandlogging.*`。分类字符串 ID 遵循 `treeland.[.]`(例如 `treeland.surface`、`treeland.input`、`treeland.workspace`、`treeland.output`、`treeland.seat`、`treeland.protocol`、`treeland.wallpaper`、`treeland.xwayland`、`treeland.shell.xdg`、`treeland.popup.focus`、`treeland.debug`)。waylib 的分类在 `waylib/src/server/wayliblogging.*`,ID 为 `waylib.*`。完整分类表见 `treeland-logging`。 + +用 `QT_LOGGING_RULES` 控制日志详细程度。全局模式下 `treeland.service` 是 **system** 单元,因此要通过 systemd drop-in 设置该变量(system 服务没有 `--user` 环境)。嵌套 dev 实例则在启动进程的环境里设置(见上面的 dev 构建一节)。 + +```bash +sudo mkdir -p /etc/systemd/system/treeland.service.d +printf '[Service]\nEnvironment=QT_LOGGING_RULES=treeland.surface.debug=true;treeland.input.debug=true\n' | sudo tee /etc/systemd/system/treeland.service.d/debug.conf +sudo systemctl daemon-reload +sudo systemctl restart treeland.service +``` + +注意:`src/main.cpp` 通过 `DLogManager::registerJournalAppender()` 直接写 journal,Qt 分类日志不依赖 stdout/stderr。随包安装的 unit 设置了 `StandardOutput=null` / `StandardError=null`,丢弃的是脚本及直接写到标准输出/错误的内容。仅在需要捕获这些内容时,才在 drop-in 中追加 `StandardOutput=journal` / `StandardError=journal`;Release 构建若还需要控制台 Qt 日志,应同时传入 `--console-log`。journal 本身是 system journal(不是 `--user`): + +```bash +# 全局 treeland 服务(以 dde 运行)最近的日志 +sudo journalctl -u treeland.service -n 200 --no-pager +# 或带完整详细度并跟随 +sudo journalctl -u treeland.service -f +``` + +若某问题只在硬件渲染下复现,注意 `treeland.sh` 的 pixman 回退可能掩盖它。 + +## 规则 +- 需要解析的状态用 `--json`;控制窗口前先用 `windows`/`clients`/`top` 查到稳定的窗口 id。 +- 改 `treeland-debug` 的命令动词或某个命令的固定首参时,**必须同步** `tools/treeland-debug/completions/` 下的三份脚本(`treeland-debug`、`_treeland-debug`、`treeland-debug.fish`)和 `debughelpers.cpp` 里的 `debugCommandNames()`/`firstArgumentCandidates()`:`tests/test_treeland_debug` 的 `testCompletionScriptsMatchCommandTable()` 会逐项比对,漏改即测试失败。 +- 截图是强证据:布局 `tree` 正确但图像不对,问题在渲染/QtQuick 场景,不在布局。 +- 优先修根因;实时工具用于观察与复现,不能替代阅读拥有该状态的那段代码路径。 +- 修改权限/提权相关的理解前,先读 [references/access.md](references/access.md),不要凭"root 能连任何 socket"类推到会话模式。 + +## 验证 + +- [ ] 改动前先用一条 `treeland-debug` 命令(通常是 `--json windows` 或 `tree`)记录当前实时状态 +- [ ] 若涉及代码,先构建(见 `treeland-build`) +- [ ] 用同一条命令复验,输出符合预期 +- [ ] 在交付说明里写出:哪条 `treeland-debug` 命令可以确认这次改动 + +## 参考文件 +- [references/cli.md](references/cli.md) —— 命令全集、全局选项、`--json` 覆盖范围、输出约定、`listen`/MCP、事件类型编号。 +- [references/access.md](references/access.md) —— 构建类型 × 访问权限矩阵、调试 socket 命名与探测顺序、polkit/`--no-escalate`、`no-auth` 调试窗口、`TREELAND_DEBUG_DIR`/`TREELAND_DEBUG_SOCKET`。 +- `tools/treeland-debug/README.md` —— 该工具自身的完整文档(含 REST/WS/MCP 细节)。 diff --git a/.agents/skills/treeland-debug/references/access.md b/.agents/skills/treeland-debug/references/access.md new file mode 100644 index 0000000000..4014ba3737 --- /dev/null +++ b/.agents/skills/treeland-debug/references/access.md @@ -0,0 +1,83 @@ +# 调试访问权限与 socket 位置 + +本文件是 treeland 调试通道权限模型的唯一出处。全部结论可在仓库内核对: +`src/modules/resource/treelanddebugsocket.cpp`、`src/modules/resource/treelandremotesource.cpp`、 +`misc/systemd/treeland.service.in`、`misc/polkit/org.deepin.dde.treeland-debug.policy.in`。 + +## 构建类型 + +构建类型决定 socket 名、位置、权限,以及客户端要不要提权。`TREELAND_DEBUG_DEV_BUILD` +只在 `CMAKE_BUILD_TYPE=Debug` 时定义(见顶层 `CMakeLists.txt`);没给 `CMAKE_BUILD_TYPE` +时两种都不是,按 Release 行为处理。 + +| | Release 构建 | Debug 构建(`TREELAND_DEBUG_DEV_BUILD`) | +| --- | --- | --- | +| socket 名 | `org.deepin.dde.treeland.debug` | `org.deepin.dde.treeland.debug-dev` | +| 默认目录 | 全局服务 `/run/treeland-debug`;会话模式 `$XDG_RUNTIME_DIR`(`/run/user/`) | `/tmp/treeland-debug-`(目录 `0700`,属主为该 UID) | +| socket 权限 | `0000`(只有 root 靠 `CAP_DAC_OVERRIDE` 连得上,连合成器自己的用户也挡) | `0600`(仅所属 UID 的进程,root 保留特权访问) | +| `remoteDebug` 开关 | 生效,默认关闭 | 忽略,始终开启 | +| 客户端提权 | 连不上就通过 `pkexec`(polkit)以 root 重跑自己 | 不提权;同 UID 直接连 | + +名字冲突时追加数字后缀(`-1`…`-99`),用非阻塞 `flock` 加活 socket 探测选择,避免覆盖 +另一个实例的 socket。Debug 构建的 `-dev` 名与 Release 名互不干扰,所以嵌套 dev 实例 +可以和全局 `treeland.service` 同时存在。 + +## 调试目录 + +- 全局服务用**自己的目录** `/run/treeland-debug`,不是进程的 `XDG_RUNTIME_DIR`(后者是 + `/run/treeland`):no-auth 窗口要把目录放宽到 `0711`,而 Qt 要求 `XDG_RUNTIME_DIR` + 保持 `0700`,否则会退回 `$TMPDIR/runtime-`。systemd 用 + `RuntimeDirectory=treeland treeland-debug` 创建这个目录,并在每次启动时重建成 `0700`。 +- 会话模式(`TREELAND_RUN_MODE=user`,或全局目录不可写)绑定在进程的 `XDG_RUNTIME_DIR`。 +- Debug 构建绑定 `/tmp/treeland-debug-`,不往宿主的 `/run` 里放 socket。 + +## 客户端探测顺序 + +`--url` → `$TREELAND_DEBUG_SOCKET` → 自动探测。自动探测按目录顺序逐个尝试候选,每个 +候选后面跟它自己的 `-N` 实例: + +1. 自己的目录(Debug 构建是 `/tmp/treeland-debug-`;Release 构建是全局目录) +2. `/run/treeland-debug` +3. `/run/treeland`(legacy 全局目录) +4. runtime 目录:Debug 构建只加自己的;Release 构建扫描 `/run/user/*`(root 可访问任何用户的会话 socket) + +Debug 构建的候选名顺序是 `-dev` 再 Release 名,因此构建类型偏好优先于后缀实例。 +`--timeout-ms` 在各候选间共享,每个候选至少留约 3 秒的探测预算;一个死 socket 只会 +拖慢而不会饿死首选实例,所以探测总耗时可达 `--timeout-ms` 加每个候选一次探测。 +显式给了 `--url` 或 `$TREELAND_DEBUG_SOCKET` 就只用它,不再探测其它候选。 + +`$TREELAND_DEBUG_SOCKET` 取 socket 路径或裸名(等价 `local:<值>`),带 scheme 的值原样 +使用。`TREELAND_DEBUG_DIR` 是显式开发/测试覆盖项,同时作用于服务端目录选择。 + +## 提权与 `--no-escalate` + +Release 构建里客户端先以自身身份尝试连接;非 root 连不到 root-only 的 socket,所以这次 +尝试会立即失败,随后才通过 `pkexec`(polkit)重新执行自己并弹出认证。随包安装的 +polkit 策略保证开箱即用:源文件 `misc/polkit/org.deepin.dde.treeland-debug.policy.in`, +安装为 `org.deepin.dde.treeland-debug.policy`(`/usr/share/polkit-1/actions`)。 + +`--no-escalate` 跳过 polkit,直接报告需要提权 —— 脚本和 CI 用这个,避免挂起等认证。 +`pkexec` 不可用时,非 root 调用者会得到一条说明如何继续的错误。 + +## `no-auth`:临时放开 Release socket + +`treeland-debug no-auth`(`WindowTreeRemote` 的 `requestNoAuth` 方法)请 treeland 把 socket +置为 `0666`、它自己的调试目录置为 `0711`(可穿越不可列目录),之后任意本机用户都能直接 +连上、不弹认证。 + +- 发请求的必须是已经穿过 `0000` socket 的调用者 —— Release 构建里那只有 root,这次连接 + 本身就是鉴权。 +- 窗口 30 分钟内无调试调用就关闭,期间每次远程调用(包括 `cursor` 的属性读取)都会重新 + 推后 30 分钟;关闭时窗口期内建立的连接也被一并断开(重建 host)。 +- 收窗只把 socket 收回 `0000`。目录在第一次开窗时被放宽并保持 `0711` 到进程退出 + (多个实例可能共用这个目录),下次启动由 systemd 重建成 `0700`。 +- 只对全局服务自己的目录生效。会话模式下 socket 在 `/run/user/`(那里还有会话总线等), + 不放宽;`no-auth` 在那里失败,仍然需要 root。 +- Debug 构建本来就在启动时放开到同 UID,`requestNoAuth` 是空操作、直接成功。 + +## 需要 root 之外提权的一条命令 + +`debug [on|off|status]` 是唯一不需要调试 socket 的命令(socket 本来就是它开出来的)。 +开关按用户存放,所以合成器不是以你的身份运行时它会自己走 `pkexec`;`--no-escalate` +只报告需要提权。REPL(`shell`)不能转发提权,因此 `shell` 里的 `debug` 只提示以一次性 +命令运行。 diff --git a/.agents/skills/treeland-debug/references/cli.md b/.agents/skills/treeland-debug/references/cli.md new file mode 100644 index 0000000000..82414ee0ac --- /dev/null +++ b/.agents/skills/treeland-debug/references/cli.md @@ -0,0 +1,129 @@ +# treeland-debug 命令参考 + +`treeland-debug --help` 是命令清单的权威来源;`tools/treeland-debug/README.md` 是该工具的 +完整文档(含 REST/WS/MCP 细节)。本文件只记录用这个工具排查问题时要记住的接口事实。 + +## 全局选项 + +``` +--url 远程对象 host URL(默认:$TREELAND_DEBUG_SOCKET,否则按构建类型探测) +--name 远程对象名(默认 WindowTree) +--timeout-ms 请求超时,毫秒(默认 30000) +--json 检查命令输出机器可读 JSON(与 listen API 返回的记录一致) +--preview 强制在终端内联预览截图(默认自动探测) +--no-preview 关闭内联预览 +--no-escalate 不走 polkit 提权,只报告需要 root(脚本/CI 用) +--log-level 本客户端自身 stderr 诊断的详细度:error、warning、info(默认)、 + debug。目前只有 info 与 debug 有差别,debug 还会标出回退连接的来源 +-h, --help 帮助 +-v, --version 版本 +``` + +socket 选择顺序与探测细节见 [access.md](access.md)。`--tree`、`--cursor` 是 `tree`、`cursor` +的向后兼容别名;不带命令时默认执行 `tree`。 + +## 检查 + +| 命令 | 输出 | +| --- | --- | +| `tree` | 完整布局树:`Mode:` + 每层 `Layer: ()` + workspace(`(active)` 标记)+ 一行一窗(`*` 标记 active 窗口,state 带 `+Min` 后缀表示 minimized)。 | +| `cursor` | xdotool 风格一行:`x:N y:N window:N`,`window 0` 表示光标下没有窗口。`--json` 为 `{x,y,window}`。 | +| `windows` | 顶层窗口表格:`ID TYPE APP-ID STATE ACTIVE MIN OUTPUT GEOMETRY TITLE`;`TYPE` 为 shell surface 类型(`xdg-toplevel`/`xdg-popup`/`xwayland`/`layer-shell`/`input-popup`/`lock-screen`/`splash-screen`),`STATE` 为 `Normal`/`Maximized`/`Fullscreen`/`Tiling`,`OUTPUT` 里的 `+` 标记驱动该窗口 frame callback 的 output。 | +| `window ` | 单窗口 `Key: value` 块(`xwininfo -id` 风格):`App ID`、`Shell type`、`Container`、`Layer`(含 `Z`)、`Workspace`、`State`、`Visible`、`Active`、`Minimized`、`Output`、`Outputs`、`Frame pacing`、`Geometry`、`Position`、`Bounding rect`、`Titlebar`、`Icon`、`Frames`、`Damage`、`Input region`、`Opaque region`,以及"为什么不在任何 output 上"的 `Last leave`(离开的 output、离开时是否 enabled、是否清空了它的窗口列表)与 `Last outputs update`(原因、启用/总数/已计算数量、是否自动模式);末行是可直接贴报告的 `-geometry WxH+X+Y`。空字段直接省略。 | +| `clients` | 每个客户端一行 `client 0x pid= [appId=] windows=`,下面跟 `exe:`、`cmd:` 与该客户端的窗口行。 | +| `idle` | `Key: value` 形式:`Idle`(距上次输入的时长)、`Inhibited`、`Screensaver`、`Inhibitors`,后面一行一个抑制来源(`[kind] pid= appId= window= "title" app= reason= active= held= exe=`)。列表**包含当前未生效**的来源,用 `active=` 区分,只有 `active` 的才算进 `Inhibited`。`kind` 为 `idle-inhibit`(`zwp_idle_inhibit_manager_v1` surface)或 `screensaver`(`treeland_screensaver_v2` inhibit)。`surfaceId`/`window=` 只有在抑制挂在 toplevel 上时才等于可控制命令的窗口 id(layer-shell / subsurface 抑制查不到窗口)。合成器没有全局空闲阈值(阈值由客户端通过 `ext-idle-notify-v1` 自行设定),所以只报告时长与抑制来源。 | +| `shortcuts` | 已注册的快捷键与手势,表格 `NAME TRIGGER ACTION FLAGS`:按键绑定触发列为 `Ctrl+Alt+T` 形式、`FLAGS` 为 `press\|release\|repeat`;手势为 `swipe -finger ` 或 `hold -finger`,`FLAGS` 留空。`--json` 为 `{name,type,key,flags,action,fingers,direction}`,`type` 0=key 1=swipe 2=hold。 | +| `top [interval-ms]` | 类似 `top` 的实时视图(默认 1000ms,Ctrl+C 退出),按每间隔帧增量降序排:顶部 `idle`/`inhibited`/抑制来源计数行,表头 `ID TYPE APP-ID STATE MIN FRAMES GEOMETRY MARKER`,`MARKER` 为 `F (focus)`(键盘聚焦)、`C (under cursor)`(光标下)或空。 | +| `events [interval-ms]` | 输入事件实时流(默认 50ms),每行先打事件类型名,同时带快捷键注册/注销/触发事件。类型编号见下。 | +| `watch [interval-ms]` | 轮询单个窗口的变化(默认 250ms)。 | +| `scene [id]` | 单个窗口(按 id/appId)或整个场景的 QtQuick 场景树 —— 用于查看不在布局 `tree` 里的菜单/弹窗/装饰。`--json` 为 `{"sceneTree": "..."}`。 | + +每个窗口都有稳定的数字 `id`(以及 `appId`),所有控制命令都接受这两种标识。用 +`windows`/`clients`/`top` 查 id。 + +### 事件类型编号 + +`1` motion、`2` button、`3` key、`4` focus、`5` cursor-window、`6` shortcut-registered、 +`7` shortcut-unregistered、`8` shortcut-triggered(定义见 +`src/modules/resource/treelandwindowtree.rep`)。`shortcut-triggered` 的 `target` 是按键触发 +那一刻的键盘聚焦窗口(动作执行前采样),手势触发带 `(gesture)` 且 `target` 为 0。 + +### `--json` 覆盖范围 + +`tree`、`cursor`、`windows`、`window`、`clients`、`idle`、`shortcuts`、`no-auth`、`scene` +输出 JSON,内容与 `listen` 的 HTTP/WS/MCP 接口一致。`top`、`events`、`watch`、`screenshot` +没有 JSON 形式(它们是流或二进制)。 + +## 输出约定 + +人类可读输出统一按 x11 工具的习惯排版: + +- **列表**(`windows`、`clients`、`top`、`shortcuts`)是表头 + 每对象恰好一行,无续行,方便 + `grep`/`head` 处理。 +- **几何**是 `WxH+X+Y`(`xwininfo -geometry` / `xdotool getwindowgeometry` 顺序),负坐标保留 + 自己的符号(`800x600-10+50`),不是从右边缘算的偏移。 +- **单个对象**(`window`、`idle`)是 `Key: value` 逐行块,键补齐对齐。 +- **嵌套结构**(`tree`、`scene`)保留树枝字符。 +- **来源 socket**:每次建立连接的运行结束时都在 stderr 上说明数据来自哪个 socket + (`treeland-debug: connected to local:...`),`shell` 进入时则作为 login 信息给出同一句话; + `help`、`--version`、`debug`、`listen` 不建立调试连接,不输出这行。`(fallback from ...)` + 只有在 `--log-level debug` 下才出现(`error`/`warning` 目前与 `info` 无差别)。 + +## 窗口控制 + +`activate`、`close`、`minimize`、`maximize`、`fullscreen`、`move `、 +`resize `、`workspace `。每条命令输出 `ok`/`failed`;`maximize` 与 +`fullscreen` 是切换语义。目标接受数字 id 或 appId;appId 命中多个窗口时,stderr 会说明 +显示了哪一个。 + +## 输入注入 + +- `move-cursor `、`event motion ` —— 移动光标。 +- `event button [press|release|click]` —— 指针按键,`btn` = `left`/`right`/`middle` + 或数字;名字映射到 Linux input code(`left`=0x110、`right`=0x111、`middle`=0x112), + 默认动作 `click`。指针按键发往**光标下**的 surface —— 先把光标移过去。 +- `event key [press|release|tap]` —— 键盘事件,默认 `tap`。`key` 可以是 **Qt::Key + 枚举名**(大小写不敏感,可带或不带 `Key_` 前缀,如 `Return`、`Escape`、`Space`、`A`、 + `F1`、`Left`),也可以是**数字**;数字按 Qt::Key 值解释,**不是** Linux evdev keycode。 + 键盘事件发往**键盘聚焦**的 surface —— 先 `activate` 窗口。 + +## 截图 + +`screenshot output [name] [file]`(省略 name 取主 output)与 `screenshot window [file]`。 +服务端渲染,PNG 字节返回给客户端,由客户端写文件并打印路径;省略 `file` 时落在 +`/tmp/treeland-debug-<毫秒时间戳>.png`,给了不带后缀的路径会自动补 `.png`。`--preview`/ +`--no-preview` 控制是否在终端内联显示。 + +## 交互式 shell + +`shell` 启动 REPL(`help` 看命令、`exit`/`quit` 退出),所有命令(含 `top`/`events`/`watch`) +都可用;Ctrl+C 中断实时视图并回到提示符。Tab 补全命令动词与 `event`/`screenshot`/`debug`/`listen` +的首个参数,↑/↓ 翻历史,提示符下 Ctrl+C 丢弃当前行、Ctrl+D 退出(管道输入仍按行读取)。 +一次性命令行的补全定义在 `tools/treeland-debug/completions/`(bash/zsh/fish)。`debug [on|off|status]` +在 REPL 里不可用 —— 它可能需要转发 polkit 提权,只能以一次性命令运行。 + +三份脚本与命令表由 `tests/test_treeland_debug` 的 `testCompletionScriptsMatchCommandTable()` 逐项 +比对(动词 = `debugCommandNames()` 去掉 REPL 专属的 `exit`/`quit`,首参 = `completionCandidates()`), +所以**新增/改名命令或首参时必须同步改这三份脚本**,否则该测试失败。 + +## 访问 + +`no-auth` —— 请合成器放开调试 socket 30 分钟(详见 [access.md](access.md))。 + +## listen(HTTP / WebSocket / MCP) + +`listen [--port

] [--host ]`(默认 `0.0.0.0:8080`,端口范围 1-65535)通过 HTTP、 +WebSocket 与 MCP 暴露同样的能力,供浏览器前端或其它程序使用。`listen` **始终编译进来** +(`Qt6::HttpServer` 与 `Qt6::WebSockets` 是硬依赖,见 `tools/treeland-debug/CMakeLists.txt`)。 + +- REST:`/api/tree`、`/api/cursor`、`/api/windows`、`/api/window`、`/api/clients`、`/api/idle`、 + `/api/shortcuts`、`/api/focused`、`/api/cursor-window`、`/api/scene`、`/api/no-auth`、 + `/api/debug`、`/api/events`、`/api/screenshot/output`、`/api/screenshot/window`,以及 + `POST /api/{activate,close,minimize,maximize,fullscreen,move,resize,workspace}`、 + `POST /api/move-cursor`、`POST /api/event/{motion,button,key}`。 +- WebSocket:`ws://host:port/ws`。 +- MCP:`POST /mcp`(JSON-RPC `initialize` / `tools/list` / `tools/call`)。 + +它**没有认证**,所以本地调试务必只绑回环:`listen --host 127.0.0.1 --port 8080`。`listen` 在 +任何连接建立前就启动服务器,因此它自己不会提权 —— Release 构建下要以 root(或 `dde` 在 +no-auth 窗口内)运行;它内部的 `debug` 写入不转发提权,需要 root 时按错误报告。 diff --git a/.agents/skills/treeland-logging/SKILL.md b/.agents/skills/treeland-logging/SKILL.md new file mode 100644 index 0000000000..f88a50c92f --- /dev/null +++ b/.agents/skills/treeland-logging/SKILL.md @@ -0,0 +1,213 @@ +--- +name: treeland-logging +description: "为 treeland 与 waylib 添加、修改、评审日志:集中式日志分类体系、级别选择、消息质量与敏感数据。在写 `qCDebug`/`qCInfo`/`qCWarning`/`qCCritical`、新增或调整日志分类(`treeland.*`、`waylib.*` 命名空间)、把裸 `qDebug()`/`qWarning()` 换成带分类的调用、清理日志输出时使用。" +--- + +# 日志规范 + +> **铁律**:不得新增裸 `qDebug()`/`qWarning()`/`qCritical()`/`qInfo()`;新分类只允许出现在集中式 `*logging.h/.cpp` 中。 + +## 目标 +让日志改动与集中式分类体系保持一致: + +- **treeland**:集中式分类在 `src/common/treelandlogging.h/.cpp` +- **waylib**:集中式分类在 `waylib/src/server/wayliblogging.h/.cpp` + +实现与评审工作都适用本 skill。 + +## 路由 +按模块归属选择日志路径,不要凭个人偏好。 + +### Treeland 代码 +使用集中式分类,声明在: + +- `src/common/treelandlogging.h` +- `src/common/treelandlogging.cpp` + +分类变量命名:`lcTl` + PascalCase 模块名(例如 `lcTlCore`、`lcTlInput`、`lcTlGestures`)。 + +字符串 ID 命名:`treeland.[.]`(例如 `treeland.core`、`treeland.input.gestures`)。 + +唯一例外是无法包含集中式头文件的独立可执行文件。目前只有两个:`treeland-xwayland`(`src/xwayland.cpp`,`lcXwaylandHelper`)与 `treeland-sd`(`src/systemd-socket.cpp`,`lcSdSocket`),它们可以在自己的 `.cpp` 里定义本地 `Q_LOGGING_CATEGORY`。其余可执行文件(`treeland-screensaver`、`treeland-debug`、`treeland-session-helper`)目前没有日志;若需要,就在各自文件里定义本地分类,不要拉入 `treelandlogging.h`。 + +### Waylib 代码 +使用集中式分类,声明在: + +- `waylib/src/server/wayliblogging.h` +- `waylib/src/server/wayliblogging.cpp` + +分类变量命名:`lcWl` + PascalCase 模块名(例如 `lcWlSeat`、`lcWlOutput`、`lcWlCursor`)。 + +字符串 ID 命名:`waylib.[.]`、`waylib.protocols.`、`waylib.qtquick.` 或 `waylib.utils.`(例如 `waylib.seat`、`waylib.input.pointer`、`waylib.protocols.inputmethod`)。 + +## Waylib 分类层级 + +``` +waylib +├── 内核 +│ ├── waylib.object lcWlObject +│ ├── waylib.socket lcWlSocket +│ ├── waylib.seat lcWlSeat +│ ├── waylib.output lcWlOutput +│ ├── waylib.output.drm lcWlOutputDrm +│ ├── waylib.output.buffer lcWlOutputBuffer +│ ├── waylib.input lcWlInput +│ ├── waylib.cursor lcWlCursor +│ ├── waylib.input.pointer lcWlPointer +│ ├── waylib.input.touch lcWlTouch +│ ├── waylib.input.gesture lcWlGesture +│ └── waylib.input.drag lcWlDrag +├── QtQuick +│ ├── waylib.texture.provider lcWlTextureProvider +│ ├── waylib.qtquick.surface lcWlSurface +│ ├── waylib.qtquick.texture lcWlQtQuickTexture +│ ├── waylib.renderer lcWlRenderer +│ └── waylib.qtquick.bufferitem lcWlBufferItem +├── 工具 +│ ├── waylib.utils.imagecapture lcWlImageCapture +│ ├── waylib.utils.cursorimage lcWlCursorImage +│ ├── waylib.utils.bufferdumper lcWlBufferDumper +│ └── waylib.utils.thread lcWlThreadUtils +├── 协议 +│ ├── waylib.protocols.foreigntoplevel lcWlForeignToplevel +│ ├── waylib.protocols.inputmethod lcWlInputMethod +│ ├── waylib.protocols.extforeigntoplevel lcWlExtForeignToplevel +│ ├── waylib.protocols.remotesubsurface lcWlRemoteSubsurface +│ └── waylib.protocols.textinput lcWlTextInput +├── Layer shell +│ ├── waylib.layer.shell lcWlLayerShell +│ └── waylib.layer.surface lcWlLayerSurface +├── XDG +│ ├── waylib.xdg.output lcWlXdgOutput +│ ├── waylib.xdg.decoration lcWlXdgDecoration +│ └── waylib.xdg.dialog lcWlXdgDialog +├── 输出扩展 +│ ├── waylib.output.layer lcWlOutputLayer +│ └── waylib.output.helper lcWlOutputHelper +├── QtQuick 扩展 +│ ├── waylib.qml.creator lcWlQmlCreator +│ └── waylib.cursor.quick lcWlQuickCursor +└── 平台与渲染 + ├── waylib.platform lcWlPlatform + ├── waylib.render.helper lcWlRenderHelper + ├── waylib.render.buffer lcWlRenderBuffer + └── waylib.render.bufferrenderer lcWlBufferRenderer +``` + +`wlroots`(`lcWlroots`,ID 为 `wlroots`)是唯一不在 `waylib.*` 命名空间下的分类,用于单独过滤 wlroots 自身的消息。 + +已知的 ID 例外:`waylib.texture.provider`(历史遗留;新分类用 `waylib.qtquick.*`)与 `wlroots`。不要重命名已有 ID —— 字符串 ID 是对外公开的 `QT_LOGGING_RULES` 契约。 + +新增或移动分类时,在同一次改动里同步更新这棵树。 + +## 强制规则 + +1. **禁止无分类日志** —— 绝不使用裸 `qDebug()`、`qWarning()`、`qCritical()`、`qInfo()`。始终使用带分类的变体:`qCDebug(cat)`、`qCInfo(cat)`、`qCWarning(cat)`、`qCCritical(cat)`。 + +2. **库代码里禁止本地 Q_LOGGING_CATEGORY** —— treeland 与 waylib 库代码的所有分类都必须声明在集中式 `*logging.h/.cpp` 中。只有独立可执行文件(例如 `treeland-xwayland`)可以在自己的 `.cpp` 里定义本地分类。 + +3. **禁止在 .h 里 include 日志头文件** —— 只有 `treelandlogging.h` / `wayliblogging.h` 自身可以声明分类。其他 `.h` 不得 `#include` 日志头文件,也不得使用 `qC*()` 宏,应把日志调用移到 `.cpp`。唯一例外是无法把日志调用移到 `.cpp` 的 header-only 模板(参见 `waylib/src/server/utils/wthreadutils.h`):这类头文件可以 include 集中式日志头并使用其中的分类。 + +4. **每个分类都要有注释** —— 每个 `Q_LOGGING_CATEGORY` 定义都要有说明。当前有两种约定: + - **Treeland**(`treelandlogging.cpp`):用分段 `//` 注释(例如 `// Core modules`、`// Input modules`)标注一组相关分类。 + - **Waylib**(`wayliblogging.cpp`):在每个定义后加行尾 `//` 注释,例如: + ```cpp + Q_LOGGING_CATEGORY(lcWlSeat, "waylib.seat", QtInfoMsg) // Seat management (keyboard focus, capability) + ``` + 给任一文件新增分类时,沿用该文件已有的约定。 + +## 日志级别 +选择能表达运维重要性的最低级别。 + +- `qCDebug`:细节调试与排障 +- `qCInfo`:正常运行信息 +- `qCWarning`:异常但可恢复 +- `qCCritical`:需要立即处理的严重故障 + +不要为了让信息“看得见”就把日常噪声升级成 warning 或 critical。 + +## 消息质量 +写具体、可过滤的消息。 + +推荐: + +```cpp +qCDebug(lcWlCursor) << "Cursor moved from" << oldPos << "to" << newPos; +``` + +避免: + +```cpp +qCDebug(lcWlCursor) << "Cursor moved"; +``` + +必要时包含: + +- 涉及的对象或子系统 +- 前后状态 +- 标识符或名称 +- 错误的影响 + +## 错误日志 +记录失败时要带上足够上下文,使排障时无需再读周边代码。 + +推荐: + +```cpp +qCWarning(lcWlCursor) << "Failed to attach device" << device->name() + << "- not a pointing device"; +``` + +避免没有对象、原因或影响的模糊失败信息。 + +## 敏感数据 +不要记录密钥、密码、token 或其他敏感用户数据。 + +## 新增分类 +需要新增日志分类时按以下步骤: + +1. **确定命名** —— 选定变量名(`lcTl*` 或 `lcWl*` + PascalCase)与位于合适层级的字符串 ID。 +2. **加声明** —— 在集中式 `.h`(`treelandlogging.h` 或 `wayliblogging.h`)的正确分段中加 `Q_DECLARE_LOGGING_CATEGORY(lcXxx)`。 +3. **加定义** —— 在集中式 `.cpp` 中加 `Q_LOGGING_CATEGORY(lcXxx, "domain.path", level)`,并用 `//` 注释说明其范围。 +4. **包含头文件** —— 在用到该分类的 `.cpp` 中加 `#include "treelandlogging.h"` 或 `#include "wayliblogging.h"`。 +5. **迁移调用点** —— 把裸 `qDebug()`/`qWarning()` 等替换为 `qCDebug(lcXxx)`/`qCWarning(lcXxx)` 等。 +6. **校验** —— 运行 `rg '\bq(Debug|Warning|Critical|Info)\s*\(' src/ waylib/src/ | rg -v 'qC(Debug|Info|Warning|Critical)'`,确认没有残留的无分类调用。只用空括号形式(`qDebug\(\)`)会漏掉 printf 风格的 `qDebug("...")`。没有 `rg` 时换成 `grep -rE` / `grep -vE`。 + +treeland 侧要改两处(waylib 同理,换成 `lcWl` / `waylib.` 前缀): + +```diff +--- a/src/common/treelandlogging.h ++++ b/src/common/treelandlogging.h + // Output module + Q_DECLARE_LOGGING_CATEGORY(lcTlOutput) ++// Foo module ++Q_DECLARE_LOGGING_CATEGORY(lcTlFoo) + +--- a/src/common/treelandlogging.cpp ++++ b/src/common/treelandlogging.cpp + // Output module + Q_LOGGING_CATEGORY(lcTlOutput, "treeland.output", QtInfoMsg) ++// Foo module ++Q_LOGGING_CATEGORY(lcTlFoo, "treeland.foo", QtInfoMsg) +``` + +调用点:`qCDebug(lcTlFoo) << ...`,并在消费该分类的 `.cpp` 里 `#include "common/treelandlogging.h"`。 + +## 评审清单 +评审日志改动时逐项确认: + +1. 分类符合 `lcTl*`/`lcWl*` 命名约定 +2. 分类声明在集中式头文件中(库代码里不得本地定义) +3. 除日志头本身、或无法移出日志调用的 header-only 模板外,没有 `.h` include 日志头或使用 `qC*()` +4. 每个 `Q_LOGGING_CATEGORY` 定义都有说明范围的 `//` 注释 +5. 所选级别与严重程度匹配 +6. 消息包含足够上下文 +7. 改动不泄露敏感信息 +8. 改动没有引入裸 `qDebug()`/`qWarning()`/`qCritical()`/`qInfo()` 调用 +9. 改动没有引入与任务无关的分类变动 + +## 仓库参考 +- `src/common/treelandlogging.h` +- `src/common/treelandlogging.cpp` +- `waylib/src/server/wayliblogging.h` +- `waylib/src/server/wayliblogging.cpp` diff --git a/.agents/skills/treeland-protocol-test/SKILL.md b/.agents/skills/treeland-protocol-test/SKILL.md new file mode 100644 index 0000000000..5cacd4661a --- /dev/null +++ b/.agents/skills/treeland-protocol-test/SKILL.md @@ -0,0 +1,164 @@ +--- +name: treeland-protocol-test +description: "在 `tests/protocols` 下新增、扩展、重构或调试 Wayland 协议测试:C 版客户端与 fixture 契约、`treeland_add_protocol_test` CMake 注册、可观察证据的断言写法、CTest 执行与 skip 处理。在创建协议测试目录与 `setup.cpp`、实现 `protocol_test_run()`、用 `client_connect`/`client_bind`/`invoke_on_server_thread`、排查 ctest 超时或残留后台进程时使用。协议实现见 `treeland-protocol` 或 `treeland-protocol-upstream`。" +--- + +# Wayland 协议测试 + +> **铁律**:断言必须来自真实 C 客户端事件或可观察的生产对象状态。mock、换成 C++ 客户端、"没崩溃" 都不算证据。 + +## 目标 +用 C 版 Wayland 客户端跑通真实的 Treeland 服务端路径。不要用 mock、也不要换成等价的 C++ 客户端,去替代协议请求、客户端事件或生产状态。 + +## 先读 +1. `tests/protocols/README.md` +2. `tests/protocols/framework/README.md` +3. 目标协议的 `README.md`、XML、`CMakeLists.txt`、`setup.cpp` 与 C 客户端 +4. `tests/protocols/framework/ProtocolTest.cmake` + +若属于协议实现工作,再按需选一个实现类 skill: + +- Treeland 自有 `treeland_*` XML 或 `QtWaylandServer::*`:`treeland-protocol` +- standard/ext/unstable/wlroots 协议封装:`treeland-protocol-upstream` + +## 新增测试 + +- [ ] 建目录 `tests/protocols//`,含 `CMakeLists.txt`、`setup.cpp`、`.c`(C 客户端) +- [ ] 写 `treeland_add_protocol_test(...)`(模板见下) +- [ ] 在 `tests/protocols/CMakeLists.txt` 里 `add_subdirectory()` +- [ ] 在 C 客户端实现 `protocol_test_run()`,并断言真实客户端事件或可观察的生产结果(见「Fixture 与客户端契约」「测试形态与证据」) +- [ ] 覆盖或剩余边界有变化时,更新该协议目录的 `README.md` 与 `tests/protocols/INDEX.md` +- [ ] `cmake --preset default` 后跑 `ctest --test-dir build -R '^test_$' -V` + +目录结构: + +```text +/ +├── CMakeLists.txt +├── setup.cpp +└── .c # C Wayland 客户端 +``` + +在 `tests/protocols/CMakeLists.txt` 中注册该目录,然后使用共享的 CMake helper: + +```cmake +treeland_add_protocol_test( + NAME example_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/example-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/example-v1.c" +) +``` + +`NAME` 用下划线分隔;CMake target 是 `test_`(`-` 会转成 `_`,见 `ProtocolTest.cmake`)。生成的客户端头文件名由 `XML` 推导;include `-client-protocol.h`,不要猜或复制别的生成文件名。需要依赖其他协议 XML 时用 `EXTRA_XMLS`,helper 会为 `XML` 和每个额外 XML 都生成客户端绑定。 + +## Fixture 与客户端契约 +用现有生产对象实现 fixture 钩子: + +```cpp +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); +} +``` + +- 不要重复注册 Treeland 启动路径已经提供的 global。 +- 只有在 fixture 需要检查已存在的服务端接口时才用 `find_server_interface(server)`;并断言该生产对象确实存在。 +- 请求需要客户端可绑定的 `wl_output` 时,添加 headless output。 +- 在 C 客户端中实现 `int protocol_test_run(const char *socket_name);`。 +- registry 与连接使用 `client_connect()`、`client_bind()`、`client_disconnect()`。 +- 客户端代码只允许 C、`wayland-client` 与 scanner 生成的 C API;不要 include Qt 或 Treeland 的 C++ API。 +- `invoke_on_server_thread()` 只用于读取生产状态,或注入没有对应客户端请求的定向 fixture 激励。绝不用它伪造请求结果。 + +### 像素测试的 fixture 条件 + +- 框架设置 `TREELAND_DISABLE_WALLPAPER=1`。使用保留 output buffer 的软件渲染路径时, + 需要固定的不透明场景背景来重绘窗口移走后暴露的像素;否则旧窗口残影和阴影累积会 + 污染整屏对比。先在没有被测操作时验证重复渲染稳定,再比较操作前后,不能通过 + 屏蔽区域或像素容差来掩盖未定位的差异。 +- `add_headless_output()` 会立即启用输出,可能使框架先于生产 `OutputManager` 将其加入 + layout。需要真实渲染且发生重复 output/cursor layer 注册时,只向已有 headless backend + 添加输出,让生产路径完成注册和启用;参考 + `tests/protocols/wayland-ext-image-copy-capture-v1/toplevel-setup.cpp`。 +- 检查捕获/离屏渲染是否影响屏幕时,先回读已提交 buffer,再单独验证下一次重绘; + 不要在取证前强制重绘,否则会覆盖共享 QSG 节点状态污染等瞬态问题。动画场景用 + capture renderer 的 `beforeRendering` / `afterRendering` 比较 live 节点状态, + 不用跨帧固定矩阵误判正常移动。 +- 整图比较需要固定光标/悬停等动态内容。指针夹具可在取基线前隐藏光标,仍保留真实 + seat/QtQuick 输入路径;不要屏蔽差异像素。移动/还原后同时比较完整捕获图像和实际 + output buffer,GPU 或物理 scanout 未实测时明确记录,不能用 pixman 通过代替。 +- renderer 的 preferred read format 不一定有 QImage 映射;明确选择支持的读回格式并 + 检查分配和读回结果,禁止把空图像地址交给 `wlr_texture_read_pixels()`。夹具窗口引用 + 用 `QPointer`,主动销毁前暂停“不应变化”的整屏比较,避免异步 frame 回调访问已销毁窗口。 + +### 捕获 / 录屏类协议的资源生命周期 + +- 服务端对象的所有者必须是请求它的客户端资源加上 session,而不是被捕获的窗口。 + `accept` 只创建 client resource;离屏视口/副本子树在第一个 session 的 `start()` 里建, + 最后一个 `stop()` 里同步释放,最后一个 client resource 也消失后再销毁包装对象。 + 窗口失效只负责 `finish()` → `stopped`,不能作为唯一的回收路径。 +- 清理必须延迟到下一轮事件循环:`stop()` 和 client resource 的 destroy listener 都跑在 + wlroots 的 `session_destroy()` 里,此时直接 `finish()` 会重入同一个 session 的销毁 + (`session_send_stopped()` 用到已释放的 resource)。 +- 用 fixture 直接计数离屏视口(`findChildren()` + `offscreen()`), + 断言:创建 source 后为 0;同一 source 的首个 session 创建 1 条管线,增加 session + 不再增加管线;销毁最后一个 session 后回到 0; + 会话期间提前销毁 source resource 仍为 1 且继续能捕获到 frame。 +- `request_frame` 的 `schedule_frame` 来自 session damage 是否非空,不能将它当作 + “已有待处理请求”的标志。按需渲染的离屏视口对每次请求都应主动调度,并自行记录 + 待完成的渲染,不能因为 damage 为空而永远等不到下一个 frame。 +- disabled output 不发送 frame,借用其时钟的离屏捕获需要独立的排队渲染兜底。 + 用真实 power-management 请求覆盖:先发 capture 再在同一批请求中关屏、关屏后 + 提交新内容并再次捕获、复电和取消排队请求;关闭原输出后重建会话,应解析窗口当前 + 可用的输出。fixture 只负责添加第二块输出、移动窗口以及读取生产状态,不替代关屏 + 或捕获请求;同时断言视口复用和兜底不提交真实输出。 + +## 测试形态与证据 +- 每个语义用例都要有名字。发出请求后用 roundtrip、指定事件、信号、模型变化或 future 完成来同步;不要用随意 sleep 或跨用例的状态机。 +- 命名为 `dispatch` 的用例只能证明可分发,不能证明业务语义覆盖。 +- 有依赖关系的步骤放在同一个 `protocol()` 用例和同一条 Wayland 连接里。只有能从新连接重新开始的场景才拆分。 +- 断言客户端事件载荷或可观察的生产结果。“没崩溃”不算成功,headless 输入与渲染用例尤其如此。 +- 覆盖范围或剩余边界变化时,更新该协议目录的 `README.md` 与 `tests/protocols/INDEX.md`。 + +## 验证 +`tests/protocols/` 整棵树只在 `BUILD_TREELAND_PROTOCOL_TESTS` 为 `ON`(默认值)时构建。`TREELAND_ENABLE_GPU_PROTOCOL_TESTS`(DMA-BUF 渲染器)和 `TREELAND_ENABLE_UINPUT_PROTOCOL_TESTS` 默认 `OFF`,对应可选用例不注册到 CTest;开启 uinput 测试后,没有 `/dev/uinput` 写权限或可用 `dde-seatd` 时运行时 skip。`DISABLE_XWAYLAND=ON` 时不构建或注册 xwindow-control 测试。 + +新增目录或修改 preset 后重新 configure: + +```bash +cmake --preset default +``` + +通过 CTest 构建并运行指定目标,例如: + +```bash +cmake --build --preset default --target test_treeland_keyboard_state_notify_unstable_v1 +ctest --test-dir build --output-on-failure \ + -R '^test_treeland_keyboard_state_notify_unstable_v1$' +``` + +加 `-V` 查看合成器与 Wayland 日志。运行整组: + +```bash +ctest --test-dir build --output-on-failure -L protocols +``` + +部分用例按设计会 skip(没有 `/dev/uinput`、没有 GPU、没有 D-Bus 服务)。CTest 把这种情况记为退出码 `77` 或 `SKIP :` 行,二者都在 `tests/protocols/framework/ProtocolTest.cmake` 中配置;skip 不算覆盖。报告某个场景通过之前,先看 `-V` 输出。 + +优先用 CTest 而不是直接启动测试可执行文件,因为 CTest 会提供 headless 后端、渲染器、超时与 skip 环境。 + +`ProtocolTest.cmake` 通过 `ENVIRONMENT_MODIFICATION` 设置 `QT_NO_XDG_DESKTOP_PORTAL=1`,禁用 Qt 的 portal 集成;fixture 覆盖 `ENVIRONMENT` 不影响该设置。修改后需重新 configure,更新 CTest 配置。 + +保留 `test-dconfig-service` 的独立进程组和 `stop()` 整组终止逻辑,不要改回只终止单个 PID 或只按 PPID 回收;机制见 `tests/protocols/framework/README.md`。 + +排查残留: + +```bash +# 1. 隔离总线与 DConfig 进程 +ps -eo pid,ppid,pgid,etimes,args | grep -E 'unix:abstract=treeland-protocol-test|dde-dconfig-daemon -p /tmp/treeland-protocol-dconfig' + +# 2. DConfig 临时目录(调用 stop() 后应被清理) +find /tmp -maxdepth 1 -name 'treeland-protocol-dconfig-*' +``` + +若 QTest 全部 PASS、测试进程已退出,但 CTest 仍超时,先确认生成的 CTest 配置包含上述设置,再检查是否有后台服务持有输出管道。不要将这种后台进程残留误判为协议失败,或用增加 timeout、标记 skip 掩盖问题。 diff --git a/.agents/skills/treeland-protocol-upstream/SKILL.md b/.agents/skills/treeland-protocol-upstream/SKILL.md new file mode 100644 index 0000000000..154a3921ff --- /dev/null +++ b/.agents/skills/treeland-protocol-upstream/SKILL.md @@ -0,0 +1,181 @@ +--- +name: treeland-protocol-upstream +description: "在 waylib 与 treeland 中封装和集成上游 Wayland 协议(standard/ext/unstable/wlr):`WServerInterface` 封装、native handle 所有权与销毁、每会话 global 隔离与撤销。在使用 `m_server->attach` 挂载 `W...` 封装、新增 `W...` 封装类、判断 wlroots `wlr_*_destroy` 与 `globalRemove()` 的归属、把协议接到 `WaylandServer::init` 启动路径时使用。treeland 私有协议见 `treeland-protocol`。" +--- + +# 上游协议封装与集成 + +> **铁律**:先确认 waylib 是否已有 `W...` 封装;销毁方式必须与 native handle 所有权一致,不要照抄 `globalRemove()`。 + +## 范围 +本 skill 只用于上游协议,不用于 treeland 私有协议。 + +出现以下任一情况即适用: + +- 协议是 standard/ext/unstable/wlr 协议 +- wlroots 已实现该 native 协议 +- 目标是 waylib `WServerInterface` 封装 +- treeland 通过 `m_server->attach()` 消费它 + +若任务涉及 treeland 自有 xml、`QtWaylandServer::*`,或在 `src/modules/*` 下新增私有模块,停下来改用 treeland 私有协议 skill。 + +## 启动装配 +`WaylandServer` 既是 QML singleton,也是 C++ 侧桌面入口。其 `init()`(`src/core/waylandserver.cpp`)负责组装启动流程,并持有 Wayland 运行时与核心 global。各功能组件自己持有协议回调与监听状态。保持启动顺序,策略回调留在所属功能组件内。旧的 `Helper` 兼容类已被移除。 + +## 目标 +- 确认 waylib 是否已有封装 +- 需要时新增 `WServerInterface` 封装 +- 把 native handle 的所有权与销毁写清楚 +- 把结果接到 `WaylandServer::init` 的启动路径上 + +## 先读 +1. `waylib/src/server/protocols` +2. `waylib/src/server/kernel` +3. `3rdparty/wlroots/include/wlr`(wlroots 原始 C API 头文件 —— 读其中的 native `wlr_*` 类型与 `wl_signal` 事件;包含方式统一用 ``) +4. `src/core/waylandserver.cpp` 与相关功能控制器 + +先搜索已有封装,不要假设 treeland 应该自己在本地重新实现一个 manager。 + +## 第一原则 +上游协议优先复用 wlroots 的 native 实现,由 waylib 提供 Qt/C++ 封装层。treeland 侧通常只负责 attach 封装并连接业务行为。 + +treeland 侧的首选形态通常是: + +```cpp +auto *iface = m_server->attach(); +connect(iface, ...); +``` + +## 最小封装要求 +提供 `WServerInterface` 子类,至少实现: + +- `interfaceName() const` +- `create(WServer *server)` +- `destroy(WServer *server)` +- `global() const` + +`create`、`destroy`、`global` 在 `WServerInterface` 上是 `protected` 虚函数(见 `waylib/src/server/kernel/wserver.h`);`interfaceName()` 是唯一的 public 纯虚函数。 + +如果封装需要注册 native `wl_signal` 监听,它必须同时继承 `WObject`,即 `class WFoo : public QObject, public WServerInterface, public WObject` —— 只继承 `WServerInterface` 是没有 `listeners()` 和 `teardown()` 的。 + +### 最小骨架 +照抄邻近封装,不要自创第三种形态: + +```cpp +// wfoo.h +class WFoo : public QObject, public WServerInterface, public WObject +{ + Q_OBJECT +public: + ~WFoo() override; + + QByteArrayView interfaceName() const override; + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; +}; +``` + +```cpp +// wfoo.cpp +WFoo::~WFoo() +{ + // 注册了 wl_signal 监听就必须调 teardown();~WObject 在还有监听组残留时会 abort。 + teardown(); +} + +void WFoo::create(WServer *server) +{ + // WServer::handle() 返回原始 wl_display*,直接交给 wlroots 的 C 构造函数; + // 返回的指针存进 m_handle(void*)。 + m_handle = wlr_foo_manager_v1_create(server->handle(), FOO_MANAGER_V1_VERSION); +} + +void WFoo::destroy([[maybe_unused]] WServer *server) +{ + // 该类型没有 wlr_foo_manager_v1_destroy():native 对象随 wl_display 回收, + // 只需清空句柄,使重启后能重新创建 global。 + m_handle = nullptr; +} + +wl_global *WFoo::global() const +{ + if (!m_handle) + return nullptr; + // nativeInterface() 把 m_handle 重新解释成 T*;wlroots C 结构体直接暴露 global 字段。 + return nativeInterface()->global; +} + +QByteArrayView WFoo::interfaceName() const +{ + // 与邻近封装一致,直接返回 wl_interface 名(不是 global 名,也不是 xml 文件名)。 + return "zwlr_foo_manager_v1"; +} +``` + +## 如何判断销毁 +不要机械照抄 treeland 私有协议里的 `globalRemove()`。 + +native handle 是存在 `m_handle`(`void*`)里的 wlroots 原始 C 指针。销毁方式取决于 native 所有权: + +- 如果 `wlr_*_create(...)` 返回的对象没有公开的 destroy 函数,`destroy()` 通常只需清空 `m_handle = nullptr` —— native 对象会在 `WServer::stop()` 销毁 `wl_display` 时被回收 +- 如果该 wlroots 类型提供显式 `wlr_*_destroy(...)`,对按 socket 创建的协议 manager,在 `destroy()` 中以 `ownsSocket() && m_handle` 为条件调用 native destroy,并对提供 `bool destroy_global_safe` 参数的接口显式传 `false`,立即销毁 global,再清空 `m_handle`;没有 owning socket 时只清空 wrapper 的 `m_handle`,native manager、global 和子对象均留给 display 回收,不调用 `wl_global_remove()` 或 native 子对象 destroy。wrapper 自身的状态与监听仍按原有生命周期清理。不要把这个条件套到本来就独立拥有 native handle 的 backend、seat、XWayland 上。 +- native manager 的显式 destroy 通常要求先销毁使用它的客户端对象;`ownsSocket()` 标记生命周期所属域,不会自动断开客户端。会话 teardown 必须先清理该域客户端再 detach manager;只有 owning socket 标记而没有完成客户端清理,不能据此认定立即销毁 global 是安全的。 +- 当前 vendored wlroots 已为 cursor-shape、pointer constraints/gestures、relative-pointer、foreign-toplevel、ext-workspace、output-management、xdg-shell/decoration/dialog/tag、session-lock、input-method、text-input-v3、virtual-keyboard 等 manager 提供显式 destroy API。以当前头文件为准,不要沿用 wrapper 中旧的“没有 destroy API”注释。 +- `WSecurityContextManager` 和 `WXdgOutputManager` 使用 waylib 本地实现(前者结构还带额外状态),应调用各自本地实现的 handle destroy 函数,再按相同的 `ownsSocket() && m_handle` 条件接入 wrapper 的 `destroy()`;不能将它们的 handle 交给 wlroots 同名类型的 destroy 函数。本地实现也必须让调用者选择销毁方式:socket-owned manager 在客户端已清理后传 `false`,display 回收同样使用非延迟路径;layout 等其他销毁入口若仍可能有客户端延迟绑定,则保留 safe destroy。 +- waylib 的 `WObject` 作用域监听列表(`listeners()->add(...)`)会在 `destroy()` 之前自动摘除:`WServer::stop()` 和 `WServer::detach()` 会对属于 `WObject` 的接口调用 `WObject::teardown()`。不要释放 display teardown 已经负责的 native 状态。`~WObject` 在还有监听组残留时会 abort,所以注册了监听的封装必须同时在自己的析构函数里调用 `teardown()`(见 `waylib/src/server/kernel/wglobal.h` 中 `WObject::teardown()` 的注释)。 + +判断方法: + +1. 读同目录下邻近的 `W...` 封装 +2. 读 `3rdparty/wlroots/include/wlr` 中对应 `wlr_*` 类型是否提供显式 `destroy()` 之类 API +3. 确认 `create()` 是否被 `if (!m_handle)` 保护;如果是,`destroy()` 必须清空 `m_handle`,否则重启后无法重新创建 global + +核心规则:销毁方式必须与 native handle 所有权一致。 + +## 每会话 global 的隔离与撤销 + +- 每个 Session 独立创建 manager,经 `Session::attachInterface()` 在暴露 global 前设置 owning socket。 +- `WServerInterface::ownsClient()` 接受 socket 的父域;要求精确 Session 隔离时,还应通过 `setFilter()` 校验 `Session::ownsClient()`,不能只依赖 `setOwnsSocket()`。 +- 没有 owning socket 的 display-owned manager 在 `destroy()` 中只清空 `m_handle`,不撤销 global、不销毁 native 子对象。只有有 owning socket 且有原生 destroy API 的 manager,才按上述条件显式销毁;没有原生 destroy API 时不能假定它支持安全 detach。 +- commit 事件携带 wlroots 临时请求列表时,使用 `Qt::DirectConnection` 同步处理;不要将列表或请求指针排队到下一轮事件循环。 + +## 通过 `WaylandServer::init` 接线 +最终仍要接回 `src/core/waylandserver.cpp`: + +1. `m_server->attach()` +2. 需要时把对象存成成员或局部变量 +3. 紧接着写业务 `connect(...)` +4. 接入 `ShellHandler`、surface/output 管理或 QML 层 + +不要把“必须在 `WaylandServer::init` 里直接 attach”当成唯一合法形式。 + +有些协议可以通过更高层的对象初始化,例如: + +```cpp +m_shellHandler->init(m_server, m_seat); +``` + +这同样算有效集成。真正的判断标准是: + +- 启动流程是否仍然从 `WaylandServer::init` 进入 +- 更高层对象是否干净地封装了某个 shell 或协议族的初始化 +- 注册入口与生命周期所有权是否依然清晰 + +若某个封装既没有从 `WaylandServer::init` 直接 attach,也没有通过更高层对象初始化,那这个协议对 treeland 来说仍未真正可用。 + +## 参考起点 +- `waylib/src/server/protocols/wforeigntoplevelv1.cpp` +- `waylib/src/server/protocols/wextforeigntoplevellistv1.cpp` +- `waylib/src/server/kernel/wserver.h` +- `src/core/waylandserver.cpp` + +## 输出要求 +用本 skill 处理真实任务时,先明确这几点: + +1. wlroots 是否已实现该协议 +2. waylib 是否已有 `W...` 封装 +3. 若没有,native handle 归谁所有、由谁负责销毁 +4. treeland 从 `WaylandServer::init` 的哪个位置进入启动路径,业务 `connect(...)` 应该放在哪里 diff --git a/.agents/skills/treeland-protocol/SKILL.md b/.agents/skills/treeland-protocol/SKILL.md new file mode 100644 index 0000000000..8a1deaa736 --- /dev/null +++ b/.agents/skills/treeland-protocol/SKILL.md @@ -0,0 +1,242 @@ +--- +name: treeland-protocol +description: "把 treeland 私有 Wayland 服务端协议接入合成器:协议 XML 与生成的代码、manager/resource 实现、资源销毁职责划分、`WServerInterface` 接线。在新增或修改 `treeland_*` 协议、在 `src/modules/*` 下实现 `QtWaylandServer::` 类、用 `waylib_generate_qtwayland_server_protocol(...)` 生成代码、区分 `destroy(...)` 与 `destroy_resource(...)`、把协议接到 `WaylandServer::init` 启动路径时使用。上游 standard/ext/unstable/wlr 协议见 `treeland-protocol-upstream`。" +--- + +# Treeland 私有协议集成 + +> **铁律**:`destroy(...)` 只做 `wl_resource_destroy(resource->handle)`;真正的业务清理只放 `destroy_resource(...)`。 + +## 范围 +本 skill 只用于 treeland 私有协议,不用于上游 wlroots/waylib 协议。 + +出现以下任一情况即适用: + +- 协议 xml 由 treeland 维护 +- 接口名通常是 `treeland_*` +- 代码位于 `src/modules/*` +- CMake 使用 `waylib_generate_qtwayland_server_protocol(...)` +- 生成类型是 `QtWaylandServer::*` + +若协议是 standard/ext/unstable/wlr 上游协议,停下来改用上游协议 skill。 + +## 启动装配 +`WaylandServer` 既是 QML singleton,也是 C++ 侧桌面入口。其 `init()`(`src/core/waylandserver.cpp`)负责组装启动流程;`src/core/waylandserver.cpp` 持有 Wayland 运行时与核心 global。各功能组件自己持有协议回调与监听状态。保持启动顺序,策略回调留在所属功能组件内。旧的 `Helper` 兼容类已被移除。 + +## 目标 +把下面四件事做对: + +- 生成服务端协议代码 +- 实现 manager 与 resource 类 +- 通过 `WServerInterface` 集成 +- 接到 `WaylandServer::init` 的启动路径上 + +## 先读 +1. 目标模块的 `CMakeLists.txt` +2. `waylib/tools/CMakeLists.txt` +3. 构建目录中的生成文件 +4. `src/core/waylandserver.cpp` 与相关功能控制器 + +先看生成文件(在对应模块的构建目录里,不在源码树): + +- `build/<模块目录>/qwayland-server-.h/.cpp` +- `build/<模块目录>/wayland--server-protocol.h/.c` + +不要猜生成类名、`Resource` 回调签名、`init(...)` 重载或 `interfaceName()`。 + +注意:`treeland_*.xml` 协议文件由外部 CMake 包 `TreelandProtocols` 提供(通过 `find_package(TreelandProtocols REQUIRED)`),不在 treeland 源码树中。通过 `${TREELAND_PROTOCOLS_DATA_DIR}/treeland-*.xml` 访问。不要在 `src/modules/` 下搜索 XML 文件。 + +从生成的 `qwayland-server-*.h/.cpp` 中直接确认至少这些事实: + +- 生成了哪些 helper API,例如 `resourceMap()`、`resource()`、`isGlobalRemoved()`、`interfaceVersion()` +- `destroy(...)`、`destroy_resource(...)`、`bind_resource(...)` 的默认行为是什么 +- `handle_destroy(...)` 只是把销毁请求转发给你重写的 `destroy(Resource *resource)`;真正销毁通常仍需 `wl_resource_destroy(resource->handle)` +- `destroy_func` 会在调用你的 `destroy_resource(...)` 之前把 resource 从 `m_resource_map` 中移除 +- `destroy_resource(...)` 返回后,生成代码会删除生成的 `Resource` 包装对象;这不代表你自己的 QObject/私有对象也被自动删除 +- `globalRemove()` 不会立即调用 `wl_global_destroy()`;它先调用 `wl_global_remove(...)`,再延迟销毁 + +这些细节决定实现边界: + +- `destroy_resource(...)` 负责清理业务对象与业务状态,不负责删除生成的 `Resource` 包装对象 +- 调用 `globalRemove()` 之后更准确的含义是“global 移除已安排”,而不是“已同步销毁” +- 如果 xml 中 manager 接口没有 destructor 请求,生成代码不会为该 manager 提供 `handle_destroy(...)` 或 `virtual void destroy(Resource *resource)`;此时不要假设可以重写 manager 的 destroy + +## 构建路径 +优先使用已有 helper(定义在 `waylib/tools/CMakeLists.txt`): + +`waylib_generate_qtwayland_server_protocol( PROTOCOL BASENAME [PREFIX ])` + +第一个参数是持有生成源码的 CMake target(通常是 `libtreeland`);`PROTOCOL` 是 xml 路径,`BASENAME` 决定生成文件名。可选的 `PREFIX` 设置生成的 C++ 类型/命名空间前缀(例如 `src/modules/personalization/` 中的 `PREFIX "/"`);默认空前缀时可省略。 + +典型产物: + +- `wayland--server-protocol.c` +- `qwayland-server-.h/.cpp` + +至少确认: + +1. target 源码列表包含 `wayland--server-protocol.c` +2. include 路径包含 `${CMAKE_CURRENT_BINARY_DIR}` +3. `BASENAME`、生成文件名与 C++ 类型名一致 +4. **`BASENAME` 必须等于 `` 把下划线换成短横线**(例如 `` → `BASENAME treeland-screensaver-unstable-v2`)。生成的 `.cpp` 内部 `#include` 由 `` 推导(下划线→短横线),而生成文件名由 `BASENAME` 推导;两者不一致时生成的 `.cpp` 找不到自己的头文件,构建失败。因此即使只改 ``(接口名不变),也必须同步更新 `BASENAME` 以及源码中每一处 `#include "qwayland-server-.h"`。 + +## 推荐代码结构 +- public 类:`QObject + WServerInterface` +- private manager:继承 `QtWaylandServer::treeland_xxx_manager_v1` +- private resource:继承 `QtWaylandServer::treeland_xxx_v1` + +把 `QtWaylandServer::*` 继承留在 `.cpp` 的私有实现类里,不要泄漏进 public 头文件。 + +判定规则:只有业务代码真的需要业务 API 时才创建 public 类,纯协议细节留在 `.cpp` 私有类中。不要因为协议里有某个子对象就为它建 public 头文件。 + +需要各层职责清单、以及「何时把子对象提升为 public 封装」时,读 `references/layering.md`。 + +## 请求处理器的参数校验 +libwayland 在请求处理器执行前会校验每个对象参数:非 nullable 参数永远不为 NULL,未知 id 与类型不匹配会让分发以协议错误失败,已销毁的 resource 不再可解析,只有标记 `allow-null="true"` 的参数才可能为 NULL。因此请求处理器无需校验传入对象是否符合协议声明类型或是否仍存活 —— 这类检查是不可达的死代码。 + +分发层无法知道、处理器仍必须检查的内容:跨客户端所有权(`wl_resource_get_client`)、inert resource(`wlr_*_from_resource` 返回 NULL)、缺失的封装(`WSurface::fromHandle` / `WOutput::fromHandle` 返回 nullptr)、协议取值规则(正数尺寸、枚举范围),以及 xml 标记 `allow-null="true"` 时的 NULL。 + +## Manager 接口接线 +public 类通常实现: + +- `create(WServer *server)` +- `destroy(WServer *server)` +- `global() const` +- `interfaceName() const` + +推荐写法: + +```cpp +// WServer::handle() 返回原始 wl_display*。直接传给生成 manager 的 init()。 +void Manager::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void Manager::destroy(WServer *server) +{ + Q_UNUSED(server); + d->globalRemove(); +} + +// 在私有 manager 类中(.cpp): +// m_global 在生成基类中是 protected。public 类无法直接访问 +// d->m_global(protected 不适用于外部指针访问)。 +// 通过私有子类中的小访问器暴露出来: +wl_global *globalHandle() const { return m_global; } + +// public 类中: +wl_global *Manager::global() const +{ + return d->globalHandle(); +} + +QByteArrayView Manager::interfaceName() const +{ + return QtWaylandServer::treeland_foo_manager_v1::interfaceName(); +} +``` + +规则: + +- 在 public manager 类中定义 `static constexpr int InterfaceVersion = N;`,并在 `create()` 中使用 +- 在 `destroy()` 中直接调用 `globalRemove()` +- 不要用多余的 `if (m_global)` 包一层 +- 子接口/resource 版本不绑定 `resource->version()` 时,同样使用类作用域常量 + +### 常见 manager 变体 +不要把 manager 只理解成“创建 global 的东西”。 + +当前代码中 manager 还经常: + +- 在 `bind_resource(Resource *resource)` 中发送初始状态 +- 在请求处理器里用 `wl_resource_create(...)` 手动创建子 resource +- 用 `resource->version()` 作为子 resource 版本,而不是另造硬编码版本 + +新私有协议应默认带 manager `destroy` 请求,并实现: + +```cpp +void destroy(Resource *resource) override +{ + wl_resource_destroy(resource->handle); +} +``` + +少数已有 manager 缺 `destroy` 请求属于历史设计问题,当作兼容例外,不要作为新协议的模板。 + +该请求本身属于协议 xml,而 xml 在外部 `TreelandProtocols` 包中(见“先读”中的说明)。添加它意味着在该包发布新的 xml 版本,本仓库无法声明它。 + +## 资源销毁 +这是最容易出错的部分,但分工只有一条:`destroy(...)` 只做 `wl_resource_destroy(resource->handle)`,业务清理只放 `destroy_resource(...)`。 + +判定规则:先问「这个 C++ 对象是否只为该 resource 创建、并应随它消亡?」 + +- 是:`destroy_resource(...)` 删除该对象;回调可能重入时用 `deleteLater()` 而不是 `delete this` +- 否:只清理该 resource 绑定的状态(从 map/列表移除 `resource->handle`,清 owner/watch/callback 记录) + +`destroy_resource(...)` 返回后生成代码会删除生成的 `Resource` 包装对象,但这不代表你自己的 QObject 被删除。完整的三种场景、manager 按客户端 resource 的处理、子 resource 创建模板(`wl_resource_create` + `wl_client_post_no_memory`)见 `references/lifetime.md`。 + +## 通过 `WaylandServer::init` 接线 +最终必须接回 `src/core/waylandserver.cpp`。 + +检查: + +1. 是否通过 `m_server->attach<...>()` 初始化 +2. 需要时是否存成 `WaylandServer` 成员 +3. attach 之后是否立即写业务 `connect(...)` +4. 是否接入 `ShellHandler`、`RootSurfaceContainer`、`QmlEngine` 或其他既有对象 + +不要把“注册点必须在 `WaylandServer::init`”理解得过死。 + +仓库中也有由更高层对象封装协议初始化的情形,例如: + +```cpp +m_shellHandler->init(m_server, m_seat); +``` + +这同样算协议注册入口。真正的判断标准是: + +- 启动流程是否仍然从 `WaylandServer::init` 进入 +- 更高层对象是否干净地封装了某个协议族的初始化 +- 注册入口与生命周期所有权是否依然易于定位 + +若某个协议既没有从 `WaylandServer::init` 直接注册,也没有通过 `ShellHandler` 这类更高层对象初始化,那它通常仍未完成集成。 + +## 反面样例 +`capture` 使用 `ws_generate_local`(裸 wayland-scanner)而不是首选的 `waylib_generate_qtwayland_server_protocol(...)` 路径,且完全没有使用 `QtWaylandServer::*`。不要把它当模板。 + +`foreign-toplevel` 已完全迁移到 `QtWaylandServer::*` + `waylib_generate_qtwayland_server_protocol(...)` 路径。它是需要 public 子对象封装(`ForeignToplevelHandleV1`、`DockPreviewContextV1`)的合法参考,但体量和复杂度不适合作为简单新协议的起点。 + +新私有协议优先参考 `appidresolver`、`prelaunch-splash` 或 `screensaver`。 + +## 参考起点 +- `src/modules/app-id-resolver/appidresolver.cpp` +- `src/modules/prelaunch-splash/prelaunchsplash.cpp` +- `src/modules/screensaver/screensaverinterfacev2.cpp` +- `waylib/tools/CMakeLists.txt` +- `src/core/waylandserver.cpp` + +## 引用 wlr_* 接口的协议 +如果 treeland xml 的对象参数使用了 wlroots 协议定义的接口(例如 `treeland-output-uuid-head-unstable-v1.xml` 接收 `zwlr_output_head_v1`),生成的服务端代码会引用该接口的 `wl_interface` 符号,例如 `zwlr_output_head_v1_interface`。 + +waylib-wlroots 只导出 `wlr_*`、`_wlr_*` 与 `waylib_*`(`3rdparty/wlroots/wlroots.syms`),因此所有协议符号对 `libwaylib-wlroots.so` 都是局部的,无法从 libtreeland 解析。需要在 libtreeland 中也生成该 wlr 协议,在消费模块里写: + +```cmake +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${CMAKE_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-output-management-unstable-v1.xml + BASENAME wlr-output-management-unstable-v1 +) +``` + +容易漏掉的原因:共享库默认允许未定义符号,所以 `--target libtreeland` 会成功。错误只在可执行文件链接 libtreeland 时才暴露(`undefined reference to _interface`),而损坏的 `libtreeland.so` 在运行时加载也会失败。 + +现存例子:`src/modules/output-uuid/CMakeLists.txt` —— `treeland-output-uuid-head-unstable-v1` 的参数是 `zwlr_output_head_v1`,所以它同时把 `wlr-output-management-unstable-v1.xml` 生成进 libtreeland。 + +## 输出要求 +用本 skill 处理真实任务时,先明确这几点: + +1. xml 与生成文件在哪里 +2. manager 的 `create/destroy/global/interfaceName` 应如何实现 +3. `destroy(...)` 与 `destroy_resource(...)` 的职责如何划分 +4. 协议从 `WaylandServer::init` 的哪个位置进入启动路径 +5. 请求处理器不再添加分发层已经完成的参数校验(见“请求处理器的参数校验”) diff --git a/.agents/skills/treeland-protocol/references/layering.md b/.agents/skills/treeland-protocol/references/layering.md new file mode 100644 index 0000000000..eccfc3b5fe --- /dev/null +++ b/.agents/skills/treeland-protocol/references/layering.md @@ -0,0 +1,52 @@ +# 分层模型(public 类 / private manager / private resource) + +由 `SKILL.md` 按需加载:需要决定「哪些代码放 public 头文件、哪些留 `.cpp`」或「要不要为子对象建 public 封装」时读本文件。 + +## 分层模型 +当前 treeland 私有协议的主流设计把业务 API 与协议实现细节分开。 + +### public 类 +public 头文件暴露面向业务的 API,不暴露 `QtWaylandServer::*` 类型。 + +public 类通常: + +- 继承 `QObject` 与 `WServerInterface` +- 向业务代码暴露方法、信号和少量查询 API +- 实现 `create/destroy/global/interfaceName` +- 用 `std::unique_ptr` 持有 private manager + +`WaylandServer::init` 与其他 treeland 业务代码 attach、连接、调用的就是这个 public 类。 + +### private manager 类 +定义在 `.cpp` 中,直接继承 `QtWaylandServer::treeland_xxx_manager_v1`。 + +它通常负责: + +- 协议 global 生命周期 +- manager 请求分发 +- `bind_resource(...)` 中的初始状态同步 +- 创建子 resource 或 context 对象 + +### private resource / context 类 +定义在 `.cpp` 中,继承 `QtWaylandServer::treeland_xxx_v1`。 + +它通常对应一个具体协议对象,负责: + +- 处理该 resource 的请求 +- 在 `destroy_resource(...)` 中清理 +- 把协议事件翻译成 public 类的信号、回调或业务动作 + +### 何时需要 public 子对象封装 +不是每个子 resource 都需要自己的 public 头文件。 + +若子对象只是 manager 的内部细节、没有其他 treeland 代码需要的业务 API,就让它保持为 `.cpp` 中的私有 resource 类。 + +若子对象需要被 treeland 业务代码长期引用、需要 parent、需要发信号、需要额外方法,或被其他类持有,就把它做成 public QObject 封装(类似 foreign-toplevel 中的 handle/context 类),下面挂一个私有协议实现类。 + +## 设计偏好 +规则: + +- 只有业务代码真的需要业务 API 时才创建 public 类 +- 纯协议细节留在 `.cpp` 私有类中 + +不要因为协议里有某个子对象就为它建 public 头文件。只有业务代码真的需要知道它时,才提升为 public 封装。 diff --git a/.agents/skills/treeland-protocol/references/lifetime.md b/.agents/skills/treeland-protocol/references/lifetime.md new file mode 100644 index 0000000000..c38ef5703c --- /dev/null +++ b/.agents/skills/treeland-protocol/references/lifetime.md @@ -0,0 +1,119 @@ +# 资源生命周期(destroy / destroy_resource) + +由 `SKILL.md` 按需加载:需要判断「对象该不该在 `destroy_resource(...)` 里删除」、处理 manager 的按客户端 resource、或创建子 resource 时读本文件。 + +## 客户端显式销毁 +在 `destroy(Resource *resource)` 中只做: + +```cpp +wl_resource_destroy(resource->handle); +``` + +不要把真正的业务清理放这里。 + +## 最终清理 +真正的清理路径优先放在 `destroy_resource(Resource *resource)`。在这里: + +- 更新存活状态 +- 发出断开/关闭相关信号 +- 清理回调与连接 +- `delete this` 或 `deleteLater()` + +典型写法: + +```cpp +void destroy_resource(Resource *) override +{ + m_alive = false; + if (onDisconnected) + onDisconnected(); + delete this; +} +``` + +如果回调可能运行在 Qt 信号分发或其他可重入路径中,优先用 `deleteLater()`。 + +不要假设 `destroy_resource(...)` 一定会删除对象本身。当前代码中也存在这些模式: + +- manager 的 resource 只清理与该 `resource->handle` 关联的 map、watch 列表或 owner map +- QObject 生命周期由 parent、外层封装对象或显式容器持有 + +也就是说,`destroy_resource(...)` 的核心职责是"干净地结束这个 resource 的生命周期",而不必然是"立即删除所有相关对象"。 + +## 何时删除对象 +如果 QObject/私有对象是专为单个 Wayland resource 创建、且没有其他持有者,`destroy_resource(...)` 就应结束该对象的生命周期。 + +典型特征: + +- 构造函数直接接收 `wl_resource *` 或 `Resource *` +- 一个对象严格对应一个客户端 resource +- 对象存在的唯一目的就是包装这个协议对象 +- 没有 parent、容器或 manager 继续持有它 + +典型实现: + +```cpp +void destroy_resource(Resource *) override +{ + delete this; +} +``` + +若存在重入风险,用: + +```cpp +void destroy_resource(Resource *) override +{ + deleteLater(); +} +``` + +## 何时不删除对象 +如果 QObject 不是由单个 resource 独占,只是借助 resource 跟踪某个客户端的状态,`destroy_resource(...)` 就只应清理该 resource 相关状态。 + +典型特征: + +- 对象本身是 manager,跟随 global 或外层接口的生命周期 +- 对象有明确的 QObject parent,由 parent 负责销毁 +- 对象仍被静态列表、管理容器或业务代码持有 +- 一个对象管理多个 resource,而不是严格一对一 + +这种情况下通常只做: + +- 从 map/列表/集合中移除 `resource->handle` +- 清理 owner、watch、callback 记录 +- 更新连接状态或可用性标记 + +不要因为一个客户端 resource 被销毁就删除仍在服务其他状态的 manager 或共享对象。 + +## 判定规则 +先问一个问题: + +"这个 C++ 对象是否只为该 resource 创建、并应随它消亡?" + +- 是:`destroy_resource(...)` 应删除该对象 +- 否:`destroy_resource(...)` 只应清理与该 resource 绑定的状态 + +## Manager 的按客户端 resource +如果 manager 只有一个轻量的按客户端代理 resource,`destroy(Resource*)` 里调用 `wl_resource_destroy(...)` 通常就够。不要把业务状态清理堆进去。 + +## 子 resource 创建 +很多现有私有协议采用"manager 手动创建子 resource,再交给私有封装对象"的模式,例如: + +```cpp +auto *child = wl_resource_create(resource->client(), + &treeland_foo_v1_interface, + resource->version(), + id); +if (!child) { + wl_client_post_no_memory(resource->client()); + return; +} +new FooContext(child); +``` + +该模式下要确认: + +- 子 resource 版本跟随 `resource->version()` +- 失败时用 `wl_client_post_no_memory(...)` +- 需要时在子对象销毁时把它从静态列表、map 或 owner 结构中移除 diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000..205d4ee172 --- /dev/null +++ b/.clang-format @@ -0,0 +1,149 @@ +# This is the clang-format style used by qt releated deepin projects. +# +# This file is modified from https://github.com/qt/qt5/blob/5b22f8ec2e4fbb58e362b709ee82f2dbd8afdfd3/_clang-format +# based on the rules from https://github.com/linuxdeepin/deepin-styleguide, +# https://wiki.qt.io/Qt_Coding_Style and https://wiki.qt.io/Coding_Conventions +# +# This is for clang-format >= 14.0.0 + +--- +# Webkit style was loosely based on the Qt style +BasedOnStyle: WebKit + +# deepin project might not use same standard. +Standard: Auto + +# Column width is limited to 100 in accordance with Qt Coding Style. +# https://wiki.qt.io/Qt_Coding_Style +# Note that this may be changed at some point in the future. +ColumnLimit: 100 +# How much weight do extra characters after the line length limit have. +# PenaltyExcessCharacter: 4 + +# Disable reflow of some specific comments +# qdoc comments: indentation rules are different. +# Translation comments and SPDX license identifiers are also excluded. +CommentPragmas: "^!|^:|^ SPDX-License-Identifier:" + +PointerAlignment: Right + +# We use template< without space. +SpaceAfterTemplateKeyword: false + +# We want to break before the operators, but not before a '='. +BreakBeforeBinaryOperators: NonAssignment + +# Braces are usually attached, but not after functions or class declarations. +BreakBeforeBraces: Custom +BraceWrapping: + AfterClass: true + AfterControlStatement: false + AfterEnum: true + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: true + AfterUnion: true + BeforeCatch: false + BeforeElse: false + IndentBraces: false + +# Indent initializers by 4 spaces +ConstructorInitializerIndentWidth: 4 + +# Indent width for line continuations. +ContinuationIndentWidth: 4 + +# No indentation for namespaces. +NamespaceIndentation: None + +# Allow indentation for preprocessing directives (if/ifdef/endif). https://reviews.llvm.org/rL312125 +IndentPPDirectives: AfterHash +# We only indent with 2 spaces for preprocessor directives +PPIndentWidth: 2 + +# Horizontally align arguments after an open bracket. +# The coding style does not specify the following, but this is what gives +# results closest to the existing code. +AlignAfterOpenBracket: Align +AlwaysBreakTemplateDeclarations: true + +# As clang-format 13 can regroup includes we enable this feature. +# basically according to https://wiki.qt.io/Coding_Conventions#Including_headers +# and https://github.com/linuxdeepin/deepin-styleguide +IncludeBlocks: Regroup +IncludeCategories: + # gtest/gmock's h files + - Regex: '^$' + Priority: 8 + CaseSensitive: true + # C system headers. + - Regex: '^<(aio|arpa/inet|assert|complex|cpio|ctype|curses|dirent|dlfcn|errno|fcntl|fenv|float|fmtmsg|fnmatch|ftw|glob|grp|iconv|inttypes|iso646|langinfo|libgen|limits|locale|math|monetary|mqueue|ndbm|netdb|net/if|netinet/in|netinet/tcp|nl_types|poll|pthread|pwd|regex|sched|search|semaphore|setjmp|signal|spawn|stdalign|stdarg|stdatomic|stdbool|stddef|stdint|stdio|stdlib|stdnoreturn|string|strings|stropts|sys/ipc|syslog|sys/mman|sys/msg|sys/resource|sys/select|sys/sem|sys/shm|sys/socket|sys/stat|sys/statvfs|sys/time|sys/times|sys/types|sys/uio|sys/un|sys/utsname|sys/wait|tar|term|termios|tgmath|threads|time|trace|uchar|ulimit|uncntrl|unistd|utime|utmpx|wchar|wctype|wordexp)\.h>$' + Priority: 8 + CaseSensitive: true + # other libraries' h files. + - Regex: '^<' + Priority: 3 +IncludeIsMainRegex: '((T|t)est)?$' +SortIncludes: CaseSensitive + +# macros for which the opening brace stays attached. +ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH, forever, Q_FOREVER, QBENCHMARK, QBENCHMARK_ONCE ] + +# Break constructor initializers before the colon and after the commas. +BreakConstructorInitializers: BeforeComma +BreakInheritanceList: BeforeComma + +# Add "// namespace " comments on closing brace for a namespace +# Ignored for namespaces that qualify as a short namespace, +# see 'ShortNamespaceLines' +FixNamespaceComments: true + +# Definition of how short a short namespace is, default 1 +ShortNamespaceLines: 1 + +# When escaping newlines in a macro attach the '\' as far left as possible, e.g. +##define a \ +# something; \ +# other; \ +# thelastlineislong; +AlignEscapedNewlines: Left + +# Avoids the addition of a space between an identifier and the +# initializer list in list-initialization. +SpaceBeforeCpp11BracedList: false + +AllowAllArgumentsOnNextLine: false +AllowShortLambdasOnASingleLine: Empty +AllowShortFunctionsOnASingleLine: Empty +AllowAllParametersOfDeclarationOnNextLine: false +AlignTrailingComments: true +BinPackArguments: false +BinPackParameters: false +PackConstructorInitializers: Never +PenaltyReturnTypeOnItsOwnLine: 130 +SeparateDefinitionBlocks: Always +WhitespaceSensitiveMacros: + - Q_PROPERTY + - Q_INTERFACES diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000..00b584c20b --- /dev/null +++ b/.editorconfig @@ -0,0 +1,27 @@ +# EditorConfig is awesome: https://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +indent_style = space +indent_size = 4 + +[*.rs] +max_line_length = 100 + +[*.{diff,md}] +# double whitespace at end of line +# denotes a line break in Markdown +trim_trailing_whitespace = false + +[*.{yml,yaml}] +indent_size = 2 + +[Makefile] +indent_style = tab diff --git a/.envrc b/.envrc new file mode 100644 index 0000000000..3bb52447c5 --- /dev/null +++ b/.envrc @@ -0,0 +1,2 @@ +watch_file nix/default.nix +use flake diff --git a/.github/ISSUE_TEMPLATE/bug_report.yaml b/.github/ISSUE_TEMPLATE/bug_report.yaml new file mode 100644 index 0000000000..ca14e7c992 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yaml @@ -0,0 +1,90 @@ +name: BUG Report | 缺陷报告 +description: General BUG report +title: "[Bug]: " +labels: ["bug"] +assignees: [] +body: +- type: markdown + attributes: + value: | + **Thanks for taking a minute to file a bug report!** + **感谢抽出时间汇报 BUG 缺陷!** + + A valid bug report should let someone other than you be able to reproduce the same issue, so please provide as much details as possible. + 一个有效的缺陷汇报应当能够使一个你之外的人可以根据所提供的信息有效的复现问题。所以请提供尽可能详细的信息。 + + ⚠ Read before creating issue 反馈之前请注意: + Only report BUG here, please use the [Discussion board][discussion-board] for non-bug, troubleshooting or general discusion. + 非 BUG 的反馈(疑难解答,行为建议,常规讨论)请转到 [Discussion 面板][discussion-board] + + [discussion-board]: https://github.com/linuxdeepin/treeland/discussions + +- type: textarea + attributes: + label: SUMMARY | 问题概要 + description: | + describe the bug you want to report + 在这里描述你遇到的 BUG + +- type: dropdown + attributes: + label: LAUNCH-WAY | 启动方式 + description: | + how to launch treeland + treeland 如何启动 + options: + - unknown + - ddm + - lightdm + default: 0 + validations: + required: true + +- type: dropdown + attributes: + label: BACKEND | 启动后端 + description: | + which backend to use + 使用哪个后端启动 + options: + - unknown + - DRM + - Wayland + - X11 + default: 0 + validations: + required: true + +- type: textarea + attributes: + label: STEPS TO REPRODUCE | 复现步骤 + description: | + describe the steps to reproduce the specific bug + 在这里描述复现 BUG 的操作步骤 + placeholder: | + 1. ... + 2. ... + 3. ... + validations: + required: true + +- type: textarea + attributes: + label: OBSERVED RESULT | 观察到的结果 + description: | + describe the observed result + 在这里描述观察到的结果 + +- type: textarea + attributes: + label: EXPECTED RESULT | 期望的结果 + description: | + describe the expected result + 在这里描述你所期望的结果 + +- type: textarea + attributes: + label: ADDITIONAL INFORMATION | 额外补充 + description: | + any additional information you may want to provide so we can offer better help + 有什么额外需要补充的信息的话,可以写到这里 diff --git a/.github/ISSUE_TEMPLATE/feature_request.yaml b/.github/ISSUE_TEMPLATE/feature_request.yaml new file mode 100644 index 0000000000..8316444994 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yaml @@ -0,0 +1,25 @@ +name: Feature Request | 功能请求 +description: General Feature request +title: "[Feature]: " +labels: [] +assignees: [] +body: +- type: markdown + attributes: + value: | + **Thanks for taking a minute to file a feature request!** + **感谢抽出时间提出新功能!** + + ⚠ Read before creating issue 反馈之前请注意: + Only request feature here, please use the [Discussion board][discussion-board] for non-bug, troubleshooting or general discusion. + 非新功能的反馈(疑难解答,行为建议,常规讨论)请转到 [Discussion 面板][discussion-board] + + [discussion-board]: https://github.com/linuxdeepin/treeland/discussions + +- type: textarea + attributes: + label: SUMMARY | 功能概要 + description: | + describe the feature you want to request + 在这里描述你想提出的新功能 + diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md new file mode 100644 index 0000000000..ad24b84e86 --- /dev/null +++ b/.github/copilot-instructions.md @@ -0,0 +1,6 @@ +# GitHub Copilot Repository Instructions for Treeland + +- Code reviews must be provided in both Chinese and English. +- Terminal commands in fenced `bash` blocks; paths/symbols in backticks. + +See `/AGENTS.md` for project-wide instructions. \ No newline at end of file diff --git a/.github/workflows/backup-to-gitlab.yml b/.github/workflows/backup-to-gitlab.yml new file mode 100644 index 0000000000..9863040fd8 --- /dev/null +++ b/.github/workflows/backup-to-gitlab.yml @@ -0,0 +1,15 @@ +name: backup to gitlab +on: [push] + +concurrency: + group: ${{ github.workflow }} + cancel-in-progress: true + +jobs: + backup-to-gitlabwh: + uses: linuxdeepin/.github/.github/workflows/backup-to-gitlabwh.yml@master + secrets: inherit + + backup-to-gitee: + uses: linuxdeepin/.github/.github/workflows/backup-to-gitee.yml@master + secrets: inherit diff --git a/.github/workflows/call-auto-tag.yml b/.github/workflows/call-auto-tag.yml new file mode 100644 index 0000000000..5018e5bebf --- /dev/null +++ b/.github/workflows/call-auto-tag.yml @@ -0,0 +1,16 @@ +name: auto tag + +on: + pull_request_target: + types: [opened, synchronize, closed] + paths: + - "debian/changelog" + +concurrency: + group: ${{ github.workflow }}-pull/${{ github.event.number }} + cancel-in-progress: true + +jobs: + auto_tag: + uses: linuxdeepin/.github/.github/workflows/auto-tag.yml@master + secrets: inherit diff --git a/.github/workflows/call-chatOps.yml b/.github/workflows/call-chatOps.yml new file mode 100644 index 0000000000..18c76bc33e --- /dev/null +++ b/.github/workflows/call-chatOps.yml @@ -0,0 +1,9 @@ +name: chatOps +on: + issue_comment: + types: [created] + +jobs: + chatopt: + uses: linuxdeepin/.github/.github/workflows/chatOps.yml@master + secrets: inherit diff --git a/.github/workflows/call-clacheck.yml b/.github/workflows/call-clacheck.yml new file mode 100644 index 0000000000..fe16a07330 --- /dev/null +++ b/.github/workflows/call-clacheck.yml @@ -0,0 +1,15 @@ +name: Call CLA check +on: + issue_comment: + types: [created] + pull_request_target: + types: [opened, closed, synchronize] + +concurrency: + group: ${{ github.workflow }}-pull/${{ github.event.number }} + cancel-in-progress: true + +jobs: + clacheck: + uses: linuxdeepin/.github/.github/workflows/cla-check.yml@master + secrets: inherit diff --git a/.github/workflows/call-commitlint.yml b/.github/workflows/call-commitlint.yml new file mode 100644 index 0000000000..69f5b2dc5a --- /dev/null +++ b/.github/workflows/call-commitlint.yml @@ -0,0 +1,11 @@ +name: Call commitlint +on: + pull_request_target: + +concurrency: + group: ${{ github.workflow }}-pull/${{ github.event.number }} + cancel-in-progress: true + +jobs: + check_job: + uses: linuxdeepin/.github/.github/workflows/commitlint.yml@master diff --git a/.github/workflows/call-license-check.yml b/.github/workflows/call-license-check.yml new file mode 100644 index 0000000000..347d55602d --- /dev/null +++ b/.github/workflows/call-license-check.yml @@ -0,0 +1,16 @@ +name: Call License and README Check +on: + pull_request_target: + types: [opened, synchronize, reopened] + +permissions: + pull-requests: write + contents: read + +concurrency: + group: ${{ github.workflow }}-pull/${{ github.event.number }} + cancel-in-progress: true + +jobs: + license-check: + uses: linuxdeepin/.github/.github/workflows/license-check.yml@master diff --git a/.github/workflows/call-update-changelog.yml b/.github/workflows/call-update-changelog.yml new file mode 100644 index 0000000000..b76b9b3ffb --- /dev/null +++ b/.github/workflows/call-update-changelog.yml @@ -0,0 +1,53 @@ +name: Call update changelog + +on: + workflow_dispatch: + inputs: + version: + description: "Target version; leave empty to auto bump" + required: false + type: string + name: + description: "Maintainer name used in debian/changelog" + required: true + type: string + email: + description: "Maintainer email used in debian/changelog" + required: true + type: string + base_branch: + description: "Base branch to read and target" + required: false + default: master + type: string + distribution: + description: "Changelog distribution" + required: false + default: unstable + type: string + create_pr: + description: "Create a pull request after generating changelog" + required: false + default: true + type: boolean + +jobs: + update_changelog: + uses: linuxdeepin/.github/.github/workflows/update-changelog.yml@master + with: + version: ${{ inputs.version }} + name: ${{ inputs.name }} + email: ${{ inputs.email }} + base_branch: ${{ inputs.base_branch }} + distribution: ${{ inputs.distribution }} + create_pr: ${{ inputs.create_pr }} + secrets: inherit + + show_result: + runs-on: ubuntu-latest + needs: update_changelog + steps: + - name: Show update changelog result + run: | + echo "Version: ${{ needs.update_changelog.outputs.version }}" + echo "Pull Request URL: ${{ needs.update_changelog.outputs.pr_url }}" diff --git a/.github/workflows/cppcheck.yml b/.github/workflows/cppcheck.yml new file mode 100644 index 0000000000..d1e8b0ab97 --- /dev/null +++ b/.github/workflows/cppcheck.yml @@ -0,0 +1,28 @@ +name: cppcheck +on: + pull_request_target: + paths-ignore: + - ".github/workflows/**" + +concurrency: + group: ${{ github.workflow }}-pull/${{ github.event.number }} + cancel-in-progress: true + +jobs: + cppchceck: + name: cppcheck + runs-on: ubuntu-latest + steps: + - run: export + - uses: actions/checkout@v7 + with: + ref: refs/heads/${{ github.event.pull_request.head.ref }} + repository: ${{ github.event.pull_request.head.repo.full_name }} + allow-unsafe-pr-checkout: true + persist-credentials: false + - uses: linuxdeepin/action-cppcheck@main + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + repository: ${{ github.repository }} + pull_request_id: ${{ github.event.pull_request.number }} + allow_approve: false diff --git a/.github/workflows/treeland-archlinux-build.yml b/.github/workflows/treeland-archlinux-build.yml new file mode 100644 index 0000000000..852e72f6f8 --- /dev/null +++ b/.github/workflows/treeland-archlinux-build.yml @@ -0,0 +1,144 @@ +name: Build treeland on Arch Linux + +# This workflow builds treeland with merged waylib code +# Dependencies are based on the official ArchLinux PKGBUILD plus +# additional dependencies from the integrated waylib code +# treeland-protocols-git is installed from AUR + +on: + pull_request: + +jobs: + container: + runs-on: ubuntu-latest + container: archlinux:latest + steps: + - name: Run in container + run: | + cat /etc/pacman.d/mirrorlist + pacman-key --init + pacman --noconfirm --noprogressbar -Syu + + - name: Install base dependencies + run: | + pacman -S --noconfirm --noprogressbar base-devel git cmake ninja pkgconfig clang make + pacman -S --noconfirm --noprogressbar fakeroot meson sudo + + - name: Install Qt6 dependencies + run: | + # Qt6 dependencies matching waylib builds + # qt6-httpserver & qt6-websockets are required by treeland-debug's + # `listen` HTTP/WebSocket server (hard build-time dependency) + pacman -S --noconfirm --noprogressbar qt6-base qt6-declarative qt6-wayland qt6-tools qt6-remoteobjects qt6-httpserver qt6-websockets + + - name: Install graphics and wayland dependencies + run: | + # Vendored waylib-wlroots deps from Arch wlroots0.19 package metadata + # (do not install system wlroots0.19) + pacman -S --noconfirm --noprogressbar \ + pixman wayland wayland-protocols wlr-protocols \ + libxcb libx11 libxkbcommon libdrm libinput seatd \ + libdisplay-info libliftoff lcms2 \ + mesa libglvnd vulkan-headers vulkan-icd-loader \ + glslang hwdata systemd \ + xcb-util-errors xcb-util-renderutil xcb-util-wm \ + xorg-xwayland + + - name: Install additional waylib dependencies + run: | + pacman -S --noconfirm --noprogressbar libxdmcp + - name: Install DTK dependencies + run: | + # Try to install DTK from available packages + # If not available, the build will proceed without them (may fail) + pacman -S --noconfirm --noprogressbar dtk6core dtk6declarative dtk6systemsettings + + - name: Install DDM dependencies + run: | + # Try to install DDM from available packages + pacman -S --noconfirm --noprogressbar ddm + + - name: Install MPV dependencies + run: | + # Try to install MPV from available packages + pacman -S --noconfirm --noprogressbar mpv + + - name: Build and Install treeland-protocols + run: | + echo "Building treeland-protocols from source..." + git clone https://github.com/linuxdeepin/treeland-protocols.git --depth 1 + cd treeland-protocols + cmake -B build \ + -DCMAKE_INSTALL_PREFIX=/usr \ + -DCMAKE_BUILD_TYPE=Release + cmake --build build + cmake --install build + echo "✅ treeland-protocols built and installed from source" + + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Configure and Build treeland with ci preset + run: | + echo "Working directory:" $PWD + echo "Configuring treeland with merged waylib code..." + rm -rf build + cmake --preset ci -DBUILD_TREELAND_PROTOCOL_TESTS=ON + cmake --build --preset ci + echo "✅ treeland built successfully with merged waylib code!" + + - name: Run unit tests + run: ctest --preset ci + + - name: Install treeland to staging directory + run: | + echo "Installing treeland to staging directory..." + mkdir -p /tmp/treeland-install + DESTDIR=/tmp/treeland-install cmake --install build + echo "✅ treeland installed to staging directory" + + echo "Installed files:" + find /tmp/treeland-install -type f | head -20 + echo "Total files installed: $(find /tmp/treeland-install -type f | wc -l)" + + - name: Create treeland installation package + run: | + cd /tmp/treeland-install + + # Install zip if not available + pacman -S --noconfirm zip + + # Create package info + echo "Creating package info..." + cat > PACKAGE_INFO.txt << EOF + Package: treeland-archlinux-build + Version: $(date +%Y%m%d-%H%M%S) + Architecture: x86_64 + Built-on: Arch Linux + Built-with: merged waylib code + CMake-Config: -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_INSTALL_LIBDIR=lib + + Installation Instructions: + 1. Extract this package to / + 2. Run: sudo ldconfig (if libraries are included) + 3. Ensure dependencies are installed on target system + + Files included in this package: + EOF + find . -type f | sort >> PACKAGE_INFO.txt + + # Create the zip package + zip -r /tmp/treeland-archlinux-$(date +%Y%m%d-%H%M%S).zip . + echo "✅ treeland installation package created" + + ls -la /tmp/treeland-archlinux-*.zip + + - name: Upload treeland ArchLinux build artifacts + if: ${{ !env.ACT }} + uses: actions/upload-artifact@v4 + with: + name: treeland-archlinux-build + path: "/tmp/treeland-archlinux-*.zip" + if-no-files-found: error + retention-days: 30 diff --git a/.github/workflows/treeland-deepin-build.yml b/.github/workflows/treeland-deepin-build.yml new file mode 100644 index 0000000000..4bb7bcf546 --- /dev/null +++ b/.github/workflows/treeland-deepin-build.yml @@ -0,0 +1,174 @@ +name: Build treeland on Deepin crimson (independent) + +on: + pull_request: + +jobs: + container: + runs-on: ubuntu-latest + container: linuxdeepin/deepin:crimson + env: + BUILD_TREELAND_PROTOCOL_TESTS: "OFF" + steps: + - uses: actions/checkout@v4 + + - name: Install build dependencies + run: | + # The Deepin crimson image ships no bash, so GitHub Actions falls + # back to `sh -e {0}`, which is dash here. Keep every step strictly + # POSIX: no arrays, no `mapfile`, no process substitution and no + # `set -o pipefail`. + set -eux + + echo "deb [trusted=yes] http://mirrors.kernel.org/deepin/beige/ crimson main commercial community" > /etc/apt/sources.list + echo "deb [trusted=yes] https://ci.deepin.com/repo/deepin/deepin-community/stable/ crimson main commercial community" >> /etc/apt/sources.list + echo "deb [trusted=yes] https://ci.deepin.com/repo/deepin/deepin-community/testing/ unstable/crimson main commercial community" >> /etc/apt/sources.list + rm -rf /etc/apt/sources.list.d + + apt-get update + # `devscripts` was only needed for `mk-build-deps`, which is no + # longer used. `dpkg-dev` is what we actually need: + # dpkg-buildpackage + dpkg-checkbuilddeps. + apt-get install -y dpkg-dev git + + # The full desktop fixture follows Treeland's normal global-session + # path, whose compositor-owned session is the system user "dde". + # The minimal CI image does not create it as part of its packages. + id -u dde >/dev/null 2>&1 || useradd --system --create-home --home-dir /var/lib/dde --shell /usr/sbin/nologin dde + + # Save the treeland workspace directory + TREELAND_DIR="$PWD" + echo "Treeland workspace directory: $TREELAND_DIR" + + # Build and install treeland-protocols locally (required build dependency not from repo) + echo "🔧 Building treeland-protocols from source (master)" + cd /tmp + if [ ! -d treeland-protocols ]; then + git clone --depth=1 --branch master --single-branch https://github.com/linuxdeepin/treeland-protocols.git + fi + cd treeland-protocols + apt-get build-dep -y . + dpkg-buildpackage -uc -us -b + apt-get install -y ../*.deb || dpkg -i ../*.deb || apt-get -f install -y + cd "$TREELAND_DIR" + + set +ex + BUILD_DEP_PROBE="$(LC_ALL=C apt-get -s build-dep -y . 2>&1)" + PROBE_RC=$? + printf '%s\n' "$BUILD_DEP_PROBE" > /tmp/treeland-checkdeps.log + set -ex + + NEED_DDM_FALLBACK=0 + if [ "$PROBE_RC" -ne 0 ]; then + case "$BUILD_DEP_PROBE" in + *libddm-dev*) NEED_DDM_FALLBACK=1 ;; + esac + fi + + if [ "$NEED_DDM_FALLBACK" -eq 1 ]; then + echo "⚠️ libddm-dev is not satisfiable from the repos, building ddm from source (master) as fallback" + sed -n '/libddm-dev/p' /tmp/treeland-checkdeps.log || true + cd /tmp + if [ ! -d ddm ]; then + git clone --depth=1 https://github.com/linuxdeepin/ddm.git + fi + cd ddm + # Install ddm build-deps + apt-get build-dep -y . + # Remove maintainer scripts to avoid post-install/remove actions in built packages + echo "🧹 Removing ddm maintainer scripts (*.postinst/*.postrm/*.prerm) before build" + rm -f debian/*.postinst debian/*.postrm debian/*.prerm || true + # Build ddm .deb packages + # + # A timestamp marker is used instead of `../*.deb`: /tmp already + # holds the treeland-protocols debs from the previous block, and + # `dpkg -i --force-all ../*.deb` would reinstall those as well. + touch /tmp/.ddm-build-start + dpkg-buildpackage -uc -us -b + # + # POSIX only: `sh` in this image is dash, so no `mapfile`, no + # process substitution and no arrays. A newline separated list + # file does the same job. + find /tmp -maxdepth 1 -name '*.deb' -newer /tmp/.ddm-build-start \ + | sort > /tmp/.ddm-debs.list + if [ ! -s /tmp/.ddm-debs.list ]; then + echo "❌ ddm build produced no .deb file in /tmp" + exit 1 + fi + echo "ddm packages built:" + cat /tmp/.ddm-debs.list + # Install built ddm packages (ignore postinst script errors since we only need dev files). + # shellcheck disable=SC2046 # word splitting over the list is intended + dpkg -i --force-all $(cat /tmp/.ddm-debs.list) || apt-get install -y -f || true + echo "✅ ddm packages installed (postinst errors ignored)" + cd "$TREELAND_DIR" + + # Fail loudly instead of silently continuing without the header + # files (that would make CMake disable the DDM integration). + if ! dpkg -s libddm-dev > /dev/null 2>&1; then + echo "❌ libddm-dev is still not installed after building ddm from source" + dpkg -l 'libddm*' || true + exit 1 + fi + + echo "🔧 Relaxing libddm-dev version constraint in debian/control" + sed -i -E 's/(libddm-dev)[[:space:]]*\([^)]*\)/\1/g' debian/control + elif [ "$PROBE_RC" -eq 0 ]; then + echo "✅ libddm-dev is satisfiable from the configured repositories, skipping ddm source build" + else + echo "⚠️ apt-get build-dep dry-run failed, but not because of libddm-dev:" + tail -20 /tmp/treeland-checkdeps.log + fi + + echo "Current Build-Depends:" + awk '/^Build-Depends:/{f=1} f && !/^Build-Depends:/ && !/^[ \t]/{exit} f{print}' \ + debian/control + + # Now install all treeland build dependencies via apt-get build-dep + apt-get build-dep -y . + + - name: Build treeland (compile only, no packaging) + run: | + set -eux + + # NOTE: debian/control is *not* patched here any more. The + # libddm-dev version constraint is relaxed in the install step, and + # only when the ddm fallback actually ran. Patching it unconditionally + # would silently hide a version regression in the repos. + echo "[Build step] current debian/control Build-Depends:" + awk '/^Build-Depends:/{f=1} f && !/^Build-Depends:/ && !/^[ \t]/{exit} f{print}' \ + debian/control + + # This is the one place where dpkg-checkbuilddeps is the right tool: + # the previous step has installed everything, so it verifies the + # *installed* state, which is exactly what we want before compiling. + set +ex + dpkg-checkbuilddeps 2> /tmp/treeland-builddeps.err + BUILDDEPS_RC=$? + set -ex + + if [ "$BUILDDEPS_RC" -ne 0 ]; then + echo "❌ Build dependencies are not satisfied:" + cat /tmp/treeland-builddeps.err + echo "📋 apt dependency resolver view:" + LC_ALL=C apt-get -s build-dep -y . || true + exit 1 + fi + + dpkg-buildpackage -uc -us -b + echo "✅ treeland built successfully (build only, no package artifacts)!" + + - name: Collect deb artifacts + run: | + set -eux + mkdir -p dist + mv ../*.deb dist/ + ls -la dist + + - name: Upload treeland deb packages as artifacts + uses: actions/upload-artifact@v4 + with: + name: treeland-deepin-deb-packages + path: dist/*.deb + if-no-files-found: error + retention-days: 30 diff --git a/.github/workflows/waylib-archlinux-build.yml b/.github/workflows/waylib-archlinux-build.yml new file mode 100644 index 0000000000..8d53594a9b --- /dev/null +++ b/.github/workflows/waylib-archlinux-build.yml @@ -0,0 +1,112 @@ +name: Build waylib on Arch Linux (independent) + +on: + pull_request: + paths: + - 'waylib/**' + - 'wlroots/**' + - '3rdparty/wlroots/**' + - '.github/workflows/waylib-archlinux-build.yml' + +jobs: + container: + runs-on: ubuntu-latest + container: archlinux:latest + steps: + - name: Run in container + run: | + cat /etc/pacman.d/mirrorlist + pacman-key --init + pacman --noconfirm --noprogressbar -Syu + - name: Install dependencies + run: | + # Vendored waylib-wlroots deps from Arch wlroots0.19 package metadata + # (do not install system wlroots0.19) + pacman -S --noconfirm --noprogressbar base-devel \ + qt6-base qt6-declarative cmake pkgconfig ninja clang make git \ + pixman wayland wayland-protocols wlr-protocols \ + libxcb libx11 libxkbcommon libdrm libinput seatd \ + libdisplay-info libliftoff lcms2 \ + mesa libglvnd vulkan-headers vulkan-icd-loader \ + glslang hwdata systemd \ + xcb-util-errors xcb-util-renderutil xcb-util-wm \ + xorg-xwayland + pacman -S --noconfirm --noprogressbar fakeroot meson sudo + + - name: Build and Install treeland-protocols + run: | + echo "Building treeland-protocols from source..." + git clone https://github.com/linuxdeepin/treeland-protocols.git --depth 1 + cd treeland-protocols + cmake -B build \ + -DCMAKE_INSTALL_PREFIX=/usr \ + -DCMAKE_BUILD_TYPE=Release + cmake --build build + cmake --install build + echo "✅ treeland-protocols built and installed from source" + + - uses: actions/checkout@v4 + + - name: Configure and Build waylib with ci preset + working-directory: waylib + run: | + echo "Working directory:" $PWD + rm -rf build + cmake --preset ci + cmake --build --preset ci + + - name: Run unit tests + working-directory: waylib + run: ctest --preset ci + + - name: Install waylib to staging directory + working-directory: waylib + run: | + echo "Installing waylib to staging directory..." + mkdir -p /tmp/waylib-install + DESTDIR=/tmp/waylib-install cmake --install build + echo "✅ waylib installed to staging directory" + + echo "Installed files:" + find /tmp/waylib-install -type f | head -20 + echo "Total files installed: $(find /tmp/waylib-install -type f | wc -l)" + + - name: Create waylib installation package + run: | + cd /tmp/waylib-install + + # Install zip if not available + pacman -S --noconfirm zip + + # Create package info + echo "Creating package info..." + cat > PACKAGE_INFO.txt << EOF + Package: waylib-archlinux-build + Version: $(date +%Y%m%d-%H%M%S) + Architecture: x86_64 + Built-on: Arch Linux + Built-with: vendored wlroots 0.19.3 + CMake-Config: vendored wlroots 0.19.3 via ../wlroots + + Installation Instructions: + 1. Extract this package to / + 2. Run: sudo ldconfig (if libraries are included) + 3. Ensure dependencies are installed on target system + + Files included in this package: + EOF + find . -type f | sort >> PACKAGE_INFO.txt + + # Create the zip package + zip -r /tmp/waylib-archlinux-$(date +%Y%m%d-%H%M%S).zip . + echo "✅ waylib installation package created" + + ls -la /tmp/waylib-archlinux-*.zip + + - name: Upload waylib ArchLinux build artifacts + uses: actions/upload-artifact@v4 + with: + name: waylib-archlinux-build + path: "/tmp/waylib-archlinux-*.zip" + if-no-files-found: error + retention-days: 30 diff --git a/.github/workflows/waylib-debian-build.yml b/.github/workflows/waylib-debian-build.yml new file mode 100644 index 0000000000..679b834e1e --- /dev/null +++ b/.github/workflows/waylib-debian-build.yml @@ -0,0 +1,61 @@ +name: Build waylib on Debian unstable (independent) + +on: + pull_request: + paths: + - 'waylib/**' + - 'wlroots/**' + - '3rdparty/wlroots/**' + - '.github/workflows/waylib-debian-build.yml' + +jobs: + container: + runs-on: ubuntu-latest + container: debian:unstable + steps: + - uses: actions/checkout@v4 + + - name: Build waylib deb package + working-directory: waylib + run: | + set -euxo pipefail + # Configure apt sources for unstable + echo "deb http://deb.debian.org/debian unstable main" > /etc/apt/sources.list + echo "deb http://deb.debian.org/debian sid main" >> /etc/apt/sources.list + + apt-get update + apt-get install -y devscripts equivs + + # Add deepin community repository to install wlr-protocols + echo "deb [trusted=yes] http://mirrors.kernel.org/deepin/beige/ crimson main commercial community" > /etc/apt/sources.list.d/deepin-community.list + apt-get update --allow-unauthenticated + apt-get install -y --allow-unauthenticated wlr-protocols + rm -f /etc/apt/sources.list.d/deepin-community.list + apt-get update + + # Build and install treeland-protocols locally (required build dependency) + echo "🔧 Building treeland-protocols from source" + WAYLIB_DIR="$PWD" + cd /tmp + if [ ! -d treeland-protocols ]; then + git clone --depth=1 --branch master --single-branch https://github.com/linuxdeepin/treeland-protocols.git + fi + cd treeland-protocols + mk-build-deps --install --remove --tool='apt-get -o Debug::pkgProblemResolver=yes --no-install-recommends --yes' debian/control + dpkg-buildpackage -uc -us -b + apt-get install -y ../*.deb || dpkg -i ../*.deb || apt-get -f install -y + cd "$WAYLIB_DIR" + + mk-build-deps --install --remove --tool='apt-get -o Debug::pkgProblemResolver=yes --no-install-recommends --yes' debian/control + + dpkg-buildpackage -uc -us -b + echo "✅ waylib deb package built successfully!" + ls -la ../*.deb + + - name: Upload waylib deb packages as artifacts + uses: actions/upload-artifact@v4 + with: + name: waylib-deb-packages + path: "*.deb" + if-no-files-found: error + retention-days: 30 diff --git a/.github/workflows/waylib-deepin-build.yml b/.github/workflows/waylib-deepin-build.yml new file mode 100644 index 0000000000..052e5a527f --- /dev/null +++ b/.github/workflows/waylib-deepin-build.yml @@ -0,0 +1,65 @@ +name: Build waylib on Deepin crimson (independent) + +on: + pull_request: + paths: + - 'waylib/**' + - 'wlroots/**' + - '3rdparty/wlroots/**' + - '.github/workflows/waylib-deepin-build.yml' + +jobs: + container: + runs-on: ubuntu-latest + container: linuxdeepin/deepin:crimson + steps: + - uses: actions/checkout@v4 + + - name: Install build dependencies + working-directory: waylib + run: | + set -euxo pipefail + echo "deb [trusted=yes] http://mirrors.kernel.org/deepin/beige/ crimson main commercial community" > /etc/apt/sources.list + echo "deb-src [trusted=yes] http://mirrors.kernel.org/deepin/beige/ crimson main commercial community" >> /etc/apt/sources.list + echo "deb [trusted=yes] https://ci.deepin.com/repo/deepin/deepin-community/stable/ crimson main commercial community" >> /etc/apt/sources.list + echo "deb-src [trusted=yes] https://ci.deepin.com/repo/deepin/deepin-community/stable/ crimson main commercial community" >> /etc/apt/sources.list + echo "deb [trusted=yes] https://ci.deepin.com/repo/deepin/deepin-community/testing/ unstable/crimson main commercial community" >> /etc/apt/sources.list + echo "deb-src [trusted=yes] https://ci.deepin.com/repo/deepin/deepin-community/testing/ unstable/crimson main commercial community" >> /etc/apt/sources.list + rm -rf /etc/apt/sources.list.d + + apt-get update + apt-get install -y devscripts equivs + + # Install wlr-protocols package directly (ignore auth for this one operation) + apt-get install -y --allow-unauthenticated wlr-protocols || true + + # Build and install treeland-protocols locally (required build dependency) + echo "🔧 Building treeland-protocols from source" + WAYLIB_DIR="$PWD" + cd /tmp + if [ ! -d treeland-protocols ]; then + git clone --depth=1 --branch master --single-branch https://github.com/linuxdeepin/treeland-protocols.git + fi + cd treeland-protocols + mk-build-deps --install --remove --tool='apt-get -o Debug::pkgProblemResolver=yes --no-install-recommends --yes' debian/control + dpkg-buildpackage -uc -us -b + apt-get install -y ../*.deb || dpkg -i ../*.deb || apt-get -f install -y + cd "$WAYLIB_DIR" + + mk-build-deps --install --remove --tool='apt-get -o Debug::pkgProblemResolver=yes --no-install-recommends --yes' debian/control + + - name: Build waylib deb package + working-directory: waylib + run: | + set -euxo pipefail + dpkg-buildpackage -uc -us -b + echo "✅ waylib deb package built successfully!" + ls -la ../*.deb + + - name: Upload waylib deb packages as artifacts + uses: actions/upload-artifact@v4 + with: + name: waylib-deepin-deb-packages + path: "*.deb" + if-no-files-found: error + retention-days: 30 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..842f3ff4d6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,87 @@ +.vscode/ +.cache/ +build*/ +.qtcreator/ + +*.user + +# Compiled Object files +*.slo +*.lo +*.o + +# Compiled Dynamic libraries +*.so +*.dylib + +# Compiled Static libraries +*.lai +*.la +*.a + +# nix +.direnv/ +result +result-* + +# clangd +compile_commands.json + +# executeable files +*.qm + +# cmake +CMakeLists.txt.user + +#ccls +.ccls-cache + +# qtcreator +*.autosave + +.qmlls.ini + +# dpkg-buildpackage +debian/.debhelper/ +debian/tmp/ +debian/treeland*/ +debian/debhelper-build-stamp +debian/files +debian/*.substvars +debian/*.debhelper.log +obj-*-linux-gnu/ + +# ai +.cursor/ +.codex/ +.claude/ +.commandcode/ +.specstory/ +.windsurf/ +.workbuddy/ +.trae/ +.zed/ +.kiro/ +.kilo/ +.kilocode/ +.pi/ +.qwen/ +.gemini/ +.opencode/ +.qoder/ +.dsh/ +CLAUDE.local.md + +# local temp & trash +.tmp/ +.Trash-0/ + +# git worktrees +.worktrees/ +.agents/worktrees/ + +# CTest run state +Testing/Temporary/ + +# codegraph index +.codegraph/ diff --git a/.tx/config b/.tx/config new file mode 100644 index 0000000000..31cdd9163d --- /dev/null +++ b/.tx/config @@ -0,0 +1,20 @@ +[main] +host = https://www.transifex.com + +[o:linuxdeepin:p:treeland:r:f56f82288bfe7a231b1be25f7b0cb008] +file_filter = translations/treeland..ts +source_file = translations/treeland.en_US.ts +source_lang = en_US +type = QT + +[o:linuxdeepin:p:treeland:r:b675317802ed042606e0660179b6b04f] +file_filter = src/plugins/lockscreen/translations/lockscreen..ts +source_file = src/plugins/lockscreen/translations/lockscreen.en_US.ts +source_lang = en_US +type = QT + +[o:linuxdeepin:p:treeland:r:7309e9da01b4b7fbf5c2ac9c2a2d23a6] +file_filter = src/plugins/multitaskview/translations/multitaskview..ts +source_file = src/plugins/multitaskview/translations/multitaskview.en_US.ts +source_lang = en_US +type = QT diff --git a/.tx/transifex.yaml b/.tx/transifex.yaml new file mode 100644 index 0000000000..2e79bbf34a --- /dev/null +++ b/.tx/transifex.yaml @@ -0,0 +1,18 @@ +filters: + - filter_type: file + source_file: translations/treeland.en_US.ts + file_format: QT + source_language: en_US + translation_files_expression: translations/treeland..ts + - filter_type: file + source_file: src/plugins/lockscreen/translations/lockscreen.en_US.ts + file_format: QT + source_language: en_US + translation_files_expression: src/plugins/lockscreen/translations/lockscreen..ts + - filter_type: file + source_file: src/plugins/multitaskview/translations/multitaskview.en_US.ts + file_format: QT + source_language: en_US + translation_files_expression: src/plugins/multitaskview/translations/multitaskview..ts +settings: + pr_branch_name: transifex_update_ diff --git a/3rdparty/wlroots/.builds/alpine.yml b/3rdparty/wlroots/.builds/alpine.yml new file mode 100644 index 0000000000..affd854117 --- /dev/null +++ b/3rdparty/wlroots/.builds/alpine.yml @@ -0,0 +1,57 @@ +image: alpine/edge +packages: + - eudev-dev + - glslang + - lcms2-dev + - libdisplay-info-dev + - libinput-dev + - libliftoff-dev + - libxkbcommon-dev + - mesa-dev + - meson + - pixman-dev + - vulkan-headers + - vulkan-loader-dev + - wayland-dev + - wayland-protocols + - xcb-util-image-dev + - xcb-util-renderutil-dev + - xcb-util-wm-dev + - xwayland-dev + - libseat-dev + - hwdata-dev + # for docs + - go + - zip +sources: + - https://gitlab.freedesktop.org/wlroots/wlroots.git +artifacts: + - public.zip +tasks: + - setup: | + cd wlroots + meson setup build --fatal-meson-warnings --default-library=both -Dauto_features=enabled -Dxcb-errors=disabled --buildtype=debugoptimized + - build: | + cd wlroots + ninja -C build + sudo ninja -C build install + - build-features-disabled: | + cd wlroots + meson setup build --reconfigure -Dauto_features=disabled + ninja -C build + - tinywl: | + cd wlroots/tinywl + make + - docs: | + go install 'codeberg.org/emersion/gyosu@latest' + include_dir="$(echo /usr/local/include/wlroots-*)" + ~/go/bin/gyosu \ + -DWLR_USE_UNSTABLE \ + $(pkg-config --cflags-only-I $(basename "$include_dir")) \ + -Iwlroots/build/protocol/ \ + -fexported-symbols='wlr_*' -fexported-symbols='WLR_*' \ + -ffile-prefix-map="$include_dir/"= \ + -fsite-name=wlroots \ + -o public \ + "$include_dir/wlr/" + zip -r ~/public.zip public/ diff --git a/3rdparty/wlroots/.builds/archlinux.yml b/3rdparty/wlroots/.builds/archlinux.yml new file mode 100644 index 0000000000..fae04ab31c --- /dev/null +++ b/3rdparty/wlroots/.builds/archlinux.yml @@ -0,0 +1,50 @@ +image: archlinux +packages: + - clang + - lcms2 + - libinput + - libdisplay-info + - libliftoff + - libxkbcommon + - mesa + - meson + - pixman + - wayland + - wayland-protocols + - xcb-util-errors + - xcb-util-image + - xcb-util-renderutil + - xcb-util-wm + - xorg-xwayland + - seatd + - vulkan-icd-loader + - vulkan-headers + - glslang + - hwdata +sources: + - https://gitlab.freedesktop.org/wlroots/wlroots.git +tasks: + - setup: | + cd wlroots + CC=gcc meson setup build-gcc --fatal-meson-warnings --default-library=both -Dauto_features=enabled --prefix /usr -Db_sanitize=address,undefined + CC=clang meson setup build-clang --fatal-meson-warnings -Dauto_features=enabled -Dc_std=c11 + - gcc: | + cd wlroots/build-gcc + ninja + sudo ninja install + cd ../tinywl + make + - clang: | + cd wlroots/build-clang + ninja + - smoke-test: | + cd wlroots/build-gcc/tinywl + sudo modprobe vkms + udevadm settle + card="/dev/dri/$(ls /sys/devices/faux/vkms/drm/ | grep ^card)" + export WLR_BACKENDS=drm + export WLR_RENDERER=pixman + export WLR_DRM_DEVICES="$card" + export UBSAN_OPTIONS=halt_on_error=1 + sudo chmod ugo+rw "$card" + sudo -E seatd-launch -- ./tinywl -s 'kill $PPID' || [ $? = 143 ] diff --git a/3rdparty/wlroots/.builds/freebsd.yml b/3rdparty/wlroots/.builds/freebsd.yml new file mode 100644 index 0000000000..a99e9c911e --- /dev/null +++ b/3rdparty/wlroots/.builds/freebsd.yml @@ -0,0 +1,37 @@ +image: freebsd/latest +packages: + - devel/evdev-proto + - devel/libudev-devd + - devel/meson # implies ninja + - devel/pkgconf + - graphics/glslang + - graphics/lcms2 + - graphics/libdrm + - graphics/libliftoff + - graphics/mesa-libs + - graphics/vulkan-headers + - graphics/vulkan-loader + - graphics/wayland + - graphics/wayland-protocols + - x11/libinput + - x11/libxcb + - x11/libxkbcommon + - x11/pixman + - x11/xcb-util-errors + - x11/xcb-util-renderutil + - x11/xcb-util-wm + - x11-servers/xwayland + - sysutils/libdisplay-info + - sysutils/seatd + - hwdata +sources: + - https://gitlab.freedesktop.org/wlroots/wlroots.git +tasks: + - wlroots: | + cd wlroots + meson setup build --fatal-meson-warnings -Dauto_features=enabled -Dallocators=gbm + ninja -C build + sudo ninja -C build install + - tinywl: | + cd wlroots/tinywl + make diff --git a/3rdparty/wlroots/.editorconfig b/3rdparty/wlroots/.editorconfig new file mode 100644 index 0000000000..7b0dfeb938 --- /dev/null +++ b/3rdparty/wlroots/.editorconfig @@ -0,0 +1,17 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = true +charset = utf-8 +trim_trailing_whitespace = true +indent_style = tab +indent_size = 4 +max_line_length = 100 + +[/.git/**] +max_line_length = unset + +[*.xml] +indent_style = space +indent_size = 2 diff --git a/3rdparty/wlroots/.gitignore b/3rdparty/wlroots/.gitignore new file mode 100644 index 0000000000..02cf3c0938 --- /dev/null +++ b/3rdparty/wlroots/.gitignore @@ -0,0 +1,2 @@ +/subprojects/* +!/subprojects/*.wrap diff --git a/3rdparty/wlroots/.gitlab-ci.yml b/3rdparty/wlroots/.gitlab-ci.yml new file mode 100644 index 0000000000..3b02ef16f4 --- /dev/null +++ b/3rdparty/wlroots/.gitlab-ci.yml @@ -0,0 +1,8 @@ +include: https://gitlab.freedesktop.org/emersion/dalligi/-/raw/master/templates/multi.yml +alpine: + extends: .dalligi + pages: true +archlinux: + extends: .dalligi +freebsd: + extends: .dalligi diff --git a/3rdparty/wlroots/.gitlab/issue_templates/Default.md b/3rdparty/wlroots/.gitlab/issue_templates/Default.md new file mode 100644 index 0000000000..68044e159a --- /dev/null +++ b/3rdparty/wlroots/.gitlab/issue_templates/Default.md @@ -0,0 +1,15 @@ + diff --git a/3rdparty/wlroots/.mailmap b/3rdparty/wlroots/.mailmap new file mode 100644 index 0000000000..42dca553ee --- /dev/null +++ b/3rdparty/wlroots/.mailmap @@ -0,0 +1,2 @@ +Isaac Freund +Kirill Primak diff --git a/3rdparty/wlroots/CONTRIBUTING.md b/3rdparty/wlroots/CONTRIBUTING.md new file mode 100644 index 0000000000..d9c49f7c23 --- /dev/null +++ b/3rdparty/wlroots/CONTRIBUTING.md @@ -0,0 +1,479 @@ +# Contributing to wlroots + +Contributing just involves sending a merge request. You will probably be more +successful with your contribution if you visit [#wlroots on Libera Chat] +upfront and discuss your plans. + +Note: rules are made to be broken. Adjust or ignore any/all of these as you see +fit, but be prepared to justify it to your peers. + +## Forking + +New GitLab accounts may not have the permission to fork repositories. You will +need to [file a user verification request] to get this permission. See the +[freedesktop wiki] for more details. + +The fork must be marked as public to allow CI to run. + +## Merge Requests + +If you already have your own merge request habits, feel free to use them. If you +don't, however, allow me to make a suggestion: feature branches pulled from +upstream. Try this: + +1. Fork wlroots +2. `git clone git@ssh.gitlab.freedesktop.org:/wlroots.git && cd wlroots` +3. `git remote add upstream https://gitlab.freedesktop.org/wlroots/wlroots.git` + +You only need to do this once. You're never going to use your fork's master +branch. Instead, when you start working on a feature, do this: + +1. `git fetch upstream` +2. `git checkout -b add-so-and-so-feature upstream/master` +3. Add and commit your changes +4. `git push -u origin add-so-and-so-feature` +5. Make a merge request from your feature branch + +When you submit your merge request, your commit log should do most of the talking +when it comes to describing your changes and their motivation. In addition to +this, your merge request's comments will ideally include a test plan that the +reviewers can use to (1) demonstrate the problem on master, if applicable and +(2) verify that the problem no longer exists with your changes applied (or that +your new features work correctly). Document all of the edge cases you're aware +of so we can adequately test them - then verify the test plan yourself before +submitting. + +## Commit Log + +Unlike many projects using GitHub and GitLab, wlroots has a [linear, "recipe" +style] history. This means that every commit should be small, digestible, +stand-alone, and functional. Rather than a purely chronological commit history +like this: + +``` +doc: final docs for view transforms +fix tests when disabled, redo broken doc formatting +better transformed-view iteration (thanks Hannah!) +try to catch more cases in tests +tests: add new spline test +fix compilation on splines +doc: notes on reticulating splines +compositor: add spline reticulation for view transforms +``` + +We aim to have a clean history which only reflects the final state, broken up +into functional groupings: + +``` +compositor: add spline reticulation for view transforms +compositor: new iterator for view transforms +tests: add view-transform correctness tests +doc: fix formatting for view transforms +``` + +This ensures that the final patch series only contains the final state, +without the changes and missteps taken along the development process. A linear +history eases reviewing, cherry-picking and reverting changes. + +If you aren't comfortable with manipulating the Git history, have a look at +[git-rebase.io]. + +## Commit Messages + +Please strive to write good commit messages. Here's some guidelines to follow: + +The first line should be limited to 50 characters and should be a sentence that +completes the thought [When applied, this commit will...] *"Implement +cmd_move"* or *"Improve performance of arrange_windows on ARM"* or similar. + +The subsequent lines should be separated from the subject line by a single +blank line, and include optional details. In this you can give justification +for the change, [reference issues], or explain some of the subtler +details of your patch. This is important because when someone finds a line of +code they don't understand later, they can use the `git blame` command to find +out what the author was thinking when they wrote it. It's also easier to review +your merge requests if they're separated into logical commits that have good +commit messages and justify themselves in the extended commit description. + +As a good rule of thumb, anything you might put into the merge request +description on GitLab is probably fair game for going into the extended commit +message as well. + +See [How to Write a Git Commit Message] for more details. + +## Code Review + +When your changes are submitted for review, one or more core committers will +look over them. Smaller changes might be merged with little fanfare, but larger +changes will typically see review from several people. Be prepared to receive +some feedback - you may be asked to make changes to your work. Our code review +process is: + +1. **Triage** the merge request. Do the commit messages make sense? Is a test + plan necessary and/or present? Add anyone as reviewers that you think should + be there (using the relevant GitLab feature, if you have the permissions, or + with an @mention if necessary). +2. **Review** the code. Look for code style violations, naming convention + violations, buffer overflows, memory leaks, logic errors, non-portable code + (including GNU-isms), etc. For significant changes to the public API, loop in + a couple more people for discussion. +3. **Execute** the test plan, if present. +4. **Merge** the merge request when all reviewers approve. +5. **File** follow-up tickets if appropriate. + +## Code of Conduct + +Note that as a project hosted on freedesktop.org, wlroots follows its +[Code of Conduct], based on the Contributor Covenant. Please conduct yourself +in a respectful and civilized manner when communicating with community members +on IRC and bug tracker. + +## Style Reference + +wlroots is written in C with a style similar to the [kernel style], but with a +few notable differences. + +Try to keep your code conforming to C11 and POSIX as much as possible, and do +not use GNU extensions. + +### Brackets + +Brackets always go on the same line, including in functions. +Always include brackets for if/while/for, even if it's a single statement. +```c +void function(void) { + if (condition1) { + do_thing1(); + } + + if (condition2) { + do_thing2(); + } else { + do_thing3(); + } +} +``` + +### Indentation + +Indentations are a single tab. + +For long lines that need to be broken, the continuation line should be indented +with an additional tab. +If the line being broken is opening a new block (functions, if, while, etc.), +the continuation line should be indented with two tabs, so they can't be +misread as being part of the block. +```c +really_long_function(argument1, argument2, ..., + argument3, argument4); + +if (condition1 && condition2 && ... + condition3 && condition4) { + do_thing(); +} +``` + +Try to break the line in the place which you think is the most appropriate. + +### Line Length + +Try to keep your lines under 100 columns, but you can break this rule if it +improves readability. Don't break lines indiscriminately, try to find nice +breaking points so your code is easy to read. + +### Names + +Global function and type names should be prefixed with `wlr_submodule_` (e.g. +`struct wlr_output`, `wlr_output_set_cursor`). For static functions and +types local to a file, the names chosen aren't as important. Local function +names shouldn't have a `wlr_` prefix. + +For include guards, use the header's filename relative to include. Uppercase +all of the characters, and replace any invalid characters with an underscore. + +### Construction/Destruction Functions + +Functions that are responsible for constructing objects should take one of the +two following forms: + +* `init`: for functions which accept a pointer to a pre-allocated object (e.g. +a member of a struct) and initialize it. Such functions must zero out the +memory before initializing it to avoid leaving unset fields. +* `create`: for functions which allocate the memory for an object, initialize +it, and return a pointer. Such functions should allocate the memory with +`calloc()` to avoid leaving unset fields. + +Likewise, functions that are responsible for destructing objects should take +one of the two following forms: + +* `finish`: for functions which accept a pointer to an object and deinitialize +it. If a finished object isn't destroyed but kept for future use, it must be +reinitialized to be used again. +* `destroy`: for functions which accept a pointer to an object, deinitialize +it, and free the memory. Such functions should always be able to accept a NULL +pointer. + +If the object has signals, the destructor function must assert that their +listener lists are empty. + +```c +void wlr_thing_init(struct wlr_thing *thing) { + *thing = (struct wlr_thing){ + // ... + }; + + wl_signal_init(&thing->events.destroy); + wl_signal_init(&thing->events.foo); +} + +void wlr_thing_finish(struct wlr_thing *thing) { + wl_signal_emit_mutable(&thing->events.destroy, NULL); + + assert(wl_list_empty(&thing->events.destroy.listener_list)); + assert(wl_list_empty(&thing->events.foo.listener_list)); +} +``` + +### Error Codes + +For functions not returning a value, they should return a (stdbool.h) bool to +indicate whether they succeeded or not. + +### Macros + +Try to keep the use of macros to a minimum, especially if a function can do the +job. If you do need to use them, try to keep them close to where they're being +used and `#undef` them after. + +### Documentation + +* Documentation comments for declarations start with `/**` and end with `*/`. +* Cross-reference other declarations by ending function names with `()`, and + writing `struct`, `union`, `enum` or `typedef` before types. +* Document fields which can be NULL with a `// may be NULL` comment, optionally + with more details describing when this can happen. +* Document the bits of a bitfield with a `// enum bar` comment. +* Document the `data` argument of a `struct wl_signal` with a `// struct foo` + comment. +* Document the contents and container of a `struct wl_list` with a + `// content.link` and `// container.list` comment. + +### Private fields + +Wrap private fields of public structures with `struct { … } WLR_PRIVATE`. This +ensures that compositor authors don't use them by accident. Within wlroots +`WLR_PRIVATE` is expanded to nothing, so private fields are accessed in the same +way as public ones. + +### Safety + +* Avoid string manipulation functions which don't take the size of the + destination buffer as input: for instance, prefer `snprintf` over `sprintf`. +* Avoid repeating type names in `sizeof()` where possible. For instance, prefer + `ptr = calloc(1, sizeof(*ptr))` over `ptr = calloc(1, sizeof(struct foo))`. +* Prefer `*ptr = (struct foo){0}` over `memset(ptr, 0, sizeof(*ptr))`. +* Prefer `*foo = *bar` over `memcpy(foo, bar, sizeof(*foo))`. + +### Example + +```c +struct wlr_backend *wlr_backend_autocreate(struct wl_display *display) { + struct wlr_backend *backend; + if (getenv("WAYLAND_DISPLAY") || getenv("_WAYLAND_DISPLAY")) { + backend = attempt_wl_backend(display); + if (backend) { + return backend; + } + } + + const char *x11_display = getenv("DISPLAY"); + if (x11_display) { + return wlr_x11_backend_create(display, x11_display); + } + + // Attempt DRM+libinput + + struct wlr_session *session = wlr_session_create(display); + if (!session) { + wlr_log(WLR_ERROR, "Failed to start a DRM session"); + return NULL; + } + + int gpu = wlr_session_find_gpu(session); + if (gpu == -1) { + wlr_log(WLR_ERROR, "Failed to open DRM device"); + goto error_session; + } + + backend = wlr_multi_backend_create(session); + if (!backend) { + goto error_gpu; + } + + struct wlr_backend *libinput = wlr_libinput_backend_create(display, session); + if (!libinput) { + goto error_multi; + } + + struct wlr_backend *drm = wlr_drm_backend_create(display, session, gpu); + if (!drm) { + goto error_libinput; + } + + wlr_multi_backend_add(backend, libinput); + wlr_multi_backend_add(backend, drm); + return backend; + +error_libinput: + wlr_backend_destroy(libinput); +error_multi: + wlr_backend_destroy(backend); +error_gpu: + wlr_session_close_file(session, gpu); +error_session: + wlr_session_destroy(session); + return NULL; +} +``` + +## Wayland protocol implementation + +Each protocol generally lives in a file with the same name, usually containing +at least one struct for each interface in the protocol. For instance, +`xdg_shell` lives in `types/wlr_xdg_shell.h` and has a `wlr_xdg_surface` struct. + +### Globals + +Global interfaces generally have public constructors and destructors. Their +struct has a field holding the `wl_global` itself, a destroy signal and a +`wl_display` destroy listener. Example: + +```c +struct wlr_compositor { + struct wl_global *global; + … + + struct { + struct wl_signal new_surface; + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; +``` + +When the destructor is called, it should emit the destroy signal, remove the +display destroy listener, destroy the `wl_global` and then destroy the struct. +The destructor can assume all clients and resources have been already +destroyed. + +### Resources + +Resources are the representation of Wayland objects on the compositor side. They +generally have an associated struct, called the _object struct_, stored in their +`user_data` field. + +Object structs can be retrieved from resources via `wl_resource_get_data`. To +prevent bad casts, a safe helper function checking the type of the resource is +used: + +```c +static const struct wl_surface_interface surface_impl; + +struct wlr_surface *wlr_surface_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_surface_interface, + &surface_impl)); + return wl_resource_get_user_data(resource); +} +``` + +If a pointer to a `wl_resource` is stored, a resource destroy handler needs to +be registered to clean it up. libwayland will automatically destroy resources +in an arbitrary order when a client is disconnected, the compositor must handle +this correctly. + +### Destroying resources + +Object structs should only be destroyed when their resource is destroyed, ie. +in the resource destroy handler (set with `wl_resource_set_implementation`). + +- If the object has a destructor request: the request handler should just call + `wl_resource_destroy` and do nothing else. The compositor must not destroy + resources on its own outside the destructor request handler. +- If the protocol specifies that an object is destroyed when an event is sent: + it's the only case where the compositor is allowed to send the event and then + call `wl_resource_destroy`. An example of this is `wl_callback`. + +### Inert resources + +Some resources can become inert in situations described in the protocol or when +the compositor decides to get rid of them. All requests made to inert resources +should be ignored, except the destructor. This is achieved by: + +1. When the resource becomes inert: destroy the object struct and call + `wl_resource_set_user_data(resource, NULL)`. Do not destroy the resource. +2. For each request made to a resource that can be inert: add a NULL check to + ignore the request if the resource is inert. +3. When the client calls the destructor request on the resource: call + `wl_resource_destroy(resource)` as usual. +4. When the resource is destroyed, if the resource isn't inert, destroy the + object struct. + +Example: + +```c +// Handles the destroy request +static void subsurface_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +// Handles a regular request +static void subsurface_set_position(struct wl_client *client, + struct wl_resource *resource, int32_t x, int32_t y) { + struct wlr_subsurface *subsurface = subsurface_from_resource(resource); + if (subsurface == NULL) { + return; + } + + … +} + +// Destroys the wlr_subsurface struct +static void subsurface_destroy(struct wlr_subsurface *subsurface) { + if (subsurface == NULL) { + return; + } + + … + + wl_resource_set_user_data(subsurface->resource, NULL); + free(subsurface); +} + +// Resource destroy listener +static void subsurface_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_subsurface *subsurface = subsurface_from_resource(resource); + subsurface_destroy(subsurface); +} + +// Makes the resource inert +static void subsurface_handle_surface_destroy(struct wl_listener *listener, + void *data) { + struct wlr_subsurface *subsurface = + wl_container_of(listener, subsurface, surface_destroy); + subsurface_destroy(subsurface); +} +``` + +[#wlroots on Libera Chat]: https://web.libera.chat/gamja/?channels=#wlroots +[file a user verification request]: https://gitlab.freedesktop.org/freedesktop/freedesktop/-/issues/new?issuable_template=User%20verification +[freedesktop wiki]: https://gitlab.freedesktop.org/freedesktop/freedesktop/-/wikis/home +[linear, "recipe" style]: https://www.bitsnbites.eu/git-history-work-log-vs-recipe/ +[git-rebase.io]: https://git-rebase.io/ +[reference issues]: https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically +[Code of Conduct]: https://www.freedesktop.org/wiki/CodeOfConduct/ +[How to Write a Git Commit Message]: https://chris.beams.io/posts/git-commit/ +[kernel style]: https://www.kernel.org/doc/Documentation/process/coding-style.rst diff --git a/3rdparty/wlroots/LICENSE b/3rdparty/wlroots/LICENSE new file mode 100644 index 0000000000..fe85581ca0 --- /dev/null +++ b/3rdparty/wlroots/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2017, 2018 Drew DeVault +Copyright (c) 2014 Jari Vetoniemi +Copyright (c) 2023 The wlroots contributors + +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. diff --git a/3rdparty/wlroots/README.md b/3rdparty/wlroots/README.md new file mode 100644 index 0000000000..603ee20c4a --- /dev/null +++ b/3rdparty/wlroots/README.md @@ -0,0 +1,87 @@ +# wlroots + +Pluggable, composable, unopinionated modules for building a [Wayland] +compositor; or about 60,000 lines of code you were going to write anyway. + +- wlroots provides backends that abstract the underlying display and input + hardware, including KMS/DRM, libinput, Wayland, X11, and headless backends, + plus any custom backends you choose to write, which can all be created or + destroyed at runtime and used in concert with each other. +- wlroots provides unopinionated, mostly standalone implementations of many + Wayland interfaces, both from wayland.xml and various protocol extensions. + We also promote the standardization of portable extensions across + many compositors. +- wlroots provides several powerful, standalone, and optional tools that + implement components common to many compositors, such as the arrangement of + outputs in physical space. +- wlroots provides an Xwayland abstraction that allows you to have excellent + Xwayland support without worrying about writing your own X11 window manager + on top of writing your compositor. +- wlroots provides a renderer abstraction that simple compositors can use to + avoid writing GL code directly, but which steps out of the way when your + needs demand custom rendering code. + +wlroots implements a huge variety of Wayland compositor features and implements +them *right*, so you can focus on the features that make your compositor +unique. By using wlroots, you get high performance, excellent hardware +compatibility, broad support for many wayland interfaces, and comfortable +development tools - or any subset of these features you like, because all of +them work independently of one another and freely compose with anything you want +to implement yourself. + +Check out our [wiki] to get started with wlroots. Join our IRC channel: +[#wlroots on Libera Chat]. + +A variety of [wrapper libraries] are available for using it with your favorite +programming language. + +## Building + +Install dependencies: + +* meson +* wayland +* wayland-protocols +* EGL and GLESv2 (optional, for the GLES2 renderer) +* Vulkan loader, headers and glslang (optional, for the Vulkan renderer) +* libdrm +* GBM (optional, for the GBM allocator) +* libinput (optional, for the libinput backend) +* xkbcommon +* udev (optional, for the session) +* pixman +* [libseat] (optional, for the session) +* [hwdata] (optional, for the DRM backend) +* [libdisplay-info] (optional, for the DRM backend) +* [libliftoff] (optional, for the DRM backend) + +If you choose to enable X11 support: + +* xwayland (build-time only, optional at runtime) +* libxcb +* libxcb-render-util +* libxcb-wm +* libxcb-errors (optional, for improved error reporting) + +Run these commands: + + meson setup build/ + ninja -C build/ + +Install like so: + + sudo ninja -C build/ install + +## Contributing + +See [CONTRIBUTING.md]. + +[Wayland]: https://wayland.freedesktop.org/ +[wiki]: https://gitlab.freedesktop.org/wlroots/wlroots/-/wikis/Getting-started +[#wlroots on Libera Chat]: https://web.libera.chat/gamja/?channels=#wlroots +[wrapper libraries]: https://gitlab.freedesktop.org/wlroots/wlroots/-/wikis/Projects-which-use-wlroots#wrapper-libraries +[libseat]: https://git.sr.ht/~kennylevinsen/seatd +[hwdata]: https://github.com/vcrhonek/hwdata +[libdisplay-info]: https://gitlab.freedesktop.org/emersion/libdisplay-info +[libliftoff]: https://gitlab.freedesktop.org/emersion/libliftoff +[CONTRIBUTING.md]: https://gitlab.freedesktop.org/wlroots/wlroots/-/blob/master/CONTRIBUTING.md diff --git a/3rdparty/wlroots/backend/backend.c b/3rdparty/wlroots/backend/backend.c new file mode 100644 index 0000000000..3d84aa636f --- /dev/null +++ b/3rdparty/wlroots/backend/backend.c @@ -0,0 +1,494 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_output.h" +#include "util/env.h" +#include "util/time.h" + +#if WLR_HAS_SESSION +#include +#endif + +#if WLR_HAS_DRM_BACKEND +#include +#include "backend/drm/monitor.h" +#endif + +#if WLR_HAS_LIBINPUT_BACKEND +#include +#endif + +#if WLR_HAS_X11_BACKEND +#include +#endif + +#define WAIT_SESSION_TIMEOUT 10000 // ms + +void wlr_backend_init(struct wlr_backend *backend, + const struct wlr_backend_impl *impl) { + *backend = (struct wlr_backend){ + .impl = impl, + }; + wl_signal_init(&backend->events.destroy); + wl_signal_init(&backend->events.new_input); + wl_signal_init(&backend->events.new_output); +} + +void wlr_backend_finish(struct wlr_backend *backend) { + wl_signal_emit_mutable(&backend->events.destroy, backend); + + assert(wl_list_empty(&backend->events.destroy.listener_list)); + assert(wl_list_empty(&backend->events.new_input.listener_list)); + assert(wl_list_empty(&backend->events.new_output.listener_list)); +} + +bool wlr_backend_start(struct wlr_backend *backend) { + if (backend->impl->start) { + return backend->impl->start(backend); + } + return true; +} + +void wlr_backend_destroy(struct wlr_backend *backend) { + if (!backend) { + return; + } + + if (backend->impl && backend->impl->destroy) { + backend->impl->destroy(backend); + } else { + free(backend); + } +} + +static struct wlr_session *session_create_and_wait(struct wl_event_loop *loop) { +#if WLR_HAS_SESSION + struct wlr_session *session = wlr_session_create(loop); + + if (!session) { + wlr_log(WLR_ERROR, "Failed to start a session"); + return NULL; + } + + if (!session->active) { + wlr_log(WLR_INFO, "Waiting for a session to become active"); + + int64_t started_at = get_current_time_msec(); + int64_t timeout = WAIT_SESSION_TIMEOUT; + + while (!session->active) { + int ret = wl_event_loop_dispatch(loop, (int)timeout); + if (ret < 0) { + wlr_log_errno(WLR_ERROR, "Failed to wait for session active: " + "wl_event_loop_dispatch failed"); + return NULL; + } + + int64_t now = get_current_time_msec(); + if (now >= started_at + WAIT_SESSION_TIMEOUT) { + break; + } + timeout = started_at + WAIT_SESSION_TIMEOUT - now; + } + + if (!session->active) { + wlr_log(WLR_ERROR, "Timeout waiting session to become active"); + return NULL; + } + } + + return session; +#else + wlr_log(WLR_ERROR, "Cannot create session: disabled at compile-time"); + return NULL; +#endif +} + +int wlr_backend_get_drm_fd(struct wlr_backend *backend) { + if (!backend->impl->get_drm_fd) { + return -1; + } + return backend->impl->get_drm_fd(backend); +} + +static size_t parse_outputs_env(const char *name) { + const char *outputs_str = getenv(name); + if (outputs_str == NULL) { + return 1; + } + + char *end; + int outputs = (int)strtol(outputs_str, &end, 10); + if (*end || outputs < 0) { + wlr_log(WLR_ERROR, "%s specified with invalid integer, ignoring", name); + return 1; + } + + return outputs; +} + +/** + * Helper to destroy the multi backend when one of its nested backends is + * destroyed. + */ +struct wlr_auto_backend_monitor { + struct wlr_backend *multi; + struct wlr_backend *primary; + + struct wl_listener multi_destroy; + struct wl_listener primary_destroy; +}; + +static void auto_backend_monitor_destroy(struct wlr_auto_backend_monitor *monitor) { + wl_list_remove(&monitor->multi_destroy.link); + wl_list_remove(&monitor->primary_destroy.link); + free(monitor); +} + +static void monitor_handle_multi_destroy(struct wl_listener *listener, void *data) { + struct wlr_auto_backend_monitor *monitor = wl_container_of(listener, monitor, multi_destroy); + auto_backend_monitor_destroy(monitor); +} + +static void monitor_handle_primary_destroy(struct wl_listener *listener, void *data) { + struct wlr_auto_backend_monitor *monitor = wl_container_of(listener, monitor, primary_destroy); + wlr_backend_destroy(monitor->multi); +} + +static struct wlr_auto_backend_monitor *auto_backend_monitor_create( + struct wlr_backend *multi, struct wlr_backend *primary) { + struct wlr_auto_backend_monitor *monitor = calloc(1, sizeof(*monitor)); + if (monitor == NULL) { + return NULL; + } + + monitor->multi = multi; + monitor->primary = primary; + + monitor->multi_destroy.notify = monitor_handle_multi_destroy; + wl_signal_add(&multi->events.destroy, &monitor->multi_destroy); + + monitor->primary_destroy.notify = monitor_handle_primary_destroy; + wl_signal_add(&primary->events.destroy, &monitor->primary_destroy); + + return monitor; +} + +static struct wlr_backend *attempt_wl_backend(struct wl_event_loop *loop) { + struct wlr_backend *backend = wlr_wl_backend_create(loop, NULL); + if (backend == NULL) { + return NULL; + } + + size_t outputs = parse_outputs_env("WLR_WL_OUTPUTS"); + for (size_t i = 0; i < outputs; ++i) { + wlr_wl_output_create(backend); + } + + return backend; +} + +static struct wlr_backend *attempt_x11_backend(struct wl_event_loop *loop, + const char *x11_display) { +#if WLR_HAS_X11_BACKEND + struct wlr_backend *backend = wlr_x11_backend_create(loop, x11_display); + if (backend == NULL) { + return NULL; + } + + size_t outputs = parse_outputs_env("WLR_X11_OUTPUTS"); + for (size_t i = 0; i < outputs; ++i) { + wlr_x11_output_create(backend); + } + + return backend; +#else + wlr_log(WLR_ERROR, "Cannot create X11 backend: disabled at compile-time"); + return NULL; +#endif +} + +static struct wlr_backend *attempt_headless_backend(struct wl_event_loop *loop) { + struct wlr_backend *backend = wlr_headless_backend_create(loop); + if (backend == NULL) { + return NULL; + } + + size_t outputs = parse_outputs_env("WLR_HEADLESS_OUTPUTS"); + for (size_t i = 0; i < outputs; ++i) { + wlr_headless_add_output(backend, 1280, 720); + } + + return backend; +} + +static struct wlr_backend *attempt_drm_backend(struct wlr_backend *backend, struct wlr_session *session) { +#if WLR_HAS_DRM_BACKEND + struct wlr_device *gpus[8]; + ssize_t num_gpus = wlr_session_find_gpus(session, 8, gpus); + if (num_gpus < 0) { + wlr_log(WLR_ERROR, "Failed to find GPUs"); + return NULL; + } + + if (num_gpus == 0) { + wlr_log(WLR_ERROR, "Found 0 GPUs, cannot create backend"); + return NULL; + } else { + wlr_log(WLR_INFO, "Found %zu GPUs", num_gpus); + } + + struct wlr_backend *primary_drm = NULL; + for (size_t i = 0; i < (size_t)num_gpus; ++i) { + struct wlr_backend *drm = wlr_drm_backend_create(session, gpus[i], primary_drm); + if (!drm) { + wlr_log(WLR_ERROR, "Failed to create DRM backend"); + continue; + } + + if (!primary_drm) { + primary_drm = drm; + } + + wlr_multi_backend_add(backend, drm); + } + if (!primary_drm) { + wlr_log(WLR_ERROR, "Could not successfully create backend on any GPU"); + return NULL; + } + + if (getenv("WLR_DRM_DEVICES") == NULL) { + drm_backend_monitor_create(backend, primary_drm, session); + } + + return primary_drm; +#else + wlr_log(WLR_ERROR, "Cannot create DRM backend: disabled at compile-time"); + return NULL; +#endif +} + +static struct wlr_backend *attempt_libinput_backend(struct wlr_session *session) { +#if WLR_HAS_LIBINPUT_BACKEND + return wlr_libinput_backend_create(session); +#else + wlr_log(WLR_ERROR, "Cannot create libinput backend: disabled at compile-time"); + return NULL; +#endif +} + +static bool attempt_backend_by_name(struct wl_event_loop *loop, + struct wlr_backend *multi, char *name, + struct wlr_session **session_ptr) { + struct wlr_backend *backend = NULL; + if (strcmp(name, "wayland") == 0) { + backend = attempt_wl_backend(loop); + } else if (strcmp(name, "x11") == 0) { + backend = attempt_x11_backend(loop, NULL); + } else if (strcmp(name, "headless") == 0) { + backend = attempt_headless_backend(loop); + } else if (strcmp(name, "drm") == 0 || strcmp(name, "libinput") == 0) { + // DRM and libinput need a session + if (*session_ptr == NULL) { + *session_ptr = session_create_and_wait(loop); + if (*session_ptr == NULL) { + wlr_log(WLR_ERROR, "failed to start a session"); + return false; + } + } + + if (strcmp(name, "libinput") == 0) { + backend = attempt_libinput_backend(*session_ptr); + } else { + // attempt_drm_backend() adds the multi drm backends itself + return attempt_drm_backend(multi, *session_ptr) != NULL; + } + } else { + wlr_log(WLR_ERROR, "unrecognized backend '%s'", name); + return false; + } + if (backend == NULL) { + return false; + } + + return wlr_multi_backend_add(multi, backend); +} + +struct wlr_backend *wlr_backend_autocreate(struct wl_event_loop *loop, + struct wlr_session **session_ptr) { + if (session_ptr != NULL) { + *session_ptr = NULL; + } + + struct wlr_session *session = NULL; + struct wlr_backend *multi = wlr_multi_backend_create(loop); + if (!multi) { + wlr_log(WLR_ERROR, "could not allocate multibackend"); + return NULL; + } + + char *names = getenv("WLR_BACKENDS"); + if (names) { + wlr_log(WLR_INFO, "Loading user-specified backends due to WLR_BACKENDS: %s", + names); + + names = strdup(names); + if (names == NULL) { + wlr_log(WLR_ERROR, "allocation failed"); + goto error; + } + + char *saveptr; + char *name = strtok_r(names, ",", &saveptr); + while (name != NULL) { + if (!attempt_backend_by_name(loop, multi, name, &session)) { + wlr_log(WLR_ERROR, "failed to add backend '%s'", name); + free(names); + goto error; + } + + name = strtok_r(NULL, ",", &saveptr); + } + + free(names); + goto success; + } + + if (getenv("WAYLAND_DISPLAY") || getenv("WAYLAND_SOCKET")) { + struct wlr_backend *wl_backend = attempt_wl_backend(loop); + if (!wl_backend) { + goto error; + } + wlr_multi_backend_add(multi, wl_backend); + + if (!auto_backend_monitor_create(multi, wl_backend)) { + goto error; + } + + goto success; + } + + const char *x11_display = getenv("DISPLAY"); + if (x11_display) { + struct wlr_backend *x11_backend = attempt_x11_backend(loop, x11_display); + if (!x11_backend) { + goto error; + } + wlr_multi_backend_add(multi, x11_backend); + + if (!auto_backend_monitor_create(multi, x11_backend)) { + goto error; + } + + goto success; + } + + // Attempt DRM+libinput + session = session_create_and_wait(loop); + if (!session) { + wlr_log(WLR_ERROR, "Failed to start a DRM session"); + goto error; + } + + struct wlr_backend *libinput = attempt_libinput_backend(session); + if (libinput) { + wlr_multi_backend_add(multi, libinput); + if (!auto_backend_monitor_create(multi, libinput)) { + goto error; + } + } else if (env_parse_bool("WLR_LIBINPUT_NO_DEVICES")) { + wlr_log(WLR_INFO, "WLR_LIBINPUT_NO_DEVICES is set, " + "starting without libinput backend"); + } else { + wlr_log(WLR_ERROR, "Failed to start libinput backend"); + wlr_log(WLR_ERROR, "Set WLR_LIBINPUT_NO_DEVICES=1 to skip libinput"); + goto error; + } + + struct wlr_backend *primary_drm = attempt_drm_backend(multi, session); + if (primary_drm == NULL) { + wlr_log(WLR_ERROR, "Failed to open any DRM device"); + goto error; + } + + if (!auto_backend_monitor_create(multi, primary_drm)) { + goto error; + } + +success: + if (session_ptr != NULL) { + *session_ptr = session; + } + return multi; + +error: + wlr_backend_destroy(multi); +#if WLR_HAS_SESSION + wlr_session_destroy(session); +#endif + return NULL; +} + +bool wlr_backend_test(struct wlr_backend *backend, + const struct wlr_backend_output_state *states, size_t states_len) { + if (backend->impl->test) { + return backend->impl->test(backend, states, states_len); + } + + for (size_t i = 0; i < states_len; i++) { + const struct wlr_backend_output_state *state = &states[i]; + assert(state->output->backend == backend); + if (!wlr_output_test_state(states[i].output, &state->base)) { + return false; + } + } + + return true; +} + +bool wlr_backend_commit(struct wlr_backend *backend, + const struct wlr_backend_output_state *states, size_t states_len) { + if (!backend->impl->commit) { + for (size_t i = 0; i < states_len; i++) { + const struct wlr_backend_output_state *state = &states[i]; + if (!wlr_output_commit_state(state->output, &state->base)) { + return false; + } + } + + return true; + } + + for (size_t i = 0; i < states_len; i++) { + const struct wlr_backend_output_state *state = &states[i]; + if (!output_prepare_commit(state->output, &state->base)) { + return false; + } + } + + if (!backend->impl->commit(backend, states, states_len)) { + return false; + } + + for (size_t i = 0; i < states_len; i++) { + const struct wlr_backend_output_state *state = &states[i]; + output_apply_commit(state->output, &state->base); + } + + for (size_t i = 0; i < states_len; i++) { + const struct wlr_backend_output_state *state = &states[i]; + output_send_commit_event(state->output, &state->base); + } + + return true; +} diff --git a/3rdparty/wlroots/backend/drm/atomic.c b/3rdparty/wlroots/backend/drm/atomic.c new file mode 100644 index 0000000000..faa535d443 --- /dev/null +++ b/3rdparty/wlroots/backend/drm/atomic.c @@ -0,0 +1,615 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "backend/drm/drm.h" +#include "backend/drm/fb.h" +#include "backend/drm/iface.h" +#include "backend/drm/util.h" +#include "render/color.h" + +static char *atomic_commit_flags_str(uint32_t flags) { + const char *const l[] = { + (flags & DRM_MODE_PAGE_FLIP_EVENT) ? "PAGE_FLIP_EVENT" : NULL, + (flags & DRM_MODE_PAGE_FLIP_ASYNC) ? "PAGE_FLIP_ASYNC" : NULL, + (flags & DRM_MODE_ATOMIC_TEST_ONLY) ? "ATOMIC_TEST_ONLY" : NULL, + (flags & DRM_MODE_ATOMIC_NONBLOCK) ? "ATOMIC_NONBLOCK" : NULL, + (flags & DRM_MODE_ATOMIC_ALLOW_MODESET) ? "ATOMIC_ALLOW_MODESET" : NULL, + }; + + char *buf = NULL; + size_t size = 0; + FILE *f = open_memstream(&buf, &size); + if (f == NULL) { + return NULL; + } + + for (size_t i = 0; i < sizeof(l) / sizeof(l[0]); i++) { + if (l[i] == NULL) { + continue; + } + if (ftell(f) > 0) { + fprintf(f, " | "); + } + fprintf(f, "%s", l[i]); + } + + if (ftell(f) == 0) { + fprintf(f, "none"); + } + + fclose(f); + + return buf; +} + +struct atomic { + drmModeAtomicReq *req; + bool failed; +}; + +static void atomic_begin(struct atomic *atom) { + *atom = (struct atomic){0}; + + atom->req = drmModeAtomicAlloc(); + if (!atom->req) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + atom->failed = true; + return; + } +} + +static bool atomic_commit(struct atomic *atom, struct wlr_drm_backend *drm, + const struct wlr_drm_device_state *state, + struct wlr_drm_page_flip *page_flip, uint32_t flags) { + if (atom->failed) { + return false; + } + + int ret = drmModeAtomicCommit(drm->fd, atom->req, flags, page_flip); + if (ret != 0) { + enum wlr_log_importance log_level = WLR_ERROR; + if (flags & DRM_MODE_ATOMIC_TEST_ONLY) { + log_level = WLR_DEBUG; + } + + if (state->connectors_len == 1) { + struct wlr_drm_connector *conn = state->connectors[0].connector; + wlr_drm_conn_log_errno(conn, log_level, "Atomic commit failed"); + } else { + wlr_log_errno(log_level, "Atomic commit failed"); + } + char *flags_str = atomic_commit_flags_str(flags); + wlr_log(WLR_DEBUG, "(Atomic commit flags: %s)", + flags_str ? flags_str : ""); + free(flags_str); + return false; + } + + return true; +} + +static void atomic_finish(struct atomic *atom) { + drmModeAtomicFree(atom->req); +} + +static void atomic_add(struct atomic *atom, uint32_t id, uint32_t prop, uint64_t val) { + if (!atom->failed && drmModeAtomicAddProperty(atom->req, id, prop, val) < 0) { + wlr_log_errno(WLR_ERROR, "Failed to add atomic DRM property"); + atom->failed = true; + } +} + +static bool create_mode_blob(struct wlr_drm_connector *conn, + const struct wlr_drm_connector_state *state, uint32_t *blob_id) { + if (!state->active) { + *blob_id = 0; + return true; + } + + if (drmModeCreatePropertyBlob(conn->backend->fd, &state->mode, + sizeof(drmModeModeInfo), blob_id)) { + wlr_log_errno(WLR_ERROR, "Unable to create mode property blob"); + return false; + } + + return true; +} + +static bool create_gamma_lut_blob(struct wlr_drm_backend *drm, + size_t size, const uint16_t *lut, uint32_t *blob_id) { + if (size == 0) { + *blob_id = 0; + return true; + } + + struct drm_color_lut *gamma = malloc(size * sizeof(*gamma)); + if (gamma == NULL) { + wlr_log(WLR_ERROR, "Failed to allocate gamma table"); + return false; + } + + const uint16_t *r = lut; + const uint16_t *g = lut + size; + const uint16_t *b = lut + 2 * size; + for (size_t i = 0; i < size; i++) { + gamma[i].red = r[i]; + gamma[i].green = g[i]; + gamma[i].blue = b[i]; + } + + if (drmModeCreatePropertyBlob(drm->fd, gamma, + size * sizeof(*gamma), blob_id) != 0) { + wlr_log_errno(WLR_ERROR, "Unable to create gamma LUT property blob"); + free(gamma); + return false; + } + free(gamma); + + return true; +} + +bool create_fb_damage_clips_blob(struct wlr_drm_backend *drm, + int width, int height, const pixman_region32_t *damage, uint32_t *blob_id) { + pixman_region32_t clipped; + pixman_region32_init(&clipped); + pixman_region32_intersect_rect(&clipped, damage, 0, 0, width, height); + + int rects_len; + const pixman_box32_t *rects = pixman_region32_rectangles(&clipped, &rects_len); + + int ret; + if (rects_len > 0) { + ret = drmModeCreatePropertyBlob(drm->fd, rects, sizeof(*rects) * rects_len, blob_id); + } else { + ret = 0; + *blob_id = 0; + } + pixman_region32_fini(&clipped); + if (ret != 0) { + wlr_log_errno(WLR_ERROR, "Failed to create FB_DAMAGE_CLIPS property blob"); + return false; + } + + return true; +} + +static uint8_t convert_cta861_eotf(enum wlr_color_transfer_function tf) { + switch (tf) { + case WLR_COLOR_TRANSFER_FUNCTION_SRGB: + abort(); // unsupported + case WLR_COLOR_TRANSFER_FUNCTION_ST2084_PQ: + return 2; + case WLR_COLOR_TRANSFER_FUNCTION_EXT_LINEAR: + abort(); // unsupported + case WLR_COLOR_TRANSFER_FUNCTION_GAMMA22: + abort(); // unsupported + case WLR_COLOR_TRANSFER_FUNCTION_BT1886: + abort(); // unsupported + } + abort(); // unreachable +} + +static uint16_t convert_cta861_color_coord(double v) { + if (v < 0) { + v = 0; + } + if (v > 1) { + v = 1; + } + return (uint16_t)round(v * 50000); +} + +static bool create_hdr_output_metadata_blob(struct wlr_drm_backend *drm, + const struct wlr_output_image_description *img_desc, uint32_t *blob_id) { + if (img_desc == NULL) { + *blob_id = 0; + return true; + } + + struct hdr_output_metadata metadata = { + .metadata_type = 0, + .hdmi_metadata_type1 = { + .eotf = convert_cta861_eotf(img_desc->transfer_function), + .metadata_type = 0, + .display_primaries = { + { + .x = convert_cta861_color_coord(img_desc->mastering_display_primaries.red.x), + .y = convert_cta861_color_coord(img_desc->mastering_display_primaries.red.y), + }, + { + .x = convert_cta861_color_coord(img_desc->mastering_display_primaries.green.x), + .y = convert_cta861_color_coord(img_desc->mastering_display_primaries.green.y), + }, + { + .x = convert_cta861_color_coord(img_desc->mastering_display_primaries.blue.x), + .y = convert_cta861_color_coord(img_desc->mastering_display_primaries.blue.y), + }, + }, + .white_point = { + .x = convert_cta861_color_coord(img_desc->mastering_display_primaries.white.x), + .y = convert_cta861_color_coord(img_desc->mastering_display_primaries.white.y), + }, + .max_display_mastering_luminance = img_desc->mastering_luminance.max, + .min_display_mastering_luminance = img_desc->mastering_luminance.min * 0.0001, + .max_cll = img_desc->max_cll, + .max_fall = img_desc->max_fall, + }, + }; + if (drmModeCreatePropertyBlob(drm->fd, &metadata, sizeof(metadata), blob_id) != 0) { + wlr_log_errno(WLR_ERROR, "Failed to create HDR_OUTPUT_METADATA property"); + return false; + } + return true; +} + +static uint64_t convert_primaries_to_colorspace(uint32_t primaries) { + switch (primaries) { + case 0: + return 0; // Default + case WLR_COLOR_NAMED_PRIMARIES_BT2020: + return 9; // BT2020_RGB + } + abort(); // unreachable +} + +static uint64_t max_bpc_for_format(uint32_t format) { + switch (format) { + case DRM_FORMAT_XRGB2101010: + case DRM_FORMAT_ARGB2101010: + case DRM_FORMAT_XBGR2101010: + case DRM_FORMAT_ABGR2101010: + return 10; + case DRM_FORMAT_XBGR16161616F: + case DRM_FORMAT_ABGR16161616F: + case DRM_FORMAT_XBGR16161616: + case DRM_FORMAT_ABGR16161616: + return 16; + default: + return 8; + } +} + +static uint64_t pick_max_bpc(struct wlr_drm_connector *conn, struct wlr_drm_fb *fb) { + uint32_t format = DRM_FORMAT_INVALID; + struct wlr_dmabuf_attributes attribs = {0}; + if (wlr_buffer_get_dmabuf(fb->wlr_buf, &attribs)) { + format = attribs.format; + } + + uint64_t target_bpc = max_bpc_for_format(format); + if (target_bpc < conn->max_bpc_bounds[0]) { + target_bpc = conn->max_bpc_bounds[0]; + } + if (target_bpc > conn->max_bpc_bounds[1]) { + target_bpc = conn->max_bpc_bounds[1]; + } + return target_bpc; +} + +static void destroy_blob(struct wlr_drm_backend *drm, uint32_t id) { + if (id == 0) { + return; + } + if (drmModeDestroyPropertyBlob(drm->fd, id) != 0) { + wlr_log_errno(WLR_ERROR, "Failed to destroy blob"); + } +} + +static void commit_blob(struct wlr_drm_backend *drm, + uint32_t *current, uint32_t next) { + if (*current == next) { + return; + } + destroy_blob(drm, *current); + *current = next; +} + +static void rollback_blob(struct wlr_drm_backend *drm, + uint32_t *current, uint32_t next) { + if (*current == next) { + return; + } + destroy_blob(drm, next); +} + +bool drm_atomic_connector_prepare(struct wlr_drm_connector_state *state, bool modeset) { + struct wlr_drm_connector *conn = state->connector; + struct wlr_drm_backend *drm = conn->backend; + struct wlr_output *output = &conn->output; + struct wlr_drm_crtc *crtc = conn->crtc; + + uint32_t mode_id = crtc->mode_id; + if (modeset) { + if (!create_mode_blob(conn, state, &mode_id)) { + return false; + } + } + + uint32_t gamma_lut = crtc->gamma_lut; + if (state->base->committed & WLR_OUTPUT_STATE_COLOR_TRANSFORM) { + size_t dim = 0; + uint16_t *lut = NULL; + if (state->base->color_transform != NULL) { + struct wlr_color_transform_lut_3x1d *tr = + color_transform_lut_3x1d_from_base(state->base->color_transform); + dim = tr->dim; + lut = tr->lut_3x1d; + } + + // Fallback to legacy gamma interface when gamma properties are not + // available (can happen on older Intel GPUs that support gamma but not + // degamma). + if (crtc->props.gamma_lut == 0) { + if (!drm_legacy_crtc_set_gamma(drm, crtc, dim, lut)) { + return false; + } + } else { + if (!create_gamma_lut_blob(drm, dim, lut, &gamma_lut)) { + return false; + } + } + } + + uint32_t fb_damage_clips = 0; + if ((state->base->committed & WLR_OUTPUT_STATE_DAMAGE) && + crtc->primary->props.fb_damage_clips != 0) { + create_fb_damage_clips_blob(drm, state->primary_fb->wlr_buf->width, + state->primary_fb->wlr_buf->height, &state->base->damage, &fb_damage_clips); + } + + int in_fence_fd = -1; + if (state->wait_timeline != NULL) { + in_fence_fd = wlr_drm_syncobj_timeline_export_sync_file(state->wait_timeline, + state->wait_point); + if (in_fence_fd < 0) { + return false; + } + } + + bool prev_vrr_enabled = + output->adaptive_sync_status == WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED; + bool vrr_enabled = prev_vrr_enabled; + if ((state->base->committed & WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED)) { + if (state->base->adaptive_sync_enabled && !output->adaptive_sync_supported) { + return false; + } + vrr_enabled = state->base->adaptive_sync_enabled; + } + + uint32_t colorspace = conn->colorspace; + if (state->base->committed & WLR_OUTPUT_STATE_IMAGE_DESCRIPTION) { + colorspace = convert_primaries_to_colorspace( + state->base->image_description ? state->base->image_description->primaries : 0); + } + + uint32_t hdr_output_metadata = conn->hdr_output_metadata; + if ((state->base->committed & WLR_OUTPUT_STATE_IMAGE_DESCRIPTION) && + !create_hdr_output_metadata_blob(drm, state->base->image_description, &hdr_output_metadata)) { + return false; + } + + state->mode_id = mode_id; + state->gamma_lut = gamma_lut; + state->fb_damage_clips = fb_damage_clips; + state->primary_in_fence_fd = in_fence_fd; + state->vrr_enabled = vrr_enabled; + state->colorspace = colorspace; + state->hdr_output_metadata = hdr_output_metadata; + return true; +} + +void drm_atomic_connector_apply_commit(struct wlr_drm_connector_state *state) { + struct wlr_drm_connector *conn = state->connector; + struct wlr_drm_crtc *crtc = conn->crtc; + struct wlr_drm_backend *drm = conn->backend; + + if (!crtc->own_mode_id) { + crtc->mode_id = 0; // don't try to delete previous master's blobs + } + crtc->own_mode_id = true; + commit_blob(drm, &crtc->mode_id, state->mode_id); + commit_blob(drm, &crtc->gamma_lut, state->gamma_lut); + commit_blob(drm, &conn->hdr_output_metadata, state->hdr_output_metadata); + + conn->output.adaptive_sync_status = state->vrr_enabled ? + WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED : WLR_OUTPUT_ADAPTIVE_SYNC_DISABLED; + + destroy_blob(drm, state->fb_damage_clips); + if (state->primary_in_fence_fd >= 0) { + close(state->primary_in_fence_fd); + } + + conn->colorspace = state->colorspace; +} + +void drm_atomic_connector_rollback_commit(struct wlr_drm_connector_state *state) { + struct wlr_drm_connector *conn = state->connector; + struct wlr_drm_crtc *crtc = conn->crtc; + struct wlr_drm_backend *drm = conn->backend; + + rollback_blob(drm, &crtc->mode_id, state->mode_id); + rollback_blob(drm, &crtc->gamma_lut, state->gamma_lut); + rollback_blob(drm, &conn->hdr_output_metadata, state->hdr_output_metadata); + + destroy_blob(drm, state->fb_damage_clips); + if (state->primary_in_fence_fd >= 0) { + close(state->primary_in_fence_fd); + } +} + +static void plane_disable(struct atomic *atom, struct wlr_drm_plane *plane) { + uint32_t id = plane->id; + const struct wlr_drm_plane_props *props = &plane->props; + atomic_add(atom, id, props->fb_id, 0); + atomic_add(atom, id, props->crtc_id, 0); +} + +static void set_plane_props(struct atomic *atom, struct wlr_drm_backend *drm, + struct wlr_drm_plane *plane, struct wlr_drm_fb *fb, uint32_t crtc_id, + const struct wlr_box *dst_box, + const struct wlr_fbox *src_box) { + uint32_t id = plane->id; + const struct wlr_drm_plane_props *props = &plane->props; + + if (fb == NULL) { + wlr_log(WLR_ERROR, "Failed to acquire FB for plane %"PRIu32, plane->id); + atom->failed = true; + return; + } + + // The src_* properties are in 16.16 fixed point + atomic_add(atom, id, props->src_x, src_box->x * (1 << 16)); + atomic_add(atom, id, props->src_y, src_box->y * (1 << 16)); + atomic_add(atom, id, props->src_w, src_box->width * (1 << 16)); + atomic_add(atom, id, props->src_h, src_box->height * (1 << 16)); + atomic_add(atom, id, props->fb_id, fb->id); + atomic_add(atom, id, props->crtc_id, crtc_id); + atomic_add(atom, id, props->crtc_x, dst_box->x); + atomic_add(atom, id, props->crtc_y, dst_box->y); + atomic_add(atom, id, props->crtc_w, dst_box->width); + atomic_add(atom, id, props->crtc_h, dst_box->height); +} + +static bool supports_cursor_hotspots(const struct wlr_drm_plane *plane) { + return plane->props.hotspot_x && plane->props.hotspot_y; +} + +static void set_plane_in_fence_fd(struct atomic *atom, + struct wlr_drm_plane *plane, int sync_file_fd) { + if (!plane->props.in_fence_fd) { + wlr_log(WLR_ERROR, "Plane %"PRIu32 " is missing the IN_FENCE_FD property", + plane->id); + atom->failed = true; + return; + } + + atomic_add(atom, plane->id, plane->props.in_fence_fd, sync_file_fd); +} + +static void atomic_connector_add(struct atomic *atom, + struct wlr_drm_connector_state *state, bool modeset) { + struct wlr_drm_connector *conn = state->connector; + struct wlr_drm_backend *drm = conn->backend; + struct wlr_drm_crtc *crtc = conn->crtc; + bool active = state->active; + + atomic_add(atom, conn->id, conn->props.crtc_id, active ? crtc->id : 0); + if (modeset && active && conn->props.link_status != 0) { + atomic_add(atom, conn->id, conn->props.link_status, + DRM_MODE_LINK_STATUS_GOOD); + } + if (active && conn->props.content_type != 0) { + atomic_add(atom, conn->id, conn->props.content_type, + DRM_MODE_CONTENT_TYPE_GRAPHICS); + } + if (modeset && active && conn->props.max_bpc != 0 && conn->max_bpc_bounds[1] != 0) { + atomic_add(atom, conn->id, conn->props.max_bpc, pick_max_bpc(conn, state->primary_fb)); + } + if (conn->props.colorspace != 0) { + atomic_add(atom, conn->id, conn->props.colorspace, state->colorspace); + } + if (conn->props.hdr_output_metadata != 0) { + atomic_add(atom, conn->id, conn->props.hdr_output_metadata, state->hdr_output_metadata); + } + atomic_add(atom, crtc->id, crtc->props.mode_id, state->mode_id); + atomic_add(atom, crtc->id, crtc->props.active, active); + if (active) { + if (crtc->props.gamma_lut != 0) { + atomic_add(atom, crtc->id, crtc->props.gamma_lut, state->gamma_lut); + } + if (crtc->props.vrr_enabled != 0) { + atomic_add(atom, crtc->id, crtc->props.vrr_enabled, state->vrr_enabled); + } + + set_plane_props(atom, drm, crtc->primary, state->primary_fb, crtc->id, + &state->primary_viewport.dst_box, &state->primary_viewport.src_box); + if (crtc->primary->props.fb_damage_clips != 0) { + atomic_add(atom, crtc->primary->id, + crtc->primary->props.fb_damage_clips, state->fb_damage_clips); + } + if (state->primary_in_fence_fd >= 0) { + set_plane_in_fence_fd(atom, crtc->primary, state->primary_in_fence_fd); + } + if (crtc->cursor) { + if (drm_connector_is_cursor_visible(conn)) { + struct wlr_fbox cursor_src = { + .width = state->cursor_fb->wlr_buf->width, + .height = state->cursor_fb->wlr_buf->height, + }; + struct wlr_box cursor_dst = { + .x = conn->cursor_x, + .y = conn->cursor_y, + .width = state->cursor_fb->wlr_buf->width, + .height = state->cursor_fb->wlr_buf->height, + }; + set_plane_props(atom, drm, crtc->cursor, state->cursor_fb, + crtc->id, &cursor_dst, &cursor_src); + if (supports_cursor_hotspots(crtc->cursor)) { + atomic_add(atom, crtc->cursor->id, + crtc->cursor->props.hotspot_x, conn->cursor_hotspot_x); + atomic_add(atom, crtc->cursor->id, + crtc->cursor->props.hotspot_y, conn->cursor_hotspot_y); + } + } else { + plane_disable(atom, crtc->cursor); + } + } + } else { + plane_disable(atom, crtc->primary); + if (crtc->cursor) { + plane_disable(atom, crtc->cursor); + } + } +} + +static bool atomic_device_commit(struct wlr_drm_backend *drm, + const struct wlr_drm_device_state *state, + struct wlr_drm_page_flip *page_flip, uint32_t flags, bool test_only) { + bool ok = false; + + for (size_t i = 0; i < state->connectors_len; i++) { + if (!drm_atomic_connector_prepare(&state->connectors[i], state->modeset)) { + goto out; + } + } + + struct atomic atom; + atomic_begin(&atom); + + for (size_t i = 0; i < state->connectors_len; i++) { + atomic_connector_add(&atom, &state->connectors[i], state->modeset); + } + + if (test_only) { + flags |= DRM_MODE_ATOMIC_TEST_ONLY; + } + if (state->modeset) { + flags |= DRM_MODE_ATOMIC_ALLOW_MODESET; + } + if (state->nonblock) { + flags |= DRM_MODE_ATOMIC_NONBLOCK; + } + + ok = atomic_commit(&atom, drm, state, page_flip, flags); + atomic_finish(&atom); + +out: + for (size_t i = 0; i < state->connectors_len; i++) { + struct wlr_drm_connector_state *conn_state = &state->connectors[i]; + if (ok && !test_only) { + drm_atomic_connector_apply_commit(conn_state); + } else { + drm_atomic_connector_rollback_commit(conn_state); + } + } + return ok; +} + +const struct wlr_drm_interface atomic_iface = { + .commit = atomic_device_commit, +}; diff --git a/3rdparty/wlroots/backend/drm/backend.c b/3rdparty/wlroots/backend/drm/backend.c new file mode 100644 index 0000000000..5a545b1927 --- /dev/null +++ b/3rdparty/wlroots/backend/drm/backend.c @@ -0,0 +1,302 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "backend/drm/drm.h" +#include "backend/drm/fb.h" +#include "render/drm_format_set.h" + +struct wlr_drm_backend *get_drm_backend_from_backend( + struct wlr_backend *wlr_backend) { + assert(wlr_backend_is_drm(wlr_backend)); + struct wlr_drm_backend *backend = wl_container_of(wlr_backend, backend, backend); + return backend; +} + +static bool backend_start(struct wlr_backend *backend) { + struct wlr_drm_backend *drm = get_drm_backend_from_backend(backend); + scan_drm_connectors(drm, NULL); + return true; +} + +static void backend_destroy(struct wlr_backend *backend) { + if (!backend) { + return; + } + + struct wlr_drm_backend *drm = get_drm_backend_from_backend(backend); + + struct wlr_drm_connector *conn, *next; + wl_list_for_each_safe(conn, next, &drm->connectors, link) { + conn->crtc = NULL; // leave CRTCs on when shutting down + destroy_drm_connector(conn); + } + + struct wlr_drm_page_flip *page_flip, *page_flip_tmp; + wl_list_for_each_safe(page_flip, page_flip_tmp, &drm->page_flips, link) { + drm_page_flip_destroy(page_flip); + } + + wlr_backend_finish(backend); + + wl_list_remove(&drm->session_destroy.link); + wl_list_remove(&drm->session_active.link); + wl_list_remove(&drm->parent_destroy.link); + wl_list_remove(&drm->dev_change.link); + wl_list_remove(&drm->dev_remove.link); + + if (drm->mgpu_renderer.wlr_rend) { + wlr_drm_format_set_finish(&drm->mgpu_formats); + finish_drm_renderer(&drm->mgpu_renderer); + } + + finish_drm_resources(drm); + + struct wlr_drm_fb *fb, *fb_tmp; + wl_list_for_each_safe(fb, fb_tmp, &drm->fbs, link) { + drm_fb_destroy(fb); + } + + free(drm->name); + wlr_session_close_file(drm->session, drm->dev); + wl_event_source_remove(drm->drm_event); + free(drm); +} + +static int backend_get_drm_fd(struct wlr_backend *backend) { + struct wlr_drm_backend *drm = get_drm_backend_from_backend(backend); + return drm->fd; +} + +static bool backend_test(struct wlr_backend *backend, + const struct wlr_backend_output_state *states, size_t states_len) { + struct wlr_drm_backend *drm = get_drm_backend_from_backend(backend); + return commit_drm_device(drm, states, states_len, true); +} + +static bool backend_commit(struct wlr_backend *backend, + const struct wlr_backend_output_state *states, size_t states_len) { + struct wlr_drm_backend *drm = get_drm_backend_from_backend(backend); + return commit_drm_device(drm, states, states_len, false); +} + +static const struct wlr_backend_impl backend_impl = { + .start = backend_start, + .destroy = backend_destroy, + .get_drm_fd = backend_get_drm_fd, + .test = backend_test, + .commit = backend_commit, +}; + +bool wlr_backend_is_drm(struct wlr_backend *b) { + return b->impl == &backend_impl; +} + +struct wlr_backend *wlr_drm_backend_get_parent(struct wlr_backend *backend) { + struct wlr_drm_backend *drm = get_drm_backend_from_backend(backend); + return drm->parent ? &drm->parent->backend : NULL; +} + +static void handle_session_active(struct wl_listener *listener, void *data) { + struct wlr_drm_backend *drm = + wl_container_of(listener, drm, session_active); + struct wlr_session *session = drm->session; + + wlr_log(WLR_INFO, "DRM FD %s", session->active ? "resumed" : "paused"); + + if (!session->active) { + // Disconnect any active connectors so that the client will modeset and + // rerender when the session is activated again. + struct wlr_drm_connector *conn; + wl_list_for_each(conn, &drm->connectors, link) { + if (conn->status == DRM_MODE_CONNECTED) { + wlr_output_destroy(&conn->output); + } + } + return; + } + + scan_drm_connectors(drm, NULL); +} + +static void handle_dev_change(struct wl_listener *listener, void *data) { + struct wlr_drm_backend *drm = wl_container_of(listener, drm, dev_change); + struct wlr_device_change_event *change = data; + + if (!drm->session->active) { + return; + } + + switch (change->type) { + case WLR_DEVICE_HOTPLUG: + wlr_log(WLR_DEBUG, "Received hotplug event for %s", drm->name); + scan_drm_connectors(drm, &change->hotplug); + break; + case WLR_DEVICE_LEASE: + wlr_log(WLR_DEBUG, "Received lease event for %s", drm->name); + scan_drm_leases(drm); + break; + default: + wlr_log(WLR_DEBUG, "Received unknown change event for %s", drm->name); + } +} + +static void handle_dev_remove(struct wl_listener *listener, void *data) { + struct wlr_drm_backend *drm = wl_container_of(listener, drm, dev_remove); + + wlr_log(WLR_INFO, "Destroying DRM backend for %s", drm->name); + backend_destroy(&drm->backend); +} + +static void handle_session_destroy(struct wl_listener *listener, void *data) { + struct wlr_drm_backend *drm = + wl_container_of(listener, drm, session_destroy); + backend_destroy(&drm->backend); +} + +static void handle_parent_destroy(struct wl_listener *listener, void *data) { + struct wlr_drm_backend *drm = + wl_container_of(listener, drm, parent_destroy); + backend_destroy(&drm->backend); +} + +static void sanitize_mgpu_modifiers(struct wlr_drm_format_set *set) { + for (size_t idx = 0; idx < set->len; idx++) { + // Implicit modifiers are not well-defined across devices, so strip + // them from all formats in multi-gpu scenarios. + struct wlr_drm_format *fmt = &set->formats[idx]; + wlr_drm_format_set_remove(set, fmt->format, DRM_FORMAT_MOD_INVALID); + } +} + +static bool init_mgpu_renderer(struct wlr_drm_backend *drm) { + if (!init_drm_renderer(drm, &drm->mgpu_renderer)) { + wlr_log(WLR_INFO, "Failed to initialize mgpu blit renderer" + ", falling back to scanning out from primary GPU"); + + for (uint32_t plane_idx = 0; plane_idx < drm->num_planes; plane_idx++) { + struct wlr_drm_plane *plane = &drm->planes[plane_idx]; + sanitize_mgpu_modifiers(&plane->formats); + } + return true; + } + + // We'll perform a multi-GPU copy for all submitted buffers, we need + // to be able to texture from them + struct wlr_renderer *renderer = drm->mgpu_renderer.wlr_rend; + const struct wlr_drm_format_set *texture_formats = + wlr_renderer_get_texture_formats(renderer, WLR_BUFFER_CAP_DMABUF); + if (texture_formats == NULL) { + wlr_log(WLR_ERROR, "Failed to query renderer texture formats"); + return false; + } + + wlr_drm_format_set_copy(&drm->mgpu_formats, texture_formats); + sanitize_mgpu_modifiers(&drm->mgpu_formats); + drm->backend.features.timeline = drm->backend.features.timeline && + drm->mgpu_renderer.wlr_rend->features.timeline; + return true; +} + +struct wlr_backend *wlr_drm_backend_create(struct wlr_session *session, + struct wlr_device *dev, struct wlr_backend *parent) { + assert(session && dev); + assert(!parent || wlr_backend_is_drm(parent)); + + char *name = drmGetDeviceNameFromFd2(dev->fd); + if (name == NULL) { + wlr_log_errno(WLR_ERROR, "drmGetDeviceNameFromFd2() failed"); + return NULL; + } + + drmVersion *version = drmGetVersion(dev->fd); + if (version == NULL) { + wlr_log_errno(WLR_ERROR, "drmGetVersion() failed"); + free(name); + return NULL; + } + wlr_log(WLR_INFO, "Initializing DRM backend for %s (%s)", name, version->name); + drmFreeVersion(version); + + struct wlr_drm_backend *drm = calloc(1, sizeof(*drm)); + if (!drm) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + wlr_backend_init(&drm->backend, &backend_impl); + + drm->backend.buffer_caps = WLR_BUFFER_CAP_DMABUF; + + drm->session = session; + wl_list_init(&drm->fbs); + wl_list_init(&drm->connectors); + wl_list_init(&drm->page_flips); + + drm->dev = dev; + drm->fd = dev->fd; + drm->name = name; + + if (parent != NULL) { + drm->parent = get_drm_backend_from_backend(parent); + + drm->parent_destroy.notify = handle_parent_destroy; + wl_signal_add(&parent->events.destroy, &drm->parent_destroy); + } else { + wl_list_init(&drm->parent_destroy.link); + } + + drm->dev_change.notify = handle_dev_change; + wl_signal_add(&dev->events.change, &drm->dev_change); + + drm->dev_remove.notify = handle_dev_remove; + wl_signal_add(&dev->events.remove, &drm->dev_remove); + + drm->drm_event = wl_event_loop_add_fd(session->event_loop, drm->fd, + WL_EVENT_READABLE, handle_drm_event, drm); + if (!drm->drm_event) { + wlr_log(WLR_ERROR, "Failed to create DRM event source"); + goto error_fd; + } + + drm->session_active.notify = handle_session_active; + wl_signal_add(&session->events.active, &drm->session_active); + + if (!check_drm_features(drm)) { + goto error_event; + } + + if (!init_drm_resources(drm)) { + goto error_event; + } + + if (drm->parent && !init_mgpu_renderer(drm)) { + goto error_mgpu_renderer; + } + + drm->session_destroy.notify = handle_session_destroy; + wl_signal_add(&session->events.destroy, &drm->session_destroy); + + return &drm->backend; + +error_mgpu_renderer: + finish_drm_renderer(&drm->mgpu_renderer); + finish_drm_resources(drm); +error_event: + wl_list_remove(&drm->session_active.link); + wl_event_source_remove(drm->drm_event); +error_fd: + wl_list_remove(&drm->dev_remove.link); + wl_list_remove(&drm->dev_change.link); + wl_list_remove(&drm->parent_destroy.link); + wlr_session_close_file(drm->session, dev); + free(drm->name); + free(drm); + return NULL; +} diff --git a/3rdparty/wlroots/backend/drm/drm.c b/3rdparty/wlroots/backend/drm/drm.c new file mode 100644 index 0000000000..bd29872fb7 --- /dev/null +++ b/3rdparty/wlroots/backend/drm/drm.c @@ -0,0 +1,2252 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "backend/drm/drm.h" +#include "backend/drm/fb.h" +#include "backend/drm/iface.h" +#include "backend/drm/util.h" +#include "render/color.h" +#include "types/wlr_output.h" +#include "util/env.h" +#include "config.h" + +#if HAVE_LIBLIFTOFF +#include +#endif + +// Output state which needs a KMS commit to be applied +static const uint32_t COMMIT_OUTPUT_STATE = + WLR_OUTPUT_STATE_BUFFER | + WLR_OUTPUT_STATE_MODE | + WLR_OUTPUT_STATE_ENABLED | + WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED | + WLR_OUTPUT_STATE_LAYERS | + WLR_OUTPUT_STATE_WAIT_TIMELINE | + WLR_OUTPUT_STATE_SIGNAL_TIMELINE | + WLR_OUTPUT_STATE_COLOR_TRANSFORM | + WLR_OUTPUT_STATE_IMAGE_DESCRIPTION; + +static const uint32_t SUPPORTED_OUTPUT_STATE = + WLR_OUTPUT_STATE_BACKEND_OPTIONAL | COMMIT_OUTPUT_STATE; + +bool check_drm_features(struct wlr_drm_backend *drm) { + if (drmGetCap(drm->fd, DRM_CAP_CURSOR_WIDTH, &drm->cursor_width)) { + drm->cursor_width = 64; + } + if (drmGetCap(drm->fd, DRM_CAP_CURSOR_HEIGHT, &drm->cursor_height)) { + drm->cursor_height = 64; + } + + uint64_t cap; + if (drmGetCap(drm->fd, DRM_CAP_PRIME, &cap) || + !(cap & DRM_PRIME_CAP_IMPORT)) { + wlr_log(WLR_ERROR, "PRIME import not supported"); + return false; + } + + if (drm->parent) { + if (drmGetCap(drm->parent->fd, DRM_CAP_PRIME, &cap) || + !(cap & DRM_PRIME_CAP_EXPORT)) { + wlr_log(WLR_ERROR, + "PRIME export not supported on primary GPU"); + return false; + } + } + + if (drmSetClientCap(drm->fd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1)) { + wlr_log(WLR_ERROR, "DRM universal planes unsupported"); + return false; + } + + if (drmGetCap(drm->fd, DRM_CAP_CRTC_IN_VBLANK_EVENT, &cap) || !cap) { + wlr_log(WLR_ERROR, "DRM_CRTC_IN_VBLANK_EVENT unsupported"); + return false; + } + + if (drmGetCap(drm->fd, DRM_CAP_TIMESTAMP_MONOTONIC, &cap) || !cap) { + wlr_log(WLR_ERROR, "DRM_CAP_TIMESTAMP_MONOTONIC unsupported"); + return false; + } + + if (env_parse_bool("WLR_DRM_FORCE_LIBLIFTOFF")) { +#if HAVE_LIBLIFTOFF + wlr_log(WLR_INFO, + "WLR_DRM_FORCE_LIBLIFTOFF set, forcing libliftoff interface"); + if (drmSetClientCap(drm->fd, DRM_CLIENT_CAP_ATOMIC, 1) != 0) { + wlr_log_errno(WLR_ERROR, "drmSetClientCap(ATOMIC) failed"); + return false; + } + drm->iface = &liftoff_iface; +#else + wlr_log(WLR_ERROR, "libliftoff interface not available"); + return false; +#endif + } else if (env_parse_bool("WLR_DRM_NO_ATOMIC")) { + wlr_log(WLR_DEBUG, + "WLR_DRM_NO_ATOMIC set, forcing legacy DRM interface"); + drm->iface = &legacy_iface; + } else if (drmSetClientCap(drm->fd, DRM_CLIENT_CAP_ATOMIC, 1)) { + wlr_log(WLR_DEBUG, + "Atomic modesetting unsupported, using legacy DRM interface"); + drm->iface = &legacy_iface; + } else { + wlr_log(WLR_DEBUG, "Using atomic DRM interface"); + drm->iface = &atomic_iface; + } +#ifdef DRM_CLIENT_CAP_CURSOR_PLANE_HOTSPOT + if (drm->iface == &atomic_iface && drmSetClientCap(drm->fd, DRM_CLIENT_CAP_CURSOR_PLANE_HOTSPOT, 1) == 0) { + wlr_log(WLR_INFO, "DRM_CLIENT_CAP_CURSOR_PLANE_HOTSPOT supported"); + } +#endif + + if (drm->iface == &legacy_iface) { + drm->supports_tearing_page_flips = drmGetCap(drm->fd, DRM_CAP_ASYNC_PAGE_FLIP, &cap) == 0 && cap == 1; + } else { + drm->supports_tearing_page_flips = drmGetCap(drm->fd, DRM_CAP_ATOMIC_ASYNC_PAGE_FLIP, &cap) == 0 && cap == 1; + drm->backend.features.timeline = drmGetCap(drm->fd, DRM_CAP_SYNCOBJ_TIMELINE, &cap) == 0 && cap == 1; + } + + if (env_parse_bool("WLR_DRM_NO_MODIFIERS")) { + wlr_log(WLR_DEBUG, "WLR_DRM_NO_MODIFIERS set, disabling modifiers"); + } else { + int ret = drmGetCap(drm->fd, DRM_CAP_ADDFB2_MODIFIERS, &cap); + drm->addfb2_modifiers = ret == 0 && cap == 1; + wlr_log(WLR_DEBUG, "ADDFB2 modifiers %s", + drm->addfb2_modifiers ? "supported" : "unsupported"); + } + + return true; +} + +static bool init_plane_cursor_sizes(struct wlr_drm_plane *plane, + const struct drm_plane_size_hint *hints, size_t hints_len) { + assert(hints_len > 0); + plane->cursor_sizes = calloc(hints_len, sizeof(plane->cursor_sizes[0])); + if (plane->cursor_sizes == NULL) { + return false; + } + plane->cursor_sizes_len = hints_len; + + for (size_t i = 0; i < hints_len; i++) { + const struct drm_plane_size_hint hint = hints[i]; + plane->cursor_sizes[i] = (struct wlr_output_cursor_size){ + .width = hint.width, + .height = hint.height, + }; + } + + return true; +} + +static bool init_plane(struct wlr_drm_backend *drm, + struct wlr_drm_plane *p, const drmModePlane *drm_plane) { + uint32_t id = drm_plane->plane_id; + + struct wlr_drm_plane_props props = {0}; + if (!get_drm_plane_props(drm->fd, id, &props)) { + return false; + } + + uint64_t type; + if (!get_drm_prop(drm->fd, id, props.type, &type)) { + return false; + } + + p->type = type; + p->id = id; + p->props = props; + p->initial_crtc_id = drm_plane->crtc_id; + + for (size_t i = 0; i < drm_plane->count_formats; ++i) { + // Force a LINEAR layout for the cursor if the driver doesn't support + // modifiers + wlr_drm_format_set_add(&p->formats, drm_plane->formats[i], + DRM_FORMAT_MOD_LINEAR); + if (type != DRM_PLANE_TYPE_CURSOR) { + wlr_drm_format_set_add(&p->formats, drm_plane->formats[i], + DRM_FORMAT_MOD_INVALID); + } + } + + if (p->props.in_formats && drm->addfb2_modifiers) { + uint64_t blob_id; + if (!get_drm_prop(drm->fd, p->id, p->props.in_formats, &blob_id)) { + wlr_log(WLR_ERROR, "Failed to read IN_FORMATS property"); + return false; + } + + drmModePropertyBlobRes *blob = drmModeGetPropertyBlob(drm->fd, blob_id); + if (!blob) { + wlr_log(WLR_ERROR, "Failed to read IN_FORMATS blob"); + return false; + } + + drmModeFormatModifierIterator iter = {0}; + while (drmModeFormatModifierBlobIterNext(blob, &iter)) { + wlr_drm_format_set_add(&p->formats, iter.fmt, iter.mod); + } + + drmModeFreePropertyBlob(blob); + } + + uint64_t size_hints_blob_id = 0; + if (p->props.size_hints) { + if (!get_drm_prop(drm->fd, p->id, p->props.size_hints, &size_hints_blob_id)) { + wlr_log(WLR_ERROR, "Failed to read SIZE_HINTS property"); + return false; + } + } + if (size_hints_blob_id != 0) { + drmModePropertyBlobRes *blob = drmModeGetPropertyBlob(drm->fd, size_hints_blob_id); + if (!blob) { + wlr_log(WLR_ERROR, "Failed to read SIZE_HINTS blob"); + return false; + } + + const struct drm_plane_size_hint *size_hints = blob->data; + size_t size_hints_len = blob->length / sizeof(size_hints[0]); + if (!init_plane_cursor_sizes(p, size_hints, size_hints_len)) { + return false; + } + + drmModeFreePropertyBlob(blob); + } else { + const struct drm_plane_size_hint size_hint = { + .width = drm->cursor_width, + .height = drm->cursor_height, + }; + if (!init_plane_cursor_sizes(p, &size_hint, 1)) { + return false; + } + } + + assert(drm->num_crtcs <= 32); + for (size_t j = 0; j < drm->num_crtcs; j++) { + uint32_t crtc_bit = 1 << j; + if ((drm_plane->possible_crtcs & crtc_bit) == 0) { + continue; + } + + struct wlr_drm_crtc *crtc = &drm->crtcs[j]; + if (type == DRM_PLANE_TYPE_PRIMARY && !crtc->primary) { + crtc->primary = p; + break; + } + if (type == DRM_PLANE_TYPE_CURSOR && !crtc->cursor) { + crtc->cursor = p; + break; + } + } + + return true; +} + +static bool init_planes(struct wlr_drm_backend *drm) { + drmModePlaneRes *plane_res = drmModeGetPlaneResources(drm->fd); + if (!plane_res) { + wlr_log_errno(WLR_ERROR, "Failed to get DRM plane resources"); + return false; + } + + wlr_log(WLR_INFO, "Found %"PRIu32" DRM planes", plane_res->count_planes); + + drm->num_planes = plane_res->count_planes; + drm->planes = calloc(drm->num_planes, sizeof(*drm->planes)); + if (drm->planes == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + goto error; + } + + for (uint32_t i = 0; i < plane_res->count_planes; ++i) { + uint32_t id = plane_res->planes[i]; + + drmModePlane *drm_plane = drmModeGetPlane(drm->fd, id); + if (!drm_plane) { + wlr_log_errno(WLR_ERROR, "Failed to get DRM plane"); + goto error; + } + + struct wlr_drm_plane *plane = &drm->planes[i]; + if (!init_plane(drm, plane, drm_plane)) { + goto error; + } + + drmModeFreePlane(drm_plane); + } + + drmModeFreePlaneResources(plane_res); + return true; + +error: + free(drm->planes); + drmModeFreePlaneResources(plane_res); + return false; +} + +bool init_drm_resources(struct wlr_drm_backend *drm) { + drmModeRes *res = drmModeGetResources(drm->fd); + if (!res) { + wlr_log_errno(WLR_ERROR, "Failed to get DRM resources"); + return false; + } + + wlr_log(WLR_INFO, "Found %d DRM CRTCs", res->count_crtcs); + + drm->num_crtcs = res->count_crtcs; + if (drm->num_crtcs == 0) { + drmModeFreeResources(res); + return true; + } + + drm->crtcs = calloc(drm->num_crtcs, sizeof(drm->crtcs[0])); + if (!drm->crtcs) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + goto error_res; + } + + for (size_t i = 0; i < drm->num_crtcs; ++i) { + struct wlr_drm_crtc *crtc = &drm->crtcs[i]; + crtc->id = res->crtcs[i]; + + drmModeCrtc *drm_crtc = drmModeGetCrtc(drm->fd, crtc->id); + if (drm_crtc == NULL) { + wlr_log_errno(WLR_ERROR, "drmModeGetCrtc failed"); + goto error_res; + } + crtc->legacy_gamma_size = drm_crtc->gamma_size; + drmModeFreeCrtc(drm_crtc); + + if (!get_drm_crtc_props(drm->fd, crtc->id, &crtc->props)) { + goto error_crtcs; + } + + wl_list_init(&crtc->layers); + } + + if (!init_planes(drm)) { + goto error_crtcs; + } + + if (drm->iface->init != NULL && !drm->iface->init(drm)) { + goto error_crtcs; + } + + drmModeFreeResources(res); + + return true; + +error_crtcs: + free(drm->crtcs); +error_res: + drmModeFreeResources(res); + return false; +} + +static void drm_plane_finish_surface(struct wlr_drm_plane *plane) { + if (!plane) { + return; + } + + drm_fb_clear(&plane->queued_fb); + if (plane->queued_release_timeline != NULL) { + wlr_drm_syncobj_timeline_signal(plane->queued_release_timeline, plane->queued_release_point); + wlr_drm_syncobj_timeline_unref(plane->queued_release_timeline); + plane->queued_release_timeline = NULL; + } + drm_fb_clear(&plane->current_fb); + if (plane->current_release_timeline != NULL) { + wlr_drm_syncobj_timeline_signal(plane->current_release_timeline, plane->current_release_point); + wlr_drm_syncobj_timeline_unref(plane->current_release_timeline); + plane->current_release_timeline = NULL; + } + + finish_drm_surface(&plane->mgpu_surf); +} + +void finish_drm_resources(struct wlr_drm_backend *drm) { + if (!drm) { + return; + } + + if (drm->iface->finish != NULL) { + drm->iface->finish(drm); + } + + for (size_t i = 0; i < drm->num_crtcs; ++i) { + struct wlr_drm_crtc *crtc = &drm->crtcs[i]; + + if (crtc->mode_id && crtc->own_mode_id) { + drmModeDestroyPropertyBlob(drm->fd, crtc->mode_id); + } + if (crtc->gamma_lut) { + drmModeDestroyPropertyBlob(drm->fd, crtc->gamma_lut); + } + } + + free(drm->crtcs); + + for (size_t i = 0; i < drm->num_planes; ++i) { + struct wlr_drm_plane *plane = &drm->planes[i]; + drm_plane_finish_surface(plane); + wlr_drm_format_set_finish(&plane->formats); + free(plane->cursor_sizes); + } + + free(drm->planes); +} + +static struct wlr_drm_connector *get_drm_connector_from_output( + struct wlr_output *wlr_output) { + assert(wlr_output_is_drm(wlr_output)); + struct wlr_drm_connector *conn = wl_container_of(wlr_output, conn, output); + return conn; +} + +static void layer_handle_addon_destroy(struct wlr_addon *addon) { + struct wlr_drm_layer *layer = wl_container_of(addon, layer, addon); + wlr_addon_finish(&layer->addon); + wl_list_remove(&layer->link); +#if HAVE_LIBLIFTOFF + liftoff_layer_destroy(layer->liftoff); +#endif + drm_fb_clear(&layer->pending_fb); + drm_fb_clear(&layer->queued_fb); + drm_fb_clear(&layer->current_fb); + free(layer->candidate_planes); + free(layer); +} + +const struct wlr_addon_interface layer_impl = { + .name = "wlr_drm_layer", + .destroy = layer_handle_addon_destroy, +}; + +struct wlr_drm_layer *get_drm_layer(struct wlr_drm_backend *drm, + struct wlr_output_layer *wlr_layer) { + struct wlr_addon *addon = + wlr_addon_find(&wlr_layer->addons, drm, &layer_impl); + assert(addon != NULL); + struct wlr_drm_layer *layer = wl_container_of(addon, layer, addon); + return layer; +} + +static struct wlr_drm_layer *get_or_create_layer(struct wlr_drm_backend *drm, + struct wlr_drm_crtc *crtc, struct wlr_output_layer *wlr_layer) { + struct wlr_drm_layer *layer; + struct wlr_addon *addon = + wlr_addon_find(&wlr_layer->addons, drm, &layer_impl); + if (addon != NULL) { + layer = wl_container_of(addon, layer, addon); + return layer; + } + + layer = calloc(1, sizeof(*layer)); + if (layer == NULL) { + return NULL; + } + + layer->wlr = wlr_layer; + +#if HAVE_LIBLIFTOFF + layer->liftoff = liftoff_layer_create(crtc->liftoff); + if (layer->liftoff == NULL) { + free(layer); + return NULL; + } +#else + abort(); // unreachable +#endif + + layer->candidate_planes = calloc(drm->num_planes, sizeof(layer->candidate_planes[0])); + if (layer->candidate_planes == NULL) { +#if HAVE_LIBLIFTOFF + liftoff_layer_destroy(layer->liftoff); +#endif + free(layer); + return NULL; + } + + wlr_addon_init(&layer->addon, &wlr_layer->addons, drm, &layer_impl); + wl_list_insert(&crtc->layers, &layer->link); + + return layer; +} + +void drm_page_flip_destroy(struct wlr_drm_page_flip *page_flip) { + if (!page_flip) { + return; + } + + wl_list_remove(&page_flip->link); + free(page_flip->connectors); + free(page_flip); +} + +static struct wlr_drm_page_flip *drm_page_flip_create(struct wlr_drm_backend *drm, + const struct wlr_drm_device_state *state) { + struct wlr_drm_page_flip *page_flip = calloc(1, sizeof(*page_flip)); + if (page_flip == NULL) { + return NULL; + } + page_flip->connectors_len = state->connectors_len; + page_flip->connectors = + calloc(page_flip->connectors_len, sizeof(page_flip->connectors[0])); + if (page_flip->connectors == NULL) { + free(page_flip); + return NULL; + } + for (size_t i = 0; i < state->connectors_len; i++) { + struct wlr_drm_connector *conn = state->connectors[i].connector; + page_flip->connectors[i] = (struct wlr_drm_page_flip_connector){ + .connector = conn, + .crtc_id = conn->crtc->id, + }; + } + wl_list_insert(&drm->page_flips, &page_flip->link); + return page_flip; +} + +static struct wlr_drm_connector *drm_page_flip_pop( + struct wlr_drm_page_flip *page_flip, uint32_t crtc_id) { + bool found = false; + size_t i; + for (i = 0; i < page_flip->connectors_len; i++) { + if (page_flip->connectors[i].crtc_id == crtc_id) { + found = true; + break; + } + } + if (!found) { + return NULL; + } + + struct wlr_drm_connector *conn = page_flip->connectors[i].connector; + if (i != page_flip->connectors_len - 1) { + page_flip->connectors[i] = page_flip->connectors[page_flip->connectors_len - 1]; + } + page_flip->connectors_len--; + return conn; +} + +static void drm_connector_set_pending_page_flip(struct wlr_drm_connector *conn, + struct wlr_drm_page_flip *page_flip) { + if (conn->pending_page_flip != NULL) { + struct wlr_drm_page_flip *page_flip = conn->pending_page_flip; + for (size_t i = 0; i < page_flip->connectors_len; i++) { + if (page_flip->connectors[i].connector == conn) { + page_flip->connectors[i].connector = NULL; + } + } + } + conn->pending_page_flip = page_flip; +} + +static void drm_connector_apply_commit(const struct wlr_drm_connector_state *state, + struct wlr_drm_page_flip *page_flip) { + struct wlr_drm_connector *conn = state->connector; + struct wlr_drm_crtc *crtc = conn->crtc; + + drm_fb_copy(&crtc->primary->queued_fb, state->primary_fb); + if (crtc->primary->queued_release_timeline != NULL) { + wlr_drm_syncobj_timeline_signal(crtc->primary->queued_release_timeline, crtc->primary->queued_release_point); + wlr_drm_syncobj_timeline_unref(crtc->primary->queued_release_timeline); + } + if (state->base->signal_timeline != NULL) { + crtc->primary->queued_release_timeline = wlr_drm_syncobj_timeline_ref(state->base->signal_timeline); + crtc->primary->queued_release_point = state->base->signal_point; + } else { + crtc->primary->queued_release_timeline = NULL; + crtc->primary->queued_release_point = 0; + } + + crtc->primary->viewport = state->primary_viewport; + if (crtc->cursor != NULL) { + drm_fb_copy(&crtc->cursor->queued_fb, state->cursor_fb); + } + drm_fb_clear(&conn->cursor_pending_fb); + + struct wlr_drm_layer *layer; + wl_list_for_each(layer, &crtc->layers, link) { + drm_fb_move(&layer->queued_fb, &layer->pending_fb); + } + + drm_connector_set_pending_page_flip(conn, page_flip); + + if (state->base->committed & WLR_OUTPUT_STATE_MODE) { + conn->refresh = calculate_refresh_rate(&state->mode); + } + + if (!state->active) { + drm_plane_finish_surface(crtc->primary); + drm_plane_finish_surface(crtc->cursor); + drm_fb_clear(&conn->cursor_pending_fb); + + conn->cursor_enabled = false; + conn->crtc = NULL; + + // Legacy uAPI doesn't support requesting page-flip events when + // turning off a CRTC + if (page_flip != NULL && conn->backend->iface == &legacy_iface) { + drm_page_flip_pop(page_flip, crtc->id); + conn->pending_page_flip = NULL; + if (page_flip->connectors_len == 0) { + drm_page_flip_destroy(page_flip); + } + } + } +} + +static void drm_connector_rollback_commit(const struct wlr_drm_connector_state *state) { + struct wlr_drm_crtc *crtc = state->connector->crtc; + + // The set_cursor() hook is a bit special: it's not really synchronized + // to commit() or test(). Once set_cursor() returns true, the new + // cursor is effectively committed. So don't roll it back here, or we + // risk ending up in a state where we don't have a cursor FB but + // wlr_drm_connector.cursor_enabled is true. + // TODO: fix our output interface to avoid this issue. + + struct wlr_drm_layer *layer; + wl_list_for_each(layer, &crtc->layers, link) { + drm_fb_clear(&layer->pending_fb); + } +} + +static bool drm_commit(struct wlr_drm_backend *drm, + const struct wlr_drm_device_state *state, + uint32_t flags, bool test_only) { + // Disallow atomic-only flags + assert((flags & ~DRM_MODE_PAGE_FLIP_FLAGS) == 0); + + struct wlr_drm_page_flip *page_flip = NULL; + if (flags & DRM_MODE_PAGE_FLIP_EVENT) { + page_flip = drm_page_flip_create(drm, state); + if (page_flip == NULL) { + return false; + } + page_flip->async = (flags & DRM_MODE_PAGE_FLIP_ASYNC); + } + + bool ok = drm->iface->commit(drm, state, page_flip, flags, test_only); + if (ok && !test_only) { + for (size_t i = 0; i < state->connectors_len; i++) { + drm_connector_apply_commit(&state->connectors[i], page_flip); + } + } else { + for (size_t i = 0; i < state->connectors_len; i++) { + drm_connector_rollback_commit(&state->connectors[i]); + } + drm_page_flip_destroy(page_flip); + } + return ok; +} + +static void drm_connector_state_init(struct wlr_drm_connector_state *state, + struct wlr_drm_connector *conn, + const struct wlr_output_state *base) { + *state = (struct wlr_drm_connector_state){ + .connector = conn, + .base = base, + .active = output_pending_enabled(&conn->output, base), + .primary_in_fence_fd = -1, + }; + + struct wlr_output_mode *mode = conn->output.current_mode; + int32_t width = conn->output.width; + int32_t height = conn->output.height; + int32_t refresh = conn->output.refresh; + + if (base->committed & WLR_OUTPUT_STATE_MODE) { + switch (base->mode_type) { + case WLR_OUTPUT_STATE_MODE_FIXED: + mode = base->mode; + break; + case WLR_OUTPUT_STATE_MODE_CUSTOM: + mode = NULL; + width = base->custom_mode.width; + height = base->custom_mode.height; + refresh = base->custom_mode.refresh; + break; + } + } + + if (mode) { + struct wlr_drm_mode *drm_mode = wl_container_of(mode, drm_mode, wlr_mode); + state->mode = drm_mode->drm_mode; + } else { + generate_cvt_mode(&state->mode, width, height, (float)refresh / 1000); + state->mode.type = DRM_MODE_TYPE_USERDEF; + } + + if (output_pending_enabled(&conn->output, base)) { + // The CRTC must be set up before this function is called + assert(conn->crtc != NULL); + + struct wlr_drm_plane *primary = conn->crtc->primary; + if (primary->queued_fb != NULL) { + state->primary_fb = drm_fb_lock(primary->queued_fb); + state->primary_viewport = primary->viewport; + } else if (primary->current_fb != NULL) { + state->primary_fb = drm_fb_lock(primary->current_fb); + state->primary_viewport = primary->viewport; + } + + if (conn->cursor_enabled) { + struct wlr_drm_plane *cursor = conn->crtc->cursor; + assert(cursor != NULL); + if (conn->cursor_pending_fb != NULL) { + state->cursor_fb = drm_fb_lock(conn->cursor_pending_fb); + } else if (cursor->queued_fb != NULL) { + state->cursor_fb = drm_fb_lock(cursor->queued_fb); + } else if (cursor->current_fb != NULL) { + state->cursor_fb = drm_fb_lock(cursor->current_fb); + } + } + } +} + +static void drm_connector_state_finish(struct wlr_drm_connector_state *state) { + drm_fb_clear(&state->primary_fb); + drm_fb_clear(&state->cursor_fb); + wlr_drm_syncobj_timeline_unref(state->wait_timeline); +} + +static bool drm_connector_state_update_primary_fb(struct wlr_drm_connector *conn, + struct wlr_drm_connector_state *state) { + struct wlr_drm_backend *drm = conn->backend; + + assert(state->base->committed & WLR_OUTPUT_STATE_BUFFER); + + struct wlr_drm_crtc *crtc = conn->crtc; + assert(crtc != NULL); + + struct wlr_drm_plane *plane = crtc->primary; + struct wlr_buffer *source_buf = state->base->buffer; + + struct wlr_drm_syncobj_timeline *wait_timeline = NULL; + uint64_t wait_point = 0; + if (state->base->committed & WLR_OUTPUT_STATE_WAIT_TIMELINE) { + wait_timeline = state->base->wait_timeline; + wait_point = state->base->wait_point; + } + assert(state->wait_timeline == NULL); + + struct wlr_buffer *local_buf; + if (drm->mgpu_renderer.wlr_rend) { + struct wlr_drm_format format = {0}; + if (!drm_plane_pick_render_format(plane, &format, &drm->mgpu_renderer)) { + wlr_log(WLR_ERROR, "Failed to pick primary plane format"); + return false; + } + + // TODO: fallback to modifier-less buffer allocation + bool ok = init_drm_surface(&plane->mgpu_surf, &drm->mgpu_renderer, + source_buf->width, source_buf->height, &format); + wlr_drm_format_finish(&format); + if (!ok) { + return false; + } + + local_buf = drm_surface_blit(&plane->mgpu_surf, source_buf, + wait_timeline, wait_point); + if (local_buf == NULL) { + return false; + } + + if (plane->mgpu_surf.timeline != NULL) { + state->wait_timeline = wlr_drm_syncobj_timeline_ref(plane->mgpu_surf.timeline); + state->wait_point = plane->mgpu_surf.point; + } + } else { + local_buf = wlr_buffer_lock(source_buf); + + if (wait_timeline != NULL) { + state->wait_timeline = wlr_drm_syncobj_timeline_ref(wait_timeline); + state->wait_point = wait_point; + } + } + + bool ok = drm_fb_import(&state->primary_fb, drm, local_buf, + &plane->formats); + wlr_buffer_unlock(local_buf); + if (!ok) { + wlr_drm_conn_log(conn, WLR_DEBUG, + "Failed to import buffer for scan-out"); + return false; + } + + output_state_get_buffer_src_box(state->base, &state->primary_viewport.src_box); + output_state_get_buffer_dst_box(state->base, &state->primary_viewport.dst_box); + + return true; +} + +static bool drm_connector_set_pending_layer_fbs(struct wlr_drm_connector *conn, + const struct wlr_output_state *state) { + struct wlr_drm_backend *drm = conn->backend; + + struct wlr_drm_crtc *crtc = conn->crtc; + if (!crtc || drm->mgpu_renderer.wlr_rend) { + return false; + } + + if (!crtc->liftoff) { + return true; // libliftoff is disabled + } + + assert(state->committed & WLR_OUTPUT_STATE_LAYERS); + + for (size_t i = 0; i < state->layers_len; i++) { + struct wlr_output_layer_state *layer_state = &state->layers[i]; + struct wlr_drm_layer *layer = + get_or_create_layer(drm, crtc, layer_state->layer); + if (!layer) { + return false; + } + + if (layer_state->buffer != NULL) { + drm_fb_import(&layer->pending_fb, drm, layer_state->buffer, NULL); + } else { + drm_fb_clear(&layer->pending_fb); + } + } + + return true; +} + +static bool drm_connector_alloc_crtc(struct wlr_drm_connector *conn); + +static bool drm_connector_prepare(struct wlr_drm_connector_state *conn_state, bool test_only) { + const struct wlr_output_state *state = conn_state->base; + struct wlr_drm_connector *conn = conn_state->connector; + struct wlr_output *output = &conn->output; + + uint32_t unsupported = state->committed & ~SUPPORTED_OUTPUT_STATE; + if (unsupported != 0) { + wlr_log(WLR_DEBUG, "Unsupported output state fields: 0x%"PRIx32, + unsupported); + return false; + } + + if ((state->committed & WLR_OUTPUT_STATE_ENABLED) && state->enabled && + output->width == 0 && output->height == 0 && + !(state->committed & WLR_OUTPUT_STATE_MODE)) { + wlr_drm_conn_log(conn, WLR_DEBUG, + "Can't enable an output without a mode"); + return false; + } + + if ((state->committed & WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED) && + state->adaptive_sync_enabled && + !output->adaptive_sync_supported) { + wlr_drm_conn_log(conn, WLR_DEBUG, + "Can't enable adaptive sync: connector doesn't support VRR"); + return false; + } + + if ((state->committed & WLR_OUTPUT_STATE_BUFFER) && conn->backend->mgpu_renderer.wlr_rend) { + struct wlr_dmabuf_attributes dmabuf; + if (!wlr_buffer_get_dmabuf(state->buffer, &dmabuf)) { + wlr_drm_conn_log(conn, WLR_DEBUG, "Buffer is not a DMA-BUF"); + return false; + } + + if (!wlr_drm_format_set_has(&conn->backend->mgpu_formats, dmabuf.format, dmabuf.modifier)) { + wlr_drm_conn_log(conn, WLR_DEBUG, + "Buffer format 0x%"PRIX32" with modifier 0x%"PRIX64" cannot be " + "imported into multi-GPU renderer", + dmabuf.format, dmabuf.modifier); + return false; + } + } + + if ((state->committed & WLR_OUTPUT_STATE_COLOR_TRANSFORM) && state->color_transform != NULL && + state->color_transform->type != COLOR_TRANSFORM_LUT_3X1D) { + wlr_drm_conn_log(conn, WLR_DEBUG, + "Only 3x1D LUT color transforms are supported"); + return false; + } + + if ((state->committed & WLR_OUTPUT_STATE_IMAGE_DESCRIPTION) && + conn->backend->iface != &atomic_iface) { + wlr_log(WLR_DEBUG, "Image descriptions are only supported by the atomic interface"); + return false; + } + + if (test_only && conn->backend->mgpu_renderer.wlr_rend) { + // If we're running as a secondary GPU, we can't perform an atomic + // commit without blitting a buffer. + return true; + } + + if (state->committed & WLR_OUTPUT_STATE_BUFFER) { + if (!drm_connector_state_update_primary_fb(conn, conn_state)) { + return false; + } + + if (conn_state->base->tearing_page_flip && !conn->backend->supports_tearing_page_flips) { + wlr_log(WLR_ERROR, "Attempted to submit a tearing page flip to an unsupported backend!"); + return false; + } + } + if (state->committed & WLR_OUTPUT_STATE_LAYERS) { + if (!drm_connector_set_pending_layer_fbs(conn, conn_state->base)) { + return false; + } + } + + if (conn_state->active && !conn_state->primary_fb) { + wlr_drm_conn_log(conn, WLR_DEBUG, + "No primary frame buffer available for this connector"); + return false; + } + + return true; +} + +static bool drm_connector_commit_state(struct wlr_drm_connector *conn, + const struct wlr_output_state *state, bool test_only) { + struct wlr_drm_backend *drm = conn->backend; + + if (!drm->session->active) { + return false; + } + + if (test_only && (state->committed & COMMIT_OUTPUT_STATE) == 0) { + // This commit doesn't change the KMS state + return true; + } + + if (output_pending_enabled(&conn->output, state) && !drm_connector_alloc_crtc(conn)) { + wlr_drm_conn_log(conn, WLR_DEBUG, + "No CRTC available for this connector"); + return false; + } + + bool ok = false; + struct wlr_drm_connector_state pending = {0}; + drm_connector_state_init(&pending, conn, state); + struct wlr_drm_device_state pending_dev = { + .modeset = state->allow_reconfiguration, + // The wlr_output API requires non-modeset commits with a new buffer to + // wait for the frame event. However compositors often perform + // non-modesets commits without a new buffer without waiting for the + // frame event. In that case we need to make the KMS commit blocking, + // otherwise the kernel will error out with EBUSY. + .nonblock = !state->allow_reconfiguration && + (state->committed & WLR_OUTPUT_STATE_BUFFER), + .connectors = &pending, + .connectors_len = 1, + }; + + if (!drm_connector_prepare(&pending, test_only)) { + goto out; + } + + if (test_only && conn->backend->mgpu_renderer.wlr_rend) { + // If we're running as a secondary GPU, we can't perform an atomic + // commit without blitting a buffer. + ok = true; + goto out; + } + + if (!pending.active && conn->crtc == NULL) { + // Disabling an already-disabled connector + ok = true; + goto out; + } + + if (!test_only && pending_dev.modeset) { + if (pending.active) { + wlr_drm_conn_log(conn, WLR_INFO, "Modesetting with %dx%d @ %.3f Hz", + pending.mode.hdisplay, pending.mode.vdisplay, + (float)calculate_refresh_rate(&pending.mode) / 1000); + } else { + wlr_drm_conn_log(conn, WLR_INFO, "Turning off"); + } + } + + // wlr_drm_interface.crtc_commit will perform either a non-blocking + // page-flip, either a blocking modeset. When performing a blocking modeset + // we'll wait for all queued page-flips to complete, so we don't need this + // safeguard. + if (!test_only && pending_dev.nonblock && conn->pending_page_flip != NULL) { + wlr_drm_conn_log(conn, WLR_ERROR, "Failed to page-flip output: " + "a page-flip is already pending"); + goto out; + } + + uint32_t flags = 0; + if (!test_only && pending.active) { + flags |= DRM_MODE_PAGE_FLIP_EVENT; + } + if (pending.base->tearing_page_flip) { + flags |= DRM_MODE_PAGE_FLIP_ASYNC; + } + + ok = drm_commit(drm, &pending_dev, flags, test_only); + +out: + drm_connector_state_finish(&pending); + return ok; +} + +static bool drm_connector_test(struct wlr_output *output, + const struct wlr_output_state *state) { + struct wlr_drm_connector *conn = get_drm_connector_from_output(output); + return drm_connector_commit_state(conn, state, true); +} + +static bool drm_connector_commit(struct wlr_output *output, + const struct wlr_output_state *state) { + struct wlr_drm_connector *conn = get_drm_connector_from_output(output); + return drm_connector_commit_state(conn, state, false); +} + +size_t drm_crtc_get_gamma_lut_size(struct wlr_drm_backend *drm, + struct wlr_drm_crtc *crtc) { + if (crtc->props.gamma_lut_size == 0 || drm->iface == &legacy_iface) { + return (size_t)crtc->legacy_gamma_size; + } + + uint64_t gamma_lut_size; + if (!get_drm_prop(drm->fd, crtc->id, crtc->props.gamma_lut_size, + &gamma_lut_size)) { + wlr_log(WLR_ERROR, "Unable to get gamma lut size"); + return 0; + } + + return gamma_lut_size; +} + +static size_t drm_connector_get_gamma_size(struct wlr_output *output) { + struct wlr_drm_connector *conn = get_drm_connector_from_output(output); + struct wlr_drm_backend *drm = conn->backend; + struct wlr_drm_crtc *crtc = conn->crtc; + + if (crtc == NULL) { + return 0; + } + + return drm_crtc_get_gamma_lut_size(drm, crtc); +} + +static void realloc_crtcs(struct wlr_drm_backend *drm, + struct wlr_drm_connector *want_conn); + +static bool drm_connector_alloc_crtc(struct wlr_drm_connector *conn) { + if (conn->crtc == NULL) { + realloc_crtcs(conn->backend, conn); + } + bool ok = conn->crtc != NULL; + if (!ok) { + wlr_drm_conn_log(conn, WLR_DEBUG, "Failed to find free CRTC"); + } + return ok; +} + +static struct wlr_drm_mode *drm_mode_create(const drmModeModeInfo *modeinfo) { + struct wlr_drm_mode *mode = calloc(1, sizeof(*mode)); + if (!mode) { + return NULL; + } + + mode->drm_mode = *modeinfo; + mode->wlr_mode.width = mode->drm_mode.hdisplay; + mode->wlr_mode.height = mode->drm_mode.vdisplay; + mode->wlr_mode.refresh = calculate_refresh_rate(modeinfo); + mode->wlr_mode.picture_aspect_ratio = get_picture_aspect_ratio(modeinfo); + if (modeinfo->type & DRM_MODE_TYPE_PREFERRED) { + mode->wlr_mode.preferred = true; + } + + return mode; +} + +struct wlr_output_mode *wlr_drm_connector_add_mode(struct wlr_output *output, + const drmModeModeInfo *modeinfo) { + struct wlr_drm_connector *conn = get_drm_connector_from_output(output); + + if (modeinfo->type != DRM_MODE_TYPE_USERDEF) { + return NULL; + } + + struct wlr_output_mode *wlr_mode; + wl_list_for_each(wlr_mode, &conn->output.modes, link) { + struct wlr_drm_mode *mode = wl_container_of(wlr_mode, mode, wlr_mode); + if (memcmp(&mode->drm_mode, modeinfo, sizeof(*modeinfo)) == 0) { + return wlr_mode; + } + } + + struct wlr_drm_mode *mode = drm_mode_create(modeinfo); + if (!mode) { + return NULL; + } + + wl_list_insert(&conn->output.modes, &mode->wlr_mode.link); + + wlr_drm_conn_log(conn, WLR_INFO, "Registered custom mode " + "%"PRId32"x%"PRId32"@%"PRId32, + mode->wlr_mode.width, mode->wlr_mode.height, + mode->wlr_mode.refresh); + + return &mode->wlr_mode; +} + +const drmModeModeInfo *wlr_drm_mode_get_info(struct wlr_output_mode *wlr_mode) { + const struct wlr_drm_mode *mode = wl_container_of(wlr_mode, mode, wlr_mode); + return &mode->drm_mode; +} + +static bool drm_connector_set_cursor(struct wlr_output *output, + struct wlr_buffer *buffer, int hotspot_x, int hotspot_y) { + struct wlr_drm_connector *conn = get_drm_connector_from_output(output); + struct wlr_drm_backend *drm = conn->backend; + struct wlr_drm_crtc *crtc = conn->crtc; + + if (!crtc) { + return false; + } + + struct wlr_drm_plane *plane = crtc->cursor; + if (plane == NULL) { + return false; + } + + if (conn->cursor_hotspot_x != hotspot_x || + conn->cursor_hotspot_y != hotspot_y) { + // Update cursor hotspot + conn->cursor_x -= hotspot_x - conn->cursor_hotspot_x; + conn->cursor_y -= hotspot_y - conn->cursor_hotspot_y; + conn->cursor_hotspot_x = hotspot_x; + conn->cursor_hotspot_y = hotspot_y; + } + + conn->cursor_enabled = false; + drm_fb_clear(&conn->cursor_pending_fb); + if (buffer != NULL) { + bool found = false; + for (size_t i = 0; i < plane->cursor_sizes_len; i++) { + struct wlr_output_cursor_size size = plane->cursor_sizes[i]; + if (size.width == buffer->width && size.height == buffer->height) { + found = true; + break; + } + } + if (!found) { + wlr_drm_conn_log(conn, WLR_DEBUG, "Cursor buffer size mismatch"); + return false; + } + + struct wlr_buffer *local_buf; + if (drm->mgpu_renderer.wlr_rend) { + struct wlr_drm_format format = {0}; + if (!drm_plane_pick_render_format(plane, &format, &drm->mgpu_renderer)) { + wlr_log(WLR_ERROR, "Failed to pick cursor plane format"); + return false; + } + + bool ok = init_drm_surface(&plane->mgpu_surf, &drm->mgpu_renderer, + buffer->width, buffer->height, &format); + wlr_drm_format_finish(&format); + if (!ok) { + return false; + } + + local_buf = drm_surface_blit(&plane->mgpu_surf, buffer, NULL, 0); + if (local_buf == NULL) { + return false; + } + } else { + local_buf = wlr_buffer_lock(buffer); + } + + bool ok = drm_fb_import(&conn->cursor_pending_fb, drm, local_buf, + &plane->formats); + wlr_buffer_unlock(local_buf); + if (!ok) { + return false; + } + + conn->cursor_enabled = true; + conn->cursor_width = buffer->width; + conn->cursor_height = buffer->height; + } + + return true; +} + +static bool drm_connector_move_cursor(struct wlr_output *output, + int x, int y) { + struct wlr_drm_connector *conn = get_drm_connector_from_output(output); + if (!conn->crtc) { + return false; + } + struct wlr_drm_plane *plane = conn->crtc->cursor; + if (!plane) { + return false; + } + + struct wlr_box box = { .x = x, .y = y }; + + int width, height; + wlr_output_transformed_resolution(output, &width, &height); + + enum wl_output_transform transform = + wlr_output_transform_invert(output->transform); + wlr_box_transform(&box, &box, transform, width, height); + + box.x -= conn->cursor_hotspot_x; + box.y -= conn->cursor_hotspot_y; + + conn->cursor_x = box.x; + conn->cursor_y = box.y; + + return true; +} + +bool drm_connector_is_cursor_visible(struct wlr_drm_connector *conn) { + return conn->cursor_enabled && + conn->cursor_x < conn->output.width && + conn->cursor_y < conn->output.height && + conn->cursor_x + conn->cursor_width >= 0 && + conn->cursor_y + conn->cursor_height >= 0; +} + +static void dealloc_crtc(struct wlr_drm_connector *conn); + +/** + * Destroy the compositor-facing part of a connector. + * + * The connector isn't destroyed when disconnected. Only the compositor-facing + * wlr_output interface is cleaned up. + */ +static void drm_connector_destroy_output(struct wlr_output *output) { + struct wlr_drm_connector *conn = get_drm_connector_from_output(output); + + wlr_output_finish(output); + + dealloc_crtc(conn); + + conn->status = DRM_MODE_DISCONNECTED; + drm_connector_set_pending_page_flip(conn, NULL); + + struct wlr_drm_mode *mode, *mode_tmp; + wl_list_for_each_safe(mode, mode_tmp, &conn->output.modes, wlr_mode.link) { + wl_list_remove(&mode->wlr_mode.link); + free(mode); + } + + conn->output = (struct wlr_output){0}; +} + +static const struct wlr_drm_format_set *drm_connector_get_cursor_formats( + struct wlr_output *output, uint32_t buffer_caps) { + if (!(buffer_caps & WLR_BUFFER_CAP_DMABUF)) { + return NULL; + } + struct wlr_drm_connector *conn = get_drm_connector_from_output(output); + if (!drm_connector_alloc_crtc(conn)) { + return NULL; + } + struct wlr_drm_plane *plane = conn->crtc->cursor; + if (!plane) { + return NULL; + } + if (conn->backend->mgpu_renderer.wlr_rend) { + return &conn->backend->mgpu_formats; + } + return &plane->formats; +} + +static const struct wlr_output_cursor_size *drm_connector_get_cursor_sizes(struct wlr_output *output, + size_t *len) { + struct wlr_drm_connector *conn = get_drm_connector_from_output(output); + if (!drm_connector_alloc_crtc(conn)) { + return NULL; + } + struct wlr_drm_plane *plane = conn->crtc->cursor; + if (!plane) { + return NULL; + } + *len = plane->cursor_sizes_len; + return plane->cursor_sizes; +} + +static const struct wlr_drm_format_set *drm_connector_get_primary_formats( + struct wlr_output *output, uint32_t buffer_caps) { + if (!(buffer_caps & WLR_BUFFER_CAP_DMABUF)) { + return NULL; + } + struct wlr_drm_connector *conn = get_drm_connector_from_output(output); + if (!drm_connector_alloc_crtc(conn)) { + return NULL; + } + if (conn->backend->mgpu_renderer.wlr_rend) { + return &conn->backend->mgpu_formats; + } + return &conn->crtc->primary->formats; +} + +static const struct wlr_output_impl output_impl = { + .set_cursor = drm_connector_set_cursor, + .move_cursor = drm_connector_move_cursor, + .destroy = drm_connector_destroy_output, + .test = drm_connector_test, + .commit = drm_connector_commit, + .get_gamma_size = drm_connector_get_gamma_size, + .get_cursor_formats = drm_connector_get_cursor_formats, + .get_cursor_sizes = drm_connector_get_cursor_sizes, + .get_primary_formats = drm_connector_get_primary_formats, +}; + +bool wlr_output_is_drm(struct wlr_output *output) { + return output->impl == &output_impl; +} + +uint32_t wlr_drm_connector_get_id(struct wlr_output *output) { + struct wlr_drm_connector *conn = get_drm_connector_from_output(output); + return conn->id; +} + +enum wl_output_transform wlr_drm_connector_get_panel_orientation( + struct wlr_output *output) { + struct wlr_drm_connector *conn = get_drm_connector_from_output(output); + if (!conn->props.panel_orientation) { + return WL_OUTPUT_TRANSFORM_NORMAL; + } + + char *orientation = get_drm_prop_enum(conn->backend->fd, conn->id, + conn->props.panel_orientation); + if (orientation == NULL) { + return WL_OUTPUT_TRANSFORM_NORMAL; + } + + enum wl_output_transform tr; + if (strcmp(orientation, "Normal") == 0) { + tr = WL_OUTPUT_TRANSFORM_NORMAL; + } else if (strcmp(orientation, "Left Side Up") == 0) { + tr = WL_OUTPUT_TRANSFORM_90; + } else if (strcmp(orientation, "Upside Down") == 0) { + tr = WL_OUTPUT_TRANSFORM_180; + } else if (strcmp(orientation, "Right Side Up") == 0) { + tr = WL_OUTPUT_TRANSFORM_270; + } else { + wlr_drm_conn_log(conn, WLR_ERROR, "Unknown panel orientation: %s", orientation); + tr = WL_OUTPUT_TRANSFORM_NORMAL; + } + + free(orientation); + return tr; +} + +static const int32_t subpixel_map[] = { + [DRM_MODE_SUBPIXEL_UNKNOWN] = WL_OUTPUT_SUBPIXEL_UNKNOWN, + [DRM_MODE_SUBPIXEL_HORIZONTAL_RGB] = WL_OUTPUT_SUBPIXEL_HORIZONTAL_RGB, + [DRM_MODE_SUBPIXEL_HORIZONTAL_BGR] = WL_OUTPUT_SUBPIXEL_HORIZONTAL_BGR, + [DRM_MODE_SUBPIXEL_VERTICAL_RGB] = WL_OUTPUT_SUBPIXEL_VERTICAL_RGB, + [DRM_MODE_SUBPIXEL_VERTICAL_BGR] = WL_OUTPUT_SUBPIXEL_VERTICAL_BGR, + [DRM_MODE_SUBPIXEL_NONE] = WL_OUTPUT_SUBPIXEL_NONE, +}; + +static void dealloc_crtc(struct wlr_drm_connector *conn) { + if (conn->crtc == NULL) { + return; + } + + wlr_drm_conn_log(conn, WLR_DEBUG, "De-allocating CRTC %" PRIu32, + conn->crtc->id); + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, false); + if (!drm_connector_commit_state(conn, &state, false)) { + // On GPU unplug, disabling the CRTC can fail with EPERM + wlr_drm_conn_log(conn, WLR_ERROR, "Failed to disable CRTC %"PRIu32, + conn->crtc->id); + } + wlr_output_state_finish(&state); +} + +static void format_nullable_crtc(char *str, size_t size, struct wlr_drm_crtc *crtc) { + if (crtc != NULL) { + snprintf(str, size, "CRTC %"PRIu32, crtc->id); + } else { + snprintf(str, size, "no CRTC"); + } +} + +static void realloc_crtcs(struct wlr_drm_backend *drm, + struct wlr_drm_connector *want_conn) { + assert(drm->num_crtcs > 0); + + size_t num_connectors = wl_list_length(&drm->connectors); + if (num_connectors == 0) { + return; + } + + wlr_log(WLR_DEBUG, "Reallocating CRTCs"); + + struct wlr_drm_connector *connectors[num_connectors]; + uint32_t connector_constraints[num_connectors]; + uint32_t previous_match[drm->num_crtcs]; + uint32_t new_match[drm->num_crtcs]; + + for (size_t i = 0; i < drm->num_crtcs; ++i) { + previous_match[i] = UNMATCHED; + } + + size_t i = 0; + struct wlr_drm_connector *conn; + wl_list_for_each(conn, &drm->connectors, link) { + connectors[i] = conn; + + if (conn->crtc) { + previous_match[conn->crtc - drm->crtcs] = i; + } + + // Only request a CRTC if the connected is currently enabled or it's the + // connector the user wants to enable + bool want_crtc = conn == want_conn || conn->output.enabled; + + if (conn->status == DRM_MODE_CONNECTED && want_crtc) { + connector_constraints[i] = conn->possible_crtcs; + } else { + // Will always fail to match anything + connector_constraints[i] = 0; + } + + ++i; + } + + match_connectors_with_crtcs(num_connectors, connector_constraints, + drm->num_crtcs, previous_match, new_match); + + // Converts our crtc=>connector result into a connector=>crtc one. + struct wlr_drm_crtc *connector_match[num_connectors]; + for (size_t i = 0 ; i < num_connectors; ++i) { + connector_match[i] = NULL; + } + for (size_t i = 0; i < drm->num_crtcs; ++i) { + if (new_match[i] != UNMATCHED) { + connector_match[new_match[i]] = &drm->crtcs[i]; + } + } + + for (size_t i = 0; i < num_connectors; ++i) { + struct wlr_drm_connector *conn = connectors[i]; + struct wlr_drm_crtc *new_crtc = connector_match[i]; + + char old_crtc_str[16], new_crtc_str[16]; + format_nullable_crtc(old_crtc_str, sizeof(old_crtc_str), conn->crtc); + format_nullable_crtc(new_crtc_str, sizeof(new_crtc_str), new_crtc); + + char crtc_str[64]; + if (conn->crtc != new_crtc) { + snprintf(crtc_str, sizeof(crtc_str), "%s → %s", old_crtc_str, new_crtc_str); + } else { + snprintf(crtc_str, sizeof(crtc_str), "%s (no change)", new_crtc_str); + } + + wlr_log(WLR_DEBUG, " Connector %s (%s%s): %s", + conn->name, drm_connector_status_str(conn->status), + connector_constraints[i] != 0 ? ", needs CRTC" : "", + crtc_str); + } + + // Refuse to remove a CRTC from an enabled connector, and refuse to + // change the CRTC of an enabled connector. + for (size_t i = 0; i < num_connectors; ++i) { + struct wlr_drm_connector *conn = connectors[i]; + if (conn->status != DRM_MODE_CONNECTED || !conn->output.enabled) { + continue; + } + if (connector_match[i] == NULL) { + wlr_log(WLR_DEBUG, "Could not match a CRTC for previously connected output; " + "keeping old configuration"); + return; + } + assert(conn->crtc != NULL); + if (connector_match[i] != conn->crtc) { + wlr_log(WLR_DEBUG, "Cannot switch CRTC for enabled output; " + "keeping old configuration"); + return; + } + } + + // Apply new configuration + for (size_t i = 0; i < num_connectors; ++i) { + struct wlr_drm_connector *conn = connectors[i]; + + if (conn->crtc != NULL && connector_match[i]) { + // We don't need to change anything + continue; + } + + dealloc_crtc(conn); + if (connector_match[i] != NULL) { + conn->crtc = connector_match[i]; + } + } +} + +static struct wlr_drm_crtc *connector_get_current_crtc( + struct wlr_drm_connector *wlr_conn, const drmModeConnector *drm_conn) { + struct wlr_drm_backend *drm = wlr_conn->backend; + + uint32_t crtc_id = 0; + if (wlr_conn->props.crtc_id != 0) { + uint64_t value; + if (!get_drm_prop(drm->fd, wlr_conn->id, + wlr_conn->props.crtc_id, &value)) { + wlr_drm_conn_log(wlr_conn, WLR_ERROR, + "Failed to get CRTC_ID connector property"); + return NULL; + } + crtc_id = (uint32_t)value; + } else if (drm_conn->encoder_id != 0) { + // Fallback to the legacy API + drmModeEncoder *enc = drmModeGetEncoder(drm->fd, drm_conn->encoder_id); + if (enc == NULL) { + wlr_drm_conn_log(wlr_conn, WLR_ERROR, + "drmModeGetEncoder() failed"); + return NULL; + } + crtc_id = enc->crtc_id; + drmModeFreeEncoder(enc); + } + if (crtc_id == 0) { + return NULL; + } + + for (size_t i = 0; i < drm->num_crtcs; ++i) { + if (drm->crtcs[i].id == crtc_id) { + return &drm->crtcs[i]; + } + } + + wlr_drm_conn_log(wlr_conn, WLR_ERROR, + "Failed to find current CRTC ID %" PRIu32, crtc_id); + return NULL; +} + +static struct wlr_drm_connector *create_drm_connector(struct wlr_drm_backend *drm, + const drmModeConnector *drm_conn) { + struct wlr_drm_connector *wlr_conn = calloc(1, sizeof(*wlr_conn)); + if (!wlr_conn) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + + wlr_conn->backend = drm; + wlr_conn->status = DRM_MODE_DISCONNECTED; + wlr_conn->id = drm_conn->connector_id; + + if (!get_drm_connector_props(drm->fd, wlr_conn->id, &wlr_conn->props)) { + free(wlr_conn); + return NULL; + } + + const char *conn_type_name = + drmModeGetConnectorTypeName(drm_conn->connector_type); + if (conn_type_name == NULL) { + conn_type_name = "Unknown"; + } + + snprintf(wlr_conn->name, sizeof(wlr_conn->name), + "%s-%"PRIu32, conn_type_name, drm_conn->connector_type_id); + + wlr_conn->possible_crtcs = + drmModeConnectorGetPossibleCrtcs(drm->fd, drm_conn); + if (wlr_conn->possible_crtcs == 0) { + wlr_drm_conn_log(wlr_conn, WLR_ERROR, "No CRTC possible"); + } + + wlr_conn->crtc = connector_get_current_crtc(wlr_conn, drm_conn); + + wl_list_insert(drm->connectors.prev, &wlr_conn->link); + return wlr_conn; +} + +static drmModeModeInfo *connector_get_current_mode(struct wlr_drm_connector *wlr_conn) { + struct wlr_drm_backend *drm = wlr_conn->backend; + + if (wlr_conn->crtc == NULL) { + return NULL; + } + + if (wlr_conn->crtc->props.mode_id != 0) { + size_t size = 0; + drmModeModeInfo *mode = get_drm_prop_blob(drm->fd, wlr_conn->crtc->id, + wlr_conn->crtc->props.mode_id, &size); + assert(mode == NULL || size == sizeof(*mode)); + return mode; + } else { + // Fallback to the legacy API + drmModeCrtc *drm_crtc = drmModeGetCrtc(drm->fd, wlr_conn->crtc->id); + if (drm_crtc == NULL) { + wlr_log_errno(WLR_ERROR, "drmModeGetCrtc failed"); + return NULL; + } + if (!drm_crtc->mode_valid) { + drmModeFreeCrtc(drm_crtc); + return NULL; + } + drmModeModeInfo *mode = malloc(sizeof(*mode)); + if (mode == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + drmModeFreeCrtc(drm_crtc); + return NULL; + } + *mode = drm_crtc->mode; + drmModeFreeCrtc(drm_crtc); + return mode; + } +} + +static bool connect_drm_connector(struct wlr_drm_connector *wlr_conn, + const drmModeConnector *drm_conn) { + struct wlr_drm_backend *drm = wlr_conn->backend; + struct wlr_output *output = &wlr_conn->output; + + wlr_log(WLR_DEBUG, "Current CRTC: %d", + wlr_conn->crtc ? (int)wlr_conn->crtc->id : -1); + + // keep track of all the modes ourselves first. We must only fill out + // the modes list after wlr_output_init() + struct wl_list modes; + wl_list_init(&modes); + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, wlr_conn->crtc != NULL); + + drmModeModeInfo *current_modeinfo = connector_get_current_mode(wlr_conn); + + wlr_log(WLR_INFO, "Detected modes:"); + + bool found_current_mode = false; + for (int i = 0; i < drm_conn->count_modes; ++i) { + if (drm_conn->modes[i].flags & DRM_MODE_FLAG_INTERLACE) { + continue; + } + + struct wlr_drm_mode *mode = drm_mode_create(&drm_conn->modes[i]); + if (!mode) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + free(current_modeinfo); + wlr_output_state_finish(&state); + return false; + } + + // If this is the current mode set on the conn's crtc, + // then set it as the conn's output current mode. + if (current_modeinfo != NULL && memcmp(&mode->drm_mode, + current_modeinfo, sizeof(*current_modeinfo)) == 0) { + wlr_output_state_set_mode(&state, &mode->wlr_mode); + found_current_mode = true; + } + + wlr_log(WLR_INFO, " %"PRId32"x%"PRId32" @ %.3f Hz %s", + mode->wlr_mode.width, mode->wlr_mode.height, + (float)mode->wlr_mode.refresh / 1000, + mode->wlr_mode.preferred ? "(preferred)" : ""); + + wl_list_insert(modes.prev, &mode->wlr_mode.link); + } + + if (current_modeinfo != NULL) { + int32_t refresh = calculate_refresh_rate(current_modeinfo); + + if (!found_current_mode) { + wlr_output_state_set_custom_mode(&state, + current_modeinfo->hdisplay, current_modeinfo->vdisplay, refresh); + } + + uint64_t mode_id = 0; + get_drm_prop(drm->fd, wlr_conn->crtc->id, + wlr_conn->crtc->props.mode_id, &mode_id); + + wlr_conn->crtc->own_mode_id = false; + wlr_conn->crtc->mode_id = mode_id; + wlr_conn->refresh = refresh; + } + + free(current_modeinfo); + + wlr_output_init(output, &drm->backend, &output_impl, drm->session->event_loop, &state); + wlr_output_state_finish(&state); + + // fill out the modes + wl_list_insert_list(&output->modes, &modes); + + wlr_output_set_name(output, wlr_conn->name); + + output->phys_width = drm_conn->mmWidth; + output->phys_height = drm_conn->mmHeight; + wlr_log(WLR_INFO, "Physical size: %"PRId32"x%"PRId32, + output->phys_width, output->phys_height); + if (drm_conn->subpixel < sizeof(subpixel_map) / sizeof(subpixel_map[0])) { + output->subpixel = subpixel_map[drm_conn->subpixel]; + } else { + wlr_log(WLR_ERROR, "Unknown subpixel value: %d", (int)drm_conn->subpixel); + } + + uint64_t non_desktop; + if (get_drm_prop(drm->fd, wlr_conn->id, + wlr_conn->props.non_desktop, &non_desktop)) { + if (non_desktop == 1) { + wlr_log(WLR_INFO, "Non-desktop connector"); + } + output->non_desktop = non_desktop; + } + + memset(wlr_conn->max_bpc_bounds, 0, sizeof(wlr_conn->max_bpc_bounds)); + if (wlr_conn->props.max_bpc != 0) { + if (!introspect_drm_prop_range(drm->fd, wlr_conn->props.max_bpc, + &wlr_conn->max_bpc_bounds[0], &wlr_conn->max_bpc_bounds[1])) { + wlr_log(WLR_ERROR, "Failed to introspect 'max bpc' property"); + } + } + + uint64_t vrr_capable = 0; + if (wlr_conn->props.vrr_capable != 0) { + get_drm_prop(drm->fd, wlr_conn->id, wlr_conn->props.vrr_capable, &vrr_capable); + } + output->adaptive_sync_supported = vrr_capable; + + size_t edid_len = 0; + uint8_t *edid = get_drm_prop_blob(drm->fd, + wlr_conn->id, wlr_conn->props.edid, &edid_len); + if (edid_len > 0) { + parse_edid(wlr_conn, edid_len, edid); + } else { + wlr_log(WLR_DEBUG, "Connector has no EDID"); + } + free(edid); + + char *subconnector = NULL; + if (wlr_conn->props.subconnector) { + subconnector = get_drm_prop_enum(drm->fd, + wlr_conn->id, wlr_conn->props.subconnector); + } + if (subconnector && strcmp(subconnector, "Native") == 0) { + free(subconnector); + subconnector = NULL; + } + + char description[128]; + snprintf(description, sizeof(description), "%s %s%s%s (%s%s%s)", + output->make, output->model, + output->serial ? " " : "", + output->serial ? output->serial : "", + output->name, + subconnector ? " via " : "", + subconnector ? subconnector : ""); + wlr_output_set_description(output, description); + + free(subconnector); + wlr_conn->status = DRM_MODE_CONNECTED; + return true; +} + +static void disconnect_drm_connector(struct wlr_drm_connector *conn); + +void scan_drm_connectors(struct wlr_drm_backend *drm, + struct wlr_device_hotplug_event *event) { + if (event != NULL && event->connector_id != 0) { + wlr_log(WLR_INFO, "Scanning DRM connector %"PRIu32" on %s", + event->connector_id, drm->name); + } else { + wlr_log(WLR_INFO, "Scanning DRM connectors on %s", drm->name); + } + + drmModeRes *res = drmModeGetResources(drm->fd); + if (!res) { + wlr_log_errno(WLR_ERROR, "Failed to get DRM resources"); + return; + } + + size_t seen_len = wl_list_length(&drm->connectors); + // +1 so length can never be 0, which is undefined behaviour. + // Last element isn't used. + bool seen[seen_len + 1]; + memset(seen, false, sizeof(seen)); + size_t new_outputs_len = 0; + struct wlr_drm_connector *new_outputs[res->count_connectors + 1]; + + for (int i = 0; i < res->count_connectors; ++i) { + uint32_t conn_id = res->connectors[i]; + + ssize_t index = -1; + struct wlr_drm_connector *c, *wlr_conn = NULL; + wl_list_for_each(c, &drm->connectors, link) { + index++; + if (c->id == conn_id) { + wlr_conn = c; + break; + } + } + + if (wlr_conn && wlr_conn->lease) { + continue; + } + + // If the hotplug event contains a connector ID, ignore any other + // connector. + if (event != NULL && event->connector_id != 0 && + event->connector_id != conn_id) { + if (wlr_conn != NULL) { + seen[index] = true; + } + continue; + } + + drmModeConnector *drm_conn = drmModeGetConnector(drm->fd, conn_id); + if (!drm_conn) { + wlr_log_errno(WLR_ERROR, "Failed to get DRM connector"); + continue; + } + + if (!wlr_conn) { + wlr_conn = create_drm_connector(drm, drm_conn); + if (wlr_conn == NULL) { + continue; + } + wlr_log(WLR_INFO, "Found connector '%s'", wlr_conn->name); + } else { + seen[index] = true; + } + + // This can only happen *after* hotplug, since we haven't read the + // connector properties yet + if (wlr_conn->props.link_status != 0) { + uint64_t link_status; + if (!get_drm_prop(drm->fd, wlr_conn->id, + wlr_conn->props.link_status, &link_status)) { + wlr_drm_conn_log(wlr_conn, WLR_ERROR, + "Failed to get link status prop"); + continue; + } + + if (link_status == DRM_MODE_LINK_STATUS_BAD) { + // We need to reload our list of modes and force a modeset + wlr_drm_conn_log(wlr_conn, WLR_INFO, "Bad link detected"); + disconnect_drm_connector(wlr_conn); + } + } + + if (wlr_conn->status == DRM_MODE_DISCONNECTED && + drm_conn->connection == DRM_MODE_CONNECTED) { + wlr_log(WLR_INFO, "'%s' connected", wlr_conn->name); + if (!connect_drm_connector(wlr_conn, drm_conn)) { + wlr_drm_conn_log(wlr_conn, WLR_ERROR, "Failed to connect DRM connector"); + continue; + } + new_outputs[new_outputs_len++] = wlr_conn; + } else if (wlr_conn->status == DRM_MODE_CONNECTED && + drm_conn->connection != DRM_MODE_CONNECTED) { + wlr_log(WLR_INFO, "'%s' disconnected", wlr_conn->name); + disconnect_drm_connector(wlr_conn); + } + + drmModeFreeConnector(drm_conn); + } + + drmModeFreeResources(res); + + // Iterate in reverse order because we'll remove items from the list and + // still want indices to remain correct. + struct wlr_drm_connector *conn, *tmp_conn; + size_t index = wl_list_length(&drm->connectors); + wl_list_for_each_reverse_safe(conn, tmp_conn, &drm->connectors, link) { + index--; + if (index >= seen_len || seen[index]) { + continue; + } + + wlr_log(WLR_INFO, "'%s' disappeared", conn->name); + destroy_drm_connector(conn); + } + + for (size_t i = 0; i < new_outputs_len; ++i) { + struct wlr_drm_connector *conn = new_outputs[i]; + + wlr_drm_conn_log(conn, WLR_INFO, "Requesting modeset"); + wl_signal_emit_mutable(&drm->backend.events.new_output, + &conn->output); + } +} + +void scan_drm_leases(struct wlr_drm_backend *drm) { + drmModeLesseeListRes *list = drmModeListLessees(drm->fd); + if (list == NULL) { + wlr_log_errno(WLR_ERROR, "drmModeListLessees failed"); + return; + } + + struct wlr_drm_connector *conn; + wl_list_for_each(conn, &drm->connectors, link) { + if (conn->lease == NULL) { + continue; + } + + bool found = false; + for (size_t i = 0; i < list->count; i++) { + if (list->lessees[i] == conn->lease->lessee_id) { + found = true; + break; + } + } + if (!found) { + wlr_log(WLR_DEBUG, "DRM lease %"PRIu32" has been terminated", + conn->lease->lessee_id); + drm_lease_destroy(conn->lease); + } + } + + drmFree(list); +} + +bool commit_drm_device(struct wlr_drm_backend *drm, + const struct wlr_backend_output_state *output_states, size_t output_states_len, + bool test_only) { + if (!drm->session->active) { + return false; + } + + struct wlr_drm_connector_state *conn_states = calloc(output_states_len, sizeof(conn_states[0])); + if (conn_states == NULL) { + return false; + } + + bool ok = false; + bool modeset = false; + size_t conn_states_len = 0; + for (size_t i = 0; i < output_states_len; i++) { + const struct wlr_backend_output_state *output_state = &output_states[i]; + struct wlr_output *output = output_state->output; + if (!output->enabled && !output_pending_enabled(output, &output_state->base)) { + // KMS rejects commits which disable already-disabled connectors + // and have the DRM_MODE_PAGE_FLIP_EVENT flag + continue; + } + + struct wlr_drm_connector *conn = get_drm_connector_from_output(output); + + if (output_pending_enabled(output, &output_state->base) && !drm_connector_alloc_crtc(conn)) { + wlr_drm_conn_log(conn, WLR_DEBUG, + "No CRTC available for this connector"); + goto out; + } + + struct wlr_drm_connector_state *conn_state = &conn_states[conn_states_len]; + drm_connector_state_init(conn_state, conn, &output_state->base); + conn_states_len++; + + if (!drm_connector_prepare(conn_state, test_only)) { + goto out; + } + + if (output_state->base.tearing_page_flip) { + wlr_log(WLR_DEBUG, "Tearing not supported for DRM device-wide commits"); + goto out; + } + + modeset |= output_state->base.allow_reconfiguration; + } + + if (test_only && drm->mgpu_renderer.wlr_rend) { + // If we're running as a secondary GPU, we can't perform an atomic + // commit without blitting a buffer. + ok = true; + goto out; + } + + uint32_t flags = 0; + if (!test_only) { + flags |= DRM_MODE_PAGE_FLIP_EVENT; + } + struct wlr_drm_device_state dev_state = { + .modeset = modeset, + .connectors = conn_states, + .connectors_len = conn_states_len, + }; + ok = drm_commit(drm, &dev_state, flags, test_only); + +out: + for (size_t i = 0; i < conn_states_len; i++) { + drm_connector_state_finish(&conn_states[i]); + } + free(conn_states); + return ok; +} + +static int mhz_to_nsec(int mhz) { + return 1000000000000LL / mhz; +} + +static void handle_page_flip(int fd, unsigned seq, + unsigned tv_sec, unsigned tv_usec, unsigned crtc_id, void *data) { + struct wlr_drm_page_flip *page_flip = data; + + struct wlr_drm_connector *conn = drm_page_flip_pop(page_flip, crtc_id); + if (conn != NULL) { + conn->pending_page_flip = NULL; + } + + uint32_t present_flags = WLR_OUTPUT_PRESENT_HW_CLOCK | WLR_OUTPUT_PRESENT_HW_COMPLETION; + if (!page_flip->async) { + present_flags |= WLR_OUTPUT_PRESENT_VSYNC; + } + + if (page_flip->connectors_len == 0) { + drm_page_flip_destroy(page_flip); + } + + if (conn == NULL) { + return; + } + + struct wlr_drm_backend *drm = conn->backend; + + if (conn->status != DRM_MODE_CONNECTED || conn->crtc == NULL) { + wlr_drm_conn_log(conn, WLR_DEBUG, + "Ignoring page-flip event for disabled connector"); + return; + } + + struct wlr_drm_plane *plane = conn->crtc->primary; + if (plane->queued_fb) { + drm_fb_move(&plane->current_fb, &plane->queued_fb); + if (plane->current_release_timeline != NULL) { + wlr_drm_syncobj_timeline_signal(plane->current_release_timeline, plane->current_release_point); + wlr_drm_syncobj_timeline_unref(plane->current_release_timeline); + } + plane->current_release_timeline = plane->queued_release_timeline; + plane->current_release_point = plane->queued_release_point; + plane->queued_release_timeline = NULL; + plane->queued_release_point = 0; + } + if (conn->crtc->cursor && conn->crtc->cursor->queued_fb) { + drm_fb_move(&conn->crtc->cursor->current_fb, + &conn->crtc->cursor->queued_fb); + } + + struct wlr_drm_layer *layer; + wl_list_for_each(layer, &conn->crtc->layers, link) { + drm_fb_move(&layer->current_fb, &layer->queued_fb); + } + + /* Don't report ZERO_COPY in multi-gpu situations, because we had to copy + * data between the GPUs, even if we were using the direct scanout + * interface. + */ + if (!drm->mgpu_renderer.wlr_rend) { + present_flags |= WLR_OUTPUT_PRESENT_ZERO_COPY; + } + + struct wlr_output_event_present present_event = { + /* The DRM backend guarantees that the presentation event will be for + * the last submitted frame. */ + .commit_seq = conn->output.commit_seq, + .presented = drm->session->active, + .when = { + .tv_sec = tv_sec, + .tv_nsec = tv_usec * 1000, + }, + .seq = seq, + .refresh = mhz_to_nsec(conn->refresh), + .flags = present_flags, + }; + wlr_output_send_present(&conn->output, &present_event); + + if (drm->session->active) { + wlr_output_send_frame(&conn->output); + } +} + +int handle_drm_event(int fd, uint32_t mask, void *data) { + struct wlr_drm_backend *drm = data; + + drmEventContext event = { + .version = 3, + .page_flip_handler2 = handle_page_flip, + }; + + if (drmHandleEvent(fd, &event) != 0) { + wlr_log(WLR_ERROR, "drmHandleEvent failed"); + wlr_backend_destroy(&drm->backend); + } + return 1; +} + +static void disconnect_drm_connector(struct wlr_drm_connector *conn) { + if (conn->status == DRM_MODE_DISCONNECTED) { + return; + } + + // This will cleanup the compositor-facing wlr_output, but won't destroy + // our wlr_drm_connector. + wlr_output_destroy(&conn->output); + + assert(conn->status == DRM_MODE_DISCONNECTED); +} + +void destroy_drm_connector(struct wlr_drm_connector *conn) { + disconnect_drm_connector(conn); + + wl_list_remove(&conn->link); + free(conn); +} + +int wlr_drm_backend_get_non_master_fd(struct wlr_backend *backend) { + assert(backend); + + struct wlr_drm_backend *drm = get_drm_backend_from_backend(backend); + int fd = open(drm->name, O_RDWR | O_CLOEXEC); + + if (fd < 0) { + wlr_log_errno(WLR_ERROR, "Unable to clone DRM fd for client fd"); + return -1; + } + + if (drmIsMaster(fd) && drmDropMaster(fd) < 0) { + wlr_log_errno(WLR_ERROR, "Failed to drop master"); + close(fd); + return -1; + } + + return fd; +} + +struct wlr_drm_lease *wlr_drm_create_lease(struct wlr_output **outputs, + size_t n_outputs, int *lease_fd_ptr) { + assert(outputs); + + if (n_outputs == 0) { + wlr_log(WLR_ERROR, "Can't lease 0 outputs"); + return NULL; + } + + struct wlr_drm_backend *drm = + get_drm_backend_from_backend(outputs[0]->backend); + + int n_objects = 0; + uint32_t objects[4 * n_outputs + 1]; + for (size_t i = 0; i < n_outputs; ++i) { + struct wlr_drm_connector *conn = + get_drm_connector_from_output(outputs[i]); + assert(conn->lease == NULL); + + if (conn->backend != drm) { + wlr_log(WLR_ERROR, "Can't lease output from different backends"); + return NULL; + } + + objects[n_objects++] = conn->id; + wlr_log(WLR_DEBUG, "Connector %d", conn->id); + + if (!drm_connector_alloc_crtc(conn)) { + wlr_log(WLR_ERROR, "Failed to allocate connector CRTC"); + return NULL; + } + + objects[n_objects++] = conn->crtc->id; + wlr_log(WLR_DEBUG, "CRTC %d", conn->crtc->id); + + objects[n_objects++] = conn->crtc->primary->id; + wlr_log(WLR_DEBUG, "Primary plane %d", conn->crtc->primary->id); + + if (conn->crtc->cursor) { + wlr_log(WLR_DEBUG, "Cursor plane %d", conn->crtc->cursor->id); + objects[n_objects++] = conn->crtc->cursor->id; + } + } + + assert(n_objects != 0); + + struct wlr_drm_lease *lease = calloc(1, sizeof(*lease)); + if (lease == NULL) { + return NULL; + } + + lease->backend = drm; + wl_signal_init(&lease->events.destroy); + + wlr_log(WLR_DEBUG, "Issuing DRM lease with %d objects", n_objects); + int lease_fd = drmModeCreateLease(drm->fd, objects, n_objects, O_CLOEXEC, + &lease->lessee_id); + if (lease_fd < 0) { + free(lease); + return NULL; + } + *lease_fd_ptr = lease_fd; + + wlr_log(WLR_DEBUG, "Issued DRM lease %"PRIu32, lease->lessee_id); + for (size_t i = 0; i < n_outputs; ++i) { + struct wlr_drm_connector *conn = + get_drm_connector_from_output(outputs[i]); + conn->lease = lease; + conn->crtc->lease = lease; + disconnect_drm_connector(conn); + } + + return lease; +} + +void wlr_drm_lease_terminate(struct wlr_drm_lease *lease) { + struct wlr_drm_backend *drm = lease->backend; + + wlr_log(WLR_DEBUG, "Terminating DRM lease %d", lease->lessee_id); + int ret = drmModeRevokeLease(drm->fd, lease->lessee_id); + if (ret < 0) { + wlr_log_errno(WLR_ERROR, "Failed to terminate lease"); + } + + drm_lease_destroy(lease); +} + +void drm_lease_destroy(struct wlr_drm_lease *lease) { + struct wlr_drm_backend *drm = lease->backend; + + wl_signal_emit_mutable(&lease->events.destroy, NULL); + + assert(wl_list_empty(&lease->events.destroy.listener_list)); + + struct wlr_drm_connector *conn; + wl_list_for_each(conn, &drm->connectors, link) { + if (conn->lease == lease) { + conn->lease = NULL; + } + } + + for (size_t i = 0; i < drm->num_crtcs; ++i) { + if (drm->crtcs[i].lease == lease) { + drm->crtcs[i].lease = NULL; + } + } + + free(lease); + scan_drm_connectors(drm, NULL); +} diff --git a/3rdparty/wlroots/backend/drm/fb.c b/3rdparty/wlroots/backend/drm/fb.c new file mode 100644 index 0000000000..575f32d91a --- /dev/null +++ b/3rdparty/wlroots/backend/drm/fb.c @@ -0,0 +1,258 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "backend/drm/drm.h" +#include "backend/drm/fb.h" +#include "render/pixel_format.h" + +void drm_fb_clear(struct wlr_drm_fb **fb_ptr) { + if (*fb_ptr == NULL) { + return; + } + + struct wlr_drm_fb *fb = *fb_ptr; + wlr_buffer_unlock(fb->wlr_buf); // may destroy the buffer + + *fb_ptr = NULL; +} + +struct wlr_drm_fb *drm_fb_lock(struct wlr_drm_fb *fb) { + wlr_buffer_lock(fb->wlr_buf); + return fb; +} + +static void drm_fb_handle_destroy(struct wlr_addon *addon) { + struct wlr_drm_fb *fb = wl_container_of(addon, fb, addon); + drm_fb_destroy(fb); +} + +static const struct wlr_addon_interface fb_addon_impl = { + .name = "wlr_drm_fb", + .destroy = drm_fb_handle_destroy, +}; + +static uint32_t get_fb_for_bo(struct wlr_drm_backend *drm, + struct wlr_dmabuf_attributes *dmabuf, uint32_t handles[static 4]) { + uint64_t modifiers[4] = {0}; + for (int i = 0; i < dmabuf->n_planes; i++) { + // KMS requires all BO planes to have the same modifier + modifiers[i] = dmabuf->modifier; + } + + uint32_t id = 0; + if (drm->addfb2_modifiers && dmabuf->modifier != DRM_FORMAT_MOD_INVALID) { + if (drmModeAddFB2WithModifiers(drm->fd, dmabuf->width, dmabuf->height, + dmabuf->format, handles, dmabuf->stride, dmabuf->offset, + modifiers, &id, DRM_MODE_FB_MODIFIERS) != 0) { + wlr_log_errno(WLR_DEBUG, "drmModeAddFB2WithModifiers failed"); + } + } else { + if (dmabuf->modifier != DRM_FORMAT_MOD_INVALID && + dmabuf->modifier != DRM_FORMAT_MOD_LINEAR) { + wlr_log(WLR_ERROR, "Cannot import DRM framebuffer with explicit " + "modifier 0x%"PRIX64, dmabuf->modifier); + return 0; + } + + int ret = drmModeAddFB2(drm->fd, dmabuf->width, dmabuf->height, + dmabuf->format, handles, dmabuf->stride, dmabuf->offset, &id, 0); + if (ret != 0 && dmabuf->format == DRM_FORMAT_ARGB8888 && + dmabuf->n_planes == 1 && dmabuf->offset[0] == 0) { + // Some big-endian machines don't support drmModeAddFB2. Try a + // last-resort fallback for ARGB8888 buffers, like Xorg's + // modesetting driver does. + wlr_log(WLR_DEBUG, "drmModeAddFB2 failed (%s), falling back to " + "legacy drmModeAddFB", strerror(-ret)); + + uint32_t depth = 32; + uint32_t bpp = 32; + ret = drmModeAddFB(drm->fd, dmabuf->width, dmabuf->height, depth, + bpp, dmabuf->stride[0], handles[0], &id); + if (ret != 0) { + wlr_log_errno(WLR_DEBUG, "drmModeAddFB failed"); + } + } else if (ret != 0) { + wlr_log_errno(WLR_DEBUG, "drmModeAddFB2 failed"); + } + } + + return id; +} + +static void close_all_bo_handles(struct wlr_drm_backend *drm, + uint32_t handles[static 4]) { + for (int i = 0; i < 4; ++i) { + if (handles[i] == 0) { + continue; + } + + // If multiple planes share the same BO handle, avoid double-closing it + bool already_closed = false; + for (int j = 0; j < i; ++j) { + if (handles[i] == handles[j]) { + already_closed = true; + break; + } + } + if (already_closed) { + continue; + } + + if (drmCloseBufferHandle(drm->fd, handles[i]) != 0) { + wlr_log_errno(WLR_ERROR, "drmCloseBufferHandle failed"); + } + } +} + +static void drm_poisoned_fb_handle_destroy(struct wlr_addon *addon) { + wlr_addon_finish(addon); + free(addon); +} + +static const struct wlr_addon_interface poisoned_fb_addon_impl = { + .name = "wlr_drm_poisoned_fb", + .destroy = drm_poisoned_fb_handle_destroy, +}; + +static bool is_buffer_poisoned(struct wlr_drm_backend *drm, + struct wlr_buffer *buf) { + return wlr_addon_find(&buf->addons, drm, &poisoned_fb_addon_impl) != NULL; +} + +/** + * Mark the buffer as "poisoned", ie. it cannot be imported into KMS. This + * allows us to avoid repeatedly trying to import it when it's not + * scanout-capable. + */ +static void poison_buffer(struct wlr_drm_backend *drm, + struct wlr_buffer *buf) { + struct wlr_addon *addon = calloc(1, sizeof(*addon)); + if (addon == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return; + } + wlr_addon_init(addon, &buf->addons, drm, &poisoned_fb_addon_impl); + wlr_log(WLR_DEBUG, "Poisoning buffer"); +} + +static struct wlr_drm_fb *drm_fb_create(struct wlr_drm_backend *drm, + struct wlr_buffer *buf, const struct wlr_drm_format_set *formats) { + struct wlr_dmabuf_attributes attribs; + if (!wlr_buffer_get_dmabuf(buf, &attribs)) { + wlr_log(WLR_DEBUG, "Failed to get DMA-BUF from buffer"); + return NULL; + } + + if (is_buffer_poisoned(drm, buf)) { + wlr_log(WLR_DEBUG, "Buffer is poisoned"); + return NULL; + } + + struct wlr_drm_fb *fb = calloc(1, sizeof(*fb)); + if (!fb) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + + if (formats && !wlr_drm_format_set_has(formats, attribs.format, + attribs.modifier)) { + // The format isn't supported by the plane. Try stripping the alpha + // channel, if any. + const struct wlr_pixel_format_info *info = + drm_get_pixel_format_info(attribs.format); + if (info != NULL && info->opaque_substitute != DRM_FORMAT_INVALID && + wlr_drm_format_set_has(formats, info->opaque_substitute, attribs.modifier)) { + attribs.format = info->opaque_substitute; + } else { + wlr_log(WLR_DEBUG, "Buffer format 0x%"PRIX32" with modifier " + "0x%"PRIX64" cannot be scanned out", + attribs.format, attribs.modifier); + goto error_fb; + } + } + + uint32_t handles[4] = {0}; + for (int i = 0; i < attribs.n_planes; ++i) { + int ret = drmPrimeFDToHandle(drm->fd, attribs.fd[i], &handles[i]); + if (ret != 0) { + wlr_log_errno(WLR_DEBUG, "drmPrimeFDToHandle failed"); + goto error_bo_handle; + } + } + + fb->id = get_fb_for_bo(drm, &attribs, handles); + if (!fb->id) { + wlr_log(WLR_DEBUG, "Failed to import BO in KMS"); + poison_buffer(drm, buf); + goto error_bo_handle; + } + + close_all_bo_handles(drm, handles); + + fb->backend = drm; + fb->wlr_buf = buf; + + wlr_addon_init(&fb->addon, &buf->addons, drm, &fb_addon_impl); + wl_list_insert(&drm->fbs, &fb->link); + + return fb; + +error_bo_handle: + close_all_bo_handles(drm, handles); +error_fb: + free(fb); + return NULL; +} + +void drm_fb_destroy(struct wlr_drm_fb *fb) { + struct wlr_drm_backend *drm = fb->backend; + + wl_list_remove(&fb->link); + wlr_addon_finish(&fb->addon); + + int ret = drmModeCloseFB(drm->fd, fb->id); + if (ret == -EINVAL) { + ret = drmModeRmFB(drm->fd, fb->id); + } + if (ret != 0) { + wlr_log(WLR_ERROR, "Failed to close FB: %s", strerror(-ret)); + } + + free(fb); +} + +bool drm_fb_import(struct wlr_drm_fb **fb_ptr, struct wlr_drm_backend *drm, + struct wlr_buffer *buf, const struct wlr_drm_format_set *formats) { + struct wlr_drm_fb *fb; + struct wlr_addon *addon = wlr_addon_find(&buf->addons, drm, &fb_addon_impl); + if (addon != NULL) { + fb = wl_container_of(addon, fb, addon); + } else { + fb = drm_fb_create(drm, buf, formats); + if (!fb) { + return false; + } + } + + wlr_buffer_lock(buf); + drm_fb_move(fb_ptr, &fb); + return true; +} + +void drm_fb_move(struct wlr_drm_fb **new, struct wlr_drm_fb **old) { + drm_fb_clear(new); + *new = *old; + *old = NULL; +} + +void drm_fb_copy(struct wlr_drm_fb **new, struct wlr_drm_fb *old) { + drm_fb_clear(new); + if (old != NULL) { + *new = drm_fb_lock(old); + } +} diff --git a/3rdparty/wlroots/backend/drm/gen_pnpids.sh b/3rdparty/wlroots/backend/drm/gen_pnpids.sh new file mode 100755 index 0000000000..5a9547ae37 --- /dev/null +++ b/3rdparty/wlroots/backend/drm/gen_pnpids.sh @@ -0,0 +1,26 @@ +#!/bin/sh -eu +# +# usage: gen_pnpids.sh < pnp.ids > pnpids.c + +gen_pnps() +{ + while read -r id vendor; do + [ "${#id}" = 3 ] || exit 1 + + printf "\tcase PNP_ID('%c', '%c', '%c'): return \"%s\";\n" \ + "$id" "${id#?}" "${id#??}" "$vendor" + done +} + +cat << EOF +#include "backend/drm/util.h" + +#define PNP_ID(a, b, c) ((a & 0x1f) << 10) | ((b & 0x1f) << 5) | (c & 0x1f) +const char *get_pnp_manufacturer(const char code[static 3]) { + switch (PNP_ID(code[0], code[1], code[2])) { +$(gen_pnps) + } + return NULL; +} +#undef PNP_ID +EOF diff --git a/3rdparty/wlroots/backend/drm/legacy.c b/3rdparty/wlroots/backend/drm/legacy.c new file mode 100644 index 0000000000..223852ec15 --- /dev/null +++ b/3rdparty/wlroots/backend/drm/legacy.c @@ -0,0 +1,286 @@ +#include +#include +#include +#include +#include +#include "backend/drm/drm.h" +#include "backend/drm/fb.h" +#include "backend/drm/iface.h" +#include "backend/drm/util.h" +#include "render/color.h" +#include "types/wlr_output.h" + +static bool legacy_fb_props_match(struct wlr_drm_fb *fb1, + struct wlr_drm_fb *fb2) { + struct wlr_dmabuf_attributes dmabuf1 = {0}, dmabuf2 = {0}; + if (!wlr_buffer_get_dmabuf(fb1->wlr_buf, &dmabuf1) || + !wlr_buffer_get_dmabuf(fb2->wlr_buf, &dmabuf2)) { + return false; + } + + if (dmabuf1.width != dmabuf2.width || + dmabuf1.height != dmabuf2.height || + dmabuf1.format != dmabuf2.format || + dmabuf1.modifier != dmabuf2.modifier || + dmabuf1.n_planes != dmabuf2.n_planes) { + return false; + } + + for (int i = 0; i < dmabuf1.n_planes; i++) { + if (dmabuf1.stride[i] != dmabuf2.stride[i] || + dmabuf1.offset[i] != dmabuf2.offset[i]) { + return false; + } + } + + return true; +} + +static bool legacy_crtc_test(const struct wlr_drm_connector_state *state, + bool modeset) { + struct wlr_drm_connector *conn = state->connector; + struct wlr_drm_crtc *crtc = conn->crtc; + + if (state->base->committed & WLR_OUTPUT_STATE_BUFFER) { + // If the size doesn't match, reject buffer (scaling is not supported) + int pending_width, pending_height; + output_pending_resolution(&state->connector->output, state->base, + &pending_width, &pending_height); + if (state->base->buffer->width != pending_width || + state->base->buffer->height != pending_height) { + wlr_log(WLR_DEBUG, "Primary buffer size mismatch"); + return false; + } + // Source crop is also not supported + struct wlr_fbox src_box; + output_state_get_buffer_src_box(state->base, &src_box); + if (src_box.x != 0.0 || src_box.y != 0.0 || + src_box.width != (double)state->base->buffer->width || + src_box.height != (double)state->base->buffer->height) { + wlr_log(WLR_DEBUG, "Source crop not supported in DRM-legacy output"); + return false; + } + + if (!modeset) { + struct wlr_drm_fb *pending_fb = state->primary_fb; + + struct wlr_drm_fb *prev_fb = crtc->primary->queued_fb; + if (!prev_fb) { + prev_fb = crtc->primary->current_fb; + } + + /* Legacy is only guaranteed to be able to display a FB if it's been + * allocated the same way as the previous one. */ + if (prev_fb != NULL && !legacy_fb_props_match(prev_fb, pending_fb)) { + wlr_drm_conn_log(conn, WLR_DEBUG, + "Cannot change scan-out buffer parameters with legacy KMS API"); + return false; + } + } + } + + return true; +} + +static bool legacy_crtc_commit(const struct wlr_drm_connector_state *state, + struct wlr_drm_page_flip *page_flip, uint32_t flags, bool modeset) { + struct wlr_drm_connector *conn = state->connector; + struct wlr_drm_backend *drm = conn->backend; + struct wlr_output *output = &conn->output; + struct wlr_drm_crtc *crtc = conn->crtc; + struct wlr_drm_plane *cursor = crtc->cursor; + + uint32_t fb_id = 0; + if (state->active) { + if (state->primary_fb == NULL) { + wlr_log(WLR_ERROR, "%s: failed to acquire primary FB", + conn->output.name); + return false; + } + fb_id = state->primary_fb->id; + } + + if (modeset) { + uint32_t *conns = NULL; + size_t conns_len = 0; + drmModeModeInfo *mode = NULL; + if (state->active) { + conns = &conn->id; + conns_len = 1; + mode = (drmModeModeInfo *)&state->mode; + } + + uint32_t dpms = state->active ? DRM_MODE_DPMS_ON : DRM_MODE_DPMS_OFF; + if (drmModeConnectorSetProperty(drm->fd, conn->id, conn->props.dpms, + dpms) != 0) { + wlr_drm_conn_log_errno(conn, WLR_ERROR, + "Failed to set DPMS property"); + return false; + } + + if (drmModeSetCrtc(drm->fd, crtc->id, fb_id, 0, 0, + conns, conns_len, mode)) { + wlr_drm_conn_log_errno(conn, WLR_ERROR, "Failed to set CRTC"); + return false; + } + } + + if (state->base->committed & WLR_OUTPUT_STATE_COLOR_TRANSFORM) { + size_t dim = 0; + uint16_t *lut = NULL; + if (state->base->color_transform != NULL) { + struct wlr_color_transform_lut_3x1d *tr = + color_transform_lut_3x1d_from_base(state->base->color_transform); + dim = tr->dim; + lut = tr->lut_3x1d; + } + + if (!drm_legacy_crtc_set_gamma(drm, crtc, dim, lut)) { + return false; + } + } + + if (state->base->committed & WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED) { + if (state->base->adaptive_sync_enabled && !output->adaptive_sync_supported) { + return false; + } + if (crtc->props.vrr_enabled != 0 && + drmModeObjectSetProperty(drm->fd, crtc->id, DRM_MODE_OBJECT_CRTC, + crtc->props.vrr_enabled, + state->base->adaptive_sync_enabled) != 0) { + wlr_drm_conn_log_errno(conn, WLR_ERROR, + "drmModeObjectSetProperty(VRR_ENABLED) failed"); + return false; + } + output->adaptive_sync_status = state->base->adaptive_sync_enabled ? + WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED : + WLR_OUTPUT_ADAPTIVE_SYNC_DISABLED; + wlr_drm_conn_log(conn, WLR_DEBUG, "VRR %s", + state->base->adaptive_sync_enabled ? "enabled" : "disabled"); + } + + if (cursor != NULL && state->active && drm_connector_is_cursor_visible(conn)) { + struct wlr_drm_fb *cursor_fb = state->cursor_fb; + if (cursor_fb == NULL) { + wlr_drm_conn_log(conn, WLR_DEBUG, "Failed to acquire cursor FB"); + return false; + } + + drmModeFB *drm_fb = drmModeGetFB(drm->fd, cursor_fb->id); + if (drm_fb == NULL) { + wlr_drm_conn_log_errno(conn, WLR_DEBUG, "Failed to get cursor " + "BO handle: drmModeGetFB failed"); + return false; + } + uint32_t cursor_handle = drm_fb->handle; + uint32_t cursor_width = drm_fb->width; + uint32_t cursor_height = drm_fb->height; + drmModeFreeFB(drm_fb); + + int ret = drmModeSetCursor(drm->fd, crtc->id, cursor_handle, + cursor_width, cursor_height); + int set_cursor_errno = errno; + if (drmCloseBufferHandle(drm->fd, cursor_handle) != 0) { + wlr_log_errno(WLR_ERROR, "drmCloseBufferHandle failed"); + } + if (ret != 0) { + wlr_drm_conn_log(conn, WLR_DEBUG, "drmModeSetCursor failed: %s", + strerror(set_cursor_errno)); + return false; + } + + if (drmModeMoveCursor(drm->fd, + crtc->id, conn->cursor_x, conn->cursor_y) != 0) { + wlr_drm_conn_log_errno(conn, WLR_ERROR, "drmModeMoveCursor failed"); + return false; + } + } else { + if (drmModeSetCursor(drm->fd, crtc->id, 0, 0, 0)) { + wlr_drm_conn_log_errno(conn, WLR_DEBUG, "drmModeSetCursor failed"); + return false; + } + } + + // Legacy uAPI doesn't support requesting page-flip events when + // turning off a CRTC + if (state->active && (flags & DRM_MODE_PAGE_FLIP_EVENT)) { + if (drmModePageFlip(drm->fd, crtc->id, fb_id, flags, page_flip)) { + wlr_drm_conn_log_errno(conn, WLR_ERROR, "drmModePageFlip failed"); + return false; + } + } + + return true; +} + +static bool legacy_commit(struct wlr_drm_backend *drm, + const struct wlr_drm_device_state *state, + struct wlr_drm_page_flip *page_flip, uint32_t flags, + bool test_only) { + for (size_t i = 0; i < state->connectors_len; i++) { + const struct wlr_drm_connector_state *conn_state = &state->connectors[i]; + if (!legacy_crtc_test(conn_state, state->modeset)) { + return false; + } + } + + if (test_only) { + return true; + } + + for (size_t i = 0; i < state->connectors_len; i++) { + const struct wlr_drm_connector_state *conn_state = &state->connectors[i]; + if (!legacy_crtc_commit(conn_state, page_flip, flags, + state->modeset)) { + return false; + } + } + + return true; +} + +static void fill_empty_gamma_table(size_t size, + uint16_t *r, uint16_t *g, uint16_t *b) { + assert(0xFFFF < UINT64_MAX / (size - 1)); + for (uint32_t i = 0; i < size; ++i) { + uint16_t val = (uint64_t)0xFFFF * i / (size - 1); + r[i] = g[i] = b[i] = val; + } +} + +bool drm_legacy_crtc_set_gamma(struct wlr_drm_backend *drm, + struct wlr_drm_crtc *crtc, size_t size, uint16_t *lut) { + uint16_t *linear_lut = NULL; + if (size == 0) { + // The legacy interface doesn't offer a way to reset the gamma LUT + size = drm_crtc_get_gamma_lut_size(drm, crtc); + if (size == 0) { + return false; + } + + linear_lut = malloc(3 * size * sizeof(uint16_t)); + if (linear_lut == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return false; + } + fill_empty_gamma_table(size, linear_lut, linear_lut + size, + linear_lut + 2 * size); + + lut = linear_lut; + } + + uint16_t *r = lut, *g = lut + size, *b = lut + 2 * size; + if (drmModeCrtcSetGamma(drm->fd, crtc->id, size, r, g, b) != 0) { + wlr_log_errno(WLR_ERROR, "Failed to set gamma LUT on CRTC %"PRIu32, + crtc->id); + free(linear_lut); + return false; + } + + free(linear_lut); + return true; +} + +const struct wlr_drm_interface legacy_iface = { + .commit = legacy_commit, +}; diff --git a/3rdparty/wlroots/backend/drm/libliftoff.c b/3rdparty/wlroots/backend/drm/libliftoff.c new file mode 100644 index 0000000000..333beacade --- /dev/null +++ b/3rdparty/wlroots/backend/drm/libliftoff.c @@ -0,0 +1,506 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "backend/drm/drm.h" +#include "backend/drm/fb.h" +#include "backend/drm/iface.h" +#include "config.h" +#include "types/wlr_output.h" + +static void log_handler(enum liftoff_log_priority priority, const char *fmt, va_list args) { + enum wlr_log_importance importance = WLR_SILENT; + switch (priority) { + case LIFTOFF_SILENT: + importance = WLR_SILENT; + break; + case LIFTOFF_ERROR: + importance = WLR_ERROR; + break; + case LIFTOFF_DEBUG: + importance = WLR_DEBUG; + break; + } + char buf[1024]; + vsnprintf(buf, sizeof(buf), fmt, args); + _wlr_log(importance, "[libliftoff] %s", buf); +} + +static bool init(struct wlr_drm_backend *drm) { + // TODO: lower log level + liftoff_log_set_priority(LIFTOFF_DEBUG); + liftoff_log_set_handler(log_handler); + + int drm_fd = fcntl(drm->fd, F_DUPFD_CLOEXEC, 0); + if (drm_fd < 0) { + wlr_log_errno(WLR_ERROR, "fcntl(F_DUPFD_CLOEXEC) failed"); + return false; + } + + drm->liftoff = liftoff_device_create(drm_fd); + if (!drm->liftoff) { + wlr_log(WLR_ERROR, "Failed to create liftoff device"); + close(drm_fd); + return false; + } + + for (size_t i = 0; i < drm->num_planes; i++) { + struct wlr_drm_plane *plane = &drm->planes[i]; + if (plane->initial_crtc_id != 0) { + continue; + } + plane->liftoff = liftoff_plane_create(drm->liftoff, plane->id); + if (plane->liftoff == NULL) { + wlr_log(WLR_ERROR, "Failed to create liftoff plane"); + return false; + } + } + + for (size_t i = 0; i < drm->num_crtcs; i++) { + struct wlr_drm_crtc *crtc = &drm->crtcs[i]; + + crtc->liftoff = liftoff_output_create(drm->liftoff, crtc->id); + if (!crtc->liftoff) { + wlr_log(WLR_ERROR, "Failed to create liftoff output"); + return false; + } + + crtc->liftoff_composition_layer = liftoff_layer_create(crtc->liftoff); + if (!crtc->liftoff_composition_layer) { + wlr_log(WLR_ERROR, "Failed to create liftoff composition layer"); + return false; + } + liftoff_output_set_composition_layer(crtc->liftoff, + crtc->liftoff_composition_layer); + + if (crtc->primary) { + crtc->primary->liftoff_layer = liftoff_layer_create(crtc->liftoff); + if (!crtc->primary->liftoff_layer) { + wlr_log(WLR_ERROR, "Failed to create liftoff layer for primary plane"); + return false; + } + } + + if (crtc->cursor) { + crtc->cursor->liftoff_layer = liftoff_layer_create(crtc->liftoff); + if (!crtc->cursor->liftoff_layer) { + wlr_log(WLR_ERROR, "Failed to create liftoff layer for cursor plane"); + return false; + } + } + } + + return true; +} + +static bool register_planes_for_crtc(struct wlr_drm_backend *drm, + struct wlr_drm_crtc *crtc) { + // When performing the first modeset on a CRTC, we need to be a bit careful + // when it comes to planes: we don't want to allow libliftoff to make use + // of planes currently already in-use on another CRTC. We need to wait for + // a modeset to happen on the other CRTC before being able to use these. + for (size_t i = 0; i < drm->num_planes; i++) { + struct wlr_drm_plane *plane = &drm->planes[i]; + if (plane->liftoff != NULL || plane->initial_crtc_id != crtc->id) { + continue; + } + plane->liftoff = liftoff_plane_create(drm->liftoff, plane->id); + if (plane->liftoff == NULL) { + wlr_log(WLR_ERROR, "Failed to create liftoff plane"); + return false; + } + } + return true; +} + +static void finish(struct wlr_drm_backend *drm) { + for (size_t i = 0; i < drm->num_crtcs; i++) { + struct wlr_drm_crtc *crtc = &drm->crtcs[i]; + + if (crtc->primary) { + liftoff_layer_destroy(crtc->primary->liftoff_layer); + } + if (crtc->cursor) { + liftoff_layer_destroy(crtc->cursor->liftoff_layer); + } + + liftoff_layer_destroy(crtc->liftoff_composition_layer); + liftoff_output_destroy(crtc->liftoff); + } + + for (size_t i = 0; i < drm->num_planes; i++) { + struct wlr_drm_plane *plane = &drm->planes[i]; + liftoff_plane_destroy(plane->liftoff); + } + + liftoff_device_destroy(drm->liftoff); +} + +static bool add_prop(drmModeAtomicReq *req, uint32_t obj, + uint32_t prop, uint64_t val) { + if (drmModeAtomicAddProperty(req, obj, prop, val) < 0) { + wlr_log_errno(WLR_ERROR, "drmModeAtomicAddProperty failed"); + return false; + } + return true; +} + +static bool set_plane_props(struct wlr_drm_plane *plane, + struct liftoff_layer *layer, struct wlr_drm_fb *fb, uint64_t zpos, + const struct wlr_box *dst_box, const struct wlr_fbox *src_box) { + if (fb == NULL) { + wlr_log(WLR_ERROR, "Failed to acquire FB for plane %"PRIu32, plane->id); + return false; + } + + // The src_* properties are in 16.16 fixed point + return liftoff_layer_set_property(layer, "zpos", zpos) == 0 && + liftoff_layer_set_property(layer, "SRC_X", src_box->x * (1 << 16)) == 0 && + liftoff_layer_set_property(layer, "SRC_Y", src_box->y * (1 << 16)) == 0 && + liftoff_layer_set_property(layer, "SRC_W", src_box->width * (1 << 16)) == 0 && + liftoff_layer_set_property(layer, "SRC_H", src_box->height * (1 << 16)) == 0 && + liftoff_layer_set_property(layer, "CRTC_X", dst_box->x) == 0 && + liftoff_layer_set_property(layer, "CRTC_Y", dst_box->y) == 0 && + liftoff_layer_set_property(layer, "CRTC_W", dst_box->width) == 0 && + liftoff_layer_set_property(layer, "CRTC_H", dst_box->height) == 0 && + liftoff_layer_set_property(layer, "FB_ID", fb->id) == 0; +} + +static bool disable_plane(struct wlr_drm_plane *plane) { + return liftoff_layer_set_property(plane->liftoff_layer, "FB_ID", 0) == 0; +} + +static uint64_t to_fp16(double v) { + return (uint64_t)round(v * (1 << 16)); +} + +static bool set_layer_props(struct wlr_drm_backend *drm, + const struct wlr_output_layer_state *state, uint64_t zpos, + struct wl_array *fb_damage_clips_arr) { + struct wlr_drm_layer *layer = get_drm_layer(drm, state->layer); + + uint32_t width = 0, height = 0; + if (state->buffer != NULL) { + width = state->buffer->width; + height = state->buffer->height; + } + + struct wlr_drm_fb *fb = layer->pending_fb; + int ret = 0; + if (state->buffer == NULL) { + ret = liftoff_layer_set_property(layer->liftoff, "FB_ID", 0); + } else if (fb == NULL) { + liftoff_layer_set_fb_composited(layer->liftoff); + } else { + ret = liftoff_layer_set_property(layer->liftoff, "FB_ID", fb->id); + } + if (ret != 0) { + return false; + } + + uint64_t crtc_x = (uint64_t)state->dst_box.x; + uint64_t crtc_y = (uint64_t)state->dst_box.y; + uint64_t crtc_w = (uint64_t)state->dst_box.width; + uint64_t crtc_h = (uint64_t)state->dst_box.height; + + struct wlr_fbox src_box = state->src_box; + if (wlr_fbox_empty(&src_box)) { + src_box = (struct wlr_fbox){ + .width = width, + .height = height, + }; + } + + uint64_t src_x = to_fp16(src_box.x); + uint64_t src_y = to_fp16(src_box.y); + uint64_t src_w = to_fp16(src_box.width); + uint64_t src_h = to_fp16(src_box.height); + + uint32_t fb_damage_clips = 0; + if (state->damage != NULL) { + uint32_t *ptr = wl_array_add(fb_damage_clips_arr, sizeof(fb_damage_clips)); + if (ptr == NULL) { + return false; + } + create_fb_damage_clips_blob(drm, width, height, + state->damage, &fb_damage_clips); + *ptr = fb_damage_clips; + } + + return + liftoff_layer_set_property(layer->liftoff, "zpos", zpos) == 0 && + liftoff_layer_set_property(layer->liftoff, "CRTC_X", crtc_x) == 0 && + liftoff_layer_set_property(layer->liftoff, "CRTC_Y", crtc_y) == 0 && + liftoff_layer_set_property(layer->liftoff, "CRTC_W", crtc_w) == 0 && + liftoff_layer_set_property(layer->liftoff, "CRTC_H", crtc_h) == 0 && + liftoff_layer_set_property(layer->liftoff, "SRC_X", src_x) == 0 && + liftoff_layer_set_property(layer->liftoff, "SRC_Y", src_y) == 0 && + liftoff_layer_set_property(layer->liftoff, "SRC_W", src_w) == 0 && + liftoff_layer_set_property(layer->liftoff, "SRC_H", src_h) == 0 && + liftoff_layer_set_property(layer->liftoff, "FB_DAMAGE_CLIPS", fb_damage_clips) == 0; +} + +static bool devid_from_fd(int fd, dev_t *devid) { + struct stat stat; + if (fstat(fd, &stat) != 0) { + wlr_log_errno(WLR_ERROR, "fstat failed"); + return false; + } + *devid = stat.st_rdev; + return true; +} + +static void update_layer_feedback(struct wlr_drm_backend *drm, + struct wlr_drm_layer *layer) { + bool changed = false; + for (size_t i = 0; i < drm->num_planes; i++) { + struct wlr_drm_plane *plane = &drm->planes[i]; + bool is_candidate = liftoff_layer_is_candidate_plane(layer->liftoff, + plane->liftoff); + if (layer->candidate_planes[i] != is_candidate) { + layer->candidate_planes[i] = is_candidate; + changed = true; + } + } + if (!changed) { + return; + } + + dev_t target_device; + if (!devid_from_fd(drm->fd, &target_device)) { + return; + } + + struct wlr_drm_format_set formats = {0}; + for (size_t i = 0; i < drm->num_planes; i++) { + struct wlr_drm_plane *plane = &drm->planes[i]; + if (!layer->candidate_planes[i]) { + continue; + } + + for (size_t j = 0; j < plane->formats.len; j++) { + const struct wlr_drm_format *format = &plane->formats.formats[j]; + for (size_t k = 0; k < format->len; k++) { + wlr_drm_format_set_add(&formats, format->format, + format->modifiers[k]); + } + } + } + + struct wlr_output_layer_feedback_event event = { + .target_device = target_device, + .formats = &formats, + }; + wl_signal_emit_mutable(&layer->wlr->events.feedback, &event); + + wlr_drm_format_set_finish(&formats); +} + +static bool add_connector(drmModeAtomicReq *req, + const struct wlr_drm_connector_state *state, + bool modeset, struct wl_array *fb_damage_clips_arr) { + struct wlr_drm_connector *conn = state->connector; + struct wlr_drm_crtc *crtc = conn->crtc; + struct wlr_drm_backend *drm = conn->backend; + bool active = state->active; + bool ok = true; + + ok = ok && add_prop(req, conn->id, conn->props.crtc_id, + active ? crtc->id : 0); + if (modeset && active && conn->props.link_status != 0) { + ok = ok && add_prop(req, conn->id, conn->props.link_status, + DRM_MODE_LINK_STATUS_GOOD); + } + if (active && conn->props.content_type != 0) { + ok = ok && add_prop(req, conn->id, conn->props.content_type, + DRM_MODE_CONTENT_TYPE_GRAPHICS); + } + // TODO: set "max bpc" + ok = ok && + add_prop(req, crtc->id, crtc->props.mode_id, state->mode_id) && + add_prop(req, crtc->id, crtc->props.active, active); + if (active) { + if (crtc->props.gamma_lut != 0) { + ok = ok && add_prop(req, crtc->id, crtc->props.gamma_lut, state->gamma_lut); + } + if (crtc->props.vrr_enabled != 0) { + ok = ok && add_prop(req, crtc->id, crtc->props.vrr_enabled, state->vrr_enabled); + } + + ok = ok && set_plane_props(crtc->primary, + crtc->primary->liftoff_layer, state->primary_fb, 0, + &state->primary_viewport.dst_box, + &state->primary_viewport.src_box); + ok = ok && set_plane_props(crtc->primary, + crtc->liftoff_composition_layer, state->primary_fb, 0, + &state->primary_viewport.dst_box, + &state->primary_viewport.src_box); + + liftoff_layer_set_property(crtc->primary->liftoff_layer, + "FB_DAMAGE_CLIPS", state->fb_damage_clips); + liftoff_layer_set_property(crtc->liftoff_composition_layer, + "FB_DAMAGE_CLIPS", state->fb_damage_clips); + + if (state->primary_in_fence_fd >= 0) { + liftoff_layer_set_property(crtc->primary->liftoff_layer, + "IN_FENCE_FD", state->primary_in_fence_fd); + liftoff_layer_set_property(crtc->liftoff_composition_layer, + "IN_FENCE_FD", state->primary_in_fence_fd); + } + + if (state->base->committed & WLR_OUTPUT_STATE_LAYERS) { + for (size_t i = 0; i < state->base->layers_len; i++) { + const struct wlr_output_layer_state *layer_state = &state->base->layers[i]; + ok = ok && set_layer_props(drm, layer_state, i + 1, + fb_damage_clips_arr); + } + } + + if (crtc->cursor) { + if (drm_connector_is_cursor_visible(conn)) { + struct wlr_fbox cursor_src = { + .width = state->cursor_fb->wlr_buf->width, + .height = state->cursor_fb->wlr_buf->height, + }; + struct wlr_box cursor_dst = { + .x = conn->cursor_x, + .y = conn->cursor_y, + .width = state->cursor_fb->wlr_buf->width, + .height = state->cursor_fb->wlr_buf->height, + }; + ok = ok && set_plane_props(crtc->cursor, crtc->cursor->liftoff_layer, + state->cursor_fb, wl_list_length(&crtc->layers) + 1, + &cursor_dst, &cursor_src); + } else { + ok = ok && disable_plane(crtc->cursor); + } + } + } else { + ok = ok && disable_plane(crtc->primary); + if (crtc->cursor) { + ok = ok && disable_plane(crtc->cursor); + } + } + + return ok; +} + +static void connector_update_layers_feedback(const struct wlr_drm_connector_state *state) { + struct wlr_drm_backend *drm = state->connector->backend; + + if (!(state->base->committed & WLR_OUTPUT_STATE_LAYERS)) { + return; + } + + for (size_t i = 0; i < state->base->layers_len; i++) { + struct wlr_output_layer_state *layer_state = &state->base->layers[i]; + struct wlr_drm_layer *layer = get_drm_layer(drm, layer_state->layer); + layer_state->accepted = + !liftoff_layer_needs_composition(layer->liftoff); + if (!layer_state->accepted) { + update_layer_feedback(drm, layer); + } + } +} + +static bool commit(struct wlr_drm_backend *drm, + const struct wlr_drm_device_state *state, + struct wlr_drm_page_flip *page_flip, uint32_t flags, bool test_only) { + bool ok = false; + struct wl_array fb_damage_clips_arr = {0}; + drmModeAtomicReq *req = NULL; + + if (test_only) { + flags |= DRM_MODE_ATOMIC_TEST_ONLY; + } + if (state->modeset) { + flags |= DRM_MODE_ATOMIC_ALLOW_MODESET; + } + if (state->nonblock) { + flags |= DRM_MODE_ATOMIC_NONBLOCK; + } + + for (size_t i = 0; i < state->connectors_len; i++) { + struct wlr_drm_connector_state *conn_state = &state->connectors[i]; + struct wlr_drm_connector *conn = conn_state->connector; + if (state->modeset && !register_planes_for_crtc(drm, conn->crtc)) { + goto out; + } + if (!drm_atomic_connector_prepare(conn_state, state->modeset)) { + goto out; + } + } + + req = drmModeAtomicAlloc(); + if (req == NULL) { + wlr_log(WLR_ERROR, "drmModeAtomicAlloc failed"); + goto out; + } + + for (size_t i = 0; i < state->connectors_len; i++) { + if (!add_connector(req, &state->connectors[i], state->modeset, &fb_damage_clips_arr)) { + goto out; + } + } + + for (size_t i = 0; i < state->connectors_len; i++) { + struct wlr_drm_connector *conn = state->connectors[i].connector; + struct wlr_drm_crtc *crtc = conn->crtc; + +#if HAVE_LIBLIFTOFF_0_5 + int ret = liftoff_output_apply(crtc->liftoff, req, flags, NULL); +#else + int ret = liftoff_output_apply(crtc->liftoff, req, flags); +#endif + if (ret != 0) { + wlr_drm_conn_log(conn, test_only ? WLR_DEBUG : WLR_ERROR, + "liftoff_output_apply failed: %s", strerror(-ret)); + goto out; + } + + if (crtc->cursor && + liftoff_layer_needs_composition(crtc->cursor->liftoff_layer)) { + wlr_drm_conn_log(conn, WLR_DEBUG, "Failed to scan-out cursor plane"); + goto out; + } + } + + ok = drmModeAtomicCommit(drm->fd, req, flags, page_flip) == 0; + if (!ok) { + wlr_log_errno(test_only ? WLR_DEBUG : WLR_ERROR, + "Atomic commit failed"); + } + +out: + drmModeAtomicFree(req); + for (size_t i = 0; i < state->connectors_len; i++) { + struct wlr_drm_connector_state *conn_state = &state->connectors[i]; + if (ok && !test_only) { + drm_atomic_connector_apply_commit(conn_state); + connector_update_layers_feedback(conn_state); + } else { + drm_atomic_connector_rollback_commit(conn_state); + } + } + + uint32_t *fb_damage_clips_ptr; + wl_array_for_each(fb_damage_clips_ptr, &fb_damage_clips_arr) { + if (drmModeDestroyPropertyBlob(drm->fd, *fb_damage_clips_ptr) != 0) { + wlr_log_errno(WLR_ERROR, "Failed to destroy FB_DAMAGE_CLIPS property blob"); + } + } + wl_array_release(&fb_damage_clips_arr); + + return ok; +} + +const struct wlr_drm_interface liftoff_iface = { + .init = init, + .finish = finish, + .commit = commit, +}; diff --git a/3rdparty/wlroots/backend/drm/meson.build b/3rdparty/wlroots/backend/drm/meson.build new file mode 100644 index 0000000000..d9e5b77f5f --- /dev/null +++ b/3rdparty/wlroots/backend/drm/meson.build @@ -0,0 +1,58 @@ +hwdata = dependency( + 'hwdata', + required: 'drm' in backends, + native: true, + not_found_message: 'Required for the DRM backend.', +) + +libdisplay_info = dependency( + 'libdisplay-info', + version: '>=0.2.0', + required: 'drm' in backends, + fallback: 'libdisplay-info', + not_found_message: 'Required for the DRM backend.', +) + +libliftoff = dependency( + 'libliftoff', + version: '>=0.4.0', + fallback: 'libliftoff', + required: get_option('libliftoff'), +) + +if not (hwdata.found() and libdisplay_info.found() and features['session']) + subdir_done() +endif + +hwdata_dir = hwdata.get_variable(pkgconfig: 'pkgdatadir') +pnpids_c = custom_target( + 'pnpids.c', + output: 'pnpids.c', + input: files(hwdata_dir / 'pnp.ids'), + feed: true, + capture: true, + command: files('gen_pnpids.sh'), +) +wlr_files += pnpids_c + +wlr_files += files( + 'atomic.c', + 'backend.c', + 'drm.c', + 'fb.c', + 'legacy.c', + 'monitor.c', + 'properties.c', + 'renderer.c', + 'util.c', +) + +if libliftoff.found() + wlr_files += files('libliftoff.c') + internal_config.set10('HAVE_LIBLIFTOFF_0_5', libliftoff.version().version_compare('>=0.5.0')) +endif + +features += { 'drm-backend': true } +internal_features += { 'libliftoff': libliftoff.found() } +wlr_deps += libdisplay_info +wlr_deps += libliftoff diff --git a/3rdparty/wlroots/backend/drm/monitor.c b/3rdparty/wlroots/backend/drm/monitor.c new file mode 100644 index 0000000000..efd8537476 --- /dev/null +++ b/3rdparty/wlroots/backend/drm/monitor.c @@ -0,0 +1,91 @@ +#include +#include +#include "backend/drm/monitor.h" +#include "backend/multi.h" +#include "backend/session/session.h" + +static void drm_backend_monitor_destroy(struct wlr_drm_backend_monitor* monitor) { + wl_list_remove(&monitor->session_add_drm_card.link); + wl_list_remove(&monitor->session_destroy.link); + wl_list_remove(&monitor->primary_drm_destroy.link); + wl_list_remove(&monitor->multi_destroy.link); + free(monitor); +} + +static void handle_add_drm_card(struct wl_listener *listener, void *data) { + struct wlr_session_add_event *event = data; + struct wlr_drm_backend_monitor *backend_monitor = + wl_container_of(listener, backend_monitor, session_add_drm_card); + + struct wlr_device *dev = + session_open_if_kms(backend_monitor->session, event->path); + if (!dev) { + wlr_log(WLR_ERROR, "Unable to open %s as DRM device", event->path); + return; + } + + wlr_log(WLR_DEBUG, "Creating DRM backend for %s after hotplug", event->path); + struct wlr_backend *child_drm = wlr_drm_backend_create(backend_monitor->session, + dev, backend_monitor->primary_drm); + if (!child_drm) { + wlr_log(WLR_ERROR, "Failed to create DRM backend after hotplug"); + return; + } + + if (!wlr_multi_backend_add(backend_monitor->multi, child_drm)) { + wlr_log(WLR_ERROR, "Failed to add new drm backend to multi backend"); + wlr_backend_destroy(child_drm); + return; + } + + if (!wlr_backend_start(child_drm)) { + wlr_log(WLR_ERROR, "Failed to start new child DRM backend"); + wlr_backend_destroy(child_drm); + } +} + +static void handle_session_destroy(struct wl_listener *listener, void *data) { + struct wlr_drm_backend_monitor *backend_monitor = + wl_container_of(listener, backend_monitor, session_destroy); + drm_backend_monitor_destroy(backend_monitor); +} + +static void handle_primary_drm_destroy(struct wl_listener *listener, void *data) { + struct wlr_drm_backend_monitor *backend_monitor = + wl_container_of(listener, backend_monitor, primary_drm_destroy); + drm_backend_monitor_destroy(backend_monitor); +} + +static void handle_multi_destroy(struct wl_listener *listener, void *data) { + struct wlr_drm_backend_monitor *backend_monitor = + wl_container_of(listener, backend_monitor, multi_destroy); + drm_backend_monitor_destroy(backend_monitor); +} + +struct wlr_drm_backend_monitor *drm_backend_monitor_create( + struct wlr_backend *multi, struct wlr_backend *primary_drm, + struct wlr_session *session) { + struct wlr_drm_backend_monitor *monitor = calloc(1, sizeof(*monitor)); + if (!monitor) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + + monitor->multi = multi; + monitor->primary_drm = primary_drm; + monitor->session = session; + + monitor->session_add_drm_card.notify = handle_add_drm_card; + wl_signal_add(&session->events.add_drm_card, &monitor->session_add_drm_card); + + monitor->session_destroy.notify = handle_session_destroy; + wl_signal_add(&session->events.destroy, &monitor->session_destroy); + + monitor->primary_drm_destroy.notify = handle_primary_drm_destroy; + wl_signal_add(&primary_drm->events.destroy, &monitor->primary_drm_destroy); + + monitor->multi_destroy.notify = handle_multi_destroy; + wl_signal_add(&multi->events.destroy, &monitor->multi_destroy); + + return monitor; +} diff --git a/3rdparty/wlroots/backend/drm/properties.c b/3rdparty/wlroots/backend/drm/properties.c new file mode 100644 index 0000000000..314023954b --- /dev/null +++ b/3rdparty/wlroots/backend/drm/properties.c @@ -0,0 +1,216 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "backend/drm/properties.h" + +/* + * Creates a mapping between property names and an array index where to store + * the ids. The prop_info arrays must be sorted by name, as bsearch is used to + * search them. + */ +struct prop_info { + const char *name; + size_t index; +}; + +static const struct prop_info connector_info[] = { +#define INDEX(name) (offsetof(struct wlr_drm_connector_props, name) / sizeof(uint32_t)) + { "CRTC_ID", INDEX(crtc_id) }, + { "Colorspace", INDEX(colorspace) }, + { "DPMS", INDEX(dpms) }, + { "EDID", INDEX(edid) }, + { "HDR_OUTPUT_METADATA", INDEX(hdr_output_metadata) }, + { "PATH", INDEX(path) }, + { "content type", INDEX(content_type) }, + { "link-status", INDEX(link_status) }, + { "max bpc", INDEX(max_bpc) }, + { "non-desktop", INDEX(non_desktop) }, + { "panel orientation", INDEX(panel_orientation) }, + { "subconnector", INDEX(subconnector) }, + { "vrr_capable", INDEX(vrr_capable) }, +#undef INDEX +}; + +static const struct prop_info crtc_info[] = { +#define INDEX(name) (offsetof(struct wlr_drm_crtc_props, name) / sizeof(uint32_t)) + { "ACTIVE", INDEX(active) }, + { "GAMMA_LUT", INDEX(gamma_lut) }, + { "GAMMA_LUT_SIZE", INDEX(gamma_lut_size) }, + { "MODE_ID", INDEX(mode_id) }, + { "OUT_FENCE_PTR", INDEX(out_fence_ptr) }, + { "VRR_ENABLED", INDEX(vrr_enabled) }, +#undef INDEX +}; + +static const struct prop_info plane_info[] = { +#define INDEX(name) (offsetof(struct wlr_drm_plane_props, name) / sizeof(uint32_t)) + { "CRTC_H", INDEX(crtc_h) }, + { "CRTC_ID", INDEX(crtc_id) }, + { "CRTC_W", INDEX(crtc_w) }, + { "CRTC_X", INDEX(crtc_x) }, + { "CRTC_Y", INDEX(crtc_y) }, + { "FB_DAMAGE_CLIPS", INDEX(fb_damage_clips) }, + { "FB_ID", INDEX(fb_id) }, + { "HOTSPOT_X", INDEX(hotspot_x) }, + { "HOTSPOT_Y", INDEX(hotspot_y) }, + { "IN_FENCE_FD", INDEX(in_fence_fd) }, + { "IN_FORMATS", INDEX(in_formats) }, + { "SIZE_HINTS", INDEX(size_hints) }, + { "SRC_H", INDEX(src_h) }, + { "SRC_W", INDEX(src_w) }, + { "SRC_X", INDEX(src_x) }, + { "SRC_Y", INDEX(src_y) }, + { "rotation", INDEX(rotation) }, + { "type", INDEX(type) }, +#undef INDEX +}; + +static int cmp_prop_info(const void *arg1, const void *arg2) { + const char *key = arg1; + const struct prop_info *elem = arg2; + + return strcmp(key, elem->name); +} + +static bool scan_properties(int fd, uint32_t id, uint32_t type, uint32_t *result, + const struct prop_info *info, size_t info_len) { + drmModeObjectProperties *props = drmModeObjectGetProperties(fd, id, type); + if (!props) { + wlr_log_errno(WLR_ERROR, "Failed to get DRM object %" PRIu32 " properties", id); + return false; + } + + for (uint32_t i = 0; i < props->count_props; ++i) { + drmModePropertyRes *prop = drmModeGetProperty(fd, props->props[i]); + if (!prop) { + wlr_log_errno(WLR_ERROR, "Failed to get property %" PRIu32 " of DRM object %" PRIu32, props->props[i], id); + continue; + } + + const struct prop_info *p = + bsearch(prop->name, info, info_len, sizeof(info[0]), cmp_prop_info); + if (p) { + result[p->index] = prop->prop_id; + } + + drmModeFreeProperty(prop); + } + + drmModeFreeObjectProperties(props); + return true; +} + +bool get_drm_connector_props(int fd, uint32_t id, struct wlr_drm_connector_props *out) { + return scan_properties(fd, id, DRM_MODE_OBJECT_CONNECTOR, (uint32_t *)out, + connector_info, sizeof(connector_info) / sizeof(connector_info[0])); +} + +bool get_drm_crtc_props(int fd, uint32_t id, struct wlr_drm_crtc_props *out) { + return scan_properties(fd, id, DRM_MODE_OBJECT_CRTC, (uint32_t *)out, + crtc_info, sizeof(crtc_info) / sizeof(crtc_info[0])); +} + +bool get_drm_plane_props(int fd, uint32_t id, struct wlr_drm_plane_props *out) { + return scan_properties(fd, id, DRM_MODE_OBJECT_PLANE, (uint32_t *)out, + plane_info, sizeof(plane_info) / sizeof(plane_info[0])); +} + +bool get_drm_prop(int fd, uint32_t obj, uint32_t prop, uint64_t *ret) { + drmModeObjectProperties *props = + drmModeObjectGetProperties(fd, obj, DRM_MODE_OBJECT_ANY); + if (!props) { + return false; + } + + bool found = false; + + for (uint32_t i = 0; i < props->count_props; ++i) { + if (props->props[i] == prop) { + *ret = props->prop_values[i]; + found = true; + break; + } + } + + drmModeFreeObjectProperties(props); + return found; +} + +void *get_drm_prop_blob(int fd, uint32_t obj, uint32_t prop, size_t *ret_len) { + uint64_t blob_id; + if (!get_drm_prop(fd, obj, prop, &blob_id)) { + return NULL; + } + + drmModePropertyBlobRes *blob = drmModeGetPropertyBlob(fd, blob_id); + if (!blob) { + return NULL; + } + + void *ptr = malloc(blob->length); + if (!ptr) { + drmModeFreePropertyBlob(blob); + return NULL; + } + + memcpy(ptr, blob->data, blob->length); + *ret_len = blob->length; + + drmModeFreePropertyBlob(blob); + return ptr; +} + +char *get_drm_prop_enum(int fd, uint32_t obj, uint32_t prop_id) { + uint64_t value; + if (!get_drm_prop(fd, obj, prop_id, &value)) { + return NULL; + } + + drmModePropertyRes *prop = drmModeGetProperty(fd, prop_id); + if (!prop) { + return NULL; + } + + char *str = NULL; + for (int i = 0; i < prop->count_enums; i++) { + if (prop->enums[i].value == value) { + str = strdup(prop->enums[i].name); + break; + } + } + + drmModeFreeProperty(prop); + + return str; +} + +bool introspect_drm_prop_range(int fd, uint32_t prop_id, + uint64_t *min, uint64_t *max) { + drmModePropertyRes *prop = drmModeGetProperty(fd, prop_id); + if (!prop) { + return false; + } + + if (drmModeGetPropertyType(prop) != DRM_MODE_PROP_RANGE) { + drmModeFreeProperty(prop); + return false; + } + + assert(prop->count_values == 2); + + if (min != NULL) { + *min = prop->values[0]; + } + if (max != NULL) { + *max = prop->values[1]; + } + + drmModeFreeProperty(prop); + return true; +} diff --git a/3rdparty/wlroots/backend/drm/renderer.c b/3rdparty/wlroots/backend/drm/renderer.c new file mode 100644 index 0000000000..af9908e912 --- /dev/null +++ b/3rdparty/wlroots/backend/drm/renderer.c @@ -0,0 +1,195 @@ +#include +#include +#include +#include +#include +#include +#include +#include "backend/drm/drm.h" +#include "backend/drm/fb.h" +#include "backend/drm/renderer.h" +#include "render/drm_format_set.h" +#include "render/pixel_format.h" +#include "render/wlr_renderer.h" + +bool init_drm_renderer(struct wlr_drm_backend *drm, + struct wlr_drm_renderer *renderer) { + wlr_log(WLR_DEBUG, "Creating multi-GPU renderer"); + renderer->wlr_rend = renderer_autocreate_with_drm_fd(drm->fd); + if (!renderer->wlr_rend) { + return false; + } + if (wlr_renderer_get_texture_formats(renderer->wlr_rend, WLR_BUFFER_CAP_DMABUF) == NULL) { + wlr_log(WLR_ERROR, "Renderer did not support importing DMA-BUFs"); + wlr_renderer_destroy(renderer->wlr_rend); + renderer->wlr_rend = NULL; + return false; + } + + renderer->allocator = wlr_allocator_autocreate(&drm->backend, renderer->wlr_rend); + if (renderer->allocator == NULL) { + wlr_renderer_destroy(renderer->wlr_rend); + renderer->wlr_rend = NULL; + return false; + } + + return true; +} + +void finish_drm_renderer(struct wlr_drm_renderer *renderer) { + if (!renderer) { + return; + } + + wlr_allocator_destroy(renderer->allocator); + wlr_renderer_destroy(renderer->wlr_rend); +} + +void finish_drm_surface(struct wlr_drm_surface *surf) { + if (!surf || !surf->renderer) { + return; + } + + wlr_drm_syncobj_timeline_unref(surf->timeline); + wlr_swapchain_destroy(surf->swapchain); + + *surf = (struct wlr_drm_surface){0}; +} + +bool init_drm_surface(struct wlr_drm_surface *surf, + struct wlr_drm_renderer *renderer, int width, int height, + const struct wlr_drm_format *drm_format) { + if (surf->swapchain != NULL && surf->swapchain->width == width && + surf->swapchain->height == height) { + return true; + } + + finish_drm_surface(surf); + + surf->swapchain = wlr_swapchain_create(renderer->allocator, width, height, + drm_format); + if (surf->swapchain == NULL) { + wlr_log(WLR_ERROR, "Failed to create swapchain"); + return false; + } + + int drm_fd = wlr_renderer_get_drm_fd(renderer->wlr_rend); + if (renderer->wlr_rend->features.timeline && drm_fd >= 0) { + surf->timeline = wlr_drm_syncobj_timeline_create(drm_fd); + if (surf->timeline == NULL) { + finish_drm_surface(surf); + wlr_log(WLR_ERROR, "Failed to create DRM syncobj timeline"); + return false; + } + } + + surf->renderer = renderer; + + return true; +} + +struct wlr_buffer *drm_surface_blit(struct wlr_drm_surface *surf, + struct wlr_buffer *buffer, + struct wlr_drm_syncobj_timeline *wait_timeline, uint64_t wait_point) { + struct wlr_renderer *renderer = surf->renderer->wlr_rend; + + if (surf->swapchain->width != buffer->width || + surf->swapchain->height != buffer->height) { + wlr_log(WLR_ERROR, "Surface size doesn't match buffer size"); + return NULL; + } + + struct wlr_texture *tex = wlr_texture_from_buffer(renderer, buffer); + if (tex == NULL) { + wlr_log(WLR_ERROR, "Failed to import source buffer into multi-GPU renderer"); + return NULL; + } + + struct wlr_buffer *dst = wlr_swapchain_acquire(surf->swapchain); + if (!dst) { + wlr_log(WLR_ERROR, "Failed to acquire multi-GPU swapchain buffer"); + goto error_tex; + } + + surf->point++; + const struct wlr_buffer_pass_options pass_options = { + .signal_timeline = surf->timeline, + .signal_point = surf->point, + }; + struct wlr_render_pass *pass = wlr_renderer_begin_buffer_pass(renderer, dst, &pass_options); + if (pass == NULL) { + wlr_log(WLR_ERROR, "Failed to begin render pass with multi-GPU destination buffer"); + goto error_dst; + } + + wlr_render_pass_add_texture(pass, &(struct wlr_render_texture_options){ + .texture = tex, + .blend_mode = WLR_RENDER_BLEND_MODE_NONE, + .wait_timeline = wait_timeline, + .wait_point = wait_point, + }); + if (!wlr_render_pass_submit(pass)) { + wlr_log(WLR_ERROR, "Failed to submit multi-GPU render pass"); + goto error_dst; + } + + wlr_texture_destroy(tex); + + return dst; + +error_dst: + wlr_buffer_unlock(dst); +error_tex: + wlr_texture_destroy(tex); + return NULL; +} + +bool drm_plane_pick_render_format(struct wlr_drm_plane *plane, + struct wlr_drm_format *fmt, struct wlr_drm_renderer *renderer) { + const struct wlr_drm_format_set *render_formats = + wlr_renderer_get_render_formats(renderer->wlr_rend); + if (render_formats == NULL) { + wlr_log(WLR_ERROR, "Failed to get render formats"); + return false; + } + + const struct wlr_drm_format_set *plane_formats = &plane->formats; + + uint32_t format = DRM_FORMAT_ARGB8888; + if (!wlr_drm_format_set_get(&plane->formats, format)) { + const struct wlr_pixel_format_info *format_info = + drm_get_pixel_format_info(format); + assert(format_info != NULL && + format_info->opaque_substitute != DRM_FORMAT_INVALID); + format = format_info->opaque_substitute; + } + + const struct wlr_drm_format *render_format = + wlr_drm_format_set_get(render_formats, format); + if (render_format == NULL) { + wlr_log(WLR_DEBUG, "Renderer doesn't support format 0x%"PRIX32, format); + return false; + } + + const struct wlr_drm_format *plane_format = + wlr_drm_format_set_get(plane_formats, format); + if (plane_format == NULL) { + wlr_log(WLR_DEBUG, "Plane %"PRIu32" doesn't support format 0x%"PRIX32, + plane->id, format); + return false; + } + + if (!wlr_drm_format_intersect(fmt, plane_format, render_format)) { + wlr_log(WLR_DEBUG, "Failed to intersect plane and render " + "modifiers for format 0x%"PRIX32, format); + return false; + } + + if (fmt->len == 0) { + wlr_drm_format_finish(fmt); + wlr_log(WLR_DEBUG, "Failed to find matching plane and renderer modifiers"); + return false; + } + + return true; +} diff --git a/3rdparty/wlroots/backend/drm/util.c b/3rdparty/wlroots/backend/drm/util.c new file mode 100644 index 0000000000..1e0307dcba --- /dev/null +++ b/3rdparty/wlroots/backend/drm/util.c @@ -0,0 +1,294 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "backend/drm/drm.h" +#include "backend/drm/util.h" + +int32_t calculate_refresh_rate(const drmModeModeInfo *mode) { + int32_t refresh = (mode->clock * 1000000LL / mode->htotal + + mode->vtotal / 2) / mode->vtotal; + + if (mode->flags & DRM_MODE_FLAG_INTERLACE) { + refresh *= 2; + } + + if (mode->flags & DRM_MODE_FLAG_DBLSCAN) { + refresh /= 2; + } + + if (mode->vscan > 1) { + refresh /= mode->vscan; + } + + return refresh; +} + +enum wlr_output_mode_aspect_ratio get_picture_aspect_ratio(const drmModeModeInfo *mode) { + switch (mode->flags & DRM_MODE_FLAG_PIC_AR_MASK) { + case DRM_MODE_FLAG_PIC_AR_NONE: + return WLR_OUTPUT_MODE_ASPECT_RATIO_NONE; + case DRM_MODE_FLAG_PIC_AR_4_3: + return WLR_OUTPUT_MODE_ASPECT_RATIO_4_3; + case DRM_MODE_FLAG_PIC_AR_16_9: + return WLR_OUTPUT_MODE_ASPECT_RATIO_16_9; + case DRM_MODE_FLAG_PIC_AR_64_27: + return WLR_OUTPUT_MODE_ASPECT_RATIO_64_27; + case DRM_MODE_FLAG_PIC_AR_256_135: + return WLR_OUTPUT_MODE_ASPECT_RATIO_256_135; + default: + wlr_log(WLR_ERROR, "Unknown mode picture aspect ratio: %u", + mode->flags & DRM_MODE_FLAG_PIC_AR_MASK); + return WLR_OUTPUT_MODE_ASPECT_RATIO_NONE; + } +} + +void parse_edid(struct wlr_drm_connector *conn, size_t len, const uint8_t *data) { + struct wlr_output *output = &conn->output; + + free(output->make); + free(output->model); + free(output->serial); + output->make = NULL; + output->model = NULL; + output->serial = NULL; + + struct di_info *info = di_info_parse_edid(data, len); + if (info == NULL) { + wlr_log(WLR_ERROR, "Failed to parse EDID"); + return; + } + + const struct di_edid *edid = di_info_get_edid(info); + const struct di_edid_vendor_product *vendor_product = di_edid_get_vendor_product(edid); + char pnp_id[] = { + vendor_product->manufacturer[0], + vendor_product->manufacturer[1], + vendor_product->manufacturer[2], + '\0', + }; + const char *manu = get_pnp_manufacturer(vendor_product->manufacturer); + if (!manu) { + manu = pnp_id; + } + output->make = strdup(manu); + + output->model = di_info_get_model(info); + output->serial = di_info_get_serial(info); + + const struct di_color_primaries *color_characteristics = di_info_get_default_color_primaries(info); + if (color_characteristics->has_primaries) { + output->default_primaries_value = (struct wlr_color_primaries) { + .red = { .x = color_characteristics->primary[0].x, .y = color_characteristics->primary[0].y }, + .green = { .x = color_characteristics->primary[1].x, .y = color_characteristics->primary[1].y }, + .blue = { .x = color_characteristics->primary[2].x, .y = color_characteristics->primary[2].y }, + .white = { .x = color_characteristics->default_white.x, .y = color_characteristics->default_white.y }, + }; + output->default_primaries = &output->default_primaries_value; + } + + const struct di_supported_signal_colorimetry *colorimetry = di_info_get_supported_signal_colorimetry(info); + bool has_bt2020 = colorimetry->bt2020_cycc || colorimetry->bt2020_ycc || colorimetry->bt2020_rgb; + if (conn->props.colorspace != 0 && has_bt2020) { + output->supported_primaries |= WLR_COLOR_NAMED_PRIMARIES_BT2020; + } + + const struct di_hdr_static_metadata *hdr_static_metadata = di_info_get_hdr_static_metadata(info); + if (conn->props.hdr_output_metadata != 0 && hdr_static_metadata->type1 && hdr_static_metadata->pq) { + output->supported_transfer_functions |= WLR_COLOR_TRANSFER_FUNCTION_ST2084_PQ; + } + + di_info_destroy(info); +} + +const char *drm_connector_status_str(drmModeConnection status) { + switch (status) { + case DRM_MODE_CONNECTED: + return "connected"; + case DRM_MODE_DISCONNECTED: + return "disconnected"; + case DRM_MODE_UNKNOWNCONNECTION: + return "unknown"; + } + return ""; +} + +static bool is_taken(size_t n, const uint32_t arr[static n], uint32_t key) { + for (size_t i = 0; i < n; ++i) { + if (arr[i] == key) { + return true; + } + } + return false; +} + +/* + * Store all of the non-recursive state in a struct, so we aren't literally + * passing 12 arguments to a function. + */ +struct match_state { + const size_t num_conns; + const uint32_t *restrict conns; + const size_t num_crtcs; + size_t score; + size_t replaced; + uint32_t *restrict res; + uint32_t *restrict best; + const uint32_t *restrict orig; + bool exit_early; +}; + +/** + * Step to process a CRTC. + * + * This is a naive implementation of maximum bipartite matching. + * + * score: The number of connectors we've matched so far. + * replaced: The number of changes from the original solution. + * crtc_index: The index of the current CRTC. + * + * This tries to match a solution as close to st->orig as it can. + * + * Returns whether we've set a new best element with this solution. + */ +static bool match_connectors_with_crtcs_(struct match_state *st, + size_t score, size_t replaced, size_t crtc_index) { + // Finished + if (crtc_index >= st->num_crtcs) { + if (score > st->score || + (score == st->score && replaced < st->replaced)) { + st->score = score; + st->replaced = replaced; + memcpy(st->best, st->res, sizeof(st->best[0]) * st->num_crtcs); + + st->exit_early = (st->score == st->num_crtcs + || st->score == st->num_conns) + && st->replaced == 0; + + return true; + } else { + return false; + } + } + + bool has_best = false; + + /* + * Attempt to use the current solution first, to try and avoid + * recalculating everything + */ + if (st->orig[crtc_index] != UNMATCHED && !is_taken(crtc_index, st->res, st->orig[crtc_index])) { + st->res[crtc_index] = st->orig[crtc_index]; + size_t crtc_score = st->conns[st->res[crtc_index]] != 0 ? 1 : 0; + if (match_connectors_with_crtcs_(st, score + crtc_score, replaced, crtc_index + 1)) { + has_best = true; + } + } + if (st->exit_early) { + return true; + } + + if (st->orig[crtc_index] != UNMATCHED) { + ++replaced; + } + + for (size_t candidate = 0; candidate < st->num_conns; ++candidate) { + // We tried this earlier + if (candidate == st->orig[crtc_index]) { + continue; + } + + // Not compatible + if (!(st->conns[candidate] & (1 << crtc_index))) { + continue; + } + + // Already taken + if (is_taken(crtc_index, st->res, candidate)) { + continue; + } + + st->res[crtc_index] = candidate; + size_t crtc_score = st->conns[candidate] != 0 ? 1 : 0; + if (match_connectors_with_crtcs_(st, score + crtc_score, replaced, crtc_index + 1)) { + has_best = true; + } + + if (st->exit_early) { + return true; + } + } + + // Maybe this CRTC can't be matched + st->res[crtc_index] = UNMATCHED; + if (match_connectors_with_crtcs_(st, score, replaced, crtc_index + 1)) { + has_best = true; + } + + return has_best; +} + +void match_connectors_with_crtcs(size_t num_conns, + const uint32_t conns[static restrict num_conns], + size_t num_crtcs, const uint32_t prev_crtcs[static restrict num_crtcs], + uint32_t new_crtcs[static restrict num_crtcs]) { + uint32_t solution[num_crtcs]; + for (size_t i = 0; i < num_crtcs; ++i) { + solution[i] = UNMATCHED; + } + + struct match_state st = { + .num_conns = num_conns, + .num_crtcs = num_crtcs, + .score = 0, + .replaced = SIZE_MAX, + .conns = conns, + .res = solution, + .best = new_crtcs, + .orig = prev_crtcs, + .exit_early = false, + }; + + match_connectors_with_crtcs_(&st, 0, 0, 0); +} + +void generate_cvt_mode(drmModeModeInfo *mode, int hdisplay, int vdisplay, + float vrefresh) { + // TODO: depending on capabilities advertised in the EDID, use reduced + // blanking if possible (and update sync polarity) + struct di_cvt_options options = { + .red_blank_ver = DI_CVT_REDUCED_BLANKING_NONE, + .h_pixels = hdisplay, + .v_lines = vdisplay, + .ip_freq_rqd = vrefresh ? vrefresh : 60, + }; + struct di_cvt_timing timing; + di_cvt_compute(&timing, &options); + + uint16_t hsync_start = hdisplay + timing.h_front_porch; + uint16_t vsync_start = timing.v_lines_rnd + timing.v_front_porch; + uint16_t hsync_end = hsync_start + timing.h_sync; + uint16_t vsync_end = vsync_start + timing.v_sync; + + *mode = (drmModeModeInfo){ + .clock = roundf(timing.act_pixel_freq * 1000), + .hdisplay = hdisplay, + .vdisplay = timing.v_lines_rnd, + .hsync_start = hsync_start, + .vsync_start = vsync_start, + .hsync_end = hsync_end, + .vsync_end = vsync_end, + .htotal = hsync_end + timing.h_back_porch, + .vtotal = vsync_end + timing.v_back_porch, + .vrefresh = roundf(timing.act_frame_rate), + .flags = DRM_MODE_FLAG_NHSYNC | DRM_MODE_FLAG_PVSYNC, + }; + snprintf(mode->name, sizeof(mode->name), "%dx%d", hdisplay, vdisplay); +} diff --git a/3rdparty/wlroots/backend/headless/backend.c b/3rdparty/wlroots/backend/headless/backend.c new file mode 100644 index 0000000000..d03f520b8f --- /dev/null +++ b/3rdparty/wlroots/backend/headless/backend.c @@ -0,0 +1,86 @@ +#include +#include +#include +#include +#include "backend/headless.h" + +struct wlr_headless_backend *headless_backend_from_backend( + struct wlr_backend *wlr_backend) { + assert(wlr_backend_is_headless(wlr_backend)); + struct wlr_headless_backend *backend = wl_container_of(wlr_backend, backend, backend); + return backend; +} + +static bool backend_start(struct wlr_backend *wlr_backend) { + struct wlr_headless_backend *backend = + headless_backend_from_backend(wlr_backend); + wlr_log(WLR_INFO, "Starting headless backend"); + + struct wlr_headless_output *output; + wl_list_for_each(output, &backend->outputs, link) { + wl_signal_emit_mutable(&backend->backend.events.new_output, + &output->wlr_output); + } + + backend->started = true; + return true; +} + +static void backend_destroy(struct wlr_backend *wlr_backend) { + struct wlr_headless_backend *backend = + headless_backend_from_backend(wlr_backend); + if (!wlr_backend) { + return; + } + + wlr_backend_finish(wlr_backend); + + struct wlr_headless_output *output, *output_tmp; + wl_list_for_each_safe(output, output_tmp, &backend->outputs, link) { + wlr_output_destroy(&output->wlr_output); + } + + wl_list_remove(&backend->event_loop_destroy.link); + + free(backend); +} + +static const struct wlr_backend_impl backend_impl = { + .start = backend_start, + .destroy = backend_destroy, +}; + +static void handle_event_loop_destroy(struct wl_listener *listener, void *data) { + struct wlr_headless_backend *backend = + wl_container_of(listener, backend, event_loop_destroy); + backend_destroy(&backend->backend); +} + +struct wlr_backend *wlr_headless_backend_create(struct wl_event_loop *loop) { + wlr_log(WLR_INFO, "Creating headless backend"); + + struct wlr_headless_backend *backend = calloc(1, sizeof(*backend)); + if (!backend) { + wlr_log(WLR_ERROR, "Failed to allocate wlr_headless_backend"); + return NULL; + } + + wlr_backend_init(&backend->backend, &backend_impl); + + backend->backend.buffer_caps = + WLR_BUFFER_CAP_DATA_PTR | WLR_BUFFER_CAP_DMABUF | WLR_BUFFER_CAP_SHM; + + backend->event_loop = loop; + wl_list_init(&backend->outputs); + + backend->event_loop_destroy.notify = handle_event_loop_destroy; + wl_event_loop_add_destroy_listener(loop, &backend->event_loop_destroy); + + backend->backend.features.timeline = true; + + return &backend->backend; +} + +bool wlr_backend_is_headless(struct wlr_backend *backend) { + return backend->impl == &backend_impl; +} diff --git a/3rdparty/wlroots/backend/headless/meson.build b/3rdparty/wlroots/backend/headless/meson.build new file mode 100644 index 0000000000..950c071609 --- /dev/null +++ b/3rdparty/wlroots/backend/headless/meson.build @@ -0,0 +1,4 @@ +wlr_files += files( + 'backend.c', + 'output.c', +) diff --git a/3rdparty/wlroots/backend/headless/output.c b/3rdparty/wlroots/backend/headless/output.c new file mode 100644 index 0000000000..a4cdb17c35 --- /dev/null +++ b/3rdparty/wlroots/backend/headless/output.c @@ -0,0 +1,160 @@ +#include +#include +#include +#include +#include +#include +#include "backend/headless.h" +#include "types/wlr_output.h" + +static const uint32_t SUPPORTED_OUTPUT_STATE = + WLR_OUTPUT_STATE_BACKEND_OPTIONAL | + WLR_OUTPUT_STATE_BUFFER | + WLR_OUTPUT_STATE_ENABLED | + WLR_OUTPUT_STATE_MODE; + +static size_t last_output_num = 0; + +static struct wlr_headless_output *headless_output_from_output( + struct wlr_output *wlr_output) { + assert(wlr_output_is_headless(wlr_output)); + struct wlr_headless_output *output = wl_container_of(wlr_output, output, wlr_output); + return output; +} + +static void output_update_refresh(struct wlr_headless_output *output, + int32_t refresh) { + if (refresh <= 0) { + refresh = HEADLESS_DEFAULT_REFRESH; + } + + output->frame_delay = 1000000 / refresh; +} + +static bool output_test(struct wlr_output *wlr_output, + const struct wlr_output_state *state) { + uint32_t unsupported = state->committed & ~SUPPORTED_OUTPUT_STATE; + if (unsupported != 0) { + wlr_log(WLR_DEBUG, "Unsupported output state fields: 0x%"PRIx32, + unsupported); + return false; + } + + if (state->committed & WLR_OUTPUT_STATE_MODE) { + assert(state->mode_type == WLR_OUTPUT_STATE_MODE_CUSTOM); + } + + if (state->committed & WLR_OUTPUT_STATE_LAYERS) { + for (size_t i = 0; i < state->layers_len; i++) { + state->layers[i].accepted = true; + } + } + + return true; +} + +static bool output_commit(struct wlr_output *wlr_output, + const struct wlr_output_state *state) { + struct wlr_headless_output *output = + headless_output_from_output(wlr_output); + + if (!output_test(wlr_output, state)) { + return false; + } + + if (state->committed & WLR_OUTPUT_STATE_MODE) { + output_update_refresh(output, state->custom_mode.refresh); + } + + if (output_pending_enabled(wlr_output, state)) { + struct wlr_output_event_present present_event = { + .commit_seq = wlr_output->commit_seq + 1, + .presented = true, + }; + output_defer_present(wlr_output, present_event); + + wl_event_source_timer_update(output->frame_timer, output->frame_delay); + } + + return true; +} + +static bool output_set_cursor(struct wlr_output *wlr_output, + struct wlr_buffer *buffer, int hotspot_x, int hotspot_y) { + return true; +} + +static bool output_move_cursor(struct wlr_output *wlr_output, int x, int y) { + return true; +} + +static void output_destroy(struct wlr_output *wlr_output) { + struct wlr_headless_output *output = headless_output_from_output(wlr_output); + + wlr_output_finish(wlr_output); + + wl_list_remove(&output->link); + wl_event_source_remove(output->frame_timer); + free(output); +} + +static const struct wlr_output_impl output_impl = { + .destroy = output_destroy, + .test = output_test, + .commit = output_commit, + .set_cursor = output_set_cursor, + .move_cursor = output_move_cursor, +}; + +bool wlr_output_is_headless(struct wlr_output *wlr_output) { + return wlr_output->impl == &output_impl; +} + +static int signal_frame(void *data) { + struct wlr_headless_output *output = data; + wlr_output_send_frame(&output->wlr_output); + return 0; +} + +struct wlr_output *wlr_headless_add_output(struct wlr_backend *wlr_backend, + unsigned int width, unsigned int height) { + struct wlr_headless_backend *backend = + headless_backend_from_backend(wlr_backend); + + struct wlr_headless_output *output = calloc(1, sizeof(*output)); + if (output == NULL) { + wlr_log(WLR_ERROR, "Failed to allocate wlr_headless_output"); + return NULL; + } + output->backend = backend; + struct wlr_output *wlr_output = &output->wlr_output; + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_custom_mode(&state, width, height, 0); + + wlr_output_init(wlr_output, &backend->backend, &output_impl, backend->event_loop, &state); + wlr_output_state_finish(&state); + + output_update_refresh(output, 0); + + size_t output_num = ++last_output_num; + + char name[64]; + snprintf(name, sizeof(name), "HEADLESS-%zu", output_num); + wlr_output_set_name(wlr_output, name); + + char description[128]; + snprintf(description, sizeof(description), "Headless output %zu", output_num); + wlr_output_set_description(wlr_output, description); + + output->frame_timer = wl_event_loop_add_timer(backend->event_loop, signal_frame, output); + + wl_list_insert(&backend->outputs, &output->link); + + if (backend->started) { + wl_signal_emit_mutable(&backend->backend.events.new_output, wlr_output); + } + + return wlr_output; +} diff --git a/3rdparty/wlroots/backend/libinput/backend.c b/3rdparty/wlroots/backend/libinput/backend.c new file mode 100644 index 0000000000..121731b311 --- /dev/null +++ b/3rdparty/wlroots/backend/libinput/backend.c @@ -0,0 +1,245 @@ +#include +#include +#include +#include +#include +#include +#include +#include "backend/libinput.h" +#include "util/env.h" + +static struct wlr_libinput_backend *get_libinput_backend_from_backend( + struct wlr_backend *wlr_backend) { + assert(wlr_backend_is_libinput(wlr_backend)); + struct wlr_libinput_backend *backend = wl_container_of(wlr_backend, backend, backend); + return backend; +} + +static int libinput_open_restricted(const char *path, + int flags, void *_backend) { + struct wlr_libinput_backend *backend = _backend; + struct wlr_device *dev = wlr_session_open_file(backend->session, path); + if (dev == NULL) { + return -1; + } + return dev->fd; +} + +static void libinput_close_restricted(int fd, void *_backend) { + struct wlr_libinput_backend *backend = _backend; + + struct wlr_device *dev; + bool found = false; + wl_list_for_each(dev, &backend->session->devices, link) { + if (dev->fd == fd) { + found = true; + break; + } + } + if (found) { + wlr_session_close_file(backend->session, dev); + } +} + +static const struct libinput_interface libinput_impl = { + .open_restricted = libinput_open_restricted, + .close_restricted = libinput_close_restricted +}; + +static int handle_libinput_readable(int fd, uint32_t mask, void *_backend) { + struct wlr_libinput_backend *backend = _backend; + int ret = libinput_dispatch(backend->libinput_context); + if (ret != 0) { + wlr_log(WLR_ERROR, "Failed to dispatch libinput: %s", strerror(-ret)); + wlr_backend_destroy(&backend->backend); + return 0; + } + struct libinput_event *event; + while ((event = libinput_get_event(backend->libinput_context))) { + handle_libinput_event(backend, event); + libinput_event_destroy(event); + } + return 0; +} + +static enum wlr_log_importance libinput_log_priority_to_wlr( + enum libinput_log_priority priority) { + switch (priority) { + case LIBINPUT_LOG_PRIORITY_ERROR: + return WLR_ERROR; + case LIBINPUT_LOG_PRIORITY_INFO: + return WLR_INFO; + default: + return WLR_DEBUG; + } +} + +static void log_libinput(struct libinput *libinput_context, + enum libinput_log_priority priority, const char *fmt, va_list args) { + enum wlr_log_importance importance = libinput_log_priority_to_wlr(priority); + static char wlr_fmt[1024]; + snprintf(wlr_fmt, sizeof(wlr_fmt), "[libinput] %s", fmt); + _wlr_vlog(importance, wlr_fmt, args); +} + +static bool backend_start(struct wlr_backend *wlr_backend) { + struct wlr_libinput_backend *backend = + get_libinput_backend_from_backend(wlr_backend); + wlr_log(WLR_DEBUG, "Starting libinput backend"); + + backend->libinput_context = libinput_udev_create_context(&libinput_impl, + backend, backend->session->udev); + if (!backend->libinput_context) { + wlr_log(WLR_ERROR, "Failed to create libinput context"); + return false; + } + + if (libinput_udev_assign_seat(backend->libinput_context, + backend->session->seat) != 0) { + wlr_log(WLR_ERROR, "Failed to assign libinput seat"); + return false; + } + + // TODO: More sophisticated logging + libinput_log_set_handler(backend->libinput_context, log_libinput); + libinput_log_set_priority(backend->libinput_context, LIBINPUT_LOG_PRIORITY_ERROR); + + int libinput_fd = libinput_get_fd(backend->libinput_context); + + handle_libinput_readable(libinput_fd, WL_EVENT_READABLE, backend); + if (!env_parse_bool("WLR_LIBINPUT_NO_DEVICES") && wl_list_empty(&backend->devices)) { + wlr_log(WLR_ERROR, "libinput initialization failed, no input devices"); + wlr_log(WLR_ERROR, "Set WLR_LIBINPUT_NO_DEVICES=1 to suppress this check"); + return false; + } + + if (backend->input_event) { + wl_event_source_remove(backend->input_event); + } + backend->input_event = wl_event_loop_add_fd(backend->session->event_loop, libinput_fd, + WL_EVENT_READABLE, handle_libinput_readable, backend); + if (!backend->input_event) { + wlr_log(WLR_ERROR, "Failed to create input event on event loop"); + return false; + } + wlr_log(WLR_DEBUG, "libinput successfully initialized"); + return true; +} + +static void backend_destroy(struct wlr_backend *wlr_backend) { + if (!wlr_backend) { + return; + } + struct wlr_libinput_backend *backend = + get_libinput_backend_from_backend(wlr_backend); + + struct wlr_libinput_input_device *dev, *tmp; + wl_list_for_each_safe(dev, tmp, &backend->devices, link) { + destroy_libinput_input_device(dev); + } + + wlr_backend_finish(wlr_backend); + + wl_list_remove(&backend->session_destroy.link); + wl_list_remove(&backend->session_signal.link); + + if (backend->input_event) { + wl_event_source_remove(backend->input_event); + } + libinput_unref(backend->libinput_context); + free(backend); +} + +static const struct wlr_backend_impl backend_impl = { + .start = backend_start, + .destroy = backend_destroy, +}; + +bool wlr_backend_is_libinput(struct wlr_backend *b) { + return b->impl == &backend_impl; +} + +static void session_signal(struct wl_listener *listener, void *data) { + struct wlr_libinput_backend *backend = + wl_container_of(listener, backend, session_signal); + struct wlr_session *session = backend->session; + + if (!backend->libinput_context) { + return; + } + + if (session->active) { + libinput_resume(backend->libinput_context); + } else { + libinput_suspend(backend->libinput_context); + } +} + +static void handle_session_destroy(struct wl_listener *listener, void *data) { + struct wlr_libinput_backend *backend = + wl_container_of(listener, backend, session_destroy); + backend_destroy(&backend->backend); +} + +struct wlr_backend *wlr_libinput_backend_create(struct wlr_session *session) { + struct wlr_libinput_backend *backend = calloc(1, sizeof(*backend)); + if (!backend) { + wlr_log(WLR_ERROR, "Allocation failed: %s", strerror(errno)); + return NULL; + } + wlr_backend_init(&backend->backend, &backend_impl); + + wl_list_init(&backend->devices); + + backend->session = session; + + backend->session_signal.notify = session_signal; + wl_signal_add(&session->events.active, &backend->session_signal); + + backend->session_destroy.notify = handle_session_destroy; + wl_signal_add(&session->events.destroy, &backend->session_destroy); + + return &backend->backend; +} + +struct libinput_device *wlr_libinput_get_device_handle( + struct wlr_input_device *wlr_dev) { + struct wlr_libinput_input_device *dev = NULL; + switch (wlr_dev->type) { + case WLR_INPUT_DEVICE_KEYBOARD: + dev = device_from_keyboard(wlr_keyboard_from_input_device(wlr_dev)); + break; + case WLR_INPUT_DEVICE_POINTER: + dev = device_from_pointer(wlr_pointer_from_input_device(wlr_dev)); + break; + case WLR_INPUT_DEVICE_SWITCH: + dev = device_from_switch(wlr_switch_from_input_device(wlr_dev)); + break; + case WLR_INPUT_DEVICE_TOUCH: + dev = device_from_touch(wlr_touch_from_input_device(wlr_dev)); + break; + case WLR_INPUT_DEVICE_TABLET: + dev = device_from_tablet(wlr_tablet_from_input_device(wlr_dev)); + break; + case WLR_INPUT_DEVICE_TABLET_PAD: + dev = device_from_tablet_pad(wlr_tablet_pad_from_input_device(wlr_dev)); + break; + } + + assert(dev); + return dev->handle; +} + +uint32_t usec_to_msec(uint64_t usec) { + return (uint32_t)(usec / 1000); +} + +const char *get_libinput_device_name(struct libinput_device *device) { + // libinput guarantees that the name is non-NULL, and an empty string if + // unset. However wlroots uses NULL to indicate that the name is unset. + const char *name = libinput_device_get_name(device); + if (name[0] == '\0') { + return NULL; + } + return name; +} diff --git a/3rdparty/wlroots/backend/libinput/events.c b/3rdparty/wlroots/backend/libinput/events.c new file mode 100644 index 0000000000..9be5def87e --- /dev/null +++ b/3rdparty/wlroots/backend/libinput/events.c @@ -0,0 +1,263 @@ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "backend/libinput.h" + +void destroy_libinput_input_device(struct wlr_libinput_input_device *dev) { + if (dev->keyboard.impl) { + wlr_keyboard_finish(&dev->keyboard); + } + if (dev->pointer.impl) { + wlr_pointer_finish(&dev->pointer); + } + if (dev->switch_device.impl) { + wlr_switch_finish(&dev->switch_device); + } + if (dev->touch.impl) { + wlr_touch_finish(&dev->touch); + } + if (dev->tablet.impl) { + finish_device_tablet(dev); + } + if (dev->tablet_pad.impl) { + finish_device_tablet_pad(dev); + } + + libinput_device_unref(dev->handle); + wl_list_remove(&dev->link); + free(dev); +} + +bool wlr_input_device_is_libinput(struct wlr_input_device *wlr_dev) { + switch (wlr_dev->type) { + case WLR_INPUT_DEVICE_KEYBOARD: + return wlr_keyboard_from_input_device(wlr_dev)->impl == + &libinput_keyboard_impl; + case WLR_INPUT_DEVICE_POINTER: + return wlr_pointer_from_input_device(wlr_dev)->impl == + &libinput_pointer_impl; + case WLR_INPUT_DEVICE_TOUCH: + return wlr_touch_from_input_device(wlr_dev)->impl == + &libinput_touch_impl; + case WLR_INPUT_DEVICE_TABLET: + return wlr_tablet_from_input_device(wlr_dev)->impl == + &libinput_tablet_impl; + case WLR_INPUT_DEVICE_TABLET_PAD: + return wlr_tablet_pad_from_input_device(wlr_dev)->impl == + &libinput_tablet_pad_impl; + case WLR_INPUT_DEVICE_SWITCH: + return wlr_switch_from_input_device(wlr_dev)->impl == + &libinput_switch_impl; + default: + return false; + } +} + +static void handle_device_added(struct wlr_libinput_backend *backend, + struct libinput_device *libinput_dev) { + int vendor = libinput_device_get_id_vendor(libinput_dev); + int product = libinput_device_get_id_product(libinput_dev); + const char *name = libinput_device_get_name(libinput_dev); + wlr_log(WLR_DEBUG, "Adding %s [%d:%d]", name, vendor, product); + + struct wlr_libinput_input_device *dev = calloc(1, sizeof(*dev)); + if (dev == NULL) { + wlr_log_errno(WLR_ERROR, "failed to allocate wlr_libinput_input_device"); + return; + } + + dev->handle = libinput_dev; + libinput_device_ref(libinput_dev); + libinput_device_set_user_data(libinput_dev, dev); + + wl_list_insert(&backend->devices, &dev->link); + + if (libinput_device_has_capability( + libinput_dev, LIBINPUT_DEVICE_CAP_KEYBOARD)) { + init_device_keyboard(dev); + + wl_signal_emit_mutable(&backend->backend.events.new_input, + &dev->keyboard.base); + } + + if (libinput_device_has_capability( + libinput_dev, LIBINPUT_DEVICE_CAP_POINTER)) { + init_device_pointer(dev); + + wl_signal_emit_mutable(&backend->backend.events.new_input, + &dev->pointer.base); + } + + if (libinput_device_has_capability( + libinput_dev, LIBINPUT_DEVICE_CAP_SWITCH)) { + init_device_switch(dev); + wl_signal_emit_mutable(&backend->backend.events.new_input, + &dev->switch_device.base); + } + + if (libinput_device_has_capability( + libinput_dev, LIBINPUT_DEVICE_CAP_TOUCH)) { + init_device_touch(dev); + wl_signal_emit_mutable(&backend->backend.events.new_input, + &dev->touch.base); + } + + if (libinput_device_has_capability(libinput_dev, + LIBINPUT_DEVICE_CAP_TABLET_TOOL)) { + init_device_tablet(dev); + wl_signal_emit_mutable(&backend->backend.events.new_input, + &dev->tablet.base); + } + + if (libinput_device_has_capability( + libinput_dev, LIBINPUT_DEVICE_CAP_TABLET_PAD)) { + init_device_tablet_pad(dev); + wl_signal_emit_mutable(&backend->backend.events.new_input, + &dev->tablet_pad.base); + } +} + +static void handle_device_removed(struct wlr_libinput_backend *backend, + struct wlr_libinput_input_device *dev) { + int vendor = libinput_device_get_id_vendor(dev->handle); + int product = libinput_device_get_id_product(dev->handle); + const char *name = libinput_device_get_name(dev->handle); + wlr_log(WLR_DEBUG, "Removing %s [%d:%d]", name, vendor, product); + + destroy_libinput_input_device(dev); +} + +void handle_libinput_event(struct wlr_libinput_backend *backend, + struct libinput_event *event) { + struct libinput_device *libinput_dev = libinput_event_get_device(event); + struct wlr_libinput_input_device *dev = + libinput_device_get_user_data(libinput_dev); + enum libinput_event_type event_type = libinput_event_get_type(event); + + if (dev == NULL && event_type != LIBINPUT_EVENT_DEVICE_ADDED) { + wlr_log(WLR_ERROR, "libinput_device has no wlr_libinput_input_device"); + return; + } + + switch (event_type) { + case LIBINPUT_EVENT_DEVICE_ADDED: + handle_device_added(backend, libinput_dev); + break; + case LIBINPUT_EVENT_DEVICE_REMOVED: + handle_device_removed(backend, dev); + break; + case LIBINPUT_EVENT_KEYBOARD_KEY: + handle_keyboard_key(event, &dev->keyboard); + break; + case LIBINPUT_EVENT_POINTER_MOTION: + handle_pointer_motion(event, &dev->pointer); + break; + case LIBINPUT_EVENT_POINTER_MOTION_ABSOLUTE: + handle_pointer_motion_abs(event, &dev->pointer); + break; + case LIBINPUT_EVENT_POINTER_BUTTON: + handle_pointer_button(event, &dev->pointer); + break; + case LIBINPUT_EVENT_POINTER_AXIS: + /* This event must be ignored in favour of the SCROLL_* events */ + break; + case LIBINPUT_EVENT_POINTER_SCROLL_WHEEL: + handle_pointer_axis_value120(event, &dev->pointer, + WL_POINTER_AXIS_SOURCE_WHEEL); + break; + case LIBINPUT_EVENT_POINTER_SCROLL_FINGER: + handle_pointer_axis_value120(event, &dev->pointer, + WL_POINTER_AXIS_SOURCE_FINGER); + break; + case LIBINPUT_EVENT_POINTER_SCROLL_CONTINUOUS: + handle_pointer_axis_value120(event, &dev->pointer, + WL_POINTER_AXIS_SOURCE_CONTINUOUS); + break; + case LIBINPUT_EVENT_TOUCH_DOWN: + handle_touch_down(event, &dev->touch); + break; + case LIBINPUT_EVENT_TOUCH_UP: + handle_touch_up(event, &dev->touch); + break; + case LIBINPUT_EVENT_TOUCH_MOTION: + handle_touch_motion(event, &dev->touch); + break; + case LIBINPUT_EVENT_TOUCH_CANCEL: + handle_touch_cancel(event, &dev->touch); + break; + case LIBINPUT_EVENT_TOUCH_FRAME: + handle_touch_frame(event, &dev->touch); + break; + case LIBINPUT_EVENT_TABLET_TOOL_AXIS: + handle_tablet_tool_axis(event, &dev->tablet); + break; + case LIBINPUT_EVENT_TABLET_TOOL_PROXIMITY: + handle_tablet_tool_proximity(event, &dev->tablet); + break; + case LIBINPUT_EVENT_TABLET_TOOL_TIP: + handle_tablet_tool_tip(event, &dev->tablet); + break; + case LIBINPUT_EVENT_TABLET_TOOL_BUTTON: + handle_tablet_tool_button(event, &dev->tablet); + break; + case LIBINPUT_EVENT_TABLET_PAD_BUTTON: + handle_tablet_pad_button(event, &dev->tablet_pad); + break; + case LIBINPUT_EVENT_TABLET_PAD_RING: + handle_tablet_pad_ring(event, &dev->tablet_pad); + break; + case LIBINPUT_EVENT_TABLET_PAD_STRIP: + handle_tablet_pad_strip(event, &dev->tablet_pad); + break; + case LIBINPUT_EVENT_SWITCH_TOGGLE: + handle_switch_toggle(event, &dev->switch_device); + break; + case LIBINPUT_EVENT_GESTURE_SWIPE_BEGIN: + handle_pointer_swipe_begin(event, &dev->pointer); + break; + case LIBINPUT_EVENT_GESTURE_SWIPE_UPDATE: + handle_pointer_swipe_update(event, &dev->pointer); + break; + case LIBINPUT_EVENT_GESTURE_SWIPE_END: + handle_pointer_swipe_end(event, &dev->pointer); + break; + case LIBINPUT_EVENT_GESTURE_PINCH_BEGIN: + handle_pointer_pinch_begin(event, &dev->pointer); + break; + case LIBINPUT_EVENT_GESTURE_PINCH_UPDATE: + handle_pointer_pinch_update(event, &dev->pointer); + break; + case LIBINPUT_EVENT_GESTURE_PINCH_END: + handle_pointer_pinch_end(event, &dev->pointer); + break; + case LIBINPUT_EVENT_GESTURE_HOLD_BEGIN: + handle_pointer_hold_begin(event, &dev->pointer); + break; + case LIBINPUT_EVENT_GESTURE_HOLD_END: + handle_pointer_hold_end(event, &dev->pointer); + break; + default: + wlr_log(WLR_DEBUG, "Unknown libinput event %d", event_type); + break; + } +} + +bool button_state_from_libinput(enum libinput_button_state state, enum wlr_button_state *out) { + switch (state) { + case LIBINPUT_BUTTON_STATE_RELEASED: + *out = WLR_BUTTON_RELEASED; + return true; + case LIBINPUT_BUTTON_STATE_PRESSED: + *out = WLR_BUTTON_PRESSED; + return true; + } + return false; +} diff --git a/3rdparty/wlroots/backend/libinput/keyboard.c b/3rdparty/wlroots/backend/libinput/keyboard.c new file mode 100644 index 0000000000..a99461040f --- /dev/null +++ b/3rdparty/wlroots/backend/libinput/keyboard.c @@ -0,0 +1,60 @@ +#include +#include +#include +#include +#include +#include "backend/libinput.h" + +struct wlr_libinput_input_device *device_from_keyboard( + struct wlr_keyboard *kb) { + assert(kb->impl == &libinput_keyboard_impl); + + struct wlr_libinput_input_device *dev = wl_container_of(kb, dev, keyboard); + return dev; +} + +static void keyboard_set_leds(struct wlr_keyboard *wlr_kb, uint32_t leds) { + struct wlr_libinput_input_device *dev = device_from_keyboard(wlr_kb); + libinput_device_led_update(dev->handle, leds); +} + +const struct wlr_keyboard_impl libinput_keyboard_impl = { + .name = "libinput-keyboard", + .led_update = keyboard_set_leds +}; + +void init_device_keyboard(struct wlr_libinput_input_device *dev) { + const char *name = get_libinput_device_name(dev->handle); + struct wlr_keyboard *wlr_kb = &dev->keyboard; + wlr_keyboard_init(wlr_kb, &libinput_keyboard_impl, name); + + libinput_device_led_update(dev->handle, 0); +} + +static bool key_state_from_libinput(enum libinput_key_state state, enum wl_keyboard_key_state *out) { + switch (state) { + case LIBINPUT_KEY_STATE_RELEASED: + *out = WL_KEYBOARD_KEY_STATE_RELEASED; + return true; + case LIBINPUT_KEY_STATE_PRESSED: + *out = WL_KEYBOARD_KEY_STATE_PRESSED; + return true; + } + return false; +} + +void handle_keyboard_key(struct libinput_event *event, + struct wlr_keyboard *kb) { + struct libinput_event_keyboard *kbevent = + libinput_event_get_keyboard_event(event); + struct wlr_keyboard_key_event wlr_event = { + .time_msec = usec_to_msec(libinput_event_keyboard_get_time_usec(kbevent)), + .keycode = libinput_event_keyboard_get_key(kbevent), + .update_state = true, + }; + if (!key_state_from_libinput(libinput_event_keyboard_get_key_state(kbevent), &wlr_event.state)) { + wlr_log(WLR_DEBUG, "Unhandled libinput key state"); + return; + } + wlr_keyboard_notify_key(kb, &wlr_event); +} diff --git a/3rdparty/wlroots/backend/libinput/meson.build b/3rdparty/wlroots/backend/libinput/meson.build new file mode 100644 index 0000000000..091b0e0eb0 --- /dev/null +++ b/3rdparty/wlroots/backend/libinput/meson.build @@ -0,0 +1,35 @@ +msg = ['Required for libinput backend support.'] +if 'libinput' in backends + msg += 'Install "libinput" or disable the libinput backend.' +endif + +libinput = dependency( + 'libinput', + version: '>=1.19.0', + required: 'libinput' in backends, + not_found_message: '\n'.join(msg), +) + +if not (libinput.found() and features['session']) + subdir_done() +endif + +wlr_files += files( + 'backend.c', + 'events.c', + 'keyboard.c', + 'pointer.c', + 'switch.c', + 'tablet_pad.c', + 'tablet_tool.c', + 'touch.c', +) + +features += { 'libinput-backend': true } +wlr_deps += libinput + +internal_config.set10('HAVE_LIBINPUT_BUSTYPE', libinput.version().version_compare('>=1.26.0')) +internal_config.set10( + 'HAVE_LIBINPUT_SWITCH_KEYPAD_SLIDE', + libinput.version().version_compare('>=1.30.901') +) diff --git a/3rdparty/wlroots/backend/libinput/pointer.c b/3rdparty/wlroots/backend/libinput/pointer.c new file mode 100644 index 0000000000..d09164a719 --- /dev/null +++ b/3rdparty/wlroots/backend/libinput/pointer.c @@ -0,0 +1,294 @@ +#include +#include +#include +#include +#include "backend/libinput.h" + +const struct wlr_pointer_impl libinput_pointer_impl = { + .name = "libinput-pointer", +}; + +void init_device_pointer(struct wlr_libinput_input_device *dev) { + const char *name = get_libinput_device_name(dev->handle); + struct wlr_pointer *wlr_pointer = &dev->pointer; + wlr_pointer_init(wlr_pointer, &libinput_pointer_impl, name); +} + +struct wlr_libinput_input_device *device_from_pointer( + struct wlr_pointer *wlr_pointer) { + assert(wlr_pointer->impl == &libinput_pointer_impl); + + struct wlr_libinput_input_device *dev = + wl_container_of(wlr_pointer, dev, pointer); + return dev; +} + +void handle_pointer_motion(struct libinput_event *event, + struct wlr_pointer *pointer) { + struct libinput_event_pointer *pevent = + libinput_event_get_pointer_event(event); + struct wlr_pointer_motion_event wlr_event = { + .pointer = pointer, + .time_msec = usec_to_msec(libinput_event_pointer_get_time_usec(pevent)), + .delta_x = libinput_event_pointer_get_dx(pevent), + .delta_y = libinput_event_pointer_get_dy(pevent), + .unaccel_dx = libinput_event_pointer_get_dx_unaccelerated(pevent), + .unaccel_dy = libinput_event_pointer_get_dy_unaccelerated(pevent), + }; + wl_signal_emit_mutable(&pointer->events.motion, &wlr_event); + wl_signal_emit_mutable(&pointer->events.frame, pointer); +} + +void handle_pointer_motion_abs(struct libinput_event *event, + struct wlr_pointer *pointer) { + struct libinput_event_pointer *pevent = + libinput_event_get_pointer_event(event); + struct wlr_pointer_motion_absolute_event wlr_event = { + .pointer = pointer, + .time_msec = usec_to_msec(libinput_event_pointer_get_time_usec(pevent)), + .x = libinput_event_pointer_get_absolute_x_transformed(pevent, 1), + .y = libinput_event_pointer_get_absolute_y_transformed(pevent, 1), + }; + wl_signal_emit_mutable(&pointer->events.motion_absolute, &wlr_event); + wl_signal_emit_mutable(&pointer->events.frame, pointer); +} + +static bool pointer_button_state_from_libinput(enum libinput_button_state state, + enum wl_pointer_button_state *out) { + switch (state) { + case LIBINPUT_BUTTON_STATE_PRESSED: + *out = WL_POINTER_BUTTON_STATE_PRESSED; + return true; + case LIBINPUT_BUTTON_STATE_RELEASED: + *out = WL_POINTER_BUTTON_STATE_RELEASED; + return true; + } + return false; +} + +static bool axis_source_from_libinput(enum libinput_pointer_axis_source source, + enum wl_pointer_axis_source *out) { + switch (source) { + case LIBINPUT_POINTER_AXIS_SOURCE_WHEEL: + *out = WL_POINTER_AXIS_SOURCE_WHEEL; + return true; + case LIBINPUT_POINTER_AXIS_SOURCE_FINGER: + *out = WL_POINTER_AXIS_SOURCE_FINGER; + return true; + case LIBINPUT_POINTER_AXIS_SOURCE_CONTINUOUS: + *out = WL_POINTER_AXIS_SOURCE_CONTINUOUS; + return true; + case LIBINPUT_POINTER_AXIS_SOURCE_WHEEL_TILT: + *out = WL_POINTER_AXIS_SOURCE_WHEEL_TILT; + return true; + } + return false; +} + +void handle_pointer_button(struct libinput_event *event, + struct wlr_pointer *pointer) { + struct libinput_event_pointer *pevent = + libinput_event_get_pointer_event(event); + struct wlr_pointer_button_event wlr_event = { + .pointer = pointer, + .time_msec = usec_to_msec(libinput_event_pointer_get_time_usec(pevent)), + .button = libinput_event_pointer_get_button(pevent), + }; + if (!pointer_button_state_from_libinput(libinput_event_pointer_get_button_state(pevent), + &wlr_event.state)) { + wlr_log(WLR_DEBUG, "Unhandled libinput button state"); + return; + } + wlr_pointer_notify_button(pointer, &wlr_event); + wl_signal_emit_mutable(&pointer->events.frame, pointer); +} + +void handle_pointer_axis(struct libinput_event *event, + struct wlr_pointer *pointer) { + struct libinput_event_pointer *pevent = + libinput_event_get_pointer_event(event); + struct wlr_pointer_axis_event wlr_event = { + .pointer = pointer, + .time_msec = usec_to_msec(libinput_event_pointer_get_time_usec(pevent)), + }; + if (!axis_source_from_libinput(libinput_event_pointer_get_axis_source(pevent), &wlr_event.source)) { + wlr_log(WLR_DEBUG, "Unhandled libinput pointer axis source"); + return; + } + const enum libinput_pointer_axis axes[] = { + LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL, + LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL, + }; + for (size_t i = 0; i < sizeof(axes) / sizeof(axes[0]); ++i) { + if (!libinput_event_pointer_has_axis(pevent, axes[i])) { + continue; + } + + switch (axes[i]) { + case LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL: + wlr_event.orientation = WL_POINTER_AXIS_VERTICAL_SCROLL; + break; + case LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL: + wlr_event.orientation = WL_POINTER_AXIS_HORIZONTAL_SCROLL; + break; + } + wlr_event.delta = + libinput_event_pointer_get_axis_value(pevent, axes[i]); + wlr_event.delta_discrete = + libinput_event_pointer_get_axis_value_discrete(pevent, axes[i]); + wlr_event.delta_discrete *= WLR_POINTER_AXIS_DISCRETE_STEP; + wlr_event.relative_direction = WL_POINTER_AXIS_RELATIVE_DIRECTION_IDENTICAL; + if (libinput_device_config_scroll_get_natural_scroll_enabled(libinput_event_get_device(event))) { + wlr_event.relative_direction = WL_POINTER_AXIS_RELATIVE_DIRECTION_INVERTED; + } + wl_signal_emit_mutable(&pointer->events.axis, &wlr_event); + } + wl_signal_emit_mutable(&pointer->events.frame, pointer); +} + +void handle_pointer_axis_value120(struct libinput_event *event, + struct wlr_pointer *pointer, enum wl_pointer_axis_source source) { + struct libinput_event_pointer *pevent = + libinput_event_get_pointer_event(event); + struct wlr_pointer_axis_event wlr_event = { + .pointer = pointer, + .time_msec = usec_to_msec(libinput_event_pointer_get_time_usec(pevent)), + .source = source, + }; + + const enum libinput_pointer_axis axes[] = { + LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL, + LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL, + }; + for (size_t i = 0; i < sizeof(axes) / sizeof(axes[0]); ++i) { + if (!libinput_event_pointer_has_axis(pevent, axes[i])) { + continue; + } + switch (axes[i]) { + case LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL: + wlr_event.orientation = WL_POINTER_AXIS_VERTICAL_SCROLL; + break; + case LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL: + wlr_event.orientation = WL_POINTER_AXIS_HORIZONTAL_SCROLL; + break; + } + wlr_event.delta = + libinput_event_pointer_get_scroll_value(pevent, axes[i]); + if (source == WL_POINTER_AXIS_SOURCE_WHEEL) { + wlr_event.delta_discrete = + libinput_event_pointer_get_scroll_value_v120(pevent, axes[i]); + } + wl_signal_emit_mutable(&pointer->events.axis, &wlr_event); + } + wl_signal_emit_mutable(&pointer->events.frame, pointer); +} + +void handle_pointer_swipe_begin(struct libinput_event *event, + struct wlr_pointer *pointer) { + struct libinput_event_gesture *gevent = + libinput_event_get_gesture_event(event); + struct wlr_pointer_swipe_begin_event wlr_event = { + .pointer = pointer, + .time_msec = + usec_to_msec(libinput_event_gesture_get_time_usec(gevent)), + .fingers = libinput_event_gesture_get_finger_count(gevent), + }; + wl_signal_emit_mutable(&pointer->events.swipe_begin, &wlr_event); +} + +void handle_pointer_swipe_update(struct libinput_event *event, + struct wlr_pointer *pointer) { + struct libinput_event_gesture *gevent = + libinput_event_get_gesture_event(event); + struct wlr_pointer_swipe_update_event wlr_event = { + .pointer = pointer, + .time_msec = + usec_to_msec(libinput_event_gesture_get_time_usec(gevent)), + .fingers = libinput_event_gesture_get_finger_count(gevent), + .dx = libinput_event_gesture_get_dx(gevent), + .dy = libinput_event_gesture_get_dy(gevent), + }; + wl_signal_emit_mutable(&pointer->events.swipe_update, &wlr_event); +} + +void handle_pointer_swipe_end(struct libinput_event *event, + struct wlr_pointer *pointer) { + struct libinput_event_gesture *gevent = + libinput_event_get_gesture_event(event); + struct wlr_pointer_swipe_end_event wlr_event = { + .pointer = pointer, + .time_msec = + usec_to_msec(libinput_event_gesture_get_time_usec(gevent)), + .cancelled = libinput_event_gesture_get_cancelled(gevent), + }; + wl_signal_emit_mutable(&pointer->events.swipe_end, &wlr_event); +} + +void handle_pointer_pinch_begin(struct libinput_event *event, + struct wlr_pointer *pointer) { + struct libinput_event_gesture *gevent = + libinput_event_get_gesture_event(event); + struct wlr_pointer_pinch_begin_event wlr_event = { + .pointer = pointer, + .time_msec = + usec_to_msec(libinput_event_gesture_get_time_usec(gevent)), + .fingers = libinput_event_gesture_get_finger_count(gevent), + }; + wl_signal_emit_mutable(&pointer->events.pinch_begin, &wlr_event); +} + +void handle_pointer_pinch_update(struct libinput_event *event, + struct wlr_pointer *pointer) { + struct libinput_event_gesture *gevent = + libinput_event_get_gesture_event(event); + struct wlr_pointer_pinch_update_event wlr_event = { + .pointer = pointer, + .time_msec = + usec_to_msec(libinput_event_gesture_get_time_usec(gevent)), + .fingers = libinput_event_gesture_get_finger_count(gevent), + .dx = libinput_event_gesture_get_dx(gevent), + .dy = libinput_event_gesture_get_dy(gevent), + .scale = libinput_event_gesture_get_scale(gevent), + .rotation = libinput_event_gesture_get_angle_delta(gevent), + }; + wl_signal_emit_mutable(&pointer->events.pinch_update, &wlr_event); +} + +void handle_pointer_pinch_end(struct libinput_event *event, + struct wlr_pointer *pointer) { + struct libinput_event_gesture *gevent = + libinput_event_get_gesture_event(event); + struct wlr_pointer_pinch_end_event wlr_event = { + .pointer = pointer, + .time_msec = + usec_to_msec(libinput_event_gesture_get_time_usec(gevent)), + .cancelled = libinput_event_gesture_get_cancelled(gevent), + }; + wl_signal_emit_mutable(&pointer->events.pinch_end, &wlr_event); +} + +void handle_pointer_hold_begin(struct libinput_event *event, + struct wlr_pointer *pointer) { + struct libinput_event_gesture *gevent = + libinput_event_get_gesture_event(event); + struct wlr_pointer_hold_begin_event wlr_event = { + .pointer = pointer, + .time_msec = + usec_to_msec(libinput_event_gesture_get_time_usec(gevent)), + .fingers = libinput_event_gesture_get_finger_count(gevent), + }; + wl_signal_emit_mutable(&pointer->events.hold_begin, &wlr_event); +} + +void handle_pointer_hold_end(struct libinput_event *event, + struct wlr_pointer *pointer) { + struct libinput_event_gesture *gevent = + libinput_event_get_gesture_event(event); + struct wlr_pointer_hold_end_event wlr_event = { + .pointer = pointer, + .time_msec = + usec_to_msec(libinput_event_gesture_get_time_usec(gevent)), + .cancelled = libinput_event_gesture_get_cancelled(gevent), + }; + wl_signal_emit_mutable(&pointer->events.hold_end, &wlr_event); +} diff --git a/3rdparty/wlroots/backend/libinput/switch.c b/3rdparty/wlroots/backend/libinput/switch.c new file mode 100644 index 0000000000..2055d88f51 --- /dev/null +++ b/3rdparty/wlroots/backend/libinput/switch.c @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include "backend/libinput.h" +#include "config.h" + +const struct wlr_switch_impl libinput_switch_impl = { + .name = "libinput-switch", +}; + +void init_device_switch(struct wlr_libinput_input_device *dev) { + const char *name = get_libinput_device_name(dev->handle); + struct wlr_switch *wlr_switch = &dev->switch_device; + wlr_switch_init(wlr_switch, &libinput_switch_impl, name); +} + +struct wlr_libinput_input_device *device_from_switch( + struct wlr_switch *wlr_switch) { + assert(wlr_switch->impl == &libinput_switch_impl); + + struct wlr_libinput_input_device *dev = + wl_container_of(wlr_switch, dev, switch_device); + return dev; +} + +static bool switch_type_from_libinput(enum libinput_switch type, enum wlr_switch_type *out) { + switch (type) { + case LIBINPUT_SWITCH_LID: + *out = WLR_SWITCH_TYPE_LID; + return true; + case LIBINPUT_SWITCH_TABLET_MODE: + *out = WLR_SWITCH_TYPE_TABLET_MODE; + return true; +#if HAVE_LIBINPUT_SWITCH_KEYPAD_SLIDE + case LIBINPUT_SWITCH_KEYPAD_SLIDE: + *out = WLR_SWITCH_TYPE_KEYPAD_SLIDE; + return true; +#endif + } + return false; +} + +static bool switch_state_from_libinput(enum libinput_switch_state state, enum wlr_switch_state *out) { + switch (state) { + case LIBINPUT_SWITCH_STATE_OFF: + *out = WLR_SWITCH_STATE_OFF; + return true; + case LIBINPUT_SWITCH_STATE_ON: + *out = WLR_SWITCH_STATE_ON; + return true; + } + return false; +} + +void handle_switch_toggle(struct libinput_event *event, + struct wlr_switch *wlr_switch) { + struct libinput_event_switch *sevent = + libinput_event_get_switch_event(event); + struct wlr_switch_toggle_event wlr_event = { + .time_msec = usec_to_msec(libinput_event_switch_get_time_usec(sevent)), + }; + if (!switch_type_from_libinput(libinput_event_switch_get_switch(sevent), &wlr_event.switch_type)) { + wlr_log(WLR_DEBUG, "Unhandled libinput switch type"); + return; + } + if (!switch_state_from_libinput(libinput_event_switch_get_switch_state(sevent), &wlr_event.switch_state)) { + wlr_log(WLR_DEBUG, "Unhandled libinput switch state"); + return; + } + wl_signal_emit_mutable(&wlr_switch->events.toggle, &wlr_event); +} diff --git a/3rdparty/wlroots/backend/libinput/tablet_pad.c b/3rdparty/wlroots/backend/libinput/tablet_pad.c new file mode 100644 index 0000000000..9d090198ad --- /dev/null +++ b/3rdparty/wlroots/backend/libinput/tablet_pad.c @@ -0,0 +1,200 @@ +#include +#include +#include +#include +#include +#include +#include "backend/libinput.h" + +const struct wlr_tablet_pad_impl libinput_tablet_pad_impl = { + .name = "libinput-tablet-pad", +}; + +static void group_destroy(struct wlr_tablet_pad_group *group) { + free(group->buttons); + free(group->strips); + free(group->rings); + free(group); +} + +static void add_pad_group_from_libinput(struct wlr_tablet_pad *pad, + struct libinput_device *device, unsigned int index) { + struct libinput_tablet_pad_mode_group *li_group = + libinput_device_tablet_pad_get_mode_group(device, index); + struct wlr_tablet_pad_group *group = calloc(1, sizeof(*group)); + if (!group) { + wlr_log_errno(WLR_ERROR, "failed to allocate wlr_tablet_pad_group"); + return; + } + + for (size_t i = 0; i < pad->ring_count; ++i) { + if (libinput_tablet_pad_mode_group_has_ring(li_group, i)) { + ++group->ring_count; + } + } + group->rings = calloc(group->ring_count, sizeof(unsigned int)); + if (group->rings == NULL) { + goto group_fail; + } + + size_t ring = 0; + for (size_t i = 0; i < pad->ring_count; ++i) { + if (libinput_tablet_pad_mode_group_has_ring(li_group, i)) { + group->rings[ring++] = i; + } + } + + for (size_t i = 0; i < pad->strip_count; ++i) { + if (libinput_tablet_pad_mode_group_has_strip(li_group, i)) { + ++group->strip_count; + } + } + group->strips = calloc(group->strip_count, sizeof(unsigned int)); + if (group->strips == NULL) { + goto group_fail; + } + size_t strip = 0; + for (size_t i = 0; i < pad->strip_count; ++i) { + if (libinput_tablet_pad_mode_group_has_strip(li_group, i)) { + group->strips[strip++] = i; + } + } + + for (size_t i = 0; i < pad->button_count; ++i) { + if (libinput_tablet_pad_mode_group_has_button(li_group, i)) { + ++group->button_count; + } + } + group->buttons = calloc(group->button_count, sizeof(unsigned int)); + if (group->buttons == NULL) { + goto group_fail; + } + size_t button = 0; + for (size_t i = 0; i < pad->button_count; ++i) { + if (libinput_tablet_pad_mode_group_has_button(li_group, i)) { + group->buttons[button++] = i; + } + } + + group->mode_count = libinput_tablet_pad_mode_group_get_num_modes(li_group); + + libinput_tablet_pad_mode_group_ref(li_group); + + wl_list_insert(&pad->groups, &group->link); + return; + +group_fail: + wlr_log(WLR_ERROR, "failed to configure wlr_tablet_pad_group"); + group_destroy(group); +} + +void init_device_tablet_pad(struct wlr_libinput_input_device *dev) { + struct libinput_device *handle = dev->handle; + const char *name = get_libinput_device_name(handle); + struct wlr_tablet_pad *wlr_tablet_pad = &dev->tablet_pad; + wlr_tablet_pad_init(wlr_tablet_pad, &libinput_tablet_pad_impl, name); + + wlr_tablet_pad->button_count = + libinput_device_tablet_pad_get_num_buttons(handle); + wlr_tablet_pad->ring_count = + libinput_device_tablet_pad_get_num_rings(handle); + wlr_tablet_pad->strip_count = + libinput_device_tablet_pad_get_num_strips(handle); + + struct udev_device *udev = libinput_device_get_udev_device(handle); + char **dst = wl_array_add(&wlr_tablet_pad->paths, sizeof(char *)); + *dst = strdup(udev_device_get_syspath(udev)); + udev_device_unref(udev); + + int groups = libinput_device_tablet_pad_get_num_mode_groups(handle); + for (int i = 0; i < groups; ++i) { + add_pad_group_from_libinput(wlr_tablet_pad, handle, i); + } +} + +void finish_device_tablet_pad(struct wlr_libinput_input_device *dev) { + struct wlr_tablet_pad_group *group, *tmp; + wl_list_for_each_safe(group, tmp, &dev->tablet_pad.groups, link) { + group_destroy(group); + } + + wlr_tablet_pad_finish(&dev->tablet_pad); + + int groups = libinput_device_tablet_pad_get_num_mode_groups(dev->handle); + for (int i = 0; i < groups; ++i) { + struct libinput_tablet_pad_mode_group *li_group = + libinput_device_tablet_pad_get_mode_group(dev->handle, i); + libinput_tablet_pad_mode_group_unref(li_group); + } +} + +struct wlr_libinput_input_device *device_from_tablet_pad( + struct wlr_tablet_pad *wlr_tablet_pad) { + assert(wlr_tablet_pad->impl == &libinput_tablet_pad_impl); + + struct wlr_libinput_input_device *dev = + wl_container_of(wlr_tablet_pad, dev, tablet_pad); + return dev; +} + +void handle_tablet_pad_button(struct libinput_event *event, + struct wlr_tablet_pad *tablet_pad) { + struct libinput_event_tablet_pad *pevent = + libinput_event_get_tablet_pad_event(event); + struct wlr_tablet_pad_button_event wlr_event = { + .time_msec = usec_to_msec(libinput_event_tablet_pad_get_time_usec(pevent)), + .button = libinput_event_tablet_pad_get_button_number(pevent), + .mode = libinput_event_tablet_pad_get_mode(pevent), + .group = libinput_tablet_pad_mode_group_get_index( + libinput_event_tablet_pad_get_mode_group(pevent)), + }; + if (!button_state_from_libinput(libinput_event_tablet_pad_get_button_state(pevent), &wlr_event.state)) { + wlr_log(WLR_DEBUG, "Unhandled libinput button state"); + return; + } + wl_signal_emit_mutable(&tablet_pad->events.button, &wlr_event); +} + +void handle_tablet_pad_ring(struct libinput_event *event, + struct wlr_tablet_pad *tablet_pad) { + struct libinput_event_tablet_pad *pevent = + libinput_event_get_tablet_pad_event(event); + struct wlr_tablet_pad_ring_event wlr_event = { + .time_msec = usec_to_msec(libinput_event_tablet_pad_get_time_usec(pevent)), + .ring = libinput_event_tablet_pad_get_ring_number(pevent), + .position = libinput_event_tablet_pad_get_ring_position(pevent), + .mode = libinput_event_tablet_pad_get_mode(pevent), + .source = WLR_TABLET_PAD_RING_SOURCE_UNKNOWN, + }; + switch (libinput_event_tablet_pad_get_ring_source(pevent)) { + case LIBINPUT_TABLET_PAD_RING_SOURCE_UNKNOWN: + wlr_event.source = WLR_TABLET_PAD_RING_SOURCE_UNKNOWN; + break; + case LIBINPUT_TABLET_PAD_RING_SOURCE_FINGER: + wlr_event.source = WLR_TABLET_PAD_RING_SOURCE_FINGER; + break; + } + wl_signal_emit_mutable(&tablet_pad->events.ring, &wlr_event); +} + +void handle_tablet_pad_strip(struct libinput_event *event, + struct wlr_tablet_pad *tablet_pad) { + struct libinput_event_tablet_pad *pevent = + libinput_event_get_tablet_pad_event(event); + struct wlr_tablet_pad_strip_event wlr_event = { + .time_msec = usec_to_msec(libinput_event_tablet_pad_get_time_usec(pevent)), + .strip = libinput_event_tablet_pad_get_strip_number(pevent), + .position = libinput_event_tablet_pad_get_strip_position(pevent), + .mode = libinput_event_tablet_pad_get_mode(pevent), + .source = WLR_TABLET_PAD_STRIP_SOURCE_UNKNOWN, + }; + switch (libinput_event_tablet_pad_get_strip_source(pevent)) { + case LIBINPUT_TABLET_PAD_STRIP_SOURCE_UNKNOWN: + wlr_event.source = WLR_TABLET_PAD_STRIP_SOURCE_UNKNOWN; + break; + case LIBINPUT_TABLET_PAD_STRIP_SOURCE_FINGER: + wlr_event.source = WLR_TABLET_PAD_STRIP_SOURCE_FINGER; + break; + } + wl_signal_emit_mutable(&tablet_pad->events.strip, &wlr_event); +} diff --git a/3rdparty/wlroots/backend/libinput/tablet_tool.c b/3rdparty/wlroots/backend/libinput/tablet_tool.c new file mode 100644 index 0000000000..782e56a86b --- /dev/null +++ b/3rdparty/wlroots/backend/libinput/tablet_tool.c @@ -0,0 +1,321 @@ +#include +#include +#include +#include +#include +#include +#include +#include "backend/libinput.h" +#include "config.h" + +struct tablet_tool { + struct wlr_tablet_tool wlr_tool; + struct libinput_tablet_tool *handle; + struct wl_list link; // wlr_libinput_input_device.tablet_tools +}; + +const struct wlr_tablet_impl libinput_tablet_impl = { + .name = "libinput-tablet-tool", +}; + +struct libinput_tablet_tool *wlr_libinput_get_tablet_tool_handle( + struct wlr_tablet_tool *wlr_tablet_tool) { + + struct tablet_tool *tool = + wl_container_of(wlr_tablet_tool, tool, wlr_tool); + + assert(tool); + return tool->handle; +} + +void init_device_tablet(struct wlr_libinput_input_device *dev) { + const char *name = get_libinput_device_name(dev->handle); + struct wlr_tablet *wlr_tablet = &dev->tablet; + wlr_tablet_init(wlr_tablet, &libinput_tablet_impl, name); + +#if HAVE_LIBINPUT_BUSTYPE + if (libinput_device_get_id_bustype(dev->handle) == BUS_USB) +#endif + { + wlr_tablet->usb_vendor_id = libinput_device_get_id_vendor(dev->handle); + wlr_tablet->usb_product_id = libinput_device_get_id_product(dev->handle); + } + + libinput_device_get_size(dev->handle, &wlr_tablet->width_mm, + &wlr_tablet->height_mm); + + struct udev_device *udev = libinput_device_get_udev_device(dev->handle); + char **dst = wl_array_add(&wlr_tablet->paths, sizeof(char *)); + *dst = strdup(udev_device_get_syspath(udev)); + udev_device_unref(udev); + + wl_list_init(&dev->tablet_tools); +} + +static void tool_destroy(struct tablet_tool *tool) { + wl_signal_emit_mutable(&tool->wlr_tool.events.destroy, &tool->wlr_tool); + libinput_tablet_tool_unref(tool->handle); + libinput_tablet_tool_set_user_data(tool->handle, NULL); + wl_list_remove(&tool->link); + free(tool); +} + +void finish_device_tablet(struct wlr_libinput_input_device *dev) { + struct tablet_tool *tool, *tmp; + wl_list_for_each_safe(tool, tmp, &dev->tablet_tools, link) { + tool_destroy(tool); + } + + wlr_tablet_finish(&dev->tablet); +} + +struct wlr_libinput_input_device *device_from_tablet( + struct wlr_tablet *wlr_tablet) { + assert(wlr_tablet->impl == &libinput_tablet_impl); + + struct wlr_libinput_input_device *dev = + wl_container_of(wlr_tablet, dev, tablet); + return dev; +} + +static bool type_from_libinput(enum libinput_tablet_tool_type type, + enum wlr_tablet_tool_type *out) { + switch (type) { + case LIBINPUT_TABLET_TOOL_TYPE_PEN: + *out = WLR_TABLET_TOOL_TYPE_PEN; + return true; + case LIBINPUT_TABLET_TOOL_TYPE_ERASER: + *out = WLR_TABLET_TOOL_TYPE_ERASER; + return true; + case LIBINPUT_TABLET_TOOL_TYPE_BRUSH: + *out = WLR_TABLET_TOOL_TYPE_BRUSH; + return true; + case LIBINPUT_TABLET_TOOL_TYPE_PENCIL: + *out = WLR_TABLET_TOOL_TYPE_PENCIL; + return true; + case LIBINPUT_TABLET_TOOL_TYPE_AIRBRUSH: + *out = WLR_TABLET_TOOL_TYPE_AIRBRUSH; + return true; + case LIBINPUT_TABLET_TOOL_TYPE_MOUSE: + *out = WLR_TABLET_TOOL_TYPE_MOUSE; + return true; + case LIBINPUT_TABLET_TOOL_TYPE_LENS: + *out = WLR_TABLET_TOOL_TYPE_LENS; + return true; + case LIBINPUT_TABLET_TOOL_TYPE_TOTEM: + *out = WLR_TABLET_TOOL_TYPE_TOTEM; + return true; + } + return false; +} + +static bool proximity_state_from_libinput(enum libinput_tablet_tool_proximity_state state, + enum wlr_tablet_tool_proximity_state *out) { + switch (state) { + case LIBINPUT_TABLET_TOOL_PROXIMITY_STATE_OUT: + *out = WLR_TABLET_TOOL_PROXIMITY_OUT; + return true; + case LIBINPUT_TABLET_TOOL_PROXIMITY_STATE_IN: + *out = WLR_TABLET_TOOL_PROXIMITY_IN; + return true; + } + return false; +} + +static bool tip_state_from_libinput(enum libinput_tablet_tool_tip_state state, + enum wlr_tablet_tool_tip_state *out) { + switch (state) { + case LIBINPUT_TABLET_TOOL_TIP_UP: + *out = WLR_TABLET_TOOL_TIP_UP; + return true; + case LIBINPUT_TABLET_TOOL_TIP_DOWN: + *out = WLR_TABLET_TOOL_TIP_DOWN; + return true; + } + return false; +} + +static struct tablet_tool *get_tablet_tool( + struct wlr_libinput_input_device *dev, + struct libinput_tablet_tool *libinput_tool) { + struct tablet_tool *tool = + libinput_tablet_tool_get_user_data(libinput_tool); + if (tool) { + return tool; + } + + enum wlr_tablet_tool_type type; + if (!type_from_libinput(libinput_tablet_tool_get_type(libinput_tool), &type)) { + wlr_log(WLR_DEBUG, "Unhandled libinput tablet tool type"); + return NULL; + } + + tool = calloc(1, sizeof(*tool)); + if (tool == NULL) { + wlr_log_errno(WLR_ERROR, "failed to allocate wlr_libinput_tablet_tool"); + return NULL; + } + + tool->wlr_tool.type = type; + tool->wlr_tool.hardware_serial = + libinput_tablet_tool_get_serial(libinput_tool); + tool->wlr_tool.hardware_wacom = + libinput_tablet_tool_get_tool_id(libinput_tool); + + tool->wlr_tool.pressure = libinput_tablet_tool_has_pressure(libinput_tool); + tool->wlr_tool.distance = libinput_tablet_tool_has_distance(libinput_tool); + tool->wlr_tool.tilt = libinput_tablet_tool_has_tilt(libinput_tool); + tool->wlr_tool.rotation = libinput_tablet_tool_has_rotation(libinput_tool); + tool->wlr_tool.slider = libinput_tablet_tool_has_slider(libinput_tool); + tool->wlr_tool.wheel = libinput_tablet_tool_has_wheel(libinput_tool); + + wl_signal_init(&tool->wlr_tool.events.destroy); + + tool->handle = libinput_tablet_tool_ref(libinput_tool); + libinput_tablet_tool_set_user_data(libinput_tool, tool); + + wl_list_insert(&dev->tablet_tools, &tool->link); + return tool; +} + +void handle_tablet_tool_axis(struct libinput_event *event, + struct wlr_tablet *wlr_tablet) { + struct libinput_event_tablet_tool *tevent = + libinput_event_get_tablet_tool_event(event); + struct wlr_libinput_input_device *dev = device_from_tablet(wlr_tablet); + struct tablet_tool *tool = + get_tablet_tool(dev, libinput_event_tablet_tool_get_tool(tevent)); + + struct wlr_tablet_tool_axis_event wlr_event = { + .tablet = wlr_tablet, + .tool = &tool->wlr_tool, + .time_msec = usec_to_msec(libinput_event_tablet_tool_get_time_usec(tevent)), + }; + if (libinput_event_tablet_tool_x_has_changed(tevent)) { + wlr_event.updated_axes |= WLR_TABLET_TOOL_AXIS_X; + wlr_event.x = libinput_event_tablet_tool_get_x_transformed(tevent, 1); + wlr_event.dx = libinput_event_tablet_tool_get_dx(tevent); + } + if (libinput_event_tablet_tool_y_has_changed(tevent)) { + wlr_event.updated_axes |= WLR_TABLET_TOOL_AXIS_Y; + wlr_event.y = libinput_event_tablet_tool_get_y_transformed(tevent, 1); + wlr_event.dy = libinput_event_tablet_tool_get_dy(tevent); + } + if (libinput_event_tablet_tool_pressure_has_changed(tevent)) { + wlr_event.updated_axes |= WLR_TABLET_TOOL_AXIS_PRESSURE; + wlr_event.pressure = libinput_event_tablet_tool_get_pressure(tevent); + } + if (libinput_event_tablet_tool_distance_has_changed(tevent)) { + wlr_event.updated_axes |= WLR_TABLET_TOOL_AXIS_DISTANCE; + wlr_event.distance = libinput_event_tablet_tool_get_distance(tevent); + } + if (libinput_event_tablet_tool_tilt_x_has_changed(tevent)) { + wlr_event.updated_axes |= WLR_TABLET_TOOL_AXIS_TILT_X; + wlr_event.tilt_x = libinput_event_tablet_tool_get_tilt_x(tevent); + } + if (libinput_event_tablet_tool_tilt_y_has_changed(tevent)) { + wlr_event.updated_axes |= WLR_TABLET_TOOL_AXIS_TILT_Y; + wlr_event.tilt_y = libinput_event_tablet_tool_get_tilt_y(tevent); + } + if (libinput_event_tablet_tool_rotation_has_changed(tevent)) { + wlr_event.updated_axes |= WLR_TABLET_TOOL_AXIS_ROTATION; + wlr_event.rotation = libinput_event_tablet_tool_get_rotation(tevent); + } + if (libinput_event_tablet_tool_slider_has_changed(tevent)) { + wlr_event.updated_axes |= WLR_TABLET_TOOL_AXIS_SLIDER; + wlr_event.slider = libinput_event_tablet_tool_get_slider_position(tevent); + } + if (libinput_event_tablet_tool_wheel_has_changed(tevent)) { + wlr_event.updated_axes |= WLR_TABLET_TOOL_AXIS_WHEEL; + wlr_event.wheel_delta = libinput_event_tablet_tool_get_wheel_delta(tevent); + } + wl_signal_emit_mutable(&wlr_tablet->events.axis, &wlr_event); +} + +void handle_tablet_tool_proximity(struct libinput_event *event, + struct wlr_tablet *wlr_tablet) { + struct libinput_event_tablet_tool *tevent = + libinput_event_get_tablet_tool_event(event); + struct wlr_libinput_input_device *dev = device_from_tablet(wlr_tablet); + struct tablet_tool *tool = + get_tablet_tool(dev, libinput_event_tablet_tool_get_tool(tevent)); + + struct wlr_tablet_tool_proximity_event wlr_event = { + .tablet = wlr_tablet, + .tool = &tool->wlr_tool, + .time_msec = usec_to_msec(libinput_event_tablet_tool_get_time_usec(tevent)), + .x = libinput_event_tablet_tool_get_x_transformed(tevent, 1), + .y = libinput_event_tablet_tool_get_y_transformed(tevent, 1), + }; + + if (!proximity_state_from_libinput(libinput_event_tablet_tool_get_proximity_state(tevent), + &wlr_event.state)) { + wlr_log(WLR_DEBUG, "Unhandled libinput tablet tool proximity state"); + return; + } + + wl_signal_emit_mutable(&wlr_tablet->events.proximity, &wlr_event); + + if (libinput_event_tablet_tool_get_proximity_state(tevent) == + LIBINPUT_TABLET_TOOL_PROXIMITY_STATE_IN) { + handle_tablet_tool_axis(event, wlr_tablet); + } + + // If the tool is not unique, libinput will not find it again after the + // proximity out, so we should destroy it + if (!libinput_tablet_tool_is_unique(tool->handle) + && libinput_event_tablet_tool_get_proximity_state(tevent) == + LIBINPUT_TABLET_TOOL_PROXIMITY_STATE_OUT) { + // The tool isn't unique, it can't be on multiple tablets + tool_destroy(tool); + } +} + +void handle_tablet_tool_tip(struct libinput_event *event, + struct wlr_tablet *wlr_tablet) { + handle_tablet_tool_axis(event, wlr_tablet); + struct libinput_event_tablet_tool *tevent = + libinput_event_get_tablet_tool_event(event); + struct wlr_libinput_input_device *dev = device_from_tablet(wlr_tablet); + struct tablet_tool *tool = + get_tablet_tool(dev, libinput_event_tablet_tool_get_tool(tevent)); + + struct wlr_tablet_tool_tip_event wlr_event = { + .tablet = wlr_tablet, + .tool = &tool->wlr_tool, + .time_msec = usec_to_msec(libinput_event_tablet_tool_get_time_usec(tevent)), + .x = libinput_event_tablet_tool_get_x_transformed(tevent, 1), + .y = libinput_event_tablet_tool_get_y_transformed(tevent, 1), + }; + + if (!tip_state_from_libinput(libinput_event_tablet_tool_get_tip_state(tevent), &wlr_event.state)) { + wlr_log(WLR_DEBUG, "Unhandled libinput tablet tool tip state"); + return; + } + + wl_signal_emit_mutable(&wlr_tablet->events.tip, &wlr_event); +} + +void handle_tablet_tool_button(struct libinput_event *event, + struct wlr_tablet *wlr_tablet) { + handle_tablet_tool_axis(event, wlr_tablet); + struct libinput_event_tablet_tool *tevent = + libinput_event_get_tablet_tool_event(event); + struct wlr_libinput_input_device *dev = device_from_tablet(wlr_tablet); + struct tablet_tool *tool = + get_tablet_tool(dev, libinput_event_tablet_tool_get_tool(tevent)); + + struct wlr_tablet_tool_button_event wlr_event = { + .tablet = wlr_tablet, + .tool = &tool->wlr_tool, + .time_msec = usec_to_msec(libinput_event_tablet_tool_get_time_usec(tevent)), + .button = libinput_event_tablet_tool_get_button(tevent), + }; + + if (!button_state_from_libinput(libinput_event_tablet_tool_get_button_state(tevent), &wlr_event.state)) { + wlr_log(WLR_DEBUG, "Unhandled libinput button state"); + return; + } + + wl_signal_emit_mutable(&wlr_tablet->events.button, &wlr_event); +} diff --git a/3rdparty/wlroots/backend/libinput/touch.c b/3rdparty/wlroots/backend/libinput/touch.c new file mode 100644 index 0000000000..077cdf2d8e --- /dev/null +++ b/3rdparty/wlroots/backend/libinput/touch.c @@ -0,0 +1,83 @@ +#include +#include +#include +#include "backend/libinput.h" + +const struct wlr_touch_impl libinput_touch_impl = { + .name = "libinput-touch", +}; + +void init_device_touch(struct wlr_libinput_input_device *dev) { + const char *name = get_libinput_device_name(dev->handle); + struct wlr_touch *wlr_touch = &dev->touch; + wlr_touch_init(wlr_touch, &libinput_touch_impl, name); + + libinput_device_get_size(dev->handle, &wlr_touch->width_mm, + &wlr_touch->height_mm); +} + +struct wlr_libinput_input_device *device_from_touch( + struct wlr_touch *wlr_touch) { + assert(wlr_touch->impl == &libinput_touch_impl); + + struct wlr_libinput_input_device *dev = + wl_container_of(wlr_touch, dev, touch); + return dev; +} + +void handle_touch_down(struct libinput_event *event, + struct wlr_touch *touch) { + struct libinput_event_touch *tevent = + libinput_event_get_touch_event(event); + struct wlr_touch_down_event wlr_event = { 0 }; + wlr_event.touch = touch; + wlr_event.time_msec = + usec_to_msec(libinput_event_touch_get_time_usec(tevent)); + wlr_event.touch_id = libinput_event_touch_get_seat_slot(tevent); + wlr_event.x = libinput_event_touch_get_x_transformed(tevent, 1); + wlr_event.y = libinput_event_touch_get_y_transformed(tevent, 1); + wl_signal_emit_mutable(&touch->events.down, &wlr_event); +} + +void handle_touch_up(struct libinput_event *event, + struct wlr_touch *touch) { + struct libinput_event_touch *tevent = + libinput_event_get_touch_event(event); + struct wlr_touch_up_event wlr_event = { + .touch = touch, + .time_msec = usec_to_msec(libinput_event_touch_get_time_usec(tevent)), + .touch_id = libinput_event_touch_get_seat_slot(tevent), + }; + wl_signal_emit_mutable(&touch->events.up, &wlr_event); +} + +void handle_touch_motion(struct libinput_event *event, + struct wlr_touch *touch) { + struct libinput_event_touch *tevent = + libinput_event_get_touch_event(event); + struct wlr_touch_motion_event wlr_event = { + .touch = touch, + .time_msec = usec_to_msec(libinput_event_touch_get_time_usec(tevent)), + .touch_id = libinput_event_touch_get_seat_slot(tevent), + .x = libinput_event_touch_get_x_transformed(tevent, 1), + .y = libinput_event_touch_get_y_transformed(tevent, 1), + }; + wl_signal_emit_mutable(&touch->events.motion, &wlr_event); +} + +void handle_touch_cancel(struct libinput_event *event, + struct wlr_touch *touch) { + struct libinput_event_touch *tevent = + libinput_event_get_touch_event(event); + struct wlr_touch_cancel_event wlr_event = { + .touch = touch, + .time_msec = usec_to_msec(libinput_event_touch_get_time_usec(tevent)), + .touch_id = libinput_event_touch_get_seat_slot(tevent), + }; + wl_signal_emit_mutable(&touch->events.cancel, &wlr_event); +} + +void handle_touch_frame(struct libinput_event *event, + struct wlr_touch *touch) { + wl_signal_emit_mutable(&touch->events.frame, NULL); +} diff --git a/3rdparty/wlroots/backend/meson.build b/3rdparty/wlroots/backend/meson.build new file mode 100644 index 0000000000..ed977d3b61 --- /dev/null +++ b/3rdparty/wlroots/backend/meson.build @@ -0,0 +1,29 @@ +wlr_files += files('backend.c') + +all_backends = ['drm', 'libinput', 'x11'] +backends = get_option('backends') +if 'auto' in backends and get_option('auto_features').enabled() + backends = all_backends +elif 'auto' in backends and get_option('auto_features').disabled() + backends = [] +endif + +session_required = 'drm' in backends or 'libinput' in backends or get_option('session').enabled() +if get_option('session').disabled() + if session_required + error('Session support is required for the DRM or libinput backends') + endif + session_required = disabler() +endif + +subdir('session') + +foreach backend : all_backends + if backend in backends or 'auto' in backends + subdir(backend) + endif +endforeach + +subdir('multi') +subdir('wayland') +subdir('headless') diff --git a/3rdparty/wlroots/backend/multi/backend.c b/3rdparty/wlroots/backend/multi/backend.c new file mode 100644 index 0000000000..3d8fb96f52 --- /dev/null +++ b/3rdparty/wlroots/backend/multi/backend.c @@ -0,0 +1,300 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "backend/multi.h" + +struct subbackend_state { + struct wlr_backend *backend; + struct wlr_backend *container; + struct wl_listener new_input; + struct wl_listener new_output; + struct wl_listener destroy; + struct wl_list link; +}; + +static struct wlr_multi_backend *multi_backend_from_backend( + struct wlr_backend *wlr_backend) { + assert(wlr_backend_is_multi(wlr_backend)); + struct wlr_multi_backend *backend = wl_container_of(wlr_backend, backend, backend); + return backend; +} + +static bool multi_backend_start(struct wlr_backend *wlr_backend) { + struct wlr_multi_backend *backend = multi_backend_from_backend(wlr_backend); + struct subbackend_state *sub; + wl_list_for_each(sub, &backend->backends, link) { + if (!wlr_backend_start(sub->backend)) { + wlr_log(WLR_ERROR, "Failed to initialize backend."); + return false; + } + } + return true; +} + +static void subbackend_state_destroy(struct subbackend_state *sub) { + wl_list_remove(&sub->new_input.link); + wl_list_remove(&sub->new_output.link); + wl_list_remove(&sub->destroy.link); + wl_list_remove(&sub->link); + free(sub); +} + +static void multi_backend_destroy(struct wlr_backend *wlr_backend) { + struct wlr_multi_backend *backend = multi_backend_from_backend(wlr_backend); + + wl_list_remove(&backend->event_loop_destroy.link); + + wlr_backend_finish(wlr_backend); + + assert(wl_list_empty(&backend->events.backend_add.listener_list)); + assert(wl_list_empty(&backend->events.backend_remove.listener_list)); + + // Some backends may depend on other backends, ie. destroying a backend may + // also destroy other backends + while (!wl_list_empty(&backend->backends)) { + struct subbackend_state *sub = + wl_container_of(backend->backends.next, sub, link); + wlr_backend_destroy(sub->backend); + } + + free(backend); +} + +static int multi_backend_get_drm_fd(struct wlr_backend *backend) { + struct wlr_multi_backend *multi = multi_backend_from_backend(backend); + + struct subbackend_state *sub; + wl_list_for_each(sub, &multi->backends, link) { + if (sub->backend->impl->get_drm_fd) { + return wlr_backend_get_drm_fd(sub->backend); + } + } + + return -1; +} + +static int compare_output_state_backend(const void *data_a, const void *data_b) { + const struct wlr_backend_output_state *a = data_a; + const struct wlr_backend_output_state *b = data_b; + + uintptr_t ptr_a = (uintptr_t)a->output->backend; + uintptr_t ptr_b = (uintptr_t)b->output->backend; + + if (ptr_a == ptr_b) { + return 0; + } else if (ptr_a < ptr_b) { + return -1; + } else { + return 1; + } +} + +static bool commit(struct wlr_backend *backend, + const struct wlr_backend_output_state *states, size_t states_len, + bool test_only) { + // Group states by backend, then perform one commit per backend + struct wlr_backend_output_state *by_backend = malloc(states_len * sizeof(by_backend[0])); + if (by_backend == NULL) { + return false; + } + memcpy(by_backend, states, states_len * sizeof(by_backend[0])); + qsort(by_backend, states_len, sizeof(by_backend[0]), compare_output_state_backend); + + bool ok = true; + for (size_t i = 0; i < states_len;) { + struct wlr_backend *sub = by_backend[i].output->backend; + + size_t len = 1; + while (i + len < states_len && + by_backend[i + len].output->backend == sub) { + len++; + } + + if (test_only) { + ok = wlr_backend_test(sub, &by_backend[i], len); + } else { + ok = wlr_backend_commit(sub, &by_backend[i], len); + } + if (!ok) { + break; + } + i += len; + } + + free(by_backend); + return ok; +} + +static bool multi_backend_test(struct wlr_backend *backend, + const struct wlr_backend_output_state *states, size_t states_len) { + return commit(backend, states, states_len, true); +} + +static bool multi_backend_commit(struct wlr_backend *backend, + const struct wlr_backend_output_state *states, size_t states_len) { + return commit(backend, states, states_len, false); +} + +static const struct wlr_backend_impl backend_impl = { + .start = multi_backend_start, + .destroy = multi_backend_destroy, + .get_drm_fd = multi_backend_get_drm_fd, + .test = multi_backend_test, + .commit = multi_backend_commit, +}; + +static void handle_event_loop_destroy(struct wl_listener *listener, void *data) { + struct wlr_multi_backend *backend = + wl_container_of(listener, backend, event_loop_destroy); + multi_backend_destroy((struct wlr_backend*)backend); +} + +struct wlr_backend *wlr_multi_backend_create(struct wl_event_loop *loop) { + struct wlr_multi_backend *backend = calloc(1, sizeof(*backend)); + if (!backend) { + wlr_log(WLR_ERROR, "Backend allocation failed"); + return NULL; + } + + wl_list_init(&backend->backends); + wlr_backend_init(&backend->backend, &backend_impl); + + wl_signal_init(&backend->events.backend_add); + wl_signal_init(&backend->events.backend_remove); + + backend->event_loop_destroy.notify = handle_event_loop_destroy; + wl_event_loop_add_destroy_listener(loop, &backend->event_loop_destroy); + + return &backend->backend; +} + +bool wlr_backend_is_multi(struct wlr_backend *b) { + return b->impl == &backend_impl; +} + +static void new_input_reemit(struct wl_listener *listener, void *data) { + struct subbackend_state *state = wl_container_of(listener, + state, new_input); + wl_signal_emit_mutable(&state->container->events.new_input, data); +} + +static void new_output_reemit(struct wl_listener *listener, void *data) { + struct subbackend_state *state = wl_container_of(listener, + state, new_output); + wl_signal_emit_mutable(&state->container->events.new_output, data); +} + +static void handle_subbackend_destroy(struct wl_listener *listener, + void *data) { + struct subbackend_state *state = wl_container_of(listener, state, destroy); + subbackend_state_destroy(state); +} + +static struct subbackend_state *multi_backend_get_subbackend(struct wlr_multi_backend *multi, + struct wlr_backend *backend) { + struct subbackend_state *sub = NULL; + wl_list_for_each(sub, &multi->backends, link) { + if (sub->backend == backend) { + return sub; + } + } + return NULL; +} + +static void multi_backend_refresh_features(struct wlr_multi_backend *multi) { + multi->backend.buffer_caps = 0; + multi->backend.features.timeline = true; + + bool has_buffer_cap = false; + uint32_t buffer_caps_intersection = + WLR_BUFFER_CAP_DATA_PTR | WLR_BUFFER_CAP_DMABUF | WLR_BUFFER_CAP_SHM; + struct subbackend_state *sub = NULL; + wl_list_for_each(sub, &multi->backends, link) { + // Only take into account backends capable of presenting a buffer + if (sub->backend->buffer_caps != 0) { + has_buffer_cap = true; + buffer_caps_intersection &= sub->backend->buffer_caps; + } + + // timeline is only applicable to backends that support DMABUFs + if (sub->backend->buffer_caps & WLR_BUFFER_CAP_DMABUF) { + multi->backend.features.timeline = multi->backend.features.timeline && + sub->backend->features.timeline; + } + } + + if (has_buffer_cap) { + multi->backend.buffer_caps = buffer_caps_intersection; + } +} + +bool wlr_multi_backend_add(struct wlr_backend *_multi, + struct wlr_backend *backend) { + assert(_multi && backend); + assert(_multi != backend); + + struct wlr_multi_backend *multi = multi_backend_from_backend(_multi); + + if (multi_backend_get_subbackend(multi, backend)) { + // already added + return true; + } + + struct subbackend_state *sub = calloc(1, sizeof(*sub)); + if (sub == NULL) { + wlr_log(WLR_ERROR, "Could not add backend: allocation failed"); + return false; + } + wl_list_insert(multi->backends.prev, &sub->link); + + sub->backend = backend; + sub->container = &multi->backend; + + wl_signal_add(&backend->events.destroy, &sub->destroy); + sub->destroy.notify = handle_subbackend_destroy; + + wl_signal_add(&backend->events.new_input, &sub->new_input); + sub->new_input.notify = new_input_reemit; + + wl_signal_add(&backend->events.new_output, &sub->new_output); + sub->new_output.notify = new_output_reemit; + + multi_backend_refresh_features(multi); + wl_signal_emit_mutable(&multi->events.backend_add, backend); + return true; +} + +void wlr_multi_backend_remove(struct wlr_backend *_multi, + struct wlr_backend *backend) { + struct wlr_multi_backend *multi = multi_backend_from_backend(_multi); + + struct subbackend_state *sub = + multi_backend_get_subbackend(multi, backend); + + if (sub) { + wl_signal_emit_mutable(&multi->events.backend_remove, backend); + subbackend_state_destroy(sub); + multi_backend_refresh_features(multi); + } +} + +bool wlr_multi_is_empty(struct wlr_backend *_backend) { + assert(wlr_backend_is_multi(_backend)); + struct wlr_multi_backend *backend = (struct wlr_multi_backend *)_backend; + return wl_list_length(&backend->backends) < 1; +} + +void wlr_multi_for_each_backend(struct wlr_backend *_backend, + void (*callback)(struct wlr_backend *backend, void *data), void *data) { + assert(wlr_backend_is_multi(_backend)); + struct wlr_multi_backend *backend = (struct wlr_multi_backend *)_backend; + struct subbackend_state *sub; + wl_list_for_each(sub, &backend->backends, link) { + callback(sub->backend, data); + } +} diff --git a/3rdparty/wlroots/backend/multi/meson.build b/3rdparty/wlroots/backend/multi/meson.build new file mode 100644 index 0000000000..be4abfb64a --- /dev/null +++ b/3rdparty/wlroots/backend/multi/meson.build @@ -0,0 +1 @@ +wlr_files += files('backend.c') diff --git a/3rdparty/wlroots/backend/session/meson.build b/3rdparty/wlroots/backend/session/meson.build new file mode 100644 index 0000000000..4c20ee9df7 --- /dev/null +++ b/3rdparty/wlroots/backend/session/meson.build @@ -0,0 +1,17 @@ +msg = 'Required for session support.' +udev = dependency('libudev', required: session_required, not_found_message: msg) +libseat = dependency( + 'libseat', + version: '>=0.2.0', + fallback: 'seatd', + default_options: ['server=disabled', 'man-pages=disabled', 'examples=disabled'], + required: session_required, + not_found_message: msg, +) +if not (udev.found() and libseat.found()) + subdir_done() +endif + +wlr_files += files('session.c') +wlr_deps += [udev, libseat] +features += { 'session': true } diff --git a/3rdparty/wlroots/backend/session/session.c b/3rdparty/wlroots/backend/session/session.c new file mode 100644 index 0000000000..8687743998 --- /dev/null +++ b/3rdparty/wlroots/backend/session/session.c @@ -0,0 +1,583 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "backend/session/session.h" +#include "util/time.h" + +#include + +#define WAIT_GPU_TIMEOUT 10000 // ms + +static void handle_enable_seat(struct libseat *seat, void *data) { + struct wlr_session *session = data; + session->active = true; + wl_signal_emit_mutable(&session->events.active, NULL); +} + +static void handle_disable_seat(struct libseat *seat, void *data) { + struct wlr_session *session = data; + session->active = false; + wl_signal_emit_mutable(&session->events.active, NULL); + libseat_disable_seat(session->seat_handle); +} + +static int libseat_event(int fd, uint32_t mask, void *data) { + struct wlr_session *session = data; + if (mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR)) { + if (mask & WL_EVENT_ERROR) { + wlr_log(WLR_ERROR, "Failed to wait for libseat event"); + } else { + wlr_log(WLR_INFO, "Failed to wait for libseat event"); + } + wlr_session_destroy(session); + return 0; + } + if (libseat_dispatch(session->seat_handle, 0) == -1) { + wlr_log_errno(WLR_ERROR, "Failed to dispatch libseat"); + wlr_session_destroy(session); + } + return 1; +} + +static struct libseat_seat_listener seat_listener = { + .enable_seat = handle_enable_seat, + .disable_seat = handle_disable_seat, +}; + +static enum wlr_log_importance libseat_log_level_to_wlr( + enum libseat_log_level level) { + switch (level) { + case LIBSEAT_LOG_LEVEL_ERROR: + return WLR_ERROR; + case LIBSEAT_LOG_LEVEL_INFO: + return WLR_INFO; + default: + return WLR_DEBUG; + } +} + +static void log_libseat(enum libseat_log_level level, + const char *fmt, va_list args) { + enum wlr_log_importance importance = libseat_log_level_to_wlr(level); + + static char wlr_fmt[1024]; + snprintf(wlr_fmt, sizeof(wlr_fmt), "[libseat] %s", fmt); + + _wlr_vlog(importance, wlr_fmt, args); +} + +static int libseat_session_init(struct wlr_session *session, + struct wl_event_loop *event_loop) { + libseat_set_log_handler(log_libseat); + libseat_set_log_level(LIBSEAT_LOG_LEVEL_INFO); + + // libseat will take care of updating the logind state if necessary + setenv("XDG_SESSION_TYPE", "wayland", 1); + + session->seat_handle = libseat_open_seat(&seat_listener, session); + if (session->seat_handle == NULL) { + wlr_log_errno(WLR_ERROR, "Unable to create seat"); + return -1; + } + + const char *seat_name = libseat_seat_name(session->seat_handle); + if (seat_name == NULL) { + wlr_log_errno(WLR_ERROR, "Unable to get seat info"); + goto error; + } + snprintf(session->seat, sizeof(session->seat), "%s", seat_name); + + session->libseat_event = wl_event_loop_add_fd(event_loop, libseat_get_fd(session->seat_handle), + WL_EVENT_READABLE, libseat_event, session); + if (session->libseat_event == NULL) { + wlr_log(WLR_ERROR, "Failed to create libseat event source"); + goto error; + } + + // We may have received enable_seat immediately after the open_seat result, + // so, dispatch once without timeout to speed up activation. + if (libseat_dispatch(session->seat_handle, 0) == -1) { + wlr_log_errno(WLR_ERROR, "libseat dispatch failed"); + goto error_dispatch; + } + + wlr_log(WLR_INFO, "Successfully loaded libseat session"); + return 0; + +error_dispatch: + wl_event_source_remove(session->libseat_event); + session->libseat_event = NULL; +error: + libseat_close_seat(session->seat_handle); + session->seat_handle = NULL; + return -1; +} + +static void libseat_session_finish(struct wlr_session *session) { + libseat_close_seat(session->seat_handle); + wl_event_source_remove(session->libseat_event); + session->seat_handle = NULL; + session->libseat_event = NULL; +} + +static bool is_drm_card(const char *sysname) { + const char prefix[] = DRM_PRIMARY_MINOR_NAME; + if (strncmp(sysname, prefix, strlen(prefix)) != 0) { + return false; + } + for (size_t i = strlen(prefix); sysname[i] != '\0'; i++) { + if (sysname[i] < '0' || sysname[i] > '9') { + return false; + } + } + return true; +} + +static void read_udev_change_event(struct wlr_device_change_event *event, + struct udev_device *udev_dev) { + const char *hotplug = udev_device_get_property_value(udev_dev, "HOTPLUG"); + if (hotplug != NULL && strcmp(hotplug, "1") == 0) { + event->type = WLR_DEVICE_HOTPLUG; + struct wlr_device_hotplug_event *hotplug = &event->hotplug; + + const char *connector = + udev_device_get_property_value(udev_dev, "CONNECTOR"); + if (connector != NULL) { + hotplug->connector_id = strtoul(connector, NULL, 10); + } + + const char *prop = + udev_device_get_property_value(udev_dev, "PROPERTY"); + if (prop != NULL) { + hotplug->prop_id = strtoul(prop, NULL, 10); + } + + return; + } + + const char *lease = udev_device_get_property_value(udev_dev, "LEASE"); + if (lease != NULL && strcmp(lease, "1") == 0) { + event->type = WLR_DEVICE_LEASE; + return; + } +} + +static int handle_udev_event(int fd, uint32_t mask, void *data) { + struct wlr_session *session = data; + + struct udev_device *udev_dev = udev_monitor_receive_device(session->mon); + if (!udev_dev) { + return 1; + } + + const char *sysname = udev_device_get_sysname(udev_dev); + const char *devnode = udev_device_get_devnode(udev_dev); + const char *action = udev_device_get_action(udev_dev); + wlr_log(WLR_DEBUG, "udev event for %s (%s)", sysname, action); + + if (!is_drm_card(sysname) || !action || !devnode) { + goto out; + } + + const char *seat = udev_device_get_property_value(udev_dev, "ID_SEAT"); + if (!seat) { + seat = "seat0"; + } + if (session->seat[0] != '\0' && strcmp(session->seat, seat) != 0) { + goto out; + } + + dev_t devnum = udev_device_get_devnum(udev_dev); + if (strcmp(action, "add") == 0) { + struct wlr_device *dev; + wl_list_for_each(dev, &session->devices, link) { + if (dev->dev == devnum) { + wlr_log(WLR_DEBUG, "Skipping duplicate device %s", sysname); + goto out; + } + } + + wlr_log(WLR_DEBUG, "DRM device %s added", sysname); + struct wlr_session_add_event event = { + .path = devnode, + }; + wl_signal_emit_mutable(&session->events.add_drm_card, &event); + } else if (strcmp(action, "change") == 0) { + struct wlr_device *dev; + wl_list_for_each(dev, &session->devices, link) { + if (dev->dev == devnum) { + wlr_log(WLR_DEBUG, "DRM device %s changed", sysname); + struct wlr_device_change_event event = {0}; + read_udev_change_event(&event, udev_dev); + wl_signal_emit_mutable(&dev->events.change, &event); + break; + } + } + } else if (strcmp(action, "remove") == 0) { + struct wlr_device *dev; + wl_list_for_each(dev, &session->devices, link) { + if (dev->dev == devnum) { + wlr_log(WLR_DEBUG, "DRM device %s removed", sysname); + wl_signal_emit_mutable(&dev->events.remove, NULL); + break; + } + } + } + +out: + udev_device_unref(udev_dev); + return 1; +} + +static void handle_event_loop_destroy(struct wl_listener *listener, void *data) { + struct wlr_session *session = + wl_container_of(listener, session, event_loop_destroy); + wlr_session_destroy(session); +} + +struct wlr_session *wlr_session_create(struct wl_event_loop *event_loop) { + struct wlr_session *session = calloc(1, sizeof(*session)); + if (!session) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + + session->event_loop = event_loop; + wl_signal_init(&session->events.active); + wl_signal_init(&session->events.add_drm_card); + wl_signal_init(&session->events.destroy); + wl_list_init(&session->devices); + + if (libseat_session_init(session, event_loop) == -1) { + wlr_log(WLR_ERROR, "Failed to load session backend"); + goto error_open; + } + + session->udev = udev_new(); + if (!session->udev) { + wlr_log_errno(WLR_ERROR, "Failed to create udev context"); + goto error_session; + } + + session->mon = udev_monitor_new_from_netlink(session->udev, "udev"); + if (!session->mon) { + wlr_log_errno(WLR_ERROR, "Failed to create udev monitor"); + goto error_udev; + } + + udev_monitor_filter_add_match_subsystem_devtype(session->mon, "drm", NULL); + udev_monitor_enable_receiving(session->mon); + + int fd = udev_monitor_get_fd(session->mon); + + session->udev_event = wl_event_loop_add_fd(event_loop, fd, + WL_EVENT_READABLE, handle_udev_event, session); + if (!session->udev_event) { + wlr_log_errno(WLR_ERROR, "Failed to create udev event source"); + goto error_mon; + } + + session->event_loop_destroy.notify = handle_event_loop_destroy; + wl_event_loop_add_destroy_listener(event_loop, &session->event_loop_destroy); + + return session; + +error_mon: + udev_monitor_unref(session->mon); +error_udev: + udev_unref(session->udev); +error_session: + libseat_session_finish(session); +error_open: + free(session); + return NULL; +} + +void wlr_session_destroy(struct wlr_session *session) { + if (!session) { + return; + } + + wl_signal_emit_mutable(&session->events.destroy, session); + + assert(wl_list_empty(&session->events.active.listener_list)); + assert(wl_list_empty(&session->events.add_drm_card.listener_list)); + assert(wl_list_empty(&session->events.destroy.listener_list)); + + wl_list_remove(&session->event_loop_destroy.link); + + wl_event_source_remove(session->udev_event); + udev_monitor_unref(session->mon); + udev_unref(session->udev); + + struct wlr_device *dev, *tmp_dev; + wl_list_for_each_safe(dev, tmp_dev, &session->devices, link) { + wlr_session_close_file(session, dev); + } + + libseat_session_finish(session); + free(session); +} + +struct wlr_device *wlr_session_open_file(struct wlr_session *session, + const char *path) { + int fd; + int device_id = libseat_open_device(session->seat_handle, path, &fd); + if (device_id == -1) { + wlr_log_errno(WLR_ERROR, "Failed to open device: '%s'", path); + return NULL; + } + + struct wlr_device *dev = malloc(sizeof(*dev)); + if (!dev) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + goto error; + } + + struct stat st; + if (fstat(fd, &st) < 0) { + wlr_log_errno(WLR_ERROR, "Stat failed"); + goto error; + } + + dev->fd = fd; + dev->dev = st.st_rdev; + dev->device_id = device_id; + wl_signal_init(&dev->events.change); + wl_signal_init(&dev->events.remove); + wl_list_insert(&session->devices, &dev->link); + + return dev; + +error: + libseat_close_device(session->seat_handle, device_id); + free(dev); + close(fd); + return NULL; +} + +void wlr_session_close_file(struct wlr_session *session, + struct wlr_device *dev) { + if (libseat_close_device(session->seat_handle, dev->device_id) == -1) { + wlr_log_errno(WLR_ERROR, "Failed to close device %d", dev->device_id); + } + + assert(wl_list_empty(&dev->events.change.listener_list)); + // TODO: assert that the "remove" listener list is empty as well. Listeners + // will typically call wlr_session_close_file() in response, and + // wl_signal_emit_mutable() installs two phantom listeners, so we'd count + // these two. + + close(dev->fd); + wl_list_remove(&dev->link); + free(dev); +} + +bool wlr_session_change_vt(struct wlr_session *session, unsigned vt) { + if (!session) { + return false; + } + return libseat_switch_session(session->seat_handle, vt) == 0; +} + +/* Tests if 'path' is KMS compatible by trying to open it. Returns the opened + * device on success. */ +struct wlr_device *session_open_if_kms(struct wlr_session *restrict session, + const char *restrict path) { + if (!path) { + return NULL; + } + + struct wlr_device *dev = wlr_session_open_file(session, path); + if (!dev) { + return NULL; + } + + if (!drmIsKMS(dev->fd)) { + wlr_log(WLR_DEBUG, "Ignoring '%s': not a KMS device", path); + wlr_session_close_file(session, dev); + return NULL; + } + + return dev; +} + +static ssize_t explicit_find_gpus(struct wlr_session *session, + size_t ret_len, struct wlr_device *ret[static ret_len], const char *str) { + char *gpus = strdup(str); + if (!gpus) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return -1; + } + + size_t i = 0; + char *save; + char *ptr = strtok_r(gpus, ":", &save); + do { + if (i >= ret_len) { + break; + } + + ret[i] = session_open_if_kms(session, ptr); + if (!ret[i]) { + wlr_log(WLR_ERROR, "Unable to open %s as KMS device", ptr); + } else { + ++i; + } + } while ((ptr = strtok_r(NULL, ":", &save))); + + free(gpus); + return i; +} + +static struct udev_enumerate *enumerate_drm_cards(struct udev *udev) { + struct udev_enumerate *en = udev_enumerate_new(udev); + if (!en) { + wlr_log(WLR_ERROR, "udev_enumerate_new failed"); + return NULL; + } + + udev_enumerate_add_match_subsystem(en, "drm"); + udev_enumerate_add_match_sysname(en, DRM_PRIMARY_MINOR_NAME "[0-9]*"); + + if (udev_enumerate_scan_devices(en) != 0) { + wlr_log(WLR_ERROR, "udev_enumerate_scan_devices failed"); + udev_enumerate_unref(en); + return NULL; + } + + return en; +} + +struct find_gpus_add_handler { + bool added; + struct wl_listener listener; +}; + +static void find_gpus_handle_add(struct wl_listener *listener, void *data) { + struct find_gpus_add_handler *handler = + wl_container_of(listener, handler, listener); + handler->added = true; +} + +ssize_t wlr_session_find_gpus(struct wlr_session *session, + size_t ret_len, struct wlr_device **ret) { + const char *explicit = getenv("WLR_DRM_DEVICES"); + if (explicit) { + wlr_log(WLR_INFO, "Opening fixed list of KMS devices from WLR_DRM_DEVICES: %s", explicit); + return explicit_find_gpus(session, ret_len, ret, explicit); + } + + struct udev_enumerate *en = enumerate_drm_cards(session->udev); + if (!en) { + return -1; + } + + if (udev_enumerate_get_list_entry(en) == NULL) { + udev_enumerate_unref(en); + en = NULL; + wlr_log(WLR_INFO, "Waiting for a KMS device"); + + struct find_gpus_add_handler handler = {0}; + handler.listener.notify = find_gpus_handle_add; + wl_signal_add(&session->events.add_drm_card, &handler.listener); + + int64_t started_at = get_current_time_msec(); + int64_t timeout = WAIT_GPU_TIMEOUT; + while (!handler.added) { + int ret = wl_event_loop_dispatch(session->event_loop, (int)timeout); + if (ret < 0) { + wlr_log_errno(WLR_ERROR, "Failed to wait for KMS device: " + "wl_event_loop_dispatch failed"); + return -1; + } + + int64_t now = get_current_time_msec(); + if (now >= started_at + WAIT_GPU_TIMEOUT) { + break; + } + timeout = started_at + WAIT_GPU_TIMEOUT - now; + } + + wl_list_remove(&handler.listener.link); + + en = enumerate_drm_cards(session->udev); + if (!en) { + return -1; + } + } + + struct udev_list_entry *entry; + size_t i = 0; + + udev_list_entry_foreach(entry, udev_enumerate_get_list_entry(en)) { + if (i == ret_len) { + break; + } + + const char *path = udev_list_entry_get_name(entry); + struct udev_device *dev = udev_device_new_from_syspath(session->udev, path); + if (!dev) { + continue; + } + + const char *seat = udev_device_get_property_value(dev, "ID_SEAT"); + if (!seat) { + seat = "seat0"; + } + if (session->seat[0] && strcmp(session->seat, seat) != 0) { + udev_device_unref(dev); + continue; + } + + bool is_primary = false; + const char *boot_display = udev_device_get_sysattr_value(dev, "boot_display"); + if (boot_display && strcmp(boot_display, "1") == 0) { + is_primary = true; + } else { + // This is owned by 'dev', so we don't need to free it + struct udev_device *pci = + udev_device_get_parent_with_subsystem_devtype(dev, "pci", NULL); + + if (pci) { + const char *id = udev_device_get_sysattr_value(pci, "boot_vga"); + if (id && strcmp(id, "1") == 0) { + is_primary = true; + } + } + } + + struct wlr_device *wlr_dev = + session_open_if_kms(session, udev_device_get_devnode(dev)); + udev_device_unref(dev); + if (!wlr_dev) { + continue; + } + + ret[i] = wlr_dev; + if (is_primary) { + struct wlr_device *tmp = ret[0]; + ret[0] = ret[i]; + ret[i] = tmp; + } + + ++i; + } + + udev_enumerate_unref(en); + + return i; +} diff --git a/3rdparty/wlroots/backend/wayland/backend.c b/3rdparty/wlroots/backend/wayland/backend.c new file mode 100644 index 0000000000..14a783b671 --- /dev/null +++ b/3rdparty/wlroots/backend/wayland/backend.c @@ -0,0 +1,744 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include "backend/wayland.h" +#include "render/drm_format_set.h" +#include "render/pixel_format.h" + +#include "drm-client-protocol.h" +#include "linux-dmabuf-v1-client-protocol.h" +#include "linux-drm-syncobj-v1-client-protocol.h" +#include "pointer-gestures-unstable-v1-client-protocol.h" +#include "presentation-time-client-protocol.h" +#include "xdg-activation-v1-client-protocol.h" +#include "xdg-decoration-unstable-v1-client-protocol.h" +#include "xdg-shell-client-protocol.h" +#include "tablet-v2-client-protocol.h" +#include "relative-pointer-unstable-v1-client-protocol.h" +#include "viewporter-client-protocol.h" + +struct wlr_wl_linux_dmabuf_feedback_v1 { + struct wlr_wl_backend *backend; + dev_t main_device_id; + struct wlr_wl_linux_dmabuf_v1_table_entry *format_table; + size_t format_table_size; + + dev_t tranche_target_device_id; +}; + +struct wlr_wl_linux_dmabuf_v1_table_entry { + uint32_t format; + uint32_t pad; /* unused */ + uint64_t modifier; +}; + +struct wlr_wl_backend *get_wl_backend_from_backend(struct wlr_backend *wlr_backend) { + assert(wlr_backend_is_wl(wlr_backend)); + struct wlr_wl_backend *backend = wl_container_of(wlr_backend, backend, backend); + return backend; +} + +static int dispatch_events(int fd, uint32_t mask, void *data) { + struct wlr_wl_backend *wl = data; + + int count = 0; + if (mask & WL_EVENT_READABLE) { + count = wl_display_dispatch(wl->remote_display); + } + if (mask & WL_EVENT_WRITABLE) { + wl_display_flush(wl->remote_display); + } + if (mask == 0) { + count = wl_display_dispatch_pending(wl->remote_display); + wl_display_flush(wl->remote_display); + } + + // Make sure we've consumed all data before disconnecting due to hangup, + // so that we process any wl_display.error events + if (!(mask & WL_EVENT_READABLE) && (mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR))) { + if (mask & WL_EVENT_ERROR) { + wlr_log(WLR_ERROR, "Failed to read from remote Wayland display"); + } else { + wlr_log(WLR_DEBUG, "Disconnected from remote Wayland display"); + } + wlr_backend_destroy(&wl->backend); + return 0; + } + + if (count < 0) { + wlr_log(WLR_ERROR, "Failed to dispatch remote Wayland display"); + wlr_backend_destroy(&wl->backend); + return 0; + } + return count; +} + +static void xdg_wm_base_handle_ping(void *data, + struct xdg_wm_base *base, uint32_t serial) { + xdg_wm_base_pong(base, serial); +} + +static const struct xdg_wm_base_listener xdg_wm_base_listener = { + xdg_wm_base_handle_ping, +}; + +static void presentation_handle_clock_id(void *data, + struct wp_presentation *presentation, uint32_t clock) { + struct wlr_wl_backend *wl = data; + + if (clock != CLOCK_MONOTONIC) { + wp_presentation_destroy(wl->presentation); + wl->presentation = NULL; + } +} + +static const struct wp_presentation_listener presentation_listener = { + .clock_id = presentation_handle_clock_id, +}; + +static void linux_dmabuf_v1_handle_format(void *data, + struct zwp_linux_dmabuf_v1 *linux_dmabuf_v1, uint32_t format) { + // Note, this event is deprecated + struct wlr_wl_backend *wl = data; + + wlr_drm_format_set_add(&wl->linux_dmabuf_v1_formats, format, + DRM_FORMAT_MOD_INVALID); +} + +static void linux_dmabuf_v1_handle_modifier(void *data, + struct zwp_linux_dmabuf_v1 *linux_dmabuf_v1, uint32_t format, + uint32_t modifier_hi, uint32_t modifier_lo) { + struct wlr_wl_backend *wl = data; + + uint64_t modifier = ((uint64_t)modifier_hi << 32) | modifier_lo; + wlr_drm_format_set_add(&wl->linux_dmabuf_v1_formats, format, modifier); +} + +static const struct zwp_linux_dmabuf_v1_listener linux_dmabuf_v1_listener = { + .format = linux_dmabuf_v1_handle_format, + .modifier = linux_dmabuf_v1_handle_modifier, +}; + +static void linux_dmabuf_feedback_v1_handle_done(void *data, + struct zwp_linux_dmabuf_feedback_v1 *feedback) { + // This space is intentionally left blank +} + +static void linux_dmabuf_feedback_v1_handle_format_table(void *data, + struct zwp_linux_dmabuf_feedback_v1 *feedback, int fd, uint32_t size) { + struct wlr_wl_linux_dmabuf_feedback_v1 *feedback_data = data; + + feedback_data->format_table = NULL; + + void *table_data = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0); + if (table_data == MAP_FAILED) { + wlr_log_errno(WLR_ERROR, "failed to mmap DMA-BUF format table"); + } else { + feedback_data->format_table = table_data; + feedback_data->format_table_size = size; + } + close(fd); +} + +static void linux_dmabuf_feedback_v1_handle_main_device(void *data, + struct zwp_linux_dmabuf_feedback_v1 *feedback, + struct wl_array *dev_id_arr) { + struct wlr_wl_linux_dmabuf_feedback_v1 *feedback_data = data; + + dev_t dev_id; + assert(dev_id_arr->size == sizeof(dev_id)); + memcpy(&dev_id, dev_id_arr->data, sizeof(dev_id)); + + feedback_data->main_device_id = dev_id; + + drmDevice *device = NULL; + if (drmGetDeviceFromDevId(dev_id, 0, &device) != 0) { + wlr_log_errno(WLR_ERROR, "drmGetDeviceFromDevId failed"); + return; + } + + const char *name = NULL; + if (device->available_nodes & (1 << DRM_NODE_RENDER)) { + name = device->nodes[DRM_NODE_RENDER]; + } else { + // Likely a split display/render setup. Pick the primary node and hope + // Mesa will open the right render node under-the-hood. + assert(device->available_nodes & (1 << DRM_NODE_PRIMARY)); + name = device->nodes[DRM_NODE_PRIMARY]; + wlr_log(WLR_DEBUG, "DRM device %s has no render node, " + "falling back to primary node", name); + } + + struct wlr_wl_backend *wl = feedback_data->backend; + assert(wl->drm_render_name == NULL); + wl->drm_render_name = strdup(name); + + drmFreeDevice(&device); +} + +static void linux_dmabuf_feedback_v1_handle_tranche_done(void *data, + struct zwp_linux_dmabuf_feedback_v1 *feedback) { + struct wlr_wl_linux_dmabuf_feedback_v1 *feedback_data = data; + feedback_data->tranche_target_device_id = 0; +} + +static void linux_dmabuf_feedback_v1_handle_tranche_target_device(void *data, + struct zwp_linux_dmabuf_feedback_v1 *feedback, + struct wl_array *dev_id_arr) { + struct wlr_wl_linux_dmabuf_feedback_v1 *feedback_data = data; + + dev_t dev_id; + assert(dev_id_arr->size == sizeof(dev_id)); + memcpy(&dev_id, dev_id_arr->data, sizeof(dev_id)); + + feedback_data->tranche_target_device_id = dev_id; +} + +static void linux_dmabuf_feedback_v1_handle_tranche_formats(void *data, + struct zwp_linux_dmabuf_feedback_v1 *feedback, + struct wl_array *indices_arr) { + struct wlr_wl_linux_dmabuf_feedback_v1 *feedback_data = data; + + if (feedback_data->format_table == NULL) { + return; + } + if (feedback_data->tranche_target_device_id != feedback_data->main_device_id) { + return; + } + + size_t table_cap = feedback_data->format_table_size / + sizeof(struct wlr_wl_linux_dmabuf_v1_table_entry); + uint16_t *index_ptr; + wl_array_for_each(index_ptr, indices_arr) { + assert(*index_ptr < table_cap); + const struct wlr_wl_linux_dmabuf_v1_table_entry *entry = + &feedback_data->format_table[*index_ptr]; + wlr_drm_format_set_add(&feedback_data->backend->linux_dmabuf_v1_formats, + entry->format, entry->modifier); + } +} + +static void linux_dmabuf_feedback_v1_handle_tranche_flags(void *data, + struct zwp_linux_dmabuf_feedback_v1 *feedback, uint32_t flags) { + // TODO: handle SCANOUT flag +} + +static const struct zwp_linux_dmabuf_feedback_v1_listener + linux_dmabuf_feedback_v1_listener = { + .done = linux_dmabuf_feedback_v1_handle_done, + .format_table = linux_dmabuf_feedback_v1_handle_format_table, + .main_device = linux_dmabuf_feedback_v1_handle_main_device, + .tranche_done = linux_dmabuf_feedback_v1_handle_tranche_done, + .tranche_target_device = linux_dmabuf_feedback_v1_handle_tranche_target_device, + .tranche_formats = linux_dmabuf_feedback_v1_handle_tranche_formats, + .tranche_flags = linux_dmabuf_feedback_v1_handle_tranche_flags, +}; + +static bool device_has_name(const drmDevice *device, const char *name) { + for (size_t i = 0; i < DRM_NODE_MAX; i++) { + if (!(device->available_nodes & (1 << i))) { + continue; + } + if (strcmp(device->nodes[i], name) == 0) { + return true; + } + } + return false; +} + +static char *get_render_name(const char *name) { + uint32_t flags = 0; + int devices_len = drmGetDevices2(flags, NULL, 0); + if (devices_len < 0) { + wlr_log(WLR_ERROR, "drmGetDevices2 failed: %s", strerror(-devices_len)); + return NULL; + } + drmDevice **devices = calloc(devices_len, sizeof(*devices)); + if (devices == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + devices_len = drmGetDevices2(flags, devices, devices_len); + if (devices_len < 0) { + free(devices); + wlr_log(WLR_ERROR, "drmGetDevices2 failed: %s", strerror(-devices_len)); + return NULL; + } + + const drmDevice *match = NULL; + for (int i = 0; i < devices_len; i++) { + if (device_has_name(devices[i], name)) { + match = devices[i]; + break; + } + } + + char *render_name = NULL; + if (match == NULL) { + wlr_log(WLR_ERROR, "Cannot find DRM device %s", name); + } else if (!(match->available_nodes & (1 << DRM_NODE_RENDER))) { + // Likely a split display/render setup. Pick the primary node and hope + // Mesa will open the right render node under-the-hood. + wlr_log(WLR_DEBUG, "DRM device %s has no render node, " + "falling back to primary node", name); + assert(match->available_nodes & (1 << DRM_NODE_PRIMARY)); + render_name = strdup(match->nodes[DRM_NODE_PRIMARY]); + } else { + render_name = strdup(match->nodes[DRM_NODE_RENDER]); + } + + for (int i = 0; i < devices_len; i++) { + drmFreeDevice(&devices[i]); + } + free(devices); + + return render_name; +} + +static void legacy_drm_handle_device(void *data, struct wl_drm *drm, + const char *name) { + struct wlr_wl_backend *wl = data; + assert(wl->drm_render_name == NULL); + wl->drm_render_name = get_render_name(name); +} + +static void legacy_drm_handle_format(void *data, struct wl_drm *drm, + uint32_t format) { + // This space is intentionally left blank +} + +static void legacy_drm_handle_authenticated(void *data, struct wl_drm *drm) { + // This space is intentionally left blank +} + +static void legacy_drm_handle_capabilities(void *data, struct wl_drm *drm, + uint32_t caps) { + // This space is intentionally left blank +} + +static const struct wl_drm_listener legacy_drm_listener = { + .device = legacy_drm_handle_device, + .format = legacy_drm_handle_format, + .authenticated = legacy_drm_handle_authenticated, + .capabilities = legacy_drm_handle_capabilities, +}; + +static void shm_handle_format(void *data, struct wl_shm *shm, + uint32_t shm_format) { + struct wlr_wl_backend *wl = data; + uint32_t drm_format = convert_wl_shm_format_to_drm(shm_format); + wlr_drm_format_set_add(&wl->shm_formats, drm_format, DRM_FORMAT_MOD_INVALID); +} + +static const struct wl_shm_listener shm_listener = { + .format = shm_handle_format, +}; + +static void registry_global(void *data, struct wl_registry *registry, + uint32_t name, const char *iface, uint32_t version) { + struct wlr_wl_backend *wl = data; + + wlr_log(WLR_DEBUG, "Remote wayland global: %s v%" PRIu32, iface, version); + + if (strcmp(iface, wl_compositor_interface.name) == 0) { + wl->compositor = wl_registry_bind(registry, name, + &wl_compositor_interface, 4); + } else if (strcmp(iface, wl_seat_interface.name) == 0) { + uint32_t target_version = version; + if (version < 5) { + target_version = 5; + } + if (version > 9) { + target_version = 9; + } + struct wl_seat *wl_seat = wl_registry_bind(registry, name, + &wl_seat_interface, target_version); + if (!create_wl_seat(wl_seat, wl, name)) { + wl_seat_destroy(wl_seat); + } + } else if (strcmp(iface, xdg_wm_base_interface.name) == 0) { + wl->xdg_wm_base = wl_registry_bind(registry, name, + &xdg_wm_base_interface, 1); + xdg_wm_base_add_listener(wl->xdg_wm_base, &xdg_wm_base_listener, NULL); + } else if (strcmp(iface, zxdg_decoration_manager_v1_interface.name) == 0) { + wl->zxdg_decoration_manager_v1 = wl_registry_bind(registry, name, + &zxdg_decoration_manager_v1_interface, 1); + } else if (strcmp(iface, zwp_pointer_gestures_v1_interface.name) == 0) { + wl->zwp_pointer_gestures_v1 = wl_registry_bind(registry, name, + &zwp_pointer_gestures_v1_interface, version < 3 ? version : 3); + } else if (strcmp(iface, wp_presentation_interface.name) == 0) { + wl->presentation = wl_registry_bind(registry, name, + &wp_presentation_interface, 1); + wp_presentation_add_listener(wl->presentation, + &presentation_listener, wl); + } else if (strcmp(iface, zwp_tablet_manager_v2_interface.name) == 0) { + wl->tablet_manager = wl_registry_bind(registry, name, + &zwp_tablet_manager_v2_interface, 1); + } else if (strcmp(iface, zwp_linux_dmabuf_v1_interface.name) == 0 && + version >= 3) { + wl->zwp_linux_dmabuf_v1 = wl_registry_bind(registry, name, + &zwp_linux_dmabuf_v1_interface, version >= 4 ? 4 : version); + zwp_linux_dmabuf_v1_add_listener(wl->zwp_linux_dmabuf_v1, + &linux_dmabuf_v1_listener, wl); + } else if (strcmp(iface, zwp_relative_pointer_manager_v1_interface.name) == 0) { + wl->zwp_relative_pointer_manager_v1 = wl_registry_bind(registry, name, + &zwp_relative_pointer_manager_v1_interface, 1); + } else if (strcmp(iface, wl_drm_interface.name) == 0) { + wl->legacy_drm = wl_registry_bind(registry, name, &wl_drm_interface, 1); + wl_drm_add_listener(wl->legacy_drm, &legacy_drm_listener, wl); + } else if (strcmp(iface, wl_shm_interface.name) == 0) { + uint32_t target_version = version; + if (version > 2) { + target_version = 2; + } + wl->shm = wl_registry_bind(registry, name, &wl_shm_interface, target_version); + wl_shm_add_listener(wl->shm, &shm_listener, wl); + } else if (strcmp(iface, xdg_activation_v1_interface.name) == 0) { + wl->activation_v1 = wl_registry_bind(registry, name, + &xdg_activation_v1_interface, 1); + } else if (strcmp(iface, wl_subcompositor_interface.name) == 0) { + wl->subcompositor = wl_registry_bind(registry, name, + &wl_subcompositor_interface, 1); + } else if (strcmp(iface, wp_viewporter_interface.name) == 0) { + wl->viewporter = wl_registry_bind(registry, name, + &wp_viewporter_interface, 1); + } else if (strcmp(iface, wp_linux_drm_syncobj_manager_v1_interface.name) == 0) { + wl->drm_syncobj_manager_v1 = wl_registry_bind(registry, name, + &wp_linux_drm_syncobj_manager_v1_interface, 1); + } +} + +static void registry_global_remove(void *data, struct wl_registry *registry, + uint32_t name) { + struct wlr_wl_backend *wl = data; + + struct wlr_wl_seat *seat; + wl_list_for_each(seat, &wl->seats, link) { + if (seat->global_name == name) { + destroy_wl_seat(seat); + break; + } + } +} + +static const struct wl_registry_listener registry_listener = { + .global = registry_global, + .global_remove = registry_global_remove +}; + +/* + * Initializes the wayland backend. Opens a connection to a remote wayland + * compositor and creates surfaces for each output, then registers globals on + * the specified display. + */ +static bool backend_start(struct wlr_backend *backend) { + struct wlr_wl_backend *wl = get_wl_backend_from_backend(backend); + wlr_log(WLR_INFO, "Starting Wayland backend"); + + wl->started = true; + + struct wlr_wl_seat *seat; + wl_list_for_each(seat, &wl->seats, link) { + if (seat->wl_keyboard) { + init_seat_keyboard(seat); + } + + if (seat->wl_touch) { + init_seat_touch(seat); + } + + if (wl->tablet_manager) { + init_seat_tablet(seat); + } + } + + for (size_t i = 0; i < wl->requested_outputs; ++i) { + wlr_wl_output_create(&wl->backend); + } + + return true; +} + +static void backend_destroy(struct wlr_backend *backend) { + if (!backend) { + return; + } + + struct wlr_wl_backend *wl = get_wl_backend_from_backend(backend); + + struct wlr_wl_output *output, *tmp_output; + wl_list_for_each_safe(output, tmp_output, &wl->outputs, link) { + wlr_output_destroy(&output->wlr_output); + } + + // Avoid using wl_list_for_each_safe() here: destroying a buffer may + // have the side-effect of destroying the next one in the list + while (!wl_list_empty(&wl->buffers)) { + struct wlr_wl_buffer *buffer = wl_container_of(wl->buffers.next, buffer, link); + destroy_wl_buffer(buffer); + } + + struct wlr_wl_drm_syncobj_timeline *timeline, *tmp_timeline; + wl_list_for_each_safe(timeline, tmp_timeline, &wl->drm_syncobj_timelines, link) { + destroy_wl_drm_syncobj_timeline(timeline); + } + + wlr_backend_finish(backend); + + wl_list_remove(&wl->event_loop_destroy.link); + + wl_event_source_remove(wl->remote_display_src); + + close(wl->drm_fd); + + wlr_drm_format_set_finish(&wl->shm_formats); + wlr_drm_format_set_finish(&wl->linux_dmabuf_v1_formats); + + struct wlr_wl_seat *seat, *tmp_seat; + wl_list_for_each_safe(seat, tmp_seat, &wl->seats, link) { + destroy_wl_seat(seat); + } + + if (wl->activation_v1) { + xdg_activation_v1_destroy(wl->activation_v1); + } + if (wl->zxdg_decoration_manager_v1) { + zxdg_decoration_manager_v1_destroy(wl->zxdg_decoration_manager_v1); + } + if (wl->zwp_pointer_gestures_v1) { + zwp_pointer_gestures_v1_destroy(wl->zwp_pointer_gestures_v1); + } + if (wl->tablet_manager) { + zwp_tablet_manager_v2_destroy(wl->tablet_manager); + } + if (wl->presentation) { + wp_presentation_destroy(wl->presentation); + } + if (wl->zwp_linux_dmabuf_v1) { + zwp_linux_dmabuf_v1_destroy(wl->zwp_linux_dmabuf_v1); + } + if (wl->drm_syncobj_manager_v1) { + wp_linux_drm_syncobj_manager_v1_destroy(wl->drm_syncobj_manager_v1); + } + if (wl->legacy_drm != NULL) { + wl_drm_destroy(wl->legacy_drm); + } + if (wl->shm) { + if (wl_shm_get_version(wl->shm) >= WL_SHM_RELEASE_SINCE_VERSION) { + wl_shm_release(wl->shm); + } else { + wl_shm_destroy(wl->shm); + } + } + if (wl->zwp_relative_pointer_manager_v1) { + zwp_relative_pointer_manager_v1_destroy(wl->zwp_relative_pointer_manager_v1); + } + if (wl->subcompositor) { + wl_subcompositor_destroy(wl->subcompositor); + } + if (wl->viewporter) { + wp_viewporter_destroy(wl->viewporter); + } + free(wl->drm_render_name); + free(wl->activation_token); + xdg_wm_base_destroy(wl->xdg_wm_base); + wl_compositor_destroy(wl->compositor); + wl_registry_destroy(wl->registry); + wl_display_flush(wl->remote_display); + wl_event_queue_destroy(wl->busy_loop_queue); + if (wl->own_remote_display) { + wl_display_disconnect(wl->remote_display); + } + free(wl); +} + +static int backend_get_drm_fd(struct wlr_backend *backend) { + struct wlr_wl_backend *wl = get_wl_backend_from_backend(backend); + return wl->drm_fd; +} + +static const struct wlr_backend_impl backend_impl = { + .start = backend_start, + .destroy = backend_destroy, + .get_drm_fd = backend_get_drm_fd, +}; + +bool wlr_backend_is_wl(struct wlr_backend *b) { + return b->impl == &backend_impl; +} + +static void handle_event_loop_destroy(struct wl_listener *listener, void *data) { + struct wlr_wl_backend *wl = wl_container_of(listener, wl, event_loop_destroy); + backend_destroy(&wl->backend); +} + +struct wlr_backend *wlr_wl_backend_create(struct wl_event_loop *loop, + struct wl_display *remote_display) { + wlr_log(WLR_INFO, "Creating wayland backend"); + + struct wlr_wl_backend *wl = calloc(1, sizeof(*wl)); + if (!wl) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + + wlr_backend_init(&wl->backend, &backend_impl); + + wl->event_loop = loop; + wl_list_init(&wl->outputs); + wl_list_init(&wl->seats); + wl_list_init(&wl->buffers); + wl_list_init(&wl->drm_syncobj_timelines); + + if (remote_display != NULL) { + wl->remote_display = remote_display; + } else { + wl->remote_display = wl_display_connect(NULL); + if (!wl->remote_display) { + wlr_log_errno(WLR_ERROR, "Could not connect to remote display"); + goto error_wl; + } + wl->own_remote_display = true; + } + + wl->busy_loop_queue = wl_display_create_queue(wl->remote_display); + if (wl->busy_loop_queue == NULL) { + wlr_log_errno(WLR_ERROR, "Could not create a Wayland event queue"); + goto error_display; + } + + wl->registry = wl_display_get_registry(wl->remote_display); + if (!wl->registry) { + wlr_log_errno(WLR_ERROR, "Could not obtain reference to remote registry"); + goto error_queue; + } + wl_registry_add_listener(wl->registry, ®istry_listener, wl); + + wl_display_roundtrip(wl->remote_display); // get globals + + if (!wl->compositor) { + wlr_log(WLR_ERROR, + "Remote Wayland compositor does not support wl_compositor"); + goto error_registry; + } + if (!wl->xdg_wm_base) { + wlr_log(WLR_ERROR, + "Remote Wayland compositor does not support xdg-shell"); + goto error_registry; + } + + wl->backend.features.timeline = wl->drm_syncobj_manager_v1 != NULL; + + wl_display_roundtrip(wl->remote_display); // process initial event bursts + + struct zwp_linux_dmabuf_feedback_v1 *linux_dmabuf_feedback_v1 = NULL; + struct wlr_wl_linux_dmabuf_feedback_v1 feedback_data = { .backend = wl }; + if (wl->zwp_linux_dmabuf_v1 != NULL && + zwp_linux_dmabuf_v1_get_version(wl->zwp_linux_dmabuf_v1) >= + ZWP_LINUX_DMABUF_V1_GET_DEFAULT_FEEDBACK_SINCE_VERSION) { + linux_dmabuf_feedback_v1 = + zwp_linux_dmabuf_v1_get_default_feedback(wl->zwp_linux_dmabuf_v1); + if (linux_dmabuf_feedback_v1 == NULL) { + wlr_log(WLR_ERROR, "Allocation failed"); + goto error_registry; + } + zwp_linux_dmabuf_feedback_v1_add_listener(linux_dmabuf_feedback_v1, + &linux_dmabuf_feedback_v1_listener, &feedback_data); + + if (wl->legacy_drm != NULL) { + wl_drm_destroy(wl->legacy_drm); + wl->legacy_drm = NULL; + + free(wl->drm_render_name); + wl->drm_render_name = NULL; + } + + wl_display_roundtrip(wl->remote_display); // get linux-dmabuf feedback events + + if (feedback_data.format_table != NULL) { + munmap(feedback_data.format_table, feedback_data.format_table_size); + } + + zwp_linux_dmabuf_feedback_v1_destroy(linux_dmabuf_feedback_v1); + } + + if (wl->zwp_linux_dmabuf_v1) { + wl->backend.buffer_caps |= WLR_BUFFER_CAP_DMABUF; + } + if (wl->shm) { + wl->backend.buffer_caps |= WLR_BUFFER_CAP_SHM; + } + + int fd = wl_display_get_fd(wl->remote_display); + wl->remote_display_src = wl_event_loop_add_fd(loop, fd, WL_EVENT_READABLE, + dispatch_events, wl); + if (!wl->remote_display_src) { + wlr_log(WLR_ERROR, "Failed to create event source"); + goto error_registry; + } + wl_event_source_check(wl->remote_display_src); + + if (wl->drm_render_name != NULL) { + wlr_log(WLR_DEBUG, "Opening DRM render node %s", wl->drm_render_name); + wl->drm_fd = open(wl->drm_render_name, O_RDWR | O_NONBLOCK | O_CLOEXEC); + if (wl->drm_fd < 0) { + wlr_log_errno(WLR_ERROR, "Failed to open DRM render node %s", + wl->drm_render_name); + goto error_remote_display_src; + } + } else { + wl->drm_fd = -1; + } + + wl->event_loop_destroy.notify = handle_event_loop_destroy; + wl_event_loop_add_destroy_listener(loop, &wl->event_loop_destroy); + + const char *token = getenv("XDG_ACTIVATION_TOKEN"); + if (token != NULL) { + wl->activation_token = strdup(token); + unsetenv("XDG_ACTIVATION_TOKEN"); + } + + return &wl->backend; + +error_remote_display_src: + wl_event_source_remove(wl->remote_display_src); +error_registry: + free(wl->drm_render_name); + if (wl->compositor) { + wl_compositor_destroy(wl->compositor); + } + if (wl->xdg_wm_base) { + xdg_wm_base_destroy(wl->xdg_wm_base); + } + wl_registry_destroy(wl->registry); +error_queue: + wl_event_queue_destroy(wl->busy_loop_queue); +error_display: + if (wl->own_remote_display) { + wl_display_disconnect(wl->remote_display); + } +error_wl: + wlr_backend_finish(&wl->backend); + free(wl); + return NULL; +} + +struct wl_display *wlr_wl_backend_get_remote_display(struct wlr_backend *backend) { + struct wlr_wl_backend *wl = get_wl_backend_from_backend(backend); + return wl->remote_display; +} diff --git a/3rdparty/wlroots/backend/wayland/meson.build b/3rdparty/wlroots/backend/wayland/meson.build new file mode 100644 index 0000000000..b606a9bb9b --- /dev/null +++ b/3rdparty/wlroots/backend/wayland/meson.build @@ -0,0 +1,30 @@ +wayland_client = dependency('wayland-client', + kwargs: wayland_kwargs, +) +wlr_deps += wayland_client + +wlr_files += files( + 'backend.c', + 'output.c', + 'seat.c', + 'pointer.c', + 'tablet_v2.c', +) + +client_protos = [ + 'drm', + 'linux-dmabuf-v1', + 'linux-drm-syncobj-v1', + 'pointer-gestures-unstable-v1', + 'presentation-time', + 'relative-pointer-unstable-v1', + 'tablet-v2', + 'viewporter', + 'xdg-activation-v1', + 'xdg-decoration-unstable-v1', + 'xdg-shell', +] + +foreach proto : client_protos + wlr_files += protocols_client_header[proto] +endforeach diff --git a/3rdparty/wlroots/backend/wayland/output.c b/3rdparty/wlroots/backend/wayland/output.c new file mode 100644 index 0000000000..fb4d1f914b --- /dev/null +++ b/3rdparty/wlroots/backend/wayland/output.c @@ -0,0 +1,1274 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include "backend/wayland.h" +#include "render/pixel_format.h" +#include "types/wlr_output.h" + +#include "linux-dmabuf-v1-client-protocol.h" +#include "linux-drm-syncobj-v1-client-protocol.h" +#include "presentation-time-client-protocol.h" +#include "viewporter-client-protocol.h" +#include "xdg-activation-v1-client-protocol.h" +#include "xdg-decoration-unstable-v1-client-protocol.h" +#include "xdg-shell-client-protocol.h" + +static const uint32_t SUPPORTED_OUTPUT_STATE = + WLR_OUTPUT_STATE_BACKEND_OPTIONAL | + WLR_OUTPUT_STATE_BUFFER | + WLR_OUTPUT_STATE_ENABLED | + WLR_OUTPUT_STATE_MODE | + WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED | + WLR_OUTPUT_STATE_WAIT_TIMELINE | + WLR_OUTPUT_STATE_SIGNAL_TIMELINE; + +static size_t last_output_num = 0; + +static const char *surface_tag = "wlr_wl_output"; + +static struct wlr_wl_output *get_wl_output_from_output( + struct wlr_output *wlr_output) { + assert(wlr_output_is_wl(wlr_output)); + struct wlr_wl_output *output = wl_container_of(wlr_output, output, wlr_output); + return output; +} + +struct wlr_wl_output *get_wl_output_from_surface(struct wlr_wl_backend *wl, + struct wl_surface *surface) { + if (wl_proxy_get_tag((struct wl_proxy *)surface) != &surface_tag) { + return NULL; + } + struct wlr_wl_output *output = wl_surface_get_user_data(surface); + assert(output != NULL); + if (output->backend != wl) { + return NULL; + } + return output; +} + +static void surface_frame_callback(void *data, struct wl_callback *cb, + uint32_t time) { + struct wlr_wl_output *output = data; + + if (cb == NULL) { + return; + } + + assert(output->frame_callback == cb); + wl_callback_destroy(cb); + output->frame_callback = NULL; + + wlr_output_send_frame(&output->wlr_output); +} + +static const struct wl_callback_listener frame_listener = { + .done = surface_frame_callback +}; + +static void presentation_feedback_destroy( + struct wlr_wl_presentation_feedback *feedback) { + wl_list_remove(&feedback->link); + wp_presentation_feedback_destroy(feedback->feedback); + free(feedback); +} + +static void presentation_feedback_handle_sync_output(void *data, + struct wp_presentation_feedback *feedback, struct wl_output *output) { + // This space is intentionally left blank +} + +static void presentation_feedback_handle_presented(void *data, + struct wp_presentation_feedback *wp_feedback, uint32_t tv_sec_hi, + uint32_t tv_sec_lo, uint32_t tv_nsec, uint32_t refresh_ns, + uint32_t seq_hi, uint32_t seq_lo, uint32_t flags) { + struct wlr_wl_presentation_feedback *feedback = data; + + struct wlr_output_event_present event = { + .commit_seq = feedback->commit_seq, + .presented = true, + .when = { + .tv_sec = ((uint64_t)tv_sec_hi << 32) | tv_sec_lo, + .tv_nsec = tv_nsec, + }, + .seq = ((uint64_t)seq_hi << 32) | seq_lo, + .refresh = refresh_ns, + .flags = flags, + }; + wlr_output_send_present(&feedback->output->wlr_output, &event); + + presentation_feedback_destroy(feedback); +} + +static void presentation_feedback_handle_discarded(void *data, + struct wp_presentation_feedback *wp_feedback) { + struct wlr_wl_presentation_feedback *feedback = data; + + struct wlr_output_event_present event = { + .commit_seq = feedback->commit_seq, + .presented = false, + }; + wlr_output_send_present(&feedback->output->wlr_output, &event); + + presentation_feedback_destroy(feedback); +} + +static const struct wp_presentation_feedback_listener + presentation_feedback_listener = { + .sync_output = presentation_feedback_handle_sync_output, + .presented = presentation_feedback_handle_presented, + .discarded = presentation_feedback_handle_discarded, +}; + +static void buffer_remove_drm_syncobj_waiter(struct wlr_wl_buffer *buffer) { + wlr_drm_syncobj_timeline_waiter_finish(&buffer->drm_syncobj_waiter); + buffer->has_drm_syncobj_waiter = false; +} + +void destroy_wl_buffer(struct wlr_wl_buffer *buffer) { + if (buffer == NULL) { + return; + } + wl_list_remove(&buffer->buffer_destroy.link); + wl_list_remove(&buffer->link); + wl_buffer_destroy(buffer->wl_buffer); + if (buffer->has_drm_syncobj_waiter) { + buffer_remove_drm_syncobj_waiter(buffer); + } + if (!buffer->released) { + wlr_buffer_unlock(buffer->buffer); + } + wlr_drm_syncobj_timeline_unref(buffer->fallback_signal_timeline); + free(buffer); +} + +static void buffer_release(struct wlr_wl_buffer *buffer) { + if (buffer->released) { + return; + } + buffer->released = true; + wlr_buffer_unlock(buffer->buffer); // might free buffer +} + +static void buffer_handle_release(void *data, struct wl_buffer *wl_buffer) { + struct wlr_wl_buffer *buffer = data; + if (buffer->has_drm_syncobj_waiter) { + return; + } + buffer_release(buffer); +} + +static const struct wl_buffer_listener buffer_listener = { + .release = buffer_handle_release, +}; + +static void buffer_handle_drm_syncobj_ready(struct wlr_drm_syncobj_timeline_waiter *waiter) { + struct wlr_wl_buffer *buffer = wl_container_of(waiter, buffer, drm_syncobj_waiter); + buffer_remove_drm_syncobj_waiter(buffer); + buffer_release(buffer); +} + +static void buffer_handle_buffer_destroy(struct wl_listener *listener, + void *data) { + struct wlr_wl_buffer *buffer = + wl_container_of(listener, buffer, buffer_destroy); + destroy_wl_buffer(buffer); +} + +static bool test_buffer(struct wlr_wl_backend *wl, + struct wlr_buffer *wlr_buffer) { + struct wlr_dmabuf_attributes dmabuf; + struct wlr_shm_attributes shm; + if (wlr_buffer_get_dmabuf(wlr_buffer, &dmabuf)) { + return wlr_drm_format_set_has(&wl->linux_dmabuf_v1_formats, + dmabuf.format, dmabuf.modifier); + } else if (wlr_buffer_get_shm(wlr_buffer, &shm)) { + return wlr_drm_format_set_has(&wl->shm_formats, shm.format, + DRM_FORMAT_MOD_INVALID); + } else { + return false; + } +} + +struct dmabuf_listener_data { + struct wl_buffer *wl_buffer; + bool done; +}; + +static void dmabuf_handle_created(void *data_, struct zwp_linux_buffer_params_v1 *params, + struct wl_buffer *buffer) { + struct dmabuf_listener_data *data = data_; + data->wl_buffer = buffer; + data->done = true; + wlr_log(WLR_DEBUG, "DMA-BUF imported into parent Wayland compositor"); +} + +static void dmabuf_handle_failed(void *data_, struct zwp_linux_buffer_params_v1 *params) { + struct dmabuf_listener_data *data = data_; + data->done = true; + wlr_log(WLR_ERROR, "Failed to import DMA-BUF into parent Wayland compositor"); +} + +static const struct zwp_linux_buffer_params_v1_listener dmabuf_listener = { + .created = dmabuf_handle_created, + .failed = dmabuf_handle_failed, +}; + +static struct wl_buffer *import_dmabuf(struct wlr_wl_backend *wl, + struct wlr_dmabuf_attributes *dmabuf) { + uint32_t modifier_hi = dmabuf->modifier >> 32; + uint32_t modifier_lo = (uint32_t)dmabuf->modifier; + struct zwp_linux_buffer_params_v1 *params = + zwp_linux_dmabuf_v1_create_params(wl->zwp_linux_dmabuf_v1); + for (int i = 0; i < dmabuf->n_planes; i++) { + zwp_linux_buffer_params_v1_add(params, dmabuf->fd[i], i, + dmabuf->offset[i], dmabuf->stride[i], modifier_hi, modifier_lo); + } + + struct dmabuf_listener_data data = {0}; + zwp_linux_buffer_params_v1_add_listener(params, &dmabuf_listener, &data); + zwp_linux_buffer_params_v1_create(params, dmabuf->width, dmabuf->height, dmabuf->format, 0); + + struct wl_event_queue *display_queue = + wl_proxy_get_queue((struct wl_proxy *)wl->remote_display); + wl_proxy_set_queue((struct wl_proxy *)params, wl->busy_loop_queue); + + while (!data.done) { + if (wl_display_dispatch_queue(wl->remote_display, wl->busy_loop_queue) < 0) { + wlr_log(WLR_ERROR, "wl_display_dispatch_queue() failed"); + break; + } + } + + struct wl_buffer *buffer = data.wl_buffer; + if (buffer != NULL) { + wl_proxy_set_queue((struct wl_proxy *)buffer, display_queue); + } + + zwp_linux_buffer_params_v1_destroy(params); + return buffer; +} + +static struct wl_buffer *import_shm(struct wlr_wl_backend *wl, + struct wlr_shm_attributes *shm) { + enum wl_shm_format wl_shm_format = convert_drm_format_to_wl_shm(shm->format); + uint32_t size = shm->stride * shm->height; + struct wl_shm_pool *pool = wl_shm_create_pool(wl->shm, shm->fd, shm->offset + size); + if (pool == NULL) { + return NULL; + } + struct wl_buffer *wl_buffer = wl_shm_pool_create_buffer(pool, shm->offset, + shm->width, shm->height, shm->stride, wl_shm_format); + wl_shm_pool_destroy(pool); + return wl_buffer; +} + +static struct wlr_wl_buffer *create_wl_buffer(struct wlr_wl_backend *wl, + struct wlr_buffer *wlr_buffer) { + if (!test_buffer(wl, wlr_buffer)) { + return NULL; + } + + struct wlr_dmabuf_attributes dmabuf; + struct wlr_shm_attributes shm; + struct wl_buffer *wl_buffer; + if (wlr_buffer_get_dmabuf(wlr_buffer, &dmabuf)) { + wl_buffer = import_dmabuf(wl, &dmabuf); + } else if (wlr_buffer_get_shm(wlr_buffer, &shm)) { + wl_buffer = import_shm(wl, &shm); + } else { + return NULL; + } + if (wl_buffer == NULL) { + return NULL; + } + + struct wlr_wl_buffer *buffer = calloc(1, sizeof(*buffer)); + if (buffer == NULL) { + wl_buffer_destroy(wl_buffer); + return NULL; + } + buffer->wl_buffer = wl_buffer; + buffer->buffer = wlr_buffer_lock(wlr_buffer); + wl_list_insert(&wl->buffers, &buffer->link); + + wl_buffer_add_listener(wl_buffer, &buffer_listener, buffer); + + buffer->buffer_destroy.notify = buffer_handle_buffer_destroy; + wl_signal_add(&wlr_buffer->events.destroy, &buffer->buffer_destroy); + + return buffer; +} + +static struct wlr_wl_buffer *get_or_create_wl_buffer(struct wlr_wl_backend *wl, + struct wlr_buffer *wlr_buffer) { + struct wlr_wl_buffer *buffer; + wl_list_for_each(buffer, &wl->buffers, link) { + // We can only re-use a wlr_wl_buffer if the parent compositor has + // released it, because wl_buffer.release is per-wl_buffer, not per + // wl_surface.commit. + if (buffer->buffer == wlr_buffer && buffer->released) { + buffer->released = false; + wlr_buffer_lock(buffer->buffer); + return buffer; + } + } + + return create_wl_buffer(wl, wlr_buffer); +} + +void destroy_wl_drm_syncobj_timeline(struct wlr_wl_drm_syncobj_timeline *timeline) { + wp_linux_drm_syncobj_timeline_v1_destroy(timeline->wl); + wlr_addon_finish(&timeline->addon); + wl_list_remove(&timeline->link); + free(timeline); +} + +static void drm_syncobj_timeline_addon_destroy(struct wlr_addon *addon) { + struct wlr_wl_drm_syncobj_timeline *timeline = wl_container_of(addon, timeline, addon); + destroy_wl_drm_syncobj_timeline(timeline); +} + +static const struct wlr_addon_interface drm_syncobj_timeline_addon_impl = { + .name = "wlr_wl_drm_syncobj_timeline", + .destroy = drm_syncobj_timeline_addon_destroy, +}; + +static struct wlr_wl_drm_syncobj_timeline *get_or_create_drm_syncobj_timeline( + struct wlr_wl_backend *wl, struct wlr_drm_syncobj_timeline *wlr_timeline) { + struct wlr_addon *addon = + wlr_addon_find(&wlr_timeline->addons, wl, &drm_syncobj_timeline_addon_impl); + if (addon != NULL) { + struct wlr_wl_drm_syncobj_timeline *timeline = wl_container_of(addon, timeline, addon); + return timeline; + } + + struct wlr_wl_drm_syncobj_timeline *timeline = calloc(1, sizeof(*timeline)); + if (timeline == NULL) { + return NULL; + } + + timeline->base = wlr_timeline; + + int fd = wlr_drm_syncobj_timeline_export(wlr_timeline); + if (fd < 0) { + free(timeline); + return NULL; + } + + timeline->wl = wp_linux_drm_syncobj_manager_v1_import_timeline(wl->drm_syncobj_manager_v1, fd); + close(fd); + if (timeline->wl == NULL) { + free(timeline); + return NULL; + } + + wlr_addon_init(&timeline->addon, &wlr_timeline->addons, wl, &drm_syncobj_timeline_addon_impl); + wl_list_insert(&wl->drm_syncobj_timelines, &timeline->link); + + return timeline; +} + +static bool update_title(struct wlr_wl_output *output, const char *title) { + struct wlr_output *wlr_output = &output->wlr_output; + + char default_title[64]; + if (title == NULL) { + snprintf(default_title, sizeof(default_title), "wlroots - %s", wlr_output->name); + title = default_title; + } + + char *wl_title = strdup(title); + if (wl_title == NULL) { + return false; + } + + free(output->title); + output->title = wl_title; + return true; +} + +static bool update_app_id(struct wlr_wl_output *output, const char *app_id) { + if (app_id == NULL) { + app_id = "wlroots"; + } + + char *wl_app_id = strdup(app_id); + if (wl_app_id == NULL) { + return false; + } + + free(output->app_id); + output->app_id = wl_app_id; + return true; +} + +static bool output_test(struct wlr_output *wlr_output, + const struct wlr_output_state *state) { + struct wlr_wl_output *output = + get_wl_output_from_output(wlr_output); + + if (state->committed & WLR_OUTPUT_STATE_BUFFER) { + // If the size doesn't match, reject buffer (scaling is not currently + // supported but could be implemented with viewporter) + int pending_width, pending_height; + output_pending_resolution(wlr_output, state, + &pending_width, &pending_height); + if (state->buffer->width != pending_width || + state->buffer->height != pending_height) { + wlr_log(WLR_DEBUG, "Primary buffer size mismatch"); + return false; + } + // Source crop is also not currently supported + struct wlr_fbox src_box; + output_state_get_buffer_src_box(state, &src_box); + if (src_box.x != 0.0 || src_box.y != 0.0 || + src_box.width != (double)state->buffer->width || + src_box.height != (double)state->buffer->height) { + wlr_log(WLR_DEBUG, "Source crop not supported in wayland output"); + return false; + } + } + + uint32_t unsupported = state->committed & ~SUPPORTED_OUTPUT_STATE; + if (unsupported != 0) { + wlr_log(WLR_DEBUG, "Unsupported output state fields: 0x%"PRIx32, + unsupported); + return false; + } + + // Adaptive sync is effectively always enabled when using the Wayland + // backend. This is not something we have control over, so we set the state + // to enabled on creating the output and never allow changing it. + assert(wlr_output->adaptive_sync_status == WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED); + if (state->committed & WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED) { + if (!state->adaptive_sync_enabled) { + wlr_log(WLR_DEBUG, "Disabling adaptive sync is not supported"); + return false; + } + } + + if (state->committed & WLR_OUTPUT_STATE_MODE) { + assert(state->mode_type == WLR_OUTPUT_STATE_MODE_CUSTOM); + + if (state->custom_mode.refresh != 0) { + wlr_log(WLR_DEBUG, "Refresh rates are not supported"); + return false; + } + } + + if ((state->committed & WLR_OUTPUT_STATE_BUFFER) && + !test_buffer(output->backend, state->buffer)) { + wlr_log(WLR_DEBUG, "Unsupported buffer format"); + return false; + } + + if ((state->committed & WLR_OUTPUT_STATE_SIGNAL_TIMELINE) && + !(state->committed & WLR_OUTPUT_STATE_WAIT_TIMELINE)) { + wlr_log(WLR_DEBUG, "Signal timeline requires a wait timeline"); + return false; + } + + if ((state->committed & WLR_OUTPUT_STATE_WAIT_TIMELINE) || + (state->committed & WLR_OUTPUT_STATE_SIGNAL_TIMELINE)) { + struct wlr_dmabuf_attributes dmabuf; + if (!wlr_buffer_get_dmabuf(state->buffer, &dmabuf)) { + wlr_log(WLR_DEBUG, "Wait/signal timelines require DMA-BUFs"); + return false; + } + } + + if (state->committed & WLR_OUTPUT_STATE_LAYERS) { + // If we can't use a sub-surface for a layer, then we can't use a + // sub-surface for any layer underneath + bool supported = output->backend->subcompositor != NULL; + for (ssize_t i = state->layers_len - 1; i >= 0; i--) { + struct wlr_output_layer_state *layer_state = &state->layers[i]; + if (layer_state->buffer != NULL) { + int x = layer_state->dst_box.x; + int y = layer_state->dst_box.y; + int width = layer_state->dst_box.width; + int height = layer_state->dst_box.height; + bool needs_viewport = width != layer_state->buffer->width || + height != layer_state->buffer->height; + if (!wlr_fbox_empty(&layer_state->src_box)) { + needs_viewport = needs_viewport || + layer_state->src_box.x != 0 || + layer_state->src_box.y != 0 || + layer_state->src_box.width != width || + layer_state->src_box.height != height; + } + if (x < 0 || y < 0 || + x + width > wlr_output->width || + y + height > wlr_output->height || + (output->backend->viewporter == NULL && needs_viewport)) { + supported = false; + } + supported = supported && + test_buffer(output->backend, layer_state->buffer); + } + layer_state->accepted = supported; + } + } + + return true; +} + +static void output_layer_handle_addon_destroy(struct wlr_addon *addon) { + struct wlr_wl_output_layer *layer = wl_container_of(addon, layer, addon); + + wlr_addon_finish(&layer->addon); + if (layer->viewport != NULL) { + wp_viewport_destroy(layer->viewport); + } + wl_subsurface_destroy(layer->subsurface); + wl_surface_destroy(layer->surface); + free(layer); +} + +static const struct wlr_addon_interface output_layer_addon_impl = { + .name = "wlr_wl_output_layer", + .destroy = output_layer_handle_addon_destroy, +}; + +static struct wlr_wl_output_layer *get_or_create_output_layer( + struct wlr_wl_output *output, struct wlr_output_layer *wlr_layer) { + assert(output->backend->subcompositor != NULL); + + struct wlr_wl_output_layer *layer; + struct wlr_addon *addon = wlr_addon_find(&wlr_layer->addons, output, + &output_layer_addon_impl); + if (addon != NULL) { + layer = wl_container_of(addon, layer, addon); + return layer; + } + + layer = calloc(1, sizeof(*layer)); + if (layer == NULL) { + return NULL; + } + + wlr_addon_init(&layer->addon, &wlr_layer->addons, output, + &output_layer_addon_impl); + + layer->surface = wl_compositor_create_surface(output->backend->compositor); + layer->subsurface = wl_subcompositor_get_subsurface( + output->backend->subcompositor, layer->surface, output->surface); + + // Set an empty input region so that input events are handled by the main + // surface + struct wl_region *region = wl_compositor_create_region(output->backend->compositor); + wl_surface_set_input_region(layer->surface, region); + wl_region_destroy(region); + + if (output->backend->viewporter != NULL) { + layer->viewport = wp_viewporter_get_viewport(output->backend->viewporter, layer->surface); + } + + return layer; +} + +static bool has_layers_order_changed(struct wlr_wl_output *output, + struct wlr_output_layer_state *layers, size_t layers_len) { + // output_basic_check() ensures that layers_len equals the number of + // registered output layers + size_t i = 0; + struct wlr_output_layer *layer; + wl_list_for_each(layer, &output->wlr_output.layers, link) { + assert(i < layers_len); + const struct wlr_output_layer_state *layer_state = &layers[i]; + if (layer_state->layer != layer) { + return true; + } + i++; + } + assert(i == layers_len); + return false; +} + +static void output_layer_unmap(struct wlr_wl_output_layer *layer) { + if (!layer->mapped) { + return; + } + + wl_surface_attach(layer->surface, NULL, 0, 0); + wl_surface_commit(layer->surface); + layer->mapped = false; +} + +static void damage_surface(struct wl_surface *surface, + const pixman_region32_t *damage) { + if (damage == NULL) { + wl_surface_damage_buffer(surface, + 0, 0, INT32_MAX, INT32_MAX); + return; + } + + int rects_len; + const pixman_box32_t *rects = pixman_region32_rectangles(damage, &rects_len); + for (int i = 0; i < rects_len; i++) { + const pixman_box32_t *r = &rects[i]; + wl_surface_damage_buffer(surface, r->x1, r->y1, + r->x2 - r->x1, r->y2 - r->y1); + } +} + +static bool output_layer_commit(struct wlr_wl_output *output, + struct wlr_wl_output_layer *layer, + const struct wlr_output_layer_state *state) { + if (state->layer->dst_box.x != state->dst_box.x || + state->layer->dst_box.y != state->dst_box.y) { + wl_subsurface_set_position(layer->subsurface, state->dst_box.x, state->dst_box.y); + } + + if (state->buffer == NULL) { + output_layer_unmap(layer); + return true; + } + + struct wlr_wl_buffer *buffer = + get_or_create_wl_buffer(output->backend, state->buffer); + if (buffer == NULL) { + return false; + } + + if (layer->viewport != NULL && + (state->layer->dst_box.width != state->dst_box.width || + state->layer->dst_box.height != state->dst_box.height)) { + wp_viewport_set_destination(layer->viewport, state->dst_box.width, state->dst_box.height); + } + if (layer->viewport != NULL && !wlr_fbox_equal(&state->layer->src_box, &state->src_box)) { + struct wlr_fbox src_box = state->src_box; + if (wlr_fbox_empty(&src_box)) { + // -1 resets the box + src_box = (struct wlr_fbox){ + .x = -1, + .y = -1, + .width = -1, + .height = -1, + }; + } + wp_viewport_set_source(layer->viewport, + wl_fixed_from_double(src_box.x), + wl_fixed_from_double(src_box.y), + wl_fixed_from_double(src_box.width), + wl_fixed_from_double(src_box.height)); + } + + wl_surface_attach(layer->surface, buffer->wl_buffer, 0, 0); + damage_surface(layer->surface, state->damage); + wl_surface_commit(layer->surface); + layer->mapped = true; + return true; +} + +static bool commit_layers(struct wlr_wl_output *output, + struct wlr_output_layer_state *layers, size_t layers_len) { + if (output->backend->subcompositor == NULL) { + return true; + } + + bool reordered = has_layers_order_changed(output, layers, layers_len); + + struct wlr_wl_output_layer *prev_layer = NULL; + for (size_t i = 0; i < layers_len; i++) { + struct wlr_wl_output_layer *layer = + get_or_create_output_layer(output, layers[i].layer); + if (layer == NULL) { + return false; + } + + if (!layers[i].accepted) { + output_layer_unmap(layer); + continue; + } + + if (prev_layer != NULL && reordered) { + wl_subsurface_place_above(layer->subsurface, + prev_layer->surface); + } + + if (!output_layer_commit(output, layer, &layers[i])) { + return false; + } + + prev_layer = layer; + } + + return true; +} + +static void unmap_callback_handle_done(void *data, struct wl_callback *callback, + uint32_t cb_data) { + struct wlr_wl_output *output = data; + output->unmap_callback = NULL; + wl_callback_destroy(callback); +} + +static const struct wl_callback_listener unmap_callback_listener = { + .done = unmap_callback_handle_done, +}; + +static bool output_commit(struct wlr_output *wlr_output, const struct wlr_output_state *state) { + struct wlr_wl_output *output = get_wl_output_from_output(wlr_output); + + if (!output_test(wlr_output, state)) { + return false; + } + + struct wlr_wl_backend *wl = output->backend; + + bool pending_enabled = output_pending_enabled(wlr_output, state); + + if (wlr_output->enabled && !pending_enabled) { + if (output->own_surface) { + output->unmap_callback = wl_display_sync(output->backend->remote_display); + if (output->unmap_callback == NULL) { + return false; + } + wl_callback_add_listener(output->unmap_callback, &unmap_callback_listener, output); + } + + wl_surface_attach(output->surface, NULL, 0, 0); + wl_surface_commit(output->surface); + + output->initialized = false; + output->configured = false; + output->has_configure_serial = false; + output->requested_width = output->requested_height = 0; + } else if (output->own_surface && pending_enabled && !output->initialized) { + xdg_toplevel_set_title(output->xdg_toplevel, output->title); + xdg_toplevel_set_app_id(output->xdg_toplevel, output->app_id); + wl_surface_commit(output->surface); + output->initialized = true; + + struct wl_event_queue *display_queue = + wl_proxy_get_queue((struct wl_proxy *)wl->remote_display); + wl_proxy_set_queue((struct wl_proxy *)output->xdg_surface, wl->busy_loop_queue); + wl_proxy_set_queue((struct wl_proxy *)output->xdg_toplevel, wl->busy_loop_queue); + + wl_display_flush(wl->remote_display); + while (!output->configured) { + if (wl_display_dispatch_queue(wl->remote_display, wl->busy_loop_queue) == -1) { + wlr_log(WLR_ERROR, "wl_display_dispatch_queue() failed"); + break; + } + } + + wl_proxy_set_queue((struct wl_proxy *)output->xdg_surface, display_queue); + wl_proxy_set_queue((struct wl_proxy *)output->xdg_toplevel, display_queue); + + if (!output->configured) { + return false; + } + } + + struct wlr_wl_buffer *buffer = NULL; + if (state->committed & WLR_OUTPUT_STATE_BUFFER) { + const pixman_region32_t *damage = NULL; + if (state->committed & WLR_OUTPUT_STATE_DAMAGE) { + damage = &state->damage; + } + + struct wlr_buffer *wlr_buffer = state->buffer; + buffer = get_or_create_wl_buffer(wl, wlr_buffer); + if (buffer == NULL) { + return false; + } + + wl_surface_attach(output->surface, buffer->wl_buffer, 0, 0); + damage_surface(output->surface, damage); + } + + if (state->committed & WLR_OUTPUT_STATE_WAIT_TIMELINE) { + struct wlr_wl_drm_syncobj_timeline *wait_timeline = + get_or_create_drm_syncobj_timeline(wl, state->wait_timeline); + + struct wlr_wl_drm_syncobj_timeline *signal_timeline; + uint64_t signal_point; + if (state->committed & WLR_OUTPUT_STATE_SIGNAL_TIMELINE) { + signal_timeline = get_or_create_drm_syncobj_timeline(wl, state->signal_timeline); + signal_point = state->signal_point; + } else { + if (buffer->fallback_signal_timeline == NULL) { + buffer->fallback_signal_timeline = + wlr_drm_syncobj_timeline_create(wl->drm_fd); + if (buffer->fallback_signal_timeline == NULL) { + return false; + } + } + signal_timeline = + get_or_create_drm_syncobj_timeline(wl, buffer->fallback_signal_timeline); + signal_point = ++buffer->fallback_signal_point; + } + + if (wait_timeline == NULL || signal_timeline == NULL) { + return false; + } + + if (output->drm_syncobj_surface_v1 == NULL) { + output->drm_syncobj_surface_v1 = wp_linux_drm_syncobj_manager_v1_get_surface( + wl->drm_syncobj_manager_v1, output->surface); + if (output->drm_syncobj_surface_v1 == NULL) { + return false; + } + } + + uint32_t wait_point_hi = state->wait_point >> 32; + uint32_t wait_point_lo = state->wait_point & UINT32_MAX; + uint32_t signal_point_hi = signal_point >> 32; + uint32_t signal_point_lo = signal_point & UINT32_MAX; + + wp_linux_drm_syncobj_surface_v1_set_acquire_point(output->drm_syncobj_surface_v1, + wait_timeline->wl, wait_point_hi, wait_point_lo); + wp_linux_drm_syncobj_surface_v1_set_release_point(output->drm_syncobj_surface_v1, + signal_timeline->wl, signal_point_hi, signal_point_lo); + + if (!wlr_drm_syncobj_timeline_waiter_init(&buffer->drm_syncobj_waiter, + signal_timeline->base, signal_point, 0, wl->event_loop, + buffer_handle_drm_syncobj_ready)) { + return false; + } + buffer->has_drm_syncobj_waiter = true; + } else { + if (output->drm_syncobj_surface_v1 != NULL) { + wp_linux_drm_syncobj_surface_v1_destroy(output->drm_syncobj_surface_v1); + output->drm_syncobj_surface_v1 = NULL; + } + } + + if ((state->committed & WLR_OUTPUT_STATE_LAYERS) && + !commit_layers(output, state->layers, state->layers_len)) { + return false; + } + + if (pending_enabled) { + if (output->frame_callback != NULL) { + wl_callback_destroy(output->frame_callback); + } + output->frame_callback = wl_surface_frame(output->surface); + wl_callback_add_listener(output->frame_callback, &frame_listener, output); + + struct wp_presentation_feedback *wp_feedback = NULL; + if (wl->presentation != NULL) { + wp_feedback = wp_presentation_feedback(wl->presentation, output->surface); + } + + if (output->has_configure_serial) { + xdg_surface_ack_configure(output->xdg_surface, output->configure_serial); + output->has_configure_serial = false; + } + + wl_surface_commit(output->surface); + + if (wp_feedback != NULL) { + struct wlr_wl_presentation_feedback *feedback = + calloc(1, sizeof(*feedback)); + if (feedback == NULL) { + wp_presentation_feedback_destroy(wp_feedback); + return false; + } + feedback->output = output; + feedback->feedback = wp_feedback; + feedback->commit_seq = output->wlr_output.commit_seq + 1; + wl_list_insert(&output->presentation_feedbacks, &feedback->link); + + wp_presentation_feedback_add_listener(wp_feedback, + &presentation_feedback_listener, feedback); + } else { + struct wlr_output_event_present present_event = { + .commit_seq = wlr_output->commit_seq + 1, + .presented = true, + }; + output_defer_present(wlr_output, present_event); + } + } + + wl_display_flush(wl->remote_display); + + return true; +} + +static bool output_set_cursor(struct wlr_output *wlr_output, + struct wlr_buffer *wlr_buffer, int hotspot_x, int hotspot_y) { + struct wlr_wl_output *output = get_wl_output_from_output(wlr_output); + struct wlr_wl_backend *backend = output->backend; + + output->cursor.hotspot_x = hotspot_x; + output->cursor.hotspot_y = hotspot_y; + + if (output->cursor.surface == NULL) { + output->cursor.surface = + wl_compositor_create_surface(backend->compositor); + } + struct wl_surface *surface = output->cursor.surface; + + if (wlr_buffer != NULL) { + struct wlr_wl_buffer *buffer = + get_or_create_wl_buffer(output->backend, wlr_buffer); + if (buffer == NULL) { + return false; + } + + wl_surface_attach(surface, buffer->wl_buffer, 0, 0); + wl_surface_damage_buffer(surface, 0, 0, INT32_MAX, INT32_MAX); + wl_surface_commit(surface); + } else { + wl_surface_attach(surface, NULL, 0, 0); + wl_surface_commit(surface); + } + + update_wl_output_cursor(output); + wl_display_flush(backend->remote_display); + return true; +} + +static const struct wlr_drm_format_set *output_get_formats( + struct wlr_output *wlr_output, uint32_t buffer_caps) { + struct wlr_wl_output *output = get_wl_output_from_output(wlr_output); + if (buffer_caps & WLR_BUFFER_CAP_DMABUF) { + return &output->backend->linux_dmabuf_v1_formats; + } else if (buffer_caps & WLR_BUFFER_CAP_SHM) { + return &output->backend->shm_formats; + } + return NULL; +} + +static void output_destroy(struct wlr_output *wlr_output) { + struct wlr_wl_output *output = get_wl_output_from_output(wlr_output); + if (output == NULL) { + return; + } + + wlr_output_finish(wlr_output); + + wl_list_remove(&output->link); + + if (output->cursor.surface) { + wl_surface_destroy(output->cursor.surface); + } + + if (output->frame_callback) { + wl_callback_destroy(output->frame_callback); + } + + struct wlr_wl_presentation_feedback *feedback, *feedback_tmp; + wl_list_for_each_safe(feedback, feedback_tmp, + &output->presentation_feedbacks, link) { + presentation_feedback_destroy(feedback); + } + + if (output->unmap_callback) { + wl_callback_destroy(output->unmap_callback); + } + + if (output->drm_syncobj_surface_v1) { + wp_linux_drm_syncobj_surface_v1_destroy(output->drm_syncobj_surface_v1); + } + if (output->zxdg_toplevel_decoration_v1) { + zxdg_toplevel_decoration_v1_destroy(output->zxdg_toplevel_decoration_v1); + } + if (output->xdg_toplevel) { + xdg_toplevel_destroy(output->xdg_toplevel); + } + if (output->xdg_surface) { + xdg_surface_destroy(output->xdg_surface); + } + if (output->own_surface) { + wl_surface_destroy(output->surface); + } + wl_display_flush(output->backend->remote_display); + + free(output->title); + free(output->app_id); + + free(output); +} + +void update_wl_output_cursor(struct wlr_wl_output *output) { + struct wlr_wl_pointer *pointer = output->cursor.pointer; + if (pointer) { + assert(pointer->output == output); + assert(output->enter_serial); + + struct wlr_wl_seat *seat = pointer->seat; + wl_pointer_set_cursor(seat->wl_pointer, output->enter_serial, + output->cursor.surface, output->cursor.hotspot_x, + output->cursor.hotspot_y); + } +} + +static bool output_move_cursor(struct wlr_output *_output, int x, int y) { + // TODO: only return true if x == current x and y == current y + return true; +} + +static const struct wlr_output_impl output_impl = { + .destroy = output_destroy, + .test = output_test, + .commit = output_commit, + .set_cursor = output_set_cursor, + .move_cursor = output_move_cursor, + .get_cursor_formats = output_get_formats, + .get_primary_formats = output_get_formats, +}; + +bool wlr_output_is_wl(struct wlr_output *wlr_output) { + return wlr_output->impl == &output_impl; +} + +static void xdg_surface_handle_configure(void *data, + struct xdg_surface *xdg_surface, uint32_t serial) { + struct wlr_wl_output *output = data; + assert(output && output->xdg_surface == xdg_surface); + + int32_t req_width = output->wlr_output.width; + int32_t req_height = output->wlr_output.height; + if (output->requested_width > 0) { + req_width = output->requested_width; + output->requested_width = 0; + } + if (output->requested_height > 0) { + req_height = output->requested_height; + output->requested_height = 0; + } + + if (output->unmap_callback != NULL) { + return; + } + + output->configured = true; + output->has_configure_serial = true; + output->configure_serial = serial; + + if (!output->wlr_output.enabled) { + // We're waiting for a configure event after an initial commit to enable + // the output. Do not notify the compositor about the requested state. + return; + } + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_custom_mode(&state, req_width, req_height, 0); + wlr_output_send_request_state(&output->wlr_output, &state); + wlr_output_state_finish(&state); +} + +static const struct xdg_surface_listener xdg_surface_listener = { + .configure = xdg_surface_handle_configure, +}; + +static void xdg_toplevel_handle_configure(void *data, + struct xdg_toplevel *xdg_toplevel, + int32_t width, int32_t height, struct wl_array *states) { + struct wlr_wl_output *output = data; + assert(output && output->xdg_toplevel == xdg_toplevel); + + if (width > 0) { + output->requested_width = width; + } + if (height > 0) { + output->requested_height = height; + } +} + +static void xdg_toplevel_handle_close(void *data, + struct xdg_toplevel *xdg_toplevel) { + struct wlr_wl_output *output = data; + assert(output && output->xdg_toplevel == xdg_toplevel); + + wlr_output_destroy(&output->wlr_output); +} + +static const struct xdg_toplevel_listener xdg_toplevel_listener = { + .configure = xdg_toplevel_handle_configure, + .close = xdg_toplevel_handle_close, +}; + +static struct wlr_wl_output *output_create(struct wlr_wl_backend *backend, + struct wl_surface *surface) { + struct wlr_wl_output *output = calloc(1, sizeof(*output)); + if (output == NULL) { + wlr_log(WLR_ERROR, "Failed to allocate wlr_wl_output"); + return NULL; + } + struct wlr_output *wlr_output = &output->wlr_output; + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_custom_mode(&state, 1280, 720, 0); + + wlr_output_init(wlr_output, &backend->backend, &output_impl, + backend->event_loop, &state); + wlr_output_state_finish(&state); + + wlr_output->adaptive_sync_status = WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED; + + size_t output_num = ++last_output_num; + + char name[64]; + snprintf(name, sizeof(name), "WL-%zu", output_num); + wlr_output_set_name(wlr_output, name); + + char description[128]; + snprintf(description, sizeof(description), "Wayland output %zu", output_num); + wlr_output_set_description(wlr_output, description); + + output->surface = surface; + output->backend = backend; + wl_list_init(&output->presentation_feedbacks); + + wl_proxy_set_tag((struct wl_proxy *)output->surface, &surface_tag); + wl_surface_set_user_data(output->surface, output); + + wl_list_insert(&backend->outputs, &output->link); + + return output; +} + +static void output_start(struct wlr_wl_output *output) { + struct wlr_output *wlr_output = &output->wlr_output; + struct wlr_wl_backend *backend = output->backend; + + wl_signal_emit_mutable(&backend->backend.events.new_output, wlr_output); + + struct wlr_wl_seat *seat; + wl_list_for_each(seat, &backend->seats, link) { + if (seat->wl_pointer) { + create_pointer(seat, output); + } + } +} + +struct wlr_output *wlr_wl_output_create(struct wlr_backend *wlr_backend) { + struct wlr_wl_backend *backend = get_wl_backend_from_backend(wlr_backend); + if (!backend->started) { + ++backend->requested_outputs; + return NULL; + } + + struct wl_surface *surface = wl_compositor_create_surface(backend->compositor); + if (surface == NULL) { + wlr_log(WLR_ERROR, "Could not create output surface"); + return NULL; + } + + struct wlr_wl_output *output = output_create(backend, surface); + if (output == NULL) { + wl_surface_destroy(surface); + return NULL; + } + + output->own_surface = true; + + output->xdg_surface = + xdg_wm_base_get_xdg_surface(backend->xdg_wm_base, output->surface); + if (!output->xdg_surface) { + wlr_log_errno(WLR_ERROR, "Could not get xdg surface"); + goto error; + } + + output->xdg_toplevel = + xdg_surface_get_toplevel(output->xdg_surface); + if (!output->xdg_toplevel) { + wlr_log_errno(WLR_ERROR, "Could not get xdg toplevel"); + goto error; + } + + if (backend->zxdg_decoration_manager_v1) { + output->zxdg_toplevel_decoration_v1 = + zxdg_decoration_manager_v1_get_toplevel_decoration( + backend->zxdg_decoration_manager_v1, output->xdg_toplevel); + if (!output->zxdg_toplevel_decoration_v1) { + wlr_log_errno(WLR_ERROR, "Could not get xdg toplevel decoration"); + goto error; + } + zxdg_toplevel_decoration_v1_set_mode(output->zxdg_toplevel_decoration_v1, + ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE); + } + + if (!update_title(output, NULL)) { + wlr_log_errno(WLR_ERROR, "Could not allocate xdg toplevel title"); + goto error; + } + if (!update_app_id(output, NULL)) { + wlr_log_errno(WLR_ERROR, "Could not allocate xdg toplevel app_id"); + goto error; + } + + xdg_surface_add_listener(output->xdg_surface, + &xdg_surface_listener, output); + xdg_toplevel_add_listener(output->xdg_toplevel, + &xdg_toplevel_listener, output); + + wl_display_flush(backend->remote_display); + + output_start(output); + + // TODO: let the compositor do this bit + if (backend->activation_v1 && backend->activation_token) { + xdg_activation_v1_activate(backend->activation_v1, + backend->activation_token, output->surface); + } + + return &output->wlr_output; + +error: + wlr_output_destroy(&output->wlr_output); + return NULL; +} + +struct wlr_output *wlr_wl_output_create_from_surface(struct wlr_backend *wlr_backend, + struct wl_surface *surface) { + struct wlr_wl_backend *backend = get_wl_backend_from_backend(wlr_backend); + assert(backend->started); + + struct wlr_wl_output *output = output_create(backend, surface); + if (output == NULL) { + wl_surface_destroy(surface); + return NULL; + } + + output_start(output); + + return &output->wlr_output; +} + +void wlr_wl_output_set_title(struct wlr_output *output, const char *title) { + struct wlr_wl_output *wl_output = get_wl_output_from_output(output); + assert(wl_output->xdg_toplevel != NULL); + + if (update_title(wl_output, title) && wl_output->initialized) { + xdg_toplevel_set_title(wl_output->xdg_toplevel, wl_output->title); + wl_display_flush(wl_output->backend->remote_display); + } +} + +void wlr_wl_output_set_app_id(struct wlr_output *output, const char *app_id) { + struct wlr_wl_output *wl_output = get_wl_output_from_output(output); + assert(wl_output->xdg_toplevel != NULL); + + if (update_app_id(wl_output, app_id) && wl_output->initialized) { + xdg_toplevel_set_app_id(wl_output->xdg_toplevel, wl_output->app_id); + wl_display_flush(wl_output->backend->remote_display); + } +} + +struct wl_surface *wlr_wl_output_get_surface(struct wlr_output *output) { + struct wlr_wl_output *wl_output = get_wl_output_from_output(output); + return wl_output->surface; +} diff --git a/3rdparty/wlroots/backend/wayland/pointer.c b/3rdparty/wlroots/backend/wayland/pointer.c new file mode 100644 index 0000000000..b61e32cd07 --- /dev/null +++ b/3rdparty/wlroots/backend/wayland/pointer.c @@ -0,0 +1,556 @@ +#include +#include +#include +#include +#include + +#include "backend/wayland.h" + +#include "pointer-gestures-unstable-v1-client-protocol.h" +#include "relative-pointer-unstable-v1-client-protocol.h" + +static struct wlr_wl_pointer *output_get_pointer(struct wlr_wl_output *output, + const struct wl_pointer *wl_pointer) { + struct wlr_wl_seat *seat; + wl_list_for_each(seat, &output->backend->seats, link) { + if (seat->wl_pointer != wl_pointer) { + continue; + } + + struct wlr_wl_pointer *pointer; + wl_list_for_each(pointer, &seat->pointers, link) { + if (pointer->output == output) { + return pointer; + } + } + } + + return NULL; +} + +static void pointer_handle_enter(void *data, struct wl_pointer *wl_pointer, + uint32_t serial, struct wl_surface *surface, wl_fixed_t sx, + wl_fixed_t sy) { + struct wlr_wl_seat *seat = data; + if (surface == NULL) { + return; + } + + struct wlr_wl_output *output = get_wl_output_from_surface(seat->backend, surface); + if (output == NULL) { + return; + } + + struct wlr_wl_pointer *pointer = output_get_pointer(output, wl_pointer); + seat->active_pointer = pointer; + + // Manage cursor icon/rendering on output + struct wlr_wl_pointer *current = output->cursor.pointer; + if (current && current != pointer) { + wlr_log(WLR_INFO, "Ignoring seat '%s' pointer in favor of seat '%s'", + seat->name, current->seat->name); + return; + } + + output->enter_serial = serial; + output->cursor.pointer = pointer; + update_wl_output_cursor(output); +} + +static void pointer_handle_leave(void *data, struct wl_pointer *wl_pointer, + uint32_t serial, struct wl_surface *surface) { + struct wlr_wl_seat *seat = data; + if (surface == NULL) { + return; + } + + struct wlr_wl_output *output = get_wl_output_from_surface(seat->backend, surface); + if (output == NULL) { + return; + } + + if (seat->active_pointer != NULL && + seat->active_pointer->output == output) { + seat->active_pointer = NULL; + } + + if (output->cursor.pointer == seat->active_pointer) { + output->enter_serial = 0; + output->cursor.pointer = NULL; + } +} + +static void pointer_handle_motion(void *data, struct wl_pointer *wl_pointer, + uint32_t time, wl_fixed_t sx, wl_fixed_t sy) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + struct wlr_output *wlr_output = &pointer->output->wlr_output; + struct wlr_pointer_motion_absolute_event event = { + .pointer = &pointer->wlr_pointer, + .time_msec = time, + .x = wl_fixed_to_double(sx) / wlr_output->width, + .y = wl_fixed_to_double(sy) / wlr_output->height, + }; + wl_signal_emit_mutable(&pointer->wlr_pointer.events.motion_absolute, &event); +} + +static void pointer_handle_button(void *data, struct wl_pointer *wl_pointer, + uint32_t serial, uint32_t time, uint32_t button, uint32_t state) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + struct wlr_pointer_button_event event = { + .pointer = &pointer->wlr_pointer, + .button = button, + .state = state, + .time_msec = time, + }; + wlr_pointer_notify_button(&pointer->wlr_pointer, &event); +} + +static void pointer_handle_axis(void *data, struct wl_pointer *wl_pointer, + uint32_t time, uint32_t axis, wl_fixed_t value) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + struct wlr_pointer_axis_event event = { + .pointer = &pointer->wlr_pointer, + .delta = wl_fixed_to_double(value), + .delta_discrete = pointer->axis_discrete, + .orientation = axis, + .time_msec = time, + .source = pointer->axis_source, + .relative_direction = pointer->axis_relative_direction, + }; + wl_signal_emit_mutable(&pointer->wlr_pointer.events.axis, &event); + + pointer->axis_discrete = 0; +} + +static void pointer_handle_frame(void *data, struct wl_pointer *wl_pointer) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + wl_signal_emit_mutable(&pointer->wlr_pointer.events.frame, + &pointer->wlr_pointer); +} + +static void pointer_handle_axis_source(void *data, + struct wl_pointer *wl_pointer, uint32_t axis_source) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + pointer->axis_source = axis_source; +} + +static void pointer_handle_axis_stop(void *data, struct wl_pointer *wl_pointer, + uint32_t time, uint32_t axis) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + struct wlr_pointer_axis_event event = { + .pointer = &pointer->wlr_pointer, + .delta = 0, + .delta_discrete = 0, + .orientation = axis, + .time_msec = time, + .source = pointer->axis_source, + }; + wl_signal_emit_mutable(&pointer->wlr_pointer.events.axis, &event); +} + +static void pointer_handle_axis_discrete(void *data, + struct wl_pointer *wl_pointer, uint32_t axis, int32_t discrete) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + pointer->axis_discrete = discrete * WLR_POINTER_AXIS_DISCRETE_STEP; +} + +static void pointer_handle_axis_value120(void *data, + struct wl_pointer *wl_pointer, uint32_t axis, int32_t value120) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + pointer->axis_discrete = value120; +} + +static void pointer_handle_axis_relative_direction(void *data, + struct wl_pointer *wl_pointer, uint32_t axis, uint32_t direction) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + pointer->axis_relative_direction = direction; +} + +static const struct wl_pointer_listener pointer_listener = { + .enter = pointer_handle_enter, + .leave = pointer_handle_leave, + .motion = pointer_handle_motion, + .button = pointer_handle_button, + .axis = pointer_handle_axis, + .frame = pointer_handle_frame, + .axis_source = pointer_handle_axis_source, + .axis_stop = pointer_handle_axis_stop, + .axis_discrete = pointer_handle_axis_discrete, + .axis_value120 = pointer_handle_axis_value120, + .axis_relative_direction = pointer_handle_axis_relative_direction, +}; + +static void gesture_swipe_begin(void *data, + struct zwp_pointer_gesture_swipe_v1 *zwp_pointer_gesture_swipe_v1, + uint32_t serial, uint32_t time, struct wl_surface *surface, + uint32_t fingers) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + pointer->fingers = fingers; + + struct wlr_pointer_swipe_begin_event wlr_event = { + .pointer = &pointer->wlr_pointer, + .time_msec = time, + .fingers = fingers, + }; + wl_signal_emit_mutable(&pointer->wlr_pointer.events.swipe_begin, &wlr_event); +} + +static void gesture_swipe_update(void *data, + struct zwp_pointer_gesture_swipe_v1 *zwp_pointer_gesture_swipe_v1, + uint32_t time, wl_fixed_t dx, wl_fixed_t dy) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + struct wlr_pointer_swipe_update_event wlr_event = { + .pointer = &pointer->wlr_pointer, + .time_msec = time, + .fingers = pointer->fingers, + .dx = wl_fixed_to_double(dx), + .dy = wl_fixed_to_double(dy), + }; + wl_signal_emit_mutable(&pointer->wlr_pointer.events.swipe_update, &wlr_event); +} + +static void gesture_swipe_end(void *data, + struct zwp_pointer_gesture_swipe_v1 *zwp_pointer_gesture_swipe_v1, + uint32_t serial, uint32_t time, int32_t cancelled) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + struct wlr_pointer_swipe_end_event wlr_event = { + .pointer = &pointer->wlr_pointer, + .time_msec = time, + .cancelled = cancelled, + }; + wl_signal_emit_mutable(&pointer->wlr_pointer.events.swipe_end, &wlr_event); +} + +static const struct zwp_pointer_gesture_swipe_v1_listener gesture_swipe_impl = { + .begin = gesture_swipe_begin, + .update = gesture_swipe_update, + .end = gesture_swipe_end, +}; + +static void gesture_pinch_begin(void *data, + struct zwp_pointer_gesture_pinch_v1 *zwp_pointer_gesture_pinch_v1, + uint32_t serial, uint32_t time, struct wl_surface *surface, + uint32_t fingers) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + pointer->fingers = fingers; + + struct wlr_pointer_pinch_begin_event wlr_event = { + .pointer = &pointer->wlr_pointer, + .time_msec = time, + .fingers = pointer->fingers, + }; + + wl_signal_emit_mutable(&pointer->wlr_pointer.events.pinch_begin, &wlr_event); +} + +static void gesture_pinch_update(void *data, + struct zwp_pointer_gesture_pinch_v1 *zwp_pointer_gesture_pinch_v1, + uint32_t time, wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t scale, + wl_fixed_t rotation) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + struct wlr_pointer_pinch_update_event wlr_event = { + .pointer = &pointer->wlr_pointer, + .time_msec = time, + .fingers = pointer->fingers, + .dx = wl_fixed_to_double(dx), + .dy = wl_fixed_to_double(dy), + .scale = wl_fixed_to_double(scale), + .rotation = wl_fixed_to_double(rotation), + }; + wl_signal_emit_mutable(&pointer->wlr_pointer.events.pinch_update, &wlr_event); +} + +static void gesture_pinch_end(void *data, + struct zwp_pointer_gesture_pinch_v1 *zwp_pointer_gesture_pinch_v1, + uint32_t serial, uint32_t time, int32_t cancelled) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + struct wlr_pointer_pinch_end_event wlr_event = { + .pointer = &pointer->wlr_pointer, + .time_msec = time, + .cancelled = cancelled, + }; + wl_signal_emit_mutable(&pointer->wlr_pointer.events.pinch_end, &wlr_event); +} + +static const struct zwp_pointer_gesture_pinch_v1_listener gesture_pinch_impl = { + .begin = gesture_pinch_begin, + .update = gesture_pinch_update, + .end = gesture_pinch_end, +}; + +static void gesture_hold_begin(void *data, + struct zwp_pointer_gesture_hold_v1 *zwp_pointer_gesture_hold_v1, + uint32_t serial, uint32_t time, struct wl_surface *surface, + uint32_t fingers) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + pointer->fingers = fingers; + + struct wlr_pointer_hold_begin_event wlr_event = { + .pointer = &pointer->wlr_pointer, + .time_msec = time, + .fingers = fingers, + }; + wl_signal_emit_mutable(&pointer->wlr_pointer.events.hold_begin, &wlr_event); +} + +static void gesture_hold_end(void *data, + struct zwp_pointer_gesture_hold_v1 *zwp_pointer_gesture_hold_v1, + uint32_t serial, uint32_t time, int32_t cancelled) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + struct wlr_pointer_hold_end_event wlr_event = { + .pointer = &pointer->wlr_pointer, + .time_msec = time, + .cancelled = cancelled, + }; + wl_signal_emit_mutable(&pointer->wlr_pointer.events.hold_end, &wlr_event); +} + +static const struct zwp_pointer_gesture_hold_v1_listener gesture_hold_impl = { + .begin = gesture_hold_begin, + .end = gesture_hold_end, +}; + +static void relative_pointer_handle_relative_motion(void *data, + struct zwp_relative_pointer_v1 *relative_pointer, uint32_t utime_hi, + uint32_t utime_lo, wl_fixed_t dx, wl_fixed_t dy, wl_fixed_t dx_unaccel, + wl_fixed_t dy_unaccel) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_pointer *pointer = seat->active_pointer; + if (pointer == NULL) { + return; + } + + uint64_t time_usec = (uint64_t)utime_hi << 32 | utime_lo; + + struct wlr_pointer_motion_event wlr_event = { + .pointer = &pointer->wlr_pointer, + .time_msec = (uint32_t)(time_usec / 1000), + .delta_x = wl_fixed_to_double(dx), + .delta_y = wl_fixed_to_double(dy), + .unaccel_dx = wl_fixed_to_double(dx_unaccel), + .unaccel_dy = wl_fixed_to_double(dy_unaccel), + }; + wl_signal_emit_mutable(&pointer->wlr_pointer.events.motion, &wlr_event); +} + +static const struct zwp_relative_pointer_v1_listener relative_pointer_listener = { + .relative_motion = relative_pointer_handle_relative_motion, +}; + +const struct wlr_pointer_impl wl_pointer_impl = { + .name = "wl-pointer", +}; + +static void destroy_pointer(struct wlr_wl_pointer *pointer) { + if (pointer->output->cursor.pointer == pointer) { + pointer->output->cursor.pointer = NULL; + } + if (pointer->seat->active_pointer == pointer) { + pointer->seat->active_pointer = NULL; + } + + wlr_pointer_finish(&pointer->wlr_pointer); + wl_list_remove(&pointer->output_destroy.link); + wl_list_remove(&pointer->link); + free(pointer); +} + +static void pointer_output_destroy(struct wl_listener *listener, void *data) { + struct wlr_wl_pointer *pointer = + wl_container_of(listener, pointer, output_destroy); + destroy_pointer(pointer); +} + +void create_pointer(struct wlr_wl_seat *seat, struct wlr_wl_output *output) { + assert(seat->wl_pointer); + + if (output_get_pointer(output, seat->wl_pointer)) { + wlr_log(WLR_DEBUG, + "pointer for output '%s' from seat '%s' already exists", + output->wlr_output.name, seat->name); + return; + } + + wlr_log(WLR_DEBUG, "creating pointer for output '%s' from seat '%s'", + output->wlr_output.name, seat->name); + + struct wlr_wl_pointer *pointer = calloc(1, sizeof(*pointer)); + if (pointer == NULL) { + wlr_log(WLR_ERROR, "failed to allocate wlr_wl_pointer"); + return; + } + + char name[64] = {0}; + snprintf(name, sizeof(name), "wayland-pointer-%s", seat->name); + wlr_pointer_init(&pointer->wlr_pointer, &wl_pointer_impl, name); + + pointer->wlr_pointer.output_name = strdup(output->wlr_output.name); + + pointer->seat = seat; + pointer->output = output; + + wl_signal_add(&output->wlr_output.events.destroy, &pointer->output_destroy); + pointer->output_destroy.notify = pointer_output_destroy; + + wl_signal_emit_mutable(&seat->backend->backend.events.new_input, + &pointer->wlr_pointer.base); + + wl_list_insert(&seat->pointers, &pointer->link); +} + +void init_seat_pointer(struct wlr_wl_seat *seat) { + assert(seat->wl_pointer); + + struct wlr_wl_backend *backend = seat->backend; + + wl_list_init(&seat->pointers); + + struct wlr_wl_output *output; + wl_list_for_each(output, &backend->outputs, link) { + create_pointer(seat, output); + } + + if (backend->zwp_pointer_gestures_v1) { + uint32_t version = zwp_pointer_gestures_v1_get_version( + backend->zwp_pointer_gestures_v1); + + seat->gesture_swipe = zwp_pointer_gestures_v1_get_swipe_gesture( + backend->zwp_pointer_gestures_v1, seat->wl_pointer); + zwp_pointer_gesture_swipe_v1_add_listener(seat->gesture_swipe, + &gesture_swipe_impl, seat); + + seat->gesture_pinch = zwp_pointer_gestures_v1_get_pinch_gesture( + backend->zwp_pointer_gestures_v1, seat->wl_pointer); + zwp_pointer_gesture_pinch_v1_add_listener(seat->gesture_pinch, + &gesture_pinch_impl, seat); + + if (version >= ZWP_POINTER_GESTURES_V1_GET_HOLD_GESTURE) { + seat->gesture_hold = zwp_pointer_gestures_v1_get_hold_gesture( + backend->zwp_pointer_gestures_v1, seat->wl_pointer); + zwp_pointer_gesture_hold_v1_add_listener(seat->gesture_hold, + &gesture_hold_impl, seat); + } + } + + if (backend->zwp_relative_pointer_manager_v1) { + seat->relative_pointer = + zwp_relative_pointer_manager_v1_get_relative_pointer( + backend->zwp_relative_pointer_manager_v1, seat->wl_pointer); + zwp_relative_pointer_v1_add_listener(seat->relative_pointer, + &relative_pointer_listener, seat); + } + + wl_pointer_add_listener(seat->wl_pointer, &pointer_listener, seat); +} + +void finish_seat_pointer(struct wlr_wl_seat *seat) { + assert(seat->wl_pointer); + + wl_pointer_release(seat->wl_pointer); + + struct wlr_wl_pointer *pointer, *tmp; + wl_list_for_each_safe(pointer, tmp, &seat->pointers, link) { + destroy_pointer(pointer); + } + + if (seat->gesture_swipe != NULL) { + zwp_pointer_gesture_swipe_v1_destroy(seat->gesture_swipe); + } + if (seat->gesture_pinch != NULL) { + zwp_pointer_gesture_pinch_v1_destroy(seat->gesture_pinch); + } + if (seat->gesture_hold != NULL) { + zwp_pointer_gesture_hold_v1_destroy(seat->gesture_hold); + } + if (seat->relative_pointer != NULL) { + zwp_relative_pointer_v1_destroy(seat->relative_pointer); + } + + seat->wl_pointer = NULL; + seat->active_pointer = NULL; +} diff --git a/3rdparty/wlroots/backend/wayland/seat.c b/3rdparty/wlroots/backend/wayland/seat.c new file mode 100644 index 0000000000..f178d9baf9 --- /dev/null +++ b/3rdparty/wlroots/backend/wayland/seat.c @@ -0,0 +1,382 @@ +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "backend/wayland.h" +#include "util/time.h" + +static void keyboard_handle_keymap(void *data, struct wl_keyboard *wl_keyboard, + uint32_t format, int32_t fd, uint32_t size) { + close(fd); +} + +static void keyboard_handle_enter(void *data, struct wl_keyboard *wl_keyboard, + uint32_t serial, struct wl_surface *surface, struct wl_array *keys) { + struct wlr_keyboard *keyboard = data; + + int64_t time_msec = get_current_time_msec(); + + uint32_t *keycode_ptr; + wl_array_for_each(keycode_ptr, keys) { + struct wlr_keyboard_key_event event = { + .keycode = *keycode_ptr, + .state = WL_KEYBOARD_KEY_STATE_PRESSED, + .time_msec = time_msec, + .update_state = false, + }; + wlr_keyboard_notify_key(keyboard, &event); + } +} + +static void keyboard_handle_leave(void *data, struct wl_keyboard *wl_keyboard, + uint32_t serial, struct wl_surface *surface) { + struct wlr_keyboard *keyboard = data; + + int64_t time_msec = get_current_time_msec(); + while (keyboard->num_keycodes > 0) { + struct wlr_keyboard_key_event event = { + .keycode = keyboard->keycodes[keyboard->num_keycodes - 1], + .state = WL_KEYBOARD_KEY_STATE_RELEASED, + .time_msec = time_msec, + .update_state = false, + }; + wlr_keyboard_notify_key(keyboard, &event); + } +} + +static void keyboard_handle_key(void *data, struct wl_keyboard *wl_keyboard, + uint32_t serial, uint32_t time, uint32_t key, uint32_t state) { + struct wlr_keyboard *keyboard = data; + + struct wlr_keyboard_key_event wlr_event = { + .keycode = key, + .state = state, + .time_msec = time, + .update_state = false, + }; + wlr_keyboard_notify_key(keyboard, &wlr_event); +} + +static void keyboard_handle_modifiers(void *data, struct wl_keyboard *wl_keyboard, + uint32_t serial, uint32_t mods_depressed, uint32_t mods_latched, + uint32_t mods_locked, uint32_t group) { + struct wlr_keyboard *keyboard = data; + wlr_keyboard_notify_modifiers(keyboard, mods_depressed, mods_latched, + mods_locked, group); +} + +static void keyboard_handle_repeat_info(void *data, + struct wl_keyboard *wl_keyboard, int32_t rate, int32_t delay) { + // This space is intentionally left blank +} + +static const struct wl_keyboard_listener keyboard_listener = { + .keymap = keyboard_handle_keymap, + .enter = keyboard_handle_enter, + .leave = keyboard_handle_leave, + .key = keyboard_handle_key, + .modifiers = keyboard_handle_modifiers, + .repeat_info = keyboard_handle_repeat_info +}; + +static const struct wlr_keyboard_impl keyboard_impl = { + .name = "wl-keyboard", +}; + +void init_seat_keyboard(struct wlr_wl_seat *seat) { + assert(seat->wl_keyboard); + + char name[128] = {0}; + snprintf(name, sizeof(name), "wayland-keyboard-%s", seat->name); + + wlr_keyboard_init(&seat->wlr_keyboard, &keyboard_impl, name); + wl_keyboard_add_listener(seat->wl_keyboard, &keyboard_listener, + &seat->wlr_keyboard); + + wl_signal_emit_mutable(&seat->backend->backend.events.new_input, + &seat->wlr_keyboard.base); +} + +static void touch_coordinates_to_absolute(struct wlr_wl_seat *seat, + wl_fixed_t x, wl_fixed_t y, double *sx, double *sy) { + /** + * TODO: multi-output touch support + * Although the wayland backend supports multi-output pointers, the support + * for multi-output touch has been left on the side for simplicity reasons. + * If this is a feature you want/need, please open an issue on the wlroots + * tracker here https://gitlab.freedesktop.org/wlroots/wlroots/-/issues + */ + struct wlr_wl_output *output, *tmp; + wl_list_for_each_safe(output, tmp, &seat->backend->outputs, link) { + *sx = wl_fixed_to_double(x) / output->wlr_output.width; + *sy = wl_fixed_to_double(y) / output->wlr_output.height; + return; // Choose the first output in the list + } + + *sx = *sy = 0; +} + +static void touch_handle_down(void *data, struct wl_touch *wl_touch, + uint32_t serial, uint32_t time, struct wl_surface *surface, + int32_t id, wl_fixed_t x, wl_fixed_t y) { + struct wlr_wl_seat *seat = data; + struct wlr_touch *touch = &seat->wlr_touch; + + struct wlr_wl_touch_points *points = &seat->touch_points; + assert(points->len != sizeof(points->ids) / sizeof(points->ids[0])); + points->ids[points->len++] = id; + + struct wlr_touch_down_event event = { + .touch = touch, + .time_msec = time, + .touch_id = id, + }; + touch_coordinates_to_absolute(seat, x, y, &event.x, &event.y); + wl_signal_emit_mutable(&touch->events.down, &event); +} + +static bool remove_touch_point(struct wlr_wl_touch_points *points, int32_t id) { + size_t i = 0; + for (; i < points->len; i++) { + if (points->ids[i] == id) { + size_t remaining = points->len - i - 1; + memmove(&points->ids[i], &points->ids[i + 1], remaining * sizeof(id)); + points->len--; + return true; + } + } + return false; +} + +static void touch_handle_up(void *data, struct wl_touch *wl_touch, + uint32_t serial, uint32_t time, int32_t id) { + struct wlr_wl_seat *seat = data; + struct wlr_touch *touch = &seat->wlr_touch; + + remove_touch_point(&seat->touch_points, id); + + struct wlr_touch_up_event event = { + .touch = touch, + .time_msec = time, + .touch_id = id, + }; + wl_signal_emit_mutable(&touch->events.up, &event); +} + +static void touch_handle_motion(void *data, struct wl_touch *wl_touch, + uint32_t time, int32_t id, wl_fixed_t x, wl_fixed_t y) { + struct wlr_wl_seat *seat = data; + struct wlr_touch *touch = &seat->wlr_touch; + + struct wlr_touch_motion_event event = { + .touch = touch, + .time_msec = time, + .touch_id = id, + }; + + touch_coordinates_to_absolute(seat, x, y, &event.x, &event.y); + wl_signal_emit_mutable(&touch->events.motion, &event); +} + +static void touch_handle_frame(void *data, struct wl_touch *wl_touch) { + struct wlr_wl_seat *seat = data; + wl_signal_emit_mutable(&seat->wlr_touch.events.frame, NULL); +} + +static void touch_handle_cancel(void *data, struct wl_touch *wl_touch) { + struct wlr_wl_seat *seat = data; + struct wlr_touch *touch = &seat->wlr_touch; + + // wayland's cancel event applies to all active touch points + for (size_t i = 0; i < seat->touch_points.len; i++) { + struct wlr_touch_cancel_event event = { + .touch = touch, + .time_msec = 0, + .touch_id = seat->touch_points.ids[i], + }; + wl_signal_emit_mutable(&touch->events.cancel, &event); + } + seat->touch_points.len = 0; +} + +static void touch_handle_shape(void *data, struct wl_touch *wl_touch, + int32_t id, wl_fixed_t major, wl_fixed_t minor) { + // no-op +} + +static void touch_handle_orientation(void *data, struct wl_touch *wl_touch, + int32_t id, wl_fixed_t orientation) { + // no-op +} + +static const struct wl_touch_listener touch_listener = { + .down = touch_handle_down, + .up = touch_handle_up, + .motion = touch_handle_motion, + .frame = touch_handle_frame, + .cancel = touch_handle_cancel, + .shape = touch_handle_shape, + .orientation = touch_handle_orientation, +}; + +static const struct wlr_touch_impl touch_impl = { + .name = "wl-touch", +}; + +void init_seat_touch(struct wlr_wl_seat *seat) { + assert(seat->wl_touch); + + char name[128] = {0}; + snprintf(name, sizeof(name), "wayland-touch-%s", seat->name); + + wlr_touch_init(&seat->wlr_touch, &touch_impl, name); + + struct wlr_wl_output *output; + wl_list_for_each(output, &seat->backend->outputs, link) { + /* Multi-output touch not supported */ + seat->wlr_touch.output_name = strdup(output->wlr_output.name); + break; + } + + wl_touch_add_listener(seat->wl_touch, &touch_listener, seat); + wl_signal_emit_mutable(&seat->backend->backend.events.new_input, + &seat->wlr_touch.base); +} + +static const struct wl_seat_listener seat_listener; + +bool create_wl_seat(struct wl_seat *wl_seat, struct wlr_wl_backend *wl, + uint32_t global_name) { + struct wlr_wl_seat *seat = calloc(1, sizeof(*seat)); + if (!seat) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return false; + } + seat->wl_seat = wl_seat; + seat->backend = wl; + seat->global_name = global_name; + wl_list_insert(&wl->seats, &seat->link); + wl_seat_add_listener(wl_seat, &seat_listener, seat); + return true; +} + +void destroy_wl_seat(struct wlr_wl_seat *seat) { + if (seat->wl_touch) { + wl_touch_release(seat->wl_touch); + wlr_touch_finish(&seat->wlr_touch); + } + if (seat->wl_pointer) { + finish_seat_pointer(seat); + } + if (seat->wl_keyboard) { + wl_keyboard_release(seat->wl_keyboard); + + if (seat->backend->started) { + wlr_keyboard_finish(&seat->wlr_keyboard); + } + } + if (seat->zwp_tablet_seat_v2) { + finish_seat_tablet(seat); + } + + free(seat->name); + assert(seat->wl_seat); + wl_seat_destroy(seat->wl_seat); + + wl_list_remove(&seat->link); + free(seat); +} + +bool wlr_input_device_is_wl(struct wlr_input_device *dev) { + switch (dev->type) { + case WLR_INPUT_DEVICE_KEYBOARD: + return wlr_keyboard_from_input_device(dev)->impl == &keyboard_impl; + case WLR_INPUT_DEVICE_POINTER: + return wlr_pointer_from_input_device(dev)->impl == &wl_pointer_impl; + case WLR_INPUT_DEVICE_TOUCH: + return wlr_touch_from_input_device(dev)->impl == &touch_impl; + case WLR_INPUT_DEVICE_TABLET: + return wlr_tablet_from_input_device(dev)-> impl == &wl_tablet_impl; + case WLR_INPUT_DEVICE_TABLET_PAD: + return wlr_tablet_pad_from_input_device(dev)->impl == &wl_tablet_pad_impl; + default: + return false; + } +} + +static void seat_handle_capabilities(void *data, struct wl_seat *wl_seat, + enum wl_seat_capability caps) { + struct wlr_wl_seat *seat = data; + struct wlr_wl_backend *backend = seat->backend; + + if ((caps & WL_SEAT_CAPABILITY_POINTER) && seat->wl_pointer == NULL) { + wlr_log(WLR_DEBUG, "seat '%s' offering pointer", seat->name); + + seat->wl_pointer = wl_seat_get_pointer(wl_seat); + init_seat_pointer(seat); + } + if (!(caps & WL_SEAT_CAPABILITY_POINTER) && seat->wl_pointer != NULL) { + wlr_log(WLR_DEBUG, "seat '%s' dropping pointer", seat->name); + finish_seat_pointer(seat); + } + + if ((caps & WL_SEAT_CAPABILITY_KEYBOARD) && seat->wl_keyboard == NULL) { + wlr_log(WLR_DEBUG, "seat '%s' offering keyboard", seat->name); + + struct wl_keyboard *wl_keyboard = wl_seat_get_keyboard(wl_seat); + seat->wl_keyboard = wl_keyboard; + + if (backend->started) { + init_seat_keyboard(seat); + } + } + if (!(caps & WL_SEAT_CAPABILITY_KEYBOARD) && seat->wl_keyboard != NULL) { + wlr_log(WLR_DEBUG, "seat '%s' dropping keyboard", seat->name); + + wl_keyboard_release(seat->wl_keyboard); + wlr_keyboard_finish(&seat->wlr_keyboard); + + seat->wl_keyboard = NULL; + } + + if ((caps & WL_SEAT_CAPABILITY_TOUCH) && seat->wl_touch == NULL) { + wlr_log(WLR_DEBUG, "seat '%s' offering touch", seat->name); + + seat->wl_touch = wl_seat_get_touch(wl_seat); + if (backend->started) { + init_seat_touch(seat); + } + } + if (!(caps & WL_SEAT_CAPABILITY_TOUCH) && seat->wl_touch != NULL) { + wlr_log(WLR_DEBUG, "seat '%s' dropping touch", seat->name); + + wl_touch_release(seat->wl_touch); + wlr_touch_finish(&seat->wlr_touch); + seat->wl_touch = NULL; + } +} + +static void seat_handle_name(void *data, struct wl_seat *wl_seat, + const char *name) { + struct wlr_wl_seat *seat = data; + free(seat->name); + seat->name = strdup(name); +} + +static const struct wl_seat_listener seat_listener = { + .capabilities = seat_handle_capabilities, + .name = seat_handle_name, +}; diff --git a/3rdparty/wlroots/backend/wayland/tablet_v2.c b/3rdparty/wlroots/backend/wayland/tablet_v2.c new file mode 100644 index 0000000000..3f6a16eed0 --- /dev/null +++ b/3rdparty/wlroots/backend/wayland/tablet_v2.c @@ -0,0 +1,932 @@ + +#include +#include +#include +#include +#include +#include +#include + +#include "backend/wayland.h" +#include "util/time.h" + +#include "tablet-v2-client-protocol.h" + +struct tablet_tool { + /* static */ + struct wlr_wl_seat *seat; + + /* semi-static */ + struct wlr_wl_output *output; + double pre_x, pre_y; + + /* per frame */ + double x, y; + + double pressure; + double distance; + double tilt_x, tilt_y; + double rotation; + double slider; + double wheel_delta; + + bool is_in; + bool is_out; + + bool is_up; + bool is_down; +}; + +struct tablet_pad_ring { + struct wl_list link; // tablet_pad_group.rings + /* static */ + struct zwp_tablet_pad_ring_v2 *ring; + struct tablet_pad_group *group; + size_t index; + + /* per frame */ + enum wlr_tablet_pad_ring_source source; + double angle; + bool stopped; +}; + +struct tablet_pad_strip { + struct wl_list link; // tablet_pad_group.strips + struct zwp_tablet_pad_strip_v2 *strip; + struct tablet_pad_group *group; + size_t index; + + enum wlr_tablet_pad_strip_source source; + double position; + bool stopped; +}; + +struct tablet_pad_group { + struct zwp_tablet_pad_group_v2 *pad_group; + struct wlr_tablet_pad *pad; + unsigned int mode; + + struct wlr_tablet_pad_group group; + + struct wl_list rings; // tablet_pad_ring.link + struct wl_list strips; // tablet_pad_strips.link +}; + +static void handle_tablet_pad_ring_source(void *data, + struct zwp_tablet_pad_ring_v2 *zwp_tablet_pad_ring_v2, + uint32_t source) { + struct tablet_pad_ring *ring = data; + ring->source = source; +} + +static void handle_tablet_pad_ring_angle(void *data, + struct zwp_tablet_pad_ring_v2 *zwp_tablet_pad_ring_v2, + wl_fixed_t degrees) { + struct tablet_pad_ring *ring = data; + ring->angle = wl_fixed_to_double(degrees); +} + +static void handle_tablet_pad_ring_stop(void *data, + struct zwp_tablet_pad_ring_v2 *zwp_tablet_pad_ring_v2) { + struct tablet_pad_ring *ring = data; + ring->stopped = true; +} + +static void handle_tablet_pad_ring_frame(void *data, + struct zwp_tablet_pad_ring_v2 *zwp_tablet_pad_ring_v2, + uint32_t time) { + struct tablet_pad_ring *ring = data; + + struct wlr_tablet_pad_ring_event evt = { + .time_msec = time, + .source = ring->source, + .ring = ring->index, + .position = ring->angle, + .mode = ring->group->mode, + }; + + if (ring->angle >= 0) { + wl_signal_emit_mutable(&ring->group->pad->events.ring, &evt); + } + if (ring->stopped) { + evt.position = -1; + wl_signal_emit_mutable(&ring->group->pad->events.ring, &evt); + } + + ring->angle = -1; + ring->stopped = false; + ring->source = 0; +} + +static const struct zwp_tablet_pad_ring_v2_listener tablet_pad_ring_listener = { + .source = handle_tablet_pad_ring_source, + .angle = handle_tablet_pad_ring_angle, + .stop = handle_tablet_pad_ring_stop, + .frame = handle_tablet_pad_ring_frame, +}; + +static void handle_tablet_pad_strip_source(void *data, + struct zwp_tablet_pad_strip_v2 *zwp_tablet_pad_strip_v2, + uint32_t source) { + struct tablet_pad_strip *strip = data; + strip->source = source; +} + +static void handle_tablet_pad_strip_position(void *data, + struct zwp_tablet_pad_strip_v2 *zwp_tablet_pad_strip_v2, + uint32_t position) { + struct tablet_pad_strip *strip = data; + strip->position = (double) position / 65536.0; +} + +static void handle_tablet_pad_strip_stop(void *data, + struct zwp_tablet_pad_strip_v2 *zwp_tablet_pad_strip_v2) { + struct tablet_pad_strip *strip = data; + strip->stopped = true; +} + +static void handle_tablet_pad_strip_frame(void *data, + struct zwp_tablet_pad_strip_v2 *zwp_tablet_pad_strip_v2, + uint32_t time) { + struct tablet_pad_strip *strip = data; + + struct wlr_tablet_pad_strip_event evt = { + .time_msec = time, + .source = strip->source, + .strip = strip->index, + .position = strip->position, + .mode = strip->group->mode, + }; + + if (strip->position >= 0) { + wl_signal_emit_mutable(&strip->group->pad->events.strip, &evt); + } + if (strip->stopped) { + evt.position = -1; + wl_signal_emit_mutable(&strip->group->pad->events.strip, &evt); + } + + strip->position = -1; + strip->stopped = false; + strip->source = 0; +} + +static const struct zwp_tablet_pad_strip_v2_listener tablet_pad_strip_listener = { + .source = handle_tablet_pad_strip_source, + .position = handle_tablet_pad_strip_position, + .stop = handle_tablet_pad_strip_stop, + .frame = handle_tablet_pad_strip_frame, +}; + +static void handle_tablet_pad_group_buttons(void *data, + struct zwp_tablet_pad_group_v2 *pad_group, + struct wl_array *buttons) { + struct tablet_pad_group *group = data; + + free(group->group.buttons); + group->group.buttons = calloc(1, buttons->size); + if (!group->group.buttons) { + // FIXME: Add actual error handling + return; + } + + group->group.button_count = buttons->size / sizeof(int); + memcpy(group->group.buttons, buttons->data, buttons->size); +} + +static void handle_tablet_pad_group_modes(void *data, + struct zwp_tablet_pad_group_v2 *pad_group, uint32_t modes) { + struct tablet_pad_group *group = data; + + group->group.mode_count = modes; +} + +static void handle_tablet_pad_group_ring(void *data, + struct zwp_tablet_pad_group_v2 *pad_group, + struct zwp_tablet_pad_ring_v2 *ring) { + struct tablet_pad_group *group = data; + struct tablet_pad_ring *tablet_ring = calloc(1, sizeof(*tablet_ring)); + if (!tablet_ring) { + zwp_tablet_pad_ring_v2_destroy(ring); + return; + } + tablet_ring->index = group->pad->ring_count++; + tablet_ring->group = group; + zwp_tablet_pad_ring_v2_add_listener(ring, &tablet_pad_ring_listener, + tablet_ring); + + group->group.rings = realloc(group->group.rings, + ++group->group.ring_count * sizeof(unsigned int)); + group->group.rings[group->group.ring_count - 1] = + tablet_ring->index; +} + +static void handle_tablet_pad_group_strip(void *data, + struct zwp_tablet_pad_group_v2 *pad_group, + struct zwp_tablet_pad_strip_v2 *strip) { + struct tablet_pad_group *group = data; + struct tablet_pad_strip *tablet_strip = calloc(1, sizeof(*tablet_strip)); + if (!tablet_strip) { + zwp_tablet_pad_strip_v2_destroy(strip); + return; + } + tablet_strip->index = group->pad->strip_count++; + tablet_strip->group = group; + zwp_tablet_pad_strip_v2_add_listener(strip, &tablet_pad_strip_listener, + tablet_strip); + + group->group.strips = realloc(group->group.strips, + ++group->group.strip_count * sizeof(unsigned int)); + group->group.strips[group->group.strip_count - 1] = + tablet_strip->index; +} + +static void handle_tablet_pad_group_done(void *data, + struct zwp_tablet_pad_group_v2 *pad_group) { + /* Empty for now */ +} + +static void handle_tablet_pad_group_mode_switch(void *data, + struct zwp_tablet_pad_group_v2 *pad_group, + uint32_t time, uint32_t serial, uint32_t mode) { + struct tablet_pad_group *group = data; + group->mode = mode; +} + +static void destroy_tablet_pad_group(struct tablet_pad_group *group) { + /* No need to remove the link on strips rings as long as we do *not* + * wl_list_remove on the wl_groups ring/strip attributes here */ + struct tablet_pad_ring *ring, *tmp_ring; + wl_list_for_each_safe(ring, tmp_ring, &group->rings, link) { + zwp_tablet_pad_ring_v2_destroy(ring->ring); + free(ring); + } + + struct tablet_pad_strip *strip, *tmp_strip; + wl_list_for_each_safe(strip, tmp_strip, &group->strips, link) { + zwp_tablet_pad_strip_v2_destroy(strip->strip); + free(strip); + } + + zwp_tablet_pad_group_v2_destroy(group->pad_group); + + free(group->group.buttons); + free(group->group.strips); + free(group->group.rings); + wl_list_remove(&group->group.link); + + free(group); +} + +static const struct zwp_tablet_pad_group_v2_listener tablet_pad_group_listener = { + .buttons = handle_tablet_pad_group_buttons, + .modes = handle_tablet_pad_group_modes, + .ring = handle_tablet_pad_group_ring, + .strip = handle_tablet_pad_group_strip, + .done = handle_tablet_pad_group_done, + .mode_switch = handle_tablet_pad_group_mode_switch, +}; + +static void handle_tablet_pad_group(void *data, + struct zwp_tablet_pad_v2 *zwp_tablet_pad, + struct zwp_tablet_pad_group_v2 *pad_group) { + struct wlr_wl_seat *seat = data; + struct wlr_tablet_pad *pad = &seat->wlr_tablet_pad; + + struct tablet_pad_group *group = calloc(1, sizeof(*group)); + if (!group) { + wlr_log_errno(WLR_ERROR, "failed to allocate tablet_pad_group"); + zwp_tablet_pad_group_v2_destroy(pad_group); + return; + } + group->pad_group = pad_group; + group->pad = pad; + + wl_list_init(&group->rings); + wl_list_init(&group->strips); + + zwp_tablet_pad_group_v2_add_listener(pad_group, + &tablet_pad_group_listener, group); + + wl_list_insert(&pad->groups, &group->group.link); +} + +static void handle_tablet_pad_path(void *data, + struct zwp_tablet_pad_v2 *zwp_tablet_pad_v2, const char *path) { + struct wlr_wl_seat *seat = data; + struct wlr_tablet_pad *tablet_pad = &seat->wlr_tablet_pad; + + char **dst = wl_array_add(&tablet_pad->paths, sizeof(char *)); + *dst = strdup(path); +} + +static void handle_tablet_pad_buttons(void *data, + struct zwp_tablet_pad_v2 *zwp_tablet_pad_v2, uint32_t buttons) { + struct wlr_wl_seat *seat = data; + struct wlr_tablet_pad *tablet_pad = &seat->wlr_tablet_pad; + + tablet_pad->button_count = buttons; +} + +static void handle_tablet_pad_button(void *data, + struct zwp_tablet_pad_v2 *zwp_tablet_pad_v2, + uint32_t time, uint32_t button, uint32_t state) { + struct wlr_wl_seat *seat = data; + struct wlr_tablet_pad_button_event evt = { + .time_msec = time, + .button = button, + .state = state, + .mode = 0, + .group = 0, + }; + + wl_signal_emit_mutable(&seat->wlr_tablet_pad.events.button, &evt); +} + +static void handle_tablet_pad_done(void *data, + struct zwp_tablet_pad_v2 *zwp_tablet_pad_v2) { + struct wlr_wl_seat *seat = data; + wl_signal_emit_mutable(&seat->backend->backend.events.new_input, + &seat->wlr_tablet_pad.base); +} + +static void handle_tablet_pad_enter(void *data, + struct zwp_tablet_pad_v2 *zwp_tablet_pad_v2, + uint32_t serial, struct zwp_tablet_v2 *tablet_p, + struct wl_surface *surface) { + struct wlr_wl_seat *seat = data; + assert(seat->zwp_tablet_v2 == tablet_p); + + wl_signal_emit_mutable(&seat->wlr_tablet_pad.events.attach_tablet, + &seat->wlr_tablet_tool); +} + +static void handle_tablet_pad_leave(void *data, + struct zwp_tablet_pad_v2 *zwp_tablet_pad_v2, + uint32_t serial, struct wl_surface *surface) { + /* Empty. Probably staying that way, unless we want to create/destroy + * tablet on enter/leave events (ehh) */ +} + +static void handle_tablet_pad_removed(void *data, + struct zwp_tablet_pad_v2 *zwp_tablet_pad_v2) { + struct wlr_wl_seat *seat = data; + + struct wlr_tablet_pad *tablet_pad = &seat->wlr_tablet_pad; + struct tablet_pad_group *group, *it; + wl_list_for_each_safe(group, it, &tablet_pad->groups, group.link) { + destroy_tablet_pad_group(group); + } + + wlr_tablet_pad_finish(tablet_pad); + zwp_tablet_pad_v2_destroy(seat->zwp_tablet_pad_v2); + seat->zwp_tablet_pad_v2 = NULL; +} + +static const struct zwp_tablet_pad_v2_listener tablet_pad_listener = { + .group = handle_tablet_pad_group, + .path = handle_tablet_pad_path, + .buttons = handle_tablet_pad_buttons, + .button = handle_tablet_pad_button, + .done = handle_tablet_pad_done, + .enter = handle_tablet_pad_enter, + .leave = handle_tablet_pad_leave, + .removed = handle_tablet_pad_removed, +}; + +const struct wlr_tablet_pad_impl wl_tablet_pad_impl = { + .name = "wl-tablet-pad", +}; + +static void handle_pad_added(void *data, + struct zwp_tablet_seat_v2 *zwp_tablet_seat_v2, + struct zwp_tablet_pad_v2 *zwp_tablet_pad_v2) { + struct wlr_wl_seat *seat = data; + if (seat->zwp_tablet_pad_v2 != NULL) { + wlr_log(WLR_ERROR, "zwp_tablet_pad_v2 is already present"); + zwp_tablet_pad_v2_destroy(zwp_tablet_pad_v2); + return; + } + + seat->zwp_tablet_pad_v2 = zwp_tablet_pad_v2; + zwp_tablet_pad_v2_add_listener(zwp_tablet_pad_v2, &tablet_pad_listener, + seat); + + wlr_tablet_pad_init(&seat->wlr_tablet_pad, &wl_tablet_pad_impl, + "wlr_tablet_v2"); +} + +static void handle_tablet_tool_done(void *data, + struct zwp_tablet_tool_v2 *id) { + /* empty */ +} + +static enum wlr_tablet_tool_type tablet_type_to_wlr_type( + enum zwp_tablet_tool_v2_type type) { + switch (type) { + case ZWP_TABLET_TOOL_V2_TYPE_PEN: + return WLR_TABLET_TOOL_TYPE_PEN; + case ZWP_TABLET_TOOL_V2_TYPE_ERASER: + return WLR_TABLET_TOOL_TYPE_ERASER; + case ZWP_TABLET_TOOL_V2_TYPE_BRUSH: + return WLR_TABLET_TOOL_TYPE_BRUSH; + case ZWP_TABLET_TOOL_V2_TYPE_PENCIL: + return WLR_TABLET_TOOL_TYPE_PENCIL; + case ZWP_TABLET_TOOL_V2_TYPE_AIRBRUSH: + return WLR_TABLET_TOOL_TYPE_AIRBRUSH; + case ZWP_TABLET_TOOL_V2_TYPE_MOUSE: + return WLR_TABLET_TOOL_TYPE_MOUSE; + case ZWP_TABLET_TOOL_V2_TYPE_LENS: + return WLR_TABLET_TOOL_TYPE_LENS; + case ZWP_TABLET_TOOL_V2_TYPE_FINGER: + // unused, see: + // https://gitlab.freedesktop.org/wayland/wayland-protocols/-/issues/18 + abort(); + } + abort(); // unreachable +} + +static void handle_tablet_tool_type(void *data, + struct zwp_tablet_tool_v2 *id, uint32_t tool_type) { + struct tablet_tool *tool = data; + struct wlr_tablet_tool *wlr_tool = &tool->seat->wlr_tablet_tool; + wlr_tool->type = tablet_type_to_wlr_type(tool_type); +} + +static void handle_tablet_tool_serial(void *data, + struct zwp_tablet_tool_v2 *id, uint32_t high, uint32_t low) { + struct tablet_tool *tool = data; + struct wlr_tablet_tool *wlr_tool = &tool->seat->wlr_tablet_tool; + wlr_tool->hardware_serial = ((uint64_t) high) << 32 | (uint64_t) low; +} + +static void handle_tablet_tool_id_wacom(void *data, + struct zwp_tablet_tool_v2 *id, uint32_t high, uint32_t low) { + struct tablet_tool *tool = data; + struct wlr_tablet_tool *wlr_tool = &tool->seat->wlr_tablet_tool; + wlr_tool->hardware_wacom = ((uint64_t) high) << 32 | (uint64_t) low; +} + +static void handle_tablet_tool_capability(void *data, + struct zwp_tablet_tool_v2 *id, uint32_t capability) { + struct tablet_tool *tool = data; + struct wlr_tablet_tool *wlr_tool = &tool->seat->wlr_tablet_tool; + + /* One event is sent for each capability */ + switch (capability) { + case ZWP_TABLET_TOOL_V2_CAPABILITY_TILT: + wlr_tool->tilt = true; + break; + case ZWP_TABLET_TOOL_V2_CAPABILITY_PRESSURE: + wlr_tool->pressure = true; + break; + case ZWP_TABLET_TOOL_V2_CAPABILITY_DISTANCE: + wlr_tool->distance = true; + break; + case ZWP_TABLET_TOOL_V2_CAPABILITY_ROTATION: + wlr_tool->rotation = true; + break; + case ZWP_TABLET_TOOL_V2_CAPABILITY_SLIDER: + wlr_tool->slider = true; + break; + case ZWP_TABLET_TOOL_V2_CAPABILITY_WHEEL: + wlr_tool->wheel = true; + break; + } +} + +static void handle_tablet_tool_proximity_in(void *data, + struct zwp_tablet_tool_v2 *id, uint32_t serial, + struct zwp_tablet_v2 *tablet_id, struct wl_surface *surface) { + struct tablet_tool *tool = data; + assert(tablet_id == tool->seat->zwp_tablet_v2); + + struct wlr_wl_output *output = get_wl_output_from_surface(tool->seat->backend, surface); + if (output == NULL) { + return; + } + + tool->is_in = true; + tool->output = output; +} + +static void handle_tablet_tool_proximity_out(void *data, + struct zwp_tablet_tool_v2 *id) { + struct tablet_tool *tool = data; + tool->is_out = true; + tool->output = NULL; +} + +static void handle_tablet_tool_down(void *data, struct zwp_tablet_tool_v2 *id, + unsigned int serial) { + struct tablet_tool *tool = data; + tool->is_down = true; +} + +static void handle_tablet_tool_up(void *data, struct zwp_tablet_tool_v2 *id) { + struct tablet_tool *tool = data; + tool->is_up = true; +} + +static void handle_tablet_tool_motion(void *data, struct zwp_tablet_tool_v2 *id, + wl_fixed_t x, wl_fixed_t y) { + struct tablet_tool *tool = data; + struct wlr_wl_output *output = tool->output; + assert(output); + + tool->x = wl_fixed_to_double(x) / output->wlr_output.width; + tool->y = wl_fixed_to_double(y) / output->wlr_output.height; +} + +static void handle_tablet_tool_pressure(void *data, + struct zwp_tablet_tool_v2 *id, uint32_t pressure) { + struct tablet_tool *tool = data; + tool->pressure = (double) pressure / 65535.0; +} + +static void handle_tablet_tool_distance(void *data, + struct zwp_tablet_tool_v2 *id, uint32_t distance) { + struct tablet_tool *tool = data; + tool->distance = (double) distance / 65535.0; +} + +static void handle_tablet_tool_tilt(void *data, struct zwp_tablet_tool_v2 *id, + wl_fixed_t x, wl_fixed_t y) { + struct tablet_tool *tool = data; + tool->tilt_x = wl_fixed_to_double(x); + tool->tilt_y = wl_fixed_to_double(y); +} + +static void handle_tablet_tool_rotation(void *data, + struct zwp_tablet_tool_v2 *id, wl_fixed_t rotation) { + struct tablet_tool *tool = data; + tool->rotation = wl_fixed_to_double(rotation); +} + +static void handle_tablet_tool_slider(void *data, struct zwp_tablet_tool_v2 *id, + int slider) { + struct tablet_tool *tool = data; + tool->slider = (double) slider / 65535.0;; +} + +// TODO: This looks wrong :/ +static void handle_tablet_tool_wheel(void *data, struct zwp_tablet_tool_v2 *id, + wl_fixed_t degree, int clicks) { + struct tablet_tool *tool = data; + tool->wheel_delta = wl_fixed_to_double(degree); +} + +static void handle_tablet_tool_button(void *data, + struct zwp_tablet_tool_v2 *id, + uint32_t serial, uint32_t button, uint32_t state) { + struct tablet_tool *tool = data; + struct wlr_wl_seat *seat = tool->seat; + struct wlr_tablet *tablet = &seat->wlr_tablet; + + struct wlr_tablet_tool_button_event evt = { + .tablet = tablet, + .tool = &seat->wlr_tablet_tool, + .time_msec = get_current_time_msec(), + .button = button, + .state = state == ZWP_TABLET_TOOL_V2_BUTTON_STATE_RELEASED ? + WLR_BUTTON_RELEASED : WLR_BUTTON_PRESSED, + }; + + wl_signal_emit_mutable(&tablet->events.button, &evt); +} + +static void clear_tablet_tool_values(struct tablet_tool *tool) { + tool->is_out = tool->is_in = false; + tool->is_up = tool->is_down = false; + tool->x = tool->y = NAN; + tool->pressure = NAN; + tool->distance = NAN; + tool->tilt_x = tool->tilt_y = NAN; + tool->rotation = NAN; + tool->slider = NAN; + tool->wheel_delta = NAN; +} + +static void handle_tablet_tool_frame(void *data, + struct zwp_tablet_tool_v2 *id, + uint32_t time) { + struct tablet_tool *tool = data; + struct wlr_wl_seat *seat = tool->seat; + + if (tool->is_out && tool->is_in) { + /* we got a tablet tool coming in and out of proximity before + * we could process it. Just ignore anything it did */ + goto clear_values; + } + struct wlr_tablet *tablet = &seat->wlr_tablet; + + if (tool->is_in) { + struct wlr_tablet_tool_proximity_event evt = { + .tablet = tablet, + .tool = &seat->wlr_tablet_tool, + .time_msec = time, + .x = tool->x, + .y = tool->y, + .state = WLR_TABLET_TOOL_PROXIMITY_IN, + }; + + wl_signal_emit_mutable(&tablet->events.proximity, &evt); + } + + { + struct wlr_tablet_tool_axis_event evt = { + .tablet = tablet, + .tool = &seat->wlr_tablet_tool, + .time_msec = time, + .updated_axes = 0, + }; + + if (!isnan(tool->x) && !tool->is_in) { + evt.updated_axes |= WLR_TABLET_TOOL_AXIS_X; + evt.x = tool->x; + } + + if (!isnan(tool->y) && !tool->is_in) { + evt.updated_axes |= WLR_TABLET_TOOL_AXIS_Y; + evt.y = tool->y; + } + + if (!isnan(tool->pressure)) { + evt.updated_axes |= WLR_TABLET_TOOL_AXIS_PRESSURE; + evt.pressure = tool->pressure; + } + + if (!isnan(tool->distance)) { + evt.updated_axes |= WLR_TABLET_TOOL_AXIS_DISTANCE; + evt.distance = tool->distance; + } + + if (!isnan(tool->tilt_x)) { + evt.updated_axes |= WLR_TABLET_TOOL_AXIS_TILT_X; + evt.tilt_x = tool->tilt_x; + } + + if (!isnan(tool->tilt_y)) { + evt.updated_axes |= WLR_TABLET_TOOL_AXIS_TILT_Y; + evt.tilt_y = tool->tilt_y; + } + + if (!isnan(tool->rotation)) { + evt.updated_axes |= WLR_TABLET_TOOL_AXIS_ROTATION; + evt.rotation = tool->rotation; + } + + if (!isnan(tool->slider)) { + evt.updated_axes |= WLR_TABLET_TOOL_AXIS_SLIDER; + evt.slider = tool->slider; + } + + if (!isnan(tool->wheel_delta)) { + evt.updated_axes |= WLR_TABLET_TOOL_AXIS_WHEEL; + evt.wheel_delta = tool->wheel_delta; + } + + if (evt.updated_axes) { + wl_signal_emit_mutable(&tablet->events.axis, &evt); + } + } + + /* This will always send down then up if we got both. + * Maybe we should send them right away, in case we get up then both in + * series? + * Downside: Here we have the frame time, if we sent right away, we + * need to generate the time */ + if (tool->is_down) { + struct wlr_tablet_tool_tip_event evt = { + .tablet = tablet, + .tool = &seat->wlr_tablet_tool, + .time_msec = time, + .x = tool->x, + .y = tool->y, + .state = WLR_TABLET_TOOL_TIP_DOWN, + }; + + wl_signal_emit_mutable(&tablet->events.tip, &evt); + } + + if (tool->is_up) { + struct wlr_tablet_tool_tip_event evt = { + .tablet = tablet, + .tool = &seat->wlr_tablet_tool, + .time_msec = time, + .x = tool->x, + .y = tool->y, + .state = WLR_TABLET_TOOL_TIP_UP, + }; + + wl_signal_emit_mutable(&tablet->events.tip, &evt); + } + + if (tool->is_out) { + struct wlr_tablet_tool_proximity_event evt = { + .tablet = tablet, + .tool = &seat->wlr_tablet_tool, + .time_msec = time, + .x = tool->x, + .y = tool->y, + .state = WLR_TABLET_TOOL_PROXIMITY_OUT, + }; + + wl_signal_emit_mutable(&tablet->events.proximity, &evt); + } + +clear_values: + clear_tablet_tool_values(tool); +} + +static void handle_tablet_tool_removed(void *data, + struct zwp_tablet_tool_v2 *id) { + struct tablet_tool *tool = data; + struct wlr_wl_seat *seat = tool->seat; + + zwp_tablet_tool_v2_destroy(seat->zwp_tablet_tool_v2); + seat->zwp_tablet_tool_v2 = NULL; + + free(tool); +} + +static const struct zwp_tablet_tool_v2_listener tablet_tool_listener = { + .removed = handle_tablet_tool_removed, + .done = handle_tablet_tool_done, + .type = handle_tablet_tool_type, + .hardware_serial = handle_tablet_tool_serial, + .hardware_id_wacom = handle_tablet_tool_id_wacom, + .capability = handle_tablet_tool_capability, + + .proximity_in = handle_tablet_tool_proximity_in, + .proximity_out = handle_tablet_tool_proximity_out, + .down = handle_tablet_tool_down, + .up = handle_tablet_tool_up, + + .motion = handle_tablet_tool_motion, + .pressure = handle_tablet_tool_pressure, + .distance = handle_tablet_tool_distance, + .tilt = handle_tablet_tool_tilt, + .rotation = handle_tablet_tool_rotation, + .slider = handle_tablet_tool_slider, + .wheel = handle_tablet_tool_wheel, + .button = handle_tablet_tool_button, + .frame = handle_tablet_tool_frame, +}; + +static void handle_tool_added(void *data, + struct zwp_tablet_seat_v2 *zwp_tablet_seat_v2, + struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2) { + struct wlr_wl_seat *seat = data; + if (seat->zwp_tablet_tool_v2 != NULL) { + wlr_log(WLR_ERROR, "zwp_tablet_tool_v2 already present"); + zwp_tablet_tool_v2_destroy(zwp_tablet_tool_v2); + return; + } + + wl_signal_init(&seat->wlr_tablet_tool.events.destroy); + + struct tablet_tool *tool = calloc(1, sizeof(*tool)); + if (tool == NULL) { + wlr_log_errno(WLR_ERROR, "failed to allocate tablet_tool"); + zwp_tablet_tool_v2_destroy(zwp_tablet_tool_v2); + return; + } + + tool->seat = seat; + clear_tablet_tool_values(tool); + + seat->zwp_tablet_tool_v2 = zwp_tablet_tool_v2; + zwp_tablet_tool_v2_add_listener(seat->zwp_tablet_tool_v2, &tablet_tool_listener, + tool); +} + +static void handle_tablet_name(void *data, struct zwp_tablet_v2 *zwp_tablet_v2, + const char *name) { + struct wlr_wl_seat *seat = data; + struct wlr_tablet *tablet = &seat->wlr_tablet; + + free(tablet->base.name); + tablet->base.name = strdup(name); +} + +static void handle_tablet_id(void *data, struct zwp_tablet_v2 *zwp_tablet_v2, + uint32_t vid, uint32_t pid) { + struct wlr_wl_seat *seat = data; + struct wlr_tablet *tablet = &seat->wlr_tablet; + + tablet->usb_vendor_id = vid; + tablet->usb_product_id = pid; +} + +static void handle_tablet_path(void *data, struct zwp_tablet_v2 *zwp_tablet_v2, + const char *path) { + struct wlr_wl_seat *seat = data; + struct wlr_tablet *tablet = &seat->wlr_tablet; + + char **dst = wl_array_add(&tablet->paths, sizeof(char *)); + *dst = strdup(path); +} + +static void handle_tablet_done(void *data, struct zwp_tablet_v2 *zwp_tablet_v2) { + struct wlr_wl_seat *seat = data; + + wl_signal_emit_mutable(&seat->backend->backend.events.new_input, + &seat->wlr_tablet.base); +} + +static void handle_tablet_removed(void *data, + struct zwp_tablet_v2 *zwp_tablet_v2) { + struct wlr_wl_seat *seat = data; + + wlr_tablet_finish(&seat->wlr_tablet); + zwp_tablet_v2_destroy(seat->zwp_tablet_v2); + seat->zwp_tablet_v2 = NULL; +} + +static const struct zwp_tablet_v2_listener tablet_listener = { + .name = handle_tablet_name, + .id = handle_tablet_id, + .path = handle_tablet_path, + .done = handle_tablet_done, + .removed = handle_tablet_removed, +}; + +const struct wlr_tablet_impl wl_tablet_impl = { + .name = "wl-tablet-tool", +}; + +static void handle_tab_added(void *data, + struct zwp_tablet_seat_v2 *zwp_tablet_seat_v2, + struct zwp_tablet_v2 *zwp_tablet_v2) { + struct wlr_wl_seat *seat = data; + if (seat->zwp_tablet_v2 != NULL) { + wlr_log(WLR_ERROR, "zwp_tablet_v2 already present"); + zwp_tablet_v2_destroy(zwp_tablet_v2); + return; + } + + seat->zwp_tablet_v2 = zwp_tablet_v2; + zwp_tablet_v2_add_listener(zwp_tablet_v2, &tablet_listener, seat); + + wlr_tablet_init(&seat->wlr_tablet, &wl_tablet_impl, "wlr_tablet_v2"); +} + +static const struct zwp_tablet_seat_v2_listener tablet_seat_listener = { + .tablet_added = handle_tab_added, + .tool_added = handle_tool_added, + .pad_added = handle_pad_added, +}; + +void init_seat_tablet(struct wlr_wl_seat *seat) { + struct zwp_tablet_manager_v2 *manager = seat->backend->tablet_manager; + assert(manager); + + /** + * TODO: multi tablet support + * The wlr_wl_seat should support multiple tablet_v2 devices, but for + * the sake of simplicity, it supports only one device of each. + * If this is a feature you want/need, please open an issue on the wlroots + * tracker here https://gitlab.freedesktop.org/wlroots/wlroots/-/issues + */ + + seat->zwp_tablet_seat_v2 = + zwp_tablet_manager_v2_get_tablet_seat(manager, seat->wl_seat); + if (seat->zwp_tablet_seat_v2 == NULL) { + wlr_log(WLR_ERROR, "failed to get zwp_tablet_manager_v2 from seat '%s'", + seat->name); + return; + } + + zwp_tablet_seat_v2_add_listener(seat->zwp_tablet_seat_v2, + &tablet_seat_listener, seat); +} + +void finish_seat_tablet(struct wlr_wl_seat *seat) { + if (seat->zwp_tablet_v2 != NULL) { + wlr_tablet_finish(&seat->wlr_tablet); + zwp_tablet_v2_destroy(seat->zwp_tablet_v2); + } + + if (seat->zwp_tablet_tool_v2 != NULL) { + struct tablet_tool *tool = + zwp_tablet_tool_v2_get_user_data(seat->zwp_tablet_tool_v2); + free(tool); + + zwp_tablet_tool_v2_destroy(seat->zwp_tablet_tool_v2); + } + + if (seat->zwp_tablet_pad_v2 != NULL) { + struct wlr_tablet_pad *tablet_pad = &seat->wlr_tablet_pad; + struct tablet_pad_group *group, *it; + wl_list_for_each_safe(group, it, &tablet_pad->groups, group.link) { + destroy_tablet_pad_group(group); + } + + wlr_tablet_pad_finish(tablet_pad); + zwp_tablet_pad_v2_destroy(seat->zwp_tablet_pad_v2); + } + + zwp_tablet_seat_v2_destroy(seat->zwp_tablet_seat_v2); + seat->zwp_tablet_seat_v2 = NULL; +} diff --git a/3rdparty/wlroots/backend/x11/backend.c b/3rdparty/wlroots/backend/x11/backend.c new file mode 100644 index 0000000000..4dc4bf16da --- /dev/null +++ b/3rdparty/wlroots/backend/x11/backend.c @@ -0,0 +1,747 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "backend/x11.h" +#include "render/drm_format_set.h" + +// See dri2_format_for_depth in mesa +const struct wlr_x11_format formats[] = { + { .drm = DRM_FORMAT_XRGB8888, .depth = 24, .bpp = 32 }, + { .drm = DRM_FORMAT_ARGB8888, .depth = 32, .bpp = 32 }, +}; + +static const struct wlr_x11_format *x11_format_from_depth(uint8_t depth) { + for (size_t i = 0; i < sizeof(formats) / sizeof(formats[0]); i++) { + if (formats[i].depth == depth) { + return &formats[i]; + } + } + return NULL; +} + +struct wlr_x11_output *get_x11_output_from_window_id( + struct wlr_x11_backend *x11, xcb_window_t window) { + struct wlr_x11_output *output; + wl_list_for_each(output, &x11->outputs, link) { + if (output->win == window) { + return output; + } + } + return NULL; +} + +static void handle_x11_error(struct wlr_x11_backend *x11, xcb_value_error_t *ev); +static void handle_x11_unknown_event(struct wlr_x11_backend *x11, + xcb_generic_event_t *ev); + +static void handle_x11_event(struct wlr_x11_backend *x11, + xcb_generic_event_t *event) { + switch (event->response_type & XCB_EVENT_RESPONSE_TYPE_MASK) { + case XCB_EXPOSE: { + xcb_expose_event_t *ev = (xcb_expose_event_t *)event; + struct wlr_x11_output *output = + get_x11_output_from_window_id(x11, ev->window); + if (output != NULL) { + pixman_region32_union_rect( + &output->exposed, &output->exposed, + ev->x, ev->y, ev->width, ev->height); + wlr_output_update_needs_frame(&output->wlr_output); + } + break; + } + case XCB_CONFIGURE_NOTIFY: { + xcb_configure_notify_event_t *ev = + (xcb_configure_notify_event_t *)event; + struct wlr_x11_output *output = + get_x11_output_from_window_id(x11, ev->window); + if (output != NULL) { + handle_x11_configure_notify(output, ev); + } + break; + } + case XCB_CLIENT_MESSAGE: { + xcb_client_message_event_t *ev = (xcb_client_message_event_t *)event; + if (ev->data.data32[0] == x11->atoms.wm_delete_window) { + struct wlr_x11_output *output = + get_x11_output_from_window_id(x11, ev->window); + if (output != NULL) { + wlr_output_destroy(&output->wlr_output); + } + } else { + wlr_log(WLR_DEBUG, "Unhandled client message %"PRIu32, + ev->data.data32[0]); + } + break; + } + case XCB_GE_GENERIC: { + xcb_ge_generic_event_t *ev = (xcb_ge_generic_event_t *)event; + if (ev->extension == x11->xinput_opcode) { + handle_x11_xinput_event(x11, ev); + } else if (ev->extension == x11->present_opcode) { + handle_x11_present_event(x11, ev); + } else { + handle_x11_unknown_event(x11, event); + } + break; + } + case 0: { + xcb_value_error_t *ev = (xcb_value_error_t *)event; + handle_x11_error(x11, ev); + break; + } + case XCB_DESTROY_NOTIFY: + case XCB_UNMAP_NOTIFY: + case XCB_MAP_NOTIFY: + break; + default: + handle_x11_unknown_event(x11, event); + break; + } +} + +static int x11_event(int fd, uint32_t mask, void *data) { + struct wlr_x11_backend *x11 = data; + + if ((mask & WL_EVENT_HANGUP) || (mask & WL_EVENT_ERROR)) { + if (mask & WL_EVENT_ERROR) { + wlr_log(WLR_ERROR, "Failed to read from X11 server"); + } + wlr_backend_destroy(&x11->backend); + return 0; + } + + xcb_generic_event_t *e; + while ((e = xcb_poll_for_event(x11->xcb))) { + handle_x11_event(x11, e); + free(e); + } + + int ret = xcb_connection_has_error(x11->xcb); + if (ret != 0) { + wlr_log(WLR_ERROR, "X11 connection error (%d)", ret); + wlr_backend_destroy(&x11->backend); + } + + return 0; +} + +struct wlr_x11_backend *get_x11_backend_from_backend( + struct wlr_backend *wlr_backend) { + assert(wlr_backend_is_x11(wlr_backend)); + struct wlr_x11_backend *backend = wl_container_of(wlr_backend, backend, backend); + return backend; +} + +static bool backend_start(struct wlr_backend *backend) { + struct wlr_x11_backend *x11 = get_x11_backend_from_backend(backend); + x11->started = true; + + wlr_log(WLR_INFO, "Starting X11 backend"); + + wl_signal_emit_mutable(&x11->backend.events.new_input, &x11->keyboard.base); + + for (size_t i = 0; i < x11->requested_outputs; ++i) { + wlr_x11_output_create(&x11->backend); + } + + return true; +} + +static void backend_destroy(struct wlr_backend *backend) { + if (!backend) { + return; + } + + struct wlr_x11_backend *x11 = get_x11_backend_from_backend(backend); + + struct wlr_x11_output *output, *tmp; + wl_list_for_each_safe(output, tmp, &x11->outputs, link) { + wlr_output_destroy(&output->wlr_output); + } + + wlr_keyboard_finish(&x11->keyboard); + + wlr_backend_finish(backend); + + if (x11->event_source) { + wl_event_source_remove(x11->event_source); + } + wl_list_remove(&x11->event_loop_destroy.link); + + wlr_drm_format_set_finish(&x11->primary_dri3_formats); + wlr_drm_format_set_finish(&x11->primary_shm_formats); + wlr_drm_format_set_finish(&x11->dri3_formats); + wlr_drm_format_set_finish(&x11->shm_formats); + +#if HAVE_XCB_ERRORS + xcb_errors_context_free(x11->errors_context); +#endif + + close(x11->drm_fd); + xcb_disconnect(x11->xcb); + free(x11); +} + +static int backend_get_drm_fd(struct wlr_backend *backend) { + struct wlr_x11_backend *x11 = get_x11_backend_from_backend(backend); + return x11->drm_fd; +} + +static const struct wlr_backend_impl backend_impl = { + .start = backend_start, + .destroy = backend_destroy, + .get_drm_fd = backend_get_drm_fd, +}; + +bool wlr_backend_is_x11(struct wlr_backend *backend) { + return backend->impl == &backend_impl; +} + +static void handle_event_loop_destroy(struct wl_listener *listener, void *data) { + struct wlr_x11_backend *x11 = wl_container_of(listener, x11, event_loop_destroy); + backend_destroy(&x11->backend); +} + +static xcb_depth_t *get_depth(xcb_screen_t *screen, uint8_t depth) { + xcb_depth_iterator_t iter = xcb_screen_allowed_depths_iterator(screen); + while (iter.rem > 0) { + if (iter.data->depth == depth) { + return iter.data; + } + xcb_depth_next(&iter); + } + return NULL; +} + +static xcb_visualid_t pick_visualid(xcb_depth_t *depth) { + xcb_visualtype_t *visuals = xcb_depth_visuals(depth); + for (int i = 0; i < xcb_depth_visuals_length(depth); i++) { + if (visuals[i]._class == XCB_VISUAL_CLASS_TRUE_COLOR) { + return visuals[i].visual_id; + } + } + return 0; +} + +static int query_dri3_drm_fd(struct wlr_x11_backend *x11) { + xcb_dri3_open_cookie_t open_cookie = + xcb_dri3_open(x11->xcb, x11->screen->root, 0); + xcb_dri3_open_reply_t *open_reply = + xcb_dri3_open_reply(x11->xcb, open_cookie, NULL); + if (open_reply == NULL) { + wlr_log(WLR_ERROR, "Failed to open DRI3"); + return -1; + } + + int *open_fds = xcb_dri3_open_reply_fds(x11->xcb, open_reply); + if (open_fds == NULL) { + wlr_log(WLR_ERROR, "xcb_dri3_open_reply_fds() failed"); + free(open_reply); + return -1; + } + + assert(open_reply->nfd == 1); + int drm_fd = open_fds[0]; + + free(open_reply); + + int flags = fcntl(drm_fd, F_GETFD); + if (flags < 0) { + wlr_log_errno(WLR_ERROR, "Failed to get DRM FD flags"); + close(drm_fd); + return -1; + } + if (fcntl(drm_fd, F_SETFD, flags | FD_CLOEXEC) < 0) { + wlr_log_errno(WLR_ERROR, "Failed to set DRM FD flags"); + close(drm_fd); + return -1; + } + + if (drmGetNodeTypeFromFd(drm_fd) != DRM_NODE_RENDER) { + char *render_name = drmGetRenderDeviceNameFromFd(drm_fd); + if (render_name == NULL) { + wlr_log(WLR_ERROR, "Failed to get DRM render node name from DRM FD"); + close(drm_fd); + return -1; + } + + close(drm_fd); + drm_fd = open(render_name, O_RDWR | O_CLOEXEC); + if (drm_fd < 0) { + wlr_log_errno(WLR_ERROR, "Failed to open DRM render node '%s'", render_name); + free(render_name); + return -1; + } + + free(render_name); + } + + return drm_fd; +} + +static bool query_dri3_modifiers(struct wlr_x11_backend *x11, + const struct wlr_x11_format *format) { + if (x11->dri3_major_version == 1 && x11->dri3_minor_version < 2) { + return true; // GetSupportedModifiers requires DRI3 1.2 + } + + // Query the root window's supported modifiers, because we only care about + // screen_modifiers for now + xcb_dri3_get_supported_modifiers_cookie_t modifiers_cookie = + xcb_dri3_get_supported_modifiers(x11->xcb, x11->screen->root, + format->depth, format->bpp); + xcb_dri3_get_supported_modifiers_reply_t *modifiers_reply = + xcb_dri3_get_supported_modifiers_reply(x11->xcb, modifiers_cookie, + NULL); + if (!modifiers_reply) { + wlr_log(WLR_ERROR, "Failed to get DMA-BUF modifiers supported by " + "the X11 server for the format 0x%"PRIX32, format->drm); + return false; + } + + // If modifiers aren't supported, DRI3 will return an empty list + const uint64_t *modifiers = + xcb_dri3_get_supported_modifiers_screen_modifiers(modifiers_reply); + int modifiers_len = + xcb_dri3_get_supported_modifiers_screen_modifiers_length(modifiers_reply); + for (int i = 0; i < modifiers_len; i++) { + wlr_drm_format_set_add(&x11->dri3_formats, format->drm, modifiers[i]); + } + + free(modifiers_reply); + return true; +} + +static bool query_formats(struct wlr_x11_backend *x11) { + xcb_depth_iterator_t iter = xcb_screen_allowed_depths_iterator(x11->screen); + while (iter.rem > 0) { + uint8_t depth = iter.data->depth; + + const struct wlr_x11_format *format = x11_format_from_depth(depth); + if (format != NULL) { + if (x11->have_shm) { + wlr_drm_format_set_add(&x11->shm_formats, format->drm, + DRM_FORMAT_MOD_INVALID); + } + + if (x11->have_dri3) { + // X11 always supports implicit modifiers + wlr_drm_format_set_add(&x11->dri3_formats, format->drm, + DRM_FORMAT_MOD_INVALID); + if (!query_dri3_modifiers(x11, format)) { + return false; + } + } + } + + xcb_depth_next(&iter); + } + + return true; +} + +static void x11_get_argb32(struct wlr_x11_backend *x11) { + xcb_render_query_pict_formats_cookie_t cookie = + xcb_render_query_pict_formats(x11->xcb); + xcb_render_query_pict_formats_reply_t *reply = + xcb_render_query_pict_formats_reply(x11->xcb, cookie, NULL); + if (!reply) { + wlr_log(WLR_ERROR, "Did not get any reply from xcb_render_query_pict_formats"); + return; + } + + xcb_render_pictforminfo_t *format = + xcb_render_util_find_standard_format(reply, XCB_PICT_STANDARD_ARGB_32); + + if (format == NULL) { + wlr_log(WLR_DEBUG, "No ARGB_32 render format"); + free(reply); + return; + } + + x11->argb32 = format->id; + free(reply); +} + +struct wlr_backend *wlr_x11_backend_create(struct wl_event_loop *loop, + const char *x11_display) { + wlr_log(WLR_INFO, "Creating X11 backend"); + + struct wlr_x11_backend *x11 = calloc(1, sizeof(*x11)); + if (!x11) { + return NULL; + } + + wlr_backend_init(&x11->backend, &backend_impl); + x11->event_loop = loop; + wl_list_init(&x11->outputs); + + x11->xcb = xcb_connect(x11_display, NULL); + if (xcb_connection_has_error(x11->xcb)) { + wlr_log(WLR_ERROR, "Failed to open xcb connection"); + goto error_x11; + } + + struct { + const char *name; + xcb_intern_atom_cookie_t cookie; + xcb_atom_t *atom; + } atom[] = { + { .name = "WM_PROTOCOLS", .atom = &x11->atoms.wm_protocols }, + { .name = "WM_DELETE_WINDOW", .atom = &x11->atoms.wm_delete_window }, + { .name = "_NET_WM_NAME", .atom = &x11->atoms.net_wm_name }, + { .name = "UTF8_STRING", .atom = &x11->atoms.utf8_string }, + { .name = "_VARIABLE_REFRESH", .atom = &x11->atoms.variable_refresh }, + }; + + for (size_t i = 0; i < sizeof(atom) / sizeof(atom[0]); ++i) { + atom[i].cookie = xcb_intern_atom(x11->xcb, + true, strlen(atom[i].name), atom[i].name); + } + + for (size_t i = 0; i < sizeof(atom) / sizeof(atom[0]); ++i) { + xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply( + x11->xcb, atom[i].cookie, NULL); + + if (reply) { + *atom[i].atom = reply->atom; + free(reply); + } else { + *atom[i].atom = XCB_ATOM_NONE; + } + } + + const xcb_query_extension_reply_t *ext; + + // DRI3 extension + + ext = xcb_get_extension_data(x11->xcb, &xcb_dri3_id); + if (ext && ext->present) { + xcb_dri3_query_version_cookie_t dri3_cookie = + xcb_dri3_query_version(x11->xcb, 1, 2); + xcb_dri3_query_version_reply_t *dri3_reply = + xcb_dri3_query_version_reply(x11->xcb, dri3_cookie, NULL); + if (dri3_reply) { + if (dri3_reply->major_version >= 1) { + x11->have_dri3 = true; + x11->dri3_major_version = dri3_reply->major_version; + x11->dri3_minor_version = dri3_reply->minor_version; + } else { + wlr_log(WLR_INFO, "X11 does not support required DRI3 version " + "(has %"PRIu32".%"PRIu32", want 1.0)", + dri3_reply->major_version, dri3_reply->minor_version); + } + free(dri3_reply); + } else { + wlr_log(WLR_INFO, "X11 does not support required DRi3 version"); + } + } else { + wlr_log(WLR_INFO, "X11 does not support DRI3 extension"); + } + + // SHM extension + + ext = xcb_get_extension_data(x11->xcb, &xcb_shm_id); + if (ext && ext->present) { + xcb_shm_query_version_cookie_t shm_cookie = + xcb_shm_query_version(x11->xcb); + xcb_shm_query_version_reply_t *shm_reply = + xcb_shm_query_version_reply(x11->xcb, shm_cookie, NULL); + if (shm_reply) { + if (shm_reply->major_version >= 1 || shm_reply->minor_version >= 2) { + if (shm_reply->shared_pixmaps) { + x11->have_shm = true; + } else { + wlr_log(WLR_INFO, "X11 does not support shared pixmaps"); + } + } else { + wlr_log(WLR_INFO, "X11 does not support required SHM version " + "(has %"PRIu32".%"PRIu32", want 1.2)", + shm_reply->major_version, shm_reply->minor_version); + } + } else { + wlr_log(WLR_INFO, "X11 does not support required SHM version"); + } + free(shm_reply); + } else { + wlr_log(WLR_INFO, "X11 does not support SHM extension"); + } + + // Present extension + + ext = xcb_get_extension_data(x11->xcb, &xcb_present_id); + if (!ext || !ext->present) { + wlr_log(WLR_ERROR, "X11 does not support Present extension"); + goto error_display; + } + x11->present_opcode = ext->major_opcode; + + xcb_present_query_version_cookie_t present_cookie = + xcb_present_query_version(x11->xcb, 1, 2); + xcb_present_query_version_reply_t *present_reply = + xcb_present_query_version_reply(x11->xcb, present_cookie, NULL); + if (!present_reply) { + wlr_log(WLR_ERROR, "Failed to query Present version"); + goto error_display; + } else if (present_reply->major_version < 1) { + wlr_log(WLR_ERROR, "X11 does not support required Present version " + "(has %"PRIu32".%"PRIu32", want 1.0)", + present_reply->major_version, present_reply->minor_version); + free(present_reply); + goto error_display; + } + free(present_reply); + + // Xfixes extension + + ext = xcb_get_extension_data(x11->xcb, &xcb_xfixes_id); + if (!ext || !ext->present) { + wlr_log(WLR_ERROR, "X11 does not support Xfixes extension"); + goto error_display; + } + + xcb_xfixes_query_version_cookie_t fixes_cookie = + xcb_xfixes_query_version(x11->xcb, 4, 0); + xcb_xfixes_query_version_reply_t *fixes_reply = + xcb_xfixes_query_version_reply(x11->xcb, fixes_cookie, NULL); + if (!fixes_reply) { + wlr_log(WLR_ERROR, "Failed to query Xfixes version"); + goto error_display; + } else if (fixes_reply->major_version < 4) { + wlr_log(WLR_ERROR, "X11 does not support required Xfixes version " + "(has %"PRIu32".%"PRIu32", want 4.0)", + fixes_reply->major_version, fixes_reply->minor_version); + free(fixes_reply); + goto error_display; + } + free(fixes_reply); + + // Xinput extension + + ext = xcb_get_extension_data(x11->xcb, &xcb_input_id); + if (!ext || !ext->present) { + wlr_log(WLR_ERROR, "X11 does not support Xinput extension"); + goto error_display; + } + x11->xinput_opcode = ext->major_opcode; + + xcb_input_xi_query_version_cookie_t xi_cookie = + xcb_input_xi_query_version(x11->xcb, 2, 0); + xcb_input_xi_query_version_reply_t *xi_reply = + xcb_input_xi_query_version_reply(x11->xcb, xi_cookie, NULL); + if (!xi_reply) { + wlr_log(WLR_ERROR, "Failed to query Xinput version"); + goto error_display; + } else if (xi_reply->major_version < 2) { + wlr_log(WLR_ERROR, "X11 does not support required Xinput version " + "(has %"PRIu32".%"PRIu32", want 2.0)", + xi_reply->major_version, xi_reply->minor_version); + free(xi_reply); + goto error_display; + } + free(xi_reply); + + if (x11->have_dri3) { + x11->backend.buffer_caps |= WLR_BUFFER_CAP_DMABUF; + } + if (x11->have_shm) { + x11->backend.buffer_caps |= WLR_BUFFER_CAP_SHM; + } + + int fd = xcb_get_file_descriptor(x11->xcb); + uint32_t events = WL_EVENT_READABLE | WL_EVENT_ERROR | WL_EVENT_HANGUP; + x11->event_source = wl_event_loop_add_fd(loop, fd, events, x11_event, x11); + if (!x11->event_source) { + wlr_log(WLR_ERROR, "Could not create event source"); + goto error_display; + } + wl_event_source_check(x11->event_source); + + x11->screen = xcb_setup_roots_iterator(xcb_get_setup(x11->xcb)).data; + if (!x11->screen) { + wlr_log(WLR_ERROR, "Failed to get X11 screen"); + goto error_event; + } + + x11->depth = get_depth(x11->screen, 24); + if (!x11->depth) { + wlr_log(WLR_ERROR, "Failed to get 24-bit depth for X11 screen"); + goto error_event; + } + + x11->visualid = pick_visualid(x11->depth); + if (!x11->visualid) { + wlr_log(WLR_ERROR, "Failed to pick X11 visual"); + goto error_event; + } + + x11->x11_format = x11_format_from_depth(x11->depth->depth); + if (!x11->x11_format) { + wlr_log(WLR_ERROR, "Unsupported depth %"PRIu8, x11->depth->depth); + goto error_event; + } + + x11->colormap = xcb_generate_id(x11->xcb); + xcb_create_colormap(x11->xcb, XCB_COLORMAP_ALLOC_NONE, x11->colormap, + x11->screen->root, x11->visualid); + + if (!query_formats(x11)) { + wlr_log(WLR_ERROR, "Failed to query supported DRM formats"); + goto error_event; + } + + x11->drm_fd = -1; + if (x11->have_dri3) { + // DRI3 may return a render node (Xwayland) or an authenticated primary + // node (plain Glamor). + x11->drm_fd = query_dri3_drm_fd(x11); + if (x11->drm_fd < 0) { + wlr_log(WLR_ERROR, "Failed to query DRI3 DRM FD"); + wlr_log(WLR_INFO, "Disabling DMA-BUF support"); + x11->have_dri3 = false; + } + } + + // Windows can only display buffers with the depth they were created with + // TODO: look into changing the window's depth at runtime + const struct wlr_drm_format *dri3_format = + wlr_drm_format_set_get(&x11->dri3_formats, x11->x11_format->drm); + if (x11->have_dri3 && dri3_format != NULL) { + wlr_drm_format_set_add(&x11->primary_dri3_formats, + dri3_format->format, DRM_FORMAT_MOD_INVALID); + for (size_t i = 0; i < dri3_format->len; i++) { + wlr_drm_format_set_add(&x11->primary_dri3_formats, + dri3_format->format, dri3_format->modifiers[i]); + } + } + + const struct wlr_drm_format *shm_format = + wlr_drm_format_set_get(&x11->shm_formats, x11->x11_format->drm); + if (x11->have_shm && shm_format != NULL) { + wlr_drm_format_set_add(&x11->primary_shm_formats, + shm_format->format, DRM_FORMAT_MOD_INVALID); + } + +#if HAVE_XCB_ERRORS + if (xcb_errors_context_new(x11->xcb, &x11->errors_context) != 0) { + wlr_log(WLR_ERROR, "Failed to create error context"); + goto error_event; + } +#endif + + wlr_keyboard_init(&x11->keyboard, &x11_keyboard_impl, + x11_keyboard_impl.name); + + x11->event_loop_destroy.notify = handle_event_loop_destroy; + wl_event_loop_add_destroy_listener(loop, &x11->event_loop_destroy); + + // Create an empty pixmap to be used as the cursor. The + // default GC foreground is 0, and that is what it will be + // filled with. + xcb_pixmap_t blank = xcb_generate_id(x11->xcb); + xcb_create_pixmap(x11->xcb, 1, blank, x11->screen->root, 1, 1); + xcb_gcontext_t gc = xcb_generate_id(x11->xcb); + xcb_create_gc(x11->xcb, gc, blank, 0, NULL); + xcb_rectangle_t rect = { .x = 0, .y = 0, .width = 1, .height = 1 }; + xcb_poly_fill_rectangle(x11->xcb, blank, gc, 1, &rect); + + x11->transparent_cursor = xcb_generate_id(x11->xcb); + xcb_create_cursor(x11->xcb, x11->transparent_cursor, blank, blank, + 0, 0, 0, 0, 0, 0, 0, 0); + + xcb_free_gc(x11->xcb, gc); + xcb_free_pixmap(x11->xcb, blank); + + x11_get_argb32(x11); + + return &x11->backend; + +error_event: + wl_event_source_remove(x11->event_source); +error_display: + xcb_disconnect(x11->xcb); +error_x11: + free(x11); + return NULL; +} + +static void handle_x11_error(struct wlr_x11_backend *x11, xcb_value_error_t *ev) { +#if HAVE_XCB_ERRORS + const char *major_name = xcb_errors_get_name_for_major_code( + x11->errors_context, ev->major_opcode); + if (!major_name) { + wlr_log(WLR_DEBUG, "X11 error happened, but could not get major name"); + goto log_raw; + } + + const char *minor_name = xcb_errors_get_name_for_minor_code( + x11->errors_context, ev->major_opcode, ev->minor_opcode); + + const char *extension; + const char *error_name = xcb_errors_get_name_for_error(x11->errors_context, + ev->error_code, &extension); + if (!error_name) { + wlr_log(WLR_DEBUG, "X11 error happened, but could not get error name"); + goto log_raw; + } + + wlr_log(WLR_ERROR, "X11 error: op %s (%s), code %s (%s), " + "sequence %"PRIu16", value %"PRIu32, + major_name, minor_name ? minor_name : "no minor", + error_name, extension ? extension : "no extension", + ev->sequence, ev->bad_value); + + return; + +log_raw: +#endif + + wlr_log(WLR_ERROR, "X11 error: op %"PRIu8":%"PRIu16", code %"PRIu8", " + "sequence %"PRIu16", value %"PRIu32, + ev->major_opcode, ev->minor_opcode, ev->error_code, + ev->sequence, ev->bad_value); +} + +static void handle_x11_unknown_event(struct wlr_x11_backend *x11, + xcb_generic_event_t *ev) { +#if HAVE_XCB_ERRORS + const char *extension; + const char *event_name = xcb_errors_get_name_for_xcb_event( + x11->errors_context, ev, &extension); + if (!event_name) { + wlr_log(WLR_DEBUG, "No name for unhandled event: %u", + ev->response_type); + return; + } + + wlr_log(WLR_DEBUG, "Unhandled X11 event: %s (%u)", event_name, ev->response_type); +#else + wlr_log(WLR_DEBUG, "Unhandled X11 event: %u", ev->response_type); +#endif +} diff --git a/3rdparty/wlroots/backend/x11/input_device.c b/3rdparty/wlroots/backend/x11/input_device.c new file mode 100644 index 0000000000..8246653b73 --- /dev/null +++ b/3rdparty/wlroots/backend/x11/input_device.c @@ -0,0 +1,331 @@ +#include + +#include + +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include "backend/x11.h" + +static void send_key_event(struct wlr_x11_backend *x11, uint32_t key, + enum wl_keyboard_key_state st, xcb_timestamp_t time) { + struct wlr_keyboard_key_event ev = { + .time_msec = time, + .keycode = key, + .state = st, + .update_state = true, + }; + wlr_keyboard_notify_key(&x11->keyboard, &ev); +} + +static void send_button_event(struct wlr_x11_output *output, uint32_t key, + enum wl_pointer_button_state st, xcb_timestamp_t time) { + struct wlr_pointer_button_event ev = { + .pointer = &output->pointer, + .time_msec = time, + .button = key, + .state = st, + }; + wlr_pointer_notify_button(&output->pointer, &ev); + wl_signal_emit_mutable(&output->pointer.events.frame, &output->pointer); +} + +static void send_axis_event(struct wlr_x11_output *output, int32_t delta, + xcb_timestamp_t time) { + struct wlr_pointer_axis_event ev = { + .pointer = &output->pointer, + .time_msec = time, + .source = WL_POINTER_AXIS_SOURCE_WHEEL, + .orientation = WL_POINTER_AXIS_VERTICAL_SCROLL, + // Most mice use a 15 degree angle per scroll click + .delta = delta * 15, + .delta_discrete = delta * WLR_POINTER_AXIS_DISCRETE_STEP, + }; + wl_signal_emit_mutable(&output->pointer.events.axis, &ev); + wl_signal_emit_mutable(&output->pointer.events.frame, &output->pointer); +} + +static void send_pointer_position_event(struct wlr_x11_output *output, + int16_t x, int16_t y, xcb_timestamp_t time) { + struct wlr_pointer_motion_absolute_event ev = { + .pointer = &output->pointer, + .time_msec = time, + .x = (double)x / output->wlr_output.width, + .y = (double)y / output->wlr_output.height, + }; + wl_signal_emit_mutable(&output->pointer.events.motion_absolute, &ev); + wl_signal_emit_mutable(&output->pointer.events.frame, &output->pointer); +} + +static void send_touch_down_event(struct wlr_x11_output *output, + int16_t x, int16_t y, int32_t touch_id, xcb_timestamp_t time) { + struct wlr_touch_down_event ev = { + .touch = &output->touch, + .time_msec = time, + .x = (double)x / output->wlr_output.width, + .y = (double)y / output->wlr_output.height, + .touch_id = touch_id, + }; + wl_signal_emit_mutable(&output->touch.events.down, &ev); + wl_signal_emit_mutable(&output->touch.events.frame, NULL); +} + +static void send_touch_motion_event(struct wlr_x11_output *output, + int16_t x, int16_t y, int32_t touch_id, xcb_timestamp_t time) { + struct wlr_touch_motion_event ev = { + .touch = &output->touch, + .time_msec = time, + .x = (double)x / output->wlr_output.width, + .y = (double)y / output->wlr_output.height, + .touch_id = touch_id, + }; + wl_signal_emit_mutable(&output->touch.events.motion, &ev); + wl_signal_emit_mutable(&output->touch.events.frame, NULL); +} + +static void send_touch_up_event(struct wlr_x11_output *output, + int32_t touch_id, xcb_timestamp_t time) { + struct wlr_touch_up_event ev = { + .touch = &output->touch, + .time_msec = time, + .touch_id = touch_id, + }; + wl_signal_emit_mutable(&output->touch.events.up, &ev); + wl_signal_emit_mutable(&output->touch.events.frame, NULL); +} + +static struct wlr_x11_touchpoint *get_touchpoint_from_x11_touch_id( + struct wlr_x11_output *output, uint32_t id) { + struct wlr_x11_touchpoint *touchpoint; + wl_list_for_each(touchpoint, &output->touchpoints, link) { + if (touchpoint->x11_id == id) { + return touchpoint; + } + } + return NULL; +} + +void handle_x11_xinput_event(struct wlr_x11_backend *x11, + xcb_ge_generic_event_t *event) { + struct wlr_x11_output *output; + + switch (event->event_type) { + case XCB_INPUT_KEY_PRESS: { + xcb_input_key_press_event_t *ev = + (xcb_input_key_press_event_t *)event; + + if (ev->flags & XCB_INPUT_KEY_EVENT_FLAGS_KEY_REPEAT) { + return; + } + + wlr_keyboard_notify_modifiers(&x11->keyboard, ev->mods.base, + ev->mods.latched, ev->mods.locked, ev->group.effective); + send_key_event(x11, ev->detail - 8, WL_KEYBOARD_KEY_STATE_PRESSED, ev->time); + x11->time = ev->time; + break; + } + case XCB_INPUT_KEY_RELEASE: { + xcb_input_key_release_event_t *ev = + (xcb_input_key_release_event_t *)event; + + wlr_keyboard_notify_modifiers(&x11->keyboard, ev->mods.base, + ev->mods.latched, ev->mods.locked, ev->group.effective); + send_key_event(x11, ev->detail - 8, WL_KEYBOARD_KEY_STATE_RELEASED, ev->time); + x11->time = ev->time; + break; + } + case XCB_INPUT_BUTTON_PRESS: { + xcb_input_button_press_event_t *ev = + (xcb_input_button_press_event_t *)event; + + output = get_x11_output_from_window_id(x11, ev->event); + if (!output) { + return; + } + + switch (ev->detail) { + case XCB_BUTTON_INDEX_1: + send_button_event(output, BTN_LEFT, WL_POINTER_BUTTON_STATE_PRESSED, + ev->time); + break; + case XCB_BUTTON_INDEX_2: + send_button_event(output, BTN_MIDDLE, WL_POINTER_BUTTON_STATE_PRESSED, + ev->time); + break; + case XCB_BUTTON_INDEX_3: + send_button_event(output, BTN_RIGHT, WL_POINTER_BUTTON_STATE_PRESSED, + ev->time); + break; + case XCB_BUTTON_INDEX_4: + send_axis_event(output, -1, ev->time); + break; + case XCB_BUTTON_INDEX_5: + send_axis_event(output, 1, ev->time); + break; + } + + x11->time = ev->time; + break; + } + case XCB_INPUT_BUTTON_RELEASE: { + xcb_input_button_release_event_t *ev = + (xcb_input_button_release_event_t *)event; + + output = get_x11_output_from_window_id(x11, ev->event); + if (!output) { + return; + } + + switch (ev->detail) { + case XCB_BUTTON_INDEX_1: + send_button_event(output, BTN_LEFT, WL_POINTER_BUTTON_STATE_RELEASED, + ev->time); + break; + case XCB_BUTTON_INDEX_2: + send_button_event(output, BTN_MIDDLE, WL_POINTER_BUTTON_STATE_RELEASED, + ev->time); + break; + case XCB_BUTTON_INDEX_3: + send_button_event(output, BTN_RIGHT, WL_POINTER_BUTTON_STATE_RELEASED, + ev->time); + break; + } + + x11->time = ev->time; + break; + } + case XCB_INPUT_MOTION: { + xcb_input_motion_event_t *ev = (xcb_input_motion_event_t *)event; + + output = get_x11_output_from_window_id(x11, ev->event); + if (!output) { + return; + } + + send_pointer_position_event(output, ev->event_x >> 16, + ev->event_y >> 16, ev->time); + x11->time = ev->time; + break; + } + case XCB_INPUT_TOUCH_BEGIN: { + xcb_input_touch_begin_event_t *ev = (xcb_input_touch_begin_event_t *)event; + + output = get_x11_output_from_window_id(x11, ev->event); + if (!output) { + return; + } + + int32_t id = 0; + if (!wl_list_empty(&output->touchpoints)) { + struct wlr_x11_touchpoint *last_touchpoint = wl_container_of( + output->touchpoints.next, last_touchpoint, link); + id = last_touchpoint->wayland_id + 1; + } + + struct wlr_x11_touchpoint *touchpoint = calloc(1, sizeof(*touchpoint)); + if (!touchpoint) { + return; + } + + touchpoint->x11_id = ev->detail; + touchpoint->wayland_id = id; + wl_list_init(&touchpoint->link); + wl_list_insert(&output->touchpoints, &touchpoint->link); + + send_touch_down_event(output, ev->event_x >> 16, + ev->event_y >> 16, touchpoint->wayland_id, ev->time); + x11->time = ev->time; + break; + } + case XCB_INPUT_TOUCH_END: { + xcb_input_touch_end_event_t *ev = (xcb_input_touch_end_event_t *)event; + + output = get_x11_output_from_window_id(x11, ev->event); + if (!output) { + return; + } + + struct wlr_x11_touchpoint *touchpoint = get_touchpoint_from_x11_touch_id(output, ev->detail); + if (!touchpoint) { + return; + } + + send_touch_up_event(output, touchpoint->wayland_id, ev->time); + x11->time = ev->time; + + wl_list_remove(&touchpoint->link); + free(touchpoint); + break; + } + case XCB_INPUT_TOUCH_UPDATE: { + xcb_input_touch_update_event_t *ev = (xcb_input_touch_update_event_t *)event; + + output = get_x11_output_from_window_id(x11, ev->event); + if (!output) { + return; + } + + struct wlr_x11_touchpoint *touchpoint = get_touchpoint_from_x11_touch_id(output, ev->detail); + if (!touchpoint) { + return; + } + + send_touch_motion_event(output, ev->event_x >> 16, + ev->event_y >> 16, touchpoint->wayland_id, ev->time); + x11->time = ev->time; + break; + } + } +} + +const struct wlr_keyboard_impl x11_keyboard_impl = { + .name = "x11-keyboard", +}; + +const struct wlr_pointer_impl x11_pointer_impl = { + .name = "x11-pointer", +}; + +const struct wlr_touch_impl x11_touch_impl = { + .name = "x11-touch", +}; + +void update_x11_pointer_position(struct wlr_x11_output *output, + xcb_timestamp_t time) { + struct wlr_x11_backend *x11 = output->x11; + + xcb_query_pointer_cookie_t cookie = + xcb_query_pointer(x11->xcb, output->win); + xcb_query_pointer_reply_t *reply = + xcb_query_pointer_reply(x11->xcb, cookie, NULL); + if (!reply) { + return; + } + + send_pointer_position_event(output, reply->win_x, reply->win_y, time); + + free(reply); +} + +bool wlr_input_device_is_x11(struct wlr_input_device *wlr_dev) { + switch (wlr_dev->type) { + case WLR_INPUT_DEVICE_KEYBOARD: + return wlr_keyboard_from_input_device(wlr_dev)->impl == &x11_keyboard_impl; + case WLR_INPUT_DEVICE_POINTER: + return wlr_pointer_from_input_device(wlr_dev)->impl == &x11_pointer_impl; + case WLR_INPUT_DEVICE_TOUCH: + return wlr_touch_from_input_device(wlr_dev)->impl == &x11_touch_impl; + default: + return false; + } +} diff --git a/3rdparty/wlroots/backend/x11/meson.build b/3rdparty/wlroots/backend/x11/meson.build new file mode 100644 index 0000000000..97b6d540bd --- /dev/null +++ b/3rdparty/wlroots/backend/x11/meson.build @@ -0,0 +1,36 @@ +x11_libs = [] +x11_required = [ + 'xcb', + 'xcb-dri3', + 'xcb-present', + 'xcb-render', + 'xcb-renderutil', + 'xcb-shm', + 'xcb-xfixes', + 'xcb-xinput', +] + +msg = ['Required for X11 backend support.'] +if 'x11' in backends + msg += 'Install "@0@" or disable the X11 backend.' +endif + +foreach lib : x11_required + dep = dependency(lib, + required: 'x11' in backends, + not_found_message: '\n'.join(msg).format(lib), + ) + if not dep.found() + subdir_done() + endif + + x11_libs += dep +endforeach + +wlr_files += files( + 'backend.c', + 'input_device.c', + 'output.c', +) +wlr_deps += x11_libs +features += { 'x11-backend': true } diff --git a/3rdparty/wlroots/backend/x11/output.c b/3rdparty/wlroots/backend/x11/output.c new file mode 100644 index 0000000000..51a9c14413 --- /dev/null +++ b/3rdparty/wlroots/backend/x11/output.c @@ -0,0 +1,804 @@ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "backend/x11.h" +#include "render/pixel_format.h" +#include "util/time.h" +#include "types/wlr_buffer.h" +#include "types/wlr_output.h" + +static const uint32_t SUPPORTED_OUTPUT_STATE = + WLR_OUTPUT_STATE_BACKEND_OPTIONAL | + WLR_OUTPUT_STATE_BUFFER | + WLR_OUTPUT_STATE_ENABLED | + WLR_OUTPUT_STATE_MODE | + WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED; + +static size_t last_output_num = 0; + +static void parse_xcb_setup(struct wlr_output *output, + xcb_connection_t *xcb) { + const xcb_setup_t *xcb_setup = xcb_get_setup(xcb); + + output->make = calloc(1, xcb_setup_vendor_length(xcb_setup) + 1); + if (output->make == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return; + } + memcpy(output->make, xcb_setup_vendor(xcb_setup), + xcb_setup_vendor_length(xcb_setup)); + + char model[64]; + snprintf(model, sizeof(model), "%"PRIu16".%"PRIu16, + xcb_setup->protocol_major_version, + xcb_setup->protocol_minor_version); + output->model = strdup(model); +} + +static struct wlr_x11_output *get_x11_output_from_output( + struct wlr_output *wlr_output) { + assert(wlr_output_is_x11(wlr_output)); + struct wlr_x11_output *output = wl_container_of(wlr_output, output, wlr_output); + return output; +} + +static bool output_set_custom_mode(struct wlr_output *wlr_output, + int32_t width, int32_t height, int32_t refresh) { + struct wlr_x11_output *output = get_x11_output_from_output(wlr_output); + struct wlr_x11_backend *x11 = output->x11; + + if (width == output->win_width && height == output->win_height) { + return true; + } + + const uint32_t values[] = { width, height }; + xcb_void_cookie_t cookie = xcb_configure_window_checked( + x11->xcb, output->win, + XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT, values); + + xcb_generic_error_t *error; + if ((error = xcb_request_check(x11->xcb, cookie))) { + wlr_log(WLR_ERROR, "Could not set window size to %dx%d\n", + width, height); + free(error); + return false; + } + + output->win_width = width; + output->win_height = height; + + // Move the pointer to its new location + update_x11_pointer_position(output, output->x11->time); + + return true; +} + +static void destroy_x11_buffer(struct wlr_x11_buffer *buffer); + +static void output_destroy(struct wlr_output *wlr_output) { + struct wlr_x11_output *output = get_x11_output_from_output(wlr_output); + struct wlr_x11_backend *x11 = output->x11; + + wlr_output_finish(wlr_output); + + pixman_region32_fini(&output->exposed); + + wlr_pointer_finish(&output->pointer); + wlr_touch_finish(&output->touch); + + struct wlr_x11_buffer *buffer, *buffer_tmp; + wl_list_for_each_safe(buffer, buffer_tmp, &output->buffers, link) { + destroy_x11_buffer(buffer); + } + + wl_list_remove(&output->link); + + if (output->cursor.pic != XCB_NONE) { + xcb_render_free_picture(x11->xcb, output->cursor.pic); + } + + // A zero event mask deletes the event context + xcb_present_select_input(x11->xcb, output->present_event_id, output->win, 0); + xcb_destroy_window(x11->xcb, output->win); + xcb_flush(x11->xcb); + free(output); +} + +static bool output_test(struct wlr_output *wlr_output, + const struct wlr_output_state *state) { + struct wlr_x11_output *output = get_x11_output_from_output(wlr_output); + struct wlr_x11_backend *x11 = output->x11; + + uint32_t unsupported = state->committed & ~SUPPORTED_OUTPUT_STATE; + if (unsupported != 0) { + wlr_log(WLR_DEBUG, "Unsupported output state fields: 0x%"PRIx32, + unsupported); + return false; + } + + if (state->committed & WLR_OUTPUT_STATE_BUFFER) { + // If the size doesn't match, reject buffer (scaling is not supported) + int pending_width, pending_height; + output_pending_resolution(wlr_output, state, + &pending_width, &pending_height); + if (state->buffer->width != pending_width || + state->buffer->height != pending_height) { + wlr_log(WLR_DEBUG, "Primary buffer size mismatch"); + return false; + } + // Source crop is not supported + struct wlr_fbox src_box; + output_state_get_buffer_src_box(state, &src_box); + if (src_box.x != 0.0 || src_box.y != 0.0 || + src_box.width != (double)state->buffer->width || + src_box.height != (double)state->buffer->height) { + wlr_log(WLR_DEBUG, "Source crop not supported in X11 output"); + return false; + } + } + + // All we can do to influence adaptive sync on the X11 backend is set the + // _VARIABLE_REFRESH window property like mesa automatically does. We don't + // have any control beyond that, so we set the state to enabled on creating + // the output and never allow changing it (just like the Wayland backend). + assert(wlr_output->adaptive_sync_status == WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED); + if (state->committed & WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED) { + if (!state->adaptive_sync_enabled) { + wlr_log(WLR_DEBUG, "Disabling adaptive sync is not supported"); + return false; + } + } + + if (state->committed & WLR_OUTPUT_STATE_BUFFER) { + struct wlr_buffer *buffer = state->buffer; + uint32_t format = buffer_get_drm_format(buffer); + if (format != x11->x11_format->drm) { + wlr_log(WLR_DEBUG, "Unsupported buffer format"); + return false; + } + struct wlr_shm_attributes shm; + if (wlr_buffer_get_shm(buffer, &shm)) { + const struct wlr_pixel_format_info *info = drm_get_pixel_format_info(format); + if (shm.stride != pixel_format_info_min_stride(info, shm.width)) { + // xcb_shm_create_pixmap() does not allow arbitrary strides. + wlr_log(WLR_DEBUG, "Unsupported shm buffer stride"); + return false; + } + } + } + + if (state->committed & WLR_OUTPUT_STATE_MODE) { + assert(state->mode_type == WLR_OUTPUT_STATE_MODE_CUSTOM); + + if (state->custom_mode.refresh != 0) { + wlr_log(WLR_DEBUG, "Refresh rates are not supported"); + return false; + } + } + + return true; +} + +static void destroy_x11_buffer(struct wlr_x11_buffer *buffer) { + if (!buffer) { + return; + } + wl_list_remove(&buffer->buffer_destroy.link); + wl_list_remove(&buffer->link); + xcb_free_pixmap(buffer->x11->xcb, buffer->pixmap); + for (size_t i = 0; i < buffer->n_busy; i++) { + wlr_buffer_unlock(buffer->buffer); + } + free(buffer); +} + +static void buffer_handle_buffer_destroy(struct wl_listener *listener, + void *data) { + struct wlr_x11_buffer *buffer = + wl_container_of(listener, buffer, buffer_destroy); + destroy_x11_buffer(buffer); +} + +static xcb_pixmap_t import_dmabuf(struct wlr_x11_output *output, + struct wlr_dmabuf_attributes *dmabuf) { + struct wlr_x11_backend *x11 = output->x11; + + if (dmabuf->format != x11->x11_format->drm) { + // The pixmap's depth must match the window's depth, otherwise Present + // will throw a Match error + return XCB_PIXMAP_NONE; + } + + // xcb closes the FDs after sending them, so we need to dup them here + struct wlr_dmabuf_attributes dup_attrs = {0}; + if (!wlr_dmabuf_attributes_copy(&dup_attrs, dmabuf)) { + return XCB_PIXMAP_NONE; + } + + const struct wlr_x11_format *x11_fmt = x11->x11_format; + xcb_pixmap_t pixmap = xcb_generate_id(x11->xcb); + + if (x11->dri3_major_version > 1 || x11->dri3_minor_version >= 2) { + if (dmabuf->n_planes > 4) { + wlr_dmabuf_attributes_finish(&dup_attrs); + return XCB_PIXMAP_NONE; + } + xcb_dri3_pixmap_from_buffers(x11->xcb, pixmap, output->win, + dmabuf->n_planes, dmabuf->width, dmabuf->height, dmabuf->stride[0], + dmabuf->offset[0], dmabuf->stride[1], dmabuf->offset[1], + dmabuf->stride[2], dmabuf->offset[2], dmabuf->stride[3], + dmabuf->offset[3], x11_fmt->depth, x11_fmt->bpp, dmabuf->modifier, + dup_attrs.fd); + } else { + // PixmapFromBuffers requires DRI3 1.2 + if (dmabuf->n_planes != 1 + || dmabuf->modifier != DRM_FORMAT_MOD_INVALID) { + wlr_dmabuf_attributes_finish(&dup_attrs); + return XCB_PIXMAP_NONE; + } + xcb_dri3_pixmap_from_buffer(x11->xcb, pixmap, output->win, + dmabuf->height * dmabuf->stride[0], dmabuf->width, dmabuf->height, + dmabuf->stride[0], x11_fmt->depth, x11_fmt->bpp, dup_attrs.fd[0]); + } + + return pixmap; +} + +static xcb_pixmap_t import_shm(struct wlr_x11_output *output, + struct wlr_shm_attributes *shm) { + struct wlr_x11_backend *x11 = output->x11; + + if (shm->format != x11->x11_format->drm) { + // The pixmap's depth must match the window's depth, otherwise Present + // will throw a Match error + return XCB_PIXMAP_NONE; + } + + const struct wlr_pixel_format_info *info = drm_get_pixel_format_info(shm->format); + if (shm->stride != pixel_format_info_min_stride(info, shm->width)) { + // xcb_shm_create_pixmap() does not allow arbitrary strides. + return XCB_PIXMAP_NONE; + } + + // xcb closes the FD after sending it + int fd = fcntl(shm->fd, F_DUPFD_CLOEXEC, 0); + if (fd < 0) { + wlr_log_errno(WLR_ERROR, "fcntl(F_DUPFD_CLOEXEC) failed"); + return XCB_PIXMAP_NONE; + } + + xcb_shm_seg_t seg = xcb_generate_id(x11->xcb); + xcb_shm_attach_fd(x11->xcb, seg, fd, false); + + xcb_pixmap_t pixmap = xcb_generate_id(x11->xcb); + xcb_shm_create_pixmap(x11->xcb, pixmap, output->win, shm->width, + shm->height, x11->x11_format->depth, seg, shm->offset); + + xcb_shm_detach(x11->xcb, seg); + + return pixmap; +} + +static struct wlr_x11_buffer *create_x11_buffer(struct wlr_x11_output *output, + struct wlr_buffer *wlr_buffer) { + struct wlr_x11_backend *x11 = output->x11; + xcb_pixmap_t pixmap = XCB_PIXMAP_NONE; + + struct wlr_dmabuf_attributes dmabuf_attrs; + struct wlr_shm_attributes shm_attrs; + if (wlr_buffer_get_dmabuf(wlr_buffer, &dmabuf_attrs)) { + pixmap = import_dmabuf(output, &dmabuf_attrs); + } else if (wlr_buffer_get_shm(wlr_buffer, &shm_attrs)) { + pixmap = import_shm(output, &shm_attrs); + } + + if (pixmap == XCB_PIXMAP_NONE) { + return NULL; + } + + struct wlr_x11_buffer *buffer = calloc(1, sizeof(*buffer)); + if (!buffer) { + xcb_free_pixmap(x11->xcb, pixmap); + return NULL; + } + buffer->buffer = wlr_buffer_lock(wlr_buffer); + buffer->n_busy = 1; + buffer->pixmap = pixmap; + buffer->x11 = x11; + wl_list_insert(&output->buffers, &buffer->link); + + buffer->buffer_destroy.notify = buffer_handle_buffer_destroy; + wl_signal_add(&wlr_buffer->events.destroy, &buffer->buffer_destroy); + + return buffer; +} + +static struct wlr_x11_buffer *get_or_create_x11_buffer( + struct wlr_x11_output *output, struct wlr_buffer *wlr_buffer) { + struct wlr_x11_buffer *buffer; + wl_list_for_each(buffer, &output->buffers, link) { + if (buffer->buffer == wlr_buffer) { + wlr_buffer_lock(buffer->buffer); + buffer->n_busy++; + return buffer; + } + } + + return create_x11_buffer(output, wlr_buffer); +} + +static bool output_commit_buffer(struct wlr_x11_output *output, + const struct wlr_output_state *state) { + struct wlr_x11_backend *x11 = output->x11; + + struct wlr_buffer *buffer = state->buffer; + struct wlr_x11_buffer *x11_buffer = + get_or_create_x11_buffer(output, buffer); + if (!x11_buffer) { + goto error; + } + + xcb_xfixes_region_t region = XCB_NONE; + if (state->committed & WLR_OUTPUT_STATE_DAMAGE) { + pixman_region32_union(&output->exposed, &output->exposed, &state->damage); + + int rects_len = 0; + const pixman_box32_t *rects = pixman_region32_rectangles(&output->exposed, &rects_len); + + xcb_rectangle_t *xcb_rects = calloc(rects_len, sizeof(xcb_rectangle_t)); + if (!xcb_rects) { + goto error; + } + + for (int i = 0; i < rects_len; i++) { + const pixman_box32_t *box = &rects[i]; + xcb_rects[i] = (struct xcb_rectangle_t){ + .x = box->x1, + .y = box->y1, + .width = box->x2 - box->x1, + .height = box->y2 - box->y1, + }; + } + + region = xcb_generate_id(x11->xcb); + xcb_xfixes_create_region(x11->xcb, region, rects_len, xcb_rects); + + free(xcb_rects); + } + + pixman_region32_clear(&output->exposed); + + uint32_t serial = output->wlr_output.commit_seq; + uint32_t options = 0; + uint64_t target_msc = output->last_msc ? output->last_msc + 1 : 0; + xcb_present_pixmap(x11->xcb, output->win, x11_buffer->pixmap, serial, + 0, region, 0, 0, XCB_NONE, XCB_NONE, XCB_NONE, options, target_msc, + 0, 0, 0, NULL); + + if (region != XCB_NONE) { + xcb_xfixes_destroy_region(x11->xcb, region); + } + + return true; + +error: + destroy_x11_buffer(x11_buffer); + return false; +} + +static bool output_commit(struct wlr_output *wlr_output, + const struct wlr_output_state *state) { + struct wlr_x11_output *output = get_x11_output_from_output(wlr_output); + struct wlr_x11_backend *x11 = output->x11; + + if (!output_test(wlr_output, state)) { + return false; + } + + if (state->committed & WLR_OUTPUT_STATE_ENABLED) { + if (state->enabled) { + xcb_map_window(x11->xcb, output->win); + } else { + xcb_unmap_window(x11->xcb, output->win); + } + } + + if (state->committed & WLR_OUTPUT_STATE_MODE) { + if (!output_set_custom_mode(wlr_output, + state->custom_mode.width, + state->custom_mode.height, + state->custom_mode.refresh)) { + return false; + } + } + + if (state->committed & WLR_OUTPUT_STATE_BUFFER) { + if (!output_commit_buffer(output, state)) { + return false; + } + } else if (output_pending_enabled(wlr_output, state)) { + uint32_t serial = output->wlr_output.commit_seq; + uint64_t target_msc = output->last_msc ? output->last_msc + 1 : 0; + xcb_present_notify_msc(x11->xcb, output->win, serial, target_msc, 0, 0); + } + + xcb_flush(x11->xcb); + + return true; +} + +static void update_x11_output_cursor(struct wlr_x11_output *output, + int32_t hotspot_x, int32_t hotspot_y) { + struct wlr_x11_backend *x11 = output->x11; + + xcb_cursor_t cursor = x11->transparent_cursor; + + if (output->cursor.pic != XCB_NONE) { + cursor = xcb_generate_id(x11->xcb); + xcb_render_create_cursor(x11->xcb, cursor, output->cursor.pic, + hotspot_x, hotspot_y); + } + + uint32_t values[] = {cursor}; + xcb_change_window_attributes(x11->xcb, output->win, + XCB_CW_CURSOR, values); + xcb_flush(x11->xcb); + + if (cursor != x11->transparent_cursor) { + xcb_free_cursor(x11->xcb, cursor); + } +} + +static bool output_cursor_to_picture(struct wlr_x11_output *output, + struct wlr_buffer *buffer) { + struct wlr_x11_backend *x11 = output->x11; + struct wlr_renderer *renderer = output->wlr_output.renderer; + + if (output->cursor.pic != XCB_NONE) { + xcb_render_free_picture(x11->xcb, output->cursor.pic); + } + output->cursor.pic = XCB_NONE; + + if (buffer == NULL) { + return true; + } + + struct wlr_texture *texture = wlr_texture_from_buffer(renderer, buffer); + if (!texture) { + return false; + } + + int depth = 32; + int stride = texture->width * 4; + uint8_t *data = malloc(texture->height * stride); + if (data == NULL) { + wlr_texture_destroy(texture); + return false; + } + + bool result = wlr_texture_read_pixels(texture, &(struct wlr_texture_read_pixels_options) { + .format = DRM_FORMAT_ARGB8888, + .stride = stride, + .data = data, + }); + + wlr_texture_destroy(texture); + + if (!result) { + free(data); + return false; + } + + xcb_pixmap_t pix = xcb_generate_id(x11->xcb); + xcb_create_pixmap(x11->xcb, depth, pix, output->win, + buffer->width, buffer->height); + + output->cursor.pic = xcb_generate_id(x11->xcb); + xcb_render_create_picture(x11->xcb, output->cursor.pic, + pix, x11->argb32, 0, 0); + + xcb_gcontext_t gc = xcb_generate_id(x11->xcb); + xcb_create_gc(x11->xcb, gc, pix, 0, NULL); + + xcb_put_image(x11->xcb, XCB_IMAGE_FORMAT_Z_PIXMAP, + pix, gc, buffer->width, buffer->height, 0, 0, 0, depth, + stride * buffer->height * sizeof(uint8_t), data); + free(data); + xcb_free_gc(x11->xcb, gc); + xcb_free_pixmap(x11->xcb, pix); + + return true; +} + +static bool output_set_cursor(struct wlr_output *wlr_output, + struct wlr_buffer *buffer, int32_t hotspot_x, int32_t hotspot_y) { + struct wlr_x11_output *output = get_x11_output_from_output(wlr_output); + struct wlr_x11_backend *x11 = output->x11; + + if (x11->argb32 == XCB_NONE) { + return false; + } + + if (buffer != NULL) { + if (hotspot_x < 0) { + hotspot_x = 0; + } + if (hotspot_x > buffer->width) { + hotspot_x = buffer->width; + } + if (hotspot_y < 0) { + hotspot_y = 0; + } + if (hotspot_y > buffer->height) { + hotspot_y = buffer->height; + } + } + + bool success = output_cursor_to_picture(output, buffer); + + update_x11_output_cursor(output, hotspot_x, hotspot_y); + + return success; +} + +static bool output_move_cursor(struct wlr_output *_output, int x, int y) { + // TODO: only return true if x == current x and y == current y + return true; +} + +static const struct wlr_drm_format_set *output_get_primary_formats( + struct wlr_output *wlr_output, uint32_t buffer_caps) { + struct wlr_x11_output *output = get_x11_output_from_output(wlr_output); + struct wlr_x11_backend *x11 = output->x11; + + if (x11->have_dri3 && (buffer_caps & WLR_BUFFER_CAP_DMABUF)) { + return &output->x11->primary_dri3_formats; + } else if (x11->have_shm && (buffer_caps & WLR_BUFFER_CAP_SHM)) { + return &output->x11->primary_shm_formats; + } + return NULL; +} + +static const struct wlr_output_impl output_impl = { + .destroy = output_destroy, + .test = output_test, + .commit = output_commit, + .set_cursor = output_set_cursor, + .move_cursor = output_move_cursor, + .get_primary_formats = output_get_primary_formats, +}; + +struct wlr_output *wlr_x11_output_create(struct wlr_backend *backend) { + struct wlr_x11_backend *x11 = get_x11_backend_from_backend(backend); + + if (!x11->started) { + ++x11->requested_outputs; + return NULL; + } + + struct wlr_x11_output *output = calloc(1, sizeof(*output)); + if (output == NULL) { + return NULL; + } + output->x11 = x11; + wl_list_init(&output->buffers); + pixman_region32_init(&output->exposed); + + struct wlr_output *wlr_output = &output->wlr_output; + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_custom_mode(&state, 1024, 768, 0); + + wlr_output_init(wlr_output, &x11->backend, &output_impl, x11->event_loop, &state); + wlr_output_state_finish(&state); + + size_t output_num = ++last_output_num; + + char name[64]; + snprintf(name, sizeof(name), "X11-%zu", output_num); + wlr_output_set_name(wlr_output, name); + + parse_xcb_setup(wlr_output, x11->xcb); + + char description[128]; + snprintf(description, sizeof(description), "X11 output %zu", output_num); + wlr_output_set_description(wlr_output, description); + + // The X11 protocol requires us to set a colormap and border pixel if the + // depth doesn't match the root window's + uint32_t mask = XCB_CW_BORDER_PIXEL | XCB_CW_EVENT_MASK | + XCB_CW_COLORMAP | XCB_CW_CURSOR; + uint32_t values[] = { + 0, + XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_STRUCTURE_NOTIFY, + x11->colormap, + x11->transparent_cursor, + }; + output->win = xcb_generate_id(x11->xcb); + xcb_create_window(x11->xcb, x11->depth->depth, output->win, + x11->screen->root, 0, 0, wlr_output->width, wlr_output->height, 0, + XCB_WINDOW_CLASS_INPUT_OUTPUT, x11->visualid, mask, values); + + output->win_width = wlr_output->width; + output->win_height = wlr_output->height; + + struct { + xcb_input_event_mask_t head; + xcb_input_xi_event_mask_t mask; + } xinput_mask = { + .head = { .deviceid = XCB_INPUT_DEVICE_ALL_MASTER, .mask_len = 1 }, + .mask = XCB_INPUT_XI_EVENT_MASK_KEY_PRESS | + XCB_INPUT_XI_EVENT_MASK_KEY_RELEASE | + XCB_INPUT_XI_EVENT_MASK_BUTTON_PRESS | + XCB_INPUT_XI_EVENT_MASK_BUTTON_RELEASE | + XCB_INPUT_XI_EVENT_MASK_MOTION | + XCB_INPUT_XI_EVENT_MASK_TOUCH_BEGIN | + XCB_INPUT_XI_EVENT_MASK_TOUCH_END | + XCB_INPUT_XI_EVENT_MASK_TOUCH_UPDATE, + }; + xcb_input_xi_select_events(x11->xcb, output->win, 1, &xinput_mask.head); + + uint32_t present_mask = XCB_PRESENT_EVENT_MASK_IDLE_NOTIFY | + XCB_PRESENT_EVENT_MASK_COMPLETE_NOTIFY; + output->present_event_id = xcb_generate_id(x11->xcb); + xcb_present_select_input(x11->xcb, output->present_event_id, output->win, + present_mask); + + xcb_change_property(x11->xcb, XCB_PROP_MODE_REPLACE, output->win, + x11->atoms.wm_protocols, XCB_ATOM_ATOM, 32, 1, + &x11->atoms.wm_delete_window); + + uint32_t enabled = 1; + xcb_change_property(x11->xcb, XCB_PROP_MODE_REPLACE, output->win, + x11->atoms.variable_refresh, XCB_ATOM_CARDINAL, 32, 1, + &enabled); + wlr_output->adaptive_sync_status = WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED; + + wlr_x11_output_set_title(wlr_output, NULL); + + xcb_flush(x11->xcb); + + wl_list_insert(&x11->outputs, &output->link); + + wlr_pointer_init(&output->pointer, &x11_pointer_impl, "x11-pointer"); + output->pointer.output_name = strdup(wlr_output->name); + + wlr_touch_init(&output->touch, &x11_touch_impl, "x11-touch"); + output->touch.output_name = strdup(wlr_output->name); + wl_list_init(&output->touchpoints); + + wl_signal_emit_mutable(&x11->backend.events.new_output, wlr_output); + wl_signal_emit_mutable(&x11->backend.events.new_input, &output->pointer.base); + wl_signal_emit_mutable(&x11->backend.events.new_input, &output->touch.base); + + return wlr_output; +} + +void handle_x11_configure_notify(struct wlr_x11_output *output, + xcb_configure_notify_event_t *ev) { + if (ev->width == 0 || ev->height == 0) { + wlr_log(WLR_DEBUG, + "Ignoring X11 configure event for height=%d, width=%d", + ev->width, ev->height); + return; + } + + output->win_width = ev->width; + output->win_height = ev->height; + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_custom_mode(&state, ev->width, ev->height, 0); + wlr_output_send_request_state(&output->wlr_output, &state); + wlr_output_state_finish(&state); +} + +bool wlr_output_is_x11(struct wlr_output *wlr_output) { + return wlr_output->impl == &output_impl; +} + +void wlr_x11_output_set_title(struct wlr_output *output, const char *title) { + struct wlr_x11_output *x11_output = get_x11_output_from_output(output); + + char wl_title[32]; + if (title == NULL) { + if (snprintf(wl_title, sizeof(wl_title), "wlroots - %s", output->name) <= 0) { + return; + } + title = wl_title; + } + + xcb_change_property(x11_output->x11->xcb, XCB_PROP_MODE_REPLACE, x11_output->win, + x11_output->x11->atoms.net_wm_name, x11_output->x11->atoms.utf8_string, 8, + strlen(title), title); +} + +static struct wlr_x11_buffer *get_x11_buffer(struct wlr_x11_output *output, + xcb_pixmap_t pixmap) { + struct wlr_x11_buffer *buffer; + wl_list_for_each(buffer, &output->buffers, link) { + if (buffer->pixmap == pixmap) { + return buffer; + } + } + return NULL; +} + +void handle_x11_present_event(struct wlr_x11_backend *x11, + xcb_ge_generic_event_t *event) { + struct wlr_x11_output *output; + + switch (event->event_type) { + case XCB_PRESENT_EVENT_IDLE_NOTIFY:; + xcb_present_idle_notify_event_t *idle_notify = + (xcb_present_idle_notify_event_t *)event; + + output = get_x11_output_from_window_id(x11, idle_notify->window); + if (!output) { + wlr_log(WLR_DEBUG, "Got PresentIdleNotify event for unknown window"); + return; + } + + struct wlr_x11_buffer *buffer = + get_x11_buffer(output, idle_notify->pixmap); + if (!buffer) { + wlr_log(WLR_DEBUG, "Got PresentIdleNotify event for unknown buffer"); + return; + } + + assert(buffer->n_busy > 0); + buffer->n_busy--; + wlr_buffer_unlock(buffer->buffer); // may destroy buffer + break; + case XCB_PRESENT_COMPLETE_NOTIFY:; + xcb_present_complete_notify_event_t *complete_notify = + (xcb_present_complete_notify_event_t *)event; + + output = get_x11_output_from_window_id(x11, complete_notify->window); + if (!output) { + wlr_log(WLR_DEBUG, "Got PresentCompleteNotify event for unknown window"); + return; + } + + output->last_msc = complete_notify->msc; + + uint32_t flags = 0; + if (complete_notify->mode == XCB_PRESENT_COMPLETE_MODE_FLIP) { + flags |= WLR_OUTPUT_PRESENT_ZERO_COPY; + } + + bool presented = complete_notify->mode != XCB_PRESENT_COMPLETE_MODE_SKIP; + struct wlr_output_event_present present_event = { + .output = &output->wlr_output, + .commit_seq = complete_notify->serial, + .presented = presented, + .seq = complete_notify->msc, + .flags = flags, + }; + timespec_from_nsec(&present_event.when, complete_notify->ust * 1000); + wlr_output_send_present(&output->wlr_output, &present_event); + + wlr_output_send_frame(&output->wlr_output); + break; + default: + wlr_log(WLR_DEBUG, "Unhandled Present event %"PRIu16, event->event_type); + } +} diff --git a/3rdparty/wlroots/docs/architecture.md b/3rdparty/wlroots/docs/architecture.md new file mode 100644 index 0000000000..7ab9212bf1 --- /dev/null +++ b/3rdparty/wlroots/docs/architecture.md @@ -0,0 +1,86 @@ +# Architecture + +This document describes the high-level design of wlroots. wlroots is modular: +each module can be used mostly independently from the rest of wlroots. For +instance, some wlroots-based compositors only use its backends, some only use +its protocol implementations. + +## Backends + +Backends are responsible for exposing input devices and output devices. +wlroots provides DRM and libinput backends to directly drive physical +devices, Wayland and X11 backends to run nested inside another compositor, +and a headless backend. A special "multi" backend is used to combine together +multiple backends, for instance DRM and libinput. Compositors can also +implement their own custom backends if they have special needs. + +Input devices such as pointers, keyboards, touch screens, tablets, switches +are supported. They emit input events (e.g. a keyboard key is pressed) which +compositors can handle and forward to Wayland clients. + +Output devices are tasked with presenting buffers to the user. They also +provide feedback, for instance presentation timestamps. Some backends support +more advanced functionality, such as displaying multiple buffers (e.g. for the +cursor image) or basic 2D transformations (e.g. rotation, clipping, scaling). + +## Renderers + +Renderers provide utilities to import buffers submitted by Wayland clients, +and a basic 2D drawing API suitable for simple compositors. wlroots provides +renderer implementations based on OpenGL ES 2, Vulkan and Pixman. Just like +backends, compositors can implement their own renderers, or use the graphics +APIs directly. + +To draw an image onto a buffer, compositors will first need to create a +texture, representing a source of pixels the renderer can sample from. This can +be done either by uploading pixels from CPU memory, or by importing already +existing GPU memory via DMA-BUFs. Compositors can then create a render pass +and submit drawing operations. Once they are done drawing, compositors can +submit the rendered buffer to an output. + +## Protocol implementations + +A number of Wayland interface implementations are provided. + +### Plumbing protocols + +wlroots ships unopinionated implementations of core plumbing interfaces, for +instance: + +- `wl_compositor` and `wl_surface` +- `wl_seat` and all input-related interfaces +- Buffer factories such as `wl_shm` and linux-dmabuf +- Additional protocols such as viewporter and presentation-time + +### Shells + +Shells give a meaning to surfaces. There are many kinds of surfaces: +application windows, tooltips, right-click menus, desktop panels, wallpapers, +lock screens, on-screen keyboards, and so on. Each of these use-cases is +fulfilled with a shell. wlroots supports xdg-shell for regular windows and +popups, Xwayland for interoperability with X11 applications, layer-shell for +desktop UI elements, and more. + +### Other protocols + +Many other protocol implementations are included, for instance: + +- xdg-activation for raising application windows +- idle-inhibit for preventing the screen from blanking when the user is + watching a video +- ext-idle-notify for notifying when the user is idle + +## Helpers + +wlroots provides additional helpers which can make it easier for compositors to +tie everything together: + +- `wlr_output_layout` organises output devices in the physical space +- `wlr_cursor` stores the current position and image of the cursor +- `wlr_scene` provides a declarative way to display surfaces + +## tinywl + +tinywl is a minimal wlroots compositor. It implements basic stacking window +management and only supports xdg-shell. It's extensively commented and is a +good learning resource for developers new to wlroots. diff --git a/3rdparty/wlroots/docs/env_vars.md b/3rdparty/wlroots/docs/env_vars.md new file mode 100644 index 0000000000..59c8f078f4 --- /dev/null +++ b/3rdparty/wlroots/docs/env_vars.md @@ -0,0 +1,78 @@ +wlroots reads these environment variables + +# wlroots specific + +* *WLR_BACKENDS*: comma-separated list of backends to use (available backends: + libinput, drm, wayland, x11, headless) +* *WLR_NO_HARDWARE_CURSORS*: set to 1 to use software cursors instead of + hardware cursors +* *WLR_XWAYLAND*: specifies the path to an Xwayland binary to be used (instead + of following shell search semantics for "Xwayland") +* *WLR_RENDERER*: forces the creation of a specified renderer (available + renderers: gles2, pixman, vulkan) +* *WLR_RENDER_DRM_DEVICE*: specifies the DRM node to use for + hardware-accelerated renderers. +* *WLR_RENDER_NO_EXPLICIT_SYNC*: set to 1 to disable explicit synchronization + support in renderers. +* *WLR_RENDERER_FORCE_SOFTWARE*: set to 1 to force software rendering for GLES2 + and Vulkan +* *WLR_EGL_NO_MODIFIERS*: set to 1 to disable format modifiers in EGL, this can + be used to understand and work around driver bugs. + +## DRM backend + +* *WLR_DRM_DEVICES*: specifies the DRM devices (as a colon separated list) + instead of auto probing them. The first existing device in this list is + considered the primary DRM device. +* *WLR_DRM_NO_ATOMIC*: set to 1 to use legacy DRM interface instead of atomic + mode setting +* *WLR_DRM_NO_MODIFIERS*: set to 1 to always allocate planes without modifiers, + this can fix certain modeset failures because of bandwidth restrictions. +* *WLR_DRM_FORCE_LIBLIFTOFF*: set to 1 to force libliftoff (by default, + libliftoff is never used) + +## Headless backend + +* *WLR_HEADLESS_OUTPUTS*: when using the headless backend specifies the number + of outputs + +## libinput backend + +* *WLR_LIBINPUT_NO_DEVICES*: set to 1 to not fail without any input devices + +## Wayland backend + +* *WLR_WL_OUTPUTS*: when using the wayland backend specifies the number of outputs + +## X11 backend + +* *WLR_X11_OUTPUTS*: when using the X11 backend specifies the number of outputs + +## gles2 renderer + +* *WLR_RENDERER_ALLOW_SOFTWARE*: allows the gles2 renderer to use software + rendering + +## scenes + +* *WLR_SCENE_DEBUG_DAMAGE*: specifies debug options for screen damage related + tasks for compositors that use scenes (available options: none, rerender, + highlight) +* *WLR_SCENE_DISABLE_DIRECT_SCANOUT*: disables direct scan-out for debugging. +* *WLR_SCENE_DISABLE_VISIBILITY*: If set to 1, the visibility of all scene nodes + will be considered to be the full node. Intelligent visibility canculations will + be disabled. Note that direct scanout will not work for most cases when this + option is set as surfaces that don't contribute to the rendered output will now + bail direct scanout (desktop background / black rect underneath). +* *WLR_SCENE_HIGHLIGHT_TRANSPARENT_REGION*: Highlights regions of scene buffers + that are advertised as transparent through wlr_scene_buffer_set_opaque_region(). + This can be used to debug issues with clients advertizing bogus opaque regions + with scene based compositors. + +# Generic + +* *DISPLAY*: if set probe X11 backend in `wlr_backend_autocreate` +* *WAYLAND_DISPLAY*, *WAYLAND_SOCKET*: if set probe Wayland backend in + `wlr_backend_autocreate` +* *XCURSOR_PATH*: directory where xcursors are located +* *XDG_SESSION_ID*: if set, session ID used by the logind session diff --git a/3rdparty/wlroots/examples/.gitignore b/3rdparty/wlroots/examples/.gitignore new file mode 100644 index 0000000000..38582982ca --- /dev/null +++ b/3rdparty/wlroots/examples/.gitignore @@ -0,0 +1 @@ +/compositor/protocols diff --git a/3rdparty/wlroots/examples/cairo-buffer.c b/3rdparty/wlroots/examples/cairo-buffer.c new file mode 100644 index 0000000000..6392b2ac55 --- /dev/null +++ b/3rdparty/wlroots/examples/cairo-buffer.c @@ -0,0 +1,194 @@ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Simple scene-graph example with a custom buffer drawn by Cairo. + * + * Input is unimplemented. Surfaces are unimplemented. */ + +struct cairo_buffer { + struct wlr_buffer base; + cairo_surface_t *surface; +}; + +static void cairo_buffer_destroy(struct wlr_buffer *wlr_buffer) { + struct cairo_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + wlr_buffer_finish(wlr_buffer); + cairo_surface_destroy(buffer->surface); + free(buffer); +} + +static bool cairo_buffer_begin_data_ptr_access(struct wlr_buffer *wlr_buffer, + uint32_t flags, void **data, uint32_t *format, size_t *stride) { + struct cairo_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + + if (flags & WLR_BUFFER_DATA_PTR_ACCESS_WRITE) { + return false; + } + + *format = DRM_FORMAT_ARGB8888; + *data = cairo_image_surface_get_data(buffer->surface); + *stride = cairo_image_surface_get_stride(buffer->surface); + return true; +} + +static void cairo_buffer_end_data_ptr_access(struct wlr_buffer *wlr_buffer) { +} + +static const struct wlr_buffer_impl cairo_buffer_impl = { + .destroy = cairo_buffer_destroy, + .begin_data_ptr_access = cairo_buffer_begin_data_ptr_access, + .end_data_ptr_access = cairo_buffer_end_data_ptr_access +}; + +static struct cairo_buffer *create_cairo_buffer(int width, int height) { + struct cairo_buffer *buffer = calloc(1, sizeof(*buffer)); + if (!buffer) { + return NULL; + } + + wlr_buffer_init(&buffer->base, &cairo_buffer_impl, width, height); + + buffer->surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, + width, height); + if (cairo_surface_status(buffer->surface) != CAIRO_STATUS_SUCCESS) { + free(buffer); + return NULL; + } + + return buffer; +} + +struct server { + struct wl_display *display; + struct wlr_backend *backend; + struct wlr_renderer *renderer; + struct wlr_allocator *allocator; + struct wlr_scene *scene; + + struct wl_listener new_output; +}; + +struct output { + struct wl_list link; + struct server *server; + struct wlr_output *wlr; + struct wlr_scene_output *scene_output; + + struct wl_listener frame; +}; + +static void output_handle_frame(struct wl_listener *listener, void *data) { + struct output *output = wl_container_of(listener, output, frame); + + wlr_scene_output_commit(output->scene_output, NULL); +} + +static void server_handle_new_output(struct wl_listener *listener, void *data) { + struct server *server = wl_container_of(listener, server, new_output); + struct wlr_output *wlr_output = data; + + wlr_output_init_render(wlr_output, server->allocator, server->renderer); + + struct output *output = calloc(1, sizeof(*output)); + output->wlr = wlr_output; + output->server = server; + output->frame.notify = output_handle_frame; + wl_signal_add(&wlr_output->events.frame, &output->frame); + + output->scene_output = wlr_scene_output_create(server->scene, wlr_output); + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, true); + struct wlr_output_mode *mode = wlr_output_preferred_mode(wlr_output); + if (mode != NULL) { + wlr_output_state_set_mode(&state, mode); + } + wlr_output_commit_state(wlr_output, &state); + wlr_output_state_finish(&state); +} + +int main(void) { + wlr_log_init(WLR_DEBUG, NULL); + + struct server server = {0}; + server.display = wl_display_create(); + server.backend = wlr_backend_autocreate(wl_display_get_event_loop(server.display), NULL); + server.scene = wlr_scene_create(); + + server.renderer = wlr_renderer_autocreate(server.backend); + wlr_renderer_init_wl_display(server.renderer, server.display); + + server.allocator = wlr_allocator_autocreate(server.backend, + server.renderer); + + server.new_output.notify = server_handle_new_output; + wl_signal_add(&server.backend->events.new_output, &server.new_output); + + if (!wlr_backend_start(server.backend)) { + wl_display_destroy(server.display); + return EXIT_FAILURE; + } + + struct cairo_buffer *buffer = create_cairo_buffer(256, 256); + if (!buffer) { + wl_display_destroy(server.display); + return EXIT_FAILURE; + } + + /* Begin drawing + * From cairo samples at https://www.cairographics.org/samples/ */ + cairo_t *cr = cairo_create(buffer->surface); + cairo_set_source_rgb(cr, 1, 1, 1); + cairo_paint(cr); + cairo_set_source_rgb(cr, 0, 0, 0); + + double x = 25.6, y = 128.0; + double x1 = 102.4, y1 = 230.4, + x2 = 153.6, y2 = 25.6, + x3 = 230.4, y3 = 128.0; + + cairo_move_to(cr, x, y); + cairo_curve_to(cr, x1, y1, x2, y2, x3, y3); + + cairo_set_line_width(cr, 10.0); + cairo_stroke(cr); + + cairo_set_source_rgba(cr, 1, 0.2, 0.2, 0.6); + cairo_set_line_width(cr, 6.0); + cairo_move_to(cr, x, y); + cairo_line_to(cr, x1, y1); + cairo_move_to(cr, x2, y2); + cairo_line_to(cr, x3, y3); + cairo_stroke(cr); + + cairo_destroy(cr); + /* End drawing */ + + struct wlr_scene_buffer *scene_buffer = wlr_scene_buffer_create( + &server.scene->tree, &buffer->base); + if (!scene_buffer) { + wl_display_destroy(server.display); + return EXIT_FAILURE; + } + + wlr_scene_node_set_position(&scene_buffer->node, 50, 50); + wlr_buffer_drop(&buffer->base); + + wl_display_run(server.display); + + wl_display_destroy(server.display); + return EXIT_SUCCESS; +} diff --git a/3rdparty/wlroots/examples/cat.c b/3rdparty/wlroots/examples/cat.c new file mode 100644 index 0000000000..cc1403d801 --- /dev/null +++ b/3rdparty/wlroots/examples/cat.c @@ -0,0 +1,2641 @@ +/* GIMP RGBA C-Source image dump (cat.c) */ + +#include "cat.h" + +const struct gimp_texture cat_tex = { + 128, 128, 4, + "[\227\017\377L\206\001\377M\212\002\377T\227\011\377V\231\010\377W\224\001\377[\222" + "\001\377T\212\001\377P\211\001\377M\203\001\377P\212\001\377Q\217\001\377K\210\001\377" + "K\210\001\377N\214\001\377Q\217\002\377W\226\001\377X\224\001\377U\214\001\377U\216\001" + "\377[\225\003\377Y\221\002\377W\217\001\377^\230\005\377^\230\006\377`\231\011\377Z" + "\225\003\377X\221\002\377Y\221\003\377X\220\003\377^\227\007\377Z\225\004\377Z\226\002" + "\377W\217\001\377Y\224\002\377X\222\002\377W\220\001\377[\227\001\377c\241\004\377a\237" + "\003\377Z\230\001\377Y\222\001\377Z\220\001\377X\216\001\377[\231\005\377j\246\025\377" + "_\232\010\377U\214\000\377o\242\026\377k\234\013\377g\231\001\377c\222\001\377X\213" + "\005\377_\221\023\377V\214\010\377T\216\002\377U\222\002\377Q\211\001\377J|\001\377W" + "\214\003\377j\235\006\377o\243\004\377g\235\002\377X\217\002\377X\226\002\377U\221\001" + "\377T\210\002\377V\212\001\377V\216\002\377Z\226\002\377Y\221\001\377[\221\002\377g\234" + "\014\377d\232\016\377g\240\032\377[\226\022\377\\\224\020\377g\235\026\377\\\225" + "\005\377V\221\002\377U\212\002\377Y\217\001\377Z\220\001\377Y\221\001\377Y\226\002\377" + "W\227\001\377P\217\001\377O\217\002\377V\231\004\377X\230\003\377[\231\004\377X\217\001" + "\377Z\215\002\377Y\212\002\377[\214\001\377\\\215\002\377]\220\001\377]\227\002\377]" + "\233\001\377X\220\001\377X\217\001\377X\215\001\377^\234\001\377]\237\002\377U\221\001" + "\377R\214\001\377S\217\001\377T\220\001\377P\217\001\377P\224\001\377O\216\001\377M\210" + "\001\377V\225\001\377S\216\001\377S\216\001\377S\224\001\377N\220\001\377Q\226\004\377" + "S\227\013\377Y\235\023\377a\241\025\377`\240\015\377]\234\005\377V\227\002\377Y\233" + "\010\377W\231\011\377P\222\002\377R\217\001\377Y\237\021\377S\232\010\377K\224\002" + "\377L\222\001\377P\214\002\377]\222\001\377]\224\002\377U\217\001\377L\212\001\377K\206" + "\001\377Q\213\001\377T\222\001\377U\220\001\377V\224\001\377V\223\001\377Y\223\001\377" + "[\223\001\377Z\221\001\377Y\222\001\377X\225\001\377V\222\002\377U\210\002\377^\225\001" + "\377i\240\013\377g\236\020\377h\240\023\377T\223\002\377R\216\001\377V\215\001\377" + "[\225\001\377Y\226\001\377[\227\001\377Z\227\001\377Z\226\002\377^\226\005\377e\232\014" + "\377\\\225\004\377a\233\005\377_\231\002\377m\246\013\377a\232\003\377_\226\002\377" + "\\\223\001\377X\224\001\377]\235\012\377c\241\016\377^\231\002\377_\222\002\377f\235" + "\006\377s\252\012\377j\242\001\377b\233\002\377a\235\006\377_\232\011\377V\220\002\377" + "T\210\002\377T\216\001\377S\216\001\377U\220\002\377e\234\005\377k\241\004\377n\244\004" + "\377s\252\014\377a\234\003\377c\235\010\377W\217\001\377U\204\001\377X\212\001\377" + "[\217\001\377]\225\001\377[\224\001\377W\216\002\377V\216\003\377T\214\002\377R\212\002" + "\377T\214\002\377U\213\001\377\\\223\005\377e\235\014\377W\221\002\377W\220\001\377" + "Y\220\001\377W\213\001\377V\214\001\377V\217\001\377W\227\002\377V\227\001\377U\227\001" + "\377V\231\003\377N\211\001\377S\215\001\377W\216\001\377T\210\002\377Q\204\002\377W\213" + "\001\377Z\217\001\377Z\216\000\377[\225\002\377b\243\013\377V\220\001\377T\207\001\377" + "U\214\001\377[\231\002\377\\\236\002\377U\220\001\377M\207\002\377N\207\001\377Q\215" + "\001\377S\216\001\377V\226\002\377U\216\000\377V\212\002\377c\233\001\377]\221\002\377" + "V\215\001\377X\230\001\377S\226\001\377L\215\001\377I\211\001\377L\217\001\377T\225\004" + "\377j\244\014\377l\246\013\377X\226\001\377T\225\004\377\\\235\016\377c\243\025\377" + "^\236\012\377K\223\002\377M\230\007\377S\235\016\377N\227\007\377P\215\001\377^\224" + "\001\377`\226\001\377Z\225\001\377Q\216\001\377M\210\001\377V\216\002\377]\227\001\377" + "_\232\001\377]\226\001\377[\223\001\377Z\222\001\377Y\216\001\377Y\216\001\377X\225\001" + "\377W\226\001\377V\216\001\377T\210\001\377]\225\001\377o\246\014\377e\235\012\377" + "b\236\014\377S\222\001\377T\213\001\377W\220\001\377W\223\001\377W\216\002\377\\\231" + "\002\377c\235\011\377l\242\027\377e\233\022\377d\234\020\377Y\223\003\377b\235\007" + "\377b\233\003\377f\237\004\377b\233\001\377b\232\002\377`\232\001\377]\235\001\377^\237" + "\005\377Y\227\002\377U\211\001\377]\220\002\377_\225\001\377c\240\001\377l\250\005\377" + "b\237\002\377^\233\001\377W\223\002\377W\221\001\377T\214\001\377T\217\001\377Z\225\005" + "\377]\230\002\377a\233\002\377b\234\001\377k\245\011\377l\247\014\377\\\227\003\377" + "g\240\015\377V\213\001\377P\202\001\377T\212\001\377Z\224\001\377Z\226\003\377\\\231" + "\010\377T\220\014\377L\207\004\377L\200\002\377Q\203\001\377^\223\003\377Y\216\001\377" + "^\224\004\377p\247\026\377]\227\005\377Y\222\001\377X\222\001\377V\213\001\377W\213" + "\001\377X\220\001\377[\233\001\377X\231\001\377O\212\002\377S\220\001\377S\211\001\377" + "V\216\001\377W\214\002\377O\204\002\377U\213\001\377Z\217\002\377\\\225\001\377Z\223" + "\001\377U\221\003\377g\247\027\377S\224\002\377O\213\001\377U\223\001\377Y\230\001\377" + "\\\234\001\377Y\226\001\377Q\215\001\377O\207\001\377S\214\001\377V\217\001\377Y\225" + "\001\377X\214\001\377_\223\001\377i\237\001\377_\223\001\377[\222\001\377Y\227\002\377" + "V\226\001\377K\206\001\377H\203\002\377J\211\001\377T\224\003\377j\244\014\377i\244" + "\010\377]\234\003\377T\222\001\377U\226\002\377\\\236\012\377a\242\012\377H\211\001" + "\377E\214\001\377I\225\010\377V\240\021\377Q\232\002\377Y\224\001\377\\\222\002\377" + "X\224\001\377Q\215\001\377P\212\001\377W\216\001\377_\226\001\377a\226\001\377^\224\001" + "\377Z\221\001\377X\217\002\377S\210\001\377U\214\001\377[\227\003\377X\227\001\377U\221" + "\001\377W\216\001\377^\227\001\377h\243\002\377`\231\001\377Z\226\002\377U\214\001\377" + "W\217\001\377Y\222\001\377X\221\001\377X\226\002\377W\227\002\377X\227\004\377U\223\005" + "\377U\220\002\377V\222\001\377V\222\001\377\\\235\004\377]\236\003\377X\226\002\377Z" + "\225\002\377`\237\001\377`\241\002\377]\235\001\377Y\232\002\377X\224\001\377U\212\001" + "\377W\214\002\377Z\221\002\377Y\216\001\377d\240\005\377`\233\003\377Z\226\001\377^\232" + "\003\377Z\227\002\377X\222\001\377c\234\010\377i\242\014\377\\\227\003\377]\235\003\377" + "[\234\002\377d\244\015\377e\244\017\377Z\230\004\377j\246\017\377W\215\001\377S\205" + "\002\377X\223\003\377j\244\037\377l\246/\377~\261P\377\224\301r\377j\236\063\377" + "M\201\001\377S\207\001\377[\222\002\377T\214\000\377`\233\013\377i\243\024\377`\233" + "\014\377h\241\027\377e\240\023\377U\217\002\377V\213\001\377[\230\002\377Z\231\001\377" + "N\210\002\377H\177\002\377W\225\001\377Y\220\001\377Z\217\001\377V\214\001\377R\210\001" + "\377]\234\001\377_\231\002\377Z\222\001\377Y\223\001\377V\223\001\377c\244\020\377Y" + "\233\007\377R\223\001\377U\224\001\377Z\232\001\377^\235\001\377]\234\002\377Y\232\002" + "\377R\222\001\377T\223\001\377W\230\001\377W\230\002\377W\213\001\377h\240\001\377h\236" + "\001\377_\222\002\377\\\221\002\377[\231\002\377X\231\001\377O\220\001\377K\213\001\377" + "O\217\002\377b\236\015\377_\233\007\377Z\227\002\377_\240\004\377U\217\002\377T\221" + "\001\377S\222\001\377U\221\001\377K\203\002\377F\202\001\377D\212\001\377K\225\004\377" + "O\232\003\377R\230\002\377U\225\001\377T\223\001\377P\211\001\377K\204\001\377R\211\001" + "\377X\223\001\377[\231\001\377[\233\001\377X\222\001\377S\212\001\377M\200\002\377U\214" + "\003\377^\226\012\377X\225\005\377Y\232\006\377V\222\001\377\\\225\001\377d\240\001\377" + "_\226\001\377Z\220\001\377X\221\001\377Y\222\001\377[\216\001\377\\\217\002\377^\233" + "\002\377V\225\001\377R\221\001\377T\215\001\377V\220\001\377Z\224\001\377X\222\002\377" + "W\225\001\377^\240\007\377V\224\001\377V\216\001\377^\236\002\377b\243\004\377[\233\003" + "\377X\230\004\377\\\234\011\377V\222\003\377U\216\001\377X\215\001\377[\217\001\377" + "h\240\005\377i\245\005\377]\227\001\377^\230\002\377Z\217\001\377[\221\001\377k\243\011" + "\377e\236\007\377W\223\001\377c\243\014\377[\234\005\377f\244\017\377f\241\015\377" + "b\236\012\377n\251\024\377W\217\001\377V\216\005\377e\237\040\377t\254B\377|\260" + "T\377\230\305y\377\250\317\222\377o\242<\377P\210\002\377^\224\006\377\\\226" + "\006\377Q\221\003\377b\241\024\377a\241\020\377S\224\005\377e\240\030\377l\245\033" + "\377Z\222\001\377]\223\002\377`\232\001\377[\226\002\377P\204\001\377T\211\001\377_\231" + "\001\377^\224\002\377^\224\001\377[\224\002\377Y\217\001\377Z\225\001\377Y\220\001\377" + "Z\221\001\377X\224\001\377R\215\001\377X\231\005\377`\241\012\377S\221\001\377R\214" + "\001\377W\226\001\377[\227\001\377_\237\002\377`\242\002\377W\226\001\377Y\232\002\377" + "g\246\011\377a\237\003\377Z\220\002\377e\236\002\377_\226\001\377X\220\001\377X\223" + "\001\377[\233\001\377Z\233\002\377V\230\002\377Q\220\001\377b\235\015\377m\247\025\377" + "Z\232\004\377U\224\001\377[\234\004\377R\220\001\377R\220\001\377R\225\001\377V\221\001" + "\377M\200\001\377M\205\002\377L\207\001\377N\217\002\377N\217\001\377J\217\002\377P\230" + "\004\377O\227\003\377O\215\001\377E\201\001\377N\205\002\377Q\223\002\377`\242\021\377" + "R\225\002\377T\223\001\377T\215\001\377T\205\001\377^\222\010\377b\226\015\377]\231" + "\014\377]\235\011\377V\223\001\377Z\221\001\377c\233\001\377b\231\002\377`\226\001\377" + "]\225\001\377Y\216\002\377[\213\002\377^\222\001\377b\235\003\377[\223\002\377Y\225\001" + "\377Z\223\002\377]\223\002\377]\222\002\377]\227\002\377[\230\002\377a\243\010\377W" + "\230\002\377R\217\001\377Z\234\003\377h\251\017\377e\245\022\377^\233\017\377`\234" + "\025\377]\230\017\377i\243\032\377d\235\016\377]\224\001\377i\241\002\377i\243\002" + "\377b\233\001\377_\233\002\377X\222\001\377W\223\001\377c\237\017\377h\243\026\377" + "\\\234\014\377`\240\015\377Y\233\003\377^\235\004\377]\231\004\377c\235\007\377f\242" + "\016\377]\232\016\377n\250/\377q\253<\377w\256H\377\177\263Q\377\234\307z\377" + "\244\315\211\377g\241+\377O\216\002\377U\222\003\377S\222\003\377N\217\001\377_\241" + "\020\377Z\235\011\377Q\220\002\377W\226\003\377\\\231\003\377d\236\003\377k\237\001\377" + "f\233\001\377_\225\001\377X\213\002\377]\225\001\377f\236\002\377c\231\001\377`\234\002" + "\377]\234\001\377W\217\001\377V\214\001\377V\223\001\377T\223\001\377T\224\002\377K\203" + "\002\377N\212\001\377_\240\004\377X\222\001\377W\222\001\377Y\225\002\377W\220\001\377" + "Z\227\001\377`\242\003\377^\241\003\377`\241\004\377h\247\007\377c\242\003\377]\231\001" + "\377^\234\001\377S\220\001\377R\216\001\377U\225\001\377Z\231\002\377`\233\002\377[\225" + "\003\377W\213\002\377h\235\016\377e\240\015\377[\233\003\377X\232\003\377\\\235\005\377" + "V\225\002\377S\222\002\377Z\234\001\377b\235\001\377L~\002\377P\205\001\377O\206\002\377" + "Z\223\001\377Y\226\001\377N\210\001\377I\212\001\377R\231\004\377J\213\001\377C}\001\377" + "L\211\001\377V\232\015\377a\242\040\377L\212\001\377N\212\001\377T\217\001\377^\232" + "\003\377a\233\003\377Y\223\001\377T\224\002\377W\232\003\377W\225\001\377\\\225\002\377" + "b\230\001\377e\234\002\377a\226\001\377\\\217\001\377X\214\002\377\\\220\001\377a\232" + "\003\377b\233\002\377[\222\001\377_\233\002\377_\225\001\377`\225\001\377a\225\001\377" + "b\231\001\377\\\227\001\377a\243\005\377`\244\007\377U\224\002\377]\237\003\377b\242" + "\007\377f\246\020\377Z\231\007\377X\225\006\377b\235\022\377w\253.\377\200\263:\377" + "m\244\033\377j\245\002\377g\236\001\377b\232\002\377]\230\001\377X\224\001\377T\220" + "\004\377f\241\034\377b\240\031\377i\250\035\377d\244\021\377Y\230\001\377^\231\001" + "\377]\223\002\377b\231\003\377]\231\005\377^\233\024\377r\253\067\377x\262A\377{" + "\261@\377\202\265I\377\230\305k\377\227\302t\377_\234\026\377P\213\002\377R" + "\213\001\377V\220\002\377W\224\002\377a\241\010\377W\230\003\377N\213\001\377R\221\001" + "\377[\231\001\377c\232\001\377i\240\002\377j\240\001\377[\221\001\377O\202\001\377]\225" + "\001\377c\235\001\377a\230\001\377b\237\003\377_\240\003\377W\216\002\377\\\232\002\377" + "Z\227\001\377U\222\001\377P\216\001\377M\210\002\377Q\207\002\377\\\232\001\377_\233" + "\002\377^\236\001\377Z\224\001\377W\213\002\377[\231\001\377h\246\010\377f\247\014\377" + "W\231\002\377]\237\003\377\\\234\001\377^\233\001\377Z\227\002\377V\225\001\377U\230" + "\001\377Z\233\001\377\\\233\002\377c\240\002\377d\232\004\377^\223\005\377^\226\007\377" + "[\231\004\377]\233\003\377`\237\005\377^\235\003\377^\236\002\377\\\235\002\377_\240" + "\001\377`\230\002\377Ey\002\377H\201\001\377N\210\001\377R\216\001\377Z\231\001\377U\221" + "\001\377N\211\001\377N\221\000\377J\212\001\377G\202\001\377G\212\001\377R\231\012\377" + "X\233\021\377I\202\001\377M\212\001\377O\221\001\377W\227\001\377_\240\001\377]\223" + "\001\377X\223\001\377W\227\001\377X\226\002\377^\231\001\377d\237\001\377i\247\002\377" + "\\\231\001\377W\216\001\377X\220\001\377Z\227\002\377f\246\011\377\\\231\002\377Y\224" + "\002\377]\227\001\377^\222\002\377c\225\001\377e\230\001\377b\227\001\377^\227\001\377" + "b\243\003\377h\252\012\377]\236\001\377^\240\001\377Z\233\001\377]\235\002\377c\244" + "\012\377g\244\020\377b\236\022\377i\243\037\377u\253\060\377}\262\060\377o\251" + "\013\377f\234\002\377`\223\001\377e\235\006\377e\233\021\377q\247\063\377y\261F\377" + "l\245\062\377o\253*\377f\246\024\377Z\231\002\377c\235\001\377a\221\003\377n\243" + "\013\377s\247\034\377g\237\037\377s\253\064\377~\264?\377x\254\065\377\177\263" + ";\377\204\265C\377q\246)\377V\224\000\377W\223\002\377T\216\001\377V\217\001\377" + "\\\227\001\377e\241\005\377W\221\001\377M\200\002\377S\220\002\377]\233\001\377b\226" + "\002\377j\234\002\377i\240\002\377\\\226\001\377R\207\001\377]\230\001\377b\233\002\377" + "_\224\002\377f\240\002\377`\233\002\377[\222\001\377c\232\002\377e\240\001\377V\213\002" + "\377R\212\001\377S\215\001\377[\226\001\377`\237\001\377^\235\001\377Y\233\001\377X\230" + "\001\377U\212\001\377[\227\001\377j\250\007\377b\242\004\377S\215\002\377Y\226\001\377" + "a\242\002\377a\240\001\377X\222\001\377Y\227\001\377^\242\001\377]\234\001\377_\234\002" + "\377c\237\001\377f\237\004\377b\227\005\377a\230\005\377_\232\003\377f\240\004\377m\246" + "\006\377g\242\001\377p\251\005\377l\246\003\377c\232\002\377a\232\001\377p\001\377M\207\001\377H\204\002\377D}\001\377I\210\001" + "\377S\226\001\377N\224\002\377K\222\002\377\\\241\025\377H\217\003\377D\210\001\377" + "U\233\004\377S\223\001\377X\223\001\377W\216\001\377S\216\001\377X\227\002\377\\\233" + "\002\377Z\222\001\377Y\227\002\377V\227\002\377^\237\010\377]\234\002\377l\245\002\377" + "u\256\003\377d\231\002\377\\\217\002\377Y\216\001\377c\237\004\377{\262\026\377j\240" + "\003\377f\225\001\377e\222\002\377i\234\002\377h\240\001\377a\231\002\377]\226\001\377" + "\\\221\001\377\\\223\001\377_\236\002\377c\237\001\377h\244\001\377d\235\002\377^\226" + "\001\377_\234\001\377Z\230\002\377c\243\016\377a\235\017\377o\251\027\377g\241\005\377" + "g\242\001\377l\246\002\377f\235\000\377j\242\013\377p\246'\377v\253A\377\217\300" + "d\377w\261;\377Y\233\001\377e\250\005\377]\236\001\377_\237\003\377p\254\026\377x" + "\263(\377p\255)\377b\236\036\377|\262<\377s\252-\377\\\233\010\377m\253\023" + "\377d\241\005\377\\\231\002\377[\230\001\377Y\231\001\377\\\227\001\377c\231\001\377" + "k\237\001\377p\247\002\377k\243\002\377e\241\002\377^\231\001\377i\243\001\377p\252\002" + "\377o\246\005\377a\233\002\377_\232\001\377b\236\002\377d\236\002\377b\233\001\377s\255" + "\013\377x\261\013\377j\241\002\377a\225\002\377Z\214\002\377_\225\002\377d\236\001\377" + "b\232\001\377b\240\001\377]\232\001\377X\225\002\377c\245\016\377S\223\002\377[\233" + "\002\377[\226\002\377c\237\004\377n\254\010\377a\242\001\377`\226\001\377h\241\001\377" + "v\256\002\377r\247\001\377j\241\001\377e\236\001\377c\234\002\377f\242\001\377f\236\001" + "\377f\234\002\377d\233\001\377a\225\002\377i\240\003\377k\242\003\377z\261\031\377~" + "\263\037\377h\240\003\377j\244\002\377d\235\002\377`\220\001\377i\243\001\377Cu\002\377" + "I\201\001\377F\201\001\377E{\002\377K\206\001\377U\225\001\377R\226\001\377J\221\001\377" + "R\231\011\377H\220\004\377E\212\002\377R\230\002\377V\226\001\377Z\221\001\377O|\001\377" + "P\203\001\377[\223\001\377`\232\001\377^\226\001\377Z\233\002\377R\226\001\377\\\235" + "\014\377c\243\014\377c\240\001\377l\251\001\377c\235\001\377Z\223\001\377X\223\001\377" + "i\246\010\377x\260\017\377j\235\001\377h\224\002\377h\230\001\377h\236\001\377c\231" + "\001\377Z\223\002\377Z\231\001\377[\226\001\377^\230\001\377a\242\003\377]\237\001\377" + "Y\230\001\377Z\225\001\377_\236\002\377c\240\001\377d\240\002\377d\242\007\377\\\231" + "\006\377d\237\012\377q\255\015\377i\243\002\377k\250\002\377f\243\003\377a\236\010\377" + "f\240\037\377s\254>\377\203\271Q\377s\256\062\377\\\235\003\377h\252\012\377a" + "\242\005\377^\236\003\377n\253\027\377\200\273\060\377j\251\027\377\\\235\006\377" + "]\235\010\377]\235\006\377_\231\002\377e\234\001\377i\240\002\377g\235\001\377a\230" + "\002\377\\\221\001\377d\233\001\377n\246\002\377o\243\001\377p\246\002\377h\241\002\377" + "a\232\002\377k\247\003\377r\255\002\377q\251\001\377j\235\002\377k\243\002\377k\242\001" + "\377j\240\001\377h\234\001\377d\234\002\377x\261\015\377w\261\007\377j\240\002\377_" + "\220\002\377Y\212\002\377V\210\002\377e\236\001\377m\250\002\377l\250\001\377f\242\002" + "\377_\236\005\377b\242\011\377\\\235\003\377]\232\002\377Y\220\001\377n\247\013\377" + "r\254\010\377i\245\001\377k\242\001\377l\241\001\377w\254\001\377x\252\001\377v\256" + "\001\377m\243\002\377d\234\002\377e\236\002\377e\234\002\377c\233\002\377`\227\002\377" + "g\236\002\377p\247\003\377h\234\001\377p\250\015\377z\261\032\377d\240\001\377d\236" + "\001\377e\236\002\377a\224\002\377h\242\001\377G|\002\377K\206\004\377K\211\006\377\071" + "m\001\377N\212\002\377]\237\001\377V\235\001\377M\222\001\377O\226\007\377N\226\007\377" + "I\217\001\377V\233\003\377V\221\001\377N\177\001\377Hu\001\377M}\001\377Y\216\001\377h" + "\241\001\377c\233\001\377[\231\002\377U\227\002\377M\215\002\377Y\230\003\377_\235\001" + "\377g\243\001\377b\235\002\377\\\230\001\377X\224\001\377l\251\012\377n\247\005\377" + "j\233\002\377i\227\002\377k\235\002\377g\236\001\377[\216\001\377U\211\001\377[\230\001" + "\377_\233\001\377`\232\002\377a\243\002\377\\\236\002\377Z\237\001\377Z\232\001\377c" + "\243\002\377o\255\004\377i\245\003\377_\235\001\377\\\233\002\377a\241\002\377i\247\004" + "\377d\241\001\377l\250\010\377e\242\011\377a\237\015\377o\251%\377x\261\066\377" + "v\260\066\377x\262.\377^\236\006\377\\\235\002\377c\245\006\377`\240\003\377q\256" + "\030\377w\263\036\377e\244\007\377b\243\002\377Z\226\001\377]\231\002\377c\236\001\377" + "j\242\002\377m\241\001\377k\241\002\377j\236\002\377f\231\001\377h\235\001\377i\240\001" + "\377h\240\002\377g\244\002\377e\244\002\377j\246\005\377n\251\004\377q\251\001\377o\241" + "\002\377p\241\001\377r\253\002\377p\244\001\377p\243\001\377j\235\002\377h\236\002\377" + "t\257\002\377p\250\001\377j\235\001\377d\223\001\377h\227\003\377]\213\002\377Z\212\001" + "\377i\241\002\377m\247\001\377n\246\003\377o\252\011\377`\241\004\377Z\231\001\377^" + "\231\002\377^\231\001\377p\254\015\377g\245\004\377j\244\001\377p\252\001\377r\245\001" + "\377w\254\001\377{\255\001\377y\262\001\377o\256\001\377a\235\002\377b\234\002\377b\236" + "\001\377`\231\001\377`\227\001\377i\240\002\377m\244\002\377h\236\001\377p\254\016\377" + "r\257\021\377`\237\001\377a\231\002\377c\232\002\377d\227\001\377g\240\001\377J\210" + "\001\377]\233\026\377h\243)\377:j\000\377R\207\002\377b\243\002\377_\242\004\377M\222" + "\001\377N\226\004\377Q\230\005\377Q\227\003\377U\232\003\377R\215\001\377K~\002\377M\200" + "\002\377T\213\001\377a\231\002\377g\236\002\377`\224\002\377]\231\001\377Z\232\001\377" + "Q\215\001\377Q\216\001\377\\\231\001\377f\242\001\377b\231\001\377X\217\002\377Y\225" + "\000\377o\252\012\377f\235\003\377d\227\001\377h\233\002\377h\236\001\377d\240\002\377" + "\\\227\001\377Y\225\001\377^\235\001\377a\234\001\377c\235\002\377c\240\002\377^\234" + "\001\377Z\231\001\377\\\237\001\377a\242\001\377n\252\010\377i\245\010\377\\\235\002" + "\377a\242\001\377d\242\001\377a\233\001\377]\232\001\377i\251\017\377a\241\014\377" + "[\234\010\377l\250\030\377{\264+\377v\260&\377t\261\035\377^\236\003\377\\\230" + "\002\377j\254\012\377c\245\006\377j\251\015\377k\253\014\377c\243\004\377g\251\003\377" + "[\230\001\377Z\227\001\377d\245\001\377h\243\001\377j\235\001\377j\240\001\377m\244\002" + "\377j\243\001\377f\237\002\377h\240\002\377k\245\002\377l\251\003\377f\247\001\377d\242" + "\002\377i\242\001\377n\247\001\377i\234\002\377o\243\002\377x\252\002\377r\241\002\377" + "t\247\001\377n\243\001\377l\240\001\377o\253\002\377j\243\001\377f\236\002\377b\231\002" + "\377\177\255\033\377b\222\006\377U\204\001\377d\233\001\377p\252\002\377j\244\001\377" + "l\253\002\377b\240\001\377a\234\002\377d\233\002\377g\241\003\377m\252\010\377_\237" + "\001\377b\237\001\377h\240\002\377r\246\002\377x\247\002\377\206\267\002\377\200\265" + "\001\377r\254\001\377k\251\002\377e\236\001\377a\232\001\377^\227\001\377a\231\001\377" + "j\241\003\377w\255\020\377z\262\025\377r\256\017\377l\254\014\377\\\236\001\377\\" + "\226\001\377b\233\001\377h\237\001\377l\245\001\377J\210\002\377S\225\016\377o\254-" + "\377K\204\004\377S\217\002\377Z\232\001\377^\241\002\377Y\234\001\377X\236\003\377[\242" + "\011\377\\\242\015\377P\230\003\377P\222\001\377P\212\001\377R\214\001\377[\223\001\377" + "g\236\002\377i\235\001\377^\222\003\377]\231\001\377Y\230\001\377U\226\002\377Q\217\002" + "\377U\224\001\377`\236\002\377c\233\001\377]\221\001\377b\241\003\377q\255\021\377_" + "\233\002\377a\230\001\377e\233\002\377d\234\002\377b\240\002\377c\246\002\377d\247\004" + "\377\\\234\001\377^\235\001\377`\235\002\377a\240\002\377^\233\002\377[\230\002\377a" + "\242\001\377^\237\000\377d\243\012\377j\247\025\377j\250\017\377d\244\003\377e\247" + "\001\377^\232\002\377W\223\001\377\\\240\006\377[\236\003\377Z\234\002\377a\241\006\377" + "s\260\026\377y\266\035\377f\245\006\377a\234\001\377a\235\002\377n\255\007\377j\250" + "\010\377j\247\011\377r\260\021\377f\246\005\377a\243\002\377Z\232\001\377f\246\012" + "\377n\253\011\377h\233\002\377l\241\001\377e\235\001\377d\240\001\377c\241\001\377b" + "\234\002\377j\245\001\377j\246\002\377g\243\002\377i\250\002\377k\245\002\377p\251\002" + "\377o\247\001\377m\241\001\377j\235\002\377q\244\002\377r\242\002\377s\246\002\377n\243" + "\001\377h\237\001\377h\243\001\377e\237\001\377`\233\002\377]\231\002\377j\246\016\377" + "`\230\003\377a\227\001\377g\240\001\377m\252\002\377i\246\001\377i\244\001\377e\235\002" + "\377a\227\002\377i\242\001\377q\253\003\377l\251\003\377b\237\001\377d\242\001\377g\240" + "\001\377m\242\001\377r\244\001\377}\257\001\377\207\271\001\377~\256\001\377t\251\001\377" + "k\242\001\377f\236\002\377b\232\001\377f\237\002\377m\245\003\377o\246\011\377z\263" + "\026\377q\256\020\377q\260\022\377_\241\002\377^\234\002\377e\235\002\377m\245\001\377" + "n\241\001\377V\230\010\377]\236\017\377w\261-\377f\244\026\377S\220\001\377V\222" + "\001\377Z\227\001\377`\234\001\377_\235\002\377[\235\002\377`\245\014\377V\232\003\377" + "W\233\002\377\\\237\001\377Y\233\001\377]\230\001\377d\232\002\377f\232\001\377b\230" + "\001\377^\230\001\377[\231\001\377W\226\002\377X\227\001\377Y\221\001\377e\240\002\377" + "g\236\002\377d\237\001\377m\253\014\377l\253\021\377[\233\001\377b\231\001\377l\237" + "\001\377h\236\002\377c\237\001\377g\250\007\377c\245\005\377\\\236\002\377^\241\001\377" + "\\\234\001\377[\232\001\377[\231\001\377^\232\001\377a\243\002\377Z\235\001\377\\\240" + "\011\377U\231\006\377`\241\012\377f\250\007\377d\247\002\377`\242\002\377V\227\002\377" + "U\232\003\377b\246\011\377\\\236\001\377^\236\001\377i\252\005\377i\251\003\377c\243" + "\002\377b\243\001\377d\245\001\377g\250\002\377a\243\002\377`\241\002\377h\251\005\377" + "e\247\002\377_\235\002\377_\237\002\377d\245\005\377e\236\003\377s\251\001\377w\254\002" + "\377j\241\001\377h\247\002\377a\235\001\377c\234\001\377j\246\002\377n\252\004\377j\247" + "\002\377k\245\001\377l\243\002\377s\255\001\377o\241\002\377k\237\002\377l\236\001\377" + "p\245\002\377m\244\001\377l\244\001\377l\243\001\377i\241\001\377h\237\001\377a\225\002" + "\377_\226\002\377]\224\001\377c\234\002\377j\237\001\377l\235\001\377l\240\001\377p\253" + "\001\377k\242\001\377e\227\002\377f\234\001\377b\226\002\377n\247\002\377s\256\002\377" + "m\241\001\377j\240\001\377j\243\002\377i\240\001\377l\242\001\377q\252\001\377t\253\001" + "\377\210\267\001\377\216\274\001\377{\257\002\377l\245\002\377j\246\001\377j\243\002" + "\377n\244\001\377t\251\005\377u\252\005\377l\245\002\377m\252\006\377r\257\021\377h" + "\246\010\377d\241\002\377f\235\001\377o\245\002\377s\244\001\377O\212\003\377W\227\004" + "\377f\243\022\377r\254\036\377V\223\001\377X\223\001\377Z\230\002\377^\223\001\377" + "a\230\001\377\\\232\001\377Z\237\004\377M\221\001\377P\223\001\377^\243\003\377\\\237" + "\001\377\\\233\001\377b\233\001\377d\241\001\377a\237\001\377\\\234\001\377\\\234\001\377" + "[\224\002\377_\233\001\377_\230\001\377k\246\003\377d\242\004\377]\236\002\377g\250\015" + "\377e\247\015\377[\233\002\377c\237\002\377f\233\002\377f\234\002\377d\242\001\377o" + "\253\017\377f\246\012\377]\236\001\377_\240\002\377Y\225\001\377[\231\001\377`\234" + "\001\377c\237\001\377c\240\001\377[\232\001\377X\232\002\377\\\237\003\377`\242\003\377" + "b\243\004\377d\245\005\377f\250\012\377Z\237\003\377W\231\002\377Y\235\002\377[\235" + "\001\377`\240\002\377b\243\001\377c\242\001\377d\244\001\377c\240\001\377g\246\002\377" + "f\247\001\377`\240\001\377^\241\002\377c\245\001\377h\251\002\377n\253\012\377j\252" + "\012\377b\241\002\377g\242\001\377t\261\002\377q\253\002\377l\247\002\377k\251\002\377" + "b\236\002\377b\236\002\377l\253\012\377}\270\034\377k\250\004\377k\246\001\377m\247" + "\002\377q\256\001\377m\241\001\377n\242\001\377o\242\001\377r\245\001\377q\247\002\377" + "n\246\001\377p\252\001\377l\242\001\377g\235\002\377c\234\001\377`\226\001\377c\227\002" + "\377l\234\001\377m\236\001\377i\231\001\377i\236\001\377i\242\001\377i\241\001\377d\230" + "\001\377h\226\002\377l\233\002\377q\244\001\377t\253\001\377o\241\001\377k\241\002\377" + "j\242\001\377j\243\001\377m\251\002\377m\247\002\377n\244\001\377{\256\001\377\203\266" + "\001\377w\254\001\377m\246\002\377o\246\001\377t\247\002\377y\250\001\377\225\266\023" + "\377\235\274\032\377u\252\003\377j\243\001\377w\264\017\377s\261\013\377g\237\002" + "\377l\242\001\377s\251\001\377s\246\001\377R\212\001\377[\227\002\377c\241\010\377l" + "\247\020\377`\235\002\377Z\225\002\377\\\234\001\377[\222\001\377\\\220\001\377`\235" + "\002\377Z\240\002\377J\223\002\377R\227\003\377V\233\002\377X\226\001\377^\223\002\377" + "a\232\001\377`\231\002\377X\222\002\377X\227\001\377[\233\001\377]\235\001\377\\\233" + "\001\377`\235\001\377k\252\003\377b\234\003\377\\\231\001\377_\243\002\377[\234\001\377" + "Y\224\002\377b\234\002\377b\232\001\377a\231\001\377a\236\002\377_\240\004\377d\247\010" + "\377\\\236\001\377_\236\002\377a\237\001\377c\244\001\377c\240\001\377_\233\001\377\\" + "\234\002\377[\236\001\377a\244\005\377b\244\004\377`\232\002\377d\237\000\377p\254\015" + "\377r\255\031\377[\234\004\377[\234\001\377]\235\001\377`\236\001\377`\235\001\377c" + "\240\001\377c\231\001\377f\246\001\377e\243\001\377g\243\001\377j\245\001\377e\240\002" + "\377_\237\002\377d\245\006\377r\262\022\377w\267\032\377c\244\007\377`\240\002\377" + "d\242\002\377p\257\001\377m\247\001\377h\246\001\377h\247\001\377d\242\002\377`\235\001" + "\377m\255\021\377z\272#\377e\247\003\377i\247\001\377j\237\001\377n\250\002\377m\241" + "\001\377l\237\002\377q\243\002\377s\246\001\377s\246\001\377p\242\001\377n\244\001\377" + "g\236\001\377g\243\001\377e\237\001\377b\227\001\377h\234\001\377n\243\001\377m\244\002" + "\377h\234\001\377g\240\002\377g\245\001\377n\251\002\377o\245\001\377o\236\002\377q\240" + "\001\377r\243\002\377u\254\002\377n\241\002\377m\246\001\377r\255\002\377o\252\002\377" + "j\237\001\377j\237\001\377m\242\001\377t\254\001\377z\257\001\377y\256\002\377t\251\001" + "\377o\241\001\377q\241\001\377v\246\001\377~\255\005\377\206\264\014\377k\242\002\377" + "i\243\001\377w\264\013\377p\256\006\377h\235\002\377n\244\002\377s\250\002\377r\244" + "\002\377e\241\002\377\\\232\002\377\\\235\002\377_\240\003\377]\235\001\377]\226\001\377" + "_\234\002\377\\\222\002\377X\215\001\377a\233\002\377^\240\002\377W\230\001\377Y\233" + "\002\377Y\232\001\377\\\227\001\377^\222\002\377d\233\002\377^\225\001\377X\224\002\377" + "X\224\001\377^\241\004\377i\252\014\377Z\233\002\377^\237\001\377k\254\006\377b\236" + "\002\377^\227\001\377`\242\002\377Y\226\001\377\\\221\001\377d\237\001\377f\241\001\377" + "b\231\002\377^\227\001\377Y\227\001\377Y\233\001\377X\225\001\377\\\233\001\377`\236" + "\001\377c\242\001\377a\237\002\377`\235\001\377^\240\001\377Z\233\001\377\\\237\001\377" + "[\231\001\377_\225\002\377a\234\001\377a\236\003\377a\237\005\377Y\232\001\377\\\234" + "\001\377b\240\001\377a\237\001\377f\244\010\377|\265\034\377i\242\002\377g\242\001\377" + "d\234\001\377i\244\001\377g\237\002\377b\240\001\377\\\236\001\377t\262\033\377\206" + "\301*\377l\254\020\377Z\236\002\377Z\235\001\377a\233\002\377k\243\002\377j\241\001" + "\377g\241\001\377c\241\001\377f\247\001\377a\241\002\377j\254\006\377f\251\010\377i" + "\254\004\377k\247\002\377i\235\001\377l\243\002\377h\234\002\377f\232\002\377g\232\002" + "\377g\232\002\377o\244\001\377n\242\001\377k\245\001\377d\237\001\377c\241\002\377b\231" + "\001\377`\224\002\377b\227\001\377k\244\002\377p\253\002\377j\237\002\377j\243\002\377" + "j\241\001\377p\250\001\377u\254\001\377s\246\002\377j\234\002\377h\233\001\377p\250\002" + "\377o\251\001\377m\244\001\377z\265\004\377r\251\001\377n\242\001\377l\241\001\377i\240" + "\001\377l\243\001\377l\237\001\377w\253\001\377w\253\001\377m\237\001\377o\241\001\377" + "o\241\002\377o\246\001\377n\252\001\377j\240\001\377l\244\001\377y\264\005\377y\262\005" + "\377l\242\001\377k\240\001\377n\245\002\377j\235\001\377a\240\001\377`\233\002\377_\237" + "\001\377[\235\001\377X\227\001\377X\222\001\377[\231\001\377[\225\002\377W\213\001\377" + "\\\223\001\377`\236\002\377\\\230\002\377\\\227\001\377Y\227\001\377\\\231\001\377[\226" + "\001\377a\237\001\377a\237\002\377Z\231\001\377X\226\001\377_\236\002\377m\254\015\377" + "^\240\002\377\\\235\001\377k\254\007\377c\240\003\377_\230\000\377b\243\001\377_\237" + "\001\377Z\222\002\377`\227\002\377d\236\002\377e\241\001\377c\235\002\377a\237\001\377" + "_\234\001\377\\\224\001\377_\231\001\377c\241\001\377b\236\002\377`\235\002\377_\237" + "\003\377d\244\017\377_\236\016\377X\231\002\377X\223\001\377\\\231\002\377a\240\001\377" + "[\230\001\377Y\230\001\377\\\234\001\377a\242\001\377b\242\001\377\\\233\002\377j\251" + "\016\377y\261\035\377j\235\000\377o\243\002\377]\221\002\377f\236\002\377g\244\001\377" + "_\237\001\377e\247\012\377\177\275)\377w\266\040\377b\244\011\377Z\236\004\377X" + "\232\002\377^\231\001\377f\236\002\377f\234\001\377f\241\001\377c\242\001\377j\254\004" + "\377h\250\003\377f\247\002\377c\241\001\377g\241\001\377n\250\001\377o\244\002\377r\246" + "\002\377m\237\002\377c\226\001\377c\226\001\377g\236\001\377o\246\001\377o\243\001\377" + "o\241\002\377m\237\002\377t\252\002\377f\230\001\377b\231\001\377a\225\001\377h\240\001" + "\377j\244\002\377q\254\001\377k\244\001\377i\235\002\377q\250\001\377u\257\002\377o\246" + "\001\377c\230\001\377e\233\002\377p\252\001\377n\247\002\377l\244\001\377t\261\002\377" + "p\253\001\377n\251\002\377l\251\003\377e\236\002\377k\244\001\377j\240\001\377u\254\002" + "\377z\256\001\377t\243\002\377m\235\001\377m\241\002\377s\256\001\377o\255\001\377h\235" + "\002\377n\244\001\377u\252\001\377\177\265\003\377q\245\001\377j\235\002\377i\241\001\377" + "f\236\002\377a\240\001\377`\231\001\377b\241\002\377`\240\001\377X\222\002\377W\220\001" + "\377\\\232\001\377[\225\001\377Y\220\001\377]\226\001\377a\232\001\377c\230\001\377a" + "\226\001\377^\222\002\377b\232\002\377`\234\004\377b\241\006\377e\245\007\377Z\226\001" + "\377[\223\001\377_\237\002\377g\247\003\377f\245\001\377a\235\001\377e\246\002\377a\240" + "\002\377a\231\001\377c\245\001\377a\243\002\377R\214\001\377Y\223\002\377`\234\002\377" + "c\244\001\377b\243\003\377_\240\002\377Z\226\002\377`\230\001\377d\231\001\377n\253\003" + "\377m\255\004\377a\243\004\377V\222\007\377Z\203)\377\213\256]\377g\235\"\377O" + "\220\000\377X\224\001\377\\\233\001\377Z\231\001\377Y\226\001\377Z\226\001\377^\234\002" + "\377a\243\001\377j\253\014\377h\247\007\377`\227\001\377m\243\001\377p\243\001\377Y" + "\217\002\377h\236\001\377h\247\002\377]\235\002\377o\257\032\377x\266\040\377j\253" + "\017\377Z\237\004\377X\236\004\377W\231\002\377\\\234\002\377j\250\007\377c\240\001\377" + "g\246\002\377j\252\004\377n\256\007\377l\254\007\377`\237\002\377c\241\001\377i\240\001" + "\377r\252\001\377w\253\001\377t\243\002\377l\234\001\377e\227\002\377a\225\001\377h\246" + "\001\377k\250\001\377l\241\002\377q\243\002\377t\251\002\377o\242\002\377h\234\001\377" + "c\232\002\377^\226\001\377f\245\001\377e\236\001\377s\260\006\377h\243\003\377g\235\002" + "\377o\247\001\377r\254\001\377j\236\002\377a\226\002\377g\236\001\377n\251\001\377l\246" + "\002\377j\247\001\377o\260\003\377i\251\001\377m\254\005\377z\267\020\377g\246\001\377" + "g\243\001\377j\246\001\377n\244\001\377t\247\002\377{\262\001\377u\245\001\377r\245\002" + "\377r\251\001\377m\243\001\377i\240\001\377n\250\001\377r\253\001\377|\264\002\377u\256" + "\002\377m\241\001\377g\235\002\377i\245\001\377X\227\001\377Y\221\002\377`\237\001\377" + "b\240\002\377\\\222\001\377^\230\000\377`\235\001\377^\225\001\377Y\217\002\377_\226" + "\002\377_\230\002\377`\234\003\377a\230\001\377d\233\002\377g\237\004\377`\233\004\377" + "g\245\020\377b\243\011\377[\232\002\377[\221\001\377_\232\001\377j\250\004\377k\253" + "\004\377b\240\001\377b\241\001\377c\241\002\377d\234\002\377m\256\003\377e\244\002\377" + "W\215\001\377[\222\001\377b\235\002\377c\241\001\377f\251\004\377f\246\005\377`\233\001" + "\377f\235\002\377m\243\001\377w\263\001\377n\251\002\377Z\223\001\377a\220\032\377\335" + "\317\305\377\377\362\365\377\373\370\361\377\225\273W\377S\220\000\377V\222" + "\001\377W\225\002\377Y\225\002\377X\217\002\377Z\232\002\377\\\235\007\377{\272(\377" + "d\240\010\377`\226\002\377l\245\002\377p\251\001\377j\236\002\377n\246\001\377j\251" + "\001\377f\245\007\377i\251\022\377h\250\014\377[\233\001\377^\240\001\377`\242\002\377" + "_\236\002\377i\251\010\377m\254\015\377Z\232\001\377]\235\002\377^\236\001\377_\240" + "\001\377i\254\004\377`\241\001\377a\234\002\377g\234\002\377r\250\002\377o\240\002\377" + "o\240\002\377k\234\001\377g\235\002\377h\246\002\377i\253\003\377h\243\001\377n\245\001" + "\377p\246\002\377q\253\001\377j\235\002\377f\236\002\377c\227\002\377b\231\001\377i\245" + "\001\377g\241\001\377n\256\005\377d\244\004\377f\240\002\377n\243\001\377s\246\001\377" + "m\242\001\377f\230\002\377h\233\002\377m\246\001\377m\245\001\377p\256\001\377m\251\002" + "\377m\247\001\377l\250\003\377v\267\014\377e\247\002\377a\243\001\377`\241\002\377c" + "\233\002\377l\244\001\377s\253\001\377r\252\001\377v\254\002\377o\244\001\377j\234\001" + "\377h\241\002\377o\256\001\377t\264\003\377t\261\002\377q\253\002\377l\246\001\377f\235" + "\002\377q\254\010\377[\230\001\377X\220\001\377[\227\001\377^\230\001\377_\225\001\377" + "a\231\001\377c\242\001\377_\232\002\377]\224\001\377\\\225\000\377e\243\010\377g\250" + "\010\377^\224\001\377e\236\002\377a\232\001\377e\237\004\377l\247\012\377c\236\002\377" + "e\235\001\377f\235\002\377i\242\002\377j\246\002\377k\253\003\377f\246\001\377k\252\002" + "\377j\244\001\377m\243\001\377r\255\002\377d\233\002\377Z\217\003\377W\214\001\377n\242" + "\001\377o\251\001\377g\245\001\377d\240\001\377g\234\002\377o\252\002\377t\255\002\377" + "v\256\001\377n\243\001\377Z\224\000\377\243\264}\377\344\326\333\377\366\352\356" + "\377\373\363\366\377\373\362\363\377\257\311\177\377N\210\000\377Y\225\002\377" + "[\227\001\377Y\226\001\377Z\235\001\377f\250\014\377x\264\034\377r\257\017\377d\237" + "\002\377q\254\002\377s\255\002\377k\236\002\377f\233\002\377d\240\001\377f\250\005\377" + "\\\235\002\377`\241\006\377Y\226\001\377_\237\001\377c\240\002\377d\236\001\377h\250" + "\003\377a\241\002\377]\237\003\377\\\236\002\377W\225\001\377_\233\002\377g\247\002\377" + "d\243\001\377[\222\001\377b\227\002\377i\236\002\377c\227\001\377e\232\000\377f\237\000" + "\377p\253\010\377g\250\003\377g\244\001\377l\243\001\377l\243\002\377o\254\001\377k" + "\251\001\377e\235\002\377d\241\001\377b\240\002\377a\234\002\377j\246\001\377i\237\001" + "\377m\250\001\377h\243\001\377j\243\002\377n\242\001\377p\244\001\377s\251\001\377l\237" + "\001\377m\241\001\377p\245\002\377r\247\001\377w\263\001\377s\250\001\377q\247\002\377" + "o\246\001\377v\267\006\377f\247\003\377]\240\001\377[\241\002\377\\\233\001\377l\246" + "\001\377s\253\002\377s\255\002\377q\254\003\377j\246\003\377c\235\002\377d\242\001\377" + "g\250\002\377k\251\003\377k\245\003\377t\255\011\377s\253\014\377l\247\013\377u\260" + "\021\377b\234\001\377`\234\001\377^\227\002\377a\231\002\377f\241\001\377f\237\001\377" + "i\243\001\377a\227\001\377X\217\000\377e\243\021\377~\271/\377a\233\001\377^\222\002" + "\377a\231\001\377g\235\003\377q\244\007\377m\241\002\377k\236\002\377m\232\001\377n\236" + "\001\377i\233\002\377_\222\001\377_\232\002\377d\246\002\377o\255\004\377r\252\001\377" + "}\261\001\377y\254\002\377^\223\002\377X\216\002\377T\212\002\377u\246\002\377w\255\002" + "\377e\237\001\377e\240\002\377i\237\002\377p\252\001\377h\234\002\377o\244\002\377l\242" + "\001\377V\222\000\377\331\320\317\377\324\303\313\377\341\317\331\377\363\345" + "\354\377\353\332\332\377\364\355\351\377y\251\061\377V\231\000\377W\221\001\377" + "_\236\004\377n\257\023\377p\257\023\377l\254\014\377p\260\013\377j\251\002\377p\252" + "\002\377s\245\001\377l\237\001\377b\226\001\377f\243\001\377j\254\003\377\\\236\001\377" + "Z\234\002\377Y\232\001\377]\234\001\377f\242\001\377e\234\001\377d\244\002\377`\243\002" + "\377_\243\005\377V\234\001\377T\220\002\377f\243\001\377k\250\001\377g\247\001\377]\224" + "\001\377_\227\000\377t\246\027\377\223\272G\377\242\277b\377u\215\071\377^\234" + "\011\377^\237\001\377f\240\002\377m\250\001\377m\252\001\377h\247\002\377d\245\001\377" + "c\243\001\377b\244\001\377]\234\001\377b\244\001\377e\244\002\377g\235\002\377p\251\001" + "\377m\244\001\377l\246\001\377j\237\002\377o\244\001\377t\255\001\377q\250\001\377q\252" + "\001\377p\244\002\377t\253\002\377y\263\002\377y\263\001\377u\253\001\377r\245\002\377" + "r\255\001\377h\240\001\377c\242\001\377e\247\004\377a\234\002\377q\252\002\377v\245\002" + "\377z\260\001\377n\254\004\377m\257\011\377d\243\001\377g\247\001\377g\245\001\377i" + "\245\001\377j\242\004\377~\263\032\377\203\263\040\377\202\264\037\377s\254\013\377" + "g\232\002\377n\245\007\377`\226\002\377`\224\002\377f\242\001\377f\240\001\377g\243\002" + "\377f\236\001\377f\240\003\377\205\274\071\377\200\270\066\377d\233\002\377b\230" + "\002\377`\226\002\377d\233\001\377z\260\015\377m\241\003\377g\226\001\377k\231\002\377" + "n\234\001\377j\234\001\377e\231\001\377`\225\001\377c\240\002\377e\243\002\377h\237\002" + "\377\210\267\001\377y\251\001\377_\225\002\377^\225\001\377X\214\001\377v\247\002\377" + "y\256\001\377e\232\002\377f\233\002\377m\240\002\377l\237\001\377]\221\002\377t\251\001" + "\377t\257\000\377k\233\034\377\326\301\315\377\313\267\301\377\347\331\343\377" + "\367\356\364\377\362\345\352\377\354\332\332\377\357\354\326\377W\221\011" + "\377Q\221\000\377c\244\011\377q\260\030\377e\246\006\377_\240\002\377[\225\002\377" + "d\244\001\377n\247\002\377u\251\001\377u\247\002\377k\236\002\377n\252\002\377l\251\002" + "\377Z\231\002\377T\225\002\377[\234\004\377a\236\003\377f\244\001\377f\240\001\377e\247" + "\002\377^\237\002\377Y\230\001\377U\221\001\377Y\225\002\377d\243\002\377d\241\002\377" + "b\240\002\377X\225\000\377\253\306s\377\363\357\336\377\353\335\332\377\345\326" + "\322\377\311\273\261\377e\212\"\377^\237\000\377d\240\001\377m\250\001\377l\246" + "\001\377b\232\002\377^\226\001\377^\236\001\377k\255\010\377o\257\007\377d\245\000\377" + "c\240\002\377g\234\002\377r\254\002\377k\243\002\377i\243\001\377e\234\001\377l\244\001" + "\377t\260\001\377v\257\001\377v\253\002\377o\240\002\377u\247\002\377z\262\001\377|\262" + "\001\377z\255\002\377r\243\003\377t\250\001\377n\243\002\377j\243\002\377p\254\003\377" + "l\245\001\377v\257\004\377q\245\001\377u\255\002\377t\263\007\377i\252\002\377e\245\002" + "\377o\254\001\377q\252\001\377o\247\002\377l\241\002\377{\257\014\377\204\263\027\377" + "\201\261\022\377r\252\004\377m\245\001\377f\236\002\377b\236\002\377d\236\002\377j\246" + "\002\377i\242\001\377i\242\001\377e\237\002\377t\255\030\377\220\304E\377u\254\032" + "\377g\233\001\377f\226\001\377f\225\001\377f\226\001\377p\252\001\377m\247\002\377c\230" + "\002\377d\232\001\377j\241\002\377g\233\002\377e\236\002\377d\236\001\377e\241\001\377" + "f\241\001\377d\227\002\377\201\261\002\377y\252\002\377g\233\001\377b\232\002\377c\230" + "\001\377u\250\002\377|\260\001\377j\236\002\377g\233\002\377i\235\002\377k\236\001\377" + "e\231\002\377{\256\001\377\203\273\014\377\230\262`\377\317\266\304\377\271\236" + "\252\377\350\332\344\377\360\342\353\377\341\316\325\377\335\307\307\377" + "\334\304\303\377\326\340\261\377`\236\020\377n\255\035\377x\267$\377e\244\004" + "\377a\233\001\377[\220\002\377e\235\001\377n\244\001\377q\245\002\377r\243\001\377t\254" + "\002\377s\253\001\377s\247\001\377d\234\001\377P\221\002\377m\251\003\377l\244\002\377" + "d\234\001\377e\244\003\377f\247\003\377`\240\002\377\\\222\002\377\\\225\002\377^\234" + "\002\377_\241\003\377X\227\000\377s\242\026\377\336\343\246\377\352\326\322\377" + "\335\306\276\377\330\303\273\377\314\271\260\377\330\311\306\377\236\245" + "r\377[\234\000\377g\250\002\377e\243\001\377d\234\001\377b\231\001\377_\230\001\377^" + "\224\001\377b\232\001\377l\251\004\377n\255\003\377h\242\001\377n\243\001\377w\261\001" + "\377m\241\002\377k\242\002\377e\233\001\377m\251\002\377u\260\002\377v\254\002\377u\250" + "\001\377q\243\002\377w\250\002\377}\264\002\377~\262\001\377z\255\001\377n\240\001\377" + "o\247\002\377n\245\002\377j\242\002\377n\252\002\377s\257\007\377n\250\003\377l\244\002" + "\377p\253\001\377s\260\003\377n\256\001\377l\246\001\377n\251\002\377t\256\001\377p\251" + "\001\377o\246\002\377|\262\014\377w\255\010\377m\246\001\377k\245\001\377h\243\002\377" + "e\243\001\377c\235\001\377f\236\001\377x\263\006\377n\242\002\377l\240\001\377d\234\001" + "\377d\231\014\377\212\301B\377l\253\020\377h\244\004\377i\240\002\377l\241\002\377" + "g\230\001\377r\253\001\377l\246\001\377h\247\002\377e\241\001\377o\250\004\377e\234\002" + "\377o\251\011\377s\256\017\377k\251\003\377h\240\001\377k\234\001\377\202\262\002\377" + "s\242\002\377h\234\001\377g\245\002\377j\250\002\377p\252\001\377x\260\002\377r\246\001" + "\377]\225\002\377g\235\003\377f\232\003\377q\244\002\377q\246\001\377i\245\000\377\245" + "\263z\377\321\275\307\377\323\277\313\377\360\345\357\377\362\347\360\377" + "\357\345\352\377\342\314\320\377\341\314\314\377\346\315\303\377\231\272" + "T\377i\246\014\377g\245\005\377_\224\002\377`\227\001\377d\230\001\377i\234\002\377" + "p\243\002\377o\241\002\377o\243\002\377s\255\001\377r\251\001\377q\245\002\377j\236\002" + "\377T\223\002\377v\255\002\377j\242\001\377e\241\002\377i\246\004\377f\242\001\377f\236" + "\002\377d\227\001\377g\235\001\377d\241\002\377]\234\002\377{\254\060\377\365\362\337" + "\377\332\305\277\377\317\265\260\377\330\302\275\377\322\274\272\377\311" + "\262\255\377\301\257\251\377\276\264\242\377U\223\002\377]\236\002\377a\237\002" + "\377c\234\002\377a\234\002\377a\236\002\377`\225\002\377c\237\001\377c\236\001\377g\244" + "\001\377l\243\002\377s\251\001\377{\263\001\377n\240\002\377m\241\001\377j\241\001\377" + "k\242\002\377o\251\001\377o\247\001\377k\243\002\377j\240\001\377p\251\001\377y\262\001" + "\377x\262\001\377x\262\001\377k\237\002\377j\242\001\377j\240\001\377j\243\002\377j\243" + "\002\377m\247\001\377k\242\002\377o\242\001\377s\252\002\377t\244\002\377t\255\002\377" + "u\257\001\377k\242\001\377m\247\001\377i\242\001\377l\245\001\377s\255\005\377f\241\001" + "\377e\243\001\377i\247\001\377g\243\001\377e\243\002\377d\232\001\377o\247\005\377u\261" + "\011\377n\250\001\377n\244\001\377l\242\001\377a\226\002\377u\260\021\377d\245\005\377" + "_\241\003\377k\252\022\377n\252\021\377k\243\005\377o\246\001\377t\252\002\377p\251" + "\001\377k\243\001\377m\244\002\377k\233\002\377j\235\002\377i\235\002\377q\253\003\377" + "y\257\001\377\177\255\001\377\207\264\001\377o\235\002\377e\231\002\377_\222\001\377" + "b\234\001\377m\252\001\377u\257\002\377j\234\002\377_\223\001\377n\242\001\377j\237\001" + "\377k\242\001\377c\227\002\377_\234\000\377\262\272\213\377\303\254\266\377\324" + "\277\312\377\336\316\333\377\372\365\371\377\355\341\351\377\344\321\331" + "\377\335\304\310\377\327\277\277\377\347\324\276\377t\247\025\377[\220\001\377" + "W\216\000\377a\233\000\377e\234\000\377k\241\000\377p\246\000\377n\243\001\377n\250\001" + "\377l\246\002\377n\246\002\377h\235\002\377d\236\001\377_\233\002\377z\260\001\377h\241" + "\002\377k\251\006\377x\261\031\377i\245\006\377i\246\003\377b\231\001\377c\235\002\377" + "^\233\000\377\217\265?\377\356\344\327\377\323\273\265\377\313\257\246\377" + "\341\315\315\377\334\313\315\377\307\263\265\377\266\240\235\377\272\244" + "\236\377\313\273\261\377Y\226\011\377_\237\003\377a\232\002\377_\226\001\377]\225" + "\002\377b\241\002\377c\237\001\377e\243\001\377c\234\002\377i\240\001\377k\236\002\377" + "{\255\002\377\201\263\001\377q\243\002\377q\250\002\377m\245\001\377l\240\001\377n\245" + "\001\377p\250\001\377h\235\002\377i\240\002\377q\254\002\377|\264\002\377}\263\002\377" + "z\263\001\377n\246\001\377m\245\001\377l\250\000\377h\245\000\377o\247\011\377\203\266" + "\035\377|\260\023\377n\241\001\377v\254\001\377x\247\002\377}\256\001\377|\257\001\377" + "s\246\002\377t\256\001\377n\245\001\377m\243\001\377j\243\001\377e\234\002\377e\237\002" + "\377j\243\001\377q\251\002\377c\236\001\377c\237\001\377k\251\004\377d\242\002\377o\255" + "\005\377o\250\002\377p\245\001\377o\243\003\377x\263\012\377g\241\000\377e\246\006\377" + "_\240\023\377d\243\024\377g\241\007\377w\255\005\377{\256\001\377z\261\001\377v\257" + "\003\377s\254\006\377o\243\005\377k\237\002\377h\234\001\377t\253\003\377\200\265\002\377" + "\211\264\001\377\214\263\002\377w\245\001\377k\242\002\377c\227\001\377_\227\001\377" + "i\247\001\377p\254\001\377d\225\002\377f\230\002\377o\241\002\377p\247\001\377h\235\002" + "\377a\230\001\377U\216\000\377\275\301\232\377\305\247\252\377\303\242\243\377" + "\347\325\335\377\364\352\362\377\364\347\357\377\346\323\334\377\312\257" + "\264\377\340\313\315\377\316\265\261\377\316\316\230\377Z\214\022\377a\225" + "\035\377`\222\"\377`\217&\377m\235\060\377p\242%\377e\235\016\377f\240\012\377" + "h\243\010\377c\234\004\377a\223\001\377d\237\001\377e\237\003\377x\261\005\377f\234" + "\000\377y\261\040\377r\257\040\377o\257\025\377f\247\005\377e\242\001\377e\235\001\377" + "\226\273G\377\354\336\316\377\304\251\245\377\342\311\310\377\327\301\277" + "\377\333\310\312\377\327\310\316\377\313\275\302\377\277\256\257\377\271" + "\246\242\377\320\276\270\377c\232\013\377d\241\001\377c\227\001\377c\226\002\377" + "h\241\001\377e\236\001\377o\256\010\377c\240\001\377a\231\001\377g\242\002\377j\235" + "\002\377}\257\001\377\201\263\001\377w\252\002\377q\246\001\377n\246\002\377l\240\002\377" + "r\247\001\377r\252\001\377f\232\002\377g\241\002\377v\260\001\377~\261\002\377{\252\001" + "\377|\257\001\377u\252\001\377v\263\010\377t\256\014\377x\263\031\377\211\300\063" + "\377\205\273+\377~\266\032\377r\254\002\377w\261\001\377|\262\002\377{\255\002\377" + "v\250\002\377p\237\001\377y\253\002\377z\252\002\377n\236\001\377l\237\001\377j\241\001" + "\377l\243\001\377n\241\002\377p\250\002\377g\235\002\377j\244\004\377m\250\006\377`\232" + "\001\377l\251\006\377r\251\001\377{\256\001\377p\241\001\377t\253\004\377o\241\001\377" + "m\246\003\377g\245\030\377Y\230\013\377l\246\027\377\211\273%\377\204\267\015\377" + "}\262\002\377}\266\012\377z\264\024\377v\260\031\377t\255\026\377\205\274'\377" + "\205\275\035\377t\246\001\377\201\255\001\377\221\271\001\377o\237\002\377f\231\002" + "\377i\242\001\377d\240\002\377d\243\002\377n\254\002\377j\235\001\377j\231\002\377r\241" + "\002\377s\245\001\377i\235\001\377a\230\002\377S\214\000\377\321\316\265\377\316\260" + "\263\377\332\277\306\377\366\352\362\377\373\367\372\377\365\355\362\377" + "\354\337\345\377\337\311\315\377\317\266\267\377\302\252\244\377\324\271" + "\253\377\270\266\232\377emd\377aff\377^bg\377_ej\377gpo\377o\200l\377s\216" + "b\377n\217M\377w\240G\377f\226(\377`\225\030\377b\225\021\377v\254\017\377k" + "\240\012\377o\246\031\377k\247\030\377h\244\017\377a\233\001\377i\244\000\377\272" + "\321u\377\331\304\264\377\301\241\227\377\302\242\232\377\337\313\310\377" + "\336\314\316\377\333\313\321\377\341\324\335\377\312\275\310\377\273\254" + "\265\377\274\251\253\377\310\266\262\377^\227\014\377c\236\002\377b\226\001\377" + "l\242\002\377r\253\001\377l\246\001\377j\252\004\377c\246\002\377`\230\001\377i\243\002" + "\377m\237\001\377\200\262\001\377w\247\002\377r\246\002\377p\247\001\377o\244\001\377" + "o\241\002\377v\256\002\377x\261\001\377e\233\002\377g\236\001\377u\251\002\377\200\263" + "\002\377z\252\001\377\206\272\016\377\203\271\031\377\211\301-\377\200\274-\377" + "o\256\027\377k\250\012\377p\255\004\377o\246\003\377m\241\001\377p\245\001\377q\246" + "\002\377r\253\002\377p\253\002\377m\236\001\377~\260\001\377|\251\001\377p\234\001\377" + "u\250\001\377s\250\001\377q\245\001\377u\252\000\377f\232\001\377r\251\006\377o\247\004" + "\377j\241\002\377g\237\001\377i\242\003\377q\250\002\377\205\265\001\377|\256\001\377" + "o\246\002\377i\237\001\377i\243\002\377m\252\035\377d\242\040\377o\254*\377l\250" + "\027\377\203\265\017\377\204\265\005\377z\255\002\377s\253\006\377v\261\027\377|\266" + "!\377~\267\040\377|\267\025\377s\250\000\377x\246\001\377\206\262\002\377z\252\002" + "\377i\234\001\377q\253\001\377l\246\001\377k\245\002\377o\252\001\377r\253\001\377o\240" + "\001\377u\250\001\377n\240\001\377j\234\002\377e\235\002\377Y\212\000\377\321\311\261" + "\377\321\266\271\377\327\277\307\377\347\325\337\377\345\323\336\377\336" + "\314\326\377\341\317\327\377\314\271\274\377\271\241\240\377\301\251\250" + "\377\212gf\377\306\250\226\377xei\377~ow\377XI\\\377XKa\377[Ne\377XLd\377" + "i`r\377tn}\377}{\206\377\201\206\210\377z\205x\377x\212d\377p\222C\377n\226" + "?\377f\225,\377l\236.\377d\227\034\377d\226\016\377\271\314q\377\301\254\237" + "\377\251\215\213\377\313\261\254\377\330\304\300\377\341\320\320\377\362" + "\350\353\377\324\306\316\377\346\332\343\377\311\274\306\377\275\251\262" + "\377\271\243\243\377\330\302\274\377i\237\022\377i\240\001\377o\241\002\377y\257" + "\001\377n\241\002\377a\227\001\377c\244\001\377g\251\003\377e\235\002\377p\246\001\377" + "t\245\002\377\202\263\001\377c\227\002\377f\235\001\377j\245\001\377m\245\002\377o\244" + "\001\377z\265\006\377x\262\003\377p\247\002\377p\243\001\377w\252\001\377|\264\000\377" + "\202\273\015\377\202\271\027\377v\261\016\377w\261\015\377]\225\000\377c\240\001" + "\377i\240\001\377q\244\001\377r\242\002\377x\251\002\377q\240\002\377p\241\001\377l\242" + "\002\377n\244\001\377y\253\001\377\201\262\001\377r\240\001\377s\241\002\377v\247\001\377" + "q\244\002\377q\246\002\377\201\271\012\377_\222\002\377l\246\004\377l\245\001\377m\241" + "\001\377q\251\001\377h\232\001\377s\250\002\377\177\260\001\377\201\263\004\377z\256" + "\020\377n\244\014\377g\237\003\377l\246\022\377p\254$\377i\247\034\377c\242\005\377" + "n\247\002\377z\253\002\377\200\260\002\377z\255\002\377u\257\006\377y\262\021\377\202" + "\273\036\377t\257\013\377u\254\002\377z\252\001\377z\247\002\377\202\261\001\377y\251" + "\002\377v\247\001\377t\250\001\377v\243\002\377\177\257\001\377v\251\001\377u\257\001\377" + "l\245\001\377h\235\002\377c\226\002\377d\231\001\377[\216\000\377\332\325\272\377\342" + "\307\311\377\335\302\307\377\361\345\354\377\375\375\374\377\367\354\363" + "\377\357\336\347\377\333\306\312\377\312\260\261\377\262\225\223\377\312" + "\260\252\377\317\264\254\377\307\256\254\377\332\306\306\377\321\277\304" + "\377\324\312\321\377\260\237\257\377wf\177\377\200m\211\377\233\215\242\377" + "\212|\222\377\207v\215\377\201r\206\377\226\207\220\377zoz\377e`h\377ggh" + "\377t|r\377\216\227\200\377\313\320\253\377\330\300\271\377\254\214\210\377" + "\312\260\254\377\330\303\277\377\323\272\272\377\357\337\343\377\332\311" + "\321\377\360\344\355\377\343\330\345\377\311\274\311\377\302\257\267\377" + "\305\260\257\377\320\277\264\377^\232\002\377m\243\001\377x\253\002\377z\252\002" + "\377m\235\002\377h\240\001\377f\246\001\377d\241\002\377j\250\001\377s\253\001\377x\252" + "\001\377~\255\002\377`\223\002\377a\225\001\377d\244\001\377l\252\001\377p\252\001\377" + "t\257\002\377q\247\001\377v\256\002\377v\250\001\377\200\267\002\377\201\270\002\377" + "\201\271\006\377s\251\002\377q\251\002\377\200\271\013\377e\232\001\377f\233\001\377" + "l\243\001\377i\231\002\377o\240\002\377|\255\002\377y\246\002\377r\237\002\377n\236\001" + "\377u\250\001\377{\260\002\377z\250\001\377w\241\002\377{\251\001\377w\250\001\377s\247" + "\001\377y\260\001\377\202\271\005\377_\223\002\377i\243\002\377p\251\003\377n\237\001\377" + "p\247\001\377l\236\001\377r\244\002\377x\252\001\377\177\261\003\377\210\267\027\377" + "\221\276\060\377m\243\006\377j\243\003\377w\260\030\377d\243\015\377l\253\017\377" + "s\255\006\377r\243\002\377v\253\001\377}\266\014\377k\247\005\377s\255\023\377\204" + "\274(\377l\240\012\377q\240\002\377~\255\001\377{\250\002\377x\245\001\377\177\261" + "\001\377y\250\002\377x\245\002\377|\247\002\377\204\260\001\377t\243\002\377p\247\002\377" + "l\247\001\377d\236\002\377Y\215\001\377]\216\001\377X\217\000\377\326\320\262\377\343" + "\303\302\377\354\321\325\377\341\321\333\377\363\353\360\377\353\335\344" + "\377\360\335\337\377\340\312\307\377\337\310\304\377\347\317\312\377\353" + "\326\323\377\345\323\321\377\360\341\346\377\361\347\354\377\365\360\363" + "\377\366\356\363\377\344\327\341\377\340\322\334\377\346\332\343\377\370" + "\361\365\377\360\351\355\377\336\322\333\377\303\256\267\377\322\276\275" + "\377\312\262\255\377\271\233\220\377\260\223\214\377\232\202\177\377\263" + "\235\226\377\301\241\220\377\215oh\377\272\233\226\377\307\256\252\377\333" + "\310\310\377\347\327\333\377\364\352\360\377\327\307\321\377\337\320\332" + "\377\325\310\326\377\303\263\300\377\277\251\260\377\305\253\252\377\310" + "\274\253\377_\240\000\377h\241\001\377k\232\002\377z\251\002\377t\245\001\377n\244" + "\001\377g\241\001\377f\236\001\377m\246\001\377u\254\002\377|\254\002\377w\247\001\377" + "[\216\002\377^\223\001\377k\250\003\377u\264\004\377r\250\001\377t\252\001\377t\251\001" + "\377u\256\001\377u\252\001\377{\260\001\377~\257\001\377\204\264\001\377\203\263\002" + "\377\200\263\002\377|\264\003\377a\223\002\377j\242\002\377k\245\002\377m\244\001\377" + "w\255\001\377t\245\002\377u\242\002\377w\246\002\377w\247\001\377v\254\001\377o\242\001" + "\377r\244\002\377\216\271\016\377\210\264\011\377{\255\002\377\177\267\002\377\201" + "\270\002\377~\261\002\377b\237\001\377c\233\002\377h\243\002\377o\252\004\377p\250\001" + "\377o\246\002\377q\251\003\377t\245\001\377~\256\001\377\207\265\020\377\226\277." + "\377l\240\003\377o\246\003\377t\255\007\377f\244\005\377r\257\022\377m\243\003\377|" + "\257\002\377w\255\001\377m\247\003\377\213\270\064\377p\251\033\377\200\271)\377" + "d\231\003\377k\235\002\377r\251\002\377r\251\002\377o\243\001\377u\253\000\377x\257\001" + "\377v\255\001\377w\256\001\377u\254\002\377m\241\001\377n\237\001\377r\255\002\377`\226" + "\002\377Y\214\002\377_\220\002\377[\220\000\377\305\307\223\377\344\277\273\377\352" + "\313\312\377\337\312\322\377\356\341\351\377\354\336\340\377\362\337\334" + "\377\362\343\337\377\367\356\355\377\342\316\317\377\277\245\247\377\344" + "\320\324\377\365\356\360\377\271\244\260\377\364\355\360\377\324\300\314" + "\377\342\322\334\377\360\346\354\377\357\345\352\377\305\263\272\377\352" + "\340\344\377\353\336\341\377\314\262\262\377\334\305\301\377\347\323\315" + "\377\342\313\302\377\334\300\263\377\343\303\257\377\333\274\243\377\303" + "\242\212\377\312\254\232\377\306\251\237\377\277\244\236\377\354\331\332" + "\377\332\305\314\377\356\342\352\377\332\311\323\377\320\276\311\377\306" + "\266\302\377\276\254\265\377\302\252\256\377\321\270\263\377\267\270\214" + "\377b\244\000\377i\243\001\377j\232\001\377|\255\002\377w\253\002\377l\235\001\377h\231" + "\002\377i\235\001\377l\237\001\377u\251\002\377{\256\001\377k\233\002\377Z\216\001\377" + "m\250\010\377x\266\014\377p\252\002\377r\246\002\377s\247\002\377v\260\002\377}\270" + "\013\377u\253\002\377{\256\001\377|\255\002\377z\246\002\377\203\261\002\377\216\275" + "\002\377u\260\002\377c\225\002\377l\245\001\377q\255\002\377o\247\001\377x\264\002\377" + "j\240\001\377k\235\002\377m\236\002\377t\251\001\377s\254\002\377n\245\001\377o\243\001" + "\377\221\302\036\377\203\266\011\377\202\267\003\377\202\272\004\377|\260\001\377" + "|\254\002\377g\243\002\377h\241\002\377e\236\001\377\200\270\016\377w\257\004\377o\247" + "\002\377q\250\002\377r\246\001\377|\253\002\377\211\267\016\377\177\255\013\377p\242" + "\003\377k\242\001\377i\243\002\377k\251\005\377j\250\005\377k\243\003\377u\254\001\377" + "r\246\001\377\204\256\022\377\260\277]\377q\250\"\377\202\271/\377n\246\006\377" + "o\245\001\377o\245\001\377u\254\012\377z\261\025\377r\254\015\377l\251\006\377k\247" + "\002\377u\262\011\377o\255\006\377i\244\001\377l\245\001\377l\245\002\377g\240\001\377" + "c\227\001\377^\217\002\377V\215\000\377\255\271x\377\340\270\262\377\337\275\266" + "\377\360\334\334\377\360\340\342\377\361\342\341\377\340\313\315\377\355" + "\340\341\377\370\360\360\377\272\230\234\377\311\255\261\377\367\355\356" + "\377\334\310\312\377\344\323\331\377\345\330\336\377\320\276\311\377\352" + "\334\345\377\330\307\315\377\261\233\243\377\317\276\276\377\375\373\373" + "\377\336\314\316\377\221wx\377\317\272\264\377\347\333\327\377\353\333\327" + "\377\353\326\314\377\336\303\261\377\344\304\254\377\351\314\262\377\357" + "\327\302\377\325\273\254\377\332\304\274\377\346\324\325\377\326\302\312" + "\377\353\335\350\377\350\334\345\377\275\254\270\377\276\255\273\377\274" + "\250\263\377\317\267\271\377\340\304\303\377\235\261_\377a\237\000\377f\233" + "\002\377u\251\002\377\204\265\002\377o\237\001\377l\236\001\377i\232\001\377k\241\002\377" + "o\244\001\377p\246\001\377p\246\001\377i\231\001\377l\242\006\377y\264\022\377p\254" + "\003\377q\255\001\377o\245\001\377q\253\001\377u\262\004\377m\246\002\377n\245\001\377" + "z\257\001\377w\246\002\377i\223\002\377|\255\001\377\206\272\003\377\200\272\023\377" + "h\234\000\377k\242\002\377w\262\002\377\201\271\001\377o\252\002\377q\260\014\377i\241" + "\002\377o\243\001\377s\247\001\377t\254\001\377p\243\001\377v\246\001\377\212\275\004\377" + "\206\272\003\377\177\264\001\377|\257\001\377w\245\002\377u\247\001\377b\235\002\377" + "e\237\002\377d\231\002\377\200\267\022\377z\260\011\377i\237\001\377k\244\002\377s" + "\253\003\377u\251\001\377~\261\005\377q\247\001\377g\235\001\377h\235\002\377e\231\001" + "\377j\246\004\377g\245\005\377f\245\010\377g\244\005\377c\231\001\377\241\263,\377" + "z\244\036\377e\241\016\377u\260\027\377w\254\010\377w\244\001\377\204\264\021\377" + "\213\272%\377\203\265\032\377i\242\005\377Z\224\001\377b\233\001\377r\253\001\377" + "s\247\001\377l\240\001\377h\243\001\377d\234\002\377f\241\001\377f\236\005\377\\\216" + "\006\377W\205\023\377\224\243p\377\352\310\312\377\312\245\250\377\356\330\330" + "\377\355\334\332\377\332\312\307\377\307\263\261\377\370\362\362\377\320" + "\272\266\377\247zr\377\365\341\335\377\344\315\313\377\335\311\311\377\343" + "\326\334\377\345\327\340\377\351\333\343\377\360\346\354\377\355\343\350" + "\377\336\317\320\377\374\361\357\377\374\367\365\377\334\307\277\377\207" + "g[\377\303\246\233\377\367\360\355\377\333\312\305\377\311\262\254\377\331" + "\301\267\377\342\310\267\377\316\261\236\377\341\305\261\377\363\346\327" + "\377\356\340\327\377\356\341\336\377\345\325\330\377\342\323\334\377\325" + "\306\324\377\267\245\265\377\274\251\271\377\277\255\272\377\337\306\304" + "\377\347\315\306\377p\236\026\377e\234\000\377j\241\001\377{\262\001\377\200\264" + "\001\377t\245\002\377o\242\002\377k\243\001\377q\256\002\377p\256\001\377m\247\001\377" + "p\251\001\377q\246\002\377\202\264\011\377m\241\004\377m\246\001\377m\252\002\377g\242" + "\002\377k\247\002\377k\250\002\377d\234\002\377t\253\003\377\177\264\002\377w\247\001\377" + "p\240\001\377z\257\002\377y\256\001\377\177\270\010\377r\244\002\377|\256\001\377\206" + "\273\002\377\203\263\000\377q\246\002\377u\261\011\377k\247\001\377p\251\001\377t\247" + "\001\377u\254\001\377z\253\001\377\205\271\001\377\205\272\002\377~\263\001\377|\260" + "\001\377}\260\002\377r\243\001\377s\247\002\377_\236\004\377c\232\001\377l\243\001\377" + "u\254\006\377~\265\024\377b\232\002\377e\237\001\377m\253\007\377r\255\005\377y\263" + "\011\377i\242\002\377e\235\003\377d\232\002\377i\235\001\377q\252\006\377k\246\004\377" + "b\236\002\377k\245\013\377h\234\002\377\213\247\015\377e\227\000\377c\232\002\377h" + "\241\003\377v\255\007\377u\252\002\377x\256\011\377k\240\002\377~\261\001\377t\247\001" + "\377]\226\001\377b\232\001\377m\247\001\377u\251\001\377v\253\001\377n\245\001\377c\235" + "\002\377g\244\024\377i\234*\377b\220\063\377r\212b\377\200\203~\377\340\303\304" + "\377\347\325\324\377\371\363\363\377\366\356\357\377\352\331\336\377\365" + "\353\354\377\376\373\372\377\344\323\313\377\252\200i\377\354\322\310\377" + "\340\310\305\377\341\315\317\377\353\336\345\377\341\322\334\377\350\333" + "\343\377\346\330\340\377\332\311\322\377\323\277\301\377\332\302\277\377" + "\361\335\321\377\341\307\265\377\204V;\377\330\275\252\377\375\375\375\377" + "\354\340\334\377\270\234\233\377\302\246\243\377\317\270\261\377\351\323" + "\304\377\340\305\257\377\347\314\272\377\365\352\341\377\353\340\332\377" + "\373\364\363\377\360\350\353\377\303\255\274\377\263\235\255\377\267\242" + "\261\377\315\262\270\377\336\275\257\377\316\277\230\377h\237\005\377i\237" + "\001\377u\261\006\377s\252\002\377|\263\001\377x\253\002\377v\262\002\377q\254\002\377" + "u\256\004\377|\261\003\377v\252\001\377r\252\001\377r\253\002\377n\242\001\377i\232\002" + "\377n\245\002\377p\252\001\377l\247\002\377k\250\001\377l\251\001\377l\245\002\377u\254" + "\003\377\200\265\004\377s\242\001\377r\241\001\377v\256\001\377u\255\004\377\216\304" + "&\377x\255\016\377\224\303\034\377\204\265\000\377\177\260\001\377{\255\001\377y" + "\257\002\377n\247\002\377s\253\002\377x\254\002\377\177\263\001\377\207\273\001\377\207" + "\274\002\377\203\271\001\377}\260\001\377\203\272\003\377{\256\001\377o\242\001\377t" + "\253\001\377r\254!\377f\232\000\377q\246\001\377q\247\001\377\202\271\031\377m\252" + "\007\377c\241\003\377`\233\002\377i\247\003\377v\262\014\377n\246\002\377e\235\002\377" + "l\244\010\377o\247\007\377r\252\005\377i\241\002\377\\\225\001\377p\247\027\377p\241" + "\014\377u\243\011\377j\230\001\377k\241\002\377r\252\012\377o\251\007\377j\236\001\377" + "n\240\002\377x\250\001\377\200\255\002\377\203\262\001\377Y\224\001\377Y\225\001\377" + "d\241\001\377j\237\001\377o\241\001\377q\246\001\377i\242\002\377h\242\030\377r\222" + "g\377{\214\200\377\177\201\210\377\254\235\246\377\346\321\315\377\374\367" + "\365\377\370\361\361\377\277\250\250\377v[\\\377}db\377\272\241\225\377\363" + "\325\307\377\345\301\253\377\364\332\313\377\343\306\275\377\344\313\311" + "\377\336\311\316\377\334\313\323\377\344\322\332\377\316\271\301\377\326" + "\302\305\377\315\266\264\377\323\273\260\377\353\320\301\377\316\255\226" + "\377\216dD\377\372\357\346\377\365\354\347\377\344\330\326\377\331\307\307" + "\377\352\332\327\377\320\267\261\377\340\311\274\377\331\277\250\377\335" + "\301\255\377\361\341\323\377\346\322\311\377\361\341\337\377\346\324\327" + "\377\317\273\306\377\263\233\250\377\274\240\246\377\340\276\263\377\352" + "\306\275\377\231\261I\377m\247\002\377i\237\001\377n\250\001\377q\243\001\377\177" + "\265\001\377z\256\002\377r\253\001\377o\237\001\377t\243\002\377\201\257\004\377\205" + "\270\012\377y\261\010\377p\252\007\377c\234\002\377d\234\002\377s\255\001\377v\252" + "\002\377z\261\001\377s\253\001\377p\250\002\377r\251\002\377}\263\007\377~\263\002\377" + "|\255\003\377z\247\001\377\201\262\001\377z\257\002\377\200\271\037\377\210\276\063" + "\377\230\310>\377z\256\000\377{\254\001\377r\240\002\377r\246\001\377r\255\001\377" + "u\261\002\377v\256\003\377\205\271\001\377\213\276\001\377~\254\001\377\201\263\002\377" + "\202\265\002\377\207\275\006\377{\256\001\377s\252\001\377n\247\001\377|\265\061\377" + "m\250\013\377f\234\001\377o\250\006\377\204\272\040\377\177\266\033\377r\253\017" + "\377l\245\012\377q\251\014\377z\261\016\377r\255\010\377d\237\001\377j\245\010\377" + "{\260\024\377|\257\022\377s\246\020\377U\221\005\377h\235\020\377x\247\023\377r" + "\243\014\377f\234\002\377o\247\001\377p\251\001\377l\241\001\377q\245\001\377t\242\002" + "\377\200\262\003\377s\241\002\377x\252\003\377k\240\006\377c\230\001\377d\232\002\377" + "j\244\001\377j\241\002\377g\236\002\377j\244\010\377s\240\060\377|\204\205\377||" + "\207\377\212\177\220\377\326\307\313\377\370\353\351\377\372\361\354\377" + "\310\244\224\377O/$\377#\011\003\377#\014\005\377\024\000\000\377D%\035\377\330\261\233" + "\377\377\366\347\377\342\314\300\377\333\277\272\377\333\305\305\377\330" + "\276\302\377\276\247\255\377\276\250\251\377\275\243\240\377\337\307\274" + "\377\360\334\316\377\355\323\277\377\325\260\221\377\343\303\251\377\306" + "\257\237\377\251\221\210\377\266\241\235\377\274\250\251\377\343\326\327" + "\377\350\330\327\377\337\312\303\377\334\301\264\377\323\272\246\377\324" + "\271\247\377\372\362\354\377\357\337\340\377\315\266\303\377\266\233\254" + "\377\257\220\234\377\323\253\236\377\341\270\250\377\333\306\255\377f\235" + "\000\377m\247\002\377l\244\001\377q\254\001\377v\256\001\377x\262\002\377o\247\001\377" + "j\243\001\377o\242\001\377q\237\001\377u\243\001\377v\254\002\377\200\271\033\377~\267" + "-\377f\237\004\377e\233\001\377s\252\002\377|\257\001\377~\260\001\377|\256\001\377y" + "\254\001\377}\257\001\377\203\270\005\377}\260\001\377}\256\002\377\202\263\001\377\177" + "\256\002\377t\247\006\377\207\300/\377\205\276\066\377\210\302\062\377r\252\000\377" + "s\254\001\377s\255\003\377m\250\001\377p\255\004\377n\247\002\377\203\266\001\377\211" + "\275\002\377\205\267\001\377|\252\002\377\201\264\001\377\204\267\006\377|\257\001\377" + "{\260\002\377v\262\002\377q\251\001\377~\267!\377u\260\015\377`\225\001\377c\234\003" + "\377\201\266\031\377\214\276'\377\200\265\034\377\177\264\036\377\200\265\035" + "\377\200\266\030\377t\256\011\377c\235\002\377_\230\001\377d\241\002\377w\254\034" + "\377w\251)\377V\217\016\377p\241\030\377\205\255\034\377\217\265,\377o\245\020" + "\377t\256\012\377q\254\002\377m\244\002\377w\253\006\377~\257\004\377x\255\003\377m" + "\246\010\377m\245\015\377\202\263\"\377\203\262$\377d\226\002\377g\240\003\377" + "X\215\001\377f\235\024\377d\226'\377\177\217w\377\200|\207\377\210}\216\377" + "\241\225\237\377\362\342\333\377\350\321\313\377\355\323\306\377\236n[\377" + "\071\025\020\377bA+\377\320\307\317\377\244\241\267\377bLB\377M(\032\377\376" + "\354\330\377\355\317\271\377\373\352\337\377\326\254\225\377\347\315\277" + "\377\323\270\260\377\340\305\272\377\325\270\254\377\372\365\357\377\375" + "\372\364\377\365\336\307\377\300\241\207\377;&\035\377\034\006\014\377\"\012\017" + "\377\040\010\010\377<&#\377\234\204}\377\346\326\324\377\350\332\326\377\310" + "\256\241\377\352\322\302\377\334\303\256\377\363\344\327\377\371\363\360" + "\377\340\317\325\377\267\234\254\377\323\262\264\377\345\277\264\377\354" + "\317\304\377pdJ\377s\255\000\377q\246\001\377w\255\003\377z\266\005\377s\256\001\377" + "u\261\005\377i\243\002\377l\241\002\377x\253\001\377{\251\002\377~\253\002\377z\253\001" + "\377n\246\002\377n\252\034\377\207\275\071\377j\240\002\377{\257\001\377\207\267" + "\002\377\177\255\001\377z\255\002\377|\261\002\377~\260\001\377\212\276\010\377|\257" + "\002\377{\254\001\377\203\270\004\377y\257\007\377t\256\016\377\217\306?\377\207\300" + ";\377x\265\036\377r\261\001\377p\254\001\377r\260\007\377m\254\007\377i\243\001\377" + "~\260\001\377\230\303\002\377\177\256\001\377u\246\001\377t\252\004\377\212\301\036" + "\377\211\300\034\377y\260\003\377{\257\001\377z\261\001\377s\250\001\377x\257\013\377" + "|\262\005\377e\236\002\377c\235\003\377w\255\011\377\206\270\030\377}\262\017\377" + "s\253\011\377g\237\002\377z\260\022\377~\264\025\377e\240\006\377^\234\003\377b\237" + "\004\377h\240\011\377e\236\021\377R\217\006\377a\230\016\377\221\264\063\377\204" + "\252*\377{\253\"\377v\255\031\377c\240\006\377m\251\022\377\203\266\"\377\210" + "\267\026\377w\250\002\377m\242\002\377r\251\013\377\203\266)\377\206\265\063\377" + "Y\211\001\377h\236\025\377h\232\034\377w\243<\377x\222\\\377\201{\206\377\205" + "w\210\377\226\203\223\377\301\260\265\377\267\237\245\377\372\362\357\377" + "\371\361\355\377\241\200}\377nP:\377\273\253|\377\307\305\260\377\247\251" + "\276\377\322\322\324\377\204dN\377\374\342\313\377\366\327\271\377\366\323" + "\260\377\366\320\252\377\370\334\276\377\366\335\306\377\357\317\275\377" + "\367\342\321\377\375\377\375\377\372\352\330\377\225t\\\377\065\034\015\377" + "B/'\377\201u{\377ymy\377^H@\377/\023\014\377\067\033\025\377\251\210u\377\333" + "\311\300\377\350\327\314\377\315\260\242\377\332\301\263\377\354\336\321" + "\377\340\317\310\377\351\331\331\377\322\261\262\377\353\303\261\377\373" + "\343\326\377\254zc\377\201tC\377y\261\011\377w\250\001\377{\257\003\377z\263\004" + "\377v\260\002\377t\257\001\377q\253\001\377o\246\002\377w\253\001\377\177\260\000\377" + "\177\255\001\377w\247\001\377n\245\001\377b\233\001\377\202\271)\377w\256\007\377~" + "\261\001\377\204\265\001\377\177\260\001\377{\254\001\377\200\262\001\377\200\262\001" + "\377\211\300\010\377u\250\002\377t\245\001\377\202\271\001\377}\267\015\377\204\276" + "\071\377\244\325`\377\217\307C\377x\265\024\377t\262\003\377y\265\006\377|\266" + "\015\377p\247\002\377s\251\001\377\206\270\002\377\204\264\002\377x\253\000\377{\262" + "\023\377\222\306=\377~\272\025\377q\252\001\377u\246\001\377~\257\001\377}\263\001" + "\377v\253\001\377p\247\007\377\202\265\007\377g\242\012\377c\240\007\377r\253\007\377" + "y\260\012\377\202\265\022\377p\247\006\377d\235\003\377v\255\025\377\200\266\036" + "\377t\254\017\377q\251\016\377b\231\001\377c\231\002\377^\233\007\377J\214\003\377" + "X\225\017\377\204\257\061\377e\226\024\377l\237\035\377v\252(\377`\233\016\377" + "t\257'\377|\262\"\377}\260\025\377r\243\002\377m\237\002\377r\247\005\377\203\270" + "\040\377w\255\031\377Y\222\005\377k\240#\377l\235/\377v\225^\377\200\200\211" + "\377~v\203\377\213|\215\377\234\210\225\377\271\241\246\377\321\272\270\377" + "\344\316\314\377\363\354\354\377\336\322\321\377\231\210\201\377\334\330" + "\273\377\346\340\303\377\355\347\314\377\333\321\303\377\265\225\215\377" + "\362\320\274\377\366\331\276\377\364\321\262\377\363\310\250\377\362\313" + "\250\377\362\316\261\377\365\326\303\377\341\271\251\377\357\320\265\377" + "tTJ\377)\031\034\377kZ\070\377\275\265\237\377\315\316\341\377\265\266\322\377" + "\325\327\333\377\213mK\377\067\031\024\377tL?\377\313\252\231\377\307\251\224" + "\377\262\217{\377\320\263\242\377\343\315\301\377\346\330\322\377\332\302" + "\303\377\306\225\203\377\330\246\211\377\371\343\323\377\303\242\223\377" + "\225\224y\377x\246-\377u\246\012\377\177\263\013\377{\257\004\377z\255\002\377" + "z\263\002\377x\263\003\377p\251\001\377s\253\001\377z\254\001\377}\255\001\377x\247\001" + "\377q\242\001\377u\247\001\377{\260\003\377~\263\003\377\177\261\001\377\203\264\001" + "\377\202\263\001\377~\250\002\377\203\263\002\377\201\264\001\377\205\273\004\377u" + "\250\001\377z\253\002\377\202\265\002\377\202\270\007\377\214\304K\377\227\314W\377" + "{\272$\377r\261\006\377r\255\001\377u\260\003\377t\254\002\377\177\257\001\377\212" + "\275\002\377\177\262\001\377v\256\001\377w\262\012\377\224\310D\377\213\300\064\377" + "u\260\000\377u\254\001\377z\256\001\377~\255\001\377\201\266\001\377v\250\002\377v\244" + "\002\377\207\267\022\377o\250!\377W\225\003\377h\245\016\377l\247\014\377|\263\037" + "\377m\247\024\377l\247\033\377j\246\026\377\200\266%\377n\243\006\377\203\264" + "\037\377l\241\013\377b\233\007\377^\233\023\377P\220\004\377Z\231\005\377n\243\017" + "\377y\253\036\377n\237\025\377x\253,\377d\234\034\377\205\274;\377{\262\"\377" + "x\256\032\377`\226\003\377[\213\001\377V\210\001\377y\254\060\377\177\264!\377\177" + "\263(\377{\253=\377}\247V\377\177\213\177\377\203~\213\377\207{\214\377\214" + "|\215\377\305\257\260\377\256\221\221\377\301\243\231\377\275\235\220\377" + "\303\247\236\377\325\300\273\377\353\334\332\377\370\364\360\377\374\373" + "\365\377\364\346\330\377\326\254\235\377\310\241\242\377\332\262\261\377" + "\341\273\274\377\333\265\267\377\314\247\254\377\266\216\217\377\323\240" + "\177\377\341\301\262\377\277\232\225\377\220b_\377oCF\377\213cP\377\264\241" + "\202\377\333\324\262\377\330\327\312\377\341\342\331\377\343\345\333\377" + "\276\270\235\377\202hW\377\347\332\321\377\364\351\340\377\312\262\250\377" + "\245\215\203\377\317\265\247\377\324\274\261\377\344\322\313\377\347\324" + "\320\377\305\236\216\377\331\271\247\377\345\311\267\377\264\201l\377\223" + "\220\221\377\207\237|\377v\242\067\377t\251\017\377r\250\002\377p\246\001\377r" + "\257\002\377m\251\004\377q\256\002\377x\256\001\377y\245\002\377}\251\001\377|\252\001" + "\377{\247\002\377{\252\002\377{\253\001\377\177\266\003\377\207\301\015\377\207\273" + "\005\377\203\262\000\377\201\254\001\377\200\257\002\377~\261\001\377\177\270\003\377" + "t\247\001\377{\254\001\377\201\265\002\377\227\311/\377\203\273\063\377\210\301" + "E\377v\265\037\377q\255\003\377s\255\001\377u\261\002\377}\265\001\377\214\276\001\377" + "\203\264\001\377w\254\001\377y\267\016\377\233\320R\377\203\273)\377s\257\005\377" + "r\256\001\377w\261\001\377v\245\001\377~\256\001\377~\257\001\377{\252\002\377\221\263" + "\001\377\200\256\012\377\203\267D\377V\225\016\377Y\230\014\377_\236\016\377s\256" + "&\377y\256\032\377\206\270\040\377q\246\006\377}\263\033\377r\250\022\377~\262" + ".\377\210\272G\377\214\275U\377\204\270N\377Z\226\007\377Z\223\001\377a\231\001" + "\377t\247\030\377y\247\036\377y\252'\377m\242!\377\177\266.\377i\240\011\377" + "v\254#\377`\227\020\377U\206\001\377Q\177\004\377\210\264X\377r\245\023\377\205" + "\266$\377~\254\071\377{\226n\377{v\204\377\214\177\216\377\214{\213\377\270" + "\242\251\377\260\224\225\377\260\217\216\377\303\241\230\377\324\265\253" + "\377\323\265\260\377\326\272\266\377\340\310\304\377\354\326\320\377\360" + "\340\330\377\357\334\314\377\366\335\302\377\302|]\377\304\177a\377\362\253" + "\227\377\365\263\241\377\314\222\202\377\231f`\377\227fW\377\310\240\211" + "\377\261\220\206\377\265\224\215\377\246gY\377\376\354\315\377\373\367\346" + "\377\356\352\330\377\357\350\323\377\360\350\325\377\347\340\321\377\324" + "\316\307\377\366\361\360\377\351\335\335\377\343\321\317\377\353\332\327" + "\377\240\214\214\377t]_\377\326\301\274\377\343\323\315\377\330\305\277\377" + "\257\214\201\377\265\224\202\377\241xa\377\216jW\377\201y\201\377\235\240" + "\247\377\224\251\207\377{\253\063\377n\244\015\377r\253\010\377q\255\007\377f" + "\236\005\377l\242\001\377{\256\002\377y\245\001\377\201\255\001\377~\250\001\377|\251" + "\001\377z\250\001\377|\254\001\377\203\274\013\377\207\300\032\377\200\270\013\377" + "\203\272\013\377\200\262\002\377x\250\001\377x\255\001\377q\245\001\377p\240\001\377" + "\202\264\017\377\233\312\062\377z\257\005\377{\263\026\377g\245\034\377\177\272" + "\067\377s\260\016\377u\260\002\377y\263\002\377\200\266\002\377\206\270\002\377|\254" + "\002\377t\251\002\377w\263\013\377\211\277(\377\217\302)\377|\263\012\377x\262" + "\001\377u\254\002\377u\252\002\377z\257\002\377}\262\001\377\177\261\002\377\234\277" + "\002\377\177\261\027\377\210\274K\377a\234'\377m\244\061\377~\264\065\377\210" + "\272\013\377\222\276\003\377\210\263\001\377\177\256\017\377\203\264\033\377u\251" + "\011\377p\246\011\377x\257\022\377\202\266\034\377v\253\012\377h\236\001\377g\236" + "\002\377h\243\002\377r\251\013\377v\254\017\377s\252\021\377~\265)\377{\263'\377" + "^\227\004\377n\243\035\377\177\264\070\377[\213\003\377Nx\007\377t\246\070\377n\240" + ")\377\177\253\064\377\203\245R\377\215\224\221\377\202v\202\377\217\200\217" + "\377\251\227\237\377\317\273\274\377\246\221\226\377\302\252\251\377\340" + "\306\277\377\355\327\317\377\324\271\261\377\306\250\244\377\340\313\305" + "\377\354\331\316\377\361\341\324\377\375\374\366\377\372\365\357\377\215" + "fX\377X%\033\377\310eE\377\260aF\377\033\005\001\377@\033\013\377B\034\027\377\316" + "\237~\377\361\323\265\377\366\347\324\377\326\265\253\377\354\332\316\377" + "\366\351\343\377\361\344\336\377\356\337\330\377\341\320\311\377\326\301" + "\271\377\311\260\251\377\243\204\200\377\211lg\377\252\217\210\377\301\252" + "\236\377\301\255\242\377ubd\377\262\234\226\377\336\313\304\377\343\317\311" + "\377\242\206\204\377mUK\377Q\065$\377`J=\377\203v\203\377\237\230\246\377" + "\246\245\255\377\237\254\227\377\206\250R\377r\242\021\377~\260\021\377n\240" + "\003\377q\241\001\377z\257\001\377x\246\002\377~\257\001\377t\242\001\377s\246\001\377" + "|\261\002\377\204\267\004\377\205\270\004\377\216\300\027\377{\257\006\377\201\267" + "\017\377~\262\001\377}\257\001\377{\255\002\377s\243\000\377~\264\023\377\242\317a" + "\377\212\270\036\377|\256\000\377m\243\002\377\\\226\000\377w\264\040\377\200\273" + "%\377}\265\006\377\203\271\001\377\203\265\001\377|\255\001\377w\250\002\377u\253\001" + "\377s\255\001\377{\266\005\377~\264\005\377}\260\001\377\177\263\001\377v\247\002\377" + "s\247\002\377z\253\001\377\202\261\000\377}\254\002\377\231\276\001\377\200\267\062" + "\377q\251#\377\205\272/\377\225\305!\377\210\272\011\377x\255\002\377r\246\001" + "\377}\257\013\377\207\270%\377\204\265\030\377\201\263\013\377\215\274\032\377" + "\233\307\065\377\227\304/\377\217\300\"\377\202\264\014\377r\251\000\377q\255" + "\014\377{\265(\377k\245\025\377e\235\021\377\206\272<\377\213\276G\377i\241" + "\035\377l\240\033\377\225\303V\377o\240\037\377i\223%\377z\243K\377\201\247" + "Y\377\201\244a\377\212\230\210\377\212\204\217\377\237\222\236\377\212y\204" + "\377\266\243\245\377\313\267\264\377\253\216\221\377\272\240\233\377\266" + "\234\224\377\265\235\225\377\271\241\235\377\306\255\250\377\364\346\333" + "\377\336\276\261\377\361\330\305\377\371\365\361\377\375\375\376\377\377" + "\377\377\377\240ru\377\230J\067\377\232VD\377uZc\377\320\300\276\377\375\365" + "\353\377\377\377\370\377\372\363\340\377\370\347\322\377\360\334\313\377" + "\351\323\312\377\351\324\317\377\300\244\245\377\271\235\235\377\317\265" + "\261\377\320\265\257\377\301\245\240\377\306\253\242\377\260\222\206\377" + "\236\202u\377\233\201u\377\245\214\177\377\226~y\377yab\377\307\262\256\377" + "\310\262\257\377\315\270\263\377\231\203}\377_HB\377eOE\377\224\203\210\377" + "\214\177\215\377\232\223\242\377\237\237\250\377\223\236\225\377\206\247" + "T\377\205\265%\377z\253\002\377{\251\002\377\177\261\001\377~\261\001\377{\261\002" + "\377q\245\001\377s\253\003\377|\264\003\377\204\266\003\377\204\262\002\377\205\265" + "\005\377\177\262\005\377|\262\012\377~\270\017\377{\256\002\377z\252\002\377w\256\000" + "\377\177\267!\377\220\302<\377z\246\000\377|\256\001\377e\226\001\377j\237\001\377" + "|\267\012\377\201\271\024\377\204\274\013\377\204\266\001\377}\261\001\377t\252" + "\001\377q\246\001\377v\257\001\377x\261\001\377x\255\001\377|\254\001\377\204\270\001\377" + "\201\262\001\377y\250\001\377r\242\001\377\216\275\030\377\217\275\015\377t\246\001" + "\377\221\274\001\377t\255\035\377\214\300\060\377\202\266\032\377o\250)\377\\" + "\227\033\377Y\225\024\377k\243\022\377r\251\011\377y\253\002\377\202\263\002\377" + "\216\275\021\377\210\272&\377\207\266\067\377\204\263\066\377\210\267:\377~" + "\257\037\377|\256\000\377~\261$\377t\246)\377w\246\063\377u\243/\377\202\256" + "\062\377\230\301T\377\210\264>\377\205\266=\377\213\274H\377s\250\064\377h" + "\232,\377w\231\\\377\203\232z\377\213\226\213\377\217\212\225\377\227\212" + "\232\377\232\214\230\377ucq\377\276\254\251\377\271\243\244\377\264\236\240" + "\377\321\271\254\377\257\227\222\377\256\225\222\377\244\214\211\377\370" + "\360\355\377\374\367\356\377\367\344\321\377\342\303\261\377\371\364\363" + "\377\375\375\375\377\376\376\376\377\304\266\300\377T/<\377\202cr\377\363" + "\360\363\377\376\376\376\377\375\375\375\377\376\375\373\377\336\303\257" + "\377\323\250\217\377\301\235\222\377\331\275\264\377\371\356\350\377\337" + "\313\311\377\267\240\242\377\302\247\245\377\274\242\237\377\322\274\272" + "\377\310\262\260\377\264\232\224\377\241\204}\377\273\247\227\377\212qi\377" + "\220uq\377nXX\377\262\236\226\377\260\233\226\377\325\300\275\377\331\305" + "\303\377\241\211\212\377\202jg\377\217{z\377\217\200\213\377\220\205\226" + "\377\220\212\232\377\222\222\234\377\221\235\225\377\207\256T\377z\252\017" + "\377v\244\001\377\177\260\003\377{\253\001\377y\256\001\377t\245\001\377w\254\001\377" + "|\254\002\377\203\263\001\377\201\260\001\377~\255\001\377\210\271\012\377\222\303" + "-\377}\264\032\377z\261\016\377~\256\001\377{\257\001\377\202\273\017\377}\257\011" + "\377|\253\001\377z\251\002\377Z\222\001\377q\251\001\377\200\267\002\377\200\265\001" + "\377~\261\001\377y\254\002\377v\257\001\377r\251\001\377q\243\002\377|\254\002\377\201" + "\262\001\377~\253\002\377\202\263\001\377\202\264\001\377\177\264\001\377z\260\001\377" + "t\251\001\377\200\271\024\377z\262\007\377t\247\002\377\215\273\007\377|\267)\377" + "b\236\022\377j\242,\377u\253@\377a\231*\377q\246\071\377\205\266+\377v\250" + "\017\377f\227\001\377\201\257\001\377\214\275\003\377{\260\015\377_\230\014\377m\244" + "!\377k\241\032\377Y\217\004\377\211\267\000\377\210\270\070\377\203\262?\377\234" + "\310\\\377\221\275@\377\201\260,\377\213\270?\377\204\263B\377q\244\064\377" + "p\244\060\377l\237*\377p\235?\377p\206m\377\205\214\216\377\222\217\235\377" + "\221\206\227\377\233\217\236\377\207{\207\377\224\206\215\377\312\270\263" + "\377\264\243\240\377\314\263\250\377\320\261\235\377zYN\377yc^\377\352\342" + "\341\377\344\316\303\377\337\300\261\377\345\310\274\377\367\351\344\377" + "\375\375\374\377\373\367\370\377\374\371\373\377\344\334\347\377\200g|\377" + "\314\276\312\377\360\353\355\377\374\371\372\377\373\371\372\377\363\346" + "\342\377\324\261\233\377\354\314\261\377\312\245\221\377\325\271\247\377" + "\321\261\237\377\353\326\316\377\325\306\307\377\232\205\204\377\264\237" + "\234\377\251\224\222\377\250\221\213\377\265\234\224\377\266\233\216\377" + "\246\213~\377\234\202y\377\225~y\377kWV\377\231\207\200\377\256\233\227\377" + "\321\277\274\377\316\274\272\377\262\237\240\377\243\216\220\377\247\224" + "\226\377\241\217\230\377\212}\215\377\201x\211\377\210\203\223\377\213\213" + "\230\377\225\244\233\377x\243J\377n\245\036\377\204\271/\377t\251\002\377x\247" + "\002\377w\246\002\377\177\262\001\377\201\260\001\377\201\263\001\377{\257\002\377u\253" + "\002\377\213\276\037\377\222\301*\377n\245\001\377t\260\010\377\200\266\001\377\201" + "\256\001\377\205\265\002\377\177\253\001\377\200\253\001\377x\246\000\377\202\256\026" + "\377\200\260\006\377\204\271\001\377\201\265\001\377}\261\003\377v\255\006\377p\252" + "\001\377w\254\001\377\207\270\002\377~\254\002\377\201\261\001\377~\254\002\377\201\262" + "\001\377\201\265\002\377y\252\001\377{\261\002\377w\260\002\377u\261\000\377u\255\001\377" + "s\246\002\377\206\276\062\377p\256\"\377p\254)\377l\246'\377o\247-\377s\252" + ".\377c\233\016\377g\236\006\377Z\220\003\377]\222\001\377u\250\001\377\207\272\007\377" + "z\260\007\377n\244\023\377f\231\022\377]\221\004\377W\215\007\377\211\264\002\377q" + "\246\030\377\225\304_\377\214\275G\377y\252\027\377y\251\027\377|\253%\377\223" + "\277G\377]\222\032\377o\241+\377r\241+\377\203\243a\377\243\244\252\377\260" + "\253\270\377\251\237\257\377\241\230\250\377\220\207\226\377wiz\377\215y" + "\206\377\270\244\242\377\272\241\237\377\341\307\271\377\277\232\204\377" + "\257\214x\377\344\321\311\377\375\371\366\377\372\370\365\377\367\350\341" + "\377\352\315\307\377\364\334\333\377\367\356\360\377\374\366\370\377\371" + "\364\370\377\275\256\274\377\204v\204\377\265\243\261\377\321\273\302\377" + "\335\307\311\377\362\344\346\377\372\363\363\377\371\356\352\377\261\207" + "r\377\266\210k\377\326\262\225\377\376\366\354\377\373\370\365\377\373\364" + "\363\377\266\241\237\377\231\205\200\377\307\265\251\377\276\252\227\377" + "\275\250\225\377\314\265\250\377\264\234\217\377\276\252\240\377\247\223" + "\216\377}eh\377\212tq\377\247\217\213\377\266\241\235\377\307\265\260\377" + "\305\262\256\377\235\205\207\377\245\216\222\377\263\244\253\377\232\214" + "\232\377\200u\206\377\200x\213\377\212\205\226\377\212\213\227\377\206\226" + "\211\377~\251V\377{\257\062\377x\253\000\377\200\260\001\377v\245\002\377}\255\001" + "\377\200\263\001\377}\264\001\377w\257\002\377r\254\007\377\222\306F\377\200\264" + "\032\377q\247\001\377q\251\003\377w\262\003\377\200\260\001\377\203\256\001\377\177" + "\250\001\377~\251\002\377x\246\001\377\207\267\010\377\207\267\004\377\205\267\002\377" + "}\257\001\377\204\266\013\377\227\302&\377u\250\000\377|\255\001\377\215\300\001\377" + "\204\262\001\377\207\264\001\377\205\260\001\377\210\267\001\377\203\262\001\377x\246" + "\002\377\177\257\001\377w\246\002\377z\257\001\377~\263\001\377s\243\001\377`\241\021" + "\377N\214\000\377c\240\011\377y\262\037\377d\240\005\377b\237\006\377p\253\017\377" + "l\243\002\377g\225\003\377w\246\014\377q\241\000\377\177\263\004\377u\255\005\377~\263" + "\"\377\\\204\000\377e\216\007\377d\217\012\377}\253\003\377\216\303\064\377\177\262" + "@\377g\236\026\377[\216\005\377h\231\006\377~\254!\377\220\274A\377u\241)\377" + "\206\255S\377\232\260\204\377\243\250\243\377\234\230\244\377\210\200\225" + "\377\222\211\233\377\217\204\226\377\224\204\225\377\215\200\216\377\242" + "\224\231\377\240\217\223\377\320\274\271\377\336\311\302\377\262\226\217" + "\377\267\233\231\377\363\357\360\377\373\370\365\377\351\324\312\377\351" + "\317\311\377\366\346\346\377\365\353\355\377\360\352\356\377\361\347\356" + "\377\322\306\322\377}i|\377P\070H\377\216\200\215\377\313\275\306\377\340" + "\322\330\377\364\347\353\377\345\316\313\377\347\320\312\377\327\265\250" + "\377\336\304\265\377\320\262\242\377\311\252\233\377\332\306\275\377\352" + "\342\342\377\331\314\316\377\216\200|\377`TR\377ygb\377iXT\377\231\200t\377" + "\314\270\255\377\301\254\247\377\262\237\236\377\234\212\211\377\202on\377" + "\266\243\237\377\234\206\205\377\267\242\240\377\302\256\256\377\253\226" + "\233\377\237\211\221\377\315\300\306\377\322\306\313\377\241\225\242\377" + "\210~\220\377\214\205\227\377\214\207\226\377\211\211\224\377\210\233\204" + "\377x\250\066\377l\232\000\377\203\257\002\377\205\265\001\377\202\265\002\377\203" + "\267\002\377|\257\002\377x\255\001\377w\262\007\377w\261\022\377n\237\001\377q\245\001" + "\377r\251\001\377t\256\002\377\202\266\004\377\204\262\002\377\205\257\002\377~\251" + "\001\377{\247\002\377\204\265\001\377\206\265\002\377\204\266\001\377~\257\001\377\205" + "\261\002\377\222\274\002\377\206\264\001\377y\251\002\377\177\261\001\377\205\271\002" + "\377\201\256\001\377\205\261\001\377\212\272\002\377\206\265\001\377{\252\002\377}" + "\253\002\377y\250\001\377}\260\001\377{\255\001\377r\241\002\377d\236\002\377[\223\002" + "\377l\250\025\377|\264\031\377t\255\011\377^\225\001\377l\246\004\377w\252\003\377" + "b\215\001\377^\215\002\377q\242\001\377\205\266\005\377v\253\007\377\216\305+\377p" + "\236\003\377f\214\001\377Ry\001\377t\254\020\377z\264$\377Q\205\010\377~\260\040\377" + "T\206\003\377_\217\005\377\177\253\040\377\260\317t\377q\230B\377k\222E\377\213" + "\230\206\377\252\250\262\377\254\245\263\377\232\216\242\377rdx\377\201m" + "}\377\205q|\377\220|\201\377\221}|\377\202ge\377\334\300\254\377\340\274" + "\242\377\255~d\377\353\333\324\377\372\367\367\377\344\325\315\377\356\337" + "\325\377\351\324\312\377\275\245\242\377\307\265\267\377\342\331\337\377" + "\307\301\310\377zq~\377\070\036+\377N\067D\377UBN\377\232\217\233\377\325\312" + "\323\377\312\273\302\377\331\310\306\377\343\320\315\377\343\313\304\377" + "\277\236\220\377\310\237\203\377\370\355\345\377\357\341\331\377\332\312" + "\306\377\327\320\315\377\274\253\246\377\273\246\235\377\271\242\232\377" + "\225}w\377mOB\377\271\233\210\377\335\312\301\377\251\216\207\377\250\220" + "\212\377nVS\377\253\227\216\377\302\257\251\377\247\220\217\377\261\234\235" + "\377\254\232\237\377\240\213\227\377\260\237\252\377\314\277\305\377\323" + "\306\314\377\235\221\241\377\214\203\226\377\205~\220\377\202\177\215\377" + "\211\217\224\377v\233U\377i\234\010\377\200\261\001\377\203\262\002\377\202\262" + "\001\377\201\262\001\377}\253\001\377}\257\002\377~\262\001\377v\247\002\377x\246\001\377" + "x\247\002\377s\241\002\377x\260\003\377y\254\001\377\177\256\001\377\202\263\001\377" + "\202\256\002\377\200\254\002\377\206\264\001\377\207\264\002\377\211\271\002\377\204" + "\255\001\377\223\267\001\377\245\307\001\377\212\263\002\377{\256\001\377s\245\002\377" + "~\260\001\377}\254\002\377\203\262\002\377\207\267\001\377\211\271\001\377\177\256" + "\001\377~\256\002\377\177\263\002\377}\257\001\377u\244\001\377z\252\002\377g\236\001\377" + "f\236\001\377s\256\026\377\210\276.\377z\262\020\377t\256\011\377i\235\001\377s" + "\246\002\377p\240\001\377o\235\001\377w\242\000\377\223\301\071\377w\254\040\377\214" + "\301/\377y\256\013\377m\240\002\377a\222\000\377z\262\025\377k\242\012\377h\226" + "\020\377x\250\024\377Gy\000\377d\214\022\377\212\246\064\377\262\316\213\377\204" + "\245l\377\207\224\211\377\220\216\234\377\207\177\222\377\205{\220\377\204" + "w\212\377l_r\377\211w\203\377\234\206\217\377\266\243\250\377\254\233\235" + "\377\277\256\255\377\367\347\340\377\326\271\243\377\314\262\244\377\336" + "\324\322\377\354\342\336\377\367\356\347\377\324\300\262\377\236\214\207" + "\377\261\247\242\377\271\262\264\377\267\260\266\377l^g\377XIP\377ven\377" + "cNZ\377eS\\\377aNY\377\210z\210\377\277\271\301\377\316\301\306\377\252\220" + "\215\377\273\240\231\377\337\306\277\377\314\270\255\377\320\267\243\377" + "\336\314\276\377\363\353\346\377\327\313\312\377\335\317\322\377\355\341" + "\342\377\364\355\355\377\341\323\315\377\234\205z\377\243\213\201\377\316" + "\272\262\377\305\256\242\377\270\241\225\377\207sm\377zd`\377\261\237\225" + "\377\254\231\225\377\262\240\235\377\262\243\247\377\227\205\222\377\221" + "~\216\377\304\266\276\377\326\311\316\377\315\300\310\377\241\226\246\377" + "\213\205\227\377\205\201\221\377\216\215\233\377z\216x\377\223\273S\377\205" + "\265\016\377\210\266\005\377\213\271\002\377\205\261\001\377~\257\001\377y\257\001\377" + "s\245\001\377z\254\001\377\200\257\002\377}\254\002\377}\253\010\377}\261\013\377y" + "\254\004\377\177\257\002\377}\253\002\377~\253\001\377v\246\002\377u\245\002\377\200" + "\260\001\377\205\265\002\377\203\253\001\377\225\275\001\377\223\267\001\377\200\253" + "\003\377\200\262\001\377{\261\002\377t\246\002\377x\251\002\377\203\264\001\377\212\267" + "\001\377\221\301\001\377\206\262\001\377\200\257\001\377\201\263\001\377z\251\002\377" + "w\246\001\377\204\264\001\377\226\275\002\377q\247\001\377m\246\002\377u\256\011\377" + "o\247\001\377y\255\001\377~\260\002\377~\256\002\377z\247\001\377}\253\001\377\220\271" + "#\377\227\302a\377Y\227\003\377\205\272\060\377}\260\026\377o\242\002\377s\253" + "\004\377v\254\003\377y\252\003\377z\247\010\377\210\263I\377}\243F\377\201\242\066" + "\377\232\264g\377\242\276\202\377z\215u\377|}\205\377\203|\214\377\204x\211" + "\377\213~\220\377~p\201\377|n{\377\265\245\252\377\327\313\317\377\354\344" + "\351\377\326\320\326\377\343\326\327\377\342\315\277\377\310\265\251\377" + "\341\324\317\377\344\326\323\377\350\335\334\377\352\343\340\377\262\243" + "\217\377\234\207l\377wjX\377\204\201v\377smk\377iZ^\377\212x\177\377\235" + "\212\226\377\221~\213\377\204nx\377\214x\200\377eV\\\377kci\377\244\237\242" + "\377\267\252\252\377\240\217\215\377\212tf\377\301\255\235\377\333\311\275" + "\377\331\316\307\377\333\312\277\377\365\357\355\377\351\336\334\377\335" + "\317\310\377\303\250\224\377\301\250\226\377\326\310\301\377\223\203\177" + "\377\270\250\242\377\333\311\303\377\264\237\221\377\220zv\377`LN\377\221" + "~z\377\236\215\206\377\226\203\204\377\247\227\233\377\234\213\230\377\232" + "\214\234\377\255\235\252\377\311\273\303\377\323\310\317\377\314\303\312" + "\377\243\233\252\377\205\177\220\377\215\212\230\377\202\207\213\377v\233" + "?\377\214\272&\377\210\264\001\377\213\257\001\377\215\264\001\377\201\260\001\377" + "t\250\001\377q\243\001\377u\244\002\377z\245\002\377z\250\001\377z\255\010\377\200\265" + "!\377\202\271'\377x\253\001\377\206\263\003\377\200\260\002\377w\247\002\377u\245" + "\001\377\201\260\002\377\207\265\002\377\206\260\001\377\214\267\001\377\214\273\004" + "\377\201\255\003\377}\262\001\377p\255\002\377k\242\002\377h\234\001\377}\257\002\377" + "\202\256\002\377\217\274\002\377\221\276\001\377\200\257\002\377{\256\002\377w\247" + "\001\377~\261\001\377\202\265\001\377\215\265\001\377\202\264\003\377x\253\006\377i\227" + "\001\377y\256\001\377w\251\001\377d\224\001\377g\226\002\377\200\255\002\377\205\262" + "\000\377\204\266\"\377f\232\020\377Z\231\001\377p\250\034\377\203\264%\377}\261" + "\035\377v\255\013\377r\251\003\377{\254\001\377\201\257\001\377\211\260i\377\216" + "\265q\377\234\276i\377|\246C\377n\225J\377\201\211\205\377\203\177\213\377" + "\203y\213\377\204w\212\377\204w\211\377\242\231\244\377\253\242\252\377\307" + "\275\306\377\342\325\336\377\313\277\306\377\277\265\276\377\323\310\314" + "\377\312\261\247\377\306\247\217\377\327\301\255\377\317\274\265\377\325" + "\307\277\377\312\266\242\377\272\242\202\377\234\202a\377oaM\377ph\\\377" + "tol\377\247\234\237\377\275\261\271\377\252\233\247\377\226\204\220\377\245" + "\225\240\377\246\230\241\377\242\230\234\377pfl\377ife\377\213\211\201\377" + "|rh\377\242\232\222\377\204t_\377\257\237\214\377\321\304\264\377\344\336" + "\331\377\365\363\364\377\343\335\330\377\317\275\257\377\250\205e\377\260" + "\217r\377\247\205j\377\230xb\377\223vi\377\332\314\311\377\316\301\277\377" + "\277\254\245\377^FD\377}ib\377\225\200|\377\222\177~\377\230\206\213\377" + "\227\210\224\377\260\244\261\377\252\232\247\377\262\243\256\377\312\274" + "\306\377\313\277\307\377\307\273\305\377\233\221\242\377\211\200\222\377" + "\203~\215\377u\203h\377u\246\022\377~\257\007\377\177\247\002\377\225\264\001\377" + "\202\253\002\377j\231\002\377z\251\002\377\201\252\001\377\201\254\001\377r\234\001\377" + "~\257\002\377}\260\007\377w\255\010\377w\251\003\377\223\277\031\377\207\270\011\377" + "\200\261\013\377x\245\001\377\206\262\001\377\213\267\001\377\206\257\002\377\212" + "\262\001\377\220\276\016\377\214\276\026\377{\264\002\377m\250\001\377n\251\001\377" + "h\235\001\377|\262\001\377}\255\001\377\210\264\001\377\221\275\002\377\203\263\002\377" + "q\245\001\377u\252\001\377|\267\003\377~\270\001\377\207\260\001\377\206\256\001\377" + "\211\266\007\377r\236\002\377y\251\002\377j\234\001\377P\202\002\377\\\216\002\377x\245" + "\001\377\210\267\026\377\206\266\021\377|\250\002\377g\237\012\377c\232#\377\200" + "\264\060\377t\253\034\377l\247\017\377m\244\014\377\206\264\032\377\227\274\070" + "\377w\240\037\377z\246\064\377\216\267X\377}\252S\377q\217`\377\212\207\217" + "\377\215\205\222\377\230\214\234\377\230\215\235\377\241\223\242\377\210" + "z\210\377\302\263\275\377\335\321\331\377\353\340\347\377\325\314\324\377" + "\266\245\255\377\247\217\214\377\243\213\200\377\330\312\302\377\326\310" + "\300\377\303\255\241\377\302\245\210\377\301\246\210\377\263\227z\377\221" + "v\\\377`M@\377pgb\377\252\247\251\377\312\304\310\377\305\276\305\377\313" + "\306\314\377\260\250\262\377\275\264\275\377\274\263\274\377\254\245\254" + "\377\255\250\256\377xss\377ysl\377ri`\377uja\377\242\232\212\377\265\257" + "\231\377\302\275\252\377\317\310\271\377\331\325\320\377\340\332\332\377" + "\325\305\276\377\303\252\224\377\322\272\246\377\277\244\212\377\237}a\377" + "tS@\377\275\243\216\377\333\313\277\377\343\331\326\377\214{}\377xd`\377" + "ve\\\377\204rq\377\210w\200\377\224\204\221\377\251\232\247\377\274\256\270" + "\377\273\253\266\377\265\242\256\377\313\275\306\377\330\313\323\377\321" + "\305\314\377\217\201\225\377\211\200\221\377x~y\377o\234<\377w\253.\377p" + "\245\001\377\201\256\001\377\177\250\001\377r\236\002\377\177\254\002\377\206\261\002" + "\377\201\253\001\377{\245\001\377\177\250\001\377~\247\001\377\202\261\001\377r\242" + "\002\377|\253\001\377\202\262\002\377|\254\003\377|\252\001\377\211\267\001\377\206\262" + "\001\377\203\256\001\377\206\257\001\377\202\253\001\377\201\264\000\377\201\272\006" + "\377n\244\001\377q\252\001\377l\240\002\377~\261\004\377\206\266\012\377\215\266\002" + "\377\213\264\001\377\211\265\001\377p\251\001\377s\254\001\377{\257\001\377\202\265" + "\001\377e\221\001\377\203\255\002\377\216\270\001\377\207\261\001\377j\232\001\377_\217" + "\002\377X\210\002\377s\241\002\377z\254\001\377\214\274A\377g\230\020\377g\223\002\377" + "y\251\010\377\203\265'\377\215\277@\377y\256\063\377\233\303i\377\236\302a" + "\377\177\254\015\377{\254\003\377l\236\011\377n\236#\377o\235\071\377p\230L\377" + "}\205\202\377\217\210\226\377\242\234\247\377\221\210\230\377\214\177\220" + "\377\226\206\224\377\256\234\245\377\320\303\311\377\334\322\332\377\311" + "\271\302\377\277\257\270\377\252\226\241\377\245\226\227\377\177j_\377\320" + "\300\264\377\320\276\257\377\320\275\252\377\312\271\244\377\301\257\234" + "\377\274\254\232\377\274\256\241\377\236\224\216\377\250\244\243\377\302" + "\300\304\377\277\275\301\377\311\307\314\377\317\315\322\377\300\270\301" + "\377\303\300\306\377\311\307\314\377\266\263\270\377\315\314\320\377\271" + "\271\274\377\235\234\230\377~ys\377TFB\377YOS\377\215}e\377\277\264\237\377" + "\266\253\223\377\273\253\220\377\300\264\243\377\336\325\323\377\337\324" + "\322\377\330\311\301\377\321\275\255\377\273\240\206\377vVA\377\225sZ\377" + "\336\316\300\377\350\336\327\377\260\244\250\377\227\210\221\377\224\207" + "\205\377ucd\377\206x\202\377\223\205\222\377\243\225\242\377\262\242\256" + "\377\300\261\272\377\273\252\263\377\301\261\271\377\312\273\301\377\317" + "\300\306\377\321\306\312\377\233\222\240\377z{\203\377w\221o\377\211\264" + "c\377p\247\004\377t\250\002\377y\247\002\377}\253\001\377~\251\001\377\201\257\001\377" + "{\247\001\377z\244\002\377v\237\002\377\203\252\001\377\204\261\002\377w\245\002\377" + "s\243\001\377z\253\001\377}\261\001\377\201\262\002\377\203\255\002\377\207\263\002\377" + "\203\256\002\377\201\254\002\377\204\255\001\377\206\267\002\377z\257\002\377s\251" + "\001\377t\254\002\377j\233\001\377n\237\002\377\220\300\024\377\212\270\000\377\211" + "\264\001\377{\251\002\377{\260\002\377v\252\002\377\177\257\001\377\202\263\001\377b" + "\221\002\377g\225\001\377\213\267\001\377\224\276\012\377\205\261\005\377l\232\001\377" + "d\221\002\377w\246\002\377{\253\001\377r\247\000\377T\211\000\377P\207\002\377O\210\002" + "\377{\255#\377\227\303K\377\231\304Z\377|\256\067\377z\251\037\377\204\260" + "\002\377\210\261\007\377\202\253*\377q\237.\377o\233>\377q\217[\377\231\227\241" + "\377\226\216\236\377\200u\211\377\207}\221\377\200t\206\377\235\215\232\377" + "\303\267\273\377\306\267\276\377\251\221\233\377\266\240\253\377\315\276" + "\306\377\311\274\304\377\241\216\217\377\264\237\226\377\275\243\214\377" + "\272\241\206\377\264\235\177\377\242\210j\377\254\225}\377\304\264\253\377" + "\331\323\322\377\316\313\315\377\300\277\300\377\300\300\300\377\271\271" + "\272\377\311\311\315\377\312\311\316\377\302\301\306\377\304\303\311\377" + "\310\307\315\377\312\311\316\377\273\272\276\377\320\320\324\377\276\301" + "\277\377\266\266\263\377\233\232\223\377\210\177\204\377jY]\377\212pV\377" + "\305\273\247\377\276\263\235\377\301\262\232\377\301\265\241\377\327\317" + "\310\377\316\277\261\377\301\261\237\377\304\261\237\377\261\231~\377|\\" + "C\377\312\263\232\377\342\325\312\377\300\262\257\377l`g\377\200t~\377\243" + "\232\241\377\215\201\213\377\230\213\227\377\217\201\221\377\243\225\244" + "\377\271\252\264\377\310\271\277\377\261\240\251\377\274\255\264\377\276" + "\255\265\377\323\306\311\377\315\303\311\377\205\202\216\377m|q\377\234\272" + "\220\377z\261\034\377l\241\000\377r\247\003\377\177\256\015\377s\246\001\377|\262" + "\012\377{\256\006\377v\244\001\377x\246\001\377\177\256\001\377s\241\002\377p\236\001" + "\377z\251\002\377z\250\001\377w\251\001\377y\260\001\377|\256\002\377\201\262\001\377" + "\177\252\001\377{\245\002\377\206\261\001\377\207\271\002\377o\242\001\377r\255\006\377" + "u\256\005\377p\240\001\377j\233\002\377\204\270\025\377\231\304.\377\207\270\004\377" + "x\252\002\377k\240\001\377|\254\001\377~\255\001\377~\261\001\377k\235\001\377m\235\002" + "\377{\252\003\377\223\277\031\377}\253\002\377}\254\001\377~\256\002\377|\261\003\377" + "m\236\002\377p\245\001\377i\245\004\377u\257&\377_\232\037\377\214\275f\377\215" + "\277T\377z\255\013\377m\237\002\377p\230\002\377\211\262\001\377\213\262\004\377u" + "\237\003\377]\214\000\377h\224\062\377\213\225\214\377\222\213\227\377~t\204\377" + "xp\200\377}u\207\377\265\254\271\377\276\260\264\377\271\244\250\377\267" + "\240\244\377\270\243\253\377\303\264\276\377\277\256\266\377\273\254\264" + "\377\241\217\223\377\227{p\377\276\241\213\377\267\235\210\377\272\246\223" + "\377\275\253\227\377\271\246\222\377\314\276\267\377\340\333\334\377\333" + "\331\335\377\307\307\307\377\275\276\271\377\261\262\254\377\275\302\276" + "\377\276\301\300\377\271\272\272\377\272\273\274\377\303\304\307\377\301" + "\303\304\377\257\262\255\377\274\300\273\377\307\314\312\377\311\313\312" + "\377\302\302\303\377\274\273\276\377\264\257\260\377\256\241\234\377\326" + "\321\312\377\265\256\234\377\305\274\253\377\266\246\223\377\314\300\261" + "\377\301\270\261\377\320\306\272\377\306\272\254\377\304\253\226\377\216" + "pS\377\242\207l\377\312\271\243\377\256\231\216\377yjs\377tdj\377rek\377" + "\245\234\246\377\264\251\261\377\223\204\223\377\237\215\235\377\256\236" + "\250\377\301\262\271\377\277\256\267\377\265\242\254\377\271\250\260\377" + "\273\253\257\377\343\327\327\377\236\225\242\377sux\377\215\243\203\377\177" + "\260)\377p\243\000\377n\236\002\377r\244\003\377j\231\003\377|\262\016\377p\244\001" + "\377u\253\003\377\200\264\021\377t\247\002\377k\232\002\377t\242\002\377y\246\001\377" + "\204\262\002\377u\244\002\377t\250\001\377m\237\001\377x\257\002\377|\255\001\377~\251" + "\002\377\213\273\007\377\201\264\002\377q\246\003\377u\260\011\377n\240\001\377s\243" + "\001\377y\250\002\377\201\266\011\377\243\310B\377\201\261\006\377j\237\002\377a\227" + "\002\377\217\274\002\377\206\260\001\377\201\262\001\377h\227\002\377u\246\001\377l\234" + "\002\377p\243\017\377{\256\030\377e\234\006\377Y\220\003\377v\257\024\377l\242\004\377" + "p\246\002\377u\255\010\377\211\277:\377\177\263:\377r\250\065\377\200\264B\377" + "`\227\022\377[\216\001\377|\253\001\377\215\266\002\377\210\257\006\377\227\265\065" + "\377\201\246@\377w\230a\377\211\216\210\377\214\207\217\377\217\204\222\377" + "\226\217\236\377\253\241\256\377\233\207\222\377\264\240\244\377\303\261" + "\263\377\270\244\252\377\270\246\260\377\246\223\236\377\275\256\267\377" + "\315\300\311\377\244\217\225\377\206ig\377\250\216{\377\265\236\213\377\252" + "\223\203\377\261\232\206\377\261\235\214\377\317\306\301\377\327\322\322" + "\377\327\325\326\377\313\314\311\377\263\266\251\377\243\251\231\377\254" + "\261\244\377\261\266\253\377\263\270\256\377\265\272\262\377\273\301\272" + "\377\271\300\271\377\265\272\262\377\263\271\261\377\301\306\300\377\305" + "\312\310\377\316\320\322\377\317\317\323\377\316\315\321\377\326\326\330" + "\377\315\312\305\377\302\274\263\377\273\261\243\377\270\256\233\377\255" + "\237\211\377\277\265\244\377\315\305\273\377\307\275\257\377\301\263\241" + "\377\227~h\377gK\063\377\245\215u\377\211xk\377XLL\377h`c\377\204z\177\377" + "\204u\200\377\255\242\252\377\261\242\254\377\236\214\232\377\252\231\244" + "\377\273\253\264\377\277\260\266\377\271\250\256\377\267\246\255\377\272" + "\251\254\377\325\307\310\377\304\270\300\377\177y\203\377\214\232{\377\211" + "\265\067\377r\250\002\377k\233\001\377q\246\003\377s\247\004\377r\247\004\377j\237\002" + "\377^\217\001\377z\246\004\377~\253\007\377r\234\001\377\177\253\000\377\203\257\002" + "\377~\253\002\377z\251\002\377p\245\002\377k\235\001\377n\237\001\377|\257\004\377\201" + "\263\011\377{\256\003\377\202\267\014\377\201\270\023\377o\246\000\377o\241\001\377" + "o\240\002\377~\254\001\377y\251\000\377\212\267\016\377w\246\002\377h\235\002\377Y\221" + "\002\377|\260\001\377\217\272\002\377\212\265\000\377z\246\002\377v\245\001\377f\225" + "\002\377_\215\001\377v\251\014\377\205\266$\377e\233\003\377_\224\001\377w\254\032" + "\377\204\267+\377\207\273)\377~\262\020\377z\254\000\377{\255\014\377\205\263" + "\067\377\205\265\063\377U\216\003\377f\234\005\377\207\262\013\377\211\260\030\377" + "\301\301\247\377\212\217x\377{\204y\377\204\204\210\377\221\207\223\377\242" + "\227\247\377\233\222\240\377\220~\216\377\232\207\221\377\302\260\267\377" + "\311\272\301\377\271\250\260\377\254\227\242\377\265\243\255\377\276\257" + "\271\377\301\264\274\377\274\256\265\377\222\200}\377p_R\377\256\223~\377" + "\250\215r\377\253\216s\377\306\262\244\377\277\261\253\377\322\314\311\377" + "\324\324\323\377\305\307\301\377\266\271\252\377\247\255\224\377\237\251" + "\212\377\242\253\215\377\242\256\220\377\240\256\221\377\252\266\237\377" + "\255\272\245\377\255\271\243\377\255\270\245\377\266\277\262\377\303\310" + "\302\377\313\316\316\377\316\322\325\377\330\331\335\377\332\332\334\377" + "\317\314\307\377\301\271\255\377\275\261\240\377\273\257\241\377\217zc\377" + "~iP\377\214{c\377\233\213x\377\311\273\261\377\241\211w\377kVH\377q\\J\377" + "aNB\377UF?\377bUU\377xlt\377\212~\212\377\225\207\221\377\245\227\240\377" + "\232\213\230\377\260\242\255\377\257\236\252\377\312\272\302\377\300\261" + "\267\377\260\236\250\377\301\261\267\377\321\302\305\377\312\275\301\377" + "\200x\207\377\213\225l\377\217\262=\377i\241\003\377r\250\012\377t\247\004\377" + "o\234\001\377g\224\002\377[\213\001\377m\231\002\377\206\253\002\377\206\261\002\377" + "~\250\005\377\232\301\020\377\203\256\001\377|\250\002\377w\247\002\377s\250\001\377" + "k\233\002\377n\236\002\377s\246\000\377\216\275/\377{\260\005\377x\254\002\377{\263" + "\006\377v\254\004\377r\244\002\377v\245\002\377\202\256\002\377n\235\002\377l\235\001\377" + "s\244\001\377j\237\001\377c\234\001\377\202\273\031\377\210\270\001\377\207\262\002" + "\377\206\260\001\377i\226\002\377U\206\001\377_\215\002\377i\232\001\377e\227\006\377" + "y\257\026\377z\255\035\377\220\277\066\377\206\265\037\377m\237\002\377p\240\000" + "\377\177\256\000\377\221\270\000\377\214\267\061\377v\241G\377^\177\070\377awE" + "\377q{c\377c_h\377G>N\377TLY\377olt\377\227\223\235\377\241\231\247\377\224" + "\210\230\377\203t\206\377\222\200\216\377\256\236\245\377\310\273\300\377" + "\243\217\231\377\266\243\253\377\231\204\220\377\300\262\271\377\300\262" + "\273\377\246\225\234\377\261\240\242\377\265\246\243\377\211so\377rQF\377" + "nK>\377\227xe\377\252\212{\377\276\253\241\377\306\272\264\377\273\263\253" + "\377\265\262\244\377\251\251\222\377\245\251\207\377\233\244y\377\227\241" + "q\377\221\235i\377\214\231g\377\222\236p\377\222\240u\377\225\243|\377\244" + "\261\222\377\250\265\235\377\267\301\262\377\306\315\306\377\306\313\311" + "\377\323\327\327\377\327\330\332\377\323\322\322\377\311\304\277\377\304" + "\274\266\377\271\254\243\377\302\272\264\377\271\256\245\377\252\232\214" + "\377\252\223{\377\270\245\217\377\264\237\217\377\203ie\377t`\\\377[EC\377" + "wfd\377vkm\377znu\377\202t}\377\217\201\212\377\231\211\224\377\232\207\222" + "\377\222\200\216\377\255\236\252\377\274\255\264\377\304\265\273\377\252" + "\230\242\377\233\207\222\377\257\233\237\377\320\303\305\377\271\254\267" + "\377\240\236{\377\225\260H\377\202\261\064\377\200\260\036\377x\251\003\377u" + "\243\003\377l\226\001\377j\223\002\377{\242\001\377\205\256\007\377\206\264\016\377" + "\206\260\031\377\255\315;\377\201\263\002\377\177\250\002\377\177\247\002\377{\244" + "\002\377y\242\002\377w\237\000\377\215\273$\377\227\304\067\377z\252\003\377z\247" + "\001\377\200\257\002\377~\255\004\377o\236\002\377\203\256\002\377\204\255\003\377q\236" + "\002\377m\235\002\377y\252\001\377u\247\002\377k\237\003\377t\252\003\377y\247\002\377" + "\206\263\002\377z\246\002\377o\237\002\377Hw\002\377\\\213\001\377d\225\003\377c\226" + "\014\377\224\306<\377\214\276\065\377\210\264\026\377\201\247\003\377q\241\002\377" + "p\237\003\377c\204,\377Yo\064\377alI\377KDN\377=\064?\377G=J\377RET\377@\060=" + "\377-\033(\377NAL\377\216\207\225\377\232\221\236\377\217\205\223\377\213" + "~\217\377\203u\205\377\221\200\216\377\312\273\301\377\272\251\254\377\272" + "\247\250\377\254\230\235\377\236\212\224\377\276\257\265\377\262\241\251" + "\377\252\227\240\377\257\235\236\377\242\224\222\377\266\250\237\377\213" + "uh\377qWM\377pTC\377\206gO\377\207jV\377\216q`\377\241\215|\377\234\215z" + "\377\230\222v\377\230\227t\377\211\211`\377}}N\377oo=\377tvE\377\203\211" + "W\377\205\216\\\377\210\220d\377\232\245~\377\250\261\224\377\251\262\233" + "\377\266\274\255\377\276\304\273\377\303\306\300\377\307\307\306\377\326" + "\326\326\377\316\312\311\377\310\301\275\377\273\256\246\377\257\235\217" + "\377\264\246\234\377\247\222{\377\275\250\235\377\242\205e\377\231}d\377" + "\215wo\377\202pk\377\203wt\377\201xu\377shj\377\211z\200\377\207w|\377\212" + "x~\377\235\213\222\377\256\240\250\377\217\200\212\377\252\232\244\377\261" + "\243\254\377\261\241\251\377\253\232\242\377\237\216\226\377\240\216\226" + "\377\263\242\250\377\324\310\314\377\257\245\216\377\236\257[\377r\243(\377" + "\226\303N\377s\246\010\377o\235\001\377n\233\002\377e\220\002\377\177\242\002\377" + "\221\270\034\377\207\266#\377\247\311J\377\233\277'\377|\252\000\377\211\263" + "\001\377\207\256\000\377\230\265\024\377\231\266\034\377|\244\000\377\177\253\011" + "\377}\254\002\377~\250\002\377z\245\001\377\204\264\003\377\201\261\003\377t\241\002" + "\377y\243\002\377z\245\002\377o\234\002\377w\250\001\377z\254\001\377}\260\003\377r\241" + "\001\377u\250\001\377n\236\002\377\204\261\001\377x\245\001\377k\232\002\377k\232\001\377" + "t\244\005\377\214\274\"\377\220\300&\377s\252\016\377b\235\005\377\215\272\017" + "\377x\252\005\377k\240\020\377\177\226V\377\200\201\203\377\237\234\242\377" + "\220\207\217\377ymt\377XHT\377=+\071\377;)\063\377cT]\377qfn\377gZe\377{p\200" + "\377\203w\207\377\207y\212\377\214~\217\377\213}\215\377\246\227\241\377" + "\305\265\264\377\254\230\232\377\241\215\217\377\220}\206\377\270\250\254" + "\377\274\254\261\377\254\233\242\377\266\243\251\377\262\242\242\377\236" + "\216\217\377\214\177~\377\245\227\221\377\227\203t\377jL\063\377iO\067\377" + "ubO\377\\H;\377dND\377^K=\377XF\064\377P@)\377aV\070\377bV\064\377uoI\377\207" + "\207\\\377\212\214b\377\221\224k\377\214\216i\377\224\227w\377\244\247\217" + "\377\235\237\212\377\245\247\224\377\237\234\214\377\265\262\251\377\271" + "\263\257\377\304\276\276\377\273\256\250\377\265\241\220\377\255\227\203" + "\377\240\203h\377\241\207v\377\222va\377\231|a\377\214wh\377nS<\377n[M\377" + "zfb\377\244\226\223\377}qs\377{po\377\212{|\377\223\204\207\377\221\203\206" + "\377\220~\201\377\220~\203\377\242\222\234\377\240\220\232\377\232\210\222" + "\377\267\253\260\377\266\251\257\377\226\205\217\377\241\220\227\377\255" + "\232\236\377\313\300\300\377\274\267\252\377\227\253i\377i\234\027\377t\246" + "\032\377y\253\034\377n\241\003\377o\241\002\377g\221\001\377y\240\001\377\226\274\064" + "\377t\243\012\377\262\320M\377\205\256\010\377\200\255\003\377}\254\001\377{\250" + "\002\377\201\251\002\377\212\255\004\377~\245\002\377i\230\001\377s\243\001\377\200\254" + "\002\377u\243\001\377y\250\002\377w\252\001\377r\242\002\377w\250\002\377w\246\002\377" + "u\244\001\377u\250\002\377{\257\012\377w\246\013\377{\253\007\377v\247\002\377w\251" + "\003\377v\243\001\377y\251\001\377_\214\001\377v\251\012\377\224\306%\377\206\267" + "\022\377{\253\001\377]\221\001\377W\215\001\377_\227\004\377d\200>\377LJR\377\063#" + "\065\377\067!\065\377_KZ\377\226\214\224\377\270\261\267\377\206|\203\377E\066" + ":\377/\033'\377P,\377j_O\377uog\377pjf\377aZZ\377" + "i^Z\377\217~y\377\204qj\377\211ys\377\220\200|\377\233\213\207\377\220}z" + "\377\264\245\242\377\231\214\225\377\206w\202\377\243\227\236\377\260\246" + "\252\377\232\213\224\377\226\204\216\377\246\221\225\377\310\273\274\377" + "\273\265\265\377~\232j\377t\234:\377o\236\021\377r\241\007\377v\245\003\377u\245" + "\001\377r\242\013\377~\260\071\377l\234\000\377\253\303\062\377\206\252\010\377s" + "\240\001\377s\241\002\377p\242\001\377q\236\001\377~\250\002\377\213\261\002\377\211" + "\255\001\377\202\251\002\377v\242\002\377z\244\002\377~\252\011\377y\247\004\377t\243" + "\001\377u\250\001\377q\243\001\377j\235\002\377o\250\002\377u\250\001\377s\242\001\377" + "g\230\002\377\\\220\001\377\200\257$\377r\244\013\377\206\265\021\377\222\302\035" + "\377\203\265\024\377[\213\000\377x\242\001\377\205\260\001\377t\241\002\377p\243\010" + "\377Ts\071\377?V\061\377$%\031\377\017\013\006\377\015\011\003\377\007\006\002\377\000\000\001\377" + "!\037!\377\000\000\000\377\000\000\000\377%!$\377\012\005\011\377$\040&\377'\024#\377i[h\377" + "zk{\377\203u\204\377\203w\204\377\223\206\225\377\246\232\242\377\317\302" + "\305\377\313\274\275\377\230\200\206\377yem\377\212v\200\377\264\244\253" + "\377\250\227\236\377\253\225\233\377\272\244\241\377\232\203\200\377\241" + "\212\205\377\226\203}\377uc_\377M\071\061\377o^V\377\250\242\232\377\265\260" + "\247\377\210~h\377{oO\377ta?\377[@\027\377U<\022\377dR-\377aN*\377bN*\377l" + "`\070\377\204\202Z\377\206\206_\377\217\217m\377\233\234\177\377\227\227z" + "\377\213\206h\377\202yY\377\221\204c\377\201pQ\377udA\377\212y\\\377~nN\377" + "^I-\377W>#\377u]M\377gJ\060\377v`G\377\245\234\224\377\231\221\201\377\204" + "zi\377mbS\377cXQ\377i`\\\377od^\377~lg\377|jg\377\204sr\377\225\205\203\377" + "\203qp\377\206qo\377\254\235\233\377\203u\201\377\221\206\220\377\231\213" + "\223\377\252\235\241\377\234\215\224\377zju\377\215|\204\377\270\253\256" + "\377\302\272\276\377\177\225n\377~\240A\377}\245\026\377o\234\001\377r\240\001" + "\377z\255\001\377u\244\010\377z\255\026\377{\250\007\377\201\250\004\377z\241\001\377" + "\214\261\033\377r\236\003\377w\247\002\377w\243\002\377\213\264\001\377\215\261\002" + "\377\212\255\002\377\207\256\002\377\202\252\001\377p\233\002\377x\242\014\377\212" + "\265,\377|\253\014\377y\251\001\377|\257\001\377s\240\001\377z\251\003\377x\245\001" + "\377q\236\001\377g\227\002\377i\233\006\377\211\265%\377\213\271\060\377~\261\026" + "\377h\233\005\377i\231\001\377p\234\001\377\201\253\002\377\220\271\003\377s\237\035" + "\377Zz+\377?S(\377\061@\036\377\012\012\003\377\000\000\000\377\000\000\000\377\000\000\000\377\015" + "\015\016\377\004\004\004\377\000\000\000\377\001\001\001\377\001\000\001\377\020\015\020\377\002\002\003\377" + "\001\000\000\377;-\071\377xgv\377zlz\377\217~\221\377\217}\216\377\243\222\235\377" + "\324\312\312\377\264\240\241\377\220{{\377lZb\377\212z\201\377\266\246\254" + "\377\261\240\243\377\303\263\261\377\301\255\250\377\266\235\221\377\231" + "~s\377\226|q\377}fa\377l[U\377g]T\377k`M\377{nU\377\177pT\377\215~b\377\210" + "y^\377q_?\377]G!\377\\D\032\377aK\037\377iV&\377m^,\377\200xI\377|tC\377wp" + "B\377\177xQ\377~xS\377\214\205`\377\206~X\377xkC\377\201uN\377\203zW\377" + "\205}^\377\233\226~\377\236\231\206\377\224\212w\377\235\223\200\377\232" + "\214u\377\237\224~\377\227\213x\377yl[\377bSA\377^UC\377PC/\377XJ;\377cV" + "L\377xmg\377\203tr\377wdd\377vef\377\204qs\377\224\200\201\377\256\240\240" + "\377\204x\201\377\204y\203\377\233\216\226\377\240\221\232\377\232\212\224" + "\377veq\377\223\201\207\377\263\247\247\377\310\304\305\377\221\241\201\377" + "m\227)\377n\231\010\377s\236\003\377t\232\003\377\213\267\032\377x\250\003\377{\251" + "\001\377k\237\002\377h\233\001\377w\247\000\377\260\277\061\377\216\246\024\377q\232" + "\001\377\177\252\002\377\203\261\002\377}\242\002\377\220\264\002\377\213\261\001\377" + "{\244\002\377u\240\003\377z\245\010\377x\246\012\377k\234\002\377z\257\002\377y\250" + "\002\377s\236\002\377\177\253\003\377z\246\001\377i\230\002\377j\231\002\377w\241\003\377" + "y\244\002\377u\246\004\377v\256\006\377e\220\002\377q\230\001\377\205\253\001\377\214" + "\261\000\377\211\265\017\377f\215\037\377Vi\063\377+>\015\377\040\062\012\377\000\000" + "\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000" + "\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377!\027\036\377h[g\377\200q\177\377" + "\237\223\241\377\204v\206\377\251\233\243\377\303\267\270\377\244\216\221" + "\377\204pv\377mYe\377\224\204\211\377\270\251\254\377\264\242\246\377\263" + "\233\232\377\271\242\231\377\267\237\224\377\237\203|\377\235\204\177\377" + "\200h`\377aH>\377ZA\064\377n_E\377sfG\377\204zX\377\242\237\204\377\243\241" + "\210\377\227\224w\377\200uT\377\203vS\377\210|U\377\203vL\377\213\204Z\377" + "\212\205Z\377\213\205]\377\213\204_\377\177vO\377xk?\377m]/\377iY.\377pb" + "\067\377skB\377}zZ\377\226\227\204\377\223\216|\377\237\235\213\377\250\246" + "\224\377\240\235\210\377\213\200k\377Q<'\377VD\066\377eVO\377O>'\377XH+\377" + "^O/\377]J,\377eT:\377\217\200x\377\210xx\377\177nl\377\202pn\377\214|x\377" + "\210sq\377\236\215\212\377~pz\377\215\201\212\377\246\231\241\377\221\201" + "\213\377\237\222\231\377rdn\377\215}\207\377\256\241\244\377\274\266\267" + "\377\226\243\205\377g\223\033\377e\224\003\377j\222\002\377p\225\004\377\224\272" + "\061\377\204\256\020\377~\251\002\377i\237\001\377b\230\000\377n\237\001\377\210\247" + "\021\377\276\311P\377|\241\004\377x\243\002\377{\253\002\377v\240\001\377\215\264" + "\002\377\202\250\002\377\200\246\002\377\204\254\002\377s\232\001\377y\245\001\377t\241" + "\001\377r\240\002\377o\234\002\377o\237\002\377y\250\002\377v\242\002\377s\237\002\377" + "l\232\002\377i\224\002\377u\242\001\377q\236\001\377r\244\002\377m\233\002\377\203\257" + "\003\377\211\262\003\377\222\272\021\377\213\263E\377\221\266V\377w\215d\377a" + "\202E\377\065M\"\377\034.\020\377\016\032\002\377\000\000\000\377\000\000\000\377\000\000\000\377" + "\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\"" + "\035!\377b[c\377sds\377\230\212\235\377\204u\211\377\246\227\241\377\302\267" + "\266\377\232\210\210\377\213y\200\377s`m\377|jv\377\247\225\233\377\216z" + "\203\377\260\234\230\377\254\225\216\377\262\232\215\377\224zo\377\207le" + "\377oVO\377s\\S\377fRE\377\\N\066\377h^=\377ld@\377}wW\377\215\211k\377zu" + "Z\377}x\\\377\206|^\377|mF\377\215\202]\377\215\203\\\377|qI\377\212\200" + "\\\377\224\215n\377\203uP\377{kA\377m\\.\377hW/\377gW\061\377ujI\377\203|" + "b\377\203}c\377\202y]\377|rO\377xkH\377YF)\377maG\377K<\034\377RE'\377zqf" + "\377SC&\377P@\036\377VA!\377P:\031\377aO\063\377\204tc\377\226\213\213\377u" + "cb\377\213zw\377\220\177y\377\216xt\377\230\205\203\377wep\377\206u\201\377" + "\246\234\241\377\220\206\216\377\227\214\223\377k^h\377qcm\377\244\227\232" + "\377\274\270\272\377\212\227w\377e\222\035\377`\216\001\377p\233\002\377r\231" + "\003\377\225\273-\377|\243\001\377\201\257\003\377r\244\007\377r\247\017\377g\230" + "\001\377t\231\002\377\270\306S\377\214\256\033\377y\245\001\377o\234\002\377r\237" + "\001\377{\246\001\377\201\250\001\377\201\246\002\377\206\250\002\377}\240\003\377\211" + "\257\002\377\177\247\001\377w\241\001\377q\240\001\377w\252\002\377f\232\002\377w\244" + "\001\377~\244\001\377j\223\002\377q\227\002\377t\243\002\377v\246\002\377y\251\005\377" + "g\227\001\377s\243\002\377|\252\002\377u\241\002\377l\232\010\377c\215+\377=]$\377" + "Ms,\377Jb>\377WlL\377[mX\377XlW\377NcM\377N`H\377AR?\377-\066,\377\012\016\011" + "\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377'#'\377JAI\377ses\377\225\207" + "\230\377\205v\210\377\270\255\262\377\271\254\254\377\245\224\224\377}kt" + "\377k[g\377\201t}\377\253\232\236\377\240\215\220\377\251\222\216\377\255" + "\222\213\377\274\242\225\377\220ra\377\225xj\377\220ti\377x^R\377iRA\377" + "N\071\036\377=,\013\377dW\064\377{rO\377\221\213m\377\214\204j\377}qW\377|lP" + "\377\203sU\377\210wZ\377\201pO\377\212yX\377\204rW\377\234\224\200\377\231" + "\221{\377\211|b\377\221\207m\377\211\201h\377\207\201h\377\212\206m\377\203" + "ze\377\204{e\377\200xZ\377YO$\377_R(\377reF\377gZ\064\377[M%\377Q@\030\377" + "rdP\377@/\013\377VC\040\377ZD#\377\\E(\377yfP\377wdT\377~oj\377\210yy\377~" + "je\377\206pi\377\224\200y\377\227\203\201\377wfr\377\215~\207\377\252\236" + "\244\377\235\220\227\377\235\217\227\377l^j\377\203u}\377\230\213\215\377" + "\265\256\264\377u\211X\377_\212\022\377_\214\001\377x\244\022\377u\243\011\377" + "|\247\013\377y\244\001\377u\245\000\377\203\265)\377\201\265\063\377g\236\017\377" + "}\250\004\377\207\252\014\377\240\270\035\377\214\256\002\377\201\245\002\377|\243" + "\001\377k\231\002\377x\243\002\377}\243\002\377\217\261\002\377\215\255\002\377p\230" + "\002\377u\236\002\377~\252\001\377~\254\001\377u\245\002\377Y\216\002\377l\230\002\377" + "v\235\001\377q\230\002\377u\234\002\377z\252\003\377p\231\003\377x\240\001\377g\236\003" + "\377t\247\001\377z\246\002\377u\234\002\377x\240\002\377W\201\003\377;a\003\377#H\002\377" + "\036\064\004\377\013\013\006\377\004\004\003\377\001\001\001\377\001\000\001\377\000\001\001\377\003\011\003\377" + "(\067%\377b{^\377w\222y\377AQ?\377\015\023\011\377\035\037\023\377==\066\377<:<\377" + "kbn\377\215\177\220\377\216\177\217\377\264\251\255\377\270\254\253\377\240" + "\216\217\377\211w~\377m\\g\377\202v|\377\267\252\254\377\234\206\216\377" + "\244\215\214\377\226yq\377\256\225\211\377\237\201p\377\221qa\377~bO\377" + "rWB\377fN\066\377UB\"\377C\064\020\377?\061\017\377J\066\026\377kV\070\377n\\B\377" + "\213\205v\377\230\224\205\377\211\200m\377\215\200k\377\231\214w\377\241" + "\226\201\377\232\216w\377\215\201i\377\241\234\210\377\243\241\215\377\235" + "\234\207\377\223\220y\377\224\216t\377\205}[\377ykC\377kZ\061\377sd<\377]" + "H\033\377Q\071\014\377sb=\377l^\064\377VC\033\377G\063\020\377]L\070\377G.\024\377" + "K\063\025\377M\066\027\377q^D\377zfT\377r]Q\377\202oi\377zgb\377\230\207|\377" + "\223\200u\377\205qn\377\226\207\210\377udp\377\200q|\377\223\210\216\377" + "\232\220\224\377\220\205\214\377fYe\377o`k\377\240\224\231\377\261\254\260" + "\377s\211X\377a\212\037\377f\222\027\377i\230\010\377x\250\010\377v\244\003\377" + "v\241\001\377{\246\007\377\200\261\032\377t\250\013\377l\243\006\377e\234\002\377q" + "\237\002\377\200\247\011\377\230\267\013\377\231\267\002\377\225\265\002\377m\232" + "\002\377u\241\002\377\205\260\002\377\223\270\002\377\212\254\001\377i\225\002\377x\242" + "\002\377\206\256\001\377\202\254\002\377u\242\002\377l\232\002\377c\222\001\377y\245" + "\003\377u\237\001\377p\233\002\377t\237\002\377w\233\001\377}\241\003\377g\240\006\377" + "u\250\001\377y\245\002\377}\247\001\377z\242\002\377]\211\001\377Ak\004\377%@\002\377." + "\063#\377!%\026\377\016\016\013\377\000\000\000\377\000\000\000\377\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\377\000\000\000\377\011\015\011\377:J#\377`l;\377@G*\377;<\064\377l" + "gn\377\224\210\224\377\207}\210\377\255\244\250\377\272\257\260\377\233\214" + "\216\377xjo\377^PZ\377{ms\377\260\244\245\377\246\225\230\377\243\220\213" + "\377\212ql\377\272\245\235\377\240\202q\377~XB\377yT?\377V\063&\377Z=,\377" + "s^E\377mW\070\377S<\033\377G/\013\377K\064\023\377xhR\377\202ub\377wiV\377\225" + "\217}\377\220\211v\377\230\221\200\377\235\226\204\377\250\241\216\377\243" + "\236\211\377\223\214q\377\221\212m\377\215\204d\377ykE\377xgB\377vb\064\377" + "lV%\377gP#\377\\D\031\377aK!\377ziB\377\177qF\377fP&\377B*\013\377\060\027\003" + "\377ZA\063\377W=,\377pYC\377\202nX\377\213xj\377fMC\377pYP\377nUN\377\206" + "oj\377\237\212\202\377\202ka\377\231\206}\377\235\220\214\377~v{\377\212" + "\201\210\377\235\221\230\377\241\226\234\377\205x\202\377`S`\377l_j\377\241" + "\232\240\377\244\243\246\377i~\071\377`\202\025\377x\244@\377`\216\002\377|\254" + "\005\377v\243\001\377y\247\002\377z\250\006\377w\246\004\377t\241\000\377}\256\005\377" + "i\235\001\377k\225\001\377|\242\001\377\210\251\002\377\214\255\001\377\214\257\001\377" + "y\241\001\377v\240\001\377\201\250\002\377\203\247\002\377\205\250\002\377s\233\001\377" + "~\247\002\377\210\264\002\377}\250\001\377x\242\002\377x\245\001\377m\232\001\377{\245" + "\004\377}\250\020\377x\245\002\377s\232\002\377l\217\002\377\207\246\002\377n\251\003" + "\377k\237\002\377k\232\002\377k\233\001\377g\231\003\377]\221\001\377Hx\003\377\031+\005" + "\377'\060\030\377MOE\377,**\377\012\007\010\377\000\000\000\377\000\000\000\377\000\000\000\377\000" + "\000\000\377\000\000\000\377\001\002\000\377\011\027\002\377,D\010\377\060I\010\377\062E\020\377=" + "H)\377rtq\377\232\221\231\377\221\206\216\377\221\205\214\377\261\245\244" + "\377\211y\177\377hX`\377UHP\377\221\206\212\377\252\240\243\377\243\224\227" + "\377\235\212\204\377\215yl\377\253\227\212\377\257\224\206\377\203]I\377" + "\222o^\377\205h\\\377t]R\377nWA\377xaD\377u`;\377hR*\377aI#\377eN+\377Y:" + "\030\377wbK\377xiS\377\177pZ\377\215\177h\377\177pT\377\230\216t\377\226\212" + "n\377\204vR\377\205wU\377\222\210i\377\216\206f\377\214\203e\377\221\206" + "h\377\223\204f\377\202pW\377\224\203o\377\215}a\377xdB\377hM-\377;\040\006\377" + "@'\015\377A'\015\377{fR\377s\\@\377jR<\377oZK\377yf[\377aKG\377eOI\377oWQ\377" + "\241\213\203\377\210lg\377\203bZ\377\232\203\200\377\233\221\223\377\205" + "\200\205\377\230\224\230\377\252\242\245\377\252\237\244\377\216\200\211" + "\377VGR\377gXe\377\230\216\226\377\236\233\235\377{\210S\377g\201\060\377" + "{\251F\377f\234\006\377p\236\002\377\177\252\002\377z\245\003\377y\244\002\377s\241" + "\003\377t\237\002\377\200\250\001\377|\252\004\377j\226\002\377w\240\001\377}\241\003\377" + "\177\243\001\377\200\244\002\377\177\245\001\377\177\246\003\377\201\251\002\377s\232" + "\002\377\177\243\001\377\200\244\002\377\207\260\002\377|\251\002\377w\246\001\377r\234" + "\001\377v\244\000\377\212\256\016\377l\222\002\377|\252\027\377r\240\002\377w\236\002" + "\377|\237\002\377\177\241\002\377p\253\011\377U\200\000\377Z\204\002\377Y\206\002\377" + "[\220\006\377\\\232\006\377S\211\004\377\020\034\003\377\000\000\000\377\023\022\016\377\"\034" + "\025\377\013\012\006\377\000\000\000\377\000\000\000\377\000\000\000\377\001\001\001\377\007\014\001\377\027" + ")\001\377&E\003\377\066^\011\377;e\020\377Mr&\377.A\030\377_[Z\377\220\203\215\377" + "\214\200\211\377\231\216\224\377\276\263\262\377\220\200\203\377g[d\377O" + "@K\377QDH\377\236\223\222\377\247\227\226\377\243\217\213\377\200kd\377\231" + "\204y\377\262\235\221\377\237\201t\377\201aS\377mOA\377I*\036\377hO>\377r" + "X?\377|gI\377v`;\377lW-\377r\\/\377oV)\377~iA\377u_\071\377~jH\377\210yY\377" + "\231\217q\377\235\224x\377\241\231}\377\216\202b\377\215\200a\377\205z]\377" + "\211~d\377\200s\\\377\177r`\377\213\177p\377\222\206z\377~oZ\377|jJ\377Q" + "\071\024\377:!\005\377F.\020\377\\H#\377nX\066\377\231\210s\377{gK\377nYE\377v" + "cQ\377]L>\377aQB\377bL>\377zaT\377\220{l\377|bT\377\200fW\377\273\262\252" + "\377\222\205\210\377\200pz\377\210}\202\377\227\216\220\377\216\205\212\377" + "i^d\377L?K\377d[d\377\226\214\225\377\207\206|\377l|M\377k\225>\377t\251" + "M\377i\240\021\377i\227\001\377t\237\002\377x\241\002\377w\237\000\377\200\254\016" + "\377v\236\003\377\206\250\002\377\230\274\026\377|\250\010\377t\240\002\377~\250" + "\002\377y\237\001\377\220\256\002\377~\240\002\377\205\254\001\377\203\253\002\377\200" + "\247\001\377\202\247\002\377}\243\001\377\204\255\002\377m\233\002\377z\256\016\377" + "{\254\012\377m\226\002\377\207\251\011\377\210\254\015\377\177\254\017\377k\227" + "\002\377\205\252\006\377r\226\002\377{\245\004\377b\243\013\377`\230\015\377Z\206\004" + "\377_\215\001\377Y\212\002\377]\224\000\377[\231\012\377/O\006\377\022\035\002\377\001\002" + "\001\377\000\000\000\377\000\000\002\377\002\003\001\377\006\011\002\377\005\007\002\377\012\030\002\377\031" + ".\002\377;X\006\377:_\003\377\066_\003\377=j\016\377=_\032\377\071D*\377a[^\377\213\177" + "\211\377\225\213\224\377\214\200\211\377\253\237\242\377\231\211\214\377" + "pdk\377ZOW\377d^`\377\203{z\377\231\215\216\377\273\254\246\377\237\210\201" + "\377\177rh\377\261\242\226\377\263\242\224\377\215r^\377v\\H\377|bT\377i" + "O?\377s^O\377xdN\377\206sU\377\205pK\377\222\177W\377\200k?\377oU&\377\204" + "oK\377zfF\377\205rV\377\201nU\377\236\224~\377\205tX\377\216\200`\377\222" + "\204c\377\215|Y\377\230\210h\377\206wU\377\203pU\377t`G\377fS>\377\\K\066" + "\377=*\026\377\061\035\004\377N\070\021\377eR%\377ub\066\377\215{U\377\217\177h\377" + "T<\036\377zeN\377bJ\066\377bJ<\377}f\\\377xaW\377\247\223\216\377w]V\377`F" + ";\377\204rj\377\274\264\254\377\212}\200\377\217\204\211\377\237\226\232" + "\377\230\217\225\377\211\201\210\377`Xa\377F?J\377`Ya\377\243\236\240\377" + "sx`\377l\216>\377\\\217\027\377u\252>\377j\235\006\377o\233\002\377k\225\001\377" + "~\245\002\377z\241\002\377v\235\000\377w\237\002\377\217\264\021\377\212\255\006\377" + "\207\256\010\377t\240\001\377y\244\002\377w\237\002\377\214\254\002\377\211\251\001" + "\377\207\250\002\377\201\246\002\377y\240\002\377}\245\001\377w\236\002\377|\250\002" + "\377b\222\002\377x\252\011\377t\234\001\377~\240\002\377\206\252\007\377}\242\005\377" + "\200\252\014\377m\225\002\377x\236\001\377y\235\003\377\202\253\025\377U\223\001\377" + "c\237\020\377a\232\012\377_\222\001\377c\223\001\377d\227\002\377Y\206\002\377\\\220" + "\011\377R\177\014\377#\067\002\377\023$\002\377\013\031\002\377\034'\002\377?F\013\377;H" + "\013\377\012*\002\377!E\003\377\067^\002\377Ly\003\377Nz\012\377t\246H\377\067R\021\377" + "?O+\377]`Y\377\200z\177\377\201w}\377|px\377\247\233\234\377\233\215\216" + "\377rfk\377SEQ\377LCK\377\214\205\204\377\252\236\234\377\273\256\246\377" + "\250\215}\377pZJ\377\217|p\377\302\266\255\377\234\205r\377z[B\377rS<\377" + "~`I\377oQ:\377mO?\377|cO\377\213wY\377\230\205d\377\222\200^\377\210uR\377" + "\206qO\377\202jF\377|b<\377\212rQ\377\206oL\377\206oI\377\202jC\377za\070" + "\377tZ\060\377\207uX\377\213|_\377vfL\377\\N\064\377\065\"\012\377\065\040\010\377" + "\066\040\004\377Q:\026\377r_\070\377\214zW\377\223\202a\377\206rU\377\201kV\377" + "kT;\377\\A*\377fK\067\377sZK\377|d[\377\233\213\204\377\232\213\205\377}h" + "_\377hRI\377\240\221\207\377\263\253\250\377|ou\377\214\202\206\377\211\177" + "\205\377\243\233\240\377\203\177\205\377UNX\377JAL\377h`g\377z|o\377kzV\377" + "g\231\064\377c\225#\377\202\261A\377n\232\004\377n\232\002\377p\222\002\377\224" + "\251\002\377\215\251\001\377x\231\001\377}\252\006\377{\241\003\377\205\253\002\377\205" + "\255\002\377|\246\001\377y\242\002\377z\242\002\377\201\244\001\377~\236\001\377\207" + "\252\002\377\202\247\002\377\177\244\001\377\202\251\002\377\215\270\003\377x\244\002" + "\377`\217\002\377o\237\002\377r\231\002\377\207\254\002\377p\225\003\377n\223\002\377" + "y\245\010\377c\215\002\377s\234\002\377\204\256\007\377x\237\002\377d\230\010\377c" + "\227\006\377\\\214\001\377Q}\002\377]\211\001\377^\206\001\377`\206\002\377Z~\001\377Y" + "\210\005\377=a\003\377%G\002\377\060J\002\377/B\003\377/?\002\377GV\005\377-F\002\377*O\003" + "\377\065\\\002\377Q|\002\377`\220\015\377X\205\031\377;c\006\377Ih\"\377m{_\377\205" + "\206~\377\204~}\377\201vz\377\246\236\236\377\232\217\217\377pbf\377I:D\377" + "<-\067\377WJM\377\201rq\377\241\223\216\377\266\243\225\377\201fV\377dNG\377" + "\236\213~\377\250\221|\377\211lP\377pL/\377}]@\377\205hN\377\177dJ\377mL" + "\061\377qR\066\377yaF\377\221\202g\377\226\213p\377\236\225z\377\247\236\204" + "\377\232\215t\377\231\211n\377\215|_\377\222\201d\377\230\210l\377\210vV" + "\377~jK\377vbG\377iS\070\377aJ/\377S>\036\377V@\033\377mY\067\377hP.\377[@\040" + "\377\231\205e\377\243\223u\377zdM\377v^D\377\203nS\377w[B\377^@)\377\210" + "pZ\377\237\211y\377\214uh\377\242\222\211\377]LF\377G\065\062\377\204rm\377" + "\304\275\271\377\222\210\207\377\204y~\377\226\214\217\377\237\226\231\377" + "\235\227\235\377oms\377@:E\377@\071F\377pmo\377ip\\\377m\206Y\377d\222\067" + "\377a\224(\377m\244\036\377`\220\000\377~\252)\377y\232\006\377\232\260\004\377" + "\215\251\002\377\200\245\002\377z\244\004\377n\224\002\377\200\245\002\377\205\251" + "\002\377\215\263\002\377t\235\001\377t\235\002\377~\242\002\377\204\251\002\377z\237" + "\002\377\207\256\001\377\177\244\002\377\211\260\001\377\204\251\001\377~\246\002\377" + "q\236\002\377a\216\001\377s\234\001\377w\235\002\377f\214\002\377l\221\000\377v\237\003" + "\377l\223\002\377r\232\002\377\201\247\002\377{\241\000\377\204\260N\377}\246\060" + "\377a\212\002\377Do\002\377Y|\002\377X{\002\377Rx\001\377\\\203\001\377Mv\002\377Jw\003\377" + "Ky\004\377Cd\002\377\064O\003\377\035\067\001\377)=\001\377:M\002\377>V\002\377\062O\002\377" + "\377e[b\377\204z" + "y\377\210xw\377\307\267\256\377\221wj\377^H>\377\201i_\377\215uh\377\227" + "{g\377\242\206j\377\234}[\377\207gE\377sS\066\377\201bH\377a@\"\377jL-\377" + "\177jK\377\201pT\377\221\210u\377\243\235\212\377\234\226\202\377\245\236" + "\216\377\240\233\214\377\243\233\214\377\235\223\204\377\223\206v\377\213" + "|l\377\224\205w\377\206sa\377\200nV\377\206tX\377\207oR\377z_;\377\203hH" + "\377\231\204b\377\251\234y\377}gP\377eI\065\377\216yb\377~iP\377fI-\377}a" + "G\377\241\213q\377\250\227\204\377\226\205s\377\217\202u\377A,$\377\\J?\377" + "\244\230\217\377\303\276\271\377\203\177\202\377\202{\200\377mck\377\213" + "\203\207\377\203y\200\377NDN\377JDL\377MIP\377ppm\377ahR\377{\235j\377Y\207" + "-\377d\225+\377a\226\014\377a\220\003\377p\232\012\377n\221\002\377{\244\002\377" + "y\241\002\377z\243\003\377k\223\002\377o\230\002\377}\250\002\377\203\254\002\377\207" + "\263\002\377p\241\003\377j\226\002\377\177\246\001\377\210\256\001\377\205\253\001\377" + "\202\252\002\377~\246\002\377\206\255\001\377w\234\002\377\206\254\006\377u\233\002\377" + "x\241\003\377w\240\002\377l\221\001\377m\224\001\377|\252\017\377\204\265\030\377|" + "\256\016\377\211\272\035\377\224\300)\377\215\270\036\377^\222\005\377p\233\012" + "\377r\226\007\377n\215\007\377`}\001\377_\177\001\377]\177\001\377Z\203\002\377Kt\002\377" + "It\002\377J\177\003\377Cj\002\377\060O\001\377@X\004\377\032\070\002\377\037<\002\377,I\000\377" + "\063W\001\377Mv\004\377\\\206\037\377Jj\002\377Yx\005\377]x\036\377Xe?\377poi\377\205" + "{\201\377\205z\201\377\225\213\215\377\232\217\217\377~tz\377_S[\377A\071" + ">\377\071\063\064\377]YU\377\177xv\377\272\255\245\377\253\227\203\377lP@\377" + "T\066-\377\203m`\377\264\240\215\377\253\226y\377\252\224v\377\231\177c\377" + "\207mS\377tU;\377fE$\377nP/\377bH%\377\201oP\377\215\177d\377\204uZ\377\210" + "}f\377\224\217\201\377\222\216\200\377\212\201r\377\232\221\204\377\243\235" + "\215\377\226\216z\377\227\211t\377\215|f\377\203pS\377q[\067\377\206nJ\377" + "\240\214k\377\257\242\205\377\242\222t\377{dK\377^A.\377w^I\377zcK\377nR" + "\070\377\200eM\377\237\213x\377\261\245\223\377\236\217|\377\220\201q\377" + "S?\062\377P<\061\377\214zj\377\271\262\244\377\244\233\223\377\205|{\377\220" + "\207\207\377\220\207\213\377\206{\200\377obl\377OEP\377F?G\377VRU\377qrg" + "\377brQ\377r\241S\377\\\216-\377b\227%\377T\204\005\377f\222\010\377g\215\001" + "\377k\223\001\377v\244\003\377\177\255\013\377y\246\004\377g\222\002\377x\243\002\377" + "\177\254\002\377\201\255\002\377t\243\001\377m\243\002\377l\232\001\377|\244\001\377" + "\210\256\001\377\201\247\002\377}\245\002\377|\247\002\377\177\247\001\377{\237\002\377" + "\210\254\002\377{\237\002\377\206\262\005\377z\244\005\377\204\257\016\377\224\275" + "$\377\225\277#\377\206\263\017\377\205\264\013\377y\243\004\377\207\265\033\377" + "\214\270#\377V\213\003\377\\\215\002\377Z}\001\377x\222\021\377]v\003\377^x\001\377" + "Zv\001\377^}\003\377Wu\002\377A`\002\377\"K\002\377<^\002\377Rk\003\377Z\003\377o\237I\377j\223>\377" + "_\210\030\377Hm\003\377Or\007\377Tv\006\377g\207!\377g\205!\377b\177!\377u\206U" + "\377_^O\377pmg\377vsn\377tqj\377\221\211\200\377\210\177x\377h^^\377g\\_" + "\377dYa\377ZRY\377GAD\377]XP\377\200zl\377\270\261\227\377\214\177a\377G" + "\060!\377V?.\377{fR\377\232\211{\377\212yh\377}jU\377\240\217y\377\227\204" + "i\377\205iH\377\201e?\377\210oI\377\206pJ\377\217\200]\377\177oK\377\211" + "{X\377\213\203^\377\200wU\377\215\206d\377\212\202a\377\222\215o\377\220" + "\207n\377\226\212p\377\200oK\377\177hC\377~e=\377\207tO\377\210uT\377\232" + "\211k\377\244\224z\377\257\242\214\377\267\253\232\377\252\235\213\377\231" + "\210v\377\203sf\377scZ\377K\066(\377fN\067\377\246\231\204\377\252\244\223" + "\377\203wk\377ynd\377ka[\377\177{v\377\213\211\207\377xtx\377d^g\377`Zc\377" + "igk\377ddc\377w|t\377bwS\377]\216\066\377My\002\377R\203\005\377Y\215\011\377f" + "\230\005\377|\244\004\377w\235\004\377u\234\002\377p\226\002\377r\231\002\377r\232\001" + "\377j\226\002\377\202\252\002\377\201\252\002\377|\246\001\377u\243\007\377t\246\031" + "\377\211\277U\377\201\255\021\377~\246\002\377n\230\002\377\177\251\004\377\207" + "\251\002\377\250\275\025\377\230\263\016\377\205\240\002\377\221\260\023\377\210" + "\257\010\377\204\251\020\377}\232\006\377\216\250\002\377\254\271\035\377\222\256" + "\003\377\201\242\001\377\206\257\001\377\200\251\001\377z\246\001\377T\203\002\377V\206" + "\006\377[\214\006\377@e\001\377[\207\005\377a\221\004\377Z\203\001\377`\207\006\377S~\002" + "\377Z\202\001\377Op\004\377Vs\002\377Gf\002\377\063S\002\377Dd\002\377Ec\007\377h\243\060" + "\377S\205\000\377Lq\003\377C`\001\377Tq\003\377Lg\001\377o\211'\377{\230F\377drC\377" + "VYE\377yvn\377yvo\377||s\377rph\377\225\221\211\377~vu\377WLS\377ZNW\377" + "nhm\377^[[\377_\\U\377\\XL\377\213\205r\377\250\241\207\377o_J\377M:\"\377" + ">)\023\377{pe\377\222\212z\377kXC\377uaL\377\231\211r\377\243\223y\377\226" + "\201b\377\202jB\377\207pI\377\210wN\377\212|T\377\221\206_\377~tN\377\207" + "\200^\377\203~Z\377}uT\377\215\205j\377\204uX\377\217\200_\377\204qJ\377" + "\210tL\377\204tK\377\242\224t\377\250\232~\377\264\252\226\377\234\215u\377" + "\264\250\225\377\237\222\200\377\221\202n\377\226\210w\377{na\377G\061+\377" + "T?\071\377\236\217}\377\265\253\235\377\233\220\207\377\177rl\377ped\377~" + "wu\377}xy\377c^e\377D;I\377H?L\377c`e\377||z\377lri\377s\201n\377f\213U\377" + "X\177!\377Z\213\010\377X\211\003\377`\216\003\377t\240\002\377\206\253\017\377r\232" + "\002\377x\244\002\377f\215\002\377\202\246\007\377\201\243\002\377|\236\003\377\205\257" + "\002\377\177\245\002\377\200\250\001\377p\237\007\377n\236\015\377\225\304n\377}\246" + "\024\377x\240\002\377y\245\002\377~\247\002\377\201\247\002\377\246\300\022\377\262" + "\265/\377~\230\004\377\236\277&\377}\253\006\377{\246\015\377\201\242\003\377\221" + "\252\001\377\242\250\025\377\226\257\011\377\206\251\002\377\204\257\001\377\203" + "\253\000\377\177\245\000\377a\222\001\377q\242\023\377V\207\002\377M~\002\377L|\003\377" + "Y\216\002\377W\214\002\377Y\217\016\377Y\213\026\377T~\023\377X|\006\377Kf\001\377b" + "\223\015\377En\001\377Z\201\012\377f\223*\377V\213\010\377W\215\003\377Hn\001\377" + "Pp\002\377Qp\004\377Oo\007\377t\223H\377[|\060\377Le%\377HT.\377Y[J\377kl_\377d" + "dZ\377{ws\377\207~|\377vlm\377ZMV\377f[c\377i^f\377\\RT\377kea\377}yn\377" + "xth\377\224\217z\377\251\244\210\377{mR\377cSF\377P>\065\377via\377\206ug" + "\377\202o_\377\207ue\377\245\226\202\377\250\234\201\377\224\204c\377\220" + "}Z\377\205sL\377\212|U\377\212\201[\377\211\201\\\377\212\177]\377\216\205" + "b\377\203vT\377\220\204f\377\206wW\377\223\205b\377\215}Z\377\235\216l\377" + "\237\220m\377\232\215k\377\245\230|\377\243\227\200\377\222\202j\377\221" + "\201j\377~l[\377\214~m\377uf]\377Q:\070\377bN@\377\227\211o\377\246\232\205" + "\377\237\226\205\377\200yn\377\200}v\377vtr\377xtu\377khi\377okn\377a^e\377" + "KIO\377\\]^\377pzo\377n}j\377bwZ\377e\234K\377Hz\004\377V\211\003\377b\226\005" + "\377g\231\002\377k\232\001\377t\244\005\377q\240\002\377t\245\004\377j\227\001\377|\251" + "\003\377|\234\000\377|\237\002\377v\236\002\377z\246\002\377n\232\002\377p\235\001\377" + "y\250\062\377\240\313\213\377z\250%\377\177\252\000\377m\232\002\377\200\246\002" + "\377\213\260\002\377\224\265\003\377\243\267!\377\227\265\036\377w\237\000\377u" + "\236\001\377z\247\002\377\201\252\002\377\204\247\002\377\216\255\016\377\224\266" + "\012\377\211\262\002\377|\244\002\377\235\273\026\377\212\246\001\377b\232\006\377" + "g\233\020\377]\215\002\377X\214\002\377Y\217\004\377^\222\004\377X\211\001\377N|\003\377" + "S\200\007\377a\216\020\377p\221\"\377Ru\002\377Py\002\377e\230\004\377k\226\024\377" + "m\236\035\377e\225\002\377\\\215\001\377V\212\001\377Hr\002\377Jq\003\377`\204,\377" + "Y\177)\377Qq!\377Og#\377EU\040\377bfJ\377ij[\377xvl\377}tp\377\210~|\377n" + "ad\377eW]\377pdl\377S@N\377WJO\377j`^\377rog\377||r\377ywk\377\224\216v\377" + "\236\225v\377{qY\377L<\060\377D\060-\377mZV\377\230\215z\377\216{k\377\215" + "{h\377\235\216z\377\241\224{\377\240\222u\377\224\206e\377\222\203d\377\205" + "vY\377\217\203g\377\217\204g\377\223\210k\377\207y\\\377\224\214q\377\213" + "\203e\377\234\222u\377\215\177]\377\243\225s\377\225\206b\377\212xR\377\204" + "pK\377\205qO\377\222\201i\377\235\220|\377\217\203w\377vi]\377O\071\061\377" + "M/(\377\235\216|\377\256\243\222\377\225\210y\377vk`\377xpk\377spn\377zz" + "z\377utw\377^Y\\\377B;C\377TNU\377baf\377pss\377qys\377m\201l\377_\203R\377" + "X\215\"\377T\205\001\377\\\217\004\377Y\211\003\377b\231\007\377c\227\006\377u\236" + "\020\377q\236\002\377t\242\003\377s\240\002\377p\233\001\377\207\260#\377v\237\002\377" + "i\224\001\377s\241\002\377c\223\002\377p\237\002\377e\226\002\377\222\302z\377\200" + "\264\065\377y\243\000\377\204\250\001\377\220\262\003\377\221\270\001\377\207\260" + "\002\377\207\253\006\377\256\302C\377\204\245\014\377w\233\001\377\204\254\002\377" + "\212\257\002\377\217\255\012\377\211\245\004\377\217\262\001\377|\241\002\377\177" + "\244\004\377\215\242\016\377\214\245\001\377_\227\004\377a\230\004\377]\223\002\377" + "R\206\001\377U\211\002\377]\221\003\377W\204\001\377Ot\002\377Y\200\002\377Z}\002\377U" + "w\001\377Nr\001\377Qw\002\377Ow\000\377a\224\007\377\\\216\002\377s\241\002\377e\224\002" + "\377`\222\002\377X\220\004\377l\233=\377Y\177'\377X}\032\377b\206*\377Zx&\377" + "Xo,\377aoC\377tzd\377vvl\377xso\377|sq\377znn\377|tt\377zps\377jad\377ul" + "g\377H>?\377\\XT\377lja\377oh^\377_TB\377\205}`\377~sR\377\177pV\377n\\L" + "\377YIE\377D\062*\377rdV\377ygV\377\177kX\377\235\220\177\377\236\224|\377" + "\235\220u\377\236\220p\377\206wW\377\207vY\377\207x\\\377\211y\\\377\177" + "lO\377\221\203e\377\223\207f\377\212|[\377\214|Z\377\210wR\377xe:\377wb\066" + "\377\217\177\\\377\230\210l\377\222\207q\377\231\220\200\377i^Y\377QCA\377" + "H\067\061\377\217\177b\377\261\246\221\377\235\221\202\377\215\203x\377\216" + "\205~\377jaa\377zyy\377wxx\377]^a\377C>D\377*\040*\377RQQ\377]_[\377rxv\377" + "{\206|\377s\216l\377b\230G\377Jz\000\377b\230\006\377^\223\003\377\\\221\001\377" + "e\234\016\377h\233\021\377u\241!\377n\233\002\377\177\253\004\377w\246\003\377[\204" + "\000\377v\247\034\377m\232\005\377l\227\004\377p\236\001\377v\250\020\377{\252\002\377" + "o\233\001\377n\241\014\377y\255\022\377u\236\001\377\211\251\002\377\231\263\010\377" + "\244\300\010\377\204\246\000\377\221\260\026\377\215\250\"\377\270\315n\377\201" + "\243\006\377\202\246\002\377\210\250\000\377\232\252\017\377\213\235\001\377\233\273" + "\001\377\211\254\001\377\204\252\002\377v\231\001\377\206\250\002\377e\234\014\377c" + "\231\012\377^\222\002\377Z\214\002\377a\221\003\377b\216\003\377e\212\003\377_\200\002" + "\377Su\002\377[y\002\377Vr\001\377[{\002\377`\210\002\377i\223#\377]\213\016\377Nu\005" + "\377v\241\005\377T\202\002\377\067d\000\377^\212'\377o\234\064\377S\200\000\377v\241" + "\020\377\223\265\022\377\237\301(\377\214\260Q\377g\202:\377`tB\377~\200v\377" + "\201\200|\377\205\202\177\377\210\205\200\377\204\204~\377\214\222\210\377" + "fa`\377?\060\066\377<\061\064\377PIK\377d[[\377phc\377uo`\377rjQ\377\201zZ\377" + "\247\237\204\377\227\211l\377fVC\377SB\065\377\067$\036\377QA;\377dSG\377uh" + "[\377\217\202o\377\214zf\377\240\220w\377\215|[\377\210y[\377\200sX\377}" + "oS\377\200pQ\377weB\377\203sO\377\212{W\377vbC\377\202oQ\377\207uZ\377\232" + "\212r\377\224\204p\377\225\207v\377ti`\377bVT\377L=?\377jZN\377\231\211n" + "\377\261\246\213\377\237\221w\377\215\201k\377\202{j\377ytk\377\204\205\200" + "\377{\177|\377rtt\377YZZ\377QTQ\377\\dU\377bp[\377\\gX\377mzk\377o\210m\377" + "Eu%\377P\207\036\377^\220\001\377[\221\002\377V\213\003\377c\227\002\377c\224\013\377" + "g\227\010\377Z\201\000\377h\220\002\377\202\252\001\377~\251\020\377\201\262/\377" + "\203\261\063\377\202\260\063\377\203\254\025\377\204\261\040\377v\244\021\377" + "y\247\002\377h\227\002\377o\237\003\377|\264;\377}\257\026\377\214\264\002\377\204" + "\246\002\377\225\261\001\377\246\267\002\377\212\245\013\377\233\267<\377\244\302" + "U\377\223\267*\377z\237\000\377\216\257\005\377\246\263$\377\247\274/\377\231" + "\266\000\377\216\254\002\377\203\246\003\377\203\251\003\377\217\263\002\377_\220\001" + "\377Y\212\000\377M~\000\377U\204\000\377V\205\000\377a\217\003\377c\214\002\377_\203" + "\000\377_\204\002\377b\212\003\377X\177\002\377Y\204\003\377d\223\023\377Oy\033\377C" + "o\000\377h\212\036\377~\246\024\377O\200\000\377Z\211)\377Kp&\377U\202\001\377f\225" + "\003\377x\241\003\377\211\254\002\377o\220\010\377\216\260R\377u\226;\377Yv,\377" + "\205\213\203\377\227\236\225\377\221\227\217\377\221\224\217\377\201{\200" + "\377\217\207\211\377cW`\377B\062<\377NAH\377i^e\377\202v~\377\223\214\217" + "\377\206\204z\377yq^\377rkP\377\233\224x\377\246\240\203\377\234\221s\377" + "\213yb\377cQC\377\070&\040\377=+(\377K=:\377RD>\377]J@\377vgX\377m^O\377qe" + "W\377wiX\377\177p[\377\210wa\377\225\206l\377\220\201i\377\227\212t\377\206" + "xf\377{l^\377\211~q\377\207|s\377i[Q\377S?:\377I\066\065\377]LG\377\205vi\377" + "\240\223~\377\255\242\216\377\245\231\204\377\203qX\377\202t_\377vnd\377" + "\203~|\377\221\221\221\377~~\202\377NOT\377MVL\377Q^N\377BP@\377\070D\064\377" + "VfO\377bzU\377Sz?\377H~\032\377P\204\012\377V\213\003\377P\202\003\377W\206\002\377" + "i\225\002\377g\222\012\377a\217\001\377p\232\003\377l\226\002\377p\235\002\377k\225" + "\002\377z\247\007\377p\236\006\377h\235\010\377\207\262\067\377r\244\020\377j\234" + "\003\377\202\261\013\377m\236\003\377s\243\006\377\204\266:\377s\255\061\377\202" + "\253\001\377\201\242\002\377\216\256\002\377\212\250\002\377\256\267\007\377\244\300" + "M\377\215\260\031\377\210\260\040\377~\247\007\377\206\253\013\377\242\273,\377" + "\230\271\037\377\222\264\002\377\211\251\002\377\216\262\004\377\205\250\001\377\207" + "\251\001\377u\235\065\377\236\277v\377\302\333\270\377t\244\066\377\220\266M" + "\377m\225\025\377_\216\006\377\\\217\024\377S\205\005\377\\\221\004\377_\225\003\377" + "Y\211\001\377e\227\031\377En\000\377Ks\001\377U~\002\377n\241\003\377Y\211\030\377O|" + "\017\377W\211\005\377g\231\015\377V\203\001\377]\210\000\377V\177\000\377]\207\033\377" + "y\244<\377h\224-\377c\211\066\377o\212U\377~\205x\377\231\231\227\377\235" + "\233\233\377\233\230\230\377\223\216\214\377qim\377\\QV\377h`b\377ztw\377" + "\211\203\210\377\233\226\224\377\210\202x\377\212\203s\377\200u_\377\207" + "}b\377\233\223t\377\246\240\203\377\242\231{\377\240\221u\377|iX\377eOH\377" + "`MJ\377A*(\377G\060.\377L;\070\377A/*\377WG>\377M\071,\377^L>\377{jZ\377\220" + "\201r\377\207zj\377\202wj\377pe[\377UIB\377WHC\377^LB\377wfW\377q`Q\377}" + "j]\377\243\232\205\377\260\251\226\377\260\250\224\377\235\222~\377\201s" + "]\377\201s`\377\202ym\377\177vo\377\204~{\377\250\247\246\377\221\225\222" + "\377q}n\377PUO\377AEE\377ENE\377:L/\377>?\377>A=\377UjH\377W\177:\377N\203&\377F\210\016\377T\223\025" + "\377t\231\023\377c\216\004\377Q\201\001\377`\214\002\377_\211\002\377c\210\001\377o" + "\233\026\377\201\253\064\377\205\245\012\377e\222\002\377n\235\002\377j\236\014\377" + "l\243\002\377c\225\010\377^\221\005\377r\244\005\377x\247\012\377q\235\001\377w\253" + "\003\377t\251\030\377x\237\013\377\226\270W\377u\235\040\377|\251E\377\217\255" + "\005\377\223\262\003\377\204\244\002\377\203\244\003\377\253\312J\377\222\266\023" + "\377~\244\000\377\211\266\034\377\213\271#\377\207\262\010\377\215\270\007\377" + "\231\274\017\377\233\266\003\377\247\275\011\377\223\253\001\377\233\270\002\377" + "o\257\061\377[\221\000\377d\230\001\377Q\203\002\377Y\223\017\377O\205\002\377Ix\001" + "\377[\214\002\377W\213\002\377V\212\003\377T\205\004\377\\\225\013\377\\\217\016\377" + "S}\003\377Tz\001\377^\216\007\377_\221\005\377U\200\005\377Z\201\020\377o\236\016\377" + "h\227\005\377\207\241\017\377e\206\005\377f\210\002\377p\227\002\377Z}\001\377Y|\012" + "\377\067R\000\377Fb\030\377izN\377t}f\377\231\232\224\377\227\227\217\377\220" + "\217\207\377\202{x\377h]d\377lfl\377lgm\377\231\220\225\377\262\253\247\377" + "\252\244\234\377\221\216\201\377\220\213y\377\211\202j\377|tS\377\216\202" + "`\377~qI\377\213{Y\377\253\243\211\377\263\255\230\377\252\243\211\377\256" + "\244\216\377\241\222}\377\233\212w\377\237\216{\377\250\232\207\377\231\213" + "x\377\225\207u\377\212{m\377\240\222\203\377\247\232\213\377\234\215}\377" + "\245\227\200\377\254\234\202\377\251\230~\377\255\236\206\377\273\255\233" + "\377\277\266\244\377\262\252\226\377\235\225\201\377\224\212u\377\211}e\377" + "\227\216x\377\220\210u\377\224\217\201\377\211\207}\377\217\216\207\377\247" + "\250\242\377\235\252\224\377gw`\377bkT\377ScN\377bv`\377Hc\065\377\030=\000\377" + "+Z\005\377E\203\013\377B}\007\377\\\222\003\377\227\240\011\377X\204\002\377c\215\002" + "\377_\207\002\377a\211\001\377e\224\014\377R\200\003\377\206\256(\377c\214\001\377" + "s\237\001\377k\233\002\377l\243\023\377g\231\010\377d\223\003\377q\242\003\377p\237" + "\002\377\177\260\005\377k\233\002\377k\235\000\377\201\250\006\377w\246\034\377\203" + "\253\066\377\251\273W\377\215\253\037\377\250\267\040\377\215\251\004\377\210" + "\252\002\377\212\263\010\377\214\263\016\377\177\242\001\377\246\273\005\377\217" + "\274B\377\213\271\040\377\214\271\013\377\205\251\001\377\243\276\006\377\230\260" + "\002\377\220\252\003\377\231\263\002\377Z\220\001\377g\233\002\377W\211\002\377Y\216" + "\005\377_\224\003\377b\223\002\377V\210\002\377_\222\003\377^\220\003\377b\235\002\377" + "d\235\003\377]\227\002\377^\230\003\377R\210\003\377[\221\003\377d\231\012\377b\227" + "\006\377g\226\023\377e\227\007\377l\232\011\377\215\253&\377_z\002\377Z}\004\377q\213" + "\003\377p\212\002\377Ts\003\377\065W\002\377Cg\004\377-Q\001\377X\202\004\377_tD\377t|n" + "\377y{r\377\212\211\201\377\222\220\213\377\217\214\210\377XQY\377b[c\377" + "~w\177\377\230\223\223\377\270\263\254\377\237\232\217\377\217\210w\377\224" + "\215x\377\220\212q\377\215\202b\377\215}Z\377\221\203_\377\217\202a\377\227" + "\214p\377\245\234\202\377\253\244\215\377\267\255\230\377\260\244\217\377" + "\264\250\225\377\264\252\230\377\262\247\226\377\253\240\217\377\254\241" + "\222\377\251\235\216\377\232\213z\377\262\245\223\377\262\244\215\377\255" + "\235\205\377\264\242\211\377\247\223z\377\267\250\225\377\272\255\233\377" + "\232\215v\377\221\207r\377\231\222~\377\215\206p\377\223\215y\377\231\223" + "\204\377\221\220\205\377\213\213\203\377\211\211\200\377\241\246\226\377" + "\201\217u\377|\211d\377\201\177U\377Q[I\377)E\035\377.T\040\377p\227Z\377J" + "\200\021\377=p\002\377P\210\003\377[\222\003\377o\212\016\377c\203\003\377b\210\002\377" + "h\224\002\377e\222\001\377R\202\001\377M\200\002\377\204\254/\377b\212\000\377q\237" + "\002\377i\236\013\377p\247\023\377j\235\005\377s\241\011\377u\243\001\377t\246\002\377" + "q\242\003\377h\232\002\377m\236\004\377|\247\003\377n\245\024\377\210\266G\377\260" + "\313P\377o\234\010\377\234\263\022\377\250\265!\377\222\256\017\377\212\261" + "\024\377\221\271'\377\203\245\001\377\236\243\003\377\221\271\060\377\216\272:" + "\377\223\300\017\377\222\272\004\377\220\256\002\377\213\247\002\377\221\255\002\377" + "\222\257\002\377_\223\002\377m\235\001\377g\230\010\377p\230\011\377n\221\012\377" + "z\234\033\377_\213\005\377W\206\003\377\\\220\002\377^\225\002\377c\234\011\377Z\210" + "\001\377j\226\026\377s\244'\377^\220\026\377V\204\014\377_\217\002\377]\206\001\377" + "o\227\002\377{\230\023\377\205\243\030\377Mp\001\377Ln\002\377f\202\002\377m\206\002" + "\377Uo\002\377\065J\001\377;T\002\377Ff\003\377?c\001\377If\040\377Sa@\377ei^\377\177" + "~v\377\220\221\204\377\201\201w\377gfc\377cac\377a]a\377\233\227\225\377" + "\252\245\235\377\223\214\201\377\224\220\203\377\215\213{\377\231\226\205" + "\377\212\205j\377\206\200]\377\216\205c\377\217\205g\377\222\206j\377\204" + "uU\377\217\201a\377\241\225x\377\260\244\211\377\250\235\202\377\235\220" + "w\377\252\240\207\377\237\224\177\377\260\247\224\377\227\211u\377\224\203" + "o\377\247\233\206\377\266\252\223\377\250\231\201\377\260\243\214\377\254" + "\237\210\377\247\232\204\377\250\233\205\377\230\213u\377\221\205r\377\212" + "\201o\377\235\227\207\377\234\233\216\377\232\232\221\377\202\202|\377\207" + "\207\177\377\177\202t\377\216\241w\377\177\217d\377r\177^\377eoc\377G\\>" + "\377&K\015\377)V\003\377Fy\021\377n\232H\377J\201\014\377d\235\002\377[\217\020\377" + "x\241=\377o\217\012\377o\220\005\377d\222\003\377_\217\001\377Z\215\003\377Y\212\002" + "\377t\241#\377p\235\017\377p\243\010\377k\234\015\377o\243\010\377f\223\005\377" + "p\236\005\377w\245\002\377}\254\002\377{\255\004\377n\237\002\377\\\217\000\377\205\256" + "\000\377f\241\017\377\210\270G\377\224\273(\377x\243\002\377u\245\013\377\202\244" + "\000\377\225\257#\377\224\263#\377\223\271\063\377\203\250\001\377\222\246\004\377" + "\200\246\006\377\206\256+\377\207\262\011\377\204\251\001\377\217\264\002\377\214" + "\256\002\377\214\264\007\377\215\261\006\377a\225\003\377e\230\002\377Y\220\004\377U" + "\213\002\377U\205\001\377`\215\001\377Sq\001\377]\211\002\377^\216\003\377]\222\003\377" + "_\220\030\377\212\264T\377k\234\025\377`\222\001\377U\203\001\377Fp\001\377b\217" + "\002\377S|\003\377[\210\005\377\223\257>\377f\217\006\377W\201\002\377Z~\005\377i\223" + "\002\377Yw\003\377Xi\001\377do\007\377Vg\004\377Rm\006\377Km\011\377:\\\000\377Qr\016\377" + "\067H\040\377]kK\377|\206l\377\214\216\200\377\227\230\217\377kih\377ead\377" + "\221\213\213\377\205{w\377\216\204{\377\214\203y\377\206\177t\377\217\214" + "|\377\217\214u\377\222\215o\377\200zX\377\203~]\377\226\215k\377\204vP\377" + "\216~Z\377\216\200]\377\230\213h\377\230\215j\377\241\230u\377\234\222t\377" + "\242\227}\377\245\233\207\377\222\205s\377\226\212t\377\250\236\211\377\256" + "\241\213\377\253\235\205\377\253\235\205\377\227\213u\377\240\224\202\377" + "\207\177m\377\214\200o\377\215\205t\377\245\241\220\377\227\226\211\377\216" + "\217\205\377\213\213\203\377\177~y\377}}t\377\220\236x\377y\221V\377^qK\377" + "Q^K\377L]D\377.N\024\377+Q\004\377@m\005\377M\203\011\377?s\001\377\202\260R\377" + "a\232\001\377Bm\025\377\203\255O\377k\217\035\377X\177\006\377O\177\001\377_\216" + "\001\377c\225\002\377V\202\002\377V\202\000\377\231\302J\377j\231\010\377i\230\002\377" + "t\246\002\377w\245\002\377t\243\003\377l\232\002\377\200\261\003\377l\236\003\377l\241" + "\001\377W\217\017\377\222\270&\377r\246\024\377\215\276Y\377\224\273,\377\201" + "\246\000\377}\247\002\377\200\255\002\377\177\245\002\377\200\246\005\377\242\302G" + "\377\177\251\006\377w\235\001\377\220\261#\377\220\256.\377\206\261.\377v\237" + "\000\377\212\265\001\377\205\253\002\377\224\271\005\377\243\305#\377O\204\001\377" + "Z\217\003\377Z\221\003\377P\210\002\377Z\224\004\377W\213\003\377\\\215\000\377e\226" + "\007\377d\226\005\377Vx\005\377t\222\024\377c\217\006\377\202\240>\377a\205\010\377" + "_\207\004\377U~\002\377f\227\006\377t\251\036\377\204\261#\377\202\252'\377q\235" + "\010\377^\214\001\377a\214\015\377\\\212\000\377T~\001\377]\205\003\377_\206\002\377" + "[|\002\377Xw\004\377Ss\004\377Db\001\377;Z\001\377\063P\003\377p\224D\377`fS\377tvh\377" + "~\177t\377d^]\377tps\377uoq\377\240\230\223\377\254\245\234\377\243\236\222" + "\377\230\222\205\377{yk\377\204\203r\377\215\213r\377\217\212k\377\211\202" + "`\377\207\200[\377\212\203]\377\227\217j\377\230\220l\377\242\232{\377\223" + "\211j\377\232\224u\377\247\240\204\377\223\215s\377\234\224\177\377\206y" + "f\377\220\203p\377\226\212t\377\244\230\177\377\254\240\207\377\247\234\206" + "\377\222\207u\377~ua\377\226\221\200\377\234\232\213\377\230\230\212\377" + "\230\231\216\377\206\206}\377\226\225\217\377\212\212\204\377\177~y\377\201" + "\201z\377\215\244h\377k\177Q\377ERA\377/B&\377\062M\031\377,N\007\377Af\007\377" + "Fr\002\377V\214\007\377F~\003\377_\237\002\377d\230,\377[\204\023\377s\235D\377Mv" + "\000\377p\216-\377Ft\000\377]\213\002\377Y\211\001\377W\207\003\377`\222\002\377\226" + "\300H\377c\215\007\377h\227\001\377i\232\003\377u\244\002\377g\230\002\377i\230\002\377" + "x\254\002\377m\235\015\377b\231\000\377{\257<\377\234\306h\377\213\266\063\377" + "\217\272\061\377\206\260\022\377\212\257\031\377\244\300=\377~\251\035\377\216" + "\261\006\377\201\244\000\377\255\310N\377\317\326\217\377n\222\000\377\220\244" + "'\377\246\276M\377r\240\006\377\211\256\023\377\223\264\002\377\206\246\002\377" + "\214\257\001\377\227\273\030\377h\236\013\377P\206\001\377W\215\003\377_\226\003\377" + "T\212\002\377^\226\000\377q\243\034\377q\245\037\377\\\216\001\377}\223\027\377\257" + "\257F\377Z\203\001\377\\\212\017\377Rz\002\377d\217\015\377c\215\007\377s\244\003\377" + "q\234\002\377\233\272\066\377h\206\001\377l\220\003\377V}\001\377o\233\004\377m\232" + "\016\377h\216\013\377b\203\001\377]|\002\377Zw\002\377Vr\002\377Ee\002\377?a\002\377Cb" + "\002\377[~\004\377Lk\004\377!\063\006\377?K,\377prd\377\214\213\204\377\212\213\204" + "\377\210\203\201\377\232\223\224\377\225\222\220\377\235\234\226\377\203" + "\201x\377|{r\377ccZ\377\214\214|\377\221\216y\377\220\214q\377\224\217q\377" + "\206~\\\377\214\204`\377\222\214j\377\251\245\214\377\223\220t\377\222\220" + "s\377\217\214p\377\222\213n\377\225\211n\377\210y`\377\203r[\377\216~h\377" + "\245\232\200\377\240\230\177\377\232\223\177\377\230\221\200\377\240\233" + "\212\377\243\243\227\377\224\224\211\377\214\215\203\377yyr\377lkh\377on" + "o\377xxw\377YYY\377x\177h\377p\213N\377DND\377ES?\377)C\030\377+M\012\377?" + "k\017\377/Z\002\377=l\002\377M\202\010\377G\201\002\377\\\226\004\377Bl\022\377{\253" + "F\377y\244H\377Cn\000\377\245\274m\377d\222\017\377b\225\003\377^\222\012\377^" + "\226\020\377\\\222\002\377n\232\026\377\201\255'\377_\221\001\377l\236\002\377d\227" + "\003\377]\220\002\377o\242\002\377o\242\006\377\214\257G\377\223\277]\377i\235\014" + "\377\\\216\003\377~\262\030\377p\230\004\377\204\263\035\377\212\273L\377\227\305" + "h\377\231\304r\377\265\327\215\377\240\307F\377\221\267\065\377\245\272\071" + "\377\223\251,\377\250\272I\377\271\313`\377\276\320`\377\233\271/\377\211" + "\245\001\377x\226\002\377\212\254\001\377\242\301)\377V\210\003\377V\211\003\377c\223" + "\004\377\\\225\004\377]\223\005\377Y\217\000\377`\222\004\377e\224\001\377d\216\004\377" + "n\223\003\377h\214\002\377n\232\002\377h\231\003\377u\247\040\377\216\274J\377\201" + "\256\015\377}\244\002\377\224\264\022\377\224\261A\377Z\201\000\377a\215\002\377" + "p\232\012\377u\227\004\377w\222\003\377l\201\002\377l\200\002\377_p\002\377`p\001\377" + "J_\002\377So\003\377+C\000\377Jp\013\377z\237\036\377<]\002\377\031\065\000\377Oi%\377" + "dv?\377np_\377kjb\377}wz\377xmu\377ndn\377qfn\377^SZ\377>\070<\377>\071=\377" + "efc\377]^V\377\207\210t\377\227\225z\377\206\202`\377\213\210d\377\216\211" + "g\377\230\227|\377\177\207]\377\236\235\177\377\226\224v\377\234\226y\377" + "\201uX\377\207z\\\377\222\207j\377\237\230}\377\230\222{\377\233\225\201" + "\377\235\232\206\377\231\230\205\377\231\231\212\377\226\227\213\377\231" + "\232\220\377wwr\377^]]\377>==\377B?A\377JFI\377B>B\377\231\245v\377]bQ\377" + "-<\"\377(A\025\377(I\011\377\062Y\017\377*S\001\377\063d\006\377\067k\005\377Cx\002\377" + "U\224\005\377Cl\002\377Nt\000\377o\233+\377y\245M\377Q\203\000\377Y\212\024\377\214" + "\266Q\377S\205\002\377R\202\002\377S\201\002\377b\222\002\377e\226\015\377{\252&\377" + "j\236\001\377k\235\001\377`\217\003\377i\227\000\377v\246\001\377s\250\026\377s\247" + "\062\377f\233\015\377p\237\003\377m\232\005\377y\255\040\377v\232\003\377t\245\012" + "\377o\236\000\377\225\273?\377\300\341\224\377\215\271<\377\204\260\027\377" + "\204\263)\377\212\261(\377\254\306]\377\247\264?\377\214\257\030\377\207\256" + "\023\377\232\303B\377\217\267(\377u\217\001\377\202\236\002\377\236\301/\377`" + "\221\003\377\\\221\003\377\\\227\004\377`\231\005\377n\237\012\377\200\245\035\377" + "g\227\001\377Y\215\002\377X\212\001\377q\231\004\377p\227\002\377f\224\002\377g\231\002" + "\377u\251\"\377f\224\005\377m\230\001\377u\236\001\377s\233\006\377b\221\004\377a\221" + "\004\377a\212\003\377m\217\006\377k\212\002\377l\210\001\377x\225\003\377j\212\002\377" + "a\203\002\377a\201\003\377`\201\007\377h\216\007\377\\\203\011\377o\244\026\377Lk\012" + "\377Hf\020\377Xy\034\377" + "\071;\377\063.\060\377zx[\377\210\230h\377XdV\377\064K*\377\036@\010\377-V\016\377" + "\037L\002\377,\\\005\377:m\007\377F{\004\377X\204\012\377`\215\021\377Lu\010\377`\207" + "\013\377U\202\024\377~\261C\377U\210\000\377U\204\000\377\210\270G\377Z\213\004\377" + "Q\204\001\377c\226\003\377W\205\002\377`\215\012\377|\252\032\377l\242\002\377[\215" + "\002\377g\232\007\377\207\264\064\377|\254\012\377h\237\014\377`\227\020\377r\245" + "\004\377}\246\001\377z\252\037\377p\244(\377\202\235\001\377\204\264\060\377\242" + "\312^\377\260\323k\377\200\243\020\377v\244\004\377\214\275@\377\230\303T\377" + "\255\320g\377\204\261.\377\240\274\040\377\210\255\020\377\235\253\040\377\224" + "\273@\377\230\274G\377\225\264\021\377\217\260\002\377\227\302\070\377V\206\003" + "\377Y\223\011\377O\216\002\377W\222\002\377U\220\003\377Q\212\003\377U\214\002\377Z" + "\220\001\377\\\221\002\377^\222\001\377n\236\006\377t\247\024\377[\211\001\377i\233" + "\015\377g\224\002\377h\217\002\377b\206\000\377}\240\022\377\224\267\011\377r\237" + "\001\377j\226\002\377r\237\003\377i\221\002\377l\227\002\377q\225\002\377k\203\003\377" + "`l\002\377eo\002\377{\230\002\377u\235\002\377Sl\010\377l\217\034\377o\213,\377Ei\005" + "\377?`\001\377Np\022\377Pc\037\377!\060\006\377FN\071\377Z[S\377XUS\377skk\377\211" + "\203\200\377ka]\377H\071\061\377TF>\377L?\071\377_VO\377e^R\377uo\\\377\211" + "\210k\377\211\215g\377{\204S\377\210\212a\377~|V\377\222\222m\377\224\221" + "m\377\177|T\377\203\177W\377\233\232x\377\213\211k\377\220\220v\377\221\222" + "~\377\222\227\200\377\227\240\204\377\210\213x\377\226\226\211\377\233\234" + "\223\377\216\214\205\377zri\377tk_\377zqe\377~yn\377kh]\377\224\245r\377" + "ViB\377\067O\060\377>Y,\377\064T\024\377\032C\002\377\037Q\001\377;s\020\377A{\006\377" + "X\213\020\377p\231#\377Nz\031\377M\204\015\377I{\000\377b\226\031\377v\253\062\377" + "_\220\002\377W\201\001\377t\245\023\377^\220\004\377`\224\005\377K}\003\377U\203\002\377" + "m\235\011\377\203\262%\377c\224\000\377[\214\000\377i\233\006\377j\227\004\377t\247" + "\002\377i\240\012\377c\226\002\377\206\260\004\377~\246\012\377l\236\017\377i\242" + "/\377\226\276K\377\221\272I\377\201\256&\377\212\237\020\377\211\241\005\377" + "o\230\005\377\235\275O\377\221\257:\377\206\252!\377}\252\022\377\214\242\006" + "\377\203\236\004\377\213\254\011\377\325\336q\377\272\311>\377\224\260\005\377" + "\221\260\002\377\225\300=\377Bx\002\377T\217\004\377S\214\002\377U\215\002\377Y\221" + "\003\377]\223\002\377X\213\002\377p\236\027\377p\233\010\377f\225\003\377b\221\007\377" + "a\220\002\377\\\212\002\377W\205\001\377f\220\002\377X\202\002\377_\211\002\377\210\256" + "\005\377\221\263\002\377l\222\002\377r\232\003\377v\236\001\377z\245\002\377q\216\003\377" + "k\200\002\377hz\004\377jw\002\377x\206\005\377{\225\001\377g\210\011\377m\230\024\377" + "q\226\040\377Zl\016\377Tl\012\377Uy\012\377Oi\034\377\040.\000\377\061<\025\377js[" + "\377\202\204u\377{zn\377qh_\377}tm\377\230\220\200\377\225\210p\377\230\210" + "m\377\230\211l\377\213|c\377\202u]\377|w\\\377tuO\377v\200N\377\206\214b" + "\377\216\220n\377~}W\377\203\201Z\377\213\212b\377\203\201R\377\212\210^" + "\377\224\223q\377\214\214l\377\213\213n\377\201\201j\377\223\226\200\377" + "\227\236\201\377\224\232\200\377\225\226\211\377\230\231\220\377\211\206" + "|\377\216\206y\377\226\216|\377\235\227\206\377\214\211|\377\201\205o\377" + "\212\262j\377BY\064\377&?\031\377+K\021\377$H\010\377\"J\002\377J\001\377x\005\377;p\001\377e\230\027\377Z\217\003\377Q\204\001\377" + "Hz\002\377I{\001\377Z\212\002\377a\224\022\377l\226\021\377n\225\004\377`\212\002\377" + "l\227\003\377p\230\004\377i\231\007\377j\227\014\377\205\265H\377o\240\031\377\211" + "\265/\377c\227\014\377Z\211\002\377m\232\004\377l\231\002\377\220\257\003\377z\251" + "\002\377u\236\026\377q\240\035\377\212\271F\377s\242\032\377h\230\001\377q\240\001" + "\377\251\315\065\377n\237\016\377u\244\006\377k\230\003\377\204\251\001\377\230\262" + "\017\377u\242\016\377\225\270\066\377v\247+\377\230\271*\377\246\276#\377\245" + "\270\013\377\240\252\001\377\241\274\014\377\215\264\007\377\207\260\000\377\202" + "\257\003\377\\\233\003\377T\221\004\377O\206\003\377T\200\003\377Ao\001\377c\225\004\377" + "c\226\004\377d\221\005\377d\224\002\377X\205\002\377O|\001\377s\232\033\377g\221\012" + "\377a\211\001\377^\212\002\377`\212\001\377i\223\002\377}\247\004\377\205\244\004\377" + "z\224\003\377p\214\003\377h\205\001\377\221\234\023\377v\212\004\377z\231\002\377s\234" + "\005\377}\234B\377[x\011\377e\225\006\377Z\205\003\377[\210\007\377h\220\020\377_\203" + "\005\377Qo\002\377Sn\001\377^{\005\377H_\002\377:M\001\377FU\003\377\066F\006\377aj@\377z" + "{k\377\177\201t\377{zr\377gdW\377\201xe\377\223\214i\377\234\232e\377\237" + "\234_\377\236\217a\377\226\201[\377\203qL\377q`@\377wlO\377\202|_\377\205" + "\201b\377|yQ\377\201\200Y\377\220\220j\377\217\216i\377\221\220r\377\211" + "\211m\377\217\221|\377\221\222\204\377\224\226\211\377\222\236|\377ztn\377" + "qj_\377nf[\377WNI\377JFF\377B@B\377ivU\377^\205D\377}\253R\377Iv#\377\062" + "\\\016\377Kx\030\377\065f\005\377/e\004\377\066l\002\377N\201\006\377]\220\003\377P\203" + "\002\377Q\201\003\377[\216\002\377\\\220\002\377F{\001\377]\225\023\377_\221\012\377" + "_\217\004\377Fv\001\377t\235\003\377]\206\002\377^\221\015\377\216\274R\377n\235\004" + "\377T\200\002\377\212\271\067\377a\227\010\377m\227\010\377l\227\002\377\240\264" + "\014\377r\231\002\377p\243\012\377`\225\011\377t\247\040\377p\231\014\377\177\251" + "\002\377n\234\003\377e\226\001\377\230\300\040\377\221\271\064\377k\230\004\377k\230" + "\003\377\177\244\002\377\240\270!\377\200\247\016\377\226\272'\377a\224\004\377" + "\202\262\023\377\223\273\033\377\245\300\"\377\233\257\007\377\221\252\001\377" + "\213\260\013\377\210\265\022\377\272\320H\377L\210\001\377T\217\003\377L\205\002" + "\377R\213\005\377[\224\004\377b\223\006\377`\205\002\377o\222\004\377g\215\000\377X\203" + "\000\377]\207\010\377[\177\001\377e\215\005\377f\217\016\377i\223\012\377W\202\001\377" + "]\205\001\377x\241\013\377g\215\004\377j\212\003\377o\213\002\377n\215\002\377i\212" + "\004\377~\234\010\377\204\250\013\377|\241\"\377x\222\027\377]\205\003\377g\225" + "\002\377\\\201\001\377Ot\003\377^\213\023\377^\214\012\377^\204\010\377f\206\015\377" + "Xr\002\377Pi\003\377Ga\002\377G_\001\377?W\003\377F[\021\377fnH\377rsb\377ii]\377kk" + "`\377[[I\377s\200E\377\224\221e\377\241\224o\377\203pP\377nY\070\377ub<\377" + "ziC\377yjH\377{pS\377yqT\377{vV\377|yU\377\202\177]\377\214\214k\377\215" + "\216o\377\214\215t\377\225\226\204\377\213\213\200\377~}t\377\202\220f\377" + "pmZ\377icZ\377]ZT\377JGF\377KJJ\377RRO\377r\212U\377ZoE\377t\244O\377Gv\036" + "\377W\214&\377?u\024\377\067p\005\377M\212\004\377Q\210\004\377T\212\002\377W\212\002" + "\377Dw\002\377O|\002\377Y\212\003\377V\211\003\377J~\002\377X\224\020\377N\202\007\377" + "L}\003\377o\230\005\377o\233\004\377e\222\004\377s\242'\377m\230\016\377t\236\004\377" + "h\220\012\377\207\265\062\377Y\205\000\377o\222\005\377\226\255\007\377o\217\003\377" + "l\236\005\377s\247\063\377f\232\030\377d\230\007\377v\236\001\377z\240\003\377u\240" + "\005\377s\241\003\377\212\270\013\377\200\254\026\377\\\212\002\377q\234\001\377\177" + "\246\002\377\214\261\005\377\177\250\006\377l\234\005\377h\233\002\377}\257\015\377" + "\223\274\"\377\246\273$\377\273\311R\377\236\264\023\377\216\261\011\377\203" + "\257\027\377\216\261,\377H~\002\377M\205\004\377L~\003\377G\200\002\377j\246\015\377" + "`\231\015\377h\241\023\377|\254*\377\213\267A\377\205\265/\377\202\253\065\377" + "f\220\004\377j\224\004\377O|\002\377[\211\013\377X\207\001\377e\204\020\377\202\256" + "\004\377Y\200\002\377Y~\002\377_\204\003\377V{\002\377_\202\003\377\200\245\004\377t\234" + "\022\377~\222\032\377w\225\014\377e\216\003\377_\215\004\377\\\214\013\377S\202\003" + "\377Jo\001\377W\203\017\377o\240'\377^\202\002\377]|\003\377_\202\002\377Uz\003\377" + "X\177\005\377Oo\002\377Da\003\377DZ\016\377S[\060\377__H\377fiQ\377Yt\061\377ZXG\377" + "tlY\377iYD\377qcE\377{lG\377\221\201U\377\233\211^\377\202oG\377\177mL\377" + "m_B\377kbE\377\200z_\377{uX\377\202~a\377\222\220y\377\213\212v\377\207\207" + "y\377{yn\377eaX\377ekP\377x\205X\377\\UN\377eb[\377ec_\377`^W\377`bQ\377" + "q\215T\377w\233Y\377s\247C\377Ar\031\377\067i\020\377\066m\007\377D\201\005\377I" + "\205\002\377Bz\002\377C}\001\377Av\002\377\067l\004\377a\227\010\377L\202\003\377I}\001\377" + "K\201\001\377]\232\016\377>u\005\377k\230\005\377^\211\002\377T\205\003\377c\226\022" + "\377x\243\061\377r\232\006\377\207\250\003\377j\213\004\377\220\267\066\377b\215" + "\000\377\200\235\004\377\252\270\005\377f\224\002\377n\244\031\377\\\220\025\377v\253" + "\060\377u\241\001\377\201\245\005\377{\235\002\377z\242\003\377z\254\006\377\205\262" + "\002\377k\232\002\377`\222\003\377q\237\005\377\200\252\003\377\201\251\005\377}\252" + "\005\377i\235\006\377i\237\004\377w\242\004\377\255\311V\377\311\322a\377\256\304" + "@\377\234\271!\377\220\262\032\377\202\261$\377t\237\023\377v\244\030\377J~" + "\004\377Av\002\377;v\004\377\\\217\015\377v\252\"\377\232\307h\377\234\307k\377" + "\241\314v\377k\230.\377N|\000\377t\237\022\377f\226\007\377e\226\003\377b\230\003" + "\377]\222\002\377`\223\002\377\231\275\004\377r\222\004\377h\206\002\377l\211\002\377" + "s\221\003\377~\237\004\377o\231\017\377\205\247\037\377d\220\007\377g\224\014\377" + "h\225\004\377]\215\002\377[\211\016\377\\\211\013\377Rw\002\377Qy\005\377\201\253N" + "\377b\213\027\377f\210\024\377a\204\013\377Xv\001\377[y\004\377Ul\003\377GZ\001\377" + "HZ\007\377GV\022\377w\203H\377~\210Q\377qpX\377ZVI\377`YJ\377nfL\377\221\207" + "^\377\237\222e\377\222|P\377\222yN\377\217uM\377\217wS\377}jL\377aR<\377" + "rkX\377wr[\377\204~i\377\213\206u\377\205\200t\377yri\377[QJ\377KC\070\377" + "GD\066\377\205\227O\377wo_\377yrc\377yuh\377oma\377x\207^\377a\211=\377\204" + "\256[\377Ai\025\377\065\\\023\377.\\\003\377P\210\003\377Dv\002\377F{\010\377Av\005\377" + "N\202\002\377\061j\002\377L\201\003\377O\211\003\377O\210\002\377N\202\003\377K\201\002" + "\377Y\221\007\377t\240\006\377g\221\002\377X\204\001\377^\220\002\377q\251/\377e\232" + "\021\377x\236\004\377q\216\002\377l\207\014\377\221\272A\377c\215\000\377\253\267" + "\011\377~\232\002\377q\241\000\377x\252,\377y\252\031\377{\255\"\377\224\270\010" + "\377y\236\011\377\224\257\006\377\177\246\006\377\210\265\002\377\200\253\002\377" + "m\233\010\377_\222\002\377b\222\004\377\177\247\013\377\222\271'\377\206\256\036" + "\377q\236\003\377\243\270\027\377\232\260!\377\215\260.\377\200\244\022\377\233" + "\272&\377\216\256\025\377\212\253\024\377\243\304Y\377\203\257\"\377[\217\002" + "\377N\177\002\377I|\002\377Q\204\004\377L{\002\377o\235!\377x\250\061\377\234\304" + "i\377p\226-\377Z\206\002\377\\\205\005\377^\210\005\377m\211\004\377X{\003\377^\212" + "\005\377O\200\002\377X\221\014\377\242\305\002\377\202\240\026\377q\217\001\377z\231" + "\002\377u\230\003\377h\221\003\377\\\211\004\377s\246\033\377d\233\016\377`\226\011" + "\377v\244\035\377a\225\021\377e\222\036\377d\213!\377c\205\020\377]|\003\377k\217" + "\037\377s\227\065\377n\223/\377n\227&\377a\204\017\377^\200\014\377Yr\021\377" + "du\031\377@N\004\377Md\007\377r}\071\377\224\212h\377\205~b\377zx`\377xx^\377s" + "pW\377zsW\377qbF\377w_?\377\231\200^\377\242\211f\377\234\202a\377\216v[" + "\377XH;\377G<\061\377geX\377spd\377zsi\377|si\377wka\377fYK\377dXG\377woT" + "\377\203\235+\377vzS\377qsT\377so_\377xtf\377\213\242m\377W\204%\377w\251" + "K\377Ds\030\377Ar\016\377Z\217\004\377M|\001\377\070g\011\377Y\213\033\377L\177\002" + "\377I\177\002\377M\201\003\377F}\001\377W\215\003\377P\210\002\377_\220\002\377Z\204" + "\002\377s\240\005\377b\213\003\377f\216\003\377a\215\003\377[\215\002\377\\\231\025\377" + "e\234\017\377\222\260\011\377j\222\014\377c\214\003\377|\255\060\377\224\252\007" + "\377~\245\004\377m\233\002\377f\225\000\377\203\264\061\377|\253\013\377|\251\005\377" + "\202\252\002\377\204\245\002\377\241\270\005\377v\247\003\377\201\255\003\377\203\256" + "\002\377x\234\005\377i\224\007\377|\247\015\377}\244\003\377\205\255\000\377\210\261" + "\000\377\216\257\013\377z\236\004\377v\245\040\377\203\252\012\377\203\247\007\377" + "\252\300\031\377\215\252\004\377\230\263&\377\271\320w\377r\237\000\377`\205\014" + "\377_\205\003\377\\\200\003\377Z|\004\377Rw\003\377V|\003\377t\221\005\377]\201\007\377" + "e\212\004\377m\223\002\377e\215\010\377[\207\002\377e\213\006\377j\214\005\377r\232" + "\003\377W\203\003\377Y\202\002\377\246\310\007\377\202\255(\377r\236\016\377k\227" + "\002\377f\227\000\377k\233\012\377`\224\003\377`\221\014\377`\216\005\377i\225\010\377" + "`\213\006\377u\231\015\377\\\205\014\377l\240\067\377j\245E\377b\230=\377^\223" + "-\377\\\215\027\377Q\177\020\377Y\214\016\377X\177\020\377=V\002\377@P\001\377We" + "\002\377e\210\010\377fx\030\377qp\070\377\202}U\377\225\220k\377\220\213i\377" + "\204~c\377xk[\377|n]\377\212yb\377\244\217n\377\253\224r\377\242\213h\377" + "\240\207h\377\222zc\377PH=\377\027\022\020\377<\067\070\377RLE\377maU\377\203" + "vc\377vdO\377mWD\377]I:\377TB\066\377}\214=\377qrP\377am\071\377o\177E\377" + "h}H\377d\221>\377Bf\023\377\204\263R\377P\207\026\377;g\002\377J~\005\377o\001\377K\177\001\377J\200\004\377H~\003\377F~\001\377M\203\003\377]\220\003" + "\377c\222\003\377}\251\002\377g\233\031\377R\201\006\377U\200\003\377i\221\003\377t" + "\247\001\377l\232'\377n\240\023\377\226\267\004\377f\237\022\377P\207\007\377s\242" + "\017\377\241\254\013\377u\240\004\377n\232\002\377i\225\005\377\177\262\016\377w\251" + "\011\377w\247\004\377l\226\003\377\224\264\003\377\201\250\003\377w\246\003\377u\244" + "\003\377|\251\004\377d\216\007\377i\223\007\377\207\255\002\377\225\275\002\377\200\260" + "\013\377v\252\017\377k\237\032\377k\236\003\377{\255;\377\203\243\000\377\202\254" + "\021\377\211\255\006\377\221\261\013\377\246\303N\377n\222\005\377\207\250\012\377" + "q\212&\377Hh\002\377Zz\003\377Hr\003\377Uy\002\377Xy\003\377Gc\002\377i\215\003\377a\207" + "\003\377_}\003\377U\200\002\377U\202\006\377i\220\003\377k\212\002\377\202\245\002\377" + "j\211\004\377j\223\010\377\230\276\011\377j\224\010\377p\241\001\377e\227\007\377" + "w\250\065\377s\236\067\377k\225\033\377d\220\012\377c\205\003\377i\212\002\377q\222" + "\006\377f\217\003\377U~\003\377[\212\010\377Z\215\021\377c\230!\377b\235$\377Y\226" + "\030\377W\222\030\377N\206\012\377Y\220\020\377d\224\016\377f\212\016\377h\214" + "\020\377cz\024\377Wj\013\377Zk\026\377\233\234m\377\236\227x\377\225\207s\377" + "\241\220\201\377\236\215~\377\236\216}\377\226\205o\377\215y_\377\231\202" + "e\377\251\224s\377\245\220r\377\224}g\377OJC\377\011\007\005\377'\035\032\377\\" + "K?\377nXG\377x_J\377u[G\377zeU\377wh\\\377WJ?\377}\210T\377PY/\377DR$\377" + "Zt<\377X\213\062\377S\212+\377Z\204\063\377n\240\062\377Ct\007\377Y\221\022\377" + "\377w`<\377" + "n]\061\377hc*\377n{\065\377^w!\377u\224)\377W\202\020\377Jz\004\377T\216\010\377" + "V\215\024\377Z\227\033\377i\243\062\377f\242+\377`\230\034\377V\215\010\377W\214" + "\001\377M\204\005\377H\200\006\377O\203\003\377L\177\002\377Y\210\006\377U|\003\377u\243" + "\036\377S\213\003\377Q\204\002\377Q~\006\377y\242.\377\211\265D\377[\221\006\377n" + "\224\005\377\204\251\013\377\202\256)\377g\230\002\377q\245\005\377\201\250\004\377" + "\210\253\002\377`\217\002\377p\245\012\377\202\255\002\377z\246\001\377o\236\003\377" + "`\221\002\377\254\270$\377\201\240(\377\241\274\017\377\231\262\004\377\205\250" + "\003\377r\233\004\377f\215\001\377i\221\003\377{\242\006\377s\232\005\377t\233\002\377" + "}\245\013\377{\242\022\377p\233\014\377|\250\002\377o\230\000\377x\236!\377|\233" + "\010\377\213\254\023\377\224\276D\377\200\246\000\377\231\301Z\377\200\256\061" + "\377\227\270\025\377\203\237\004\377Pk\002\377V|\003\377=c\001\377Sp\002\377Zk\002\377" + "Nc\002\377]z\002\377j\202\003\377z\243\003\377o\224\005\377Z\220\012\377O\212\005\377" + "{\253\003\377t\246\002\377_\217\004\377]\213\002\377\232\277\002\377u\240\025\377[\211" + "\023\377e\227\013\377e\225\034\377t\243\037\377e\235\017\377m\237\"\377\206\260" + "N\377~\254C\377c\226\021\377m\230\025\377e\230\002\377_\220\003\377a\224\004\377" + "n\237\010\377m\231\022\377\221\262\067\377\260\303\064\377\254\275=\377c\231" + "\021\377Z\225\024\377a\236\026\377Z\223\007\377_\230\012\377W\220\001\377V\216\002" + "\377U\211\002\377b\217\011\377q\230\026\377g\221\015\377_\212\017\377b\205\034\377" + "i\202)\377|\214J\377\212\220c\377\223\225o\377\213\213c\377\213\201a\377" + "\215\177c\377W@\070\377zdR\377\250\225q\377}nC\377\207yL\377\205zG\377zx\071" + "\377gn\037\377j\203+\377Qt\015\377[~\026\377Hl\013\377Is\003\377m\245,\377k\243" + ".\377}\260J\377Q\210\040\377u\253A\377V\212\004\377Z\215\003\377M\177\002\377I~" + "\004\377\377j\206;\377l\207\061\377y\214;\377w\211\071\377Rf!\377?S\016\377`t\025" + "\377j\203\020\377o\213\011\377m\212\004\377~\225\004\377q\232\003\377\200\220\003\377" + "{\230\061\377\201\252L\377j\227\004\377l\235\023\377\203\250\061\377]\222\031\377" + "]\215\003\377m\232\030\377[{\034\377Fj\002\377@g\003\377By\005\377F}\012\377]\230'\377" + "l\252\060\377r\250\014\377]\214\003\377l\234\011\377a\215\007\377b\226\006\377~\252" + "\023\377n\234\014\377O~\002\377d\226\013\377W\207\025\377j\227\014\377\211\262\003" + "\377\\\214\011\377b\235\025\377\226\260\003\377k\225\007\377z\247\002\377\234\261" + "\025\377q\240\003\377f\221\005\377|\241\004\377x\236\002\377\\\206\002\377w\233\004\377" + "\206\245\002\377\210\244\004\377\223\255\010\377y\232\003\377|\242\013\377s\235\004" + "\377x\242\003\377\215\254\005\377e\217\002\377m\237\014\377u\233\000\377\242\264." + "\377\204\223\016\377\221\261\003\377\201\255\002\377t\252\026\377t\247\023\377\207" + "\270\060\377\205\260\037\377\211\267\021\377s\235\004\377\211\261\"\377\205\256" + "\024\377q\231\002\377ct\004\377u\230\005\377p\241\004\377j\225\005\377Z\210\004\377l\235" + ")\377v\237'\377_\202\005\377g\231\004\377L\201\001\377l\230\016\377Q\177\003\377N" + "\202\002\377b\233\002\377O\212\002\377_\226\002\377p\250\003\377O\202\001\377X\211\005" + "\377l\235\030\377p\236\063\377T\202\020\377T\203\007\377m\233*\377Z\224\007\377" + "L\203\002\377b\227\003\377T\207\002\377`\231\002\377d\235\014\377S\213\003\377P\204" + "\004\377J~\003\377V\213\003\377[\214\004\377`\212\002\377b\212\004\377w\236\012\377{\250" + "\016\377a\217\024\377Nu\003\377Nf\011\377IW\007\377\\o\010\377z\211#\377\220\241" + "I\377\207\252=\377\243\274X\377\201\222-\377x\213\036\377Qe\010\377`x\031\377" + "n\220\064\377d\204\032\377]\205\012\377\\\213\012\377U\204\002\377Gp\001\377Pu\000" + "\377R}\010\377q\232\023\377\223\265\061\377Rt\012\377`\214\000\377r\243-\377w\241" + "\071\377h\237\017\377X\211\014\377\177\233%\377f\215&\377M\177\002\377:j\000\377" + "Z\207!\377N|\012\377Cm\001\377H{\004\377a\001\377n\235@\377\223\304" + "o\377s\252K\377Dk\013\377Is\004\377m\232\010\377`\212\002\377c\216\004\377m\223\004" + "\377\224\265(\377\202\243\033\377\204\247\015\377d\237\026\377P\203\004\377V\206" + "\011\377X\206\012\377u\236\010\377\206\256\002\377\210\262\031\377\214\264\007\377" + "\214\240\015\377\211\252\005\377\237\267\034\377~\253\024\377\207\257\023\377m" + "\224\004\377z\237\004\377r\227\011\377i\223\011\377u\242\004\377\212\257\003\377\203" + "\247\003\377u\234\004\377z\242\002\377q\235\003\377u\236\002\377u\226\015\377u\235\006" + "\377f\225\003\377o\236\003\377{\245\006\377\220\264\010\377\214\252\004\377\206\252" + "\003\377\215\261\004\377\204\246\003\377[z\001\377\212\241\020\377\206\232\004\377\224" + "\246\005\377\226\263\024\377x\247\034\377\200\255\036\377s\236\000\377i\233\006\377" + "g\230\007\377_\227\005\377\\\214\004\377Fn\000\377V\206\003\377Aw\004\377R\207\003\377" + "f\232\005\377Y\204\002\377\\\215\003\377V\220\002\377f\234\003\377^\223\004\377_\216" + "\004\377p\237\004\377P{\003\377W\177\013\377b\221\004\377v\252\002\377P\204\003\377V\204" + "\004\377a\213\010\377P\201\000\377k\236\037\377b\217\027\377o\242+\377U\213\000\377" + "_\221\006\377Z\216\007\377X\223\007\377m\242\024\377o\241\013\377k\240\016\377z\254" + ";\377y\254?\377a\230\027\377]\220\007\377f\222\031\377Wx\025\377Nk\002\377q\225" + "\067\377o\241\065\377q\245\"\377z\254'\377Z\212\006\377]~\007\377]\210\022\377c" + "\221\025\377c\226\017\377Y\177\022\377_\220\006\377_\223\003\377O}\007\377c\221\030" + "\377v\243/\377\206\271/\377~\255'\377\223\266K\377\220\261K\377\227\276]" + "\377\237\311o\377\230\306k\377m\236\020\377h\230\016\377\210\257-\377\\\226" + "\012\377Y\216\023\377d\226\006\377Hs\000\377n\222/\377_\177\035\377Rl\004\377\202" + "\255G\377|\256P\377}\256=\377Kt\015\377a\217$\377t\244\011\377X\212\006\377S" + "\203\010\377a\222\012\377y\243\002\377\240\275\070\377Q\207\012\377j\237\013\377" + "h\227\021\377Kx\003\377m\243\021\377Y\211\006\377w\241\003\377\203\262\011\377\203" + "\260\005\377\177\246\014\377y\231\005\377\216\256\002\377o\222\003\377v\240\005\377" + "g\221\002\377\200\251\004\377k\227\006\377m\240\013\377h\231\004\377y\244\005\377\231" + "\300\010\377s\240\011\377n\230\004\377w\237\002\377e\221\002\377}\234\003\377\250\254" + "\024\377l\224\003\377k\232\003\377e\226\002\377\202\247\030\377\204\246\002\377\212" + "\253\003\377\217\262\004\377\227\270\003\377\221\262\003\377d\211\002\377k\223\003\377" + "~\240\004\377\227\245\006\377\220\237\006\377\222\255\015\377\214\257\015\377y\250" + "\007\377c\222\005\377[\213\004\377r\245\021\377q\253\030\377k\246\030\377Bv\001\377" + "@s\002\377J}\002\377S\203\003\377U|\011\377U\211\003\377c\232\004\377f\225\002\377W\210" + "\003\377h\230\002\377m\233\002\377Z\210\005\377c\222\023\377L\214\006\377p\244\003\377" + "l\236\003\377R\201\004\377M\177\002\377_\217\002\377^\215\002\377a\216\024\377o\243" + "=\377a\240\011\377h\241\034\377\205\270N\377b\236\026\377T\216\010\377i\233\016" + "\377_\222\003\377x\254/\377\200\265;\377d\234\014\377g\240\005\377e\230\001\377" + "X\207\013\377h\224\065\377f\222\026\377~\250\060\377~\255=\377}\255/\377q\234" + "\021\377t\240\023\377e\231\005\377\\\216\003\377a\225\004\377p\243\016\377o\243\016" + "\377}\265\061\377j\236\066\377\226\302v\377\220\276J\377q\243\035\377c\214\023" + "\377Vt\014\377u\235\061\377\210\264\\\377V\204\037\377Z\221\031\377\201\266;" + "\377z\257,\377w\250\025\377^\213\004\377V}\016\377l\223\012\377i\221#\377e\212" + "%\377]\200\007\377\177\252O\377_\222-\377v\244(\377Rx\022\377m\237\061\377W\204" + "\027\377m\232\003\377h\227\005\377W\203\006\377q\233\003\377\225\267\062\377s\227\020" + "\377n\233\034\377h\234\014\377i\233\011\377f\233\015\377g\225\026\377j\231\013" + "\377\205\266\003\377m\252\025\377s\245\010\377a\217\004\377o\237\004\377~\254\002\377" + "m\234\004\377\211\256\007\377z\240\010\377i\224\004\377y\242\007\377r\236\020\377n" + "\235\003\377\203\257\004\377t\244\007\377`\214\005\377s\236\003\377n\231\003\377l\226" + "\005\377\225\247\002\377{\236\024\377k\223\002\377t\233\007\377g\217\002\377~\253\005" + "\377p\233\004\377s\232\003\377\211\261\002\377\216\263\002\377\200\247\002\377\212" + "\260\004\377p\227\002\377\204\244\003\377}\224\003\377\243\257\002\377\242\271'\377" + "}\241\002\377t\241\006\377R\206\002\377Z\222\005\377O\205\006\377`\226\027\377w\247" + "-\377v\246\062\377[\216\"\377M\202\000\377>r\001\377W\205\005\377N\204\003\377W\212" + "\004\377o\240\010\377Kz\003\377d\230\004\377Y\213\004\377[\214\012\377Z\216\004\377F" + "~\002\377O\205\003\377{\254\002\377i\226\003\377R{\003\377X\214\003\377]\217\004\377Y\212" + "\013\377q\236'\377|\265;\377q\251-\377o\241+\377`\224\016\377L\202\003\377M\200" + "\003\377M~\010\377V\205\003\377d\213\023\377y\231\030\377p\235\035\377d\231\026\377" + "s\247)\377\\\220\021\377{\257<\377\201\260P\377]\224\010\377d\231\007\377a\231" + "\004\377h\242\022\377^\220\011\377t\241\024\377\212\264'\377k\225\013\377o\227" + "\024\377\207\252A\377\225\273P\377|\256\061\377k\235\035\377k\230\035\377}\245" + "/\377\201\260E\377r\247>\377e\231!\377^\220\022\377m\234!\377[\215\016\377" + "V\213\020\377b\227\026\377y\244\033\377~\247\064\377o\222\015\377u\243\066\377" + "Z\207\037\377|\255H\377W\177\037\377s\252*\377Rz\005\377f\223\"\377T\204\015\377" + "Gp\001\377[\204\002\377w\245+\377x\242\003\377v\236\023\377\204\250\024\377k\217" + "\026\377h\230\006\377l\236\031\377o\236\007\377q\234\030\377p\240\007\377\206\266" + "\010\377r\244\011\377h\246\036\377y\250\000\377i\226\002\377r\240\003\377\200\261" + "\003\377q\235\003\377\201\242\020\377\215\261\032\377q\236\003\377Zs\002\377l\230\003" + "\377r\231\003\377\214\263\004\377u\242\005\377n\230\006\377\203\245\013\377q\224\020" + "\377p\234\011\377\201\247\036\377u\241\013\377v\236\006\377y\243\001\377s\241\001" + "\377m\233\003\377]\212\004\377t\237\004\377{\245\003\377\222\267\004\377n\227\002\377" + "\204\246\006\377\204\246\005\377\227\266\013\377\220\252\004\377\231\257\005\377\270" + "\274@\377|\243\016\377p\233\001\377`\225\003\377a\225\002\377a\223\003\377T\206\004" + "\377X\216\003\377Y\220\001\377b\220\031\377\225\275`\377c\211\030\377T\204\003\377" + "H~\002\377V\212\003\377g\240\002\377M\205\003\377a\227\004\377Q\202\002\377Ky\002\377^" + "\212\014\377S\204\002\377U\207\003\377m\236\003\377^\210\002\377h\235\002\377a\227\003" + "\377L\205\003\377a\232\011\377h\240\021\377j\242\033\377}\260A\377\232\305h\377" + "g\237\023\377Fw\002\377Z\215\003\377V\213\006\377V\206\003\377f\235\012\377V\216\004" + "\377]\222\002\377U\213\002\377V\217\002\377^\226\003\377[\224\005\377R\213\005\377o\240" + "\033\377r\241\016\377a\214\015\377f\232\"\377b\226\011\377i\236\013\377o\236\037" + "\377{\250?\377e\221\027\377\225\267\065\377\200\244\031\377^\205\004\377t\241" + "'\377i\237\037\377k\240\"\377l\232%\377Fg\006\377^\216\024\377z\241\063\377\212" + "\235<\377b\220\031\377L~\003\377V\211\004\377p\235\016\377g}\035\377\207\264\065" + "\377z\246*\377}\264B\377^\215'\377l\221\062\377d\214!\377k\222\033\377Mu\010" + "\377@f\002\377Z\205\004\377v\244\"\377w\247\022\377m\224\001\377\241\272*\377h\213" + "\017\377^\214\011\377j\230\005\377\216\257#\377k\227\004\377\207\260\005\377\204" + "\255\007\377h\224\005\377f\235\021\377j\244\024\377|\252\002\377q\240\004\377\206\256" + "\004\377u\241\002\377h\224\002\377r\217\007\377\211\251\013\377j\227\003\377]\201\003" + "\377i\220\002\377\227\270\003\377p\227\002\377z\243\020\377u\242\001\377\177\255\031" + "\377g\221\003\377g\217\010\377g\215\012\377n\230\005\377\177\252\007\377y\242\014" + "\377{\243\025\377l\225\003\377f\221\004\377\210\261\004\377s\234\003\377\200\246\003" + "\377}\240\003\377\207\247\003\377\214\250\003\377\200\241\006\377\220\267\021\377" + "\202\245\003\377\242\261\031\377\226\260-\377u\236\002\377]\227\023\377Y\210\001" + "\377Nv\000\377_\202\017\377U\210\005\377]\231\010\377a\236\010\377Y\216\000\377_\223" + "\027\377W\214\006\377G\202\003\377b\226\023\377d\232\001\377[\223\007\377f\225\002\377" + "Q}\005\377Hs\002\377`\212\013\377S\200\004\377W\212\003\377X\212\002\377^\206\003\377" + "l\234\004\377n\245\004\377J\177\003\377i\235\007\377t\250\026\377|\260+\377u\253\065" + "\377\207\266L\377\225\300T\377\207\264B\377r\225\066\377^\201\023\377`\220" + "\021\377Iu\003\377L~\006\377R\205\004\377S\201\003\377]\221\015\377`\233\005\377M\201" + "\000\377_\224\005\377d\225\013\377`\220\011\377h\231\021\377\\\214\004\377h\241\017" + "\377b\227\012\377v\246\036\377k\231\035\377j\232\014\377u\245\022\377~\241\033" + "\377r\230\030\377\204\260Q\377\200\255J\377i\210+\377}\227A\377}\251A\377" + "\200\257I\377b\226)\377]\222\036\377\\\222\026\377F{\005\377\\\222\007\377v\245" + "\005\377j\225\011\377t\254\024\377^\214\020\377p\245\035\377Y\213\014\377u\246(" + "\377Z\212!\377R~\016\377F_\004\377JX\006\377h\216\007\377u\250#\377\214\261\001\377" + "\207\244\012\377\177\251\026\377l\224\024\377i\232\002\377t\251\035\377h\231\011" + "\377\204\260\005\377x\244\010\377\200\251\005\377`\216\011\377k\245.\377j\240\013" + "\377w\246\002\377\205\260\004\377w\235\004\377i\225\002\377v\235\003\377l\221\005\377" + "}\247\002\377u\245\006\377q\235\007\377r\232\003\377\224\265\010\377v\237$\377l\232" + "\012\377l\231\004\377~\254\002\377w\247\030\377r\236\015\377w\236\007\377{\243\004\377" + "u\232\004\377\212\261\032\377`\214\003\377\222\267)\377v\243\004\377\200\253\005\377" + "p\225\000\377\210\255\004\377\203\246\005\377\207\247\007\377\215\245\001\377l\212" + "\003\377~\225\004\377\204\242\010\377\222\261\010\377\211\247\024\377\220\262\016" + "\377=u\005\377[\216\"\377\213\271G\377Fw\005\377Dp\002\377:j\001\377b\231\013\377" + "Y\217\002\377Q\210\005\377o\250\005\377X\212\001\377p\244\030\377\\\225\001\377]\225" + "\007\377a\223\003\377Ls\005\377V\203\005\377U\202\005\377Xv\010\377c\223\004\377N\201" + "\003\377Y\213\005\377a\220\006\377a\215\005\377\\\213\003\377V\206\001\377~\251\061\377" + "\216\301F\377l\242\"\377\241\313i\377\211\267A\377\215\274L\377\262\334\214" + "\377h\215<\377h\214/\377h\240\007\377U\216\005\377W\216\004\377^\215\004\377Q\203" + "\003\377e\234\004\377s\254\034\377\202\262E\377z\244\060\377i\227\011\377e\223\013" + "\377d\225\013\377j\237\015\377c\222\017\377j\225\011\377\211\261\011\377{\245" + "\012\377\177\250\037\377\234\300c\377|\251F\377\204\251Z\377{\241G\377g\226" + "/\377R\206\015\377a\210\020\377dw\004\377\201\262\032\377\201\255\067\377x\247" + "\061\377r\251.\377i\233\017\377z\245\002\377q\243-\377l\240\020\377`\224\027\377" + "d\233\"\377d\234\030\377|\261-\377v\252(\377c\223\010\377[\205\005\377Nu\005\377" + "x\244\005\377\200\260\022\377x\234\005\377\204\245\023\377z\245\031\377m\233\005\377" + "q\233\005\377}\256&\377\204\260\005\377V\204\004\377z\247\015\377^\204\004\377g\222" + "!\377\211\265a\377\200\254\011\377}\253\003\377v\241\002\377n\230\004\377c\212\002" + "\377{\233\010\377\\\210\002\377r\243\014\377n\233\002\377q\232\002\377\201\250\005" + "\377y\231\016\377u\237\011\377\217\254\017\377\202\256\025\377\236\312Q\377\206" + "\261\061\377p\237\005\377{\245\013\377\234\274\016\377q\225\002\377\215\264\010\377" + "t\237\021\377a\211\005\377\214\271\022\377z\254\016\377}\254\034\377\231\273\016" + "\377\207\244\011\377\216\251\012\377\211\236\033\377\211\247\006\377Oc\001\377w" + "\233\003\377\211\261\017\377\205\247\013\377r\227\006\377[\207\003\377\200\246A\377" + "y\253\071\377d\221\034\377@c\002\377;a\002\377Iq\003\377W\211\005\377J\177\001\377g\231" + "\003\377Lu\004\377W\216\003\377b\242\006\377[\230\010\377P\203\000\377u\230.\377U\202" + "\005\377T\201\002\377Ir\003\377U\215\003\377I\177\003\377]\225\010\377Hi\003\377Vq\007\377" + "Or\002\377]\212\004\377;X\001\377^\207\015\377c\217\020\377w\253\032\377\203\270\060" + "\377\205\273\066\377\210\274\067\377r\244%\377Ms\015\377\177\241,\377a\213\023" + "\377l\244\025\377[\217\003\377c\234\004\377a\227\005\377j\234\005\377v\251\013\377" + "s\244\016\377x\247'\377y\245.\377q\242'\377o\237(\377g\226\036\377_\222\032" + "\377]\217\016\377`\222\017\377h\234\033\377Z\215\010\377\201\257\020\377\201\242" + "\040\377\177\253\037\377{\254%\377x\251\015\377~\246\013\377\206\254\031\377w" + "\246\020\377m\243\027\377d\231\025\377b\232\027\377W\213\011\377v\246\003\377]\205" + "\013\377e\225\013\377n\243\040\377z\253*\377X\211\020\377P~\004\377{\247=\377{" + "\245*\377Wz\006\377Qv\011\377\200\256\003\377p\240\001\377\240\272+\377r\243\027" + "\377\205\252\005\377s\240\004\377\214\264\004\377~\253\004\377^\216\020\377y\252\007" + "\377R\201\003\377h\230\027\377t\242%\377\231\300S\377\243\303!\377\234\271\"" + "\377\232\264$\377\207\240\021\377r\216\005\377\202\237\005\377h\226\003\377o\235" + "\013\377\206\254\003\377j\227\003\377\214\261\005\377y\241\006\377r\236\007\377\221" + "\262\014\377\205\255\016\377V\201\010\377}\247\015\377\216\261\013\377n\225\013" + "\377\220\265\007\377\205\260\005\377\210\256\024\377z\243\004\377x\241\003\377v\243" + "\010\377\215\267)\377\250\301.\377\252\302\033\377\222\257(\377\224\260\025" + "\377~\233\006\377\220\256\007\377\203\241\003\377\207\254\002\377y\232\002\377\212" + "\247\011\377\207\256\022\377", +}; + diff --git a/3rdparty/wlroots/examples/cat.h b/3rdparty/wlroots/examples/cat.h new file mode 100644 index 0000000000..46dc50f601 --- /dev/null +++ b/3rdparty/wlroots/examples/cat.h @@ -0,0 +1,13 @@ +#ifndef _CAT_H +#define _CAT_H + +struct gimp_texture { + unsigned int width; + unsigned int height; + unsigned int bytes_per_pixel; /* 2:RGB16, 3:RGB, 4:RGBA */ + unsigned char pixel_data[128 * 128 * 4 + 1]; +}; + +extern const struct gimp_texture cat_tex; + +#endif diff --git a/3rdparty/wlroots/examples/embedded.c b/3rdparty/wlroots/examples/embedded.c new file mode 100644 index 0000000000..f0f661198d --- /dev/null +++ b/3rdparty/wlroots/examples/embedded.c @@ -0,0 +1,244 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "xdg-shell-client-protocol.h" + +struct surface { + struct wlr_surface *wlr; + struct wl_listener commit; + struct wl_listener destroy; +}; + +static struct wl_display *remote_display = NULL; +static struct wl_compositor *compositor = NULL; +static struct wl_subcompositor *subcompositor = NULL; +static struct xdg_wm_base *wm_base = NULL; + +static struct wl_egl_window *egl_window = NULL; +static struct wlr_egl_surface *egl_surface = NULL; +static struct wl_surface *main_surface = NULL; +static struct wl_callback *frame_callback = NULL; + +static struct wlr_scene *scene = NULL; +static struct wlr_scene_output *scene_output = NULL; +static struct wl_listener new_surface = {0}; +static struct wl_listener output_frame = {0}; + +static EGLDisplay egl_display; +static EGLConfig egl_config; +static EGLContext egl_context; + +static int width = 500; +static int height = 500; + +static void draw_main_surface(void); + +static void frame_handle_done(void *data, struct wl_callback *callback, uint32_t t) { + wl_callback_destroy(callback); + frame_callback = NULL; + draw_main_surface(); +} + +static const struct wl_callback_listener frame_listener = { + .done = frame_handle_done, +}; + +static void draw_main_surface(void) { + frame_callback = wl_surface_frame(main_surface); + wl_callback_add_listener(frame_callback, &frame_listener, NULL); + + eglMakeCurrent(egl_display, egl_surface, egl_surface, egl_context); + eglSwapInterval(egl_display, 0); + + glViewport(0, 0, width, height); + glClearColor(1, 0, 0, 1); + glClear(GL_COLOR_BUFFER_BIT); + + eglSwapBuffers(egl_display, egl_surface); + wl_display_flush(remote_display); +} + +static void xdg_surface_handle_configure(void *data, + struct xdg_surface *xdg_surface, uint32_t serial) { + xdg_surface_ack_configure(xdg_surface, serial); + if (frame_callback == NULL) { + draw_main_surface(); + } +} + +static const struct xdg_surface_listener xdg_surface_listener = { + .configure = xdg_surface_handle_configure, +}; + +static void xdg_toplevel_handle_configure(void *data, + struct xdg_toplevel *xdg_toplevel, int32_t w, int32_t h, + struct wl_array *states) { + if (w != 0 && h != 0) { + width = w; + height = h; + } +} + +static const struct xdg_toplevel_listener xdg_toplevel_listener = { + .configure = xdg_toplevel_handle_configure, +}; + +static void handle_global(void *data, struct wl_registry *registry, + uint32_t name, const char *interface, uint32_t version) { + if (strcmp(interface, wl_compositor_interface.name) == 0) { + compositor = wl_registry_bind(registry, name, &wl_compositor_interface, 4); + } else if (strcmp(interface, wl_subcompositor_interface.name) == 0) { + subcompositor = wl_registry_bind(registry, name, &wl_subcompositor_interface, 1); + } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) { + wm_base = wl_registry_bind(registry, name, &xdg_wm_base_interface, 1); + } +} + +static void handle_global_remove(void *data, struct wl_registry *registry, + uint32_t name) { + // Who cares? +} + +static const struct wl_registry_listener registry_listener = { + .global = handle_global, + .global_remove = handle_global_remove, +}; + +static void output_handle_frame(struct wl_listener *listener, void *data) { + wlr_scene_output_commit(scene_output, NULL); + + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + wlr_scene_output_send_frame_done(scene_output, &now); +} + +static void surface_handle_commit(struct wl_listener *listener, void *data) { + struct surface *surface = wl_container_of(listener, surface, commit); + struct wlr_xdg_toplevel *xdg_toplevel = + wlr_xdg_toplevel_try_from_wlr_surface(surface->wlr); + if (xdg_toplevel != NULL && xdg_toplevel->base->initial_commit) { + wlr_xdg_toplevel_set_size(xdg_toplevel, 0, 0); + } +} + +static void surface_handle_destroy(struct wl_listener *listener, void *data) { + struct surface *surface = wl_container_of(listener, surface, destroy); + wl_list_remove(&surface->commit.link); + wl_list_remove(&surface->destroy.link); + free(surface); +} + +static void handle_new_surface(struct wl_listener *listener, void *data) { + struct wlr_surface *wlr_surface = data; + + struct surface *surface = calloc(1, sizeof(*surface)); + surface->wlr = wlr_surface; + + surface->commit.notify = surface_handle_commit; + wl_signal_add(&wlr_surface->events.commit, &surface->commit); + + surface->destroy.notify = surface_handle_destroy; + wl_signal_add(&wlr_surface->events.destroy, &surface->destroy); + + wlr_scene_surface_create(&scene->tree, wlr_surface); +} + +static void init_egl(struct wl_display *display) { + egl_display = eglGetPlatformDisplay(EGL_PLATFORM_WAYLAND_KHR, display, NULL); + eglInitialize(egl_display, NULL, NULL); + + EGLint matched = 0; + const EGLint config_attribs[] = { + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, + EGL_RED_SIZE, 8, + EGL_GREEN_SIZE, 8, + EGL_BLUE_SIZE, 8, + EGL_ALPHA_SIZE, 8, + EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, + EGL_NONE, + }; + eglChooseConfig(egl_display, config_attribs, &egl_config, 1, &matched); + + const EGLint context_attribs[] = { + EGL_CONTEXT_CLIENT_VERSION, 2, + EGL_NONE, + }; + egl_context = eglCreateContext(egl_display, egl_config, EGL_NO_CONTEXT, context_attribs); +} + +int main(int argc, char *argv[]) { + wlr_log_init(WLR_DEBUG, NULL); + + remote_display = wl_display_connect(NULL); + struct wl_registry *registry = wl_display_get_registry(remote_display); + wl_registry_add_listener(registry, ®istry_listener, NULL); + wl_display_roundtrip(remote_display); + + init_egl(remote_display); + + struct wl_display *local_display = wl_display_create(); + struct wl_event_loop *event_loop = wl_display_get_event_loop(local_display); + struct wlr_backend *backend = wlr_wl_backend_create(event_loop, remote_display); + struct wlr_renderer *renderer = wlr_renderer_autocreate(backend); + wlr_renderer_init_wl_display(renderer, local_display); + struct wlr_allocator *allocator = wlr_allocator_autocreate(backend, renderer); + scene = wlr_scene_create(); + struct wlr_compositor *wlr_compositor = wlr_compositor_create(local_display, 5, renderer); + + wlr_xdg_shell_create(local_display, 2); + + new_surface.notify = handle_new_surface; + wl_signal_add(&wlr_compositor->events.new_surface, &new_surface); + + wlr_backend_start(backend); + + main_surface = wl_compositor_create_surface(compositor); + struct xdg_surface *xdg_surface = xdg_wm_base_get_xdg_surface(wm_base, main_surface); + struct xdg_toplevel *xdg_toplevel = xdg_surface_get_toplevel(xdg_surface); + xdg_surface_add_listener(xdg_surface, &xdg_surface_listener, NULL); + xdg_toplevel_add_listener(xdg_toplevel, &xdg_toplevel_listener, NULL); + + egl_window = wl_egl_window_create(main_surface, width, height); + egl_surface = eglCreatePlatformWindowSurface(egl_display, + egl_config, egl_window, NULL); + + struct wl_surface *child_surface = wl_compositor_create_surface(compositor); + struct wl_subsurface *subsurface = wl_subcompositor_get_subsurface(subcompositor, child_surface, main_surface); + wl_subsurface_set_position(subsurface, 20, 20); + struct wlr_output *output = wlr_wl_output_create_from_surface(backend, child_surface); + wlr_output_init_render(output, allocator, renderer); + scene_output = wlr_scene_output_create(scene, output); + + output_frame.notify = output_handle_frame; + wl_signal_add(&output->events.frame, &output_frame); + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, true); + wlr_output_commit_state(output, &state); + wlr_output_state_finish(&state); + + wl_surface_commit(main_surface); + wl_display_flush(remote_display); + + const char *socket = wl_display_add_socket_auto(local_display); + setenv("WAYLAND_DISPLAY", socket, true); + wlr_log(WLR_INFO, "Running embedded Wayland compositor on WAYLAND_DISPLAY=%s", socket); + + wl_display_run(local_display); + + return 0; +} diff --git a/3rdparty/wlroots/examples/meson.build b/3rdparty/wlroots/examples/meson.build new file mode 100644 index 0000000000..28a83cccca --- /dev/null +++ b/3rdparty/wlroots/examples/meson.build @@ -0,0 +1,64 @@ +cairo = dependency('cairo', required: false, disabler: true) +# Only needed for drm_fourcc.h +libdrm_header = dependency('libdrm').partial_dependency(compile_args: true, includes: true) +wayland_client = dependency('wayland-client', required: false, disabler: true) +wayland_egl = dependency('wayland-egl', required: false, disabler: true) +egl = dependency('egl', version: '>= 1.5', required: false, disabler: true) +glesv2 = dependency('glesv2', required: false, disabler: true) + +compositors = { + 'simple': { + 'src': 'simple.c', + }, + 'pointer': { + 'src': 'pointer.c', + }, + 'touch': { + 'src': ['touch.c', 'cat.c'], + }, + 'tablet': { + 'src': 'tablet.c', + }, + 'rotation': { + 'src': ['rotation.c', 'cat.c'], + }, + 'output-layout': { + 'src': ['output-layout.c', 'cat.c'], + }, + 'scene-graph': { + 'src': 'scene-graph.c', + 'proto': ['xdg-shell'], + }, + 'output-layers': { + 'src': 'output-layers.c', + 'proto': [ + 'xdg-shell', + ], + }, + 'cairo-buffer': { + 'src': 'cairo-buffer.c', + 'dep': cairo, + }, + 'embedded': { + 'src': [ + 'embedded.c', + protocols_code['xdg-shell'], + protocols_client_header['xdg-shell'], + ], + 'dep': [wayland_client, wayland_egl, egl, glesv2], + }, +} + +foreach name, info : compositors + extra_src = [] + foreach p : info.get('proto', []) + extra_src += protocols_server_header[p] + endforeach + + executable( + name, + [info.get('src'), extra_src], + dependencies: [wlroots, libdrm_header, info.get('dep', [])], + build_by_default: get_option('examples'), + ) +endforeach diff --git a/3rdparty/wlroots/examples/output-layers.c b/3rdparty/wlroots/examples/output-layers.c new file mode 100644 index 0000000000..0535ff0b11 --- /dev/null +++ b/3rdparty/wlroots/examples/output-layers.c @@ -0,0 +1,344 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Simple compositor making use of the output layers API. The compositor will + * attempt to display client surfaces with output layers. Input is + * unimplemented. + * + * New surfaces are stacked on top of the existing ones as they appear. + * Surfaces that don't make it into an output layer are rendered as usual. */ + +struct server { + struct wl_display *wl_display; + struct wlr_backend *backend; + struct wlr_renderer *renderer; + struct wlr_allocator *allocator; + struct wlr_linux_dmabuf_v1 *linux_dmabuf_v1; + + struct wl_list outputs; + + struct wl_listener new_output; + struct wl_listener new_surface; +}; + +struct output_surface { + struct wlr_surface *wlr_surface; + struct wlr_output_layer *layer; + struct server *server; + struct wl_list link; + + int x, y; + struct wlr_buffer *buffer; + + bool first_commit, layer_accepted, prev_layer_accepted; + + struct wl_listener destroy; + struct wl_listener commit; + struct wl_listener layer_feedback; +}; + +struct output { + struct wl_list link; + struct server *server; + struct wlr_output *wlr_output; + struct wl_list surfaces; + + struct wl_listener frame; +}; + +static void output_handle_frame(struct wl_listener *listener, void *data) { + struct output *output = wl_container_of(listener, output, frame); + + struct wl_array layers_arr = {0}; + struct output_surface *output_surface; + wl_list_for_each(output_surface, &output->surfaces, link) { + struct wlr_output_layer_state *layer_state = + wl_array_add(&layers_arr, sizeof(*layer_state)); + *layer_state = (struct wlr_output_layer_state){ + .layer = output_surface->layer, + .buffer = output_surface->buffer, + .dst_box = { + .x = output_surface->x, + .y = output_surface->y, + .width = output_surface->wlr_surface->current.width, + .height = output_surface->wlr_surface->current.height, + }, + }; + } + + struct wlr_output_state output_state; + wlr_output_state_init(&output_state); + wlr_output_state_set_layers(&output_state, layers_arr.data, + layers_arr.size / sizeof(struct wlr_output_layer_state)); + + if (!wlr_output_test_state(output->wlr_output, &output_state)) { + wlr_log(WLR_ERROR, "wlr_output_test_state() failed"); + return; + } + + int width, height; + wlr_output_effective_resolution(output->wlr_output, &width, &height); + + struct wlr_render_pass *pass = wlr_output_begin_render_pass(output->wlr_output, &output_state, NULL); + wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){ + .box = { .width = width, .height = height }, + .color = { 0.3, 0.3, 0.3, 1 }, + }); + + size_t i = 0; + struct wlr_output_layer_state *layers = layers_arr.data; + wl_list_for_each(output_surface, &output->surfaces, link) { + struct wlr_surface *wlr_surface = output_surface->wlr_surface; + + output_surface->layer_accepted = layers[i].accepted; + i++; + + if (wlr_surface->buffer == NULL || output_surface->layer_accepted) { + continue; + } + + struct wlr_texture *texture = wlr_surface_get_texture(wlr_surface); + if (texture == NULL) { + continue; + } + + wlr_render_pass_add_texture(pass, &(struct wlr_render_texture_options){ + .texture = texture, + .dst_box = { .x = output_surface->x, .y = output_surface->y }, + }); + } + + wlr_render_pass_submit(pass); + + wlr_output_commit_state(output->wlr_output, &output_state); + wlr_output_state_finish(&output_state); + + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + + wl_list_for_each(output_surface, &output->surfaces, link) { + wlr_surface_send_frame_done(output_surface->wlr_surface, &now); + + if (output_surface->wlr_surface->buffer == NULL) { + continue; + } + + if ((output_surface->first_commit || + !output_surface->prev_layer_accepted) && + output_surface->layer_accepted) { + wlr_log(WLR_INFO, "Scanning out wlr_surface %p on output '%s'", + output_surface->wlr_surface, output->wlr_output->name); + } + if ((output_surface->first_commit || + output_surface->prev_layer_accepted) && + !output_surface->layer_accepted) { + wlr_log(WLR_INFO, "Cannot scan out wlr_surface %p on output '%s'", + output_surface->wlr_surface, output->wlr_output->name); + } + output_surface->prev_layer_accepted = output_surface->layer_accepted; + output_surface->first_commit = false; + } + + wl_array_release(&layers_arr); +} + +static void server_handle_new_output(struct wl_listener *listener, void *data) { + struct server *server = wl_container_of(listener, server, new_output); + struct wlr_output *wlr_output = data; + + wlr_output_init_render(wlr_output, server->allocator, server->renderer); + + struct output *output = calloc(1, sizeof(*output)); + output->wlr_output = wlr_output; + output->server = server; + wl_list_init(&output->surfaces); + output->frame.notify = output_handle_frame; + wl_signal_add(&wlr_output->events.frame, &output->frame); + wl_list_insert(&server->outputs, &output->link); + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, true); + struct wlr_output_mode *mode = wlr_output_preferred_mode(wlr_output); + if (mode != NULL) { + wlr_output_state_set_mode(&state, mode); + } + wlr_output_commit_state(wlr_output, &state); + wlr_output_state_finish(&state); + + wlr_output_create_global(wlr_output, server->wl_display); +} + +static void output_surface_handle_destroy(struct wl_listener *listener, + void *data) { + struct output_surface *output_surface = + wl_container_of(listener, output_surface, destroy); + wlr_buffer_unlock(output_surface->buffer); + wl_list_remove(&output_surface->destroy.link); + wl_list_remove(&output_surface->commit.link); + wl_list_remove(&output_surface->layer_feedback.link); + wl_list_remove(&output_surface->link); + wlr_output_layer_destroy(output_surface->layer); + free(output_surface); +} + +static void output_surface_handle_commit(struct wl_listener *listener, + void *data) { + struct output_surface *output_surface = + wl_container_of(listener, output_surface, commit); + + struct wlr_xdg_toplevel *xdg_toplevel = + wlr_xdg_toplevel_try_from_wlr_surface(output_surface->wlr_surface); + if (xdg_toplevel != NULL && xdg_toplevel->base->initial_commit) { + wlr_xdg_toplevel_set_size(xdg_toplevel, 0, 0); + } + + struct wlr_buffer *buffer = NULL; + if (output_surface->wlr_surface->buffer != NULL) { + buffer = wlr_buffer_lock(&output_surface->wlr_surface->buffer->base); + } + + wlr_buffer_unlock(output_surface->buffer); + output_surface->buffer = buffer; +} + +static void output_surface_handle_layer_feedback(struct wl_listener *listener, + void *data) { + struct output_surface *output_surface = + wl_container_of(listener, output_surface, layer_feedback); + const struct wlr_output_layer_feedback_event *event = data; + + wlr_log(WLR_DEBUG, "Sending linux-dmabuf feedback to surface %p", + output_surface->wlr_surface); + + struct wlr_linux_dmabuf_feedback_v1 feedback = {0}; + const struct wlr_linux_dmabuf_feedback_v1_init_options options = { + .main_renderer = output_surface->server->renderer, + .output_layer_feedback_event = event, + }; + wlr_linux_dmabuf_feedback_v1_init_with_options(&feedback, &options); + wlr_linux_dmabuf_v1_set_surface_feedback(output_surface->server->linux_dmabuf_v1, + output_surface->wlr_surface, &feedback); + wlr_linux_dmabuf_feedback_v1_finish(&feedback); +} + +static void server_handle_new_surface(struct wl_listener *listener, + void *data) { + struct server *server = wl_container_of(listener, server, new_surface); + struct wlr_surface *wlr_surface = data; + + struct output *output; + wl_list_for_each(output, &server->outputs, link) { + struct output_surface *output_surface = calloc(1, sizeof(*output_surface)); + output_surface->wlr_surface = wlr_surface; + output_surface->server = server; + output_surface->destroy.notify = output_surface_handle_destroy; + wl_signal_add(&wlr_surface->events.destroy, &output_surface->destroy); + output_surface->commit.notify = output_surface_handle_commit; + wl_signal_add(&wlr_surface->events.commit, &output_surface->commit); + + output_surface->layer = wlr_output_layer_create(output->wlr_output); + output_surface->layer_feedback.notify = output_surface_handle_layer_feedback; + wl_signal_add(&output_surface->layer->events.feedback, + &output_surface->layer_feedback); + + int pos = 50 * wl_list_length(&output->surfaces); + + output_surface->x = output_surface->y = pos; + output_surface->first_commit = true; + + wl_list_insert(output->surfaces.prev, &output_surface->link); + } +} + +int main(int argc, char *argv[]) { + wlr_log_init(WLR_DEBUG, NULL); + + char *startup_cmd = NULL; + + int c; + while ((c = getopt(argc, argv, "s:")) != -1) { + switch (c) { + case 's': + startup_cmd = optarg; + break; + default: + printf("usage: %s [-s startup-command]\n", argv[0]); + return EXIT_FAILURE; + } + } + if (optind < argc) { + printf("usage: %s [-s startup-command]\n", argv[0]); + return EXIT_FAILURE; + } + + struct server server = {0}; + server.wl_display = wl_display_create(); + server.backend = wlr_backend_autocreate(wl_display_get_event_loop(server.wl_display), NULL); + + server.renderer = wlr_renderer_autocreate(server.backend); + wlr_renderer_init_wl_shm(server.renderer, server.wl_display); + + if (wlr_renderer_get_texture_formats(server.renderer, WLR_BUFFER_CAP_DMABUF) != NULL) { + wlr_drm_create(server.wl_display, server.renderer); + server.linux_dmabuf_v1 = wlr_linux_dmabuf_v1_create_with_renderer( + server.wl_display, 4, server.renderer); + } + + server.allocator = wlr_allocator_autocreate(server.backend, + server.renderer); + + struct wlr_compositor *compositor = + wlr_compositor_create(server.wl_display, 5, server.renderer); + + wlr_xdg_shell_create(server.wl_display, 1); + + wl_list_init(&server.outputs); + + server.new_output.notify = server_handle_new_output; + wl_signal_add(&server.backend->events.new_output, &server.new_output); + + server.new_surface.notify = server_handle_new_surface; + wl_signal_add(&compositor->events.new_surface, &server.new_surface); + + const char *socket = wl_display_add_socket_auto(server.wl_display); + if (!socket) { + wl_display_destroy(server.wl_display); + return EXIT_FAILURE; + } + + if (!wlr_backend_start(server.backend)) { + wl_display_destroy(server.wl_display); + return EXIT_FAILURE; + } + + setenv("WAYLAND_DISPLAY", socket, true); + if (startup_cmd != NULL) { + if (fork() == 0) { + execlp("sh", "sh", "-c", startup_cmd, (char *)NULL); + } + } + + wlr_log(WLR_INFO, "Running Wayland compositor on WAYLAND_DISPLAY=%s", + socket); + wl_display_run(server.wl_display); + + wl_display_destroy_clients(server.wl_display); + wl_display_destroy(server.wl_display); + return EXIT_SUCCESS; +} diff --git a/3rdparty/wlroots/examples/output-layout.c b/3rdparty/wlroots/examples/output-layout.c new file mode 100644 index 0000000000..c481ddf80b --- /dev/null +++ b/3rdparty/wlroots/examples/output-layout.c @@ -0,0 +1,304 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "cat.h" + +struct sample_state { + struct wl_display *display; + struct wl_listener new_output; + struct wl_listener new_input; + struct wlr_renderer *renderer; + struct wlr_allocator *allocator; + struct wlr_texture *cat_texture; + struct wlr_output_layout *layout; + float x_offs, y_offs; + float x_vel, y_vel; + struct timespec ts_last; +}; + +struct sample_output { + struct sample_state *sample; + struct wlr_output *output; + struct wl_listener frame; + struct wl_listener destroy; +}; + +struct sample_keyboard { + struct sample_state *sample; + struct wlr_keyboard *wlr_keyboard; + struct wl_listener key; + struct wl_listener destroy; +}; + +static void animate_cat(struct sample_state *sample, + struct wlr_output *output) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + long ms = (ts.tv_sec - sample->ts_last.tv_sec) * 1000 + + (ts.tv_nsec - sample->ts_last.tv_nsec) / 1000000; + // how many seconds have passed since the last time we animated + float seconds = ms / 1000.0f; + + if (seconds > 0.1f) { + // XXX when we switch vt, the rendering loop stops so try to detect + // that and pause when it happens. + seconds = 0.0f; + } + + // check for collisions and bounce + bool ur_collision = !wlr_output_layout_output_at(sample->layout, + sample->x_offs + 128, sample->y_offs); + bool ul_collision = !wlr_output_layout_output_at(sample->layout, + sample->x_offs, sample->y_offs); + bool ll_collision = !wlr_output_layout_output_at(sample->layout, + sample->x_offs, sample->y_offs + 128); + bool lr_collision = !wlr_output_layout_output_at(sample->layout, + sample->x_offs + 128, sample->y_offs + 128); + + if (ur_collision && ul_collision && ll_collision && lr_collision) { + // oops we went off the screen somehow + struct wlr_output_layout_output *l_output = + wlr_output_layout_get(sample->layout, output); + sample->x_offs = l_output->x + 20; + sample->y_offs = l_output->y + 20; + } else if (ur_collision && ul_collision) { + sample->y_vel = fabs(sample->y_vel); + } else if (lr_collision && ll_collision) { + sample->y_vel = -fabs(sample->y_vel); + } else if (ll_collision && ul_collision) { + sample->x_vel = fabs(sample->x_vel); + } else if (ur_collision && lr_collision) { + sample->x_vel = -fabs(sample->x_vel); + } else { + if (ur_collision || lr_collision) { + sample->x_vel = -fabs(sample->x_vel); + } + if (ul_collision || ll_collision) { + sample->x_vel = fabs(sample->x_vel); + } + if (ul_collision || ur_collision) { + sample->y_vel = fabs(sample->y_vel); + } + if (ll_collision || lr_collision) { + sample->y_vel = -fabs(sample->y_vel); + } + } + + sample->x_offs += sample->x_vel * seconds; + sample->y_offs += sample->y_vel * seconds; + sample->ts_last = ts; +} + +static void output_frame_notify(struct wl_listener *listener, void *data) { + struct sample_output *output = wl_container_of(listener, output, frame); + struct sample_state *sample = output->sample; + struct wlr_output *wlr_output = output->output; + + struct wlr_output_state output_state; + wlr_output_state_init(&output_state); + struct wlr_render_pass *pass = wlr_output_begin_render_pass(wlr_output, &output_state, NULL); + + wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){ + .box = { .width = wlr_output->width, .height = wlr_output->height }, + .color = { 0.25, 0.25, 0.25, 1 }, + }); + + animate_cat(sample, output->output); + + struct wlr_box box = { + .x = sample->x_offs, .y = sample->y_offs, + .width = 128, .height = 128, + }; + if (wlr_output_layout_intersects(sample->layout, output->output, &box)) { + // transform global coordinates to local coordinates + double local_x = sample->x_offs; + double local_y = sample->y_offs; + wlr_output_layout_output_coords(sample->layout, output->output, + &local_x, &local_y); + + wlr_render_pass_add_texture(pass, &(struct wlr_render_texture_options){ + .texture = sample->cat_texture, + .dst_box = box, + }); + } + + wlr_render_pass_submit(pass); + wlr_output_commit_state(wlr_output, &output_state); + wlr_output_state_finish(&output_state); +} + +static void update_velocities(struct sample_state *sample, + float x_diff, float y_diff) { + sample->x_vel += x_diff; + sample->y_vel += y_diff; +} + +static void output_remove_notify(struct wl_listener *listener, void *data) { + struct sample_output *sample_output = wl_container_of(listener, sample_output, destroy); + struct sample_state *sample = sample_output->sample; + wlr_output_layout_remove(sample->layout, sample_output->output); + wl_list_remove(&sample_output->frame.link); + wl_list_remove(&sample_output->destroy.link); + free(sample_output); +} + +static void new_output_notify(struct wl_listener *listener, void *data) { + struct wlr_output *output = data; + struct sample_state *sample = wl_container_of(listener, sample, new_output); + + wlr_output_init_render(output, sample->allocator, sample->renderer); + + struct sample_output *sample_output = calloc(1, sizeof(*sample_output)); + wlr_output_layout_add_auto(sample->layout, output); + sample_output->output = output; + sample_output->sample = sample; + wl_signal_add(&output->events.frame, &sample_output->frame); + sample_output->frame.notify = output_frame_notify; + wl_signal_add(&output->events.destroy, &sample_output->destroy); + sample_output->destroy.notify = output_remove_notify; + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, true); + struct wlr_output_mode *mode = wlr_output_preferred_mode(output); + if (mode != NULL) { + wlr_output_state_set_mode(&state, mode); + } + wlr_output_commit_state(output, &state); + wlr_output_state_finish(&state); +} + +static void keyboard_key_notify(struct wl_listener *listener, void *data) { + struct sample_keyboard *keyboard = wl_container_of(listener, keyboard, key); + struct sample_state *sample = keyboard->sample; + struct wlr_keyboard_key_event *event = data; + uint32_t keycode = event->keycode + 8; + const xkb_keysym_t *syms; + int nsyms = xkb_state_key_get_syms(keyboard->wlr_keyboard->xkb_state, + keycode, &syms); + for (int i = 0; i < nsyms; i++) { + xkb_keysym_t sym = syms[i]; + if (sym == XKB_KEY_Escape) { + wl_display_terminate(sample->display); + } + // NOTE: It may be better to simply refer to our key state during each frame + // and make this change in pixels/sec^2 + // Also, key repeat + int delta = 75; + if (event->state == WL_KEYBOARD_KEY_STATE_PRESSED) { + switch (sym) { + case XKB_KEY_Left: + update_velocities(sample, -delta, 0); + break; + case XKB_KEY_Right: + update_velocities(sample, delta, 0); + break; + case XKB_KEY_Up: + update_velocities(sample, 0, -delta); + break; + case XKB_KEY_Down: + update_velocities(sample, 0, delta); + break; + } + } + } +} + +static void keyboard_destroy_notify(struct wl_listener *listener, void *data) { + struct sample_keyboard *keyboard = wl_container_of(listener, keyboard, destroy); + wl_list_remove(&keyboard->destroy.link); + wl_list_remove(&keyboard->key.link); + free(keyboard); +} + +static void new_input_notify(struct wl_listener *listener, void *data) { + struct wlr_input_device *device = data; + struct sample_state *sample = wl_container_of(listener, sample, new_input); + switch (device->type) { + case WLR_INPUT_DEVICE_KEYBOARD:; + struct sample_keyboard *keyboard = calloc(1, sizeof(*keyboard)); + keyboard->wlr_keyboard = wlr_keyboard_from_input_device(device); + keyboard->sample = sample; + wl_signal_add(&device->events.destroy, &keyboard->destroy); + keyboard->destroy.notify = keyboard_destroy_notify; + wl_signal_add(&keyboard->wlr_keyboard->events.key, &keyboard->key); + keyboard->key.notify = keyboard_key_notify; + struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + if (!context) { + wlr_log(WLR_ERROR, "Failed to create XKB context"); + exit(1); + } + struct xkb_keymap *keymap = xkb_keymap_new_from_names(context, NULL, + XKB_KEYMAP_COMPILE_NO_FLAGS); + if (!keymap) { + wlr_log(WLR_ERROR, "Failed to create XKB keymap"); + exit(1); + } + wlr_keyboard_set_keymap(keyboard->wlr_keyboard, keymap); + xkb_keymap_unref(keymap); + xkb_context_unref(context); + break; + default: + break; + } +} + + +int main(int argc, char *argv[]) { + wlr_log_init(WLR_DEBUG, NULL); + struct wl_display *display = wl_display_create(); + struct sample_state state = { + .x_vel = 500, + .y_vel = 500, + .display = display, + }; + + state.layout = wlr_output_layout_create(display); + clock_gettime(CLOCK_MONOTONIC, &state.ts_last); + + struct wlr_backend *wlr = wlr_backend_autocreate(wl_display_get_event_loop(display), NULL); + if (!wlr) { + exit(1); + } + + wl_signal_add(&wlr->events.new_output, &state.new_output); + state.new_output.notify = new_output_notify; + wl_signal_add(&wlr->events.new_input, &state.new_input); + state.new_input.notify = new_input_notify; + + state.renderer = wlr_renderer_autocreate(wlr); + state.cat_texture = wlr_texture_from_pixels(state.renderer, + DRM_FORMAT_ABGR8888, cat_tex.width * 4, cat_tex.width, cat_tex.height, + cat_tex.pixel_data); + + state.allocator = wlr_allocator_autocreate(wlr, state.renderer); + + if (!wlr_backend_start(wlr)) { + wlr_log(WLR_ERROR, "Failed to start backend"); + wlr_backend_destroy(wlr); + exit(1); + } + wl_display_run(display); + + wlr_texture_destroy(state.cat_texture); + + wl_display_destroy(state.display); +} diff --git a/3rdparty/wlroots/examples/pointer.c b/3rdparty/wlroots/examples/pointer.c new file mode 100644 index 0000000000..f3ef5435e7 --- /dev/null +++ b/3rdparty/wlroots/examples/pointer.c @@ -0,0 +1,416 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct sample_state { + struct wl_display *display; + struct compositor_state *compositor; + struct wlr_renderer *renderer; + struct wlr_allocator *allocator; + struct wlr_xcursor_manager *xcursor_manager; + struct wlr_cursor *cursor; + double cur_x, cur_y; + float default_color[4]; + float clear_color[4]; + struct wlr_output_layout *layout; + struct wl_list devices; + struct timespec last_frame; + + struct wl_listener new_output; + struct wl_listener new_input; + struct wl_listener cursor_motion; + struct wl_listener cursor_motion_absolute; + struct wl_listener cursor_button; + struct wl_listener cursor_axis; + + struct wl_listener touch_motion; + struct wl_listener touch_up; + struct wl_listener touch_down; + struct wl_listener touch_cancel; + struct wl_list touch_points; + + struct wl_listener tablet_tool_axis; + struct wl_listener tablet_tool_proxmity; + struct wl_listener tablet_tool_tip; + struct wl_listener tablet_tool_button; +}; + +struct touch_point { + int32_t touch_id; + double x, y; + struct wl_list link; +}; + +struct sample_output { + struct sample_state *state; + struct wlr_output *output; + struct wl_listener frame; + struct wl_listener destroy; +}; + +struct sample_keyboard { + struct sample_state *state; + struct wlr_keyboard *wlr_keyboard; + struct wl_listener key; + struct wl_listener destroy; +}; + +static void warp_to_touch(struct sample_state *state, + struct wlr_input_device *dev) { + if (wl_list_empty(&state->touch_points)) { + return; + } + + double x = 0, y = 0; + size_t n = 0; + struct touch_point *point; + wl_list_for_each(point, &state->touch_points, link) { + x += point->x; + y += point->y; + n++; + } + x /= n; + y /= n; + wlr_cursor_warp_absolute(state->cursor, dev, x, y); +} + +static void output_frame_notify(struct wl_listener *listener, void *data) { + struct sample_output *sample_output = wl_container_of(listener, sample_output, frame); + struct sample_state *state = sample_output->state; + struct wlr_output *wlr_output = sample_output->output; + struct wlr_renderer *renderer = state->renderer; + assert(renderer); + + struct wlr_output_state output_state; + wlr_output_state_init(&output_state); + struct wlr_render_pass *pass = wlr_output_begin_render_pass(wlr_output, &output_state, NULL); + wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){ + .box = { .width = wlr_output->width, .height = wlr_output->height }, + .color = { + state->clear_color[0], + state->clear_color[1], + state->clear_color[2], + state->clear_color[3], + }, + }); + wlr_output_add_software_cursors_to_render_pass(wlr_output, pass, NULL); + wlr_render_pass_submit(pass); + wlr_output_commit_state(wlr_output, &output_state); + wlr_output_state_finish(&output_state); +} + +static void handle_cursor_motion(struct wl_listener *listener, void *data) { + struct sample_state *sample = + wl_container_of(listener, sample, cursor_motion); + struct wlr_pointer_motion_event *event = data; + wlr_cursor_move(sample->cursor, &event->pointer->base, event->delta_x, + event->delta_y); +} + +static void handle_cursor_motion_absolute(struct wl_listener *listener, + void *data) { + struct sample_state *sample = + wl_container_of(listener, sample, cursor_motion_absolute); + struct wlr_pointer_motion_absolute_event *event = data; + + sample->cur_x = event->x; + sample->cur_y = event->y; + + wlr_cursor_warp_absolute(sample->cursor, &event->pointer->base, + sample->cur_x, sample->cur_y); +} + +static void handle_cursor_button(struct wl_listener *listener, void *data) { + struct sample_state *sample = + wl_container_of(listener, sample, cursor_button); + struct wlr_pointer_button_event *event = data; + + float (*color)[4]; + if (event->state == WL_POINTER_BUTTON_STATE_RELEASED) { + color = &sample->default_color; + memcpy(&sample->clear_color, color, sizeof(*color)); + } else { + float red[4] = { 0.25f, 0.25f, 0.25f, 1 }; + red[event->button % 3] = 1; + color = &red; + memcpy(&sample->clear_color, color, sizeof(*color)); + } +} + +static void handle_cursor_axis(struct wl_listener *listener, void *data) { + struct sample_state *sample = + wl_container_of(listener, sample, cursor_axis); + struct wlr_pointer_axis_event *event = data; + + for (size_t i = 0; i < 3; ++i) { + sample->default_color[i] += event->delta > 0 ? -0.05f : 0.05f; + if (sample->default_color[i] > 1.0f) { + sample->default_color[i] = 1.0f; + } + if (sample->default_color[i] < 0.0f) { + sample->default_color[i] = 0.0f; + } + } + + memcpy(&sample->clear_color, &sample->default_color, + sizeof(sample->clear_color)); +} + +static void handle_touch_up(struct wl_listener *listener, void *data) { + struct sample_state *sample = wl_container_of(listener, sample, touch_up); + struct wlr_touch_up_event *event = data; + + struct touch_point *point, *tmp; + wl_list_for_each_safe(point, tmp, &sample->touch_points, link) { + if (point->touch_id == event->touch_id) { + wl_list_remove(&point->link); + break; + } + } + + warp_to_touch(sample, &event->touch->base); +} + +static void handle_touch_down(struct wl_listener *listener, void *data) { + struct sample_state *sample = wl_container_of(listener, sample, touch_down); + struct wlr_touch_down_event *event = data; + struct touch_point *point = calloc(1, sizeof(*point)); + point->touch_id = event->touch_id; + point->x = event->x; + point->y = event->y; + wl_list_insert(&sample->touch_points, &point->link); + + warp_to_touch(sample, &event->touch->base); +} + +static void handle_touch_motion(struct wl_listener *listener, void *data) { + struct sample_state *sample = + wl_container_of(listener, sample, touch_motion); + struct wlr_touch_motion_event *event = data; + + struct touch_point *point; + wl_list_for_each(point, &sample->touch_points, link) { + if (point->touch_id == event->touch_id) { + point->x = event->x; + point->y = event->y; + break; + } + } + + warp_to_touch(sample, &event->touch->base); +} + +static void handle_touch_cancel(struct wl_listener *listener, void *data) { + wlr_log(WLR_DEBUG, "TODO: touch cancel"); +} + +static void handle_tablet_tool_axis(struct wl_listener *listener, void *data) { + struct sample_state *sample = + wl_container_of(listener, sample, tablet_tool_axis); + struct wlr_tablet_tool_axis_event *event = data; + if ((event->updated_axes & WLR_TABLET_TOOL_AXIS_X) && + (event->updated_axes & WLR_TABLET_TOOL_AXIS_Y)) { + wlr_cursor_warp_absolute(sample->cursor, &event->tablet->base, + event->x, event->y); + } +} + +static void keyboard_key_notify(struct wl_listener *listener, void *data) { + struct sample_keyboard *keyboard = wl_container_of(listener, keyboard, key); + struct sample_state *sample = keyboard->state; + struct wlr_keyboard_key_event *event = data; + uint32_t keycode = event->keycode + 8; + const xkb_keysym_t *syms; + int nsyms = xkb_state_key_get_syms(keyboard->wlr_keyboard->xkb_state, + keycode, &syms); + for (int i = 0; i < nsyms; i++) { + xkb_keysym_t sym = syms[i]; + if (sym == XKB_KEY_Escape) { + wl_display_terminate(sample->display); + } + } +} + +static void output_remove_notify(struct wl_listener *listener, void *data) { + struct sample_output *sample_output = wl_container_of(listener, sample_output, destroy); + struct sample_state *sample = sample_output->state; + wlr_output_layout_remove(sample->layout, sample_output->output); + wl_list_remove(&sample_output->frame.link); + wl_list_remove(&sample_output->destroy.link); + free(sample_output); +} + +static void new_output_notify(struct wl_listener *listener, void *data) { + struct wlr_output *output = data; + struct sample_state *sample = wl_container_of(listener, sample, new_output); + + wlr_output_init_render(output, sample->allocator, sample->renderer); + + struct sample_output *sample_output = calloc(1, sizeof(*sample_output)); + sample_output->output = output; + sample_output->state = sample; + wl_signal_add(&output->events.frame, &sample_output->frame); + sample_output->frame.notify = output_frame_notify; + wl_signal_add(&output->events.destroy, &sample_output->destroy); + sample_output->destroy.notify = output_remove_notify; + wlr_output_layout_add_auto(sample->layout, sample_output->output); + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, true); + struct wlr_output_mode *mode = wlr_output_preferred_mode(output); + if (mode != NULL) { + wlr_output_state_set_mode(&state, mode); + } + wlr_output_commit_state(output, &state); + wlr_output_state_finish(&state); +} + + +static void keyboard_destroy_notify(struct wl_listener *listener, void *data) { + struct sample_keyboard *keyboard = wl_container_of(listener, keyboard, destroy); + wl_list_remove(&keyboard->destroy.link); + wl_list_remove(&keyboard->key.link); + free(keyboard); +} + +static void new_input_notify(struct wl_listener *listener, void *data) { + struct wlr_input_device *device = data; + struct sample_state *state = wl_container_of(listener, state, new_input); + switch (device->type) { + case WLR_INPUT_DEVICE_POINTER: + case WLR_INPUT_DEVICE_TOUCH: + case WLR_INPUT_DEVICE_TABLET: + wlr_cursor_attach_input_device(state->cursor, device); + break; + + case WLR_INPUT_DEVICE_KEYBOARD:; + struct sample_keyboard *keyboard = calloc(1, sizeof(*keyboard)); + keyboard->wlr_keyboard = wlr_keyboard_from_input_device(device); + keyboard->state = state; + wl_signal_add(&device->events.destroy, &keyboard->destroy); + keyboard->destroy.notify = keyboard_destroy_notify; + wl_signal_add(&keyboard->wlr_keyboard->events.key, &keyboard->key); + keyboard->key.notify = keyboard_key_notify; + struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + if (!context) { + wlr_log(WLR_ERROR, "Failed to create XKB context"); + exit(1); + } + struct xkb_keymap *keymap = xkb_keymap_new_from_names(context, NULL, + XKB_KEYMAP_COMPILE_NO_FLAGS); + if (!keymap) { + wlr_log(WLR_ERROR, "Failed to create XKB keymap"); + exit(1); + } + wlr_keyboard_set_keymap(keyboard->wlr_keyboard, keymap); + xkb_keymap_unref(keymap); + xkb_context_unref(context); + break; + default: + break; + } +} + + +int main(int argc, char *argv[]) { + wlr_log_init(WLR_DEBUG, NULL); + struct wl_display *display = wl_display_create(); + struct sample_state state = { + .default_color = { 0.25f, 0.25f, 0.25f, 1 }, + .clear_color = { 0.25f, 0.25f, 0.25f, 1 }, + .display = display + }; + + struct wlr_backend *wlr = wlr_backend_autocreate(wl_display_get_event_loop(display), NULL); + if (!wlr) { + exit(1); + } + + state.renderer = wlr_renderer_autocreate(wlr); + state.allocator = wlr_allocator_autocreate(wlr, state.renderer); + + state.cursor = wlr_cursor_create(); + state.layout = wlr_output_layout_create(display); + wlr_cursor_attach_output_layout(state.cursor, state.layout); + //wlr_cursor_map_to_region(state.cursor, state.config->cursor.mapped_box); + wl_list_init(&state.devices); + wl_list_init(&state.touch_points); + + // pointer events + wl_signal_add(&state.cursor->events.motion, &state.cursor_motion); + state.cursor_motion.notify = handle_cursor_motion; + + wl_signal_add(&state.cursor->events.motion_absolute, + &state.cursor_motion_absolute); + state.cursor_motion_absolute.notify = handle_cursor_motion_absolute; + + wl_signal_add(&state.cursor->events.button, &state.cursor_button); + state.cursor_button.notify = handle_cursor_button; + + wl_signal_add(&state.cursor->events.axis, &state.cursor_axis); + state.cursor_axis.notify = handle_cursor_axis; + + // touch events + wl_signal_add(&state.cursor->events.touch_up, &state.touch_up); + state.touch_up.notify = handle_touch_up; + + wl_signal_add(&state.cursor->events.touch_down, &state.touch_down); + state.touch_down.notify = handle_touch_down; + + wl_signal_add(&state.cursor->events.touch_motion, &state.touch_motion); + state.touch_motion.notify = handle_touch_motion; + + wl_signal_add(&state.cursor->events.touch_cancel, &state.touch_cancel); + state.touch_cancel.notify = handle_touch_cancel; + + wl_signal_add(&wlr->events.new_input, &state.new_input); + state.new_input.notify = new_input_notify; + + wl_signal_add(&wlr->events.new_output, &state.new_output); + state.new_output.notify = new_output_notify; + + // tool events + wl_signal_add(&state.cursor->events.tablet_tool_axis, + &state.tablet_tool_axis); + state.tablet_tool_axis.notify = handle_tablet_tool_axis; + + state.xcursor_manager = wlr_xcursor_manager_create(NULL, 24); + if (!state.xcursor_manager) { + wlr_log(WLR_ERROR, "Failed to load default cursor"); + return 1; + } + + wlr_cursor_set_xcursor(state.cursor, state.xcursor_manager, "default"); + + clock_gettime(CLOCK_MONOTONIC, &state.last_frame); + + if (!wlr_backend_start(wlr)) { + wlr_log(WLR_ERROR, "Failed to start backend"); + wlr_backend_destroy(wlr); + exit(1); + } + wl_display_run(display); + wl_display_destroy(display); + + wlr_xcursor_manager_destroy(state.xcursor_manager); + wlr_cursor_destroy(state.cursor); +} diff --git a/3rdparty/wlroots/examples/rotation.c b/3rdparty/wlroots/examples/rotation.c new file mode 100644 index 0000000000..18bfbd38d5 --- /dev/null +++ b/3rdparty/wlroots/examples/rotation.c @@ -0,0 +1,288 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "cat.h" + +struct sample_state { + struct wl_display *display; + struct wl_listener new_output; + struct wl_listener new_input; + struct timespec last_frame; + struct wlr_renderer *renderer; + struct wlr_allocator *allocator; + struct wlr_texture *cat_texture; + struct wl_list outputs; + enum wl_output_transform transform; +}; + +struct sample_output { + struct sample_state *sample; + struct wlr_output *output; + struct wl_listener frame; + struct wl_listener destroy; + float x_offs, y_offs; + float x_vel, y_vel; + struct wl_list link; +}; + +struct sample_keyboard { + struct sample_state *sample; + struct wlr_keyboard *wlr_keyboard; + struct wl_listener key; + struct wl_listener destroy; +}; + +static void output_frame_notify(struct wl_listener *listener, void *data) { + struct sample_output *sample_output = wl_container_of(listener, sample_output, frame); + struct sample_state *sample = sample_output->sample; + struct wlr_output *wlr_output = sample_output->output; + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + + int32_t width, height; + wlr_output_effective_resolution(wlr_output, &width, &height); + + struct wlr_output_state output_state; + wlr_output_state_init(&output_state); + struct wlr_render_pass *pass = wlr_output_begin_render_pass(wlr_output, &output_state, NULL); + + wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){ + .box = { .width = wlr_output->width, .height = wlr_output->height }, + .color = { 0.25, 0.25, 0.25, 1 }, + }); + + for (int y = -128 + (int)sample_output->y_offs; y < height; y += 128) { + for (int x = -128 + (int)sample_output->x_offs; x < width; x += 128) { + wlr_render_pass_add_texture(pass, &(struct wlr_render_texture_options){ + .texture = sample->cat_texture, + .dst_box = { .x = x, .y = y }, + .transform = wlr_output->transform, + }); + } + } + + wlr_render_pass_submit(pass); + wlr_output_commit_state(wlr_output, &output_state); + wlr_output_state_finish(&output_state); + + long ms = (now.tv_sec - sample->last_frame.tv_sec) * 1000 + + (now.tv_nsec - sample->last_frame.tv_nsec) / 1000000; + float seconds = ms / 1000.0f; + + sample_output->x_offs += sample_output->x_vel * seconds; + sample_output->y_offs += sample_output->y_vel * seconds; + if (sample_output->x_offs > 128) { + sample_output->x_offs = 0; + } + if (sample_output->y_offs > 128) { + sample_output->y_offs = 0; + } + sample->last_frame = now; +} + +static void update_velocities(struct sample_state *sample, + float x_diff, float y_diff) { + struct sample_output *sample_output; + wl_list_for_each(sample_output, &sample->outputs, link) { + sample_output->x_vel += x_diff; + sample_output->y_vel += y_diff; + } +} + +static void output_remove_notify(struct wl_listener *listener, void *data) { + struct sample_output *sample_output = wl_container_of(listener, sample_output, destroy); + wl_list_remove(&sample_output->frame.link); + wl_list_remove(&sample_output->destroy.link); + free(sample_output); +} + +static void new_output_notify(struct wl_listener *listener, void *data) { + struct wlr_output *output = data; + struct sample_state *sample = wl_container_of(listener, sample, new_output); + + wlr_output_init_render(output, sample->allocator, sample->renderer); + + struct sample_output *sample_output = calloc(1, sizeof(*sample_output)); + sample_output->x_offs = sample_output->y_offs = 0; + sample_output->x_vel = sample_output->y_vel = 128; + + sample_output->output = output; + sample_output->sample = sample; + wl_signal_add(&output->events.frame, &sample_output->frame); + sample_output->frame.notify = output_frame_notify; + wl_signal_add(&output->events.destroy, &sample_output->destroy); + sample_output->destroy.notify = output_remove_notify; + wl_list_insert(&sample->outputs, &sample_output->link); + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_transform(&state, sample->transform); + wlr_output_state_set_enabled(&state, true); + struct wlr_output_mode *mode = wlr_output_preferred_mode(output); + if (mode != NULL) { + wlr_output_state_set_mode(&state, mode); + } + wlr_output_commit_state(output, &state); + wlr_output_state_finish(&state); +} + +static void keyboard_key_notify(struct wl_listener *listener, void *data) { + struct sample_keyboard *keyboard = wl_container_of(listener, keyboard, key); + struct sample_state *sample = keyboard->sample; + struct wlr_keyboard_key_event *event = data; + uint32_t keycode = event->keycode + 8; + const xkb_keysym_t *syms; + int nsyms = xkb_state_key_get_syms(keyboard->wlr_keyboard->xkb_state, + keycode, &syms); + for (int i = 0; i < nsyms; i++) { + xkb_keysym_t sym = syms[i]; + if (sym == XKB_KEY_Escape) { + wl_display_terminate(sample->display); + } + if (event->state == WL_KEYBOARD_KEY_STATE_PRESSED) { + switch (sym) { + case XKB_KEY_Left: + update_velocities(sample, -16, 0); + break; + case XKB_KEY_Right: + update_velocities(sample, 16, 0); + break; + case XKB_KEY_Up: + update_velocities(sample, 0, -16); + break; + case XKB_KEY_Down: + update_velocities(sample, 0, 16); + break; + } + } + } +} + +static void keyboard_destroy_notify(struct wl_listener *listener, void *data) { + struct sample_keyboard *keyboard = wl_container_of(listener, keyboard, destroy); + wl_list_remove(&keyboard->destroy.link); + wl_list_remove(&keyboard->key.link); + free(keyboard); +} + +static void new_input_notify(struct wl_listener *listener, void *data) { + struct wlr_input_device *device = data; + struct sample_state *sample = wl_container_of(listener, sample, new_input); + switch (device->type) { + case WLR_INPUT_DEVICE_KEYBOARD:; + struct sample_keyboard *keyboard = calloc(1, sizeof(*keyboard)); + keyboard->wlr_keyboard = wlr_keyboard_from_input_device(device); + keyboard->sample = sample; + wl_signal_add(&device->events.destroy, &keyboard->destroy); + keyboard->destroy.notify = keyboard_destroy_notify; + wl_signal_add(&keyboard->wlr_keyboard->events.key, &keyboard->key); + keyboard->key.notify = keyboard_key_notify; + struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + if (!context) { + wlr_log(WLR_ERROR, "Failed to create XKB context"); + exit(1); + } + struct xkb_keymap *keymap = xkb_keymap_new_from_names(context, NULL, + XKB_KEYMAP_COMPILE_NO_FLAGS); + if (!keymap) { + wlr_log(WLR_ERROR, "Failed to create XKB keymap"); + exit(1); + } + wlr_keyboard_set_keymap(keyboard->wlr_keyboard, keymap); + xkb_keymap_unref(keymap); + xkb_context_unref(context); + break; + default: + break; + } +} + + +int main(int argc, char *argv[]) { + int c; + enum wl_output_transform transform = WL_OUTPUT_TRANSFORM_NORMAL; + while ((c = getopt(argc, argv, "r:")) != -1) { + switch (c) { + case 'r': + if (strcmp(optarg, "90") == 0) { + transform = WL_OUTPUT_TRANSFORM_90; + } else if (strcmp(optarg, "180") == 0) { + transform = WL_OUTPUT_TRANSFORM_180; + } else if (strcmp(optarg, "270") == 0) { + transform = WL_OUTPUT_TRANSFORM_270; + } else if (strcmp(optarg, "flipped") == 0) { + transform = WL_OUTPUT_TRANSFORM_FLIPPED; + } else if (strcmp(optarg, "flipped-90") == 0) { + transform = WL_OUTPUT_TRANSFORM_FLIPPED_90; + } else if (strcmp(optarg, "flipped-180") == 0) { + transform = WL_OUTPUT_TRANSFORM_FLIPPED_180; + } else if (strcmp(optarg, "flipped-270") == 0) { + transform = WL_OUTPUT_TRANSFORM_FLIPPED_270; + } else { + wlr_log(WLR_ERROR, "got unknown transform value: %s", optarg); + } + break; + default: + return 1; + } + } + wlr_log_init(WLR_DEBUG, NULL); + struct wl_display *display = wl_display_create(); + struct sample_state state = { + .display = display, + .transform = transform + }; + wl_list_init(&state.outputs); + + struct wlr_backend *wlr = wlr_backend_autocreate(wl_display_get_event_loop(display), NULL); + if (!wlr) { + exit(1); + } + + wl_signal_add(&wlr->events.new_output, &state.new_output); + state.new_output.notify = new_output_notify; + wl_signal_add(&wlr->events.new_input, &state.new_input); + state.new_input.notify = new_input_notify; + clock_gettime(CLOCK_MONOTONIC, &state.last_frame); + + state.renderer = wlr_renderer_autocreate(wlr); + if (!state.renderer) { + wlr_log(WLR_ERROR, "Could not start compositor, OOM"); + wlr_backend_destroy(wlr); + exit(EXIT_FAILURE); + } + state.cat_texture = wlr_texture_from_pixels(state.renderer, + DRM_FORMAT_ABGR8888, cat_tex.width * 4, cat_tex.width, cat_tex.height, + cat_tex.pixel_data); + if (!state.cat_texture) { + wlr_log(WLR_ERROR, "Could not start compositor, OOM"); + exit(EXIT_FAILURE); + } + + state.allocator = wlr_allocator_autocreate(wlr, state.renderer); + + if (!wlr_backend_start(wlr)) { + wlr_log(WLR_ERROR, "Failed to start backend"); + wlr_backend_destroy(wlr); + exit(1); + } + wl_display_run(display); + + wlr_texture_destroy(state.cat_texture); + wl_display_destroy(display); +} diff --git a/3rdparty/wlroots/examples/scene-graph.c b/3rdparty/wlroots/examples/scene-graph.c new file mode 100644 index 0000000000..4219865346 --- /dev/null +++ b/3rdparty/wlroots/examples/scene-graph.c @@ -0,0 +1,214 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Simple compositor making use of the scene-graph API. Input is unimplemented. + * + * New surfaces are stacked on top of the existing ones as they appear. */ + +static const int border_width = 3; + +struct server { + struct wl_display *display; + struct wlr_backend *backend; + struct wlr_renderer *renderer; + struct wlr_allocator *allocator; + struct wlr_scene *scene; + + uint32_t surface_offset; + + struct wl_listener new_output; + struct wl_listener new_surface; +}; + +struct surface { + struct wlr_surface *wlr; + struct wlr_scene_surface *scene_surface; + struct wlr_scene_rect *border; + struct wl_list link; + + struct wl_listener commit; + struct wl_listener destroy; +}; + +struct output { + struct wl_list link; + struct server *server; + struct wlr_output *wlr; + struct wlr_scene_output *scene_output; + + struct wl_listener frame; +}; + +static void output_handle_frame(struct wl_listener *listener, void *data) { + struct output *output = wl_container_of(listener, output, frame); + + if (!wlr_scene_output_commit(output->scene_output, NULL)) { + return; + } + + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + wlr_scene_output_send_frame_done(output->scene_output, &now); +} + +static void server_handle_new_output(struct wl_listener *listener, void *data) { + struct server *server = wl_container_of(listener, server, new_output); + struct wlr_output *wlr_output = data; + + wlr_output_init_render(wlr_output, server->allocator, server->renderer); + + struct output *output = calloc(1, sizeof(*output)); + output->wlr = wlr_output; + output->server = server; + output->frame.notify = output_handle_frame; + wl_signal_add(&wlr_output->events.frame, &output->frame); + + output->scene_output = wlr_scene_output_create(server->scene, wlr_output); + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, true); + struct wlr_output_mode *mode = wlr_output_preferred_mode(wlr_output); + if (mode != NULL) { + wlr_output_state_set_mode(&state, mode); + } + wlr_output_commit_state(wlr_output, &state); + wlr_output_state_finish(&state); + + wlr_output_create_global(wlr_output, server->display); +} + +static void surface_handle_commit(struct wl_listener *listener, void *data) { + struct surface *surface = wl_container_of(listener, surface, commit); + + wlr_scene_rect_set_size(surface->border, + surface->wlr->current.width + 2 * border_width, + surface->wlr->current.height + 2 * border_width); + + struct wlr_xdg_toplevel *xdg_toplevel = + wlr_xdg_toplevel_try_from_wlr_surface(surface->wlr); + if (xdg_toplevel != NULL && xdg_toplevel->base->initial_commit) { + wlr_xdg_toplevel_set_size(xdg_toplevel, 0, 0); + } +} + +static void surface_handle_destroy(struct wl_listener *listener, void *data) { + struct surface *surface = wl_container_of(listener, surface, destroy); + wlr_scene_node_destroy(&surface->scene_surface->buffer->node); + wlr_scene_node_destroy(&surface->border->node); + wl_list_remove(&surface->destroy.link); + wl_list_remove(&surface->link); + free(surface); +} + +static void server_handle_new_surface(struct wl_listener *listener, + void *data) { + struct server *server = wl_container_of(listener, server, new_surface); + struct wlr_surface *wlr_surface = data; + + int pos = server->surface_offset; + server->surface_offset += 50; + + struct surface *surface = calloc(1, sizeof(*surface)); + surface->wlr = wlr_surface; + surface->commit.notify = surface_handle_commit; + wl_signal_add(&wlr_surface->events.commit, &surface->commit); + surface->destroy.notify = surface_handle_destroy; + wl_signal_add(&wlr_surface->events.destroy, &surface->destroy); + + /* Border dimensions will be set in surface.commit handler */ + surface->border = wlr_scene_rect_create(&server->scene->tree, + 0, 0, (float[4]){ 0.5f, 0.5f, 0.5f, 1 }); + wlr_scene_node_set_position(&surface->border->node, pos, pos); + + surface->scene_surface = + wlr_scene_surface_create(&server->scene->tree, wlr_surface); + + wlr_scene_node_set_position(&surface->scene_surface->buffer->node, + pos + border_width, pos + border_width); +} + +int main(int argc, char *argv[]) { + wlr_log_init(WLR_DEBUG, NULL); + + char *startup_cmd = NULL; + + int c; + while ((c = getopt(argc, argv, "s:")) != -1) { + switch (c) { + case 's': + startup_cmd = optarg; + break; + default: + printf("usage: %s [-s startup-command]\n", argv[0]); + return EXIT_FAILURE; + } + } + if (optind < argc) { + printf("usage: %s [-s startup-command]\n", argv[0]); + return EXIT_FAILURE; + } + + struct server server = {0}; + server.surface_offset = 0; + server.display = wl_display_create(); + server.backend = wlr_backend_autocreate(wl_display_get_event_loop(server.display), NULL); + server.scene = wlr_scene_create(); + + server.renderer = wlr_renderer_autocreate(server.backend); + wlr_renderer_init_wl_display(server.renderer, server.display); + + server.allocator = wlr_allocator_autocreate(server.backend, + server.renderer); + + struct wlr_compositor *compositor = + wlr_compositor_create(server.display, 5, server.renderer); + + wlr_xdg_shell_create(server.display, 2); + + server.new_output.notify = server_handle_new_output; + wl_signal_add(&server.backend->events.new_output, &server.new_output); + + server.new_surface.notify = server_handle_new_surface; + wl_signal_add(&compositor->events.new_surface, &server.new_surface); + + const char *socket = wl_display_add_socket_auto(server.display); + if (!socket) { + wl_display_destroy(server.display); + return EXIT_FAILURE; + } + + if (!wlr_backend_start(server.backend)) { + wl_display_destroy(server.display); + return EXIT_FAILURE; + } + + setenv("WAYLAND_DISPLAY", socket, true); + if (startup_cmd != NULL) { + if (fork() == 0) { + execl("/bin/sh", "/bin/sh", "-c", startup_cmd, (void *)NULL); + } + } + + wlr_log(WLR_INFO, "Running Wayland compositor on WAYLAND_DISPLAY=%s", + socket); + wl_display_run(server.display); + + wl_display_destroy_clients(server.display); + wl_display_destroy(server.display); + return EXIT_SUCCESS; +} diff --git a/3rdparty/wlroots/examples/simple.c b/3rdparty/wlroots/examples/simple.c new file mode 100644 index 0000000000..d16708654f --- /dev/null +++ b/3rdparty/wlroots/examples/simple.c @@ -0,0 +1,204 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct sample_state { + struct wl_display *display; + struct wl_listener new_output; + struct wl_listener new_input; + struct wlr_renderer *renderer; + struct wlr_allocator *allocator; + struct timespec last_frame; + float color[4]; + int dec; +}; + +struct sample_output { + struct sample_state *sample; + struct wlr_output *output; + struct wl_listener frame; + struct wl_listener destroy; +}; + +struct sample_keyboard { + struct sample_state *sample; + struct wlr_keyboard *wlr_keyboard; + struct wl_listener key; + struct wl_listener destroy; +}; + +static void output_frame_notify(struct wl_listener *listener, void *data) { + struct sample_output *sample_output = + wl_container_of(listener, sample_output, frame); + struct sample_state *sample = sample_output->sample; + struct wlr_output *wlr_output = sample_output->output; + + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + + long ms = (now.tv_sec - sample->last_frame.tv_sec) * 1000 + + (now.tv_nsec - sample->last_frame.tv_nsec) / 1000000; + int inc = (sample->dec + 1) % 3; + + sample->color[inc] += ms / 2000.0f; + sample->color[sample->dec] -= ms / 2000.0f; + + if (sample->color[sample->dec] < 0.0f) { + sample->color[inc] = 1.0f; + sample->color[sample->dec] = 0.0f; + sample->dec = inc; + } + + struct wlr_output_state state; + wlr_output_state_init(&state); + struct wlr_render_pass *pass = wlr_output_begin_render_pass(wlr_output, &state, NULL); + wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){ + .box = { .width = wlr_output->width, .height = wlr_output->height }, + .color = { + .r = sample->color[0], + .g = sample->color[1], + .b = sample->color[2], + .a = sample->color[3], + }, + }); + wlr_render_pass_submit(pass); + + wlr_output_commit_state(wlr_output, &state); + wlr_output_state_finish(&state); + sample->last_frame = now; +} + +static void output_remove_notify(struct wl_listener *listener, void *data) { + struct sample_output *sample_output = + wl_container_of(listener, sample_output, destroy); + wlr_log(WLR_DEBUG, "Output removed"); + wl_list_remove(&sample_output->frame.link); + wl_list_remove(&sample_output->destroy.link); + free(sample_output); +} + +static void new_output_notify(struct wl_listener *listener, void *data) { + struct wlr_output *output = data; + struct sample_state *sample = + wl_container_of(listener, sample, new_output); + + wlr_output_init_render(output, sample->allocator, sample->renderer); + + struct sample_output *sample_output = calloc(1, sizeof(*sample_output)); + sample_output->output = output; + sample_output->sample = sample; + wl_signal_add(&output->events.frame, &sample_output->frame); + sample_output->frame.notify = output_frame_notify; + wl_signal_add(&output->events.destroy, &sample_output->destroy); + sample_output->destroy.notify = output_remove_notify; + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, true); + struct wlr_output_mode *mode = wlr_output_preferred_mode(output); + if (mode != NULL) { + wlr_output_state_set_mode(&state, mode); + } + wlr_output_commit_state(output, &state); + wlr_output_state_finish(&state); +} + +static void keyboard_key_notify(struct wl_listener *listener, void *data) { + struct sample_keyboard *keyboard = wl_container_of(listener, keyboard, key); + struct sample_state *sample = keyboard->sample; + struct wlr_keyboard_key_event *event = data; + uint32_t keycode = event->keycode + 8; + const xkb_keysym_t *syms; + int nsyms = xkb_state_key_get_syms(keyboard->wlr_keyboard->xkb_state, + keycode, &syms); + for (int i = 0; i < nsyms; i++) { + xkb_keysym_t sym = syms[i]; + if (sym == XKB_KEY_Escape) { + wl_display_terminate(sample->display); + } + } +} + +static void keyboard_destroy_notify(struct wl_listener *listener, void *data) { + struct sample_keyboard *keyboard = + wl_container_of(listener, keyboard, destroy); + wl_list_remove(&keyboard->destroy.link); + wl_list_remove(&keyboard->key.link); + free(keyboard); +} + +static void new_input_notify(struct wl_listener *listener, void *data) { + struct wlr_input_device *device = data; + struct sample_state *sample = wl_container_of(listener, sample, new_input); + switch (device->type) { + case WLR_INPUT_DEVICE_KEYBOARD:; + struct sample_keyboard *keyboard = calloc(1, sizeof(*keyboard)); + keyboard->wlr_keyboard = wlr_keyboard_from_input_device(device); + keyboard->sample = sample; + wl_signal_add(&device->events.destroy, &keyboard->destroy); + keyboard->destroy.notify = keyboard_destroy_notify; + wl_signal_add(&keyboard->wlr_keyboard->events.key, &keyboard->key); + keyboard->key.notify = keyboard_key_notify; + struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + if (!context) { + wlr_log(WLR_ERROR, "Failed to create XKB context"); + exit(1); + } + struct xkb_keymap *keymap = xkb_keymap_new_from_names(context, NULL, + XKB_KEYMAP_COMPILE_NO_FLAGS); + if (!keymap) { + wlr_log(WLR_ERROR, "Failed to create XKB keymap"); + exit(1); + } + wlr_keyboard_set_keymap(keyboard->wlr_keyboard, keymap); + xkb_keymap_unref(keymap); + xkb_context_unref(context); + break; + default: + break; + } +} + +int main(void) { + wlr_log_init(WLR_DEBUG, NULL); + struct wl_display *display = wl_display_create(); + struct sample_state state = { + .color = { 1.0, 0.0, 0.0, 1.0 }, + .dec = 0, + .last_frame = { 0 }, + .display = display + }; + struct wlr_backend *backend = wlr_backend_autocreate(wl_display_get_event_loop(display), NULL); + if (!backend) { + exit(1); + } + + state.renderer = wlr_renderer_autocreate(backend); + state.allocator = wlr_allocator_autocreate(backend, state.renderer); + + wl_signal_add(&backend->events.new_output, &state.new_output); + state.new_output.notify = new_output_notify; + wl_signal_add(&backend->events.new_input, &state.new_input); + state.new_input.notify = new_input_notify; + clock_gettime(CLOCK_MONOTONIC, &state.last_frame); + + if (!wlr_backend_start(backend)) { + wlr_log(WLR_ERROR, "Failed to start backend"); + wlr_backend_destroy(backend); + exit(1); + } + wl_display_run(display); + wl_display_destroy(display); +} diff --git a/3rdparty/wlroots/examples/tablet.c b/3rdparty/wlroots/examples/tablet.c new file mode 100644 index 0000000000..78666fff7f --- /dev/null +++ b/3rdparty/wlroots/examples/tablet.c @@ -0,0 +1,416 @@ +#undef _POSIX_C_SOURCE +#define _XOPEN_SOURCE 600 // for M_PI +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct sample_state { + struct wl_display *display; + struct wlr_renderer *renderer; + struct wlr_allocator *allocator; + bool proximity, tap, button; + double distance; + double pressure; + double x, y; + double x_tilt, y_tilt; + double width_mm, height_mm; + double ring; + struct wl_list link; + float tool_color[4]; + float pad_color[4]; + struct timespec last_frame; + struct wl_listener new_output; + struct wl_listener new_input; + struct wl_list tablet_tools; + struct wl_list tablet_pads; +}; + +struct tablet_tool_state { + struct sample_state *sample; + struct wlr_tablet *wlr_tablet; + struct wl_listener destroy; + struct wl_listener axis; + struct wl_listener proximity; + struct wl_listener tip; + struct wl_listener button; + struct wl_list link; + void *data; +}; + +struct tablet_pad_state { + struct sample_state *sample; + struct wlr_tablet_pad *wlr_tablet_pad; + struct wl_listener destroy; + struct wl_listener button; + struct wl_listener ring; + struct wl_list link; + void *data; +}; + +struct sample_output { + struct sample_state *sample; + struct wlr_output *output; + struct wl_listener frame; + struct wl_listener destroy; +}; + +struct sample_keyboard { + struct sample_state *sample; + struct wlr_keyboard *wlr_keyboard; + struct wl_listener key; + struct wl_listener destroy; +}; + +static void output_frame_notify(struct wl_listener *listener, void *data) { + struct sample_output *sample_output = wl_container_of(listener, sample_output, frame); + struct sample_state *sample = sample_output->sample; + struct wlr_output *wlr_output = sample_output->output; + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + + int32_t width, height; + wlr_output_effective_resolution(wlr_output, &width, &height); + + struct wlr_output_state output_state; + wlr_output_state_init(&output_state); + struct wlr_render_pass *pass = wlr_output_begin_render_pass(wlr_output, &output_state, NULL); + + wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){ + .box = { .width = wlr_output->width, .height = wlr_output->height }, + .color = { 0.25, 0.25, 0.25, 1 }, + }); + + float distance = 0.8f * (1 - sample->distance); + float tool_color[4] = { distance, distance, distance, 1 }; + for (size_t i = 0; sample->button && i < 4; ++i) { + tool_color[i] = sample->tool_color[i]; + } + float scale = 4; + + float pad_width = sample->width_mm * scale; + float pad_height = sample->height_mm * scale; + float left = width / 2.0f - pad_width / 2.0f; + float top = height / 2.0f - pad_height / 2.0f; + wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){ + .box = { + .x = left, + .y = top, + .width = pad_width, + .height = pad_height, + }, + .color = { + sample->pad_color[0], + sample->pad_color[1], + sample->pad_color[2], + sample->pad_color[3], + }, + }); + + if (sample->proximity) { + struct wlr_box box = { + .x = (sample->x * pad_width) - 8 * (sample->pressure + 1) + left, + .y = (sample->y * pad_height) - 8 * (sample->pressure + 1) + top, + .width = 16 * (sample->pressure + 1), + .height = 16 * (sample->pressure + 1), + }; + + // TODO: use sample->ring + wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){ + .box = box, + .color = { + tool_color[0], + tool_color[1], + tool_color[2], + tool_color[3], + }, + }); + + box.x += sample->x_tilt; + box.y += sample->y_tilt; + box.width /= 2; + box.height /= 2; + wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){ + .box = box, + .color = { + tool_color[0], + tool_color[1], + tool_color[2], + tool_color[3], + }, + }); + } + + wlr_render_pass_submit(pass); + wlr_output_commit_state(wlr_output, &output_state); + wlr_output_state_finish(&output_state); + sample->last_frame = now; +} + +static void tablet_tool_axis_notify(struct wl_listener *listener, void *data) { + struct tablet_tool_state *tstate = wl_container_of(listener, tstate, axis); + struct wlr_tablet_tool_axis_event *event = data; + struct sample_state *sample = tstate->sample; + if ((event->updated_axes & WLR_TABLET_TOOL_AXIS_X)) { + sample->x = event->x; + } + if ((event->updated_axes & WLR_TABLET_TOOL_AXIS_Y)) { + sample->y = event->y; + } + if ((event->updated_axes & WLR_TABLET_TOOL_AXIS_DISTANCE)) { + sample->distance = event->distance; + } + if ((event->updated_axes & WLR_TABLET_TOOL_AXIS_PRESSURE)) { + sample->pressure = event->pressure; + } + if ((event->updated_axes & WLR_TABLET_TOOL_AXIS_TILT_X)) { + sample->x_tilt = event->tilt_x; + } + if ((event->updated_axes & WLR_TABLET_TOOL_AXIS_TILT_Y)) { + sample->y_tilt = event->tilt_y; + } +} + +static void tablet_tool_proximity_notify(struct wl_listener *listener, void *data) { + struct tablet_tool_state *tstate = wl_container_of(listener, tstate, proximity); + struct wlr_tablet_tool_proximity_event *event = data; + struct sample_state *sample = tstate->sample; + sample->proximity = event->state == WLR_TABLET_TOOL_PROXIMITY_IN; +} + +static void tablet_tool_button_notify(struct wl_listener *listener, void *data) { + struct tablet_tool_state *tstate = wl_container_of(listener, tstate, button); + struct wlr_tablet_tool_button_event *event = data; + struct sample_state *sample = tstate->sample; + if (event->state == WLR_BUTTON_RELEASED) { + sample->button = false; + } else { + sample->button = true; + for (size_t i = 0; i < 3; ++i) { + if (event->button % 3 == i) { + sample->tool_color[i] = 0; + } else { + sample->tool_color[i] = 1; + } + } + } +} + +static void tablet_pad_button_notify(struct wl_listener *listener, void *data) { + struct tablet_pad_state *pstate = wl_container_of(listener, pstate, button); + struct wlr_tablet_pad_button_event *event = data; + struct sample_state *sample = pstate->sample; + float default_color[4] = { 0.5, 0.5, 0.5, 1.0 }; + if (event->state == WLR_BUTTON_RELEASED) { + memcpy(sample->pad_color, default_color, sizeof(default_color)); + } else { + for (size_t i = 0; i < 3; ++i) { + if (event->button % 3 == i) { + sample->pad_color[i] = 0; + } else { + sample->pad_color[i] = 1; + } + } + } +} + +static void tablet_pad_ring_notify(struct wl_listener *listener, void *data) { + struct tablet_pad_state *pstate = wl_container_of(listener, pstate, ring); + struct wlr_tablet_pad_ring_event *event = data; + struct sample_state *sample = pstate->sample; + if (event->position != -1) { + sample->ring = -(event->position * (M_PI / 180.0)); + } +} + +static void tablet_tool_destroy_notify(struct wl_listener *listener, void *data) { + struct tablet_tool_state *tstate = wl_container_of(listener, tstate, destroy); + wl_list_remove(&tstate->link); + wl_list_remove(&tstate->destroy.link); + wl_list_remove(&tstate->axis.link); + wl_list_remove(&tstate->proximity.link); + wl_list_remove(&tstate->button.link); + free(tstate); +} + +static void tablet_pad_destroy_notify(struct wl_listener *listener, void *data) { + struct tablet_pad_state *pstate = wl_container_of(listener, pstate, destroy); + wl_list_remove(&pstate->link); + wl_list_remove(&pstate->destroy.link); + wl_list_remove(&pstate->ring.link); + wl_list_remove(&pstate->button.link); + free(pstate); +} + +static void output_remove_notify(struct wl_listener *listener, void *data) { + struct sample_output *sample_output = wl_container_of(listener, sample_output, destroy); + wl_list_remove(&sample_output->frame.link); + wl_list_remove(&sample_output->destroy.link); + free(sample_output); +} + +static void new_output_notify(struct wl_listener *listener, void *data) { + struct wlr_output *output = data; + struct sample_state *sample = wl_container_of(listener, sample, new_output); + + wlr_output_init_render(output, sample->allocator, sample->renderer); + + struct sample_output *sample_output = calloc(1, sizeof(*sample_output)); + sample_output->output = output; + sample_output->sample = sample; + wl_signal_add(&output->events.frame, &sample_output->frame); + sample_output->frame.notify = output_frame_notify; + wl_signal_add(&output->events.destroy, &sample_output->destroy); + sample_output->destroy.notify = output_remove_notify; + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, true); + struct wlr_output_mode *mode = wlr_output_preferred_mode(output); + if (mode != NULL) { + wlr_output_state_set_mode(&state, mode); + } + wlr_output_commit_state(output, &state); + wlr_output_state_finish(&state); +} + +static void keyboard_key_notify(struct wl_listener *listener, void *data) { + struct sample_keyboard *keyboard = wl_container_of(listener, keyboard, key); + struct sample_state *sample = keyboard->sample; + struct wlr_keyboard_key_event *event = data; + uint32_t keycode = event->keycode + 8; + const xkb_keysym_t *syms; + int nsyms = xkb_state_key_get_syms(keyboard->wlr_keyboard->xkb_state, + keycode, &syms); + for (int i = 0; i < nsyms; i++) { + xkb_keysym_t sym = syms[i]; + if (sym == XKB_KEY_Escape) { + wl_display_terminate(sample->display); + } + } +} + +static void keyboard_destroy_notify(struct wl_listener *listener, void *data) { + struct sample_keyboard *keyboard = wl_container_of(listener, keyboard, destroy); + wl_list_remove(&keyboard->destroy.link); + wl_list_remove(&keyboard->key.link); + free(keyboard); +} + +static void new_input_notify(struct wl_listener *listener, void *data) { + struct wlr_input_device *device = data; + struct sample_state *sample = wl_container_of(listener, sample, new_input); + switch (device->type) { + case WLR_INPUT_DEVICE_KEYBOARD:; + struct sample_keyboard *keyboard = calloc(1, sizeof(*keyboard)); + keyboard->wlr_keyboard = wlr_keyboard_from_input_device(device); + keyboard->sample = sample; + wl_signal_add(&device->events.destroy, &keyboard->destroy); + keyboard->destroy.notify = keyboard_destroy_notify; + wl_signal_add(&keyboard->wlr_keyboard->events.key, &keyboard->key); + keyboard->key.notify = keyboard_key_notify; + struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + if (!context) { + wlr_log(WLR_ERROR, "Failed to create XKB context"); + exit(1); + } + struct xkb_keymap *keymap = xkb_keymap_new_from_names(context, NULL, + XKB_KEYMAP_COMPILE_NO_FLAGS); + if (!keymap) { + wlr_log(WLR_ERROR, "Failed to create XKB keymap"); + exit(1); + } + wlr_keyboard_set_keymap(keyboard->wlr_keyboard, keymap); + xkb_keymap_unref(keymap); + xkb_context_unref(context); + break; + case WLR_INPUT_DEVICE_TABLET_PAD:; + struct tablet_pad_state *pstate = calloc(1, sizeof(*pstate)); + pstate->wlr_tablet_pad = wlr_tablet_pad_from_input_device(device); + pstate->sample = sample; + pstate->destroy.notify = tablet_pad_destroy_notify; + wl_signal_add(&device->events.destroy, &pstate->destroy); + pstate->button.notify = tablet_pad_button_notify; + wl_signal_add(&pstate->wlr_tablet_pad->events.button, &pstate->button); + pstate->ring.notify = tablet_pad_ring_notify; + wl_signal_add(&pstate->wlr_tablet_pad->events.ring, &pstate->ring); + wl_list_insert(&sample->tablet_pads, &pstate->link); + break; + case WLR_INPUT_DEVICE_TABLET:; + struct wlr_tablet *tablet = wlr_tablet_from_input_device(device); + sample->width_mm = tablet->width_mm == 0 ? + 20 : tablet->width_mm; + sample->height_mm = tablet->height_mm == 0 ? + 10 : tablet->height_mm; + + struct tablet_tool_state *tstate = calloc(1, sizeof(*tstate)); + tstate->wlr_tablet = tablet; + tstate->sample = sample; + tstate->destroy.notify = tablet_tool_destroy_notify; + wl_signal_add(&device->events.destroy, &tstate->destroy); + tstate->axis.notify = tablet_tool_axis_notify; + wl_signal_add(&tablet->events.axis, &tstate->axis); + tstate->proximity.notify = tablet_tool_proximity_notify; + wl_signal_add(&tablet->events.proximity, &tstate->proximity); + tstate->button.notify = tablet_tool_button_notify; + wl_signal_add(&tablet->events.button, &tstate->button); + wl_list_insert(&sample->tablet_tools, &tstate->link); + break; + default: + break; + } +} + +int main(int argc, char *argv[]) { + wlr_log_init(WLR_DEBUG, NULL); + struct wl_display *display = wl_display_create(); + struct sample_state state = { + .display = display, + .tool_color = { 1, 1, 1, 1 }, + .pad_color = { 0.5, 0.5, 0.5, 1.0 } + }; + wl_list_init(&state.tablet_pads); + wl_list_init(&state.tablet_tools); + struct wlr_backend *wlr = wlr_backend_autocreate(wl_display_get_event_loop(display), NULL); + if (!wlr) { + exit(1); + } + + wl_signal_add(&wlr->events.new_output, &state.new_output); + state.new_output.notify = new_output_notify; + wl_signal_add(&wlr->events.new_input, &state.new_input); + state.new_input.notify = new_input_notify; + clock_gettime(CLOCK_MONOTONIC, &state.last_frame); + + state.renderer = wlr_renderer_autocreate(wlr); + if (!state.renderer) { + wlr_log(WLR_ERROR, "Could not start compositor, OOM"); + exit(EXIT_FAILURE); + } + + state.allocator = wlr_allocator_autocreate(wlr, state.renderer); + + if (!wlr_backend_start(wlr)) { + wlr_log(WLR_ERROR, "Failed to start backend"); + wlr_backend_destroy(wlr); + exit(1); + } + wl_display_run(display); + + wl_display_destroy(display); +} diff --git a/3rdparty/wlroots/examples/touch.c b/3rdparty/wlroots/examples/touch.c new file mode 100644 index 0000000000..b891837a4e --- /dev/null +++ b/3rdparty/wlroots/examples/touch.c @@ -0,0 +1,311 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "cat.h" + +struct sample_state { + struct wl_display *display; + struct wlr_renderer *renderer; + struct wlr_allocator *allocator; + struct wlr_texture *cat_texture; + struct wl_list touch_points; + struct timespec last_frame; + struct wl_listener new_output; + struct wl_listener new_input; + struct wl_list touch; +}; + +struct touch_point { + int32_t touch_id; + double x, y; + struct wl_list link; +}; + +struct touch_state { + struct sample_state *sample; + struct wlr_touch *wlr_touch; + struct wl_listener destroy; + struct wl_listener down; + struct wl_listener up; + struct wl_listener motion; + struct wl_listener cancel; + struct wl_list link; + void *data; +}; + +struct sample_output { + struct sample_state *sample; + struct wlr_output *output; + struct wl_listener frame; + struct wl_listener destroy; +}; + +struct sample_keyboard { + struct sample_state *sample; + struct wlr_keyboard *wlr_keyboard; + struct wl_listener key; + struct wl_listener destroy; +}; + +static void output_frame_notify(struct wl_listener *listener, void *data) { + struct sample_output *sample_output = wl_container_of(listener, sample_output, frame); + struct sample_state *sample = sample_output->sample; + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + + struct wlr_output *wlr_output = sample_output->output; + + int32_t width, height; + wlr_output_effective_resolution(wlr_output, &width, &height); + + struct wlr_output_state output_state; + wlr_output_state_init(&output_state); + struct wlr_render_pass *pass = wlr_output_begin_render_pass(wlr_output, &output_state, NULL); + wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){ + .box = { .width = width, .height = height }, + .color = { 0.25, 0.25, 0.25, 1 }, + }); + + struct touch_point *p; + wl_list_for_each(p, &sample->touch_points, link) { + int x = (int)(p->x * width) - sample->cat_texture->width / 2; + int y = (int)(p->y * height) - sample->cat_texture->height / 2; + wlr_render_pass_add_texture(pass, &(struct wlr_render_texture_options){ + .texture = sample->cat_texture, + .dst_box = { .x = x, .y = y }, + }); + } + + wlr_render_pass_submit(pass); + wlr_output_commit_state(wlr_output, &output_state); + wlr_output_state_finish(&output_state); + sample->last_frame = now; +} + +static void touch_down_notify(struct wl_listener *listener, void *data) { + struct wlr_touch_down_event *event = data; + struct touch_state *tstate = wl_container_of(listener, tstate, down); + struct sample_state *sample = tstate->sample; + struct touch_point *point = calloc(1, sizeof(*point)); + point->touch_id = event->touch_id; + point->x = event->x; + point->y = event->y; + wl_list_insert(&sample->touch_points, &point->link); +} + +static void touch_up_notify(struct wl_listener *listener, void *data ) { + struct wlr_touch_up_event *event = data; + struct touch_state *tstate = wl_container_of(listener, tstate, up); + struct sample_state *sample = tstate->sample; + struct touch_point *point, *tmp; + wl_list_for_each_safe(point, tmp, &sample->touch_points, link) { + if (point->touch_id == event->touch_id) { + wl_list_remove(&point->link); + break; + } + } +} + +static void touch_motion_notify(struct wl_listener *listener, void *data) { + struct wlr_touch_motion_event *event = data; + struct touch_state *tstate = wl_container_of(listener, tstate, motion); + struct sample_state *sample = tstate->sample; + struct touch_point *point; + wl_list_for_each(point, &sample->touch_points, link) { + if (point->touch_id == event->touch_id) { + point->x = event->x; + point->y = event->y; + break; + } + } +} + +static void touch_cancel_notify(struct wl_listener *listener, void *data) { + struct wlr_touch_cancel_event *event = data; + struct touch_state *tstate = wl_container_of(listener, tstate, cancel); + struct sample_state *sample = tstate->sample; + struct touch_point *point, *tmp; + wl_list_for_each_safe(point, tmp, &sample->touch_points, link) { + if (point->touch_id == event->touch_id) { + wl_list_remove(&point->link); + break; + } + } +} + +static void touch_destroy_notify(struct wl_listener *listener, void *data) { + struct touch_state *tstate = wl_container_of(listener, tstate, destroy); + wl_list_remove(&tstate->link); + wl_list_remove(&tstate->destroy.link); + wl_list_remove(&tstate->down.link); + wl_list_remove(&tstate->up.link); + wl_list_remove(&tstate->motion.link); + wl_list_remove(&tstate->cancel.link); + free(tstate); +} + +static void output_remove_notify(struct wl_listener *listener, void *data) { + struct sample_output *sample_output = wl_container_of(listener, sample_output, destroy); + wl_list_remove(&sample_output->frame.link); + wl_list_remove(&sample_output->destroy.link); + free(sample_output); +} + +static void new_output_notify(struct wl_listener *listener, void *data) { + struct wlr_output *output = data; + struct sample_state *sample = wl_container_of(listener, sample, new_output); + + wlr_output_init_render(output, sample->allocator, sample->renderer); + + struct sample_output *sample_output = calloc(1, sizeof(*sample_output)); + sample_output->output = output; + sample_output->sample = sample; + wl_signal_add(&output->events.frame, &sample_output->frame); + sample_output->frame.notify = output_frame_notify; + wl_signal_add(&output->events.destroy, &sample_output->destroy); + sample_output->destroy.notify = output_remove_notify; + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, true); + struct wlr_output_mode *mode = wlr_output_preferred_mode(output); + if (mode != NULL) { + wlr_output_state_set_mode(&state, mode); + } + wlr_output_commit_state(output, &state); + wlr_output_state_finish(&state); +} + +static void keyboard_key_notify(struct wl_listener *listener, void *data) { + struct sample_keyboard *keyboard = wl_container_of(listener, keyboard, key); + struct sample_state *sample = keyboard->sample; + struct wlr_keyboard_key_event *event = data; + uint32_t keycode = event->keycode + 8; + const xkb_keysym_t *syms; + int nsyms = xkb_state_key_get_syms(keyboard->wlr_keyboard->xkb_state, + keycode, &syms); + for (int i = 0; i < nsyms; i++) { + xkb_keysym_t sym = syms[i]; + if (sym == XKB_KEY_Escape) { + wl_display_terminate(sample->display); + } + } +} + +static void keyboard_destroy_notify(struct wl_listener *listener, void *data) { + struct sample_keyboard *keyboard = wl_container_of(listener, keyboard, destroy); + wl_list_remove(&keyboard->destroy.link); + wl_list_remove(&keyboard->key.link); + free(keyboard); +} + +static void new_input_notify(struct wl_listener *listener, void *data) { + struct wlr_input_device *device = data; + struct sample_state *sample = wl_container_of(listener, sample, new_input); + switch (device->type) { + case WLR_INPUT_DEVICE_KEYBOARD:; + struct sample_keyboard *keyboard = calloc(1, sizeof(*keyboard)); + keyboard->wlr_keyboard = wlr_keyboard_from_input_device(device); + keyboard->sample = sample; + wl_signal_add(&device->events.destroy, &keyboard->destroy); + keyboard->destroy.notify = keyboard_destroy_notify; + wl_signal_add(&keyboard->wlr_keyboard->events.key, &keyboard->key); + keyboard->key.notify = keyboard_key_notify; + struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + if (!context) { + wlr_log(WLR_ERROR, "Failed to create XKB context"); + exit(1); + } + struct xkb_keymap *keymap = xkb_keymap_new_from_names(context, NULL, + XKB_KEYMAP_COMPILE_NO_FLAGS); + if (!keymap) { + wlr_log(WLR_ERROR, "Failed to create XKB keymap"); + exit(1); + } + wlr_keyboard_set_keymap(keyboard->wlr_keyboard, keymap); + xkb_keymap_unref(keymap); + xkb_context_unref(context); + break; + case WLR_INPUT_DEVICE_TOUCH:; + struct touch_state *tstate = calloc(1, sizeof(*tstate)); + tstate->wlr_touch = wlr_touch_from_input_device(device); + tstate->sample = sample; + tstate->destroy.notify = touch_destroy_notify; + wl_signal_add(&device->events.destroy, &tstate->destroy); + tstate->down.notify = touch_down_notify; + wl_signal_add(&tstate->wlr_touch->events.down, &tstate->down); + tstate->motion.notify = touch_motion_notify; + wl_signal_add(&tstate->wlr_touch->events.motion, &tstate->motion); + tstate->up.notify = touch_up_notify; + wl_signal_add(&tstate->wlr_touch->events.up, &tstate->up); + tstate->cancel.notify = touch_cancel_notify; + wl_signal_add(&tstate->wlr_touch->events.cancel, &tstate->cancel); + wl_list_insert(&sample->touch, &tstate->link); + break; + default: + break; + } +} + + +int main(int argc, char *argv[]) { + wlr_log_init(WLR_DEBUG, NULL); + struct wl_display *display = wl_display_create(); + struct sample_state state = { + .display = display + }; + wl_list_init(&state.touch_points); + wl_list_init(&state.touch); + + struct wlr_backend *wlr = wlr_backend_autocreate(wl_display_get_event_loop(display), NULL); + if (!wlr) { + exit(1); + } + + wl_signal_add(&wlr->events.new_output, &state.new_output); + state.new_output.notify = new_output_notify; + wl_signal_add(&wlr->events.new_input, &state.new_input); + state.new_input.notify = new_input_notify; + clock_gettime(CLOCK_MONOTONIC, &state.last_frame); + + state.renderer = wlr_renderer_autocreate(wlr); + if (!state.renderer) { + wlr_log(WLR_ERROR, "Could not start compositor, OOM"); + exit(EXIT_FAILURE); + } + state.cat_texture = wlr_texture_from_pixels(state.renderer, + DRM_FORMAT_ARGB8888, cat_tex.width * 4, cat_tex.width, cat_tex.height, + cat_tex.pixel_data); + if (!state.cat_texture) { + wlr_log(WLR_ERROR, "Could not start compositor, OOM"); + exit(EXIT_FAILURE); + } + + state.allocator = wlr_allocator_autocreate(wlr, state.renderer); + + if (!wlr_backend_start(wlr)) { + wlr_log(WLR_ERROR, "Failed to start backend"); + wlr_backend_destroy(wlr); + exit(1); + } + wl_display_run(display); + + wlr_texture_destroy(state.cat_texture); + wl_display_destroy(display); +} diff --git a/3rdparty/wlroots/include/backend/drm/drm.h b/3rdparty/wlroots/include/backend/drm/drm.h new file mode 100644 index 0000000000..a8c5e077ab --- /dev/null +++ b/3rdparty/wlroots/include/backend/drm/drm.h @@ -0,0 +1,265 @@ +#ifndef BACKEND_DRM_DRM_H +#define BACKEND_DRM_DRM_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "backend/drm/iface.h" +#include "backend/drm/properties.h" +#include "backend/drm/renderer.h" + +struct wlr_drm_viewport { + struct wlr_fbox src_box; + struct wlr_box dst_box; +}; + +struct wlr_drm_plane { + uint32_t type; + uint32_t id; + + /* Only initialized on multi-GPU setups */ + struct wlr_drm_surface mgpu_surf; + + /* Buffer submitted to the kernel, will be presented on next vblank */ + struct wlr_drm_fb *queued_fb; + struct wlr_drm_syncobj_timeline *queued_release_timeline; + uint64_t queued_release_point; + /* Buffer currently displayed on screen */ + struct wlr_drm_fb *current_fb; + struct wlr_drm_syncobj_timeline *current_release_timeline; + uint64_t current_release_point; + /* Viewport belonging to the last committed fb */ + struct wlr_drm_viewport viewport; + + struct wlr_drm_format_set formats; + + struct wlr_output_cursor_size *cursor_sizes; + size_t cursor_sizes_len; + + struct wlr_drm_plane_props props; + + uint32_t initial_crtc_id; + struct liftoff_plane *liftoff; + struct liftoff_layer *liftoff_layer; +}; + +struct wlr_drm_layer { + struct wlr_output_layer *wlr; + struct liftoff_layer *liftoff; + struct wlr_addon addon; // wlr_output_layer.addons + struct wl_list link; // wlr_drm_crtc.layers + + /* Buffer to be submitted to the kernel on the next page-flip */ + struct wlr_drm_fb *pending_fb; + /* Buffer submitted to the kernel, will be presented on next vblank */ + struct wlr_drm_fb *queued_fb; + /* Buffer currently displayed on screen */ + struct wlr_drm_fb *current_fb; + + // One entry per wlr_drm_backend.planes + bool *candidate_planes; +}; + +struct wlr_drm_crtc { + uint32_t id; + struct wlr_drm_lease *lease; + struct liftoff_output *liftoff; + struct liftoff_layer *liftoff_composition_layer; + struct wl_list layers; // wlr_drm_layer.link + + // Atomic modesetting only + bool own_mode_id; + uint32_t mode_id; + uint32_t gamma_lut; + + // Legacy only + int legacy_gamma_size; + + struct wlr_drm_plane *primary; + struct wlr_drm_plane *cursor; + + struct wlr_drm_crtc_props props; +}; + +struct wlr_drm_backend { + struct wlr_backend backend; + + struct wlr_drm_backend *parent; + const struct wlr_drm_interface *iface; + bool addfb2_modifiers; + + int fd; + char *name; + struct wlr_device *dev; + struct liftoff_device *liftoff; + + size_t num_crtcs; + struct wlr_drm_crtc *crtcs; + + size_t num_planes; + struct wlr_drm_plane *planes; + + struct wl_event_source *drm_event; + + struct wl_listener session_destroy; + struct wl_listener session_active; + struct wl_listener parent_destroy; + struct wl_listener dev_change; + struct wl_listener dev_remove; + + struct wl_list fbs; // wlr_drm_fb.link + struct wl_list connectors; // wlr_drm_connector.link + + struct wl_list page_flips; // wlr_drm_page_flip.link + + /* Only initialized on multi-GPU setups */ + struct wlr_drm_renderer mgpu_renderer; + + struct wlr_session *session; + + uint64_t cursor_width, cursor_height; + + struct wlr_drm_format_set mgpu_formats; + + bool supports_tearing_page_flips; +}; + +struct wlr_drm_mode { + struct wlr_output_mode wlr_mode; + drmModeModeInfo drm_mode; +}; + +struct wlr_drm_device_state { + bool modeset; + bool nonblock; + + struct wlr_drm_connector_state *connectors; + size_t connectors_len; +}; + +struct wlr_drm_connector_state { + struct wlr_drm_connector *connector; + const struct wlr_output_state *base; + bool active; + drmModeModeInfo mode; + struct wlr_drm_fb *primary_fb; + struct wlr_drm_viewport primary_viewport; + struct wlr_drm_fb *cursor_fb; + + struct wlr_drm_syncobj_timeline *wait_timeline; + uint64_t wait_point; + + // used by atomic + uint32_t mode_id; + uint32_t gamma_lut; + uint32_t fb_damage_clips; + int primary_in_fence_fd; + bool vrr_enabled; + uint32_t colorspace; + uint32_t hdr_output_metadata; +}; + +/** + * Per-page-flip tracking struct. + * + * We've asked for a state change in the kernel, and yet to receive a + * notification for its completion. Currently, the kernel only has a queue + * length of 1, and no way to modify your submissions after they're sent. + * + * However, we might have multiple in-flight page-flip events, for instance + * when performing a non-blocking commit followed by a blocking commit. In + * that case, conn will be set to NULL on the non-blocking commit to indicate + * that it's been superseded. + */ +struct wlr_drm_page_flip { + struct wl_list link; // wlr_drm_connector.page_flips + struct wlr_drm_page_flip_connector *connectors; + size_t connectors_len; + // True if DRM_MODE_PAGE_FLIP_ASYNC was set + bool async; +}; + +struct wlr_drm_page_flip_connector { + uint32_t crtc_id; + struct wlr_drm_connector *connector; // may be NULL +}; + +struct wlr_drm_connector { + struct wlr_output output; // only valid if status != DISCONNECTED + + struct wlr_drm_backend *backend; + char name[24]; + drmModeConnection status; + uint32_t id; + uint64_t max_bpc_bounds[2]; + struct wlr_drm_lease *lease; + + struct wlr_drm_crtc *crtc; + uint32_t possible_crtcs; + + struct wlr_drm_connector_props props; + + bool cursor_enabled; + int cursor_x, cursor_y; + int cursor_width, cursor_height; + int cursor_hotspot_x, cursor_hotspot_y; + /* Buffer to be submitted to the kernel on the next page-flip */ + struct wlr_drm_fb *cursor_pending_fb; + + struct wl_list link; // wlr_drm_backend.connectors + + // Last committed page-flip + struct wlr_drm_page_flip *pending_page_flip; + + // Atomic modesetting only + uint32_t colorspace; + uint32_t hdr_output_metadata; + + int32_t refresh; +}; + +struct wlr_drm_backend *get_drm_backend_from_backend( + struct wlr_backend *wlr_backend); +bool check_drm_features(struct wlr_drm_backend *drm); +bool init_drm_resources(struct wlr_drm_backend *drm); +void finish_drm_resources(struct wlr_drm_backend *drm); +void scan_drm_connectors(struct wlr_drm_backend *state, + struct wlr_device_hotplug_event *event); +void scan_drm_leases(struct wlr_drm_backend *drm); +bool commit_drm_device(struct wlr_drm_backend *drm, + const struct wlr_backend_output_state *states, size_t states_len, bool test_only); +int handle_drm_event(int fd, uint32_t mask, void *data); +void destroy_drm_connector(struct wlr_drm_connector *conn); +bool drm_connector_is_cursor_visible(struct wlr_drm_connector *conn); +size_t drm_crtc_get_gamma_lut_size(struct wlr_drm_backend *drm, + struct wlr_drm_crtc *crtc); +void drm_lease_destroy(struct wlr_drm_lease *lease); +void drm_page_flip_destroy(struct wlr_drm_page_flip *page_flip); + +struct wlr_drm_layer *get_drm_layer(struct wlr_drm_backend *drm, + struct wlr_output_layer *layer); + +#if __STDC_VERSION__ >= 202311L + +#define wlr_drm_conn_log(conn, verb, fmt, ...) \ + wlr_log(verb, "connector %s: " fmt, conn->name __VA_OPT__(,) __VA_ARGS__) +#define wlr_drm_conn_log_errno(conn, verb, fmt, ...) \ + wlr_log_errno(verb, "connector %s: " fmt, conn->name __VA_OPT__(,) __VA_ARGS__) + +#else + +#define wlr_drm_conn_log(conn, verb, fmt, ...) \ + wlr_log(verb, "connector %s: " fmt, conn->name, ##__VA_ARGS__) +#define wlr_drm_conn_log_errno(conn, verb, fmt, ...) \ + wlr_log_errno(verb, "connector %s: " fmt, conn->name, ##__VA_ARGS__) + +#endif + +#endif diff --git a/3rdparty/wlroots/include/backend/drm/fb.h b/3rdparty/wlroots/include/backend/drm/fb.h new file mode 100644 index 0000000000..e8d328e979 --- /dev/null +++ b/3rdparty/wlroots/include/backend/drm/fb.h @@ -0,0 +1,28 @@ +#ifndef BACKEND_DRM_FB_H +#define BACKEND_DRM_FB_H + +#include +#include +#include + +struct wlr_drm_format_set; + +struct wlr_drm_fb { + struct wlr_buffer *wlr_buf; + struct wlr_addon addon; + struct wlr_drm_backend *backend; + struct wl_list link; // wlr_drm_backend.fbs + + uint32_t id; +}; + +bool drm_fb_import(struct wlr_drm_fb **fb, struct wlr_drm_backend *drm, + struct wlr_buffer *buf, const struct wlr_drm_format_set *formats); +void drm_fb_destroy(struct wlr_drm_fb *fb); + +void drm_fb_clear(struct wlr_drm_fb **fb); +void drm_fb_copy(struct wlr_drm_fb **new, struct wlr_drm_fb *old); +void drm_fb_move(struct wlr_drm_fb **new, struct wlr_drm_fb **old); +struct wlr_drm_fb *drm_fb_lock(struct wlr_drm_fb *fb); + +#endif diff --git a/3rdparty/wlroots/include/backend/drm/iface.h b/3rdparty/wlroots/include/backend/drm/iface.h new file mode 100644 index 0000000000..bc96105890 --- /dev/null +++ b/3rdparty/wlroots/include/backend/drm/iface.h @@ -0,0 +1,43 @@ +#ifndef BACKEND_DRM_IFACE_H +#define BACKEND_DRM_IFACE_H + +#include +#include +#include +#include +#include + +struct wlr_drm_backend; +struct wlr_drm_connector; +struct wlr_drm_crtc; +struct wlr_drm_device_state; +struct wlr_drm_connector_state; +struct wlr_drm_fb; +struct wlr_drm_page_flip; + +// Used to provide atomic or legacy DRM functions +struct wlr_drm_interface { + bool (*init)(struct wlr_drm_backend *drm); + void (*finish)(struct wlr_drm_backend *drm); + bool (*commit)(struct wlr_drm_backend *drm, + const struct wlr_drm_device_state *state, + struct wlr_drm_page_flip *page_flip, uint32_t flags, bool test_only); +}; + +extern const struct wlr_drm_interface atomic_iface; +extern const struct wlr_drm_interface legacy_iface; +extern const struct wlr_drm_interface liftoff_iface; + +bool drm_legacy_crtc_set_gamma(struct wlr_drm_backend *drm, + struct wlr_drm_crtc *crtc, size_t size, uint16_t *lut); + +bool create_fb_damage_clips_blob(struct wlr_drm_backend *drm, + int width, int height, const pixman_region32_t *damage, uint32_t *blob_id); +bool drm_atomic_reset(struct wlr_drm_backend *drm); + +bool drm_atomic_connector_prepare(struct wlr_drm_connector_state *state, + bool modeset); +void drm_atomic_connector_apply_commit(struct wlr_drm_connector_state *state); +void drm_atomic_connector_rollback_commit(struct wlr_drm_connector_state *state); + +#endif diff --git a/3rdparty/wlroots/include/backend/drm/monitor.h b/3rdparty/wlroots/include/backend/drm/monitor.h new file mode 100644 index 0000000000..518171932e --- /dev/null +++ b/3rdparty/wlroots/include/backend/drm/monitor.h @@ -0,0 +1,24 @@ +#ifndef BACKEND_DRM_MONITOR_H +#define BACKEND_DRM_MONITOR_H + +#include + +/** + * Helper to create new DRM sub-backends on GPU hotplug. + */ +struct wlr_drm_backend_monitor { + struct wlr_backend *multi; + struct wlr_backend *primary_drm; + struct wlr_session *session; + + struct wl_listener multi_destroy; + struct wl_listener primary_drm_destroy; + struct wl_listener session_destroy; + struct wl_listener session_add_drm_card; +}; + +struct wlr_drm_backend_monitor *drm_backend_monitor_create( + struct wlr_backend *multi, struct wlr_backend *primary_drm, + struct wlr_session *session); + +#endif diff --git a/3rdparty/wlroots/include/backend/drm/properties.h b/3rdparty/wlroots/include/backend/drm/properties.h new file mode 100644 index 0000000000..c02d655baf --- /dev/null +++ b/3rdparty/wlroots/include/backend/drm/properties.h @@ -0,0 +1,82 @@ +#ifndef BACKEND_DRM_PROPERTIES_H +#define BACKEND_DRM_PROPERTIES_H + +#include +#include +#include + +/* + * These types contain the property ids for several DRM objects. + * For more details, see: + * https://dri.freedesktop.org/docs/drm/gpu/drm-kms.html#kms-properties + */ + +struct wlr_drm_connector_props { + uint32_t edid; + uint32_t dpms; + uint32_t link_status; // not guaranteed to exist + uint32_t path; + uint32_t vrr_capable; // not guaranteed to exist + uint32_t subconnector; // not guaranteed to exist + uint32_t non_desktop; + uint32_t panel_orientation; // not guaranteed to exist + uint32_t content_type; // not guaranteed to exist + uint32_t max_bpc; // not guaranteed to exist + + // atomic-modesetting only + + uint32_t crtc_id; + uint32_t colorspace; + uint32_t hdr_output_metadata; +}; + +struct wlr_drm_crtc_props { + // Neither of these are guaranteed to exist + uint32_t vrr_enabled; + uint32_t gamma_lut; + uint32_t gamma_lut_size; + + // atomic-modesetting only + + uint32_t active; + uint32_t mode_id; + uint32_t out_fence_ptr; +}; + +struct wlr_drm_plane_props { + uint32_t type; + uint32_t rotation; // Not guaranteed to exist + uint32_t in_formats; // Not guaranteed to exist + uint32_t size_hints; // Not guaranteed to exist + + // atomic-modesetting only + + uint32_t src_x; + uint32_t src_y; + uint32_t src_w; + uint32_t src_h; + uint32_t crtc_x; + uint32_t crtc_y; + uint32_t crtc_w; + uint32_t crtc_h; + uint32_t fb_id; + uint32_t crtc_id; + uint32_t fb_damage_clips; + uint32_t hotspot_x; + uint32_t hotspot_y; + uint32_t in_fence_fd; +}; + +bool get_drm_connector_props(int fd, uint32_t id, + struct wlr_drm_connector_props *out); +bool get_drm_crtc_props(int fd, uint32_t id, struct wlr_drm_crtc_props *out); +bool get_drm_plane_props(int fd, uint32_t id, struct wlr_drm_plane_props *out); + +bool get_drm_prop(int fd, uint32_t obj, uint32_t prop, uint64_t *ret); +void *get_drm_prop_blob(int fd, uint32_t obj, uint32_t prop, size_t *ret_len); +char *get_drm_prop_enum(int fd, uint32_t obj, uint32_t prop); + +bool introspect_drm_prop_range(int fd, uint32_t prop_id, + uint64_t *min, uint64_t *max); + +#endif diff --git a/3rdparty/wlroots/include/backend/drm/renderer.h b/3rdparty/wlroots/include/backend/drm/renderer.h new file mode 100644 index 0000000000..2cf98fdb9e --- /dev/null +++ b/3rdparty/wlroots/include/backend/drm/renderer.h @@ -0,0 +1,44 @@ +#ifndef BACKEND_DRM_RENDERER_H +#define BACKEND_DRM_RENDERER_H + +#include +#include +#include +#include +#include + +struct wlr_drm_backend; +struct wlr_drm_format; +struct wlr_drm_plane; +struct wlr_buffer; + +struct wlr_drm_renderer { + struct wlr_renderer *wlr_rend; + struct wlr_allocator *allocator; +}; + +struct wlr_drm_surface { + struct wlr_drm_renderer *renderer; + struct wlr_swapchain *swapchain; + + struct wlr_drm_syncobj_timeline *timeline; + uint64_t point; +}; + +bool init_drm_renderer(struct wlr_drm_backend *drm, + struct wlr_drm_renderer *renderer); +void finish_drm_renderer(struct wlr_drm_renderer *renderer); + +bool init_drm_surface(struct wlr_drm_surface *surf, + struct wlr_drm_renderer *renderer, int width, int height, + const struct wlr_drm_format *drm_format); +void finish_drm_surface(struct wlr_drm_surface *surf); + +struct wlr_buffer *drm_surface_blit(struct wlr_drm_surface *surf, + struct wlr_buffer *buffer, + struct wlr_drm_syncobj_timeline *wait_timeline, uint64_t wait_point); + +bool drm_plane_pick_render_format(struct wlr_drm_plane *plane, + struct wlr_drm_format *fmt, struct wlr_drm_renderer *renderer); + +#endif diff --git a/3rdparty/wlroots/include/backend/drm/util.h b/3rdparty/wlroots/include/backend/drm/util.h new file mode 100644 index 0000000000..9ba5f435ee --- /dev/null +++ b/3rdparty/wlroots/include/backend/drm/util.h @@ -0,0 +1,41 @@ +#ifndef BACKEND_DRM_UTIL_H +#define BACKEND_DRM_UTIL_H + +#include +#include +#include + +struct wlr_drm_connector; + +// Calculates a more accurate refresh rate (mHz) than what mode itself provides +int32_t calculate_refresh_rate(const drmModeModeInfo *mode); +enum wlr_output_mode_aspect_ratio get_picture_aspect_ratio(const drmModeModeInfo *mode); +// Returns manufacturer based on pnp id +const char *get_pnp_manufacturer(const char code[static 3]); +// Populates the make/model/phys_{width,height} of output from the edid data +void parse_edid(struct wlr_drm_connector *conn, size_t len, const uint8_t *data); +const char *drm_connector_status_str(drmModeConnection status); +void generate_cvt_mode(drmModeModeInfo *mode, int hdisplay, int vdisplay, + float vrefresh); + +// Part of match_connectors_with_crtcs +#define UNMATCHED ((uint32_t)-1) + +/** + * Tries to match DRM connectors with DRM CRTCs. + * + * conns contains an array of bitmasks describing compatible CRTCs. For + * instance bit 0 set in an connector element means that it's compatible with + * CRTC 0. + * + * prev_crtcs contains connector indices each CRTC was previously matched with, + * or UNMATCHED. + * + * new_crtcs is populated with the new connector indices. + */ +void match_connectors_with_crtcs(size_t num_conns, + const uint32_t conns[static restrict num_conns], + size_t num_crtcs, const uint32_t prev_crtcs[static restrict num_crtcs], + uint32_t new_crtcs[static restrict num_crtcs]); + +#endif diff --git a/3rdparty/wlroots/include/backend/headless.h b/3rdparty/wlroots/include/backend/headless.h new file mode 100644 index 0000000000..21df86ea6f --- /dev/null +++ b/3rdparty/wlroots/include/backend/headless.h @@ -0,0 +1,30 @@ +#ifndef BACKEND_HEADLESS_H +#define BACKEND_HEADLESS_H + +#include +#include + +#define HEADLESS_DEFAULT_REFRESH (60 * 1000) // 60 Hz + +struct wlr_headless_backend { + struct wlr_backend backend; + struct wl_event_loop *event_loop; + struct wl_list outputs; + struct wl_listener event_loop_destroy; + bool started; +}; + +struct wlr_headless_output { + struct wlr_output wlr_output; + + struct wlr_headless_backend *backend; + struct wl_list link; + + struct wl_event_source *frame_timer; + int frame_delay; // ms +}; + +struct wlr_headless_backend *headless_backend_from_backend( + struct wlr_backend *wlr_backend); + +#endif diff --git a/3rdparty/wlroots/include/backend/libinput.h b/3rdparty/wlroots/include/backend/libinput.h new file mode 100644 index 0000000000..e7123884e0 --- /dev/null +++ b/3rdparty/wlroots/include/backend/libinput.h @@ -0,0 +1,137 @@ +#ifndef BACKEND_LIBINPUT_H +#define BACKEND_LIBINPUT_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct wlr_libinput_backend { + struct wlr_backend backend; + + struct wlr_session *session; + + struct libinput *libinput_context; + struct wl_event_source *input_event; + + struct wl_listener session_destroy; + struct wl_listener session_signal; + + struct wl_list devices; // wlr_libinput_device.link +}; + +struct wlr_libinput_input_device { + struct libinput_device *handle; + + struct wlr_keyboard keyboard; + struct wlr_pointer pointer; + struct wlr_switch switch_device; + struct wlr_touch touch; + struct wlr_tablet tablet; + struct wl_list tablet_tools; // see backend/libinput/tablet_tool.c + struct wlr_tablet_pad tablet_pad; + + struct wl_list link; +}; + +uint32_t usec_to_msec(uint64_t usec); + +void handle_libinput_event(struct wlr_libinput_backend *state, + struct libinput_event *event); + +void destroy_libinput_input_device(struct wlr_libinput_input_device *dev); +const char *get_libinput_device_name(struct libinput_device *device); + +extern const struct wlr_keyboard_impl libinput_keyboard_impl; +extern const struct wlr_pointer_impl libinput_pointer_impl; +extern const struct wlr_switch_impl libinput_switch_impl; +extern const struct wlr_tablet_impl libinput_tablet_impl; +extern const struct wlr_tablet_pad_impl libinput_tablet_pad_impl; +extern const struct wlr_touch_impl libinput_touch_impl; + +void init_device_keyboard(struct wlr_libinput_input_device *dev); +struct wlr_libinput_input_device *device_from_keyboard(struct wlr_keyboard *kb); +void handle_keyboard_key(struct libinput_event *event, struct wlr_keyboard *kb); + +void init_device_pointer(struct wlr_libinput_input_device *dev); +struct wlr_libinput_input_device *device_from_pointer(struct wlr_pointer *kb); +void handle_pointer_motion(struct libinput_event *event, + struct wlr_pointer *pointer); +void handle_pointer_motion_abs(struct libinput_event *event, + struct wlr_pointer *pointer); +void handle_pointer_button(struct libinput_event *event, + struct wlr_pointer *pointer); +void handle_pointer_axis(struct libinput_event *event, + struct wlr_pointer *pointer); +void handle_pointer_axis_value120(struct libinput_event *event, + struct wlr_pointer *pointer, enum wl_pointer_axis_source source); +void handle_pointer_swipe_begin(struct libinput_event *event, + struct wlr_pointer *pointer); +void handle_pointer_swipe_update(struct libinput_event *event, + struct wlr_pointer *pointer); +void handle_pointer_swipe_end(struct libinput_event *event, + struct wlr_pointer *pointer); +void handle_pointer_pinch_begin(struct libinput_event *event, + struct wlr_pointer *pointer); +void handle_pointer_pinch_update(struct libinput_event *event, + struct wlr_pointer *pointer); +void handle_pointer_pinch_end(struct libinput_event *event, + struct wlr_pointer *pointer); +void handle_pointer_hold_begin(struct libinput_event *event, + struct wlr_pointer *pointer); +void handle_pointer_hold_end(struct libinput_event *event, + struct wlr_pointer *pointer); + +void init_device_switch(struct wlr_libinput_input_device *dev); +struct wlr_libinput_input_device *device_from_switch( + struct wlr_switch *switch_device); +void handle_switch_toggle(struct libinput_event *event, + struct wlr_switch *switch_device); + +void init_device_touch(struct wlr_libinput_input_device *dev); +struct wlr_libinput_input_device *device_from_touch( + struct wlr_touch *touch); +void handle_touch_down(struct libinput_event *event, + struct wlr_touch *touch); +void handle_touch_up(struct libinput_event *event, + struct wlr_touch *touch); +void handle_touch_motion(struct libinput_event *event, + struct wlr_touch *touch); +void handle_touch_cancel(struct libinput_event *event, + struct wlr_touch *touch); +void handle_touch_frame(struct libinput_event *event, + struct wlr_touch *touch); + +void init_device_tablet(struct wlr_libinput_input_device *dev); +void finish_device_tablet(struct wlr_libinput_input_device *dev); +struct wlr_libinput_input_device *device_from_tablet( + struct wlr_tablet *tablet); +void handle_tablet_tool_axis(struct libinput_event *event, + struct wlr_tablet *tablet); +void handle_tablet_tool_proximity(struct libinput_event *event, + struct wlr_tablet *tablet); +void handle_tablet_tool_tip(struct libinput_event *event, + struct wlr_tablet *tablet); +void handle_tablet_tool_button(struct libinput_event *event, + struct wlr_tablet *tablet); + +void init_device_tablet_pad(struct wlr_libinput_input_device *dev); +void finish_device_tablet_pad(struct wlr_libinput_input_device *dev); +struct wlr_libinput_input_device *device_from_tablet_pad( + struct wlr_tablet_pad *tablet_pad); +void handle_tablet_pad_button(struct libinput_event *event, + struct wlr_tablet_pad *tablet_pad); +void handle_tablet_pad_ring(struct libinput_event *event, + struct wlr_tablet_pad *tablet_pad); +void handle_tablet_pad_strip(struct libinput_event *event, + struct wlr_tablet_pad *tablet_pad); + +bool button_state_from_libinput(enum libinput_button_state state, enum wlr_button_state *out); + +#endif diff --git a/3rdparty/wlroots/include/backend/multi.h b/3rdparty/wlroots/include/backend/multi.h new file mode 100644 index 0000000000..3ffd814068 --- /dev/null +++ b/3rdparty/wlroots/include/backend/multi.h @@ -0,0 +1,21 @@ +#ifndef BACKEND_MULTI_H +#define BACKEND_MULTI_H + +#include +#include +#include + +struct wlr_multi_backend { + struct wlr_backend backend; + + struct wl_list backends; + + struct wl_listener event_loop_destroy; + + struct { + struct wl_signal backend_add; + struct wl_signal backend_remove; + } events; +}; + +#endif diff --git a/3rdparty/wlroots/include/backend/session/session.h b/3rdparty/wlroots/include/backend/session/session.h new file mode 100644 index 0000000000..0275f69fa1 --- /dev/null +++ b/3rdparty/wlroots/include/backend/session/session.h @@ -0,0 +1,20 @@ +#ifndef BACKEND_SESSION_SESSION_H +#define BACKEND_SESSION_SESSION_H + +#include + +struct wl_display; +struct wlr_session; + +struct wlr_session *libseat_session_create(struct wl_display *disp); +void libseat_session_destroy(struct wlr_session *base); +int libseat_session_open_device(struct wlr_session *base, const char *path); +void libseat_session_close_device(struct wlr_session *base, int fd); +bool libseat_change_vt(struct wlr_session *base, unsigned vt); + +void session_init(struct wlr_session *session); + +struct wlr_device *session_open_if_kms(struct wlr_session *restrict session, + const char *restrict path); + +#endif diff --git a/3rdparty/wlroots/include/backend/wayland.h b/3rdparty/wlroots/include/backend/wayland.h new file mode 100644 index 0000000000..e24eb9fdfb --- /dev/null +++ b/3rdparty/wlroots/include/backend/wayland.h @@ -0,0 +1,217 @@ +#ifndef BACKEND_WAYLAND_H +#define BACKEND_WAYLAND_H + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct wlr_wl_backend { + struct wlr_backend backend; + + /* local state */ + bool started; + struct wl_event_loop *event_loop; + struct wl_event_queue *busy_loop_queue; + struct wl_list outputs; + int drm_fd; + struct wl_list buffers; // wlr_wl_buffer.link + size_t requested_outputs; + struct wl_listener event_loop_destroy; + char *activation_token; + + /* remote state */ + struct wl_display *remote_display; + bool own_remote_display; + struct wl_event_source *remote_display_src; + struct wl_registry *registry; + struct wl_compositor *compositor; + struct xdg_wm_base *xdg_wm_base; + struct zxdg_decoration_manager_v1 *zxdg_decoration_manager_v1; + struct zwp_pointer_gestures_v1 *zwp_pointer_gestures_v1; + struct wp_presentation *presentation; + struct wl_shm *shm; + struct zwp_linux_dmabuf_v1 *zwp_linux_dmabuf_v1; + struct wp_linux_drm_syncobj_manager_v1 *drm_syncobj_manager_v1; + struct wl_list drm_syncobj_timelines; // wlr_wl_drm_syncobj_timeline.link + struct zwp_relative_pointer_manager_v1 *zwp_relative_pointer_manager_v1; + struct wl_list seats; // wlr_wl_seat.link + struct zwp_tablet_manager_v2 *tablet_manager; + struct wlr_drm_format_set shm_formats; + struct wlr_drm_format_set linux_dmabuf_v1_formats; + struct wl_drm *legacy_drm; + struct xdg_activation_v1 *activation_v1; + struct wl_subcompositor *subcompositor; + struct wp_viewporter *viewporter; + char *drm_render_name; +}; + +struct wlr_wl_buffer { + struct wlr_buffer *buffer; + struct wl_buffer *wl_buffer; + bool released; + struct wl_list link; // wlr_wl_backend.buffers + struct wl_listener buffer_destroy; + + bool has_drm_syncobj_waiter; + struct wlr_drm_syncobj_timeline_waiter drm_syncobj_waiter; + + struct wlr_drm_syncobj_timeline *fallback_signal_timeline; + uint64_t fallback_signal_point; +}; + +struct wlr_wl_drm_syncobj_timeline { + struct wlr_drm_syncobj_timeline *base; + struct wlr_addon addon; + struct wl_list link; // wlr_wl_backend.drm_syncobj_timelines + struct wp_linux_drm_syncobj_timeline_v1 *wl; +}; + +struct wlr_wl_presentation_feedback { + struct wlr_wl_output *output; + struct wl_list link; + struct wp_presentation_feedback *feedback; + uint32_t commit_seq; +}; + +struct wlr_wl_output_layer { + struct wlr_addon addon; + + struct wl_surface *surface; + struct wl_subsurface *subsurface; + struct wp_viewport *viewport; + bool mapped; +}; + +struct wlr_wl_output { + struct wlr_output wlr_output; + + struct wlr_wl_backend *backend; + struct wl_list link; + + struct wl_surface *surface; + bool own_surface; + struct wl_callback *frame_callback; + struct xdg_surface *xdg_surface; + struct xdg_toplevel *xdg_toplevel; + struct zxdg_toplevel_decoration_v1 *zxdg_toplevel_decoration_v1; + struct wp_linux_drm_syncobj_surface_v1 *drm_syncobj_surface_v1; + struct wl_list presentation_feedbacks; + + char *title; + char *app_id; + + // 0 if not requested + int32_t requested_width, requested_height; + + uint32_t configure_serial; + bool has_configure_serial; + bool configured; + + bool initialized; + + // If not NULL, the host compositor hasn't acknowledged the unmapping yet; + // ignore all configure events + struct wl_callback *unmap_callback; + + uint32_t enter_serial; + + struct { + struct wlr_wl_pointer *pointer; + struct wl_surface *surface; + int32_t hotspot_x, hotspot_y; + } cursor; +}; + +struct wlr_wl_pointer { + struct wlr_pointer wlr_pointer; + + struct wlr_wl_seat *seat; + struct wlr_wl_output *output; + + enum wl_pointer_axis_source axis_source; + int32_t axis_discrete; + uint32_t fingers; // trackpad gesture + enum wl_pointer_axis_relative_direction axis_relative_direction; + + struct wl_listener output_destroy; + + struct wl_list link; +}; + +struct wlr_wl_touch_points { + int32_t ids[64]; + size_t len; +}; + +struct wlr_wl_seat { + char *name; + struct wl_seat *wl_seat; + uint32_t global_name; + + struct wlr_wl_backend *backend; + + struct wl_keyboard *wl_keyboard; + struct wlr_keyboard wlr_keyboard; + + struct wl_pointer *wl_pointer; + struct wlr_wl_pointer *active_pointer; + struct wl_list pointers; // wlr_wl_pointer.link + + struct zwp_pointer_gesture_swipe_v1 *gesture_swipe; + struct zwp_pointer_gesture_pinch_v1 *gesture_pinch; + struct zwp_pointer_gesture_hold_v1 *gesture_hold; + struct zwp_relative_pointer_v1 *relative_pointer; + + struct wl_touch *wl_touch; + struct wlr_touch wlr_touch; + struct wlr_wl_touch_points touch_points; + + struct zwp_tablet_seat_v2 *zwp_tablet_seat_v2; + struct zwp_tablet_v2 *zwp_tablet_v2; + struct wlr_tablet wlr_tablet; + struct zwp_tablet_tool_v2 *zwp_tablet_tool_v2; + struct wlr_tablet_tool wlr_tablet_tool; + struct zwp_tablet_pad_v2 *zwp_tablet_pad_v2; + struct wlr_tablet_pad wlr_tablet_pad; + + struct wl_list link; // wlr_wl_backend.seats +}; + +struct wlr_wl_backend *get_wl_backend_from_backend(struct wlr_backend *backend); +struct wlr_wl_output *get_wl_output_from_surface(struct wlr_wl_backend *wl, + struct wl_surface *surface); +void update_wl_output_cursor(struct wlr_wl_output *output); + +void init_seat_keyboard(struct wlr_wl_seat *seat); + +void init_seat_pointer(struct wlr_wl_seat *seat); +void finish_seat_pointer(struct wlr_wl_seat *seat); +void create_pointer(struct wlr_wl_seat *seat, struct wlr_wl_output *output); + +void init_seat_touch(struct wlr_wl_seat *seat); + +void init_seat_tablet(struct wlr_wl_seat *seat); +void finish_seat_tablet(struct wlr_wl_seat *seat); + +bool create_wl_seat(struct wl_seat *wl_seat, struct wlr_wl_backend *wl, + uint32_t global_name); +void destroy_wl_seat(struct wlr_wl_seat *seat); +void destroy_wl_buffer(struct wlr_wl_buffer *buffer); +void destroy_wl_drm_syncobj_timeline(struct wlr_wl_drm_syncobj_timeline *timeline); + +extern const struct wlr_pointer_impl wl_pointer_impl; +extern const struct wlr_tablet_pad_impl wl_tablet_pad_impl; +extern const struct wlr_tablet_impl wl_tablet_impl; + +#endif diff --git a/3rdparty/wlroots/include/backend/x11.h b/3rdparty/wlroots/include/backend/x11.h new file mode 100644 index 0000000000..fcea4d2572 --- /dev/null +++ b/3rdparty/wlroots/include/backend/x11.h @@ -0,0 +1,147 @@ +#ifndef BACKEND_X11_H +#define BACKEND_X11_H + +#include + +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" + +#if HAVE_XCB_ERRORS +#include +#endif + +#define XCB_EVENT_RESPONSE_TYPE_MASK 0x7f + +struct wlr_x11_backend; + +struct wlr_x11_output { + struct wlr_output wlr_output; + struct wlr_x11_backend *x11; + struct wl_list link; // wlr_x11_backend.outputs + + xcb_window_t win; + xcb_present_event_t present_event_id; + + int32_t win_width, win_height; + + struct wlr_pointer pointer; + + struct wlr_touch touch; + struct wl_list touchpoints; // wlr_x11_touchpoint.link + + struct wl_list buffers; // wlr_x11_buffer.link + + pixman_region32_t exposed; + + uint64_t last_msc; + + struct { + struct wlr_swapchain *swapchain; + xcb_render_picture_t pic; + } cursor; +}; + +struct wlr_x11_touchpoint { + uint32_t x11_id; + int wayland_id; + struct wl_list link; // wlr_x11_output.touch_points +}; + +struct wlr_x11_backend { + struct wlr_backend backend; + struct wl_event_loop *event_loop; + bool started; + + xcb_connection_t *xcb; + xcb_screen_t *screen; + xcb_depth_t *depth; + xcb_visualid_t visualid; + xcb_colormap_t colormap; + xcb_cursor_t transparent_cursor; + xcb_render_pictformat_t argb32; + + bool have_shm; + bool have_dri3; + uint32_t dri3_major_version, dri3_minor_version; + + size_t requested_outputs; + struct wl_list outputs; // wlr_x11_output.link + + struct wlr_keyboard keyboard; + + int drm_fd; + struct wlr_drm_format_set dri3_formats; + struct wlr_drm_format_set shm_formats; + const struct wlr_x11_format *x11_format; + struct wlr_drm_format_set primary_dri3_formats; + struct wlr_drm_format_set primary_shm_formats; + struct wl_event_source *event_source; + + struct { + xcb_atom_t wm_protocols; + xcb_atom_t wm_delete_window; + xcb_atom_t net_wm_name; + xcb_atom_t utf8_string; + xcb_atom_t variable_refresh; + } atoms; + + // The time we last received an event + xcb_timestamp_t time; + +#if HAVE_XCB_ERRORS + xcb_errors_context_t *errors_context; +#endif + + uint8_t present_opcode; + uint8_t xinput_opcode; + + struct wl_listener event_loop_destroy; +}; + +struct wlr_x11_buffer { + struct wlr_x11_backend *x11; + struct wlr_buffer *buffer; + xcb_pixmap_t pixmap; + struct wl_list link; // wlr_x11_output.buffers + struct wl_listener buffer_destroy; + size_t n_busy; +}; + +struct wlr_x11_format { + uint32_t drm; + uint8_t depth, bpp; +}; + +struct wlr_x11_backend *get_x11_backend_from_backend( + struct wlr_backend *wlr_backend); +struct wlr_x11_output *get_x11_output_from_window_id( + struct wlr_x11_backend *x11, xcb_window_t window); + +extern const struct wlr_keyboard_impl x11_keyboard_impl; +extern const struct wlr_pointer_impl x11_pointer_impl; +extern const struct wlr_touch_impl x11_touch_impl; + +void handle_x11_xinput_event(struct wlr_x11_backend *x11, + xcb_ge_generic_event_t *event); +void update_x11_pointer_position(struct wlr_x11_output *output, + xcb_timestamp_t time); + +void handle_x11_configure_notify(struct wlr_x11_output *output, + xcb_configure_notify_event_t *event); +void handle_x11_present_event(struct wlr_x11_backend *x11, + xcb_ge_generic_event_t *event); + +#endif diff --git a/3rdparty/wlroots/include/interfaces/wlr_input_device.h b/3rdparty/wlroots/include/interfaces/wlr_input_device.h new file mode 100644 index 0000000000..c24b53662a --- /dev/null +++ b/3rdparty/wlroots/include/interfaces/wlr_input_device.h @@ -0,0 +1,20 @@ +#ifndef INTERFACES_INPUT_DEVICE_H +#define INTERFACES_INPUT_DEVICE_H + +#include + +/** + * Initializes a given wlr_input_device. Allocates memory for the name and sets + * its vendor and product id to 0. + * wlr_device must be non-NULL. + */ +void wlr_input_device_init(struct wlr_input_device *wlr_device, + enum wlr_input_device_type type, const char *name); + +/** + * Cleans up all the memory owned by a given wlr_input_device and signals + * the destroy event. + */ +void wlr_input_device_finish(struct wlr_input_device *wlr_device); + +#endif diff --git a/3rdparty/wlroots/include/meson.build b/3rdparty/wlroots/include/meson.build new file mode 100644 index 0000000000..165166c336 --- /dev/null +++ b/3rdparty/wlroots/include/meson.build @@ -0,0 +1,38 @@ +subdir('wlr') + +exclude_files = ['meson.build', 'config.h.in', 'version.h.in'] +if not features.get('drm-backend') + exclude_files += 'backend/drm.h' + exclude_files += 'types/wlr_drm_lease_v1.h' +endif +if not features.get('libinput-backend') + exclude_files += 'backend/libinput.h' +endif +if not features.get('x11-backend') + exclude_files += 'backend/x11.h' +endif +if not features.get('xwayland') + exclude_files += 'xwayland.h' +endif +if not features.get('gles2-renderer') + exclude_files += ['render/egl.h', 'render/gles2.h'] +endif +if not features.get('vulkan-renderer') + exclude_files += 'render/vulkan.h' +endif +if not features.get('session') + exclude_files += 'backend/session.h' +endif + +install_subdir('wlr', + install_dir: get_option('includedir') / versioned_name, + exclude_files: exclude_files, +) + +foreach name, have : internal_features + internal_config.set10('HAVE_' + name.underscorify().to_upper(), have) +endforeach +wlr_files += configure_file( + output: 'config.h', + configuration: internal_config, +) diff --git a/3rdparty/wlroots/include/render/allocator/drm_dumb.h b/3rdparty/wlroots/include/render/allocator/drm_dumb.h new file mode 100644 index 0000000000..f505d651a6 --- /dev/null +++ b/3rdparty/wlroots/include/render/allocator/drm_dumb.h @@ -0,0 +1,37 @@ +#ifndef RENDER_ALLOCATOR_DRM_DUMB_H +#define RENDER_ALLOCATOR_DRM_DUMB_H + +#include +#include +#include + +struct wlr_drm_dumb_buffer { + struct wlr_buffer base; + struct wl_list link; // wlr_drm_dumb_allocator.buffers + + int drm_fd; // -1 if the allocator has been destroyed + struct wlr_dmabuf_attributes dmabuf; + + uint32_t format; + uint32_t handle; + uint32_t stride; + uint32_t width, height; + + uint64_t size; + void *data; +}; + +struct wlr_drm_dumb_allocator { + struct wlr_allocator base; + struct wl_list buffers; // wlr_drm_dumb_buffer.link + int drm_fd; +}; + +/** + * Creates a new drm dumb allocator from a DRM FD. + * + * Does not take ownership over the FD. + */ +struct wlr_allocator *wlr_drm_dumb_allocator_create(int fd); + +#endif diff --git a/3rdparty/wlroots/include/render/allocator/gbm.h b/3rdparty/wlroots/include/render/allocator/gbm.h new file mode 100644 index 0000000000..7d0016eb48 --- /dev/null +++ b/3rdparty/wlroots/include/render/allocator/gbm.h @@ -0,0 +1,34 @@ +#ifndef RENDER_ALLOCATOR_GBM_H +#define RENDER_ALLOCATOR_GBM_H + +#include +#include +#include +#include + +struct wlr_gbm_buffer { + struct wlr_buffer base; + + struct wl_list link; // wlr_gbm_allocator.buffers + + struct gbm_bo *gbm_bo; // NULL if the gbm_device has been destroyed + struct wlr_dmabuf_attributes dmabuf; +}; + +struct wlr_gbm_allocator { + struct wlr_allocator base; + + int fd; + struct gbm_device *gbm_device; + + struct wl_list buffers; // wlr_gbm_buffer.link +}; + +/** + * Creates a new GBM allocator from a DRM FD. + * + * Takes ownership over the FD. + */ +struct wlr_allocator *wlr_gbm_allocator_create(int drm_fd); + +#endif diff --git a/3rdparty/wlroots/include/render/allocator/shm.h b/3rdparty/wlroots/include/render/allocator/shm.h new file mode 100644 index 0000000000..602efdc35a --- /dev/null +++ b/3rdparty/wlroots/include/render/allocator/shm.h @@ -0,0 +1,23 @@ +#ifndef RENDER_ALLOCATOR_SHM_H +#define RENDER_ALLOCATOR_SHM_H + +#include +#include + +struct wlr_shm_buffer { + struct wlr_buffer base; + struct wlr_shm_attributes shm; + void *data; + size_t size; +}; + +struct wlr_shm_allocator { + struct wlr_allocator base; +}; + +/** + * Creates a new shared memory allocator. + */ +struct wlr_allocator *wlr_shm_allocator_create(void); + +#endif diff --git a/3rdparty/wlroots/include/render/allocator/udmabuf.h b/3rdparty/wlroots/include/render/allocator/udmabuf.h new file mode 100644 index 0000000000..b38b5ab0d5 --- /dev/null +++ b/3rdparty/wlroots/include/render/allocator/udmabuf.h @@ -0,0 +1,23 @@ +#ifndef RENDER_ALLOCATOR_UDMABUF_H +#define RENDER_ALLOCATOR_UDMABUF_H + +#include +#include + +struct wlr_udmabuf_buffer { + struct wlr_buffer base; + + size_t size; + struct wlr_shm_attributes shm; + struct wlr_dmabuf_attributes dmabuf; +}; + +struct wlr_udmabuf_allocator { + struct wlr_allocator base; + + int fd; +}; + +struct wlr_allocator *wlr_udmabuf_allocator_create(void); + +#endif diff --git a/3rdparty/wlroots/include/render/color.h b/3rdparty/wlroots/include/render/color.h new file mode 100644 index 0000000000..60c841d125 --- /dev/null +++ b/3rdparty/wlroots/include/render/color.h @@ -0,0 +1,111 @@ +#ifndef RENDER_COLOR_H +#define RENDER_COLOR_H + +#include +#include +#include + +enum wlr_color_transform_type { + COLOR_TRANSFORM_INVERSE_EOTF, + COLOR_TRANSFORM_LCMS2, + COLOR_TRANSFORM_LUT_3X1D, + COLOR_TRANSFORM_MATRIX, + COLOR_TRANSFORM_PIPELINE, +}; + +struct wlr_color_transform { + int ref_count; + struct wlr_addon_set addons; // per-renderer helper state + + enum wlr_color_transform_type type; +}; + +struct wlr_color_transform_inverse_eotf { + struct wlr_color_transform base; + + enum wlr_color_transfer_function tf; +}; + +/** + * The formula is approximated via three 1D look-up tables. The flat lut_3x1d + * array has a length of 3 * dim. + * + * The offset of a color value for a given channel and color index is: + * + * offset = channel_index * dim + color_index + */ +struct wlr_color_transform_lut_3x1d { + struct wlr_color_transform base; + + uint16_t *lut_3x1d; + size_t dim; +}; + +struct wlr_color_transform_matrix { + struct wlr_color_transform base; + + float matrix[9]; +}; + +struct wlr_color_transform_pipeline { + struct wlr_color_transform base; + + struct wlr_color_transform **transforms; + size_t len; +}; + +void wlr_color_transform_init(struct wlr_color_transform *tr, + enum wlr_color_transform_type type); + +/** + * Get a struct wlr_color_transform_lcms2 from a generic struct wlr_color_transform. + * Asserts that the base type is COLOR_TRANSFORM_LCMS2. + */ +struct wlr_color_transform_lcms2 *color_transform_lcms2_from_base( + struct wlr_color_transform *tr); + +void color_transform_lcms2_finish(struct wlr_color_transform_lcms2 *tr); + +/** + * Evaluate a LCMS2 color transform for a given RGB triplet. + */ +void color_transform_lcms2_eval(struct wlr_color_transform_lcms2 *tr, + float out[static 3], const float in[static 3]); + +/** + * Gets a wlr_color_transform_inverse_eotf from a generic wlr_color_transform. + * Asserts that the base type is COLOR_TRANSFORM_INVERSE_EOTF + */ +struct wlr_color_transform_inverse_eotf *wlr_color_transform_inverse_eotf_from_base( + struct wlr_color_transform *tr); + +/** + * Get a struct wlr_color_transform_lut_3x1d from a generic + * struct wlr_color_transform. Asserts that the base type is + * COLOR_TRANSFORM_LUT_3X1D. + */ +struct wlr_color_transform_lut_3x1d *color_transform_lut_3x1d_from_base( + struct wlr_color_transform *tr); + +/** + * Create a simplified / normalized wlr_color_transform pipeline. + * `transforms` may contain NULL transforms, they will be interpreted as the + * identity transform, and removed. + * `*result` may be set to a transform of a type different from + * `wlr_color_transform_pipeline`, or to NULL if all input transforms are NULL + */ +bool color_transform_compose(struct wlr_color_transform **result, + struct wlr_color_transform **transforms, size_t len); + +/** + * Compute the matrix to convert RGB color values to CIE 1931 XYZ. + */ +void wlr_color_primaries_to_xyz(const struct wlr_color_primaries *primaries, float matrix[static 9]); + +/** + * Get default luminances for a transfer function. + */ +void wlr_color_transfer_function_get_default_luminance(enum wlr_color_transfer_function tf, + struct wlr_color_luminances *lum); + +#endif diff --git a/3rdparty/wlroots/include/render/dmabuf.h b/3rdparty/wlroots/include/render/dmabuf.h new file mode 100644 index 0000000000..3d905ce9ed --- /dev/null +++ b/3rdparty/wlroots/include/render/dmabuf.h @@ -0,0 +1,35 @@ +#ifndef RENDER_DMABUF_H +#define RENDER_DMABUF_H + +#include +#include + +// Copied from to avoid #ifdef soup +#define DMA_BUF_SYNC_READ (1 << 0) +#define DMA_BUF_SYNC_WRITE (2 << 0) +#define DMA_BUF_SYNC_RW (DMA_BUF_SYNC_READ | DMA_BUF_SYNC_WRITE) + +/** + * Check whether DMA-BUF import/export from/to sync_file is available. + * + * If this function returns true, dmabuf_import_sync_file() is supported. + */ +bool dmabuf_check_sync_file_import_export(void); + +/** + * Import a sync_file into a DMA-BUF with DMA_BUF_IOCTL_IMPORT_SYNC_FILE. + * + * This can be used to make explicit sync interoperate with implicit sync. + */ +bool dmabuf_import_sync_file(int dmabuf_fd, uint32_t flags, int sync_file_fd); + +/** + * Export a sync_file from a DMA-BUF with DMA_BUF_IOCTL_EXPORT_SYNC_FILE. + * + * The sync_file FD is returned on success, -1 is returned on error. + * + * This can be used to make explicit sync interoperate with implicit sync. + */ +int dmabuf_export_sync_file(int dmabuf_fd, uint32_t flags); + +#endif diff --git a/3rdparty/wlroots/include/render/drm_format_set.h b/3rdparty/wlroots/include/render/drm_format_set.h new file mode 100644 index 0000000000..ea192a503a --- /dev/null +++ b/3rdparty/wlroots/include/render/drm_format_set.h @@ -0,0 +1,23 @@ +#ifndef RENDER_DRM_FORMAT_SET_H +#define RENDER_DRM_FORMAT_SET_H + +#include + +void wlr_drm_format_init(struct wlr_drm_format *fmt, uint32_t format); +bool wlr_drm_format_has(const struct wlr_drm_format *fmt, uint64_t modifier); +bool wlr_drm_format_add(struct wlr_drm_format *fmt, uint64_t modifier); +bool wlr_drm_format_copy(struct wlr_drm_format *dst, const struct wlr_drm_format *src); +/** + * Intersect modifiers for two DRM formats. The `dst` must be zeroed or initialized + * with other state being replaced. + * + * Both arguments must have the same format field. If the formats aren't + * compatible, NULL is returned. If either format doesn't support any modifier, + * a format that doesn't support any modifier is returned. + */ +bool wlr_drm_format_intersect(struct wlr_drm_format *dst, + const struct wlr_drm_format *a, const struct wlr_drm_format *b); + +bool wlr_drm_format_set_copy(struct wlr_drm_format_set *dst, const struct wlr_drm_format_set *src); + +#endif diff --git a/3rdparty/wlroots/include/render/drm_syncobj_merger.h b/3rdparty/wlroots/include/render/drm_syncobj_merger.h new file mode 100644 index 0000000000..c55c87314c --- /dev/null +++ b/3rdparty/wlroots/include/render/drm_syncobj_merger.h @@ -0,0 +1,44 @@ +#ifndef WLR_RENDER_DRM_SYNCOBJ_MERGER_H +#define WLR_RENDER_DRM_SYNCOBJ_MERGER_H + +#include + +/** + * Accumulate timeline points, to have a destination timeline point be + * signalled when all inputs are + */ +struct wlr_drm_syncobj_merger { + int n_ref; + struct wlr_drm_syncobj_timeline *dst_timeline; + uint64_t dst_point; + int sync_fd; +}; + +/** + * Create a new merger. + * + * The given timeline point will be signalled when all input points are + * signalled and the merger is destroyed. + */ +struct wlr_drm_syncobj_merger *wlr_drm_syncobj_merger_create( + struct wlr_drm_syncobj_timeline *dst_timeline, uint64_t dst_point); + +struct wlr_drm_syncobj_merger *wlr_drm_syncobj_merger_ref( + struct wlr_drm_syncobj_merger *merger); + +/** + * Target timeline point is materialized when all inputs are, and the merger is + * destroyed. + */ +void wlr_drm_syncobj_merger_unref(struct wlr_drm_syncobj_merger *merger); +/** + * Add a new timeline point to wait for. + * + * If the point is not materialized, the supplied event loop is used to schedule + * a wait. + */ +bool wlr_drm_syncobj_merger_add(struct wlr_drm_syncobj_merger *merger, + struct wlr_drm_syncobj_timeline *dst_timeline, uint64_t dst_point, + struct wl_event_loop *loop); + +#endif diff --git a/3rdparty/wlroots/include/render/egl.h b/3rdparty/wlroots/include/render/egl.h new file mode 100644 index 0000000000..103ab57df7 --- /dev/null +++ b/3rdparty/wlroots/include/render/egl.h @@ -0,0 +1,120 @@ +#ifndef RENDER_EGL_H +#define RENDER_EGL_H + +#include + +struct wlr_egl { + EGLDisplay display; + EGLContext context; + EGLDeviceEXT device; // may be EGL_NO_DEVICE_EXT + struct gbm_device *gbm_device; + + struct { + // Display extensions + bool KHR_image_base; + bool EXT_image_dma_buf_import; + bool EXT_image_dma_buf_import_modifiers; + bool IMG_context_priority; + bool EXT_create_context_robustness; + + // Device extensions + bool EXT_device_drm; + bool EXT_device_drm_render_node; + + // Client extensions + bool EXT_device_query; + bool KHR_platform_gbm; + bool EXT_platform_device; + bool KHR_display_reference; + } exts; + + struct { + PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT; + PFNEGLCREATEIMAGEKHRPROC eglCreateImageKHR; + PFNEGLDESTROYIMAGEKHRPROC eglDestroyImageKHR; + PFNEGLQUERYDMABUFFORMATSEXTPROC eglQueryDmaBufFormatsEXT; + PFNEGLQUERYDMABUFMODIFIERSEXTPROC eglQueryDmaBufModifiersEXT; + PFNEGLDEBUGMESSAGECONTROLKHRPROC eglDebugMessageControlKHR; + PFNEGLQUERYDISPLAYATTRIBEXTPROC eglQueryDisplayAttribEXT; + PFNEGLQUERYDEVICESTRINGEXTPROC eglQueryDeviceStringEXT; + PFNEGLQUERYDEVICESEXTPROC eglQueryDevicesEXT; + PFNEGLCREATESYNCKHRPROC eglCreateSyncKHR; + PFNEGLDESTROYSYNCKHRPROC eglDestroySyncKHR; + PFNEGLDUPNATIVEFENCEFDANDROIDPROC eglDupNativeFenceFDANDROID; + PFNEGLWAITSYNCKHRPROC eglWaitSyncKHR; + } procs; + + bool has_modifiers; + struct wlr_drm_format_set dmabuf_texture_formats; + struct wlr_drm_format_set dmabuf_render_formats; +}; + +struct wlr_egl_context { + EGLDisplay display; + EGLContext context; + EGLSurface draw_surface; + EGLSurface read_surface; +}; + +/** + * Initializes an EGL context for the given DRM FD. + * + * Will attempt to load all possibly required API functions. + */ +struct wlr_egl *wlr_egl_create_with_drm_fd(int drm_fd); + +/** + * Frees all related EGL resources, makes the context not-current and + * unbinds a bound wayland display. + */ +void wlr_egl_destroy(struct wlr_egl *egl); + +/** + * Creates an EGL image from the given dmabuf attributes. Check usability + * of the dmabuf with wlr_egl_check_import_dmabuf once first. + */ +EGLImageKHR wlr_egl_create_image_from_dmabuf(struct wlr_egl *egl, + struct wlr_dmabuf_attributes *attributes, bool *external_only); + +/** + * Get DMA-BUF formats suitable for sampling usage. + */ +const struct wlr_drm_format_set *wlr_egl_get_dmabuf_texture_formats( + struct wlr_egl *egl); +/** + * Get DMA-BUF formats suitable for rendering usage. + */ +const struct wlr_drm_format_set *wlr_egl_get_dmabuf_render_formats( + struct wlr_egl *egl); + +/** + * Destroys an EGL image created with the given wlr_egl. + */ +bool wlr_egl_destroy_image(struct wlr_egl *egl, EGLImageKHR image); + +int wlr_egl_dup_drm_fd(struct wlr_egl *egl); + +/** + * Restore EGL context that was previously saved using wlr_egl_save_current(). + */ +bool wlr_egl_restore_context(struct wlr_egl_context *context); + +/** + * Make the EGL context current. + * + * The old EGL context is saved. Callers are expected to clear the current + * context when they are done by calling wlr_egl_restore_context(). + */ +bool wlr_egl_make_current(struct wlr_egl *egl, struct wlr_egl_context *save_context); + +bool wlr_egl_unset_current(struct wlr_egl *egl); + +EGLSyncKHR wlr_egl_create_sync(struct wlr_egl *egl, int fence_fd); + +void wlr_egl_destroy_sync(struct wlr_egl *egl, EGLSyncKHR sync); + +int wlr_egl_dup_fence_fd(struct wlr_egl *egl, EGLSyncKHR sync); + +bool wlr_egl_wait_sync(struct wlr_egl *egl, EGLSyncKHR sync); + +#endif diff --git a/3rdparty/wlroots/include/render/gles2.h b/3rdparty/wlroots/include/render/gles2.h new file mode 100644 index 0000000000..6b852dcb73 --- /dev/null +++ b/3rdparty/wlroots/include/render/gles2.h @@ -0,0 +1,176 @@ +#ifndef RENDER_GLES2_H +#define RENDER_GLES2_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "render/egl.h" + +// mesa ships old GL headers that don't include this type, so for distros that use headers from +// mesa we need to def it ourselves until they update. +// https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/23144 +typedef void (GL_APIENTRYP PFNGLGETINTEGER64VEXTPROC) (GLenum pname, GLint64 *data); + +struct wlr_gles2_pixel_format { + uint32_t drm_format; + // optional field, if empty then internalformat = format + GLint gl_internalformat; + GLint gl_format, gl_type; +}; + +struct wlr_gles2_tex_shader { + GLuint program; + GLint proj; + GLint tex_proj; + GLint tex; + GLint alpha; + GLint pos_attrib; +}; + +struct wlr_gles2_renderer { + struct wlr_renderer wlr_renderer; + + struct wlr_egl *egl; + int drm_fd; + + struct wlr_drm_format_set shm_texture_formats; + + const char *exts_str; + struct { + bool EXT_read_format_bgra; + bool KHR_debug; + bool OES_egl_image_external; + bool OES_egl_image; + bool EXT_texture_type_2_10_10_10_REV; + bool OES_texture_half_float_linear; + bool EXT_texture_norm16; + bool EXT_disjoint_timer_query; + } exts; + + struct { + PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES; + PFNGLDEBUGMESSAGECALLBACKKHRPROC glDebugMessageCallbackKHR; + PFNGLDEBUGMESSAGECONTROLKHRPROC glDebugMessageControlKHR; + PFNGLPOPDEBUGGROUPKHRPROC glPopDebugGroupKHR; + PFNGLPUSHDEBUGGROUPKHRPROC glPushDebugGroupKHR; + PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC glEGLImageTargetRenderbufferStorageOES; + PFNGLGETGRAPHICSRESETSTATUSKHRPROC glGetGraphicsResetStatusKHR; + PFNGLGENQUERIESEXTPROC glGenQueriesEXT; + PFNGLDELETEQUERIESEXTPROC glDeleteQueriesEXT; + PFNGLQUERYCOUNTEREXTPROC glQueryCounterEXT; + PFNGLGETQUERYOBJECTIVEXTPROC glGetQueryObjectivEXT; + PFNGLGETQUERYOBJECTUI64VEXTPROC glGetQueryObjectui64vEXT; + PFNGLGETINTEGER64VEXTPROC glGetInteger64vEXT; + } procs; + + struct { + struct { + GLuint program; + GLint proj; + GLint color; + GLint pos_attrib; + } quad; + struct wlr_gles2_tex_shader tex_rgba; + struct wlr_gles2_tex_shader tex_rgbx; + struct wlr_gles2_tex_shader tex_ext; + } shaders; + + struct wl_list buffers; // wlr_gles2_buffer.link + struct wl_list textures; // wlr_gles2_texture.link +}; + +struct wlr_gles2_render_timer { + struct wlr_render_timer base; + struct wlr_gles2_renderer *renderer; + struct timespec cpu_start; + struct timespec cpu_end; + GLuint id; + GLint64 gl_cpu_end; +}; + +struct wlr_gles2_buffer { + struct wlr_buffer *buffer; + struct wlr_gles2_renderer *renderer; + struct wl_list link; // wlr_gles2_renderer.buffers + bool external_only; + + EGLImageKHR image; + GLuint rbo; + GLuint fbo; + GLuint tex; + + struct wlr_addon addon; +}; + +struct wlr_gles2_texture { + struct wlr_texture wlr_texture; + struct wlr_gles2_renderer *renderer; + struct wl_list link; // wlr_gles2_renderer.textures + + GLenum target; + + // If this texture is imported from a buffer, the texture is does not own + // these states. These cannot be destroyed along with the texture in this + // case. + GLuint tex; + GLuint fbo; + + bool has_alpha; + + uint32_t drm_format; // for mutable textures only, used to interpret upload data + struct wlr_gles2_buffer *buffer; // for DMA-BUF imports only +}; + +struct wlr_gles2_render_pass { + struct wlr_render_pass base; + struct wlr_gles2_buffer *buffer; + float projection_matrix[9]; + struct wlr_egl_context prev_ctx; + struct wlr_gles2_render_timer *timer; + struct wlr_drm_syncobj_timeline *signal_timeline; + uint64_t signal_point; +}; + +bool is_gles2_pixel_format_supported(const struct wlr_gles2_renderer *renderer, + const struct wlr_gles2_pixel_format *format); +const struct wlr_gles2_pixel_format *get_gles2_format_from_drm(uint32_t fmt); +const struct wlr_gles2_pixel_format *get_gles2_format_from_gl( + GLint gl_format, GLint gl_type, bool alpha); +void get_gles2_shm_formats(const struct wlr_gles2_renderer *renderer, + struct wlr_drm_format_set *out); + +GLuint gles2_buffer_get_fbo(struct wlr_gles2_buffer *buffer); + +struct wlr_gles2_renderer *gles2_get_renderer( + struct wlr_renderer *wlr_renderer); +struct wlr_gles2_render_timer *gles2_get_render_timer( + struct wlr_render_timer *timer); +struct wlr_gles2_texture *gles2_get_texture( + struct wlr_texture *wlr_texture); +struct wlr_gles2_buffer *gles2_buffer_get_or_create(struct wlr_gles2_renderer *renderer, + struct wlr_buffer *wlr_buffer); + +struct wlr_texture *gles2_texture_from_buffer(struct wlr_renderer *wlr_renderer, + struct wlr_buffer *buffer); +void gles2_texture_destroy(struct wlr_gles2_texture *texture); + +void push_gles2_debug_(struct wlr_gles2_renderer *renderer, + const char *file, const char *func); +#define push_gles2_debug(renderer) push_gles2_debug_(renderer, _WLR_FILENAME, __func__) +void pop_gles2_debug(struct wlr_gles2_renderer *renderer); + +struct wlr_gles2_render_pass *begin_gles2_buffer_pass(struct wlr_gles2_buffer *buffer, + struct wlr_egl_context *prev_ctx, struct wlr_gles2_render_timer *timer, + struct wlr_drm_syncobj_timeline *signal_timeline, uint64_t signal_point); + +#endif diff --git a/3rdparty/wlroots/include/render/pixel_format.h b/3rdparty/wlroots/include/render/pixel_format.h new file mode 100644 index 0000000000..b5f2b2411b --- /dev/null +++ b/3rdparty/wlroots/include/render/pixel_format.h @@ -0,0 +1,71 @@ +#ifndef RENDER_PIXEL_FORMAT_H +#define RENDER_PIXEL_FORMAT_H + +#include + +/** + * Information about a pixel format. + * + * A pixel format is identified via its DRM four character code (see ). + * + * Simple formats have a block size of 1×1 pixels and bytes_per_block contains + * the number of bytes per pixel (including padding). + * + * Tiled formats (e.g. sub-sampled YCbCr) are described with a block size + * greater than 1×1 pixels. A block is a rectangle of pixels which are stored + * next to each other in a byte-aligned memory region. + */ +struct wlr_pixel_format_info { + uint32_t drm_format; + + /* Equivalent of the format if it has an alpha channel, + * DRM_FORMAT_INVALID (0) if NA + */ + uint32_t opaque_substitute; + + /* Bytes per block (including padding) */ + uint32_t bytes_per_block; + /* Size of a block in pixels (zero for 1×1) */ + uint32_t block_width, block_height; +}; + +/** + * Get pixel format information from a DRM FourCC. + * + * NULL is returned if the pixel format is unknown. + */ +const struct wlr_pixel_format_info *drm_get_pixel_format_info(uint32_t fmt); +/** + * Get the number of pixels per block for a pixel format. + */ +uint32_t pixel_format_info_pixels_per_block(const struct wlr_pixel_format_info *info); +/** + * Get the minimum stride for a given pixel format and width. + */ +int32_t pixel_format_info_min_stride(const struct wlr_pixel_format_info *info, int32_t width); +/** + * Check whether a stride is large enough for a given pixel format and width. + */ +bool pixel_format_info_check_stride(const struct wlr_pixel_format_info *info, + int32_t stride, int32_t width); + +/** + * Convert an enum wl_shm_format to a DRM FourCC. + */ +uint32_t convert_wl_shm_format_to_drm(enum wl_shm_format fmt); +/** + * Convert a DRM FourCC to an enum wl_shm_format. + */ +enum wl_shm_format convert_drm_format_to_wl_shm(uint32_t fmt); + +/** + * Return true if the DRM FourCC fmt has an alpha channel, false otherwise. + */ +bool pixel_format_has_alpha(uint32_t fmt); + +/** + * Return true if the DRM FourCC fmt belongs to a YCbCr colorspace family, false otherwise. + */ +bool pixel_format_is_ycbcr(uint32_t fmt); + +#endif diff --git a/3rdparty/wlroots/include/render/pixman.h b/3rdparty/wlroots/include/render/pixman.h new file mode 100644 index 0000000000..0984214477 --- /dev/null +++ b/3rdparty/wlroots/include/render/pixman.h @@ -0,0 +1,64 @@ +#ifndef RENDER_PIXMAN_H +#define RENDER_PIXMAN_H + +#include +#include +#include +#include +#include "render/pixel_format.h" + +struct wlr_pixman_pixel_format { + uint32_t drm_format; + pixman_format_code_t pixman_format; +}; + +struct wlr_pixman_buffer; + +struct wlr_pixman_renderer { + struct wlr_renderer wlr_renderer; + + struct wl_list buffers; // wlr_pixman_buffer.link + struct wl_list textures; // wlr_pixman_texture.link + + struct wlr_drm_format_set drm_formats; +}; + +struct wlr_pixman_buffer { + struct wlr_buffer *buffer; + struct wlr_pixman_renderer *renderer; + + pixman_image_t *image; + + struct wl_listener buffer_destroy; + struct wl_list link; // wlr_pixman_renderer.buffers +}; + +struct wlr_pixman_texture { + struct wlr_texture wlr_texture; + struct wlr_pixman_renderer *renderer; + struct wl_list link; // wlr_pixman_renderer.textures + + pixman_image_t *image; + pixman_format_code_t format; + const struct wlr_pixel_format_info *format_info; + + void *data; // if created via texture_from_pixels + struct wlr_buffer *buffer; // if created via texture_from_buffer +}; + +struct wlr_pixman_render_pass { + struct wlr_render_pass base; + struct wlr_pixman_buffer *buffer; +}; + +pixman_format_code_t get_pixman_format_from_drm(uint32_t fmt); +uint32_t get_drm_format_from_pixman(pixman_format_code_t fmt); +const uint32_t *get_pixman_drm_formats(size_t *len); + +bool begin_pixman_data_ptr_access(struct wlr_buffer *buffer, pixman_image_t **image_ptr, + uint32_t flags); + +struct wlr_pixman_render_pass *begin_pixman_render_pass( + struct wlr_pixman_buffer *buffer); + +#endif diff --git a/3rdparty/wlroots/include/render/vulkan.h b/3rdparty/wlroots/include/render/vulkan.h new file mode 100644 index 0000000000..f96619f2c6 --- /dev/null +++ b/3rdparty/wlroots/include/render/vulkan.h @@ -0,0 +1,591 @@ +#ifndef RENDER_VULKAN_H +#define RENDER_VULKAN_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "util/rect_union.h" + +struct wlr_vk_descriptor_pool; +struct wlr_vk_texture; + +struct wlr_vk_instance { + VkInstance instance; + VkDebugUtilsMessengerEXT messenger; + + struct { + PFN_vkCreateDebugUtilsMessengerEXT createDebugUtilsMessengerEXT; + PFN_vkDestroyDebugUtilsMessengerEXT destroyDebugUtilsMessengerEXT; + } api; +}; + +// Creates and initializes a vulkan instance. +// The debug parameter determines if validation layers are enabled and a +// debug messenger created. +struct wlr_vk_instance *vulkan_instance_create(bool debug); +void vulkan_instance_destroy(struct wlr_vk_instance *ini); + +// Logical vulkan device state. +struct wlr_vk_device { + struct wlr_vk_instance *instance; + + VkPhysicalDevice phdev; + VkDevice dev; + + int drm_fd; + + bool sync_file_import_export; + bool implicit_sync_interop; + bool sampler_ycbcr_conversion; + + // we only ever need one queue for rendering and transfer commands + uint32_t queue_family; + VkQueue queue; + + struct { + PFN_vkGetMemoryFdPropertiesKHR vkGetMemoryFdPropertiesKHR; + PFN_vkWaitSemaphoresKHR vkWaitSemaphoresKHR; + PFN_vkGetSemaphoreCounterValueKHR vkGetSemaphoreCounterValueKHR; + PFN_vkGetSemaphoreFdKHR vkGetSemaphoreFdKHR; + PFN_vkImportSemaphoreFdKHR vkImportSemaphoreFdKHR; + PFN_vkQueueSubmit2KHR vkQueueSubmit2KHR; + } api; + + uint32_t format_prop_count; + struct wlr_vk_format_props *format_props; + struct wlr_drm_format_set dmabuf_render_formats; + struct wlr_drm_format_set dmabuf_texture_formats; + struct wlr_drm_format_set shm_texture_formats; +}; + +// Tries to find the VkPhysicalDevice for the given drm fd. +// Might find none and return VK_NULL_HANDLE. +VkPhysicalDevice vulkan_find_drm_phdev(struct wlr_vk_instance *ini, int drm_fd); +int vulkan_open_phdev_drm_fd(VkPhysicalDevice phdev); + +// Creates a device for the given instance and physical device. +struct wlr_vk_device *vulkan_device_create(struct wlr_vk_instance *ini, + VkPhysicalDevice phdev); +void vulkan_device_destroy(struct wlr_vk_device *dev); + +// Tries to find any memory bit for the given vulkan device that +// supports the given flags and is set in req_bits (e.g. if memory +// type 2 is ok, (req_bits & (1 << 2)) must not be 0. +// Set req_bits to 0xFFFFFFFF to allow all types. +int vulkan_find_mem_type(struct wlr_vk_device *device, + VkMemoryPropertyFlags flags, uint32_t req_bits); + +struct wlr_vk_format { + uint32_t drm; + VkFormat vk; + VkFormat vk_srgb; // sRGB version of the format, or 0 if nonexistent +}; + +extern const VkImageUsageFlags vulkan_render_usage, vulkan_shm_tex_usage, vulkan_dma_tex_usage; + +// Returns all known format mappings. +// Might not be supported for gpu/usecase. +const struct wlr_vk_format *vulkan_get_format_list(size_t *len); +const struct wlr_vk_format *vulkan_get_format_from_drm(uint32_t drm_format); + +struct wlr_vk_format_modifier_props { + VkDrmFormatModifierPropertiesEXT props; + VkExtent2D max_extent; + bool has_mutable_srgb; +}; + +struct wlr_vk_format_props { + struct wlr_vk_format format; + + struct { + VkExtent2D max_extent; + VkFormatFeatureFlags features; + bool has_mutable_srgb; + } shm; + + struct { + uint32_t render_mod_count; + struct wlr_vk_format_modifier_props *render_mods; + + uint32_t texture_mod_count; + struct wlr_vk_format_modifier_props *texture_mods; + } dmabuf; +}; + +void vulkan_format_props_query(struct wlr_vk_device *dev, + const struct wlr_vk_format *format); +const struct wlr_vk_format_modifier_props *vulkan_format_props_find_modifier( + const struct wlr_vk_format_props *props, uint64_t mod, bool render); +void vulkan_format_props_finish(struct wlr_vk_format_props *props); +bool vulkan_format_is_ycbcr(const struct wlr_vk_format *format); + +struct wlr_vk_pipeline_layout_key { + enum wlr_scale_filter_mode filter_mode; + + // for YCbCr pipelines only + struct { + const struct wlr_vk_format *format; + enum wlr_color_encoding encoding; + enum wlr_color_range range; + } ycbcr; +}; + +struct wlr_vk_pipeline_layout { + struct wlr_vk_pipeline_layout_key key; + + VkPipelineLayout vk; + VkDescriptorSetLayout ds; + VkSampler sampler; + + // for YCbCr pipelines only + struct { + VkSamplerYcbcrConversion conversion; + VkFormat format; + } ycbcr; + + struct wl_list link; // struct wlr_vk_renderer.pipeline_layouts +}; + +// Constants used to pick the color transform for the texture drawing +// fragment shader. Must match those in shaders/texture.frag +enum wlr_vk_texture_transform { + WLR_VK_TEXTURE_TRANSFORM_IDENTITY = 0, + WLR_VK_TEXTURE_TRANSFORM_SRGB = 1, + WLR_VK_TEXTURE_TRANSFORM_ST2084_PQ = 2, + WLR_VK_TEXTURE_TRANSFORM_GAMMA22 = 3, + WLR_VK_TEXTURE_TRANSFORM_BT1886 = 4, +}; + +enum wlr_vk_shader_source { + WLR_VK_SHADER_SOURCE_TEXTURE, + WLR_VK_SHADER_SOURCE_SINGLE_COLOR, +}; + +// Constants used to pick the color transform for the blend-to-output +// fragment shader. Must match those in shaders/output.frag +enum wlr_vk_output_transform { + WLR_VK_OUTPUT_TRANSFORM_IDENTITY = 0, + WLR_VK_OUTPUT_TRANSFORM_INVERSE_SRGB = 1, + WLR_VK_OUTPUT_TRANSFORM_INVERSE_ST2084_PQ = 2, + WLR_VK_OUTPUT_TRANSFORM_LUT3D = 3, + WLR_VK_OUTPUT_TRANSFORM_INVERSE_GAMMA22 = 4, + WLR_VK_OUTPUT_TRANSFORM_INVERSE_BT1886 = 5, +}; + +struct wlr_vk_pipeline_key { + struct wlr_vk_pipeline_layout_key layout; + enum wlr_vk_shader_source source; + enum wlr_render_blend_mode blend_mode; + + // only used if source is texture + enum wlr_vk_texture_transform texture_transform; +}; + +struct wlr_vk_pipeline { + struct wlr_vk_pipeline_key key; + + VkPipeline vk; + const struct wlr_vk_pipeline_layout *layout; + struct wlr_vk_render_format_setup *setup; + struct wl_list link; // struct wlr_vk_render_format_setup +}; + +// For each format we want to render, we need a separate renderpass +// and therefore also separate pipelines. +struct wlr_vk_render_format_setup { + struct wl_list link; // wlr_vk_renderer.render_format_setups + const struct wlr_vk_format *render_format; // used in renderpass + bool use_blending_buffer; + bool use_srgb; + VkRenderPass render_pass; + + VkPipeline output_pipe_identity; + VkPipeline output_pipe_srgb; + VkPipeline output_pipe_pq; + VkPipeline output_pipe_lut3d; + VkPipeline output_pipe_gamma22; + VkPipeline output_pipe_bt1886; + + struct wlr_vk_renderer *renderer; + struct wl_list pipelines; // struct wlr_vk_pipeline.link +}; + +// Final output framebuffer and image view +struct wlr_vk_render_buffer_out { + VkImageView image_view; + VkFramebuffer framebuffer; + bool transitioned; +}; + +// Renderer-internal representation of an wlr_buffer imported for rendering. +struct wlr_vk_render_buffer { + struct wlr_buffer *wlr_buffer; + struct wlr_addon addon; + struct wlr_vk_renderer *renderer; + struct wl_list link; // wlr_vk_renderer.buffers + + VkDeviceMemory memories[WLR_DMABUF_MAX_PLANES]; + uint32_t mem_count; + VkImage image; + + // Framebuffer and image view for rendering directly onto the buffer image, + // without any color transform. + struct { + struct wlr_vk_render_buffer_out out; + struct wlr_vk_render_format_setup *render_setup; + } linear; + + // Framebuffer and image view for rendering directly onto the buffer image. + // This requires that the image support an _SRGB VkFormat, and does + // not work with color transforms. + struct { + struct wlr_vk_render_buffer_out out; + struct wlr_vk_render_format_setup *render_setup; + } srgb; + + // Framebuffer, image view, and blending image to render indirectly + // onto the buffer image. This works for general image types and permits + // color transforms. + struct { + struct wlr_vk_render_buffer_out out; + struct wlr_vk_render_format_setup *render_setup; + + VkImage blend_image; + VkImageView blend_image_view; + VkDeviceMemory blend_memory; + VkDescriptorSet blend_descriptor_set; + struct wlr_vk_descriptor_pool *blend_attachment_pool; + bool blend_transitioned; + } two_pass; +}; + +bool vulkan_setup_one_pass_framebuffer(struct wlr_vk_render_buffer *buffer, + const struct wlr_dmabuf_attributes *dmabuf, bool srgb); +bool vulkan_setup_two_pass_framebuffer(struct wlr_vk_render_buffer *buffer, + const struct wlr_dmabuf_attributes *dmabuf); + +struct wlr_vk_command_buffer { + VkCommandBuffer vk; + bool recording; + uint64_t timeline_point; + // Textures to destroy after the command buffer completes + struct wl_list destroy_textures; // wlr_vk_texture.destroy_link + // Staging shared buffers to release after the command buffer completes + struct wl_list stage_buffers; // wlr_vk_shared_buffer.link + // Color transform to unref after the command buffer completes + struct wlr_color_transform *color_transform; + + // For DMA-BUF implicit sync interop, may be NULL + VkSemaphore binary_semaphore; + + struct wl_array wait_semaphores; // VkSemaphore +}; + +#define VULKAN_COMMAND_BUFFERS_CAP 64 + +// Vulkan wlr_renderer implementation on top of a wlr_vk_device. +struct wlr_vk_renderer { + struct wlr_renderer wlr_renderer; + struct wlr_backend *backend; + struct wlr_vk_device *dev; + + VkCommandPool command_pool; + + VkShaderModule vert_module; + VkShaderModule tex_frag_module; + VkShaderModule quad_frag_module; + VkShaderModule output_module; + + struct wl_list pipeline_layouts; // struct wlr_vk_pipeline_layout.link + + // for blend->output subpass + VkPipelineLayout output_pipe_layout; + VkDescriptorSetLayout output_ds_srgb_layout; + VkDescriptorSetLayout output_ds_lut3d_layout; + VkSampler output_sampler_lut3d; + // descriptor set indicating dummy 1x1x1 image, for use in the lut3d slot + VkDescriptorSet output_ds_lut3d_dummy; + struct wlr_vk_descriptor_pool *output_ds_lut3d_dummy_pool; + + size_t last_output_pool_size; + struct wl_list output_descriptor_pools; // wlr_vk_descriptor_pool.link + + // dummy sampler to bind when output shader is not using a lookup table + VkImage dummy3d_image; + VkDeviceMemory dummy3d_mem; + VkImageView dummy3d_image_view; + bool dummy3d_image_transitioned; + + VkSemaphore timeline_semaphore; + uint64_t timeline_point; + + size_t last_pool_size; + struct wl_list descriptor_pools; // wlr_vk_descriptor_pool.link + struct wl_list render_format_setups; // wlr_vk_render_format_setup.link + + + struct wl_list textures; // wlr_vk_texture.link + // Textures to return to foreign queue + struct wl_list foreign_textures; // wlr_vk_texture.foreign_link + + struct wl_list render_buffers; // wlr_vk_render_buffer.link + + struct wl_list color_transforms; // wlr_vk_color_transform.link + + // Pool of command buffers + struct wlr_vk_command_buffer command_buffers[VULKAN_COMMAND_BUFFERS_CAP]; + + struct { + struct wlr_vk_command_buffer *cb; + uint64_t last_timeline_point; + struct wl_list buffers; // wlr_vk_shared_buffer.link + } stage; + + struct { + bool initialized; + uint32_t drm_format; + uint32_t width, height; + VkImage dst_image; + VkDeviceMemory dst_img_memory; + } read_pixels_cache; +}; + +// vertex shader push constant range data +struct wlr_vk_vert_pcr_data { + float mat4[4][4]; + float uv_off[2]; + float uv_size[2]; +}; + +struct wlr_vk_frag_texture_pcr_data { + float matrix[4][4]; // only a 3x3 subset is used + float alpha; + float luminance_multiplier; +}; + +struct wlr_vk_frag_output_pcr_data { + float matrix[4][4]; // only a 3x3 subset is used + float lut_3d_offset; + float lut_3d_scale; +}; + +struct wlr_vk_texture_view { + struct wl_list link; // struct wlr_vk_texture.views + const struct wlr_vk_pipeline_layout *layout; + bool srgb; + + VkDescriptorSet ds; + VkImageView image_view; + struct wlr_vk_descriptor_pool *ds_pool; +}; + +struct wlr_vk_pipeline *setup_get_or_create_pipeline( + struct wlr_vk_render_format_setup *setup, + const struct wlr_vk_pipeline_key *key); +struct wlr_vk_pipeline_layout *get_or_create_pipeline_layout( + struct wlr_vk_renderer *renderer, + const struct wlr_vk_pipeline_layout_key *key); +struct wlr_vk_texture_view *vulkan_texture_get_or_create_view( + struct wlr_vk_texture *texture, + const struct wlr_vk_pipeline_layout *layout, bool srgb); + +// Creates a vulkan renderer for the given device. +struct wlr_renderer *vulkan_renderer_create_for_device(struct wlr_vk_device *dev); + +// stage utility - for uploading/retrieving data +// Gets an command buffer in recording state which is guaranteed to be +// executed before the next frame. +VkCommandBuffer vulkan_record_stage_cb(struct wlr_vk_renderer *renderer); + +// Submits the current stage command buffer and waits until it has +// finished execution. +bool vulkan_submit_stage_wait(struct wlr_vk_renderer *renderer); + +struct wlr_vk_render_pass_texture { + struct wlr_vk_texture *texture; + + struct wlr_drm_syncobj_timeline *wait_timeline; + uint64_t wait_point; +}; + +struct wlr_vk_render_pass { + struct wlr_render_pass base; + struct wlr_vk_renderer *renderer; + struct wlr_vk_render_buffer *render_buffer; + struct wlr_vk_render_buffer_out *render_buffer_out; + struct wlr_vk_render_format_setup *render_setup; + struct wlr_vk_command_buffer *command_buffer; + struct rect_union updated_region; + VkPipeline bound_pipeline; + float projection[9]; + bool failed; + bool two_pass; // rendering via intermediate blending buffer + struct wlr_color_transform *color_transform; + + struct wlr_drm_syncobj_timeline *signal_timeline; + uint64_t signal_point; + + struct wl_array textures; // struct wlr_vk_render_pass_texture +}; + +struct wlr_vk_render_pass *vulkan_begin_render_pass(struct wlr_vk_renderer *renderer, + struct wlr_vk_render_buffer *buffer, const struct wlr_buffer_pass_options *options); + +// Suballocates a buffer span with the given size that can be mapped +// and used as staging buffer. The allocation is implicitly released when the +// stage cb has finished execution. The start of the span will be a multiple +// of the given alignment. +struct wlr_vk_buffer_span vulkan_get_stage_span( + struct wlr_vk_renderer *renderer, VkDeviceSize size, + VkDeviceSize alignment); + +// Tries to allocate a texture descriptor set. Will additionally +// return the pool it was allocated from when successful (for freeing it later). +struct wlr_vk_descriptor_pool *vulkan_alloc_texture_ds( + struct wlr_vk_renderer *renderer, VkDescriptorSetLayout ds_layout, + VkDescriptorSet *ds); + +// Tries to allocate a descriptor set for the blending image. Will +// additionally return the pool it was allocated from when successful +// (for freeing it later). +struct wlr_vk_descriptor_pool *vulkan_alloc_blend_ds( + struct wlr_vk_renderer *renderer, VkDescriptorSet *ds); + +// Frees the given descriptor set from the pool its pool. +void vulkan_free_ds(struct wlr_vk_renderer *renderer, + struct wlr_vk_descriptor_pool *pool, VkDescriptorSet ds); +struct wlr_vk_format_props *vulkan_format_props_from_drm( + struct wlr_vk_device *dev, uint32_t drm_format); +struct wlr_vk_renderer *vulkan_get_renderer(struct wlr_renderer *r); + +struct wlr_vk_command_buffer *vulkan_acquire_command_buffer( + struct wlr_vk_renderer *renderer); +uint64_t vulkan_end_command_buffer(struct wlr_vk_command_buffer *cb, + struct wlr_vk_renderer *renderer); +void vulkan_reset_command_buffer(struct wlr_vk_command_buffer *cb); +bool vulkan_wait_command_buffer(struct wlr_vk_command_buffer *cb, + struct wlr_vk_renderer *renderer); + +bool vulkan_sync_render_pass_release(struct wlr_vk_renderer *renderer, + struct wlr_vk_render_pass *pass); +bool vulkan_sync_foreign_texture_acquire(struct wlr_vk_texture *texture, + int sync_file_fds[static WLR_DMABUF_MAX_PLANES]); +bool vulkan_sync_render_buffer_acquire(struct wlr_vk_render_buffer *render_buffer, + int sync_file_fds[static WLR_DMABUF_MAX_PLANES]); + +bool vulkan_read_pixels(struct wlr_vk_renderer *vk_renderer, + VkFormat src_format, VkImage src_image, + uint32_t drm_format, uint32_t stride, + uint32_t width, uint32_t height, uint32_t src_x, uint32_t src_y, + uint32_t dst_x, uint32_t dst_y, void *data); + +// State (e.g. image texture) associated with a surface. +struct wlr_vk_texture { + struct wlr_texture wlr_texture; + struct wlr_vk_renderer *renderer; + uint32_t mem_count; + VkDeviceMemory memories[WLR_DMABUF_MAX_PLANES]; + VkImage image; + const struct wlr_vk_format *format; + struct wlr_vk_command_buffer *last_used_cb; // to track when it can be destroyed + bool dmabuf_imported; + bool owned; // if dmabuf_imported: whether we have ownership of the image + bool transitioned; // if dma_imported: whether we transitioned it away from preinit + bool has_alpha; // whether the image is has alpha channel + bool using_mutable_srgb; // can be accessed through _SRGB format view + struct wl_list foreign_link; // wlr_vk_renderer.foreign_textures + struct wl_list destroy_link; // wlr_vk_command_buffer.destroy_textures + struct wl_list link; // wlr_vk_renderer.textures + + // If imported from a wlr_buffer + struct wlr_buffer *buffer; + struct wlr_addon buffer_addon; + + struct wl_list views; // struct wlr_vk_texture_view.link +}; + +struct wlr_vk_texture *vulkan_get_texture(struct wlr_texture *wlr_texture); +VkImage vulkan_import_dmabuf(struct wlr_vk_renderer *renderer, + const struct wlr_dmabuf_attributes *attribs, + VkDeviceMemory mems[static WLR_DMABUF_MAX_PLANES], uint32_t *n_mems, + bool for_render, bool *using_mutable_srgb); +struct wlr_texture *vulkan_texture_from_buffer( + struct wlr_renderer *wlr_renderer, struct wlr_buffer *buffer); +void vulkan_texture_destroy(struct wlr_vk_texture *texture); + +struct wlr_vk_descriptor_pool { + VkDescriptorPool pool; + uint32_t free; // number of textures that can be allocated + struct wl_list link; // wlr_vk_renderer.descriptor_pools +}; + +struct wlr_vk_allocation { + VkDeviceSize start; + VkDeviceSize size; +}; + +// List of suballocated staging buffers. +// Used to upload to/read from device local images. +struct wlr_vk_shared_buffer { + struct wl_list link; // wlr_vk_renderer.stage.buffers or wlr_vk_command_buffer.stage_buffers + VkBuffer buffer; + VkDeviceMemory memory; + VkDeviceSize buf_size; + void *cpu_mapping; + struct wl_array allocs; // struct wlr_vk_allocation + int64_t last_used_ms; +}; + +// Suballocated range on a buffer. +struct wlr_vk_buffer_span { + struct wlr_vk_shared_buffer *buffer; + struct wlr_vk_allocation alloc; +}; + + +// Prepared form for a color transform +struct wlr_vk_color_transform { + struct wlr_addon addon; // owned by: wlr_vk_renderer + struct wl_list link; // wlr_vk_renderer, list of all color transforms + + // if populated, carries the entire transform, other parameters are to be ignored + struct { + size_t dim; + VkImage image; + VkImageView image_view; + VkDeviceMemory memory; + VkDescriptorSet ds; + struct wlr_vk_descriptor_pool *ds_pool; + } lut_3d; + + float color_matrix[9]; + enum wlr_color_transfer_function inverse_eotf; +}; +void vk_color_transform_destroy(struct wlr_addon *addon); + +// util +const char *vulkan_strerror(VkResult err); +void vulkan_change_layout(VkCommandBuffer cb, VkImage img, + VkImageLayout ol, VkPipelineStageFlags srcs, VkAccessFlags srca, + VkImageLayout nl, VkPipelineStageFlags dsts, VkAccessFlags dsta); + +#if __STDC_VERSION__ >= 202311L + +#define wlr_vk_error(fmt, res, ...) wlr_log(WLR_ERROR, fmt ": %s (%d)", \ + vulkan_strerror(res), res __VA_OPT__(,) __VA_ARGS__) + +#else + +#define wlr_vk_error(fmt, res, ...) wlr_log(WLR_ERROR, fmt ": %s (%d)", \ + vulkan_strerror(res), res, ##__VA_ARGS__) + +#endif + +#endif // RENDER_VULKAN_H diff --git a/3rdparty/wlroots/include/render/wlr_renderer.h b/3rdparty/wlroots/include/render/wlr_renderer.h new file mode 100644 index 0000000000..f6661384b9 --- /dev/null +++ b/3rdparty/wlroots/include/render/wlr_renderer.h @@ -0,0 +1,17 @@ +#ifndef RENDER_WLR_RENDERER_H +#define RENDER_WLR_RENDERER_H + +#include + +/** + * Automatically select and create a renderer suitable for the DRM FD. + */ +struct wlr_renderer *renderer_autocreate_with_drm_fd(int drm_fd); +/** + * Get the supported render formats. Buffers allocated with a format from this + * list may be used with wlr_renderer_begin_buffer_pass(). + */ +const struct wlr_drm_format_set *wlr_renderer_get_render_formats( + struct wlr_renderer *renderer); + +#endif diff --git a/3rdparty/wlroots/include/types/wlr_buffer.h b/3rdparty/wlroots/include/types/wlr_buffer.h new file mode 100644 index 0000000000..45acf7a1d4 --- /dev/null +++ b/3rdparty/wlroots/include/types/wlr_buffer.h @@ -0,0 +1,74 @@ +#ifndef TYPES_WLR_BUFFER +#define TYPES_WLR_BUFFER + +#include + +/** + * A read-only buffer that holds a data pointer. + * + * This is suitable for passing raw pixel data to a function that accepts a + * wlr_buffer. + */ +struct wlr_readonly_data_buffer { + struct wlr_buffer base; + + const void *data; + uint32_t format; + size_t stride; + + void *saved_data; +}; + +/** + * Wraps a read-only data pointer into a wlr_buffer. The data pointer may be + * accessed until readonly_data_buffer_drop() is called. + */ +struct wlr_readonly_data_buffer *readonly_data_buffer_create(uint32_t format, + size_t stride, uint32_t width, uint32_t height, const void *data); +/** + * Drops ownership of the buffer (see wlr_buffer_drop() for more details) and + * perform a copy of the data pointer if a consumer still has the buffer locked. + */ +bool readonly_data_buffer_drop(struct wlr_readonly_data_buffer *buffer); + +struct wlr_dmabuf_buffer { + struct wlr_buffer base; + struct wlr_dmabuf_attributes dmabuf; + bool saved; +}; + +/** + * Wraps a DMA-BUF into a wlr_buffer. The DMA-BUF may be accessed until + * dmabuf_buffer_drop() is called. + */ +struct wlr_dmabuf_buffer *dmabuf_buffer_create( + struct wlr_dmabuf_attributes *dmabuf); +/** + * Drops ownership of the buffer (see wlr_buffer_drop() for more details) and + * takes a reference to the DMA-BUF (by dup'ing its file descriptors) if a + * consumer still has the buffer locked. + */ +bool dmabuf_buffer_drop(struct wlr_dmabuf_buffer *buffer); + +/** + * Creates a struct wlr_client_buffer from a given struct wlr_buffer by creating + * a texture from it, and copying its struct wl_resource. + */ +struct wlr_client_buffer *wlr_client_buffer_create(struct wlr_buffer *buffer, + struct wlr_renderer *renderer); +/** + * Try to update the buffer's content. + * + * Fails if there's more than one reference to the buffer or if the texture + * isn't mutable. + */ +bool wlr_client_buffer_apply_damage(struct wlr_client_buffer *client_buffer, + struct wlr_buffer *next, const pixman_region32_t *damage); + +/** + * Return the DRM format of the buffer. If this buffer isn't shared + * memory or a DMA-BUF, returns DRM_FORMAT_INVALID. + */ +uint32_t buffer_get_drm_format(struct wlr_buffer *buffer); + +#endif diff --git a/3rdparty/wlroots/include/types/wlr_data_device.h b/3rdparty/wlroots/include/types/wlr_data_device.h new file mode 100644 index 0000000000..99aff42819 --- /dev/null +++ b/3rdparty/wlroots/include/types/wlr_data_device.h @@ -0,0 +1,43 @@ +#ifndef TYPES_WLR_DATA_DEVICE_H +#define TYPES_WLR_DATA_DEVICE_H + +#include +#include + +#define DATA_DEVICE_ALL_ACTIONS (WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY | \ + WL_DATA_DEVICE_MANAGER_DND_ACTION_MOVE | \ + WL_DATA_DEVICE_MANAGER_DND_ACTION_ASK) + +struct wlr_client_data_source { + struct wlr_data_source source; + struct wlr_data_source_impl impl; + struct wl_resource *resource; + bool finalized; +}; + +extern const struct wlr_surface_role drag_icon_surface_role; + +struct wlr_data_offer *data_offer_create(struct wl_resource *device_resource, + struct wlr_data_source *source, enum wlr_data_offer_type type); +void data_offer_update_action(struct wlr_data_offer *offer); +void data_offer_destroy(struct wlr_data_offer *offer); + +struct wlr_client_data_source *client_data_source_create( + struct wl_client *client, uint32_t version, uint32_t id, + struct wl_list *resource_list); +struct wlr_client_data_source *client_data_source_from_resource( + struct wl_resource *resource); +void data_source_notify_finish(struct wlr_data_source *source); + +struct wlr_seat_client *seat_client_from_data_device_resource( + struct wl_resource *resource); +/** + * Creates a new wl_data_offer if there is a wl_data_source currently set as + * the seat selection and sends it to the seat client, followed by the + * wl_data_device.selection() event. If there is no current selection, the + * wl_data_device.selection() event will carry a NULL wl_data_offer. If the + * client does not have a wl_data_device for the seat nothing will be done. + */ +void seat_client_send_selection(struct wlr_seat_client *seat_client); + +#endif diff --git a/3rdparty/wlroots/include/types/wlr_keyboard.h b/3rdparty/wlroots/include/types/wlr_keyboard.h new file mode 100644 index 0000000000..7cd26e8a59 --- /dev/null +++ b/3rdparty/wlroots/include/types/wlr_keyboard.h @@ -0,0 +1,8 @@ +#include + +void keyboard_key_update(struct wlr_keyboard *keyboard, + struct wlr_keyboard_key_event *event); + +bool keyboard_modifier_update(struct wlr_keyboard *keyboard); + +void keyboard_led_update(struct wlr_keyboard *keyboard); diff --git a/3rdparty/wlroots/include/types/wlr_output.h b/3rdparty/wlroots/include/types/wlr_output.h new file mode 100644 index 0000000000..fdbffaf9d4 --- /dev/null +++ b/3rdparty/wlroots/include/types/wlr_output.h @@ -0,0 +1,39 @@ +#ifndef TYPES_WLR_OUTPUT_H +#define TYPES_WLR_OUTPUT_H + +#include +#include + +void output_pending_resolution(struct wlr_output *output, + const struct wlr_output_state *state, int *width, int *height); +bool output_pending_enabled(struct wlr_output *output, + const struct wlr_output_state *state); +const struct wlr_output_image_description *output_pending_image_description( + struct wlr_output *output, const struct wlr_output_state *state); + +bool output_pick_format(struct wlr_output *output, + const struct wlr_drm_format_set *display_formats, + struct wlr_drm_format *format, uint32_t fmt); +bool output_ensure_buffer(struct wlr_output *output, + struct wlr_output_state *state, bool *new_back_buffer); + +bool output_cursor_set_texture(struct wlr_output_cursor *cursor, + struct wlr_texture *texture, bool own_texture, const struct wlr_fbox *src_box, + int dst_width, int dst_height, enum wl_output_transform transform, + int32_t hotspot_x, int32_t hotspot_y, struct wlr_drm_syncobj_timeline *wait_timeline, + uint64_t wait_point); +bool output_cursor_refresh_color_transform(struct wlr_output_cursor *cursor, + const struct wlr_output_image_description *img_desc); + +void output_defer_present(struct wlr_output *output, struct wlr_output_event_present event); + +bool output_prepare_commit(struct wlr_output *output, const struct wlr_output_state *state); +void output_apply_commit(struct wlr_output *output, const struct wlr_output_state *state); +void output_send_commit_event(struct wlr_output *output, const struct wlr_output_state *state); + +void output_state_get_buffer_src_box(const struct wlr_output_state *state, + struct wlr_fbox *out); +void output_state_get_buffer_dst_box(const struct wlr_output_state *state, + struct wlr_box *out); + +#endif diff --git a/3rdparty/wlroots/include/types/wlr_region.h b/3rdparty/wlroots/include/types/wlr_region.h new file mode 100644 index 0000000000..a44a9f09a5 --- /dev/null +++ b/3rdparty/wlroots/include/types/wlr_region.h @@ -0,0 +1,14 @@ +#ifndef TYPES_WLR_REGION_H +#define TYPES_WLR_REGION_H + +#include + +struct wl_client; + +/* + * Creates a new region resource with the provided new ID. + */ +struct wl_resource *region_create(struct wl_client *client, + uint32_t version, uint32_t id); + +#endif diff --git a/3rdparty/wlroots/include/types/wlr_scene.h b/3rdparty/wlroots/include/types/wlr_scene.h new file mode 100644 index 0000000000..c4b40cdd0c --- /dev/null +++ b/3rdparty/wlroots/include/types/wlr_scene.h @@ -0,0 +1,12 @@ +#ifndef TYPES_WLR_SCENE_H +#define TYPES_WLR_SCENE_H + +#include + +struct wlr_scene *scene_node_get_root(struct wlr_scene_node *node); + +void scene_node_get_size(struct wlr_scene_node *node, int *width, int *height); + +void scene_surface_set_clip(struct wlr_scene_surface *surface, struct wlr_box *clip); + +#endif diff --git a/3rdparty/wlroots/include/types/wlr_seat.h b/3rdparty/wlroots/include/types/wlr_seat.h new file mode 100644 index 0000000000..844faba0d4 --- /dev/null +++ b/3rdparty/wlroots/include/types/wlr_seat.h @@ -0,0 +1,33 @@ +#ifndef TYPES_WLR_SEAT_H +#define TYPES_WLR_SEAT_H + +#include +#include + +extern const struct wlr_pointer_grab_interface default_pointer_grab_impl; +extern const struct wlr_keyboard_grab_interface default_keyboard_grab_impl; +extern const struct wlr_touch_grab_interface default_touch_grab_impl; + +void seat_client_create_pointer(struct wlr_seat_client *seat_client, + uint32_t version, uint32_t id); +void seat_client_create_inert_pointer(struct wl_client *client, + uint32_t version, uint32_t id); +void seat_client_destroy_pointer(struct wl_resource *resource); +void seat_client_send_pointer_leave_raw(struct wlr_seat_client *seat_client, + struct wlr_surface *surface); + +void seat_client_create_keyboard(struct wlr_seat_client *seat_client, + uint32_t version, uint32_t id); +void seat_client_create_inert_keyboard(struct wl_client *client, + uint32_t version, uint32_t id); +void seat_client_destroy_keyboard(struct wl_resource *resource); +void seat_client_send_keyboard_leave_raw(struct wlr_seat_client *seat_client, + struct wlr_surface *surface); + +void seat_client_create_touch(struct wlr_seat_client *seat_client, + uint32_t version, uint32_t id); +void seat_client_create_inert_touch(struct wl_client *client, + uint32_t version, uint32_t id); +void seat_client_destroy_touch(struct wl_resource *resource); + +#endif diff --git a/3rdparty/wlroots/include/types/wlr_subcompositor.h b/3rdparty/wlroots/include/types/wlr_subcompositor.h new file mode 100644 index 0000000000..147b2838c7 --- /dev/null +++ b/3rdparty/wlroots/include/types/wlr_subcompositor.h @@ -0,0 +1,9 @@ +#ifndef TYPES_WLR_SUBCOMPOSITOR_H +#define TYPES_WLR_SUBCOMPOSITOR_H + +#include + +void subsurface_consider_map(struct wlr_subsurface *subsurface); +void subsurface_handle_parent_commit(struct wlr_subsurface *subsurface); + +#endif diff --git a/3rdparty/wlroots/include/types/wlr_tablet_v2.h b/3rdparty/wlroots/include/types/wlr_tablet_v2.h new file mode 100644 index 0000000000..af6a25838d --- /dev/null +++ b/3rdparty/wlroots/include/types/wlr_tablet_v2.h @@ -0,0 +1,94 @@ +#ifndef TYPES_WLR_TABLET_V2_H +#define TYPES_WLR_TABLET_V2_H + +#include "tablet-v2-protocol.h" +#include +#include + +struct wlr_tablet_seat_v2 { + struct wl_list link; // wlr_tablet_manager_v2.seats + struct wlr_seat *wlr_seat; + struct wlr_tablet_manager_v2 *manager; + + struct wl_list tablets; // wlr_tablet_v2_tablet.link + struct wl_list tools; + struct wl_list pads; + + struct wl_list clients; // wlr_tablet_seat_v2_client.link + + struct wl_listener seat_destroy; +}; + +struct wlr_tablet_seat_client_v2 { + struct wl_list seat_link; + struct wl_list client_link; + struct wl_client *wl_client; + struct wl_resource *resource; + + struct wlr_tablet_manager_client_v2 *client; + struct wlr_seat_client *seat_client; + + struct wl_listener seat_client_destroy; + + struct wl_list tools; // wlr_tablet_tool_client_v2.link + struct wl_list tablets; // wlr_tablet_client_v2.link + struct wl_list pads; // wlr_tablet_pad_client_v2.link +}; + +struct wlr_tablet_client_v2 { + struct wl_list seat_link; // wlr_tablet_seat_client_v2.tablet + struct wl_list tablet_link; // wlr_tablet_v2_tablet.clients + struct wl_client *client; + struct wl_resource *resource; +}; + +struct wlr_tablet_pad_client_v2 { + struct wl_list seat_link; + struct wl_list pad_link; + struct wl_client *client; + struct wl_resource *resource; + struct wlr_tablet_v2_tablet_pad *pad; + struct wlr_tablet_seat_client_v2 *seat; + + size_t button_count; + + size_t group_count; + struct wl_resource **groups; + + size_t ring_count; + struct wl_resource **rings; + + size_t strip_count; + struct wl_resource **strips; +}; + +struct wlr_tablet_tool_client_v2 { + struct wl_list seat_link; + struct wl_list tool_link; + struct wl_client *client; + struct wl_resource *resource; + struct wlr_tablet_v2_tablet_tool *tool; + struct wlr_tablet_seat_client_v2 *seat; + + struct wl_event_source *frame_source; +}; + +struct wlr_tablet_client_v2 *tablet_client_from_resource(struct wl_resource *resource); +void destroy_tablet_v2(struct wl_resource *resource); +void add_tablet_client(struct wlr_tablet_seat_client_v2 *seat, struct wlr_tablet_v2_tablet *tablet); + +void destroy_tablet_pad_v2(struct wl_resource *resource); +struct wlr_tablet_pad_client_v2 *tablet_pad_client_from_resource(struct wl_resource *resource); +void add_tablet_pad_client(struct wlr_tablet_seat_client_v2 *seat, struct wlr_tablet_v2_tablet_pad *pad); + +void destroy_tablet_tool_v2(struct wl_resource *resource); +struct wlr_tablet_tool_client_v2 *tablet_tool_client_from_resource(struct wl_resource *resource); +void add_tablet_tool_client(struct wlr_tablet_seat_client_v2 *seat, struct wlr_tablet_v2_tablet_tool *tool); + +struct wlr_tablet_seat_client_v2 *tablet_seat_client_from_resource(struct wl_resource *resource); +void tablet_seat_client_v2_destroy(struct wl_resource *resource); +struct wlr_tablet_seat_v2 *get_or_create_tablet_seat( + struct wlr_tablet_manager_v2 *manager, + struct wlr_seat *wlr_seat); + +#endif /* TYPES_WLR_TABLET_V2_H */ diff --git a/3rdparty/wlroots/include/types/wlr_xdg_shell.h b/3rdparty/wlroots/include/types/wlr_xdg_shell.h new file mode 100644 index 0000000000..1b4c89c2f8 --- /dev/null +++ b/3rdparty/wlroots/include/types/wlr_xdg_shell.h @@ -0,0 +1,39 @@ +#ifndef TYPES_WLR_XDG_SHELL_H +#define TYPES_WLR_XDG_SHELL_H + +#include +#include +#include "xdg-shell-protocol.h" + +void create_xdg_surface(struct wlr_xdg_client *client, struct wlr_surface *wlr_surface, + uint32_t id); +void destroy_xdg_surface(struct wlr_xdg_surface *surface); + +bool set_xdg_surface_role(struct wlr_xdg_surface *surface, enum wlr_xdg_surface_role role); +void set_xdg_surface_role_object(struct wlr_xdg_surface *surface, + struct wl_resource *role_resource); + +void create_xdg_positioner(struct wlr_xdg_client *client, uint32_t id); + +void create_xdg_popup(struct wlr_xdg_surface *surface, + struct wlr_xdg_surface *parent, + struct wlr_xdg_positioner *positioner, uint32_t id); +void reset_xdg_popup(struct wlr_xdg_popup *popup); +void destroy_xdg_popup(struct wlr_xdg_popup *popup); +void handle_xdg_popup_client_commit(struct wlr_xdg_popup *popup); +struct wlr_xdg_popup_configure *send_xdg_popup_configure( + struct wlr_xdg_popup *popup); +void handle_xdg_popup_ack_configure(struct wlr_xdg_popup *popup, + struct wlr_xdg_popup_configure *configure); + +void create_xdg_toplevel(struct wlr_xdg_surface *surface, + uint32_t id); +void reset_xdg_toplevel(struct wlr_xdg_toplevel *toplevel); +void destroy_xdg_toplevel(struct wlr_xdg_toplevel *toplevel); +void handle_xdg_toplevel_client_commit(struct wlr_xdg_toplevel *toplevel); +struct wlr_xdg_toplevel_configure *send_xdg_toplevel_configure( + struct wlr_xdg_toplevel *toplevel); +void handle_xdg_toplevel_ack_configure(struct wlr_xdg_toplevel *toplevel, + struct wlr_xdg_toplevel_configure *configure); + +#endif diff --git a/3rdparty/wlroots/include/util/array.h b/3rdparty/wlroots/include/util/array.h new file mode 100644 index 0000000000..a51bdb640a --- /dev/null +++ b/3rdparty/wlroots/include/util/array.h @@ -0,0 +1,18 @@ +#ifndef UTIL_ARRAY_H +#define UTIL_ARRAY_H + +#include +#include +#include + +/** + * Remove a chunk of memory of the specified size at the specified offset. + */ +void array_remove_at(struct wl_array *arr, size_t offset, size_t size); + +/** + * Grow or shrink the array to fit the specifized size. + */ +bool array_realloc(struct wl_array *arr, size_t size); + +#endif diff --git a/3rdparty/wlroots/include/util/env.h b/3rdparty/wlroots/include/util/env.h new file mode 100644 index 0000000000..e271f4bfdf --- /dev/null +++ b/3rdparty/wlroots/include/util/env.h @@ -0,0 +1,23 @@ +#ifndef UTIL_ENV_H +#define UTIL_ENV_H + +#include +#include + +/** + * Parse a bool from an environment variable. + * + * On success, the parsed value is returned. On error, false is returned. + */ +bool env_parse_bool(const char *option); + +/** + * Pick a choice from an environment variable. + * + * On success, the choice index is returned. On error, zero is returned. + * + * switches is a NULL-terminated array. + */ +size_t env_parse_switch(const char *option, const char **switches); + +#endif diff --git a/3rdparty/wlroots/include/util/fd.h b/3rdparty/wlroots/include/util/fd.h new file mode 100644 index 0000000000..9a353bf8b7 --- /dev/null +++ b/3rdparty/wlroots/include/util/fd.h @@ -0,0 +1,8 @@ +#ifndef UTIL_FD_H +#define UTIL_FD_H + +#include + +bool set_cloexec(int fd, bool cloexec); + +#endif diff --git a/3rdparty/wlroots/include/util/global.h b/3rdparty/wlroots/include/util/global.h new file mode 100644 index 0000000000..1c979ab110 --- /dev/null +++ b/3rdparty/wlroots/include/util/global.h @@ -0,0 +1,14 @@ +#ifndef UTIL_GLOBAL_H +#define UTIL_GLOBAL_H + +#include + +/** + * Destroy a transient global. + * + * Globals that are created and destroyed on the fly need special handling to + * prevent race conditions with wl_registry. Use this function to destroy them. + */ +void wlr_global_destroy_safe(struct wl_global *global); + +#endif diff --git a/3rdparty/wlroots/include/util/matrix.h b/3rdparty/wlroots/include/util/matrix.h new file mode 100644 index 0000000000..c45c99a068 --- /dev/null +++ b/3rdparty/wlroots/include/util/matrix.h @@ -0,0 +1,49 @@ +#ifndef UTIL_MATRIX_H +#define UTIL_MATRIX_H + +#include + +struct wlr_box; + +/** Writes the identity matrix into mat */ +void wlr_matrix_identity(float mat[static 9]); + +/** mat ← a × b */ +void wlr_matrix_multiply(float mat[static 9], const float a[static 9], + const float b[static 9]); + +/** Writes a 2D translation matrix to mat of magnitude (x, y) */ +void wlr_matrix_translate(float mat[static 9], float x, float y); + +/** Writes a 2D scale matrix to mat of magnitude (x, y) */ +void wlr_matrix_scale(float mat[static 9], float x, float y); + +/** Writes a transformation matrix which applies the specified + * wl_output_transform to mat */ +void wlr_matrix_transform(float mat[static 9], + enum wl_output_transform transform); + +/** Shortcut for the various matrix operations involved in projecting the + * specified wlr_box onto a given orthographic projection with a given + * rotation. The result is written to mat, which can be applied to each + * coordinate of the box to get a new coordinate from [-1,1]. */ +void wlr_matrix_project_box(float mat[static 9], const struct wlr_box *box, + enum wl_output_transform transform, const float projection[static 9]); + +/** + * Writes a 2D orthographic projection matrix to mat of (width, height) with a + * specified wl_output_transform. + * + * Equivalent to glOrtho(0, width, 0, height, 1, -1) with the transform applied. + */ +void matrix_projection(float mat[static 9], int width, int height, + enum wl_output_transform transform); + +/** + * Compute the inverse of a matrix. + * + * The matrix needs to be inversible. + */ +void matrix_invert(float out[static 9], float m[static 9]); + +#endif diff --git a/3rdparty/wlroots/include/util/mem.h b/3rdparty/wlroots/include/util/mem.h new file mode 100644 index 0000000000..8971d20871 --- /dev/null +++ b/3rdparty/wlroots/include/util/mem.h @@ -0,0 +1,14 @@ +#ifndef UTIL_MEM_H +#define UTIL_MEM_H + +#include +#include + +/** + * Allocate a new block of memory and copy *src to it, then store the address + * of the new allocation in *out. Returns true if it worked, or false if + * allocation failed. + */ +bool memdup(void *out, const void *src, size_t size); + +#endif // UTIL_MEM_H diff --git a/3rdparty/wlroots/include/util/rect_union.h b/3rdparty/wlroots/include/util/rect_union.h new file mode 100644 index 0000000000..2d74f94d53 --- /dev/null +++ b/3rdparty/wlroots/include/util/rect_union.h @@ -0,0 +1,76 @@ +#ifndef UTIL_RECT_UNION_H +#define UTIL_RECT_UNION_H + +#include +#include +#include +#include + +/** + * `struct rect_union` is a data structure to efficiently accumulate a number + * of rectangles and then, when needed, compute a disjoint cover of their union. + * (That is: produce a list of disjoint rectangles which covers every point + * that was contained in one of the added rectangles.) + * + * Add rectangles to the union with `rect_union_add()`; to compute the disjoint + * union, run `rect_union_evaluate()`, which will place the result in `.region`. + * If there were any allocation failures, `.region` will instead contain the + * bounding box for the entire list of rectangles. + * + * Example usage: + * + * struct rect_union r; + * rect_union_init(&r); + * for (j in ...) { + * rect_union_add(&r, box[j]); + * } + * const pixman_region32_t *reg = rect_union_evaluate(&r); + * int nboxes; + * pixman_box32_t *boxes = pixman_region32_rectangles(reg, nboxes); + * for (int i = 0; i < nboxes; i++) { + * do_stuff(boxes[i]); + * } + * rect_union_destroy(&r); + * + */ +struct rect_union { + pixman_box32_t bounding_box; // Always up-to-date bounding box + pixman_region32_t region; // Updated only on _evaluate() + + struct wl_array unsorted; // pixman_box32_t + bool alloc_failure; // If this is true, fall back to computing a bounding box +}; + +/** + * Initialize *r, disregarding any previous contents. + */ +void rect_union_init(struct rect_union *r); + +/** + * Free heap data associated with *r; should only be called after rect_union_init. + * Leaves *r in an invalid state. + */ +void rect_union_finish(struct rect_union *r); + +/** + * Add a rectangle to the union. If `box` is empty or invalid (x2 > x1 || y2 > y1), + * do nothing. + * + * Amortized time: O(1) + */ +void rect_union_add(struct rect_union *r, pixman_box32_t box); + +/** + * Compute an exact cover of the rectangles added so far, and return + * a pointer to a pixman_region32_t giving that cover. The pointer will + * remain valid until the next time *r is modified. If there was an allocation + * failure, this function may return a single-rectangle bounding box instead. + * + * This may be called multiple times and interleaved with rect_union_add(). + * + * Worst case time: O(t^2), where t is the number of rectangles in the list. + * Best case time: O(t), if rectangles are disjoint and have y-x band structure + */ +const pixman_region32_t *rect_union_evaluate(struct rect_union *r); + +#endif diff --git a/3rdparty/wlroots/include/util/set.h b/3rdparty/wlroots/include/util/set.h new file mode 100644 index 0000000000..d6330108a5 --- /dev/null +++ b/3rdparty/wlroots/include/util/set.h @@ -0,0 +1,29 @@ +#ifndef UTIL_SET_H +#define UTIL_SET_H + +#include +#include +#include + +/** + * Add target to values. + * + * Target is added to the end of the set. + * + * Returns the index of target, or -1 if the set is full or target already + * exists. + */ +ssize_t set_add(uint32_t values[], size_t *len, size_t cap, uint32_t target); + +/** + * Remove target from values. + * + * When target is removed, the last element of the set is moved to where + * target was. + * + * Returns the previous index of target, or -1 if target wasn't in values. + */ +ssize_t set_remove(uint32_t values[], size_t *len, size_t cap, uint32_t target); + +#endif + diff --git a/3rdparty/wlroots/include/util/shm.h b/3rdparty/wlroots/include/util/shm.h new file mode 100644 index 0000000000..3beabcabcb --- /dev/null +++ b/3rdparty/wlroots/include/util/shm.h @@ -0,0 +1,11 @@ +#ifndef UTIL_SHM_H +#define UTIL_SHM_H + +#include +#include + +int create_shm_file(void); +int allocate_shm_file(size_t size); +bool allocate_shm_file_pair(size_t size, int *rw_fd, int *ro_fd); + +#endif diff --git a/3rdparty/wlroots/include/util/time.h b/3rdparty/wlroots/include/util/time.h new file mode 100644 index 0000000000..dd164bf2f2 --- /dev/null +++ b/3rdparty/wlroots/include/util/time.h @@ -0,0 +1,35 @@ +#ifndef UTIL_TIME_H +#define UTIL_TIME_H + +#include +#include + +static const long NSEC_PER_SEC = 1000000000; + +/** + * Get the current time, in milliseconds. + */ +int64_t get_current_time_msec(void); + +/** + * Convert a timespec to milliseconds. + */ +int64_t timespec_to_msec(const struct timespec *a); + +/** + * Convert a timespec to nanoseconds. + */ +int64_t timespec_to_nsec(const struct timespec *a); + +/** + * Convert nanoseconds to a timespec. + */ +void timespec_from_nsec(struct timespec *r, int64_t nsec); + +/** + * Subtracts timespec `b` from timespec `a`, and stores the difference in `r`. + */ +void timespec_sub(struct timespec *r, const struct timespec *a, + const struct timespec *b); + +#endif diff --git a/3rdparty/wlroots/include/util/token.h b/3rdparty/wlroots/include/util/token.h new file mode 100644 index 0000000000..3aef69cfeb --- /dev/null +++ b/3rdparty/wlroots/include/util/token.h @@ -0,0 +1,16 @@ +#ifndef UTIL_TOKEN_H +#define UTIL_TOKEN_H + +#include + +/** + * Number of bytes used by a token, including the terminating zero byte. + */ +#define TOKEN_SIZE 33 + +/** + * Generate a random token string. + */ +bool generate_token(char out[static TOKEN_SIZE]); + +#endif diff --git a/3rdparty/wlroots/include/util/utf8.h b/3rdparty/wlroots/include/util/utf8.h new file mode 100644 index 0000000000..4d5172c786 --- /dev/null +++ b/3rdparty/wlroots/include/util/utf8.h @@ -0,0 +1,11 @@ +#ifndef UTIL_UTF8_H +#define UTIL_UTF8_H + +#include + +/** + * Return true if and only if the string is a valid UTF-8 sequence. + */ +bool is_utf8(const char *string); + +#endif diff --git a/3rdparty/wlroots/include/wlr/backend.h b/3rdparty/wlroots/include/wlr/backend.h new file mode 100644 index 0000000000..31588ca9c9 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/backend.h @@ -0,0 +1,103 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_BACKEND_H +#define WLR_BACKEND_H + +#include +#include + +struct wlr_session; +struct wlr_backend_impl; + +/** + * Per-output state for wlr_backend_test() and wlr_backend_commit(). + */ +struct wlr_backend_output_state { + struct wlr_output *output; + struct wlr_output_state base; +}; + +/** + * A backend provides a set of input and output devices. + * + * Buffer capabilities and features can change over the lifetime of a backend, + * for instance when a child backend is added to a multi-backend. + */ +struct wlr_backend { + const struct wlr_backend_impl *impl; + + // Bitfield of supported buffer capabilities (see enum wlr_buffer_cap) + uint32_t buffer_caps; + + struct { + // Whether wait/signal timelines are supported in output commits + bool timeline; + } features; + + struct { + /** Raised when destroyed */ + struct wl_signal destroy; + /** Raised when new inputs are added, passed the struct wlr_input_device */ + struct wl_signal new_input; + /** Raised when new outputs are added, passed the struct wlr_output */ + struct wl_signal new_output; + } events; +}; + +/** + * Automatically initializes the most suitable backend given the environment. + * Will always return a multi-backend. The backend is created but not started. + * Returns NULL on failure. + * + * If session_ptr is not NULL, it's populated with the session which has been + * created with the backend, if any. + * + * The multi-backend will be destroyed if one of the primary underlying + * backends is destroyed (e.g. if the primary DRM device is unplugged). + */ +struct wlr_backend *wlr_backend_autocreate(struct wl_event_loop *loop, + struct wlr_session **session_ptr); +/** + * Start the backend. This may signal new_input or new_output immediately, but + * may also wait until the event loop is started. Returns false on failure. + */ +bool wlr_backend_start(struct wlr_backend *backend); +/** + * Destroy the backend and clean up all of its resources. Normally called + * automatically when the event loop is destroyed. + */ +void wlr_backend_destroy(struct wlr_backend *backend); +/** + * Returns the DRM node file descriptor used by the backend's underlying + * platform. Can be used by consumers for additional rendering operations. + * The consumer must not close the file descriptor since the backend continues + * to have ownership of it. + */ +int wlr_backend_get_drm_fd(struct wlr_backend *backend); + +/** + * Atomically test a new configuration for multiple outputs. + * + * Some backends (e.g. DRM) have global backend-wide limitations. This function + * can be used to check whether changes across multiple outputs are supported by + * the backend. + */ +bool wlr_backend_test(struct wlr_backend *backend, + const struct wlr_backend_output_state *states, size_t states_len); +/** + * Atomically apply a new configuration for multiple outputs. + * + * There is no guarantee that the changes will be applied atomically. Users + * should call wlr_backend_test() first to check that the new state is supported + * by the backend. + */ +bool wlr_backend_commit(struct wlr_backend *backend, + const struct wlr_backend_output_state *states, size_t states_len); + +#endif diff --git a/3rdparty/wlroots/include/wlr/backend/drm.h b/3rdparty/wlroots/include/wlr/backend/drm.h new file mode 100644 index 0000000000..3ca6390abb --- /dev/null +++ b/3rdparty/wlroots/include/wlr/backend/drm.h @@ -0,0 +1,103 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_BACKEND_DRM_H +#define WLR_BACKEND_DRM_H + +#include +#include +#include +#include + +struct wlr_drm_backend; +typedef struct _drmModeModeInfo drmModeModeInfo; + +struct wlr_drm_lease { + int fd; + uint32_t lessee_id; + struct wlr_drm_backend *backend; + + struct { + struct wl_signal destroy; + } events; + + void *data; +}; + +/** + * Creates a DRM backend using the specified GPU file descriptor (typically from + * a device node in /dev/dri). + * + * To slave this to another DRM backend, pass it as the parent (which _must_ be + * a DRM backend, other kinds of backends raise SIGABRT). + */ +struct wlr_backend *wlr_drm_backend_create(struct wlr_session *session, + struct wlr_device *dev, struct wlr_backend *parent); + +bool wlr_backend_is_drm(struct wlr_backend *backend); +bool wlr_output_is_drm(struct wlr_output *output); + +/** + * Get the parent DRM backend, if any. + */ +struct wlr_backend *wlr_drm_backend_get_parent(struct wlr_backend *backend); + +/** + * Get the KMS connector object ID. + */ +uint32_t wlr_drm_connector_get_id(struct wlr_output *output); + +/** + * Tries to open non-master DRM FD. The compositor must not call drmSetMaster() + * on the returned FD. + * + * Returns a valid opened DRM FD, or -1 on error. + */ +int wlr_drm_backend_get_non_master_fd(struct wlr_backend *backend); + +/** + * Leases the given outputs to the caller. The outputs must be from the + * associated DRM backend. + * + * Returns NULL on error. + */ +struct wlr_drm_lease *wlr_drm_create_lease(struct wlr_output **outputs, + size_t n_outputs, int *lease_fd); + +/** + * Terminates and destroys a given lease. + * + * The outputs will be owned again by the backend. + */ +void wlr_drm_lease_terminate(struct wlr_drm_lease *lease); + +/** + * Add mode to the list of available modes. + */ +struct wlr_output_mode *wlr_drm_connector_add_mode(struct wlr_output *output, + const drmModeModeInfo *mode); + +/** + * Get the raw DRM mode information from a struct wlr_output_mode. + * + * The mode passed in must belong to a DRM output. + */ +const drmModeModeInfo *wlr_drm_mode_get_info(struct wlr_output_mode *mode); + +/** + * Get the connector's panel orientation. + * + * On some devices the panel is mounted in the casing in such a way that the + * top side of the panel does not match with the top side of the device. This + * function returns the output transform which needs to be applied to compensate + * for this. + */ +enum wl_output_transform wlr_drm_connector_get_panel_orientation( + struct wlr_output *output); + +#endif diff --git a/3rdparty/wlroots/include/wlr/backend/headless.h b/3rdparty/wlroots/include/wlr/backend/headless.h new file mode 100644 index 0000000000..126f1ff215 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/backend/headless.h @@ -0,0 +1,31 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_BACKEND_HEADLESS_H +#define WLR_BACKEND_HEADLESS_H + +#include +#include + +/** + * Creates a headless backend. A headless backend has no outputs or inputs by + * default. + */ +struct wlr_backend *wlr_headless_backend_create(struct wl_event_loop *loop); +/** + * Create a new headless output. + * + * The buffers presented on the output won't be displayed to the user. + */ +struct wlr_output *wlr_headless_add_output(struct wlr_backend *backend, + unsigned int width, unsigned int height); + +bool wlr_backend_is_headless(struct wlr_backend *backend); +bool wlr_output_is_headless(struct wlr_output *output); + +#endif diff --git a/3rdparty/wlroots/include/wlr/backend/interface.h b/3rdparty/wlroots/include/wlr/backend/interface.h new file mode 100644 index 0000000000..648fa66e86 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/backend/interface.h @@ -0,0 +1,38 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_BACKEND_INTERFACE_H +#define WLR_BACKEND_INTERFACE_H + +#include +#include + +struct wlr_output_state; + +struct wlr_backend_impl { + bool (*start)(struct wlr_backend *backend); + void (*destroy)(struct wlr_backend *backend); + int (*get_drm_fd)(struct wlr_backend *backend); + bool (*test)(struct wlr_backend *backend, + const struct wlr_backend_output_state *states, size_t states_len); + bool (*commit)(struct wlr_backend *backend, + const struct wlr_backend_output_state *states, size_t states_len); +}; + +/** + * Initializes common state on a struct wlr_backend and sets the implementation + * to the provided struct wlr_backend_impl reference. + */ +void wlr_backend_init(struct wlr_backend *backend, + const struct wlr_backend_impl *impl); +/** + * Emit the destroy event and clean up common backend state. + */ +void wlr_backend_finish(struct wlr_backend *backend); + +#endif diff --git a/3rdparty/wlroots/include/wlr/backend/libinput.h b/3rdparty/wlroots/include/wlr/backend/libinput.h new file mode 100644 index 0000000000..2a4e1996ee --- /dev/null +++ b/3rdparty/wlroots/include/wlr/backend/libinput.h @@ -0,0 +1,35 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_BACKEND_LIBINPUT_H +#define WLR_BACKEND_LIBINPUT_H + +#include +#include +#include +#include + +struct wlr_input_device; +struct wlr_tablet_tool; + +struct wlr_backend *wlr_libinput_backend_create(struct wlr_session *session); +/** + * Gets the underlying struct libinput_device handle for the given input device. + */ +struct libinput_device *wlr_libinput_get_device_handle( + struct wlr_input_device *dev); +/** + * Gets the underlying struct libinput_tablet_tool handle for the given tablet tool. + */ +struct libinput_tablet_tool *wlr_libinput_get_tablet_tool_handle( + struct wlr_tablet_tool *wlr_tablet_tool); + +bool wlr_backend_is_libinput(struct wlr_backend *backend); +bool wlr_input_device_is_libinput(struct wlr_input_device *device); + +#endif diff --git a/3rdparty/wlroots/include/wlr/backend/multi.h b/3rdparty/wlroots/include/wlr/backend/multi.h new file mode 100644 index 0000000000..c4322d98b0 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/backend/multi.h @@ -0,0 +1,35 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_BACKEND_MULTI_H +#define WLR_BACKEND_MULTI_H + +#include + +/** + * Creates a multi-backend. Multi-backends wrap an arbitrary number of backends + * and aggregate their new_output/new_input signals. + */ +struct wlr_backend *wlr_multi_backend_create(struct wl_event_loop *loop); +/** + * Adds the given backend to the multi backend. This should be done before the + * new backend is started. + */ +bool wlr_multi_backend_add(struct wlr_backend *multi, + struct wlr_backend *backend); + +void wlr_multi_backend_remove(struct wlr_backend *multi, + struct wlr_backend *backend); + +bool wlr_backend_is_multi(struct wlr_backend *backend); +bool wlr_multi_is_empty(struct wlr_backend *backend); + +void wlr_multi_for_each_backend(struct wlr_backend *backend, + void (*callback)(struct wlr_backend *backend, void *data), void *data); + +#endif diff --git a/3rdparty/wlroots/include/wlr/backend/session.h b/3rdparty/wlroots/include/wlr/backend/session.h new file mode 100644 index 0000000000..a1ff0c317a --- /dev/null +++ b/3rdparty/wlroots/include/wlr/backend/session.h @@ -0,0 +1,146 @@ +#ifndef WLR_BACKEND_SESSION_H +#define WLR_BACKEND_SESSION_H + +#include +#include +#include + +struct libseat; + +/** + * An opened physical device. + */ +struct wlr_device { + int fd; + int device_id; + dev_t dev; + struct wl_list link; // wlr_session.devices + + struct { + struct wl_signal change; // struct wlr_device_change_event + struct wl_signal remove; + } events; +}; + +/** + * A session manages access to physical devices (such as GPUs and input + * devices). + * + * A session is only required when running on bare metal (e.g. with the KMS or + * libinput backends). + * + * The session listens for device hotplug events, and relays that information + * via the add_drm_card event and the change/remove events on struct wlr_device. + * The session provides functions to gain access to physical device (which is a + * privileged operation), see wlr_session_open_file(). The session also keeps + * track of the virtual terminal state (allowing users to switch between + * compositors or TTYs), see wlr_session_change_vt() and the active event. + */ +struct wlr_session { + /* + * Signal for when the session becomes active/inactive. + * It's called when we swap virtual terminal. + */ + bool active; + + char seat[256]; + + struct udev *udev; + struct udev_monitor *mon; + struct wl_event_source *udev_event; + + struct libseat *seat_handle; + struct wl_event_source *libseat_event; + + struct wl_list devices; // wlr_device.link + + struct wl_event_loop *event_loop; + + struct { + struct wl_signal active; + struct wl_signal add_drm_card; // struct wlr_session_add_event + struct wl_signal destroy; + } events; + + struct { + struct wl_listener event_loop_destroy; + } WLR_PRIVATE; +}; + +struct wlr_session_add_event { + const char *path; +}; + +enum wlr_device_change_type { + WLR_DEVICE_HOTPLUG = 1, + WLR_DEVICE_LEASE, +}; + +struct wlr_device_hotplug_event { + uint32_t connector_id; + uint32_t prop_id; +}; + +struct wlr_device_change_event { + enum wlr_device_change_type type; + union { + struct wlr_device_hotplug_event hotplug; + }; +}; + +/* + * Opens a session, taking control of the current virtual terminal. + * This should not be called if another program is already in control + * of the terminal (Xorg, another Wayland compositor, etc.). + * + * Returns NULL on error. + */ +struct wlr_session *wlr_session_create(struct wl_event_loop *loop); + +/* + * Closes a previously opened session and restores the virtual terminal. + * You should call wlr_session_close_file() on each files you opened + * with wlr_session_open_file() before you call this. + */ +void wlr_session_destroy(struct wlr_session *session); + +/* + * Opens the file at path. + * + * This can only be used to open DRM or evdev (input) devices. Files opened via + * this function must be closed by calling wlr_session_close_file(). + * + * When the session becomes inactive: + * + * - DRM files lose their DRM master status + * - evdev files become invalid and should be closed + */ +struct wlr_device *wlr_session_open_file(struct wlr_session *session, + const char *path); + +/* + * Closes a file previously opened with wlr_session_open_file(). + */ +void wlr_session_close_file(struct wlr_session *session, + struct wlr_device *device); + +/* + * Changes the virtual terminal. + */ +bool wlr_session_change_vt(struct wlr_session *session, unsigned vt); + +/** + * Enumerate and open KMS devices. + * + * ret is filled with up to ret_len devices. The number of devices ret has been + * filled with is returned on success. If more devices than ret_len are probed, + * the extraneous ones are ignored. If there is no KMS device, the function + * will block until such device is detected up to a timeout. The first device + * returned is the default device (marked as "boot_vga" by the kernel). + * + * On error, or if no device was found, -1 is returned. + */ +ssize_t wlr_session_find_gpus(struct wlr_session *session, + size_t ret_len, struct wlr_device **ret); + +#endif diff --git a/3rdparty/wlroots/include/wlr/backend/wayland.h b/3rdparty/wlroots/include/wlr/backend/wayland.h new file mode 100644 index 0000000000..c732de68c6 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/backend/wayland.h @@ -0,0 +1,76 @@ +#ifndef WLR_BACKEND_WAYLAND_H +#define WLR_BACKEND_WAYLAND_H + +#include +#include +#include +#include +#include + +struct wlr_input_device; + +/** + * Creates a new Wayland backend. This backend will be created with no outputs; + * you must use wlr_wl_output_create() to add them. + * + * The remote_display argument is an existing libwayland-client struct wl_display + * to use. Leave it NULL to create a new connection to the compositor. + */ +struct wlr_backend *wlr_wl_backend_create(struct wl_event_loop *loop, + struct wl_display *remote_display); + +/** + * Returns the remote struct wl_display used by the Wayland backend. + */ +struct wl_display *wlr_wl_backend_get_remote_display(struct wlr_backend *backend); + +/** + * Adds a new output to this backend. + * + * This creates a new xdg_toplevel in the parent Wayland compositor. + * + * You may remove outputs by destroying them. + * + * Note that if called before initializing the backend, this will return NULL + * and your outputs will be created during initialization (and given to you via + * the new_output signal). + */ +struct wlr_output *wlr_wl_output_create(struct wlr_backend *backend); + +/** + * Create a new output from an existing struct wl_surface. + */ +struct wlr_output *wlr_wl_output_create_from_surface(struct wlr_backend *backend, + struct wl_surface *surface); + +/** + * Check whether the provided backend is a Wayland backend. + */ +bool wlr_backend_is_wl(struct wlr_backend *backend); + +/** + * Check whether the provided input device is a Wayland input device. + */ +bool wlr_input_device_is_wl(struct wlr_input_device *device); + +/** + * Check whether the provided output device is a Wayland output device. + */ +bool wlr_output_is_wl(struct wlr_output *output); + +/** + * Sets the title of a struct wlr_output which is a Wayland toplevel. + */ +void wlr_wl_output_set_title(struct wlr_output *output, const char *title); + +/** + * Sets the app_id of a struct wlr_output which is a Wayland toplevel. + */ +void wlr_wl_output_set_app_id(struct wlr_output *output, const char *app_id); + +/** + * Returns the remote struct wl_surface used by the Wayland output. + */ +struct wl_surface *wlr_wl_output_get_surface(struct wlr_output *output); + +#endif diff --git a/3rdparty/wlroots/include/wlr/backend/x11.h b/3rdparty/wlroots/include/wlr/backend/x11.h new file mode 100644 index 0000000000..1791041ceb --- /dev/null +++ b/3rdparty/wlroots/include/wlr/backend/x11.h @@ -0,0 +1,51 @@ +#ifndef WLR_BACKEND_X11_H +#define WLR_BACKEND_X11_H + +#include + +#include + +#include +#include + +struct wlr_input_device; + +/** + * Creates a new X11 backend. This backend will be created with no outputs; + * you must use wlr_x11_output_create() to add them. + * + * The `x11_display` argument is the name of the X Display socket. Set + * to NULL for the default behaviour of XOpenDisplay(). + */ +struct wlr_backend *wlr_x11_backend_create(struct wl_event_loop *loop, + const char *x11_display); + +/** + * Adds a new output to this backend. You may remove outputs by destroying them. + * Note that if called before initializing the backend, this will return NULL + * and your outputs will be created during initialization (and given to you via + * the new_output signal). + */ +struct wlr_output *wlr_x11_output_create(struct wlr_backend *backend); + +/** + * Check whether this backend is an X11 backend. + */ +bool wlr_backend_is_x11(struct wlr_backend *backend); + +/** + * Check whether this input device is an X11 input device. + */ +bool wlr_input_device_is_x11(struct wlr_input_device *device); + +/** + * Check whether this output device is an X11 output device. + */ +bool wlr_output_is_x11(struct wlr_output *output); + +/** + * Sets the title of a struct wlr_output which is an X11 window. + */ +void wlr_x11_output_set_title(struct wlr_output *output, const char *title); + +#endif diff --git a/3rdparty/wlroots/include/wlr/config.h.in b/3rdparty/wlroots/include/wlr/config.h.in new file mode 100644 index 0000000000..ef186343ec --- /dev/null +++ b/3rdparty/wlroots/include/wlr/config.h.in @@ -0,0 +1,76 @@ +#ifndef WLR_CONFIG_H +#define WLR_CONFIG_H + +/** + * Whether the DRM backend is compile-time enabled. Equivalent to the + * pkg-config "have_drm_backend" variable. + * + * Required for . + */ +#mesondefine WLR_HAS_DRM_BACKEND +/** + * Whether the libinput backend is compile-time enabled. Equivalent to the + * pkg-config "have_libinput_backend" vartiable. + * + * Required for . + */ +#mesondefine WLR_HAS_LIBINPUT_BACKEND +/** + * Whether the X11 backend is compile-time enabled. Equivalent to the + * pkg-config "have_x11_backend" variable. + * + * Required for . + */ +#mesondefine WLR_HAS_X11_BACKEND + +/** + * Whether the GLES2 renderer is compile-time enabled. Equivalent to the + * pkg-config "have_gles2_renderer" variable. + * + * Required for . + */ +#mesondefine WLR_HAS_GLES2_RENDERER +/** + * Whether the Vulkan renderer is compile-time enabled. Equivalent to the + * pkg-config "have_vulkan_renderer" variable. + * + * Required for . + */ +#mesondefine WLR_HAS_VULKAN_RENDERER + +/** + * Whether the GBM allocator is compile-time enabled. Equivalent to the + * pkg-config "have_gbm_allocator" variable. + */ +#mesondefine WLR_HAS_GBM_ALLOCATOR +/** + * Whether the udmabuf allocator is compile-time enabled. Equivalent to the + * pkg-config "have_udmabuf_allocator" variable. + */ +#mesondefine WLR_HAS_UDMABUF_ALLOCATOR + +/** + * Whether Xwayland support is compile-time enabled. Equivalent to the + * pkg-config "have_xwayland" variable. + * + * Required for . + */ +#mesondefine WLR_HAS_XWAYLAND + +/** + * Whether session support is compile-time enabled. Equivalent to the + * pkg-config "have_session" variable. + * + * Required for . + */ +#mesondefine WLR_HAS_SESSION + +/** + * Whether traditional color management support is compile-time enabled. + * Equivalent to the pkg-config "have_color_management" variable. + * + * Required for ICC profile support in . + */ +#mesondefine WLR_HAS_COLOR_MANAGEMENT + +#endif diff --git a/3rdparty/wlroots/include/wlr/interfaces/wlr_buffer.h b/3rdparty/wlroots/include/wlr/interfaces/wlr_buffer.h new file mode 100644 index 0000000000..4244a00d5a --- /dev/null +++ b/3rdparty/wlroots/include/wlr/interfaces/wlr_buffer.h @@ -0,0 +1,53 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_INTERFACES_WLR_BUFFER_H +#define WLR_INTERFACES_WLR_BUFFER_H + +#include + +struct wlr_buffer_impl { + void (*destroy)(struct wlr_buffer *buffer); + bool (*get_dmabuf)(struct wlr_buffer *buffer, + struct wlr_dmabuf_attributes *attribs); + bool (*get_shm)(struct wlr_buffer *buffer, + struct wlr_shm_attributes *attribs); + bool (*begin_data_ptr_access)(struct wlr_buffer *buffer, uint32_t flags, + void **data, uint32_t *format, size_t *stride); + void (*end_data_ptr_access)(struct wlr_buffer *buffer); +}; + +struct wlr_buffer_resource_interface { + const char *name; + bool (*is_instance)(struct wl_resource *resource); + struct wlr_buffer *(*from_resource)(struct wl_resource *resource); +}; + +/** + * Initialize a buffer. This function should be called by producers. The + * initialized buffer is referenced: once the producer is done with the buffer + * they should call wlr_buffer_drop(). + */ +void wlr_buffer_init(struct wlr_buffer *buffer, + const struct wlr_buffer_impl *impl, int width, int height); + +/** + * Emit the destroy event and clean up common buffer state. + */ +void wlr_buffer_finish(struct wlr_buffer *buffer); + +/** + * Allows the registration of a struct wl_resource implementation. + * + * The matching function will be called for the struct wl_resource when creating + * a struct wlr_buffer from a struct wl_resource. + */ +void wlr_buffer_register_resource_interface( + const struct wlr_buffer_resource_interface *iface); + +#endif diff --git a/3rdparty/wlroots/include/wlr/interfaces/wlr_ext_image_capture_source_v1.h b/3rdparty/wlroots/include/wlr/interfaces/wlr_ext_image_capture_source_v1.h new file mode 100644 index 0000000000..a87e8afd69 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/interfaces/wlr_ext_image_capture_source_v1.h @@ -0,0 +1,45 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_INTERFACES_WLR_EXT_IMAGE_CAPTURE_SOURCE_V1_H +#define WLR_INTERFACES_WLR_EXT_IMAGE_CAPTURE_SOURCE_V1_H + +#include +#include + +struct wlr_ext_image_copy_capture_frame_v1; +struct wlr_swapchain; +struct wlr_renderer; +struct wlr_seat; + +struct wlr_ext_image_capture_source_v1_interface { + // TODO: drop with_cursors flag + void (*start)(struct wlr_ext_image_capture_source_v1 *source, bool with_cursors); + void (*stop)(struct wlr_ext_image_capture_source_v1 *source); + void (*request_frame)(struct wlr_ext_image_capture_source_v1 *source, bool schedule_frame); + void (*copy_frame)(struct wlr_ext_image_capture_source_v1 *source, + struct wlr_ext_image_copy_capture_frame_v1 *dst_frame, + struct wlr_ext_image_capture_source_v1_frame_event *frame_event); + struct wlr_ext_image_capture_source_v1_cursor *(*get_pointer_cursor)( + struct wlr_ext_image_capture_source_v1 *source, struct wlr_seat *seat); +}; + +void wlr_ext_image_capture_source_v1_init(struct wlr_ext_image_capture_source_v1 *source, + const struct wlr_ext_image_capture_source_v1_interface *impl); +void wlr_ext_image_capture_source_v1_finish(struct wlr_ext_image_capture_source_v1 *source); +bool wlr_ext_image_capture_source_v1_create_resource(struct wlr_ext_image_capture_source_v1 *source, + struct wl_client *client, uint32_t new_id); +bool wlr_ext_image_capture_source_v1_set_constraints_from_swapchain( + struct wlr_ext_image_capture_source_v1 *source, + struct wlr_swapchain *swapchain, struct wlr_renderer *renderer); + +void wlr_ext_image_capture_source_v1_cursor_init(struct wlr_ext_image_capture_source_v1_cursor *source_cursor, + const struct wlr_ext_image_capture_source_v1_interface *impl); +void wlr_ext_image_capture_source_v1_cursor_finish(struct wlr_ext_image_capture_source_v1_cursor *source_cursor); + +#endif diff --git a/3rdparty/wlroots/include/wlr/interfaces/wlr_keyboard.h b/3rdparty/wlroots/include/wlr/interfaces/wlr_keyboard.h new file mode 100644 index 0000000000..2ec7c8cfe1 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/interfaces/wlr_keyboard.h @@ -0,0 +1,34 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_INTERFACES_WLR_KEYBOARD_H +#define WLR_INTERFACES_WLR_KEYBOARD_H + +#include +#include + +struct wlr_keyboard_impl { + const char *name; + void (*led_update)(struct wlr_keyboard *keyboard, uint32_t leds); +}; + +void wlr_keyboard_init(struct wlr_keyboard *keyboard, + const struct wlr_keyboard_impl *impl, const char *name); + +/** + * Cleans up all of the resources owned by the struct wlr_keyboard. + */ +void wlr_keyboard_finish(struct wlr_keyboard *keyboard); + +void wlr_keyboard_notify_key(struct wlr_keyboard *keyboard, + struct wlr_keyboard_key_event *event); +void wlr_keyboard_notify_modifiers(struct wlr_keyboard *keyboard, + uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, + uint32_t group); + +#endif diff --git a/3rdparty/wlroots/include/wlr/interfaces/wlr_output.h b/3rdparty/wlroots/include/wlr/interfaces/wlr_output.h new file mode 100644 index 0000000000..6da2c2c546 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/interfaces/wlr_output.h @@ -0,0 +1,139 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_INTERFACES_WLR_OUTPUT_H +#define WLR_INTERFACES_WLR_OUTPUT_H + +#include +#include +#include + +/** + * Output state fields that don't require backend support. Backends can ignore + * them without breaking the API contract. + */ +#define WLR_OUTPUT_STATE_BACKEND_OPTIONAL \ + (WLR_OUTPUT_STATE_DAMAGE | \ + WLR_OUTPUT_STATE_SCALE | \ + WLR_OUTPUT_STATE_TRANSFORM | \ + WLR_OUTPUT_STATE_RENDER_FORMAT | \ + WLR_OUTPUT_STATE_SUBPIXEL | \ + WLR_OUTPUT_STATE_LAYERS) + +struct wlr_output_cursor_size { + int width, height; +}; + +/** + * A backend implementation of struct wlr_output. + * + * The commit function is mandatory. Other functions are optional. + */ +struct wlr_output_impl { + /** + * Set the output cursor plane image. + * + * If buffer is NULL, the cursor should be hidden. + * + * The hotspot indicates the offset that needs to be applied to the + * top-left corner of the image to match the cursor position. In other + * words, the image should be displayed at (x - hotspot_x, y - hotspot_y). + * The hotspot is given in the buffer's coordinate space. + */ + bool (*set_cursor)(struct wlr_output *output, struct wlr_buffer *buffer, + int hotspot_x, int hotspot_y); + /** + * Set the output cursor plane position. + * + * The position is relative to the cursor hotspot, see set_cursor. + */ + bool (*move_cursor)(struct wlr_output *output, int x, int y); + /** + * Cleanup backend-specific resources tied to the output. + */ + void (*destroy)(struct wlr_output *output); + /** + * Check that the supplied output state is a valid configuration. + * + * If this function returns true, commit can only fail due to a runtime + * error. + */ + bool (*test)(struct wlr_output *output, const struct wlr_output_state *state); + /** + * Commit the supplied output state. + * + * If a buffer has been attached, a frame event is scheduled. + */ + bool (*commit)(struct wlr_output *output, const struct wlr_output_state *state); + /** + * Get the maximum number of gamma LUT elements for each channel. + * + * Zero can be returned if the output doesn't support gamma LUTs. + */ + size_t (*get_gamma_size)(struct wlr_output *output); + /** + * Get the list of formats suitable for the cursor, assuming a buffer with + * the specified capabilities. + * + * If unimplemented, the cursor buffer has no format constraint. If NULL is + * returned, no format is suitable. + */ + const struct wlr_drm_format_set *(*get_cursor_formats)( + struct wlr_output *output, uint32_t buffer_caps); + /** + * Get the list of sizes suitable for the cursor buffer. Attempts to use a + * different size for the cursor may fail. + */ + const struct wlr_output_cursor_size *(*get_cursor_sizes)(struct wlr_output *output, + size_t *len); + /** + * Get the list of DRM formats suitable for the primary buffer, + * assuming a buffer with the specified capabilities. + * + * If unimplemented, the primary buffer has no format constraint. If NULL + * is returned, no format is suitable. + */ + const struct wlr_drm_format_set *(*get_primary_formats)( + struct wlr_output *output, uint32_t buffer_caps); +}; + +/** + * Initialize a new output. + */ +void wlr_output_init(struct wlr_output *output, struct wlr_backend *backend, + const struct wlr_output_impl *impl, struct wl_event_loop *event_loop, + const struct wlr_output_state *state); +/** + * Emit the destroy event and clean up common output state. + */ +void wlr_output_finish(struct wlr_output *output); +/** + * Notify compositors that they need to submit a new frame in order to apply + * output changes. + */ +void wlr_output_update_needs_frame(struct wlr_output *output); +/** + * Send a frame event. + * + * See wlr_output.events.frame. + */ +void wlr_output_send_frame(struct wlr_output *output); +/** + * Send a present event. + * + * See wlr_output.events.present. + */ +void wlr_output_send_present(struct wlr_output *output, + struct wlr_output_event_present *event); +/** + * Request the compositor to apply new state. + */ +void wlr_output_send_request_state(struct wlr_output *output, + const struct wlr_output_state *state); + +#endif diff --git a/3rdparty/wlroots/include/wlr/interfaces/wlr_pointer.h b/3rdparty/wlroots/include/wlr/interfaces/wlr_pointer.h new file mode 100644 index 0000000000..93adb714e0 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/interfaces/wlr_pointer.h @@ -0,0 +1,25 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_INTERFACES_WLR_POINTER_H +#define WLR_INTERFACES_WLR_POINTER_H + +#include + +struct wlr_pointer_impl { + const char *name; +}; + +void wlr_pointer_init(struct wlr_pointer *pointer, + const struct wlr_pointer_impl *impl, const char *name); +void wlr_pointer_finish(struct wlr_pointer *pointer); + +void wlr_pointer_notify_button(struct wlr_pointer *pointer, + struct wlr_pointer_button_event *event); + +#endif diff --git a/3rdparty/wlroots/include/wlr/interfaces/wlr_switch.h b/3rdparty/wlroots/include/wlr/interfaces/wlr_switch.h new file mode 100644 index 0000000000..793ed25c2c --- /dev/null +++ b/3rdparty/wlroots/include/wlr/interfaces/wlr_switch.h @@ -0,0 +1,22 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_INTERFACES_WLR_SWITCH_H +#define WLR_INTERFACES_WLR_SWITCH_H + +#include + +struct wlr_switch_impl { + const char *name; +}; + +void wlr_switch_init(struct wlr_switch *switch_device, + const struct wlr_switch_impl *impl, const char *name); +void wlr_switch_finish(struct wlr_switch *switch_device); + +#endif diff --git a/3rdparty/wlroots/include/wlr/interfaces/wlr_tablet_pad.h b/3rdparty/wlroots/include/wlr/interfaces/wlr_tablet_pad.h new file mode 100644 index 0000000000..f4a422f2fe --- /dev/null +++ b/3rdparty/wlroots/include/wlr/interfaces/wlr_tablet_pad.h @@ -0,0 +1,30 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_INTERFACES_WLR_TABLET_PAD_H +#define WLR_INTERFACES_WLR_TABLET_PAD_H + +#include + +struct wlr_tablet_pad_impl { + const char *name; +}; + +void wlr_tablet_pad_init(struct wlr_tablet_pad *pad, + const struct wlr_tablet_pad_impl *impl, const char *name); + +/** + * Cleans up the resources owned by a struct wlr_tablet_pad. + * + * This function will not clean the memory allocated by + * struct wlr_tablet_pad_group, it's the responsibility of the caller to clean + * it. + */ +void wlr_tablet_pad_finish(struct wlr_tablet_pad *pad); + +#endif diff --git a/3rdparty/wlroots/include/wlr/interfaces/wlr_tablet_tool.h b/3rdparty/wlroots/include/wlr/interfaces/wlr_tablet_tool.h new file mode 100644 index 0000000000..68bf8cf74c --- /dev/null +++ b/3rdparty/wlroots/include/wlr/interfaces/wlr_tablet_tool.h @@ -0,0 +1,22 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_INTERFACES_WLR_TABLET_TOOL_H +#define WLR_INTERFACES_WLR_TABLET_TOOL_H + +#include + +struct wlr_tablet_impl { + const char *name; +}; + +void wlr_tablet_init(struct wlr_tablet *tablet, + const struct wlr_tablet_impl *impl, const char *name); +void wlr_tablet_finish(struct wlr_tablet *tablet); + +#endif diff --git a/3rdparty/wlroots/include/wlr/interfaces/wlr_touch.h b/3rdparty/wlroots/include/wlr/interfaces/wlr_touch.h new file mode 100644 index 0000000000..e48a92f222 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/interfaces/wlr_touch.h @@ -0,0 +1,22 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_INTERFACES_WLR_TOUCH_H +#define WLR_INTERFACES_WLR_TOUCH_H + +#include + +struct wlr_touch_impl { + const char *name; +}; + +void wlr_touch_init(struct wlr_touch *touch, + const struct wlr_touch_impl *impl, const char *name); +void wlr_touch_finish(struct wlr_touch *touch); + +#endif diff --git a/3rdparty/wlroots/include/wlr/meson.build b/3rdparty/wlroots/include/wlr/meson.build new file mode 100644 index 0000000000..5d25a577f3 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/meson.build @@ -0,0 +1,25 @@ +version_base = meson.project_version().split('-')[0] +version_array = version_base.split('.') +version_data = configuration_data() +version_data.set_quoted('WLR_VERSION_STR', meson.project_version()) +version_data.set('WLR_VERSION_MAJOR', version_array[0]) +version_data.set('WLR_VERSION_MINOR', version_array[1]) +version_data.set('WLR_VERSION_MICRO', version_array[2]) + +conf_data = configuration_data() +foreach name, have : features + conf_data.set10('WLR_HAS_' + name.underscorify().to_upper(), have) +endforeach + +conf_h = configure_file( + input: 'config.h.in', + output: 'config.h', + configuration: conf_data, +) +ver_h = configure_file( + input: 'version.h.in', + output: 'version.h', + configuration: version_data, +) + +install_headers(conf_h, ver_h, subdir: versioned_name / 'wlr') diff --git a/3rdparty/wlroots/include/wlr/render/allocator.h b/3rdparty/wlroots/include/wlr/render/allocator.h new file mode 100644 index 0000000000..8715919f37 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/render/allocator.h @@ -0,0 +1,80 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_ALLOCATOR_H +#define WLR_ALLOCATOR_H + +#include + +struct wlr_allocator; +struct wlr_backend; +struct wlr_drm_format; +struct wlr_renderer; + +struct wlr_allocator_interface { + struct wlr_buffer *(*create_buffer)(struct wlr_allocator *alloc, + int width, int height, const struct wlr_drm_format *format); + void (*destroy)(struct wlr_allocator *alloc); +}; + +void wlr_allocator_init(struct wlr_allocator *alloc, + const struct wlr_allocator_interface *impl, uint32_t buffer_caps); + +/** + * An allocator is responsible for allocating memory for pixel buffers. + * + * Each allocator may return buffers with different capabilities (shared + * memory, DMA-BUF, memory mapping, etc), placement (main memory, VRAM on a + * GPU, etc) and properties (possible usage, access performance, etc). See + * struct wlr_buffer. + * + * An allocator can be passed to a struct wlr_swapchain for multiple buffering. + */ +struct wlr_allocator { + const struct wlr_allocator_interface *impl; + + // Capabilities of the buffers created with this allocator + uint32_t buffer_caps; + + struct { + struct wl_signal destroy; + } events; +}; + +/** + * Creates the adequate struct wlr_allocator given a backend and a renderer. + */ +struct wlr_allocator *wlr_allocator_autocreate(struct wlr_backend *backend, + struct wlr_renderer *renderer); +/** + * Destroy the allocator. + */ +void wlr_allocator_destroy(struct wlr_allocator *alloc); + +/** + * Allocate a new buffer. + * + * When the caller is done with it, they must unreference it by calling + * wlr_buffer_drop(). + * + * The `format` passed in indicates the format to use and the list of + * acceptable modifiers. The order in which modifiers are listed is not + * significant. + * + * When running with legacy drivers which don't support explicit modifiers, the + * allocator must recognize two modifiers: INVALID (for implicit tiling and/or + * compression) and LINEAR. + * + * The allocator must return a buffer using one of the modifiers listed. In + * particular, allocators must not return a buffer with an implicit modifier + * unless the user has allowed it by passing INVALID in the modifier list. + */ +struct wlr_buffer *wlr_allocator_create_buffer(struct wlr_allocator *alloc, + int width, int height, const struct wlr_drm_format *format); + +#endif diff --git a/3rdparty/wlroots/include/wlr/render/color.h b/3rdparty/wlroots/include/wlr/render/color.h new file mode 100644 index 0000000000..31d2c85e9d --- /dev/null +++ b/3rdparty/wlroots/include/wlr/render/color.h @@ -0,0 +1,187 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_RENDER_COLOR_H +#define WLR_RENDER_COLOR_H + +#include +#include +#include + +/** + * Well-known color primaries. + */ +enum wlr_color_named_primaries { + WLR_COLOR_NAMED_PRIMARIES_SRGB = 1 << 0, + WLR_COLOR_NAMED_PRIMARIES_BT2020 = 1 << 1, +}; + +/** + * Well-known color transfer functions. + */ +enum wlr_color_transfer_function { + WLR_COLOR_TRANSFER_FUNCTION_SRGB = 1 << 0, + WLR_COLOR_TRANSFER_FUNCTION_ST2084_PQ = 1 << 1, + WLR_COLOR_TRANSFER_FUNCTION_EXT_LINEAR = 1 << 2, + WLR_COLOR_TRANSFER_FUNCTION_GAMMA22 = 1 << 3, + WLR_COLOR_TRANSFER_FUNCTION_BT1886 = 1 << 4, +}; + +/** + * Specifies alpha blending modes. Note that premultiplied_electrical + * is the default, so there is no "none" or "unset" value. + */ +enum wlr_alpha_mode { + WLR_COLOR_ALPHA_MODE_PREMULTIPLIED_ELECTRICAL, + WLR_COLOR_ALPHA_MODE_PREMULTIPLIED_OPTICAL, + WLR_COLOR_ALPHA_MODE_STRAIGHT, +}; + +/** + * Well-known color encodings, each representing a set of matrix coefficients + * used to convert that particular YCbCr encoding to RGB. NONE means the + * value is unset or unknown. + */ +enum wlr_color_encoding { + WLR_COLOR_ENCODING_NONE = 0, + WLR_COLOR_ENCODING_IDENTITY = 1 << 0, + WLR_COLOR_ENCODING_BT709 = 1 << 1, + WLR_COLOR_ENCODING_FCC = 1 << 2, + WLR_COLOR_ENCODING_BT601 = 1 << 3, + WLR_COLOR_ENCODING_SMPTE240 = 1 << 4, + WLR_COLOR_ENCODING_BT2020 = 1 << 5, + WLR_COLOR_ENCODING_BT2020_CL = 1 << 6, + WLR_COLOR_ENCODING_ICTCP = 1 << 7, +}; + +/** + * Specifies whether a particular color-encoding uses full- or limited-range + * values. NONE means the value is unset or unknown. + */ +enum wlr_color_range { + WLR_COLOR_RANGE_NONE, + WLR_COLOR_RANGE_LIMITED, + WLR_COLOR_RANGE_FULL, +}; + +/** + * Chroma sample locations, corresponding to Chroma420SampleLocType code + * points in H.273. NONE means the value is unset or unknown. + */ +enum wlr_color_chroma_location { + WLR_COLOR_CHROMA_LOCATION_NONE, + WLR_COLOR_CHROMA_LOCATION_TYPE0, + WLR_COLOR_CHROMA_LOCATION_TYPE1, + WLR_COLOR_CHROMA_LOCATION_TYPE2, + WLR_COLOR_CHROMA_LOCATION_TYPE3, + WLR_COLOR_CHROMA_LOCATION_TYPE4, + WLR_COLOR_CHROMA_LOCATION_TYPE5, +}; + +/** + * CIE 1931 xy chromaticity coordinates. + */ +struct wlr_color_cie1931_xy { + float x, y; +}; + +/** + * Color primaries and white point describing a color volume. + */ +struct wlr_color_primaries { + struct wlr_color_cie1931_xy red, green, blue, white; +}; + +/** + * Luminance range and reference white luminance level, in cd/m². + */ +struct wlr_color_luminances { + float min, max, reference; +}; + +/** + * A color transformation formula, which maps a linear color space with + * sRGB primaries to an output color space. + * + * For ease of use, this type is heap allocated and reference counted. + * Use wlr_color_transform_ref()/wlr_color_transform_unref(). The initial reference + * count after creation is 1. + * + * Color transforms are immutable; their type/parameters should not be changed, + * and this API provides no functions to modify them after creation. + * + * This formula may be implemented using a 3d look-up table, or some other + * means. + */ +struct wlr_color_transform; + +/** + * Initialize a color transformation to convert linear + * (with sRGB(?) primaries) to an ICC profile. Returns NULL on failure. + */ +struct wlr_color_transform *wlr_color_transform_init_linear_to_icc( + const void *data, size_t size); + +/** + * Initialize a color transformation to apply EOTF⁻¹ encoding. Returns + * NULL on failure. + */ +struct wlr_color_transform *wlr_color_transform_init_linear_to_inverse_eotf( + enum wlr_color_transfer_function tf); + +/** + * Initialize a color transformation to apply three 1D look-up tables. dim + * is the number of elements in each individual LUT. Returns NULL on failure. + */ +struct wlr_color_transform *wlr_color_transform_init_lut_3x1d(size_t dim, + const uint16_t *r, const uint16_t *g, const uint16_t *b); + +/** + * Initialize a color transformation to apply a 3×3 matrix. Returns NULL on + * failure. + */ +struct wlr_color_transform *wlr_color_transform_init_matrix(const float matrix[static 9]); + +/** + * Initialize a color transformation to apply a sequence of color transforms + * one after another. + */ +struct wlr_color_transform *wlr_color_transform_init_pipeline( + struct wlr_color_transform **transforms, size_t len); + +/** + * Increase the reference count of the color transform by 1. + */ +struct wlr_color_transform *wlr_color_transform_ref(struct wlr_color_transform *tr); + +/** + * Reduce the reference count of the color transform by 1; freeing it and + * all associated resources when the reference count hits zero. + */ +void wlr_color_transform_unref(struct wlr_color_transform *tr); + +/** + * Evaluate a color transform for a given RGB triplet. + */ +void wlr_color_transform_eval(struct wlr_color_transform *tr, + float out[static 3], const float in[static 3]); + +/** + * Obtain primaries values from a well-known primaries name. + */ +void wlr_color_primaries_from_named(struct wlr_color_primaries *out, + enum wlr_color_named_primaries named); + +/** + * Compute the matrix to convert between two linear RGB color spaces + */ +void wlr_color_primaries_transform_absolute_colorimetric( + const struct wlr_color_primaries *source, + const struct wlr_color_primaries *destination, float matrix[static 9]); + +#endif diff --git a/3rdparty/wlroots/include/wlr/render/dmabuf.h b/3rdparty/wlroots/include/wlr/render/dmabuf.h new file mode 100644 index 0000000000..62f8e02175 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/render/dmabuf.h @@ -0,0 +1,55 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_RENDER_DMABUF_H +#define WLR_RENDER_DMABUF_H + +#include +#include + +#define WLR_DMABUF_MAX_PLANES 4 + +/** + * A Linux DMA-BUF pixel buffer. + * + * If the buffer was allocated with explicit modifiers enabled, the `modifier` + * field must not be INVALID. + * + * If the buffer was allocated with explicit modifiers disabled (either because + * the driver doesn't support it, or because the user didn't specify a valid + * modifier list), the `modifier` field can have two values: INVALID means that + * an implicit vendor-defined modifier is in use, LINEAR means that the buffer + * is linear. The `modifier` field must not have any other value. + * + * When importing a DMA-BUF, users must not ignore the modifier unless it's + * INVALID or LINEAR. In particular, users must not import a DMA-BUF to a + * legacy API which doesn't support specifying an explicit modifier unless the + * modifier is set to INVALID or LINEAR. + */ +struct wlr_dmabuf_attributes { + int32_t width, height; + uint32_t format; // FourCC code, see DRM_FORMAT_* in + uint64_t modifier; // see DRM_FORMAT_MOD_* in + + int n_planes; + uint32_t offset[WLR_DMABUF_MAX_PLANES]; + uint32_t stride[WLR_DMABUF_MAX_PLANES]; + int fd[WLR_DMABUF_MAX_PLANES]; +}; + +/** + * Closes all file descriptors in the DMA-BUF attributes. + */ +void wlr_dmabuf_attributes_finish(struct wlr_dmabuf_attributes *attribs); +/** + * Clones the DMA-BUF attributes. + */ +bool wlr_dmabuf_attributes_copy(struct wlr_dmabuf_attributes *dst, + const struct wlr_dmabuf_attributes *src); + +#endif diff --git a/3rdparty/wlroots/include/wlr/render/drm_format_set.h b/3rdparty/wlroots/include/wlr/render/drm_format_set.h new file mode 100644 index 0000000000..16dcfe9fdf --- /dev/null +++ b/3rdparty/wlroots/include/wlr/render/drm_format_set.h @@ -0,0 +1,100 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_RENDER_DRM_FORMAT_SET_H +#define WLR_RENDER_DRM_FORMAT_SET_H + +#include +#include +#include + +/** A single DRM format, with a set of modifiers attached. */ +struct wlr_drm_format { + // The actual DRM format, from `drm_fourcc.h` + uint32_t format; + // The number of modifiers + size_t len; + // The capacity of the array; do not use. + size_t capacity; + // The actual modifiers + uint64_t *modifiers; +}; + +/** + * Free all resources allocated to this DRM format. + */ +void wlr_drm_format_finish(struct wlr_drm_format *format); + +/** + * A set of DRM formats and modifiers. + * + * This is used to describe the supported format + modifier combinations. For + * instance, backends will report the set they can display, and renderers will + * report the set they can render to. For a more general overview of formats + * and modifiers, see: + * https://www.kernel.org/doc/html/next/userspace-api/dma-buf-alloc-exchange.html#formats-and-modifiers + * + * For compatibility with legacy drivers which don't support explicit + * modifiers, the special modifier DRM_FORMAT_MOD_INVALID is used to indicate + * that implicit modifiers are supported. Legacy drivers can also support the + * DRM_FORMAT_MOD_LINEAR modifier, which forces the buffer to have a linear + * layout. + * + * Users must not assume that implicit modifiers are supported unless INVALID + * is listed in the modifier list. + */ +struct wlr_drm_format_set { + // The number of formats + size_t len; + // The capacity of the array; private to wlroots + size_t capacity; + // A pointer to an array of `struct wlr_drm_format *` of length `len`. + struct wlr_drm_format *formats; +}; + +/** + * Free all of the DRM formats in the set, making the set empty. + */ +void wlr_drm_format_set_finish(struct wlr_drm_format_set *set); + +/** + * Return a pointer to a member of this struct wlr_drm_format_set of format + * `format`, or NULL if none exists. + */ +const struct wlr_drm_format *wlr_drm_format_set_get( + const struct wlr_drm_format_set *set, uint32_t format); + +bool wlr_drm_format_set_remove(struct wlr_drm_format_set *set, uint32_t format, + uint64_t modifier); + +bool wlr_drm_format_set_has(const struct wlr_drm_format_set *set, + uint32_t format, uint64_t modifier); + +bool wlr_drm_format_set_add(struct wlr_drm_format_set *set, uint32_t format, + uint64_t modifier); + +/** + * Intersect two DRM format sets `a` and `b`, storing in the destination set + * `dst` the format + modifier pairs which are in both source sets. The `dst` + * must either be zeroed or initialized with other state to be replaced. + * + * Returns false on failure or when the intersection is empty. + */ +bool wlr_drm_format_set_intersect(struct wlr_drm_format_set *dst, + const struct wlr_drm_format_set *a, const struct wlr_drm_format_set *b); + +/** + * Unions DRM format set `a` and `b`, storing in the destination set + * `dst`. The `dst` must either be zeroed or initialized with other state + * to be replaced. + * + * Returns false on failure. + */ +bool wlr_drm_format_set_union(struct wlr_drm_format_set *dst, + const struct wlr_drm_format_set *a, const struct wlr_drm_format_set *b); +#endif diff --git a/3rdparty/wlroots/include/wlr/render/drm_syncobj.h b/3rdparty/wlroots/include/wlr/render/drm_syncobj.h new file mode 100644 index 0000000000..fabe23d1c7 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/render/drm_syncobj.h @@ -0,0 +1,134 @@ +#ifndef WLR_RENDER_DRM_SYNCOBJ_H +#define WLR_RENDER_DRM_SYNCOBJ_H + +#include +#include +#include +#include + +/** + * A synchronization timeline. + * + * Timelines are used to synchronize accesses to buffers. Given a producer + * (writing contents to a buffer) and a consumer (reading from the buffer), the + * compositor needs to synchronize back-and-forth between these two users. The + * consumer needs to wait for the producer to signal that they're done with the + * writes, and the producer needs to wait for the consumer to signal that + * they're done with the reads. + * + * Timelines provide synchronization points in the form of monotonically + * increasing 64-bit integer values. + * + * wlroots timelines are designed after Vulkan timeline semaphores. For more + * information on the Vulkan APIs, see: + * https://www.khronos.org/blog/vulkan-timeline-semaphores + * + * wlroots timelines are powered by DRM synchronization objects (drm_syncobj): + * https://dri.freedesktop.org/docs/drm/gpu/drm-mm.html#drm-sync-objects + */ +struct wlr_drm_syncobj_timeline { + int drm_fd; + uint32_t handle; + + struct wlr_addon_set addons; + + struct { + size_t n_refs; + } WLR_PRIVATE; +}; + +struct wlr_drm_syncobj_timeline_waiter; + +typedef void (*wlr_drm_syncobj_timeline_ready_callback)( + struct wlr_drm_syncobj_timeline_waiter *waiter); + +struct wlr_drm_syncobj_timeline_waiter { + struct { + int ev_fd; + struct wl_event_source *event_source; + wlr_drm_syncobj_timeline_ready_callback callback; + } WLR_PRIVATE; +}; + +/** + * Create a new synchronization timeline. + */ +struct wlr_drm_syncobj_timeline *wlr_drm_syncobj_timeline_create(int drm_fd); +/** + * Import a timeline from a drm_syncobj FD. + */ +struct wlr_drm_syncobj_timeline *wlr_drm_syncobj_timeline_import(int drm_fd, + int drm_syncobj_fd); +/** + * Reference a synchronization timeline. + */ +struct wlr_drm_syncobj_timeline *wlr_drm_syncobj_timeline_ref(struct wlr_drm_syncobj_timeline *timeline); +/** + * Unreference a synchronization timeline. + */ +void wlr_drm_syncobj_timeline_unref(struct wlr_drm_syncobj_timeline *timeline); +/** + * Export a drm_syncobj FD from a timeline. + */ +int wlr_drm_syncobj_timeline_export(struct wlr_drm_syncobj_timeline *timeline); +/** + * Transfer a point from a timeline to another. + * + * Both timelines must have been created with the same DRM FD. + */ +bool wlr_drm_syncobj_timeline_transfer(struct wlr_drm_syncobj_timeline *dst, + uint64_t dst_point, struct wlr_drm_syncobj_timeline *src, uint64_t src_point); +/** + * Check if a timeline point has been signalled or has materialized. + * + * Flags can be: + * + * - DRM_SYNCOBJ_WAIT_FLAGS_WAIT_FOR_SUBMIT to wait for the point to be + * signalled + * - DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE to only wait for a fence to + * materialize + */ +bool wlr_drm_syncobj_timeline_check(struct wlr_drm_syncobj_timeline *timeline, + uint64_t point, uint32_t flags, bool *result); +/** + * Signals a timeline point. + */ +bool wlr_drm_syncobj_timeline_signal(struct wlr_drm_syncobj_timeline *timeline, uint64_t point); +/** + * Asynchronously wait for a timeline point. + * + * See wlr_drm_syncobj_timeline_check() for a definition of flags. + * + * A callback must be provided that will be invoked when the waiter has finished. + */ +bool wlr_drm_syncobj_timeline_waiter_init(struct wlr_drm_syncobj_timeline_waiter *waiter, + struct wlr_drm_syncobj_timeline *timeline, uint64_t point, uint32_t flags, + struct wl_event_loop *loop, wlr_drm_syncobj_timeline_ready_callback callback); +/** + * Cancel a timeline waiter. + */ +void wlr_drm_syncobj_timeline_waiter_finish(struct wlr_drm_syncobj_timeline_waiter *waiter); +/** + * Export a timeline point as a sync_file FD. + * + * The returned sync_file will be signalled when the provided point is + * signalled on the timeline. + * + * This allows inter-operation with other APIs which don't support drm_syncobj + * yet. The synchronization point needs to have already materialized: + * wait-before-signal is not supported. + */ +int wlr_drm_syncobj_timeline_export_sync_file(struct wlr_drm_syncobj_timeline *timeline, + uint64_t src_point); +/** + * Import a timeline point from a sync_file FD. + * + * The provided timeline point will be signalled when the provided sync_file is. + * + * This allows inter-operation with other APIs which don't support drm_syncobj + * yet. + */ +bool wlr_drm_syncobj_timeline_import_sync_file(struct wlr_drm_syncobj_timeline *timeline, + uint64_t dst_point, int sync_file_fd); + +#endif diff --git a/3rdparty/wlroots/include/wlr/render/egl.h b/3rdparty/wlroots/include/wlr/render/egl.h new file mode 100644 index 0000000000..9bf1b80199 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/render/egl.h @@ -0,0 +1,56 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_RENDER_EGL_H +#define WLR_RENDER_EGL_H + +#ifndef EGL_NO_X11 +#define EGL_NO_X11 +#endif +#ifndef EGL_NO_PLATFORM_SPECIFIC_TYPES +#define EGL_NO_PLATFORM_SPECIFIC_TYPES +#endif + +#include + +#include +#include +#include +#include +#include +#include +#include + +struct wlr_egl; + +/** + * Create a struct wlr_egl with an existing EGL display and context. + * + * This is typically used by compositors which want to customize EGL + * initialization. + */ +struct wlr_egl *wlr_egl_create_with_context(EGLDisplay display, + EGLContext context); + +/** + * Get the EGL display used by the struct wlr_egl. + * + * This is typically used by compositors which need to perform custom OpenGL + * operations. + */ +EGLDisplay wlr_egl_get_display(struct wlr_egl *egl); + +/** + * Get the EGL context used by the struct wlr_egl. + * + * This is typically used by compositors which need to perform custom OpenGL + * operations. + */ +EGLContext wlr_egl_get_context(struct wlr_egl *egl); + +#endif diff --git a/3rdparty/wlroots/include/wlr/render/gles2.h b/3rdparty/wlroots/include/wlr/render/gles2.h new file mode 100644 index 0000000000..454e7eb0ee --- /dev/null +++ b/3rdparty/wlroots/include/wlr/render/gles2.h @@ -0,0 +1,51 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_RENDER_GLES2_H +#define WLR_RENDER_GLES2_H + +#include + +#include + +struct wlr_egl; + +/** + * OpenGL ES 2 renderer. + * + * Care must be taken to avoid stepping each other's toes with EGL contexts: + * the current EGL is global state. The GLES2 renderer operations will save + * and restore any previous EGL context when called. A render pass is seen as + * a single operation. + * + * The GLES2 renderer doesn't support arbitrarily nested render passes. It + * supports a subset only: after a nested render pass is created, any parent + * render pass can't be used before the nested render pass is submitted. + */ + +struct wlr_renderer *wlr_gles2_renderer_create_with_drm_fd(int drm_fd); +struct wlr_renderer *wlr_gles2_renderer_create(struct wlr_egl *egl); + +struct wlr_egl *wlr_gles2_renderer_get_egl(struct wlr_renderer *renderer); +bool wlr_gles2_renderer_check_ext(struct wlr_renderer *renderer, const char *ext); +GLuint wlr_gles2_renderer_get_buffer_fbo(struct wlr_renderer *renderer, struct wlr_buffer *buffer); + +struct wlr_gles2_texture_attribs { + GLenum target; /* either GL_TEXTURE_2D or GL_TEXTURE_EXTERNAL_OES */ + GLuint tex; + + bool has_alpha; +}; + +bool wlr_renderer_is_gles2(struct wlr_renderer *wlr_renderer); +bool wlr_render_timer_is_gles2(struct wlr_render_timer *timer); +bool wlr_texture_is_gles2(struct wlr_texture *texture); +void wlr_gles2_texture_get_attribs(struct wlr_texture *texture, + struct wlr_gles2_texture_attribs *attribs); + +#endif diff --git a/3rdparty/wlroots/include/wlr/render/interface.h b/3rdparty/wlroots/include/wlr/render/interface.h new file mode 100644 index 0000000000..89f6de9708 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/render/interface.h @@ -0,0 +1,90 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_RENDER_INTERFACE_H +#define WLR_RENDER_INTERFACE_H + +#include +#include +#include +#include +#include +#include + +struct wlr_box; +struct wlr_fbox; + +struct wlr_renderer_impl { + const struct wlr_drm_format_set *(*get_texture_formats)( + struct wlr_renderer *renderer, uint32_t buffer_caps); + const struct wlr_drm_format_set *(*get_render_formats)( + struct wlr_renderer *renderer); + void (*destroy)(struct wlr_renderer *renderer); + int (*get_drm_fd)(struct wlr_renderer *renderer); + struct wlr_texture *(*texture_from_buffer)(struct wlr_renderer *renderer, + struct wlr_buffer *buffer); + struct wlr_render_pass *(*begin_buffer_pass)(struct wlr_renderer *renderer, + struct wlr_buffer *buffer, const struct wlr_buffer_pass_options *options); + struct wlr_render_timer *(*render_timer_create)(struct wlr_renderer *renderer); +}; + +void wlr_renderer_init(struct wlr_renderer *renderer, + const struct wlr_renderer_impl *impl, uint32_t render_buffer_caps); + +struct wlr_texture_impl { + bool (*update_from_buffer)(struct wlr_texture *texture, + struct wlr_buffer *buffer, const pixman_region32_t *damage); + bool (*read_pixels)(struct wlr_texture *texture, + const struct wlr_texture_read_pixels_options *options); + uint32_t (*preferred_read_format)(struct wlr_texture *texture); + void (*destroy)(struct wlr_texture *texture); +}; + +void wlr_texture_init(struct wlr_texture *texture, struct wlr_renderer *rendener, + const struct wlr_texture_impl *impl, uint32_t width, uint32_t height); + +struct wlr_render_pass { + const struct wlr_render_pass_impl *impl; +}; + +void wlr_render_pass_init(struct wlr_render_pass *pass, + const struct wlr_render_pass_impl *impl); + +struct wlr_render_pass_impl { + bool (*submit)(struct wlr_render_pass *pass); + void (*add_texture)(struct wlr_render_pass *pass, + const struct wlr_render_texture_options *options); + /* Implementers are also guaranteed that options->box is nonempty */ + void (*add_rect)(struct wlr_render_pass *pass, + const struct wlr_render_rect_options *options); +}; + +struct wlr_render_timer { + const struct wlr_render_timer_impl *impl; +}; + +struct wlr_render_timer_impl { + int (*get_duration_ns)(struct wlr_render_timer *timer); + void (*destroy)(struct wlr_render_timer *timer); +}; + +void wlr_render_texture_options_get_src_box(const struct wlr_render_texture_options *options, + struct wlr_fbox *box); +void wlr_render_texture_options_get_dst_box(const struct wlr_render_texture_options *options, + struct wlr_box *box); +float wlr_render_texture_options_get_alpha(const struct wlr_render_texture_options *options); +void wlr_render_rect_options_get_box(const struct wlr_render_rect_options *options, + const struct wlr_buffer *buffer, struct wlr_box *box); + +void wlr_texture_read_pixels_options_get_src_box( + const struct wlr_texture_read_pixels_options *options, + const struct wlr_texture *texture, struct wlr_box *box); +void *wlr_texture_read_pixel_options_get_data( + const struct wlr_texture_read_pixels_options *options); + +#endif diff --git a/3rdparty/wlroots/include/wlr/render/pass.h b/3rdparty/wlroots/include/wlr/render/pass.h new file mode 100644 index 0000000000..61ab77132c --- /dev/null +++ b/3rdparty/wlroots/include/wlr/render/pass.h @@ -0,0 +1,160 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_RENDER_PASS_H +#define WLR_RENDER_PASS_H + +#include +#include +#include +#include +#include + +struct wlr_renderer; +struct wlr_buffer; + +/** + * A render pass accumulates drawing operations until submitted to the GPU. + */ +struct wlr_render_pass; + +/** + * An object that can be queried after a render to get the duration of the render. + */ +struct wlr_render_timer; + +struct wlr_buffer_pass_options { + /* Timer to measure the duration of the render pass */ + struct wlr_render_timer *timer; + /* Color transform to apply to the output of the render pass. + * Leave NULL to indicate the default transform (Gamma 2.2 encoding for + * sRGB monitors) */ + struct wlr_color_transform *color_transform; + + /* Signal a timeline synchronization point when the render pass completes. + * + * When a compositor provides a signal timeline, the renderer may skip + * implicit signal synchronization. + * + * Support for this feature is advertised by features.timeline in + * struct wlr_renderer. + */ + struct wlr_drm_syncobj_timeline *signal_timeline; + uint64_t signal_point; +}; + +/** + * Begin a new render pass with the supplied destination buffer. + * + * Callers must call wlr_render_pass_submit() once they are done with the + * render pass. + */ +struct wlr_render_pass *wlr_renderer_begin_buffer_pass(struct wlr_renderer *renderer, + struct wlr_buffer *buffer, const struct wlr_buffer_pass_options *options); + +/** + * Submit the render pass. + * + * The render pass cannot be used after this function is called. + */ +bool wlr_render_pass_submit(struct wlr_render_pass *render_pass); + +/** + * Blend modes. + */ +enum wlr_render_blend_mode { + /* Pre-multiplied alpha (default) */ + WLR_RENDER_BLEND_MODE_PREMULTIPLIED, + /* Blending is disabled */ + WLR_RENDER_BLEND_MODE_NONE, +}; + +/** + * Filter modes. + */ +enum wlr_scale_filter_mode { + /* bilinear texture filtering (default) */ + WLR_SCALE_FILTER_BILINEAR, + /* nearest texture filtering */ + WLR_SCALE_FILTER_NEAREST, +}; + +struct wlr_render_texture_options { + /* Source texture */ + struct wlr_texture *texture; + /* Source coordinates, leave empty to render the whole texture */ + struct wlr_fbox src_box; + /* Destination coordinates, width/height default to the texture size */ + struct wlr_box dst_box; + /* Opacity between 0 (transparent) and 1 (opaque), leave NULL for opaque */ + const float *alpha; + /* Clip region, leave NULL to disable clipping */ + const pixman_region32_t *clip; + /* Transform applied to the source texture */ + enum wl_output_transform transform; + /* Filtering */ + enum wlr_scale_filter_mode filter_mode; + /* Blend mode */ + enum wlr_render_blend_mode blend_mode; + /* Transfer function the source texture is encoded with */ + enum wlr_color_transfer_function transfer_function; + /* Primaries describing the color volume of the source texture */ + const struct wlr_color_primaries *primaries; + /* Color encoding of the source texture for YCbCr conversion to RGB */ + enum wlr_color_encoding color_encoding; + /* Color range of the source texture */ + enum wlr_color_range color_range; + /* Default: 1.0 */ + const float *luminance_multiplier; + + /* Wait for a timeline synchronization point before texturing. + * + * When a compositor provides a wait timeline, the renderer may skip + * implicit wait synchronization. + * + * Support for this feature is advertised by features.timeline in + * struct wlr_renderer. + */ + struct wlr_drm_syncobj_timeline *wait_timeline; + uint64_t wait_point; +}; + +/** + * Render a texture. + */ +void wlr_render_pass_add_texture(struct wlr_render_pass *render_pass, + const struct wlr_render_texture_options *options); + +/** + * A color value. + * + * Each channel has values between 0 and 1 inclusive. The R, G, B + * channels need to be pre-multiplied by A. + */ +struct wlr_render_color { + float r, g, b, a; +}; + +struct wlr_render_rect_options { + /* Rectangle coordinates */ + struct wlr_box box; + /* Source color */ + struct wlr_render_color color; + /* Clip region, leave NULL to disable clipping */ + const pixman_region32_t *clip; + /* Blend mode */ + enum wlr_render_blend_mode blend_mode; +}; + +/** + * Render a rectangle. + */ +void wlr_render_pass_add_rect(struct wlr_render_pass *render_pass, + const struct wlr_render_rect_options *options); + +#endif diff --git a/3rdparty/wlroots/include/wlr/render/pixman.h b/3rdparty/wlroots/include/wlr/render/pixman.h new file mode 100644 index 0000000000..206dd78c65 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/render/pixman.h @@ -0,0 +1,24 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_RENDER_PIXMAN_H +#define WLR_RENDER_PIXMAN_H + +#include +#include + +struct wlr_renderer *wlr_pixman_renderer_create(void); + +bool wlr_renderer_is_pixman(struct wlr_renderer *wlr_renderer); +bool wlr_texture_is_pixman(struct wlr_texture *texture); + +pixman_image_t *wlr_pixman_renderer_get_buffer_image( + struct wlr_renderer *wlr_renderer, struct wlr_buffer *wlr_buffer); +pixman_image_t *wlr_pixman_texture_get_image(struct wlr_texture *wlr_texture); + +#endif diff --git a/3rdparty/wlroots/include/wlr/render/swapchain.h b/3rdparty/wlroots/include/wlr/render/swapchain.h new file mode 100644 index 0000000000..4ca1ac5905 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/render/swapchain.h @@ -0,0 +1,50 @@ +#ifndef WLR_RENDER_SWAPCHAIN_H +#define WLR_RENDER_SWAPCHAIN_H + +#include +#include +#include + +#define WLR_SWAPCHAIN_CAP 4 + +struct wlr_swapchain_slot { + struct wlr_buffer *buffer; + bool acquired; // waiting for release + + struct { + struct wl_listener release; + } WLR_PRIVATE; +}; + +struct wlr_swapchain { + struct wlr_allocator *allocator; // NULL if destroyed + + int width, height; + struct wlr_drm_format format; + + struct wlr_swapchain_slot slots[WLR_SWAPCHAIN_CAP]; + + struct { + struct wl_listener allocator_destroy; + } WLR_PRIVATE; +}; + +struct wlr_swapchain *wlr_swapchain_create( + struct wlr_allocator *alloc, int width, int height, + const struct wlr_drm_format *format); +void wlr_swapchain_destroy(struct wlr_swapchain *swapchain); +/** + * Acquire a buffer from the swap chain. + * + * The returned buffer is locked. When the caller is done with it, they must + * unlock it by calling wlr_buffer_unlock. + */ +struct wlr_buffer *wlr_swapchain_acquire(struct wlr_swapchain *swapchain); +/** + * Returns true if this buffer has been created by this swapchain, and false + * otherwise. + */ +bool wlr_swapchain_has_buffer(struct wlr_swapchain *swapchain, + struct wlr_buffer *buffer); + +#endif diff --git a/3rdparty/wlroots/include/wlr/render/vulkan.h b/3rdparty/wlroots/include/wlr/render/vulkan.h new file mode 100644 index 0000000000..5ee84e05fb --- /dev/null +++ b/3rdparty/wlroots/include/wlr/render/vulkan.h @@ -0,0 +1,52 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ + +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_RENDER_VULKAN_H +#define WLR_RENDER_VULKAN_H + +#include +#include + +#include +#include + +struct wlr_buffer; + +struct wlr_vk_image_attribs { + VkImage image; + VkImageLayout layout; + VkFormat format; +}; + +struct wlr_renderer *wlr_vk_renderer_create_with_drm_fd(int drm_fd); + +VkInstance wlr_vk_renderer_get_instance(struct wlr_renderer *renderer); +VkPhysicalDevice wlr_vk_renderer_get_physical_device(struct wlr_renderer *renderer); +VkDevice wlr_vk_renderer_get_device(struct wlr_renderer *renderer); +uint32_t wlr_vk_renderer_get_queue_family(struct wlr_renderer *renderer); + +bool wlr_renderer_is_vk(struct wlr_renderer *wlr_renderer); +bool wlr_texture_is_vk(struct wlr_texture *texture); + +void wlr_vk_texture_get_image_attribs(struct wlr_texture *texture, + struct wlr_vk_image_attribs *attribs); +bool wlr_vk_texture_has_alpha(struct wlr_texture *texture); + +/* waylib extensions (not upstream): Qt Quick RHI bridge helpers. + * Reuse wlroots' own wlr_vk_render_buffer (same path as tinywl/scene), + * instead of creating a parallel VkImage import of the scanout dmabuf. */ +bool waylib_vk_renderer_get_render_buffer_attribs(struct wlr_renderer *renderer, + struct wlr_buffer *buffer, struct wlr_vk_image_attribs *attribs); +bool waylib_vk_renderer_record_render_buffer_acquire(struct wlr_renderer *renderer, + struct wlr_buffer *buffer, VkCommandBuffer cb); +bool waylib_vk_renderer_record_render_buffer_release(struct wlr_renderer *renderer, + struct wlr_buffer *buffer, VkCommandBuffer cb, VkImageLayout old_layout); +bool waylib_vk_renderer_flush_stage(struct wlr_renderer *renderer); + +#endif diff --git a/3rdparty/wlroots/include/wlr/render/wlr_renderer.h b/3rdparty/wlroots/include/wlr/render/wlr_renderer.h new file mode 100644 index 0000000000..902d7564db --- /dev/null +++ b/3rdparty/wlroots/include/wlr/render/wlr_renderer.h @@ -0,0 +1,131 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_RENDER_WLR_RENDERER_H +#define WLR_RENDER_WLR_RENDERER_H + +#include +#include +#include +#include +#include + +struct wlr_backend; +struct wlr_renderer_impl; +struct wlr_drm_format_set; +struct wlr_buffer; +struct wlr_box; +struct wlr_fbox; + +/** + * A renderer for basic 2D operations. + */ +struct wlr_renderer { + // Capabilities required for the buffer used as a render target (bitmask of + // enum wlr_buffer_cap) + uint32_t render_buffer_caps; + // Supported color encodings for YCbCr textures + uint32_t color_encodings; // bitmask of enum wlr_color_encoding + + struct { + struct wl_signal destroy; + /** + * Emitted when the GPU is lost, e.g. on GPU reset. + * + * Compositors should destroy the renderer and re-create it. + */ + struct wl_signal lost; + } events; + + struct { + /** + * Whether color transforms are supported for input textures + */ + bool input_color_transform; + /** + * Does the renderer support color transforms on its output? + */ + bool output_color_transform; + /** + * Whether wait/signal timelines are supported. + * + * See struct wlr_drm_syncobj_timeline. + */ + bool timeline; + } features; + + struct { + const struct wlr_renderer_impl *impl; + } WLR_PRIVATE; +}; + +/** + * Automatically create a new renderer. + * + * Selects an appropriate renderer type to use depending on the backend, + * platform, environment, etc. + */ +struct wlr_renderer *wlr_renderer_autocreate(struct wlr_backend *backend); + +/** + * Get the formats supporting sampling usage. + * + * The buffer capabilities must be passed in. + * + * Buffers allocated with a format from this list may be passed to + * wlr_texture_from_buffer(). + */ +const struct wlr_drm_format_set *wlr_renderer_get_texture_formats( + struct wlr_renderer *r, uint32_t buffer_caps); + +/** + * Initializes wl_shm, linux-dmabuf and other buffer factory protocols. + * + * Returns false on failure. + */ +bool wlr_renderer_init_wl_display(struct wlr_renderer *r, + struct wl_display *wl_display); + +/** + * Initializes wl_shm on the provided struct wl_display. + */ +bool wlr_renderer_init_wl_shm(struct wlr_renderer *r, + struct wl_display *wl_display); + +/** + * Obtains the FD of the DRM device used for rendering, or -1 if unavailable. + * + * The caller doesn't have ownership of the FD, it must not close it. + */ +int wlr_renderer_get_drm_fd(struct wlr_renderer *r); + +/** + * Destroys the renderer. + * + * Textures must be destroyed separately. + */ +void wlr_renderer_destroy(struct wlr_renderer *renderer); + +/** + * Allocate and initialise a new render timer. + */ +struct wlr_render_timer *wlr_render_timer_create(struct wlr_renderer *renderer); + +/** + * Get the render duration in nanoseconds from the timer. + * + * Returns -1 if the duration is unavailable. + */ +int wlr_render_timer_get_duration_ns(struct wlr_render_timer *timer); + +/** + * Destroy the render timer. + */ +void wlr_render_timer_destroy(struct wlr_render_timer *timer); + +#endif diff --git a/3rdparty/wlroots/include/wlr/render/wlr_texture.h b/3rdparty/wlroots/include/wlr/render/wlr_texture.h new file mode 100644 index 0000000000..1e352c6e6d --- /dev/null +++ b/3rdparty/wlroots/include/wlr/render/wlr_texture.h @@ -0,0 +1,85 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_RENDER_WLR_TEXTURE_H +#define WLR_RENDER_WLR_TEXTURE_H + +#include +#include +#include +#include +#include + +struct wlr_buffer; +struct wlr_renderer; +struct wlr_texture_impl; + +struct wlr_texture { + const struct wlr_texture_impl *impl; + uint32_t width, height; + + struct wlr_renderer *renderer; +}; + +struct wlr_texture_read_pixels_options { + /** Memory location to read pixels into */ + void *data; + /** Format used for writing the pixel data */ + uint32_t format; + /** Stride in bytes for the data */ + uint32_t stride; + /** Destination offsets */ + uint32_t dst_x, dst_y; + /** Source box of the texture to read from. If empty, the full texture is assumed. */ + const struct wlr_box src_box; +}; + +bool wlr_texture_read_pixels(struct wlr_texture *texture, + const struct wlr_texture_read_pixels_options *options); + +uint32_t wlr_texture_preferred_read_format(struct wlr_texture *texture); + +/** + * Create a new texture from raw pixel data. `stride` is in bytes. The returned + * texture is mutable. + */ +struct wlr_texture *wlr_texture_from_pixels(struct wlr_renderer *renderer, + uint32_t fmt, uint32_t stride, uint32_t width, uint32_t height, + const void *data); + +/** + * Create a new texture from a DMA-BUF. The returned texture is immutable. + */ +struct wlr_texture *wlr_texture_from_dmabuf(struct wlr_renderer *renderer, + struct wlr_dmabuf_attributes *attribs); + +/** + * Update a texture with a struct wlr_buffer's contents. + * + * The update might be rejected (in case the texture is immutable, the buffer + * has an unsupported type/format, etc), so callers must be prepared to fall + * back to re-creating the texture from scratch via wlr_texture_from_buffer(). + * + * The damage can be used by the renderer as an optimization: only the supplied + * region needs to be updated. + */ +bool wlr_texture_update_from_buffer(struct wlr_texture *texture, + struct wlr_buffer *buffer, const pixman_region32_t *damage); + +/** + * Destroys the texture. + */ +void wlr_texture_destroy(struct wlr_texture *texture); + +/** + * Create a new texture from a buffer. + */ +struct wlr_texture *wlr_texture_from_buffer(struct wlr_renderer *renderer, + struct wlr_buffer *buffer); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_alpha_modifier_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_alpha_modifier_v1.h new file mode 100644 index 0000000000..2485ee46ff --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_alpha_modifier_v1.h @@ -0,0 +1,46 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_ALPHA_MODIFIER_V1_H +#define WLR_TYPES_WLR_ALPHA_MODIFIER_V1_H + +#include +#include + +struct wlr_surface; + +struct wlr_alpha_modifier_surface_v1_state { + double multiplier; // between 0 and 1 +}; + +struct wlr_alpha_modifier_v1 { + struct wl_global *global; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_alpha_modifier_v1 *wlr_alpha_modifier_v1_create(struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_alpha_modifier_v1_destroy(struct wlr_alpha_modifier_v1 *manager, bool destroy_global_safe); + +const struct wlr_alpha_modifier_surface_v1_state *wlr_alpha_modifier_v1_get_surface_state( + struct wlr_surface *surface); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_buffer.h b/3rdparty/wlroots/include/wlr/types/wlr_buffer.h new file mode 100644 index 0000000000..8fd38905ef --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_buffer.h @@ -0,0 +1,209 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_BUFFER_H +#define WLR_TYPES_WLR_BUFFER_H + +#include +#include +#include +#include + +struct wlr_buffer; +struct wlr_renderer; + +/** + * Shared-memory attributes for a buffer. + */ +struct wlr_shm_attributes { + int fd; + uint32_t format; // FourCC code, see DRM_FORMAT_* in + int width, height; + int stride; // Number of bytes between consecutive pixel lines + off_t offset; // Offset in bytes of the first pixel in FD +}; + +/** + * Buffer capabilities. + * + * These bits indicate the features supported by a struct wlr_buffer. There is + * one bit per function in struct wlr_buffer_impl. + */ +enum wlr_buffer_cap { + WLR_BUFFER_CAP_DATA_PTR = 1 << 0, + WLR_BUFFER_CAP_DMABUF = 1 << 1, + WLR_BUFFER_CAP_SHM = 1 << 2, +}; + +/** + * A buffer containing pixel data. + * + * A buffer has a single producer (the party who created the buffer) and + * multiple consumers (parties reading the buffer). When all consumers are done + * with the buffer, it gets released and can be re-used by the producer. When + * the producer and all consumers are done with the buffer, it gets destroyed. + */ +struct wlr_buffer { + const struct wlr_buffer_impl *impl; + + int width, height; + + bool dropped; + size_t n_locks; + bool accessing_data_ptr; + + struct { + struct wl_signal destroy; + struct wl_signal release; + } events; + + struct wlr_addon_set addons; +}; + +/** + * Unreference the buffer. This function should be called by producers when + * they are done with the buffer. + */ +void wlr_buffer_drop(struct wlr_buffer *buffer); +/** + * Lock the buffer. This function should be called by consumers to make + * sure the buffer can be safely read from. Once the consumer is done with the + * buffer, they should call wlr_buffer_unlock(). + */ +struct wlr_buffer *wlr_buffer_lock(struct wlr_buffer *buffer); +/** + * Unlock the buffer. This function should be called by consumers once they are + * done with the buffer. + */ +void wlr_buffer_unlock(struct wlr_buffer *buffer); +/** + * Reads the DMA-BUF attributes of the buffer. If this buffer isn't a DMA-BUF, + * returns false. + * + * The returned DMA-BUF attributes are valid for the lifetime of the + * struct wlr_buffer. The caller isn't responsible for cleaning up the DMA-BUF + * attributes. + */ +bool wlr_buffer_get_dmabuf(struct wlr_buffer *buffer, + struct wlr_dmabuf_attributes *attribs); +/** + * Read shared memory attributes of the buffer. If this buffer isn't shared + * memory, returns false. + * + * The returned shared memory attributes are valid for the lifetime of the + * struct wlr_buffer. The caller isn't responsible for cleaning up the shared + * memory attributes. + */ +bool wlr_buffer_get_shm(struct wlr_buffer *buffer, + struct wlr_shm_attributes *attribs); +/** + * Transforms a struct wl_resource into a struct wlr_buffer and locks it. Once + * the caller is done with the buffer, they must call wlr_buffer_unlock(). + * + * The provided struct wl_resource must be a wl_buffer. + */ +struct wlr_buffer *wlr_buffer_try_from_resource(struct wl_resource *resource); + +/** + * Check whether a buffer is fully opaque. + * + * When true is returned, the buffer is guaranteed to be fully opaque, but the + * reverse is not true: false may be returned in cases where the buffer is fully + * opaque. + */ +bool wlr_buffer_is_opaque(struct wlr_buffer *buffer); + +/** + * Buffer data pointer access flags. + */ +enum wlr_buffer_data_ptr_access_flag { + /** + * The buffer contents can be read back. + */ + WLR_BUFFER_DATA_PTR_ACCESS_READ = 1 << 0, + /** + * The buffer contents can be written to. + */ + WLR_BUFFER_DATA_PTR_ACCESS_WRITE = 1 << 1, +}; + +/** + * Get a pointer to a region of memory referring to the buffer's underlying + * storage. The format and stride can be used to interpret the memory region + * contents. + * + * The returned pointer should be pointing to a valid memory region for the + * operations specified in the flags. The returned pointer is only valid up to + * the next wlr_buffer_end_data_ptr_access() call. + */ +bool wlr_buffer_begin_data_ptr_access(struct wlr_buffer *buffer, uint32_t flags, + void **data, uint32_t *format, size_t *stride); +/** + * Indicate that a pointer to a buffer's underlying memory will no longer be + * used. + * + * This function must be called after wlr_buffer_begin_data_ptr_access(). + */ +void wlr_buffer_end_data_ptr_access(struct wlr_buffer *buffer); + +/** + * A client buffer. + */ +struct wlr_client_buffer { + struct wlr_buffer base; + + /** + * The buffer's texture, if any. A buffer will not have a texture if the + * client destroys the buffer before it has been released. + */ + struct wlr_texture *texture; + /** + * The buffer this client buffer was created from. NULL if destroyed. + */ + struct wlr_buffer *source; + + struct { + struct wl_listener source_destroy; + struct wl_listener renderer_destroy; + + size_t n_ignore_locks; + } WLR_PRIVATE; +}; + +/** + * Get a client buffer from a generic buffer. If the buffer isn't a client + * buffer, returns NULL. + */ +struct wlr_client_buffer *wlr_client_buffer_get(struct wlr_buffer *buffer); + +/** + * A single-pixel buffer. Used by clients to draw solid-color rectangles. + */ +struct wlr_single_pixel_buffer_v1 { + struct wlr_buffer base; + + // Full-scale for each component is UINT32_MAX + uint32_t r, g, b, a; + + struct { + struct wl_resource *resource; + struct wl_listener release; + + // Packed little-endian DRM_FORMAT_ARGB8888. Used for data_ptr_access + uint8_t argb8888[4]; + } WLR_PRIVATE; +}; + +/** + * If the wlr_buffer is a wlr_single_pixel_buffer_v1 then unwrap it. + * Otherwise, returns NULL. + */ +struct wlr_single_pixel_buffer_v1 *wlr_single_pixel_buffer_v1_try_from_buffer( + struct wlr_buffer *buffer); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_color_management_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_color_management_v1.h new file mode 100644 index 0000000000..1f6b2a59bd --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_color_management_v1.h @@ -0,0 +1,150 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_COLOR_MANAGEMENT_V1_H +#define WLR_TYPES_WLR_COLOR_MANAGEMENT_V1_H + +#include +#include +#include + +#include + +struct wlr_renderer; +struct wlr_surface; + +struct wlr_image_description_v1_data { + uint32_t tf_named; // enum wp_color_manager_v1_transfer_function, zero if unset + uint32_t primaries_named; // enum wp_color_manager_v1_primaries, zero if unset + + bool has_mastering_display_primaries; + struct wlr_color_primaries mastering_display_primaries; + + bool has_mastering_luminance; + struct { + float min, max; // cd/m² + } mastering_luminance; + + uint32_t max_cll, max_fall; // cd/m², zero if unset +}; + +struct wlr_color_manager_v1_features { + bool icc_v2_v4; + bool parametric; + bool set_primaries; + bool set_tf_power; + bool set_luminances; + bool set_mastering_display_primaries; + bool extended_target_volume; + bool windows_scrgb; +}; + +struct wlr_color_manager_v1_options { + struct wlr_color_manager_v1_features features; + + const enum wp_color_manager_v1_render_intent *render_intents; + size_t render_intents_len; + + const enum wp_color_manager_v1_transfer_function *transfer_functions; + size_t transfer_functions_len; + + const enum wp_color_manager_v1_primaries *primaries; + size_t primaries_len; +}; + +struct wlr_color_manager_v1 { + struct wl_global *global; + + struct { + struct wl_signal destroy; + } events; + + struct { + struct wlr_color_manager_v1_features features; + + enum wp_color_manager_v1_render_intent *render_intents; + size_t render_intents_len; + + enum wp_color_manager_v1_transfer_function *transfer_functions; + size_t transfer_functions_len; + + enum wp_color_manager_v1_primaries *primaries; + size_t primaries_len; + + struct wl_list outputs; // wlr_color_management_output_v1.link + struct wl_list surface_feedbacks; // wlr_color_management_surface_feedback_v1.link + + uint64_t last_image_desc_identity; + + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_color_manager_v1 *wlr_color_manager_v1_create(struct wl_display *display, + uint32_t version, const struct wlr_color_manager_v1_options *options); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_color_manager_v1_destroy(struct wlr_color_manager_v1 *manager, bool destroy_global_safe); + +const struct wlr_image_description_v1_data * +wlr_surface_get_image_description_v1_data(struct wlr_surface *surface); + +void wlr_color_manager_v1_set_surface_preferred_image_description( + struct wlr_color_manager_v1 *manager, struct wlr_surface *surface, + const struct wlr_image_description_v1_data *data); + +/** + * Convert a protocol transfer function to enum wlr_color_transfer_function. + * Aborts if there is no matching wlroots entry. + */ +enum wlr_color_transfer_function +wlr_color_manager_v1_transfer_function_to_wlr(enum wp_color_manager_v1_transfer_function tf); + +/** + * Convert an enum wlr_color_transfer_function value into a protocol transfer function. + */ +enum wp_color_manager_v1_transfer_function +wlr_color_manager_v1_transfer_function_from_wlr(enum wlr_color_transfer_function tf); + +/** + * Convert a protocol named primaries to enum wlr_color_named_primaries. + * Aborts if there is no matching wlroots entry. + */ +enum wlr_color_named_primaries +wlr_color_manager_v1_primaries_to_wlr(enum wp_color_manager_v1_primaries primaries); + +/** + * Convert an enum wlr_color_named_primaries value into protocol primaries. + */ +enum wp_color_manager_v1_primaries +wlr_color_manager_v1_primaries_from_wlr(enum wlr_color_named_primaries primaries); + +/** + * Get a list of supported transfer functions for a renderer. The caller is + * responsible for free'ing the array. + */ +enum wp_color_manager_v1_transfer_function * +wlr_color_manager_v1_transfer_function_list_from_renderer(struct wlr_renderer *renderer, size_t *len); + +/** + * Get a list of supported named primaries for a renderer. The caller is + * responsible for free'ing the array. + */ +enum wp_color_manager_v1_primaries * +wlr_color_manager_v1_primaries_list_from_renderer(struct wlr_renderer *renderer, size_t *len); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_color_representation_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_color_representation_v1.h new file mode 100644 index 0000000000..ae20865a0e --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_color_representation_v1.h @@ -0,0 +1,109 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_COLOR_REPRESENTATION_V1_H +#define WLR_TYPES_WLR_COLOR_REPRESENTATION_V1_H + +#include +#include +#include +#include + +struct wlr_surface; +struct wlr_renderer; + +// Supported coefficients and range are always paired together +struct wlr_color_representation_v1_coeffs_and_range { + enum wp_color_representation_surface_v1_coefficients coeffs; + enum wp_color_representation_surface_v1_range range; +}; + +struct wlr_color_representation_manager_v1 { + struct wl_global *global; + + struct { + // Manager is being destroyed + struct wl_signal destroy; + } events; + + struct { + enum wp_color_representation_surface_v1_alpha_mode + *supported_alpha_modes; + size_t supported_alpha_modes_len; + + struct wlr_color_representation_v1_coeffs_and_range + *supported_coeffs_and_ranges; + size_t supported_coeffs_and_ranges_len; + + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +// Options used when initialising a wlr_color_representation_manager_v1 +struct wlr_color_representation_v1_options { + const enum wp_color_representation_surface_v1_alpha_mode *supported_alpha_modes; + size_t supported_alpha_modes_len; + + const struct wlr_color_representation_v1_coeffs_and_range *supported_coeffs_and_ranges; + size_t supported_coeffs_and_ranges_len; +}; + +struct wlr_color_representation_manager_v1 *wlr_color_representation_manager_v1_create( + struct wl_display *display, uint32_t version, + const struct wlr_color_representation_v1_options *options); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_color_representation_manager_v1_destroy( + struct wlr_color_representation_manager_v1 *manager, bool destroy_global_safe); + +struct wlr_color_representation_manager_v1 *wlr_color_representation_manager_v1_create_with_renderer( + struct wl_display *display, uint32_t version, struct wlr_renderer *renderer); + +// This is all the color-representation state which can be attached to a +// surface, double-buffered and made current on commit +struct wlr_color_representation_v1_surface_state { + // The enum premultiplied_electrical has value zero and is defined + // to be the default if unspecified. + enum wp_color_representation_surface_v1_alpha_mode alpha_mode; + + // If zero then indicates unset, otherwise values correspond to + // enum wp_color_representation_surface_v1_coefficients + uint32_t coefficients; + + // If zero then indicates unset, otherwise values correspond to + // enum wp_color_representation_surface_v1_range + uint32_t range; + + // If zero then indicates unset, otherwise values correspond to + // enum wp_color_representation_surface_v1_chroma_location + uint32_t chroma_location; +}; + +// Get the current color representation state committed to a surface +const struct wlr_color_representation_v1_surface_state *wlr_color_representation_v1_get_surface_state( + struct wlr_surface *surface); + +enum wlr_alpha_mode wlr_color_representation_v1_alpha_mode_to_wlr( + enum wp_color_representation_surface_v1_alpha_mode wp_val); +enum wlr_color_encoding wlr_color_representation_v1_color_encoding_to_wlr( + enum wp_color_representation_surface_v1_coefficients wp_val); +enum wlr_color_range wlr_color_representation_v1_color_range_to_wlr( + enum wp_color_representation_surface_v1_range wp_val); +enum wlr_color_chroma_location wlr_color_representation_v1_chroma_location_to_wlr( + enum wp_color_representation_surface_v1_chroma_location wp_val); + +#endif // WLR_TYPES_WLR_COLOR_REPRESENTATION_V1_H diff --git a/3rdparty/wlroots/include/wlr/types/wlr_compositor.h b/3rdparty/wlroots/include/wlr/types/wlr_compositor.h new file mode 100644 index 0000000000..70baebb80c --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_compositor.h @@ -0,0 +1,593 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_COMPOSITOR_H +#define WLR_TYPES_WLR_COMPOSITOR_H + +#include +#include +#include +#include +#include +#include +#include + +struct wlr_surface; + +enum wlr_surface_state_field { + WLR_SURFACE_STATE_BUFFER = 1 << 0, + WLR_SURFACE_STATE_SURFACE_DAMAGE = 1 << 1, + WLR_SURFACE_STATE_BUFFER_DAMAGE = 1 << 2, + WLR_SURFACE_STATE_OPAQUE_REGION = 1 << 3, + WLR_SURFACE_STATE_INPUT_REGION = 1 << 4, + WLR_SURFACE_STATE_TRANSFORM = 1 << 5, + WLR_SURFACE_STATE_SCALE = 1 << 6, + WLR_SURFACE_STATE_FRAME_CALLBACK_LIST = 1 << 7, + WLR_SURFACE_STATE_VIEWPORT = 1 << 8, + WLR_SURFACE_STATE_OFFSET = 1 << 9, +}; + +struct wlr_surface_state { + uint32_t committed; // enum wlr_surface_state_field + // Sequence number of the surface state. Incremented on each commit, may + // overflow. + uint32_t seq; + + struct wlr_buffer *buffer; + int32_t dx, dy; // relative to previous position + pixman_region32_t surface_damage, buffer_damage; // clipped to bounds + pixman_region32_t opaque, input; + enum wl_output_transform transform; + int32_t scale; + struct wl_list frame_callback_list; // wl_resource + + int width, height; // in surface-local coordinates + int buffer_width, buffer_height; + + struct wl_list subsurfaces_below; + struct wl_list subsurfaces_above; + + /** + * The viewport is applied after the surface transform and scale. + * + * If has_src is true, the surface content is cropped to the provided + * rectangle. If has_dst is true, the surface content is scaled to the + * provided rectangle. + */ + struct { + bool has_src, has_dst; + // In coordinates after scale/transform are applied, but before the + // destination rectangle is applied + struct wlr_fbox src; + int dst_width, dst_height; // in surface-local coordinates + } viewport; + + // Number of locks that prevent this surface state from being committed. + size_t cached_state_locks; + struct wl_list cached_state_link; // wlr_surface.cached + + // Sync'ed object states, one per struct wlr_surface_synced + struct wl_array synced; // void * +}; + +struct wlr_surface_role { + const char *name; + /** + * If true, the role isn't represented by any object. + * For example, this applies to cursor surfaces. + */ + bool no_object; + /** + * Called when the client sends the wl_surface.commit request. May be NULL. + * Typically used to check that the pending state is valid, and send + * protocol errors if not. + * + * If the role is represented by an object, this is only called if + * such object exists. + */ + void (*client_commit)(struct wlr_surface *surface); + /** + * Called when a new surface state is committed. May be NULL. + * + * If the role is represented by an object, this is only called if + * such object exists. + */ + void (*commit)(struct wlr_surface *surface); + /** + * Called when the surface is mapped. May be NULL. + * + * If the role is represented by an object, this is only called if + * such object exists. + */ + void (*map)(struct wlr_surface *surface); + /** + * Called when the surface is unmapped. May be NULL. + * + * If the role is represented by an object, this is only called if + * such object exists. + */ + void (*unmap)(struct wlr_surface *surface); + /** + * Called when the object representing the role is destroyed. May be NULL. + */ + void (*destroy)(struct wlr_surface *surface); +}; + +struct wlr_surface_output { + struct wlr_surface *surface; + struct wlr_output *output; + + struct wl_list link; // wlr_surface.current_outputs + + struct { + struct wl_listener bind; + struct wl_listener destroy; + + bool suspended; + } WLR_PRIVATE; +}; + +struct wlr_surface { + struct wl_resource *resource; + struct wlr_compositor *compositor; + /** + * The surface's buffer, if any. A surface has an attached buffer when it + * commits with a non-null buffer in its pending state. A surface will not + * have a buffer if it has never committed one, has committed a null buffer, + * or something went wrong with uploading the buffer. + */ + struct wlr_client_buffer *buffer; + /** + * The last commit's buffer damage, in buffer-local coordinates. This + * contains both the damage accumulated by the client via + * `wlr_surface_state.surface_damage` and `wlr_surface_state.buffer_damage`. + * If the buffer has been resized, the whole buffer is damaged. + * + * This region needs to be scaled and transformed into output coordinates, + * just like the buffer's texture. In addition, if the buffer has shrunk the + * old size needs to be damaged and if the buffer has moved the old and new + * positions need to be damaged. + */ + pixman_region32_t buffer_damage; + /** + * The current opaque region, in surface-local coordinates. It is clipped to + * the surface bounds. If the surface's buffer is using a fully opaque + * format, this is set to the whole surface. + */ + pixman_region32_t opaque_region; + /** + * The current input region, in surface-local coordinates. It is clipped to + * the surface bounds. + * + * If the protocol states that the input region is ignored, this is empty. + */ + pixman_region32_t input_region; + /** + * `current` contains the current, committed surface state. `pending` + * accumulates state changes from the client between commits and shouldn't + * be accessed by the compositor directly. + */ + struct wlr_surface_state current, pending; + + struct wl_list cached; // wlr_surface_state.cached_link + + /** + * Whether the surface is ready to be displayed. + */ + bool mapped; + + /** + * The lifetime-bound role of the surface. NULL if the role was never set. + */ + const struct wlr_surface_role *role; + + /** + * The role object representing the role. NULL if the role isn't + * represented by any object or the object was destroyed. + */ + struct wl_resource *role_resource; + + struct { + /** + * Signals that the client has sent a wl_surface.commit request. + * + * The state to be committed can be accessed in wlr_surface.pending. + * + * The commit may not be applied immediately, in which case it's marked + * as "cached" and put into a queue. See wlr_surface_lock_pending(). + */ + struct wl_signal client_commit; + /** + * Signals that a commit has been applied. + * + * The new state can be accessed in wlr_surface.current. + */ + struct wl_signal commit; + + /** + * Signals that the surface has a non-null buffer committed and is + * ready to be displayed. + */ + struct wl_signal map; + /** + * Signals that the surface shouldn't be displayed anymore. This can + * happen when a null buffer is committed, the associated role object + * is destroyed, or when the role-specific conditions for the surface + * to be mapped no longer apply. + */ + struct wl_signal unmap; + + /** + * Signals that a new child sub-surface has been added. + * + * Note: unlike other new_* signals, new_subsurface is emitted when + * the subsurface is added to the parent surface's current state, + * not when the object is created. + */ + struct wl_signal new_subsurface; // struct wlr_subsurface + + /** + * Signals that the surface is being destroyed. + */ + struct wl_signal destroy; + } events; + + struct wl_list current_outputs; // wlr_surface_output.link + + struct wlr_addon_set addons; + void *data; + + struct { + struct wl_listener role_resource_destroy; + + struct { + int32_t scale; + enum wl_output_transform transform; + int width, height; + int buffer_width, buffer_height; + } previous; + + bool unmap_commit; + + bool opaque; + + bool handling_commit; + bool pending_rejected; + + int32_t preferred_buffer_scale; + bool preferred_buffer_transform_sent; + enum wl_output_transform preferred_buffer_transform; + + struct wl_list synced; // wlr_surface_synced.link + size_t synced_len; + + struct wl_resource *pending_buffer_resource; + struct wl_listener pending_buffer_resource_destroy; + } WLR_PRIVATE; +}; + +struct wlr_renderer; + +struct wlr_compositor { + struct wl_global *global; + struct wlr_renderer *renderer; // may be NULL + + struct { + struct wl_signal new_surface; + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + struct wl_listener renderer_destroy; + } WLR_PRIVATE; +}; + +typedef void (*wlr_surface_iterator_func_t)(struct wlr_surface *surface, + int sx, int sy, void *data); + +/** + * Set the lifetime role for this surface. + * + * If the surface already has a different role and/or has a role object set, + * the function fails and sends an error to the client. + * + * Returns true on success, false otherwise. + */ +bool wlr_surface_set_role(struct wlr_surface *surface, const struct wlr_surface_role *role, + struct wl_resource *error_resource, uint32_t error_code); + +/** + * Set the role object for this surface. The surface must have a role and + * no already set role object. + * + * When the resource is destroyed, the surface is unmapped, + * wlr_surface_role.destroy is called and the role object is unset. + */ +void wlr_surface_set_role_object(struct wlr_surface *surface, struct wl_resource *role_resource); + +/** + * Map the surface. If the surface is already mapped, this is no-op. + * + * This function must only be used by surface role implementations. + */ +void wlr_surface_map(struct wlr_surface *surface); + +/** + * Unmap the surface. If the surface is already unmapped, this is no-op. + * + * This function must only be used by surface role implementations. + */ +void wlr_surface_unmap(struct wlr_surface *surface); + +/** + * Mark the pending state of a surface as rejected due to a protocol violation, + * preventing it from being cached or committed. + * + * This function must only be used while processing a commit request. + */ +void wlr_surface_reject_pending(struct wlr_surface *surface, struct wl_resource *resource, + uint32_t code, const char *msg, ...); + +/** + * Whether or not this surface currently has an attached buffer. A surface has + * an attached buffer when it commits with a non-null buffer in its pending + * state. A surface will not have a buffer if it has never committed one or has + * committed a null buffer. + */ +bool wlr_surface_has_buffer(struct wlr_surface *surface); + +/** + * Check whether this surface state has an attached buffer. + * + * A surface has an attached buffer when the client commits with a non-null + * buffer. A surface will not have a buffer if the client never committed one, + * or committed a null buffer. + * + * Note that wlr_surface_state.buffer may be NULL even if this function returns + * true: the buffer field is reset after commit, to allow the buffer to be + * released to the client. Additionally, the buffer import or upload may fail. + */ +bool wlr_surface_state_has_buffer(const struct wlr_surface_state *state); + +/** + * Get the texture of the buffer currently attached to this surface. Returns + * NULL if no buffer is currently attached or if something went wrong with + * uploading the buffer. + */ +struct wlr_texture *wlr_surface_get_texture(struct wlr_surface *surface); + +/** + * Get the root of the subsurface tree for this surface. + * May return the same surface passed if that surface is the root. + * Never returns NULL. + */ +struct wlr_surface *wlr_surface_get_root_surface(struct wlr_surface *surface); + +/** + * Check if the surface accepts input events at the given surface-local + * coordinates. Does not check the surface's subsurfaces. + */ +bool wlr_surface_point_accepts_input(struct wlr_surface *surface, + double sx, double sy); + +/** + * Find a surface in this surface's tree that accepts input events and has all + * parents mapped (except this surface, which can be unmapped) at the given + * surface-local coordinates. Returns the surface and coordinates in the leaf + * surface coordinate system or NULL if no surface is found at that location. + */ +struct wlr_surface *wlr_surface_surface_at(struct wlr_surface *surface, + double sx, double sy, double *sub_x, double *sub_y); + +/** + * Notify the client that the surface has entered an output. + * + * This is a no-op if the surface has already entered the output. + */ +void wlr_surface_send_enter(struct wlr_surface *surface, + struct wlr_output *output); + +/** + * Notify the client that the surface has left an output. + * + * This is a no-op if the surface has already left the output. + */ +void wlr_surface_send_leave(struct wlr_surface *surface, + struct wlr_output *output); + +/** + * Complete the queued frame callbacks for this surface. + * + * This will send an event to the client indicating that now is a good time to + * draw its next frame. + */ +void wlr_surface_send_frame_done(struct wlr_surface *surface, + const struct timespec *when); + +/** + * Get the bounding box that contains the surface and all subsurfaces in + * surface coordinates. + * X and y may be negative, if there are subsurfaces with negative position. + */ +void wlr_surface_get_extents(struct wlr_surface *surface, struct wlr_box *box); + +/** + * Get the struct wlr_surface corresponding to a wl_surface resource. + * + * This asserts that the resource is a valid wl_surface resource created by + * wlroots and will never return NULL. + */ +struct wlr_surface *wlr_surface_from_resource(struct wl_resource *resource); + +/** + * Call `iterator` on each mapped surface in the surface tree (whether or not + * this surface is mapped), with the surface's position relative to the root + * surface. The function is called from root to leaves (in rendering order). + */ +void wlr_surface_for_each_surface(struct wlr_surface *surface, + wlr_surface_iterator_func_t iterator, void *user_data); + +/** + * Get the effective surface damage in surface-local coordinate space. + */ +void wlr_surface_get_effective_damage(struct wlr_surface *surface, + pixman_region32_t *damage); + +/** + * Get the source rectangle describing the region of the buffer that needs to + * be sampled to render this surface's current state. The box is in + * buffer-local coordinates. + * + * If the viewport's source rectangle is unset, the position is zero and the + * size is the buffer's. + */ +void wlr_surface_get_buffer_source_box(struct wlr_surface *surface, + struct wlr_fbox *box); + +/** + * Acquire a lock for the pending surface state. + * + * The state won't be committed before the caller releases the lock. Instead, + * the state becomes cached. The caller needs to use wlr_surface_unlock_cached() + * to release the lock. + * + * Returns a surface commit sequence number for the cached state. + */ +uint32_t wlr_surface_lock_pending(struct wlr_surface *surface); + +/** + * Release a lock for a cached state. + * + * Callers should not assume that the cached state will immediately be + * committed. Another caller may still have an active lock. + */ +void wlr_surface_unlock_cached(struct wlr_surface *surface, uint32_t seq); + +/** + * Set the preferred buffer scale for the surface. + * + * This sends an event to the client indicating the preferred scale to use for + * buffers attached to this surface. + */ +void wlr_surface_set_preferred_buffer_scale(struct wlr_surface *surface, + int32_t scale); + +/** + * Set the preferred buffer transform for the surface. + * + * This sends an event to the client indicating the preferred transform to use + * for buffers attached to this surface. + */ +void wlr_surface_set_preferred_buffer_transform(struct wlr_surface *surface, + enum wl_output_transform transform); + +struct wlr_surface_synced; + +/** + * Implementation for struct wlr_surface_synced. + * + * struct wlr_surface takes care of allocating the sync'ed object state. + * + * The only mandatory field is state_size. + */ +struct wlr_surface_synced_impl { + // Size in bytes of the state struct. + size_t state_size; + // Initialize a state. If NULL, this is a no-op. + void (*init_state)(void *state); + // Finish a state. If NULL, this is a no-op. + void (*finish_state)(void *state); + // Move a state. If NULL, memcpy() is used. + void (*move_state)(void *dst, void *src); + + // Called when the state is committed. If NULL, this is a no-op. + // If an object is a surface role object which has state synchronized with + // the surface state, the role commit hook should be preferred over this. + void (*commit)(struct wlr_surface_synced *synced); +}; + +/** + * An object synchronized with a surface. + * + * This is typically used by surface add-ons which integrate with the surface + * commit mechanism. + * + * A sync'ed object maintains state whose lifecycle is managed by + * struct wlr_surface_synced_impl. Clients make requests to mutate the pending + * state, then clients commit the pending state via wl_surface.commit. The + * pending state may become cached, then becomes current when it's applied. + */ +struct wlr_surface_synced { + struct wlr_surface *surface; + const struct wlr_surface_synced_impl *impl; + struct wl_list link; // wlr_surface.synced + size_t index; +}; + +/** + * Initialize a sync'ed object. + * + * pending and current must be pointers to the sync'ed object's state. This + * function will initialize them. + */ +bool wlr_surface_synced_init(struct wlr_surface_synced *synced, + struct wlr_surface *surface, const struct wlr_surface_synced_impl *impl, + void *pending, void *current); +/** + * Finish a sync'ed object. + * + * This must be called before the struct wlr_surface is destroyed. + */ +void wlr_surface_synced_finish(struct wlr_surface_synced *synced); +/** + * Obtain a sync'ed object state. + */ +void *wlr_surface_synced_get_state(struct wlr_surface_synced *synced, + const struct wlr_surface_state *state); + +/** + * Get a Pixman region from a wl_region resource. + */ +const pixman_region32_t *wlr_region_from_resource(struct wl_resource *resource); + +/** + * Create the wl_compositor global, which can be used by clients to create + * surfaces and regions. + * + * If a renderer is supplied, the compositor will create struct wlr_texture + * objects from client buffers on surface commit. + */ +struct wlr_compositor *wlr_compositor_create(struct wl_display *display, + uint32_t version, struct wlr_renderer *renderer); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_compositor_destroy(struct wlr_compositor *compositor, bool destroy_global_safe); + +/** + * Set the renderer used for creating struct wlr_texture objects from client + * buffers on surface commit. + * + * The renderer may be NULL, in which case no textures are created. + * + * Calling this function does not update existing textures, it only affects + * future surface commits. + */ +void wlr_compositor_set_renderer(struct wlr_compositor *compositor, + struct wlr_renderer *renderer); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_content_type_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_content_type_v1.h new file mode 100644 index 0000000000..b4382b9439 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_content_type_v1.h @@ -0,0 +1,50 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_CONTENT_TYPE_V1_H +#define WLR_TYPES_WLR_CONTENT_TYPE_V1_H + +#include +#include +#include + +struct wlr_surface; + +struct wlr_content_type_manager_v1 { + struct wl_global *global; + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_content_type_manager_v1 *wlr_content_type_manager_v1_create( + struct wl_display *display, uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_content_type_manager_v1_destroy(struct wlr_content_type_manager_v1 *manager, + bool destroy_global_safe); +enum wp_content_type_v1_type wlr_surface_get_content_type_v1( + struct wlr_content_type_manager_v1 *manager, struct wlr_surface *surface); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_cursor.h b/3rdparty/wlroots/include/wlr/types/wlr_cursor.h new file mode 100644 index 0000000000..aaa18a4377 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_cursor.h @@ -0,0 +1,218 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_CURSOR_H +#define WLR_TYPES_WLR_CURSOR_H + +#include +#include + +struct wlr_input_device; +struct wlr_surface; +struct wlr_xcursor_manager; + +/** + * wlr_cursor implements the behavior of the "cursor", that is, the image on the + * screen typically moved about with a mouse or so. It provides tracking for + * this in global coordinates, and integrates with struct wlr_output, + * struct wlr_output_layout, and struct wlr_input_device. You can use it to + * abstract multiple input devices over a single cursor, constrain cursor + * movement to the usable area of a struct wlr_output_layout and communicate + * position updates to the hardware cursor, constrain specific input devices to + * specific outputs or regions of the screen, and so on. + */ + +struct wlr_box; +struct wlr_cursor_state; + +struct wlr_cursor { + struct wlr_cursor_state *state; + double x, y; + + /** + * The interpretation of these signals is the responsibility of the + * compositor, but some helpers are provided for your benefit. If you + * receive a relative motion event, for example, you may want to call + * wlr_cursor_move(). If you receive an absolute event, call + * wlr_cursor_warp_absolute(). If you pass an input device into these + * functions, it will apply the region/output constraints associated with + * that device to the resulting cursor motion. If an output layout is + * attached, these functions will constrain the resulting cursor motion to + * within the usable space of the output layout. + * + * Re-broadcasting these signals to, for example, a struct wlr_seat, is also + * your responsibility. + */ + struct { + struct wl_signal motion; // struct wlr_pointer_motion_event + struct wl_signal motion_absolute; // struct wlr_pointer_motion_absolute_event + struct wl_signal button; // struct wlr_pointer_button_event + struct wl_signal axis; // struct wlr_pointer_axis_event + struct wl_signal frame; + struct wl_signal swipe_begin; // struct wlr_pointer_swipe_begin_event + struct wl_signal swipe_update; // struct wlr_pointer_swipe_update_event + struct wl_signal swipe_end; // struct wlr_pointer_swipe_end_event + struct wl_signal pinch_begin; // struct wlr_pointer_pinch_begin_event + struct wl_signal pinch_update; // struct wlr_pointer_pinch_update_event + struct wl_signal pinch_end; // struct wlr_pointer_pinch_end_event + struct wl_signal hold_begin; // struct wlr_pointer_hold_begin_event + struct wl_signal hold_end; // struct wlr_pointer_hold_end_event + + struct wl_signal touch_up; // struct wlr_touch_up_event + struct wl_signal touch_down; // struct wlr_touch_down_event + struct wl_signal touch_motion; // struct wlr_touch_motion_event + struct wl_signal touch_cancel; // struct wlr_touch_cancel_event + struct wl_signal touch_frame; + + struct wl_signal tablet_tool_axis; // struct wlr_tablet_tool_axis_event + struct wl_signal tablet_tool_proximity; // struct wlr_tablet_tool_proximity_event + struct wl_signal tablet_tool_tip; // struct wlr_tablet_tool_tip_event + struct wl_signal tablet_tool_button; // struct wlr_tablet_tool_button_event + } events; + + void *data; +}; + +struct wlr_cursor *wlr_cursor_create(void); + +void wlr_cursor_destroy(struct wlr_cursor *cur); + +/** + * Warp the cursor to the given x and y in layout coordinates. If x and y are + * out of the layout boundaries or constraints, no warp will happen. + * + * `dev` may be passed to respect device mapping constraints. If `dev` is NULL, + * device mapping constraints will be ignored. + * + * Returns true when the cursor warp was successful. + */ +bool wlr_cursor_warp(struct wlr_cursor *cur, struct wlr_input_device *dev, + double lx, double ly); + +/** + * Convert absolute 0..1 coordinates to layout coordinates. + * + * `dev` may be passed to respect device mapping constraints. If `dev` is NULL, + * device mapping constraints will be ignored. + */ +void wlr_cursor_absolute_to_layout_coords(struct wlr_cursor *cur, + struct wlr_input_device *dev, double x, double y, double *lx, double *ly); + + +/** + * Warp the cursor to the given x and y coordinates. If the given point is out + * of the layout boundaries or constraints, the closest point will be used. + * If one coordinate is NAN, it will be ignored. + * + * `dev` may be passed to respect device mapping constraints. If `dev` is NULL, + * device mapping constraints will be ignored. + */ +void wlr_cursor_warp_closest(struct wlr_cursor *cur, + struct wlr_input_device *dev, double x, double y); + +/** + * Warp the cursor to the given x and y in absolute 0..1 coordinates. If the + * given point is out of the layout boundaries or constraints, the closest point + * will be used. If one coordinate is NAN, it will be ignored. + * + * `dev` may be passed to respect device mapping constraints. If `dev` is NULL, + * device mapping constraints will be ignored. + */ +void wlr_cursor_warp_absolute(struct wlr_cursor *cur, + struct wlr_input_device *dev, double x, double y); + +/** + * Move the cursor in the direction of the given x and y layout coordinates. If + * one coordinate is NAN, it will be ignored. + * + * `dev` may be passed to respect device mapping constraints. If `dev` is NULL, + * device mapping constraints will be ignored. + */ +void wlr_cursor_move(struct wlr_cursor *cur, struct wlr_input_device *dev, + double delta_x, double delta_y); + +/** + * Set the cursor buffer. + * + * The buffer is used on all outputs and is scaled accordingly. The hotspot is + * expressed in logical coordinates. A NULL buffer hides the cursor. + */ +void wlr_cursor_set_buffer(struct wlr_cursor *cur, struct wlr_buffer *buffer, + int32_t hotspot_x, int32_t hotspot_y, float scale); + +/** + * Hide the cursor image. + */ +void wlr_cursor_unset_image(struct wlr_cursor *cur); + +/** + * Set the cursor image from an XCursor theme. + * + * The image will be loaded from the struct wlr_xcursor_manager. + */ +void wlr_cursor_set_xcursor(struct wlr_cursor *cur, + struct wlr_xcursor_manager *manager, const char *name); + +/** + * Set the cursor surface. The surface can be committed to update the cursor + * image. The surface position is subtracted from the hotspot. A NULL surface + * commit hides the cursor. + */ +void wlr_cursor_set_surface(struct wlr_cursor *cur, struct wlr_surface *surface, + int32_t hotspot_x, int32_t hotspot_y); + +/** + * Attaches this input device to this cursor. The input device must be one of: + * + * - WLR_INPUT_DEVICE_POINTER + * - WLR_INPUT_DEVICE_TOUCH + * - WLR_INPUT_DEVICE_TABLET + */ +void wlr_cursor_attach_input_device(struct wlr_cursor *cur, + struct wlr_input_device *dev); + +void wlr_cursor_detach_input_device(struct wlr_cursor *cur, + struct wlr_input_device *dev); +/** + * Uses the given layout to establish the boundaries and movement semantics of + * this cursor. Cursors without an output layout allow infinite movement in any + * direction and do not support absolute input events. + */ +void wlr_cursor_attach_output_layout(struct wlr_cursor *cur, + struct wlr_output_layout *l); + +/** + * Attaches this cursor to the given output, which must be among the outputs in + * the current output_layout for this cursor. This call is invalid for a cursor + * without an associated output layout. + */ +void wlr_cursor_map_to_output(struct wlr_cursor *cur, + struct wlr_output *output); + +/** + * Maps all input from a specific input device to a given output. The input + * device must be attached to this cursor and the output must be among the + * outputs in the attached output layout. + */ +void wlr_cursor_map_input_to_output(struct wlr_cursor *cur, + struct wlr_input_device *dev, struct wlr_output *output); + +/** + * Maps this cursor to an arbitrary region on the associated + * struct wlr_output_layout. + */ +void wlr_cursor_map_to_region(struct wlr_cursor *cur, const struct wlr_box *box); + +/** + * Maps inputs from this input device to an arbitrary region on the associated + * struct wlr_output_layout. + */ +void wlr_cursor_map_input_to_region(struct wlr_cursor *cur, + struct wlr_input_device *dev, const struct wlr_box *box); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_cursor_shape_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_cursor_shape_v1.h new file mode 100644 index 0000000000..5ea7662598 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_cursor_shape_v1.h @@ -0,0 +1,74 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_CURSOR_SHAPE_V1_H +#define WLR_TYPES_WLR_CURSOR_SHAPE_V1_H + +#include +#include +#include + +/** + * Manager for the cursor-shape-v1 protocol. + * + * Compositors should listen to the request_set_shape event and handle it in + * the same way as wlr_seat.events.request_set_cursor. + */ +struct wlr_cursor_shape_manager_v1 { + struct wl_global *global; + + struct { + struct wl_signal request_set_shape; // struct wlr_cursor_shape_manager_v1_request_set_shape_event + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +enum wlr_cursor_shape_manager_v1_device_type { + WLR_CURSOR_SHAPE_MANAGER_V1_DEVICE_TYPE_POINTER, + WLR_CURSOR_SHAPE_MANAGER_V1_DEVICE_TYPE_TABLET_TOOL, +}; + +struct wlr_cursor_shape_manager_v1_request_set_shape_event { + struct wlr_seat_client *seat_client; + enum wlr_cursor_shape_manager_v1_device_type device_type; + // NULL if device_type is not TABLET_TOOL + struct wlr_tablet_v2_tablet_tool *tablet_tool; + uint32_t serial; + enum wp_cursor_shape_device_v1_shape shape; +}; + +struct wlr_cursor_shape_manager_v1 *wlr_cursor_shape_manager_v1_create( + struct wl_display *display, uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_cursor_shape_manager_v1_destroy(struct wlr_cursor_shape_manager_v1 *manager, + bool destroy_global_safe); + +/** + * Get the name of a cursor shape. + * + * The name can be used to load a cursor from an XCursor theme. + */ +const char *wlr_cursor_shape_v1_name(enum wp_cursor_shape_device_v1_shape shape); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_damage_ring.h b/3rdparty/wlroots/include/wlr/types/wlr_damage_ring.h new file mode 100644 index 0000000000..cc2eaa0f2e --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_damage_ring.h @@ -0,0 +1,79 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_DAMAGE_RING_H +#define WLR_TYPES_WLR_DAMAGE_RING_H + +#include +#include +#include +#include +#include + +struct wlr_box; + +struct wlr_damage_ring_buffer { + struct wlr_buffer *buffer; + pixman_region32_t damage; + + struct wlr_damage_ring *ring; + struct wl_list link; // wlr_damage_ring.buffers + + struct { + struct wl_listener destroy; + } WLR_PRIVATE; +}; + +struct wlr_damage_ring { + // Difference between the current buffer and the previous one + pixman_region32_t current; + + struct { + struct wl_list buffers; // wlr_damage_ring_buffer.link + } WLR_PRIVATE; +}; + +void wlr_damage_ring_init(struct wlr_damage_ring *ring); + +void wlr_damage_ring_finish(struct wlr_damage_ring *ring); + +/** + * Add a region to the current damage. The region must be in the buffer-local + * coordinate space. + */ +void wlr_damage_ring_add(struct wlr_damage_ring *ring, + const pixman_region32_t *damage); + +/** + * Add a box to the current damage. The box must be in the buffer-local + * coordinate space. + */ +void wlr_damage_ring_add_box(struct wlr_damage_ring *ring, + const struct wlr_box *box); + +/** + * Damage the ring fully. + */ +void wlr_damage_ring_add_whole(struct wlr_damage_ring *ring); + +/** + * Get accumulated buffer damage and rotate the damage ring. + * + * The accumulated buffer damage is the difference between the to-be-painted + * buffer and the passed-in buffer. In other words, this is the region that + * needs to be redrawn. + * + * Users should damage the ring if an error occurs while rendering or + * submitting the new buffer to the backend. + * + * The returned damage will be in the buffer-local coordinate space. + */ +void wlr_damage_ring_rotate_buffer(struct wlr_damage_ring *ring, + struct wlr_buffer *buffer, pixman_region32_t *damage); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_data_control_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_data_control_v1.h new file mode 100644 index 0000000000..66e2faed86 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_data_control_v1.h @@ -0,0 +1,71 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_DATA_CONTROL_V1_H +#define WLR_TYPES_WLR_DATA_CONTROL_V1_H + +#include +#include +#include + +/** + * Deprecated: this protocol is legacy and superseded by ext-data-control-v1. + * The implementation will be dropped in a future wlroots version. + * + * Consider using `wlr_ext_data_control_manager_v1` as a replacement. + */ +struct wlr_data_control_manager_v1 { + struct wl_global *global; + struct wl_list devices; // wlr_data_control_device_v1.link + + struct { + struct wl_signal destroy; + struct wl_signal new_device; // wlr_data_control_device_v1 + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_data_control_device_v1 { + struct wl_resource *resource; + struct wlr_data_control_manager_v1 *manager; + struct wl_list link; // wlr_data_control_manager_v1.devices + + struct wlr_seat *seat; + struct wl_resource *selection_offer_resource; // current selection offer + struct wl_resource *primary_selection_offer_resource; // current primary selection offer + + struct { + struct wl_listener seat_destroy; + struct wl_listener seat_set_selection; + struct wl_listener seat_set_primary_selection; + } WLR_PRIVATE; +}; + +struct wlr_data_control_manager_v1 *wlr_data_control_manager_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_data_control_manager_v1_destroy(struct wlr_data_control_manager_v1 *manager, + bool destroy_global_safe); + +void wlr_data_control_device_v1_destroy( + struct wlr_data_control_device_v1 *device); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_data_device.h b/3rdparty/wlroots/include/wlr/types/wlr_data_device.h new file mode 100644 index 0000000000..96a4e234c9 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_data_device.h @@ -0,0 +1,279 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_DATA_DEVICE_H +#define WLR_TYPES_WLR_DATA_DEVICE_H + +#include +#include +#include + +struct wlr_data_device_manager { + struct wl_global *global; + struct wl_list data_sources; + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +enum wlr_data_offer_type { + WLR_DATA_OFFER_SELECTION, + WLR_DATA_OFFER_DRAG, +}; + +struct wlr_data_offer { + struct wl_resource *resource; + struct wlr_data_source *source; + enum wlr_data_offer_type type; + struct wl_list link; // wlr_seat.{selection_offers,drag_offers} + + uint32_t actions; + enum wl_data_device_manager_dnd_action preferred_action; + bool in_ask; + + struct { + struct wl_listener source_destroy; + } WLR_PRIVATE; +}; + +/** + * A data source implementation. Only the `send` function is mandatory. Refer to + * the matching `wlr_data_source_*` functions documentation to know what they do. + */ +struct wlr_data_source_impl { + void (*send)(struct wlr_data_source *source, const char *mime_type, + int32_t fd); + void (*accept)(struct wlr_data_source *source, uint32_t serial, + const char *mime_type); + void (*destroy)(struct wlr_data_source *source); + + void (*dnd_drop)(struct wlr_data_source *source); + void (*dnd_finish)(struct wlr_data_source *source); + void (*dnd_action)(struct wlr_data_source *source, + enum wl_data_device_manager_dnd_action action); +}; + +struct wlr_data_source { + const struct wlr_data_source_impl *impl; + + // source metadata + struct wl_array mime_types; + int32_t actions; + + // source status + bool accepted; + + // drag'n'drop status + enum wl_data_device_manager_dnd_action current_dnd_action; + uint32_t compositor_action; + + struct { + struct wl_signal destroy; + struct wl_signal dnd_action; // struct wlr_data_source + } events; +}; + +struct wlr_drag; + +struct wlr_drag_icon { + struct wlr_drag *drag; + struct wlr_surface *surface; + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener surface_destroy; + } WLR_PRIVATE; +}; + +enum wlr_drag_grab_type { + WLR_DRAG_GRAB_KEYBOARD, + WLR_DRAG_GRAB_KEYBOARD_POINTER, + WLR_DRAG_GRAB_KEYBOARD_TOUCH, +}; + +struct wlr_drag { + enum wlr_drag_grab_type grab_type; + struct wlr_seat_keyboard_grab keyboard_grab; + struct wlr_seat_pointer_grab pointer_grab; + struct wlr_seat_touch_grab touch_grab; + + struct wlr_seat *seat; + struct wlr_seat_client *seat_client; + struct wlr_seat_client *focus_client; + + struct wlr_drag_icon *icon; // can be NULL + struct wlr_surface *focus; // can be NULL + struct wlr_data_source *source; // can be NULL + + bool started, dropped, cancelling; + int32_t grab_touch_id, touch_id; // if WLR_DRAG_GRAB_TOUCH + + struct { + struct wl_signal focus; + struct wl_signal motion; // struct wlr_drag_motion_event + struct wl_signal drop; // struct wlr_drag_drop_event + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener source_destroy; + struct wl_listener seat_client_destroy; + struct wl_listener focus_destroy; + struct wl_listener icon_destroy; + } WLR_PRIVATE; +}; + +struct wlr_drag_motion_event { + struct wlr_drag *drag; + uint32_t time; + double sx, sy; +}; + +struct wlr_drag_drop_event { + struct wlr_drag *drag; + uint32_t time; +}; + +/** + * Create a wl_data_device_manager global for this display. + */ +struct wlr_data_device_manager *wlr_data_device_manager_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_data_device_manager_destroy(struct wlr_data_device_manager *manager, + bool destroy_global_safe); + +/** + * Requests a selection to be set for the seat. If the request comes from + * a client, then set `client` to be the matching seat client so that this + * function can verify that the serial provided was once sent to the client + * on this seat. + */ +void wlr_seat_request_set_selection(struct wlr_seat *seat, + struct wlr_seat_client *client, struct wlr_data_source *source, + uint32_t serial); + +/** + * Sets the current selection for the seat. NULL can be provided to clear it. + * This removes the previous one if there was any. In case the selection doesn't + * come from a client, wl_display_next_serial() can be used to generate a + * serial. + */ +void wlr_seat_set_selection(struct wlr_seat *seat, + struct wlr_data_source *source, uint32_t serial); + +/** + * Creates a new drag. To request to start the drag, call + * wlr_seat_request_start_drag(). + */ +struct wlr_drag *wlr_drag_create(struct wlr_seat_client *seat_client, + struct wlr_data_source *source, struct wlr_surface *icon_surface); + +/** + * Requests a drag to be started on the seat. + */ +void wlr_seat_request_start_drag(struct wlr_seat *seat, struct wlr_drag *drag, + struct wlr_surface *origin, uint32_t serial); + +/** + * Starts a drag on the seat. This starts an implicit keyboard grab, but doesn't + * start a pointer or a touch grab. + */ +void wlr_seat_start_drag(struct wlr_seat *seat, struct wlr_drag *drag, + uint32_t serial); + +/** + * Starts a pointer drag on the seat. This starts implicit keyboard and pointer + * grabs. + */ +void wlr_seat_start_pointer_drag(struct wlr_seat *seat, struct wlr_drag *drag, + uint32_t serial); + +/** + * Starts a touch drag on the seat. This starts implicit keyboard and touch + * grabs. + */ +void wlr_seat_start_touch_drag(struct wlr_seat *seat, struct wlr_drag *drag, + uint32_t serial, struct wlr_touch_point *point); + +/** + * Initializes the data source with the provided implementation. + */ +void wlr_data_source_init(struct wlr_data_source *source, + const struct wlr_data_source_impl *impl); + +/** + * Sends the data as the specified MIME type over the passed file descriptor, + * then close it. + */ +void wlr_data_source_send(struct wlr_data_source *source, const char *mime_type, + int32_t fd); + +/** + * Notifies the data source that a target accepts one of the offered MIME types. + * If a target doesn't accept any of the offered types, `mime_type` is NULL. + */ +void wlr_data_source_accept(struct wlr_data_source *source, uint32_t serial, + const char *mime_type); + +/** + * Notifies the data source it is no longer valid and should be destroyed. That + * destroys immediately the data source. + */ +void wlr_data_source_destroy(struct wlr_data_source *source); + +/** + * Notifies the data source that the drop operation was performed. This does not + * indicate acceptance. + * + * The data source may still be used in the future and should not be destroyed + * here. + */ +void wlr_data_source_dnd_drop(struct wlr_data_source *source); + +/** + * Notifies the data source that the drag-and-drop operation concluded. That + * potentially destroys immediately the data source. + */ +void wlr_data_source_dnd_finish(struct wlr_data_source *source); + +/** + * Notifies the data source that a target accepts the drag with the specified + * action. + * + * This shouldn't be called after wlr_data_source_dnd_drop() unless the + * drag-and-drop operation ended in an "ask" action. + */ +void wlr_data_source_dnd_action(struct wlr_data_source *source, + enum wl_data_device_manager_dnd_action action); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_drm.h b/3rdparty/wlroots/include/wlr/types/wlr_drm.h new file mode 100644 index 0000000000..5227e355d0 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_drm.h @@ -0,0 +1,72 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_DRM_H +#define WLR_TYPES_WLR_DRM_H + +#include +#include +#include +#include + +struct wlr_renderer; + +struct wlr_drm_buffer { + struct wlr_buffer base; + + struct wl_resource *resource; // can be NULL if the client destroyed it + struct wlr_dmabuf_attributes dmabuf; + + struct { + struct wl_listener release; + } WLR_PRIVATE; +}; + +/** + * A stub implementation of Mesa's wl_drm protocol. + * + * It only implements the minimum necessary for modern clients to behave + * properly. In particular, flink handles are left unimplemented. + * + * Deprecated: this protocol is legacy and superseded by linux-dmabuf. The + * implementation will be dropped in a future wlroots version. + */ +struct wlr_drm { + struct wl_global *global; + + struct { + struct wl_signal destroy; + } events; + + struct { + char *node_name; + struct wlr_drm_format_set formats; + + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_drm_buffer *wlr_drm_buffer_try_from_resource( + struct wl_resource *resource); + +struct wlr_drm *wlr_drm_create(struct wl_display *display, + struct wlr_renderer *renderer); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_drm_destroy(struct wlr_drm *drm, bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_drm_lease_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_drm_lease_v1.h new file mode 100644 index 0000000000..cdb0b4a771 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_drm_lease_v1.h @@ -0,0 +1,166 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_DRM_LEASE_V1_H +#define WLR_TYPES_WLR_DRM_LEASE_V1_H + +#include +#include + +struct wlr_backend; +struct wlr_output; + +struct wlr_drm_lease_v1_manager { + struct wl_list devices; // wlr_drm_lease_device_v1.link + + struct wl_display *display; + + struct { + struct wl_signal destroy; + + /** + * Upon receiving this signal, call + * wlr_drm_lease_device_v1_grant_lease_request() to grant a lease of the + * requested DRM resources, or + * wlr_drm_lease_device_v1_reject_lease_request() to reject the request. + */ + struct wl_signal request; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_drm_lease_device_v1 { + struct wl_list resources; + struct wl_global *global; + + struct wlr_drm_lease_v1_manager *manager; + struct wlr_backend *backend; + + struct wl_list connectors; // wlr_drm_lease_connector_v1.link + struct wl_list leases; // wlr_drm_lease_v1.link + struct wl_list requests; // wlr_drm_lease_request_v1.link + struct wl_list link; // wlr_drm_lease_v1_manager.devices + + void *data; + + struct { + struct wl_listener backend_destroy; + } WLR_PRIVATE; +}; + +struct wlr_drm_lease_v1; + +struct wlr_drm_lease_connector_v1 { + struct wl_list resources; // wl_resource_get_link() + + struct wlr_output *output; + struct wlr_drm_lease_device_v1 *device; + + struct wl_list link; // wlr_drm_lease_device_v1.connectors + + struct { + struct wl_listener destroy; + } WLR_PRIVATE; +}; + +struct wlr_drm_lease_request_v1 { + struct wl_resource *resource; + + struct wlr_drm_lease_device_v1 *device; + + struct wlr_drm_lease_connector_v1 **connectors; + size_t n_connectors; + + struct wl_resource *lease_resource; + + bool invalid; + + struct wl_list link; // wlr_drm_lease_device_v1.requests +}; + +struct wlr_drm_lease_v1 { + struct wl_resource *resource; + struct wlr_drm_lease *drm_lease; + + struct wlr_drm_lease_device_v1 *device; + + struct wl_list link; // wlr_drm_lease_device_v1.leases + + void *data; + + struct { + struct wl_listener destroy; + } WLR_PRIVATE; +}; + +/** + * Creates a DRM lease manager. A DRM lease device will be created for each + * DRM backend supplied in case of a struct wlr_multi_backend. + * + * Returns NULL if no DRM backend is supplied. + */ +struct wlr_drm_lease_v1_manager *wlr_drm_lease_v1_manager_create( + struct wl_display *display, struct wlr_backend *backend); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_drm_lease_v1_manager_destroy(struct wlr_drm_lease_v1_manager *manager, + bool destroy_global_safe); + +/** + * Offers a wlr_output for lease. + * + * Returns false if the output can't be offered to lease. + */ +bool wlr_drm_lease_v1_manager_offer_output( + struct wlr_drm_lease_v1_manager *manager, struct wlr_output *output); + +/** + * Withdraws a previously offered output for lease. If the output is leased to + * a client, a finished event will be send and the lease will be terminated. + */ +void wlr_drm_lease_v1_manager_withdraw_output( + struct wlr_drm_lease_v1_manager *manager, struct wlr_output *output); + +/** + * Grants a client's lease request. The lease device will then provision the + * DRM lease and transfer the file descriptor to the client. After calling this, + * each struct wlr_output leased is destroyed, and will be re-issued through + * wlr_backend.events.new_outputs when the lease is revoked. + * + * This will return NULL without leasing any resources if the lease is invalid; + * this can happen for example if two clients request the same resources and an + * attempt to grant both leases is made. + */ +struct wlr_drm_lease_v1 *wlr_drm_lease_request_v1_grant( + struct wlr_drm_lease_request_v1 *request); + +/** + * Rejects a client's lease request. The output will still be available to + * lease until withdrawn by the compositor. + */ +void wlr_drm_lease_request_v1_reject(struct wlr_drm_lease_request_v1 *request); + +/** + * Revokes a client's lease request. The output will still be available to + * lease until withdrawn by the compositor. + */ +void wlr_drm_lease_v1_revoke(struct wlr_drm_lease_v1 *lease); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_export_dmabuf_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_export_dmabuf_v1.h new file mode 100644 index 0000000000..d85a11f7dd --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_export_dmabuf_v1.h @@ -0,0 +1,60 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_EXPORT_DMABUF_V1_H +#define WLR_TYPES_WLR_EXPORT_DMABUF_V1_H + +#include +#include +#include + +struct wlr_export_dmabuf_manager_v1 { + struct wl_global *global; + struct wl_list frames; // wlr_export_dmabuf_frame_v1.link + + struct { + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_export_dmabuf_frame_v1 { + struct wl_resource *resource; + struct wlr_export_dmabuf_manager_v1 *manager; + struct wl_list link; // wlr_export_dmabuf_manager_v1.frames + + struct wlr_output *output; + + bool cursor_locked; + + struct { + struct wl_listener output_commit; + struct wl_listener output_destroy; + } WLR_PRIVATE; +}; + +struct wlr_export_dmabuf_manager_v1 *wlr_export_dmabuf_manager_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_export_dmabuf_manager_v1_destroy(struct wlr_export_dmabuf_manager_v1 *manager, + bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_ext_data_control_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_ext_data_control_v1.h new file mode 100644 index 0000000000..ad03221dd2 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_ext_data_control_v1.h @@ -0,0 +1,65 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_EXT_DATA_CONTROL_V1_H +#define WLR_TYPES_WLR_EXT_DATA_CONTROL_V1_H + +#include +#include +#include + +struct wlr_ext_data_control_manager_v1 { + struct wl_global *global; + struct wl_list devices; // wlr_ext_data_control_device_v1.link + + struct { + struct wl_signal destroy; + struct wl_signal new_device; // wlr_ext_data_control_device_v1 + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_ext_data_control_device_v1 { + struct wl_resource *resource; + struct wlr_ext_data_control_manager_v1 *manager; + struct wl_list link; // wlr_ext_data_control_manager_v1.devices + + struct wlr_seat *seat; + struct wl_resource *selection_offer_resource; // current selection offer + struct wl_resource *primary_selection_offer_resource; // current primary selection offer + + struct { + struct wl_listener seat_destroy; + struct wl_listener seat_set_selection; + struct wl_listener seat_set_primary_selection; + } WLR_PRIVATE; +}; + +struct wlr_ext_data_control_manager_v1 *wlr_ext_data_control_manager_v1_create( + struct wl_display *display, uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_ext_data_control_manager_v1_destroy(struct wlr_ext_data_control_manager_v1 *manager, + bool destroy_global_safe); + +void wlr_ext_data_control_device_v1_destroy( + struct wlr_ext_data_control_device_v1 *device); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_ext_foreign_toplevel_list_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_ext_foreign_toplevel_list_v1.h new file mode 100644 index 0000000000..52b5abc73b --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_ext_foreign_toplevel_list_v1.h @@ -0,0 +1,86 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_FOREIGN_TOPLEVEL_LIST_V1_H +#define WLR_TYPES_WLR_FOREIGN_TOPLEVEL_LIST_V1_H + +#include +#include + +struct wlr_ext_foreign_toplevel_list_v1 { + struct wl_global *global; + struct wl_list resources; // wl_resource_get_link() + struct wl_list toplevels; // ext_foreign_toplevel_handle_v1.link + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_ext_foreign_toplevel_handle_v1 { + struct wlr_ext_foreign_toplevel_list_v1 *list; + struct wl_list resources; // wl_resource_get_link() + struct wl_list link; // wlr_ext_foreign_toplevel_list_v1.toplevels + + char *title; + char *app_id; + char *identifier; + + struct { + struct wl_signal destroy; + } events; + + void *data; +}; + +struct wlr_ext_foreign_toplevel_handle_v1_state { + const char *title; + const char *app_id; +}; + +struct wlr_ext_foreign_toplevel_list_v1 *wlr_ext_foreign_toplevel_list_v1_create( + struct wl_display *display, uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_ext_foreign_toplevel_list_v1_destroy(struct wlr_ext_foreign_toplevel_list_v1 *list, + bool destroy_global_safe); + +struct wlr_ext_foreign_toplevel_handle_v1 *wlr_ext_foreign_toplevel_handle_v1_create( + struct wlr_ext_foreign_toplevel_list_v1 *list, + const struct wlr_ext_foreign_toplevel_handle_v1_state *state); + +/** + * Destroy the given toplevel handle, sending the closed event to any + * client. + */ +void wlr_ext_foreign_toplevel_handle_v1_destroy( + struct wlr_ext_foreign_toplevel_handle_v1 *toplevel); + +void wlr_ext_foreign_toplevel_handle_v1_update_state( + struct wlr_ext_foreign_toplevel_handle_v1 *toplevel, + const struct wlr_ext_foreign_toplevel_handle_v1_state *state); + +struct wlr_ext_foreign_toplevel_handle_v1 *wlr_ext_foreign_toplevel_handle_v1_from_resource( + struct wl_resource *resource); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_ext_image_capture_source_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_ext_image_capture_source_v1.h new file mode 100644 index 0000000000..08bac25425 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_ext_image_capture_source_v1.h @@ -0,0 +1,169 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_EXT_IMAGE_CAPTURE_SOURCE_V1_H +#define WLR_TYPES_WLR_EXT_IMAGE_CAPTURE_SOURCE_V1_H + +#include +#include +#include +#include + +struct wlr_scene_node; +struct wlr_allocator; +struct wlr_renderer; + +/** + * A screen capture source. + * + * When the size, device or formats change, the constraints_update event is + * emitted. + * + * The device and formats advertised are suitable for copying into a + * struct wlr_buffer. + */ +struct wlr_ext_image_capture_source_v1 { + const struct wlr_ext_image_capture_source_v1_interface *impl; + struct wl_list resources; // wl_resource_get_link() + + uint32_t width, height; + + uint32_t *shm_formats; + size_t shm_formats_len; + + dev_t dmabuf_device; + struct wlr_drm_format_set dmabuf_formats; + + struct { + struct wl_signal constraints_update; + struct wl_signal frame; // struct wlr_ext_image_capture_source_v1_frame_event + struct wl_signal destroy; + } events; +}; + +/** + * Event indicating that the source has produced a new frame. + */ +struct wlr_ext_image_capture_source_v1_frame_event { + const pixman_region32_t *damage; +}; + +/** + * A cursor capture source. + * + * Provides additional cursor-specific functionality on top of + * struct wlr_ext_image_capture_source_v1. + */ +struct wlr_ext_image_capture_source_v1_cursor { + struct wlr_ext_image_capture_source_v1 base; + + bool entered; + int32_t x, y; + struct { + int32_t x, y; + } hotspot; + + struct { + struct wl_signal update; + } events; +}; + +/** + * Interface exposing one screen capture source per output. + */ +struct wlr_ext_output_image_capture_source_manager_v1 { + struct wl_global *global; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +/** + * Interface exposing one screen capture source per foreign toplevel. + */ +struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1 { + struct wl_global *global; + + struct { + struct wl_signal destroy; + struct wl_signal new_request; // struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request { + struct wlr_ext_foreign_toplevel_handle_v1 *toplevel_handle; + struct wl_client *client; + + struct { + uint32_t new_id; + } WLR_PRIVATE; +}; + +/** + * Obtain a struct wlr_ext_image_capture_source_v1 from an ext_image_capture_source_v1 + * resource. + * + * Asserts that the resource has the correct type. Returns NULL if the resource + * is inert. + */ +struct wlr_ext_image_capture_source_v1 *wlr_ext_image_capture_source_v1_from_resource(struct wl_resource *resource); + +struct wlr_ext_output_image_capture_source_manager_v1 *wlr_ext_output_image_capture_source_manager_v1_create( + struct wl_display *display, uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_ext_output_image_capture_source_manager_v1_destroy( + struct wlr_ext_output_image_capture_source_manager_v1 *manager, bool destroy_global_safe); + +struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1 * +wlr_ext_foreign_toplevel_image_capture_source_manager_v1_create(struct wl_display *display, uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_ext_foreign_toplevel_image_capture_source_manager_v1_destroy( + struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1 *manager, bool destroy_global_safe); + +bool wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request_accept( + struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request *request, + struct wlr_ext_image_capture_source_v1 *source); + +struct wlr_ext_image_capture_source_v1 *wlr_ext_image_capture_source_v1_create_with_scene_node( + struct wlr_scene_node *node, struct wl_event_loop *event_loop, + struct wlr_allocator *allocator, struct wlr_renderer *renderer); + +/** + * Returns the corresponding wlr_output for a image capture source + * managed by wlr_ext_output_image_capture_source_manager_v1 + * or NULL if the image capture source is not managed by + * wlr_ext_output_image_capture_source_manager_v1. + */ +struct wlr_output *wlr_output_try_from_ext_image_capture_source_v1(struct wlr_ext_image_capture_source_v1 *source); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_ext_image_copy_capture_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_ext_image_copy_capture_v1.h new file mode 100644 index 0000000000..7a65464f13 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_ext_image_copy_capture_v1.h @@ -0,0 +1,101 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_EXT_IMAGE_COPY_CAPTURE_V1_H +#define WLR_TYPES_WLR_EXT_IMAGE_COPY_CAPTURE_V1_H + +#include +#include +#include +#include +#include + +struct wlr_renderer; + +struct wlr_ext_image_copy_capture_manager_v1 { + struct wl_global *global; + + struct { + struct wl_signal new_session; // wlr_ext_image_copy_capture_session_v1 + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_ext_image_copy_capture_session_v1 { + struct wl_resource *resource; + struct wlr_ext_image_capture_source_v1 *source; + struct wlr_ext_image_copy_capture_frame_v1 *frame; + + struct { + struct wl_signal destroy; + } events; + + struct { + struct wl_listener source_destroy; + struct wl_listener source_constraints_update; + struct wl_listener source_frame; + + pixman_region32_t damage; + } WLR_PRIVATE; +}; + +struct wlr_ext_image_copy_capture_frame_v1 { + struct wl_resource *resource; + bool capturing; + struct wlr_buffer *buffer; + pixman_region32_t buffer_damage; + + struct { + struct wl_signal destroy; + } events; + + struct { + struct wlr_ext_image_copy_capture_session_v1 *session; + } WLR_PRIVATE; +}; + +struct wlr_ext_image_copy_capture_manager_v1 *wlr_ext_image_copy_capture_manager_v1_create( + struct wl_display *display, uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_ext_image_copy_capture_manager_v1_destroy( + struct wlr_ext_image_copy_capture_manager_v1 *manager, bool destroy_global_safe); + +/** + * Notify the client that the frame is ready. + * + * This function destroys the frame. + */ +void wlr_ext_image_copy_capture_frame_v1_ready(struct wlr_ext_image_copy_capture_frame_v1 *frame, + enum wl_output_transform transform, const struct timespec *presentation_time); +/** + * Notify the client that the frame has failed. + * + * This function destroys the frame. + */ +void wlr_ext_image_copy_capture_frame_v1_fail(struct wlr_ext_image_copy_capture_frame_v1 *frame, + enum ext_image_copy_capture_frame_v1_failure_reason reason); +/** + * Copy a struct wlr_buffer into the client-provided buffer for the frame. + */ +bool wlr_ext_image_copy_capture_frame_v1_copy_buffer(struct wlr_ext_image_copy_capture_frame_v1 *frame, + struct wlr_buffer *src, struct wlr_renderer *renderer); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_ext_workspace_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_ext_workspace_v1.h new file mode 100644 index 0000000000..a9f4ed78a9 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_ext_workspace_v1.h @@ -0,0 +1,158 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_EXT_WORKSPACE_V1_H +#define WLR_TYPES_WLR_EXT_WORKSPACE_V1_H + +#include +#include +#include + +struct wlr_output; + +enum wlr_ext_workspace_v1_request_type { + WLR_EXT_WORKSPACE_V1_REQUEST_CREATE_WORKSPACE, + WLR_EXT_WORKSPACE_V1_REQUEST_ACTIVATE, + WLR_EXT_WORKSPACE_V1_REQUEST_DEACTIVATE, + WLR_EXT_WORKSPACE_V1_REQUEST_ASSIGN, + WLR_EXT_WORKSPACE_V1_REQUEST_REMOVE, +}; + +struct wlr_ext_workspace_v1_request { + enum wlr_ext_workspace_v1_request_type type; + struct wl_list link; // wlr_ext_workspace_manager_v1_resource.requests + union { + struct { + char *name; + struct wlr_ext_workspace_group_handle_v1 *group; // NULL if destroyed + } create_workspace; + struct { + struct wlr_ext_workspace_handle_v1 *workspace; // NULL if destroyed + } activate; + struct { + struct wlr_ext_workspace_handle_v1 *workspace; // NULL if destroyed + } deactivate; + struct { + struct wlr_ext_workspace_handle_v1 *workspace; // NULL if destroyed + struct wlr_ext_workspace_group_handle_v1 *group; // NULL if destroyed + } assign; + struct { + struct wlr_ext_workspace_handle_v1 *workspace; // NULL if destroyed + } remove; + }; +}; + +struct wlr_ext_workspace_v1_commit_event { + struct wl_list *requests; // wlr_ext_workspace_v1_request.link +}; + +struct wlr_ext_workspace_manager_v1 { + struct wl_global *global; + struct wl_list groups; // wlr_ext_workspace_group_handle_v1.link + struct wl_list workspaces; // wlr_ext_workspace_handle_v1.link + + struct { + struct wl_signal commit; // wlr_ext_workspace_v1_commit_event + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_list resources; // wlr_ext_workspace_manager_v1_resource.link + struct wl_event_source *idle_source; + struct wl_event_loop *event_loop; + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_ext_workspace_group_handle_v1 { + struct wlr_ext_workspace_manager_v1 *manager; + uint32_t caps; // ext_workspace_group_handle_v1_group_capabilities + struct { + struct wl_signal destroy; + } events; + + struct wl_list link; // wlr_ext_workspace_manager_v1.groups + + void *data; + + struct { + struct wl_list outputs; // wlr_ext_workspace_v1_group_output.link + struct wl_list resources; // wlr_ext_workspace_manager_v1_resource.link + } WLR_PRIVATE; +}; + +struct wlr_ext_workspace_handle_v1 { + struct wlr_ext_workspace_manager_v1 *manager; + struct wlr_ext_workspace_group_handle_v1 *group; // May be NULL + char *id; + char *name; + struct wl_array coordinates; + uint32_t caps; // ext_workspace_handle_v1_workspace_capabilities + uint32_t state; // ext_workspace_handle_v1_state + + struct { + struct wl_signal destroy; + } events; + + struct wl_list link; // wlr_ext_workspace_manager_v1.workspaces + + void *data; + + struct { + struct wl_list resources; // wlr_ext_workspace_v1_resource.link + } WLR_PRIVATE; +}; + +struct wlr_ext_workspace_manager_v1 *wlr_ext_workspace_manager_v1_create( + struct wl_display *display, uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_ext_workspace_manager_v1_destroy(struct wlr_ext_workspace_manager_v1 *manager, + bool destroy_global_safe); + +struct wlr_ext_workspace_group_handle_v1 *wlr_ext_workspace_group_handle_v1_create( + struct wlr_ext_workspace_manager_v1 *manager, uint32_t caps); +void wlr_ext_workspace_group_handle_v1_destroy( + struct wlr_ext_workspace_group_handle_v1 *group); + +void wlr_ext_workspace_group_handle_v1_output_enter( + struct wlr_ext_workspace_group_handle_v1 *group, struct wlr_output *output); +void wlr_ext_workspace_group_handle_v1_output_leave( + struct wlr_ext_workspace_group_handle_v1 *group, struct wlr_output *output); + +struct wlr_ext_workspace_handle_v1 *wlr_ext_workspace_handle_v1_create( + struct wlr_ext_workspace_manager_v1 *manager, const char *id, uint32_t caps); +void wlr_ext_workspace_handle_v1_destroy(struct wlr_ext_workspace_handle_v1 *workspace); + +void wlr_ext_workspace_handle_v1_set_group( + struct wlr_ext_workspace_handle_v1 *workspace, + struct wlr_ext_workspace_group_handle_v1 *group); +void wlr_ext_workspace_handle_v1_set_name( + struct wlr_ext_workspace_handle_v1 *workspace, const char *name); +void wlr_ext_workspace_handle_v1_set_coordinates( + struct wlr_ext_workspace_handle_v1 *workspace, + const uint32_t *coords, size_t coords_len); +void wlr_ext_workspace_handle_v1_set_active( + struct wlr_ext_workspace_handle_v1 *workspace, bool enabled); +void wlr_ext_workspace_handle_v1_set_urgent( + struct wlr_ext_workspace_handle_v1 *workspace, bool enabled); +void wlr_ext_workspace_handle_v1_set_hidden( + struct wlr_ext_workspace_handle_v1 *workspace, bool enabled); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_fixes.h b/3rdparty/wlroots/include/wlr/types/wlr_fixes.h new file mode 100644 index 0000000000..3c97625166 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_fixes.h @@ -0,0 +1,41 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_FIXES_H +#define WLR_TYPES_WLR_FIXES_H + +#include +#include + +struct wlr_fixes { + struct wl_global *global; + + struct { + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_fixes *wlr_fixes_create(struct wl_display *display, uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_fixes_destroy(struct wlr_fixes *fixes, bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_foreign_toplevel_management_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_foreign_toplevel_management_v1.h new file mode 100644 index 0000000000..b472a9f4b5 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_foreign_toplevel_management_v1.h @@ -0,0 +1,169 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_FOREIGN_TOPLEVEL_MANAGEMENT_V1_H +#define WLR_TYPES_WLR_FOREIGN_TOPLEVEL_MANAGEMENT_V1_H + +#include +#include +#include + +struct wlr_foreign_toplevel_manager_v1 { + struct wl_event_loop *event_loop; + struct wl_global *global; + struct wl_list resources; // wl_resource_get_link() + struct wl_list toplevels; // wlr_foreign_toplevel_handle_v1.link + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +enum wlr_foreign_toplevel_handle_v1_state { + WLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MAXIMIZED = (1 << 0), + WLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MINIMIZED = (1 << 1), + WLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_ACTIVATED = (1 << 2), + WLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN = (1 << 3), +}; + +struct wlr_foreign_toplevel_handle_v1_output { + struct wl_list link; // wlr_foreign_toplevel_handle_v1.outputs + struct wlr_output *output; + struct wlr_foreign_toplevel_handle_v1 *toplevel; + + struct { + struct wl_listener output_bind; + struct wl_listener output_destroy; + } WLR_PRIVATE; +}; + +struct wlr_foreign_toplevel_handle_v1 { + struct wlr_foreign_toplevel_manager_v1 *manager; + struct wl_list resources; + struct wl_list link; + struct wl_event_source *idle_source; + + char *title; + char *app_id; + struct wlr_foreign_toplevel_handle_v1 *parent; + struct wl_list outputs; // wlr_foreign_toplevel_v1_output.link + uint32_t state; // enum wlr_foreign_toplevel_v1_state + + struct { + // struct wlr_foreign_toplevel_handle_v1_maximized_event + struct wl_signal request_maximize; + // struct wlr_foreign_toplevel_handle_v1_minimized_event + struct wl_signal request_minimize; + // struct wlr_foreign_toplevel_handle_v1_activated_event + struct wl_signal request_activate; + // struct wlr_foreign_toplevel_handle_v1_fullscreen_event + struct wl_signal request_fullscreen; + struct wl_signal request_close; + + // struct wlr_foreign_toplevel_handle_v1_set_rectangle_event + struct wl_signal set_rectangle; + struct wl_signal destroy; + } events; + + void *data; +}; + +struct wlr_foreign_toplevel_handle_v1_maximized_event { + struct wlr_foreign_toplevel_handle_v1 *toplevel; + bool maximized; +}; + +struct wlr_foreign_toplevel_handle_v1_minimized_event { + struct wlr_foreign_toplevel_handle_v1 *toplevel; + bool minimized; +}; + +struct wlr_foreign_toplevel_handle_v1_activated_event { + struct wlr_foreign_toplevel_handle_v1 *toplevel; + struct wlr_seat *seat; +}; + +struct wlr_foreign_toplevel_handle_v1_fullscreen_event { + struct wlr_foreign_toplevel_handle_v1 *toplevel; + bool fullscreen; + struct wlr_output *output; +}; + +struct wlr_foreign_toplevel_handle_v1_set_rectangle_event { + struct wlr_foreign_toplevel_handle_v1 *toplevel; + struct wlr_surface *surface; + int32_t x, y, width, height; +}; + +struct wlr_foreign_toplevel_manager_v1 *wlr_foreign_toplevel_manager_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_foreign_toplevel_manager_v1_destroy(struct wlr_foreign_toplevel_manager_v1 *manager, + bool destroy_global_safe); + +struct wlr_foreign_toplevel_handle_v1 *wlr_foreign_toplevel_handle_v1_create( + struct wlr_foreign_toplevel_manager_v1 *manager); +/** + * Destroy the given toplevel handle, sending the closed event to any + * client. Also, if the destroyed toplevel is set as a parent of any + * other valid toplevel, clients still holding a handle to both are + * sent a parent signal with NULL parent. If this is not desired, the + * caller should ensure that any child toplevels are destroyed before + * the parent. + */ +void wlr_foreign_toplevel_handle_v1_destroy( + struct wlr_foreign_toplevel_handle_v1 *toplevel); + +void wlr_foreign_toplevel_handle_v1_set_title( + struct wlr_foreign_toplevel_handle_v1 *toplevel, const char *title); +void wlr_foreign_toplevel_handle_v1_set_app_id( + struct wlr_foreign_toplevel_handle_v1 *toplevel, const char *app_id); + +void wlr_foreign_toplevel_handle_v1_output_enter( + struct wlr_foreign_toplevel_handle_v1 *toplevel, struct wlr_output *output); +void wlr_foreign_toplevel_handle_v1_output_leave( + struct wlr_foreign_toplevel_handle_v1 *toplevel, struct wlr_output *output); + +void wlr_foreign_toplevel_handle_v1_set_maximized( + struct wlr_foreign_toplevel_handle_v1 *toplevel, bool maximized); +void wlr_foreign_toplevel_handle_v1_set_minimized( + struct wlr_foreign_toplevel_handle_v1 *toplevel, bool minimized); +void wlr_foreign_toplevel_handle_v1_set_activated( + struct wlr_foreign_toplevel_handle_v1 *toplevel, bool activated); +void wlr_foreign_toplevel_handle_v1_set_fullscreen( + struct wlr_foreign_toplevel_handle_v1* toplevel, bool fullscreen); + +/** + * Set the parent of a toplevel. If the parent changed from its previous + * value, also sends a parent event to all clients that hold handles to + * both toplevel and parent (no message is sent to clients that have + * previously destroyed their parent handle). NULL is allowed as the + * parent, meaning no parent exists. + */ +void wlr_foreign_toplevel_handle_v1_set_parent( + struct wlr_foreign_toplevel_handle_v1 *toplevel, + struct wlr_foreign_toplevel_handle_v1 *parent); + + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_fractional_scale_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_fractional_scale_v1.h new file mode 100644 index 0000000000..a8774b6b12 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_fractional_scale_v1.h @@ -0,0 +1,48 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_FRACTIONAL_SCALE_V1_H +#define WLR_TYPES_WLR_FRACTIONAL_SCALE_V1_H + +#include +#include + +struct wlr_surface; + +struct wlr_fractional_scale_manager_v1 { + struct wl_global *global; + + struct { + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +void wlr_fractional_scale_v1_notify_scale( + struct wlr_surface *surface, double scale); + +struct wlr_fractional_scale_manager_v1 *wlr_fractional_scale_manager_v1_create( + struct wl_display *display, uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_fractional_scale_manager_v1_destroy(struct wlr_fractional_scale_manager_v1 *mgr, + bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_gamma_control_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_gamma_control_v1.h new file mode 100644 index 0000000000..3719800408 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_gamma_control_v1.h @@ -0,0 +1,75 @@ +#ifndef WLR_TYPES_WLR_GAMMA_CONTROL_V1_H +#define WLR_TYPES_WLR_GAMMA_CONTROL_V1_H + +#include +#include + +struct wlr_output; +struct wlr_output_state; + +struct wlr_gamma_control_manager_v1 { + struct wl_global *global; + struct wl_list controls; // wlr_gamma_control_v1.link + + // Fallback to use when an struct wlr_output doesn't support gamma LUTs. + // Can be used to apply gamma LUTs via a struct wlr_renderer. Leave zero to + // indicate that the fallback is unsupported. + size_t fallback_gamma_size; + + struct { + struct wl_signal destroy; + struct wl_signal set_gamma; // struct wlr_gamma_control_manager_v1_set_gamma_event + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_gamma_control_manager_v1_set_gamma_event { + struct wlr_output *output; + struct wlr_gamma_control_v1 *control; // may be NULL +}; + +struct wlr_gamma_control_v1 { + struct wl_resource *resource; + struct wlr_output *output; + struct wlr_gamma_control_manager_v1 *manager; + struct wl_list link; + + uint16_t *table; + size_t ramp_size; + + void *data; + + struct { + struct wl_listener output_destroy_listener; + } WLR_PRIVATE; +}; + +struct wlr_gamma_control_manager_v1 *wlr_gamma_control_manager_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_gamma_control_manager_v1_destroy(struct wlr_gamma_control_manager_v1 *manager, + bool destroy_global_safe); +struct wlr_gamma_control_v1 *wlr_gamma_control_manager_v1_get_control( + struct wlr_gamma_control_manager_v1 *manager, struct wlr_output *output); +bool wlr_gamma_control_v1_apply(struct wlr_gamma_control_v1 *gamma_control, + struct wlr_output_state *output_state); +struct wlr_color_transform *wlr_gamma_control_v1_get_color_transform( + struct wlr_gamma_control_v1 *gamma_control); +void wlr_gamma_control_v1_send_failed_and_destroy(struct wlr_gamma_control_v1 *gamma_control); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_idle_inhibit_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_idle_inhibit_v1.h new file mode 100644 index 0000000000..25be9d7a56 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_idle_inhibit_v1.h @@ -0,0 +1,75 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_IDLE_INHIBIT_V1_H +#define WLR_TYPES_WLR_IDLE_INHIBIT_V1_H + +#include +#include + +/* This interface permits clients to inhibit the idle behavior such as + * screenblanking, locking, and screensaving. + * + * This allows clients to ensure they stay visible instead of being hidden by + * power-saving. + * + * Inhibitors are created for surfaces. They should only be in effect, while + * this surface is visible. + * The effect could also be limited to outputs it is displayed on (e.g. + * dimm/dpms off outputs, except the one a video is displayed on). + */ + +struct wlr_idle_inhibit_manager_v1 { + struct wl_list inhibitors; // wlr_idle_inhibit_inhibitor_v1.link + struct wl_global *global; + + struct { + struct wl_signal new_inhibitor; // struct wlr_idle_inhibitor_v1 + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_idle_inhibitor_v1 { + struct wlr_surface *surface; + struct wl_resource *resource; + + struct wl_list link; // wlr_idle_inhibit_manager_v1.inhibitors + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener surface_destroy; + } WLR_PRIVATE; +}; + +struct wlr_idle_inhibit_manager_v1 *wlr_idle_inhibit_v1_create(struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_idle_inhibit_v1_destroy(struct wlr_idle_inhibit_manager_v1 *manager, + bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_idle_notify_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_idle_notify_v1.h new file mode 100644 index 0000000000..33c76b660c --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_idle_notify_v1.h @@ -0,0 +1,67 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_IDLE_NOTIFY_H +#define WLR_TYPES_WLR_IDLE_NOTIFY_H + +#include +#include + +struct wlr_seat; + +/** + * An idle notifier, implementing the ext-idle-notify-v1 protocol. + */ +struct wlr_idle_notifier_v1 { + struct wl_global *global; + + struct { + bool inhibited; + struct wl_list notifications; // wlr_idle_notification_v1.link + + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + + +/** + * Create the ext_idle_notifier_v1 global. + */ +struct wlr_idle_notifier_v1 *wlr_idle_notifier_v1_create(struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_idle_notifier_v1_destroy(struct wlr_idle_notifier_v1 *notifier, bool destroy_global_safe); + +/** + * Inhibit idle. + * + * Compositors should call this function when the idle state is disabled, e.g. + * because a visible client is using the idle-inhibit protocol. + */ +void wlr_idle_notifier_v1_set_inhibited(struct wlr_idle_notifier_v1 *notifier, + bool inhibited); + +/** + * Notify for user activity on a seat. + * + * Compositors should call this function whenever an input event is triggered + * on a seat. + */ +void wlr_idle_notifier_v1_notify_activity(struct wlr_idle_notifier_v1 *notifier, + struct wlr_seat *seat); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_input_device.h b/3rdparty/wlroots/include/wlr/types/wlr_input_device.h new file mode 100644 index 0000000000..7f78cf2b27 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_input_device.h @@ -0,0 +1,51 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_INPUT_DEVICE_H +#define WLR_TYPES_WLR_INPUT_DEVICE_H + +#include + +enum wlr_button_state { + WLR_BUTTON_RELEASED, + WLR_BUTTON_PRESSED, +}; + +/** + * Type of an input device. + */ +enum wlr_input_device_type { + WLR_INPUT_DEVICE_KEYBOARD, // struct wlr_keyboard + WLR_INPUT_DEVICE_POINTER, // struct wlr_pointer + WLR_INPUT_DEVICE_TOUCH, // struct wlr_touch + WLR_INPUT_DEVICE_TABLET, // struct wlr_tablet + WLR_INPUT_DEVICE_TABLET_PAD, // struct wlr_tablet_pad + WLR_INPUT_DEVICE_SWITCH, // struct wlr_switch +}; + +/** + * An input device. + * + * Depending on its type, the input device can be converted to a more specific + * type. See the various wlr_*_from_input_device() functions. + * + * Input devices are typically advertised by the new_input event in + * struct wlr_backend. + */ +struct wlr_input_device { + enum wlr_input_device_type type; + char *name; // may be NULL + + struct { + struct wl_signal destroy; + } events; + + void *data; +}; + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_input_method_v2.h b/3rdparty/wlroots/include/wlr/types/wlr_input_method_v2.h new file mode 100644 index 0000000000..6e43067f8b --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_input_method_v2.h @@ -0,0 +1,163 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_INPUT_METHOD_V2_H +#define WLR_TYPES_WLR_INPUT_METHOD_V2_H +#include +#include +#include +#include +#include + +struct wlr_input_method_v2_preedit_string { + char *text; + int32_t cursor_begin; + int32_t cursor_end; +}; + +struct wlr_input_method_v2_delete_surrounding_text { + uint32_t before_length; + uint32_t after_length; +}; + +struct wlr_input_method_v2_state { + struct wlr_input_method_v2_preedit_string preedit; + char *commit_text; + struct wlr_input_method_v2_delete_surrounding_text delete; +}; + +struct wlr_input_method_v2 { + struct wl_resource *resource; + + struct wlr_seat *seat; + struct wlr_seat_client *seat_client; + + struct wlr_input_method_v2_state pending; + struct wlr_input_method_v2_state current; + bool active; // pending compositor-side state + bool client_active; // state known to the client + uint32_t current_serial; // received in last commit call + + struct wl_list popup_surfaces; + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab; + + struct wl_list link; + + struct { + struct wl_signal commit; + struct wl_signal new_popup_surface; // struct wlr_input_popup_surface_v2 + struct wl_signal grab_keyboard; // struct wlr_input_method_keyboard_grab_v2 + struct wl_signal destroy; + } events; + + struct { + struct wl_listener seat_client_destroy; + } WLR_PRIVATE; +}; + +struct wlr_input_popup_surface_v2 { + struct wl_resource *resource; + struct wlr_input_method_v2 *input_method; + struct wl_list link; + + struct wlr_surface *surface; + + struct { + struct wl_signal destroy; + } events; + + void *data; +}; + +struct wlr_input_method_keyboard_grab_v2 { + struct wl_resource *resource; + struct wlr_input_method_v2 *input_method; + struct wlr_keyboard *keyboard; + + struct { + struct wl_signal destroy; // struct wlr_input_method_keyboard_grab_v2 + } events; + + struct { + struct wl_listener keyboard_keymap; + struct wl_listener keyboard_repeat_info; + struct wl_listener keyboard_destroy; + } WLR_PRIVATE; +}; + +struct wlr_input_method_manager_v2 { + struct wl_global *global; + struct wl_list input_methods; // struct wlr_input_method_v2.link + + struct { + struct wl_signal new_input_method; // struct wlr_input_method_v2 + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_input_method_manager_v2 *wlr_input_method_manager_v2_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_input_method_manager_v2_destroy(struct wlr_input_method_manager_v2 *manager, + bool destroy_global_safe); + +void wlr_input_method_v2_send_activate( + struct wlr_input_method_v2 *input_method); +void wlr_input_method_v2_send_deactivate( + struct wlr_input_method_v2 *input_method); +void wlr_input_method_v2_send_surrounding_text( + struct wlr_input_method_v2 *input_method, const char *text, + uint32_t cursor, uint32_t anchor); +void wlr_input_method_v2_send_content_type( + struct wlr_input_method_v2 *input_method, uint32_t hint, + uint32_t purpose); +void wlr_input_method_v2_send_text_change_cause( + struct wlr_input_method_v2 *input_method, uint32_t cause); +void wlr_input_method_v2_send_done(struct wlr_input_method_v2 *input_method); +void wlr_input_method_v2_send_unavailable( + struct wlr_input_method_v2 *input_method); + +/** + * Get a struct wlr_input_popup_surface_v2 from a struct wlr_surface. + * + * Returns NULL if the surface has a different role or if the input popup + * surface has been destroyed. + */ +struct wlr_input_popup_surface_v2 *wlr_input_popup_surface_v2_try_from_wlr_surface( + struct wlr_surface *surface); + +void wlr_input_popup_surface_v2_send_text_input_rectangle( + struct wlr_input_popup_surface_v2 *popup_surface, struct wlr_box *sbox); + +void wlr_input_method_keyboard_grab_v2_send_key( + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab, + uint32_t time, uint32_t key, uint32_t state); +void wlr_input_method_keyboard_grab_v2_send_modifiers( + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab, + struct wlr_keyboard_modifiers *modifiers); +void wlr_input_method_keyboard_grab_v2_set_keyboard( + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab, + struct wlr_keyboard *keyboard); +void wlr_input_method_keyboard_grab_v2_destroy( + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_keyboard.h b/3rdparty/wlroots/include/wlr/types/wlr_keyboard.h new file mode 100644 index 0000000000..20a310fdea --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_keyboard.h @@ -0,0 +1,161 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_KEYBOARD_H +#define WLR_TYPES_WLR_KEYBOARD_H + +#include +#include +#include +#include +#include +#include + +#define WLR_LED_COUNT 5 + +enum wlr_keyboard_led { + WLR_LED_NUM_LOCK = 1 << 0, + WLR_LED_CAPS_LOCK = 1 << 1, + WLR_LED_SCROLL_LOCK = 1 << 2, + WLR_LED_COMPOSE = 1 << 3, + WLR_LED_KANA = 1 << 4, +}; + +#define WLR_MODIFIER_COUNT 8 + +enum wlr_keyboard_modifier { + WLR_MODIFIER_SHIFT = 1 << 0, + WLR_MODIFIER_CAPS = 1 << 1, + WLR_MODIFIER_CTRL = 1 << 2, + WLR_MODIFIER_ALT = 1 << 3, + WLR_MODIFIER_MOD2 = 1 << 4, + WLR_MODIFIER_MOD3 = 1 << 5, + WLR_MODIFIER_LOGO = 1 << 6, + WLR_MODIFIER_MOD5 = 1 << 7, +}; + +#define WLR_KEYBOARD_KEYS_CAP 32 + +struct wlr_keyboard_impl; + +struct wlr_keyboard_modifiers { + xkb_mod_mask_t depressed; + xkb_mod_mask_t latched; + xkb_mod_mask_t locked; + xkb_layout_index_t group; +}; + +struct wlr_keyboard { + struct wlr_input_device base; + + const struct wlr_keyboard_impl *impl; + struct wlr_keyboard_group *group; + + char *keymap_string; + size_t keymap_size; + int keymap_fd; + struct xkb_keymap *keymap; + struct xkb_state *xkb_state; + xkb_led_index_t led_indexes[WLR_LED_COUNT]; + xkb_mod_index_t mod_indexes[WLR_MODIFIER_COUNT]; + + uint32_t leds; + uint32_t keycodes[WLR_KEYBOARD_KEYS_CAP]; + size_t num_keycodes; + struct wlr_keyboard_modifiers modifiers; + + struct { + int32_t rate; + int32_t delay; + } repeat_info; + + struct { + /** + * The `key` event signals with a struct wlr_keyboard_key_event that a + * key has been pressed or released on the keyboard. This event is + * emitted before the xkb state of the keyboard has been updated + * (including modifiers). + */ + struct wl_signal key; + + /** + * The `modifiers` event signals that the modifier state of the + * struct wlr_keyboard has been updated. At this time, you can read the + * modifier state of the struct wlr_keyboard and handle the updated + * state by sending it to clients. + */ + struct wl_signal modifiers; + struct wl_signal keymap; + struct wl_signal repeat_info; + } events; + + void *data; +}; + +struct wlr_keyboard_key_event { + uint32_t time_msec; + uint32_t keycode; + bool update_state; // if backend doesn't update modifiers on its own + enum wl_keyboard_key_state state; +}; + +/** + * Get a struct wlr_keyboard from a struct wlr_input_device. + * + * Asserts that the input device is a keyboard. + */ +struct wlr_keyboard *wlr_keyboard_from_input_device( + struct wlr_input_device *input_device); + +bool wlr_keyboard_set_keymap(struct wlr_keyboard *kb, + struct xkb_keymap *keymap); + +bool wlr_keyboard_keymaps_match(struct xkb_keymap *km1, struct xkb_keymap *km2); + +/** + * Interpret pointer button key symbols. + * + * Returns a button code (BTN_*) if the key symbol is a pointer button + * (XKB_KEY_Pointer_Button*), 0 otherwise. + */ +uint32_t wlr_keyboard_keysym_to_pointer_button(xkb_keysym_t keysym); + +/** + * Interpret pointer motion key symbols. + * + * Sets dx and dy to horizontal and vertical motion deltas (0, 1 or -1) if the + * key symbol is a pointer motion (XKB_KEY_Pointer_*). Otherwise, sets both dx + * and dy to 0. + */ +void wlr_keyboard_keysym_to_pointer_motion(xkb_keysym_t keysym, int *dx, int *dy); + +/** + * Set the keyboard repeat info. + * + * rate is in key repeats/second and delay is in milliseconds. + */ +void wlr_keyboard_set_repeat_info(struct wlr_keyboard *kb, int32_t rate_hz, + int32_t delay_ms); + +/** + * Update the LEDs on the device, if any. + * + * leds is a bitmask of enum wlr_keyboard_led. + * + * If the device doesn't have the provided LEDs, this function is a no-op. + */ +void wlr_keyboard_led_update(struct wlr_keyboard *keyboard, uint32_t leds); + +/** + * Get the set of currently depressed or latched modifiers. + * + * A bitmask of enum wlr_keyboard_modifier is returned. + */ +uint32_t wlr_keyboard_get_modifiers(struct wlr_keyboard *keyboard); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_keyboard_group.h b/3rdparty/wlroots/include/wlr/types/wlr_keyboard_group.h new file mode 100644 index 0000000000..0d5c6a2a4f --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_keyboard_group.h @@ -0,0 +1,59 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_KEYBOARD_GROUP_H +#define WLR_TYPES_WLR_KEYBOARD_GROUP_H + +#include +#include + +struct wlr_keyboard_group { + struct wlr_keyboard keyboard; + struct wl_list devices; // keyboard_group_device.link + struct wl_list keys; // keyboard_group_key.link + + struct { + /** + * Sent when a keyboard has entered the group with keys currently + * pressed that are not pressed by any other keyboard in the group. The + * data for this signal will be a struct wl_array containing the key + * codes. This should be used to update the compositor's internal state. + * Bindings should not be triggered based off of these key codes and + * they should also not notify any surfaces of the key press. + */ + struct wl_signal enter; + + /** + * Sent when a keyboard has left the group with keys currently pressed + * that are not pressed by any other keyboard in the group. The data for + * this signal will be a struct wl_array containing the key codes. This + * should be used to update the compositor's internal state. Bindings + * should not be triggered based off of these key codes. Additionally, + * surfaces should only be notified if they received a corresponding key + * press for the key code. + */ + struct wl_signal leave; + } events; + + void *data; +}; + +struct wlr_keyboard_group *wlr_keyboard_group_create(void); + +struct wlr_keyboard_group *wlr_keyboard_group_from_wlr_keyboard( + struct wlr_keyboard *keyboard); + +bool wlr_keyboard_group_add_keyboard(struct wlr_keyboard_group *group, + struct wlr_keyboard *keyboard); + +void wlr_keyboard_group_remove_keyboard(struct wlr_keyboard_group *group, + struct wlr_keyboard *keyboard); + +void wlr_keyboard_group_destroy(struct wlr_keyboard_group *group); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_keyboard_shortcuts_inhibit_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_keyboard_shortcuts_inhibit_v1.h new file mode 100644 index 0000000000..86876d989f --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_keyboard_shortcuts_inhibit_v1.h @@ -0,0 +1,103 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_KEYBOARD_SHORTCUTS_INHIBIT_V1_H +#define WLR_TYPES_WLR_KEYBOARD_SHORTCUTS_INHIBIT_V1_H + +#include +#include +#include + +/* This interface permits clients to inhibit keyboard shortcut processing by + * the compositor. + * + * This allows clients to pass them on to e.g. remote desktops or virtual + * machine guests. + * + * Inhibitors are created for surfaces and seats. They should only be in effect + * while this surface has focus. + */ + +struct wlr_keyboard_shortcuts_inhibit_manager_v1 { + // wlr_keyboard_shortcuts_inhibitor_v1.link + struct wl_list inhibitors; + struct wl_global *global; + + struct { + struct wl_signal new_inhibitor; // struct wlr_keyboard_shortcuts_inhibitor_v1 + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_keyboard_shortcuts_inhibitor_v1 { + struct wlr_surface *surface; + struct wlr_seat *seat; + bool active; + struct wl_resource *resource; + + // wlr_keyboard_shortcuts_inhibit_manager_v1.inhibitors + struct wl_list link; + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener surface_destroy; + struct wl_listener seat_destroy; + } WLR_PRIVATE; +}; + +/* + * A compositor creating a manager will handle the new_inhibitor event and call + * wlr_keyboard_shortcuts_inhibitor_v1_activate() if it decides to honour the + * inhibitor. This will send the active event to the client, confirming + * activation of the inhibitor. From then on the compositor should respect the + * inhibitor until it calls wlr_keyboard_shortcuts_inhibitor_v1_deactivate() to + * suspend the inhibitor with an inactive event to the client or receives the + * destroy signal from wlroots, telling it that the inhibitor has been + * destroyed. + * + * Not sending the active event to the client is the only way under the + * protocol to let the client know that the compositor will not be honouring an + * inhibitor. It's the client's job to somehow deal with not receiving the + * event, i.e. not assume that shortcuts are inhibited and maybe destroy the + * pending and request a new inhibitor after a timeout. + */ + +struct wlr_keyboard_shortcuts_inhibit_manager_v1 * +wlr_keyboard_shortcuts_inhibit_v1_create(struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_keyboard_shortcuts_inhibit_v1_destroy( + struct wlr_keyboard_shortcuts_inhibit_manager_v1 *manager, bool destroy_global_safe); + +void wlr_keyboard_shortcuts_inhibitor_v1_activate( + struct wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor); + +void wlr_keyboard_shortcuts_inhibitor_v1_deactivate( + struct wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_layer_shell_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_layer_shell_v1.h new file mode 100644 index 0000000000..6a6760ba95 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_layer_shell_v1.h @@ -0,0 +1,212 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_LAYER_SHELL_V1_H +#define WLR_TYPES_WLR_LAYER_SHELL_V1_H + +#include +#include +#include +#include +#include +#include "wlr-layer-shell-unstable-v1-protocol.h" + +/** + * wlr_layer_shell_v1 allows clients to arrange themselves in "layers" on the + * desktop in accordance with the wlr-layer-shell protocol. When a client is + * added, the new_surface signal will be raised and passed a reference to our + * struct wlr_layer_surface_v1. At this time, the client will have configured the + * surface as it desires, including information like desired anchors and + * margins. The compositor should use this information to decide how to arrange + * the layer on-screen, then determine the dimensions of the layer and call + * wlr_layer_surface_v1_configure(). The client will then attach a buffer and + * commit the surface, at which point the wlr_layer_surface_v1 map signal is + * raised and the compositor should begin rendering the surface. + */ +struct wlr_layer_shell_v1 { + struct wl_global *global; + + struct { + // Note: the output may be NULL. In this case, it is your + // responsibility to assign an output before returning. + struct wl_signal new_surface; // struct wlr_layer_surface_v1 + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +enum wlr_layer_surface_v1_state_field { + WLR_LAYER_SURFACE_V1_STATE_DESIRED_SIZE = 1 << 0, + WLR_LAYER_SURFACE_V1_STATE_ANCHOR = 1 << 1, + WLR_LAYER_SURFACE_V1_STATE_EXCLUSIVE_ZONE = 1 << 2, + WLR_LAYER_SURFACE_V1_STATE_MARGIN = 1 << 3, + WLR_LAYER_SURFACE_V1_STATE_KEYBOARD_INTERACTIVITY = 1 << 4, + WLR_LAYER_SURFACE_V1_STATE_LAYER = 1 << 5, + WLR_LAYER_SURFACE_V1_STATE_EXCLUSIVE_EDGE = 1 << 6, +}; + +struct wlr_layer_surface_v1_state { + uint32_t committed; // enum wlr_layer_surface_v1_state_field + + uint32_t anchor; + int32_t exclusive_zone; + struct { + int32_t top, right, bottom, left; + } margin; + enum zwlr_layer_surface_v1_keyboard_interactivity keyboard_interactive; + uint32_t desired_width, desired_height; + enum zwlr_layer_shell_v1_layer layer; + uint32_t exclusive_edge; + + uint32_t configure_serial; + uint32_t actual_width, actual_height; +}; + +struct wlr_layer_surface_v1_configure { + struct wl_list link; // wlr_layer_surface_v1.configure_list + uint32_t serial; + + uint32_t width, height; +}; + +struct wlr_layer_surface_v1 { + struct wlr_surface *surface; + struct wlr_output *output; + struct wl_resource *resource; + struct wlr_layer_shell_v1 *shell; + struct wl_list popups; // wlr_xdg_popup.link + + char *namespace; + + bool configured; + struct wl_list configure_list; + + struct wlr_layer_surface_v1_state current, pending; + + // Whether the surface is ready to receive configure events + bool initialized; + // Whether the latest commit is an initial commit + bool initial_commit; + + struct { + /** + * The destroy signal indicates that the struct wlr_layer_surface is + * about to be freed. It is guaranteed that the unmap signal is raised + * before the destroy signal if the layer surface is destroyed while + * mapped. + */ + struct wl_signal destroy; + /** + * The new_popup signal is raised when a new popup is created. The data + * parameter passed to the listener is a pointer to the new + * struct wlr_xdg_popup. + */ + struct wl_signal new_popup; + } events; + + void *data; + + struct { + struct wlr_surface_synced synced; + } WLR_PRIVATE; +}; + +struct wlr_layer_shell_v1 *wlr_layer_shell_v1_create(struct wl_display *display, + uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_layer_shell_v1_destroy(struct wlr_layer_shell_v1 *layer_shell, bool destroy_global_safe); + +/** + * Notifies the layer surface to configure itself with this width/height. The + * layer_surface will signal its map event when the surface is ready to assume + * this size. Returns the associated configure serial. + */ +uint32_t wlr_layer_surface_v1_configure(struct wlr_layer_surface_v1 *surface, + uint32_t width, uint32_t height); + +/** + * Notify the client that the surface has been closed and destroy the + * struct wlr_layer_surface_v1, rendering the resource inert. + */ +void wlr_layer_surface_v1_destroy(struct wlr_layer_surface_v1 *surface); + +/** + * Get a struct wlr_layer_surface from a struct wlr_surface. + * + * Returns NULL if the surface doesn't have the layer surface role or if + * the layer surface has been destroyed. + */ +struct wlr_layer_surface_v1 *wlr_layer_surface_v1_try_from_wlr_surface( + struct wlr_surface *surface); + +/** + * Calls the iterator function for each mapped sub-surface and popup of this + * surface (whether or not this surface is mapped). + */ +void wlr_layer_surface_v1_for_each_surface(struct wlr_layer_surface_v1 *surface, + wlr_surface_iterator_func_t iterator, void *user_data); + +/** + * Call `iterator` on each popup's surface and popup's subsurface in the + * layer surface's tree, with the surfaces's position relative to the root + * layer surface. The function is called from root to leaves (in rendering + * order). + */ +void wlr_layer_surface_v1_for_each_popup_surface( + struct wlr_layer_surface_v1 *surface, + wlr_surface_iterator_func_t iterator, void *user_data); + +/** + * Find a surface within this layer-surface tree at the given surface-local + * coordinates. Returns the surface and coordinates in the leaf surface + * coordinate system or NULL if no surface is found at that location. + */ +struct wlr_surface *wlr_layer_surface_v1_surface_at( + struct wlr_layer_surface_v1 *surface, double sx, double sy, + double *sub_x, double *sub_y); + +/** + * Find a surface within this layer-surface's popup tree at the given + * surface-local coordinates. Returns the surface and coordinates in the leaf + * surface coordinate system or NULL if no surface is found at that location. + */ +struct wlr_surface *wlr_layer_surface_v1_popup_surface_at( + struct wlr_layer_surface_v1 *surface, double sx, double sy, + double *sub_x, double *sub_y); + +/** + * Get the corresponding struct wlr_layer_surface_v1 from a resource. + * + * Aborts if the resource doesn't have the correct type. + */ +struct wlr_layer_surface_v1 *wlr_layer_surface_v1_from_resource( + struct wl_resource *resource); + +/** + * Get the edge the exclusive zone must be applied to. + * + * Returns WLR_EDGE_NONE if the exclusive zone is nonpositive or must not be applied. + */ +enum wlr_edges wlr_layer_surface_v1_get_exclusive_edge(struct wlr_layer_surface_v1 *surface); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_linux_dmabuf_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_linux_dmabuf_v1.h new file mode 100644 index 0000000000..2938e8f5ae --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_linux_dmabuf_v1.h @@ -0,0 +1,151 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_LINUX_DMABUF_V1_H +#define WLR_TYPES_WLR_LINUX_DMABUF_V1_H + +#include +#include +#include +#include +#include +#include +#include + +struct wlr_surface; + +struct wlr_dmabuf_v1_buffer { + struct wlr_buffer base; + + struct wl_resource *resource; // can be NULL if the client destroyed it + struct wlr_dmabuf_attributes attributes; + + struct { + struct wl_listener release; + } WLR_PRIVATE; +}; + +/** + * Returns the struct wlr_dmabuf_buffer if the given resource was created + * via the linux-dmabuf buffer protocol or NULL otherwise. + */ +struct wlr_dmabuf_v1_buffer *wlr_dmabuf_v1_buffer_try_from_buffer_resource( + struct wl_resource *buffer_resource); + +struct wlr_linux_dmabuf_feedback_v1 { + dev_t main_device; + struct wl_array tranches; // struct wlr_linux_dmabuf_feedback_v1_tranche +}; + +struct wlr_linux_dmabuf_feedback_v1_tranche { + dev_t target_device; + uint32_t flags; // bitfield of enum zwp_linux_dmabuf_feedback_v1_tranche_flags + struct wlr_drm_format_set formats; +}; + +/* the protocol interface */ +struct wlr_linux_dmabuf_v1 { + struct wl_global *global; + + struct { + struct wl_signal destroy; + } events; + + struct { + struct wlr_linux_dmabuf_feedback_v1_compiled *default_feedback; + struct wlr_drm_format_set default_formats; // for legacy clients + struct wl_list surfaces; // wlr_linux_dmabuf_v1_surface.link + + int main_device_fd; // to sanity check FDs sent by clients, -1 if unavailable + + struct wl_listener display_destroy; + + bool (*check_dmabuf_callback)(struct wlr_dmabuf_attributes *attribs, void *data); + void *check_dmabuf_callback_data; + } WLR_PRIVATE; +}; + +/** + * Create the linux-dmabuf-v1 global. + * + * Compositors using struct wlr_renderer should use + * wlr_linux_dmabuf_v1_create_with_renderer() instead. + */ +struct wlr_linux_dmabuf_v1 *wlr_linux_dmabuf_v1_create(struct wl_display *display, + uint32_t version, const struct wlr_linux_dmabuf_feedback_v1 *default_feedback); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_linux_dmabuf_v1_destroy(struct wlr_linux_dmabuf_v1 *linux_dmabuf, + bool destroy_global_safe); + +/** + * Create the linux-dmabuf-v1 global. + * + * The default DMA-BUF feedback is initialized from the struct wlr_renderer. + */ +struct wlr_linux_dmabuf_v1 *wlr_linux_dmabuf_v1_create_with_renderer(struct wl_display *display, + uint32_t version, struct wlr_renderer *renderer); + +/** + * Set the dmabuf import check callback + * + * This can be used by consumers who want to implement specific dmabuf checks. Useful for + * users such as gamescope who do not use the rendering logic of wlroots. + */ +void wlr_linux_dmabuf_v1_set_check_dmabuf_callback(struct wlr_linux_dmabuf_v1 *linux_dmabuf, + bool (*callback)(struct wlr_dmabuf_attributes *attribs, void *data), void *data); + +/** + * Set a surface's DMA-BUF feedback. + * + * Passing a NULL feedback resets it to the default feedback. + */ +bool wlr_linux_dmabuf_v1_set_surface_feedback( + struct wlr_linux_dmabuf_v1 *linux_dmabuf, struct wlr_surface *surface, + const struct wlr_linux_dmabuf_feedback_v1 *feedback); + +/** + * Append a tranche at the end of the DMA-BUF feedback list. + * + * Tranches must be added with decreasing priority. + */ +struct wlr_linux_dmabuf_feedback_v1_tranche *wlr_linux_dmabuf_feedback_add_tranche( + struct wlr_linux_dmabuf_feedback_v1 *feedback); + +/** + * Release resources allocated by a DMA-BUF feedback object. + */ +void wlr_linux_dmabuf_feedback_v1_finish(struct wlr_linux_dmabuf_feedback_v1 *feedback); + +struct wlr_linux_dmabuf_feedback_v1_init_options { + // Main renderer used by the compositor + struct wlr_renderer *main_renderer; + // Output on which direct scan-out is possible on the primary plane, or NULL + struct wlr_output *scanout_primary_output; + // Output layer feedback event, or NULL + const struct wlr_output_layer_feedback_event *output_layer_feedback_event; +}; + +/** + * Initialize a DMA-BUF feedback object with the provided options. + * + * The caller is responsible for calling wlr_linux_dmabuf_feedback_v1_finish() after use. + */ +bool wlr_linux_dmabuf_feedback_v1_init_with_options(struct wlr_linux_dmabuf_feedback_v1 *feedback, + const struct wlr_linux_dmabuf_feedback_v1_init_options *options); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_linux_drm_syncobj_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_linux_drm_syncobj_v1.h new file mode 100644 index 0000000000..b5d9d3c5fe --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_linux_drm_syncobj_v1.h @@ -0,0 +1,91 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_LINUX_DRM_SYNCOBJ_V1_H +#define WLR_TYPES_WLR_LINUX_DRM_SYNCOBJ_V1_H + +#include +#include +#include + +struct wlr_buffer; +struct wlr_surface; + +struct wlr_linux_drm_syncobj_surface_v1_state { + struct wlr_drm_syncobj_timeline *acquire_timeline; + uint64_t acquire_point; + + struct { + bool committed; + struct wlr_drm_syncobj_timeline *release_timeline; + uint64_t release_point; + struct wlr_drm_syncobj_merger *release_merger; + } WLR_PRIVATE; +}; + +struct wlr_linux_drm_syncobj_manager_v1 { + struct wl_global *global; + + struct { + int drm_fd; + + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +/** + * Advertise explicit synchronization support to clients. + * + * The compositor must be prepared to handle fences coming from clients and to + * send release fences correctly. In particular, both the renderer and the + * backend need to support explicit synchronization. + */ +struct wlr_linux_drm_syncobj_manager_v1 *wlr_linux_drm_syncobj_manager_v1_create( + struct wl_display *display, uint32_t version, int drm_fd); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_linux_drm_syncobj_manager_v1_destroy(struct wlr_linux_drm_syncobj_manager_v1 *manager, + bool destroy_global_safe); + +struct wlr_linux_drm_syncobj_surface_v1_state *wlr_linux_drm_syncobj_v1_get_surface_state( + struct wlr_surface *surface); + +/** + * Signal the release point when wlr_buffer.events.release is emitted. + * + * Compositors unwilling to track fine-grained commit release can call this + * helper on surface commit. + */ +bool wlr_linux_drm_syncobj_v1_state_signal_release_with_buffer( + struct wlr_linux_drm_syncobj_surface_v1_state *state, struct wlr_buffer *buffer); + +/** + * Register a release point for buffer usage. + * + * This function may be called multiple times for the same commit. The client's + * release point will be signalled when all registered points are signalled, and + * a new buffer has been committed. + * + * Because the given release point may not be materialized, a wl_event_loop must + * be supplied to schedule a wait internally, if needed + */ +bool wlr_linux_drm_syncobj_v1_state_add_release_point( + struct wlr_linux_drm_syncobj_surface_v1_state *state, + struct wlr_drm_syncobj_timeline *release_timeline, uint64_t release_point, + struct wl_event_loop *event_loop); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_output.h b/3rdparty/wlroots/include/wlr/types/wlr_output.h new file mode 100644 index 0000000000..4485b36945 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_output.h @@ -0,0 +1,671 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_OUTPUT_H +#define WLR_TYPES_WLR_OUTPUT_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +enum wlr_output_mode_aspect_ratio { + WLR_OUTPUT_MODE_ASPECT_RATIO_NONE, + WLR_OUTPUT_MODE_ASPECT_RATIO_4_3, + WLR_OUTPUT_MODE_ASPECT_RATIO_16_9, + WLR_OUTPUT_MODE_ASPECT_RATIO_64_27, + WLR_OUTPUT_MODE_ASPECT_RATIO_256_135, +}; + +struct wlr_output_mode { + int32_t width, height; + int32_t refresh; // mHz + bool preferred; + enum wlr_output_mode_aspect_ratio picture_aspect_ratio; + struct wl_list link; +}; + +struct wlr_output_cursor { + struct wlr_output *output; + double x, y; + bool enabled; + bool visible; + uint32_t width, height; + struct wlr_fbox src_box; + enum wl_output_transform transform; + int32_t hotspot_x, hotspot_y; + struct wlr_texture *texture; + bool own_texture; + struct wlr_drm_syncobj_timeline *wait_timeline; + uint64_t wait_point; + struct wl_list link; + + struct { + struct wl_listener renderer_destroy; + struct wlr_color_transform *color_transform; + } WLR_PRIVATE; +}; + +enum wlr_output_adaptive_sync_status { + WLR_OUTPUT_ADAPTIVE_SYNC_DISABLED, + WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED, +}; + +enum wlr_output_state_field { + WLR_OUTPUT_STATE_BUFFER = 1 << 0, + WLR_OUTPUT_STATE_DAMAGE = 1 << 1, + WLR_OUTPUT_STATE_MODE = 1 << 2, + WLR_OUTPUT_STATE_ENABLED = 1 << 3, + WLR_OUTPUT_STATE_SCALE = 1 << 4, + WLR_OUTPUT_STATE_TRANSFORM = 1 << 5, + WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED = 1 << 6, + WLR_OUTPUT_STATE_RENDER_FORMAT = 1 << 7, + WLR_OUTPUT_STATE_SUBPIXEL = 1 << 8, + WLR_OUTPUT_STATE_LAYERS = 1 << 9, + WLR_OUTPUT_STATE_WAIT_TIMELINE = 1 << 10, + WLR_OUTPUT_STATE_SIGNAL_TIMELINE = 1 << 11, + WLR_OUTPUT_STATE_COLOR_TRANSFORM = 1 << 12, + WLR_OUTPUT_STATE_IMAGE_DESCRIPTION = 1 << 13, +}; + +enum wlr_output_state_mode_type { + WLR_OUTPUT_STATE_MODE_FIXED, + WLR_OUTPUT_STATE_MODE_CUSTOM, +}; + +/** + * Colorimetric image description. + * + * Carries information about the color encoding used for a struct wlr_buffer. + * + * Supported primaries are advertised in wlr_output.supported_primaries. + * Supported transfer functions are advertised in + * wlr_output.supported_transfer_functions. + * + * mastering_display_primaries, mastering_luminance, max_cll and max_fall are + * optional. Luminances are given in cd/m². + */ +struct wlr_output_image_description { + enum wlr_color_named_primaries primaries; + enum wlr_color_transfer_function transfer_function; + + struct wlr_color_primaries mastering_display_primaries; + struct { + double min, max; + } mastering_luminance; + double max_cll; // max content light level + double max_fall; // max frame-average light level +}; + +/** + * Holds the double-buffered output state. + */ +struct wlr_output_state { + uint32_t committed; // enum wlr_output_state_field + // Set to true to allow output reconfiguration to occur which may result + // in temporary output disruptions and content misrepresentations. + bool allow_reconfiguration; + pixman_region32_t damage; // output-buffer-local coordinates + bool enabled; + float scale; + enum wl_output_transform transform; + bool adaptive_sync_enabled; + uint32_t render_format; + enum wl_output_subpixel subpixel; + + struct wlr_buffer *buffer; + // Source crop for the buffer. If all zeros then no crop is applied. + // As usual with source crop, this is in buffer coordinates. + // Double-buffered by WLR_OUTPUT_STATE_BUFFER along with `buffer`. + struct wlr_fbox buffer_src_box; + // Destination rect to scale the buffer to (after source crop). If width + // and height are zero then the buffer is displayed at native size. The + // offset is relative to the origin of this output. Double-buffered by + // WLR_OUTPUT_STATE_BUFFER along with `buffer`. + struct wlr_box buffer_dst_box; + + /* Request a tearing page-flip. When enabled, this may cause the output to + * display a part of the previous buffer and a part of the current buffer at + * the same time. The backend may reject the commit if a tearing page-flip + * cannot be performed, in which case the caller should fall back to a + * regular page-flip at the next wlr_output.frame event. */ + bool tearing_page_flip; + + enum wlr_output_state_mode_type mode_type; + struct wlr_output_mode *mode; + struct { + int32_t width, height; + int32_t refresh; // mHz, may be zero + } custom_mode; + + struct wlr_output_layer_state *layers; + size_t layers_len; + + struct wlr_drm_syncobj_timeline *wait_timeline; + uint64_t wait_point; + struct wlr_drm_syncobj_timeline *signal_timeline; + uint64_t signal_point; + + struct wlr_color_transform *color_transform; + + struct wlr_output_image_description *image_description; +}; + +struct wlr_output_impl; +struct wlr_render_pass; + +/** + * A compositor output region. This typically corresponds to a monitor that + * displays part of the compositor space. + * + * The `frame` event will be emitted when it is a good time for the compositor + * to submit a new frame. + * + * To render a new frame compositors should call wlr_output_begin_render_pass(), + * perform rendering on that render pass, and finally call + * wlr_output_commit_state(). + */ +struct wlr_output { + const struct wlr_output_impl *impl; + struct wlr_backend *backend; + struct wl_event_loop *event_loop; + + struct wl_global *global; + struct wl_list resources; + + char *name; + char *description; // may be NULL + char *make, *model, *serial; // may be NULL + int32_t phys_width, phys_height; // mm + const struct wlr_color_primaries *default_primaries; // may be NULL + + // Note: some backends may have zero modes + struct wl_list modes; // wlr_output_mode.link + struct wlr_output_mode *current_mode; + int32_t width, height; + int32_t refresh; // mHz, may be zero + + uint32_t supported_primaries; // bitfield of enum wlr_color_named_primaries + uint32_t supported_transfer_functions; // bitfield of enum wlr_color_transfer_function + + bool enabled; + float scale; + enum wl_output_subpixel subpixel; + enum wl_output_transform transform; + enum wlr_output_adaptive_sync_status adaptive_sync_status; + uint32_t render_format; + const struct wlr_output_image_description *image_description; + + // Indicates whether making changes to adaptive sync status is supported. + // If false, changes to adaptive sync status is guaranteed to fail. If + // true, changes may either succeed or fail. + bool adaptive_sync_supported; + + bool needs_frame; + // damage for cursors and fullscreen surface, in output-local coordinates + bool frame_pending; + + // true for example with VR headsets + bool non_desktop; + + // Commit sequence number. Incremented on each commit, may overflow. + uint32_t commit_seq; + + struct { + // Request to render a frame + struct wl_signal frame; + // Emitted when software cursors or backend-specific logic damage the + // output + struct wl_signal damage; // struct wlr_output_event_damage + // Emitted when a new frame needs to be committed (because of + // backend-specific logic) + struct wl_signal needs_frame; + // Emitted right before commit + struct wl_signal precommit; // struct wlr_output_event_precommit + // Emitted right after commit + struct wl_signal commit; // struct wlr_output_event_commit + // Emitted right after a commit has been presented to the user for + // enabled outputs + struct wl_signal present; // struct wlr_output_event_present + // Emitted after a client bound the wl_output global + struct wl_signal bind; // struct wlr_output_event_bind + struct wl_signal description; + struct wl_signal request_state; // struct wlr_output_event_request_state + struct wl_signal destroy; + } events; + + struct wl_event_source *idle_frame; + struct wl_event_source *idle_done; + + int attach_render_locks; // number of locks forcing rendering + + struct wl_list cursors; // wlr_output_cursor.link + struct wlr_output_cursor *hardware_cursor; + struct wlr_swapchain *cursor_swapchain; + struct wlr_buffer *cursor_front_buffer; + int software_cursor_locks; // number of locks forcing software cursors + + struct wl_list layers; // wlr_output_layer.link + + struct wlr_allocator *allocator; + struct wlr_renderer *renderer; + struct wlr_swapchain *swapchain; + + struct wlr_addon_set addons; + + void *data; + + struct { + struct wl_listener display_destroy; + struct wlr_output_image_description image_description_value; + struct wlr_color_transform *color_transform; + struct wlr_color_primaries default_primaries_value; + } WLR_PRIVATE; +}; + +struct wlr_output_event_damage { + struct wlr_output *output; + const pixman_region32_t *damage; // output-buffer-local coordinates +}; + +struct wlr_output_event_precommit { + struct wlr_output *output; + struct timespec when; + const struct wlr_output_state *state; +}; + +struct wlr_output_event_commit { + struct wlr_output *output; + struct timespec when; + const struct wlr_output_state *state; +}; + +enum wlr_output_present_flag { + // The presentation was synchronized to the "vertical retrace" by the + // display hardware such that tearing does not happen. + WLR_OUTPUT_PRESENT_VSYNC = 0x1, + // The display hardware provided measurements that the hardware driver + // converted into a presentation timestamp. + WLR_OUTPUT_PRESENT_HW_CLOCK = 0x2, + // The display hardware signalled that it started using the new image + // content. + WLR_OUTPUT_PRESENT_HW_COMPLETION = 0x4, + // The presentation of this update was done zero-copy. + WLR_OUTPUT_PRESENT_ZERO_COPY = 0x8, +}; + +struct wlr_output_event_present { + struct wlr_output *output; + // Frame submission for which this presentation event is for (see + // wlr_output.commit_seq). + uint32_t commit_seq; + // Whether the frame was presented at all. + bool presented; + // Time when the content update turned into light the first time. + struct timespec when; + // Vertical retrace counter. Zero if unavailable. + unsigned seq; + // Prediction of how many nanoseconds after `when` the very next output + // refresh may occur. Zero if unknown. + int refresh; // nsec + uint32_t flags; // enum wlr_output_present_flag +}; + +struct wlr_output_event_bind { + struct wlr_output *output; + struct wl_resource *resource; +}; + +struct wlr_output_event_request_state { + struct wlr_output *output; + const struct wlr_output_state *state; +}; + +void wlr_output_create_global(struct wlr_output *output, struct wl_display *display); +void wlr_output_destroy_global(struct wlr_output *output); +/** + * Initialize the output's rendering subsystem with the provided allocator and + * renderer. After initialization, this function may invoked again to reinitialize + * the allocator and renderer to different values. + * + * Call this function prior to any call to wlr_output_begin_render_pass(), + * wlr_output_commit_state() or wlr_output_cursor_create(). + * + * The buffer capabilities of the provided must match the capabilities of the + * output's backend. Returns false otherwise. + */ +bool wlr_output_init_render(struct wlr_output *output, + struct wlr_allocator *allocator, struct wlr_renderer *renderer); +/** + * Returns the preferred mode for this output. If the output doesn't support + * modes, returns NULL. + */ +struct wlr_output_mode *wlr_output_preferred_mode(struct wlr_output *output); +/** + * Set the output name. + * + * Output names are subject to the following rules: + * + * - Each output name must be unique. + * - The name cannot change after the output has been advertised to clients. + * + * For more details, see the protocol documentation for wl_output.name. + */ +void wlr_output_set_name(struct wlr_output *output, const char *name); +void wlr_output_set_description(struct wlr_output *output, const char *desc); +/** + * Schedule a done event. + * + * This is intended to be used by wl_output add-on interfaces. + */ +void wlr_output_schedule_done(struct wlr_output *output); +void wlr_output_destroy(struct wlr_output *output); +/** + * Computes the transformed output resolution. + */ +void wlr_output_transformed_resolution(struct wlr_output *output, + int *width, int *height); +/** + * Computes the transformed and scaled output resolution. + */ +void wlr_output_effective_resolution(struct wlr_output *output, + int *width, int *height); +/** + * Test whether this output state would be accepted by the backend. If this + * function returns true, wlr_output_commit_state() will only fail due to a + * runtime error. This function does not change the current state of the + * output. + */ +bool wlr_output_test_state(struct wlr_output *output, + const struct wlr_output_state *state); +/** + * Attempts to apply the state to this output. This function may fail for any + * reason and return false. If failed, none of the state would have been applied, + * this function is atomic. If the commit succeeded, true is returned. + * + * Note: wlr_output_state_finish() would typically be called after the state + * has been committed. + */ +bool wlr_output_commit_state(struct wlr_output *output, + const struct wlr_output_state *state); +/** + * Manually schedules a `frame` event. If a `frame` event is already pending, + * it is a no-op. + */ +void wlr_output_schedule_frame(struct wlr_output *output); +/** + * Returns the maximum length of each gamma ramp, or 0 if unsupported. + */ +size_t wlr_output_get_gamma_size(struct wlr_output *output); +/** + * Returns the wlr_output matching the provided wl_output resource. If the + * resource isn't a wl_output, it aborts. If the resource is inert (because the + * wlr_output has been destroyed), NULL is returned. + */ +struct wlr_output *wlr_output_from_resource(struct wl_resource *resource); +/** + * Locks the output to only use rendering instead of direct scan-out. This is + * useful if direct scan-out needs to be temporarily disabled (e.g. during + * screen capture). There must be as many unlocks as there have been locks to + * restore the original state. There should never be an unlock before a lock. + */ +void wlr_output_lock_attach_render(struct wlr_output *output, bool lock); +/** + * Locks the output to only use software cursors instead of hardware cursors. + * This is useful if hardware cursors need to be temporarily disabled (e.g. + * during screen capture). There must be as many unlocks as there have been + * locks to restore the original state. There should never be an unlock before + * a lock. + */ +void wlr_output_lock_software_cursors(struct wlr_output *output, bool lock); +/** + * Render software cursors. The damage is in buffer-local coordinate space. + * + * This is a utility function that can be called when compositors render. + */ +void wlr_output_add_software_cursors_to_render_pass(struct wlr_output *output, + struct wlr_render_pass *render_pass, const pixman_region32_t *damage); +/** + * Get the set of DRM formats suitable for the primary buffer, assuming a + * buffer with the specified capabilities. + * + * NULL is returned if the backend doesn't have any format constraint, ie. all + * formats are supported. An empty set is returned if the backend doesn't + * support any format. + */ +const struct wlr_drm_format_set *wlr_output_get_primary_formats( + struct wlr_output *output, uint32_t buffer_caps); +/** + * Check whether direct scan-out is allowed on the output. + * + * Direct scan-out is typically disallowed when there are software cursors or + * during screen capture. + */ +bool wlr_output_is_direct_scanout_allowed(struct wlr_output *output); + + +struct wlr_output_cursor *wlr_output_cursor_create(struct wlr_output *output); +bool wlr_output_cursor_set_buffer(struct wlr_output_cursor *cursor, + struct wlr_buffer *buffer, int32_t hotspot_x, int32_t hotspot_y); +bool wlr_output_cursor_move(struct wlr_output_cursor *cursor, + double x, double y); +void wlr_output_cursor_destroy(struct wlr_output_cursor *cursor); + +/** + * Initialize an output state. + */ +void wlr_output_state_init(struct wlr_output_state *state); +/** + * Releases all resources associated with an output state. + */ +void wlr_output_state_finish(struct wlr_output_state *state); +/** + * Enables or disables an output. A disabled output is turned off and doesn't + * emit `frame` events. + * + * This state will be applied once wlr_output_commit_state() is called. + */ +void wlr_output_state_set_enabled(struct wlr_output_state *state, + bool enabled); +/** + * Sets the output mode of an output. An output mode will specify the resolution + * and refresh rate, among other things. + * + * This state will be applied once wlr_output_commit_state() is called. + */ +void wlr_output_state_set_mode(struct wlr_output_state *state, + struct wlr_output_mode *mode); +/** + * Sets a custom output mode for an output. See wlr_output_state_set_mode() + * for details. + * + * When the output advertises fixed modes, custom modes are not guaranteed to + * work correctly, they may result in visual artifacts. If a suitable fixed mode + * is available, compositors should prefer it and use wlr_output_state_set_mode() + * instead of custom modes. + * + * Setting `refresh` to zero lets the backend pick a preferred value. The + * output needs to be enabled. + * + * This state will be applied once wlr_output_commit_state() is called. + */ +void wlr_output_state_set_custom_mode(struct wlr_output_state *state, + int32_t width, int32_t height, int32_t refresh); +/** + * Sets the scale of an output. The scale is used to increase the size of UI + * elements to aid users who use high DPI outputs. + * + * This state will be applied once wlr_output_commit_state() is called. + */ +void wlr_output_state_set_scale(struct wlr_output_state *state, float scale); +/** + * Sets the transform of an output. The transform is used to rotate or flip + * the contents of the screen. + * + * This state will be applied once wlr_output_commit_state() is called. + */ +void wlr_output_state_set_transform(struct wlr_output_state *state, + enum wl_output_transform transform); +/** + * Enables or disable adaptive sync for an output (ie. variable refresh rate). + * Compositors can inspect `wlr_output.adaptive_sync_status` to query the + * effective status. Backends that don't support adaptive sync will reject the + * output commit. + * + * This state will be applied once wlr_output_commit_state() is called. + */ +void wlr_output_state_set_adaptive_sync_enabled(struct wlr_output_state *state, + bool enabled); +/** + * Sets the render format for an output. + * + * The default value is DRM_FORMAT_XRGB8888. + * + * While high bit depth render formats are necessary for a monitor to receive + * useful high bit data, they do not guarantee it; a DRM_FORMAT_XBGR2101010 + * buffer will only lead to sending 10-bpc image data to the monitor if + * hardware and software permit this. + * + * This only affects the format of the output buffer used when rendering using + * the output's own swapchain as with wlr_output_begin_render_pass(). It has no + * impact on the cursor buffer format, or on the formats supported for direct + * scan-out (see also wlr_output_state_set_buffer()). + * + * This state will be applied once wlr_output_commit_state() is called. + */ +void wlr_output_state_set_render_format(struct wlr_output_state *state, + uint32_t format); +/** + * Sets the subpixel layout hint for an output. Note that this is only a hint + * and may be ignored. The default value depends on the backend. + * + * This state will be applied once wlr_output_commit_state() is called. + */ +void wlr_output_state_set_subpixel(struct wlr_output_state *state, + enum wl_output_subpixel subpixel); +/** + * Sets the buffer for an output. The buffer contains the contents of the + * screen. If the compositor wishes to present a new frame, they must commit + * with a buffer. + * + * This state will be applied once wlr_output_commit_state() is called. + */ +void wlr_output_state_set_buffer(struct wlr_output_state *state, + struct wlr_buffer *buffer); +/** + * Sets the damage region for an output. This is used as a hint to the backend + * and can be used to reduce power consumption or increase performance on some + * devices. + * + * This should be called in along with wlr_output_state_set_buffer(). + * This state will be applied once wlr_output_commit_state() is called. + */ +void wlr_output_state_set_damage(struct wlr_output_state *state, + const pixman_region32_t *damage); +/** + * Set the output layers for an output. Output layers are used to try and take + * advantage of backend features that may reduce the amount of things that + * need to be composited. + * + * The array must be kept valid by the caller until wlr_output_state_finish() + * and all copies of the state have been finished as well. + * This state will be applied once wlr_output_commit_state() is called. + */ +void wlr_output_state_set_layers(struct wlr_output_state *state, + struct wlr_output_layer_state *layers, size_t layers_len); +/** + * Set a timeline point to wait on before displaying the next frame. + * + * Committing a wait timeline point without a buffer is invalid. + * + * There is only a single wait timeline point, waiting for multiple timeline + * points is unsupported. + * + * Support for this feature is advertised by the timeline field in + * struct wlr_output. + */ +void wlr_output_state_set_wait_timeline(struct wlr_output_state *state, + struct wlr_drm_syncobj_timeline *timeline, uint64_t src_point); +/** + * Set a timeline point to be signalled when the frame is no longer being used + * by the backend. + * + * Committing a signal timeline point without a buffer is invalid. + * + * There is only a single signal timeline point, signalling multiple timeline + * points is unsupported. + * + * Support for this feature is advertised by the timeline field in + * struct wlr_output. + */ +void wlr_output_state_set_signal_timeline(struct wlr_output_state *state, + struct wlr_drm_syncobj_timeline *timeline, uint64_t dst_point); +/** + * Set the color transform for an output. + * + * The color transform is applied after blending output layers. + */ +void wlr_output_state_set_color_transform(struct wlr_output_state *state, + struct wlr_color_transform *tr); + +/** + * Set the colorimetry image description. + */ +bool wlr_output_state_set_image_description(struct wlr_output_state *state, + const struct wlr_output_image_description *image_desc); + +/** + * Copies the output state from src to dst. It is safe to then + * wlr_output_state_finish() src and have dst still be valid. + * + * Note: The lifetime of the output layers inside the state are not managed. It + * is the responsibility of the constructor of the output layers to make sure + * they remain valid for the output state and all copies made. + */ +bool wlr_output_state_copy(struct wlr_output_state *dst, + const struct wlr_output_state *src); + + +/** + * Re-configure the swapchain as required for the output's primary buffer. + * + * If a NULL swapchain is passed in, a new swapchain is allocated. If the + * swapchain is already suitable for the output's primary buffer, this function + * is a no-op. + * + * The state describes the output changes the swapchain's buffers will be + * committed with. A NULL state indicates no change. + */ +bool wlr_output_configure_primary_swapchain(struct wlr_output *output, + const struct wlr_output_state *state, struct wlr_swapchain **swapchain); +/** + * Begin a render pass on this output. + * + * Compositors can call this function to begin rendering. After the render pass + * has been submitted, they should call wlr_output_commit_state() to submit the + * new frame. + * + * On error, NULL is returned. Creating a render pass on a disabled output is + * an error. + * + * The state describes the output changes the rendered frame will be + * committed with. A NULL state indicates no change. + * + * If non-NULL, buffer_age is set to the drawing buffer age in number of + * frames or -1 if unknown. This is useful for damage tracking. + */ +struct wlr_render_pass *wlr_output_begin_render_pass(struct wlr_output *output, + struct wlr_output_state *state, struct wlr_buffer_pass_options *render_options); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_output_layer.h b/3rdparty/wlroots/include/wlr/types/wlr_output_layer.h new file mode 100644 index 0000000000..af59ab8dcf --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_output_layer.h @@ -0,0 +1,103 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_OUTPUT_LAYER_H +#define WLR_TYPES_WLR_OUTPUT_LAYER_H + +#include +#include +#include +#include + +/** + * An output layer. + * + * Output layers are displayed between the output primary buffer (see + * wlr_output_attach_buffer()) and the cursor buffer. They can offload some + * rendering work to the backend. + * + * To configure output layers, callers should call wlr_output_layer_create() to + * create layers, attach struct wlr_output_layer_state onto + * struct wlr_output_state via wlr_output_state_set_layers() to describe their new + * state, and commit the output via wlr_output_commit_state(). + * + * Backends may have arbitrary limitations when it comes to displaying output + * layers. Backends indicate whether or not a layer can be displayed via + * wlr_output_layer_state.accepted after wlr_output_test_state() or + * wlr_output_commit_state() is called. Compositors using the output layers API + * directly are expected to setup layers, call wlr_output_test_state(), paint + * the layers that the backend rejected with the renderer, then call + * wlr_output_commit_state(). + * + * Callers are responsible for disabling output layers when they need the full + * output contents to be composited onto a single buffer, e.g. during screen + * capture. + * + * Callers must always include the state for all layers on output test/commit. + */ +struct wlr_output_layer { + struct wl_list link; // wlr_output.layers + struct wlr_addon_set addons; + + struct { + struct wl_signal feedback; // struct wlr_output_layer_feedback_event + } events; + + void *data; + + struct { + struct wlr_fbox src_box; + struct wlr_box dst_box; + } WLR_PRIVATE; +}; + +/** + * State for an output layer. + */ +struct wlr_output_layer_state { + struct wlr_output_layer *layer; + + // Buffer to display, or NULL to disable the layer + struct wlr_buffer *buffer; + // Source box, leave empty to use the whole buffer + struct wlr_fbox src_box; + // Destination box in output-buffer-local coordinates + struct wlr_box dst_box; + // Damaged region since last commit in buffer-local coordinates. Leave NULL + // to damage the whole buffer. + const pixman_region32_t *damage; + + // Populated by the backend after wlr_output_test_state() and + // wlr_output_commit_state(), indicates whether the backend has acknowledged + // and will take care of displaying the layer + bool accepted; +}; + +/** + * Feedback for an output layer. + * + * After an output commit, if the backend is not able to display a layer, it + * can send feedback events. These events can be used to re-allocate the + * layer's buffers so that they have a higher chance to get displayed. + */ +struct wlr_output_layer_feedback_event { + dev_t target_device; + const struct wlr_drm_format_set *formats; +}; + +/** + * Create a new output layer. + */ +struct wlr_output_layer *wlr_output_layer_create(struct wlr_output *output); + +/** + * Destroy an output layer. + */ +void wlr_output_layer_destroy(struct wlr_output_layer *layer); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_output_layout.h b/3rdparty/wlroots/include/wlr/types/wlr_output_layout.h new file mode 100644 index 0000000000..b2665b0689 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_output_layout.h @@ -0,0 +1,166 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_OUTPUT_LAYOUT_H +#define WLR_TYPES_WLR_OUTPUT_LAYOUT_H + +#include +#include +#include +#include + +struct wlr_box; + +/** + * Helper to arrange outputs in a 2D coordinate space. The output effective + * resolution is used, see wlr_output_effective_resolution(). + * + * Outputs added to the output layout are automatically exposed to clients (see + * wlr_output_create_global()). They are no longer exposed when removed from the + * layout. + */ +struct wlr_output_layout { + struct wl_list outputs; + struct wl_display *display; + + struct { + struct wl_signal add; // struct wlr_output_layout_output + struct wl_signal change; + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_output_layout_output { + struct wlr_output_layout *layout; + + struct wlr_output *output; + + int x, y; + struct wl_list link; + + bool auto_configured; + + struct { + struct wl_signal destroy; + } events; + + struct { + struct wlr_addon addon; + + struct wl_listener commit; + } WLR_PRIVATE; +}; + +struct wlr_output_layout *wlr_output_layout_create(struct wl_display *display); + +void wlr_output_layout_destroy(struct wlr_output_layout *layout); + +/** + * Get the output layout for the specified output. Returns NULL if no output + * matches. + */ +struct wlr_output_layout_output *wlr_output_layout_get( + struct wlr_output_layout *layout, struct wlr_output *reference); + +/** + * Get the output at the specified layout coordinates. Returns NULL if no + * output matches the coordinates. + */ +struct wlr_output *wlr_output_layout_output_at( + struct wlr_output_layout *layout, double lx, double ly); + +/** + * Add the output to the layout at the specified coordinates. If the output is + * already a part of the output layout, it will become manually configured and + * will be moved to the specified coordinates. + * + * Returns the output's output layout, or NULL on error. + */ +struct wlr_output_layout_output *wlr_output_layout_add(struct wlr_output_layout *layout, + struct wlr_output *output, int lx, int ly); + +/** + * Add the output to the layout as automatically configured. This will place + * the output in a sensible location in the layout. The coordinates of + * the output in the layout will be adjusted dynamically when the layout + * changes. If the output is already a part of the layout, it will become + * automatically configured. + * + * Returns the output's output layout, or NULL on error. + */ +struct wlr_output_layout_output *wlr_output_layout_add_auto(struct wlr_output_layout *layout, + struct wlr_output *output); + +/** + * Remove the output from the layout. If the output is already not a part of + * the layout, this function is a no-op. + */ +void wlr_output_layout_remove(struct wlr_output_layout *layout, + struct wlr_output *output); + +/** + * Given x and y in layout coordinates, adjusts them to local output + * coordinates relative to the given reference output. + */ +void wlr_output_layout_output_coords(struct wlr_output_layout *layout, + struct wlr_output *reference, double *lx, double *ly); + +bool wlr_output_layout_contains_point(struct wlr_output_layout *layout, + struct wlr_output *reference, int lx, int ly); + +bool wlr_output_layout_intersects(struct wlr_output_layout *layout, + struct wlr_output *reference, const struct wlr_box *target_lbox); + +/** + * Get the closest point on this layout from the given point from the reference + * output. If reference is NULL, gets the closest point from the entire layout. + * If the layout is empty, the result is the given point itself. + */ +void wlr_output_layout_closest_point(struct wlr_output_layout *layout, + struct wlr_output *reference, double lx, double ly, + double *dest_lx, double *dest_ly); + +/** + * Get the box of the layout for the given reference output in layout + * coordinates. If `reference` is NULL, the box will be for the extents of the + * entire layout. If the output isn't in the layout, the box will be empty. + */ +void wlr_output_layout_get_box(struct wlr_output_layout *layout, + struct wlr_output *reference, struct wlr_box *dest_box); + +/** + * Get the output closest to the center of the layout extents. + */ +struct wlr_output *wlr_output_layout_get_center_output( + struct wlr_output_layout *layout); + +enum wlr_direction { + WLR_DIRECTION_UP = 1 << 0, + WLR_DIRECTION_DOWN = 1 << 1, + WLR_DIRECTION_LEFT = 1 << 2, + WLR_DIRECTION_RIGHT = 1 << 3, +}; + +/** + * Get the closest adjacent output to the reference output from the reference + * point in the given direction. + */ +struct wlr_output *wlr_output_layout_adjacent_output( + struct wlr_output_layout *layout, enum wlr_direction direction, + struct wlr_output *reference, double ref_lx, double ref_ly); +struct wlr_output *wlr_output_layout_farthest_output( + struct wlr_output_layout *layout, enum wlr_direction direction, + struct wlr_output *reference, double ref_lx, double ref_ly); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_output_management_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_output_management_v1.h new file mode 100644 index 0000000000..bff20e5d9c --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_output_management_v1.h @@ -0,0 +1,187 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_OUTPUT_MANAGEMENT_V1_H +#define WLR_TYPES_WLR_OUTPUT_MANAGEMENT_V1_H + +#include +#include +#include + +struct wlr_output_manager_v1 { + struct wl_display *display; + struct wl_global *global; + struct wl_list resources; // wl_resource_get_link() + + struct wl_list heads; // wlr_output_head_v1.link + uint32_t serial; + bool current_configuration_dirty; + + struct { + /** + * The `apply` and `test` events are emitted when a client requests a + * configuration to be applied or tested. The compositor should send + * feedback with `wlr_output_configuration_v1_send_succeeded` xor + * `wlr_output_configuration_v1_send_failed`. + * + * The compositor gains ownership over the configuration (passed as the + * event data). That is, the compositor is responsible for destroying + * the configuration. + */ + struct wl_signal apply; // struct wlr_output_configuration_v1 + struct wl_signal test; // struct wlr_output_configuration_v1 + + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_output_head_v1_state { + struct wlr_output *output; + + bool enabled; + struct wlr_output_mode *mode; + struct { + int32_t width, height; + int32_t refresh; + } custom_mode; + int32_t x, y; + enum wl_output_transform transform; + float scale; + bool adaptive_sync_enabled; +}; + +struct wlr_output_head_v1 { + struct wlr_output_head_v1_state state; + struct wlr_output_manager_v1 *manager; + struct wl_list link; // wlr_output_manager_v1.heads + + struct wl_list resources; // wl_resource_get_link() + struct wl_list mode_resources; // wl_resource_get_link() + + struct { + struct wl_listener output_destroy; + } WLR_PRIVATE; +}; + +struct wlr_output_configuration_v1 { + struct wl_list heads; // wlr_output_configuration_head_v1.link + + // client state + struct wlr_output_manager_v1 *manager; + uint32_t serial; + bool finalized; // client has requested to apply the config + bool finished; // feedback has been sent by the compositor + struct wl_resource *resource; // can be NULL if destroyed early +}; + +struct wlr_output_configuration_head_v1 { + struct wlr_output_head_v1_state state; + struct wlr_output_configuration_v1 *config; + struct wl_list link; // wlr_output_configuration_v1.heads + + // client state + struct wl_resource *resource; // can be NULL if finalized or disabled + + struct { + struct wl_listener output_destroy; + } WLR_PRIVATE; +}; + +/** + * Create a new output manager. The compositor is responsible for calling + * wlr_output_manager_v1_set_configuration() whenever the current output + * configuration changes. + */ +struct wlr_output_manager_v1 *wlr_output_manager_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_output_manager_v1_destroy(struct wlr_output_manager_v1 *manager, bool destroy_global_safe); +/** + * Updates the output manager's current configuration. This will broadcast any + * changes to all clients. + * + * This function takes ownership over `config`. That is, the compositor must not + * access the configuration anymore. + */ +void wlr_output_manager_v1_set_configuration( + struct wlr_output_manager_v1 *manager, + struct wlr_output_configuration_v1 *config); + +/** + * Create a new, empty output configuration. Compositors should add current head + * status with wlr_output_configuration_head_v1_create(). They can then call + * wlr_output_manager_v1_set_configuration(). + */ +struct wlr_output_configuration_v1 *wlr_output_configuration_v1_create(void); +void wlr_output_configuration_v1_destroy( + struct wlr_output_configuration_v1 *config); +/** + * If the configuration comes from a client request, this sends positive + * feedback to the client (configuration has been applied). + */ +void wlr_output_configuration_v1_send_succeeded( + struct wlr_output_configuration_v1 *config); +/** + * If the configuration comes from a client request, this sends negative + * feedback to the client (configuration has not been applied). + */ +void wlr_output_configuration_v1_send_failed( + struct wlr_output_configuration_v1 *config); + +/** + * Create a new configuration head for the given output. This adds the head to + * the provided output configuration. + * + * The configuration head will be pre-filled with data from `output`. The + * compositor should adjust this data according to its current internal state. + */ +struct wlr_output_configuration_head_v1 * + wlr_output_configuration_head_v1_create( + struct wlr_output_configuration_v1 *config, struct wlr_output *output); + +/** + * Apply the head state on the supplied struct wlr_output_state. + * + * Compositors can then pass the resulting struct wlr_output_state to + * wlr_output_commit_state() or wlr_output_test_state(). + * + * The position needs to be applied manually by the caller. + */ +void wlr_output_head_v1_state_apply( + const struct wlr_output_head_v1_state *head_state, + struct wlr_output_state *output_state); + +/** + * Build an array of struct wlr_output_state reflecting the new configuration. + * + * The states_len pointer will be populated with the number of elements in the + * array. The caller is responsible for freeing the array. + * + * The returned array can be passed to wlr_backend_test() and + * wlr_backend_commit(). + */ +struct wlr_backend_output_state *wlr_output_configuration_v1_build_state( + const struct wlr_output_configuration_v1 *config, size_t *states_len); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_output_power_management_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_output_power_management_v1.h new file mode 100644 index 0000000000..57e1a07963 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_output_power_management_v1.h @@ -0,0 +1,59 @@ +#ifndef WLR_TYPES_WLR_OUTPUT_POWER_MANAGEMENT_V1_H +#define WLR_TYPES_WLR_OUTPUT_POWER_MANAGEMENT_V1_H + +#include +#include +#include "wlr-output-power-management-unstable-v1-protocol.h" + +struct wlr_output_power_manager_v1 { + struct wl_global *global; + struct wl_list output_powers; // wlr_output_power_v1.link + + struct { + struct wl_signal set_mode; // struct wlr_output_power_v1_set_mode_event + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_output_power_v1 { + struct wl_resource *resource; + struct wlr_output *output; + struct wlr_output_power_manager_v1 *manager; + struct wl_list link; // wlr_output_power_manager_v1.output_powers + + void *data; + + struct { + struct wl_listener output_destroy_listener; + struct wl_listener output_commit_listener; + } WLR_PRIVATE; +}; + +struct wlr_output_power_v1_set_mode_event { + struct wlr_output *output; + enum zwlr_output_power_v1_mode mode; +}; + +struct wlr_output_power_manager_v1 *wlr_output_power_manager_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_output_power_manager_v1_destroy(struct wlr_output_power_manager_v1 *manager, + bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_output_swapchain_manager.h b/3rdparty/wlroots/include/wlr/types/wlr_output_swapchain_manager.h new file mode 100644 index 0000000000..26b3e5636e --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_output_swapchain_manager.h @@ -0,0 +1,91 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_OUTPUT_SWAPCHAIN_MANAGER_H +#define WLR_TYPES_WLR_OUTPUT_SWAPCHAIN_MANAGER_H + +#include + +struct wlr_backend; +struct wlr_backend_output_state; +struct wlr_output; + +/** + * Helper to allocate swapchains for mode-setting. + * + * Compositors are expected to call wlr_output_swapchain_manager_init(), then + * pass the new desired output states to wlr_output_swapchain_manager_prepare(). + * Compositors may retry that step with different desired output states until + * they find a working configuration. Then, compositors should use + * wlr_output_swapchain_manager_get_swapchain() to get pending swapchains for + * outputs, render onto a new buffer acquired from the swapchain, and call + * wlr_backend_commit(). If that succeeds, wlr_output_swapchain_manager_apply() + * should be called. After compositors are done with the manager, be it after a + * success or failure, they should call wlr_output_swapchain_manager_finish(). + */ +struct wlr_output_swapchain_manager { + struct wlr_backend *backend; + + struct { + struct wl_array outputs; // struct wlr_output_swapchain_manager_output + } WLR_PRIVATE; +}; + +/** + * Initialize the manager. + * + * Compositors should call wlr_output_swapchain_manager_finish() to cleanup the + * manager. + */ +void wlr_output_swapchain_manager_init(struct wlr_output_swapchain_manager *manager, + struct wlr_backend *backend); + +/** + * Prepare a commit for a mode-setting backend commit. + * + * This function allocates (and potentially re-allocates) swapchains suitable + * for the new output configuration. On success, compositors should call + * wlr_output_swapchain_manager_get_swapchain() to get the pending swapchain, + * repaint with a buffer acquired from the swapchain, call wlr_backend_commit() + * and then wlr_output_swapchain_manager_apply(). + * + * Compositors should include all enabled outputs to maximize the chance to + * find a working configuration, even if an output state is unchanged by the + * compositor. This function might re-create swapchains for already-enabled + * outputs. + */ +bool wlr_output_swapchain_manager_prepare(struct wlr_output_swapchain_manager *manager, + const struct wlr_backend_output_state *states, size_t states_len); + +/** + * Get the pending swapchain for an output. + * + * This can only be called after a successful + * wlr_output_swapchain_manager_prepare(), if the output was passed in. + * + * If the output is disabled, NULL is returned. + */ +struct wlr_swapchain *wlr_output_swapchain_manager_get_swapchain( + struct wlr_output_swapchain_manager *manager, struct wlr_output *output); + +/** + * Apply swapchains allocated for the last successful call to + * wlr_output_swapchain_manager_prepare(). + * + * This function swaps output swapchains with new swapchains suitable for the + * new output configuration. It should be called after a successful + * wlr_backend_commit(). + */ +void wlr_output_swapchain_manager_apply(struct wlr_output_swapchain_manager *manager); + +/** + * Cleanup resources allocated by the manager. + */ +void wlr_output_swapchain_manager_finish(struct wlr_output_swapchain_manager *manager); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_pointer.h b/3rdparty/wlroots/include/wlr/types/wlr_pointer.h new file mode 100644 index 0000000000..756ffa1f60 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_pointer.h @@ -0,0 +1,152 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_POINTER_H +#define WLR_TYPES_WLR_POINTER_H + +#include +#include +#include +#include + +#define WLR_POINTER_BUTTONS_CAP 16 + +struct wlr_pointer_impl; + +struct wlr_pointer { + struct wlr_input_device base; + + const struct wlr_pointer_impl *impl; + + char *output_name; + + uint32_t buttons[WLR_POINTER_BUTTONS_CAP]; + size_t button_count; + + struct { + struct wl_signal motion; // struct wlr_pointer_motion_event + struct wl_signal motion_absolute; // struct wlr_pointer_motion_absolute_event + struct wl_signal button; // struct wlr_pointer_button_event + struct wl_signal axis; // struct wlr_pointer_axis_event + struct wl_signal frame; + + struct wl_signal swipe_begin; // struct wlr_pointer_swipe_begin_event + struct wl_signal swipe_update; // struct wlr_pointer_swipe_update_event + struct wl_signal swipe_end; // struct wlr_pointer_swipe_end_event + + struct wl_signal pinch_begin; // struct wlr_pointer_pinch_begin_event + struct wl_signal pinch_update; // struct wlr_pointer_pinch_update_event + struct wl_signal pinch_end; // struct wlr_pointer_pinch_end_event + + struct wl_signal hold_begin; // struct wlr_pointer_hold_begin_event + struct wl_signal hold_end; // struct wlr_pointer_hold_end_event + } events; + + void *data; +}; + +struct wlr_pointer_motion_event { + struct wlr_pointer *pointer; + uint32_t time_msec; + double delta_x, delta_y; + double unaccel_dx, unaccel_dy; +}; + +struct wlr_pointer_motion_absolute_event { + struct wlr_pointer *pointer; + uint32_t time_msec; + // From 0..1 + double x, y; +}; + +struct wlr_pointer_button_event { + struct wlr_pointer *pointer; + uint32_t time_msec; + uint32_t button; + enum wl_pointer_button_state state; +}; + +#define WLR_POINTER_AXIS_DISCRETE_STEP 120 + +struct wlr_pointer_axis_event { + struct wlr_pointer *pointer; + uint32_t time_msec; + enum wl_pointer_axis_source source; + enum wl_pointer_axis orientation; + enum wl_pointer_axis_relative_direction relative_direction; + double delta; + int32_t delta_discrete; +}; + +struct wlr_pointer_swipe_begin_event { + struct wlr_pointer *pointer; + uint32_t time_msec; + uint32_t fingers; +}; + +struct wlr_pointer_swipe_update_event { + struct wlr_pointer *pointer; + uint32_t time_msec; + uint32_t fingers; + // Relative coordinates of the logical center of the gesture + // compared to the previous event. + double dx, dy; +}; + +struct wlr_pointer_swipe_end_event { + struct wlr_pointer *pointer; + uint32_t time_msec; + bool cancelled; +}; + +struct wlr_pointer_pinch_begin_event { + struct wlr_pointer *pointer; + uint32_t time_msec; + uint32_t fingers; +}; + +struct wlr_pointer_pinch_update_event { + struct wlr_pointer *pointer; + uint32_t time_msec; + uint32_t fingers; + // Relative coordinates of the logical center of the gesture + // compared to the previous event. + double dx, dy; + // Absolute scale compared to the begin event + double scale; + // Relative angle in degrees clockwise compared to the previous event. + double rotation; +}; + +struct wlr_pointer_pinch_end_event { + struct wlr_pointer *pointer; + uint32_t time_msec; + bool cancelled; +}; + +struct wlr_pointer_hold_begin_event { + struct wlr_pointer *pointer; + uint32_t time_msec; + uint32_t fingers; +}; + +struct wlr_pointer_hold_end_event { + struct wlr_pointer *pointer; + uint32_t time_msec; + bool cancelled; +}; + +/** + * Get a struct wlr_pointer from a struct wlr_input_device. + * + * Asserts that the input device is a pointer. + */ +struct wlr_pointer *wlr_pointer_from_input_device( + struct wlr_input_device *input_device); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_pointer_constraints_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_pointer_constraints_v1.h new file mode 100644 index 0000000000..d26908c4fc --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_pointer_constraints_v1.h @@ -0,0 +1,122 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_POINTER_CONSTRAINTS_V1_H +#define WLR_TYPES_WLR_POINTER_CONSTRAINTS_V1_H + +#include +#include +#include +#include +#include +#include +#include + +struct wlr_seat; + +enum wlr_pointer_constraint_v1_type { + WLR_POINTER_CONSTRAINT_V1_LOCKED, + WLR_POINTER_CONSTRAINT_V1_CONFINED, +}; + +enum wlr_pointer_constraint_v1_state_field { + WLR_POINTER_CONSTRAINT_V1_STATE_REGION = 1 << 0, + WLR_POINTER_CONSTRAINT_V1_STATE_CURSOR_HINT = 1 << 1, +}; + +struct wlr_pointer_constraint_v1_state { + uint32_t committed; // enum wlr_pointer_constraint_v1_state_field + pixman_region32_t region; + + // only valid for locked_pointer + struct { + bool enabled; + double x, y; + } cursor_hint; +}; + +struct wlr_pointer_constraint_v1 { + struct wlr_pointer_constraints_v1 *pointer_constraints; + + struct wl_resource *resource; + struct wlr_surface *surface; + struct wlr_seat *seat; + enum zwp_pointer_constraints_v1_lifetime lifetime; + enum wlr_pointer_constraint_v1_type type; + pixman_region32_t region; + + struct wlr_pointer_constraint_v1_state current, pending; + + struct wl_list link; // wlr_pointer_constraints_v1.constraints + + struct { + /** + * Emitted when a pointer constraint's region is updated. + */ + struct wl_signal set_region; + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener surface_destroy; + struct wl_listener seat_destroy; + + struct wlr_surface_synced synced; + + bool destroying; + } WLR_PRIVATE; +}; + +struct wlr_pointer_constraints_v1 { + struct wl_global *global; + struct wl_list constraints; // wlr_pointer_constraint_v1.link + + struct { + struct wl_signal destroy; + struct wl_signal new_constraint; // struct wlr_pointer_constraint_v1 + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_pointer_constraints_v1 *wlr_pointer_constraints_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_pointer_constraints_v1_destroy(struct wlr_pointer_constraints_v1 *pointer_constraints, + bool destroy_global_safe); + +struct wlr_pointer_constraint_v1 * + wlr_pointer_constraints_v1_constraint_for_surface( + struct wlr_pointer_constraints_v1 *pointer_constraints, + struct wlr_surface *surface, struct wlr_seat *seat); + +void wlr_pointer_constraint_v1_send_activated( + struct wlr_pointer_constraint_v1 *constraint); +/** + * Deactivate the constraint. May destroy the constraint. + */ +void wlr_pointer_constraint_v1_send_deactivated( + struct wlr_pointer_constraint_v1 *constraint); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_pointer_gestures_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_pointer_gestures_v1.h new file mode 100644 index 0000000000..16f29cfe2d --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_pointer_gestures_v1.h @@ -0,0 +1,98 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_POINTER_GESTURES_V1_H +#define WLR_TYPES_WLR_POINTER_GESTURES_V1_H + +#include +#include +#include + +struct wlr_surface; + +struct wlr_pointer_gestures_v1 { + struct wl_global *global; + struct wl_list swipes; // wl_resource_get_link() + struct wl_list pinches; // wl_resource_get_link() + struct wl_list holds; // wl_resource_get_link() + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_pointer_gestures_v1 *wlr_pointer_gestures_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_pointer_gestures_v1_destroy(struct wlr_pointer_gestures_v1 *gestures, + bool destroy_global_safe); + +void wlr_pointer_gestures_v1_send_swipe_begin( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + uint32_t fingers); +void wlr_pointer_gestures_v1_send_swipe_update( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + double dx, + double dy); +void wlr_pointer_gestures_v1_send_swipe_end( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + bool cancelled); + +void wlr_pointer_gestures_v1_send_pinch_begin( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + uint32_t fingers); +void wlr_pointer_gestures_v1_send_pinch_update( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + double dx, + double dy, + double scale, + double rotation); +void wlr_pointer_gestures_v1_send_pinch_end( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + bool cancelled); + +void wlr_pointer_gestures_v1_send_hold_begin( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + uint32_t fingers); +void wlr_pointer_gestures_v1_send_hold_end( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + bool cancelled); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_presentation_time.h b/3rdparty/wlroots/include/wlr/types/wlr_presentation_time.h new file mode 100644 index 0000000000..1481f5755b --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_presentation_time.h @@ -0,0 +1,121 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_PRESENTATION_TIME_H +#define WLR_TYPES_WLR_PRESENTATION_TIME_H + +#include +#include +#include + +struct wlr_surface; + +struct wlr_output; +struct wlr_output_event_present; + +struct wlr_presentation { + struct wl_global *global; + + struct { + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_presentation_feedback { + struct wl_list resources; // wl_resource_get_link() + + // Only when the wlr_presentation_surface_textured_on_output() or + // wlr_presentation_surface_scanned_out_on_output() helper has been called. + struct wlr_output *output; + bool output_committed; + uint32_t output_commit_seq; + bool zero_copy; + + struct { + struct wl_listener output_commit; + struct wl_listener output_present; + struct wl_listener output_destroy; + } WLR_PRIVATE; +}; + +struct wlr_presentation_event { + struct wlr_output *output; + uint64_t tv_sec; + uint32_t tv_nsec; + uint32_t refresh; + uint64_t seq; + uint32_t flags; // enum wp_presentation_feedback_kind +}; + +struct wlr_backend; + +struct wlr_presentation *wlr_presentation_create(struct wl_display *display, + struct wlr_backend *backend, uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_presentation_destroy(struct wlr_presentation *presentation, bool destroy_global_safe); +/** + * Mark the current surface's buffer as sampled. + * + * The compositor must call this function when it uses the surface's current + * contents (e.g. when rendering the surface's current texture, when + * referencing its current buffer, or when directly scanning out its current + * buffer). A wlr_presentation_feedback is returned. The compositor should call + * wlr_presentation_feedback_send_presented() if this content has been displayed, + * then wlr_presentation_feedback_destroy(). + * + * NULL is returned if the client hasn't requested presentation feedback for + * this surface. + */ +struct wlr_presentation_feedback *wlr_presentation_surface_sampled( + struct wlr_surface *surface); +void wlr_presentation_feedback_send_presented( + struct wlr_presentation_feedback *feedback, + const struct wlr_presentation_event *event); +void wlr_presentation_feedback_destroy( + struct wlr_presentation_feedback *feedback); + +/** + * Fill a wlr_presentation_event from a struct wlr_output_event_present. + */ +void wlr_presentation_event_from_output(struct wlr_presentation_event *event, + const struct wlr_output_event_present *output_event); + +/** + * Mark the current surface's buffer as textured on the given output. + * + * Instead of calling wlr_presentation_surface_sampled() and managing the + * struct wlr_presentation_feedback itself, the compositor can call this function + * before a wlr_output_commit_state() call to indicate that the surface's current + * contents have been copied to a buffer which will be displayed on the output. + */ +void wlr_presentation_surface_textured_on_output(struct wlr_surface *surface, + struct wlr_output *output); +/** + * Mark the current surface's buffer as scanned out on the given output. + * + * Same as wlr_presentation_surface_textured_on_output(), but indicates direct + * scan-out. + */ +void wlr_presentation_surface_scanned_out_on_output(struct wlr_surface *surface, + struct wlr_output *output); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_primary_selection.h b/3rdparty/wlroots/include/wlr/types/wlr_primary_selection.h new file mode 100644 index 0000000000..af3d484900 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_primary_selection.h @@ -0,0 +1,68 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_PRIMARY_SELECTION_H +#define WLR_TYPES_WLR_PRIMARY_SELECTION_H + +#include +#include + +struct wlr_primary_selection_source; + +/** + * A data source implementation. Only the `send` function is mandatory. + */ +struct wlr_primary_selection_source_impl { + void (*send)(struct wlr_primary_selection_source *source, + const char *mime_type, int fd); + void (*destroy)(struct wlr_primary_selection_source *source); +}; + +/** + * A source is the sending side of a selection. + */ +struct wlr_primary_selection_source { + const struct wlr_primary_selection_source_impl *impl; + + // source metadata + struct wl_array mime_types; + + struct { + struct wl_signal destroy; + } events; + + void *data; +}; + +void wlr_primary_selection_source_init( + struct wlr_primary_selection_source *source, + const struct wlr_primary_selection_source_impl *impl); +void wlr_primary_selection_source_destroy( + struct wlr_primary_selection_source *source); +void wlr_primary_selection_source_send( + struct wlr_primary_selection_source *source, const char *mime_type, + int fd); + +/** + * Request setting the primary selection. If `client` is not null, then the + * serial will be checked against the set of serials sent to the client on that + * seat. + */ +void wlr_seat_request_set_primary_selection(struct wlr_seat *seat, + struct wlr_seat_client *client, + struct wlr_primary_selection_source *source, uint32_t serial); +/** + * Sets the current primary selection for the seat. NULL can be provided to + * clear it. This removes the previous one if there was any. In case the + * selection doesn't come from a client, wl_display_next_serial() can be used to + * generate a serial. + */ +void wlr_seat_set_primary_selection(struct wlr_seat *seat, + struct wlr_primary_selection_source *source, uint32_t serial); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_primary_selection_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_primary_selection_v1.h new file mode 100644 index 0000000000..7369cfc917 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_primary_selection_v1.h @@ -0,0 +1,67 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_PRIMARY_SELECTION_V1_H +#define WLR_TYPES_WLR_PRIMARY_SELECTION_V1_H + +#include +#include +#include + +struct wlr_primary_selection_v1_device_manager { + struct wl_global *global; + struct wl_list devices; // wlr_primary_selection_v1_device.link + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +/** + * A device is a per-seat object used to set and get the current selection. + */ +struct wlr_primary_selection_v1_device { + struct wlr_primary_selection_v1_device_manager *manager; + struct wlr_seat *seat; + struct wl_list link; // wlr_primary_selection_v1_device_manager.devices + struct wl_list resources; // wl_resource_get_link() + + struct wl_list offers; // wl_resource_get_link() + + void *data; + + struct { + struct wl_listener seat_destroy; + struct wl_listener seat_focus_change; + struct wl_listener seat_set_primary_selection; + } WLR_PRIVATE; +}; + +struct wlr_primary_selection_v1_device_manager * + wlr_primary_selection_v1_device_manager_create(struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_primary_selection_v1_device_manager_destroy( + struct wlr_primary_selection_v1_device_manager *manager, bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_relative_pointer_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_relative_pointer_v1.h new file mode 100644 index 0000000000..464d2e284a --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_relative_pointer_v1.h @@ -0,0 +1,96 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_RELATIVE_POINTER_V1_H +#define WLR_TYPES_WLR_RELATIVE_POINTER_V1_H + +#include +#include + +/** + * This protocol specifies a set of interfaces used for making clients able to + * receive relative pointer events not obstructed by barriers (such as the + * monitor edge or pointer constraints). + */ + +/** + * A global interface used for getting the relative pointer object for a given + * pointer. + */ +struct wlr_relative_pointer_manager_v1 { + struct wl_global *global; + struct wl_list relative_pointers; // wlr_relative_pointer_v1.link + + struct { + struct wl_signal destroy; + struct wl_signal new_relative_pointer; // struct wlr_relative_pointer_v1 + } events; + + void *data; + + struct { + struct wl_listener display_destroy_listener; + } WLR_PRIVATE; +}; + +/** + * A wp_relative_pointer object is an extension to the wl_pointer interface + * used for emitting relative pointer events. It shares the same focus as + * wl_pointer objects of the same seat and will only emit events when it has + * focus. + */ +struct wlr_relative_pointer_v1 { + struct wl_resource *resource; + struct wl_resource *pointer_resource; + struct wlr_seat *seat; + struct wl_list link; // wlr_relative_pointer_manager_v1.relative_pointers + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener seat_destroy; + struct wl_listener pointer_destroy; + } WLR_PRIVATE; +}; + +struct wlr_relative_pointer_manager_v1 *wlr_relative_pointer_manager_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_relative_pointer_manager_v1_destroy(struct wlr_relative_pointer_manager_v1 *manager, + bool destroy_global_safe); + +/** + * Send a relative motion event to the seat. Time is given in microseconds + * (unlike wl_pointer which uses milliseconds). + */ +void wlr_relative_pointer_manager_v1_send_relative_motion( + struct wlr_relative_pointer_manager_v1 *manager, struct wlr_seat *seat, + uint64_t time_usec, double dx, double dy, + double dx_unaccel, double dy_unaccel); + +/** + * Get a relative pointer from its resource. Returns NULL if inert. + */ +struct wlr_relative_pointer_v1 *wlr_relative_pointer_v1_from_resource( + struct wl_resource *resource); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_scene.h b/3rdparty/wlroots/include/wlr/types/wlr_scene.h new file mode 100644 index 0000000000..6c627b1f9d --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_scene.h @@ -0,0 +1,742 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_SCENE_H +#define WLR_TYPES_WLR_SCENE_H + +/** + * The scene-graph API provides a declarative way to display surfaces. The + * compositor creates a scene, adds surfaces, then renders the scene on + * outputs. + * + * The scene-graph API only supports basic 2D composition operations (like the + * KMS API or the Wayland protocol does). For anything more complicated, + * compositors need to implement custom rendering logic. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +struct wlr_output; +struct wlr_output_layout; +struct wlr_output_layout_output; +struct wlr_xdg_surface; +struct wlr_layer_surface_v1; +struct wlr_drag_icon; +struct wlr_surface; + +struct wlr_scene_node; +struct wlr_scene_buffer; +struct wlr_scene_output_layout; + +struct wlr_presentation; +struct wlr_linux_dmabuf_v1; +struct wlr_gamma_control_manager_v1; +struct wlr_color_manager_v1; +struct wlr_output_state; + +typedef bool (*wlr_scene_buffer_point_accepts_input_func_t)( + struct wlr_scene_buffer *buffer, double *sx, double *sy); + +typedef void (*wlr_scene_buffer_iterator_func_t)( + struct wlr_scene_buffer *buffer, int sx, int sy, void *user_data); + +enum wlr_scene_node_type { + WLR_SCENE_NODE_TREE, + WLR_SCENE_NODE_RECT, + WLR_SCENE_NODE_BUFFER, +}; + +/** A node is an object in the scene. */ +struct wlr_scene_node { + enum wlr_scene_node_type type; + struct wlr_scene_tree *parent; + + struct wl_list link; // wlr_scene_tree.children + + bool enabled; + int x, y; // relative to parent + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct wlr_addon_set addons; + + struct { + pixman_region32_t visible; + } WLR_PRIVATE; +}; + +enum wlr_scene_debug_damage_option { + WLR_SCENE_DEBUG_DAMAGE_NONE, + WLR_SCENE_DEBUG_DAMAGE_RERENDER, + WLR_SCENE_DEBUG_DAMAGE_HIGHLIGHT +}; + +/** A sub-tree in the scene-graph. */ +struct wlr_scene_tree { + struct wlr_scene_node node; + + struct wl_list children; // wlr_scene_node.link +}; + +/** The root scene-graph node. */ +struct wlr_scene { + struct wlr_scene_tree tree; + + struct wl_list outputs; // wlr_scene_output.link + + // May be NULL + struct wlr_linux_dmabuf_v1 *linux_dmabuf_v1; + struct wlr_gamma_control_manager_v1 *gamma_control_manager_v1; + struct wlr_color_manager_v1 *color_manager_v1; + + bool restack_xwayland_surfaces; + + struct { + struct wl_listener linux_dmabuf_v1_destroy; + struct wl_listener gamma_control_manager_v1_destroy; + struct wl_listener gamma_control_manager_v1_set_gamma; + struct wl_listener color_manager_v1_destroy; + + enum wlr_scene_debug_damage_option debug_damage_option; + bool direct_scanout; + bool calculate_visibility; + bool highlight_transparent_region; + } WLR_PRIVATE; +}; + +/** A scene-graph node displaying a single surface. */ +struct wlr_scene_surface { + struct wlr_scene_buffer *buffer; + struct wlr_surface *surface; + + struct { + struct wlr_box clip; + + struct wlr_addon addon; + + struct wl_listener outputs_update; + struct wl_listener output_sample; + struct wl_listener frame_done; + struct wl_listener surface_destroy; + struct wl_listener surface_commit; + } WLR_PRIVATE; +}; + +/** A scene-graph node displaying a solid-colored rectangle */ +struct wlr_scene_rect { + struct wlr_scene_node node; + int width, height; + float color[4]; +}; + +struct wlr_scene_outputs_update_event { + struct wlr_scene_output **active; + size_t size; +}; + +struct wlr_scene_output_sample_event { + struct wlr_scene_output *output; + bool direct_scanout; + struct wlr_drm_syncobj_timeline *release_timeline; + uint64_t release_point; +}; + +struct wlr_scene_frame_done_event { + struct wlr_scene_output *output; + struct timespec when; +}; + +/** A scene-graph node displaying a buffer */ +struct wlr_scene_buffer { + struct wlr_scene_node node; + + // May be NULL + struct wlr_buffer *buffer; + + struct { + struct wl_signal outputs_update; // struct wlr_scene_outputs_update_event + struct wl_signal output_enter; // struct wlr_scene_output + struct wl_signal output_leave; // struct wlr_scene_output + struct wl_signal output_sample; // struct wlr_scene_output_sample_event + struct wl_signal frame_done; // struct wlr_scene_frame_done_event + } events; + + // May be NULL + wlr_scene_buffer_point_accepts_input_func_t point_accepts_input; + + /** + * The output that the largest area of this buffer is displayed on. + * This may be NULL if the buffer is not currently displayed on any + * outputs. + */ + struct wlr_scene_output *primary_output; + + float opacity; + enum wlr_scale_filter_mode filter_mode; + struct wlr_fbox src_box; + int dst_width, dst_height; + enum wl_output_transform transform; + pixman_region32_t opaque_region; + enum wlr_color_transfer_function transfer_function; + enum wlr_color_named_primaries primaries; + enum wlr_color_encoding color_encoding; + enum wlr_color_range color_range; + + struct { + uint64_t active_outputs; + struct wlr_texture *texture; + struct wlr_linux_dmabuf_feedback_v1_init_options prev_feedback_options; + + bool own_buffer; + int buffer_width, buffer_height; + bool buffer_is_opaque; + + struct wlr_drm_syncobj_timeline *wait_timeline; + uint64_t wait_point; + + struct wl_listener buffer_release; + struct wl_listener renderer_destroy; + + // True if the underlying buffer is a wlr_single_pixel_buffer_v1 + bool is_single_pixel_buffer; + // If is_single_pixel_buffer is set, contains the color of the buffer + // as {R, G, B, A} where the max value of each component is UINT32_MAX + uint32_t single_pixel_buffer_color[4]; + } WLR_PRIVATE; +}; + +/** A viewport for an output in the scene-graph */ +struct wlr_scene_output { + struct wlr_output *output; + struct wl_list link; // wlr_scene.outputs + struct wlr_scene *scene; + struct wlr_addon addon; + + struct wlr_damage_ring damage_ring; + + int x, y; + + struct { + struct wl_signal destroy; + } events; + + struct { + pixman_region32_t pending_commit_damage; + + uint8_t index; + + /** + * When scanout is applicable, we increment this every time a frame is rendered until + * DMABUF_FEEDBACK_DEBOUNCE_FRAMES is hit to debounce the scanout dmabuf feedback. Likewise, + * when scanout is no longer applicable, we decrement this until zero is hit to debounce + * composition dmabuf feedback. + */ + uint8_t dmabuf_feedback_debounce; + bool prev_scanout; + + bool gamma_lut_changed; + struct wlr_gamma_control_v1 *gamma_lut; + struct wlr_color_transform *gamma_lut_color_transform; + + struct wlr_color_transform *prev_gamma_lut_color_transform; + struct wlr_color_transform *prev_supplied_color_transform; + struct wlr_color_transform *combined_color_transform; + + struct wl_listener output_commit; + struct wl_listener output_damage; + struct wl_listener output_needs_frame; + + struct wl_list damage_highlight_regions; + + struct wl_array render_list; + + struct wlr_drm_syncobj_timeline *in_timeline; + uint64_t in_point; + struct wlr_drm_syncobj_timeline *out_timeline; + uint64_t out_point; + } WLR_PRIVATE; +}; + +struct wlr_scene_timer { + int64_t pre_render_duration; + struct wlr_render_timer *render_timer; +}; + +/** A layer shell scene helper */ +struct wlr_scene_layer_surface_v1 { + struct wlr_scene_tree *tree; + struct wlr_layer_surface_v1 *layer_surface; + + struct { + struct wl_listener tree_destroy; + struct wl_listener layer_surface_destroy; + struct wl_listener layer_surface_map; + struct wl_listener layer_surface_unmap; + } WLR_PRIVATE; +}; + +/** + * Immediately destroy the scene-graph node. + */ +void wlr_scene_node_destroy(struct wlr_scene_node *node); +/** + * Enable or disable this node. If a node is disabled, all of its children are + * implicitly disabled as well. + */ +void wlr_scene_node_set_enabled(struct wlr_scene_node *node, bool enabled); +/** + * Set the position of the node relative to its parent. + */ +void wlr_scene_node_set_position(struct wlr_scene_node *node, int x, int y); +/** + * Move the node right above the specified sibling. + * Asserts that node and sibling are distinct and share the same parent. + */ +void wlr_scene_node_place_above(struct wlr_scene_node *node, + struct wlr_scene_node *sibling); +/** + * Move the node right below the specified sibling. + * Asserts that node and sibling are distinct and share the same parent. + */ +void wlr_scene_node_place_below(struct wlr_scene_node *node, + struct wlr_scene_node *sibling); +/** + * Move the node above all of its sibling nodes. + */ +void wlr_scene_node_raise_to_top(struct wlr_scene_node *node); +/** + * Move the node below all of its sibling nodes. + */ +void wlr_scene_node_lower_to_bottom(struct wlr_scene_node *node); +/** + * Move the node to another location in the tree. + */ +void wlr_scene_node_reparent(struct wlr_scene_node *node, + struct wlr_scene_tree *new_parent); +/** + * Get the node's layout-local coordinates. + * + * True is returned if the node and all of its ancestors are enabled. + */ +bool wlr_scene_node_coords(struct wlr_scene_node *node, int *lx, int *ly); +/** + * Call `iterator` on each buffer in the scene-graph, with the buffer's + * position in layout coordinates. The function is called from root to leaves + * (in rendering order). + */ +void wlr_scene_node_for_each_buffer(struct wlr_scene_node *node, + wlr_scene_buffer_iterator_func_t iterator, void *user_data); +/** + * Find the topmost node in this scene-graph that contains the point at the + * given layout-local coordinates. (For surface nodes, this means accepting + * input events at that point.) Returns the node and coordinates relative to the + * returned node, or NULL if no node is found at that location. + */ +struct wlr_scene_node *wlr_scene_node_at(struct wlr_scene_node *node, + double lx, double ly, double *nx, double *ny); + +/** + * Create a new scene-graph. + * + * The graph is also a struct wlr_scene_node. Associated resources can be + * destroyed through wlr_scene_node_destroy(). + */ +struct wlr_scene *wlr_scene_create(void); + +/** + * Handles linux_dmabuf_v1 feedback for all surfaces in the scene. + * + * Asserts that a struct wlr_linux_dmabuf_v1 hasn't already been set for the scene. + */ +void wlr_scene_set_linux_dmabuf_v1(struct wlr_scene *scene, + struct wlr_linux_dmabuf_v1 *linux_dmabuf_v1); + +/** + * Handles gamma_control_v1 for all outputs in the scene. + * + * Asserts that a struct wlr_gamma_control_manager_v1 hasn't already been set + * for the scene. + */ +void wlr_scene_set_gamma_control_manager_v1(struct wlr_scene *scene, + struct wlr_gamma_control_manager_v1 *gamma_control); + +/** + * Handles color_management_v1 feedback for all surfaces in the scene. + * + * Asserts that a struct wlr_color_manager_v1 hasn't already been set for the scene. + */ +void wlr_scene_set_color_manager_v1(struct wlr_scene *scene, struct wlr_color_manager_v1 *manager); + +/** + * Add a node displaying nothing but its children. + */ +struct wlr_scene_tree *wlr_scene_tree_create(struct wlr_scene_tree *parent); + +/** + * Add a node displaying a single surface to the scene-graph. + * + * The child sub-surfaces are ignored. See wlr_scene_subsurface_tree_create() + * + * Note that this helper does multiple things on behalf of the compositor. Some + * of these include protocol implementations where compositors just need to enable + * the protocols: + * - wp_viewporter + * - wp_presentation_time + * - wp_fractional_scale_v1 + * - wp_alpha_modifier_v1 + * - wp_linux_drm_syncobj_v1 + * - zwp_linux_dmabuf_v1 presentation feedback with wlr_scene_set_linux_dmabuf_v1() + * + * This helper will also transparently: + * - Send preferred buffer scale¹ + * - Send preferred buffer transform¹ + * - Restack xwayland surfaces. See wlr_xwayland_surface_restack()² + * - Send output enter/leave events. + * + * ¹ Note that scale and transform sent to the surface will be based on the output + * which has the largest visible surface area. Intelligent visibility calculations + * influence this. + * ² xwayland stacking order is undefined when the xwayland surfaces do not + * intersect. + */ +struct wlr_scene_surface *wlr_scene_surface_create(struct wlr_scene_tree *parent, + struct wlr_surface *surface); + +/** + * If this node represents a wlr_scene_buffer, that buffer will be returned. It + * is not legal to feed a node that does not represent a wlr_scene_buffer. + */ +struct wlr_scene_buffer *wlr_scene_buffer_from_node(struct wlr_scene_node *node); + +/** + * If this node represents a wlr_scene_tree, that tree will be returned. It + * is not legal to feed a node that does not represent a wlr_scene_tree. + */ +struct wlr_scene_tree *wlr_scene_tree_from_node(struct wlr_scene_node *node); + +/** + * If this node represents a wlr_scene_rect, that rect will be returned. It + * is not legal to feed a node that does not represent a wlr_scene_rect. + */ +struct wlr_scene_rect *wlr_scene_rect_from_node(struct wlr_scene_node *node); + +/** + * If this buffer is backed by a surface, then the struct wlr_scene_surface is + * returned. If not, NULL will be returned. + */ +struct wlr_scene_surface *wlr_scene_surface_try_from_buffer( + struct wlr_scene_buffer *scene_buffer); + +/** + * Call wlr_surface_send_frame_done() if the surface is visible. + */ +void wlr_scene_surface_send_frame_done(struct wlr_scene_surface *scene_surface, + const struct timespec *when); + +/** + * Add a node displaying a solid-colored rectangle to the scene-graph. + * + * The color argument must be a premultiplied color value. + */ +struct wlr_scene_rect *wlr_scene_rect_create(struct wlr_scene_tree *parent, + int width, int height, const float color[static 4]); + +/** + * Change the width and height of an existing rectangle node. + */ +void wlr_scene_rect_set_size(struct wlr_scene_rect *rect, int width, int height); + +/** + * Change the color of an existing rectangle node. + * + * The color argument must be a premultiplied color value. + */ +void wlr_scene_rect_set_color(struct wlr_scene_rect *rect, const float color[static 4]); + +/** + * Add a node displaying a buffer to the scene-graph. + * + * If the buffer is NULL, this node will not be displayed. + */ +struct wlr_scene_buffer *wlr_scene_buffer_create(struct wlr_scene_tree *parent, + struct wlr_buffer *buffer); + +/** + * Sets the buffer's backing buffer. + * + * If the buffer is NULL, the buffer node will not be displayed. + */ +void wlr_scene_buffer_set_buffer(struct wlr_scene_buffer *scene_buffer, + struct wlr_buffer *buffer); + +/** + * Sets the buffer's backing buffer with a custom damage region. + * + * The damage region is in buffer-local coordinates. If the region is NULL, + * the whole buffer node will be damaged. + */ +void wlr_scene_buffer_set_buffer_with_damage(struct wlr_scene_buffer *scene_buffer, + struct wlr_buffer *buffer, const pixman_region32_t *region); + +/** + * Options for wlr_scene_buffer_set_buffer_with_options(). + */ +struct wlr_scene_buffer_set_buffer_options { + // The damage region is in buffer-local coordinates. If the region is NULL, + // the whole buffer node will be damaged. + const pixman_region32_t *damage; + + // Wait for a timeline synchronization point before reading from the buffer. + struct wlr_drm_syncobj_timeline *wait_timeline; + uint64_t wait_point; +}; + +/** + * Sets the buffer's backing buffer. + * + * If the buffer is NULL, the buffer node will not be displayed. If options is + * NULL, empty options are used. + */ +void wlr_scene_buffer_set_buffer_with_options(struct wlr_scene_buffer *scene_buffer, + struct wlr_buffer *buffer, const struct wlr_scene_buffer_set_buffer_options *options); + +/** + * Sets the buffer's opaque region. This is an optimization hint used to + * determine if buffers which reside under this one need to be rendered or not. + */ +void wlr_scene_buffer_set_opaque_region(struct wlr_scene_buffer *scene_buffer, + const pixman_region32_t *region); + +/** + * Set the source rectangle describing the region of the buffer which will be + * sampled to render this node. This allows cropping the buffer. + * + * If NULL, the whole buffer is sampled. By default, the source box is NULL. + */ +void wlr_scene_buffer_set_source_box(struct wlr_scene_buffer *scene_buffer, + const struct wlr_fbox *box); + +/** + * Set the destination size describing the region of the scene-graph the buffer + * will be painted onto. This allows scaling the buffer. + * + * If zero, the destination size will be the buffer size. By default, the + * destination size is zero. + */ +void wlr_scene_buffer_set_dest_size(struct wlr_scene_buffer *scene_buffer, + int width, int height); + +/** + * Set a transform which will be applied to the buffer. + */ +void wlr_scene_buffer_set_transform(struct wlr_scene_buffer *scene_buffer, + enum wl_output_transform transform); + +/** +* Sets the opacity of this buffer +*/ +void wlr_scene_buffer_set_opacity(struct wlr_scene_buffer *scene_buffer, + float opacity); + +/** +* Sets the filter mode to use when scaling the buffer +*/ +void wlr_scene_buffer_set_filter_mode(struct wlr_scene_buffer *scene_buffer, + enum wlr_scale_filter_mode filter_mode); + +void wlr_scene_buffer_set_transfer_function(struct wlr_scene_buffer *scene_buffer, + enum wlr_color_transfer_function transfer_function); + +void wlr_scene_buffer_set_primaries(struct wlr_scene_buffer *scene_buffer, + enum wlr_color_named_primaries primaries); + +void wlr_scene_buffer_set_color_encoding(struct wlr_scene_buffer *scene_buffer, + enum wlr_color_encoding encoding); + +void wlr_scene_buffer_set_color_range(struct wlr_scene_buffer *scene_buffer, + enum wlr_color_range range); + +/** + * Calls the buffer's frame_done signal. + */ +void wlr_scene_buffer_send_frame_done(struct wlr_scene_buffer *scene_buffer, + struct wlr_scene_frame_done_event *event); + +/** + * Add a viewport for the specified output to the scene-graph. + * + * An output can only be added once to the scene-graph. + */ +struct wlr_scene_output *wlr_scene_output_create(struct wlr_scene *scene, + struct wlr_output *output); +/** + * Destroy a scene-graph output. + */ +void wlr_scene_output_destroy(struct wlr_scene_output *scene_output); +/** + * Set the output's position in the scene-graph. + */ +void wlr_scene_output_set_position(struct wlr_scene_output *scene_output, + int lx, int ly); + +struct wlr_scene_output_state_options { + struct wlr_scene_timer *timer; + + /** + * Color transform to apply before the output's color transform. Cannot be + * used when the output has a non-NULL image description set. + */ + struct wlr_color_transform *color_transform; + + /** + * Allows use of a custom swapchain. This can be useful when trying out an + * output configuration. The swapchain dimensions must match the respective + * wlr_output_state or output size if not specified. + */ + struct wlr_swapchain *swapchain; +}; + +/** + * Returns true if scene wants to render a new frame. False, if no new frame + * is needed and an output commit can be skipped for the current frame. + */ +bool wlr_scene_output_needs_frame(struct wlr_scene_output *scene_output); + +/** + * Render and commit an output. + */ +bool wlr_scene_output_commit(struct wlr_scene_output *scene_output, + const struct wlr_scene_output_state_options *options); + +/** + * Render and populate given output state. + */ +bool wlr_scene_output_build_state(struct wlr_scene_output *scene_output, + struct wlr_output_state *state, const struct wlr_scene_output_state_options *options); + +/** + * Retrieve the duration in nanoseconds between the last wlr_scene_output_commit() call and the end + * of its operations, including those on the GPU that may have finished after the call returned. + * + * Returns -1 if the duration is unavailable. + */ +int64_t wlr_scene_timer_get_duration_ns(struct wlr_scene_timer *timer); +void wlr_scene_timer_finish(struct wlr_scene_timer *timer); + +/** + * Call wlr_surface_send_frame_done() on all surfaces in the scene rendered by + * wlr_scene_output_commit() for which wlr_scene_surface.primary_output + * matches the given scene_output. + */ +void wlr_scene_output_send_frame_done(struct wlr_scene_output *scene_output, + struct timespec *now); +/** + * Call `iterator` on each buffer in the scene-graph visible on the output, + * with the buffer's position in layout coordinates. The function is called + * from root to leaves (in rendering order). + */ +void wlr_scene_output_for_each_buffer(struct wlr_scene_output *scene_output, + wlr_scene_buffer_iterator_func_t iterator, void *user_data); +/** + * Get a scene-graph output from a struct wlr_output. + * + * If the output hasn't been added to the scene-graph, returns NULL. + */ +struct wlr_scene_output *wlr_scene_get_scene_output(struct wlr_scene *scene, + struct wlr_output *output); + +/** + * Attach an output layout to a scene. + * + * The resulting scene output layout allows to synchronize the positions of scene + * outputs with the positions of corresponding layout outputs. + * + * It is automatically destroyed when the scene or the output layout is destroyed. + */ +struct wlr_scene_output_layout *wlr_scene_attach_output_layout(struct wlr_scene *scene, + struct wlr_output_layout *output_layout); + +/** + * Add an output to the scene output layout. + * + * When the layout output is repositioned, the scene output will be repositioned + * accordingly. + */ +void wlr_scene_output_layout_add_output(struct wlr_scene_output_layout *sol, + struct wlr_output_layout_output *lo, struct wlr_scene_output *so); + +/** + * Add a node displaying a surface and all of its sub-surfaces to the + * scene-graph. + */ +struct wlr_scene_tree *wlr_scene_subsurface_tree_create( + struct wlr_scene_tree *parent, struct wlr_surface *surface); + +/** + * Sets a cropping region for any subsurface trees that are children of this + * scene node. The clip coordinate space will be that of the root surface of + * the subsurface tree. + * + * A NULL or empty clip will disable clipping + */ +void wlr_scene_subsurface_tree_set_clip(struct wlr_scene_node *node, + const struct wlr_box *clip); + +/** + * Add a node displaying an xdg_surface and all of its sub-surfaces to the + * scene-graph. + * + * The origin of the returned scene-graph node will match the top-left corner + * of the xdg_surface window geometry. + */ +struct wlr_scene_tree *wlr_scene_xdg_surface_create( + struct wlr_scene_tree *parent, struct wlr_xdg_surface *xdg_surface); + +/** + * Add a node displaying a layer_surface_v1 and all of its sub-surfaces to the + * scene-graph. + * + * The origin of the returned scene-graph node will match the top-left corner + * of the layer surface. + */ +struct wlr_scene_layer_surface_v1 *wlr_scene_layer_surface_v1_create( + struct wlr_scene_tree *parent, struct wlr_layer_surface_v1 *layer_surface); + +/** + * Configure a layer_surface_v1, position its scene node in accordance to its + * current state, and update the remaining usable area. + * + * full_area represents the entire area that may be used by the layer surface + * if its exclusive_zone is -1, and is usually the output dimensions. + * usable_area represents what remains of full_area that can be used if + * exclusive_zone is >= 0. usable_area is updated if the surface has a positive + * exclusive_zone, so that it can be used for the next layer surface. + */ +void wlr_scene_layer_surface_v1_configure( + struct wlr_scene_layer_surface_v1 *scene_layer_surface, + const struct wlr_box *full_area, struct wlr_box *usable_area); + +/** + * Add a node displaying a drag icon and all its sub-surfaces to the + * scene-graph. + */ +struct wlr_scene_tree *wlr_scene_drag_icon_create( + struct wlr_scene_tree *parent, struct wlr_drag_icon *drag_icon); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_screencopy_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_screencopy_v1.h new file mode 100644 index 0000000000..40611e9d99 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_screencopy_v1.h @@ -0,0 +1,87 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_SCREENCOPY_V1_H +#define WLR_TYPES_WLR_SCREENCOPY_V1_H + +#include +#include +#include +#include + +/** + * Deprecated: this protocol is deprecated and superseded by ext-image-copy-capture-v1. + * The implementation will be dropped in a future wlroots version. + * + * Consider using `wlr_ext_image_capture_source_v1` instead. + */ + +struct wlr_screencopy_manager_v1 { + struct wl_global *global; + struct wl_list frames; // wlr_screencopy_frame_v1.link + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_screencopy_v1_client { + int ref; + struct wlr_screencopy_manager_v1 *manager; + struct wl_list damages; +}; + +struct wlr_screencopy_frame_v1 { + struct wl_resource *resource; + struct wlr_screencopy_v1_client *client; + struct wl_list link; // wlr_screencopy_manager_v1.frames + + uint32_t shm_format, dmabuf_format; // DRM format codes + struct wlr_box box; + int shm_stride; + + bool overlay_cursor, cursor_locked; + + bool with_damage; + + enum wlr_buffer_cap buffer_cap; + struct wlr_buffer *buffer; + + struct wlr_output *output; + + void *data; + + struct { + struct wl_listener output_commit; + struct wl_listener output_destroy; + } WLR_PRIVATE; +}; + +struct wlr_screencopy_manager_v1 *wlr_screencopy_manager_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_screencopy_manager_v1_destroy(struct wlr_screencopy_manager_v1 *manager, + bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_seat.h b/3rdparty/wlroots/include/wlr/types/wlr_seat.h new file mode 100644 index 0000000000..670b4458bd --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_seat.h @@ -0,0 +1,769 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_SEAT_H +#define WLR_TYPES_WLR_SEAT_H + +#include +#include +#include +#include +#include + +struct wlr_surface; + +#define WLR_SERIAL_RINGSET_SIZE 128 + +struct wlr_serial_range { + uint32_t min_incl; + uint32_t max_incl; +}; +struct wlr_serial_ringset { + struct wlr_serial_range data[WLR_SERIAL_RINGSET_SIZE]; + int end; + int count; +}; + +/** + * Contains state for a single client's bound wl_seat resource and can be used + * to issue input events to that client. The lifetime of these objects is + * managed by struct wlr_seat; some may be NULL. + */ +struct wlr_seat_client { + struct wl_client *client; + struct wlr_seat *seat; + struct wl_list link; + + // lists of wl_resource + struct wl_list resources; + struct wl_list pointers; + struct wl_list keyboards; + struct wl_list touches; + struct wl_list data_devices; + + struct { + struct wl_signal destroy; + } events; + + // set of serials which were sent to the client on this seat + // for use by wlr_seat_client_{next_serial,validate_event_serial} + struct wlr_serial_ringset serials; + bool needs_touch_frame; + + // When the client doesn't support high-resolution scroll, accumulate deltas + // until we can notify a discrete event. + // Some mice have a free spinning wheel, making possible to lock the wheel + // when the accumulator value is not 0. To avoid synchronization issues + // between the mouse wheel and the accumulators, store the last delta and + // when the scroll direction changes, reset the accumulator. + // Indexed by wlr_axis_orientation. + struct { + int32_t acc_discrete[2]; + int32_t last_discrete[2]; + double acc_axis[2]; + } value120; +}; + +struct wlr_touch_point { + int32_t touch_id; + struct wlr_surface *surface; // may be NULL if destroyed + struct wlr_seat_client *client; + + struct wlr_surface *focus_surface; + struct wlr_seat_client *focus_client; + double sx, sy; + + struct { + struct wl_signal destroy; + } events; + + struct wl_list link; + + struct { + struct wl_listener surface_destroy; + struct wl_listener focus_surface_destroy; + struct wl_listener client_destroy; + } WLR_PRIVATE; +}; + +struct wlr_seat_pointer_grab; + +struct wlr_pointer_grab_interface { + void (*enter)(struct wlr_seat_pointer_grab *grab, + struct wlr_surface *surface, double sx, double sy); + void (*clear_focus)(struct wlr_seat_pointer_grab *grab); + void (*motion)(struct wlr_seat_pointer_grab *grab, uint32_t time_msec, + double sx, double sy); + uint32_t (*button)(struct wlr_seat_pointer_grab *grab, uint32_t time_msec, + uint32_t button, enum wl_pointer_button_state state); + void (*axis)(struct wlr_seat_pointer_grab *grab, uint32_t time_msec, + enum wl_pointer_axis orientation, double value, + int32_t value_discrete, enum wl_pointer_axis_source source, + enum wl_pointer_axis_relative_direction relative_direction); + void (*frame)(struct wlr_seat_pointer_grab *grab); + void (*cancel)(struct wlr_seat_pointer_grab *grab); +}; + +struct wlr_seat_keyboard_grab; + +struct wlr_keyboard_grab_interface { + void (*enter)(struct wlr_seat_keyboard_grab *grab, + struct wlr_surface *surface, const uint32_t keycodes[], + size_t num_keycodes, const struct wlr_keyboard_modifiers *modifiers); + void (*clear_focus)(struct wlr_seat_keyboard_grab *grab); + void (*key)(struct wlr_seat_keyboard_grab *grab, uint32_t time_msec, + uint32_t key, uint32_t state); + void (*modifiers)(struct wlr_seat_keyboard_grab *grab, + const struct wlr_keyboard_modifiers *modifiers); + void (*cancel)(struct wlr_seat_keyboard_grab *grab); +}; + +struct wlr_seat_touch_grab; + +struct wlr_touch_grab_interface { + uint32_t (*down)(struct wlr_seat_touch_grab *grab, uint32_t time_msec, + struct wlr_touch_point *point); + uint32_t (*up)(struct wlr_seat_touch_grab *grab, uint32_t time_msec, + struct wlr_touch_point *point); + void (*motion)(struct wlr_seat_touch_grab *grab, uint32_t time_msec, + struct wlr_touch_point *point); + void (*enter)(struct wlr_seat_touch_grab *grab, uint32_t time_msec, + struct wlr_touch_point *point); + void (*frame)(struct wlr_seat_touch_grab *grab); + // Cancel grab + void (*cancel)(struct wlr_seat_touch_grab *grab); + // Send wl_touch.cancel + void (*wl_cancel)(struct wlr_seat_touch_grab *grab, + struct wlr_seat_client *seat_client); + void (*clear_focus)(struct wlr_seat_touch_grab *grab, uint32_t time_msec, + struct wlr_touch_point *point); +}; + +/** + * Passed to wlr_seat_touch_start_grab() to start a grab of the touch device. + * The grabber is responsible for handling touch events for the seat. + */ +struct wlr_seat_touch_grab { + const struct wlr_touch_grab_interface *interface; + struct wlr_seat *seat; + void *data; +}; + +/** + * Passed to wlr_seat_keyboard_start_grab() to start a grab of the keyboard. + * The grabber is responsible for handling keyboard events for the seat. + */ +struct wlr_seat_keyboard_grab { + const struct wlr_keyboard_grab_interface *interface; + struct wlr_seat *seat; + void *data; +}; + +/** + * Passed to wlr_seat_pointer_start_grab() to start a grab of the pointer. The + * grabber is responsible for handling pointer events for the seat. + */ +struct wlr_seat_pointer_grab { + const struct wlr_pointer_grab_interface *interface; + struct wlr_seat *seat; + void *data; +}; + +struct wlr_seat_pointer_button { + uint32_t button; + size_t n_pressed; +}; + +struct wlr_seat_pointer_state { + struct wlr_seat *seat; + struct wlr_seat_client *focused_client; + struct wlr_surface *focused_surface; + double sx, sy; + + struct wlr_seat_pointer_grab *grab; + struct wlr_seat_pointer_grab *default_grab; + + bool sent_axis_source; + enum wl_pointer_axis_source cached_axis_source; + + struct wlr_seat_pointer_button buttons[WLR_POINTER_BUTTONS_CAP]; + size_t button_count; + + uint32_t grab_button; + uint32_t grab_serial; + uint32_t grab_time; + + + struct { + struct wl_signal focus_change; // struct wlr_seat_pointer_focus_change_event + } events; + + struct { + struct wl_listener surface_destroy; + } WLR_PRIVATE; +}; + +struct wlr_seat_keyboard_state { + struct wlr_seat *seat; + struct wlr_keyboard *keyboard; + + struct wlr_seat_client *focused_client; + struct wlr_surface *focused_surface; + + struct wlr_seat_keyboard_grab *grab; + struct wlr_seat_keyboard_grab *default_grab; + + struct { + struct wl_signal focus_change; // struct wlr_seat_keyboard_focus_change_event + } events; + + struct { + struct wl_listener keyboard_destroy; + struct wl_listener keyboard_keymap; + struct wl_listener keyboard_repeat_info; + + struct wl_listener surface_destroy; + } WLR_PRIVATE; +}; + +struct wlr_seat_touch_state { + struct wlr_seat *seat; + struct wl_list touch_points; // wlr_touch_point.link + + uint32_t grab_serial; + uint32_t grab_id; + + struct wlr_seat_touch_grab *grab; + struct wlr_seat_touch_grab *default_grab; +}; + +struct wlr_primary_selection_source; + +struct wlr_seat { + struct wl_global *global; + struct wl_display *display; + struct wl_list clients; + + char *name; + uint32_t capabilities; + uint32_t accumulated_capabilities; + + struct wlr_data_source *selection_source; + uint32_t selection_serial; + struct wl_list selection_offers; // wlr_data_offer.link + + struct wlr_primary_selection_source *primary_selection_source; + uint32_t primary_selection_serial; + + // `drag` goes away before `drag_source`, when the implicit grab ends + struct wlr_drag *drag; + struct wlr_data_source *drag_source; + uint32_t drag_serial; + struct wl_list drag_offers; // wlr_data_offer.link + + struct wlr_seat_pointer_state pointer_state; + struct wlr_seat_keyboard_state keyboard_state; + struct wlr_seat_touch_state touch_state; + + struct { + struct wl_signal pointer_grab_begin; + struct wl_signal pointer_grab_end; + + struct wl_signal keyboard_grab_begin; + struct wl_signal keyboard_grab_end; + + struct wl_signal touch_grab_begin; + struct wl_signal touch_grab_end; + + // struct wlr_seat_pointer_request_set_cursor_event + struct wl_signal request_set_cursor; + + // Called when an application _wants_ to set the selection (user copies some data). + // Compositors should listen to this event and call wlr_seat_set_selection() + // if they want to accept the client's request. + struct wl_signal request_set_selection; // struct wlr_seat_request_set_selection_event + // Called after the data source is set for the selection. + struct wl_signal set_selection; + + // Called when an application _wants_ to set the primary selection (user selects some data). + // Compositors should listen to this event and call wlr_seat_set_primary_selection() + // if they want to accept the client's request. + struct wl_signal request_set_primary_selection; // struct wlr_seat_request_set_primary_selection_event + // Called after the primary selection source object is set. + struct wl_signal set_primary_selection; + + // struct wlr_seat_request_start_drag_event + struct wl_signal request_start_drag; + struct wl_signal start_drag; // struct wlr_drag + + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + struct wl_listener selection_source_destroy; + struct wl_listener primary_selection_source_destroy; + struct wl_listener drag_source_destroy; + } WLR_PRIVATE; +}; + +struct wlr_seat_pointer_request_set_cursor_event { + struct wlr_seat_client *seat_client; + struct wlr_surface *surface; + uint32_t serial; + int32_t hotspot_x, hotspot_y; +}; + +struct wlr_seat_request_set_selection_event { + struct wlr_data_source *source; + uint32_t serial; +}; + +struct wlr_seat_request_set_primary_selection_event { + struct wlr_primary_selection_source *source; + uint32_t serial; +}; + +struct wlr_seat_request_start_drag_event { + struct wlr_drag *drag; + struct wlr_surface *origin; + uint32_t serial; +}; + +struct wlr_seat_pointer_focus_change_event { + struct wlr_seat *seat; + struct wlr_surface *old_surface, *new_surface; + double sx, sy; +}; + +struct wlr_seat_keyboard_focus_change_event { + struct wlr_seat *seat; + struct wlr_surface *old_surface, *new_surface; +}; + +/** + * Allocates a new struct wlr_seat and adds a wl_seat global to the display. + */ +struct wlr_seat *wlr_seat_create(struct wl_display *display, const char *name); +/** + * Destroys a seat, removes its wl_seat global and clears focus for all + * devices belonging to the seat. + */ +void wlr_seat_destroy(struct wlr_seat *wlr_seat); +/** + * Gets a struct wlr_seat_client for the specified client, or returns NULL if no + * client is bound for that client. + */ +struct wlr_seat_client *wlr_seat_client_for_wl_client(struct wlr_seat *wlr_seat, + struct wl_client *wl_client); +/** + * Updates the capabilities available on this seat. + * Will automatically send them to all clients. + */ +void wlr_seat_set_capabilities(struct wlr_seat *wlr_seat, + uint32_t capabilities); +/** + * Updates the name of this seat. + * Will automatically send it to all clients. + */ +void wlr_seat_set_name(struct wlr_seat *wlr_seat, const char *name); + +/** + * Whether or not the surface has pointer focus + */ +bool wlr_seat_pointer_surface_has_focus(struct wlr_seat *wlr_seat, + struct wlr_surface *surface); + +/** + * Send a pointer enter event to the given surface and consider it to be the + * focused surface for the pointer. This will send a leave event to the last + * surface that was entered. Coordinates for the enter event are surface-local. + * This function does not respect pointer grabs: you probably want + * wlr_seat_pointer_notify_enter() instead. + */ +void wlr_seat_pointer_enter(struct wlr_seat *wlr_seat, + struct wlr_surface *surface, double sx, double sy); + +/** + * Clear the focused surface for the pointer and leave all entered surfaces. + * This function does not respect pointer grabs: you probably want + * wlr_seat_pointer_notify_clear_focus() instead. + */ +void wlr_seat_pointer_clear_focus(struct wlr_seat *wlr_seat); + +/** + * Send a motion event to the surface with pointer focus. Coordinates for the + * motion event are surface-local. This function does not respect pointer grabs: + * you probably want wlr_seat_pointer_notify_motion() instead. + */ +void wlr_seat_pointer_send_motion(struct wlr_seat *wlr_seat, uint32_t time_msec, + double sx, double sy); + +/** + * Send a button event to the surface with pointer focus. Coordinates for the + * button event are surface-local. Returns the serial. This function does not + * respect pointer grabs: you probably want wlr_seat_pointer_notify_button() + * instead. + */ +uint32_t wlr_seat_pointer_send_button(struct wlr_seat *wlr_seat, + uint32_t time_msec, uint32_t button, enum wl_pointer_button_state state); + +/** + * Send an axis event to the surface with pointer focus. This function does not + * respect pointer grabs: you probably want wlr_seat_pointer_notify_axis() + * instead. + */ +void wlr_seat_pointer_send_axis(struct wlr_seat *wlr_seat, uint32_t time_msec, + enum wl_pointer_axis orientation, double value, + int32_t value_discrete, enum wl_pointer_axis_source source, + enum wl_pointer_axis_relative_direction relative_direction); + +/** + * Send a frame event to the surface with pointer focus. This function does not + * respect pointer grabs: you probably want wlr_seat_pointer_notify_frame() + * instead. + */ +void wlr_seat_pointer_send_frame(struct wlr_seat *wlr_seat); + +/** + * Notify the seat of a pointer enter event to the given surface and request it + * to be the focused surface for the pointer. Pass surface-local coordinates + * where the enter occurred. This will send a leave event to the currently- + * focused surface. Defers to any grab of the pointer. + */ +void wlr_seat_pointer_notify_enter(struct wlr_seat *wlr_seat, + struct wlr_surface *surface, double sx, double sy); + +/** + * Notify the seat of a pointer leave event to the currently-focused surface. + * Defers to any grab of the pointer. + */ +void wlr_seat_pointer_notify_clear_focus(struct wlr_seat *wlr_seat); + +/** + * Warp the pointer of this seat to the given surface-local coordinates, without + * generating motion events. + */ +void wlr_seat_pointer_warp(struct wlr_seat *wlr_seat, double sx, double sy); + +/** + * Notify the seat of motion over the given surface. Pass surface-local + * coordinates where the pointer motion occurred. Defers to any grab of the + * pointer. + */ +void wlr_seat_pointer_notify_motion(struct wlr_seat *wlr_seat, + uint32_t time_msec, double sx, double sy); + +/** + * Notify the seat that a button has been pressed. Returns the serial of the + * button press or zero if no button press was sent. Defers to any grab of the + * pointer. + */ +uint32_t wlr_seat_pointer_notify_button(struct wlr_seat *wlr_seat, + uint32_t time_msec, uint32_t button, enum wl_pointer_button_state state); + +/** + * Notify the seat of an axis event. Defers to any grab of the pointer. + */ +void wlr_seat_pointer_notify_axis(struct wlr_seat *wlr_seat, uint32_t time_msec, + enum wl_pointer_axis orientation, double value, + int32_t value_discrete, enum wl_pointer_axis_source source, + enum wl_pointer_axis_relative_direction relative_direction); + +/** + * Notify the seat of a frame event. Frame events are sent to end a group of + * events that logically belong together. Motion, button and axis events should + * all be followed by a frame event. Defers to any grab of the pointer. + */ +void wlr_seat_pointer_notify_frame(struct wlr_seat *wlr_seat); + +/** + * Start a grab of the pointer of this seat. The grabber is responsible for + * handling all pointer events until the grab ends. + */ +void wlr_seat_pointer_start_grab(struct wlr_seat *wlr_seat, + struct wlr_seat_pointer_grab *grab); + +/** + * End the grab of the pointer of this seat. This reverts the grab back to the + * default grab for the pointer. + */ +void wlr_seat_pointer_end_grab(struct wlr_seat *wlr_seat); + +/** + * Whether or not the pointer has a grab other than the default grab. + */ +bool wlr_seat_pointer_has_grab(struct wlr_seat *seat); + +/** + * Set this keyboard as the active keyboard for the seat. + */ +void wlr_seat_set_keyboard(struct wlr_seat *seat, struct wlr_keyboard *keyboard); + +/** + * Get the active keyboard for the seat. + */ +struct wlr_keyboard *wlr_seat_get_keyboard(struct wlr_seat *seat); + +/** + * Send the keyboard key to focused keyboard resources. This function does not + * respect keyboard grabs: you probably want wlr_seat_keyboard_notify_key() + * instead. + */ +void wlr_seat_keyboard_send_key(struct wlr_seat *seat, uint32_t time_msec, + uint32_t key, uint32_t state); + +/** + * Send the modifier state to focused keyboard resources. This function does + * not respect keyboard grabs: you probably want + * wlr_seat_keyboard_notify_modifiers() instead. + */ +void wlr_seat_keyboard_send_modifiers(struct wlr_seat *seat, + const struct wlr_keyboard_modifiers *modifiers); + +/** + * Send a keyboard enter event to the given surface and consider it to be the + * focused surface for the keyboard. This will send a leave event to the last + * surface that was entered. This function does not respect keyboard grabs: you + * probably want wlr_seat_keyboard_notify_enter() instead. + */ +void wlr_seat_keyboard_enter(struct wlr_seat *seat, + struct wlr_surface *surface, const uint32_t keycodes[], size_t num_keycodes, + const struct wlr_keyboard_modifiers *modifiers); + +/** + * Clear the focused surface for the keyboard and leave all entered surfaces. + * This function does not respect keyboard grabs: you probably want + * wlr_seat_keyboard_notify_clear_focus() instead. + */ +void wlr_seat_keyboard_clear_focus(struct wlr_seat *wlr_seat); + +/** + * Notify the seat that a key has been pressed on the keyboard. Defers to any + * keyboard grabs. + */ +void wlr_seat_keyboard_notify_key(struct wlr_seat *seat, uint32_t time_msec, + uint32_t key, uint32_t state); + +/** + * Notify the seat that the modifiers for the keyboard have changed. Defers to + * any keyboard grabs. + */ +void wlr_seat_keyboard_notify_modifiers(struct wlr_seat *seat, + const struct wlr_keyboard_modifiers *modifiers); + +/** + * Notify the seat that the keyboard focus has changed and request it to be the + * focused surface for this keyboard. Defers to any current grab of the seat's + * keyboard. + */ +void wlr_seat_keyboard_notify_enter(struct wlr_seat *seat, + struct wlr_surface *surface, const uint32_t keycodes[], size_t num_keycodes, + const struct wlr_keyboard_modifiers *modifiers); + +/** + * Notify the seat of a keyboard leave event to the currently-focused surface. + * Defers to any keyboard grabs. + */ +void wlr_seat_keyboard_notify_clear_focus(struct wlr_seat *wlr_seat); + +/** + * Start a grab of the keyboard of this seat. The grabber is responsible for + * handling all keyboard events until the grab ends. + */ +void wlr_seat_keyboard_start_grab(struct wlr_seat *wlr_seat, + struct wlr_seat_keyboard_grab *grab); + +/** + * End the grab of the keyboard of this seat. This reverts the grab back to the + * default grab for the keyboard. + */ +void wlr_seat_keyboard_end_grab(struct wlr_seat *wlr_seat); + +/** + * Whether or not the keyboard has a grab other than the default grab + */ +bool wlr_seat_keyboard_has_grab(struct wlr_seat *seat); + +/** + * Get the active touch point with the given `touch_id`. If the touch point does + * not exist or is no longer active, returns NULL. + */ +struct wlr_touch_point *wlr_seat_touch_get_point(struct wlr_seat *seat, + int32_t touch_id); + +/** + * Notify the seat that the touch point given by `touch_id` has entered a new + * surface. The surface is required. To clear focus, use + * wlr_seat_touch_point_clear_focus(). + */ +void wlr_seat_touch_point_focus(struct wlr_seat *seat, + struct wlr_surface *surface, uint32_t time_msec, + int32_t touch_id, double sx, double sy); + +/** + * Clear the focused surface for the touch point given by `touch_id`. + */ +void wlr_seat_touch_point_clear_focus(struct wlr_seat *seat, uint32_t time_msec, + int32_t touch_id); + +/** + * Send a touch down event to the client of the given surface. All future touch + * events for this point will go to this surface. If the touch down is valid, + * this will add a new touch point with the given `touch_id`. The touch down may + * not be valid if the surface seat client does not accept touch input. + * Coordinates are surface-local. This function does not respect touch grabs: + * you probably want wlr_seat_touch_notify_down() instead. + */ +uint32_t wlr_seat_touch_send_down(struct wlr_seat *seat, + struct wlr_surface *surface, uint32_t time_msec, + int32_t touch_id, double sx, double sy); + +/** + * Send a touch up event for the touch point given by the `touch_id`. The event + * will go to the client for the surface given in the corresponding touch down + * event. This will remove the touch point. This function does not respect touch + * grabs: you probably want wlr_seat_touch_notify_up() instead. + */ +uint32_t wlr_seat_touch_send_up(struct wlr_seat *seat, uint32_t time_msec, + int32_t touch_id); + +/** + * Send a touch motion event for the touch point given by the `touch_id`. The + * event will go to the client for the surface given in the corresponding touch + * down event. This function does not respect touch grabs: you probably want + * wlr_seat_touch_notify_motion() instead. + */ +void wlr_seat_touch_send_motion(struct wlr_seat *seat, uint32_t time_msec, + int32_t touch_id, double sx, double sy); + +/** + * Notify the seat that this is a global gesture and the client should cancel + * processing it. The event will go to the client given. + * This function does not respect touch grabs: you probably want + * wlr_seat_touch_notify_cancel() instead. + */ +void wlr_seat_touch_send_cancel(struct wlr_seat *seat, + struct wlr_seat_client *seat_client); + +void wlr_seat_touch_send_frame(struct wlr_seat *seat); + +/** + * Notify the seat of a touch down on the given surface. Defers to any grab of + * the touch device. + */ +uint32_t wlr_seat_touch_notify_down(struct wlr_seat *seat, + struct wlr_surface *surface, uint32_t time_msec, + int32_t touch_id, double sx, double sy); + +/** + * Notify the seat that the touch point given by `touch_id` is up. Defers to any + * grab of the touch device. + */ +uint32_t wlr_seat_touch_notify_up(struct wlr_seat *seat, uint32_t time_msec, + int32_t touch_id); + +/** + * Notify the seat that the touch point given by `touch_id` has moved. Defers to + * any grab of the touch device. The seat should be notified of touch motion + * even if the surface is not the owner of the touch point for processing by + * grabs. + */ +void wlr_seat_touch_notify_motion(struct wlr_seat *seat, uint32_t time_msec, + int32_t touch_id, double sx, double sy); + +/** + * Notify the seat that this is a global gesture and the client should + * cancel processing it. Defers to any grab of the touch device. + */ +void wlr_seat_touch_notify_cancel(struct wlr_seat *seat, + struct wlr_seat_client *seat_client); + +void wlr_seat_touch_notify_frame(struct wlr_seat *seat); +void wlr_seat_touch_notify_clear_focus(struct wlr_seat *seat, + uint32_t time_msec, int32_t touch_id); + +/** + * How many touch points are currently down for the seat. + */ +int wlr_seat_touch_num_points(struct wlr_seat *seat); + +/** + * Start a grab of the touch device of this seat. The grabber is responsible for + * handling all touch events until the grab ends. + */ +void wlr_seat_touch_start_grab(struct wlr_seat *wlr_seat, + struct wlr_seat_touch_grab *grab); + +/** + * End the grab of the touch device of this seat. This reverts the grab back to + * the default grab for the touch device. + */ +void wlr_seat_touch_end_grab(struct wlr_seat *wlr_seat); + +/** + * Whether or not the seat has a touch grab other than the default grab. + */ +bool wlr_seat_touch_has_grab(struct wlr_seat *seat); + +/** + * Check whether this serial is valid to start a pointer grab action. + */ +bool wlr_seat_validate_pointer_grab_serial(struct wlr_seat *seat, + struct wlr_surface *origin, uint32_t serial); + +/** + * Check whether this serial is valid to start a touch grab action. If it's the + * case and point_ptr is non-NULL, `*point_ptr` is set to the touch point matching + * the serial. + */ +bool wlr_seat_validate_touch_grab_serial(struct wlr_seat *seat, + struct wlr_surface *origin, uint32_t serial, + struct wlr_touch_point **point_ptr); + +/** + * Return a new serial (from wl_display_serial_next()) for the client, and + * update the seat client's set of valid serials. Use this for all input + * events; otherwise wlr_seat_client_validate_event_serial() may fail when + * handed a correctly functioning client's request serials. + */ +uint32_t wlr_seat_client_next_serial(struct wlr_seat_client *client); + +/** + * Return true if the serial number could have been produced by + * wlr_seat_client_next_serial() and is "older" (by less than UINT32_MAX/2) than + * the current display serial value. + * + * This function should have no false negatives, and the only false positive + * responses allowed are for elements that are still "older" than the current + * display serial value and also older than all serial values remaining in + * the seat client's serial ring buffer, if that buffer is also full. + */ +bool wlr_seat_client_validate_event_serial(struct wlr_seat_client *client, + uint32_t serial); + +/** + * Get a seat client from a seat resource. Returns NULL if inert. + */ +struct wlr_seat_client *wlr_seat_client_from_resource( + struct wl_resource *resource); + +/** + * Get a seat client from a pointer resource. Returns NULL if inert. + */ +struct wlr_seat_client *wlr_seat_client_from_pointer_resource( + struct wl_resource *resource); + +/** + * Check whether a surface has bound to touch events. + */ +bool wlr_surface_accepts_touch(struct wlr_surface *surface, struct wlr_seat *wlr_seat); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_security_context_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_security_context_v1.h new file mode 100644 index 0000000000..3a5fcfbcb7 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_security_context_v1.h @@ -0,0 +1,69 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_SECURITY_CONTEXT_V1_H +#define WLR_TYPES_WLR_SECURITY_CONTEXT_V1_H + +#include +#include + +/** + * An implementation of the security context protocol. + * + * Compositors can create this manager, setup a filter for Wayland globals via + * wl_display_set_global_filter(), and inside the filter query the security + * context state via wlr_security_context_manager_v1_lookup_client(). + */ +struct wlr_security_context_manager_v1 { + struct wl_global *global; + + struct { + struct wl_signal destroy; + struct wl_signal commit; // struct wlr_security_context_v1_commit_event + } events; + + void *data; + + struct { + struct wl_list contexts; // wlr_security_context_v1.link + + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_security_context_v1_state { + char *sandbox_engine; // may be NULL + char *app_id; // may be NULL + char *instance_id; // may be NULL +}; + +struct wlr_security_context_v1_commit_event { + const struct wlr_security_context_v1_state *state; + // Client which created the security context + struct wl_client *parent_client; +}; + +struct wlr_security_context_manager_v1 *wlr_security_context_manager_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_security_context_manager_v1_destroy(struct wlr_security_context_manager_v1 *manager, + bool destroy_global_safe); +const struct wlr_security_context_v1_state *wlr_security_context_manager_v1_lookup_client( + struct wlr_security_context_manager_v1 *manager, const struct wl_client *client); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_server_decoration.h b/3rdparty/wlroots/include/wlr/types/wlr_server_decoration.h new file mode 100644 index 0000000000..94fdfa7a9f --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_server_decoration.h @@ -0,0 +1,102 @@ +/* + * This protocol is obsolete and will be removed in a future version. The + * recommended replacement is xdg-decoration. + */ + +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_SERVER_DECORATION_H +#define WLR_TYPES_WLR_SERVER_DECORATION_H + +#include +#include + +/** + * Possible values to use in request_mode and the event mode. Same as + * org_kde_kwin_server_decoration_manager_mode. + */ +enum wlr_server_decoration_manager_mode { + /** + * Undecorated: The surface is not decorated at all, neither server nor + * client-side. An example is a popup surface which should not be + * decorated. + */ + WLR_SERVER_DECORATION_MANAGER_MODE_NONE = 0, + /** + * Client-side decoration: The decoration is part of the surface and the + * client. + */ + WLR_SERVER_DECORATION_MANAGER_MODE_CLIENT = 1, + /** + * Server-side decoration: The server embeds the surface into a decoration + * frame. + */ + WLR_SERVER_DECORATION_MANAGER_MODE_SERVER = 2, +}; + +/** + * A decoration negotiation interface which implements the KDE protocol. + */ +struct wlr_server_decoration_manager { + struct wl_global *global; + struct wl_list resources; // wl_resource_get_link() + struct wl_list decorations; // wlr_server_decoration.link + + uint32_t default_mode; // enum wlr_server_decoration_manager_mode + + struct { + struct wl_signal new_decoration; + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_server_decoration { + struct wl_resource *resource; + struct wlr_surface *surface; + struct wl_list link; + + uint32_t mode; // enum wlr_server_decoration_manager_mode + + struct { + struct wl_signal destroy; + struct wl_signal mode; + } events; + + void *data; + + struct { + struct wl_listener surface_destroy_listener; + } WLR_PRIVATE; +}; + +struct wlr_server_decoration_manager *wlr_server_decoration_manager_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_server_decoration_manager_destroy(struct wlr_server_decoration_manager *manager, + bool destroy_global_safe); +void wlr_server_decoration_manager_set_default_mode( + struct wlr_server_decoration_manager *manager, uint32_t default_mode); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_session_lock_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_session_lock_v1.h new file mode 100644 index 0000000000..1d95192754 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_session_lock_v1.h @@ -0,0 +1,121 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_SESSION_LOCK_H +#define WLR_TYPES_WLR_SESSION_LOCK_H + +#include +#include +#include +#include + +struct wlr_session_lock_manager_v1 { + struct wl_global *global; + + struct { + struct wl_signal new_lock; // struct wlr_session_lock_v1 + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_session_lock_v1 { + struct wl_resource *resource; + + struct wl_list surfaces; // struct wlr_session_lock_surface_v1.link + + struct { + struct wl_signal new_surface; // struct wlr_session_lock_surface_v1 + struct wl_signal unlock; + struct wl_signal destroy; + } events; + + void *data; + + struct { + bool locked_sent; + } WLR_PRIVATE; +}; + +struct wlr_session_lock_surface_v1_state { + uint32_t width, height; + uint32_t configure_serial; +}; + +struct wlr_session_lock_surface_v1_configure { + struct wl_list link; // wlr_session_lock_surface_v1.configure_list + uint32_t serial; + + uint32_t width, height; +}; + +struct wlr_session_lock_surface_v1 { + struct wl_resource *resource; + struct wl_list link; // wlr_session_lock_v1.surfaces + + struct wlr_output *output; + struct wlr_surface *surface; + + bool configured; + + struct wl_list configure_list; // wlr_session_lock_surface_v1_configure.link + + struct wlr_session_lock_surface_v1_state current; + struct wlr_session_lock_surface_v1_state pending; + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wlr_surface_synced synced; + + struct wl_listener output_destroy; + } WLR_PRIVATE; +}; + +struct wlr_session_lock_manager_v1 *wlr_session_lock_manager_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_session_lock_manager_v1_destroy(struct wlr_session_lock_manager_v1 *lock_manager, + bool destroy_global_safe); + +void wlr_session_lock_v1_send_locked(struct wlr_session_lock_v1 *lock); +void wlr_session_lock_v1_destroy(struct wlr_session_lock_v1 *lock); + +uint32_t wlr_session_lock_surface_v1_configure( + struct wlr_session_lock_surface_v1 *lock_surface, + uint32_t width, uint32_t height); + +/** + * Get a struct wlr_session_lock_surface_v1 from a struct wlr_surface. + * + * Returns NULL if the surface has a different role or if the lock surface + * has been destroyed. + */ +struct wlr_session_lock_surface_v1 *wlr_session_lock_surface_v1_try_from_wlr_surface( + struct wlr_surface *surface); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_shm.h b/3rdparty/wlroots/include/wlr/types/wlr_shm.h new file mode 100644 index 0000000000..3e14ff4f84 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_shm.h @@ -0,0 +1,66 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_SHM_H +#define WLR_TYPES_WLR_SHM_H + +#include +#include + +struct wlr_renderer; + +/** + * Shared memory buffer interface. + * + * The buffers created via this interface are not safe to use from different + * threads. + * + * Currently, accessing two buffers concurrently via + * wlr_buffer_begin_data_ptr_access() will return an error. + */ +struct wlr_shm { + struct wl_global *global; + + struct { + uint32_t *formats; + size_t formats_len; + + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +/** + * Create the wl_shm global. + * + * Compositors using struct wlr_renderer should use wlr_shm_create_with_renderer() + * instead. + */ +struct wlr_shm *wlr_shm_create(struct wl_display *display, uint32_t version, + const uint32_t *formats, size_t formats_len); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_shm_destroy(struct wlr_shm *shm, bool destroy_global_safe); + +/** + * Create the wl_shm global. + * + * The pixel formats advertised to clients are taken from the struct wlr_renderer. + */ +struct wlr_shm *wlr_shm_create_with_renderer(struct wl_display *display, + uint32_t version, struct wlr_renderer *renderer); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_single_pixel_buffer_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_single_pixel_buffer_v1.h new file mode 100644 index 0000000000..2ac04a94b2 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_single_pixel_buffer_v1.h @@ -0,0 +1,40 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_SINGLE_PIXEL_BUFFER_V1_H +#define WLR_TYPES_WLR_SINGLE_PIXEL_BUFFER_V1_H + +#include +#include + +struct wlr_single_pixel_buffer_manager_v1 { + struct wl_global *global; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + + +struct wlr_single_pixel_buffer_manager_v1 *wlr_single_pixel_buffer_manager_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_single_pixel_buffer_manager_v1_destroy(struct wlr_single_pixel_buffer_manager_v1 *manager, + bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_subcompositor.h b/3rdparty/wlroots/include/wlr/types/wlr_subcompositor.h new file mode 100644 index 0000000000..ca74d90afe --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_subcompositor.h @@ -0,0 +1,93 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_SUBCOMPOSITOR_H +#define WLR_TYPES_WLR_SUBCOMPOSITOR_H + +#include +#include +#include +#include + +/** + * The sub-surface state describing the sub-surface's relationship with its + * parent. Contrary to other states, this one is not applied on surface commit. + * Instead, it's applied on parent surface commit. + */ +struct wlr_subsurface_parent_state { + int32_t x, y; + struct wl_list link; + + struct { + struct wlr_surface_synced *synced; + } WLR_PRIVATE; +}; + +struct wlr_subsurface { + struct wl_resource *resource; + struct wlr_surface *surface; + struct wlr_surface *parent; + + struct wlr_subsurface_parent_state current, pending; + + uint32_t cached_seq; + bool has_cache; + + bool synchronized; + bool added; + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wlr_surface_synced parent_synced; + + struct wl_listener surface_client_commit; + struct wl_listener parent_destroy; + } WLR_PRIVATE; +}; + +struct wlr_subcompositor { + struct wl_global *global; + + struct { + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +/** + * Get a struct wlr_subsurface from a struct wlr_surface. + * + * Returns NULL if the surface doesn't have the subsurface role or if + * the subsurface has been destroyed. + */ +struct wlr_subsurface *wlr_subsurface_try_from_wlr_surface( + struct wlr_surface *surface); + +struct wlr_subcompositor *wlr_subcompositor_create(struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_subcompositor_destroy(struct wlr_subcompositor *subcompositor, bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_switch.h b/3rdparty/wlroots/include/wlr/types/wlr_switch.h new file mode 100644 index 0000000000..2b9e91266e --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_switch.h @@ -0,0 +1,61 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_SWITCH_H +#define WLR_TYPES_WLR_SWITCH_H + +#include +#include +#include + +struct wlr_switch_impl; + +/** + * A switch input device. Typically a switch input device can indicate whether + * a laptop lid is opened or closed, or whether tablet mode is enabled. + * + * See https://wayland.freedesktop.org/libinput/doc/latest/switches.html + */ +struct wlr_switch { + struct wlr_input_device base; + + const struct wlr_switch_impl *impl; + + struct { + struct wl_signal toggle; // struct wlr_switch_toggle_event + } events; + + void *data; +}; + +enum wlr_switch_type { + WLR_SWITCH_TYPE_LID, + WLR_SWITCH_TYPE_TABLET_MODE, + WLR_SWITCH_TYPE_KEYPAD_SLIDE, +}; + +enum wlr_switch_state { + WLR_SWITCH_STATE_OFF = 0, + WLR_SWITCH_STATE_ON, +}; + +struct wlr_switch_toggle_event { + uint32_t time_msec; + enum wlr_switch_type switch_type; + enum wlr_switch_state switch_state; +}; + +/** + * Get a struct wlr_switch from a struct wlr_input_device. + * + * Asserts that the input device is a switch. + */ +struct wlr_switch *wlr_switch_from_input_device( + struct wlr_input_device *input_device); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_tablet_pad.h b/3rdparty/wlroots/include/wlr/types/wlr_tablet_pad.h new file mode 100644 index 0000000000..f19505a976 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_tablet_pad.h @@ -0,0 +1,103 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_TABLET_PAD_H +#define WLR_TYPES_WLR_TABLET_PAD_H + +#include +#include +#include + +/* + * NOTE: the wlr tablet pad implementation does not currently support tablets + * with more than one mode. I don't own any such hardware so I cannot test it + * and it is too complicated to make a meaningful implementation of blindly. + */ + +struct wlr_tablet_pad_impl; + +struct wlr_tablet_pad { + struct wlr_input_device base; + + const struct wlr_tablet_pad_impl *impl; + + struct { + struct wl_signal button; + struct wl_signal ring; + struct wl_signal strip; + struct wl_signal attach_tablet; // struct wlr_tablet_tool + } events; + + size_t button_count; + size_t ring_count; + size_t strip_count; + + struct wl_list groups; // wlr_tablet_pad_group.link + struct wl_array paths; // char * + + void *data; +}; + +struct wlr_tablet_pad_group { + struct wl_list link; + + size_t button_count; + unsigned int *buttons; + + size_t strip_count; + unsigned int *strips; + + size_t ring_count; + unsigned int *rings; + + unsigned int mode_count; +}; + +struct wlr_tablet_pad_button_event { + uint32_t time_msec; + uint32_t button; + enum wlr_button_state state; + unsigned int mode; + unsigned int group; +}; + +enum wlr_tablet_pad_ring_source { + WLR_TABLET_PAD_RING_SOURCE_UNKNOWN, + WLR_TABLET_PAD_RING_SOURCE_FINGER, +}; + +struct wlr_tablet_pad_ring_event { + uint32_t time_msec; + enum wlr_tablet_pad_ring_source source; + uint32_t ring; + double position; + unsigned int mode; +}; + +enum wlr_tablet_pad_strip_source { + WLR_TABLET_PAD_STRIP_SOURCE_UNKNOWN, + WLR_TABLET_PAD_STRIP_SOURCE_FINGER, +}; + +struct wlr_tablet_pad_strip_event { + uint32_t time_msec; + enum wlr_tablet_pad_strip_source source; + uint32_t strip; + double position; + unsigned int mode; +}; + +/** + * Get a struct wlr_tablet_pad from a struct wlr_input_device. + * + * Asserts that the input device is a tablet pad. + */ +struct wlr_tablet_pad *wlr_tablet_pad_from_input_device( + struct wlr_input_device *); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_tablet_tool.h b/3rdparty/wlroots/include/wlr/types/wlr_tablet_tool.h new file mode 100644 index 0000000000..97abd56085 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_tablet_tool.h @@ -0,0 +1,155 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_TABLET_TOOL_H +#define WLR_TYPES_TABLET_TOOL_H + +#include +#include +#include + +/* + * Copy+Paste from libinput, but this should neither use libinput, nor + * tablet-v2 headers, so we can't include them + */ +enum wlr_tablet_tool_type { + /** A generic pen */ + WLR_TABLET_TOOL_TYPE_PEN = 1, + /** Eraser */ + WLR_TABLET_TOOL_TYPE_ERASER, + /** A paintbrush-like tool */ + WLR_TABLET_TOOL_TYPE_BRUSH, + /** Physical drawing tool, e.g. Wacom Inking Pen */ + WLR_TABLET_TOOL_TYPE_PENCIL, + /** An airbrush-like tool */ + WLR_TABLET_TOOL_TYPE_AIRBRUSH, + /** A mouse bound to the tablet */ + WLR_TABLET_TOOL_TYPE_MOUSE, + /** A mouse tool with a lens */ + WLR_TABLET_TOOL_TYPE_LENS, + /** A rotary device with positional and rotation data */ + WLR_TABLET_TOOL_TYPE_TOTEM, +}; + +struct wlr_tablet_tool { + enum wlr_tablet_tool_type type; + uint64_t hardware_serial; + uint64_t hardware_wacom; + + // Capabilities + bool tilt; + bool pressure; + bool distance; + bool rotation; + bool slider; + bool wheel; + + struct { + struct wl_signal destroy; + } events; + + void *data; +}; + +struct wlr_tablet_impl; + +struct wlr_tablet { + struct wlr_input_device base; + + const struct wlr_tablet_impl *impl; + + uint16_t usb_vendor_id, usb_product_id; // zero if unset + double width_mm, height_mm; + + struct { + struct wl_signal axis; // struct wlr_tablet_tool_axis_event + struct wl_signal proximity; // struct wlr_tablet_tool_proximity_event + struct wl_signal tip; // struct wlr_tablet_tool_tip_event + struct wl_signal button; // struct wlr_tablet_tool_button_event + } events; + + struct wl_array paths; // char * + + void *data; +}; + +enum wlr_tablet_tool_axes { + WLR_TABLET_TOOL_AXIS_X = 1 << 0, + WLR_TABLET_TOOL_AXIS_Y = 1 << 1, + WLR_TABLET_TOOL_AXIS_DISTANCE = 1 << 2, + WLR_TABLET_TOOL_AXIS_PRESSURE = 1 << 3, + WLR_TABLET_TOOL_AXIS_TILT_X = 1 << 4, + WLR_TABLET_TOOL_AXIS_TILT_Y = 1 << 5, + WLR_TABLET_TOOL_AXIS_ROTATION = 1 << 6, + WLR_TABLET_TOOL_AXIS_SLIDER = 1 << 7, + WLR_TABLET_TOOL_AXIS_WHEEL = 1 << 8, +}; + +struct wlr_tablet_tool_axis_event { + struct wlr_tablet *tablet; + struct wlr_tablet_tool *tool; + + uint32_t time_msec; + uint32_t updated_axes; + // From 0..1 + double x, y; + // Relative to last event + double dx, dy; + double pressure; + double distance; + double tilt_x, tilt_y; + double rotation; + double slider; + double wheel_delta; +}; + +enum wlr_tablet_tool_proximity_state { + WLR_TABLET_TOOL_PROXIMITY_OUT, + WLR_TABLET_TOOL_PROXIMITY_IN, +}; + +struct wlr_tablet_tool_proximity_event { + struct wlr_tablet *tablet; + struct wlr_tablet_tool *tool; + uint32_t time_msec; + // From 0..1 + double x, y; + enum wlr_tablet_tool_proximity_state state; +}; + +enum wlr_tablet_tool_tip_state { + WLR_TABLET_TOOL_TIP_UP, + WLR_TABLET_TOOL_TIP_DOWN, +}; + +struct wlr_tablet_tool_tip_event { + struct wlr_tablet *tablet; + struct wlr_tablet_tool *tool; + uint32_t time_msec; + // From 0..1 + double x, y; + enum wlr_tablet_tool_tip_state state; +}; + +struct wlr_tablet_tool_button_event { + struct wlr_tablet *tablet; + struct wlr_tablet_tool *tool; + uint32_t time_msec; + uint32_t button; + enum wlr_button_state state; +}; + +/** + * Get a struct wlr_tablet from a struct wlr_input_device. + * + * Asserts that the input device is a tablet tool. + */ +struct wlr_tablet *wlr_tablet_from_input_device( + struct wlr_input_device *input_device); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_tablet_v2.h b/3rdparty/wlroots/include/wlr/types/wlr_tablet_v2.h new file mode 100644 index 0000000000..044e9c0d77 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_tablet_v2.h @@ -0,0 +1,352 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_TABLET_V2_H +#define WLR_TYPES_WLR_TABLET_V2_H + +#include +#include +#include +#include + +/* This can probably be even lower,the tools don't have a lot of buttons */ +#define WLR_TABLET_V2_TOOL_BUTTONS_CAP 16 + +struct wlr_input_device; + +struct wlr_tablet_pad_v2_grab_interface; + +struct wlr_tablet_pad_v2_grab { + const struct wlr_tablet_pad_v2_grab_interface *interface; + struct wlr_tablet_v2_tablet_pad *pad; + void *data; +}; + +struct wlr_tablet_tool_v2_grab_interface; + +struct wlr_tablet_tool_v2_grab { + const struct wlr_tablet_tool_v2_grab_interface *interface; + struct wlr_tablet_v2_tablet_tool *tool; + void *data; +}; + +struct wlr_tablet_client_v2; +struct wlr_tablet_tool_client_v2; +struct wlr_tablet_pad_client_v2; + +struct wlr_tablet_manager_v2 { + struct wl_global *wl_global; + struct wl_list clients; // wlr_tablet_manager_client_v2.link + struct wl_list seats; // wlr_tablet_seat_v2.link + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_tablet_v2_tablet { + struct wl_list link; // wlr_tablet_seat_v2.tablets + struct wlr_tablet *wlr_tablet; + struct wlr_input_device *wlr_device; + struct wl_list clients; // wlr_tablet_client_v2.tablet_link + + struct wlr_tablet_client_v2 *current_client; + + struct { + struct wl_listener tablet_destroy; + } WLR_PRIVATE; +}; + +struct wlr_tablet_v2_tablet_tool { + struct wl_list link; // wlr_tablet_seat_v2.tablets + struct wlr_tablet_tool *wlr_tool; + struct wl_list clients; // wlr_tablet_tool_client_v2.tool_link + + struct wlr_tablet_tool_client_v2 *current_client; + struct wlr_surface *focused_surface; + + struct wlr_tablet_tool_v2_grab *grab; + struct wlr_tablet_tool_v2_grab default_grab; + + uint32_t proximity_serial; + bool is_down; + uint32_t down_serial; + size_t num_buttons; + uint32_t pressed_buttons[WLR_TABLET_V2_TOOL_BUTTONS_CAP]; + uint32_t pressed_serials[WLR_TABLET_V2_TOOL_BUTTONS_CAP]; + + struct { + struct wl_signal set_cursor; // struct wlr_tablet_v2_event_cursor + } events; + + struct { + struct wl_listener surface_destroy; + struct wl_listener tool_destroy; + } WLR_PRIVATE; +}; + +struct wlr_tablet_v2_tablet_pad { + struct wl_list link; // wlr_tablet_seat_v2.pads + struct wlr_tablet_pad *wlr_pad; + struct wlr_input_device *wlr_device; + struct wl_list clients; // wlr_tablet_pad_client_v2.pad_link + + size_t group_count; + uint32_t *groups; + + struct wlr_tablet_pad_client_v2 *current_client; + struct wlr_tablet_pad_v2_grab *grab; + struct wlr_tablet_pad_v2_grab default_grab; + + struct { + struct wl_signal button_feedback; // struct wlr_tablet_v2_event_feedback + struct wl_signal strip_feedback; // struct wlr_tablet_v2_event_feedback + struct wl_signal ring_feedback; // struct wlr_tablet_v2_event_feedback + } events; + + struct { + struct wl_listener pad_destroy; + } WLR_PRIVATE; +}; + +struct wlr_tablet_v2_event_cursor { + struct wlr_surface *surface; + uint32_t serial; + int32_t hotspot_x; + int32_t hotspot_y; + struct wlr_seat_client *seat_client; +}; + +struct wlr_tablet_v2_event_feedback { + const char *description; + size_t index; + uint32_t serial; +}; + +struct wlr_tablet_v2_tablet *wlr_tablet_create( + struct wlr_tablet_manager_v2 *manager, + struct wlr_seat *wlr_seat, + struct wlr_input_device *wlr_device); + +struct wlr_tablet_v2_tablet_pad *wlr_tablet_pad_create( + struct wlr_tablet_manager_v2 *manager, + struct wlr_seat *wlr_seat, + struct wlr_input_device *wlr_device); + +struct wlr_tablet_v2_tablet_tool *wlr_tablet_tool_create( + struct wlr_tablet_manager_v2 *manager, + struct wlr_seat *wlr_seat, + struct wlr_tablet_tool *wlr_tool); + +struct wlr_tablet_manager_v2 *wlr_tablet_v2_create(struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_tablet_v2_destroy(struct wlr_tablet_manager_v2 *manager, bool destroy_global_safe); + +void wlr_send_tablet_v2_tablet_tool_proximity_in( + struct wlr_tablet_v2_tablet_tool *tool, + struct wlr_tablet_v2_tablet *tablet, + struct wlr_surface *surface); + +void wlr_send_tablet_v2_tablet_tool_down(struct wlr_tablet_v2_tablet_tool *tool); +void wlr_send_tablet_v2_tablet_tool_up(struct wlr_tablet_v2_tablet_tool *tool); + +void wlr_send_tablet_v2_tablet_tool_motion( + struct wlr_tablet_v2_tablet_tool *tool, double x, double y); + +void wlr_send_tablet_v2_tablet_tool_pressure( + struct wlr_tablet_v2_tablet_tool *tool, double pressure); + +void wlr_send_tablet_v2_tablet_tool_distance( + struct wlr_tablet_v2_tablet_tool *tool, double distance); + +void wlr_send_tablet_v2_tablet_tool_tilt( + struct wlr_tablet_v2_tablet_tool *tool, double x, double y); + +void wlr_send_tablet_v2_tablet_tool_rotation( + struct wlr_tablet_v2_tablet_tool *tool, double degrees); + +void wlr_send_tablet_v2_tablet_tool_slider( + struct wlr_tablet_v2_tablet_tool *tool, double position); + +void wlr_send_tablet_v2_tablet_tool_wheel( + struct wlr_tablet_v2_tablet_tool *tool, double degrees, int32_t clicks); + +void wlr_send_tablet_v2_tablet_tool_proximity_out( + struct wlr_tablet_v2_tablet_tool *tool); + +void wlr_send_tablet_v2_tablet_tool_button( + struct wlr_tablet_v2_tablet_tool *tool, uint32_t button, + enum zwp_tablet_pad_v2_button_state state); + + + +void wlr_tablet_v2_tablet_tool_notify_proximity_in( + struct wlr_tablet_v2_tablet_tool *tool, + struct wlr_tablet_v2_tablet *tablet, + struct wlr_surface *surface); + +void wlr_tablet_v2_tablet_tool_notify_down(struct wlr_tablet_v2_tablet_tool *tool); +void wlr_tablet_v2_tablet_tool_notify_up(struct wlr_tablet_v2_tablet_tool *tool); + +void wlr_tablet_v2_tablet_tool_notify_motion( + struct wlr_tablet_v2_tablet_tool *tool, double x, double y); + +void wlr_tablet_v2_tablet_tool_notify_pressure( + struct wlr_tablet_v2_tablet_tool *tool, double pressure); + +void wlr_tablet_v2_tablet_tool_notify_distance( + struct wlr_tablet_v2_tablet_tool *tool, double distance); + +void wlr_tablet_v2_tablet_tool_notify_tilt( + struct wlr_tablet_v2_tablet_tool *tool, double x, double y); + +void wlr_tablet_v2_tablet_tool_notify_rotation( + struct wlr_tablet_v2_tablet_tool *tool, double degrees); + +void wlr_tablet_v2_tablet_tool_notify_slider( + struct wlr_tablet_v2_tablet_tool *tool, double position); + +void wlr_tablet_v2_tablet_tool_notify_wheel( + struct wlr_tablet_v2_tablet_tool *tool, double degrees, int32_t clicks); + +void wlr_tablet_v2_tablet_tool_notify_proximity_out( + struct wlr_tablet_v2_tablet_tool *tool); + +void wlr_tablet_v2_tablet_tool_notify_button( + struct wlr_tablet_v2_tablet_tool *tool, uint32_t button, + enum zwp_tablet_pad_v2_button_state state); + + +struct wlr_tablet_tool_v2_grab_interface { + void (*proximity_in)( + struct wlr_tablet_tool_v2_grab *grab, + struct wlr_tablet_v2_tablet *tablet, + struct wlr_surface *surface); + + void (*down)(struct wlr_tablet_tool_v2_grab *grab); + void (*up)(struct wlr_tablet_tool_v2_grab *grab); + + void (*motion)(struct wlr_tablet_tool_v2_grab *grab, double x, double y); + + void (*pressure)(struct wlr_tablet_tool_v2_grab *grab, double pressure); + + void (*distance)(struct wlr_tablet_tool_v2_grab *grab, double distance); + + void (*tilt)(struct wlr_tablet_tool_v2_grab *grab, double x, double y); + + void (*rotation)(struct wlr_tablet_tool_v2_grab *grab, double degrees); + + void (*slider)(struct wlr_tablet_tool_v2_grab *grab, double position); + + void (*wheel)(struct wlr_tablet_tool_v2_grab *grab, double degrees, int32_t clicks); + + void (*proximity_out)(struct wlr_tablet_tool_v2_grab *grab); + + void (*button)( + struct wlr_tablet_tool_v2_grab *grab, uint32_t button, + enum zwp_tablet_pad_v2_button_state state); + void (*cancel)(struct wlr_tablet_tool_v2_grab *grab); +}; + +void wlr_tablet_tool_v2_start_grab(struct wlr_tablet_v2_tablet_tool *tool, struct wlr_tablet_tool_v2_grab *grab); +void wlr_tablet_tool_v2_end_grab(struct wlr_tablet_v2_tablet_tool *tool); + +void wlr_tablet_tool_v2_start_implicit_grab(struct wlr_tablet_v2_tablet_tool *tool); + +bool wlr_tablet_tool_v2_has_implicit_grab( + struct wlr_tablet_v2_tablet_tool *tool); + +uint32_t wlr_send_tablet_v2_tablet_pad_enter( + struct wlr_tablet_v2_tablet_pad *pad, + struct wlr_tablet_v2_tablet *tablet, + struct wlr_surface *surface); + +void wlr_send_tablet_v2_tablet_pad_button( + struct wlr_tablet_v2_tablet_pad *pad, size_t button, + uint32_t time, enum zwp_tablet_pad_v2_button_state state); + +void wlr_send_tablet_v2_tablet_pad_strip(struct wlr_tablet_v2_tablet_pad *pad, + uint32_t strip, double position, bool finger, uint32_t time); +void wlr_send_tablet_v2_tablet_pad_ring(struct wlr_tablet_v2_tablet_pad *pad, + uint32_t ring, double position, bool finger, uint32_t time); + +uint32_t wlr_send_tablet_v2_tablet_pad_leave(struct wlr_tablet_v2_tablet_pad *pad, + struct wlr_surface *surface); + +uint32_t wlr_send_tablet_v2_tablet_pad_mode(struct wlr_tablet_v2_tablet_pad *pad, + size_t group, uint32_t mode, uint32_t time); + + +uint32_t wlr_tablet_v2_tablet_pad_notify_enter( + struct wlr_tablet_v2_tablet_pad *pad, + struct wlr_tablet_v2_tablet *tablet, + struct wlr_surface *surface); + +void wlr_tablet_v2_tablet_pad_notify_button( + struct wlr_tablet_v2_tablet_pad *pad, size_t button, + uint32_t time, enum zwp_tablet_pad_v2_button_state state); + +void wlr_tablet_v2_tablet_pad_notify_strip( + struct wlr_tablet_v2_tablet_pad *pad, + uint32_t strip, double position, bool finger, uint32_t time); +void wlr_tablet_v2_tablet_pad_notify_ring( + struct wlr_tablet_v2_tablet_pad *pad, + uint32_t ring, double position, bool finger, uint32_t time); + +uint32_t wlr_tablet_v2_tablet_pad_notify_leave( + struct wlr_tablet_v2_tablet_pad *pad, struct wlr_surface *surface); + +uint32_t wlr_tablet_v2_tablet_pad_notify_mode( + struct wlr_tablet_v2_tablet_pad *pad, + size_t group, uint32_t mode, uint32_t time); + +struct wlr_tablet_pad_v2_grab_interface { + uint32_t (*enter)( + struct wlr_tablet_pad_v2_grab *grab, + struct wlr_tablet_v2_tablet *tablet, + struct wlr_surface *surface); + + void (*button)(struct wlr_tablet_pad_v2_grab *grab,size_t button, + uint32_t time, enum zwp_tablet_pad_v2_button_state state); + + void (*strip)(struct wlr_tablet_pad_v2_grab *grab, + uint32_t strip, double position, bool finger, uint32_t time); + void (*ring)(struct wlr_tablet_pad_v2_grab *grab, + uint32_t ring, double position, bool finger, uint32_t time); + + uint32_t (*leave)(struct wlr_tablet_pad_v2_grab *grab, + struct wlr_surface *surface); + + uint32_t (*mode)(struct wlr_tablet_pad_v2_grab *grab, + size_t group, uint32_t mode, uint32_t time); + + void (*cancel)(struct wlr_tablet_pad_v2_grab *grab); +}; + +void wlr_tablet_v2_end_grab(struct wlr_tablet_v2_tablet_pad *pad); +void wlr_tablet_v2_start_grab(struct wlr_tablet_v2_tablet_pad *pad, struct wlr_tablet_pad_v2_grab *grab); + +bool wlr_surface_accepts_tablet_v2(struct wlr_surface *surface, + struct wlr_tablet_v2_tablet *tablet); +#endif /* WLR_TYPES_WLR_TABLET_V2_H */ diff --git a/3rdparty/wlroots/include/wlr/types/wlr_tearing_control_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_tearing_control_v1.h new file mode 100644 index 0000000000..bb82283d45 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_tearing_control_v1.h @@ -0,0 +1,82 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_TEARING_CONTROL_MANAGER_V1_H +#define WLR_TYPES_WLR_TEARING_CONTROL_MANAGER_V1_H + +#include +#include +#include +#include +#include + +struct wlr_tearing_control_v1 { + struct wl_client *client; + struct wl_list link; + struct wl_resource *resource; + + enum wp_tearing_control_v1_presentation_hint current, pending; + + struct { + struct wl_signal set_hint; + struct wl_signal destroy; + } events; + + struct wlr_surface *surface; + + struct { + enum wp_tearing_control_v1_presentation_hint previous; + struct wlr_addon addon; + struct wlr_surface_synced synced; + + struct wl_listener surface_commit; + } WLR_PRIVATE; +}; + +struct wlr_tearing_control_manager_v1 { + struct wl_global *global; + + struct wl_list surface_hints; // wlr_tearing_control_v1.link + + struct { + struct wl_signal new_object; // struct wlr_tearing_control_v1* + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_tearing_control_manager_v1 *wlr_tearing_control_manager_v1_create( + struct wl_display *display, uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_tearing_control_manager_v1_destroy(struct wlr_tearing_control_manager_v1 *manager, + bool destroy_global_safe); + +/** + * Returns the tearing hint for a given surface + */ +enum wp_tearing_control_v1_presentation_hint +wlr_tearing_control_manager_v1_surface_hint_from_surface( + struct wlr_tearing_control_manager_v1 *manager, + struct wlr_surface *surface); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_text_input_v3.h b/3rdparty/wlroots/include/wlr/types/wlr_text_input_v3.h new file mode 100644 index 0000000000..cad5010a83 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_text_input_v3.h @@ -0,0 +1,117 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_TEXT_INPUT_V3_H +#define WLR_TYPES_WLR_TEXT_INPUT_V3_H + +#include +#include +#include +#include + +struct wlr_surface; + +enum wlr_text_input_v3_features { + WLR_TEXT_INPUT_V3_FEATURE_SURROUNDING_TEXT = 1 << 0, + WLR_TEXT_INPUT_V3_FEATURE_CONTENT_TYPE = 1 << 1, + WLR_TEXT_INPUT_V3_FEATURE_CURSOR_RECTANGLE = 1 << 2, +}; + +struct wlr_text_input_v3_state { + struct { + char *text; // NULL is allowed and equivalent to empty string + uint32_t cursor; + uint32_t anchor; + } surrounding; + + uint32_t text_change_cause; + + struct { + uint32_t hint; + uint32_t purpose; + } content_type; + + struct wlr_box cursor_rectangle; + + // Tracks which features were used in the current commit. + // Useful in the enabling commit, where usage means support. + uint32_t features; // bitfield of enum wlr_text_input_v3_features +}; + +struct wlr_text_input_v3 { + struct wlr_seat *seat; // becomes null when seat destroyed + struct wl_resource *resource; + struct wlr_surface *focused_surface; + struct wlr_text_input_v3_state pending; + struct wlr_text_input_v3_state current; + uint32_t current_serial; // next in line to send + bool pending_enabled; + bool current_enabled; + // supported in the current text input, more granular than surface + uint32_t active_features; // bitfield of enum wlr_text_input_v3_features + + struct wl_list link; + + struct { + struct wl_signal enable; + struct wl_signal commit; + struct wl_signal disable; + struct wl_signal destroy; + } events; + + struct { + struct wl_listener surface_destroy; + struct wl_listener seat_destroy; + } WLR_PRIVATE; +}; + +struct wlr_text_input_manager_v3 { + struct wl_global *global; + struct wl_list text_inputs; // wlr_text_input_v3.link + + struct { + struct wl_signal new_text_input; // struct wlr_text_input_v3 + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_text_input_manager_v3 *wlr_text_input_manager_v3_create( + struct wl_display *wl_display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_text_input_manager_v3_destroy(struct wlr_text_input_manager_v3 *manager, + bool destroy_global_safe); + +// Sends enter to the surface and saves it +void wlr_text_input_v3_send_enter(struct wlr_text_input_v3 *text_input, + struct wlr_surface *wlr_surface); +// Sends leave to the currently focused surface and clears it +void wlr_text_input_v3_send_leave(struct wlr_text_input_v3 *text_input); +void wlr_text_input_v3_send_preedit_string(struct wlr_text_input_v3 *text_input, + const char *text, int32_t cursor_begin, int32_t cursor_end); +void wlr_text_input_v3_send_commit_string(struct wlr_text_input_v3 *text_input, + const char *text); +void wlr_text_input_v3_send_delete_surrounding_text( + struct wlr_text_input_v3 *text_input, uint32_t before_length, + uint32_t after_length); +void wlr_text_input_v3_send_done(struct wlr_text_input_v3 *text_input); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_touch.h b/3rdparty/wlroots/include/wlr/types/wlr_touch.h new file mode 100644 index 0000000000..82c4b8618f --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_touch.h @@ -0,0 +1,73 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_TOUCH_H +#define WLR_TYPES_WLR_TOUCH_H + +#include +#include +#include + +struct wlr_touch_impl; + +struct wlr_touch { + struct wlr_input_device base; + + const struct wlr_touch_impl *impl; + + char *output_name; + double width_mm, height_mm; + + struct { + struct wl_signal down; // struct wlr_touch_down_event + struct wl_signal up; // struct wlr_touch_up_event + struct wl_signal motion; // struct wlr_touch_motion_event + struct wl_signal cancel; // struct wlr_touch_cancel_event + struct wl_signal frame; + } events; + + void *data; +}; + +struct wlr_touch_down_event { + struct wlr_touch *touch; + uint32_t time_msec; + int32_t touch_id; + // From 0..1 + double x, y; +}; + +struct wlr_touch_up_event { + struct wlr_touch *touch; + uint32_t time_msec; + int32_t touch_id; +}; + +struct wlr_touch_motion_event { + struct wlr_touch *touch; + uint32_t time_msec; + int32_t touch_id; + // From 0..1 + double x, y; +}; + +struct wlr_touch_cancel_event { + struct wlr_touch *touch; + uint32_t time_msec; + int32_t touch_id; +}; + +/** + * Get a struct wlr_touch from a struct wlr_input_device. + * + * Asserts that the input device is a touch device. + */ +struct wlr_touch *wlr_touch_from_input_device( + struct wlr_input_device *input_device); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_transient_seat_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_transient_seat_v1.h new file mode 100644 index 0000000000..1d285c0715 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_transient_seat_v1.h @@ -0,0 +1,83 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_TRANSIENT_SEAT_V1_H +#define WLR_TYPES_WLR_TRANSIENT_SEAT_V1_H + +#include +#include + +struct wlr_seat; + +struct wlr_transient_seat_v1 { + struct wl_resource *resource; + struct wlr_seat *seat; + + struct { + struct wl_listener seat_destroy; + } WLR_PRIVATE; +}; + +struct wlr_transient_seat_manager_v1 { + struct wl_global *global; + + struct { + struct wl_signal destroy; + + /** + * Upon receiving this signal, call + * wlr_transient_seat_v1_ready() to pass a newly created seat + * to the manager, or + * wlr_transient_seat_v1_deny() to deny the request to create + * a seat. + */ + struct wl_signal create_seat; // struct wlr_transient_seat_v1 + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_transient_seat_manager_v1 *wlr_transient_seat_manager_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_transient_seat_manager_v1_destroy(struct wlr_transient_seat_manager_v1 *manager, + bool destroy_global_safe); + +/** + * To be called when the create_seat event is received. + * + * This signals that the seat was successfully added and is ready. + * + * When the transient seat is destroyed by the client, the wlr_seat will be + * destroyed. The wlr_seat may also be destroyed from elsewhere, in which case + * the transient seat will become inert. + */ +void wlr_transient_seat_v1_ready(struct wlr_transient_seat_v1 *seat, + struct wlr_seat *wlr_seat); + +/** + * To be called when the create_seat event is received. + * + * This signals that the compositor has denied the user's request to create a + * transient seat. + */ +void wlr_transient_seat_v1_deny(struct wlr_transient_seat_v1 *seat); + +#endif /* WLR_TYPES_WLR_TRANSIENT_SEAT_V1_H */ diff --git a/3rdparty/wlroots/include/wlr/types/wlr_viewporter.h b/3rdparty/wlroots/include/wlr/types/wlr_viewporter.h new file mode 100644 index 0000000000..514372117c --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_viewporter.h @@ -0,0 +1,52 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_VIEWPORTER_H +#define WLR_TYPES_WLR_VIEWPORTER_H + +#include +#include + +/** + * Implementation for the viewporter protocol. + * + * When enabling viewporter, compositors need to update their rendering logic: + * + * - The size of the surface texture may not match the surface size anymore. + * Compositors must use the surface size only. + * - When rendering a surface texture, compositors should use + * wlr_surface_get_buffer_source_box() to get the source rectangle and crop + * the texture accordingly. + */ +struct wlr_viewporter { + struct wl_global *global; + + struct { + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_viewporter *wlr_viewporter_create(struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_viewporter_destroy(struct wlr_viewporter *viewporter, bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_virtual_keyboard_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_virtual_keyboard_v1.h new file mode 100644 index 0000000000..0e4de402a7 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_virtual_keyboard_v1.h @@ -0,0 +1,73 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_VIRTUAL_KEYBOARD_V1_H +#define WLR_TYPES_WLR_VIRTUAL_KEYBOARD_V1_H + +#include +#include +#include + +struct wlr_virtual_keyboard_manager_v1 { + struct wl_global *global; + struct wl_list virtual_keyboards; // wlr_virtual_keyboard_v1.link + + struct { + struct wl_signal new_virtual_keyboard; // struct wlr_virtual_keyboard_v1 + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_virtual_keyboard_v1 { + struct wlr_keyboard keyboard; + struct wl_resource *resource; + struct wlr_seat *seat; + bool has_keymap; + + struct wl_list link; // wlr_virtual_keyboard_manager_v1.virtual_keyboards + + struct { + struct wl_listener seat_destroy; + } WLR_PRIVATE; +}; + +struct wlr_virtual_keyboard_manager_v1* wlr_virtual_keyboard_manager_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_virtual_keyboard_manager_v1_destroy(struct wlr_virtual_keyboard_manager_v1 *manager, + bool destroy_global_safe); + +/** + * Get the struct wlr_virtual_keyboard_v1 corresponding to a zwp_virtual_keyboard_v1 resource. + * + * Asserts that the resource is a valid zwp_virtual_keyboard_v1 resource created by wlroots. + * + * Returns NULL if the resource is inert. + */ +struct wlr_virtual_keyboard_v1 *wlr_virtual_keyboard_v1_from_resource( + struct wl_resource *resource); + +struct wlr_virtual_keyboard_v1 *wlr_input_device_get_virtual_keyboard( + struct wlr_input_device *wlr_dev); + + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_virtual_pointer_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_virtual_pointer_v1.h new file mode 100644 index 0000000000..2f22898575 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_virtual_pointer_v1.h @@ -0,0 +1,66 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_VIRTUAL_POINTER_V1_H +#define WLR_TYPES_WLR_VIRTUAL_POINTER_V1_H + +#include +#include +#include +#include +#include + +struct wlr_virtual_pointer_manager_v1 { + struct wl_global *global; + struct wl_list virtual_pointers; // wlr_virtual_pointer_v1.link + + struct { + struct wl_signal new_virtual_pointer; // struct wlr_virtual_pointer_v1_new_pointer_event + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_virtual_pointer_v1 { + struct wlr_pointer pointer; + struct wl_resource *resource; + /* Vertical and horizontal */ + struct wlr_pointer_axis_event axis_event[2]; + enum wl_pointer_axis axis; + bool axis_valid[2]; + + struct wl_list link; // wlr_virtual_pointer_manager_v1.virtual_pointers +}; + +struct wlr_virtual_pointer_v1_new_pointer_event { + struct wlr_virtual_pointer_v1 *new_pointer; + /** Suggested by client; may be NULL. */ + struct wlr_seat *suggested_seat; + struct wlr_output *suggested_output; +}; + +struct wlr_virtual_pointer_manager_v1* wlr_virtual_pointer_manager_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_virtual_pointer_manager_v1_destroy(struct wlr_virtual_pointer_manager_v1 *manager, + bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_xcursor_manager.h b/3rdparty/wlroots/include/wlr/types/wlr_xcursor_manager.h new file mode 100644 index 0000000000..53993159bd --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_xcursor_manager.h @@ -0,0 +1,59 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_XCURSOR_MANAGER_H +#define WLR_TYPES_WLR_XCURSOR_MANAGER_H + +#include +#include + +/** + * An XCursor theme at a particular scale factor of the base size. + */ +struct wlr_xcursor_manager_theme { + float scale; + struct wlr_xcursor_theme *theme; + struct wl_list link; +}; + +/** + * struct wlr_xcursor_manager dynamically loads xcursor themes at sizes necessary + * for use on outputs at arbitrary scale factors. You should call + * wlr_xcursor_manager_load() for each output you will show your cursor on, with + * the scale factor parameter set to that output's scale factor. + */ +struct wlr_xcursor_manager { + char *name; + uint32_t size; + struct wl_list scaled_themes; // wlr_xcursor_manager_theme.link +}; + +/** + * Creates a new XCursor manager with the given xcursor theme name and base size + * (for use when scale=1). + */ +struct wlr_xcursor_manager *wlr_xcursor_manager_create(const char *name, + uint32_t size); + +void wlr_xcursor_manager_destroy(struct wlr_xcursor_manager *manager); + +/** + * Ensures an xcursor theme at the given scale factor is loaded in the manager. + */ +bool wlr_xcursor_manager_load(struct wlr_xcursor_manager *manager, + float scale); + +/** + * Retrieves a wlr_xcursor reference for the given cursor name at the given + * scale factor, or NULL if this struct wlr_xcursor_manager has not loaded a + * cursor theme at the requested scale. + */ +struct wlr_xcursor *wlr_xcursor_manager_get_xcursor( + struct wlr_xcursor_manager *manager, const char *name, float scale); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_xdg_activation_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_xdg_activation_v1.h new file mode 100644 index 0000000000..36eb938494 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_xdg_activation_v1.h @@ -0,0 +1,102 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_XDG_ACTIVATION_V1 +#define WLR_TYPES_WLR_XDG_ACTIVATION_V1 + +#include +#include + +struct wlr_xdg_activation_token_v1 { + struct wlr_xdg_activation_v1 *activation; + // The source surface that created the token. + struct wlr_surface *surface; // can be NULL + struct wlr_seat *seat; // can be NULL + // The serial for the input event that created the token. + uint32_t serial; // invalid if seat is NULL + // The application ID to be activated. This is just a hint. + char *app_id; // can be NULL + struct wl_list link; // wlr_xdg_activation_v1.tokens + + void *data; + + struct { + struct wl_signal destroy; + } events; + + struct { + char *token; + struct wl_resource *resource; // can be NULL + struct wl_event_source *timeout; // can be NULL + + struct wl_listener seat_destroy; + struct wl_listener surface_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_activation_v1 { + struct wl_global *global; + uint32_t token_timeout_msec; // token timeout in milliseconds (0 to disable) + + struct wl_list tokens; // wlr_xdg_activation_token_v1.link + + struct { + struct wl_signal destroy; + struct wl_signal request_activate; // struct wlr_xdg_activation_v1_request_activate_event + struct wl_signal new_token; // struct wlr_xdg_activation_token_v1 + } events; + + struct { + struct wl_display *display; + + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_activation_v1_request_activate_event { + struct wlr_xdg_activation_v1 *activation; + // The token used to request activation. + struct wlr_xdg_activation_token_v1 *token; + // The surface requesting for activation. + struct wlr_surface *surface; +}; + +struct wlr_xdg_activation_v1 *wlr_xdg_activation_v1_create( + struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_xdg_activation_v1_destroy(struct wlr_xdg_activation_v1 *activation, + bool destroy_global_safe); + +struct wlr_xdg_activation_token_v1 *wlr_xdg_activation_token_v1_create( + struct wlr_xdg_activation_v1 *activation); + +void wlr_xdg_activation_token_v1_destroy( + struct wlr_xdg_activation_token_v1 *token); + +struct wlr_xdg_activation_token_v1 *wlr_xdg_activation_v1_find_token( + struct wlr_xdg_activation_v1 *activation, const char *token_str); + +// Get a string suitable for exporting to launched clients +const char *wlr_xdg_activation_token_v1_get_name( + struct wlr_xdg_activation_token_v1 *token); + +// Add a token to the pool of known tokens +struct wlr_xdg_activation_token_v1 *wlr_xdg_activation_v1_add_token( + struct wlr_xdg_activation_v1 *activation, const char *token_str); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_xdg_decoration_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_xdg_decoration_v1.h new file mode 100644 index 0000000000..a4d77ba3cd --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_xdg_decoration_v1.h @@ -0,0 +1,89 @@ +#ifndef WLR_TYPES_WLR_XDG_DECORATION_V1 +#define WLR_TYPES_WLR_XDG_DECORATION_V1 + +#include +#include +#include + +enum wlr_xdg_toplevel_decoration_v1_mode { + WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_NONE = 0, + WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE = 1, + WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE = 2, +}; + +struct wlr_xdg_decoration_manager_v1 { + struct wl_global *global; + struct wl_list decorations; // wlr_xdg_toplevel_decoration.link + + struct { + struct wl_signal new_toplevel_decoration; // struct wlr_xdg_toplevel_decoration + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_toplevel_decoration_v1_configure { + struct wl_list link; // wlr_xdg_toplevel_decoration.configure_list + struct wlr_xdg_surface_configure *surface_configure; + enum wlr_xdg_toplevel_decoration_v1_mode mode; +}; + +struct wlr_xdg_toplevel_decoration_v1_state { + enum wlr_xdg_toplevel_decoration_v1_mode mode; +}; + +struct wlr_xdg_toplevel_decoration_v1 { + struct wl_resource *resource; + struct wlr_xdg_toplevel *toplevel; + struct wlr_xdg_decoration_manager_v1 *manager; + struct wl_list link; // wlr_xdg_decoration_manager_v1.link + + struct wlr_xdg_toplevel_decoration_v1_state current, pending; + + enum wlr_xdg_toplevel_decoration_v1_mode scheduled_mode; + enum wlr_xdg_toplevel_decoration_v1_mode requested_mode; + + struct wl_list configure_list; // wlr_xdg_toplevel_decoration_v1_configure.link + + struct { + struct wl_signal destroy; + struct wl_signal request_mode; + } events; + + void *data; + + struct { + struct wl_listener toplevel_destroy; + struct wl_listener surface_configure; + struct wl_listener surface_ack_configure; + + struct wlr_surface_synced synced; + } WLR_PRIVATE; +}; + +struct wlr_xdg_decoration_manager_v1 * + wlr_xdg_decoration_manager_v1_create(struct wl_display *display); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_xdg_decoration_manager_v1_destroy(struct wlr_xdg_decoration_manager_v1 *manager, + bool destroy_global_safe); + +uint32_t wlr_xdg_toplevel_decoration_v1_set_mode( + struct wlr_xdg_toplevel_decoration_v1 *decoration, + enum wlr_xdg_toplevel_decoration_v1_mode mode); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_xdg_dialog_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_xdg_dialog_v1.h new file mode 100644 index 0000000000..ea271838ff --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_xdg_dialog_v1.h @@ -0,0 +1,71 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_XDG_DIALOG_V1_H +#define WLR_TYPES_WLR_XDG_DIALOG_V1_H + +#include +#include +#include + +struct wlr_xdg_dialog_v1 { + struct wl_resource *resource; + struct wlr_xdg_toplevel *xdg_toplevel; + + bool modal; + + struct { + struct wl_signal destroy; + // Corresponds to both xdg_dialog_v1.set_modal and xdg_dialog_v1.unset_modal + struct wl_signal set_modal; + } events; + + struct { + struct wlr_addon surface_addon; + + struct wl_listener xdg_toplevel_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_wm_dialog_v1 { + struct wl_global *global; + + struct { + struct wl_signal destroy; + struct wl_signal new_dialog; // struct wlr_xdg_dialog_v1 + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_wm_dialog_v1 *wlr_xdg_wm_dialog_v1_create(struct wl_display *display, + uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_xdg_wm_dialog_v1_destroy(struct wlr_xdg_wm_dialog_v1 *wm, bool destroy_global_safe); + +/** + * Get a struct wlr_xdg_dialog_v1 from a struct wlr_xdg_toplevel. + * + * Returns NULL if there's no xdg_dialog_v1 associated with the xdg toplevel. + */ +struct wlr_xdg_dialog_v1 *wlr_xdg_dialog_v1_try_from_wlr_xdg_toplevel( + struct wlr_xdg_toplevel *xdg_toplevel); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_xdg_foreign_registry.h b/3rdparty/wlroots/include/wlr/types/wlr_xdg_foreign_registry.h new file mode 100644 index 0000000000..ffefb7438d --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_xdg_foreign_registry.h @@ -0,0 +1,91 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_XDG_FOREIGN_REGISTRY_H +#define WLR_TYPES_WLR_XDG_FOREIGN_REGISTRY_H + +#include +#include + +#define WLR_XDG_FOREIGN_HANDLE_SIZE 37 + +/** + * struct wlr_xdg_foreign_registry is used for storing a list of exported + * surfaces with the xdg-foreign family of protocols. + * + * It can be used to allow interoperability between clients using different + * versions of the protocol (if all versions use the same registry). + */ +struct wlr_xdg_foreign_registry { + struct wl_list exported_surfaces; // struct wlr_xdg_foreign_exported_surface + + struct { + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_foreign_exported { + struct wl_list link; // wlr_xdg_foreign_registry.exported_surfaces + struct wlr_xdg_foreign_registry *registry; + + struct wlr_xdg_toplevel *toplevel; + + char handle[WLR_XDG_FOREIGN_HANDLE_SIZE]; + + struct { + struct wl_signal destroy; + } events; +}; + +/** + * Create an empty struct wlr_xdg_foreign_registry. + * + * It will be destroyed when the associated display is destroyed. + */ +struct wlr_xdg_foreign_registry *wlr_xdg_foreign_registry_create( + struct wl_display *display); + +/** + * Destroy the foreign surface registry. + * + * destroy_global_safe is ignored because the registry has no globals. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_xdg_foreign_registry_destroy(struct wlr_xdg_foreign_registry *registry, + bool destroy_global_safe); + +/** + * Add the given exported surface to the registry and assign it a unique handle. + * The caller is responsible for removing the exported surface from the repository + * if it is destroyed. + * + * Returns true if the initialization was successful. + */ +bool wlr_xdg_foreign_exported_init(struct wlr_xdg_foreign_exported *surface, + struct wlr_xdg_foreign_registry *registry); + +/** + * Find an exported surface with the given handle, or NULL if such a surface + * does not exist. + */ +struct wlr_xdg_foreign_exported *wlr_xdg_foreign_registry_find_by_handle( + struct wlr_xdg_foreign_registry *registry, const char *handle); + +/** + * Remove the given surface from the registry it was previously added in. + */ +void wlr_xdg_foreign_exported_finish(struct wlr_xdg_foreign_exported *surface); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_xdg_foreign_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_xdg_foreign_v1.h new file mode 100644 index 0000000000..0757f81992 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_xdg_foreign_v1.h @@ -0,0 +1,86 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_XDG_FOREIGN_V1_H +#define WLR_TYPES_WLR_XDG_FOREIGN_V1_H + +#include +#include +#include + +struct wlr_xdg_foreign_v1 { + struct { + struct wl_global *global; + struct wl_list objects; // wlr_xdg_exported_v1.link or wlr_xdg_imported_v1.link + } exporter, importer; + + struct wlr_xdg_foreign_registry *registry; + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener foreign_registry_destroy; + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_exported_v1 { + struct wlr_xdg_foreign_exported base; + + struct wl_resource *resource; + struct wl_list link; // wlr_xdg_foreign_v1.exporter.objects + + struct { + struct wl_listener xdg_toplevel_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_imported_v1 { + struct wlr_xdg_foreign_exported *exported; + + struct wl_resource *resource; + struct wl_list link; // wlr_xdg_foreign_v1.importer.objects + struct wl_list children; + + struct { + struct wl_listener exported_destroyed; + } WLR_PRIVATE; +}; + +struct wlr_xdg_imported_child_v1 { + struct wlr_xdg_imported_v1 *imported; + struct wlr_xdg_toplevel *toplevel; + + struct wl_list link; // wlr_xdg_imported_v1.children + + struct { + struct wl_listener xdg_toplevel_destroy; + struct wl_listener xdg_toplevel_set_parent; + } WLR_PRIVATE; +}; + +struct wlr_xdg_foreign_v1 *wlr_xdg_foreign_v1_create( + struct wl_display *display, struct wlr_xdg_foreign_registry *registry); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_xdg_foreign_v1_destroy(struct wlr_xdg_foreign_v1 *foreign, bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_xdg_foreign_v2.h b/3rdparty/wlroots/include/wlr/types/wlr_xdg_foreign_v2.h new file mode 100644 index 0000000000..89a181494a --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_xdg_foreign_v2.h @@ -0,0 +1,86 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_XDG_FOREIGN_V2_H +#define WLR_TYPES_WLR_XDG_FOREIGN_V2_H + +#include +#include +#include + +struct wlr_xdg_foreign_v2 { + struct { + struct wl_global *global; + struct wl_list objects; // wlr_xdg_exported_v2.link or wlr_xdg_imported_v2.link + } exporter, importer; + + struct wlr_xdg_foreign_registry *registry; + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener foreign_registry_destroy; + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_exported_v2 { + struct wlr_xdg_foreign_exported base; + + struct wl_resource *resource; + struct wl_list link; // wlr_xdg_foreign_v2.exporter.objects + + struct { + struct wl_listener xdg_toplevel_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_imported_v2 { + struct wlr_xdg_foreign_exported *exported; + + struct wl_resource *resource; + struct wl_list link; // wlr_xdg_foreign_v2.importer.objects + struct wl_list children; + + struct { + struct wl_listener exported_destroyed; + } WLR_PRIVATE; +}; + +struct wlr_xdg_imported_child_v2 { + struct wlr_xdg_imported_v2 *imported; + struct wlr_xdg_toplevel *toplevel; + + struct wl_list link; // wlr_xdg_imported_v2.children + + struct { + struct wl_listener xdg_toplevel_destroy; + struct wl_listener xdg_toplevel_set_parent; + } WLR_PRIVATE; +}; + +struct wlr_xdg_foreign_v2 *wlr_xdg_foreign_v2_create( + struct wl_display *display, struct wlr_xdg_foreign_registry *registry); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_xdg_foreign_v2_destroy(struct wlr_xdg_foreign_v2 *foreign, bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_xdg_output_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_xdg_output_v1.h new file mode 100644 index 0000000000..37b2973200 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_xdg_output_v1.h @@ -0,0 +1,65 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_XDG_OUTPUT_V1_H +#define WLR_TYPES_WLR_XDG_OUTPUT_V1_H +#include +#include +#include + +struct wlr_xdg_output_v1 { + struct wlr_xdg_output_manager_v1 *manager; + struct wl_list resources; + struct wl_list link; + + struct wlr_output_layout_output *layout_output; + + int32_t x, y; + int32_t width, height; + + struct { + struct wl_listener destroy; + struct wl_listener description; + } WLR_PRIVATE; +}; + +struct wlr_xdg_output_manager_v1 { + struct wl_global *global; + struct wlr_output_layout *layout; + + struct wl_list outputs; + + struct { + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + struct wl_listener layout_add; + struct wl_listener layout_change; + struct wl_listener layout_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_output_manager_v1 *wlr_xdg_output_manager_v1_create( + struct wl_display *display, struct wlr_output_layout *layout); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_xdg_output_manager_v1_destroy(struct wlr_xdg_output_manager_v1 *manager, + bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_xdg_shell.h b/3rdparty/wlroots/include/wlr/types/wlr_xdg_shell.h new file mode 100644 index 0000000000..24a1849154 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_xdg_shell.h @@ -0,0 +1,606 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_XDG_SHELL_H +#define WLR_TYPES_WLR_XDG_SHELL_H + +#include +#include +#include +#include +#include +#include + +struct wlr_xdg_shell { + struct wl_global *global; + uint32_t version; + struct wl_list clients; + struct wl_list popup_grabs; + uint32_t ping_timeout; + + struct { + struct wl_signal new_surface; // struct wlr_xdg_surface + struct wl_signal new_toplevel; // struct wlr_xdg_toplevel + struct wl_signal new_popup; // struct wlr_xdg_popup + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_client { + struct wlr_xdg_shell *shell; + struct wl_resource *resource; + struct wl_client *client; + struct wl_list surfaces; + + struct wl_list link; // wlr_xdg_shell.clients + + uint32_t ping_serial; + struct wl_event_source *ping_timer; +}; + +struct wlr_xdg_positioner_rules { + struct wlr_box anchor_rect; + enum xdg_positioner_anchor anchor; + enum xdg_positioner_gravity gravity; + enum xdg_positioner_constraint_adjustment constraint_adjustment; + + bool reactive; + + bool has_parent_configure_serial; + uint32_t parent_configure_serial; + + struct { + int32_t width, height; + } size, parent_size; + + struct { + int32_t x, y; + } offset; +}; + +struct wlr_xdg_positioner { + struct wl_resource *resource; + struct wlr_xdg_positioner_rules rules; +}; + +struct wlr_xdg_popup_state { + // Position of the popup relative to the upper left corner of + // the window geometry of the parent surface + struct wlr_box geometry; + + bool reactive; +}; + +enum wlr_xdg_popup_configure_field { + WLR_XDG_POPUP_CONFIGURE_REPOSITION_TOKEN = 1 << 0, +}; + +struct wlr_xdg_popup_configure { + uint32_t fields; // enum wlr_xdg_popup_configure_field + struct wlr_box geometry; + struct wlr_xdg_positioner_rules rules; + uint32_t reposition_token; +}; + +struct wlr_xdg_popup { + struct wlr_xdg_surface *base; + struct wl_list link; + + struct wl_resource *resource; + struct wlr_surface *parent; + struct wlr_seat *seat; + + struct wlr_xdg_popup_configure scheduled; + + struct wlr_xdg_popup_state current, pending; + + struct { + struct wl_signal destroy; + + struct wl_signal reposition; + } events; + + struct wl_list grab_link; // wlr_xdg_popup_grab.popups + + struct { + struct wlr_surface_synced synced; + } WLR_PRIVATE; +}; + +// each seat gets a popup grab +struct wlr_xdg_popup_grab { + struct wl_client *client; + struct wlr_seat_pointer_grab pointer_grab; + struct wlr_seat_keyboard_grab keyboard_grab; + struct wlr_seat_touch_grab touch_grab; + struct wlr_seat *seat; + struct wl_list popups; + struct wl_list link; // wlr_xdg_shell.popup_grabs + + struct { + struct wl_listener seat_destroy; + } WLR_PRIVATE; +}; + +enum wlr_xdg_surface_role { + WLR_XDG_SURFACE_ROLE_NONE, + WLR_XDG_SURFACE_ROLE_TOPLEVEL, + WLR_XDG_SURFACE_ROLE_POPUP, +}; + +struct wlr_xdg_toplevel_state { + bool maximized, fullscreen, resizing, activated, suspended; + uint32_t tiled; // enum wlr_edges + uint32_t constrained; // enum wlr_edges + int32_t width, height; + int32_t max_width, max_height; + int32_t min_width, min_height; +}; + +enum wlr_xdg_toplevel_wm_capabilities { + WLR_XDG_TOPLEVEL_WM_CAPABILITIES_WINDOW_MENU = 1 << 0, + WLR_XDG_TOPLEVEL_WM_CAPABILITIES_MAXIMIZE = 1 << 1, + WLR_XDG_TOPLEVEL_WM_CAPABILITIES_FULLSCREEN = 1 << 2, + WLR_XDG_TOPLEVEL_WM_CAPABILITIES_MINIMIZE = 1 << 3, +}; + +enum wlr_xdg_toplevel_configure_field { + WLR_XDG_TOPLEVEL_CONFIGURE_BOUNDS = 1 << 0, + WLR_XDG_TOPLEVEL_CONFIGURE_WM_CAPABILITIES = 1 << 1, +}; + +/** + * State set in an toplevel configure sequence. + */ +struct wlr_xdg_toplevel_configure { + // Bitmask of optional fields which are set + uint32_t fields; // enum wlr_xdg_toplevel_configure_field + + // The following fields must always be set to reflect the current state + bool maximized, fullscreen, resizing, activated, suspended; + uint32_t tiled; // enum wlr_edges + uint32_t constrained; // enum wlr_edges + int32_t width, height; + + // Only for WLR_XDG_TOPLEVEL_CONFIGURE_BOUNDS + struct { + int32_t width, height; + } bounds; + // Only for WLR_XDG_TOPLEVEL_CONFIGURE_WM_CAPABILITIES + uint32_t wm_capabilities; // enum wlr_xdg_toplevel_wm_capabilities +}; + +struct wlr_xdg_toplevel_requested { + bool maximized, minimized, fullscreen; + struct wlr_output *fullscreen_output; + + struct { + struct wl_listener fullscreen_output_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_toplevel { + struct wl_resource *resource; + struct wlr_xdg_surface *base; + + struct wlr_xdg_toplevel *parent; + + struct wlr_xdg_toplevel_state current, pending; + + // Properties to be sent to the client in the next configure event. + struct wlr_xdg_toplevel_configure scheduled; + + // Properties that the client has requested. Intended to be checked + // by the compositor on surface map and state change requests (such as + // xdg_toplevel.set_fullscreen) and handled accordingly. + struct wlr_xdg_toplevel_requested requested; + + char *title; + char *app_id; + + struct { + struct wl_signal destroy; + + // Note: as per xdg-shell protocol, the compositor has to + // handle state requests by sending a configure event, + // even if it didn't actually change the state. Therefore, + // every compositor implementing xdg-shell support *must* + // listen to these signals and schedule a configure event + // immediately or at some time in the future; not doing so + // is a protocol violation. + struct wl_signal request_maximize; + struct wl_signal request_fullscreen; + + struct wl_signal request_minimize; + struct wl_signal request_move; + struct wl_signal request_resize; + struct wl_signal request_show_window_menu; + struct wl_signal set_parent; + struct wl_signal set_title; + struct wl_signal set_app_id; + } events; + + struct { + struct wlr_surface_synced synced; + + struct wl_listener parent_unmap; + } WLR_PRIVATE; +}; + +struct wlr_xdg_surface_configure { + struct wlr_xdg_surface *surface; + struct wl_list link; // wlr_xdg_surface.configure_list + uint32_t serial; + + union { + struct wlr_xdg_toplevel_configure *toplevel_configure; + struct wlr_xdg_popup_configure *popup_configure; + }; +}; + +enum wlr_xdg_surface_state_field { + WLR_XDG_SURFACE_STATE_WINDOW_GEOMETRY = 1 << 0, +}; + +struct wlr_xdg_surface_state { + uint32_t committed; // enum wlr_xdg_surface_state_field + + struct wlr_box geometry; + + uint32_t configure_serial; +}; + +/** + * An xdg-surface is a user interface element requiring management by the + * compositor. An xdg-surface alone isn't useful, a role should be assigned to + * it in order to map it. + */ +struct wlr_xdg_surface { + struct wlr_xdg_client *client; + struct wl_resource *resource; + struct wlr_surface *surface; + struct wl_list link; // wlr_xdg_client.surfaces + + /** + * The lifetime-bound role of the xdg_surface. WLR_XDG_SURFACE_ROLE_NONE + * if the role was never set. + */ + enum wlr_xdg_surface_role role; + /** + * The role object representing the role. NULL if the object was destroyed. + */ + struct wl_resource *role_resource; + + // NULL if the role resource is inert + union { + struct wlr_xdg_toplevel *toplevel; + struct wlr_xdg_popup *popup; + }; + + struct wl_list popups; // wlr_xdg_popup.link + + bool configured; + struct wl_event_source *configure_idle; + uint32_t scheduled_serial; + struct wl_list configure_list; + + struct wlr_xdg_surface_state current, pending; + + // Whether the surface is ready to receive configure events + bool initialized; + // Whether the latest commit is an initial commit + bool initial_commit; + + struct wlr_box geometry; + + struct { + struct wl_signal destroy; + struct wl_signal ping_timeout; + struct wl_signal new_popup; + + // for protocol extensions + struct wl_signal configure; // struct wlr_xdg_surface_configure + struct wl_signal ack_configure; // struct wlr_xdg_surface_configure + } events; + + void *data; + + struct { + struct wlr_surface_synced synced; + + struct wl_listener role_resource_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_toplevel_move_event { + struct wlr_xdg_toplevel *toplevel; + struct wlr_seat_client *seat; + uint32_t serial; +}; + +struct wlr_xdg_toplevel_resize_event { + struct wlr_xdg_toplevel *toplevel; + struct wlr_seat_client *seat; + uint32_t serial; + uint32_t edges; +}; + +struct wlr_xdg_toplevel_show_window_menu_event { + struct wlr_xdg_toplevel *toplevel; + struct wlr_seat_client *seat; + uint32_t serial; + int32_t x, y; +}; + +/** + * Create the xdg_wm_base global with the specified version. + */ +struct wlr_xdg_shell *wlr_xdg_shell_create(struct wl_display *display, + uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_xdg_shell_destroy(struct wlr_xdg_shell *xdg_shell, bool destroy_global_safe); + +/** Get the corresponding struct wlr_xdg_surface from a resource. + * + * Aborts if the resource doesn't have the correct type. Returns NULL if the + * resource is inert. + */ +struct wlr_xdg_surface *wlr_xdg_surface_from_resource( + struct wl_resource *resource); + +/** Get the corresponding struct wlr_xdg_popup from a resource. + * + * Aborts if the resource doesn't have the correct type. Returns NULL if the + * resource is inert. + */ +struct wlr_xdg_popup *wlr_xdg_popup_from_resource( + struct wl_resource *resource); + +/** Get the corresponding struct wlr_xdg_toplevel from a resource. + * + * Aborts if the resource doesn't have the correct type. Returns NULL if the + * resource is inert. + */ +struct wlr_xdg_toplevel *wlr_xdg_toplevel_from_resource( + struct wl_resource *resource); + +/** Get the corresponding struct wlr_xdg_positioner from a resource. + * + * Aborts if the resource doesn't have the correct type. + */ +struct wlr_xdg_positioner *wlr_xdg_positioner_from_resource( + struct wl_resource *resource); + +/** + * Send a ping to the surface. If the surface does not respond in a reasonable + * amount of time, the ping_timeout event will be emitted. + */ +void wlr_xdg_surface_ping(struct wlr_xdg_surface *surface); + +/** + * Configure the toplevel. Returns the associated configure serial. + */ +uint32_t wlr_xdg_toplevel_configure(struct wlr_xdg_toplevel *toplevel, + const struct wlr_xdg_toplevel_configure *configure); + +/** + * Request that this toplevel surface be the given size. Returns the associated + * configure serial. + */ +uint32_t wlr_xdg_toplevel_set_size(struct wlr_xdg_toplevel *toplevel, + int32_t width, int32_t height); + +/** + * Request that this toplevel show itself in an activated or deactivated + * state. Returns the associated configure serial. + */ +uint32_t wlr_xdg_toplevel_set_activated(struct wlr_xdg_toplevel *toplevel, + bool activated); + +/** + * Request that this toplevel consider itself maximized or not + * maximized. Returns the associated configure serial. + */ +uint32_t wlr_xdg_toplevel_set_maximized(struct wlr_xdg_toplevel *toplevel, + bool maximized); + +/** + * Request that this toplevel consider itself fullscreen or not + * fullscreen. Returns the associated configure serial. + */ +uint32_t wlr_xdg_toplevel_set_fullscreen(struct wlr_xdg_toplevel *toplevel, + bool fullscreen); + +/** + * Request that this toplevel consider itself to be resizing or not + * resizing. Returns the associated configure serial. + */ +uint32_t wlr_xdg_toplevel_set_resizing(struct wlr_xdg_toplevel *toplevel, + bool resizing); + +/** + * Request that this toplevel consider itself in a tiled layout and some + * edges are adjacent to another part of the tiling grid. `tiled_edges` is a + * bitfield of enum wlr_edges. Returns the associated configure serial. + */ +uint32_t wlr_xdg_toplevel_set_tiled(struct wlr_xdg_toplevel *toplevel, + uint32_t tiled_edges); + +/** + * Configure the recommended bounds for the client's window geometry size. + * Returns the associated configure serial. + */ +uint32_t wlr_xdg_toplevel_set_bounds(struct wlr_xdg_toplevel *toplevel, + int32_t width, int32_t height); + +/** + * Configure the window manager capabilities for this toplevel. `caps` is a + * bitfield of `enum wlr_xdg_toplevel_wm_capabilities`. Returns the associated + * configure serial. + */ +uint32_t wlr_xdg_toplevel_set_wm_capabilities(struct wlr_xdg_toplevel *toplevel, + uint32_t caps); + +/** + * Request that this toplevel consider itself suspended or not + * suspended. Returns the associated configure serial. + */ +uint32_t wlr_xdg_toplevel_set_suspended(struct wlr_xdg_toplevel *toplevel, + bool suspended); + +/** + * Request that this toplevel consider itself constrained and doesn't attempt to + * resize from some edges. `constrained_edges` is a bitfield of enum wlr_edges. + * Returns the associated configure serial. + */ +uint32_t wlr_xdg_toplevel_set_constrained(struct wlr_xdg_toplevel *toplevel, + uint32_t constrained_edges); + +/** + * Request that this toplevel closes. + */ +void wlr_xdg_toplevel_send_close(struct wlr_xdg_toplevel *toplevel); + +/** + * Sets the parent of this toplevel. Parent can be NULL. + * + * Returns true on success, false if setting the parent would create a loop. + */ +bool wlr_xdg_toplevel_set_parent(struct wlr_xdg_toplevel *toplevel, + struct wlr_xdg_toplevel *parent); + +/** + * Notify the client that the popup has been dismissed and destroy the + * struct wlr_xdg_popup, rendering the resource inert. + */ +void wlr_xdg_popup_destroy(struct wlr_xdg_popup *popup); + +/** + * Get the position for this popup in the surface parent's coordinate system. + */ +void wlr_xdg_popup_get_position(struct wlr_xdg_popup *popup, + double *popup_sx, double *popup_sy); + +/** + * Returns true if a positioner is complete. + */ +bool wlr_xdg_positioner_is_complete(struct wlr_xdg_positioner *positioner); + +/** + * Get the geometry based on positioner rules. + */ +void wlr_xdg_positioner_rules_get_geometry( + const struct wlr_xdg_positioner_rules *rules, struct wlr_box *box); + +/** + * Unconstrain the box from the constraint area according to positioner rules. + */ +void wlr_xdg_positioner_rules_unconstrain_box( + const struct wlr_xdg_positioner_rules *rules, + const struct wlr_box *constraint, struct wlr_box *box); + +/** + * Convert the given coordinates in the popup coordinate system to the toplevel + * surface coordinate system. + */ +void wlr_xdg_popup_get_toplevel_coords(struct wlr_xdg_popup *popup, + int popup_sx, int popup_sy, int *toplevel_sx, int *toplevel_sy); + +/** + * Set the geometry of this popup to unconstrain it according to its + * xdg-positioner rules. The box should be in the popup's root toplevel parent + * surface coordinate system. + */ +void wlr_xdg_popup_unconstrain_from_box(struct wlr_xdg_popup *popup, + const struct wlr_box *toplevel_space_box); + +/** + * Find a surface within this xdg-surface tree at the given surface-local + * coordinates. Returns the surface and coordinates in the leaf surface + * coordinate system or NULL if no surface is found at that location. + */ +struct wlr_surface *wlr_xdg_surface_surface_at( + struct wlr_xdg_surface *surface, double sx, double sy, + double *sub_x, double *sub_y); + +/** + * Find a surface within this xdg-surface's popup tree at the given + * surface-local coordinates. Returns the surface and coordinates in the leaf + * surface coordinate system or NULL if no surface is found at that location. + */ +struct wlr_surface *wlr_xdg_surface_popup_surface_at( + struct wlr_xdg_surface *surface, double sx, double sy, + double *sub_x, double *sub_y); + +/** + * Get a struct wlr_xdg_surface from a struct wlr_surface. + * + * Returns NULL if the surface doesn't have the xdg_surface role or + * if the xdg_surface has been destroyed. + */ +struct wlr_xdg_surface *wlr_xdg_surface_try_from_wlr_surface(struct wlr_surface *surface); + +/** + * Get a struct wlr_xdg_toplevel from a struct wlr_surface. + * + * Returns NULL if the surface doesn't have the xdg_surface role, the + * xdg_surface is not a toplevel, or the xdg_surface/xdg_toplevel objects have + * been destroyed. + */ +struct wlr_xdg_toplevel *wlr_xdg_toplevel_try_from_wlr_surface(struct wlr_surface *surface); + +/** + * Get a struct wlr_xdg_popup from a struct wlr_surface. + * + * Returns NULL if the surface doesn't have the xdg_surface role, the + * xdg_surface is not a popup, or the xdg_surface/xdg_popup objects have + * been destroyed. + */ +struct wlr_xdg_popup *wlr_xdg_popup_try_from_wlr_surface(struct wlr_surface *surface); + +/** + * Call `iterator` on each mapped surface and popup in the xdg-surface tree + * (whether or not this xdg-surface is mapped), with the surface's position + * relative to the root xdg-surface. The function is called from root to leaves + * (in rendering order). + */ +void wlr_xdg_surface_for_each_surface(struct wlr_xdg_surface *surface, + wlr_surface_iterator_func_t iterator, void *user_data); + +/** + * Call `iterator` on each mapped popup's surface and popup's subsurface in the + * xdg-surface tree (whether or not this xdg-surface is mapped), with the + * surfaces's position relative to the root xdg-surface. The function is called + * from root to leaves (in rendering order). + */ +void wlr_xdg_surface_for_each_popup_surface(struct wlr_xdg_surface *surface, + wlr_surface_iterator_func_t iterator, void *user_data); + +/** + * Schedule a surface configuration. This should only be called by protocols + * extending the shell. + */ +uint32_t wlr_xdg_surface_schedule_configure(struct wlr_xdg_surface *surface); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_xdg_system_bell_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_xdg_system_bell_v1.h new file mode 100644 index 0000000000..dd172cf687 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_xdg_system_bell_v1.h @@ -0,0 +1,48 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_XDG_SYSTEM_BELL_V1_H +#define WLR_TYPES_WLR_XDG_SYSTEM_BELL_V1_H + +#include +#include + +struct wlr_xdg_system_bell_v1 { + struct wl_global *global; + + struct { + struct wl_signal destroy; + struct wl_signal ring; // struct wlr_xdg_system_bell_v1_ring_event + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_system_bell_v1_ring_event { + struct wl_client *client; + struct wlr_surface *surface; // May be NULL +}; + +struct wlr_xdg_system_bell_v1 *wlr_xdg_system_bell_v1_create(struct wl_display *display, + uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_xdg_system_bell_v1_destroy(struct wlr_xdg_system_bell_v1 *bell, bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_xdg_toplevel_icon_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_xdg_toplevel_icon_v1.h new file mode 100644 index 0000000000..fbf7f9fe4f --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_xdg_toplevel_icon_v1.h @@ -0,0 +1,94 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_XDG_TOPLEVEL_ICON_V1_H +#define WLR_TYPES_WLR_XDG_TOPLEVEL_ICON_V1_H + +#include +#include + +#include + +struct wlr_xdg_toplevel_icon_manager_v1 { + struct wl_global *global; + + struct wl_list resources; + + int *sizes; + size_t n_sizes; + + struct { + struct wl_signal set_icon; // struct wlr_xdg_toplevel_icon_manager_v1_set_icon_event + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_toplevel_icon_manager_v1_set_icon_event { + struct wlr_xdg_toplevel *toplevel; + + // Must be referenced to be used after the event is emitted + struct wlr_xdg_toplevel_icon_v1 *icon; // May be NULL +}; + +struct wlr_xdg_toplevel_icon_v1_buffer { + struct wlr_buffer *buffer; + int scale; + + struct wl_list link; // wlr_xdg_toplevel_icon_v1.buffers +}; + +struct wlr_xdg_toplevel_icon_v1 { + char *name; // May be NULL + struct wl_list buffers; // wlr_xdg_toplevel_icon_v1_buffer.link + + struct { + int n_refs; + bool immutable; + } WLR_PRIVATE; +}; + +struct wlr_xdg_toplevel_icon_manager_v1 *wlr_xdg_toplevel_icon_manager_v1_create( + struct wl_display *display, uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_xdg_toplevel_icon_manager_v1_destroy(struct wlr_xdg_toplevel_icon_manager_v1 *manager, + bool destroy_global_safe); + +/** + * Set icon size preferences. + * + * The list may be empty. + */ +void wlr_xdg_toplevel_icon_manager_v1_set_sizes(struct wlr_xdg_toplevel_icon_manager_v1 *manager, + int *sizes, size_t n_sizes); + +/** + * Reference an icon. + */ +struct wlr_xdg_toplevel_icon_v1 *wlr_xdg_toplevel_icon_v1_ref( + struct wlr_xdg_toplevel_icon_v1 *icon); + +/** + * Unreference an icon. When the icon reference count reaches 0, it is destroyed. + */ +void wlr_xdg_toplevel_icon_v1_unref(struct wlr_xdg_toplevel_icon_v1 *icon); + +#endif diff --git a/3rdparty/wlroots/include/wlr/types/wlr_xdg_toplevel_tag_v1.h b/3rdparty/wlroots/include/wlr/types/wlr_xdg_toplevel_tag_v1.h new file mode 100644 index 0000000000..0edac33909 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/types/wlr_xdg_toplevel_tag_v1.h @@ -0,0 +1,55 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_XDG_TOPLEVEL_TAG_V1_H +#define WLR_TYPES_WLR_XDG_TOPLEVEL_TAG_V1_H + +#include +#include + +struct wlr_xdg_toplevel_tag_manager_v1 { + struct wl_global *global; + + struct { + struct wl_signal set_tag; // struct wlr_xdg_toplevel_tag_manager_v1_set_tag_event + struct wl_signal set_description; // struct wlr_xdg_toplevel_tag_manager_v1_set_description_event + struct wl_signal destroy; + } events; + + struct { + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xdg_toplevel_tag_manager_v1_set_tag_event { + struct wlr_xdg_toplevel *toplevel; + const char *tag; +}; + +struct wlr_xdg_toplevel_tag_manager_v1_set_description_event { + struct wlr_xdg_toplevel *toplevel; + const char *description; +}; + +struct wlr_xdg_toplevel_tag_manager_v1 *wlr_xdg_toplevel_tag_manager_v1_create( + struct wl_display *display, uint32_t version); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_xdg_toplevel_tag_manager_v1_destroy(struct wlr_xdg_toplevel_tag_manager_v1 *manager, + bool destroy_global_safe); + +#endif diff --git a/3rdparty/wlroots/include/wlr/util/addon.h b/3rdparty/wlroots/include/wlr/util/addon.h new file mode 100644 index 0000000000..8819acce25 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/util/addon.h @@ -0,0 +1,47 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_UTIL_ADDON_H +#define WLR_UTIL_ADDON_H + +#include + +struct wlr_addon_set { + struct { + struct wl_list addons; + } WLR_PRIVATE; +}; + +struct wlr_addon; + +struct wlr_addon_interface { + const char *name; + // Has to call wlr_addon_finish() + void (*destroy)(struct wlr_addon *addon); +}; + +struct wlr_addon { + const struct wlr_addon_interface *impl; + + struct { + const void *owner; + struct wl_list link; + } WLR_PRIVATE; +}; + +void wlr_addon_set_init(struct wlr_addon_set *set); +void wlr_addon_set_finish(struct wlr_addon_set *set); + +void wlr_addon_init(struct wlr_addon *addon, struct wlr_addon_set *set, + const void *owner, const struct wlr_addon_interface *impl); +void wlr_addon_finish(struct wlr_addon *addon); + +struct wlr_addon *wlr_addon_find(struct wlr_addon_set *set, const void *owner, + const struct wlr_addon_interface *impl); + +#endif diff --git a/3rdparty/wlroots/include/wlr/util/box.h b/3rdparty/wlroots/include/wlr/util/box.h new file mode 100644 index 0000000000..64dcbc5cf8 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/util/box.h @@ -0,0 +1,122 @@ +/* +* This is a stable interface of wlroots. Future changes will be limited to: + * + * - New functions + * - New struct members + * - New enum members + * + * Note that wlroots does not make an ABI compatibility promise - in the future, + * the layout and size of structs used by wlroots may change, requiring code + * depending on this header to be recompiled (but not edited). + * + * Breaking changes are announced in the release notes and follow a 1-year + * deprecation schedule. + */ +#ifndef WLR_UTIL_BOX_H +#define WLR_UTIL_BOX_H + +#include +#include + +/** + * A box representing a rectangle region in a 2D space. + * + * The x and y coordinates are inclusive, and the width and height lengths are + * exclusive. In other words, the box starts from the coordinates (x, y), and + * goes up to but not including (x + width, y + height). + */ +struct wlr_box { + int x, y; + int width, height; +}; + +/** + * A floating-point box representing a rectangle region in a 2D space. + * + * struct wlr_fbox has the same semantics as struct wlr_box. + */ +struct wlr_fbox { + double x, y; + double width, height; +}; + +/** + * Functions below accept NULL where a box is expected, which is treated + * the same as an empty box. + */ + +/** + * Finds the closest point within the box bounds. + * + * Returns NAN if the box is empty. + */ +void wlr_box_closest_point(const struct wlr_box *box, double x, double y, + double *dest_x, double *dest_y); + +/** + * Gives the intersecting box between two struct wlr_box. + * + * Returns an empty box if the provided boxes don't intersect. + */ +bool wlr_box_intersection(struct wlr_box *dest, const struct wlr_box *box_a, + const struct wlr_box *box_b); + +/** + * Verifies if a point is contained within the bounds of a given struct wlr_box. + * + * For example: + * + * - A point at (100, 50) is not contained in the box (0, 0, 100, 50). + * - A point at (10, 10) is contained in the box (10, 0, 50, 50). + */ +bool wlr_box_contains_point(const struct wlr_box *box, double x, double y); + +/** + * Verifies that a box is fully contained within another box. + * + * Returns true if the "smaller" box is fully contained within the "bigger" box. + * If either of the boxes are empty, false is returned. + */ +bool wlr_box_contains_box(const struct wlr_box *bigger, const struct wlr_box *smaller); + +/** + * Checks whether a box is empty or not. + * + * A box is considered empty if its width and/or height is zero or negative. + */ +bool wlr_box_empty(const struct wlr_box *box); + +/** + * Transforms a box inside a (0, 0, width, height) box. + */ +void wlr_box_transform(struct wlr_box *dest, const struct wlr_box *box, + enum wl_output_transform transform, int width, int height); + +/** + * Checks whether a box is empty or not. + * + * A box is considered empty if its width and/or height is zero or negative. + */ +bool wlr_fbox_empty(const struct wlr_fbox *box); + +/** + * Transforms a floating-point box inside a (0, 0, width, height) box. + */ +void wlr_fbox_transform(struct wlr_fbox *dest, const struct wlr_fbox *box, + enum wl_output_transform transform, double width, double height); + +#ifdef WLR_USE_UNSTABLE + +/** + * Returns true if the two boxes are equal, false otherwise. + */ +bool wlr_box_equal(const struct wlr_box *a, const struct wlr_box *b); + +/** + * Returns true if the two boxes are equal, false otherwise. + */ +bool wlr_fbox_equal(const struct wlr_fbox *a, const struct wlr_fbox *b); + +#endif + +#endif diff --git a/3rdparty/wlroots/include/wlr/util/edges.h b/3rdparty/wlroots/include/wlr/util/edges.h new file mode 100644 index 0000000000..be40556257 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/util/edges.h @@ -0,0 +1,27 @@ +/* + * This is a stable interface of wlroots. Future changes will be limited to: + * + * - New functions + * - New struct members + * - New enum members + * + * Note that wlroots does not make an ABI compatibility promise - in the future, + * the layout and size of structs used by wlroots may change, requiring code + * depending on this header to be recompiled (but not edited). + * + * Breaking changes are announced in the release notes and follow a 1-year + * deprecation schedule. + */ + +#ifndef WLR_UTIL_EDGES_H +#define WLR_UTIL_EDGES_H + +enum wlr_edges { + WLR_EDGE_NONE = 0, + WLR_EDGE_TOP = 1 << 0, + WLR_EDGE_BOTTOM = 1 << 1, + WLR_EDGE_LEFT = 1 << 2, + WLR_EDGE_RIGHT = 1 << 3, +}; + +#endif diff --git a/3rdparty/wlroots/include/wlr/util/log.h b/3rdparty/wlroots/include/wlr/util/log.h new file mode 100644 index 0000000000..799dd509a9 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/util/log.h @@ -0,0 +1,86 @@ +/* + * This is a stable interface of wlroots. Future changes will be limited to: + * + * - New functions + * - New struct members + * - New enum members + * + * Note that wlroots does not make an ABI compatibility promise - in the future, + * the layout and size of structs used by wlroots may change, requiring code + * depending on this header to be recompiled (but not edited). + * + * Breaking changes are announced in the release notes and follow a 1-year + * deprecation schedule. + */ + +#ifndef WLR_UTIL_LOG_H +#define WLR_UTIL_LOG_H + +#include +#include +#include +#include + +enum wlr_log_importance { + WLR_SILENT = 0, + WLR_ERROR = 1, + WLR_INFO = 2, + WLR_DEBUG = 3, + WLR_LOG_IMPORTANCE_LAST, +}; + +typedef void (*wlr_log_func_t)(enum wlr_log_importance importance, + const char *fmt, va_list args); + +/** + * Set the log verbosity and callback. + * + * Only messages less than or equal to the supplied verbosity will be logged. + * If the callback is NULL, the default logger is used. + * + * This function can be called multiple times to update the verbosity or + * callback function. + */ +void wlr_log_init(enum wlr_log_importance verbosity, wlr_log_func_t callback); + +/** + * Get the current log verbosity configured by wlr_log_init(). + */ +enum wlr_log_importance wlr_log_get_verbosity(void); + +#ifdef __GNUC__ +#define _WLR_ATTRIB_PRINTF(start, end) __attribute__((format(printf, start, end))) +#else +#define _WLR_ATTRIB_PRINTF(start, end) +#endif + +void _wlr_log(enum wlr_log_importance verbosity, const char *format, ...) _WLR_ATTRIB_PRINTF(2, 3); +void _wlr_vlog(enum wlr_log_importance verbosity, const char *format, va_list args) _WLR_ATTRIB_PRINTF(2, 0); + +#ifdef _WLR_REL_SRC_DIR +// strip prefix from __FILE__, leaving the path relative to the project root +#define _WLR_FILENAME ((const char *)__FILE__ + sizeof(_WLR_REL_SRC_DIR) - 1) +#else +#define _WLR_FILENAME __FILE__ +#endif + +#define wlr_vlog(verb, fmt, args) \ + _wlr_vlog(verb, "[%s:%d] " fmt, _WLR_FILENAME, __LINE__, args) + +#if __STDC_VERSION__ >= 202311L + +#define wlr_log(verb, fmt, ...) \ + _wlr_log(verb, "[%s:%d] " fmt, _WLR_FILENAME, __LINE__ __VA_OPT__(,) __VA_ARGS__) +#define wlr_log_errno(verb, fmt, ...) \ + wlr_log(verb, fmt ": %s" __VA_OPT__(,) __VA_ARGS__, strerror(errno)) + +#else + +#define wlr_log(verb, fmt, ...) \ + _wlr_log(verb, "[%s:%d] " fmt, _WLR_FILENAME, __LINE__, ##__VA_ARGS__) +#define wlr_log_errno(verb, fmt, ...) \ + wlr_log(verb, fmt ": %s", ##__VA_ARGS__, strerror(errno)) + +#endif + +#endif diff --git a/3rdparty/wlroots/include/wlr/util/region.h b/3rdparty/wlroots/include/wlr/util/region.h new file mode 100644 index 0000000000..ccd926fd15 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/util/region.h @@ -0,0 +1,77 @@ +/* + * This is a stable interface of wlroots. Future changes will be limited to: + * + * - New functions + * - New struct members + * - New enum members + * + * Note that wlroots does not make an ABI compatibility promise - in the future, + * the layout and size of structs used by wlroots may change, requiring code + * depending on this header to be recompiled (but not edited). + * + * Breaking changes are announced in the release notes and follow a 1-year + * deprecation schedule. + */ + +#ifndef WLR_UTIL_REGION_H +#define WLR_UTIL_REGION_H + +#include +#include +#include + +/** + * Scale a region by the specified factor. + * + * The resulting coordinates are rounded up or down so that the new region is + * at least as big as the original one if the scale factor is greater or equal + * to 1. + * + * Also see wlr_region_scale_xy(). + */ +void wlr_region_scale(pixman_region32_t *dst, const pixman_region32_t *src, + float scale); + +/** + * Scale a region by the specified factors. + * + * The X and Y coordinates are scaled separately by scale_x and scale_y. + * + * The resulting coordinates are rounded up or down so that the new region is + * at least as big as the original one if the scale factor is greater or equal + * to 1. + */ +void wlr_region_scale_xy(pixman_region32_t *dst, const pixman_region32_t *src, + float scale_x, float scale_y); + +/** + * Applies a transform to a region inside a box of size `width` x `height`. + */ +void wlr_region_transform(pixman_region32_t *dst, const pixman_region32_t *src, + enum wl_output_transform transform, int width, int height); + +/** + * Expands the region by distance on both axis. distance must be + * a non-negative number. + */ +void wlr_region_expand(pixman_region32_t *dst, const pixman_region32_t *src, + int distance); + +/* + * Builds the smallest possible region that contains the region rotated about + * the point (ox, oy). + */ +void wlr_region_rotated_bounds(pixman_region32_t *dst, const pixman_region32_t *src, + float rotation, int ox, int oy); + +/** + * Confine a point inside a region. + * + * x1 and y1 are the old position, x2 and y2 are the new tentative position. + * The function returns true with confined coordinates in x2_out and y2_out if + * the old position is within the region, or false otherwise. + */ +bool wlr_region_confine(const pixman_region32_t *region, double x1, double y1, double x2, + double y2, double *x2_out, double *y2_out); + +#endif diff --git a/3rdparty/wlroots/include/wlr/util/transform.h b/3rdparty/wlroots/include/wlr/util/transform.h new file mode 100644 index 0000000000..6195e6d0bf --- /dev/null +++ b/3rdparty/wlroots/include/wlr/util/transform.h @@ -0,0 +1,33 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_UTIL_TRANSFORM_H +#define WLR_UTIL_TRANSFORM_H + +#include + +/** + * Returns the transform that, when composed with `tr`, gives + * `WL_OUTPUT_TRANSFORM_NORMAL`. + */ +enum wl_output_transform wlr_output_transform_invert( + enum wl_output_transform tr); + +/** + * Returns a transform that, when applied, has the same effect as applying + * sequentially `tr_a` and `tr_b`. + */ +enum wl_output_transform wlr_output_transform_compose( + enum wl_output_transform tr_a, enum wl_output_transform tr_b); + +/** + * Applies a transform to coordinates. + */ +void wlr_output_transform_coords(enum wl_output_transform tr, int *x, int *y); + +#endif diff --git a/3rdparty/wlroots/include/wlr/version.h.in b/3rdparty/wlroots/include/wlr/version.h.in new file mode 100644 index 0000000000..10ff734696 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/version.h.in @@ -0,0 +1,17 @@ +#ifndef WLR_VERSION_H +#define WLR_VERSION_H + +#mesondefine WLR_VERSION_STR + +#mesondefine WLR_VERSION_MAJOR +#mesondefine WLR_VERSION_MINOR +#mesondefine WLR_VERSION_MICRO + +#define WLR_VERSION_NUM ((WLR_VERSION_MAJOR << 16) | (WLR_VERSION_MINOR << 8) | WLR_VERSION_MICRO) + +/* For runtime version detection */ +int wlr_version_get_major(void); +int wlr_version_get_minor(void); +int wlr_version_get_micro(void); + +#endif diff --git a/3rdparty/wlroots/include/wlr/xcursor.h b/3rdparty/wlroots/include/wlr/xcursor.h new file mode 100644 index 0000000000..5e9c140ae1 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/xcursor.h @@ -0,0 +1,136 @@ +/* + * Copyright © 2012 Intel Corporation + * + * 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 (including the + * next paragraph) 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. + */ + +/* + * This is a stable interface of wlroots. Future changes will be limited to: + * + * - New functions + * - New struct members + * - New enum members + * + * Note that wlroots does not make an ABI compatibility promise - in the future, + * the layout and size of structs used by wlroots may change, requiring code + * depending on this header to be recompiled (but not edited). + * + * Breaking changes are announced in the release notes and follow a 1-year + * deprecation schedule. + */ + +#ifndef WLR_XCURSOR_H +#define WLR_XCURSOR_H + +#include +#include + +/** + * A still cursor image. + * + * The buffer contains pixels laid out in a packed DRM_FORMAT_ARGB8888 format. + */ +struct wlr_xcursor_image { + uint32_t width; /* actual width */ + uint32_t height; /* actual height */ + uint32_t hotspot_x; /* hot-spot x (must be inside image) */ + uint32_t hotspot_y; /* hot-spot y (must be inside image) */ + uint32_t delay; /* animation delay to next frame (ms) */ + uint8_t *buffer; /* pixel data */ + + struct { + struct wlr_readonly_data_buffer *readonly_buffer; + } WLR_PRIVATE; +}; + +/** + * A cursor. + * + * If the cursor is animated, it may contain more than a single image. + */ +struct wlr_xcursor { + unsigned int image_count; + struct wlr_xcursor_image **images; + char *name; + uint32_t total_delay; /* total duration of the animation in ms */ +}; + +/** + * Container for an Xcursor theme. + */ +struct wlr_xcursor_theme { + unsigned int cursor_count; + struct wlr_xcursor **cursors; + char *name; + int size; +}; + +/** + * Loads the named Xcursor theme. + * + * This is useful if you need cursor images for your compositor to use when a + * client-side cursor is not available or you wish to override client-side + * cursors for a particular UI interaction (such as using a grab cursor when + * moving a window around). + * + * The size is given in pixels. + * + * If a cursor theme with the given name couldn't be loaded, a fallback theme + * is loaded. + * + * On error, NULL is returned. + */ +struct wlr_xcursor_theme *wlr_xcursor_theme_load(const char *name, int size); + +/** + * Destroy a cursor theme. + * + * This implicitly destroys all child cursors and cursor images. + */ +void wlr_xcursor_theme_destroy(struct wlr_xcursor_theme *theme); + +/** + * Obtain a cursor for the specified name (e.g. "default"). + * + * If the cursor could not be found, NULL is returned. + */ +struct wlr_xcursor *wlr_xcursor_theme_get_cursor( + struct wlr_xcursor_theme *theme, const char *name); + +/** + * Find the frame for a given elapsed time in a cursor animation. + * + * This function converts a timestamp (in ms) to a cursor image index. + */ +int wlr_xcursor_frame(struct wlr_xcursor *cursor, uint32_t time); + +/** + * Get a struct wlr_buffer from a cursor image. + */ +struct wlr_buffer *wlr_xcursor_image_get_buffer(struct wlr_xcursor_image *image); + +/** + * Get the name of the resize cursor for the given edges. + */ +const char *wlr_xcursor_get_resize_name(enum wlr_edges edges); + +#endif diff --git a/3rdparty/wlroots/include/wlr/xwayland.h b/3rdparty/wlroots/include/wlr/xwayland.h new file mode 100644 index 0000000000..cf2ef2636f --- /dev/null +++ b/3rdparty/wlroots/include/wlr/xwayland.h @@ -0,0 +1,2 @@ +#include +#include diff --git a/3rdparty/wlroots/include/wlr/xwayland/server.h b/3rdparty/wlroots/include/wlr/xwayland/server.h new file mode 100644 index 0000000000..b699b8f4fa --- /dev/null +++ b/3rdparty/wlroots/include/wlr/xwayland/server.h @@ -0,0 +1,68 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_XWAYLAND_SERVER_H +#define WLR_XWAYLAND_SERVER_H + +#include +#include +#include +#include + +struct wlr_xwayland_server_options { + bool lazy; + bool enable_wm; + bool no_touch_pointer_emulation; + bool force_xrandr_emulation; + int terminate_delay; // in seconds, 0 to terminate immediately +}; + +struct wlr_xwayland_server { + pid_t pid; + struct wl_client *client; + struct wl_event_source *pipe_source; + int wm_fd[2], wl_fd[2]; + bool ready; + + time_t server_start; + + /* Anything above display is reset on Xwayland restart, rest is conserved */ + + int display; + char display_name[16]; + int x_fd[2]; + struct wl_event_source *x_fd_read_event[2]; + struct wlr_xwayland_server_options options; + + struct wl_display *wl_display; + struct wl_event_source *idle_source; + + struct { + struct wl_signal start; + struct wl_signal ready; + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_listener client_destroy; + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_xwayland_server_ready_event { + struct wlr_xwayland_server *server; + int wm_fd; +}; + +struct wlr_xwayland_server *wlr_xwayland_server_create( + struct wl_display *display, struct wlr_xwayland_server_options *options); +void wlr_xwayland_server_destroy(struct wlr_xwayland_server *server); + +#endif diff --git a/3rdparty/wlroots/include/wlr/xwayland/shell.h b/3rdparty/wlroots/include/wlr/xwayland/shell.h new file mode 100644 index 0000000000..344ac22017 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/xwayland/shell.h @@ -0,0 +1,80 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_XWAYLAND_SHELL_H +#define WLR_XWAYLAND_SHELL_H + +#include +#include + +/** + * The Xwayland shell. + * + * This is a shell only exposed to Xwayland. + */ +struct wlr_xwayland_shell_v1 { + struct wl_global *global; + + struct { + struct wl_signal destroy; + struct wl_signal new_surface; // struct wlr_xwayland_surface_v1 + } events; + + struct { + struct wl_client *client; + struct wl_list surfaces; // wlr_xwayland_surface_v1.link + + struct wl_listener display_destroy; + struct wl_listener client_destroy; + } WLR_PRIVATE; +}; + +/** + * An Xwayland shell surface. + */ +struct wlr_xwayland_surface_v1 { + struct wlr_surface *surface; + uint64_t serial; + + struct { + struct wl_resource *resource; + struct wl_list link; + struct wlr_xwayland_shell_v1 *shell; + bool added; + } WLR_PRIVATE; +}; + +/** + * Create the xwayland_shell_v1 global. + * + * Compositors should add a global filter (see wl_display_set_global_filter()) + * to only expose this global to Xwayland clients. + */ +struct wlr_xwayland_shell_v1 *wlr_xwayland_shell_v1_create( + struct wl_display *display, uint32_t version); + +/** + * Destroy the xwayland_shell_v1 global. + */ +void wlr_xwayland_shell_v1_destroy(struct wlr_xwayland_shell_v1 *shell); + +/** + * Allow a client to bind to the xwayland_shell_v1 global. + */ +void wlr_xwayland_shell_v1_set_client(struct wlr_xwayland_shell_v1 *shell, + struct wl_client *client); + +/** + * Get a Wayland surface from an xwayland_shell_v1 serial. + * + * Returns NULL if the serial hasn't been associated with any surface. + */ +struct wlr_surface *wlr_xwayland_shell_v1_surface_from_serial( + struct wlr_xwayland_shell_v1 *shell, uint64_t serial); + +#endif diff --git a/3rdparty/wlroots/include/wlr/xwayland/xwayland.h b/3rdparty/wlroots/include/wlr/xwayland/xwayland.h new file mode 100644 index 0000000000..5c98bf6349 --- /dev/null +++ b/3rdparty/wlroots/include/wlr/xwayland/xwayland.h @@ -0,0 +1,450 @@ +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_XWAYLAND_XWAYLAND_H +#define WLR_XWAYLAND_XWAYLAND_H + +#include +#include +#include +#include +#include +#include +#include + +struct wlr_box; +struct wlr_buffer; +struct wlr_xwm; +struct wlr_data_source; +struct wlr_drag; + +/** + * Xwayland integration. + * + * This includes a utility to start and monitor the Xwayland process (see + * struct wlr_xwayland_server), an implementation of the xwayland_shell_v1 + * Wayland protocol, and a X11 window manager. + * + * Compositors are expected to set DISPLAY (see display_name) and listen to the + * new_surface event. + * + * Compositors may want to only expose the xwayland_shell_v1 Wayland global to + * the Xwayland client. To do so, they can set up a global filter via + * wl_display_set_global_filter() to ensure the global stored in + * shell_v1.global is only exposed to the client stored in server.client. + */ +struct wlr_xwayland { + struct wlr_xwayland_server *server; + bool own_server; + struct wlr_xwm *xwm; + struct wlr_xwayland_shell_v1 *shell_v1; + + // Value the DISPLAY environment variable should be set to by the compositor + const char *display_name; + + struct wl_display *wl_display; + struct wlr_compositor *compositor; + struct wlr_seat *seat; + + struct { + struct wl_signal destroy; + struct wl_signal ready; + struct wl_signal new_surface; // struct wlr_xwayland_surface + struct wl_signal remove_startup_info; // struct wlr_xwayland_remove_startup_info_event + } events; + + /** + * Add a custom event handler to xwayland. Return true if the event was + * handled or false to use the default wlr-xwayland handler. wlr-xwayland will + * free the event. + */ + bool (*user_event_handler)(struct wlr_xwayland *wlr_xwayland, xcb_generic_event_t *event); + + void *data; + + struct { + struct wlr_buffer *cursor_buffer; + struct { + int32_t x, y; + } cursor_hotspot; + + struct wl_listener server_start; + struct wl_listener server_ready; + struct wl_listener server_destroy; + struct wl_listener seat_destroy; + struct wl_listener shell_destroy; + } WLR_PRIVATE; +}; + +enum wlr_xwayland_surface_decorations { + WLR_XWAYLAND_SURFACE_DECORATIONS_ALL = 0, + WLR_XWAYLAND_SURFACE_DECORATIONS_NO_BORDER = 1, + WLR_XWAYLAND_SURFACE_DECORATIONS_NO_TITLE = 2, +}; + +/** + * This represents the input focus described as follows: + * + * https://www.x.org/releases/X11R7.6/doc/xorg-docs/specs/ICCCM/icccm.html#input_focus + */ +enum wlr_xwayland_icccm_input_model { + WLR_ICCCM_INPUT_MODEL_NONE = 0, + WLR_ICCCM_INPUT_MODEL_PASSIVE = 1, + WLR_ICCCM_INPUT_MODEL_LOCAL = 2, + WLR_ICCCM_INPUT_MODEL_GLOBAL = 3, +}; + +/** + * The type of window (_NET_WM_WINDOW_TYPE). See: + * https://specifications.freedesktop.org/wm-spec/latest/ + */ +enum wlr_xwayland_net_wm_window_type { + WLR_XWAYLAND_NET_WM_WINDOW_TYPE_DESKTOP = 0, + WLR_XWAYLAND_NET_WM_WINDOW_TYPE_DOCK, + WLR_XWAYLAND_NET_WM_WINDOW_TYPE_TOOLBAR, + WLR_XWAYLAND_NET_WM_WINDOW_TYPE_MENU, + WLR_XWAYLAND_NET_WM_WINDOW_TYPE_UTILITY, + WLR_XWAYLAND_NET_WM_WINDOW_TYPE_SPLASH, + WLR_XWAYLAND_NET_WM_WINDOW_TYPE_DIALOG, + WLR_XWAYLAND_NET_WM_WINDOW_TYPE_DROPDOWN_MENU, + WLR_XWAYLAND_NET_WM_WINDOW_TYPE_POPUP_MENU, + WLR_XWAYLAND_NET_WM_WINDOW_TYPE_TOOLTIP, + WLR_XWAYLAND_NET_WM_WINDOW_TYPE_NOTIFICATION, + WLR_XWAYLAND_NET_WM_WINDOW_TYPE_COMBO, + WLR_XWAYLAND_NET_WM_WINDOW_TYPE_DND, + WLR_XWAYLAND_NET_WM_WINDOW_TYPE_NORMAL, +}; + +/** + * An Xwayland user interface component. It has an absolute position in + * layout-local coordinates. + * + * The inner struct wlr_surface is valid once the associate event is emitted. + * Compositors can set up e.g. map and unmap listeners at this point. The + * struct wlr_surface becomes invalid when the dissociate event is emitted. + */ +struct wlr_xwayland_surface { + xcb_window_t window_id; + struct wlr_xwm *xwm; + uint32_t surface_id; + uint64_t serial; + + struct wl_list link; + struct wl_list stack_link; + struct wl_list unpaired_link; + + struct wlr_surface *surface; + struct wlr_addon surface_addon; + + int16_t x, y; + uint16_t width, height; + bool override_redirect; + float opacity; + + char *title; + char *class; + char *instance; + char *role; + char *startup_id; + pid_t pid; + + struct wl_list children; // wlr_xwayland_surface.parent_link + struct wlr_xwayland_surface *parent; + struct wl_list parent_link; // wlr_xwayland_surface.children + + xcb_atom_t *window_type; + size_t window_type_len; + + xcb_atom_t *protocols; + size_t protocols_len; + + uint32_t decorations; + xcb_icccm_wm_hints_t *hints; + xcb_size_hints_t *size_hints; + /* + * _NET_WM_STRUT_PARTIAL (used by e.g. XWayland panels). + * Note that right/bottom values are offsets from the lower + * right corner of the X11 screen, and the exact relation + * between X11 screen coordinates and the wlr_output_layout + * depends on the XWayland implementation. + */ + xcb_ewmh_wm_strut_partial_t *strut_partial; + + bool pinging; + struct wl_event_source *ping_timer; + + // _NET_WM_STATE + bool modal; + bool fullscreen; + bool maximized_vert, maximized_horz; + bool minimized; + bool withdrawn; + bool sticky; + bool shaded; + bool skip_taskbar; + bool skip_pager; + bool above; + bool below; + bool demands_attention; + + bool has_alpha; + bool has_input_shape; + bool has_clip_shape; + pixman_region32_t input_shape; + pixman_region32_t clip_shape; + + struct { + struct wl_signal destroy; + struct wl_signal request_configure; // struct wlr_xwayland_surface_configure_event + struct wl_signal request_move; + struct wl_signal request_resize; // struct wlr_xwayland_resize_event + struct wl_signal request_minimize; // struct wlr_xwayland_minimize_event + struct wl_signal request_maximize; + struct wl_signal request_fullscreen; + struct wl_signal request_activate; + struct wl_signal request_close; + struct wl_signal request_sticky; + struct wl_signal request_shaded; + struct wl_signal request_skip_taskbar; + struct wl_signal request_skip_pager; + struct wl_signal request_above; + struct wl_signal request_below; + struct wl_signal request_demands_attention; + + struct wl_signal associate; + struct wl_signal dissociate; + + struct wl_signal set_title; + struct wl_signal set_class; + struct wl_signal set_role; + struct wl_signal set_parent; + struct wl_signal set_startup_id; + struct wl_signal set_window_type; + struct wl_signal set_hints; + struct wl_signal set_size_hints; + struct wl_signal set_decorations; + struct wl_signal set_strut_partial; + struct wl_signal set_override_redirect; + struct wl_signal set_geometry; + struct wl_signal set_opacity; + struct wl_signal set_icon; + struct wl_signal set_input_shape; + struct wl_signal set_clip_shape; + struct wl_signal focus_in; + struct wl_signal grab_focus; + /* can be used to set initial maximized/fullscreen geometry */ + struct wl_signal map_request; + struct wl_signal ping_timeout; + } events; + + void *data; + + struct { + char *wm_name, *net_wm_name; + + struct wl_listener surface_commit; + struct wl_listener surface_map; + struct wl_listener surface_unmap; + } WLR_PRIVATE; +}; + +struct wlr_xwayland_surface_configure_event { + struct wlr_xwayland_surface *surface; + int16_t x, y; + uint16_t width, height; + uint16_t mask; // xcb_config_window_t +}; + +struct wlr_xwayland_remove_startup_info_event { + const char *id; + xcb_window_t window; +}; + +struct wlr_xwayland_resize_event { + struct wlr_xwayland_surface *surface; + uint32_t edges; +}; + +struct wlr_xwayland_minimize_event { + struct wlr_xwayland_surface *surface; + bool minimize; +}; + +/** Create an Xwayland server and XWM. + * + * The server supports a lazy mode in which Xwayland is only started when a + * client tries to connect. + */ +struct wlr_xwayland *wlr_xwayland_create(struct wl_display *wl_display, + struct wlr_compositor *compositor, bool lazy); + +/** + * Create an XWM from an existing Xwayland server. + */ +struct wlr_xwayland *wlr_xwayland_create_with_server(struct wl_display *display, + struct wlr_compositor *compositor, struct wlr_xwayland_server *server); + +void wlr_xwayland_destroy(struct wlr_xwayland *wlr_xwayland); + +void wlr_xwayland_set_cursor(struct wlr_xwayland *wlr_xwayland, + struct wlr_buffer *buffer, int32_t hotspot_x, int32_t hotspot_y); + +void wlr_xwayland_surface_activate(struct wlr_xwayland_surface *surface, + bool activated); + +/** + * Restack surface relative to sibling. + * If sibling is NULL, then the surface is moved to the top or the bottom + * of the stack (depending on the mode). + */ +void wlr_xwayland_surface_restack(struct wlr_xwayland_surface *surface, + struct wlr_xwayland_surface *sibling, enum xcb_stack_mode_t mode); + +void wlr_xwayland_surface_configure(struct wlr_xwayland_surface *surface, + int16_t x, int16_t y, uint16_t width, uint16_t height); + +void wlr_xwayland_surface_close(struct wlr_xwayland_surface *surface); + +void wlr_xwayland_surface_set_withdrawn(struct wlr_xwayland_surface *surface, + bool withdrawn); + +void wlr_xwayland_surface_set_minimized(struct wlr_xwayland_surface *surface, + bool minimized); + +void wlr_xwayland_surface_set_maximized(struct wlr_xwayland_surface *surface, + bool maximized_horz, bool maximized_vert); + +void wlr_xwayland_surface_set_fullscreen(struct wlr_xwayland_surface *surface, + bool fullscreen); + +void wlr_xwayland_surface_set_sticky( + struct wlr_xwayland_surface *surface, bool sticky); + +void wlr_xwayland_surface_set_shaded( + struct wlr_xwayland_surface *surface, bool shaded); + +void wlr_xwayland_surface_set_skip_taskbar( + struct wlr_xwayland_surface *surface, bool skip_taskbar); + +void wlr_xwayland_surface_set_skip_pager( + struct wlr_xwayland_surface *surface, bool skip_pager); + +void wlr_xwayland_surface_set_above( + struct wlr_xwayland_surface *surface, bool above); + +void wlr_xwayland_surface_set_below( + struct wlr_xwayland_surface *surface, bool below); + +void wlr_xwayland_surface_set_demands_attention( + struct wlr_xwayland_surface *surface, bool demands_attention); + +void wlr_xwayland_set_seat(struct wlr_xwayland *xwayland, + struct wlr_seat *seat); + +/** + * Get a struct wlr_xwayland_surface from a struct wlr_surface. + * + * If the surface hasn't been created by Xwayland or has no X11 window + * associated, NULL is returned. + */ +struct wlr_xwayland_surface *wlr_xwayland_surface_try_from_wlr_surface( + struct wlr_surface *surface); + +/** + * Get the effective input region for an Xwayland surface for input handling. + */ +void wlr_xwayland_surface_get_input_region( + const struct wlr_xwayland_surface *xsurface, pixman_region32_t *region); + +/** + * Check whether a surface-local point is inside the effective input region of + * an Xwayland surface. + */ +bool wlr_xwayland_surface_point_accepts_input( + const struct wlr_xwayland_surface *xsurface, double sx, double sy); + +/** + * Offer focus by sending WM_TAKE_FOCUS to a client window supporting it. + * The client may accept or ignore the offer. If it accepts, the surface will + * emit the focus_in signal notifying the compositor that it has received focus. + * + * This is a more compatible method of giving focus to windows using the + * Globally Active input model (see wlr_xwayland_icccm_input_model()) than + * calling wlr_xwayland_surface_activate() unconditionally, since there is no + * reliable way to know in advance whether these windows want to be focused. + */ +void wlr_xwayland_surface_offer_focus(struct wlr_xwayland_surface *xsurface); + +void wlr_xwayland_surface_ping(struct wlr_xwayland_surface *surface); + +/** + * Returns true if the surface has the given window type. + * Note: a surface may have multiple window types set. + */ +bool wlr_xwayland_surface_has_window_type( + const struct wlr_xwayland_surface *xsurface, + enum wlr_xwayland_net_wm_window_type window_type); + +/** Metric to guess if an OR window should "receive" focus + * + * In the pure X setups, window managers usually straight up ignore override + * redirect windows, and never touch them. (we have to handle them for mapping) + * + * When such a window wants to receive keyboard input (e.g. rofi/dzen) it will + * use mechanics we don't support (sniffing/grabbing input). + * [Sadly this is unrelated to xwayland-keyboard-grab] + * + * To still support these windows, while keeping general OR semantics as is, we + * need to hand a subset of windows focus. + * The dirty truth is, we need to hand focus to any Xwayland window, though + * pretending this window has focus makes it easier to handle unmap. + * + * This function provides a handy metric based on the window type to guess if + * the OR window wants focus. + * It's probably not perfect, nor exactly intended but works in practice. + * + * Returns: true if the window should receive focus + * false if it should be ignored + */ +bool wlr_xwayland_surface_override_redirect_wants_focus( + const struct wlr_xwayland_surface *xsurface); + +enum wlr_xwayland_icccm_input_model wlr_xwayland_surface_icccm_input_model( + const struct wlr_xwayland_surface *xsurface); + +/** + * Sets the _NET_WORKAREA root window property. The compositor should set + * one workarea per virtual desktop. This indicates the usable geometry + * (relative to the virtual desktop viewport) that is not covered by + * panels, docks, etc. Unfortunately, it is not possible to specify + * per-output workareas. + */ +void wlr_xwayland_set_workareas(struct wlr_xwayland *wlr_xwayland, + const struct wlr_box *workareas, size_t num_workareas); + +/** + * Fetches the icon set via the _NET_WM_ICON property. + * + * Returns true on success. The caller is responsible for freeing the reply + * using xcb_ewmh_get_wm_icon_reply_wipe(). + */ +bool wlr_xwayland_surface_fetch_icon( + const struct wlr_xwayland_surface *xsurface, + xcb_ewmh_get_wm_icon_reply_t *icon_reply); + +/** + * Get the XCB connection of the XWM. + * + * The connection is only valid after wlr_xwayland.events.ready, and becomes + * invalid on wlr_xwayland_server.events.destroy. In that case, NULL is + * returned. + */ +xcb_connection_t *wlr_xwayland_get_xwm_connection( + struct wlr_xwayland *wlr_xwayland); + +#endif diff --git a/3rdparty/wlroots/include/xcursor/cursor_data.h b/3rdparty/wlroots/include/xcursor/cursor_data.h new file mode 100644 index 0000000000..832701415b --- /dev/null +++ b/3rdparty/wlroots/include/xcursor/cursor_data.h @@ -0,0 +1,570 @@ +/* +* Copyright 1999 SuSE, Inc. +* +* 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 (including the +* next paragraph) 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. +* +* Author: Keith Packard, SuSE, Inc. +*/ + +#include +#include + +static const uint32_t cursor_data[] = { + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0xff000000, + 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, + 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, 0xffffffff, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0xff000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0x00000000, 0xffffffff, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0x00000000, + 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, + 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, + 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0xffffffff, 0x00000000, 0xffffffff, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0xffffffff, 0x00000000, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, + 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xffffffff, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, + 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xffffffff, 0xff000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, 0xffffffff, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xff000000, + 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, + 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, + 0xffffffff, 0xff000000, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xff000000, 0xffffffff, + 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, + 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0xff000000, + 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0x00000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0xffffffff, 0xff000000, 0xffffffff, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0xffffffff, 0x00000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0xff000000, 0xffffffff, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, 0xffffffff, 0xff000000, + 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xffffffff, 0xffffffff, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xff000000, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, + 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, + 0xffffffff, 0xff000000, 0xff000000, 0xffffffff, 0xffffffff, 0xffffffff, + 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0xffffffff, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0xffffffff, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xffffffff, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0xffffffff, 0xff000000, 0xff000000, 0xff000000, 0xff000000, 0xff000000, + 0xff000000, 0xff000000, 0xff000000, 0xffffffff, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, +}; + +static const struct cursor_metadata { + char *name; + int width, height; + int hotspot_x, hotspot_y; + size_t offset; +} cursor_metadata[] = { + { "bottom_left_corner", 16, 16, 1, 14, 0 }, + { "bottom_right_corner", 16, 16, 14, 14, 256 }, + { "bottom_side", 15, 16, 7, 14, 512 }, + { "grabbing", 16, 16, 8, 8, 752 }, + { "left_ptr", 10, 16, 1, 1, 1008 }, + { "left_side", 16, 15, 1, 7, 1168 }, + { "right_side", 16, 15, 14, 7, 1408 }, + { "top_left_corner", 16, 16, 1, 1, 1648 }, + { "top_right_corner", 16, 16, 14, 1, 1904 }, + { "top_side", 15, 16, 7, 1, 2160 }, + { "xterm", 9, 16, 4, 8, 2400 }, + { "hand1", 13, 16, 12, 0, 2544 }, + { "watch", 16, 16, 15, 9, 2752 }, + + /* https://www.freedesktop.org/wiki/Specifications/cursor-spec/ */ + { "sw-resize", 16, 16, 1, 14, 0 }, + { "se-resize", 16, 16, 14, 14, 256 }, + { "s-resize", 15, 16, 7, 14, 512 }, + { "all-scroll", 16, 16, 8, 8, 752 }, + { "default", 10, 16, 1, 1, 1008 }, + { "w-resize", 16, 15, 1, 7, 1168 }, + { "e-resize", 16, 15, 14, 7, 1408 }, + { "nw-resize", 16, 16, 1, 1, 1648 }, + { "ne-resize", 16, 16, 14, 1, 1904 }, + { "n-resize", 15, 16, 7, 1, 2160 }, + { "text", 9, 16, 4, 8, 2400 }, + { "pointer", 13, 16, 12, 0, 2544 }, + { "wait", 16, 16, 15, 9, 2752 }, +}; diff --git a/3rdparty/wlroots/include/xcursor/xcursor.h b/3rdparty/wlroots/include/xcursor/xcursor.h new file mode 100644 index 0000000000..459f816686 --- /dev/null +++ b/3rdparty/wlroots/include/xcursor/xcursor.h @@ -0,0 +1,58 @@ +/* + * Copyright © 2002 Keith Packard + * + * 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 (including the + * next paragraph) 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. + */ + +#ifndef XCURSOR_H +#define XCURSOR_H + +#include + +struct xcursor_image { + uint32_t version; /* version of the image data */ + uint32_t size; /* nominal size for matching */ + uint32_t width; /* actual width */ + uint32_t height; /* actual height */ + uint32_t xhot; /* hot spot x (must be inside image) */ + uint32_t yhot; /* hot spot y (must be inside image) */ + uint32_t delay; /* animation delay to next frame (ms) */ + uint32_t *pixels; /* pointer to pixels */ +}; + +/* + * Other data structures exposed by the library API + */ +struct xcursor_images { + int nimage; /* number of images */ + struct xcursor_image **images; /* array of XcursorImage pointers */ + char *name; /* name used to load images */ +}; + +void +xcursor_images_destroy(struct xcursor_images *images); + +void +xcursor_load_theme(const char *theme, int size, + void (*load_callback)(struct xcursor_images *, void *), + void *user_data); +#endif diff --git a/3rdparty/wlroots/include/xwayland/selection.h b/3rdparty/wlroots/include/xwayland/selection.h new file mode 100644 index 0000000000..3083102329 --- /dev/null +++ b/3rdparty/wlroots/include/xwayland/selection.h @@ -0,0 +1,95 @@ +#ifndef XWAYLAND_SELECTION_H +#define XWAYLAND_SELECTION_H + +#include +#include +#include + +#define INCR_CHUNK_SIZE (64 * 1024) + +#define XDND_VERSION 5 + +struct wlr_primary_selection_source; + +struct wlr_xwm_selection; + +struct wlr_drag; +struct wlr_data_source; + +struct wlr_xwm_selection_transfer { + struct wlr_xwm_selection *selection; + + bool incr; + bool flush_property_on_delete; + bool property_set; + struct wl_array source_data; + int wl_client_fd; + struct wl_event_source *event_source; + struct wl_list link; + + // when sending to x11 + xcb_selection_request_event_t request; + + // when receiving from x11 + int property_start; + xcb_get_property_reply_t *property_reply; + xcb_window_t incoming_window; +}; + +struct wlr_xwm_selection { + struct wlr_xwm *xwm; + + xcb_atom_t atom; + xcb_window_t window; + xcb_window_t owner; + xcb_timestamp_t timestamp; + + struct wl_list incoming; + struct wl_list outgoing; +}; + +struct wlr_xwm_selection_transfer * +xwm_selection_find_incoming_transfer_by_window( + struct wlr_xwm_selection *selection, xcb_window_t window); + +void xwm_selection_transfer_remove_event_source( + struct wlr_xwm_selection_transfer *transfer); +void xwm_selection_transfer_close_wl_client_fd( + struct wlr_xwm_selection_transfer *transfer); +void xwm_selection_transfer_destroy_property_reply( + struct wlr_xwm_selection_transfer *transfer); +void xwm_selection_transfer_init(struct wlr_xwm_selection_transfer *transfer, + struct wlr_xwm_selection *selection); +void xwm_selection_transfer_destroy( + struct wlr_xwm_selection_transfer *transfer); + +void xwm_selection_transfer_destroy_outgoing( + struct wlr_xwm_selection_transfer *transfer); + +xcb_atom_t xwm_mime_type_to_atom(struct wlr_xwm *xwm, char *mime_type); +char *xwm_mime_type_from_atom(struct wlr_xwm *xwm, xcb_atom_t atom); +struct wlr_xwm_selection *xwm_get_selection(struct wlr_xwm *xwm, + xcb_atom_t selection_atom); + +void xwm_send_incr_chunk(struct wlr_xwm_selection_transfer *transfer); +void xwm_handle_selection_request(struct wlr_xwm *xwm, + xcb_selection_request_event_t *req); +void xwm_handle_selection_destroy_notify(struct wlr_xwm *xwm, + xcb_destroy_notify_event_t *event); + +void xwm_get_incr_chunk(struct wlr_xwm_selection_transfer *transfer); +void xwm_handle_selection_notify(struct wlr_xwm *xwm, + xcb_selection_notify_event_t *event); +int xwm_handle_xfixes_selection_notify(struct wlr_xwm *xwm, + xcb_xfixes_selection_notify_event_t *event); +bool data_source_is_xwayland(struct wlr_data_source *wlr_source); +bool primary_selection_source_is_xwayland( + struct wlr_primary_selection_source *wlr_source); + +void xwm_seat_handle_start_drag(struct wlr_xwm *xwm, struct wlr_drag *drag); + +void xwm_selection_init(struct wlr_xwm_selection *selection, + struct wlr_xwm *xwm, xcb_atom_t atom); +void xwm_selection_finish(struct wlr_xwm_selection *selection); + +#endif diff --git a/3rdparty/wlroots/include/xwayland/xwm.h b/3rdparty/wlroots/include/xwayland/xwm.h new file mode 100644 index 0000000000..da59af105a --- /dev/null +++ b/3rdparty/wlroots/include/xwayland/xwm.h @@ -0,0 +1,194 @@ +#ifndef XWAYLAND_XWM_H +#define XWAYLAND_XWM_H + +#include +#include +#include +#include +#include "config.h" +#include "xwayland/selection.h" + +#if HAVE_XCB_ERRORS +#include +#endif + +/* This is in xcb/xcb_event.h, but pulling xcb-util just for a constant + * others redefine anyway is meh + */ +#define XCB_EVENT_RESPONSE_TYPE_MASK (0x7f) + +enum atom_name { + WL_SURFACE_ID, + WL_SURFACE_SERIAL, + WM_DELETE_WINDOW, + WM_PROTOCOLS, + WM_HINTS, + WM_NORMAL_HINTS, + WM_SIZE_HINTS, + WM_WINDOW_ROLE, + MOTIF_WM_HINTS, + UTF8_STRING, + WM_S0, + NET_SUPPORTED, + NET_WM_CM_S0, + NET_WM_PID, + NET_WM_NAME, + NET_WM_STATE, + NET_WM_STRUT_PARTIAL, + NET_WM_WINDOW_TYPE, + NET_WM_ICON, + WM_TAKE_FOCUS, + WINDOW, + NET_ACTIVE_WINDOW, + NET_CLOSE_WINDOW, + NET_WM_MOVERESIZE, + NET_SUPPORTING_WM_CHECK, + NET_WM_STATE_FOCUSED, + NET_WM_STATE_MODAL, + NET_WM_STATE_FULLSCREEN, + NET_WM_STATE_MAXIMIZED_VERT, + NET_WM_STATE_MAXIMIZED_HORZ, + NET_WM_STATE_HIDDEN, + NET_WM_STATE_STICKY, + NET_WM_STATE_SHADED, + NET_WM_STATE_SKIP_TASKBAR, + NET_WM_STATE_SKIP_PAGER, + NET_WM_STATE_ABOVE, + NET_WM_STATE_BELOW, + NET_WM_STATE_DEMANDS_ATTENTION, + NET_WM_PING, + WM_CHANGE_STATE, + WM_STATE, + CLIPBOARD, + PRIMARY, + WL_SELECTION, + TARGETS, + CLIPBOARD_MANAGER, + INCR, + TEXT, + TIMESTAMP, + DELETE, + NET_STARTUP_ID, + NET_STARTUP_INFO, + NET_STARTUP_INFO_BEGIN, + NET_WM_WINDOW_OPACITY, + NET_WM_WINDOW_TYPE_NORMAL, + NET_WM_WINDOW_TYPE_UTILITY, + NET_WM_WINDOW_TYPE_TOOLTIP, + NET_WM_WINDOW_TYPE_DND, + NET_WM_WINDOW_TYPE_DROPDOWN_MENU, + NET_WM_WINDOW_TYPE_POPUP_MENU, + NET_WM_WINDOW_TYPE_COMBO, + NET_WM_WINDOW_TYPE_MENU, + NET_WM_WINDOW_TYPE_NOTIFICATION, + NET_WM_WINDOW_TYPE_SPLASH, + NET_WM_WINDOW_TYPE_DESKTOP, + NET_WM_WINDOW_TYPE_DOCK, + NET_WM_WINDOW_TYPE_TOOLBAR, + NET_WM_WINDOW_TYPE_DIALOG, + DND_SELECTION, + DND_AWARE, + DND_STATUS, + DND_POSITION, + DND_ENTER, + DND_LEAVE, + DND_DROP, + DND_FINISHED, + DND_PROXY, + DND_TYPE_LIST, + DND_ACTION_MOVE, + DND_ACTION_COPY, + DND_ACTION_ASK, + DND_ACTION_PRIVATE, + NET_CLIENT_LIST, + NET_CLIENT_LIST_STACKING, + NET_WORKAREA, + ATOM_LAST // keep last +}; + +struct wlr_xwm { + struct wlr_xwayland *xwayland; + struct wl_event_source *event_source; + struct wlr_seat *seat; + uint32_t ping_timeout; + + xcb_atom_t atoms[ATOM_LAST]; + xcb_connection_t *xcb_conn; + xcb_screen_t *screen; + xcb_window_t window; + xcb_window_t no_focus_window; + xcb_visualid_t visual_id; + xcb_colormap_t colormap; + xcb_render_pictformat_t render_format_id; + xcb_cursor_t cursor; + + struct wlr_xwm_selection clipboard_selection; + struct wlr_xwm_selection primary_selection; + struct wlr_xwm_selection dnd_selection; + + struct wlr_xwayland_surface *focus_surface; + struct wlr_xwayland_surface *offered_focus; + + // Surfaces in creation order + struct wl_list surfaces; // wlr_xwayland_surface.link + // Surfaces in bottom-to-top stacking order, for _NET_CLIENT_LIST_STACKING + struct wl_list surfaces_in_stack_order; // wlr_xwayland_surface.stack_link + struct wl_list unpaired_surfaces; // wlr_xwayland_surface.unpaired_link + struct wl_list pending_startup_ids; // pending_startup_id + + struct wlr_drag *drag; + struct wlr_xwayland_surface *drag_focus; + struct wlr_xwayland_surface *drop_focus; + + const xcb_query_extension_reply_t *xfixes; + const xcb_query_extension_reply_t *xres; + const xcb_query_extension_reply_t *shape; + bool shape_input_supported; + uint32_t xfixes_major_version; +#if HAVE_XCB_ERRORS + xcb_errors_context_t *errors_context; +#endif + unsigned int last_focus_seq; + + struct wl_listener compositor_new_surface; + struct wl_listener compositor_destroy; + struct wl_listener shell_v1_new_surface; + struct wl_listener shell_v1_destroy; + struct wl_listener seat_set_selection; + struct wl_listener seat_set_primary_selection; + struct wl_listener seat_start_drag; + struct wl_listener seat_drag_focus; + struct wl_listener seat_drag_motion; + struct wl_listener seat_drag_drop; + struct wl_listener seat_drag_destroy; + struct wl_listener seat_drag_source_destroy; + struct wl_listener drag_focus_destroy; + struct wl_listener drop_focus_destroy; +}; + +// xwm_create takes ownership of wm_fd and will close it under all circumstances. +struct wlr_xwm *xwm_create(struct wlr_xwayland *wlr_xwayland, int wm_fd); + +void xwm_destroy(struct wlr_xwm *xwm); + +void xwm_set_cursor(struct wlr_xwm *xwm, struct wlr_buffer *buffer, + int32_t hotspot_x, int32_t hotspot_y); + +int xwm_handle_selection_event(struct wlr_xwm *xwm, xcb_generic_event_t *event); +int xwm_handle_selection_client_message(struct wlr_xwm *xwm, + xcb_client_message_event_t *ev); +void xwm_seat_unlink_drag_handlers(struct wlr_xwm *xwm); + +void xwm_set_seat(struct wlr_xwm *xwm, struct wlr_seat *seat); + +char *xwm_get_atom_name(struct wlr_xwm *xwm, xcb_atom_t atom); +bool xwm_atoms_contains(struct wlr_xwm *xwm, xcb_atom_t *atoms, + size_t num_atoms, enum atom_name needle); + +xcb_void_cookie_t xwm_send_event_with_size(xcb_connection_t *c, + uint8_t propagate, xcb_window_t destination, + uint32_t event_mask, const void *event, uint32_t length); + +void xwm_schedule_flush(struct wlr_xwm *xwm); + +#endif diff --git a/3rdparty/wlroots/meson.build b/3rdparty/wlroots/meson.build new file mode 100644 index 0000000000..41ce1ea25d --- /dev/null +++ b/3rdparty/wlroots/meson.build @@ -0,0 +1,189 @@ +project( + 'wlroots', + 'c', + version: '0.20.2', + license: 'MIT', + meson_version: '>=1.3', + default_options: [ + 'c_std=' + (meson.version().version_compare('>=1.4.0') ? 'c23,c11' : 'c11'), + 'warning_level=2', + 'werror=true', + 'wrap_mode=nodownload', + ], +) + +version = meson.project_version().split('-')[0] +version_major = version.split('.')[0] +version_minor = version.split('.')[1] +versioned_name = '@0@-@1@.@2@'.format(meson.project_name(), version_major, version_minor) + +little_endian = target_machine.endian() == 'little' +big_endian = target_machine.endian() == 'big' + +add_project_arguments([ + '-D_POSIX_C_SOURCE=200809L', + '-DWLR_USE_UNSTABLE', + '-DWLR_PRIVATE=', + '-DWLR_LITTLE_ENDIAN=@0@'.format(little_endian.to_int()), + '-DWLR_BIG_ENDIAN=@0@'.format(big_endian.to_int()), +], language: 'c') + +cc = meson.get_compiler('c') + +add_project_arguments(cc.get_supported_arguments([ + '-Wundef', + '-Wlogical-op', + '-Wmissing-include-dirs', + '-Wold-style-definition', + '-Wpointer-arith', + '-Winit-self', + '-Wstrict-prototypes', + '-Wimplicit-fallthrough=2', + '-Wendif-labels', + '-Wstrict-aliasing=2', + '-Woverflow', + '-Wmissing-prototypes', + '-Walloca', + + '-Wno-missing-braces', + '-Wno-missing-field-initializers', + '-Wno-unused-parameter', +]), language: 'c') + +fs = import('fs') + +# Strip relative path prefixes from the code if possible, otherwise hide them. +relative_dir = fs.relative_to(meson.current_source_dir(), meson.global_build_root()) + '/' +if cc.has_argument('-fmacro-prefix-map=/prefix/to/hide=') + add_project_arguments( + '-fmacro-prefix-map=@0@='.format(relative_dir), + language: 'c', + ) +else + add_project_arguments( + '-D_WLR_REL_SRC_DIR="@0@"'.format(relative_dir), + language: 'c', + ) +endif + +features = { + 'drm-backend': false, + 'x11-backend': false, + 'libinput-backend': false, + 'xwayland': false, + 'gles2-renderer': false, + 'vulkan-renderer': false, + 'gbm-allocator': false, + 'udmabuf-allocator': false, + 'session': false, + 'color-management': false, +} +internal_features = { + 'xcb-errors': false, + 'egl': false, + 'libliftoff': false, +} +internal_config = configuration_data() + +wayland_kwargs = { + 'version': '>=1.24.0', + 'fallback': 'wayland', + 'default_options': [ + 'tests=false', + 'documentation=false', + ], +} +wayland_server = dependency('wayland-server', + kwargs: wayland_kwargs, +) + +drm = dependency('libdrm', + version: '>=2.4.129', + fallback: 'libdrm', + default_options: [ + 'auto_features=disabled', + 'tests=false', + ], +) +xkbcommon = dependency('xkbcommon', + version: '>=1.8.0', + fallback: 'libxkbcommon', + default_options: [ + 'enable-tools=false', + 'enable-x11=false', + 'enable-docs=false', + 'enable-xkbregistry=false', + ], +) +pixman = dependency('pixman-1', + version: '>=0.43.0', + fallback: 'pixman', + default_options: ['werror=false'], +) +math = cc.find_library('m') +rt = cc.find_library('rt') + +wlr_files = [] +wlr_deps = [ + wayland_server, + drm, + xkbcommon, + pixman, + math, + rt, +] + +subdir('protocol') +subdir('render') + +subdir('backend') +subdir('types') +subdir('util') +subdir('xcursor') +subdir('xwayland') + +subdir('include') + +wlr_inc = include_directories('include') + +symbols_file = 'wlroots.syms' +symbols_flag = '-Wl,--version-script,@0@/@1@'.format(meson.current_source_dir(), symbols_file) +lib_wlr = library( + versioned_name, wlr_files, + dependencies: wlr_deps, + include_directories: [wlr_inc], + install: true, + link_args: symbols_flag, + link_depends: symbols_file, +) + +wlr_vars = {} +foreach name, have : features + wlr_vars += { 'have_' + name.underscorify(): have.to_string() } +endforeach + +wlroots = declare_dependency( + link_with: lib_wlr, + dependencies: wlr_deps, + include_directories: wlr_inc, + variables: wlr_vars, +) + +meson.override_dependency(versioned_name, wlroots) + +summary(features + internal_features, bool_yn: true) + +if get_option('examples') + subdir('examples') + subdir('tinywl') +endif + +pkgconfig = import('pkgconfig') +pkgconfig.generate( + lib_wlr, + name: versioned_name, + description: 'Wayland compositor library', + subdirs: versioned_name, + url: 'https://gitlab.freedesktop.org/wlroots/wlroots', + variables: wlr_vars, +) diff --git a/3rdparty/wlroots/meson.options b/3rdparty/wlroots/meson.options new file mode 100644 index 0000000000..5863764aaa --- /dev/null +++ b/3rdparty/wlroots/meson.options @@ -0,0 +1,11 @@ +option('xcb-errors', type: 'feature', value: 'auto', description: 'Use xcb-errors util library') +option('xwayland', type: 'feature', value: 'auto', yield: true, description: 'Enable support for X11 applications') +option('examples', type: 'boolean', value: true, description: 'Build example applications') +option('icon_directory', description: 'Location used to look for cursors (default: ${datadir}/icons)', type: 'string', value: '') +option('renderers', type: 'array', choices: ['auto', 'gles2', 'vulkan'], value: ['auto'], description: 'Select built-in renderers') +option('backends', type: 'array', choices: ['auto', 'drm', 'libinput', 'x11'], value: ['auto'], description: 'Select built-in backends') +option('allocators', type: 'array', choices: ['auto', 'gbm', 'udmabuf'], value: ['auto'], + description: 'Select built-in allocators') +option('session', type: 'feature', value: 'auto', description: 'Enable session support') +option('color-management', type: 'feature', value: 'auto', description: 'Enable support for color management') +option('libliftoff', type: 'feature', value: 'auto', description: 'Enable support for libliftoff') diff --git a/3rdparty/wlroots/protocol/drm.xml b/3rdparty/wlroots/protocol/drm.xml new file mode 100644 index 0000000000..eaf2654ab2 --- /dev/null +++ b/3rdparty/wlroots/protocol/drm.xml @@ -0,0 +1,189 @@ + + + + + Copyright © 2008-2011 Kristian Høgsberg + Copyright © 2010-2011 Intel Corporation + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that\n the above copyright notice appear in + all copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + the copyright holders not be used in advertising or publicity + pertaining to distribution of the software without specific, + written prior permission. The copyright holders make no + representations about the suitability of this software for any + purpose. It is provided "as is" without express or implied + warranty. + + THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY + SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN + AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + THIS SOFTWARE. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Bitmask of capabilities. + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/3rdparty/wlroots/protocol/input-method-unstable-v2.xml b/3rdparty/wlroots/protocol/input-method-unstable-v2.xml new file mode 100644 index 0000000000..84d04703a7 --- /dev/null +++ b/3rdparty/wlroots/protocol/input-method-unstable-v2.xml @@ -0,0 +1,494 @@ + + + + + Copyright © 2008-2011 Kristian Høgsberg + Copyright © 2010-2011 Intel Corporation + Copyright © 2012-2013 Collabora, Ltd. + Copyright © 2012, 2013 Intel Corporation + Copyright © 2015, 2016 Jan Arne Petersen + Copyright © 2017, 2018 Red Hat, Inc. + Copyright © 2018 Purism SPC + + 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 (including the next + paragraph) 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. + + + + This protocol allows applications to act as input methods for compositors. + + An input method context is used to manage the state of the input method. + + Text strings are UTF-8 encoded, their indices and lengths are in bytes. + + This document adheres to the RFC 2119 when using words like "must", + "should", "may", etc. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + An input method object allows for clients to compose text. + + The objects connects the client to a text input in an application, and + lets the client to serve as an input method for a seat. + + The zwp_input_method_v2 object can occupy two distinct states: active and + inactive. In the active state, the object is associated to and + communicates with a text input. In the inactive state, there is no + associated text input, and the only communication is with the compositor. + Initially, the input method is in the inactive state. + + Requests issued in the inactive state must be accepted by the compositor. + Because of the serial mechanism, and the state reset on activate event, + they will not have any effect on the state of the next text input. + + There must be no more than one input method object per seat. + + + + + + + + + Notification that a text input focused on this seat requested the input + method to be activated. + + This event serves the purpose of providing the compositor with an + active input method. + + This event resets all state associated with previous + surrounding_text, text_change_cause, and content_type events, as well + as the state associated with set_preedit_string, commit_string, and + delete_surrounding_text requests. In addition, it marks the + zwp_input_method_v2 object as active, and makes any existing + zwp_input_popup_surface_v2 objects visible. + + The surrounding_text, and content_type events must follow before the + next done event if the text input supports the respective + functionality. + + State set with this event is double-buffered. It will get applied on + the next zwp_input_method_v2.done event, and stay valid until changed. + + + + + + Notification that no focused text input currently needs an active + input method on this seat. + + This event marks the zwp_input_method_v2 object as inactive. The + compositor must make all existing zwp_input_popup_surface_v2 objects + invisible until the next activate event. + + State set with this event is double-buffered. It will get applied on + the next zwp_input_method_v2.done event, and stay valid until changed. + + + + + + Updates the surrounding plain text around the cursor, excluding the + preedit text. + + If any preedit text is present, it is replaced with the cursor for the + purpose of this event. + + The argument text is a buffer containing the surrounding text, and must + include the cursor position, and the complete selection. It should + contain additional characters before and after these. There is a + maximum length of wayland messages, so text can not be longer than 4000 + bytes. + + cursor is the byte offset of the cursor within the text buffer. + + anchor is the byte offset of the selection anchor within the text + buffer. If there is no selected text, anchor must be the same as + cursor. + + If this event does not arrive before the first done event, the input + method may assume that the text input does not support this + functionality and ignore following surrounding_text events. + + Values set with this event are double-buffered. They will get applied + and set to initial values on the next zwp_input_method_v2.done + event. + + The initial state for affected fields is empty, meaning that the text + input does not support sending surrounding text. If the empty values + get applied, subsequent attempts to change them may have no effect. + + + + + + + + + Tells the input method why the text surrounding the cursor changed. + + Whenever the client detects an external change in text, cursor, or + anchor position, it must issue this request to the compositor. This + request is intended to give the input method a chance to update the + preedit text in an appropriate way, e.g. by removing it when the user + starts typing with a keyboard. + + cause describes the source of the change. + + The value set with this event is double-buffered. It will get applied + and set to its initial value on the next zwp_input_method_v2.done + event. + + The initial value of cause is input_method. + + + + + + + Indicates the content type and hint for the current + zwp_input_method_v2 instance. + + Values set with this event are double-buffered. They will get applied + on the next zwp_input_method_v2.done event. + + The initial value for hint is none, and the initial value for purpose + is normal. + + + + + + + + Atomically applies state changes recently sent to the client. + + The done event establishes and updates the state of the client, and + must be issued after any changes to apply them. + + Text input state (content purpose, content hint, surrounding text, and + change cause) is conceptually double-buffered within an input method + context. + + Events modify the pending state, as opposed to the current state in use + by the input method. A done event atomically applies all pending state, + replacing the current state. After done, the new pending state is as + documented for each related request. + + Events must be applied in the order of arrival. + + Neither current nor pending state are modified unless noted otherwise. + + + + + + Send the commit string text for insertion to the application. + + Inserts a string at current cursor position (see commit event + sequence). The string to commit could be either just a single character + after a key press or the result of some composing. + + The argument text is a buffer containing the string to insert. There is + a maximum length of wayland messages, so text can not be longer than + 4000 bytes. + + Values set with this event are double-buffered. They must be applied + and reset to initial on the next zwp_text_input_v3.commit request. + + The initial value of text is an empty string. + + + + + + + Send the pre-edit string text to the application text input. + + Place a new composing text (pre-edit) at the current cursor position. + Any previously set composing text must be removed. Any previously + existing selected text must be removed. The cursor is moved to a new + position within the preedit string. + + The argument text is a buffer containing the preedit string. There is + a maximum length of wayland messages, so text can not be longer than + 4000 bytes. + + The arguments cursor_begin and cursor_end are counted in bytes relative + to the beginning of the submitted string buffer. Cursor should be + hidden by the text input when both are equal to -1. + + cursor_begin indicates the beginning of the cursor. cursor_end + indicates the end of the cursor. It may be equal or different than + cursor_begin. + + Values set with this event are double-buffered. They must be applied on + the next zwp_input_method_v2.commit event. + + The initial value of text is an empty string. The initial value of + cursor_begin, and cursor_end are both 0. + + + + + + + + + Remove the surrounding text. + + before_length and after_length are the number of bytes before and after + the current cursor index (excluding the preedit text) to delete. + + If any preedit text is present, it is replaced with the cursor for the + purpose of this event. In effect before_length is counted from the + beginning of preedit text, and after_length from its end (see commit + event sequence). + + Values set with this event are double-buffered. They must be applied + and reset to initial on the next zwp_input_method_v2.commit request. + + The initial values of both before_length and after_length are 0. + + + + + + + + Apply state changes from commit_string, set_preedit_string and + delete_surrounding_text requests. + + The state relating to these events is double-buffered, and each one + modifies the pending state. This request replaces the current state + with the pending state. + + The connected text input is expected to proceed by evaluating the + changes in the following order: + + 1. Replace existing preedit string with the cursor. + 2. Delete requested surrounding text. + 3. Insert commit string with the cursor at its end. + 4. Calculate surrounding text to send. + 5. Insert new preedit text in cursor position. + 6. Place cursor inside preedit text. + + The serial number reflects the last state of the zwp_input_method_v2 + object known to the client. The value of the serial argument must be + equal to the number of done events already issued by that object. When + the compositor receives a commit request with a serial different than + the number of past done events, it must proceed as normal, except it + should not change the current state of the zwp_input_method_v2 object. + + + + + + + Creates a new zwp_input_popup_surface_v2 object wrapping a given + surface. + + The surface gets assigned the "input_popup" role. If the surface + already has an assigned role, the compositor must issue a protocol + error. + + + + + + + + Allow an input method to receive hardware keyboard input and process + key events to generate text events (with pre-edit) over the wire. This + allows input methods which compose multiple key events for inputting + text like it is done for CJK languages. + + The compositor should send all keyboard events on the seat to the grab + holder via the returned wl_keyboard object. Nevertheless, the + compositor may decide not to forward any particular event. The + compositor must not further process any event after it has been + forwarded to the grab holder. + + Releasing the resulting wl_keyboard object releases the grab. + + + + + + + The input method ceased to be available. + + The compositor must issue this event as the only event on the object if + there was another input_method object associated with the same seat at + the time of its creation. + + The compositor must issue this request when the object is no longer + usable, e.g. due to seat removal. + + The input method context becomes inert and should be destroyed after + deactivation is handled. Any further requests and events except for the + destroy request must be ignored. + + + + + + Destroys the zwp_text_input_v2 object and any associated child + objects, i.e. zwp_input_popup_surface_v2 and + zwp_input_method_keyboard_grab_v2. + + + + + + + This interface marks a surface as a popup for interacting with an input + method. + + The compositor should place it near the active text input area. It must + be visible if and only if the input method is in the active state. + + The client must not destroy the underlying wl_surface while the + zwp_input_popup_surface_v2 object exists. + + + + + Notify about the position of the area of the text input expressed as a + rectangle in surface local coordinates. + + This is a hint to the input method telling it the relative position of + the text being entered. + + + + + + + + + + + + + + The zwp_input_method_keyboard_grab_v2 interface represents an exclusive + grab of the wl_keyboard interface associated with the seat. + + + + + This event provides a file descriptor to the client which can be + memory-mapped to provide a keyboard mapping description. + + + + + + + + + A key was pressed or released. + The time argument is a timestamp with millisecond granularity, with an + undefined base. + + + + + + + + + + Notifies clients that the modifier and/or group state has changed, and + it should update its local state. + + + + + + + + + + + + + + + Informs the client about the keyboard's repeat rate and delay. + + This event is sent as soon as the zwp_input_method_keyboard_grab_v2 + object has been created, and is guaranteed to be received by the + client before any key press event. + + Negative values for either rate or delay are illegal. A rate of zero + will disable any repeating (regardless of the value of delay). + + This event can be sent later on as well with a new value if necessary, + so clients should continue listening for the event past the creation + of zwp_input_method_keyboard_grab_v2. + + + + + + + + + The input method manager allows the client to become the input method on + a chosen seat. + + No more than one input method must be associated with any seat at any + given time. + + + + + Request a new input zwp_input_method_v2 object associated with a given + seat. + + + + + + + + Destroys the zwp_input_method_manager_v2 object. + + The zwp_input_method_v2 objects originating from it remain valid. + + + + diff --git a/3rdparty/wlroots/protocol/meson.build b/3rdparty/wlroots/protocol/meson.build new file mode 100644 index 0000000000..30aeb68c62 --- /dev/null +++ b/3rdparty/wlroots/protocol/meson.build @@ -0,0 +1,113 @@ +wayland_protos = dependency('wayland-protocols', + version: '>=1.47', + fallback: 'wayland-protocols', + default_options: ['tests=false'], +) +wl_protocol_dir = wayland_protos.get_variable('pkgdatadir') +wlr_deps += wayland_protos + +wayland_scanner_dep = dependency('wayland-scanner', + kwargs: wayland_kwargs, + native: true, +) +wayland_scanner = find_program( + wayland_scanner_dep.get_variable('wayland_scanner'), + native: true, +) + +protocols = { + # Stable upstream protocols + 'linux-dmabuf-v1': wl_protocol_dir / 'stable/linux-dmabuf/linux-dmabuf-v1.xml', + 'presentation-time': wl_protocol_dir / 'stable/presentation-time/presentation-time.xml', + 'tablet-v2': wl_protocol_dir / 'stable/tablet/tablet-v2.xml', + 'viewporter': wl_protocol_dir / 'stable/viewporter/viewporter.xml', + 'xdg-shell': wl_protocol_dir / 'stable/xdg-shell/xdg-shell.xml', + + # Staging upstream protocols + 'alpha-modifier-v1': wl_protocol_dir / 'staging/alpha-modifier/alpha-modifier-v1.xml', + 'color-management-v1': wl_protocol_dir / 'staging/color-management/color-management-v1.xml', + 'color-representation-v1': wl_protocol_dir / 'staging/color-representation/color-representation-v1.xml', + 'content-type-v1': wl_protocol_dir / 'staging/content-type/content-type-v1.xml', + 'cursor-shape-v1': wl_protocol_dir / 'staging/cursor-shape/cursor-shape-v1.xml', + 'drm-lease-v1': wl_protocol_dir / 'staging/drm-lease/drm-lease-v1.xml', + 'ext-foreign-toplevel-list-v1': wl_protocol_dir / 'staging/ext-foreign-toplevel-list/ext-foreign-toplevel-list-v1.xml', + 'ext-idle-notify-v1': wl_protocol_dir / 'staging/ext-idle-notify/ext-idle-notify-v1.xml', + 'ext-image-capture-source-v1': wl_protocol_dir / 'staging/ext-image-capture-source/ext-image-capture-source-v1.xml', + 'ext-image-copy-capture-v1': wl_protocol_dir / 'staging/ext-image-copy-capture/ext-image-copy-capture-v1.xml', + 'ext-session-lock-v1': wl_protocol_dir / 'staging/ext-session-lock/ext-session-lock-v1.xml', + 'ext-data-control-v1': wl_protocol_dir / 'staging/ext-data-control/ext-data-control-v1.xml', + 'ext-workspace-v1': wl_protocol_dir / 'staging/ext-workspace/ext-workspace-v1.xml', + 'fractional-scale-v1': wl_protocol_dir / 'staging/fractional-scale/fractional-scale-v1.xml', + 'linux-drm-syncobj-v1': wl_protocol_dir / 'staging/linux-drm-syncobj/linux-drm-syncobj-v1.xml', + 'security-context-v1': wl_protocol_dir / 'staging/security-context/security-context-v1.xml', + 'single-pixel-buffer-v1': wl_protocol_dir / 'staging/single-pixel-buffer/single-pixel-buffer-v1.xml', + 'xdg-activation-v1': wl_protocol_dir / 'staging/xdg-activation/xdg-activation-v1.xml', + 'xdg-dialog-v1': wl_protocol_dir / 'staging/xdg-dialog/xdg-dialog-v1.xml', + 'xdg-system-bell-v1': wl_protocol_dir / 'staging/xdg-system-bell/xdg-system-bell-v1.xml', + 'xdg-toplevel-icon-v1': wl_protocol_dir / 'staging/xdg-toplevel-icon/xdg-toplevel-icon-v1.xml', + 'xdg-toplevel-tag-v1': wl_protocol_dir / 'staging/xdg-toplevel-tag/xdg-toplevel-tag-v1.xml', + 'xwayland-shell-v1': wl_protocol_dir / 'staging/xwayland-shell/xwayland-shell-v1.xml', + 'tearing-control-v1': wl_protocol_dir / 'staging/tearing-control/tearing-control-v1.xml', + + # Unstable upstream protocols + 'idle-inhibit-unstable-v1': wl_protocol_dir / 'unstable/idle-inhibit/idle-inhibit-unstable-v1.xml', + 'keyboard-shortcuts-inhibit-unstable-v1': wl_protocol_dir / 'unstable/keyboard-shortcuts-inhibit/keyboard-shortcuts-inhibit-unstable-v1.xml', + 'pointer-constraints-unstable-v1': wl_protocol_dir / 'unstable/pointer-constraints/pointer-constraints-unstable-v1.xml', + 'pointer-gestures-unstable-v1': wl_protocol_dir / 'unstable/pointer-gestures/pointer-gestures-unstable-v1.xml', + 'primary-selection-unstable-v1': wl_protocol_dir / 'unstable/primary-selection/primary-selection-unstable-v1.xml', + 'relative-pointer-unstable-v1': wl_protocol_dir / 'unstable/relative-pointer/relative-pointer-unstable-v1.xml', + 'text-input-unstable-v3': wl_protocol_dir / 'unstable/text-input/text-input-unstable-v3.xml', + 'xdg-decoration-unstable-v1': wl_protocol_dir / 'unstable/xdg-decoration/xdg-decoration-unstable-v1.xml', + 'xdg-foreign-unstable-v1': wl_protocol_dir / 'unstable/xdg-foreign/xdg-foreign-unstable-v1.xml', + 'xdg-foreign-unstable-v2': wl_protocol_dir / 'unstable/xdg-foreign/xdg-foreign-unstable-v2.xml', + 'xdg-output-unstable-v1': wl_protocol_dir / 'unstable/xdg-output/xdg-output-unstable-v1.xml', + 'ext-transient-seat-v1': wl_protocol_dir / 'staging/ext-transient-seat/ext-transient-seat-v1.xml', + + # Other protocols + 'drm': 'drm.xml', + 'input-method-unstable-v2': 'input-method-unstable-v2.xml', + 'kde-server-decoration': 'server-decoration.xml', + 'virtual-keyboard-unstable-v1': 'virtual-keyboard-unstable-v1.xml', + 'wlr-data-control-unstable-v1': 'wlr-data-control-unstable-v1.xml', + 'wlr-export-dmabuf-unstable-v1': 'wlr-export-dmabuf-unstable-v1.xml', + 'wlr-foreign-toplevel-management-unstable-v1': 'wlr-foreign-toplevel-management-unstable-v1.xml', + 'wlr-gamma-control-unstable-v1': 'wlr-gamma-control-unstable-v1.xml', + 'wlr-layer-shell-unstable-v1': 'wlr-layer-shell-unstable-v1.xml', + 'wlr-output-management-unstable-v1': 'wlr-output-management-unstable-v1.xml', + 'wlr-output-power-management-unstable-v1': 'wlr-output-power-management-unstable-v1.xml', + 'wlr-screencopy-unstable-v1': 'wlr-screencopy-unstable-v1.xml', + 'wlr-virtual-pointer-unstable-v1': 'wlr-virtual-pointer-unstable-v1.xml', +} + +protocols_code = {} +protocols_server_header = {} +protocols_client_header = {} +foreach name, path : protocols + code = custom_target( + name.underscorify() + '_c', + input: path, + output: '@BASENAME@-protocol.c', + command: [wayland_scanner, 'private-code', '@INPUT@', '@OUTPUT@'], + ) + wlr_files += code + + server_header = custom_target( + name.underscorify() + '_server_h', + input: path, + output: '@BASENAME@-protocol.h', + command: [wayland_scanner, 'server-header', '@INPUT@', '@OUTPUT@'], + ) + wlr_files += server_header + + client_header = custom_target( + name.underscorify() + '_client_h', + input: path, + output: '@BASENAME@-client-protocol.h', + command: [wayland_scanner, 'client-header', '@INPUT@', '@OUTPUT@'], + build_by_default: false, + ) + + protocols_code += { name: code } + protocols_server_header += { name: server_header } + protocols_client_header += { name: client_header } +endforeach diff --git a/3rdparty/wlroots/protocol/server-decoration.xml b/3rdparty/wlroots/protocol/server-decoration.xml new file mode 100644 index 0000000000..45f1128416 --- /dev/null +++ b/3rdparty/wlroots/protocol/server-decoration.xml @@ -0,0 +1,94 @@ + + + . + ]]> + + + This interface allows to coordinate whether the server should create + a server-side window decoration around a wl_surface representing a + shell surface (wl_shell_surface or similar). By announcing support + for this interface the server indicates that it supports server + side decorations. + + + + When a client creates a server-side decoration object it indicates + that it supports the protocol. The client is supposed to tell the + server whether it wants server-side decorations or will provide + client-side decorations. + + If the client does not create a server-side decoration object for + a surface the server interprets this as lack of support for this + protocol and considers it as client-side decorated. Nevertheless a + client-side decorated surface should use this protocol to indicate + to the server that it does not want a server-side deco. + + + + + + + + + + + + + This event is emitted directly after binding the interface. It contains + the default mode for the decoration. When a new server decoration object + is created this new object will be in the default mode until the first + request_mode is requested. + + The server may change the default mode at any time. + + + + + + + + + + + + + + + + + + + + + This event is emitted directly after the decoration is created and + represents the base decoration policy by the server. E.g. a server + which wants all surfaces to be client-side decorated will send Client, + a server which wants server-side decoration will send Server. + + The client can request a different mode through the decoration request. + The server will acknowledge this by another event with the same mode. So + even if a server prefers server-side decoration it's possible to force a + client-side decoration. + + The server may emit this event at any time. In this case the client can + again request a different mode. It's the responsibility of the server to + prevent a feedback loop. + + + + + diff --git a/3rdparty/wlroots/protocol/virtual-keyboard-unstable-v1.xml b/3rdparty/wlroots/protocol/virtual-keyboard-unstable-v1.xml new file mode 100644 index 0000000000..5095c91b81 --- /dev/null +++ b/3rdparty/wlroots/protocol/virtual-keyboard-unstable-v1.xml @@ -0,0 +1,113 @@ + + + + Copyright © 2008-2011 Kristian Høgsberg + Copyright © 2010-2013 Intel Corporation + Copyright © 2012-2013 Collabora, Ltd. + Copyright © 2018 Purism SPC + + 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 (including the next + paragraph) 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. + + + + + The virtual keyboard provides an application with requests which emulate + the behaviour of a physical keyboard. + + This interface can be used by clients on its own to provide raw input + events, or it can accompany the input method protocol. + + + + + Provide a file descriptor to the compositor which can be + memory-mapped to provide a keyboard mapping description. + + Format carries a value from the keymap_format enumeration. + + + + + + + + + + + + + A key was pressed or released. + The time argument is a timestamp with millisecond granularity, with an + undefined base. All requests regarding a single object must share the + same clock. + + Keymap must be set before issuing this request. + + State carries a value from the key_state enumeration. + + + + + + + + + Notifies the compositor that the modifier and/or group state has + changed, and it should update state. + + The client should use wl_keyboard.modifiers event to synchronize its + internal state with seat state. + + Keymap must be set before issuing this request. + + + + + + + + + + + + + + + A virtual keyboard manager allows an application to provide keyboard + input events as if they came from a physical keyboard. + + + + + + + + + Creates a new virtual keyboard associated to a seat. + + If the compositor enables a keyboard to perform arbitrary actions, it + should present an error when an untrusted client requests a new + keyboard. + + + + + + diff --git a/3rdparty/wlroots/protocol/wlr-data-control-unstable-v1.xml b/3rdparty/wlroots/protocol/wlr-data-control-unstable-v1.xml new file mode 100644 index 0000000000..75e8671b0d --- /dev/null +++ b/3rdparty/wlroots/protocol/wlr-data-control-unstable-v1.xml @@ -0,0 +1,278 @@ + + + + Copyright © 2018 Simon Ser + Copyright © 2019 Ivan Molodetskikh + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + the copyright holders not be used in advertising or publicity + pertaining to distribution of the software without specific, + written prior permission. The copyright holders make no + representations about the suitability of this software for any + purpose. It is provided "as is" without express or implied + warranty. + + THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY + SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN + AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + THIS SOFTWARE. + + + + This protocol allows a privileged client to control data devices. In + particular, the client will be able to manage the current selection and take + the role of a clipboard manager. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + This interface is a manager that allows creating per-seat data device + controls. + + + + + Create a new data source. + + + + + + + Create a data device that can be used to manage a seat's selection. + + + + + + + + All objects created by the manager will still remain valid, until their + appropriate destroy request has been called. + + + + + + + This interface allows a client to manage a seat's selection. + + When the seat is destroyed, this object becomes inert. + + + + + This request asks the compositor to set the selection to the data from + the source on behalf of the client. + + The given source may not be used in any further set_selection or + set_primary_selection requests. Attempting to use a previously used + source is a protocol error. + + To unset the selection, set the source to NULL. + + + + + + + Destroys the data device object. + + + + + + The data_offer event introduces a new wlr_data_control_offer object, + which will subsequently be used in either the + wlr_data_control_device.selection event (for the regular clipboard + selections) or the wlr_data_control_device.primary_selection event (for + the primary clipboard selections). Immediately following the + wlr_data_control_device.data_offer event, the new data_offer object + will send out wlr_data_control_offer.offer events to describe the MIME + types it offers. + + + + + + + The selection event is sent out to notify the client of a new + wlr_data_control_offer for the selection for this device. The + wlr_data_control_device.data_offer and the wlr_data_control_offer.offer + events are sent out immediately before this event to introduce the data + offer object. The selection event is sent to a client when a new + selection is set. The wlr_data_control_offer is valid until a new + wlr_data_control_offer or NULL is received. The client must destroy the + previous selection wlr_data_control_offer, if any, upon receiving this + event. + + The first selection event is sent upon binding the + wlr_data_control_device object. + + + + + + + This data control object is no longer valid and should be destroyed by + the client. + + + + + + + + The primary_selection event is sent out to notify the client of a new + wlr_data_control_offer for the primary selection for this device. The + wlr_data_control_device.data_offer and the wlr_data_control_offer.offer + events are sent out immediately before this event to introduce the data + offer object. The primary_selection event is sent to a client when a + new primary selection is set. The wlr_data_control_offer is valid until + a new wlr_data_control_offer or NULL is received. The client must + destroy the previous primary selection wlr_data_control_offer, if any, + upon receiving this event. + + If the compositor supports primary selection, the first + primary_selection event is sent upon binding the + wlr_data_control_device object. + + + + + + + This request asks the compositor to set the primary selection to the + data from the source on behalf of the client. + + The given source may not be used in any further set_selection or + set_primary_selection requests. Attempting to use a previously used + source is a protocol error. + + To unset the primary selection, set the source to NULL. + + The compositor will ignore this request if it does not support primary + selection. + + + + + + + + + + + + The wlr_data_control_source object is the source side of a + wlr_data_control_offer. It is created by the source client in a data + transfer and provides a way to describe the offered data and a way to + respond to requests to transfer the data. + + + + + + + + + This request adds a MIME type to the set of MIME types advertised to + targets. Can be called several times to offer multiple types. + + Calling this after wlr_data_control_device.set_selection is a protocol + error. + + + + + + + Destroys the data source object. + + + + + + Request for data from the client. Send the data as the specified MIME + type over the passed file descriptor, then close it. + + + + + + + + This data source is no longer valid. The data source has been replaced + by another data source. + + The client should clean up and destroy this data source. + + + + + + + A wlr_data_control_offer represents a piece of data offered for transfer + by another client (the source client). The offer describes the different + MIME types that the data can be converted to and provides the mechanism + for transferring the data directly from the source client. + + + + + To transfer the offered data, the client issues this request and + indicates the MIME type it wants to receive. The transfer happens + through the passed file descriptor (typically created with the pipe + system call). The source client writes the data in the MIME type + representation requested and then closes the file descriptor. + + The receiving client reads from the read end of the pipe until EOF and + then closes its end, at which point the transfer is complete. + + This request may happen multiple times for different MIME types. + + + + + + + + Destroys the data offer object. + + + + + + Sent immediately after creating the wlr_data_control_offer object. + One event per offered MIME type. + + + + + diff --git a/3rdparty/wlroots/protocol/wlr-export-dmabuf-unstable-v1.xml b/3rdparty/wlroots/protocol/wlr-export-dmabuf-unstable-v1.xml new file mode 100644 index 0000000000..d41efbb1db --- /dev/null +++ b/3rdparty/wlroots/protocol/wlr-export-dmabuf-unstable-v1.xml @@ -0,0 +1,203 @@ + + + + Copyright © 2018 Rostislav Pehlivanov + + 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 (including the next + paragraph) 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. + + + + An interface to capture surfaces in an efficient way by exporting DMA-BUFs. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + This object is a manager with which to start capturing from sources. + + + + + Capture the next frame of an entire output. + + + + + + + + + All objects created by the manager will still remain valid, until their + appropriate destroy request has been called. + + + + + + + This object represents a single DMA-BUF frame. + + If the capture is successful, the compositor will first send a "frame" + event, followed by one or several "object". When the frame is available + for readout, the "ready" event is sent. + + If the capture failed, the "cancel" event is sent. This can happen anytime + before the "ready" event. + + Once either a "ready" or a "cancel" event is received, the client should + destroy the frame. Once an "object" event is received, the client is + responsible for closing the associated file descriptor. + + All frames are read-only and may not be written into or altered. + + + + + Special flags that should be respected by the client. + + + + + + + Main event supplying the client with information about the frame. If the + capture didn't fail, this event is always emitted first before any other + events. + + This event is followed by a number of "object" as specified by the + "num_objects" argument. + + + + + + + + + + + + + + + + Event which serves to supply the client with the file descriptors + containing the data for each object. + + After receiving this event, the client must always close the file + descriptor as soon as they're done with it and even if the frame fails. + + + + + + + + + + + + This event is sent as soon as the frame is presented, indicating it is + available for reading. This event includes the time at which + presentation happened at. + + The timestamp is expressed as tv_sec_hi, tv_sec_lo, tv_nsec triples, + each component being an unsigned 32-bit value. Whole seconds are in + tv_sec which is a 64-bit value combined from tv_sec_hi and tv_sec_lo, + and the additional fractional part in tv_nsec as nanoseconds. Hence, + for valid timestamps tv_nsec must be in [0, 999999999]. The seconds part + may have an arbitrary offset at start. + + After receiving this event, the client should destroy this object. + + + + + + + + + Indicates reason for cancelling the frame. + + + + + + + + + If the capture failed or if the frame is no longer valid after the + "frame" event has been emitted, this event will be used to inform the + client to scrap the frame. + + If the failure is temporary, the client may capture again the same + source. If the failure is permanent, any further attempts to capture the + same source will fail again. + + After receiving this event, the client should destroy this object. + + + + + + + Unreferences the frame. This request must be called as soon as it's no + longer used. + + It can be called at any time by the client. The client will still have + to close any FDs it has been given. + + + + diff --git a/3rdparty/wlroots/protocol/wlr-foreign-toplevel-management-unstable-v1.xml b/3rdparty/wlroots/protocol/wlr-foreign-toplevel-management-unstable-v1.xml new file mode 100644 index 0000000000..44505bbb69 --- /dev/null +++ b/3rdparty/wlroots/protocol/wlr-foreign-toplevel-management-unstable-v1.xml @@ -0,0 +1,270 @@ + + + + Copyright © 2018 Ilia Bozhinov + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + the copyright holders not be used in advertising or publicity + pertaining to distribution of the software without specific, + written prior permission. The copyright holders make no + representations about the suitability of this software for any + purpose. It is provided "as is" without express or implied + warranty. + + THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY + SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN + AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + THIS SOFTWARE. + + + + + The purpose of this protocol is to enable the creation of taskbars + and docks by providing them with a list of opened applications and + letting them request certain actions on them, like maximizing, etc. + + After a client binds the zwlr_foreign_toplevel_manager_v1, each opened + toplevel window will be sent via the toplevel event + + + + + This event is emitted whenever a new toplevel window is created. It + is emitted for all toplevels, regardless of the app that has created + them. + + All initial details of the toplevel(title, app_id, states, etc.) will + be sent immediately after this event via the corresponding events in + zwlr_foreign_toplevel_handle_v1. + + + + + + + Indicates the client no longer wishes to receive events for new toplevels. + However the compositor may emit further toplevel_created events, until + the finished event is emitted. + + The client must not send any more requests after this one. + + + + + + This event indicates that the compositor is done sending events to the + zwlr_foreign_toplevel_manager_v1. The server will destroy the object + immediately after sending this request, so it will become invalid and + the client should free any resources associated with it. + + + + + + + A zwlr_foreign_toplevel_handle_v1 object represents an opened toplevel + window. Each app may have multiple opened toplevels. + + Each toplevel has a list of outputs it is visible on, conveyed to the + client with the output_enter and output_leave events. + + + + + This event is emitted whenever the title of the toplevel changes. + + + + + + + This event is emitted whenever the app-id of the toplevel changes. + + + + + + + This event is emitted whenever the toplevel becomes visible on + the given output. A toplevel may be visible on multiple outputs. + + + + + + + This event is emitted whenever the toplevel stops being visible on + the given output. It is guaranteed that an entered-output event + with the same output has been emitted before this event. + + + + + + + Requests that the toplevel be maximized. If the maximized state actually + changes, this will be indicated by the state event. + + + + + + Requests that the toplevel be unmaximized. If the maximized state actually + changes, this will be indicated by the state event. + + + + + + Requests that the toplevel be minimized. If the minimized state actually + changes, this will be indicated by the state event. + + + + + + Requests that the toplevel be unminimized. If the minimized state actually + changes, this will be indicated by the state event. + + + + + + Request that this toplevel be activated on the given seat. + There is no guarantee the toplevel will be actually activated. + + + + + + + The different states that a toplevel can have. These have the same meaning + as the states with the same names defined in xdg-toplevel + + + + + + + + + + + This event is emitted immediately after the zlw_foreign_toplevel_handle_v1 + is created and each time the toplevel state changes, either because of a + compositor action or because of a request in this protocol. + + + + + + + + This event is sent after all changes in the toplevel state have been + sent. + + This allows changes to the zwlr_foreign_toplevel_handle_v1 properties + to be seen as atomic, even if they happen via multiple events. + + + + + + Send a request to the toplevel to close itself. The compositor would + typically use a shell-specific method to carry out this request, for + example by sending the xdg_toplevel.close event. However, this gives + no guarantees the toplevel will actually be destroyed. If and when + this happens, the zwlr_foreign_toplevel_handle_v1.closed event will + be emitted. + + + + + + The rectangle of the surface specified in this request corresponds to + the place where the app using this protocol represents the given toplevel. + It can be used by the compositor as a hint for some operations, e.g + minimizing. The client is however not required to set this, in which + case the compositor is free to decide some default value. + + If the client specifies more than one rectangle, only the last one is + considered. + + The dimensions are given in surface-local coordinates. + Setting width=height=0 removes the already-set rectangle. + + + + + + + + + + + + + + + + This event means the toplevel has been destroyed. It is guaranteed there + won't be any more events for this zwlr_foreign_toplevel_handle_v1. The + toplevel itself becomes inert so any requests will be ignored except the + destroy request. + + + + + + Destroys the zwlr_foreign_toplevel_handle_v1 object. + + This request should be called either when the client does not want to + use the toplevel anymore or after the closed event to finalize the + destruction of the object. + + + + + + + + Requests that the toplevel be fullscreened on the given output. If the + fullscreen state and/or the outputs the toplevel is visible on actually + change, this will be indicated by the state and output_enter/leave + events. + + The output parameter is only a hint to the compositor. Also, if output + is NULL, the compositor should decide which output the toplevel will be + fullscreened on, if at all. + + + + + + + Requests that the toplevel be unfullscreened. If the fullscreen state + actually changes, this will be indicated by the state event. + + + + + + + + This event is emitted whenever the parent of the toplevel changes. + + No event is emitted when the parent handle is destroyed by the client. + + + + + diff --git a/3rdparty/wlroots/protocol/wlr-gamma-control-unstable-v1.xml b/3rdparty/wlroots/protocol/wlr-gamma-control-unstable-v1.xml new file mode 100644 index 0000000000..16e0be8b14 --- /dev/null +++ b/3rdparty/wlroots/protocol/wlr-gamma-control-unstable-v1.xml @@ -0,0 +1,126 @@ + + + + Copyright © 2015 Giulio camuffo + Copyright © 2018 Simon Ser + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + the copyright holders not be used in advertising or publicity + pertaining to distribution of the software without specific, + written prior permission. The copyright holders make no + representations about the suitability of this software for any + purpose. It is provided "as is" without express or implied + warranty. + + THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY + SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN + AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + THIS SOFTWARE. + + + + This protocol allows a privileged client to set the gamma tables for + outputs. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + This interface is a manager that allows creating per-output gamma + controls. + + + + + Create a gamma control that can be used to adjust gamma tables for the + provided output. + + + + + + + + All objects created by the manager will still remain valid, until their + appropriate destroy request has been called. + + + + + + + This interface allows a client to adjust gamma tables for a particular + output. + + The client will receive the gamma size, and will then be able to set gamma + tables. At any time the compositor can send a failed event indicating that + this object is no longer valid. + + There can only be at most one gamma control object per output, which + has exclusive access to this particular output. When the gamma control + object is destroyed, the gamma table is restored to its original value. + + + + + Advertise the size of each gamma ramp. + + This event is sent immediately when the gamma control object is created. + + + + + + + + + + + Set the gamma table. The file descriptor can be memory-mapped to provide + the raw gamma table, which contains successive gamma ramps for the red, + green and blue channels. Each gamma ramp is an array of 16-byte unsigned + integers which has the same length as the gamma size. + + The file descriptor data must have the same length as three times the + gamma size. + + + + + + + This event indicates that the gamma control is no longer valid. This + can happen for a number of reasons, including: + - The output doesn't support gamma tables + - Setting the gamma tables failed + - Another client already has exclusive gamma control for this output + - The compositor has transferred gamma control to another client + + Upon receiving this event, the client should destroy this object. + + + + + + Destroys the gamma control object. If the object is still valid, this + restores the original gamma tables. + + + + diff --git a/3rdparty/wlroots/protocol/wlr-layer-shell-unstable-v1.xml b/3rdparty/wlroots/protocol/wlr-layer-shell-unstable-v1.xml new file mode 100644 index 0000000000..e9f27e4fdb --- /dev/null +++ b/3rdparty/wlroots/protocol/wlr-layer-shell-unstable-v1.xml @@ -0,0 +1,407 @@ + + + + Copyright © 2017 Drew DeVault + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + the copyright holders not be used in advertising or publicity + pertaining to distribution of the software without specific, + written prior permission. The copyright holders make no + representations about the suitability of this software for any + purpose. It is provided "as is" without express or implied + warranty. + + THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY + SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN + AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + THIS SOFTWARE. + + + + + Clients can use this interface to assign the surface_layer role to + wl_surfaces. Such surfaces are assigned to a "layer" of the output and + rendered with a defined z-depth respective to each other. They may also be + anchored to the edges and corners of a screen and specify input handling + semantics. This interface should be suitable for the implementation of + many desktop shell components, and a broad number of other applications + that interact with the desktop. + + + + + Create a layer surface for an existing surface. This assigns the role of + layer_surface, or raises a protocol error if another role is already + assigned. + + Creating a layer surface from a wl_surface which has a buffer attached + or committed is a client error, and any attempts by a client to attach + or manipulate a buffer prior to the first layer_surface.configure call + must also be treated as errors. + + After creating a layer_surface object and setting it up, the client + must perform an initial commit without any buffer attached. + The compositor will reply with a layer_surface.configure event. + The client must acknowledge it and is then allowed to attach a buffer + to map the surface. + + You may pass NULL for output to allow the compositor to decide which + output to use. Generally this will be the one that the user most + recently interacted with. + + Clients can specify a namespace that defines the purpose of the layer + surface. + + + + + + + + + + + + + + + + + These values indicate which layers a surface can be rendered in. They + are ordered by z depth, bottom-most first. Traditional shell surfaces + will typically be rendered between the bottom and top layers. + Fullscreen shell surfaces are typically rendered at the top layer. + Multiple surfaces can share a single layer, and ordering within a + single layer is undefined. + + + + + + + + + + + + + This request indicates that the client will not use the layer_shell + object any more. Objects that have been created through this instance + are not affected. + + + + + + + An interface that may be implemented by a wl_surface, for surfaces that + are designed to be rendered as a layer of a stacked desktop-like + environment. + + Layer surface state (layer, size, anchor, exclusive zone, + margin, interactivity) is double-buffered, and will be applied at the + time wl_surface.commit of the corresponding wl_surface is called. + + Attaching a null buffer to a layer surface unmaps it. + + Unmapping a layer_surface means that the surface cannot be shown by the + compositor until it is explicitly mapped again. The layer_surface + returns to the state it had right after layer_shell.get_layer_surface. + The client can re-map the surface by performing a commit without any + buffer attached, waiting for a configure event and handling it as usual. + + + + + Sets the size of the surface in surface-local coordinates. The + compositor will display the surface centered with respect to its + anchors. + + If you pass 0 for either value, the compositor will assign it and + inform you of the assignment in the configure event. You must set your + anchor to opposite edges in the dimensions you omit; not doing so is a + protocol error. Both values are 0 by default. + + Size is double-buffered, see wl_surface.commit. + + + + + + + + Requests that the compositor anchor the surface to the specified edges + and corners. If two orthogonal edges are specified (e.g. 'top' and + 'left'), then the anchor point will be the intersection of the edges + (e.g. the top left corner of the output); otherwise the anchor point + will be centered on that edge, or in the center if none is specified. + + Anchor is double-buffered, see wl_surface.commit. + + + + + + + Requests that the compositor avoids occluding an area with other + surfaces. The compositor's use of this information is + implementation-dependent - do not assume that this region will not + actually be occluded. + + A positive value is only meaningful if the surface is anchored to one + edge or an edge and both perpendicular edges. If the surface is not + anchored, anchored to only two perpendicular edges (a corner), anchored + to only two parallel edges or anchored to all edges, a positive value + will be treated the same as zero. + + A positive zone is the distance from the edge in surface-local + coordinates to consider exclusive. + + Surfaces that do not wish to have an exclusive zone may instead specify + how they should interact with surfaces that do. If set to zero, the + surface indicates that it would like to be moved to avoid occluding + surfaces with a positive exclusive zone. If set to -1, the surface + indicates that it would not like to be moved to accommodate for other + surfaces, and the compositor should extend it all the way to the edges + it is anchored to. + + For example, a panel might set its exclusive zone to 10, so that + maximized shell surfaces are not shown on top of it. A notification + might set its exclusive zone to 0, so that it is moved to avoid + occluding the panel, but shell surfaces are shown underneath it. A + wallpaper or lock screen might set their exclusive zone to -1, so that + they stretch below or over the panel. + + The default value is 0. + + Exclusive zone is double-buffered, see wl_surface.commit. + + + + + + + Requests that the surface be placed some distance away from the anchor + point on the output, in surface-local coordinates. Setting this value + for edges you are not anchored to has no effect. + + The exclusive zone includes the margin. + + Margin is double-buffered, see wl_surface.commit. + + + + + + + + + + Types of keyboard interaction possible for layer shell surfaces. The + rationale for this is twofold: (1) some applications are not interested + in keyboard events and not allowing them to be focused can improve the + desktop experience; (2) some applications will want to take exclusive + keyboard focus. + + + + + This value indicates that this surface is not interested in keyboard + events and the compositor should never assign it the keyboard focus. + + This is the default value, set for newly created layer shell surfaces. + + This is useful for e.g. desktop widgets that display information or + only have interaction with non-keyboard input devices. + + + + + Request exclusive keyboard focus if this surface is above the shell surface layer. + + For the top and overlay layers, the seat will always give + exclusive keyboard focus to the top-most layer which has keyboard + interactivity set to exclusive. If this layer contains multiple + surfaces with keyboard interactivity set to exclusive, the compositor + determines the one receiving keyboard events in an implementation- + defined manner. In this case, no guarantee is made when this surface + will receive keyboard focus (if ever). + + For the bottom and background layers, the compositor is allowed to use + normal focus semantics. + + This setting is mainly intended for applications that need to ensure + they receive all keyboard events, such as a lock screen or a password + prompt. + + + + + This requests the compositor to allow this surface to be focused and + unfocused by the user in an implementation-defined manner. The user + should be able to unfocus this surface even regardless of the layer + it is on. + + Typically, the compositor will want to use its normal mechanism to + manage keyboard focus between layer shell surfaces with this setting + and regular toplevels on the desktop layer (e.g. click to focus). + Nevertheless, it is possible for a compositor to require a special + interaction to focus or unfocus layer shell surfaces (e.g. requiring + a click even if focus follows the mouse normally, or providing a + keybinding to switch focus between layers). + + This setting is mainly intended for desktop shell components (e.g. + panels) that allow keyboard interaction. Using this option can allow + implementing a desktop shell that can be fully usable without the + mouse. + + + + + + + Set how keyboard events are delivered to this surface. By default, + layer shell surfaces do not receive keyboard events; this request can + be used to change this. + + This setting is inherited by child surfaces set by the get_popup + request. + + Layer surfaces receive pointer, touch, and tablet events normally. If + you do not want to receive them, set the input region on your surface + to an empty region. + + Keyboard interactivity is double-buffered, see wl_surface.commit. + + + + + + + This assigns an xdg_popup's parent to this layer_surface. This popup + should have been created via xdg_surface::get_popup with the parent set + to NULL, and this request must be invoked before committing the popup's + initial state. + + See the documentation of xdg_popup for more details about what an + xdg_popup is and how it is used. + + + + + + + When a configure event is received, if a client commits the + surface in response to the configure event, then the client + must make an ack_configure request sometime before the commit + request, passing along the serial of the configure event. + + If the client receives multiple configure events before it + can respond to one, it only has to ack the last configure event. + + A client is not required to commit immediately after sending + an ack_configure request - it may even ack_configure several times + before its next surface commit. + + A client may send multiple ack_configure requests before committing, but + only the last request sent before a commit indicates which configure + event the client really is responding to. + + + + + + + This request destroys the layer surface. + + + + + + The configure event asks the client to resize its surface. + + Clients should arrange their surface for the new states, and then send + an ack_configure request with the serial sent in this configure event at + some point before committing the new surface. + + The client is free to dismiss all but the last configure event it + received. + + The width and height arguments specify the size of the window in + surface-local coordinates. + + The size is a hint, in the sense that the client is free to ignore it if + it doesn't resize, pick a smaller size (to satisfy aspect ratio or + resize in steps of NxM pixels). If the client picks a smaller size and + is anchored to two opposite anchors (e.g. 'top' and 'bottom'), the + surface will be centered on this axis. + + If the width or height arguments are zero, it means the client should + decide its own window dimension. + + + + + + + + + The closed event is sent by the compositor when the surface will no + longer be shown. The output may have been destroyed or the user may + have asked for it to be removed. Further changes to the surface will be + ignored. The client should destroy the resource after receiving this + event, and create a new surface if they so choose. + + + + + + + + + + + + + + + + + + + + + + + Change the layer that the surface is rendered on. + + Layer is double-buffered, see wl_surface.commit. + + + + + + + + + Requests an edge for the exclusive zone to apply. The exclusive + edge will be automatically deduced from anchor points when possible, + but when the surface is anchored to a corner, it will be necessary + to set it explicitly to disambiguate, as it is not possible to deduce + which one of the two corner edges should be used. + + The edge must be one the surface is anchored to, otherwise the + invalid_exclusive_edge protocol error will be raised. + + + + + diff --git a/3rdparty/wlroots/protocol/wlr-output-management-unstable-v1.xml b/3rdparty/wlroots/protocol/wlr-output-management-unstable-v1.xml new file mode 100644 index 0000000000..541284a8c1 --- /dev/null +++ b/3rdparty/wlroots/protocol/wlr-output-management-unstable-v1.xml @@ -0,0 +1,611 @@ + + + + Copyright © 2019 Purism SPC + + Permission to use, copy, modify, distribute, and sell this + software and its documentation for any purpose is hereby granted + without fee, provided that the above copyright notice appear in + all copies and that both that copyright notice and this permission + notice appear in supporting documentation, and that the name of + the copyright holders not be used in advertising or publicity + pertaining to distribution of the software without specific, + written prior permission. The copyright holders make no + representations about the suitability of this software for any + purpose. It is provided "as is" without express or implied + warranty. + + THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS + SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY + SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN + AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, + ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + THIS SOFTWARE. + + + + This protocol exposes interfaces to obtain and modify output device + configuration. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + This interface is a manager that allows reading and writing the current + output device configuration. + + Output devices that display pixels (e.g. a physical monitor or a virtual + output in a window) are represented as heads. Heads cannot be created nor + destroyed by the client, but they can be enabled or disabled and their + properties can be changed. Each head may have one or more available modes. + + Whenever a head appears (e.g. a monitor is plugged in), it will be + advertised via the head event. Immediately after the output manager is + bound, all current heads are advertised. + + Whenever a head's properties change, the relevant wlr_output_head events + will be sent. Not all head properties will be sent: only properties that + have changed need to. + + Whenever a head disappears (e.g. a monitor is unplugged), a + wlr_output_head.finished event will be sent. + + After one or more heads appear, change or disappear, the done event will + be sent. It carries a serial which can be used in a create_configuration + request to update heads properties. + + The information obtained from this protocol should only be used for output + configuration purposes. This protocol is not designed to be a generic + output property advertisement protocol for regular clients. Instead, + protocols such as xdg-output should be used. + + + + + This event introduces a new head. This happens whenever a new head + appears (e.g. a monitor is plugged in) or after the output manager is + bound. + + + + + + + This event is sent after all information has been sent after binding to + the output manager object and after any subsequent changes. This applies + to child head and mode objects as well. In other words, this event is + sent whenever a head or mode is created or destroyed and whenever one of + their properties has been changed. Not all state is re-sent each time + the current configuration changes: only the actual changes are sent. + + This allows changes to the output configuration to be seen as atomic, + even if they happen via multiple events. + + A serial is sent to be used in a future create_configuration request. + + + + + + + Create a new output configuration object. This allows to update head + properties. + + + + + + + + Indicates the client no longer wishes to receive events for output + configuration changes. However the compositor may emit further events, + until the finished event is emitted. + + The client must not send any more requests after this one. + + + + + + This event indicates that the compositor is done sending manager events. + The compositor will destroy the object immediately after sending this + event, so it will become invalid and the client should release any + resources associated with it. + + + + + + + A head is an output device. The difference between a wl_output object and + a head is that heads are advertised even if they are turned off. A head + object only advertises properties and cannot be used directly to change + them. + + A head has some read-only properties: modes, name, description and + physical_size. These cannot be changed by clients. + + Other properties can be updated via a wlr_output_configuration object. + + Properties sent via this interface are applied atomically via the + wlr_output_manager.done event. No guarantees are made regarding the order + in which properties are sent. + + + + + This event describes the head name. + + The naming convention is compositor defined, but limited to alphanumeric + characters and dashes (-). Each name is unique among all wlr_output_head + objects, but if a wlr_output_head object is destroyed the same name may + be reused later. The names will also remain consistent across sessions + with the same hardware and software configuration. + + Examples of names include 'HDMI-A-1', 'WL-1', 'X11-1', etc. However, do + not assume that the name is a reflection of an underlying DRM + connector, X11 connection, etc. + + If this head matches a wl_output, the wl_output.name event must report + the same name. + + The name event is sent after a wlr_output_head object is created. This + event is only sent once per object, and the name does not change over + the lifetime of the wlr_output_head object. + + + + + + + This event describes a human-readable description of the head. + + The description is a UTF-8 string with no convention defined for its + contents. Examples might include 'Foocorp 11" Display' or 'Virtual X11 + output via :1'. However, do not assume that the name is a reflection of + the make, model, serial of the underlying DRM connector or the display + name of the underlying X11 connection, etc. + + If this head matches a wl_output, the wl_output.description event must + report the same name. + + The description event is sent after a wlr_output_head object is created. + This event is only sent once per object, and the description does not + change over the lifetime of the wlr_output_head object. + + + + + + + This event describes the physical size of the head. This event is only + sent if the head has a physical size (e.g. is not a projector or a + virtual device). + + The physical size event is sent after a wlr_output_head object is created. This + event is only sent once per object, and the physical size does not change over + the lifetime of the wlr_output_head object. + + + + + + + + This event introduces a mode for this head. It is sent once per + supported mode. + + + + + + + This event describes whether the head is enabled. A disabled head is not + mapped to a region of the global compositor space. + + When a head is disabled, some properties (current_mode, position, + transform and scale) are irrelevant. + + + + + + + This event describes the mode currently in use for this head. It is only + sent if the output is enabled. + + + + + + + This events describes the position of the head in the global compositor + space. It is only sent if the output is enabled. + + + + + + + + This event describes the transformation currently applied to the head. + It is only sent if the output is enabled. + + + + + + + This events describes the scale of the head in the global compositor + space. It is only sent if the output is enabled. + + + + + + + This event indicates that the head is no longer available. The head + object becomes inert. Clients should send a destroy request and release + any resources associated with it. + + + + + + + + This event describes the manufacturer of the head. + + Together with the model and serial_number events the purpose is to + allow clients to recognize heads from previous sessions and for example + load head-specific configurations back. + + It is not guaranteed this event will be ever sent. A reason for that + can be that the compositor does not have information about the make of + the head or the definition of a make is not sensible in the current + setup, for example in a virtual session. Clients can still try to + identify the head by available information from other events but should + be aware that there is an increased risk of false positives. + + If sent, the make event is sent after a wlr_output_head object is + created and only sent once per object. The make does not change over + the lifetime of the wlr_output_head object. + + It is not recommended to display the make string in UI to users. For + that the string provided by the description event should be preferred. + + + + + + + This event describes the model of the head. + + Together with the make and serial_number events the purpose is to + allow clients to recognize heads from previous sessions and for example + load head-specific configurations back. + + It is not guaranteed this event will be ever sent. A reason for that + can be that the compositor does not have information about the model of + the head or the definition of a model is not sensible in the current + setup, for example in a virtual session. Clients can still try to + identify the head by available information from other events but should + be aware that there is an increased risk of false positives. + + If sent, the model event is sent after a wlr_output_head object is + created and only sent once per object. The model does not change over + the lifetime of the wlr_output_head object. + + It is not recommended to display the model string in UI to users. For + that the string provided by the description event should be preferred. + + + + + + + This event describes the serial number of the head. + + Together with the make and model events the purpose is to allow clients + to recognize heads from previous sessions and for example load head- + specific configurations back. + + It is not guaranteed this event will be ever sent. A reason for that + can be that the compositor does not have information about the serial + number of the head or the definition of a serial number is not sensible + in the current setup. Clients can still try to identify the head by + available information from other events but should be aware that there + is an increased risk of false positives. + + If sent, the serial number event is sent after a wlr_output_head object + is created and only sent once per object. The serial number does not + change over the lifetime of the wlr_output_head object. + + It is not recommended to display the serial_number string in UI to + users. For that the string provided by the description event should be + preferred. + + + + + + + + + This request indicates that the client will no longer use this head + object. + + + + + + + + + + + + + This event describes whether adaptive sync is currently enabled for + the head or not. Adaptive sync is also known as Variable Refresh + Rate or VRR. + + + + + + + + This object describes an output mode. + + Some heads don't support output modes, in which case modes won't be + advertised. + + Properties sent via this interface are applied atomically via the + wlr_output_manager.done event. No guarantees are made regarding the order + in which properties are sent. + + + + + This event describes the mode size. The size is given in physical + hardware units of the output device. This is not necessarily the same as + the output size in the global compositor space. For instance, the output + may be scaled or transformed. + + + + + + + + This event describes the mode's fixed vertical refresh rate. It is only + sent if the mode has a fixed refresh rate. + + + + + + + This event advertises this mode as preferred. + + + + + + This event indicates that the mode is no longer available. The mode + object becomes inert. Clients should send a destroy request and release + any resources associated with it. + + + + + + + + This request indicates that the client will no longer use this mode + object. + + + + + + + This object is used by the client to describe a full output configuration. + + First, the client needs to setup the output configuration. Each head can + be either enabled (and configured) or disabled. It is a protocol error to + send two enable_head or disable_head requests with the same head. It is a + protocol error to omit a head in a configuration. + + Then, the client can apply or test the configuration. The compositor will + then reply with a succeeded, failed or cancelled event. Finally the client + should destroy the configuration object. + + + + + + + + + + + Enable a head. This request creates a head configuration object that can + be used to change the head's properties. + + + + + + + + Disable a head. + + + + + + + Apply the new output configuration. + + In case the configuration is successfully applied, there is no guarantee + that the new output state matches completely the requested + configuration. For instance, a compositor might round the scale if it + doesn't support fractional scaling. + + After this request has been sent, the compositor must respond with an + succeeded, failed or cancelled event. Sending a request that isn't the + destructor is a protocol error. + + + + + + Test the new output configuration. The configuration won't be applied, + but will only be validated. + + Even if the compositor succeeds to test a configuration, applying it may + fail. + + After this request has been sent, the compositor must respond with an + succeeded, failed or cancelled event. Sending a request that isn't the + destructor is a protocol error. + + + + + + Sent after the compositor has successfully applied the changes or + tested them. + + Upon receiving this event, the client should destroy this object. + + If the current configuration has changed, events to describe the changes + will be sent followed by a wlr_output_manager.done event. + + + + + + Sent if the compositor rejects the changes or failed to apply them. The + compositor should revert any changes made by the apply request that + triggered this event. + + Upon receiving this event, the client should destroy this object. + + + + + + Sent if the compositor cancels the configuration because the state of an + output changed and the client has outdated information (e.g. after an + output has been hotplugged). + + The client can create a new configuration with a newer serial and try + again. + + Upon receiving this event, the client should destroy this object. + + + + + + Using this request a client can tell the compositor that it is not going + to use the configuration object anymore. Any changes to the outputs + that have not been applied will be discarded. + + This request also destroys wlr_output_configuration_head objects created + via this object. + + + + + + + This object is used by the client to update a single head's configuration. + + It is a protocol error to set the same property twice. + + + + + + + + + + + + + + This request sets the head's mode. + + + + + + + This request assigns a custom mode to the head. The size is given in + physical hardware units of the output device. If set to zero, the + refresh rate is unspecified. + + It is a protocol error to set both a mode and a custom mode. + + + + + + + + + This request sets the head's position in the global compositor space. + + + + + + + + This request sets the head's transform. + + + + + + + This request sets the head's scale. + + + + + + + + + This request enables/disables adaptive sync. Adaptive sync is also + known as Variable Refresh Rate or VRR. + + + + + diff --git a/3rdparty/wlroots/protocol/wlr-output-power-management-unstable-v1.xml b/3rdparty/wlroots/protocol/wlr-output-power-management-unstable-v1.xml new file mode 100644 index 0000000000..20dbb77604 --- /dev/null +++ b/3rdparty/wlroots/protocol/wlr-output-power-management-unstable-v1.xml @@ -0,0 +1,128 @@ + + + + Copyright © 2019 Purism SPC + + 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 (including the next + paragraph) 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. + + + + This protocol allows clients to control power management modes + of outputs that are currently part of the compositor space. The + intent is to allow special clients like desktop shells to power + down outputs when the system is idle. + + To modify outputs not currently part of the compositor space see + wlr-output-management. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + This interface is a manager that allows creating per-output power + management mode controls. + + + + + Create an output power management mode control that can be used to + adjust the power management mode for a given output. + + + + + + + + All objects created by the manager will still remain valid, until their + appropriate destroy request has been called. + + + + + + + This object offers requests to set the power management mode of + an output. + + + + + + + + + + + + + + Set an output's power save mode to the given mode. The mode change + is effective immediately. If the output does not support the given + mode a failed event is sent. + + + + + + + Report the power management mode change of an output. + + The mode event is sent after an output changed its power + management mode. The reason can be a client using set_mode or the + compositor deciding to change an output's mode. + This event is also sent immediately when the object is created + so the client is informed about the current power management mode. + + + + + + + This event indicates that the output power management mode control + is no longer valid. This can happen for a number of reasons, + including: + - The output doesn't support power management + - Another client already has exclusive power management mode control + for this output + - The output disappeared + + Upon receiving this event, the client should destroy this object. + + + + + + Destroys the output power management mode control object. + + + + diff --git a/3rdparty/wlroots/protocol/wlr-screencopy-unstable-v1.xml b/3rdparty/wlroots/protocol/wlr-screencopy-unstable-v1.xml new file mode 100644 index 0000000000..85b57d7ea9 --- /dev/null +++ b/3rdparty/wlroots/protocol/wlr-screencopy-unstable-v1.xml @@ -0,0 +1,231 @@ + + + + Copyright © 2018 Simon Ser + Copyright © 2019 Andri Yngvason + + 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 (including the next + paragraph) 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. + + + + This protocol allows clients to ask the compositor to copy part of the + screen content to a client buffer. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + This object is a manager which offers requests to start capturing from a + source. + + + + + Capture the next frame of an entire output. + + + + + + + + + Capture the next frame of an output's region. + + The region is given in output logical coordinates, see + xdg_output.logical_size. The region will be clipped to the output's + extents. + + + + + + + + + + + + + All objects created by the manager will still remain valid, until their + appropriate destroy request has been called. + + + + + + + This object represents a single frame. + + When created, a series of buffer events will be sent, each representing a + supported buffer type. The "buffer_done" event is sent afterwards to + indicate that all supported buffer types have been enumerated. The client + will then be able to send a "copy" request. If the capture is successful, + the compositor will send a "flags" event followed by a "ready" event. + + For objects version 2 or lower, wl_shm buffers are always supported, ie. + the "buffer" event is guaranteed to be sent. + + If the capture failed, the "failed" event is sent. This can happen anytime + before the "ready" event. + + Once either a "ready" or a "failed" event is received, the client should + destroy the frame. + + + + + Provides information about wl_shm buffer parameters that need to be + used for this frame. This event is sent once after the frame is created + if wl_shm buffers are supported. + + + + + + + + + + Copy the frame to the supplied buffer. The buffer must have the + correct size, see zwlr_screencopy_frame_v1.buffer and + zwlr_screencopy_frame_v1.linux_dmabuf. The buffer needs to have a + supported format. + + If the frame is successfully copied, "flags" and "ready" events are + sent. Otherwise, a "failed" event is sent. + + + + + + + + + + + + + + + + Provides flags about the frame. This event is sent once before the + "ready" event. + + + + + + + Called as soon as the frame is copied, indicating it is available + for reading. This event includes the time at which the presentation took place. + + The timestamp is expressed as tv_sec_hi, tv_sec_lo, tv_nsec triples, + each component being an unsigned 32-bit value. Whole seconds are in + tv_sec which is a 64-bit value combined from tv_sec_hi and tv_sec_lo, + and the additional fractional part in tv_nsec as nanoseconds. Hence, + for valid timestamps tv_nsec must be in [0, 999999999]. The seconds part + may have an arbitrary offset at start. + + After receiving this event, the client should destroy the object. + + + + + + + + + This event indicates that the attempted frame copy has failed. + + After receiving this event, the client should destroy the object. + + + + + + Destroys the frame. This request can be sent at any time by the client. + + + + + + + Same as copy, except it waits until there is damage to copy. + + + + + + + This event is sent right before the ready event when copy_with_damage is + requested. It may be generated multiple times for each copy_with_damage + request. + + The arguments describe a box around an area that has changed since the + last copy request that was derived from the current screencopy manager + instance. + + The union of all regions received between the call to copy_with_damage + and a ready event is the total damage since the prior ready event. + + + + + + + + + + + Provides information about linux-dmabuf buffer parameters that need to + be used for this frame. This event is sent once after the frame is + created if linux-dmabuf buffers are supported. + + + + + + + + + This event is sent once after all buffer events have been sent. + + The client should proceed to create a buffer of one of the supported + types, and send a "copy" request. + + + + diff --git a/3rdparty/wlroots/protocol/wlr-virtual-pointer-unstable-v1.xml b/3rdparty/wlroots/protocol/wlr-virtual-pointer-unstable-v1.xml new file mode 100644 index 0000000000..ea243e7c80 --- /dev/null +++ b/3rdparty/wlroots/protocol/wlr-virtual-pointer-unstable-v1.xml @@ -0,0 +1,152 @@ + + + + Copyright © 2019 Josef Gajdusek + + 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 (including the next + paragraph) 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. + + + + + This protocol allows clients to emulate a physical pointer device. The + requests are mostly mirror opposites of those specified in wl_pointer. + + + + + + + + + + The pointer has moved by a relative amount to the previous request. + + Values are in the global compositor space. + + + + + + + + + The pointer has moved in an absolute coordinate frame. + + Value of x can range from 0 to x_extent, value of y can range from 0 + to y_extent. + + + + + + + + + + + A button was pressed or released. + + + + + + + + + Scroll and other axis requests. + + + + + + + + + Indicates the set of events that logically belong together. + + + + + + Source information for scroll and other axis. + + + + + + + Stop notification for scroll and other axes. + + + + + + + + Discrete step information for scroll and other axes. + + This event allows the client to extend data normally sent using the axis + event with discrete value. + + + + + + + + + + + + + + + This object allows clients to create individual virtual pointer objects. + + + + + Creates a new virtual pointer. The optional seat is a suggestion to the + compositor. + + + + + + + + + + + + + Creates a new virtual pointer. The seat and the output arguments are + optional. If the seat argument is set, the compositor should assign the + input device to the requested seat. If the output argument is set, the + compositor should map the input device to the requested output. + + + + + + + diff --git a/3rdparty/wlroots/release.sh b/3rdparty/wlroots/release.sh new file mode 100755 index 0000000000..8531a23b48 --- /dev/null +++ b/3rdparty/wlroots/release.sh @@ -0,0 +1,32 @@ +#!/bin/sh -eu + +prev=$(git describe --tags --abbrev=0) +next=$(meson rewrite kwargs info project / | jq -r '.kwargs["project#/"].version') + +case "$next" in +*-dev) + echo "This is a development version" + exit 1 + ;; +esac + +if [ "$prev" = "$next" ]; then + echo "Version not bumped in meson.build" + exit 1 +fi + +if ! git diff-index --quiet HEAD -- meson.build; then + echo "meson.build not committed" + exit 1 +fi + +shortlog="$(git shortlog --no-merges "$prev..")" +(echo "wlroots $next"; echo ""; echo "$shortlog") | git tag "$next" -ase -F - + +prefix=wlroots-$next +archive=$prefix.tar.gz +git archive --prefix="$prefix/" -o "$archive" "$next" +gpg --output "$archive".sig --detach-sig "$archive" + +git push --follow-tags +glab release create "$next" "$archive" "$archive.sig" --notes "" diff --git a/3rdparty/wlroots/render/allocator/allocator.c b/3rdparty/wlroots/render/allocator/allocator.c new file mode 100644 index 0000000000..b7dbf3d659 --- /dev/null +++ b/3rdparty/wlroots/render/allocator/allocator.c @@ -0,0 +1,201 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "render/allocator/drm_dumb.h" +#include "render/allocator/shm.h" +#include "render/wlr_renderer.h" + +#if WLR_HAS_GBM_ALLOCATOR +#include "render/allocator/gbm.h" +#endif + +#if WLR_HAS_UDMABUF_ALLOCATOR +#include "render/allocator/udmabuf.h" +#endif + +void wlr_allocator_init(struct wlr_allocator *alloc, + const struct wlr_allocator_interface *impl, uint32_t buffer_caps) { + assert(impl && impl->destroy && impl->create_buffer); + *alloc = (struct wlr_allocator){ + .impl = impl, + .buffer_caps = buffer_caps, + }; + + wl_signal_init(&alloc->events.destroy); +} + +/* Re-open the DRM node to avoid GEM handle ref'counting issues. See: + * https://gitlab.freedesktop.org/mesa/drm/-/merge_requests/110 + */ +static int reopen_drm_node(int drm_fd, bool allow_render_node) { + if (drmIsMaster(drm_fd)) { + // Only recent kernels support empty leases + uint32_t lessee_id; + int lease_fd = drmModeCreateLease(drm_fd, NULL, 0, O_CLOEXEC, &lessee_id); + if (lease_fd >= 0) { + return lease_fd; + } else if (lease_fd != -EINVAL && lease_fd != -EOPNOTSUPP) { + wlr_log_errno(WLR_ERROR, "drmModeCreateLease failed"); + return -1; + } + wlr_log(WLR_DEBUG, "drmModeCreateLease failed, " + "falling back to plain open"); + } + + char *name = NULL; + if (allow_render_node) { + name = drmGetRenderDeviceNameFromFd(drm_fd); + } + if (name == NULL) { + // Either the DRM device has no render node, either the caller wants + // a primary node + name = drmGetDeviceNameFromFd2(drm_fd); + if (name == NULL) { + wlr_log(WLR_ERROR, "drmGetDeviceNameFromFd2 failed"); + return -1; + } + } + + int new_fd = open(name, O_RDWR | O_CLOEXEC); + if (new_fd < 0) { + wlr_log_errno(WLR_ERROR, "Failed to open DRM node '%s'", name); + free(name); + return -1; + } + + free(name); + + // If we're using a DRM primary node and we are DRM master (e.g. because + // we're running under the DRM backend), we need to use the legacy DRM + // authentication mechanism to have the permission to manipulate DRM dumb + // buffers. + if (drmIsMaster(drm_fd) && drmGetNodeTypeFromFd(new_fd) == DRM_NODE_PRIMARY) { + drm_magic_t magic; + if (drmGetMagic(new_fd, &magic) < 0) { + wlr_log_errno(WLR_ERROR, "drmGetMagic failed"); + close(new_fd); + return -1; + } + + if (drmAuthMagic(drm_fd, magic) < 0) { + wlr_log_errno(WLR_ERROR, "drmAuthMagic failed"); + close(new_fd); + return -1; + } + } + + return new_fd; +} + +struct wlr_allocator *wlr_allocator_autocreate(struct wlr_backend *backend, + struct wlr_renderer *renderer) { + uint32_t backend_caps = backend->buffer_caps; + uint32_t renderer_caps = renderer->render_buffer_caps; + + // Note, drm_fd may be negative if unavailable + int drm_fd = wlr_backend_get_drm_fd(backend); + if (drm_fd < 0) { + drm_fd = wlr_renderer_get_drm_fd(renderer); + } + + struct wlr_allocator *alloc = NULL; + + uint32_t gbm_caps = WLR_BUFFER_CAP_DMABUF; + if ((backend_caps & gbm_caps) && (renderer_caps & gbm_caps) + && drm_fd >= 0) { +#if WLR_HAS_GBM_ALLOCATOR + wlr_log(WLR_DEBUG, "Trying to create gbm allocator"); + int gbm_fd = reopen_drm_node(drm_fd, true); + if (gbm_fd < 0) { + return NULL; + } + if ((alloc = wlr_gbm_allocator_create(gbm_fd)) != NULL) { + return alloc; + } + close(gbm_fd); + wlr_log(WLR_DEBUG, "Failed to create gbm allocator"); +#else + wlr_log(WLR_DEBUG, "Skipping gbm allocator: disabled at compile-time"); +#endif + } + + uint32_t shm_caps = WLR_BUFFER_CAP_SHM | WLR_BUFFER_CAP_DATA_PTR; + if ((backend_caps & shm_caps) && (renderer_caps & shm_caps)) { + wlr_log(WLR_DEBUG, "Trying to create shm allocator"); + if ((alloc = wlr_shm_allocator_create()) != NULL) { + return alloc; + } + wlr_log(WLR_DEBUG, "Failed to create shm allocator"); + } + + uint32_t drm_caps = WLR_BUFFER_CAP_DMABUF | WLR_BUFFER_CAP_DATA_PTR; + if ((backend_caps & drm_caps) && (renderer_caps & drm_caps) + && drm_fd >= 0 && drmIsMaster(drm_fd)) { + wlr_log(WLR_DEBUG, "Trying to create drm dumb allocator"); + int dumb_fd = reopen_drm_node(drm_fd, false); + if (dumb_fd < 0) { + return NULL; + } + if ((alloc = wlr_drm_dumb_allocator_create(dumb_fd)) != NULL) { + return alloc; + } + close(dumb_fd); + wlr_log(WLR_DEBUG, "Failed to create drm dumb allocator"); + } + + uint32_t udmabuf_caps = WLR_BUFFER_CAP_DMABUF | WLR_BUFFER_CAP_SHM; + if ((backend_caps & udmabuf_caps) && (renderer_caps & udmabuf_caps) && + drm_fd < 0) { +#if WLR_HAS_UDMABUF_ALLOCATOR + wlr_log(WLR_DEBUG, "Trying udmabuf allocator"); + if ((alloc = wlr_udmabuf_allocator_create()) != NULL) { + return alloc; + } + wlr_log(WLR_DEBUG, "Failed to create udmabuf allocator"); +#else + wlr_log(WLR_DEBUG, "Skipping udmabuf allocator: disabled at compile-time"); +#endif + } + + wlr_log(WLR_ERROR, "Failed to create allocator"); + return NULL; +} + +void wlr_allocator_destroy(struct wlr_allocator *alloc) { + if (alloc == NULL) { + return; + } + wl_signal_emit_mutable(&alloc->events.destroy, NULL); + + assert(wl_list_empty(&alloc->events.destroy.listener_list)); + + alloc->impl->destroy(alloc); +} + +struct wlr_buffer *wlr_allocator_create_buffer(struct wlr_allocator *alloc, + int width, int height, const struct wlr_drm_format *format) { + struct wlr_buffer *buffer = + alloc->impl->create_buffer(alloc, width, height, format); + if (buffer == NULL) { + return NULL; + } + if (alloc->buffer_caps & WLR_BUFFER_CAP_DATA_PTR) { + assert(buffer->impl->begin_data_ptr_access && + buffer->impl->end_data_ptr_access); + } + if (alloc->buffer_caps & WLR_BUFFER_CAP_DMABUF) { + assert(buffer->impl->get_dmabuf); + } + if (alloc->buffer_caps & WLR_BUFFER_CAP_SHM) { + assert(buffer->impl->get_shm); + } + return buffer; +} diff --git a/3rdparty/wlroots/render/allocator/drm_dumb.c b/3rdparty/wlroots/render/allocator/drm_dumb.c new file mode 100644 index 0000000000..ea2757b0be --- /dev/null +++ b/3rdparty/wlroots/render/allocator/drm_dumb.c @@ -0,0 +1,232 @@ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "render/allocator/drm_dumb.h" +#include "render/drm_format_set.h" +#include "render/pixel_format.h" + +static const struct wlr_buffer_impl buffer_impl; + +static struct wlr_drm_dumb_buffer *drm_dumb_buffer_from_buffer( + struct wlr_buffer *wlr_buf) { + assert(wlr_buf->impl == &buffer_impl); + struct wlr_drm_dumb_buffer *buf = wl_container_of(wlr_buf, buf, base); + return buf; +} + +static struct wlr_drm_dumb_buffer *create_buffer( + struct wlr_drm_dumb_allocator *alloc, int width, int height, + const struct wlr_drm_format *format) { + if (!wlr_drm_format_has(format, DRM_FORMAT_MOD_INVALID) && + !wlr_drm_format_has(format, DRM_FORMAT_MOD_LINEAR)) { + wlr_log(WLR_ERROR, "DRM dumb allocator only supports INVALID and " + "LINEAR modifiers"); + return NULL; + } + + const struct wlr_pixel_format_info *info = + drm_get_pixel_format_info(format->format); + if (info == NULL) { + wlr_log(WLR_ERROR, "DRM format 0x%"PRIX32" not supported", + format->format); + return NULL; + } else if (pixel_format_info_pixels_per_block(info) != 1) { + wlr_log(WLR_ERROR, "Block formats are not supported"); + return NULL; + } + + struct wlr_drm_dumb_buffer *buffer = calloc(1, sizeof(*buffer)); + if (buffer == NULL) { + return NULL; + } + wlr_buffer_init(&buffer->base, &buffer_impl, width, height); + wl_list_insert(&alloc->buffers, &buffer->link); + + buffer->drm_fd = alloc->drm_fd; + + uint32_t bpp = 8 * info->bytes_per_block; + if (drmModeCreateDumbBuffer(alloc->drm_fd, width, height, bpp, 0, + &buffer->handle, &buffer->stride, &buffer->size) != 0) { + wlr_log_errno(WLR_ERROR, "Failed to create DRM dumb buffer"); + goto create_destroy; + } + + buffer->width = width; + buffer->height = height; + buffer->format = format->format; + + uint64_t offset; + if (drmModeMapDumbBuffer(alloc->drm_fd, buffer->handle, &offset) != 0) { + wlr_log_errno(WLR_ERROR, "Failed to map DRM dumb buffer"); + goto create_destroy; + } + + buffer->data = mmap(NULL, buffer->size, PROT_READ | PROT_WRITE, MAP_SHARED, + alloc->drm_fd, offset); + if (buffer->data == MAP_FAILED) { + wlr_log_errno(WLR_ERROR, "Failed to mmap DRM dumb buffer"); + goto create_destroy; + } + + memset(buffer->data, 0, buffer->size); + + int prime_fd; + if (drmPrimeHandleToFD(alloc->drm_fd, buffer->handle, DRM_CLOEXEC, + &prime_fd) != 0) { + wlr_log_errno(WLR_ERROR, "Failed to get PRIME handle from GEM handle"); + goto create_destroy; + } + + buffer->dmabuf = (struct wlr_dmabuf_attributes){ + .width = buffer->width, + .height = buffer->height, + .format = format->format, + .modifier = DRM_FORMAT_MOD_LINEAR, + .n_planes = 1, + .offset[0] = 0, + .stride[0] = buffer->stride, + .fd[0] = prime_fd, + }; + + wlr_log(WLR_DEBUG, "Allocated %"PRIu32"x%"PRIu32" DRM dumb buffer", + buffer->width, buffer->height); + + return buffer; + +create_destroy: + wlr_buffer_drop(&buffer->base); + return NULL; +} + +static bool drm_dumb_buffer_begin_data_ptr_access(struct wlr_buffer *wlr_buffer, + uint32_t flags, void **data, uint32_t *format, size_t *stride) { + struct wlr_drm_dumb_buffer *buf = drm_dumb_buffer_from_buffer(wlr_buffer); + *data = buf->data; + *stride = buf->stride; + *format = buf->format; + return true; +} + +static void drm_dumb_buffer_end_data_ptr_access(struct wlr_buffer *wlr_buffer) { + // This space is intentionally left blank +} + +static bool buffer_get_dmabuf(struct wlr_buffer *wlr_buffer, + struct wlr_dmabuf_attributes *attribs) { + struct wlr_drm_dumb_buffer *buf = drm_dumb_buffer_from_buffer(wlr_buffer); + *attribs = buf->dmabuf; + return true; +} + +static void buffer_destroy(struct wlr_buffer *wlr_buffer) { + struct wlr_drm_dumb_buffer *buf = drm_dumb_buffer_from_buffer(wlr_buffer); + + wlr_buffer_finish(wlr_buffer); + + if (buf->data) { + munmap(buf->data, buf->size); + } + + wlr_dmabuf_attributes_finish(&buf->dmabuf); + + if (buf->drm_fd >= 0) { + if (drmModeDestroyDumbBuffer(buf->drm_fd, buf->handle) != 0) { + wlr_log_errno(WLR_ERROR, "Failed to destroy DRM dumb buffer"); + } + } + + wl_list_remove(&buf->link); + free(buf); +} + +static const struct wlr_buffer_impl buffer_impl = { + .destroy = buffer_destroy, + .get_dmabuf = buffer_get_dmabuf, + .begin_data_ptr_access = drm_dumb_buffer_begin_data_ptr_access, + .end_data_ptr_access = drm_dumb_buffer_end_data_ptr_access, +}; + +static const struct wlr_allocator_interface allocator_impl; + +static struct wlr_drm_dumb_allocator *drm_dumb_alloc_from_alloc( + struct wlr_allocator *wlr_alloc) { + assert(wlr_alloc->impl == &allocator_impl); + struct wlr_drm_dumb_allocator *alloc = wl_container_of(wlr_alloc, alloc, base); + return alloc; +} + +static struct wlr_buffer *allocator_create_buffer( + struct wlr_allocator *wlr_alloc, int width, int height, + const struct wlr_drm_format *drm_format) { + struct wlr_drm_dumb_allocator *alloc = drm_dumb_alloc_from_alloc(wlr_alloc); + struct wlr_drm_dumb_buffer *buffer = create_buffer(alloc, width, height, + drm_format); + if (buffer == NULL) { + return NULL; + } + return &buffer->base; +} + +static void allocator_destroy(struct wlr_allocator *wlr_alloc) { + struct wlr_drm_dumb_allocator *alloc = drm_dumb_alloc_from_alloc(wlr_alloc); + + struct wlr_drm_dumb_buffer *buf, *buf_tmp; + wl_list_for_each_safe(buf, buf_tmp, &alloc->buffers, link) { + buf->drm_fd = -1; + wl_list_remove(&buf->link); + wl_list_init(&buf->link); + } + + close(alloc->drm_fd); + free(alloc); +} + +static const struct wlr_allocator_interface allocator_impl = { + .create_buffer = allocator_create_buffer, + .destroy = allocator_destroy, +}; + +struct wlr_allocator *wlr_drm_dumb_allocator_create(int drm_fd) { + if (drmGetNodeTypeFromFd(drm_fd) != DRM_NODE_PRIMARY) { + wlr_log(WLR_ERROR, "Cannot use DRM dumb buffers with non-primary DRM FD"); + return NULL; + } + + uint64_t has_dumb = 0; + if (drmGetCap(drm_fd, DRM_CAP_DUMB_BUFFER, &has_dumb) < 0) { + wlr_log(WLR_ERROR, "Failed to get DRM capabilities"); + return NULL; + } + + if (has_dumb == 0) { + wlr_log(WLR_ERROR, "DRM dumb buffers not supported"); + return NULL; + } + + struct wlr_drm_dumb_allocator *alloc = calloc(1, sizeof(*alloc)); + if (alloc == NULL) { + return NULL; + } + wlr_allocator_init(&alloc->base, &allocator_impl, + WLR_BUFFER_CAP_DATA_PTR | WLR_BUFFER_CAP_DMABUF); + + alloc->drm_fd = drm_fd; + wl_list_init(&alloc->buffers); + + wlr_log(WLR_DEBUG, "Created DRM dumb allocator"); + return &alloc->base; +} diff --git a/3rdparty/wlroots/render/allocator/gbm.c b/3rdparty/wlroots/render/allocator/gbm.c new file mode 100644 index 0000000000..fadfac9f8d --- /dev/null +++ b/3rdparty/wlroots/render/allocator/gbm.c @@ -0,0 +1,228 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "render/allocator/gbm.h" +#include "render/drm_format_set.h" + +static const struct wlr_buffer_impl buffer_impl; + +static struct wlr_gbm_buffer *get_gbm_buffer_from_buffer( + struct wlr_buffer *wlr_buffer) { + assert(wlr_buffer->impl == &buffer_impl); + struct wlr_gbm_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + return buffer; +} + +static bool export_gbm_bo(struct gbm_bo *bo, + struct wlr_dmabuf_attributes *out) { + struct wlr_dmabuf_attributes attribs = {0}; + + attribs.n_planes = gbm_bo_get_plane_count(bo); + if (attribs.n_planes > WLR_DMABUF_MAX_PLANES) { + wlr_log(WLR_ERROR, "GBM BO contains too many planes (%d)", + attribs.n_planes); + return false; + } + + attribs.width = gbm_bo_get_width(bo); + attribs.height = gbm_bo_get_height(bo); + attribs.format = gbm_bo_get_format(bo); + attribs.modifier = gbm_bo_get_modifier(bo); + + int i; + for (i = 0; i < attribs.n_planes; ++i) { + attribs.fd[i] = gbm_bo_get_fd_for_plane(bo, i); + if (attribs.fd[i] < 0) { + wlr_log(WLR_ERROR, "gbm_bo_get_fd_for_plane failed"); + goto error_fd; + } + + attribs.offset[i] = gbm_bo_get_offset(bo, i); + attribs.stride[i] = gbm_bo_get_stride_for_plane(bo, i); + } + + *out = attribs; + return true; + +error_fd: + for (int j = 0; j < i; ++j) { + close(attribs.fd[j]); + } + return false; +} + +static struct wlr_gbm_buffer *create_buffer(struct wlr_gbm_allocator *alloc, + int width, int height, const struct wlr_drm_format *format) { + struct gbm_device *gbm_device = alloc->gbm_device; + + assert(format->len > 0); + + bool has_modifier = true; + uint64_t fallback_modifier = DRM_FORMAT_MOD_INVALID; + errno = 0; + struct gbm_bo *bo = gbm_bo_create_with_modifiers(gbm_device, width, height, + format->format, format->modifiers, format->len); + if (bo == NULL) { + uint32_t usage = GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING; + if (format->len == 1 && + format->modifiers[0] == DRM_FORMAT_MOD_LINEAR) { + usage |= GBM_BO_USE_LINEAR; + fallback_modifier = DRM_FORMAT_MOD_LINEAR; + } else if (!wlr_drm_format_has(format, DRM_FORMAT_MOD_INVALID)) { + // If the format doesn't accept an implicit modifier, bail out. + wlr_log_errno(WLR_ERROR, "gbm_bo_create_with_modifiers failed"); + return NULL; + } + errno = 0; + bo = gbm_bo_create(gbm_device, width, height, format->format, usage); + has_modifier = false; + } + if (bo == NULL) { + wlr_log_errno(WLR_ERROR, "gbm_bo_create failed"); + return NULL; + } + + struct wlr_gbm_buffer *buffer = calloc(1, sizeof(*buffer)); + if (buffer == NULL) { + gbm_bo_destroy(bo); + return NULL; + } + wlr_buffer_init(&buffer->base, &buffer_impl, width, height); + buffer->gbm_bo = bo; + + if (!export_gbm_bo(bo, &buffer->dmabuf)) { + free(buffer); + gbm_bo_destroy(bo); + return NULL; + } + + // If the buffer has been allocated with an implicit modifier, make sure we + // don't populate the modifier field: other parts of the stack may not + // understand modifiers, and they can't strip the modifier. + if (!has_modifier) { + buffer->dmabuf.modifier = fallback_modifier; + } + + wl_list_insert(&alloc->buffers, &buffer->link); + + char *format_name = drmGetFormatName(buffer->dmabuf.format); + char *modifier_name = drmGetFormatModifierName(buffer->dmabuf.modifier); + wlr_log(WLR_DEBUG, "Allocated %dx%d GBM buffer " + "with format %s (0x%08"PRIX32"), modifier %s (0x%016"PRIX64")", + buffer->base.width, buffer->base.height, + format_name ? format_name : "", buffer->dmabuf.format, + modifier_name ? modifier_name : "", buffer->dmabuf.modifier); + free(format_name); + free(modifier_name); + + return buffer; +} + +static void buffer_destroy(struct wlr_buffer *wlr_buffer) { + struct wlr_gbm_buffer *buffer = get_gbm_buffer_from_buffer(wlr_buffer); + + wlr_buffer_finish(wlr_buffer); + + wlr_dmabuf_attributes_finish(&buffer->dmabuf); + if (buffer->gbm_bo != NULL) { + gbm_bo_destroy(buffer->gbm_bo); + } + wl_list_remove(&buffer->link); + free(buffer); +} + +static bool buffer_get_dmabuf(struct wlr_buffer *wlr_buffer, + struct wlr_dmabuf_attributes *attribs) { + struct wlr_gbm_buffer *buffer = + get_gbm_buffer_from_buffer(wlr_buffer); + *attribs = buffer->dmabuf; + return true; +} + +static const struct wlr_buffer_impl buffer_impl = { + .destroy = buffer_destroy, + .get_dmabuf = buffer_get_dmabuf, +}; + +static const struct wlr_allocator_interface allocator_impl; + +static struct wlr_gbm_allocator *get_gbm_alloc_from_alloc( + struct wlr_allocator *wlr_alloc) { + assert(wlr_alloc->impl == &allocator_impl); + struct wlr_gbm_allocator *alloc = wl_container_of(wlr_alloc, alloc, base); + return alloc; +} + +struct wlr_allocator *wlr_gbm_allocator_create(int fd) { + uint64_t cap; + if (drmGetCap(fd, DRM_CAP_PRIME, &cap) || + !(cap & DRM_PRIME_CAP_EXPORT)) { + wlr_log(WLR_ERROR, "PRIME export not supported"); + return NULL; + } + + struct wlr_gbm_allocator *alloc = calloc(1, sizeof(*alloc)); + if (alloc == NULL) { + return NULL; + } + wlr_allocator_init(&alloc->base, &allocator_impl, WLR_BUFFER_CAP_DMABUF); + + alloc->fd = fd; + wl_list_init(&alloc->buffers); + + alloc->gbm_device = gbm_create_device(fd); + if (alloc->gbm_device == NULL) { + wlr_log(WLR_ERROR, "gbm_create_device failed"); + free(alloc); + return NULL; + } + + wlr_log(WLR_DEBUG, "Created GBM allocator with backend %s", + gbm_device_get_backend_name(alloc->gbm_device)); + char *drm_name = drmGetDeviceNameFromFd2(fd); + wlr_log(WLR_DEBUG, "Using DRM node %s", drm_name); + free(drm_name); + + return &alloc->base; +} + +static void allocator_destroy(struct wlr_allocator *wlr_alloc) { + struct wlr_gbm_allocator *alloc = get_gbm_alloc_from_alloc(wlr_alloc); + + // The gbm_bo objects need to be destroyed before the gbm_device + struct wlr_gbm_buffer *buf, *buf_tmp; + wl_list_for_each_safe(buf, buf_tmp, &alloc->buffers, link) { + gbm_bo_destroy(buf->gbm_bo); + buf->gbm_bo = NULL; + wl_list_remove(&buf->link); + wl_list_init(&buf->link); + } + + gbm_device_destroy(alloc->gbm_device); + close(alloc->fd); + free(alloc); +} + +static struct wlr_buffer *allocator_create_buffer( + struct wlr_allocator *wlr_alloc, int width, int height, + const struct wlr_drm_format *format) { + struct wlr_gbm_allocator *alloc = get_gbm_alloc_from_alloc(wlr_alloc); + struct wlr_gbm_buffer *buffer = create_buffer(alloc, width, height, format); + if (buffer == NULL) { + return NULL; + } + return &buffer->base; +} + +static const struct wlr_allocator_interface allocator_impl = { + .destroy = allocator_destroy, + .create_buffer = allocator_create_buffer, +}; diff --git a/3rdparty/wlroots/render/allocator/meson.build b/3rdparty/wlroots/render/allocator/meson.build new file mode 100644 index 0000000000..b812f69414 --- /dev/null +++ b/3rdparty/wlroots/render/allocator/meson.build @@ -0,0 +1,41 @@ +allocators = get_option('allocators') +if 'auto' in allocators and get_option('auto_features').enabled() + allocators = ['gbm', 'udmabuf'] +elif 'auto' in allocators and get_option('auto_features').disabled() + allocators = [] +endif + +wlr_files += files( + 'allocator.c', + 'shm.c', + 'drm_dumb.c', +) + +gbm = disabler() +if 'gbm' in allocators or 'auto' in allocators + gbm = dependency('gbm', version: '>=21.1', required: 'gbm' in allocators) +endif +if gbm.found() + wlr_files += files('gbm.c') + wlr_deps += gbm + features += { 'gbm-allocator': true } +endif + +udmabuf = false +if 'udmabuf' in allocators or 'auto' in allocators + args = ['-D_GNU_SOURCE'] + prefix = [ + '#include ', + '#include ', + ] + udmabuf = (cc.has_function('memfd_create', args: args, prefix: prefix) and + cc.has_define('F_ADD_SEALS', args: args, prefix: prefix) and + cc.has_header('linux/udmabuf.h')) +endif +if 'udmabuf' in allocators and not udmabuf + error('memfd_create(), F_ADD_SEALS and are required for the udmabuf allocator') +endif +if udmabuf + wlr_files += files('udmabuf.c') + features += { 'udmabuf-allocator': true } +endif diff --git a/3rdparty/wlroots/render/allocator/shm.c b/3rdparty/wlroots/render/allocator/shm.c new file mode 100644 index 0000000000..b5be7d0142 --- /dev/null +++ b/3rdparty/wlroots/render/allocator/shm.c @@ -0,0 +1,121 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "render/pixel_format.h" +#include "render/allocator/shm.h" +#include "util/shm.h" + +static const struct wlr_buffer_impl buffer_impl; + +static struct wlr_shm_buffer *shm_buffer_from_buffer( + struct wlr_buffer *wlr_buffer) { + assert(wlr_buffer->impl == &buffer_impl); + struct wlr_shm_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + return buffer; +} + +static void buffer_destroy(struct wlr_buffer *wlr_buffer) { + struct wlr_shm_buffer *buffer = shm_buffer_from_buffer(wlr_buffer); + wlr_buffer_finish(wlr_buffer); + munmap(buffer->data, buffer->size); + close(buffer->shm.fd); + free(buffer); +} + +static bool buffer_get_shm(struct wlr_buffer *wlr_buffer, + struct wlr_shm_attributes *shm) { + struct wlr_shm_buffer *buffer = shm_buffer_from_buffer(wlr_buffer); + *shm = buffer->shm; + return true; +} + +static bool shm_buffer_begin_data_ptr_access(struct wlr_buffer *wlr_buffer, + uint32_t flags, void **data, uint32_t *format, size_t *stride) { + struct wlr_shm_buffer *buffer = shm_buffer_from_buffer(wlr_buffer); + *data = buffer->data; + *format = buffer->shm.format; + *stride = buffer->shm.stride; + return true; +} + +static void shm_buffer_end_data_ptr_access(struct wlr_buffer *wlr_buffer) { + // This space is intentionally left blank +} + +static const struct wlr_buffer_impl buffer_impl = { + .destroy = buffer_destroy, + .get_shm = buffer_get_shm, + .begin_data_ptr_access = shm_buffer_begin_data_ptr_access, + .end_data_ptr_access = shm_buffer_end_data_ptr_access, +}; + +static struct wlr_buffer *allocator_create_buffer( + struct wlr_allocator *wlr_allocator, int width, int height, + const struct wlr_drm_format *format) { + const struct wlr_pixel_format_info *info = + drm_get_pixel_format_info(format->format); + if (info == NULL) { + wlr_log(WLR_ERROR, "Unsupported pixel format 0x%"PRIX32, format->format); + return NULL; + } + + struct wlr_shm_buffer *buffer = calloc(1, sizeof(*buffer)); + if (buffer == NULL) { + return NULL; + } + wlr_buffer_init(&buffer->base, &buffer_impl, width, height); + + // TODO: consider using a single file for multiple buffers + int stride = pixel_format_info_min_stride(info, width); // TODO: align? + buffer->size = stride * height; + buffer->shm.fd = allocate_shm_file(buffer->size); + if (buffer->shm.fd < 0) { + free(buffer); + return NULL; + } + + buffer->shm.format = format->format; + buffer->shm.width = width; + buffer->shm.height = height; + buffer->shm.stride = stride; + buffer->shm.offset = 0; + + buffer->data = mmap(NULL, buffer->size, PROT_READ | PROT_WRITE, MAP_SHARED, + buffer->shm.fd, 0); + if (buffer->data == MAP_FAILED) { + wlr_log_errno(WLR_ERROR, "mmap failed"); + close(buffer->shm.fd); + free(buffer); + return NULL; + } + + return &buffer->base; +} + +static void allocator_destroy(struct wlr_allocator *wlr_allocator) { + free(wlr_allocator); +} + +static const struct wlr_allocator_interface allocator_impl = { + .destroy = allocator_destroy, + .create_buffer = allocator_create_buffer, +}; + +struct wlr_allocator *wlr_shm_allocator_create(void) { + struct wlr_shm_allocator *allocator = calloc(1, sizeof(*allocator)); + if (allocator == NULL) { + return NULL; + } + wlr_allocator_init(&allocator->base, &allocator_impl, + WLR_BUFFER_CAP_DATA_PTR | WLR_BUFFER_CAP_SHM); + + wlr_log(WLR_DEBUG, "Created shm allocator"); + return &allocator->base; +} diff --git a/3rdparty/wlroots/render/allocator/udmabuf.c b/3rdparty/wlroots/render/allocator/udmabuf.c new file mode 100644 index 0000000000..8a7109aa5f --- /dev/null +++ b/3rdparty/wlroots/render/allocator/udmabuf.c @@ -0,0 +1,163 @@ +#undef _POSIX_C_SOURCE +#define _GNU_SOURCE // for memfd_create() and F_ADD_SEALS + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "render/allocator/udmabuf.h" +#include "render/pixel_format.h" + +static bool buffer_get_shm(struct wlr_buffer *wlr_buffer, struct wlr_shm_attributes *shm) { + struct wlr_udmabuf_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + *shm = buffer->shm; + return true; +} + +static bool buffer_get_dmabuf(struct wlr_buffer *wlr_buffer, struct wlr_dmabuf_attributes *dmabuf) { + struct wlr_udmabuf_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + *dmabuf = buffer->dmabuf; + return true; +} + +static void buffer_destroy(struct wlr_buffer *wlr_buffer) { + struct wlr_udmabuf_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + wlr_buffer_finish(wlr_buffer); + wlr_dmabuf_attributes_finish(&buffer->dmabuf); + close(buffer->shm.fd); + free(buffer); +} + +static const struct wlr_buffer_impl buffer_impl = { + .destroy = buffer_destroy, + .get_shm = buffer_get_shm, + .get_dmabuf = buffer_get_dmabuf, +}; + +static struct wlr_buffer *allocator_create_buffer( + struct wlr_allocator *wlr_allocator, int width, int height, + const struct wlr_drm_format *format) { + struct wlr_udmabuf_allocator *allocator = wl_container_of(wlr_allocator, allocator, base); + + const struct wlr_pixel_format_info *info = + drm_get_pixel_format_info(format->format); + if (info == NULL) { + wlr_log(WLR_ERROR, "Unsupported pixel format 0x%"PRIX32, format->format); + return NULL; + } + + long page_size = sysconf(_SC_PAGE_SIZE); + if (page_size == -1) { + wlr_log_errno(WLR_ERROR, "Failed to query page size"); + return NULL; + } + + struct wlr_udmabuf_buffer *buffer = calloc(1, sizeof(*buffer)); + if (buffer == NULL) { + return NULL; + } + wlr_buffer_init(&buffer->base, &buffer_impl, width, height); + + // TODO: consider using a single file for multiple buffers + int stride = pixel_format_info_min_stride(info, width); // TODO: align? + size_t size = stride * height; + if (size % page_size != 0) { + size += page_size - (size % page_size); + } + + int memfd = memfd_create("wlroots", MFD_CLOEXEC | MFD_ALLOW_SEALING); + if (memfd < 0) { + wlr_log_errno(WLR_ERROR, "memfd_create() failed"); + goto err_buffer; + } + + if (ftruncate(memfd, size) < 0) { + wlr_log_errno(WLR_ERROR, "ftruncate() failed"); + goto err_memfd; + } + + if (fcntl(memfd, F_ADD_SEALS, F_SEAL_SEAL | F_SEAL_SHRINK) < 0) { + wlr_log_errno(WLR_ERROR, "fcntl(F_ADD_SEALS) failed"); + goto err_memfd; + } + + struct udmabuf_create udmabuf_create = { + .memfd = memfd, + .flags = UDMABUF_FLAGS_CLOEXEC, + .offset = 0, + .size = size, + }; + int dmabuf_fd = ioctl(allocator->fd, UDMABUF_CREATE, &udmabuf_create); + if (dmabuf_fd < 0) { + wlr_log_errno(WLR_ERROR, "ioctl(UDMABUF_CREATE) failed"); + goto err_memfd; + } + + buffer->size = size; + buffer->shm = (struct wlr_shm_attributes){ + .width = width, + .height = height, + .format = format->format, + .offset = 0, + .stride = stride, + .fd = memfd, + }; + buffer->dmabuf = (struct wlr_dmabuf_attributes){ + .width = width, + .height = height, + .format = format->format, + .modifier = DRM_FORMAT_MOD_LINEAR, + .n_planes = 1, + .offset[0] = 0, + .stride[0] = stride, + .fd[0] = dmabuf_fd, + }; + + return &buffer->base; + +err_memfd: + close(memfd); +err_buffer: + free(buffer); + return NULL; +} + +static void allocator_destroy(struct wlr_allocator *wlr_allocator) { + struct wlr_udmabuf_allocator *allocator = wl_container_of(wlr_allocator, allocator, base); + close(allocator->fd); + free(allocator); +} + +static const struct wlr_allocator_interface allocator_impl = { + .destroy = allocator_destroy, + .create_buffer = allocator_create_buffer, +}; + +struct wlr_allocator *wlr_udmabuf_allocator_create(void) { + int fd = open("/dev/udmabuf", O_RDWR | O_CLOEXEC); + if (fd < 0) { + wlr_log_errno(WLR_ERROR, "Failed to open /dev/udmabuf"); + return NULL; + } + + struct wlr_udmabuf_allocator *allocator = calloc(1, sizeof(*allocator)); + if (allocator == NULL) { + close(fd); + return NULL; + } + wlr_allocator_init(&allocator->base, &allocator_impl, + WLR_BUFFER_CAP_SHM | WLR_BUFFER_CAP_DMABUF); + + allocator->fd = fd; + + return &allocator->base; +} diff --git a/3rdparty/wlroots/render/color.c b/3rdparty/wlroots/render/color.c new file mode 100644 index 0000000000..e89fab2600 --- /dev/null +++ b/3rdparty/wlroots/render/color.c @@ -0,0 +1,433 @@ +#include +#include +#include +#include +#include "render/color.h" +#include "util/matrix.h" + +// See H.273 ColourPrimaries + +static const struct wlr_color_primaries COLOR_PRIMARIES_SRGB = { // code point 1 + .red = { 0.640, 0.330 }, + .green = { 0.300, 0.600 }, + .blue = { 0.150, 0.060 }, + .white = { 0.3127, 0.3290 }, +}; + +static const struct wlr_color_primaries COLOR_PRIMARIES_BT2020 = { // code point 9 + .red = { 0.708, 0.292 }, + .green = { 0.170, 0.797 }, + .blue = { 0.131, 0.046 }, + .white = { 0.3127, 0.3290 }, +}; + +void wlr_color_transform_init(struct wlr_color_transform *tr, enum wlr_color_transform_type type) { + *tr = (struct wlr_color_transform){ + .type = type, + .ref_count = 1, + }; + wlr_addon_set_init(&tr->addons); +} + +struct wlr_color_transform *wlr_color_transform_init_linear_to_inverse_eotf( + enum wlr_color_transfer_function tf) { + struct wlr_color_transform_inverse_eotf *tx = calloc(1, sizeof(*tx)); + if (!tx) { + return NULL; + } + wlr_color_transform_init(&tx->base, COLOR_TRANSFORM_INVERSE_EOTF); + tx->tf = tf; + return &tx->base; +} + +struct wlr_color_transform *wlr_color_transform_init_lut_3x1d(size_t dim, + const uint16_t *r, const uint16_t *g, const uint16_t *b) { + uint16_t *lut_3x1d = malloc(3 * dim * sizeof(lut_3x1d[0])); + if (lut_3x1d == NULL) { + return NULL; + } + + memcpy(&lut_3x1d[0 * dim], r, dim * sizeof(lut_3x1d[0])); + memcpy(&lut_3x1d[1 * dim], g, dim * sizeof(lut_3x1d[0])); + memcpy(&lut_3x1d[2 * dim], b, dim * sizeof(lut_3x1d[0])); + + struct wlr_color_transform_lut_3x1d *tx = calloc(1, sizeof(*tx)); + if (!tx) { + free(lut_3x1d); + return NULL; + } + wlr_color_transform_init(&tx->base, COLOR_TRANSFORM_LUT_3X1D); + tx->lut_3x1d = lut_3x1d; + tx->dim = dim; + return &tx->base; +} + +struct wlr_color_transform *wlr_color_transform_init_matrix(const float matrix[static 9]) { + struct wlr_color_transform_matrix *tx = calloc(1, sizeof(*tx)); + if (!tx) { + return NULL; + } + wlr_color_transform_init(&tx->base, COLOR_TRANSFORM_MATRIX); + memcpy(tx->matrix, matrix, sizeof(tx->matrix)); + return &tx->base; +} + +struct wlr_color_transform *wlr_color_transform_init_pipeline( + struct wlr_color_transform **transforms, size_t len) { + assert(len > 0); + + struct wlr_color_transform **copy = calloc(len, sizeof(copy[0])); + if (copy == NULL) { + return NULL; + } + + struct wlr_color_transform_pipeline *tx = calloc(1, sizeof(*tx)); + if (!tx) { + free(copy); + return NULL; + } + wlr_color_transform_init(&tx->base, COLOR_TRANSFORM_PIPELINE); + + for (size_t i = 0; i < len; i++) { + assert(transforms[i] != NULL); + copy[i] = wlr_color_transform_ref(transforms[i]); + } + + tx->transforms = copy; + tx->len = len; + + return &tx->base; +} + +static void color_transform_destroy(struct wlr_color_transform *tr) { + switch (tr->type) { + case COLOR_TRANSFORM_INVERSE_EOTF: + case COLOR_TRANSFORM_MATRIX: + break; + case COLOR_TRANSFORM_LCMS2: + color_transform_lcms2_finish(color_transform_lcms2_from_base(tr)); + break; + case COLOR_TRANSFORM_LUT_3X1D:; + struct wlr_color_transform_lut_3x1d *lut_3x1d = color_transform_lut_3x1d_from_base(tr); + free(lut_3x1d->lut_3x1d); + break; + case COLOR_TRANSFORM_PIPELINE:; + struct wlr_color_transform_pipeline *pipeline = + wl_container_of(tr, pipeline, base); + for (size_t i = 0; i < pipeline->len; i++) { + wlr_color_transform_unref(pipeline->transforms[i]); + } + free(pipeline->transforms); + break; + } + wlr_addon_set_finish(&tr->addons); + free(tr); +} + +struct wlr_color_transform *wlr_color_transform_ref(struct wlr_color_transform *tr) { + tr->ref_count += 1; + return tr; +} + +void wlr_color_transform_unref(struct wlr_color_transform *tr) { + if (!tr) { + return; + } + assert(tr->ref_count > 0); + tr->ref_count -= 1; + if (tr->ref_count == 0) { + color_transform_destroy(tr); + } +} + +struct wlr_color_transform_inverse_eotf *wlr_color_transform_inverse_eotf_from_base( + struct wlr_color_transform *tr) { + assert(tr->type == COLOR_TRANSFORM_INVERSE_EOTF); + struct wlr_color_transform_inverse_eotf *inverse_eotf = wl_container_of(tr, inverse_eotf, base); + return inverse_eotf; +} + +struct wlr_color_transform_lut_3x1d *color_transform_lut_3x1d_from_base( + struct wlr_color_transform *tr) { + assert(tr->type == COLOR_TRANSFORM_LUT_3X1D); + struct wlr_color_transform_lut_3x1d *lut_3x1d = wl_container_of(tr, lut_3x1d, base); + return lut_3x1d; +} + +static float srgb_eval_inverse_eotf(float x) { + // See https://www.w3.org/Graphics/Color/srgb + if (x <= 0.0031308) { + return 12.92 * x; + } else { + return 1.055 * powf(x, 1.0 / 2.4) - 0.055; + } +} + +static float st2084_pq_eval_inverse_eotf(float x) { + // H.273 TransferCharacteristics code point 16 + float c1 = 0.8359375; + float c2 = 18.8515625; + float c3 = 18.6875; + float m = 78.84375; + float n = 0.1593017578125; + if (x < 0) { + x = 0; + } + if (x > 1) { + x = 1; + } + float pow_n = powf(x, n); + return powf((c1 + c2 * pow_n) / (1 + c3 * pow_n), m); +} + +static float bt1886_eval_inverse_eotf(float x) { + float lb = powf(0.0001, 1.0 / 2.4); + float lw = powf(1.0, 1.0 / 2.4); + float a = powf(lw - lb, 2.4); + float b = lb / (lw - lb); + return powf(x / a, 1.0 / 2.4) - b; +} + +static float transfer_function_eval_inverse_eotf( + enum wlr_color_transfer_function tf, float x) { + switch (tf) { + case WLR_COLOR_TRANSFER_FUNCTION_SRGB: + return srgb_eval_inverse_eotf(x); + case WLR_COLOR_TRANSFER_FUNCTION_ST2084_PQ: + return st2084_pq_eval_inverse_eotf(x); + case WLR_COLOR_TRANSFER_FUNCTION_EXT_LINEAR: + return x; + case WLR_COLOR_TRANSFER_FUNCTION_GAMMA22: + return powf(x, 1.0 / 2.2); + case WLR_COLOR_TRANSFER_FUNCTION_BT1886: + return bt1886_eval_inverse_eotf(x); + } + abort(); // unreachable +} + +static void color_transform_inverse_eotf_eval( + struct wlr_color_transform_inverse_eotf *tr, + float out[static 3], const float in[static 3]) { + for (size_t i = 0; i < 3; i++) { + out[i] = transfer_function_eval_inverse_eotf(tr->tf, in[i]); + } +} + +static float lut_1d_get(const uint16_t *lut, size_t len, size_t i) { + if (i >= len) { + i = len - 1; + } + return (float) lut[i] / UINT16_MAX; +} + +static float lut_1d_eval(const uint16_t *lut, size_t len, float x) { + double pos = x * (len - 1); + double int_part; + double frac_part = modf(pos, &int_part); + size_t i = (size_t) int_part; + double a = lut_1d_get(lut, len, i); + double b = lut_1d_get(lut, len, i + 1); + return a * (1 - frac_part) + b * frac_part; +} + +static void color_transform_lut_3x1d_eval(struct wlr_color_transform_lut_3x1d *tr, + float out[static 3], const float in[static 3]) { + for (size_t i = 0; i < 3; i++) { + out[i] = lut_1d_eval(&tr->lut_3x1d[tr->dim * i], tr->dim, in[i]); + } +} + +static void multiply_matrix_vector(float out[static 3], float m[static 9], const float v[static 3]); + +void wlr_color_transform_eval(struct wlr_color_transform *tr, + float out[static 3], const float in[static 3]) { + switch (tr->type) { + case COLOR_TRANSFORM_INVERSE_EOTF: + color_transform_inverse_eotf_eval(wlr_color_transform_inverse_eotf_from_base(tr), out, in); + break; + case COLOR_TRANSFORM_LCMS2: + color_transform_lcms2_eval(color_transform_lcms2_from_base(tr), out, in); + break; + case COLOR_TRANSFORM_LUT_3X1D: + color_transform_lut_3x1d_eval(color_transform_lut_3x1d_from_base(tr), out, in); + break; + case COLOR_TRANSFORM_MATRIX:; + struct wlr_color_transform_matrix *matrix = wl_container_of(tr, matrix, base); + multiply_matrix_vector(out, matrix->matrix, in); + break; + case COLOR_TRANSFORM_PIPELINE:; + struct wlr_color_transform_pipeline *pipeline = + wl_container_of(tr, pipeline, base); + float color[3]; + memcpy(color, in, sizeof(color)); + for (size_t i = 0; i < pipeline->len; i++) { + wlr_color_transform_eval(pipeline->transforms[i], color, color); + } + memcpy(out, color, sizeof(color)); + break; + } +} + +static size_t color_transform_compose_collect(struct wlr_color_transform **out, + size_t out_capacity, struct wlr_color_transform **transforms, size_t len) { + size_t count = 0; + for (size_t i = 0; i < len; i++) { + struct wlr_color_transform *transform = transforms[i]; + if (transform == NULL) { + continue; + } + + if (transform->type == COLOR_TRANSFORM_PIPELINE) { + struct wlr_color_transform_pipeline *pipeline = wl_container_of(transform, + pipeline, base); + count += color_transform_compose_collect(out, out_capacity, + pipeline->transforms, pipeline->len); + } else { + if (out_capacity > 0) { + *out = wlr_color_transform_ref(transform); + out++; + out_capacity--; + } + count++; + } + } + return count; +} + +bool color_transform_compose(struct wlr_color_transform **result, + struct wlr_color_transform **transforms, size_t len) { + // The normalized form has the following properties : + // - No NULL transform in a pipeline + // - No pipeline of length 1 + // - No nested pipelines + bool status = false; + + size_t result_len = color_transform_compose_collect(NULL, 0, transforms, len); + if (result_len == 0) { + *result = NULL; + return true; + } + + struct wlr_color_transform **result_transforms = calloc(result_len, + sizeof(result_transforms[0])); + if (result_transforms == NULL) { + return false; + } + color_transform_compose_collect(result_transforms, result_len, transforms, len); + + if (result_len == 1) { + *result = wlr_color_transform_ref(result_transforms[0]); + } else { + *result = wlr_color_transform_init_pipeline(result_transforms, result_len); + if (*result == NULL) { + goto cleanup_transforms; + } + } + status = true; + +cleanup_transforms: + for (size_t i = 0; i < result_len; i++) { + wlr_color_transform_unref(result_transforms[i]); + } + free(result_transforms); + return status; +} + +void wlr_color_primaries_from_named(struct wlr_color_primaries *out, + enum wlr_color_named_primaries named) { + switch (named) { + case WLR_COLOR_NAMED_PRIMARIES_SRGB: + *out = COLOR_PRIMARIES_SRGB; + return; + case WLR_COLOR_NAMED_PRIMARIES_BT2020: + *out = COLOR_PRIMARIES_BT2020; + return; + } + abort(); +} + +static void multiply_matrix_vector(float out[static 3], float m[static 9], const float v[static 3]) { + float result[3] = { + m[0] * v[0] + m[1] * v[1] + m[2] * v[2], + m[3] * v[0] + m[4] * v[1] + m[5] * v[2], + m[6] * v[0] + m[7] * v[1] + m[8] * v[2], + }; + memcpy(out, result, sizeof(result)); +} + +static void xy_to_xyz(float out[static 3], struct wlr_color_cie1931_xy src) { + if (src.y == 0) { + out[0] = out[1] = out[2] = 0; + return; + } + + out[0] = src.x / src.y; + out[1] = 1; + out[2] = (1 - src.x - src.y) / src.y; +} + +void wlr_color_primaries_to_xyz(const struct wlr_color_primaries *primaries, float matrix[static 9]) { + // See: http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html + + float r[3], g[3], b[3], w[3]; + xy_to_xyz(r, primaries->red); + xy_to_xyz(g, primaries->green); + xy_to_xyz(b, primaries->blue); + xy_to_xyz(w, primaries->white); + + float xyz_matrix[9] = { + r[0], g[0], b[0], + r[1], g[1], b[1], + r[2], g[2], b[2], + }; + matrix_invert(xyz_matrix, xyz_matrix); + + float S[3]; + multiply_matrix_vector(S, xyz_matrix, w); + + float result[] = { + S[0] * r[0], S[1] * g[0], S[2] * b[0], + S[0] * r[1], S[1] * g[1], S[2] * b[1], + S[0] * r[2], S[1] * g[2], S[2] * b[2], + }; + memcpy(matrix, result, sizeof(result)); +} + +void wlr_color_primaries_transform_absolute_colorimetric( + const struct wlr_color_primaries *source, + const struct wlr_color_primaries *destination, float matrix[static 9]) { + float source_to_xyz[9]; + wlr_color_primaries_to_xyz(source, source_to_xyz); + float destination_to_xyz[9]; + wlr_color_primaries_to_xyz(destination, destination_to_xyz); + float xyz_to_destination[9]; + matrix_invert(xyz_to_destination, destination_to_xyz); + wlr_matrix_multiply(matrix, xyz_to_destination, source_to_xyz); +} + +void wlr_color_transfer_function_get_default_luminance(enum wlr_color_transfer_function tf, + struct wlr_color_luminances *lum) { + switch (tf) { + case WLR_COLOR_TRANSFER_FUNCTION_ST2084_PQ: + *lum = (struct wlr_color_luminances){ + .min = 0.005, + .max = 10000, + .reference = 203, + }; + break; + case WLR_COLOR_TRANSFER_FUNCTION_BT1886: + *lum = (struct wlr_color_luminances){ + .min = 0.01, + .max = 100, + .reference = 100, + }; + break; + default: + *lum = (struct wlr_color_luminances){ + .min = 0.2, + .max = 80, + .reference = 80, + }; + break; + } +} diff --git a/3rdparty/wlroots/render/color_fallback.c b/3rdparty/wlroots/render/color_fallback.c new file mode 100644 index 0000000000..1b25881c4a --- /dev/null +++ b/3rdparty/wlroots/render/color_fallback.c @@ -0,0 +1,24 @@ +#include +#include +#include "render/color.h" + +struct wlr_color_transform *wlr_color_transform_init_linear_to_icc( + const void *data, size_t size) { + wlr_log(WLR_ERROR, "Cannot create color transform from ICC profile: " + "LCMS2 is compile-time disabled"); + return NULL; +} + +struct wlr_color_transform_lcms2 *color_transform_lcms2_from_base( + struct wlr_color_transform *tr) { + abort(); // unreachable +} + +void color_transform_lcms2_finish(struct wlr_color_transform_lcms2 *tr) { + abort(); // unreachable +} + +void color_transform_lcms2_eval(struct wlr_color_transform_lcms2 *tr, + float out[static 3], const float in[static 3]) { + abort(); // unreachable +} diff --git a/3rdparty/wlroots/render/color_lcms2.c b/3rdparty/wlroots/render/color_lcms2.c new file mode 100644 index 0000000000..39e16cdd72 --- /dev/null +++ b/3rdparty/wlroots/render/color_lcms2.c @@ -0,0 +1,113 @@ +#include +#include +#include +#include +#include +#include "render/color.h" + +struct wlr_color_transform_lcms2 { + struct wlr_color_transform base; + + cmsContext ctx; + cmsHTRANSFORM lcms; +}; + +static const cmsCIExyY srgb_whitepoint = { 0.3127, 0.3291, 1 }; + +static const cmsCIExyYTRIPLE srgb_primaries = { + .Red = { 0.64, 0.33, 1 }, + .Green = { 0.3, 0.6, 1 }, + .Blue = { 0.15, 0.06, 1}, +}; + +static void handle_lcms_error(cmsContext ctx, cmsUInt32Number code, const char *text) { + wlr_log(WLR_ERROR, "[lcms] %s", text); +} + +struct wlr_color_transform *wlr_color_transform_init_linear_to_icc( + const void *data, size_t size) { + struct wlr_color_transform_lcms2 *tx = NULL; + + cmsContext ctx = cmsCreateContext(NULL, NULL); + if (ctx == NULL) { + wlr_log(WLR_ERROR, "cmsCreateContext failed"); + return NULL; + } + + cmsSetLogErrorHandlerTHR(ctx, handle_lcms_error); + + cmsHPROFILE icc_profile = cmsOpenProfileFromMemTHR(ctx, data, size); + if (icc_profile == NULL) { + wlr_log(WLR_ERROR, "cmsOpenProfileFromMemTHR failed"); + goto error_ctx; + } + + if (cmsGetDeviceClass(icc_profile) != cmsSigDisplayClass) { + wlr_log(WLR_ERROR, "ICC profile must have the Display device class"); + goto error_icc_profile; + } + + cmsToneCurve *linear_tone_curve = cmsBuildGamma(ctx, 1); + if (linear_tone_curve == NULL) { + wlr_log(WLR_ERROR, "cmsBuildGamma failed"); + goto error_icc_profile; + } + + cmsToneCurve *linear_tf[] = { + linear_tone_curve, + linear_tone_curve, + linear_tone_curve, + }; + cmsHPROFILE srgb_profile = cmsCreateRGBProfileTHR(ctx, &srgb_whitepoint, + &srgb_primaries, linear_tf); + cmsFreeToneCurve(linear_tone_curve); + if (srgb_profile == NULL) { + wlr_log(WLR_ERROR, "cmsCreateRGBProfileTHR failed"); + goto error_icc_profile; + } + + cmsHTRANSFORM lcms_tr = cmsCreateTransformTHR(ctx, + srgb_profile, TYPE_RGB_FLT, icc_profile, TYPE_RGB_FLT, + INTENT_RELATIVE_COLORIMETRIC, 0); + cmsCloseProfile(srgb_profile); + cmsCloseProfile(icc_profile); + if (lcms_tr == NULL) { + wlr_log(WLR_ERROR, "cmsCreateTransformTHR failed"); + goto error_ctx; + } + + tx = calloc(1, sizeof(*tx)); + if (!tx) { + cmsDeleteTransform(lcms_tr); + goto error_ctx; + } + wlr_color_transform_init(&tx->base, COLOR_TRANSFORM_LCMS2); + + tx->ctx = ctx; + tx->lcms = lcms_tr; + + return &tx->base; + +error_icc_profile: + cmsCloseProfile(icc_profile); +error_ctx: + cmsDeleteContext(ctx); + return NULL; +} + +void color_transform_lcms2_finish(struct wlr_color_transform_lcms2 *tr) { + cmsDeleteTransform(tr->lcms); + cmsDeleteContext(tr->ctx); +} + +struct wlr_color_transform_lcms2 *color_transform_lcms2_from_base( + struct wlr_color_transform *tr) { + assert(tr->type == COLOR_TRANSFORM_LCMS2); + struct wlr_color_transform_lcms2 *lcms2 = wl_container_of(tr, lcms2, base); + return lcms2; +} + +void color_transform_lcms2_eval(struct wlr_color_transform_lcms2 *tr, + float out[static 3], const float in[static 3]) { + cmsDoTransform(tr->lcms, in, out, 1); +} diff --git a/3rdparty/wlroots/render/dmabuf.c b/3rdparty/wlroots/render/dmabuf.c new file mode 100644 index 0000000000..7096dbc08f --- /dev/null +++ b/3rdparty/wlroots/render/dmabuf.c @@ -0,0 +1,37 @@ +#include +#include +#include +#include +#include "render/dmabuf.h" + +void wlr_dmabuf_attributes_finish(struct wlr_dmabuf_attributes *attribs) { + for (int i = 0; i < attribs->n_planes; ++i) { + close(attribs->fd[i]); + attribs->fd[i] = -1; + } + attribs->n_planes = 0; +} + +bool wlr_dmabuf_attributes_copy(struct wlr_dmabuf_attributes *dst, + const struct wlr_dmabuf_attributes *src) { + *dst = *src; + + int i; + for (i = 0; i < src->n_planes; ++i) { + dst->fd[i] = fcntl(src->fd[i], F_DUPFD_CLOEXEC, 0); + if (dst->fd[i] < 0) { + wlr_log_errno(WLR_ERROR, "fcntl(F_DUPFD_CLOEXEC) failed"); + goto error; + } + } + + return true; + +error: + for (int j = 0; j < i; j++) { + close(dst->fd[j]); + dst->fd[j] = -1; + } + dst->n_planes = 0; + return false; +} diff --git a/3rdparty/wlroots/render/dmabuf_fallback.c b/3rdparty/wlroots/render/dmabuf_fallback.c new file mode 100644 index 0000000000..820d46d566 --- /dev/null +++ b/3rdparty/wlroots/render/dmabuf_fallback.c @@ -0,0 +1,17 @@ +#include + +#include "render/dmabuf.h" + +bool dmabuf_check_sync_file_import_export(void) { + return false; +} + +bool dmabuf_import_sync_file(int dmabuf_fd, uint32_t flags, int sync_file_fd) { + wlr_log(WLR_ERROR, "DMA-BUF sync_file import IOCTL not available on this system"); + return false; +} + +int dmabuf_export_sync_file(int dmabuf_fd, uint32_t flags) { + wlr_log(WLR_ERROR, "DMA-BUF sync_file export IOCTL not available on this system"); + return false; +} diff --git a/3rdparty/wlroots/render/dmabuf_linux.c b/3rdparty/wlroots/render/dmabuf_linux.c new file mode 100644 index 0000000000..53fb909bc8 --- /dev/null +++ b/3rdparty/wlroots/render/dmabuf_linux.c @@ -0,0 +1,75 @@ +#include +#include +#include +#include +#include +#include + +#include "render/dmabuf.h" + +bool dmabuf_check_sync_file_import_export(void) { + /* Unfortunately there's no better way to check the availability of the + * IOCTL than to check the kernel version. See the discussion at: + * https://lore.kernel.org/dri-devel/20220601161303.64797-1-contact@emersion.fr/ + */ + + struct utsname utsname = {0}; + if (uname(&utsname) != 0) { + wlr_log_errno(WLR_ERROR, "uname failed"); + return false; + } + + if (strcmp(utsname.sysname, "Linux") != 0) { + return false; + } + + // Trim release suffix if any, e.g. "-arch1-1" + for (size_t i = 0; utsname.release[i] != '\0'; i++) { + char ch = utsname.release[i]; + if ((ch < '0' || ch > '9') && ch != '.') { + utsname.release[i] = '\0'; + break; + } + } + + char *rel = strtok(utsname.release, "."); + int major = atoi(rel); + + int minor = 0; + rel = strtok(NULL, "."); + if (rel != NULL) { + minor = atoi(rel); + } + + int patch = 0; + rel = strtok(NULL, "."); + if (rel != NULL) { + patch = atoi(rel); + } + + return KERNEL_VERSION(major, minor, patch) >= KERNEL_VERSION(5, 20, 0); +} + +bool dmabuf_import_sync_file(int dmabuf_fd, uint32_t flags, int sync_file_fd) { + struct dma_buf_import_sync_file data = { + .flags = flags, + .fd = sync_file_fd, + }; + if (drmIoctl(dmabuf_fd, DMA_BUF_IOCTL_IMPORT_SYNC_FILE, &data) != 0) { + wlr_log_errno(WLR_ERROR, "drmIoctl(IMPORT_SYNC_FILE) failed"); + return false; + } + return true; +} + +int dmabuf_export_sync_file(int dmabuf_fd, uint32_t flags) { + struct dma_buf_export_sync_file data = { + .flags = flags, + .fd = -1, + }; + if (drmIoctl(dmabuf_fd, DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &data) != 0) { + wlr_log_errno(WLR_ERROR, "drmIoctl(EXPORT_SYNC_FILE) failed"); + return -1; + } + return data.fd; +} diff --git a/3rdparty/wlroots/render/drm_format_set.c b/3rdparty/wlroots/render/drm_format_set.c new file mode 100644 index 0000000000..58d65290ad --- /dev/null +++ b/3rdparty/wlroots/render/drm_format_set.c @@ -0,0 +1,301 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "render/drm_format_set.h" + +void wlr_drm_format_finish(struct wlr_drm_format *format) { + if (!format) { + return; + } + + free(format->modifiers); +} + +void wlr_drm_format_set_finish(struct wlr_drm_format_set *set) { + for (size_t i = 0; i < set->len; ++i) { + wlr_drm_format_finish(&set->formats[i]); + } + free(set->formats); + + set->len = 0; + set->capacity = 0; + set->formats = NULL; +} + +static struct wlr_drm_format *format_set_get(const struct wlr_drm_format_set *set, + uint32_t format) { + for (size_t i = 0; i < set->len; ++i) { + if (set->formats[i].format == format) { + return &set->formats[i]; + } + } + + return NULL; +} + +const struct wlr_drm_format *wlr_drm_format_set_get( + const struct wlr_drm_format_set *set, uint32_t format) { + return format_set_get(set, format); +} + +bool wlr_drm_format_set_has(const struct wlr_drm_format_set *set, + uint32_t format, uint64_t modifier) { + const struct wlr_drm_format *fmt = wlr_drm_format_set_get(set, format); + if (!fmt) { + return false; + } + return wlr_drm_format_has(fmt, modifier); +} + +bool wlr_drm_format_set_add(struct wlr_drm_format_set *set, uint32_t format, + uint64_t modifier) { + assert(format != DRM_FORMAT_INVALID); + + struct wlr_drm_format *existing = format_set_get(set, format); + if (existing) { + return wlr_drm_format_add(existing, modifier); + } + + struct wlr_drm_format fmt; + wlr_drm_format_init(&fmt, format); + if (!wlr_drm_format_add(&fmt, modifier)) { + wlr_drm_format_finish(&fmt); + return false; + } + + if (set->len == set->capacity) { + size_t capacity = set->capacity ? set->capacity * 2 : 4; + + struct wlr_drm_format *fmts = realloc(set->formats, sizeof(*fmts) * capacity); + if (!fmts) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + wlr_drm_format_finish(&fmt); + return false; + } + + set->capacity = capacity; + set->formats = fmts; + } + + set->formats[set->len++] = fmt; + return true; +} + +bool wlr_drm_format_set_remove(struct wlr_drm_format_set *set, uint32_t format, + uint64_t modifier) { + struct wlr_drm_format *fmt = format_set_get(set, format); + if (fmt == NULL) { + return false; + } + + for (size_t idx = 0; idx < fmt->len; idx++) { + if (fmt->modifiers[idx] == modifier) { + memmove(&fmt->modifiers[idx], &fmt->modifiers[idx+1], (fmt->len - idx - 1) * sizeof(fmt->modifiers[0])); + fmt->len--; + return true; + } + } + return false; +} + +void wlr_drm_format_init(struct wlr_drm_format *fmt, uint32_t format) { + *fmt = (struct wlr_drm_format){ + .format = format, + }; +} + +bool wlr_drm_format_has(const struct wlr_drm_format *fmt, uint64_t modifier) { + for (size_t i = 0; i < fmt->len; ++i) { + if (fmt->modifiers[i] == modifier) { + return true; + } + } + return false; +} + +bool wlr_drm_format_add(struct wlr_drm_format *fmt, uint64_t modifier) { + if (wlr_drm_format_has(fmt, modifier)) { + return true; + } + + if (fmt->len == fmt->capacity) { + size_t capacity = fmt->capacity ? fmt->capacity * 2 : 4; + + uint64_t *new_modifiers = realloc(fmt->modifiers, sizeof(*fmt->modifiers) * capacity); + if (!new_modifiers) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return false; + } + + fmt->capacity = capacity; + fmt->modifiers = new_modifiers; + } + + fmt->modifiers[fmt->len++] = modifier; + return true; +} + +bool wlr_drm_format_copy(struct wlr_drm_format *dst, const struct wlr_drm_format *src) { + assert(src->len <= src->capacity); + + uint64_t *modifiers = malloc(sizeof(*modifiers) * src->len); + if (!modifiers) { + return false; + } + + memcpy(modifiers, src->modifiers, sizeof(*modifiers) * src->len); + + wlr_drm_format_finish(dst); + dst->capacity = src->len; + dst->len = src->len; + dst->format = src->format; + dst->modifiers = modifiers; + return true; +} + +bool wlr_drm_format_set_copy(struct wlr_drm_format_set *dst, const struct wlr_drm_format_set *src) { + struct wlr_drm_format *formats = malloc(src->len * sizeof(formats[0])); + if (formats == NULL) { + return false; + } + + struct wlr_drm_format_set out = { + .len = 0, + .capacity = src->len, + .formats = formats, + }; + + size_t i; + for (i = 0; i < src->len; i++) { + out.formats[out.len] = (struct wlr_drm_format){0}; + if (!wlr_drm_format_copy(&out.formats[out.len], &src->formats[i])) { + wlr_drm_format_set_finish(&out); + return false; + } + + out.len++; + } + + *dst = out; + + return true; +} + +bool wlr_drm_format_intersect(struct wlr_drm_format *dst, + const struct wlr_drm_format *a, const struct wlr_drm_format *b) { + assert(a->format == b->format); + + size_t capacity = a->len < b->len ? a->len : b->len; + uint64_t *modifiers = malloc(sizeof(*modifiers) * capacity); + if (!modifiers) { + return false; + } + + struct wlr_drm_format fmt = { + .capacity = capacity, + .len = 0, + .modifiers = modifiers, + .format = a->format, + }; + + for (size_t i = 0; i < a->len; i++) { + for (size_t j = 0; j < b->len; j++) { + if (a->modifiers[i] == b->modifiers[j]) { + assert(fmt.len < fmt.capacity); + fmt.modifiers[fmt.len++] = a->modifiers[i]; + break; + } + } + } + + wlr_drm_format_finish(dst); + *dst = fmt; + return true; +} + +bool wlr_drm_format_set_intersect(struct wlr_drm_format_set *dst, + const struct wlr_drm_format_set *a, const struct wlr_drm_format_set *b) { + struct wlr_drm_format_set out = {0}; + out.capacity = a->len < b->len ? a->len : b->len; + out.formats = malloc(sizeof(*out.formats) * out.capacity); + if (out.formats == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return false; + } + + for (size_t i = 0; i < a->len; i++) { + for (size_t j = 0; j < b->len; j++) { + if (a->formats[i].format == b->formats[j].format) { + // When the two formats have no common modifier, keep + // intersecting the rest of the formats: they may be compatible + // with each other + out.formats[out.len] = (struct wlr_drm_format){0}; + if (!wlr_drm_format_intersect(&out.formats[out.len], + &a->formats[i], &b->formats[j])) { + wlr_drm_format_set_finish(&out); + return false; + } + + if (out.formats[out.len].len == 0) { + wlr_drm_format_finish(&out.formats[out.len]); + } else { + out.len++; + } + + break; + } + } + } + + if (out.len == 0) { + wlr_drm_format_set_finish(&out); + return false; + } + + wlr_drm_format_set_finish(dst); + *dst = out; + return true; +} + +static bool drm_format_set_extend(struct wlr_drm_format_set *dst, + const struct wlr_drm_format_set *src) { + for (size_t i = 0; i < src->len; i++) { + struct wlr_drm_format *format = &src->formats[i]; + for (size_t j = 0; j < format->len; j++) { + if (!wlr_drm_format_set_add(dst, format->format, format->modifiers[j])) { + wlr_log_errno(WLR_ERROR, "Adding format/modifier to set failed"); + return false; + } + } + } + + return true; +} + +bool wlr_drm_format_set_union(struct wlr_drm_format_set *dst, + const struct wlr_drm_format_set *a, const struct wlr_drm_format_set *b) { + struct wlr_drm_format_set out = {0}; + out.capacity = a->len + b->len; + out.formats = malloc(sizeof(*out.formats) * out.capacity); + if (out.formats == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return false; + } + + // Add both a and b sets into out + if (!drm_format_set_extend(&out, a) || + !drm_format_set_extend(&out, b)) { + wlr_drm_format_set_finish(&out); + return false; + } + + wlr_drm_format_set_finish(dst); + *dst = out; + + return true; +} diff --git a/3rdparty/wlroots/render/drm_syncobj.c b/3rdparty/wlroots/render/drm_syncobj.c new file mode 100644 index 0000000000..2abe2cff64 --- /dev/null +++ b/3rdparty/wlroots/render/drm_syncobj.c @@ -0,0 +1,255 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" + +#if HAVE_EVENTFD +#include +#endif + +static struct wlr_drm_syncobj_timeline *timeline_create(int drm_fd, uint32_t handle) { + struct wlr_drm_syncobj_timeline *timeline = calloc(1, sizeof(*timeline)); + if (timeline == NULL) { + return NULL; + } + + timeline->drm_fd = drm_fd; + timeline->n_refs = 1; + timeline->handle = handle; + + wlr_addon_set_init(&timeline->addons); + + return timeline; +} + +struct wlr_drm_syncobj_timeline *wlr_drm_syncobj_timeline_create(int drm_fd) { + uint32_t handle = 0; + if (drmSyncobjCreate(drm_fd, 0, &handle) != 0) { + wlr_log_errno(WLR_ERROR, "drmSyncobjCreate failed"); + return NULL; + } + + struct wlr_drm_syncobj_timeline *timeline = timeline_create(drm_fd, handle); + if (timeline == NULL) { + drmSyncobjDestroy(drm_fd, handle); + } + + return timeline; +} + +struct wlr_drm_syncobj_timeline *wlr_drm_syncobj_timeline_import(int drm_fd, + int drm_syncobj_fd) { + uint32_t handle = 0; + if (drmSyncobjFDToHandle(drm_fd, drm_syncobj_fd, &handle) != 0) { + wlr_log_errno(WLR_ERROR, "drmSyncobjFDToHandle failed"); + return NULL; + } + + struct wlr_drm_syncobj_timeline *timeline = timeline_create(drm_fd, handle); + if (timeline == NULL) { + drmSyncobjDestroy(drm_fd, handle); + } + + return timeline; +} + +struct wlr_drm_syncobj_timeline *wlr_drm_syncobj_timeline_ref(struct wlr_drm_syncobj_timeline *timeline) { + timeline->n_refs++; + return timeline; +} + +void wlr_drm_syncobj_timeline_unref(struct wlr_drm_syncobj_timeline *timeline) { + if (timeline == NULL) { + return; + } + + assert(timeline->n_refs > 0); + timeline->n_refs--; + if (timeline->n_refs > 0) { + return; + } + + wlr_addon_set_finish(&timeline->addons); + drmSyncobjDestroy(timeline->drm_fd, timeline->handle); + free(timeline); +} + +int wlr_drm_syncobj_timeline_export(struct wlr_drm_syncobj_timeline *timeline) { + int drm_syncobj_fd = -1; + if (drmSyncobjHandleToFD(timeline->drm_fd, timeline->handle, &drm_syncobj_fd) != 0) { + wlr_log_errno(WLR_ERROR, "drmSyncobjHandleToFD failed"); + return -1; + } + return drm_syncobj_fd; +} + +bool wlr_drm_syncobj_timeline_transfer(struct wlr_drm_syncobj_timeline *dst, + uint64_t dst_point, struct wlr_drm_syncobj_timeline *src, uint64_t src_point) { + assert(dst->drm_fd == src->drm_fd); + + if (drmSyncobjTransfer(dst->drm_fd, dst->handle, dst_point, + src->handle, src_point, 0) != 0) { + wlr_log_errno(WLR_ERROR, "drmSyncobjTransfer failed"); + return false; + } + + return true; +} + +int wlr_drm_syncobj_timeline_export_sync_file(struct wlr_drm_syncobj_timeline *timeline, + uint64_t src_point) { + int sync_file_fd = -1; + + uint32_t syncobj_handle; + if (drmSyncobjCreate(timeline->drm_fd, 0, &syncobj_handle) != 0) { + wlr_log_errno(WLR_ERROR, "drmSyncobjCreate failed"); + return -1; + } + + if (drmSyncobjTransfer(timeline->drm_fd, syncobj_handle, 0, + timeline->handle, src_point, 0) != 0) { + wlr_log_errno(WLR_ERROR, "drmSyncobjTransfer failed"); + goto out; + } + + if (drmSyncobjExportSyncFile(timeline->drm_fd, + syncobj_handle, &sync_file_fd) != 0) { + wlr_log_errno(WLR_ERROR, "drmSyncobjExportSyncFile failed"); + goto out; + } + +out: + drmSyncobjDestroy(timeline->drm_fd, syncobj_handle); + return sync_file_fd; +} + +bool wlr_drm_syncobj_timeline_import_sync_file(struct wlr_drm_syncobj_timeline *timeline, + uint64_t dst_point, int sync_file_fd) { + bool ok = false; + + uint32_t syncobj_handle; + if (drmSyncobjCreate(timeline->drm_fd, 0, &syncobj_handle) != 0) { + wlr_log_errno(WLR_ERROR, "drmSyncobjCreate failed"); + return false; + } + + if (drmSyncobjImportSyncFile(timeline->drm_fd, syncobj_handle, + sync_file_fd) != 0) { + wlr_log_errno(WLR_ERROR, "drmSyncobjImportSyncFile failed"); + goto out; + } + + if (drmSyncobjTransfer(timeline->drm_fd, timeline->handle, dst_point, + syncobj_handle, 0, 0) != 0) { + wlr_log_errno(WLR_ERROR, "drmSyncobjTransfer failed"); + goto out; + } + + ok = true; + +out: + drmSyncobjDestroy(timeline->drm_fd, syncobj_handle); + return ok; +} + +bool wlr_drm_syncobj_timeline_check(struct wlr_drm_syncobj_timeline *timeline, + uint64_t point, uint32_t flags, bool *result) { + int etime; +#if defined(__FreeBSD__) + etime = ETIMEDOUT; +#else + etime = ETIME; +#endif + + int ret = drmSyncobjTimelineWait(timeline->drm_fd, &timeline->handle, &point, 1, 0, flags, NULL); + if (ret != 0 && ret != -etime) { + wlr_log_errno(WLR_ERROR, "drmSyncobjTimelineWait() failed"); + return false; + } + + *result = ret == 0; + return true; +} + +bool wlr_drm_syncobj_timeline_signal(struct wlr_drm_syncobj_timeline *timeline, uint64_t point) { + if (drmSyncobjTimelineSignal(timeline->drm_fd, &timeline->handle, &point, 1) != 0) { + wlr_log(WLR_ERROR, "drmSyncobjTimelineSignal() failed"); + return false; + } + return true; +} + +static int handle_eventfd_ready(int ev_fd, uint32_t mask, void *data) { + struct wlr_drm_syncobj_timeline_waiter *waiter = data; + + if (mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR)) { + wlr_log(WLR_ERROR, "Failed to wait for render timeline: eventfd error"); + } + + if (mask & WL_EVENT_READABLE) { + uint64_t ev_fd_value; + if (read(ev_fd, &ev_fd_value, sizeof(ev_fd_value)) <= 0) { + wlr_log(WLR_ERROR, "Failed to wait for render timeline: read() failed"); + } + } + + waiter->callback(waiter); + return 0; +} + +bool wlr_drm_syncobj_timeline_waiter_init(struct wlr_drm_syncobj_timeline_waiter *waiter, + struct wlr_drm_syncobj_timeline *timeline, uint64_t point, uint32_t flags, + struct wl_event_loop *loop, wlr_drm_syncobj_timeline_ready_callback callback) { + assert(callback); + + int ev_fd; +#if HAVE_EVENTFD + ev_fd = eventfd(0, EFD_CLOEXEC); + if (ev_fd < 0) { + wlr_log_errno(WLR_ERROR, "eventfd() failed"); + } +#else + ev_fd = -1; + wlr_log(WLR_ERROR, "eventfd() is unavailable"); +#endif + if (ev_fd < 0) { + return false; + } + + struct drm_syncobj_eventfd syncobj_eventfd = { + .handle = timeline->handle, + .flags = flags, + .point = point, + .fd = ev_fd, + }; + if (drmIoctl(timeline->drm_fd, DRM_IOCTL_SYNCOBJ_EVENTFD, &syncobj_eventfd) != 0) { + wlr_log_errno(WLR_ERROR, "DRM_IOCTL_SYNCOBJ_EVENTFD failed"); + close(ev_fd); + return false; + } + + struct wl_event_source *source = wl_event_loop_add_fd(loop, ev_fd, WL_EVENT_READABLE, handle_eventfd_ready, waiter); + if (source == NULL) { + wlr_log(WLR_ERROR, "Failed to add FD to event loop"); + close(ev_fd); + return false; + } + + *waiter = (struct wlr_drm_syncobj_timeline_waiter){ + .ev_fd = ev_fd, + .event_source = source, + .callback = callback, + }; + return true; +} + +void wlr_drm_syncobj_timeline_waiter_finish(struct wlr_drm_syncobj_timeline_waiter *waiter) { + wl_event_source_remove(waiter->event_source); + close(waiter->ev_fd); +} diff --git a/3rdparty/wlroots/render/drm_syncobj_merger.c b/3rdparty/wlroots/render/drm_syncobj_merger.c new file mode 100644 index 0000000000..d50d28c287 --- /dev/null +++ b/3rdparty/wlroots/render/drm_syncobj_merger.c @@ -0,0 +1,133 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "render/drm_syncobj_merger.h" + +#include "config.h" + +#if HAVE_LINUX_SYNC_FILE + +#include +#include + +static int sync_file_merge(int fd1, int fd2) { + // The kernel will automatically prune signalled fences + struct sync_merge_data merge_data = { .fd2 = fd2 }; + if (ioctl(fd1, SYNC_IOC_MERGE, &merge_data) < 0) { + wlr_log_errno(WLR_ERROR, "ioctl(SYNC_IOC_MERGE) failed"); + return -1; + } + + return merge_data.fence; +} + +#else + +static int sync_file_merge(int fd1, int fd2) { + wlr_log(WLR_ERROR, "sync_file support is unavailable"); + return -1; +} + +#endif + +struct wlr_drm_syncobj_merger *wlr_drm_syncobj_merger_create( + struct wlr_drm_syncobj_timeline *dst_timeline, uint64_t dst_point) { + struct wlr_drm_syncobj_merger *merger = calloc(1, sizeof(*merger)); + if (merger == NULL) { + return NULL; + } + merger->n_ref = 1; + merger->dst_timeline = wlr_drm_syncobj_timeline_ref(dst_timeline); + merger->dst_point = dst_point; + merger->sync_fd = -1; + return merger; +} + +struct wlr_drm_syncobj_merger *wlr_drm_syncobj_merger_ref( + struct wlr_drm_syncobj_merger *merger) { + assert(merger->n_ref > 0); + merger->n_ref++; + return merger; +} + +void wlr_drm_syncobj_merger_unref(struct wlr_drm_syncobj_merger *merger) { + if (merger == NULL) { + return; + } + assert(merger->n_ref > 0); + merger->n_ref--; + if (merger->n_ref > 0) { + return; + } + + if (merger->sync_fd != -1) { + wlr_drm_syncobj_timeline_import_sync_file(merger->dst_timeline, + merger->dst_point, merger->sync_fd); + close(merger->sync_fd); + } else { + wlr_drm_syncobj_timeline_signal(merger->dst_timeline, merger->dst_point); + } + wlr_drm_syncobj_timeline_unref(merger->dst_timeline); + free(merger); +} + +static bool merger_add_exportable(struct wlr_drm_syncobj_merger *merger, + struct wlr_drm_syncobj_timeline *src_timeline, uint64_t src_point) { + int new_sync = wlr_drm_syncobj_timeline_export_sync_file(src_timeline, src_point); + if (merger->sync_fd != -1) { + int fd2 = new_sync; + new_sync = sync_file_merge(merger->sync_fd, fd2); + close(fd2); + close(merger->sync_fd); + } + merger->sync_fd = new_sync; + return true; +} + +struct export_waiter { + struct wlr_drm_syncobj_timeline_waiter waiter; + struct wlr_drm_syncobj_merger *merger; + struct wlr_drm_syncobj_timeline *src_timeline; + uint64_t src_point; +}; + +static void export_waiter_handle_ready(struct wlr_drm_syncobj_timeline_waiter *waiter) { + struct export_waiter *add = wl_container_of(waiter, add, waiter); + merger_add_exportable(add->merger, add->src_timeline, add->src_point); + wlr_drm_syncobj_merger_unref(add->merger); + wlr_drm_syncobj_timeline_unref(add->src_timeline); + wlr_drm_syncobj_timeline_waiter_finish(&add->waiter); + free(add); +} + +bool wlr_drm_syncobj_merger_add(struct wlr_drm_syncobj_merger *merger, + struct wlr_drm_syncobj_timeline *src_timeline, uint64_t src_point, + struct wl_event_loop *loop) { + assert(loop != NULL); + bool exportable = false; + int flags = DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE; + if (!wlr_drm_syncobj_timeline_check(src_timeline, src_point, flags, &exportable)) { + return false; + } + if (exportable) { + return merger_add_exportable(merger, src_timeline, src_point); + } + struct export_waiter *add = calloc(1, sizeof(*add)); + if (add == NULL) { + return false; + } + if (!wlr_drm_syncobj_timeline_waiter_init(&add->waiter, src_timeline, src_point, + flags, loop, export_waiter_handle_ready)) { + return false; + } + add->merger = merger; + add->src_timeline = wlr_drm_syncobj_timeline_ref(src_timeline); + add->src_point = src_point; + merger->n_ref++; + return true; +} diff --git a/3rdparty/wlroots/render/egl.c b/3rdparty/wlroots/render/egl.c new file mode 100644 index 0000000000..8673acabff --- /dev/null +++ b/3rdparty/wlroots/render/egl.c @@ -0,0 +1,1118 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "render/egl.h" +#include "util/env.h" + +static enum wlr_log_importance egl_log_importance_to_wlr(EGLint type) { + switch (type) { + case EGL_DEBUG_MSG_CRITICAL_KHR: return WLR_ERROR; + case EGL_DEBUG_MSG_ERROR_KHR: return WLR_ERROR; + case EGL_DEBUG_MSG_WARN_KHR: return WLR_ERROR; + case EGL_DEBUG_MSG_INFO_KHR: return WLR_INFO; + default: return WLR_INFO; + } +} + +static const char *egl_error_str(EGLint error) { + switch (error) { + case EGL_SUCCESS: + return "EGL_SUCCESS"; + case EGL_NOT_INITIALIZED: + return "EGL_NOT_INITIALIZED"; + case EGL_BAD_ACCESS: + return "EGL_BAD_ACCESS"; + case EGL_BAD_ALLOC: + return "EGL_BAD_ALLOC"; + case EGL_BAD_ATTRIBUTE: + return "EGL_BAD_ATTRIBUTE"; + case EGL_BAD_CONTEXT: + return "EGL_BAD_CONTEXT"; + case EGL_BAD_CONFIG: + return "EGL_BAD_CONFIG"; + case EGL_BAD_CURRENT_SURFACE: + return "EGL_BAD_CURRENT_SURFACE"; + case EGL_BAD_DISPLAY: + return "EGL_BAD_DISPLAY"; + case EGL_BAD_DEVICE_EXT: + return "EGL_BAD_DEVICE_EXT"; + case EGL_BAD_SURFACE: + return "EGL_BAD_SURFACE"; + case EGL_BAD_MATCH: + return "EGL_BAD_MATCH"; + case EGL_BAD_PARAMETER: + return "EGL_BAD_PARAMETER"; + case EGL_BAD_NATIVE_PIXMAP: + return "EGL_BAD_NATIVE_PIXMAP"; + case EGL_BAD_NATIVE_WINDOW: + return "EGL_BAD_NATIVE_WINDOW"; + case EGL_CONTEXT_LOST: + return "EGL_CONTEXT_LOST"; + } + return "unknown error"; +} + +static void egl_log(EGLenum error, const char *command, EGLint msg_type, + EGLLabelKHR thread, EGLLabelKHR obj, const char *msg) { + _wlr_log(egl_log_importance_to_wlr(msg_type), + "[EGL] command: %s, error: %s (0x%x), message: \"%s\"", + command, egl_error_str(error), error, msg); +} + +static bool check_egl_ext(const char *exts, const char *ext) { + size_t extlen = strlen(ext); + const char *end = exts + strlen(exts); + + while (exts < end) { + if (*exts == ' ') { + exts++; + continue; + } + size_t n = strcspn(exts, " "); + if (n == extlen && strncmp(ext, exts, n) == 0) { + return true; + } + exts += n; + } + return false; +} + +static void load_egl_proc(void *proc_ptr, const char *name) { + void *proc = (void *)eglGetProcAddress(name); + if (proc == NULL) { + wlr_log(WLR_ERROR, "eglGetProcAddress(%s) failed", name); + abort(); + } + *(void **)proc_ptr = proc; +} + +static int get_egl_dmabuf_formats(struct wlr_egl *egl, EGLint **formats); +static int get_egl_dmabuf_modifiers(struct wlr_egl *egl, EGLint format, + uint64_t **modifiers, EGLBoolean **external_only); + +static void log_modifier(uint64_t modifier, bool external_only) { + char *mod_name = drmGetFormatModifierName(modifier); + wlr_log(WLR_DEBUG, " %s (0x%016"PRIX64"): ✓ texture %s render", + mod_name ? mod_name : "", modifier, external_only ? "✗" : "✓"); + free(mod_name); +} + +static void init_dmabuf_formats(struct wlr_egl *egl) { + bool no_modifiers = env_parse_bool("WLR_EGL_NO_MODIFIERS"); + if (no_modifiers) { + wlr_log(WLR_INFO, "WLR_EGL_NO_MODIFIERS set, disabling modifiers for EGL"); + } + + EGLint *formats; + int formats_len = get_egl_dmabuf_formats(egl, &formats); + if (formats_len < 0) { + return; + } + + wlr_log(WLR_DEBUG, "Supported DMA-BUF formats:"); + + bool has_modifiers = false; + for (int i = 0; i < formats_len; i++) { + EGLint fmt = formats[i]; + + uint64_t *modifiers = NULL; + EGLBoolean *external_only = NULL; + int modifiers_len = 0; + if (!no_modifiers) { + modifiers_len = get_egl_dmabuf_modifiers(egl, fmt, &modifiers, &external_only); + } + if (modifiers_len < 0) { + continue; + } + + has_modifiers = has_modifiers || modifiers_len > 0; + + bool all_external_only = true; + for (int j = 0; j < modifiers_len; j++) { + wlr_drm_format_set_add(&egl->dmabuf_texture_formats, fmt, + modifiers[j]); + if (!external_only[j]) { + wlr_drm_format_set_add(&egl->dmabuf_render_formats, fmt, + modifiers[j]); + all_external_only = false; + } + } + + // EGL always supports implicit modifiers. If at least one modifier supports rendering, + // assume the implicit modifier supports rendering too. + wlr_drm_format_set_add(&egl->dmabuf_texture_formats, fmt, + DRM_FORMAT_MOD_INVALID); + if (modifiers_len == 0 || !all_external_only) { + wlr_drm_format_set_add(&egl->dmabuf_render_formats, fmt, + DRM_FORMAT_MOD_INVALID); + } + + if (modifiers_len == 0) { + // Assume the linear layout is supported if the driver doesn't + // explicitly say otherwise + wlr_drm_format_set_add(&egl->dmabuf_texture_formats, fmt, + DRM_FORMAT_MOD_LINEAR); + wlr_drm_format_set_add(&egl->dmabuf_render_formats, fmt, + DRM_FORMAT_MOD_LINEAR); + } + + if (wlr_log_get_verbosity() >= WLR_DEBUG) { + char *fmt_name = drmGetFormatName(fmt); + wlr_log(WLR_DEBUG, " %s (0x%08"PRIX32")", + fmt_name ? fmt_name : "", fmt); + free(fmt_name); + + log_modifier(DRM_FORMAT_MOD_INVALID, false); + if (modifiers_len == 0) { + log_modifier(DRM_FORMAT_MOD_LINEAR, false); + } + for (int j = 0; j < modifiers_len; j++) { + log_modifier(modifiers[j], external_only[j]); + } + } + + free(modifiers); + free(external_only); + } + free(formats); + + egl->has_modifiers = has_modifiers; + if (!no_modifiers) { + wlr_log(WLR_DEBUG, "EGL DMA-BUF format modifiers %s", + has_modifiers ? "supported" : "unsupported"); + } +} + +static struct wlr_egl *egl_create(void) { + const char *client_exts_str = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); + if (client_exts_str == NULL) { + if (eglGetError() == EGL_BAD_DISPLAY) { + wlr_log(WLR_ERROR, "EGL_EXT_client_extensions not supported"); + } else { + wlr_log(WLR_ERROR, "Failed to query EGL client extensions"); + } + return NULL; + } + + wlr_log(WLR_INFO, "Supported EGL client extensions: %s", client_exts_str); + + if (!check_egl_ext(client_exts_str, "EGL_EXT_platform_base")) { + wlr_log(WLR_ERROR, "EGL_EXT_platform_base not supported"); + return NULL; + } + + struct wlr_egl *egl = calloc(1, sizeof(*egl)); + if (egl == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + + load_egl_proc(&egl->procs.eglGetPlatformDisplayEXT, + "eglGetPlatformDisplayEXT"); + + egl->exts.KHR_platform_gbm = check_egl_ext(client_exts_str, + "EGL_KHR_platform_gbm"); + egl->exts.EXT_platform_device = check_egl_ext(client_exts_str, + "EGL_EXT_platform_device"); + egl->exts.KHR_display_reference = check_egl_ext(client_exts_str, + "EGL_KHR_display_reference"); + + if (check_egl_ext(client_exts_str, "EGL_EXT_device_base") || check_egl_ext(client_exts_str, "EGL_EXT_device_enumeration")) { + load_egl_proc(&egl->procs.eglQueryDevicesEXT, "eglQueryDevicesEXT"); + } + + if (check_egl_ext(client_exts_str, "EGL_EXT_device_base") || check_egl_ext(client_exts_str, "EGL_EXT_device_query")) { + egl->exts.EXT_device_query = true; + load_egl_proc(&egl->procs.eglQueryDeviceStringEXT, + "eglQueryDeviceStringEXT"); + load_egl_proc(&egl->procs.eglQueryDisplayAttribEXT, + "eglQueryDisplayAttribEXT"); + } + + if (check_egl_ext(client_exts_str, "EGL_KHR_debug")) { + load_egl_proc(&egl->procs.eglDebugMessageControlKHR, + "eglDebugMessageControlKHR"); + + static const EGLAttrib debug_attribs[] = { + EGL_DEBUG_MSG_CRITICAL_KHR, EGL_TRUE, + EGL_DEBUG_MSG_ERROR_KHR, EGL_TRUE, + EGL_DEBUG_MSG_WARN_KHR, EGL_TRUE, + EGL_DEBUG_MSG_INFO_KHR, EGL_TRUE, + EGL_NONE, + }; + egl->procs.eglDebugMessageControlKHR(egl_log, debug_attribs); + } + + if (eglBindAPI(EGL_OPENGL_ES_API) == EGL_FALSE) { + wlr_log(WLR_ERROR, "Failed to bind to the OpenGL ES API"); + free(egl); + return NULL; + } + + return egl; +} + +static bool egl_init_display(struct wlr_egl *egl, EGLDisplay display, + bool allow_software) { + egl->display = display; + + EGLint major, minor; + if (eglInitialize(egl->display, &major, &minor) == EGL_FALSE) { + wlr_log(WLR_ERROR, "Failed to initialize EGL"); + return false; + } + + const char *display_exts_str = eglQueryString(egl->display, EGL_EXTENSIONS); + if (display_exts_str == NULL) { + wlr_log(WLR_ERROR, "Failed to query EGL display extensions"); + return false; + } + + if (check_egl_ext(display_exts_str, "EGL_KHR_image_base")) { + egl->exts.KHR_image_base = true; + load_egl_proc(&egl->procs.eglCreateImageKHR, "eglCreateImageKHR"); + load_egl_proc(&egl->procs.eglDestroyImageKHR, "eglDestroyImageKHR"); + } + + egl->exts.EXT_image_dma_buf_import = + check_egl_ext(display_exts_str, "EGL_EXT_image_dma_buf_import"); + if (check_egl_ext(display_exts_str, + "EGL_EXT_image_dma_buf_import_modifiers")) { + egl->exts.EXT_image_dma_buf_import_modifiers = true; + load_egl_proc(&egl->procs.eglQueryDmaBufFormatsEXT, + "eglQueryDmaBufFormatsEXT"); + load_egl_proc(&egl->procs.eglQueryDmaBufModifiersEXT, + "eglQueryDmaBufModifiersEXT"); + } + + egl->exts.EXT_create_context_robustness = + check_egl_ext(display_exts_str, "EGL_EXT_create_context_robustness"); + + const char *device_exts_str = NULL, *driver_name = NULL; + if (egl->exts.EXT_device_query) { + EGLAttrib device_attrib; + if (!egl->procs.eglQueryDisplayAttribEXT(egl->display, + EGL_DEVICE_EXT, &device_attrib)) { + wlr_log(WLR_ERROR, "eglQueryDisplayAttribEXT(EGL_DEVICE_EXT) failed"); + return false; + } + egl->device = (EGLDeviceEXT)device_attrib; + + device_exts_str = + egl->procs.eglQueryDeviceStringEXT(egl->device, EGL_EXTENSIONS); + if (device_exts_str == NULL) { + wlr_log(WLR_ERROR, "eglQueryDeviceStringEXT(EGL_EXTENSIONS) failed"); + return false; + } + +#ifdef EGL_DRIVER_NAME_EXT + if (check_egl_ext(device_exts_str, "EGL_EXT_device_persistent_id")) { + driver_name = egl->procs.eglQueryDeviceStringEXT(egl->device, + EGL_DRIVER_NAME_EXT); + } +#endif + + egl->exts.EXT_device_drm = + check_egl_ext(device_exts_str, "EGL_EXT_device_drm"); + egl->exts.EXT_device_drm_render_node = + check_egl_ext(device_exts_str, "EGL_EXT_device_drm_render_node"); + + // The only way a non-DRM device is selected is when the user + // explicitly picks software rendering + if (check_egl_ext(device_exts_str, "EGL_MESA_device_software")) { + if (allow_software || env_parse_bool("WLR_RENDERER_ALLOW_SOFTWARE")) { + wlr_log(WLR_INFO, "Using software rendering"); + } else { + wlr_log(WLR_ERROR, "Software rendering detected, please use " + "the WLR_RENDERER_ALLOW_SOFTWARE environment variable " + "to proceed"); + return false; + } + } + } + + if (!check_egl_ext(display_exts_str, "EGL_KHR_no_config_context") && + !check_egl_ext(display_exts_str, "EGL_MESA_configless_context")) { + wlr_log(WLR_ERROR, "EGL_KHR_no_config_context or " + "EGL_MESA_configless_context not supported"); + return false; + } + + if (!check_egl_ext(display_exts_str, "EGL_KHR_surfaceless_context")) { + wlr_log(WLR_ERROR, "EGL_KHR_surfaceless_context not supported"); + return false; + } + + if (check_egl_ext(display_exts_str, "EGL_KHR_fence_sync") && + check_egl_ext(display_exts_str, "EGL_ANDROID_native_fence_sync")) { + load_egl_proc(&egl->procs.eglCreateSyncKHR, "eglCreateSyncKHR"); + load_egl_proc(&egl->procs.eglDestroySyncKHR, "eglDestroySyncKHR"); + load_egl_proc(&egl->procs.eglDupNativeFenceFDANDROID, + "eglDupNativeFenceFDANDROID"); + } + + if (check_egl_ext(display_exts_str, "EGL_KHR_wait_sync")) { + load_egl_proc(&egl->procs.eglWaitSyncKHR, "eglWaitSyncKHR"); + } + + egl->exts.IMG_context_priority = + check_egl_ext(display_exts_str, "EGL_IMG_context_priority"); + + wlr_log(WLR_INFO, "Using EGL %d.%d", (int)major, (int)minor); + wlr_log(WLR_INFO, "Supported EGL display extensions: %s", display_exts_str); + if (device_exts_str != NULL) { + wlr_log(WLR_INFO, "Supported EGL device extensions: %s", device_exts_str); + } + wlr_log(WLR_INFO, "EGL vendor: %s", eglQueryString(egl->display, EGL_VENDOR)); + if (driver_name != NULL) { + wlr_log(WLR_INFO, "EGL driver name: %s", driver_name); + } + + init_dmabuf_formats(egl); + + return true; +} + +static bool egl_init(struct wlr_egl *egl, EGLenum platform, + void *remote_display, bool allow_software) { + EGLint display_attribs[3] = {0}; + size_t display_attribs_len = 0; + + if (egl->exts.KHR_display_reference) { + display_attribs[display_attribs_len++] = EGL_TRACK_REFERENCES_KHR; + display_attribs[display_attribs_len++] = EGL_TRUE; + } + + display_attribs[display_attribs_len++] = EGL_NONE; + assert(display_attribs_len <= sizeof(display_attribs) / sizeof(display_attribs[0])); + + EGLDisplay display = egl->procs.eglGetPlatformDisplayEXT(platform, + remote_display, display_attribs); + if (display == EGL_NO_DISPLAY) { + wlr_log(WLR_ERROR, "Failed to create EGL display"); + return false; + } + + if (!egl_init_display(egl, display, allow_software)) { + if (egl->exts.KHR_display_reference) { + eglTerminate(display); + } + return false; + } + + size_t atti = 0; + EGLint attribs[7]; + attribs[atti++] = EGL_CONTEXT_CLIENT_VERSION; + attribs[atti++] = 2; + + // Request a high priority context if possible + // TODO: only do this if we're running as the DRM master + bool request_high_priority = egl->exts.IMG_context_priority; + + // Try to reschedule all of our rendering to be completed first. If it + // fails, it will fallback to the default priority (MEDIUM). + if (request_high_priority) { + attribs[atti++] = EGL_CONTEXT_PRIORITY_LEVEL_IMG; + attribs[atti++] = EGL_CONTEXT_PRIORITY_HIGH_IMG; + } + + if (egl->exts.EXT_create_context_robustness) { + attribs[atti++] = EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY_EXT; + attribs[atti++] = EGL_LOSE_CONTEXT_ON_RESET_EXT; + } + + attribs[atti++] = EGL_NONE; + assert(atti <= sizeof(attribs)/sizeof(attribs[0])); + + egl->context = eglCreateContext(egl->display, EGL_NO_CONFIG_KHR, + EGL_NO_CONTEXT, attribs); + if (egl->context == EGL_NO_CONTEXT) { + wlr_log(WLR_ERROR, "Failed to create EGL context"); + return false; + } + + if (request_high_priority) { + EGLint priority = EGL_CONTEXT_PRIORITY_MEDIUM_IMG; + eglQueryContext(egl->display, egl->context, + EGL_CONTEXT_PRIORITY_LEVEL_IMG, &priority); + if (priority != EGL_CONTEXT_PRIORITY_HIGH_IMG) { + wlr_log(WLR_INFO, "Failed to obtain a high priority context"); + } else { + wlr_log(WLR_DEBUG, "Obtained high priority context"); + } + } + + return true; +} + +static bool device_has_name(const drmDevice *device, const char *name); + +static EGLDeviceEXT get_egl_device_from_drm_fd(struct wlr_egl *egl, + int drm_fd) { + if (egl->procs.eglQueryDevicesEXT == NULL) { + wlr_log(WLR_DEBUG, "EGL_EXT_device_enumeration not supported"); + return EGL_NO_DEVICE_EXT; + } else if (!egl->exts.EXT_device_query) { + wlr_log(WLR_DEBUG, "EGL_EXT_device_query not supported"); + return EGL_NO_DEVICE_EXT; + } + + EGLint nb_devices = 0; + if (!egl->procs.eglQueryDevicesEXT(0, NULL, &nb_devices)) { + wlr_log(WLR_ERROR, "Failed to query EGL devices"); + return EGL_NO_DEVICE_EXT; + } + + EGLDeviceEXT *devices = calloc(nb_devices, sizeof(*devices)); + if (devices == NULL) { + wlr_log_errno(WLR_ERROR, "Failed to allocate EGL device list"); + return EGL_NO_DEVICE_EXT; + } + + if (!egl->procs.eglQueryDevicesEXT(nb_devices, devices, &nb_devices)) { + wlr_log(WLR_ERROR, "Failed to query EGL devices"); + free(devices); + return EGL_NO_DEVICE_EXT; + } + + drmDevice *selected_drm_device = NULL; + if (drm_fd >= 0) { + int ret = drmGetDevice(drm_fd, &selected_drm_device); + if (ret < 0) { + wlr_log(WLR_ERROR, "Failed to get DRM device: %s", strerror(-ret)); + free(devices); + return EGL_NO_DEVICE_EXT; + } + } + + EGLDeviceEXT egl_device = NULL; + for (int i = 0; i < nb_devices; i++) { + const char *device_exts_str = egl->procs.eglQueryDeviceStringEXT(devices[i], EGL_EXTENSIONS); + if (device_exts_str == NULL) { + wlr_log(WLR_ERROR, "eglQueryDeviceStringEXT(EGL_EXTENSIONS) failed"); + continue; + } + + const char *egl_device_name = NULL; + if (check_egl_ext(device_exts_str, "EGL_EXT_device_drm")) { + egl_device_name = egl->procs.eglQueryDeviceStringEXT(devices[i], EGL_DRM_DEVICE_FILE_EXT); + if (egl_device_name == NULL) { + wlr_log(WLR_ERROR, "eglQueryDeviceStringEXT(EGL_DRM_DEVICE_FILE_EXT) failed"); + continue; + } + } + + bool is_software = check_egl_ext(device_exts_str, "EGL_MESA_device_software"); + + bool found; + if (selected_drm_device != NULL) { + found = egl_device_name != NULL && device_has_name(selected_drm_device, egl_device_name); + } else { + found = is_software; + } + if (found) { + if (egl_device_name != NULL) { + wlr_log(WLR_DEBUG, "Using EGL device %s", egl_device_name); + } + egl_device = devices[i]; + break; + } + } + + drmFreeDevice(&selected_drm_device); + free(devices); + + return egl_device; +} + +static int open_render_node(int drm_fd) { + char *render_name = drmGetRenderDeviceNameFromFd(drm_fd); + if (render_name == NULL) { + // This can happen on split render/display platforms, fallback to + // primary node + render_name = drmGetPrimaryDeviceNameFromFd(drm_fd); + if (render_name == NULL) { + wlr_log_errno(WLR_ERROR, "drmGetPrimaryDeviceNameFromFd failed"); + return -1; + } + wlr_log(WLR_DEBUG, "DRM device '%s' has no render node, " + "falling back to primary node", render_name); + } + + int render_fd = open(render_name, O_RDWR | O_CLOEXEC); + if (render_fd < 0) { + wlr_log_errno(WLR_ERROR, "Failed to open DRM node '%s'", render_name); + } + free(render_name); + return render_fd; +} + +struct wlr_egl *wlr_egl_create_with_drm_fd(int drm_fd) { + bool allow_software = drm_fd < 0; + + struct wlr_egl *egl = egl_create(); + if (egl == NULL) { + wlr_log(WLR_ERROR, "Failed to create EGL context"); + return NULL; + } + + if (egl->exts.EXT_platform_device) { + /* + * Search for the EGL device matching the DRM fd using the + * EXT_device_enumeration extension. + */ + EGLDeviceEXT egl_device = get_egl_device_from_drm_fd(egl, drm_fd); + if (egl_device != EGL_NO_DEVICE_EXT) { + if (egl_init(egl, EGL_PLATFORM_DEVICE_EXT, egl_device, allow_software)) { + wlr_log(WLR_DEBUG, "Using EGL_PLATFORM_DEVICE_EXT"); + return egl; + } + goto error; + } + /* Falls back on GBM in case the device was not found */ + } else { + wlr_log(WLR_DEBUG, "EXT_platform_device not supported"); + } + + if (egl->exts.KHR_platform_gbm && drm_fd >= 0) { + int gbm_fd = open_render_node(drm_fd); + if (gbm_fd < 0) { + wlr_log(WLR_ERROR, "Failed to open DRM render node"); + goto error; + } + + egl->gbm_device = gbm_create_device(gbm_fd); + if (!egl->gbm_device) { + close(gbm_fd); + wlr_log(WLR_ERROR, "Failed to create GBM device"); + goto error; + } + + if (egl_init(egl, EGL_PLATFORM_GBM_KHR, egl->gbm_device, allow_software)) { + wlr_log(WLR_DEBUG, "Using EGL_PLATFORM_GBM_KHR"); + return egl; + } + + gbm_device_destroy(egl->gbm_device); + close(gbm_fd); + } else { + wlr_log(WLR_DEBUG, "KHR_platform_gbm not supported"); + } + +error: + wlr_log(WLR_ERROR, "Failed to initialize EGL context"); + free(egl); + eglReleaseThread(); + return NULL; +} + +struct wlr_egl *wlr_egl_create_with_context(EGLDisplay display, + EGLContext context) { + EGLint client_type; + if (!eglQueryContext(display, context, EGL_CONTEXT_CLIENT_TYPE, &client_type) || + client_type != EGL_OPENGL_ES_API) { + wlr_log(WLR_ERROR, "Unsupported EGL context client type (need OpenGL ES)"); + return NULL; + } + + EGLint client_version; + if (!eglQueryContext(display, context, EGL_CONTEXT_CLIENT_VERSION, &client_version) || + client_version < 2) { + wlr_log(WLR_ERROR, "Unsupported EGL context client version (need OpenGL ES >= 2)"); + return NULL; + } + + struct wlr_egl *egl = egl_create(); + if (egl == NULL) { + return NULL; + } + + if (!egl_init_display(egl, display, true)) { + free(egl); + return NULL; + } + + egl->context = context; + + return egl; +} + +void wlr_egl_destroy(struct wlr_egl *egl) { + if (egl == NULL) { + return; + } + + wlr_drm_format_set_finish(&egl->dmabuf_render_formats); + wlr_drm_format_set_finish(&egl->dmabuf_texture_formats); + + eglMakeCurrent(egl->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + eglDestroyContext(egl->display, egl->context); + + if (egl->exts.KHR_display_reference) { + eglTerminate(egl->display); + } + + eglReleaseThread(); + + if (egl->gbm_device) { + int gbm_fd = gbm_device_get_fd(egl->gbm_device); + gbm_device_destroy(egl->gbm_device); + close(gbm_fd); + } + + free(egl); +} + +EGLDisplay wlr_egl_get_display(struct wlr_egl *egl) { + return egl->display; +} + +EGLContext wlr_egl_get_context(struct wlr_egl *egl) { + return egl->context; +} + +bool wlr_egl_destroy_image(struct wlr_egl *egl, EGLImage image) { + if (!egl->exts.KHR_image_base) { + return false; + } + if (!image) { + return true; + } + return egl->procs.eglDestroyImageKHR(egl->display, image); +} + +bool wlr_egl_make_current(struct wlr_egl *egl, + struct wlr_egl_context *save_context) { + if (save_context != NULL) { + save_context->display = eglGetCurrentDisplay(); + save_context->context = eglGetCurrentContext(); + save_context->draw_surface = eglGetCurrentSurface(EGL_DRAW); + save_context->read_surface = eglGetCurrentSurface(EGL_READ); + } + if (!eglMakeCurrent(egl->display, EGL_NO_SURFACE, EGL_NO_SURFACE, + egl->context)) { + wlr_log(WLR_ERROR, "eglMakeCurrent failed"); + return false; + } + return true; +} + +bool wlr_egl_unset_current(struct wlr_egl *egl) { + if (!eglMakeCurrent(egl->display, EGL_NO_SURFACE, EGL_NO_SURFACE, + EGL_NO_CONTEXT)) { + wlr_log(WLR_ERROR, "eglMakeCurrent failed"); + return false; + } + return true; +} + +bool wlr_egl_restore_context(struct wlr_egl_context *context) { + // If the saved context is a null-context, we must use the current + // display instead of the saved display because eglMakeCurrent() can't + // handle EGL_NO_DISPLAY. + EGLDisplay display = context->display == EGL_NO_DISPLAY ? + eglGetCurrentDisplay() : context->display; + + // If the current display is also EGL_NO_DISPLAY, we assume that there + // is currently no context set and no action needs to be taken to unset + // the context. + if (display == EGL_NO_DISPLAY) { + return true; + } + + return eglMakeCurrent(display, context->draw_surface, + context->read_surface, context->context); +} + +EGLImageKHR wlr_egl_create_image_from_dmabuf(struct wlr_egl *egl, + struct wlr_dmabuf_attributes *attributes, bool *external_only) { + if (!egl->exts.KHR_image_base || !egl->exts.EXT_image_dma_buf_import) { + wlr_log(WLR_ERROR, "dmabuf import extension not present"); + return NULL; + } + + if (attributes->modifier != DRM_FORMAT_MOD_INVALID && + attributes->modifier != DRM_FORMAT_MOD_LINEAR && + !egl->has_modifiers) { + wlr_log(WLR_ERROR, "EGL implementation doesn't support modifiers"); + return NULL; + } + + unsigned int atti = 0; + EGLint attribs[50]; + attribs[atti++] = EGL_WIDTH; + attribs[atti++] = attributes->width; + attribs[atti++] = EGL_HEIGHT; + attribs[atti++] = attributes->height; + attribs[atti++] = EGL_LINUX_DRM_FOURCC_EXT; + attribs[atti++] = attributes->format; + + struct { + EGLint fd; + EGLint offset; + EGLint pitch; + EGLint mod_lo; + EGLint mod_hi; + } attr_names[WLR_DMABUF_MAX_PLANES] = { + { + EGL_DMA_BUF_PLANE0_FD_EXT, + EGL_DMA_BUF_PLANE0_OFFSET_EXT, + EGL_DMA_BUF_PLANE0_PITCH_EXT, + EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT, + EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT + }, { + EGL_DMA_BUF_PLANE1_FD_EXT, + EGL_DMA_BUF_PLANE1_OFFSET_EXT, + EGL_DMA_BUF_PLANE1_PITCH_EXT, + EGL_DMA_BUF_PLANE1_MODIFIER_LO_EXT, + EGL_DMA_BUF_PLANE1_MODIFIER_HI_EXT + }, { + EGL_DMA_BUF_PLANE2_FD_EXT, + EGL_DMA_BUF_PLANE2_OFFSET_EXT, + EGL_DMA_BUF_PLANE2_PITCH_EXT, + EGL_DMA_BUF_PLANE2_MODIFIER_LO_EXT, + EGL_DMA_BUF_PLANE2_MODIFIER_HI_EXT + }, { + EGL_DMA_BUF_PLANE3_FD_EXT, + EGL_DMA_BUF_PLANE3_OFFSET_EXT, + EGL_DMA_BUF_PLANE3_PITCH_EXT, + EGL_DMA_BUF_PLANE3_MODIFIER_LO_EXT, + EGL_DMA_BUF_PLANE3_MODIFIER_HI_EXT + } + }; + + for (int i = 0; i < attributes->n_planes; i++) { + attribs[atti++] = attr_names[i].fd; + attribs[atti++] = attributes->fd[i]; + attribs[atti++] = attr_names[i].offset; + attribs[atti++] = attributes->offset[i]; + attribs[atti++] = attr_names[i].pitch; + attribs[atti++] = attributes->stride[i]; + if (egl->has_modifiers && + attributes->modifier != DRM_FORMAT_MOD_INVALID) { + attribs[atti++] = attr_names[i].mod_lo; + attribs[atti++] = attributes->modifier & 0xFFFFFFFF; + attribs[atti++] = attr_names[i].mod_hi; + attribs[atti++] = attributes->modifier >> 32; + } + } + + // Our clients don't expect our usage to trash the buffer contents + attribs[atti++] = EGL_IMAGE_PRESERVED_KHR; + attribs[atti++] = EGL_TRUE; + + attribs[atti++] = EGL_NONE; + assert(atti <= sizeof(attribs)/sizeof(attribs[0])); + + EGLImageKHR image = egl->procs.eglCreateImageKHR(egl->display, EGL_NO_CONTEXT, + EGL_LINUX_DMA_BUF_EXT, NULL, attribs); + if (image == EGL_NO_IMAGE_KHR) { + wlr_log(WLR_ERROR, "eglCreateImageKHR failed"); + return EGL_NO_IMAGE_KHR; + } + + *external_only = !wlr_drm_format_set_has(&egl->dmabuf_render_formats, + attributes->format, attributes->modifier); + return image; +} + +static int get_egl_dmabuf_formats(struct wlr_egl *egl, EGLint **formats) { + if (!egl->exts.EXT_image_dma_buf_import) { + wlr_log(WLR_DEBUG, "DMA-BUF import extension not present"); + return -1; + } + + // when we only have the image_dmabuf_import extension we can't query + // which formats are supported. These two are on almost always + // supported; it's the intended way to just try to create buffers. + // Just a guess but better than not supporting dmabufs at all, + // given that the modifiers extension isn't supported everywhere. + if (!egl->exts.EXT_image_dma_buf_import_modifiers) { + static const EGLint fallback_formats[] = { + DRM_FORMAT_ARGB8888, + DRM_FORMAT_XRGB8888, + }; + int num = sizeof(fallback_formats) / sizeof(fallback_formats[0]); + + *formats = calloc(num, sizeof(**formats)); + if (!*formats) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return -1; + } + + memcpy(*formats, fallback_formats, num * sizeof(**formats)); + return num; + } + + EGLint num; + if (!egl->procs.eglQueryDmaBufFormatsEXT(egl->display, 0, NULL, &num)) { + wlr_log(WLR_ERROR, "Failed to query number of dmabuf formats"); + return -1; + } + + *formats = calloc(num, sizeof(**formats)); + if (*formats == NULL) { + wlr_log(WLR_ERROR, "Allocation failed: %s", strerror(errno)); + return -1; + } + + if (!egl->procs.eglQueryDmaBufFormatsEXT(egl->display, num, *formats, &num)) { + wlr_log(WLR_ERROR, "Failed to query dmabuf format"); + free(*formats); + return -1; + } + return num; +} + +static int get_egl_dmabuf_modifiers(struct wlr_egl *egl, EGLint format, + uint64_t **modifiers, EGLBoolean **external_only) { + *modifiers = NULL; + *external_only = NULL; + + if (!egl->exts.EXT_image_dma_buf_import) { + wlr_log(WLR_DEBUG, "DMA-BUF extension not present"); + return -1; + } + if (!egl->exts.EXT_image_dma_buf_import_modifiers) { + return 0; + } + + EGLint num; + if (!egl->procs.eglQueryDmaBufModifiersEXT(egl->display, format, 0, + NULL, NULL, &num)) { + wlr_log(WLR_ERROR, "Failed to query dmabuf number of modifiers"); + return -1; + } + if (num == 0) { + return 0; + } + + *modifiers = calloc(num, sizeof(**modifiers)); + if (*modifiers == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return -1; + } + *external_only = calloc(num, sizeof(**external_only)); + if (*external_only == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + free(*modifiers); + *modifiers = NULL; + return -1; + } + + if (!egl->procs.eglQueryDmaBufModifiersEXT(egl->display, format, num, + *modifiers, *external_only, &num)) { + wlr_log(WLR_ERROR, "Failed to query dmabuf modifiers"); + free(*modifiers); + free(*external_only); + return -1; + } + return num; +} + +const struct wlr_drm_format_set *wlr_egl_get_dmabuf_texture_formats( + struct wlr_egl *egl) { + return &egl->dmabuf_texture_formats; +} + +const struct wlr_drm_format_set *wlr_egl_get_dmabuf_render_formats( + struct wlr_egl *egl) { + return &egl->dmabuf_render_formats; +} + +static bool device_has_name(const drmDevice *device, const char *name) { + for (size_t i = 0; i < DRM_NODE_MAX; i++) { + if (!(device->available_nodes & (1 << i))) { + continue; + } + if (strcmp(device->nodes[i], name) == 0) { + return true; + } + } + return false; +} + +static char *get_render_name(const char *name) { + uint32_t flags = 0; + int devices_len = drmGetDevices2(flags, NULL, 0); + if (devices_len < 0) { + wlr_log(WLR_ERROR, "drmGetDevices2 failed: %s", strerror(-devices_len)); + return NULL; + } + drmDevice **devices = calloc(devices_len, sizeof(*devices)); + if (devices == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + devices_len = drmGetDevices2(flags, devices, devices_len); + if (devices_len < 0) { + free(devices); + wlr_log(WLR_ERROR, "drmGetDevices2 failed: %s", strerror(-devices_len)); + return NULL; + } + + const drmDevice *match = NULL; + for (int i = 0; i < devices_len; i++) { + if (device_has_name(devices[i], name)) { + match = devices[i]; + break; + } + } + + char *render_name = NULL; + if (match == NULL) { + wlr_log(WLR_ERROR, "Cannot find DRM device %s", name); + } else if (!(match->available_nodes & (1 << DRM_NODE_RENDER))) { + // Likely a split display/render setup. Pick the primary node and hope + // Mesa will open the right render node under-the-hood. + wlr_log(WLR_DEBUG, "DRM device %s has no render node, " + "falling back to primary node", name); + assert(match->available_nodes & (1 << DRM_NODE_PRIMARY)); + render_name = strdup(match->nodes[DRM_NODE_PRIMARY]); + } else { + render_name = strdup(match->nodes[DRM_NODE_RENDER]); + } + + for (int i = 0; i < devices_len; i++) { + drmFreeDevice(&devices[i]); + } + free(devices); + + return render_name; +} + +static int dup_egl_device_drm_fd(struct wlr_egl *egl) { + if (egl->device == EGL_NO_DEVICE_EXT || (!egl->exts.EXT_device_drm && + !egl->exts.EXT_device_drm_render_node)) { + return -1; + } + + char *render_name = NULL; +#ifdef EGL_EXT_device_drm_render_node + if (egl->exts.EXT_device_drm_render_node) { + const char *name = egl->procs.eglQueryDeviceStringEXT(egl->device, + EGL_DRM_RENDER_NODE_FILE_EXT); + if (name == NULL) { + wlr_log(WLR_DEBUG, "EGL device has no render node"); + return -1; + } + render_name = strdup(name); + } +#endif + + if (render_name == NULL) { + const char *primary_name = egl->procs.eglQueryDeviceStringEXT(egl->device, + EGL_DRM_DEVICE_FILE_EXT); + if (primary_name == NULL) { + wlr_log(WLR_ERROR, + "eglQueryDeviceStringEXT(EGL_DRM_DEVICE_FILE_EXT) failed"); + return -1; + } + + render_name = get_render_name(primary_name); + if (render_name == NULL) { + wlr_log(WLR_ERROR, "Can't find render node name for device %s", + primary_name); + return -1; + } + } + + int render_fd = open(render_name, O_RDWR | O_NONBLOCK | O_CLOEXEC); + if (render_fd < 0) { + wlr_log_errno(WLR_ERROR, "Failed to open DRM render node %s", + render_name); + free(render_name); + return -1; + } + free(render_name); + + return render_fd; +} + +int wlr_egl_dup_drm_fd(struct wlr_egl *egl) { + int fd = dup_egl_device_drm_fd(egl); + if (fd >= 0) { + return fd; + } + + // Fallback to GBM's FD if we can't use EGLDevice + if (egl->gbm_device == NULL) { + return -1; + } + + fd = fcntl(gbm_device_get_fd(egl->gbm_device), F_DUPFD_CLOEXEC, 0); + if (fd < 0) { + wlr_log_errno(WLR_ERROR, "Failed to dup GBM FD"); + } + return fd; +} + +EGLSyncKHR wlr_egl_create_sync(struct wlr_egl *egl, int fence_fd) { + if (!egl->procs.eglCreateSyncKHR) { + return EGL_NO_SYNC_KHR; + } + + EGLint attribs[3] = { EGL_NONE }; + int dup_fd = -1; + if (fence_fd >= 0) { + dup_fd = fcntl(fence_fd, F_DUPFD_CLOEXEC, 0); + if (dup_fd < 0) { + wlr_log_errno(WLR_ERROR, "dup failed"); + return EGL_NO_SYNC_KHR; + } + + attribs[0] = EGL_SYNC_NATIVE_FENCE_FD_ANDROID; + attribs[1] = dup_fd; + attribs[2] = EGL_NONE; + } + + EGLSyncKHR sync = egl->procs.eglCreateSyncKHR(egl->display, + EGL_SYNC_NATIVE_FENCE_ANDROID, attribs); + if (sync == EGL_NO_SYNC_KHR) { + wlr_log(WLR_ERROR, "eglCreateSyncKHR failed"); + if (dup_fd >= 0) { + close(dup_fd); + } + } + return sync; +} + +void wlr_egl_destroy_sync(struct wlr_egl *egl, EGLSyncKHR sync) { + if (sync == EGL_NO_SYNC_KHR) { + return; + } + assert(egl->procs.eglDestroySyncKHR); + if (egl->procs.eglDestroySyncKHR(egl->display, sync) != EGL_TRUE) { + wlr_log(WLR_ERROR, "eglDestroySyncKHR failed"); + } +} + +int wlr_egl_dup_fence_fd(struct wlr_egl *egl, EGLSyncKHR sync) { + if (!egl->procs.eglDupNativeFenceFDANDROID) { + return -1; + } + + int fd = egl->procs.eglDupNativeFenceFDANDROID(egl->display, sync); + if (fd == EGL_NO_NATIVE_FENCE_FD_ANDROID) { + wlr_log(WLR_ERROR, "eglDupNativeFenceFDANDROID failed"); + return -1; + } + + return fd; +} + +bool wlr_egl_wait_sync(struct wlr_egl *egl, EGLSyncKHR sync) { + if (egl->procs.eglWaitSyncKHR(egl->display, sync, 0) != EGL_TRUE) { + wlr_log(WLR_ERROR, "eglWaitSyncKHR failed"); + return false; + } + return true; +} diff --git a/3rdparty/wlroots/render/gles2/meson.build b/3rdparty/wlroots/render/gles2/meson.build new file mode 100644 index 0000000000..a16ec4061b --- /dev/null +++ b/3rdparty/wlroots/render/gles2/meson.build @@ -0,0 +1,19 @@ +glesv2 = dependency('glesv2', required: 'gles2' in renderers) + +if not (glesv2.found() and internal_features['egl']) + subdir_done() +endif + +glslang = find_program('glslang', 'glslangValidator', native: true, required: false, disabler: true) + +features += { 'gles2-renderer': true } +wlr_deps += glesv2 + +wlr_files += files( + 'pass.c', + 'pixel_format.c', + 'renderer.c', + 'texture.c', +) + +subdir('shaders') diff --git a/3rdparty/wlroots/render/gles2/pass.c b/3rdparty/wlroots/render/gles2/pass.c new file mode 100644 index 0000000000..a70ea13207 --- /dev/null +++ b/3rdparty/wlroots/render/gles2/pass.c @@ -0,0 +1,353 @@ +#include +#include +#include +#include +#include +#include +#include +#include "render/egl.h" +#include "render/gles2.h" +#include "util/matrix.h" + +#define MAX_QUADS 86 // 4kb + +static const struct wlr_render_pass_impl render_pass_impl; + +static struct wlr_gles2_render_pass *get_render_pass(struct wlr_render_pass *wlr_pass) { + assert(wlr_pass->impl == &render_pass_impl); + struct wlr_gles2_render_pass *pass = wl_container_of(wlr_pass, pass, base); + return pass; +} + +static bool render_pass_submit(struct wlr_render_pass *wlr_pass) { + struct wlr_gles2_render_pass *pass = get_render_pass(wlr_pass); + struct wlr_gles2_renderer *renderer = pass->buffer->renderer; + struct wlr_gles2_render_timer *timer = pass->timer; + bool ok = false; + + push_gles2_debug(renderer); + + if (timer) { + // clear disjoint flag + GLint64 disjoint; + renderer->procs.glGetInteger64vEXT(GL_GPU_DISJOINT_EXT, &disjoint); + // set up the query + renderer->procs.glQueryCounterEXT(timer->id, GL_TIMESTAMP_EXT); + // get end-of-CPU-work time in GL time domain + renderer->procs.glGetInteger64vEXT(GL_TIMESTAMP_EXT, &timer->gl_cpu_end); + // get end-of-CPU-work time in CPU time domain + clock_gettime(CLOCK_MONOTONIC, &timer->cpu_end); + } + + if (pass->signal_timeline != NULL) { + EGLSyncKHR sync = wlr_egl_create_sync(renderer->egl, -1); + if (sync == EGL_NO_SYNC_KHR) { + goto out; + } + + int sync_file_fd = wlr_egl_dup_fence_fd(renderer->egl, sync); + wlr_egl_destroy_sync(renderer->egl, sync); + if (sync_file_fd < 0) { + goto out; + } + + ok = wlr_drm_syncobj_timeline_import_sync_file(pass->signal_timeline, pass->signal_point, sync_file_fd); + close(sync_file_fd); + if (!ok) { + goto out; + } + } else { + glFlush(); + } + + ok = true; + +out: + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + pop_gles2_debug(renderer); + wlr_egl_restore_context(&pass->prev_ctx); + + wlr_drm_syncobj_timeline_unref(pass->signal_timeline); + wlr_buffer_unlock(pass->buffer->buffer); + free(pass); + + return ok; +} + +static void render(const struct wlr_box *box, const pixman_region32_t *clip, GLint attrib) { + pixman_region32_t region; + pixman_region32_init_rect(®ion, box->x, box->y, box->width, box->height); + + if (clip) { + pixman_region32_intersect(®ion, ®ion, clip); + } + + int rects_len; + const pixman_box32_t *rects = pixman_region32_rectangles(®ion, &rects_len); + if (rects_len == 0) { + pixman_region32_fini(®ion); + return; + } + + glEnableVertexAttribArray(attrib); + + for (int i = 0; i < rects_len;) { + int batch = rects_len - i < MAX_QUADS ? rects_len - i : MAX_QUADS; + int batch_end = batch + i; + + size_t vert_index = 0; + GLfloat verts[MAX_QUADS * 6 * 2]; + for (; i < batch_end; i++) { + const pixman_box32_t *rect = &rects[i]; + + verts[vert_index++] = (GLfloat)(rect->x1 - box->x) / box->width; + verts[vert_index++] = (GLfloat)(rect->y1 - box->y) / box->height; + verts[vert_index++] = (GLfloat)(rect->x2 - box->x) / box->width; + verts[vert_index++] = (GLfloat)(rect->y1 - box->y) / box->height; + verts[vert_index++] = (GLfloat)(rect->x1 - box->x) / box->width; + verts[vert_index++] = (GLfloat)(rect->y2 - box->y) / box->height; + verts[vert_index++] = (GLfloat)(rect->x2 - box->x) / box->width; + verts[vert_index++] = (GLfloat)(rect->y1 - box->y) / box->height; + verts[vert_index++] = (GLfloat)(rect->x2 - box->x) / box->width; + verts[vert_index++] = (GLfloat)(rect->y2 - box->y) / box->height; + verts[vert_index++] = (GLfloat)(rect->x1 - box->x) / box->width; + verts[vert_index++] = (GLfloat)(rect->y2 - box->y) / box->height; + } + + glVertexAttribPointer(attrib, 2, GL_FLOAT, GL_FALSE, 0, verts); + glDrawArrays(GL_TRIANGLES, 0, batch * 6); + } + + glDisableVertexAttribArray(attrib); + + pixman_region32_fini(®ion); +} + +static void set_proj_matrix(GLint loc, float proj[9], const struct wlr_box *box) { + float gl_matrix[9]; + wlr_matrix_identity(gl_matrix); + wlr_matrix_translate(gl_matrix, box->x, box->y); + wlr_matrix_scale(gl_matrix, box->width, box->height); + wlr_matrix_multiply(gl_matrix, proj, gl_matrix); + glUniformMatrix3fv(loc, 1, GL_FALSE, gl_matrix); +} + +static void set_tex_matrix(GLint loc, enum wl_output_transform trans, + const struct wlr_fbox *box) { + float tex_matrix[9]; + wlr_matrix_identity(tex_matrix); + wlr_matrix_translate(tex_matrix, box->x, box->y); + wlr_matrix_scale(tex_matrix, box->width, box->height); + wlr_matrix_translate(tex_matrix, .5, .5); + + // since textures have a different origin point we have to transform + // differently if we are rotating + if (trans & WL_OUTPUT_TRANSFORM_90) { + wlr_matrix_transform(tex_matrix, wlr_output_transform_invert(trans)); + } else { + wlr_matrix_transform(tex_matrix, trans); + } + wlr_matrix_translate(tex_matrix, -.5, -.5); + + glUniformMatrix3fv(loc, 1, GL_FALSE, tex_matrix); +} + +static void setup_blending(enum wlr_render_blend_mode mode) { + switch (mode) { + case WLR_RENDER_BLEND_MODE_PREMULTIPLIED: + glEnable(GL_BLEND); + break; + case WLR_RENDER_BLEND_MODE_NONE: + glDisable(GL_BLEND); + break; + } +} + +static void render_pass_add_texture(struct wlr_render_pass *wlr_pass, + const struct wlr_render_texture_options *options) { + struct wlr_gles2_render_pass *pass = get_render_pass(wlr_pass); + struct wlr_gles2_renderer *renderer = pass->buffer->renderer; + struct wlr_gles2_texture *texture = gles2_get_texture(options->texture); + + struct wlr_gles2_tex_shader *shader = NULL; + + switch (texture->target) { + case GL_TEXTURE_2D: + if (texture->has_alpha) { + shader = &renderer->shaders.tex_rgba; + } else { + shader = &renderer->shaders.tex_rgbx; + } + break; + case GL_TEXTURE_EXTERNAL_OES: + // EGL_EXT_image_dma_buf_import_modifiers requires + // GL_OES_EGL_image_external + assert(renderer->exts.OES_egl_image_external); + shader = &renderer->shaders.tex_ext; + break; + default: + abort(); + } + + struct wlr_box dst_box; + struct wlr_fbox src_fbox; + wlr_render_texture_options_get_src_box(options, &src_fbox); + wlr_render_texture_options_get_dst_box(options, &dst_box); + float alpha = wlr_render_texture_options_get_alpha(options); + + src_fbox.x /= options->texture->width; + src_fbox.y /= options->texture->height; + src_fbox.width /= options->texture->width; + src_fbox.height /= options->texture->height; + + push_gles2_debug(renderer); + + if (options->wait_timeline != NULL) { + int sync_file_fd = + wlr_drm_syncobj_timeline_export_sync_file(options->wait_timeline, options->wait_point); + if (sync_file_fd < 0) { + return; + } + + EGLSyncKHR sync = wlr_egl_create_sync(renderer->egl, sync_file_fd); + close(sync_file_fd); + if (sync == EGL_NO_SYNC_KHR) { + return; + } + + bool ok = wlr_egl_wait_sync(renderer->egl, sync); + wlr_egl_destroy_sync(renderer->egl, sync); + if (!ok) { + return; + } + } + + setup_blending(!texture->has_alpha && alpha == 1.0 ? + WLR_RENDER_BLEND_MODE_NONE : options->blend_mode); + + glUseProgram(shader->program); + + glActiveTexture(GL_TEXTURE0); + glBindTexture(texture->target, texture->tex); + + switch (options->filter_mode) { + case WLR_SCALE_FILTER_BILINEAR: + glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + break; + case WLR_SCALE_FILTER_NEAREST: + glTexParameteri(texture->target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(texture->target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + break; + } + + glUniform1i(shader->tex, 0); + glUniform1f(shader->alpha, alpha); + set_proj_matrix(shader->proj, pass->projection_matrix, &dst_box); + set_tex_matrix(shader->tex_proj, options->transform, &src_fbox); + + render(&dst_box, options->clip, shader->pos_attrib); + + glBindTexture(texture->target, 0); + pop_gles2_debug(renderer); +} + +static void render_pass_add_rect(struct wlr_render_pass *wlr_pass, + const struct wlr_render_rect_options *options) { + struct wlr_gles2_render_pass *pass = get_render_pass(wlr_pass); + struct wlr_gles2_renderer *renderer = pass->buffer->renderer; + + const struct wlr_render_color *color = &options->color; + struct wlr_box box; + struct wlr_buffer *wlr_buffer = pass->buffer->buffer; + wlr_render_rect_options_get_box(options, wlr_buffer, &box); + + push_gles2_debug(renderer); + enum wlr_render_blend_mode blend_mode = + color->a == 1.0 ? WLR_RENDER_BLEND_MODE_NONE : options->blend_mode; + if (blend_mode == WLR_RENDER_BLEND_MODE_NONE && + options->clip == NULL && + box.x == 0 && box.y == 0 && + box.width == wlr_buffer->width && + box.height == wlr_buffer->height) { + glClearColor(color->r, color->g, color->b, color->a); + glClear(GL_COLOR_BUFFER_BIT); + } else { + setup_blending(blend_mode); + glUseProgram(renderer->shaders.quad.program); + set_proj_matrix(renderer->shaders.quad.proj, pass->projection_matrix, &box); + glUniform4f(renderer->shaders.quad.color, color->r, color->g, color->b, color->a); + render(&box, options->clip, renderer->shaders.quad.pos_attrib); + } + + pop_gles2_debug(renderer); +} + +static const struct wlr_render_pass_impl render_pass_impl = { + .submit = render_pass_submit, + .add_texture = render_pass_add_texture, + .add_rect = render_pass_add_rect, +}; + +static const char *reset_status_str(GLenum status) { + switch (status) { + case GL_GUILTY_CONTEXT_RESET_KHR: + return "guilty"; + case GL_INNOCENT_CONTEXT_RESET_KHR: + return "innocent"; + case GL_UNKNOWN_CONTEXT_RESET_KHR: + return "unknown"; + default: + return ""; + } +} + +struct wlr_gles2_render_pass *begin_gles2_buffer_pass(struct wlr_gles2_buffer *buffer, + struct wlr_egl_context *prev_ctx, struct wlr_gles2_render_timer *timer, + struct wlr_drm_syncobj_timeline *signal_timeline, uint64_t signal_point) { + struct wlr_gles2_renderer *renderer = buffer->renderer; + struct wlr_buffer *wlr_buffer = buffer->buffer; + + if (renderer->procs.glGetGraphicsResetStatusKHR) { + GLenum status = renderer->procs.glGetGraphicsResetStatusKHR(); + if (status != GL_NO_ERROR) { + wlr_log(WLR_ERROR, "GPU reset (%s)", reset_status_str(status)); + wl_signal_emit_mutable(&renderer->wlr_renderer.events.lost, NULL); + return NULL; + } + } + + GLint fbo = gles2_buffer_get_fbo(buffer); + if (!fbo) { + return NULL; + } + + struct wlr_gles2_render_pass *pass = calloc(1, sizeof(*pass)); + if (pass == NULL) { + return NULL; + } + + wlr_render_pass_init(&pass->base, &render_pass_impl); + wlr_buffer_lock(wlr_buffer); + pass->buffer = buffer; + pass->timer = timer; + pass->prev_ctx = *prev_ctx; + if (signal_timeline != NULL) { + pass->signal_timeline = wlr_drm_syncobj_timeline_ref(signal_timeline); + pass->signal_point = signal_point; + } + + matrix_projection(pass->projection_matrix, wlr_buffer->width, wlr_buffer->height, + WL_OUTPUT_TRANSFORM_FLIPPED_180); + + push_gles2_debug(renderer); + glBindFramebuffer(GL_FRAMEBUFFER, fbo); + + glViewport(0, 0, wlr_buffer->width, wlr_buffer->height); + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_SCISSOR_TEST); + pop_gles2_debug(renderer); + + return pass; +} diff --git a/3rdparty/wlroots/render/gles2/pixel_format.c b/3rdparty/wlroots/render/gles2/pixel_format.c new file mode 100644 index 0000000000..fbc113817f --- /dev/null +++ b/3rdparty/wlroots/render/gles2/pixel_format.c @@ -0,0 +1,173 @@ +#include +#include +#include +#include "render/gles2.h" +#include "render/pixel_format.h" + +/* + * The DRM formats are little endian while the GL formats are big endian, + * so DRM_FORMAT_ARGB8888 is actually compatible with GL_BGRA_EXT. + */ +static const struct wlr_gles2_pixel_format formats[] = { + { + .drm_format = DRM_FORMAT_ARGB8888, + .gl_format = GL_BGRA_EXT, + .gl_type = GL_UNSIGNED_BYTE, + }, + { + .drm_format = DRM_FORMAT_XRGB8888, + .gl_format = GL_BGRA_EXT, + .gl_type = GL_UNSIGNED_BYTE, + }, + { + .drm_format = DRM_FORMAT_XBGR8888, + .gl_format = GL_RGBA, + .gl_type = GL_UNSIGNED_BYTE, + }, + { + .drm_format = DRM_FORMAT_ABGR8888, + .gl_format = GL_RGBA, + .gl_type = GL_UNSIGNED_BYTE, + }, + { + .drm_format = DRM_FORMAT_BGR888, + .gl_format = GL_RGB, + .gl_type = GL_UNSIGNED_BYTE, + }, +#if WLR_LITTLE_ENDIAN + { + .drm_format = DRM_FORMAT_RGBX4444, + .gl_format = GL_RGBA, + .gl_type = GL_UNSIGNED_SHORT_4_4_4_4, + }, + { + .drm_format = DRM_FORMAT_RGBA4444, + .gl_format = GL_RGBA, + .gl_type = GL_UNSIGNED_SHORT_4_4_4_4, + }, + { + .drm_format = DRM_FORMAT_RGBX5551, + .gl_format = GL_RGBA, + .gl_type = GL_UNSIGNED_SHORT_5_5_5_1, + }, + { + .drm_format = DRM_FORMAT_RGBA5551, + .gl_format = GL_RGBA, + .gl_type = GL_UNSIGNED_SHORT_5_5_5_1, + }, + { + .drm_format = DRM_FORMAT_RGB565, + .gl_format = GL_RGB, + .gl_type = GL_UNSIGNED_SHORT_5_6_5, + }, + { + .drm_format = DRM_FORMAT_XBGR2101010, + .gl_format = GL_RGBA, + .gl_type = GL_UNSIGNED_INT_2_10_10_10_REV_EXT, + }, + { + .drm_format = DRM_FORMAT_ABGR2101010, + .gl_format = GL_RGBA, + .gl_type = GL_UNSIGNED_INT_2_10_10_10_REV_EXT, + }, + { + .drm_format = DRM_FORMAT_BGR161616F, + .gl_format = GL_RGB, + .gl_type = GL_HALF_FLOAT_OES, + }, + { + .drm_format = DRM_FORMAT_XBGR16161616F, + .gl_format = GL_RGBA, + .gl_type = GL_HALF_FLOAT_OES, + }, + { + .drm_format = DRM_FORMAT_ABGR16161616F, + .gl_format = GL_RGBA, + .gl_type = GL_HALF_FLOAT_OES, + }, + { + .drm_format = DRM_FORMAT_BGR161616, + .gl_internalformat = GL_RGB16_EXT, + .gl_format = GL_RGB, + .gl_type = GL_UNSIGNED_SHORT, + }, + { + .drm_format = DRM_FORMAT_XBGR16161616, + .gl_internalformat = GL_RGBA16_EXT, + .gl_format = GL_RGBA, + .gl_type = GL_UNSIGNED_SHORT, + }, + { + .drm_format = DRM_FORMAT_ABGR16161616, + .gl_internalformat = GL_RGBA16_EXT, + .gl_format = GL_RGBA, + .gl_type = GL_UNSIGNED_SHORT, + }, +#endif +}; + +// TODO: more pixel formats + +/* + * Return true if supported for texturing, even if other operations like + * reading aren't supported. + */ +bool is_gles2_pixel_format_supported(const struct wlr_gles2_renderer *renderer, + const struct wlr_gles2_pixel_format *format) { + if (format->gl_type == GL_UNSIGNED_INT_2_10_10_10_REV_EXT + && !renderer->exts.EXT_texture_type_2_10_10_10_REV) { + return false; + } + if (format->gl_type == GL_HALF_FLOAT_OES + && !renderer->exts.OES_texture_half_float_linear) { + return false; + } + if (format->gl_type == GL_UNSIGNED_SHORT + && !renderer->exts.EXT_texture_norm16) { + return false; + } + /* + * Note that we don't need to check for GL_EXT_texture_format_BGRA8888 + * here, since we've already checked if we have it at renderer creation + * time and bailed out if not. We do the check there because Wayland + * requires all compositors to support SHM buffers in that format. + */ + return true; +} + +const struct wlr_gles2_pixel_format *get_gles2_format_from_drm(uint32_t fmt) { + for (size_t i = 0; i < sizeof(formats) / sizeof(*formats); ++i) { + if (formats[i].drm_format == fmt) { + return &formats[i]; + } + } + return NULL; +} + +const struct wlr_gles2_pixel_format *get_gles2_format_from_gl( + GLint gl_format, GLint gl_type, bool alpha) { + for (size_t i = 0; i < sizeof(formats) / sizeof(*formats); ++i) { + if (formats[i].gl_format != gl_format || + formats[i].gl_type != gl_type) { + continue; + } + + if (pixel_format_has_alpha(formats[i].drm_format) != alpha) { + continue; + } + + return &formats[i]; + } + return NULL; +} + +void get_gles2_shm_formats(const struct wlr_gles2_renderer *renderer, + struct wlr_drm_format_set *out) { + for (size_t i = 0; i < sizeof(formats) / sizeof(formats[0]); i++) { + if (!is_gles2_pixel_format_supported(renderer, &formats[i])) { + continue; + } + wlr_drm_format_set_add(out, formats[i].drm_format, DRM_FORMAT_MOD_INVALID); + wlr_drm_format_set_add(out, formats[i].drm_format, DRM_FORMAT_MOD_LINEAR); + } +} diff --git a/3rdparty/wlroots/render/gles2/renderer.c b/3rdparty/wlroots/render/gles2/renderer.c new file mode 100644 index 0000000000..e362daee81 --- /dev/null +++ b/3rdparty/wlroots/render/gles2/renderer.c @@ -0,0 +1,718 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "render/egl.h" +#include "render/gles2.h" +#include "render/pixel_format.h" +#include "util/time.h" + +#include "common_vert_src.h" +#include "quad_frag_src.h" +#include "tex_rgba_frag_src.h" +#include "tex_rgbx_frag_src.h" +#include "tex_external_frag_src.h" + +static const struct wlr_renderer_impl renderer_impl; +static const struct wlr_render_timer_impl render_timer_impl; + +bool wlr_renderer_is_gles2(struct wlr_renderer *wlr_renderer) { + return wlr_renderer->impl == &renderer_impl; +} + +struct wlr_gles2_renderer *gles2_get_renderer( + struct wlr_renderer *wlr_renderer) { + assert(wlr_renderer_is_gles2(wlr_renderer)); + struct wlr_gles2_renderer *renderer = wl_container_of(wlr_renderer, renderer, wlr_renderer); + return renderer; +} + +bool wlr_render_timer_is_gles2(struct wlr_render_timer *timer) { + return timer->impl == &render_timer_impl; +} + +struct wlr_gles2_render_timer *gles2_get_render_timer(struct wlr_render_timer *wlr_timer) { + assert(wlr_render_timer_is_gles2(wlr_timer)); + struct wlr_gles2_render_timer *timer = wl_container_of(wlr_timer, timer, base); + return timer; +} + +static void destroy_buffer(struct wlr_gles2_buffer *buffer) { + wl_list_remove(&buffer->link); + wlr_addon_finish(&buffer->addon); + + struct wlr_egl_context prev_ctx; + wlr_egl_make_current(buffer->renderer->egl, &prev_ctx); + + push_gles2_debug(buffer->renderer); + + glDeleteFramebuffers(1, &buffer->fbo); + glDeleteRenderbuffers(1, &buffer->rbo); + glDeleteTextures(1, &buffer->tex); + + pop_gles2_debug(buffer->renderer); + + wlr_egl_destroy_image(buffer->renderer->egl, buffer->image); + + wlr_egl_restore_context(&prev_ctx); + + free(buffer); +} + +static void handle_buffer_destroy(struct wlr_addon *addon) { + struct wlr_gles2_buffer *buffer = + wl_container_of(addon, buffer, addon); + destroy_buffer(buffer); +} + +static const struct wlr_addon_interface buffer_addon_impl = { + .name = "wlr_gles2_buffer", + .destroy = handle_buffer_destroy, +}; + +GLuint gles2_buffer_get_fbo(struct wlr_gles2_buffer *buffer) { + if (buffer->external_only) { + wlr_log(WLR_ERROR, "DMA-BUF format is external-only"); + return 0; + } + + if (buffer->fbo) { + return buffer->fbo; + } + + push_gles2_debug(buffer->renderer); + + if (!buffer->rbo) { + glGenRenderbuffers(1, &buffer->rbo); + glBindRenderbuffer(GL_RENDERBUFFER, buffer->rbo); + buffer->renderer->procs.glEGLImageTargetRenderbufferStorageOES(GL_RENDERBUFFER, + buffer->image); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + } + + glGenFramebuffers(1, &buffer->fbo); + glBindFramebuffer(GL_FRAMEBUFFER, buffer->fbo); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + GL_RENDERBUFFER, buffer->rbo); + GLenum fb_status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + if (fb_status != GL_FRAMEBUFFER_COMPLETE) { + wlr_log(WLR_ERROR, "Failed to create FBO"); + glDeleteFramebuffers(1, &buffer->fbo); + buffer->fbo = 0; + } + + pop_gles2_debug(buffer->renderer); + + return buffer->fbo; +} + +struct wlr_gles2_buffer *gles2_buffer_get_or_create(struct wlr_gles2_renderer *renderer, + struct wlr_buffer *wlr_buffer) { + struct wlr_addon *addon = + wlr_addon_find(&wlr_buffer->addons, renderer, &buffer_addon_impl); + if (addon) { + struct wlr_gles2_buffer *buffer = wl_container_of(addon, buffer, addon); + return buffer; + } + + struct wlr_gles2_buffer *buffer = calloc(1, sizeof(*buffer)); + if (buffer == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + buffer->buffer = wlr_buffer; + buffer->renderer = renderer; + + struct wlr_dmabuf_attributes dmabuf = {0}; + if (!wlr_buffer_get_dmabuf(wlr_buffer, &dmabuf)) { + goto error_buffer; + } + + buffer->image = wlr_egl_create_image_from_dmabuf(renderer->egl, + &dmabuf, &buffer->external_only); + if (buffer->image == EGL_NO_IMAGE_KHR) { + goto error_buffer; + } + + wlr_addon_init(&buffer->addon, &wlr_buffer->addons, renderer, + &buffer_addon_impl); + + wl_list_insert(&renderer->buffers, &buffer->link); + + wlr_log(WLR_DEBUG, "Created GL FBO for buffer %dx%d", + wlr_buffer->width, wlr_buffer->height); + + return buffer; + +error_buffer: + free(buffer); + return NULL; +} + +static const struct wlr_drm_format_set *gles2_get_texture_formats( + struct wlr_renderer *wlr_renderer, uint32_t buffer_caps) { + struct wlr_gles2_renderer *renderer = gles2_get_renderer(wlr_renderer); + if (buffer_caps & WLR_BUFFER_CAP_DMABUF) { + return wlr_egl_get_dmabuf_texture_formats(renderer->egl); + } else if (buffer_caps & WLR_BUFFER_CAP_DATA_PTR) { + return &renderer->shm_texture_formats; + } else { + return NULL; + } +} + +static const struct wlr_drm_format_set *gles2_get_render_formats( + struct wlr_renderer *wlr_renderer) { + struct wlr_gles2_renderer *renderer = gles2_get_renderer(wlr_renderer); + return wlr_egl_get_dmabuf_render_formats(renderer->egl); +} + +static int gles2_get_drm_fd(struct wlr_renderer *wlr_renderer) { + struct wlr_gles2_renderer *renderer = + gles2_get_renderer(wlr_renderer); + + if (renderer->drm_fd < 0) { + renderer->drm_fd = wlr_egl_dup_drm_fd(renderer->egl); + } + + return renderer->drm_fd; +} + +struct wlr_egl *wlr_gles2_renderer_get_egl(struct wlr_renderer *wlr_renderer) { + struct wlr_gles2_renderer *renderer = + gles2_get_renderer(wlr_renderer); + return renderer->egl; +} + +static void gles2_destroy(struct wlr_renderer *wlr_renderer) { + struct wlr_gles2_renderer *renderer = gles2_get_renderer(wlr_renderer); + + wlr_egl_make_current(renderer->egl, NULL); + + struct wlr_gles2_texture *tex, *tex_tmp; + wl_list_for_each_safe(tex, tex_tmp, &renderer->textures, link) { + gles2_texture_destroy(tex); + } + + struct wlr_gles2_buffer *buffer, *buffer_tmp; + wl_list_for_each_safe(buffer, buffer_tmp, &renderer->buffers, link) { + destroy_buffer(buffer); + } + + push_gles2_debug(renderer); + glDeleteProgram(renderer->shaders.quad.program); + glDeleteProgram(renderer->shaders.tex_rgba.program); + glDeleteProgram(renderer->shaders.tex_rgbx.program); + glDeleteProgram(renderer->shaders.tex_ext.program); + pop_gles2_debug(renderer); + + if (renderer->exts.KHR_debug) { + glDisable(GL_DEBUG_OUTPUT_KHR); + renderer->procs.glDebugMessageCallbackKHR(NULL, NULL); + } + + wlr_egl_unset_current(renderer->egl); + wlr_egl_destroy(renderer->egl); + + wlr_drm_format_set_finish(&renderer->shm_texture_formats); + + if (renderer->drm_fd >= 0) { + close(renderer->drm_fd); + } + + free(renderer); +} + +static struct wlr_render_pass *gles2_begin_buffer_pass(struct wlr_renderer *wlr_renderer, + struct wlr_buffer *wlr_buffer, const struct wlr_buffer_pass_options *options) { + struct wlr_gles2_renderer *renderer = gles2_get_renderer(wlr_renderer); + + struct wlr_egl_context prev_ctx = {0}; + if (!wlr_egl_make_current(renderer->egl, &prev_ctx)) { + return NULL; + } + + struct wlr_gles2_render_timer *timer = NULL; + if (options->timer) { + timer = gles2_get_render_timer(options->timer); + clock_gettime(CLOCK_MONOTONIC, &timer->cpu_start); + } + + struct wlr_gles2_buffer *buffer = gles2_buffer_get_or_create(renderer, wlr_buffer); + if (!buffer) { + return NULL; + } + + struct wlr_gles2_render_pass *pass = begin_gles2_buffer_pass(buffer, + &prev_ctx, timer, options->signal_timeline, options->signal_point); + if (!pass) { + return NULL; + } + return &pass->base; +} + +GLuint wlr_gles2_renderer_get_buffer_fbo(struct wlr_renderer *wlr_renderer, + struct wlr_buffer *wlr_buffer) { + struct wlr_gles2_renderer *renderer = gles2_get_renderer(wlr_renderer); + GLuint fbo = 0; + + struct wlr_egl_context prev_ctx = {0}; + if (!wlr_egl_make_current(renderer->egl, &prev_ctx)) { + return 0; + } + + struct wlr_gles2_buffer *buffer = gles2_buffer_get_or_create(renderer, wlr_buffer); + if (buffer) { + fbo = gles2_buffer_get_fbo(buffer); + } + + wlr_egl_restore_context(&prev_ctx); + return fbo; +} + +static struct wlr_render_timer *gles2_render_timer_create(struct wlr_renderer *wlr_renderer) { + struct wlr_gles2_renderer *renderer = gles2_get_renderer(wlr_renderer); + if (!renderer->exts.EXT_disjoint_timer_query) { + wlr_log(WLR_ERROR, "can't create timer, EXT_disjoint_timer_query not available"); + return NULL; + } + + struct wlr_gles2_render_timer *timer = calloc(1, sizeof(*timer)); + if (!timer) { + return NULL; + } + timer->base.impl = &render_timer_impl; + timer->renderer = renderer; + + struct wlr_egl_context prev_ctx; + wlr_egl_make_current(renderer->egl, &prev_ctx); + renderer->procs.glGenQueriesEXT(1, &timer->id); + wlr_egl_restore_context(&prev_ctx); + + return &timer->base; +} + +static int gles2_get_render_time(struct wlr_render_timer *wlr_timer) { + struct wlr_gles2_render_timer *timer = gles2_get_render_timer(wlr_timer); + struct wlr_gles2_renderer *renderer = timer->renderer; + + struct wlr_egl_context prev_ctx; + wlr_egl_make_current(renderer->egl, &prev_ctx); + + GLint64 disjoint; + renderer->procs.glGetInteger64vEXT(GL_GPU_DISJOINT_EXT, &disjoint); + if (disjoint) { + wlr_log(WLR_ERROR, "a disjoint operation occurred and the render timer is invalid"); + wlr_egl_restore_context(&prev_ctx); + return -1; + } + + GLint available; + renderer->procs.glGetQueryObjectivEXT(timer->id, + GL_QUERY_RESULT_AVAILABLE_EXT, &available); + if (!available) { + wlr_log(WLR_ERROR, "timer was read too early, gpu isn't done!"); + wlr_egl_restore_context(&prev_ctx); + return -1; + } + + GLuint64 gl_render_end; + renderer->procs.glGetQueryObjectui64vEXT(timer->id, GL_QUERY_RESULT_EXT, + &gl_render_end); + + int64_t cpu_nsec_total = timespec_to_nsec(&timer->cpu_end) - timespec_to_nsec(&timer->cpu_start); + + wlr_egl_restore_context(&prev_ctx); + return gl_render_end - timer->gl_cpu_end + cpu_nsec_total; +} + +static void gles2_render_timer_destroy(struct wlr_render_timer *wlr_timer) { + struct wlr_gles2_render_timer *timer = wl_container_of(wlr_timer, timer, base); + struct wlr_gles2_renderer *renderer = timer->renderer; + + struct wlr_egl_context prev_ctx; + wlr_egl_make_current(renderer->egl, &prev_ctx); + renderer->procs.glDeleteQueriesEXT(1, &timer->id); + wlr_egl_restore_context(&prev_ctx); + free(timer); +} + +static const struct wlr_renderer_impl renderer_impl = { + .destroy = gles2_destroy, + .get_texture_formats = gles2_get_texture_formats, + .get_render_formats = gles2_get_render_formats, + .get_drm_fd = gles2_get_drm_fd, + .texture_from_buffer = gles2_texture_from_buffer, + .begin_buffer_pass = gles2_begin_buffer_pass, + .render_timer_create = gles2_render_timer_create, +}; + +static const struct wlr_render_timer_impl render_timer_impl = { + .get_duration_ns = gles2_get_render_time, + .destroy = gles2_render_timer_destroy, +}; + +void push_gles2_debug_(struct wlr_gles2_renderer *renderer, + const char *file, const char *func) { + if (!renderer->procs.glPushDebugGroupKHR) { + return; + } + + int len = snprintf(NULL, 0, "%s:%s", file, func) + 1; + char str[len]; + snprintf(str, len, "%s:%s", file, func); + renderer->procs.glPushDebugGroupKHR(GL_DEBUG_SOURCE_APPLICATION_KHR, 1, -1, str); +} + +void pop_gles2_debug(struct wlr_gles2_renderer *renderer) { + if (renderer->procs.glPopDebugGroupKHR) { + renderer->procs.glPopDebugGroupKHR(); + } +} + +static enum wlr_log_importance gles2_log_importance_to_wlr(GLenum type) { + switch (type) { + case GL_DEBUG_TYPE_ERROR_KHR: return WLR_ERROR; + case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR: return WLR_DEBUG; + case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR: return WLR_ERROR; + case GL_DEBUG_TYPE_PORTABILITY_KHR: return WLR_DEBUG; + case GL_DEBUG_TYPE_PERFORMANCE_KHR: return WLR_DEBUG; + case GL_DEBUG_TYPE_OTHER_KHR: return WLR_DEBUG; + case GL_DEBUG_TYPE_MARKER_KHR: return WLR_DEBUG; + case GL_DEBUG_TYPE_PUSH_GROUP_KHR: return WLR_DEBUG; + case GL_DEBUG_TYPE_POP_GROUP_KHR: return WLR_DEBUG; + default: return WLR_DEBUG; + } +} + +static void gles2_log(GLenum src, GLenum type, GLuint id, GLenum severity, + GLsizei len, const GLchar *msg, const void *user) { + _wlr_log(gles2_log_importance_to_wlr(type), "[GLES2] %s", msg); +} + +static GLuint compile_shader(struct wlr_gles2_renderer *renderer, + GLenum type, const GLchar *src) { + push_gles2_debug(renderer); + + GLuint shader = glCreateShader(type); + glShaderSource(shader, 1, &src, NULL); + glCompileShader(shader); + + GLint ok; + glGetShaderiv(shader, GL_COMPILE_STATUS, &ok); + if (ok == GL_FALSE) { + wlr_log(WLR_ERROR, "Failed to compile shader"); + glDeleteShader(shader); + shader = 0; + } + + pop_gles2_debug(renderer); + return shader; +} + +static GLuint link_program(struct wlr_gles2_renderer *renderer, + const GLchar *vert_src, const GLchar *frag_src) { + push_gles2_debug(renderer); + + GLuint vert = compile_shader(renderer, GL_VERTEX_SHADER, vert_src); + if (!vert) { + goto error; + } + + GLuint frag = compile_shader(renderer, GL_FRAGMENT_SHADER, frag_src); + if (!frag) { + glDeleteShader(vert); + goto error; + } + + GLuint prog = glCreateProgram(); + glAttachShader(prog, vert); + glAttachShader(prog, frag); + glLinkProgram(prog); + + glDetachShader(prog, vert); + glDetachShader(prog, frag); + glDeleteShader(vert); + glDeleteShader(frag); + + GLint ok; + glGetProgramiv(prog, GL_LINK_STATUS, &ok); + if (ok == GL_FALSE) { + wlr_log(WLR_ERROR, "Failed to link shader"); + glDeleteProgram(prog); + goto error; + } + + pop_gles2_debug(renderer); + return prog; + +error: + pop_gles2_debug(renderer); + return 0; +} + +static bool check_gl_ext(const char *exts, const char *ext) { + size_t extlen = strlen(ext); + const char *end = exts + strlen(exts); + + while (exts < end) { + if (exts[0] == ' ') { + exts++; + continue; + } + size_t n = strcspn(exts, " "); + if (n == extlen && strncmp(ext, exts, n) == 0) { + return true; + } + exts += n; + } + return false; +} + +static void load_gl_proc(void *proc_ptr, const char *name) { + void *proc = (void *)eglGetProcAddress(name); + if (proc == NULL) { + wlr_log(WLR_ERROR, "eglGetProcAddress(%s) failed", name); + abort(); + } + *(void **)proc_ptr = proc; +} + +struct wlr_renderer *wlr_gles2_renderer_create_with_drm_fd(int drm_fd) { + struct wlr_egl *egl = wlr_egl_create_with_drm_fd(drm_fd); + if (egl == NULL) { + wlr_log(WLR_ERROR, "Could not initialize EGL"); + return NULL; + } + + struct wlr_renderer *renderer = wlr_gles2_renderer_create(egl); + if (!renderer) { + wlr_log(WLR_ERROR, "Failed to create GLES2 renderer"); + wlr_egl_destroy(egl); + return NULL; + } + + return renderer; +} + +struct wlr_renderer *wlr_gles2_renderer_create(struct wlr_egl *egl) { + if (!wlr_egl_make_current(egl, NULL)) { + return NULL; + } + + const char *exts_str = (const char *)glGetString(GL_EXTENSIONS); + if (exts_str == NULL) { + wlr_log(WLR_ERROR, "Failed to get GL_EXTENSIONS"); + return NULL; + } + + struct wlr_gles2_renderer *renderer = calloc(1, sizeof(*renderer)); + if (renderer == NULL) { + return NULL; + } + wlr_renderer_init(&renderer->wlr_renderer, &renderer_impl, WLR_BUFFER_CAP_DMABUF); + renderer->wlr_renderer.features.output_color_transform = false; + + wl_list_init(&renderer->buffers); + wl_list_init(&renderer->textures); + + renderer->egl = egl; + renderer->exts_str = exts_str; + renderer->drm_fd = -1; + + wlr_log(WLR_INFO, "Creating GLES2 renderer"); + wlr_log(WLR_INFO, "Using %s", glGetString(GL_VERSION)); + wlr_log(WLR_INFO, "GL vendor: %s", glGetString(GL_VENDOR)); + wlr_log(WLR_INFO, "GL renderer: %s", glGetString(GL_RENDERER)); + wlr_log(WLR_INFO, "Supported GLES2 extensions: %s", exts_str); + + if (!renderer->egl->exts.EXT_image_dma_buf_import) { + wlr_log(WLR_ERROR, "EGL_EXT_image_dma_buf_import not supported"); + free(renderer); + return NULL; + } + if (!check_gl_ext(exts_str, "GL_EXT_texture_format_BGRA8888")) { + wlr_log(WLR_ERROR, "BGRA8888 format not supported by GLES2"); + free(renderer); + return NULL; + } + if (!check_gl_ext(exts_str, "GL_EXT_unpack_subimage")) { + wlr_log(WLR_ERROR, "GL_EXT_unpack_subimage not supported"); + free(renderer); + return NULL; + } + + renderer->exts.EXT_read_format_bgra = + check_gl_ext(exts_str, "GL_EXT_read_format_bgra"); + + renderer->exts.EXT_texture_type_2_10_10_10_REV = + check_gl_ext(exts_str, "GL_EXT_texture_type_2_10_10_10_REV"); + + renderer->exts.OES_texture_half_float_linear = + check_gl_ext(exts_str, "GL_OES_texture_half_float_linear"); + + renderer->exts.EXT_texture_norm16 = + check_gl_ext(exts_str, "GL_EXT_texture_norm16"); + + if (check_gl_ext(exts_str, "GL_KHR_debug")) { + renderer->exts.KHR_debug = true; + load_gl_proc(&renderer->procs.glDebugMessageCallbackKHR, + "glDebugMessageCallbackKHR"); + load_gl_proc(&renderer->procs.glDebugMessageControlKHR, + "glDebugMessageControlKHR"); + } + + if (check_gl_ext(exts_str, "GL_OES_EGL_image_external")) { + renderer->exts.OES_egl_image_external = true; + load_gl_proc(&renderer->procs.glEGLImageTargetTexture2DOES, + "glEGLImageTargetTexture2DOES"); + } + + if (check_gl_ext(exts_str, "GL_OES_EGL_image")) { + renderer->exts.OES_egl_image = true; + load_gl_proc(&renderer->procs.glEGLImageTargetRenderbufferStorageOES, + "glEGLImageTargetRenderbufferStorageOES"); + } + + if (check_gl_ext(exts_str, "GL_KHR_robustness")) { + GLint notif_strategy = 0; + glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_KHR, ¬if_strategy); + switch (notif_strategy) { + case GL_LOSE_CONTEXT_ON_RESET_KHR: + wlr_log(WLR_DEBUG, "GPU reset notifications are enabled"); + load_gl_proc(&renderer->procs.glGetGraphicsResetStatusKHR, + "glGetGraphicsResetStatusKHR"); + break; + case GL_NO_RESET_NOTIFICATION_KHR: + wlr_log(WLR_DEBUG, "GPU reset notifications are disabled"); + break; + } + } + + if (check_gl_ext(exts_str, "GL_EXT_disjoint_timer_query")) { + renderer->exts.EXT_disjoint_timer_query = true; + load_gl_proc(&renderer->procs.glGenQueriesEXT, "glGenQueriesEXT"); + load_gl_proc(&renderer->procs.glDeleteQueriesEXT, "glDeleteQueriesEXT"); + load_gl_proc(&renderer->procs.glQueryCounterEXT, "glQueryCounterEXT"); + load_gl_proc(&renderer->procs.glGetQueryObjectivEXT, "glGetQueryObjectivEXT"); + load_gl_proc(&renderer->procs.glGetQueryObjectui64vEXT, "glGetQueryObjectui64vEXT"); + if (eglGetProcAddress("glGetInteger64vEXT")) { + load_gl_proc(&renderer->procs.glGetInteger64vEXT, "glGetInteger64vEXT"); + } else { + load_gl_proc(&renderer->procs.glGetInteger64vEXT, "glGetInteger64v"); + } + } + + if (renderer->exts.KHR_debug) { + glEnable(GL_DEBUG_OUTPUT_KHR); + glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR); + renderer->procs.glDebugMessageCallbackKHR(gles2_log, NULL); + + // Silence unwanted message types + renderer->procs.glDebugMessageControlKHR(GL_DONT_CARE, + GL_DEBUG_TYPE_POP_GROUP_KHR, GL_DONT_CARE, 0, NULL, GL_FALSE); + renderer->procs.glDebugMessageControlKHR(GL_DONT_CARE, + GL_DEBUG_TYPE_PUSH_GROUP_KHR, GL_DONT_CARE, 0, NULL, GL_FALSE); + } + + push_gles2_debug(renderer); + + GLuint prog; + renderer->shaders.quad.program = prog = + link_program(renderer, common_vert_src, quad_frag_src); + if (!renderer->shaders.quad.program) { + goto error; + } + renderer->shaders.quad.proj = glGetUniformLocation(prog, "proj"); + renderer->shaders.quad.color = glGetUniformLocation(prog, "color"); + renderer->shaders.quad.pos_attrib = glGetAttribLocation(prog, "pos"); + + renderer->shaders.tex_rgba.program = prog = + link_program(renderer, common_vert_src, tex_rgba_frag_src); + if (!renderer->shaders.tex_rgba.program) { + goto error; + } + renderer->shaders.tex_rgba.proj = glGetUniformLocation(prog, "proj"); + renderer->shaders.tex_rgba.tex_proj = glGetUniformLocation(prog, "tex_proj"); + renderer->shaders.tex_rgba.tex = glGetUniformLocation(prog, "tex"); + renderer->shaders.tex_rgba.alpha = glGetUniformLocation(prog, "alpha"); + renderer->shaders.tex_rgba.pos_attrib = glGetAttribLocation(prog, "pos"); + + renderer->shaders.tex_rgbx.program = prog = + link_program(renderer, common_vert_src, tex_rgbx_frag_src); + if (!renderer->shaders.tex_rgbx.program) { + goto error; + } + renderer->shaders.tex_rgbx.proj = glGetUniformLocation(prog, "proj"); + renderer->shaders.tex_rgbx.tex_proj = glGetUniformLocation(prog, "tex_proj"); + renderer->shaders.tex_rgbx.tex = glGetUniformLocation(prog, "tex"); + renderer->shaders.tex_rgbx.alpha = glGetUniformLocation(prog, "alpha"); + renderer->shaders.tex_rgbx.pos_attrib = glGetAttribLocation(prog, "pos"); + + if (renderer->exts.OES_egl_image_external) { + renderer->shaders.tex_ext.program = prog = + link_program(renderer, common_vert_src, tex_external_frag_src); + if (!renderer->shaders.tex_ext.program) { + goto error; + } + renderer->shaders.tex_ext.proj = glGetUniformLocation(prog, "proj"); + renderer->shaders.tex_ext.tex_proj = glGetUniformLocation(prog, "tex_proj"); + renderer->shaders.tex_ext.tex = glGetUniformLocation(prog, "tex"); + renderer->shaders.tex_ext.alpha = glGetUniformLocation(prog, "alpha"); + renderer->shaders.tex_ext.pos_attrib = glGetAttribLocation(prog, "pos"); + } + + pop_gles2_debug(renderer); + + wlr_egl_unset_current(renderer->egl); + + get_gles2_shm_formats(renderer, &renderer->shm_texture_formats); + + int drm_fd = wlr_renderer_get_drm_fd(&renderer->wlr_renderer); + uint64_t cap_syncobj_timeline; + if (drm_fd >= 0 && drmGetCap(drm_fd, DRM_CAP_SYNCOBJ_TIMELINE, &cap_syncobj_timeline) == 0) { + renderer->wlr_renderer.features.timeline = egl->procs.eglDupNativeFenceFDANDROID && + egl->procs.eglWaitSyncKHR && cap_syncobj_timeline != 0; + } + + return &renderer->wlr_renderer; + +error: + glDeleteProgram(renderer->shaders.quad.program); + glDeleteProgram(renderer->shaders.tex_rgba.program); + glDeleteProgram(renderer->shaders.tex_rgbx.program); + glDeleteProgram(renderer->shaders.tex_ext.program); + + pop_gles2_debug(renderer); + + if (renderer->exts.KHR_debug) { + glDisable(GL_DEBUG_OUTPUT_KHR); + renderer->procs.glDebugMessageCallbackKHR(NULL, NULL); + } + + wlr_egl_unset_current(renderer->egl); + + free(renderer); + return NULL; +} + +bool wlr_gles2_renderer_check_ext(struct wlr_renderer *wlr_renderer, + const char *ext) { + struct wlr_gles2_renderer *renderer = gles2_get_renderer(wlr_renderer); + return check_gl_ext(renderer->exts_str, ext); +} diff --git a/3rdparty/wlroots/render/gles2/shaders/check.sh b/3rdparty/wlroots/render/gles2/shaders/check.sh new file mode 100644 index 0000000000..18f4be2462 --- /dev/null +++ b/3rdparty/wlroots/render/gles2/shaders/check.sh @@ -0,0 +1,4 @@ +#!/bin/sh -eu + +# glslang prints log messages to stdout, remap to stderr +exec "$@" >&2 diff --git a/3rdparty/wlroots/render/gles2/shaders/common.vert b/3rdparty/wlroots/render/gles2/shaders/common.vert new file mode 100644 index 0000000000..f51548ab38 --- /dev/null +++ b/3rdparty/wlroots/render/gles2/shaders/common.vert @@ -0,0 +1,10 @@ +uniform mat3 proj; +uniform mat3 tex_proj; +attribute vec2 pos; +varying vec2 v_texcoord; + +void main() { + vec3 pos3 = vec3(pos, 1.0); + gl_Position = vec4(pos3 * proj, 1.0); + v_texcoord = (pos3 * tex_proj).xy; +} diff --git a/3rdparty/wlroots/render/gles2/shaders/embed.sh b/3rdparty/wlroots/render/gles2/shaders/embed.sh new file mode 100755 index 0000000000..acd7a1199f --- /dev/null +++ b/3rdparty/wlroots/render/gles2/shaders/embed.sh @@ -0,0 +1,11 @@ +#!/bin/sh -eu + +var=${1:-data} +hex="$(od -A n -t x1 -v)" + +echo "static const char $var[] = {" +for byte in $hex; do + echo " 0x$byte," +done +echo " 0x00," +echo "};" diff --git a/3rdparty/wlroots/render/gles2/shaders/meson.build b/3rdparty/wlroots/render/gles2/shaders/meson.build new file mode 100644 index 0000000000..1e649f7b5d --- /dev/null +++ b/3rdparty/wlroots/render/gles2/shaders/meson.build @@ -0,0 +1,32 @@ +check = find_program('./check.sh', native: true) +embed = find_program('./embed.sh', native: true) + +shaders = [ + 'common.vert', + 'quad.frag', + 'tex_rgba.frag', + 'tex_rgbx.frag', + 'tex_external.frag', +] + +foreach name : shaders + custom_target( + 'gles2-' + name, + input: name, + output: name + '_check', + command: [check, glslang, '@INPUT@'], + capture: true, + build_by_default: true, + ) + + output = name.underscorify() + '_src.h' + var = name.underscorify() + '_src' + wlr_files += custom_target( + output, + command: [embed, var], + input: name, + output: output, + feed: true, + capture: true, + ) +endforeach diff --git a/3rdparty/wlroots/render/gles2/shaders/quad.frag b/3rdparty/wlroots/render/gles2/shaders/quad.frag new file mode 100644 index 0000000000..97d3a31c12 --- /dev/null +++ b/3rdparty/wlroots/render/gles2/shaders/quad.frag @@ -0,0 +1,13 @@ +#ifdef GL_FRAGMENT_PRECISION_HIGH +precision highp float; +#else +precision mediump float; +#endif + +varying vec4 v_color; +varying vec2 v_texcoord; +uniform vec4 color; + +void main() { + gl_FragColor = color; +} diff --git a/3rdparty/wlroots/render/gles2/shaders/tex_external.frag b/3rdparty/wlroots/render/gles2/shaders/tex_external.frag new file mode 100644 index 0000000000..73909fe03a --- /dev/null +++ b/3rdparty/wlroots/render/gles2/shaders/tex_external.frag @@ -0,0 +1,15 @@ +#extension GL_OES_EGL_image_external : require + +#ifdef GL_FRAGMENT_PRECISION_HIGH +precision highp float; +#else +precision mediump float; +#endif + +varying vec2 v_texcoord; +uniform samplerExternalOES texture0; +uniform float alpha; + +void main() { + gl_FragColor = texture2D(texture0, v_texcoord) * alpha; +} diff --git a/3rdparty/wlroots/render/gles2/shaders/tex_rgba.frag b/3rdparty/wlroots/render/gles2/shaders/tex_rgba.frag new file mode 100644 index 0000000000..c0a0dea616 --- /dev/null +++ b/3rdparty/wlroots/render/gles2/shaders/tex_rgba.frag @@ -0,0 +1,13 @@ +#ifdef GL_FRAGMENT_PRECISION_HIGH +precision highp float; +#else +precision mediump float; +#endif + +varying vec2 v_texcoord; +uniform sampler2D tex; +uniform float alpha; + +void main() { + gl_FragColor = texture2D(tex, v_texcoord) * alpha; +} diff --git a/3rdparty/wlroots/render/gles2/shaders/tex_rgbx.frag b/3rdparty/wlroots/render/gles2/shaders/tex_rgbx.frag new file mode 100644 index 0000000000..ae40ad53e4 --- /dev/null +++ b/3rdparty/wlroots/render/gles2/shaders/tex_rgbx.frag @@ -0,0 +1,13 @@ +#ifdef GL_FRAGMENT_PRECISION_HIGH +precision highp float; +#else +precision mediump float; +#endif + +varying vec2 v_texcoord; +uniform sampler2D tex; +uniform float alpha; + +void main() { + gl_FragColor = vec4(texture2D(tex, v_texcoord).rgb, 1.0) * alpha; +} diff --git a/3rdparty/wlroots/render/gles2/texture.c b/3rdparty/wlroots/render/gles2/texture.c new file mode 100644 index 0000000000..9a967ebdb1 --- /dev/null +++ b/3rdparty/wlroots/render/gles2/texture.c @@ -0,0 +1,440 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "render/egl.h" +#include "render/gles2.h" +#include "render/pixel_format.h" + +static const struct wlr_texture_impl texture_impl; + +bool wlr_texture_is_gles2(struct wlr_texture *wlr_texture) { + return wlr_texture->impl == &texture_impl; +} + +struct wlr_gles2_texture *gles2_get_texture( + struct wlr_texture *wlr_texture) { + assert(wlr_texture_is_gles2(wlr_texture)); + struct wlr_gles2_texture *texture = wl_container_of(wlr_texture, texture, wlr_texture); + return texture; +} + +static bool gles2_texture_update_from_buffer(struct wlr_texture *wlr_texture, + struct wlr_buffer *buffer, const pixman_region32_t *damage) { + struct wlr_gles2_texture *texture = gles2_get_texture(wlr_texture); + + if (texture->drm_format == DRM_FORMAT_INVALID) { + return false; + } + + void *data; + uint32_t format; + size_t stride; + if (!wlr_buffer_begin_data_ptr_access(buffer, + WLR_BUFFER_DATA_PTR_ACCESS_READ, &data, &format, &stride)) { + return false; + } + + if (format != texture->drm_format) { + wlr_buffer_end_data_ptr_access(buffer); + return false; + } + + const struct wlr_gles2_pixel_format *fmt = + get_gles2_format_from_drm(texture->drm_format); + assert(fmt); + + const struct wlr_pixel_format_info *drm_fmt = + drm_get_pixel_format_info(texture->drm_format); + assert(drm_fmt); + if (pixel_format_info_pixels_per_block(drm_fmt) != 1) { + wlr_buffer_end_data_ptr_access(buffer); + wlr_log(WLR_ERROR, "Cannot update texture: block formats are not supported"); + return false; + } + + if (!pixel_format_info_check_stride(drm_fmt, stride, buffer->width)) { + wlr_buffer_end_data_ptr_access(buffer); + return false; + } + + struct wlr_egl_context prev_ctx; + wlr_egl_make_current(texture->renderer->egl, &prev_ctx); + + push_gles2_debug(texture->renderer); + + glBindTexture(GL_TEXTURE_2D, texture->tex); + + int rects_len = 0; + const pixman_box32_t *rects = pixman_region32_rectangles(damage, &rects_len); + + for (int i = 0; i < rects_len; i++) { + pixman_box32_t rect = rects[i]; + + glPixelStorei(GL_UNPACK_ROW_LENGTH_EXT, stride / drm_fmt->bytes_per_block); + glPixelStorei(GL_UNPACK_SKIP_PIXELS_EXT, rect.x1); + glPixelStorei(GL_UNPACK_SKIP_ROWS_EXT, rect.y1); + + int width = rect.x2 - rect.x1; + int height = rect.y2 - rect.y1; + glTexSubImage2D(GL_TEXTURE_2D, 0, rect.x1, rect.y1, width, height, + fmt->gl_format, fmt->gl_type, data); + } + + glPixelStorei(GL_UNPACK_ROW_LENGTH_EXT, 0); + glPixelStorei(GL_UNPACK_SKIP_PIXELS_EXT, 0); + glPixelStorei(GL_UNPACK_SKIP_ROWS_EXT, 0); + + glBindTexture(GL_TEXTURE_2D, 0); + + pop_gles2_debug(texture->renderer); + + wlr_egl_restore_context(&prev_ctx); + + wlr_buffer_end_data_ptr_access(buffer); + + return true; +} + +void gles2_texture_destroy(struct wlr_gles2_texture *texture) { + wl_list_remove(&texture->link); + if (texture->buffer != NULL) { + wlr_buffer_unlock(texture->buffer->buffer); + } else { + struct wlr_egl_context prev_ctx; + wlr_egl_make_current(texture->renderer->egl, &prev_ctx); + + push_gles2_debug(texture->renderer); + + glDeleteTextures(1, &texture->tex); + glDeleteFramebuffers(1, &texture->fbo); + + pop_gles2_debug(texture->renderer); + + wlr_egl_restore_context(&prev_ctx); + } + + free(texture); +} + +static void handle_gles2_texture_destroy(struct wlr_texture *wlr_texture) { + gles2_texture_destroy(gles2_get_texture(wlr_texture)); +} + +static bool gles2_texture_bind(struct wlr_gles2_texture *texture) { + if (texture->fbo) { + glBindFramebuffer(GL_FRAMEBUFFER, texture->fbo); + } else if (texture->buffer) { + if (texture->buffer->external_only) { + return false; + } + + GLuint fbo = gles2_buffer_get_fbo(texture->buffer); + if (!fbo) { + return false; + } + + glBindFramebuffer(GL_FRAMEBUFFER, fbo); + } else { + glGenFramebuffers(1, &texture->fbo); + glBindFramebuffer(GL_FRAMEBUFFER, texture->fbo); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, + texture->target, texture->tex, 0); + + GLenum fb_status = glCheckFramebufferStatus(GL_FRAMEBUFFER); + if (fb_status != GL_FRAMEBUFFER_COMPLETE) { + wlr_log(WLR_ERROR, "Failed to create FBO"); + glDeleteFramebuffers(1, &texture->fbo); + texture->fbo = 0; + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + return false; + } + } + + return true; +} + +static bool gles2_texture_read_pixels(struct wlr_texture *wlr_texture, + const struct wlr_texture_read_pixels_options *options) { + struct wlr_gles2_texture *texture = gles2_get_texture(wlr_texture); + + struct wlr_box src; + wlr_texture_read_pixels_options_get_src_box(options, wlr_texture, &src); + + const struct wlr_gles2_pixel_format *fmt = + get_gles2_format_from_drm(options->format); + if (fmt == NULL || !is_gles2_pixel_format_supported(texture->renderer, fmt)) { + wlr_log(WLR_ERROR, "Cannot read pixels: unsupported pixel format 0x%"PRIX32, options->format); + return false; + } + + if (fmt->gl_format == GL_BGRA_EXT && !texture->renderer->exts.EXT_read_format_bgra) { + wlr_log(WLR_ERROR, + "Cannot read pixels: missing GL_EXT_read_format_bgra extension"); + return false; + } + + const struct wlr_pixel_format_info *drm_fmt = + drm_get_pixel_format_info(fmt->drm_format); + assert(drm_fmt); + if (pixel_format_info_pixels_per_block(drm_fmt) != 1) { + wlr_log(WLR_ERROR, "Cannot read pixels: block formats are not supported"); + return false; + } + + push_gles2_debug(texture->renderer); + struct wlr_egl_context prev_ctx; + if (!wlr_egl_make_current(texture->renderer->egl, &prev_ctx)) { + return false; + } + + if (!gles2_texture_bind(texture)) { + return false; + } + + // Make sure any pending drawing is finished before we try to read it + glFinish(); + + glGetError(); // Clear the error flag + + unsigned char *p = wlr_texture_read_pixel_options_get_data(options); + + glPixelStorei(GL_PACK_ALIGNMENT, 1); + uint32_t pack_stride = pixel_format_info_min_stride(drm_fmt, src.width); + if (pack_stride == options->stride && options->dst_x == 0) { + // Under these particular conditions, we can read the pixels with only + // one glReadPixels call + + glReadPixels(src.x, src.y, src.width, src.height, fmt->gl_format, fmt->gl_type, p); + } else { + // Unfortunately GLES2 doesn't support GL_PACK_ROW_LENGTH, so we have to read + // the lines out row by row + for (int32_t i = 0; i < src.height; ++i) { + uint32_t y = src.y + i; + glReadPixels(src.x, y, src.width, 1, fmt->gl_format, + fmt->gl_type, p + i * options->stride); + } + } + + wlr_egl_restore_context(&prev_ctx); + pop_gles2_debug(texture->renderer); + + return glGetError() == GL_NO_ERROR; +} + +static uint32_t gles2_texture_preferred_read_format(struct wlr_texture *wlr_texture) { + struct wlr_gles2_texture *texture = gles2_get_texture(wlr_texture); + + push_gles2_debug(texture->renderer); + + uint32_t fmt = DRM_FORMAT_INVALID; + + struct wlr_egl_context prev_ctx; + if (!wlr_egl_make_current(texture->renderer->egl, &prev_ctx)) { + return fmt; + } + + if (!gles2_texture_bind(texture)) { + goto out; + } + + GLint gl_format = -1, gl_type = -1, alpha_size = -1; + glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &gl_format); + glGetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &gl_type); + glGetIntegerv(GL_ALPHA_BITS, &alpha_size); + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + pop_gles2_debug(texture->renderer); + + const struct wlr_gles2_pixel_format *pix_fmt = + get_gles2_format_from_gl(gl_format, gl_type, alpha_size > 0); + if (pix_fmt != NULL) { + fmt = pix_fmt->drm_format; + goto out; + } + + if (texture->renderer->exts.EXT_read_format_bgra) { + fmt = DRM_FORMAT_XRGB8888; + goto out; + } + +out: + wlr_egl_restore_context(&prev_ctx); + return fmt; +} + +static const struct wlr_texture_impl texture_impl = { + .update_from_buffer = gles2_texture_update_from_buffer, + .read_pixels = gles2_texture_read_pixels, + .preferred_read_format = gles2_texture_preferred_read_format, + .destroy = handle_gles2_texture_destroy, +}; + +static struct wlr_gles2_texture *gles2_texture_create( + struct wlr_gles2_renderer *renderer, uint32_t width, uint32_t height) { + struct wlr_gles2_texture *texture = calloc(1, sizeof(*texture)); + if (texture == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + wlr_texture_init(&texture->wlr_texture, &renderer->wlr_renderer, + &texture_impl, width, height); + texture->renderer = renderer; + wl_list_insert(&renderer->textures, &texture->link); + return texture; +} + +static struct wlr_texture *gles2_texture_from_pixels( + struct wlr_renderer *wlr_renderer, + uint32_t drm_format, uint32_t stride, uint32_t width, + uint32_t height, const void *data) { + struct wlr_gles2_renderer *renderer = gles2_get_renderer(wlr_renderer); + + const struct wlr_gles2_pixel_format *fmt = + get_gles2_format_from_drm(drm_format); + if (fmt == NULL) { + wlr_log(WLR_ERROR, "Unsupported pixel format 0x%"PRIX32, drm_format); + return NULL; + } + + const struct wlr_pixel_format_info *drm_fmt = + drm_get_pixel_format_info(drm_format); + assert(drm_fmt); + if (pixel_format_info_pixels_per_block(drm_fmt) != 1) { + wlr_log(WLR_ERROR, "Cannot upload texture: block formats are not supported"); + return NULL; + } + + if (!pixel_format_info_check_stride(drm_fmt, stride, width)) { + return NULL; + } + + struct wlr_gles2_texture *texture = + gles2_texture_create(renderer, width, height); + if (texture == NULL) { + return NULL; + } + texture->target = GL_TEXTURE_2D; + texture->has_alpha = pixel_format_has_alpha(fmt->drm_format); + texture->drm_format = fmt->drm_format; + + GLint internal_format = fmt->gl_internalformat; + if (!internal_format) { + internal_format = fmt->gl_format; + } + + struct wlr_egl_context prev_ctx; + wlr_egl_make_current(renderer->egl, &prev_ctx); + + push_gles2_debug(renderer); + + glGenTextures(1, &texture->tex); + glBindTexture(GL_TEXTURE_2D, texture->tex); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glPixelStorei(GL_UNPACK_ROW_LENGTH_EXT, stride / drm_fmt->bytes_per_block); + glTexImage2D(GL_TEXTURE_2D, 0, internal_format, width, height, 0, + fmt->gl_format, fmt->gl_type, data); + glPixelStorei(GL_UNPACK_ROW_LENGTH_EXT, 0); + + glBindTexture(GL_TEXTURE_2D, 0); + + pop_gles2_debug(renderer); + + wlr_egl_restore_context(&prev_ctx); + + return &texture->wlr_texture; +} + +static struct wlr_texture *gles2_texture_from_dmabuf( + struct wlr_gles2_renderer *renderer, struct wlr_buffer *wlr_buffer, + struct wlr_dmabuf_attributes *attribs) { + if (!renderer->procs.glEGLImageTargetTexture2DOES) { + return NULL; + } + + struct wlr_gles2_buffer *buffer = gles2_buffer_get_or_create(renderer, wlr_buffer); + if (!buffer) { + return NULL; + } + + struct wlr_gles2_texture *texture = + gles2_texture_create(renderer, attribs->width, attribs->height); + if (texture == NULL) { + return NULL; + } + + texture->target = buffer->external_only ? GL_TEXTURE_EXTERNAL_OES : GL_TEXTURE_2D; + texture->buffer = buffer; + texture->drm_format = DRM_FORMAT_INVALID; // texture can't be written anyways + texture->has_alpha = pixel_format_has_alpha(attribs->format); + + struct wlr_egl_context prev_ctx; + wlr_egl_make_current(renderer->egl, &prev_ctx); + push_gles2_debug(texture->renderer); + + bool invalid; + if (!buffer->tex) { + glGenTextures(1, &buffer->tex); + invalid = true; + } else { + // External changes are immediately made visible by the GL implementation + invalid = !buffer->external_only; + } + + if (invalid) { + glBindTexture(texture->target, buffer->tex); + glTexParameteri(texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + renderer->procs.glEGLImageTargetTexture2DOES(texture->target, buffer->image); + glBindTexture(texture->target, 0); + } + + pop_gles2_debug(texture->renderer); + wlr_egl_restore_context(&prev_ctx); + + texture->tex = buffer->tex; + wlr_buffer_lock(texture->buffer->buffer); + return &texture->wlr_texture; +} + +struct wlr_texture *gles2_texture_from_buffer(struct wlr_renderer *wlr_renderer, + struct wlr_buffer *buffer) { + struct wlr_gles2_renderer *renderer = gles2_get_renderer(wlr_renderer); + + void *data; + uint32_t format; + size_t stride; + struct wlr_dmabuf_attributes dmabuf; + if (wlr_buffer_get_dmabuf(buffer, &dmabuf)) { + return gles2_texture_from_dmabuf(renderer, buffer, &dmabuf); + } else if (wlr_buffer_begin_data_ptr_access(buffer, + WLR_BUFFER_DATA_PTR_ACCESS_READ, &data, &format, &stride)) { + struct wlr_texture *tex = gles2_texture_from_pixels(wlr_renderer, + format, stride, buffer->width, buffer->height, data); + wlr_buffer_end_data_ptr_access(buffer); + return tex; + } else { + return NULL; + } +} + +void wlr_gles2_texture_get_attribs(struct wlr_texture *wlr_texture, + struct wlr_gles2_texture_attribs *attribs) { + struct wlr_gles2_texture *texture = gles2_get_texture(wlr_texture); + *attribs = (struct wlr_gles2_texture_attribs){ + .target = texture->target, + .tex = texture->tex, + .has_alpha = texture->has_alpha, + }; +} diff --git a/3rdparty/wlroots/render/meson.build b/3rdparty/wlroots/render/meson.build new file mode 100644 index 0000000000..517d76bf05 --- /dev/null +++ b/3rdparty/wlroots/render/meson.build @@ -0,0 +1,74 @@ +renderers = get_option('renderers') +if 'auto' in renderers and get_option('auto_features').enabled() + renderers = ['gles2', 'vulkan'] +elif 'auto' in renderers and get_option('auto_features').disabled() + renderers = [] +endif + +wlr_files += files( + 'color.c', + 'dmabuf.c', + 'drm_format_set.c', + 'drm_syncobj_merger.c', + 'drm_syncobj.c', + 'pass.c', + 'pixel_format.c', + 'swapchain.c', + 'wlr_renderer.c', + 'wlr_texture.c', +) + +has_dma_buf_import_sync_file = cc.has_header('linux/dma-buf.h') and cc.has_define( + 'DMA_BUF_IOCTL_IMPORT_SYNC_FILE', + prefix: '#include ', +) +if has_dma_buf_import_sync_file and target_machine.system() == 'linux' + wlr_files += files('dmabuf_linux.c') +else + wlr_files += files('dmabuf_fallback.c') +endif + +internal_config.set10('HAVE_EVENTFD', cc.has_header('sys/eventfd.h')) +internal_config.set10('HAVE_LINUX_SYNC_FILE', cc.has_header('linux/sync_file.h')) + +if 'gles2' in renderers or 'auto' in renderers + egl = dependency('egl', required: 'gles2' in renderers) + if egl.found() + eglext_version = cc.get_define( + 'EGL_EGLEXT_VERSION', + dependencies: egl, + prefix: '#include ', + ).to_int() + if eglext_version < 20210604 + egl = dependency( + '', + required: 'gles2' in renderers, + not_found_message: 'EGL headers too old', + ) + endif + endif + gbm = dependency('gbm', required: 'gles2' in renderers) + if egl.found() and gbm.found() + wlr_deps += [egl, gbm] + wlr_files += files('egl.c') + internal_features += { 'egl': true } + endif + subdir('gles2') +endif + +if 'vulkan' in renderers or 'auto' in renderers + subdir('vulkan') +endif + +subdir('pixman') + +subdir('allocator') + +lcms2 = dependency('lcms2', required: get_option('color-management')) +if lcms2.found() + wlr_deps += lcms2 + wlr_files += files('color_lcms2.c') + features += { 'color-management': true } +else + wlr_files += files('color_fallback.c') +endif diff --git a/3rdparty/wlroots/render/pass.c b/3rdparty/wlroots/render/pass.c new file mode 100644 index 0000000000..23bdf96dde --- /dev/null +++ b/3rdparty/wlroots/render/pass.c @@ -0,0 +1,76 @@ +#include +#include +#include + +void wlr_render_pass_init(struct wlr_render_pass *render_pass, + const struct wlr_render_pass_impl *impl) { + assert(impl->submit && impl->add_texture && impl->add_rect); + *render_pass = (struct wlr_render_pass){ + .impl = impl, + }; +} + +bool wlr_render_pass_submit(struct wlr_render_pass *render_pass) { + return render_pass->impl->submit(render_pass); +} + +void wlr_render_pass_add_texture(struct wlr_render_pass *render_pass, + const struct wlr_render_texture_options *options) { + // make sure the texture source box does not try and sample outside of the + // texture + if (!wlr_fbox_empty(&options->src_box)) { + const struct wlr_fbox *box = &options->src_box; + assert(box->x >= 0 && box->y >= 0 && + (uint32_t)(box->x + box->width) <= options->texture->width && + (uint32_t)(box->y + box->height) <= options->texture->height); + } + + render_pass->impl->add_texture(render_pass, options); +} + +void wlr_render_pass_add_rect(struct wlr_render_pass *render_pass, + const struct wlr_render_rect_options *options) { + assert(options->box.width >= 0 && options->box.height >= 0); + render_pass->impl->add_rect(render_pass, options); +} + +void wlr_render_texture_options_get_src_box(const struct wlr_render_texture_options *options, + struct wlr_fbox *box) { + *box = options->src_box; + if (wlr_fbox_empty(box)) { + *box = (struct wlr_fbox){ + .width = options->texture->width, + .height = options->texture->height, + }; + } +} + +void wlr_render_texture_options_get_dst_box(const struct wlr_render_texture_options *options, + struct wlr_box *box) { + *box = options->dst_box; + if (wlr_box_empty(box)) { + box->width = options->texture->width; + box->height = options->texture->height; + } +} + +float wlr_render_texture_options_get_alpha(const struct wlr_render_texture_options *options) { + if (options->alpha == NULL) { + return 1; + } + return *options->alpha; +} + +void wlr_render_rect_options_get_box(const struct wlr_render_rect_options *options, + const struct wlr_buffer *buffer, struct wlr_box *box) { + if (wlr_box_empty(&options->box)) { + *box = (struct wlr_box){ + .width = buffer->width, + .height = buffer->height, + }; + + return; + } + + *box = options->box; +} diff --git a/3rdparty/wlroots/render/pixel_format.c b/3rdparty/wlroots/render/pixel_format.c new file mode 100644 index 0000000000..c60dd9d2ae --- /dev/null +++ b/3rdparty/wlroots/render/pixel_format.c @@ -0,0 +1,374 @@ +#include +#include +#include +#include "render/pixel_format.h" + +static const struct wlr_pixel_format_info pixel_format_info[] = { + { + .drm_format = DRM_FORMAT_XRGB8888, + .bytes_per_block = 4, + }, + { + .drm_format = DRM_FORMAT_ARGB8888, + .opaque_substitute = DRM_FORMAT_XRGB8888, + .bytes_per_block = 4, + }, + { + .drm_format = DRM_FORMAT_XBGR8888, + .bytes_per_block = 4, + }, + { + .drm_format = DRM_FORMAT_ABGR8888, + .opaque_substitute = DRM_FORMAT_XBGR8888, + .bytes_per_block = 4, + }, + { + .drm_format = DRM_FORMAT_RGBX8888, + .bytes_per_block = 4, + }, + { + .drm_format = DRM_FORMAT_RGBA8888, + .opaque_substitute = DRM_FORMAT_RGBX8888, + .bytes_per_block = 4, + }, + { + .drm_format = DRM_FORMAT_BGRX8888, + .bytes_per_block = 4, + }, + { + .drm_format = DRM_FORMAT_BGRA8888, + .opaque_substitute = DRM_FORMAT_BGRX8888, + .bytes_per_block = 4, + }, + { + .drm_format = DRM_FORMAT_R8, + .bytes_per_block = 1, + }, + { + .drm_format = DRM_FORMAT_R16F, + .bytes_per_block = 2, + }, + { + .drm_format = DRM_FORMAT_R32F, + .bytes_per_block = 4, + }, + { + .drm_format = DRM_FORMAT_GR88, + .bytes_per_block = 2, + }, + { + .drm_format = DRM_FORMAT_GR1616F, + .bytes_per_block = 4, + }, + { + .drm_format = DRM_FORMAT_GR3232F, + .bytes_per_block = 8, + }, + { + .drm_format = DRM_FORMAT_RGB888, + .bytes_per_block = 3, + }, + { + .drm_format = DRM_FORMAT_BGR888, + .bytes_per_block = 3, + }, + { + .drm_format = DRM_FORMAT_BGR161616, + .bytes_per_block = 6, + }, + { + .drm_format = DRM_FORMAT_BGR161616F, + .bytes_per_block = 6, + }, + { + .drm_format = DRM_FORMAT_BGR323232F, + .bytes_per_block = 12, + }, + { + .drm_format = DRM_FORMAT_RGBX4444, + .bytes_per_block = 2, + }, + { + .drm_format = DRM_FORMAT_RGBA4444, + .opaque_substitute = DRM_FORMAT_RGBX4444, + .bytes_per_block = 2, + }, + { + .drm_format = DRM_FORMAT_BGRX4444, + .bytes_per_block = 2, + }, + { + .drm_format = DRM_FORMAT_BGRA4444, + .opaque_substitute = DRM_FORMAT_BGRX4444, + .bytes_per_block = 2, + }, + { + .drm_format = DRM_FORMAT_RGBX5551, + .bytes_per_block = 2, + }, + { + .drm_format = DRM_FORMAT_RGBA5551, + .opaque_substitute = DRM_FORMAT_RGBX5551, + .bytes_per_block = 2, + }, + { + .drm_format = DRM_FORMAT_BGRX5551, + .bytes_per_block = 2, + }, + { + .drm_format = DRM_FORMAT_BGRA5551, + .opaque_substitute = DRM_FORMAT_BGRX5551, + .bytes_per_block = 2, + }, + { + .drm_format = DRM_FORMAT_XRGB1555, + .bytes_per_block = 2, + }, + { + .drm_format = DRM_FORMAT_ARGB1555, + .opaque_substitute = DRM_FORMAT_XRGB1555, + .bytes_per_block = 2, + }, + { + .drm_format = DRM_FORMAT_RGB565, + .bytes_per_block = 2, + }, + { + .drm_format = DRM_FORMAT_BGR565, + .bytes_per_block = 2, + }, + { + .drm_format = DRM_FORMAT_XRGB2101010, + .bytes_per_block = 4, + }, + { + .drm_format = DRM_FORMAT_ARGB2101010, + .opaque_substitute = DRM_FORMAT_XRGB2101010, + .bytes_per_block = 4, + }, + { + .drm_format = DRM_FORMAT_XBGR2101010, + .bytes_per_block = 4, + }, + { + .drm_format = DRM_FORMAT_ABGR2101010, + .opaque_substitute = DRM_FORMAT_XBGR2101010, + .bytes_per_block = 4, + }, + { + .drm_format = DRM_FORMAT_XBGR16161616F, + .bytes_per_block = 8, + }, + { + .drm_format = DRM_FORMAT_ABGR16161616F, + .opaque_substitute = DRM_FORMAT_XBGR16161616F, + .bytes_per_block = 8, + }, + { + .drm_format = DRM_FORMAT_ABGR32323232F, + .bytes_per_block = 16, + }, + { + .drm_format = DRM_FORMAT_XBGR16161616, + .bytes_per_block = 8, + }, + { + .drm_format = DRM_FORMAT_ABGR16161616, + .opaque_substitute = DRM_FORMAT_XBGR16161616, + .bytes_per_block = 8, + }, + { + .drm_format = DRM_FORMAT_YVYU, + .bytes_per_block = 4, + .block_width = 2, + .block_height = 1, + }, + { + .drm_format = DRM_FORMAT_VYUY, + .bytes_per_block = 4, + .block_width = 2, + .block_height = 1, + }, +}; + +static const uint32_t opaque_pixel_formats[] = { + DRM_FORMAT_XRGB8888, + DRM_FORMAT_XBGR8888, + DRM_FORMAT_RGBX8888, + DRM_FORMAT_BGRX8888, + DRM_FORMAT_R8, + DRM_FORMAT_GR88, + DRM_FORMAT_RGB888, + DRM_FORMAT_BGR888, + DRM_FORMAT_RGBX4444, + DRM_FORMAT_BGRX4444, + DRM_FORMAT_RGBX5551, + DRM_FORMAT_BGRX5551, + DRM_FORMAT_XRGB1555, + DRM_FORMAT_RGB565, + DRM_FORMAT_BGR565, + DRM_FORMAT_XRGB2101010, + DRM_FORMAT_XBGR2101010, + DRM_FORMAT_XBGR16161616F, + DRM_FORMAT_XBGR16161616, + DRM_FORMAT_YVYU, + DRM_FORMAT_VYUY, + DRM_FORMAT_NV12, + DRM_FORMAT_P010, +}; + +static const size_t pixel_format_info_size = + sizeof(pixel_format_info) / sizeof(pixel_format_info[0]); + +static const size_t opaque_pixel_formats_size = + sizeof(opaque_pixel_formats) / sizeof(opaque_pixel_formats[0]); + +const struct wlr_pixel_format_info *drm_get_pixel_format_info(uint32_t fmt) { + for (size_t i = 0; i < pixel_format_info_size; ++i) { + if (pixel_format_info[i].drm_format == fmt) { + return &pixel_format_info[i]; + } + } + + return NULL; +} + +uint32_t convert_wl_shm_format_to_drm(enum wl_shm_format fmt) { + switch (fmt) { + case WL_SHM_FORMAT_XRGB8888: + return DRM_FORMAT_XRGB8888; + case WL_SHM_FORMAT_ARGB8888: + return DRM_FORMAT_ARGB8888; + default: + return (uint32_t)fmt; + } +} + +enum wl_shm_format convert_drm_format_to_wl_shm(uint32_t fmt) { + switch (fmt) { + case DRM_FORMAT_XRGB8888: + return WL_SHM_FORMAT_XRGB8888; + case DRM_FORMAT_ARGB8888: + return WL_SHM_FORMAT_ARGB8888; + default: + return (enum wl_shm_format)fmt; + } +} + +uint32_t pixel_format_info_pixels_per_block(const struct wlr_pixel_format_info *info) { + uint32_t pixels = info->block_width * info->block_height; + return pixels > 0 ? pixels : 1; +} + +static int32_t div_round_up(int32_t dividend, int32_t divisor) { + int32_t quotient = dividend / divisor; + if (dividend % divisor != 0) { + quotient++; + } + return quotient; +} + +int32_t pixel_format_info_min_stride(const struct wlr_pixel_format_info *fmt, int32_t width) { + int32_t pixels_per_block = (int32_t)pixel_format_info_pixels_per_block(fmt); + int32_t bytes_per_block = (int32_t)fmt->bytes_per_block; + if (width > INT32_MAX / bytes_per_block) { + wlr_log(WLR_DEBUG, "Invalid width %d (overflow)", width); + return 0; + } + return div_round_up(width * bytes_per_block, pixels_per_block); +} + +bool pixel_format_info_check_stride(const struct wlr_pixel_format_info *fmt, + int32_t stride, int32_t width) { + int32_t bytes_per_block = (int32_t)fmt->bytes_per_block; + if (stride % bytes_per_block != 0) { + wlr_log(WLR_DEBUG, "Invalid stride %d (incompatible with %d " + "bytes-per-block)", stride, bytes_per_block); + return false; + } + + int32_t min_stride = pixel_format_info_min_stride(fmt, width); + if (min_stride <= 0) { + return false; + } else if (stride < min_stride) { + wlr_log(WLR_DEBUG, "Invalid stride %d (too small for %d " + "bytes-per-block and width %d)", stride, bytes_per_block, width); + return false; + } + + return true; +} + +bool pixel_format_has_alpha(uint32_t fmt) { + for (size_t i = 0; i < opaque_pixel_formats_size; i++) { + if (fmt == opaque_pixel_formats[i]) { + return false; + } + } + return true; +} + +bool pixel_format_is_ycbcr(uint32_t format) { + switch (format) { + case DRM_FORMAT_AYUV: + case DRM_FORMAT_NV12: + case DRM_FORMAT_NV15: + case DRM_FORMAT_NV16: + case DRM_FORMAT_NV20: + case DRM_FORMAT_NV21: + case DRM_FORMAT_NV24: + case DRM_FORMAT_NV30: + case DRM_FORMAT_NV42: + case DRM_FORMAT_NV61: + case DRM_FORMAT_P010: + case DRM_FORMAT_P012: + case DRM_FORMAT_P016: + case DRM_FORMAT_P030: + case DRM_FORMAT_P210: + case DRM_FORMAT_Q401: + case DRM_FORMAT_Q410: + case DRM_FORMAT_S010: + case DRM_FORMAT_S012: + case DRM_FORMAT_S016: + case DRM_FORMAT_S210: + case DRM_FORMAT_S212: + case DRM_FORMAT_S216: + case DRM_FORMAT_S410: + case DRM_FORMAT_S412: + case DRM_FORMAT_S416: + case DRM_FORMAT_UYVY: + case DRM_FORMAT_VUY101010: + case DRM_FORMAT_VUY888: + case DRM_FORMAT_VYUY: + case DRM_FORMAT_X0L0: + case DRM_FORMAT_X0L2: + case DRM_FORMAT_XVYU12_16161616: + case DRM_FORMAT_XVYU16161616: + case DRM_FORMAT_XVYU2101010: + case DRM_FORMAT_XYUV8888: + case DRM_FORMAT_Y0L0: + case DRM_FORMAT_Y0L2: + case DRM_FORMAT_Y210: + case DRM_FORMAT_Y212: + case DRM_FORMAT_Y216: + case DRM_FORMAT_Y410: + case DRM_FORMAT_Y412: + case DRM_FORMAT_Y416: + case DRM_FORMAT_YUV410: + case DRM_FORMAT_YUV411: + case DRM_FORMAT_YUV420: + case DRM_FORMAT_YUV420_10BIT: + case DRM_FORMAT_YUV420_8BIT: + case DRM_FORMAT_YUV422: + case DRM_FORMAT_YUV444: + case DRM_FORMAT_YUYV: + case DRM_FORMAT_YVU410: + case DRM_FORMAT_YVU411: + case DRM_FORMAT_YVU420: + case DRM_FORMAT_YVU422: + case DRM_FORMAT_YVU444: + case DRM_FORMAT_YVYU: + return true; + } + return false; +} diff --git a/3rdparty/wlroots/render/pixman/meson.build b/3rdparty/wlroots/render/pixman/meson.build new file mode 100644 index 0000000000..dea96b096d --- /dev/null +++ b/3rdparty/wlroots/render/pixman/meson.build @@ -0,0 +1,9 @@ +pixman = dependency('pixman-1', version: '>=0.46.0') + +wlr_deps += pixman + +wlr_files += files( + 'pass.c', + 'pixel_format.c', + 'renderer.c', +) diff --git a/3rdparty/wlroots/render/pixman/pass.c b/3rdparty/wlroots/render/pixman/pass.c new file mode 100644 index 0000000000..af738bb42f --- /dev/null +++ b/3rdparty/wlroots/render/pixman/pass.c @@ -0,0 +1,254 @@ +#include +#include +#include "render/pixman.h" + +static const struct wlr_render_pass_impl render_pass_impl; + +static struct wlr_pixman_render_pass *get_render_pass(struct wlr_render_pass *wlr_pass) { + assert(wlr_pass->impl == &render_pass_impl); + struct wlr_pixman_render_pass *pass = wl_container_of(wlr_pass, pass, base); + return pass; +} + +static struct wlr_pixman_texture *get_texture(struct wlr_texture *wlr_texture) { + assert(wlr_texture_is_pixman(wlr_texture)); + struct wlr_pixman_texture *texture = wl_container_of(wlr_texture, texture, wlr_texture); + return texture; +} + +static bool render_pass_submit(struct wlr_render_pass *wlr_pass) { + struct wlr_pixman_render_pass *pass = get_render_pass(wlr_pass); + + wlr_buffer_end_data_ptr_access(pass->buffer->buffer); + wlr_buffer_unlock(pass->buffer->buffer); + free(pass); + + return true; +} + +static pixman_op_t get_pixman_blending(enum wlr_render_blend_mode mode) { + switch (mode) { + case WLR_RENDER_BLEND_MODE_PREMULTIPLIED: + return PIXMAN_OP_OVER; + case WLR_RENDER_BLEND_MODE_NONE: + return PIXMAN_OP_SRC; + } + abort(); +} + +static void render_pass_add_texture(struct wlr_render_pass *wlr_pass, + const struct wlr_render_texture_options *options) { + struct wlr_pixman_render_pass *pass = get_render_pass(wlr_pass); + struct wlr_pixman_texture *texture = get_texture(options->texture); + struct wlr_pixman_buffer *buffer = pass->buffer; + + if (texture->buffer != NULL && !begin_pixman_data_ptr_access(texture->buffer, + &texture->image, WLR_BUFFER_DATA_PTR_ACCESS_READ)) { + return; + } + + pixman_op_t op = get_pixman_blending(options->blend_mode); + pixman_image_set_clip_region32(buffer->image, options->clip); + + struct wlr_fbox src_fbox; + wlr_render_texture_options_get_src_box(options, &src_fbox); + struct wlr_box src_box = { + .x = roundf(src_fbox.x), + .y = roundf(src_fbox.y), + .width = roundf(src_fbox.width), + .height = roundf(src_fbox.height), + }; + + struct wlr_box dst_box; + wlr_render_texture_options_get_dst_box(options, &dst_box); + + pixman_image_t *mask = NULL; + float alpha = wlr_render_texture_options_get_alpha(options); + if (alpha != 1) { + mask = pixman_image_create_solid_fill(&(struct pixman_color){ + .alpha = 0xFFFF * alpha, + }); + } + + // Rotate the source size into destination coordinates + struct wlr_box src_box_transformed; + wlr_box_transform(&src_box_transformed, &src_box, options->transform, + buffer->buffer->width, buffer->buffer->height); + + if (options->transform != WL_OUTPUT_TRANSFORM_NORMAL || + src_box_transformed.width != dst_box.width || + src_box_transformed.height != dst_box.height) { + // Cosinus/sinus values are exact integers for enum wl_output_transform entries + int tr_cos = 1, tr_sin = 0, tr_x = 0, tr_y = 0; + switch (options->transform) { + case WL_OUTPUT_TRANSFORM_NORMAL: + case WL_OUTPUT_TRANSFORM_FLIPPED: + break; + case WL_OUTPUT_TRANSFORM_90: + case WL_OUTPUT_TRANSFORM_FLIPPED_90: + tr_cos = 0; + tr_sin = 1; + tr_y = src_box.width; + break; + case WL_OUTPUT_TRANSFORM_180: + case WL_OUTPUT_TRANSFORM_FLIPPED_180: + tr_cos = -1; + tr_sin = 0; + tr_x = src_box.width; + tr_y = src_box.height; + break; + case WL_OUTPUT_TRANSFORM_270: + case WL_OUTPUT_TRANSFORM_FLIPPED_270: + tr_cos = 0; + tr_sin = -1; + tr_x = src_box.height; + break; + } + + // Pixman transforms are generally the opposite of what you expect because they + // apply to the coordinate system rather than the image. The comments here + // refer to what happens to the image, so all the code between + // pixman_transform_init_identity() and pixman_image_set_transform() is probably + // best read backwards. Also this means translations are in the opposite + // direction, imagine them as moving the origin around rather than moving the + // image. + // + // Beware that this doesn't work quite the same as wp_viewporter: We apply crop + // before transform and scale, whereas it defines crop in post-transform-scale + // coordinates. But this only applies to internal wlroots code - the viewporter + // extension code makes sure that to clients everything works as it should. + + struct pixman_transform transform; + pixman_transform_init_identity(&transform); + + // Apply scaling to get to the dst_box size. Because the scaling is applied last + // it depends on the whether the rotation swapped width and height, which is why + // we use src_box_transformed instead of src_box. + pixman_transform_scale(&transform, NULL, + pixman_double_to_fixed(src_box_transformed.width / (double)dst_box.width), + pixman_double_to_fixed(src_box_transformed.height / (double)dst_box.height)); + + // pixman rotates about the origin which again leaves everything outside of the + // viewport. Translate the result so that its new top-left corner is back at the + // origin. + pixman_transform_translate(&transform, NULL, + -pixman_int_to_fixed(tr_x), -pixman_int_to_fixed(tr_y)); + + // Apply the rotation + pixman_transform_rotate(&transform, NULL, + pixman_int_to_fixed(tr_cos), pixman_int_to_fixed(tr_sin)); + + // Apply flip before rotation + if (options->transform >= WL_OUTPUT_TRANSFORM_FLIPPED) { + // The flip leaves everything left of the Y axis which is outside the + // viewport. So translate everything back into the viewport. + pixman_transform_translate(&transform, NULL, + -pixman_int_to_fixed(src_box.width), pixman_int_to_fixed(0)); + // Flip by applying a scale of -1 to the X axis + pixman_transform_scale(&transform, NULL, + pixman_int_to_fixed(-1), pixman_int_to_fixed(1)); + } + + // Apply the translation for source crop so the origin is now at the top-left of + // the region we're actually using. Do this last so all the other transforms + // apply on top of this. + pixman_transform_translate(&transform, NULL, + pixman_int_to_fixed(src_box.x), pixman_int_to_fixed(src_box.y)); + + pixman_image_set_transform(texture->image, &transform); + + switch (options->filter_mode) { + case WLR_SCALE_FILTER_BILINEAR: + pixman_image_set_repeat(texture->image, PIXMAN_REPEAT_PAD); + pixman_image_set_filter(texture->image, PIXMAN_FILTER_BILINEAR, NULL, 0); + break; + case WLR_SCALE_FILTER_NEAREST: + pixman_image_set_filter(texture->image, PIXMAN_FILTER_NEAREST, NULL, 0); + break; + } + + // Now composite the result onto the pass buffer. We specify a source origin of 0,0 + // because the x,y part of source crop is already done using the transform. The + // width,height part of source crop is done here by the width and height we pass: + // because of the scaling, cropping at the end by dst_box.{width,height} is + // equivalent to if we cropped at the start by src_box.{width,height}. + pixman_image_composite32(op, texture->image, mask, buffer->image, + 0, 0, // source x,y + 0, 0, // mask x,y + dst_box.x, dst_box.y, // dest x,y + dst_box.width, dst_box.height // composite width,height + ); + + pixman_image_set_transform(texture->image, NULL); + } else { + // No transforms or crop needed, just a straight blit from the source + pixman_image_set_transform(texture->image, NULL); + pixman_image_composite32(op, texture->image, mask, buffer->image, + src_box.x, src_box.y, 0, 0, dst_box.x, dst_box.y, + src_box.width, src_box.height); + } + + pixman_image_set_clip_region32(buffer->image, NULL); + + if (texture->buffer != NULL) { + wlr_buffer_end_data_ptr_access(texture->buffer); + } + + if (mask != NULL) { + pixman_image_unref(mask); + } +} + +static void render_pass_add_rect(struct wlr_render_pass *wlr_pass, + const struct wlr_render_rect_options *options) { + struct wlr_pixman_render_pass *pass = get_render_pass(wlr_pass); + struct wlr_pixman_buffer *buffer = pass->buffer; + struct wlr_box box; + wlr_render_rect_options_get_box(options, pass->buffer->buffer, &box); + + pixman_op_t op = get_pixman_blending(options->color.a == 1 ? + WLR_RENDER_BLEND_MODE_NONE : options->blend_mode); + + struct pixman_color color = { + .red = options->color.r * 0xFFFF, + .green = options->color.g * 0xFFFF, + .blue = options->color.b * 0xFFFF, + .alpha = options->color.a * 0xFFFF, + }; + + pixman_image_t *fill = pixman_image_create_solid_fill(&color); + + pixman_image_set_clip_region32(buffer->image, options->clip); + pixman_image_composite32(op, fill, NULL, buffer->image, + 0, 0, 0, 0, box.x, box.y, box.width, box.height); + pixman_image_set_clip_region32(buffer->image, NULL); + + pixman_image_unref(fill); +} + +static const struct wlr_render_pass_impl render_pass_impl = { + .submit = render_pass_submit, + .add_texture = render_pass_add_texture, + .add_rect = render_pass_add_rect, +}; + +struct wlr_pixman_render_pass *begin_pixman_render_pass( + struct wlr_pixman_buffer *buffer) { + struct wlr_pixman_render_pass *pass = calloc(1, sizeof(*pass)); + if (pass == NULL) { + return NULL; + } + + wlr_render_pass_init(&pass->base, &render_pass_impl); + + if (!begin_pixman_data_ptr_access(buffer->buffer, &buffer->image, + WLR_BUFFER_DATA_PTR_ACCESS_READ | WLR_BUFFER_DATA_PTR_ACCESS_WRITE)) { + free(pass); + return NULL; + } + + wlr_buffer_lock(buffer->buffer); + pass->buffer = buffer; + + return pass; +} diff --git a/3rdparty/wlroots/render/pixman/pixel_format.c b/3rdparty/wlroots/render/pixman/pixel_format.c new file mode 100644 index 0000000000..c308a2b67f --- /dev/null +++ b/3rdparty/wlroots/render/pixman/pixel_format.c @@ -0,0 +1,135 @@ +#include +#include + +#include "render/pixman.h" + +static const struct wlr_pixman_pixel_format formats[] = { + { + .drm_format = DRM_FORMAT_ARGB8888, +#if WLR_BIG_ENDIAN + .pixman_format = PIXMAN_b8g8r8a8, +#else + .pixman_format = PIXMAN_a8r8g8b8, +#endif + }, + { + .drm_format = DRM_FORMAT_XBGR8888, +#if WLR_BIG_ENDIAN + .pixman_format = PIXMAN_r8g8b8x8, +#else + .pixman_format = PIXMAN_x8b8g8r8, +#endif + }, + { + .drm_format = DRM_FORMAT_XRGB8888, +#if WLR_BIG_ENDIAN + .pixman_format = PIXMAN_b8g8r8x8, +#else + .pixman_format = PIXMAN_x8r8g8b8, +#endif + }, + { + .drm_format = DRM_FORMAT_ABGR8888, +#if WLR_BIG_ENDIAN + .pixman_format = PIXMAN_r8g8b8a8, +#else + .pixman_format = PIXMAN_a8b8g8r8, +#endif + }, + { + .drm_format = DRM_FORMAT_RGBA8888, +#if WLR_BIG_ENDIAN + .pixman_format = PIXMAN_a8b8g8r8, +#else + .pixman_format = PIXMAN_r8g8b8a8, +#endif + }, + { + .drm_format = DRM_FORMAT_RGBX8888, +#if WLR_BIG_ENDIAN + .pixman_format = PIXMAN_x8b8g8r8, +#else + .pixman_format = PIXMAN_r8g8b8x8, +#endif + }, + { + .drm_format = DRM_FORMAT_BGRA8888, +#if WLR_BIG_ENDIAN + .pixman_format = PIXMAN_a8r8g8b8, +#else + .pixman_format = PIXMAN_b8g8r8a8, +#endif + }, + { + .drm_format = DRM_FORMAT_BGRX8888, +#if WLR_BIG_ENDIAN + .pixman_format = PIXMAN_x8r8g8b8, +#else + .pixman_format = PIXMAN_b8g8r8x8, +#endif + }, +#if WLR_LITTLE_ENDIAN + // Since DRM formats are always little-endian, they don't have an + // equivalent on big-endian if their components are spanning across + // multiple bytes. + { + .drm_format = DRM_FORMAT_RGB565, + .pixman_format = PIXMAN_r5g6b5, + }, + { + .drm_format = DRM_FORMAT_BGR565, + .pixman_format = PIXMAN_b5g6r5, + }, + { + .drm_format = DRM_FORMAT_ARGB2101010, + .pixman_format = PIXMAN_a2r10g10b10, + }, + { + .drm_format = DRM_FORMAT_XRGB2101010, + .pixman_format = PIXMAN_x2r10g10b10, + }, + { + .drm_format = DRM_FORMAT_ABGR2101010, + .pixman_format = PIXMAN_a2b10g10r10, + }, + { + .drm_format = DRM_FORMAT_XBGR2101010, + .pixman_format = PIXMAN_x2b10g10r10, + }, + { + .drm_format = DRM_FORMAT_ABGR16161616, + .pixman_format = PIXMAN_a16b16g16r16, + }, +#endif +}; + +pixman_format_code_t get_pixman_format_from_drm(uint32_t fmt) { + for (size_t i = 0; i < sizeof(formats) / sizeof(*formats); ++i) { + if (formats[i].drm_format == fmt) { + return formats[i].pixman_format; + } + } + + wlr_log(WLR_ERROR, "DRM format 0x%"PRIX32" has no pixman equivalent", fmt); + return 0; +} + +uint32_t get_drm_format_from_pixman(pixman_format_code_t fmt) { + for (size_t i = 0; i < sizeof(formats) / sizeof(*formats); ++i) { + if (formats[i].pixman_format == fmt) { + return formats[i].drm_format; + } + } + + wlr_log(WLR_ERROR, "pixman format 0x%"PRIX32" has no drm equivalent", fmt); + return DRM_FORMAT_INVALID; +} + +const uint32_t *get_pixman_drm_formats(size_t *len) { + static uint32_t drm_formats[sizeof(formats) / sizeof(formats[0])]; + *len = sizeof(formats) / sizeof(formats[0]); + for (size_t i = 0; i < sizeof(formats) / sizeof(formats[0]); i++) { + drm_formats[i] = formats[i].drm_format; + } + return drm_formats; +} diff --git a/3rdparty/wlroots/render/pixman/renderer.c b/3rdparty/wlroots/render/pixman/renderer.c new file mode 100644 index 0000000000..4631a33ab8 --- /dev/null +++ b/3rdparty/wlroots/render/pixman/renderer.c @@ -0,0 +1,363 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "render/pixman.h" +#include "types/wlr_buffer.h" + +static const struct wlr_renderer_impl renderer_impl; + +bool wlr_renderer_is_pixman(struct wlr_renderer *wlr_renderer) { + return wlr_renderer->impl == &renderer_impl; +} + +static struct wlr_pixman_renderer *get_renderer( + struct wlr_renderer *wlr_renderer) { + assert(wlr_renderer_is_pixman(wlr_renderer)); + struct wlr_pixman_renderer *renderer = wl_container_of(wlr_renderer, renderer, wlr_renderer); + return renderer; +} + +bool begin_pixman_data_ptr_access(struct wlr_buffer *wlr_buffer, pixman_image_t **image_ptr, + uint32_t flags) { + pixman_image_t *image = *image_ptr; + + void *data = NULL; + uint32_t drm_format; + size_t stride; + if (!wlr_buffer_begin_data_ptr_access(wlr_buffer, flags, + &data, &drm_format, &stride)) { + return false; + } + + // If the data pointer has changed, re-create the Pixman image. This can + // happen if it's a client buffer and the wl_shm_pool has been resized. + if (data != pixman_image_get_data(image)) { + pixman_format_code_t format = get_pixman_format_from_drm(drm_format); + assert(format != 0); + + pixman_image_t *new_image = pixman_image_create_bits_no_clear(format, + wlr_buffer->width, wlr_buffer->height, data, stride); + if (new_image == NULL) { + wlr_buffer_end_data_ptr_access(wlr_buffer); + return false; + } + + pixman_image_unref(image); + image = new_image; + } + + *image_ptr = image; + return true; +} + +static struct wlr_pixman_buffer *get_buffer( + struct wlr_pixman_renderer *renderer, struct wlr_buffer *wlr_buffer) { + struct wlr_pixman_buffer *buffer; + wl_list_for_each(buffer, &renderer->buffers, link) { + if (buffer->buffer == wlr_buffer) { + return buffer; + } + } + return NULL; +} + +static const struct wlr_texture_impl texture_impl; + +bool wlr_texture_is_pixman(struct wlr_texture *texture) { + return texture->impl == &texture_impl; +} + +static struct wlr_pixman_texture *get_texture( + struct wlr_texture *wlr_texture) { + assert(wlr_texture_is_pixman(wlr_texture)); + struct wlr_pixman_texture *texture = wl_container_of(wlr_texture, texture, wlr_texture); + return texture; +} + +static void texture_destroy(struct wlr_texture *wlr_texture) { + struct wlr_pixman_texture *texture = get_texture(wlr_texture); + wl_list_remove(&texture->link); + pixman_image_unref(texture->image); + wlr_buffer_unlock(texture->buffer); + free(texture->data); + free(texture); +} + +static bool texture_read_pixels(struct wlr_texture *wlr_texture, + const struct wlr_texture_read_pixels_options *options) { + struct wlr_pixman_texture *texture = get_texture(wlr_texture); + + struct wlr_box src; + wlr_texture_read_pixels_options_get_src_box(options, wlr_texture, &src); + + pixman_format_code_t fmt = get_pixman_format_from_drm(options->format); + if (fmt == 0) { + wlr_log(WLR_ERROR, "Cannot read pixels: unsupported pixel format"); + return false; + } + + void *p = wlr_texture_read_pixel_options_get_data(options); + + pixman_image_t *dst = pixman_image_create_bits_no_clear(fmt, + src.width, src.height, p, options->stride); + + pixman_image_composite32(PIXMAN_OP_SRC, texture->image, NULL, dst, + src.x, src.y, 0, 0, 0, 0, src.width, src.height); + + pixman_image_unref(dst); + + return true; +} + +static uint32_t pixman_texture_preferred_read_format(struct wlr_texture *wlr_texture) { + struct wlr_pixman_texture *texture = get_texture(wlr_texture); + + pixman_format_code_t pixman_format = pixman_image_get_format(texture->image); + return get_drm_format_from_pixman(pixman_format); +} + +static const struct wlr_texture_impl texture_impl = { + .read_pixels = texture_read_pixels, + .preferred_read_format = pixman_texture_preferred_read_format, + .destroy = texture_destroy, +}; + +static void destroy_buffer(struct wlr_pixman_buffer *buffer) { + wl_list_remove(&buffer->link); + wl_list_remove(&buffer->buffer_destroy.link); + + pixman_image_unref(buffer->image); + + free(buffer); +} + +static void handle_destroy_buffer(struct wl_listener *listener, void *data) { + struct wlr_pixman_buffer *buffer = + wl_container_of(listener, buffer, buffer_destroy); + destroy_buffer(buffer); +} + +static struct wlr_pixman_buffer *create_buffer( + struct wlr_pixman_renderer *renderer, struct wlr_buffer *wlr_buffer) { + struct wlr_pixman_buffer *buffer = calloc(1, sizeof(*buffer)); + if (buffer == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + buffer->buffer = wlr_buffer; + buffer->renderer = renderer; + + void *data = NULL; + uint32_t drm_format; + size_t stride; + if (!wlr_buffer_begin_data_ptr_access(wlr_buffer, + WLR_BUFFER_DATA_PTR_ACCESS_READ | WLR_BUFFER_DATA_PTR_ACCESS_WRITE, + &data, &drm_format, &stride)) { + wlr_log(WLR_ERROR, "Failed to get buffer data"); + goto error_buffer; + } + wlr_buffer_end_data_ptr_access(wlr_buffer); + + pixman_format_code_t format = get_pixman_format_from_drm(drm_format); + if (format == 0) { + wlr_log(WLR_ERROR, "Unsupported pixman drm format 0x%"PRIX32, + drm_format); + goto error_buffer; + } + + buffer->image = pixman_image_create_bits(format, wlr_buffer->width, + wlr_buffer->height, data, stride); + if (!buffer->image) { + wlr_log(WLR_ERROR, "Failed to allocate pixman image"); + goto error_buffer; + } + + buffer->buffer_destroy.notify = handle_destroy_buffer; + wl_signal_add(&wlr_buffer->events.destroy, &buffer->buffer_destroy); + + wl_list_insert(&renderer->buffers, &buffer->link); + + wlr_log(WLR_DEBUG, "Created pixman buffer %dx%d", + wlr_buffer->width, wlr_buffer->height); + + return buffer; + +error_buffer: + free(buffer); + return NULL; +} + +static const struct wlr_drm_format_set *pixman_get_texture_formats( + struct wlr_renderer *wlr_renderer, uint32_t buffer_caps) { + struct wlr_pixman_renderer *renderer = get_renderer(wlr_renderer); + if (buffer_caps & WLR_BUFFER_CAP_DATA_PTR) { + return &renderer->drm_formats; + } else { + return NULL; + } +} + +static const struct wlr_drm_format_set *pixman_get_render_formats( + struct wlr_renderer *wlr_renderer) { + struct wlr_pixman_renderer *renderer = get_renderer(wlr_renderer); + return &renderer->drm_formats; +} + +static struct wlr_pixman_texture *pixman_texture_create( + struct wlr_pixman_renderer *renderer, uint32_t drm_format, + uint32_t width, uint32_t height) { + struct wlr_pixman_texture *texture = calloc(1, sizeof(*texture)); + if (texture == NULL) { + wlr_log_errno(WLR_ERROR, "Failed to allocate pixman texture"); + return NULL; + } + + wlr_texture_init(&texture->wlr_texture, &renderer->wlr_renderer, + &texture_impl, width, height); + + texture->format_info = drm_get_pixel_format_info(drm_format); + if (!texture->format_info) { + wlr_log(WLR_ERROR, "Unsupported drm format 0x%"PRIX32, drm_format); + free(texture); + return NULL; + } + + texture->format = get_pixman_format_from_drm(drm_format); + if (texture->format == 0) { + wlr_log(WLR_ERROR, "Unsupported pixman drm format 0x%"PRIX32, + drm_format); + free(texture); + return NULL; + } + + wl_list_insert(&renderer->textures, &texture->link); + + return texture; +} + +static struct wlr_texture *pixman_texture_from_buffer( + struct wlr_renderer *wlr_renderer, struct wlr_buffer *buffer) { + struct wlr_pixman_renderer *renderer = get_renderer(wlr_renderer); + + void *data = NULL; + uint32_t drm_format; + size_t stride; + if (!wlr_buffer_begin_data_ptr_access(buffer, WLR_BUFFER_DATA_PTR_ACCESS_READ, + &data, &drm_format, &stride)) { + return NULL; + } + wlr_buffer_end_data_ptr_access(buffer); + + struct wlr_pixman_texture *texture = pixman_texture_create(renderer, + drm_format, buffer->width, buffer->height); + if (texture == NULL) { + return NULL; + } + + texture->image = pixman_image_create_bits_no_clear(texture->format, + buffer->width, buffer->height, data, stride); + if (!texture->image) { + wlr_log(WLR_ERROR, "Failed to create pixman image"); + wl_list_remove(&texture->link); + free(texture); + return NULL; + } + + texture->buffer = wlr_buffer_lock(buffer); + + return &texture->wlr_texture; +} + +static void pixman_destroy(struct wlr_renderer *wlr_renderer) { + struct wlr_pixman_renderer *renderer = get_renderer(wlr_renderer); + + struct wlr_pixman_buffer *buffer, *buffer_tmp; + wl_list_for_each_safe(buffer, buffer_tmp, &renderer->buffers, link) { + destroy_buffer(buffer); + } + + struct wlr_pixman_texture *tex, *tex_tmp; + wl_list_for_each_safe(tex, tex_tmp, &renderer->textures, link) { + wlr_texture_destroy(&tex->wlr_texture); + } + + wlr_drm_format_set_finish(&renderer->drm_formats); + + free(renderer); +} + +static struct wlr_render_pass *pixman_begin_buffer_pass(struct wlr_renderer *wlr_renderer, + struct wlr_buffer *wlr_buffer, const struct wlr_buffer_pass_options *options) { + struct wlr_pixman_renderer *renderer = get_renderer(wlr_renderer); + + struct wlr_pixman_buffer *buffer = get_buffer(renderer, wlr_buffer); + if (buffer == NULL) { + buffer = create_buffer(renderer, wlr_buffer); + } + if (buffer == NULL) { + return NULL; + } + + struct wlr_pixman_render_pass *pass = begin_pixman_render_pass(buffer); + if (pass == NULL) { + return NULL; + } + return &pass->base; +} + +static const struct wlr_renderer_impl renderer_impl = { + .get_texture_formats = pixman_get_texture_formats, + .get_render_formats = pixman_get_render_formats, + .texture_from_buffer = pixman_texture_from_buffer, + .destroy = pixman_destroy, + .begin_buffer_pass = pixman_begin_buffer_pass, +}; + +struct wlr_renderer *wlr_pixman_renderer_create(void) { + struct wlr_pixman_renderer *renderer = calloc(1, sizeof(*renderer)); + if (renderer == NULL) { + return NULL; + } + + wlr_log(WLR_INFO, "Creating pixman renderer"); + wlr_renderer_init(&renderer->wlr_renderer, &renderer_impl, WLR_BUFFER_CAP_DATA_PTR); + renderer->wlr_renderer.features.output_color_transform = false; + wl_list_init(&renderer->buffers); + wl_list_init(&renderer->textures); + + size_t len = 0; + const uint32_t *formats = get_pixman_drm_formats(&len); + + for (size_t i = 0; i < len; ++i) { + wlr_drm_format_set_add(&renderer->drm_formats, formats[i], + DRM_FORMAT_MOD_INVALID); + wlr_drm_format_set_add(&renderer->drm_formats, formats[i], + DRM_FORMAT_MOD_LINEAR); + } + + return &renderer->wlr_renderer; +} + +pixman_image_t *wlr_pixman_renderer_get_buffer_image( + struct wlr_renderer *wlr_renderer, struct wlr_buffer *wlr_buffer) { + struct wlr_pixman_renderer *renderer = get_renderer(wlr_renderer); + struct wlr_pixman_buffer *buffer = get_buffer(renderer, wlr_buffer); + if (!buffer) { + buffer = create_buffer(renderer, wlr_buffer); + } + if (!buffer) { + return NULL; + } + return buffer->image; +} + +pixman_image_t *wlr_pixman_texture_get_image(struct wlr_texture *wlr_texture) { + struct wlr_pixman_texture *texture = get_texture(wlr_texture); + return texture->image; +} diff --git a/3rdparty/wlroots/render/swapchain.c b/3rdparty/wlroots/render/swapchain.c new file mode 100644 index 0000000000..24d6f1a875 --- /dev/null +++ b/3rdparty/wlroots/render/swapchain.c @@ -0,0 +1,122 @@ +#include +#include +#include +#include +#include +#include +#include "render/drm_format_set.h" + +static void swapchain_handle_allocator_destroy(struct wl_listener *listener, + void *data) { + struct wlr_swapchain *swapchain = + wl_container_of(listener, swapchain, allocator_destroy); + swapchain->allocator = NULL; + wl_list_remove(&swapchain->allocator_destroy.link); + wl_list_init(&swapchain->allocator_destroy.link); +} + +struct wlr_swapchain *wlr_swapchain_create( + struct wlr_allocator *alloc, int width, int height, + const struct wlr_drm_format *format) { + assert(width > 0 && height > 0); + + struct wlr_swapchain *swapchain = calloc(1, sizeof(*swapchain)); + if (swapchain == NULL) { + return NULL; + } + swapchain->allocator = alloc; + swapchain->width = width; + swapchain->height = height; + + if (!wlr_drm_format_copy(&swapchain->format, format)) { + free(swapchain); + return NULL; + } + + swapchain->allocator_destroy.notify = swapchain_handle_allocator_destroy; + wl_signal_add(&alloc->events.destroy, &swapchain->allocator_destroy); + + return swapchain; +} + +static void slot_reset(struct wlr_swapchain_slot *slot) { + if (slot->acquired) { + wl_list_remove(&slot->release.link); + } + wlr_buffer_drop(slot->buffer); + *slot = (struct wlr_swapchain_slot){0}; +} + +void wlr_swapchain_destroy(struct wlr_swapchain *swapchain) { + if (swapchain == NULL) { + return; + } + for (size_t i = 0; i < WLR_SWAPCHAIN_CAP; i++) { + slot_reset(&swapchain->slots[i]); + } + wl_list_remove(&swapchain->allocator_destroy.link); + wlr_drm_format_finish(&swapchain->format); + free(swapchain); +} + +static void slot_handle_release(struct wl_listener *listener, void *data) { + struct wlr_swapchain_slot *slot = + wl_container_of(listener, slot, release); + wl_list_remove(&slot->release.link); + slot->acquired = false; +} + +static struct wlr_buffer *slot_acquire(struct wlr_swapchain *swapchain, + struct wlr_swapchain_slot *slot) { + assert(!slot->acquired); + assert(slot->buffer != NULL); + + slot->acquired = true; + + slot->release.notify = slot_handle_release; + wl_signal_add(&slot->buffer->events.release, &slot->release); + + return wlr_buffer_lock(slot->buffer); +} + +struct wlr_buffer *wlr_swapchain_acquire(struct wlr_swapchain *swapchain) { + struct wlr_swapchain_slot *free_slot = NULL; + for (size_t i = 0; i < WLR_SWAPCHAIN_CAP; i++) { + struct wlr_swapchain_slot *slot = &swapchain->slots[i]; + if (slot->acquired) { + continue; + } + if (slot->buffer != NULL) { + return slot_acquire(swapchain, slot); + } + free_slot = slot; + } + if (free_slot == NULL) { + wlr_log(WLR_ERROR, "No free output buffer slot"); + return NULL; + } + + if (swapchain->allocator == NULL) { + return NULL; + } + + wlr_log(WLR_DEBUG, "Allocating new swapchain buffer"); + free_slot->buffer = wlr_allocator_create_buffer(swapchain->allocator, + swapchain->width, swapchain->height, &swapchain->format); + if (free_slot->buffer == NULL) { + wlr_log(WLR_ERROR, "Failed to allocate buffer"); + return NULL; + } + return slot_acquire(swapchain, free_slot); +} + +bool wlr_swapchain_has_buffer(struct wlr_swapchain *swapchain, + struct wlr_buffer *buffer) { + for (size_t i = 0; i < WLR_SWAPCHAIN_CAP; i++) { + struct wlr_swapchain_slot *slot = &swapchain->slots[i]; + if (slot->buffer == buffer) { + return true; + } + } + return false; +} diff --git a/3rdparty/wlroots/render/vulkan/meson.build b/3rdparty/wlroots/render/vulkan/meson.build new file mode 100644 index 0000000000..36a822f9a4 --- /dev/null +++ b/3rdparty/wlroots/render/vulkan/meson.build @@ -0,0 +1,51 @@ +msg = [] +if 'vulkan' in renderers + msg += 'Install "@0@" or pass "-Dvulkan=disabled" to disable it.' +else + msg += 'Required for vulkan renderer support.' +endif + +dep_vulkan = dependency('vulkan', + version: '>=1.2.182', + required: 'vulkan' in renderers, + not_found_message: '\n'.join(msg).format('vulkan') +) +if not dep_vulkan.found() + subdir_done() +endif + +# Vulkan headers are installed separately from the loader (which ships the +# pkg-config file) +if not cc.check_header('vulkan/vulkan.h', dependencies: dep_vulkan) + if 'vulkan' in renderers + error('\n'.join(msg).format('vulkan-headers')) + else + subdir_done() + endif +endif + +glslang = find_program('glslang', 'glslangValidator', native: true, required: false) +if not glslang.found() + if 'vulkan' in renderers + error('\n'.join(msg).format('glslang')) + else + subdir_done() + endif +endif + +glslang_version_info = run_command(glslang, '--version', check: true).stdout() +glslang_version = glslang_version_info.split('\n')[0].split(':')[-1] + +wlr_files += files( + 'pass.c', + 'renderer.c', + 'texture.c', + 'vulkan.c', + 'util.c', + 'pixel_format.c', +) + +wlr_deps += dep_vulkan +features += { 'vulkan-renderer': true } + +subdir('shaders') diff --git a/3rdparty/wlroots/render/vulkan/pass.c b/3rdparty/wlroots/render/vulkan/pass.c new file mode 100644 index 0000000000..503e37c07f --- /dev/null +++ b/3rdparty/wlroots/render/vulkan/pass.c @@ -0,0 +1,1357 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "render/color.h" +#include "render/vulkan.h" +#include "util/matrix.h" + +static const struct wlr_render_pass_impl render_pass_impl; +static const struct wlr_addon_interface vk_color_transform_impl; + +static struct wlr_vk_render_pass *get_render_pass(struct wlr_render_pass *wlr_pass) { + assert(wlr_pass->impl == &render_pass_impl); + struct wlr_vk_render_pass *pass = wl_container_of(wlr_pass, pass, base); + return pass; +} + +static struct wlr_vk_color_transform *get_color_transform( + struct wlr_color_transform *c, struct wlr_vk_renderer *renderer) { + struct wlr_addon *a = wlr_addon_find(&c->addons, renderer, &vk_color_transform_impl); + if (!a) { + return NULL; + } + struct wlr_vk_color_transform *transform = wl_container_of(a, transform, addon); + return transform; +} + +static void bind_pipeline(struct wlr_vk_render_pass *pass, VkPipeline pipeline) { + if (pipeline == pass->bound_pipeline) { + return; + } + + vkCmdBindPipeline(pass->command_buffer->vk, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); + pass->bound_pipeline = pipeline; +} + +static void get_clip_region(struct wlr_vk_render_pass *pass, + const pixman_region32_t *in, pixman_region32_t *out) { + if (in != NULL) { + pixman_region32_init(out); + pixman_region32_copy(out, in); + } else { + struct wlr_buffer *buffer = pass->render_buffer->wlr_buffer; + pixman_region32_init_rect(out, 0, 0, buffer->width, buffer->height); + } +} + +static void convert_pixman_box_to_vk_rect(const pixman_box32_t *box, VkRect2D *rect) { + *rect = (VkRect2D){ + .offset = { .x = box->x1, .y = box->y1 }, + .extent = { .width = box->x2 - box->x1, .height = box->y2 - box->y1 }, + }; +} + +static float color_to_linear(float non_linear) { + return pow(non_linear, 2.2); +} + +static float color_to_linear_premult(float non_linear, float alpha) { + return (alpha == 0) ? 0 : color_to_linear(non_linear / alpha) * alpha; +} + +static void encode_proj_matrix(const float mat3[9], float mat4[4][4]) { + float result[4][4] = { + { mat3[0], mat3[1], 0, mat3[2] }, + { mat3[3], mat3[4], 0, mat3[5] }, + { 0, 0, 1, 0 }, + { 0, 0, 0, 1 }, + }; + + memcpy(mat4, result, sizeof(result)); +} + +static void encode_color_matrix(const float mat3[9], float mat4[4][4]) { + float result[4][4] = { + { mat3[0], mat3[1], mat3[2], 0 }, + { mat3[3], mat3[4], mat3[5], 0 }, + { mat3[6], mat3[7], mat3[8], 0 }, + { 0, 0, 0, 0 }, + }; + + memcpy(mat4, result, sizeof(result)); +} + +static void render_pass_destroy(struct wlr_vk_render_pass *pass) { + struct wlr_vk_render_pass_texture *pass_texture; + wl_array_for_each(pass_texture, &pass->textures) { + wlr_drm_syncobj_timeline_unref(pass_texture->wait_timeline); + } + + wlr_color_transform_unref(pass->color_transform); + wlr_drm_syncobj_timeline_unref(pass->signal_timeline); + rect_union_finish(&pass->updated_region); + wl_array_release(&pass->textures); + free(pass); +} + +static VkSemaphore render_pass_wait_sync_file(struct wlr_vk_render_pass *pass, + size_t sem_index, int sync_file_fd) { + struct wlr_vk_renderer *renderer = pass->renderer; + struct wlr_vk_command_buffer *render_cb = pass->command_buffer; + VkResult res; + + VkSemaphore *wait_semaphores = render_cb->wait_semaphores.data; + size_t wait_semaphores_len = render_cb->wait_semaphores.size / sizeof(wait_semaphores[0]); + + VkSemaphore *sem_ptr; + if (sem_index >= wait_semaphores_len) { + sem_ptr = wl_array_add(&render_cb->wait_semaphores, sizeof(*sem_ptr)); + if (sem_ptr == NULL) { + return VK_NULL_HANDLE; + } + *sem_ptr = VK_NULL_HANDLE; + } else { + sem_ptr = &wait_semaphores[sem_index]; + } + + if (*sem_ptr == VK_NULL_HANDLE) { + VkSemaphoreCreateInfo semaphore_info = { + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, + }; + res = vkCreateSemaphore(renderer->dev->dev, &semaphore_info, NULL, sem_ptr); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateSemaphore", res); + return VK_NULL_HANDLE; + } + } + + VkImportSemaphoreFdInfoKHR import_info = { + .sType = VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR, + .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT, + .flags = VK_SEMAPHORE_IMPORT_TEMPORARY_BIT, + .semaphore = *sem_ptr, + .fd = sync_file_fd, + }; + res = renderer->dev->api.vkImportSemaphoreFdKHR(renderer->dev->dev, &import_info); + if (res != VK_SUCCESS) { + wlr_vk_error("vkImportSemaphoreFdKHR", res); + return VK_NULL_HANDLE; + } + + return *sem_ptr; +} + +static bool render_pass_wait_render_buffer(struct wlr_vk_render_pass *pass, + VkSemaphoreSubmitInfoKHR *render_wait, uint32_t *render_wait_len_ptr) { + int sync_file_fds[WLR_DMABUF_MAX_PLANES]; + for (size_t i = 0; i < WLR_DMABUF_MAX_PLANES; i++) { + sync_file_fds[i] = -1; + } + + if (!vulkan_sync_render_buffer_acquire(pass->render_buffer, sync_file_fds)) { + return false; + } + + for (size_t i = 0; i < WLR_DMABUF_MAX_PLANES; i++) { + if (sync_file_fds[i] < 0) { + continue; + } + + VkSemaphore sem = render_pass_wait_sync_file(pass, *render_wait_len_ptr, sync_file_fds[i]); + if (sem == VK_NULL_HANDLE) { + close(sync_file_fds[i]); + continue; + } + + render_wait[*render_wait_len_ptr] = (VkSemaphoreSubmitInfoKHR){ + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO_KHR, + .semaphore = sem, + .stageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR, + }; + + (*render_wait_len_ptr)++; + } + + return true; +} + +static bool unwrap_color_transform(struct wlr_color_transform *transform, + float matrix[static 9], enum wlr_color_transfer_function *tf) { + if (transform == NULL) { + wlr_matrix_identity(matrix); + *tf = WLR_COLOR_TRANSFER_FUNCTION_GAMMA22; + return true; + } + struct wlr_color_transform_inverse_eotf *eotf; + struct wlr_color_transform_matrix *as_matrix; + struct wlr_color_transform_pipeline *pipeline; + switch (transform->type) { + case COLOR_TRANSFORM_INVERSE_EOTF: + eotf = wlr_color_transform_inverse_eotf_from_base(transform); + wlr_matrix_identity(matrix); + *tf = eotf->tf; + return true; + case COLOR_TRANSFORM_MATRIX: + as_matrix = wl_container_of(transform, as_matrix, base); + memcpy(matrix, as_matrix->matrix, sizeof(float[9])); + *tf = WLR_COLOR_TRANSFER_FUNCTION_EXT_LINEAR; + return true; + case COLOR_TRANSFORM_PIPELINE: + pipeline = wl_container_of(transform, pipeline, base); + if (pipeline->len != 2 + || pipeline->transforms[0]->type != COLOR_TRANSFORM_MATRIX + || pipeline->transforms[1]->type != COLOR_TRANSFORM_INVERSE_EOTF) { + return false; + } + as_matrix = wl_container_of(pipeline->transforms[0], as_matrix, base); + eotf = wlr_color_transform_inverse_eotf_from_base(pipeline->transforms[1]); + memcpy(matrix, as_matrix->matrix, sizeof(float[9])); + *tf = eotf->tf; + return true; + case COLOR_TRANSFORM_LCMS2: + case COLOR_TRANSFORM_LUT_3X1D: + return false; + } + return false; +} + +static bool render_pass_submit(struct wlr_render_pass *wlr_pass) { + struct wlr_vk_render_pass *pass = get_render_pass(wlr_pass); + struct wlr_vk_renderer *renderer = pass->renderer; + struct wlr_vk_command_buffer *render_cb = pass->command_buffer; + struct wlr_vk_render_buffer *render_buffer = pass->render_buffer; + struct wlr_vk_command_buffer *stage_cb = NULL; + VkSemaphoreSubmitInfoKHR *render_wait = NULL; + bool device_lost = false; + + if (pass->failed) { + goto error; + } + + if (vulkan_record_stage_cb(renderer) == VK_NULL_HANDLE) { + goto error; + } + + stage_cb = renderer->stage.cb; + assert(stage_cb != NULL); + renderer->stage.cb = NULL; + + if (pass->two_pass) { + // Apply output shader to map blend image to actual output image + vkCmdNextSubpass(render_cb->vk, VK_SUBPASS_CONTENTS_INLINE); + + int width = pass->render_buffer->wlr_buffer->width; + int height = pass->render_buffer->wlr_buffer->height; + + float final_matrix[9] = { + width, 0, -1, + 0, height, -1, + 0, 0, 0, + }; + struct wlr_vk_vert_pcr_data vert_pcr_data = { + .uv_off = { 0, 0 }, + .uv_size = { 1, 1 }, + }; + encode_proj_matrix(final_matrix, vert_pcr_data.mat4); + + float matrix[9]; + enum wlr_color_transfer_function tf = WLR_COLOR_TRANSFER_FUNCTION_GAMMA22; + bool need_lut = false; + size_t dim = 1; + struct wlr_vk_color_transform *transform = NULL; + if (pass->color_transform != NULL) { + transform = get_color_transform(pass->color_transform, renderer); + assert(transform); + need_lut = transform->lut_3d.dim > 0; + dim = need_lut ? transform->lut_3d.dim : 1; + memcpy(matrix, transform->color_matrix, sizeof(matrix)); + tf = transform->inverse_eotf; + } + if (pass->color_transform == NULL || need_lut) { + wlr_matrix_identity(matrix); + } + + struct wlr_vk_frag_output_pcr_data frag_pcr_data = { + .lut_3d_offset = 0.5f / dim, + .lut_3d_scale = (float)(dim - 1) / dim, + }; + + encode_color_matrix(matrix, frag_pcr_data.matrix); + + VkPipeline pipeline = VK_NULL_HANDLE; + if (need_lut) { + pipeline = render_buffer->two_pass.render_setup->output_pipe_lut3d; + } else { + switch (tf) { + case WLR_COLOR_TRANSFER_FUNCTION_EXT_LINEAR: + pipeline = render_buffer->two_pass.render_setup->output_pipe_identity; + break; + case WLR_COLOR_TRANSFER_FUNCTION_SRGB: + pipeline = render_buffer->two_pass.render_setup->output_pipe_srgb; + break; + case WLR_COLOR_TRANSFER_FUNCTION_ST2084_PQ: + pipeline = render_buffer->two_pass.render_setup->output_pipe_pq; + break; + case WLR_COLOR_TRANSFER_FUNCTION_GAMMA22: + pipeline = render_buffer->two_pass.render_setup->output_pipe_gamma22; + break; + case WLR_COLOR_TRANSFER_FUNCTION_BT1886: + pipeline = render_buffer->two_pass.render_setup->output_pipe_bt1886; + break; + } + } + bind_pipeline(pass, pipeline); + vkCmdPushConstants(render_cb->vk, renderer->output_pipe_layout, + VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(vert_pcr_data), &vert_pcr_data); + vkCmdPushConstants(render_cb->vk, renderer->output_pipe_layout, + VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(vert_pcr_data), + sizeof(frag_pcr_data), &frag_pcr_data); + + VkDescriptorSet lut_ds; + if (need_lut) { + lut_ds = transform->lut_3d.ds; + } else { + lut_ds = renderer->output_ds_lut3d_dummy; + } + VkDescriptorSet ds[] = { + render_buffer->two_pass.blend_descriptor_set, // set 0 + lut_ds, // set 1 + }; + size_t ds_len = sizeof(ds) / sizeof(ds[0]); + vkCmdBindDescriptorSets(render_cb->vk, + VK_PIPELINE_BIND_POINT_GRAPHICS, renderer->output_pipe_layout, + 0, ds_len, ds, 0, NULL); + + const pixman_region32_t *clip = rect_union_evaluate(&pass->updated_region); + int clip_rects_len; + const pixman_box32_t *clip_rects = pixman_region32_rectangles( + clip, &clip_rects_len); + for (int i = 0; i < clip_rects_len; i++) { + VkRect2D rect; + convert_pixman_box_to_vk_rect(&clip_rects[i], &rect); + vkCmdSetScissor(render_cb->vk, 0, 1, &rect); + vkCmdDraw(render_cb->vk, 4, 1, 0, 0); + } + } + + vkCmdEndRenderPass(render_cb->vk); + + size_t pass_textures_len = pass->textures.size / sizeof(struct wlr_vk_render_pass_texture); + size_t render_wait_cap = (1 + pass_textures_len) * WLR_DMABUF_MAX_PLANES; + render_wait = calloc(render_wait_cap, sizeof(*render_wait)); + if (render_wait == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + goto error; + } + + uint32_t barrier_count = wl_list_length(&renderer->foreign_textures) + 1; + VkImageMemoryBarrier *acquire_barriers = calloc(barrier_count, sizeof(*acquire_barriers)); + VkImageMemoryBarrier *release_barriers = calloc(barrier_count, sizeof(*release_barriers)); + if (acquire_barriers == NULL || release_barriers == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + free(acquire_barriers); + free(release_barriers); + goto error; + } + + struct wlr_vk_texture *texture, *tmp_tex; + size_t idx = 0; + wl_list_for_each_safe(texture, tmp_tex, &renderer->foreign_textures, foreign_link) { + if (!texture->transitioned) { + texture->transitioned = true; + } + + // acquire + acquire_barriers[idx] = (VkImageMemoryBarrier){ + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, + .dstQueueFamilyIndex = renderer->dev->queue_family, + .image = texture->image, + .oldLayout = VK_IMAGE_LAYOUT_GENERAL, + .newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + .srcAccessMask = 0, // ignored anyways + .dstAccessMask = VK_ACCESS_SHADER_READ_BIT, + .subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .subresourceRange.layerCount = 1, + .subresourceRange.levelCount = 1, + }; + + // release + release_barriers[idx] = (VkImageMemoryBarrier){ + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .srcQueueFamilyIndex = renderer->dev->queue_family, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, + .image = texture->image, + .oldLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .srcAccessMask = VK_ACCESS_SHADER_READ_BIT, + .dstAccessMask = 0, // ignored anyways + .subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .subresourceRange.layerCount = 1, + .subresourceRange.levelCount = 1, + }; + + ++idx; + + wl_list_remove(&texture->foreign_link); + texture->owned = false; + } + + uint32_t render_wait_len = 0; + struct wlr_vk_render_pass_texture *pass_texture; + wl_array_for_each(pass_texture, &pass->textures) { + int sync_file_fds[WLR_DMABUF_MAX_PLANES]; + for (size_t i = 0; i < WLR_DMABUF_MAX_PLANES; i++) { + sync_file_fds[i] = -1; + } + + if (pass_texture->wait_timeline) { + int sync_file_fd = wlr_drm_syncobj_timeline_export_sync_file(pass_texture->wait_timeline, pass_texture->wait_point); + if (sync_file_fd < 0) { + wlr_log(WLR_ERROR, "Failed to export wait timeline point as sync_file"); + continue; + } + + sync_file_fds[0] = sync_file_fd; + } else { + struct wlr_vk_texture *texture = pass_texture->texture; + if (!vulkan_sync_foreign_texture_acquire(texture, sync_file_fds)) { + wlr_log(WLR_ERROR, "Failed to wait for foreign texture DMA-BUF fence"); + continue; + } + } + + for (size_t i = 0; i < WLR_DMABUF_MAX_PLANES; i++) { + if (sync_file_fds[i] < 0) { + continue; + } + + VkSemaphore sem = render_pass_wait_sync_file(pass, render_wait_len, sync_file_fds[i]); + if (sem == VK_NULL_HANDLE) { + close(sync_file_fds[i]); + continue; + } + + render_wait[render_wait_len] = (VkSemaphoreSubmitInfoKHR){ + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO_KHR, + .semaphore = sem, + .stageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR, + }; + + render_wait_len++; + } + } + + if (!render_pass_wait_render_buffer(pass, render_wait, &render_wait_len)) { + wlr_log(WLR_ERROR, "Failed to wait for render buffer DMA-BUF fence"); + } + + // also add acquire/release barriers for the current render buffer + VkImageLayout src_layout = VK_IMAGE_LAYOUT_GENERAL; + if (!pass->render_buffer_out->transitioned) { + src_layout = VK_IMAGE_LAYOUT_PREINITIALIZED; + pass->render_buffer_out->transitioned = true; + } + + if (pass->two_pass) { + // The render pass changes the blend image layout from + // color attachment to read only, so on each frame, before + // the render pass starts, we change it back + VkImageLayout blend_src_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + if (!render_buffer->two_pass.blend_transitioned) { + blend_src_layout = VK_IMAGE_LAYOUT_UNDEFINED; + render_buffer->two_pass.blend_transitioned = true; + } + + VkImageMemoryBarrier blend_acq_barrier = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .image = render_buffer->two_pass.blend_image, + .oldLayout = blend_src_layout, + .newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .srcAccessMask = VK_ACCESS_SHADER_READ_BIT, + .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .subresourceRange = { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .layerCount = 1, + .levelCount = 1, + }, + }; + vkCmdPipelineBarrier(stage_cb->vk, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + 0, 0, NULL, 0, NULL, 1, &blend_acq_barrier); + } + + // acquire render buffer before rendering + acquire_barriers[idx] = (VkImageMemoryBarrier){ + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, + .dstQueueFamilyIndex = renderer->dev->queue_family, + .image = render_buffer->image, + .oldLayout = src_layout, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .srcAccessMask = 0, // ignored anyways + .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .subresourceRange.layerCount = 1, + .subresourceRange.levelCount = 1, + }; + + // release render buffer after rendering + release_barriers[idx] = (VkImageMemoryBarrier){ + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .srcQueueFamilyIndex = renderer->dev->queue_family, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, + .image = render_buffer->image, + .oldLayout = VK_IMAGE_LAYOUT_GENERAL, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dstAccessMask = 0, // ignored anyways + .subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .subresourceRange.layerCount = 1, + .subresourceRange.levelCount = 1, + }; + + ++idx; + + vkCmdPipelineBarrier(stage_cb->vk, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + 0, 0, NULL, 0, NULL, barrier_count, acquire_barriers); + + vkCmdPipelineBarrier(render_cb->vk, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, + barrier_count, release_barriers); + + free(acquire_barriers); + free(release_barriers); + + // No semaphores needed here. + // We don't need a semaphore from the stage/transfer submission + // to the render submissions since they are on the same queue + // and we have a renderpass dependency for that. + uint64_t stage_timeline_point = vulkan_end_command_buffer(stage_cb, renderer); + if (stage_timeline_point == 0) { + goto error; + } + + VkCommandBufferSubmitInfoKHR stage_cb_info = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO_KHR, + .commandBuffer = stage_cb->vk, + }; + VkSemaphoreSubmitInfoKHR stage_signal = { + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO_KHR, + .semaphore = renderer->timeline_semaphore, + .value = stage_timeline_point, + }; + VkSubmitInfo2KHR stage_submit = { + .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO_2_KHR, + .commandBufferInfoCount = 1, + .pCommandBufferInfos = &stage_cb_info, + .signalSemaphoreInfoCount = 1, + .pSignalSemaphoreInfos = &stage_signal, + }; + + VkSemaphoreSubmitInfoKHR stage_wait; + if (renderer->stage.last_timeline_point > 0) { + stage_wait = (VkSemaphoreSubmitInfoKHR){ + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO_KHR, + .semaphore = renderer->timeline_semaphore, + .value = renderer->stage.last_timeline_point, + .stageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR, + }; + + stage_submit.waitSemaphoreInfoCount = 1; + stage_submit.pWaitSemaphoreInfos = &stage_wait; + } + + renderer->stage.last_timeline_point = stage_timeline_point; + + uint64_t render_timeline_point = vulkan_end_command_buffer(render_cb, renderer); + if (render_timeline_point == 0) { + goto error; + } + + uint32_t render_signal_len = 1; + VkSemaphoreSubmitInfoKHR render_signal[2] = {0}; + render_signal[0] = (VkSemaphoreSubmitInfoKHR){ + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO_KHR, + .semaphore = renderer->timeline_semaphore, + .value = render_timeline_point, + }; + if (renderer->dev->implicit_sync_interop || pass->signal_timeline != NULL) { + if (render_cb->binary_semaphore == VK_NULL_HANDLE) { + VkExportSemaphoreCreateInfo export_info = { + .sType = VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO, + .handleTypes = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT, + }; + VkSemaphoreCreateInfo semaphore_info = { + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, + .pNext = &export_info, + }; + VkResult res = vkCreateSemaphore(renderer->dev->dev, &semaphore_info, + NULL, &render_cb->binary_semaphore); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateSemaphore", res); + goto error; + } + } + + render_signal[render_signal_len++] = (VkSemaphoreSubmitInfoKHR){ + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO_KHR, + .semaphore = render_cb->binary_semaphore, + }; + } + + VkCommandBufferSubmitInfoKHR render_cb_info = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO_KHR, + .commandBuffer = render_cb->vk, + }; + VkSubmitInfo2KHR render_submit = { + .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO_2_KHR, + .waitSemaphoreInfoCount = render_wait_len, + .pWaitSemaphoreInfos = render_wait, + .commandBufferInfoCount = 1, + .pCommandBufferInfos = &render_cb_info, + .signalSemaphoreInfoCount = render_signal_len, + .pSignalSemaphoreInfos = render_signal, + }; + + VkSubmitInfo2KHR submit_info[] = { stage_submit, render_submit }; + VkResult res = renderer->dev->api.vkQueueSubmit2KHR(renderer->dev->queue, 2, submit_info, VK_NULL_HANDLE); + + if (res != VK_SUCCESS) { + device_lost = res == VK_ERROR_DEVICE_LOST; + wlr_vk_error("vkQueueSubmit", res); + goto error; + } + + free(render_wait); + + struct wlr_vk_shared_buffer *stage_buf, *stage_buf_tmp; + wl_list_for_each_safe(stage_buf, stage_buf_tmp, &renderer->stage.buffers, link) { + if (stage_buf->allocs.size == 0) { + continue; + } + wl_list_remove(&stage_buf->link); + wl_list_insert(&stage_cb->stage_buffers, &stage_buf->link); + } + + if (!vulkan_sync_render_pass_release(renderer, pass)) { + wlr_log(WLR_ERROR, "Failed to sync render buffer"); + } + + render_pass_destroy(pass); + wlr_buffer_unlock(render_buffer->wlr_buffer); + return true; + +error: + free(render_wait); + vulkan_reset_command_buffer(stage_cb); + vulkan_reset_command_buffer(render_cb); + wlr_buffer_unlock(render_buffer->wlr_buffer); + render_pass_destroy(pass); + + if (device_lost) { + wl_signal_emit_mutable(&renderer->wlr_renderer.events.lost, NULL); + } + + return false; +} + +static void render_pass_mark_box_updated(struct wlr_vk_render_pass *pass, + const struct wlr_box *box) { + if (!pass->two_pass) { + return; + } + + pixman_box32_t pixman_box = { + .x1 = box->x, + .x2 = box->x + box->width, + .y1 = box->y, + .y2 = box->y + box->height, + }; + rect_union_add(&pass->updated_region, pixman_box); +} + +static void render_pass_add_rect(struct wlr_render_pass *wlr_pass, + const struct wlr_render_rect_options *options) { + struct wlr_vk_render_pass *pass = get_render_pass(wlr_pass); + VkCommandBuffer cb = pass->command_buffer->vk; + + // Input color values are given in sRGB space, shader expects + // them in linear space. The shader does all computation in linear + // space and expects in inputs in linear space since it outputs + // colors in linear space as well (and vulkan then automatically + // does the conversion for out sRGB render targets). + float linear_color[] = { + color_to_linear_premult(options->color.r, options->color.a), + color_to_linear_premult(options->color.g, options->color.a), + color_to_linear_premult(options->color.b, options->color.a), + options->color.a, // no conversion for alpha + }; + + pixman_region32_t clip; + get_clip_region(pass, options->clip, &clip); + + int clip_rects_len; + const pixman_box32_t *clip_rects = pixman_region32_rectangles(&clip, &clip_rects_len); + // Record regions possibly updated for use in second subpass + for (int i = 0; i < clip_rects_len; i++) { + struct wlr_box clip_box = { + .x = clip_rects[i].x1, + .y = clip_rects[i].y1, + .width = clip_rects[i].x2 - clip_rects[i].x1, + .height = clip_rects[i].y2 - clip_rects[i].y1, + }; + struct wlr_box intersection; + if (!wlr_box_intersection(&intersection, &options->box, &clip_box)) { + continue; + } + render_pass_mark_box_updated(pass, &intersection); + } + + struct wlr_box box; + wlr_render_rect_options_get_box(options, pass->render_buffer->wlr_buffer, &box); + + switch (options->blend_mode) { + case WLR_RENDER_BLEND_MODE_PREMULTIPLIED:; + float proj[9], matrix[9]; + wlr_matrix_identity(proj); + wlr_matrix_project_box(matrix, &box, WL_OUTPUT_TRANSFORM_NORMAL, proj); + wlr_matrix_multiply(matrix, pass->projection, matrix); + + struct wlr_vk_pipeline *pipe = setup_get_or_create_pipeline( + pass->render_setup, + &(struct wlr_vk_pipeline_key) { + .source = WLR_VK_SHADER_SOURCE_SINGLE_COLOR, + .layout = {0}, + }); + if (!pipe) { + pass->failed = true; + break; + } + + struct wlr_vk_vert_pcr_data vert_pcr_data = { + .uv_off = { 0, 0 }, + .uv_size = { 1, 1 }, + }; + encode_proj_matrix(matrix, vert_pcr_data.mat4); + + bind_pipeline(pass, pipe->vk); + vkCmdPushConstants(cb, pipe->layout->vk, + VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(vert_pcr_data), &vert_pcr_data); + vkCmdPushConstants(cb, pipe->layout->vk, + VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(vert_pcr_data), sizeof(float) * 4, + linear_color); + + for (int i = 0; i < clip_rects_len; i++) { + VkRect2D rect; + convert_pixman_box_to_vk_rect(&clip_rects[i], &rect); + vkCmdSetScissor(cb, 0, 1, &rect); + vkCmdDraw(cb, 4, 1, 0, 0); + } + break; + case WLR_RENDER_BLEND_MODE_NONE:; + VkClearAttachment clear_att = { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .colorAttachment = 0, + .clearValue.color.float32 = { + linear_color[0], + linear_color[1], + linear_color[2], + linear_color[3], + }, + }; + VkClearRect clear_rect = { + .layerCount = 1, + }; + for (int i = 0; i < clip_rects_len; i++) { + convert_pixman_box_to_vk_rect(&clip_rects[i], &clear_rect.rect); + vkCmdClearAttachments(cb, 1, &clear_att, 1, &clear_rect); + } + break; + } + + pixman_region32_fini(&clip); +} + +static void render_pass_add_texture(struct wlr_render_pass *wlr_pass, + const struct wlr_render_texture_options *options) { + struct wlr_vk_render_pass *pass = get_render_pass(wlr_pass); + struct wlr_vk_renderer *renderer = pass->renderer; + VkCommandBuffer cb = pass->command_buffer->vk; + + struct wlr_vk_texture *texture = vulkan_get_texture(options->texture); + assert(texture->renderer == renderer); + + if (texture->dmabuf_imported && !texture->owned) { + // Store this texture in the list of textures that need to be + // acquired before rendering and released after rendering. + // We don't do it here immediately since barriers inside + // a renderpass are suboptimal (would require additional renderpass + // dependency and potentially multiple barriers) and it's + // better to issue one barrier for all used textures anyways. + texture->owned = true; + assert(texture->foreign_link.prev == NULL); + assert(texture->foreign_link.next == NULL); + wl_list_insert(&renderer->foreign_textures, &texture->foreign_link); + } + + struct wlr_fbox src_box; + wlr_render_texture_options_get_src_box(options, &src_box); + struct wlr_box dst_box; + wlr_render_texture_options_get_dst_box(options, &dst_box); + float alpha = wlr_render_texture_options_get_alpha(options); + + float proj[9], matrix[9]; + wlr_matrix_identity(proj); + wlr_matrix_project_box(matrix, &dst_box, options->transform, proj); + wlr_matrix_multiply(matrix, pass->projection, matrix); + + struct wlr_vk_vert_pcr_data vert_pcr_data = { + .uv_off = { + src_box.x / options->texture->width, + src_box.y / options->texture->height, + }, + .uv_size = { + src_box.width / options->texture->width, + src_box.height / options->texture->height, + }, + }; + encode_proj_matrix(matrix, vert_pcr_data.mat4); + + enum wlr_color_transfer_function tf = options->transfer_function; + if (tf == 0) { + tf = WLR_COLOR_TRANSFER_FUNCTION_GAMMA22; + } + + bool srgb_image_view = false; + enum wlr_vk_texture_transform tex_transform = 0; + switch (tf) { + case WLR_COLOR_TRANSFER_FUNCTION_SRGB: + if (texture->using_mutable_srgb) { + tex_transform = WLR_VK_TEXTURE_TRANSFORM_IDENTITY; + srgb_image_view = true; + } else { + tex_transform = WLR_VK_TEXTURE_TRANSFORM_SRGB; + } + break; + case WLR_COLOR_TRANSFER_FUNCTION_EXT_LINEAR: + tex_transform = WLR_VK_TEXTURE_TRANSFORM_IDENTITY; + break; + case WLR_COLOR_TRANSFER_FUNCTION_ST2084_PQ: + tex_transform = WLR_VK_TEXTURE_TRANSFORM_ST2084_PQ; + break; + case WLR_COLOR_TRANSFER_FUNCTION_GAMMA22: + tex_transform = WLR_VK_TEXTURE_TRANSFORM_GAMMA22; + break; + case WLR_COLOR_TRANSFER_FUNCTION_BT1886: + tex_transform = WLR_VK_TEXTURE_TRANSFORM_BT1886; + break; + } + + enum wlr_color_encoding color_encoding = options->color_encoding; + bool is_ycbcr = vulkan_format_is_ycbcr(texture->format); + if (is_ycbcr && color_encoding == WLR_COLOR_ENCODING_NONE) { + color_encoding = WLR_COLOR_ENCODING_BT601; + } + + enum wlr_color_range color_range = options->color_range; + if (is_ycbcr && color_range == WLR_COLOR_RANGE_NONE) { + color_range = WLR_COLOR_RANGE_LIMITED; + } + + struct wlr_vk_pipeline *pipe = setup_get_or_create_pipeline( + pass->render_setup, + &(struct wlr_vk_pipeline_key) { + .source = WLR_VK_SHADER_SOURCE_TEXTURE, + .layout = { + .ycbcr = { + .format = is_ycbcr ? texture->format : NULL, + .encoding = color_encoding, + .range = color_range, + }, + .filter_mode = options->filter_mode, + }, + .texture_transform = tex_transform, + .blend_mode = !texture->has_alpha && alpha == 1.0 ? + WLR_RENDER_BLEND_MODE_NONE : options->blend_mode, + }); + if (!pipe) { + pass->failed = true; + return; + } + + struct wlr_vk_texture_view *view = + vulkan_texture_get_or_create_view(texture, pipe->layout, srgb_image_view); + if (!view) { + pass->failed = true; + return; + } + + float color_matrix[9]; + if (options->primaries != NULL) { + struct wlr_color_primaries srgb; + wlr_color_primaries_from_named(&srgb, WLR_COLOR_NAMED_PRIMARIES_SRGB); + + wlr_color_primaries_transform_absolute_colorimetric(options->primaries, + &srgb, color_matrix); + } else { + wlr_matrix_identity(color_matrix); + } + + float luminance_multiplier = 1; + if (options->luminance_multiplier != NULL) { + luminance_multiplier = *options->luminance_multiplier; + } + + struct wlr_vk_frag_texture_pcr_data frag_pcr_data = { + .alpha = alpha, + .luminance_multiplier = luminance_multiplier, + }; + encode_color_matrix(color_matrix, frag_pcr_data.matrix); + + bind_pipeline(pass, pipe->vk); + + vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, + pipe->layout->vk, 0, 1, &view->ds, 0, NULL); + + vkCmdPushConstants(cb, pipe->layout->vk, + VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(vert_pcr_data), &vert_pcr_data); + vkCmdPushConstants(cb, pipe->layout->vk, + VK_SHADER_STAGE_FRAGMENT_BIT, sizeof(vert_pcr_data), + sizeof(frag_pcr_data), &frag_pcr_data); + + pixman_region32_t clip; + get_clip_region(pass, options->clip, &clip); + + int clip_rects_len; + const pixman_box32_t *clip_rects = pixman_region32_rectangles(&clip, &clip_rects_len); + for (int i = 0; i < clip_rects_len; i++) { + VkRect2D rect; + convert_pixman_box_to_vk_rect(&clip_rects[i], &rect); + vkCmdSetScissor(cb, 0, 1, &rect); + vkCmdDraw(cb, 4, 1, 0, 0); + + struct wlr_box clip_box = { + .x = clip_rects[i].x1, + .y = clip_rects[i].y1, + .width = clip_rects[i].x2 - clip_rects[i].x1, + .height = clip_rects[i].y2 - clip_rects[i].y1, + }; + struct wlr_box intersection; + if (!wlr_box_intersection(&intersection, &dst_box, &clip_box)) { + continue; + } + render_pass_mark_box_updated(pass, &intersection); + } + + texture->last_used_cb = pass->command_buffer; + + pixman_region32_fini(&clip); + + if (texture->dmabuf_imported || (options != NULL && options->wait_timeline != NULL)) { + struct wlr_vk_render_pass_texture *pass_texture = + wl_array_add(&pass->textures, sizeof(*pass_texture)); + if (pass_texture == NULL) { + pass->failed = true; + return; + } + + struct wlr_drm_syncobj_timeline *wait_timeline = NULL; + uint64_t wait_point = 0; + if (options != NULL && options->wait_timeline != NULL) { + wait_timeline = wlr_drm_syncobj_timeline_ref(options->wait_timeline); + wait_point = options->wait_point; + } + + *pass_texture = (struct wlr_vk_render_pass_texture){ + .texture = texture, + .wait_timeline = wait_timeline, + .wait_point = wait_point, + }; + } +} + +static const struct wlr_render_pass_impl render_pass_impl = { + .submit = render_pass_submit, + .add_rect = render_pass_add_rect, + .add_texture = render_pass_add_texture, +}; + + +void vk_color_transform_destroy(struct wlr_addon *addon) { + struct wlr_vk_renderer *renderer = (struct wlr_vk_renderer *)addon->owner; + struct wlr_vk_color_transform *transform = wl_container_of(addon, transform, addon); + + VkDevice dev = renderer->dev->dev; + if (transform->lut_3d.image) { + vkDestroyImage(dev, transform->lut_3d.image, NULL); + vkDestroyImageView(dev, transform->lut_3d.image_view, NULL); + vkFreeMemory(dev, transform->lut_3d.memory, NULL); + vulkan_free_ds(renderer, transform->lut_3d.ds_pool, transform->lut_3d.ds); + } + + wl_list_remove(&transform->link); + wlr_addon_finish(&transform->addon); + free(transform); +} + +static bool create_3d_lut_image(struct wlr_vk_renderer *renderer, + struct wlr_color_transform *tr, size_t dim_len, + VkImage *image, VkImageView *image_view, + VkDeviceMemory *memory, VkDescriptorSet *ds, + struct wlr_vk_descriptor_pool **ds_pool) { + VkDevice dev = renderer->dev->dev; + VkResult res; + + *image = VK_NULL_HANDLE; + *memory = VK_NULL_HANDLE; + *image_view = VK_NULL_HANDLE; + *ds = VK_NULL_HANDLE; + *ds_pool = NULL; + + // R32G32B32 is not a required Vulkan format + // TODO: use it when available + VkFormat format = VK_FORMAT_R32G32B32A32_SFLOAT; + + VkImageCreateInfo img_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, + .imageType = VK_IMAGE_TYPE_3D, + .format = format, + .mipLevels = 1, + .arrayLayers = 1, + .samples = VK_SAMPLE_COUNT_1_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .extent = (VkExtent3D) { dim_len, dim_len, dim_len }, + .tiling = VK_IMAGE_TILING_OPTIMAL, + .usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, + }; + res = vkCreateImage(dev, &img_info, NULL, image); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateImage failed", res); + return NULL; + } + + VkMemoryRequirements mem_reqs = {0}; + vkGetImageMemoryRequirements(dev, *image, &mem_reqs); + + int mem_type_index = vulkan_find_mem_type(renderer->dev, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, mem_reqs.memoryTypeBits); + if (mem_type_index == -1) { + wlr_log(WLR_ERROR, "Failed to find suitable memory type"); + goto fail_image; + } + + VkMemoryAllocateInfo mem_info = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = mem_reqs.size, + .memoryTypeIndex = mem_type_index, + }; + res = vkAllocateMemory(dev, &mem_info, NULL, memory); + if (res != VK_SUCCESS) { + wlr_vk_error("vkAllocateMemory failed", res); + goto fail_image; + } + + res = vkBindImageMemory(dev, *image, *memory, 0); + if (res != VK_SUCCESS) { + wlr_vk_error("vkBindMemory failed", res); + goto fail_memory; + } + + VkImageViewCreateInfo view_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, + .viewType = VK_IMAGE_VIEW_TYPE_3D, + .format = format, + .components.r = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.g = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.b = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.a = VK_COMPONENT_SWIZZLE_IDENTITY, + .subresourceRange = (VkImageSubresourceRange) { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + .image = *image, + }; + res = vkCreateImageView(dev, &view_info, NULL, image_view); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateImageView failed", res); + goto fail_image; + } + + size_t bytes_per_block = 4 * sizeof(float); + size_t size = dim_len * dim_len * dim_len * bytes_per_block; + struct wlr_vk_buffer_span span = vulkan_get_stage_span(renderer, + size, bytes_per_block); + if (!span.buffer || span.alloc.size != size) { + wlr_log(WLR_ERROR, "Failed to retrieve staging buffer"); + goto fail_imageview; + } + + float sample_range = 1.0f / (dim_len - 1); + char *map = (char *)span.buffer->cpu_mapping + span.alloc.start; + float *dst = (float *)map; + for (size_t b_index = 0; b_index < dim_len; b_index++) { + for (size_t g_index = 0; g_index < dim_len; g_index++) { + for (size_t r_index = 0; r_index < dim_len; r_index++) { + size_t sample_index = r_index + dim_len * g_index + dim_len * dim_len * b_index; + size_t dst_offset = 4 * sample_index; + + float rgb_in[3] = { + r_index * sample_range, + g_index * sample_range, + b_index * sample_range, + }; + float rgb_out[3]; + wlr_color_transform_eval(tr, rgb_out, rgb_in); + + dst[dst_offset] = rgb_out[0]; + dst[dst_offset + 1] = rgb_out[1]; + dst[dst_offset + 2] = rgb_out[2]; + dst[dst_offset + 3] = 1.0; + } + } + } + + VkCommandBuffer cb = vulkan_record_stage_cb(renderer); + vulkan_change_layout(cb, *image, + VK_IMAGE_LAYOUT_UNDEFINED, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_WRITE_BIT); + VkBufferImageCopy copy = { + .bufferOffset = span.alloc.start, + .imageExtent.width = dim_len, + .imageExtent.height = dim_len, + .imageExtent.depth = dim_len, + .imageSubresource.layerCount = 1, + .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + }; + vkCmdCopyBufferToImage(cb, span.buffer->buffer, *image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©); + vulkan_change_layout(cb, *image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_WRITE_BIT, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_ACCESS_SHADER_READ_BIT); + + *ds_pool = vulkan_alloc_texture_ds(renderer, + renderer->output_ds_lut3d_layout, ds); + if (!*ds_pool) { + wlr_log(WLR_ERROR, "Failed to allocate descriptor"); + goto fail_imageview; + } + + VkDescriptorImageInfo ds_img_info = { + .imageView = *image_view, + .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + }; + VkWriteDescriptorSet ds_write = { + .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .dstSet = *ds, + .pImageInfo = &ds_img_info, + }; + vkUpdateDescriptorSets(dev, 1, &ds_write, 0, NULL); + + return true; + +fail_imageview: + vkDestroyImageView(dev, *image_view, NULL); +fail_memory: + vkFreeMemory(dev, *memory, NULL); +fail_image: + vkDestroyImage(dev, *image, NULL); + return false; +} + +static struct wlr_vk_color_transform *vk_color_transform_create( + struct wlr_vk_renderer *renderer, struct wlr_color_transform *transform) { + struct wlr_vk_color_transform *vk_transform = + calloc(1, sizeof(*vk_transform)); + if (!vk_transform) { + return NULL; + } + + bool need_lut = !unwrap_color_transform(transform, vk_transform->color_matrix, + &vk_transform->inverse_eotf); + + if (need_lut) { + vk_transform->lut_3d.dim = 33; + if (!create_3d_lut_image(renderer, transform, + vk_transform->lut_3d.dim, + &vk_transform->lut_3d.image, + &vk_transform->lut_3d.image_view, + &vk_transform->lut_3d.memory, + &vk_transform->lut_3d.ds, + &vk_transform->lut_3d.ds_pool)) { + free(vk_transform); + return NULL; + } + } + + wlr_addon_init(&vk_transform->addon, &transform->addons, + renderer, &vk_color_transform_impl); + wl_list_insert(&renderer->color_transforms, &vk_transform->link); + + return vk_transform; +} + + +static const struct wlr_addon_interface vk_color_transform_impl = { + "vk_color_transform", + .destroy = vk_color_transform_destroy, +}; + +struct wlr_vk_render_pass *vulkan_begin_render_pass(struct wlr_vk_renderer *renderer, + struct wlr_vk_render_buffer *buffer, const struct wlr_buffer_pass_options *options) { + uint32_t inv_eotf; + if (options != NULL && options->color_transform != NULL) { + if (options->color_transform->type == COLOR_TRANSFORM_INVERSE_EOTF) { + struct wlr_color_transform_inverse_eotf *tr = + wlr_color_transform_inverse_eotf_from_base(options->color_transform); + inv_eotf = tr->tf; + } else { + // Color transform is not an inverse EOTF + inv_eotf = 0; + } + } else { + // This is the default when unspecified + inv_eotf = WLR_COLOR_TRANSFER_FUNCTION_GAMMA22; + } + + bool using_linear_pathway = inv_eotf == WLR_COLOR_TRANSFER_FUNCTION_EXT_LINEAR; + bool using_srgb_pathway = inv_eotf == WLR_COLOR_TRANSFER_FUNCTION_SRGB && + buffer->srgb.out.framebuffer != VK_NULL_HANDLE; + bool using_two_pass_pathway = !using_linear_pathway && !using_srgb_pathway; + + if (using_linear_pathway && !buffer->linear.out.image_view) { + struct wlr_dmabuf_attributes attribs; + wlr_buffer_get_dmabuf(buffer->wlr_buffer, &attribs); + if (!vulkan_setup_one_pass_framebuffer(buffer, &attribs, false)) { + wlr_log(WLR_ERROR, "Failed to set up blend image"); + return NULL; + } + } + + if (using_two_pass_pathway) { + if (options != NULL && options->color_transform != NULL && + !get_color_transform(options->color_transform, renderer)) { + /* Try to create a new color transform */ + if (!vk_color_transform_create(renderer, options->color_transform)) { + wlr_log(WLR_ERROR, "Failed to create color transform"); + return NULL; + } + } + + if (!buffer->two_pass.out.image_view) { + struct wlr_dmabuf_attributes attribs; + wlr_buffer_get_dmabuf(buffer->wlr_buffer, &attribs); + if (!vulkan_setup_two_pass_framebuffer(buffer, &attribs)) { + wlr_log(WLR_ERROR, "Failed to set up blend image"); + return NULL; + } + } + } + + struct wlr_vk_render_format_setup *render_setup; + struct wlr_vk_render_buffer_out *buffer_out; + if (using_two_pass_pathway) { + render_setup = buffer->two_pass.render_setup; + buffer_out = &buffer->two_pass.out; + } else if (using_srgb_pathway) { + render_setup = buffer->srgb.render_setup; + buffer_out = &buffer->srgb.out; + } else if (using_linear_pathway) { + render_setup = buffer->linear.render_setup; + buffer_out = &buffer->linear.out; + } else { + abort(); // unreachable + } + + struct wlr_vk_render_pass *pass = calloc(1, sizeof(*pass)); + if (pass == NULL) { + return NULL; + } + + wlr_render_pass_init(&pass->base, &render_pass_impl); + pass->renderer = renderer; + pass->two_pass = using_two_pass_pathway; + if (options != NULL && options->color_transform != NULL) { + pass->color_transform = wlr_color_transform_ref(options->color_transform); + } + if (options != NULL && options->signal_timeline != NULL) { + pass->signal_timeline = wlr_drm_syncobj_timeline_ref(options->signal_timeline); + pass->signal_point = options->signal_point; + } + + rect_union_init(&pass->updated_region); + + struct wlr_vk_command_buffer *cb = vulkan_acquire_command_buffer(renderer); + if (cb == NULL) { + free(pass); + return NULL; + } + + VkCommandBufferBeginInfo begin_info = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, + }; + VkResult res = vkBeginCommandBuffer(cb->vk, &begin_info); + if (res != VK_SUCCESS) { + wlr_vk_error("vkBeginCommandBuffer", res); + vulkan_reset_command_buffer(cb); + free(pass); + return NULL; + } + + if (!renderer->dummy3d_image_transitioned) { + renderer->dummy3d_image_transitioned = true; + vulkan_change_layout(cb->vk, renderer->dummy3d_image, + VK_IMAGE_LAYOUT_UNDEFINED, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + 0, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_ACCESS_SHADER_READ_BIT); + } + + int width = buffer->wlr_buffer->width; + int height = buffer->wlr_buffer->height; + VkRect2D rect = { .extent = { width, height } }; + + VkRenderPassBeginInfo rp_info = { + .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, + .renderArea = rect, + .clearValueCount = 0, + .renderPass = render_setup->render_pass, + .framebuffer = buffer_out->framebuffer, + }; + vkCmdBeginRenderPass(cb->vk, &rp_info, VK_SUBPASS_CONTENTS_INLINE); + + vkCmdSetViewport(cb->vk, 0, 1, &(VkViewport){ + .width = width, + .height = height, + .maxDepth = 1, + }); + + // matrix_projection() assumes a GL coordinate system so we need + // to pass WL_OUTPUT_TRANSFORM_FLIPPED_180 to adjust it for vulkan. + matrix_projection(pass->projection, width, height, WL_OUTPUT_TRANSFORM_FLIPPED_180); + + wlr_buffer_lock(buffer->wlr_buffer); + pass->render_buffer = buffer; + pass->render_buffer_out = buffer_out; + pass->render_setup = render_setup; + pass->command_buffer = cb; + return pass; +} diff --git a/3rdparty/wlroots/render/vulkan/pixel_format.c b/3rdparty/wlroots/render/vulkan/pixel_format.c new file mode 100644 index 0000000000..9b17d079a0 --- /dev/null +++ b/3rdparty/wlroots/render/vulkan/pixel_format.c @@ -0,0 +1,615 @@ +#include +#include +#include +#include +#include +#include +#include "render/pixel_format.h" +#include "render/vulkan.h" + +static const struct wlr_vk_format formats[] = { + // Vulkan non-packed 8-bits-per-channel formats have an inverted channel + // order compared to the DRM formats, because DRM format channel order + // is little-endian while Vulkan format channel order is in memory byte + // order. + { + .drm = DRM_FORMAT_R8, + .vk = VK_FORMAT_R8_UNORM, + .vk_srgb = VK_FORMAT_R8_SRGB, + }, + { + .drm = DRM_FORMAT_R16F, + .vk = VK_FORMAT_R16_SFLOAT, + }, + { + .drm = DRM_FORMAT_R32F, + .vk = VK_FORMAT_R32_SFLOAT, + }, + { + .drm = DRM_FORMAT_GR88, + .vk = VK_FORMAT_R8G8_UNORM, + .vk_srgb = VK_FORMAT_R8G8_SRGB, + }, + { + .drm = DRM_FORMAT_GR1616F, + .vk = VK_FORMAT_R16G16_SFLOAT, + }, + { + .drm = DRM_FORMAT_GR3232F, + .vk = VK_FORMAT_R32G32_SFLOAT, + }, + { + .drm = DRM_FORMAT_RGB888, + .vk = VK_FORMAT_B8G8R8_UNORM, + .vk_srgb = VK_FORMAT_B8G8R8_SRGB, + }, + { + .drm = DRM_FORMAT_BGR888, + .vk = VK_FORMAT_R8G8B8_UNORM, + .vk_srgb = VK_FORMAT_R8G8B8_SRGB, + }, + { + .drm = DRM_FORMAT_XRGB8888, + .vk = VK_FORMAT_B8G8R8A8_UNORM, + .vk_srgb = VK_FORMAT_B8G8R8A8_SRGB, + }, + { + .drm = DRM_FORMAT_XBGR8888, + .vk = VK_FORMAT_R8G8B8A8_UNORM, + .vk_srgb = VK_FORMAT_R8G8B8A8_SRGB, + }, + // The Vulkan _SRGB formats correspond to unpremultiplied alpha, but + // the Wayland protocol specifies premultiplied alpha on electrical values + { + .drm = DRM_FORMAT_ARGB8888, + .vk = VK_FORMAT_B8G8R8A8_UNORM, + }, + { + .drm = DRM_FORMAT_ABGR8888, + .vk = VK_FORMAT_R8G8B8A8_UNORM, + }, + // Vulkan packed formats have the same channel order as DRM formats on + // little endian systems. +#if WLR_LITTLE_ENDIAN + { + .drm = DRM_FORMAT_RGBA4444, + .vk = VK_FORMAT_R4G4B4A4_UNORM_PACK16, + }, + { + .drm = DRM_FORMAT_RGBX4444, + .vk = VK_FORMAT_R4G4B4A4_UNORM_PACK16, + }, + { + .drm = DRM_FORMAT_BGRA4444, + .vk = VK_FORMAT_B4G4R4A4_UNORM_PACK16, + }, + { + .drm = DRM_FORMAT_BGRX4444, + .vk = VK_FORMAT_B4G4R4A4_UNORM_PACK16, + }, + { + .drm = DRM_FORMAT_RGB565, + .vk = VK_FORMAT_R5G6B5_UNORM_PACK16, + }, + { + .drm = DRM_FORMAT_BGR565, + .vk = VK_FORMAT_B5G6R5_UNORM_PACK16, + }, + { + .drm = DRM_FORMAT_RGBA5551, + .vk = VK_FORMAT_R5G5B5A1_UNORM_PACK16, + }, + { + .drm = DRM_FORMAT_RGBX5551, + .vk = VK_FORMAT_R5G5B5A1_UNORM_PACK16, + }, + { + .drm = DRM_FORMAT_BGRA5551, + .vk = VK_FORMAT_B5G5R5A1_UNORM_PACK16, + }, + { + .drm = DRM_FORMAT_BGRX5551, + .vk = VK_FORMAT_B5G5R5A1_UNORM_PACK16, + }, + { + .drm = DRM_FORMAT_ARGB1555, + .vk = VK_FORMAT_A1R5G5B5_UNORM_PACK16, + }, + { + .drm = DRM_FORMAT_XRGB1555, + .vk = VK_FORMAT_A1R5G5B5_UNORM_PACK16, + }, + { + .drm = DRM_FORMAT_ARGB2101010, + .vk = VK_FORMAT_A2R10G10B10_UNORM_PACK32, + }, + { + .drm = DRM_FORMAT_XRGB2101010, + .vk = VK_FORMAT_A2R10G10B10_UNORM_PACK32, + }, + { + .drm = DRM_FORMAT_ABGR2101010, + .vk = VK_FORMAT_A2B10G10R10_UNORM_PACK32, + }, + { + .drm = DRM_FORMAT_XBGR2101010, + .vk = VK_FORMAT_A2B10G10R10_UNORM_PACK32, + }, +#endif + + // Vulkan 16-bits-per-channel formats have an inverted channel order + // compared to DRM formats, just like the 8-bits-per-channel ones. + // On little endian systems the memory representation of each channel + // matches the DRM formats'. +#if WLR_LITTLE_ENDIAN + { + .drm = DRM_FORMAT_BGR161616, + .vk = VK_FORMAT_R16G16B16_UNORM, + }, + { + .drm = DRM_FORMAT_BGR161616F, + .vk = VK_FORMAT_R16G16B16_SFLOAT, + }, + { + .drm = DRM_FORMAT_ABGR16161616, + .vk = VK_FORMAT_R16G16B16A16_UNORM, + }, + { + .drm = DRM_FORMAT_XBGR16161616, + .vk = VK_FORMAT_R16G16B16A16_UNORM, + }, + { + .drm = DRM_FORMAT_ABGR16161616F, + .vk = VK_FORMAT_R16G16B16A16_SFLOAT, + }, + { + .drm = DRM_FORMAT_XBGR16161616F, + .vk = VK_FORMAT_R16G16B16A16_SFLOAT, + }, + { + .drm = DRM_FORMAT_BGR323232F, + .vk = VK_FORMAT_R32G32B32_SFLOAT, + }, + { + .drm = DRM_FORMAT_ABGR32323232F, + .vk = VK_FORMAT_R32G32B32A32_SFLOAT, + }, +#endif + + // YCbCr formats + // R -> V, G -> Y, B -> U + // 420 -> 2x2 subsampled, 422 -> 2x1 subsampled, 444 -> non-subsampled + { + .drm = DRM_FORMAT_UYVY, + .vk = VK_FORMAT_B8G8R8G8_422_UNORM, + }, + { + .drm = DRM_FORMAT_YUYV, + .vk = VK_FORMAT_G8B8G8R8_422_UNORM, + }, + { + .drm = DRM_FORMAT_NV12, + .vk = VK_FORMAT_G8_B8R8_2PLANE_420_UNORM, + }, + { + .drm = DRM_FORMAT_NV16, + .vk = VK_FORMAT_G8_B8R8_2PLANE_422_UNORM, + }, + { + .drm = DRM_FORMAT_YUV420, + .vk = VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM, + }, + { + .drm = DRM_FORMAT_YUV422, + .vk = VK_FORMAT_G8_B8_R8_3PLANE_422_UNORM, + }, + { + .drm = DRM_FORMAT_YUV444, + .vk = VK_FORMAT_G8_B8_R8_3PLANE_444_UNORM, + }, + // 3PACK16 formats split the memory in three 16-bit words, so they have an + // inverted channel order compared to DRM formats. +#if WLR_LITTLE_ENDIAN + { + .drm = DRM_FORMAT_P010, + .vk = VK_FORMAT_G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16, + }, + { + .drm = DRM_FORMAT_P210, + .vk = VK_FORMAT_G10X6_B10X6R10X6_2PLANE_422_UNORM_3PACK16, + }, + { + .drm = DRM_FORMAT_P012, + .vk = VK_FORMAT_G12X4_B12X4R12X4_2PLANE_420_UNORM_3PACK16, + }, + { + .drm = DRM_FORMAT_P016, + .vk = VK_FORMAT_G16_B16R16_2PLANE_420_UNORM, + }, + { + .drm = DRM_FORMAT_Q410, + .vk = VK_FORMAT_G10X6_B10X6_R10X6_3PLANE_444_UNORM_3PACK16, + }, +#endif + // TODO: add DRM_FORMAT_NV24/VK_FORMAT_G8_B8R8_2PLANE_444_UNORM (requires + // Vulkan 1.3 or VK_EXT_ycbcr_2plane_444_formats) +}; + +const struct wlr_vk_format *vulkan_get_format_list(size_t *len) { + *len = sizeof(formats) / sizeof(formats[0]); + return formats; +} + +const struct wlr_vk_format *vulkan_get_format_from_drm(uint32_t drm_format) { + for (unsigned i = 0; i < sizeof(formats) / sizeof(formats[0]); ++i) { + if (formats[i].drm == drm_format) { + return &formats[i]; + } + } + return NULL; +} + +const VkImageUsageFlags vulkan_render_usage = + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; +const VkImageUsageFlags vulkan_shm_tex_usage = + VK_IMAGE_USAGE_SAMPLED_BIT | + VK_IMAGE_USAGE_TRANSFER_DST_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT; +const VkImageUsageFlags vulkan_dma_tex_usage = + VK_IMAGE_USAGE_SAMPLED_BIT | + VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + +static const VkFormatFeatureFlags render_features = + VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | + VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT; +static const VkFormatFeatureFlags shm_tex_features = + VK_FORMAT_FEATURE_TRANSFER_SRC_BIT | + VK_FORMAT_FEATURE_TRANSFER_DST_BIT | + VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | + // NOTE: we don't strictly require this, we could create a NEAREST + // sampler for formats that need it, in case this ever makes problems. + VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; +static const VkFormatFeatureFlags dma_tex_features = + VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | + // NOTE: we don't strictly require this, we could create a NEAREST + // sampler for formats that need it, in case this ever makes problems. + VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; +static const VkFormatFeatureFlags ycbcr_tex_features = + VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT | + VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT; + +// vk_format_variant should be set to 0=VK_FORMAT_UNDEFINED when not used +static bool query_modifier_usage_support(struct wlr_vk_device *dev, VkFormat vk_format, + VkFormat vk_format_variant, VkImageUsageFlags usage, + const VkDrmFormatModifierPropertiesEXT *m, + struct wlr_vk_format_modifier_props *out, const char **errmsg) { + VkResult res; + *errmsg = NULL; + + VkFormat view_formats[2] = { + vk_format, + vk_format_variant, + }; + VkImageFormatListCreateInfoKHR listi = { + .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO_KHR, + .pViewFormats = view_formats, + .viewFormatCount = vk_format_variant ? 2 : 1, + }; + VkPhysicalDeviceImageDrmFormatModifierInfoEXT modi = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_DRM_FORMAT_MODIFIER_INFO_EXT, + .drmFormatModifier = m->drmFormatModifier, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .pNext = &listi, + }; + VkPhysicalDeviceExternalImageFormatInfo efmti = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO, + .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, + .pNext = &modi, + }; + VkPhysicalDeviceImageFormatInfo2 fmti = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2, + .type = VK_IMAGE_TYPE_2D, + .format = vk_format, + .usage = usage, + .flags = vk_format_variant ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0, + .tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT, + .pNext = &efmti, + }; + + VkExternalImageFormatProperties efmtp = { + .sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES, + }; + VkImageFormatProperties2 ifmtp = { + .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2, + .pNext = &efmtp, + }; + const VkExternalMemoryProperties *emp = &efmtp.externalMemoryProperties; + + res = vkGetPhysicalDeviceImageFormatProperties2(dev->phdev, &fmti, &ifmtp); + if (res != VK_SUCCESS) { + if (res == VK_ERROR_FORMAT_NOT_SUPPORTED) { + *errmsg = "unsupported format"; + } else { + wlr_vk_error("vkGetPhysicalDeviceImageFormatProperties2", res); + *errmsg = "failed to get format properties"; + } + return false; + } else if (!(emp->externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT)) { + *errmsg = "import not supported"; + return false; + } + + VkExtent3D me = ifmtp.imageFormatProperties.maxExtent; + *out = (struct wlr_vk_format_modifier_props){ + .props = *m, + .max_extent.width = me.width, + .max_extent.height = me.height, + }; + return true; +} + +static bool query_shm_support(struct wlr_vk_device *dev, VkFormat vk_format, + VkFormat vk_format_variant, VkImageFormatProperties *out, + const char **errmsg) { + VkResult res; + *errmsg = NULL; + + VkFormat view_formats[2] = { + vk_format, + vk_format_variant, + }; + VkImageFormatListCreateInfoKHR listi = { + .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO_KHR, + .pViewFormats = view_formats, + .viewFormatCount = vk_format_variant ? 2 : 1, + .pNext = NULL, + }; + VkPhysicalDeviceImageFormatInfo2 fmti = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2, + .type = VK_IMAGE_TYPE_2D, + .format = vk_format, + .tiling = VK_IMAGE_TILING_OPTIMAL, + .usage = vulkan_shm_tex_usage, + .flags = vk_format_variant ? VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT : 0, + .pNext = &listi, + }; + VkImageFormatProperties2 ifmtp = { + .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2, + }; + + res = vkGetPhysicalDeviceImageFormatProperties2(dev->phdev, &fmti, &ifmtp); + if (res != VK_SUCCESS) { + if (res == VK_ERROR_FORMAT_NOT_SUPPORTED) { + *errmsg = "unsupported format"; + } else { + wlr_vk_error("vkGetPhysicalDeviceImageFormatProperties2", res); + *errmsg = "failed to get format properties"; + } + return false; + } + + *out = ifmtp.imageFormatProperties; + return true; +} + +static bool query_modifier_support(struct wlr_vk_device *dev, + struct wlr_vk_format_props *props, size_t modifier_count) { + VkDrmFormatModifierPropertiesListEXT modp = { + .sType = VK_STRUCTURE_TYPE_DRM_FORMAT_MODIFIER_PROPERTIES_LIST_EXT, + .drmFormatModifierCount = modifier_count, + }; + VkFormatProperties2 fmtp = { + .sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, + .pNext = &modp, + }; + + modp.pDrmFormatModifierProperties = + calloc(modifier_count, sizeof(*modp.pDrmFormatModifierProperties)); + if (!modp.pDrmFormatModifierProperties) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return false; + } + + vkGetPhysicalDeviceFormatProperties2(dev->phdev, props->format.vk, &fmtp); + + props->dmabuf.render_mods = + calloc(modp.drmFormatModifierCount, sizeof(*props->dmabuf.render_mods)); + props->dmabuf.texture_mods = + calloc(modp.drmFormatModifierCount, sizeof(*props->dmabuf.texture_mods)); + if (!props->dmabuf.render_mods || !props->dmabuf.texture_mods) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + free(modp.pDrmFormatModifierProperties); + free(props->dmabuf.render_mods); + free(props->dmabuf.texture_mods); + props->dmabuf.render_mods = NULL; + props->dmabuf.texture_mods = NULL; + return false; + } + + bool found = false; + for (uint32_t i = 0; i < modp.drmFormatModifierCount; ++i) { + VkDrmFormatModifierPropertiesEXT m = modp.pDrmFormatModifierProperties[i]; + char render_status[256], texture_status[256]; + + // check that specific modifier for render usage + const char *errmsg = "unknown error"; + if ((m.drmFormatModifierTilingFeatures & render_features) == render_features && + !vulkan_format_is_ycbcr(&props->format)) { + struct wlr_vk_format_modifier_props p = {0}; + bool supported = false; + if (query_modifier_usage_support(dev, props->format.vk, + props->format.vk_srgb, vulkan_render_usage, &m, &p, &errmsg)) { + supported = true; + p.has_mutable_srgb = props->format.vk_srgb != 0; + } + if (!supported && props->format.vk_srgb) { + supported = query_modifier_usage_support(dev, props->format.vk, + 0, vulkan_render_usage, &m, &p, &errmsg); + } + + if (supported) { + props->dmabuf.render_mods[props->dmabuf.render_mod_count++] = p; + wlr_drm_format_set_add(&dev->dmabuf_render_formats, + props->format.drm, m.drmFormatModifier); + found = true; + } + } else { + errmsg = "missing required features"; + } + if (errmsg != NULL) { + snprintf(render_status, sizeof(render_status), "✗ render (%s)", errmsg); + } else { + snprintf(render_status, sizeof(render_status), "✓ render"); + } + + // check that specific modifier for texture usage + errmsg = "unknown error"; + VkFormatFeatureFlags features = dma_tex_features; + if (vulkan_format_is_ycbcr(&props->format)) { + features |= ycbcr_tex_features; + } + if ((m.drmFormatModifierTilingFeatures & features) == features) { + struct wlr_vk_format_modifier_props p = {0}; + bool supported = false; + if (query_modifier_usage_support(dev, props->format.vk, + props->format.vk_srgb, vulkan_dma_tex_usage, &m, &p, &errmsg)) { + supported = true; + p.has_mutable_srgb = props->format.vk_srgb != 0; + } + if (!supported && props->format.vk_srgb) { + supported = query_modifier_usage_support(dev, props->format.vk, + 0, vulkan_dma_tex_usage, &m, &p, &errmsg); + } + + if (supported) { + props->dmabuf.texture_mods[props->dmabuf.texture_mod_count++] = p; + wlr_drm_format_set_add(&dev->dmabuf_texture_formats, + props->format.drm, m.drmFormatModifier); + found = true; + } + } else { + errmsg = "missing required features"; + } + if (errmsg != NULL) { + snprintf(texture_status, sizeof(texture_status), "✗ texture (%s)", errmsg); + } else { + snprintf(texture_status, sizeof(texture_status), "✓ texture"); + } + + char *modifier_name = drmGetFormatModifierName(m.drmFormatModifier); + wlr_log(WLR_DEBUG, " DMA-BUF modifier %s " + "(0x%016"PRIX64", %"PRIu32" planes): %s %s", + modifier_name ? modifier_name : "", m.drmFormatModifier, + m.drmFormatModifierPlaneCount, texture_status, render_status); + free(modifier_name); + } + + free(modp.pDrmFormatModifierProperties); + return found; +} + +void vulkan_format_props_query(struct wlr_vk_device *dev, + const struct wlr_vk_format *format) { + if (vulkan_format_is_ycbcr(format) && !dev->sampler_ycbcr_conversion) { + return; + } + + char *format_name = drmGetFormatName(format->drm); + wlr_log(WLR_DEBUG, " %s (0x%08"PRIX32")", + format_name ? format_name : "", format->drm); + free(format_name); + + VkDrmFormatModifierPropertiesListEXT modp = { + .sType = VK_STRUCTURE_TYPE_DRM_FORMAT_MODIFIER_PROPERTIES_LIST_EXT, + }; + VkFormatProperties2 fmtp = { + .sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2, + .pNext = &modp, + }; + + vkGetPhysicalDeviceFormatProperties2(dev->phdev, format->vk, &fmtp); + + bool add_fmt_props = false; + struct wlr_vk_format_props props = {0}; + props.format = *format; + + const struct wlr_pixel_format_info *format_info = drm_get_pixel_format_info(format->drm); + + // shm texture properties + char shm_texture_status[256]; + const char *errmsg = "unknown error"; + if ((fmtp.formatProperties.optimalTilingFeatures & shm_tex_features) == shm_tex_features && + !vulkan_format_is_ycbcr(format) && format_info != NULL) { + VkImageFormatProperties ifmtp; + bool supported = false, has_mutable_srgb = false; + if (query_shm_support(dev, format->vk, format->vk_srgb, &ifmtp, &errmsg)) { + supported = true; + has_mutable_srgb = format->vk_srgb != 0; + } + if (!supported && format->vk_srgb) { + supported = query_shm_support(dev, format->vk, 0, &ifmtp, &errmsg); + } + + if (supported) { + props.shm.max_extent.width = ifmtp.maxExtent.width; + props.shm.max_extent.height = ifmtp.maxExtent.height; + props.shm.features = fmtp.formatProperties.optimalTilingFeatures; + props.shm.has_mutable_srgb = has_mutable_srgb; + + wlr_drm_format_set_add(&dev->shm_texture_formats, + format->drm, DRM_FORMAT_MOD_LINEAR); + + add_fmt_props = true; + } + } else { + errmsg = "missing required features"; + } + + if (errmsg != NULL) { + snprintf(shm_texture_status, sizeof(shm_texture_status), "✗ texture (%s)", errmsg); + } else { + snprintf(shm_texture_status, sizeof(shm_texture_status), "✓ texture"); + } + wlr_log(WLR_DEBUG, " Shared memory: %s", shm_texture_status); + + if (modp.drmFormatModifierCount > 0) { + add_fmt_props |= query_modifier_support(dev, &props, + modp.drmFormatModifierCount); + } + + if (add_fmt_props) { + dev->format_props[dev->format_prop_count] = props; + ++dev->format_prop_count; + } else { + vulkan_format_props_finish(&props); + } +} + +void vulkan_format_props_finish(struct wlr_vk_format_props *props) { + free(props->dmabuf.texture_mods); + free(props->dmabuf.render_mods); +} + +const struct wlr_vk_format_modifier_props *vulkan_format_props_find_modifier( + const struct wlr_vk_format_props *props, uint64_t mod, bool render) { + uint32_t len; + const struct wlr_vk_format_modifier_props *mods; + if (render) { + len = props->dmabuf.render_mod_count; + mods = props->dmabuf.render_mods; + } else { + len = props->dmabuf.texture_mod_count; + mods = props->dmabuf.texture_mods; + } + + for (uint32_t i = 0; i < len; ++i) { + if (mods[i].props.drmFormatModifier == mod) { + return &mods[i]; + } + } + return NULL; +} + +bool vulkan_format_is_ycbcr(const struct wlr_vk_format *format) { + return pixel_format_is_ycbcr(format->drm); +} diff --git a/3rdparty/wlroots/render/vulkan/renderer.c b/3rdparty/wlroots/render/vulkan/renderer.c new file mode 100644 index 0000000000..90d4b8ab56 --- /dev/null +++ b/3rdparty/wlroots/render/vulkan/renderer.c @@ -0,0 +1,2790 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "render/dmabuf.h" +#include "render/pixel_format.h" +#include "render/vulkan.h" +#include "render/vulkan/shaders/common.vert.h" +#include "render/vulkan/shaders/texture.frag.h" +#include "render/vulkan/shaders/quad.frag.h" +#include "render/vulkan/shaders/output.frag.h" +#include "types/wlr_buffer.h" +#include "util/time.h" + +// TODO: +// - simplify stage allocation, don't track allocations but use ringbuffer-like +// - use a pipeline cache (not sure when to save though, after every pipeline +// creation?) +// - create pipelines as derivatives of each other +// - evaluate if creating VkDeviceMemory pools is a good idea. +// We can expect wayland client images to be fairly large (and shouldn't +// have more than 4k of those I guess) but pooling memory allocations +// might still be a good idea. + +static const VkDeviceSize min_stage_size = 1024 * 1024; // 1MB +static const VkDeviceSize max_stage_size = 256 * min_stage_size; // 256MB +static const size_t start_descriptor_pool_size = 256u; +static bool default_debug = true; + +static const struct wlr_renderer_impl renderer_impl; + +bool wlr_renderer_is_vk(struct wlr_renderer *wlr_renderer) { + return wlr_renderer->impl == &renderer_impl; +} + +struct wlr_vk_renderer *vulkan_get_renderer(struct wlr_renderer *wlr_renderer) { + assert(wlr_renderer_is_vk(wlr_renderer)); + struct wlr_vk_renderer *renderer = wl_container_of(wlr_renderer, renderer, wlr_renderer); + return renderer; +} + +static struct wlr_vk_render_format_setup *find_or_create_render_setup( + struct wlr_vk_renderer *renderer, const struct wlr_vk_format *format, + bool has_blending_buffer, bool srgb); + +static struct wlr_vk_descriptor_pool *alloc_ds( + struct wlr_vk_renderer *renderer, VkDescriptorSet *ds, + VkDescriptorType type, const VkDescriptorSetLayout *layout, + struct wl_list *pool_list, size_t *last_pool_size) { + VkResult res; + + VkDescriptorSetAllocateInfo ds_info = { + .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, + .descriptorSetCount = 1, + .pSetLayouts = layout, + }; + + struct wlr_vk_descriptor_pool *pool; + wl_list_for_each(pool, pool_list, link) { + if (pool->free > 0) { + ds_info.descriptorPool = pool->pool; + res = vkAllocateDescriptorSets(renderer->dev->dev, &ds_info, ds); + switch (res) { + case VK_ERROR_FRAGMENTED_POOL: + case VK_ERROR_OUT_OF_POOL_MEMORY: + // Descriptor sets with more than one descriptor can cause us + // to run out of pool memory early or lead to fragmentation + // that makes the pool unable to service our allocation + // request. Try the next pool or allocate a new one. + continue; + case VK_SUCCESS: + --pool->free; + return pool; + default: + wlr_vk_error("vkAllocateDescriptorSets", res); + return NULL; + } + } + } + + pool = calloc(1, sizeof(*pool)); + if (!pool) { + wlr_log_errno(WLR_ERROR, "allocation failed"); + return NULL; + } + + size_t count = 2 * (*last_pool_size); + if (!count) { + count = start_descriptor_pool_size; + } + + pool->free = count; + VkDescriptorPoolSize pool_size = { + .descriptorCount = count, + .type = type, + }; + + VkDescriptorPoolCreateInfo dpool_info = { + .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, + .maxSets = count, + .poolSizeCount = 1, + .pPoolSizes = &pool_size, + .flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, + }; + + res = vkCreateDescriptorPool(renderer->dev->dev, &dpool_info, NULL, + &pool->pool); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateDescriptorPool", res); + free(pool); + return NULL; + } + + *last_pool_size = count; + wl_list_insert(pool_list, &pool->link); + + ds_info.descriptorPool = pool->pool; + res = vkAllocateDescriptorSets(renderer->dev->dev, &ds_info, ds); + if (res != VK_SUCCESS) { + wlr_vk_error("vkAllocateDescriptorSets", res); + return NULL; + } + + --pool->free; + return pool; +} + +struct wlr_vk_descriptor_pool *vulkan_alloc_texture_ds( + struct wlr_vk_renderer *renderer, VkDescriptorSetLayout ds_layout, + VkDescriptorSet *ds) { + return alloc_ds(renderer, ds, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + &ds_layout, &renderer->descriptor_pools, + &renderer->last_pool_size); +} + +struct wlr_vk_descriptor_pool *vulkan_alloc_blend_ds( + struct wlr_vk_renderer *renderer, VkDescriptorSet *ds) { + return alloc_ds(renderer, ds, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, + &renderer->output_ds_srgb_layout, &renderer->output_descriptor_pools, + &renderer->last_output_pool_size); +} + +void vulkan_free_ds(struct wlr_vk_renderer *renderer, + struct wlr_vk_descriptor_pool *pool, VkDescriptorSet ds) { + vkFreeDescriptorSets(renderer->dev->dev, pool->pool, 1, &ds); + ++pool->free; +} + +static void destroy_render_format_setup(struct wlr_vk_renderer *renderer, + struct wlr_vk_render_format_setup *setup) { + if (!setup) { + return; + } + + VkDevice dev = renderer->dev->dev; + vkDestroyRenderPass(dev, setup->render_pass, NULL); + vkDestroyPipeline(dev, setup->output_pipe_identity, NULL); + vkDestroyPipeline(dev, setup->output_pipe_srgb, NULL); + vkDestroyPipeline(dev, setup->output_pipe_pq, NULL); + vkDestroyPipeline(dev, setup->output_pipe_lut3d, NULL); + vkDestroyPipeline(dev, setup->output_pipe_gamma22, NULL); + vkDestroyPipeline(dev, setup->output_pipe_bt1886, NULL); + + struct wlr_vk_pipeline *pipeline, *tmp_pipeline; + wl_list_for_each_safe(pipeline, tmp_pipeline, &setup->pipelines, link) { + vkDestroyPipeline(dev, pipeline->vk, NULL); + free(pipeline); + } + + free(setup); +} + +static void shared_buffer_destroy(struct wlr_vk_renderer *r, + struct wlr_vk_shared_buffer *buffer) { + if (!buffer) { + return; + } + + if (buffer->allocs.size > 0) { + wlr_log(WLR_ERROR, "shared_buffer_finish: %zu allocations left", + buffer->allocs.size / sizeof(struct wlr_vk_allocation)); + } + + wl_array_release(&buffer->allocs); + if (buffer->cpu_mapping) { + vkUnmapMemory(r->dev->dev, buffer->memory); + buffer->cpu_mapping = NULL; + } + if (buffer->buffer) { + vkDestroyBuffer(r->dev->dev, buffer->buffer, NULL); + } + if (buffer->memory) { + vkFreeMemory(r->dev->dev, buffer->memory, NULL); + } + + wl_list_remove(&buffer->link); + free(buffer); +} + +struct wlr_vk_buffer_span vulkan_get_stage_span(struct wlr_vk_renderer *r, + VkDeviceSize size, VkDeviceSize alignment) { + // try to find free span + // simple greedy allocation algorithm - should be enough for this usecase + // since all allocations are freed together after the frame + struct wlr_vk_shared_buffer *buf; + wl_list_for_each_reverse(buf, &r->stage.buffers, link) { + VkDeviceSize start = 0u; + if (buf->allocs.size > 0) { + const struct wlr_vk_allocation *allocs = buf->allocs.data; + size_t allocs_len = buf->allocs.size / sizeof(struct wlr_vk_allocation); + const struct wlr_vk_allocation *last = &allocs[allocs_len - 1]; + start = last->start + last->size; + } + + assert(start <= buf->buf_size); + + // ensure the proposed start is a multiple of alignment + start += alignment - 1 - ((start + alignment - 1) % alignment); + + if (buf->buf_size - start < size) { + continue; + } + + struct wlr_vk_allocation *a = wl_array_add(&buf->allocs, sizeof(*a)); + if (a == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + goto error_alloc; + } + + *a = (struct wlr_vk_allocation){ + .start = start, + .size = size, + }; + return (struct wlr_vk_buffer_span) { + .buffer = buf, + .alloc = *a, + }; + } + + if (size > max_stage_size) { + wlr_log(WLR_ERROR, "cannot vulkan stage buffer: " + "requested size (%zu bytes) exceeds maximum (%zu bytes)", + (size_t)size, (size_t)max_stage_size); + goto error_alloc; + } + + // we didn't find a free buffer - create one + // size = clamp(max(size * 2, prev_size * 2), min_size, max_size) + VkDeviceSize bsize = size * 2; + bsize = bsize < min_stage_size ? min_stage_size : bsize; + if (!wl_list_empty(&r->stage.buffers)) { + struct wl_list *last_link = r->stage.buffers.prev; + struct wlr_vk_shared_buffer *prev = wl_container_of( + last_link, prev, link); + VkDeviceSize last_size = 2 * prev->buf_size; + bsize = bsize < last_size ? last_size : bsize; + } + + if (bsize > max_stage_size) { + wlr_log(WLR_INFO, "vulkan stage buffers have reached max size"); + bsize = max_stage_size; + } + + // create buffer + buf = calloc(1, sizeof(*buf)); + if (!buf) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + goto error_alloc; + } + + wl_list_init(&buf->link); + + VkResult res; + VkBufferCreateInfo buf_info = { + .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .size = bsize, + .usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | + VK_BUFFER_USAGE_TRANSFER_SRC_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + }; + res = vkCreateBuffer(r->dev->dev, &buf_info, NULL, &buf->buffer); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateBuffer", res); + goto error; + } + + VkMemoryRequirements mem_reqs; + vkGetBufferMemoryRequirements(r->dev->dev, buf->buffer, &mem_reqs); + + int mem_type_index = vulkan_find_mem_type(r->dev, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, mem_reqs.memoryTypeBits); + if (mem_type_index < 0) { + wlr_log(WLR_ERROR, "Failed to find memory type"); + goto error; + } + + VkMemoryAllocateInfo mem_info = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = mem_reqs.size, + .memoryTypeIndex = (uint32_t)mem_type_index, + }; + res = vkAllocateMemory(r->dev->dev, &mem_info, NULL, &buf->memory); + if (res != VK_SUCCESS) { + wlr_vk_error("vkAllocatorMemory", res); + goto error; + } + + res = vkBindBufferMemory(r->dev->dev, buf->buffer, buf->memory, 0); + if (res != VK_SUCCESS) { + wlr_vk_error("vkBindBufferMemory", res); + goto error; + } + + res = vkMapMemory(r->dev->dev, buf->memory, 0, VK_WHOLE_SIZE, 0, &buf->cpu_mapping); + if (res != VK_SUCCESS) { + wlr_vk_error("vkMapMemory", res); + goto error; + } + + struct wlr_vk_allocation *a = wl_array_add(&buf->allocs, sizeof(*a)); + if (a == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + goto error; + } + + buf->buf_size = bsize; + wl_list_insert(&r->stage.buffers, &buf->link); + + *a = (struct wlr_vk_allocation){ + .start = 0, + .size = size, + }; + return (struct wlr_vk_buffer_span) { + .buffer = buf, + .alloc = *a, + }; + +error: + shared_buffer_destroy(r, buf); + +error_alloc: + return (struct wlr_vk_buffer_span) { + .buffer = NULL, + .alloc = (struct wlr_vk_allocation) {0, 0}, + }; +} + +VkCommandBuffer vulkan_record_stage_cb(struct wlr_vk_renderer *renderer) { + if (renderer->stage.cb == NULL) { + renderer->stage.cb = vulkan_acquire_command_buffer(renderer); + if (renderer->stage.cb == NULL) { + return VK_NULL_HANDLE; + } + + VkCommandBufferBeginInfo begin_info = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, + }; + vkBeginCommandBuffer(renderer->stage.cb->vk, &begin_info); + } + + return renderer->stage.cb->vk; +} + +bool vulkan_submit_stage_wait(struct wlr_vk_renderer *renderer) { + if (renderer->stage.cb == NULL) { + return false; + } + + struct wlr_vk_command_buffer *cb = renderer->stage.cb; + renderer->stage.cb = NULL; + + uint64_t timeline_point = vulkan_end_command_buffer(cb, renderer); + if (timeline_point == 0) { + return false; + } + + VkTimelineSemaphoreSubmitInfoKHR timeline_submit_info = { + .sType = VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO_KHR, + .signalSemaphoreValueCount = 1, + .pSignalSemaphoreValues = &timeline_point, + }; + VkSubmitInfo submit_info = { + .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, + .pNext = &timeline_submit_info, + .commandBufferCount = 1, + .pCommandBuffers = &cb->vk, + .signalSemaphoreCount = 1, + .pSignalSemaphores = &renderer->timeline_semaphore, + }; + VkResult res = vkQueueSubmit(renderer->dev->queue, 1, &submit_info, VK_NULL_HANDLE); + if (res != VK_SUCCESS) { + wlr_vk_error("vkQueueSubmit", res); + return false; + } + + // NOTE: don't release stage allocations here since they may still be + // used for reading. Will be done next frame. + + return vulkan_wait_command_buffer(cb, renderer); +} + +bool waylib_vk_renderer_flush_stage(struct wlr_renderer *wlr_renderer) { + assert(wlr_renderer_is_vk(wlr_renderer)); + struct wlr_vk_renderer *renderer = vulkan_get_renderer(wlr_renderer); + if (renderer->stage.cb == NULL) { + return true; + } + return vulkan_submit_stage_wait(renderer); +} + +struct wlr_vk_format_props *vulkan_format_props_from_drm( + struct wlr_vk_device *dev, uint32_t drm_fmt) { + for (size_t i = 0u; i < dev->format_prop_count; ++i) { + if (dev->format_props[i].format.drm == drm_fmt) { + return &dev->format_props[i]; + } + } + return NULL; +} + +static bool init_command_buffer(struct wlr_vk_command_buffer *cb, + struct wlr_vk_renderer *renderer) { + VkResult res; + + VkCommandBuffer vk_cb = VK_NULL_HANDLE; + VkCommandBufferAllocateInfo cmd_buf_info = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, + .commandPool = renderer->command_pool, + .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, + .commandBufferCount = 1, + }; + res = vkAllocateCommandBuffers(renderer->dev->dev, &cmd_buf_info, &vk_cb); + if (res != VK_SUCCESS) { + wlr_vk_error("vkAllocateCommandBuffers", res); + return false; + } + + *cb = (struct wlr_vk_command_buffer){ + .vk = vk_cb, + }; + wl_list_init(&cb->destroy_textures); + wl_list_init(&cb->stage_buffers); + return true; +} + +bool vulkan_wait_command_buffer(struct wlr_vk_command_buffer *cb, + struct wlr_vk_renderer *renderer) { + VkResult res; + + assert(cb->vk != VK_NULL_HANDLE && !cb->recording); + + VkSemaphoreWaitInfoKHR wait_info = { + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO_KHR, + .semaphoreCount = 1, + .pSemaphores = &renderer->timeline_semaphore, + .pValues = &cb->timeline_point, + }; + res = renderer->dev->api.vkWaitSemaphoresKHR(renderer->dev->dev, &wait_info, UINT64_MAX); + if (res != VK_SUCCESS) { + wlr_vk_error("vkWaitSemaphoresKHR", res); + return false; + } + + return true; +} + +static void release_command_buffer_resources(struct wlr_vk_command_buffer *cb, + struct wlr_vk_renderer *renderer, int64_t now) { + struct wlr_vk_texture *texture, *texture_tmp; + wl_list_for_each_safe(texture, texture_tmp, &cb->destroy_textures, destroy_link) { + wl_list_remove(&texture->destroy_link); + texture->last_used_cb = NULL; + wlr_texture_destroy(&texture->wlr_texture); + } + + struct wlr_vk_shared_buffer *buf, *buf_tmp; + wl_list_for_each_safe(buf, buf_tmp, &cb->stage_buffers, link) { + buf->allocs.size = 0; + buf->last_used_ms = now; + + wl_list_remove(&buf->link); + wl_list_insert(&renderer->stage.buffers, &buf->link); + } + + if (cb->color_transform) { + wlr_color_transform_unref(cb->color_transform); + cb->color_transform = NULL; + } +} + +static struct wlr_vk_command_buffer *get_command_buffer( + struct wlr_vk_renderer *renderer) { + VkResult res; + + uint64_t current_point; + res = renderer->dev->api.vkGetSemaphoreCounterValueKHR(renderer->dev->dev, + renderer->timeline_semaphore, ¤t_point); + if (res != VK_SUCCESS) { + wlr_vk_error("vkGetSemaphoreCounterValueKHR", res); + return NULL; + } + + + // Garbage collect any buffers that have remained unused for too long + int64_t now = get_current_time_msec(); + struct wlr_vk_shared_buffer *buf, *buf_tmp; + wl_list_for_each_safe(buf, buf_tmp, &renderer->stage.buffers, link) { + if (buf->allocs.size == 0 && buf->last_used_ms + 10000 < now) { + shared_buffer_destroy(renderer, buf); + } + } + + // Destroy textures for completed command buffers + for (size_t i = 0; i < VULKAN_COMMAND_BUFFERS_CAP; i++) { + struct wlr_vk_command_buffer *cb = &renderer->command_buffers[i]; + if (cb->vk != VK_NULL_HANDLE && !cb->recording && + cb->timeline_point <= current_point) { + release_command_buffer_resources(cb, renderer, now); + } + } + + // First try to find an existing command buffer which isn't busy + struct wlr_vk_command_buffer *unused = NULL; + struct wlr_vk_command_buffer *wait = NULL; + for (size_t i = 0; i < VULKAN_COMMAND_BUFFERS_CAP; i++) { + struct wlr_vk_command_buffer *cb = &renderer->command_buffers[i]; + if (cb->vk == VK_NULL_HANDLE) { + unused = cb; + break; + } + if (cb->recording) { + continue; + } + + if (cb->timeline_point <= current_point) { + return cb; + } + if (wait == NULL || cb->timeline_point < wait->timeline_point) { + wait = cb; + } + } + + // If there is an unused slot, initialize it + if (unused != NULL) { + if (!init_command_buffer(unused, renderer)) { + return NULL; + } + return unused; + } + + // Block until a busy command buffer becomes available + if (!vulkan_wait_command_buffer(wait, renderer)) { + return NULL; + } + return wait; +} + +struct wlr_vk_command_buffer *vulkan_acquire_command_buffer( + struct wlr_vk_renderer *renderer) { + struct wlr_vk_command_buffer *cb = get_command_buffer(renderer); + if (cb == NULL) { + return NULL; + } + + assert(!cb->recording); + cb->recording = true; + + return cb; +} + +uint64_t vulkan_end_command_buffer(struct wlr_vk_command_buffer *cb, + struct wlr_vk_renderer *renderer) { + assert(cb->recording); + cb->recording = false; + + VkResult res = vkEndCommandBuffer(cb->vk); + if (res != VK_SUCCESS) { + wlr_vk_error("vkEndCommandBuffer", res); + return 0; + } + + renderer->timeline_point++; + cb->timeline_point = renderer->timeline_point; + return cb->timeline_point; +} + +void vulkan_reset_command_buffer(struct wlr_vk_command_buffer *cb) { + if (cb == NULL) { + return; + } + + cb->recording = false; + + VkResult res = vkResetCommandBuffer(cb->vk, 0); + if (res != VK_SUCCESS) { + wlr_vk_error("vkResetCommandBuffer", res); + } +} + +static void finish_render_buffer_out(struct wlr_vk_render_buffer_out *out, + VkDevice dev) { + vkDestroyFramebuffer(dev, out->framebuffer, NULL); + vkDestroyImageView(dev, out->image_view, NULL); +} + +static void destroy_render_buffer(struct wlr_vk_render_buffer *buffer) { + wl_list_remove(&buffer->link); + wlr_addon_finish(&buffer->addon); + + VkDevice dev = buffer->renderer->dev->dev; + + // TODO: asynchronously wait for the command buffers using this render + // buffer to complete (just like we do for textures) + VkResult res = vkQueueWaitIdle(buffer->renderer->dev->queue); + if (res != VK_SUCCESS) { + wlr_vk_error("vkQueueWaitIdle", res); + } + + finish_render_buffer_out(&buffer->linear.out, dev); + finish_render_buffer_out(&buffer->srgb.out, dev); + + finish_render_buffer_out(&buffer->two_pass.out, dev); + vkDestroyImage(dev, buffer->two_pass.blend_image, NULL); + vkFreeMemory(dev, buffer->two_pass.blend_memory, NULL); + vkDestroyImageView(dev, buffer->two_pass.blend_image_view, NULL); + if (buffer->two_pass.blend_attachment_pool) { + vulkan_free_ds(buffer->renderer, buffer->two_pass.blend_attachment_pool, + buffer->two_pass.blend_descriptor_set); + } + + vkDestroyImage(dev, buffer->image, NULL); + for (size_t i = 0u; i < buffer->mem_count; ++i) { + vkFreeMemory(dev, buffer->memories[i], NULL); + } + + free(buffer); +} + +static void handle_render_buffer_destroy(struct wlr_addon *addon) { + struct wlr_vk_render_buffer *buffer = wl_container_of(addon, buffer, addon); + destroy_render_buffer(buffer); +} + +static struct wlr_addon_interface render_buffer_addon_impl = { + .name = "wlr_vk_render_buffer", + .destroy = handle_render_buffer_destroy, +}; + +bool vulkan_setup_two_pass_framebuffer(struct wlr_vk_render_buffer *buffer, + const struct wlr_dmabuf_attributes *dmabuf) { + struct wlr_vk_renderer *renderer = buffer->renderer; + VkResult res; + VkDevice dev = renderer->dev->dev; + + const struct wlr_vk_format_props *fmt = vulkan_format_props_from_drm( + renderer->dev, dmabuf->format); + assert(fmt); + + VkImageViewCreateInfo view_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, + .image = buffer->image, + .viewType = VK_IMAGE_VIEW_TYPE_2D, + .format = fmt->format.vk, + .components.r = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.g = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.b = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.a = VK_COMPONENT_SWIZZLE_IDENTITY, + .subresourceRange = (VkImageSubresourceRange) { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }; + + res = vkCreateImageView(dev, &view_info, NULL, &buffer->two_pass.out.image_view); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateImageView failed", res); + goto error; + } + + buffer->two_pass.render_setup = find_or_create_render_setup( + renderer, &fmt->format, true, false); + if (!buffer->two_pass.render_setup) { + goto error; + } + + // Set up an extra 16F buffer on which to do linear blending, + // and afterwards to render onto the target + VkImageCreateInfo img_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, + .imageType = VK_IMAGE_TYPE_2D, + .format = VK_FORMAT_R16G16B16A16_SFLOAT, + .mipLevels = 1, + .arrayLayers = 1, + .samples = VK_SAMPLE_COUNT_1_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .tiling = VK_IMAGE_TILING_OPTIMAL, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .extent = (VkExtent3D) { dmabuf->width, dmabuf->height, 1 }, + .usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, + }; + + res = vkCreateImage(dev, &img_info, NULL, &buffer->two_pass.blend_image); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateImage failed", res); + goto error; + } + + VkMemoryRequirements mem_reqs; + vkGetImageMemoryRequirements(dev, buffer->two_pass.blend_image, &mem_reqs); + + int mem_type_index = vulkan_find_mem_type(renderer->dev, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, mem_reqs.memoryTypeBits); + if (mem_type_index == -1) { + wlr_log(WLR_ERROR, "failed to find suitable vulkan memory type"); + goto error; + } + + VkMemoryAllocateInfo mem_info = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = mem_reqs.size, + .memoryTypeIndex = mem_type_index, + }; + + res = vkAllocateMemory(dev, &mem_info, NULL, &buffer->two_pass.blend_memory); + if (res != VK_SUCCESS) { + wlr_vk_error("vkAllocatorMemory failed", res); + goto error; + } + + res = vkBindImageMemory(dev, buffer->two_pass.blend_image, buffer->two_pass.blend_memory, 0); + if (res != VK_SUCCESS) { + wlr_vk_error("vkBindMemory failed", res); + goto error; + } + + VkImageViewCreateInfo blend_view_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, + .image = buffer->two_pass.blend_image, + .viewType = VK_IMAGE_VIEW_TYPE_2D, + .format = img_info.format, + .components.r = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.g = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.b = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.a = VK_COMPONENT_SWIZZLE_IDENTITY, + .subresourceRange = (VkImageSubresourceRange) { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }; + + res = vkCreateImageView(dev, &blend_view_info, NULL, &buffer->two_pass.blend_image_view); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateImageView failed", res); + goto error; + } + + buffer->two_pass.blend_attachment_pool = vulkan_alloc_blend_ds(renderer, + &buffer->two_pass.blend_descriptor_set); + if (!buffer->two_pass.blend_attachment_pool) { + wlr_log(WLR_ERROR, "failed to allocate descriptor"); + goto error; + } + + VkDescriptorImageInfo ds_attach_info = { + .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + .imageView = buffer->two_pass.blend_image_view, + .sampler = VK_NULL_HANDLE, + }; + VkWriteDescriptorSet ds_write = { + .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, + .dstSet = buffer->two_pass.blend_descriptor_set, + .dstBinding = 0, + .pImageInfo = &ds_attach_info, + }; + vkUpdateDescriptorSets(dev, 1, &ds_write, 0, NULL); + + VkImageView attachments[] = { + buffer->two_pass.blend_image_view, + buffer->two_pass.out.image_view, + }; + VkFramebufferCreateInfo fb_info = { + .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, + .attachmentCount = sizeof(attachments) / sizeof(attachments[0]), + .pAttachments = attachments, + .flags = 0u, + .width = dmabuf->width, + .height = dmabuf->height, + .layers = 1u, + .renderPass = buffer->two_pass.render_setup->render_pass, + }; + + res = vkCreateFramebuffer(dev, &fb_info, NULL, &buffer->two_pass.out.framebuffer); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateFramebuffer", res); + goto error; + } + + return true; + +error: + // cleaning up everything is the caller's responsibility, + // since it will need to do this anyway if framebuffer setup fails + return false; +} + +bool vulkan_setup_one_pass_framebuffer(struct wlr_vk_render_buffer *buffer, + const struct wlr_dmabuf_attributes *dmabuf, bool srgb) { + struct wlr_vk_renderer *renderer = buffer->renderer; + VkResult res; + VkDevice dev = renderer->dev->dev; + + const struct wlr_vk_format_props *fmt = vulkan_format_props_from_drm( + renderer->dev, dmabuf->format); + assert(fmt); + + VkFormat vk_fmt = srgb ? fmt->format.vk_srgb : fmt->format.vk; + assert(vk_fmt != VK_FORMAT_UNDEFINED); + + struct wlr_vk_render_buffer_out *out = srgb ? &buffer->srgb.out : &buffer->linear.out; + + // Set up the srgb framebuffer by default; two-pass framebuffer and + // blending image will be set up later if necessary + VkImageViewCreateInfo view_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, + .image = buffer->image, + .viewType = VK_IMAGE_VIEW_TYPE_2D, + .format = vk_fmt, + .components.r = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.g = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.b = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.a = VK_COMPONENT_SWIZZLE_IDENTITY, + .subresourceRange = (VkImageSubresourceRange) { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + }; + + res = vkCreateImageView(dev, &view_info, NULL, &out->image_view); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateImageView failed", res); + goto error; + } + + struct wlr_vk_render_format_setup *render_setup = + find_or_create_render_setup(renderer, &fmt->format, false, srgb); + if (!render_setup) { + goto error; + } + + VkFramebufferCreateInfo fb_info = { + .sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, + .attachmentCount = 1, + .pAttachments = &out->image_view, + .flags = 0u, + .width = dmabuf->width, + .height = dmabuf->height, + .layers = 1u, + .renderPass = render_setup->render_pass, + }; + + res = vkCreateFramebuffer(dev, &fb_info, NULL, &out->framebuffer); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateFramebuffer", res); + goto error; + } + + if (srgb) { + buffer->srgb.render_setup = render_setup; + } else { + buffer->linear.render_setup = render_setup; + } + + return true; + +error: + // cleaning up everything is the caller's responsibility, + // since it will need to do this anyway if framebuffer setup fails + return false; +} + +static struct wlr_vk_render_buffer *create_render_buffer( + struct wlr_vk_renderer *renderer, struct wlr_buffer *wlr_buffer) { + struct wlr_vk_render_buffer *buffer = calloc(1, sizeof(*buffer)); + if (buffer == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + buffer->wlr_buffer = wlr_buffer; + buffer->renderer = renderer; + wlr_addon_init(&buffer->addon, &wlr_buffer->addons, renderer, + &render_buffer_addon_impl); + wl_list_insert(&renderer->render_buffers, &buffer->link); + + struct wlr_dmabuf_attributes dmabuf = {0}; + if (!wlr_buffer_get_dmabuf(wlr_buffer, &dmabuf)) { + goto error; + } + + wlr_log(WLR_DEBUG, "vulkan create_render_buffer: %.4s, %dx%d", + (const char*) &dmabuf.format, dmabuf.width, dmabuf.height); + + bool using_mutable_srgb = false; + buffer->image = vulkan_import_dmabuf(renderer, &dmabuf, + buffer->memories, &buffer->mem_count, true, &using_mutable_srgb); + if (!buffer->image) { + goto error; + } + + const struct wlr_vk_format_props *fmt = vulkan_format_props_from_drm( + renderer->dev, dmabuf.format); + if (fmt == NULL) { + wlr_log(WLR_ERROR, "Unsupported pixel format %"PRIx32 " (%.4s)", + dmabuf.format, (const char*) &dmabuf.format); + goto error; + } + + if (using_mutable_srgb) { + if (!vulkan_setup_one_pass_framebuffer(buffer, &dmabuf, true)) { + goto error; + } + } else { + // Set up the two-pass framebuffer & blending image + if (!vulkan_setup_two_pass_framebuffer(buffer, &dmabuf)) { + goto error; + } + } + + return buffer; + +error: + if (buffer) { + destroy_render_buffer(buffer); + } + + wlr_dmabuf_attributes_finish(&dmabuf); + return NULL; +} + +static struct wlr_vk_render_buffer *get_render_buffer( + struct wlr_vk_renderer *renderer, struct wlr_buffer *wlr_buffer) { + struct wlr_addon *addon = + wlr_addon_find(&wlr_buffer->addons, renderer, &render_buffer_addon_impl); + if (addon == NULL) { + return NULL; + } + + struct wlr_vk_render_buffer *buffer = wl_container_of(addon, buffer, addon); + return buffer; +} + +static struct wlr_vk_render_buffer *get_or_create_render_buffer( + struct wlr_vk_renderer *renderer, struct wlr_buffer *wlr_buffer) { + struct wlr_vk_render_buffer *render_buffer = + get_render_buffer(renderer, wlr_buffer); + if (render_buffer != NULL) { + return render_buffer; + } + return create_render_buffer(renderer, wlr_buffer); +} + +bool waylib_vk_renderer_get_render_buffer_attribs(struct wlr_renderer *wlr_renderer, + struct wlr_buffer *wlr_buffer, struct wlr_vk_image_attribs *attribs) { + if (wlr_renderer == NULL || wlr_buffer == NULL || attribs == NULL) { + return false; + } + if (!wlr_renderer_is_vk(wlr_renderer)) { + return false; + } + + struct wlr_vk_renderer *renderer = vulkan_get_renderer(wlr_renderer); + struct wlr_vk_render_buffer *render_buffer = + get_or_create_render_buffer(renderer, wlr_buffer); + if (render_buffer == NULL) { + return false; + } + + struct wlr_dmabuf_attributes dmabuf = {0}; + if (!wlr_buffer_get_dmabuf(wlr_buffer, &dmabuf)) { + wlr_log(WLR_ERROR, "wlr_buffer_get_dmabuf failed"); + return false; + } + + const struct wlr_vk_format *format = vulkan_get_format_from_drm(dmabuf.format); + if (format == NULL) { + wlr_log(WLR_ERROR, "Unsupported pixel format %"PRIx32 " (%.4s)", + dmabuf.format, (const char *)&dmabuf.format); + return false; + } + + attribs->image = render_buffer->image; + attribs->layout = VK_IMAGE_LAYOUT_GENERAL; + attribs->format = format->vk; + return true; +} + +bool waylib_vk_renderer_record_render_buffer_acquire(struct wlr_renderer *wlr_renderer, + struct wlr_buffer *wlr_buffer, VkCommandBuffer cb) { + if (wlr_renderer == NULL || wlr_buffer == NULL || cb == VK_NULL_HANDLE) { + return false; + } + if (!wlr_renderer_is_vk(wlr_renderer)) { + return false; + } + + struct wlr_vk_renderer *renderer = vulkan_get_renderer(wlr_renderer); + struct wlr_vk_render_buffer *render_buffer = + get_or_create_render_buffer(renderer, wlr_buffer); + if (render_buffer == NULL) { + return false; + } + + /* Match wlroots pass.c / tinywl: foreign ownership transfer into the + * graphics queue before writing the scanout image. */ + VkImageLayout src_layout = VK_IMAGE_LAYOUT_GENERAL; + if (!render_buffer->linear.out.transitioned && + !render_buffer->srgb.out.transitioned && + !render_buffer->two_pass.out.transitioned) { + src_layout = VK_IMAGE_LAYOUT_PREINITIALIZED; + } + // All output pathways share the imported VkImage. Once this acquire + // barrier runs, each pathway observes GENERAL on subsequent use. + render_buffer->linear.out.transitioned = true; + render_buffer->srgb.out.transitioned = true; + render_buffer->two_pass.out.transitioned = true; + + VkImageMemoryBarrier barrier = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, + .dstQueueFamilyIndex = renderer->dev->queue_family, + .image = render_buffer->image, + .oldLayout = src_layout, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .srcAccessMask = 0, + .dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .subresourceRange.layerCount = 1, + .subresourceRange.levelCount = 1, + }; + + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + 0, 0, NULL, 0, NULL, 1, &barrier); + return true; +} + +bool waylib_vk_renderer_record_render_buffer_release(struct wlr_renderer *wlr_renderer, + struct wlr_buffer *wlr_buffer, VkCommandBuffer cb, + VkImageLayout old_layout) { + if (wlr_renderer == NULL || wlr_buffer == NULL || cb == VK_NULL_HANDLE) { + return false; + } + if (!wlr_renderer_is_vk(wlr_renderer)) { + return false; + } + + struct wlr_vk_renderer *renderer = vulkan_get_renderer(wlr_renderer); + struct wlr_vk_render_buffer *render_buffer = + get_render_buffer(renderer, wlr_buffer); + if (render_buffer == NULL) { + return false; + } + + VkImageMemoryBarrier barrier = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .srcQueueFamilyIndex = renderer->dev->queue_family, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, + .image = render_buffer->image, + .oldLayout = old_layout, + .newLayout = VK_IMAGE_LAYOUT_GENERAL, + .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dstAccessMask = 0, + .subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .subresourceRange.layerCount = 1, + .subresourceRange.levelCount = 1, + }; + + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, 0, NULL, 0, NULL, 1, &barrier); + return true; +} + +static bool buffer_export_sync_file(struct wlr_vk_renderer *renderer, struct wlr_buffer *buffer, + uint32_t flags, int sync_file_fds[static WLR_DMABUF_MAX_PLANES]) { + struct wlr_dmabuf_attributes dmabuf = {0}; + if (!wlr_buffer_get_dmabuf(buffer, &dmabuf)) { + wlr_log(WLR_ERROR, "wlr_buffer_get_dmabuf() failed"); + return false; + } + + if (!renderer->dev->implicit_sync_interop) { + // We have no choice but to block here sadly + + for (int i = 0; i < dmabuf.n_planes; i++) { + struct pollfd pollfd = { + .fd = dmabuf.fd[i], + .events = (flags & DMA_BUF_SYNC_WRITE) ? POLLOUT : POLLIN, + }; + int timeout_ms = 1000; + int ret = poll(&pollfd, 1, timeout_ms); + if (ret < 0) { + wlr_log_errno(WLR_ERROR, "Failed to wait for DMA-BUF fence"); + return false; + } else if (ret == 0) { + wlr_log(WLR_ERROR, "Timed out while waiting for DMA-BUF fence"); + return false; + } + } + + return true; + } + + for (int i = 0; i < dmabuf.n_planes; i++) { + int sync_file_fd = dmabuf_export_sync_file(dmabuf.fd[i], flags); + if (sync_file_fd < 0) { + wlr_log(WLR_ERROR, "Failed to extract DMA-BUF fence"); + return false; + } + + sync_file_fds[i] = sync_file_fd; + } + + return true; +} + +bool vulkan_sync_foreign_texture_acquire(struct wlr_vk_texture *texture, + int sync_file_fds[static WLR_DMABUF_MAX_PLANES]) { + return buffer_export_sync_file(texture->renderer, texture->buffer, DMA_BUF_SYNC_READ, sync_file_fds); +} + +bool vulkan_sync_render_buffer_acquire(struct wlr_vk_render_buffer *render_buffer, + int sync_file_fds[static WLR_DMABUF_MAX_PLANES]) { + return buffer_export_sync_file(render_buffer->renderer, render_buffer->wlr_buffer, + DMA_BUF_SYNC_WRITE, sync_file_fds); +} + +static bool buffer_import_sync_file(struct wlr_buffer *buffer, uint32_t flags, int sync_file_fd) { + struct wlr_dmabuf_attributes dmabuf = {0}; + if (!wlr_buffer_get_dmabuf(buffer, &dmabuf)) { + wlr_log(WLR_ERROR, "wlr_buffer_get_dmabuf() failed"); + return false; + } + + for (int i = 0; i < dmabuf.n_planes; i++) { + if (!dmabuf_import_sync_file(dmabuf.fd[i], flags, + sync_file_fd)) { + return false; + } + } + + return true; +} + +bool vulkan_sync_render_pass_release(struct wlr_vk_renderer *renderer, + struct wlr_vk_render_pass *pass) { + VkResult res; + struct wlr_vk_command_buffer *cb = pass->command_buffer; + + if (!renderer->dev->implicit_sync_interop && pass->signal_timeline == NULL) { + // We have no choice but to block here sadly + return vulkan_wait_command_buffer(cb, renderer); + } + + assert(cb->binary_semaphore != VK_NULL_HANDLE); + + // Note: vkGetSemaphoreFdKHR implicitly resets the semaphore + const VkSemaphoreGetFdInfoKHR get_fence_fd_info = { + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR, + .semaphore = cb->binary_semaphore, + .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT, + }; + int sync_file_fd = -1; + res = renderer->dev->api.vkGetSemaphoreFdKHR(renderer->dev->dev, + &get_fence_fd_info, &sync_file_fd); + if (res != VK_SUCCESS) { + wlr_vk_error("vkGetSemaphoreFdKHR", res); + return false; + } + + bool ok = false; + if (pass->signal_timeline != NULL) { + if (!wlr_drm_syncobj_timeline_import_sync_file(pass->signal_timeline, + pass->signal_point, sync_file_fd)) { + goto out; + } + } else { + if (!buffer_import_sync_file(pass->render_buffer->wlr_buffer, DMA_BUF_SYNC_WRITE, sync_file_fd)) { + goto out; + } + + struct wlr_vk_render_pass_texture *pass_texture; + wl_array_for_each(pass_texture, &pass->textures) { + if (!buffer_import_sync_file(pass_texture->texture->buffer, DMA_BUF_SYNC_READ, sync_file_fd)) { + goto out; + } + } + } + + ok = true; + +out: + close(sync_file_fd); + return ok; +} + +static const struct wlr_drm_format_set *vulkan_get_texture_formats( + struct wlr_renderer *wlr_renderer, uint32_t buffer_caps) { + struct wlr_vk_renderer *renderer = vulkan_get_renderer(wlr_renderer); + if (buffer_caps & WLR_BUFFER_CAP_DMABUF) { + return &renderer->dev->dmabuf_texture_formats; + } else if (buffer_caps & WLR_BUFFER_CAP_DATA_PTR) { + return &renderer->dev->shm_texture_formats; + } else { + return NULL; + } +} + +static const struct wlr_drm_format_set *vulkan_get_render_formats( + struct wlr_renderer *wlr_renderer) { + struct wlr_vk_renderer *renderer = vulkan_get_renderer(wlr_renderer); + return &renderer->dev->dmabuf_render_formats; +} + +static void vulkan_destroy(struct wlr_renderer *wlr_renderer) { + struct wlr_vk_renderer *renderer = vulkan_get_renderer(wlr_renderer); + struct wlr_vk_device *dev = renderer->dev; + if (!dev) { + free(renderer); + return; + } + + VkResult res = vkDeviceWaitIdle(renderer->dev->dev); + if (res != VK_SUCCESS) { + wlr_vk_error("vkDeviceWaitIdle", res); + } + + for (size_t i = 0; i < VULKAN_COMMAND_BUFFERS_CAP; i++) { + struct wlr_vk_command_buffer *cb = &renderer->command_buffers[i]; + if (cb->vk == VK_NULL_HANDLE) { + continue; + } + release_command_buffer_resources(cb, renderer, 0); + if (cb->binary_semaphore != VK_NULL_HANDLE) { + vkDestroySemaphore(renderer->dev->dev, cb->binary_semaphore, NULL); + } + VkSemaphore *sem_ptr; + wl_array_for_each(sem_ptr, &cb->wait_semaphores) { + vkDestroySemaphore(renderer->dev->dev, *sem_ptr, NULL); + } + wl_array_release(&cb->wait_semaphores); + } + + // stage.cb automatically freed with command pool + struct wlr_vk_shared_buffer *buf, *tmp_buf; + wl_list_for_each_safe(buf, tmp_buf, &renderer->stage.buffers, link) { + shared_buffer_destroy(renderer, buf); + } + + struct wlr_vk_texture *tex, *tex_tmp; + wl_list_for_each_safe(tex, tex_tmp, &renderer->textures, link) { + vulkan_texture_destroy(tex); + } + + struct wlr_vk_render_buffer *render_buffer, *render_buffer_tmp; + wl_list_for_each_safe(render_buffer, render_buffer_tmp, + &renderer->render_buffers, link) { + destroy_render_buffer(render_buffer); + } + + struct wlr_vk_color_transform *color_transform, *color_transform_tmp; + wl_list_for_each_safe(color_transform, color_transform_tmp, + &renderer->color_transforms, link) { + vk_color_transform_destroy(&color_transform->addon); + } + + struct wlr_vk_render_format_setup *setup, *tmp_setup; + wl_list_for_each_safe(setup, tmp_setup, + &renderer->render_format_setups, link) { + destroy_render_format_setup(renderer, setup); + } + + struct wlr_vk_descriptor_pool *pool, *tmp_pool; + wl_list_for_each_safe(pool, tmp_pool, &renderer->descriptor_pools, link) { + vkDestroyDescriptorPool(dev->dev, pool->pool, NULL); + free(pool); + } + wl_list_for_each_safe(pool, tmp_pool, &renderer->output_descriptor_pools, link) { + vkDestroyDescriptorPool(dev->dev, pool->pool, NULL); + free(pool); + } + + vkDestroyShaderModule(dev->dev, renderer->vert_module, NULL); + vkDestroyShaderModule(dev->dev, renderer->tex_frag_module, NULL); + vkDestroyShaderModule(dev->dev, renderer->quad_frag_module, NULL); + vkDestroyShaderModule(dev->dev, renderer->output_module, NULL); + + struct wlr_vk_pipeline_layout *pipeline_layout, *pipeline_layout_tmp; + wl_list_for_each_safe(pipeline_layout, pipeline_layout_tmp, + &renderer->pipeline_layouts, link) { + vkDestroyPipelineLayout(dev->dev, pipeline_layout->vk, NULL); + vkDestroyDescriptorSetLayout(dev->dev, pipeline_layout->ds, NULL); + vkDestroySampler(dev->dev, pipeline_layout->sampler, NULL); + vkDestroySamplerYcbcrConversion(dev->dev, pipeline_layout->ycbcr.conversion, NULL); + free(pipeline_layout); + } + + vkDestroyImageView(dev->dev, renderer->dummy3d_image_view, NULL); + vkDestroyImage(dev->dev, renderer->dummy3d_image, NULL); + vkFreeMemory(dev->dev, renderer->dummy3d_mem, NULL); + + vkDestroySemaphore(dev->dev, renderer->timeline_semaphore, NULL); + vkDestroyPipelineLayout(dev->dev, renderer->output_pipe_layout, NULL); + vkDestroyDescriptorSetLayout(dev->dev, renderer->output_ds_srgb_layout, NULL); + vkDestroyDescriptorSetLayout(dev->dev, renderer->output_ds_lut3d_layout, NULL); + vkDestroyCommandPool(dev->dev, renderer->command_pool, NULL); + vkDestroySampler(dev->dev, renderer->output_sampler_lut3d, NULL); + + if (renderer->read_pixels_cache.initialized) { + vkFreeMemory(dev->dev, renderer->read_pixels_cache.dst_img_memory, NULL); + vkDestroyImage(dev->dev, renderer->read_pixels_cache.dst_image, NULL); + } + + struct wlr_vk_instance *ini = dev->instance; + vulkan_device_destroy(dev); + vulkan_instance_destroy(ini); + free(renderer); +} + +bool vulkan_read_pixels(struct wlr_vk_renderer *vk_renderer, + VkFormat src_format, VkImage src_image, + uint32_t drm_format, uint32_t stride, + uint32_t width, uint32_t height, uint32_t src_x, uint32_t src_y, + uint32_t dst_x, uint32_t dst_y, void *data) { + VkDevice dev = vk_renderer->dev->dev; + + const struct wlr_pixel_format_info *pixel_format_info = drm_get_pixel_format_info(drm_format); + if (!pixel_format_info) { + wlr_log(WLR_ERROR, "vulkan_read_pixels: could not find pixel format info " + "for DRM format 0x%08x", drm_format); + return false; + } else if (pixel_format_info_pixels_per_block(pixel_format_info) != 1) { + wlr_log(WLR_ERROR, "vulkan_read_pixels: block formats are not supported"); + return false; + } + + const struct wlr_vk_format *wlr_vk_format = vulkan_get_format_from_drm(drm_format); + if (!wlr_vk_format) { + wlr_log(WLR_ERROR, "vulkan_read_pixels: no vulkan format " + "matching drm format 0x%08x available", drm_format); + return false; + } + VkFormat dst_format = wlr_vk_format->vk; + VkFormatProperties dst_format_props = {0}, src_format_props = {0}; + vkGetPhysicalDeviceFormatProperties(vk_renderer->dev->phdev, dst_format, &dst_format_props); + vkGetPhysicalDeviceFormatProperties(vk_renderer->dev->phdev, src_format, &src_format_props); + + bool blit_supported = src_format_props.optimalTilingFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT && + dst_format_props.linearTilingFeatures & VK_FORMAT_FEATURE_BLIT_DST_BIT; + if (!blit_supported && src_format != dst_format) { + wlr_log(WLR_ERROR, "vulkan_read_pixels: blit unsupported and no manual " + "conversion available from src to dst format."); + return false; + } + + VkResult res; + VkImage dst_image; + VkDeviceMemory dst_img_memory; + bool use_cached = vk_renderer->read_pixels_cache.initialized && + vk_renderer->read_pixels_cache.drm_format == drm_format && + vk_renderer->read_pixels_cache.width == width && + vk_renderer->read_pixels_cache.height == height; + + if (use_cached) { + dst_image = vk_renderer->read_pixels_cache.dst_image; + dst_img_memory = vk_renderer->read_pixels_cache.dst_img_memory; + } else { + VkImageCreateInfo image_create_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, + .imageType = VK_IMAGE_TYPE_2D, + .format = dst_format, + .extent.width = width, + .extent.height = height, + .extent.depth = 1, + .arrayLayers = 1, + .mipLevels = 1, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .samples = VK_SAMPLE_COUNT_1_BIT, + .tiling = VK_IMAGE_TILING_LINEAR, + .usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT + }; + res = vkCreateImage(dev, &image_create_info, NULL, &dst_image); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateImage", res); + return false; + } + + VkMemoryRequirements mem_reqs; + vkGetImageMemoryRequirements(dev, dst_image, &mem_reqs); + + int mem_type = vulkan_find_mem_type(vk_renderer->dev, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | + VK_MEMORY_PROPERTY_HOST_CACHED_BIT, + mem_reqs.memoryTypeBits); + if (mem_type < 0) { + wlr_log(WLR_ERROR, "vulkan_read_pixels: could not find adequate memory type"); + goto destroy_image; + } + + VkMemoryAllocateInfo mem_alloc_info = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + }; + mem_alloc_info.allocationSize = mem_reqs.size; + mem_alloc_info.memoryTypeIndex = mem_type; + + res = vkAllocateMemory(dev, &mem_alloc_info, NULL, &dst_img_memory); + if (res != VK_SUCCESS) { + wlr_vk_error("vkAllocateMemory", res); + goto destroy_image; + } + res = vkBindImageMemory(dev, dst_image, dst_img_memory, 0); + if (res != VK_SUCCESS) { + wlr_vk_error("vkBindImageMemory", res); + goto free_memory; + } + + if (vk_renderer->read_pixels_cache.initialized) { + vkFreeMemory(dev, vk_renderer->read_pixels_cache.dst_img_memory, NULL); + vkDestroyImage(dev, vk_renderer->read_pixels_cache.dst_image, NULL); + } + vk_renderer->read_pixels_cache.initialized = true; + vk_renderer->read_pixels_cache.drm_format = drm_format; + vk_renderer->read_pixels_cache.dst_image = dst_image; + vk_renderer->read_pixels_cache.dst_img_memory = dst_img_memory; + vk_renderer->read_pixels_cache.width = width; + vk_renderer->read_pixels_cache.height = height; + } + + VkCommandBuffer cb = vulkan_record_stage_cb(vk_renderer); + if (cb == VK_NULL_HANDLE) { + return false; + } + + vulkan_change_layout(cb, dst_image, + VK_IMAGE_LAYOUT_UNDEFINED, + VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_WRITE_BIT); + vulkan_change_layout(cb, src_image, + VK_IMAGE_LAYOUT_GENERAL, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_MEMORY_READ_BIT, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_READ_BIT); + + if (blit_supported) { + VkImageBlit image_blit_region = { + .srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .srcSubresource.layerCount = 1, + .srcOffsets[0] = { + .x = src_x, + .y = src_y, + .z = 0, + }, + .srcOffsets[1] = { + .x = src_x + width, + .y = src_y + height, + .z = 1, + }, + .dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .dstSubresource.layerCount = 1, + .dstOffsets[1] = { + .x = width, + .y = height, + .z = 1, + } + }; + vkCmdBlitImage(cb, src_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + dst_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + 1, &image_blit_region, VK_FILTER_NEAREST); + } else { + wlr_log(WLR_DEBUG, "vulkan_read_pixels: blit unsupported, falling back to vkCmdCopyImage."); + VkImageCopy image_region = { + .srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .srcSubresource.layerCount = 1, + .srcOffset = { + .x = src_x, + .y = src_y, + }, + .dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .dstSubresource.layerCount = 1, + .extent = { + .width = width, + .height = height, + .depth = 1, + } + }; + vkCmdCopyImage(cb, src_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + dst_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &image_region); + } + + vulkan_change_layout(cb, dst_image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_WRITE_BIT, + VK_IMAGE_LAYOUT_GENERAL, + VK_PIPELINE_STAGE_TRANSFER_BIT, + 0); + vulkan_change_layout(cb, src_image, + VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_READ_BIT, + VK_IMAGE_LAYOUT_GENERAL, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_MEMORY_READ_BIT); + + if (!vulkan_submit_stage_wait(vk_renderer)) { + return false; + } + + VkImageSubresource img_sub_res = { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .arrayLayer = 0, + .mipLevel = 0 + }; + VkSubresourceLayout img_sub_layout; + vkGetImageSubresourceLayout(dev, dst_image, &img_sub_res, &img_sub_layout); + + void *v; + res = vkMapMemory(dev, dst_img_memory, 0, VK_WHOLE_SIZE, 0, &v); + if (res != VK_SUCCESS) { + wlr_vk_error("vkMapMemory", res); + return false; + } + + VkMappedMemoryRange mem_range = { + .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, + .memory = dst_img_memory, + .offset = 0, + .size = VK_WHOLE_SIZE, + }; + res = vkInvalidateMappedMemoryRanges(dev, 1, &mem_range); + if (res != VK_SUCCESS) { + wlr_vk_error("vkInvalidateMappedMemoryRanges", res); + vkUnmapMemory(dev, dst_img_memory); + return false; + } + + const char *d = (const char *)v + img_sub_layout.offset; + unsigned char *p = (unsigned char *)data + dst_y * stride; + uint32_t bytes_per_pixel = pixel_format_info->bytes_per_block; + uint32_t pack_stride = img_sub_layout.rowPitch; + if (pack_stride == stride && dst_x == 0) { + memcpy(p, d, height * stride); + } else { + for (size_t i = 0; i < height; ++i) { + memcpy(p + i * stride + dst_x * bytes_per_pixel, d + i * pack_stride, width * bytes_per_pixel); + } + } + + vkUnmapMemory(dev, dst_img_memory); + // Don't need to free anything else, since memory and image are cached + return true; + +free_memory: + vkFreeMemory(dev, dst_img_memory, NULL); +destroy_image: + vkDestroyImage(dev, dst_image, NULL); + + return false; +} + +static int vulkan_get_drm_fd(struct wlr_renderer *wlr_renderer) { + struct wlr_vk_renderer *renderer = vulkan_get_renderer(wlr_renderer); + return renderer->dev->drm_fd; +} + +static struct wlr_render_pass *vulkan_begin_buffer_pass(struct wlr_renderer *wlr_renderer, + struct wlr_buffer *buffer, const struct wlr_buffer_pass_options *options) { + struct wlr_vk_renderer *renderer = vulkan_get_renderer(wlr_renderer); + + struct wlr_vk_render_buffer *render_buffer = get_render_buffer(renderer, buffer); + if (!render_buffer) { + render_buffer = create_render_buffer(renderer, buffer); + if (!render_buffer) { + return NULL; + } + } + + struct wlr_vk_render_pass *render_pass = vulkan_begin_render_pass( + renderer, render_buffer, options); + if (render_pass == NULL) { + return NULL; + } + return &render_pass->base; +} + +static const struct wlr_renderer_impl renderer_impl = { + .get_texture_formats = vulkan_get_texture_formats, + .get_render_formats = vulkan_get_render_formats, + .destroy = vulkan_destroy, + .get_drm_fd = vulkan_get_drm_fd, + .texture_from_buffer = vulkan_texture_from_buffer, + .begin_buffer_pass = vulkan_begin_buffer_pass, +}; + +// Initializes the VkDescriptorSetLayout and VkPipelineLayout needed +// for the texture rendering pipeline using the given VkSampler. +static bool init_tex_layouts(struct wlr_vk_renderer *renderer, + VkSampler tex_sampler, VkDescriptorSetLayout *out_ds_layout, + VkPipelineLayout *out_pipe_layout) { + VkResult res; + VkDevice dev = renderer->dev->dev; + + VkDescriptorSetLayoutBinding ds_binding = { + .binding = 0, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, + .pImmutableSamplers = &tex_sampler, + }; + + VkDescriptorSetLayoutCreateInfo ds_info = { + .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + .bindingCount = 1, + .pBindings = &ds_binding, + }; + + res = vkCreateDescriptorSetLayout(dev, &ds_info, NULL, out_ds_layout); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateDescriptorSetLayout", res); + return false; + } + + VkPushConstantRange pc_ranges[] = { + { + .size = sizeof(struct wlr_vk_vert_pcr_data), + .stageFlags = VK_SHADER_STAGE_VERTEX_BIT, + }, + { + .offset = pc_ranges[0].size, + .size = sizeof(struct wlr_vk_frag_texture_pcr_data), + .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, + }, + }; + + VkPipelineLayoutCreateInfo pl_info = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, + .setLayoutCount = 1, + .pSetLayouts = out_ds_layout, + .pushConstantRangeCount = sizeof(pc_ranges) / sizeof(pc_ranges[0]), + .pPushConstantRanges = pc_ranges, + }; + + res = vkCreatePipelineLayout(dev, &pl_info, NULL, out_pipe_layout); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreatePipelineLayout", res); + return false; + } + + return true; +} + +static bool init_blend_to_output_layouts(struct wlr_vk_renderer *renderer) { + VkResult res; + VkDevice dev = renderer->dev->dev; + + VkDescriptorSetLayoutBinding ds_binding_input = { + .binding = 0, + .descriptorType = VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, + .pImmutableSamplers = NULL, + }; + + VkDescriptorSetLayoutCreateInfo ds_info = { + .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + .bindingCount = 1, + .pBindings = &ds_binding_input, + }; + + res = vkCreateDescriptorSetLayout(dev, &ds_info, NULL, &renderer->output_ds_srgb_layout); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateDescriptorSetLayout", res); + return false; + } + + VkSamplerCreateInfo sampler_create_info = { + .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, + .magFilter = VK_FILTER_LINEAR, + .minFilter = VK_FILTER_LINEAR, + .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST, + .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .minLod = 0.f, + .maxLod = 0.25f, + }; + + res = vkCreateSampler(renderer->dev->dev, &sampler_create_info, NULL, + &renderer->output_sampler_lut3d); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateSampler", res); + return false; + } + + VkDescriptorSetLayoutBinding ds_binding_lut3d = { + .binding = 0, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .descriptorCount = 1, + .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, + .pImmutableSamplers = &renderer->output_sampler_lut3d, + }; + + VkDescriptorSetLayoutCreateInfo ds_lut3d_info = { + .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + .bindingCount = 1, + .pBindings = &ds_binding_lut3d, + }; + + res = vkCreateDescriptorSetLayout(dev, &ds_lut3d_info, NULL, + &renderer->output_ds_lut3d_layout); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateDescriptorSetLayout", res); + return false; + } + + // pipeline layout -- standard vertex uniforms, no shader uniforms + VkPushConstantRange pc_ranges[] = { + { + .offset = 0, + .size = sizeof(struct wlr_vk_vert_pcr_data), + .stageFlags = VK_SHADER_STAGE_VERTEX_BIT, + }, + { + .offset = sizeof(struct wlr_vk_vert_pcr_data), + .size = sizeof(struct wlr_vk_frag_output_pcr_data), + .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT, + }, + }; + + VkDescriptorSetLayout out_ds_layouts[] = { + renderer->output_ds_srgb_layout, + renderer->output_ds_lut3d_layout, + }; + + VkPipelineLayoutCreateInfo pl_info = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, + .setLayoutCount = sizeof(out_ds_layouts) / sizeof(out_ds_layouts[0]), + .pSetLayouts = out_ds_layouts, + .pushConstantRangeCount = sizeof(pc_ranges) / sizeof(pc_ranges[0]), + .pPushConstantRanges = pc_ranges, + }; + + res = vkCreatePipelineLayout(dev, &pl_info, NULL, &renderer->output_pipe_layout); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreatePipelineLayout", res); + return false; + } + + return true; +} + +static bool pipeline_layout_key_equals( + const struct wlr_vk_pipeline_layout_key *a, + const struct wlr_vk_pipeline_layout_key *b) { + assert(!a->ycbcr.format || vulkan_format_is_ycbcr(a->ycbcr.format)); + assert(!b->ycbcr.format || vulkan_format_is_ycbcr(b->ycbcr.format)); + + if (a->filter_mode != b->filter_mode) { + return false; + } + + if (a->ycbcr.format != b->ycbcr.format || + a->ycbcr.encoding != b->ycbcr.encoding || + a->ycbcr.range != b->ycbcr.range) { + return false; + } + + return true; +} + +static bool pipeline_key_equals(const struct wlr_vk_pipeline_key *a, + const struct wlr_vk_pipeline_key *b) { + if (!pipeline_layout_key_equals(&a->layout, &b->layout)) { + return false; + } + + if (a->blend_mode != b->blend_mode) { + return false; + } + + if (a->source != b->source) { + return false; + } + + if (a->source == WLR_VK_SHADER_SOURCE_TEXTURE && + a->texture_transform != b->texture_transform) { + return false; + } + + return true; +} + +// Initializes the pipeline for rendering textures and using the given +// VkRenderPass and VkPipelineLayout. +struct wlr_vk_pipeline *setup_get_or_create_pipeline( + struct wlr_vk_render_format_setup *setup, + const struct wlr_vk_pipeline_key *key) { + struct wlr_vk_pipeline *pipeline; + wl_list_for_each(pipeline, &setup->pipelines, link) { + if (pipeline_key_equals(&pipeline->key, key)) { + return pipeline; + } + } + + struct wlr_vk_renderer *renderer = setup->renderer; + + struct wlr_vk_pipeline_layout *pipeline_layout = get_or_create_pipeline_layout( + renderer, &key->layout); + if (!pipeline_layout) { + return NULL; + } + + pipeline = calloc(1, sizeof(*pipeline)); + if (!pipeline) { + return NULL; + } + + pipeline->setup = setup; + pipeline->key = *key; + pipeline->layout = pipeline_layout; + + VkResult res; + VkDevice dev = renderer->dev->dev; + + uint32_t color_transform_type = key->texture_transform; + + VkSpecializationMapEntry spec_entry = { + .constantID = 0, + .offset = 0, + .size = sizeof(uint32_t), + }; + + VkSpecializationInfo specialization = { + .mapEntryCount = 1, + .pMapEntries = &spec_entry, + .dataSize = sizeof(uint32_t), + .pData = &color_transform_type, + }; + + VkPipelineShaderStageCreateInfo stages[2]; + stages[0] = (VkPipelineShaderStageCreateInfo) { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_VERTEX_BIT, + .module = renderer->vert_module, + .pName = "main", + }; + + switch (key->source) { + case WLR_VK_SHADER_SOURCE_SINGLE_COLOR: + stages[1] = (VkPipelineShaderStageCreateInfo) { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_FRAGMENT_BIT, + .module = renderer->quad_frag_module, + .pName = "main", + }; + break; + case WLR_VK_SHADER_SOURCE_TEXTURE: + stages[1] = (VkPipelineShaderStageCreateInfo) { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_FRAGMENT_BIT, + .module = renderer->tex_frag_module, + .pName = "main", + .pSpecializationInfo = &specialization, + }; + break; + } + + VkPipelineInputAssemblyStateCreateInfo assembly = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, + .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, + }; + + VkPipelineRasterizationStateCreateInfo rasterization = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, + .polygonMode = VK_POLYGON_MODE_FILL, + .cullMode = VK_CULL_MODE_NONE, + .frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE, + .lineWidth = 1.f, + }; + + VkPipelineColorBlendAttachmentState blend_attachment = { + .blendEnable = key->blend_mode == WLR_RENDER_BLEND_MODE_PREMULTIPLIED, + // we generally work with pre-multiplied alpha + .srcColorBlendFactor = VK_BLEND_FACTOR_ONE, + .dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, + .colorBlendOp = VK_BLEND_OP_ADD, + .srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE, + .dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, + .alphaBlendOp = VK_BLEND_OP_ADD, + .colorWriteMask = + VK_COLOR_COMPONENT_R_BIT | + VK_COLOR_COMPONENT_G_BIT | + VK_COLOR_COMPONENT_B_BIT | + VK_COLOR_COMPONENT_A_BIT, + }; + + VkPipelineColorBlendStateCreateInfo blend = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, + .attachmentCount = 1, + .pAttachments = &blend_attachment, + }; + + VkPipelineMultisampleStateCreateInfo multisample = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, + .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT, + }; + + VkPipelineViewportStateCreateInfo viewport = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, + .viewportCount = 1, + .scissorCount = 1, + }; + + VkDynamicState dyn_states[] = { + VK_DYNAMIC_STATE_VIEWPORT, + VK_DYNAMIC_STATE_SCISSOR, + }; + VkPipelineDynamicStateCreateInfo dynamic = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, + .pDynamicStates = dyn_states, + .dynamicStateCount = sizeof(dyn_states) / sizeof(dyn_states[0]), + }; + + VkPipelineVertexInputStateCreateInfo vertex = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, + }; + + VkGraphicsPipelineCreateInfo pinfo = { + .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, + .layout = pipeline_layout->vk, + .renderPass = setup->render_pass, + .subpass = 0, + .stageCount = sizeof(stages) / sizeof(stages[0]), + .pStages = stages, + + .pInputAssemblyState = &assembly, + .pRasterizationState = &rasterization, + .pColorBlendState = &blend, + .pMultisampleState = &multisample, + .pViewportState = &viewport, + .pDynamicState = &dynamic, + .pVertexInputState = &vertex, + }; + + VkPipelineCache cache = VK_NULL_HANDLE; + res = vkCreateGraphicsPipelines(dev, cache, 1, &pinfo, NULL, &pipeline->vk); + if (res != VK_SUCCESS) { + wlr_vk_error("failed to create vulkan pipelines:", res); + free(pipeline); + return NULL; + } + + wl_list_insert(&setup->pipelines, &pipeline->link); + return pipeline; +} + +static bool init_blend_to_output_pipeline(struct wlr_vk_renderer *renderer, + VkRenderPass rp, VkPipelineLayout pipe_layout, VkPipeline *pipe, + enum wlr_vk_output_transform transform) { + VkResult res; + VkDevice dev = renderer->dev->dev; + + uint32_t output_transform_type = transform; + VkSpecializationMapEntry spec_entry = { + .constantID = 0, + .offset = 0, + .size = sizeof(uint32_t), + }; + VkSpecializationInfo specialization = { + .mapEntryCount = 1, + .pMapEntries = &spec_entry, + .dataSize = sizeof(uint32_t), + .pData = &output_transform_type, + }; + + VkPipelineShaderStageCreateInfo tex_stages[] = { + { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_VERTEX_BIT, + .module = renderer->vert_module, + .pName = "main", + }, + { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_FRAGMENT_BIT, + .module = renderer->output_module, + .pName = "main", + .pSpecializationInfo = &specialization, + }, + }; + + VkPipelineInputAssemblyStateCreateInfo assembly = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, + .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, + }; + + VkPipelineRasterizationStateCreateInfo rasterization = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, + .polygonMode = VK_POLYGON_MODE_FILL, + .cullMode = VK_CULL_MODE_NONE, + .frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE, + .lineWidth = 1.f, + }; + + VkPipelineColorBlendAttachmentState blend_attachment = { + .blendEnable = false, + .colorWriteMask = + VK_COLOR_COMPONENT_R_BIT | + VK_COLOR_COMPONENT_G_BIT | + VK_COLOR_COMPONENT_B_BIT | + VK_COLOR_COMPONENT_A_BIT, + }; + + VkPipelineColorBlendStateCreateInfo blend = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, + .attachmentCount = 1, + .pAttachments = &blend_attachment, + }; + + VkPipelineMultisampleStateCreateInfo multisample = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, + .rasterizationSamples = VK_SAMPLE_COUNT_1_BIT, + }; + + VkPipelineViewportStateCreateInfo viewport = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, + .viewportCount = 1, + .scissorCount = 1, + }; + + VkDynamicState dyn_states[] = { + VK_DYNAMIC_STATE_VIEWPORT, + VK_DYNAMIC_STATE_SCISSOR, + }; + VkPipelineDynamicStateCreateInfo dynamic = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, + .pDynamicStates = dyn_states, + .dynamicStateCount = sizeof(dyn_states) / sizeof(dyn_states[0]), + }; + + VkPipelineVertexInputStateCreateInfo vertex = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, + }; + + VkGraphicsPipelineCreateInfo pinfo = { + .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, + .pNext = NULL, + .layout = pipe_layout, + .renderPass = rp, + .subpass = 1, // second subpass! + .stageCount = sizeof(tex_stages) / sizeof(tex_stages[0]), + .pStages = tex_stages, + .pInputAssemblyState = &assembly, + .pRasterizationState = &rasterization, + .pColorBlendState = &blend, + .pMultisampleState = &multisample, + .pViewportState = &viewport, + .pDynamicState = &dynamic, + .pVertexInputState = &vertex, + }; + + VkPipelineCache cache = VK_NULL_HANDLE; + res = vkCreateGraphicsPipelines(dev, cache, 1, &pinfo, NULL, pipe); + if (res != VK_SUCCESS) { + wlr_vk_error("failed to create vulkan pipelines:", res); + return false; + } + + return true; +} + +static VkSamplerYcbcrModelConversion ycbcr_model_from_wlr(enum wlr_color_encoding encoding) { + switch (encoding) { + case WLR_COLOR_ENCODING_NONE: + abort(); // must be explicit + case WLR_COLOR_ENCODING_BT601: + return VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601; + case WLR_COLOR_ENCODING_BT709: + return VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709; + case WLR_COLOR_ENCODING_BT2020: + return VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_2020; + default: + abort(); // unsupported + } +} + +static VkSamplerYcbcrRange ycbcr_range_from_wlr(enum wlr_color_range range) { + switch (range) { + case WLR_COLOR_RANGE_NONE: + abort(); // must be explicit + case WLR_COLOR_RANGE_LIMITED: + return VK_SAMPLER_YCBCR_RANGE_ITU_NARROW; + case WLR_COLOR_RANGE_FULL: + return VK_SAMPLER_YCBCR_RANGE_ITU_FULL; + } + abort(); // unreachable +} + +struct wlr_vk_pipeline_layout *get_or_create_pipeline_layout( + struct wlr_vk_renderer *renderer, + const struct wlr_vk_pipeline_layout_key *key) { + struct wlr_vk_pipeline_layout *pipeline_layout; + wl_list_for_each(pipeline_layout, &renderer->pipeline_layouts, link) { + if (pipeline_layout_key_equals(&pipeline_layout->key, key)) { + return pipeline_layout; + } + } + + pipeline_layout = calloc(1, sizeof(*pipeline_layout)); + if (!pipeline_layout) { + return NULL; + } + + pipeline_layout->key = *key; + + VkResult res; + VkFilter filter = VK_FILTER_LINEAR; + switch (key->filter_mode) { + case WLR_SCALE_FILTER_BILINEAR: + filter = VK_FILTER_LINEAR; + break; + case WLR_SCALE_FILTER_NEAREST: + filter = VK_FILTER_NEAREST; + break; + } + + VkSamplerYcbcrConversionInfo conversion_info; + VkSamplerCreateInfo sampler_create_info = { + .sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, + .magFilter = filter, + .minFilter = filter, + .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST, + .addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE, + .minLod = 0.f, + .maxLod = 0.25f, + }; + + if (key->ycbcr.format) { + VkSamplerYcbcrConversionCreateInfo conversion_create_info = { + .sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO, + .format = key->ycbcr.format->vk, + .ycbcrModel = ycbcr_model_from_wlr(key->ycbcr.encoding), + .ycbcrRange = ycbcr_range_from_wlr(key->ycbcr.range), + .xChromaOffset = VK_CHROMA_LOCATION_MIDPOINT, + .yChromaOffset = VK_CHROMA_LOCATION_MIDPOINT, + .chromaFilter = VK_FILTER_LINEAR, + }; + res = vkCreateSamplerYcbcrConversion(renderer->dev->dev, + &conversion_create_info, NULL, &pipeline_layout->ycbcr.conversion); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateSamplerYcbcrConversion", res); + free(pipeline_layout); + return NULL; + } + + conversion_info = (VkSamplerYcbcrConversionInfo){ + .sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO, + .conversion = pipeline_layout->ycbcr.conversion, + }; + sampler_create_info.pNext = &conversion_info; + } else { + assert(key->ycbcr.encoding == WLR_COLOR_ENCODING_NONE || key->ycbcr.encoding == WLR_COLOR_ENCODING_IDENTITY); + assert(key->ycbcr.range == WLR_COLOR_RANGE_NONE || key->ycbcr.range == WLR_COLOR_RANGE_FULL); + } + + res = vkCreateSampler(renderer->dev->dev, &sampler_create_info, NULL, &pipeline_layout->sampler); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateSampler", res); + free(pipeline_layout); + return NULL; + } + + if (!init_tex_layouts(renderer, pipeline_layout->sampler, &pipeline_layout->ds, &pipeline_layout->vk)) { + free(pipeline_layout); + return NULL; + } + + wl_list_insert(&renderer->pipeline_layouts, &pipeline_layout->link); + return pipeline_layout; +} + + +/* The fragment shader for the blend->image subpass can be configured to either + * use or not a sampler3d lookup table; however, even if the shader does not use + * the sampler, a valid descriptor set should be bound. Create that here, linked to + * a 1x1x1 image. + */ +static bool init_dummy_images(struct wlr_vk_renderer *renderer) { + VkResult res; + VkDevice dev = renderer->dev->dev; + + VkFormat format = VK_FORMAT_R32G32B32A32_SFLOAT; + + VkImageCreateInfo img_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, + .imageType = VK_IMAGE_TYPE_3D, + .format = format, + .mipLevels = 1, + .arrayLayers = 1, + .samples = VK_SAMPLE_COUNT_1_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .extent = (VkExtent3D) { 1, 1, 1 }, + .tiling = VK_IMAGE_TILING_OPTIMAL, + .usage = VK_IMAGE_USAGE_SAMPLED_BIT, + }; + res = vkCreateImage(dev, &img_info, NULL, &renderer->dummy3d_image); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateImage failed", res); + return false; + } + + VkMemoryRequirements mem_reqs = {0}; + vkGetImageMemoryRequirements(dev, renderer->dummy3d_image, &mem_reqs); + int mem_type_index = vulkan_find_mem_type(renderer->dev, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, mem_reqs.memoryTypeBits); + if (mem_type_index == -1) { + wlr_log(WLR_ERROR, "Failed to find suitable memory type"); + return false; + } + VkMemoryAllocateInfo mem_info = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = mem_reqs.size, + .memoryTypeIndex = mem_type_index, + }; + res = vkAllocateMemory(dev, &mem_info, NULL, &renderer->dummy3d_mem); + if (res != VK_SUCCESS) { + wlr_vk_error("vkAllocateMemory failed", res); + return false; + } + res = vkBindImageMemory(dev, renderer->dummy3d_image, renderer->dummy3d_mem, 0); + if (res != VK_SUCCESS) { + wlr_vk_error("vkBindMemory failed", res); + return false; + } + + VkImageViewCreateInfo view_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, + .viewType = VK_IMAGE_VIEW_TYPE_3D, + .format = format, + .components.r = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.g = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.b = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.a = VK_COMPONENT_SWIZZLE_IDENTITY, + .subresourceRange = (VkImageSubresourceRange) { + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + .image = renderer->dummy3d_image, + }; + res = vkCreateImageView(dev, &view_info, NULL, &renderer->dummy3d_image_view); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateImageView failed", res); + return false; + } + + renderer->output_ds_lut3d_dummy_pool = vulkan_alloc_texture_ds(renderer, + renderer->output_ds_lut3d_layout, &renderer->output_ds_lut3d_dummy); + if (!renderer->output_ds_lut3d_dummy_pool) { + wlr_log(WLR_ERROR, "Failed to allocate descriptor"); + return false; + } + VkDescriptorImageInfo ds_img_info = { + .imageView = renderer->dummy3d_image_view, + .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + }; + VkWriteDescriptorSet ds_write = { + .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .dstSet = renderer->output_ds_lut3d_dummy, + .pImageInfo = &ds_img_info, + }; + vkUpdateDescriptorSets(dev, 1, &ds_write, 0, NULL); + + return true; +} + +// Creates static render data, such as sampler, layouts and shader modules +// for the given renderer. +// Cleanup is done by destroying the renderer. +static bool init_static_render_data(struct wlr_vk_renderer *renderer) { + VkResult res; + VkDevice dev = renderer->dev->dev; + + if (!init_blend_to_output_layouts(renderer)) { + return false; + } + + if (!init_dummy_images(renderer)) { + return false; + } + + // load vert module and tex frag module since they are needed to + // initialize the tex pipeline + VkShaderModuleCreateInfo sinfo = { + .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, + .codeSize = sizeof(common_vert_data), + .pCode = common_vert_data, + }; + res = vkCreateShaderModule(dev, &sinfo, NULL, &renderer->vert_module); + if (res != VK_SUCCESS) { + wlr_vk_error("Failed to create vertex shader module", res); + return false; + } + + sinfo = (VkShaderModuleCreateInfo){ + .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, + .codeSize = sizeof(texture_frag_data), + .pCode = texture_frag_data, + }; + res = vkCreateShaderModule(dev, &sinfo, NULL, &renderer->tex_frag_module); + if (res != VK_SUCCESS) { + wlr_vk_error("Failed to create tex fragment shader module", res); + return false; + } + + sinfo = (VkShaderModuleCreateInfo){ + .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, + .codeSize = sizeof(quad_frag_data), + .pCode = quad_frag_data, + }; + res = vkCreateShaderModule(dev, &sinfo, NULL, &renderer->quad_frag_module); + if (res != VK_SUCCESS) { + wlr_vk_error("Failed to create quad fragment shader module", res); + return false; + } + + sinfo = (VkShaderModuleCreateInfo){ + .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, + .codeSize = sizeof(output_frag_data), + .pCode = output_frag_data, + }; + res = vkCreateShaderModule(dev, &sinfo, NULL, &renderer->output_module); + if (res != VK_SUCCESS) { + wlr_vk_error("Failed to create blend->output fragment shader module", res); + return false; + } + + return true; +} + +static struct wlr_vk_render_format_setup *find_or_create_render_setup( + struct wlr_vk_renderer *renderer, const struct wlr_vk_format *format, + bool use_blending_buffer, bool srgb) { + struct wlr_vk_render_format_setup *setup; + wl_list_for_each(setup, &renderer->render_format_setups, link) { + if (setup->render_format == format && + setup->use_blending_buffer == use_blending_buffer && + setup->use_srgb == srgb) { + return setup; + } + } + + setup = calloc(1u, sizeof(*setup)); + if (!setup) { + wlr_log(WLR_ERROR, "Allocation failed"); + return NULL; + } + + setup->render_format = format; + setup->use_blending_buffer = use_blending_buffer; + setup->use_srgb = srgb; + setup->renderer = renderer; + wl_list_init(&setup->pipelines); + + VkDevice dev = renderer->dev->dev; + VkResult res; + + if (use_blending_buffer) { + VkAttachmentDescription attachments[] = { + { + .format = VK_FORMAT_R16G16B16A16_SFLOAT, + .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_LOAD, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + .finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + }, + { + .format = format->vk, + .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_LOAD, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = VK_IMAGE_LAYOUT_GENERAL, + .finalLayout = VK_IMAGE_LAYOUT_GENERAL, + } + }; + + VkAttachmentReference blend_write_ref = { + .attachment = 0u, + .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + }; + + VkAttachmentReference blend_read_ref = { + .attachment = 0u, + .layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + }; + + VkAttachmentReference color_ref = { + .attachment = 1u, + .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + }; + + VkSubpassDescription subpasses[] = { + { + .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, + .colorAttachmentCount = 1, + .pColorAttachments = &blend_write_ref, + }, + { + .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, + .inputAttachmentCount = 1, + .pInputAttachments = &blend_read_ref, + .colorAttachmentCount = 1, + .pColorAttachments = &color_ref, + } + }; + + VkSubpassDependency deps[] = { + { + .srcSubpass = VK_SUBPASS_EXTERNAL, + .srcStageMask = VK_PIPELINE_STAGE_HOST_BIT | + VK_PIPELINE_STAGE_TRANSFER_BIT | + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT | + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .srcAccessMask = VK_ACCESS_HOST_WRITE_BIT | + VK_ACCESS_TRANSFER_WRITE_BIT | + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dstSubpass = 0, + .dstStageMask = VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, + .dstAccessMask = VK_ACCESS_UNIFORM_READ_BIT | + VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | + VK_ACCESS_INDIRECT_COMMAND_READ_BIT | + VK_ACCESS_SHADER_READ_BIT, + }, + { + .srcSubpass = 0, + .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dstSubpass = 1, + .dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, + .dstAccessMask = VK_ACCESS_SHADER_READ_BIT, + .dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT, + }, + { + .srcSubpass = 1, + .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dstSubpass = VK_SUBPASS_EXTERNAL, + .dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT | + VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | + VK_ACCESS_MEMORY_READ_BIT, + }, + }; + + VkRenderPassCreateInfo rp_info = { + .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, + .pNext = NULL, + .flags = 0, + .attachmentCount = sizeof(attachments) / sizeof(attachments[0]), + .pAttachments = attachments, + .subpassCount = sizeof(subpasses) / sizeof(subpasses[0]), + .pSubpasses = subpasses, + .dependencyCount = sizeof(deps) / sizeof(deps[0]), + .pDependencies = deps, + }; + + res = vkCreateRenderPass(dev, &rp_info, NULL, &setup->render_pass); + if (res != VK_SUCCESS) { + wlr_vk_error("Failed to create 2-step render pass", res); + goto error; + } + + // this is only well defined if render pass has a 2nd subpass + if (!init_blend_to_output_pipeline( + renderer, setup->render_pass, renderer->output_pipe_layout, + &setup->output_pipe_identity, WLR_VK_OUTPUT_TRANSFORM_IDENTITY)) { + goto error; + } + if (!init_blend_to_output_pipeline( + renderer, setup->render_pass, renderer->output_pipe_layout, + &setup->output_pipe_lut3d, WLR_VK_OUTPUT_TRANSFORM_LUT3D)) { + goto error; + } + if (!init_blend_to_output_pipeline( + renderer, setup->render_pass, renderer->output_pipe_layout, + &setup->output_pipe_srgb, WLR_VK_OUTPUT_TRANSFORM_INVERSE_SRGB)) { + goto error; + } + if (!init_blend_to_output_pipeline( + renderer, setup->render_pass, renderer->output_pipe_layout, + &setup->output_pipe_pq, WLR_VK_OUTPUT_TRANSFORM_INVERSE_ST2084_PQ)) { + goto error; + } + if (!init_blend_to_output_pipeline( + renderer, setup->render_pass, renderer->output_pipe_layout, + &setup->output_pipe_gamma22, WLR_VK_OUTPUT_TRANSFORM_INVERSE_GAMMA22)) { + goto error; + } + if (!init_blend_to_output_pipeline( + renderer, setup->render_pass, renderer->output_pipe_layout, + &setup->output_pipe_bt1886, WLR_VK_OUTPUT_TRANSFORM_INVERSE_BT1886)) { + goto error; + } + } else { + VkAttachmentDescription attachment = { + .format = format->vk, + .samples = VK_SAMPLE_COUNT_1_BIT, + .loadOp = VK_ATTACHMENT_LOAD_OP_LOAD, + .storeOp = VK_ATTACHMENT_STORE_OP_STORE, + .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, + .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE, + .initialLayout = VK_IMAGE_LAYOUT_GENERAL, + .finalLayout = VK_IMAGE_LAYOUT_GENERAL, + }; + if (srgb) { + assert(format->vk_srgb); + attachment.format = format->vk_srgb; + } + + VkAttachmentReference color_ref = { + .attachment = 0u, + .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + }; + + VkSubpassDescription subpass = { + .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, + .colorAttachmentCount = 1, + .pColorAttachments = &color_ref, + }; + + VkSubpassDependency deps[] = { + { + .srcSubpass = VK_SUBPASS_EXTERNAL, + .srcStageMask = VK_PIPELINE_STAGE_HOST_BIT | + VK_PIPELINE_STAGE_TRANSFER_BIT | + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT | + VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .srcAccessMask = VK_ACCESS_HOST_WRITE_BIT | + VK_ACCESS_TRANSFER_WRITE_BIT | + VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dstSubpass = 0, + .dstStageMask = VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, + .dstAccessMask = VK_ACCESS_UNIFORM_READ_BIT | + VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | + VK_ACCESS_INDIRECT_COMMAND_READ_BIT | + VK_ACCESS_SHADER_READ_BIT, + }, + { + .srcSubpass = 0, + .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, + .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, + .dstSubpass = VK_SUBPASS_EXTERNAL, + .dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT | + VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | + VK_ACCESS_MEMORY_READ_BIT, + }, + }; + + VkRenderPassCreateInfo rp_info = { + .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, + .attachmentCount = 1, + .pAttachments = &attachment, + .subpassCount = 1, + .pSubpasses = &subpass, + .dependencyCount = sizeof(deps) / sizeof(deps[0]), + .pDependencies = deps, + }; + + res = vkCreateRenderPass(dev, &rp_info, NULL, &setup->render_pass); + if (res != VK_SUCCESS) { + wlr_vk_error("Failed to create render pass", res); + goto error; + } + } + + if (!setup_get_or_create_pipeline(setup, &(struct wlr_vk_pipeline_key){ + .source = WLR_VK_SHADER_SOURCE_SINGLE_COLOR, + .layout = {0}, + })) { + goto error; + } + + if (!setup_get_or_create_pipeline(setup, &(struct wlr_vk_pipeline_key){ + .source = WLR_VK_SHADER_SOURCE_TEXTURE, + .texture_transform = WLR_VK_TEXTURE_TRANSFORM_IDENTITY, + .layout = {0}, + })) { + goto error; + } + + if (!setup_get_or_create_pipeline(setup, &(struct wlr_vk_pipeline_key){ + .source = WLR_VK_SHADER_SOURCE_TEXTURE, + .texture_transform = WLR_VK_TEXTURE_TRANSFORM_SRGB, + .layout = {0}, + })) { + goto error; + } + + wl_list_insert(&renderer->render_format_setups, &setup->link); + return setup; + +error: + destroy_render_format_setup(renderer, setup); + return NULL; +} + +struct wlr_renderer *vulkan_renderer_create_for_device(struct wlr_vk_device *dev) { + struct wlr_vk_renderer *renderer; + VkResult res; + if (!(renderer = calloc(1, sizeof(*renderer)))) { + wlr_log_errno(WLR_ERROR, "failed to allocate wlr_vk_renderer"); + return NULL; + } + + renderer->dev = dev; + wlr_renderer_init(&renderer->wlr_renderer, &renderer_impl, WLR_BUFFER_CAP_DMABUF); + renderer->wlr_renderer.features.input_color_transform = true; + renderer->wlr_renderer.features.output_color_transform = true; + wl_list_init(&renderer->stage.buffers); + wl_list_init(&renderer->foreign_textures); + wl_list_init(&renderer->textures); + wl_list_init(&renderer->descriptor_pools); + wl_list_init(&renderer->output_descriptor_pools); + wl_list_init(&renderer->render_format_setups); + wl_list_init(&renderer->render_buffers); + wl_list_init(&renderer->color_transforms); + wl_list_init(&renderer->pipeline_layouts); + + renderer->wlr_renderer.color_encodings = + WLR_COLOR_ENCODING_BT601 | + WLR_COLOR_ENCODING_BT709 | + WLR_COLOR_ENCODING_BT2020; + + uint64_t cap_syncobj_timeline; + if (dev->drm_fd >= 0 && drmGetCap(dev->drm_fd, DRM_CAP_SYNCOBJ_TIMELINE, &cap_syncobj_timeline) == 0) { + renderer->wlr_renderer.features.timeline = dev->sync_file_import_export && cap_syncobj_timeline != 0; + } + + if (!init_static_render_data(renderer)) { + goto error; + } + + VkCommandPoolCreateInfo cpool_info = { + .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, + .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, + .queueFamilyIndex = dev->queue_family, + }; + res = vkCreateCommandPool(dev->dev, &cpool_info, NULL, + &renderer->command_pool); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateCommandPool", res); + goto error; + } + + VkSemaphoreTypeCreateInfoKHR semaphore_type_info = { + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO_KHR, + .semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE_KHR, + .initialValue = 0, + }; + VkSemaphoreCreateInfo semaphore_info = { + .sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, + .pNext = &semaphore_type_info, + }; + res = vkCreateSemaphore(dev->dev, &semaphore_info, NULL, + &renderer->timeline_semaphore); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateSemaphore", res); + goto error; + } + + return &renderer->wlr_renderer; + +error: + vulkan_destroy(&renderer->wlr_renderer); + return NULL; +} + +struct wlr_renderer *wlr_vk_renderer_create_with_drm_fd(int drm_fd) { + wlr_log(WLR_INFO, "The vulkan renderer is only experimental and " + "not expected to be ready for daily use"); + wlr_log(WLR_INFO, "Run with VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation " + "to enable the validation layer"); + + struct wlr_vk_instance *ini = vulkan_instance_create(default_debug); + if (!ini) { + wlr_log(WLR_ERROR, "creating vulkan instance for renderer failed"); + return NULL; + } + + VkPhysicalDevice phdev = vulkan_find_drm_phdev(ini, drm_fd); + if (!phdev) { + // We rather fail here than doing some guesswork + wlr_log(WLR_ERROR, "Could not match drm and vulkan device"); + goto error; + } + + struct wlr_vk_device *dev = vulkan_device_create(ini, phdev); + if (!dev) { + wlr_log(WLR_ERROR, "Failed to create vulkan device"); + goto error; + } + + // Do not use the drm_fd that was passed in: we should prefer the render + // node even if a primary node was provided + dev->drm_fd = vulkan_open_phdev_drm_fd(phdev); + + return vulkan_renderer_create_for_device(dev); + +error: + vulkan_instance_destroy(ini); + return NULL; +} + +VkInstance wlr_vk_renderer_get_instance(struct wlr_renderer *renderer) { + struct wlr_vk_renderer *vk_renderer = vulkan_get_renderer(renderer); + return vk_renderer->dev->instance->instance; +} + +VkPhysicalDevice wlr_vk_renderer_get_physical_device(struct wlr_renderer *renderer) { + struct wlr_vk_renderer *vk_renderer = vulkan_get_renderer(renderer); + return vk_renderer->dev->phdev; +} + +VkDevice wlr_vk_renderer_get_device(struct wlr_renderer *renderer) { + struct wlr_vk_renderer *vk_renderer = vulkan_get_renderer(renderer); + return vk_renderer->dev->dev; +} + +uint32_t wlr_vk_renderer_get_queue_family(struct wlr_renderer *renderer) { + struct wlr_vk_renderer *vk_renderer = vulkan_get_renderer(renderer); + return vk_renderer->dev->queue_family; +} diff --git a/3rdparty/wlroots/render/vulkan/shaders/common.vert b/3rdparty/wlroots/render/vulkan/shaders/common.vert new file mode 100644 index 0000000000..f1579790d3 --- /dev/null +++ b/3rdparty/wlroots/render/vulkan/shaders/common.vert @@ -0,0 +1,18 @@ +#version 450 + +// we use a mat4 since it uses the same size as mat3 due to +// alignment. Easier to deal with (tightly-packed) mat4 though. +layout(push_constant, row_major) uniform UBO { + mat4 proj; + vec2 uv_offset; + vec2 uv_size; +} data; + +layout(location = 0) out vec2 uv; + +void main() { + vec2 pos = vec2(float((gl_VertexIndex + 1) & 2) * 0.5f, + float(gl_VertexIndex & 2) * 0.5f); + uv = data.uv_offset + pos * data.uv_size; + gl_Position = data.proj * vec4(pos, 0.0, 1.0); +} diff --git a/3rdparty/wlroots/render/vulkan/shaders/meson.build b/3rdparty/wlroots/render/vulkan/shaders/meson.build new file mode 100644 index 0000000000..50f4a1f0d2 --- /dev/null +++ b/3rdparty/wlroots/render/vulkan/shaders/meson.build @@ -0,0 +1,24 @@ +vulkan_shaders_src = [ + 'common.vert', + 'texture.frag', + 'quad.frag', + 'output.frag', +] + +vulkan_shaders = [] +foreach shader : vulkan_shaders_src + name = shader.underscorify() + '_data' + args = [glslang, '-V', '@INPUT@', '-o', '@OUTPUT@', '--vn', name] + if glslang_version.version_compare('>=11.0.0') + args += '--quiet' + endif + header = custom_target( + shader + '_spv', + output: shader + '.h', + input: shader, + command: args) + + vulkan_shaders += [header] +endforeach + +wlr_files += vulkan_shaders diff --git a/3rdparty/wlroots/render/vulkan/shaders/output.frag b/3rdparty/wlroots/render/vulkan/shaders/output.frag new file mode 100644 index 0000000000..e63de802fb --- /dev/null +++ b/3rdparty/wlroots/render/vulkan/shaders/output.frag @@ -0,0 +1,95 @@ +#version 450 + +layout (input_attachment_index = 0, set = 0, binding = 0) uniform subpassInput in_color; + +layout(set = 1, binding = 0) uniform sampler3D lut_3d; + +layout(location = 0) in vec2 uv; +layout(location = 0) out vec4 out_color; + +/* struct wlr_vk_frag_output_pcr_data */ +layout(push_constant, row_major) uniform UBO { + layout(offset = 80) mat4 matrix; + float lut_3d_offset; + float lut_3d_scale; +} data; + +layout (constant_id = 0) const int OUTPUT_TRANSFORM = 0; + +// Matches enum wlr_vk_output_transform +#define OUTPUT_TRANSFORM_IDENTITY 0 +#define OUTPUT_TRANSFORM_INVERSE_SRGB 1 +#define OUTPUT_TRANSFORM_INVERSE_ST2084_PQ 2 +#define OUTPUT_TRANSFORM_LUT_3D 3 +#define OUTPUT_TRANSFORM_INVERSE_GAMMA22 4 +#define OUTPUT_TRANSFORM_INVERSE_BT1886 5 + +float linear_channel_to_srgb(float x) { + return max(min(x * 12.92, 0.04045), 1.055 * pow(x, 1. / 2.4) - 0.055); +} + +vec3 linear_color_to_srgb(vec3 color) { + return vec3( + linear_channel_to_srgb(color.r), + linear_channel_to_srgb(color.g), + linear_channel_to_srgb(color.b) + ); +} + +vec3 linear_color_to_pq(vec3 color) { + // H.273 TransferCharacteristics code point 16 + float c1 = 0.8359375; + float c2 = 18.8515625; + float c3 = 18.6875; + float m = 78.84375; + float n = 0.1593017578125; + vec3 pow_n = pow(clamp(color, vec3(0), vec3(1)), vec3(n)); + return pow((vec3(c1) + c2 * pow_n) / (vec3(1) + c3 * pow_n), vec3(m)); +} + +vec3 linear_color_to_bt1886(vec3 color) { + float Lmin = 0.01; + float Lmax = 100.0; + float lb = pow(Lmin, 1.0 / 2.4); + float lw = pow(Lmax, 1.0 / 2.4); + float a = pow(lw - lb, 2.4); + float b = lb / (lw - lb); + vec3 L = color * (Lmax - Lmin) + vec3(Lmin); + return pow(L / a, vec3(1.0 / 2.4)) - vec3(b); +} + +void main() { + vec4 in_color = subpassLoad(in_color).rgba; + + // Convert from pre-multiplied alpha to straight alpha + float alpha = in_color.a; + vec3 rgb; + if (alpha == 0) { + rgb = vec3(0); + } else { + rgb = in_color.rgb / alpha; + } + + rgb = mat3(data.matrix) * rgb; + + if (OUTPUT_TRANSFORM != OUTPUT_TRANSFORM_IDENTITY) { + rgb = max(rgb, vec3(0)); + } + if (OUTPUT_TRANSFORM == OUTPUT_TRANSFORM_LUT_3D) { + // Apply 3D LUT + vec3 pos = data.lut_3d_offset + rgb * data.lut_3d_scale; + rgb = texture(lut_3d, pos).rgb; + } else if (OUTPUT_TRANSFORM == OUTPUT_TRANSFORM_INVERSE_ST2084_PQ) { + rgb = linear_color_to_pq(rgb); + } else if (OUTPUT_TRANSFORM == OUTPUT_TRANSFORM_INVERSE_SRGB) { + // Produce sRGB encoded values + rgb = linear_color_to_srgb(rgb); + } else if (OUTPUT_TRANSFORM == OUTPUT_TRANSFORM_INVERSE_GAMMA22) { + rgb = pow(rgb, vec3(1. / 2.2)); + } else if (OUTPUT_TRANSFORM == OUTPUT_TRANSFORM_INVERSE_BT1886) { + rgb = linear_color_to_bt1886(rgb); + } + + // Back to pre-multiplied alpha + out_color = vec4(rgb * alpha, alpha); +} diff --git a/3rdparty/wlroots/render/vulkan/shaders/quad.frag b/3rdparty/wlroots/render/vulkan/shaders/quad.frag new file mode 100644 index 0000000000..affd1f1161 --- /dev/null +++ b/3rdparty/wlroots/render/vulkan/shaders/quad.frag @@ -0,0 +1,10 @@ +#version 450 + +layout(location = 0) out vec4 out_color; +layout(push_constant) uniform UBO { + layout(offset = 80) vec4 color; +} data; + +void main() { + out_color = data.color; +} diff --git a/3rdparty/wlroots/render/vulkan/shaders/texture.frag b/3rdparty/wlroots/render/vulkan/shaders/texture.frag new file mode 100644 index 0000000000..3ec9742354 --- /dev/null +++ b/3rdparty/wlroots/render/vulkan/shaders/texture.frag @@ -0,0 +1,93 @@ +#version 450 + +layout(set = 0, binding = 0) uniform sampler2D tex; + +layout(location = 0) in vec2 uv; +layout(location = 0) out vec4 out_color; + +// struct wlr_vk_frag_texture_pcr_data +layout(push_constant, row_major) uniform UBO { + layout(offset = 80) mat4 matrix; + float alpha; + float luminance_multiplier; +} data; + +layout (constant_id = 0) const int TEXTURE_TRANSFORM = 0; + +// Matches enum wlr_vk_texture_transform +#define TEXTURE_TRANSFORM_IDENTITY 0 +#define TEXTURE_TRANSFORM_SRGB 1 +#define TEXTURE_TRANSFORM_ST2084_PQ 2 +#define TEXTURE_TRANSFORM_GAMMA22 3 +#define TEXTURE_TRANSFORM_BT1886 4 + +float srgb_channel_to_linear(float x) { + return mix(x / 12.92, + pow((x + 0.055) / 1.055, 2.4), + x > 0.04045); +} + +vec3 srgb_color_to_linear(vec3 color) { + return vec3( + srgb_channel_to_linear(color.r), + srgb_channel_to_linear(color.g), + srgb_channel_to_linear(color.b) + ); +} + +vec3 pq_color_to_linear(vec3 color) { + float inv_m1 = 1 / 0.1593017578125; + float inv_m2 = 1 / 78.84375; + float c1 = 0.8359375; + float c2 = 18.8515625; + float c3 = 18.6875; + vec3 num = max(pow(color, vec3(inv_m2)) - c1, 0); + vec3 denom = c2 - c3 * pow(color, vec3(inv_m2)); + return pow(num / denom, vec3(inv_m1)); +} + +vec3 bt1886_color_to_linear(vec3 color) { + float Lmin = 0.01; + float Lmax = 100.0; + float lb = pow(Lmin, 1.0 / 2.4); + float lw = pow(Lmax, 1.0 / 2.4); + float a = pow(lw - lb, 2.4); + float b = lb / (lw - lb); + vec3 L = a * pow(color + vec3(b), vec3(2.4)); + return (L - Lmin) / (Lmax - Lmin); +} + +void main() { + vec4 in_color = textureLod(tex, uv, 0); + + // Convert from pre-multiplied alpha to straight alpha + float alpha = in_color.a; + vec3 rgb; + if (alpha == 0) { + rgb = vec3(0); + } else { + rgb = in_color.rgb / alpha; + } + + if (TEXTURE_TRANSFORM != TEXTURE_TRANSFORM_IDENTITY) { + rgb = max(rgb, vec3(0)); + } + if (TEXTURE_TRANSFORM == TEXTURE_TRANSFORM_SRGB) { + rgb = srgb_color_to_linear(rgb); + } else if (TEXTURE_TRANSFORM == TEXTURE_TRANSFORM_ST2084_PQ) { + rgb = pq_color_to_linear(rgb); + } else if (TEXTURE_TRANSFORM == TEXTURE_TRANSFORM_GAMMA22) { + rgb = pow(rgb, vec3(2.2)); + } else if (TEXTURE_TRANSFORM == TEXTURE_TRANSFORM_BT1886) { + rgb = bt1886_color_to_linear(rgb); + } + + rgb *= data.luminance_multiplier; + + rgb = mat3(data.matrix) * rgb; + + // Back to pre-multiplied alpha + out_color = vec4(rgb * alpha, alpha); + + out_color *= data.alpha; +} diff --git a/3rdparty/wlroots/render/vulkan/texture.c b/3rdparty/wlroots/render/vulkan/texture.c new file mode 100644 index 0000000000..57db97a567 --- /dev/null +++ b/3rdparty/wlroots/render/vulkan/texture.c @@ -0,0 +1,840 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "render/pixel_format.h" +#include "render/vulkan.h" + +static const struct wlr_texture_impl texture_impl; + +bool wlr_texture_is_vk(struct wlr_texture *wlr_texture) { + return wlr_texture->impl == &texture_impl; +} + +struct wlr_vk_texture *vulkan_get_texture(struct wlr_texture *wlr_texture) { + assert(wlr_texture_is_vk(wlr_texture)); + struct wlr_vk_texture *texture = wl_container_of(wlr_texture, texture, wlr_texture); + return texture; +} + +static VkImageAspectFlagBits mem_plane_aspect(unsigned i) { + switch (i) { + case 0: return VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT; + case 1: return VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT; + case 2: return VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT; + case 3: return VK_IMAGE_ASPECT_MEMORY_PLANE_3_BIT_EXT; + default: abort(); // unreachable + } +} + +// Will transition the texture to shaderReadOnlyOptimal layout for reading +// from fragment shader later on +static bool write_pixels(struct wlr_vk_texture *texture, + uint32_t stride, const pixman_region32_t *region, const void *vdata, + VkImageLayout old_layout, VkPipelineStageFlags src_stage, + VkAccessFlags src_access) { + struct wlr_vk_renderer *renderer = texture->renderer; + + const struct wlr_pixel_format_info *format_info = drm_get_pixel_format_info(texture->format->drm); + assert(format_info); + + uint32_t bsize = 0; + + // deferred upload by transfer; using staging buffer + // calculate maximum side needed + int rects_len = 0; + const pixman_box32_t *rects = pixman_region32_rectangles(region, &rects_len); + for (int i = 0; i < rects_len; i++) { + pixman_box32_t rect = rects[i]; + uint32_t width = rect.x2 - rect.x1; + uint32_t height = rect.y2 - rect.y1; + + // make sure assumptions are met + assert((uint32_t)rect.x2 <= texture->wlr_texture.width); + assert((uint32_t)rect.y2 <= texture->wlr_texture.height); + + bsize += height * pixel_format_info_min_stride(format_info, width); + } + + VkBufferImageCopy *copies = calloc((size_t)rects_len, sizeof(*copies)); + if (!copies) { + wlr_log(WLR_ERROR, "Failed to allocate image copy parameters"); + return false; + } + + // get staging buffer + struct wlr_vk_buffer_span span = vulkan_get_stage_span(renderer, bsize, format_info->bytes_per_block); + if (!span.buffer || span.alloc.size != bsize) { + wlr_log(WLR_ERROR, "Failed to retrieve staging buffer"); + free(copies); + return false; + } + char *map = (char*)span.buffer->cpu_mapping + span.alloc.start; + + // upload data + + uint32_t buf_off = span.alloc.start; + for (int i = 0; i < rects_len; i++) { + pixman_box32_t rect = rects[i]; + uint32_t width = rect.x2 - rect.x1; + uint32_t height = rect.y2 - rect.y1; + uint32_t src_x = rect.x1; + uint32_t src_y = rect.y1; + uint32_t packed_stride = (uint32_t)pixel_format_info_min_stride(format_info, width); + + // write data into staging buffer span + const char *pdata = vdata; // data iterator + pdata += stride * src_y; + pdata += format_info->bytes_per_block * src_x; + if (src_x == 0 && width == texture->wlr_texture.width && + stride == packed_stride) { + memcpy(map, pdata, packed_stride * height); + map += packed_stride * height; + } else { + for (unsigned i = 0u; i < height; ++i) { + memcpy(map, pdata, packed_stride); + pdata += stride; + map += packed_stride; + } + } + + copies[i] = (VkBufferImageCopy) { + .imageExtent.width = width, + .imageExtent.height = height, + .imageExtent.depth = 1, + .imageOffset.x = src_x, + .imageOffset.y = src_y, + .imageOffset.z = 0, + .bufferOffset = buf_off, + .bufferRowLength = width, + .bufferImageHeight = height, + .imageSubresource.mipLevel = 0, + .imageSubresource.baseArrayLayer = 0, + .imageSubresource.layerCount = 1, + .imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + }; + + + buf_off += height * packed_stride; + } + + // record staging cb + // will be executed before next frame + VkCommandBuffer cb = vulkan_record_stage_cb(renderer); + if (cb == VK_NULL_HANDLE) { + free(copies); + return false; + } + + vulkan_change_layout(cb, texture->image, + old_layout, src_stage, src_access, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_WRITE_BIT); + + vkCmdCopyBufferToImage(cb, span.buffer->buffer, texture->image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, (uint32_t)rects_len, copies); + vulkan_change_layout(cb, texture->image, + VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_ACCESS_TRANSFER_WRITE_BIT, + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_ACCESS_SHADER_READ_BIT); + texture->last_used_cb = renderer->stage.cb; + + free(copies); + + return true; +} + +static bool vulkan_texture_update_from_buffer(struct wlr_texture *wlr_texture, + struct wlr_buffer *buffer, const pixman_region32_t *damage) { + struct wlr_vk_texture *texture = vulkan_get_texture(wlr_texture); + + void *data; + uint32_t format; + size_t stride; + if (!wlr_buffer_begin_data_ptr_access(buffer, + WLR_BUFFER_DATA_PTR_ACCESS_READ, &data, &format, &stride)) { + return false; + } + + bool ok = true; + + if (format != texture->format->drm) { + ok = false; + goto out; + } + + ok = write_pixels(texture, stride, damage, data, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT); + +out: + wlr_buffer_end_data_ptr_access(buffer); + return ok; +} + +void vulkan_texture_destroy(struct wlr_vk_texture *texture) { + if (texture->buffer != NULL) { + wlr_addon_finish(&texture->buffer_addon); + texture->buffer = NULL; + } + + // when we recorded a command to fill this image _this_ frame, + // it has to be executed before the texture can be destroyed. + // Add it to the renderer->destroy_textures list, destroying + // _after_ the stage command buffer has executed + if (texture->last_used_cb != NULL) { + assert(texture->destroy_link.next == NULL); // not already inserted + wl_list_insert(&texture->last_used_cb->destroy_textures, + &texture->destroy_link); + return; + } + + wl_list_remove(&texture->link); + + VkDevice dev = texture->renderer->dev->dev; + + struct wlr_vk_texture_view *view, *tmp_view; + wl_list_for_each_safe(view, tmp_view, &texture->views, link) { + vulkan_free_ds(texture->renderer, view->ds_pool, view->ds); + vkDestroyImageView(dev, view->image_view, NULL); + free(view); + } + + vkDestroyImage(dev, texture->image, NULL); + + for (unsigned i = 0u; i < texture->mem_count; ++i) { + vkFreeMemory(dev, texture->memories[i], NULL); + } + + free(texture); +} + +static void vulkan_texture_unref(struct wlr_texture *wlr_texture) { + struct wlr_vk_texture *texture = vulkan_get_texture(wlr_texture); + if (texture->buffer != NULL) { + // Keep the texture around, in case the buffer is re-used later. We're + // still listening to the buffer's destroy event. + wlr_buffer_unlock(texture->buffer); + } else { + vulkan_texture_destroy(texture); + } +} + +static bool vulkan_texture_read_pixels(struct wlr_texture *wlr_texture, + const struct wlr_texture_read_pixels_options *options) { + struct wlr_vk_texture *texture = vulkan_get_texture(wlr_texture); + + struct wlr_box src; + wlr_texture_read_pixels_options_get_src_box(options, wlr_texture, &src); + + void *p = wlr_texture_read_pixel_options_get_data(options); + + return vulkan_read_pixels(texture->renderer, texture->format->vk, texture->image, + options->format, options->stride, src.width, src.height, src.x, src.y, 0, 0, p); +} + +static uint32_t vulkan_texture_preferred_read_format(struct wlr_texture *wlr_texture) { + struct wlr_vk_texture *texture = vulkan_get_texture(wlr_texture); + return texture->format->drm; +} + +static const struct wlr_texture_impl texture_impl = { + .update_from_buffer = vulkan_texture_update_from_buffer, + .read_pixels = vulkan_texture_read_pixels, + .preferred_read_format = vulkan_texture_preferred_read_format, + .destroy = vulkan_texture_unref, +}; + +static struct wlr_vk_texture *vulkan_texture_create( + struct wlr_vk_renderer *renderer, uint32_t width, uint32_t height) { + struct wlr_vk_texture *texture = calloc(1, sizeof(*texture)); + if (texture == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + wlr_texture_init(&texture->wlr_texture, &renderer->wlr_renderer, + &texture_impl, width, height); + texture->renderer = renderer; + wl_list_insert(&renderer->textures, &texture->link); + wl_list_init(&texture->views); + return texture; +} + +struct wlr_vk_texture_view *vulkan_texture_get_or_create_view(struct wlr_vk_texture *texture, + const struct wlr_vk_pipeline_layout *pipeline_layout, bool srgb) { + assert(texture->using_mutable_srgb || !srgb); + + struct wlr_vk_texture_view *view; + wl_list_for_each(view, &texture->views, link) { + if (view->layout == pipeline_layout && view->srgb == srgb) { + return view; + } + } + + view = calloc(1, sizeof(*view)); + if (!view) { + return NULL; + } + + view->layout = pipeline_layout; + view->srgb = srgb; + + VkResult res; + VkDevice dev = texture->renderer->dev->dev; + + VkImageViewCreateInfo view_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, + .viewType = VK_IMAGE_VIEW_TYPE_2D, + .format = srgb ? texture->format->vk_srgb : texture->format->vk, + .components.r = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.g = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.b = VK_COMPONENT_SWIZZLE_IDENTITY, + .components.a = texture->has_alpha || vulkan_format_is_ycbcr(texture->format) + ? VK_COMPONENT_SWIZZLE_IDENTITY + : VK_COMPONENT_SWIZZLE_ONE, + .subresourceRange = (VkImageSubresourceRange){ + .aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .baseMipLevel = 0, + .levelCount = 1, + .baseArrayLayer = 0, + .layerCount = 1, + }, + .image = texture->image, + }; + + VkSamplerYcbcrConversionInfo ycbcr_conversion_info; + if (vulkan_format_is_ycbcr(texture->format)) { + assert(pipeline_layout->ycbcr.conversion != VK_NULL_HANDLE); + ycbcr_conversion_info = (VkSamplerYcbcrConversionInfo){ + .sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO, + .conversion = pipeline_layout->ycbcr.conversion, + }; + view_info.pNext = &ycbcr_conversion_info; + } + + res = vkCreateImageView(dev, &view_info, NULL, &view->image_view); + if (res != VK_SUCCESS) { + free(view); + wlr_vk_error("vkCreateImageView failed", res); + return NULL; + } + + view->ds_pool = vulkan_alloc_texture_ds(texture->renderer, pipeline_layout->ds, &view->ds); + if (!view->ds_pool) { + free(view); + wlr_log(WLR_ERROR, "failed to allocate descriptor"); + return NULL; + } + + VkDescriptorImageInfo ds_img_info = { + .imageView = view->image_view, + .imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + }; + + VkWriteDescriptorSet ds_write = { + .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, + .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, + .dstSet = view->ds, + .pImageInfo = &ds_img_info, + }; + + vkUpdateDescriptorSets(dev, 1, &ds_write, 0, NULL); + + wl_list_insert(&texture->views, &view->link); + return view; +} + +static void texture_set_format(struct wlr_vk_texture *texture, + const struct wlr_vk_format *format, bool has_mutable_srgb) { + assert(!(vulkan_format_is_ycbcr(format) && has_mutable_srgb)); + + texture->format = format; + texture->using_mutable_srgb = has_mutable_srgb; + + const struct wlr_pixel_format_info *format_info = + drm_get_pixel_format_info(format->drm); + if (format_info != NULL) { + texture->has_alpha = pixel_format_has_alpha(format->drm); + } else { + // We don't have format info for multi-planar formats + assert(vulkan_format_is_ycbcr(texture->format)); + } +} + +static struct wlr_texture *vulkan_texture_from_pixels( + struct wlr_vk_renderer *renderer, uint32_t drm_fmt, uint32_t stride, + uint32_t width, uint32_t height, const void *data) { + VkResult res; + VkDevice dev = renderer->dev->dev; + + const struct wlr_vk_format_props *fmt = + vulkan_format_props_from_drm(renderer->dev, drm_fmt); + if (fmt == NULL || vulkan_format_is_ycbcr(&fmt->format)) { + char *format_name = drmGetFormatName(drm_fmt); + wlr_log(WLR_ERROR, "Unsupported pixel format %s (0x%08"PRIX32")", + format_name, drm_fmt); + free(format_name); + return NULL; + } + + if (width > fmt->shm.max_extent.width || height > fmt->shm.max_extent.height) { + wlr_log(WLR_ERROR, "Texture is too large to upload (%"PRIu32"x%"PRIu32" > %"PRIu32"x%"PRIu32")", + width, height, fmt->shm.max_extent.width, fmt->shm.max_extent.height); + return NULL; + } + + struct wlr_vk_texture *texture = vulkan_texture_create(renderer, width, height); + if (texture == NULL) { + return NULL; + } + + texture_set_format(texture, &fmt->format, fmt->shm.has_mutable_srgb); + + VkFormat view_formats[] = { + fmt->format.vk, + fmt->format.vk_srgb, + }; + VkImageFormatListCreateInfoKHR list_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO_KHR, + .pViewFormats = view_formats, + .viewFormatCount = sizeof(view_formats) / sizeof(view_formats[0]), + }; + VkImageCreateInfo img_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, + .imageType = VK_IMAGE_TYPE_2D, + .format = texture->format->vk, + .mipLevels = 1, + .arrayLayers = 1, + .samples = VK_SAMPLE_COUNT_1_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .extent = (VkExtent3D) { width, height, 1 }, + .tiling = VK_IMAGE_TILING_OPTIMAL, + .usage = vulkan_shm_tex_usage, + .pNext = fmt->shm.has_mutable_srgb ? &list_info : NULL, + }; + if (fmt->shm.has_mutable_srgb) { + img_info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; + } + + res = vkCreateImage(dev, &img_info, NULL, &texture->image); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateImage failed", res); + goto error; + } + + VkMemoryRequirements mem_reqs; + vkGetImageMemoryRequirements(dev, texture->image, &mem_reqs); + + int mem_type_index = vulkan_find_mem_type(renderer->dev, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, mem_reqs.memoryTypeBits); + if (mem_type_index == -1) { + wlr_log(WLR_ERROR, "failed to find suitable vulkan memory type"); + goto error; + } + + VkMemoryAllocateInfo mem_info = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = mem_reqs.size, + .memoryTypeIndex = mem_type_index, + }; + + res = vkAllocateMemory(dev, &mem_info, NULL, &texture->memories[0]); + if (res != VK_SUCCESS) { + wlr_vk_error("vkAllocatorMemory failed", res); + goto error; + } + + texture->mem_count = 1; + res = vkBindImageMemory(dev, texture->image, texture->memories[0], 0); + if (res != VK_SUCCESS) { + wlr_vk_error("vkBindMemory failed", res); + goto error; + } + + pixman_region32_t region; + pixman_region32_init_rect(®ion, 0, 0, width, height); + if (!write_pixels(texture, stride, ®ion, data, VK_IMAGE_LAYOUT_UNDEFINED, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0)) { + goto error; + } + + return &texture->wlr_texture; + +error: + vulkan_texture_destroy(texture); + return NULL; +} + +static bool is_dmabuf_disjoint(const struct wlr_dmabuf_attributes *attribs) { + if (attribs->n_planes == 1) { + return false; + } + + struct stat first_stat; + if (fstat(attribs->fd[0], &first_stat) != 0) { + wlr_log_errno(WLR_ERROR, "fstat failed"); + return true; + } + + for (int i = 1; i < attribs->n_planes; i++) { + struct stat plane_stat; + if (fstat(attribs->fd[i], &plane_stat) != 0) { + wlr_log_errno(WLR_ERROR, "fstat failed"); + return true; + } + + if (first_stat.st_ino != plane_stat.st_ino) { + return true; + } + } + + return false; +} + +VkImage vulkan_import_dmabuf(struct wlr_vk_renderer *renderer, + const struct wlr_dmabuf_attributes *attribs, + VkDeviceMemory mems[static WLR_DMABUF_MAX_PLANES], uint32_t *n_mems, + bool for_render, bool *using_mutable_srgb) { + VkResult res; + VkDevice dev = renderer->dev->dev; + *n_mems = 0u; + + struct wlr_vk_format_props *fmt = vulkan_format_props_from_drm(renderer->dev, + attribs->format); + if (fmt == NULL) { + char *format_name = drmGetFormatName(attribs->format); + wlr_log(WLR_ERROR, "Unsupported pixel format %s (0x%08"PRIX32")", + format_name, attribs->format); + free(format_name); + return VK_NULL_HANDLE; + } + + uint32_t plane_count = attribs->n_planes; + assert(plane_count < WLR_DMABUF_MAX_PLANES); + const struct wlr_vk_format_modifier_props *mod = + vulkan_format_props_find_modifier(fmt, attribs->modifier, for_render); + if (!mod) { + char *format_name = drmGetFormatName(attribs->format); + char *modifier_name = drmGetFormatModifierName(attribs->modifier); + wlr_log(WLR_ERROR, "Format %s (0x%08"PRIX32") can't be used with modifier " + "%s (0x%016"PRIX64")", format_name, attribs->format, + modifier_name, attribs->modifier); + free(format_name); + free(modifier_name); + return VK_NULL_HANDLE; + } + + if ((uint32_t) attribs->width > mod->max_extent.width || + (uint32_t) attribs->height > mod->max_extent.height) { + wlr_log(WLR_ERROR, "DMA-BUF is too large to import (%"PRIi32"x%"PRIi32" > %"PRIu32"x%"PRIu32")", + attribs->width, attribs->height, mod->max_extent.width, mod->max_extent.height); + return VK_NULL_HANDLE; + } + + if (mod->props.drmFormatModifierPlaneCount != plane_count) { + wlr_log(WLR_ERROR, "Number of planes (%d) does not match format (%d)", + plane_count, mod->props.drmFormatModifierPlaneCount); + return VK_NULL_HANDLE; + } + + // check if we have to create the image disjoint + bool disjoint = is_dmabuf_disjoint(attribs); + if (disjoint && !(mod->props.drmFormatModifierTilingFeatures + & VK_FORMAT_FEATURE_DISJOINT_BIT)) { + wlr_log(WLR_ERROR, "Format/Modifier does not support disjoint images"); + return VK_NULL_HANDLE; + } + + VkExternalMemoryHandleTypeFlagBits htype = + VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT; + + VkImageCreateInfo img_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, + .imageType = VK_IMAGE_TYPE_2D, + .format = fmt->format.vk, + .mipLevels = 1, + .arrayLayers = 1, + .samples = VK_SAMPLE_COUNT_1_BIT, + .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .extent = (VkExtent3D) { attribs->width, attribs->height, 1 }, + .usage = for_render ? vulkan_render_usage : vulkan_dma_tex_usage, + }; + if (disjoint) { + img_info.flags = VK_IMAGE_CREATE_DISJOINT_BIT; + } + if (mod->has_mutable_srgb) { + img_info.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; + } + + VkExternalMemoryImageCreateInfo eimg = { + .sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO, + .handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, + }; + img_info.pNext = &eimg; + + VkSubresourceLayout plane_layouts[WLR_DMABUF_MAX_PLANES] = {0}; + + img_info.tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT; + for (unsigned i = 0u; i < plane_count; ++i) { + plane_layouts[i].offset = attribs->offset[i]; + plane_layouts[i].rowPitch = attribs->stride[i]; + plane_layouts[i].size = 0; + } + + VkImageDrmFormatModifierExplicitCreateInfoEXT mod_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT, + .drmFormatModifierPlaneCount = plane_count, + .drmFormatModifier = mod->props.drmFormatModifier, + .pPlaneLayouts = plane_layouts, + }; + eimg.pNext = &mod_info; + + VkFormat view_formats[] = { + fmt->format.vk, + fmt->format.vk_srgb, + }; + VkImageFormatListCreateInfoKHR list_info = { + .sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO_KHR, + .pViewFormats = view_formats, + .viewFormatCount = sizeof(view_formats) / sizeof(view_formats[0]), + }; + if (mod->has_mutable_srgb) { + mod_info.pNext = &list_info; + } + + VkImage image; + res = vkCreateImage(dev, &img_info, NULL, &image); + if (res != VK_SUCCESS) { + wlr_vk_error("vkCreateImage", res); + return VK_NULL_HANDLE; + } + + unsigned mem_count = disjoint ? plane_count : 1u; + VkBindImageMemoryInfo bindi[WLR_DMABUF_MAX_PLANES] = {0}; + VkBindImagePlaneMemoryInfo planei[WLR_DMABUF_MAX_PLANES] = {0}; + + for (unsigned i = 0u; i < mem_count; ++i) { + VkMemoryFdPropertiesKHR fdp = { + .sType = VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR, + }; + res = renderer->dev->api.vkGetMemoryFdPropertiesKHR(dev, htype, + attribs->fd[i], &fdp); + if (res != VK_SUCCESS) { + wlr_vk_error("getMemoryFdPropertiesKHR", res); + goto error_image; + } + + VkImageMemoryRequirementsInfo2 memri = { + .image = image, + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2, + }; + + VkImagePlaneMemoryRequirementsInfo planeri; + if (disjoint) { + planeri = (VkImagePlaneMemoryRequirementsInfo){ + .sType = VK_STRUCTURE_TYPE_IMAGE_PLANE_MEMORY_REQUIREMENTS_INFO, + .planeAspect = mem_plane_aspect(i), + }; + memri.pNext = &planeri; + } + + VkMemoryRequirements2 memr = { + .sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2, + }; + + vkGetImageMemoryRequirements2(dev, &memri, &memr); + int mem = vulkan_find_mem_type(renderer->dev, 0, + memr.memoryRequirements.memoryTypeBits & fdp.memoryTypeBits); + if (mem < 0) { + wlr_log(WLR_ERROR, "no valid memory type index"); + goto error_image; + } + + // Since importing transfers ownership of the FD to Vulkan, we have + // to duplicate it since this operation does not transfer ownership + // of the attribs to this texture. Will be closed by Vulkan on + // vkFreeMemory. + int dfd = fcntl(attribs->fd[i], F_DUPFD_CLOEXEC, 0); + if (dfd < 0) { + wlr_log_errno(WLR_ERROR, "fcntl(F_DUPFD_CLOEXEC) failed"); + goto error_image; + } + + VkMemoryAllocateInfo memi = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = memr.memoryRequirements.size, + .memoryTypeIndex = mem, + }; + + VkImportMemoryFdInfoKHR importi = { + .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR, + .fd = dfd, + .handleType = htype, + }; + memi.pNext = &importi; + + VkMemoryDedicatedAllocateInfo dedi = { + .sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO, + .image = image, + }; + importi.pNext = &dedi; + + res = vkAllocateMemory(dev, &memi, NULL, &mems[i]); + if (res != VK_SUCCESS) { + close(dfd); + wlr_vk_error("vkAllocateMemory failed", res); + goto error_image; + } + + ++(*n_mems); + + // fill bind info + bindi[i].image = image; + bindi[i].memory = mems[i]; + bindi[i].memoryOffset = 0; + bindi[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO; + + if (disjoint) { + planei[i].sType = VK_STRUCTURE_TYPE_BIND_IMAGE_PLANE_MEMORY_INFO; + planei[i].planeAspect = planeri.planeAspect; + bindi[i].pNext = &planei[i]; + } + } + + res = vkBindImageMemory2(dev, mem_count, bindi); + if (res != VK_SUCCESS) { + wlr_vk_error("vkBindMemory failed", res); + goto error_image; + } + + *using_mutable_srgb = mod->has_mutable_srgb; + return image; + +error_image: + vkDestroyImage(dev, image, NULL); + for (size_t i = 0u; i < *n_mems; ++i) { + vkFreeMemory(dev, mems[i], NULL); + mems[i] = VK_NULL_HANDLE; + } + + return VK_NULL_HANDLE; +} + +static struct wlr_vk_texture *vulkan_texture_from_dmabuf( + struct wlr_vk_renderer *renderer, + struct wlr_dmabuf_attributes *attribs) { + const struct wlr_vk_format_props *fmt = vulkan_format_props_from_drm( + renderer->dev, attribs->format); + if (fmt == NULL) { + char *format_name = drmGetFormatName(attribs->format); + wlr_log(WLR_ERROR, "Unsupported pixel format %s (0x%08"PRIX32")", + format_name, attribs->format); + free(format_name); + return NULL; + } + + struct wlr_vk_texture *texture = vulkan_texture_create(renderer, + attribs->width, attribs->height); + if (texture == NULL) { + return NULL; + } + + bool using_mutable_srgb = false; + texture->image = vulkan_import_dmabuf(renderer, attribs, + texture->memories, &texture->mem_count, false, &using_mutable_srgb); + if (!texture->image) { + goto error; + } + texture_set_format(texture, &fmt->format, using_mutable_srgb); + + texture->dmabuf_imported = true; + + return texture; + +error: + vulkan_texture_destroy(texture); + return NULL; +} + +static void texture_handle_buffer_destroy(struct wlr_addon *addon) { + struct wlr_vk_texture *texture = + wl_container_of(addon, texture, buffer_addon); + // We might keep the texture around, waiting for pending command buffers to + // complete before free'ing descriptor sets. + vulkan_texture_destroy(texture); +} + +static const struct wlr_addon_interface buffer_addon_impl = { + .name = "wlr_vk_texture", + .destroy = texture_handle_buffer_destroy, +}; + +static struct wlr_texture *vulkan_texture_from_dmabuf_buffer( + struct wlr_vk_renderer *renderer, struct wlr_buffer *buffer, + struct wlr_dmabuf_attributes *dmabuf) { + struct wlr_addon *addon = + wlr_addon_find(&buffer->addons, renderer, &buffer_addon_impl); + if (addon != NULL) { + struct wlr_vk_texture *texture = + wl_container_of(addon, texture, buffer_addon); + wlr_buffer_lock(texture->buffer); + return &texture->wlr_texture; + } + + struct wlr_vk_texture *texture = vulkan_texture_from_dmabuf(renderer, dmabuf); + if (texture == NULL) { + return NULL; + } + + texture->buffer = wlr_buffer_lock(buffer); + wlr_addon_init(&texture->buffer_addon, &buffer->addons, renderer, + &buffer_addon_impl); + + return &texture->wlr_texture; +} + +struct wlr_texture *vulkan_texture_from_buffer(struct wlr_renderer *wlr_renderer, + struct wlr_buffer *buffer) { + struct wlr_vk_renderer *renderer = vulkan_get_renderer(wlr_renderer); + + void *data; + uint32_t format; + size_t stride; + struct wlr_dmabuf_attributes dmabuf; + if (wlr_buffer_get_dmabuf(buffer, &dmabuf)) { + return vulkan_texture_from_dmabuf_buffer(renderer, buffer, &dmabuf); + } else if (wlr_buffer_begin_data_ptr_access(buffer, + WLR_BUFFER_DATA_PTR_ACCESS_READ, &data, &format, &stride)) { + struct wlr_texture *tex = vulkan_texture_from_pixels(renderer, + format, stride, buffer->width, buffer->height, data); + wlr_buffer_end_data_ptr_access(buffer); + return tex; + } else { + return NULL; + } +} + +void wlr_vk_texture_get_image_attribs(struct wlr_texture *texture, + struct wlr_vk_image_attribs *attribs) { + struct wlr_vk_texture *vk_texture = vulkan_get_texture(texture); + attribs->image = vk_texture->image; + attribs->format = vk_texture->format->vk; + attribs->layout = vk_texture->transitioned ? + VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL; +} + +bool wlr_vk_texture_has_alpha(struct wlr_texture *texture) { + struct wlr_vk_texture *vk_texture = vulkan_get_texture(texture); + return vk_texture->has_alpha; +} diff --git a/3rdparty/wlroots/render/vulkan/util.c b/3rdparty/wlroots/render/vulkan/util.c new file mode 100644 index 0000000000..73a14073a1 --- /dev/null +++ b/3rdparty/wlroots/render/vulkan/util.c @@ -0,0 +1,78 @@ +#include +#include +#include "render/vulkan.h" + +int vulkan_find_mem_type(struct wlr_vk_device *dev, + VkMemoryPropertyFlags flags, uint32_t req_bits) { + VkPhysicalDeviceMemoryProperties props; + vkGetPhysicalDeviceMemoryProperties(dev->phdev, &props); + + for (unsigned i = 0u; i < props.memoryTypeCount; ++i) { + if (req_bits & (1 << i)) { + if ((props.memoryTypes[i].propertyFlags & flags) == flags) { + return i; + } + } + } + + return -1; +} + +const char *vulkan_strerror(VkResult err) { +#define ERR_STR(r) case VK_ ##r: return #r + switch (err) { + ERR_STR(SUCCESS); + ERR_STR(NOT_READY); + ERR_STR(TIMEOUT); + ERR_STR(EVENT_SET); + ERR_STR(EVENT_RESET); + ERR_STR(INCOMPLETE); + ERR_STR(ERROR_OUT_OF_HOST_MEMORY); + ERR_STR(ERROR_OUT_OF_DEVICE_MEMORY); + ERR_STR(ERROR_INITIALIZATION_FAILED); + ERR_STR(ERROR_DEVICE_LOST); + ERR_STR(ERROR_MEMORY_MAP_FAILED); + ERR_STR(ERROR_LAYER_NOT_PRESENT); + ERR_STR(ERROR_EXTENSION_NOT_PRESENT); + ERR_STR(ERROR_FEATURE_NOT_PRESENT); + ERR_STR(ERROR_INCOMPATIBLE_DRIVER); + ERR_STR(ERROR_TOO_MANY_OBJECTS); + ERR_STR(ERROR_FORMAT_NOT_SUPPORTED); + ERR_STR(ERROR_FRAGMENTED_POOL); + ERR_STR(ERROR_UNKNOWN); + ERR_STR(ERROR_OUT_OF_POOL_MEMORY); + ERR_STR(ERROR_INVALID_EXTERNAL_HANDLE); + ERR_STR(ERROR_FRAGMENTATION); + ERR_STR(ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS); + ERR_STR(PIPELINE_COMPILE_REQUIRED_EXT); + ERR_STR(ERROR_SURFACE_LOST_KHR); + ERR_STR(ERROR_NATIVE_WINDOW_IN_USE_KHR); + ERR_STR(SUBOPTIMAL_KHR); + ERR_STR(ERROR_OUT_OF_DATE_KHR); + ERR_STR(ERROR_INCOMPATIBLE_DISPLAY_KHR); + ERR_STR(ERROR_VALIDATION_FAILED_EXT); + ERR_STR(ERROR_INVALID_DRM_FORMAT_MODIFIER_PLANE_LAYOUT_EXT); + default: + return ""; + } +#undef ERR_STR +} + +void vulkan_change_layout(VkCommandBuffer cb, VkImage img, + VkImageLayout ol, VkPipelineStageFlags srcs, VkAccessFlags srca, + VkImageLayout nl, VkPipelineStageFlags dsts, VkAccessFlags dsta) { + VkImageMemoryBarrier barrier = { + .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, + .oldLayout = ol, + .newLayout = nl, + .image = img, + .subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT, + .subresourceRange.layerCount = 1, + .subresourceRange.levelCount = 1, + .srcAccessMask = srca, + .dstAccessMask = dsta, + .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, + }; + vkCmdPipelineBarrier(cb, srcs, dsts, 0, 0, NULL, 0, NULL, 1, &barrier); +} diff --git a/3rdparty/wlroots/render/vulkan/vulkan.c b/3rdparty/wlroots/render/vulkan/vulkan.c new file mode 100644 index 0000000000..0c0445d802 --- /dev/null +++ b/3rdparty/wlroots/render/vulkan/vulkan.c @@ -0,0 +1,682 @@ +#if defined(__FreeBSD__) +#undef _POSIX_C_SOURCE +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "render/dmabuf.h" +#include "render/vulkan.h" + +#if defined(__linux__) +#include +#endif + +static bool check_extension(const VkExtensionProperties *avail, + uint32_t avail_len, const char *name) { + for (size_t i = 0; i < avail_len; i++) { + if (strcmp(avail[i].extensionName, name) == 0) { + return true; + } + } + return false; +} + +static VKAPI_ATTR VkBool32 debug_callback(VkDebugUtilsMessageSeverityFlagBitsEXT severity, + VkDebugUtilsMessageTypeFlagsEXT type, + const VkDebugUtilsMessengerCallbackDataEXT *debug_data, + void *data) { + // we ignore some of the non-helpful warnings + static const char *const ignored[] = { + // notifies us that shader output is not consumed since + // we use the shared vertex buffer with uv output + "UNASSIGNED-CoreValidation-Shader-OutputNotConsumed", + }; + + if (debug_data->pMessageIdName) { + for (unsigned i = 0; i < sizeof(ignored) / sizeof(ignored[0]); ++i) { + if (strcmp(debug_data->pMessageIdName, ignored[i]) == 0) { + return false; + } + } + } + + enum wlr_log_importance importance; + switch (severity) { + case VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT: + case VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT: + importance = WLR_ERROR; + break; + default: + case VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT: + importance = WLR_INFO; + break; + } + + wlr_log(importance, "%s (%s)", debug_data->pMessage, + debug_data->pMessageIdName); + if (debug_data->queueLabelCount > 0) { + const char *name = debug_data->pQueueLabels[0].pLabelName; + if (name) { + wlr_log(importance, " last label '%s'", name); + } + } + + for (unsigned i = 0; i < debug_data->objectCount; ++i) { + if (debug_data->pObjects[i].pObjectName) { + wlr_log(importance, " involving '%s'", debug_data->pMessage); + } + } + + return false; +} + +struct wlr_vk_instance *vulkan_instance_create(bool debug) { + // we require vulkan 1.1 + PFN_vkEnumerateInstanceVersion pfEnumInstanceVersion = + (PFN_vkEnumerateInstanceVersion) + vkGetInstanceProcAddr(VK_NULL_HANDLE, "vkEnumerateInstanceVersion"); + if (!pfEnumInstanceVersion) { + wlr_log(WLR_ERROR, "wlroots requires vulkan 1.1 which is not available"); + return NULL; + } + + uint32_t ini_version; + if (pfEnumInstanceVersion(&ini_version) != VK_SUCCESS || + ini_version < VK_API_VERSION_1_1) { + wlr_log(WLR_ERROR, "wlroots requires vulkan 1.1 which is not available"); + return NULL; + } + + uint32_t avail_extc = 0; + VkResult res; + res = vkEnumerateInstanceExtensionProperties(NULL, &avail_extc, NULL); + if ((res != VK_SUCCESS) || (avail_extc == 0)) { + wlr_vk_error("Could not enumerate instance extensions (1)", res); + return NULL; + } + + VkExtensionProperties avail_ext_props[avail_extc + 1]; + res = vkEnumerateInstanceExtensionProperties(NULL, &avail_extc, + avail_ext_props); + if (res != VK_SUCCESS) { + wlr_vk_error("Could not enumerate instance extensions (2)", res); + return NULL; + } + + for (size_t j = 0; j < avail_extc; ++j) { + wlr_log(WLR_DEBUG, "Vulkan instance extension %s v%"PRIu32, + avail_ext_props[j].extensionName, avail_ext_props[j].specVersion); + } + + struct wlr_vk_instance *ini = calloc(1, sizeof(*ini)); + if (!ini) { + wlr_log_errno(WLR_ERROR, "allocation failed"); + return NULL; + } + + size_t extensions_len = 0; + const char *extensions[1] = {0}; + + bool debug_utils_found = false; + if (debug && check_extension(avail_ext_props, avail_extc, + VK_EXT_DEBUG_UTILS_EXTENSION_NAME)) { + debug_utils_found = true; + extensions[extensions_len++] = VK_EXT_DEBUG_UTILS_EXTENSION_NAME; + } + + assert(extensions_len <= sizeof(extensions) / sizeof(extensions[0])); + + VkApplicationInfo application_info = { + .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, + .pEngineName = "wlroots", + .engineVersion = WLR_VERSION_NUM, + .apiVersion = VK_API_VERSION_1_1, + }; + + VkInstanceCreateInfo instance_info = { + .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, + .pApplicationInfo = &application_info, + .enabledExtensionCount = extensions_len, + .ppEnabledExtensionNames = extensions, + .enabledLayerCount = 0, + .ppEnabledLayerNames = NULL, + }; + + VkDebugUtilsMessageSeverityFlagsEXT severity = + // VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; + VkDebugUtilsMessageTypeFlagsEXT types = + // VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; + + VkDebugUtilsMessengerCreateInfoEXT debug_info = { + .sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT, + .messageSeverity = severity, + .messageType = types, + .pfnUserCallback = &debug_callback, + .pUserData = ini, + }; + + if (debug_utils_found) { + // already adding the debug utils messenger extension to + // instance creation gives us additional information during + // instance creation and destruction, can be useful for debugging + // layers/extensions not being found. + instance_info.pNext = &debug_info; + } + + res = vkCreateInstance(&instance_info, NULL, &ini->instance); + if (res != VK_SUCCESS) { + wlr_vk_error("Could not create instance", res); + goto error; + } + + if (debug_utils_found) { + ini->api.createDebugUtilsMessengerEXT = + (PFN_vkCreateDebugUtilsMessengerEXT) vkGetInstanceProcAddr( + ini->instance, "vkCreateDebugUtilsMessengerEXT"); + ini->api.destroyDebugUtilsMessengerEXT = + (PFN_vkDestroyDebugUtilsMessengerEXT) vkGetInstanceProcAddr( + ini->instance, "vkDestroyDebugUtilsMessengerEXT"); + + if (ini->api.createDebugUtilsMessengerEXT) { + ini->api.createDebugUtilsMessengerEXT(ini->instance, + &debug_info, NULL, &ini->messenger); + } else { + wlr_log(WLR_ERROR, "vkCreateDebugUtilsMessengerEXT not found"); + } + } + + return ini; + +error: + vulkan_instance_destroy(ini); + return NULL; +} + +void vulkan_instance_destroy(struct wlr_vk_instance *ini) { + if (!ini) { + return; + } + + if (ini->messenger && ini->api.destroyDebugUtilsMessengerEXT) { + ini->api.destroyDebugUtilsMessengerEXT(ini->instance, + ini->messenger, NULL); + } + + if (ini->instance) { + vkDestroyInstance(ini->instance, NULL); + } + + free(ini); +} + +static void log_phdev(const VkPhysicalDeviceProperties *props) { + uint32_t vv_major = VK_VERSION_MAJOR(props->apiVersion); + uint32_t vv_minor = VK_VERSION_MINOR(props->apiVersion); + uint32_t vv_patch = VK_VERSION_PATCH(props->apiVersion); + + uint32_t dv_major = VK_VERSION_MAJOR(props->driverVersion); + uint32_t dv_minor = VK_VERSION_MINOR(props->driverVersion); + uint32_t dv_patch = VK_VERSION_PATCH(props->driverVersion); + + const char *dev_type = "unknown"; + switch (props->deviceType) { + case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: + dev_type = "integrated"; + break; + case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: + dev_type = "discrete"; + break; + case VK_PHYSICAL_DEVICE_TYPE_CPU: + dev_type = "cpu"; + break; + case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: + dev_type = "vgpu"; + break; + default: + break; + } + + wlr_log(WLR_INFO, "Vulkan device: '%s'", props->deviceName); + wlr_log(WLR_INFO, " Device type: '%s'", dev_type); + wlr_log(WLR_INFO, " Supported API version: %u.%u.%u", vv_major, vv_minor, vv_patch); + wlr_log(WLR_INFO, " Driver version: %u.%u.%u", dv_major, dv_minor, dv_patch); +} + +VkPhysicalDevice vulkan_find_drm_phdev(struct wlr_vk_instance *ini, int drm_fd) { + VkResult res; + uint32_t num_phdevs; + + res = vkEnumeratePhysicalDevices(ini->instance, &num_phdevs, NULL); + if (res != VK_SUCCESS) { + wlr_vk_error("Could not retrieve physical devices", res); + return VK_NULL_HANDLE; + } + + VkPhysicalDevice phdevs[1 + num_phdevs]; + res = vkEnumeratePhysicalDevices(ini->instance, &num_phdevs, phdevs); + if (res != VK_SUCCESS) { + wlr_vk_error("Could not retrieve physical devices", res); + return VK_NULL_HANDLE; + } + + struct stat drm_stat = {0}; + if (drm_fd >= 0 && fstat(drm_fd, &drm_stat) != 0) { + wlr_log_errno(WLR_ERROR, "fstat failed"); + return VK_NULL_HANDLE; + } + + for (uint32_t i = 0; i < num_phdevs; ++i) { + VkPhysicalDevice phdev = phdevs[i]; + + // check whether device supports vulkan 1.1, needed for + // vkGetPhysicalDeviceProperties2 + VkPhysicalDeviceProperties phdev_props; + vkGetPhysicalDeviceProperties(phdev, &phdev_props); + + log_phdev(&phdev_props); + + if (phdev_props.apiVersion < VK_API_VERSION_1_1) { + // NOTE: we could additionally check whether the + // VkPhysicalDeviceProperties2KHR extension is supported but + // implementations not supporting 1.1 are unlikely in future + continue; + } + + // check for extensions + uint32_t avail_extc = 0; + res = vkEnumerateDeviceExtensionProperties(phdev, NULL, + &avail_extc, NULL); + if ((res != VK_SUCCESS) || (avail_extc == 0)) { + wlr_vk_error(" Could not enumerate device extensions", res); + continue; + } + + VkExtensionProperties avail_ext_props[avail_extc + 1]; + res = vkEnumerateDeviceExtensionProperties(phdev, NULL, + &avail_extc, avail_ext_props); + if (res != VK_SUCCESS) { + wlr_vk_error(" Could not enumerate device extensions", res); + continue; + } + + bool has_drm_props = check_extension(avail_ext_props, avail_extc, + VK_EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME); + bool has_driver_props = check_extension(avail_ext_props, avail_extc, + VK_KHR_DRIVER_PROPERTIES_EXTENSION_NAME); + + VkPhysicalDeviceProperties2 props = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, + }; + + VkPhysicalDeviceDrmPropertiesEXT drm_props = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT, + }; + if (has_drm_props) { + drm_props.pNext = props.pNext; + props.pNext = &drm_props; + } + + VkPhysicalDeviceDriverPropertiesKHR driver_props = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES, + }; + if (has_driver_props) { + driver_props.pNext = props.pNext; + props.pNext = &driver_props; + } + + vkGetPhysicalDeviceProperties2(phdev, &props); + + if (has_driver_props) { + wlr_log(WLR_INFO, " Driver name: %s (%s)", driver_props.driverName, driver_props.driverInfo); + } + + bool found; + if (drm_fd >= 0) { + if (!has_drm_props) { + wlr_log(WLR_DEBUG, " Ignoring physical device \"%s\": " + "VK_EXT_physical_device_drm not supported", + phdev_props.deviceName); + continue; + } + + dev_t primary_devid = makedev(drm_props.primaryMajor, drm_props.primaryMinor); + dev_t render_devid = makedev(drm_props.renderMajor, drm_props.renderMinor); + found = primary_devid == drm_stat.st_rdev || render_devid == drm_stat.st_rdev; + } else { + found = phdev_props.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU; + } + + if (found) { + wlr_log(WLR_INFO, "Found matching Vulkan physical device: %s", + phdev_props.deviceName); + return phdev; + } + } + + return VK_NULL_HANDLE; +} + +int vulkan_open_phdev_drm_fd(VkPhysicalDevice phdev) { + // vulkan_find_drm_phdev() already checks that VK_EXT_physical_device_drm + // is supported + VkPhysicalDeviceDrmPropertiesEXT drm_props = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT, + }; + VkPhysicalDeviceProperties2 props = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, + .pNext = &drm_props, + }; + vkGetPhysicalDeviceProperties2(phdev, &props); + + dev_t devid; + if (drm_props.hasRender) { + devid = makedev(drm_props.renderMajor, drm_props.renderMinor); + } else if (drm_props.hasPrimary) { + devid = makedev(drm_props.primaryMajor, drm_props.primaryMinor); + } else { + wlr_log(WLR_INFO, "Physical device is missing both render and primary nodes"); + return -1; + } + + drmDevice *device = NULL; + if (drmGetDeviceFromDevId(devid, 0, &device) != 0) { + wlr_log_errno(WLR_ERROR, "drmGetDeviceFromDevId failed"); + return -1; + } + + const char *name = NULL; + if (device->available_nodes & (1 << DRM_NODE_RENDER)) { + name = device->nodes[DRM_NODE_RENDER]; + } else { + assert(device->available_nodes & (1 << DRM_NODE_PRIMARY)); + name = device->nodes[DRM_NODE_PRIMARY]; + wlr_log(WLR_DEBUG, "DRM device %s has no render node, " + "falling back to primary node", name); + } + + int drm_fd = open(name, O_RDWR | O_NONBLOCK | O_CLOEXEC); + if (drm_fd < 0) { + wlr_log_errno(WLR_ERROR, "Failed to open DRM node %s", name); + } + drmFreeDevice(&device); + return drm_fd; +} + +static void load_device_proc(struct wlr_vk_device *dev, const char *name, + void *proc_ptr) { + void *proc = (void *)vkGetDeviceProcAddr(dev->dev, name); + if (proc == NULL) { + abort(); + } + *(void **)proc_ptr = proc; +} + +struct wlr_vk_device *vulkan_device_create(struct wlr_vk_instance *ini, + VkPhysicalDevice phdev) { + VkResult res; + + uint32_t avail_extc = 0; + res = vkEnumerateDeviceExtensionProperties(phdev, NULL, + &avail_extc, NULL); + if (res != VK_SUCCESS || avail_extc == 0) { + wlr_vk_error("Could not enumerate device extensions (1)", res); + return NULL; + } + + VkExtensionProperties avail_ext_props[avail_extc + 1]; + res = vkEnumerateDeviceExtensionProperties(phdev, NULL, + &avail_extc, avail_ext_props); + if (res != VK_SUCCESS) { + wlr_vk_error("Could not enumerate device extensions (2)", res); + return NULL; + } + + for (size_t j = 0; j < avail_extc; ++j) { + wlr_log(WLR_DEBUG, "Vulkan device extension %s v%"PRIu32, + avail_ext_props[j].extensionName, avail_ext_props[j].specVersion); + } + + struct wlr_vk_device *dev = calloc(1, sizeof(*dev)); + if (!dev) { + wlr_log_errno(WLR_ERROR, "allocation failed"); + return NULL; + } + + dev->phdev = phdev; + dev->instance = ini; + dev->drm_fd = -1; + + // For dmabuf import we require at least the external_memory_fd, + // external_memory_dma_buf, queue_family_foreign, + // image_drm_format_modifier, and image_format_list extensions. + // The size is set to a large number to allow for other conditional + // extensions before the device is created + const char *extensions[32] = {0}; + size_t extensions_len = 0; + extensions[extensions_len++] = VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME; + extensions[extensions_len++] = VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME; // or vulkan 1.2 + extensions[extensions_len++] = VK_EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME; + extensions[extensions_len++] = VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME; + extensions[extensions_len++] = VK_EXT_IMAGE_DRM_FORMAT_MODIFIER_EXTENSION_NAME; + extensions[extensions_len++] = VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME; // or vulkan 1.2 + extensions[extensions_len++] = VK_KHR_SYNCHRONIZATION_2_EXTENSION_NAME; // or vulkan 1.3 + + for (size_t i = 0; i < extensions_len; i++) { + if (!check_extension(avail_ext_props, avail_extc, extensions[i])) { + wlr_log(WLR_ERROR, "vulkan: required device extension %s not found", + extensions[i]); + goto error; + } + } + + { + uint32_t qfam_count; + vkGetPhysicalDeviceQueueFamilyProperties(phdev, &qfam_count, NULL); + assert(qfam_count > 0); + VkQueueFamilyProperties queue_props[qfam_count]; + vkGetPhysicalDeviceQueueFamilyProperties(phdev, &qfam_count, + queue_props); + + bool graphics_found = false; + for (unsigned i = 0u; i < qfam_count; ++i) { + graphics_found = queue_props[i].queueFlags & VK_QUEUE_GRAPHICS_BIT; + if (graphics_found) { + dev->queue_family = i; + break; + } + } + assert(graphics_found); + } + + bool exportable_semaphore = false, importable_semaphore = false; + bool has_external_semaphore_fd = + check_extension(avail_ext_props, avail_extc, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME); + if (has_external_semaphore_fd) { + const VkPhysicalDeviceExternalSemaphoreInfo ext_semaphore_info = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO, + .handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT, + }; + VkExternalSemaphoreProperties ext_semaphore_props = { + .sType = VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES, + }; + vkGetPhysicalDeviceExternalSemaphoreProperties(phdev, + &ext_semaphore_info, &ext_semaphore_props); + exportable_semaphore = ext_semaphore_props.externalSemaphoreFeatures & + VK_EXTERNAL_SEMAPHORE_FEATURE_EXPORTABLE_BIT; + importable_semaphore = ext_semaphore_props.externalSemaphoreFeatures & + VK_EXTERNAL_SEMAPHORE_FEATURE_IMPORTABLE_BIT; + extensions[extensions_len++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME; + } + if (!exportable_semaphore) { + wlr_log(WLR_DEBUG, "VkSemaphore is not exportable to a sync_file"); + } + if (!importable_semaphore) { + wlr_log(WLR_DEBUG, "VkSemaphore is not importable from a sync_file"); + } + + bool dmabuf_sync_file_import_export = dmabuf_check_sync_file_import_export(); + if (!dmabuf_sync_file_import_export) { + wlr_log(WLR_DEBUG, "DMA-BUF sync_file import/export not supported"); + } + + dev->sync_file_import_export = exportable_semaphore && importable_semaphore; + dev->implicit_sync_interop = + exportable_semaphore && importable_semaphore && dmabuf_sync_file_import_export; + if (dev->implicit_sync_interop) { + wlr_log(WLR_DEBUG, "Implicit sync interop supported"); + } else { + wlr_log(WLR_INFO, "Implicit sync interop not supported, " + "falling back to blocking"); + } + + VkPhysicalDeviceSamplerYcbcrConversionFeatures phdev_sampler_ycbcr_features = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES, + }; + VkPhysicalDeviceFeatures2 phdev_features = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, + .pNext = &phdev_sampler_ycbcr_features, + }; + vkGetPhysicalDeviceFeatures2(phdev, &phdev_features); + + dev->sampler_ycbcr_conversion = phdev_sampler_ycbcr_features.samplerYcbcrConversion; + wlr_log(WLR_DEBUG, "Sampler YCbCr conversion %s", + dev->sampler_ycbcr_conversion ? "supported" : "not supported"); + + const float prio = 1.f; + VkDeviceQueueCreateInfo qinfo = { + .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, + .queueFamilyIndex = dev->queue_family, + .queueCount = 1, + .pQueuePriorities = &prio, + }; + + VkDeviceQueueGlobalPriorityCreateInfoEXT global_priority; + bool has_global_priority = check_extension(avail_ext_props, avail_extc, + VK_EXT_GLOBAL_PRIORITY_EXTENSION_NAME); + if (has_global_priority) { + // If global priorities are supported, request a high-priority context + global_priority = (VkDeviceQueueGlobalPriorityCreateInfoEXT){ + .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_GLOBAL_PRIORITY_CREATE_INFO_EXT, + .globalPriority = VK_QUEUE_GLOBAL_PRIORITY_HIGH_EXT, + }; + qinfo.pNext = &global_priority; + extensions[extensions_len++] = VK_EXT_GLOBAL_PRIORITY_EXTENSION_NAME; + wlr_log(WLR_DEBUG, "Requesting a high-priority device queue"); + } else { + wlr_log(WLR_DEBUG, "Global priorities are not supported, " + "falling back to regular queue priority"); + } + + VkPhysicalDeviceSamplerYcbcrConversionFeatures sampler_ycbcr_features = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES, + .samplerYcbcrConversion = dev->sampler_ycbcr_conversion, + }; + VkPhysicalDeviceSynchronization2FeaturesKHR sync2_features = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SYNCHRONIZATION_2_FEATURES_KHR, + .pNext = &sampler_ycbcr_features, + .synchronization2 = VK_TRUE, + }; + VkPhysicalDeviceTimelineSemaphoreFeaturesKHR timeline_features = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES_KHR, + .pNext = &sync2_features, + .timelineSemaphore = VK_TRUE, + }; + VkDeviceCreateInfo dev_info = { + .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, + .pNext = &timeline_features, + .queueCreateInfoCount = 1u, + .pQueueCreateInfos = &qinfo, + .enabledExtensionCount = extensions_len, + .ppEnabledExtensionNames = extensions, + }; + + assert(extensions_len <= sizeof(extensions) / sizeof(extensions[0])); + + res = vkCreateDevice(phdev, &dev_info, NULL, &dev->dev); + + if (has_global_priority && (res == VK_ERROR_NOT_PERMITTED_EXT || + res == VK_ERROR_INITIALIZATION_FAILED)) { + // Try to recover from the driver denying a global priority queue + wlr_log(WLR_DEBUG, "Failed to obtain a high-priority device queue, " + "falling back to regular queue priority"); + qinfo.pNext = NULL; + res = vkCreateDevice(phdev, &dev_info, NULL, &dev->dev); + } + + if (res != VK_SUCCESS) { + wlr_vk_error("Failed to create vulkan device", res); + goto error; + } + + vkGetDeviceQueue(dev->dev, dev->queue_family, 0, &dev->queue); + + load_device_proc(dev, "vkGetMemoryFdPropertiesKHR", + &dev->api.vkGetMemoryFdPropertiesKHR); + load_device_proc(dev, "vkWaitSemaphoresKHR", &dev->api.vkWaitSemaphoresKHR); + load_device_proc(dev, "vkGetSemaphoreCounterValueKHR", + &dev->api.vkGetSemaphoreCounterValueKHR); + load_device_proc(dev, "vkQueueSubmit2KHR", &dev->api.vkQueueSubmit2KHR); + + if (has_external_semaphore_fd) { + load_device_proc(dev, "vkGetSemaphoreFdKHR", &dev->api.vkGetSemaphoreFdKHR); + load_device_proc(dev, "vkImportSemaphoreFdKHR", &dev->api.vkImportSemaphoreFdKHR); + } + + size_t max_fmts; + const struct wlr_vk_format *fmts = vulkan_get_format_list(&max_fmts); + dev->format_props = calloc(max_fmts, sizeof(*dev->format_props)); + if (!dev->format_props) { + wlr_log_errno(WLR_ERROR, "allocation failed"); + goto error; + } + + wlr_log(WLR_DEBUG, "Supported Vulkan formats:"); + for (unsigned i = 0u; i < max_fmts; ++i) { + vulkan_format_props_query(dev, &fmts[i]); + } + + return dev; + +error: + vulkan_device_destroy(dev); + return NULL; +} + +void vulkan_device_destroy(struct wlr_vk_device *dev) { + if (!dev) { + return; + } + + if (dev->dev) { + vkDestroyDevice(dev->dev, NULL); + } + + if (dev->drm_fd > 0) { + close(dev->drm_fd); + } + + wlr_drm_format_set_finish(&dev->dmabuf_render_formats); + wlr_drm_format_set_finish(&dev->dmabuf_texture_formats); + wlr_drm_format_set_finish(&dev->shm_texture_formats); + + for (unsigned i = 0u; i < dev->format_prop_count; ++i) { + vulkan_format_props_finish(&dev->format_props[i]); + } + + free(dev->format_props); + free(dev); +} diff --git a/3rdparty/wlroots/render/wlr_renderer.c b/3rdparty/wlroots/render/wlr_renderer.c new file mode 100644 index 0000000000..e65314ccce --- /dev/null +++ b/3rdparty/wlroots/render/wlr_renderer.c @@ -0,0 +1,336 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#if WLR_HAS_GLES2_RENDERER +#include +#include +#endif + +#if WLR_HAS_VULKAN_RENDERER +#include +#endif // WLR_HAS_VULKAN_RENDERER + +#include "render/wlr_renderer.h" +#include "util/env.h" + +void wlr_renderer_init(struct wlr_renderer *renderer, + const struct wlr_renderer_impl *impl, uint32_t render_buffer_caps) { + assert(impl->begin_buffer_pass); + assert(impl->get_texture_formats); + assert(render_buffer_caps != 0); + + *renderer = (struct wlr_renderer){ + .impl = impl, + .render_buffer_caps = render_buffer_caps, + }; + + wl_signal_init(&renderer->events.destroy); + wl_signal_init(&renderer->events.lost); +} + +void wlr_renderer_destroy(struct wlr_renderer *r) { + if (!r) { + return; + } + + wl_signal_emit_mutable(&r->events.destroy, r); + + assert(wl_list_empty(&r->events.destroy.listener_list)); + assert(wl_list_empty(&r->events.lost.listener_list)); + + if (r->impl && r->impl->destroy) { + r->impl->destroy(r); + } else { + free(r); + } +} + +const struct wlr_drm_format_set *wlr_renderer_get_texture_formats( + struct wlr_renderer *r, uint32_t buffer_caps) { + return r->impl->get_texture_formats(r, buffer_caps); +} + +const struct wlr_drm_format_set *wlr_renderer_get_render_formats( + struct wlr_renderer *r) { + if (!r->impl->get_render_formats) { + return NULL; + } + return r->impl->get_render_formats(r); +} + +bool wlr_renderer_init_wl_shm(struct wlr_renderer *r, + struct wl_display *wl_display) { + return wlr_shm_create_with_renderer(wl_display, 2, r) != NULL; +} + +bool wlr_renderer_init_wl_display(struct wlr_renderer *r, + struct wl_display *wl_display) { + if (!wlr_renderer_init_wl_shm(r, wl_display)) { + return false; + } + + if (wlr_renderer_get_texture_formats(r, WLR_BUFFER_CAP_DMABUF) != NULL && + wlr_renderer_get_drm_fd(r) >= 0 && + wlr_linux_dmabuf_v1_create_with_renderer(wl_display, 4, r) == NULL) { + return false; + } + + return true; +} + +static int open_drm_render_node(void) { + uint32_t flags = 0; + int devices_len = drmGetDevices2(flags, NULL, 0); + if (devices_len < 0) { + wlr_log(WLR_ERROR, "drmGetDevices2 failed: %s", strerror(-devices_len)); + return -1; + } + drmDevice **devices = calloc(devices_len, sizeof(*devices)); + if (devices == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return -1; + } + devices_len = drmGetDevices2(flags, devices, devices_len); + if (devices_len < 0) { + free(devices); + wlr_log(WLR_ERROR, "drmGetDevices2 failed: %s", strerror(-devices_len)); + return -1; + } + + int fd = -1; + for (int i = 0; i < devices_len; i++) { + drmDevice *dev = devices[i]; + if (dev->available_nodes & (1 << DRM_NODE_RENDER)) { + const char *name = dev->nodes[DRM_NODE_RENDER]; + wlr_log(WLR_DEBUG, "Opening DRM render node '%s'", name); + fd = open(name, O_RDWR | O_CLOEXEC); + if (fd < 0) { + wlr_log_errno(WLR_ERROR, "Failed to open '%s'", name); + goto out; + } + break; + } + } + if (fd < 0) { + wlr_log(WLR_ERROR, "Failed to find any DRM render node"); + } + +out: + for (int i = 0; i < devices_len; i++) { + drmFreeDevice(&devices[i]); + } + free(devices); + + return fd; +} + +static bool open_preferred_drm_fd(struct wlr_backend *backend, int *drm_fd_ptr, + bool *own_drm_fd) { + if (*drm_fd_ptr >= 0) { + return true; + } + + if (env_parse_bool("WLR_RENDERER_FORCE_SOFTWARE")) { + *drm_fd_ptr = -1; + *own_drm_fd = false; + return true; + } + + // Allow the user to override the render node + const char *render_name = getenv("WLR_RENDER_DRM_DEVICE"); + if (render_name != NULL) { + wlr_log(WLR_INFO, + "Opening DRM render node '%s' from WLR_RENDER_DRM_DEVICE", + render_name); + int drm_fd = open(render_name, O_RDWR | O_CLOEXEC); + if (drm_fd < 0) { + wlr_log_errno(WLR_ERROR, "Failed to open '%s'", render_name); + return false; + } + if (drmGetNodeTypeFromFd(drm_fd) != DRM_NODE_RENDER) { + wlr_log(WLR_ERROR, "'%s' is not a DRM render node", render_name); + close(drm_fd); + return false; + } + *drm_fd_ptr = drm_fd; + *own_drm_fd = true; + return true; + } + + // Prefer the backend's DRM node, if any + int backend_drm_fd = wlr_backend_get_drm_fd(backend); + if (backend_drm_fd >= 0) { + *drm_fd_ptr = backend_drm_fd; + *own_drm_fd = false; + return true; + } + + // If the backend hasn't picked a DRM FD, but accepts DMA-BUFs, pick an + // arbitrary render node + if (backend->buffer_caps & WLR_BUFFER_CAP_DMABUF) { + int drm_fd = open_drm_render_node(); + if (drm_fd < 0) { + return false; + } + *drm_fd_ptr = drm_fd; + *own_drm_fd = true; + return true; + } + + return false; +} + +static void log_creation_failure(bool is_auto, const char *msg) { + wlr_log(is_auto ? WLR_DEBUG : WLR_ERROR, "%s%s", msg, is_auto ? ". Skipping!" : ""); +} + +static bool has_render_node(struct wlr_backend *backend) { + if (!backend) { + return false; + } + + int backend_drm_fd = wlr_backend_get_drm_fd(backend); + if (backend_drm_fd < 0) { + return false; + } + + char *render_node = drmGetRenderDeviceNameFromFd(backend_drm_fd); + bool has_render_node = render_node != NULL; + free(render_node); + + return has_render_node; +} + +static struct wlr_renderer *renderer_autocreate(struct wlr_backend *backend, int drm_fd) { + const char *renderer_options[] = { + "auto", + "gles2", + "vulkan", + "pixman", + NULL + }; + + const char *renderer_name = renderer_options[env_parse_switch("WLR_RENDERER", renderer_options)]; + bool is_auto = strcmp(renderer_name, "auto") == 0; + struct wlr_renderer *renderer = NULL; + + bool own_drm_fd = false; + + if ((is_auto && WLR_HAS_GLES2_RENDERER) || strcmp(renderer_name, "gles2") == 0) { + if (!open_preferred_drm_fd(backend, &drm_fd, &own_drm_fd)) { + log_creation_failure(is_auto, "Cannot create GLES2 renderer: no DRM FD available"); + } else { +#if WLR_HAS_GLES2_RENDERER + renderer = wlr_gles2_renderer_create_with_drm_fd(drm_fd); +#else + wlr_log(WLR_ERROR, "Cannot create GLES renderer: disabled at compile-time"); +#endif + if (renderer) { + goto out; + } else { + log_creation_failure(is_auto, "Failed to create a GLES2 renderer"); + } + } + } + + if ((is_auto && WLR_HAS_VULKAN_RENDERER) || strcmp(renderer_name, "vulkan") == 0) { + if (!open_preferred_drm_fd(backend, &drm_fd, &own_drm_fd)) { + log_creation_failure(is_auto, "Cannot create Vulkan renderer: no DRM FD available"); + } else { +#if WLR_HAS_VULKAN_RENDERER + renderer = wlr_vk_renderer_create_with_drm_fd(drm_fd); +#else + wlr_log(WLR_ERROR, "Cannot create Vulkan renderer: disabled at compile-time"); +#endif + if (renderer) { + goto out; + } else { + log_creation_failure(is_auto, "Failed to create a Vulkan renderer"); + } + } + } + + if ((is_auto && !has_render_node(backend)) || strcmp(renderer_name, "pixman") == 0) { + renderer = wlr_pixman_renderer_create(); + if (renderer) { + goto out; + } else { + log_creation_failure(is_auto, "Failed to create a pixman renderer"); + } + } + +out: + if (renderer == NULL) { + wlr_log(WLR_ERROR, "Could not initialize renderer"); + } + if (own_drm_fd && drm_fd >= 0) { + close(drm_fd); + } + if (renderer != NULL && env_parse_bool("WLR_RENDER_NO_EXPLICIT_SYNC")) { + renderer->features.timeline = false; + } + return renderer; +} + +struct wlr_renderer *renderer_autocreate_with_drm_fd(int drm_fd) { + assert(drm_fd >= 0); + + return renderer_autocreate(NULL, drm_fd); +} + +struct wlr_renderer *wlr_renderer_autocreate(struct wlr_backend *backend) { + return renderer_autocreate(backend, -1); +} + +int wlr_renderer_get_drm_fd(struct wlr_renderer *r) { + if (!r->impl->get_drm_fd) { + return -1; + } + return r->impl->get_drm_fd(r); +} + +struct wlr_render_pass *wlr_renderer_begin_buffer_pass(struct wlr_renderer *renderer, + struct wlr_buffer *buffer, const struct wlr_buffer_pass_options *options) { + struct wlr_buffer_pass_options default_options = {0}; + if (!options) { + options = &default_options; + } + + return renderer->impl->begin_buffer_pass(renderer, buffer, options); +} + +struct wlr_render_timer *wlr_render_timer_create(struct wlr_renderer *renderer) { + if (!renderer->impl->render_timer_create) { + return NULL; + } + return renderer->impl->render_timer_create(renderer); +} + +int wlr_render_timer_get_duration_ns(struct wlr_render_timer *timer) { + if (!timer->impl->get_duration_ns) { + return -1; + } + return timer->impl->get_duration_ns(timer); +} + +void wlr_render_timer_destroy(struct wlr_render_timer *timer) { + if (!timer->impl->destroy) { + return; + } + timer->impl->destroy(timer); +} diff --git a/3rdparty/wlroots/render/wlr_texture.c b/3rdparty/wlroots/render/wlr_texture.c new file mode 100644 index 0000000000..3526ee1402 --- /dev/null +++ b/3rdparty/wlroots/render/wlr_texture.c @@ -0,0 +1,137 @@ +#include +#include +#include +#include +#include +#include +#include +#include "render/pixel_format.h" +#include "types/wlr_buffer.h" + +void wlr_texture_init(struct wlr_texture *texture, struct wlr_renderer *renderer, + const struct wlr_texture_impl *impl, uint32_t width, uint32_t height) { + assert(renderer); + + *texture = (struct wlr_texture){ + .renderer = renderer, + .impl = impl, + .width = width, + .height = height, + }; +} + +void wlr_texture_destroy(struct wlr_texture *texture) { + if (texture && texture->impl && texture->impl->destroy) { + texture->impl->destroy(texture); + } else { + free(texture); + } +} + +void wlr_texture_read_pixels_options_get_src_box( + const struct wlr_texture_read_pixels_options *options, + const struct wlr_texture *texture, struct wlr_box *box) { + if (wlr_box_empty(&options->src_box)) { + *box = (struct wlr_box){ + .x = 0, + .y = 0, + .width = texture->width, + .height = texture->height, + }; + return; + } + + *box = options->src_box; +} + +void *wlr_texture_read_pixel_options_get_data( + const struct wlr_texture_read_pixels_options *options) { + const struct wlr_pixel_format_info *fmt = drm_get_pixel_format_info(options->format); + + return (char *)options->data + + pixel_format_info_min_stride(fmt, options->dst_x) + + options->dst_y * options->stride; +} + +bool wlr_texture_read_pixels(struct wlr_texture *texture, + const struct wlr_texture_read_pixels_options *options) { + if (!texture->impl->read_pixels) { + return false; + } + + return texture->impl->read_pixels(texture, options); +} + +uint32_t wlr_texture_preferred_read_format(struct wlr_texture *texture) { + if (!texture->impl->preferred_read_format) { + return DRM_FORMAT_INVALID; + } + + return texture->impl->preferred_read_format(texture); +} + +struct wlr_texture *wlr_texture_from_pixels(struct wlr_renderer *renderer, + uint32_t fmt, uint32_t stride, uint32_t width, uint32_t height, + const void *data) { + assert(width > 0); + assert(height > 0); + assert(stride > 0); + assert(data); + + struct wlr_readonly_data_buffer *buffer = + readonly_data_buffer_create(fmt, stride, width, height, data); + if (buffer == NULL) { + return NULL; + } + + struct wlr_texture *texture = + wlr_texture_from_buffer(renderer, &buffer->base); + + // By this point, the renderer should have locked the buffer if it still + // needs to access it in the future. + readonly_data_buffer_drop(buffer); + + return texture; +} + +struct wlr_texture *wlr_texture_from_dmabuf(struct wlr_renderer *renderer, + struct wlr_dmabuf_attributes *attribs) { + struct wlr_dmabuf_buffer *buffer = dmabuf_buffer_create(attribs); + if (buffer == NULL) { + return NULL; + } + + struct wlr_texture *texture = + wlr_texture_from_buffer(renderer, &buffer->base); + + // By this point, the renderer should have locked the buffer if it still + // needs to access it in the future. + dmabuf_buffer_drop(buffer); + + return texture; +} + +struct wlr_texture *wlr_texture_from_buffer(struct wlr_renderer *renderer, + struct wlr_buffer *buffer) { + if (!renderer->impl->texture_from_buffer) { + return NULL; + } + return renderer->impl->texture_from_buffer(renderer, buffer); +} + +bool wlr_texture_update_from_buffer(struct wlr_texture *texture, + struct wlr_buffer *buffer, const pixman_region32_t *damage) { + if (!texture->impl->update_from_buffer) { + return false; + } + if (texture->width != (uint32_t)buffer->width || + texture->height != (uint32_t)buffer->height) { + return false; + } + const pixman_box32_t *extents = pixman_region32_extents(damage); + if (extents->x1 < 0 || extents->y1 < 0 || extents->x2 > buffer->width || + extents->y2 > buffer->height) { + return false; + } + return texture->impl->update_from_buffer(texture, buffer, damage); +} diff --git a/3rdparty/wlroots/subprojects/libdisplay-info.wrap b/3rdparty/wlroots/subprojects/libdisplay-info.wrap new file mode 100644 index 0000000000..f92d3041f1 --- /dev/null +++ b/3rdparty/wlroots/subprojects/libdisplay-info.wrap @@ -0,0 +1,3 @@ +[wrap-git] +url = https://gitlab.freedesktop.org/emersion/libdisplay-info.git +revision = HEAD diff --git a/3rdparty/wlroots/subprojects/libdrm.wrap b/3rdparty/wlroots/subprojects/libdrm.wrap new file mode 100644 index 0000000000..2b5ca29c8b --- /dev/null +++ b/3rdparty/wlroots/subprojects/libdrm.wrap @@ -0,0 +1,3 @@ +[wrap-git] +url = https://gitlab.freedesktop.org/mesa/drm.git +revision = HEAD diff --git a/3rdparty/wlroots/subprojects/libliftoff.wrap b/3rdparty/wlroots/subprojects/libliftoff.wrap new file mode 100644 index 0000000000..57e6bb2317 --- /dev/null +++ b/3rdparty/wlroots/subprojects/libliftoff.wrap @@ -0,0 +1,3 @@ +[wrap-git] +url = https://gitlab.freedesktop.org/emersion/libliftoff.git +revision = HEAD diff --git a/3rdparty/wlroots/subprojects/libxkbcommon.wrap b/3rdparty/wlroots/subprojects/libxkbcommon.wrap new file mode 100644 index 0000000000..102b844969 --- /dev/null +++ b/3rdparty/wlroots/subprojects/libxkbcommon.wrap @@ -0,0 +1,3 @@ +[wrap-git] +url = https://github.com/xkbcommon/libxkbcommon.git +revision = HEAD diff --git a/3rdparty/wlroots/subprojects/pixman.wrap b/3rdparty/wlroots/subprojects/pixman.wrap new file mode 100644 index 0000000000..e34794a929 --- /dev/null +++ b/3rdparty/wlroots/subprojects/pixman.wrap @@ -0,0 +1,3 @@ +[wrap-git] +url = https://gitlab.freedesktop.org/pixman/pixman.git +revision = HEAD diff --git a/3rdparty/wlroots/subprojects/seatd.wrap b/3rdparty/wlroots/subprojects/seatd.wrap new file mode 100644 index 0000000000..2116366b80 --- /dev/null +++ b/3rdparty/wlroots/subprojects/seatd.wrap @@ -0,0 +1,3 @@ +[wrap-git] +url = https://git.sr.ht/~kennylevinsen/seatd +revision = HEAD diff --git a/3rdparty/wlroots/subprojects/wayland-protocols.wrap b/3rdparty/wlroots/subprojects/wayland-protocols.wrap new file mode 100644 index 0000000000..7b093efceb --- /dev/null +++ b/3rdparty/wlroots/subprojects/wayland-protocols.wrap @@ -0,0 +1,3 @@ +[wrap-git] +url = https://gitlab.freedesktop.org/wayland/wayland-protocols.git +revision = HEAD diff --git a/3rdparty/wlroots/subprojects/wayland.wrap b/3rdparty/wlroots/subprojects/wayland.wrap new file mode 100644 index 0000000000..18d2656714 --- /dev/null +++ b/3rdparty/wlroots/subprojects/wayland.wrap @@ -0,0 +1,3 @@ +[wrap-git] +url = https://gitlab.freedesktop.org/wayland/wayland.git +revision = HEAD diff --git a/3rdparty/wlroots/tinywl/.gitignore b/3rdparty/wlroots/tinywl/.gitignore new file mode 100644 index 0000000000..5de73fac92 --- /dev/null +++ b/3rdparty/wlroots/tinywl/.gitignore @@ -0,0 +1,3 @@ +tinywl +tinywl.o +*-protocol.h diff --git a/3rdparty/wlroots/tinywl/LICENSE b/3rdparty/wlroots/tinywl/LICENSE new file mode 100644 index 0000000000..0153f3022d --- /dev/null +++ b/3rdparty/wlroots/tinywl/LICENSE @@ -0,0 +1,125 @@ +This work is licensed under CC0, which effectively puts it in the public domain. + +--- + +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/3rdparty/wlroots/tinywl/Makefile b/3rdparty/wlroots/tinywl/Makefile new file mode 100644 index 0000000000..2efe4a436c --- /dev/null +++ b/3rdparty/wlroots/tinywl/Makefile @@ -0,0 +1,18 @@ +PKG_CONFIG?=pkg-config + +PKGS="wlroots-0.20" wayland-server xkbcommon +CFLAGS_PKG_CONFIG!=$(PKG_CONFIG) --cflags $(PKGS) +CFLAGS+=$(CFLAGS_PKG_CONFIG) +LIBS!=$(PKG_CONFIG) --libs $(PKGS) + +all: tinywl + +tinywl.o: tinywl.c + $(CC) -c $< -g -Werror $(CFLAGS) -I. -DWLR_USE_UNSTABLE -o $@ +tinywl: tinywl.o + $(CC) $^ -g -Werror $(CFLAGS) $(LDFLAGS) $(LIBS) -o $@ + +clean: + rm -f tinywl tinywl.o + +.PHONY: all clean diff --git a/3rdparty/wlroots/tinywl/README.md b/3rdparty/wlroots/tinywl/README.md new file mode 100644 index 0000000000..7fc83b96df --- /dev/null +++ b/3rdparty/wlroots/tinywl/README.md @@ -0,0 +1,45 @@ +# TinyWL + +This is the "minimum viable product" Wayland compositor based on wlroots. It +aims to implement a Wayland compositor in the fewest lines of code possible, +while still supporting a reasonable set of features. Reading this code is the +best starting point for anyone looking to build their own Wayland compositor +based on wlroots. + +## Building TinyWL + +TinyWL is disconnected from the main wlroots build system, in order to make it +easier to understand the build requirements for your own Wayland compositors. +Simply install the dependencies: + +- wlroots +- wayland-protocols + +And run `make`. + +## Running TinyWL + +You can run TinyWL with `./tinywl`. In an existing Wayland or X11 session, +tinywl will open a Wayland or X11 window respectively to act as a virtual +display. You can then open Wayland windows by setting `WAYLAND_DISPLAY` to the +value shown in the logs. You can also run `./tinywl` from a TTY. + +In either case, you will likely want to specify `-s [cmd]` to run a command at +startup, such as a terminal emulator. This will be necessary to start any new +programs from within the compositor, as TinyWL does not support any custom +keybindings. TinyWL supports the following keybindings: + +- `Alt+Escape`: Terminate the compositor +- `Alt+F1`: Cycle between windows + +## Limitations + +Notable omissions from TinyWL: + +- HiDPI support +- Any kind of configuration, e.g. output layout +- Any protocol other than xdg-shell (e.g. layer-shell, for + panels/taskbars/etc; or Xwayland, for proxied X11 windows) +- Optional protocols, e.g. screen capture, primary selection, virtual + keyboard, etc. Most of these are plug-and-play with wlroots, but they're + omitted for brevity. diff --git a/3rdparty/wlroots/tinywl/meson.build b/3rdparty/wlroots/tinywl/meson.build new file mode 100644 index 0000000000..07b4a5e993 --- /dev/null +++ b/3rdparty/wlroots/tinywl/meson.build @@ -0,0 +1,5 @@ +executable( + 'tinywl', + 'tinywl.c', + dependencies: wlroots, +) diff --git a/3rdparty/wlroots/tinywl/tinywl.c b/3rdparty/wlroots/tinywl/tinywl.c new file mode 100644 index 0000000000..fe242e1a93 --- /dev/null +++ b/3rdparty/wlroots/tinywl/tinywl.c @@ -0,0 +1,1101 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* For brevity's sake, struct members are annotated where they are used. */ +enum tinywl_cursor_mode { + TINYWL_CURSOR_PASSTHROUGH, + TINYWL_CURSOR_MOVE, + TINYWL_CURSOR_RESIZE, +}; + +struct tinywl_server { + struct wl_display *wl_display; + struct wlr_backend *backend; + struct wlr_renderer *renderer; + struct wlr_allocator *allocator; + struct wlr_scene *scene; + struct wlr_scene_output_layout *scene_layout; + + struct wlr_xdg_shell *xdg_shell; + struct wl_listener new_xdg_toplevel; + struct wl_listener new_xdg_popup; + struct wl_list toplevels; + + struct wlr_cursor *cursor; + struct wlr_xcursor_manager *cursor_mgr; + struct wl_listener cursor_motion; + struct wl_listener cursor_motion_absolute; + struct wl_listener cursor_button; + struct wl_listener cursor_axis; + struct wl_listener cursor_frame; + + struct wlr_seat *seat; + struct wl_listener new_input; + struct wl_listener request_cursor; + struct wl_listener pointer_focus_change; + struct wl_listener request_set_selection; + struct wl_list keyboards; + enum tinywl_cursor_mode cursor_mode; + struct tinywl_toplevel *grabbed_toplevel; + double grab_x, grab_y; + struct wlr_box grab_geobox; + uint32_t resize_edges; + + struct wlr_output_layout *output_layout; + struct wl_list outputs; + struct wl_listener new_output; +}; + +struct tinywl_output { + struct wl_list link; + struct tinywl_server *server; + struct wlr_output *wlr_output; + struct wl_listener frame; + struct wl_listener request_state; + struct wl_listener destroy; +}; + +struct tinywl_toplevel { + struct wl_list link; + struct tinywl_server *server; + struct wlr_xdg_toplevel *xdg_toplevel; + struct wlr_scene_tree *scene_tree; + struct wl_listener map; + struct wl_listener unmap; + struct wl_listener commit; + struct wl_listener destroy; + struct wl_listener request_move; + struct wl_listener request_resize; + struct wl_listener request_maximize; + struct wl_listener request_fullscreen; +}; + +struct tinywl_popup { + struct wlr_xdg_popup *xdg_popup; + struct wl_listener commit; + struct wl_listener destroy; +}; + +struct tinywl_keyboard { + struct wl_list link; + struct tinywl_server *server; + struct wlr_keyboard *wlr_keyboard; + + struct wl_listener modifiers; + struct wl_listener key; + struct wl_listener destroy; +}; + +static void focus_toplevel(struct tinywl_toplevel *toplevel) { + /* Note: this function only deals with keyboard focus. */ + if (toplevel == NULL) { + return; + } + struct tinywl_server *server = toplevel->server; + struct wlr_seat *seat = server->seat; + struct wlr_surface *prev_surface = seat->keyboard_state.focused_surface; + struct wlr_surface *surface = toplevel->xdg_toplevel->base->surface; + if (prev_surface == surface) { + /* Don't re-focus an already focused surface. */ + return; + } + if (prev_surface) { + /* + * Deactivate the previously focused surface. This lets the client know + * it no longer has focus and the client will repaint accordingly, e.g. + * stop displaying a caret. + */ + struct wlr_xdg_toplevel *prev_toplevel = + wlr_xdg_toplevel_try_from_wlr_surface(prev_surface); + if (prev_toplevel != NULL) { + wlr_xdg_toplevel_set_activated(prev_toplevel, false); + } + } + struct wlr_keyboard *keyboard = wlr_seat_get_keyboard(seat); + /* Move the toplevel to the front */ + wlr_scene_node_raise_to_top(&toplevel->scene_tree->node); + wl_list_remove(&toplevel->link); + wl_list_insert(&server->toplevels, &toplevel->link); + /* Activate the new surface */ + wlr_xdg_toplevel_set_activated(toplevel->xdg_toplevel, true); + /* + * Tell the seat to have the keyboard enter this surface. wlroots will keep + * track of this and automatically send key events to the appropriate + * clients without additional work on your part. + */ + if (keyboard != NULL) { + wlr_seat_keyboard_notify_enter(seat, surface, + keyboard->keycodes, keyboard->num_keycodes, &keyboard->modifiers); + } +} + +static void keyboard_handle_modifiers( + struct wl_listener *listener, void *data) { + /* This event is raised when a modifier key, such as shift or alt, is + * pressed. We simply communicate this to the client. */ + struct tinywl_keyboard *keyboard = + wl_container_of(listener, keyboard, modifiers); + /* + * A seat can only have one keyboard, but this is a limitation of the + * Wayland protocol - not wlroots. We assign all connected keyboards to the + * same seat. You can swap out the underlying wlr_keyboard like this and + * wlr_seat handles this transparently. + */ + wlr_seat_set_keyboard(keyboard->server->seat, keyboard->wlr_keyboard); + /* Send modifiers to the client. */ + wlr_seat_keyboard_notify_modifiers(keyboard->server->seat, + &keyboard->wlr_keyboard->modifiers); +} + +static bool handle_keybinding(struct tinywl_server *server, xkb_keysym_t sym) { + /* + * Here we handle compositor keybindings. This is when the compositor is + * processing keys, rather than passing them on to the client for its own + * processing. + * + * This function assumes Alt is held down. + */ + switch (sym) { + case XKB_KEY_Escape: + wl_display_terminate(server->wl_display); + break; + case XKB_KEY_F1: + /* Cycle to the next toplevel */ + if (wl_list_length(&server->toplevels) < 2) { + break; + } + struct tinywl_toplevel *next_toplevel = + wl_container_of(server->toplevels.prev, next_toplevel, link); + focus_toplevel(next_toplevel); + break; + default: + return false; + } + return true; +} + +static void keyboard_handle_key( + struct wl_listener *listener, void *data) { + /* This event is raised when a key is pressed or released. */ + struct tinywl_keyboard *keyboard = + wl_container_of(listener, keyboard, key); + struct tinywl_server *server = keyboard->server; + struct wlr_keyboard_key_event *event = data; + struct wlr_seat *seat = server->seat; + + /* Translate libinput keycode -> xkbcommon */ + uint32_t keycode = event->keycode + 8; + /* Get a list of keysyms based on the keymap for this keyboard */ + const xkb_keysym_t *syms; + int nsyms = xkb_state_key_get_syms( + keyboard->wlr_keyboard->xkb_state, keycode, &syms); + + bool handled = false; + uint32_t modifiers = wlr_keyboard_get_modifiers(keyboard->wlr_keyboard); + if ((modifiers & WLR_MODIFIER_ALT) && + event->state == WL_KEYBOARD_KEY_STATE_PRESSED) { + /* If alt is held down and this button was _pressed_, we attempt to + * process it as a compositor keybinding. */ + for (int i = 0; i < nsyms; i++) { + handled = handle_keybinding(server, syms[i]); + } + } + + if (!handled) { + /* Otherwise, we pass it along to the client. */ + wlr_seat_set_keyboard(seat, keyboard->wlr_keyboard); + wlr_seat_keyboard_notify_key(seat, event->time_msec, + event->keycode, event->state); + } +} + +static void keyboard_handle_destroy(struct wl_listener *listener, void *data) { + /* This event is raised by the keyboard base wlr_input_device to signal + * the destruction of the wlr_keyboard. It will no longer receive events + * and should be destroyed. + */ + struct tinywl_keyboard *keyboard = + wl_container_of(listener, keyboard, destroy); + wl_list_remove(&keyboard->modifiers.link); + wl_list_remove(&keyboard->key.link); + wl_list_remove(&keyboard->destroy.link); + wl_list_remove(&keyboard->link); + free(keyboard); +} + +static void server_new_keyboard(struct tinywl_server *server, + struct wlr_input_device *device) { + struct wlr_keyboard *wlr_keyboard = wlr_keyboard_from_input_device(device); + + struct tinywl_keyboard *keyboard = calloc(1, sizeof(*keyboard)); + keyboard->server = server; + keyboard->wlr_keyboard = wlr_keyboard; + + /* We need to prepare an XKB keymap and assign it to the keyboard. This + * assumes the defaults (e.g. layout = "us"). */ + struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + struct xkb_keymap *keymap = xkb_keymap_new_from_names(context, NULL, + XKB_KEYMAP_COMPILE_NO_FLAGS); + + wlr_keyboard_set_keymap(wlr_keyboard, keymap); + xkb_keymap_unref(keymap); + xkb_context_unref(context); + wlr_keyboard_set_repeat_info(wlr_keyboard, 25, 600); + + /* Here we set up listeners for keyboard events. */ + keyboard->modifiers.notify = keyboard_handle_modifiers; + wl_signal_add(&wlr_keyboard->events.modifiers, &keyboard->modifiers); + keyboard->key.notify = keyboard_handle_key; + wl_signal_add(&wlr_keyboard->events.key, &keyboard->key); + keyboard->destroy.notify = keyboard_handle_destroy; + wl_signal_add(&device->events.destroy, &keyboard->destroy); + + wlr_seat_set_keyboard(server->seat, keyboard->wlr_keyboard); + + /* And add the keyboard to our list of keyboards */ + wl_list_insert(&server->keyboards, &keyboard->link); +} + +static void server_new_pointer(struct tinywl_server *server, + struct wlr_input_device *device) { + /* We don't do anything special with pointers. All of our pointer handling + * is proxied through wlr_cursor. On another compositor, you might take this + * opportunity to do libinput configuration on the device to set + * acceleration, etc. */ + wlr_cursor_attach_input_device(server->cursor, device); +} + +static void server_new_input(struct wl_listener *listener, void *data) { + /* This event is raised by the backend when a new input device becomes + * available. */ + struct tinywl_server *server = + wl_container_of(listener, server, new_input); + struct wlr_input_device *device = data; + switch (device->type) { + case WLR_INPUT_DEVICE_KEYBOARD: + server_new_keyboard(server, device); + break; + case WLR_INPUT_DEVICE_POINTER: + server_new_pointer(server, device); + break; + default: + break; + } + /* We need to let the wlr_seat know what our capabilities are, which is + * communiciated to the client. In TinyWL we always have a cursor, even if + * there are no pointer devices, so we always include that capability. */ + uint32_t caps = WL_SEAT_CAPABILITY_POINTER; + if (!wl_list_empty(&server->keyboards)) { + caps |= WL_SEAT_CAPABILITY_KEYBOARD; + } + wlr_seat_set_capabilities(server->seat, caps); +} + +static void seat_request_cursor(struct wl_listener *listener, void *data) { + struct tinywl_server *server = wl_container_of( + listener, server, request_cursor); + /* This event is raised by the seat when a client provides a cursor image */ + struct wlr_seat_pointer_request_set_cursor_event *event = data; + struct wlr_seat_client *focused_client = + server->seat->pointer_state.focused_client; + /* This can be sent by any client, so we check to make sure this one is + * actually has pointer focus first. */ + if (focused_client == event->seat_client) { + /* Once we've vetted the client, we can tell the cursor to use the + * provided surface as the cursor image. It will set the hardware cursor + * on the output that it's currently on and continue to do so as the + * cursor moves between outputs. */ + wlr_cursor_set_surface(server->cursor, event->surface, + event->hotspot_x, event->hotspot_y); + } +} + +static void seat_pointer_focus_change(struct wl_listener *listener, void *data) { + struct tinywl_server *server = wl_container_of( + listener, server, pointer_focus_change); + /* This event is raised when the pointer focus is changed, including when the + * client is closed. We set the cursor image to its default if target surface + * is NULL */ + struct wlr_seat_pointer_focus_change_event *event = data; + if (event->new_surface == NULL) { + wlr_cursor_set_xcursor(server->cursor, server->cursor_mgr, "default"); + } +} + +static void seat_request_set_selection(struct wl_listener *listener, void *data) { + /* This event is raised by the seat when a client wants to set the selection, + * usually when the user copies something. wlroots allows compositors to + * ignore such requests if they so choose, but in tinywl we always honor + */ + struct tinywl_server *server = wl_container_of( + listener, server, request_set_selection); + struct wlr_seat_request_set_selection_event *event = data; + wlr_seat_set_selection(server->seat, event->source, event->serial); +} + +static struct tinywl_toplevel *desktop_toplevel_at( + struct tinywl_server *server, double lx, double ly, + struct wlr_surface **surface, double *sx, double *sy) { + /* This returns the topmost node in the scene at the given layout coords. + * We only care about surface nodes as we are specifically looking for a + * surface in the surface tree of a tinywl_toplevel. */ + struct wlr_scene_node *node = wlr_scene_node_at( + &server->scene->tree.node, lx, ly, sx, sy); + if (node == NULL || node->type != WLR_SCENE_NODE_BUFFER) { + return NULL; + } + struct wlr_scene_buffer *scene_buffer = wlr_scene_buffer_from_node(node); + struct wlr_scene_surface *scene_surface = + wlr_scene_surface_try_from_buffer(scene_buffer); + if (!scene_surface) { + return NULL; + } + + *surface = scene_surface->surface; + /* Find the node corresponding to the tinywl_toplevel at the root of this + * surface tree, it is the only one for which we set the data field. */ + struct wlr_scene_tree *tree = node->parent; + while (tree != NULL && tree->node.data == NULL) { + tree = tree->node.parent; + } + return tree->node.data; +} + +static void reset_cursor_mode(struct tinywl_server *server) { + /* Reset the cursor mode to passthrough. */ + server->cursor_mode = TINYWL_CURSOR_PASSTHROUGH; + server->grabbed_toplevel = NULL; +} + +static void process_cursor_move(struct tinywl_server *server) { + /* Move the grabbed toplevel to the new position. */ + struct tinywl_toplevel *toplevel = server->grabbed_toplevel; + wlr_scene_node_set_position(&toplevel->scene_tree->node, + server->cursor->x - server->grab_x, + server->cursor->y - server->grab_y); +} + +static void process_cursor_resize(struct tinywl_server *server) { + /* + * Resizing the grabbed toplevel can be a little bit complicated, because we + * could be resizing from any corner or edge. This not only resizes the + * toplevel on one or two axes, but can also move the toplevel if you resize + * from the top or left edges (or top-left corner). + * + * Note that some shortcuts are taken here. In a more fleshed-out + * compositor, you'd wait for the client to prepare a buffer at the new + * size, then commit any movement that was prepared. + */ + struct tinywl_toplevel *toplevel = server->grabbed_toplevel; + double border_x = server->cursor->x - server->grab_x; + double border_y = server->cursor->y - server->grab_y; + int new_left = server->grab_geobox.x; + int new_right = server->grab_geobox.x + server->grab_geobox.width; + int new_top = server->grab_geobox.y; + int new_bottom = server->grab_geobox.y + server->grab_geobox.height; + + if (server->resize_edges & WLR_EDGE_TOP) { + new_top = border_y; + if (new_top >= new_bottom) { + new_top = new_bottom - 1; + } + } else if (server->resize_edges & WLR_EDGE_BOTTOM) { + new_bottom = border_y; + if (new_bottom <= new_top) { + new_bottom = new_top + 1; + } + } + if (server->resize_edges & WLR_EDGE_LEFT) { + new_left = border_x; + if (new_left >= new_right) { + new_left = new_right - 1; + } + } else if (server->resize_edges & WLR_EDGE_RIGHT) { + new_right = border_x; + if (new_right <= new_left) { + new_right = new_left + 1; + } + } + + struct wlr_box *geo_box = &toplevel->xdg_toplevel->base->geometry; + wlr_scene_node_set_position(&toplevel->scene_tree->node, + new_left - geo_box->x, new_top - geo_box->y); + + int new_width = new_right - new_left; + int new_height = new_bottom - new_top; + wlr_xdg_toplevel_set_size(toplevel->xdg_toplevel, new_width, new_height); +} + +static void process_cursor_motion(struct tinywl_server *server, uint32_t time) { + /* If the mode is non-passthrough, delegate to those functions. */ + if (server->cursor_mode == TINYWL_CURSOR_MOVE) { + process_cursor_move(server); + return; + } else if (server->cursor_mode == TINYWL_CURSOR_RESIZE) { + process_cursor_resize(server); + return; + } + + /* Otherwise, find the toplevel under the pointer and send the event along. */ + double sx, sy; + struct wlr_seat *seat = server->seat; + struct wlr_surface *surface = NULL; + struct tinywl_toplevel *toplevel = desktop_toplevel_at(server, + server->cursor->x, server->cursor->y, &surface, &sx, &sy); + if (!toplevel) { + /* If there's no toplevel under the cursor, set the cursor image to a + * default. This is what makes the cursor image appear when you move it + * around the screen, not over any toplevels. */ + wlr_cursor_set_xcursor(server->cursor, server->cursor_mgr, "default"); + } + if (surface) { + /* + * Send pointer enter and motion events. + * + * The enter event gives the surface "pointer focus", which is distinct + * from keyboard focus. You get pointer focus by moving the pointer over + * a window. + * + * Note that wlroots will avoid sending duplicate enter/motion events if + * the surface has already has pointer focus or if the client is already + * aware of the coordinates passed. + */ + wlr_seat_pointer_notify_enter(seat, surface, sx, sy); + wlr_seat_pointer_notify_motion(seat, time, sx, sy); + } else { + /* Clear pointer focus so future button events and such are not sent to + * the last client to have the cursor over it. */ + wlr_seat_pointer_clear_focus(seat); + } +} + +static void server_cursor_motion(struct wl_listener *listener, void *data) { + /* This event is forwarded by the cursor when a pointer emits a _relative_ + * pointer motion event (i.e. a delta) */ + struct tinywl_server *server = + wl_container_of(listener, server, cursor_motion); + struct wlr_pointer_motion_event *event = data; + /* The cursor doesn't move unless we tell it to. The cursor automatically + * handles constraining the motion to the output layout, as well as any + * special configuration applied for the specific input device which + * generated the event. You can pass NULL for the device if you want to move + * the cursor around without any input. */ + wlr_cursor_move(server->cursor, &event->pointer->base, + event->delta_x, event->delta_y); + process_cursor_motion(server, event->time_msec); +} + +static void server_cursor_motion_absolute( + struct wl_listener *listener, void *data) { + /* This event is forwarded by the cursor when a pointer emits an _absolute_ + * motion event, from 0..1 on each axis. This happens, for example, when + * wlroots is running under a Wayland window rather than KMS+DRM, and you + * move the mouse over the window. You could enter the window from any edge, + * so we have to warp the mouse there. There is also some hardware which + * emits these events. */ + struct tinywl_server *server = + wl_container_of(listener, server, cursor_motion_absolute); + struct wlr_pointer_motion_absolute_event *event = data; + wlr_cursor_warp_absolute(server->cursor, &event->pointer->base, event->x, + event->y); + process_cursor_motion(server, event->time_msec); +} + +static void server_cursor_button(struct wl_listener *listener, void *data) { + /* This event is forwarded by the cursor when a pointer emits a button + * event. */ + struct tinywl_server *server = + wl_container_of(listener, server, cursor_button); + struct wlr_pointer_button_event *event = data; + /* Notify the client with pointer focus that a button press has occurred */ + wlr_seat_pointer_notify_button(server->seat, + event->time_msec, event->button, event->state); + if (event->state == WL_POINTER_BUTTON_STATE_RELEASED) { + /* If you released any buttons, we exit interactive move/resize mode. */ + reset_cursor_mode(server); + } else { + /* Focus that client if the button was _pressed_ */ + double sx, sy; + struct wlr_surface *surface = NULL; + struct tinywl_toplevel *toplevel = desktop_toplevel_at(server, + server->cursor->x, server->cursor->y, &surface, &sx, &sy); + focus_toplevel(toplevel); + } +} + +static void server_cursor_axis(struct wl_listener *listener, void *data) { + /* This event is forwarded by the cursor when a pointer emits an axis event, + * for example when you move the scroll wheel. */ + struct tinywl_server *server = + wl_container_of(listener, server, cursor_axis); + struct wlr_pointer_axis_event *event = data; + /* Notify the client with pointer focus of the axis event. */ + wlr_seat_pointer_notify_axis(server->seat, + event->time_msec, event->orientation, event->delta, + event->delta_discrete, event->source, event->relative_direction); +} + +static void server_cursor_frame(struct wl_listener *listener, void *data) { + /* This event is forwarded by the cursor when a pointer emits an frame + * event. Frame events are sent after regular pointer events to group + * multiple events together. For instance, two axis events may happen at the + * same time, in which case a frame event won't be sent in between. */ + struct tinywl_server *server = + wl_container_of(listener, server, cursor_frame); + /* Notify the client with pointer focus of the frame event. */ + wlr_seat_pointer_notify_frame(server->seat); +} + +static void output_frame(struct wl_listener *listener, void *data) { + /* This function is called every time an output is ready to display a frame, + * generally at the output's refresh rate (e.g. 60Hz). */ + struct tinywl_output *output = wl_container_of(listener, output, frame); + struct wlr_scene *scene = output->server->scene; + + struct wlr_scene_output *scene_output = wlr_scene_get_scene_output( + scene, output->wlr_output); + + /* Render the scene if needed and commit the output */ + wlr_scene_output_commit(scene_output, NULL); + + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + wlr_scene_output_send_frame_done(scene_output, &now); +} + +static void output_request_state(struct wl_listener *listener, void *data) { + /* This function is called when the backend requests a new state for + * the output. For example, Wayland and X11 backends request a new mode + * when the output window is resized. */ + struct tinywl_output *output = wl_container_of(listener, output, request_state); + const struct wlr_output_event_request_state *event = data; + wlr_output_commit_state(output->wlr_output, event->state); +} + +static void output_destroy(struct wl_listener *listener, void *data) { + struct tinywl_output *output = wl_container_of(listener, output, destroy); + + wl_list_remove(&output->frame.link); + wl_list_remove(&output->request_state.link); + wl_list_remove(&output->destroy.link); + wl_list_remove(&output->link); + free(output); +} + +static void server_new_output(struct wl_listener *listener, void *data) { + /* This event is raised by the backend when a new output (aka a display or + * monitor) becomes available. */ + struct tinywl_server *server = + wl_container_of(listener, server, new_output); + struct wlr_output *wlr_output = data; + + /* Configures the output created by the backend to use our allocator + * and our renderer. Must be done once, before committing the output */ + wlr_output_init_render(wlr_output, server->allocator, server->renderer); + + /* The output may be disabled, switch it on. */ + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, true); + + /* Some backends don't have modes. DRM+KMS does, and we need to set a mode + * before we can use the output. The mode is a tuple of (width, height, + * refresh rate), and each monitor supports only a specific set of modes. We + * just pick the monitor's preferred mode, a more sophisticated compositor + * would let the user configure it. */ + struct wlr_output_mode *mode = wlr_output_preferred_mode(wlr_output); + if (mode != NULL) { + wlr_output_state_set_mode(&state, mode); + } + + /* Atomically applies the new output state. */ + wlr_output_commit_state(wlr_output, &state); + wlr_output_state_finish(&state); + + /* Allocates and configures our state for this output */ + struct tinywl_output *output = calloc(1, sizeof(*output)); + output->wlr_output = wlr_output; + output->server = server; + + /* Sets up a listener for the frame event. */ + output->frame.notify = output_frame; + wl_signal_add(&wlr_output->events.frame, &output->frame); + + /* Sets up a listener for the state request event. */ + output->request_state.notify = output_request_state; + wl_signal_add(&wlr_output->events.request_state, &output->request_state); + + /* Sets up a listener for the destroy event. */ + output->destroy.notify = output_destroy; + wl_signal_add(&wlr_output->events.destroy, &output->destroy); + + wl_list_insert(&server->outputs, &output->link); + + /* Adds this to the output layout. The add_auto function arranges outputs + * from left-to-right in the order they appear. A more sophisticated + * compositor would let the user configure the arrangement of outputs in the + * layout. + * + * The output layout utility automatically adds a wl_output global to the + * display, which Wayland clients can see to find out information about the + * output (such as DPI, scale factor, manufacturer, etc). + */ + struct wlr_output_layout_output *l_output = wlr_output_layout_add_auto(server->output_layout, + wlr_output); + struct wlr_scene_output *scene_output = wlr_scene_output_create(server->scene, wlr_output); + wlr_scene_output_layout_add_output(server->scene_layout, l_output, scene_output); +} + +static void xdg_toplevel_map(struct wl_listener *listener, void *data) { + /* Called when the surface is mapped, or ready to display on-screen. */ + struct tinywl_toplevel *toplevel = wl_container_of(listener, toplevel, map); + + wl_list_insert(&toplevel->server->toplevels, &toplevel->link); + + focus_toplevel(toplevel); +} + +static void xdg_toplevel_unmap(struct wl_listener *listener, void *data) { + /* Called when the surface is unmapped, and should no longer be shown. */ + struct tinywl_toplevel *toplevel = wl_container_of(listener, toplevel, unmap); + + /* Reset the cursor mode if the grabbed toplevel was unmapped. */ + if (toplevel == toplevel->server->grabbed_toplevel) { + reset_cursor_mode(toplevel->server); + } + + wl_list_remove(&toplevel->link); +} + +static void xdg_toplevel_commit(struct wl_listener *listener, void *data) { + /* Called when a new surface state is committed. */ + struct tinywl_toplevel *toplevel = wl_container_of(listener, toplevel, commit); + + if (toplevel->xdg_toplevel->base->initial_commit) { + /* When an xdg_surface performs an initial commit, the compositor must + * reply with a configure so the client can map the surface. tinywl + * configures the xdg_toplevel with 0,0 size to let the client pick the + * dimensions itself. */ + wlr_xdg_toplevel_set_size(toplevel->xdg_toplevel, 0, 0); + } +} + +static void xdg_toplevel_destroy(struct wl_listener *listener, void *data) { + /* Called when the xdg_toplevel is destroyed. */ + struct tinywl_toplevel *toplevel = wl_container_of(listener, toplevel, destroy); + + wl_list_remove(&toplevel->map.link); + wl_list_remove(&toplevel->unmap.link); + wl_list_remove(&toplevel->commit.link); + wl_list_remove(&toplevel->destroy.link); + wl_list_remove(&toplevel->request_move.link); + wl_list_remove(&toplevel->request_resize.link); + wl_list_remove(&toplevel->request_maximize.link); + wl_list_remove(&toplevel->request_fullscreen.link); + + free(toplevel); +} + +static void begin_interactive(struct tinywl_toplevel *toplevel, + enum tinywl_cursor_mode mode, uint32_t edges) { + /* This function sets up an interactive move or resize operation, where the + * compositor stops propagating pointer events to clients and instead + * consumes them itself, to move or resize windows. */ + struct tinywl_server *server = toplevel->server; + + server->grabbed_toplevel = toplevel; + server->cursor_mode = mode; + + if (mode == TINYWL_CURSOR_MOVE) { + server->grab_x = server->cursor->x - toplevel->scene_tree->node.x; + server->grab_y = server->cursor->y - toplevel->scene_tree->node.y; + } else { + struct wlr_box *geo_box = &toplevel->xdg_toplevel->base->geometry; + + double border_x = (toplevel->scene_tree->node.x + geo_box->x) + + ((edges & WLR_EDGE_RIGHT) ? geo_box->width : 0); + double border_y = (toplevel->scene_tree->node.y + geo_box->y) + + ((edges & WLR_EDGE_BOTTOM) ? geo_box->height : 0); + server->grab_x = server->cursor->x - border_x; + server->grab_y = server->cursor->y - border_y; + + server->grab_geobox = *geo_box; + server->grab_geobox.x += toplevel->scene_tree->node.x; + server->grab_geobox.y += toplevel->scene_tree->node.y; + + server->resize_edges = edges; + } +} + +static void xdg_toplevel_request_move( + struct wl_listener *listener, void *data) { + /* This event is raised when a client would like to begin an interactive + * move, typically because the user clicked on their client-side + * decorations. Note that a more sophisticated compositor should check the + * provided serial against a list of button press serials sent to this + * client, to prevent the client from requesting this whenever they want. */ + struct tinywl_toplevel *toplevel = wl_container_of(listener, toplevel, request_move); + begin_interactive(toplevel, TINYWL_CURSOR_MOVE, 0); +} + +static void xdg_toplevel_request_resize( + struct wl_listener *listener, void *data) { + /* This event is raised when a client would like to begin an interactive + * resize, typically because the user clicked on their client-side + * decorations. Note that a more sophisticated compositor should check the + * provided serial against a list of button press serials sent to this + * client, to prevent the client from requesting this whenever they want. */ + struct wlr_xdg_toplevel_resize_event *event = data; + struct tinywl_toplevel *toplevel = wl_container_of(listener, toplevel, request_resize); + begin_interactive(toplevel, TINYWL_CURSOR_RESIZE, event->edges); +} + +static void xdg_toplevel_request_maximize( + struct wl_listener *listener, void *data) { + /* This event is raised when a client would like to maximize itself, + * typically because the user clicked on the maximize button on client-side + * decorations. tinywl doesn't support maximization, but to conform to + * xdg-shell protocol we still must send a configure. + * wlr_xdg_surface_schedule_configure() is used to send an empty reply. + * However, if the request was sent before an initial commit, we don't do + * anything and let the client finish the initial surface setup. */ + struct tinywl_toplevel *toplevel = + wl_container_of(listener, toplevel, request_maximize); + if (toplevel->xdg_toplevel->base->initialized) { + wlr_xdg_surface_schedule_configure(toplevel->xdg_toplevel->base); + } +} + +static void xdg_toplevel_request_fullscreen( + struct wl_listener *listener, void *data) { + /* Just as with request_maximize, we must send a configure here. */ + struct tinywl_toplevel *toplevel = + wl_container_of(listener, toplevel, request_fullscreen); + if (toplevel->xdg_toplevel->base->initialized) { + wlr_xdg_surface_schedule_configure(toplevel->xdg_toplevel->base); + } +} + +static void server_new_xdg_toplevel(struct wl_listener *listener, void *data) { + /* This event is raised when a client creates a new toplevel (application window). */ + struct tinywl_server *server = wl_container_of(listener, server, new_xdg_toplevel); + struct wlr_xdg_toplevel *xdg_toplevel = data; + + /* Allocate a tinywl_toplevel for this surface */ + struct tinywl_toplevel *toplevel = calloc(1, sizeof(*toplevel)); + toplevel->server = server; + toplevel->xdg_toplevel = xdg_toplevel; + toplevel->scene_tree = + wlr_scene_xdg_surface_create(&toplevel->server->scene->tree, xdg_toplevel->base); + toplevel->scene_tree->node.data = toplevel; + xdg_toplevel->base->data = toplevel->scene_tree; + + /* Listen to the various events it can emit */ + toplevel->map.notify = xdg_toplevel_map; + wl_signal_add(&xdg_toplevel->base->surface->events.map, &toplevel->map); + toplevel->unmap.notify = xdg_toplevel_unmap; + wl_signal_add(&xdg_toplevel->base->surface->events.unmap, &toplevel->unmap); + toplevel->commit.notify = xdg_toplevel_commit; + wl_signal_add(&xdg_toplevel->base->surface->events.commit, &toplevel->commit); + + toplevel->destroy.notify = xdg_toplevel_destroy; + wl_signal_add(&xdg_toplevel->events.destroy, &toplevel->destroy); + + /* cotd */ + toplevel->request_move.notify = xdg_toplevel_request_move; + wl_signal_add(&xdg_toplevel->events.request_move, &toplevel->request_move); + toplevel->request_resize.notify = xdg_toplevel_request_resize; + wl_signal_add(&xdg_toplevel->events.request_resize, &toplevel->request_resize); + toplevel->request_maximize.notify = xdg_toplevel_request_maximize; + wl_signal_add(&xdg_toplevel->events.request_maximize, &toplevel->request_maximize); + toplevel->request_fullscreen.notify = xdg_toplevel_request_fullscreen; + wl_signal_add(&xdg_toplevel->events.request_fullscreen, &toplevel->request_fullscreen); +} + +static void xdg_popup_commit(struct wl_listener *listener, void *data) { + /* Called when a new surface state is committed. */ + struct tinywl_popup *popup = wl_container_of(listener, popup, commit); + + if (popup->xdg_popup->base->initial_commit) { + /* When an xdg_surface performs an initial commit, the compositor must + * reply with a configure so the client can map the surface. + * tinywl sends an empty configure. A more sophisticated compositor + * might change an xdg_popup's geometry to ensure it's not positioned + * off-screen, for example. */ + wlr_xdg_surface_schedule_configure(popup->xdg_popup->base); + } +} + +static void xdg_popup_destroy(struct wl_listener *listener, void *data) { + /* Called when the xdg_popup is destroyed. */ + struct tinywl_popup *popup = wl_container_of(listener, popup, destroy); + + wl_list_remove(&popup->commit.link); + wl_list_remove(&popup->destroy.link); + + free(popup); +} + +static void server_new_xdg_popup(struct wl_listener *listener, void *data) { + /* This event is raised when a client creates a new popup. */ + struct wlr_xdg_popup *xdg_popup = data; + + struct tinywl_popup *popup = calloc(1, sizeof(*popup)); + popup->xdg_popup = xdg_popup; + + /* We must add xdg popups to the scene graph so they get rendered. The + * wlroots scene graph provides a helper for this, but to use it we must + * provide the proper parent scene node of the xdg popup. To enable this, + * we always set the user data field of xdg_surfaces to the corresponding + * scene node. */ + struct wlr_xdg_surface *parent = wlr_xdg_surface_try_from_wlr_surface(xdg_popup->parent); + assert(parent != NULL); + struct wlr_scene_tree *parent_tree = parent->data; + xdg_popup->base->data = wlr_scene_xdg_surface_create(parent_tree, xdg_popup->base); + + popup->commit.notify = xdg_popup_commit; + wl_signal_add(&xdg_popup->base->surface->events.commit, &popup->commit); + + popup->destroy.notify = xdg_popup_destroy; + wl_signal_add(&xdg_popup->events.destroy, &popup->destroy); +} + +int main(int argc, char *argv[]) { + wlr_log_init(WLR_DEBUG, NULL); + char *startup_cmd = NULL; + + int c; + while ((c = getopt(argc, argv, "s:h")) != -1) { + switch (c) { + case 's': + startup_cmd = optarg; + break; + default: + printf("Usage: %s [-s startup command]\n", argv[0]); + return 0; + } + } + if (optind < argc) { + printf("Usage: %s [-s startup command]\n", argv[0]); + return 0; + } + + struct tinywl_server server = {0}; + /* The Wayland display is managed by libwayland. It handles accepting + * clients from the Unix socket, managing Wayland globals, and so on. */ + server.wl_display = wl_display_create(); + /* The backend is a wlroots feature which abstracts the underlying input and + * output hardware. The autocreate option will choose the most suitable + * backend based on the current environment, such as opening an X11 window + * if an X11 server is running. */ + server.backend = wlr_backend_autocreate(wl_display_get_event_loop(server.wl_display), NULL); + if (server.backend == NULL) { + wlr_log(WLR_ERROR, "failed to create wlr_backend"); + return 1; + } + + /* Autocreates a renderer, either Pixman, GLES2 or Vulkan for us. The user + * can also specify a renderer using the WLR_RENDERER env var. + * The renderer is responsible for defining the various pixel formats it + * supports for shared memory, this configures that for clients. */ + server.renderer = wlr_renderer_autocreate(server.backend); + if (server.renderer == NULL) { + wlr_log(WLR_ERROR, "failed to create wlr_renderer"); + return 1; + } + + wlr_renderer_init_wl_display(server.renderer, server.wl_display); + + /* Autocreates an allocator for us. + * The allocator is the bridge between the renderer and the backend. It + * handles the buffer creation, allowing wlroots to render onto the + * screen */ + server.allocator = wlr_allocator_autocreate(server.backend, + server.renderer); + if (server.allocator == NULL) { + wlr_log(WLR_ERROR, "failed to create wlr_allocator"); + return 1; + } + + /* This creates some hands-off wlroots interfaces. The compositor is + * necessary for clients to allocate surfaces, the subcompositor allows to + * assign the role of subsurfaces to surfaces and the data device manager + * handles the clipboard. Each of these wlroots interfaces has room for you + * to dig your fingers in and play with their behavior if you want. Note that + * the clients cannot set the selection directly without compositor approval, + * see the handling of the request_set_selection event below.*/ + wlr_compositor_create(server.wl_display, 5, server.renderer); + wlr_subcompositor_create(server.wl_display); + wlr_data_device_manager_create(server.wl_display); + + /* Creates an output layout, which a wlroots utility for working with an + * arrangement of screens in a physical layout. */ + server.output_layout = wlr_output_layout_create(server.wl_display); + + /* Configure a listener to be notified when new outputs are available on the + * backend. */ + wl_list_init(&server.outputs); + server.new_output.notify = server_new_output; + wl_signal_add(&server.backend->events.new_output, &server.new_output); + + /* Create a scene graph. This is a wlroots abstraction that handles all + * rendering and damage tracking. All the compositor author needs to do + * is add things that should be rendered to the scene graph at the proper + * positions and then call wlr_scene_output_commit() to render a frame if + * necessary. + */ + server.scene = wlr_scene_create(); + server.scene_layout = wlr_scene_attach_output_layout(server.scene, server.output_layout); + + /* Set up xdg-shell version 3. The xdg-shell is a Wayland protocol which is + * used for application windows. For more detail on shells, refer to + * https://drewdevault.com/2018/07/29/Wayland-shells.html. + */ + wl_list_init(&server.toplevels); + server.xdg_shell = wlr_xdg_shell_create(server.wl_display, 3); + server.new_xdg_toplevel.notify = server_new_xdg_toplevel; + wl_signal_add(&server.xdg_shell->events.new_toplevel, &server.new_xdg_toplevel); + server.new_xdg_popup.notify = server_new_xdg_popup; + wl_signal_add(&server.xdg_shell->events.new_popup, &server.new_xdg_popup); + + /* + * Creates a cursor, which is a wlroots utility for tracking the cursor + * image shown on screen. + */ + server.cursor = wlr_cursor_create(); + wlr_cursor_attach_output_layout(server.cursor, server.output_layout); + + /* Creates an xcursor manager, another wlroots utility which loads up + * Xcursor themes to source cursor images from and makes sure that cursor + * images are available at all scale factors on the screen (necessary for + * HiDPI support). */ + server.cursor_mgr = wlr_xcursor_manager_create(NULL, 24); + + /* + * wlr_cursor *only* displays an image on screen. It does not move around + * when the pointer moves. However, we can attach input devices to it, and + * it will generate aggregate events for all of them. In these events, we + * can choose how we want to process them, forwarding them to clients and + * moving the cursor around. More detail on this process is described in + * https://drewdevault.com/2018/07/17/Input-handling-in-wlroots.html. + * + * And more comments are sprinkled throughout the notify functions above. + */ + server.cursor_mode = TINYWL_CURSOR_PASSTHROUGH; + server.cursor_motion.notify = server_cursor_motion; + wl_signal_add(&server.cursor->events.motion, &server.cursor_motion); + server.cursor_motion_absolute.notify = server_cursor_motion_absolute; + wl_signal_add(&server.cursor->events.motion_absolute, + &server.cursor_motion_absolute); + server.cursor_button.notify = server_cursor_button; + wl_signal_add(&server.cursor->events.button, &server.cursor_button); + server.cursor_axis.notify = server_cursor_axis; + wl_signal_add(&server.cursor->events.axis, &server.cursor_axis); + server.cursor_frame.notify = server_cursor_frame; + wl_signal_add(&server.cursor->events.frame, &server.cursor_frame); + + /* + * Configures a seat, which is a single "seat" at which a user sits and + * operates the computer. This conceptually includes up to one keyboard, + * pointer, touch, and drawing tablet device. We also rig up a listener to + * let us know when new input devices are available on the backend. + */ + wl_list_init(&server.keyboards); + server.new_input.notify = server_new_input; + wl_signal_add(&server.backend->events.new_input, &server.new_input); + server.seat = wlr_seat_create(server.wl_display, "seat0"); + server.request_cursor.notify = seat_request_cursor; + wl_signal_add(&server.seat->events.request_set_cursor, + &server.request_cursor); + server.pointer_focus_change.notify = seat_pointer_focus_change; + wl_signal_add(&server.seat->pointer_state.events.focus_change, + &server.pointer_focus_change); + server.request_set_selection.notify = seat_request_set_selection; + wl_signal_add(&server.seat->events.request_set_selection, + &server.request_set_selection); + + /* Add a Unix socket to the Wayland display. */ + const char *socket = wl_display_add_socket_auto(server.wl_display); + if (!socket) { + wlr_backend_destroy(server.backend); + return 1; + } + + /* Start the backend. This will enumerate outputs and inputs, become the DRM + * master, etc */ + if (!wlr_backend_start(server.backend)) { + wlr_backend_destroy(server.backend); + wl_display_destroy(server.wl_display); + return 1; + } + + /* Set the WAYLAND_DISPLAY environment variable to our socket and run the + * startup command if requested. */ + setenv("WAYLAND_DISPLAY", socket, true); + if (startup_cmd) { + if (fork() == 0) { + execl("/bin/sh", "/bin/sh", "-c", startup_cmd, (void *)NULL); + } + } + /* Run the Wayland event loop. This does not return until you exit the + * compositor. Starting the backend rigged up all of the necessary event + * loop configuration to listen to libinput events, DRM events, generate + * frame events at the refresh rate, and so on. */ + wlr_log(WLR_INFO, "Running Wayland compositor on WAYLAND_DISPLAY=%s", + socket); + wl_display_run(server.wl_display); + + + /* Once wl_display_run returns, we destroy all clients then shut down the + * server. */ + wl_display_destroy_clients(server.wl_display); + + wl_list_remove(&server.new_xdg_toplevel.link); + wl_list_remove(&server.new_xdg_popup.link); + + wl_list_remove(&server.cursor_motion.link); + wl_list_remove(&server.cursor_motion_absolute.link); + wl_list_remove(&server.cursor_button.link); + wl_list_remove(&server.cursor_axis.link); + wl_list_remove(&server.cursor_frame.link); + + wl_list_remove(&server.new_input.link); + wl_list_remove(&server.request_cursor.link); + wl_list_remove(&server.pointer_focus_change.link); + wl_list_remove(&server.request_set_selection.link); + + wl_list_remove(&server.new_output.link); + + wlr_scene_node_destroy(&server.scene->tree.node); + wlr_xcursor_manager_destroy(server.cursor_mgr); + wlr_cursor_destroy(server.cursor); + wlr_allocator_destroy(server.allocator); + wlr_renderer_destroy(server.renderer); + wlr_backend_destroy(server.backend); + wl_display_destroy(server.wl_display); + return 0; +} diff --git a/3rdparty/wlroots/types/buffer/buffer.c b/3rdparty/wlroots/types/buffer/buffer.c new file mode 100644 index 0000000000..c10405eb13 --- /dev/null +++ b/3rdparty/wlroots/types/buffer/buffer.c @@ -0,0 +1,156 @@ +#include +#include +#include +#include +#include +#include "render/pixel_format.h" +#include "types/wlr_buffer.h" + +static _Atomic size_t buffer_count; + +void wlr_buffer_init(struct wlr_buffer *buffer, + const struct wlr_buffer_impl *impl, int width, int height) { + assert(impl->destroy); + if (impl->begin_data_ptr_access || impl->end_data_ptr_access) { + assert(impl->begin_data_ptr_access && impl->end_data_ptr_access); + } + + *buffer = (struct wlr_buffer){ + .impl = impl, + .width = width, + .height = height, + }; + + wl_signal_init(&buffer->events.destroy); + wl_signal_init(&buffer->events.release); + + wlr_addon_set_init(&buffer->addons); + atomic_fetch_add_explicit(&buffer_count, 1, memory_order_relaxed); +} + +void wlr_buffer_finish(struct wlr_buffer *buffer) { + wl_signal_emit_mutable(&buffer->events.destroy, NULL); + wlr_addon_set_finish(&buffer->addons); + + assert(wl_list_empty(&buffer->events.destroy.listener_list)); + assert(wl_list_empty(&buffer->events.release.listener_list)); + size_t previous = atomic_fetch_sub_explicit(&buffer_count, 1, memory_order_relaxed); + assert(previous > 0); +} + +size_t waylib_buffer_get_count(void) { + return atomic_load_explicit(&buffer_count, memory_order_relaxed); +} + +static void buffer_consider_destroy(struct wlr_buffer *buffer) { + if (!buffer->dropped || buffer->n_locks > 0) { + return; + } + + assert(!buffer->accessing_data_ptr); + + buffer->impl->destroy(buffer); +} + +void wlr_buffer_drop(struct wlr_buffer *buffer) { + if (buffer == NULL) { + return; + } + + assert(!buffer->dropped); + buffer->dropped = true; + buffer_consider_destroy(buffer); +} + +struct wlr_buffer *wlr_buffer_lock(struct wlr_buffer *buffer) { + buffer->n_locks++; + return buffer; +} + +void wlr_buffer_unlock(struct wlr_buffer *buffer) { + if (buffer == NULL) { + return; + } + + assert(buffer->n_locks > 0); + buffer->n_locks--; + + if (buffer->n_locks == 0) { + wl_signal_emit_mutable(&buffer->events.release, NULL); + } + + buffer_consider_destroy(buffer); +} + +bool wlr_buffer_get_dmabuf(struct wlr_buffer *buffer, + struct wlr_dmabuf_attributes *attribs) { + if (!buffer->impl->get_dmabuf) { + return false; + } + return buffer->impl->get_dmabuf(buffer, attribs); +} + +bool wlr_buffer_begin_data_ptr_access(struct wlr_buffer *buffer, uint32_t flags, + void **data, uint32_t *format, size_t *stride) { + assert(!buffer->accessing_data_ptr); + if (!buffer->impl->begin_data_ptr_access) { + return false; + } + if (!buffer->impl->begin_data_ptr_access(buffer, flags, data, format, stride)) { + return false; + } + buffer->accessing_data_ptr = true; + return true; +} + +void wlr_buffer_end_data_ptr_access(struct wlr_buffer *buffer) { + assert(buffer->accessing_data_ptr); + buffer->impl->end_data_ptr_access(buffer); + buffer->accessing_data_ptr = false; +} + +bool wlr_buffer_get_shm(struct wlr_buffer *buffer, + struct wlr_shm_attributes *attribs) { + if (!buffer->impl->get_shm) { + return false; + } + return buffer->impl->get_shm(buffer, attribs); +} + +bool wlr_buffer_is_opaque(struct wlr_buffer *buffer) { + void *data; + uint32_t format = buffer_get_drm_format(buffer); + size_t stride; + + if (format != DRM_FORMAT_INVALID) { + // pass + } else if (wlr_buffer_begin_data_ptr_access(buffer, + WLR_BUFFER_DATA_PTR_ACCESS_READ, &data, &format, &stride)) { + bool opaque = false; + if (buffer->width == 1 && buffer->height == 1 && format == DRM_FORMAT_ARGB8888) { + // Special case for single-pixel-buffer-v1 + const uint8_t *argb8888 = data; // little-endian byte order + opaque = argb8888[3] == 0xFF; + } + wlr_buffer_end_data_ptr_access(buffer); + if (opaque) { + return true; + } + } else { + return false; + } + + return !pixel_format_has_alpha(format); +} + +uint32_t buffer_get_drm_format(struct wlr_buffer *buffer) { + uint32_t format = DRM_FORMAT_INVALID; + struct wlr_dmabuf_attributes dmabuf; + struct wlr_shm_attributes shm; + if (wlr_buffer_get_dmabuf(buffer, &dmabuf)) { + format = dmabuf.format; + } else if (wlr_buffer_get_shm(buffer, &shm)) { + format = shm.format; + } + return format; +} diff --git a/3rdparty/wlroots/types/buffer/client.c b/3rdparty/wlroots/types/buffer/client.c new file mode 100644 index 0000000000..5bc670334a --- /dev/null +++ b/3rdparty/wlroots/types/buffer/client.c @@ -0,0 +1,147 @@ +#include +#include +#include +#include +#include +#include "types/wlr_buffer.h" + +static const struct wlr_buffer_impl client_buffer_impl; + +struct wlr_client_buffer *wlr_client_buffer_get(struct wlr_buffer *wlr_buffer) { + if (wlr_buffer->impl != &client_buffer_impl) { + return NULL; + } + struct wlr_client_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + return buffer; +} + +static struct wlr_client_buffer *client_buffer_from_buffer( + struct wlr_buffer *buffer) { + struct wlr_client_buffer *client_buffer = wlr_client_buffer_get(buffer); + assert(client_buffer != NULL); + return client_buffer; +} + +static void client_buffer_destroy(struct wlr_buffer *buffer) { + struct wlr_client_buffer *client_buffer = client_buffer_from_buffer(buffer); + + wlr_buffer_finish(buffer); + + wl_list_remove(&client_buffer->source_destroy.link); + wl_list_remove(&client_buffer->renderer_destroy.link); + wlr_texture_destroy(client_buffer->texture); + free(client_buffer); +} + +static bool client_buffer_get_dmabuf(struct wlr_buffer *buffer, + struct wlr_dmabuf_attributes *attribs) { + struct wlr_client_buffer *client_buffer = client_buffer_from_buffer(buffer); + + if (client_buffer->source == NULL) { + return false; + } + + return wlr_buffer_get_dmabuf(client_buffer->source, attribs); +} + +static bool client_buffer_get_shm(struct wlr_buffer *buffer, + struct wlr_shm_attributes *attribs) { + struct wlr_client_buffer *client_buffer = client_buffer_from_buffer(buffer); + + if (client_buffer->source == NULL) { + return false; + } + + return wlr_buffer_get_shm(client_buffer->source, attribs); +} + +static bool client_buffer_begin_data_ptr_access(struct wlr_buffer *buffer, uint32_t flags, + void **data, uint32_t *format, size_t *stride) { + struct wlr_client_buffer *client_buffer = client_buffer_from_buffer(buffer); + + if (client_buffer->source == NULL) { + return false; + } + + return wlr_buffer_begin_data_ptr_access(client_buffer->source, flags, data, format, stride); +} + +static void client_buffer_end_data_ptr_access(struct wlr_buffer *buffer) { + struct wlr_client_buffer *client_buffer = client_buffer_from_buffer(buffer); + + if (client_buffer->source == NULL) { + return; + } + + wlr_buffer_end_data_ptr_access(client_buffer->source); +} + +static const struct wlr_buffer_impl client_buffer_impl = { + .destroy = client_buffer_destroy, + .get_dmabuf = client_buffer_get_dmabuf, + .get_shm = client_buffer_get_shm, + .begin_data_ptr_access = client_buffer_begin_data_ptr_access, + .end_data_ptr_access = client_buffer_end_data_ptr_access, +}; + +static void client_buffer_handle_source_destroy(struct wl_listener *listener, + void *data) { + struct wlr_client_buffer *client_buffer = + wl_container_of(listener, client_buffer, source_destroy); + wl_list_remove(&client_buffer->source_destroy.link); + wl_list_init(&client_buffer->source_destroy.link); + client_buffer->source = NULL; +} + +static void client_buffer_handle_renderer_destroy(struct wl_listener *listener, + void *data) { + struct wlr_client_buffer *client_buffer = + wl_container_of(listener, client_buffer, renderer_destroy); + wl_list_remove(&client_buffer->renderer_destroy.link); + wl_list_init(&client_buffer->renderer_destroy.link); + client_buffer->texture = NULL; +} + +struct wlr_client_buffer *wlr_client_buffer_create(struct wlr_buffer *buffer, + struct wlr_renderer *renderer) { + struct wlr_texture *texture = wlr_texture_from_buffer(renderer, buffer); + if (texture == NULL) { + wlr_log(WLR_ERROR, "Failed to create texture"); + return NULL; + } + + struct wlr_client_buffer *client_buffer = calloc(1, sizeof(*client_buffer)); + if (client_buffer == NULL) { + wlr_texture_destroy(texture); + return NULL; + } + wlr_buffer_init(&client_buffer->base, &client_buffer_impl, + texture->width, texture->height); + client_buffer->source = buffer; + client_buffer->texture = texture; + + wl_signal_add(&buffer->events.destroy, &client_buffer->source_destroy); + client_buffer->source_destroy.notify = client_buffer_handle_source_destroy; + + wl_signal_add(&texture->renderer->events.destroy, &client_buffer->renderer_destroy); + client_buffer->renderer_destroy.notify = client_buffer_handle_renderer_destroy; + + // Ensure the buffer will be released before being destroyed + wlr_buffer_lock(&client_buffer->base); + wlr_buffer_drop(&client_buffer->base); + + return client_buffer; +} + +bool wlr_client_buffer_apply_damage(struct wlr_client_buffer *client_buffer, + struct wlr_buffer *next, const pixman_region32_t *damage) { + if (client_buffer->base.n_locks - client_buffer->n_ignore_locks > 1) { + // Someone else still has a reference to the buffer + return false; + } + if (client_buffer->texture == NULL) { + return false; + } + + return wlr_texture_update_from_buffer(client_buffer->texture, next, damage); +} diff --git a/3rdparty/wlroots/types/buffer/dmabuf.c b/3rdparty/wlroots/types/buffer/dmabuf.c new file mode 100644 index 0000000000..078821e43c --- /dev/null +++ b/3rdparty/wlroots/types/buffer/dmabuf.c @@ -0,0 +1,71 @@ +#include +#include +#include +#include +#include "types/wlr_buffer.h" + +static const struct wlr_buffer_impl dmabuf_buffer_impl; + +static struct wlr_dmabuf_buffer *dmabuf_buffer_from_buffer( + struct wlr_buffer *wlr_buffer) { + assert(wlr_buffer->impl == &dmabuf_buffer_impl); + struct wlr_dmabuf_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + return buffer; +} + +static void dmabuf_buffer_destroy(struct wlr_buffer *wlr_buffer) { + struct wlr_dmabuf_buffer *buffer = dmabuf_buffer_from_buffer(wlr_buffer); + wlr_buffer_finish(wlr_buffer); + if (buffer->saved) { + wlr_dmabuf_attributes_finish(&buffer->dmabuf); + } + free(buffer); +} + +static bool dmabuf_buffer_get_dmabuf(struct wlr_buffer *wlr_buffer, + struct wlr_dmabuf_attributes *dmabuf) { + struct wlr_dmabuf_buffer *buffer = dmabuf_buffer_from_buffer(wlr_buffer); + if (buffer->dmabuf.n_planes == 0) { + return false; + } + *dmabuf = buffer->dmabuf; + return true; +} + +static const struct wlr_buffer_impl dmabuf_buffer_impl = { + .destroy = dmabuf_buffer_destroy, + .get_dmabuf = dmabuf_buffer_get_dmabuf, +}; + +struct wlr_dmabuf_buffer *dmabuf_buffer_create( + struct wlr_dmabuf_attributes *dmabuf) { + struct wlr_dmabuf_buffer *buffer = calloc(1, sizeof(*buffer)); + if (buffer == NULL) { + return NULL; + } + wlr_buffer_init(&buffer->base, &dmabuf_buffer_impl, + dmabuf->width, dmabuf->height); + + buffer->dmabuf = *dmabuf; + + return buffer; +} + +bool dmabuf_buffer_drop(struct wlr_dmabuf_buffer *buffer) { + bool ok = true; + + if (buffer->base.n_locks > 0) { + struct wlr_dmabuf_attributes saved_dmabuf = {0}; + if (!wlr_dmabuf_attributes_copy(&saved_dmabuf, &buffer->dmabuf)) { + wlr_log(WLR_ERROR, "Failed to save DMA-BUF"); + ok = false; + buffer->dmabuf = (struct wlr_dmabuf_attributes){0}; + } else { + buffer->dmabuf = saved_dmabuf; + buffer->saved = true; + } + } + + wlr_buffer_drop(&buffer->base); + return ok; +} diff --git a/3rdparty/wlroots/types/buffer/readonly_data.c b/3rdparty/wlroots/types/buffer/readonly_data.c new file mode 100644 index 0000000000..1c8fcf126f --- /dev/null +++ b/3rdparty/wlroots/types/buffer/readonly_data.c @@ -0,0 +1,89 @@ +#include +#include +#include +#include +#include +#include "types/wlr_buffer.h" + +static const struct wlr_buffer_impl readonly_data_buffer_impl; + +static struct wlr_readonly_data_buffer *readonly_data_buffer_from_buffer( + struct wlr_buffer *wlr_buffer) { + assert(wlr_buffer->impl == &readonly_data_buffer_impl); + struct wlr_readonly_data_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + return buffer; +} + +static void readonly_data_buffer_destroy(struct wlr_buffer *wlr_buffer) { + struct wlr_readonly_data_buffer *buffer = + readonly_data_buffer_from_buffer(wlr_buffer); + wlr_buffer_finish(wlr_buffer); + free(buffer->saved_data); + free(buffer); +} + +static bool readonly_data_buffer_begin_data_ptr_access(struct wlr_buffer *wlr_buffer, + uint32_t flags, void **data, uint32_t *format, size_t *stride) { + struct wlr_readonly_data_buffer *buffer = + readonly_data_buffer_from_buffer(wlr_buffer); + if (buffer->data == NULL) { + return false; + } + if (flags & WLR_BUFFER_DATA_PTR_ACCESS_WRITE) { + return false; + } + *data = (void *)buffer->data; + *format = buffer->format; + *stride = buffer->stride; + return true; +} + +static void readonly_data_buffer_end_data_ptr_access(struct wlr_buffer *wlr_buffer) { + // This space is intentionally left blank +} + +static const struct wlr_buffer_impl readonly_data_buffer_impl = { + .destroy = readonly_data_buffer_destroy, + .begin_data_ptr_access = readonly_data_buffer_begin_data_ptr_access, + .end_data_ptr_access = readonly_data_buffer_end_data_ptr_access, +}; + +struct wlr_readonly_data_buffer *readonly_data_buffer_create(uint32_t format, + size_t stride, uint32_t width, uint32_t height, const void *data) { + struct wlr_readonly_data_buffer *buffer = calloc(1, sizeof(*buffer)); + if (buffer == NULL) { + return NULL; + } + wlr_buffer_init(&buffer->base, &readonly_data_buffer_impl, width, height); + + buffer->data = data; + buffer->format = format; + buffer->stride = stride; + + return buffer; +} + +bool readonly_data_buffer_drop(struct wlr_readonly_data_buffer *buffer) { + bool ok = true; + + if (buffer->base.n_locks > 0) { + size_t size = buffer->stride * buffer->base.height; + buffer->saved_data = malloc(size); + if (buffer->saved_data == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + ok = false; + buffer->data = NULL; + // We can't destroy the buffer, or we risk use-after-free in the + // consumers. We can't allow accesses to buffer->data anymore, so + // set it to NULL and make subsequent begin_data_ptr_access() + // calls fail. + } else { + memcpy(buffer->saved_data, buffer->data, size); + buffer->data = buffer->saved_data; + } + } + + wlr_buffer_drop(&buffer->base); + return ok; +} + diff --git a/3rdparty/wlroots/types/buffer/resource.c b/3rdparty/wlroots/types/buffer/resource.c new file mode 100644 index 0000000000..14d8f82d10 --- /dev/null +++ b/3rdparty/wlroots/types/buffer/resource.c @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include +#include "types/wlr_buffer.h" + +/* struct wlr_buffer_resource_interface */ +static struct wl_array buffer_resource_interfaces = {0}; + +void wlr_buffer_register_resource_interface( + const struct wlr_buffer_resource_interface *iface) { + assert(iface); + assert(iface->is_instance); + assert(iface->from_resource); + + const struct wlr_buffer_resource_interface **iface_ptr; + wl_array_for_each(iface_ptr, &buffer_resource_interfaces) { + if (*iface_ptr == iface) { + wlr_log(WLR_DEBUG, "wlr_resource_buffer_interface %s has already" + "been registered", iface->name); + return; + } + } + + iface_ptr = wl_array_add(&buffer_resource_interfaces, sizeof(iface)); + *iface_ptr = iface; +} + +static const struct wlr_buffer_resource_interface *get_buffer_resource_iface( + struct wl_resource *resource) { + struct wlr_buffer_resource_interface **iface_ptr; + wl_array_for_each(iface_ptr, &buffer_resource_interfaces) { + if ((*iface_ptr)->is_instance(resource)) { + return *iface_ptr; + } + } + + return NULL; +} + +struct wlr_buffer *wlr_buffer_try_from_resource(struct wl_resource *resource) { + if (strcmp(wl_resource_get_class(resource), wl_buffer_interface.name) != 0) { + return NULL; + } + + const struct wlr_buffer_resource_interface *iface = + get_buffer_resource_iface(resource); + if (!iface) { + wlr_log(WLR_ERROR, "Unknown buffer type"); + return NULL; + } + + struct wlr_buffer *buffer = iface->from_resource(resource); + if (!buffer) { + wlr_log(WLR_ERROR, "Failed to create %s buffer", iface->name); + return NULL; + } + + return wlr_buffer_lock(buffer); +} diff --git a/3rdparty/wlroots/types/data_device/wlr_data_device.c b/3rdparty/wlroots/types/data_device/wlr_data_device.c new file mode 100644 index 0000000000..54f9925c35 --- /dev/null +++ b/3rdparty/wlroots/types/data_device/wlr_data_device.c @@ -0,0 +1,343 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_data_device.h" +#include "util/global.h" + +#define DATA_DEVICE_MANAGER_VERSION 3 + +static const struct wl_data_device_interface data_device_impl; + +struct wlr_seat_client *seat_client_from_data_device_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_data_device_interface, + &data_device_impl)); + return wl_resource_get_user_data(resource); +} + +static void data_device_set_selection(struct wl_client *client, + struct wl_resource *device_resource, + struct wl_resource *source_resource, uint32_t serial) { + struct wlr_seat_client *seat_client = + seat_client_from_data_device_resource(device_resource); + if (seat_client == NULL) { + return; + } + + struct wlr_client_data_source *source = NULL; + if (source_resource != NULL) { + source = client_data_source_from_resource(source_resource); + } + + if (source != NULL) { + source->finalized = true; + } + + struct wlr_data_source *wlr_source = + source != NULL ? &source->source : NULL; + wlr_seat_request_set_selection(seat_client->seat, seat_client, wlr_source, serial); +} + +static void data_device_start_drag(struct wl_client *client, + struct wl_resource *device_resource, + struct wl_resource *source_resource, + struct wl_resource *origin_resource, struct wl_resource *icon_resource, + uint32_t serial) { + struct wlr_seat_client *seat_client = + seat_client_from_data_device_resource(device_resource); + if (seat_client == NULL) { + return; + } + + struct wlr_surface *origin = wlr_surface_from_resource(origin_resource); + + struct wlr_client_data_source *source = NULL; + if (source_resource != NULL) { + source = client_data_source_from_resource(source_resource); + } + + struct wlr_surface *icon = NULL; + if (icon_resource) { + icon = wlr_surface_from_resource(icon_resource); + if (!wlr_surface_set_role(icon, &drag_icon_surface_role, + icon_resource, WL_DATA_DEVICE_ERROR_ROLE)) { + return; + } + } + + struct wlr_data_source *wlr_source = + source != NULL ? &source->source : NULL; + struct wlr_drag *drag = wlr_drag_create(seat_client, wlr_source, icon); + if (drag == NULL) { + wl_resource_post_no_memory(device_resource); + return; + } + + if (source != NULL) { + source->finalized = true; + } + + wlr_seat_request_start_drag(seat_client->seat, drag, origin, serial); +} + +static void data_device_release(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wl_data_device_interface data_device_impl = { + .start_drag = data_device_start_drag, + .set_selection = data_device_set_selection, + .release = data_device_release, +}; + +static void data_device_handle_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); +} + +static void device_resource_send_selection(struct wl_resource *device_resource) { + struct wlr_seat_client *seat_client = + seat_client_from_data_device_resource(device_resource); + assert(seat_client != NULL); + + struct wlr_data_source *source = seat_client->seat->selection_source; + if (source != NULL) { + struct wlr_data_offer *offer = data_offer_create(device_resource, + source, WLR_DATA_OFFER_SELECTION); + if (offer == NULL) { + wl_client_post_no_memory(seat_client->client); + return; + } + + wl_data_device_send_selection(device_resource, offer->resource); + } else { + wl_data_device_send_selection(device_resource, NULL); + } +} + +void seat_client_send_selection(struct wlr_seat_client *seat_client) { + struct wlr_data_source *source = seat_client->seat->selection_source; + if (source != NULL) { + source->accepted = false; + } + + // Keep this client's offers until it receives the new selection event and + // destroys them. Closing a popup can restore focus to another surface of + // the same client before its queued receive request is dispatched. + // Offers belonging to other clients must still become inert on focus loss. + struct wlr_data_offer *offer, *tmp; + wl_list_for_each_safe(offer, tmp, + &seat_client->seat->selection_offers, link) { + if (offer->source == source && + wl_resource_get_client(offer->resource) == seat_client->client) { + continue; + } + + data_offer_destroy(offer); + } + + struct wl_resource *device_resource; + wl_resource_for_each(device_resource, &seat_client->data_devices) { + device_resource_send_selection(device_resource); + } +} + +void wlr_seat_request_set_selection(struct wlr_seat *seat, + struct wlr_seat_client *client, + struct wlr_data_source *source, uint32_t serial) { + if (client && !wlr_seat_client_validate_event_serial(client, serial)) { + wlr_log(WLR_DEBUG, "Rejecting set_selection request, " + "serial %"PRIu32" was never given to client", serial); + return; + } + + if (seat->selection_source && + serial - seat->selection_serial > UINT32_MAX / 2) { + wlr_log(WLR_DEBUG, "Rejecting set_selection request, serial indicates superseded " + "(%"PRIu32" < %"PRIu32")", serial, seat->selection_serial); + return; + } + + struct wlr_seat_request_set_selection_event event = { + .source = source, + .serial = serial, + }; + wl_signal_emit_mutable(&seat->events.request_set_selection, &event); +} + +static void seat_handle_selection_source_destroy( + struct wl_listener *listener, void *data) { + struct wlr_seat *seat = + wl_container_of(listener, seat, selection_source_destroy); + + wl_list_remove(&seat->selection_source_destroy.link); + seat->selection_source = NULL; + + struct wlr_seat_client *focused_client = + seat->keyboard_state.focused_client; + if (focused_client != NULL) { + seat_client_send_selection(focused_client); + } + + wl_signal_emit_mutable(&seat->events.set_selection, seat); +} + +void wlr_seat_set_selection(struct wlr_seat *seat, + struct wlr_data_source *source, uint32_t serial) { + if (seat->selection_source == source) { + seat->selection_serial = serial; + return; + } + + if (seat->selection_source) { + wl_list_remove(&seat->selection_source_destroy.link); + wlr_data_source_destroy(seat->selection_source); + seat->selection_source = NULL; + } + + seat->selection_source = source; + seat->selection_serial = serial; + + if (source) { + seat->selection_source_destroy.notify = + seat_handle_selection_source_destroy; + wl_signal_add(&source->events.destroy, + &seat->selection_source_destroy); + } + + struct wlr_seat_client *focused_client = + seat->keyboard_state.focused_client; + if (focused_client) { + seat_client_send_selection(focused_client); + } + + wl_signal_emit_mutable(&seat->events.set_selection, seat); +} + + +static const struct wl_data_device_manager_interface data_device_manager_impl; + +static struct wlr_data_device_manager *data_device_manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_data_device_manager_interface, + &data_device_manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void data_device_manager_get_data_device(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + struct wl_resource *seat_resource) { + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat_resource); + + uint32_t version = wl_resource_get_version(manager_resource); + struct wl_resource *resource = wl_resource_create(client, + &wl_data_device_interface, version, id); + if (resource == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + wl_resource_set_implementation(resource, &data_device_impl, seat_client, + data_device_handle_resource_destroy); + if (seat_client == NULL) { + wl_list_init(wl_resource_get_link(resource)); + return; + } + wl_list_insert(&seat_client->data_devices, wl_resource_get_link(resource)); + + struct wlr_seat_client *focused_client = + seat_client->seat->keyboard_state.focused_client; + if (focused_client == seat_client) { + device_resource_send_selection(resource); + } +} + +static void data_device_manager_create_data_source(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id) { + struct wlr_data_device_manager *manager = + data_device_manager_from_resource(manager_resource); + + client_data_source_create(client, wl_resource_get_version(manager_resource), + id, &manager->data_sources); +} + +static const struct wl_data_device_manager_interface + data_device_manager_impl = { + .create_data_source = data_device_manager_create_data_source, + .get_data_device = data_device_manager_get_data_device, +}; + +static void data_device_manager_bind(struct wl_client *client, + void *data, uint32_t version, uint32_t id) { + struct wlr_data_device_manager *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &wl_data_device_manager_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &data_device_manager_impl, + manager, NULL); +} + +static void data_device_manager_destroy(struct wlr_data_device_manager *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_data_device_manager_destroy(struct wlr_data_device_manager *manager, + bool destroy_global_safe) { + data_device_manager_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_data_device_manager *manager = + wl_container_of(listener, manager, display_destroy); + data_device_manager_destroy(manager, false); +} + +struct wlr_data_device_manager *wlr_data_device_manager_create( + struct wl_display *display) { + struct wlr_data_device_manager *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + wlr_log(WLR_ERROR, "could not create data device manager"); + return NULL; + } + + wl_list_init(&manager->data_sources); + wl_signal_init(&manager->events.destroy); + + manager->global = + wl_global_create(display, &wl_data_device_manager_interface, + DATA_DEVICE_MANAGER_VERSION, manager, data_device_manager_bind); + if (!manager->global) { + wlr_log(WLR_ERROR, "could not create data device manager wl_global"); + free(manager); + return NULL; + } + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/data_device/wlr_data_offer.c b/3rdparty/wlroots/types/data_device/wlr_data_offer.c new file mode 100644 index 0000000000..4bb9d0c24f --- /dev/null +++ b/3rdparty/wlroots/types/data_device/wlr_data_offer.c @@ -0,0 +1,284 @@ +#undef _POSIX_C_SOURCE +#define _XOPEN_SOURCE 700 // for ffs() +#include +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_data_device.h" + +static const struct wl_data_offer_interface data_offer_impl; + +static struct wlr_data_offer *data_offer_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_data_offer_interface, + &data_offer_impl)); + return wl_resource_get_user_data(resource); +} + +static uint32_t data_offer_choose_action(struct wlr_data_offer *offer) { + uint32_t offer_actions, preferred_action = 0; + if (wl_resource_get_version(offer->resource) >= + WL_DATA_OFFER_ACTION_SINCE_VERSION) { + offer_actions = offer->actions; + preferred_action = offer->preferred_action; + } else { + offer_actions = WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY; + } + + uint32_t source_actions; + if (offer->source->actions >= 0) { + source_actions = offer->source->actions; + } else { + source_actions = WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY; + } + + uint32_t available_actions = offer_actions & source_actions; + if (!available_actions) { + return WL_DATA_DEVICE_MANAGER_DND_ACTION_NONE; + } + + if (offer->source->compositor_action & available_actions) { + return offer->source->compositor_action; + } + + // If the dest side has a preferred DnD action, use it + if ((preferred_action & available_actions) != 0) { + return preferred_action; + } + + // Use the first found action, in bit order + return 1 << (ffs(available_actions) - 1); +} + +void data_offer_update_action(struct wlr_data_offer *offer) { + assert(offer->type == WLR_DATA_OFFER_DRAG); + + uint32_t action = data_offer_choose_action(offer); + if (offer->source->current_dnd_action == action) { + return; + } + offer->source->current_dnd_action = action; + + if (offer->in_ask) { + return; + } + + wlr_data_source_dnd_action(offer->source, action); + + if (wl_resource_get_version(offer->resource) >= + WL_DATA_OFFER_ACTION_SINCE_VERSION) { + wl_data_offer_send_action(offer->resource, action); + } +} + +static void data_offer_handle_accept(struct wl_client *client, + struct wl_resource *resource, uint32_t serial, const char *mime_type) { + struct wlr_data_offer *offer = data_offer_from_resource(resource); + if (offer == NULL) { + return; + } + + if (offer->type != WLR_DATA_OFFER_DRAG) { + wlr_log(WLR_DEBUG, "Ignoring wl_data_offer.accept request on a " + "non-drag-and-drop offer"); + return; + } + + wlr_data_source_accept(offer->source, serial, mime_type); +} + +static void data_offer_handle_receive(struct wl_client *client, + struct wl_resource *resource, const char *mime_type, int32_t fd) { + struct wlr_data_offer *offer = data_offer_from_resource(resource); + if (offer == NULL) { + close(fd); + return; + } + + wlr_data_source_send(offer->source, mime_type, fd); +} + +static void data_offer_source_dnd_finish(struct wlr_data_offer *offer) { + struct wlr_data_source *source = offer->source; + if (source->actions < 0) { + return; + } + + if (offer->in_ask) { + wlr_data_source_dnd_action(source, source->current_dnd_action); + } + + wlr_data_source_dnd_finish(source); +} + +static void data_offer_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void data_offer_handle_finish(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_data_offer *offer = data_offer_from_resource(resource); + if (offer == NULL) { + return; + } + + // TODO: also fail while we have a drag-and-drop grab + if (offer->type != WLR_DATA_OFFER_DRAG) { + wl_resource_post_error(offer->resource, + WL_DATA_OFFER_ERROR_INVALID_FINISH, "Offer is not drag-and-drop"); + return; + } + if (!offer->source->accepted) { + wl_resource_post_error(offer->resource, + WL_DATA_OFFER_ERROR_INVALID_FINISH, "Premature finish request"); + return; + } + enum wl_data_device_manager_dnd_action action = + offer->source->current_dnd_action; + if (action == WL_DATA_DEVICE_MANAGER_DND_ACTION_NONE || + action == WL_DATA_DEVICE_MANAGER_DND_ACTION_ASK) { + wl_resource_post_error(offer->resource, + WL_DATA_OFFER_ERROR_INVALID_FINISH, + "Offer finished with an invalid action"); + return; + } + + data_offer_source_dnd_finish(offer); + data_offer_destroy(offer); +} + +static void data_offer_handle_set_actions(struct wl_client *client, + struct wl_resource *resource, uint32_t actions, + uint32_t preferred_action) { + struct wlr_data_offer *offer = data_offer_from_resource(resource); + if (offer == NULL) { + return; + } + + if (actions & ~DATA_DEVICE_ALL_ACTIONS) { + wl_resource_post_error(offer->resource, + WL_DATA_OFFER_ERROR_INVALID_ACTION_MASK, + "invalid action mask %x", actions); + return; + } + + if (preferred_action && (!(preferred_action & actions) || + __builtin_popcount(preferred_action) > 1)) { + wl_resource_post_error(offer->resource, + WL_DATA_OFFER_ERROR_INVALID_ACTION, + "invalid action %x", preferred_action); + return; + } + + if (offer->type != WLR_DATA_OFFER_DRAG) { + wl_resource_post_error(offer->resource, + WL_DATA_OFFER_ERROR_INVALID_OFFER, + "set_action can only be sent to drag-and-drop offers"); + return; + } + + offer->actions = actions; + offer->preferred_action = preferred_action; + + data_offer_update_action(offer); +} + +void data_offer_destroy(struct wlr_data_offer *offer) { + if (offer == NULL) { + return; + } + + wl_list_remove(&offer->source_destroy.link); + wl_list_remove(&offer->link); + + if (offer->type == WLR_DATA_OFFER_DRAG && offer->source) { + // If the drag destination has version < 3, wl_data_offer.finish + // won't be called, so do this here as a safety net, because + // we still want the version >= 3 drag source to be happy. + if (wl_resource_get_version(offer->resource) < + WL_DATA_OFFER_ACTION_SINCE_VERSION) { + data_offer_source_dnd_finish(offer); + } else if (offer->source->impl->dnd_finish) { + wlr_data_source_destroy(offer->source); + } + } + + // Make the resource inert + wl_resource_set_user_data(offer->resource, NULL); + + free(offer); +} + +static const struct wl_data_offer_interface data_offer_impl = { + .accept = data_offer_handle_accept, + .receive = data_offer_handle_receive, + .destroy = data_offer_handle_destroy, + .finish = data_offer_handle_finish, + .set_actions = data_offer_handle_set_actions, +}; + +static void data_offer_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_data_offer *offer = data_offer_from_resource(resource); + data_offer_destroy(offer); +} + +static void data_offer_handle_source_destroy(struct wl_listener *listener, + void *data) { + struct wlr_data_offer *offer = + wl_container_of(listener, offer, source_destroy); + // Prevent data_offer_destroy from destroying the source again + offer->source = NULL; + data_offer_destroy(offer); +} + +struct wlr_data_offer *data_offer_create(struct wl_resource *device_resource, + struct wlr_data_source *source, enum wlr_data_offer_type type) { + struct wlr_seat_client *seat_client = + seat_client_from_data_device_resource(device_resource); + assert(seat_client != NULL); + assert(source != NULL); // a NULL source means no selection + + struct wlr_data_offer *offer = calloc(1, sizeof(*offer)); + if (offer == NULL) { + return NULL; + } + offer->source = source; + offer->type = type; + + struct wl_client *client = wl_resource_get_client(device_resource); + uint32_t version = wl_resource_get_version(device_resource); + offer->resource = + wl_resource_create(client, &wl_data_offer_interface, version, 0); + if (offer->resource == NULL) { + free(offer); + return NULL; + } + wl_resource_set_implementation(offer->resource, &data_offer_impl, offer, + data_offer_handle_resource_destroy); + + switch (type) { + case WLR_DATA_OFFER_SELECTION: + wl_list_insert(&seat_client->seat->selection_offers, &offer->link); + break; + case WLR_DATA_OFFER_DRAG: + wl_list_insert(&seat_client->seat->drag_offers, &offer->link); + break; + } + + offer->source_destroy.notify = data_offer_handle_source_destroy; + wl_signal_add(&source->events.destroy, &offer->source_destroy); + + wl_data_device_send_data_offer(device_resource, offer->resource); + + char **p; + wl_array_for_each(p, &source->mime_types) { + wl_data_offer_send_offer(offer->resource, *p); + } + + return offer; +} diff --git a/3rdparty/wlroots/types/data_device/wlr_data_source.c b/3rdparty/wlroots/types/data_device/wlr_data_source.c new file mode 100644 index 0000000000..6e534f5c3b --- /dev/null +++ b/3rdparty/wlroots/types/data_device/wlr_data_source.c @@ -0,0 +1,276 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_data_device.h" + +void wlr_data_source_init(struct wlr_data_source *source, + const struct wlr_data_source_impl *impl) { + assert(impl->send); + + *source = (struct wlr_data_source){ + .impl = impl, + .actions = -1, + }; + wl_array_init(&source->mime_types); + wl_signal_init(&source->events.destroy); + wl_signal_init(&source->events.dnd_action); +} + +void wlr_data_source_send(struct wlr_data_source *source, const char *mime_type, + int32_t fd) { + source->impl->send(source, mime_type, fd); +} + +void wlr_data_source_accept(struct wlr_data_source *source, uint32_t serial, + const char *mime_type) { + source->accepted = (mime_type != NULL); + if (source->impl->accept) { + source->impl->accept(source, serial, mime_type); + } +} + +void wlr_data_source_destroy(struct wlr_data_source *source) { + if (source == NULL) { + return; + } + + wl_signal_emit_mutable(&source->events.destroy, source); + + assert(wl_list_empty(&source->events.destroy.listener_list)); + + char **p; + wl_array_for_each(p, &source->mime_types) { + free(*p); + } + wl_array_release(&source->mime_types); + + if (source->impl->destroy) { + source->impl->destroy(source); + } else { + free(source); + } +} + +void wlr_data_source_dnd_drop(struct wlr_data_source *source) { + if (source->impl->dnd_drop) { + source->impl->dnd_drop(source); + } +} + +void wlr_data_source_dnd_finish(struct wlr_data_source *source) { + if (source->impl->dnd_finish) { + source->impl->dnd_finish(source); + } +} + +void wlr_data_source_dnd_action(struct wlr_data_source *source, + enum wl_data_device_manager_dnd_action action) { + source->current_dnd_action = action; + if (source->impl->dnd_action) { + source->impl->dnd_action(source, action); + } + wl_signal_emit_mutable(&source->events.dnd_action, source); +} + + +static const struct wl_data_source_interface data_source_impl; + +struct wlr_client_data_source *client_data_source_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_data_source_interface, + &data_source_impl)); + return wl_resource_get_user_data(resource); +} + +static void client_data_source_accept(struct wlr_data_source *wlr_source, + uint32_t serial, const char *mime_type); + +static struct wlr_client_data_source *client_data_source_from_wlr_data_source( + struct wlr_data_source *wlr_source) { + assert(wlr_source->impl->accept == client_data_source_accept); + struct wlr_client_data_source *source = wl_container_of(wlr_source, source, source); + return source; +} + +static void client_data_source_accept(struct wlr_data_source *wlr_source, + uint32_t serial, const char *mime_type) { + struct wlr_client_data_source *source = + client_data_source_from_wlr_data_source(wlr_source); + wl_data_source_send_target(source->resource, mime_type); +} + +static void client_data_source_send(struct wlr_data_source *wlr_source, + const char *mime_type, int32_t fd) { + struct wlr_client_data_source *source = + client_data_source_from_wlr_data_source(wlr_source); + wl_data_source_send_send(source->resource, mime_type, fd); + close(fd); +} + +static void client_data_source_destroy(struct wlr_data_source *wlr_source) { + struct wlr_client_data_source *source = + client_data_source_from_wlr_data_source(wlr_source); + wl_data_source_send_cancelled(source->resource); + wl_resource_set_user_data(source->resource, NULL); + free(source); +} + +static void client_data_source_dnd_drop(struct wlr_data_source *wlr_source) { + struct wlr_client_data_source *source = + client_data_source_from_wlr_data_source(wlr_source); + assert(wl_resource_get_version(source->resource) >= + WL_DATA_SOURCE_DND_DROP_PERFORMED_SINCE_VERSION); + wl_data_source_send_dnd_drop_performed(source->resource); +} + +static void client_data_source_dnd_finish(struct wlr_data_source *wlr_source) { + struct wlr_client_data_source *source = + client_data_source_from_wlr_data_source(wlr_source); + assert(wl_resource_get_version(source->resource) >= + WL_DATA_SOURCE_DND_FINISHED_SINCE_VERSION); + wl_data_source_send_dnd_finished(source->resource); +} + +static void client_data_source_dnd_action(struct wlr_data_source *wlr_source, + enum wl_data_device_manager_dnd_action action) { + struct wlr_client_data_source *source = + client_data_source_from_wlr_data_source(wlr_source); + assert(wl_resource_get_version(source->resource) >= + WL_DATA_SOURCE_ACTION_SINCE_VERSION); + wl_data_source_send_action(source->resource, action); +} + +static void data_source_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void data_source_set_actions(struct wl_client *client, + struct wl_resource *resource, uint32_t dnd_actions) { + struct wlr_client_data_source *source = + client_data_source_from_resource(resource); + if (source == NULL) { + return; + } + + if (source->source.actions >= 0) { + wl_resource_post_error(source->resource, + WL_DATA_SOURCE_ERROR_INVALID_ACTION_MASK, + "cannot set actions more than once"); + return; + } + + if (dnd_actions & ~DATA_DEVICE_ALL_ACTIONS) { + wl_resource_post_error(source->resource, + WL_DATA_SOURCE_ERROR_INVALID_ACTION_MASK, + "invalid action mask %x", dnd_actions); + return; + } + + if (source->finalized) { + wl_resource_post_error(source->resource, + WL_DATA_SOURCE_ERROR_INVALID_ACTION_MASK, + "invalid action change after wl_data_device.start_drag"); + return; + } + + source->source.actions = dnd_actions; +} + +static void data_source_offer(struct wl_client *client, + struct wl_resource *resource, const char *mime_type) { + struct wlr_client_data_source *source = + client_data_source_from_resource(resource); + if (source == NULL) { + return; + } + if (source->finalized) { + wlr_log(WLR_DEBUG, "Offering additional MIME type after " + "wl_data_device.set_selection"); + } + + const char **mime_type_ptr; + wl_array_for_each(mime_type_ptr, &source->source.mime_types) { + if (strcmp(*mime_type_ptr, mime_type) == 0) { + wlr_log(WLR_DEBUG, "Ignoring duplicate MIME type offer %s", + mime_type); + return; + } + } + + char *dup_mime_type = strdup(mime_type); + if (dup_mime_type == NULL) { + wl_resource_post_no_memory(resource); + return; + } + + char **p = wl_array_add(&source->source.mime_types, sizeof(*p)); + if (p == NULL) { + free(dup_mime_type); + wl_resource_post_no_memory(resource); + return; + } + + *p = dup_mime_type; +} + +static const struct wl_data_source_interface data_source_impl = { + .destroy = data_source_destroy, + .offer = data_source_offer, + .set_actions = data_source_set_actions, +}; + +static void data_source_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_client_data_source *source = + client_data_source_from_resource(resource); + if (source != NULL) { + wlr_data_source_destroy(&source->source); + } + wl_list_remove(wl_resource_get_link(resource)); +} + +struct wlr_client_data_source *client_data_source_create( + struct wl_client *client, uint32_t version, uint32_t id, + struct wl_list *resource_list) { + struct wlr_client_data_source *source = calloc(1, sizeof(*source)); + if (source == NULL) { + return NULL; + } + + source->resource = wl_resource_create(client, &wl_data_source_interface, + version, id); + if (source->resource == NULL) { + wl_resource_post_no_memory(source->resource); + free(source); + return NULL; + } + wl_resource_set_implementation(source->resource, &data_source_impl, + source, data_source_handle_resource_destroy); + wl_list_insert(resource_list, wl_resource_get_link(source->resource)); + + source->impl.accept = client_data_source_accept; + source->impl.send = client_data_source_send; + source->impl.destroy = client_data_source_destroy; + + if (wl_resource_get_version(source->resource) >= + WL_DATA_SOURCE_DND_DROP_PERFORMED_SINCE_VERSION) { + source->impl.dnd_drop = client_data_source_dnd_drop; + } + if (wl_resource_get_version(source->resource) >= + WL_DATA_SOURCE_DND_FINISHED_SINCE_VERSION) { + source->impl.dnd_finish = client_data_source_dnd_finish; + } + if (wl_resource_get_version(source->resource) >= + WL_DATA_SOURCE_ACTION_SINCE_VERSION) { + source->impl.dnd_action = client_data_source_dnd_action; + } + + wlr_data_source_init(&source->source, &source->impl); + return source; +} diff --git a/3rdparty/wlroots/types/data_device/wlr_drag.c b/3rdparty/wlroots/types/data_device/wlr_drag.c new file mode 100644 index 0000000000..df706ca354 --- /dev/null +++ b/3rdparty/wlroots/types/data_device/wlr_drag.c @@ -0,0 +1,561 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_data_device.h" + +static void drag_handle_seat_client_destroy(struct wl_listener *listener, + void *data) { + struct wlr_drag *drag = + wl_container_of(listener, drag, seat_client_destroy); + + drag->focus_client = NULL; + wl_list_remove(&drag->seat_client_destroy.link); +} + +static void drag_set_focus(struct wlr_drag *drag, + struct wlr_surface *surface, double sx, double sy); + +static void drag_handle_focus_destroy(struct wl_listener *listener, void *data) { + struct wlr_drag *drag = wl_container_of(listener, drag, focus_destroy); + drag_set_focus(drag, NULL, 0, 0); +} + +static void drag_set_focus(struct wlr_drag *drag, + struct wlr_surface *surface, double sx, double sy) { + if (drag->focus == surface) { + return; + } + + if (drag->focus_client) { + wl_list_remove(&drag->seat_client_destroy.link); + + // If we're switching focus to another client, we want to destroy all + // offers without destroying the source. If the drag operation ends, we + // want to keep the offer around for the data transfer. + struct wlr_data_offer *offer, *tmp; + wl_list_for_each_safe(offer, tmp, + &drag->focus_client->seat->drag_offers, link) { + struct wl_client *client = wl_resource_get_client(offer->resource); + if (!drag->dropped && offer->source == drag->source && + client == drag->focus_client->client) { + offer->source = NULL; + data_offer_destroy(offer); + } + } + + struct wl_resource *resource; + wl_resource_for_each(resource, &drag->focus_client->data_devices) { + wl_data_device_send_leave(resource); + } + + drag->focus_client = NULL; + } + + wl_list_remove(&drag->focus_destroy.link); + wl_list_init(&drag->focus_destroy.link); + drag->focus = NULL; + + if (!surface) { + goto out; + } + + if (!drag->source && drag->seat_client && + wl_resource_get_client(surface->resource) != + drag->seat_client->client) { + goto out; + } + + struct wlr_seat_client *focus_client = wlr_seat_client_for_wl_client( + drag->seat, wl_resource_get_client(surface->resource)); + if (!focus_client) { + goto out; + } + + if (drag->source != NULL) { + drag->source->accepted = false; + + uint32_t serial = + wl_display_next_serial(drag->seat->display); + + struct wl_resource *device_resource; + wl_resource_for_each(device_resource, &focus_client->data_devices) { + struct wlr_data_offer *offer = data_offer_create(device_resource, + drag->source, WLR_DATA_OFFER_DRAG); + if (offer == NULL) { + wl_resource_post_no_memory(device_resource); + return; + } + + data_offer_update_action(offer); + + if (wl_resource_get_version(offer->resource) >= + WL_DATA_OFFER_SOURCE_ACTIONS_SINCE_VERSION) { + wl_data_offer_send_source_actions(offer->resource, + drag->source->actions); + } + + wl_data_device_send_enter(device_resource, serial, + surface->resource, + wl_fixed_from_double(sx), wl_fixed_from_double(sy), + offer->resource); + } + } + + drag->focus = surface; + drag->focus_client = focus_client; + drag->focus_destroy.notify = drag_handle_focus_destroy; + wl_signal_add(&surface->events.destroy, &drag->focus_destroy); + drag->seat_client_destroy.notify = drag_handle_seat_client_destroy; + wl_signal_add(&focus_client->events.destroy, &drag->seat_client_destroy); + +out: + wl_signal_emit_mutable(&drag->events.focus, drag); +} + +static void drag_icon_destroy(struct wlr_drag_icon *icon) { + icon->drag->icon = NULL; + wl_list_remove(&icon->surface_destroy.link); + wl_signal_emit_mutable(&icon->events.destroy, icon); + + assert(wl_list_empty(&icon->events.destroy.listener_list)); + + free(icon); +} + +static void drag_destroy(struct wlr_drag *drag) { + if (drag->cancelling) { + return; + } + drag->cancelling = true; + + if (drag->started) { + wlr_seat_keyboard_end_grab(drag->seat); + switch (drag->grab_type) { + case WLR_DRAG_GRAB_KEYBOARD: + break; + case WLR_DRAG_GRAB_KEYBOARD_POINTER: + wlr_seat_pointer_end_grab(drag->seat); + break; + case WLR_DRAG_GRAB_KEYBOARD_TOUCH: + wlr_seat_touch_end_grab(drag->seat); + break; + } + } + + if (drag->started) { + drag_set_focus(drag, NULL, 0, 0); + + assert(drag->seat->drag == drag); + drag->seat->drag = NULL; + } + + // We issue destroy after ending the grab to allow focus changes. + // Furthermore, we wait until after clearing the drag focus in order + // to ensure that the wl_data_device.leave is sent before emitting the + // signal. This allows e.g. wl_pointer.enter to be sent in the destroy + // signal handler. + wl_signal_emit_mutable(&drag->events.destroy, drag); + + assert(wl_list_empty(&drag->events.focus.listener_list)); + assert(wl_list_empty(&drag->events.motion.listener_list)); + assert(wl_list_empty(&drag->events.drop.listener_list)); + assert(wl_list_empty(&drag->events.destroy.listener_list)); + + if (drag->source) { + wl_list_remove(&drag->source_destroy.link); + } + wl_list_remove(&drag->focus_destroy.link); + + if (drag->icon != NULL) { + drag_icon_destroy(drag->icon); + } + free(drag); +} + +static void drag_handle_pointer_enter(struct wlr_seat_pointer_grab *grab, + struct wlr_surface *surface, double sx, double sy) { + struct wlr_drag *drag = grab->data; + drag_set_focus(drag, surface, sx, sy); +} + +static void drag_handle_pointer_clear_focus(struct wlr_seat_pointer_grab *grab) { + struct wlr_drag *drag = grab->data; + drag_set_focus(drag, NULL, 0, 0); +} + +static void drag_handle_pointer_motion(struct wlr_seat_pointer_grab *grab, + uint32_t time, double sx, double sy) { + struct wlr_drag *drag = grab->data; + if (drag->focus != NULL && drag->focus_client != NULL) { + struct wl_resource *resource; + wl_resource_for_each(resource, &drag->focus_client->data_devices) { + wl_data_device_send_motion(resource, time, wl_fixed_from_double(sx), + wl_fixed_from_double(sy)); + } + + struct wlr_drag_motion_event event = { + .drag = drag, + .time = time, + .sx = sx, + .sy = sy, + }; + wl_signal_emit_mutable(&drag->events.motion, &event); + } +} + +static void drag_drop(struct wlr_drag *drag, uint32_t time) { + assert(drag->focus_client); + + drag->dropped = true; + + struct wl_resource *resource; + wl_resource_for_each(resource, &drag->focus_client->data_devices) { + wl_data_device_send_drop(resource); + } + if (drag->source) { + wlr_data_source_dnd_drop(drag->source); + } + + struct wlr_drag_drop_event event = { + .drag = drag, + .time = time, + }; + wl_signal_emit_mutable(&drag->events.drop, &event); +} + +static uint32_t drag_handle_pointer_button(struct wlr_seat_pointer_grab *grab, + uint32_t time, uint32_t button, uint32_t state) { + struct wlr_drag *drag = grab->data; + + if (drag->source && + grab->seat->pointer_state.grab_button == button && + state == WL_POINTER_BUTTON_STATE_RELEASED) { + if (drag->focus_client && drag->source->current_dnd_action && + drag->source->accepted) { + drag_drop(drag, time); + } else if (drag->source->impl->dnd_finish) { + // This will end the grab and free `drag` + wlr_data_source_destroy(drag->source); + return 0; + } + } + + if (grab->seat->pointer_state.button_count == 0 && + state == WL_POINTER_BUTTON_STATE_RELEASED) { + drag_destroy(drag); + } + + return 0; +} + +static void drag_handle_pointer_axis(struct wlr_seat_pointer_grab *grab, + uint32_t time, enum wl_pointer_axis orientation, double value, + int32_t value_discrete, enum wl_pointer_axis_source source, + enum wl_pointer_axis_relative_direction relative_direction) { + // This space is intentionally left blank +} + +static void drag_handle_pointer_cancel(struct wlr_seat_pointer_grab *grab) { + struct wlr_drag *drag = grab->data; + drag_destroy(drag); +} + +static const struct wlr_pointer_grab_interface + data_device_pointer_drag_interface = { + .enter = drag_handle_pointer_enter, + .clear_focus = drag_handle_pointer_clear_focus, + .motion = drag_handle_pointer_motion, + .button = drag_handle_pointer_button, + .axis = drag_handle_pointer_axis, + .cancel = drag_handle_pointer_cancel, +}; + +static uint32_t drag_handle_touch_down(struct wlr_seat_touch_grab *grab, + uint32_t time, struct wlr_touch_point *point) { + // eat the event + return 0; +} + +static uint32_t drag_handle_touch_up(struct wlr_seat_touch_grab *grab, + uint32_t time, struct wlr_touch_point *point) { + struct wlr_drag *drag = grab->data; + if (drag->grab_touch_id != point->touch_id) { + return 0; + } + + if (drag->focus_client && drag->source->current_dnd_action && + drag->source->accepted) { + drag_drop(drag, time); + } else if (drag->source->impl->dnd_finish) { + // This will end the grab and free `drag` + wlr_data_source_destroy(drag->source); + return 0; + } + + drag_destroy(drag); + return 0; +} + +static void drag_handle_touch_motion(struct wlr_seat_touch_grab *grab, + uint32_t time, struct wlr_touch_point *point) { + struct wlr_drag *drag = grab->data; + if (drag->focus && drag->focus_client) { + struct wl_resource *resource; + wl_resource_for_each(resource, &drag->focus_client->data_devices) { + wl_data_device_send_motion(resource, time, + wl_fixed_from_double(point->sx), + wl_fixed_from_double(point->sy)); + } + + struct wlr_drag_motion_event event = { + .drag = drag, + .time = time, + .sx = point->sx, + .sy = point->sy, + }; + wl_signal_emit_mutable(&drag->events.motion, &event); + } +} + +static void drag_handle_touch_enter(struct wlr_seat_touch_grab *grab, + uint32_t time, struct wlr_touch_point *point) { + struct wlr_drag *drag = grab->data; + drag_set_focus(drag, point->focus_surface, point->sx, point->sy); +} + +static void drag_handle_touch_cancel(struct wlr_seat_touch_grab *grab) { + struct wlr_drag *drag = grab->data; + drag_destroy(drag); +} + +static void drag_handle_clear_focus(struct wlr_seat_touch_grab *grab, uint32_t time_msec, + struct wlr_touch_point *point) { + struct wlr_drag *drag = grab->data; + drag_set_focus(drag, NULL, 0, 0); +} + +static const struct wlr_touch_grab_interface + data_device_touch_drag_interface = { + .down = drag_handle_touch_down, + .up = drag_handle_touch_up, + .motion = drag_handle_touch_motion, + .enter = drag_handle_touch_enter, + .cancel = drag_handle_touch_cancel, + .clear_focus = drag_handle_clear_focus, +}; + +static void drag_handle_keyboard_enter(struct wlr_seat_keyboard_grab *grab, + struct wlr_surface *surface, const uint32_t keycodes[], size_t num_keycodes, + const struct wlr_keyboard_modifiers *modifiers) { + // nothing has keyboard focus during drags +} + +static void drag_handle_keyboard_clear_focus(struct wlr_seat_keyboard_grab *grab) { + // nothing has keyboard focus during drags +} + +static void drag_handle_keyboard_key(struct wlr_seat_keyboard_grab *grab, + uint32_t time, uint32_t key, uint32_t state) { + // no keyboard input during drags +} + +static void drag_handle_keyboard_modifiers(struct wlr_seat_keyboard_grab *grab, + const struct wlr_keyboard_modifiers *modifiers) { + //struct wlr_keyboard *keyboard = grab->seat->keyboard_state.keyboard; + // TODO change the dnd action based on what modifier is pressed on the + // keyboard +} + +static void drag_handle_keyboard_cancel(struct wlr_seat_keyboard_grab *grab) { + struct wlr_drag *drag = grab->data; + drag_destroy(drag); +} + +static const struct wlr_keyboard_grab_interface + data_device_keyboard_drag_interface = { + .enter = drag_handle_keyboard_enter, + .clear_focus = drag_handle_keyboard_clear_focus, + .key = drag_handle_keyboard_key, + .modifiers = drag_handle_keyboard_modifiers, + .cancel = drag_handle_keyboard_cancel, +}; + +static void drag_handle_icon_destroy(struct wl_listener *listener, void *data) { + struct wlr_drag *drag = wl_container_of(listener, drag, icon_destroy); + drag->icon = NULL; + wl_list_remove(&drag->icon_destroy.link); +} + +static void drag_handle_drag_source_destroy(struct wl_listener *listener, + void *data) { + struct wlr_drag *drag = wl_container_of(listener, drag, source_destroy); + drag_destroy(drag); +} + +static void drag_icon_surface_role_commit(struct wlr_surface *surface) { + assert(surface->role == &drag_icon_surface_role); + + pixman_region32_clear(&surface->input_region); + if (wlr_surface_has_buffer(surface)) { + wlr_surface_map(surface); + } +} + +const struct wlr_surface_role drag_icon_surface_role = { + .name = "wl_data_device-icon", + .no_object = true, + .commit = drag_icon_surface_role_commit, +}; + +static void drag_icon_handle_surface_destroy(struct wl_listener *listener, + void *data) { + struct wlr_drag_icon *icon = + wl_container_of(listener, icon, surface_destroy); + drag_icon_destroy(icon); +} + +static struct wlr_drag_icon *drag_icon_create(struct wlr_drag *drag, + struct wlr_surface *surface) { + struct wlr_drag_icon *icon = calloc(1, sizeof(*icon)); + if (!icon) { + return NULL; + } + + icon->drag = drag; + icon->surface = surface; + + wl_signal_init(&icon->events.destroy); + + icon->surface_destroy.notify = drag_icon_handle_surface_destroy; + wl_signal_add(&surface->events.destroy, &icon->surface_destroy); + + drag_icon_surface_role_commit(surface); + + return icon; +} + +struct wlr_drag *wlr_drag_create(struct wlr_seat_client *seat_client, + struct wlr_data_source *source, struct wlr_surface *icon_surface) { + struct wlr_drag *drag = calloc(1, sizeof(*drag)); + if (drag == NULL) { + return NULL; + } + + wl_signal_init(&drag->events.focus); + wl_signal_init(&drag->events.motion); + wl_signal_init(&drag->events.drop); + wl_signal_init(&drag->events.destroy); + + wl_list_init(&drag->focus_destroy.link); + + drag->seat = seat_client->seat; + drag->seat_client = seat_client; + + if (icon_surface) { + struct wlr_drag_icon *icon = drag_icon_create(drag, icon_surface); + if (icon == NULL) { + free(drag); + return NULL; + } + + drag->icon = icon; + + drag->icon_destroy.notify = drag_handle_icon_destroy; + wl_signal_add(&icon->events.destroy, &drag->icon_destroy); + } + + drag->source = source; + if (source != NULL) { + drag->source_destroy.notify = drag_handle_drag_source_destroy; + wl_signal_add(&source->events.destroy, &drag->source_destroy); + } + + drag->pointer_grab.data = drag; + drag->pointer_grab.interface = &data_device_pointer_drag_interface; + + drag->touch_grab.data = drag; + drag->touch_grab.interface = &data_device_touch_drag_interface; + + drag->keyboard_grab.data = drag; + drag->keyboard_grab.interface = &data_device_keyboard_drag_interface; + + return drag; +} + +void wlr_seat_request_start_drag(struct wlr_seat *seat, struct wlr_drag *drag, + struct wlr_surface *origin, uint32_t serial) { + assert(drag->seat == seat); + + if (seat->drag != NULL) { + wlr_log(WLR_DEBUG, "Rejecting start_drag request, " + "another drag-and-drop operation is already in progress"); + return; + } + + struct wlr_seat_request_start_drag_event event = { + .drag = drag, + .origin = origin, + .serial = serial, + }; + wl_signal_emit_mutable(&seat->events.request_start_drag, &event); +} + +static void seat_handle_drag_source_destroy(struct wl_listener *listener, + void *data) { + struct wlr_seat *seat = + wl_container_of(listener, seat, drag_source_destroy); + wl_list_remove(&seat->drag_source_destroy.link); + seat->drag_source = NULL; +} + +void wlr_seat_start_drag(struct wlr_seat *seat, struct wlr_drag *drag, + uint32_t serial) { + assert(drag->seat == seat); + assert(!drag->started); + drag->started = true; + + wlr_seat_keyboard_start_grab(seat, &drag->keyboard_grab); + + seat->drag = drag; + seat->drag_serial = serial; + + // We need to destroy the previous source, because listeners only expect one + // active drag source at a time. + wlr_data_source_destroy(seat->drag_source); + seat->drag_source = drag->source; + if (drag->source != NULL) { + seat->drag_source_destroy.notify = seat_handle_drag_source_destroy; + wl_signal_add(&drag->source->events.destroy, &seat->drag_source_destroy); + } + + wl_signal_emit_mutable(&seat->events.start_drag, drag); +} + +void wlr_seat_start_pointer_drag(struct wlr_seat *seat, struct wlr_drag *drag, + uint32_t serial) { + drag->grab_type = WLR_DRAG_GRAB_KEYBOARD_POINTER; + + wlr_seat_pointer_clear_focus(seat); + wlr_seat_pointer_start_grab(seat, &drag->pointer_grab); + + wlr_seat_start_drag(seat, drag, serial); +} + +void wlr_seat_start_touch_drag(struct wlr_seat *seat, struct wlr_drag *drag, + uint32_t serial, struct wlr_touch_point *point) { + drag->grab_type = WLR_DRAG_GRAB_KEYBOARD_TOUCH; + drag->grab_touch_id = seat->touch_state.grab_id; + drag->touch_id = point->touch_id; + + wlr_seat_touch_start_grab(seat, &drag->touch_grab); + drag_set_focus(drag, point->surface, point->sx, point->sy); + + wlr_seat_start_drag(seat, drag, serial); +} diff --git a/3rdparty/wlroots/types/ext_image_capture_source_v1/base.c b/3rdparty/wlroots/types/ext_image_capture_source_v1/base.c new file mode 100644 index 0000000000..eccbb28843 --- /dev/null +++ b/3rdparty/wlroots/types/ext_image_capture_source_v1/base.c @@ -0,0 +1,172 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ext-image-capture-source-v1-protocol.h" +#include "render/wlr_renderer.h" + +static void source_handle_destroy(struct wl_client *client, + struct wl_resource *source_resource) { + wl_resource_destroy(source_resource); +} + +static const struct ext_image_capture_source_v1_interface source_impl = { + .destroy = source_handle_destroy, +}; + +struct wlr_ext_image_capture_source_v1 *wlr_ext_image_capture_source_v1_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_image_capture_source_v1_interface, &source_impl)); + return wl_resource_get_user_data(resource); +} + +static void source_handle_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +void wlr_ext_image_capture_source_v1_init(struct wlr_ext_image_capture_source_v1 *source, + const struct wlr_ext_image_capture_source_v1_interface *impl) { + *source = (struct wlr_ext_image_capture_source_v1){ + .impl = impl, + }; + wl_list_init(&source->resources); + wl_signal_init(&source->events.destroy); + wl_signal_init(&source->events.constraints_update); + wl_signal_init(&source->events.frame); +} + +void wlr_ext_image_capture_source_v1_finish(struct wlr_ext_image_capture_source_v1 *source) { + wl_signal_emit_mutable(&source->events.destroy, NULL); + + assert(wl_list_empty(&source->events.destroy.listener_list)); + assert(wl_list_empty(&source->events.constraints_update.listener_list)); + assert(wl_list_empty(&source->events.frame.listener_list)); + + struct wl_resource *resource, *resource_tmp; + wl_resource_for_each_safe(resource, resource_tmp, &source->resources) { + wl_resource_set_user_data(resource, NULL); + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + } + + free(source->shm_formats); + wlr_drm_format_set_finish(&source->dmabuf_formats); +} + +bool wlr_ext_image_capture_source_v1_create_resource(struct wlr_ext_image_capture_source_v1 *source, + struct wl_client *client, uint32_t new_id) { + struct wl_resource *resource = wl_resource_create(client, + &ext_image_capture_source_v1_interface, 1, new_id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return false; + } + wl_resource_set_implementation(resource, &source_impl, source, + source_handle_resource_destroy); + if (source != NULL) { + wl_list_insert(&source->resources, wl_resource_get_link(resource)); + } else { + wl_list_init(wl_resource_get_link(resource)); + } + return true; +} + +static uint32_t get_swapchain_shm_format(struct wlr_swapchain *swapchain, + struct wlr_renderer *renderer) { + struct wlr_buffer *buffer = wlr_swapchain_acquire(swapchain); + if (buffer == NULL) { + return DRM_FORMAT_INVALID; + } + + struct wlr_texture *texture = wlr_texture_from_buffer(renderer, buffer); + wlr_buffer_unlock(buffer); + if (texture == NULL) { + return DRM_FORMAT_INVALID; + } + + uint32_t format = wlr_texture_preferred_read_format(texture); + wlr_texture_destroy(texture); + + return format; +} + +static void add_drm_format(struct wlr_drm_format_set *set, const struct wlr_drm_format *fmt) { + for (size_t i = 0; i < fmt->len; i++) { + wlr_drm_format_set_add(set, fmt->format, fmt->modifiers[i]); + } +} + +bool wlr_ext_image_capture_source_v1_set_constraints_from_swapchain(struct wlr_ext_image_capture_source_v1 *source, + struct wlr_swapchain *swapchain, struct wlr_renderer *renderer) { + source->width = swapchain->width; + source->height = swapchain->height; + + uint32_t shm_format = get_swapchain_shm_format(swapchain, renderer); + if (shm_format != DRM_FORMAT_INVALID) { + uint32_t *shm_formats = calloc(1, sizeof(shm_formats[0])); + if (shm_formats == NULL) { + wlr_log(WLR_ERROR, "Allocation failed"); + return false; + } + shm_formats[0] = shm_format; + + source->shm_formats_len = 1; + free(source->shm_formats); + source->shm_formats = shm_formats; + } + + int drm_fd = wlr_renderer_get_drm_fd(renderer); + if (swapchain->allocator != NULL && + (swapchain->allocator->buffer_caps & WLR_BUFFER_CAP_DMABUF) && + drm_fd >= 0) { + struct stat dev_stat; + if (fstat(drm_fd, &dev_stat) != 0) { + wlr_log_errno(WLR_ERROR, "fstat() failed"); + return false; + } + + source->dmabuf_device = dev_stat.st_rdev; + + wlr_drm_format_set_finish(&source->dmabuf_formats); + source->dmabuf_formats = (struct wlr_drm_format_set){0}; + + add_drm_format(&source->dmabuf_formats, &swapchain->format); + + const struct wlr_drm_format_set *render_formats = + wlr_renderer_get_render_formats(renderer); + assert(render_formats != NULL); + + // Not all clients support fancy formats. Always ensure we provide + // support for ARGB8888 and XRGB8888 for simple clients. + uint32_t fallback_formats[] = { DRM_FORMAT_ARGB8888, DRM_FORMAT_XRGB8888 }; + for (size_t i = 0; i < sizeof(fallback_formats) / sizeof(fallback_formats[0]); i++) { + const struct wlr_drm_format *fmt = + wlr_drm_format_set_get(render_formats, fallback_formats[i]); + if (fmt != NULL && swapchain->format.format != fmt->format) { + add_drm_format(&source->dmabuf_formats, fmt); + } + } + } + + wl_signal_emit_mutable(&source->events.constraints_update, NULL); + return true; +} + +void wlr_ext_image_capture_source_v1_cursor_init(struct wlr_ext_image_capture_source_v1_cursor *source_cursor, + const struct wlr_ext_image_capture_source_v1_interface *impl) { + *source_cursor = (struct wlr_ext_image_capture_source_v1_cursor){0}; + wlr_ext_image_capture_source_v1_init(&source_cursor->base, impl); + wl_signal_init(&source_cursor->events.update); +} + +void wlr_ext_image_capture_source_v1_cursor_finish(struct wlr_ext_image_capture_source_v1_cursor *source_cursor) { + wlr_ext_image_capture_source_v1_finish(&source_cursor->base); + assert(wl_list_empty(&source_cursor->events.update.listener_list)); +} diff --git a/3rdparty/wlroots/types/ext_image_capture_source_v1/foreign_toplevel.c b/3rdparty/wlroots/types/ext_image_capture_source_v1/foreign_toplevel.c new file mode 100644 index 0000000000..28bb0badd8 --- /dev/null +++ b/3rdparty/wlroots/types/ext_image_capture_source_v1/foreign_toplevel.c @@ -0,0 +1,123 @@ +#include +#include +#include +#include +#include +#include "ext-image-capture-source-v1-protocol.h" +#include "util/global.h" + +#define FOREIGN_TOPLEVEL_IMAGE_SOURCE_MANAGER_V1_VERSION 1 + +static const struct ext_foreign_toplevel_image_capture_source_manager_v1_interface foreign_toplevel_manager_impl; + +static struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1 * +foreign_toplevel_manager_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_foreign_toplevel_image_capture_source_manager_v1_interface, + &foreign_toplevel_manager_impl)); + return wl_resource_get_user_data(resource); +} + +bool wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request_accept( + struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request *request, + struct wlr_ext_image_capture_source_v1 *source) { + return wlr_ext_image_capture_source_v1_create_resource(source, request->client, request->new_id); +} + +static void foreign_toplevel_manager_handle_create_source(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t new_id, + struct wl_resource *foreign_toplevel_resource) { + struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1 *manager = + foreign_toplevel_manager_from_resource(manager_resource); + struct wlr_ext_foreign_toplevel_handle_v1 *toplevel_handle = + wlr_ext_foreign_toplevel_handle_v1_from_resource(foreign_toplevel_resource); + if (toplevel_handle == NULL) { + wlr_ext_image_capture_source_v1_create_resource(NULL, client, new_id); + return; + } + + struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request request = { + .toplevel_handle = toplevel_handle, + .client = client, + .new_id = new_id, + }; + + wl_signal_emit_mutable(&manager->events.new_request, &request); +} + +static void foreign_toplevel_manager_handle_destroy(struct wl_client *client, + struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static const struct ext_foreign_toplevel_image_capture_source_manager_v1_interface foreign_toplevel_manager_impl = { + .create_source = foreign_toplevel_manager_handle_create_source, + .destroy = foreign_toplevel_manager_handle_destroy, +}; + +static void foreign_toplevel_manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &ext_foreign_toplevel_image_capture_source_manager_v1_interface, version, id); + if (!resource) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &foreign_toplevel_manager_impl, manager, NULL); +} + +static void ext_foreign_toplevel_image_capture_source_manager_v1_destroy( + struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, NULL); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + assert(wl_list_empty(&manager->events.new_request.listener_list)); + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_ext_foreign_toplevel_image_capture_source_manager_v1_destroy( + struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1 *manager, bool destroy_global_safe) { + ext_foreign_toplevel_image_capture_source_manager_v1_destroy(manager, destroy_global_safe); +} + +static void foreign_toplevel_manager_handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + ext_foreign_toplevel_image_capture_source_manager_v1_destroy(manager, false); +} + +struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1 * +wlr_ext_foreign_toplevel_image_capture_source_manager_v1_create(struct wl_display *display, + uint32_t version) { + assert(version <= FOREIGN_TOPLEVEL_IMAGE_SOURCE_MANAGER_V1_VERSION); + + struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1 *manager = + calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + manager->global = wl_global_create(display, + &ext_foreign_toplevel_image_capture_source_manager_v1_interface, + version, manager, foreign_toplevel_manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + wl_signal_init(&manager->events.destroy); + wl_signal_init(&manager->events.new_request); + + manager->display_destroy.notify = foreign_toplevel_manager_handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/ext_image_capture_source_v1/output.c b/3rdparty/wlroots/types/ext_image_capture_source_v1/output.c new file mode 100644 index 0000000000..5c167f1ee0 --- /dev/null +++ b/3rdparty/wlroots/types/ext_image_capture_source_v1/output.c @@ -0,0 +1,426 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ext-image-capture-source-v1-protocol.h" +#include "util/global.h" + +#define OUTPUT_IMAGE_SOURCE_MANAGER_V1_VERSION 1 + +struct output_cursor_source { + struct wlr_ext_image_capture_source_v1_cursor base; + + struct wlr_output *output; + struct wlr_buffer *prev_buffer; + bool initialized; + bool needs_frame; + + struct wl_listener output_commit; + struct wl_listener prev_buffer_release; +}; + +struct wlr_ext_output_image_capture_source_v1 { + struct wlr_ext_image_capture_source_v1 base; + struct wlr_addon addon; + + struct wlr_output *output; + + struct wl_listener output_commit; + + struct output_cursor_source cursor; + + size_t num_started; + bool software_cursors_locked; +}; + +struct wlr_ext_output_image_capture_source_v1_frame_event { + struct wlr_ext_image_capture_source_v1_frame_event base; + struct wlr_buffer *buffer; + struct timespec when; +}; + +static void output_source_start(struct wlr_ext_image_capture_source_v1 *base, + bool with_cursors) { + struct wlr_ext_output_image_capture_source_v1 *source = wl_container_of(base, source, base); + source->num_started++; + if (source->num_started > 1) { + return; + } + wlr_output_lock_attach_render(source->output, true); + if (with_cursors) { + wlr_output_lock_software_cursors(source->output, true); + } + source->software_cursors_locked = with_cursors; +} + +static void output_source_stop(struct wlr_ext_image_capture_source_v1 *base) { + struct wlr_ext_output_image_capture_source_v1 *source = wl_container_of(base, source, base); + assert(source->num_started > 0); + source->num_started--; + if (source->num_started > 0) { + return; + } + wlr_output_lock_attach_render(source->output, false); + if (source->software_cursors_locked) { + wlr_output_lock_software_cursors(source->output, false); + } +} + +static void output_source_request_frame(struct wlr_ext_image_capture_source_v1 *base, + bool schedule_frame) { + struct wlr_ext_output_image_capture_source_v1 *source = wl_container_of(base, source, base); + if (schedule_frame) { + wlr_output_update_needs_frame(source->output); + } +} + +static void output_source_copy_frame(struct wlr_ext_image_capture_source_v1 *base, + struct wlr_ext_image_copy_capture_frame_v1 *frame, + struct wlr_ext_image_capture_source_v1_frame_event *base_event) { + struct wlr_ext_output_image_capture_source_v1 *source = wl_container_of(base, source, base); + struct wlr_ext_output_image_capture_source_v1_frame_event *event = + wl_container_of(base_event, event, base); + + if (wlr_ext_image_copy_capture_frame_v1_copy_buffer(frame, + event->buffer, source->output->renderer)) { + wlr_ext_image_copy_capture_frame_v1_ready(frame, + source->output->transform, &event->when); + } +} + +static struct wlr_ext_image_capture_source_v1_cursor *output_source_get_pointer_cursor( + struct wlr_ext_image_capture_source_v1 *base, struct wlr_seat *seat) { + // TODO: handle seat + struct wlr_ext_output_image_capture_source_v1 *source = wl_container_of(base, source, base); + return &source->cursor.base; +} + +static const struct wlr_ext_image_capture_source_v1_interface output_source_impl = { + .start = output_source_start, + .stop = output_source_stop, + .request_frame = output_source_request_frame, + .copy_frame = output_source_copy_frame, + .get_pointer_cursor = output_source_get_pointer_cursor, +}; + +static void source_update_buffer_constraints(struct wlr_ext_output_image_capture_source_v1 *source) { + struct wlr_output *output = source->output; + + if (!output->enabled) { + return; + } + + if (!wlr_output_configure_primary_swapchain(output, NULL, &output->swapchain)) { + return; + } + + wlr_ext_image_capture_source_v1_set_constraints_from_swapchain(&source->base, + output->swapchain, output->renderer); +} + +static void source_handle_output_commit(struct wl_listener *listener, + void *data) { + struct wlr_ext_output_image_capture_source_v1 *source = wl_container_of(listener, source, output_commit); + struct wlr_output_event_commit *event = data; + + if (event->state->committed & (WLR_OUTPUT_STATE_MODE | + WLR_OUTPUT_STATE_RENDER_FORMAT | WLR_OUTPUT_STATE_ENABLED)) { + source_update_buffer_constraints(source); + } + + if (event->state->committed & WLR_OUTPUT_STATE_BUFFER) { + struct wlr_buffer *buffer = event->state->buffer; + + pixman_region32_t full_damage; + pixman_region32_init_rect(&full_damage, 0, 0, buffer->width, buffer->height); + + const pixman_region32_t *damage; + if (event->state->committed & WLR_OUTPUT_STATE_DAMAGE) { + damage = &event->state->damage; + } else { + damage = &full_damage; + } + + struct wlr_ext_output_image_capture_source_v1_frame_event frame_event = { + .base = { + .damage = damage, + }, + .buffer = buffer, + .when = event->when, // TODO: predict next presentation time instead + }; + wl_signal_emit_mutable(&source->base.events.frame, &frame_event); + + pixman_region32_fini(&full_damage); + } +} + +static void output_cursor_source_init(struct output_cursor_source *cursor_source, + struct wlr_output *output); +static void output_cursor_source_finish(struct output_cursor_source *cursor_source); + +static void output_addon_destroy(struct wlr_addon *addon) { + struct wlr_ext_output_image_capture_source_v1 *source = wl_container_of(addon, source, addon); + wlr_ext_image_capture_source_v1_finish(&source->base); + output_cursor_source_finish(&source->cursor); + wl_list_remove(&source->output_commit.link); + wlr_addon_finish(&source->addon); + free(source); +} + +static const struct wlr_addon_interface output_addon_impl = { + .name = "wlr_ext_output_image_capture_source_v1", + .destroy = output_addon_destroy, +}; + +static void output_manager_handle_create_source(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t new_id, + struct wl_resource *output_resource) { + struct wlr_output *output = wlr_output_from_resource(output_resource); + if (output == NULL) { + wlr_ext_image_capture_source_v1_create_resource(NULL, client, new_id); + return; + } + + struct wlr_ext_output_image_capture_source_v1 *source; + struct wlr_addon *addon = wlr_addon_find(&output->addons, NULL, &output_addon_impl); + if (addon != NULL) { + source = wl_container_of(addon, source, addon); + } else { + source = calloc(1, sizeof(*source)); + if (source == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + + wlr_ext_image_capture_source_v1_init(&source->base, &output_source_impl); + wlr_addon_init(&source->addon, &output->addons, NULL, &output_addon_impl); + source->output = output; + + source->output_commit.notify = source_handle_output_commit; + wl_signal_add(&output->events.commit, &source->output_commit); + + source_update_buffer_constraints(source); + + output_cursor_source_init(&source->cursor, output); + } + + if (!wlr_ext_image_capture_source_v1_create_resource(&source->base, client, new_id)) { + return; + } +} + +static void output_manager_handle_destroy(struct wl_client *client, + struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static const struct ext_output_image_capture_source_manager_v1_interface output_manager_impl = { + .create_source = output_manager_handle_create_source, + .destroy = output_manager_handle_destroy, +}; + +static void output_manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_ext_output_image_capture_source_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &ext_output_image_capture_source_manager_v1_interface, version, id); + if (!resource) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &output_manager_impl, manager, NULL); +} + +static void ext_output_image_capture_source_manager_v1_destroy( + struct wlr_ext_output_image_capture_source_manager_v1 *manager, + bool destroy_global_safe) { + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_ext_output_image_capture_source_manager_v1_destroy( + struct wlr_ext_output_image_capture_source_manager_v1 *manager, bool destroy_global_safe) { + ext_output_image_capture_source_manager_v1_destroy(manager, destroy_global_safe); +} + +static void output_manager_handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_ext_output_image_capture_source_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + ext_output_image_capture_source_manager_v1_destroy(manager, false); +} + +struct wlr_ext_output_image_capture_source_manager_v1 *wlr_ext_output_image_capture_source_manager_v1_create( + struct wl_display *display, uint32_t version) { + assert(version <= OUTPUT_IMAGE_SOURCE_MANAGER_V1_VERSION); + + struct wlr_ext_output_image_capture_source_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + manager->global = wl_global_create(display, + &ext_output_image_capture_source_manager_v1_interface, version, manager, output_manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + manager->display_destroy.notify = output_manager_handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} + +static void output_cursor_source_request_frame(struct wlr_ext_image_capture_source_v1 *base, + bool schedule_frame) { + struct output_cursor_source *cursor_source = wl_container_of(base, cursor_source, base); + if (schedule_frame) { + wlr_output_update_needs_frame(cursor_source->output); + cursor_source->needs_frame = true; + } +} + +static void output_cursor_source_copy_frame(struct wlr_ext_image_capture_source_v1 *base, + struct wlr_ext_image_copy_capture_frame_v1 *frame, + struct wlr_ext_image_capture_source_v1_frame_event *base_event) { + struct output_cursor_source *cursor_source = wl_container_of(base, cursor_source, base); + + struct wlr_buffer *src_buffer = cursor_source->output->cursor_front_buffer; + if (src_buffer == NULL) { + wlr_ext_image_copy_capture_frame_v1_fail(frame, EXT_IMAGE_COPY_CAPTURE_FRAME_V1_FAILURE_REASON_STOPPED); + return; + } + + if (!wlr_ext_image_copy_capture_frame_v1_copy_buffer(frame, + src_buffer, cursor_source->output->renderer)) { + return; + } + + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + + wlr_ext_image_copy_capture_frame_v1_ready(frame, + cursor_source->output->transform, &now); +} + +static const struct wlr_ext_image_capture_source_v1_interface output_cursor_source_impl = { + .request_frame = output_cursor_source_request_frame, + .copy_frame = output_cursor_source_copy_frame, +}; + +static void output_cursor_source_update(struct output_cursor_source *cursor_source) { + struct wlr_output *output = cursor_source->output; + + if (output->cursor_swapchain != NULL && !cursor_source->initialized) { + wlr_ext_image_capture_source_v1_set_constraints_from_swapchain(&cursor_source->base.base, + output->cursor_swapchain, output->renderer); + cursor_source->initialized = true; + } + + struct wlr_output_cursor *output_cursor = output->hardware_cursor; + if (output_cursor == NULL || !output_cursor->visible) { + cursor_source->base.entered = false; + wl_signal_emit_mutable(&cursor_source->base.events.update, NULL); + return; + } + + if (output->cursor_swapchain != NULL && + ((int)cursor_source->base.base.width != output->cursor_swapchain->width || + (int)cursor_source->base.base.height != output->cursor_swapchain->height)) { + cursor_source->base.base.width = output->cursor_swapchain->width; + cursor_source->base.base.height = output->cursor_swapchain->height; + wl_signal_emit_mutable(&cursor_source->base.base.events.constraints_update, NULL); + } + + cursor_source->base.entered = true; + cursor_source->base.x = round(output_cursor->x); + cursor_source->base.y = round(output_cursor->y); + cursor_source->base.hotspot.x = output_cursor->hotspot_x; + cursor_source->base.hotspot.y = output_cursor->hotspot_y; + wl_signal_emit_mutable(&cursor_source->base.events.update, NULL); +} + +static void output_cursor_source_handle_prev_buffer_release(struct wl_listener *listener, + void *data) { + struct output_cursor_source *cursor_source = wl_container_of(listener, cursor_source, prev_buffer_release); + wl_list_remove(&cursor_source->prev_buffer_release.link); + wl_list_init(&cursor_source->prev_buffer_release.link); + cursor_source->prev_buffer = NULL; +} + +static void output_cursor_source_handle_output_commit(struct wl_listener *listener, + void *data) { + struct output_cursor_source *cursor_source = wl_container_of(listener, cursor_source, output_commit); + struct wlr_output_event_commit *event = data; + + output_cursor_source_update(cursor_source); + + struct wlr_buffer *buffer = cursor_source->output->cursor_front_buffer; + if (buffer != NULL && (buffer != cursor_source->prev_buffer || cursor_source->needs_frame)) { + pixman_region32_t full_damage; + pixman_region32_init_rect(&full_damage, 0, 0, buffer->width, buffer->height); + + struct wlr_ext_output_image_capture_source_v1_frame_event frame_event = { + .base = { + .damage = &full_damage, + }, + .buffer = buffer, + .when = event->when, // TODO: predict next presentation time instead + }; + wl_signal_emit_mutable(&cursor_source->base.base.events.frame, &frame_event); + + pixman_region32_fini(&full_damage); + + assert(buffer->n_locks > 0); + cursor_source->prev_buffer = buffer; + wl_list_remove(&cursor_source->prev_buffer_release.link); + cursor_source->prev_buffer_release.notify = output_cursor_source_handle_prev_buffer_release; + wl_signal_add(&buffer->events.release, &cursor_source->prev_buffer_release); + } + + cursor_source->needs_frame = false; +} + +static void output_cursor_source_init(struct output_cursor_source *cursor_source, + struct wlr_output *output) { + wlr_ext_image_capture_source_v1_cursor_init(&cursor_source->base, &output_cursor_source_impl); + + // Caller is responsible for destroying the output cursor source when the + // output is destroyed + cursor_source->output = output; + + cursor_source->output_commit.notify = output_cursor_source_handle_output_commit; + wl_signal_add(&output->events.commit, &cursor_source->output_commit); + + wl_list_init(&cursor_source->prev_buffer_release.link); + + output_cursor_source_update(cursor_source); +} + +static void output_cursor_source_finish(struct output_cursor_source *cursor_source) { + wlr_ext_image_capture_source_v1_cursor_finish(&cursor_source->base); + wl_list_remove(&cursor_source->output_commit.link); + wl_list_remove(&cursor_source->prev_buffer_release.link); +} + +struct wlr_output *wlr_output_try_from_ext_image_capture_source_v1(struct wlr_ext_image_capture_source_v1 *source) { + if (source->impl == &output_source_impl) { + struct wlr_ext_output_image_capture_source_v1 *output_source = + (struct wlr_ext_output_image_capture_source_v1*)source; + return output_source->output; + } + + return NULL; +} diff --git a/3rdparty/wlroots/types/ext_image_capture_source_v1/scene.c b/3rdparty/wlroots/types/ext_image_capture_source_v1/scene.c new file mode 100644 index 0000000000..7d4b8928ae --- /dev/null +++ b/3rdparty/wlroots/types/ext_image_capture_source_v1/scene.c @@ -0,0 +1,337 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "types/wlr_output.h" +#include "types/wlr_scene.h" + +struct scene_node_source { + struct wlr_ext_image_capture_source_v1 base; + + struct wlr_scene_node *node; + + struct wlr_backend backend; + struct wlr_output output; + struct wlr_scene_output *scene_output; + + size_t num_started; + + struct wl_listener node_destroy; + struct wl_listener scene_output_destroy; + struct wl_listener output_frame; +}; + +struct scene_node_source_frame_event { + struct wlr_ext_image_capture_source_v1_frame_event base; + struct wlr_buffer *buffer; + struct timespec when; +}; + +static size_t last_output_num = 0; + +static void _get_scene_node_extents(struct wlr_scene_node *node, int lx, int ly, + int *x_min, int *y_min, int *x_max, int *y_max) { + switch (node->type) { + case WLR_SCENE_NODE_TREE:; + struct wlr_scene_tree *scene_tree = wlr_scene_tree_from_node(node); + struct wlr_scene_node *child; + wl_list_for_each(child, &scene_tree->children, link) { + _get_scene_node_extents(child, lx + child->x, ly + child->y, x_min, y_min, x_max, y_max); + } + break; + case WLR_SCENE_NODE_RECT: + case WLR_SCENE_NODE_BUFFER:; + struct wlr_box node_box = { .x = lx, .y = ly }; + scene_node_get_size(node, &node_box.width, &node_box.height); + + if (node_box.x < *x_min) { + *x_min = node_box.x; + } + if (node_box.y < *y_min) { + *y_min = node_box.y; + } + if (node_box.x + node_box.width > *x_max) { + *x_max = node_box.x + node_box.width; + } + if (node_box.y + node_box.height > *y_max) { + *y_max = node_box.y + node_box.height; + } + break; + } +} + +static void get_scene_node_extents(struct wlr_scene_node *node, struct wlr_box *box) { + int lx = 0, ly = 0; + wlr_scene_node_coords(node, &lx, &ly); + *box = (struct wlr_box){ .x = INT_MAX, .y = INT_MAX }; + int x_max = INT_MIN, y_max = INT_MIN; + _get_scene_node_extents(node, lx, ly, &box->x, &box->y, &x_max, &y_max); + box->width = x_max - box->x; + box->height = y_max - box->y; +} + +static void source_render(struct scene_node_source *source) { + struct wlr_scene_output *scene_output = source->scene_output; + + struct wlr_box extents; + get_scene_node_extents(source->node, &extents); + + if (extents.width == 0 || extents.height == 0) { + return; + } + + wlr_scene_output_set_position(scene_output, extents.x, extents.y); + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, true); + wlr_output_state_set_custom_mode(&state, extents.width, extents.height, 0); + bool ok = wlr_scene_output_build_state(scene_output, &state, NULL) && + wlr_output_commit_state(scene_output->output, &state); + wlr_output_state_finish(&state); + + if (!ok) { + // TODO: send failure + return; + } +} + +static void source_start(struct wlr_ext_image_capture_source_v1 *base, bool with_cursors) { + struct scene_node_source *source = wl_container_of(base, source, base); + + source->num_started++; + if (source->num_started > 1) { + return; + } + + source_render(source); + + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + wlr_scene_output_send_frame_done(source->scene_output, &now); +} + +static void source_stop(struct wlr_ext_image_capture_source_v1 *base) { + struct scene_node_source *source = wl_container_of(base, source, base); + + source->num_started--; + if (source->num_started > 0) { + return; + } + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, false); + wlr_output_commit_state(&source->output, &state); + wlr_output_state_finish(&state); +} + +static void source_request_frame(struct wlr_ext_image_capture_source_v1 *base, + bool schedule_frame) { + struct scene_node_source *source = wl_container_of(base, source, base); + if (source->output.frame_pending) { + wlr_output_send_frame(&source->output); + } + if (schedule_frame) { + wlr_output_update_needs_frame(&source->output); + } +} + +static void source_copy_frame(struct wlr_ext_image_capture_source_v1 *base, + struct wlr_ext_image_copy_capture_frame_v1 *frame, + struct wlr_ext_image_capture_source_v1_frame_event *base_event) { + struct scene_node_source *source = wl_container_of(base, source, base); + struct scene_node_source_frame_event *event = wl_container_of(base_event, event, base); + + if (wlr_ext_image_copy_capture_frame_v1_copy_buffer(frame, + event->buffer, source->output.renderer)) { + wlr_ext_image_copy_capture_frame_v1_ready(frame, + source->output.transform, &event->when); + } +} + +static const struct wlr_ext_image_capture_source_v1_interface source_impl = { + .start = source_start, + .stop = source_stop, + .request_frame = source_request_frame, + .copy_frame = source_copy_frame, +}; + +static const struct wlr_backend_impl backend_impl = {0}; + +static void source_update_buffer_constraints(struct scene_node_source *source, + const struct wlr_output_state *state) { + struct wlr_output *output = &source->output; + + if (!wlr_output_configure_primary_swapchain(output, state, &output->swapchain)) { + return; + } + + wlr_ext_image_capture_source_v1_set_constraints_from_swapchain(&source->base, + output->swapchain, output->renderer); +} + +static bool output_test(struct wlr_output *output, const struct wlr_output_state *state) { + uint32_t supported = + WLR_OUTPUT_STATE_BACKEND_OPTIONAL | + WLR_OUTPUT_STATE_BUFFER | + WLR_OUTPUT_STATE_ENABLED | + WLR_OUTPUT_STATE_MODE; + if ((state->committed & ~supported) != 0) { + return false; + } + + if (state->committed & WLR_OUTPUT_STATE_BUFFER) { + int pending_width, pending_height; + output_pending_resolution(output, state, + &pending_width, &pending_height); + if (state->buffer->width != pending_width || + state->buffer->height != pending_height) { + return false; + } + struct wlr_fbox src_box; + output_state_get_buffer_src_box(state, &src_box); + if (src_box.x != 0.0 || src_box.y != 0.0 || + src_box.width != (double)state->buffer->width || + src_box.height != (double)state->buffer->height) { + return false; + } + } + + return true; +} + +static bool output_commit(struct wlr_output *output, const struct wlr_output_state *state) { + struct scene_node_source *source = wl_container_of(output, source, output); + + if ((state->committed & WLR_OUTPUT_STATE_ENABLED) && !state->enabled) { + return true; + } + + if (state->committed & WLR_OUTPUT_STATE_MODE) { + source_update_buffer_constraints(source, state); + } + + if (!(state->committed & WLR_OUTPUT_STATE_BUFFER)) { + wlr_log(WLR_DEBUG, "Failed to commit capture output: missing buffer"); + return false; + } + + struct wlr_buffer *buffer = state->buffer; + + pixman_region32_t full_damage; + pixman_region32_init_rect(&full_damage, 0, 0, buffer->width, buffer->height); + + const pixman_region32_t *damage; + if (state->committed & WLR_OUTPUT_STATE_DAMAGE) { + damage = &state->damage; + } else { + damage = &full_damage; + } + + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + + struct scene_node_source_frame_event frame_event = { + .base = { .damage = damage }, + .buffer = buffer, + .when = now, + }; + wl_signal_emit_mutable(&source->base.events.frame, &frame_event.base); + + pixman_region32_fini(&full_damage); + + return true; +} + +static const struct wlr_output_impl output_impl = { + .test = output_test, + .commit = output_commit, +}; + +static void source_destroy(struct scene_node_source *source) { + wl_list_remove(&source->node_destroy.link); + wl_list_remove(&source->scene_output_destroy.link); + wl_list_remove(&source->output_frame.link); + wlr_ext_image_capture_source_v1_finish(&source->base); + wlr_scene_output_destroy(source->scene_output); + wlr_output_finish(&source->output); + wlr_backend_finish(&source->backend); + free(source); +} + +static void source_handle_node_destroy(struct wl_listener *listener, void *data) { + struct scene_node_source *source = wl_container_of(listener, source, node_destroy); + source_destroy(source); +} + +static void source_handle_scene_output_destroy(struct wl_listener *listener, void *data) { + struct scene_node_source *source = wl_container_of(listener, source, scene_output_destroy); + source->scene_output = NULL; + wl_list_remove(&source->scene_output_destroy.link); + wl_list_init(&source->scene_output_destroy.link); +} + +static void source_handle_output_frame(struct wl_listener *listener, void *data) { + struct scene_node_source *source = wl_container_of(listener, source, output_frame); + if (source->scene_output == NULL) { + return; + } + + if (!wlr_scene_output_needs_frame(source->scene_output)) { + return; + } + + // We can only emit frames with damage + if (!pixman_region32_empty(&source->scene_output->pending_commit_damage)) { + source_render(source); + } + + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + wlr_scene_output_send_frame_done(source->scene_output, &now); +} + +struct wlr_ext_image_capture_source_v1 *wlr_ext_image_capture_source_v1_create_with_scene_node( + struct wlr_scene_node *node, struct wl_event_loop *event_loop, + struct wlr_allocator *allocator, struct wlr_renderer *renderer) { + struct scene_node_source *source = calloc(1, sizeof(*source)); + if (source == NULL) { + return NULL; + } + + source->node = node; + + wlr_ext_image_capture_source_v1_init(&source->base, &source_impl); + + wlr_backend_init(&source->backend, &backend_impl); + source->backend.buffer_caps = WLR_BUFFER_CAP_DMABUF | WLR_BUFFER_CAP_SHM; + + wlr_output_init(&source->output, &source->backend, &output_impl, event_loop, NULL); + + size_t output_num = ++last_output_num; + char name[64]; + snprintf(name, sizeof(name), "CAPTURE-%zu", output_num); + wlr_output_set_name(&source->output, name); + + wlr_output_init_render(&source->output, allocator, renderer); + + struct wlr_scene *scene = scene_node_get_root(node); + source->scene_output = wlr_scene_output_create(scene, &source->output); + + source->node_destroy.notify = source_handle_node_destroy; + wl_signal_add(&node->events.destroy, &source->node_destroy); + + source->scene_output_destroy.notify = source_handle_scene_output_destroy; + wl_signal_add(&source->scene_output->events.destroy, &source->scene_output_destroy); + + source->output_frame.notify = source_handle_output_frame; + wl_signal_add(&source->output.events.frame, &source->output_frame); + + return &source->base; +} diff --git a/3rdparty/wlroots/types/meson.build b/3rdparty/wlroots/types/meson.build new file mode 100644 index 0000000000..26958f048d --- /dev/null +++ b/3rdparty/wlroots/types/meson.build @@ -0,0 +1,116 @@ +wlr_files += files( + 'data_device/wlr_data_device.c', + 'data_device/wlr_data_offer.c', + 'data_device/wlr_data_source.c', + 'data_device/wlr_drag.c', + 'ext_image_capture_source_v1/base.c', + 'ext_image_capture_source_v1/output.c', + 'ext_image_capture_source_v1/foreign_toplevel.c', + 'ext_image_capture_source_v1/scene.c', + 'output/cursor.c', + 'output/output.c', + 'output/render.c', + 'output/state.c', + 'output/swapchain.c', + 'scene/drag_icon.c', + 'scene/subsurface_tree.c', + 'scene/surface.c', + 'scene/wlr_scene.c', + 'scene/output_layout.c', + 'scene/xdg_shell.c', + 'scene/layer_shell_v1.c', + 'seat/wlr_seat_keyboard.c', + 'seat/wlr_seat_pointer.c', + 'seat/wlr_seat_touch.c', + 'seat/wlr_seat.c', + 'tablet_v2/wlr_tablet_v2_pad.c', + 'tablet_v2/wlr_tablet_v2_tablet.c', + 'tablet_v2/wlr_tablet_v2_tool.c', + 'tablet_v2/wlr_tablet_v2.c', + 'xdg_shell/wlr_xdg_popup.c', + 'xdg_shell/wlr_xdg_positioner.c', + 'xdg_shell/wlr_xdg_shell.c', + 'xdg_shell/wlr_xdg_surface.c', + 'xdg_shell/wlr_xdg_toplevel.c', + 'buffer/buffer.c', + 'buffer/client.c', + 'buffer/dmabuf.c', + 'buffer/readonly_data.c', + 'buffer/resource.c', + 'wlr_alpha_modifier_v1.c', + 'wlr_color_management_v1.c', + 'wlr_color_representation_v1.c', + 'wlr_compositor.c', + 'wlr_content_type_v1.c', + 'wlr_cursor.c', + 'wlr_cursor_shape_v1.c', + 'wlr_damage_ring.c', + 'wlr_data_control_v1.c', + 'wlr_drm.c', + 'wlr_export_dmabuf_v1.c', + 'wlr_ext_data_control_v1.c', + 'wlr_ext_foreign_toplevel_list_v1.c', + 'wlr_ext_image_copy_capture_v1.c', + 'wlr_ext_workspace_v1.c', + 'wlr_fixes.c', + 'wlr_foreign_toplevel_management_v1.c', + 'wlr_fractional_scale_v1.c', + 'wlr_gamma_control_v1.c', + 'wlr_idle_inhibit_v1.c', + 'wlr_idle_notify_v1.c', + 'wlr_input_device.c', + 'wlr_input_method_v2.c', + 'wlr_keyboard.c', + 'wlr_keyboard_group.c', + 'wlr_keyboard_shortcuts_inhibit_v1.c', + 'wlr_layer_shell_v1.c', + 'wlr_linux_dmabuf_v1.c', + 'wlr_linux_drm_syncobj_v1.c', + 'wlr_output_layer.c', + 'wlr_output_layout.c', + 'wlr_output_management_v1.c', + 'wlr_output_power_management_v1.c', + 'wlr_output_swapchain_manager.c', + 'wlr_pointer_constraints_v1.c', + 'wlr_pointer_gestures_v1.c', + 'wlr_pointer.c', + 'wlr_presentation_time.c', + 'wlr_primary_selection_v1.c', + 'wlr_primary_selection.c', + 'wlr_region.c', + 'wlr_relative_pointer_v1.c', + 'wlr_screencopy_v1.c', + 'wlr_security_context_v1.c', + 'wlr_server_decoration.c', + 'wlr_session_lock_v1.c', + 'wlr_shm.c', + 'wlr_single_pixel_buffer_v1.c', + 'wlr_subcompositor.c', + 'wlr_switch.c', + 'wlr_tablet_pad.c', + 'wlr_tablet_tool.c', + 'wlr_tearing_control_v1.c', + 'wlr_text_input_v3.c', + 'wlr_touch.c', + 'wlr_transient_seat_v1.c', + 'wlr_viewporter.c', + 'wlr_virtual_keyboard_v1.c', + 'wlr_virtual_pointer_v1.c', + 'wlr_xcursor_manager.c', + 'wlr_xdg_activation_v1.c', + 'wlr_xdg_decoration_v1.c', + 'wlr_xdg_dialog_v1.c', + 'wlr_xdg_foreign_v1.c', + 'wlr_xdg_foreign_v2.c', + 'wlr_xdg_foreign_registry.c', + 'wlr_xdg_output_v1.c', + 'wlr_xdg_system_bell_v1.c', + 'wlr_xdg_toplevel_icon_v1.c', + 'wlr_xdg_toplevel_tag_v1.c', +) + +if features.get('drm-backend') + wlr_files += files( + 'wlr_drm_lease_v1.c', + ) +endif diff --git a/3rdparty/wlroots/types/output/cursor.c b/3rdparty/wlroots/types/output/cursor.c new file mode 100644 index 0000000000..5e93b0b2e0 --- /dev/null +++ b/3rdparty/wlroots/types/output/cursor.c @@ -0,0 +1,538 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "render/color.h" +#include "types/wlr_buffer.h" +#include "types/wlr_output.h" + +static bool output_set_hardware_cursor(struct wlr_output *output, + struct wlr_buffer *buffer, int hotspot_x, int hotspot_y) { + if (!output->impl->set_cursor) { + return false; + } + + if (!output->impl->set_cursor(output, buffer, hotspot_x, hotspot_y)) { + return false; + } + + wlr_output_update_needs_frame(output); + + wlr_buffer_unlock(output->cursor_front_buffer); + output->cursor_front_buffer = NULL; + + if (buffer != NULL) { + output->cursor_front_buffer = wlr_buffer_lock(buffer); + } + + return true; +} + +static bool output_move_hardware_cursor(struct wlr_output *output, int x, int y) { + assert(output->impl->move_cursor); + if (!output->impl->move_cursor(output, x, y)) { + return false; + } + wlr_output_update_needs_frame(output); + return true; +} + +static void output_cursor_damage_whole(struct wlr_output_cursor *cursor); + +static void output_disable_hardware_cursor(struct wlr_output *output) { + if (output->hardware_cursor == NULL) { + return; + } + + output_set_hardware_cursor(output, NULL, 0, 0); + output_cursor_damage_whole(output->hardware_cursor); + output->hardware_cursor = NULL; +} + +void wlr_output_lock_software_cursors(struct wlr_output *output, bool lock) { + if (lock) { + ++output->software_cursor_locks; + } else { + assert(output->software_cursor_locks > 0); + --output->software_cursor_locks; + } + wlr_log(WLR_DEBUG, "%s hardware cursors on output '%s' (locks: %d)", + lock ? "Disabling" : "Enabling", output->name, + output->software_cursor_locks); + + if (output->software_cursor_locks > 0) { + output_disable_hardware_cursor(output); + } + + // If it's possible to use hardware cursors again, don't switch immediately + // since a recorder is likely to lock software cursors for the next frame + // again. +} + +/** + * Returns the cursor box, scaled for its output. + */ +static void output_cursor_get_box(struct wlr_output_cursor *cursor, + struct wlr_box *box) { + box->x = cursor->x - cursor->hotspot_x; + box->y = cursor->y - cursor->hotspot_y; + box->width = cursor->width; + box->height = cursor->height; +} + +void wlr_output_add_software_cursors_to_render_pass(struct wlr_output *output, + struct wlr_render_pass *render_pass, const pixman_region32_t *damage) { + int width, height; + wlr_output_transformed_resolution(output, &width, &height); + + struct wlr_output_cursor *cursor; + wl_list_for_each(cursor, &output->cursors, link) { + if (!cursor->enabled || !cursor->visible || + output->hardware_cursor == cursor) { + continue; + } + + struct wlr_texture *texture = cursor->texture; + if (texture == NULL) { + continue; + } + + struct wlr_box box; + output_cursor_get_box(cursor, &box); + wlr_box_transform(&box, &box, + wlr_output_transform_invert(output->transform), width, height); + + pixman_region32_t cursor_damage; + pixman_region32_init_rect(&cursor_damage, + box.x, box.y, box.width, box.height); + if (damage != NULL) { + pixman_region32_intersect(&cursor_damage, &cursor_damage, damage); + } + + if (pixman_region32_empty(&cursor_damage)) { + pixman_region32_fini(&cursor_damage); + continue; + } + + wlr_render_pass_add_texture(render_pass, &(struct wlr_render_texture_options) { + .texture = texture, + .src_box = cursor->src_box, + .dst_box = box, + .clip = &cursor_damage, + .transform = output->transform, + }); + + pixman_region32_fini(&cursor_damage); + } +} + +static void output_cursor_damage_whole(struct wlr_output_cursor *cursor) { + struct wlr_box box; + output_cursor_get_box(cursor, &box); + + pixman_region32_t damage; + pixman_region32_init_rect(&damage, box.x, box.y, box.width, box.height); + + struct wlr_output_event_damage event = { + .output = cursor->output, + .damage = &damage, + }; + wl_signal_emit_mutable(&cursor->output->events.damage, &event); + + pixman_region32_fini(&damage); +} + +static void output_cursor_update_visible(struct wlr_output_cursor *cursor) { + struct wlr_box output_box; + output_box.x = output_box.y = 0; + wlr_output_transformed_resolution(cursor->output, &output_box.width, + &output_box.height); + + struct wlr_box cursor_box; + output_cursor_get_box(cursor, &cursor_box); + + struct wlr_box intersection; + cursor->visible = + wlr_box_intersection(&intersection, &output_box, &cursor_box); +} + +static bool output_pick_cursor_format(struct wlr_output *output, + struct wlr_drm_format *format) { + struct wlr_allocator *allocator = output->allocator; + assert(allocator != NULL); + + const struct wlr_drm_format_set *display_formats = NULL; + if (output->impl->get_cursor_formats) { + display_formats = + output->impl->get_cursor_formats(output, allocator->buffer_caps); + if (display_formats == NULL) { + wlr_log(WLR_DEBUG, "Failed to get cursor display formats"); + return false; + } + } + + return output_pick_format(output, display_formats, format, DRM_FORMAT_ARGB8888); +} + +static struct wlr_buffer *render_cursor_buffer(struct wlr_output_cursor *cursor) { + struct wlr_output *output = cursor->output; + + struct wlr_texture *texture = cursor->texture; + if (texture == NULL) { + return NULL; + } + + struct wlr_allocator *allocator = output->allocator; + struct wlr_renderer *renderer = output->renderer; + assert(allocator != NULL && renderer != NULL); + + int width = cursor->width; + int height = cursor->height; + if (output->impl->get_cursor_sizes) { + // Apply hardware limitations on buffer size + size_t sizes_len = 0; + const struct wlr_output_cursor_size *sizes = + output->impl->get_cursor_sizes(cursor->output, &sizes_len); + if (sizes_len == 0) { + wlr_log(WLR_DEBUG, "Hardware cursor not supported"); + return NULL; + } + + bool found = false; + for (size_t i = 0; i < sizes_len; i++) { + struct wlr_output_cursor_size size = sizes[i]; + if ((int)texture->width <= size.width && (int)texture->height <= size.height) { + width = size.width; + height = size.height; + found = true; + break; + } + } + + if (!found) { + wlr_log(WLR_DEBUG, "Cursor texture too large (%dx%d), " + "exceeds hardware limitations", texture->width, + texture->height); + return NULL; + } + } + + if (output->cursor_swapchain == NULL || + output->cursor_swapchain->width != width || + output->cursor_swapchain->height != height) { + struct wlr_drm_format format = {0}; + if (!output_pick_cursor_format(output, &format)) { + wlr_log(WLR_DEBUG, "Failed to pick cursor format"); + return NULL; + } + + wlr_swapchain_destroy(output->cursor_swapchain); + output->cursor_swapchain = wlr_swapchain_create(allocator, + width, height, &format); + wlr_drm_format_finish(&format); + if (output->cursor_swapchain == NULL) { + wlr_log(WLR_ERROR, "Failed to create cursor swapchain"); + return NULL; + } + } + + struct wlr_buffer *buffer = wlr_swapchain_acquire(output->cursor_swapchain); + if (buffer == NULL) { + return NULL; + } + + struct wlr_box dst_box = { + .width = cursor->width, + .height = cursor->height, + }; + wlr_box_transform(&dst_box, &dst_box, wlr_output_transform_invert(output->transform), + buffer->width, buffer->height); + + struct wlr_buffer_pass_options options = { + .color_transform = cursor->color_transform, + }; + struct wlr_render_pass *pass = wlr_renderer_begin_buffer_pass(renderer, buffer, &options); + if (pass == NULL) { + wlr_buffer_unlock(buffer); + return NULL; + } + + enum wl_output_transform transform = wlr_output_transform_invert(cursor->transform); + transform = wlr_output_transform_compose(transform, output->transform); + + wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){ + .box = { .width = buffer->width, .height = buffer->height }, + .blend_mode = WLR_RENDER_BLEND_MODE_NONE, + }); + wlr_render_pass_add_texture(pass, &(struct wlr_render_texture_options){ + .texture = texture, + .src_box = cursor->src_box, + .dst_box = dst_box, + .transform = transform, + .wait_timeline = cursor->wait_timeline, + .wait_point = cursor->wait_point, + }); + + if (!wlr_render_pass_submit(pass)) { + wlr_buffer_unlock(buffer); + return NULL; + } + + return buffer; +} + +static bool output_cursor_attempt_hardware(struct wlr_output_cursor *cursor) { + struct wlr_output *output = cursor->output; + + if (!output->impl->set_cursor || output->software_cursor_locks > 0) { + return false; + } + + struct wlr_texture *texture = cursor->texture; + + // If the cursor was hidden or was a software cursor, the hardware + // cursor position is outdated + output_move_hardware_cursor(cursor->output, (int)cursor->x, (int)cursor->y); + + struct wlr_buffer *buffer = NULL; + if (texture != NULL) { + buffer = render_cursor_buffer(cursor); + if (buffer == NULL) { + wlr_log(WLR_DEBUG, "Failed to render cursor buffer"); + return false; + } + } + + struct wlr_box hotspot = { + .x = cursor->hotspot_x, + .y = cursor->hotspot_y, + }; + wlr_box_transform(&hotspot, &hotspot, + wlr_output_transform_invert(output->transform), + buffer ? buffer->width : 0, buffer ? buffer->height : 0); + + bool ok = output_set_hardware_cursor(output, buffer, hotspot.x, hotspot.y); + wlr_buffer_unlock(buffer); + if (ok) { + output->hardware_cursor = cursor; + } + return ok; +} + +bool wlr_output_cursor_set_buffer(struct wlr_output_cursor *cursor, + struct wlr_buffer *buffer, int32_t hotspot_x, int32_t hotspot_y) { + struct wlr_renderer *renderer = cursor->output->renderer; + assert(renderer != NULL); + + struct wlr_texture *texture = NULL; + struct wlr_fbox src_box = {0}; + int dst_width = 0, dst_height = 0; + if (buffer != NULL) { + texture = wlr_texture_from_buffer(renderer, buffer); + if (texture == NULL) { + return false; + } + + src_box = (struct wlr_fbox){ + .width = texture->width, + .height = texture->height, + }; + + dst_width = texture->width / cursor->output->scale; + dst_height = texture->height / cursor->output->scale; + } + + hotspot_x /= cursor->output->scale; + hotspot_y /= cursor->output->scale; + + return output_cursor_set_texture(cursor, texture, true, &src_box, + dst_width, dst_height, WL_OUTPUT_TRANSFORM_NORMAL, hotspot_x, hotspot_y, + NULL, 0); +} + +static void output_cursor_handle_renderer_destroy(struct wl_listener *listener, + void *data) { + struct wlr_output_cursor *cursor = wl_container_of(listener, cursor, renderer_destroy); + output_cursor_set_texture(cursor, NULL, false, NULL, 0, 0, + WL_OUTPUT_TRANSFORM_NORMAL, 0, 0, NULL, 0); +} + +bool output_cursor_set_texture(struct wlr_output_cursor *cursor, + struct wlr_texture *texture, bool own_texture, const struct wlr_fbox *src_box, + int dst_width, int dst_height, enum wl_output_transform transform, + int32_t hotspot_x, int32_t hotspot_y, + struct wlr_drm_syncobj_timeline *wait_timeline, uint64_t wait_point) { + if (texture == NULL && !cursor->enabled) { + // Cursor is still disabled, do nothing + return true; + } + + struct wlr_output *output = cursor->output; + + if (cursor->output->hardware_cursor != cursor) { + output_cursor_damage_whole(cursor); + } + + cursor->enabled = texture != NULL; + if (texture != NULL) { + cursor->width = (int)roundf(dst_width * output->scale); + cursor->height = (int)roundf(dst_height * output->scale); + cursor->src_box = *src_box; + cursor->transform = transform; + } else { + cursor->width = 0; + cursor->height = 0; + } + + cursor->hotspot_x = (int)roundf(hotspot_x * output->scale); + cursor->hotspot_y = (int)roundf(hotspot_y * output->scale); + + output_cursor_update_visible(cursor); + + if (cursor->own_texture) { + wlr_texture_destroy(cursor->texture); + } + cursor->texture = texture; + cursor->own_texture = own_texture; + + wlr_drm_syncobj_timeline_unref(cursor->wait_timeline); + if (wait_timeline != NULL) { + cursor->wait_timeline = wlr_drm_syncobj_timeline_ref(wait_timeline); + cursor->wait_point = wait_point; + } else { + cursor->wait_timeline = NULL; + cursor->wait_point = 0; + } + + wl_list_remove(&cursor->renderer_destroy.link); + if (texture != NULL) { + cursor->renderer_destroy.notify = output_cursor_handle_renderer_destroy; + wl_signal_add(&texture->renderer->events.destroy, &cursor->renderer_destroy); + } else { + wl_list_init(&cursor->renderer_destroy.link); + } + + if (output->hardware_cursor == NULL || output->hardware_cursor == cursor) { + if (output_cursor_attempt_hardware(cursor)) { + return true; + } + + wlr_log(WLR_DEBUG, "Falling back to software cursor on output '%s'", output->name); + output_disable_hardware_cursor(output); + } + + output_cursor_damage_whole(cursor); + return true; +} + +bool wlr_output_cursor_move(struct wlr_output_cursor *cursor, + double x, double y) { + // Scale coordinates for the output + x *= cursor->output->scale; + y *= cursor->output->scale; + + if (cursor->x == x && cursor->y == y) { + return true; + } + + if (cursor->output->hardware_cursor != cursor) { + output_cursor_damage_whole(cursor); + } + + cursor->x = x; + cursor->y = y; + bool was_visible = cursor->visible; + output_cursor_update_visible(cursor); + + if (!was_visible && !cursor->visible) { + // Cursor is still hidden, do nothing + return true; + } + + if (cursor->output->hardware_cursor != cursor) { + output_cursor_damage_whole(cursor); + return true; + } + + return output_move_hardware_cursor(cursor->output, (int)x, (int)y); +} + +struct wlr_output_cursor *wlr_output_cursor_create(struct wlr_output *output) { + struct wlr_output_cursor *cursor = calloc(1, sizeof(*cursor)); + if (cursor == NULL) { + return NULL; + } + cursor->output = output; + wl_list_insert(&output->cursors, &cursor->link); + cursor->visible = true; // default position is at (0, 0) + wl_list_init(&cursor->renderer_destroy.link); + output_cursor_refresh_color_transform(cursor, output->image_description); + return cursor; +} + +void wlr_output_cursor_destroy(struct wlr_output_cursor *cursor) { + if (cursor == NULL) { + return; + } + if (cursor->output->hardware_cursor == cursor) { + // If this cursor was the hardware cursor, disable it + output_disable_hardware_cursor(cursor->output); + } else { + output_cursor_damage_whole(cursor); + } + wl_list_remove(&cursor->renderer_destroy.link); + if (cursor->own_texture) { + wlr_texture_destroy(cursor->texture); + } + wlr_drm_syncobj_timeline_unref(cursor->wait_timeline); + wl_list_remove(&cursor->link); + wlr_color_transform_unref(cursor->color_transform); + free(cursor); +} + +bool output_cursor_refresh_color_transform(struct wlr_output_cursor *output_cursor, + const struct wlr_output_image_description *img_desc) { + wlr_color_transform_unref(output_cursor->color_transform); + output_cursor->color_transform = NULL; + if (img_desc == NULL) { + return true; + } + + struct wlr_color_primaries primaries_srgb; + wlr_color_primaries_from_named(&primaries_srgb, WLR_COLOR_NAMED_PRIMARIES_SRGB); + struct wlr_color_primaries primaries; + wlr_color_primaries_from_named(&primaries, img_desc->primaries); + float matrix[9]; + wlr_color_primaries_transform_absolute_colorimetric(&primaries_srgb, &primaries, matrix); + + // Source is sRGB, which has reference == max + struct wlr_color_luminances dst_lum; + wlr_color_transfer_function_get_default_luminance(img_desc->transfer_function, &dst_lum); + float luminance_multiplier = dst_lum.reference / dst_lum.max; + for (int i = 0; i < 9; ++i) { + matrix[i] *= luminance_multiplier; + } + + struct wlr_color_transform *transforms[] = { + wlr_color_transform_init_matrix(matrix), + wlr_color_transform_init_linear_to_inverse_eotf(img_desc->transfer_function), + }; + if (transforms[0] == NULL || transforms[1] == NULL) { + wlr_color_transform_unref(transforms[0]); + wlr_color_transform_unref(transforms[1]); + return false; + } + output_cursor->color_transform = wlr_color_transform_init_pipeline(transforms, + sizeof(transforms) / sizeof(transforms[0])); + wlr_color_transform_unref(transforms[0]); + wlr_color_transform_unref(transforms[1]); + return output_cursor->color_transform != NULL; +} diff --git a/3rdparty/wlroots/types/output/output.c b/3rdparty/wlroots/types/output/output.c new file mode 100644 index 0000000000..3715950ce0 --- /dev/null +++ b/3rdparty/wlroots/types/output/output.c @@ -0,0 +1,1020 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_output.h" +#include "util/env.h" +#include "util/global.h" + +#define OUTPUT_VERSION 4 + +static void send_geometry(struct wl_resource *resource) { + struct wlr_output *output = wlr_output_from_resource(resource); + wl_output_send_geometry(resource, 0, 0, + output->phys_width, output->phys_height, output->subpixel, + "Unknown", "Unknown", output->transform); +} + +static void send_current_mode(struct wl_resource *resource) { + struct wlr_output *output = wlr_output_from_resource(resource); + if (output->current_mode != NULL) { + struct wlr_output_mode *mode = output->current_mode; + wl_output_send_mode(resource, WL_OUTPUT_MODE_CURRENT, + mode->width, mode->height, mode->refresh); + } else { + // Output has no mode + wl_output_send_mode(resource, WL_OUTPUT_MODE_CURRENT, output->width, + output->height, output->refresh); + } +} + +static void send_scale(struct wl_resource *resource) { + struct wlr_output *output = wlr_output_from_resource(resource); + uint32_t version = wl_resource_get_version(resource); + if (version >= WL_OUTPUT_SCALE_SINCE_VERSION) { + wl_output_send_scale(resource, (uint32_t)ceil(output->scale)); + } +} + +static void send_name(struct wl_resource *resource) { + struct wlr_output *output = wlr_output_from_resource(resource); + uint32_t version = wl_resource_get_version(resource); + if (version >= WL_OUTPUT_NAME_SINCE_VERSION) { + wl_output_send_name(resource, output->name); + } +} + +static void send_description(struct wl_resource *resource) { + struct wlr_output *output = wlr_output_from_resource(resource); + uint32_t version = wl_resource_get_version(resource); + if (output->description != NULL && + version >= WL_OUTPUT_DESCRIPTION_SINCE_VERSION) { + wl_output_send_description(resource, output->description); + } +} + +static void send_done(struct wl_resource *resource) { + uint32_t version = wl_resource_get_version(resource); + if (version >= WL_OUTPUT_DONE_SINCE_VERSION) { + wl_output_send_done(resource); + } +} + +static void output_handle_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void output_handle_release(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wl_output_interface output_impl = { + .release = output_handle_release, +}; + +static void output_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + // `output` can be NULL if the output global is being destroyed + struct wlr_output *output = data; + + struct wl_resource *resource = wl_resource_create(wl_client, + &wl_output_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + wl_resource_set_implementation(resource, &output_impl, output, + output_handle_resource_destroy); + + if (output == NULL) { + wl_list_init(wl_resource_get_link(resource)); + return; + } + + wl_list_insert(&output->resources, wl_resource_get_link(resource)); + + send_geometry(resource); + send_current_mode(resource); + send_scale(resource); + send_name(resource); + send_description(resource); + send_done(resource); + + struct wlr_output_event_bind evt = { + .output = output, + .resource = resource, + }; + + wl_signal_emit_mutable(&output->events.bind, &evt); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_output *output = wl_container_of(listener, output, display_destroy); + wlr_output_destroy_global(output); +} + +void wlr_output_create_global(struct wlr_output *output, struct wl_display *display) { + if (output->global != NULL) { + return; + } + + output->global = wl_global_create(display, + &wl_output_interface, OUTPUT_VERSION, output, output_bind); + if (output->global == NULL) { + wlr_log(WLR_ERROR, "Failed to allocate wl_output global"); + return; + } + + wl_list_remove(&output->display_destroy.link); + wl_display_add_destroy_listener(display, &output->display_destroy); +} + +void wlr_output_destroy_global(struct wlr_output *output) { + if (output->global == NULL) { + return; + } + + // Make all output resources inert + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &output->resources) { + wl_resource_set_user_data(resource, NULL); + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + } + + wl_list_remove(&output->display_destroy.link); + wl_list_init(&output->display_destroy.link); + + wlr_global_destroy_safe(output->global); + output->global = NULL; +} + +static void schedule_done_handle_idle_timer(void *data) { + struct wlr_output *output = data; + output->idle_done = NULL; + + struct wl_resource *resource; + wl_resource_for_each(resource, &output->resources) { + send_done(resource); + } +} + +void wlr_output_schedule_done(struct wlr_output *output) { + if (output->idle_done != NULL) { + return; // Already scheduled + } + + output->idle_done = wl_event_loop_add_idle(output->event_loop, + schedule_done_handle_idle_timer, output); +} + +struct wlr_output *wlr_output_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_output_interface, + &output_impl)); + return wl_resource_get_user_data(resource); +} + +void wlr_output_set_name(struct wlr_output *output, const char *name) { + assert(output->global == NULL); + + free(output->name); + output->name = strdup(name); +} + +void wlr_output_set_description(struct wlr_output *output, const char *desc) { + if (output->description != NULL && desc != NULL && + strcmp(output->description, desc) == 0) { + return; + } + + free(output->description); + if (desc != NULL) { + output->description = strdup(desc); + } else { + output->description = NULL; + } + + struct wl_resource *resource; + wl_resource_for_each(resource, &output->resources) { + send_description(resource); + } + wlr_output_schedule_done(output); + + wl_signal_emit_mutable(&output->events.description, output); +} + +static void output_apply_state(struct wlr_output *output, + const struct wlr_output_state *state) { + if (state->committed & WLR_OUTPUT_STATE_RENDER_FORMAT) { + output->render_format = state->render_format; + } + + if (state->committed & WLR_OUTPUT_STATE_SUBPIXEL) { + output->subpixel = state->subpixel; + } + + if (state->committed & WLR_OUTPUT_STATE_ENABLED) { + output->enabled = state->enabled; + } + + bool scale_updated = state->committed & WLR_OUTPUT_STATE_SCALE; + if (scale_updated) { + output->scale = state->scale; + } + + if (state->committed & WLR_OUTPUT_STATE_TRANSFORM) { + output->transform = state->transform; + } + + if (state->committed & WLR_OUTPUT_STATE_IMAGE_DESCRIPTION) { + if (state->image_description != NULL) { + output->image_description_value = *state->image_description; + output->image_description = &output->image_description_value; + } else { + output->image_description = NULL; + } + + struct wlr_output_cursor *output_cursor; + wl_list_for_each(output_cursor, &output->cursors, link) { + output_cursor_refresh_color_transform(output_cursor, output->image_description); + } + } + + if (state->committed & WLR_OUTPUT_STATE_COLOR_TRANSFORM) { + wlr_color_transform_unref(output->color_transform); + if (state->color_transform != NULL) { + output->color_transform = wlr_color_transform_ref(state->color_transform); + } else { + output->color_transform = NULL; + } + } + + bool geometry_updated = state->committed & + (WLR_OUTPUT_STATE_MODE | WLR_OUTPUT_STATE_TRANSFORM | + WLR_OUTPUT_STATE_SUBPIXEL); + + // Destroy the swapchains when an output is disabled + if ((state->committed & WLR_OUTPUT_STATE_ENABLED) && !state->enabled) { + wlr_swapchain_destroy(output->swapchain); + output->swapchain = NULL; + wlr_swapchain_destroy(output->cursor_swapchain); + output->cursor_swapchain = NULL; + } + + if (state->committed & WLR_OUTPUT_STATE_LAYERS) { + for (size_t i = 0; i < state->layers_len; i++) { + struct wlr_output_layer_state *layer_state = &state->layers[i]; + struct wlr_output_layer *layer = layer_state->layer; + + // Commit layer ordering + wl_list_remove(&layer->link); + wl_list_insert(output->layers.prev, &layer->link); + + // Commit layer state + layer->src_box = layer_state->src_box; + layer->dst_box = layer_state->dst_box; + } + } + + bool mode_updated = false; + if (state->committed & WLR_OUTPUT_STATE_MODE) { + int width = 0, height = 0, refresh = 0; + switch (state->mode_type) { + case WLR_OUTPUT_STATE_MODE_FIXED:; + struct wlr_output_mode *mode = state->mode; + output->current_mode = mode; + if (mode != NULL) { + width = mode->width; + height = mode->height; + refresh = mode->refresh; + } + break; + case WLR_OUTPUT_STATE_MODE_CUSTOM: + output->current_mode = NULL; + width = state->custom_mode.width; + height = state->custom_mode.height; + refresh = state->custom_mode.refresh; + break; + } + + if (output->width != width || output->height != height || + output->refresh != refresh) { + output->width = width; + output->height = height; + + output->refresh = refresh; + + if (output->swapchain != NULL && + (output->swapchain->width != output->width || + output->swapchain->height != output->height)) { + wlr_swapchain_destroy(output->swapchain); + output->swapchain = NULL; + } + + mode_updated = true; + } + } + + if (geometry_updated || scale_updated || mode_updated) { + struct wl_resource *resource; + wl_resource_for_each(resource, &output->resources) { + if (mode_updated) { + send_current_mode(resource); + } + if (geometry_updated) { + send_geometry(resource); + } + if (scale_updated) { + send_scale(resource); + } + } + wlr_output_schedule_done(output); + } +} + +void wlr_output_init(struct wlr_output *output, struct wlr_backend *backend, + const struct wlr_output_impl *impl, struct wl_event_loop *event_loop, + const struct wlr_output_state *state) { + assert(impl->commit); + if (impl->set_cursor || impl->move_cursor) { + assert(impl->set_cursor && impl->move_cursor); + } + + *output = (struct wlr_output){ + .backend = backend, + .impl = impl, + .event_loop = event_loop, + .render_format = DRM_FORMAT_XRGB8888, + .transform = WL_OUTPUT_TRANSFORM_NORMAL, + .scale = 1, + .commit_seq = 0, + }; + + wl_list_init(&output->modes); + wl_list_init(&output->cursors); + wl_list_init(&output->layers); + wl_list_init(&output->resources); + + wl_signal_init(&output->events.frame); + wl_signal_init(&output->events.damage); + wl_signal_init(&output->events.needs_frame); + wl_signal_init(&output->events.precommit); + wl_signal_init(&output->events.commit); + wl_signal_init(&output->events.present); + wl_signal_init(&output->events.bind); + wl_signal_init(&output->events.description); + wl_signal_init(&output->events.request_state); + wl_signal_init(&output->events.destroy); + + output->software_cursor_locks = env_parse_bool("WLR_NO_HARDWARE_CURSORS"); + if (output->software_cursor_locks) { + wlr_log(WLR_DEBUG, "WLR_NO_HARDWARE_CURSORS set, forcing software cursors"); + } + + wlr_addon_set_init(&output->addons); + + wl_list_init(&output->display_destroy.link); + output->display_destroy.notify = handle_display_destroy; + + if (state) { + output_apply_state(output, state); + } +} + +void wlr_output_finish(struct wlr_output *output) { + wl_signal_emit_mutable(&output->events.destroy, output); + wlr_addon_set_finish(&output->addons); + + assert(wl_list_empty(&output->events.frame.listener_list)); + assert(wl_list_empty(&output->events.damage.listener_list)); + assert(wl_list_empty(&output->events.needs_frame.listener_list)); + assert(wl_list_empty(&output->events.precommit.listener_list)); + assert(wl_list_empty(&output->events.commit.listener_list)); + assert(wl_list_empty(&output->events.present.listener_list)); + assert(wl_list_empty(&output->events.bind.listener_list)); + assert(wl_list_empty(&output->events.description.listener_list)); + assert(wl_list_empty(&output->events.request_state.listener_list)); + assert(wl_list_empty(&output->events.destroy.listener_list)); + + wlr_output_destroy_global(output); + + wl_list_remove(&output->display_destroy.link); + + // The backend is responsible for free-ing the list of modes + + struct wlr_output_cursor *cursor, *tmp_cursor; + wl_list_for_each_safe(cursor, tmp_cursor, &output->cursors, link) { + wlr_output_cursor_destroy(cursor); + } + + struct wlr_output_layer *layer, *tmp_layer; + wl_list_for_each_safe(layer, tmp_layer, &output->layers, link) { + wlr_output_layer_destroy(layer); + } + + wlr_swapchain_destroy(output->cursor_swapchain); + wlr_buffer_unlock(output->cursor_front_buffer); + wlr_color_transform_unref(output->color_transform); + + wlr_swapchain_destroy(output->swapchain); + + if (output->idle_frame != NULL) { + wl_event_source_remove(output->idle_frame); + } + + if (output->idle_done != NULL) { + wl_event_source_remove(output->idle_done); + } + + free(output->name); + free(output->description); + free(output->make); + free(output->model); + free(output->serial); +} + +void wlr_output_destroy(struct wlr_output *output) { + if (!output) { + return; + } + + if (output->impl && output->impl->destroy) { + output->impl->destroy(output); + } else { + wlr_output_finish(output); + free(output); + } +} + +void wlr_output_transformed_resolution(struct wlr_output *output, + int *width, int *height) { + if (output->transform % 2 == 0) { + *width = output->width; + *height = output->height; + } else { + *width = output->height; + *height = output->width; + } +} + +void wlr_output_effective_resolution(struct wlr_output *output, + int *width, int *height) { + wlr_output_transformed_resolution(output, width, height); + *width /= output->scale; + *height /= output->scale; +} + +struct wlr_output_mode *wlr_output_preferred_mode(struct wlr_output *output) { + if (wl_list_empty(&output->modes)) { + return NULL; + } + + struct wlr_output_mode *mode; + wl_list_for_each(mode, &output->modes, link) { + if (mode->preferred) { + return mode; + } + } + + // No preferred mode, choose the first one + return wl_container_of(output->modes.next, mode, link); +} + +void output_pending_resolution(struct wlr_output *output, + const struct wlr_output_state *state, int *width, int *height) { + if (state->committed & WLR_OUTPUT_STATE_MODE) { + switch (state->mode_type) { + case WLR_OUTPUT_STATE_MODE_FIXED: + *width = state->mode->width; + *height = state->mode->height; + return; + case WLR_OUTPUT_STATE_MODE_CUSTOM: + *width = state->custom_mode.width; + *height = state->custom_mode.height; + return; + } + abort(); + } else { + *width = output->width; + *height = output->height; + } +} + +bool output_pending_enabled(struct wlr_output *output, + const struct wlr_output_state *state) { + if (state->committed & WLR_OUTPUT_STATE_ENABLED) { + return state->enabled; + } + return output->enabled; +} + +const struct wlr_output_image_description *output_pending_image_description( + struct wlr_output *output, const struct wlr_output_state *state) { + if (state->committed & WLR_OUTPUT_STATE_IMAGE_DESCRIPTION) { + return state->image_description; + } + return output->image_description; +} + +/** + * Compare a struct wlr_output_state with the current state of a struct + * wlr_output. + * + * Returns a bitfield of the unchanged fields. + * + * Some fields are not checked: damage always changes in-between frames, the + * contents of the buffer might have changed, etc. + */ +static uint32_t output_compare_state(struct wlr_output *output, + const struct wlr_output_state *state) { + uint32_t fields = 0; + if (state->committed & WLR_OUTPUT_STATE_MODE) { + bool unchanged = false; + switch (state->mode_type) { + case WLR_OUTPUT_STATE_MODE_FIXED: + unchanged = output->current_mode == state->mode; + break; + case WLR_OUTPUT_STATE_MODE_CUSTOM: + unchanged = output->width == state->custom_mode.width && + output->height == state->custom_mode.height && + output->refresh == state->custom_mode.refresh; + break; + } + if (unchanged) { + fields |= WLR_OUTPUT_STATE_MODE; + } + } + if ((state->committed & WLR_OUTPUT_STATE_ENABLED) && output->enabled == state->enabled) { + fields |= WLR_OUTPUT_STATE_ENABLED; + } + if ((state->committed & WLR_OUTPUT_STATE_SCALE) && output->scale == state->scale) { + fields |= WLR_OUTPUT_STATE_SCALE; + } + if ((state->committed & WLR_OUTPUT_STATE_TRANSFORM) && + output->transform == state->transform) { + fields |= WLR_OUTPUT_STATE_TRANSFORM; + } + if (state->committed & WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED) { + bool enabled = + output->adaptive_sync_status != WLR_OUTPUT_ADAPTIVE_SYNC_DISABLED; + if (enabled == state->adaptive_sync_enabled) { + fields |= WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED; + } + } + if ((state->committed & WLR_OUTPUT_STATE_RENDER_FORMAT) && + output->render_format == state->render_format) { + fields |= WLR_OUTPUT_STATE_RENDER_FORMAT; + } + if ((state->committed & WLR_OUTPUT_STATE_SUBPIXEL) && + output->subpixel == state->subpixel) { + fields |= WLR_OUTPUT_STATE_SUBPIXEL; + } + if ((state->committed & WLR_OUTPUT_STATE_COLOR_TRANSFORM) && + output->color_transform == state->color_transform) { + fields |= WLR_OUTPUT_STATE_COLOR_TRANSFORM; + } + return fields; +} + +static bool output_basic_test(struct wlr_output *output, + const struct wlr_output_state *state) { + if (state->committed & WLR_OUTPUT_STATE_BUFFER) { + struct wlr_fbox src_box; + output_state_get_buffer_src_box(state, &src_box); + + // Source box must be contained within the buffer + if (src_box.x < 0.0 || src_box.y < 0.0 || + src_box.x + src_box.width > state->buffer->width || + src_box.y + src_box.height > state->buffer->height) { + wlr_log(WLR_ERROR, "Tried to commit with invalid buffer_src_box"); + return false; + } + + // Source box must not be empty (but it can be smaller than 1 pixel, + // some DRM devices support sub-pixel crops) + if (wlr_fbox_empty(&src_box)) { + wlr_log(WLR_ERROR, "Tried to commit with an empty buffer_src_box"); + return false; + } + + // Destination box cannot be entirely off-screen (but it also doesn't + // have to be entirely on-screen). This also checks the dst box is + // not empty. + int pending_width, pending_height; + output_pending_resolution(output, state, &pending_width, &pending_height); + struct wlr_box output_box = { + .width = pending_width, + .height = pending_height + }; + struct wlr_box dst_box; + output_state_get_buffer_dst_box(state, &dst_box); + if (!wlr_box_intersection(&output_box, &output_box, &dst_box)) { + wlr_log(WLR_ERROR, "Primary buffer is entirely off-screen or 0-sized"); + return false; + } + } else { + if (state->tearing_page_flip) { + wlr_log(WLR_ERROR, "Tried to commit a tearing page flip without a buffer"); + return false; + } + if (state->committed & WLR_OUTPUT_STATE_WAIT_TIMELINE) { + wlr_log(WLR_DEBUG, "Tried to set wait timeline without a buffer"); + return false; + } + if (state->committed & WLR_OUTPUT_STATE_SIGNAL_TIMELINE) { + wlr_log(WLR_DEBUG, "Tried to set signal timeline without a buffer"); + return false; + } + } + + if (state->committed & WLR_OUTPUT_STATE_RENDER_FORMAT) { + struct wlr_allocator *allocator = output->allocator; + assert(allocator != NULL); + + const struct wlr_drm_format_set *display_formats = + wlr_output_get_primary_formats(output, allocator->buffer_caps); + struct wlr_drm_format format = {0}; + if (!output_pick_format(output, display_formats, &format, state->render_format)) { + wlr_log(WLR_ERROR, "Failed to pick primary buffer format for output"); + return false; + } + + wlr_drm_format_finish(&format); + } + + bool enabled = output_pending_enabled(output, state); + + if (enabled && (state->committed & (WLR_OUTPUT_STATE_ENABLED | + WLR_OUTPUT_STATE_MODE))) { + int pending_width, pending_height; + output_pending_resolution(output, state, + &pending_width, &pending_height); + if (pending_width == 0 || pending_height == 0) { + wlr_log(WLR_DEBUG, "Tried to enable an output with a zero mode"); + return false; + } + } + + const struct { + enum wlr_output_state_field field; + const char *name; + } needs_enabled[] = { + { WLR_OUTPUT_STATE_BUFFER, "buffer" }, + { WLR_OUTPUT_STATE_MODE, "mode" }, + { WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED, "adaptive sync" }, + { WLR_OUTPUT_STATE_RENDER_FORMAT, "render format" }, + { WLR_OUTPUT_STATE_SUBPIXEL, "subpixel" }, + { WLR_OUTPUT_STATE_COLOR_TRANSFORM, "color transform" }, + { WLR_OUTPUT_STATE_IMAGE_DESCRIPTION, "image description" }, + }; + if (!enabled) { + for (size_t i = 0; i < sizeof(needs_enabled) / sizeof(needs_enabled[0]); i++) { + if (state->committed & needs_enabled[i].field) { + wlr_log(WLR_DEBUG, "Tried to set %s on a disabled output", needs_enabled[i].name); + return false; + } + } + } + + if (state->committed & WLR_OUTPUT_STATE_LAYERS) { + if (state->layers_len != (size_t)wl_list_length(&output->layers)) { + wlr_log(WLR_DEBUG, "All output layers must be specified in wlr_output_state.layers"); + return false; + } + + for (size_t i = 0; i < state->layers_len; i++) { + state->layers[i].accepted = false; + } + } + + if ((state->committed & (WLR_OUTPUT_STATE_WAIT_TIMELINE | WLR_OUTPUT_STATE_SIGNAL_TIMELINE)) && + !output->backend->features.timeline) { + wlr_log(WLR_DEBUG, "Wait/signal timelines are not supported for this output"); + return false; + } + + if ((state->committed & WLR_OUTPUT_STATE_IMAGE_DESCRIPTION) && + state->image_description != NULL) { + if (!(output->supported_primaries & state->image_description->primaries)) { + wlr_log(WLR_DEBUG, "Unsupported image description primaries"); + return false; + } + if (!(output->supported_transfer_functions & state->image_description->transfer_function)) { + wlr_log(WLR_DEBUG, "Unsupported image description transfer function"); + return false; + } + } + + return true; +} + +bool wlr_output_test_state(struct wlr_output *output, + const struct wlr_output_state *state) { + uint32_t unchanged = output_compare_state(output, state); + + // Create a shallow copy of the state with only the fields which have been + // changed and potentially a new buffer. + struct wlr_output_state copy = *state; + copy.committed &= ~unchanged; + + if (!output_basic_test(output, ©)) { + return false; + } + if (!output->impl->test) { + return true; + } + + bool new_back_buffer = false; + if (!output_ensure_buffer(output, ©, &new_back_buffer)) { + return false; + } + + bool success = output->impl->test(output, ©); + if (new_back_buffer) { + wlr_buffer_unlock(copy.buffer); + } + return success; +} + +bool output_prepare_commit(struct wlr_output *output, const struct wlr_output_state *state) { + if (!output_basic_test(output, state)) { + wlr_log(WLR_ERROR, "Basic output test failed for %s", output->name); + return false; + } + + if ((state->committed & WLR_OUTPUT_STATE_BUFFER) && + output->idle_frame != NULL) { + wl_event_source_remove(output->idle_frame); + output->idle_frame = NULL; + } + + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + + struct wlr_output_event_precommit pre_event = { + .output = output, + .when = now, + .state = state, + }; + wl_signal_emit_mutable(&output->events.precommit, &pre_event); + + return true; +} + +void output_apply_commit(struct wlr_output *output, const struct wlr_output_state *state) { + output->commit_seq++; + + if (output_pending_enabled(output, state)) { + output->frame_pending = true; + output->needs_frame = false; + } + + output_apply_state(output, state); +} + +void output_send_commit_event(struct wlr_output *output, const struct wlr_output_state *state) { + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + struct wlr_output_event_commit event = { + .output = output, + .when = now, + .state = state, + }; + wl_signal_emit_mutable(&output->events.commit, &event); +} + +bool wlr_output_commit_state(struct wlr_output *output, + const struct wlr_output_state *state) { + uint32_t unchanged = output_compare_state(output, state); + + // Create a shallow copy of the state with only the fields which have been + // changed and potentially a new buffer. + struct wlr_output_state pending = *state; + pending.committed &= ~unchanged; + + if (!output_basic_test(output, &pending)) { + wlr_log(WLR_ERROR, "Basic output test failed for %s", output->name); + return false; + } + + bool new_back_buffer = false; + if (!output_ensure_buffer(output, &pending, &new_back_buffer)) { + return false; + } + + if (!output_prepare_commit(output, &pending)) { + return false; + } + + if (!output->impl->commit(output, &pending)) { + if (new_back_buffer) { + wlr_buffer_unlock(pending.buffer); + } + return false; + } + + output_apply_commit(output, &pending); + output_send_commit_event(output, &pending); + + if (new_back_buffer) { + wlr_buffer_unlock(pending.buffer); + } + + return true; +} + +void wlr_output_send_frame(struct wlr_output *output) { + output->frame_pending = false; + if (output->enabled) { + wl_signal_emit_mutable(&output->events.frame, output); + } +} + +static void schedule_frame_handle_idle_timer(void *data) { + struct wlr_output *output = data; + output->idle_frame = NULL; + if (!output->frame_pending) { + wlr_output_send_frame(output); + } +} + +void wlr_output_schedule_frame(struct wlr_output *output) { + // Make sure the compositor commits a new frame. This is necessary to make + // clients which ask for frame callbacks without submitting a new buffer + // work. + wlr_output_update_needs_frame(output); + + if (output->frame_pending || output->idle_frame != NULL) { + return; + } + + // We're using an idle timer here in case a buffer swap happens right after + // this function is called + output->idle_frame = wl_event_loop_add_idle(output->event_loop, + schedule_frame_handle_idle_timer, output); +} + +void wlr_output_send_present(struct wlr_output *output, + struct wlr_output_event_present *event) { + assert(event); + event->output = output; + + if (event->presented && (event->when.tv_sec == 0 && event->when.tv_nsec == 0)) { + if (clock_gettime(CLOCK_MONOTONIC, &event->when) != 0) { + wlr_log_errno(WLR_ERROR, "failed to send output present event: " + "failed to read clock"); + return; + } + } + + wl_signal_emit_mutable(&output->events.present, event); +} + +struct deferred_present_event { + struct wlr_output *output; + struct wl_event_source *idle_source; + struct wlr_output_event_present event; + struct wl_listener output_destroy; +}; + +static void deferred_present_event_destroy(struct deferred_present_event *deferred) { + wl_list_remove(&deferred->output_destroy.link); + free(deferred); +} + +static void deferred_present_event_handle_idle(void *data) { + struct deferred_present_event *deferred = data; + wlr_output_send_present(deferred->output, &deferred->event); + deferred_present_event_destroy(deferred); +} + +static void deferred_present_event_handle_output_destroy(struct wl_listener *listener, void *data) { + struct deferred_present_event *deferred = wl_container_of(listener, deferred, output_destroy); + wl_event_source_remove(deferred->idle_source); + deferred_present_event_destroy(deferred); +} + +void output_defer_present(struct wlr_output *output, struct wlr_output_event_present event) { + struct deferred_present_event *deferred = calloc(1, sizeof(*deferred)); + if (!deferred) { + return; + } + *deferred = (struct deferred_present_event){ + .output = output, + .event = event, + }; + deferred->output_destroy.notify = deferred_present_event_handle_output_destroy; + wl_signal_add(&output->events.destroy, &deferred->output_destroy); + + deferred->idle_source = wl_event_loop_add_idle(output->event_loop, + deferred_present_event_handle_idle, deferred); +} + +void output_state_get_buffer_src_box(const struct wlr_output_state *state, + struct wlr_fbox *out) { + out->x = state->buffer_src_box.x; + out->y = state->buffer_src_box.y; + // If the source box is unset then default to the whole buffer. + if (state->buffer_src_box.width == 0.0 && + state->buffer_src_box.height == 0.0) { + out->width = (double)state->buffer->width; + out->height = (double)state->buffer->height; + } else { + out->width = state->buffer_src_box.width; + out->height = state->buffer_src_box.height; + } +} + +void output_state_get_buffer_dst_box(const struct wlr_output_state *state, + struct wlr_box *out) { + out->x = state->buffer_dst_box.x; + out->y = state->buffer_dst_box.y; + // If the dst box is unset then default to source crop size (which itself + // defaults to the whole buffer size if unset) + if (state->buffer_dst_box.width == 0 && + state->buffer_dst_box.height == 0) { + struct wlr_fbox src_box; + output_state_get_buffer_src_box(state, &src_box); + out->width = (int)src_box.width; + out->height = (int)src_box.height; + } else { + out->width = state->buffer_dst_box.width; + out->height = state->buffer_dst_box.height; + } +} + +void wlr_output_send_request_state(struct wlr_output *output, + const struct wlr_output_state *state) { + uint32_t unchanged = output_compare_state(output, state); + struct wlr_output_state copy = *state; + copy.committed &= ~unchanged; + if (copy.committed == 0) { + return; + } + + struct wlr_output_event_request_state event = { + .output = output, + .state = ©, + }; + wl_signal_emit_mutable(&output->events.request_state, &event); +} + +size_t wlr_output_get_gamma_size(struct wlr_output *output) { + if (!output->impl->get_gamma_size) { + return 0; + } + return output->impl->get_gamma_size(output); +} + +void wlr_output_update_needs_frame(struct wlr_output *output) { + if (output->needs_frame) { + return; + } + output->needs_frame = true; + wl_signal_emit_mutable(&output->events.needs_frame, output); +} + +const struct wlr_drm_format_set *wlr_output_get_primary_formats( + struct wlr_output *output, uint32_t buffer_caps) { + if (!output->impl->get_primary_formats) { + return NULL; + } + + const struct wlr_drm_format_set *formats = + output->impl->get_primary_formats(output, buffer_caps); + if (formats == NULL) { + wlr_log(WLR_ERROR, "Failed to get primary display formats"); + + static const struct wlr_drm_format_set empty_format_set = {0}; + return &empty_format_set; + } + + return formats; +} + +bool wlr_output_is_direct_scanout_allowed(struct wlr_output *output) { + if (output->attach_render_locks > 0) { + wlr_log(WLR_DEBUG, "Direct scan-out disabled by lock"); + return false; + } + + // If the output has at least one software cursor, reject direct scan-out + struct wlr_output_cursor *cursor; + wl_list_for_each(cursor, &output->cursors, link) { + if (cursor->enabled && cursor->visible && + cursor != output->hardware_cursor) { + wlr_log(WLR_DEBUG, + "Direct scan-out disabled by software cursor"); + return false; + } + } + + return true; +} diff --git a/3rdparty/wlroots/types/output/render.c b/3rdparty/wlroots/types/output/render.c new file mode 100644 index 0000000000..155da5cf89 --- /dev/null +++ b/3rdparty/wlroots/types/output/render.c @@ -0,0 +1,218 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "render/drm_format_set.h" +#include "render/wlr_renderer.h" +#include "render/pixel_format.h" +#include "types/wlr_output.h" + +bool wlr_output_init_render(struct wlr_output *output, + struct wlr_allocator *allocator, struct wlr_renderer *renderer) { + assert(allocator != NULL && renderer != NULL); + + if (!(output->backend->buffer_caps & allocator->buffer_caps)) { + wlr_log(WLR_ERROR, "output backend and allocator buffer capabilities " + "don't match"); + return false; + } else if (!(renderer->render_buffer_caps & allocator->buffer_caps)) { + wlr_log(WLR_ERROR, "renderer and allocator buffer capabilities " + "don't match"); + return false; + } + + wlr_swapchain_destroy(output->swapchain); + output->swapchain = NULL; + + wlr_swapchain_destroy(output->cursor_swapchain); + output->cursor_swapchain = NULL; + + output->allocator = allocator; + output->renderer = renderer; + + return true; +} + +static struct wlr_buffer *output_acquire_empty_buffer(struct wlr_output *output, + const struct wlr_output_state *state) { + assert(!(state->committed & WLR_OUTPUT_STATE_BUFFER)); + + // wlr_output_configure_primary_swapchain() function will call + // wlr_output_test_state(), which can call us again. This is dangerous: we + // risk infinite recursion. However, a buffer will always be supplied in + // wlr_output_test_state(), which will prevent us from being called. + if (!wlr_output_configure_primary_swapchain(output, state, + &output->swapchain)) { + return NULL; + } + + struct wlr_buffer *buffer = wlr_swapchain_acquire(output->swapchain); + if (buffer == NULL) { + return NULL; + } + + struct wlr_render_pass *pass = + wlr_renderer_begin_buffer_pass(output->renderer, buffer, NULL); + if (pass == NULL) { + wlr_buffer_unlock(buffer); + return NULL; + } + + wlr_render_pass_add_rect(pass, &(struct wlr_render_rect_options){ + .color = { 0, 0, 0, 0 }, + .blend_mode = WLR_RENDER_BLEND_MODE_NONE, + }); + + if (!wlr_render_pass_submit(pass)) { + wlr_buffer_unlock(buffer); + return NULL; + } + + return buffer; +} + +// This function may attach a new, empty buffer if necessary. +// If so, the new_back_buffer out parameter will be set to true. +bool output_ensure_buffer(struct wlr_output *output, + struct wlr_output_state *state, bool *new_buffer) { + assert(*new_buffer == false); + + // If we already have a buffer, we don't need to allocate a new one + if (state->committed & WLR_OUTPUT_STATE_BUFFER) { + return true; + } + + // If the compositor hasn't called wlr_output_init_render(), they will use + // their own logic to attach buffers + if (output->renderer == NULL) { + return true; + } + + bool enabled = output->enabled; + if (state->committed & WLR_OUTPUT_STATE_ENABLED) { + enabled = state->enabled; + } + + // If we're lighting up an output or changing its mode, make sure to + // provide a new buffer + bool needs_new_buffer = false; + if ((state->committed & WLR_OUTPUT_STATE_ENABLED) && state->enabled) { + needs_new_buffer = true; + } + if (state->committed & WLR_OUTPUT_STATE_MODE) { + needs_new_buffer = true; + } + if (state->committed & WLR_OUTPUT_STATE_RENDER_FORMAT) { + needs_new_buffer = true; + } + if (state->allow_reconfiguration && output->commit_seq == 0 && enabled) { + // On first commit, require a new buffer if the compositor called a + // mode-setting function, even if the mode won't change. This makes it + // so the swapchain is created now. + needs_new_buffer = true; + } + if (!needs_new_buffer) { + return true; + } + + wlr_log(WLR_DEBUG, "Attaching empty buffer to output for modeset"); + struct wlr_buffer *buffer = output_acquire_empty_buffer(output, state); + if (buffer == NULL) { + return false; + } + + *new_buffer = true; + wlr_output_state_set_buffer(state, buffer); + wlr_buffer_unlock(buffer); + return true; +} + +void wlr_output_lock_attach_render(struct wlr_output *output, bool lock) { + if (lock) { + ++output->attach_render_locks; + } else { + assert(output->attach_render_locks > 0); + --output->attach_render_locks; + } + wlr_log(WLR_DEBUG, "%s direct scan-out on output '%s' (locks: %d)", + lock ? "Disabling" : "Enabling", output->name, + output->attach_render_locks); +} + +bool output_pick_format(struct wlr_output *output, + const struct wlr_drm_format_set *display_formats, + struct wlr_drm_format *format, uint32_t fmt) { + struct wlr_renderer *renderer = output->renderer; + struct wlr_allocator *allocator = output->allocator; + assert(renderer != NULL && allocator != NULL); + + const struct wlr_drm_format_set *render_formats = + wlr_renderer_get_render_formats(renderer); + if (render_formats == NULL) { + wlr_log(WLR_ERROR, "Failed to get render formats"); + return false; + } + + const struct wlr_drm_format *render_format = + wlr_drm_format_set_get(render_formats, fmt); + if (render_format == NULL) { + wlr_log(WLR_DEBUG, "Renderer doesn't support format 0x%"PRIX32, fmt); + return false; + } + + if (display_formats != NULL) { + const struct wlr_drm_format *display_format = + wlr_drm_format_set_get(display_formats, fmt); + if (display_format == NULL) { + wlr_log(WLR_DEBUG, "Output doesn't support format 0x%"PRIX32, fmt); + return false; + } + if (!wlr_drm_format_intersect(format, display_format, render_format)) { + wlr_log(WLR_DEBUG, "Failed to intersect display and render " + "modifiers for format 0x%"PRIX32 " on output %s", + fmt, output->name); + return false; + } + } else { + // The output can display any format + if (!wlr_drm_format_copy(format, render_format)) { + return false; + } + } + + if (format->len == 0) { + wlr_drm_format_finish(format); + wlr_log(WLR_DEBUG, "Failed to pick output format"); + return false; + } + + return true; +} + +struct wlr_render_pass *wlr_output_begin_render_pass(struct wlr_output *output, + struct wlr_output_state *state, struct wlr_buffer_pass_options *render_options) { + if (!wlr_output_configure_primary_swapchain(output, state, &output->swapchain)) { + return NULL; + } + + struct wlr_buffer *buffer = wlr_swapchain_acquire(output->swapchain); + if (buffer == NULL) { + return NULL; + } + + struct wlr_renderer *renderer = output->renderer; + assert(renderer != NULL); + struct wlr_render_pass *pass = wlr_renderer_begin_buffer_pass(renderer, buffer, render_options); + if (pass == NULL) { + return NULL; + } + + wlr_output_state_set_buffer(state, buffer); + wlr_buffer_unlock(buffer); + return pass; +} diff --git a/3rdparty/wlroots/types/output/state.c b/3rdparty/wlroots/types/output/state.c new file mode 100644 index 0000000000..f2c655e211 --- /dev/null +++ b/3rdparty/wlroots/types/output/state.c @@ -0,0 +1,197 @@ +#include +#include +#include +#include +#include +#include "types/wlr_output.h" + +void wlr_output_state_init(struct wlr_output_state *state) { + *state = (struct wlr_output_state){0}; + pixman_region32_init(&state->damage); +} + +void wlr_output_state_finish(struct wlr_output_state *state) { + wlr_buffer_unlock(state->buffer); + // struct wlr_buffer is ref'counted, so the pointer may remain valid after + // wlr_buffer_unlock(). Reset the field to NULL to ensure nobody mistakenly + // reads it after output_state_finish(). + state->buffer = NULL; + pixman_region32_fini(&state->damage); + wlr_drm_syncobj_timeline_unref(state->wait_timeline); + wlr_drm_syncobj_timeline_unref(state->signal_timeline); + wlr_color_transform_unref(state->color_transform); + free(state->image_description); +} + +void wlr_output_state_set_enabled(struct wlr_output_state *state, + bool enabled) { + state->committed |= WLR_OUTPUT_STATE_ENABLED; + state->enabled = enabled; + state->allow_reconfiguration = true; +} + +void wlr_output_state_set_mode(struct wlr_output_state *state, + struct wlr_output_mode *mode) { + state->committed |= WLR_OUTPUT_STATE_MODE; + state->mode_type = WLR_OUTPUT_STATE_MODE_FIXED; + state->mode = mode; + state->allow_reconfiguration = true; +} + +void wlr_output_state_set_custom_mode(struct wlr_output_state *state, + int32_t width, int32_t height, int32_t refresh) { + state->committed |= WLR_OUTPUT_STATE_MODE; + state->mode_type = WLR_OUTPUT_STATE_MODE_CUSTOM; + state->custom_mode.width = width; + state->custom_mode.height = height; + state->custom_mode.refresh = refresh; + state->allow_reconfiguration = true; +} + +void wlr_output_state_set_scale(struct wlr_output_state *state, float scale) { + state->committed |= WLR_OUTPUT_STATE_SCALE; + state->scale = scale; +} + +void wlr_output_state_set_transform(struct wlr_output_state *state, + enum wl_output_transform transform) { + state->committed |= WLR_OUTPUT_STATE_TRANSFORM; + state->transform = transform; +} + +void wlr_output_state_set_adaptive_sync_enabled(struct wlr_output_state *state, + bool enabled) { + state->committed |= WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED; + state->adaptive_sync_enabled = enabled; +} + +void wlr_output_state_set_render_format(struct wlr_output_state *state, + uint32_t format) { + state->committed |= WLR_OUTPUT_STATE_RENDER_FORMAT; + state->render_format = format; +} + +void wlr_output_state_set_subpixel(struct wlr_output_state *state, + enum wl_output_subpixel subpixel) { + state->committed |= WLR_OUTPUT_STATE_SUBPIXEL; + state->subpixel = subpixel; +} + +void wlr_output_state_set_buffer(struct wlr_output_state *state, + struct wlr_buffer *buffer) { + state->committed |= WLR_OUTPUT_STATE_BUFFER; + wlr_buffer_unlock(state->buffer); + state->buffer = wlr_buffer_lock(buffer); +} + +void wlr_output_state_set_damage(struct wlr_output_state *state, + const pixman_region32_t *damage) { + state->committed |= WLR_OUTPUT_STATE_DAMAGE; + pixman_region32_copy(&state->damage, damage); +} + +void wlr_output_state_set_layers(struct wlr_output_state *state, + struct wlr_output_layer_state *layers, size_t layers_len) { + state->committed |= WLR_OUTPUT_STATE_LAYERS; + state->layers = layers; + state->layers_len = layers_len; +} + +void wlr_output_state_set_wait_timeline(struct wlr_output_state *state, + struct wlr_drm_syncobj_timeline *timeline, uint64_t src_point) { + state->committed |= WLR_OUTPUT_STATE_WAIT_TIMELINE; + wlr_drm_syncobj_timeline_unref(state->wait_timeline); + state->wait_timeline = wlr_drm_syncobj_timeline_ref(timeline); + state->wait_point = src_point; +} + +void wlr_output_state_set_signal_timeline(struct wlr_output_state *state, + struct wlr_drm_syncobj_timeline *timeline, uint64_t dst_point) { + state->committed |= WLR_OUTPUT_STATE_SIGNAL_TIMELINE; + wlr_drm_syncobj_timeline_unref(state->signal_timeline); + state->signal_timeline = wlr_drm_syncobj_timeline_ref(timeline); + state->signal_point = dst_point; +} + +void wlr_output_state_set_color_transform(struct wlr_output_state *state, + struct wlr_color_transform *tr) { + state->committed |= WLR_OUTPUT_STATE_COLOR_TRANSFORM; + wlr_color_transform_unref(state->color_transform); + if (tr) { + state->color_transform = wlr_color_transform_ref(tr); + } else { + state->color_transform = NULL; + } +} + +bool wlr_output_state_set_image_description(struct wlr_output_state *state, + const struct wlr_output_image_description *image_desc) { + struct wlr_output_image_description *copy = NULL; + if (image_desc != NULL) { + copy = malloc(sizeof(*copy)); + if (copy == NULL) { + return false; + } + *copy = *image_desc; + } + + state->committed |= WLR_OUTPUT_STATE_IMAGE_DESCRIPTION; + free(state->image_description); + state->image_description = copy; + return true; +} + +bool wlr_output_state_copy(struct wlr_output_state *dst, + const struct wlr_output_state *src) { + struct wlr_output_state copy = *src; + copy.committed &= ~(WLR_OUTPUT_STATE_BUFFER | + WLR_OUTPUT_STATE_DAMAGE | + WLR_OUTPUT_STATE_WAIT_TIMELINE | + WLR_OUTPUT_STATE_SIGNAL_TIMELINE | + WLR_OUTPUT_STATE_COLOR_TRANSFORM | + WLR_OUTPUT_STATE_IMAGE_DESCRIPTION); + copy.buffer = NULL; + copy.buffer_src_box = (struct wlr_fbox){0}; + copy.buffer_dst_box = (struct wlr_box){0}; + pixman_region32_init(©.damage); + copy.wait_timeline = NULL; + copy.signal_timeline = NULL; + copy.color_transform = NULL; + copy.image_description = NULL; + + if (src->committed & WLR_OUTPUT_STATE_BUFFER) { + wlr_output_state_set_buffer(©, src->buffer); + copy.buffer_src_box = src->buffer_src_box; + copy.buffer_dst_box = src->buffer_dst_box; + } + + if (src->committed & WLR_OUTPUT_STATE_DAMAGE) { + wlr_output_state_set_damage(©, &src->damage); + } + + if (src->committed & WLR_OUTPUT_STATE_WAIT_TIMELINE) { + wlr_output_state_set_wait_timeline(©, src->wait_timeline, + src->wait_point); + } + if (src->committed & WLR_OUTPUT_STATE_SIGNAL_TIMELINE) { + wlr_output_state_set_signal_timeline(©, src->signal_timeline, + src->signal_point); + } + + if (src->committed & WLR_OUTPUT_STATE_COLOR_TRANSFORM) { + wlr_output_state_set_color_transform(©, src->color_transform); + } + if (src->committed & WLR_OUTPUT_STATE_IMAGE_DESCRIPTION) { + if (!wlr_output_state_set_image_description(©, src->image_description)) { + goto err; + } + } + + wlr_output_state_finish(dst); + *dst = copy; + return true; + +err: + wlr_output_state_finish(dst); + return false; +} diff --git a/3rdparty/wlroots/types/output/swapchain.c b/3rdparty/wlroots/types/output/swapchain.c new file mode 100644 index 0000000000..01857a204d --- /dev/null +++ b/3rdparty/wlroots/types/output/swapchain.c @@ -0,0 +1,118 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "render/drm_format_set.h" +#include "types/wlr_output.h" + +static struct wlr_swapchain *create_swapchain(struct wlr_output *output, + int width, int height, uint32_t render_format, bool allow_modifiers) { + struct wlr_allocator *allocator = output->allocator; + assert(output->allocator != NULL); + + const struct wlr_drm_format_set *display_formats = + wlr_output_get_primary_formats(output, allocator->buffer_caps); + struct wlr_drm_format format = {0}; + if (!output_pick_format(output, display_formats, &format, render_format)) { + wlr_log(WLR_ERROR, "Failed to pick primary buffer format for output '%s'", + output->name); + return NULL; + } + + char *format_name = drmGetFormatName(format.format); + wlr_log(WLR_DEBUG, "Choosing primary buffer format %s (0x%08"PRIX32") for output '%s'", + format_name ? format_name : "", format.format, output->name); + free(format_name); + + if (!allow_modifiers && (format.len != 1 || format.modifiers[0] != DRM_FORMAT_MOD_LINEAR)) { + if (!wlr_drm_format_has(&format, DRM_FORMAT_MOD_INVALID)) { + wlr_log(WLR_DEBUG, "Implicit modifiers not supported"); + wlr_drm_format_finish(&format); + return NULL; + } + + format.len = 0; + if (!wlr_drm_format_add(&format, DRM_FORMAT_MOD_INVALID)) { + wlr_log(WLR_DEBUG, "Failed to add implicit modifier to format"); + wlr_drm_format_finish(&format); + return NULL; + } + } + + struct wlr_swapchain *swapchain = wlr_swapchain_create(allocator, width, height, &format); + wlr_drm_format_finish(&format); + return swapchain; +} + +static bool test_swapchain(struct wlr_output *output, + struct wlr_swapchain *swapchain, const struct wlr_output_state *state) { + struct wlr_buffer *buffer = wlr_swapchain_acquire(swapchain); + if (buffer == NULL) { + return false; + } + + struct wlr_output_state copy = *state; + copy.committed |= WLR_OUTPUT_STATE_BUFFER; + copy.buffer = buffer; + bool ok = wlr_output_test_state(output, ©); + wlr_buffer_unlock(buffer); + return ok; +} + +bool wlr_output_configure_primary_swapchain(struct wlr_output *output, + const struct wlr_output_state *state, struct wlr_swapchain **swapchain_ptr) { + struct wlr_output_state empty_state; + if (state == NULL) { + wlr_output_state_init(&empty_state); + state = &empty_state; + } + + int width, height; + output_pending_resolution(output, state, &width, &height); + + uint32_t format = output->render_format; + if (state->committed & WLR_OUTPUT_STATE_RENDER_FORMAT) { + format = state->render_format; + } + + // Re-use the existing swapchain if possible + struct wlr_swapchain *old_swapchain = *swapchain_ptr; + if (old_swapchain != NULL && + old_swapchain->width == width && old_swapchain->height == height && + old_swapchain->format.format == format) { + return true; + } + + struct wlr_swapchain *swapchain = create_swapchain(output, width, height, format, true); + if (swapchain == NULL) { + wlr_log(WLR_ERROR, "Failed to create swapchain for output '%s'", output->name); + return false; + } + + wlr_log(WLR_DEBUG, "Testing swapchain for output '%s'", output->name); + if (!test_swapchain(output, swapchain, state)) { + wlr_log(WLR_DEBUG, "Output test failed on '%s', retrying without modifiers", + output->name); + wlr_swapchain_destroy(swapchain); + swapchain = create_swapchain(output, width, height, format, false); + if (swapchain == NULL) { + wlr_log(WLR_ERROR, "Failed to create modifier-less swapchain for output '%s'", + output->name); + return false; + } + wlr_log(WLR_DEBUG, "Testing modifier-less swapchain for output '%s'", output->name); + if (!test_swapchain(output, swapchain, state)) { + wlr_log(WLR_ERROR, "Swapchain for output '%s' failed test", output->name); + wlr_swapchain_destroy(swapchain); + return false; + } + } + + wlr_swapchain_destroy(*swapchain_ptr); + *swapchain_ptr = swapchain; + return true; +} diff --git a/3rdparty/wlroots/types/scene/drag_icon.c b/3rdparty/wlroots/types/scene/drag_icon.c new file mode 100644 index 0000000000..84b202c3df --- /dev/null +++ b/3rdparty/wlroots/types/scene/drag_icon.c @@ -0,0 +1,71 @@ +#include +#include "wlr/types/wlr_compositor.h" +#include +#include + +struct wlr_scene_drag_icon { + struct wlr_scene_tree *tree; + struct wlr_scene_tree *surface_tree; + struct wlr_drag_icon *drag_icon; + + struct wl_listener tree_destroy; + struct wl_listener drag_icon_surface_commit; + struct wl_listener drag_icon_destroy; +}; + +static void drag_icon_handle_surface_commit(struct wl_listener *listener, void *data) { + struct wlr_scene_drag_icon *icon = + wl_container_of(listener, icon, drag_icon_surface_commit); + struct wlr_surface *surface = icon->drag_icon->surface; + struct wlr_scene_node *node = &icon->surface_tree->node; + wlr_scene_node_set_position(node, + node->x + surface->current.dx, node->y + surface->current.dy); +} + +static void drag_icon_handle_tree_destroy(struct wl_listener *listener, void *data) { + struct wlr_scene_drag_icon *icon = + wl_container_of(listener, icon, tree_destroy); + wl_list_remove(&icon->tree_destroy.link); + wl_list_remove(&icon->drag_icon_surface_commit.link); + wl_list_remove(&icon->drag_icon_destroy.link); + free(icon); +} + +static void drag_icon_handle_destroy(struct wl_listener *listener, void *data) { + struct wlr_scene_drag_icon *icon = + wl_container_of(listener, icon, drag_icon_destroy); + wlr_scene_node_destroy(&icon->tree->node); +} + +struct wlr_scene_tree *wlr_scene_drag_icon_create( + struct wlr_scene_tree *parent, struct wlr_drag_icon *drag_icon) { + struct wlr_scene_drag_icon *icon = calloc(1, sizeof(*icon)); + if (!icon) { + return NULL; + } + + icon->drag_icon = drag_icon; + + icon->tree = wlr_scene_tree_create(parent); + if (!icon->tree) { + free(icon); + return NULL; + } + + icon->surface_tree = wlr_scene_subsurface_tree_create( + icon->tree, drag_icon->surface); + if (!icon->surface_tree) { + wlr_scene_node_destroy(&icon->tree->node); + free(icon); + return NULL; + } + + icon->tree_destroy.notify = drag_icon_handle_tree_destroy; + wl_signal_add(&icon->tree->node.events.destroy, &icon->tree_destroy); + icon->drag_icon_surface_commit.notify = drag_icon_handle_surface_commit; + wl_signal_add(&drag_icon->surface->events.commit, &icon->drag_icon_surface_commit); + icon->drag_icon_destroy.notify = drag_icon_handle_destroy; + wl_signal_add(&drag_icon->events.destroy, &icon->drag_icon_destroy); + + return icon->tree; +} diff --git a/3rdparty/wlroots/types/scene/layer_shell_v1.c b/3rdparty/wlroots/types/scene/layer_shell_v1.c new file mode 100644 index 0000000000..234227df10 --- /dev/null +++ b/3rdparty/wlroots/types/scene/layer_shell_v1.c @@ -0,0 +1,153 @@ +#include +#include +#include +#include + +static void scene_layer_surface_handle_tree_destroy( + struct wl_listener *listener, void *data) { + struct wlr_scene_layer_surface_v1 *scene_layer_surface = + wl_container_of(listener, scene_layer_surface, tree_destroy); + // tree and surface_node will be cleaned up by scene_node_finish + wl_list_remove(&scene_layer_surface->tree_destroy.link); + wl_list_remove(&scene_layer_surface->layer_surface_destroy.link); + free(scene_layer_surface); +} + +static void scene_layer_surface_handle_layer_surface_destroy( + struct wl_listener *listener, void *data) { + struct wlr_scene_layer_surface_v1 *scene_layer_surface = + wl_container_of(listener, scene_layer_surface, layer_surface_destroy); + wlr_scene_node_destroy(&scene_layer_surface->tree->node); +} + +static void layer_surface_exclusive_zone( + struct wlr_layer_surface_v1_state *state, + enum wlr_edges edge, + struct wlr_box *usable_area) { + switch (edge) { + case WLR_EDGE_NONE: + return; + case WLR_EDGE_TOP: + usable_area->y += state->exclusive_zone + state->margin.top; + usable_area->height -= state->exclusive_zone + state->margin.top; + break; + case WLR_EDGE_BOTTOM: + usable_area->height -= state->exclusive_zone + state->margin.bottom; + break; + case WLR_EDGE_LEFT: + usable_area->x += state->exclusive_zone + state->margin.left; + usable_area->width -= state->exclusive_zone + state->margin.left; + break; + case WLR_EDGE_RIGHT: + usable_area->width -= state->exclusive_zone + state->margin.right; + break; + } + + if (usable_area->width < 0) { + usable_area->width = 0; + } + if (usable_area->height < 0) { + usable_area->height = 0; + } +} + +void wlr_scene_layer_surface_v1_configure( + struct wlr_scene_layer_surface_v1 *scene_layer_surface, + const struct wlr_box *full_area, struct wlr_box *usable_area) { + struct wlr_layer_surface_v1 *layer_surface = + scene_layer_surface->layer_surface; + struct wlr_layer_surface_v1_state *state = &layer_surface->current; + + // If the exclusive zone is set to -1, the layer surface will use the + // full area of the output, otherwise it is constrained to the + // remaining usable area. + struct wlr_box bounds; + if (state->exclusive_zone == -1) { + bounds = *full_area; + } else { + bounds = *usable_area; + } + + struct wlr_box box = { + .width = state->desired_width, + .height = state->desired_height, + }; + + // Horizontal positioning + if (box.width == 0) { + box.x = bounds.x + state->margin.left; + box.width = bounds.width - + (state->margin.left + state->margin.right); + } else if (state->anchor & ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT && + state->anchor & ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT) { + box.x = bounds.x + bounds.width/2 -box.width/2; + } else if (state->anchor & ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT) { + box.x = bounds.x + state->margin.left; + } else if (state->anchor & ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT) { + box.x = bounds.x + bounds.width - box.width - state->margin.right; + } else { + box.x = bounds.x + bounds.width/2 - box.width/2; + } + + // Vertical positioning + if (box.height == 0) { + box.y = bounds.y + state->margin.top; + box.height = bounds.height - + (state->margin.top + state->margin.bottom); + } else if (state->anchor & ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP && + state->anchor & ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM) { + box.y = bounds.y + bounds.height/2 - box.height/2; + } else if (state->anchor & ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP) { + box.y = bounds.y + state->margin.top; + } else if (state->anchor & ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM) { + box.y = bounds.y + bounds.height - box.height - state->margin.bottom; + } else { + box.y = bounds.y + bounds.height/2 - box.height/2; + } + + wlr_scene_node_set_position(&scene_layer_surface->tree->node, box.x, box.y); + wlr_layer_surface_v1_configure(layer_surface, box.width, box.height); + + if (layer_surface->surface->mapped && state->exclusive_zone > 0) { + enum wlr_edges edge = wlr_layer_surface_v1_get_exclusive_edge(layer_surface); + layer_surface_exclusive_zone(state, edge, usable_area); + } +} + +struct wlr_scene_layer_surface_v1 *wlr_scene_layer_surface_v1_create( + struct wlr_scene_tree *parent, + struct wlr_layer_surface_v1 *layer_surface) { + struct wlr_scene_layer_surface_v1 *scene_layer_surface = + calloc(1, sizeof(*scene_layer_surface)); + if (scene_layer_surface == NULL) { + return NULL; + } + + scene_layer_surface->layer_surface = layer_surface; + + scene_layer_surface->tree = wlr_scene_tree_create(parent); + if (scene_layer_surface->tree == NULL) { + free(scene_layer_surface); + return NULL; + } + + struct wlr_scene_tree *surface_tree = wlr_scene_subsurface_tree_create( + scene_layer_surface->tree, layer_surface->surface); + if (surface_tree == NULL) { + wlr_scene_node_destroy(&scene_layer_surface->tree->node); + free(scene_layer_surface); + return NULL; + } + + scene_layer_surface->tree_destroy.notify = + scene_layer_surface_handle_tree_destroy; + wl_signal_add(&scene_layer_surface->tree->node.events.destroy, + &scene_layer_surface->tree_destroy); + + scene_layer_surface->layer_surface_destroy.notify = + scene_layer_surface_handle_layer_surface_destroy; + wl_signal_add(&layer_surface->events.destroy, + &scene_layer_surface->layer_surface_destroy); + + return scene_layer_surface; +} diff --git a/3rdparty/wlroots/types/scene/output_layout.c b/3rdparty/wlroots/types/scene/output_layout.c new file mode 100644 index 0000000000..88185904ef --- /dev/null +++ b/3rdparty/wlroots/types/scene/output_layout.c @@ -0,0 +1,141 @@ +#include +#include +#include +#include + +struct wlr_scene_output_layout { + struct wlr_output_layout *layout; + struct wlr_scene *scene; + + struct wl_list outputs; // wlr_scene_output_layout_output.link + + struct wl_listener layout_change; + struct wl_listener layout_destroy; + struct wl_listener scene_destroy; +}; + +struct wlr_scene_output_layout_output { + struct wlr_output_layout_output *layout_output; + struct wlr_scene_output *scene_output; + + struct wl_list link; // wlr_scene_output_layout.outputs + + struct wl_listener layout_output_destroy; + struct wl_listener scene_output_destroy; +}; + +static void scene_output_layout_output_destroy( + struct wlr_scene_output_layout_output *solo) { + wl_list_remove(&solo->layout_output_destroy.link); + wl_list_remove(&solo->scene_output_destroy.link); + wl_list_remove(&solo->link); + free(solo); +} + +static void scene_output_layout_output_handle_layout_output_destroy( + struct wl_listener *listener, void *data) { + struct wlr_scene_output_layout_output *solo = + wl_container_of(listener, solo, layout_output_destroy); + scene_output_layout_output_destroy(solo); +} + +static void scene_output_layout_output_handle_scene_output_destroy( + struct wl_listener *listener, void *data) { + struct wlr_scene_output_layout_output *solo = + wl_container_of(listener, solo, scene_output_destroy); + scene_output_layout_output_destroy(solo); +} + +static void scene_output_layout_destroy(struct wlr_scene_output_layout *sol) { + struct wlr_scene_output_layout_output *solo, *tmp; + wl_list_for_each_safe(solo, tmp, &sol->outputs, link) { + scene_output_layout_output_destroy(solo); + } + wl_list_remove(&sol->layout_change.link); + wl_list_remove(&sol->layout_destroy.link); + wl_list_remove(&sol->scene_destroy.link); + free(sol); +} + +static void scene_output_layout_handle_layout_change( + struct wl_listener *listener, void *data) { + struct wlr_scene_output_layout *sol = + wl_container_of(listener, sol, layout_change); + + struct wlr_scene_output_layout_output *solo; + wl_list_for_each(solo, &sol->outputs, link) { + wlr_scene_output_set_position(solo->scene_output, + solo->layout_output->x, solo->layout_output->y); + } +} + +void wlr_scene_output_layout_add_output(struct wlr_scene_output_layout *sol, + struct wlr_output_layout_output *lo, struct wlr_scene_output *so) { + assert(lo->output == so->output); + + struct wlr_scene_output_layout_output *solo; + wl_list_for_each(solo, &sol->outputs, link) { + if (solo->scene_output == so) { + return; + } + } + + solo = calloc(1, sizeof(*solo)); + if (solo == NULL) { + return; + } + + solo->scene_output = so; + solo->layout_output = lo; + + solo->layout_output_destroy.notify = + scene_output_layout_output_handle_layout_output_destroy; + wl_signal_add(&lo->events.destroy, &solo->layout_output_destroy); + + solo->scene_output_destroy.notify = + scene_output_layout_output_handle_scene_output_destroy; + wl_signal_add(&solo->scene_output->events.destroy, + &solo->scene_output_destroy); + + wl_list_insert(&sol->outputs, &solo->link); + + wlr_scene_output_set_position(solo->scene_output, lo->x, lo->y); +} + +static void scene_output_layout_handle_layout_destroy( + struct wl_listener *listener, void *data) { + struct wlr_scene_output_layout *sol = + wl_container_of(listener, sol, layout_destroy); + scene_output_layout_destroy(sol); +} + +static void scene_output_layout_handle_scene_destroy( + struct wl_listener *listener, void *data) { + struct wlr_scene_output_layout *sol = + wl_container_of(listener, sol, scene_destroy); + scene_output_layout_destroy(sol); +} + +struct wlr_scene_output_layout *wlr_scene_attach_output_layout(struct wlr_scene *scene, + struct wlr_output_layout *output_layout) { + struct wlr_scene_output_layout *sol = calloc(1, sizeof(*sol)); + if (sol == NULL) { + return NULL; + } + + sol->scene = scene; + sol->layout = output_layout; + + wl_list_init(&sol->outputs); + + sol->layout_destroy.notify = scene_output_layout_handle_layout_destroy; + wl_signal_add(&output_layout->events.destroy, &sol->layout_destroy); + + sol->layout_change.notify = scene_output_layout_handle_layout_change; + wl_signal_add(&output_layout->events.change, &sol->layout_change); + + sol->scene_destroy.notify = scene_output_layout_handle_scene_destroy; + wl_signal_add(&scene->tree.node.events.destroy, &sol->scene_destroy); + + return sol; +} diff --git a/3rdparty/wlroots/types/scene/subsurface_tree.c b/3rdparty/wlroots/types/scene/subsurface_tree.c new file mode 100644 index 0000000000..4e0a3f9990 --- /dev/null +++ b/3rdparty/wlroots/types/scene/subsurface_tree.c @@ -0,0 +1,370 @@ +#include +#include +#include +#include +#include +#include +#include "types/wlr_scene.h" + +/** + * A tree for a surface and all of its child sub-surfaces. + * + * `tree` contains `scene_surface` and one node per sub-surface. + */ +struct wlr_scene_subsurface_tree { + struct wlr_scene_tree *tree; + struct wlr_surface *surface; + struct wlr_scene_surface *scene_surface; + + struct wl_listener surface_destroy; + struct wl_listener surface_commit; + struct wl_listener surface_map; + struct wl_listener surface_unmap; + struct wl_listener surface_new_subsurface; + + struct wlr_scene_subsurface_tree *parent; // NULL for the top-level surface + + struct wlr_addon scene_addon; + + struct wlr_box clip; + + // Only valid if the surface is a sub-surface + + struct wlr_addon surface_addon; + + struct wl_listener subsurface_destroy; +}; + +static void subsurface_tree_addon_destroy(struct wlr_addon *addon) { + struct wlr_scene_subsurface_tree *subsurface_tree = + wl_container_of(addon, subsurface_tree, scene_addon); + // tree and scene_surface will be cleaned up by scene_node_finish + if (subsurface_tree->parent) { + wlr_addon_finish(&subsurface_tree->surface_addon); + wl_list_remove(&subsurface_tree->subsurface_destroy.link); + } + wlr_addon_finish(&subsurface_tree->scene_addon); + wl_list_remove(&subsurface_tree->surface_destroy.link); + wl_list_remove(&subsurface_tree->surface_commit.link); + wl_list_remove(&subsurface_tree->surface_map.link); + wl_list_remove(&subsurface_tree->surface_unmap.link); + wl_list_remove(&subsurface_tree->surface_new_subsurface.link); + free(subsurface_tree); +} + +static const struct wlr_addon_interface subsurface_tree_surface_addon_impl; + +static struct wlr_scene_subsurface_tree *subsurface_tree_from_subsurface( + struct wlr_scene_subsurface_tree *parent, + struct wlr_subsurface *subsurface) { + struct wlr_addon *addon = wlr_addon_find(&subsurface->surface->addons, + parent, &subsurface_tree_surface_addon_impl); + assert(addon != NULL); + struct wlr_scene_subsurface_tree *subsurface_tree = + wl_container_of(addon, subsurface_tree, surface_addon); + return subsurface_tree; +} + +static bool subsurface_tree_reconfigure_clip( + struct wlr_scene_subsurface_tree *subsurface_tree) { + if (subsurface_tree->parent) { + subsurface_tree->clip = (struct wlr_box){ + .x = subsurface_tree->parent->clip.x - subsurface_tree->tree->node.x, + .y = subsurface_tree->parent->clip.y - subsurface_tree->tree->node.y, + .width = subsurface_tree->parent->clip.width, + .height = subsurface_tree->parent->clip.height, + }; + } + + if (wlr_box_empty(&subsurface_tree->clip)) { + scene_surface_set_clip(subsurface_tree->scene_surface, NULL); + wlr_scene_node_set_enabled(&subsurface_tree->scene_surface->buffer->node, true); + wlr_scene_node_set_position(&subsurface_tree->scene_surface->buffer->node, 0, 0); + + return false; + } else { + struct wlr_box clip = subsurface_tree->clip; + struct wlr_box surface_box = { + .width = subsurface_tree->surface->current.width, + .height = subsurface_tree->surface->current.height, + }; + + bool intersects = wlr_box_intersection(&clip, &clip, &surface_box); + wlr_scene_node_set_enabled(&subsurface_tree->scene_surface->buffer->node, intersects); + + if (intersects) { + wlr_scene_node_set_position(&subsurface_tree->scene_surface->buffer->node, clip.x, clip.y); + scene_surface_set_clip(subsurface_tree->scene_surface, &clip); + } + + return true; + } +} + +static void subsurface_tree_reconfigure( + struct wlr_scene_subsurface_tree *subsurface_tree) { + bool has_clip = subsurface_tree_reconfigure_clip(subsurface_tree); + + struct wlr_surface *surface = subsurface_tree->surface; + + struct wlr_scene_node *prev = NULL; + struct wlr_subsurface *subsurface; + wl_list_for_each(subsurface, &surface->current.subsurfaces_below, + current.link) { + struct wlr_scene_subsurface_tree *child = + subsurface_tree_from_subsurface(subsurface_tree, subsurface); + if (prev != NULL) { + wlr_scene_node_place_above(&child->tree->node, prev); + } + prev = &child->tree->node; + + wlr_scene_node_set_position(&child->tree->node, + subsurface->current.x, subsurface->current.y); + + if (has_clip) { + subsurface_tree_reconfigure_clip(child); + } + } + + if (prev != NULL) { + wlr_scene_node_place_above(&subsurface_tree->scene_surface->buffer->node, prev); + } + prev = &subsurface_tree->scene_surface->buffer->node; + + wl_list_for_each(subsurface, &surface->current.subsurfaces_above, + current.link) { + struct wlr_scene_subsurface_tree *child = + subsurface_tree_from_subsurface(subsurface_tree, subsurface); + wlr_scene_node_place_above(&child->tree->node, prev); + prev = &child->tree->node; + + wlr_scene_node_set_position(&child->tree->node, + subsurface->current.x, subsurface->current.y); + + if (has_clip) { + subsurface_tree_reconfigure_clip(child); + } + } +} + +static void subsurface_tree_handle_surface_destroy(struct wl_listener *listener, + void *data) { + struct wlr_scene_subsurface_tree *subsurface_tree = + wl_container_of(listener, subsurface_tree, surface_destroy); + wlr_scene_node_destroy(&subsurface_tree->tree->node); +} + +static void subsurface_tree_handle_surface_commit(struct wl_listener *listener, + void *data) { + struct wlr_scene_subsurface_tree *subsurface_tree = + wl_container_of(listener, subsurface_tree, surface_commit); + + // TODO: only do this on subsurface order or position change + subsurface_tree_reconfigure(subsurface_tree); +} + +static void subsurface_tree_handle_subsurface_destroy(struct wl_listener *listener, + void *data) { + struct wlr_scene_subsurface_tree *subsurface_tree = + wl_container_of(listener, subsurface_tree, subsurface_destroy); + wlr_scene_node_destroy(&subsurface_tree->tree->node); +} + +static void subsurface_tree_handle_surface_map(struct wl_listener *listener, + void *data) { + struct wlr_scene_subsurface_tree *subsurface_tree = + wl_container_of(listener, subsurface_tree, surface_map); + + wlr_scene_node_set_enabled(&subsurface_tree->tree->node, true); +} + +static void subsurface_tree_handle_surface_unmap(struct wl_listener *listener, + void *data) { + struct wlr_scene_subsurface_tree *subsurface_tree = + wl_container_of(listener, subsurface_tree, surface_unmap); + + wlr_scene_node_set_enabled(&subsurface_tree->tree->node, false); +} + +static void subsurface_tree_surface_addon_destroy(struct wlr_addon *addon) { + struct wlr_scene_subsurface_tree *subsurface_tree = + wl_container_of(addon, subsurface_tree, surface_addon); + wlr_scene_node_destroy(&subsurface_tree->tree->node); +} + +static const struct wlr_addon_interface subsurface_tree_surface_addon_impl = { + .name = "wlr_scene_subsurface_tree", + .destroy = subsurface_tree_surface_addon_destroy, +}; + +static struct wlr_scene_subsurface_tree *scene_surface_tree_create( + struct wlr_scene_tree *parent, struct wlr_surface *surface); + +static bool subsurface_tree_create_subsurface( + struct wlr_scene_subsurface_tree *parent, + struct wlr_subsurface *subsurface) { + struct wlr_scene_subsurface_tree *child = scene_surface_tree_create( + parent->tree, subsurface->surface); + if (child == NULL) { + return false; + } + + child->parent = parent; + + wlr_addon_init(&child->surface_addon, &subsurface->surface->addons, + parent, &subsurface_tree_surface_addon_impl); + + child->subsurface_destroy.notify = subsurface_tree_handle_subsurface_destroy; + wl_signal_add(&subsurface->events.destroy, &child->subsurface_destroy); + + return true; +} + +static void subsurface_tree_handle_surface_new_subsurface( + struct wl_listener *listener, void *data) { + struct wlr_scene_subsurface_tree *subsurface_tree = + wl_container_of(listener, subsurface_tree, surface_new_subsurface); + struct wlr_subsurface *subsurface = data; + if (!subsurface_tree_create_subsurface(subsurface_tree, subsurface)) { + wl_resource_post_no_memory(subsurface->resource); + } +} + +static const struct wlr_addon_interface subsurface_tree_addon_impl = { + .name = "wlr_scene_subsurface_tree", + .destroy = subsurface_tree_addon_destroy, +}; + +static struct wlr_scene_subsurface_tree *scene_surface_tree_create( + struct wlr_scene_tree *parent, struct wlr_surface *surface) { + struct wlr_scene_subsurface_tree *subsurface_tree = + calloc(1, sizeof(*subsurface_tree)); + if (subsurface_tree == NULL) { + return NULL; + } + + subsurface_tree->tree = wlr_scene_tree_create(parent); + if (subsurface_tree->tree == NULL) { + goto error_surface_tree; + } + + subsurface_tree->scene_surface = + wlr_scene_surface_create(subsurface_tree->tree, surface); + if (subsurface_tree->scene_surface == NULL) { + goto error_scene_surface; + } + + subsurface_tree->surface = surface; + + struct wlr_subsurface *subsurface; + wl_list_for_each(subsurface, &surface->current.subsurfaces_below, + current.link) { + if (!subsurface_tree_create_subsurface(subsurface_tree, subsurface)) { + goto error_scene_surface; + } + } + wl_list_for_each(subsurface, &surface->current.subsurfaces_above, + current.link) { + if (!subsurface_tree_create_subsurface(subsurface_tree, subsurface)) { + goto error_scene_surface; + } + } + + subsurface_tree_reconfigure(subsurface_tree); + + wlr_addon_init(&subsurface_tree->scene_addon, &subsurface_tree->tree->node.addons, + NULL, &subsurface_tree_addon_impl); + + subsurface_tree->surface_destroy.notify = subsurface_tree_handle_surface_destroy; + wl_signal_add(&surface->events.destroy, &subsurface_tree->surface_destroy); + + subsurface_tree->surface_commit.notify = subsurface_tree_handle_surface_commit; + wl_signal_add(&surface->events.commit, &subsurface_tree->surface_commit); + + subsurface_tree->surface_map.notify = subsurface_tree_handle_surface_map; + wl_signal_add(&surface->events.map, &subsurface_tree->surface_map); + + subsurface_tree->surface_unmap.notify = subsurface_tree_handle_surface_unmap; + wl_signal_add(&surface->events.unmap, &subsurface_tree->surface_unmap); + + subsurface_tree->surface_new_subsurface.notify = + subsurface_tree_handle_surface_new_subsurface; + wl_signal_add(&surface->events.new_subsurface, + &subsurface_tree->surface_new_subsurface); + + wlr_scene_node_set_enabled(&subsurface_tree->tree->node, surface->mapped); + + return subsurface_tree; + +error_scene_surface: + wlr_scene_node_destroy(&subsurface_tree->tree->node); +error_surface_tree: + free(subsurface_tree); + return NULL; +} + +struct wlr_scene_tree *wlr_scene_subsurface_tree_create( + struct wlr_scene_tree *parent, struct wlr_surface *surface) { + struct wlr_scene_subsurface_tree *subsurface_tree = + scene_surface_tree_create(parent, surface); + if (subsurface_tree == NULL) { + return NULL; + } + return subsurface_tree->tree; +} + +static struct wlr_scene_subsurface_tree *get_subsurface_tree_from_node( + struct wlr_scene_node *node) { + struct wlr_addon *addon = wlr_addon_find(&node->addons, NULL, &subsurface_tree_addon_impl); + if (!addon) { + return NULL; + } + + struct wlr_scene_subsurface_tree *tree = + wl_container_of(addon, tree, scene_addon); + return tree; +} + +static bool subsurface_tree_set_clip(struct wlr_scene_node *node, + const struct wlr_box *clip) { + if (node->type != WLR_SCENE_NODE_TREE) { + return false; + } + + bool discovered_subsurface_tree = false; + struct wlr_scene_subsurface_tree *tree = get_subsurface_tree_from_node(node); + if (tree) { + if (tree->parent == NULL) { + if (wlr_box_equal(&tree->clip, clip)) { + return true; + } + + if (clip) { + tree->clip = *clip; + } else { + tree->clip = (struct wlr_box){0}; + } + } + + discovered_subsurface_tree = true; + subsurface_tree_reconfigure_clip(tree); + } + + struct wlr_scene_tree *scene_tree = wlr_scene_tree_from_node(node); + struct wlr_scene_node *child; + wl_list_for_each(child, &scene_tree->children, link) { + discovered_subsurface_tree |= subsurface_tree_set_clip(child, clip); + } + + return discovered_subsurface_tree; +} + +void wlr_scene_subsurface_tree_set_clip(struct wlr_scene_node *node, + const struct wlr_box *clip) { +#ifndef NDEBUG + bool found = +#endif + subsurface_tree_set_clip(node, clip); + + assert(found); +} diff --git a/3rdparty/wlroots/types/scene/surface.c b/3rdparty/wlroots/types/scene/surface.c new file mode 100644 index 0000000000..1aceeba8ba --- /dev/null +++ b/3rdparty/wlroots/types/scene/surface.c @@ -0,0 +1,493 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_scene.h" + +#include + +#if WLR_HAS_XWAYLAND +#include +#endif + +static double get_surface_preferred_buffer_scale(struct wlr_surface *surface) { + double scale = 1; + struct wlr_surface_output *surface_output; + wl_list_for_each(surface_output, &surface->current_outputs, link) { + if (surface_output->output->scale > scale) { + scale = surface_output->output->scale; + } + } + return scale; +} + +// Output used for frame pacing (surface frame callbacks, presentation +// time feedback, etc), may be NULL +static struct wlr_output *get_surface_frame_pacing_output(struct wlr_surface *surface) { + struct wlr_output *frame_pacing_output = NULL; + struct wlr_surface_output *surface_output; + wl_list_for_each(surface_output, &surface->current_outputs, link) { + if (!surface_output->suspended && (frame_pacing_output == NULL || + surface_output->output->refresh > frame_pacing_output->refresh)) { + frame_pacing_output = surface_output->output; + } + } + return frame_pacing_output; +} + +static int get_tf_preference(enum wlr_color_transfer_function tf) { + switch (tf) { + case WLR_COLOR_TRANSFER_FUNCTION_GAMMA22: + return 0; + case WLR_COLOR_TRANSFER_FUNCTION_ST2084_PQ: + return 1; + case WLR_COLOR_TRANSFER_FUNCTION_BT1886: + case WLR_COLOR_TRANSFER_FUNCTION_SRGB: + case WLR_COLOR_TRANSFER_FUNCTION_EXT_LINEAR: + return -1; + } + abort(); // unreachable +} + +static int get_primaries_preference(enum wlr_color_named_primaries primaries) { + switch (primaries) { + case WLR_COLOR_NAMED_PRIMARIES_SRGB: + return 0; + case WLR_COLOR_NAMED_PRIMARIES_BT2020: + return 1; + } + abort(); // unreachable +} + +static void get_surface_preferred_image_description(struct wlr_surface *surface, + struct wlr_image_description_v1_data *out) { + struct wlr_output_image_description preferred = { + .transfer_function = WLR_COLOR_TRANSFER_FUNCTION_GAMMA22, + .primaries = WLR_COLOR_NAMED_PRIMARIES_SRGB, + }; + + struct wlr_surface_output *surface_output; + wl_list_for_each(surface_output, &surface->current_outputs, link) { + const struct wlr_output_image_description *img_desc = + surface_output->output->image_description; + if (img_desc == NULL) { + continue; + } + if (get_tf_preference(preferred.transfer_function) < get_tf_preference(img_desc->transfer_function)) { + preferred.transfer_function = img_desc->transfer_function; + } + if (get_primaries_preference(preferred.primaries) < get_primaries_preference(img_desc->primaries)) { + preferred.primaries = img_desc->primaries; + } + } + + *out = (struct wlr_image_description_v1_data){ + .tf_named = wlr_color_manager_v1_transfer_function_from_wlr(preferred.transfer_function), + .primaries_named = wlr_color_manager_v1_primaries_from_wlr(preferred.primaries), + }; +} + +static void handle_scene_buffer_outputs_update( + struct wl_listener *listener, void *data) { + struct wlr_scene_surface *surface = + wl_container_of(listener, surface, outputs_update); + struct wlr_scene_outputs_update_event *event = data; + struct wlr_scene *scene = scene_node_get_root(&surface->buffer->node); + + // If the surface is no longer visible on any output in the scene, keep the + // last sent preferred configuration to avoid unnecessary redraws + bool suspend = event->size == 0; + + // To avoid sending redundant leave/enter events when a surface is hidden and then shown + // without moving to a different output the following policy is implemented: + // + // 1. When a surface transitions from being visible on >0 outputs to being visible on 0 outputs + // don't send any leave events. + // + // 2. When a surface transitions from being visible on 0 outputs to being visible on >0 outputs + // send leave events for all entered outputs on which the surface is no longer visible as + // well as enter events for any outputs not already entered. + struct wlr_surface_output *entered_output, *tmp; + wl_list_for_each_safe(entered_output, tmp, &surface->surface->current_outputs, link) { + bool active = false; + for (size_t i = 0; i < event->size; i++) { + if (entered_output->output == event->active[i]->output) { + active = true; + break; + } + } + + struct wlr_scene_output *scene_output; + wl_list_for_each(scene_output, &scene->outputs, link) { + if (scene_output->output == entered_output->output) { + entered_output->suspended = suspend; + if (!suspend && !active) { + wlr_surface_send_leave(surface->surface, entered_output->output); + } + break; + } + } + } + + // No reason to update the preferred configuration if we aren't sending leave/enter events. + if (suspend) { + return; + } + + for (size_t i = 0; i < event->size; i++) { + // This function internally checks if an enter event was already sent for the output + // to avoid sending redundant events. + wlr_surface_send_enter(surface->surface, event->active[i]->output); + } + + double scale = get_surface_preferred_buffer_scale(surface->surface); + wlr_fractional_scale_v1_notify_scale(surface->surface, scale); + wlr_surface_set_preferred_buffer_scale(surface->surface, ceil(scale)); + + if (scene->color_manager_v1 != NULL) { + struct wlr_image_description_v1_data img_desc = {0}; + get_surface_preferred_image_description(surface->surface, &img_desc); + wlr_color_manager_v1_set_surface_preferred_image_description(scene->color_manager_v1, + surface->surface, &img_desc); + } +} + +static void handle_scene_buffer_output_sample( + struct wl_listener *listener, void *data) { + struct wlr_scene_surface *surface = + wl_container_of(listener, surface, output_sample); + const struct wlr_scene_output_sample_event *event = data; + struct wlr_output *output = event->output->output; + if (get_surface_frame_pacing_output(surface->surface) != output) { + return; + } + + if (event->direct_scanout) { + wlr_presentation_surface_scanned_out_on_output(surface->surface, output); + } else { + wlr_presentation_surface_textured_on_output(surface->surface, output); + } + + struct wlr_linux_drm_syncobj_surface_v1_state *syncobj_surface_state = + wlr_linux_drm_syncobj_v1_get_surface_state(surface->surface); + if (syncobj_surface_state != NULL && event->release_timeline != NULL) { + wlr_linux_drm_syncobj_v1_state_add_release_point(syncobj_surface_state, + event->release_timeline, event->release_point, output->event_loop); + } +} + +static void handle_scene_buffer_frame_done( + struct wl_listener *listener, void *data) { + struct wlr_scene_surface *surface = + wl_container_of(listener, surface, frame_done); + struct wlr_scene_frame_done_event *event = data; + if (get_surface_frame_pacing_output(surface->surface) != event->output->output) { + return; + } + + wlr_surface_send_frame_done(surface->surface, &event->when); +} + +void wlr_scene_surface_send_frame_done(struct wlr_scene_surface *scene_surface, + const struct timespec *when) { + if (!pixman_region32_empty(&scene_surface->buffer->node.visible)) { + wlr_surface_send_frame_done(scene_surface->surface, when); + } +} + +static void scene_surface_handle_surface_destroy( + struct wl_listener *listener, void *data) { + struct wlr_scene_surface *surface = + wl_container_of(listener, surface, surface_destroy); + + wlr_scene_node_destroy(&surface->buffer->node); +} + +// This is used for wlr_scene where it unconditionally locks buffers preventing +// reuse of the existing texture for shm clients. With the usage pattern of +// wlr_scene surface handling, we can mark its locked buffer as safe +// for mutation. +static void client_buffer_mark_next_can_damage(struct wlr_client_buffer *buffer) { + buffer->n_ignore_locks++; +} + +static void scene_buffer_unmark_client_buffer(struct wlr_scene_buffer *scene_buffer) { + if (!scene_buffer->buffer) { + return; + } + + struct wlr_client_buffer *buffer = wlr_client_buffer_get(scene_buffer->buffer); + if (!buffer) { + return; + } + + // If the buffer was a single-pixel buffer where we cached its color + // then it won't have been marked as damage-allowed. + if (buffer->n_ignore_locks > 0) { + buffer->n_ignore_locks--; + } +} + +static int min(int a, int b) { + return a < b ? a : b; +} + +static void surface_reconfigure(struct wlr_scene_surface *scene_surface) { + struct wlr_scene_buffer *scene_buffer = scene_surface->buffer; + struct wlr_surface *surface = scene_surface->surface; + struct wlr_surface_state *state = &surface->current; + + struct wlr_fbox src_box; + wlr_surface_get_buffer_source_box(surface, &src_box); + + pixman_region32_t opaque; + pixman_region32_init(&opaque); + pixman_region32_copy(&opaque, &surface->opaque_region); + + int width = state->width; + int height = state->height; + + if (!wlr_box_empty(&scene_surface->clip)) { + struct wlr_box *clip = &scene_surface->clip; + + int buffer_width = state->buffer_width; + int buffer_height = state->buffer_height; + width = min(clip->width, width - clip->x); + height = min(clip->height, height - clip->y); + + wlr_fbox_transform(&src_box, &src_box, state->transform, + buffer_width, buffer_height); + wlr_output_transform_coords(state->transform, &buffer_width, &buffer_height); + + src_box.x += (double)(clip->x * src_box.width) / state->width; + src_box.y += (double)(clip->y * src_box.height) / state->height; + src_box.width *= (double)width / state->width; + src_box.height *= (double)height / state->height; + + wlr_fbox_transform(&src_box, &src_box, wlr_output_transform_invert(state->transform), + buffer_width, buffer_height); + + pixman_region32_translate(&opaque, -clip->x, -clip->y); + pixman_region32_intersect_rect(&opaque, &opaque, 0, 0, width, height); + } + + if (width <= 0 || height <= 0) { + wlr_scene_buffer_set_buffer(scene_buffer, NULL); + pixman_region32_fini(&opaque); + return; + } + + float opacity = 1.0; + const struct wlr_alpha_modifier_surface_v1_state *alpha_modifier_state = + wlr_alpha_modifier_v1_get_surface_state(surface); + if (alpha_modifier_state != NULL) { + opacity = (float)alpha_modifier_state->multiplier; + } + + enum wlr_color_transfer_function tf = WLR_COLOR_TRANSFER_FUNCTION_GAMMA22; + enum wlr_color_named_primaries primaries = WLR_COLOR_NAMED_PRIMARIES_SRGB; + const struct wlr_image_description_v1_data *img_desc = + wlr_surface_get_image_description_v1_data(surface); + if (img_desc != NULL) { + tf = wlr_color_manager_v1_transfer_function_to_wlr(img_desc->tf_named); + primaries = wlr_color_manager_v1_primaries_to_wlr(img_desc->primaries_named); + } + + enum wlr_color_encoding color_encoding = WLR_COLOR_ENCODING_NONE; + enum wlr_color_range color_range = WLR_COLOR_RANGE_NONE; + const struct wlr_color_representation_v1_surface_state *color_repr = + wlr_color_representation_v1_get_surface_state(surface); + if (color_repr != NULL) { + if (color_repr->coefficients != 0) { + color_encoding = wlr_color_representation_v1_color_encoding_to_wlr(color_repr->coefficients); + } + if (color_repr->range != 0) { + color_range = wlr_color_representation_v1_color_range_to_wlr(color_repr->range); + } + } + + wlr_scene_buffer_set_opaque_region(scene_buffer, &opaque); + wlr_scene_buffer_set_source_box(scene_buffer, &src_box); + wlr_scene_buffer_set_dest_size(scene_buffer, width, height); + wlr_scene_buffer_set_transform(scene_buffer, state->transform); + wlr_scene_buffer_set_opacity(scene_buffer, opacity); + wlr_scene_buffer_set_transfer_function(scene_buffer, tf); + wlr_scene_buffer_set_primaries(scene_buffer, primaries); + wlr_scene_buffer_set_color_encoding(scene_buffer, color_encoding); + wlr_scene_buffer_set_color_range(scene_buffer, color_range); + + scene_buffer_unmark_client_buffer(scene_buffer); + + if (surface->buffer) { + // If we've cached the buffer's single-pixel buffer color + // then any in-place updates to the texture wouldn't be + // reflected in rendering. So only allow in-place texture + // updates if it's not a single pixel buffer. Note that we + // can't use the cached scene_buffer->is_single_pixel_buffer + // because that's only set later on. + bool is_single_pixel_buffer = false; + if (surface->buffer->source != NULL) { + struct wlr_single_pixel_buffer_v1 *spb = + wlr_single_pixel_buffer_v1_try_from_buffer(surface->buffer->source); + is_single_pixel_buffer = spb != NULL; + } + if (!is_single_pixel_buffer) { + client_buffer_mark_next_can_damage(surface->buffer); + } + + struct wlr_linux_drm_syncobj_surface_v1_state *syncobj_surface_state = + wlr_linux_drm_syncobj_v1_get_surface_state(surface); + + struct wlr_scene_buffer_set_buffer_options options = { + .damage = &surface->buffer_damage, + }; + if (syncobj_surface_state != NULL) { + options.wait_timeline = syncobj_surface_state->acquire_timeline; + options.wait_point = syncobj_surface_state->acquire_point; + } + wlr_scene_buffer_set_buffer_with_options(scene_buffer, + &surface->buffer->base, &options); + } else { + wlr_scene_buffer_set_buffer(scene_buffer, NULL); + } + + pixman_region32_fini(&opaque); +} + +static void handle_scene_surface_surface_commit( + struct wl_listener *listener, void *data) { + struct wlr_scene_surface *surface = + wl_container_of(listener, surface, surface_commit); + struct wlr_scene_buffer *scene_buffer = surface->buffer; + + surface_reconfigure(surface); + + // If the surface has requested a frame done event, honour that. The + // frame_callback_list will be populated in this case. We should only + // schedule the frame however if the node is enabled and there is an + // output intersecting, otherwise the frame done events would never reach + // the surface anyway. + int lx, ly; + bool enabled = wlr_scene_node_coords(&scene_buffer->node, &lx, &ly); + struct wlr_output *output = get_surface_frame_pacing_output(surface->surface); + if (!wl_list_empty(&surface->surface->current.frame_callback_list) && output && enabled) { + wlr_output_schedule_frame(output); + } +} + +static bool scene_buffer_point_accepts_input(struct wlr_scene_buffer *scene_buffer, + double *sx, double *sy) { + struct wlr_scene_surface *scene_surface = + wlr_scene_surface_try_from_buffer(scene_buffer); + + *sx += scene_surface->clip.x; + *sy += scene_surface->clip.y; + + struct wlr_surface *surface = scene_surface->surface; +#if WLR_HAS_XWAYLAND + struct wlr_xwayland_surface *xsurface = + wlr_xwayland_surface_try_from_wlr_surface(surface); + if (xsurface != NULL) { + return wlr_xwayland_surface_point_accepts_input( + xsurface, *sx, *sy); + } +#endif + + return wlr_surface_point_accepts_input(surface, *sx, *sy); +} + +static void surface_addon_destroy(struct wlr_addon *addon) { + struct wlr_scene_surface *surface = wl_container_of(addon, surface, addon); + + scene_buffer_unmark_client_buffer(surface->buffer); + + wlr_addon_finish(&surface->addon); + + wl_list_remove(&surface->outputs_update.link); + wl_list_remove(&surface->output_sample.link); + wl_list_remove(&surface->frame_done.link); + wl_list_remove(&surface->surface_destroy.link); + wl_list_remove(&surface->surface_commit.link); + + free(surface); +} + +static const struct wlr_addon_interface surface_addon_impl = { + .name = "wlr_scene_surface", + .destroy = surface_addon_destroy, +}; + +struct wlr_scene_surface *wlr_scene_surface_try_from_buffer( + struct wlr_scene_buffer *scene_buffer) { + struct wlr_addon *addon = wlr_addon_find(&scene_buffer->node.addons, + scene_buffer, &surface_addon_impl); + if (!addon) { + return NULL; + } + + struct wlr_scene_surface *surface = wl_container_of(addon, surface, addon); + return surface; +} + +struct wlr_scene_surface *wlr_scene_surface_create(struct wlr_scene_tree *parent, + struct wlr_surface *wlr_surface) { + struct wlr_scene_surface *surface = calloc(1, sizeof(*surface)); + if (surface == NULL) { + return NULL; + } + + struct wlr_scene_buffer *scene_buffer = wlr_scene_buffer_create(parent, NULL); + if (!scene_buffer) { + free(surface); + return NULL; + } + + surface->buffer = scene_buffer; + surface->surface = wlr_surface; + scene_buffer->point_accepts_input = scene_buffer_point_accepts_input; + + surface->outputs_update.notify = handle_scene_buffer_outputs_update; + wl_signal_add(&scene_buffer->events.outputs_update, &surface->outputs_update); + + surface->output_sample.notify = handle_scene_buffer_output_sample; + wl_signal_add(&scene_buffer->events.output_sample, &surface->output_sample); + + surface->frame_done.notify = handle_scene_buffer_frame_done; + wl_signal_add(&scene_buffer->events.frame_done, &surface->frame_done); + + surface->surface_destroy.notify = scene_surface_handle_surface_destroy; + wl_signal_add(&wlr_surface->events.destroy, &surface->surface_destroy); + + surface->surface_commit.notify = handle_scene_surface_surface_commit; + wl_signal_add(&wlr_surface->events.commit, &surface->surface_commit); + + wlr_addon_init(&surface->addon, &scene_buffer->node.addons, + scene_buffer, &surface_addon_impl); + + surface_reconfigure(surface); + + return surface; +} + +void scene_surface_set_clip(struct wlr_scene_surface *surface, struct wlr_box *clip) { + if (wlr_box_equal(clip, &surface->clip)) { + return; + } + + if (clip) { + surface->clip = *clip; + } else { + surface->clip = (struct wlr_box){0}; + } + + surface_reconfigure(surface); +} diff --git a/3rdparty/wlroots/types/scene/wlr_scene.c b/3rdparty/wlroots/types/scene/wlr_scene.c new file mode 100644 index 0000000000..7bc8b767be --- /dev/null +++ b/3rdparty/wlroots/types/scene/wlr_scene.c @@ -0,0 +1,2730 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "render/color.h" +#include "types/wlr_output.h" +#include "types/wlr_scene.h" +#include "util/array.h" +#include "util/env.h" +#include "util/time.h" + +#include + +#if WLR_HAS_XWAYLAND +#include +#endif + +#define DMABUF_FEEDBACK_DEBOUNCE_FRAMES 30 +#define HIGHLIGHT_DAMAGE_FADEOUT_TIME 250 + +struct wlr_scene_tree *wlr_scene_tree_from_node(struct wlr_scene_node *node) { + assert(node->type == WLR_SCENE_NODE_TREE); + struct wlr_scene_tree *tree = wl_container_of(node, tree, node); + return tree; +} + +struct wlr_scene_rect *wlr_scene_rect_from_node(struct wlr_scene_node *node) { + assert(node->type == WLR_SCENE_NODE_RECT); + struct wlr_scene_rect *rect = wl_container_of(node, rect, node); + return rect; +} + +struct wlr_scene_buffer *wlr_scene_buffer_from_node( + struct wlr_scene_node *node) { + assert(node->type == WLR_SCENE_NODE_BUFFER); + struct wlr_scene_buffer *buffer = wl_container_of(node, buffer, node); + return buffer; +} + +struct wlr_scene *scene_node_get_root(struct wlr_scene_node *node) { + struct wlr_scene_tree *tree; + if (node->type == WLR_SCENE_NODE_TREE) { + tree = wlr_scene_tree_from_node(node); + } else { + tree = node->parent; + } + + while (tree->node.parent != NULL) { + tree = tree->node.parent; + } + struct wlr_scene *scene = wl_container_of(tree, scene, tree); + return scene; +} + +static void scene_node_init(struct wlr_scene_node *node, + enum wlr_scene_node_type type, struct wlr_scene_tree *parent) { + *node = (struct wlr_scene_node){ + .type = type, + .parent = parent, + .enabled = true, + }; + + wl_list_init(&node->link); + + wl_signal_init(&node->events.destroy); + pixman_region32_init(&node->visible); + + if (parent != NULL) { + wl_list_insert(parent->children.prev, &node->link); + } + + wlr_addon_set_init(&node->addons); +} + +struct highlight_region { + pixman_region32_t region; + struct timespec when; + struct wl_list link; +}; + +static void scene_buffer_set_buffer(struct wlr_scene_buffer *scene_buffer, + struct wlr_buffer *buffer); +static void scene_buffer_set_texture(struct wlr_scene_buffer *scene_buffer, + struct wlr_texture *texture); + +void wlr_scene_node_destroy(struct wlr_scene_node *node) { + if (node == NULL) { + return; + } + + // We want to call the destroy listeners before we do anything else + // in case the destroy signal would like to remove children before they + // are recursively destroyed. + wl_signal_emit_mutable(&node->events.destroy, NULL); + wlr_addon_set_finish(&node->addons); + + wlr_scene_node_set_enabled(node, false); + + struct wlr_scene *scene = scene_node_get_root(node); + if (node->type == WLR_SCENE_NODE_BUFFER) { + struct wlr_scene_buffer *scene_buffer = wlr_scene_buffer_from_node(node); + + uint64_t active = scene_buffer->active_outputs; + if (active) { + struct wlr_scene_output *scene_output; + wl_list_for_each(scene_output, &scene->outputs, link) { + if (active & (1ull << scene_output->index)) { + wl_signal_emit_mutable(&scene_buffer->events.output_leave, + scene_output); + } + } + } + + scene_buffer_set_buffer(scene_buffer, NULL); + scene_buffer_set_texture(scene_buffer, NULL); + pixman_region32_fini(&scene_buffer->opaque_region); + wlr_drm_syncobj_timeline_unref(scene_buffer->wait_timeline); + + assert(wl_list_empty(&scene_buffer->events.output_leave.listener_list)); + assert(wl_list_empty(&scene_buffer->events.output_enter.listener_list)); + assert(wl_list_empty(&scene_buffer->events.outputs_update.listener_list)); + assert(wl_list_empty(&scene_buffer->events.output_sample.listener_list)); + assert(wl_list_empty(&scene_buffer->events.frame_done.listener_list)); + } else if (node->type == WLR_SCENE_NODE_TREE) { + struct wlr_scene_tree *scene_tree = wlr_scene_tree_from_node(node); + + if (scene_tree == &scene->tree) { + assert(!node->parent); + struct wlr_scene_output *scene_output, *scene_output_tmp; + wl_list_for_each_safe(scene_output, scene_output_tmp, &scene->outputs, link) { + wlr_scene_output_destroy(scene_output); + } + + wl_list_remove(&scene->linux_dmabuf_v1_destroy.link); + wl_list_remove(&scene->gamma_control_manager_v1_destroy.link); + wl_list_remove(&scene->gamma_control_manager_v1_set_gamma.link); + } else { + assert(node->parent); + } + + struct wlr_scene_node *child, *child_tmp; + wl_list_for_each_safe(child, child_tmp, + &scene_tree->children, link) { + wlr_scene_node_destroy(child); + } + } + + assert(wl_list_empty(&node->events.destroy.listener_list)); + + wl_list_remove(&node->link); + pixman_region32_fini(&node->visible); + free(node); +} + +static void scene_tree_init(struct wlr_scene_tree *tree, + struct wlr_scene_tree *parent) { + *tree = (struct wlr_scene_tree){0}; + scene_node_init(&tree->node, WLR_SCENE_NODE_TREE, parent); + wl_list_init(&tree->children); +} + +struct wlr_scene *wlr_scene_create(void) { + struct wlr_scene *scene = calloc(1, sizeof(*scene)); + if (scene == NULL) { + return NULL; + } + + scene_tree_init(&scene->tree, NULL); + + wl_list_init(&scene->outputs); + wl_list_init(&scene->linux_dmabuf_v1_destroy.link); + wl_list_init(&scene->gamma_control_manager_v1_destroy.link); + wl_list_init(&scene->gamma_control_manager_v1_set_gamma.link); + + scene->restack_xwayland_surfaces = true; + + const char *debug_damage_options[] = { + "none", + "rerender", + "highlight", + NULL + }; + + scene->debug_damage_option = env_parse_switch("WLR_SCENE_DEBUG_DAMAGE", debug_damage_options); + scene->direct_scanout = !env_parse_bool("WLR_SCENE_DISABLE_DIRECT_SCANOUT"); + scene->calculate_visibility = !env_parse_bool("WLR_SCENE_DISABLE_VISIBILITY"); + scene->highlight_transparent_region = env_parse_bool("WLR_SCENE_HIGHLIGHT_TRANSPARENT_REGION"); + + return scene; +} + +struct wlr_scene_tree *wlr_scene_tree_create(struct wlr_scene_tree *parent) { + assert(parent); + + struct wlr_scene_tree *tree = calloc(1, sizeof(*tree)); + if (tree == NULL) { + return NULL; + } + + scene_tree_init(tree, parent); + return tree; +} + +typedef bool (*scene_node_box_iterator_func_t)(struct wlr_scene_node *node, + int sx, int sy, void *data); + +static bool _scene_nodes_in_box(struct wlr_scene_node *node, struct wlr_box *box, + scene_node_box_iterator_func_t iterator, void *user_data, int lx, int ly) { + if (!node->enabled) { + return false; + } + + switch (node->type) { + case WLR_SCENE_NODE_TREE:; + struct wlr_scene_tree *scene_tree = wlr_scene_tree_from_node(node); + struct wlr_scene_node *child; + wl_list_for_each_reverse(child, &scene_tree->children, link) { + if (_scene_nodes_in_box(child, box, iterator, user_data, lx + child->x, ly + child->y)) { + return true; + } + } + break; + case WLR_SCENE_NODE_RECT: + case WLR_SCENE_NODE_BUFFER:; + struct wlr_box node_box = { .x = lx, .y = ly }; + scene_node_get_size(node, &node_box.width, &node_box.height); + + if (wlr_box_intersection(&node_box, &node_box, box) && + iterator(node, lx, ly, user_data)) { + return true; + } + break; + } + + return false; +} + +static bool scene_nodes_in_box(struct wlr_scene_node *node, struct wlr_box *box, + scene_node_box_iterator_func_t iterator, void *user_data) { + int x, y; + wlr_scene_node_coords(node, &x, &y); + + return _scene_nodes_in_box(node, box, iterator, user_data, x, y); +} + +static void scene_node_opaque_region(struct wlr_scene_node *node, int x, int y, + pixman_region32_t *opaque) { + int width, height; + scene_node_get_size(node, &width, &height); + + if (node->type == WLR_SCENE_NODE_RECT) { + struct wlr_scene_rect *scene_rect = wlr_scene_rect_from_node(node); + if (scene_rect->color[3] != 1) { + return; + } + } else if (node->type == WLR_SCENE_NODE_BUFFER) { + struct wlr_scene_buffer *scene_buffer = wlr_scene_buffer_from_node(node); + + if (!scene_buffer->buffer) { + return; + } + + if (scene_buffer->opacity != 1) { + return; + } + + if (!scene_buffer->buffer_is_opaque) { + pixman_region32_copy(opaque, &scene_buffer->opaque_region); + pixman_region32_intersect_rect(opaque, opaque, 0, 0, width, height); + pixman_region32_translate(opaque, x, y); + return; + } + } + + pixman_region32_fini(opaque); + pixman_region32_init_rect(opaque, x, y, width, height); +} + +struct scene_update_data { + pixman_region32_t *visible; + const pixman_region32_t *update_region; + struct wlr_box update_box; + struct wl_list *outputs; + bool calculate_visibility; + bool restack_xwayland_surfaces; + +#if WLR_HAS_XWAYLAND + struct wlr_xwayland_surface *restack_above; +#endif +}; + +static uint32_t region_area(const pixman_region32_t *region) { + uint32_t area = 0; + + int nrects; + pixman_box32_t *rects = pixman_region32_rectangles(region, &nrects); + for (int i = 0; i < nrects; ++i) { + area += (rects[i].x2 - rects[i].x1) * (rects[i].y2 - rects[i].y1); + } + + return area; +} + +static void scale_region(pixman_region32_t *region, float scale, bool round_up) { + wlr_region_scale(region, region, scale); + + if (round_up && floor(scale) != scale) { + wlr_region_expand(region, region, 1); + } +} + +struct render_data { + enum wl_output_transform transform; + float scale; + struct wlr_box logical; + int trans_width, trans_height; + + struct wlr_scene_output *output; + + struct wlr_render_pass *render_pass; + pixman_region32_t damage; +}; + +static void logical_to_buffer_coords(pixman_region32_t *region, const struct render_data *data, + bool round_up) { + enum wl_output_transform transform = wlr_output_transform_invert(data->transform); + scale_region(region, data->scale, round_up); + wlr_region_transform(region, region, transform, data->trans_width, data->trans_height); +} + +static void output_to_buffer_coords(pixman_region32_t *damage, struct wlr_output *output) { + int width, height; + wlr_output_transformed_resolution(output, &width, &height); + + wlr_region_transform(damage, damage, + wlr_output_transform_invert(output->transform), width, height); +} + +static int scale_length(int length, int offset, float scale) { + return round((offset + length) * scale) - round(offset * scale); +} + +static void scale_box(struct wlr_box *box, float scale) { + box->width = scale_length(box->width, box->x, scale); + box->height = scale_length(box->height, box->y, scale); + box->x = round(box->x * scale); + box->y = round(box->y * scale); +} + +static void transform_output_box(struct wlr_box *box, const struct render_data *data) { + enum wl_output_transform transform = wlr_output_transform_invert(data->transform); + scale_box(box, data->scale); + wlr_box_transform(box, box, transform, data->trans_width, data->trans_height); +} + +static void scene_output_damage(struct wlr_scene_output *scene_output, + const pixman_region32_t *damage) { + struct wlr_output *output = scene_output->output; + + pixman_region32_t clipped; + pixman_region32_init(&clipped); + pixman_region32_intersect_rect(&clipped, damage, 0, 0, output->width, output->height); + + if (!pixman_region32_empty(&clipped)) { + wlr_output_schedule_frame(scene_output->output); + wlr_damage_ring_add(&scene_output->damage_ring, &clipped); + + pixman_region32_union(&scene_output->pending_commit_damage, + &scene_output->pending_commit_damage, &clipped); + } + + pixman_region32_fini(&clipped); +} + +static void scene_output_damage_whole(struct wlr_scene_output *scene_output) { + struct wlr_output *output = scene_output->output; + + pixman_region32_t damage; + pixman_region32_init_rect(&damage, 0, 0, output->width, output->height); + scene_output_damage(scene_output, &damage); + pixman_region32_fini(&damage); +} + +static void scene_damage_outputs(struct wlr_scene *scene, const pixman_region32_t *damage) { + if (pixman_region32_empty(damage)) { + return; + } + + struct wlr_scene_output *scene_output; + wl_list_for_each(scene_output, &scene->outputs, link) { + pixman_region32_t output_damage; + pixman_region32_init(&output_damage); + pixman_region32_copy(&output_damage, damage); + pixman_region32_translate(&output_damage, + -scene_output->x, -scene_output->y); + scale_region(&output_damage, scene_output->output->scale, true); + output_to_buffer_coords(&output_damage, scene_output->output); + scene_output_damage(scene_output, &output_damage); + pixman_region32_fini(&output_damage); + } +} + +static void update_node_update_outputs(struct wlr_scene_node *node, + struct wl_list *outputs, struct wlr_scene_output *ignore, + struct wlr_scene_output *force) { + if (node->type != WLR_SCENE_NODE_BUFFER) { + return; + } + + struct wlr_scene_buffer *scene_buffer = wlr_scene_buffer_from_node(node); + + uint32_t largest_overlap = 0; + struct wlr_scene_output *old_primary_output = scene_buffer->primary_output; + scene_buffer->primary_output = NULL; + + size_t count = 0; + uint64_t active_outputs = 0; + + if (!pixman_region32_empty(&node->visible)) { + struct wlr_scene_output *scene_output; + + // Compute the region covered by all outputs, then intersect with the + // node's visible region + pixman_region32_t visible; + pixman_region32_init(&visible); + wl_list_for_each(scene_output, outputs, link) { + int width, height; + wlr_output_effective_resolution(scene_output->output, &width, &height); + pixman_region32_union_rect(&visible, &visible, + scene_output->x, scene_output->y, width, height); + } + pixman_region32_intersect(&visible, &visible, &node->visible); + uint32_t visible_area = region_area(&visible); + pixman_region32_fini(&visible); + + // let's update the outputs in two steps: + // - the primary outputs + // - the enter/leave signals + // This ensures that the enter/leave signals can rely on the primary output + // to have a reasonable value. Otherwise, they may get a value that's in + // the middle of a calculation. + wl_list_for_each(scene_output, outputs, link) { + if (scene_output == ignore) { + continue; + } + + if (!scene_output->output->enabled) { + continue; + } + + struct wlr_box output_box = { + .x = scene_output->x, + .y = scene_output->y, + }; + wlr_output_effective_resolution(scene_output->output, + &output_box.width, &output_box.height); + + pixman_region32_t intersection; + pixman_region32_init(&intersection); + pixman_region32_intersect_rect(&intersection, &node->visible, + output_box.x, output_box.y, output_box.width, output_box.height); + uint32_t overlap = region_area(&intersection); + pixman_region32_fini(&intersection); + + // If the overlap accounts for 10% of the visible node area or less, + // ignore this output + if (overlap > 0.1 * visible_area) { + if (overlap >= largest_overlap) { + largest_overlap = overlap; + scene_buffer->primary_output = scene_output; + } + + active_outputs |= 1ull << scene_output->index; + count++; + } + } + } + + uint64_t old_active = scene_buffer->active_outputs; + scene_buffer->active_outputs = active_outputs; + + struct wlr_scene_output *scene_output; + wl_list_for_each(scene_output, outputs, link) { + uint64_t mask = 1ull << scene_output->index; + bool intersects = active_outputs & mask; + bool intersects_before = old_active & mask; + + if (intersects && !intersects_before) { + wl_signal_emit_mutable(&scene_buffer->events.output_enter, scene_output); + } else if (!intersects && intersects_before) { + wl_signal_emit_mutable(&scene_buffer->events.output_leave, scene_output); + } + } + + // if there are active outputs on this node, we should always have a primary + // output + assert(!scene_buffer->active_outputs || scene_buffer->primary_output); + + // Skip output update event if nothing was updated + if (old_active == active_outputs && + (!force || ((1ull << force->index) & ~active_outputs)) && + old_primary_output == scene_buffer->primary_output) { + return; + } + + struct wlr_scene_output *outputs_array[64]; + struct wlr_scene_outputs_update_event event = { + .active = outputs_array, + .size = count, + }; + + size_t i = 0; + wl_list_for_each(scene_output, outputs, link) { + if (~active_outputs & (1ull << scene_output->index)) { + continue; + } + + assert(i < count); + outputs_array[i++] = scene_output; + } + + wl_signal_emit_mutable(&scene_buffer->events.outputs_update, &event); +} + +#if WLR_HAS_XWAYLAND +static struct wlr_xwayland_surface *scene_node_try_get_managed_xwayland_surface( + struct wlr_scene_node *node) { + if (node->type != WLR_SCENE_NODE_BUFFER) { + return NULL; + } + + struct wlr_scene_buffer *buffer_node = wlr_scene_buffer_from_node(node); + struct wlr_scene_surface *surface_node = wlr_scene_surface_try_from_buffer(buffer_node); + if (!surface_node) { + return NULL; + } + + struct wlr_xwayland_surface *xwayland_surface = + wlr_xwayland_surface_try_from_wlr_surface(surface_node->surface); + if (!xwayland_surface || xwayland_surface->override_redirect) { + return NULL; + } + + return xwayland_surface; +} + +static void restack_xwayland_surface(struct wlr_scene_node *node, + struct wlr_box *box, struct scene_update_data *data) { + struct wlr_xwayland_surface *xwayland_surface = + scene_node_try_get_managed_xwayland_surface(node); + if (!xwayland_surface) { + return; + } + + // ensure this node is entirely inside the update region. If not, we can't + // restack this node since we're not considering the whole thing. + if (wlr_box_contains_box(&data->update_box, box)) { + if (data->restack_above) { + wlr_xwayland_surface_restack(xwayland_surface, data->restack_above, XCB_STACK_MODE_BELOW); + } else { + wlr_xwayland_surface_restack(xwayland_surface, NULL, XCB_STACK_MODE_ABOVE); + } + } + + data->restack_above = xwayland_surface; +} +#endif + +static bool scene_node_update_iterator(struct wlr_scene_node *node, + int lx, int ly, void *_data) { + struct scene_update_data *data = _data; + + struct wlr_box box = { .x = lx, .y = ly }; + scene_node_get_size(node, &box.width, &box.height); + + pixman_region32_subtract(&node->visible, &node->visible, data->update_region); + pixman_region32_union(&node->visible, &node->visible, data->visible); + pixman_region32_intersect_rect(&node->visible, &node->visible, + lx, ly, box.width, box.height); + + if (data->calculate_visibility) { + pixman_region32_t opaque; + pixman_region32_init(&opaque); + scene_node_opaque_region(node, lx, ly, &opaque); + pixman_region32_subtract(data->visible, data->visible, &opaque); + pixman_region32_fini(&opaque); + } + + update_node_update_outputs(node, data->outputs, NULL, NULL); +#if WLR_HAS_XWAYLAND + if (data->restack_xwayland_surfaces) { + restack_xwayland_surface(node, &box, data); + } +#endif + + return false; +} + +static void scene_node_visibility(struct wlr_scene_node *node, + pixman_region32_t *visible) { + if (!node->enabled) { + return; + } + + if (node->type == WLR_SCENE_NODE_TREE) { + struct wlr_scene_tree *scene_tree = wlr_scene_tree_from_node(node); + struct wlr_scene_node *child; + wl_list_for_each(child, &scene_tree->children, link) { + scene_node_visibility(child, visible); + } + return; + } + + pixman_region32_union(visible, visible, &node->visible); +} + +static void scene_node_bounds(struct wlr_scene_node *node, + int x, int y, pixman_region32_t *visible) { + if (!node->enabled) { + return; + } + + if (node->type == WLR_SCENE_NODE_TREE) { + struct wlr_scene_tree *scene_tree = wlr_scene_tree_from_node(node); + struct wlr_scene_node *child; + wl_list_for_each(child, &scene_tree->children, link) { + scene_node_bounds(child, x + child->x, y + child->y, visible); + } + return; + } + + int width, height; + scene_node_get_size(node, &width, &height); + pixman_region32_union_rect(visible, visible, x, y, width, height); +} + +static void scene_update_region(struct wlr_scene *scene, + const pixman_region32_t *update_region) { + pixman_region32_t visible; + pixman_region32_init(&visible); + pixman_region32_copy(&visible, update_region); + + struct pixman_box32 *region_box = pixman_region32_extents(update_region); + struct scene_update_data data = { + .visible = &visible, + .update_region = update_region, + .update_box = { + .x = region_box->x1, + .y = region_box->y1, + .width = region_box->x2 - region_box->x1, + .height = region_box->y2 - region_box->y1, + }, + .outputs = &scene->outputs, + .calculate_visibility = scene->calculate_visibility, + .restack_xwayland_surfaces = scene->restack_xwayland_surfaces, + }; + + // update node visibility and output enter/leave events + scene_nodes_in_box(&scene->tree.node, &data.update_box, scene_node_update_iterator, &data); + + pixman_region32_fini(&visible); +} + +static void scene_node_cleanup_when_disabled(struct wlr_scene_node *node, + bool xwayland_restack, struct wl_list *outputs) { + if (node->type == WLR_SCENE_NODE_TREE) { + struct wlr_scene_tree *scene_tree = wlr_scene_tree_from_node(node); + struct wlr_scene_node *child; + wl_list_for_each(child, &scene_tree->children, link) { + if (!child->enabled) { + continue; + } + + scene_node_cleanup_when_disabled(child, xwayland_restack, outputs); + } + return; + } + + pixman_region32_clear(&node->visible); + update_node_update_outputs(node, outputs, NULL, NULL); + +#if WLR_HAS_XWAYLAND + if (xwayland_restack) { + struct wlr_xwayland_surface *xwayland_surface = + scene_node_try_get_managed_xwayland_surface(node); + if (!xwayland_surface) { + return; + } + + wlr_xwayland_surface_restack(xwayland_surface, NULL, XCB_STACK_MODE_BELOW); + } +#endif +} + +/** + * Updates the nodes visibility, xwayland restacking, send leave/enter events + * and damages the screen. The damage region is used to not only damage the + * screen, but to direct the update logic to only update certain parts of the + * screen and not the whole thing. If a NULL damage is given, the damage is + * assumed to be the previous nodes visibility. + * + * Currently, the only usage for an explicit damage is for update scenarios where + * the scene node might be enabled/disabled. If the scene node is disabled, the + * update logic will ignore the node. This is normally desirable as most update + * scenarios like updating the color or whatever. However, it's not what we want + * when disabling the node. Note that reparenting the node could lead to the node + * being reparented to a disabled super tree. + */ +static void scene_node_update(struct wlr_scene_node *node, + pixman_region32_t *damage) { + struct wlr_scene *scene = scene_node_get_root(node); + + int x, y; + if (!wlr_scene_node_coords(node, &x, &y)) { + // We assume explicit damage on a disabled tree means the node was just + // disabled. + if (damage) { + scene_node_cleanup_when_disabled(node, scene->restack_xwayland_surfaces, &scene->outputs); + + scene_update_region(scene, damage); + scene_damage_outputs(scene, damage); + pixman_region32_fini(damage); + } + + return; + } + + pixman_region32_t visible; + if (!damage) { + pixman_region32_init(&visible); + scene_node_visibility(node, &visible); + damage = &visible; + } + + pixman_region32_t update_region; + pixman_region32_init(&update_region); + pixman_region32_copy(&update_region, damage); + scene_node_bounds(node, x, y, &update_region); + + scene_update_region(scene, &update_region); + pixman_region32_fini(&update_region); + + scene_node_visibility(node, damage); + scene_damage_outputs(scene, damage); + pixman_region32_fini(damage); +} + +struct wlr_scene_rect *wlr_scene_rect_create(struct wlr_scene_tree *parent, + int width, int height, const float color[static 4]) { + assert(parent); + assert(width >= 0 && height >= 0); + + struct wlr_scene_rect *scene_rect = calloc(1, sizeof(*scene_rect)); + if (scene_rect == NULL) { + return NULL; + } + scene_node_init(&scene_rect->node, WLR_SCENE_NODE_RECT, parent); + + scene_rect->width = width; + scene_rect->height = height; + memcpy(scene_rect->color, color, sizeof(scene_rect->color)); + + scene_node_update(&scene_rect->node, NULL); + + return scene_rect; +} + +void wlr_scene_rect_set_size(struct wlr_scene_rect *rect, int width, int height) { + if (rect->width == width && rect->height == height) { + return; + } + + assert(width >= 0 && height >= 0); + + rect->width = width; + rect->height = height; + scene_node_update(&rect->node, NULL); +} + +void wlr_scene_rect_set_color(struct wlr_scene_rect *rect, const float color[static 4]) { + if (memcmp(rect->color, color, sizeof(rect->color)) == 0) { + return; + } + + memcpy(rect->color, color, sizeof(rect->color)); + scene_node_update(&rect->node, NULL); +} + +static void scene_buffer_handle_buffer_release(struct wl_listener *listener, + void *data) { + struct wlr_scene_buffer *scene_buffer = + wl_container_of(listener, scene_buffer, buffer_release); + + scene_buffer->buffer = NULL; + wl_list_remove(&scene_buffer->buffer_release.link); + wl_list_init(&scene_buffer->buffer_release.link); +} + +static void scene_buffer_set_buffer(struct wlr_scene_buffer *scene_buffer, + struct wlr_buffer *buffer) { + wl_list_remove(&scene_buffer->buffer_release.link); + wl_list_init(&scene_buffer->buffer_release.link); + if (scene_buffer->own_buffer) { + wlr_buffer_unlock(scene_buffer->buffer); + } + scene_buffer->buffer = NULL; + scene_buffer->own_buffer = false; + scene_buffer->buffer_width = scene_buffer->buffer_height = 0; + scene_buffer->buffer_is_opaque = false; + + if (!buffer) { + return; + } + + scene_buffer->own_buffer = true; + scene_buffer->buffer = wlr_buffer_lock(buffer); + scene_buffer->buffer_width = buffer->width; + scene_buffer->buffer_height = buffer->height; + scene_buffer->buffer_is_opaque = wlr_buffer_is_opaque(buffer); + + scene_buffer->buffer_release.notify = scene_buffer_handle_buffer_release; + wl_signal_add(&buffer->events.release, &scene_buffer->buffer_release); +} + +static void scene_buffer_handle_renderer_destroy(struct wl_listener *listener, + void *data) { + struct wlr_scene_buffer *scene_buffer = wl_container_of(listener, scene_buffer, renderer_destroy); + scene_buffer_set_texture(scene_buffer, NULL); +} + +static void scene_buffer_set_texture(struct wlr_scene_buffer *scene_buffer, + struct wlr_texture *texture) { + wl_list_remove(&scene_buffer->renderer_destroy.link); + wlr_texture_destroy(scene_buffer->texture); + scene_buffer->texture = texture; + + if (texture != NULL) { + scene_buffer->renderer_destroy.notify = scene_buffer_handle_renderer_destroy; + wl_signal_add(&texture->renderer->events.destroy, &scene_buffer->renderer_destroy); + } else { + wl_list_init(&scene_buffer->renderer_destroy.link); + } +} + +static void scene_buffer_set_wait_timeline(struct wlr_scene_buffer *scene_buffer, + struct wlr_drm_syncobj_timeline *timeline, uint64_t point) { + wlr_drm_syncobj_timeline_unref(scene_buffer->wait_timeline); + if (timeline != NULL) { + scene_buffer->wait_timeline = wlr_drm_syncobj_timeline_ref(timeline); + scene_buffer->wait_point = point; + } else { + scene_buffer->wait_timeline = NULL; + scene_buffer->wait_point = 0; + } +} + +struct wlr_scene_buffer *wlr_scene_buffer_create(struct wlr_scene_tree *parent, + struct wlr_buffer *buffer) { + struct wlr_scene_buffer *scene_buffer = calloc(1, sizeof(*scene_buffer)); + if (scene_buffer == NULL) { + return NULL; + } + assert(parent); + scene_node_init(&scene_buffer->node, WLR_SCENE_NODE_BUFFER, parent); + + wl_signal_init(&scene_buffer->events.outputs_update); + wl_signal_init(&scene_buffer->events.output_enter); + wl_signal_init(&scene_buffer->events.output_leave); + wl_signal_init(&scene_buffer->events.output_sample); + wl_signal_init(&scene_buffer->events.frame_done); + + pixman_region32_init(&scene_buffer->opaque_region); + wl_list_init(&scene_buffer->buffer_release.link); + wl_list_init(&scene_buffer->renderer_destroy.link); + scene_buffer->opacity = 1; + + scene_buffer_set_buffer(scene_buffer, buffer); + scene_node_update(&scene_buffer->node, NULL); + + return scene_buffer; +} + +void wlr_scene_buffer_set_buffer_with_options(struct wlr_scene_buffer *scene_buffer, + struct wlr_buffer *buffer, const struct wlr_scene_buffer_set_buffer_options *options) { + const struct wlr_scene_buffer_set_buffer_options default_options = {0}; + if (options == NULL) { + options = &default_options; + } + + // specifying a region for a NULL buffer doesn't make sense. We need to know + // about the buffer to scale the buffer local coordinates down to scene + // coordinates. + assert(buffer || !options->damage); + + bool mapped = buffer != NULL; + bool prev_mapped = scene_buffer->buffer != NULL || scene_buffer->texture != NULL; + + if (!mapped && !prev_mapped) { + // unmapping already unmapped buffer - noop + return; + } + + // if this node used to not be mapped or its previous displayed + // buffer region will be different from what the new buffer would + // produce we need to update the node. + bool update = mapped != prev_mapped; + if (buffer != NULL && scene_buffer->dst_width == 0 && scene_buffer->dst_height == 0) { + update = update || scene_buffer->buffer_width != buffer->width || + scene_buffer->buffer_height != buffer->height; + } + + // If this is a buffer change, check if it's a single pixel buffer. + // Cache that so we can still apply rendering optimisations even when + // the original buffer has been freed after texture upload. + if (buffer != scene_buffer->buffer) { + scene_buffer->is_single_pixel_buffer = false; + struct wlr_client_buffer *client_buffer = NULL; + if (buffer != NULL) { + client_buffer = wlr_client_buffer_get(buffer); + } + if (client_buffer != NULL && client_buffer->source != NULL) { + struct wlr_single_pixel_buffer_v1 *single_pixel_buffer = + wlr_single_pixel_buffer_v1_try_from_buffer(client_buffer->source); + if (single_pixel_buffer != NULL) { + scene_buffer->is_single_pixel_buffer = true; + scene_buffer->single_pixel_buffer_color[0] = single_pixel_buffer->r; + scene_buffer->single_pixel_buffer_color[1] = single_pixel_buffer->g; + scene_buffer->single_pixel_buffer_color[2] = single_pixel_buffer->b; + scene_buffer->single_pixel_buffer_color[3] = single_pixel_buffer->a; + } + } + } + + scene_buffer_set_buffer(scene_buffer, buffer); + scene_buffer_set_texture(scene_buffer, NULL); + scene_buffer_set_wait_timeline(scene_buffer, + options->wait_timeline, options->wait_point); + + if (update) { + scene_node_update(&scene_buffer->node, NULL); + // updating the node will already damage the whole node for us. Return + // early to not damage again + return; + } + + int lx, ly; + if (!wlr_scene_node_coords(&scene_buffer->node, &lx, &ly)) { + return; + } + + pixman_region32_t fallback_damage; + pixman_region32_init_rect(&fallback_damage, 0, 0, buffer->width, buffer->height); + const pixman_region32_t *damage = options->damage; + if (!damage) { + damage = &fallback_damage; + } + + struct wlr_fbox box = scene_buffer->src_box; + if (wlr_fbox_empty(&box)) { + box.x = 0; + box.y = 0; + box.width = buffer->width; + box.height = buffer->height; + } + + wlr_fbox_transform(&box, &box, scene_buffer->transform, + buffer->width, buffer->height); + + float scale_x, scale_y; + if (scene_buffer->dst_width || scene_buffer->dst_height) { + scale_x = scene_buffer->dst_width / box.width; + scale_y = scene_buffer->dst_height / box.height; + } else { + scale_x = buffer->width / box.width; + scale_y = buffer->height / box.height; + } + + pixman_region32_t trans_damage; + pixman_region32_init(&trans_damage); + wlr_region_transform(&trans_damage, damage, + scene_buffer->transform, buffer->width, buffer->height); + pixman_region32_intersect_rect(&trans_damage, &trans_damage, + box.x, box.y, box.width, box.height); + pixman_region32_translate(&trans_damage, -box.x, -box.y); + + struct wlr_scene *scene = scene_node_get_root(&scene_buffer->node); + struct wlr_scene_output *scene_output; + wl_list_for_each(scene_output, &scene->outputs, link) { + float output_scale = scene_output->output->scale; + float output_scale_x = output_scale * scale_x; + float output_scale_y = output_scale * scale_y; + pixman_region32_t output_damage; + pixman_region32_init(&output_damage); + wlr_region_scale_xy(&output_damage, &trans_damage, + output_scale_x, output_scale_y); + + // One output pixel will match (buffer_scale_x)x(buffer_scale_y) buffer pixels. + // If the buffer is upscaled on the given axis (output_scale_* > 1.0, + // buffer_scale_* < 1.0), its contents will bleed into adjacent + // (ceil(output_scale_* / 2)) output pixels because of linear filtering. + // Additionally, if the buffer is downscaled (output_scale_* < 1.0, + // buffer_scale_* > 1.0), and one output pixel matches a non-integer number of + // buffer pixels, its contents will bleed into neighboring output pixels. + // Handle both cases by computing buffer_scale_{x,y} and checking if they are + // integer numbers; ceilf() is used to ensure that the distance is at least 1. + float buffer_scale_x = 1.0f / output_scale_x; + float buffer_scale_y = 1.0f / output_scale_y; + int dist_x = floor(buffer_scale_x) != buffer_scale_x ? + (int)ceilf(output_scale_x / 2.0f) : 0; + int dist_y = floor(buffer_scale_y) != buffer_scale_y ? + (int)ceilf(output_scale_y / 2.0f) : 0; + // TODO: expand with per-axis distances + wlr_region_expand(&output_damage, &output_damage, + dist_x >= dist_y ? dist_x : dist_y); + + pixman_region32_t cull_region; + pixman_region32_init(&cull_region); + pixman_region32_copy(&cull_region, &scene_buffer->node.visible); + scale_region(&cull_region, output_scale, true); + pixman_region32_translate(&cull_region, -lx * output_scale, -ly * output_scale); + pixman_region32_intersect(&output_damage, &output_damage, &cull_region); + pixman_region32_fini(&cull_region); + + pixman_region32_translate(&output_damage, + (int)round((lx - scene_output->x) * output_scale), + (int)round((ly - scene_output->y) * output_scale)); + output_to_buffer_coords(&output_damage, scene_output->output); + scene_output_damage(scene_output, &output_damage); + pixman_region32_fini(&output_damage); + } + + pixman_region32_fini(&trans_damage); + pixman_region32_fini(&fallback_damage); +} + +void wlr_scene_buffer_set_buffer_with_damage(struct wlr_scene_buffer *scene_buffer, + struct wlr_buffer *buffer, const pixman_region32_t *damage) { + const struct wlr_scene_buffer_set_buffer_options options = { + .damage = damage, + }; + wlr_scene_buffer_set_buffer_with_options(scene_buffer, buffer, &options); +} + +void wlr_scene_buffer_set_buffer(struct wlr_scene_buffer *scene_buffer, + struct wlr_buffer *buffer) { + wlr_scene_buffer_set_buffer_with_options(scene_buffer, buffer, NULL); +} + +void wlr_scene_buffer_set_opaque_region(struct wlr_scene_buffer *scene_buffer, + const pixman_region32_t *region) { + if (pixman_region32_equal(&scene_buffer->opaque_region, region)) { + return; + } + + pixman_region32_copy(&scene_buffer->opaque_region, region); + + int x, y; + if (!wlr_scene_node_coords(&scene_buffer->node, &x, &y)) { + return; + } + + pixman_region32_t update_region; + pixman_region32_init(&update_region); + scene_node_bounds(&scene_buffer->node, x, y, &update_region); + scene_update_region(scene_node_get_root(&scene_buffer->node), &update_region); + pixman_region32_fini(&update_region); +} + +void wlr_scene_buffer_set_source_box(struct wlr_scene_buffer *scene_buffer, + const struct wlr_fbox *box) { + if (wlr_fbox_equal(&scene_buffer->src_box, box)) { + return; + } + + if (box != NULL) { + assert(box->x >= 0 && box->y >= 0 && box->width >= 0 && box->height >= 0); + scene_buffer->src_box = *box; + } else { + scene_buffer->src_box = (struct wlr_fbox){0}; + } + + scene_node_update(&scene_buffer->node, NULL); +} + +void wlr_scene_buffer_set_dest_size(struct wlr_scene_buffer *scene_buffer, + int width, int height) { + if (scene_buffer->dst_width == width && scene_buffer->dst_height == height) { + return; + } + + assert(width >= 0 && height >= 0); + scene_buffer->dst_width = width; + scene_buffer->dst_height = height; + scene_node_update(&scene_buffer->node, NULL); +} + +void wlr_scene_buffer_set_transform(struct wlr_scene_buffer *scene_buffer, + enum wl_output_transform transform) { + if (scene_buffer->transform == transform) { + return; + } + + scene_buffer->transform = transform; + scene_node_update(&scene_buffer->node, NULL); +} + +void wlr_scene_buffer_send_frame_done(struct wlr_scene_buffer *scene_buffer, + struct wlr_scene_frame_done_event *event) { + if (!pixman_region32_empty(&scene_buffer->node.visible)) { + wl_signal_emit_mutable(&scene_buffer->events.frame_done, event); + } +} + +void wlr_scene_buffer_set_opacity(struct wlr_scene_buffer *scene_buffer, + float opacity) { + if (scene_buffer->opacity == opacity) { + return; + } + + assert(opacity >= 0 && opacity <= 1); + scene_buffer->opacity = opacity; + scene_node_update(&scene_buffer->node, NULL); +} + +void wlr_scene_buffer_set_filter_mode(struct wlr_scene_buffer *scene_buffer, + enum wlr_scale_filter_mode filter_mode) { + if (scene_buffer->filter_mode == filter_mode) { + return; + } + + scene_buffer->filter_mode = filter_mode; + scene_node_update(&scene_buffer->node, NULL); +} + +void wlr_scene_buffer_set_transfer_function(struct wlr_scene_buffer *scene_buffer, + enum wlr_color_transfer_function transfer_function) { + if (scene_buffer->transfer_function == transfer_function) { + return; + } + + scene_buffer->transfer_function = transfer_function; + scene_node_update(&scene_buffer->node, NULL); +} + +void wlr_scene_buffer_set_primaries(struct wlr_scene_buffer *scene_buffer, + enum wlr_color_named_primaries primaries) { + if (scene_buffer->primaries == primaries) { + return; + } + + scene_buffer->primaries = primaries; + scene_node_update(&scene_buffer->node, NULL); +} + +void wlr_scene_buffer_set_color_encoding(struct wlr_scene_buffer *scene_buffer, + enum wlr_color_encoding color_encoding) { + if (scene_buffer->color_encoding == color_encoding) { + return; + } + + scene_buffer->color_encoding = color_encoding; + scene_node_update(&scene_buffer->node, NULL); +} + +void wlr_scene_buffer_set_color_range(struct wlr_scene_buffer *scene_buffer, + enum wlr_color_range color_range) { + if (scene_buffer->color_range == color_range) { + return; + } + + scene_buffer->color_range = color_range; + scene_node_update(&scene_buffer->node, NULL); +} + +static struct wlr_texture *scene_buffer_get_texture( + struct wlr_scene_buffer *scene_buffer, struct wlr_renderer *renderer) { + if (scene_buffer->buffer == NULL || scene_buffer->texture != NULL) { + return scene_buffer->texture; + } + + struct wlr_client_buffer *client_buffer = + wlr_client_buffer_get(scene_buffer->buffer); + if (client_buffer != NULL) { + return client_buffer->texture; + } + + struct wlr_texture *texture = + wlr_texture_from_buffer(renderer, scene_buffer->buffer); + if (texture != NULL && scene_buffer->own_buffer) { + scene_buffer->own_buffer = false; + wlr_buffer_unlock(scene_buffer->buffer); + } + scene_buffer_set_texture(scene_buffer, texture); + return texture; +} + +void scene_node_get_size(struct wlr_scene_node *node, int *width, int *height) { + *width = 0; + *height = 0; + + switch (node->type) { + case WLR_SCENE_NODE_TREE: + return; + case WLR_SCENE_NODE_RECT:; + struct wlr_scene_rect *scene_rect = wlr_scene_rect_from_node(node); + *width = scene_rect->width; + *height = scene_rect->height; + break; + case WLR_SCENE_NODE_BUFFER:; + struct wlr_scene_buffer *scene_buffer = wlr_scene_buffer_from_node(node); + if (scene_buffer->dst_width > 0 && scene_buffer->dst_height > 0) { + *width = scene_buffer->dst_width; + *height = scene_buffer->dst_height; + } else { + *width = scene_buffer->buffer_width; + *height = scene_buffer->buffer_height; + wlr_output_transform_coords(scene_buffer->transform, width, height); + } + break; + } +} + +void wlr_scene_node_set_enabled(struct wlr_scene_node *node, bool enabled) { + if (node->enabled == enabled) { + return; + } + + int x, y; + pixman_region32_t visible; + pixman_region32_init(&visible); + if (wlr_scene_node_coords(node, &x, &y)) { + scene_node_visibility(node, &visible); + } + + node->enabled = enabled; + + scene_node_update(node, &visible); +} + +void wlr_scene_node_set_position(struct wlr_scene_node *node, int x, int y) { + if (node->x == x && node->y == y) { + return; + } + + node->x = x; + node->y = y; + scene_node_update(node, NULL); +} + +void wlr_scene_node_place_above(struct wlr_scene_node *node, + struct wlr_scene_node *sibling) { + assert(node != sibling); + assert(node->parent == sibling->parent); + + if (node->link.prev == &sibling->link) { + return; + } + + wl_list_remove(&node->link); + wl_list_insert(&sibling->link, &node->link); + scene_node_update(node, NULL); +} + +void wlr_scene_node_place_below(struct wlr_scene_node *node, + struct wlr_scene_node *sibling) { + assert(node != sibling); + assert(node->parent == sibling->parent); + + if (node->link.next == &sibling->link) { + return; + } + + wl_list_remove(&node->link); + wl_list_insert(sibling->link.prev, &node->link); + scene_node_update(node, NULL); +} + +void wlr_scene_node_raise_to_top(struct wlr_scene_node *node) { + struct wlr_scene_node *current_top = wl_container_of( + node->parent->children.prev, current_top, link); + if (node == current_top) { + return; + } + wlr_scene_node_place_above(node, current_top); +} + +void wlr_scene_node_lower_to_bottom(struct wlr_scene_node *node) { + struct wlr_scene_node *current_bottom = wl_container_of( + node->parent->children.next, current_bottom, link); + if (node == current_bottom) { + return; + } + wlr_scene_node_place_below(node, current_bottom); +} + +void wlr_scene_node_reparent(struct wlr_scene_node *node, + struct wlr_scene_tree *new_parent) { + assert(new_parent != NULL); + + if (node->parent == new_parent) { + return; + } + + /* Ensure that a node cannot become its own ancestor */ + for (struct wlr_scene_tree *ancestor = new_parent; ancestor != NULL; + ancestor = ancestor->node.parent) { + assert(&ancestor->node != node); + } + + int x, y; + pixman_region32_t visible; + pixman_region32_init(&visible); + if (wlr_scene_node_coords(node, &x, &y)) { + scene_node_visibility(node, &visible); + } + + wl_list_remove(&node->link); + node->parent = new_parent; + wl_list_insert(new_parent->children.prev, &node->link); + scene_node_update(node, &visible); +} + +bool wlr_scene_node_coords(struct wlr_scene_node *node, + int *lx_ptr, int *ly_ptr) { + assert(node); + + int lx = 0, ly = 0; + bool enabled = true; + while (true) { + lx += node->x; + ly += node->y; + enabled = enabled && node->enabled; + if (node->parent == NULL) { + break; + } + + node = &node->parent->node; + } + + *lx_ptr = lx; + *ly_ptr = ly; + return enabled; +} + +static void scene_node_for_each_scene_buffer(struct wlr_scene_node *node, + int lx, int ly, wlr_scene_buffer_iterator_func_t user_iterator, + void *user_data) { + if (!node->enabled) { + return; + } + + lx += node->x; + ly += node->y; + + if (node->type == WLR_SCENE_NODE_BUFFER) { + struct wlr_scene_buffer *scene_buffer = wlr_scene_buffer_from_node(node); + user_iterator(scene_buffer, lx, ly, user_data); + } else if (node->type == WLR_SCENE_NODE_TREE) { + struct wlr_scene_tree *scene_tree = wlr_scene_tree_from_node(node); + struct wlr_scene_node *child; + wl_list_for_each(child, &scene_tree->children, link) { + scene_node_for_each_scene_buffer(child, lx, ly, user_iterator, user_data); + } + } +} + +void wlr_scene_node_for_each_buffer(struct wlr_scene_node *node, + wlr_scene_buffer_iterator_func_t user_iterator, void *user_data) { + scene_node_for_each_scene_buffer(node, 0, 0, user_iterator, user_data); +} + +struct node_at_data { + double lx, ly; + double rx, ry; + struct wlr_scene_node *node; +}; + +static bool scene_node_at_iterator(struct wlr_scene_node *node, + int lx, int ly, void *data) { + struct node_at_data *at_data = data; + + double rx = at_data->lx - lx; + double ry = at_data->ly - ly; + + if (node->type == WLR_SCENE_NODE_BUFFER) { + struct wlr_scene_buffer *scene_buffer = wlr_scene_buffer_from_node(node); + + if (scene_buffer->point_accepts_input && + !scene_buffer->point_accepts_input(scene_buffer, &rx, &ry)) { + return false; + } + } + + at_data->rx = rx; + at_data->ry = ry; + at_data->node = node; + return true; +} + +struct wlr_scene_node *wlr_scene_node_at(struct wlr_scene_node *node, + double lx, double ly, double *nx, double *ny) { + struct wlr_box box = { + .x = floor(lx), + .y = floor(ly), + .width = 1, + .height = 1 + }; + + struct node_at_data data = { + .lx = lx, + .ly = ly + }; + + if (scene_nodes_in_box(node, &box, scene_node_at_iterator, &data)) { + if (nx) { + *nx = data.rx; + } + if (ny) { + *ny = data.ry; + } + return data.node; + } + + return NULL; +} + +struct render_list_entry { + struct wlr_scene_node *node; + bool highlight_transparent_region; + int x, y; +}; + +static float get_luminance_multiplier(const struct wlr_color_luminances *src_lum, + const struct wlr_color_luminances *dst_lum) { + return (dst_lum->reference / src_lum->reference) * (src_lum->max / dst_lum->max); +} + +static void scene_entry_render(struct render_list_entry *entry, const struct render_data *data) { + struct wlr_scene_node *node = entry->node; + + pixman_region32_t render_region; + pixman_region32_init(&render_region); + pixman_region32_copy(&render_region, &node->visible); + pixman_region32_translate(&render_region, -data->logical.x, -data->logical.y); + logical_to_buffer_coords(&render_region, data, true); + pixman_region32_intersect(&render_region, &render_region, &data->damage); + if (pixman_region32_empty(&render_region)) { + pixman_region32_fini(&render_region); + return; + } + + int x = entry->x - data->logical.x; + int y = entry->y - data->logical.y; + + struct wlr_box dst_box = { + .x = x, + .y = y, + }; + scene_node_get_size(node, &dst_box.width, &dst_box.height); + transform_output_box(&dst_box, data); + + pixman_region32_t opaque; + pixman_region32_init(&opaque); + scene_node_opaque_region(node, x, y, &opaque); + logical_to_buffer_coords(&opaque, data, false); + pixman_region32_subtract(&opaque, &render_region, &opaque); + + switch (node->type) { + case WLR_SCENE_NODE_TREE: + assert(false); + break; + case WLR_SCENE_NODE_RECT:; + struct wlr_scene_rect *scene_rect = wlr_scene_rect_from_node(node); + + wlr_render_pass_add_rect(data->render_pass, &(struct wlr_render_rect_options){ + .box = dst_box, + .color = { + .r = scene_rect->color[0], + .g = scene_rect->color[1], + .b = scene_rect->color[2], + .a = scene_rect->color[3], + }, + .clip = &render_region, + }); + break; + case WLR_SCENE_NODE_BUFFER:; + struct wlr_scene_buffer *scene_buffer = wlr_scene_buffer_from_node(node); + + if (scene_buffer->is_single_pixel_buffer) { + // Render the buffer as a rect, this is likely to be more efficient + wlr_render_pass_add_rect(data->render_pass, &(struct wlr_render_rect_options){ + .box = dst_box, + .color = { + .r = (float)scene_buffer->single_pixel_buffer_color[0] / (float)UINT32_MAX, + .g = (float)scene_buffer->single_pixel_buffer_color[1] / (float)UINT32_MAX, + .b = (float)scene_buffer->single_pixel_buffer_color[2] / (float)UINT32_MAX, + .a = (float)scene_buffer->single_pixel_buffer_color[3] / + (float)UINT32_MAX * scene_buffer->opacity, + }, + .clip = &render_region, + }); + break; + } + + struct wlr_texture *texture = scene_buffer_get_texture(scene_buffer, + data->output->output->renderer); + if (texture == NULL) { + scene_output_damage(data->output, &render_region); + break; + } + + enum wl_output_transform transform = + wlr_output_transform_invert(scene_buffer->transform); + transform = wlr_output_transform_compose(transform, data->transform); + + struct wlr_color_primaries primaries = {0}; + if (scene_buffer->primaries != 0) { + wlr_color_primaries_from_named(&primaries, scene_buffer->primaries); + } + + struct wlr_color_luminances src_lum, srgb_lum; + wlr_color_transfer_function_get_default_luminance( + scene_buffer->transfer_function, &src_lum); + wlr_color_transfer_function_get_default_luminance( + WLR_COLOR_TRANSFER_FUNCTION_SRGB, &srgb_lum); + float luminance_multiplier = get_luminance_multiplier(&src_lum, &srgb_lum); + + wlr_render_pass_add_texture(data->render_pass, &(struct wlr_render_texture_options) { + .texture = texture, + .src_box = scene_buffer->src_box, + .dst_box = dst_box, + .transform = transform, + .clip = &render_region, + .alpha = &scene_buffer->opacity, + .filter_mode = scene_buffer->filter_mode, + .blend_mode = !data->output->scene->calculate_visibility || + !pixman_region32_empty(&opaque) ? + WLR_RENDER_BLEND_MODE_PREMULTIPLIED : WLR_RENDER_BLEND_MODE_NONE, + .transfer_function = scene_buffer->transfer_function, + .primaries = scene_buffer->primaries != 0 ? &primaries : NULL, + .color_encoding = scene_buffer->color_encoding, + .color_range = scene_buffer->color_range, + .luminance_multiplier = &luminance_multiplier, + .wait_timeline = scene_buffer->wait_timeline, + .wait_point = scene_buffer->wait_point, + }); + + struct wlr_scene_output_sample_event sample_event = { + .output = data->output, + .direct_scanout = false, + .release_timeline = data->output->in_timeline, + .release_point = data->output->in_point, + }; + wl_signal_emit_mutable(&scene_buffer->events.output_sample, &sample_event); + + if (entry->highlight_transparent_region) { + wlr_render_pass_add_rect(data->render_pass, &(struct wlr_render_rect_options){ + .box = dst_box, + .color = { .r = 0, .g = 0.3, .b = 0, .a = 0.3 }, + .clip = &opaque, + }); + } + + break; + } + + pixman_region32_fini(&opaque); + pixman_region32_fini(&render_region); +} + +static void scene_handle_linux_dmabuf_v1_destroy(struct wl_listener *listener, + void *data) { + struct wlr_scene *scene = + wl_container_of(listener, scene, linux_dmabuf_v1_destroy); + wl_list_remove(&scene->linux_dmabuf_v1_destroy.link); + wl_list_init(&scene->linux_dmabuf_v1_destroy.link); + scene->linux_dmabuf_v1 = NULL; +} + +void wlr_scene_set_linux_dmabuf_v1(struct wlr_scene *scene, + struct wlr_linux_dmabuf_v1 *linux_dmabuf_v1) { + assert(scene->linux_dmabuf_v1 == NULL); + scene->linux_dmabuf_v1 = linux_dmabuf_v1; + scene->linux_dmabuf_v1_destroy.notify = scene_handle_linux_dmabuf_v1_destroy; + wl_signal_add(&linux_dmabuf_v1->events.destroy, &scene->linux_dmabuf_v1_destroy); +} + +static void scene_handle_gamma_control_manager_v1_set_gamma(struct wl_listener *listener, + void *data) { + const struct wlr_gamma_control_manager_v1_set_gamma_event *event = data; + struct wlr_scene *scene = + wl_container_of(listener, scene, gamma_control_manager_v1_set_gamma); + struct wlr_scene_output *output = wlr_scene_get_scene_output(scene, event->output); + if (!output) { + // this scene might not own this output. + return; + } + + output->gamma_lut_changed = true; + output->gamma_lut = event->control; + wlr_color_transform_unref(output->gamma_lut_color_transform); + output->gamma_lut_color_transform = wlr_gamma_control_v1_get_color_transform(event->control); + wlr_output_schedule_frame(output->output); +} + +static void scene_handle_gamma_control_manager_v1_destroy(struct wl_listener *listener, + void *data) { + struct wlr_scene *scene = + wl_container_of(listener, scene, gamma_control_manager_v1_destroy); + wl_list_remove(&scene->gamma_control_manager_v1_destroy.link); + wl_list_init(&scene->gamma_control_manager_v1_destroy.link); + wl_list_remove(&scene->gamma_control_manager_v1_set_gamma.link); + wl_list_init(&scene->gamma_control_manager_v1_set_gamma.link); + scene->gamma_control_manager_v1 = NULL; + + struct wlr_scene_output *output; + wl_list_for_each(output, &scene->outputs, link) { + output->gamma_lut_changed = false; + output->gamma_lut = NULL; + wlr_color_transform_unref(output->gamma_lut_color_transform); + output->gamma_lut_color_transform = NULL; + } +} + +void wlr_scene_set_gamma_control_manager_v1(struct wlr_scene *scene, + struct wlr_gamma_control_manager_v1 *gamma_control) { + assert(scene->gamma_control_manager_v1 == NULL); + scene->gamma_control_manager_v1 = gamma_control; + + scene->gamma_control_manager_v1_destroy.notify = + scene_handle_gamma_control_manager_v1_destroy; + wl_signal_add(&gamma_control->events.destroy, &scene->gamma_control_manager_v1_destroy); + scene->gamma_control_manager_v1_set_gamma.notify = + scene_handle_gamma_control_manager_v1_set_gamma; + wl_signal_add(&gamma_control->events.set_gamma, &scene->gamma_control_manager_v1_set_gamma); +} + +static void scene_handle_color_manager_v1_destroy(struct wl_listener *listener, void *data) { + struct wlr_scene *scene = wl_container_of(listener, scene, color_manager_v1_destroy); + wl_list_remove(&scene->color_manager_v1_destroy.link); + wl_list_init(&scene->color_manager_v1_destroy.link); + scene->color_manager_v1 = NULL; +} + +void wlr_scene_set_color_manager_v1(struct wlr_scene *scene, struct wlr_color_manager_v1 *manager) { + assert(scene->color_manager_v1 == NULL); + scene->color_manager_v1 = manager; + + scene->color_manager_v1_destroy.notify = scene_handle_color_manager_v1_destroy; + wl_signal_add(&manager->events.destroy, &scene->color_manager_v1_destroy); +} + +static void scene_output_handle_destroy(struct wlr_addon *addon) { + struct wlr_scene_output *scene_output = + wl_container_of(addon, scene_output, addon); + wlr_scene_output_destroy(scene_output); +} + +static const struct wlr_addon_interface output_addon_impl = { + .name = "wlr_scene_output", + .destroy = scene_output_handle_destroy, +}; + +static void scene_node_output_update(struct wlr_scene_node *node, + struct wl_list *outputs, struct wlr_scene_output *ignore, + struct wlr_scene_output *force) { + if (node->type == WLR_SCENE_NODE_TREE) { + struct wlr_scene_tree *scene_tree = wlr_scene_tree_from_node(node); + struct wlr_scene_node *child; + wl_list_for_each(child, &scene_tree->children, link) { + scene_node_output_update(child, outputs, ignore, force); + } + return; + } + + update_node_update_outputs(node, outputs, ignore, force); +} + +static void scene_output_update_geometry(struct wlr_scene_output *scene_output, + bool force_update) { + scene_output_damage_whole(scene_output); + + scene_node_output_update(&scene_output->scene->tree.node, + &scene_output->scene->outputs, NULL, force_update ? scene_output : NULL); +} + +static void scene_output_handle_commit(struct wl_listener *listener, void *data) { + struct wlr_scene_output *scene_output = wl_container_of(listener, + scene_output, output_commit); + struct wlr_output_event_commit *event = data; + const struct wlr_output_state *state = event->state; + + // if the output has been committed with a certain damage, we know that region + // will be acknowledged by the backend so we don't need to keep track of it + // anymore + if (state->committed & WLR_OUTPUT_STATE_BUFFER) { + if (state->committed & WLR_OUTPUT_STATE_DAMAGE) { + pixman_region32_subtract(&scene_output->pending_commit_damage, + &scene_output->pending_commit_damage, &state->damage); + } else { + pixman_region32_fini(&scene_output->pending_commit_damage); + pixman_region32_init(&scene_output->pending_commit_damage); + } + } + + bool force_update = state->committed & ( + WLR_OUTPUT_STATE_TRANSFORM | + WLR_OUTPUT_STATE_SCALE | + WLR_OUTPUT_STATE_SUBPIXEL); + + if (force_update || state->committed & (WLR_OUTPUT_STATE_MODE | + WLR_OUTPUT_STATE_ENABLED)) { + scene_output_update_geometry(scene_output, force_update); + } + + if (scene_output->scene->debug_damage_option == WLR_SCENE_DEBUG_DAMAGE_HIGHLIGHT && + !wl_list_empty(&scene_output->damage_highlight_regions)) { + wlr_output_schedule_frame(scene_output->output); + } + + // Next time the output is enabled, try to re-apply the gamma LUT + if (scene_output->scene->gamma_control_manager_v1 && + (state->committed & WLR_OUTPUT_STATE_ENABLED) && + !scene_output->output->enabled) { + scene_output->gamma_lut_changed = true; + } +} + +static void scene_output_handle_damage(struct wl_listener *listener, void *data) { + struct wlr_scene_output *scene_output = wl_container_of(listener, + scene_output, output_damage); + struct wlr_output *output = scene_output->output; + struct wlr_output_event_damage *event = data; + + int width, height; + wlr_output_transformed_resolution(output, &width, &height); + + pixman_region32_t damage; + pixman_region32_init(&damage); + pixman_region32_copy(&damage, event->damage); + wlr_region_transform(&damage, &damage, + wlr_output_transform_invert(output->transform), width, height); + scene_output_damage(scene_output, &damage); + pixman_region32_fini(&damage); +} + +static void scene_output_handle_needs_frame(struct wl_listener *listener, void *data) { + struct wlr_scene_output *scene_output = wl_container_of(listener, + scene_output, output_needs_frame); + wlr_output_schedule_frame(scene_output->output); +} + +struct wlr_scene_output *wlr_scene_output_create(struct wlr_scene *scene, + struct wlr_output *output) { + struct wlr_scene_output *scene_output = calloc(1, sizeof(*scene_output)); + if (scene_output == NULL) { + return NULL; + } + + scene_output->output = output; + scene_output->scene = scene; + wlr_addon_init(&scene_output->addon, &output->addons, scene, &output_addon_impl); + + wlr_damage_ring_init(&scene_output->damage_ring); + pixman_region32_init(&scene_output->pending_commit_damage); + wl_list_init(&scene_output->damage_highlight_regions); + + int prev_output_index = -1; + struct wl_list *prev_output_link = &scene->outputs; + + struct wlr_scene_output *current_output; + wl_list_for_each(current_output, &scene->outputs, link) { + if (prev_output_index + 1 != current_output->index) { + break; + } + + prev_output_index = current_output->index; + prev_output_link = ¤t_output->link; + } + + int drm_fd = wlr_backend_get_drm_fd(output->backend); + if (drm_fd >= 0 && output->backend->features.timeline && + output->renderer != NULL && output->renderer->features.timeline) { + scene_output->in_timeline = wlr_drm_syncobj_timeline_create(drm_fd); + scene_output->out_timeline = wlr_drm_syncobj_timeline_create(drm_fd); + if (scene_output->in_timeline == NULL || scene_output->out_timeline == NULL) { + wlr_drm_syncobj_timeline_unref(scene_output->in_timeline); + wlr_drm_syncobj_timeline_unref(scene_output->out_timeline); + return NULL; + } + } + + scene_output->index = prev_output_index + 1; + assert(scene_output->index < 64); + wl_list_insert(prev_output_link, &scene_output->link); + + wl_signal_init(&scene_output->events.destroy); + + scene_output->output_commit.notify = scene_output_handle_commit; + wl_signal_add(&output->events.commit, &scene_output->output_commit); + + scene_output->output_damage.notify = scene_output_handle_damage; + wl_signal_add(&output->events.damage, &scene_output->output_damage); + + scene_output->output_needs_frame.notify = scene_output_handle_needs_frame; + wl_signal_add(&output->events.needs_frame, &scene_output->output_needs_frame); + + scene_output_update_geometry(scene_output, false); + + return scene_output; +} + +static void highlight_region_destroy(struct highlight_region *damage) { + wl_list_remove(&damage->link); + pixman_region32_fini(&damage->region); + free(damage); +} + +void wlr_scene_output_destroy(struct wlr_scene_output *scene_output) { + if (scene_output == NULL) { + return; + } + + wl_signal_emit_mutable(&scene_output->events.destroy, NULL); + + scene_node_output_update(&scene_output->scene->tree.node, + &scene_output->scene->outputs, scene_output, NULL); + + assert(wl_list_empty(&scene_output->events.destroy.listener_list)); + + struct highlight_region *damage, *tmp_damage; + wl_list_for_each_safe(damage, tmp_damage, &scene_output->damage_highlight_regions, link) { + highlight_region_destroy(damage); + } + + wlr_addon_finish(&scene_output->addon); + wlr_damage_ring_finish(&scene_output->damage_ring); + pixman_region32_fini(&scene_output->pending_commit_damage); + wl_list_remove(&scene_output->link); + wl_list_remove(&scene_output->output_commit.link); + wl_list_remove(&scene_output->output_damage.link); + wl_list_remove(&scene_output->output_needs_frame.link); + if (scene_output->in_timeline != NULL) { + wlr_drm_syncobj_timeline_signal(scene_output->in_timeline, UINT64_MAX); + wlr_drm_syncobj_timeline_unref(scene_output->in_timeline); + } + if (scene_output->out_timeline != NULL) { + wlr_drm_syncobj_timeline_signal(scene_output->out_timeline, UINT64_MAX); + wlr_drm_syncobj_timeline_unref(scene_output->out_timeline); + } + wlr_color_transform_unref(scene_output->gamma_lut_color_transform); + wlr_color_transform_unref(scene_output->prev_gamma_lut_color_transform); + wlr_color_transform_unref(scene_output->prev_supplied_color_transform); + wlr_color_transform_unref(scene_output->combined_color_transform); + wl_array_release(&scene_output->render_list); + free(scene_output); +} + +struct wlr_scene_output *wlr_scene_get_scene_output(struct wlr_scene *scene, + struct wlr_output *output) { + struct wlr_addon *addon = + wlr_addon_find(&output->addons, scene, &output_addon_impl); + if (addon == NULL) { + return NULL; + } + struct wlr_scene_output *scene_output = + wl_container_of(addon, scene_output, addon); + return scene_output; +} + +void wlr_scene_output_set_position(struct wlr_scene_output *scene_output, + int lx, int ly) { + if (scene_output->x == lx && scene_output->y == ly) { + return; + } + + scene_output->x = lx; + scene_output->y = ly; + + scene_output_update_geometry(scene_output, false); +} + +static bool scene_node_invisible(struct wlr_scene_node *node) { + if (node->type == WLR_SCENE_NODE_TREE) { + return true; + } else if (node->type == WLR_SCENE_NODE_RECT) { + struct wlr_scene_rect *rect = wlr_scene_rect_from_node(node); + + return rect->color[3] == 0.f; + } else if (node->type == WLR_SCENE_NODE_BUFFER) { + struct wlr_scene_buffer *buffer = wlr_scene_buffer_from_node(node); + + return buffer->buffer == NULL && buffer->texture == NULL; + } + + return false; +} + +struct render_list_constructor_data { + struct wlr_box box; + struct wl_array *render_list; + bool calculate_visibility; + bool highlight_transparent_region; + bool fractional_scale; +}; + +static bool scene_buffer_is_black_opaque(struct wlr_scene_buffer *scene_buffer) { + return scene_buffer->is_single_pixel_buffer && + scene_buffer->single_pixel_buffer_color[0] == 0 && + scene_buffer->single_pixel_buffer_color[1] == 0 && + scene_buffer->single_pixel_buffer_color[2] == 0 && + scene_buffer->single_pixel_buffer_color[3] == UINT32_MAX && + scene_buffer->opacity == 1.0; +} + +static bool construct_render_list_iterator(struct wlr_scene_node *node, + int lx, int ly, void *_data) { + struct render_list_constructor_data *data = _data; + + if (scene_node_invisible(node)) { + return false; + } + + // While rendering, the background should always be black. If we see a + // black rect, we can ignore rendering everything under the rect, and + // unless fractional scale is used even the rect itself (to avoid running + // into issues regarding damage region expansion). + if (node->type == WLR_SCENE_NODE_RECT && data->calculate_visibility && + (!data->fractional_scale || data->render_list->size == 0)) { + struct wlr_scene_rect *rect = wlr_scene_rect_from_node(node); + float *black = (float[4]){ 0.f, 0.f, 0.f, 1.f }; + + if (memcmp(rect->color, black, sizeof(float) * 4) == 0) { + return false; + } + } + + // Apply the same special-case to black opaque single-pixel buffers + if (node->type == WLR_SCENE_NODE_BUFFER && data->calculate_visibility && + (!data->fractional_scale || data->render_list->size == 0)) { + struct wlr_scene_buffer *scene_buffer = wlr_scene_buffer_from_node(node); + + if (scene_buffer_is_black_opaque(scene_buffer)) { + return false; + } + } + + pixman_region32_t intersection; + pixman_region32_init(&intersection); + pixman_region32_intersect_rect(&intersection, &node->visible, + data->box.x, data->box.y, + data->box.width, data->box.height); + if (pixman_region32_empty(&intersection)) { + pixman_region32_fini(&intersection); + return false; + } + + pixman_region32_fini(&intersection); + + struct render_list_entry *entry = wl_array_add(data->render_list, sizeof(*entry)); + if (!entry) { + return false; + } + + *entry = (struct render_list_entry){ + .node = node, + .x = lx, + .y = ly, + .highlight_transparent_region = data->highlight_transparent_region, + }; + + return false; +} + +static void scene_buffer_send_dmabuf_feedback(const struct wlr_scene *scene, + struct wlr_scene_buffer *scene_buffer, + const struct wlr_linux_dmabuf_feedback_v1_init_options *options) { + if (!scene->linux_dmabuf_v1) { + return; + } + + struct wlr_scene_surface *surface = wlr_scene_surface_try_from_buffer(scene_buffer); + if (!surface) { + return; + } + + // compare to the previous options so that we don't send + // duplicate feedback events. + if (memcmp(options, &scene_buffer->prev_feedback_options, sizeof(*options)) == 0) { + return; + } + + scene_buffer->prev_feedback_options = *options; + + struct wlr_linux_dmabuf_feedback_v1 feedback = {0}; + if (!wlr_linux_dmabuf_feedback_v1_init_with_options(&feedback, options)) { + return; + } + + enum wl_output_transform preferred_buffer_transform = WL_OUTPUT_TRANSFORM_NORMAL; + if (options->scanout_primary_output != NULL) { + preferred_buffer_transform = options->scanout_primary_output->transform; + } + + // TODO: also send wl_surface.preferred_buffer_transform when running with + // pure software rendering + wlr_surface_set_preferred_buffer_transform(surface->surface, preferred_buffer_transform); + wlr_linux_dmabuf_v1_set_surface_feedback(scene->linux_dmabuf_v1, + surface->surface, &feedback); + + wlr_linux_dmabuf_feedback_v1_finish(&feedback); +} + +static bool color_management_is_scanout_allowed(const struct wlr_output_image_description *img_desc, + const struct wlr_scene_buffer *buffer) { + // Disallow scanout if the output has colorimetry information but buffer + // doesn't; allow it only if the output also lacks it. + if (buffer->transfer_function == 0 && buffer->primaries == 0) { + return img_desc == NULL; + } + + // If the output has colorimetry information, the buffer must match it for + // direct scanout to be allowed. + if (img_desc != NULL) { + return img_desc->transfer_function == buffer->transfer_function && + img_desc->primaries == buffer->primaries; + } + // If the output doesn't have colorimetry image description set, we can only + // scan out buffers with default colorimetry (gamma2.2 transfer and sRGB + // primaries) used in wlroots. + return buffer->transfer_function == WLR_COLOR_TRANSFER_FUNCTION_GAMMA22 && + buffer->primaries == WLR_COLOR_NAMED_PRIMARIES_SRGB; +} + +enum scene_direct_scanout_result { + // This scene node is not a candidate for scanout + SCANOUT_INELIGIBLE, + + // This scene node is a candidate for scanout, but is currently + // incompatible due to e.g. buffer mismatch, and if possible we'd like to + // resolve this incompatibility. + SCANOUT_CANDIDATE, + + // Scanout is successful. + SCANOUT_SUCCESS, +}; + +static enum scene_direct_scanout_result scene_entry_try_direct_scanout( + struct render_list_entry *entry, struct wlr_output_state *state, + const struct render_data *data) { + struct wlr_scene_output *scene_output = data->output; + struct wlr_scene_node *node = entry->node; + + if (!scene_output->scene->direct_scanout) { + return SCANOUT_INELIGIBLE; + } + + if (node->type != WLR_SCENE_NODE_BUFFER) { + return SCANOUT_INELIGIBLE; + } + + if (state->committed & (WLR_OUTPUT_STATE_MODE | + WLR_OUTPUT_STATE_ENABLED | + WLR_OUTPUT_STATE_RENDER_FORMAT)) { + // Legacy DRM will explode if we try to modeset with a direct scanout buffer + return SCANOUT_INELIGIBLE; + } + + if (!wlr_output_is_direct_scanout_allowed(scene_output->output)) { + return SCANOUT_INELIGIBLE; + } + + struct wlr_scene_buffer *buffer = wlr_scene_buffer_from_node(node); + if (buffer->buffer == NULL) { + return SCANOUT_INELIGIBLE; + } + + // The native size of the buffer after any transform is applied + int default_width = buffer->buffer->width; + int default_height = buffer->buffer->height; + wlr_output_transform_coords(buffer->transform, &default_width, &default_height); + struct wlr_fbox default_box = { + .width = default_width, + .height = default_height, + }; + + if (buffer->transform != data->transform) { + return SCANOUT_INELIGIBLE; + } + + const struct wlr_output_image_description *img_desc = output_pending_image_description(scene_output->output, state); + if (!color_management_is_scanout_allowed(img_desc, buffer)) { + return SCANOUT_INELIGIBLE; + } + + bool is_color_repr_none = buffer->color_encoding == WLR_COLOR_ENCODING_NONE && + buffer->color_range == WLR_COLOR_RANGE_NONE; + bool is_color_repr_identity_full = buffer->color_encoding == WLR_COLOR_ENCODING_IDENTITY && + buffer->color_range == WLR_COLOR_RANGE_FULL; + + if (!(is_color_repr_none || is_color_repr_identity_full)) { + return SCANOUT_INELIGIBLE; + } + + // We want to ensure optimal buffer selection, but as direct-scanout can be enabled and disabled + // on a frame-by-frame basis, we wait for a few frames to send the new format recommendations. + // Maybe we should only send feedback in this case if tests fail. + if (scene_output->dmabuf_feedback_debounce >= DMABUF_FEEDBACK_DEBOUNCE_FRAMES + && buffer->primary_output == scene_output) { + struct wlr_linux_dmabuf_feedback_v1_init_options options = { + .main_renderer = scene_output->output->renderer, + .scanout_primary_output = scene_output->output, + }; + + scene_buffer_send_dmabuf_feedback(scene_output->scene, buffer, &options); + } + + struct wlr_output_state pending; + wlr_output_state_init(&pending); + if (!wlr_output_state_copy(&pending, state)) { + return SCANOUT_CANDIDATE; + } + + if (!wlr_fbox_empty(&buffer->src_box) && + !wlr_fbox_equal(&buffer->src_box, &default_box)) { + pending.buffer_src_box = buffer->src_box; + } + + // Translate the position from scene coordinates to output coordinates + pending.buffer_dst_box.x = entry->x - scene_output->x; + pending.buffer_dst_box.y = entry->y - scene_output->y; + + scene_node_get_size(node, &pending.buffer_dst_box.width, &pending.buffer_dst_box.height); + transform_output_box(&pending.buffer_dst_box, data); + + struct wlr_buffer *wlr_buffer = buffer->buffer; + struct wlr_client_buffer *client_buffer = wlr_client_buffer_get(wlr_buffer); + if (client_buffer != NULL && client_buffer->source != NULL && client_buffer->source->n_locks > 0) { + wlr_buffer = client_buffer->source; + } + + wlr_output_state_set_buffer(&pending, wlr_buffer); + if (buffer->wait_timeline != NULL) { + wlr_output_state_set_wait_timeline(&pending, buffer->wait_timeline, buffer->wait_point); + } + + if (scene_output->out_timeline) { + scene_output->out_point++; + wlr_output_state_set_signal_timeline(&pending, scene_output->out_timeline, scene_output->out_point); + } + + if (!wlr_output_test_state(scene_output->output, &pending)) { + wlr_output_state_finish(&pending); + return SCANOUT_CANDIDATE; + } + + wlr_output_state_copy(state, &pending); + wlr_output_state_finish(&pending); + + struct wlr_scene_output_sample_event sample_event = { + .output = scene_output, + .direct_scanout = true, + .release_timeline = data->output->out_timeline, + .release_point = data->output->out_point, + }; + wl_signal_emit_mutable(&buffer->events.output_sample, &sample_event); + return SCANOUT_SUCCESS; +} + +bool wlr_scene_output_needs_frame(struct wlr_scene_output *scene_output) { + return scene_output->output->needs_frame || + !pixman_region32_empty(&scene_output->pending_commit_damage) || + scene_output->gamma_lut_changed; +} + +bool wlr_scene_output_commit(struct wlr_scene_output *scene_output, + const struct wlr_scene_output_state_options *options) { + if (!wlr_scene_output_needs_frame(scene_output)) { + return true; + } + + bool ok = false; + struct wlr_output_state state; + wlr_output_state_init(&state); + if (!wlr_scene_output_build_state(scene_output, &state, options)) { + goto out; + } + + ok = wlr_output_commit_state(scene_output->output, &state); + if (!ok) { + goto out; + } + +out: + wlr_output_state_finish(&state); + return ok; +} + +static void scene_output_state_attempt_gamma(struct wlr_scene_output *scene_output, + struct wlr_output_state *state) { + if (!scene_output->gamma_lut_changed) { + return; + } + + struct wlr_output_state gamma_pending = {0}; + if (!wlr_output_state_copy(&gamma_pending, state)) { + return; + } + + wlr_output_state_set_color_transform(&gamma_pending, scene_output->gamma_lut_color_transform); + scene_output->gamma_lut_changed = false; + + if (!wlr_output_test_state(scene_output->output, &gamma_pending)) { + wlr_gamma_control_v1_send_failed_and_destroy(scene_output->gamma_lut); + + scene_output->gamma_lut = NULL; + wlr_color_transform_unref(scene_output->gamma_lut_color_transform); + scene_output->gamma_lut_color_transform = NULL; + wlr_output_state_finish(&gamma_pending); + return; + } + + wlr_output_state_copy(state, &gamma_pending); + wlr_output_state_finish(&gamma_pending); +} + +static bool scene_output_combine_color_transforms( + struct wlr_scene_output *scene_output, struct wlr_color_transform *supplied, + const struct wlr_output_image_description *img_desc, bool render_gamma_lut) { + bool result = false; + struct wlr_color_transform *color_matrix = NULL; + struct wlr_color_transform *inv_eotf = NULL; + struct wlr_color_transform *user_gamma = NULL; + + if (img_desc != NULL) { + assert(supplied == NULL); + struct wlr_color_primaries primaries_srgb; + wlr_color_primaries_from_named(&primaries_srgb, WLR_COLOR_NAMED_PRIMARIES_SRGB); + struct wlr_color_primaries primaries; + wlr_color_primaries_from_named(&primaries, img_desc->primaries); + float matrix[9]; + wlr_color_primaries_transform_absolute_colorimetric(&primaries_srgb, &primaries, matrix); + + struct wlr_color_luminances srgb_lum, dst_lum; + wlr_color_transfer_function_get_default_luminance( + WLR_COLOR_TRANSFER_FUNCTION_SRGB, &srgb_lum); + wlr_color_transfer_function_get_default_luminance(img_desc->transfer_function, &dst_lum); + float luminance_multiplier = get_luminance_multiplier(&srgb_lum, &dst_lum); + for (int i = 0; i < 9; ++i) { + matrix[i] *= luminance_multiplier; + } + + color_matrix = wlr_color_transform_init_matrix(matrix); + inv_eotf = wlr_color_transform_init_linear_to_inverse_eotf(img_desc->transfer_function); + if (color_matrix == NULL || inv_eotf == NULL) { + goto cleanup_transforms; + } + } else if (supplied != NULL) { + inv_eotf = wlr_color_transform_ref(supplied); + } else { + inv_eotf = wlr_color_transform_init_linear_to_inverse_eotf( + WLR_COLOR_TRANSFER_FUNCTION_GAMMA22); + if (inv_eotf == NULL) { + goto cleanup_transforms; + } + } + + struct wlr_color_transform *gamma_lut = scene_output->gamma_lut_color_transform; + if (gamma_lut != NULL && render_gamma_lut) { + user_gamma = wlr_color_transform_ref(gamma_lut); + } + + struct wlr_color_transform *combined; + struct wlr_color_transform *transforms[] = { + color_matrix, + inv_eotf, + user_gamma, + }; + const size_t transforms_len = sizeof(transforms) / sizeof(transforms[0]); + if (!color_transform_compose(&combined, transforms, transforms_len)) { + goto cleanup_transforms; + } + + wlr_color_transform_unref(scene_output->prev_gamma_lut_color_transform); + scene_output->prev_gamma_lut_color_transform = gamma_lut ? wlr_color_transform_ref(gamma_lut) : NULL; + wlr_color_transform_unref(scene_output->prev_supplied_color_transform); + scene_output->prev_supplied_color_transform = supplied ? wlr_color_transform_ref(supplied) : NULL; + wlr_color_transform_unref(scene_output->combined_color_transform); + scene_output->combined_color_transform = combined; + + result = true; + +cleanup_transforms: + wlr_color_transform_unref(color_matrix); + wlr_color_transform_unref(inv_eotf); + wlr_color_transform_unref(user_gamma); + return result; +} + +bool wlr_scene_output_build_state(struct wlr_scene_output *scene_output, + struct wlr_output_state *state, const struct wlr_scene_output_state_options *options) { + struct wlr_scene_output_state_options default_options = {0}; + if (!options) { + options = &default_options; + } + struct wlr_scene_timer *timer = options->timer; + struct timespec start_time; + if (timer) { + clock_gettime(CLOCK_MONOTONIC, &start_time); + wlr_scene_timer_finish(timer); + *timer = (struct wlr_scene_timer){0}; + } + + if ((state->committed & WLR_OUTPUT_STATE_ENABLED) && !state->enabled) { + // if the state is being disabled, do nothing. + return true; + } + + struct wlr_output *output = scene_output->output; + enum wlr_scene_debug_damage_option debug_damage = + scene_output->scene->debug_damage_option; + + bool render_gamma_lut = false; + if (wlr_output_get_gamma_size(output) == 0 && output->renderer->features.output_color_transform) { + if (scene_output->gamma_lut_color_transform != scene_output->prev_gamma_lut_color_transform) { + scene_output_damage_whole(scene_output); + } + if (scene_output->gamma_lut_color_transform != NULL) { + render_gamma_lut = true; + } + } + + struct render_data render_data = { + .transform = output->transform, + .scale = output->scale, + .logical = { .x = scene_output->x, .y = scene_output->y }, + .output = scene_output, + }; + + int resolution_width, resolution_height; + output_pending_resolution(output, state, + &resolution_width, &resolution_height); + + if (state->committed & WLR_OUTPUT_STATE_TRANSFORM) { + if (render_data.transform != state->transform) { + scene_output_damage_whole(scene_output); + } + + render_data.transform = state->transform; + } + + if (state->committed & WLR_OUTPUT_STATE_SCALE) { + if (render_data.scale != state->scale) { + scene_output_damage_whole(scene_output); + } + + render_data.scale = state->scale; + } + + render_data.trans_width = resolution_width; + render_data.trans_height = resolution_height; + wlr_output_transform_coords(render_data.transform, + &render_data.trans_width, &render_data.trans_height); + + render_data.logical.width = render_data.trans_width / render_data.scale; + render_data.logical.height = render_data.trans_height / render_data.scale; + + struct render_list_constructor_data list_con = { + .box = render_data.logical, + .render_list = &scene_output->render_list, + .calculate_visibility = scene_output->scene->calculate_visibility, + .highlight_transparent_region = scene_output->scene->highlight_transparent_region, + .fractional_scale = floor(render_data.scale) != render_data.scale, + }; + + list_con.render_list->size = 0; + scene_nodes_in_box(&scene_output->scene->tree.node, &list_con.box, + construct_render_list_iterator, &list_con); + array_realloc(list_con.render_list, list_con.render_list->size); + + struct render_list_entry *list_data = list_con.render_list->data; + int list_len = list_con.render_list->size / sizeof(*list_data); + + if (debug_damage == WLR_SCENE_DEBUG_DAMAGE_RERENDER) { + scene_output_damage_whole(scene_output); + } + + struct timespec now; + if (debug_damage == WLR_SCENE_DEBUG_DAMAGE_HIGHLIGHT) { + struct wl_list *regions = &scene_output->damage_highlight_regions; + clock_gettime(CLOCK_MONOTONIC, &now); + + // add the current frame's damage if there is damage + if (!pixman_region32_empty(&scene_output->damage_ring.current)) { + struct highlight_region *current_damage = calloc(1, sizeof(*current_damage)); + if (current_damage) { + pixman_region32_init(¤t_damage->region); + pixman_region32_copy(¤t_damage->region, + &scene_output->damage_ring.current); + current_damage->when = now; + wl_list_insert(regions, ¤t_damage->link); + } + } + + pixman_region32_t acc_damage; + pixman_region32_init(&acc_damage); + struct highlight_region *damage, *tmp_damage; + wl_list_for_each_safe(damage, tmp_damage, regions, link) { + // remove overlapping damage regions + pixman_region32_subtract(&damage->region, &damage->region, &acc_damage); + pixman_region32_union(&acc_damage, &acc_damage, &damage->region); + + // if this damage is too old or has nothing in it, get rid of it + struct timespec time_diff; + timespec_sub(&time_diff, &now, &damage->when); + if (timespec_to_msec(&time_diff) >= HIGHLIGHT_DAMAGE_FADEOUT_TIME || + pixman_region32_empty(&damage->region)) { + highlight_region_destroy(damage); + } + } + + scene_output_damage(scene_output, &acc_damage); + pixman_region32_fini(&acc_damage); + } + + wlr_output_state_set_damage(state, &scene_output->pending_commit_damage); + + // We only want to try direct scanout if: + // - There is only one entry in the render list + // - There are no color transforms that need to be applied + // - Damage highlight debugging is not enabled + enum scene_direct_scanout_result scanout_result = SCANOUT_INELIGIBLE; + if (options->color_transform == NULL && !render_gamma_lut && list_len == 1 + && debug_damage != WLR_SCENE_DEBUG_DAMAGE_HIGHLIGHT) { + scanout_result = scene_entry_try_direct_scanout(&list_data[0], state, &render_data); + } + + if (scanout_result == SCANOUT_INELIGIBLE) { + if (scene_output->dmabuf_feedback_debounce > 0) { + // We cannot scan out, so count down towards sending composition dmabuf feedback + scene_output->dmabuf_feedback_debounce--; + } + } else if (scene_output->dmabuf_feedback_debounce < DMABUF_FEEDBACK_DEBOUNCE_FRAMES) { + // We either want to scan out or successfully scanned out, so count up towards sending + // scanout dmabuf feedback + scene_output->dmabuf_feedback_debounce++; + } + + bool scanout = scanout_result == SCANOUT_SUCCESS; + if (scene_output->prev_scanout != scanout) { + scene_output->prev_scanout = scanout; + wlr_log(WLR_DEBUG, "Direct scan-out %s", + scanout ? "enabled" : "disabled"); + } + + if (scanout) { + scene_output_state_attempt_gamma(scene_output, state); + + if (timer) { + struct timespec end_time, duration; + clock_gettime(CLOCK_MONOTONIC, &end_time); + timespec_sub(&duration, &end_time, &start_time); + timer->pre_render_duration = timespec_to_nsec(&duration); + } + return true; + } + + struct wlr_swapchain *swapchain = options->swapchain; + if (!swapchain) { + if (!wlr_output_configure_primary_swapchain(output, state, &output->swapchain)) { + return false; + } + + swapchain = output->swapchain; + } + + struct wlr_buffer *buffer = wlr_swapchain_acquire(swapchain); + if (buffer == NULL) { + return false; + } + + assert(buffer->width == resolution_width && buffer->height == resolution_height); + + if (timer) { + timer->render_timer = wlr_render_timer_create(output->renderer); + + struct timespec end_time, duration; + clock_gettime(CLOCK_MONOTONIC, &end_time); + timespec_sub(&duration, &end_time, &start_time); + timer->pre_render_duration = timespec_to_nsec(&duration); + } + + if ((render_gamma_lut + && scene_output->gamma_lut_color_transform != scene_output->prev_gamma_lut_color_transform) + || scene_output->prev_supplied_color_transform != options->color_transform + || (state->committed & WLR_OUTPUT_STATE_IMAGE_DESCRIPTION)) { + const struct wlr_output_image_description *output_description = + output_pending_image_description(output, state); + if (!scene_output_combine_color_transforms(scene_output, options->color_transform, + output_description, render_gamma_lut)) { + wlr_buffer_unlock(buffer); + return false; + } + } + + scene_output->in_point++; + struct wlr_render_pass *render_pass = wlr_renderer_begin_buffer_pass(output->renderer, buffer, + &(struct wlr_buffer_pass_options){ + .timer = timer ? timer->render_timer : NULL, + .color_transform = scene_output->combined_color_transform, + .signal_timeline = scene_output->in_timeline, + .signal_point = scene_output->in_point, + }); + if (render_pass == NULL) { + wlr_buffer_unlock(buffer); + return false; + } + + render_data.render_pass = render_pass; + + pixman_region32_init(&render_data.damage); + wlr_damage_ring_rotate_buffer(&scene_output->damage_ring, buffer, + &render_data.damage); + + pixman_region32_t background; + pixman_region32_init(&background); + pixman_region32_copy(&background, &render_data.damage); + + // Cull areas of the background that are occluded by opaque regions of + // scene nodes above. Those scene nodes will just render atop having us + // never see the background. + if (scene_output->scene->calculate_visibility) { + for (int i = list_len - 1; i >= 0; i--) { + struct render_list_entry *entry = &list_data[i]; + + // We must only cull opaque regions that are visible by the node. + // The node's visibility will have the knowledge of a black rect + // that may have been omitted from the render list via the black + // rect optimization. In order to ensure we don't cull background + // rendering in that black rect region, consider the node's visibility. + pixman_region32_t opaque; + pixman_region32_init(&opaque); + scene_node_opaque_region(entry->node, entry->x, entry->y, &opaque); + pixman_region32_intersect(&opaque, &opaque, &entry->node->visible); + + pixman_region32_translate(&opaque, -scene_output->x, -scene_output->y); + logical_to_buffer_coords(&opaque, &render_data, false); + pixman_region32_subtract(&background, &background, &opaque); + pixman_region32_fini(&opaque); + } + + if (floor(render_data.scale) != render_data.scale) { + wlr_region_expand(&background, &background, 1); + + // reintersect with the damage because we never want to render + // outside of the damage region + pixman_region32_intersect(&background, &background, &render_data.damage); + } + } + + wlr_render_pass_add_rect(render_pass, &(struct wlr_render_rect_options){ + .box = { .width = buffer->width, .height = buffer->height }, + .color = { .r = 0, .g = 0, .b = 0, .a = 1 }, + .clip = &background, + }); + pixman_region32_fini(&background); + + for (int i = list_len - 1; i >= 0; i--) { + struct render_list_entry *entry = &list_data[i]; + scene_entry_render(entry, &render_data); + + if (entry->node->type == WLR_SCENE_NODE_BUFFER) { + struct wlr_scene_buffer *buffer = wlr_scene_buffer_from_node(entry->node); + + // Direct scanout counts up to DMABUF_FEEDBACK_DEBOUNCE_FRAMES before sending new dmabuf + // feedback, and on composition we wait until it hits zero again. If we knew that an + // entry could never be a scanout candidate, we could send feedback to it + // unconditionally without debounce, but for now it is all or nothing + if (scene_output->dmabuf_feedback_debounce == 0 && buffer->primary_output == scene_output) { + struct wlr_linux_dmabuf_feedback_v1_init_options options = { + .main_renderer = output->renderer, + .scanout_primary_output = NULL, + }; + + scene_buffer_send_dmabuf_feedback(scene_output->scene, buffer, &options); + } + } + } + + if (debug_damage == WLR_SCENE_DEBUG_DAMAGE_HIGHLIGHT) { + struct highlight_region *damage; + wl_list_for_each(damage, &scene_output->damage_highlight_regions, link) { + struct timespec time_diff; + timespec_sub(&time_diff, &now, &damage->when); + int64_t time_diff_ms = timespec_to_msec(&time_diff); + float alpha = 1.0 - (double)time_diff_ms / HIGHLIGHT_DAMAGE_FADEOUT_TIME; + + wlr_render_pass_add_rect(render_pass, &(struct wlr_render_rect_options){ + .box = { .width = buffer->width, .height = buffer->height }, + .color = { .r = alpha * 0.5, .g = 0, .b = 0, .a = alpha * 0.5 }, + .clip = &damage->region, + }); + } + } + + wlr_output_add_software_cursors_to_render_pass(output, render_pass, &render_data.damage); + pixman_region32_fini(&render_data.damage); + + if (!wlr_render_pass_submit(render_pass)) { + wlr_buffer_unlock(buffer); + + // if we failed to render the buffer, it will have undefined contents + // Trash the damage ring + wlr_damage_ring_add_whole(&scene_output->damage_ring); + return false; + } + + wlr_output_state_set_buffer(state, buffer); + wlr_buffer_unlock(buffer); + + if (scene_output->in_timeline != NULL) { + wlr_output_state_set_wait_timeline(state, scene_output->in_timeline, + scene_output->in_point); + scene_output->out_point++; + wlr_output_state_set_signal_timeline(state, scene_output->out_timeline, + scene_output->out_point); + } + + if (!render_gamma_lut) { + scene_output_state_attempt_gamma(scene_output, state); + } + + return true; +} + +int64_t wlr_scene_timer_get_duration_ns(struct wlr_scene_timer *timer) { + int64_t pre_render = timer->pre_render_duration; + if (!timer->render_timer) { + return pre_render; + } + int64_t render = wlr_render_timer_get_duration_ns(timer->render_timer); + return render != -1 ? pre_render + render : -1; +} + +void wlr_scene_timer_finish(struct wlr_scene_timer *timer) { + if (timer->render_timer) { + wlr_render_timer_destroy(timer->render_timer); + } +} + +static void scene_node_send_frame_done(struct wlr_scene_node *node, + struct wlr_scene_output *scene_output, struct timespec *now) { + if (!node->enabled) { + return; + } + + if (node->type == WLR_SCENE_NODE_BUFFER) { + struct wlr_scene_buffer *scene_buffer = + wlr_scene_buffer_from_node(node); + struct wlr_scene_frame_done_event event = { + .output = scene_output, + .when = *now, + }; + wlr_scene_buffer_send_frame_done(scene_buffer, &event); + } else if (node->type == WLR_SCENE_NODE_TREE) { + struct wlr_scene_tree *scene_tree = wlr_scene_tree_from_node(node); + struct wlr_scene_node *child; + wl_list_for_each(child, &scene_tree->children, link) { + scene_node_send_frame_done(child, scene_output, now); + } + } +} + +void wlr_scene_output_send_frame_done(struct wlr_scene_output *scene_output, + struct timespec *now) { + scene_node_send_frame_done(&scene_output->scene->tree.node, + scene_output, now); +} + +static void scene_output_for_each_scene_buffer(const struct wlr_box *output_box, + struct wlr_scene_node *node, int lx, int ly, + wlr_scene_buffer_iterator_func_t user_iterator, void *user_data) { + if (!node->enabled) { + return; + } + + lx += node->x; + ly += node->y; + + if (node->type == WLR_SCENE_NODE_BUFFER) { + struct wlr_box node_box = { .x = lx, .y = ly }; + scene_node_get_size(node, &node_box.width, &node_box.height); + + struct wlr_box intersection; + if (wlr_box_intersection(&intersection, output_box, &node_box)) { + struct wlr_scene_buffer *scene_buffer = + wlr_scene_buffer_from_node(node); + user_iterator(scene_buffer, lx, ly, user_data); + } + } else if (node->type == WLR_SCENE_NODE_TREE) { + struct wlr_scene_tree *scene_tree = wlr_scene_tree_from_node(node); + struct wlr_scene_node *child; + wl_list_for_each(child, &scene_tree->children, link) { + scene_output_for_each_scene_buffer(output_box, child, lx, ly, + user_iterator, user_data); + } + } +} + +void wlr_scene_output_for_each_buffer(struct wlr_scene_output *scene_output, + wlr_scene_buffer_iterator_func_t iterator, void *user_data) { + struct wlr_box box = { .x = scene_output->x, .y = scene_output->y }; + wlr_output_effective_resolution(scene_output->output, + &box.width, &box.height); + scene_output_for_each_scene_buffer(&box, &scene_output->scene->tree.node, 0, 0, + iterator, user_data); +} diff --git a/3rdparty/wlroots/types/scene/xdg_shell.c b/3rdparty/wlroots/types/scene/xdg_shell.c new file mode 100644 index 0000000000..73d0acb79d --- /dev/null +++ b/3rdparty/wlroots/types/scene/xdg_shell.c @@ -0,0 +1,97 @@ +#include +#include +#include + +struct wlr_scene_xdg_surface { + struct wlr_scene_tree *tree; + struct wlr_xdg_surface *xdg_surface; + struct wlr_scene_tree *surface_tree; + + struct wl_listener tree_destroy; + struct wl_listener xdg_surface_destroy; + struct wl_listener xdg_surface_commit; +}; + +static void scene_xdg_surface_handle_tree_destroy(struct wl_listener *listener, + void *data) { + struct wlr_scene_xdg_surface *scene_xdg_surface = + wl_container_of(listener, scene_xdg_surface, tree_destroy); + // tree and surface_node will be cleaned up by scene_node_finish + wl_list_remove(&scene_xdg_surface->tree_destroy.link); + wl_list_remove(&scene_xdg_surface->xdg_surface_destroy.link); + wl_list_remove(&scene_xdg_surface->xdg_surface_commit.link); + free(scene_xdg_surface); +} + +static void scene_xdg_surface_handle_xdg_surface_destroy(struct wl_listener *listener, + void *data) { + struct wlr_scene_xdg_surface *scene_xdg_surface = + wl_container_of(listener, scene_xdg_surface, xdg_surface_destroy); + wlr_scene_node_destroy(&scene_xdg_surface->tree->node); +} + +static void scene_xdg_surface_update_position( + struct wlr_scene_xdg_surface *scene_xdg_surface) { + struct wlr_xdg_surface *xdg_surface = scene_xdg_surface->xdg_surface; + + wlr_scene_node_set_position(&scene_xdg_surface->surface_tree->node, + -xdg_surface->geometry.x, -xdg_surface->geometry.y); + + if (xdg_surface->role == WLR_XDG_SURFACE_ROLE_POPUP) { + struct wlr_xdg_popup *popup = xdg_surface->popup; + if (popup != NULL) { + wlr_scene_node_set_position(&scene_xdg_surface->tree->node, + popup->current.geometry.x, popup->current.geometry.y); + } + } +} + +static void scene_xdg_surface_handle_xdg_surface_commit(struct wl_listener *listener, + void *data) { + struct wlr_scene_xdg_surface *scene_xdg_surface = + wl_container_of(listener, scene_xdg_surface, xdg_surface_commit); + scene_xdg_surface_update_position(scene_xdg_surface); +} + +struct wlr_scene_tree *wlr_scene_xdg_surface_create( + struct wlr_scene_tree *parent, struct wlr_xdg_surface *xdg_surface) { + struct wlr_scene_xdg_surface *scene_xdg_surface = + calloc(1, sizeof(*scene_xdg_surface)); + if (scene_xdg_surface == NULL) { + return NULL; + } + + scene_xdg_surface->xdg_surface = xdg_surface; + + scene_xdg_surface->tree = wlr_scene_tree_create(parent); + if (scene_xdg_surface->tree == NULL) { + free(scene_xdg_surface); + return NULL; + } + + scene_xdg_surface->surface_tree = wlr_scene_subsurface_tree_create( + scene_xdg_surface->tree, xdg_surface->surface); + if (scene_xdg_surface->surface_tree == NULL) { + wlr_scene_node_destroy(&scene_xdg_surface->tree->node); + free(scene_xdg_surface); + return NULL; + } + + scene_xdg_surface->tree_destroy.notify = + scene_xdg_surface_handle_tree_destroy; + wl_signal_add(&scene_xdg_surface->tree->node.events.destroy, + &scene_xdg_surface->tree_destroy); + + scene_xdg_surface->xdg_surface_destroy.notify = + scene_xdg_surface_handle_xdg_surface_destroy; + wl_signal_add(&xdg_surface->events.destroy, &scene_xdg_surface->xdg_surface_destroy); + + scene_xdg_surface->xdg_surface_commit.notify = + scene_xdg_surface_handle_xdg_surface_commit; + wl_signal_add(&xdg_surface->surface->events.commit, + &scene_xdg_surface->xdg_surface_commit); + + scene_xdg_surface_update_position(scene_xdg_surface); + + return scene_xdg_surface->tree; +} diff --git a/3rdparty/wlroots/types/seat/wlr_seat.c b/3rdparty/wlroots/types/seat/wlr_seat.c new file mode 100644 index 0000000000..015a57b526 --- /dev/null +++ b/3rdparty/wlroots/types/seat/wlr_seat.c @@ -0,0 +1,524 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_seat.h" +#include "util/global.h" + +#define SEAT_VERSION 9 + +static void seat_handle_get_pointer(struct wl_client *client, + struct wl_resource *seat_resource, uint32_t id) { + uint32_t version = wl_resource_get_version(seat_resource); + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat_resource); + if (!seat_client) { + // The client still needs a resource, so here's a dummy: + seat_client_create_inert_pointer(client, version, id); + return; + } + if (!(seat_client->seat->accumulated_capabilities & WL_SEAT_CAPABILITY_POINTER)) { + wl_resource_post_error(seat_resource, WL_SEAT_ERROR_MISSING_CAPABILITY, + "wl_seat.get_pointer called when no pointer capability has existed"); + return; + } + + seat_client_create_pointer(seat_client, version, id); +} + +static void seat_handle_get_keyboard(struct wl_client *client, + struct wl_resource *seat_resource, uint32_t id) { + uint32_t version = wl_resource_get_version(seat_resource); + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat_resource); + if (!seat_client) { + seat_client_create_inert_keyboard(client, version, id); + return; + } + if (!(seat_client->seat->accumulated_capabilities & WL_SEAT_CAPABILITY_KEYBOARD)) { + wl_resource_post_error(seat_resource, WL_SEAT_ERROR_MISSING_CAPABILITY, + "wl_seat.get_keyboard called when no keyboard capability has existed"); + return; + } + + seat_client_create_keyboard(seat_client, version, id); +} + +static void seat_handle_get_touch(struct wl_client *client, + struct wl_resource *seat_resource, uint32_t id) { + uint32_t version = wl_resource_get_version(seat_resource); + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat_resource); + if (!seat_client) { + seat_client_create_inert_touch(client, version, id); + return; + } + if (!(seat_client->seat->accumulated_capabilities & WL_SEAT_CAPABILITY_TOUCH)) { + wl_resource_post_error(seat_resource, WL_SEAT_ERROR_MISSING_CAPABILITY, + "wl_seat.get_touch called when no touch capability has existed"); + return; + } + + seat_client_create_touch(seat_client, version, id); +} + +static void seat_client_destroy(struct wlr_seat_client *client) { + wl_signal_emit_mutable(&client->events.destroy, client); + + assert(wl_list_empty(&client->events.destroy.listener_list)); + + if (client == client->seat->pointer_state.focused_client) { + client->seat->pointer_state.focused_client = NULL; + } + if (client == client->seat->keyboard_state.focused_client) { + client->seat->keyboard_state.focused_client = NULL; + } + + if (client->seat->drag && client == client->seat->drag->seat_client) { + client->seat->drag->seat_client = NULL; + } + + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &client->pointers) { + seat_client_destroy_pointer(resource); + } + wl_resource_for_each_safe(resource, tmp, &client->keyboards) { + seat_client_destroy_keyboard(resource); + } + wl_resource_for_each_safe(resource, tmp, &client->touches) { + seat_client_destroy_touch(resource); + } + wl_resource_for_each_safe(resource, tmp, &client->data_devices) { + // Make the data device inert + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + wl_resource_set_user_data(resource, NULL); + } + wl_resource_for_each_safe(resource, tmp, &client->resources) { + // Make the seat resource inert + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + wl_resource_set_user_data(resource, NULL); + } + + wl_list_remove(&client->link); + free(client); +} + +static void seat_client_handle_resource_destroy( + struct wl_resource *seat_resource) { + struct wlr_seat_client *client = + wlr_seat_client_from_resource(seat_resource); + if (!client) { + return; + } + + wl_list_remove(wl_resource_get_link(seat_resource)); + if (!wl_list_empty(&client->resources)) { + return; + } + + seat_client_destroy(client); +} + +static void seat_handle_release(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wl_seat_interface seat_impl = { + .get_pointer = seat_handle_get_pointer, + .get_keyboard = seat_handle_get_keyboard, + .get_touch = seat_handle_get_touch, + .release = seat_handle_release, +}; + +static struct wlr_seat_client *seat_client_create(struct wlr_seat *wlr_seat, + struct wl_client *client, struct wl_resource *wl_resource) { + struct wlr_seat_client *seat_client = calloc(1, sizeof(*seat_client)); + if (!seat_client) { + return NULL; + } + + seat_client->client = client; + seat_client->seat = wlr_seat; + wl_list_init(&seat_client->resources); + wl_list_init(&seat_client->pointers); + wl_list_init(&seat_client->keyboards); + wl_list_init(&seat_client->touches); + wl_list_init(&seat_client->data_devices); + + wl_signal_init(&seat_client->events.destroy); + + wl_list_insert(&wlr_seat->clients, &seat_client->link); + + struct wlr_surface *pointer_focus = + wlr_seat->pointer_state.focused_surface; + if (pointer_focus != NULL && + wl_resource_get_client(pointer_focus->resource) == client) { + wlr_seat->pointer_state.focused_client = seat_client; + } + + struct wlr_surface *keyboard_focus = + wlr_seat->keyboard_state.focused_surface; + if (keyboard_focus != NULL && + wl_resource_get_client(keyboard_focus->resource) == client) { + wlr_seat->keyboard_state.focused_client = seat_client; + } + + return seat_client; +} + +static void seat_handle_bind(struct wl_client *client, void *_wlr_seat, + uint32_t version, uint32_t id) { + // `wlr_seat` can be NULL if the seat global is being destroyed + struct wlr_seat *wlr_seat = _wlr_seat; + + struct wl_resource *wl_resource = + wl_resource_create(client, &wl_seat_interface, version, id); + if (wl_resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(wl_resource, &seat_impl, NULL, + seat_client_handle_resource_destroy); + wl_list_init(wl_resource_get_link(wl_resource)); + if (wlr_seat == NULL) { + return; + } + + struct wlr_seat_client *seat_client = + wlr_seat_client_for_wl_client(wlr_seat, client); + if (!seat_client) { + seat_client = seat_client_create(wlr_seat, client, wl_resource); + } + + if (seat_client == NULL) { + wl_resource_destroy(wl_resource); + wl_client_post_no_memory(client); + return; + } + + wl_resource_set_user_data(wl_resource, seat_client); + wl_list_insert(&seat_client->resources, wl_resource_get_link(wl_resource)); + if (version >= WL_SEAT_NAME_SINCE_VERSION) { + wl_seat_send_name(wl_resource, wlr_seat->name); + } + wl_seat_send_capabilities(wl_resource, wlr_seat->capabilities); +} + +void wlr_seat_destroy(struct wlr_seat *seat) { + if (!seat) { + return; + } + + wlr_seat_pointer_clear_focus(seat); + wlr_seat_keyboard_clear_focus(seat); + + wlr_seat_set_keyboard(seat, NULL); + + struct wlr_touch_point *point; + wl_list_for_each(point, &seat->touch_state.touch_points, link) { + wlr_seat_touch_point_clear_focus(seat, 0, point->touch_id); + } + + wl_signal_emit_mutable(&seat->events.destroy, seat); + + assert(wl_list_empty(&seat->pointer_state.events.focus_change.listener_list)); + + assert(wl_list_empty(&seat->keyboard_state.events.focus_change.listener_list)); + + assert(wl_list_empty(&seat->events.request_start_drag.listener_list)); + assert(wl_list_empty(&seat->events.start_drag.listener_list)); + + assert(wl_list_empty(&seat->events.request_set_cursor.listener_list)); + + assert(wl_list_empty(&seat->events.request_set_selection.listener_list)); + assert(wl_list_empty(&seat->events.set_selection.listener_list)); + assert(wl_list_empty(&seat->events.request_set_primary_selection.listener_list)); + assert(wl_list_empty(&seat->events.set_primary_selection.listener_list)); + + assert(wl_list_empty(&seat->events.pointer_grab_begin.listener_list)); + assert(wl_list_empty(&seat->events.pointer_grab_end.listener_list)); + + assert(wl_list_empty(&seat->events.keyboard_grab_begin.listener_list)); + assert(wl_list_empty(&seat->events.keyboard_grab_end.listener_list)); + + assert(wl_list_empty(&seat->events.touch_grab_begin.listener_list)); + assert(wl_list_empty(&seat->events.touch_grab_end.listener_list)); + + assert(wl_list_empty(&seat->events.destroy.listener_list)); + + wl_list_remove(&seat->display_destroy.link); + + wlr_data_source_destroy(seat->selection_source); + wlr_primary_selection_source_destroy(seat->primary_selection_source); + + struct wlr_seat_client *client, *tmp; + wl_list_for_each_safe(client, tmp, &seat->clients, link) { + seat_client_destroy(client); + } + + wlr_global_destroy_safe(seat->global); + free(seat->pointer_state.default_grab); + free(seat->keyboard_state.default_grab); + free(seat->touch_state.default_grab); + free(seat->name); + free(seat); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_seat *seat = + wl_container_of(listener, seat, display_destroy); + wlr_seat_destroy(seat); +} + +struct wlr_seat *wlr_seat_create(struct wl_display *display, const char *name) { + struct wlr_seat *seat = calloc(1, sizeof(*seat)); + if (!seat) { + return NULL; + } + + // pointer state + seat->pointer_state.seat = seat; + wl_list_init(&seat->pointer_state.surface_destroy.link); + + struct wlr_seat_pointer_grab *pointer_grab = calloc(1, sizeof(*pointer_grab)); + if (!pointer_grab) { + free(seat); + return NULL; + } + pointer_grab->interface = &default_pointer_grab_impl; + pointer_grab->seat = seat; + seat->pointer_state.default_grab = pointer_grab; + seat->pointer_state.grab = pointer_grab; + + wl_signal_init(&seat->pointer_state.events.focus_change); + + // keyboard state + struct wlr_seat_keyboard_grab *keyboard_grab = calloc(1, sizeof(*keyboard_grab)); + if (!keyboard_grab) { + free(pointer_grab); + free(seat); + return NULL; + } + keyboard_grab->interface = &default_keyboard_grab_impl; + keyboard_grab->seat = seat; + seat->keyboard_state.default_grab = keyboard_grab; + seat->keyboard_state.grab = keyboard_grab; + + seat->keyboard_state.seat = seat; + wl_list_init(&seat->keyboard_state.surface_destroy.link); + + wl_signal_init(&seat->keyboard_state.events.focus_change); + + // touch state + struct wlr_seat_touch_grab *touch_grab = calloc(1, sizeof(*touch_grab)); + if (!touch_grab) { + free(pointer_grab); + free(keyboard_grab); + free(seat); + return NULL; + } + touch_grab->interface = &default_touch_grab_impl; + touch_grab->seat = seat; + seat->touch_state.default_grab = touch_grab; + seat->touch_state.grab = touch_grab; + + seat->touch_state.seat = seat; + wl_list_init(&seat->touch_state.touch_points); + + seat->global = wl_global_create(display, &wl_seat_interface, + SEAT_VERSION, seat, seat_handle_bind); + if (seat->global == NULL) { + free(touch_grab); + free(pointer_grab); + free(keyboard_grab); + free(seat); + return NULL; + } + seat->display = display; + seat->name = strdup(name); + wl_list_init(&seat->clients); + wl_list_init(&seat->selection_offers); + wl_list_init(&seat->drag_offers); + + wl_signal_init(&seat->events.request_start_drag); + wl_signal_init(&seat->events.start_drag); + + wl_signal_init(&seat->events.request_set_cursor); + + wl_signal_init(&seat->events.request_set_selection); + wl_signal_init(&seat->events.set_selection); + wl_signal_init(&seat->events.request_set_primary_selection); + wl_signal_init(&seat->events.set_primary_selection); + + wl_signal_init(&seat->events.pointer_grab_begin); + wl_signal_init(&seat->events.pointer_grab_end); + + wl_signal_init(&seat->events.keyboard_grab_begin); + wl_signal_init(&seat->events.keyboard_grab_end); + + wl_signal_init(&seat->events.touch_grab_begin); + wl_signal_init(&seat->events.touch_grab_end); + + wl_signal_init(&seat->events.destroy); + + seat->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &seat->display_destroy); + + return seat; +} + +struct wlr_seat_client *wlr_seat_client_for_wl_client(struct wlr_seat *wlr_seat, + struct wl_client *wl_client) { + struct wlr_seat_client *seat_client; + wl_list_for_each(seat_client, &wlr_seat->clients, link) { + if (seat_client->client == wl_client) { + return seat_client; + } + } + return NULL; +} + +void wlr_seat_set_capabilities(struct wlr_seat *wlr_seat, + uint32_t capabilities) { + // if the capabilities haven't changed (i.e a redundant mouse was removed), + // we don't actually have to do anything + if (capabilities == wlr_seat->capabilities) { + return; + } + wlr_seat->capabilities = capabilities; + wlr_seat->accumulated_capabilities |= capabilities; + + struct wlr_seat_client *client; + wl_list_for_each(client, &wlr_seat->clients, link) { + // Make resources inert if necessary + if ((capabilities & WL_SEAT_CAPABILITY_POINTER) == 0) { + struct wlr_seat_client *focused_client = + wlr_seat->pointer_state.focused_client; + struct wlr_surface *focused_surface = + wlr_seat->pointer_state.focused_surface; + + if (focused_client != NULL && focused_surface != NULL) { + seat_client_send_pointer_leave_raw(focused_client, focused_surface); + } + + // Note: we don't set focused client/surface to NULL since we need + // them to send the enter event if the pointer is recreated + + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &client->pointers) { + seat_client_destroy_pointer(resource); + } + } + if ((capabilities & WL_SEAT_CAPABILITY_KEYBOARD) == 0) { + struct wlr_seat_client *focused_client = + wlr_seat->keyboard_state.focused_client; + struct wlr_surface *focused_surface = + wlr_seat->keyboard_state.focused_surface; + + if (focused_client != NULL && focused_surface != NULL) { + seat_client_send_keyboard_leave_raw(focused_client, + focused_surface); + } + + // Note: we don't set focused client/surface to NULL since we need + // them to send the enter event if the keyboard is recreated + + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &client->keyboards) { + seat_client_destroy_keyboard(resource); + } + } + if ((capabilities & WL_SEAT_CAPABILITY_TOUCH) == 0) { + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &client->touches) { + seat_client_destroy_touch(resource); + } + } + + struct wl_resource *resource; + wl_resource_for_each(resource, &client->resources) { + wl_seat_send_capabilities(resource, capabilities); + } + } +} + +void wlr_seat_set_name(struct wlr_seat *wlr_seat, const char *name) { + free(wlr_seat->name); + wlr_seat->name = strdup(name); + struct wlr_seat_client *client; + wl_list_for_each(client, &wlr_seat->clients, link) { + struct wl_resource *resource; + wl_resource_for_each(resource, &client->resources) { + wl_seat_send_name(resource, name); + } + } +} + +struct wlr_seat_client *wlr_seat_client_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_seat_interface, + &seat_impl)); + return wl_resource_get_user_data(resource); +} + +uint32_t wlr_seat_client_next_serial(struct wlr_seat_client *client) { + struct wl_display *display = wl_client_get_display(client->client); + uint32_t serial = wl_display_next_serial(display); + if (serial == 0) { + serial = wl_display_next_serial(display); + } + + struct wlr_serial_ringset *set = &client->serials; + if (set->count == 0) { + set->data[0].min_incl = serial; + set->data[0].max_incl = serial; + set->count = 1; + set->end = 0; + } else if (set->data[set->end].max_incl + 1 != serial) { + if (set->count < WLR_SERIAL_RINGSET_SIZE) { + set->count++; + } + set->end = (set->end + 1) % WLR_SERIAL_RINGSET_SIZE; + set->data[set->end].min_incl = serial; + set->data[set->end].max_incl = serial; + } else { + set->data[set->end].max_incl = serial; + } + + return serial; +} + +bool wlr_seat_client_validate_event_serial(struct wlr_seat_client *client, uint32_t serial) { + uint32_t cur = wl_display_get_serial(wl_client_get_display(client->client)); + struct wlr_serial_ringset *set = &client->serials; + uint32_t rev_dist = cur - serial; + + if (rev_dist >= UINT32_MAX / 2) { + // serial is closer to being 'newer' instead of 'older' than + // the current serial, so it's either invalid or incredibly old + return false; + } + + for (int i = 0; i < set->count; i++) { + int j = (set->end - i + WLR_SERIAL_RINGSET_SIZE) % WLR_SERIAL_RINGSET_SIZE; + if (rev_dist < cur - set->data[j].max_incl) { + return false; + } + if (rev_dist <= cur - set->data[j].min_incl) { + return true; + } + } + + // Iff the set is full, then `rev_dist` is large enough that serial + // could already have been recycled out of the set. + return set->count == WLR_SERIAL_RINGSET_SIZE; +} diff --git a/3rdparty/wlroots/types/seat/wlr_seat_keyboard.c b/3rdparty/wlroots/types/seat/wlr_seat_keyboard.c new file mode 100644 index 0000000000..3227035e2b --- /dev/null +++ b/3rdparty/wlroots/types/seat/wlr_seat_keyboard.c @@ -0,0 +1,479 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_data_device.h" +#include "types/wlr_seat.h" + +static void default_keyboard_enter(struct wlr_seat_keyboard_grab *grab, + struct wlr_surface *surface, const uint32_t keycodes[], size_t num_keycodes, + const struct wlr_keyboard_modifiers *modifiers) { + wlr_seat_keyboard_enter(grab->seat, surface, keycodes, num_keycodes, modifiers); +} + +static void default_keyboard_clear_focus(struct wlr_seat_keyboard_grab *grab) { + wlr_seat_keyboard_clear_focus(grab->seat); +} + +static void default_keyboard_key(struct wlr_seat_keyboard_grab *grab, + uint32_t time, uint32_t key, uint32_t state) { + wlr_seat_keyboard_send_key(grab->seat, time, key, state); +} + +static void default_keyboard_modifiers(struct wlr_seat_keyboard_grab *grab, + const struct wlr_keyboard_modifiers *modifiers) { + wlr_seat_keyboard_send_modifiers(grab->seat, modifiers); +} + +static void default_keyboard_cancel(struct wlr_seat_keyboard_grab *grab) { + // cannot be cancelled +} + +const struct wlr_keyboard_grab_interface default_keyboard_grab_impl = { + .enter = default_keyboard_enter, + .clear_focus = default_keyboard_clear_focus, + .key = default_keyboard_key, + .modifiers = default_keyboard_modifiers, + .cancel = default_keyboard_cancel, +}; + + +static void keyboard_release(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wl_keyboard_interface keyboard_impl = { + .release = keyboard_release, +}; + +static struct wlr_seat_client *seat_client_from_keyboard_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_keyboard_interface, + &keyboard_impl)); + return wl_resource_get_user_data(resource); +} + +static void keyboard_handle_resource_destroy(struct wl_resource *resource) { + seat_client_destroy_keyboard(resource); +} + + +void wlr_seat_keyboard_send_key(struct wlr_seat *wlr_seat, uint32_t time, + uint32_t key, uint32_t state) { + struct wlr_seat_client *client = wlr_seat->keyboard_state.focused_client; + if (!client) { + return; + } + + uint32_t serial = wlr_seat_client_next_serial(client); + struct wl_resource *resource; + wl_resource_for_each(resource, &client->keyboards) { + if (seat_client_from_keyboard_resource(resource) == NULL) { + continue; + } + + wl_keyboard_send_key(resource, serial, time, key, state); + } +} + +static void seat_client_send_keymap(struct wlr_seat_client *client, + struct wlr_keyboard *keyboard); + +static void handle_keyboard_keymap(struct wl_listener *listener, void *data) { + struct wlr_seat_keyboard_state *state = + wl_container_of(listener, state, keyboard_keymap); + struct wlr_seat_client *client; + wl_list_for_each(client, &state->seat->clients, link) { + seat_client_send_keymap(client, state->keyboard); + } +} + +static void seat_client_send_repeat_info(struct wlr_seat_client *client, + struct wlr_keyboard *keyboard); + +static void handle_keyboard_repeat_info(struct wl_listener *listener, + void *data) { + struct wlr_seat_keyboard_state *state = + wl_container_of(listener, state, keyboard_repeat_info); + struct wlr_seat_client *client; + wl_list_for_each(client, &state->seat->clients, link) { + seat_client_send_repeat_info(client, state->keyboard); + } +} + +static void handle_keyboard_destroy(struct wl_listener *listener, void *data) { + struct wlr_seat_keyboard_state *state = + wl_container_of(listener, state, keyboard_destroy); + wlr_seat_set_keyboard(state->seat, NULL); +} + +void wlr_seat_set_keyboard(struct wlr_seat *seat, + struct wlr_keyboard *keyboard) { + // TODO call this on device key event before the event reaches the + // compositor and set a pending keyboard and then send the new keyboard + // state on the next keyboard notify event. + if (seat->keyboard_state.keyboard == keyboard) { + return; + } + + // send the keymap only if it has changed + bool needs_keymap_update = + !seat->keyboard_state.keyboard || !keyboard || + seat->keyboard_state.keyboard->keymap != keyboard->keymap; + + if (seat->keyboard_state.keyboard) { + wl_list_remove(&seat->keyboard_state.keyboard_destroy.link); + wl_list_remove(&seat->keyboard_state.keyboard_keymap.link); + wl_list_remove(&seat->keyboard_state.keyboard_repeat_info.link); + seat->keyboard_state.keyboard = NULL; + } + + if (keyboard) { + seat->keyboard_state.keyboard = keyboard; + + wl_signal_add(&keyboard->base.events.destroy, + &seat->keyboard_state.keyboard_destroy); + seat->keyboard_state.keyboard_destroy.notify = handle_keyboard_destroy; + wl_signal_add(&keyboard->events.keymap, + &seat->keyboard_state.keyboard_keymap); + seat->keyboard_state.keyboard_keymap.notify = handle_keyboard_keymap; + wl_signal_add(&keyboard->events.repeat_info, + &seat->keyboard_state.keyboard_repeat_info); + seat->keyboard_state.keyboard_repeat_info.notify = + handle_keyboard_repeat_info; + + struct wlr_seat_client *client; + wl_list_for_each(client, &seat->clients, link) { + if (needs_keymap_update) { + seat_client_send_keymap(client, keyboard); + } + seat_client_send_repeat_info(client, keyboard); + } + + wlr_seat_keyboard_send_modifiers(seat, &keyboard->modifiers); + } else { + seat->keyboard_state.keyboard = NULL; + } +} + +struct wlr_keyboard *wlr_seat_get_keyboard(struct wlr_seat *seat) { + return seat->keyboard_state.keyboard; +} + +void wlr_seat_keyboard_start_grab(struct wlr_seat *wlr_seat, + struct wlr_seat_keyboard_grab *grab) { + grab->seat = wlr_seat; + wlr_seat->keyboard_state.grab = grab; + + wl_signal_emit_mutable(&wlr_seat->events.keyboard_grab_begin, grab); +} + +void wlr_seat_keyboard_end_grab(struct wlr_seat *wlr_seat) { + struct wlr_seat_keyboard_grab *grab = wlr_seat->keyboard_state.grab; + + if (grab != wlr_seat->keyboard_state.default_grab) { + wlr_seat->keyboard_state.grab = wlr_seat->keyboard_state.default_grab; + wl_signal_emit_mutable(&wlr_seat->events.keyboard_grab_end, grab); + if (grab->interface->cancel) { + grab->interface->cancel(grab); + } + } +} + +static void seat_keyboard_handle_surface_destroy(struct wl_listener *listener, + void *data) { + struct wlr_seat_keyboard_state *state = wl_container_of( + listener, state, surface_destroy); + wl_list_remove(&state->surface_destroy.link); + wl_list_init(&state->surface_destroy.link); + wlr_seat_keyboard_clear_focus(state->seat); +} + +void wlr_seat_keyboard_send_modifiers(struct wlr_seat *seat, + const struct wlr_keyboard_modifiers *modifiers) { + struct wlr_seat_client *client = seat->keyboard_state.focused_client; + if (client == NULL) { + return; + } + + uint32_t serial = wlr_seat_client_next_serial(client); + struct wl_resource *resource; + wl_resource_for_each(resource, &client->keyboards) { + if (seat_client_from_keyboard_resource(resource) == NULL) { + continue; + } + + if (modifiers == NULL) { + wl_keyboard_send_modifiers(resource, serial, 0, 0, 0, 0); + } else { + wl_keyboard_send_modifiers(resource, serial, + modifiers->depressed, modifiers->latched, + modifiers->locked, modifiers->group); + } + } +} + +void seat_client_send_keyboard_leave_raw(struct wlr_seat_client *seat_client, + struct wlr_surface *surface) { + uint32_t serial = wlr_seat_client_next_serial(seat_client); + struct wl_resource *resource; + wl_resource_for_each(resource, &seat_client->keyboards) { + if (seat_client_from_keyboard_resource(resource) == NULL) { + continue; + } + wl_keyboard_send_leave(resource, serial, surface->resource); + } +} + +void wlr_seat_keyboard_enter(struct wlr_seat *seat, + struct wlr_surface *surface, const uint32_t keycodes[], size_t num_keycodes, + const struct wlr_keyboard_modifiers *modifiers) { + if (seat->keyboard_state.focused_surface == surface) { + // this surface already got an enter notify + return; + } + + struct wlr_seat_client *client = NULL; + + if (surface) { + struct wl_client *wl_client = wl_resource_get_client(surface->resource); + client = wlr_seat_client_for_wl_client(seat, wl_client); + } + + struct wlr_seat_client *focused_client = + seat->keyboard_state.focused_client; + struct wlr_surface *focused_surface = + seat->keyboard_state.focused_surface; + + // leave the previously entered surface + if (focused_client != NULL && focused_surface != NULL) { + seat_client_send_keyboard_leave_raw(focused_client, focused_surface); + } + + // enter the current surface + if (client != NULL) { + struct wl_array keys = { + .data = (void *)keycodes, + .size = num_keycodes * sizeof(keycodes[0]), + }; + uint32_t serial = wlr_seat_client_next_serial(client); + struct wl_resource *resource; + wl_resource_for_each(resource, &client->keyboards) { + if (seat_client_from_keyboard_resource(resource) == NULL) { + continue; + } + wl_keyboard_send_enter(resource, serial, surface->resource, &keys); + } + } + + // reinitialize the focus destroy events + wl_list_remove(&seat->keyboard_state.surface_destroy.link); + wl_list_init(&seat->keyboard_state.surface_destroy.link); + if (surface) { + wl_signal_add(&surface->events.destroy, + &seat->keyboard_state.surface_destroy); + seat->keyboard_state.surface_destroy.notify = + seat_keyboard_handle_surface_destroy; + } + + seat->keyboard_state.focused_client = client; + seat->keyboard_state.focused_surface = surface; + + if (client != NULL) { + // tell new client about any modifier change last, + // as it targets seat->keyboard_state.focused_client + wlr_seat_keyboard_send_modifiers(seat, modifiers); + + seat_client_send_selection(client); + } + + struct wlr_seat_keyboard_focus_change_event event = { + .seat = seat, + .old_surface = focused_surface, + .new_surface = surface, + }; + wl_signal_emit_mutable(&seat->keyboard_state.events.focus_change, &event); +} + +void wlr_seat_keyboard_notify_enter(struct wlr_seat *seat, + struct wlr_surface *surface, const uint32_t keycodes[], size_t num_keycodes, + const struct wlr_keyboard_modifiers *modifiers) { + // NULL surfaces are prohibited in the grab-compatible API. Use + // wlr_seat_keyboard_notify_clear_focus() instead. + assert(surface); + struct wlr_seat_keyboard_grab *grab = seat->keyboard_state.grab; + grab->interface->enter(grab, surface, keycodes, num_keycodes, modifiers); +} + +void wlr_seat_keyboard_clear_focus(struct wlr_seat *seat) { + wlr_seat_keyboard_enter(seat, NULL, NULL, 0, NULL); +} + +void wlr_seat_keyboard_notify_clear_focus(struct wlr_seat *seat) { + struct wlr_seat_keyboard_grab *grab = seat->keyboard_state.grab; + grab->interface->clear_focus(grab); +} + +bool wlr_seat_keyboard_has_grab(struct wlr_seat *seat) { + return seat->keyboard_state.grab->interface != &default_keyboard_grab_impl; +} + +void wlr_seat_keyboard_notify_modifiers(struct wlr_seat *seat, + const struct wlr_keyboard_modifiers *modifiers) { + struct wlr_seat_keyboard_grab *grab = seat->keyboard_state.grab; + grab->interface->modifiers(grab, modifiers); +} + +void wlr_seat_keyboard_notify_key(struct wlr_seat *seat, uint32_t time, + uint32_t key, uint32_t state) { + struct wlr_seat_keyboard_grab *grab = seat->keyboard_state.grab; + grab->interface->key(grab, time, key, state); +} + +static void seat_client_send_keymap(struct wlr_seat_client *client, + struct wlr_keyboard *keyboard) { + if (!keyboard) { + return; + } + + enum wl_keyboard_keymap_format format; + int fd, devnull = -1; + uint32_t size; + if (keyboard->keymap != NULL) { + format = WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1; + fd = keyboard->keymap_fd; + size = keyboard->keymap_size; + } else { + format = WL_KEYBOARD_KEYMAP_FORMAT_NO_KEYMAP; + devnull = open("/dev/null", O_RDONLY | O_CLOEXEC); + if (devnull < 0) { + wlr_log_errno(WLR_ERROR, "Failed to open /dev/null"); + return; + } + fd = devnull; + size = 0; + } + + // TODO: We should probably lift all of the keys set by the other + // keyboard + struct wl_resource *resource; + wl_resource_for_each(resource, &client->keyboards) { + if (seat_client_from_keyboard_resource(resource) == NULL) { + continue; + } + + wl_keyboard_send_keymap(resource, format, fd, size); + } + + if (devnull >= 0) { + close(devnull); + } +} + +static void seat_client_send_repeat_info(struct wlr_seat_client *client, + struct wlr_keyboard *keyboard) { + if (!keyboard) { + return; + } + + struct wl_resource *resource; + wl_resource_for_each(resource, &client->keyboards) { + if (seat_client_from_keyboard_resource(resource) == NULL) { + continue; + } + + if (wl_resource_get_version(resource) >= + WL_KEYBOARD_REPEAT_INFO_SINCE_VERSION) { + wl_keyboard_send_repeat_info(resource, + keyboard->repeat_info.rate, keyboard->repeat_info.delay); + } + } +} + +void seat_client_create_keyboard(struct wlr_seat_client *seat_client, + uint32_t version, uint32_t id) { + struct wl_resource *resource = wl_resource_create(seat_client->client, + &wl_keyboard_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(seat_client->client); + return; + } + wl_resource_set_implementation(resource, &keyboard_impl, seat_client, + keyboard_handle_resource_destroy); + wl_list_insert(&seat_client->keyboards, wl_resource_get_link(resource)); + + if ((seat_client->seat->capabilities & WL_SEAT_CAPABILITY_KEYBOARD) == 0) { + wl_resource_set_user_data(resource, NULL); + return; + } + + struct wlr_keyboard *keyboard = seat_client->seat->keyboard_state.keyboard; + if (keyboard == NULL) { + return; + } + seat_client_send_keymap(seat_client, keyboard); + seat_client_send_repeat_info(seat_client, keyboard); + + struct wlr_seat_client *focused_client = + seat_client->seat->keyboard_state.focused_client; + struct wlr_surface *focused_surface = + seat_client->seat->keyboard_state.focused_surface; + + // Send an enter event if there is a focused client/surface stored + if (focused_client == seat_client && focused_surface != NULL) { + uint32_t *keycodes = keyboard->keycodes; + size_t num_keycodes = keyboard->num_keycodes; + + struct wl_array keys; + wl_array_init(&keys); + for (size_t i = 0; i < num_keycodes; ++i) { + uint32_t *p = wl_array_add(&keys, sizeof(uint32_t)); + if (!p) { + wlr_log(WLR_ERROR, "Cannot allocate memory, skipping keycode: %" PRIu32 "\n", + keycodes[i]); + continue; + } + *p = keycodes[i]; + } + + uint32_t serial = wlr_seat_client_next_serial(focused_client); + struct wl_resource *resource; + wl_resource_for_each(resource, &focused_client->keyboards) { + if (wl_resource_get_id(resource) == id) { + if (seat_client_from_keyboard_resource(resource) == NULL) { + continue; + } + wl_keyboard_send_enter(resource, serial, + focused_surface->resource, &keys); + } + } + + wl_array_release(&keys); + + wlr_seat_keyboard_send_modifiers(seat_client->seat, + &keyboard->modifiers); + } +} + +void seat_client_create_inert_keyboard(struct wl_client *client, + uint32_t version, uint32_t id) { + struct wl_resource *resource = + wl_resource_create(client, &wl_keyboard_interface, version, id); + if (!resource) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &keyboard_impl, NULL, NULL); +} + +void seat_client_destroy_keyboard(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + wl_resource_set_user_data(resource, NULL); +} diff --git a/3rdparty/wlroots/types/seat/wlr_seat_pointer.c b/3rdparty/wlroots/types/seat/wlr_seat_pointer.c new file mode 100644 index 0000000000..d578d0a57e --- /dev/null +++ b/3rdparty/wlroots/types/seat/wlr_seat_pointer.c @@ -0,0 +1,627 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_seat.h" + +static void default_pointer_enter(struct wlr_seat_pointer_grab *grab, + struct wlr_surface *surface, double sx, double sy) { + wlr_seat_pointer_enter(grab->seat, surface, sx, sy); +} + +static void default_pointer_clear_focus(struct wlr_seat_pointer_grab *grab) { + wlr_seat_pointer_clear_focus(grab->seat); +} + +static void default_pointer_motion(struct wlr_seat_pointer_grab *grab, + uint32_t time, double sx, double sy) { + wlr_seat_pointer_send_motion(grab->seat, time, sx, sy); +} + +static uint32_t default_pointer_button(struct wlr_seat_pointer_grab *grab, + uint32_t time, uint32_t button, enum wl_pointer_button_state state) { + return wlr_seat_pointer_send_button(grab->seat, time, button, state); +} + +static void default_pointer_axis(struct wlr_seat_pointer_grab *grab, + uint32_t time, enum wl_pointer_axis orientation, double value, + int32_t value_discrete, enum wl_pointer_axis_source source, + enum wl_pointer_axis_relative_direction relative_direction) { + wlr_seat_pointer_send_axis(grab->seat, time, orientation, value, + value_discrete, source, relative_direction); +} + +static void default_pointer_frame(struct wlr_seat_pointer_grab *grab) { + wlr_seat_pointer_send_frame(grab->seat); +} + +static void default_pointer_cancel(struct wlr_seat_pointer_grab *grab) { + // cannot be cancelled +} + +const struct wlr_pointer_grab_interface default_pointer_grab_impl = { + .enter = default_pointer_enter, + .clear_focus = default_pointer_clear_focus, + .motion = default_pointer_motion, + .button = default_pointer_button, + .axis = default_pointer_axis, + .frame = default_pointer_frame, + .cancel = default_pointer_cancel, +}; + + +static void pointer_send_frame(struct wl_resource *resource) { + if (wl_resource_get_version(resource) >= + WL_POINTER_FRAME_SINCE_VERSION) { + wl_pointer_send_frame(resource); + } +} + +static const struct wl_pointer_interface pointer_impl; + +struct wlr_seat_client *wlr_seat_client_from_pointer_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_pointer_interface, + &pointer_impl)); + return wl_resource_get_user_data(resource); +} + +static void pointer_cursor_surface_handle_commit(struct wlr_surface *surface) { + pixman_region32_clear(&surface->input_region); + if (wlr_surface_has_buffer(surface)) { + wlr_surface_map(surface); + } +} + +static const struct wlr_surface_role pointer_cursor_surface_role = { + .name = "wl_pointer-cursor", + .no_object = true, + .commit = pointer_cursor_surface_handle_commit, +}; + +static void pointer_set_cursor(struct wl_client *client, + struct wl_resource *pointer_resource, uint32_t serial, + struct wl_resource *surface_resource, + int32_t hotspot_x, int32_t hotspot_y) { + struct wlr_seat_client *seat_client = + wlr_seat_client_from_pointer_resource(pointer_resource); + if (seat_client == NULL) { + return; + } + + struct wlr_surface *surface = NULL; + if (surface_resource != NULL) { + surface = wlr_surface_from_resource(surface_resource); + if (!wlr_surface_set_role(surface, &pointer_cursor_surface_role, + surface_resource, WL_POINTER_ERROR_ROLE)) { + return; + } + + pointer_cursor_surface_handle_commit(surface); + } + + struct wlr_seat_pointer_request_set_cursor_event event = { + .seat_client = seat_client, + .surface = surface, + .serial = serial, + .hotspot_x = hotspot_x, + .hotspot_y = hotspot_y, + }; + wl_signal_emit_mutable(&seat_client->seat->events.request_set_cursor, &event); +} + +static void pointer_release(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wl_pointer_interface pointer_impl = { + .set_cursor = pointer_set_cursor, + .release = pointer_release, +}; + +static void pointer_handle_resource_destroy(struct wl_resource *resource) { + seat_client_destroy_pointer(resource); +} + + +bool wlr_seat_pointer_surface_has_focus(struct wlr_seat *wlr_seat, + struct wlr_surface *surface) { + return surface == wlr_seat->pointer_state.focused_surface; +} + +static void seat_pointer_handle_surface_destroy(struct wl_listener *listener, + void *data) { + struct wlr_seat_pointer_state *state = + wl_container_of(listener, state, surface_destroy); + wl_list_remove(&state->surface_destroy.link); + wl_list_init(&state->surface_destroy.link); + wlr_seat_pointer_clear_focus(state->seat); +} + +void seat_client_send_pointer_leave_raw(struct wlr_seat_client *seat_client, + struct wlr_surface *surface) { + uint32_t serial = wlr_seat_client_next_serial(seat_client); + struct wl_resource *resource; + wl_resource_for_each(resource, &seat_client->pointers) { + if (wlr_seat_client_from_pointer_resource(resource) == NULL) { + continue; + } + + wl_pointer_send_leave(resource, serial, surface->resource); + pointer_send_frame(resource); + } +} + +void wlr_seat_pointer_enter(struct wlr_seat *wlr_seat, + struct wlr_surface *surface, double sx, double sy) { + if (wlr_seat->pointer_state.focused_surface == surface) { + // this surface already got an enter notify + return; + } + + struct wlr_seat_client *client = NULL; + if (surface) { + struct wl_client *wl_client = wl_resource_get_client(surface->resource); + client = wlr_seat_client_for_wl_client(wlr_seat, wl_client); + } + + struct wlr_seat_client *focused_client = + wlr_seat->pointer_state.focused_client; + struct wlr_surface *focused_surface = + wlr_seat->pointer_state.focused_surface; + + // leave the previously entered surface + if (focused_client != NULL && focused_surface != NULL) { + seat_client_send_pointer_leave_raw(focused_client, focused_surface); + } + + // enter the current surface + if (client != NULL && surface != NULL) { + uint32_t serial = wlr_seat_client_next_serial(client); + struct wl_resource *resource; + wl_resource_for_each(resource, &client->pointers) { + if (wlr_seat_client_from_pointer_resource(resource) == NULL) { + continue; + } + + wl_pointer_send_enter(resource, serial, surface->resource, + wl_fixed_from_double(sx), wl_fixed_from_double(sy)); + pointer_send_frame(resource); + } + } + + // reinitialize the focus destroy events + wl_list_remove(&wlr_seat->pointer_state.surface_destroy.link); + wl_list_init(&wlr_seat->pointer_state.surface_destroy.link); + if (surface != NULL) { + wl_signal_add(&surface->events.destroy, + &wlr_seat->pointer_state.surface_destroy); + wlr_seat->pointer_state.surface_destroy.notify = + seat_pointer_handle_surface_destroy; + } + + wlr_seat->pointer_state.focused_client = client; + wlr_seat->pointer_state.focused_surface = surface; + if (surface != NULL) { + wlr_seat_pointer_warp(wlr_seat, sx, sy); + } else { + wlr_seat_pointer_warp(wlr_seat, NAN, NAN); + } + + struct wlr_seat_pointer_focus_change_event event = { + .seat = wlr_seat, + .new_surface = surface, + .old_surface = focused_surface, + .sx = sx, + .sy = sy, + }; + wl_signal_emit_mutable(&wlr_seat->pointer_state.events.focus_change, &event); +} + +void wlr_seat_pointer_clear_focus(struct wlr_seat *wlr_seat) { + wlr_seat_pointer_enter(wlr_seat, NULL, 0, 0); +} + +void wlr_seat_pointer_warp(struct wlr_seat *wlr_seat, double sx, double sy) { + wlr_seat->pointer_state.sx = sx; + wlr_seat->pointer_state.sy = sy; +} + +void wlr_seat_pointer_send_motion(struct wlr_seat *wlr_seat, uint32_t time, + double sx, double sy) { + struct wlr_seat_client *client = wlr_seat->pointer_state.focused_client; + if (client == NULL) { + return; + } + + // Ensure we don't send duplicate motion events. Instead of comparing with an + // epsilon, chop off some precision by converting to a `wl_fixed_t` first, + // since that is what a client receives. + wl_fixed_t sx_fixed = wl_fixed_from_double(sx); + wl_fixed_t sy_fixed = wl_fixed_from_double(sy); + if (wl_fixed_from_double(wlr_seat->pointer_state.sx) != sx_fixed || + wl_fixed_from_double(wlr_seat->pointer_state.sy) != sy_fixed) { + struct wl_resource *resource; + wl_resource_for_each(resource, &client->pointers) { + if (wlr_seat_client_from_pointer_resource(resource) == NULL) { + continue; + } + + wl_pointer_send_motion(resource, time, sx_fixed, sy_fixed); + } + } + + wlr_seat_pointer_warp(wlr_seat, sx, sy); +} + +uint32_t wlr_seat_pointer_send_button(struct wlr_seat *wlr_seat, uint32_t time, + uint32_t button, enum wl_pointer_button_state state) { + struct wlr_seat_client *client = wlr_seat->pointer_state.focused_client; + if (client == NULL) { + return 0; + } + + uint32_t serial = wlr_seat_client_next_serial(client); + struct wl_resource *resource; + wl_resource_for_each(resource, &client->pointers) { + if (wlr_seat_client_from_pointer_resource(resource) == NULL) { + continue; + } + + wl_pointer_send_button(resource, serial, time, button, state); + } + return serial; +} + +static bool should_reset_value120_accumulators(int32_t current, int32_t last) { + if (last == 0) { + return true; + } + + return (current < 0 && last > 0) || (current > 0 && last < 0); +} + +static void update_value120_accumulators(struct wlr_seat_client *client, + enum wl_pointer_axis orientation, + double value, int32_t value_discrete, + double *low_res_value, int32_t *low_res_value_discrete) { + if (value_discrete == 0) { + // Continuous scrolling has no effect on accumulators + return; + } + + int32_t *acc_discrete = &client->value120.acc_discrete[orientation]; + int32_t *last_discrete = &client->value120.last_discrete[orientation]; + double *acc_axis = &client->value120.acc_axis[orientation]; + + if (should_reset_value120_accumulators(value_discrete, *last_discrete)) { + *acc_discrete = 0; + *acc_axis = 0; + } + *acc_discrete += value_discrete; + *last_discrete = value_discrete; + *acc_axis += value; + + // Compute low resolution event values for older clients and reset + // the accumulators if needed + *low_res_value_discrete = *acc_discrete / WLR_POINTER_AXIS_DISCRETE_STEP; + if (*low_res_value_discrete == 0) { + *low_res_value = 0; + } else { + *acc_discrete -= *low_res_value_discrete * WLR_POINTER_AXIS_DISCRETE_STEP; + *low_res_value = *acc_axis; + *acc_axis = 0; + } +} + +void wlr_seat_pointer_send_axis(struct wlr_seat *wlr_seat, uint32_t time, + enum wl_pointer_axis orientation, double value, + int32_t value_discrete, enum wl_pointer_axis_source source, + enum wl_pointer_axis_relative_direction relative_direction) { + struct wlr_seat_client *client = wlr_seat->pointer_state.focused_client; + if (client == NULL) { + return; + } + + bool send_source = false; + if (wlr_seat->pointer_state.sent_axis_source) { + assert(wlr_seat->pointer_state.cached_axis_source == source); + } else { + wlr_seat->pointer_state.sent_axis_source = true; + wlr_seat->pointer_state.cached_axis_source = source; + send_source = true; + } + + double low_res_value = 0.0; + int32_t low_res_value_discrete = 0; + update_value120_accumulators(client, orientation, value, value_discrete, + &low_res_value, &low_res_value_discrete); + + struct wl_resource *resource; + wl_resource_for_each(resource, &client->pointers) { + if (wlr_seat_client_from_pointer_resource(resource) == NULL) { + continue; + } + + uint32_t version = wl_resource_get_version(resource); + + if (version < WL_POINTER_AXIS_VALUE120_SINCE_VERSION && + value_discrete != 0 && low_res_value_discrete == 0) { + // The client doesn't support high resolution discrete scrolling + // and we haven't accumulated enough wheel clicks for a single + // low resolution event. Don't send anything. + continue; + } + + if (send_source && version >= WL_POINTER_AXIS_SOURCE_SINCE_VERSION) { + wl_pointer_send_axis_source(resource, source); + } + if (value) { + if (version >= WL_POINTER_AXIS_RELATIVE_DIRECTION_SINCE_VERSION) { + wl_pointer_send_axis_relative_direction(resource, + orientation, relative_direction); + } + if (value_discrete) { + if (version >= WL_POINTER_AXIS_VALUE120_SINCE_VERSION) { + // High resolution discrete scrolling + wl_pointer_send_axis_value120(resource, orientation, + value_discrete); + wl_pointer_send_axis(resource, time, orientation, + wl_fixed_from_double(value)); + } else { + // Low resolution discrete scrolling + if (version >= WL_POINTER_AXIS_DISCRETE_SINCE_VERSION) { + wl_pointer_send_axis_discrete(resource, orientation, + low_res_value_discrete); + } + wl_pointer_send_axis(resource, time, orientation, + wl_fixed_from_double(low_res_value)); + } + } else { + // Continuous scrolling + wl_pointer_send_axis(resource, time, orientation, + wl_fixed_from_double(value)); + } + } else if (version >= WL_POINTER_AXIS_STOP_SINCE_VERSION) { + wl_pointer_send_axis_stop(resource, time, orientation); + } + } +} + +void wlr_seat_pointer_send_frame(struct wlr_seat *wlr_seat) { + struct wlr_seat_client *client = wlr_seat->pointer_state.focused_client; + if (client == NULL) { + return; + } + + wlr_seat->pointer_state.sent_axis_source = false; + + struct wl_resource *resource; + wl_resource_for_each(resource, &client->pointers) { + if (wlr_seat_client_from_pointer_resource(resource) == NULL) { + continue; + } + + pointer_send_frame(resource); + } +} + +void wlr_seat_pointer_start_grab(struct wlr_seat *wlr_seat, + struct wlr_seat_pointer_grab *grab) { + assert(wlr_seat); + grab->seat = wlr_seat; + wlr_seat->pointer_state.grab = grab; + + // Preserve drag grab priority + if (wlr_seat->drag && grab != &wlr_seat->drag->pointer_grab) { + return; + } + + wl_signal_emit_mutable(&wlr_seat->events.pointer_grab_begin, grab); +} + +void wlr_seat_pointer_end_grab(struct wlr_seat *wlr_seat) { + struct wlr_seat_pointer_grab *grab = wlr_seat->pointer_state.grab; + if (grab != wlr_seat->pointer_state.default_grab) { + wlr_seat->pointer_state.grab = wlr_seat->pointer_state.default_grab; + wl_signal_emit_mutable(&wlr_seat->events.pointer_grab_end, grab); + if (grab->interface->cancel) { + grab->interface->cancel(grab); + } + } +} + +// Switching focus means the new surface doesn't know about the currently +// pressed buttons. This function allows to reset them. +static void reset_buttons(struct wlr_seat *wlr_seat) { + wlr_seat->pointer_state.button_count = 0; +} + +void wlr_seat_pointer_notify_enter(struct wlr_seat *wlr_seat, + struct wlr_surface *surface, double sx, double sy) { + // NULL surfaces are prohibited in the grab-compatible API. Use + // wlr_seat_pointer_notify_clear_focus() instead. + assert(surface); + struct wlr_seat_pointer_grab *grab = wlr_seat->pointer_state.grab; + struct wlr_surface *focused_surface = wlr_seat->pointer_state.focused_surface; + + grab->interface->enter(grab, surface, sx, sy); + + if (focused_surface != wlr_seat->pointer_state.focused_surface) { + reset_buttons(wlr_seat); + } +} + +void wlr_seat_pointer_notify_clear_focus(struct wlr_seat *wlr_seat) { + struct wlr_seat_pointer_grab *grab = wlr_seat->pointer_state.grab; + struct wlr_surface *focused_surface = wlr_seat->pointer_state.focused_surface; + + grab->interface->clear_focus(grab); + + if (focused_surface != wlr_seat->pointer_state.focused_surface) { + reset_buttons(wlr_seat); + } +} + +void wlr_seat_pointer_notify_motion(struct wlr_seat *wlr_seat, uint32_t time, + double sx, double sy) { + struct wlr_seat_pointer_grab *grab = wlr_seat->pointer_state.grab; + grab->interface->motion(grab, time, sx, sy); +} + +uint32_t wlr_seat_pointer_notify_button(struct wlr_seat *wlr_seat, + uint32_t time, uint32_t button, enum wl_pointer_button_state state) { + struct wlr_seat_pointer_state* pointer_state = &wlr_seat->pointer_state; + + if (state == WL_POINTER_BUTTON_STATE_PRESSED) { + if (pointer_state->button_count == 0) { + pointer_state->grab_button = button; + pointer_state->grab_time = time; + } + for (size_t i = 0; i < pointer_state->button_count; i++) { + struct wlr_seat_pointer_button *pointer_button = &pointer_state->buttons[i]; + if (pointer_button->button == button) { + ++pointer_button->n_pressed; + return 0; + } + } + if (pointer_state->button_count == WLR_POINTER_BUTTONS_CAP) { + return 0; + } + pointer_state->buttons[pointer_state->button_count++] = (struct wlr_seat_pointer_button){ + .button = button, + .n_pressed = 1, + }; + } else { + bool found = false; + for (size_t i = 0; i < pointer_state->button_count; i++) { + struct wlr_seat_pointer_button *pointer_button = &pointer_state->buttons[i]; + if (pointer_button->button == button) { + if (--pointer_button->n_pressed > 0) { + return 0; + } + *pointer_button = pointer_state->buttons[--pointer_state->button_count]; + found = true; + break; + } + } + if (!found) { + return 0; + } + } + + struct wlr_seat_pointer_grab *grab = pointer_state->grab; + uint32_t serial = grab->interface->button(grab, time, button, state); + + if (serial && pointer_state->button_count == 1 && + state == WL_POINTER_BUTTON_STATE_PRESSED) { + pointer_state->grab_serial = serial; + } + + return serial; +} + +void wlr_seat_pointer_notify_axis(struct wlr_seat *wlr_seat, uint32_t time, + enum wl_pointer_axis orientation, double value, + int32_t value_discrete, enum wl_pointer_axis_source source, + enum wl_pointer_axis_relative_direction relative_direction) { + struct wlr_seat_pointer_grab *grab = wlr_seat->pointer_state.grab; + grab->interface->axis(grab, time, orientation, value, value_discrete, + source, relative_direction); +} + +void wlr_seat_pointer_notify_frame(struct wlr_seat *wlr_seat) { + struct wlr_seat_pointer_grab *grab = wlr_seat->pointer_state.grab; + if (grab->interface->frame) { + grab->interface->frame(grab); + } +} + +bool wlr_seat_pointer_has_grab(struct wlr_seat *seat) { + return seat->pointer_state.grab->interface != &default_pointer_grab_impl; +} + +void seat_client_create_pointer(struct wlr_seat_client *seat_client, + uint32_t version, uint32_t id) { + struct wl_resource *resource = wl_resource_create(seat_client->client, + &wl_pointer_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(seat_client->client); + return; + } + wl_resource_set_implementation(resource, &pointer_impl, seat_client, + &pointer_handle_resource_destroy); + wl_list_insert(&seat_client->pointers, wl_resource_get_link(resource)); + + if ((seat_client->seat->capabilities & WL_SEAT_CAPABILITY_POINTER) == 0) { + wl_resource_set_user_data(resource, NULL); + return; + } + + struct wlr_seat_client *focused_client = + seat_client->seat->pointer_state.focused_client; + struct wlr_surface *focused_surface = + seat_client->seat->pointer_state.focused_surface; + + // Send an enter event if there is a focused client/surface stored + if (focused_client == seat_client && focused_surface != NULL) { + double sx = seat_client->seat->pointer_state.sx; + double sy = seat_client->seat->pointer_state.sy; + + uint32_t serial = wlr_seat_client_next_serial(focused_client); + struct wl_resource *resource; + wl_resource_for_each(resource, &focused_client->pointers) { + if (wl_resource_get_id(resource) == id) { + if (wlr_seat_client_from_pointer_resource(resource) == NULL) { + continue; + } + + wl_pointer_send_enter(resource, serial, focused_surface->resource, + wl_fixed_from_double(sx), wl_fixed_from_double(sy)); + pointer_send_frame(resource); + } + } + } +} + +void seat_client_create_inert_pointer(struct wl_client *client, + uint32_t version, uint32_t id) { + struct wl_resource *resource = + wl_resource_create(client, &wl_pointer_interface, version, id); + if (!resource) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &pointer_impl, NULL, NULL); +} + +void seat_client_destroy_pointer(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + wl_resource_set_user_data(resource, NULL); +} + +bool wlr_seat_validate_pointer_grab_serial(struct wlr_seat *seat, + struct wlr_surface *origin, uint32_t serial) { + if (seat->pointer_state.button_count != 1 || + seat->pointer_state.grab_serial != serial) { + wlr_log(WLR_DEBUG, "Pointer grab serial validation failed: " + "button_count=%zu grab_serial=%"PRIu32" (got %"PRIu32")", + seat->pointer_state.button_count, + seat->pointer_state.grab_serial, serial); + return false; + } + + if (origin != NULL && seat->pointer_state.focused_surface != origin) { + wlr_log(WLR_DEBUG, "Pointer grab serial validation failed: " + "invalid origin surface"); + return false; + } + + return true; +} diff --git a/3rdparty/wlroots/types/seat/wlr_seat_touch.c b/3rdparty/wlroots/types/seat/wlr_seat_touch.c new file mode 100644 index 0000000000..217c19e70d --- /dev/null +++ b/3rdparty/wlroots/types/seat/wlr_seat_touch.c @@ -0,0 +1,506 @@ +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_seat.h" + +static uint32_t default_touch_down(struct wlr_seat_touch_grab *grab, + uint32_t time, struct wlr_touch_point *point) { + return wlr_seat_touch_send_down(grab->seat, point->surface, time, + point->touch_id, point->sx, point->sy); +} + +static uint32_t default_touch_up(struct wlr_seat_touch_grab *grab, uint32_t time, + struct wlr_touch_point *point) { + return wlr_seat_touch_send_up(grab->seat, time, point->touch_id); +} + +static void default_touch_motion(struct wlr_seat_touch_grab *grab, + uint32_t time, struct wlr_touch_point *point) { + if (!point->focus_surface || point->focus_surface == point->surface) { + wlr_seat_touch_send_motion(grab->seat, time, point->touch_id, point->sx, + point->sy); + } +} + +static void default_touch_enter(struct wlr_seat_touch_grab *grab, + uint32_t time, struct wlr_touch_point *point) { + // not handled by default +} + +static void default_touch_frame(struct wlr_seat_touch_grab *grab) { + wlr_seat_touch_send_frame(grab->seat); +} + +static void default_touch_cancel(struct wlr_seat_touch_grab *grab) { + // cannot be cancelled +} + +static void default_touch_wl_cancel(struct wlr_seat_touch_grab *grab, + struct wlr_seat_client *seat_client) { + wlr_seat_touch_send_cancel(grab->seat, seat_client); +} + +static void default_touch_clear_focus(struct wlr_seat_touch_grab *grab, uint32_t time_msec, + struct wlr_touch_point *point) { + wlr_seat_touch_point_clear_focus(grab->seat, time_msec, point->touch_id); +} + + +const struct wlr_touch_grab_interface default_touch_grab_impl = { + .down = default_touch_down, + .up = default_touch_up, + .motion = default_touch_motion, + .enter = default_touch_enter, + .frame = default_touch_frame, + .cancel = default_touch_cancel, + .wl_cancel = default_touch_wl_cancel, + .clear_focus = default_touch_clear_focus, +}; + + +static void touch_release(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wl_touch_interface touch_impl = { + .release = touch_release, +}; + +static void touch_handle_resource_destroy(struct wl_resource *resource) { + seat_client_destroy_touch(resource); +} + +static struct wlr_seat_client *seat_client_from_touch_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_touch_interface, + &touch_impl)); + return wl_resource_get_user_data(resource); +} + + +void wlr_seat_touch_start_grab(struct wlr_seat *wlr_seat, + struct wlr_seat_touch_grab *grab) { + grab->seat = wlr_seat; + wlr_seat->touch_state.grab = grab; + + wl_signal_emit_mutable(&wlr_seat->events.touch_grab_begin, grab); +} + +void wlr_seat_touch_end_grab(struct wlr_seat *wlr_seat) { + struct wlr_seat_touch_grab *grab = wlr_seat->touch_state.grab; + + if (grab != wlr_seat->touch_state.default_grab) { + wlr_seat->touch_state.grab = wlr_seat->touch_state.default_grab; + wl_signal_emit_mutable(&wlr_seat->events.touch_grab_end, grab); + if (grab->interface->cancel) { + grab->interface->cancel(grab); + } + } +} + +static void touch_point_clear_focus(struct wlr_touch_point *point) { + if (point->focus_surface) { + wl_list_remove(&point->focus_surface_destroy.link); + point->focus_client = NULL; + point->focus_surface = NULL; + } +} + +static void touch_point_destroy(struct wlr_touch_point *point) { + wl_signal_emit_mutable(&point->events.destroy, point); + + assert(wl_list_empty(&point->events.destroy.listener_list)); + + touch_point_clear_focus(point); + wl_list_remove(&point->surface_destroy.link); + wl_list_remove(&point->client_destroy.link); + wl_list_remove(&point->link); + free(point); +} + +static void touch_point_handle_surface_destroy(struct wl_listener *listener, + void *data) { + struct wlr_touch_point *point = + wl_container_of(listener, point, surface_destroy); + // Touch point itself is destroyed on up event + point->surface = NULL; + wl_list_remove(&point->surface_destroy.link); + wl_list_init(&point->surface_destroy.link); +} + +static void touch_point_handle_client_destroy(struct wl_listener *listener, + void *data) { + struct wlr_touch_point *point = + wl_container_of(listener, point, client_destroy); + touch_point_destroy(point); +} + +static struct wlr_touch_point *touch_point_create( + struct wlr_seat *seat, int32_t touch_id, + struct wlr_surface *surface, double sx, double sy) { + struct wl_client *wl_client = wl_resource_get_client(surface->resource); + struct wlr_seat_client *client = + wlr_seat_client_for_wl_client(seat, wl_client); + + if (client == NULL || wl_list_empty(&client->touches)) { + // touch points are not valid without a connected client with touch + return NULL; + } + + struct wlr_touch_point *point = calloc(1, sizeof(*point)); + if (!point) { + return NULL; + } + + point->touch_id = touch_id; + point->surface = surface; + point->client = client; + + point->sx = sx; + point->sy = sy; + + wl_signal_init(&point->events.destroy); + + wl_signal_add(&surface->events.destroy, &point->surface_destroy); + point->surface_destroy.notify = touch_point_handle_surface_destroy; + wl_signal_add(&client->events.destroy, &point->client_destroy); + point->client_destroy.notify = touch_point_handle_client_destroy; + wl_list_insert(&seat->touch_state.touch_points, &point->link); + + return point; +} + +struct wlr_touch_point *wlr_seat_touch_get_point( + struct wlr_seat *seat, int32_t touch_id) { + struct wlr_touch_point *point = NULL; + wl_list_for_each(point, &seat->touch_state.touch_points, link) { + if (point->touch_id == touch_id) { + return point; + } + } + + return NULL; +} + +uint32_t wlr_seat_touch_notify_down(struct wlr_seat *seat, + struct wlr_surface *surface, uint32_t time, int32_t touch_id, double sx, + double sy) { + struct wlr_seat_touch_grab *grab = seat->touch_state.grab; + struct wlr_touch_point *point = + touch_point_create(seat, touch_id, surface, sx, sy); + if (!point) { + wlr_log(WLR_ERROR, "could not create touch point"); + return 0; + } + + uint32_t serial = grab->interface->down(grab, time, point); + + if (!serial) { + touch_point_destroy(point); + return 0; + } + + if (serial && wlr_seat_touch_num_points(seat) == 1) { + seat->touch_state.grab_serial = serial; + seat->touch_state.grab_id = touch_id; + } + + return serial; +} + +uint32_t wlr_seat_touch_notify_up(struct wlr_seat *seat, uint32_t time, + int32_t touch_id) { + struct wlr_seat_touch_grab *grab = seat->touch_state.grab; + struct wlr_touch_point *point = wlr_seat_touch_get_point(seat, touch_id); + if (!point) { + return 0; + } + + uint32_t serial = grab->interface->up(grab, time, point); + + touch_point_destroy(point); + return serial; +} + +void wlr_seat_touch_notify_motion(struct wlr_seat *seat, uint32_t time, + int32_t touch_id, double sx, double sy) { + struct wlr_seat_touch_grab *grab = seat->touch_state.grab; + struct wlr_touch_point *point = wlr_seat_touch_get_point(seat, touch_id); + if (!point) { + return; + } + + point->sx = sx; + point->sy = sy; + + grab->interface->motion(grab, time, point); +} + +void wlr_seat_touch_notify_frame(struct wlr_seat *seat) { + struct wlr_seat_touch_grab *grab = seat->touch_state.grab; + if (grab->interface->frame) { + grab->interface->frame(grab); + } +} + +void wlr_seat_touch_notify_cancel(struct wlr_seat *seat, + struct wlr_seat_client *seat_client) { + struct wlr_seat_touch_grab *grab = seat->touch_state.grab; + if (grab->interface->wl_cancel) { + grab->interface->wl_cancel(grab, seat_client); + } + + struct wlr_touch_point *point, *tmp; + wl_list_for_each_safe(point, tmp, &seat->touch_state.touch_points, link) { + if (point->client == seat_client) { + touch_point_destroy(point); + } + } +} + +void wlr_seat_touch_notify_clear_focus(struct wlr_seat *seat, + uint32_t time, int32_t touch_id) { + struct wlr_seat_touch_grab *grab = seat->touch_state.grab; + struct wlr_touch_point *point = wlr_seat_touch_get_point(seat, touch_id); + if (!point) { + return; + } + + if (grab->interface->clear_focus) { + grab->interface->clear_focus(grab, time, point); + } +} + +static void handle_point_focus_destroy(struct wl_listener *listener, + void *data) { + struct wlr_touch_point *point = + wl_container_of(listener, point, focus_surface_destroy); + touch_point_clear_focus(point); +} + +static void touch_point_set_focus(struct wlr_touch_point *point, + struct wlr_surface *surface, double sx, double sy) { + if (point->focus_surface == surface) { + return; + } + + touch_point_clear_focus(point); + + if (surface && surface->resource) { + struct wlr_seat_client *client = + wlr_seat_client_for_wl_client(point->client->seat, + wl_resource_get_client(surface->resource)); + + if (client && !wl_list_empty(&client->touches)) { + wl_signal_add(&surface->events.destroy, &point->focus_surface_destroy); + point->focus_surface_destroy.notify = handle_point_focus_destroy; + point->focus_surface = surface; + point->focus_client = client; + point->sx = sx; + point->sy = sy; + } + } +} + +void wlr_seat_touch_point_focus(struct wlr_seat *seat, + struct wlr_surface *surface, uint32_t time, int32_t touch_id, double sx, + double sy) { + assert(surface); + struct wlr_touch_point *point = wlr_seat_touch_get_point(seat, touch_id); + if (!point) { + wlr_log(WLR_ERROR, "got touch point focus for unknown touch point"); + return; + } + struct wlr_surface *focus = point->focus_surface; + touch_point_set_focus(point, surface, sx, sy); + + if (focus != point->focus_surface) { + struct wlr_seat_touch_grab *grab = seat->touch_state.grab; + grab->interface->enter(grab, time, point); + } +} + +void wlr_seat_touch_point_clear_focus(struct wlr_seat *seat, uint32_t time, + int32_t touch_id) { + struct wlr_touch_point *point = wlr_seat_touch_get_point(seat, touch_id); + if (!point) { + wlr_log(WLR_ERROR, "got touch point focus for unknown touch point"); + return; + } + + touch_point_clear_focus(point); +} + +uint32_t wlr_seat_touch_send_down(struct wlr_seat *seat, + struct wlr_surface *surface, uint32_t time, int32_t touch_id, double sx, + double sy) { + struct wlr_touch_point *point = wlr_seat_touch_get_point(seat, touch_id); + if (!point) { + wlr_log(WLR_ERROR, "got touch down for unknown touch point"); + return 0; + } + + uint32_t serial = wlr_seat_client_next_serial(point->client); + struct wl_resource *resource; + wl_resource_for_each(resource, &point->client->touches) { + if (seat_client_from_touch_resource(resource) == NULL) { + continue; + } + wl_touch_send_down(resource, serial, time, surface->resource, + touch_id, wl_fixed_from_double(sx), wl_fixed_from_double(sy)); + } + + point->client->needs_touch_frame = true; + + return serial; +} + +uint32_t wlr_seat_touch_send_up(struct wlr_seat *seat, uint32_t time, int32_t touch_id) { + struct wlr_touch_point *point = wlr_seat_touch_get_point(seat, touch_id); + if (!point) { + wlr_log(WLR_ERROR, "got touch up for unknown touch point"); + return 0; + } + + uint32_t serial = wlr_seat_client_next_serial(point->client); + struct wl_resource *resource; + wl_resource_for_each(resource, &point->client->touches) { + if (seat_client_from_touch_resource(resource) == NULL) { + continue; + } + wl_touch_send_up(resource, serial, time, touch_id); + } + + point->client->needs_touch_frame = true; + return serial; +} + +void wlr_seat_touch_send_motion(struct wlr_seat *seat, uint32_t time, int32_t touch_id, + double sx, double sy) { + struct wlr_touch_point *point = wlr_seat_touch_get_point(seat, touch_id); + if (!point) { + wlr_log(WLR_ERROR, "got touch motion for unknown touch point"); + return; + } + + struct wl_resource *resource; + wl_resource_for_each(resource, &point->client->touches) { + if (seat_client_from_touch_resource(resource) == NULL) { + continue; + } + wl_touch_send_motion(resource, time, touch_id, wl_fixed_from_double(sx), + wl_fixed_from_double(sy)); + } + + point->client->needs_touch_frame = true; +} + +void wlr_seat_touch_send_frame(struct wlr_seat *seat) { + struct wlr_seat_client *seat_client; + wl_list_for_each(seat_client, &seat->clients, link) { + if (!seat_client->needs_touch_frame) { + continue; + } + + struct wl_resource *resource; + wl_resource_for_each(resource, &seat_client->touches) { + wl_touch_send_frame(resource); + } + seat_client->needs_touch_frame = false; + } +} + +void wlr_seat_touch_send_cancel(struct wlr_seat *seat, + struct wlr_seat_client *seat_client) { + struct wl_resource *resource; + wl_resource_for_each(resource, &seat_client->touches) { + if (seat_client_from_touch_resource(resource) == NULL) { + continue; + } + wl_touch_send_cancel(resource); + } +} + +int wlr_seat_touch_num_points(struct wlr_seat *seat) { + return wl_list_length(&seat->touch_state.touch_points); +} + +bool wlr_seat_touch_has_grab(struct wlr_seat *seat) { + return seat->touch_state.grab->interface != &default_touch_grab_impl; +} + + +void seat_client_create_touch(struct wlr_seat_client *seat_client, + uint32_t version, uint32_t id) { + struct wl_resource *resource = wl_resource_create(seat_client->client, + &wl_touch_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(seat_client->client); + return; + } + wl_resource_set_implementation(resource, &touch_impl, seat_client, + &touch_handle_resource_destroy); + wl_list_insert(&seat_client->touches, wl_resource_get_link(resource)); + + if ((seat_client->seat->capabilities & WL_SEAT_CAPABILITY_TOUCH) == 0) { + wl_resource_set_user_data(resource, NULL); + } +} + +void seat_client_create_inert_touch(struct wl_client *client, uint32_t version, + uint32_t id) { + struct wl_resource *resource = + wl_resource_create(client, &wl_touch_interface, version, id); + if (!resource) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &touch_impl, NULL, NULL); +} + +void seat_client_destroy_touch(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + wl_resource_set_user_data(resource, NULL); +} + +bool wlr_seat_validate_touch_grab_serial(struct wlr_seat *seat, + struct wlr_surface *origin, uint32_t serial, + struct wlr_touch_point **point_ptr) { + if (wlr_seat_touch_num_points(seat) != 1 || + seat->touch_state.grab_serial != serial) { + wlr_log(WLR_DEBUG, "Touch grab serial validation failed: " + "num_points=%d grab_serial=%"PRIu32" (got %"PRIu32")", + wlr_seat_touch_num_points(seat), + seat->touch_state.grab_serial, serial); + return false; + } + + struct wlr_touch_point *point; + wl_list_for_each(point, &seat->touch_state.touch_points, link) { + if (origin == NULL || point->surface == origin) { + if (point_ptr != NULL) { + *point_ptr = point; + } + return true; + } + } + + wlr_log(WLR_DEBUG, "Touch grab serial validation failed: " + "invalid origin surface"); + return false; +} + +bool wlr_surface_accepts_touch(struct wlr_surface *surface, struct wlr_seat *wlr_seat) { + struct wl_client *client = wl_resource_get_client(surface->resource); + struct wlr_seat_client *seat_client = wlr_seat_client_for_wl_client(wlr_seat, client); + if (!seat_client) { + return false; + } + return !wl_list_empty(&seat_client->touches); +} diff --git a/3rdparty/wlroots/types/tablet_v2/wlr_tablet_v2.c b/3rdparty/wlroots/types/tablet_v2/wlr_tablet_v2.c new file mode 100644 index 0000000000..71a3e73a22 --- /dev/null +++ b/3rdparty/wlroots/types/tablet_v2/wlr_tablet_v2.c @@ -0,0 +1,330 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "tablet-v2-protocol.h" +#include "util/global.h" + +#define TABLET_MANAGER_VERSION 1 + +struct wlr_tablet_manager_client_v2 { + struct wl_list link; + struct wl_client *client; + struct wl_resource *resource; + struct wlr_tablet_manager_v2 *manager; + + struct wl_list tablet_seats; // wlr_tablet_seat_client_v2.link +}; + +static void tablet_seat_destroy(struct wlr_tablet_seat_v2 *seat) { + struct wlr_tablet_seat_client_v2 *client, *client_tmp; + wl_list_for_each_safe(client, client_tmp, &seat->clients, seat_link) { + tablet_seat_client_v2_destroy(client->resource); + } + + wl_list_remove(&seat->link); + wl_list_remove(&seat->seat_destroy.link); + free(seat); +} + +static void handle_wlr_seat_destroy(struct wl_listener *listener, void *data) { + struct wlr_tablet_seat_v2 *seat = + wl_container_of(listener, seat, seat_destroy); + tablet_seat_destroy(seat); +} + +static struct wlr_tablet_seat_v2 *create_tablet_seat( + struct wlr_tablet_manager_v2 *manager, + struct wlr_seat *wlr_seat) { + struct wlr_tablet_seat_v2 *tablet_seat = calloc(1, sizeof(*tablet_seat)); + if (!tablet_seat) { + return NULL; + } + + tablet_seat->manager = manager; + tablet_seat->wlr_seat = wlr_seat; + + wl_list_init(&tablet_seat->clients); + + wl_list_init(&tablet_seat->tablets); + wl_list_init(&tablet_seat->tools); + wl_list_init(&tablet_seat->pads); + + tablet_seat->seat_destroy.notify = handle_wlr_seat_destroy; + wl_signal_add(&wlr_seat->events.destroy, &tablet_seat->seat_destroy); + + wl_list_insert(&manager->seats, &tablet_seat->link); + return tablet_seat; +} + +struct wlr_tablet_seat_v2 *get_or_create_tablet_seat( + struct wlr_tablet_manager_v2 *manager, + struct wlr_seat *wlr_seat) { + struct wlr_tablet_seat_v2 *pos; + wl_list_for_each(pos, &manager->seats, link) { + if (pos->wlr_seat == wlr_seat) { + return pos; + } + } + + return create_tablet_seat(manager, wlr_seat); +} + +static void tablet_seat_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwp_tablet_seat_v2_interface seat_impl = { + .destroy = tablet_seat_handle_destroy, +}; + +struct wlr_tablet_seat_client_v2 *tablet_seat_client_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwp_tablet_seat_v2_interface, + &seat_impl)); + return wl_resource_get_user_data(resource); +} + +void tablet_seat_client_v2_destroy(struct wl_resource *resource) { + struct wlr_tablet_seat_client_v2 *seat = tablet_seat_client_from_resource(resource); + if (!seat) { + return; + } + + struct wlr_tablet_client_v2 *tablet; + struct wlr_tablet_client_v2 *tmp_tablet; + wl_list_for_each_safe(tablet, tmp_tablet, &seat->tablets, seat_link) { + destroy_tablet_v2(tablet->resource); + } + + struct wlr_tablet_pad_client_v2 *pad; + struct wlr_tablet_pad_client_v2 *tmp_pad; + wl_list_for_each_safe(pad, tmp_pad, &seat->pads, seat_link) { + destroy_tablet_pad_v2(pad->resource); + } + + struct wlr_tablet_tool_client_v2 *tool; + struct wlr_tablet_tool_client_v2 *tmp_tool; + wl_list_for_each_safe(tool, tmp_tool, &seat->tools, seat_link) { + destroy_tablet_tool_v2(tool->resource); + } + + wl_list_remove(&seat->seat_link); + wl_list_remove(&seat->client_link); + wl_list_remove(&seat->seat_client_destroy.link); + + free(seat); + wl_resource_set_user_data(resource, NULL); +} + +static void handle_seat_client_destroy(struct wl_listener *listener, void *data) { + struct wlr_tablet_seat_client_v2 *seat = + wl_container_of(listener, seat, seat_client_destroy); + tablet_seat_client_v2_destroy(seat->resource); +} + +static void tablet_manager_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static struct wlr_tablet_manager_client_v2 *tablet_manager_client_from_resource( + struct wl_resource *resource); + +static void get_tablet_seat(struct wl_client *wl_client, struct wl_resource *resource, + uint32_t id, struct wl_resource *seat_resource) { + struct wlr_tablet_manager_client_v2 *manager = + tablet_manager_client_from_resource(resource); + if (!manager) { + /* Inert manager, just set up the resource for later + * destruction, without allocations or advertising things + */ + wl_resource_set_implementation(seat_resource, &seat_impl, NULL, + tablet_seat_client_v2_destroy); + return; + } + struct wl_resource *tablet_seat_resource = wl_resource_create(wl_client, + &zwp_tablet_seat_v2_interface, TABLET_MANAGER_VERSION, id); + if (tablet_seat_resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + wl_resource_set_implementation(tablet_seat_resource, &seat_impl, NULL, + tablet_seat_client_v2_destroy); + + struct wlr_seat_client *seat = wlr_seat_client_from_resource(seat_resource); + if (seat == NULL) { + return; + } + struct wlr_tablet_seat_v2 *tablet_seat = + get_or_create_tablet_seat(manager->manager, seat->seat); + + if (!tablet_seat) { // This can only happen when we ran out of memory + wl_client_post_no_memory(wl_client); + return; + } + + struct wlr_tablet_seat_client_v2 *seat_client = calloc(1, sizeof(*seat_client)); + if (seat_client == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + + seat_client->resource = tablet_seat_resource; + seat_client->seat_client = seat; + seat_client->client = manager; + seat_client->wl_client = wl_client; + wl_list_init(&seat_client->tools); + wl_list_init(&seat_client->tablets); + wl_list_init(&seat_client->pads); + wl_resource_set_user_data(tablet_seat_resource, seat_client); + + seat_client->seat_client_destroy.notify = handle_seat_client_destroy; + wl_signal_add(&seat->events.destroy, &seat_client->seat_client_destroy); + + wl_list_insert(&manager->tablet_seats, &seat_client->client_link); + wl_list_insert(&tablet_seat->clients, &seat_client->seat_link); + + // We need to emit the devices already on the seat + struct wlr_tablet_v2_tablet *tablet_pos; + wl_list_for_each(tablet_pos, &tablet_seat->tablets, link) { + add_tablet_client(seat_client, tablet_pos); + } + + struct wlr_tablet_v2_tablet_pad *pad_pos; + wl_list_for_each(pad_pos, &tablet_seat->pads, link) { + add_tablet_pad_client(seat_client, pad_pos); + } + + struct wlr_tablet_v2_tablet_tool *tool_pos; + wl_list_for_each(tool_pos, &tablet_seat->tools, link) { + add_tablet_tool_client(seat_client, tool_pos); + } +} + +static const struct zwp_tablet_manager_v2_interface manager_impl = { + .get_tablet_seat = get_tablet_seat, + .destroy = tablet_manager_destroy, +}; + +static struct wlr_tablet_manager_client_v2 *tablet_manager_client_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwp_tablet_manager_v2_interface, + &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void wlr_tablet_manager_v2_destroy(struct wl_resource *resource) { + struct wlr_tablet_manager_client_v2 *client = + tablet_manager_client_from_resource(resource); + if (!client) { + return; + } + + struct wlr_tablet_seat_client_v2 *pos; + struct wlr_tablet_seat_client_v2 *tmp; + wl_list_for_each_safe(pos, tmp, &client->tablet_seats, client_link) { + tablet_seat_client_v2_destroy(pos->resource); + } + + wl_list_remove(&client->link); + + free(client); + wl_resource_set_user_data(resource, NULL); +} + +static void tablet_v2_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_tablet_manager_v2 *manager = data; + + struct wlr_tablet_manager_client_v2 *client = calloc(1, sizeof(*client)); + if (client == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + + wl_list_init(&client->tablet_seats); + + client->resource = + wl_resource_create(wl_client, &zwp_tablet_manager_v2_interface, version, id); + if (client->resource == NULL) { + free(client); + wl_client_post_no_memory(wl_client); + return; + } + client->client = wl_client; + client->manager = manager; + + wl_resource_set_implementation(client->resource, &manager_impl, client, + wlr_tablet_manager_v2_destroy); + wl_list_init(&client->link); + if (manager == NULL) { + return; + } + + wl_list_insert(&manager->clients, &client->link); +} + +static void tablet_manager_v2_destroy(struct wlr_tablet_manager_v2 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + + struct wlr_tablet_seat_v2 *seat, *tmp; + wl_list_for_each_safe(seat, tmp, &manager->seats, link) { + tablet_seat_destroy(seat); + } + + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->wl_global); + } else { + wl_global_destroy(manager->wl_global); + } + free(manager); +} + +void wlr_tablet_v2_destroy(struct wlr_tablet_manager_v2 *manager, bool destroy_global_safe) { + tablet_manager_v2_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_tablet_manager_v2 *manager = + wl_container_of(listener, manager, display_destroy); + tablet_manager_v2_destroy(manager, false); +} + +struct wlr_tablet_manager_v2 *wlr_tablet_v2_create(struct wl_display *display) { + struct wlr_tablet_manager_v2 *tablet = calloc(1, sizeof(*tablet)); + if (!tablet) { + return NULL; + } + + tablet->wl_global = wl_global_create(display, + &zwp_tablet_manager_v2_interface, TABLET_MANAGER_VERSION, + tablet, tablet_v2_bind); + if (tablet->wl_global == NULL) { + free(tablet); + return NULL; + } + + wl_signal_init(&tablet->events.destroy); + + wl_list_init(&tablet->clients); + wl_list_init(&tablet->seats); + + tablet->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &tablet->display_destroy); + + return tablet; +} diff --git a/3rdparty/wlroots/types/tablet_v2/wlr_tablet_v2_pad.c b/3rdparty/wlroots/types/tablet_v2/wlr_tablet_v2_pad.c new file mode 100644 index 0000000000..2e0439a368 --- /dev/null +++ b/3rdparty/wlroots/types/tablet_v2/wlr_tablet_v2_pad.c @@ -0,0 +1,701 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "util/time.h" +#include "tablet-v2-protocol.h" + +static const struct wlr_tablet_pad_v2_grab_interface default_pad_grab_interface; + +struct tablet_pad_auxiliary_user_data { + struct wlr_tablet_pad_client_v2 *pad; + size_t index; +}; + +static void handle_tablet_pad_v2_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void destroy_tablet_pad_ring_v2(struct wl_resource *resource) { + struct tablet_pad_auxiliary_user_data *aux = wl_resource_get_user_data(resource); + + if (!aux) { + return; + } + + aux->pad->rings[aux->index] = NULL; + free(aux); + wl_resource_set_user_data(resource, NULL); +} + +static void handle_tablet_pad_ring_v2_set_feedback(struct wl_client *client, + struct wl_resource *resource, const char *description, + uint32_t serial) { + struct tablet_pad_auxiliary_user_data *aux = wl_resource_get_user_data(resource); + if (!aux) { + return; + } + + struct wlr_tablet_v2_event_feedback evt = { + .serial = serial, + .description = description, + .index = aux->index + }; + + wl_signal_emit_mutable(&aux->pad->pad->events.ring_feedback, &evt); +} + +static void handle_tablet_pad_ring_v2_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwp_tablet_pad_ring_v2_interface tablet_pad_ring_impl = { + .set_feedback = handle_tablet_pad_ring_v2_set_feedback, + .destroy = handle_tablet_pad_ring_v2_destroy, +}; + +static void destroy_tablet_pad_strip_v2(struct wl_resource *resource) { + struct tablet_pad_auxiliary_user_data *aux = wl_resource_get_user_data(resource); + if (!aux) { + return; + } + + aux->pad->strips[aux->index] = NULL; + free(aux); + wl_resource_set_user_data(resource, NULL); +} + +static void handle_tablet_pad_strip_v2_set_feedback(struct wl_client *client, + struct wl_resource *resource, const char *description, + uint32_t serial) { + struct tablet_pad_auxiliary_user_data *aux = wl_resource_get_user_data(resource); + if (!aux) { + return; + } + + struct wlr_tablet_v2_event_feedback evt = { + .serial = serial, + .description = description, + .index = aux->index + }; + + wl_signal_emit_mutable(&aux->pad->pad->events.strip_feedback, &evt); +} + +static void handle_tablet_pad_strip_v2_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwp_tablet_pad_strip_v2_interface tablet_pad_strip_impl = { + .set_feedback = handle_tablet_pad_strip_v2_set_feedback, + .destroy = handle_tablet_pad_strip_v2_destroy, +}; + +static void handle_tablet_pad_v2_set_feedback( struct wl_client *client, + struct wl_resource *resource, uint32_t button, + const char *description, uint32_t serial) { + struct wlr_tablet_pad_client_v2 *pad = tablet_pad_client_from_resource(resource); + if (!pad) { + return; + } + + struct wlr_tablet_v2_event_feedback evt = { + .serial = serial, + .index = button, + .description = description, + }; + + wl_signal_emit_mutable(&pad->pad->events.button_feedback, &evt); +} + +static const struct zwp_tablet_pad_v2_interface tablet_pad_impl = { + .set_feedback = handle_tablet_pad_v2_set_feedback, + .destroy = handle_tablet_pad_v2_destroy, +}; + +static void destroy_tablet_pad_group_v2(struct wl_resource *resource) { + struct tablet_pad_auxiliary_user_data *aux = wl_resource_get_user_data(resource); + + if (!aux) { + return; + } + + aux->pad->groups[aux->index] = NULL; + free(aux); + wl_resource_set_user_data(resource, NULL); +} + +void destroy_tablet_pad_v2(struct wl_resource *resource) { + struct wlr_tablet_pad_client_v2 *pad = + tablet_pad_client_from_resource(resource); + + if (!pad) { + return; + } + + wl_list_remove(&pad->seat_link); + wl_list_remove(&pad->pad_link); + + /* This isn't optimal, if the client destroys the resources in another + * order, it will be disconnected. + * But this makes things *way* easier for us, and (untested) I doubt + * clients will destroy it in another order. + */ + for (size_t i = 0; i < pad->group_count; ++i) { + if (pad->groups[i]) { + destroy_tablet_pad_group_v2(pad->groups[i]); + } + } + free(pad->groups); + + for (size_t i = 0; i < pad->ring_count; ++i) { + if (pad->rings[i]) { + destroy_tablet_pad_ring_v2(pad->rings[i]); + } + } + free(pad->rings); + + for (size_t i = 0; i < pad->strip_count; ++i) { + if (pad->strips[i]) { + destroy_tablet_pad_strip_v2(pad->strips[i]); + } + } + free(pad->strips); + + if (pad->pad->current_client == pad) { + pad->pad->current_client = NULL; + } + free(pad); + wl_resource_set_user_data(resource, NULL); +} + +static void handle_tablet_pad_group_v2_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwp_tablet_pad_group_v2_interface tablet_pad_group_impl = { + .destroy = handle_tablet_pad_group_v2_destroy, +}; + +static void add_tablet_pad_group(struct wlr_tablet_v2_tablet_pad *pad, + struct wlr_tablet_pad_client_v2 *client, + struct wlr_tablet_pad_group *group, size_t index) { + + uint32_t version = wl_resource_get_version(client->resource); + client->groups[index] = wl_resource_create(client->client, + &zwp_tablet_pad_group_v2_interface, version, 0); + if (!client->groups[index]) { + wl_client_post_no_memory(client->client); + return; + } + struct tablet_pad_auxiliary_user_data *user_data = calloc(1, sizeof(*user_data)); + if (!user_data) { + wl_client_post_no_memory(client->client); + return; + } + user_data->pad = client; + user_data->index = index; + wl_resource_set_implementation(client->groups[index], &tablet_pad_group_impl, + user_data, destroy_tablet_pad_group_v2); + + zwp_tablet_pad_v2_send_group(client->resource, client->groups[index]); + zwp_tablet_pad_group_v2_send_modes(client->groups[index], group->mode_count); + + struct wl_array button_array; + wl_array_init(&button_array); + wl_array_add(&button_array, group->button_count * sizeof(int)); + memcpy(button_array.data, group->buttons, group->button_count * sizeof(int)); + zwp_tablet_pad_group_v2_send_buttons(client->groups[index], &button_array); + wl_array_release(&button_array); + + client->strip_count = group->strip_count; + for (size_t i = 0; i < group->strip_count; ++i) { + size_t strip = group->strips[i]; + struct tablet_pad_auxiliary_user_data *user_data = calloc(1, sizeof(*user_data)); + if (!user_data) { + wl_client_post_no_memory(client->client); + return; + } + user_data->pad = client; + user_data->index = strip; + client->strips[strip] = wl_resource_create(client->client, + &zwp_tablet_pad_strip_v2_interface, version, 0); + if (!client->strips[strip]) { + free(user_data); + wl_client_post_no_memory(client->client); + return; + } + wl_resource_set_implementation(client->strips[strip], + &tablet_pad_strip_impl, user_data, destroy_tablet_pad_strip_v2); + zwp_tablet_pad_group_v2_send_strip(client->groups[index], + client->strips[strip]); + } + + client->ring_count = group->ring_count; + for (size_t i = 0; i < group->ring_count; ++i) { + size_t ring = group->rings[i]; + struct tablet_pad_auxiliary_user_data *user_data = calloc(1, sizeof(*user_data)); + if (!user_data) { + wl_client_post_no_memory(client->client); + return; + } + user_data->pad = client; + user_data->index = ring; + client->rings[ring] = wl_resource_create(client->client, + &zwp_tablet_pad_ring_v2_interface, version, 0); + if (!client->rings[ring]) { + free(user_data); + wl_client_post_no_memory(client->client); + return; + } + wl_resource_set_implementation(client->rings[ring], + &tablet_pad_ring_impl, user_data, destroy_tablet_pad_ring_v2); + zwp_tablet_pad_group_v2_send_ring(client->groups[index], + client->rings[ring]); + } + + zwp_tablet_pad_group_v2_send_done(client->groups[index]); +} + +void add_tablet_pad_client(struct wlr_tablet_seat_client_v2 *seat, + struct wlr_tablet_v2_tablet_pad *pad) { + struct wlr_tablet_pad_client_v2 *client = calloc(1, sizeof(*client)); + if (!client) { + wl_client_post_no_memory(seat->wl_client); + return; + } + client->pad = pad; + client->seat = seat; + + client->groups = calloc(wl_list_length(&pad->wlr_pad->groups), sizeof(*client->groups)); + if (!client->groups) { + wl_client_post_no_memory(seat->wl_client); + free(client); + return; + } + + client->rings = calloc(pad->wlr_pad->ring_count, sizeof(*client->rings)); + if (!client->rings) { + wl_client_post_no_memory(seat->wl_client); + free(client->groups); + free(client); + return; + } + + client->strips = calloc(pad->wlr_pad->strip_count, sizeof(*client->strips)); + if (!client->strips) { + wl_client_post_no_memory(seat->wl_client); + free(client->groups); + free(client->rings); + free(client); + return; + } + + uint32_t version = wl_resource_get_version(seat->resource); + client->resource = wl_resource_create(seat->wl_client, + &zwp_tablet_pad_v2_interface, version, 0); + if (!client->resource) { + wl_client_post_no_memory(seat->wl_client); + free(client->groups); + free(client->rings); + free(client->strips); + free(client); + return; + } + wl_resource_set_implementation(client->resource, &tablet_pad_impl, + client, destroy_tablet_pad_v2); + zwp_tablet_seat_v2_send_pad_added(seat->resource, client->resource); + client->client = seat->wl_client; + + // Send the expected events + if (pad->wlr_pad->button_count) { + zwp_tablet_pad_v2_send_buttons(client->resource, pad->wlr_pad->button_count); + } + + const char **path_ptr; + wl_array_for_each(path_ptr, &pad->wlr_pad->paths) { + zwp_tablet_pad_v2_send_path(client->resource, *path_ptr); + } + + size_t i = 0; + struct wlr_tablet_pad_group *group; + client->group_count = pad->group_count; + wl_list_for_each(group, &pad->wlr_pad->groups, link) { + add_tablet_pad_group(pad, client, group, i++); + } + + zwp_tablet_pad_v2_send_done(client->resource); + + wl_list_insert(&seat->pads, &client->seat_link); + wl_list_insert(&pad->clients, &client->pad_link); +} + +static void handle_wlr_tablet_pad_destroy(struct wl_listener *listener, void *data) { + struct wlr_tablet_v2_tablet_pad *pad = + wl_container_of(listener, pad, pad_destroy); + + struct wlr_tablet_pad_client_v2 *client; + struct wlr_tablet_pad_client_v2 *tmp_client; + wl_list_for_each_safe(client, tmp_client, &pad->clients, pad_link) { + zwp_tablet_pad_v2_send_removed(client->resource); + destroy_tablet_pad_v2(client->resource); + } + + wl_list_remove(&pad->clients); + wl_list_remove(&pad->link); + wl_list_remove(&pad->pad_destroy.link); + wl_list_remove(&pad->events.button_feedback.listener_list); + wl_list_remove(&pad->events.strip_feedback.listener_list); + wl_list_remove(&pad->events.ring_feedback.listener_list); + free(pad); +} + +struct wlr_tablet_v2_tablet_pad *wlr_tablet_pad_create( + struct wlr_tablet_manager_v2 *manager, + struct wlr_seat *wlr_seat, + struct wlr_input_device *wlr_device) { + assert(wlr_device->type == WLR_INPUT_DEVICE_TABLET_PAD); + struct wlr_tablet_seat_v2 *seat = get_or_create_tablet_seat(manager, wlr_seat); + if (!seat) { + return NULL; + } + struct wlr_tablet_pad *wlr_pad = wlr_tablet_pad_from_input_device(wlr_device); + struct wlr_tablet_v2_tablet_pad *pad = calloc(1, sizeof(*pad)); + if (!pad) { + return NULL; + } + pad->default_grab.interface = &default_pad_grab_interface; + pad->default_grab.pad = pad; + pad->grab = &pad->default_grab; + + pad->group_count = wl_list_length(&wlr_pad->groups); + pad->groups = calloc(pad->group_count, sizeof(uint32_t)); + if (!pad->groups) { + free(pad); + return NULL; + } + + pad->wlr_pad = wlr_pad; + wl_list_init(&pad->clients); + + pad->pad_destroy.notify = handle_wlr_tablet_pad_destroy; + wl_signal_add(&wlr_device->events.destroy, &pad->pad_destroy); + wl_list_insert(&seat->pads, &pad->link); + + // We need to create a tablet client for all clients on the seat + struct wlr_tablet_seat_client_v2 *pos; + wl_list_for_each(pos, &seat->clients, seat_link) { + // Tell the clients about the new tool + add_tablet_pad_client(pos, pad); + } + + wl_signal_init(&pad->events.button_feedback); + wl_signal_init(&pad->events.strip_feedback); + wl_signal_init(&pad->events.ring_feedback); + + return pad; +} + +struct wlr_tablet_pad_client_v2 *tablet_pad_client_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwp_tablet_pad_v2_interface, + &tablet_pad_impl)); + return wl_resource_get_user_data(resource); +} + +/* Actual protocol foo */ +uint32_t wlr_send_tablet_v2_tablet_pad_enter( + struct wlr_tablet_v2_tablet_pad *pad, + struct wlr_tablet_v2_tablet *tablet, + struct wlr_surface *surface) { + struct wl_client *client = wl_resource_get_client(surface->resource); + + struct wlr_tablet_client_v2 *tablet_tmp; + struct wlr_tablet_client_v2 *tablet_client = NULL; + wl_list_for_each(tablet_tmp, &tablet->clients, tablet_link) { + if (tablet_tmp->client == client) { + tablet_client = tablet_tmp; + break; + } + } + + // Couldn't find the client binding for the surface's client. Either + // the client didn't bind tablet_v2 at all, or not for the relevant + // seat + if (!tablet_client) { + return 0; + } + + struct wlr_tablet_pad_client_v2 *pad_tmp = NULL; + struct wlr_tablet_pad_client_v2 *pad_client = NULL; + wl_list_for_each(pad_tmp, &pad->clients, pad_link) { + if (pad_tmp->client == client) { + pad_client = pad_tmp; + break; + } + } + + // Couldn't find the client binding for the surface's client. Either + // the client didn't bind tablet_v2 at all, or not for the relevant + // seat + if (!pad_client) { + return 0; + } + + pad->current_client = pad_client; + + uint32_t serial = wlr_seat_client_next_serial( + pad_client->seat->seat_client); + + zwp_tablet_pad_v2_send_enter(pad_client->resource, serial, + tablet_client->resource, surface->resource); + + uint32_t time = get_current_time_msec(); + for (size_t i = 0; i < pad->group_count; ++i) { + if (pad_client->groups[i]) { + zwp_tablet_pad_group_v2_send_mode_switch( + pad_client->groups[i], time, serial, pad->groups[i]); + } + } + + return serial; +} + +void wlr_send_tablet_v2_tablet_pad_button( + struct wlr_tablet_v2_tablet_pad *pad, size_t button, + uint32_t time, enum zwp_tablet_pad_v2_button_state state) { + + if (pad->current_client) { + zwp_tablet_pad_v2_send_button(pad->current_client->resource, + time, button, state); + } +} + +void wlr_send_tablet_v2_tablet_pad_strip(struct wlr_tablet_v2_tablet_pad *pad, + uint32_t strip, double position, bool finger, uint32_t time) { + if (!pad->current_client || + !pad->current_client->strips || + !pad->current_client->strips[strip]) { + return; + } + struct wl_resource *resource = pad->current_client->strips[strip]; + + if (finger) { + zwp_tablet_pad_strip_v2_send_source(resource, ZWP_TABLET_PAD_STRIP_V2_SOURCE_FINGER); + } + + if (position < 0) { + zwp_tablet_pad_strip_v2_send_stop(resource); + } else { + zwp_tablet_pad_strip_v2_send_position(resource, position * 65535); + } + zwp_tablet_pad_strip_v2_send_frame(resource, time); +} + +void wlr_send_tablet_v2_tablet_pad_ring(struct wlr_tablet_v2_tablet_pad *pad, + uint32_t ring, double position, bool finger, uint32_t time) { + if (!pad->current_client || + !pad->current_client->rings || + !pad->current_client->rings[ring]) { + return; + } + struct wl_resource *resource = pad->current_client->rings[ring]; + + if (finger) { + zwp_tablet_pad_ring_v2_send_source(resource, ZWP_TABLET_PAD_RING_V2_SOURCE_FINGER); + } + + if (position < 0) { + zwp_tablet_pad_ring_v2_send_stop(resource); + } else { + zwp_tablet_pad_ring_v2_send_angle(resource, wl_fixed_from_double(position)); + } + zwp_tablet_pad_ring_v2_send_frame(resource, time); +} + +uint32_t wlr_send_tablet_v2_tablet_pad_leave(struct wlr_tablet_v2_tablet_pad *pad, + struct wlr_surface *surface) { + struct wl_client *client = wl_resource_get_client(surface->resource); + if (!pad->current_client || client != pad->current_client->client) { + return 0; + } + + + uint32_t serial = wlr_seat_client_next_serial( + pad->current_client->seat->seat_client); + + zwp_tablet_pad_v2_send_leave(pad->current_client->resource, serial, surface->resource); + return serial; +} + +uint32_t wlr_send_tablet_v2_tablet_pad_mode(struct wlr_tablet_v2_tablet_pad *pad, + size_t group, uint32_t mode, uint32_t time) { + if (!pad->current_client || + !pad->current_client->groups || + !pad->current_client->groups[group] ) { + return 0; + } + + if (pad->groups[group] == mode) { + return 0; + } + + pad->groups[group] = mode; + + uint32_t serial = wlr_seat_client_next_serial( + pad->current_client->seat->seat_client); + + zwp_tablet_pad_group_v2_send_mode_switch( + pad->current_client->groups[group], time, serial, mode); + return serial; +} + +bool wlr_surface_accepts_tablet_v2(struct wlr_surface *surface, + struct wlr_tablet_v2_tablet *tablet) { + struct wl_client *client = wl_resource_get_client(surface->resource); + + if (tablet->current_client && + tablet->current_client->client == client) { + return true; + } + + struct wlr_tablet_client_v2 *tablet_tmp; + wl_list_for_each(tablet_tmp, &tablet->clients, tablet_link) { + if (tablet_tmp->client == client) { + return true; + } + } + + return false; +} + + +uint32_t wlr_tablet_v2_tablet_pad_notify_enter( + struct wlr_tablet_v2_tablet_pad *pad, + struct wlr_tablet_v2_tablet *tablet, + struct wlr_surface *surface) { + if (pad->grab && pad->grab->interface->enter) { + return pad->grab->interface->enter(pad->grab, tablet, surface); + } + + return 0; +} + +void wlr_tablet_v2_tablet_pad_notify_button( + struct wlr_tablet_v2_tablet_pad *pad, size_t button, + uint32_t time, enum zwp_tablet_pad_v2_button_state state) { + if (pad->grab && pad->grab->interface->button) { + pad->grab->interface->button(pad->grab, button, time, state); + } +} + +void wlr_tablet_v2_tablet_pad_notify_strip( + struct wlr_tablet_v2_tablet_pad *pad, + uint32_t strip, double position, bool finger, uint32_t time) { + if (pad->grab && pad->grab->interface->strip) { + pad->grab->interface->strip(pad->grab, strip, position, finger, time); + } +} + +void wlr_tablet_v2_tablet_pad_notify_ring( + struct wlr_tablet_v2_tablet_pad *pad, + uint32_t ring, double position, bool finger, uint32_t time) { + if (pad->grab && pad->grab->interface->ring) { + pad->grab->interface->ring(pad->grab, ring, position, finger, time); + } +} + +uint32_t wlr_tablet_v2_tablet_pad_notify_leave( + struct wlr_tablet_v2_tablet_pad *pad, struct wlr_surface *surface) { + if (pad->grab && pad->grab->interface->leave) { + return pad->grab->interface->leave(pad->grab, surface); + } + + return 0; +} + +uint32_t wlr_tablet_v2_tablet_pad_notify_mode( + struct wlr_tablet_v2_tablet_pad *pad, + size_t group, uint32_t mode, uint32_t time) { + if (pad->grab && pad->grab->interface->mode) { + return pad->grab->interface->mode(pad->grab, group, mode, time); + } + + return 0; +} + +void wlr_tablet_v2_start_grab(struct wlr_tablet_v2_tablet_pad *pad, + struct wlr_tablet_pad_v2_grab *grab) { + if (grab != &pad->default_grab) { + struct wlr_tablet_pad_v2_grab *prev = pad->grab; + grab->pad = pad; + pad->grab = grab; + if (prev && prev->interface->cancel) { + prev->interface->cancel(prev); + } + } +} + +void wlr_tablet_v2_end_grab(struct wlr_tablet_v2_tablet_pad *pad) { + struct wlr_tablet_pad_v2_grab *grab = pad->grab; + if (grab && grab != &pad->default_grab) { + pad->grab = &pad->default_grab; + if (grab->interface->cancel) { + grab->interface->cancel(grab); + } + } +} + +static uint32_t default_pad_enter( + struct wlr_tablet_pad_v2_grab *grab, + struct wlr_tablet_v2_tablet *tablet, + struct wlr_surface *surface) { + return wlr_send_tablet_v2_tablet_pad_enter(grab->pad, tablet, surface); +} + +static void default_pad_button(struct wlr_tablet_pad_v2_grab *grab,size_t button, + uint32_t time, enum zwp_tablet_pad_v2_button_state state) { + wlr_send_tablet_v2_tablet_pad_button(grab->pad, button, time, state); +} + +static void default_pad_strip(struct wlr_tablet_pad_v2_grab *grab, + uint32_t strip, double position, bool finger, uint32_t time) { + wlr_send_tablet_v2_tablet_pad_strip(grab->pad, strip, position, finger, time); +} + +static void default_pad_ring(struct wlr_tablet_pad_v2_grab *grab, + uint32_t ring, double position, bool finger, uint32_t time) { + wlr_send_tablet_v2_tablet_pad_ring(grab->pad, ring, position, finger, time); +} + +static uint32_t default_pad_leave(struct wlr_tablet_pad_v2_grab *grab, + struct wlr_surface *surface) { + return wlr_send_tablet_v2_tablet_pad_leave(grab->pad, surface); +} + +static uint32_t default_pad_mode(struct wlr_tablet_pad_v2_grab *grab, + size_t group, uint32_t mode, uint32_t time) { + return wlr_send_tablet_v2_tablet_pad_mode(grab->pad, group, mode, time); +} + +static void default_pad_cancel(struct wlr_tablet_pad_v2_grab *grab) { + // Do nothing, the default cancel can be ignored. +} + +static const struct wlr_tablet_pad_v2_grab_interface default_pad_grab_interface = { + .enter = default_pad_enter, + .button = default_pad_button, + .strip = default_pad_strip, + .ring = default_pad_ring, + .leave = default_pad_leave, + .mode = default_pad_mode, + .cancel = default_pad_cancel, +}; diff --git a/3rdparty/wlroots/types/tablet_v2/wlr_tablet_v2_tablet.c b/3rdparty/wlroots/types/tablet_v2/wlr_tablet_v2_tablet.c new file mode 100644 index 0000000000..36609e8a68 --- /dev/null +++ b/3rdparty/wlroots/types/tablet_v2/wlr_tablet_v2_tablet.c @@ -0,0 +1,131 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tablet-v2-protocol.h" + +void destroy_tablet_v2(struct wl_resource *resource) { + struct wlr_tablet_client_v2 *tablet = tablet_client_from_resource(resource); + + if (!tablet) { + return; + } + + wl_list_remove(&tablet->seat_link); + wl_list_remove(&tablet->tablet_link); + free(tablet); + wl_resource_set_user_data(resource, NULL); +} + +static void handle_tablet_v2_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwp_tablet_v2_interface tablet_impl = { + .destroy = handle_tablet_v2_destroy, +}; + +static void handle_wlr_tablet_destroy(struct wl_listener *listener, void *data) { + struct wlr_tablet_v2_tablet *tablet = + wl_container_of(listener, tablet, tablet_destroy); + + struct wlr_tablet_client_v2 *pos; + struct wlr_tablet_client_v2 *tmp; + wl_list_for_each_safe(pos, tmp, &tablet->clients, tablet_link) { + zwp_tablet_v2_send_removed(pos->resource); + } + + wl_list_remove(&tablet->clients); + wl_list_remove(&tablet->link); + wl_list_remove(&tablet->tablet_destroy.link); + free(tablet); +} + +struct wlr_tablet_v2_tablet *wlr_tablet_create( + struct wlr_tablet_manager_v2 *manager, + struct wlr_seat *wlr_seat, + struct wlr_input_device *wlr_device) { + assert(wlr_device->type == WLR_INPUT_DEVICE_TABLET); + struct wlr_tablet_seat_v2 *seat = get_or_create_tablet_seat(manager, wlr_seat); + if (!seat) { + return NULL; + } + struct wlr_tablet *wlr_tablet = wlr_tablet_from_input_device(wlr_device); + struct wlr_tablet_v2_tablet *tablet = calloc(1, sizeof(*tablet)); + if (!tablet) { + return NULL; + } + + tablet->wlr_tablet = wlr_tablet; + tablet->wlr_device = wlr_device; + wl_list_init(&tablet->clients); + + + tablet->tablet_destroy.notify = handle_wlr_tablet_destroy; + wl_signal_add(&wlr_device->events.destroy, &tablet->tablet_destroy); + wl_list_insert(&seat->tablets, &tablet->link); + + // We need to create a tablet client for all clients on the seat + struct wlr_tablet_seat_client_v2 *pos; + wl_list_for_each(pos, &seat->clients, seat_link) { + // Tell the clients about the new tool + add_tablet_client(pos, tablet); + } + + return tablet; +} + + +void add_tablet_client(struct wlr_tablet_seat_client_v2 *seat, + struct wlr_tablet_v2_tablet *tablet) { + struct wlr_tablet_client_v2 *client = calloc(1, sizeof(*client)); + if (!client) { + return; + } + + uint32_t version = wl_resource_get_version(seat->resource); + client->resource = + wl_resource_create(seat->wl_client, &zwp_tablet_v2_interface, + version, 0); + if (!client->resource) { + wl_resource_post_no_memory(seat->resource); + free(client); + return; + } + wl_resource_set_implementation(client->resource, &tablet_impl, + client, destroy_tablet_v2); + zwp_tablet_seat_v2_send_tablet_added(seat->resource, client->resource); + + if (tablet->wlr_tablet->base.name) { + zwp_tablet_v2_send_name(client->resource, + tablet->wlr_tablet->base.name); + } + if (tablet->wlr_tablet->usb_vendor_id != 0) { + zwp_tablet_v2_send_id(client->resource, + tablet->wlr_tablet->usb_vendor_id, tablet->wlr_tablet->usb_product_id); + } + + const char **path_ptr; + wl_array_for_each(path_ptr, &tablet->wlr_tablet->paths) { + zwp_tablet_v2_send_path(client->resource, *path_ptr); + } + + zwp_tablet_v2_send_done(client->resource); + + client->client = seat->wl_client; + wl_list_insert(&seat->tablets, &client->seat_link); + wl_list_insert(&tablet->clients, &client->tablet_link); +} + + +struct wlr_tablet_client_v2 *tablet_client_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwp_tablet_v2_interface, + &tablet_impl)); + return wl_resource_get_user_data(resource); +} diff --git a/3rdparty/wlroots/types/tablet_v2/wlr_tablet_v2_tool.c b/3rdparty/wlroots/types/tablet_v2/wlr_tablet_v2_tool.c new file mode 100644 index 0000000000..e73aa767b3 --- /dev/null +++ b/3rdparty/wlroots/types/tablet_v2/wlr_tablet_v2_tool.c @@ -0,0 +1,840 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "util/set.h" +#include "util/time.h" +#include "tablet-v2-protocol.h" + +static const struct wlr_tablet_tool_v2_grab_interface default_tool_grab_interface; + +static void tablet_tool_cursor_surface_handle_commit(struct wlr_surface *surface) { + pixman_region32_clear(&surface->input_region); + if (wlr_surface_has_buffer(surface)) { + wlr_surface_map(surface); + } +} + +static const struct wlr_surface_role tablet_tool_cursor_surface_role = { + .name = "wp_tablet_tool-cursor", + .no_object = true, + .commit = tablet_tool_cursor_surface_handle_commit, +}; + +static void handle_tablet_tool_v2_set_cursor(struct wl_client *client, + struct wl_resource *resource, uint32_t serial, + struct wl_resource *surface_resource, + int32_t hotspot_x, int32_t hotspot_y) { + struct wlr_tablet_tool_client_v2 *tool = tablet_tool_client_from_resource(resource); + if (!tool || !tool->tool) { + return; + } + + struct wlr_surface *surface = NULL; + if (surface_resource != NULL) { + surface = wlr_surface_from_resource(surface_resource); + if (!wlr_surface_set_role(surface, &tablet_tool_cursor_surface_role, + surface_resource, ZWP_TABLET_TOOL_V2_ERROR_ROLE)) { + return; + } + + tablet_tool_cursor_surface_handle_commit(surface); + } + + struct wlr_tablet_v2_event_cursor evt = { + .surface = surface, + .serial = serial, + .hotspot_x = hotspot_x, + .hotspot_y = hotspot_y, + .seat_client = tool->seat->seat_client, + }; + + wl_signal_emit_mutable(&tool->tool->events.set_cursor, &evt); +} + +static void handle_tablet_tool_v2_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} +static const struct zwp_tablet_tool_v2_interface tablet_tool_impl = { + .set_cursor = handle_tablet_tool_v2_set_cursor, + .destroy = handle_tablet_tool_v2_destroy, +}; + +static enum zwp_tablet_tool_v2_type tablet_type_from_wlr_type( + enum wlr_tablet_tool_type wlr_type) { + switch(wlr_type) { + case WLR_TABLET_TOOL_TYPE_PEN: + return ZWP_TABLET_TOOL_V2_TYPE_PEN; + case WLR_TABLET_TOOL_TYPE_ERASER: + return ZWP_TABLET_TOOL_V2_TYPE_ERASER; + case WLR_TABLET_TOOL_TYPE_BRUSH: + return ZWP_TABLET_TOOL_V2_TYPE_BRUSH; + case WLR_TABLET_TOOL_TYPE_PENCIL: + return ZWP_TABLET_TOOL_V2_TYPE_PENCIL; + case WLR_TABLET_TOOL_TYPE_AIRBRUSH: + return ZWP_TABLET_TOOL_V2_TYPE_AIRBRUSH; + case WLR_TABLET_TOOL_TYPE_MOUSE: + return ZWP_TABLET_TOOL_V2_TYPE_MOUSE; + case WLR_TABLET_TOOL_TYPE_LENS: + return ZWP_TABLET_TOOL_V2_TYPE_LENS; + case WLR_TABLET_TOOL_TYPE_TOTEM: + // missing, see: + // https://gitlab.freedesktop.org/wayland/wayland-protocols/-/issues/19 + abort(); + } + abort(); // unreachable +} + +void destroy_tablet_tool_v2(struct wl_resource *resource) { + struct wlr_tablet_tool_client_v2 *client = + tablet_tool_client_from_resource(resource); + + if (!client) { + return; + } + + if (client->frame_source) { + wl_event_source_remove(client->frame_source); + } + + if (client->tool && client->tool->current_client == client) { + wl_list_remove(&client->tool->surface_destroy.link); + wl_list_init(&client->tool->surface_destroy.link); + client->tool->current_client = NULL; + client->tool->focused_surface = NULL; + } + + wl_list_remove(&client->seat_link); + wl_list_remove(&client->tool_link); + free(client); + + wl_resource_set_user_data(resource, NULL); +} + +void add_tablet_tool_client(struct wlr_tablet_seat_client_v2 *seat, + struct wlr_tablet_v2_tablet_tool *tool) { + struct wlr_tablet_tool_client_v2 *client = calloc(1, sizeof(*client)); + if (!client) { + return; + } + client->tool = tool; + client->seat = seat; + + uint32_t version = wl_resource_get_version(seat->resource); + client->resource = wl_resource_create(seat->wl_client, + &zwp_tablet_tool_v2_interface, version, 0); + if (!client->resource) { + free(client); + return; + } + wl_resource_set_implementation(client->resource, &tablet_tool_impl, + client, destroy_tablet_tool_v2); + zwp_tablet_seat_v2_send_tool_added(seat->resource, client->resource); + + // Send the expected events + if (tool->wlr_tool->hardware_serial) { + zwp_tablet_tool_v2_send_hardware_serial( + client->resource, + tool->wlr_tool->hardware_serial >> 32, + tool->wlr_tool->hardware_serial & 0xFFFFFFFF); + } + if (tool->wlr_tool->hardware_wacom) { + zwp_tablet_tool_v2_send_hardware_id_wacom( + client->resource, + tool->wlr_tool->hardware_wacom >> 32, + tool->wlr_tool->hardware_wacom & 0xFFFFFFFF); + } + zwp_tablet_tool_v2_send_type(client->resource, + tablet_type_from_wlr_type(tool->wlr_tool->type)); + + if (tool->wlr_tool->tilt) { + zwp_tablet_tool_v2_send_capability(client->resource, + ZWP_TABLET_TOOL_V2_CAPABILITY_TILT); + } + + if (tool->wlr_tool->pressure) { + zwp_tablet_tool_v2_send_capability(client->resource, + ZWP_TABLET_TOOL_V2_CAPABILITY_PRESSURE); + } + + if (tool->wlr_tool->distance) { + zwp_tablet_tool_v2_send_capability(client->resource, + ZWP_TABLET_TOOL_V2_CAPABILITY_DISTANCE); + } + + if (tool->wlr_tool->rotation) { + zwp_tablet_tool_v2_send_capability(client->resource, + ZWP_TABLET_TOOL_V2_CAPABILITY_ROTATION); + } + + if (tool->wlr_tool->slider) { + zwp_tablet_tool_v2_send_capability(client->resource, + ZWP_TABLET_TOOL_V2_CAPABILITY_SLIDER); + } + + if (tool->wlr_tool->wheel) { + zwp_tablet_tool_v2_send_capability(client->resource, + ZWP_TABLET_TOOL_V2_CAPABILITY_WHEEL); + } + + zwp_tablet_tool_v2_send_done(client->resource); + + client->client = seat->wl_client; + wl_list_insert(&seat->tools, &client->seat_link); + wl_list_insert(&tool->clients, &client->tool_link); +} + +static void handle_wlr_tablet_tool_destroy(struct wl_listener *listener, void *data) { + struct wlr_tablet_v2_tablet_tool *tool = + wl_container_of(listener, tool, tool_destroy); + + struct wlr_tablet_tool_client_v2 *pos; + struct wlr_tablet_tool_client_v2 *tmp; + wl_list_for_each_safe(pos, tmp, &tool->clients, tool_link) { + zwp_tablet_tool_v2_send_removed(pos->resource); + pos->tool = NULL; + } + + wl_list_remove(&tool->clients); + wl_list_remove(&tool->link); + wl_list_remove(&tool->tool_destroy.link); + wl_list_remove(&tool->events.set_cursor.listener_list); + wl_list_remove(&tool->surface_destroy.link); + free(tool); +} + +struct wlr_tablet_v2_tablet_tool *wlr_tablet_tool_create( + struct wlr_tablet_manager_v2 *manager, + struct wlr_seat *wlr_seat, + struct wlr_tablet_tool *wlr_tool) { + switch (wlr_tool->type) { + case WLR_TABLET_TOOL_TYPE_PEN: + case WLR_TABLET_TOOL_TYPE_ERASER: + case WLR_TABLET_TOOL_TYPE_BRUSH: + case WLR_TABLET_TOOL_TYPE_PENCIL: + case WLR_TABLET_TOOL_TYPE_AIRBRUSH: + case WLR_TABLET_TOOL_TYPE_MOUSE: + case WLR_TABLET_TOOL_TYPE_LENS: + /* supported */ + break; + default: + /* Unsupported */ + return NULL; + } + + struct wlr_tablet_seat_v2 *seat = get_or_create_tablet_seat(manager, wlr_seat); + if (!seat) { + return NULL; + } + struct wlr_tablet_v2_tablet_tool *tool = calloc(1, sizeof(*tool)); + if (!tool) { + return NULL; + } + + tool->wlr_tool = wlr_tool; + wl_list_init(&tool->clients); + wl_list_init(&tool->surface_destroy.link); + tool->default_grab.tool = tool; + tool->default_grab.interface = &default_tool_grab_interface; + tool->grab = &tool->default_grab; + + tool->tool_destroy.notify = handle_wlr_tablet_tool_destroy; + wl_signal_add(&wlr_tool->events.destroy, &tool->tool_destroy); + wl_list_insert(&seat->tools, &tool->link); + + // We need to create a tablet client for all clients on the seat + struct wlr_tablet_seat_client_v2 *pos; + wl_list_for_each(pos, &seat->clients, seat_link) { + // Tell the clients about the new tool + add_tablet_tool_client(pos, tool); + } + + wl_signal_init(&tool->events.set_cursor); + + return tool; +} + +struct wlr_tablet_tool_client_v2 *tablet_tool_client_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwp_tablet_tool_v2_interface, + &tablet_tool_impl)); + return wl_resource_get_user_data(resource); +} + +static ssize_t tablet_tool_button_update(struct wlr_tablet_v2_tablet_tool *tool, + uint32_t button, enum zwp_tablet_pad_v2_button_state state) { + ssize_t i; + if (state == ZWP_TABLET_PAD_V2_BUTTON_STATE_PRESSED) { + i = set_add(tool->pressed_buttons, &tool->num_buttons, + WLR_TABLET_V2_TOOL_BUTTONS_CAP, button); + if (i != -1) { + tool->pressed_serials[i] = -1; + } else { + wlr_log(WLR_ERROR, "Failed to add tablet tool button %x", button); + } + } else { + i = set_remove(tool->pressed_buttons, &tool->num_buttons, + WLR_TABLET_V2_TOOL_BUTTONS_CAP, button); + if (i != -1) { + tool->pressed_serials[i] = tool->pressed_serials[tool->num_buttons]; + } else { + wlr_log(WLR_ERROR, "Failed to remove tablet tool button %x", button); + } + } + return i; +} + +static void send_tool_frame(void *data) { + struct wlr_tablet_tool_client_v2 *tool = data; + + zwp_tablet_tool_v2_send_frame(tool->resource, get_current_time_msec()); + tool->frame_source = NULL; +} + +static void queue_tool_frame(struct wlr_tablet_tool_client_v2 *tool) { + struct wl_display *display = wl_client_get_display(tool->client); + struct wl_event_loop *loop = wl_display_get_event_loop(display); + if (!tool->frame_source) { + tool->frame_source = + wl_event_loop_add_idle(loop, send_tool_frame, tool); + } +} + +static void handle_tablet_tool_surface_destroy(struct wl_listener *listener, + void *data) { + struct wlr_tablet_v2_tablet_tool *tool = + wl_container_of(listener, tool, surface_destroy); + wlr_send_tablet_v2_tablet_tool_proximity_out(tool); +} + +void wlr_send_tablet_v2_tablet_tool_proximity_in( + struct wlr_tablet_v2_tablet_tool *tool, + struct wlr_tablet_v2_tablet *tablet, + struct wlr_surface *surface) { + struct wl_client *client = wl_resource_get_client(surface->resource); + + if (tool->focused_surface == surface) { + return; + } + + wlr_send_tablet_v2_tablet_tool_proximity_out(tool); + + struct wlr_tablet_client_v2 *tablet_tmp; + struct wlr_tablet_client_v2 *tablet_client = NULL; + wl_list_for_each(tablet_tmp, &tablet->clients, tablet_link) { + if (tablet_tmp->client == client) { + tablet_client = tablet_tmp; + break; + } + } + + // Couldn't find the client binding for the surface's client. Either + // the client didn't bind tablet_v2 at all, or not for the relevant + // seat + if (!tablet_client) { + return; + } + + struct wlr_tablet_tool_client_v2 *tool_tmp = NULL; + struct wlr_tablet_tool_client_v2 *tool_client = NULL; + wl_list_for_each(tool_tmp, &tool->clients, tool_link) { + if (tool_tmp->client == client) { + tool_client = tool_tmp; + break; + } + } + + // Couldn't find the client binding for the surface's client. Either + // the client didn't bind tablet_v2 at all, or not for the relevant + // seat + if (!tool_client) { + return; + } + + // Reinitialize the focus destroy events + wl_list_remove(&tool->surface_destroy.link); + wl_signal_add(&surface->events.destroy, &tool->surface_destroy); + tool->surface_destroy.notify = handle_tablet_tool_surface_destroy; + + tool->current_client = tool_client; + + uint32_t serial = wlr_seat_client_next_serial(tool_client->seat->seat_client); + tool->focused_surface = surface; + tool->proximity_serial = serial; + + zwp_tablet_tool_v2_send_proximity_in(tool_client->resource, serial, + tablet_client->resource, surface->resource); + /* Send all the pressed buttons */ + for (size_t i = 0; i < tool->num_buttons; ++i) { + wlr_send_tablet_v2_tablet_tool_button(tool, + tool->pressed_buttons[i], + ZWP_TABLET_PAD_V2_BUTTON_STATE_PRESSED); + } + if (tool->is_down) { + wlr_send_tablet_v2_tablet_tool_down(tool); + } + + queue_tool_frame(tool_client); +} + +void wlr_send_tablet_v2_tablet_tool_motion( + struct wlr_tablet_v2_tablet_tool *tool, double x, double y) { + if (!tool->current_client) { + return; + } + + zwp_tablet_tool_v2_send_motion(tool->current_client->resource, + wl_fixed_from_double(x), wl_fixed_from_double(y)); + + queue_tool_frame(tool->current_client); +} + +void wlr_send_tablet_v2_tablet_tool_proximity_out( + struct wlr_tablet_v2_tablet_tool *tool) { + if (tool->current_client) { + for (size_t i = 0; i < tool->num_buttons; ++i) { + zwp_tablet_tool_v2_send_button(tool->current_client->resource, + tool->pressed_serials[i], + tool->pressed_buttons[i], + ZWP_TABLET_PAD_V2_BUTTON_STATE_RELEASED); + } + if (tool->is_down) { + zwp_tablet_tool_v2_send_up(tool->current_client->resource); + } + if (tool->current_client->frame_source) { + wl_event_source_remove(tool->current_client->frame_source); + send_tool_frame(tool->current_client); + } + zwp_tablet_tool_v2_send_proximity_out(tool->current_client->resource); + send_tool_frame(tool->current_client); + + wl_list_remove(&tool->surface_destroy.link); + wl_list_init(&tool->surface_destroy.link); + tool->current_client = NULL; + tool->focused_surface = NULL; + } +} + +void wlr_send_tablet_v2_tablet_tool_pressure( + struct wlr_tablet_v2_tablet_tool *tool, double pressure) { + if (tool->current_client) { + zwp_tablet_tool_v2_send_pressure(tool->current_client->resource, + pressure * 65535); + + queue_tool_frame(tool->current_client); + } +} + +void wlr_send_tablet_v2_tablet_tool_distance( + struct wlr_tablet_v2_tablet_tool *tool, double distance) { + if (tool->current_client) { + zwp_tablet_tool_v2_send_distance(tool->current_client->resource, + distance * 65535); + + queue_tool_frame(tool->current_client); + } +} + +void wlr_send_tablet_v2_tablet_tool_tilt( + struct wlr_tablet_v2_tablet_tool *tool, double x, double y) { + if (!tool->current_client) { + return; + } + + zwp_tablet_tool_v2_send_tilt(tool->current_client->resource, + wl_fixed_from_double(x), wl_fixed_from_double(y)); + + queue_tool_frame(tool->current_client); +} + +void wlr_send_tablet_v2_tablet_tool_rotation( + struct wlr_tablet_v2_tablet_tool *tool, double degrees) { + if (!tool->current_client) { + return; + } + + zwp_tablet_tool_v2_send_rotation(tool->current_client->resource, + wl_fixed_from_double(degrees)); + + queue_tool_frame(tool->current_client); +} + +void wlr_send_tablet_v2_tablet_tool_slider( + struct wlr_tablet_v2_tablet_tool *tool, double position) { + if (!tool->current_client) { + return; + } + + zwp_tablet_tool_v2_send_slider(tool->current_client->resource, + position * 65535); + + queue_tool_frame(tool->current_client); +} + +void wlr_send_tablet_v2_tablet_tool_button( + struct wlr_tablet_v2_tablet_tool *tool, uint32_t button, + enum zwp_tablet_pad_v2_button_state state) { + ssize_t index = tablet_tool_button_update(tool, button, state); + + if (tool->current_client) { + uint32_t serial = wlr_seat_client_next_serial( + tool->current_client->seat->seat_client); + if (index >= 0) { + tool->pressed_serials[index] = serial; + } + + zwp_tablet_tool_v2_send_button(tool->current_client->resource, + serial, button, state); + queue_tool_frame(tool->current_client); + } +} + +void wlr_send_tablet_v2_tablet_tool_wheel( + struct wlr_tablet_v2_tablet_tool *tool, double degrees, int32_t clicks) { + if (tool->current_client) { + zwp_tablet_tool_v2_send_wheel(tool->current_client->resource, + wl_fixed_from_double(degrees), clicks); + + queue_tool_frame(tool->current_client); + } +} + +void wlr_send_tablet_v2_tablet_tool_down(struct wlr_tablet_v2_tablet_tool *tool) { + if (tool->is_down) { + return; + } + + tool->is_down = true; + if (tool->current_client) { + uint32_t serial = wlr_seat_client_next_serial( + tool->current_client->seat->seat_client); + + zwp_tablet_tool_v2_send_down(tool->current_client->resource, + serial); + queue_tool_frame(tool->current_client); + + tool->down_serial = serial; + } +} + +void wlr_send_tablet_v2_tablet_tool_up(struct wlr_tablet_v2_tablet_tool *tool) { + if (!tool->is_down) { + return; + } + tool->is_down = false; + tool->down_serial = 0; + + if (tool->current_client) { + zwp_tablet_tool_v2_send_up(tool->current_client->resource); + queue_tool_frame(tool->current_client); + } +} + + +void wlr_tablet_v2_tablet_tool_notify_proximity_in( + struct wlr_tablet_v2_tablet_tool *tool, + struct wlr_tablet_v2_tablet *tablet, + struct wlr_surface *surface) { + if (tool->grab->interface->proximity_in) { + tool->grab->interface->proximity_in(tool->grab, tablet, surface); + } +} + +void wlr_tablet_v2_tablet_tool_notify_down(struct wlr_tablet_v2_tablet_tool *tool) { + if (tool->grab->interface->down) { + tool->grab->interface->down(tool->grab); + } +} +void wlr_tablet_v2_tablet_tool_notify_up(struct wlr_tablet_v2_tablet_tool *tool) { + if (tool->grab->interface->up) { + tool->grab->interface->up(tool->grab); + } +} + +void wlr_tablet_v2_tablet_tool_notify_motion( + struct wlr_tablet_v2_tablet_tool *tool, double x, double y) { + if (tool->grab->interface->motion) { + tool->grab->interface->motion(tool->grab, x, y); + } +} + +void wlr_tablet_v2_tablet_tool_notify_pressure( + struct wlr_tablet_v2_tablet_tool *tool, double pressure) { + if (tool->grab->interface->pressure) { + tool->grab->interface->pressure(tool->grab, pressure); + } +} + +void wlr_tablet_v2_tablet_tool_notify_distance( + struct wlr_tablet_v2_tablet_tool *tool, double distance) { + if (tool->grab->interface->distance) { + tool->grab->interface->distance(tool->grab, distance); + } +} + +void wlr_tablet_v2_tablet_tool_notify_tilt( + struct wlr_tablet_v2_tablet_tool *tool, double x, double y) { + if (tool->grab->interface->tilt) { + tool->grab->interface->tilt(tool->grab, x, y); + } +} + +void wlr_tablet_v2_tablet_tool_notify_rotation( + struct wlr_tablet_v2_tablet_tool *tool, double degrees) { + if (tool->grab->interface->rotation) { + tool->grab->interface->rotation(tool->grab, degrees); + } +} + +void wlr_tablet_v2_tablet_tool_notify_slider( + struct wlr_tablet_v2_tablet_tool *tool, double position) { + if (tool->grab->interface->slider) { + tool->grab->interface->slider(tool->grab, position); + } +} + +void wlr_tablet_v2_tablet_tool_notify_wheel( + struct wlr_tablet_v2_tablet_tool *tool, double degrees, int32_t clicks) { + if (tool->grab->interface->wheel) { + tool->grab->interface->wheel(tool->grab, degrees, clicks); + } +} + +void wlr_tablet_v2_tablet_tool_notify_proximity_out( + struct wlr_tablet_v2_tablet_tool *tool) { + if (tool->grab->interface->proximity_out) { + tool->grab->interface->proximity_out(tool->grab); + } +} + +void wlr_tablet_v2_tablet_tool_notify_button( + struct wlr_tablet_v2_tablet_tool *tool, uint32_t button, + enum zwp_tablet_pad_v2_button_state state) { + if (tool->grab->interface->button) { + tool->grab->interface->button(tool->grab, button, state); + } +} + +void wlr_tablet_tool_v2_start_grab(struct wlr_tablet_v2_tablet_tool *tool, + struct wlr_tablet_tool_v2_grab *grab) { + wlr_tablet_tool_v2_end_grab(tool); + tool->grab = grab; +} + +void wlr_tablet_tool_v2_end_grab(struct wlr_tablet_v2_tablet_tool *tool) { + if (tool->grab->interface->cancel) { + tool->grab->interface->cancel(tool->grab); + } + tool->grab = &tool->default_grab; +} + + +static void default_tool_proximity_in( + struct wlr_tablet_tool_v2_grab *grab, + struct wlr_tablet_v2_tablet *tablet, + struct wlr_surface *surface) { + wlr_send_tablet_v2_tablet_tool_proximity_in(grab->tool, tablet, surface); +} + +static void default_tool_down(struct wlr_tablet_tool_v2_grab *grab) { + wlr_send_tablet_v2_tablet_tool_down(grab->tool); +} +static void default_tool_up(struct wlr_tablet_tool_v2_grab *grab) { + wlr_send_tablet_v2_tablet_tool_up(grab->tool); +} + +static void default_tool_motion( + struct wlr_tablet_tool_v2_grab *grab, double x, double y) { + wlr_send_tablet_v2_tablet_tool_motion(grab->tool, x, y); +} + +static void default_tool_pressure( + struct wlr_tablet_tool_v2_grab *grab, double pressure) { + wlr_send_tablet_v2_tablet_tool_pressure(grab->tool, pressure); +} + +static void default_tool_distance( + struct wlr_tablet_tool_v2_grab *grab, double distance) { + wlr_send_tablet_v2_tablet_tool_distance(grab->tool, distance); +} + +static void default_tool_tilt( + struct wlr_tablet_tool_v2_grab *grab, double x, double y) { + wlr_send_tablet_v2_tablet_tool_tilt(grab->tool, x, y); +} + +static void default_tool_rotation( + struct wlr_tablet_tool_v2_grab *grab, double degrees) { + wlr_send_tablet_v2_tablet_tool_rotation(grab->tool, degrees); +} + +static void default_tool_slider( + struct wlr_tablet_tool_v2_grab *grab, double position) { + wlr_send_tablet_v2_tablet_tool_slider(grab->tool, position); +} + +static void default_tool_wheel( + struct wlr_tablet_tool_v2_grab *grab, double degrees, int32_t clicks) { + wlr_send_tablet_v2_tablet_tool_wheel(grab->tool, degrees, clicks); +} + +static void default_tool_proximity_out(struct wlr_tablet_tool_v2_grab *grab) { + wlr_send_tablet_v2_tablet_tool_proximity_out(grab->tool); +} + +static void default_tool_button( + struct wlr_tablet_tool_v2_grab *grab, uint32_t button, + enum zwp_tablet_pad_v2_button_state state) { + wlr_send_tablet_v2_tablet_tool_button(grab->tool, button, state); +} + +static void default_tool_cancel(struct wlr_tablet_tool_v2_grab *grab) { + /* Do nothing. Default grab can't be canceled */ +} + +static const struct wlr_tablet_tool_v2_grab_interface + default_tool_grab_interface = { + .proximity_in = default_tool_proximity_in, + .down = default_tool_down, + .up = default_tool_up, + .motion = default_tool_motion, + .pressure = default_tool_pressure, + .distance = default_tool_distance, + .tilt = default_tool_tilt, + .rotation = default_tool_rotation, + .slider = default_tool_slider, + .wheel = default_tool_wheel, + .proximity_out = default_tool_proximity_out, + .button = default_tool_button, + .cancel = default_tool_cancel, +}; + +struct implicit_grab_state { + struct wlr_surface *original; + bool released; + + struct wlr_surface *focused; + struct wlr_tablet_v2_tablet *tablet; +}; + +static void check_and_release_implicit_grab(struct wlr_tablet_tool_v2_grab *grab) { + struct implicit_grab_state *state = grab->data; + /* Still button or tip pressed. We should hold the grab */ + if (grab->tool->is_down || grab->tool->num_buttons > 0 || state->released) { + return; + } + + state->released = true; + + /* We should still focus the same surface. Do nothing */ + if (state->original == state->focused) { + wlr_tablet_tool_v2_end_grab(grab->tool); + return; + } + + wlr_send_tablet_v2_tablet_tool_proximity_out(grab->tool); + if (state->focused) { + wlr_send_tablet_v2_tablet_tool_proximity_in(grab->tool, + state->tablet, state->focused); + } + + wlr_tablet_tool_v2_end_grab(grab->tool); +} + +static void implicit_tool_proximity_in( + struct wlr_tablet_tool_v2_grab *grab, + struct wlr_tablet_v2_tablet *tablet, + struct wlr_surface *surface) { + + /* As long as we got an implicit grab, proximity won't change + * But should track the currently focused surface to change to it when + * the grab is released. + */ + struct implicit_grab_state *state = grab->data; + state->focused = surface; + state->tablet = tablet; +} + +static void implicit_tool_proximity_out(struct wlr_tablet_tool_v2_grab *grab) { + struct implicit_grab_state *state = grab->data; + state->focused = NULL; +} + +static void implicit_tool_down(struct wlr_tablet_tool_v2_grab *grab) { + wlr_send_tablet_v2_tablet_tool_down(grab->tool); +} + +static void implicit_tool_up(struct wlr_tablet_tool_v2_grab *grab) { + wlr_send_tablet_v2_tablet_tool_up(grab->tool); + check_and_release_implicit_grab(grab); +} + +static void implicit_tool_button( + struct wlr_tablet_tool_v2_grab *grab, uint32_t button, + enum zwp_tablet_pad_v2_button_state state) { + wlr_send_tablet_v2_tablet_tool_button(grab->tool, button, state); + check_and_release_implicit_grab(grab); +} + +static void implicit_tool_cancel(struct wlr_tablet_tool_v2_grab *grab) { + check_and_release_implicit_grab(grab); + free(grab->data); + free(grab); +} + +static const struct wlr_tablet_tool_v2_grab_interface + implicit_tool_grab_interface = { + .proximity_in = implicit_tool_proximity_in, + .down = implicit_tool_down, + .up = implicit_tool_up, + .motion = default_tool_motion, + .pressure = default_tool_pressure, + .distance = default_tool_distance, + .tilt = default_tool_tilt, + .rotation = default_tool_rotation, + .slider = default_tool_slider, + .wheel = default_tool_wheel, + .proximity_out = implicit_tool_proximity_out, + .button = implicit_tool_button, + .cancel = implicit_tool_cancel, +}; + +bool wlr_tablet_tool_v2_has_implicit_grab( + struct wlr_tablet_v2_tablet_tool *tool) { + return tool->grab->interface == &implicit_tool_grab_interface; +} + +void wlr_tablet_tool_v2_start_implicit_grab( + struct wlr_tablet_v2_tablet_tool *tool) { + if (wlr_tablet_tool_v2_has_implicit_grab(tool) || !tool->focused_surface) { + return; + } + + /* No current implicit grab */ + if (!(tool->is_down || tool->num_buttons > 0)) { + return; + } + + struct wlr_tablet_tool_v2_grab *grab = calloc(1, sizeof(*grab)); + if (!grab) { + return; + } + + grab->interface = &implicit_tool_grab_interface; + grab->tool = tool; + struct implicit_grab_state *state = calloc(1, sizeof(*state)); + if (!state) { + free(grab); + return; + } + + state->original = tool->focused_surface; + state->focused = tool->focused_surface; + grab->data = state; + + wlr_tablet_tool_v2_start_grab(tool, grab); +} diff --git a/3rdparty/wlroots/types/wlr_alpha_modifier_v1.c b/3rdparty/wlroots/types/wlr_alpha_modifier_v1.c new file mode 100644 index 0000000000..71810c895b --- /dev/null +++ b/3rdparty/wlroots/types/wlr_alpha_modifier_v1.c @@ -0,0 +1,204 @@ +#include +#include +#include +#include +#include +#include +#include "alpha-modifier-v1-protocol.h" +#include "util/global.h" + +#define ALPHA_MODIFIER_VERSION 1 + +struct wlr_alpha_modifier_surface_v1 { + struct wl_resource *resource; + struct wlr_surface *surface; + struct wlr_addon addon; + struct wlr_surface_synced synced; + struct wlr_alpha_modifier_surface_v1_state pending, current; +}; + +static const struct wp_alpha_modifier_surface_v1_interface surface_impl; + +// Returns NULL if the wl_surface was destroyed +static struct wlr_alpha_modifier_surface_v1 *surface_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wp_alpha_modifier_surface_v1_interface, + &surface_impl)); + return wl_resource_get_user_data(resource); +} + +static void surface_destroy(struct wlr_alpha_modifier_surface_v1 *surface) { + if (surface == NULL) { + return; + } + wlr_surface_synced_finish(&surface->synced); + wlr_addon_finish(&surface->addon); + wl_resource_set_user_data(surface->resource, NULL); + free(surface); +} + +static void surface_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_alpha_modifier_surface_v1 *surface = surface_from_resource(resource); + surface_destroy(surface); +} + +static void surface_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void surface_handle_set_multiplier(struct wl_client *client, + struct wl_resource *resource, uint32_t multiplier) { + struct wlr_alpha_modifier_surface_v1 *surface = surface_from_resource(resource); + if (surface == NULL) { + wl_resource_post_error(resource, + WP_ALPHA_MODIFIER_SURFACE_V1_ERROR_NO_SURFACE, + "The wl_surface object has been destroyed"); + return; + } + surface->pending.multiplier = (double)multiplier / UINT32_MAX; +} + +static const struct wp_alpha_modifier_surface_v1_interface surface_impl = { + .destroy = surface_handle_destroy, + .set_multiplier = surface_handle_set_multiplier, +}; + +static void surface_synced_init_state(void *_state) { + struct wlr_alpha_modifier_surface_v1_state *state = _state; + state->multiplier = 1; +} + +static const struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(struct wlr_alpha_modifier_surface_v1_state), + .init_state = surface_synced_init_state, +}; + +static void surface_addon_destroy(struct wlr_addon *addon) { + struct wlr_alpha_modifier_surface_v1 *surface = wl_container_of(addon, surface, addon); + surface_destroy(surface); +} + +static const struct wlr_addon_interface surface_addon_impl = { + .name = "wp_alpha_modifier_surface_v1", + .destroy = surface_addon_destroy, +}; + +static struct wlr_alpha_modifier_surface_v1 *surface_from_wlr_surface( + struct wlr_surface *wlr_surface) { + struct wlr_addon *addon = wlr_addon_find(&wlr_surface->addons, NULL, &surface_addon_impl); + if (addon == NULL) { + return NULL; + } + struct wlr_alpha_modifier_surface_v1 *surface = wl_container_of(addon, surface, addon); + return surface; +} + +static void manager_handle_destroy(struct wl_client *client, struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void manager_handle_get_surface(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + struct wl_resource *surface_resource) { + struct wlr_surface *wlr_surface = wlr_surface_from_resource(surface_resource); + + if (surface_from_wlr_surface(wlr_surface) != NULL) { + wl_resource_post_error(manager_resource, + WP_ALPHA_MODIFIER_V1_ERROR_ALREADY_CONSTRUCTED, + "The wl_surface object already has a wp_alpha_modifier_surface_v1 object"); + return; + } + + struct wlr_alpha_modifier_surface_v1 *surface = calloc(1, sizeof(*surface)); + if (surface == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + + if (!wlr_surface_synced_init(&surface->synced, wlr_surface, + &surface_synced_impl, &surface->pending, &surface->current)) { + free(surface); + wl_resource_post_no_memory(manager_resource); + return; + } + + uint32_t version = wl_resource_get_version(manager_resource); + surface->resource = wl_resource_create(client, + &wp_alpha_modifier_surface_v1_interface, version, id); + if (surface->resource == NULL) { + wlr_surface_synced_finish(&surface->synced); + free(surface); + wl_resource_post_no_memory(manager_resource); + return; + } + wl_resource_set_implementation(surface->resource, &surface_impl, + surface, surface_handle_resource_destroy); + + surface->surface = wlr_surface; + wlr_addon_init(&surface->addon, &wlr_surface->addons, NULL, &surface_addon_impl); +} + +static const struct wp_alpha_modifier_v1_interface manager_impl = { + .destroy = manager_handle_destroy, + .get_surface = manager_handle_get_surface, +}; + +static void manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wl_resource *resource = wl_resource_create(client, + &wp_alpha_modifier_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, NULL, NULL); +} + +static void alpha_modifier_v1_destroy(struct wlr_alpha_modifier_v1 *manager, + bool destroy_global_safe) { + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_alpha_modifier_v1_destroy(struct wlr_alpha_modifier_v1 *manager, + bool destroy_global_safe) { + alpha_modifier_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_alpha_modifier_v1 *manager = wl_container_of(listener, manager, display_destroy); + alpha_modifier_v1_destroy(manager, false); +} + +struct wlr_alpha_modifier_v1 *wlr_alpha_modifier_v1_create(struct wl_display *display) { + struct wlr_alpha_modifier_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + manager->global = wl_global_create(display, &wp_alpha_modifier_v1_interface, + ALPHA_MODIFIER_VERSION, NULL, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} + +const struct wlr_alpha_modifier_surface_v1_state *wlr_alpha_modifier_v1_get_surface_state( + struct wlr_surface *wlr_surface) { + struct wlr_alpha_modifier_surface_v1 *surface = surface_from_wlr_surface(wlr_surface); + if (surface == NULL) { + return NULL; + } + return &surface->current; +} diff --git a/3rdparty/wlroots/types/wlr_color_management_v1.c b/3rdparty/wlroots/types/wlr_color_management_v1.c new file mode 100644 index 0000000000..801c9c88a1 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_color_management_v1.c @@ -0,0 +1,1181 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "color-management-v1-protocol.h" +#include "render/color.h" +#include "util/mem.h" +#include "util/global.h" + +#define COLOR_MANAGEMENT_V1_VERSION 2 + +struct wlr_color_management_output_v1 { + struct wl_resource *resource; + struct wlr_output *output; + struct wlr_color_manager_v1 *manager; + struct wl_list link; + + struct wl_listener output_destroy; +}; + +struct wlr_color_management_surface_v1_state { + bool has_image_desc_data; + struct wlr_image_description_v1_data image_desc_data; +}; + +struct wlr_color_management_surface_v1 { + struct wl_resource *resource; + struct wlr_surface *surface; + struct wlr_color_manager_v1 *manager; + + struct wlr_addon addon; + struct wlr_surface_synced synced; + + struct wlr_color_management_surface_v1_state current, pending; +}; + +struct wlr_color_management_surface_feedback_v1 { + struct wl_resource *resource; + struct wlr_surface *surface; + struct wlr_color_manager_v1 *manager; + struct wl_list link; + + struct wlr_image_description_v1_data data; + + struct wl_listener surface_destroy; +}; + +struct wlr_image_description_v1 { + struct wl_resource *resource; + bool get_info_allowed; + struct wlr_image_description_v1_data data; // immutable +}; + +struct wlr_image_description_creator_params_v1 { + struct wl_resource *resource; + struct wlr_color_manager_v1 *manager; + struct wlr_image_description_v1_data data; +}; + +static void resource_handle_destroy(struct wl_client *client, struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static int32_t encode_cie1931_coord(float value) { + return round(value * 1000 * 1000); +} + +static float decode_cie1931_coord(int32_t raw) { + return (float)raw / (1000 * 1000); +} + +static bool cie1931_xy_equal(const struct wlr_color_cie1931_xy *a, + const struct wlr_color_cie1931_xy *b) { + return a->x == b->x && a->y == b->y; +} + +static bool primaries_equal(const struct wlr_color_primaries *a, + const struct wlr_color_primaries *b) { + return cie1931_xy_equal(&a->red, &b->red) && + cie1931_xy_equal(&a->green, &b->green) && + cie1931_xy_equal(&a->blue, &b->blue) && + cie1931_xy_equal(&a->white, &b->white); +} + +static bool img_desc_data_equal(const struct wlr_image_description_v1_data *a, + const struct wlr_image_description_v1_data *b) { + if (a->tf_named != b->tf_named || + a->primaries_named != b->primaries_named || + a->has_mastering_display_primaries != b->has_mastering_display_primaries || + a->has_mastering_luminance != b->has_mastering_luminance || + a->max_cll != b->max_cll || + a->max_fall != b->max_fall) { + return false; + } + if (a->has_mastering_display_primaries && + !primaries_equal(&a->mastering_display_primaries, &b->mastering_display_primaries)) { + return false; + } + if (a->has_mastering_luminance && + (a->mastering_luminance.min != b->mastering_luminance.min || + a->mastering_luminance.max != b->mastering_luminance.max)) { + return false; + } + return true; +} + +static const struct wp_image_description_v1_interface image_desc_impl; + +static struct wlr_image_description_v1 *image_desc_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wp_image_description_v1_interface, &image_desc_impl)); + return wl_resource_get_user_data(resource); +} + +static void image_desc_handle_get_information(struct wl_client *client, + struct wl_resource *image_desc_resource, uint32_t id) { + struct wlr_image_description_v1 *image_desc = image_desc_from_resource(image_desc_resource); + if (image_desc == NULL) { + wl_resource_post_error(image_desc_resource, + WP_IMAGE_DESCRIPTION_V1_ERROR_NOT_READY, + "image description is in failed state"); + return; + } + + if (!image_desc->get_info_allowed) { + wl_resource_post_error(image_desc_resource, + WP_IMAGE_DESCRIPTION_V1_ERROR_NO_INFORMATION, + "get_information not allowed"); + return; + } + + uint32_t version = wl_resource_get_version(image_desc_resource); + struct wl_resource *resource = wl_resource_create(client, + &wp_image_description_info_v1_interface, version, id); + if (!resource) { + wl_client_post_no_memory(client); + return; + } + + struct wlr_color_primaries primaries; + wlr_color_primaries_from_named(&primaries, + wlr_color_manager_v1_primaries_to_wlr(image_desc->data.primaries_named)); + + struct wlr_color_luminances luminances; + wlr_color_transfer_function_get_default_luminance( + wlr_color_manager_v1_transfer_function_to_wlr(image_desc->data.tf_named), &luminances); + + wp_image_description_info_v1_send_primaries_named(resource, image_desc->data.primaries_named); + wp_image_description_info_v1_send_primaries(resource, + encode_cie1931_coord(primaries.red.x), encode_cie1931_coord(primaries.red.y), + encode_cie1931_coord(primaries.green.x), encode_cie1931_coord(primaries.green.y), + encode_cie1931_coord(primaries.blue.x), encode_cie1931_coord(primaries.blue.y), + encode_cie1931_coord(primaries.white.x), encode_cie1931_coord(primaries.white.y)); + wp_image_description_info_v1_send_tf_named(resource, image_desc->data.tf_named); + wp_image_description_info_v1_send_luminances(resource, + round(luminances.min * 10000), round(luminances.max), + round(luminances.reference)); + // TODO: send mastering display primaries and luminances here when we add + // support for features.set_mastering_display_primaries + wp_image_description_info_v1_send_target_primaries(resource, + encode_cie1931_coord(primaries.red.x), encode_cie1931_coord(primaries.red.y), + encode_cie1931_coord(primaries.green.x), encode_cie1931_coord(primaries.green.y), + encode_cie1931_coord(primaries.blue.x), encode_cie1931_coord(primaries.blue.y), + encode_cie1931_coord(primaries.white.x), encode_cie1931_coord(primaries.white.y)); + wp_image_description_info_v1_send_target_luminance(resource, + round(luminances.min * 10000), round(luminances.max)); + // TODO: send target_max_cll and target_max_fall + wp_image_description_info_v1_send_done(resource); + wl_resource_destroy(resource); +} + +static const struct wp_image_description_v1_interface image_desc_impl = { + .destroy = resource_handle_destroy, + .get_information = image_desc_handle_get_information, +}; + +static void image_desc_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_image_description_v1 *image_desc = image_desc_from_resource(resource); + free(image_desc); +} + +static struct wl_resource *image_desc_create_resource( + struct wl_resource *parent_resource, uint32_t id) { + struct wl_client *client = wl_resource_get_client(parent_resource); + uint32_t version = wl_resource_get_version(parent_resource); + return wl_resource_create(client, &wp_image_description_v1_interface, + version, id); +} + +static void image_desc_create_ready(struct wlr_color_manager_v1 *manager, + struct wl_resource *parent_resource, uint32_t id, + const struct wlr_image_description_v1_data *data, + bool get_info_allowed) { + struct wlr_image_description_v1 *image_desc = calloc(1, sizeof(*image_desc)); + if (image_desc == NULL) { + wl_resource_post_no_memory(parent_resource); + return; + } + + image_desc->data = *data; + image_desc->get_info_allowed = get_info_allowed; + + image_desc->resource = image_desc_create_resource(parent_resource, id); + if (!image_desc->resource) { + wl_resource_post_no_memory(parent_resource); + free(image_desc); + return; + } + wl_resource_set_implementation(image_desc->resource, &image_desc_impl, + image_desc, image_desc_handle_resource_destroy); + + uint32_t version = wl_resource_get_version(image_desc->resource); + if (!wp_color_manager_v1_transfer_function_is_valid(data->tf_named, version)) { + wp_image_description_v1_send_failed(image_desc->resource, + WP_IMAGE_DESCRIPTION_V1_CAUSE_LOW_VERSION, "unhandled value for tf_named"); + return; + } + + // TODO: de-duplicate identity + uint64_t identity = ++manager->last_image_desc_identity; + uint32_t identity_hi = identity >> 32; + uint32_t identity_lo = (uint32_t)identity; + + if (version >= WP_IMAGE_DESCRIPTION_V1_READY2_SINCE_VERSION) { + wp_image_description_v1_send_ready2(image_desc->resource, identity_hi, identity_lo); + } else { + wp_image_description_v1_send_ready(image_desc->resource, identity_lo); + } +} + +static void image_desc_create_failed(struct wl_resource *parent_resource, uint32_t id, + enum wp_image_description_v1_cause cause, const char *msg) { + struct wl_resource *resource = image_desc_create_resource(parent_resource, id); + if (resource == NULL) { + wl_resource_post_no_memory(parent_resource); + return; + } + wl_resource_set_implementation(resource, &image_desc_impl, NULL, NULL); + + wp_image_description_v1_send_failed(resource, cause, msg); +} + +static const struct wp_color_management_output_v1_interface cm_output_impl; + +static struct wlr_color_management_output_v1 *cm_output_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wp_color_management_output_v1_interface, &cm_output_impl)); + return wl_resource_get_user_data(resource); +} + +static void cm_output_handle_get_image_description(struct wl_client *client, + struct wl_resource *cm_output_resource, uint32_t id) { + struct wlr_color_management_output_v1 *cm_output = cm_output_from_resource(cm_output_resource); + if (cm_output == NULL) { + image_desc_create_failed(cm_output_resource, id, + WP_IMAGE_DESCRIPTION_V1_CAUSE_NO_OUTPUT, + "output has been destroyed"); + return; + } + + struct wlr_image_description_v1_data data = { + .tf_named = WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_GAMMA22, + .primaries_named = WP_COLOR_MANAGER_V1_PRIMARIES_SRGB, + }; + const struct wlr_output_image_description *image_desc = cm_output->output->image_description; + if (image_desc != NULL) { + data.tf_named = wlr_color_manager_v1_transfer_function_from_wlr(image_desc->transfer_function); + data.primaries_named = wlr_color_manager_v1_primaries_from_wlr(image_desc->primaries); + } + image_desc_create_ready(cm_output->manager, cm_output_resource, id, &data, true); +} + +static const struct wp_color_management_output_v1_interface cm_output_impl = { + .destroy = resource_handle_destroy, + .get_image_description = cm_output_handle_get_image_description, +}; + +static void cm_output_destroy(struct wlr_color_management_output_v1 *cm_output) { + if (cm_output == NULL) { + return; + } + wl_resource_set_user_data(cm_output->resource, NULL); // make inert + wl_list_remove(&cm_output->output_destroy.link); + wl_list_remove(&cm_output->link); + free(cm_output); +} + +static void cm_output_handle_output_destroy(struct wl_listener *listener, void *data) { + struct wlr_color_management_output_v1 *cm_output = wl_container_of(listener, cm_output, output_destroy); + cm_output_destroy(cm_output); +} + +static void cm_output_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_color_management_output_v1 *cm_output = cm_output_from_resource(resource); + cm_output_destroy(cm_output); +} + +static void cm_surface_destroy(struct wlr_color_management_surface_v1 *cm_surface) { + if (cm_surface == NULL) { + return; + } + wl_resource_set_user_data(cm_surface->resource, NULL); // make inert + wlr_surface_synced_finish(&cm_surface->synced); + wlr_addon_finish(&cm_surface->addon); + free(cm_surface); +} + +static const struct wlr_surface_synced_impl cm_surface_synced_impl = { + .state_size = sizeof(struct wlr_color_management_surface_v1_state), +}; + +static void cm_surface_handle_addon_destroy(struct wlr_addon *addon) { + struct wlr_color_management_surface_v1 *cm_surface = wl_container_of(addon, cm_surface, addon); + cm_surface_destroy(cm_surface); +} + +static const struct wlr_addon_interface cm_surface_addon_impl = { + .name = "wlr_color_management_surface_v1", + .destroy = cm_surface_handle_addon_destroy, +}; + +static const struct wp_color_management_surface_v1_interface cm_surface_impl; + +static struct wlr_color_management_surface_v1 *cm_surface_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wp_color_management_surface_v1_interface, &cm_surface_impl)); + return wl_resource_get_user_data(resource); +} + +static void cm_surface_handle_set_image_description(struct wl_client *client, + struct wl_resource *cm_surface_resource, + struct wl_resource *image_desc_resource, uint32_t render_intent) { + struct wlr_color_management_surface_v1 *cm_surface = cm_surface_from_resource(cm_surface_resource); + if (cm_surface == NULL) { + wl_resource_post_error(cm_surface_resource, + WP_COLOR_MANAGEMENT_SURFACE_V1_ERROR_INERT, + "set_image_description cannot be sent on an inert object"); + return; + } + + struct wlr_image_description_v1 *image_desc = image_desc_from_resource(image_desc_resource); + + if (image_desc == NULL) { + wl_resource_post_error(cm_surface_resource, + WP_COLOR_MANAGEMENT_SURFACE_V1_ERROR_IMAGE_DESCRIPTION, + "Image description to be set is invalid"); + return; + } + + bool found = false; + for (size_t i = 0; i < cm_surface->manager->render_intents_len; i++) { + if (cm_surface->manager->render_intents[i] == render_intent) { + found = true; + break; + } + } + if (!found) { + wl_resource_post_error(cm_surface_resource, + WP_COLOR_MANAGEMENT_SURFACE_V1_ERROR_RENDER_INTENT, + "invalid render intent"); + return; + } + + cm_surface->pending.has_image_desc_data = true; + cm_surface->pending.image_desc_data = image_desc->data; +} + +static void cm_surface_handle_unset_image_description(struct wl_client *client, + struct wl_resource *cm_surface_resource) { + struct wlr_color_management_surface_v1 *cm_surface = cm_surface_from_resource(cm_surface_resource); + if (cm_surface == NULL) { + wl_resource_post_error(cm_surface_resource, + WP_COLOR_MANAGEMENT_SURFACE_V1_ERROR_INERT, + "set_image_description cannot be sent on an inert object"); + return; + } + + cm_surface->pending.has_image_desc_data = false; +} + +static const struct wp_color_management_surface_v1_interface cm_surface_impl = { + .destroy = resource_handle_destroy, + .set_image_description = cm_surface_handle_set_image_description, + .unset_image_description = cm_surface_handle_unset_image_description, +}; + +static void cm_surface_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_color_management_surface_v1 *cm_surface = cm_surface_from_resource(resource); + cm_surface_destroy(cm_surface); +} + +static const struct wp_color_management_surface_feedback_v1_interface surface_feedback_impl; + +static struct wlr_color_management_surface_feedback_v1 *surface_feedback_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wp_color_management_surface_feedback_v1_interface, &surface_feedback_impl)); + return wl_resource_get_user_data(resource); +} + +static void surface_feedback_handle_get_preferred(struct wl_client *client, + struct wl_resource *surface_feedback_resource, uint32_t id) { + struct wlr_color_management_surface_feedback_v1 *surface_feedback = + surface_feedback_from_resource(surface_feedback_resource); + if (surface_feedback == NULL) { + wl_resource_post_error(surface_feedback_resource, + WP_COLOR_MANAGEMENT_SURFACE_FEEDBACK_V1_ERROR_INERT, + "get_preferred sent on inert feedback surface"); + return; + } + + image_desc_create_ready(surface_feedback->manager, + surface_feedback_resource, id, &surface_feedback->data, true); +} + +static void surface_feedback_handle_get_preferred_parametric(struct wl_client *client, + struct wl_resource *surface_feedback_resource, uint32_t id) { + struct wlr_color_management_surface_feedback_v1 *surface_feedback = + surface_feedback_from_resource(surface_feedback_resource); + if (surface_feedback == NULL) { + wl_resource_post_error(surface_feedback_resource, + WP_COLOR_MANAGEMENT_SURFACE_FEEDBACK_V1_ERROR_INERT, + "get_preferred_parametric sent on inert feedback surface"); + return; + } + + image_desc_create_ready(surface_feedback->manager, + surface_feedback_resource, id, &surface_feedback->data, true); +} + +static const struct wp_color_management_surface_feedback_v1_interface surface_feedback_impl = { + .destroy = resource_handle_destroy, + .get_preferred = surface_feedback_handle_get_preferred, + .get_preferred_parametric = surface_feedback_handle_get_preferred_parametric, +}; + +static void surface_feedback_destroy(struct wlr_color_management_surface_feedback_v1 *surface_feedback) { + if (surface_feedback == NULL) { + return; + } + wl_resource_set_user_data(surface_feedback->resource, NULL); // make inert + wl_list_remove(&surface_feedback->surface_destroy.link); + wl_list_remove(&surface_feedback->link); + free(surface_feedback); +} + +static void surface_feedback_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_color_management_surface_feedback_v1 *surface_feedback = + surface_feedback_from_resource(resource); + surface_feedback_destroy(surface_feedback); +} + +static void surface_feedback_handle_surface_destroy(struct wl_listener *listener, void *data) { + struct wlr_color_management_surface_feedback_v1 *surface_feedback = + wl_container_of(listener, surface_feedback, surface_destroy); + surface_feedback_destroy(surface_feedback); +} + +static const struct wp_image_description_creator_params_v1_interface image_desc_creator_params_impl; + +static struct wlr_image_description_creator_params_v1 * +image_desc_creator_params_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_image_description_creator_params_v1_interface, + &image_desc_creator_params_impl)); + return wl_resource_get_user_data(resource); +} + +static bool check_mastering_luminance_range(struct wl_resource *params_resource, + const struct wlr_image_description_v1_data *data, + float value, const char *name) { + if (!data->has_mastering_luminance || value == 0) { + return true; + } + + if (value <= data->mastering_luminance.min) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_LUMINANCE, + "%s must be greater than min L of the mastering luminance range", + name); + return false; + } + if (value > data->mastering_luminance.max) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_LUMINANCE, + "%s must be less or equal to max L of the mastering luminance range", + name); + return false; + } + + return true; +} + +static void image_desc_creator_params_handle_create(struct wl_client *client, + struct wl_resource *params_resource, uint32_t id) { + struct wlr_image_description_creator_params_v1 *params = + image_desc_creator_params_from_resource(params_resource); + + if (params->data.tf_named == 0) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INCOMPLETE_SET, + "missing transfer function"); + return; + } + if (params->data.primaries_named == 0) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INCOMPLETE_SET, + "missing primaries"); + return; + } + + if (params->data.max_cll != 0 && params->data.max_fall != 0 && + params->data.max_fall > params->data.max_cll) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_LUMINANCE, + "max_fall must be less or equal to max_cll"); + return; + } + + uint32_t version = wl_resource_get_version(params_resource); + if (version < 2 && + (!check_mastering_luminance_range(params_resource, ¶ms->data, params->data.max_cll, "max_cll") || + !check_mastering_luminance_range(params_resource, ¶ms->data, params->data.max_fall, "max_fall"))) { + return; + } + + // TODO: check that the target color volume is contained within the + // primary color volume + + image_desc_create_ready(params->manager, params_resource, id, ¶ms->data, false); +} + +static void image_desc_creator_params_handle_set_tf_named(struct wl_client *client, + struct wl_resource *params_resource, uint32_t tf) { + struct wlr_image_description_creator_params_v1 *params = + image_desc_creator_params_from_resource(params_resource); + + if (params->data.tf_named != 0) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_ALREADY_SET, + "transfer function already set"); + return; + } + + bool found = false; + for (size_t i = 0; i < params->manager->transfer_functions_len; i++) { + if (params->manager->transfer_functions[i] == tf) { + found = true; + break; + } + } + if (!found) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_TF, + "invalid transfer function"); + return; + } + + params->data.tf_named = tf; +} + +static void image_desc_creator_params_handle_set_tf_power(struct wl_client *client, + struct wl_resource *params_resource, uint32_t eexp) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_UNSUPPORTED_FEATURE, + "set_tf_power is not supported"); +} + +static void image_desc_creator_params_handle_set_primaries_named(struct wl_client *client, + struct wl_resource *params_resource, uint32_t primaries) { + struct wlr_image_description_creator_params_v1 *params = + image_desc_creator_params_from_resource(params_resource); + + if (params->data.primaries_named != 0) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_ALREADY_SET, + "primaries already set"); + return; + } + + bool found = false; + for (size_t i = 0; i < params->manager->primaries_len; i++) { + if (params->manager->primaries[i] == primaries) { + found = true; + break; + } + } + if (!found) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_PRIMARIES_NAMED, + "invalid primaries"); + return; + } + + params->data.primaries_named = primaries; +} + +static void image_desc_creator_params_handle_set_primaries(struct wl_client *client, + struct wl_resource *params_resource, int32_t r_x, int32_t r_y, + int32_t g_x, int32_t g_y, int32_t b_x, int32_t b_y, + int32_t w_x, int32_t w_y) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_UNSUPPORTED_FEATURE, + "set_primaries is not supported"); +} + +static void image_desc_creator_params_handle_set_luminances(struct wl_client *client, + struct wl_resource *params_resource, uint32_t min_lum, + uint32_t max_lum, uint32_t reference_lum) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_UNSUPPORTED_FEATURE, + "set_luminances is not supported"); +} + +static void image_desc_creator_params_handle_set_mastering_display_primaries( + struct wl_client *client, struct wl_resource *params_resource, + int32_t r_x, int32_t r_y, int32_t g_x, int32_t g_y, + int32_t b_x, int32_t b_y, int32_t w_x, int32_t w_y) { + struct wlr_image_description_creator_params_v1 *params = + image_desc_creator_params_from_resource(params_resource); + if (!params->manager->features.set_mastering_display_primaries) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_UNSUPPORTED_FEATURE, + "set_mastering_display_primaries is not supported"); + return; + } + + if (params->data.has_mastering_display_primaries) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_ALREADY_SET, + "mastering display primaries already set"); + return; + } + + params->data.has_mastering_display_primaries = true; + params->data.mastering_display_primaries = (struct wlr_color_primaries){ + .red = { decode_cie1931_coord(r_x), decode_cie1931_coord(r_y) }, + .green = { decode_cie1931_coord(g_x), decode_cie1931_coord(g_y) }, + .blue = { decode_cie1931_coord(b_x), decode_cie1931_coord(b_y) }, + .white = { decode_cie1931_coord(w_x), decode_cie1931_coord(w_y) }, + }; +} + +static void image_desc_creator_params_handle_set_mastering_luminance(struct wl_client *client, + struct wl_resource *params_resource, uint32_t min_lum, uint32_t max_lum) { + struct wlr_image_description_creator_params_v1 *params = + image_desc_creator_params_from_resource(params_resource); + if (!params->manager->features.set_mastering_display_primaries) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_UNSUPPORTED_FEATURE, + "set_mastering_luminance is not supported"); + return; + } + + if (params->data.has_mastering_luminance) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_ALREADY_SET, + "mastering luminance already set"); + return; + } + + params->data.has_mastering_luminance = true; + params->data.mastering_luminance.min = (float)min_lum / 10000; + params->data.mastering_luminance.max = max_lum; + + if (params->data.mastering_luminance.max <= params->data.mastering_luminance.min) { + wl_resource_post_error(params_resource, + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_INVALID_LUMINANCE, + "max luminance must be greater than min luminance"); + return; + } +} + +static void image_desc_creator_params_handle_set_max_cll(struct wl_client *client, + struct wl_resource *params_resource, uint32_t max_cll) { + struct wlr_image_description_creator_params_v1 *params = + image_desc_creator_params_from_resource(params_resource); + params->data.max_cll = max_cll; +} + +static void image_desc_creator_params_handle_set_max_fall(struct wl_client *client, + struct wl_resource *params_resource, uint32_t max_fall) { + struct wlr_image_description_creator_params_v1 *params = + image_desc_creator_params_from_resource(params_resource); + params->data.max_fall = max_fall; +} + +static const struct wp_image_description_creator_params_v1_interface image_desc_creator_params_impl = { + .create = image_desc_creator_params_handle_create, + .set_tf_named = image_desc_creator_params_handle_set_tf_named, + .set_tf_power = image_desc_creator_params_handle_set_tf_power, + .set_primaries_named = image_desc_creator_params_handle_set_primaries_named, + .set_primaries = image_desc_creator_params_handle_set_primaries, + .set_luminances = image_desc_creator_params_handle_set_luminances, + .set_mastering_display_primaries = image_desc_creator_params_handle_set_mastering_display_primaries, + .set_mastering_luminance = image_desc_creator_params_handle_set_mastering_luminance, + .set_max_cll = image_desc_creator_params_handle_set_max_cll, + .set_max_fall = image_desc_creator_params_handle_set_max_fall, +}; + +static void image_desc_creator_params_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_image_description_creator_params_v1 *params = + image_desc_creator_params_from_resource(resource); + free(params); +} + +static const struct wp_color_manager_v1_interface manager_impl; + +static struct wlr_color_manager_v1 *manager_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wp_color_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void manager_handle_get_output(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + struct wl_resource *output_resource) { + struct wlr_color_manager_v1 *manager = manager_from_resource(manager_resource); + struct wlr_output *output = wlr_output_from_resource(output_resource); + + uint32_t version = wl_resource_get_version(manager_resource); + struct wl_resource *cm_output_resource = wl_resource_create(client, + &wp_color_management_output_v1_interface, version, id); + if (!cm_output_resource) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(cm_output_resource, &cm_output_impl, + NULL, cm_output_handle_resource_destroy); + + if (output == NULL) { + return; // leave the wp_color_management_output_v1 resource inert + } + + struct wlr_color_management_output_v1 *cm_output = calloc(1, sizeof(*cm_output)); + if (cm_output == NULL) { + wl_client_post_no_memory(client); + return; + } + + cm_output->resource = cm_output_resource; + cm_output->manager = manager; + cm_output->output = output; + + cm_output->output_destroy.notify = cm_output_handle_output_destroy; + wl_signal_add(&output->events.destroy, &cm_output->output_destroy); + + wl_list_insert(&manager->outputs, &cm_output->link); + wl_resource_set_user_data(cm_output->resource, cm_output); +} + +static struct wlr_color_management_surface_v1 *cm_surface_from_surface(struct wlr_surface *surface) { + struct wlr_addon *addon = wlr_addon_find(&surface->addons, NULL, &cm_surface_addon_impl); + if (addon == NULL) { + return NULL; + } + struct wlr_color_management_surface_v1 *cm_surface = wl_container_of(addon, cm_surface, addon); + return cm_surface; +} + +static void manager_handle_get_surface(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + struct wl_resource *surface_resource) { + struct wlr_color_manager_v1 *manager = manager_from_resource(manager_resource); + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + + if (cm_surface_from_surface(surface) != NULL) { + wl_resource_post_error(manager_resource, + WP_COLOR_MANAGER_V1_ERROR_SURFACE_EXISTS, + "wp_color_management_surface_v1 already constructed for this surface"); + return; + } + + struct wlr_color_management_surface_v1 *cm_surface = calloc(1, sizeof(*cm_surface)); + if (cm_surface == NULL) { + wl_client_post_no_memory(client); + return; + } + + if (!wlr_surface_synced_init(&cm_surface->synced, surface, &cm_surface_synced_impl, + &cm_surface->pending, &cm_surface->current)) { + wl_client_post_no_memory(client); + free(cm_surface); + return; + } + + uint32_t version = wl_resource_get_version(manager_resource); + cm_surface->resource = wl_resource_create(client, + &wp_color_management_surface_v1_interface, version, id); + if (!cm_surface->resource) { + wl_client_post_no_memory(client); + wlr_surface_synced_finish(&cm_surface->synced); + free(cm_surface); + return; + } + wl_resource_set_implementation(cm_surface->resource, &cm_surface_impl, cm_surface, cm_surface_handle_resource_destroy); + + cm_surface->manager = manager; + cm_surface->surface = surface; + + wlr_addon_init(&cm_surface->addon, &surface->addons, NULL, &cm_surface_addon_impl); +} + +static void manager_handle_get_surface_feedback(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + struct wl_resource *surface_resource) { + struct wlr_color_manager_v1 *manager = manager_from_resource(manager_resource); + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + + struct wlr_color_management_surface_feedback_v1 *surface_feedback = + calloc(1, sizeof(*surface_feedback)); + if (surface_feedback == NULL) { + wl_client_post_no_memory(client); + return; + } + + surface_feedback->manager = manager; + + uint32_t version = wl_resource_get_version(manager_resource); + surface_feedback->resource = wl_resource_create(client, + &wp_color_management_surface_feedback_v1_interface, version, id); + if (!surface_feedback->resource) { + wl_client_post_no_memory(client); + free(surface_feedback); + return; + } + wl_resource_set_implementation(surface_feedback->resource, &surface_feedback_impl, + surface_feedback, surface_feedback_handle_resource_destroy); + + surface_feedback->surface = surface; + surface_feedback->data = (struct wlr_image_description_v1_data){ + .tf_named = WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_GAMMA22, + .primaries_named = WP_COLOR_MANAGER_V1_PRIMARIES_SRGB, + }; + + surface_feedback->surface_destroy.notify = surface_feedback_handle_surface_destroy; + wl_signal_add(&surface->events.destroy, &surface_feedback->surface_destroy); + + wl_list_insert(&manager->surface_feedbacks, &surface_feedback->link); +} + +static void manager_handle_create_icc_creator(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id) { + wl_resource_post_error(manager_resource, + WP_COLOR_MANAGER_V1_ERROR_UNSUPPORTED_FEATURE, + "new_icc_creator is not supported"); +} + +static void manager_handle_create_parametric_creator(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id) { + struct wlr_color_manager_v1 *manager = manager_from_resource(manager_resource); + if (!manager->features.parametric) { + wl_resource_post_error(manager_resource, + WP_COLOR_MANAGER_V1_ERROR_UNSUPPORTED_FEATURE, + "new_parametric_creator is not supported"); + return; + } + + struct wlr_image_description_creator_params_v1 *params = calloc(1, sizeof(*params)); + if (params == NULL) { + wl_client_post_no_memory(client); + return; + } + + params->manager = manager; + + uint32_t version = wl_resource_get_version(manager_resource); + params->resource = wl_resource_create(client, + &wp_image_description_creator_params_v1_interface, version, id); + if (!params->resource) { + wl_client_post_no_memory(client); + free(params); + return; + } + wl_resource_set_implementation(params->resource, &image_desc_creator_params_impl, + params, image_desc_creator_params_handle_resource_destroy); +} + +static void manager_handle_create_windows_scrgb(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id) { + wl_resource_post_error(manager_resource, + WP_COLOR_MANAGER_V1_ERROR_UNSUPPORTED_FEATURE, + "get_windows_scrgb is not supported"); +} + +static const struct wp_color_manager_v1_interface manager_impl = { + .destroy = resource_handle_destroy, + .get_output = manager_handle_get_output, + .get_surface = manager_handle_get_surface, + .get_surface_feedback = manager_handle_get_surface_feedback, + .create_icc_creator = manager_handle_create_icc_creator, + .create_parametric_creator = manager_handle_create_parametric_creator, + .create_windows_scrgb = manager_handle_create_windows_scrgb, +}; + +static void manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_color_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &wp_color_manager_v1_interface, version, id); + if (!resource) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, manager, NULL); + wl_list_init(wl_resource_get_link(resource)); + if (manager == NULL) { + return; + } + + + const bool features[] = { + [WP_COLOR_MANAGER_V1_FEATURE_ICC_V2_V4] = manager->features.icc_v2_v4, + [WP_COLOR_MANAGER_V1_FEATURE_PARAMETRIC] = manager->features.parametric, + [WP_COLOR_MANAGER_V1_FEATURE_SET_PRIMARIES] = manager->features.set_primaries, + [WP_COLOR_MANAGER_V1_FEATURE_SET_TF_POWER] = manager->features.set_tf_power, + [WP_COLOR_MANAGER_V1_FEATURE_SET_LUMINANCES] = manager->features.set_luminances, + [WP_COLOR_MANAGER_V1_FEATURE_SET_MASTERING_DISPLAY_PRIMARIES] = manager->features.set_mastering_display_primaries, + [WP_COLOR_MANAGER_V1_FEATURE_EXTENDED_TARGET_VOLUME] = manager->features.extended_target_volume, + [WP_COLOR_MANAGER_V1_FEATURE_WINDOWS_SCRGB] = manager->features.windows_scrgb, + }; + + for (uint32_t i = 0; i < sizeof(features) / sizeof(features[0]); i++) { + if (features[i]) { + wp_color_manager_v1_send_supported_feature(resource, i); + } + } + for (size_t i = 0; i < manager->render_intents_len; i++) { + wp_color_manager_v1_send_supported_intent(resource, + manager->render_intents[i]); + } + for (size_t i = 0; i < manager->transfer_functions_len; i++) { + enum wp_color_manager_v1_transfer_function tf = manager->transfer_functions[i]; + if (!wp_color_manager_v1_transfer_function_is_valid(tf, version)) { + continue; + } + wp_color_manager_v1_send_supported_tf_named(resource, tf); + } + for (size_t i = 0; i < manager->primaries_len; i++) { + wp_color_manager_v1_send_supported_primaries_named(resource, + manager->primaries[i]); + } + + wp_color_manager_v1_send_done(resource); +} + +static void color_manager_v1_destroy(struct wlr_color_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, NULL); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager->render_intents); + free(manager->transfer_functions); + free(manager->primaries); + free(manager); +} + +void wlr_color_manager_v1_destroy(struct wlr_color_manager_v1 *manager, bool destroy_global_safe) { + color_manager_v1_destroy(manager, destroy_global_safe); +} + +static void manager_handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_color_manager_v1 *manager = wl_container_of(listener, manager, display_destroy); + color_manager_v1_destroy(manager, false); +} + +struct wlr_color_manager_v1 *wlr_color_manager_v1_create(struct wl_display *display, + uint32_t version, const struct wlr_color_manager_v1_options *options) { + assert(version <= COLOR_MANAGEMENT_V1_VERSION); + + bool has_perceptual_render_intent = false; + for (size_t i = 0; i < options->render_intents_len; i++) { + if (options->render_intents[i] == WP_COLOR_MANAGER_V1_RENDER_INTENT_PERCEPTUAL) { + has_perceptual_render_intent = true; + } + } + assert(has_perceptual_render_intent); + + for (size_t i = 0; i < options->transfer_functions_len; i++) { + assert(options->transfer_functions[i] != WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_SRGB); + } + + // TODO: add support for all of these features + assert(!options->features.icc_v2_v4); + assert(!options->features.set_primaries); + assert(!options->features.set_tf_power); + assert(!options->features.set_luminances); + assert(!options->features.extended_target_volume); + assert(!options->features.windows_scrgb); + + struct wlr_color_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + manager->features = options->features; + + bool ok = + memdup(&manager->render_intents, options->render_intents, sizeof(options->render_intents[0]) * options->render_intents_len) && + memdup(&manager->transfer_functions, options->transfer_functions, sizeof(options->transfer_functions[0]) * options->transfer_functions_len) && + memdup(&manager->primaries, options->primaries, sizeof(options->primaries[0]) * options->primaries_len); + if (!ok) { + goto err_options; + } + + manager->render_intents_len = options->render_intents_len; + manager->transfer_functions_len = options->transfer_functions_len; + manager->primaries_len = options->primaries_len; + + wl_signal_init(&manager->events.destroy); + wl_list_init(&manager->outputs); + wl_list_init(&manager->surface_feedbacks); + + manager->global = wl_global_create(display, &wp_color_manager_v1_interface, + version, manager, manager_bind); + if (manager->global == NULL) { + goto err_options; + } + + manager->display_destroy.notify = manager_handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; + +err_options: + free(manager->render_intents); + free(manager->transfer_functions); + free(manager->primaries); + free(manager); + return NULL; +} + +const struct wlr_image_description_v1_data * +wlr_surface_get_image_description_v1_data(struct wlr_surface *surface) { + struct wlr_color_management_surface_v1 *cm_surface = cm_surface_from_surface(surface); + if (cm_surface == NULL || !cm_surface->current.has_image_desc_data) { + return NULL; + } + return &cm_surface->current.image_desc_data; +} + +void wlr_color_manager_v1_set_surface_preferred_image_description( + struct wlr_color_manager_v1 *manager, struct wlr_surface *surface, + const struct wlr_image_description_v1_data *data) { + // TODO: de-duplicate identity + uint64_t identity = ++manager->last_image_desc_identity; + uint32_t identity_hi = identity >> 32; + uint32_t identity_lo = (uint32_t)identity; + + struct wlr_color_management_surface_feedback_v1 *surface_feedback; + wl_list_for_each(surface_feedback, &manager->surface_feedbacks, link) { + if (surface_feedback->surface != surface || + img_desc_data_equal(&surface_feedback->data, data)) { + continue; + } + + surface_feedback->data = *data; + + uint32_t version = wl_resource_get_version(surface_feedback->resource); + if (version >= WP_COLOR_MANAGEMENT_SURFACE_FEEDBACK_V1_PREFERRED_CHANGED2_SINCE_VERSION) { + wp_color_management_surface_feedback_v1_send_preferred_changed2( + surface_feedback->resource, identity_hi, identity_lo); + } else { + wp_color_management_surface_feedback_v1_send_preferred_changed( + surface_feedback->resource, identity_lo); + } + } +} + +enum wlr_color_transfer_function +wlr_color_manager_v1_transfer_function_to_wlr(enum wp_color_manager_v1_transfer_function tf) { + switch (tf) { + case WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_COMPOUND_POWER_2_4: + return WLR_COLOR_TRANSFER_FUNCTION_SRGB; + case WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_ST2084_PQ: + return WLR_COLOR_TRANSFER_FUNCTION_ST2084_PQ; + case WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_EXT_LINEAR: + return WLR_COLOR_TRANSFER_FUNCTION_EXT_LINEAR; + case WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_GAMMA22: + return WLR_COLOR_TRANSFER_FUNCTION_GAMMA22; + case WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_BT1886: + return WLR_COLOR_TRANSFER_FUNCTION_BT1886; + default: + abort(); + } +} + +enum wp_color_manager_v1_transfer_function +wlr_color_manager_v1_transfer_function_from_wlr(enum wlr_color_transfer_function tf) { + switch (tf) { + case WLR_COLOR_TRANSFER_FUNCTION_SRGB: + return WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_COMPOUND_POWER_2_4; + case WLR_COLOR_TRANSFER_FUNCTION_ST2084_PQ: + return WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_ST2084_PQ; + case WLR_COLOR_TRANSFER_FUNCTION_EXT_LINEAR: + return WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_EXT_LINEAR; + case WLR_COLOR_TRANSFER_FUNCTION_GAMMA22: + return WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_GAMMA22; + case WLR_COLOR_TRANSFER_FUNCTION_BT1886: + return WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_BT1886; + } + abort(); +} + +enum wlr_color_named_primaries +wlr_color_manager_v1_primaries_to_wlr(enum wp_color_manager_v1_primaries primaries) { + switch (primaries) { + case WP_COLOR_MANAGER_V1_PRIMARIES_SRGB: + return WLR_COLOR_NAMED_PRIMARIES_SRGB; + case WP_COLOR_MANAGER_V1_PRIMARIES_BT2020: + return WLR_COLOR_NAMED_PRIMARIES_BT2020; + default: + abort(); + } +} + +enum wp_color_manager_v1_primaries +wlr_color_manager_v1_primaries_from_wlr(enum wlr_color_named_primaries primaries) { + switch (primaries) { + case WLR_COLOR_NAMED_PRIMARIES_SRGB: + return WP_COLOR_MANAGER_V1_PRIMARIES_SRGB; + case WLR_COLOR_NAMED_PRIMARIES_BT2020: + return WP_COLOR_MANAGER_V1_PRIMARIES_BT2020; + } + abort(); +} + +enum wp_color_manager_v1_transfer_function * +wlr_color_manager_v1_transfer_function_list_from_renderer(struct wlr_renderer *renderer, size_t *len) { + if (!renderer->features.input_color_transform) { + *len = 0; + return NULL; + } + + const enum wp_color_manager_v1_transfer_function list[] = { + WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_GAMMA22, + WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_ST2084_PQ, + WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_EXT_LINEAR, + WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_BT1886, + WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_COMPOUND_POWER_2_4, + }; + + enum wp_color_manager_v1_transfer_function *out = NULL; + if (!memdup(&out, list, sizeof(list))) { + *len = 0; + return NULL; + } + + *len = sizeof(list) / sizeof(list[0]); + return out; +} + +enum wp_color_manager_v1_primaries * +wlr_color_manager_v1_primaries_list_from_renderer(struct wlr_renderer *renderer, size_t *len) { + if (!renderer->features.input_color_transform) { + *len = 0; + return NULL; + } + + const enum wp_color_manager_v1_primaries list[] = { + WP_COLOR_MANAGER_V1_PRIMARIES_SRGB, + WP_COLOR_MANAGER_V1_PRIMARIES_BT2020, + }; + + enum wp_color_manager_v1_primaries *out = NULL; + if (!memdup(&out, list, sizeof(list))) { + *len = 0; + return NULL; + } + + *len = sizeof(list) / sizeof(list[0]); + return out; +} diff --git a/3rdparty/wlroots/types/wlr_color_representation_v1.c b/3rdparty/wlroots/types/wlr_color_representation_v1.c new file mode 100644 index 0000000000..eb62950e37 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_color_representation_v1.c @@ -0,0 +1,527 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "color-representation-v1-protocol.h" +#include "render/pixel_format.h" +#include "types/wlr_buffer.h" +#include "util/mem.h" +#include "util/global.h" + +#define WP_COLOR_REPRESENTATION_VERSION 1 + +enum wlr_alpha_mode wlr_color_representation_v1_alpha_mode_to_wlr( + enum wp_color_representation_surface_v1_alpha_mode wp_val) { + switch (wp_val) { + case WP_COLOR_REPRESENTATION_SURFACE_V1_ALPHA_MODE_PREMULTIPLIED_ELECTRICAL: + return WLR_COLOR_ALPHA_MODE_PREMULTIPLIED_ELECTRICAL; + case WP_COLOR_REPRESENTATION_SURFACE_V1_ALPHA_MODE_PREMULTIPLIED_OPTICAL: + return WLR_COLOR_ALPHA_MODE_PREMULTIPLIED_OPTICAL; + case WP_COLOR_REPRESENTATION_SURFACE_V1_ALPHA_MODE_STRAIGHT: + return WLR_COLOR_ALPHA_MODE_STRAIGHT; + } + abort(); // unreachable +} + +enum wlr_color_encoding wlr_color_representation_v1_color_encoding_to_wlr( + enum wp_color_representation_surface_v1_coefficients wp_val) { + switch (wp_val) { + case WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_IDENTITY: + return WLR_COLOR_ENCODING_IDENTITY; + case WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_BT709: + return WLR_COLOR_ENCODING_BT709; + case WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_FCC: + return WLR_COLOR_ENCODING_FCC; + case WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_BT601: + return WLR_COLOR_ENCODING_BT601; + case WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_SMPTE240: + return WLR_COLOR_ENCODING_SMPTE240; + case WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_BT2020: + return WLR_COLOR_ENCODING_BT2020; + case WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_BT2020_CL: + return WLR_COLOR_ENCODING_BT2020_CL; + case WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_ICTCP: + return WLR_COLOR_ENCODING_ICTCP; + } + abort(); // unreachable +} + +enum wlr_color_range wlr_color_representation_v1_color_range_to_wlr( + enum wp_color_representation_surface_v1_range wp_val) { + switch (wp_val) { + case WP_COLOR_REPRESENTATION_SURFACE_V1_RANGE_LIMITED: + return WLR_COLOR_RANGE_LIMITED; + case WP_COLOR_REPRESENTATION_SURFACE_V1_RANGE_FULL: + return WLR_COLOR_RANGE_FULL; + } + abort(); // unreachable +} + +enum wlr_color_chroma_location wlr_color_representation_v1_chroma_location_to_wlr( + enum wp_color_representation_surface_v1_chroma_location wp_val) { + switch (wp_val) { + case WP_COLOR_REPRESENTATION_SURFACE_V1_CHROMA_LOCATION_TYPE_0: + return WLR_COLOR_CHROMA_LOCATION_TYPE0; + case WP_COLOR_REPRESENTATION_SURFACE_V1_CHROMA_LOCATION_TYPE_1: + return WLR_COLOR_CHROMA_LOCATION_TYPE1; + case WP_COLOR_REPRESENTATION_SURFACE_V1_CHROMA_LOCATION_TYPE_2: + return WLR_COLOR_CHROMA_LOCATION_TYPE2; + case WP_COLOR_REPRESENTATION_SURFACE_V1_CHROMA_LOCATION_TYPE_3: + return WLR_COLOR_CHROMA_LOCATION_TYPE3; + case WP_COLOR_REPRESENTATION_SURFACE_V1_CHROMA_LOCATION_TYPE_4: + return WLR_COLOR_CHROMA_LOCATION_TYPE4; + case WP_COLOR_REPRESENTATION_SURFACE_V1_CHROMA_LOCATION_TYPE_5: + return WLR_COLOR_CHROMA_LOCATION_TYPE5; + } + abort(); // unreachable +} + +struct wlr_color_representation_v1 { + struct wl_resource *resource; + struct wlr_surface *surface; + + struct wlr_color_representation_manager_v1 *manager; + + // Associate the wlr_color_representation_v1 with a wlr_surface + struct wlr_addon addon; + + struct wlr_surface_synced synced; + struct wlr_color_representation_v1_surface_state pending, current; +}; + +static const struct wp_color_representation_surface_v1_interface color_repr_impl; + +static struct wlr_color_representation_v1 *color_repr_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_color_representation_surface_v1_interface, + &color_repr_impl)); + return wl_resource_get_user_data(resource); +} + +static void color_repr_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + // Actual destroying is done by the resource-destroy handler + wl_resource_destroy(resource); +} + +static void color_repr_handle_set_alpha_mode(struct wl_client *client, + struct wl_resource *resource, uint32_t alpha_mode) { + struct wlr_color_representation_v1 *color_repr = + color_repr_from_resource(resource); + if (color_repr == NULL) { + wl_resource_post_error(resource, WP_COLOR_REPRESENTATION_SURFACE_V1_ERROR_INERT, + "Associated surface has been destroyed, object is inert"); + return; + } + + bool found = false; + for (size_t i = 0; i < color_repr->manager->supported_alpha_modes_len; i++) { + if (color_repr->manager->supported_alpha_modes[i] == alpha_mode) { + found = true; + break; + } + } + if (!found) { + wl_resource_post_error(resource, + WP_COLOR_REPRESENTATION_SURFACE_V1_ERROR_ALPHA_MODE, + "Unsupported alpha mode"); + return; + } + + color_repr->pending.alpha_mode = alpha_mode; +} + +static void color_repr_handle_set_coefficients_and_range(struct wl_client *client, + struct wl_resource *resource, uint32_t coefficients, + uint32_t range) { + struct wlr_color_representation_v1 *color_repr = + color_repr_from_resource(resource); + if (color_repr == NULL) { + wl_resource_post_error(resource, WP_COLOR_REPRESENTATION_SURFACE_V1_ERROR_INERT, + "Associated surface has been destroyed, object is inert"); + return; + } + + bool found = false; + for (size_t i = 0; i < color_repr->manager->supported_coeffs_and_ranges_len; i++) { + struct wlr_color_representation_v1_coeffs_and_range *supported = + &color_repr->manager->supported_coeffs_and_ranges[i]; + if (supported->coeffs == coefficients && supported->range == range) { + found = true; + break; + } + } + if (!found) { + wl_resource_post_error(resource, + WP_COLOR_REPRESENTATION_SURFACE_V1_ERROR_COEFFICIENTS, + "Unsupported coefficients/range pair"); + return; + } + + color_repr->pending.coefficients = coefficients; + color_repr->pending.range = range; +} + +static void color_repr_handle_set_chroma_location(struct wl_client *client, + struct wl_resource *resource, uint32_t chroma_location) { + struct wlr_color_representation_v1 *color_repr = + color_repr_from_resource(resource); + if (color_repr == NULL) { + wl_resource_post_error(resource, WP_COLOR_REPRESENTATION_SURFACE_V1_ERROR_INERT, + "Associated surface has been destroyed, object is inert"); + return; + } + + uint32_t version = wl_resource_get_version(resource); + if (!wp_color_representation_surface_v1_chroma_location_is_valid( + version, chroma_location)) { + wl_resource_post_error(resource, WP_COLOR_REPRESENTATION_SURFACE_V1_ERROR_CHROMA_LOCATION, + "Chroma location is not a valid enum value"); + return; + } + + // In this protocol there's no concept of supported chroma locations + // from a client point-of-view. The compositor should just ignore any + // chroma locations it doesn't know what to do with. + + color_repr->pending.chroma_location = chroma_location; +} + +static const struct wp_color_representation_surface_v1_interface color_repr_impl = { + .destroy = color_repr_handle_destroy, + .set_alpha_mode = color_repr_handle_set_alpha_mode, + .set_coefficients_and_range = color_repr_handle_set_coefficients_and_range, + .set_chroma_location = color_repr_handle_set_chroma_location, +}; + +static void color_repr_destroy(struct wlr_color_representation_v1 *color_repr) { + if (color_repr == NULL) { + return; + } + wlr_surface_synced_finish(&color_repr->synced); + wlr_addon_finish(&color_repr->addon); + wl_resource_set_user_data(color_repr->resource, NULL); + free(color_repr); +} + +static void color_repr_addon_destroy(struct wlr_addon *addon) { + struct wlr_color_representation_v1 *color_repr = + wl_container_of(addon, color_repr, addon); + color_repr_destroy(color_repr); +} + +static const struct wlr_addon_interface surface_addon_impl = { + .name = "wlr_color_representation_v1", + .destroy = color_repr_addon_destroy, +}; + +static void color_repr_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_color_representation_v1 *color_repr = + color_repr_from_resource(resource); + color_repr_destroy(color_repr); +} + +static void color_repr_manager_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + // Actual destroying is done by the resource-destroy handler + wl_resource_destroy(resource); +} + +static void surface_synced_commit(struct wlr_surface_synced *synced) { + struct wlr_color_representation_v1 *color_repr = wl_container_of(synced, color_repr, synced); + + if (color_repr->current.coefficients == 0 && color_repr->current.range == 0) { + return; + } + + uint32_t drm_format = DRM_FORMAT_INVALID; + if (color_repr->surface->buffer){ + drm_format = buffer_get_drm_format(&color_repr->surface->buffer->base); + } + if (drm_format == DRM_FORMAT_INVALID) { + return; + } + bool is_ycbcr = pixel_format_is_ycbcr(drm_format); + + bool is_identity_full = + color_repr->current.coefficients == WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_IDENTITY && + color_repr->current.range == WP_COLOR_REPRESENTATION_SURFACE_V1_RANGE_FULL; + + if (is_ycbcr) { + if (is_identity_full) { + wl_resource_post_error(color_repr->resource, + WP_COLOR_REPRESENTATION_SURFACE_V1_ERROR_PIXEL_FORMAT, + "unexpected encoding/range for yuv"); + } + } else /* rgb */ { + if (!is_identity_full) { + wl_resource_post_error(color_repr->resource, + WP_COLOR_REPRESENTATION_SURFACE_V1_ERROR_PIXEL_FORMAT, + "unexpected encoding/range for rgb"); + } + } +} + +static const struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(struct wlr_color_representation_v1_surface_state), + .commit = surface_synced_commit +}; + +static struct wlr_color_representation_v1 *color_repr_from_surface( + struct wlr_surface *surface) { + struct wlr_addon *addon = wlr_addon_find(&surface->addons, NULL, &surface_addon_impl); + if (addon == NULL) { + return NULL; + } + struct wlr_color_representation_v1 *color_repr = wl_container_of(addon, color_repr, addon); + return color_repr; +} + +static const struct wp_color_representation_manager_v1_interface color_repr_manager_impl; + +static struct wlr_color_representation_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_color_representation_manager_v1_interface, + &color_repr_manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void color_repr_manager_handle_get_surface(struct wl_client *client, + struct wl_resource *manager_resource, + uint32_t color_repr_id, + struct wl_resource *surface_resource) { + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + + // Check if there's already a color-representation attached to + // this surface + if (color_repr_from_surface(surface) != NULL) { + wl_resource_post_error(manager_resource, + WP_COLOR_REPRESENTATION_MANAGER_V1_ERROR_SURFACE_EXISTS, + "wp_color_representation_surface_v1 already exists for this surface"); + return; + } + + struct wlr_color_representation_v1 *color_repr = calloc(1, sizeof(*color_repr)); + if (!color_repr) { + wl_resource_post_no_memory(manager_resource); + return; + } + + color_repr->manager = manager_from_resource(manager_resource); + color_repr->surface = surface; + + if (!wlr_surface_synced_init(&color_repr->synced, surface, + &surface_synced_impl, &color_repr->pending, &color_repr->current)) { + free(color_repr); + wl_resource_post_no_memory(manager_resource); + return; + } + + uint32_t version = wl_resource_get_version(manager_resource); + color_repr->resource = wl_resource_create(client, + &wp_color_representation_surface_v1_interface, version, color_repr_id); + if (color_repr->resource == NULL) { + wlr_surface_synced_finish(&color_repr->synced); + free(color_repr); + wl_resource_post_no_memory(manager_resource); + return; + } + wl_resource_set_implementation(color_repr->resource, + &color_repr_impl, color_repr, color_repr_handle_resource_destroy); + + wlr_addon_init(&color_repr->addon, &surface->addons, NULL, &surface_addon_impl); +} + +static const struct wp_color_representation_manager_v1_interface color_repr_manager_impl = { + .destroy = color_repr_manager_handle_destroy, + .get_surface = color_repr_manager_handle_get_surface, +}; + +static void send_supported(struct wlr_color_representation_manager_v1 *manager, + struct wl_resource *resource) { + for (size_t i = 0; i < manager->supported_alpha_modes_len; i++) { + wp_color_representation_manager_v1_send_supported_alpha_mode( + resource, manager->supported_alpha_modes[i]); + } + + for (size_t i = 0; i < manager->supported_coeffs_and_ranges_len; i++) { + struct wlr_color_representation_v1_coeffs_and_range *supported = + &manager->supported_coeffs_and_ranges[i]; + wp_color_representation_manager_v1_send_supported_coefficients_and_ranges( + resource, supported->coeffs, supported->range); + } + + // Note that there is no event for supported chroma locations in the + // v1 protocol. + + wp_color_representation_manager_v1_send_done(resource); +} + +static void manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_color_representation_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &wp_color_representation_manager_v1_interface, + version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &color_repr_manager_impl, manager, NULL); + wl_list_init(wl_resource_get_link(resource)); + if (manager == NULL) { + return; + } + + + send_supported(manager, resource); +} + +static void color_representation_manager_v1_destroy( + struct wlr_color_representation_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, NULL); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager->supported_alpha_modes); + free(manager->supported_coeffs_and_ranges); + free(manager); +} + +void wlr_color_representation_manager_v1_destroy( + struct wlr_color_representation_manager_v1 *manager, bool destroy_global_safe) { + color_representation_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_color_representation_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + color_representation_manager_v1_destroy(manager, false); +} + +struct wlr_color_representation_manager_v1 *wlr_color_representation_manager_v1_create( + struct wl_display *display, uint32_t version, + const struct wlr_color_representation_v1_options *options) { + assert(version <= WP_COLOR_REPRESENTATION_VERSION); + + struct wlr_color_representation_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + bool ok = true; + ok &= memdup(&manager->supported_alpha_modes, + options->supported_alpha_modes, + sizeof(options->supported_alpha_modes[0]) * options->supported_alpha_modes_len); + manager->supported_alpha_modes_len = options->supported_alpha_modes_len; + ok &= memdup(&manager->supported_coeffs_and_ranges, + options->supported_coeffs_and_ranges, + sizeof(options->supported_coeffs_and_ranges[0]) * options->supported_coeffs_and_ranges_len); + manager->supported_coeffs_and_ranges_len = options->supported_coeffs_and_ranges_len; + if (!ok) { + goto err_options; + } + + manager->global = wl_global_create(display, + &wp_color_representation_manager_v1_interface, + version, manager, manager_bind); + if (manager->global == NULL) { + goto err_options; + } + + wl_signal_init(&manager->events.destroy); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; + +err_options: + free(manager->supported_alpha_modes); + free(manager->supported_coeffs_and_ranges); + free(manager); + return NULL; +} + +static const enum wp_color_representation_surface_v1_coefficients coefficients[] = { + WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_IDENTITY, + WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_BT709, + WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_FCC, + WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_BT601, + WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_SMPTE240, + WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_BT2020, + WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_BT2020_CL, + WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_ICTCP, +}; + +#define COEFFICIENTS_LEN (sizeof(coefficients) / sizeof(coefficients[0])) + +static const enum wp_color_representation_surface_v1_range ranges[] = { + WP_COLOR_REPRESENTATION_SURFACE_V1_RANGE_LIMITED, + WP_COLOR_REPRESENTATION_SURFACE_V1_RANGE_FULL, +}; + +#define RANGES_LEN (sizeof(ranges) / sizeof(ranges[0])) + +struct wlr_color_representation_manager_v1 *wlr_color_representation_manager_v1_create_with_renderer( + struct wl_display *display, uint32_t version, struct wlr_renderer *renderer) { + const enum wp_color_representation_surface_v1_alpha_mode alpha_modes[] = { + WP_COLOR_REPRESENTATION_SURFACE_V1_ALPHA_MODE_PREMULTIPLIED_ELECTRICAL, + }; + + struct wlr_color_representation_v1_coeffs_and_range coeffs_and_ranges[COEFFICIENTS_LEN * RANGES_LEN]; + size_t coeffs_and_ranges_len = 0; + coeffs_and_ranges[coeffs_and_ranges_len++] = (struct wlr_color_representation_v1_coeffs_and_range){ + .coeffs = WP_COLOR_REPRESENTATION_SURFACE_V1_COEFFICIENTS_IDENTITY, + .range = WP_COLOR_REPRESENTATION_SURFACE_V1_RANGE_FULL, + }; + for (size_t i = 0; i < COEFFICIENTS_LEN; i++) { + enum wp_color_representation_surface_v1_coefficients coeffs = coefficients[i]; + enum wlr_color_encoding enc = wlr_color_representation_v1_color_encoding_to_wlr(coeffs); + if (!(renderer->color_encodings & enc)) { + continue; + } + for (size_t j = 0; j < RANGES_LEN; j++) { + coeffs_and_ranges[coeffs_and_ranges_len] = (struct wlr_color_representation_v1_coeffs_and_range){ + .coeffs = coeffs, + .range = ranges[j], + }; + coeffs_and_ranges_len++; + } + } + + const struct wlr_color_representation_v1_options options = { + .supported_alpha_modes = alpha_modes, + .supported_alpha_modes_len = sizeof(alpha_modes) / sizeof(alpha_modes[0]), + .supported_coeffs_and_ranges = coeffs_and_ranges, + .supported_coeffs_and_ranges_len = coeffs_and_ranges_len, + }; + return wlr_color_representation_manager_v1_create(display, version, &options); +} + +const struct wlr_color_representation_v1_surface_state *wlr_color_representation_v1_get_surface_state( + struct wlr_surface *surface) { + struct wlr_color_representation_v1 *color_repr = color_repr_from_surface(surface); + if (color_repr == NULL) { + return NULL; + } + return &color_repr->current; +} diff --git a/3rdparty/wlroots/types/wlr_compositor.c b/3rdparty/wlroots/types/wlr_compositor.c new file mode 100644 index 0000000000..274b9c9f9a --- /dev/null +++ b/3rdparty/wlroots/types/wlr_compositor.c @@ -0,0 +1,1545 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_buffer.h" +#include "types/wlr_region.h" +#include "types/wlr_subcompositor.h" +#include "util/array.h" +#include "util/time.h" +#include "util/global.h" + +#define COMPOSITOR_VERSION 6 +#define CALLBACK_VERSION 1 + +static int min(int fst, int snd) { + if (fst < snd) { + return fst; + } else { + return snd; + } +} + +static int max(int fst, int snd) { + if (fst > snd) { + return fst; + } else { + return snd; + } +} + +static void set_pending_buffer_resource(struct wlr_surface *surface, + struct wl_resource *resource) { + wl_list_remove(&surface->pending_buffer_resource_destroy.link); + surface->pending_buffer_resource = resource; + if (resource != NULL) { + wl_resource_add_destroy_listener(resource, &surface->pending_buffer_resource_destroy); + } else { + wl_list_init(&surface->pending_buffer_resource_destroy.link); + } +} + +static void pending_buffer_resource_handle_destroy(struct wl_listener *listener, void *data) { + struct wlr_surface *surface = + wl_container_of(listener, surface, pending_buffer_resource_destroy); + + set_pending_buffer_resource(surface, NULL); +} + +static void surface_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_surface *surface = wlr_surface_from_resource(resource); + if (surface->role_resource != NULL) { + wl_resource_post_error(resource, + WL_SURFACE_ERROR_DEFUNCT_ROLE_OBJECT, + "surface was destroyed before its role object"); + return; + } + wl_resource_destroy(resource); +} + +static void surface_handle_attach(struct wl_client *client, + struct wl_resource *resource, + struct wl_resource *buffer_resource, int32_t dx, int32_t dy) { + struct wlr_surface *surface = wlr_surface_from_resource(resource); + + if (wl_resource_get_version(resource) >= WL_SURFACE_OFFSET_SINCE_VERSION && + (dx != 0 || dy != 0)) { + wl_resource_post_error(resource, WL_SURFACE_ERROR_INVALID_OFFSET, + "Offset must be zero on wl_surface.attach version >= %"PRIu32, + WL_SURFACE_OFFSET_SINCE_VERSION); + return; + } + + surface->pending.committed |= WLR_SURFACE_STATE_BUFFER; + set_pending_buffer_resource(surface, buffer_resource); + + if (wl_resource_get_version(resource) < WL_SURFACE_OFFSET_SINCE_VERSION) { + surface->pending.committed |= WLR_SURFACE_STATE_OFFSET; + surface->pending.dx = dx; + surface->pending.dy = dy; + } +} + +static void surface_handle_damage(struct wl_client *client, + struct wl_resource *resource, + int32_t x, int32_t y, int32_t width, int32_t height) { + struct wlr_surface *surface = wlr_surface_from_resource(resource); + if (width < 0 || height < 0) { + return; + } + surface->pending.committed |= WLR_SURFACE_STATE_SURFACE_DAMAGE; + pixman_region32_union_rect(&surface->pending.surface_damage, + &surface->pending.surface_damage, + x, y, width, height); +} + +static void callback_handle_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void surface_handle_frame(struct wl_client *client, + struct wl_resource *resource, uint32_t callback) { + struct wlr_surface *surface = wlr_surface_from_resource(resource); + + struct wl_resource *callback_resource = wl_resource_create(client, + &wl_callback_interface, CALLBACK_VERSION, callback); + if (callback_resource == NULL) { + wl_resource_post_no_memory(resource); + return; + } + wl_resource_set_implementation(callback_resource, NULL, NULL, + callback_handle_resource_destroy); + + wl_list_insert(surface->pending.frame_callback_list.prev, + wl_resource_get_link(callback_resource)); + + surface->pending.committed |= WLR_SURFACE_STATE_FRAME_CALLBACK_LIST; +} + +static void surface_handle_set_opaque_region(struct wl_client *client, + struct wl_resource *resource, + struct wl_resource *region_resource) { + struct wlr_surface *surface = wlr_surface_from_resource(resource); + surface->pending.committed |= WLR_SURFACE_STATE_OPAQUE_REGION; + if (region_resource) { + const pixman_region32_t *region = wlr_region_from_resource(region_resource); + pixman_region32_copy(&surface->pending.opaque, region); + } else { + pixman_region32_clear(&surface->pending.opaque); + } +} + +static void surface_handle_set_input_region(struct wl_client *client, + struct wl_resource *resource, + struct wl_resource *region_resource) { + struct wlr_surface *surface = wlr_surface_from_resource(resource); + surface->pending.committed |= WLR_SURFACE_STATE_INPUT_REGION; + if (region_resource) { + const pixman_region32_t *region = wlr_region_from_resource(region_resource); + pixman_region32_copy(&surface->pending.input, region); + } else { + pixman_region32_fini(&surface->pending.input); + pixman_region32_init_rect(&surface->pending.input, + INT32_MIN, INT32_MIN, UINT32_MAX, UINT32_MAX); + } +} + +static void surface_state_transformed_buffer_size(struct wlr_surface_state *state, + int *width, int *height) { + *width = state->buffer_width; + *height = state->buffer_height; + wlr_output_transform_coords(state->transform, width, height); +} + +/** + * Computes the surface viewport source size, ie. the size after applying the + * surface's scale, transform and cropping (via the viewport's source + * rectangle) but before applying the viewport scaling (via the viewport's + * destination rectangle). + */ +static void surface_state_viewport_src_size(struct wlr_surface_state *state, + int *out_width, int *out_height) { + if (state->buffer_width == 0 && state->buffer_height == 0) { + *out_width = *out_height = 0; + return; + } + + if (state->viewport.has_src) { + *out_width = state->viewport.src.width; + *out_height = state->viewport.src.height; + } else { + surface_state_transformed_buffer_size(state, + out_width, out_height); + *out_width /= state->scale; + *out_height /= state->scale; + } +} + +static void surface_finalize_pending(struct wlr_surface *surface) { + struct wlr_surface_state *pending = &surface->pending; + + if ((pending->committed & WLR_SURFACE_STATE_BUFFER)) { + struct wl_resource *buffer_resource = surface->pending_buffer_resource; + if (buffer_resource != NULL) { + set_pending_buffer_resource(surface, NULL); + + pending->buffer = wlr_buffer_try_from_resource(buffer_resource); + if (pending->buffer == NULL) { + wlr_surface_reject_pending(surface, + buffer_resource, -1, "unknown buffer type"); + } + } + + if (pending->buffer != NULL) { + pending->buffer_width = pending->buffer->width; + pending->buffer_height = pending->buffer->height; + } else { + pending->buffer_width = pending->buffer_height = 0; + } + } + + if (!pending->viewport.has_src && + (pending->buffer_width % pending->scale != 0 || + pending->buffer_height % pending->scale != 0)) { + // TODO: send WL_SURFACE_ERROR_INVALID_SIZE error to cursor surfaces + // once this issue is resolved: + // https://gitlab.freedesktop.org/wayland/wayland/-/issues/194 + if (!surface->role + || strcmp(surface->role->name, "wl_pointer-cursor") == 0 + || strcmp(surface->role->name, "wp_tablet_tool-cursor") == 0) { + wlr_log(WLR_DEBUG, "Client bug: submitted a buffer whose size (%dx%d) " + "is not divisible by scale (%d)", pending->buffer_width, + pending->buffer_height, pending->scale); + } else { + wlr_surface_reject_pending(surface, surface->resource, + WL_SURFACE_ERROR_INVALID_SIZE, + "Buffer size (%dx%d) is not divisible by scale (%d)", + pending->buffer_width, pending->buffer_height, pending->scale); + } + } + + if (pending->viewport.has_dst) { + if (pending->buffer_width == 0 && pending->buffer_height == 0) { + pending->width = pending->height = 0; + } else { + pending->width = pending->viewport.dst_width; + pending->height = pending->viewport.dst_height; + } + } else { + surface_state_viewport_src_size(pending, &pending->width, &pending->height); + } + + pixman_region32_intersect_rect(&pending->surface_damage, + &pending->surface_damage, 0, 0, pending->width, pending->height); + + pixman_region32_intersect_rect(&pending->buffer_damage, + &pending->buffer_damage, 0, 0, pending->buffer_width, + pending->buffer_height); +} + +static void surface_update_damage(pixman_region32_t *buffer_damage, + struct wlr_surface_state *state) { + pixman_region32_clear(buffer_damage); + + // Copy over surface damage + buffer damage + pixman_region32_t surface_damage; + pixman_region32_init(&surface_damage); + + pixman_region32_copy(&surface_damage, &state->surface_damage); + + if (state->viewport.has_dst) { + int src_width, src_height; + surface_state_viewport_src_size(state, &src_width, &src_height); + float scale_x = (float)state->viewport.dst_width / src_width; + float scale_y = (float)state->viewport.dst_height / src_height; + wlr_region_scale_xy(&surface_damage, &surface_damage, + 1.0 / scale_x, 1.0 / scale_y); + } + if (state->viewport.has_src) { + // This is lossy: do a best-effort conversion + pixman_region32_translate(&surface_damage, + floor(state->viewport.src.x), + floor(state->viewport.src.y)); + } + + wlr_region_scale(&surface_damage, &surface_damage, state->scale); + + int width, height; + surface_state_transformed_buffer_size(state, &width, &height); + wlr_region_transform(&surface_damage, &surface_damage, + wlr_output_transform_invert(state->transform), + width, height); + + pixman_region32_union(buffer_damage, + &state->buffer_damage, &surface_damage); + + pixman_region32_fini(&surface_damage); +} + +static void *surface_synced_create_state(struct wlr_surface_synced *synced) { + void *state = calloc(1, synced->impl->state_size); + if (state == NULL) { + return NULL; + } + if (synced->impl->init_state) { + synced->impl->init_state(state); + } + return state; +} + +static void surface_synced_destroy_state(struct wlr_surface_synced *synced, + void *state) { + if (state == NULL) { + return; + } + if (synced->impl->finish_state) { + synced->impl->finish_state(state); + } + free(state); +} + +static void surface_synced_move_state(struct wlr_surface_synced *synced, + void *dst, void *src) { + if (synced->impl->move_state) { + synced->impl->move_state(dst, src); + } else { + memcpy(dst, src, synced->impl->state_size); + } +} + +/** + * Overwrite state with a copy of the next state, then clear the next state. + */ +static void surface_state_move(struct wlr_surface_state *state, + struct wlr_surface_state *next, struct wlr_surface *surface) { + state->width = next->width; + state->height = next->height; + state->buffer_width = next->buffer_width; + state->buffer_height = next->buffer_height; + + if (next->committed & WLR_SURFACE_STATE_SCALE) { + state->scale = next->scale; + } + if (next->committed & WLR_SURFACE_STATE_TRANSFORM) { + state->transform = next->transform; + } + if (next->committed & WLR_SURFACE_STATE_OFFSET) { + state->dx = next->dx; + state->dy = next->dy; + next->dx = next->dy = 0; + } else { + state->dx = state->dy = 0; + } + if (next->committed & WLR_SURFACE_STATE_BUFFER) { + wlr_buffer_unlock(state->buffer); + state->buffer = NULL; + if (next->buffer) { + state->buffer = wlr_buffer_lock(next->buffer); + } + wlr_buffer_unlock(next->buffer); + next->buffer = NULL; + } + if (next->committed & WLR_SURFACE_STATE_SURFACE_DAMAGE) { + pixman_region32_copy(&state->surface_damage, &next->surface_damage); + pixman_region32_clear(&next->surface_damage); + } else { + pixman_region32_clear(&state->surface_damage); + } + if (next->committed & WLR_SURFACE_STATE_BUFFER_DAMAGE) { + pixman_region32_copy(&state->buffer_damage, &next->buffer_damage); + pixman_region32_clear(&next->buffer_damage); + } else { + pixman_region32_clear(&state->buffer_damage); + } + if (next->committed & WLR_SURFACE_STATE_OPAQUE_REGION) { + pixman_region32_copy(&state->opaque, &next->opaque); + } + if (next->committed & WLR_SURFACE_STATE_INPUT_REGION) { + pixman_region32_copy(&state->input, &next->input); + } + if (next->committed & WLR_SURFACE_STATE_VIEWPORT) { + state->viewport = next->viewport; + } + if (next->committed & WLR_SURFACE_STATE_FRAME_CALLBACK_LIST) { + wl_list_insert_list(&state->frame_callback_list, + &next->frame_callback_list); + wl_list_init(&next->frame_callback_list); + } + + void **state_synced = state->synced.data; + void **next_synced = next->synced.data; + struct wlr_surface_synced *synced; + wl_list_for_each(synced, &surface->synced, link) { + surface_synced_move_state(synced, + state_synced[synced->index], next_synced[synced->index]); + } + + // commit subsurface order + struct wlr_subsurface_parent_state *sub_state_next, *sub_state; + wl_list_for_each(sub_state_next, &next->subsurfaces_below, link) { + sub_state = wlr_surface_synced_get_state(sub_state_next->synced, state); + wl_list_remove(&sub_state->link); + wl_list_insert(state->subsurfaces_below.prev, &sub_state->link); + } + wl_list_for_each(sub_state_next, &next->subsurfaces_above, link) { + sub_state = wlr_surface_synced_get_state(sub_state_next->synced, state); + wl_list_remove(&sub_state->link); + wl_list_insert(state->subsurfaces_above.prev, &sub_state->link); + } + + state->committed = next->committed; + next->committed = 0; + + state->seq = next->seq; + + state->cached_state_locks = next->cached_state_locks; + next->cached_state_locks = 0; +} + +static void surface_apply_damage(struct wlr_surface *surface) { + if (surface->current.buffer == NULL) { + // NULL commit + if (surface->buffer != NULL) { + wlr_buffer_unlock(&surface->buffer->base); + } + surface->buffer = NULL; + surface->opaque = false; + return; + } + + surface->opaque = wlr_buffer_is_opaque(surface->current.buffer); + + if (surface->buffer != NULL) { + if (wlr_client_buffer_apply_damage(surface->buffer, + surface->current.buffer, &surface->buffer_damage)) { + wlr_buffer_unlock(surface->current.buffer); + surface->current.buffer = NULL; + return; + } + } + + if (surface->compositor->renderer == NULL) { + return; + } + + struct wlr_client_buffer *buffer = wlr_client_buffer_create( + surface->current.buffer, surface->compositor->renderer); + + if (buffer == NULL) { + wlr_log(WLR_ERROR, "Failed to upload buffer"); + return; + } + + if (surface->buffer != NULL) { + wlr_buffer_unlock(&surface->buffer->base); + } + surface->buffer = buffer; +} + +static void surface_update_opaque_region(struct wlr_surface *surface) { + if (!wlr_surface_has_buffer(surface)) { + pixman_region32_clear(&surface->opaque_region); + return; + } + + if (surface->opaque) { + pixman_region32_fini(&surface->opaque_region); + pixman_region32_init_rect(&surface->opaque_region, + 0, 0, surface->current.width, surface->current.height); + return; + } + + pixman_region32_intersect_rect(&surface->opaque_region, + &surface->current.opaque, + 0, 0, surface->current.width, surface->current.height); +} + +static void surface_update_input_region(struct wlr_surface *surface) { + pixman_region32_intersect_rect(&surface->input_region, + &surface->current.input, + 0, 0, surface->current.width, surface->current.height); +} + +static bool surface_state_init(struct wlr_surface_state *state, + struct wlr_surface *surface); +static void surface_state_finish(struct wlr_surface_state *state); + +static void surface_cache_pending(struct wlr_surface *surface) { + struct wlr_surface_state *cached = calloc(1, sizeof(*cached)); + if (!cached) { + goto error; + } + + if (!surface_state_init(cached, surface)) { + goto error_cached; + } + + void **cached_synced = cached->synced.data; + struct wlr_surface_synced *synced; + wl_list_for_each(synced, &surface->synced, link) { + void *synced_state = surface_synced_create_state(synced); + if (synced_state == NULL) { + goto error_state; + } + cached_synced[synced->index] = synced_state; + } + + surface_state_move(cached, &surface->pending, surface); + + wl_list_insert(surface->cached.prev, &cached->cached_state_link); + + surface->pending.seq++; + + return; + +error_state: + surface_state_finish(cached); +error_cached: + free(cached); +error: + wl_resource_post_no_memory(surface->resource); +} + +static void surface_commit_state(struct wlr_surface *surface, + struct wlr_surface_state *next) { + assert(next->cached_state_locks == 0); + + bool invalid_buffer = next->committed & WLR_SURFACE_STATE_BUFFER; + + if (invalid_buffer && next->buffer == NULL) { + surface->unmap_commit = surface->mapped; + wlr_surface_unmap(surface); + } else { + surface->unmap_commit = false; + } + + surface->previous.scale = surface->current.scale; + surface->previous.transform = surface->current.transform; + surface->previous.width = surface->current.width; + surface->previous.height = surface->current.height; + surface->previous.buffer_width = surface->current.buffer_width; + surface->previous.buffer_height = surface->current.buffer_height; + + surface_state_move(&surface->current, next, surface); + surface_update_damage(&surface->buffer_damage, &surface->current); + + if (invalid_buffer) { + surface_apply_damage(surface); + } + surface_update_opaque_region(surface); + surface_update_input_region(surface); + + struct wlr_subsurface *subsurface; + wl_list_for_each(subsurface, &surface->current.subsurfaces_below, current.link) { + subsurface_handle_parent_commit(subsurface); + } + wl_list_for_each(subsurface, &surface->current.subsurfaces_above, current.link) { + subsurface_handle_parent_commit(subsurface); + } + + // If we're committing the pending state, bump the pending sequence number + // here, to allow commit listeners to lock the new pending state. + if (next == &surface->pending) { + surface->pending.seq++; + } + + struct wlr_surface_synced *synced; + wl_list_for_each(synced, &surface->synced, link) { + if (synced->impl->commit) { + synced->impl->commit(synced); + } + } + + if (surface->role != NULL && surface->role->commit != NULL && + (surface->role_resource != NULL || surface->role->no_object)) { + surface->role->commit(surface); + } + + wl_signal_emit_mutable(&surface->events.commit, surface); + + // Release the buffer after emitting the commit event, so that listeners can + // access it. Don't leave the buffer locked so that wl_shm buffers can be + // released immediately on commit when they are uploaded to the GPU. + wlr_buffer_unlock(surface->current.buffer); + surface->current.buffer = NULL; +} + +static void surface_handle_commit(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_surface *surface = wlr_surface_from_resource(resource); + surface->handling_commit = true; + + surface_finalize_pending(surface); + + if (surface->role != NULL && surface->role->client_commit != NULL && + (surface->role_resource != NULL || surface->role->no_object)) { + surface->role->client_commit(surface); + } + + wl_signal_emit_mutable(&surface->events.client_commit, NULL); + + surface->handling_commit = false; + if (surface->pending_rejected) { + return; + } + + if (surface->pending.cached_state_locks > 0 || !wl_list_empty(&surface->cached)) { + surface_cache_pending(surface); + } else { + surface_commit_state(surface, &surface->pending); + } +} + +static void surface_handle_set_buffer_transform(struct wl_client *client, + struct wl_resource *resource, int32_t transform) { + if (transform < WL_OUTPUT_TRANSFORM_NORMAL || + transform > WL_OUTPUT_TRANSFORM_FLIPPED_270) { + wl_resource_post_error(resource, WL_SURFACE_ERROR_INVALID_TRANSFORM, + "Specified transform value (%d) is invalid", transform); + return; + } + struct wlr_surface *surface = wlr_surface_from_resource(resource); + surface->pending.committed |= WLR_SURFACE_STATE_TRANSFORM; + surface->pending.transform = transform; +} + +static void surface_handle_set_buffer_scale(struct wl_client *client, + struct wl_resource *resource, int32_t scale) { + if (scale <= 0) { + wl_resource_post_error(resource, WL_SURFACE_ERROR_INVALID_SCALE, + "Specified scale value (%d) is not positive", scale); + return; + } + struct wlr_surface *surface = wlr_surface_from_resource(resource); + surface->pending.committed |= WLR_SURFACE_STATE_SCALE; + surface->pending.scale = scale; +} + +static void surface_handle_damage_buffer(struct wl_client *client, + struct wl_resource *resource, + int32_t x, int32_t y, int32_t width, + int32_t height) { + struct wlr_surface *surface = wlr_surface_from_resource(resource); + if (width < 0 || height < 0) { + return; + } + surface->pending.committed |= WLR_SURFACE_STATE_BUFFER_DAMAGE; + pixman_region32_union_rect(&surface->pending.buffer_damage, + &surface->pending.buffer_damage, + x, y, width, height); +} + +static void surface_handle_offset(struct wl_client *client, + struct wl_resource *resource, int32_t x, int32_t y) { + struct wlr_surface *surface = wlr_surface_from_resource(resource); + + surface->pending.committed |= WLR_SURFACE_STATE_OFFSET; + surface->pending.dx = x; + surface->pending.dy = y; +} + +static const struct wl_surface_interface surface_implementation = { + .destroy = surface_handle_destroy, + .attach = surface_handle_attach, + .damage = surface_handle_damage, + .frame = surface_handle_frame, + .set_opaque_region = surface_handle_set_opaque_region, + .set_input_region = surface_handle_set_input_region, + .commit = surface_handle_commit, + .set_buffer_transform = surface_handle_set_buffer_transform, + .set_buffer_scale = surface_handle_set_buffer_scale, + .damage_buffer = surface_handle_damage_buffer, + .offset = surface_handle_offset, +}; + +struct wlr_surface *wlr_surface_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_surface_interface, + &surface_implementation)); + return wl_resource_get_user_data(resource); +} + +static bool surface_state_init(struct wlr_surface_state *state, + struct wlr_surface *surface) { + *state = (struct wlr_surface_state){ + .scale = 1, + .transform = WL_OUTPUT_TRANSFORM_NORMAL, + }; + + wl_list_init(&state->subsurfaces_above); + wl_list_init(&state->subsurfaces_below); + + wl_list_init(&state->frame_callback_list); + + pixman_region32_init(&state->surface_damage); + pixman_region32_init(&state->buffer_damage); + pixman_region32_init(&state->opaque); + pixman_region32_init_rect(&state->input, + INT32_MIN, INT32_MIN, UINT32_MAX, UINT32_MAX); + + wl_array_init(&state->synced); + void *ptr = wl_array_add(&state->synced, surface->synced_len * sizeof(void *)); + return ptr != NULL; +} + +static void surface_state_finish(struct wlr_surface_state *state) { + wlr_buffer_unlock(state->buffer); + + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &state->frame_callback_list) { + wl_resource_destroy(resource); + } + + pixman_region32_fini(&state->surface_damage); + pixman_region32_fini(&state->buffer_damage); + pixman_region32_fini(&state->opaque); + pixman_region32_fini(&state->input); + + wl_array_release(&state->synced); +} + +static void surface_state_destroy_cached(struct wlr_surface_state *state, + struct wlr_surface *surface) { + void **synced_states = state->synced.data; + struct wlr_surface_synced *synced; + wl_list_for_each(synced, &surface->synced, link) { + surface_synced_destroy_state(synced, synced_states[synced->index]); + } + + surface_state_finish(state); + wl_list_remove(&state->cached_state_link); + free(state); +} + +static void surface_output_destroy(struct wlr_surface_output *surface_output); +static void surface_destroy_role_object(struct wlr_surface *surface); + +static void surface_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_surface *surface = wlr_surface_from_resource(resource); + + surface_destroy_role_object(surface); + + wl_signal_emit_mutable(&surface->events.destroy, surface); + wlr_addon_set_finish(&surface->addons); + + assert(wl_list_empty(&surface->events.client_commit.listener_list)); + assert(wl_list_empty(&surface->events.commit.listener_list)); + assert(wl_list_empty(&surface->events.map.listener_list)); + assert(wl_list_empty(&surface->events.unmap.listener_list)); + assert(wl_list_empty(&surface->events.destroy.listener_list)); + assert(wl_list_empty(&surface->events.new_subsurface.listener_list)); + + assert(wl_list_empty(&surface->synced)); + + struct wlr_surface_state *cached, *cached_tmp; + wl_list_for_each_safe(cached, cached_tmp, &surface->cached, cached_state_link) { + surface_state_destroy_cached(cached, surface); + } + + wl_list_remove(&surface->role_resource_destroy.link); + + wl_list_remove(&surface->pending_buffer_resource_destroy.link); + + surface_state_finish(&surface->pending); + surface_state_finish(&surface->current); + pixman_region32_fini(&surface->buffer_damage); + pixman_region32_fini(&surface->opaque_region); + pixman_region32_fini(&surface->input_region); + if (surface->buffer != NULL) { + wlr_buffer_unlock(&surface->buffer->base); + } + + struct wlr_surface_output *surface_output, *surface_output_tmp; + wl_list_for_each_safe(surface_output, surface_output_tmp, + &surface->current_outputs, link) { + surface_output_destroy(surface_output); + } + + free(surface); +} + +static struct wlr_surface *surface_create(struct wl_client *client, + uint32_t version, uint32_t id, struct wlr_compositor *compositor) { + struct wlr_surface *surface = calloc(1, sizeof(*surface)); + if (!surface) { + wl_client_post_no_memory(client); + return NULL; + } + surface->resource = wl_resource_create(client, &wl_surface_interface, + version, id); + if (surface->resource == NULL) { + free(surface); + wl_client_post_no_memory(client); + return NULL; + } + wl_resource_set_implementation(surface->resource, &surface_implementation, + surface, surface_handle_resource_destroy); + + wlr_log(WLR_DEBUG, "New wlr_surface %p (res %p)", surface, surface->resource); + + surface->compositor = compositor; + + surface_state_init(&surface->current, surface); + surface_state_init(&surface->pending, surface); + surface->pending.seq = 1; + + wl_signal_init(&surface->events.client_commit); + wl_signal_init(&surface->events.commit); + wl_signal_init(&surface->events.map); + wl_signal_init(&surface->events.unmap); + wl_signal_init(&surface->events.destroy); + wl_signal_init(&surface->events.new_subsurface); + + wl_list_init(&surface->current_outputs); + wl_list_init(&surface->cached); + pixman_region32_init(&surface->buffer_damage); + pixman_region32_init(&surface->opaque_region); + pixman_region32_init(&surface->input_region); + wlr_addon_set_init(&surface->addons); + wl_list_init(&surface->synced); + + wl_list_init(&surface->role_resource_destroy.link); + + surface->pending_buffer_resource_destroy.notify = pending_buffer_resource_handle_destroy; + wl_list_init(&surface->pending_buffer_resource_destroy.link); + + return surface; +} + +struct wlr_texture *wlr_surface_get_texture(struct wlr_surface *surface) { + if (surface->buffer == NULL) { + return NULL; + } + return surface->buffer->texture; +} + +bool wlr_surface_has_buffer(struct wlr_surface *surface) { + return wlr_surface_state_has_buffer(&surface->current); +} + +bool wlr_surface_state_has_buffer(const struct wlr_surface_state *state) { + return state->buffer_width > 0 && state->buffer_height > 0; +} + +void wlr_surface_map(struct wlr_surface *surface) { + if (surface->mapped) { + return; + } + assert(wlr_surface_has_buffer(surface)); + surface->mapped = true; + + struct wlr_subsurface *subsurface; + wl_list_for_each(subsurface, &surface->current.subsurfaces_below, current.link) { + subsurface_consider_map(subsurface); + } + wl_list_for_each(subsurface, &surface->current.subsurfaces_above, current.link) { + subsurface_consider_map(subsurface); + } + + if (surface->role != NULL && surface->role->map != NULL && + (surface->role_resource != NULL || surface->role->no_object)) { + surface->role->map(surface); + } + + wl_signal_emit_mutable(&surface->events.map, NULL); +} + +void wlr_surface_unmap(struct wlr_surface *surface) { + if (!surface->mapped) { + return; + } + surface->mapped = false; + wl_signal_emit_mutable(&surface->events.unmap, NULL); + if (surface->role != NULL && surface->role->unmap != NULL && + (surface->role_resource != NULL || surface->role->no_object)) { + surface->role->unmap(surface); + } + + struct wlr_subsurface *subsurface; + wl_list_for_each(subsurface, &surface->current.subsurfaces_below, current.link) { + wlr_surface_unmap(subsurface->surface); + } + wl_list_for_each(subsurface, &surface->current.subsurfaces_above, current.link) { + wlr_surface_unmap(subsurface->surface); + } +} + +void wlr_surface_reject_pending(struct wlr_surface *surface, struct wl_resource *resource, + uint32_t code, const char *msg, ...) { + assert(surface->handling_commit); + if (surface->pending_rejected) { + return; + } + + va_list args; + va_start(args, msg); + + wl_resource_post_error_vargs(resource, code, msg, args); + surface->pending_rejected = true; + + va_end(args); +} + +bool wlr_surface_set_role(struct wlr_surface *surface, const struct wlr_surface_role *role, + struct wl_resource *error_resource, uint32_t error_code) { + assert(role != NULL); + + if (surface->role != NULL && surface->role != role) { + if (error_resource != NULL) { + wl_resource_post_error(error_resource, error_code, + "Cannot assign role %s to wl_surface@%" PRIu32 ", already has role %s", + role->name, wl_resource_get_id(surface->resource), + surface->role->name); + } + return false; + } + if (surface->role_resource != NULL) { + wl_resource_post_error(error_resource, error_code, + "Cannot reassign role %s to wl_surface@%" PRIu32 ", role object still exists", + role->name, wl_resource_get_id(surface->resource)); + return false; + } + + surface->role = role; + return true; +} + +static void surface_handle_role_resource_destroy(struct wl_listener *listener, void *data) { + struct wlr_surface *surface = wl_container_of(listener, surface, role_resource_destroy); + surface_destroy_role_object(surface); +} + +void wlr_surface_set_role_object(struct wlr_surface *surface, struct wl_resource *role_resource) { + assert(surface->role != NULL); + assert(!surface->role->no_object); + assert(surface->role_resource == NULL); + assert(role_resource != NULL); + surface->role_resource = role_resource; + surface->role_resource_destroy.notify = surface_handle_role_resource_destroy; + wl_resource_add_destroy_listener(role_resource, &surface->role_resource_destroy); +} + +static void surface_destroy_role_object(struct wlr_surface *surface) { + if (surface->role_resource == NULL) { + return; + } + wlr_surface_unmap(surface); + if (surface->role->destroy != NULL) { + surface->role->destroy(surface); + } + surface->role_resource = NULL; + wl_list_remove(&surface->role_resource_destroy.link); + wl_list_init(&surface->role_resource_destroy.link); +} + +uint32_t wlr_surface_lock_pending(struct wlr_surface *surface) { + surface->pending.cached_state_locks++; + return surface->pending.seq; +} + +void wlr_surface_unlock_cached(struct wlr_surface *surface, uint32_t seq) { + if (surface->pending.seq == seq) { + assert(surface->pending.cached_state_locks > 0); + surface->pending.cached_state_locks--; + return; + } + + bool found = false; + struct wlr_surface_state *cached; + wl_list_for_each(cached, &surface->cached, cached_state_link) { + if (cached->seq == seq) { + found = true; + break; + } + } + assert(found); + + assert(cached->cached_state_locks > 0); + cached->cached_state_locks--; + + if (cached->cached_state_locks != 0) { + return; + } + + if (cached->cached_state_link.prev != &surface->cached) { + // This isn't the first cached state. This means we're blocked on a + // previous cached state. + return; + } + + // TODO: consider merging all committed states together + struct wlr_surface_state *next, *tmp; + wl_list_for_each_safe(next, tmp, &surface->cached, cached_state_link) { + if (next->cached_state_locks > 0) { + break; + } + + surface_commit_state(surface, next); + surface_state_destroy_cached(next, surface); + } +} + +struct wlr_surface *wlr_surface_get_root_surface(struct wlr_surface *surface) { + struct wlr_subsurface *subsurface; + while ((subsurface = wlr_subsurface_try_from_wlr_surface(surface))) { + surface = subsurface->parent; + } + return surface; +} + +bool wlr_surface_point_accepts_input(struct wlr_surface *surface, + double sx, double sy) { + return sx >= 0 && sx < surface->current.width && + sy >= 0 && sy < surface->current.height && + pixman_region32_contains_point(&surface->input_region, + floor(sx), floor(sy), NULL); +} + +struct wlr_surface *wlr_surface_surface_at(struct wlr_surface *surface, + double sx, double sy, double *sub_x, double *sub_y) { + struct wlr_subsurface *subsurface; + wl_list_for_each_reverse(subsurface, &surface->current.subsurfaces_above, + current.link) { + if (!subsurface->surface->mapped) { + continue; + } + + double _sub_x = subsurface->current.x; + double _sub_y = subsurface->current.y; + struct wlr_surface *sub = wlr_surface_surface_at(subsurface->surface, + sx - _sub_x, sy - _sub_y, sub_x, sub_y); + if (sub != NULL) { + return sub; + } + } + + if (wlr_surface_point_accepts_input(surface, sx, sy)) { + if (sub_x) { + *sub_x = sx; + } + if (sub_y) { + *sub_y = sy; + } + return surface; + } + + wl_list_for_each_reverse(subsurface, &surface->current.subsurfaces_below, + current.link) { + if (!subsurface->surface->mapped) { + continue; + } + + double _sub_x = subsurface->current.x; + double _sub_y = subsurface->current.y; + struct wlr_surface *sub = wlr_surface_surface_at(subsurface->surface, + sx - _sub_x, sy - _sub_y, sub_x, sub_y); + if (sub != NULL) { + return sub; + } + } + + return NULL; +} + +static void surface_output_destroy(struct wlr_surface_output *surface_output) { + wl_list_remove(&surface_output->bind.link); + wl_list_remove(&surface_output->destroy.link); + wl_list_remove(&surface_output->link); + + free(surface_output); +} + +static void surface_handle_output_bind(struct wl_listener *listener, + void *data) { + struct wlr_output_event_bind *evt = data; + struct wlr_surface_output *surface_output = + wl_container_of(listener, surface_output, bind); + struct wl_client *client = wl_resource_get_client( + surface_output->surface->resource); + if (client == wl_resource_get_client(evt->resource)) { + wl_surface_send_enter(surface_output->surface->resource, evt->resource); + } +} + +static void surface_handle_output_destroy(struct wl_listener *listener, + void *data) { + struct wlr_surface_output *surface_output = + wl_container_of(listener, surface_output, destroy); + surface_output_destroy(surface_output); +} + +void wlr_surface_send_enter(struct wlr_surface *surface, + struct wlr_output *output) { + struct wl_client *client = wl_resource_get_client(surface->resource); + struct wlr_surface_output *surface_output; + struct wl_resource *resource; + + wl_list_for_each(surface_output, &surface->current_outputs, link) { + if (surface_output->output == output) { + return; + } + } + + surface_output = calloc(1, sizeof(*surface_output)); + if (surface_output == NULL) { + return; + } + surface_output->bind.notify = surface_handle_output_bind; + surface_output->destroy.notify = surface_handle_output_destroy; + + wl_signal_add(&output->events.bind, &surface_output->bind); + wl_signal_add(&output->events.destroy, &surface_output->destroy); + + surface_output->surface = surface; + surface_output->output = output; + wl_list_insert(&surface->current_outputs, &surface_output->link); + + wl_resource_for_each(resource, &output->resources) { + if (client == wl_resource_get_client(resource)) { + wl_surface_send_enter(surface->resource, resource); + } + } +} + +void wlr_surface_send_leave(struct wlr_surface *surface, + struct wlr_output *output) { + struct wl_client *client = wl_resource_get_client(surface->resource); + struct wlr_surface_output *surface_output, *tmp; + struct wl_resource *resource; + + wl_list_for_each_safe(surface_output, tmp, + &surface->current_outputs, link) { + if (surface_output->output == output) { + surface_output_destroy(surface_output); + wl_resource_for_each(resource, &output->resources) { + if (client == wl_resource_get_client(resource)) { + wl_surface_send_leave(surface->resource, resource); + } + } + break; + } + } +} + +void wlr_surface_send_frame_done(struct wlr_surface *surface, + const struct timespec *when) { + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, + &surface->current.frame_callback_list) { + wl_callback_send_done(resource, timespec_to_msec(when)); + wl_resource_destroy(resource); + } +} + +static void surface_for_each_surface(struct wlr_surface *surface, int x, int y, + wlr_surface_iterator_func_t iterator, void *user_data) { + struct wlr_subsurface *subsurface; + wl_list_for_each(subsurface, &surface->current.subsurfaces_below, current.link) { + if (!subsurface->surface->mapped) { + continue; + } + + struct wlr_subsurface_parent_state *state = &subsurface->current; + int sx = state->x; + int sy = state->y; + + surface_for_each_surface(subsurface->surface, x + sx, y + sy, + iterator, user_data); + } + + iterator(surface, x, y, user_data); + + wl_list_for_each(subsurface, &surface->current.subsurfaces_above, current.link) { + if (!subsurface->surface->mapped) { + continue; + } + + struct wlr_subsurface_parent_state *state = &subsurface->current; + int sx = state->x; + int sy = state->y; + + surface_for_each_surface(subsurface->surface, x + sx, y + sy, + iterator, user_data); + } +} + +void wlr_surface_for_each_surface(struct wlr_surface *surface, + wlr_surface_iterator_func_t iterator, void *user_data) { + surface_for_each_surface(surface, 0, 0, iterator, user_data); +} + +struct bound_acc { + int32_t min_x, min_y; + int32_t max_x, max_y; +}; + +static void handle_bounding_box_surface(struct wlr_surface *surface, + int x, int y, void *data) { + struct bound_acc *acc = data; + + acc->min_x = min(x, acc->min_x); + acc->min_y = min(y, acc->min_y); + + acc->max_x = max(x + surface->current.width, acc->max_x); + acc->max_y = max(y + surface->current.height, acc->max_y); +} + +void wlr_surface_get_extents(struct wlr_surface *surface, struct wlr_box *box) { + struct bound_acc acc = { + .min_x = 0, + .min_y = 0, + .max_x = surface->current.width, + .max_y = surface->current.height, + }; + + wlr_surface_for_each_surface(surface, handle_bounding_box_surface, &acc); + + box->x = acc.min_x; + box->y = acc.min_y; + box->width = acc.max_x - acc.min_x; + box->height = acc.max_y - acc.min_y; +} + +static void crop_region(pixman_region32_t *dst, pixman_region32_t *src, + const struct wlr_box *box) { + pixman_region32_intersect_rect(dst, src, + box->x, box->y, box->width, box->height); + pixman_region32_translate(dst, -box->x, -box->y); +} + +void wlr_surface_get_effective_damage(struct wlr_surface *surface, + pixman_region32_t *damage) { + pixman_region32_clear(damage); + + // Transform and copy the buffer damage in terms of surface coordinates. + wlr_region_transform(damage, &surface->buffer_damage, + surface->current.transform, surface->current.buffer_width, + surface->current.buffer_height); + wlr_region_scale(damage, damage, 1.0 / (float)surface->current.scale); + + if (surface->current.viewport.has_src) { + struct wlr_box src_box = { + .x = floor(surface->current.viewport.src.x), + .y = floor(surface->current.viewport.src.y), + .width = ceil(surface->current.viewport.src.width), + .height = ceil(surface->current.viewport.src.height), + }; + crop_region(damage, damage, &src_box); + } + if (surface->current.viewport.has_dst) { + int src_width, src_height; + surface_state_viewport_src_size(&surface->current, + &src_width, &src_height); + float scale_x = (float)surface->current.viewport.dst_width / src_width; + float scale_y = (float)surface->current.viewport.dst_height / src_height; + wlr_region_scale_xy(damage, damage, scale_x, scale_y); + } +} + +void wlr_surface_get_buffer_source_box(struct wlr_surface *surface, + struct wlr_fbox *box) { + box->x = box->y = 0; + box->width = surface->current.buffer_width; + box->height = surface->current.buffer_height; + + if (surface->current.viewport.has_src) { + box->x = surface->current.viewport.src.x * surface->current.scale; + box->y = surface->current.viewport.src.y * surface->current.scale; + box->width = surface->current.viewport.src.width * surface->current.scale; + box->height = surface->current.viewport.src.height * surface->current.scale; + + int width, height; + surface_state_transformed_buffer_size(&surface->current, &width, &height); + wlr_fbox_transform(box, box, + wlr_output_transform_invert(surface->current.transform), + width, height); + } +} + +void wlr_surface_set_preferred_buffer_scale(struct wlr_surface *surface, + int32_t scale) { + assert(scale > 0); + + if (wl_resource_get_version(surface->resource) < + WL_SURFACE_PREFERRED_BUFFER_SCALE_SINCE_VERSION) { + return; + } + + if (surface->preferred_buffer_scale == scale) { + return; + } + + wl_surface_send_preferred_buffer_scale(surface->resource, scale); + surface->preferred_buffer_scale = scale; +} + +void wlr_surface_set_preferred_buffer_transform(struct wlr_surface *surface, + enum wl_output_transform transform) { + if (wl_resource_get_version(surface->resource) < + WL_SURFACE_PREFERRED_BUFFER_TRANSFORM_SINCE_VERSION) { + return; + } + + if (surface->preferred_buffer_transform == transform && + surface->preferred_buffer_transform_sent) { + return; + } + + wl_surface_send_preferred_buffer_transform(surface->resource, transform); + surface->preferred_buffer_transform_sent = true; + surface->preferred_buffer_transform = transform; +} + +static const struct wl_compositor_interface compositor_impl; + +static struct wlr_compositor *compositor_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_compositor_interface, + &compositor_impl)); + return wl_resource_get_user_data(resource); +} + +static void compositor_create_surface(struct wl_client *client, + struct wl_resource *resource, uint32_t id) { + struct wlr_compositor *compositor = compositor_from_resource(resource); + + struct wlr_surface *surface = surface_create(client, + wl_resource_get_version(resource), id, compositor); + if (surface == NULL) { + wl_client_post_no_memory(client); + return; + } + + wl_signal_emit_mutable(&compositor->events.new_surface, surface); +} + +static void compositor_create_region(struct wl_client *client, + struct wl_resource *resource, uint32_t id) { + region_create(client, wl_resource_get_version(resource), id); +} + +static const struct wl_compositor_interface compositor_impl = { + .create_surface = compositor_create_surface, + .create_region = compositor_create_region, +}; + +static void compositor_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_compositor *compositor = data; + + struct wl_resource *resource = + wl_resource_create(wl_client, &wl_compositor_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + wl_resource_set_implementation(resource, &compositor_impl, compositor, NULL); +} + +static void compositor_destroy(struct wlr_compositor *compositor, + bool destroy_global_safe) { + wl_signal_emit_mutable(&compositor->events.destroy, NULL); + + assert(wl_list_empty(&compositor->events.new_surface.listener_list)); + assert(wl_list_empty(&compositor->events.destroy.listener_list)); + + wl_list_remove(&compositor->display_destroy.link); + wl_list_remove(&compositor->renderer_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(compositor->global); + } else { + wl_global_destroy(compositor->global); + } + free(compositor); +} + +void wlr_compositor_destroy(struct wlr_compositor *compositor, bool destroy_global_safe) { + compositor_destroy(compositor, destroy_global_safe); +} + +static void compositor_handle_display_destroy( + struct wl_listener *listener, void *data) { + struct wlr_compositor *compositor = + wl_container_of(listener, compositor, display_destroy); + compositor_destroy(compositor, false); +} + +static void compositor_handle_renderer_destroy( + struct wl_listener *listener, void *data) { + struct wlr_compositor *compositor = + wl_container_of(listener, compositor, renderer_destroy); + wlr_compositor_set_renderer(compositor, NULL); +} + +struct wlr_compositor *wlr_compositor_create(struct wl_display *display, + uint32_t version, struct wlr_renderer *renderer) { + assert(version <= COMPOSITOR_VERSION); + + struct wlr_compositor *compositor = calloc(1, sizeof(*compositor)); + if (!compositor) { + return NULL; + } + + compositor->global = wl_global_create(display, &wl_compositor_interface, + version, compositor, compositor_bind); + if (!compositor->global) { + free(compositor); + return NULL; + } + + wl_signal_init(&compositor->events.new_surface); + wl_signal_init(&compositor->events.destroy); + + wl_list_init(&compositor->renderer_destroy.link); + + compositor->display_destroy.notify = compositor_handle_display_destroy; + wl_display_add_destroy_listener(display, &compositor->display_destroy); + + wlr_compositor_set_renderer(compositor, renderer); + + return compositor; +} + +void wlr_compositor_set_renderer(struct wlr_compositor *compositor, + struct wlr_renderer *renderer) { + wl_list_remove(&compositor->renderer_destroy.link); + compositor->renderer = renderer; + + if (renderer != NULL) { + compositor->renderer_destroy.notify = compositor_handle_renderer_destroy; + wl_signal_add(&renderer->events.destroy, &compositor->renderer_destroy); + } else { + wl_list_init(&compositor->renderer_destroy.link); + } +} + +static bool surface_state_add_synced(struct wlr_surface_state *state, void *value) { + void **ptr = wl_array_add(&state->synced, sizeof(void *)); + if (ptr == NULL) { + return false; + } + *ptr = value; + return true; +} + +static void *surface_state_remove_synced(struct wlr_surface_state *state, + struct wlr_surface_synced *synced) { + void **synced_states = state->synced.data; + void *synced_state = synced_states[synced->index]; + array_remove_at(&state->synced, synced->index * sizeof(void *), sizeof(void *)); + return synced_state; +} + +static void surface_state_remove_and_destroy_synced(struct wlr_surface_state *state, + struct wlr_surface_synced *synced) { + void *synced_state = surface_state_remove_synced(state, synced); + surface_synced_destroy_state(synced, synced_state); +} + +bool wlr_surface_synced_init(struct wlr_surface_synced *synced, + struct wlr_surface *surface, const struct wlr_surface_synced_impl *impl, + void *pending, void *current) { + assert(impl->state_size > 0); + + struct wlr_surface_synced *other; + wl_list_for_each(other, &surface->synced, link) { + assert(synced != other); + } + + memset(pending, 0, impl->state_size); + memset(current, 0, impl->state_size); + if (impl->init_state) { + impl->init_state(pending); + impl->init_state(current); + } + if (!surface_state_add_synced(&surface->pending, pending)) { + goto error_init; + } + if (!surface_state_add_synced(&surface->current, current)) { + goto error_pending; + } + + *synced = (struct wlr_surface_synced){ + .surface = surface, + .impl = impl, + .index = surface->synced_len, + }; + + struct wlr_surface_state *cached; + wl_list_for_each(cached, &surface->cached, cached_state_link) { + void *synced_state = surface_synced_create_state(synced); + if (synced_state == NULL || + !surface_state_add_synced(cached, synced_state)) { + surface_synced_destroy_state(synced, synced_state); + goto error_cached; + } + } + + wl_list_insert(&surface->synced, &synced->link); + surface->synced_len++; + + return true; + +error_cached:; + struct wlr_surface_state *failed_at = cached; + wl_list_for_each(cached, &surface->cached, cached_state_link) { + if (cached == failed_at) { + break; + } + surface_state_remove_and_destroy_synced(cached, synced); + } + surface_state_remove_synced(&surface->current, synced); +error_pending: + surface_state_remove_synced(&surface->pending, synced); +error_init: + if (synced->impl->finish_state) { + synced->impl->finish_state(pending); + synced->impl->finish_state(current); + } + return false; +} + +void wlr_surface_synced_finish(struct wlr_surface_synced *synced) { + struct wlr_surface *surface = synced->surface; + + bool found = false; + struct wlr_surface_synced *other; + wl_list_for_each(other, &surface->synced, link) { + if (other == synced) { + found = true; + } else if (other->index > synced->index) { + other->index--; + } + } + assert(found); + + struct wlr_surface_state *cached; + wl_list_for_each(cached, &surface->cached, cached_state_link) { + surface_state_remove_and_destroy_synced(cached, synced); + } + + void *pending = surface_state_remove_synced(&surface->pending, synced); + void *current = surface_state_remove_synced(&surface->current, synced); + if (synced->impl->finish_state) { + synced->impl->finish_state(pending); + synced->impl->finish_state(current); + } + + wl_list_remove(&synced->link); + synced->surface->synced_len--; +} + +void *wlr_surface_synced_get_state(struct wlr_surface_synced *synced, + const struct wlr_surface_state *state) { + void **synced_states = state->synced.data; + return synced_states[synced->index]; +} diff --git a/3rdparty/wlroots/types/wlr_content_type_v1.c b/3rdparty/wlroots/types/wlr_content_type_v1.c new file mode 100644 index 0000000000..7a62922099 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_content_type_v1.c @@ -0,0 +1,215 @@ +#include +#include +#include +#include +#include + +#include "content-type-v1-protocol.h" +#include "util/global.h" + +#define CONTENT_TYPE_VERSION 1 + +struct wlr_content_type_v1_surface { + struct wl_resource *resource; + struct wlr_addon addon; + enum wp_content_type_v1_type pending, current; + + struct wlr_surface_synced synced; +}; + +static void resource_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wp_content_type_v1_interface content_type_surface_impl; +static const struct wp_content_type_manager_v1_interface manager_impl; + +// Returns NULL if the resource is inert +static struct wlr_content_type_v1_surface *content_type_surface_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_content_type_v1_interface, &content_type_surface_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_content_type_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_content_type_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void content_type_surface_handle_set_content_type(struct wl_client *client, + struct wl_resource *resource, uint32_t type) { + struct wlr_content_type_v1_surface *content_type_surface = + content_type_surface_from_resource(resource); + if (content_type_surface == NULL) { + return; + } + content_type_surface->pending = type; +} + +static const struct wp_content_type_v1_interface content_type_surface_impl = { + .destroy = resource_handle_destroy, + .set_content_type = content_type_surface_handle_set_content_type, +}; + +static void content_type_surface_destroy( + struct wlr_content_type_v1_surface *content_type_surface) { + if (content_type_surface == NULL) { + return; + } + wlr_addon_finish(&content_type_surface->addon); + wlr_surface_synced_finish(&content_type_surface->synced); + wl_resource_set_user_data(content_type_surface->resource, NULL); + free(content_type_surface); +} + +static void surface_addon_destroy(struct wlr_addon *addon) { + struct wlr_content_type_v1_surface *content_type_surface = + wl_container_of(addon, content_type_surface, addon); + content_type_surface_destroy(content_type_surface); +} + +static const struct wlr_addon_interface surface_addon_impl = { + .name = "wp_content_type_v1", + .destroy = surface_addon_destroy, +}; + +static const struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(enum wp_content_type_v1_type), +}; + +static void content_type_surface_handle_resource_destroy( + struct wl_resource *resource) { + struct wlr_content_type_v1_surface *content_type_surface = + content_type_surface_from_resource(resource); + content_type_surface_destroy(content_type_surface); +} + +static void manager_handle_get_surface_content_type(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + struct wl_resource *surface_resource) { + struct wlr_content_type_manager_v1 *manager = + manager_from_resource(manager_resource); + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + + if (wlr_addon_find(&surface->addons, manager, &surface_addon_impl) != NULL) { + wl_resource_post_error(manager_resource, + WP_CONTENT_TYPE_MANAGER_V1_ERROR_ALREADY_CONSTRUCTED, + "wp_content_type_v1 already constructed for this surface"); + return; + } + + struct wlr_content_type_v1_surface *content_type_surface = + calloc(1, sizeof(*content_type_surface)); + if (content_type_surface == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + + if (!wlr_surface_synced_init(&content_type_surface->synced, surface, + &surface_synced_impl, &content_type_surface->pending, + &content_type_surface->current)) { + free(content_type_surface); + wl_resource_post_no_memory(manager_resource); + return; + } + + uint32_t version = wl_resource_get_version(manager_resource); + content_type_surface->resource = wl_resource_create(client, + &wp_content_type_v1_interface, version, id); + if (content_type_surface->resource == NULL) { + wlr_surface_synced_finish(&content_type_surface->synced); + free(content_type_surface); + wl_resource_post_no_memory(manager_resource); + return; + } + wl_resource_set_implementation(content_type_surface->resource, + &content_type_surface_impl, content_type_surface, + content_type_surface_handle_resource_destroy); + + wlr_addon_init(&content_type_surface->addon, &surface->addons, + manager, &surface_addon_impl); +} + +static const struct wp_content_type_manager_v1_interface manager_impl = { + .destroy = resource_handle_destroy, + .get_surface_content_type = manager_handle_get_surface_content_type, +}; + +static void manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_content_type_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &wp_content_type_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, manager, NULL); +} + +static void content_type_manager_v1_destroy(struct wlr_content_type_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, NULL); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + wl_list_remove(&manager->display_destroy.link); + free(manager); +} + +void wlr_content_type_manager_v1_destroy(struct wlr_content_type_manager_v1 *manager, + bool destroy_global_safe) { + content_type_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_content_type_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + content_type_manager_v1_destroy(manager, false); +} + +struct wlr_content_type_manager_v1 *wlr_content_type_manager_v1_create( + struct wl_display *display, uint32_t version) { + assert(version <= CONTENT_TYPE_VERSION); + + struct wlr_content_type_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + manager->global = wl_global_create(display, + &wp_content_type_manager_v1_interface, version, manager, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + wl_signal_init(&manager->events.destroy); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} + +enum wp_content_type_v1_type wlr_surface_get_content_type_v1( + struct wlr_content_type_manager_v1 *manager, struct wlr_surface *surface) { + struct wlr_addon *addon = + wlr_addon_find(&surface->addons, manager, &surface_addon_impl); + if (addon == NULL) { + return WP_CONTENT_TYPE_V1_TYPE_NONE; + } + + struct wlr_content_type_v1_surface *content_type_surface = + wl_container_of(addon, content_type_surface, addon); + return content_type_surface->current; +} diff --git a/3rdparty/wlroots/types/wlr_cursor.c b/3rdparty/wlroots/types/wlr_cursor.c new file mode 100644 index 0000000000..8d0d774753 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_cursor.c @@ -0,0 +1,1254 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_output.h" + +struct wlr_cursor_device { + struct wlr_cursor *cursor; + struct wlr_input_device *device; + struct wl_list link; + struct wlr_output *mapped_output; + struct wlr_box mapped_box; // empty if unset + + struct wl_listener motion; + struct wl_listener motion_absolute; + struct wl_listener button; + struct wl_listener axis; + struct wl_listener frame; + struct wl_listener swipe_begin; + struct wl_listener swipe_update; + struct wl_listener swipe_end; + struct wl_listener pinch_begin; + struct wl_listener pinch_update; + struct wl_listener pinch_end; + struct wl_listener hold_begin; + struct wl_listener hold_end; + + struct wl_listener touch_down; + struct wl_listener touch_up; + struct wl_listener touch_motion; + struct wl_listener touch_cancel; + struct wl_listener touch_frame; + + struct wl_listener tablet_tool_axis; + struct wl_listener tablet_tool_proximity; + struct wl_listener tablet_tool_tip; + struct wl_listener tablet_tool_button; + + struct wl_listener destroy; +}; + +struct wlr_cursor_output_cursor { + struct wlr_cursor *cursor; + struct wlr_output_cursor *output_cursor; + struct wl_list link; + + struct wl_listener layout_output_destroy; + + // only when using a surface as the cursor image + struct wl_listener output_commit; + + // only when using an XCursor as the cursor image + struct wlr_xcursor *xcursor; + size_t xcursor_index; + struct wl_event_source *xcursor_timer; +}; + +struct wlr_cursor_state { + struct wlr_cursor cursor; + + struct wl_list devices; // wlr_cursor_device.link + struct wl_list output_cursors; // wlr_cursor_output_cursor.link + struct wlr_output_layout *layout; + struct wlr_output *mapped_output; + struct wlr_box mapped_box; // empty if unset + + struct wl_listener layout_add; + struct wl_listener layout_change; + struct wl_listener layout_destroy; + + // only when using a buffer as the cursor image + struct wlr_buffer *buffer; + struct { + int32_t x, y; + } buffer_hotspot; + float buffer_scale; + + // only when using a surface as the cursor image + struct wlr_surface *surface; + struct { + int32_t x, y; + } surface_hotspot; + struct wl_listener surface_commit; + struct wl_listener surface_destroy; + + // only when using an XCursor as the cursor image + struct wlr_xcursor_manager *xcursor_manager; + char *xcursor_name; +}; + +struct wlr_cursor *wlr_cursor_create(void) { + struct wlr_cursor_state *state = calloc(1, sizeof(*state)); + if (!state) { + wlr_log(WLR_ERROR, "Failed to allocate wlr_cursor_state"); + return NULL; + } + struct wlr_cursor *cur = &state->cursor; + + cur->state = state; + + wl_list_init(&cur->state->devices); + wl_list_init(&cur->state->output_cursors); + + // pointer signals + wl_signal_init(&cur->events.motion); + wl_signal_init(&cur->events.motion_absolute); + wl_signal_init(&cur->events.button); + wl_signal_init(&cur->events.axis); + wl_signal_init(&cur->events.frame); + wl_signal_init(&cur->events.swipe_begin); + wl_signal_init(&cur->events.swipe_update); + wl_signal_init(&cur->events.swipe_end); + wl_signal_init(&cur->events.pinch_begin); + wl_signal_init(&cur->events.pinch_update); + wl_signal_init(&cur->events.pinch_end); + wl_signal_init(&cur->events.hold_begin); + wl_signal_init(&cur->events.hold_end); + + // touch signals + wl_signal_init(&cur->events.touch_up); + wl_signal_init(&cur->events.touch_down); + wl_signal_init(&cur->events.touch_motion); + wl_signal_init(&cur->events.touch_cancel); + wl_signal_init(&cur->events.touch_frame); + + // tablet tool signals + wl_signal_init(&cur->events.tablet_tool_tip); + wl_signal_init(&cur->events.tablet_tool_axis); + wl_signal_init(&cur->events.tablet_tool_button); + wl_signal_init(&cur->events.tablet_tool_proximity); + + wl_list_init(&cur->state->surface_destroy.link); + wl_list_init(&cur->state->surface_commit.link); + + cur->x = 100; + cur->y = 100; + + return cur; +} + +static void cursor_output_cursor_reset_image(struct wlr_cursor_output_cursor *output_cursor); + +static void output_cursor_destroy(struct wlr_cursor_output_cursor *output_cursor) { + cursor_output_cursor_reset_image(output_cursor); + wl_list_remove(&output_cursor->layout_output_destroy.link); + wl_list_remove(&output_cursor->link); + wl_list_remove(&output_cursor->output_commit.link); + wlr_output_cursor_destroy(output_cursor->output_cursor); + free(output_cursor); +} + +static void cursor_detach_output_layout(struct wlr_cursor *cur) { + if (!cur->state->layout) { + return; + } + + struct wlr_cursor_output_cursor *output_cursor, *tmp; + wl_list_for_each_safe(output_cursor, tmp, &cur->state->output_cursors, + link) { + output_cursor_destroy(output_cursor); + } + + wl_list_remove(&cur->state->layout_destroy.link); + wl_list_remove(&cur->state->layout_change.link); + wl_list_remove(&cur->state->layout_add.link); + + cur->state->layout = NULL; +} + +static void cursor_device_destroy(struct wlr_cursor_device *c_device) { + struct wlr_input_device *dev = c_device->device; + switch (dev->type) { + case WLR_INPUT_DEVICE_POINTER: + wl_list_remove(&c_device->motion.link); + wl_list_remove(&c_device->motion_absolute.link); + wl_list_remove(&c_device->button.link); + wl_list_remove(&c_device->axis.link); + wl_list_remove(&c_device->frame.link); + wl_list_remove(&c_device->swipe_begin.link); + wl_list_remove(&c_device->swipe_update.link); + wl_list_remove(&c_device->swipe_end.link); + wl_list_remove(&c_device->pinch_begin.link); + wl_list_remove(&c_device->pinch_update.link); + wl_list_remove(&c_device->pinch_end.link); + wl_list_remove(&c_device->hold_begin.link); + wl_list_remove(&c_device->hold_end.link); + break; + case WLR_INPUT_DEVICE_TOUCH: + wl_list_remove(&c_device->touch_down.link); + wl_list_remove(&c_device->touch_up.link); + wl_list_remove(&c_device->touch_motion.link); + wl_list_remove(&c_device->touch_cancel.link); + wl_list_remove(&c_device->touch_frame.link); + break; + case WLR_INPUT_DEVICE_TABLET: + wl_list_remove(&c_device->tablet_tool_axis.link); + wl_list_remove(&c_device->tablet_tool_proximity.link); + wl_list_remove(&c_device->tablet_tool_tip.link); + wl_list_remove(&c_device->tablet_tool_button.link); + break; + default: + abort(); // unreachable + } + + wl_list_remove(&c_device->link); + wl_list_remove(&c_device->destroy.link); + free(c_device); +} + +static void cursor_reset_image(struct wlr_cursor *cur) { + wlr_buffer_unlock(cur->state->buffer); + cur->state->buffer = NULL; + + if (cur->state->surface != NULL) { + struct wlr_cursor_output_cursor *output_cursor; + wl_list_for_each(output_cursor, &cur->state->output_cursors, link) { + wlr_surface_send_leave(cur->state->surface, + output_cursor->output_cursor->output); + } + } + + wl_list_remove(&cur->state->surface_destroy.link); + wl_list_remove(&cur->state->surface_commit.link); + wl_list_init(&cur->state->surface_destroy.link); + wl_list_init(&cur->state->surface_commit.link); + cur->state->surface = NULL; + + cur->state->xcursor_manager = NULL; + free(cur->state->xcursor_name); + cur->state->xcursor_name = NULL; +} + +void wlr_cursor_destroy(struct wlr_cursor *cur) { + // pointer signals + assert(wl_list_empty(&cur->events.motion.listener_list)); + assert(wl_list_empty(&cur->events.motion_absolute.listener_list)); + assert(wl_list_empty(&cur->events.button.listener_list)); + assert(wl_list_empty(&cur->events.axis.listener_list)); + assert(wl_list_empty(&cur->events.frame.listener_list)); + assert(wl_list_empty(&cur->events.swipe_begin.listener_list)); + assert(wl_list_empty(&cur->events.swipe_update.listener_list)); + assert(wl_list_empty(&cur->events.swipe_end.listener_list)); + assert(wl_list_empty(&cur->events.pinch_begin.listener_list)); + assert(wl_list_empty(&cur->events.pinch_update.listener_list)); + assert(wl_list_empty(&cur->events.pinch_end.listener_list)); + assert(wl_list_empty(&cur->events.hold_begin.listener_list)); + assert(wl_list_empty(&cur->events.hold_end.listener_list)); + + // touch signals + assert(wl_list_empty(&cur->events.touch_up.listener_list)); + assert(wl_list_empty(&cur->events.touch_down.listener_list)); + assert(wl_list_empty(&cur->events.touch_motion.listener_list)); + assert(wl_list_empty(&cur->events.touch_cancel.listener_list)); + assert(wl_list_empty(&cur->events.touch_frame.listener_list)); + + // tablet tool signals + assert(wl_list_empty(&cur->events.tablet_tool_tip.listener_list)); + assert(wl_list_empty(&cur->events.tablet_tool_axis.listener_list)); + assert(wl_list_empty(&cur->events.tablet_tool_button.listener_list)); + assert(wl_list_empty(&cur->events.tablet_tool_proximity.listener_list)); + + cursor_reset_image(cur); + cursor_detach_output_layout(cur); + + struct wlr_cursor_device *device, *device_tmp = NULL; + wl_list_for_each_safe(device, device_tmp, &cur->state->devices, link) { + cursor_device_destroy(device); + } + + free(cur->state); +} + +static struct wlr_cursor_device *get_cursor_device(struct wlr_cursor *cur, + struct wlr_input_device *device) { + struct wlr_cursor_device *c_device, *ret = NULL; + wl_list_for_each(c_device, &cur->state->devices, link) { + if (c_device->device == device) { + ret = c_device; + break; + } + } + + return ret; +} + +static void output_cursor_move(struct wlr_cursor_output_cursor *output_cursor) { + struct wlr_cursor *cur = output_cursor->cursor; + + double output_x = cur->x, output_y = cur->y; + wlr_output_layout_output_coords(cur->state->layout, + output_cursor->output_cursor->output, &output_x, &output_y); + wlr_output_cursor_move(output_cursor->output_cursor, + output_x, output_y); +} + +static void cursor_warp_unchecked(struct wlr_cursor *cur, + double lx, double ly) { + assert(cur->state->layout); + if (!isfinite(lx) || !isfinite(ly)) { + assert(false); + return; + } + + cur->x = lx; + cur->y = ly; + + struct wlr_cursor_output_cursor *output_cursor; + wl_list_for_each(output_cursor, &cur->state->output_cursors, link) { + output_cursor_move(output_cursor); + } +} + +/** + * Get the most specific mapping box for the device in this order: + * + * 1. device geometry mapping + * 2. device output mapping + * 3. cursor geometry mapping + * 4. cursor output mapping + * + * Absolute movement for touch and pen devices will be relative to this box and + * pointer movement will be constrained to this box. + * + * If none of these are set, the box is empty and absolute movement should be + * relative to the extents of the layout. + */ +static void get_mapping(struct wlr_cursor *cur, + struct wlr_input_device *dev, struct wlr_box *box) { + assert(cur->state->layout); + + *box = (struct wlr_box){0}; + + struct wlr_cursor_device *c_device = get_cursor_device(cur, dev); + if (c_device) { + if (!wlr_box_empty(&c_device->mapped_box)) { + *box = c_device->mapped_box; + return; + } + if (c_device->mapped_output) { + wlr_output_layout_get_box(cur->state->layout, + c_device->mapped_output, box); + return; + } + } + + if (!wlr_box_empty(&cur->state->mapped_box)) { + *box = cur->state->mapped_box; + return; + } + if (cur->state->mapped_output) { + wlr_output_layout_get_box(cur->state->layout, + cur->state->mapped_output, box); + return; + } +} + +bool wlr_cursor_warp(struct wlr_cursor *cur, struct wlr_input_device *dev, + double lx, double ly) { + assert(cur->state->layout); + + bool result = false; + struct wlr_box mapping; + get_mapping(cur, dev, &mapping); + if (!wlr_box_empty(&mapping)) { + result = wlr_box_contains_point(&mapping, lx, ly); + } else { + result = wlr_output_layout_contains_point(cur->state->layout, NULL, + lx, ly); + } + + if (result) { + cursor_warp_unchecked(cur, lx, ly); + } + + return result; +} + +void wlr_cursor_warp_closest(struct wlr_cursor *cur, + struct wlr_input_device *dev, double lx, double ly) { + struct wlr_box mapping; + get_mapping(cur, dev, &mapping); + if (!wlr_box_empty(&mapping)) { + wlr_box_closest_point(&mapping, lx, ly, &lx, &ly); + } else if (!wl_list_empty(&cur->state->layout->outputs)) { + wlr_output_layout_closest_point(cur->state->layout, NULL, lx, ly, + &lx, &ly); + } else { + /* + * There is no mapping box for the input device and the + * output layout is empty. This can happen for example + * when external monitors are turned off/disconnected. + * In this case, all (x,y) points are equally invalid, + * so leave the cursor in its current location (better + * from a user standpoint than warping it to (0,0)). + */ + return; + } + + cursor_warp_unchecked(cur, lx, ly); +} + +void wlr_cursor_absolute_to_layout_coords(struct wlr_cursor *cur, + struct wlr_input_device *dev, double x, double y, + double *lx, double *ly) { + assert(cur->state->layout); + + struct wlr_box mapping; + get_mapping(cur, dev, &mapping); + if (wlr_box_empty(&mapping)) { + wlr_output_layout_get_box(cur->state->layout, NULL, &mapping); + } + + *lx = !isnan(x) ? mapping.width * x + mapping.x : cur->x; + *ly = !isnan(y) ? mapping.height * y + mapping.y : cur->y; +} + +void wlr_cursor_warp_absolute(struct wlr_cursor *cur, + struct wlr_input_device *dev, double x, double y) { + assert(cur->state->layout); + + double lx, ly; + wlr_cursor_absolute_to_layout_coords(cur, dev, x, y, &lx, &ly); + + wlr_cursor_warp_closest(cur, dev, lx, ly); +} + +void wlr_cursor_move(struct wlr_cursor *cur, struct wlr_input_device *dev, + double delta_x, double delta_y) { + assert(cur->state->layout); + + double lx = !isnan(delta_x) ? cur->x + delta_x : cur->x; + double ly = !isnan(delta_y) ? cur->y + delta_y : cur->y; + + wlr_cursor_warp_closest(cur, dev, lx, ly); +} + +static void cursor_output_cursor_reset_image(struct wlr_cursor_output_cursor *output_cursor) { + output_cursor->xcursor = NULL; + output_cursor->xcursor_index = 0; + if (output_cursor->xcursor_timer != NULL) { + wl_event_source_remove(output_cursor->xcursor_timer); + } + output_cursor->xcursor_timer = NULL; +} + +static void cursor_update_outputs(struct wlr_cursor *cur); + +void wlr_cursor_set_buffer(struct wlr_cursor *cur, struct wlr_buffer *buffer, + int32_t hotspot_x, int32_t hotspot_y, float scale) { + if (buffer == cur->state->buffer && + hotspot_x == cur->state->buffer_hotspot.x && + hotspot_y == cur->state->buffer_hotspot.y && + scale == cur->state->buffer_scale) { + return; + } + + cursor_reset_image(cur); + + if (buffer != NULL) { + cur->state->buffer = wlr_buffer_lock(buffer); + cur->state->buffer_hotspot.x = hotspot_x; + cur->state->buffer_hotspot.y = hotspot_y; + cur->state->buffer_scale = scale; + } + + cursor_update_outputs(cur); +} + +void wlr_cursor_unset_image(struct wlr_cursor *cur) { + cursor_reset_image(cur); + cursor_update_outputs(cur); +} + +static void output_cursor_set_xcursor_image(struct wlr_cursor_output_cursor *output_cursor, size_t i); + +static int handle_xcursor_timer(void *data) { + struct wlr_cursor_output_cursor *output_cursor = data; + size_t i = (output_cursor->xcursor_index + 1) % output_cursor->xcursor->image_count; + output_cursor_set_xcursor_image(output_cursor, i); + return 0; +} + +static void output_cursor_set_xcursor_image(struct wlr_cursor_output_cursor *output_cursor, size_t i) { + struct wlr_xcursor_image *image = output_cursor->xcursor->images[i]; + + struct wlr_buffer *buffer = wlr_xcursor_image_get_buffer(image); + wlr_output_cursor_set_buffer(output_cursor->output_cursor, buffer, image->hotspot_x, image->hotspot_y); + + output_cursor->xcursor_index = i; + + if (output_cursor->xcursor->image_count == 1 || image->delay == 0) { + return; + } + + if (output_cursor->xcursor_timer == NULL) { + struct wl_event_loop *event_loop = output_cursor->output_cursor->output->event_loop; + output_cursor->xcursor_timer = + wl_event_loop_add_timer(event_loop, handle_xcursor_timer, output_cursor); + if (output_cursor->xcursor_timer == NULL) { + wlr_log(WLR_ERROR, "wl_event_loop_add_timer failed"); + return; + } + } + + wl_event_source_timer_update(output_cursor->xcursor_timer, image->delay); +} + +static void cursor_output_cursor_update(struct wlr_cursor_output_cursor *output_cursor) { + struct wlr_cursor *cur = output_cursor->cursor; + struct wlr_output *output = output_cursor->output_cursor->output; + + cursor_output_cursor_reset_image(output_cursor); + + if (cur->state->buffer != NULL) { + struct wlr_renderer *renderer = output->renderer; + assert(renderer != NULL); + + struct wlr_buffer *buffer = cur->state->buffer; + int32_t hotspot_x = cur->state->buffer_hotspot.x; + int32_t hotspot_y = cur->state->buffer_hotspot.y; + float scale = cur->state->buffer_scale; + + struct wlr_texture *texture = NULL; + struct wlr_fbox src_box = {0}; + int dst_width = 0, dst_height = 0; + if (buffer != NULL) { + texture = wlr_texture_from_buffer(renderer, buffer); + if (texture) { + src_box = (struct wlr_fbox){ + .width = texture->width, + .height = texture->height, + }; + + dst_width = texture->width / scale; + dst_height = texture->height / scale; + } + } + + output_cursor_set_texture(output_cursor->output_cursor, texture, true, + &src_box, dst_width, dst_height, WL_OUTPUT_TRANSFORM_NORMAL, + hotspot_x, hotspot_y, NULL, 0); + } else if (cur->state->surface != NULL) { + struct wlr_surface *surface = cur->state->surface; + + struct wlr_texture *texture = wlr_surface_get_texture(surface); + int32_t hotspot_x = cur->state->surface_hotspot.x; + int32_t hotspot_y = cur->state->surface_hotspot.y; + + struct wlr_fbox src_box; + wlr_surface_get_buffer_source_box(surface, &src_box); + int dst_width = surface->current.width; + int dst_height = surface->current.height; + + struct wlr_linux_drm_syncobj_surface_v1_state *syncobj_surface_state = + wlr_linux_drm_syncobj_v1_get_surface_state(surface); + struct wlr_drm_syncobj_timeline *wait_timeline = NULL; + uint64_t wait_point = 0; + if (syncobj_surface_state != NULL) { + wait_timeline = syncobj_surface_state->acquire_timeline; + wait_point = syncobj_surface_state->acquire_point; + } + + output_cursor_set_texture(output_cursor->output_cursor, texture, false, + &src_box, dst_width, dst_height, surface->current.transform, + hotspot_x, hotspot_y, wait_timeline, wait_point); + + if (syncobj_surface_state != NULL && + surface->buffer != NULL && surface->buffer->source != NULL && + (surface->current.committed & WLR_SURFACE_STATE_BUFFER)) { + wlr_linux_drm_syncobj_v1_state_signal_release_with_buffer(syncobj_surface_state, + surface->buffer->source); + } + + if (output_cursor->output_cursor->visible) { + wlr_surface_send_enter(surface, output); + } else { + wlr_surface_send_leave(surface, output); + } + + float scale = 1; + struct wlr_surface_output *surface_output; + wl_list_for_each(surface_output, &surface->current_outputs, link) { + if (surface_output->output->scale > scale) { + scale = surface_output->output->scale; + } + } + wlr_fractional_scale_v1_notify_scale(surface, scale); + wlr_surface_set_preferred_buffer_scale(surface, ceil(scale)); + } else if (cur->state->xcursor_name != NULL) { + struct wlr_xcursor_manager *manager = cur->state->xcursor_manager; + const char *name = cur->state->xcursor_name; + + float scale = output->scale; + wlr_xcursor_manager_load(manager, scale); + struct wlr_xcursor *xcursor = wlr_xcursor_manager_get_xcursor(manager, name, scale); + if (xcursor == NULL) { + /* Try the default cursor: better the wrong image than an invisible + * (and therefore practically unusable) cursor */ + wlr_log(WLR_DEBUG, "XCursor theme is missing '%s' cursor, falling back to 'default'", name); + xcursor = wlr_xcursor_manager_get_xcursor(manager, "default", scale); + if (xcursor == NULL) { + wlr_log(WLR_DEBUG, "XCursor theme is missing a 'default' cursor"); + wlr_output_cursor_set_buffer(output_cursor->output_cursor, NULL, 0, 0); + return; + } + } + + output_cursor->xcursor = xcursor; + output_cursor_set_xcursor_image(output_cursor, 0); + } else { + wlr_output_cursor_set_buffer(output_cursor->output_cursor, NULL, 0, 0); + } +} + +static void output_cursor_output_handle_output_commit( + struct wl_listener *listener, void *data) { + struct wlr_cursor_output_cursor *output_cursor = + wl_container_of(listener, output_cursor, output_commit); + const struct wlr_output_event_commit *event = data; + + if (event->state->committed & (WLR_OUTPUT_STATE_SCALE | WLR_OUTPUT_STATE_TRANSFORM + | WLR_OUTPUT_STATE_ENABLED | WLR_OUTPUT_STATE_IMAGE_DESCRIPTION)) { + cursor_output_cursor_update(output_cursor); + } + + struct wlr_surface *surface = output_cursor->cursor->state->surface; + if (surface && output_cursor->output_cursor->visible && + (event->state->committed & WLR_OUTPUT_STATE_BUFFER)) { + wlr_surface_send_frame_done(surface, &event->when); + } +} + +static void cursor_update_outputs(struct wlr_cursor *cur) { + struct wlr_cursor_output_cursor *output_cursor; + wl_list_for_each(output_cursor, &cur->state->output_cursors, link) { + cursor_output_cursor_update(output_cursor); + } +} + +void wlr_cursor_set_xcursor(struct wlr_cursor *cur, + struct wlr_xcursor_manager *manager, const char *name) { + if (manager == cur->state->xcursor_manager && + cur->state->xcursor_name != NULL && + strcmp(name, cur->state->xcursor_name) == 0) { + return; + } + + cursor_reset_image(cur); + + cur->state->xcursor_manager = manager; + cur->state->xcursor_name = strdup(name); + + cursor_update_outputs(cur); +} + +static void cursor_handle_surface_destroy(struct wl_listener *listener, void *data) { + struct wlr_cursor_state *state = wl_container_of(listener, state, surface_destroy); + assert(state->surface != NULL); + wlr_cursor_unset_image(&state->cursor); +} + +static void cursor_handle_surface_commit(struct wl_listener *listener, void *data) { + struct wlr_cursor_state *state = wl_container_of(listener, state, surface_commit); + struct wlr_surface *surface = state->surface; + + state->surface_hotspot.x -= surface->current.dx; + state->surface_hotspot.y -= surface->current.dy; + + cursor_update_outputs(&state->cursor); +} + +void wlr_cursor_set_surface(struct wlr_cursor *cur, struct wlr_surface *surface, + int32_t hotspot_x, int32_t hotspot_y) { + if (surface == NULL) { + wlr_cursor_unset_image(cur); + return; + } + + if (surface == cur->state->surface && + hotspot_x == cur->state->surface_hotspot.x && + hotspot_y == cur->state->surface_hotspot.y) { + return; + } + + if (surface != cur->state->surface) { + // Only send wl_surface.leave if the surface changes + cursor_reset_image(cur); + + cur->state->surface = surface; + + wl_signal_add(&surface->events.destroy, &cur->state->surface_destroy); + cur->state->surface_destroy.notify = cursor_handle_surface_destroy; + wl_signal_add(&surface->events.commit, &cur->state->surface_commit); + cur->state->surface_commit.notify = cursor_handle_surface_commit; + } + + cur->state->surface_hotspot.x = hotspot_x; + cur->state->surface_hotspot.y = hotspot_y; + + cursor_update_outputs(cur); +} + +static void handle_pointer_motion(struct wl_listener *listener, void *data) { + struct wlr_pointer_motion_event *event = data; + struct wlr_cursor_device *device = + wl_container_of(listener, device, motion); + wl_signal_emit_mutable(&device->cursor->events.motion, event); +} + +static void apply_output_transform(double *x, double *y, + enum wl_output_transform transform) { + double dx = 0.0, dy = 0.0; + double width = 1.0, height = 1.0; + + switch (transform) { + case WL_OUTPUT_TRANSFORM_NORMAL: + dx = *x; + dy = *y; + break; + case WL_OUTPUT_TRANSFORM_90: + dx = height - *y; + dy = *x; + break; + case WL_OUTPUT_TRANSFORM_180: + dx = width - *x; + dy = height - *y; + break; + case WL_OUTPUT_TRANSFORM_270: + dx = *y; + dy = width - *x; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED: + dx = width - *x; + dy = *y; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED_90: + dx = *y; + dy = *x; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED_180: + dx = *x; + dy = height - *y; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED_270: + dx = height - *y; + dy = width - *x; + break; + } + *x = dx; + *y = dy; +} + + +static struct wlr_output *get_mapped_output(struct wlr_cursor_device *cursor_device) { + if (cursor_device->mapped_output) { + return cursor_device->mapped_output; + } + + struct wlr_cursor *cursor = cursor_device->cursor; + assert(cursor); + if (cursor->state->mapped_output) { + return cursor->state->mapped_output; + } + return NULL; +} + + +static void handle_pointer_motion_absolute(struct wl_listener *listener, + void *data) { + struct wlr_pointer_motion_absolute_event *event = data; + struct wlr_cursor_device *device = + wl_container_of(listener, device, motion_absolute); + + struct wlr_output *output = + get_mapped_output(device); + if (output) { + apply_output_transform(&event->x, &event->y, output->transform); + } + wl_signal_emit_mutable(&device->cursor->events.motion_absolute, event); +} + +static void handle_pointer_button(struct wl_listener *listener, void *data) { + struct wlr_pointer_button_event *event = data; + struct wlr_cursor_device *device = + wl_container_of(listener, device, button); + wl_signal_emit_mutable(&device->cursor->events.button, event); +} + +static void handle_pointer_axis(struct wl_listener *listener, void *data) { + struct wlr_pointer_axis_event *event = data; + struct wlr_cursor_device *device = wl_container_of(listener, device, axis); + wl_signal_emit_mutable(&device->cursor->events.axis, event); +} + +static void handle_pointer_frame(struct wl_listener *listener, void *data) { + struct wlr_cursor_device *device = wl_container_of(listener, device, frame); + wl_signal_emit_mutable(&device->cursor->events.frame, device->cursor); +} + +static void handle_pointer_swipe_begin(struct wl_listener *listener, void *data) { + struct wlr_pointer_swipe_begin_event *event = data; + struct wlr_cursor_device *device = wl_container_of(listener, device, swipe_begin); + wl_signal_emit_mutable(&device->cursor->events.swipe_begin, event); +} + +static void handle_pointer_swipe_update(struct wl_listener *listener, void *data) { + struct wlr_pointer_swipe_update_event *event = data; + struct wlr_cursor_device *device = wl_container_of(listener, device, swipe_update); + wl_signal_emit_mutable(&device->cursor->events.swipe_update, event); +} + +static void handle_pointer_swipe_end(struct wl_listener *listener, void *data) { + struct wlr_pointer_swipe_end_event *event = data; + struct wlr_cursor_device *device = wl_container_of(listener, device, swipe_end); + wl_signal_emit_mutable(&device->cursor->events.swipe_end, event); +} + +static void handle_pointer_pinch_begin(struct wl_listener *listener, void *data) { + struct wlr_pointer_pinch_begin_event *event = data; + struct wlr_cursor_device *device = wl_container_of(listener, device, pinch_begin); + wl_signal_emit_mutable(&device->cursor->events.pinch_begin, event); +} + +static void handle_pointer_pinch_update(struct wl_listener *listener, void *data) { + struct wlr_pointer_pinch_update_event *event = data; + struct wlr_cursor_device *device = wl_container_of(listener, device, pinch_update); + wl_signal_emit_mutable(&device->cursor->events.pinch_update, event); +} + +static void handle_pointer_pinch_end(struct wl_listener *listener, void *data) { + struct wlr_pointer_pinch_end_event *event = data; + struct wlr_cursor_device *device = wl_container_of(listener, device, pinch_end); + wl_signal_emit_mutable(&device->cursor->events.pinch_end, event); +} + +static void handle_pointer_hold_begin(struct wl_listener *listener, void *data) { + struct wlr_pointer_hold_begin_event *event = data; + struct wlr_cursor_device *device = wl_container_of(listener, device, hold_begin); + wl_signal_emit_mutable(&device->cursor->events.hold_begin, event); +} + +static void handle_pointer_hold_end(struct wl_listener *listener, void *data) { + struct wlr_pointer_hold_end_event *event = data; + struct wlr_cursor_device *device = wl_container_of(listener, device, hold_end); + wl_signal_emit_mutable(&device->cursor->events.hold_end, event); +} + +static void handle_touch_up(struct wl_listener *listener, void *data) { + struct wlr_touch_up_event *event = data; + struct wlr_cursor_device *device; + device = wl_container_of(listener, device, touch_up); + wl_signal_emit_mutable(&device->cursor->events.touch_up, event); +} + +static void handle_touch_down(struct wl_listener *listener, void *data) { + struct wlr_touch_down_event *event = data; + struct wlr_cursor_device *device; + device = wl_container_of(listener, device, touch_down); + + struct wlr_output *output = + get_mapped_output(device); + if (output) { + apply_output_transform(&event->x, &event->y, output->transform); + } + wl_signal_emit_mutable(&device->cursor->events.touch_down, event); +} + +static void handle_touch_motion(struct wl_listener *listener, void *data) { + struct wlr_touch_motion_event *event = data; + struct wlr_cursor_device *device; + device = wl_container_of(listener, device, touch_motion); + + struct wlr_output *output = + get_mapped_output(device); + if (output) { + apply_output_transform(&event->x, &event->y, output->transform); + } + wl_signal_emit_mutable(&device->cursor->events.touch_motion, event); +} + +static void handle_touch_cancel(struct wl_listener *listener, void *data) { + struct wlr_touch_cancel_event *event = data; + struct wlr_cursor_device *device; + device = wl_container_of(listener, device, touch_cancel); + wl_signal_emit_mutable(&device->cursor->events.touch_cancel, event); +} + +static void handle_touch_frame(struct wl_listener *listener, void *data) { + struct wlr_cursor_device *device = + wl_container_of(listener, device, touch_frame); + wl_signal_emit_mutable(&device->cursor->events.touch_frame, NULL); +} + +static void handle_tablet_tool_tip(struct wl_listener *listener, void *data) { + struct wlr_tablet_tool_tip_event *event = data; + struct wlr_cursor_device *device; + device = wl_container_of(listener, device, tablet_tool_tip); + + struct wlr_output *output = + get_mapped_output(device); + if (output) { + apply_output_transform(&event->x, &event->y, output->transform); + } + wl_signal_emit_mutable(&device->cursor->events.tablet_tool_tip, event); +} + +static void handle_tablet_tool_axis(struct wl_listener *listener, void *data) { + struct wlr_tablet_tool_axis_event *event = data; + struct wlr_cursor_device *device; + device = wl_container_of(listener, device, tablet_tool_axis); + + struct wlr_output *output = get_mapped_output(device); + if (output) { + // In the case that only one axis received an event, rotating the input can + // cause the change to actually happen on the other axis, as far as clients + // are concerned. + // + // Here, we feed apply_output_transform NAN on the axis that didn't change, + // and remap the axes flags based on whether it returns NAN itself. + double x = event->updated_axes & WLR_TABLET_TOOL_AXIS_X ? event->x : NAN; + double y = event->updated_axes & WLR_TABLET_TOOL_AXIS_Y ? event->y : NAN; + + apply_output_transform(&x, &y, output->transform); + + event->updated_axes &= ~(WLR_TABLET_TOOL_AXIS_X | WLR_TABLET_TOOL_AXIS_Y); + event->x = event->y = 0; + + if (!isnan(x)) { + event->updated_axes |= WLR_TABLET_TOOL_AXIS_X; + event->x = x; + } + + if (!isnan(y)) { + event->updated_axes |= WLR_TABLET_TOOL_AXIS_Y; + event->y = y; + } + } + + wl_signal_emit_mutable(&device->cursor->events.tablet_tool_axis, event); +} + +static void handle_tablet_tool_button(struct wl_listener *listener, + void *data) { + struct wlr_tablet_tool_button_event *event = data; + struct wlr_cursor_device *device; + device = wl_container_of(listener, device, tablet_tool_button); + wl_signal_emit_mutable(&device->cursor->events.tablet_tool_button, event); +} + +static void handle_tablet_tool_proximity(struct wl_listener *listener, + void *data) { + struct wlr_tablet_tool_proximity_event *event = data; + struct wlr_cursor_device *device; + device = wl_container_of(listener, device, tablet_tool_proximity); + + struct wlr_output *output = + get_mapped_output(device); + if (output) { + apply_output_transform(&event->x, &event->y, output->transform); + } + wl_signal_emit_mutable(&device->cursor->events.tablet_tool_proximity, event); +} + +static void handle_device_destroy(struct wl_listener *listener, void *data) { + struct wlr_cursor_device *c_device; + c_device = wl_container_of(listener, c_device, destroy); + wlr_cursor_detach_input_device(c_device->cursor, c_device->device); +} + +static struct wlr_cursor_device *cursor_device_create( + struct wlr_cursor *cursor, struct wlr_input_device *device) { + struct wlr_cursor_device *c_device = calloc(1, sizeof(*c_device)); + if (!c_device) { + wlr_log(WLR_ERROR, "Failed to allocate wlr_cursor_device"); + return NULL; + } + + c_device->cursor = cursor; + c_device->device = device; + + // listen to events + wl_signal_add(&device->events.destroy, &c_device->destroy); + c_device->destroy.notify = handle_device_destroy; + + switch (device->type) { + case WLR_INPUT_DEVICE_POINTER:; + struct wlr_pointer *pointer = wlr_pointer_from_input_device(device); + + wl_signal_add(&pointer->events.motion, &c_device->motion); + c_device->motion.notify = handle_pointer_motion; + + wl_signal_add(&pointer->events.motion_absolute, + &c_device->motion_absolute); + c_device->motion_absolute.notify = handle_pointer_motion_absolute; + + wl_signal_add(&pointer->events.button, &c_device->button); + c_device->button.notify = handle_pointer_button; + + wl_signal_add(&pointer->events.axis, &c_device->axis); + c_device->axis.notify = handle_pointer_axis; + + wl_signal_add(&pointer->events.frame, &c_device->frame); + c_device->frame.notify = handle_pointer_frame; + + wl_signal_add(&pointer->events.swipe_begin, &c_device->swipe_begin); + c_device->swipe_begin.notify = handle_pointer_swipe_begin; + + wl_signal_add(&pointer->events.swipe_update, &c_device->swipe_update); + c_device->swipe_update.notify = handle_pointer_swipe_update; + + wl_signal_add(&pointer->events.swipe_end, &c_device->swipe_end); + c_device->swipe_end.notify = handle_pointer_swipe_end; + + wl_signal_add(&pointer->events.pinch_begin, &c_device->pinch_begin); + c_device->pinch_begin.notify = handle_pointer_pinch_begin; + + wl_signal_add(&pointer->events.pinch_update, &c_device->pinch_update); + c_device->pinch_update.notify = handle_pointer_pinch_update; + + wl_signal_add(&pointer->events.pinch_end, &c_device->pinch_end); + c_device->pinch_end.notify = handle_pointer_pinch_end; + + wl_signal_add(&pointer->events.hold_begin, &c_device->hold_begin); + c_device->hold_begin.notify = handle_pointer_hold_begin; + + wl_signal_add(&pointer->events.hold_end, &c_device->hold_end); + c_device->hold_end.notify = handle_pointer_hold_end; + + break; + case WLR_INPUT_DEVICE_TOUCH:; + struct wlr_touch *touch = wlr_touch_from_input_device(device); + + wl_signal_add(&touch->events.motion, &c_device->touch_motion); + c_device->touch_motion.notify = handle_touch_motion; + + wl_signal_add(&touch->events.down, &c_device->touch_down); + c_device->touch_down.notify = handle_touch_down; + + wl_signal_add(&touch->events.up, &c_device->touch_up); + c_device->touch_up.notify = handle_touch_up; + + wl_signal_add(&touch->events.cancel, &c_device->touch_cancel); + c_device->touch_cancel.notify = handle_touch_cancel; + + wl_signal_add(&touch->events.frame, &c_device->touch_frame); + c_device->touch_frame.notify = handle_touch_frame; + + break; + case WLR_INPUT_DEVICE_TABLET:; + struct wlr_tablet *tablet = wlr_tablet_from_input_device(device); + + wl_signal_add(&tablet->events.tip, &c_device->tablet_tool_tip); + c_device->tablet_tool_tip.notify = handle_tablet_tool_tip; + + wl_signal_add(&tablet->events.proximity, + &c_device->tablet_tool_proximity); + c_device->tablet_tool_proximity.notify = handle_tablet_tool_proximity; + + wl_signal_add(&tablet->events.axis, &c_device->tablet_tool_axis); + c_device->tablet_tool_axis.notify = handle_tablet_tool_axis; + + wl_signal_add(&tablet->events.button, &c_device->tablet_tool_button); + c_device->tablet_tool_button.notify = handle_tablet_tool_button; + + break; + + default: + abort(); // unreachable + } + + wl_list_insert(&cursor->state->devices, &c_device->link); + + return c_device; +} + +void wlr_cursor_attach_input_device(struct wlr_cursor *cur, + struct wlr_input_device *dev) { + switch (dev->type) { + case WLR_INPUT_DEVICE_POINTER: + case WLR_INPUT_DEVICE_TOUCH: + case WLR_INPUT_DEVICE_TABLET: + break; + default: + wlr_log(WLR_ERROR, "only device types of pointer, touch or tablet tool" + "are supported"); + return; + } + + // make sure it is not already attached + struct wlr_cursor_device *_dev; + wl_list_for_each(_dev, &cur->state->devices, link) { + if (_dev->device == dev) { + return; + } + } + + cursor_device_create(cur, dev); +} + +void wlr_cursor_detach_input_device(struct wlr_cursor *cur, + struct wlr_input_device *dev) { + struct wlr_cursor_device *c_device, *tmp = NULL; + wl_list_for_each_safe(c_device, tmp, &cur->state->devices, link) { + if (c_device->device == dev) { + cursor_device_destroy(c_device); + } + } +} + +static void handle_layout_destroy(struct wl_listener *listener, void *data) { + struct wlr_cursor_state *state = + wl_container_of(listener, state, layout_destroy); + cursor_detach_output_layout(&state->cursor); +} + +static void handle_layout_output_destroy(struct wl_listener *listener, + void *data) { + struct wlr_cursor_output_cursor *output_cursor = + wl_container_of(listener, output_cursor, layout_output_destroy); + output_cursor_destroy(output_cursor); +} + +static void layout_add(struct wlr_cursor_state *state, + struct wlr_output_layout_output *l_output) { + struct wlr_cursor_output_cursor *output_cursor; + wl_list_for_each(output_cursor, &state->output_cursors, link) { + if (output_cursor->output_cursor->output == l_output->output) { + return; // already added + } + } + + output_cursor = calloc(1, sizeof(*output_cursor)); + if (output_cursor == NULL) { + wlr_log(WLR_ERROR, "Failed to allocate wlr_cursor_output_cursor"); + return; + } + output_cursor->cursor = &state->cursor; + + output_cursor->output_cursor = wlr_output_cursor_create(l_output->output); + if (output_cursor->output_cursor == NULL) { + wlr_log(WLR_ERROR, "Failed to create wlr_output_cursor"); + free(output_cursor); + return; + } + + output_cursor->layout_output_destroy.notify = handle_layout_output_destroy; + wl_signal_add(&l_output->events.destroy, + &output_cursor->layout_output_destroy); + + wl_list_insert(&state->output_cursors, &output_cursor->link); + + wl_signal_add(&output_cursor->output_cursor->output->events.commit, + &output_cursor->output_commit); + output_cursor->output_commit.notify = output_cursor_output_handle_output_commit; + + output_cursor_move(output_cursor); + cursor_output_cursor_update(output_cursor); +} + +static void handle_layout_add(struct wl_listener *listener, void *data) { + struct wlr_cursor_state *state = + wl_container_of(listener, state, layout_add); + struct wlr_output_layout_output *l_output = data; + layout_add(state, l_output); +} + +static void handle_layout_change(struct wl_listener *listener, void *data) { + struct wlr_cursor_state *state = + wl_container_of(listener, state, layout_change); + struct wlr_output_layout *layout = data; + + if (!wlr_output_layout_contains_point(layout, NULL, state->cursor.x, + state->cursor.y) && !wl_list_empty(&layout->outputs)) { + // the output we were on has gone away so go to the closest boundary + // point (unless the layout is empty; compare warp_closest()) + double x, y; + wlr_output_layout_closest_point(layout, NULL, state->cursor.x, + state->cursor.y, &x, &y); + + cursor_warp_unchecked(&state->cursor, x, y); + } +} + +void wlr_cursor_attach_output_layout(struct wlr_cursor *cur, + struct wlr_output_layout *l) { + cursor_detach_output_layout(cur); + + if (l == NULL) { + return; + } + + wl_signal_add(&l->events.add, &cur->state->layout_add); + cur->state->layout_add.notify = handle_layout_add; + wl_signal_add(&l->events.change, &cur->state->layout_change); + cur->state->layout_change.notify = handle_layout_change; + wl_signal_add(&l->events.destroy, &cur->state->layout_destroy); + cur->state->layout_destroy.notify = handle_layout_destroy; + + cur->state->layout = l; + + struct wlr_output_layout_output *l_output; + wl_list_for_each(l_output, &l->outputs, link) { + layout_add(cur->state, l_output); + } +} + +void wlr_cursor_map_to_output(struct wlr_cursor *cur, + struct wlr_output *output) { + cur->state->mapped_output = output; +} + +void wlr_cursor_map_input_to_output(struct wlr_cursor *cur, + struct wlr_input_device *dev, struct wlr_output *output) { + struct wlr_cursor_device *c_device = get_cursor_device(cur, dev); + if (!c_device) { + wlr_log(WLR_ERROR, "Cannot map device \"%s\" to output" + " (not found in this cursor)", dev->name); + return; + } + + c_device->mapped_output = output; +} + +void wlr_cursor_map_to_region(struct wlr_cursor *cur, + const struct wlr_box *box) { + cur->state->mapped_box = wlr_box_empty(box) ? (struct wlr_box){0} : *box; +} + +void wlr_cursor_map_input_to_region(struct wlr_cursor *cur, + struct wlr_input_device *dev, const struct wlr_box *box) { + struct wlr_cursor_device *c_device = get_cursor_device(cur, dev); + if (!c_device) { + wlr_log(WLR_ERROR, "Cannot map device \"%s\" to geometry (not found in" + "this cursor)", dev->name); + return; + } + + c_device->mapped_box = wlr_box_empty(box) ? (struct wlr_box){0} : *box; +} diff --git a/3rdparty/wlroots/types/wlr_cursor_shape_v1.c b/3rdparty/wlroots/types/wlr_cursor_shape_v1.c new file mode 100644 index 0000000000..320acff6d1 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_cursor_shape_v1.c @@ -0,0 +1,284 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cursor-shape-v1-protocol.h" +#include "types/wlr_tablet_v2.h" +#include "util/global.h" + +#define CURSOR_SHAPE_MANAGER_V1_VERSION 2 + +struct wlr_cursor_shape_device_v1 { + struct wl_resource *resource; + struct wlr_cursor_shape_manager_v1 *manager; + enum wlr_cursor_shape_manager_v1_device_type type; + struct wlr_seat_client *seat_client; + // NULL if device_type is not TABLET_TOOL + struct wlr_tablet_v2_tablet_tool *tablet_tool; + + struct wl_listener seat_client_destroy; + struct wl_listener tablet_tool_destroy; +}; + +static const struct wp_cursor_shape_device_v1_interface device_impl; +static const struct wp_cursor_shape_manager_v1_interface manager_impl; + +// Returns NULL if the resource is inert +static struct wlr_cursor_shape_device_v1 *device_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wp_cursor_shape_device_v1_interface, &device_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_cursor_shape_manager_v1 *manager_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wp_cursor_shape_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void resource_handle_destroy(struct wl_client *client, struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void device_handle_set_shape(struct wl_client *client, struct wl_resource *device_resource, + uint32_t serial, uint32_t shape) { + struct wlr_cursor_shape_device_v1 *device = device_from_resource(device_resource); + if (device == NULL) { + return; + } + + uint32_t version = wl_resource_get_version(device_resource); + if (!wp_cursor_shape_device_v1_shape_is_valid(shape, version)) { + wl_resource_post_error(device_resource, WP_CURSOR_SHAPE_DEVICE_V1_ERROR_INVALID_SHAPE, + "Invalid shape %"PRIu32, shape); + return; + } + + struct wlr_cursor_shape_manager_v1_request_set_shape_event event = { + .seat_client = device->seat_client, + .device_type = device->type, + .tablet_tool = device->tablet_tool, + .serial = serial, + .shape = shape, + }; + wl_signal_emit_mutable(&device->manager->events.request_set_shape, &event); +} + +static const struct wp_cursor_shape_device_v1_interface device_impl = { + .destroy = resource_handle_destroy, + .set_shape = device_handle_set_shape, +}; + +static void device_destroy(struct wlr_cursor_shape_device_v1 *device) { + if (device == NULL) { + return; + } + wl_list_remove(&device->seat_client_destroy.link); + wl_list_remove(&device->tablet_tool_destroy.link); + wl_resource_set_user_data(device->resource, NULL); // make inert + free(device); +} + +static void device_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_cursor_shape_device_v1 *device = device_from_resource(resource); + device_destroy(device); +} + +static void device_handle_seat_client_destroy(struct wl_listener *listener, void *data) { + struct wlr_cursor_shape_device_v1 *device = wl_container_of(listener, device, seat_client_destroy); + device_destroy(device); +} + +static void device_handle_tablet_tool_destroy(struct wl_listener *listener, void *data) { + struct wlr_cursor_shape_device_v1 *device = wl_container_of(listener, device, tablet_tool_destroy); + device_destroy(device); +} + +static void create_device(struct wl_resource *manager_resource, uint32_t id, + struct wlr_seat_client *seat_client, + enum wlr_cursor_shape_manager_v1_device_type type, + struct wlr_tablet_v2_tablet_tool *tablet_tool) { + struct wlr_cursor_shape_manager_v1 *manager = manager_from_resource(manager_resource); + + struct wl_client *client = wl_resource_get_client(manager_resource); + uint32_t version = wl_resource_get_version(manager_resource); + struct wl_resource *device_resource = wl_resource_create(client, + &wp_cursor_shape_device_v1_interface, version, id); + if (device_resource == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + wl_resource_set_implementation(device_resource, + &device_impl, NULL, device_handle_resource_destroy); + + if (seat_client == NULL) { + return; // leave the resource inert + } + + struct wlr_cursor_shape_device_v1 *device = calloc(1, sizeof(*device)); + if (device == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + + assert((type == WLR_CURSOR_SHAPE_MANAGER_V1_DEVICE_TYPE_TABLET_TOOL) == + (tablet_tool != NULL)); + + device->resource = device_resource; + device->manager = manager; + device->type = type; + device->tablet_tool = tablet_tool; + device->seat_client = seat_client; + + device->seat_client_destroy.notify = device_handle_seat_client_destroy; + wl_signal_add(&seat_client->events.destroy, &device->seat_client_destroy); + + if (tablet_tool != NULL) { + device->tablet_tool_destroy.notify = device_handle_tablet_tool_destroy; + wl_signal_add(&tablet_tool->wlr_tool->events.destroy, &device->tablet_tool_destroy); + } else { + wl_list_init(&device->tablet_tool_destroy.link); + } + + wl_resource_set_user_data(device_resource, device); +} + +static void manager_handle_get_pointer(struct wl_client *client, struct wl_resource *manager_resource, + uint32_t id, struct wl_resource *pointer_resource) { + struct wlr_seat_client *seat_client = wlr_seat_client_from_pointer_resource(pointer_resource); + create_device(manager_resource, id, seat_client, + WLR_CURSOR_SHAPE_MANAGER_V1_DEVICE_TYPE_POINTER, NULL); +} + +static void manager_handle_get_tablet_tool_v2(struct wl_client *client, struct wl_resource *manager_resource, + uint32_t id, struct wl_resource *tablet_tool_resource) { + struct wlr_tablet_tool_client_v2 *tablet_tool_client = tablet_tool_client_from_resource(tablet_tool_resource); + + struct wlr_seat_client *seat_client = NULL; + struct wlr_tablet_v2_tablet_tool *tablet_tool = NULL; + if (tablet_tool_client != NULL && tablet_tool_client->tool != NULL) { + seat_client = tablet_tool_client->seat->seat_client; + tablet_tool = tablet_tool_client->tool; + } + + create_device(manager_resource, id, seat_client, + WLR_CURSOR_SHAPE_MANAGER_V1_DEVICE_TYPE_TABLET_TOOL, tablet_tool); +} + +static const struct wp_cursor_shape_manager_v1_interface manager_impl = { + .destroy = resource_handle_destroy, + .get_pointer = manager_handle_get_pointer, + .get_tablet_tool_v2 = manager_handle_get_tablet_tool_v2, +}; + +static void manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_cursor_shape_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &wp_cursor_shape_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, manager, NULL); +} + +static void cursor_shape_manager_v1_destroy(struct wlr_cursor_shape_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, NULL); + + assert(wl_list_empty(&manager->events.request_set_shape.listener_list)); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + wl_list_remove(&manager->display_destroy.link); + free(manager); +} + +void wlr_cursor_shape_manager_v1_destroy(struct wlr_cursor_shape_manager_v1 *manager, + bool destroy_global_safe) { + cursor_shape_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_cursor_shape_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + cursor_shape_manager_v1_destroy(manager, false); +} + +struct wlr_cursor_shape_manager_v1 *wlr_cursor_shape_manager_v1_create( + struct wl_display *display, uint32_t version) { + assert(version <= CURSOR_SHAPE_MANAGER_V1_VERSION); + + struct wlr_cursor_shape_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + manager->global = wl_global_create(display, + &wp_cursor_shape_manager_v1_interface, version, manager, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + wl_signal_init(&manager->events.request_set_shape); + wl_signal_init(&manager->events.destroy); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} + +static const char *const shape_names[] = { + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT] = "default", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CONTEXT_MENU] = "context-menu", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_HELP] = "help", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_POINTER] = "pointer", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_PROGRESS] = "progress", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_WAIT] = "wait", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CELL] = "cell", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_CROSSHAIR] = "crosshair", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_TEXT] = "text", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_VERTICAL_TEXT] = "vertical-text", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ALIAS] = "alias", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_COPY] = "copy", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_MOVE] = "move", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NO_DROP] = "no-drop", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NOT_ALLOWED] = "not-allowed", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_GRAB] = "grab", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_GRABBING] = "grabbing", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_E_RESIZE] = "e-resize", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_N_RESIZE] = "n-resize", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NE_RESIZE] = "ne-resize", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NW_RESIZE] = "nw-resize", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_S_RESIZE] = "s-resize", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_SE_RESIZE] = "se-resize", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_SW_RESIZE] = "sw-resize", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_W_RESIZE] = "w-resize", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_EW_RESIZE] = "ew-resize", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NS_RESIZE] = "ns-resize", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NESW_RESIZE] = "nesw-resize", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_NWSE_RESIZE] = "nwse-resize", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_COL_RESIZE] = "col-resize", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ROW_RESIZE] = "row-resize", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ALL_SCROLL] = "all-scroll", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ZOOM_IN] = "zoom-in", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ZOOM_OUT] = "zoom-out", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DND_ASK] = "dnd-ask", + [WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ALL_RESIZE] = "all-resize", +}; + +const char *wlr_cursor_shape_v1_name(enum wp_cursor_shape_device_v1_shape shape) { + assert(shape < sizeof(shape_names) / sizeof(shape_names[0])); + return shape_names[shape]; +} diff --git a/3rdparty/wlroots/types/wlr_damage_ring.c b/3rdparty/wlroots/types/wlr_damage_ring.c new file mode 100644 index 0000000000..b5be7391b8 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_damage_ring.c @@ -0,0 +1,130 @@ +#include +#include +#include +#include +#include +#include +#include + +#define WLR_DAMAGE_RING_MAX_RECTS 20 + +void wlr_damage_ring_init(struct wlr_damage_ring *ring) { + *ring = (struct wlr_damage_ring){ 0 }; + pixman_region32_init(&ring->current); + wl_list_init(&ring->buffers); +} + +static void buffer_destroy(struct wlr_damage_ring_buffer *entry) { + wl_list_remove(&entry->destroy.link); + wl_list_remove(&entry->link); + pixman_region32_fini(&entry->damage); + free(entry); +} + +void wlr_damage_ring_finish(struct wlr_damage_ring *ring) { + pixman_region32_fini(&ring->current); + struct wlr_damage_ring_buffer *entry, *tmp_entry; + wl_list_for_each_safe(entry, tmp_entry, &ring->buffers, link) { + buffer_destroy(entry); + } +} + +void wlr_damage_ring_add(struct wlr_damage_ring *ring, + const pixman_region32_t *damage) { + pixman_region32_union(&ring->current, &ring->current, damage); +} + +void wlr_damage_ring_add_box(struct wlr_damage_ring *ring, + const struct wlr_box *box) { + pixman_region32_union_rect(&ring->current, + &ring->current, box->x, box->y, + box->width, box->height); +} + +void wlr_damage_ring_add_whole(struct wlr_damage_ring *ring) { + int width = 0; + int height = 0; + + struct wlr_damage_ring_buffer *entry; + wl_list_for_each(entry, &ring->buffers, link) { + width = width < entry->buffer->width ? entry->buffer->width : width; + height = height < entry->buffer->height ? entry->buffer->height : height; + } + + pixman_region32_union_rect(&ring->current, + &ring->current, 0, 0, width, height); +} + +static void entry_squash_damage(struct wlr_damage_ring_buffer *entry) { + pixman_region32_t *prev; + if (entry->link.prev == &entry->ring->buffers) { + // this entry is the first in the list + prev = &entry->ring->current; + } else { + struct wlr_damage_ring_buffer *last = + wl_container_of(entry->link.prev, last, link); + prev = &last->damage; + } + + pixman_region32_union(prev, prev, &entry->damage); +} + +static void buffer_handle_destroy(struct wl_listener *listener, void *data) { + struct wlr_damage_ring_buffer *entry = wl_container_of(listener, entry, destroy); + entry_squash_damage(entry); + buffer_destroy(entry); +} + +void wlr_damage_ring_rotate_buffer(struct wlr_damage_ring *ring, + struct wlr_buffer *buffer, pixman_region32_t *damage) { + pixman_region32_copy(damage, &ring->current); + + struct wlr_damage_ring_buffer *entry; + wl_list_for_each(entry, &ring->buffers, link) { + if (entry->buffer != buffer) { + pixman_region32_union(damage, damage, &entry->damage); + continue; + } + + pixman_region32_intersect_rect(damage, damage, 0, 0, buffer->width, buffer->height); + + // Check the number of rectangles + int n_rects = pixman_region32_n_rects(damage); + if (n_rects > WLR_DAMAGE_RING_MAX_RECTS) { + pixman_box32_t *extents = pixman_region32_extents(damage); + pixman_region32_union_rect(damage, damage, + extents->x1, extents->y1, + extents->x2 - extents->x1, + extents->y2 - extents->y1); + } + + // rotate + entry_squash_damage(entry); + pixman_region32_copy(&entry->damage, &ring->current); + pixman_region32_clear(&ring->current); + + wl_list_remove(&entry->link); + wl_list_insert(&ring->buffers, &entry->link); + return; + } + + pixman_region32_clear(damage); + pixman_region32_union_rect(damage, damage, + 0, 0, buffer->width, buffer->height); + + entry = calloc(1, sizeof(*entry)); + if (!entry) { + return; + } + + pixman_region32_init(&entry->damage); + pixman_region32_copy(&entry->damage, &ring->current); + pixman_region32_clear(&ring->current); + + wl_list_insert(&ring->buffers, &entry->link); + entry->buffer = buffer; + entry->ring = ring; + + entry->destroy.notify = buffer_handle_destroy; + wl_signal_add(&buffer->events.destroy, &entry->destroy); +} diff --git a/3rdparty/wlroots/types/wlr_data_control_v1.c b/3rdparty/wlroots/types/wlr_data_control_v1.c new file mode 100644 index 0000000000..66bcd41482 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_data_control_v1.c @@ -0,0 +1,717 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "wlr-data-control-unstable-v1-protocol.h" +#include "util/global.h" + +#define DATA_CONTROL_MANAGER_VERSION 2 + +struct data_control_source { + struct wl_resource *resource; + struct wl_array mime_types; + bool finalized; + + // Only one of these is non-NULL. + struct wlr_data_source *active_source; + struct wlr_primary_selection_source *active_primary_source; +}; + +static const struct zwlr_data_control_source_v1_interface source_impl; + +static struct data_control_source *source_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_data_control_source_v1_interface, &source_impl)); + return wl_resource_get_user_data(resource); +} + +static void source_handle_offer(struct wl_client *client, + struct wl_resource *resource, const char *mime_type) { + struct data_control_source *source = source_from_resource(resource); + if (source == NULL) { + return; + } + + if (source->finalized) { + wl_resource_post_error(resource, + ZWLR_DATA_CONTROL_SOURCE_V1_ERROR_INVALID_OFFER, + "cannot mutate offer after set_selection or " + "set_primary_selection"); + return; + } + + const char **mime_type_ptr; + wl_array_for_each(mime_type_ptr, &source->mime_types) { + if (strcmp(*mime_type_ptr, mime_type) == 0) { + wlr_log(WLR_DEBUG, "Ignoring duplicate MIME type offer %s", + mime_type); + return; + } + } + + char *dup_mime_type = strdup(mime_type); + if (dup_mime_type == NULL) { + wl_resource_post_no_memory(resource); + return; + } + + char **p = wl_array_add(&source->mime_types, sizeof(char *)); + if (p == NULL) { + free(dup_mime_type); + wl_resource_post_no_memory(resource); + return; + } + + *p = dup_mime_type; +} + +static void source_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwlr_data_control_source_v1_interface source_impl = { + .offer = source_handle_offer, + .destroy = source_handle_destroy, +}; + +static void data_control_source_destroy(struct data_control_source *source) { + if (source == NULL) { + return; + } + + char **p; + wl_array_for_each(p, &source->mime_types) { + free(*p); + } + wl_array_release(&source->mime_types); + + // Prevent destructors below from calling this recursively. + wl_resource_set_user_data(source->resource, NULL); + + if (source->active_source != NULL) { + wlr_data_source_destroy(source->active_source); + } else if (source->active_primary_source != NULL) { + wlr_primary_selection_source_destroy( + source->active_primary_source); + } + + free(source); +} + +static void source_handle_resource_destroy(struct wl_resource *resource) { + struct data_control_source *source = source_from_resource(resource); + data_control_source_destroy(source); +} + + +struct client_data_source { + struct wlr_data_source source; + struct wl_resource *resource; +}; + +static const struct wlr_data_source_impl client_source_impl; + +static struct client_data_source * + client_data_source_from_source(struct wlr_data_source *wlr_source) { + assert(wlr_source->impl == &client_source_impl); + struct client_data_source *source = wl_container_of(wlr_source, source, source); + return source; +} + +static void client_source_send(struct wlr_data_source *wlr_source, + const char *mime_type, int fd) { + struct client_data_source *source = + client_data_source_from_source(wlr_source); + zwlr_data_control_source_v1_send_send(source->resource, mime_type, fd); + close(fd); +} + +static void client_source_destroy(struct wlr_data_source *wlr_source) { + struct client_data_source *client_source = + client_data_source_from_source(wlr_source); + struct data_control_source *source = + source_from_resource(client_source->resource); + free(client_source); + + if (source == NULL) { + return; + } + + source->active_source = NULL; + + zwlr_data_control_source_v1_send_cancelled(source->resource); + data_control_source_destroy(source); +} + +static const struct wlr_data_source_impl client_source_impl = { + .send = client_source_send, + .destroy = client_source_destroy, +}; + + +struct client_primary_selection_source { + struct wlr_primary_selection_source source; + struct wl_resource *resource; +}; + +static const struct wlr_primary_selection_source_impl +client_primary_selection_source_impl; + +static struct client_primary_selection_source * + client_primary_selection_source_from_source( + struct wlr_primary_selection_source *wlr_source) { + assert(wlr_source->impl == &client_primary_selection_source_impl); + struct client_primary_selection_source *source = wl_container_of(wlr_source, source, source); + return source; +} + +static void client_primary_selection_source_send( + struct wlr_primary_selection_source *wlr_source, + const char *mime_type, int fd) { + struct client_primary_selection_source *source = + client_primary_selection_source_from_source(wlr_source); + zwlr_data_control_source_v1_send_send(source->resource, mime_type, fd); + close(fd); +} + +static void client_primary_selection_source_destroy( + struct wlr_primary_selection_source *wlr_source) { + struct client_primary_selection_source *client_source = + client_primary_selection_source_from_source(wlr_source); + struct data_control_source *source = + source_from_resource(client_source->resource); + free(client_source); + + if (source == NULL) { + return; + } + + source->active_primary_source = NULL; + + zwlr_data_control_source_v1_send_cancelled(source->resource); + data_control_source_destroy(source); +} + +static const struct wlr_primary_selection_source_impl +client_primary_selection_source_impl = { + .send = client_primary_selection_source_send, + .destroy = client_primary_selection_source_destroy, +}; + + +struct data_offer { + struct wl_resource *resource; + struct wlr_data_control_device_v1 *device; + bool is_primary; +}; + +static void data_offer_destroy(struct data_offer *offer) { + if (offer == NULL) { + return; + } + + struct wlr_data_control_device_v1 *device = offer->device; + if (device != NULL) { + if (offer->is_primary) { + device->primary_selection_offer_resource = NULL; + } else { + device->selection_offer_resource = NULL; + } + } + + wl_resource_set_user_data(offer->resource, NULL); + free(offer); +} + +static const struct zwlr_data_control_offer_v1_interface offer_impl; + +static struct data_offer *data_offer_from_offer_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_data_control_offer_v1_interface, &offer_impl)); + return wl_resource_get_user_data(resource); +} + +static void offer_handle_receive(struct wl_client *client, + struct wl_resource *resource, const char *mime_type, int fd) { + struct data_offer *offer = data_offer_from_offer_resource(resource); + if (offer == NULL) { + close(fd); + return; + } + + struct wlr_data_control_device_v1 *device = offer->device; + if (device == NULL) { + close(fd); + return; + } + + if (offer->is_primary) { + if (device->seat->primary_selection_source == NULL) { + close(fd); + return; + } + wlr_primary_selection_source_send( + device->seat->primary_selection_source, + mime_type, fd); + } else { + if (device->seat->selection_source == NULL) { + close(fd); + return; + } + wlr_data_source_send(device->seat->selection_source, mime_type, fd); + } +} + +static void offer_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwlr_data_control_offer_v1_interface offer_impl = { + .receive = offer_handle_receive, + .destroy = offer_handle_destroy, +}; + +static void offer_handle_resource_destroy(struct wl_resource *resource) { + struct data_offer *offer = data_offer_from_offer_resource(resource); + data_offer_destroy(offer); +} + +static struct wl_resource *create_offer(struct wlr_data_control_device_v1 *device, + struct wl_array *mime_types, bool is_primary) { + struct wl_client *client = wl_resource_get_client(device->resource); + + struct data_offer *offer = calloc(1, sizeof(*offer)); + if (offer == NULL) { + wl_client_post_no_memory(client); + return NULL; + } + + offer->device = device; + offer->is_primary = is_primary; + + uint32_t version = wl_resource_get_version(device->resource); + struct wl_resource *resource = wl_resource_create(client, + &zwlr_data_control_offer_v1_interface, version, 0); + if (resource == NULL) { + free(offer); + return NULL; + } + + offer->resource = resource; + + wl_resource_set_implementation(resource, &offer_impl, offer, + offer_handle_resource_destroy); + + zwlr_data_control_device_v1_send_data_offer(device->resource, resource); + + char **p; + wl_array_for_each(p, mime_types) { + zwlr_data_control_offer_v1_send_offer(resource, *p); + } + + return resource; +} + + +static const struct zwlr_data_control_device_v1_interface control_impl; + +static struct wlr_data_control_device_v1 *control_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_data_control_device_v1_interface, &control_impl)); + return wl_resource_get_user_data(resource); +} + +static void control_handle_set_selection(struct wl_client *client, + struct wl_resource *control_resource, + struct wl_resource *source_resource) { + struct wlr_data_control_device_v1 *device = + control_from_resource(control_resource); + if (device == NULL) { + return; + } + + struct data_control_source *source = NULL; + if (source_resource != NULL) { + source = source_from_resource(source_resource); + } + + if (source == NULL) { + wlr_seat_request_set_selection(device->seat, NULL, NULL, + wl_display_next_serial(device->seat->display)); + + return; + } + + if (source->active_source != NULL || + source->active_primary_source != NULL) { + wl_resource_post_error(control_resource, + ZWLR_DATA_CONTROL_DEVICE_V1_ERROR_USED_SOURCE, + "cannot use a data source in set_selection or " + "set_primary_selection more than once"); + + return; + } + + struct client_data_source *client_source = calloc(1, sizeof(*client_source)); + if (client_source == NULL) { + wl_client_post_no_memory(client); + return; + } + client_source->resource = source_resource; + + struct wlr_data_source *wlr_source = &client_source->source; + wlr_data_source_init(wlr_source, &client_source_impl); + source->active_source = wlr_source; + + wl_array_release(&wlr_source->mime_types); + wlr_source->mime_types = source->mime_types; + wl_array_init(&source->mime_types); + + source->finalized = true; + + wlr_seat_request_set_selection(device->seat, NULL, wlr_source, + wl_display_next_serial(device->seat->display)); +} + +static void control_handle_set_primary_selection(struct wl_client *client, + struct wl_resource *control_resource, + struct wl_resource *source_resource) { + struct wlr_data_control_device_v1 *device = + control_from_resource(control_resource); + if (device == NULL) { + return; + } + + struct data_control_source *source = NULL; + if (source_resource != NULL) { + source = source_from_resource(source_resource); + } + + if (source == NULL) { + wlr_seat_request_set_primary_selection(device->seat, NULL, NULL, + wl_display_next_serial(device->seat->display)); + + return; + } + + if (source->active_source != NULL || + source->active_primary_source != NULL) { + wl_resource_post_error(control_resource, + ZWLR_DATA_CONTROL_DEVICE_V1_ERROR_USED_SOURCE, + "cannot use a data source in set_selection or " + "set_primary_selection more than once"); + + return; + } + + struct client_primary_selection_source *client_source = calloc(1, sizeof(*client_source)); + if (client_source == NULL) { + wl_client_post_no_memory(client); + return; + } + client_source->resource = source_resource; + + struct wlr_primary_selection_source *wlr_source = &client_source->source; + wlr_primary_selection_source_init(wlr_source, &client_primary_selection_source_impl); + source->active_primary_source = wlr_source; + + wl_array_release(&wlr_source->mime_types); + wlr_source->mime_types = source->mime_types; + wl_array_init(&source->mime_types); + + source->finalized = true; + + wlr_seat_request_set_primary_selection(device->seat, NULL, wlr_source, + wl_display_next_serial(device->seat->display)); +} + +static void control_handle_destroy(struct wl_client *client, + struct wl_resource *control_resource) { + wl_resource_destroy(control_resource); +} + +static const struct zwlr_data_control_device_v1_interface control_impl = { + .set_selection = control_handle_set_selection, + .set_primary_selection = control_handle_set_primary_selection, + .destroy = control_handle_destroy, +}; + +static void control_send_selection(struct wlr_data_control_device_v1 *device) { + struct wlr_data_source *source = device->seat->selection_source; + + if (device->selection_offer_resource != NULL) { + // Make the offer inert + struct data_offer *offer = data_offer_from_offer_resource( + device->selection_offer_resource); + data_offer_destroy(offer); + } + + device->selection_offer_resource = NULL; + if (source != NULL) { + device->selection_offer_resource = + create_offer(device, &source->mime_types, false); + if (device->selection_offer_resource == NULL) { + wl_resource_post_no_memory(device->resource); + return; + } + } + + zwlr_data_control_device_v1_send_selection(device->resource, + device->selection_offer_resource); +} + +static void control_send_primary_selection( + struct wlr_data_control_device_v1 *device) { + uint32_t version = wl_resource_get_version(device->resource); + if (version < ZWLR_DATA_CONTROL_DEVICE_V1_PRIMARY_SELECTION_SINCE_VERSION) { + return; + } + + struct wlr_primary_selection_source *source = + device->seat->primary_selection_source; + + if (device->primary_selection_offer_resource != NULL) { + // Make the offer inert + struct data_offer *offer = data_offer_from_offer_resource( + device->primary_selection_offer_resource); + data_offer_destroy(offer); + } + + device->primary_selection_offer_resource = NULL; + if (source != NULL) { + device->primary_selection_offer_resource = + create_offer(device, &source->mime_types, true); + if (device->primary_selection_offer_resource == NULL) { + wl_resource_post_no_memory(device->resource); + return; + } + } + + zwlr_data_control_device_v1_send_primary_selection(device->resource, + device->primary_selection_offer_resource); +} + +static void control_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_data_control_device_v1 *device = control_from_resource(resource); + wlr_data_control_device_v1_destroy(device); +} + +static void control_handle_seat_destroy(struct wl_listener *listener, + void *data) { + struct wlr_data_control_device_v1 *device = + wl_container_of(listener, device, seat_destroy); + wlr_data_control_device_v1_destroy(device); +} + +static void control_handle_seat_set_selection(struct wl_listener *listener, + void *data) { + struct wlr_data_control_device_v1 *device = + wl_container_of(listener, device, seat_set_selection); + control_send_selection(device); +} + +static void control_handle_seat_set_primary_selection( + struct wl_listener *listener, + void *data) { + struct wlr_data_control_device_v1 *device = + wl_container_of(listener, device, seat_set_primary_selection); + control_send_primary_selection(device); +} + +void wlr_data_control_device_v1_destroy(struct wlr_data_control_device_v1 *device) { + if (device == NULL) { + return; + } + zwlr_data_control_device_v1_send_finished(device->resource); + // Make the resources inert + wl_resource_set_user_data(device->resource, NULL); + if (device->selection_offer_resource != NULL) { + struct data_offer *offer = data_offer_from_offer_resource( + device->selection_offer_resource); + data_offer_destroy(offer); + } + if (device->primary_selection_offer_resource != NULL) { + struct data_offer *offer = data_offer_from_offer_resource( + device->primary_selection_offer_resource); + data_offer_destroy(offer); + } + wl_list_remove(&device->seat_destroy.link); + wl_list_remove(&device->seat_set_selection.link); + wl_list_remove(&device->seat_set_primary_selection.link); + wl_list_remove(&device->link); + free(device); +} + + +static const struct zwlr_data_control_manager_v1_interface manager_impl; + +static struct wlr_data_control_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_data_control_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void manager_handle_create_data_source(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id) { + struct data_control_source *source = calloc(1, sizeof(*source)); + if (source == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + + wl_array_init(&source->mime_types); + + uint32_t version = wl_resource_get_version(manager_resource); + source->resource = wl_resource_create(client, + &zwlr_data_control_source_v1_interface, version, id); + if (source->resource == NULL) { + wl_resource_post_no_memory(manager_resource); + wl_array_release(&source->mime_types); + free(source); + return; + } + wl_resource_set_implementation(source->resource, &source_impl, source, + source_handle_resource_destroy); +} + +static void manager_handle_get_data_device(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + struct wl_resource *seat_resource) { + struct wlr_data_control_manager_v1 *manager = + manager_from_resource(manager_resource); + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat_resource); + + uint32_t version = wl_resource_get_version(manager_resource); + struct wl_resource *resource = wl_resource_create(client, + &zwlr_data_control_device_v1_interface, version, id); + if (resource == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + wl_resource_set_implementation(resource, &control_impl, NULL, + control_handle_resource_destroy); + if (seat_client == NULL) { + return; + } + + struct wlr_data_control_device_v1 *device = calloc(1, sizeof(*device)); + if (device == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + device->manager = manager; + device->seat = seat_client->seat; + device->resource = resource; + wl_resource_set_user_data(resource, device); + + device->seat_destroy.notify = control_handle_seat_destroy; + wl_signal_add(&device->seat->events.destroy, &device->seat_destroy); + + device->seat_set_selection.notify = control_handle_seat_set_selection; + wl_signal_add(&device->seat->events.set_selection, + &device->seat_set_selection); + + device->seat_set_primary_selection.notify = + control_handle_seat_set_primary_selection; + wl_signal_add(&device->seat->events.set_primary_selection, + &device->seat_set_primary_selection); + + wl_list_insert(&manager->devices, &device->link); + wl_signal_emit_mutable(&manager->events.new_device, device); + + // At this point maybe the compositor decided to destroy the device. If + // it's the case then the resource will be inert. + device = control_from_resource(resource); + if (device != NULL) { + control_send_selection(device); + control_send_primary_selection(device); + } +} + +static void manager_handle_destroy(struct wl_client *client, + struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static const struct zwlr_data_control_manager_v1_interface manager_impl = { + .create_data_source = manager_handle_create_data_source, + .get_data_device = manager_handle_get_data_device, + .destroy = manager_handle_destroy, +}; + +static void manager_bind(struct wl_client *client, void *data, uint32_t version, + uint32_t id) { + struct wlr_data_control_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &zwlr_data_control_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, manager, NULL); +} + +static void data_control_manager_v1_destroy(struct wlr_data_control_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + assert(wl_list_empty(&manager->events.new_device.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_data_control_manager_v1_destroy(struct wlr_data_control_manager_v1 *manager, + bool destroy_global_safe) { + data_control_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_data_control_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + data_control_manager_v1_destroy(manager, false); +} + +struct wlr_data_control_manager_v1 *wlr_data_control_manager_v1_create( + struct wl_display *display) { + struct wlr_data_control_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + wl_list_init(&manager->devices); + + wl_signal_init(&manager->events.destroy); + wl_signal_init(&manager->events.new_device); + + manager->global = wl_global_create(display, + &zwlr_data_control_manager_v1_interface, + DATA_CONTROL_MANAGER_VERSION, manager, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_drm.c b/3rdparty/wlroots/types/wlr_drm.c new file mode 100644 index 0000000000..815d536db3 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_drm.c @@ -0,0 +1,288 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "drm-protocol.h" +#include "render/drm_format_set.h" +#include "util/global.h" + +#define WLR_DRM_VERSION 2 + +static void buffer_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wl_buffer_interface wl_buffer_impl = { + .destroy = buffer_handle_destroy, +}; + +static const struct wlr_buffer_impl buffer_impl; + +static struct wlr_drm_buffer *drm_buffer_from_buffer( + struct wlr_buffer *wlr_buffer) { + assert(wlr_buffer->impl == &buffer_impl); + struct wlr_drm_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + return buffer; +} + +static void buffer_destroy(struct wlr_buffer *wlr_buffer) { + struct wlr_drm_buffer *buffer = drm_buffer_from_buffer(wlr_buffer); + wl_list_remove(&buffer->release.link); + + wlr_buffer_finish(wlr_buffer); + + if (buffer->resource != NULL) { + wl_resource_set_user_data(buffer->resource, NULL); + } + wlr_dmabuf_attributes_finish(&buffer->dmabuf); + free(buffer); +} + +static bool buffer_get_dmabuf(struct wlr_buffer *wlr_buffer, + struct wlr_dmabuf_attributes *dmabuf) { + struct wlr_drm_buffer *buffer = drm_buffer_from_buffer(wlr_buffer); + *dmabuf = buffer->dmabuf; + return true; +} + +static const struct wlr_buffer_impl buffer_impl = { + .destroy = buffer_destroy, + .get_dmabuf = buffer_get_dmabuf, +}; + +static bool buffer_resource_is_instance(struct wl_resource *resource) { + return wl_resource_instance_of(resource, &wl_buffer_interface, + &wl_buffer_impl); +} + +struct wlr_drm_buffer *wlr_drm_buffer_try_from_resource( + struct wl_resource *resource) { + if (!buffer_resource_is_instance(resource)) { + return NULL; + } + return wl_resource_get_user_data(resource); +} + +static void buffer_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_drm_buffer *buffer = wlr_drm_buffer_try_from_resource(resource); + assert(buffer != NULL); + buffer->resource = NULL; + wlr_buffer_drop(&buffer->base); +} + +static void buffer_handle_release(struct wl_listener *listener, void *data) { + struct wlr_drm_buffer *buffer = wl_container_of(listener, buffer, release); + if (buffer->resource != NULL) { + wl_buffer_send_release(buffer->resource); + } +} + +static void drm_handle_authenticate(struct wl_client *client, + struct wl_resource *resource, uint32_t id) { + // We only use render nodes, which don't need authentication + wl_drm_send_authenticated(resource); +} + +static void drm_handle_create_buffer(struct wl_client *client, + struct wl_resource *resource, uint32_t id, uint32_t name, int32_t width, + int32_t height, uint32_t stride, uint32_t format) { + wl_resource_post_error(resource, WL_DRM_ERROR_INVALID_NAME, + "Flink handles are not supported, use DMA-BUF instead"); +} + +static void drm_handle_create_planar_buffer(struct wl_client *client, + struct wl_resource *resource, uint32_t id, uint32_t name, int32_t width, + int32_t height, uint32_t format, int32_t offset0, int32_t stride0, + int32_t offset1, int32_t stride1, int32_t offset2, int32_t stride2) { + wl_resource_post_error(resource, WL_DRM_ERROR_INVALID_NAME, + "Flink handles are not supported, use DMA-BUF instead"); +} + +static void drm_handle_create_prime_buffer(struct wl_client *client, + struct wl_resource *resource, uint32_t id, int fd, int32_t width, + int32_t height, uint32_t format, int32_t offset0, int32_t stride0, + int32_t offset1, int32_t stride1, int32_t offset2, int32_t stride2) { + struct wlr_dmabuf_attributes dmabuf = { + .width = width, + .height = height, + .format = format, + .modifier = DRM_FORMAT_MOD_INVALID, + .n_planes = 1, + .offset[0] = offset0, + .stride[0] = stride0, + .fd[0] = fd, + }; + + struct wlr_drm_buffer *buffer = calloc(1, sizeof(*buffer)); + if (buffer == NULL) { + close(fd); + wl_resource_post_no_memory(resource); + return; + } + wlr_buffer_init(&buffer->base, &buffer_impl, width, height); + + buffer->resource = wl_resource_create(client, &wl_buffer_interface, 1, id); + if (buffer->resource == NULL) { + free(buffer); + close(fd); + wl_resource_post_no_memory(resource); + return; + } + wl_resource_set_implementation(buffer->resource, &wl_buffer_impl, buffer, + buffer_handle_resource_destroy); + + buffer->dmabuf = dmabuf; + + buffer->release.notify = buffer_handle_release; + wl_signal_add(&buffer->base.events.release, &buffer->release); +} + +static const struct wl_drm_interface drm_impl = { + .authenticate = drm_handle_authenticate, + .create_buffer = drm_handle_create_buffer, + .create_planar_buffer = drm_handle_create_planar_buffer, + .create_prime_buffer = drm_handle_create_prime_buffer, +}; + +static void drm_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_drm *drm = data; + + struct wl_resource *resource = wl_resource_create(client, + &wl_drm_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &drm_impl, drm, NULL); + wl_list_init(wl_resource_get_link(resource)); + if (drm == NULL) { + return; + } + + + wl_drm_send_device(resource, drm->node_name); + wl_drm_send_capabilities(resource, WL_DRM_CAPABILITY_PRIME); + + for (size_t i = 0; i < drm->formats.len; i++) { + const struct wlr_drm_format *fmt = &drm->formats.formats[i]; + if (wlr_drm_format_has(fmt, DRM_FORMAT_MOD_INVALID)) { + wl_drm_send_format(resource, fmt->format); + } + } +} + +static struct wlr_buffer *buffer_from_resource(struct wl_resource *resource) { + struct wlr_drm_buffer *buffer = wlr_drm_buffer_try_from_resource(resource); + assert(buffer != NULL); + return &buffer->base; +} + +static const struct wlr_buffer_resource_interface buffer_resource_interface = { + .name = "wlr_drm_buffer", + .is_instance = buffer_resource_is_instance, + .from_resource = buffer_from_resource, +}; + +static void drm_destroy(struct wlr_drm *drm, + bool destroy_global_safe) { + wl_signal_emit_mutable(&drm->events.destroy, NULL); + + assert(wl_list_empty(&drm->events.destroy.listener_list)); + + wl_list_remove(&drm->display_destroy.link); + + wlr_drm_format_set_finish(&drm->formats); + free(drm->node_name); + if (destroy_global_safe) { + wlr_global_destroy_safe(drm->global); + } else { + wl_global_destroy(drm->global); + } + free(drm); +} + +void wlr_drm_destroy(struct wlr_drm *drm, bool destroy_global_safe) { + drm_destroy(drm, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_drm *drm = wl_container_of(listener, drm, display_destroy); + drm_destroy(drm, false); +} + +struct wlr_drm *wlr_drm_create(struct wl_display *display, + struct wlr_renderer *renderer) { + int drm_fd = wlr_renderer_get_drm_fd(renderer); + if (drm_fd < 0) { + wlr_log(WLR_ERROR, "Failed to get DRM FD from renderer"); + return NULL; + } + + drmDevice *dev = NULL; + if (drmGetDevice2(drm_fd, 0, &dev) != 0) { + wlr_log(WLR_ERROR, "drmGetDevice2 failed"); + return NULL; + } + + char *node_name = NULL; + if (dev->available_nodes & (1 << DRM_NODE_RENDER)) { + node_name = strdup(dev->nodes[DRM_NODE_RENDER]); + } else { + assert(dev->available_nodes & (1 << DRM_NODE_PRIMARY)); + wlr_log(WLR_DEBUG, "No DRM render node available, " + "falling back to primary node '%s'", dev->nodes[DRM_NODE_PRIMARY]); + node_name = strdup(dev->nodes[DRM_NODE_PRIMARY]); + } + drmFreeDevice(&dev); + if (node_name == NULL) { + return NULL; + } + + struct wlr_drm *drm = calloc(1, sizeof(*drm)); + if (drm == NULL) { + free(node_name); + return NULL; + } + + drm->node_name = node_name; + wl_signal_init(&drm->events.destroy); + + const struct wlr_drm_format_set *formats = + wlr_renderer_get_texture_formats(renderer, WLR_BUFFER_CAP_DMABUF); + if (formats == NULL) { + goto error; + } + + if (!wlr_drm_format_set_copy(&drm->formats, formats)) { + goto error; + } + + drm->global = wl_global_create(display, &wl_drm_interface, WLR_DRM_VERSION, + drm, drm_bind); + if (drm->global == NULL) { + goto error; + } + + drm->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &drm->display_destroy); + + wlr_buffer_register_resource_interface(&buffer_resource_interface); + + return drm; + +error: + wlr_drm_format_set_finish(&drm->formats); + free(drm->node_name); + free(drm); + return NULL; +} diff --git a/3rdparty/wlroots/types/wlr_drm_lease_v1.c b/3rdparty/wlroots/types/wlr_drm_lease_v1.c new file mode 100644 index 0000000000..1def8b3a6f --- /dev/null +++ b/3rdparty/wlroots/types/wlr_drm_lease_v1.c @@ -0,0 +1,707 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "backend/drm/drm.h" +#include "drm-lease-v1-protocol.h" +#include "util/global.h" + +#define DRM_LEASE_DEVICE_V1_VERSION 1 + +static struct wp_drm_lease_device_v1_interface lease_device_impl; +static struct wp_drm_lease_connector_v1_interface lease_connector_impl; +static struct wp_drm_lease_request_v1_interface lease_request_impl; +static struct wp_drm_lease_v1_interface lease_impl; + +static struct wlr_drm_lease_device_v1 *drm_lease_device_v1_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_drm_lease_device_v1_interface, &lease_device_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_drm_lease_connector_v1 * +drm_lease_connector_v1_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_drm_lease_connector_v1_interface, &lease_connector_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_drm_lease_request_v1 *drm_lease_request_v1_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_drm_lease_request_v1_interface, &lease_request_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_drm_lease_v1 *drm_lease_v1_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_drm_lease_v1_interface, &lease_impl)); + return wl_resource_get_user_data(resource); +} + +static void drm_lease_request_v1_destroy( + struct wlr_drm_lease_request_v1 *request) { + if (!request) { + return; + } + + wlr_log(WLR_DEBUG, "Destroying request %p", request); + + wl_list_remove(&request->link); + wl_resource_set_user_data(request->resource, NULL); + + free(request->connectors); + free(request); +} + +static void drm_lease_connector_v1_destroy( + struct wlr_drm_lease_connector_v1 *connector) { + if (!connector) { + return; + } + + wlr_log(WLR_DEBUG, "Destroying connector %s", connector->output->name); + + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &connector->resources) { + wp_drm_lease_connector_v1_send_withdrawn(resource); + + wl_resource_set_user_data(resource, NULL); + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + } + + struct wl_resource *device_resource; + wl_resource_for_each(device_resource, &connector->device->resources) { + wp_drm_lease_device_v1_send_done(device_resource); + } + + wl_list_remove(&connector->link); + wl_list_remove(&connector->destroy.link); + free(connector); +} + +static void drm_lease_device_v1_destroy( + struct wlr_drm_lease_device_v1 *device, bool destroy_global_safe) { + if (!device) { + return; + } + + struct wlr_drm_backend *backend = + get_drm_backend_from_backend(device->backend); + wlr_log(WLR_DEBUG, "Destroying wlr_drm_lease_device_v1 for %s", + backend->name); + + struct wl_resource *resource, *tmp_resource; + wl_resource_for_each_safe(resource, tmp_resource, &device->resources) { + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + wl_resource_set_user_data(resource, NULL); + } + + struct wlr_drm_lease_request_v1 *request, *tmp_request; + wl_list_for_each_safe(request, tmp_request, &device->requests, link) { + drm_lease_request_v1_destroy(request); + } + + struct wlr_drm_lease_v1 *lease, *tmp_lease; + wl_list_for_each_safe(lease, tmp_lease, &device->leases, link) { + wlr_drm_lease_terminate(lease->drm_lease); + } + + struct wlr_drm_lease_connector_v1 *connector, *tmp_connector; + wl_list_for_each_safe(connector, tmp_connector, &device->connectors, link) { + drm_lease_connector_v1_destroy(connector); + } + + wl_list_remove(&device->link); + wl_list_remove(&device->backend_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(device->global); + } else { + wl_global_destroy(device->global); + } + + free(device); +} + +static void lease_handle_destroy(struct wl_listener *listener, void *data) { + struct wlr_drm_lease_v1 *lease = wl_container_of(listener, lease, destroy); + + wlr_log(WLR_DEBUG, "Destroying lease %"PRIu32, lease->drm_lease->lessee_id); + + wp_drm_lease_v1_send_finished(lease->resource); + + wl_list_remove(&lease->destroy.link); + + wl_list_remove(&lease->link); + wl_resource_set_user_data(lease->resource, NULL); + + free(lease); +} + +struct wlr_drm_lease_v1 *wlr_drm_lease_request_v1_grant( + struct wlr_drm_lease_request_v1 *request) { + assert(!request->invalid); + wlr_log(WLR_DEBUG, "Attempting to grant request %p", request); + + struct wlr_drm_lease_v1 *lease = calloc(1, sizeof(*lease)); + if (!lease) { + wl_resource_post_no_memory(request->resource); + return NULL; + } + + lease->device = request->device; + lease->resource = request->lease_resource; + + /* Transform connectors list into wlr_output for leasing */ + struct wlr_output *outputs[request->n_connectors + 1]; + for(size_t i = 0; i < request->n_connectors; ++i) { + outputs[i] = request->connectors[i]->output; + } + + int fd; + lease->drm_lease = wlr_drm_create_lease(outputs, request->n_connectors, &fd); + if (!lease->drm_lease) { + wlr_log(WLR_ERROR, "wlr_drm_create_lease failed"); + wp_drm_lease_v1_send_finished(lease->resource); + free(lease); + return NULL; + } + + lease->destroy.notify = lease_handle_destroy; + wl_signal_add(&lease->drm_lease->events.destroy, &lease->destroy); + + wl_list_insert(&lease->device->leases, &lease->link); + wl_resource_set_user_data(lease->resource, lease); + + wlr_log(WLR_DEBUG, "Granting request %p", request); + + wp_drm_lease_v1_send_lease_fd(lease->resource, fd); + close(fd); + + return lease; +} + +void wlr_drm_lease_request_v1_reject( + struct wlr_drm_lease_request_v1 *request) { + assert(request); + + wlr_log(WLR_DEBUG, "Rejecting request %p", request); + + request->invalid = true; + wp_drm_lease_v1_send_finished(request->lease_resource); +} + +void wlr_drm_lease_v1_revoke(struct wlr_drm_lease_v1 *lease) { + assert(lease); + wlr_log(WLR_DEBUG, "Revoking lease %"PRIu32, lease->drm_lease->lessee_id); + wlr_drm_lease_terminate(lease->drm_lease); +} + +static void drm_lease_v1_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_drm_lease_v1 *lease = drm_lease_v1_from_resource(resource); + if (lease != NULL) { + wlr_drm_lease_terminate(lease->drm_lease); + } +} + +static void drm_lease_v1_handle_destroy( + struct wl_client *client, struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static struct wp_drm_lease_v1_interface lease_impl = { + .destroy = drm_lease_v1_handle_destroy, +}; + +static void drm_lease_request_v1_handle_resource_destroy( + struct wl_resource *resource) { + struct wlr_drm_lease_request_v1 *request = + drm_lease_request_v1_from_resource(resource); + drm_lease_request_v1_destroy(request); +} + +static void drm_lease_request_v1_handle_request_connector( + struct wl_client *client, struct wl_resource *request_resource, + struct wl_resource *connector_resource) { + struct wlr_drm_lease_request_v1 *request = + drm_lease_request_v1_from_resource(request_resource); + if (!request) { + wlr_log(WLR_ERROR, "Request has been destroyed"); + return; + } + + struct wlr_drm_lease_connector_v1 *connector = + drm_lease_connector_v1_from_resource(connector_resource); + + if (!connector) { + /* This connector offer has been withdrawn or is leased */ + wlr_log(WLR_ERROR, "Failed to request connector"); + request->invalid = true; + return; + } + + wlr_log(WLR_DEBUG, "Requesting connector %s", connector->output->name); + + if (request->device != connector->device) { + wlr_log(WLR_ERROR, "The connector belongs to another device"); + wl_resource_post_error(request_resource, + WP_DRM_LEASE_REQUEST_V1_ERROR_WRONG_DEVICE, + "The requested connector belongs to another device"); + return; + } + + for (size_t i = 0; i < request->n_connectors; ++i) { + struct wlr_drm_lease_connector_v1 *tmp = request->connectors[i]; + + if (connector == tmp) { + wlr_log(WLR_ERROR, "The connector has already been requested"); + wl_resource_post_error(request_resource, + WP_DRM_LEASE_REQUEST_V1_ERROR_DUPLICATE_CONNECTOR, + "The connector has already been requested"); + return; + } + } + + size_t n_connectors = request->n_connectors + 1; + + struct wlr_drm_lease_connector_v1 **tmp_connectors = + realloc(request->connectors, + n_connectors * sizeof(struct wlr_drm_lease_connector_v1 *)); + if (!tmp_connectors) { + wlr_log(WLR_ERROR, "Failed to grow connectors request array"); + return; + } + + request->connectors = tmp_connectors; + request->connectors[request->n_connectors] = connector; + request->n_connectors = n_connectors; +} + +static void drm_lease_request_v1_handle_submit( + struct wl_client *client, struct wl_resource *resource, uint32_t id) { + uint32_t version = wl_resource_get_version(resource); + struct wl_resource *lease_resource = wl_resource_create(client, + &wp_drm_lease_v1_interface, version, id); + if (!lease_resource) { + wlr_log(WLR_ERROR, "Failed to allocate wl_resource"); + wl_resource_post_no_memory(resource); + return; + } + + wl_resource_set_implementation(lease_resource, &lease_impl, NULL, + drm_lease_v1_handle_resource_destroy); + + struct wlr_drm_lease_request_v1 *request = + drm_lease_request_v1_from_resource(resource); + if (!request) { + wlr_log(WLR_DEBUG, "Request has been destroyed"); + wp_drm_lease_v1_send_finished(lease_resource); + return; + } + + /* Pre-emptively reject invalid lease requests */ + if (request->invalid) { + wlr_log(WLR_ERROR, "Invalid request"); + wp_drm_lease_v1_send_finished(lease_resource); + return; + } else if (request->n_connectors == 0) { + wl_resource_post_error(lease_resource, + WP_DRM_LEASE_REQUEST_V1_ERROR_EMPTY_LEASE, + "Lease request has no connectors"); + return; + } + + request->lease_resource = lease_resource; + + wl_signal_emit_mutable(&request->device->manager->events.request, + request); + + /* If the compositor didn't act upon the request, reject it */ + if (!request->invalid && wl_resource_get_user_data(lease_resource) == NULL) { + wlr_drm_lease_request_v1_reject(request); + } + + /* Request is done */ + wl_resource_destroy(resource); +} + +static struct wp_drm_lease_request_v1_interface lease_request_impl = { + .request_connector = drm_lease_request_v1_handle_request_connector, + .submit = drm_lease_request_v1_handle_submit, +}; + +static void drm_lease_device_v1_handle_resource_destroy( + struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void drm_lease_device_v1_handle_release( + struct wl_client *client, struct wl_resource *resource) { + wp_drm_lease_device_v1_send_released(resource); + wl_resource_destroy(resource); +} + +static void drm_lease_device_v1_handle_create_lease_request( + struct wl_client *client, struct wl_resource *resource, uint32_t id) { + uint32_t version = wl_resource_get_version(resource); + struct wl_resource *request_resource = wl_resource_create(client, + &wp_drm_lease_request_v1_interface, version, id); + if (!request_resource) { + wlr_log(WLR_ERROR, "Failed to allocate wl_resource"); + return; + } + + wl_resource_set_implementation(request_resource, &lease_request_impl, + NULL, drm_lease_request_v1_handle_resource_destroy); + + struct wlr_drm_lease_device_v1 *device = + drm_lease_device_v1_from_resource(resource); + if (!device) { + wlr_log(WLR_DEBUG, "Failed to create lease request, " + "wlr_drm_lease_device_v1 has been destroyed"); + return; + } + + struct wlr_drm_lease_request_v1 *req = calloc(1, sizeof(*req)); + if (!req) { + wlr_log(WLR_ERROR, "Failed to allocate wlr_drm_lease_request_v1"); + wl_resource_post_no_memory(resource); + return; + } + + wlr_log(WLR_DEBUG, "Created request %p", req); + + req->device = device; + req->resource = request_resource; + req->connectors = NULL; + req->n_connectors = 0; + + wl_resource_set_user_data(request_resource, req); + + wl_list_insert(&device->requests, &req->link); +} + +static struct wp_drm_lease_device_v1_interface lease_device_impl = { + .release = drm_lease_device_v1_handle_release, + .create_lease_request = drm_lease_device_v1_handle_create_lease_request, +}; + +static void drm_connector_v1_handle_resource_destroy( + struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void drm_connector_v1_handle_destroy( + struct wl_client *client, struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static struct wp_drm_lease_connector_v1_interface lease_connector_impl = { + .destroy = drm_connector_v1_handle_destroy, +}; + +static void drm_lease_connector_v1_send_to_client( + struct wlr_drm_lease_connector_v1 *connector, + struct wl_resource *resource) { + struct wl_client *client = wl_resource_get_client(resource); + + uint32_t version = wl_resource_get_version(resource); + struct wl_resource *connector_resource = wl_resource_create(client, + &wp_drm_lease_connector_v1_interface, version, 0); + if (!connector_resource) { + wl_client_post_no_memory(client); + return; + } + + wl_resource_set_implementation(connector_resource, &lease_connector_impl, + connector, drm_connector_v1_handle_resource_destroy); + wp_drm_lease_device_v1_send_connector(resource, connector_resource); + + struct wlr_output *output = connector->output; + wp_drm_lease_connector_v1_send_name(connector_resource, output->name); + + // TODO: re-send the description when it's updated + wp_drm_lease_connector_v1_send_description(connector_resource, + output->description); + + wp_drm_lease_connector_v1_send_connector_id(connector_resource, + wlr_drm_connector_get_id(output)); + + wp_drm_lease_connector_v1_send_done(connector_resource); + + wl_list_insert(&connector->resources, + wl_resource_get_link(connector_resource)); +} + +static void lease_device_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wl_resource *device_resource = wl_resource_create(wl_client, + &wp_drm_lease_device_v1_interface, version, id); + if (!device_resource) { + wl_client_post_no_memory(wl_client); + return; + } + + wl_resource_set_implementation(device_resource, &lease_device_impl, NULL, + drm_lease_device_v1_handle_resource_destroy); + + struct wlr_drm_lease_device_v1 *device = data; + if (!device) { + wlr_log(WLR_DEBUG, "Failed to bind lease device, " + "the wlr_drm_lease_device_v1 has been destroyed"); + wl_list_init(wl_resource_get_link(device_resource)); + return; + } + + wl_resource_set_user_data(device_resource, device); + wl_list_insert(&device->resources, wl_resource_get_link(device_resource)); + + int fd = wlr_drm_backend_get_non_master_fd(device->backend); + if (fd < 0) { + wlr_log(WLR_ERROR, "Unable to get read only DRM fd for leasing"); + wl_client_post_no_memory(wl_client); + return; + } + + wp_drm_lease_device_v1_send_drm_fd(device_resource, fd); + close(fd); + + struct wlr_drm_lease_connector_v1 *connector; + wl_list_for_each(connector, &device->connectors, link) { + drm_lease_connector_v1_send_to_client(connector, device_resource); + } + + wp_drm_lease_device_v1_send_done(device_resource); +} + +static void handle_output_destroy(struct wl_listener *listener, void *data) { + struct wlr_drm_lease_connector_v1 *conn = wl_container_of(listener, conn, + destroy); + wlr_log(WLR_DEBUG, "Handle destruction of output %s", conn->output->name); + wlr_drm_lease_v1_manager_withdraw_output(conn->device->manager, conn->output); +} + +bool wlr_drm_lease_v1_manager_offer_output( + struct wlr_drm_lease_v1_manager *manager, struct wlr_output *output) { + assert(manager && output); + assert(wlr_output_is_drm(output)); + + wlr_log(WLR_DEBUG, "Offering output %s", output->name); + + struct wlr_drm_lease_device_v1 *device = NULL, *tmp_device; + wl_list_for_each(tmp_device, &manager->devices, link) { + if (tmp_device->backend == output->backend) { + device = tmp_device; + break; + } + } + + if (!device) { + wlr_log(WLR_ERROR, "No wlr_drm_lease_device_v1 associated with the " + "offered output"); + return false; + } + + struct wlr_drm_lease_connector_v1 *tmp_connector; + wl_list_for_each(tmp_connector, &device->connectors, link) { + if (tmp_connector->output == output) { + wlr_log(WLR_ERROR, "Output %s has already been offered", + output->name); + return false; + } + } + + struct wlr_drm_lease_connector_v1 *connector = calloc(1, sizeof(*connector)); + if (!connector) { + wlr_log(WLR_ERROR, "Failed to allocate wlr_drm_lease_connector_v1"); + return false; + } + + connector->output = output; + connector->device = device; + + connector->destroy.notify = handle_output_destroy; + wl_signal_add(&output->events.destroy, &connector->destroy); + + wl_list_init(&connector->resources); + wl_list_insert(&device->connectors, &connector->link); + + struct wl_resource *resource; + wl_resource_for_each(resource, &device->resources) { + drm_lease_connector_v1_send_to_client(connector, resource); + wp_drm_lease_device_v1_send_done(resource); + } + + return true; +} + +void wlr_drm_lease_v1_manager_withdraw_output( + struct wlr_drm_lease_v1_manager *manager, struct wlr_output *output) { + assert(manager && output); + + wlr_log(WLR_DEBUG, "Withdrawing output %s", output->name); + + struct wlr_drm_lease_device_v1 *device = NULL, *tmp_device; + wl_list_for_each(tmp_device, &manager->devices, link) { + if (tmp_device->backend == output->backend) { + device = tmp_device; + break; + } + } + + if (!device) { + wlr_log(WLR_ERROR, "No wlr_drm_lease_device_v1 associated with the " + "given output"); + return; + } + + struct wlr_drm_lease_connector_v1 *connector = NULL, *tmp_conn; + wl_list_for_each(tmp_conn, &device->connectors, link) { + if (tmp_conn->output == output) { + connector = tmp_conn; + break; + } + } + + if (!connector) { + wlr_log(WLR_DEBUG, "No wlr_drm_connector_v1 associated with the given " + "output"); + return; + } + + drm_lease_connector_v1_destroy(connector); +} + +static void handle_backend_destroy(struct wl_listener *listener, void *data) { + struct wlr_drm_lease_device_v1 *device = + wl_container_of(listener, device, backend_destroy); + drm_lease_device_v1_destroy(device, true); +} + +static void drm_lease_device_v1_create(struct wlr_drm_lease_v1_manager *manager, + struct wlr_backend *backend) { + struct wlr_drm_backend *drm_backend = get_drm_backend_from_backend(backend); + + // Make sure we can get a non-master FD for the DRM backend. On some setups + // we don't have the permission for this. + int fd = wlr_drm_backend_get_non_master_fd(backend); + if (fd < 0) { + wlr_log(WLR_INFO, "Skipping %s: failed to get read-only DRM FD", + drm_backend->name); + return; + } + close(fd); + + wlr_log(WLR_DEBUG, "Creating wlr_drm_lease_device_v1 for %s", + drm_backend->name); + + struct wlr_drm_lease_device_v1 *lease_device = calloc(1, sizeof(*lease_device)); + + if (!lease_device) { + wlr_log(WLR_ERROR, "Failed to allocate wlr_drm_lease_device_v1"); + return; + } + + lease_device->manager = manager; + lease_device->backend = backend; + wl_list_init(&lease_device->resources); + wl_list_init(&lease_device->connectors); + wl_list_init(&lease_device->requests); + wl_list_init(&lease_device->leases); + wl_list_init(&lease_device->link); + + lease_device->global = wl_global_create(manager->display, + &wp_drm_lease_device_v1_interface, DRM_LEASE_DEVICE_V1_VERSION, + lease_device, lease_device_bind); + + if (!lease_device->global) { + wlr_log(WLR_ERROR, "Failed to allocate wp_drm_lease_device_v1 global"); + free(lease_device); + return; + } + + lease_device->backend_destroy.notify = handle_backend_destroy; + wl_signal_add(&backend->events.destroy, &lease_device->backend_destroy); + + wl_list_insert(&manager->devices, &lease_device->link); +} + +static void multi_backend_cb(struct wlr_backend *backend, void *data) { + if (!wlr_backend_is_drm(backend)) { + return; + } + + struct wlr_drm_lease_v1_manager *manager = data; + drm_lease_device_v1_create(manager, backend); +} + +static void drm_lease_v1_manager_destroy(struct wlr_drm_lease_v1_manager *manager, + bool destroy_global_safe) { + wlr_log(WLR_DEBUG, "Destroying wlr_drm_lease_v1_manager"); + + wl_signal_emit_mutable(&manager->events.destroy, NULL); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + assert(wl_list_empty(&manager->events.request.listener_list)); + + struct wlr_drm_lease_device_v1 *device, *tmp; + wl_list_for_each_safe(device, tmp, &manager->devices, link) { + drm_lease_device_v1_destroy(device, destroy_global_safe); + } + + wl_list_remove(&manager->display_destroy.link); + free(manager); +} + +void wlr_drm_lease_v1_manager_destroy(struct wlr_drm_lease_v1_manager *manager, + bool destroy_global_safe) { + drm_lease_v1_manager_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_drm_lease_v1_manager *manager = wl_container_of(listener, manager, + display_destroy); + drm_lease_v1_manager_destroy(manager, false); +} + +struct wlr_drm_lease_v1_manager *wlr_drm_lease_v1_manager_create( + struct wl_display *display, struct wlr_backend *backend) { + struct wlr_drm_lease_v1_manager *manager = calloc(1, sizeof(*manager)); + if (!manager) { + wlr_log(WLR_ERROR, "Failed to allocate wlr_drm_lease_v1_manager"); + return NULL; + } + + wl_list_init(&manager->devices); + manager->display = display; + + if (wlr_backend_is_multi(backend)) { + /* TODO: handle backends added after the manager is created */ + wlr_multi_for_each_backend(backend, multi_backend_cb, manager); + } else if (wlr_backend_is_drm(backend)) { + drm_lease_device_v1_create(manager, backend); + } + + if (wl_list_empty(&manager->devices)) { + wlr_log(WLR_DEBUG, "No DRM backend supplied, failed to create " + "wlr_drm_lease_v1_manager"); + free(manager); + return NULL; + } + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + wl_signal_init(&manager->events.destroy); + wl_signal_init(&manager->events.request); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_export_dmabuf_v1.c b/3rdparty/wlroots/types/wlr_export_dmabuf_v1.c new file mode 100644 index 0000000000..95e8011f30 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_export_dmabuf_v1.c @@ -0,0 +1,241 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "wlr-export-dmabuf-unstable-v1-protocol.h" +#include "util/global.h" + +#define EXPORT_DMABUF_MANAGER_VERSION 1 + + +static const struct zwlr_export_dmabuf_frame_v1_interface frame_impl; + +static struct wlr_export_dmabuf_frame_v1 *frame_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_export_dmabuf_frame_v1_interface, &frame_impl)); + return wl_resource_get_user_data(resource); +} + +static void frame_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwlr_export_dmabuf_frame_v1_interface frame_impl = { + .destroy = frame_handle_destroy, +}; + +static void frame_destroy(struct wlr_export_dmabuf_frame_v1 *frame) { + if (frame == NULL) { + return; + } + if (frame->output != NULL) { + wlr_output_lock_attach_render(frame->output, false); + if (frame->cursor_locked) { + wlr_output_lock_software_cursors(frame->output, false); + } + } + wl_list_remove(&frame->link); + wl_list_remove(&frame->output_commit.link); + wl_list_remove(&frame->output_destroy.link); + // Make the frame resource inert + wl_resource_set_user_data(frame->resource, NULL); + free(frame); +} + +static void frame_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_export_dmabuf_frame_v1 *frame = frame_from_resource(resource); + frame_destroy(frame); +} + +static void frame_output_handle_commit(struct wl_listener *listener, + void *data) { + struct wlr_export_dmabuf_frame_v1 *frame = + wl_container_of(listener, frame, output_commit); + struct wlr_output_event_commit *event = data; + + if (!(event->state->committed & WLR_OUTPUT_STATE_BUFFER)) { + return; + } + + wl_list_remove(&frame->output_commit.link); + wl_list_init(&frame->output_commit.link); + + struct wlr_dmabuf_attributes attribs = {0}; + if (!wlr_buffer_get_dmabuf(event->state->buffer, &attribs)) { + zwlr_export_dmabuf_frame_v1_send_cancel(frame->resource, + ZWLR_EXPORT_DMABUF_FRAME_V1_CANCEL_REASON_TEMPORARY); + frame_destroy(frame); + return; + } + + uint32_t frame_flags = ZWLR_EXPORT_DMABUF_FRAME_V1_FLAGS_TRANSIENT; + uint32_t mod_high = attribs.modifier >> 32; + uint32_t mod_low = attribs.modifier & 0xFFFFFFFF; + zwlr_export_dmabuf_frame_v1_send_frame(frame->resource, + attribs.width, attribs.height, 0, 0, 0, frame_flags, + attribs.format, mod_high, mod_low, attribs.n_planes); + + for (int i = 0; i < attribs.n_planes; ++i) { + off_t size = lseek(attribs.fd[i], 0, SEEK_END); + zwlr_export_dmabuf_frame_v1_send_object(frame->resource, i, + attribs.fd[i], size, attribs.offset[i], attribs.stride[i], i); + } + + time_t tv_sec = event->when.tv_sec; + uint32_t tv_sec_hi = (sizeof(tv_sec) > 4) ? tv_sec >> 32 : 0; + uint32_t tv_sec_lo = tv_sec & 0xFFFFFFFF; + zwlr_export_dmabuf_frame_v1_send_ready(frame->resource, + tv_sec_hi, tv_sec_lo, event->when.tv_nsec); + frame_destroy(frame); +} + +static void frame_output_handle_destroy(struct wl_listener *listener, void *data) { + struct wlr_export_dmabuf_frame_v1 *frame = wl_container_of(listener, frame, output_destroy); + frame_destroy(frame); +} + + +static const struct zwlr_export_dmabuf_manager_v1_interface manager_impl; + +static struct wlr_export_dmabuf_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_export_dmabuf_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void manager_handle_capture_output(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + int32_t overlay_cursor, struct wl_resource *output_resource) { + struct wlr_export_dmabuf_manager_v1 *manager = + manager_from_resource(manager_resource); + struct wlr_output *output = wlr_output_from_resource(output_resource); + + struct wlr_export_dmabuf_frame_v1 *frame = calloc(1, sizeof(*frame)); + if (frame == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + frame->manager = manager; + wl_list_init(&frame->output_commit.link); + wl_list_init(&frame->output_destroy.link); + + uint32_t version = wl_resource_get_version(manager_resource); + frame->resource = wl_resource_create(client, + &zwlr_export_dmabuf_frame_v1_interface, version, id); + if (frame->resource == NULL) { + wl_client_post_no_memory(client); + free(frame); + return; + } + wl_resource_set_implementation(frame->resource, &frame_impl, frame, + frame_handle_resource_destroy); + + wl_list_insert(&manager->frames, &frame->link); + + if (output == NULL || !output->enabled) { + zwlr_export_dmabuf_frame_v1_send_cancel(frame->resource, + ZWLR_EXPORT_DMABUF_FRAME_V1_CANCEL_REASON_PERMANENT); + frame_destroy(frame); + return; + } + + frame->output = output; + + wlr_output_lock_attach_render(frame->output, true); + if (overlay_cursor) { + wlr_output_lock_software_cursors(frame->output, true); + frame->cursor_locked = true; + } + + wl_list_remove(&frame->output_commit.link); + wl_signal_add(&output->events.commit, &frame->output_commit); + frame->output_commit.notify = frame_output_handle_commit; + wl_signal_add(&output->events.destroy, &frame->output_destroy); + frame->output_destroy.notify = frame_output_handle_destroy; + + // Request a frame because we can't assume that the current front buffer is still usable. It may + // have been released already, and we shouldn't lock it here because compositors want to render + // into the least damaged buffer. + wlr_output_update_needs_frame(output); +} + +static void manager_handle_destroy(struct wl_client *client, + struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static const struct zwlr_export_dmabuf_manager_v1_interface manager_impl = { + .capture_output = manager_handle_capture_output, + .destroy = manager_handle_destroy, +}; + +static void manager_bind(struct wl_client *client, void *data, uint32_t version, + uint32_t id) { + struct wlr_export_dmabuf_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &zwlr_export_dmabuf_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, manager, + NULL); +} + +static void export_dmabuf_manager_v1_destroy(struct wlr_export_dmabuf_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_export_dmabuf_manager_v1_destroy(struct wlr_export_dmabuf_manager_v1 *manager, + bool destroy_global_safe) { + export_dmabuf_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_export_dmabuf_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + export_dmabuf_manager_v1_destroy(manager, false); +} + +struct wlr_export_dmabuf_manager_v1 *wlr_export_dmabuf_manager_v1_create( + struct wl_display *display) { + struct wlr_export_dmabuf_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + wl_list_init(&manager->frames); + + wl_signal_init(&manager->events.destroy); + + manager->global = wl_global_create(display, + &zwlr_export_dmabuf_manager_v1_interface, EXPORT_DMABUF_MANAGER_VERSION, + manager, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_ext_data_control_v1.c b/3rdparty/wlroots/types/wlr_ext_data_control_v1.c new file mode 100644 index 0000000000..9cb373f30b --- /dev/null +++ b/3rdparty/wlroots/types/wlr_ext_data_control_v1.c @@ -0,0 +1,718 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ext-data-control-v1-protocol.h" +#include "util/global.h" + +#define EXT_DATA_CONTROL_MANAGER_VERSION 1 + +struct data_control_source { + struct wl_resource *resource; + struct wl_array mime_types; + bool finalized; + + // Only one of these is non-NULL. + struct wlr_data_source *active_source; + struct wlr_primary_selection_source *active_primary_source; +}; + +static const struct ext_data_control_source_v1_interface source_impl; + +static struct data_control_source *source_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_data_control_source_v1_interface, &source_impl)); + return wl_resource_get_user_data(resource); +} + +static void source_handle_offer(struct wl_client *client, + struct wl_resource *resource, const char *mime_type) { + struct data_control_source *source = source_from_resource(resource); + if (source == NULL) { + return; + } + + if (source->finalized) { + wl_resource_post_error(resource, + EXT_DATA_CONTROL_SOURCE_V1_ERROR_INVALID_OFFER, + "cannot mutate offer after set_selection or " + "set_primary_selection"); + return; + } + + const char **mime_type_ptr; + wl_array_for_each(mime_type_ptr, &source->mime_types) { + if (strcmp(*mime_type_ptr, mime_type) == 0) { + wlr_log(WLR_DEBUG, "Ignoring duplicate MIME type offer %s", + mime_type); + return; + } + } + + char *dup_mime_type = strdup(mime_type); + if (dup_mime_type == NULL) { + wl_resource_post_no_memory(resource); + return; + } + + char **p = wl_array_add(&source->mime_types, sizeof(char *)); + if (p == NULL) { + free(dup_mime_type); + wl_resource_post_no_memory(resource); + return; + } + + *p = dup_mime_type; +} + +static void source_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct ext_data_control_source_v1_interface source_impl = { + .offer = source_handle_offer, + .destroy = source_handle_destroy, +}; + +static void data_control_source_destroy(struct data_control_source *source) { + if (source == NULL) { + return; + } + + char **p; + wl_array_for_each(p, &source->mime_types) { + free(*p); + } + wl_array_release(&source->mime_types); + + // Prevent destructors below from calling this recursively. + wl_resource_set_user_data(source->resource, NULL); + + if (source->active_source != NULL) { + wlr_data_source_destroy(source->active_source); + } else if (source->active_primary_source != NULL) { + wlr_primary_selection_source_destroy( + source->active_primary_source); + } + + free(source); +} + +static void source_handle_resource_destroy(struct wl_resource *resource) { + struct data_control_source *source = source_from_resource(resource); + data_control_source_destroy(source); +} + + +struct client_data_source { + struct wlr_data_source source; + struct wl_resource *resource; +}; + +static const struct wlr_data_source_impl client_source_impl; + +static struct client_data_source * + client_data_source_from_source(struct wlr_data_source *wlr_source) { + assert(wlr_source->impl == &client_source_impl); + struct client_data_source *source = wl_container_of(wlr_source, source, source); + return source; +} + +static void client_source_send(struct wlr_data_source *wlr_source, + const char *mime_type, int fd) { + struct client_data_source *source = + client_data_source_from_source(wlr_source); + ext_data_control_source_v1_send_send(source->resource, mime_type, fd); + close(fd); +} + +static void client_source_destroy(struct wlr_data_source *wlr_source) { + struct client_data_source *client_source = + client_data_source_from_source(wlr_source); + struct data_control_source *source = + source_from_resource(client_source->resource); + free(client_source); + + if (source == NULL) { + return; + } + + source->active_source = NULL; + + ext_data_control_source_v1_send_cancelled(source->resource); + data_control_source_destroy(source); +} + +static const struct wlr_data_source_impl client_source_impl = { + .send = client_source_send, + .destroy = client_source_destroy, +}; + + +struct client_primary_selection_source { + struct wlr_primary_selection_source source; + struct wl_resource *resource; +}; + +static const struct wlr_primary_selection_source_impl +client_primary_selection_source_impl; + +static struct client_primary_selection_source * + client_primary_selection_source_from_source( + struct wlr_primary_selection_source *wlr_source) { + assert(wlr_source->impl == &client_primary_selection_source_impl); + struct client_primary_selection_source *source = wl_container_of(wlr_source, source, source); + return source; +} + +static void client_primary_selection_source_send( + struct wlr_primary_selection_source *wlr_source, + const char *mime_type, int fd) { + struct client_primary_selection_source *source = + client_primary_selection_source_from_source(wlr_source); + ext_data_control_source_v1_send_send(source->resource, mime_type, fd); + close(fd); +} + +static void client_primary_selection_source_destroy( + struct wlr_primary_selection_source *wlr_source) { + struct client_primary_selection_source *client_source = + client_primary_selection_source_from_source(wlr_source); + struct data_control_source *source = + source_from_resource(client_source->resource); + free(client_source); + + if (source == NULL) { + return; + } + + source->active_primary_source = NULL; + + ext_data_control_source_v1_send_cancelled(source->resource); + data_control_source_destroy(source); +} + +static const struct wlr_primary_selection_source_impl +client_primary_selection_source_impl = { + .send = client_primary_selection_source_send, + .destroy = client_primary_selection_source_destroy, +}; + + +struct data_offer { + struct wl_resource *resource; + struct wlr_ext_data_control_device_v1 *device; + bool is_primary; +}; + +static void data_offer_destroy(struct data_offer *offer) { + if (offer == NULL) { + return; + } + + struct wlr_ext_data_control_device_v1 *device = offer->device; + if (device != NULL) { + if (offer->is_primary) { + device->primary_selection_offer_resource = NULL; + } else { + device->selection_offer_resource = NULL; + } + } + + wl_resource_set_user_data(offer->resource, NULL); + free(offer); +} + +static const struct ext_data_control_offer_v1_interface offer_impl; + +static struct data_offer *data_offer_from_offer_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_data_control_offer_v1_interface, &offer_impl)); + return wl_resource_get_user_data(resource); +} + +static void offer_handle_receive(struct wl_client *client, + struct wl_resource *resource, const char *mime_type, int fd) { + struct data_offer *offer = data_offer_from_offer_resource(resource); + if (offer == NULL) { + close(fd); + return; + } + + struct wlr_ext_data_control_device_v1 *device = offer->device; + if (device == NULL) { + close(fd); + return; + } + + if (offer->is_primary) { + if (device->seat->primary_selection_source == NULL) { + close(fd); + return; + } + wlr_primary_selection_source_send( + device->seat->primary_selection_source, + mime_type, fd); + } else { + if (device->seat->selection_source == NULL) { + close(fd); + return; + } + wlr_data_source_send(device->seat->selection_source, mime_type, fd); + } +} + +static void offer_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct ext_data_control_offer_v1_interface offer_impl = { + .receive = offer_handle_receive, + .destroy = offer_handle_destroy, +}; + +static void offer_handle_resource_destroy(struct wl_resource *resource) { + struct data_offer *offer = data_offer_from_offer_resource(resource); + data_offer_destroy(offer); +} + +static struct wl_resource *create_offer(struct wlr_ext_data_control_device_v1 *device, + struct wl_array *mime_types, bool is_primary) { + struct wl_client *client = wl_resource_get_client(device->resource); + + struct data_offer *offer = calloc(1, sizeof(*offer)); + if (offer == NULL) { + wl_client_post_no_memory(client); + return NULL; + } + + offer->device = device; + offer->is_primary = is_primary; + + uint32_t version = wl_resource_get_version(device->resource); + struct wl_resource *resource = wl_resource_create(client, + &ext_data_control_offer_v1_interface, version, 0); + if (resource == NULL) { + free(offer); + return NULL; + } + + offer->resource = resource; + + wl_resource_set_implementation(resource, &offer_impl, offer, + offer_handle_resource_destroy); + + ext_data_control_device_v1_send_data_offer(device->resource, resource); + + char **p; + wl_array_for_each(p, mime_types) { + ext_data_control_offer_v1_send_offer(resource, *p); + } + + return resource; +} + + +static const struct ext_data_control_device_v1_interface control_impl; + +static struct wlr_ext_data_control_device_v1 *control_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_data_control_device_v1_interface, &control_impl)); + return wl_resource_get_user_data(resource); +} + +static void control_handle_set_selection(struct wl_client *client, + struct wl_resource *control_resource, + struct wl_resource *source_resource) { + struct wlr_ext_data_control_device_v1 *device = + control_from_resource(control_resource); + if (device == NULL) { + return; + } + + struct data_control_source *source = NULL; + if (source_resource != NULL) { + source = source_from_resource(source_resource); + } + + if (source == NULL) { + wlr_seat_request_set_selection(device->seat, NULL, NULL, + wl_display_next_serial(device->seat->display)); + + return; + } + + if (source->active_source != NULL || + source->active_primary_source != NULL) { + wl_resource_post_error(control_resource, + EXT_DATA_CONTROL_DEVICE_V1_ERROR_USED_SOURCE, + "cannot use a data source in set_selection or " + "set_primary_selection more than once"); + + return; + } + + struct client_data_source *client_source = calloc(1, sizeof(*client_source)); + if (client_source == NULL) { + wl_client_post_no_memory(client); + return; + } + client_source->resource = source_resource; + + struct wlr_data_source *wlr_source = &client_source->source; + wlr_data_source_init(wlr_source, &client_source_impl); + source->active_source = wlr_source; + + wl_array_release(&wlr_source->mime_types); + wlr_source->mime_types = source->mime_types; + wl_array_init(&source->mime_types); + + source->finalized = true; + + wlr_seat_request_set_selection(device->seat, NULL, wlr_source, + wl_display_next_serial(device->seat->display)); +} + +static void control_handle_set_primary_selection(struct wl_client *client, + struct wl_resource *control_resource, + struct wl_resource *source_resource) { + struct wlr_ext_data_control_device_v1 *device = + control_from_resource(control_resource); + if (device == NULL) { + return; + } + + struct data_control_source *source = NULL; + if (source_resource != NULL) { + source = source_from_resource(source_resource); + } + + if (source == NULL) { + wlr_seat_request_set_primary_selection(device->seat, NULL, NULL, + wl_display_next_serial(device->seat->display)); + + return; + } + + if (source->active_source != NULL || + source->active_primary_source != NULL) { + wl_resource_post_error(control_resource, + EXT_DATA_CONTROL_DEVICE_V1_ERROR_USED_SOURCE, + "cannot use a data source in set_selection or " + "set_primary_selection more than once"); + + return; + } + + struct client_primary_selection_source *client_source = calloc(1, sizeof(*client_source)); + if (client_source == NULL) { + wl_client_post_no_memory(client); + return; + } + client_source->resource = source_resource; + + struct wlr_primary_selection_source *wlr_source = &client_source->source; + wlr_primary_selection_source_init(wlr_source, &client_primary_selection_source_impl); + source->active_primary_source = wlr_source; + + wl_array_release(&wlr_source->mime_types); + wlr_source->mime_types = source->mime_types; + wl_array_init(&source->mime_types); + + source->finalized = true; + + wlr_seat_request_set_primary_selection(device->seat, NULL, wlr_source, + wl_display_next_serial(device->seat->display)); +} + +static void control_handle_destroy(struct wl_client *client, + struct wl_resource *control_resource) { + wl_resource_destroy(control_resource); +} + +static const struct ext_data_control_device_v1_interface control_impl = { + .set_selection = control_handle_set_selection, + .set_primary_selection = control_handle_set_primary_selection, + .destroy = control_handle_destroy, +}; + +static void control_send_selection(struct wlr_ext_data_control_device_v1 *device) { + struct wlr_data_source *source = device->seat->selection_source; + + if (device->selection_offer_resource != NULL) { + // Make the offer inert + struct data_offer *offer = data_offer_from_offer_resource( + device->selection_offer_resource); + data_offer_destroy(offer); + } + + device->selection_offer_resource = NULL; + if (source != NULL) { + device->selection_offer_resource = + create_offer(device, &source->mime_types, false); + if (device->selection_offer_resource == NULL) { + wl_resource_post_no_memory(device->resource); + return; + } + } + + ext_data_control_device_v1_send_selection(device->resource, + device->selection_offer_resource); +} + +static void control_send_primary_selection( + struct wlr_ext_data_control_device_v1 *device) { + uint32_t version = wl_resource_get_version(device->resource); + if (version < EXT_DATA_CONTROL_DEVICE_V1_PRIMARY_SELECTION_SINCE_VERSION) { + return; + } + + struct wlr_primary_selection_source *source = + device->seat->primary_selection_source; + + if (device->primary_selection_offer_resource != NULL) { + // Make the offer inert + struct data_offer *offer = data_offer_from_offer_resource( + device->primary_selection_offer_resource); + data_offer_destroy(offer); + } + + device->primary_selection_offer_resource = NULL; + if (source != NULL) { + device->primary_selection_offer_resource = + create_offer(device, &source->mime_types, true); + if (device->primary_selection_offer_resource == NULL) { + wl_resource_post_no_memory(device->resource); + return; + } + } + + ext_data_control_device_v1_send_primary_selection(device->resource, + device->primary_selection_offer_resource); +} + +static void control_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_ext_data_control_device_v1 *device = control_from_resource(resource); + wlr_ext_data_control_device_v1_destroy(device); +} + +static void control_handle_seat_destroy(struct wl_listener *listener, + void *data) { + struct wlr_ext_data_control_device_v1 *device = + wl_container_of(listener, device, seat_destroy); + wlr_ext_data_control_device_v1_destroy(device); +} + +static void control_handle_seat_set_selection(struct wl_listener *listener, + void *data) { + struct wlr_ext_data_control_device_v1 *device = + wl_container_of(listener, device, seat_set_selection); + control_send_selection(device); +} + +static void control_handle_seat_set_primary_selection( + struct wl_listener *listener, + void *data) { + struct wlr_ext_data_control_device_v1 *device = + wl_container_of(listener, device, seat_set_primary_selection); + control_send_primary_selection(device); +} + +void wlr_ext_data_control_device_v1_destroy(struct wlr_ext_data_control_device_v1 *device) { + if (device == NULL) { + return; + } + ext_data_control_device_v1_send_finished(device->resource); + // Make the resources inert + wl_resource_set_user_data(device->resource, NULL); + if (device->selection_offer_resource != NULL) { + struct data_offer *offer = data_offer_from_offer_resource( + device->selection_offer_resource); + data_offer_destroy(offer); + } + if (device->primary_selection_offer_resource != NULL) { + struct data_offer *offer = data_offer_from_offer_resource( + device->primary_selection_offer_resource); + data_offer_destroy(offer); + } + wl_list_remove(&device->seat_destroy.link); + wl_list_remove(&device->seat_set_selection.link); + wl_list_remove(&device->seat_set_primary_selection.link); + wl_list_remove(&device->link); + free(device); +} + + +static const struct ext_data_control_manager_v1_interface manager_impl; + +static struct wlr_ext_data_control_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_data_control_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void manager_handle_create_data_source(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id) { + struct data_control_source *source = calloc(1, sizeof(*source)); + if (source == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + + wl_array_init(&source->mime_types); + + uint32_t version = wl_resource_get_version(manager_resource); + source->resource = wl_resource_create(client, + &ext_data_control_source_v1_interface, version, id); + if (source->resource == NULL) { + wl_resource_post_no_memory(manager_resource); + wl_array_release(&source->mime_types); + free(source); + return; + } + wl_resource_set_implementation(source->resource, &source_impl, source, + source_handle_resource_destroy); +} + +static void manager_handle_get_data_device(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + struct wl_resource *seat_resource) { + struct wlr_ext_data_control_manager_v1 *manager = + manager_from_resource(manager_resource); + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat_resource); + + uint32_t version = wl_resource_get_version(manager_resource); + struct wl_resource *resource = wl_resource_create(client, + &ext_data_control_device_v1_interface, version, id); + if (resource == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + wl_resource_set_implementation(resource, &control_impl, NULL, + control_handle_resource_destroy); + if (seat_client == NULL) { + return; + } + + struct wlr_ext_data_control_device_v1 *device = calloc(1, sizeof(*device)); + if (device == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + device->manager = manager; + device->seat = seat_client->seat; + device->resource = resource; + wl_resource_set_user_data(resource, device); + + device->seat_destroy.notify = control_handle_seat_destroy; + wl_signal_add(&device->seat->events.destroy, &device->seat_destroy); + + device->seat_set_selection.notify = control_handle_seat_set_selection; + wl_signal_add(&device->seat->events.set_selection, + &device->seat_set_selection); + + device->seat_set_primary_selection.notify = + control_handle_seat_set_primary_selection; + wl_signal_add(&device->seat->events.set_primary_selection, + &device->seat_set_primary_selection); + + wl_list_insert(&manager->devices, &device->link); + wl_signal_emit_mutable(&manager->events.new_device, device); + + // At this point maybe the compositor decided to destroy the device. If + // it's the case then the resource will be inert. + device = control_from_resource(resource); + if (device != NULL) { + control_send_selection(device); + control_send_primary_selection(device); + } +} + +static void manager_handle_destroy(struct wl_client *client, + struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static const struct ext_data_control_manager_v1_interface manager_impl = { + .create_data_source = manager_handle_create_data_source, + .get_data_device = manager_handle_get_data_device, + .destroy = manager_handle_destroy, +}; + +static void manager_bind(struct wl_client *client, void *data, uint32_t version, + uint32_t id) { + struct wlr_ext_data_control_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &ext_data_control_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, manager, NULL); +} + +static void ext_data_control_manager_v1_destroy(struct wlr_ext_data_control_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + assert(wl_list_empty(&manager->events.new_device.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_ext_data_control_manager_v1_destroy(struct wlr_ext_data_control_manager_v1 *manager, + bool destroy_global_safe) { + ext_data_control_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_ext_data_control_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + ext_data_control_manager_v1_destroy(manager, false); +} + +struct wlr_ext_data_control_manager_v1 *wlr_ext_data_control_manager_v1_create( + struct wl_display *display, uint32_t version) { + assert(version <= EXT_DATA_CONTROL_MANAGER_VERSION); + + struct wlr_ext_data_control_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + wl_list_init(&manager->devices); + wl_signal_init(&manager->events.destroy); + wl_signal_init(&manager->events.new_device); + + manager->global = wl_global_create(display, + &ext_data_control_manager_v1_interface, + version, manager, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_ext_foreign_toplevel_list_v1.c b/3rdparty/wlroots/types/wlr_ext_foreign_toplevel_list_v1.c new file mode 100644 index 0000000000..079768ea5a --- /dev/null +++ b/3rdparty/wlroots/types/wlr_ext_foreign_toplevel_list_v1.c @@ -0,0 +1,313 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "ext-foreign-toplevel-list-v1-protocol.h" + +#include "util/token.h" +#include "util/global.h" + +#define FOREIGN_TOPLEVEL_LIST_V1_VERSION 1 + +static const struct ext_foreign_toplevel_handle_v1_interface toplevel_handle_impl; + +static void foreign_toplevel_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_foreign_toplevel_handle_v1_interface, + &toplevel_handle_impl)); + + wl_resource_destroy(resource); +} + +static const struct ext_foreign_toplevel_handle_v1_interface toplevel_handle_impl = { + .destroy = foreign_toplevel_handle_destroy, +}; + +// Returns true if clients need to be notified about the update +static bool update_string(struct wlr_ext_foreign_toplevel_handle_v1 *toplevel, + char **dst, const char *src) { + if (src == NULL) { + if (*dst == NULL) { + return false; + } + } else if (*dst != NULL && strcmp(*dst, src) == 0) { + return false; + } + + free(*dst); + if (src != NULL) { + *dst = strdup(src); + if (*dst == NULL) { + struct wl_resource *resource; + wl_resource_for_each(resource, &toplevel->resources) { + wl_resource_post_no_memory(resource); + } + return false; + } + } else { + *dst = NULL; + } + return true; +} + +struct wlr_ext_foreign_toplevel_handle_v1 *wlr_ext_foreign_toplevel_handle_v1_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &ext_foreign_toplevel_handle_v1_interface, + &toplevel_handle_impl)); + return wl_resource_get_user_data(resource); +} + +void wlr_ext_foreign_toplevel_handle_v1_update_state( + struct wlr_ext_foreign_toplevel_handle_v1 *toplevel, + const struct wlr_ext_foreign_toplevel_handle_v1_state *state) { + bool changed_app_id = update_string(toplevel, &toplevel->app_id, state->app_id); + bool changed_title = update_string(toplevel, &toplevel->title, state->title); + + if (!changed_app_id && !changed_title) { + return; + } + + struct wl_resource *resource; + wl_resource_for_each(resource, &toplevel->resources) { + if (changed_app_id) { + ext_foreign_toplevel_handle_v1_send_app_id(resource, state->app_id ? state->app_id : ""); + } + if (changed_title) { + ext_foreign_toplevel_handle_v1_send_title(resource, state->title ? state->title : ""); + } + ext_foreign_toplevel_handle_v1_send_done(resource); + } +} + +void wlr_ext_foreign_toplevel_handle_v1_destroy( + struct wlr_ext_foreign_toplevel_handle_v1 *toplevel) { + if (!toplevel) { + return; + } + + wl_signal_emit_mutable(&toplevel->events.destroy, NULL); + + assert(wl_list_empty(&toplevel->events.destroy.listener_list)); + + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &toplevel->resources) { + ext_foreign_toplevel_handle_v1_send_closed(resource); + wl_resource_set_user_data(resource, NULL); + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + } + + wl_list_remove(&toplevel->link); + + free(toplevel->title); + free(toplevel->app_id); + free(toplevel->identifier); + free(toplevel); +} + +static void foreign_toplevel_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static struct wl_resource *create_toplevel_resource_for_resource( + struct wlr_ext_foreign_toplevel_handle_v1 *toplevel, + struct wl_resource *list_resource) { + struct wl_client *client = wl_resource_get_client(list_resource); + struct wl_resource *resource = wl_resource_create(client, + &ext_foreign_toplevel_handle_v1_interface, + wl_resource_get_version(list_resource), 0); + if (!resource) { + wl_client_post_no_memory(client); + return NULL; + } + + wl_resource_set_implementation(resource, &toplevel_handle_impl, toplevel, + foreign_toplevel_resource_destroy); + + wl_list_insert(&toplevel->resources, wl_resource_get_link(resource)); + ext_foreign_toplevel_list_v1_send_toplevel(list_resource, resource); + return resource; +} + +static void toplevel_send_details_to_toplevel_resource( + struct wlr_ext_foreign_toplevel_handle_v1 *toplevel, + struct wl_resource *resource) { + if (toplevel->title) { + ext_foreign_toplevel_handle_v1_send_title(resource, toplevel->title); + } + if (toplevel->app_id) { + ext_foreign_toplevel_handle_v1_send_app_id(resource, toplevel->app_id); + } + assert(toplevel->identifier); // Required to exist by protocol. + ext_foreign_toplevel_handle_v1_send_identifier(resource, toplevel->identifier); + ext_foreign_toplevel_handle_v1_send_done(resource); +} + +struct wlr_ext_foreign_toplevel_handle_v1 * +wlr_ext_foreign_toplevel_handle_v1_create(struct wlr_ext_foreign_toplevel_list_v1 *list, + const struct wlr_ext_foreign_toplevel_handle_v1_state *state) { + struct wlr_ext_foreign_toplevel_handle_v1 *toplevel = calloc(1, sizeof(*toplevel)); + if (!toplevel) { + wlr_log(WLR_ERROR, "failed to allocate memory for toplevel handle"); + return NULL; + } + + toplevel->identifier = calloc(TOKEN_SIZE, sizeof(char)); + if (toplevel->identifier == NULL) { + wlr_log(WLR_ERROR, "failed to allocate memory for toplevel identifier"); + free(toplevel); + return NULL; + } + + if (!generate_token(toplevel->identifier)) { + free(toplevel->identifier); + free(toplevel); + return NULL; + } + + wl_list_insert(list->toplevels.prev, &toplevel->link); + toplevel->list = list; + if (state->app_id) { + toplevel->app_id = strdup(state->app_id); + } + if (state->title) { + toplevel->title = strdup(state->title); + } + + wl_list_init(&toplevel->resources); + + wl_signal_init(&toplevel->events.destroy); + + struct wl_resource *list_resource, *toplevel_resource; + wl_resource_for_each(list_resource, &list->resources) { + toplevel_resource = create_toplevel_resource_for_resource(toplevel, list_resource); + if (!toplevel_resource) { + continue; + } + toplevel_send_details_to_toplevel_resource(toplevel, toplevel_resource); + } + + return toplevel; +} + +static const struct ext_foreign_toplevel_list_v1_interface + foreign_toplevel_list_impl; + +static void foreign_toplevel_list_handle_stop(struct wl_client *client, + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_foreign_toplevel_list_v1_interface, + &foreign_toplevel_list_impl)); + + ext_foreign_toplevel_list_v1_send_finished(resource); + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); +} + +static void foreign_toplevel_list_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_foreign_toplevel_list_v1_interface, + &foreign_toplevel_list_impl)); + + wl_resource_destroy(resource); +} + +static const struct ext_foreign_toplevel_list_v1_interface + foreign_toplevel_list_impl = { + .stop = foreign_toplevel_list_handle_stop, + .destroy = foreign_toplevel_list_handle_destroy +}; + +static void foreign_toplevel_list_resource_destroy( + struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void foreign_toplevel_list_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_ext_foreign_toplevel_list_v1 *list = data; + struct wl_resource *resource = wl_resource_create(client, + &ext_foreign_toplevel_list_v1_interface, version, id); + if (!resource) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &foreign_toplevel_list_impl, + list, foreign_toplevel_list_resource_destroy); + wl_list_init(wl_resource_get_link(resource)); + if (list == NULL) { + return; + } + + + wl_list_insert(&list->resources, wl_resource_get_link(resource)); + + struct wlr_ext_foreign_toplevel_handle_v1 *toplevel; + wl_list_for_each(toplevel, &list->toplevels, link) { + struct wl_resource *toplevel_resource = + create_toplevel_resource_for_resource(toplevel, resource); + toplevel_send_details_to_toplevel_resource(toplevel, + toplevel_resource); + } +} + +static void ext_foreign_toplevel_list_v1_destroy(struct wlr_ext_foreign_toplevel_list_v1 *list, + bool destroy_global_safe) { + wl_signal_emit_mutable(&list->events.destroy, NULL); + + assert(wl_list_empty(&list->events.destroy.listener_list)); + + wl_list_remove(&list->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(list->global); + } else { + wl_global_destroy(list->global); + } + free(list); +} + +void wlr_ext_foreign_toplevel_list_v1_destroy(struct wlr_ext_foreign_toplevel_list_v1 *list, + bool destroy_global_safe) { + ext_foreign_toplevel_list_v1_destroy(list, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_ext_foreign_toplevel_list_v1 *list = + wl_container_of(listener, list, display_destroy); + ext_foreign_toplevel_list_v1_destroy(list, false); +} + +struct wlr_ext_foreign_toplevel_list_v1 *wlr_ext_foreign_toplevel_list_v1_create( + struct wl_display *display, uint32_t version) { + assert(version <= FOREIGN_TOPLEVEL_LIST_V1_VERSION); + + struct wlr_ext_foreign_toplevel_list_v1 *list = calloc(1, sizeof(*list)); + if (!list) { + return NULL; + } + + list->global = wl_global_create(display, + &ext_foreign_toplevel_list_v1_interface, + version, list, + foreign_toplevel_list_bind); + if (!list->global) { + free(list); + return NULL; + } + + wl_signal_init(&list->events.destroy); + + wl_list_init(&list->resources); + wl_list_init(&list->toplevels); + + list->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &list->display_destroy); + + return list; +} diff --git a/3rdparty/wlroots/types/wlr_ext_image_copy_capture_v1.c b/3rdparty/wlroots/types/wlr_ext_image_copy_capture_v1.c new file mode 100644 index 0000000000..2d481e8b63 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_ext_image_copy_capture_v1.c @@ -0,0 +1,718 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ext-image-copy-capture-v1-protocol.h" +#include "render/pixel_format.h" +#include "util/global.h" + +#define IMAGE_COPY_CAPTURE_MANAGER_V1_VERSION 1 + +struct wlr_ext_image_copy_capture_cursor_session_v1 { + struct wl_resource *resource; + struct wlr_ext_image_capture_source_v1_cursor *source; + struct wlr_ext_image_copy_capture_manager_v1 *manager; + bool capture_session_created; + + struct { + bool entered; + int32_t x, y; + struct { + int32_t x, y; + } hotspot; + } prev; + + struct wl_listener source_destroy; + struct wl_listener source_update; +}; + +static const struct ext_image_copy_capture_manager_v1_interface manager_impl; +static const struct ext_image_copy_capture_frame_v1_interface frame_impl; +static const struct ext_image_copy_capture_session_v1_interface session_impl; +static const struct ext_image_copy_capture_cursor_session_v1_interface cursor_session_impl; + +static struct wlr_ext_image_copy_capture_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_image_copy_capture_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_ext_image_copy_capture_frame_v1 *frame_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_image_copy_capture_frame_v1_interface, &frame_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_ext_image_copy_capture_session_v1 *session_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_image_copy_capture_session_v1_interface, &session_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_ext_image_copy_capture_cursor_session_v1 *cursor_session_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_image_copy_capture_cursor_session_v1_interface, &cursor_session_impl)); + return wl_resource_get_user_data(resource); +} + +static void frame_destroy(struct wlr_ext_image_copy_capture_frame_v1 *frame) { + if (frame == NULL) { + return; + } + wl_signal_emit_mutable(&frame->events.destroy, NULL); + assert(wl_list_empty(&frame->events.destroy.listener_list)); + wl_resource_set_user_data(frame->resource, NULL); + wlr_buffer_unlock(frame->buffer); + pixman_region32_fini(&frame->buffer_damage); + if (frame->session->frame == frame) { + frame->session->frame = NULL; + } + free(frame); +} + +static void frame_handle_resource_destroy(struct wl_resource *resource) { + frame_destroy(wl_resource_get_user_data(resource)); +} + +void wlr_ext_image_copy_capture_frame_v1_ready(struct wlr_ext_image_copy_capture_frame_v1 *frame, + enum wl_output_transform transform, + const struct timespec *presentation_time) { + assert(frame->capturing); + + int rects_len = 0; + const pixman_box32_t *rects = + pixman_region32_rectangles(&frame->session->damage, &rects_len); + for (int i = 0; i < rects_len; i++) { + const pixman_box32_t *rect = &rects[i]; + ext_image_copy_capture_frame_v1_send_damage(frame->resource, + rect->x1, rect->y1, rect->x2 - rect->x1, rect->y2 - rect->y1); + } + + pixman_region32_clear(&frame->session->damage); + + uint64_t pres_time_sec = (uint64_t)presentation_time->tv_sec; + ext_image_copy_capture_frame_v1_send_transform(frame->resource, transform); + ext_image_copy_capture_frame_v1_send_presentation_time(frame->resource, + pres_time_sec >> 32, (uint32_t)pres_time_sec, presentation_time->tv_nsec); + ext_image_copy_capture_frame_v1_send_ready(frame->resource); + frame_destroy(frame); +} + +static bool copy_dmabuf(struct wlr_buffer *dst, + struct wlr_buffer *src, struct wlr_renderer *renderer, + const pixman_region32_t *clip) { + struct wlr_texture *texture = wlr_texture_from_buffer(renderer, src); + if (texture == NULL) { + return false; + } + + bool ok = false; + struct wlr_render_pass *pass = wlr_renderer_begin_buffer_pass(renderer, dst, NULL); + if (!pass) { + goto out; + } + + wlr_render_pass_add_texture(pass, &(struct wlr_render_texture_options) { + .texture = texture, + .clip = clip, + .blend_mode = WLR_RENDER_BLEND_MODE_NONE, + }); + + ok = wlr_render_pass_submit(pass); + +out: + wlr_texture_destroy(texture); + return ok; +} + +static bool copy_shm(void *data, uint32_t format, size_t stride, + struct wlr_buffer *src, struct wlr_renderer *renderer) { + // TODO: bypass renderer if source buffer supports data ptr access + struct wlr_texture *texture = wlr_texture_from_buffer(renderer, src); + if (!texture) { + return false; + } + + // TODO: only copy damaged region + bool ok = wlr_texture_read_pixels(texture, &(struct wlr_texture_read_pixels_options){ + .data = data, + .format = format, + .stride = stride, + }); + + wlr_texture_destroy(texture); + + return ok; +} + +bool wlr_ext_image_copy_capture_frame_v1_copy_buffer(struct wlr_ext_image_copy_capture_frame_v1 *frame, + struct wlr_buffer *src, struct wlr_renderer *renderer) { + struct wlr_buffer *dst = frame->buffer; + + if (src->width != dst->width || src->height != dst->height) { + wlr_ext_image_copy_capture_frame_v1_fail(frame, + EXT_IMAGE_COPY_CAPTURE_FRAME_V1_FAILURE_REASON_BUFFER_CONSTRAINTS); + return false; + } + + bool ok = false; + enum ext_image_copy_capture_frame_v1_failure_reason failure_reason = + EXT_IMAGE_COPY_CAPTURE_FRAME_V1_FAILURE_REASON_UNKNOWN; + struct wlr_dmabuf_attributes dmabuf; + void *data; + uint32_t format; + size_t stride; + if (wlr_buffer_get_dmabuf(dst, &dmabuf)) { + if (frame->session->source->dmabuf_formats.len == 0) { + ok = false; + failure_reason = EXT_IMAGE_COPY_CAPTURE_FRAME_V1_FAILURE_REASON_BUFFER_CONSTRAINTS; + } else { + ok = copy_dmabuf(dst, src, renderer, &frame->buffer_damage); + } + } else if (wlr_buffer_begin_data_ptr_access(dst, + WLR_BUFFER_DATA_PTR_ACCESS_WRITE, &data, &format, &stride)) { + if (frame->session->source->shm_formats_len == 0) { + ok = false; + failure_reason = EXT_IMAGE_COPY_CAPTURE_FRAME_V1_FAILURE_REASON_BUFFER_CONSTRAINTS; + } else { + ok = copy_shm(data, format, stride, src, renderer); + } + wlr_buffer_end_data_ptr_access(dst); + } + if (!ok) { + wlr_ext_image_copy_capture_frame_v1_fail(frame, failure_reason); + return false; + } + + return true; +} + +void wlr_ext_image_copy_capture_frame_v1_fail(struct wlr_ext_image_copy_capture_frame_v1 *frame, + enum ext_image_copy_capture_frame_v1_failure_reason reason) { + ext_image_copy_capture_frame_v1_send_failed(frame->resource, reason); + frame_destroy(frame); +} + +static void frame_handle_destroy(struct wl_client *client, + struct wl_resource *frame_resource) { + wl_resource_destroy(frame_resource); +} + +static void frame_handle_attach_buffer(struct wl_client *client, + struct wl_resource *frame_resource, struct wl_resource *buffer_resource) { + struct wlr_ext_image_copy_capture_frame_v1 *frame = frame_from_resource(frame_resource); + if (frame == NULL) { + return; + } + + if (frame->capturing) { + wl_resource_post_error(frame->resource, + EXT_IMAGE_COPY_CAPTURE_FRAME_V1_ERROR_ALREADY_CAPTURED, + "attach_buffer sent after capture"); + return; + } + + struct wlr_buffer *buffer = wlr_buffer_try_from_resource(buffer_resource); + if (buffer == NULL) { + wl_resource_post_no_memory(frame_resource); + return; + } + + wlr_buffer_unlock(frame->buffer); + frame->buffer = buffer; +} + +static void frame_handle_damage_buffer(struct wl_client *client, + struct wl_resource *frame_resource, int32_t x, int32_t y, + int32_t width, int32_t height) { + struct wlr_ext_image_copy_capture_frame_v1 *frame = frame_from_resource(frame_resource); + if (frame == NULL) { + return; + } + + if (frame->capturing) { + wl_resource_post_error(frame->resource, + EXT_IMAGE_COPY_CAPTURE_FRAME_V1_ERROR_ALREADY_CAPTURED, + "damage_buffer sent after capture"); + return; + } + + if (x < 0 || y < 0 || width <= 0 || height <= 0) { + wl_resource_post_error(frame->resource, + EXT_IMAGE_COPY_CAPTURE_FRAME_V1_ERROR_INVALID_BUFFER_DAMAGE, + "Invalid buffer damage coordinates"); + return; + } + + pixman_region32_union_rect(&frame->buffer_damage, &frame->buffer_damage, + x, y, width, height); +} + +static void frame_handle_capture(struct wl_client *client, + struct wl_resource *frame_resource) { + struct wlr_ext_image_copy_capture_frame_v1 *frame = frame_from_resource(frame_resource); + if (frame == NULL) { + return; + } + + if (frame->capturing) { + wl_resource_post_error(frame->resource, + EXT_IMAGE_COPY_CAPTURE_FRAME_V1_ERROR_ALREADY_CAPTURED, + "capture sent twice"); + return; + } + + if (frame->buffer == NULL) { + wl_resource_post_error(frame->resource, + EXT_IMAGE_COPY_CAPTURE_FRAME_V1_ERROR_NO_BUFFER, + "No buffer attached"); + return; + } + + frame->capturing = true; + + bool schedule_frame = !pixman_region32_empty(&frame->session->damage); + struct wlr_ext_image_capture_source_v1 *source = frame->session->source; + if (source->impl->request_frame) { + source->impl->request_frame(source, schedule_frame); + } +} + +static const struct ext_image_copy_capture_frame_v1_interface frame_impl = { + .destroy = frame_handle_destroy, + .attach_buffer = frame_handle_attach_buffer, + .damage_buffer = frame_handle_damage_buffer, + .capture = frame_handle_capture, +}; + +static void session_handle_destroy(struct wl_client *client, + struct wl_resource *session_resource) { + wl_resource_destroy(session_resource); +} + +static void session_handle_create_frame(struct wl_client *client, + struct wl_resource *session_resource, uint32_t new_id) { + struct wlr_ext_image_copy_capture_session_v1 *session = session_from_resource(session_resource); + + if (session != NULL && session->frame != NULL) { + wl_resource_post_error(session_resource, + EXT_IMAGE_COPY_CAPTURE_SESSION_V1_ERROR_DUPLICATE_FRAME, + "session already has a frame object"); + return; + } + + uint32_t version = wl_resource_get_version(session_resource); + struct wl_resource *frame_resource = wl_resource_create(client, + &ext_image_copy_capture_frame_v1_interface, version, new_id); + if (frame_resource == NULL) { + wl_resource_post_no_memory(frame_resource); + return; + } + wl_resource_set_implementation(frame_resource, &frame_impl, NULL, + frame_handle_resource_destroy); + + if (session == NULL) { + ext_image_copy_capture_frame_v1_send_failed(frame_resource, + EXT_IMAGE_COPY_CAPTURE_FRAME_V1_FAILURE_REASON_STOPPED); + return; + } + + struct wlr_ext_image_copy_capture_frame_v1 *frame = calloc(1, sizeof(*frame)); + if (frame == NULL) { + wl_resource_post_no_memory(session_resource); + return; + } + + frame->resource = frame_resource; + frame->session = session; + pixman_region32_init(&frame->buffer_damage); + wl_signal_init(&frame->events.destroy); + + wl_resource_set_user_data(frame_resource, frame); + + session->frame = frame; +} + +static const struct ext_image_copy_capture_session_v1_interface session_impl = { + .destroy = session_handle_destroy, + .create_frame = session_handle_create_frame, +}; + +static void session_send_constraints(struct wlr_ext_image_copy_capture_session_v1 *session) { + struct wlr_ext_image_capture_source_v1 *source = session->source; + + ext_image_copy_capture_session_v1_send_buffer_size(session->resource, + source->width, source->height); + + for (size_t i = 0; i < source->shm_formats_len; i++) { + ext_image_copy_capture_session_v1_send_shm_format(session->resource, + convert_drm_format_to_wl_shm(source->shm_formats[i])); + } + + if (source->dmabuf_formats.len > 0) { + struct wl_array dev_id_array = { + .data = &source->dmabuf_device, + .size = sizeof(source->dmabuf_device), + }; + ext_image_copy_capture_session_v1_send_dmabuf_device(session->resource, + &dev_id_array); + } + for (size_t i = 0; i < source->dmabuf_formats.len; i++) { + struct wlr_drm_format *fmt = &source->dmabuf_formats.formats[i]; + struct wl_array modifiers_array = { + .data = fmt->modifiers, + .size = fmt->len * sizeof(fmt->modifiers[0]), + }; + ext_image_copy_capture_session_v1_send_dmabuf_format(session->resource, + fmt->format, &modifiers_array); + } + + ext_image_copy_capture_session_v1_send_done(session->resource); +} + +static void session_destroy(struct wlr_ext_image_copy_capture_session_v1 *session) { + if (session == NULL) { + return; + } + + wl_signal_emit_mutable(&session->events.destroy, NULL); + + if (session->frame != NULL) { + wlr_ext_image_copy_capture_frame_v1_fail(session->frame, + EXT_IMAGE_COPY_CAPTURE_FRAME_V1_FAILURE_REASON_STOPPED); + } + + if (session->source->impl->stop) { + session->source->impl->stop(session->source); + } + + ext_image_copy_capture_session_v1_send_stopped(session->resource); + wl_resource_set_user_data(session->resource, NULL); + + pixman_region32_fini(&session->damage); + wl_list_remove(&session->source_destroy.link); + wl_list_remove(&session->source_constraints_update.link); + wl_list_remove(&session->source_frame.link); + + assert(wl_list_empty(&session->events.destroy.listener_list)); + + free(session); +} + +static void session_handle_source_destroy(struct wl_listener *listener, void *data) { + struct wlr_ext_image_copy_capture_session_v1 *session = wl_container_of(listener, session, source_destroy); + session_destroy(session); +} + +static void session_handle_source_constraints_update(struct wl_listener *listener, + void *data) { + struct wlr_ext_image_copy_capture_session_v1 *session = + wl_container_of(listener, session, source_constraints_update); + session_send_constraints(session); +} + +static void session_handle_source_frame(struct wl_listener *listener, void *data) { + struct wlr_ext_image_copy_capture_session_v1 *session = wl_container_of(listener, session, source_frame); + struct wlr_ext_image_capture_source_v1_frame_event *event = data; + + pixman_region32_union(&session->damage, &session->damage, event->damage); + + struct wlr_ext_image_copy_capture_frame_v1 *frame = session->frame; + if (frame != NULL && frame->capturing && + !pixman_region32_empty(&session->damage)) { + pixman_region32_union(&frame->buffer_damage, + &frame->buffer_damage, &session->damage); + + struct wlr_ext_image_capture_source_v1 *source = frame->session->source; + source->impl->copy_frame(source, frame, event); + } +} + +static void session_handle_resource_destroy(struct wl_resource *resource) { + session_destroy(session_from_resource(resource)); +} + +static void session_create(struct wl_resource *parent_resource, uint32_t new_id, + struct wlr_ext_image_capture_source_v1 *source, uint32_t options, struct wlr_ext_image_copy_capture_manager_v1 *manager) { + struct wl_client *client = wl_resource_get_client(parent_resource); + uint32_t version = wl_resource_get_version(parent_resource); + struct wl_resource *session_resource = wl_resource_create(client, + &ext_image_copy_capture_session_v1_interface, version, new_id); + if (session_resource == NULL) { + wl_resource_post_no_memory(parent_resource); + return; + } + wl_resource_set_implementation(session_resource, &session_impl, NULL, + session_handle_resource_destroy); + + if (source == NULL) { + ext_image_copy_capture_session_v1_send_stopped(session_resource); + return; + } + + struct wlr_ext_image_copy_capture_session_v1 *session = calloc(1, sizeof(*session)); + if (session == NULL) { + wl_resource_post_no_memory(parent_resource); + return; + } + + if (source->impl->start) { + source->impl->start(source, options & EXT_IMAGE_COPY_CAPTURE_MANAGER_V1_OPTIONS_PAINT_CURSORS); + } + + session->resource = session_resource; + session->source = source; + pixman_region32_init_rect(&session->damage, 0, 0, source->width, + source->height); + + session->source_destroy.notify = session_handle_source_destroy; + wl_signal_add(&source->events.destroy, &session->source_destroy); + + session->source_constraints_update.notify = session_handle_source_constraints_update; + wl_signal_add(&source->events.constraints_update, &session->source_constraints_update); + + session->source_frame.notify = session_handle_source_frame; + wl_signal_add(&source->events.frame, &session->source_frame); + + wl_resource_set_user_data(session_resource, session); + session_send_constraints(session); + + wl_signal_init(&session->events.destroy); + wl_signal_emit_mutable(&manager->events.new_session, session); +} + +static void cursor_session_destroy(struct wlr_ext_image_copy_capture_cursor_session_v1 *cursor_session) { + if (cursor_session == NULL) { + return; + } + if (cursor_session->source->entered) { + ext_image_copy_capture_cursor_session_v1_send_leave(cursor_session->resource); + } + wl_resource_set_user_data(cursor_session->resource, NULL); + wl_list_remove(&cursor_session->source_destroy.link); + wl_list_remove(&cursor_session->source_update.link); + free(cursor_session); +} + +static void cursor_session_handle_destroy(struct wl_client *client, + struct wl_resource *cursor_session_resource) { + wl_resource_destroy(cursor_session_resource); +} + +static void cursor_session_handle_get_capture_session(struct wl_client *client, + struct wl_resource *cursor_session_resource, uint32_t new_id) { + struct wlr_ext_image_copy_capture_cursor_session_v1 *cursor_session = + cursor_session_from_resource(cursor_session_resource); + + if (cursor_session != NULL && cursor_session->capture_session_created) { + wl_resource_post_error(cursor_session_resource, + EXT_IMAGE_COPY_CAPTURE_CURSOR_SESSION_V1_ERROR_DUPLICATE_SESSION, + "get_capture_session sent twice"); + return; + } + + struct wlr_ext_image_copy_capture_manager_v1 *manager = NULL; + struct wlr_ext_image_capture_source_v1 *source = NULL; + + if (cursor_session != NULL) { + manager = cursor_session->manager; + cursor_session->capture_session_created = true; + source = &cursor_session->source->base; + } + + session_create(cursor_session_resource, new_id, source, 0, manager); +} + +static const struct ext_image_copy_capture_cursor_session_v1_interface cursor_session_impl = { + .destroy = cursor_session_handle_destroy, + .get_capture_session = cursor_session_handle_get_capture_session, +}; + +static void cursor_session_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_ext_image_copy_capture_cursor_session_v1 *cursor_session = + cursor_session_from_resource(resource); + cursor_session_destroy(cursor_session); +} + +static void cursor_session_handle_source_destroy(struct wl_listener *listener, + void *data) { + struct wlr_ext_image_copy_capture_cursor_session_v1 *cursor_session = + wl_container_of(listener, cursor_session, source_destroy); + cursor_session_destroy(cursor_session); +} + +static void cursor_session_update( + struct wlr_ext_image_copy_capture_cursor_session_v1 *cursor_session) { + struct wlr_ext_image_capture_source_v1_cursor *cursor_source = cursor_session->source; + + if (cursor_source->entered && !cursor_session->prev.entered) { + ext_image_copy_capture_cursor_session_v1_send_enter(cursor_session->resource); + } + if (!cursor_source->entered && cursor_session->prev.entered) { + ext_image_copy_capture_cursor_session_v1_send_leave(cursor_session->resource); + } + + if (cursor_source->x != cursor_session->prev.x || + cursor_source->y != cursor_session->prev.y) { + ext_image_copy_capture_cursor_session_v1_send_position(cursor_session->resource, + cursor_source->x, cursor_source->y); + } + + if (cursor_source->hotspot.x != cursor_session->prev.hotspot.x || + cursor_source->hotspot.y != cursor_session->prev.hotspot.y) { + ext_image_copy_capture_cursor_session_v1_send_hotspot(cursor_session->resource, + cursor_source->hotspot.x, cursor_source->hotspot.y); + } + + cursor_session->prev.entered = cursor_source->entered; + cursor_session->prev.x = cursor_source->x; + cursor_session->prev.y = cursor_source->y; + cursor_session->prev.hotspot.y = cursor_source->hotspot.y; + cursor_session->prev.hotspot.y = cursor_source->hotspot.y; +} + +static void cursor_session_handle_source_update(struct wl_listener *listener, + void *data) { + struct wlr_ext_image_copy_capture_cursor_session_v1 *cursor_session = + wl_container_of(listener, cursor_session, source_update); + cursor_session_update(cursor_session); +} + +static void manager_handle_create_session(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t new_id, + struct wl_resource *source_resource, uint32_t options) { + struct wlr_ext_image_capture_source_v1 *source = + wlr_ext_image_capture_source_v1_from_resource(source_resource); + session_create(manager_resource, new_id, source, options, manager_from_resource(manager_resource)); +} + +static void manager_handle_create_pointer_cursor_session(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t new_id, + struct wl_resource *source_resource, struct wl_resource *pointer_resource) { + struct wlr_ext_image_capture_source_v1 *source = wlr_ext_image_capture_source_v1_from_resource(source_resource); + struct wlr_seat_client *seat_client = wlr_seat_client_from_pointer_resource(pointer_resource); + + struct wlr_seat *seat = NULL; + if (seat_client != NULL) { + seat = seat_client->seat; + } + + struct wlr_ext_image_capture_source_v1_cursor *source_cursor = NULL; + if (source != NULL && seat != NULL && source->impl->get_pointer_cursor) { + source_cursor = source->impl->get_pointer_cursor(source, seat); + } + + uint32_t version = wl_resource_get_version(manager_resource); + struct wl_resource *cursor_session_resource = wl_resource_create(client, + &ext_image_copy_capture_cursor_session_v1_interface, version, new_id); + if (cursor_session_resource == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + wl_resource_set_implementation(cursor_session_resource, &cursor_session_impl, NULL, + cursor_session_handle_resource_destroy); + + if (source_cursor == NULL) { + return; // leave inert + } + + struct wlr_ext_image_copy_capture_cursor_session_v1 *cursor_session = calloc(1, sizeof(*cursor_session)); + if (cursor_session == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + + cursor_session->resource = cursor_session_resource; + cursor_session->source = source_cursor; + cursor_session->manager = manager_from_resource(manager_resource); + + cursor_session->source_destroy.notify = cursor_session_handle_source_destroy; + wl_signal_add(&source_cursor->base.events.destroy, &cursor_session->source_destroy); + + cursor_session->source_update.notify = cursor_session_handle_source_update; + wl_signal_add(&source_cursor->events.update, &cursor_session->source_update); + + wl_resource_set_user_data(cursor_session_resource, cursor_session); + + cursor_session_update(cursor_session); +} + +static void manager_handle_destroy(struct wl_client *client, + struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static const struct ext_image_copy_capture_manager_v1_interface manager_impl = { + .create_session = manager_handle_create_session, + .create_pointer_cursor_session = manager_handle_create_pointer_cursor_session, + .destroy = manager_handle_destroy, +}; + +static void manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_ext_image_copy_capture_manager_v1 *manager = data; + struct wl_resource *resource = wl_resource_create(client, + &ext_image_copy_capture_manager_v1_interface, version, id); + if (!resource) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, manager, NULL); +} + +static void ext_image_copy_capture_manager_v1_destroy( + struct wlr_ext_image_copy_capture_manager_v1 *manager, + bool destroy_global_safe) { + assert(wl_list_empty(&manager->events.new_session.listener_list)); + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_ext_image_copy_capture_manager_v1_destroy( + struct wlr_ext_image_copy_capture_manager_v1 *manager, bool destroy_global_safe) { + ext_image_copy_capture_manager_v1_destroy(manager, destroy_global_safe); +} + +static void manager_handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_ext_image_copy_capture_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + ext_image_copy_capture_manager_v1_destroy(manager, false); +} + +struct wlr_ext_image_copy_capture_manager_v1 *wlr_ext_image_copy_capture_manager_v1_create( + struct wl_display *display, uint32_t version) { + assert(version <= IMAGE_COPY_CAPTURE_MANAGER_V1_VERSION); + + struct wlr_ext_image_copy_capture_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + manager->global = wl_global_create(display, + &ext_image_copy_capture_manager_v1_interface, version, manager, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + manager->display_destroy.notify = manager_handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + wl_signal_init(&manager->events.new_session); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_ext_workspace_v1.c b/3rdparty/wlroots/types/wlr_ext_workspace_v1.c new file mode 100644 index 0000000000..ed313d846e --- /dev/null +++ b/3rdparty/wlroots/types/wlr_ext_workspace_v1.c @@ -0,0 +1,964 @@ +#include +#include +#include +#include +#include +#include +#include "ext-workspace-v1-protocol.h" +#include "util/global.h" + +#define EXT_WORKSPACE_V1_VERSION 1 + +struct wlr_ext_workspace_v1_group_output { + struct wlr_output *output; + struct wlr_ext_workspace_group_handle_v1 *group; + struct wl_listener output_bind; + struct wl_listener output_destroy; + struct wl_list link; +}; + +// These structs wrap wl_resource of each interface to access the request queue +// (wlr_ext_workspace_manager_v1_resource.requests) assigned per manager resource + +struct wlr_ext_workspace_manager_v1_resource { + struct wl_resource *resource; + struct wlr_ext_workspace_manager_v1 *manager; + struct wl_list requests; // wlr_ext_workspace_v1_request.link + struct wl_list workspace_resources; // wlr_ext_workspace_v1_resource.link + struct wl_list group_resources; // wlr_ext_workspace_group_v1_resource.link + struct wl_list link; // wlr_ext_workspace_manager_v1.resources +}; + +struct wlr_ext_workspace_group_v1_resource { + struct wl_resource *resource; + struct wlr_ext_workspace_group_handle_v1 *group; + struct wlr_ext_workspace_manager_v1_resource *manager; + struct wl_list link; // wlr_ext_workspace_group_v1.resources + struct wl_list manager_resource_link; // wlr_ext_workspace_manager_v1_resource.group_resources +}; + +struct wlr_ext_workspace_v1_resource { + struct wl_resource *resource; + struct wlr_ext_workspace_handle_v1 *workspace; + struct wlr_ext_workspace_manager_v1_resource *manager; + struct wl_list link; // wlr_ext_workspace_v1.resources + struct wl_list manager_resource_link; // wlr_ext_workspace_manager_v1_resource.workspace_resources +}; + +static const struct ext_workspace_group_handle_v1_interface group_impl; + +static struct wlr_ext_workspace_group_v1_resource *group_resource_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_workspace_group_handle_v1_interface, &group_impl)); + return wl_resource_get_user_data(resource); +} + +static const struct ext_workspace_handle_v1_interface workspace_impl; + +static struct wlr_ext_workspace_v1_resource *workspace_resource_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_workspace_handle_v1_interface, &workspace_impl)); + return wl_resource_get_user_data(resource); +} + +static const struct ext_workspace_manager_v1_interface manager_impl; + +static struct wlr_ext_workspace_manager_v1_resource *manager_resource_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_workspace_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void workspace_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void workspace_handle_activate(struct wl_client *client, + struct wl_resource *workspace_resource) { + struct wlr_ext_workspace_v1_resource *workspace_res = + workspace_resource_from_resource(workspace_resource); + if (!workspace_res) { + return; + } + + struct wlr_ext_workspace_v1_request *req = calloc(1, sizeof(*req)); + if (!req) { + wl_resource_post_no_memory(workspace_resource); + return; + } + req->type = WLR_EXT_WORKSPACE_V1_REQUEST_ACTIVATE; + req->activate.workspace = workspace_res->workspace; + wl_list_insert(workspace_res->manager->requests.prev, &req->link); +} + +static void workspace_handle_deactivate(struct wl_client *client, + struct wl_resource *workspace_resource) { + struct wlr_ext_workspace_v1_resource *workspace_res = + workspace_resource_from_resource(workspace_resource); + if (!workspace_res) { + return; + } + + struct wlr_ext_workspace_v1_request *req = calloc(1, sizeof(*req)); + if (!req) { + wl_resource_post_no_memory(workspace_resource); + return; + } + req->type = WLR_EXT_WORKSPACE_V1_REQUEST_DEACTIVATE; + req->deactivate.workspace = workspace_res->workspace; + wl_list_insert(workspace_res->manager->requests.prev, &req->link); +} + +static void workspace_handle_assign(struct wl_client *client, + struct wl_resource *workspace_resource, + struct wl_resource *group_resource) { + struct wlr_ext_workspace_v1_resource *workspace_res = + workspace_resource_from_resource(workspace_resource); + struct wlr_ext_workspace_group_v1_resource *group_res = + group_resource_from_resource(group_resource); + if (!workspace_res || !group_res) { + return; + } + + struct wlr_ext_workspace_v1_request *req = calloc(1, sizeof(*req)); + if (!req) { + wl_resource_post_no_memory(workspace_resource); + return; + } + req->type = WLR_EXT_WORKSPACE_V1_REQUEST_ASSIGN; + req->assign.group = group_res->group; + req->assign.workspace = workspace_res->workspace; + wl_list_insert(workspace_res->manager->requests.prev, &req->link); +} + +static void workspace_handle_remove(struct wl_client *client, + struct wl_resource *workspace_resource) { + struct wlr_ext_workspace_v1_resource *workspace_res = + workspace_resource_from_resource(workspace_resource); + if (!workspace_res) { + return; + } + + struct wlr_ext_workspace_v1_request *req = calloc(1, sizeof(*req)); + if (!req) { + wl_resource_post_no_memory(workspace_resource); + return; + } + req->type = WLR_EXT_WORKSPACE_V1_REQUEST_REMOVE; + req->remove.workspace = workspace_res->workspace; + wl_list_insert(workspace_res->manager->requests.prev, &req->link); +} + +static const struct ext_workspace_handle_v1_interface workspace_impl = { + .destroy = workspace_handle_destroy, + .activate = workspace_handle_activate, + .deactivate = workspace_handle_deactivate, + .assign = workspace_handle_assign, + .remove = workspace_handle_remove, +}; + +static void group_handle_create_workspace(struct wl_client *client, + struct wl_resource *group_resource, const char *name) { + struct wlr_ext_workspace_group_v1_resource *group_res = + group_resource_from_resource(group_resource); + if (!group_res) { + return; + } + + struct wlr_ext_workspace_v1_request *req = calloc(1, sizeof(*req)); + if (!req) { + wl_resource_post_no_memory(group_resource); + return; + } + req->create_workspace.name = strdup(name); + if (!req->create_workspace.name) { + free(req); + wl_resource_post_no_memory(group_resource); + return; + } + req->type = WLR_EXT_WORKSPACE_V1_REQUEST_CREATE_WORKSPACE; + req->create_workspace.group = group_res->group; + wl_list_insert(group_res->manager->requests.prev, &req->link); +} + +static void group_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct ext_workspace_group_handle_v1_interface group_impl = { + .create_workspace = group_handle_create_workspace, + .destroy = group_handle_destroy, +}; + +static void destroy_workspace_resource( + struct wlr_ext_workspace_v1_resource *workspace_res) { + wl_list_remove(&workspace_res->link); + wl_list_remove(&workspace_res->manager_resource_link); + wl_resource_set_user_data(workspace_res->resource, NULL); + free(workspace_res); +} + +static void workspace_resource_destroy(struct wl_resource *resource) { + struct wlr_ext_workspace_v1_resource *workspace_res = + workspace_resource_from_resource(resource); + if (workspace_res) { + destroy_workspace_resource(workspace_res); + } +} + +static struct wlr_ext_workspace_v1_resource *create_workspace_resource( + struct wlr_ext_workspace_handle_v1 *workspace, + struct wlr_ext_workspace_manager_v1_resource *manager_res) { + struct wlr_ext_workspace_v1_resource *workspace_res = + calloc(1, sizeof(*workspace_res)); + if (!workspace_res) { + return NULL; + } + + struct wl_client *client = wl_resource_get_client(manager_res->resource); + workspace_res->resource = wl_resource_create(client, + &ext_workspace_handle_v1_interface, + wl_resource_get_version(manager_res->resource), 0); + if (!workspace_res->resource) { + free(workspace_res); + return NULL; + } + wl_resource_set_implementation(workspace_res->resource, + &workspace_impl, workspace_res, workspace_resource_destroy); + + workspace_res->workspace = workspace; + workspace_res->manager = manager_res; + wl_list_insert(&workspace->resources, &workspace_res->link); + wl_list_insert(&manager_res->workspace_resources, &workspace_res->manager_resource_link); + + return workspace_res; +} + +static void destroy_group_resource(struct wlr_ext_workspace_group_v1_resource *group_res) { + wl_list_remove(&group_res->link); + wl_list_remove(&group_res->manager_resource_link); + wl_resource_set_user_data(group_res->resource, NULL); + free(group_res); +} + +static void group_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_ext_workspace_group_v1_resource *group_res = + group_resource_from_resource(resource); + if (group_res) { + destroy_group_resource(group_res); + } +} + +static struct wlr_ext_workspace_group_v1_resource *create_group_resource( + struct wlr_ext_workspace_group_handle_v1 *group, + struct wlr_ext_workspace_manager_v1_resource *manager_res) { + struct wlr_ext_workspace_group_v1_resource *group_res = + calloc(1, sizeof(*group_res)); + if (!group_res) { + return NULL; + } + + struct wl_client *client = wl_resource_get_client(manager_res->resource); + uint32_t version = wl_resource_get_version(manager_res->resource); + group_res->resource = wl_resource_create(client, + &ext_workspace_group_handle_v1_interface, version, 0); + if (group_res->resource == NULL) { + free(group_res); + return NULL; + } + wl_resource_set_implementation(group_res->resource, &group_impl, + group_res, group_handle_resource_destroy); + + group_res->group = group; + group_res->manager = manager_res; + wl_list_insert(&group->resources, &group_res->link); + wl_list_insert(&manager_res->group_resources, &group_res->manager_resource_link); + + return group_res; +} + +static void destroy_requests(struct wlr_ext_workspace_manager_v1_resource *manager_res) { + struct wlr_ext_workspace_v1_request *req, *tmp; + wl_list_for_each_safe(req, tmp, &manager_res->requests, link) { + if (req->type == WLR_EXT_WORKSPACE_V1_REQUEST_CREATE_WORKSPACE) { + free(req->create_workspace.name); + } + wl_list_remove(&req->link); + free(req); + } +} + +static void clear_requests_by(struct wlr_ext_workspace_manager_v1_resource *manager_res, + struct wlr_ext_workspace_group_handle_v1 *group, + struct wlr_ext_workspace_handle_v1 *workspace) { + struct wlr_ext_workspace_v1_request *req, *tmp; + wl_list_for_each_safe(req, tmp, &manager_res->requests, link) { + switch (req->type) { + case WLR_EXT_WORKSPACE_V1_REQUEST_CREATE_WORKSPACE: + if (group && req->create_workspace.group == group) { + req->create_workspace.group = NULL; + } + break; + case WLR_EXT_WORKSPACE_V1_REQUEST_ACTIVATE: + if (workspace && req->activate.workspace == workspace) { + req->activate.workspace = NULL; + } + break; + case WLR_EXT_WORKSPACE_V1_REQUEST_DEACTIVATE: + if (workspace && req->deactivate.workspace == workspace) { + req->deactivate.workspace = NULL; + } + break; + case WLR_EXT_WORKSPACE_V1_REQUEST_ASSIGN: + if (workspace && req->assign.workspace == workspace) { + req->assign.workspace = NULL; + } + if (group && req->assign.group == group) { + req->assign.group = NULL; + } + break; + case WLR_EXT_WORKSPACE_V1_REQUEST_REMOVE: + if (workspace && req->remove.workspace == workspace) { + req->remove.workspace = NULL; + } + break; + } + } +} + +static void manager_handle_commit(struct wl_client *client, struct wl_resource *resource) { + struct wlr_ext_workspace_manager_v1_resource *manager_res = + manager_resource_from_resource(resource); + if (!manager_res) { + return; + } + + struct wlr_ext_workspace_v1_commit_event commit_event = { + .requests = &manager_res->requests, + }; + wl_signal_emit_mutable(&manager_res->manager->events.commit, &commit_event); + destroy_requests(manager_res); +} + +static void handle_idle(void *data) { + struct wlr_ext_workspace_manager_v1 *manager = data; + + struct wlr_ext_workspace_manager_v1_resource *manager_res; + wl_list_for_each(manager_res, &manager->resources, link) { + ext_workspace_manager_v1_send_done(manager_res->resource); + } + manager->idle_source = NULL; +} + +static void manager_schedule_done(struct wlr_ext_workspace_manager_v1 *manager) { + if (!manager->idle_source) { + manager->idle_source = wl_event_loop_add_idle(manager->event_loop, + handle_idle, manager); + } +} + +static void workspace_send_details(struct wlr_ext_workspace_v1_resource *workspace_res) { + struct wlr_ext_workspace_handle_v1 *workspace = workspace_res->workspace; + struct wl_resource *resource = workspace_res->resource; + + ext_workspace_handle_v1_send_capabilities(resource, workspace->caps); + if (workspace->coordinates.size > 0) { + ext_workspace_handle_v1_send_coordinates(resource, &workspace->coordinates); + } + if (workspace->name) { + ext_workspace_handle_v1_send_name(resource, workspace->name); + } + if (workspace->id) { + ext_workspace_handle_v1_send_id(resource, workspace->id); + } + ext_workspace_handle_v1_send_state(resource, workspace->state); + manager_schedule_done(workspace->manager); +} + +static void manager_handle_stop(struct wl_client *client, struct wl_resource *resource) { + ext_workspace_manager_v1_send_finished(resource); + wl_resource_destroy(resource); +} + +static const struct ext_workspace_manager_v1_interface manager_impl = { + .commit = manager_handle_commit, + .stop = manager_handle_stop, +}; + +static void destroy_manager_resource(struct wlr_ext_workspace_manager_v1_resource *manager_res) { + destroy_requests(manager_res); + + struct wlr_ext_workspace_v1_resource *workspace_res, *tmp2; + wl_list_for_each_safe(workspace_res, tmp2, + &manager_res->workspace_resources, manager_resource_link) { + destroy_workspace_resource(workspace_res); + } + struct wlr_ext_workspace_group_v1_resource *group_res, *tmp3; + wl_list_for_each_safe(group_res, tmp3, + &manager_res->group_resources, manager_resource_link) { + destroy_group_resource(group_res); + } + + wl_list_remove(&manager_res->link); + wl_resource_set_user_data(manager_res->resource, NULL); + free(manager_res); +} + +static void manager_resource_destroy(struct wl_resource *resource) { + struct wlr_ext_workspace_manager_v1_resource *manager_res = + manager_resource_from_resource(resource); + if (manager_res) { + destroy_manager_resource(manager_res); + } +} + +static void group_send_details(struct wlr_ext_workspace_group_v1_resource *group_res) { + struct wlr_ext_workspace_group_handle_v1 *group = group_res->group; + struct wl_resource *resource = group_res->resource; + struct wl_client *client = wl_resource_get_client(resource); + + ext_workspace_group_handle_v1_send_capabilities(resource, group->caps); + + struct wlr_ext_workspace_v1_group_output *group_output; + wl_list_for_each(group_output, &group->outputs, link) { + struct wl_resource *output_resource; + wl_resource_for_each(output_resource, &group_output->output->resources) { + if (wl_resource_get_client(output_resource) == client) { + ext_workspace_group_handle_v1_send_output_enter( + resource, output_resource); + } + } + } + + manager_schedule_done(group->manager); +} + +static void manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_ext_workspace_manager_v1 *manager = data; + + struct wlr_ext_workspace_manager_v1_resource *manager_res = + calloc(1, sizeof(*manager_res)); + if (!manager_res) { + wl_client_post_no_memory(client); + return; + } + + manager_res->manager = manager; + wl_list_init(&manager_res->requests); + wl_list_init(&manager_res->workspace_resources); + wl_list_init(&manager_res->group_resources); + + manager_res->resource = wl_resource_create(client, + &ext_workspace_manager_v1_interface, version, id); + if (!manager_res->resource) { + free(manager_res); + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(manager_res->resource, &manager_impl, + manager_res, manager_resource_destroy); + wl_list_init(&manager_res->link); + if (manager == NULL) { + return; + } + + wl_list_insert(&manager->resources, &manager_res->link); + + struct wlr_ext_workspace_group_handle_v1 *group; + wl_list_for_each(group, &manager->groups, link) { + struct wlr_ext_workspace_group_v1_resource *group_res = + create_group_resource(group, manager_res); + if (!group_res) { + wl_resource_post_no_memory(manager_res->resource); + continue; + } + ext_workspace_manager_v1_send_workspace_group( + manager_res->resource, group_res->resource); + group_send_details(group_res); + } + + struct wlr_ext_workspace_handle_v1 *workspace; + wl_list_for_each(workspace, &manager->workspaces, link) { + struct wlr_ext_workspace_v1_resource *workspace_res = + create_workspace_resource(workspace, manager_res); + if (!workspace_res) { + wl_resource_post_no_memory(manager_res->resource); + continue; + } + ext_workspace_manager_v1_send_workspace( + manager_res->resource, workspace_res->resource); + workspace_send_details(workspace_res); + + if (!workspace->group) { + continue; + } + struct wlr_ext_workspace_group_v1_resource *group_res; + wl_list_for_each(group_res, &workspace->group->resources, link) { + if (group_res->manager == manager_res) { + ext_workspace_group_handle_v1_send_workspace_enter( + group_res->resource, workspace_res->resource); + } + } + } + + ext_workspace_manager_v1_send_done(manager_res->resource); +} + +static void ext_workspace_manager_v1_destroy(struct wlr_ext_workspace_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, NULL); + assert(wl_list_empty(&manager->events.commit.listener_list)); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + struct wlr_ext_workspace_group_handle_v1 *group, *tmp; + wl_list_for_each_safe(group, tmp, &manager->groups, link) { + wlr_ext_workspace_group_handle_v1_destroy(group); + } + + struct wlr_ext_workspace_handle_v1 *workspace, *tmp2; + wl_list_for_each_safe(workspace, tmp2, &manager->workspaces, link) { + wlr_ext_workspace_handle_v1_destroy(workspace); + } + + struct wlr_ext_workspace_manager_v1_resource *manager_res, *tmp3; + wl_list_for_each_safe(manager_res, tmp3, &manager->resources, link) { + destroy_manager_resource(manager_res); + } + + if (manager->idle_source) { + wl_event_source_remove(manager->idle_source); + } + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_ext_workspace_manager_v1_destroy(struct wlr_ext_workspace_manager_v1 *manager, + bool destroy_global_safe) { + ext_workspace_manager_v1_destroy(manager, destroy_global_safe); +} + +static void manager_handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_ext_workspace_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + ext_workspace_manager_v1_destroy(manager, false); +} + +struct wlr_ext_workspace_manager_v1 *wlr_ext_workspace_manager_v1_create( + struct wl_display *display, uint32_t version) { + assert(version <= EXT_WORKSPACE_V1_VERSION); + + struct wlr_ext_workspace_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (!manager) { + return NULL; + } + + manager->global = wl_global_create(display, + &ext_workspace_manager_v1_interface, + version, manager, manager_bind); + if (!manager->global) { + free(manager); + return NULL; + } + + manager->event_loop = wl_display_get_event_loop(display); + + manager->display_destroy.notify = manager_handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + wl_list_init(&manager->groups); + wl_list_init(&manager->workspaces); + wl_list_init(&manager->resources); + wl_signal_init(&manager->events.commit); + wl_signal_init(&manager->events.destroy); + + return manager; +} + +struct wlr_ext_workspace_group_handle_v1 *wlr_ext_workspace_group_handle_v1_create( + struct wlr_ext_workspace_manager_v1 *manager, uint32_t caps) { + struct wlr_ext_workspace_group_handle_v1 *group = calloc(1, sizeof(*group)); + if (!group) { + return NULL; + } + + group->manager = manager; + group->caps = caps; + + wl_list_init(&group->outputs); + wl_list_init(&group->resources); + wl_signal_init(&group->events.destroy); + + wl_list_insert(manager->groups.prev, &group->link); + + struct wlr_ext_workspace_manager_v1_resource *manager_res; + wl_list_for_each(manager_res, &manager->resources, link) { + struct wlr_ext_workspace_group_v1_resource *group_res = + create_group_resource(group, manager_res); + if (!group_res) { + continue; + } + ext_workspace_manager_v1_send_workspace_group( + manager_res->resource, group_res->resource); + group_send_details(group_res); + } + + manager_schedule_done(manager); + + return group; +} + +static void workspace_send_group(struct wlr_ext_workspace_handle_v1 *workspace, + struct wlr_ext_workspace_group_handle_v1 *group, bool enter) { + + struct wlr_ext_workspace_v1_resource *workspace_res; + wl_list_for_each(workspace_res, &workspace->resources, link) { + struct wlr_ext_workspace_group_v1_resource *group_res; + wl_list_for_each(group_res, &group->resources, link) { + if (group_res->manager != workspace_res->manager) { + continue; + } + if (enter) { + ext_workspace_group_handle_v1_send_workspace_enter( + group_res->resource, workspace_res->resource); + } else { + ext_workspace_group_handle_v1_send_workspace_leave( + group_res->resource, workspace_res->resource); + } + } + } + + manager_schedule_done(workspace->manager); +} + +static void destroy_group_output(struct wlr_ext_workspace_v1_group_output *group_output) { + wl_list_remove(&group_output->output_bind.link); + wl_list_remove(&group_output->output_destroy.link); + wl_list_remove(&group_output->link); + free(group_output); +} + +static void group_send_output(struct wlr_ext_workspace_group_handle_v1 *group, + struct wlr_output *output, bool enter) { + + struct wlr_ext_workspace_group_v1_resource *group_res; + wl_list_for_each(group_res, &group->resources, link) { + struct wl_client *client = + wl_resource_get_client(group_res->resource); + + struct wl_resource *output_resource; + wl_resource_for_each(output_resource, &output->resources) { + if (wl_resource_get_client(output_resource) != client) { + continue; + } + if (enter) { + ext_workspace_group_handle_v1_send_output_enter( + group_res->resource, output_resource); + } else { + ext_workspace_group_handle_v1_send_output_leave( + group_res->resource, output_resource); + } + } + } + + manager_schedule_done(group->manager); +} + +void wlr_ext_workspace_group_handle_v1_destroy( + struct wlr_ext_workspace_group_handle_v1 *group) { + if (!group) { + return; + } + + wl_signal_emit_mutable(&group->events.destroy, NULL); + + assert(wl_list_empty(&group->events.destroy.listener_list)); + + struct wlr_ext_workspace_handle_v1 *workspace; + wl_list_for_each(workspace, &group->manager->workspaces, link) { + if (workspace->group == group) { + workspace_send_group(workspace, group, false); + workspace->group = NULL; + } + } + + struct wlr_ext_workspace_group_v1_resource *group_res, *tmp; + wl_list_for_each_safe(group_res, tmp, &group->resources, link) { + ext_workspace_group_handle_v1_send_removed(group_res->resource); + destroy_group_resource(group_res); + } + + struct wlr_ext_workspace_manager_v1_resource *manager_res; + wl_list_for_each(manager_res, &group->manager->resources, link) { + clear_requests_by(manager_res, group, NULL); + } + + struct wlr_ext_workspace_v1_group_output *group_output, *tmp3; + wl_list_for_each_safe(group_output, tmp3, &group->outputs, link) { + group_send_output(group, group_output->output, false); + destroy_group_output(group_output); + } + + manager_schedule_done(group->manager); + + wl_list_remove(&group->link); + free(group); +} + +static void handle_output_bind(struct wl_listener *listener, void *data) { + struct wlr_ext_workspace_v1_group_output *group_output = + wl_container_of(listener, group_output, output_bind); + struct wlr_output_event_bind *event = data; + struct wl_client *client = wl_resource_get_client(event->resource); + + struct wlr_ext_workspace_group_v1_resource *group_res; + wl_list_for_each(group_res, &group_output->group->resources, link) { + if (wl_resource_get_client(group_res->resource) == client) { + ext_workspace_group_handle_v1_send_output_enter( + group_res->resource, event->resource); + } + } + + manager_schedule_done(group_output->group->manager); +} + +static void handle_output_destroy(struct wl_listener *listener, void *data) { + struct wlr_ext_workspace_v1_group_output *group_output = + wl_container_of(listener, group_output, output_destroy); + group_send_output(group_output->group, group_output->output, false); + destroy_group_output(group_output); +} + +static struct wlr_ext_workspace_v1_group_output *get_group_output( + struct wlr_ext_workspace_group_handle_v1 *group, + struct wlr_output *output) { + struct wlr_ext_workspace_v1_group_output *group_output; + wl_list_for_each(group_output, &group->outputs, link) { + if (group_output->output == output) { + return group_output; + } + } + return NULL; +} + +void wlr_ext_workspace_group_handle_v1_output_enter( + struct wlr_ext_workspace_group_handle_v1 *group, + struct wlr_output *output) { + if (get_group_output(group, output)) { + return; + } + struct wlr_ext_workspace_v1_group_output *group_output = + calloc(1, sizeof(*group_output)); + if (!group_output) { + return; + } + group_output->output = output; + group_output->group = group; + wl_list_insert(&group->outputs, &group_output->link); + + group_output->output_bind.notify = handle_output_bind; + wl_signal_add(&output->events.bind, &group_output->output_bind); + group_output->output_destroy.notify = handle_output_destroy; + wl_signal_add(&output->events.destroy, &group_output->output_destroy); + + group_send_output(group, output, true); +} + +void wlr_ext_workspace_group_handle_v1_output_leave( + struct wlr_ext_workspace_group_handle_v1 *group, + struct wlr_output *output) { + struct wlr_ext_workspace_v1_group_output *group_output = + get_group_output(group, output); + if (!group_output) { + return; + } + + group_send_output(group, output, false); + destroy_group_output(group_output); +} + +struct wlr_ext_workspace_handle_v1 *wlr_ext_workspace_handle_v1_create( + struct wlr_ext_workspace_manager_v1 *manager, const char *id, uint32_t caps) { + struct wlr_ext_workspace_handle_v1 *workspace = calloc(1, sizeof(*workspace)); + if (!workspace) { + return NULL; + } + + workspace->manager = manager; + workspace->caps = caps; + + if (id) { + workspace->id = strdup(id); + if (!workspace->id) { + free(workspace); + return NULL; + } + } + + wl_list_init(&workspace->resources); + wl_array_init(&workspace->coordinates); + wl_signal_init(&workspace->events.destroy); + + wl_list_insert(manager->workspaces.prev, &workspace->link); + + struct wlr_ext_workspace_manager_v1_resource *manager_res; + wl_list_for_each(manager_res, &manager->resources, link) { + struct wlr_ext_workspace_v1_resource *workspace_res = + create_workspace_resource(workspace, manager_res); + if (!workspace_res) { + continue; + } + ext_workspace_manager_v1_send_workspace( + manager_res->resource, workspace_res->resource); + workspace_send_details(workspace_res); + } + + manager_schedule_done(manager); + + return workspace; +} + +void wlr_ext_workspace_handle_v1_destroy(struct wlr_ext_workspace_handle_v1 *workspace) { + if (!workspace) { + return; + } + + wl_signal_emit_mutable(&workspace->events.destroy, NULL); + + assert(wl_list_empty(&workspace->events.destroy.listener_list)); + + if (workspace->group) { + workspace_send_group(workspace, workspace->group, false); + } + + struct wlr_ext_workspace_v1_resource *workspace_res, *tmp; + wl_list_for_each_safe(workspace_res, tmp, &workspace->resources, link) { + ext_workspace_handle_v1_send_removed(workspace_res->resource); + destroy_workspace_resource(workspace_res); + } + + struct wlr_ext_workspace_manager_v1_resource *manager_res; + wl_list_for_each(manager_res, &workspace->manager->resources, link) { + clear_requests_by(manager_res, NULL, workspace); + } + + manager_schedule_done(workspace->manager); + + wl_list_remove(&workspace->link); + wl_array_release(&workspace->coordinates); + free(workspace->id); + free(workspace->name); + free(workspace); +} + +void wlr_ext_workspace_handle_v1_set_group( + struct wlr_ext_workspace_handle_v1 *workspace, + struct wlr_ext_workspace_group_handle_v1 *group) { + if (workspace->group == group) { + return; + } + + if (workspace->group) { + workspace_send_group(workspace, workspace->group, false); + } + workspace->group = group; + if (group) { + workspace_send_group(workspace, group, true); + } +} + +void wlr_ext_workspace_handle_v1_set_name( + struct wlr_ext_workspace_handle_v1 *workspace, const char *name) { + assert(name); + + if (workspace->name && strcmp(workspace->name, name) == 0) { + return; + } + + free(workspace->name); + workspace->name = strdup(name); + if (workspace->name == NULL) { + return; + } + + struct wlr_ext_workspace_v1_resource *workspace_res; + wl_list_for_each(workspace_res, &workspace->resources, link) { + ext_workspace_handle_v1_send_name( + workspace_res->resource, workspace->name); + } + + manager_schedule_done(workspace->manager); +} + +void wlr_ext_workspace_handle_v1_set_coordinates( + struct wlr_ext_workspace_handle_v1 *workspace, + const uint32_t *coords, size_t coords_len) { + size_t size = coords_len * sizeof(coords[0]); + if (size == workspace->coordinates.size && (size == 0 || + memcmp(workspace->coordinates.data, coords, size) == 0)) { + return; + } + + wl_array_release(&workspace->coordinates); + wl_array_init(&workspace->coordinates); + struct wl_array arr = { + .data = (void *)coords, + .size = size, + }; + wl_array_copy(&workspace->coordinates, &arr); + + struct wlr_ext_workspace_v1_resource *workspace_res; + wl_list_for_each(workspace_res, &workspace->resources, link) { + ext_workspace_handle_v1_send_coordinates( + workspace_res->resource, &workspace->coordinates); + } + + manager_schedule_done(workspace->manager); +} + +static void workspace_set_state(struct wlr_ext_workspace_handle_v1 *workspace, + enum ext_workspace_handle_v1_state state, bool enabled) { + uint32_t old_state = workspace->state; + if (enabled) { + workspace->state |= state; + } else { + workspace->state &= ~state; + } + if (old_state == workspace->state) { + return; + } + + struct wlr_ext_workspace_v1_resource *workspace_res; + wl_list_for_each(workspace_res, &workspace->resources, link) { + ext_workspace_handle_v1_send_state( + workspace_res->resource, workspace->state); + } + + manager_schedule_done(workspace->manager); +} + +void wlr_ext_workspace_handle_v1_set_active( + struct wlr_ext_workspace_handle_v1 *workspace, bool enabled) { + workspace_set_state(workspace, EXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE, enabled); +} + +void wlr_ext_workspace_handle_v1_set_urgent( + struct wlr_ext_workspace_handle_v1 *workspace, bool enabled) { + workspace_set_state(workspace, EXT_WORKSPACE_HANDLE_V1_STATE_URGENT, enabled); +} + +void wlr_ext_workspace_handle_v1_set_hidden( + struct wlr_ext_workspace_handle_v1 *workspace, bool enabled) { + workspace_set_state(workspace, EXT_WORKSPACE_HANDLE_V1_STATE_HIDDEN, enabled); +} diff --git a/3rdparty/wlroots/types/wlr_fixes.c b/3rdparty/wlroots/types/wlr_fixes.c new file mode 100644 index 0000000000..3d471f9d8f --- /dev/null +++ b/3rdparty/wlroots/types/wlr_fixes.c @@ -0,0 +1,80 @@ +#include +#include +#include +#include + +#include +#include "util/global.h" + +#define FIXES_VERSION 1 + +static void fixes_destroy(struct wl_client *client, struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void fixes_destroy_registry(struct wl_client *client, struct wl_resource *resource, + struct wl_resource *registry) { + wl_resource_destroy(registry); +} + +static const struct wl_fixes_interface fixes_impl = { + .destroy = fixes_destroy, + .destroy_registry = fixes_destroy_registry, +}; + +static void fixes_bind(struct wl_client *wl_client, void *data, uint32_t version, uint32_t id) { + struct wlr_fixes *fixes = data; + + struct wl_resource *resource = wl_resource_create(wl_client, &wl_fixes_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + wl_resource_set_implementation(resource, &fixes_impl, fixes, NULL); +} + +static void fixes_destroy_internal(struct wlr_fixes *fixes, + bool destroy_global_safe) { + wl_signal_emit_mutable(&fixes->events.destroy, NULL); + + assert(wl_list_empty(&fixes->events.destroy.listener_list)); + + wl_list_remove(&fixes->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(fixes->global); + } else { + wl_global_destroy(fixes->global); + } + free(fixes); +} + +void wlr_fixes_destroy(struct wlr_fixes *fixes, bool destroy_global_safe) { + fixes_destroy_internal(fixes, destroy_global_safe); +} + +static void fixes_handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_fixes *fixes = wl_container_of(listener, fixes, display_destroy); + fixes_destroy_internal(fixes, false); +} + +struct wlr_fixes *wlr_fixes_create(struct wl_display *display, uint32_t version) { + assert(version <= FIXES_VERSION); + + struct wlr_fixes *fixes = calloc(1, sizeof(*fixes)); + if (fixes == NULL) { + return NULL; + } + + fixes->global = wl_global_create(display, &wl_fixes_interface, version, fixes, fixes_bind); + if (fixes->global == NULL) { + free(fixes); + return NULL; + } + + wl_signal_init(&fixes->events.destroy); + + fixes->display_destroy.notify = fixes_handle_display_destroy; + wl_display_add_destroy_listener(display, &fixes->display_destroy); + + return fixes; +} diff --git a/3rdparty/wlroots/types/wlr_foreign_toplevel_management_v1.c b/3rdparty/wlroots/types/wlr_foreign_toplevel_management_v1.c new file mode 100644 index 0000000000..90d7988b7a --- /dev/null +++ b/3rdparty/wlroots/types/wlr_foreign_toplevel_management_v1.c @@ -0,0 +1,697 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "wlr-foreign-toplevel-management-unstable-v1-protocol.h" +#include "util/global.h" + +#define FOREIGN_TOPLEVEL_MANAGEMENT_V1_VERSION 3 + +#define FOREIGN_TOPLEVEL_HANDLE_V1_STATE_COUNT 32 + +static const struct zwlr_foreign_toplevel_handle_v1_interface toplevel_handle_impl; + +static struct wlr_foreign_toplevel_handle_v1 *toplevel_handle_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_foreign_toplevel_handle_v1_interface, + &toplevel_handle_impl)); + return wl_resource_get_user_data(resource); +} + +static void toplevel_handle_send_maximized_event(struct wl_resource *resource, + bool state) { + struct wlr_foreign_toplevel_handle_v1 *toplevel = + toplevel_handle_from_resource(resource); + if (!toplevel) { + return; + } + struct wlr_foreign_toplevel_handle_v1_maximized_event event = { + .toplevel = toplevel, + .maximized = state, + }; + wl_signal_emit_mutable(&toplevel->events.request_maximize, &event); +} + +static void foreign_toplevel_handle_set_maximized(struct wl_client *client, + struct wl_resource *resource) { + toplevel_handle_send_maximized_event(resource, true); +} + +static void foreign_toplevel_handle_unset_maximized(struct wl_client *client, + struct wl_resource *resource) { + toplevel_handle_send_maximized_event(resource, false); +} + +static void toplevel_send_minimized_event(struct wl_resource *resource, + bool state) { + struct wlr_foreign_toplevel_handle_v1 *toplevel = + toplevel_handle_from_resource(resource); + if (!toplevel) { + return; + } + + struct wlr_foreign_toplevel_handle_v1_minimized_event event = { + .toplevel = toplevel, + .minimized = state, + }; + wl_signal_emit_mutable(&toplevel->events.request_minimize, &event); +} + +static void foreign_toplevel_handle_set_minimized(struct wl_client *client, + struct wl_resource *resource) { + toplevel_send_minimized_event(resource, true); +} + +static void foreign_toplevel_handle_unset_minimized(struct wl_client *client, + struct wl_resource *resource) { + toplevel_send_minimized_event(resource, false); +} + +static void toplevel_send_fullscreen_event(struct wl_resource *resource, + bool state, struct wl_resource *output_resource) { + struct wlr_foreign_toplevel_handle_v1 *toplevel = + toplevel_handle_from_resource(resource); + if (!toplevel) { + return; + } + + struct wlr_output *output = NULL; + if (output_resource) { + output = wlr_output_from_resource(output_resource); + } + struct wlr_foreign_toplevel_handle_v1_fullscreen_event event = { + .toplevel = toplevel, + .fullscreen = state, + .output = output, + }; + wl_signal_emit_mutable(&toplevel->events.request_fullscreen, &event); +} + +static void foreign_toplevel_handle_set_fullscreen(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *output) { + toplevel_send_fullscreen_event(resource, true, output); +} + +static void foreign_toplevel_handle_unset_fullscreen(struct wl_client *client, + struct wl_resource *resource) { + toplevel_send_fullscreen_event(resource, false, NULL); +} + +static void foreign_toplevel_handle_activate(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *seat) { + struct wlr_foreign_toplevel_handle_v1 *toplevel = + toplevel_handle_from_resource(resource); + if (!toplevel) { + return; + } + struct wlr_seat_client *seat_client = wlr_seat_client_from_resource(seat); + if (!seat_client) { + return; + } + + struct wlr_foreign_toplevel_handle_v1_activated_event event = { + .toplevel = toplevel, + .seat = seat_client->seat, + }; + wl_signal_emit_mutable(&toplevel->events.request_activate, &event); +} + +static void foreign_toplevel_handle_close(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_foreign_toplevel_handle_v1 *toplevel = + toplevel_handle_from_resource(resource); + if (!toplevel) { + return; + } + wl_signal_emit_mutable(&toplevel->events.request_close, toplevel); +} + +static void foreign_toplevel_handle_set_rectangle(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *surface, + int32_t x, int32_t y, int32_t width, int32_t height) { + struct wlr_foreign_toplevel_handle_v1 *toplevel = + toplevel_handle_from_resource(resource); + if (!toplevel) { + return; + } + + if (width < 0 || height < 0) { + wl_resource_post_error(resource, + ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_ERROR_INVALID_RECTANGLE, + "invalid rectangle passed to set_rectangle: width/height < 0"); + return; + } + + struct wlr_foreign_toplevel_handle_v1_set_rectangle_event event = { + .toplevel = toplevel, + .surface = wlr_surface_from_resource(surface), + .x = x, + .y = y, + .width = width, + .height = height, + }; + wl_signal_emit_mutable(&toplevel->events.set_rectangle, &event); +} + +static void foreign_toplevel_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwlr_foreign_toplevel_handle_v1_interface toplevel_handle_impl = { + .set_maximized = foreign_toplevel_handle_set_maximized, + .unset_maximized = foreign_toplevel_handle_unset_maximized, + .set_minimized = foreign_toplevel_handle_set_minimized, + .unset_minimized = foreign_toplevel_handle_unset_minimized, + .activate = foreign_toplevel_handle_activate, + .close = foreign_toplevel_handle_close, + .set_rectangle = foreign_toplevel_handle_set_rectangle, + .destroy = foreign_toplevel_handle_destroy, + .set_fullscreen = foreign_toplevel_handle_set_fullscreen, + .unset_fullscreen = foreign_toplevel_handle_unset_fullscreen, +}; + +static void toplevel_idle_send_done(void *data) { + struct wlr_foreign_toplevel_handle_v1 *toplevel = data; + struct wl_resource *resource; + wl_resource_for_each(resource, &toplevel->resources) { + zwlr_foreign_toplevel_handle_v1_send_done(resource); + } + + toplevel->idle_source = NULL; +} + +static void toplevel_update_idle_source( + struct wlr_foreign_toplevel_handle_v1 *toplevel) { + if (toplevel->idle_source) { + return; + } + + toplevel->idle_source = wl_event_loop_add_idle(toplevel->manager->event_loop, + toplevel_idle_send_done, toplevel); +} + +void wlr_foreign_toplevel_handle_v1_set_title( + struct wlr_foreign_toplevel_handle_v1 *toplevel, const char *title) { + free(toplevel->title); + toplevel->title = strdup(title); + if (toplevel->title == NULL) { + wlr_log(WLR_ERROR, "failed to allocate memory for toplevel title"); + return; + } + + struct wl_resource *resource; + wl_resource_for_each(resource, &toplevel->resources) { + zwlr_foreign_toplevel_handle_v1_send_title(resource, title); + } + + toplevel_update_idle_source(toplevel); +} + +void wlr_foreign_toplevel_handle_v1_set_app_id( + struct wlr_foreign_toplevel_handle_v1 *toplevel, const char *app_id) { + free(toplevel->app_id); + toplevel->app_id = strdup(app_id); + if (toplevel->app_id == NULL) { + wlr_log(WLR_ERROR, "failed to allocate memory for toplevel app_id"); + return; + } + + struct wl_resource *resource; + wl_resource_for_each(resource, &toplevel->resources) { + zwlr_foreign_toplevel_handle_v1_send_app_id(resource, app_id); + } + + toplevel_update_idle_source(toplevel); +} + +static void send_output_to_resource(struct wl_resource *resource, + struct wlr_output *output, bool enter) { + struct wl_client *client = wl_resource_get_client(resource); + struct wl_resource *output_resource; + + wl_resource_for_each(output_resource, &output->resources) { + if (wl_resource_get_client(output_resource) == client) { + if (enter) { + zwlr_foreign_toplevel_handle_v1_send_output_enter(resource, + output_resource); + } else { + zwlr_foreign_toplevel_handle_v1_send_output_leave(resource, + output_resource); + } + } + } +} + +static void toplevel_send_output(struct wlr_foreign_toplevel_handle_v1 *toplevel, + struct wlr_output *output, bool enter) { + struct wl_resource *resource; + wl_resource_for_each(resource, &toplevel->resources) { + send_output_to_resource(resource, output, enter); + } + + toplevel_update_idle_source(toplevel); +} + +static void toplevel_handle_output_bind(struct wl_listener *listener, + void *data) { + struct wlr_foreign_toplevel_handle_v1_output *toplevel_output = + wl_container_of(listener, toplevel_output, output_bind); + struct wlr_output_event_bind *event = data; + struct wl_client *client = wl_resource_get_client(event->resource); + + struct wl_resource *resource; + wl_resource_for_each(resource, &toplevel_output->toplevel->resources) { + if (wl_resource_get_client(resource) == client) { + send_output_to_resource(resource, toplevel_output->output, true); + } + } + + toplevel_update_idle_source(toplevel_output->toplevel); +} + +static void toplevel_output_destroy( + struct wlr_foreign_toplevel_handle_v1_output *toplevel_output) { + wl_list_remove(&toplevel_output->link); + wl_list_remove(&toplevel_output->output_bind.link); + wl_list_remove(&toplevel_output->output_destroy.link); + free(toplevel_output); +} + +static void toplevel_output_leave( + struct wlr_foreign_toplevel_handle_v1_output *toplevel_output) { + struct wlr_foreign_toplevel_handle_v1 *toplevel = toplevel_output->toplevel; + struct wlr_output *output = toplevel_output->output; + toplevel_send_output(toplevel, output, false); + toplevel_output_destroy(toplevel_output); +} + +static void toplevel_handle_output_destroy(struct wl_listener *listener, + void *data) { + struct wlr_foreign_toplevel_handle_v1_output *toplevel_output = + wl_container_of(listener, toplevel_output, output_destroy); + toplevel_output_leave(toplevel_output); +} + +void wlr_foreign_toplevel_handle_v1_output_enter( + struct wlr_foreign_toplevel_handle_v1 *toplevel, + struct wlr_output *output) { + struct wlr_foreign_toplevel_handle_v1_output *toplevel_output; + wl_list_for_each(toplevel_output, &toplevel->outputs, link) { + if (toplevel_output->output == output) { + return; // we have already sent output_enter event + } + } + + toplevel_output = calloc(1, sizeof(*toplevel_output)); + if (!toplevel_output) { + wlr_log(WLR_ERROR, "failed to allocate memory for toplevel output"); + return; + } + + toplevel_output->output = output; + toplevel_output->toplevel = toplevel; + wl_list_insert(&toplevel->outputs, &toplevel_output->link); + + toplevel_output->output_bind.notify = toplevel_handle_output_bind; + wl_signal_add(&output->events.bind, &toplevel_output->output_bind); + + toplevel_output->output_destroy.notify = toplevel_handle_output_destroy; + wl_signal_add(&output->events.destroy, &toplevel_output->output_destroy); + + toplevel_send_output(toplevel, output, true); +} + +void wlr_foreign_toplevel_handle_v1_output_leave( + struct wlr_foreign_toplevel_handle_v1 *toplevel, + struct wlr_output *output) { + struct wlr_foreign_toplevel_handle_v1_output *toplevel_output_iterator; + wl_list_for_each(toplevel_output_iterator, &toplevel->outputs, link) { + if (toplevel_output_iterator->output == output) { + toplevel_output_leave(toplevel_output_iterator); + return; + } + } + + // XXX: log an error? crash? +} + +static void fill_array_from_toplevel_state(struct wl_array *states, + uint32_t data[], uint32_t state, uint32_t version) { + size_t nstates = 0; + if (state & WLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MAXIMIZED) { + data[nstates++] = ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MAXIMIZED; + } + if (state & WLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MINIMIZED) { + data[nstates++] = ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MINIMIZED; + } + if (state & WLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_ACTIVATED) { + data[nstates++] = ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_ACTIVATED; + } + if (version >= ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN_SINCE_VERSION + && (state & WLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN)) { + data[nstates++] = ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN; + } + assert(nstates <= FOREIGN_TOPLEVEL_HANDLE_V1_STATE_COUNT); + + *states = (struct wl_array){ + .data = data, + .size = nstates * sizeof(data[0]) + }; +} + +static void toplevel_send_state(struct wlr_foreign_toplevel_handle_v1 *toplevel) { + struct wl_array state_array; + uint32_t states[FOREIGN_TOPLEVEL_HANDLE_V1_STATE_COUNT]; + + struct wl_resource *resource; + wl_resource_for_each(resource, &toplevel->resources) { + fill_array_from_toplevel_state(&state_array, states, + toplevel->state, wl_resource_get_version(resource)); + zwlr_foreign_toplevel_handle_v1_send_state(resource, &state_array); + } + toplevel_update_idle_source(toplevel); +} + +static void set_state(struct wlr_foreign_toplevel_handle_v1 *toplevel, + bool new_state_val, enum wlr_foreign_toplevel_handle_v1_state state) { + if (new_state_val == !!(toplevel->state & state)) { + return; + } + if (new_state_val) { + toplevel->state |= state; + } else { + toplevel->state &= ~state; + } + toplevel_send_state(toplevel); +} + +void wlr_foreign_toplevel_handle_v1_set_maximized( + struct wlr_foreign_toplevel_handle_v1 *toplevel, bool maximized) { + set_state(toplevel, maximized, WLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MAXIMIZED); +} + +void wlr_foreign_toplevel_handle_v1_set_minimized( + struct wlr_foreign_toplevel_handle_v1 *toplevel, bool minimized) { + set_state(toplevel, minimized, WLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_MINIMIZED); +} + +void wlr_foreign_toplevel_handle_v1_set_activated( + struct wlr_foreign_toplevel_handle_v1 *toplevel, bool activated) { + set_state(toplevel, activated, WLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_ACTIVATED); +} + +void wlr_foreign_toplevel_handle_v1_set_fullscreen( + struct wlr_foreign_toplevel_handle_v1 * toplevel, bool fullscreen) { + set_state(toplevel, fullscreen, WLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN); +} + +static void toplevel_resource_send_parent( + struct wl_resource *toplevel_resource, + struct wlr_foreign_toplevel_handle_v1 *parent) { + if (wl_resource_get_version(toplevel_resource) < + ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_PARENT_SINCE_VERSION) { + return; + } + struct wl_client *client = wl_resource_get_client(toplevel_resource); + if (parent) { + struct wl_resource *parent_resource; + wl_resource_for_each(parent_resource, &parent->resources) { + if (wl_resource_get_client(parent_resource) == client) { + zwlr_foreign_toplevel_handle_v1_send_parent( + toplevel_resource, parent_resource); + } + } + } else { + zwlr_foreign_toplevel_handle_v1_send_parent(toplevel_resource, NULL); + } +} + +void wlr_foreign_toplevel_handle_v1_set_parent( + struct wlr_foreign_toplevel_handle_v1 *toplevel, + struct wlr_foreign_toplevel_handle_v1 *parent) { + if (parent == toplevel->parent) { + /* only send parent event to the clients if there was a change */ + return; + } + struct wl_resource *toplevel_resource, *tmp; + wl_resource_for_each_safe(toplevel_resource, tmp, &toplevel->resources) { + toplevel_resource_send_parent(toplevel_resource, parent); + } + toplevel->parent = parent; + toplevel_update_idle_source(toplevel); +} + +void wlr_foreign_toplevel_handle_v1_destroy( + struct wlr_foreign_toplevel_handle_v1 *toplevel) { + if (!toplevel) { + return; + } + + wl_signal_emit_mutable(&toplevel->events.destroy, toplevel); + + assert(wl_list_empty(&toplevel->events.request_maximize.listener_list)); + assert(wl_list_empty(&toplevel->events.request_minimize.listener_list)); + assert(wl_list_empty(&toplevel->events.request_activate.listener_list)); + assert(wl_list_empty(&toplevel->events.request_fullscreen.listener_list)); + assert(wl_list_empty(&toplevel->events.request_close.listener_list)); + assert(wl_list_empty(&toplevel->events.set_rectangle.listener_list)); + assert(wl_list_empty(&toplevel->events.destroy.listener_list)); + + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &toplevel->resources) { + zwlr_foreign_toplevel_handle_v1_send_closed(resource); + wl_resource_set_user_data(resource, NULL); + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + } + + struct wlr_foreign_toplevel_handle_v1_output *toplevel_output, *tmp2; + wl_list_for_each_safe(toplevel_output, tmp2, &toplevel->outputs, link) { + toplevel_output_destroy(toplevel_output); + } + + if (toplevel->idle_source) { + wl_event_source_remove(toplevel->idle_source); + } + + wl_list_remove(&toplevel->link); + + /* need to ensure no other toplevels hold a pointer to this one as + * a parent, so that a later call to foreign_toplevel_manager_bind() + * will not result in a segfault */ + struct wlr_foreign_toplevel_handle_v1 *tl, *tmp3; + wl_list_for_each_safe(tl, tmp3, &toplevel->manager->toplevels, link) { + if (tl->parent == toplevel) { + /* Note: we send a parent signal to all clients in this case; + * the caller should first destroy the child handles if it + * wishes to avoid this behavior. */ + wlr_foreign_toplevel_handle_v1_set_parent(tl, NULL); + } + } + + free(toplevel->title); + free(toplevel->app_id); + free(toplevel); +} + +static void foreign_toplevel_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static struct wl_resource *create_toplevel_resource_for_resource( + struct wlr_foreign_toplevel_handle_v1 *toplevel, + struct wl_resource *manager_resource) { + struct wl_client *client = wl_resource_get_client(manager_resource); + struct wl_resource *resource = wl_resource_create(client, + &zwlr_foreign_toplevel_handle_v1_interface, + wl_resource_get_version(manager_resource), 0); + if (!resource) { + wl_client_post_no_memory(client); + return NULL; + } + + wl_resource_set_implementation(resource, &toplevel_handle_impl, toplevel, + foreign_toplevel_resource_destroy); + + wl_list_insert(&toplevel->resources, wl_resource_get_link(resource)); + zwlr_foreign_toplevel_manager_v1_send_toplevel(manager_resource, resource); + return resource; +} + +struct wlr_foreign_toplevel_handle_v1 * +wlr_foreign_toplevel_handle_v1_create( + struct wlr_foreign_toplevel_manager_v1 *manager) { + struct wlr_foreign_toplevel_handle_v1 *toplevel = calloc(1, sizeof(*toplevel)); + if (!toplevel) { + return NULL; + } + + wl_list_insert(manager->toplevels.prev, &toplevel->link); + toplevel->manager = manager; + + wl_list_init(&toplevel->resources); + wl_list_init(&toplevel->outputs); + + wl_signal_init(&toplevel->events.request_maximize); + wl_signal_init(&toplevel->events.request_minimize); + wl_signal_init(&toplevel->events.request_activate); + wl_signal_init(&toplevel->events.request_fullscreen); + wl_signal_init(&toplevel->events.request_close); + wl_signal_init(&toplevel->events.set_rectangle); + wl_signal_init(&toplevel->events.destroy); + + struct wl_resource *manager_resource, *tmp; + wl_resource_for_each_safe(manager_resource, tmp, &manager->resources) { + create_toplevel_resource_for_resource(toplevel, manager_resource); + } + + return toplevel; +} + +static const struct zwlr_foreign_toplevel_manager_v1_interface + foreign_toplevel_manager_impl; + +static void foreign_toplevel_manager_handle_stop(struct wl_client *client, + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_foreign_toplevel_manager_v1_interface, + &foreign_toplevel_manager_impl)); + + zwlr_foreign_toplevel_manager_v1_send_finished(resource); + wl_resource_destroy(resource); +} + +static const struct zwlr_foreign_toplevel_manager_v1_interface + foreign_toplevel_manager_impl = { + .stop = foreign_toplevel_manager_handle_stop +}; + +static void foreign_toplevel_manager_resource_destroy( + struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void toplevel_send_details_to_toplevel_resource( + struct wlr_foreign_toplevel_handle_v1 *toplevel, + struct wl_resource *resource) { + if (toplevel->title) { + zwlr_foreign_toplevel_handle_v1_send_title(resource, toplevel->title); + } + if (toplevel->app_id) { + zwlr_foreign_toplevel_handle_v1_send_app_id(resource, toplevel->app_id); + } + + struct wlr_foreign_toplevel_handle_v1_output *output; + wl_list_for_each(output, &toplevel->outputs, link) { + send_output_to_resource(resource, output->output, true); + } + + struct wl_array state_array; + uint32_t states[FOREIGN_TOPLEVEL_HANDLE_V1_STATE_COUNT]; + fill_array_from_toplevel_state(&state_array, states, + toplevel->state, wl_resource_get_version(resource)); + zwlr_foreign_toplevel_handle_v1_send_state(resource, &state_array); + + toplevel_resource_send_parent(resource, toplevel->parent); + + zwlr_foreign_toplevel_handle_v1_send_done(resource); +} + +static void foreign_toplevel_manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_foreign_toplevel_manager_v1 *manager = data; + struct wl_resource *resource = wl_resource_create(client, + &zwlr_foreign_toplevel_manager_v1_interface, version, id); + if (!resource) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &foreign_toplevel_manager_impl, + manager, foreign_toplevel_manager_resource_destroy); + wl_list_init(wl_resource_get_link(resource)); + if (manager == NULL) { + return; + } + + + wl_list_insert(&manager->resources, wl_resource_get_link(resource)); + + struct wlr_foreign_toplevel_handle_v1 *toplevel, *tmp; + /* First loop: create a handle for all toplevels for all clients. + * Separation into two loops avoid the case where a child handle + * is created before a parent handle, so the parent relationship + * could not be sent to a client. */ + wl_list_for_each_safe(toplevel, tmp, &manager->toplevels, link) { + create_toplevel_resource_for_resource(toplevel, resource); + } + /* Second loop: send details about each toplevel. */ + wl_list_for_each_safe(toplevel, tmp, &manager->toplevels, link) { + struct wl_resource *toplevel_resource; + wl_resource_for_each(toplevel_resource, &toplevel->resources) { + if (wl_resource_get_client(toplevel_resource) == client) { + toplevel_send_details_to_toplevel_resource(toplevel, + toplevel_resource); + } + } + } +} + +static void foreign_toplevel_manager_v1_destroy(struct wlr_foreign_toplevel_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_foreign_toplevel_manager_v1_destroy(struct wlr_foreign_toplevel_manager_v1 *manager, + bool destroy_global_safe) { + foreign_toplevel_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_foreign_toplevel_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + foreign_toplevel_manager_v1_destroy(manager, false); +} + +struct wlr_foreign_toplevel_manager_v1 *wlr_foreign_toplevel_manager_v1_create( + struct wl_display *display) { + struct wlr_foreign_toplevel_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (!manager) { + return NULL; + } + + manager->event_loop = wl_display_get_event_loop(display); + manager->global = wl_global_create(display, + &zwlr_foreign_toplevel_manager_v1_interface, + FOREIGN_TOPLEVEL_MANAGEMENT_V1_VERSION, manager, + foreign_toplevel_manager_bind); + if (!manager->global) { + free(manager); + return NULL; + } + + wl_signal_init(&manager->events.destroy); + + wl_list_init(&manager->resources); + wl_list_init(&manager->toplevels); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_fractional_scale_v1.c b/3rdparty/wlroots/types/wlr_fractional_scale_v1.c new file mode 100644 index 0000000000..0a58c59f66 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_fractional_scale_v1.c @@ -0,0 +1,222 @@ +#include +#include +#include +#include +#include +#include + +#include "fractional-scale-v1-protocol.h" +#include "util/global.h" + +#define FRACTIONAL_SCALE_VERSION 1 + +struct wlr_fractional_scale_v1 { + struct wl_resource *resource; + struct wlr_addon addon; + + // Used for dummy objects to store scale + double scale; +}; + +static const struct wp_fractional_scale_v1_interface fractional_scale_interface; + +static struct wlr_fractional_scale_v1 *fractional_scale_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_fractional_scale_v1_interface, &fractional_scale_interface)); + return wl_resource_get_user_data(resource); +} + +static const struct wp_fractional_scale_manager_v1_interface scale_manager_interface; + +static void fractional_scale_destroy(struct wlr_fractional_scale_v1 *info) { + if (info == NULL) { + return; + } + + // If this is a dummy object then we do not have a wl_resource + if (info->resource != NULL) { + wl_resource_set_user_data(info->resource, NULL); + } + wlr_addon_finish(&info->addon); + free(info); +} + +static void fractional_scale_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_fractional_scale_v1 *info = fractional_scale_from_resource(resource); + fractional_scale_destroy(info); +} + +static void fractional_scale_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wp_fractional_scale_v1_interface fractional_scale_interface = { + .destroy = fractional_scale_handle_destroy, +}; + +static void fractional_scale_addon_destroy(struct wlr_addon *addon) { + struct wlr_fractional_scale_v1 *info = wl_container_of(addon, info, addon); + fractional_scale_destroy(info); +} + +static const struct wlr_addon_interface fractional_scale_addon_impl = { + .name = "wlr_fractional_scale_v1", + .destroy = fractional_scale_addon_destroy, +}; + +static uint32_t double_to_v120(double d) { + return round(d * 120); +} + +void wlr_fractional_scale_v1_notify_scale(struct wlr_surface *surface, double scale) { + struct wlr_addon *addon = wlr_addon_find(&surface->addons, + NULL, &fractional_scale_addon_impl); + + if (addon == NULL) { + // Create a dummy object to store the scale + struct wlr_fractional_scale_v1 *info = calloc(1, sizeof(*info)); + if (info == NULL) { + return; + } + + wlr_addon_init(&info->addon, &surface->addons, NULL, &fractional_scale_addon_impl); + info->scale = scale; + return; + } + + struct wlr_fractional_scale_v1 *info = wl_container_of(addon, info, addon); + if (info->scale == scale) { + return; + } + + info->scale = scale; + + if (!info->resource) { + // Update existing dummy object + return; + } + + wp_fractional_scale_v1_send_preferred_scale(info->resource, double_to_v120(scale)); +} + +static void handle_get_fractional_scale(struct wl_client *client, + struct wl_resource *mgr_resource, uint32_t id, + struct wl_resource *surface_resource) { + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + struct wlr_fractional_scale_v1 *info = NULL; + + // If no fractional_scale object had been created but scale had been set, then + // there will be a dummy object for us to fill out with a resource. Check if + // that's the case. + struct wlr_addon *addon = wlr_addon_find(&surface->addons, NULL, &fractional_scale_addon_impl); + + if (addon != NULL) { + info = wl_container_of(addon, info, addon); + if (info->resource != NULL) { + wl_resource_post_error(mgr_resource, + WP_FRACTIONAL_SCALE_MANAGER_V1_ERROR_FRACTIONAL_SCALE_EXISTS, + "a surface scale object for that surface already exists"); + return; + } + } + + if (info == NULL) { + info = calloc(1, sizeof(*info)); + if (info == NULL) { + wl_client_post_no_memory(client); + return; + } + + wlr_addon_init(&info->addon, &surface->addons, NULL, &fractional_scale_addon_impl); + } + + uint32_t version = wl_resource_get_version(mgr_resource); + info->resource = wl_resource_create(client, &wp_fractional_scale_v1_interface, version, id); + if (info->resource == NULL) { + wl_client_post_no_memory(client); + fractional_scale_destroy(info); + return; + } + wl_resource_set_implementation(info->resource, + &fractional_scale_interface, info, + fractional_scale_handle_resource_destroy); + + if (info->scale != 0) { + wp_fractional_scale_v1_send_preferred_scale(info->resource, double_to_v120(info->scale)); + } +} + +static void fractional_scale_manager_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wp_fractional_scale_manager_v1_interface scale_manager_interface = { + .destroy = fractional_scale_manager_handle_destroy, + .get_fractional_scale = handle_get_fractional_scale, +}; + +static void fractional_scale_manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_fractional_scale_manager_v1 *mgr = data; + + struct wl_resource *resource = wl_resource_create(client, + &wp_fractional_scale_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &scale_manager_interface, mgr, NULL); +} + +static void fractional_scale_manager_v1_destroy(struct wlr_fractional_scale_manager_v1 *mgr, + bool destroy_global_safe) { + wl_signal_emit_mutable(&mgr->events.destroy, NULL); + assert(wl_list_empty(&mgr->events.destroy.listener_list)); + wl_list_remove(&mgr->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(mgr->global); + } else { + wl_global_destroy(mgr->global); + } + free(mgr); +} + +void wlr_fractional_scale_manager_v1_destroy(struct wlr_fractional_scale_manager_v1 *mgr, + bool destroy_global_safe) { + fractional_scale_manager_v1_destroy(mgr, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_fractional_scale_manager_v1 *mgr = + wl_container_of(listener, mgr, display_destroy); + fractional_scale_manager_v1_destroy(mgr, false); +} + +struct wlr_fractional_scale_manager_v1 *wlr_fractional_scale_manager_v1_create( + struct wl_display *display, uint32_t version) { + assert(version <= FRACTIONAL_SCALE_VERSION); + + struct wlr_fractional_scale_manager_v1 *mgr = calloc(1, sizeof(*mgr)); + if (mgr == NULL) { + return NULL; + } + + mgr->global = wl_global_create(display, + &wp_fractional_scale_manager_v1_interface, + version, mgr, fractional_scale_manager_bind); + if (mgr->global == NULL) { + free(mgr); + return NULL; + } + + mgr->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &mgr->display_destroy); + + wl_signal_init(&mgr->events.destroy); + + return mgr; +} + diff --git a/3rdparty/wlroots/types/wlr_gamma_control_v1.c b/3rdparty/wlroots/types/wlr_gamma_control_v1.c new file mode 100644 index 0000000000..a25fce7ab7 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_gamma_control_v1.c @@ -0,0 +1,317 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "wlr-gamma-control-unstable-v1-protocol.h" +#include "util/global.h" + +#define GAMMA_CONTROL_MANAGER_V1_VERSION 1 + +static void gamma_control_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void gamma_control_destroy(struct wlr_gamma_control_v1 *gamma_control) { + if (gamma_control == NULL) { + return; + } + + struct wlr_gamma_control_manager_v1 *manager = gamma_control->manager; + struct wlr_output *output = gamma_control->output; + + wl_resource_set_user_data(gamma_control->resource, NULL); + wl_list_remove(&gamma_control->output_destroy_listener.link); + wl_list_remove(&gamma_control->link); + free(gamma_control->table); + free(gamma_control); + + struct wlr_gamma_control_manager_v1_set_gamma_event event = { + .output = output, + }; + wl_signal_emit_mutable(&manager->events.set_gamma, &event); +} + +static const struct zwlr_gamma_control_v1_interface gamma_control_impl; + +static struct wlr_gamma_control_v1 *gamma_control_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwlr_gamma_control_v1_interface, + &gamma_control_impl)); + return wl_resource_get_user_data(resource); +} + +static void gamma_control_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_gamma_control_v1 *gamma_control = + gamma_control_from_resource(resource); + gamma_control_destroy(gamma_control); +} + +static void gamma_control_handle_output_destroy(struct wl_listener *listener, + void *data) { + struct wlr_gamma_control_v1 *gamma_control = + wl_container_of(listener, gamma_control, output_destroy_listener); + gamma_control_destroy(gamma_control); +} + +static void gamma_control_handle_set_gamma(struct wl_client *client, + struct wl_resource *gamma_control_resource, int fd) { + struct wlr_gamma_control_v1 *gamma_control = + gamma_control_from_resource(gamma_control_resource); + if (gamma_control == NULL) { + goto error_fd; + } + + size_t table_size = gamma_control->ramp_size * 3 * sizeof(uint16_t); + + // Refuse to block when reading + int fd_flags = fcntl(fd, F_GETFL, 0); + if (fd_flags == -1) { + wlr_log_errno(WLR_ERROR, "failed to get FD flags"); + wlr_gamma_control_v1_send_failed_and_destroy(gamma_control); + goto error_fd; + } + if (fcntl(fd, F_SETFL, fd_flags | O_NONBLOCK) == -1) { + wlr_log_errno(WLR_ERROR, "failed to set FD flags"); + wlr_gamma_control_v1_send_failed_and_destroy(gamma_control); + goto error_fd; + } + + // Use the heap since gamma tables can be large + uint16_t *table = malloc(table_size); + if (table == NULL) { + wl_resource_post_no_memory(gamma_control_resource); + goto error_fd; + } + + ssize_t n_read = pread(fd, table, table_size, 0); + if (n_read < 0) { + wlr_log_errno(WLR_ERROR, "failed to read gamma table"); + wlr_gamma_control_v1_send_failed_and_destroy(gamma_control); + goto error_table; + } else if ((size_t)n_read != table_size) { + wl_resource_post_error(gamma_control_resource, + ZWLR_GAMMA_CONTROL_V1_ERROR_INVALID_GAMMA, + "The gamma ramps don't have the correct size"); + goto error_table; + } + close(fd); + + free(gamma_control->table); + gamma_control->table = table; + + struct wlr_gamma_control_manager_v1_set_gamma_event event = { + .output = gamma_control->output, + .control = gamma_control, + }; + wl_signal_emit_mutable(&gamma_control->manager->events.set_gamma, &event); + + return; + +error_table: + free(table); +error_fd: + close(fd); +} + +static const struct zwlr_gamma_control_v1_interface gamma_control_impl = { + .destroy = gamma_control_handle_destroy, + .set_gamma = gamma_control_handle_set_gamma, +}; + +static const struct zwlr_gamma_control_manager_v1_interface + gamma_control_manager_impl; + +static struct wlr_gamma_control_manager_v1 *gamma_control_manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_gamma_control_manager_v1_interface, &gamma_control_manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void gamma_control_manager_get_gamma_control(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + struct wl_resource *output_resource) { + struct wlr_gamma_control_manager_v1 *manager = + gamma_control_manager_from_resource(manager_resource); + struct wlr_output *output = wlr_output_from_resource(output_resource); + + uint32_t version = wl_resource_get_version(manager_resource); + struct wl_resource *resource = wl_resource_create(client, + &zwlr_gamma_control_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &gamma_control_impl, + NULL, gamma_control_handle_resource_destroy); + + if (output == NULL) { + zwlr_gamma_control_v1_send_failed(resource); + return; + } + + size_t gamma_size = wlr_output_get_gamma_size(output); + if (gamma_size == 0) { + gamma_size = manager->fallback_gamma_size; + } + if (gamma_size == 0) { + zwlr_gamma_control_v1_send_failed(resource); + return; + } + + if (wlr_gamma_control_manager_v1_get_control(manager, output) != NULL) { + zwlr_gamma_control_v1_send_failed(resource); + return; + } + + struct wlr_gamma_control_v1 *gamma_control = calloc(1, sizeof(*gamma_control)); + if (gamma_control == NULL) { + wl_client_post_no_memory(client); + return; + } + gamma_control->output = output; + gamma_control->manager = manager; + gamma_control->resource = resource; + gamma_control->ramp_size = gamma_size; + wl_resource_set_user_data(resource, gamma_control); + + wl_signal_add(&output->events.destroy, + &gamma_control->output_destroy_listener); + gamma_control->output_destroy_listener.notify = + gamma_control_handle_output_destroy; + + wl_list_insert(&manager->controls, &gamma_control->link); + zwlr_gamma_control_v1_send_gamma_size(gamma_control->resource, gamma_size); +} + +static void gamma_control_manager_destroy(struct wl_client *client, + struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static const struct zwlr_gamma_control_manager_v1_interface + gamma_control_manager_impl = { + .get_gamma_control = gamma_control_manager_get_gamma_control, + .destroy = gamma_control_manager_destroy, +}; + +static void gamma_control_manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_gamma_control_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &zwlr_gamma_control_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &gamma_control_manager_impl, + manager, NULL); +} + +static void gamma_control_manager_v1_destroy(struct wlr_gamma_control_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + assert(wl_list_empty(&manager->events.set_gamma.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_gamma_control_manager_v1_destroy(struct wlr_gamma_control_manager_v1 *manager, + bool destroy_global_safe) { + gamma_control_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_gamma_control_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + gamma_control_manager_v1_destroy(manager, false); +} + +struct wlr_gamma_control_manager_v1 *wlr_gamma_control_manager_v1_create( + struct wl_display *display) { + struct wlr_gamma_control_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (!manager) { + return NULL; + } + + manager->global = wl_global_create(display, + &zwlr_gamma_control_manager_v1_interface, + GAMMA_CONTROL_MANAGER_V1_VERSION, manager, gamma_control_manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + wl_signal_init(&manager->events.destroy); + wl_signal_init(&manager->events.set_gamma); + + wl_list_init(&manager->controls); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} + +struct wlr_gamma_control_v1 *wlr_gamma_control_manager_v1_get_control( + struct wlr_gamma_control_manager_v1 *manager, struct wlr_output *output) { + struct wlr_gamma_control_v1 *gamma_control; + wl_list_for_each(gamma_control, &manager->controls, link) { + if (gamma_control->output == output) { + return gamma_control; + } + } + return NULL; +} + +struct wlr_color_transform *wlr_gamma_control_v1_get_color_transform( + struct wlr_gamma_control_v1 *gamma_control) { + if (gamma_control == NULL || gamma_control->table == NULL) { + return NULL; + } + + const uint16_t *r = gamma_control->table; + const uint16_t *g = gamma_control->table + gamma_control->ramp_size; + const uint16_t *b = gamma_control->table + 2 * gamma_control->ramp_size; + + return wlr_color_transform_init_lut_3x1d(gamma_control->ramp_size, r, g, b); +} + +bool wlr_gamma_control_v1_apply(struct wlr_gamma_control_v1 *gamma_control, + struct wlr_output_state *output_state) { + struct wlr_color_transform *tr = NULL; + if (gamma_control != NULL && gamma_control->table != NULL) { + tr = wlr_gamma_control_v1_get_color_transform(gamma_control); + if (tr == NULL) { + return false; + } + } + + wlr_output_state_set_color_transform(output_state, tr); + return true; +} + +void wlr_gamma_control_v1_send_failed_and_destroy(struct wlr_gamma_control_v1 *gamma_control) { + if (gamma_control == NULL) { + return; + } + zwlr_gamma_control_v1_send_failed(gamma_control->resource); + gamma_control_destroy(gamma_control); +} diff --git a/3rdparty/wlroots/types/wlr_idle_inhibit_v1.c b/3rdparty/wlroots/types/wlr_idle_inhibit_v1.c new file mode 100644 index 0000000000..54a9999e8e --- /dev/null +++ b/3rdparty/wlroots/types/wlr_idle_inhibit_v1.c @@ -0,0 +1,182 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "idle-inhibit-unstable-v1-protocol.h" +#include "util/global.h" + +static const struct zwp_idle_inhibit_manager_v1_interface idle_inhibit_impl; + +static const struct zwp_idle_inhibitor_v1_interface idle_inhibitor_impl; + +static struct wlr_idle_inhibit_manager_v1 * +wlr_idle_inhibit_manager_v1_from_resource(struct wl_resource *manager_resource) { + assert(wl_resource_instance_of(manager_resource, + &zwp_idle_inhibit_manager_v1_interface, + &idle_inhibit_impl)); + return wl_resource_get_user_data(manager_resource); +} + +static struct wlr_idle_inhibitor_v1 * +wlr_idle_inhibitor_v1_from_resource(struct wl_resource *inhibitor_resource) { + assert(wl_resource_instance_of(inhibitor_resource, + &zwp_idle_inhibitor_v1_interface, + &idle_inhibitor_impl)); + return wl_resource_get_user_data(inhibitor_resource); +} + +static void idle_inhibitor_v1_destroy(struct wlr_idle_inhibitor_v1 *inhibitor) { + if (!inhibitor) { + return; + } + + wl_signal_emit_mutable(&inhibitor->events.destroy, inhibitor->surface); + + assert(wl_list_empty(&inhibitor->events.destroy.listener_list)); + + wl_resource_set_user_data(inhibitor->resource, NULL); + wl_list_remove(&inhibitor->link); + wl_list_remove(&inhibitor->surface_destroy.link); + free(inhibitor); +} + +static void idle_inhibitor_v1_handle_resource_destroy( + struct wl_resource *inhibitor_resource) { + struct wlr_idle_inhibitor_v1 *inhibitor = + wlr_idle_inhibitor_v1_from_resource(inhibitor_resource); + idle_inhibitor_v1_destroy(inhibitor); +} + +static void idle_inhibitor_handle_surface_destroy( + struct wl_listener *listener, void *data) { + struct wlr_idle_inhibitor_v1 *inhibitor = + wl_container_of(listener, inhibitor, surface_destroy); + idle_inhibitor_v1_destroy(inhibitor); +} + +static void idle_inhibitor_v1_handle_destroy(struct wl_client *client, + struct wl_resource *inhibitor_resource) { + wl_resource_destroy(inhibitor_resource); +} + +static const struct zwp_idle_inhibitor_v1_interface idle_inhibitor_impl = { + .destroy = idle_inhibitor_v1_handle_destroy, +}; + +static void manager_handle_create_inhibitor(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + struct wl_resource *surface_resource) { + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + struct wlr_idle_inhibit_manager_v1 *manager = + wlr_idle_inhibit_manager_v1_from_resource(manager_resource); + + struct wlr_idle_inhibitor_v1 *inhibitor = calloc(1, sizeof(*inhibitor)); + if (!inhibitor) { + wl_client_post_no_memory(client); + return; + } + + uint32_t version = wl_resource_get_version(manager_resource); + struct wl_resource *inhibitor_resource = wl_resource_create(client, + &zwp_idle_inhibitor_v1_interface, version, id); + if (!inhibitor_resource) { + wl_client_post_no_memory(client); + free(inhibitor); + return; + } + + inhibitor->resource = inhibitor_resource; + inhibitor->surface = surface; + + wl_signal_init(&inhibitor->events.destroy); + + inhibitor->surface_destroy.notify = idle_inhibitor_handle_surface_destroy; + wl_signal_add(&surface->events.destroy, &inhibitor->surface_destroy); + + wl_resource_set_implementation(inhibitor_resource, &idle_inhibitor_impl, + inhibitor, idle_inhibitor_v1_handle_resource_destroy); + + wl_list_insert(&manager->inhibitors, &inhibitor->link); + wl_signal_emit_mutable(&manager->events.new_inhibitor, inhibitor); +} + +static void manager_handle_destroy(struct wl_client *client, + struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static const struct zwp_idle_inhibit_manager_v1_interface idle_inhibit_impl = { + .destroy = manager_handle_destroy, + .create_inhibitor = manager_handle_create_inhibitor, +}; + +static void idle_inhibit_manager_v1_destroy(struct wlr_idle_inhibit_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.new_inhibitor.listener_list)); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_idle_inhibit_v1_destroy(struct wlr_idle_inhibit_manager_v1 *manager, + bool destroy_global_safe) { + idle_inhibit_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_idle_inhibit_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + idle_inhibit_manager_v1_destroy(manager, false); +} + +static void idle_inhibit_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_idle_inhibit_manager_v1 *manager = data; + + struct wl_resource *manager_resource = wl_resource_create(wl_client, + &zwp_idle_inhibit_manager_v1_interface, version, id); + if (!manager_resource) { + wl_client_post_no_memory(wl_client); + return; + } + + wl_resource_set_implementation(manager_resource, &idle_inhibit_impl, + manager, NULL); +} + +struct wlr_idle_inhibit_manager_v1 *wlr_idle_inhibit_v1_create(struct wl_display *display) { + struct wlr_idle_inhibit_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (!manager) { + return NULL; + } + + wl_list_init(&manager->inhibitors); + + wl_signal_init(&manager->events.new_inhibitor); + wl_signal_init(&manager->events.destroy); + + manager->global = wl_global_create(display, + &zwp_idle_inhibit_manager_v1_interface, 1, + manager, idle_inhibit_bind); + if (!manager->global) { + free(manager); + return NULL; + } + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_idle_notify_v1.c b/3rdparty/wlroots/types/wlr_idle_notify_v1.c new file mode 100644 index 0000000000..6723fdf447 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_idle_notify_v1.c @@ -0,0 +1,279 @@ +#include +#include +#include +#include +#include +#include "ext-idle-notify-v1-protocol.h" +#include "util/global.h" + +#define IDLE_NOTIFIER_VERSION 2 + +struct wlr_idle_notification_v1 { + struct wl_resource *resource; + struct wl_list link; // wlr_idle_notifier_v1.notifications + struct wlr_idle_notifier_v1 *notifier; + struct wlr_seat *seat; + + uint32_t timeout_ms; + struct wl_event_source *timer; + + bool idle; + bool obey_inhibitors; + + struct wl_listener seat_destroy; +}; + +static void resource_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct ext_idle_notifier_v1_interface notifier_impl; + +static const struct ext_idle_notification_v1_interface notification_impl = { + .destroy = resource_handle_destroy, +}; + +// Returns NULL if the resource is inert +static struct wlr_idle_notification_v1 *notification_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_idle_notification_v1_interface, ¬ification_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_idle_notifier_v1 *notifier_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_idle_notifier_v1_interface, ¬ifier_impl)); + return wl_resource_get_user_data(resource); +} + +static void notification_set_idle(struct wlr_idle_notification_v1 *notification, + bool idle) { + if (notification->idle == idle) { + return; + } + + if (idle) { + ext_idle_notification_v1_send_idled(notification->resource); + } else { + ext_idle_notification_v1_send_resumed(notification->resource); + } + + notification->idle = idle; +} + +static int notification_handle_timer(void *data) { + struct wlr_idle_notification_v1 *notification = data; + notification_set_idle(notification, true); + return 0; +} + +static void notification_destroy(struct wlr_idle_notification_v1 *notification) { + if (notification == NULL) { + return; + } + wl_list_remove(¬ification->link); + wl_list_remove(¬ification->seat_destroy.link); + if (notification->timer != NULL) { + wl_event_source_remove(notification->timer); + } + wl_resource_set_user_data(notification->resource, NULL); // make inert + free(notification); +} + +static void notification_reset_timer(struct wlr_idle_notification_v1 *notification) { + if (notification->notifier->inhibited && notification->obey_inhibitors) { + notification_set_idle(notification, false); + if (notification->timer != NULL) { + wl_event_source_timer_update(notification->timer, 0); + } + return; + } + + if (notification->timer != NULL) { + wl_event_source_timer_update(notification->timer, + notification->timeout_ms); + } else { + notification_set_idle(notification, true); + } +} + +static void notification_handle_activity(struct wlr_idle_notification_v1 *notification) { + notification_set_idle(notification, false); + notification_reset_timer(notification); +} + +static void notification_handle_seat_destroy(struct wl_listener *listener, + void *data) { + struct wlr_idle_notification_v1 *notification = + wl_container_of(listener, notification, seat_destroy); + notification_destroy(notification); +} + +static void notification_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_idle_notification_v1 *notification = + notification_from_resource(resource); + notification_destroy(notification); +} + +static void construct_idle_notification(struct wl_client *client, + struct wl_resource *notifier_resource, uint32_t id, uint32_t timeout, + struct wl_resource *seat_resource, bool obey_inhibitors) { + struct wlr_idle_notifier_v1 *notifier = + notifier_from_resource(notifier_resource); + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat_resource); + + uint32_t version = wl_resource_get_version(notifier_resource); + struct wl_resource *resource = wl_resource_create(client, + &ext_idle_notification_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, ¬ification_impl, NULL, + notification_handle_resource_destroy); + + if (seat_client == NULL) { + return; // leave the resource inert + } + + struct wlr_idle_notification_v1 *notification = + calloc(1, sizeof(*notification)); + if (notification == NULL) { + wl_client_post_no_memory(client); + return; + } + + notification->notifier = notifier; + notification->resource = resource; + notification->timeout_ms = timeout; + notification->seat = seat_client->seat; + notification->obey_inhibitors = obey_inhibitors; + + if (timeout > 0) { + struct wl_display *display = wl_client_get_display(client); + struct wl_event_loop *loop = wl_display_get_event_loop(display); + notification->timer = wl_event_loop_add_timer(loop, + notification_handle_timer, notification); + if (notification->timer == NULL) { + free(notification); + wl_client_post_no_memory(client); + return; + } + } + + notification->seat_destroy.notify = notification_handle_seat_destroy; + wl_signal_add(&seat_client->seat->events.destroy, ¬ification->seat_destroy); + + wl_resource_set_user_data(resource, notification); + wl_list_insert(¬ifier->notifications, ¬ification->link); + + notification_reset_timer(notification); +} + +static void notifier_handle_get_input_idle_notification( + struct wl_client *client, + struct wl_resource *notifier_resource, uint32_t id, + uint32_t timeout, struct wl_resource *seat_resource) { + construct_idle_notification(client, notifier_resource, id, + timeout, seat_resource, false); +} + +static void notifier_handle_get_idle_notification( + struct wl_client *client, + struct wl_resource *notifier_resource, uint32_t id, + uint32_t timeout, struct wl_resource *seat_resource) { + construct_idle_notification(client, notifier_resource, id, + timeout, seat_resource, true); +} + +static const struct ext_idle_notifier_v1_interface notifier_impl = { + .destroy = resource_handle_destroy, + .get_idle_notification = notifier_handle_get_idle_notification, + .get_input_idle_notification = notifier_handle_get_input_idle_notification, +}; + +static void notifier_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_idle_notifier_v1 *notifier = data; + + struct wl_resource *resource = wl_resource_create(client, + &ext_idle_notifier_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, ¬ifier_impl, notifier, NULL); +} + +static void idle_notifier_v1_destroy(struct wlr_idle_notifier_v1 *notifier, + bool destroy_global_safe) { + if (destroy_global_safe) { + wlr_global_destroy_safe(notifier->global); + } else { + wl_global_destroy(notifier->global); + } + wl_list_remove(¬ifier->display_destroy.link); + free(notifier); +} + +void wlr_idle_notifier_v1_destroy(struct wlr_idle_notifier_v1 *notifier, bool destroy_global_safe) { + idle_notifier_v1_destroy(notifier, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_idle_notifier_v1 *notifier = + wl_container_of(listener, notifier, display_destroy); + idle_notifier_v1_destroy(notifier, false); +} + +struct wlr_idle_notifier_v1 *wlr_idle_notifier_v1_create(struct wl_display *display) { + struct wlr_idle_notifier_v1 *notifier = calloc(1, sizeof(*notifier)); + if (notifier == NULL) { + return NULL; + } + + notifier->global = wl_global_create(display, + &ext_idle_notifier_v1_interface, IDLE_NOTIFIER_VERSION, notifier, + notifier_bind); + if (notifier->global == NULL) { + free(notifier); + return NULL; + } + + wl_list_init(¬ifier->notifications); + + notifier->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, ¬ifier->display_destroy); + + return notifier; +} + +void wlr_idle_notifier_v1_set_inhibited(struct wlr_idle_notifier_v1 *notifier, + bool inhibited) { + if (notifier->inhibited == inhibited) { + return; + } + + notifier->inhibited = inhibited; + + struct wlr_idle_notification_v1 *notification; + wl_list_for_each(notification, ¬ifier->notifications, link) { + if (notification->obey_inhibitors) { + notification_reset_timer(notification); + } + } +} + +void wlr_idle_notifier_v1_notify_activity(struct wlr_idle_notifier_v1 *notifier, + struct wlr_seat *seat) { + struct wlr_idle_notification_v1 *notification; + wl_list_for_each(notification, ¬ifier->notifications, link) { + if (notification->seat == seat && !(notifier->inhibited && notification->obey_inhibitors)) { + notification_handle_activity(notification); + } + } +} diff --git a/3rdparty/wlroots/types/wlr_input_device.c b/3rdparty/wlroots/types/wlr_input_device.c new file mode 100644 index 0000000000..201059db8f --- /dev/null +++ b/3rdparty/wlroots/types/wlr_input_device.c @@ -0,0 +1,26 @@ +#include +#include +#include +#include "interfaces/wlr_input_device.h" + +void wlr_input_device_init(struct wlr_input_device *dev, + enum wlr_input_device_type type, const char *name) { + *dev = (struct wlr_input_device){ + .type = type, + .name = name ? strdup(name) : NULL, + }; + + wl_signal_init(&dev->events.destroy); +} + +void wlr_input_device_finish(struct wlr_input_device *wlr_device) { + if (!wlr_device) { + return; + } + + wl_signal_emit_mutable(&wlr_device->events.destroy, wlr_device); + + assert(wl_list_empty(&wlr_device->events.destroy.listener_list)); + + free(wlr_device->name); +} diff --git a/3rdparty/wlroots/types/wlr_input_method_v2.c b/3rdparty/wlroots/types/wlr_input_method_v2.c new file mode 100644 index 0000000000..9787a5363c --- /dev/null +++ b/3rdparty/wlroots/types/wlr_input_method_v2.c @@ -0,0 +1,658 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "input-method-unstable-v2-protocol.h" +#include "util/global.h" + +// Note: zwp_input_popup_surface_v2 and zwp_input_method_keyboard_grab_v2 objects +// become inert when the corresponding zwp_input_method_v2 is destroyed + +static const struct zwp_input_method_v2_interface input_method_impl; +static const struct zwp_input_method_keyboard_grab_v2_interface keyboard_grab_impl; + +static void input_state_reset(struct wlr_input_method_v2_state *state) { + free(state->commit_text); + free(state->preedit.text); + *state = (struct wlr_input_method_v2_state){0}; +} + +static void popup_surface_destroy(struct wlr_input_popup_surface_v2 *popup_surface) { + wlr_surface_unmap(popup_surface->surface); + + wl_signal_emit_mutable(&popup_surface->events.destroy, NULL); + + assert(wl_list_empty(&popup_surface->events.destroy.listener_list)); + + wl_list_remove(&popup_surface->link); + wl_resource_set_user_data(popup_surface->resource, NULL); + free(popup_surface); +} + +static struct wlr_input_method_v2 *input_method_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwp_input_method_v2_interface, &input_method_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_input_method_keyboard_grab_v2 *keyboard_grab_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwp_input_method_keyboard_grab_v2_interface, + &keyboard_grab_impl)); + return wl_resource_get_user_data(resource); +} + +static void input_method_destroy(struct wlr_input_method_v2 *input_method) { + struct wlr_input_popup_surface_v2 *popup_surface, *tmp; + wl_list_for_each_safe( + popup_surface, tmp, &input_method->popup_surfaces, link) { + popup_surface_destroy(popup_surface); + } + wlr_input_method_keyboard_grab_v2_destroy(input_method->keyboard_grab); + wl_signal_emit_mutable(&input_method->events.destroy, NULL); + + assert(wl_list_empty(&input_method->events.commit.listener_list)); + assert(wl_list_empty(&input_method->events.new_popup_surface.listener_list)); + assert(wl_list_empty(&input_method->events.grab_keyboard.listener_list)); + assert(wl_list_empty(&input_method->events.destroy.listener_list)); + + wl_list_remove(wl_resource_get_link(input_method->resource)); + wl_list_remove(&input_method->seat_client_destroy.link); + input_state_reset(&input_method->pending); + input_state_reset(&input_method->current); + free(input_method); +} + +static void input_method_resource_destroy(struct wl_resource *resource) { + struct wlr_input_method_v2 *input_method = + input_method_from_resource(resource); + if (!input_method) { + return; + } + input_method_destroy(input_method); +} + +static void im_destroy(struct wl_client *client, struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void im_commit(struct wl_client *client, struct wl_resource *resource, + uint32_t serial) { + struct wlr_input_method_v2 *input_method = + input_method_from_resource(resource); + if (!input_method) { + return; + } + if (serial != input_method->current_serial) { + input_state_reset(&input_method->pending); + return; + } + input_state_reset(&input_method->current); + + // This transfers ownership of the current commit_text and + // preedit.text from pending to current: + input_method->current = input_method->pending; + input_method->pending = (struct wlr_input_method_v2_state){0}; + + wl_signal_emit_mutable(&input_method->events.commit, NULL); +} + +static void im_commit_string(struct wl_client *client, + struct wl_resource *resource, const char *text) { + struct wlr_input_method_v2 *input_method = + input_method_from_resource(resource); + if (!input_method) { + return; + } + free(input_method->pending.commit_text); + input_method->pending.commit_text = strdup(text); + if (input_method->pending.commit_text == NULL) { + wl_client_post_no_memory(client); + return; + } +} + +static void im_set_preedit_string(struct wl_client *client, + struct wl_resource *resource, const char *text, int32_t cursor_begin, + int32_t cursor_end) { + struct wlr_input_method_v2 *input_method = + input_method_from_resource(resource); + if (!input_method) { + return; + } + input_method->pending.preedit.cursor_begin = cursor_begin; + input_method->pending.preedit.cursor_end = cursor_end; + free(input_method->pending.preedit.text); + input_method->pending.preedit.text = strdup(text); + if (input_method->pending.preedit.text == NULL) { + wl_client_post_no_memory(client); + return; + } +} + +static void im_delete_surrounding_text(struct wl_client *client, + struct wl_resource *resource, + uint32_t before_length, uint32_t after_length) { + struct wlr_input_method_v2 *input_method = + input_method_from_resource(resource); + if (!input_method) { + return; + } + input_method->pending.delete.before_length = before_length; + input_method->pending.delete.after_length = after_length; +} + +void wlr_input_popup_surface_v2_send_text_input_rectangle( + struct wlr_input_popup_surface_v2 *popup_surface, + struct wlr_box *sbox) { + zwp_input_popup_surface_v2_send_text_input_rectangle( + popup_surface->resource, sbox->x, sbox->y, sbox->width, sbox->height); +} + +static void popup_surface_update_mapped(struct wlr_input_popup_surface_v2 *popup_surface) { + if (popup_surface->input_method->client_active) { + if (wlr_surface_has_buffer(popup_surface->surface)) { + wlr_surface_map(popup_surface->surface); + } + } else { + wlr_surface_unmap(popup_surface->surface); + } +} + +static void popup_surface_surface_role_commit(struct wlr_surface *surface) { + struct wlr_input_popup_surface_v2 *popup_surface = + wlr_input_popup_surface_v2_try_from_wlr_surface(surface); + if (popup_surface == NULL) { + return; + } + + popup_surface_update_mapped(popup_surface); +} + +static void popup_surface_surface_role_destroy(struct wlr_surface *surface) { + struct wlr_input_popup_surface_v2 *popup_surface = + wlr_input_popup_surface_v2_try_from_wlr_surface(surface); + if (popup_surface == NULL) { + return; + } + + popup_surface_destroy(popup_surface); +} + +static const struct wlr_surface_role input_popup_surface_v2_role = { + .name = "zwp_input_popup_surface_v2", + .commit = popup_surface_surface_role_commit, + .destroy = popup_surface_surface_role_destroy, +}; + +static const struct zwp_input_popup_surface_v2_interface input_popup_impl; + +static struct wlr_input_popup_surface_v2 *popup_surface_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwp_input_popup_surface_v2_interface, + &input_popup_impl)); + return wl_resource_get_user_data(resource); +} + +struct wlr_input_popup_surface_v2 *wlr_input_popup_surface_v2_try_from_wlr_surface( + struct wlr_surface *surface) { + if (surface->role != &input_popup_surface_v2_role || surface->role_resource == NULL) { + return NULL; + } + return popup_surface_from_resource(surface->role_resource); +} + +static void popup_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwp_input_popup_surface_v2_interface input_popup_impl = { + .destroy = popup_destroy, +}; + +static void im_get_input_popup_surface(struct wl_client *client, + struct wl_resource *resource, uint32_t id, + struct wl_resource *surface_resource) { + struct wlr_input_method_v2 *input_method = + input_method_from_resource(resource); + if (!input_method) { + return; + } + + struct wlr_input_popup_surface_v2 *popup_surface = calloc(1, sizeof(*popup_surface)); + if (!popup_surface) { + wl_client_post_no_memory(client); + return; + } + + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + if (!wlr_surface_set_role(surface, &input_popup_surface_v2_role, + resource, ZWP_INPUT_METHOD_V2_ERROR_ROLE)) { + free(popup_surface); + return; + } + + struct wl_resource *popup_resource = wl_resource_create( + client, &zwp_input_popup_surface_v2_interface, + wl_resource_get_version(resource), id); + if (!popup_resource) { + free(popup_surface); + wl_client_post_no_memory(client); + return; + } + + wl_resource_set_implementation(popup_resource, &input_popup_impl, + popup_surface, NULL); + + wlr_surface_set_role_object(surface, popup_resource); + + popup_surface->resource = popup_resource; + popup_surface->input_method = input_method; + popup_surface->surface = surface; + + wl_signal_init(&popup_surface->events.destroy); + + popup_surface_update_mapped(popup_surface); + + wl_list_insert(&input_method->popup_surfaces, &popup_surface->link); + wl_signal_emit_mutable(&input_method->events.new_popup_surface, popup_surface); +} + +void wlr_input_method_keyboard_grab_v2_destroy( + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab) { + if (!keyboard_grab) { + return; + } + wl_signal_emit_mutable(&keyboard_grab->events.destroy, NULL); + assert(wl_list_empty(&keyboard_grab->events.destroy.listener_list)); + + keyboard_grab->input_method->keyboard_grab = NULL; + if (keyboard_grab->keyboard) { + wl_list_remove(&keyboard_grab->keyboard_keymap.link); + wl_list_remove(&keyboard_grab->keyboard_repeat_info.link); + wl_list_remove(&keyboard_grab->keyboard_destroy.link); + } + wl_resource_set_user_data(keyboard_grab->resource, NULL); + free(keyboard_grab); +} + +static void keyboard_grab_resource_destroy(struct wl_resource *resource) { + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab = + keyboard_grab_from_resource(resource); + wlr_input_method_keyboard_grab_v2_destroy(keyboard_grab); +} + +static void keyboard_grab_release(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwp_input_method_keyboard_grab_v2_interface keyboard_grab_impl = { + .release = keyboard_grab_release, +}; + +void wlr_input_method_keyboard_grab_v2_send_key( + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab, + uint32_t time, uint32_t key, uint32_t state) { + zwp_input_method_keyboard_grab_v2_send_key( + keyboard_grab->resource, + wlr_seat_client_next_serial(keyboard_grab->input_method->seat_client), + time, key, state); +} + +void wlr_input_method_keyboard_grab_v2_send_modifiers( + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab, + struct wlr_keyboard_modifiers *modifiers) { + zwp_input_method_keyboard_grab_v2_send_modifiers( + keyboard_grab->resource, + wlr_seat_client_next_serial(keyboard_grab->input_method->seat_client), + modifiers->depressed, modifiers->latched, + modifiers->locked, modifiers->group); +} + +static void keyboard_grab_send_keymap( + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab, + struct wlr_keyboard *keyboard) { + enum wl_keyboard_keymap_format format; + int fd, devnull = -1; + if (keyboard->keymap != NULL) { + format = WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1; + fd = keyboard->keymap_fd; + } else { + format = WL_KEYBOARD_KEYMAP_FORMAT_NO_KEYMAP; + devnull = open("/dev/null", O_RDONLY | O_CLOEXEC); + if (devnull < 0) { + wlr_log_errno(WLR_ERROR, "Failed to open /dev/null"); + return; + } + fd = devnull; + } + + zwp_input_method_keyboard_grab_v2_send_keymap(keyboard_grab->resource, + format, fd, keyboard->keymap_size); + + if (devnull >= 0) { + close(devnull); + } +} + +static void keyboard_grab_send_repeat_info( + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab, + struct wlr_keyboard *keyboard) { + zwp_input_method_keyboard_grab_v2_send_repeat_info( + keyboard_grab->resource, keyboard->repeat_info.rate, + keyboard->repeat_info.delay); +} + +static void handle_keyboard_keymap(struct wl_listener *listener, void *data) { + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab = + wl_container_of(listener, keyboard_grab, keyboard_keymap); + keyboard_grab_send_keymap(keyboard_grab, data); +} + +static void handle_keyboard_repeat_info(struct wl_listener *listener, + void *data) { + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab = + wl_container_of(listener, keyboard_grab, keyboard_repeat_info); + keyboard_grab_send_repeat_info(keyboard_grab, data); +} + +static void handle_keyboard_destroy(struct wl_listener *listener, + void *data) { + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab = + wl_container_of(listener, keyboard_grab, keyboard_destroy); + wlr_input_method_keyboard_grab_v2_set_keyboard(keyboard_grab, NULL); +} + +void wlr_input_method_keyboard_grab_v2_set_keyboard( + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab, + struct wlr_keyboard *keyboard) { + if (keyboard == keyboard_grab->keyboard) { + return; + } + + if (keyboard_grab->keyboard) { + wl_list_remove(&keyboard_grab->keyboard_keymap.link); + wl_list_remove(&keyboard_grab->keyboard_repeat_info.link); + wl_list_remove(&keyboard_grab->keyboard_destroy.link); + } + + if (keyboard) { + if (keyboard_grab->keyboard == NULL || + !wlr_keyboard_keymaps_match(keyboard_grab->keyboard->keymap, + keyboard->keymap)) { + // Only send keymap if it changed, otherwise if the input-method + // client sent back the same keymap with virtual-keyboard, it would + // result in an infinite loop of keymap updates. + keyboard_grab_send_keymap(keyboard_grab, keyboard); + } + keyboard_grab_send_repeat_info(keyboard_grab, keyboard); + keyboard_grab->keyboard_keymap.notify = handle_keyboard_keymap; + wl_signal_add(&keyboard->events.keymap, + &keyboard_grab->keyboard_keymap); + keyboard_grab->keyboard_repeat_info.notify = + handle_keyboard_repeat_info; + wl_signal_add(&keyboard->events.repeat_info, + &keyboard_grab->keyboard_repeat_info); + keyboard_grab->keyboard_destroy.notify = + handle_keyboard_destroy; + wl_signal_add(&keyboard->base.events.destroy, + &keyboard_grab->keyboard_destroy); + + wlr_input_method_keyboard_grab_v2_send_modifiers(keyboard_grab, + &keyboard->modifiers); + } + + keyboard_grab->keyboard = keyboard; +}; + +static void im_grab_keyboard(struct wl_client *client, + struct wl_resource *resource, uint32_t keyboard) { + struct wlr_input_method_v2 *input_method = + input_method_from_resource(resource); + if (!input_method) { + return; + } + if (input_method->keyboard_grab) { + // Already grabbed + return; + } + struct wlr_input_method_keyboard_grab_v2 *keyboard_grab = calloc(1, sizeof(*keyboard_grab)); + if (!keyboard_grab) { + wl_client_post_no_memory(client); + return; + } + struct wl_resource *keyboard_grab_resource = wl_resource_create( + client, &zwp_input_method_keyboard_grab_v2_interface, + wl_resource_get_version(resource), keyboard); + if (keyboard_grab_resource == NULL) { + free(keyboard_grab); + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(keyboard_grab_resource, + &keyboard_grab_impl, keyboard_grab, + keyboard_grab_resource_destroy); + keyboard_grab->resource = keyboard_grab_resource; + keyboard_grab->input_method = input_method; + input_method->keyboard_grab = keyboard_grab; + + wl_signal_init(&keyboard_grab->events.destroy); + + wl_signal_emit_mutable(&input_method->events.grab_keyboard, keyboard_grab); +} + +static const struct zwp_input_method_v2_interface input_method_impl = { + .destroy = im_destroy, + .commit = im_commit, + .commit_string = im_commit_string, + .set_preedit_string = im_set_preedit_string, + .delete_surrounding_text = im_delete_surrounding_text, + .get_input_popup_surface = im_get_input_popup_surface, + .grab_keyboard = im_grab_keyboard, +}; + +void wlr_input_method_v2_send_activate( + struct wlr_input_method_v2 *input_method) { + zwp_input_method_v2_send_activate(input_method->resource); + input_method->active = true; +} + +void wlr_input_method_v2_send_deactivate( + struct wlr_input_method_v2 *input_method) { + zwp_input_method_v2_send_deactivate(input_method->resource); + input_method->active = false; +} + +void wlr_input_method_v2_send_surrounding_text( + struct wlr_input_method_v2 *input_method, const char *text, + uint32_t cursor, uint32_t anchor) { + const char *send_text = text; + if (!send_text) { + send_text = ""; + } + zwp_input_method_v2_send_surrounding_text(input_method->resource, send_text, + cursor, anchor); +} + +void wlr_input_method_v2_send_text_change_cause( + struct wlr_input_method_v2 *input_method, uint32_t cause) { + zwp_input_method_v2_send_text_change_cause(input_method->resource, cause); +} + +void wlr_input_method_v2_send_content_type( + struct wlr_input_method_v2 *input_method, + uint32_t hint, uint32_t purpose) { + zwp_input_method_v2_send_content_type(input_method->resource, hint, + purpose); +} + +void wlr_input_method_v2_send_done(struct wlr_input_method_v2 *input_method) { + zwp_input_method_v2_send_done(input_method->resource); + input_method->client_active = input_method->active; + input_method->current_serial++; + struct wlr_input_popup_surface_v2 *popup_surface; + wl_list_for_each(popup_surface, &input_method->popup_surfaces, link) { + popup_surface_update_mapped(popup_surface); + } +} + +void wlr_input_method_v2_send_unavailable( + struct wlr_input_method_v2 *input_method) { + zwp_input_method_v2_send_unavailable(input_method->resource); + struct wl_resource *resource = input_method->resource; + input_method_destroy(input_method); + wl_resource_set_user_data(resource, NULL); +} + +static const struct zwp_input_method_manager_v2_interface + input_method_manager_impl; + +static struct wlr_input_method_manager_v2 *input_method_manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwp_input_method_manager_v2_interface, &input_method_manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void input_method_handle_seat_client_destroy(struct wl_listener *listener, + void *data) { + struct wlr_input_method_v2 *input_method = wl_container_of(listener, + input_method, seat_client_destroy); + wlr_input_method_v2_send_unavailable(input_method); +} + +static void manager_get_input_method(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *seat, + uint32_t input_method_id) { + struct wlr_input_method_manager_v2 *im_manager = + input_method_manager_from_resource(resource); + struct wlr_seat_client *seat_client = wlr_seat_client_from_resource(seat); + + int version = wl_resource_get_version(resource); + struct wl_resource *im_resource = wl_resource_create(client, + &zwp_input_method_v2_interface, version, input_method_id); + if (im_resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(im_resource, &input_method_impl, + NULL, input_method_resource_destroy); + wl_list_init(wl_resource_get_link(im_resource)); + if (seat_client == NULL) { + return; + } + + struct wlr_input_method_v2 *input_method = calloc(1, sizeof(*input_method)); + if (!input_method) { + wl_client_post_no_memory(client); + return; + } + wl_list_init(&input_method->popup_surfaces); + + wl_signal_init(&input_method->events.commit); + wl_signal_init(&input_method->events.new_popup_surface); + wl_signal_init(&input_method->events.grab_keyboard); + wl_signal_init(&input_method->events.destroy); + + input_method->seat_client = seat_client; + input_method->seat = input_method->seat_client->seat; + wl_signal_add(&input_method->seat_client->events.destroy, + &input_method->seat_client_destroy); + input_method->seat_client_destroy.notify = + input_method_handle_seat_client_destroy; + + input_method->resource = im_resource; + wl_resource_set_user_data(im_resource, input_method); + wl_list_insert(&im_manager->input_methods, + wl_resource_get_link(input_method->resource)); + wl_signal_emit_mutable(&im_manager->events.new_input_method, input_method); +} + +static void manager_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwp_input_method_manager_v2_interface + input_method_manager_impl = { + .get_input_method = manager_get_input_method, + .destroy = manager_destroy, +}; + +static void input_method_manager_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_input_method_manager_v2 *im_manager = data; + + struct wl_resource *bound_resource = wl_resource_create(wl_client, + &zwp_input_method_manager_v2_interface, version, id); + if (bound_resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + wl_resource_set_implementation(bound_resource, &input_method_manager_impl, + im_manager, NULL); +} + +static void input_method_manager_v2_destroy(struct wlr_input_method_manager_v2 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, NULL); + + assert(wl_list_empty(&manager->events.new_input_method.listener_list)); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_input_method_manager_v2_destroy(struct wlr_input_method_manager_v2 *manager, + bool destroy_global_safe) { + input_method_manager_v2_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_input_method_manager_v2 *manager = + wl_container_of(listener, manager, display_destroy); + input_method_manager_v2_destroy(manager, false); +} + +struct wlr_input_method_manager_v2 *wlr_input_method_manager_v2_create( + struct wl_display *display) { + struct wlr_input_method_manager_v2 *im_manager = calloc(1, sizeof(*im_manager)); + if (!im_manager) { + return NULL; + } + + wl_signal_init(&im_manager->events.new_input_method); + wl_signal_init(&im_manager->events.destroy); + + wl_list_init(&im_manager->input_methods); + + im_manager->global = wl_global_create(display, + &zwp_input_method_manager_v2_interface, 1, im_manager, + input_method_manager_bind); + if (!im_manager->global) { + free(im_manager); + return NULL; + } + + im_manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &im_manager->display_destroy); + + return im_manager; +} diff --git a/3rdparty/wlroots/types/wlr_keyboard.c b/3rdparty/wlroots/types/wlr_keyboard.c new file mode 100644 index 0000000000..adc705db55 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_keyboard.c @@ -0,0 +1,367 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "interfaces/wlr_input_device.h" +#include "types/wlr_keyboard.h" +#include "util/set.h" +#include "util/shm.h" +#include "util/time.h" + +struct wlr_keyboard *wlr_keyboard_from_input_device( + struct wlr_input_device *input_device) { + assert(input_device->type == WLR_INPUT_DEVICE_KEYBOARD); + return wl_container_of(input_device, (struct wlr_keyboard *)NULL, base); +} + +void keyboard_led_update(struct wlr_keyboard *keyboard) { + if (keyboard->xkb_state == NULL) { + return; + } + + uint32_t leds = 0; + for (uint32_t i = 0; i < WLR_LED_COUNT; ++i) { + if (xkb_state_led_index_is_active(keyboard->xkb_state, + keyboard->led_indexes[i])) { + leds |= (1 << i); + } + } + wlr_keyboard_led_update(keyboard, leds); +} + +/** + * Update the modifier state of the wlr-keyboard. Returns true if the modifier + * state changed. + */ +bool keyboard_modifier_update(struct wlr_keyboard *keyboard) { + if (keyboard->xkb_state == NULL) { + return false; + } + + xkb_mod_mask_t depressed = xkb_state_serialize_mods(keyboard->xkb_state, + XKB_STATE_MODS_DEPRESSED); + xkb_mod_mask_t latched = xkb_state_serialize_mods(keyboard->xkb_state, + XKB_STATE_MODS_LATCHED); + xkb_mod_mask_t locked = xkb_state_serialize_mods(keyboard->xkb_state, + XKB_STATE_MODS_LOCKED); + xkb_layout_index_t group = xkb_state_serialize_layout(keyboard->xkb_state, + XKB_STATE_LAYOUT_EFFECTIVE); + if (depressed == keyboard->modifiers.depressed && + latched == keyboard->modifiers.latched && + locked == keyboard->modifiers.locked && + group == keyboard->modifiers.group) { + return false; + } + + keyboard->modifiers.depressed = depressed; + keyboard->modifiers.latched = latched; + keyboard->modifiers.locked = locked; + keyboard->modifiers.group = group; + + return true; +} + +void keyboard_key_update(struct wlr_keyboard *keyboard, + struct wlr_keyboard_key_event *event) { + if (event->state == WL_KEYBOARD_KEY_STATE_PRESSED) { + set_add(keyboard->keycodes, &keyboard->num_keycodes, + WLR_KEYBOARD_KEYS_CAP, event->keycode); + } + if (event->state == WL_KEYBOARD_KEY_STATE_RELEASED) { + set_remove(keyboard->keycodes, &keyboard->num_keycodes, + WLR_KEYBOARD_KEYS_CAP, event->keycode); + } + + assert(keyboard->num_keycodes <= WLR_KEYBOARD_KEYS_CAP); +} + +void wlr_keyboard_notify_modifiers(struct wlr_keyboard *keyboard, + uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, + uint32_t group) { + if (keyboard->xkb_state == NULL) { + if (keyboard->modifiers.depressed != mods_depressed || + keyboard->modifiers.latched != mods_latched || + keyboard->modifiers.locked != mods_locked || + keyboard->modifiers.group != group) { + keyboard->modifiers.depressed = mods_depressed; + keyboard->modifiers.latched = mods_latched; + keyboard->modifiers.locked = mods_locked; + keyboard->modifiers.group = group; + wl_signal_emit_mutable(&keyboard->events.modifiers, keyboard); + } + return; + } + xkb_state_update_mask(keyboard->xkb_state, mods_depressed, mods_latched, + mods_locked, 0, 0, group); + + bool updated = keyboard_modifier_update(keyboard); + if (updated) { + wl_signal_emit_mutable(&keyboard->events.modifiers, keyboard); + } + + keyboard_led_update(keyboard); +} + +void wlr_keyboard_notify_key(struct wlr_keyboard *keyboard, + struct wlr_keyboard_key_event *event) { + keyboard_key_update(keyboard, event); + wl_signal_emit_mutable(&keyboard->events.key, event); + + if (keyboard->xkb_state == NULL) { + return; + } + + if (event->update_state) { + uint32_t keycode = event->keycode + 8; + xkb_state_update_key(keyboard->xkb_state, keycode, + event->state == WL_KEYBOARD_KEY_STATE_PRESSED ? XKB_KEY_DOWN : XKB_KEY_UP); + } + + bool updated = keyboard_modifier_update(keyboard); + if (updated) { + wl_signal_emit_mutable(&keyboard->events.modifiers, keyboard); + } + + keyboard_led_update(keyboard); +} + +void wlr_keyboard_init(struct wlr_keyboard *kb, + const struct wlr_keyboard_impl *impl, const char *name) { + *kb = (struct wlr_keyboard){ + .impl = impl, + .keymap_fd = -1, + + // Sane defaults + .repeat_info.rate = 25, + .repeat_info.delay = 600, + }; + wlr_input_device_init(&kb->base, WLR_INPUT_DEVICE_KEYBOARD, name); + + wl_signal_init(&kb->events.key); + wl_signal_init(&kb->events.modifiers); + wl_signal_init(&kb->events.keymap); + wl_signal_init(&kb->events.repeat_info); +} + +static void keyboard_unset_keymap(struct wlr_keyboard *kb) { + xkb_keymap_unref(kb->keymap); + kb->keymap = NULL; + xkb_state_unref(kb->xkb_state); + kb->xkb_state = NULL; + free(kb->keymap_string); + kb->keymap_string = NULL; + kb->keymap_size = 0; + if (kb->keymap_fd >= 0) { + close(kb->keymap_fd); + } + kb->keymap_fd = -1; +} + +void wlr_keyboard_finish(struct wlr_keyboard *kb) { + /* Release pressed keys */ + int64_t time_msec = get_current_time_msec(); + while (kb->num_keycodes > 0) { + struct wlr_keyboard_key_event event = { + .time_msec = time_msec, + .keycode = kb->keycodes[kb->num_keycodes - 1], + .update_state = false, + .state = WL_KEYBOARD_KEY_STATE_RELEASED, + }; + wlr_keyboard_notify_key(kb, &event); // updates num_keycodes + } + + wlr_input_device_finish(&kb->base); + + assert(wl_list_empty(&kb->events.key.listener_list)); + assert(wl_list_empty(&kb->events.modifiers.listener_list)); + assert(wl_list_empty(&kb->events.keymap.listener_list)); + assert(wl_list_empty(&kb->events.repeat_info.listener_list)); + + keyboard_unset_keymap(kb); +} + +void wlr_keyboard_led_update(struct wlr_keyboard *kb, uint32_t leds) { + if (kb->leds == leds) { + return; + } + + kb->leds = leds; + + if (kb->impl && kb->impl->led_update) { + kb->impl->led_update(kb, leds); + } +} + +bool wlr_keyboard_set_keymap(struct wlr_keyboard *kb, struct xkb_keymap *keymap) { + if (keymap == NULL) { + keyboard_unset_keymap(kb); + wl_signal_emit_mutable(&kb->events.keymap, kb); + return true; + } + + struct xkb_state *xkb_state = xkb_state_new(keymap); + if (xkb_state == NULL) { + wlr_log(WLR_ERROR, "Failed to create XKB state"); + return false; + } + + char *keymap_str = xkb_keymap_get_as_string(keymap, XKB_KEYMAP_FORMAT_TEXT_V1); + if (keymap_str == NULL) { + wlr_log(WLR_ERROR, "Failed to get string version of keymap"); + goto error_xkb_state; + } + size_t keymap_size = strlen(keymap_str) + 1; + + int rw_fd = -1, ro_fd = -1; + if (!allocate_shm_file_pair(keymap_size, &rw_fd, &ro_fd)) { + wlr_log(WLR_ERROR, "Failed to allocate shm file for keymap"); + goto error_keymap_str; + } + + void *dst = mmap(NULL, keymap_size, PROT_READ | PROT_WRITE, MAP_SHARED, rw_fd, 0); + close(rw_fd); + if (dst == MAP_FAILED) { + wlr_log_errno(WLR_ERROR, "mmap failed"); + close(ro_fd); + goto error_keymap_str; + } + + memcpy(dst, keymap_str, keymap_size); + munmap(dst, keymap_size); + + keyboard_unset_keymap(kb); + kb->keymap = xkb_keymap_ref(keymap); + kb->xkb_state = xkb_state; + kb->keymap_string = keymap_str; + kb->keymap_size = keymap_size; + kb->keymap_fd = ro_fd; + + const char *led_names[WLR_LED_COUNT] = { + XKB_LED_NAME_NUM, + XKB_LED_NAME_CAPS, + XKB_LED_NAME_SCROLL, + XKB_LED_NAME_COMPOSE, + XKB_LED_NAME_KANA, + }; + for (size_t i = 0; i < WLR_LED_COUNT; ++i) { + kb->led_indexes[i] = xkb_map_led_get_index(kb->keymap, led_names[i]); + } + + const char *mod_names[WLR_MODIFIER_COUNT] = { + XKB_MOD_NAME_SHIFT, + XKB_MOD_NAME_CAPS, + XKB_MOD_NAME_CTRL, // "Control" + XKB_MOD_NAME_ALT, // "Mod1" + XKB_MOD_NAME_NUM, // "Mod2" + "Mod3", + XKB_MOD_NAME_LOGO, // "Mod4" + "Mod5", + }; + // TODO: there's also "Ctrl", "Alt"? + for (size_t i = 0; i < WLR_MODIFIER_COUNT; ++i) { + kb->mod_indexes[i] = xkb_map_mod_get_index(kb->keymap, mod_names[i]); + } + + for (size_t i = 0; i < kb->num_keycodes; ++i) { + xkb_keycode_t keycode = kb->keycodes[i] + 8; + xkb_state_update_key(kb->xkb_state, keycode, XKB_KEY_DOWN); + } + + keyboard_modifier_update(kb); + + wl_signal_emit_mutable(&kb->events.keymap, kb); + + return true; + +error_keymap_str: + free(keymap_str); +error_xkb_state: + xkb_state_unref(xkb_state); + return false; +} + +void wlr_keyboard_set_repeat_info(struct wlr_keyboard *kb, int32_t rate, + int32_t delay) { + if (kb->repeat_info.rate == rate && kb->repeat_info.delay == delay) { + return; + } + kb->repeat_info.rate = rate; + kb->repeat_info.delay = delay; + wl_signal_emit_mutable(&kb->events.repeat_info, kb); +} + +uint32_t wlr_keyboard_get_modifiers(struct wlr_keyboard *kb) { + xkb_mod_mask_t mask = kb->modifiers.depressed | kb->modifiers.latched; + uint32_t modifiers = 0; + for (size_t i = 0; i < WLR_MODIFIER_COUNT; ++i) { + if (kb->mod_indexes[i] != XKB_MOD_INVALID && + (mask & (1 << kb->mod_indexes[i]))) { + modifiers |= (1 << i); + } + } + return modifiers; +} + +bool wlr_keyboard_keymaps_match(struct xkb_keymap *km1, + struct xkb_keymap *km2) { + if (!km1 && !km2) { + return true; + } + if (!km1 || !km2) { + return false; + } + char *km1_str = xkb_keymap_get_as_string(km1, XKB_KEYMAP_FORMAT_TEXT_V1); + char *km2_str = xkb_keymap_get_as_string(km2, XKB_KEYMAP_FORMAT_TEXT_V1); + bool result = strcmp(km1_str, km2_str) == 0; + free(km1_str); + free(km2_str); + return result; +} + +uint32_t wlr_keyboard_keysym_to_pointer_button(xkb_keysym_t keysym) { + switch (keysym) { + case XKB_KEY_Pointer_Button1: + return BTN_LEFT; + case XKB_KEY_Pointer_Button2: + return BTN_MIDDLE; + case XKB_KEY_Pointer_Button3: + return BTN_RIGHT; + default: + return 0; + } +} + +void wlr_keyboard_keysym_to_pointer_motion(xkb_keysym_t keysym, int *dx, int *dy) { + *dx = 0; + switch (keysym) { + case XKB_KEY_Pointer_Right: + case XKB_KEY_Pointer_DownRight: + case XKB_KEY_Pointer_UpRight: + *dx = 1; + break; + case XKB_KEY_Pointer_Left: + case XKB_KEY_Pointer_DownLeft: + case XKB_KEY_Pointer_UpLeft: + *dx = -1; + break; + } + + *dy = 0; + switch (keysym) { + case XKB_KEY_Pointer_Down: + case XKB_KEY_Pointer_DownLeft: + case XKB_KEY_Pointer_DownRight: + *dy = 1; + break; + case XKB_KEY_Pointer_Up: + case XKB_KEY_Pointer_UpLeft: + case XKB_KEY_Pointer_UpRight: + *dy = -1; + break; + } +} diff --git a/3rdparty/wlroots/types/wlr_keyboard_group.c b/3rdparty/wlroots/types/wlr_keyboard_group.c new file mode 100644 index 0000000000..6005ba647e --- /dev/null +++ b/3rdparty/wlroots/types/wlr_keyboard_group.c @@ -0,0 +1,328 @@ +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_keyboard.h" +#include "wlr/interfaces/wlr_keyboard.h" +#include "wlr/types/wlr_keyboard.h" +#include "wlr/types/wlr_keyboard_group.h" +#include "wlr/util/log.h" +#include "util/time.h" + +struct keyboard_group_device { + struct wlr_keyboard *keyboard; + struct wl_listener key; + struct wl_listener modifiers; + struct wl_listener keymap; + struct wl_listener repeat_info; + struct wl_listener destroy; + struct wl_list link; // wlr_keyboard_group.devices +}; + +struct keyboard_group_key { + uint32_t keycode; + size_t count; + struct wl_list link; // wlr_keyboard_group.keys +}; + +static void keyboard_set_leds(struct wlr_keyboard *kb, uint32_t leds) { + struct wlr_keyboard_group *group = wlr_keyboard_group_from_wlr_keyboard(kb); + struct keyboard_group_device *device; + wl_list_for_each(device, &group->devices, link) { + wlr_keyboard_led_update(device->keyboard, leds); + } +} + +static const struct wlr_keyboard_impl impl = { + .name = "keyboard-group", + .led_update = keyboard_set_leds +}; + +struct wlr_keyboard_group *wlr_keyboard_group_create(void) { + struct wlr_keyboard_group *group = calloc(1, sizeof(*group)); + if (!group) { + wlr_log(WLR_ERROR, "Failed to allocate wlr_keyboard_group"); + return NULL; + } + + wlr_keyboard_init(&group->keyboard, &impl, "wlr_keyboard_group"); + wl_list_init(&group->devices); + wl_list_init(&group->keys); + + wl_signal_init(&group->events.enter); + wl_signal_init(&group->events.leave); + + return group; +} + +struct wlr_keyboard_group *wlr_keyboard_group_from_wlr_keyboard( + struct wlr_keyboard *keyboard) { + if (keyboard->impl != &impl) { + return NULL; + } + struct wlr_keyboard_group *group = wl_container_of(keyboard, group, keyboard); + return group; +} + +static bool process_key(struct keyboard_group_device *group_device, + struct wlr_keyboard_key_event *event) { + struct wlr_keyboard_group *group = group_device->keyboard->group; + + struct keyboard_group_key *key, *tmp; + wl_list_for_each_safe(key, tmp, &group->keys, link) { + if (key->keycode != event->keycode) { + continue; + } + if (event->state == WL_KEYBOARD_KEY_STATE_PRESSED) { + key->count++; + return false; + } + if (event->state == WL_KEYBOARD_KEY_STATE_RELEASED) { + key->count--; + if (key->count > 0) { + return false; + } + wl_list_remove(&key->link); + free(key); + } + break; + } + + if (event->state == WL_KEYBOARD_KEY_STATE_PRESSED) { + struct keyboard_group_key *key = calloc(1, sizeof(*key)); + if (!key) { + wlr_log(WLR_ERROR, "Failed to allocate keyboard_group_key"); + return false; + } + key->keycode = event->keycode; + key->count = 1; + wl_list_insert(&group->keys, &key->link); + } + + return true; +} + +static void handle_keyboard_key(struct wl_listener *listener, void *data) { + struct keyboard_group_device *group_device = + wl_container_of(listener, group_device, key); + if (process_key(group_device, data)) { + wlr_keyboard_notify_key(&group_device->keyboard->group->keyboard, data); + } +} + +static void handle_keyboard_modifiers(struct wl_listener *listener, + void *data) { + // Sync the effective layout (group modifier) to all keyboards. The rest of + // the modifiers will be derived from the wlr_keyboard_group's key state + struct keyboard_group_device *group_device = + wl_container_of(listener, group_device, modifiers); + struct wlr_keyboard_modifiers mods = group_device->keyboard->modifiers; + + struct keyboard_group_device *device; + wl_list_for_each(device, &group_device->keyboard->group->devices, link) { + if (mods.depressed != device->keyboard->modifiers.depressed || + mods.latched != device->keyboard->modifiers.latched || + mods.locked != device->keyboard->modifiers.locked || + mods.group != device->keyboard->modifiers.group) { + wlr_keyboard_notify_modifiers(device->keyboard, + mods.depressed, mods.latched, mods.locked, mods.group); + return; + } + } + + wlr_keyboard_notify_modifiers(&group_device->keyboard->group->keyboard, + mods.depressed, mods.latched, mods.locked, mods.group); +} + +static void handle_keyboard_keymap(struct wl_listener *listener, void *data) { + struct keyboard_group_device *group_device = + wl_container_of(listener, group_device, keymap); + struct wlr_keyboard *keyboard = group_device->keyboard; + + if (!wlr_keyboard_keymaps_match(keyboard->group->keyboard.keymap, + keyboard->keymap)) { + struct keyboard_group_device *device; + wl_list_for_each(device, &keyboard->group->devices, link) { + if (!wlr_keyboard_keymaps_match(keyboard->keymap, + device->keyboard->keymap)) { + wlr_keyboard_set_keymap(device->keyboard, keyboard->keymap); + return; + } + } + } + + wlr_keyboard_set_keymap(&keyboard->group->keyboard, keyboard->keymap); +} + +static void handle_keyboard_repeat_info(struct wl_listener *listener, + void *data) { + struct keyboard_group_device *group_device = + wl_container_of(listener, group_device, repeat_info); + struct wlr_keyboard *keyboard = group_device->keyboard; + + struct keyboard_group_device *device; + wl_list_for_each(device, &keyboard->group->devices, link) { + struct wlr_keyboard *devkb = device->keyboard; + if (devkb->repeat_info.rate != keyboard->repeat_info.rate || + devkb->repeat_info.delay != keyboard->repeat_info.delay) { + wlr_keyboard_set_repeat_info(devkb, keyboard->repeat_info.rate, + keyboard->repeat_info.delay); + return; + } + } + + wlr_keyboard_set_repeat_info(&keyboard->group->keyboard, + keyboard->repeat_info.rate, keyboard->repeat_info.delay); +} + +static void refresh_state(struct keyboard_group_device *device, + enum wl_keyboard_key_state state) { + struct wl_array keys; + wl_array_init(&keys); + + for (size_t i = 0; i < device->keyboard->num_keycodes; i++) { + struct wlr_keyboard_key_event event = { + .time_msec = get_current_time_msec(), + .keycode = device->keyboard->keycodes[i], + .update_state = true, + .state = state + }; + + // Update the group's key state and determine whether this is a unique + // key that needs to be passed on to the compositor + if (process_key(device, &event)) { + // Update state for wlr_keyboard_group's keyboard + keyboard_key_update(&device->keyboard->group->keyboard, &event); + keyboard_modifier_update(&device->keyboard->group->keyboard); + keyboard_led_update(&device->keyboard->group->keyboard); + + // Add the key to the array + uint32_t *key = wl_array_add(&keys, sizeof(uint32_t)); + *key = event.keycode; + } + } + + // If there are any unique keys, emit the enter/leave event + if (keys.size > 0) { + if (state == WL_KEYBOARD_KEY_STATE_PRESSED) { + wl_signal_emit_mutable(&device->keyboard->group->events.enter, &keys); + } else { + wl_signal_emit_mutable(&device->keyboard->group->events.leave, &keys); + } + } + + wl_array_release(&keys); +} + +static void remove_keyboard_group_device(struct keyboard_group_device *device) { + refresh_state(device, WL_KEYBOARD_KEY_STATE_RELEASED); + device->keyboard->group = NULL; + wl_list_remove(&device->link); + wl_list_remove(&device->key.link); + wl_list_remove(&device->modifiers.link); + wl_list_remove(&device->keymap.link); + wl_list_remove(&device->repeat_info.link); + wl_list_remove(&device->destroy.link); + free(device); +} + +static void handle_keyboard_destroy(struct wl_listener *listener, void *data) { + struct keyboard_group_device *device = + wl_container_of(listener, device, destroy); + remove_keyboard_group_device(device); +} + +bool wlr_keyboard_group_add_keyboard(struct wlr_keyboard_group *group, + struct wlr_keyboard *keyboard) { + if (keyboard->group) { + wlr_log(WLR_ERROR, "A wlr_keyboard can only belong to one group"); + return false; + } + + if (keyboard->impl == &impl) { + wlr_log(WLR_ERROR, "Cannot add a group's keyboard to a group"); + return false; + } + + if (!wlr_keyboard_keymaps_match(group->keyboard.keymap, keyboard->keymap)) { + wlr_log(WLR_ERROR, "Device keymap does not match keyboard group's"); + return false; + } + + struct keyboard_group_device *device = calloc(1, sizeof(*device)); + if (!device) { + wlr_log(WLR_ERROR, "Failed to allocate keyboard_group_device"); + return false; + } + + device->keyboard = keyboard; + keyboard->group = group; + wl_list_insert(&group->devices, &device->link); + + wl_signal_add(&keyboard->events.key, &device->key); + device->key.notify = handle_keyboard_key; + + wl_signal_add(&keyboard->events.modifiers, &device->modifiers); + device->modifiers.notify = handle_keyboard_modifiers; + + wl_signal_add(&keyboard->events.keymap, &device->keymap); + device->keymap.notify = handle_keyboard_keymap; + + wl_signal_add(&keyboard->events.repeat_info, &device->repeat_info); + device->repeat_info.notify = handle_keyboard_repeat_info; + + wl_signal_add(&keyboard->base.events.destroy, &device->destroy); + device->destroy.notify = handle_keyboard_destroy; + + struct wlr_keyboard *group_kb = &group->keyboard; + if (keyboard->modifiers.group != group_kb->modifiers.group) { + wlr_keyboard_notify_modifiers(keyboard, keyboard->modifiers.depressed, + keyboard->modifiers.latched, keyboard->modifiers.locked, + group_kb->modifiers.group); + } + if (keyboard->repeat_info.rate != group_kb->repeat_info.rate || + keyboard->repeat_info.delay != group_kb->repeat_info.delay) { + wlr_keyboard_set_repeat_info(keyboard, group_kb->repeat_info.rate, + group_kb->repeat_info.delay); + } + + refresh_state(device, WL_KEYBOARD_KEY_STATE_PRESSED); + return true; +} + +void wlr_keyboard_group_remove_keyboard(struct wlr_keyboard_group *group, + struct wlr_keyboard *keyboard) { + struct keyboard_group_device *device, *tmp; + wl_list_for_each_safe(device, tmp, &group->devices, link) { + if (device->keyboard == keyboard) { + remove_keyboard_group_device(device); + return; + } + } + wlr_log(WLR_ERROR, "keyboard not found in group"); +} + +void wlr_keyboard_group_destroy(struct wlr_keyboard_group *group) { + struct keyboard_group_device *device, *tmp_device; + wl_list_for_each_safe(device, tmp_device, &group->devices, link) { + remove_keyboard_group_device(device); + } + + // Now group->keys might not be empty if a wlr_keyboard has emitted + // duplicated key presses + struct keyboard_group_key *key, *tmp_key; + wl_list_for_each_safe(key, tmp_key, &group->keys, link) { + wl_list_remove(&key->link); + free(key); + } + + wlr_keyboard_finish(&group->keyboard); + + assert(wl_list_empty(&group->events.enter.listener_list)); + assert(wl_list_empty(&group->events.leave.listener_list)); + + free(group); +} diff --git a/3rdparty/wlroots/types/wlr_keyboard_shortcuts_inhibit_v1.c b/3rdparty/wlroots/types/wlr_keyboard_shortcuts_inhibit_v1.c new file mode 100644 index 0000000000..21405915ec --- /dev/null +++ b/3rdparty/wlroots/types/wlr_keyboard_shortcuts_inhibit_v1.c @@ -0,0 +1,252 @@ +#include +#include +#include +#include +#include +#include "keyboard-shortcuts-inhibit-unstable-v1-protocol.h" +#include "util/global.h" + +static const struct zwp_keyboard_shortcuts_inhibit_manager_v1_interface + keyboard_shortcuts_inhibit_impl; + +static const struct zwp_keyboard_shortcuts_inhibitor_v1_interface + keyboard_shortcuts_inhibitor_impl; + +static struct wlr_keyboard_shortcuts_inhibit_manager_v1 * +wlr_keyboard_shortcuts_inhibit_manager_v1_from_resource( + struct wl_resource *manager_resource) { + assert(wl_resource_instance_of(manager_resource, + &zwp_keyboard_shortcuts_inhibit_manager_v1_interface, + &keyboard_shortcuts_inhibit_impl)); + return wl_resource_get_user_data(manager_resource); +} + +static struct wlr_keyboard_shortcuts_inhibitor_v1 * +wlr_keyboard_shortcuts_inhibitor_v1_from_resource( + struct wl_resource *inhibitor_resource) { + assert(wl_resource_instance_of(inhibitor_resource, + &zwp_keyboard_shortcuts_inhibitor_v1_interface, + &keyboard_shortcuts_inhibitor_impl)); + return wl_resource_get_user_data(inhibitor_resource); +} + +static void keyboard_shortcuts_inhibitor_v1_destroy( + struct wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor) { + if (!inhibitor) { + return; + } + + wl_signal_emit_mutable(&inhibitor->events.destroy, inhibitor); + + assert(wl_list_empty(&inhibitor->events.destroy.listener_list)); + + wl_resource_set_user_data(inhibitor->resource, NULL); + wl_list_remove(&inhibitor->link); + wl_list_remove(&inhibitor->surface_destroy.link); + wl_list_remove(&inhibitor->seat_destroy.link); + free(inhibitor); +} + +static void keyboard_shortcuts_inhibitor_v1_handle_resource_destroy( + struct wl_resource *inhibitor_resource) { + struct wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor = + wlr_keyboard_shortcuts_inhibitor_v1_from_resource( + inhibitor_resource); + keyboard_shortcuts_inhibitor_v1_destroy(inhibitor); +} + +static void keyboard_shortcuts_inhibitor_handle_surface_destroy( + struct wl_listener *listener, void *data) { + struct wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor = + wl_container_of(listener, inhibitor, surface_destroy); + + // be gracious and notify client that destruction of a referenced + // resource makes inhibitor moot + wlr_keyboard_shortcuts_inhibitor_v1_deactivate(inhibitor); + keyboard_shortcuts_inhibitor_v1_destroy(inhibitor); +} + +static void keyboard_shortcuts_inhibitor_handle_seat_destroy( + struct wl_listener *listener, void *data) { + struct wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor = + wl_container_of(listener, inhibitor, seat_destroy); + wlr_keyboard_shortcuts_inhibitor_v1_deactivate(inhibitor); + keyboard_shortcuts_inhibitor_v1_destroy(inhibitor); +} + +static void keyboard_shortcuts_inhibitor_v1_handle_destroy( + struct wl_client *client, + struct wl_resource *inhibitor_resource) { + wl_resource_destroy(inhibitor_resource); +} + +static const struct zwp_keyboard_shortcuts_inhibitor_v1_interface +keyboard_shortcuts_inhibitor_impl = { + .destroy = keyboard_shortcuts_inhibitor_v1_handle_destroy, +}; + +static void manager_handle_inhibit_shortcuts(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + struct wl_resource *surface_resource, + struct wl_resource *seat_resource) { + struct wlr_surface *surface = + wlr_surface_from_resource(surface_resource); + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat_resource); + struct wlr_keyboard_shortcuts_inhibit_manager_v1 *manager = + wlr_keyboard_shortcuts_inhibit_manager_v1_from_resource( + manager_resource); + + uint32_t version = wl_resource_get_version(manager_resource); + struct wl_resource *inhibitor_resource = wl_resource_create(client, + &zwp_keyboard_shortcuts_inhibitor_v1_interface, version, id); + if (inhibitor_resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(inhibitor_resource, + &keyboard_shortcuts_inhibitor_impl, NULL, + keyboard_shortcuts_inhibitor_v1_handle_resource_destroy); + if (seat_client == NULL) { + return; + } + + struct wlr_seat *seat = seat_client->seat; + struct wlr_keyboard_shortcuts_inhibitor_v1 *existing_inhibitor; + wl_list_for_each(existing_inhibitor, &manager->inhibitors, link) { + if (existing_inhibitor->surface != surface || + existing_inhibitor->seat != seat) { + continue; + } + + wl_resource_post_error(manager_resource, + ZWP_KEYBOARD_SHORTCUTS_INHIBIT_MANAGER_V1_ERROR_ALREADY_INHIBITED, + "this surface already has keyboard shortcuts " + "inhibited on this seat"); + return; + } + + struct wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor = calloc(1, sizeof(*inhibitor)); + if (!inhibitor) { + wl_client_post_no_memory(client); + return; + } + + inhibitor->resource = inhibitor_resource; + inhibitor->surface = surface; + inhibitor->seat = seat; + inhibitor->active = false; + + wl_signal_init(&inhibitor->events.destroy); + + inhibitor->surface_destroy.notify = + keyboard_shortcuts_inhibitor_handle_surface_destroy; + wl_signal_add(&surface->events.destroy, &inhibitor->surface_destroy); + + inhibitor->seat_destroy.notify = + keyboard_shortcuts_inhibitor_handle_seat_destroy; + wl_signal_add(&seat->events.destroy, &inhibitor->seat_destroy); + + wl_resource_set_user_data(inhibitor_resource, inhibitor); + wl_list_insert(&manager->inhibitors, &inhibitor->link); + wl_signal_emit_mutable(&manager->events.new_inhibitor, inhibitor); +} + +static void manager_handle_destroy(struct wl_client *client, + struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static const struct zwp_keyboard_shortcuts_inhibit_manager_v1_interface +keyboard_shortcuts_inhibit_impl = { + .destroy = manager_handle_destroy, + .inhibit_shortcuts = manager_handle_inhibit_shortcuts, +}; + +static void keyboard_shortcuts_inhibit_manager_v1_destroy( + struct wlr_keyboard_shortcuts_inhibit_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.new_inhibitor.listener_list)); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_keyboard_shortcuts_inhibit_v1_destroy( + struct wlr_keyboard_shortcuts_inhibit_manager_v1 *manager, bool destroy_global_safe) { + keyboard_shortcuts_inhibit_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_keyboard_shortcuts_inhibit_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + keyboard_shortcuts_inhibit_manager_v1_destroy(manager, false); +} + +static void keyboard_shortcuts_inhibit_bind(struct wl_client *wl_client, + void *data, uint32_t version, uint32_t id) { + struct wlr_keyboard_shortcuts_inhibit_manager_v1 *manager = data; + + struct wl_resource *manager_resource = wl_resource_create(wl_client, + &zwp_keyboard_shortcuts_inhibit_manager_v1_interface, + version, id); + if (!manager_resource) { + wl_client_post_no_memory(wl_client); + return; + } + + wl_resource_set_implementation(manager_resource, + &keyboard_shortcuts_inhibit_impl, manager, NULL); +} + +struct wlr_keyboard_shortcuts_inhibit_manager_v1 * +wlr_keyboard_shortcuts_inhibit_v1_create(struct wl_display *display) { + struct wlr_keyboard_shortcuts_inhibit_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (!manager) { + return NULL; + } + + wl_list_init(&manager->inhibitors); + + wl_signal_init(&manager->events.new_inhibitor); + wl_signal_init(&manager->events.destroy); + + manager->global = wl_global_create(display, + &zwp_keyboard_shortcuts_inhibit_manager_v1_interface, 1, + manager, keyboard_shortcuts_inhibit_bind); + if (!manager->global) { + free(manager); + return NULL; + } + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} + +void wlr_keyboard_shortcuts_inhibitor_v1_activate( + struct wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor) { + if (!inhibitor->active) { + zwp_keyboard_shortcuts_inhibitor_v1_send_active( + inhibitor->resource); + inhibitor->active = true; + } +} + +void wlr_keyboard_shortcuts_inhibitor_v1_deactivate( + struct wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor) { + if (inhibitor->active) { + zwp_keyboard_shortcuts_inhibitor_v1_send_inactive( + inhibitor->resource); + inhibitor->active = false; + } +} diff --git a/3rdparty/wlroots/types/wlr_layer_shell_v1.c b/3rdparty/wlroots/types/wlr_layer_shell_v1.c new file mode 100644 index 0000000000..5466939ebe --- /dev/null +++ b/3rdparty/wlroots/types/wlr_layer_shell_v1.c @@ -0,0 +1,699 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "wlr-layer-shell-unstable-v1-protocol.h" +#include "util/global.h" + +// Note: zwlr_layer_surface_v1 becomes inert on wlr_layer_surface_v1_destroy() + +#define LAYER_SHELL_VERSION 5 + +static void resource_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwlr_layer_shell_v1_interface layer_shell_implementation; +static const struct zwlr_layer_surface_v1_interface layer_surface_implementation; + +static void layer_surface_configure_destroy( + struct wlr_layer_surface_v1_configure *configure) { + if (configure == NULL) { + return; + } + wl_list_remove(&configure->link); + free(configure); +} + +static void layer_surface_reset(struct wlr_layer_surface_v1 *surface) { + surface->configured = false; + surface->initialized = false; + + struct wlr_xdg_popup *popup, *popup_tmp; + wl_list_for_each_safe(popup, popup_tmp, &surface->popups, link) { + wlr_xdg_popup_destroy(popup); + } + + struct wlr_layer_surface_v1_configure *configure, *tmp; + wl_list_for_each_safe(configure, tmp, &surface->configure_list, link) { + layer_surface_configure_destroy(configure); + } +} + +static void layer_surface_destroy(struct wlr_layer_surface_v1 *surface) { + wlr_surface_unmap(surface->surface); + layer_surface_reset(surface); + + wl_signal_emit_mutable(&surface->events.destroy, surface); + + assert(wl_list_empty(&surface->events.destroy.listener_list)); + assert(wl_list_empty(&surface->events.new_popup.listener_list)); + + wlr_surface_synced_finish(&surface->synced); + wl_resource_set_user_data(surface->resource, NULL); + free(surface->namespace); + free(surface); +} + +static struct wlr_layer_shell_v1 *layer_shell_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwlr_layer_shell_v1_interface, + &layer_shell_implementation)); + return wl_resource_get_user_data(resource); +} + +struct wlr_layer_surface_v1 *wlr_layer_surface_v1_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwlr_layer_surface_v1_interface, + &layer_surface_implementation)); + return wl_resource_get_user_data(resource); +} + +static const struct wlr_surface_role layer_surface_role; + +struct wlr_layer_surface_v1 *wlr_layer_surface_v1_try_from_wlr_surface( + struct wlr_surface *surface) { + if (surface->role != &layer_surface_role || surface->role_resource == NULL) { + return NULL; + } + return wlr_layer_surface_v1_from_resource(surface->role_resource); +} + +static void layer_surface_handle_ack_configure(struct wl_client *client, + struct wl_resource *resource, uint32_t serial) { + struct wlr_layer_surface_v1 *surface = + wlr_layer_surface_v1_from_resource(resource); + + if (!surface) { + return; + } + + // First find the ack'ed configure + bool found = false; + struct wlr_layer_surface_v1_configure *configure, *tmp; + wl_list_for_each(configure, &surface->configure_list, link) { + if (configure->serial == serial) { + found = true; + break; + } + } + if (!found) { + wl_resource_post_error(resource, + ZWLR_LAYER_SURFACE_V1_ERROR_INVALID_SURFACE_STATE, + "wrong configure serial: %" PRIu32, serial); + return; + } + // Then remove old configures from the list + wl_list_for_each_safe(configure, tmp, &surface->configure_list, link) { + if (configure->serial == serial) { + break; + } + layer_surface_configure_destroy(configure); + } + + surface->pending.configure_serial = configure->serial; + surface->pending.actual_width = configure->width; + surface->pending.actual_height = configure->height; + + surface->configured = true; + + layer_surface_configure_destroy(configure); +} + +static void layer_surface_handle_set_size(struct wl_client *client, + struct wl_resource *resource, uint32_t width, uint32_t height) { + struct wlr_layer_surface_v1 *surface = + wlr_layer_surface_v1_from_resource(resource); + + if (!surface) { + return; + } + + if (width > INT32_MAX || height > INT32_MAX) { + wl_client_post_implementation_error(client, + "zwlr_layer_surface_v1.set_size: width and height can't be greater than INT32_MAX"); + return; + } + + if (surface->pending.desired_width == width + && surface->pending.desired_height == height) { + return; + } + + surface->pending.committed |= WLR_LAYER_SURFACE_V1_STATE_DESIRED_SIZE; + surface->pending.desired_width = width; + surface->pending.desired_height = height; +} + +static void layer_surface_handle_set_anchor(struct wl_client *client, + struct wl_resource *resource, uint32_t anchor) { + uint32_t version = wl_resource_get_version(resource); + if (!zwlr_layer_surface_v1_anchor_is_valid(anchor, version)) { + wl_resource_post_error(resource, + ZWLR_LAYER_SURFACE_V1_ERROR_INVALID_ANCHOR, + "invalid anchor %" PRIu32, anchor); + } + struct wlr_layer_surface_v1 *surface = + wlr_layer_surface_v1_from_resource(resource); + + if (!surface) { + return; + } + + if (surface->pending.anchor == anchor) { + return; + } + + surface->pending.committed |= WLR_LAYER_SURFACE_V1_STATE_ANCHOR; + surface->pending.anchor = anchor; +} + +static void layer_surface_handle_set_exclusive_zone(struct wl_client *client, + struct wl_resource *resource, int32_t zone) { + struct wlr_layer_surface_v1 *surface = wlr_layer_surface_v1_from_resource(resource); + + if (!surface) { + return; + } + + if (surface->pending.exclusive_zone == zone) { + return; + } + + surface->pending.committed |= WLR_LAYER_SURFACE_V1_STATE_EXCLUSIVE_ZONE; + surface->pending.exclusive_zone = zone; +} + +static void layer_surface_handle_set_margin( + struct wl_client *client, struct wl_resource *resource, + int32_t top, int32_t right, int32_t bottom, int32_t left) { + struct wlr_layer_surface_v1 *surface = + wlr_layer_surface_v1_from_resource(resource); + + if (!surface) { + return; + } + + if (surface->pending.margin.top == top + && surface->pending.margin.right == right + && surface->pending.margin.bottom == bottom + && surface->pending.margin.left == left) { + return; + } + + surface->pending.committed |= WLR_LAYER_SURFACE_V1_STATE_MARGIN; + surface->pending.margin.top = top; + surface->pending.margin.right = right; + surface->pending.margin.bottom = bottom; + surface->pending.margin.left = left; +} + +static void layer_surface_handle_set_keyboard_interactivity( + struct wl_client *client, struct wl_resource *resource, + uint32_t interactive) { + struct wlr_layer_surface_v1 *surface = wlr_layer_surface_v1_from_resource(resource); + + if (!surface) { + return; + } + + surface->pending.committed |= WLR_LAYER_SURFACE_V1_STATE_KEYBOARD_INTERACTIVITY; + uint32_t version = wl_resource_get_version(resource); + if (version < ZWLR_LAYER_SURFACE_V1_KEYBOARD_INTERACTIVITY_ON_DEMAND_SINCE_VERSION) { + surface->pending.keyboard_interactive = !!interactive; + } else { + if (!zwlr_layer_surface_v1_keyboard_interactivity_is_valid(interactive, version)) { + wl_resource_post_error(resource, + ZWLR_LAYER_SURFACE_V1_ERROR_INVALID_KEYBOARD_INTERACTIVITY, + "wrong keyboard interactivity value: %" PRIu32, interactive); + } else { + surface->pending.keyboard_interactive = interactive; + } + } +} + +static void layer_surface_handle_get_popup(struct wl_client *client, + struct wl_resource *layer_resource, + struct wl_resource *popup_resource) { + struct wlr_layer_surface_v1 *parent = + wlr_layer_surface_v1_from_resource(layer_resource); + struct wlr_xdg_popup *popup = + wlr_xdg_popup_from_resource(popup_resource); + + if (!parent) { + return; + } + if (popup->parent != NULL) { + wl_resource_post_error(layer_resource, -1, "xdg_popup already has a parent"); + return; + } + popup->parent = parent->surface; + wl_list_insert(&parent->popups, &popup->link); + wl_signal_emit_mutable(&parent->events.new_popup, popup); +} + +static void layer_surface_set_layer(struct wl_client *client, + struct wl_resource *surface_resource, uint32_t layer) { + struct wlr_layer_surface_v1 *surface = + wlr_layer_surface_v1_from_resource(surface_resource); + if (!surface) { + return; + } + uint32_t version = wl_resource_get_version(surface->resource); + if (!zwlr_layer_shell_v1_layer_is_valid(layer, version)) { + // XXX: this sends a zwlr_layer_shell_v1 error to a zwlr_layer_surface_v1 object + wl_resource_post_error(surface->resource, + ZWLR_LAYER_SHELL_V1_ERROR_INVALID_LAYER, + "Invalid layer %" PRIu32, layer); + return; + } + + if (surface->pending.layer == layer) { + return; + } + + surface->pending.committed |= WLR_LAYER_SURFACE_V1_STATE_LAYER; + surface->pending.layer = layer; +} + +static void layer_surface_set_exclusive_edge(struct wl_client *client, + struct wl_resource *surface_resource, uint32_t edge) { + struct wlr_layer_surface_v1 *surface = + wlr_layer_surface_v1_from_resource(surface_resource); + if (!surface) { + return; + } + uint32_t version = wl_resource_get_version(surface->resource); + if (!zwlr_layer_surface_v1_anchor_is_valid(edge, version)) { + wl_resource_post_error(surface->resource, + ZWLR_LAYER_SURFACE_V1_ERROR_INVALID_EXCLUSIVE_EDGE, + "invalid exclusive edge %" PRIu32, edge); + return; + } + + surface->pending.committed |= WLR_LAYER_SURFACE_V1_STATE_EXCLUSIVE_EDGE; + surface->pending.exclusive_edge = edge; +} + +static const struct zwlr_layer_surface_v1_interface layer_surface_implementation = { + .destroy = resource_handle_destroy, + .ack_configure = layer_surface_handle_ack_configure, + .set_size = layer_surface_handle_set_size, + .set_anchor = layer_surface_handle_set_anchor, + .set_exclusive_zone = layer_surface_handle_set_exclusive_zone, + .set_margin = layer_surface_handle_set_margin, + .set_keyboard_interactivity = layer_surface_handle_set_keyboard_interactivity, + .get_popup = layer_surface_handle_get_popup, + .set_layer = layer_surface_set_layer, + .set_exclusive_edge = layer_surface_set_exclusive_edge, +}; + +uint32_t wlr_layer_surface_v1_configure(struct wlr_layer_surface_v1 *surface, + uint32_t width, uint32_t height) { + assert(surface->initialized); + + struct wl_display *display = + wl_client_get_display(wl_resource_get_client(surface->resource)); + struct wlr_layer_surface_v1_configure *configure = calloc(1, sizeof(*configure)); + if (configure == NULL) { + wl_client_post_no_memory(wl_resource_get_client(surface->resource)); + return surface->pending.configure_serial; + } + wl_list_insert(surface->configure_list.prev, &configure->link); + configure->width = width; + configure->height = height; + configure->serial = wl_display_next_serial(display); + zwlr_layer_surface_v1_send_configure(surface->resource, + configure->serial, configure->width, + configure->height); + return configure->serial; +} + +void wlr_layer_surface_v1_destroy(struct wlr_layer_surface_v1 *surface) { + if (surface == NULL) { + return; + } + zwlr_layer_surface_v1_send_closed(surface->resource); + layer_surface_destroy(surface); +} + +static void layer_surface_role_client_commit(struct wlr_surface *wlr_surface) { + struct wlr_layer_surface_v1 *surface = + wlr_layer_surface_v1_try_from_wlr_surface(wlr_surface); + if (surface == NULL) { + return; + } + + if (wlr_surface_state_has_buffer(&wlr_surface->pending) && !surface->configured) { + wlr_surface_reject_pending(wlr_surface, surface->resource, + ZWLR_LAYER_SHELL_V1_ERROR_ALREADY_CONSTRUCTED, + "layer_surface has never been configured"); + return; + } + + uint32_t anchor = surface->pending.anchor; + + const uint32_t horiz = ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT | + ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT; + if (surface->pending.desired_width == 0 && (anchor & horiz) != horiz) { + wlr_surface_reject_pending(wlr_surface, surface->resource, + ZWLR_LAYER_SURFACE_V1_ERROR_INVALID_SIZE, + "width 0 requested without setting left and right anchors"); + return; + } + + const uint32_t vert = ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP | + ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM; + if (surface->pending.desired_height == 0 && (anchor & vert) != vert) { + wlr_surface_reject_pending(wlr_surface, surface->resource, + ZWLR_LAYER_SURFACE_V1_ERROR_INVALID_SIZE, + "height 0 requested without setting top and bottom anchors"); + return; + } + + if ((anchor & surface->pending.exclusive_edge) != surface->pending.exclusive_edge) { + wlr_surface_reject_pending(wlr_surface, surface->resource, + ZWLR_LAYER_SURFACE_V1_ERROR_INVALID_EXCLUSIVE_EDGE, + "exclusive edge is invalid given the surface anchors"); + } +} + +static void layer_surface_role_commit(struct wlr_surface *wlr_surface) { + struct wlr_layer_surface_v1 *surface = + wlr_layer_surface_v1_try_from_wlr_surface(wlr_surface); + if (surface == NULL) { + return; + } + + if (surface->surface->unmap_commit) { + layer_surface_reset(surface); + + assert(!surface->initialized); + surface->initial_commit = false; + } else { + surface->initial_commit = !surface->initialized; + surface->initialized = true; + } + + if (wlr_surface_has_buffer(wlr_surface)) { + wlr_surface_map(wlr_surface); + } +} + +static void layer_surface_role_destroy(struct wlr_surface *wlr_surface) { + struct wlr_layer_surface_v1 *surface = + wlr_layer_surface_v1_try_from_wlr_surface(wlr_surface); + if (surface == NULL) { + return; + } + + layer_surface_destroy(surface); +} + +static const struct wlr_surface_role layer_surface_role = { + .name = "zwlr_layer_surface_v1", + .client_commit = layer_surface_role_client_commit, + .commit = layer_surface_role_commit, + .destroy = layer_surface_role_destroy, +}; + +static void surface_synced_move_state(void *_dst, void *_src) { + struct wlr_layer_surface_v1_state *dst = _dst, *src = _src; + *dst = *src; + src->committed = 0; +} + +static const struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(struct wlr_layer_surface_v1_state), + .move_state = surface_synced_move_state, +}; + +static void layer_shell_handle_get_layer_surface(struct wl_client *wl_client, + struct wl_resource *client_resource, uint32_t id, + struct wl_resource *surface_resource, + struct wl_resource *output_resource, + uint32_t layer, const char *namespace) { + struct wlr_layer_shell_v1 *shell = + layer_shell_from_resource(client_resource); + struct wlr_surface *wlr_surface = + wlr_surface_from_resource(surface_resource); + + uint32_t version = wl_resource_get_version(client_resource); + if (!zwlr_layer_shell_v1_layer_is_valid(layer, version)) { + wl_resource_post_error(client_resource, + ZWLR_LAYER_SHELL_V1_ERROR_INVALID_LAYER, + "Invalid layer %" PRIu32, layer); + return; + } + + struct wlr_layer_surface_v1 *surface = calloc(1, sizeof(*surface)); + if (surface == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + + if (!wlr_surface_set_role(wlr_surface, &layer_surface_role, + client_resource, ZWLR_LAYER_SHELL_V1_ERROR_ROLE)) { + free(surface); + return; + } + + surface->shell = shell; + surface->surface = wlr_surface; + if (output_resource) { + surface->output = wlr_output_from_resource(output_resource); + } + surface->namespace = strdup(namespace); + if (surface->namespace == NULL) { + goto error_surface; + } + + if (!wlr_surface_synced_init(&surface->synced, wlr_surface, + &surface_synced_impl, &surface->pending, &surface->current)) { + goto error_namespace; + } + + surface->current.layer = surface->pending.layer = layer; + + struct wlr_surface_state *cached; + wl_list_for_each(cached, &wlr_surface->cached, cached_state_link) { + struct wlr_layer_surface_v1_state *state = + wlr_surface_synced_get_state(&surface->synced, cached); + state->layer = layer; + } + + surface->resource = wl_resource_create(wl_client, &zwlr_layer_surface_v1_interface, + wl_resource_get_version(client_resource), id); + if (surface->resource == NULL) { + goto error_synced; + } + + wl_list_init(&surface->configure_list); + wl_list_init(&surface->popups); + + wl_signal_init(&surface->events.destroy); + wl_signal_init(&surface->events.new_popup); + + wlr_log(WLR_DEBUG, "new layer_surface %p (res %p)", + surface, surface->resource); + wl_resource_set_implementation(surface->resource, + &layer_surface_implementation, surface, NULL); + + wlr_surface_set_role_object(wlr_surface, surface->resource); + + wl_signal_emit_mutable(&surface->shell->events.new_surface, surface); + + return; + +error_synced: + wlr_surface_synced_finish(&surface->synced); +error_namespace: + free(surface->namespace); +error_surface: + free(surface); + wl_client_post_no_memory(wl_client); +} + +static const struct zwlr_layer_shell_v1_interface layer_shell_implementation = { + .get_layer_surface = layer_shell_handle_get_layer_surface, + .destroy = resource_handle_destroy, +}; + +static void layer_shell_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_layer_shell_v1 *layer_shell = data; + + struct wl_resource *resource = wl_resource_create( + wl_client, &zwlr_layer_shell_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + wl_resource_set_implementation(resource, + &layer_shell_implementation, layer_shell, NULL); +} + +static void layer_shell_v1_destroy(struct wlr_layer_shell_v1 *layer_shell, + bool destroy_global_safe) { + wl_signal_emit_mutable(&layer_shell->events.destroy, layer_shell); + + assert(wl_list_empty(&layer_shell->events.new_surface.listener_list)); + assert(wl_list_empty(&layer_shell->events.destroy.listener_list)); + + wl_list_remove(&layer_shell->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(layer_shell->global); + } else { + wl_global_destroy(layer_shell->global); + } + free(layer_shell); +} + +void wlr_layer_shell_v1_destroy(struct wlr_layer_shell_v1 *layer_shell, bool destroy_global_safe) { + layer_shell_v1_destroy(layer_shell, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_layer_shell_v1 *layer_shell = + wl_container_of(listener, layer_shell, display_destroy); + layer_shell_v1_destroy(layer_shell, false); +} + +struct wlr_layer_shell_v1 *wlr_layer_shell_v1_create(struct wl_display *display, + uint32_t version) { + assert(version <= LAYER_SHELL_VERSION); + + struct wlr_layer_shell_v1 *layer_shell = calloc(1, sizeof(*layer_shell)); + if (!layer_shell) { + return NULL; + } + + struct wl_global *global = wl_global_create(display, + &zwlr_layer_shell_v1_interface, version, layer_shell, layer_shell_bind); + if (!global) { + free(layer_shell); + return NULL; + } + layer_shell->global = global; + + wl_signal_init(&layer_shell->events.new_surface); + wl_signal_init(&layer_shell->events.destroy); + + layer_shell->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &layer_shell->display_destroy); + + return layer_shell; +} + +struct layer_surface_iterator_data { + wlr_surface_iterator_func_t user_iterator; + void *user_data; + int x, y; +}; + +static void layer_surface_iterator(struct wlr_surface *surface, + int sx, int sy, void *data) { + struct layer_surface_iterator_data *iter_data = data; + iter_data->user_iterator(surface, iter_data->x + sx, iter_data->y + sy, + iter_data->user_data); +} + +void wlr_layer_surface_v1_for_each_surface(struct wlr_layer_surface_v1 *surface, + wlr_surface_iterator_func_t iterator, void *user_data) { + wlr_surface_for_each_surface(surface->surface, iterator, user_data); + wlr_layer_surface_v1_for_each_popup_surface(surface, iterator, user_data); +} + +void wlr_layer_surface_v1_for_each_popup_surface(struct wlr_layer_surface_v1 *surface, + wlr_surface_iterator_func_t iterator, void *user_data) { + struct wlr_xdg_popup *popup; + wl_list_for_each(popup, &surface->popups, link) { + if (!popup->base->surface->mapped) { + continue; + } + + double popup_sx, popup_sy; + popup_sx = popup->current.geometry.x - popup->base->geometry.x; + popup_sy = popup->current.geometry.y - popup->base->geometry.y; + + struct layer_surface_iterator_data data = { + .user_iterator = iterator, + .user_data = user_data, + .x = popup_sx, .y = popup_sy, + }; + + wlr_xdg_surface_for_each_surface(popup->base, + layer_surface_iterator, &data); + } +} + +struct wlr_surface *wlr_layer_surface_v1_surface_at( + struct wlr_layer_surface_v1 *surface, double sx, double sy, + double *sub_x, double *sub_y) { + struct wlr_surface *sub = wlr_layer_surface_v1_popup_surface_at(surface, + sx, sy, sub_x, sub_y); + if (sub != NULL) { + return sub; + } + return wlr_surface_surface_at(surface->surface, sx, sy, sub_x, sub_y); +} + +struct wlr_surface *wlr_layer_surface_v1_popup_surface_at( + struct wlr_layer_surface_v1 *surface, double sx, double sy, + double *sub_x, double *sub_y) { + struct wlr_xdg_popup *popup; + wl_list_for_each(popup, &surface->popups, link) { + if (!popup->base->surface->mapped) { + continue; + } + + double popup_sx, popup_sy; + popup_sx = popup->current.geometry.x - popup->base->geometry.x; + popup_sy = popup->current.geometry.y - popup->base->geometry.y; + + struct wlr_surface *sub = wlr_xdg_surface_surface_at( + popup->base, sx - popup_sx, sy - popup_sy, sub_x, sub_y); + if (sub != NULL) { + return sub; + } + } + + return NULL; +} + +enum wlr_edges wlr_layer_surface_v1_get_exclusive_edge(struct wlr_layer_surface_v1 *surface) { + if (surface->current.exclusive_zone <= 0) { + return WLR_EDGE_NONE; + } + uint32_t anchor = surface->current.anchor; + if (surface->current.exclusive_edge != 0) { + anchor = surface->current.exclusive_edge; + } + switch (anchor) { + case ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP: + case ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT | ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT | + ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP: + return WLR_EDGE_TOP; + case ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM: + case ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT | ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT | + ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM: + return WLR_EDGE_BOTTOM; + case ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT: + case ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP | ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM | + ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT: + return WLR_EDGE_LEFT; + case ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT: + case ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP | ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM | + ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT: + return WLR_EDGE_RIGHT; + default: + return WLR_EDGE_NONE; + } +} diff --git a/3rdparty/wlroots/types/wlr_linux_dmabuf_v1.c b/3rdparty/wlroots/types/wlr_linux_dmabuf_v1.c new file mode 100644 index 0000000000..a311d3e371 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_linux_dmabuf_v1.c @@ -0,0 +1,1192 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "linux-dmabuf-v1-protocol.h" +#include "render/drm_format_set.h" +#include "util/shm.h" + +#if WLR_HAS_DRM_BACKEND +#include +#include "util/global.h" +#endif + +#define LINUX_DMABUF_VERSION 5 + +struct wlr_linux_buffer_params_v1 { + struct wl_resource *resource; + struct wlr_linux_dmabuf_v1 *linux_dmabuf; + struct wlr_dmabuf_attributes attributes; + bool has_modifier; +}; + +struct wlr_linux_dmabuf_feedback_v1_compiled_tranche { + dev_t target_device; + uint32_t flags; // bitfield of enum zwp_linux_dmabuf_feedback_v1_tranche_flags + struct wl_array indices; // uint16_t +}; + +struct wlr_linux_dmabuf_feedback_v1_compiled { + dev_t main_device; + int table_fd; + size_t table_size; + + size_t tranches_len; + struct wlr_linux_dmabuf_feedback_v1_compiled_tranche tranches[]; +}; + +struct wlr_linux_dmabuf_feedback_v1_table_entry { + uint32_t format; + uint32_t pad; // unused + uint64_t modifier; +}; + +static_assert(sizeof(struct wlr_linux_dmabuf_feedback_v1_table_entry) == 16, + "Expected wlr_linux_dmabuf_feedback_v1_table_entry to be tightly packed"); + +struct wlr_linux_dmabuf_v1_surface { + struct wlr_surface *surface; + struct wlr_linux_dmabuf_v1 *linux_dmabuf; + struct wl_list link; // wlr_linux_dmabuf_v1.surfaces + + struct wlr_addon addon; + struct wlr_linux_dmabuf_feedback_v1_compiled *feedback; + + struct wl_list feedback_resources; // wl_resource_get_link +}; + +static void buffer_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wl_buffer_interface wl_buffer_impl = { + .destroy = buffer_handle_destroy, +}; + +static bool buffer_resource_is_instance(struct wl_resource *resource) { + return wl_resource_instance_of(resource, &wl_buffer_interface, + &wl_buffer_impl); +} + +struct wlr_dmabuf_v1_buffer *wlr_dmabuf_v1_buffer_try_from_buffer_resource( + struct wl_resource *resource) { + if (!buffer_resource_is_instance(resource) || + wl_resource_get_user_data(resource) == NULL) { + return NULL; + } + return wl_resource_get_user_data(resource); +} + +static const struct wlr_buffer_impl buffer_impl; + +static struct wlr_dmabuf_v1_buffer *dmabuf_v1_buffer_from_buffer( + struct wlr_buffer *wlr_buffer) { + assert(wlr_buffer->impl == &buffer_impl); + struct wlr_dmabuf_v1_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + return buffer; +} + +static void buffer_destroy(struct wlr_buffer *wlr_buffer) { + struct wlr_dmabuf_v1_buffer *buffer = + dmabuf_v1_buffer_from_buffer(wlr_buffer); + wl_list_remove(&buffer->release.link); + + wlr_buffer_finish(wlr_buffer); + + if (buffer->resource != NULL) { + wl_resource_set_user_data(buffer->resource, NULL); + } + wlr_dmabuf_attributes_finish(&buffer->attributes); + free(buffer); +} + +static bool buffer_get_dmabuf(struct wlr_buffer *wlr_buffer, + struct wlr_dmabuf_attributes *attribs) { + struct wlr_dmabuf_v1_buffer *buffer = + dmabuf_v1_buffer_from_buffer(wlr_buffer); + *attribs = buffer->attributes; + return true; +} + +static const struct wlr_buffer_impl buffer_impl = { + .destroy = buffer_destroy, + .get_dmabuf = buffer_get_dmabuf, +}; + +static void buffer_handle_release(struct wl_listener *listener, void *data) { + struct wlr_dmabuf_v1_buffer *buffer = + wl_container_of(listener, buffer, release); + if (buffer->resource != NULL) { + wl_buffer_send_release(buffer->resource); + } +} + +static const struct zwp_linux_buffer_params_v1_interface buffer_params_impl; + +static struct wlr_linux_buffer_params_v1 *params_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwp_linux_buffer_params_v1_interface, &buffer_params_impl)); + return wl_resource_get_user_data(resource); +} + +static void params_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void params_add(struct wl_client *client, + struct wl_resource *params_resource, int32_t fd, + uint32_t plane_idx, uint32_t offset, uint32_t stride, + uint32_t modifier_hi, uint32_t modifier_lo) { + struct wlr_linux_buffer_params_v1 *params = + params_from_resource(params_resource); + if (!params) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_ALREADY_USED, + "params was already used to create a wl_buffer"); + close(fd); + return; + } + + if (plane_idx >= WLR_DMABUF_MAX_PLANES) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_PLANE_IDX, + "plane index %u > %u", plane_idx, WLR_DMABUF_MAX_PLANES); + close(fd); + return; + } + + if (params->attributes.fd[plane_idx] != -1) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_PLANE_SET, + "a dmabuf with FD %d has already been added for plane %u", + params->attributes.fd[plane_idx], plane_idx); + close(fd); + return; + } + + uint64_t modifier = ((uint64_t)modifier_hi << 32) | modifier_lo; + if (params->has_modifier && modifier != params->attributes.modifier) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_INVALID_FORMAT, + "sent modifier %" PRIu64 " for plane %u, expected" + " modifier %" PRIu64 " like other planes", + modifier, plane_idx, params->attributes.modifier); + close(fd); + return; + } + + params->attributes.modifier = modifier; + params->has_modifier = true; + + params->attributes.fd[plane_idx] = fd; + params->attributes.offset[plane_idx] = offset; + params->attributes.stride[plane_idx] = stride; + params->attributes.n_planes++; +} + +static void buffer_handle_resource_destroy(struct wl_resource *buffer_resource) { + struct wlr_dmabuf_v1_buffer *buffer = + wlr_dmabuf_v1_buffer_try_from_buffer_resource(buffer_resource); + assert(buffer != NULL); + buffer->resource = NULL; + wlr_buffer_drop(&buffer->base); +} + +static bool check_import_dmabuf(struct wlr_dmabuf_attributes *attribs, void *data) { + struct wlr_linux_dmabuf_v1 *linux_dmabuf = data; + + if (linux_dmabuf->main_device_fd < 0) { + return true; + } + + // TODO: check number of planes + for (int i = 0; i < attribs->n_planes; i++) { + uint32_t handle = 0; + if (drmPrimeFDToHandle(linux_dmabuf->main_device_fd, attribs->fd[i], &handle) != 0) { + wlr_log_errno(WLR_ERROR, "Failed to import DMA-BUF FD for plane %d", i); + return false; + } + if (drmCloseBufferHandle(linux_dmabuf->main_device_fd, handle) != 0) { + wlr_log_errno(WLR_ERROR, "Failed to close buffer handle for plane %d", i); + return false; + } + } + return true; +} + +static void params_create_common(struct wl_resource *params_resource, + uint32_t buffer_id, int32_t width, int32_t height, uint32_t format, + uint32_t flags) { + struct wlr_linux_buffer_params_v1 *params = + params_from_resource(params_resource); + if (!params) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_ALREADY_USED, + "params was already used to create a wl_buffer"); + return; + } + + struct wlr_dmabuf_attributes attribs = params->attributes; + struct wlr_linux_dmabuf_v1 *linux_dmabuf = params->linux_dmabuf; + + // Make the params resource inert + wl_resource_set_user_data(params_resource, NULL); + free(params); + + if (!attribs.n_planes) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_INCOMPLETE, + "no dmabuf has been added to the params"); + goto err_out; + } + + if (attribs.fd[0] == -1) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_INCOMPLETE, + "no dmabuf has been added for plane 0"); + goto err_out; + } + + if ((attribs.fd[3] >= 0 || attribs.fd[2] >= 0) && + (attribs.fd[2] == -1 || attribs.fd[1] == -1)) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_INCOMPLETE, + "gap in dmabuf planes"); + goto err_out; + } + + /* reject unknown flags */ + uint32_t version = wl_resource_get_version(params_resource); + if (!zwp_linux_buffer_params_v1_flags_is_valid(flags, version)) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_INVALID_FORMAT, + "Unknown dmabuf flags %"PRIu32, flags); + goto err_out; + } + + if (flags != 0) { + wlr_log(WLR_ERROR, "dmabuf flags aren't supported"); + goto err_failed; + } + + attribs.width = width; + attribs.height = height; + attribs.format = format; + + if (width < 1 || height < 1) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_INVALID_DIMENSIONS, + "invalid width %d or height %d", width, height); + goto err_out; + } + + for (int i = 0; i < attribs.n_planes; i++) { + if ((uint64_t)attribs.offset[i] + + attribs.stride[i] > UINT32_MAX) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_OUT_OF_BOUNDS, + "size overflow for plane %d", i); + goto err_out; + } + + if ((uint64_t)attribs.offset[i] + + (uint64_t)attribs.stride[i] * height > UINT32_MAX) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_OUT_OF_BOUNDS, + "size overflow for plane %d", i); + goto err_out; + } + + off_t size = lseek(attribs.fd[i], 0, SEEK_END); + if (size == -1) { + // Skip checks if kernel does no support seek on buffer + continue; + } + if (attribs.offset[i] > size) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_OUT_OF_BOUNDS, + "invalid offset %" PRIu32 " for plane %d", + attribs.offset[i], i); + goto err_out; + } + + if (attribs.offset[i] + attribs.stride[i] > size || + attribs.stride[i] == 0) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_OUT_OF_BOUNDS, + "invalid stride %" PRIu32 " for plane %d", + attribs.stride[i], i); + goto err_out; + } + + // planes > 0 might be subsampled according to fourcc format + if (i == 0 && attribs.offset[i] + + attribs.stride[i] * height > size) { + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_OUT_OF_BOUNDS, + "invalid buffer stride or height for plane %d", i); + goto err_out; + } + } + + /* Check if dmabuf is usable */ + if (!linux_dmabuf->check_dmabuf_callback(&attribs, + linux_dmabuf->check_dmabuf_callback_data)) { + goto err_failed; + } + + struct wlr_dmabuf_v1_buffer *buffer = calloc(1, sizeof(*buffer)); + if (!buffer) { + wl_resource_post_no_memory(params_resource); + goto err_failed; + } + wlr_buffer_init(&buffer->base, &buffer_impl, attribs.width, attribs.height); + + struct wl_client *client = wl_resource_get_client(params_resource); + buffer->resource = wl_resource_create(client, &wl_buffer_interface, + 1, buffer_id); + if (!buffer->resource) { + wl_resource_post_no_memory(params_resource); + free(buffer); + goto err_failed; + } + wl_resource_set_implementation(buffer->resource, + &wl_buffer_impl, buffer, buffer_handle_resource_destroy); + + buffer->attributes = attribs; + + buffer->release.notify = buffer_handle_release; + wl_signal_add(&buffer->base.events.release, &buffer->release); + + /* send 'created' event when the request is not for an immediate + * import, that is buffer_id is zero */ + if (buffer_id == 0) { + zwp_linux_buffer_params_v1_send_created(params_resource, + buffer->resource); + } + + return; + +err_failed: + if (buffer_id == 0) { + zwp_linux_buffer_params_v1_send_failed(params_resource); + } else { + /* since the behavior is left implementation defined by the + * protocol in case of create_immed failure due to an unknown cause, + * we choose to treat it as a fatal error and immediately kill the + * client instead of creating an invalid handle and waiting for it + * to be used. + */ + wl_resource_post_error(params_resource, + ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_INVALID_WL_BUFFER, + "importing the supplied dmabufs failed"); + } +err_out: + wlr_dmabuf_attributes_finish(&attribs); +} + +static void params_create(struct wl_client *client, + struct wl_resource *params_resource, + int32_t width, int32_t height, uint32_t format, uint32_t flags) { + params_create_common(params_resource, 0, width, height, format, + flags); +} + +static void params_create_immed(struct wl_client *client, + struct wl_resource *params_resource, uint32_t buffer_id, + int32_t width, int32_t height, uint32_t format, uint32_t flags) { + params_create_common(params_resource, buffer_id, width, height, + format, flags); +} + +static const struct zwp_linux_buffer_params_v1_interface buffer_params_impl = { + .destroy = params_destroy, + .add = params_add, + .create = params_create, + .create_immed = params_create_immed, +}; + +static void params_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_linux_buffer_params_v1 *params = params_from_resource(resource); + if (!params) { + return; + } + wlr_dmabuf_attributes_finish(¶ms->attributes); + free(params); +} + +static const struct zwp_linux_dmabuf_v1_interface linux_dmabuf_impl; + +static struct wlr_linux_dmabuf_v1 *linux_dmabuf_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwp_linux_dmabuf_v1_interface, + &linux_dmabuf_impl)); + + struct wlr_linux_dmabuf_v1 *dmabuf = wl_resource_get_user_data(resource); + assert(dmabuf); + return dmabuf; +} + +static void linux_dmabuf_create_params(struct wl_client *client, + struct wl_resource *linux_dmabuf_resource, + uint32_t params_id) { + struct wlr_linux_dmabuf_v1 *linux_dmabuf = + linux_dmabuf_from_resource(linux_dmabuf_resource); + + struct wlr_linux_buffer_params_v1 *params = calloc(1, sizeof(*params)); + if (!params) { + wl_resource_post_no_memory(linux_dmabuf_resource); + return; + } + + for (int i = 0; i < WLR_DMABUF_MAX_PLANES; i++) { + params->attributes.fd[i] = -1; + } + + params->linux_dmabuf = linux_dmabuf; + + uint32_t version = wl_resource_get_version(linux_dmabuf_resource); + params->resource = wl_resource_create(client, + &zwp_linux_buffer_params_v1_interface, version, params_id); + if (!params->resource) { + free(params); + wl_resource_post_no_memory(linux_dmabuf_resource); + return; + } + wl_resource_set_implementation(params->resource, + &buffer_params_impl, params, params_handle_resource_destroy); +} + +static void linux_dmabuf_feedback_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwp_linux_dmabuf_feedback_v1_interface + linux_dmabuf_feedback_impl = { + .destroy = linux_dmabuf_feedback_destroy, +}; + +static ssize_t get_drm_format_set_index(const struct wlr_drm_format_set *set, + uint32_t format, uint64_t modifier) { + bool format_found = false; + const struct wlr_drm_format *fmt; + size_t idx = 0; + for (size_t i = 0; i < set->len; i++) { + fmt = &set->formats[i]; + if (fmt->format == format) { + format_found = true; + break; + } + idx += fmt->len; + } + if (!format_found) { + return -1; + } + + for (size_t i = 0; i < fmt->len; i++) { + if (fmt->modifiers[i] == modifier) { + return idx; + } + idx++; + } + return -1; +} + +static struct wlr_linux_dmabuf_feedback_v1_compiled *feedback_compile( + const struct wlr_linux_dmabuf_feedback_v1 *feedback) { + const struct wlr_linux_dmabuf_feedback_v1_tranche *tranches = feedback->tranches.data; + size_t tranches_len = feedback->tranches.size / sizeof(struct wlr_linux_dmabuf_feedback_v1_tranche); + assert(tranches_len > 0); + + // Make one big format set that contains all formats across all tranches so that we + // can build an index + struct wlr_drm_format_set all_formats = {0}; + for (size_t i = 0; i < tranches_len; i++) { + const struct wlr_linux_dmabuf_feedback_v1_tranche *tranche = &tranches[i]; + if (!wlr_drm_format_set_union(&all_formats, &all_formats, &tranche->formats)) { + wlr_log(WLR_ERROR, "Failed to union scanout formats into one tranche"); + goto err_all_formats; + } + } + + size_t table_len = 0; + for (size_t i = 0; i < all_formats.len; i++) { + const struct wlr_drm_format *fmt = &all_formats.formats[i]; + table_len += fmt->len; + } + assert(table_len > 0); + + size_t table_size = + table_len * sizeof(struct wlr_linux_dmabuf_feedback_v1_table_entry); + int rw_fd, ro_fd; + if (!allocate_shm_file_pair(table_size, &rw_fd, &ro_fd)) { + wlr_log(WLR_ERROR, "Failed to allocate shm file for format table"); + return NULL; + } + + struct wlr_linux_dmabuf_feedback_v1_table_entry *table = + mmap(NULL, table_size, PROT_READ | PROT_WRITE, MAP_SHARED, rw_fd, 0); + if (table == MAP_FAILED) { + wlr_log_errno(WLR_ERROR, "mmap failed"); + close(rw_fd); + close(ro_fd); + goto err_all_formats; + } + + close(rw_fd); + + size_t n = 0; + for (size_t i = 0; i < all_formats.len; i++) { + const struct wlr_drm_format *fmt = &all_formats.formats[i]; + + for (size_t k = 0; k < fmt->len; k++) { + table[n] = (struct wlr_linux_dmabuf_feedback_v1_table_entry){ + .format = fmt->format, + .modifier = fmt->modifiers[k], + }; + n++; + } + } + assert(n == table_len); + + munmap(table, table_size); + + struct wlr_linux_dmabuf_feedback_v1_compiled *compiled = calloc(1, sizeof(*compiled) + + tranches_len * sizeof(struct wlr_linux_dmabuf_feedback_v1_compiled_tranche)); + if (compiled == NULL) { + close(ro_fd); + goto err_all_formats; + } + + compiled->main_device = feedback->main_device; + compiled->tranches_len = tranches_len; + compiled->table_fd = ro_fd; + compiled->table_size = table_size; + + // Build the indices lists for all tranches + for (size_t i = 0; i < tranches_len; i++) { + const struct wlr_linux_dmabuf_feedback_v1_tranche *tranche = &tranches[i]; + struct wlr_linux_dmabuf_feedback_v1_compiled_tranche *compiled_tranche = + &compiled->tranches[i]; + + compiled_tranche->target_device = tranche->target_device; + compiled_tranche->flags = tranche->flags; + + wl_array_init(&compiled_tranche->indices); + if (!wl_array_add(&compiled_tranche->indices, table_len * sizeof(uint16_t))) { + wlr_log(WLR_ERROR, "Failed to allocate tranche indices array"); + goto error_compiled; + } + + n = 0; + uint16_t *indices = compiled_tranche->indices.data; + for (size_t j = 0; j < tranche->formats.len; j++) { + const struct wlr_drm_format *fmt = &tranche->formats.formats[j]; + for (size_t k = 0; k < fmt->len; k++) { + ssize_t index = get_drm_format_set_index( + &all_formats, fmt->format, fmt->modifiers[k]); + if (index < 0) { + wlr_log(WLR_ERROR, "Format 0x%" PRIX32 " and modifier " + "0x%" PRIX64 " are in tranche #%zu but are missing " + "from the fallback tranche", + fmt->format, fmt->modifiers[k], i); + goto error_compiled; + } + indices[n] = index; + n++; + } + } + compiled_tranche->indices.size = n * sizeof(uint16_t); + } + + wlr_drm_format_set_finish(&all_formats); + + return compiled; + +error_compiled: + close(compiled->table_fd); + free(compiled); +err_all_formats: + wlr_drm_format_set_finish(&all_formats); + return NULL; +} + +static void compiled_feedback_destroy( + struct wlr_linux_dmabuf_feedback_v1_compiled *feedback) { + if (feedback == NULL) { + return; + } + for (size_t i = 0; i < feedback->tranches_len; i++) { + wl_array_release(&feedback->tranches[i].indices); + } + close(feedback->table_fd); + free(feedback); +} + +static void feedback_tranche_send( + const struct wlr_linux_dmabuf_feedback_v1_compiled_tranche *tranche, + struct wl_resource *resource) { + struct wl_array dev_array = { + .size = sizeof(tranche->target_device), + .data = (void *)&tranche->target_device, + }; + zwp_linux_dmabuf_feedback_v1_send_tranche_target_device(resource, &dev_array); + zwp_linux_dmabuf_feedback_v1_send_tranche_flags(resource, tranche->flags); + zwp_linux_dmabuf_feedback_v1_send_tranche_formats(resource, + (struct wl_array *)&tranche->indices); + zwp_linux_dmabuf_feedback_v1_send_tranche_done(resource); +} + +static void feedback_send(const struct wlr_linux_dmabuf_feedback_v1_compiled *feedback, + struct wl_resource *resource) { + struct wl_array dev_array = { + .size = sizeof(feedback->main_device), + .data = (void *)&feedback->main_device, + }; + zwp_linux_dmabuf_feedback_v1_send_main_device(resource, &dev_array); + + zwp_linux_dmabuf_feedback_v1_send_format_table(resource, + feedback->table_fd, feedback->table_size); + + for (size_t i = 0; i < feedback->tranches_len; i++) { + feedback_tranche_send(&feedback->tranches[i], resource); + } + + zwp_linux_dmabuf_feedback_v1_send_done(resource); +} + +static void linux_dmabuf_get_default_feedback(struct wl_client *client, + struct wl_resource *resource, uint32_t id) { + struct wlr_linux_dmabuf_v1 *linux_dmabuf = + linux_dmabuf_from_resource(resource); + + uint32_t version = wl_resource_get_version(resource); + struct wl_resource *feedback_resource = wl_resource_create(client, + &zwp_linux_dmabuf_feedback_v1_interface, version, id); + if (feedback_resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(feedback_resource, &linux_dmabuf_feedback_impl, + NULL, NULL); + + feedback_send(linux_dmabuf->default_feedback, feedback_resource); +} + +static void surface_destroy(struct wlr_linux_dmabuf_v1_surface *surface) { + struct wl_resource *resource, *resource_tmp; + wl_resource_for_each_safe(resource, resource_tmp, &surface->feedback_resources) { + struct wl_list *link = wl_resource_get_link(resource); + wl_list_remove(link); + wl_list_init(link); + } + + compiled_feedback_destroy(surface->feedback); + + wlr_addon_finish(&surface->addon); + wl_list_remove(&surface->link); + free(surface); +} + +static void surface_addon_destroy(struct wlr_addon *addon) { + struct wlr_linux_dmabuf_v1_surface *surface = + wl_container_of(addon, surface, addon); + surface_destroy(surface); +} + +static const struct wlr_addon_interface surface_addon_impl = { + .name = "wlr_linux_dmabuf_v1_surface", + .destroy = surface_addon_destroy, +}; + +static struct wlr_linux_dmabuf_v1_surface *surface_get_or_create( + struct wlr_linux_dmabuf_v1 *linux_dmabuf, + struct wlr_surface *wlr_surface) { + struct wlr_addon *addon = + wlr_addon_find(&wlr_surface->addons, linux_dmabuf, &surface_addon_impl); + if (addon != NULL) { + struct wlr_linux_dmabuf_v1_surface *surface = + wl_container_of(addon, surface, addon); + return surface; + } + + struct wlr_linux_dmabuf_v1_surface *surface = calloc(1, sizeof(*surface)); + if (surface == NULL) { + return NULL; + } + + surface->surface = wlr_surface; + surface->linux_dmabuf = linux_dmabuf; + wl_list_init(&surface->feedback_resources); + wlr_addon_init(&surface->addon, &wlr_surface->addons, linux_dmabuf, + &surface_addon_impl); + wl_list_insert(&linux_dmabuf->surfaces, &surface->link); + + return surface; +} + +static const struct wlr_linux_dmabuf_feedback_v1_compiled *surface_get_feedback( + struct wlr_linux_dmabuf_v1_surface *surface) { + if (surface->feedback != NULL) { + return surface->feedback; + } + return surface->linux_dmabuf->default_feedback; +} + +static void surface_feedback_handle_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void linux_dmabuf_get_surface_feedback(struct wl_client *client, + struct wl_resource *resource, uint32_t id, + struct wl_resource *surface_resource) { + struct wlr_linux_dmabuf_v1 *linux_dmabuf = + linux_dmabuf_from_resource(resource); + struct wlr_surface *wlr_surface = wlr_surface_from_resource(surface_resource); + + struct wlr_linux_dmabuf_v1_surface *surface = + surface_get_or_create(linux_dmabuf, wlr_surface); + if (surface == NULL) { + wl_client_post_no_memory(client); + return; + } + + uint32_t version = wl_resource_get_version(resource); + struct wl_resource *feedback_resource = wl_resource_create(client, + &zwp_linux_dmabuf_feedback_v1_interface, version, id); + if (feedback_resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(feedback_resource, &linux_dmabuf_feedback_impl, + NULL, surface_feedback_handle_resource_destroy); + wl_list_insert(&surface->feedback_resources, wl_resource_get_link(feedback_resource)); + + feedback_send(surface_get_feedback(surface), feedback_resource); +} + +static void linux_dmabuf_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwp_linux_dmabuf_v1_interface linux_dmabuf_impl = { + .destroy = linux_dmabuf_destroy, + .create_params = linux_dmabuf_create_params, + .get_default_feedback = linux_dmabuf_get_default_feedback, + .get_surface_feedback = linux_dmabuf_get_surface_feedback, +}; + +static void linux_dmabuf_send_modifiers(struct wl_resource *resource, + const struct wlr_drm_format *fmt) { + if (wl_resource_get_version(resource) < ZWP_LINUX_DMABUF_V1_MODIFIER_SINCE_VERSION) { + if (wlr_drm_format_has(fmt, DRM_FORMAT_MOD_INVALID)) { + zwp_linux_dmabuf_v1_send_format(resource, fmt->format); + } + return; + } + + // In case only INVALID and LINEAR are advertised, send INVALID only due to XWayland: + // https://gitlab.freedesktop.org/xorg/xserver/-/issues/1166 + if (fmt->len == 2 && wlr_drm_format_has(fmt, DRM_FORMAT_MOD_INVALID) + && wlr_drm_format_has(fmt, DRM_FORMAT_MOD_LINEAR)) { + uint64_t mod = DRM_FORMAT_MOD_INVALID; + zwp_linux_dmabuf_v1_send_modifier(resource, fmt->format, + mod >> 32, mod & 0xFFFFFFFF); + return; + } + + for (size_t i = 0; i < fmt->len; i++) { + uint64_t mod = fmt->modifiers[i]; + zwp_linux_dmabuf_v1_send_modifier(resource, fmt->format, + mod >> 32, mod & 0xFFFFFFFF); + } +} + +static void linux_dmabuf_send_formats(struct wlr_linux_dmabuf_v1 *linux_dmabuf, + struct wl_resource *resource) { + for (size_t i = 0; i < linux_dmabuf->default_formats.len; i++) { + const struct wlr_drm_format *fmt = &linux_dmabuf->default_formats.formats[i]; + linux_dmabuf_send_modifiers(resource, fmt); + } +} + +static void linux_dmabuf_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_linux_dmabuf_v1 *linux_dmabuf = data; + + struct wl_resource *resource = wl_resource_create(client, + &zwp_linux_dmabuf_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &linux_dmabuf_impl, + linux_dmabuf, NULL); + wl_list_init(wl_resource_get_link(resource)); + if (linux_dmabuf == NULL) { + return; + } + + + if (version < ZWP_LINUX_DMABUF_V1_GET_DEFAULT_FEEDBACK_SINCE_VERSION) { + linux_dmabuf_send_formats(linux_dmabuf, resource); + } +} + +static struct wlr_buffer *buffer_from_resource(struct wl_resource *resource) { + struct wlr_dmabuf_v1_buffer *buffer = + wlr_dmabuf_v1_buffer_try_from_buffer_resource(resource); + assert(buffer != NULL); + return &buffer->base; +} + +static const struct wlr_buffer_resource_interface buffer_resource_interface = { + .name = "wlr_dmabuf_v1_buffer", + .is_instance = buffer_resource_is_instance, + .from_resource = buffer_from_resource, +}; + +static void linux_dmabuf_v1_destroy(struct wlr_linux_dmabuf_v1 *linux_dmabuf, + bool destroy_global_safe) { + wl_signal_emit_mutable(&linux_dmabuf->events.destroy, linux_dmabuf); + + assert(wl_list_empty(&linux_dmabuf->events.destroy.listener_list)); + + struct wlr_linux_dmabuf_v1_surface *surface, *surface_tmp; + wl_list_for_each_safe(surface, surface_tmp, &linux_dmabuf->surfaces, link) { + surface_destroy(surface); + } + + compiled_feedback_destroy(linux_dmabuf->default_feedback); + wlr_drm_format_set_finish(&linux_dmabuf->default_formats); + if (linux_dmabuf->main_device_fd >= 0) { + close(linux_dmabuf->main_device_fd); + } + + wl_list_remove(&linux_dmabuf->display_destroy.link); + + if (destroy_global_safe) { + wlr_global_destroy_safe(linux_dmabuf->global); + } else { + wl_global_destroy(linux_dmabuf->global); + } + free(linux_dmabuf); +} + +void wlr_linux_dmabuf_v1_destroy(struct wlr_linux_dmabuf_v1 *linux_dmabuf, + bool destroy_global_safe) { + linux_dmabuf_v1_destroy(linux_dmabuf, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_linux_dmabuf_v1 *linux_dmabuf = + wl_container_of(listener, linux_dmabuf, display_destroy); + linux_dmabuf_v1_destroy(linux_dmabuf, false); +} + +static bool set_default_feedback(struct wlr_linux_dmabuf_v1 *linux_dmabuf, + const struct wlr_linux_dmabuf_feedback_v1 *feedback) { + struct wlr_linux_dmabuf_feedback_v1_compiled *compiled = feedback_compile(feedback); + if (compiled == NULL) { + return false; + } + + drmDevice *device = NULL; + if (drmGetDeviceFromDevId(feedback->main_device, 0, &device) != 0) { + wlr_log_errno(WLR_ERROR, "drmGetDeviceFromDevId failed"); + goto error_compiled; + } + + int main_device_fd = -1; + if (device->available_nodes & (1 << DRM_NODE_RENDER)) { + const char *name = device->nodes[DRM_NODE_RENDER]; + main_device_fd = open(name, O_RDWR | O_CLOEXEC); + drmFreeDevice(&device); + if (main_device_fd < 0) { + wlr_log_errno(WLR_ERROR, "Failed to open DRM device %s", name); + goto error_compiled; + } + } else { + // Likely a split display/render setup. Unfortunately we have no way to + // get back the proper render node used by the renderer under-the-hood. + // TODO: drop once mesa!24825 is widespread + assert(device->available_nodes & (1 << DRM_NODE_PRIMARY)); + wlr_log(WLR_DEBUG, "DRM device %s has no render node, " + "skipping DMA-BUF import checks", device->nodes[DRM_NODE_PRIMARY]); + drmFreeDevice(&device); + } + + size_t tranches_len = + feedback->tranches.size / sizeof(struct wlr_linux_dmabuf_feedback_v1_tranche); + const struct wlr_linux_dmabuf_feedback_v1_tranche *tranches = feedback->tranches.data; + struct wlr_drm_format_set formats = {0}; + for (size_t i = 0; i < tranches_len; i++) { + const struct wlr_linux_dmabuf_feedback_v1_tranche *tranche = &tranches[i]; + + if (!wlr_drm_format_set_union(&formats, &formats, &tranche->formats)) { + goto error_formats; + } + } + + compiled_feedback_destroy(linux_dmabuf->default_feedback); + linux_dmabuf->default_feedback = compiled; + + if (linux_dmabuf->main_device_fd >= 0) { + close(linux_dmabuf->main_device_fd); + } + linux_dmabuf->main_device_fd = main_device_fd; + + wlr_drm_format_set_finish(&linux_dmabuf->default_formats); + linux_dmabuf->default_formats = formats; + + return true; + +error_formats: + wlr_drm_format_set_finish(&formats); +error_compiled: + compiled_feedback_destroy(compiled); + return false; +} + +struct wlr_linux_dmabuf_v1 *wlr_linux_dmabuf_v1_create(struct wl_display *display, + uint32_t version, const struct wlr_linux_dmabuf_feedback_v1 *default_feedback) { + assert(version <= LINUX_DMABUF_VERSION); + + struct wlr_linux_dmabuf_v1 *linux_dmabuf = calloc(1, sizeof(*linux_dmabuf)); + if (linux_dmabuf == NULL) { + wlr_log(WLR_ERROR, "could not create simple dmabuf manager"); + return NULL; + } + linux_dmabuf->main_device_fd = -1; + + wl_list_init(&linux_dmabuf->surfaces); + + wl_signal_init(&linux_dmabuf->events.destroy); + + linux_dmabuf->global = wl_global_create(display, &zwp_linux_dmabuf_v1_interface, + version, linux_dmabuf, linux_dmabuf_bind); + if (!linux_dmabuf->global) { + wlr_log(WLR_ERROR, "could not create linux dmabuf v1 wl global"); + goto error_linux_dmabuf; + } + + if (!set_default_feedback(linux_dmabuf, default_feedback)) { + goto error_global; + } + + linux_dmabuf->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &linux_dmabuf->display_destroy); + + wlr_linux_dmabuf_v1_set_check_dmabuf_callback(linux_dmabuf, + check_import_dmabuf, linux_dmabuf); + + wlr_buffer_register_resource_interface(&buffer_resource_interface); + + return linux_dmabuf; + +error_global: + wl_global_destroy(linux_dmabuf->global); +error_linux_dmabuf: + free(linux_dmabuf); + return NULL; +} + +struct wlr_linux_dmabuf_v1 *wlr_linux_dmabuf_v1_create_with_renderer(struct wl_display *display, + uint32_t version, struct wlr_renderer *renderer) { + const struct wlr_linux_dmabuf_feedback_v1_init_options options = { + .main_renderer = renderer, + }; + struct wlr_linux_dmabuf_feedback_v1 feedback = {0}; + if (!wlr_linux_dmabuf_feedback_v1_init_with_options(&feedback, &options)) { + return NULL; + } + struct wlr_linux_dmabuf_v1 *linux_dmabuf = + wlr_linux_dmabuf_v1_create(display, version, &feedback); + wlr_linux_dmabuf_feedback_v1_finish(&feedback); + return linux_dmabuf; +} + +void wlr_linux_dmabuf_v1_set_check_dmabuf_callback(struct wlr_linux_dmabuf_v1 *linux_dmabuf, + bool (*callback)(struct wlr_dmabuf_attributes *attribs, void *data), void *data) { + assert(callback); + linux_dmabuf->check_dmabuf_callback = callback; + linux_dmabuf->check_dmabuf_callback_data = data; +} + +bool wlr_linux_dmabuf_v1_set_surface_feedback( + struct wlr_linux_dmabuf_v1 *linux_dmabuf, + struct wlr_surface *wlr_surface, + const struct wlr_linux_dmabuf_feedback_v1 *feedback) { + struct wlr_linux_dmabuf_v1_surface *surface = + surface_get_or_create(linux_dmabuf, wlr_surface); + if (surface == NULL) { + return false; + } + + struct wlr_linux_dmabuf_feedback_v1_compiled *compiled = NULL; + if (feedback != NULL) { + compiled = feedback_compile(feedback); + if (compiled == NULL) { + return false; + } + } + + compiled_feedback_destroy(surface->feedback); + surface->feedback = compiled; + + struct wl_resource *resource; + wl_resource_for_each(resource, &surface->feedback_resources) { + feedback_send(surface_get_feedback(surface), resource); + } + + return true; +} + +struct wlr_linux_dmabuf_feedback_v1_tranche *wlr_linux_dmabuf_feedback_add_tranche( + struct wlr_linux_dmabuf_feedback_v1 *feedback) { + struct wlr_linux_dmabuf_feedback_v1_tranche *tranche = + wl_array_add(&feedback->tranches, sizeof(*tranche)); + if (tranche == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + *tranche = (struct wlr_linux_dmabuf_feedback_v1_tranche){0}; + return tranche; +} + +void wlr_linux_dmabuf_feedback_v1_finish(struct wlr_linux_dmabuf_feedback_v1 *feedback) { + struct wlr_linux_dmabuf_feedback_v1_tranche *tranche; + wl_array_for_each(tranche, &feedback->tranches) { + wlr_drm_format_set_finish(&tranche->formats); + } + wl_array_release(&feedback->tranches); +} + +static bool devid_from_fd(int fd, dev_t *devid) { + struct stat stat; + if (fstat(fd, &stat) != 0) { + wlr_log_errno(WLR_ERROR, "fstat failed"); + return false; + } + *devid = stat.st_rdev; + return true; +} + +static bool is_secondary_drm_backend(struct wlr_backend *backend) { +#if WLR_HAS_DRM_BACKEND + return wlr_backend_is_drm(backend) && + wlr_drm_backend_get_parent(backend) != NULL; +#else + return false; +#endif +} + +bool wlr_linux_dmabuf_feedback_v1_init_with_options(struct wlr_linux_dmabuf_feedback_v1 *feedback, + const struct wlr_linux_dmabuf_feedback_v1_init_options *options) { + assert(options->main_renderer != NULL); + assert(options->scanout_primary_output == NULL || + options->output_layer_feedback_event == NULL); + + *feedback = (struct wlr_linux_dmabuf_feedback_v1){0}; + + int renderer_drm_fd = wlr_renderer_get_drm_fd(options->main_renderer); + if (renderer_drm_fd < 0) { + wlr_log(WLR_ERROR, "Failed to get renderer DRM FD"); + goto error; + } + dev_t renderer_dev; + if (!devid_from_fd(renderer_drm_fd, &renderer_dev)) { + goto error; + } + + feedback->main_device = renderer_dev; + + const struct wlr_drm_format_set *renderer_formats = + wlr_renderer_get_texture_formats(options->main_renderer, WLR_BUFFER_CAP_DMABUF); + if (renderer_formats == NULL) { + wlr_log(WLR_ERROR, "Failed to get renderer DMA-BUF texture formats"); + goto error; + } + + if (options->output_layer_feedback_event != NULL) { + const struct wlr_output_layer_feedback_event *event = options->output_layer_feedback_event; + + struct wlr_linux_dmabuf_feedback_v1_tranche *tranche = + wlr_linux_dmabuf_feedback_add_tranche(feedback); + if (tranche == NULL) { + goto error; + } + + tranche->target_device = event->target_device; + tranche->flags = ZWP_LINUX_DMABUF_FEEDBACK_V1_TRANCHE_FLAGS_SCANOUT; + if (!wlr_drm_format_set_intersect(&tranche->formats, event->formats, renderer_formats)) { + wlr_log(WLR_ERROR, "Failed to intersect renderer and scanout formats"); + goto error; + } + } else if (options->scanout_primary_output != NULL && + !is_secondary_drm_backend(options->scanout_primary_output->backend)) { + int backend_drm_fd = wlr_backend_get_drm_fd(options->scanout_primary_output->backend); + if (backend_drm_fd < 0) { + wlr_log(WLR_ERROR, "Failed to get backend DRM FD"); + goto error; + } + dev_t backend_dev; + if (!devid_from_fd(backend_drm_fd, &backend_dev)) { + goto error; + } + + const struct wlr_drm_format_set *scanout_formats = + wlr_output_get_primary_formats(options->scanout_primary_output, WLR_BUFFER_CAP_DMABUF); + if (scanout_formats == NULL) { + wlr_log(WLR_ERROR, "Failed to get output primary DMA-BUF formats"); + goto error; + } + + struct wlr_linux_dmabuf_feedback_v1_tranche *tranche = + wlr_linux_dmabuf_feedback_add_tranche(feedback); + if (tranche == NULL) { + goto error; + } + + tranche->target_device = backend_dev; + tranche->flags = ZWP_LINUX_DMABUF_FEEDBACK_V1_TRANCHE_FLAGS_SCANOUT; + if (!wlr_drm_format_set_intersect(&tranche->formats, scanout_formats, renderer_formats)) { + wlr_log(WLR_ERROR, "Failed to intersect renderer and scanout formats"); + goto error; + } + } + + struct wlr_linux_dmabuf_feedback_v1_tranche *tranche = + wlr_linux_dmabuf_feedback_add_tranche(feedback); + if (tranche == NULL) { + goto error; + } + + tranche->target_device = renderer_dev; + if (!wlr_drm_format_set_copy(&tranche->formats, renderer_formats)) { + goto error; + } + + return true; + +error: + wlr_linux_dmabuf_feedback_v1_finish(feedback); + return false; +} diff --git a/3rdparty/wlroots/types/wlr_linux_drm_syncobj_v1.c b/3rdparty/wlroots/types/wlr_linux_drm_syncobj_v1.c new file mode 100644 index 0000000000..4aefc45e7b --- /dev/null +++ b/3rdparty/wlroots/types/wlr_linux_drm_syncobj_v1.c @@ -0,0 +1,559 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "config.h" +#include "linux-drm-syncobj-v1-protocol.h" +#include "render/drm_syncobj_merger.h" +#include "util/global.h" + +#define LINUX_DRM_SYNCOBJ_V1_VERSION 1 + +struct wlr_linux_drm_syncobj_surface_v1 { + struct wl_resource *resource; + struct wlr_surface *surface; + struct wlr_linux_drm_syncobj_surface_v1_state pending, current; + + struct wlr_addon addon; + struct wlr_surface_synced synced; + + struct wl_listener client_commit; +}; + +struct wlr_linux_drm_syncobj_surface_v1_commit { + struct wlr_surface *surface; + struct wlr_drm_syncobj_timeline_waiter waiter; + uint32_t cached_seq; + + struct wl_listener surface_destroy; +}; + +static const struct wp_linux_drm_syncobj_manager_v1_interface manager_impl; +static const struct wp_linux_drm_syncobj_timeline_v1_interface timeline_impl; +static const struct wp_linux_drm_syncobj_surface_v1_interface surface_impl; + +static struct wlr_linux_drm_syncobj_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_linux_drm_syncobj_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_drm_syncobj_timeline *timeline_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_linux_drm_syncobj_timeline_v1_interface, &timeline_impl)); + return wl_resource_get_user_data(resource); +} + +// Returns NULL if the syncobj surface is inert +static struct wlr_linux_drm_syncobj_surface_v1 *surface_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_linux_drm_syncobj_surface_v1_interface, &surface_impl)); + return wl_resource_get_user_data(resource); +} + +static void timeline_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_drm_syncobj_timeline *timeline = timeline_from_resource(resource); + wlr_drm_syncobj_timeline_unref(timeline); +} + +static void timeline_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wp_linux_drm_syncobj_timeline_v1_interface timeline_impl = { + .destroy = timeline_handle_destroy, +}; + +static void surface_destroy(struct wlr_linux_drm_syncobj_surface_v1 *surface) { + if (surface == NULL) { + return; + } + wl_list_remove(&surface->client_commit.link); + wlr_addon_finish(&surface->addon); + wlr_surface_synced_finish(&surface->synced); + wl_resource_set_user_data(surface->resource, NULL); + free(surface); +} + +static void surface_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void surface_handle_set_acquire_point(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *timeline_resource, + uint32_t point_hi, uint32_t point_lo) { + struct wlr_linux_drm_syncobj_surface_v1 *surface = + surface_from_resource(resource); + if (surface == NULL) { + wl_resource_post_error(resource, + WP_LINUX_DRM_SYNCOBJ_SURFACE_V1_ERROR_NO_SURFACE, + "The surface has been destroyed"); + return; + } + + struct wlr_drm_syncobj_timeline *timeline = + timeline_from_resource(timeline_resource); + uint64_t point = (uint64_t)point_hi << 32 | point_lo; + + wlr_drm_syncobj_timeline_unref(surface->pending.acquire_timeline); + surface->pending.acquire_timeline = wlr_drm_syncobj_timeline_ref(timeline); + surface->pending.acquire_point = point; +} + +static void surface_handle_set_release_point(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *timeline_resource, + uint32_t point_hi, uint32_t point_lo) { + struct wlr_linux_drm_syncobj_surface_v1 *surface = + surface_from_resource(resource); + if (surface == NULL) { + wl_resource_post_error(resource, + WP_LINUX_DRM_SYNCOBJ_SURFACE_V1_ERROR_NO_SURFACE, + "The surface has been destroyed"); + return; + } + + struct wlr_drm_syncobj_timeline *timeline = + timeline_from_resource(timeline_resource); + uint64_t point = (uint64_t)point_hi << 32 | point_lo; + + wlr_drm_syncobj_timeline_unref(surface->pending.release_timeline); + surface->pending.release_timeline = wlr_drm_syncobj_timeline_ref(timeline); + surface->pending.release_point = point; +} + +static const struct wp_linux_drm_syncobj_surface_v1_interface surface_impl = { + .destroy = surface_handle_destroy, + .set_acquire_point = surface_handle_set_acquire_point, + .set_release_point = surface_handle_set_release_point, +}; + +static void surface_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_linux_drm_syncobj_surface_v1 *surface = + surface_from_resource(resource); + surface_destroy(surface); +} + +static void surface_addon_handle_surface_destroy(struct wlr_addon *addon) { + struct wlr_linux_drm_syncobj_surface_v1 *surface = + wl_container_of(addon, surface, addon); + surface_destroy(surface); +} + +static const struct wlr_addon_interface surface_addon_impl = { + .name = "wp_linux_drm_syncobj_surface_v1", + .destroy = surface_addon_handle_surface_destroy, +}; + +static void surface_synced_finish_state(void *_state) { + struct wlr_linux_drm_syncobj_surface_v1_state *state = _state; + wlr_drm_syncobj_timeline_unref(state->acquire_timeline); + wlr_drm_syncobj_timeline_unref(state->release_timeline); + wlr_drm_syncobj_merger_unref(state->release_merger); +} + +static void surface_synced_move_state(void *_dst, void *_src) { + struct wlr_linux_drm_syncobj_surface_v1_state *dst = _dst, *src = _src; + if (src->acquire_timeline == NULL) { + // ignore commits that did not attach a buffer + return; + } + surface_synced_finish_state(dst); + *dst = *src; + dst->committed = true; + *src = (struct wlr_linux_drm_syncobj_surface_v1_state){0}; +} + +static void surface_synced_commit(struct wlr_surface_synced *synced) { + struct wlr_linux_drm_syncobj_surface_v1 *surface = wl_container_of(synced, surface, synced); + + if (!surface->current.committed) { + return; + } + + surface->current.release_merger = wlr_drm_syncobj_merger_create( + surface->current.release_timeline, surface->current.release_point); + surface->current.committed = false; +} + + +static const struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(struct wlr_linux_drm_syncobj_surface_v1_state), + .finish_state = surface_synced_finish_state, + .move_state = surface_synced_move_state, + .commit = surface_synced_commit, +}; + +static void manager_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static struct wlr_linux_drm_syncobj_surface_v1 *surface_from_wlr_surface( + struct wlr_surface *wlr_surface) { + struct wlr_addon *addon = + wlr_addon_find(&wlr_surface->addons, NULL, &surface_addon_impl); + if (addon == NULL) { + return NULL; + } + struct wlr_linux_drm_syncobj_surface_v1 *surface = + wl_container_of(addon, surface, addon); + return surface; +} + +static void surface_commit_destroy(struct wlr_linux_drm_syncobj_surface_v1_commit *commit) { + wlr_surface_unlock_cached(commit->surface, commit->cached_seq); + wl_list_remove(&commit->surface_destroy.link); + wlr_drm_syncobj_timeline_waiter_finish(&commit->waiter); + free(commit); +} + +static void surface_commit_handle_waiter_ready(struct wlr_drm_syncobj_timeline_waiter *waiter) { + struct wlr_linux_drm_syncobj_surface_v1_commit *commit = + wl_container_of(waiter, commit, waiter); + surface_commit_destroy(commit); +} + +static void surface_commit_handle_surface_destroy(struct wl_listener *listener, + void *data) { + struct wlr_linux_drm_syncobj_surface_v1_commit *commit = + wl_container_of(listener, commit, surface_destroy); + surface_commit_destroy(commit); +} + +// Block the surface commit until the fence materializes +static bool lock_surface_commit(struct wlr_linux_drm_syncobj_surface_v1 *surface, + struct wlr_drm_syncobj_timeline *timeline, uint64_t point) { + uint32_t flags = DRM_SYNCOBJ_WAIT_FLAGS_WAIT_AVAILABLE; + + bool already_materialized = false; + if (!wlr_drm_syncobj_timeline_check(timeline, point, flags, &already_materialized)) { + return false; + } else if (already_materialized) { + return true; + } + + struct wlr_linux_drm_syncobj_surface_v1_commit *commit = calloc(1, sizeof(*commit)); + if (commit == NULL) { + return false; + } + + struct wl_client *client = wl_resource_get_client(surface->resource); + struct wl_display *display = wl_client_get_display(client); + struct wl_event_loop *loop = wl_display_get_event_loop(display); + if (!wlr_drm_syncobj_timeline_waiter_init(&commit->waiter, timeline, point, + flags, loop, surface_commit_handle_waiter_ready)) { + free(commit); + return false; + } + + commit->surface = surface->surface; + commit->cached_seq = wlr_surface_lock_pending(surface->surface); + + commit->surface_destroy.notify = surface_commit_handle_surface_destroy; + wl_signal_add(&surface->surface->events.destroy, &commit->surface_destroy); + + return true; +} + +static void surface_handle_client_commit(struct wl_listener *listener, + void *data) { + struct wlr_linux_drm_syncobj_surface_v1 *surface = + wl_container_of(listener, surface, client_commit); + + if (surface->pending.acquire_timeline != NULL && + surface->surface->pending.buffer == NULL) { + wlr_surface_reject_pending(surface->surface, surface->resource, + WP_LINUX_DRM_SYNCOBJ_SURFACE_V1_ERROR_NO_BUFFER, + "Acquire point set but no buffer attached"); + return; + } + if (surface->pending.release_timeline != NULL && + surface->surface->pending.buffer == NULL) { + wlr_surface_reject_pending(surface->surface, surface->resource, + WP_LINUX_DRM_SYNCOBJ_SURFACE_V1_ERROR_NO_BUFFER, + "Release point set but no buffer attached"); + return; + } + + if (surface->pending.acquire_timeline == NULL && + surface->surface->pending.buffer != NULL) { + wlr_surface_reject_pending(surface->surface, surface->resource, + WP_LINUX_DRM_SYNCOBJ_SURFACE_V1_ERROR_NO_ACQUIRE_POINT, + "Buffer attached but no acquire point set"); + return; + } + if (surface->pending.release_timeline == NULL && + surface->surface->pending.buffer != NULL) { + wlr_surface_reject_pending(surface->surface, surface->resource, + WP_LINUX_DRM_SYNCOBJ_SURFACE_V1_ERROR_NO_RELEASE_POINT, + "Buffer attached but no release point set"); + return; + } + + if (surface->pending.acquire_timeline != NULL && + surface->pending.release_timeline != NULL && + surface->pending.acquire_timeline == surface->pending.release_timeline && + surface->pending.acquire_point >= surface->pending.release_point) { + wlr_surface_reject_pending(surface->surface, surface->resource, + WP_LINUX_DRM_SYNCOBJ_SURFACE_V1_ERROR_CONFLICTING_POINTS, + "Acquire and release points conflict"); + return; + } + + if (surface->pending.acquire_timeline != NULL && !lock_surface_commit( + surface, surface->pending.acquire_timeline, surface->pending.acquire_point)) { + wl_resource_post_no_memory(surface->resource); + return; + } +} + +static void manager_handle_get_surface(struct wl_client *client, + struct wl_resource *resource, uint32_t id, + struct wl_resource *surface_resource) { + struct wlr_surface *wlr_surface = wlr_surface_from_resource(surface_resource); + + if (surface_from_wlr_surface(wlr_surface) != NULL) { + wl_resource_post_error(resource, + WP_LINUX_DRM_SYNCOBJ_MANAGER_V1_ERROR_SURFACE_EXISTS, + "wp_linux_drm_syncobj_surface_v1 already created for this surface"); + return; + } + + struct wlr_linux_drm_syncobj_surface_v1 *surface = calloc(1, sizeof(*surface)); + if (surface == NULL) { + wl_resource_post_no_memory(resource); + return; + } + + if (!wlr_surface_synced_init(&surface->synced, wlr_surface, + &surface_synced_impl, &surface->pending, &surface->current)) { + goto error_surface; + } + + uint32_t version = wl_resource_get_version(resource); + surface->resource = wl_resource_create(client, + &wp_linux_drm_syncobj_surface_v1_interface, version, id); + if (surface->resource == NULL) { + goto error_surface_synced; + } + wl_resource_set_implementation(surface->resource, + &surface_impl, surface, surface_handle_resource_destroy); + + surface->surface = wlr_surface; + + surface->client_commit.notify = surface_handle_client_commit; + wl_signal_add(&wlr_surface->events.client_commit, &surface->client_commit); + + wlr_addon_init(&surface->addon, &wlr_surface->addons, NULL, &surface_addon_impl); + + return; + +error_surface_synced: + wlr_surface_synced_finish(&surface->synced); +error_surface: + free(surface); + wl_resource_post_no_memory(resource); +} + +static void manager_handle_import_timeline(struct wl_client *client, + struct wl_resource *resource, uint32_t id, int drm_syncobj_fd) { + struct wlr_linux_drm_syncobj_manager_v1 *manager = + manager_from_resource(resource); + + struct wlr_drm_syncobj_timeline *timeline = + wlr_drm_syncobj_timeline_import(manager->drm_fd, drm_syncobj_fd); + close(drm_syncobj_fd); + if (timeline == NULL) { + wl_resource_post_error(resource, + WP_LINUX_DRM_SYNCOBJ_MANAGER_V1_ERROR_INVALID_TIMELINE, + "Failed to import drm_syncobj timeline"); + return; + } + + uint32_t version = wl_resource_get_version(resource); + struct wl_resource *timeline_resource = wl_resource_create(client, + &wp_linux_drm_syncobj_timeline_v1_interface, version, id); + if (timeline_resource == NULL) { + wlr_drm_syncobj_timeline_unref(timeline); + wl_resource_post_no_memory(resource); + return; + } + wl_resource_set_implementation(timeline_resource, + &timeline_impl, timeline, timeline_handle_resource_destroy); +} + +static const struct wp_linux_drm_syncobj_manager_v1_interface manager_impl = { + .destroy = manager_handle_destroy, + .get_surface = manager_handle_get_surface, + .import_timeline = manager_handle_import_timeline, +}; + +static void manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_linux_drm_syncobj_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &wp_linux_drm_syncobj_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, manager, NULL); +} + +static void linux_drm_syncobj_manager_v1_destroy(struct wlr_linux_drm_syncobj_manager_v1 *manager, + bool destroy_global_safe) { + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + close(manager->drm_fd); + free(manager); +} + +void wlr_linux_drm_syncobj_manager_v1_destroy(struct wlr_linux_drm_syncobj_manager_v1 *manager, + bool destroy_global_safe) { + linux_drm_syncobj_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_linux_drm_syncobj_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + linux_drm_syncobj_manager_v1_destroy(manager, false); +} + +static bool check_syncobj_eventfd(int drm_fd) { + if (!HAVE_EVENTFD) { + return false; + } + + uint64_t value = 0; + if (drmGetCap(drm_fd, DRM_CAP_SYNCOBJ_TIMELINE, &value) != 0 || value == 0) { + return false; + } + + // Try waiting with invalid syncobj should fail with ENOENT + struct drm_syncobj_eventfd syncobj_eventfd = { + .handle = 0, + .fd = -1, + }; + return drmIoctl(drm_fd, DRM_IOCTL_SYNCOBJ_EVENTFD, &syncobj_eventfd) != 0 && errno == ENOENT; +} + +struct wlr_linux_drm_syncobj_manager_v1 *wlr_linux_drm_syncobj_manager_v1_create( + struct wl_display *display, uint32_t version, int drm_fd) { + assert(version <= LINUX_DRM_SYNCOBJ_V1_VERSION); + + if (!HAVE_LINUX_SYNC_FILE) { + wlr_log(WLR_INFO, "Linux sync_file unavailable, disabling linux-drm-syncobj-v1"); + return NULL; + } + + if (!check_syncobj_eventfd(drm_fd)) { + wlr_log(WLR_INFO, "DRM syncobj eventfd unavailable, disabling linux-drm-syncobj-v1"); + return NULL; + } + + struct wlr_linux_drm_syncobj_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + manager->drm_fd = fcntl(drm_fd, F_DUPFD_CLOEXEC, 0); + if (manager->drm_fd < 0) { + goto error_manager; + } + + manager->global = wl_global_create(display, + &wp_linux_drm_syncobj_manager_v1_interface, + version, manager, manager_bind); + if (manager->global == NULL) { + goto error_drm_fd; + } + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; + +error_drm_fd: + close(manager->drm_fd); +error_manager: + free(manager); + return NULL; +} + +struct wlr_linux_drm_syncobj_surface_v1_state * +wlr_linux_drm_syncobj_v1_get_surface_state(struct wlr_surface *wlr_surface) { + struct wlr_linux_drm_syncobj_surface_v1 *surface = + surface_from_wlr_surface(wlr_surface); + if (surface == NULL) { + return NULL; + } + return &surface->current; +} + +struct release_signaller { + struct wlr_drm_syncobj_merger *merger; + struct wl_listener buffer_release; +}; + +static void release_signaller_handle_buffer_release(struct wl_listener *listener, void *data) { + struct release_signaller *signaller = wl_container_of(listener, signaller, buffer_release); + + wlr_drm_syncobj_merger_unref(signaller->merger); + wl_list_remove(&signaller->buffer_release.link); + free(signaller); +} + +bool wlr_linux_drm_syncobj_v1_state_signal_release_with_buffer( + struct wlr_linux_drm_syncobj_surface_v1_state *state, struct wlr_buffer *buffer) { + assert(buffer->n_locks > 0); + if (state->release_merger == NULL) { + // This can happen if an existing surface with a buffer has a + // syncobj_surface_v1_state created but no new buffer with release + // timeline committed. + return true; + } + + struct release_signaller *signaller = calloc(1, sizeof(*signaller)); + if (signaller == NULL) { + return false; + } + + signaller->merger = wlr_drm_syncobj_merger_ref(state->release_merger); + signaller->buffer_release.notify = release_signaller_handle_buffer_release; + wl_signal_add(&buffer->events.release, &signaller->buffer_release); + + return true; +} + +bool wlr_linux_drm_syncobj_v1_state_add_release_point( + struct wlr_linux_drm_syncobj_surface_v1_state *state, + struct wlr_drm_syncobj_timeline *release_timeline, uint64_t release_point, + struct wl_event_loop *event_loop) { + if (state->release_merger == NULL) { + // This can happen if an existing surface with a buffer has a + // syncobj_surface_v1_state created but no new buffer with release + // timeline committed. + return true; + } + return wlr_drm_syncobj_merger_add(state->release_merger, + release_timeline, release_point, event_loop); +} diff --git a/3rdparty/wlroots/types/wlr_output_layer.c b/3rdparty/wlroots/types/wlr_output_layer.c new file mode 100644 index 0000000000..068cf58a58 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_output_layer.c @@ -0,0 +1,30 @@ +#include +#include +#include + +struct wlr_output_layer *wlr_output_layer_create(struct wlr_output *output) { + struct wlr_output_layer *layer = calloc(1, sizeof(*layer)); + if (layer == NULL) { + return NULL; + } + + wl_list_insert(&output->layers, &layer->link); + wlr_addon_set_init(&layer->addons); + + wl_signal_init(&layer->events.feedback); + + return layer; +} + +void wlr_output_layer_destroy(struct wlr_output_layer *layer) { + if (layer == NULL) { + return; + } + + wlr_addon_set_finish(&layer->addons); + + assert(wl_list_empty(&layer->events.feedback.listener_list)); + + wl_list_remove(&layer->link); + free(layer); +} diff --git a/3rdparty/wlroots/types/wlr_output_layout.c b/3rdparty/wlroots/types/wlr_output_layout.c new file mode 100644 index 0000000000..ef27511795 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_output_layout.c @@ -0,0 +1,496 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +static const struct wlr_addon_interface addon_impl; + +static void output_layout_handle_display_destroy(struct wl_listener *listener, + void *data) { + struct wlr_output_layout *layout = wl_container_of(listener, layout, display_destroy); + wlr_output_layout_destroy(layout); +} + +struct wlr_output_layout *wlr_output_layout_create(struct wl_display *display) { + struct wlr_output_layout *layout = calloc(1, sizeof(*layout)); + if (layout == NULL) { + return NULL; + } + wl_list_init(&layout->outputs); + layout->display = display; + + wl_signal_init(&layout->events.add); + wl_signal_init(&layout->events.change); + wl_signal_init(&layout->events.destroy); + + layout->display_destroy.notify = output_layout_handle_display_destroy; + wl_display_add_destroy_listener(display, &layout->display_destroy); + + return layout; +} + +static void output_layout_output_destroy( + struct wlr_output_layout_output *l_output) { + wl_signal_emit_mutable(&l_output->events.destroy, l_output); + + assert(wl_list_empty(&l_output->events.destroy.listener_list)); + + wlr_output_destroy_global(l_output->output); + wl_list_remove(&l_output->commit.link); + wl_list_remove(&l_output->link); + wlr_addon_finish(&l_output->addon); + free(l_output); +} + +void wlr_output_layout_destroy(struct wlr_output_layout *layout) { + if (!layout) { + return; + } + + wl_signal_emit_mutable(&layout->events.destroy, layout); + + assert(wl_list_empty(&layout->events.add.listener_list)); + assert(wl_list_empty(&layout->events.change.listener_list)); + assert(wl_list_empty(&layout->events.destroy.listener_list)); + + struct wlr_output_layout_output *l_output, *temp; + wl_list_for_each_safe(l_output, temp, &layout->outputs, link) { + output_layout_output_destroy(l_output); + } + + wl_list_remove(&layout->display_destroy.link); + free(layout); +} + +static void output_layout_output_get_box( + struct wlr_output_layout_output *l_output, + struct wlr_box *box) { + box->x = l_output->x; + box->y = l_output->y; + wlr_output_effective_resolution(l_output->output, + &box->width, &box->height); +} + +/** + * This must be called whenever the layout changes to reconfigure the auto + * configured outputs and emit the `changed` event. + * + * Auto configured outputs are placed to the right of the north east corner of + * the rightmost output in the layout in a horizontal line. + */ +static void output_layout_reconfigure(struct wlr_output_layout *layout) { + int max_x = INT_MIN; + int max_x_y = INT_MIN; // y value for the max_x output + + // find the rightmost x coordinate occupied by a manually configured output + // in the layout + struct wlr_output_layout_output *l_output; + struct wlr_box output_box; + + wl_list_for_each(l_output, &layout->outputs, link) { + if (l_output->auto_configured) { + continue; + } + + output_layout_output_get_box(l_output, &output_box); + if (output_box.x + output_box.width > max_x) { + max_x = output_box.x + output_box.width; + max_x_y = output_box.y; + } + } + + if (max_x == INT_MIN) { + // there are no manually configured outputs + max_x = 0; + max_x_y = 0; + } + + wl_list_for_each(l_output, &layout->outputs, link) { + if (!l_output->auto_configured) { + continue; + } + output_layout_output_get_box(l_output, &output_box); + l_output->x = max_x; + l_output->y = max_x_y; + max_x += output_box.width; + } + + wl_signal_emit_mutable(&layout->events.change, layout); +} + +static void output_update_global(struct wlr_output_layout *layout, + struct wlr_output *output) { + // Don't expose the output if it doesn't have a current mode + if (output->width > 0 && output->height > 0) { + wlr_output_create_global(output, layout->display); + } else { + wlr_output_destroy_global(output); + } +} + +static void handle_output_commit(struct wl_listener *listener, void *data) { + struct wlr_output_layout_output *l_output = + wl_container_of(listener, l_output, commit); + struct wlr_output_event_commit *event = data; + + if (event->state->committed & (WLR_OUTPUT_STATE_SCALE | + WLR_OUTPUT_STATE_TRANSFORM | + WLR_OUTPUT_STATE_MODE)) { + output_layout_reconfigure(l_output->layout); + output_update_global(l_output->layout, l_output->output); + } +} + +static void addon_destroy(struct wlr_addon *addon) { + assert(addon->impl == &addon_impl); + struct wlr_output_layout_output *l_output = + wl_container_of(addon, l_output, addon); + struct wlr_output_layout *layout = l_output->layout; + output_layout_output_destroy(l_output); + output_layout_reconfigure(layout); +} + +static const struct wlr_addon_interface addon_impl = { + .name = "wlr_output_layout_output", + .destroy = addon_destroy, +}; + +static struct wlr_output_layout_output *output_layout_output_create( + struct wlr_output_layout *layout, struct wlr_output *output) { + struct wlr_output_layout_output *l_output = calloc(1, sizeof(*l_output)); + if (l_output == NULL) { + return NULL; + } + l_output->layout = layout; + l_output->output = output; + + wl_signal_init(&l_output->events.destroy); + + /* + * Insert at the end of the list so that auto-configuring the + * new output doesn't change the layout of other outputs + */ + wl_list_insert(layout->outputs.prev, &l_output->link); + + wl_signal_add(&output->events.commit, &l_output->commit); + l_output->commit.notify = handle_output_commit; + + wlr_addon_init(&l_output->addon, &output->addons, layout, &addon_impl); + + return l_output; +} + +static struct wlr_output_layout_output *output_layout_add(struct wlr_output_layout *layout, + struct wlr_output *output, int lx, int ly, + bool auto_configured) { + struct wlr_output_layout_output *l_output = + wlr_output_layout_get(layout, output); + bool is_new = l_output == NULL; + if (is_new) { + l_output = output_layout_output_create(layout, output); + if (l_output == NULL) { + return NULL; + } + } + + l_output->x = lx; + l_output->y = ly; + l_output->auto_configured = auto_configured; + + output_layout_reconfigure(layout); + output_update_global(layout, output); + + if (is_new) { + wl_signal_emit_mutable(&layout->events.add, l_output); + } + + return l_output; +} + +struct wlr_output_layout_output *wlr_output_layout_add(struct wlr_output_layout *layout, + struct wlr_output *output, int lx, int ly) { + return output_layout_add(layout, output, lx, ly, false); +} + +struct wlr_output_layout_output *wlr_output_layout_add_auto(struct wlr_output_layout *layout, + struct wlr_output *output) { + return output_layout_add(layout, output, 0, 0, true); +} + +void wlr_output_layout_remove(struct wlr_output_layout *layout, + struct wlr_output *output) { + struct wlr_output_layout_output *l_output = + wlr_output_layout_get(layout, output); + if (l_output != NULL) { + output_layout_output_destroy(l_output); + output_layout_reconfigure(layout); + } +} + +struct wlr_output_layout_output *wlr_output_layout_get( + struct wlr_output_layout *layout, struct wlr_output *reference) { + struct wlr_output_layout_output *l_output = NULL; + struct wlr_addon *addon = + wlr_addon_find(&reference->addons, layout, &addon_impl); + if (addon) { + l_output = wl_container_of(addon, l_output, addon); + } + return l_output; +} + +bool wlr_output_layout_contains_point(struct wlr_output_layout *layout, + struct wlr_output *reference, int lx, int ly) { + if (reference) { + struct wlr_output_layout_output *l_output = + wlr_output_layout_get(layout, reference); + if (!l_output) { + return false; + } + struct wlr_box output_box; + output_layout_output_get_box(l_output, &output_box); + return wlr_box_contains_point(&output_box, lx, ly); + } else { + return !!wlr_output_layout_output_at(layout, lx, ly); + } +} + +bool wlr_output_layout_intersects(struct wlr_output_layout *layout, + struct wlr_output *reference, const struct wlr_box *target_lbox) { + struct wlr_box out_box; + + if (reference == NULL) { + struct wlr_output_layout_output *l_output; + wl_list_for_each(l_output, &layout->outputs, link) { + struct wlr_box output_box; + output_layout_output_get_box(l_output, &output_box); + if (wlr_box_intersection(&out_box, &output_box, target_lbox)) { + return true; + } + } + return false; + } else { + struct wlr_output_layout_output *l_output = + wlr_output_layout_get(layout, reference); + if (!l_output) { + return false; + } + + struct wlr_box output_box; + output_layout_output_get_box(l_output, &output_box); + return wlr_box_intersection(&out_box, &output_box, target_lbox); + } +} + +struct wlr_output *wlr_output_layout_output_at(struct wlr_output_layout *layout, + double lx, double ly) { + struct wlr_output_layout_output *l_output; + wl_list_for_each(l_output, &layout->outputs, link) { + struct wlr_box output_box; + output_layout_output_get_box(l_output, &output_box); + if (wlr_box_contains_point(&output_box, lx, ly)) { + return l_output->output; + } + } + return NULL; +} + +void wlr_output_layout_output_coords(struct wlr_output_layout *layout, + struct wlr_output *reference, double *lx, double *ly) { + assert(layout && reference); + double src_x = *lx; + double src_y = *ly; + + struct wlr_output_layout_output *l_output; + wl_list_for_each(l_output, &layout->outputs, link) { + if (l_output->output == reference) { + *lx = src_x - (double)l_output->x; + *ly = src_y - (double)l_output->y; + return; + } + } +} + +void wlr_output_layout_closest_point(struct wlr_output_layout *layout, + struct wlr_output *reference, double lx, double ly, double *dest_lx, + double *dest_ly) { + if (dest_lx == NULL && dest_ly == NULL) { + return; + } + + double min_x = lx, min_y = ly, min_distance = DBL_MAX; + struct wlr_output_layout_output *l_output; + wl_list_for_each(l_output, &layout->outputs, link) { + if (reference != NULL && reference != l_output->output) { + continue; + } + + double output_x, output_y, output_distance; + struct wlr_box output_box; + output_layout_output_get_box(l_output, &output_box); + wlr_box_closest_point(&output_box, lx, ly, &output_x, &output_y); + + // calculate squared distance suitable for comparison + output_distance = + (lx - output_x) * (lx - output_x) + (ly - output_y) * (ly - output_y); + + if (!isfinite(output_distance)) { + output_distance = DBL_MAX; + } + + if (output_distance < min_distance) { + min_x = output_x; + min_y = output_y; + min_distance = output_distance; + } + } + + if (dest_lx) { + *dest_lx = min_x; + } + if (dest_ly) { + *dest_ly = min_y; + } +} + +void wlr_output_layout_get_box(struct wlr_output_layout *layout, + struct wlr_output *reference, struct wlr_box *dest_box) { + *dest_box = (struct wlr_box){0}; + + struct wlr_output_layout_output *l_output; + if (reference) { + // output extents + l_output = wlr_output_layout_get(layout, reference); + + if (l_output) { + output_layout_output_get_box(l_output, dest_box); + } + } else { + // layout extents + int min_x = 0, max_x = 0, min_y = 0, max_y = 0; + if (!wl_list_empty(&layout->outputs)) { + min_x = min_y = INT_MAX; + max_x = max_y = INT_MIN; + wl_list_for_each(l_output, &layout->outputs, link) { + struct wlr_box output_box; + output_layout_output_get_box(l_output, &output_box); + if (output_box.x < min_x) { + min_x = output_box.x; + } + if (output_box.y < min_y) { + min_y = output_box.y; + } + if (output_box.x + output_box.width > max_x) { + max_x = output_box.x + output_box.width; + } + if (output_box.y + output_box.height > max_y) { + max_y = output_box.y + output_box.height; + } + } + } + + dest_box->x = min_x; + dest_box->y = min_y; + dest_box->width = max_x - min_x; + dest_box->height = max_y - min_y; + } +} + +struct wlr_output *wlr_output_layout_get_center_output( + struct wlr_output_layout *layout) { + if (wl_list_empty(&layout->outputs)) { + return NULL; + } + + struct wlr_box extents; + wlr_output_layout_get_box(layout, NULL, &extents); + double center_x = extents.width / 2. + extents.x; + double center_y = extents.height / 2. + extents.y; + + double dest_x = 0, dest_y = 0; + wlr_output_layout_closest_point(layout, NULL, center_x, center_y, + &dest_x, &dest_y); + + return wlr_output_layout_output_at(layout, dest_x, dest_y); +} + +enum distance_selection_method { + NEAREST, + FARTHEST +}; + +static struct wlr_output *wlr_output_layout_output_in_direction( + struct wlr_output_layout *layout, enum wlr_direction direction, + struct wlr_output *reference, double ref_lx, double ref_ly, + enum distance_selection_method distance_method) { + assert(reference); + + struct wlr_box ref_box; + wlr_output_layout_get_box(layout, reference, &ref_box); + if (wlr_box_empty(&ref_box)) { + // The output doesn't belong to the layout + return NULL; + } + + double min_distance = (distance_method == NEAREST) ? DBL_MAX : DBL_MIN; + struct wlr_output *closest_output = NULL; + struct wlr_output_layout_output *l_output; + wl_list_for_each(l_output, &layout->outputs, link) { + if (reference != NULL && reference == l_output->output) { + continue; + } + + struct wlr_box box; + output_layout_output_get_box(l_output, &box); + + bool match = false; + // test to make sure this output is in the given direction + if (direction & WLR_DIRECTION_LEFT) { + match = box.x + box.width <= ref_box.x || match; + } + if (direction & WLR_DIRECTION_RIGHT) { + match = box.x >= ref_box.x + ref_box.width || match; + } + if (direction & WLR_DIRECTION_UP) { + match = box.y + box.height <= ref_box.y || match; + } + if (direction & WLR_DIRECTION_DOWN) { + match = box.y >= ref_box.y + ref_box.height || match; + } + if (!match) { + continue; + } + + // calculate distance from the given reference point + double x, y; + wlr_output_layout_closest_point(layout, l_output->output, + ref_lx, ref_ly, &x, &y); + double distance = + (x - ref_lx) * (x - ref_lx) + (y - ref_ly) * (y - ref_ly); + + if ((distance_method == NEAREST) + ? distance < min_distance + : distance > min_distance) { + min_distance = distance; + closest_output = l_output->output; + } + } + return closest_output; +} + +struct wlr_output *wlr_output_layout_adjacent_output( + struct wlr_output_layout *layout, enum wlr_direction direction, + struct wlr_output *reference, double ref_lx, double ref_ly) { + return wlr_output_layout_output_in_direction(layout, direction, + reference, ref_lx, ref_ly, NEAREST); +} + +struct wlr_output *wlr_output_layout_farthest_output( + struct wlr_output_layout *layout, enum wlr_direction direction, + struct wlr_output *reference, double ref_lx, double ref_ly) { + return wlr_output_layout_output_in_direction(layout, direction, + reference, ref_lx, ref_ly, FARTHEST); +} diff --git a/3rdparty/wlroots/types/wlr_output_management_v1.c b/3rdparty/wlroots/types/wlr_output_management_v1.c new file mode 100644 index 0000000000..6f6937d87b --- /dev/null +++ b/3rdparty/wlroots/types/wlr_output_management_v1.c @@ -0,0 +1,1078 @@ +#include +#include +#include +#include +#include +#include +#include +#include "wlr-output-management-unstable-v1-protocol.h" +#include "util/global.h" + +#define OUTPUT_MANAGER_VERSION 4 + +enum { + HEAD_STATE_ENABLED = 1 << 0, + HEAD_STATE_MODE = 1 << 1, + HEAD_STATE_POSITION = 1 << 2, + HEAD_STATE_TRANSFORM = 1 << 3, + HEAD_STATE_SCALE = 1 << 4, + HEAD_STATE_ADAPTIVE_SYNC = 1 << 5, +}; + +static const uint32_t HEAD_STATE_ALL = HEAD_STATE_ENABLED | HEAD_STATE_MODE | + HEAD_STATE_POSITION | HEAD_STATE_TRANSFORM | HEAD_STATE_SCALE | + HEAD_STATE_ADAPTIVE_SYNC; + +static const struct zwlr_output_head_v1_interface head_impl; + +// Can return NULL if the head is inert +static struct wlr_output_head_v1 *head_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_output_head_v1_interface, &head_impl)); + return wl_resource_get_user_data(resource); +} + +static const struct zwlr_output_mode_v1_interface output_mode_impl; + +// Can return NULL if the mode is custom or inert +static struct wlr_output_mode *mode_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_output_mode_v1_interface, &output_mode_impl)); + return wl_resource_get_user_data(resource); +} + +static void head_destroy(struct wlr_output_head_v1 *head) { + if (head == NULL) { + return; + } + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &head->mode_resources) { + zwlr_output_mode_v1_send_finished(resource); + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + wl_resource_set_user_data(resource, NULL); + } + wl_resource_for_each_safe(resource, tmp, &head->resources) { + zwlr_output_head_v1_send_finished(resource); + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + wl_resource_set_user_data(resource, NULL); + } + wl_list_remove(&head->link); + wl_list_remove(&head->output_destroy.link); + free(head); +} + +static void head_handle_output_destroy(struct wl_listener *listener, + void *data) { + struct wlr_output_head_v1 *head = + wl_container_of(listener, head, output_destroy); + head->manager->current_configuration_dirty = true; + head_destroy(head); +} + +static struct wlr_output_head_v1 *head_create( + struct wlr_output_manager_v1 *manager, struct wlr_output *output) { + struct wlr_output_head_v1 *head = calloc(1, sizeof(*head)); + if (head == NULL) { + return NULL; + } + head->manager = manager; + head->state.output = output; + wl_list_init(&head->resources); + wl_list_init(&head->mode_resources); + wl_list_insert(&manager->heads, &head->link); + head->output_destroy.notify = head_handle_output_destroy; + wl_signal_add(&output->events.destroy, &head->output_destroy); + return head; +} + +static void head_destroy_custom_mode_resources(struct wlr_output_head_v1 *head) { + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &head->mode_resources) { + if (wl_resource_get_user_data(resource) != NULL) { + continue; + } + zwlr_output_mode_v1_send_finished(resource); + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + } +} + +static bool head_has_custom_mode_resources(const struct wlr_output_head_v1 *head) { + struct wl_resource *resource; + wl_resource_for_each(resource, &head->mode_resources) { + if (wl_resource_get_user_data(resource) == NULL) { + return true; + } + } + return false; +} + + +static void config_head_destroy( + struct wlr_output_configuration_head_v1 *config_head) { + if (config_head == NULL) { + return; + } + if (config_head->resource != NULL) { + wl_resource_set_user_data(config_head->resource, NULL); // make inert + } + wl_list_remove(&config_head->link); + wl_list_remove(&config_head->output_destroy.link); + free(config_head); +} + +static void config_head_handle_output_destroy(struct wl_listener *listener, + void *data) { + struct wlr_output_configuration_head_v1 *config_head = + wl_container_of(listener, config_head, output_destroy); + config_head_destroy(config_head); +} + +static struct wlr_output_configuration_head_v1 *config_head_create( + struct wlr_output_configuration_v1 *config, struct wlr_output *output) { + struct wlr_output_configuration_head_v1 *config_head = + calloc(1, sizeof(*config_head)); + if (config_head == NULL) { + return NULL; + } + config_head->config = config; + config_head->state.output = output; + wl_list_insert(&config->heads, &config_head->link); + config_head->output_destroy.notify = config_head_handle_output_destroy; + wl_signal_add(&output->events.destroy, &config_head->output_destroy); + return config_head; +} + +struct wlr_output_configuration_head_v1 * + wlr_output_configuration_head_v1_create( + struct wlr_output_configuration_v1 *config, struct wlr_output *output) { + struct wlr_output_configuration_head_v1 *config_head = + config_head_create(config, output); + if (config_head == NULL) { + return NULL; + } + config_head->state.enabled = output->enabled; + config_head->state.mode = output->current_mode; + config_head->state.custom_mode.width = output->width; + config_head->state.custom_mode.height = output->height; + config_head->state.custom_mode.refresh = output->refresh; + config_head->state.transform = output->transform; + config_head->state.scale = output->scale; + config_head->state.adaptive_sync_enabled = + output->adaptive_sync_status == WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED; + return config_head; +} + +static const struct zwlr_output_configuration_head_v1_interface config_head_impl; + +// Can return NULL if the configuration head is inert +static struct wlr_output_configuration_head_v1 *config_head_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_output_configuration_head_v1_interface, &config_head_impl)); + return wl_resource_get_user_data(resource); +} + +static void config_head_handle_set_mode(struct wl_client *client, + struct wl_resource *config_head_resource, + struct wl_resource *mode_resource) { + struct wlr_output_configuration_head_v1 *config_head = + config_head_from_resource(config_head_resource); + if (config_head == NULL) { + return; + } + + // Mode can be NULL if the output uses a custom mode (in which case we + // expose a virtual mode with user data set to NULL). + struct wlr_output_mode *mode = mode_from_resource(mode_resource); + struct wlr_output *output = config_head->state.output; + + bool found = mode == NULL; + struct wlr_output_mode *m; + wl_list_for_each(m, &output->modes, link) { + if (mode == m) { + found = true; + break; + } + } + + if (!found) { + wl_resource_post_error(config_head_resource, + ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_MODE, + "mode doesn't belong to head"); + return; + } + + config_head->state.mode = mode; + if (mode != NULL) { + config_head->state.custom_mode.width = 0; + config_head->state.custom_mode.height = 0; + config_head->state.custom_mode.refresh = 0; + } +} + +static void config_head_handle_set_custom_mode(struct wl_client *client, + struct wl_resource *config_head_resource, int32_t width, int32_t height, + int32_t refresh) { + struct wlr_output_configuration_head_v1 *config_head = + config_head_from_resource(config_head_resource); + if (config_head == NULL) { + return; + } + + if (width <= 0 || height <= 0 || refresh < 0) { + wl_resource_post_error(config_head_resource, + ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_CUSTOM_MODE, + "invalid custom mode"); + return; + } + + config_head->state.mode = NULL; + config_head->state.custom_mode.width = width; + config_head->state.custom_mode.height = height; + config_head->state.custom_mode.refresh = refresh; +} + +static void config_head_handle_set_position(struct wl_client *client, + struct wl_resource *config_head_resource, int32_t x, int32_t y) { + struct wlr_output_configuration_head_v1 *config_head = + config_head_from_resource(config_head_resource); + if (config_head == NULL) { + return; + } + + config_head->state.x = x; + config_head->state.y = y; +} + +static void config_head_handle_set_transform(struct wl_client *client, + struct wl_resource *config_head_resource, int32_t transform) { + struct wlr_output_configuration_head_v1 *config_head = + config_head_from_resource(config_head_resource); + if (config_head == NULL) { + return; + } + + if (!wl_output_transform_is_valid(transform, 1)) { + wl_resource_post_error(config_head_resource, + ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_TRANSFORM, + "invalid transform"); + return; + } + + config_head->state.transform = transform; +} + +static void config_head_handle_set_scale(struct wl_client *client, + struct wl_resource *config_head_resource, wl_fixed_t scale_fixed) { + struct wlr_output_configuration_head_v1 *config_head = + config_head_from_resource(config_head_resource); + if (config_head == NULL) { + return; + } + + float scale = wl_fixed_to_double(scale_fixed); + if (scale <= 0) { + wl_resource_post_error(config_head_resource, + ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_SCALE, + "invalid scale"); + return; + } + + config_head->state.scale = scale; +} + +static void config_head_handle_set_adaptive_sync(struct wl_client *client, + struct wl_resource *config_head_resource, uint32_t state) { + struct wlr_output_configuration_head_v1 *config_head = + config_head_from_resource(config_head_resource); + if (config_head == NULL) { + return; + } + + switch (state) { + case ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_ENABLED: + config_head->state.adaptive_sync_enabled = true; + break; + case ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_DISABLED: + config_head->state.adaptive_sync_enabled = false; + break; + default: + wl_resource_post_error(config_head_resource, + ZWLR_OUTPUT_CONFIGURATION_HEAD_V1_ERROR_INVALID_ADAPTIVE_SYNC_STATE, + "client requested invalid adaptive sync state %ul", state); + break; + } +} + +static const struct zwlr_output_configuration_head_v1_interface config_head_impl = { + .set_mode = config_head_handle_set_mode, + .set_custom_mode = config_head_handle_set_custom_mode, + .set_position = config_head_handle_set_position, + .set_transform = config_head_handle_set_transform, + .set_scale = config_head_handle_set_scale, + .set_adaptive_sync = config_head_handle_set_adaptive_sync, +}; + +static void config_head_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_output_configuration_head_v1 *config_head = + config_head_from_resource(resource); + config_head_destroy(config_head); +} + + +static const struct zwlr_output_configuration_v1_interface config_impl; + +// Can return NULL if the config has been used +static struct wlr_output_configuration_v1 *config_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_output_configuration_v1_interface, &config_impl)); + return wl_resource_get_user_data(resource); +} + +// Checks that the head is unconfigured (ie. no enable_head/disable_head request +// has yet been sent for this head), if not sends a protocol error. +static bool config_check_head_is_unconfigured( + struct wlr_output_configuration_v1 *config, struct wlr_output *output) { + struct wlr_output_configuration_head_v1 *head; + wl_list_for_each(head, &config->heads, link) { + if (head->state.output == output) { + wl_resource_post_error(config->resource, + ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_ALREADY_CONFIGURED_HEAD, + "head has already been configured"); + return false; + } + } + return true; +} + +static void config_handle_enable_head(struct wl_client *client, + struct wl_resource *config_resource, uint32_t id, + struct wl_resource *head_resource) { + struct wlr_output_configuration_v1 *config = + config_from_resource(config_resource); + if (config == NULL || config->finalized) { + wl_resource_post_error(config_resource, + ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_ALREADY_USED, + "configuration object has already been used"); + return; + } + struct wlr_output_head_v1 *head = head_from_resource(head_resource); + + // Create an inert resource if the head no longer exists + struct wlr_output_configuration_head_v1 *config_head = NULL; + if (head != NULL) { + if (!config_check_head_is_unconfigured(config, head->state.output)) { + return; + } + config_head = config_head_create(config, head->state.output); + if (config_head == NULL) { + wl_resource_post_no_memory(config_resource); + return; + } + config_head->state = head->state; + } + + uint32_t version = wl_resource_get_version(config_resource); + struct wl_resource *resource = wl_resource_create(client, + &zwlr_output_configuration_head_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &config_head_impl, + config_head, config_head_handle_resource_destroy); + + if (config_head != NULL) { + config_head->resource = resource; + config_head->state.enabled = true; + } +} + +static void config_handle_disable_head(struct wl_client *client, + struct wl_resource *config_resource, + struct wl_resource *head_resource) { + struct wlr_output_configuration_v1 *config = + config_from_resource(config_resource); + if (config == NULL || config->finalized) { + wl_resource_post_error(config_resource, + ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_ALREADY_USED, + "configuration object has already been used"); + return; + } + struct wlr_output_head_v1 *head = head_from_resource(head_resource); + if (head == NULL) { + return; + } + + if (!config_check_head_is_unconfigured(config, head->state.output)) { + return; + } + struct wlr_output_configuration_head_v1 *config_head = + config_head_create(config, head->state.output); + if (config_head == NULL) { + wl_resource_post_no_memory(config_resource); + return; + } + + config_head->state.enabled = false; +} + +// Finalizes a configuration. This prevents the same config from being used +// multiple times. +static void config_finalize(struct wlr_output_configuration_v1 *config) { + if (config->finalized) { + return; + } + + // Destroy config head resources now, the client is forbidden to use them at + // this point anyway + struct wlr_output_configuration_head_v1 *config_head, *tmp; + wl_list_for_each_safe(config_head, tmp, &config->heads, link) { + // Resource is NULL if head has been disabled + if (config_head->resource != NULL) { + wl_resource_set_user_data(config_head->resource, NULL); + wl_resource_destroy(config_head->resource); + config_head->resource = NULL; + } + } + + config->finalized = true; +} + +// Destroys the config if serial is invalid +static bool config_validate_serial(struct wlr_output_configuration_v1 *config) { + if (config->serial != config->manager->serial) { + wlr_log(WLR_DEBUG, "Ignored configuration request: invalid serial"); + zwlr_output_configuration_v1_send_cancelled(config->resource); + wlr_output_configuration_v1_destroy(config); + return false; + } + return true; +} + +static void config_handle_apply(struct wl_client *client, + struct wl_resource *config_resource) { + struct wlr_output_configuration_v1 *config = + config_from_resource(config_resource); + if (config == NULL || config->finalized) { + wl_resource_post_error(config_resource, + ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_ALREADY_USED, + "configuration object has already been used"); + return; + } + + config_finalize(config); + if (!config_validate_serial(config)) { + return; + } + + wl_signal_emit_mutable(&config->manager->events.apply, config); +} + +static void config_handle_test(struct wl_client *client, + struct wl_resource *config_resource) { + struct wlr_output_configuration_v1 *config = + config_from_resource(config_resource); + if (config == NULL || config->finalized) { + wl_resource_post_error(config_resource, + ZWLR_OUTPUT_CONFIGURATION_V1_ERROR_ALREADY_USED, + "configuration object has already been used"); + return; + } + + config_finalize(config); + if (!config_validate_serial(config)) { + return; + } + + wl_signal_emit_mutable(&config->manager->events.test, config); +} + +static void config_handle_destroy(struct wl_client *client, + struct wl_resource *config_resource) { + wl_resource_destroy(config_resource); +} + +static const struct zwlr_output_configuration_v1_interface config_impl = { + .enable_head = config_handle_enable_head, + .disable_head = config_handle_disable_head, + .apply = config_handle_apply, + .test = config_handle_test, + .destroy = config_handle_destroy, +}; + +static struct wlr_output_configuration_v1 *config_create(bool finalized) { + struct wlr_output_configuration_v1 *config = calloc(1, sizeof(*config)); + if (config == NULL) { + return NULL; + } + wl_list_init(&config->heads); + config->finalized = finalized; + return config; +} + +struct wlr_output_configuration_v1 *wlr_output_configuration_v1_create(void) { + return config_create(true); +} + +void wlr_output_configuration_v1_destroy( + struct wlr_output_configuration_v1 *config) { + if (config == NULL) { + return; + } + config_finalize(config); + if (config->resource != NULL) { + wl_resource_set_user_data(config->resource, NULL); // make inert + } + struct wlr_output_configuration_head_v1 *config_head, *tmp; + wl_list_for_each_safe(config_head, tmp, &config->heads, link) { + config_head_destroy(config_head); + } + free(config); +} + +static void config_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_output_configuration_v1 *config = config_from_resource(resource); + if (config == NULL) { + return; + } + if (config->finalized) { + config->resource = NULL; // we no longer own the config + } else { + wlr_output_configuration_v1_destroy(config); + } +} + +void wlr_output_configuration_v1_send_succeeded( + struct wlr_output_configuration_v1 *config) { + assert(!config->finished); + if (config->resource == NULL) { + return; // client destroyed the resource early + } + zwlr_output_configuration_v1_send_succeeded(config->resource); + config->finished = true; +} + +void wlr_output_configuration_v1_send_failed( + struct wlr_output_configuration_v1 *config) { + assert(!config->finished); + if (config->resource == NULL) { + return; // client destroyed the resource early + } + zwlr_output_configuration_v1_send_failed(config->resource); + config->finished = true; +} + + +static const struct zwlr_output_manager_v1_interface manager_impl; + +static struct wlr_output_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_output_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void manager_handle_create_configuration(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, uint32_t serial) { + struct wlr_output_manager_v1 *manager = + manager_from_resource(manager_resource); + + struct wlr_output_configuration_v1 *config = config_create(false); + if (config == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + config->manager = manager; + config->serial = serial; + + uint32_t version = wl_resource_get_version(manager_resource); + config->resource = wl_resource_create(client, + &zwlr_output_configuration_v1_interface, version, id); + if (config->resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(config->resource, &config_impl, + config, config_handle_resource_destroy); +} + +static void manager_handle_stop(struct wl_client *client, + struct wl_resource *manager_resource) { + zwlr_output_manager_v1_send_finished(manager_resource); + wl_resource_destroy(manager_resource); +} + +static const struct zwlr_output_manager_v1_interface manager_impl = { + .create_configuration = manager_handle_create_configuration, + .stop = manager_handle_stop, +}; + +static void manager_handle_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void manager_send_head(struct wlr_output_manager_v1 *manager, + struct wlr_output_head_v1 *head, struct wl_resource *manager_resource); + +static void manager_bind(struct wl_client *client, void *data, uint32_t version, + uint32_t id) { + struct wlr_output_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &zwlr_output_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, manager, + manager_handle_resource_destroy); + wl_list_init(wl_resource_get_link(resource)); + if (manager == NULL) { + return; + } + + + wl_list_insert(&manager->resources, wl_resource_get_link(resource)); + + struct wlr_output_head_v1 *head; + wl_list_for_each(head, &manager->heads, link) { + manager_send_head(manager, head, resource); + } + + zwlr_output_manager_v1_send_done(resource, manager->serial); +} + +static void output_manager_v1_destroy(struct wlr_output_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + assert(wl_list_empty(&manager->events.apply.listener_list)); + assert(wl_list_empty(&manager->events.test.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + struct wlr_output_head_v1 *head, *tmp; + wl_list_for_each_safe(head, tmp, &manager->heads, link) { + head_destroy(head); + } + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_output_manager_v1_destroy(struct wlr_output_manager_v1 *manager, + bool destroy_global_safe) { + output_manager_v1_destroy(manager, destroy_global_safe); +} + +static void manager_handle_display_destroy(struct wl_listener *listener, + void *data) { + struct wlr_output_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + output_manager_v1_destroy(manager, false); +} + +struct wlr_output_manager_v1 *wlr_output_manager_v1_create( + struct wl_display *display) { + struct wlr_output_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + manager->display = display; + + wl_list_init(&manager->resources); + wl_list_init(&manager->heads); + + wl_signal_init(&manager->events.destroy); + wl_signal_init(&manager->events.apply); + wl_signal_init(&manager->events.test); + + manager->global = wl_global_create(display, + &zwlr_output_manager_v1_interface, OUTPUT_MANAGER_VERSION, + manager, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + manager->display_destroy.notify = manager_handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} + +static struct wlr_output_configuration_head_v1 *configuration_get_head( + struct wlr_output_configuration_v1 *config, struct wlr_output *output) { + struct wlr_output_configuration_head_v1 *head; + wl_list_for_each(head, &config->heads, link) { + if (head->state.output == output) { + return head; + } + } + return NULL; +} + +static void send_mode_state(struct wl_resource *mode_resource, + struct wlr_output_mode *mode) { + zwlr_output_mode_v1_send_size(mode_resource, mode->width, mode->height); + if (mode->refresh > 0) { + zwlr_output_mode_v1_send_refresh(mode_resource, mode->refresh); + } + if (mode->preferred) { + zwlr_output_mode_v1_send_preferred(mode_resource); + } +} + +static void output_mode_handle_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void output_mode_handle_release(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwlr_output_mode_v1_interface output_mode_impl = { + .release = output_mode_handle_release, +}; + +static struct wl_resource *head_send_mode(struct wlr_output_head_v1 *head, + struct wl_resource *head_resource, struct wlr_output_mode *mode) { + struct wl_client *client = wl_resource_get_client(head_resource); + uint32_t version = wl_resource_get_version(head_resource); + struct wl_resource *mode_resource = + wl_resource_create(client, &zwlr_output_mode_v1_interface, version, 0); + if (mode_resource == NULL) { + wl_resource_post_no_memory(head_resource); + return NULL; + } + wl_resource_set_implementation(mode_resource, &output_mode_impl, mode, + output_mode_handle_resource_destroy); + wl_list_insert(&head->mode_resources, wl_resource_get_link(mode_resource)); + + zwlr_output_head_v1_send_mode(head_resource, mode_resource); + + if (mode != NULL) { + send_mode_state(mode_resource, mode); + } + + return mode_resource; +} + +// Sends new head state to a client. +static void head_send_state(struct wlr_output_head_v1 *head, + struct wl_resource *head_resource, uint32_t state) { + struct wl_client *client = wl_resource_get_client(head_resource); + + if (state & HEAD_STATE_ENABLED) { + zwlr_output_head_v1_send_enabled(head_resource, head->state.enabled); + // On enabling we send all current data since clients have not been + // notified about potential data changes while the head was disabled. + state = HEAD_STATE_ALL; + } + + if (!head->state.enabled) { + return; + } + + if (state & HEAD_STATE_MODE) { + bool found = false; + struct wl_resource *mode_resource; + wl_resource_for_each(mode_resource, &head->mode_resources) { + if (wl_resource_get_client(mode_resource) == client && + mode_from_resource(mode_resource) == head->state.mode) { + found = true; + break; + } + } + assert(found); + + if (head->state.mode == NULL) { + // Fake a single output mode if output doesn't support modes + struct wlr_output_mode virtual_mode = { + .width = head->state.custom_mode.width, + .height = head->state.custom_mode.height, + .refresh = head->state.custom_mode.refresh, + }; + send_mode_state(mode_resource, &virtual_mode); + } + + zwlr_output_head_v1_send_current_mode(head_resource, mode_resource); + } + + if (state & HEAD_STATE_POSITION) { + zwlr_output_head_v1_send_position(head_resource, + head->state.x, head->state.y); + } + + if (state & HEAD_STATE_TRANSFORM) { + zwlr_output_head_v1_send_transform(head_resource, + head->state.transform); + } + + if (state & HEAD_STATE_SCALE) { + zwlr_output_head_v1_send_scale(head_resource, + wl_fixed_from_double(head->state.scale)); + } + + if ((state & HEAD_STATE_ADAPTIVE_SYNC) && + wl_resource_get_version(head_resource) >= + ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_SINCE_VERSION) { + if (head->state.adaptive_sync_enabled) { + zwlr_output_head_v1_send_adaptive_sync(head_resource, + ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_ENABLED); + } else { + zwlr_output_head_v1_send_adaptive_sync(head_resource, + ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_DISABLED); + } + } +} + +static void head_handle_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void head_handle_release(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwlr_output_head_v1_interface head_impl = { + .release = head_handle_release, +}; + +static void manager_send_head(struct wlr_output_manager_v1 *manager, + struct wlr_output_head_v1 *head, struct wl_resource *manager_resource) { + struct wlr_output *output = head->state.output; + + struct wl_client *client = wl_resource_get_client(manager_resource); + uint32_t version = wl_resource_get_version(manager_resource); + struct wl_resource *head_resource = wl_resource_create(client, + &zwlr_output_head_v1_interface, version, 0); + if (head_resource == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + wl_resource_set_implementation(head_resource, &head_impl, head, + head_handle_resource_destroy); + wl_list_insert(&head->resources, wl_resource_get_link(head_resource)); + + zwlr_output_manager_v1_send_head(manager_resource, head_resource); + + zwlr_output_head_v1_send_name(head_resource, output->name); + zwlr_output_head_v1_send_description(head_resource, + output->description ? output->description : "Unknown"); + + if (output->phys_width > 0 && output->phys_height > 0) { + zwlr_output_head_v1_send_physical_size(head_resource, + output->phys_width, output->phys_height); + } + + if (version >= ZWLR_OUTPUT_HEAD_V1_MAKE_SINCE_VERSION && output->make != NULL) { + zwlr_output_head_v1_send_make(head_resource, output->make); + } + if (version >= ZWLR_OUTPUT_HEAD_V1_MODEL_SINCE_VERSION && output->model != NULL) { + zwlr_output_head_v1_send_model(head_resource, output->model); + } + if (version >= ZWLR_OUTPUT_HEAD_V1_SERIAL_NUMBER_SINCE_VERSION && output->serial != NULL) { + zwlr_output_head_v1_send_serial_number(head_resource, output->serial); + } + + struct wlr_output_mode *mode; + wl_list_for_each(mode, &output->modes, link) { + head_send_mode(head, head_resource, mode); + } + + if (head->state.mode == NULL && head->state.enabled) { + // Output doesn't have a fixed mode set. Send a virtual one. + head_send_mode(head, head_resource, NULL); + } + + head_send_state(head, head_resource, HEAD_STATE_ALL); +} + +// Compute state that has changed and sends it to all clients. Then writes the +// new state to the head. +static bool manager_update_head(struct wlr_output_manager_v1 *manager, + struct wlr_output_head_v1 *head, + struct wlr_output_head_v1_state *next) { + struct wlr_output_head_v1_state *current = &head->state; + + uint32_t state = 0; + if (current->enabled != next->enabled) { + state |= HEAD_STATE_ENABLED; + } + if (current->mode != next->mode) { + state |= HEAD_STATE_MODE; + } + if (current->custom_mode.width != next->custom_mode.width || + current->custom_mode.height != next->custom_mode.height || + current->custom_mode.refresh != next->custom_mode.refresh) { + state |= HEAD_STATE_MODE; + } + if (current->x != next->x || current->y != next->y) { + state |= HEAD_STATE_POSITION; + } + if (current->transform != next->transform) { + state |= HEAD_STATE_TRANSFORM; + } + if (current->scale != next->scale) { + state |= HEAD_STATE_SCALE; + } + if (current->adaptive_sync_enabled != next->adaptive_sync_enabled) { + state |= HEAD_STATE_ADAPTIVE_SYNC; + } + + // If a mode was added to wlr_output.modes we need to add the new mode + // to the wlr_output_head + struct wlr_output_mode *mode; + wl_list_for_each(mode, &head->state.output->modes, link) { + bool found = false; + struct wl_resource *mode_resource; + wl_resource_for_each(mode_resource, &head->mode_resources) { + if (mode_from_resource(mode_resource) == mode) { + found = true; + break; + } + } + if (!found) { + struct wl_resource *resource; + wl_resource_for_each(resource, &head->resources) { + head_send_mode(head, resource, mode); + } + } + } + + if (next->mode == NULL && next->enabled && !head_has_custom_mode_resources(head)) { + struct wl_resource *resource; + wl_resource_for_each(resource, &head->resources) { + head_send_mode(head, resource, NULL); + } + } else if (next->mode != NULL) { + head_destroy_custom_mode_resources(head); + } + + if (state != 0) { + *current = *next; + + struct wl_resource *resource; + wl_resource_for_each(resource, &head->resources) { + head_send_state(head, resource, state); + } + } + + return state != 0; +} + +void wlr_output_manager_v1_set_configuration( + struct wlr_output_manager_v1 *manager, + struct wlr_output_configuration_v1 *config) { + bool changed = manager->current_configuration_dirty; + + // Either update or destroy existing heads + struct wlr_output_head_v1 *existing_head, *head_tmp; + wl_list_for_each_safe(existing_head, head_tmp, &manager->heads, link) { + struct wlr_output_configuration_head_v1 *updated_head = + configuration_get_head(config, existing_head->state.output); + if (updated_head != NULL) { + changed |= manager_update_head(manager, + existing_head, &updated_head->state); + config_head_destroy(updated_head); + } else { + head_destroy(existing_head); + changed = true; + } + } + + // Heads remaining in `config` are new heads + + // Move new heads to current config + struct wlr_output_configuration_head_v1 *config_head, *config_head_tmp; + wl_list_for_each_safe(config_head, config_head_tmp, &config->heads, link) { + struct wlr_output_head_v1 *head = + head_create(manager, config_head->state.output); + if (head == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + continue; + } + + head->state = config_head->state; + + struct wl_resource *manager_resource; + wl_resource_for_each(manager_resource, &manager->resources) { + manager_send_head(manager, head, manager_resource); + } + + changed = true; + } + + wlr_output_configuration_v1_destroy(config); + + if (!changed) { + return; + } + + manager->serial = wl_display_next_serial(manager->display); + struct wl_resource *manager_resource; + wl_resource_for_each(manager_resource, &manager->resources) { + zwlr_output_manager_v1_send_done(manager_resource, + manager->serial); + } + manager->current_configuration_dirty = false; +} + +void wlr_output_head_v1_state_apply( + const struct wlr_output_head_v1_state *head_state, + struct wlr_output_state *output_state) { + wlr_output_state_set_enabled(output_state, head_state->enabled); + + if (!head_state->enabled) { + return; + } + + if (head_state->mode != NULL) { + wlr_output_state_set_mode(output_state, head_state->mode); + } else { + wlr_output_state_set_custom_mode(output_state, + head_state->custom_mode.width, + head_state->custom_mode.height, + head_state->custom_mode.refresh); + } + + wlr_output_state_set_scale(output_state, head_state->scale); + wlr_output_state_set_transform(output_state, head_state->transform); + wlr_output_state_set_adaptive_sync_enabled(output_state, + head_state->adaptive_sync_enabled); +} + +struct wlr_backend_output_state *wlr_output_configuration_v1_build_state( + const struct wlr_output_configuration_v1 *config, size_t *states_len) { + *states_len = wl_list_length(&config->heads); + struct wlr_backend_output_state *states = calloc(*states_len, sizeof(states[0])); + if (states == NULL) { + return NULL; + } + + size_t i = 0; + const struct wlr_output_configuration_head_v1 *config_head; + wl_list_for_each(config_head, &config->heads, link) { + struct wlr_backend_output_state *state = &states[i]; + i++; + + state->output = config_head->state.output; + wlr_output_state_init(&state->base); + wlr_output_head_v1_state_apply(&config_head->state, &state->base); + } + + return states; +} diff --git a/3rdparty/wlroots/types/wlr_output_power_management_v1.c b/3rdparty/wlroots/types/wlr_output_power_management_v1.c new file mode 100644 index 0000000000..0730bb2868 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_output_power_management_v1.c @@ -0,0 +1,245 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "wlr-output-power-management-unstable-v1-protocol.h" +#include "util/global.h" + +#define OUTPUT_POWER_MANAGER_V1_VERSION 1 + +static void output_power_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void output_power_destroy(struct wlr_output_power_v1 *output_power) { + if (output_power == NULL) { + return; + } + wl_resource_set_user_data(output_power->resource, NULL); + wl_list_remove(&output_power->output_destroy_listener.link); + wl_list_remove(&output_power->output_commit_listener.link); + wl_list_remove(&output_power->link); + free(output_power); +} + +static const struct zwlr_output_power_v1_interface output_power_impl; + +static struct wlr_output_power_v1 *output_power_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwlr_output_power_v1_interface, + &output_power_impl)); + return wl_resource_get_user_data(resource); +} + +static void output_power_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_output_power_v1 *output_power = + output_power_from_resource(resource); + output_power_destroy(output_power); +} + +static void output_power_handle_output_destroy(struct wl_listener *listener, + void *data) { + struct wlr_output_power_v1 *output_power = + wl_container_of(listener, output_power, output_destroy_listener); + zwlr_output_power_v1_send_failed(output_power->resource); + output_power_destroy(output_power); +} + +static void output_power_v1_send_mode(struct wlr_output_power_v1 *output_power) { + enum zwlr_output_power_v1_mode mode; + + mode = output_power->output->enabled ? ZWLR_OUTPUT_POWER_V1_MODE_ON : + ZWLR_OUTPUT_POWER_V1_MODE_OFF; + zwlr_output_power_v1_send_mode(output_power->resource, mode); +} + +static void output_power_handle_output_commit(struct wl_listener *listener, + void *data) { + struct wlr_output_power_v1 *output_power = + wl_container_of(listener, output_power, output_commit_listener); + struct wlr_output_event_commit *event = data; + if (event->state->committed & WLR_OUTPUT_STATE_ENABLED) { + output_power_v1_send_mode(output_power); + } +} + +static void output_power_handle_set_mode(struct wl_client *client, + struct wl_resource *output_power_resource, + enum zwlr_output_power_v1_mode mode) { + struct wlr_output_power_v1 *output_power = + output_power_from_resource(output_power_resource); + if (output_power == NULL) { + return; + } + + uint32_t version = wl_resource_get_version(output_power_resource); + if (!zwlr_output_power_v1_mode_is_valid(mode, version)) { + wlr_log(WLR_ERROR, "Invalid power mode %d", mode); + wl_resource_post_error(output_power_resource, + ZWLR_OUTPUT_POWER_V1_ERROR_INVALID_MODE, + "Invalid power mode"); + return; + } + + struct wlr_output_power_v1_set_mode_event event = { + .output = output_power->output, + .mode = mode, + }; + wl_signal_emit_mutable(&output_power->manager->events.set_mode, &event); +} + +static const struct zwlr_output_power_v1_interface output_power_impl = { + .destroy = output_power_handle_destroy, + .set_mode = output_power_handle_set_mode, +}; + +static const struct zwlr_output_power_manager_v1_interface + output_power_manager_impl; + +static struct wlr_output_power_manager_v1 *output_power_manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_output_power_manager_v1_interface, &output_power_manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void output_power_manager_get_output_power(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + struct wl_resource *output_resource) { + struct wlr_output_power_manager_v1 *manager = + output_power_manager_from_resource(manager_resource); + struct wlr_output *output = wlr_output_from_resource(output_resource); + + struct wlr_output_power_v1 *output_power = calloc(1, sizeof(*output_power)); + if (output_power == NULL) { + wl_client_post_no_memory(client); + return; + } + output_power->output = output; + output_power->manager = manager; + wl_list_init(&output_power->link); + + uint32_t version = wl_resource_get_version(manager_resource); + output_power->resource = wl_resource_create(client, + &zwlr_output_power_v1_interface, version, id); + if (output_power->resource == NULL) { + free(output_power); + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(output_power->resource, &output_power_impl, + output_power, output_power_handle_resource_destroy); + + if (!output) { + wl_resource_set_user_data(output_power->resource, NULL); + zwlr_output_power_v1_send_failed(output_power->resource); + free(output_power); + return; + } + + wl_signal_add(&output->events.destroy, + &output_power->output_destroy_listener); + output_power->output_destroy_listener.notify = + output_power_handle_output_destroy; + wl_signal_add(&output->events.commit, + &output_power->output_commit_listener); + output_power->output_commit_listener.notify = + output_power_handle_output_commit; + + struct wlr_output_power_v1 *mgmt; + wl_list_for_each(mgmt, &manager->output_powers, link) { + if (mgmt->output == output) { + zwlr_output_power_v1_send_failed(output_power->resource); + output_power_destroy(output_power); + return; + } + } + + wl_list_insert(&manager->output_powers, &output_power->link); + output_power_v1_send_mode(output_power); +} + +static void output_power_manager_destroy(struct wl_client *client, + struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static const struct zwlr_output_power_manager_v1_interface + output_power_manager_impl = { + .get_output_power = output_power_manager_get_output_power, + .destroy = output_power_manager_destroy, +}; + +static void output_power_manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_output_power_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &zwlr_output_power_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &output_power_manager_impl, + manager, NULL); +} + +static void output_power_manager_v1_destroy(struct wlr_output_power_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.set_mode.listener_list)); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + wl_list_remove(&manager->display_destroy.link); + free(manager); +} + +void wlr_output_power_manager_v1_destroy(struct wlr_output_power_manager_v1 *manager, + bool destroy_global_safe) { + output_power_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_output_power_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + output_power_manager_v1_destroy(manager, false); +} + +struct wlr_output_power_manager_v1 *wlr_output_power_manager_v1_create( + struct wl_display *display) { + struct wlr_output_power_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (!manager) { + return NULL; + } + + manager->global = wl_global_create(display, + &zwlr_output_power_manager_v1_interface, + OUTPUT_POWER_MANAGER_V1_VERSION, manager, output_power_manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + wl_signal_init(&manager->events.set_mode); + wl_signal_init(&manager->events.destroy); + + wl_list_init(&manager->output_powers); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_output_swapchain_manager.c b/3rdparty/wlroots/types/wlr_output_swapchain_manager.c new file mode 100644 index 0000000000..d91d5f510c --- /dev/null +++ b/3rdparty/wlroots/types/wlr_output_swapchain_manager.c @@ -0,0 +1,255 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "render/drm_format_set.h" +#include "types/wlr_output.h" + +struct wlr_output_swapchain_manager_output { + struct wlr_output *output; + // Newly allocated swapchain. Can be NULL if the old swapchain is re-used + // or if the output is disabled. + struct wlr_swapchain *new_swapchain; + // True if the output was included in the last successful call to + // wlr_output_swapchain_manager_prepare(). + bool test_success; + // Pending swapchain which will replace the old one when + // wlr_output_swapchain_manager_apply() is called. Can be either a pointer + // to the newly allocated swapchain, or the old swapchain, or NULL. + struct wlr_swapchain *pending_swapchain; +}; + +void wlr_output_swapchain_manager_init(struct wlr_output_swapchain_manager *manager, + struct wlr_backend *backend) { + *manager = (struct wlr_output_swapchain_manager){ + .backend = backend, + }; +} + +static struct wlr_output_swapchain_manager_output *manager_get_output( + struct wlr_output_swapchain_manager *manager, struct wlr_output *output) { + struct wlr_output_swapchain_manager_output *manager_output; + wl_array_for_each(manager_output, &manager->outputs) { + if (manager_output->output == output) { + return manager_output; + } + } + return NULL; +} + +static struct wlr_output_swapchain_manager_output *manager_get_or_add_output( + struct wlr_output_swapchain_manager *manager, struct wlr_output *output) { + struct wlr_output_swapchain_manager_output *manager_output = manager_get_output(manager, output); + if (manager_output != NULL) { + return manager_output; + } + + manager_output = wl_array_add(&manager->outputs, sizeof(*manager_output)); + if (manager_output == NULL) { + return NULL; + } + *manager_output = (struct wlr_output_swapchain_manager_output){ + .output = output, + }; + return manager_output; +} + +static bool swapchain_is_compatible(struct wlr_swapchain *swapchain, + int width, int height, const struct wlr_drm_format *format) { + if (swapchain == NULL) { + return false; + } + if (swapchain->width != width || swapchain->height != height) { + return false; + } + if (swapchain->format.format != format->format || swapchain->format.len != format->len) { + return false; + } + assert(format->len > 0); + return memcmp(swapchain->format.modifiers, format->modifiers, format->len * sizeof(format->modifiers[0])) == 0; +} + +static struct wlr_swapchain *manager_output_get_swapchain( + struct wlr_output_swapchain_manager_output *manager_output, + int width, int height, const struct wlr_drm_format *format) { + struct wlr_output *output = manager_output->output; + + if (swapchain_is_compatible(output->swapchain, width, height, format)) { + return output->swapchain; + } + if (swapchain_is_compatible(manager_output->new_swapchain, width, height, format)) { + return manager_output->new_swapchain; + } + + struct wlr_swapchain *swapchain = wlr_swapchain_create(output->allocator, width, height, format); + if (swapchain == NULL) { + return NULL; + } + wlr_swapchain_destroy(manager_output->new_swapchain); + manager_output->new_swapchain = swapchain; + return swapchain; +} + +static bool manager_output_prepare(struct wlr_output_swapchain_manager_output *manager_output, + struct wlr_output_state *state, bool explicit_modifiers) { + struct wlr_output *output = manager_output->output; + struct wlr_allocator *allocator = output->allocator; + assert(allocator != NULL); + + if (!output_pending_enabled(output, state)) { + manager_output->pending_swapchain = NULL; + return true; + } + + int width, height; + output_pending_resolution(output, state, &width, &height); + if (width == 0 || height == 0) { + wlr_log(WLR_DEBUG, "Cannot allocate swapchain for zero resolution (%dx%d)", width, height); + return false; + } + + uint32_t fmt = output->render_format; + if (state->committed & WLR_OUTPUT_STATE_RENDER_FORMAT) { + fmt = state->render_format; + } + + const struct wlr_drm_format_set *display_formats = + wlr_output_get_primary_formats(output, allocator->buffer_caps); + struct wlr_drm_format format = {0}; + if (!output_pick_format(output, display_formats, &format, fmt)) { + return false; + } + + if (!explicit_modifiers && (format.len != 1 || format.modifiers[0] != DRM_FORMAT_MOD_LINEAR)) { + if (!wlr_drm_format_has(&format, DRM_FORMAT_MOD_INVALID)) { + wlr_log(WLR_DEBUG, "Implicit modifiers not supported"); + wlr_drm_format_finish(&format); + return false; + } + + format.len = 0; + if (!wlr_drm_format_add(&format, DRM_FORMAT_MOD_INVALID)) { + wlr_log(WLR_DEBUG, "Failed to add implicit modifier to format"); + wlr_drm_format_finish(&format); + return false; + } + } + + struct wlr_swapchain *swapchain = + manager_output_get_swapchain(manager_output, width, height, &format); + wlr_drm_format_finish(&format); + if (swapchain == NULL) { + return false; + } + + struct wlr_buffer *buffer = wlr_swapchain_acquire(swapchain); + if (buffer == NULL) { + return false; + } + + wlr_output_state_set_buffer(state, buffer); + wlr_buffer_unlock(buffer); + manager_output->pending_swapchain = swapchain; + return true; +} + +static bool manager_test(struct wlr_output_swapchain_manager *manager, + struct wlr_backend_output_state *states, size_t states_len, + bool explicit_modifiers) { + wlr_log(WLR_DEBUG, "Preparing test commit for %zu outputs with %s modifiers", + states_len, explicit_modifiers ? "explicit": "implicit"); + + struct wlr_output_swapchain_manager_output *manager_output; + wl_array_for_each(manager_output, &manager->outputs) { + manager_output->test_success = false; + } + + for (size_t i = 0; i < states_len; i++) { + struct wlr_backend_output_state *state = &states[i]; + struct wlr_output_swapchain_manager_output *manager_output = + manager_get_or_add_output(manager, state->output); + if (manager_output == NULL) { + return false; + } + if (!manager_output_prepare(manager_output, &state->base, explicit_modifiers)) { + return false; + } + } + + bool ok = wlr_backend_test(manager->backend, states, states_len); + wlr_log(WLR_DEBUG, "Test commit for %zu outputs %s", + states_len, ok ? "succeeded" : "failed"); + if (!ok) { + return false; + } + + for (size_t i = 0; i < states_len; i++) { + struct wlr_output_swapchain_manager_output *manager_output = + manager_get_output(manager, states[i].output); + assert(manager_output != NULL); + manager_output->test_success = true; + } + + return true; +} + +bool wlr_output_swapchain_manager_prepare(struct wlr_output_swapchain_manager *manager, + const struct wlr_backend_output_state *states, size_t states_len) { + bool ok = false; + struct wlr_backend_output_state *pending = malloc(states_len * sizeof(states[0])); + if (pending == NULL) { + return false; + } + for (size_t i = 0; i < states_len; i++) { + pending[i] = states[i]; + pending[i].base.buffer = NULL; + } + + ok = manager_test(manager, pending, states_len, true); + if (!ok) { + ok = manager_test(manager, pending, states_len, false); + } + + for (size_t i = 0; i < states_len; i++) { + wlr_buffer_unlock(pending[i].base.buffer); + } + free(pending); + + return ok; +} + +struct wlr_swapchain *wlr_output_swapchain_manager_get_swapchain( + struct wlr_output_swapchain_manager *manager, struct wlr_output *output) { + struct wlr_output_swapchain_manager_output *manager_output = + manager_get_output(manager, output); + assert(manager_output != NULL && manager_output->test_success); + return manager_output->pending_swapchain; +} + +void wlr_output_swapchain_manager_apply(struct wlr_output_swapchain_manager *manager) { + struct wlr_output_swapchain_manager_output *manager_output; + wl_array_for_each(manager_output, &manager->outputs) { + struct wlr_output *output = manager_output->output; + if (!manager_output->test_success || manager_output->pending_swapchain == output->swapchain) { + continue; + } + + wlr_swapchain_destroy(output->swapchain); + output->swapchain = manager_output->new_swapchain; + manager_output->new_swapchain = NULL; + manager_output->test_success = false; + } +} + +void wlr_output_swapchain_manager_finish(struct wlr_output_swapchain_manager *manager) { + struct wlr_output_swapchain_manager_output *manager_output; + wl_array_for_each(manager_output, &manager->outputs) { + wlr_swapchain_destroy(manager_output->new_swapchain); + } + wl_array_release(&manager->outputs); +} diff --git a/3rdparty/wlroots/types/wlr_pointer.c b/3rdparty/wlroots/types/wlr_pointer.c new file mode 100644 index 0000000000..e99981907d --- /dev/null +++ b/3rdparty/wlroots/types/wlr_pointer.c @@ -0,0 +1,82 @@ +#include +#include +#include +#include +#include +#include + +#include "interfaces/wlr_input_device.h" +#include "util/set.h" +#include "util/time.h" + +struct wlr_pointer *wlr_pointer_from_input_device( + struct wlr_input_device *input_device) { + assert(input_device->type == WLR_INPUT_DEVICE_POINTER); + return wl_container_of(input_device, (struct wlr_pointer *)NULL, base); +} + +void wlr_pointer_init(struct wlr_pointer *pointer, + const struct wlr_pointer_impl *impl, const char *name) { + *pointer = (struct wlr_pointer){ + .impl = impl, + }; + wlr_input_device_init(&pointer->base, WLR_INPUT_DEVICE_POINTER, name); + + wl_signal_init(&pointer->events.motion); + wl_signal_init(&pointer->events.motion_absolute); + wl_signal_init(&pointer->events.button); + wl_signal_init(&pointer->events.axis); + wl_signal_init(&pointer->events.frame); + wl_signal_init(&pointer->events.swipe_begin); + wl_signal_init(&pointer->events.swipe_update); + wl_signal_init(&pointer->events.swipe_end); + wl_signal_init(&pointer->events.pinch_begin); + wl_signal_init(&pointer->events.pinch_update); + wl_signal_init(&pointer->events.pinch_end); + wl_signal_init(&pointer->events.hold_begin); + wl_signal_init(&pointer->events.hold_end); +} + +void wlr_pointer_finish(struct wlr_pointer *pointer) { + int64_t time_msec = get_current_time_msec(); + while (pointer->button_count > 0) { + struct wlr_pointer_button_event event = { + .pointer = pointer, + .time_msec = time_msec, + .button = pointer->buttons[pointer->button_count - 1], + .state = WL_POINTER_BUTTON_STATE_RELEASED, + }; + wlr_pointer_notify_button(pointer, &event); + } + + wlr_input_device_finish(&pointer->base); + + assert(wl_list_empty(&pointer->events.motion.listener_list)); + assert(wl_list_empty(&pointer->events.motion_absolute.listener_list)); + assert(wl_list_empty(&pointer->events.button.listener_list)); + assert(wl_list_empty(&pointer->events.axis.listener_list)); + assert(wl_list_empty(&pointer->events.frame.listener_list)); + assert(wl_list_empty(&pointer->events.swipe_begin.listener_list)); + assert(wl_list_empty(&pointer->events.swipe_update.listener_list)); + assert(wl_list_empty(&pointer->events.swipe_end.listener_list)); + assert(wl_list_empty(&pointer->events.pinch_begin.listener_list)); + assert(wl_list_empty(&pointer->events.pinch_update.listener_list)); + assert(wl_list_empty(&pointer->events.pinch_end.listener_list)); + assert(wl_list_empty(&pointer->events.hold_begin.listener_list)); + assert(wl_list_empty(&pointer->events.hold_end.listener_list)); + + free(pointer->output_name); +} + +void wlr_pointer_notify_button(struct wlr_pointer *pointer, + struct wlr_pointer_button_event *event) { + if (event->state == WL_POINTER_BUTTON_STATE_PRESSED) { + set_add(pointer->buttons, &pointer->button_count, + WLR_POINTER_BUTTONS_CAP, event->button); + } else { + set_remove(pointer->buttons, &pointer->button_count, + WLR_POINTER_BUTTONS_CAP, event->button); + } + + wl_signal_emit_mutable(&pointer->events.button, event); +} diff --git a/3rdparty/wlroots/types/wlr_pointer_constraints_v1.c b/3rdparty/wlroots/types/wlr_pointer_constraints_v1.c new file mode 100644 index 0000000000..740323335e --- /dev/null +++ b/3rdparty/wlroots/types/wlr_pointer_constraints_v1.c @@ -0,0 +1,427 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "pointer-constraints-unstable-v1-protocol.h" +#include "util/global.h" + +static const struct zwp_locked_pointer_v1_interface locked_pointer_impl; +static const struct zwp_confined_pointer_v1_interface confined_pointer_impl; +static const struct zwp_pointer_constraints_v1_interface pointer_constraints_impl; +static void pointer_constraint_destroy(struct wlr_pointer_constraint_v1 *constraint); + +static struct wlr_pointer_constraint_v1 *pointer_constraint_from_resource( + struct wl_resource *resource) { + assert( + wl_resource_instance_of( + resource, &zwp_confined_pointer_v1_interface, + &confined_pointer_impl) || + wl_resource_instance_of( + resource, &zwp_locked_pointer_v1_interface, + &locked_pointer_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_pointer_constraints_v1 *pointer_constraints_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwp_pointer_constraints_v1_interface, + &pointer_constraints_impl)); + return wl_resource_get_user_data(resource); +} + +static void resource_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void pointer_constraint_destroy(struct wlr_pointer_constraint_v1 *constraint) { + if (constraint == NULL || constraint->destroying) { + return; + } + + // Calling wlr_pointer_constraint_v1_send_deactivated() for a oneshot constraint + // that is being destroyed results in another pointer_constraint_destroy() call. + // Avoid finalizing the state twice by setting a flag. + constraint->destroying = true; + + wlr_log(WLR_DEBUG, "destroying constraint %p", constraint); + + wl_signal_emit_mutable(&constraint->events.destroy, constraint); + + assert(wl_list_empty(&constraint->events.set_region.listener_list)); + assert(wl_list_empty(&constraint->events.destroy.listener_list)); + + wl_resource_set_user_data(constraint->resource, NULL); + wlr_surface_synced_finish(&constraint->synced); + wl_list_remove(&constraint->link); + wl_list_remove(&constraint->surface_destroy.link); + wl_list_remove(&constraint->seat_destroy.link); + pixman_region32_fini(&constraint->region); + free(constraint); +} + +static void pointer_constraint_destroy_resource(struct wl_resource *resource) { + struct wlr_pointer_constraint_v1 *constraint = + pointer_constraint_from_resource(resource); + + pointer_constraint_destroy(constraint); +} + +static void pointer_constraint_handle_set_region(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *region_resource) { + struct wlr_pointer_constraint_v1 *constraint = + pointer_constraint_from_resource(resource); + if (constraint == NULL) { + return; + } + + pixman_region32_clear(&constraint->pending.region); + if (region_resource) { + const pixman_region32_t *region = wlr_region_from_resource(region_resource); + pixman_region32_copy(&constraint->pending.region, region); + } + + constraint->pending.committed |= WLR_POINTER_CONSTRAINT_V1_STATE_REGION; +} + +static void pointer_constraint_set_cursor_position_hint(struct wl_client *client, + struct wl_resource *resource, wl_fixed_t x, wl_fixed_t y) { + struct wlr_pointer_constraint_v1 *constraint = + pointer_constraint_from_resource(resource); + if (constraint == NULL) { + return; + } + + constraint->pending.cursor_hint.enabled = true; + constraint->pending.cursor_hint.x = wl_fixed_to_double(x); + constraint->pending.cursor_hint.y = wl_fixed_to_double(y); + constraint->pending.committed |= WLR_POINTER_CONSTRAINT_V1_STATE_CURSOR_HINT; +} + +// Returns true if the region has changed +static bool update_region(struct wlr_pointer_constraint_v1 *constraint) { + pixman_region32_t region; + pixman_region32_init(®ion); + + if (!pixman_region32_empty(&constraint->current.region)) { + pixman_region32_intersect(®ion, + &constraint->surface->input_region, &constraint->current.region); + } else { + pixman_region32_copy(®ion, &constraint->surface->input_region); + } + + if (pixman_region32_equal(®ion, &constraint->region)) { + pixman_region32_fini(®ion); + return false; + } + + pixman_region32_fini(&constraint->region); + constraint->region = region; + + return true; +} + +static void handle_surface_destroy(struct wl_listener *listener, void *data) { + struct wlr_pointer_constraint_v1 *constraint = + wl_container_of(listener, constraint, surface_destroy); + + pointer_constraint_destroy(constraint); +} + +static void handle_seat_destroy(struct wl_listener *listener, void *data) { + struct wlr_pointer_constraint_v1 *constraint = + wl_container_of(listener, constraint, seat_destroy); + + pointer_constraint_destroy(constraint); +} + +static const struct zwp_confined_pointer_v1_interface confined_pointer_impl = { + .destroy = resource_destroy, + .set_region = pointer_constraint_handle_set_region, +}; + +static const struct zwp_locked_pointer_v1_interface locked_pointer_impl = { + .destroy = resource_destroy, + .set_region = pointer_constraint_handle_set_region, + .set_cursor_position_hint = pointer_constraint_set_cursor_position_hint, +}; + +static void surface_synced_init_state(void *_state) { + struct wlr_pointer_constraint_v1_state *state = _state; + pixman_region32_init(&state->region); +} + +static void surface_synced_finish_state(void *_state) { + struct wlr_pointer_constraint_v1_state *state = _state; + pixman_region32_fini(&state->region); +} + +static void surface_synced_move_state(void *_dst, void *_src) { + struct wlr_pointer_constraint_v1_state *dst = _dst, *src = _src; + + if (src->committed & WLR_POINTER_CONSTRAINT_V1_STATE_REGION) { + pixman_region32_copy(&dst->region, &src->region); + } + if (src->committed & WLR_POINTER_CONSTRAINT_V1_STATE_CURSOR_HINT) { + dst->cursor_hint = src->cursor_hint; + } + + dst->committed = src->committed; + src->committed = 0; +} + +static void surface_synced_commit(struct wlr_surface_synced *synced) { + struct wlr_pointer_constraint_v1 *constraint = wl_container_of(synced, constraint, synced); + + if (update_region(constraint)) { + wl_signal_emit_mutable(&constraint->events.set_region, NULL); + } +} + +static const struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(struct wlr_pointer_constraint_v1_state), + .init_state = surface_synced_init_state, + .finish_state = surface_synced_finish_state, + .move_state = surface_synced_move_state, + .commit = surface_synced_commit, +}; + +static void pointer_constraint_create(struct wl_client *client, + struct wl_resource *pointer_constraints_resource, uint32_t id, + struct wl_resource *surface_resource, + struct wl_resource *pointer_resource, + struct wl_resource *region_resource, + enum zwp_pointer_constraints_v1_lifetime lifetime, + enum wlr_pointer_constraint_v1_type type) { + struct wlr_pointer_constraints_v1 *pointer_constraints = + pointer_constraints_from_resource(pointer_constraints_resource); + + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + struct wlr_seat_client *seat_client = + wlr_seat_client_from_pointer_resource(pointer_resource); + + uint32_t version = wl_resource_get_version(pointer_constraints_resource); + + bool locked_pointer = type == WLR_POINTER_CONSTRAINT_V1_LOCKED; + + struct wl_resource *resource = locked_pointer ? + wl_resource_create(client, &zwp_locked_pointer_v1_interface, version, id) : + wl_resource_create(client, &zwp_confined_pointer_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + + void *impl = locked_pointer ? + (void *)&locked_pointer_impl : (void *)&confined_pointer_impl; + wl_resource_set_implementation(resource, impl, NULL, + pointer_constraint_destroy_resource); + + if (seat_client == NULL) { + // Leave the resource inert + return; + } + + struct wlr_seat *seat = seat_client->seat; + + if (wlr_pointer_constraints_v1_constraint_for_surface(pointer_constraints, + surface, seat)) { + wl_resource_destroy(resource); + wl_resource_post_error(pointer_constraints_resource, + ZWP_POINTER_CONSTRAINTS_V1_ERROR_ALREADY_CONSTRAINED, + "a pointer constraint with a wl_pointer of the same wl_seat" + " is already on this surface"); + return; + } + + struct wlr_pointer_constraint_v1 *constraint = calloc(1, sizeof(*constraint)); + if (constraint == NULL) { + wl_resource_destroy(resource); + wl_client_post_no_memory(client); + return; + } + + if (!wlr_surface_synced_init(&constraint->synced, surface, + &surface_synced_impl, &constraint->pending, &constraint->current)) { + free(constraint); + wl_resource_destroy(resource); + wl_client_post_no_memory(client); + return; + } + + constraint->resource = resource; + constraint->surface = surface; + constraint->seat = seat; + constraint->lifetime = lifetime; + constraint->type = type; + constraint->pointer_constraints = pointer_constraints; + + wl_signal_init(&constraint->events.set_region); + wl_signal_init(&constraint->events.destroy); + + pixman_region32_init(&constraint->region); + + if (region_resource) { + pixman_region32_copy(&constraint->current.region, + wlr_region_from_resource(region_resource)); + update_region(constraint); + } + + constraint->surface_destroy.notify = handle_surface_destroy; + wl_signal_add(&surface->events.destroy, &constraint->surface_destroy); + + constraint->seat_destroy.notify = handle_seat_destroy; + wl_signal_add(&seat->events.destroy, &constraint->seat_destroy); + + wl_resource_set_user_data(resource, constraint); + + wlr_log(WLR_DEBUG, "new %s_pointer %p (res %p)", + locked_pointer ? "locked" : "confined", + constraint, constraint->resource); + + wl_list_insert(&pointer_constraints->constraints, &constraint->link); + + wl_signal_emit_mutable(&pointer_constraints->events.new_constraint, + constraint); +} + +static void pointer_constraints_lock_pointer(struct wl_client *client, + struct wl_resource *cons_resource, uint32_t id, + struct wl_resource *surface, struct wl_resource *pointer, + struct wl_resource *region, enum zwp_pointer_constraints_v1_lifetime lifetime) { + pointer_constraint_create(client, cons_resource, id, surface, pointer, + region, lifetime, WLR_POINTER_CONSTRAINT_V1_LOCKED); +} + +static void pointer_constraints_confine_pointer(struct wl_client *client, + struct wl_resource *cons_resource, uint32_t id, + struct wl_resource *surface, struct wl_resource *pointer, + struct wl_resource *region, + enum zwp_pointer_constraints_v1_lifetime lifetime) { + pointer_constraint_create(client, cons_resource, id, surface, pointer, + region, lifetime, WLR_POINTER_CONSTRAINT_V1_CONFINED); +} + +static const struct zwp_pointer_constraints_v1_interface + pointer_constraints_impl = { + .destroy = resource_destroy, + .lock_pointer = pointer_constraints_lock_pointer, + .confine_pointer = pointer_constraints_confine_pointer, +}; + +static void pointer_constraints_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_pointer_constraints_v1 *pointer_constraints = data; + + struct wl_resource *resource = wl_resource_create(client, + &zwp_pointer_constraints_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + + wl_resource_set_implementation(resource, &pointer_constraints_impl, + pointer_constraints, NULL); +} + +static void pointer_constraints_v1_destroy(struct wlr_pointer_constraints_v1 *pointer_constraints, + bool destroy_global_safe) { + wl_signal_emit_mutable(&pointer_constraints->events.destroy, NULL); + + assert(wl_list_empty(&pointer_constraints->events.destroy.listener_list)); + assert(wl_list_empty(&pointer_constraints->events.new_constraint.listener_list)); + + wl_list_remove(&pointer_constraints->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(pointer_constraints->global); + } else { + wl_global_destroy(pointer_constraints->global); + } + free(pointer_constraints); +} + +void wlr_pointer_constraints_v1_destroy(struct wlr_pointer_constraints_v1 *pointer_constraints, + bool destroy_global_safe) { + pointer_constraints_v1_destroy(pointer_constraints, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_pointer_constraints_v1 *pointer_constraints = + wl_container_of(listener, pointer_constraints, display_destroy); + pointer_constraints_v1_destroy(pointer_constraints, false); +} + +struct wlr_pointer_constraints_v1 *wlr_pointer_constraints_v1_create( + struct wl_display *display) { + struct wlr_pointer_constraints_v1 *pointer_constraints = + calloc(1, sizeof(*pointer_constraints)); + if (!pointer_constraints) { + return NULL; + } + + struct wl_global *wl_global = wl_global_create(display, + &zwp_pointer_constraints_v1_interface, 1, pointer_constraints, + pointer_constraints_bind); + if (!wl_global) { + free(pointer_constraints); + return NULL; + } + pointer_constraints->global = wl_global; + + wl_list_init(&pointer_constraints->constraints); + + wl_signal_init(&pointer_constraints->events.destroy); + wl_signal_init(&pointer_constraints->events.new_constraint); + + pointer_constraints->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, + &pointer_constraints->display_destroy); + + return pointer_constraints; +} + +struct wlr_pointer_constraint_v1 * + wlr_pointer_constraints_v1_constraint_for_surface( + struct wlr_pointer_constraints_v1 *pointer_constraints, + struct wlr_surface *surface, struct wlr_seat *seat) { + struct wlr_pointer_constraint_v1 *constraint; + wl_list_for_each(constraint, &pointer_constraints->constraints, link) { + if (constraint->surface == surface && constraint->seat == seat) { + return constraint; + } + } + + return NULL; +} + +void wlr_pointer_constraint_v1_send_activated( + struct wlr_pointer_constraint_v1 *constraint) { + wlr_log(WLR_DEBUG, "constrained %p", constraint); + if (constraint->type == WLR_POINTER_CONSTRAINT_V1_LOCKED) { + zwp_locked_pointer_v1_send_locked(constraint->resource); + } else { + zwp_confined_pointer_v1_send_confined(constraint->resource); + } +} + +void wlr_pointer_constraint_v1_send_deactivated( + struct wlr_pointer_constraint_v1 *constraint) { + wlr_log(WLR_DEBUG, "unconstrained %p", constraint); + if (constraint->type == WLR_POINTER_CONSTRAINT_V1_LOCKED) { + zwp_locked_pointer_v1_send_unlocked(constraint->resource); + } else { + zwp_confined_pointer_v1_send_unconfined(constraint->resource); + } + + if (constraint->lifetime == + ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_ONESHOT) { + pointer_constraint_destroy(constraint); + } +} diff --git a/3rdparty/wlroots/types/wlr_pointer_gestures_v1.c b/3rdparty/wlroots/types/wlr_pointer_gestures_v1.c new file mode 100644 index 0000000000..5df889e57a --- /dev/null +++ b/3rdparty/wlroots/types/wlr_pointer_gestures_v1.c @@ -0,0 +1,449 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "pointer-gestures-unstable-v1-protocol.h" +#include "util/global.h" + +#define POINTER_GESTURES_VERSION 3 + +static void resource_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void resource_remove_from_list(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static const struct zwp_pointer_gestures_v1_interface gestures_impl; +static const struct zwp_pointer_gesture_swipe_v1_interface swipe_impl; +static const struct zwp_pointer_gesture_pinch_v1_interface pinch_impl; +static const struct zwp_pointer_gesture_hold_v1_interface hold_impl; + +static struct wlr_pointer_gestures_v1 *pointer_gestures_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwp_pointer_gestures_v1_interface, &gestures_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_seat *seat_from_pointer_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwp_pointer_gesture_swipe_v1_interface, &swipe_impl) || + wl_resource_instance_of(resource, + &zwp_pointer_gesture_pinch_v1_interface, &pinch_impl) || + wl_resource_instance_of(resource, + &zwp_pointer_gesture_hold_v1_interface, &hold_impl)); + return wl_resource_get_user_data(resource); +} + +void wlr_pointer_gestures_v1_send_swipe_begin( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + uint32_t fingers) { + struct wlr_surface *focus = seat->pointer_state.focused_surface; + struct wlr_seat_client *focus_seat_client = + seat->pointer_state.focused_client; + if (focus == NULL || focus_seat_client == NULL) { + return; + } + + struct wl_client *focus_client = focus_seat_client->client; + uint32_t serial = wlr_seat_client_next_serial(focus_seat_client); + + struct wl_resource *gesture; + wl_resource_for_each(gesture, &gestures->swipes) { + struct wlr_seat *gesture_seat = seat_from_pointer_resource(gesture); + struct wl_client *gesture_client = wl_resource_get_client(gesture); + if (gesture_seat != seat || gesture_client != focus_client) { + continue; + } + zwp_pointer_gesture_swipe_v1_send_begin(gesture, serial, + time_msec, focus->resource, fingers); + } +} + +void wlr_pointer_gestures_v1_send_swipe_update( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + double dx, + double dy) { + struct wlr_surface *focus = seat->pointer_state.focused_surface; + struct wlr_seat_client *focus_seat_client = + seat->pointer_state.focused_client; + if (focus == NULL || focus_seat_client == NULL) { + return; + } + + struct wl_client *focus_client = focus_seat_client->client; + + struct wl_resource *gesture; + wl_resource_for_each(gesture, &gestures->swipes) { + struct wlr_seat *gesture_seat = seat_from_pointer_resource(gesture); + struct wl_client *gesture_client = wl_resource_get_client(gesture); + if (gesture_seat != seat || gesture_client != focus_client) { + continue; + } + zwp_pointer_gesture_swipe_v1_send_update(gesture, time_msec, + wl_fixed_from_double(dx), wl_fixed_from_double(dy)); + } +} + +void wlr_pointer_gestures_v1_send_swipe_end( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + bool cancelled) { + struct wlr_surface *focus = seat->pointer_state.focused_surface; + struct wlr_seat_client *focus_seat_client = + seat->pointer_state.focused_client; + if (focus == NULL || focus_seat_client == NULL) { + return; + } + + struct wl_client *focus_client = focus_seat_client->client; + uint32_t serial = wlr_seat_client_next_serial(focus_seat_client); + + struct wl_resource *gesture; + wl_resource_for_each(gesture, &gestures->swipes) { + struct wlr_seat *gesture_seat = seat_from_pointer_resource(gesture); + struct wl_client *gesture_client = wl_resource_get_client(gesture); + if (gesture_seat != seat || gesture_client != focus_client) { + continue; + } + zwp_pointer_gesture_swipe_v1_send_end(gesture, serial, + time_msec, cancelled); + } +} + +static const struct zwp_pointer_gesture_swipe_v1_interface swipe_impl = { + .destroy = resource_handle_destroy, +}; + +static void get_swipe_gesture(struct wl_client *client, + struct wl_resource *gestures_resource, + uint32_t id, + struct wl_resource *pointer_resource) { + struct wlr_seat_client *seat_client = + wlr_seat_client_from_pointer_resource(pointer_resource); + struct wlr_seat *seat = NULL; + + if (seat_client != NULL) { + seat = seat_client->seat; + } + // Otherwise, the resource will be inert + // (NULL seat, so all seat comparisons will fail) + + struct wlr_pointer_gestures_v1 *gestures = + pointer_gestures_from_resource(gestures_resource); + + struct wl_resource *gesture = wl_resource_create(client, + &zwp_pointer_gesture_swipe_v1_interface, + wl_resource_get_version(gestures_resource), + id); + if (gesture == NULL) { + wl_client_post_no_memory(client); + return; + } + + wl_resource_set_implementation(gesture, &swipe_impl, seat, + resource_remove_from_list); + wl_list_insert(&gestures->swipes, wl_resource_get_link(gesture)); +} + +void wlr_pointer_gestures_v1_send_pinch_begin( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + uint32_t fingers) { + struct wlr_surface *focus = seat->pointer_state.focused_surface; + struct wlr_seat_client *focus_seat_client = + seat->pointer_state.focused_client; + if (focus == NULL || focus_seat_client == NULL) { + return; + } + + struct wl_client *focus_client = focus_seat_client->client; + uint32_t serial = wlr_seat_client_next_serial(focus_seat_client); + + struct wl_resource *gesture; + wl_resource_for_each(gesture, &gestures->pinches) { + struct wlr_seat *gesture_seat = seat_from_pointer_resource(gesture); + struct wl_client *gesture_client = wl_resource_get_client(gesture); + if (gesture_seat != seat || gesture_client != focus_client) { + continue; + } + zwp_pointer_gesture_pinch_v1_send_begin(gesture, serial, + time_msec, focus->resource, fingers); + } +} + +void wlr_pointer_gestures_v1_send_pinch_update( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + double dx, + double dy, + double scale, + double rotation) { + struct wlr_surface *focus = seat->pointer_state.focused_surface; + struct wlr_seat_client *focus_seat_client = + seat->pointer_state.focused_client; + if (focus == NULL || focus_seat_client == NULL) { + return; + } + + struct wl_client *focus_client = focus_seat_client->client; + + struct wl_resource *gesture; + wl_resource_for_each(gesture, &gestures->pinches) { + struct wlr_seat *gesture_seat = seat_from_pointer_resource(gesture); + struct wl_client *gesture_client = wl_resource_get_client(gesture); + if (gesture_seat != seat || gesture_client != focus_client) { + continue; + } + zwp_pointer_gesture_pinch_v1_send_update(gesture, time_msec, + wl_fixed_from_double(dx), wl_fixed_from_double(dy), + wl_fixed_from_double(scale), + wl_fixed_from_double(rotation)); + } +} + +void wlr_pointer_gestures_v1_send_pinch_end( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + bool cancelled) { + struct wlr_surface *focus = seat->pointer_state.focused_surface; + struct wlr_seat_client *focus_seat_client = + seat->pointer_state.focused_client; + if (focus == NULL || focus_seat_client == NULL) { + return; + } + + struct wl_client *focus_client = focus_seat_client->client; + uint32_t serial = wlr_seat_client_next_serial(focus_seat_client); + + struct wl_resource *gesture; + wl_resource_for_each(gesture, &gestures->pinches) { + struct wlr_seat *gesture_seat = seat_from_pointer_resource(gesture); + struct wl_client *gesture_client = wl_resource_get_client(gesture); + if (gesture_seat != seat || gesture_client != focus_client) { + continue; + } + zwp_pointer_gesture_pinch_v1_send_end(gesture, serial, + time_msec, cancelled); + } +} + +static const struct zwp_pointer_gesture_pinch_v1_interface pinch_impl = { + .destroy = resource_handle_destroy, +}; + +static void get_pinch_gesture(struct wl_client *client, + struct wl_resource *gestures_resource, + uint32_t id, + struct wl_resource *pointer_resource) { + struct wlr_seat_client *seat_client = + wlr_seat_client_from_pointer_resource(pointer_resource); + struct wlr_seat *seat = NULL; + + if (seat_client != NULL) { + seat = seat_client->seat; + } + // Otherwise, the resource will be inert + // (NULL seat, so all seat comparisons will fail) + + struct wlr_pointer_gestures_v1 *gestures = + pointer_gestures_from_resource(gestures_resource); + + struct wl_resource *gesture = wl_resource_create(client, + &zwp_pointer_gesture_pinch_v1_interface, + wl_resource_get_version(gestures_resource), + id); + if (gesture == NULL) { + wl_client_post_no_memory(client); + return; + } + + wl_resource_set_implementation(gesture, &pinch_impl, seat, + resource_remove_from_list); + wl_list_insert(&gestures->pinches, wl_resource_get_link(gesture)); +} + +static void pointer_gestures_release(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +void wlr_pointer_gestures_v1_send_hold_begin( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + uint32_t fingers) { + struct wlr_surface *focus = seat->pointer_state.focused_surface; + struct wlr_seat_client *focus_seat_client = + seat->pointer_state.focused_client; + if (focus == NULL || focus_seat_client == NULL) { + return; + } + + struct wl_client *focus_client = focus_seat_client->client; + uint32_t serial = wlr_seat_client_next_serial(focus_seat_client); + + struct wl_resource *gesture; + wl_resource_for_each(gesture, &gestures->holds) { + struct wlr_seat *gesture_seat = seat_from_pointer_resource(gesture); + struct wl_client *gesture_client = wl_resource_get_client(gesture); + if (gesture_seat != seat || gesture_client != focus_client) { + continue; + } + zwp_pointer_gesture_hold_v1_send_begin(gesture, serial, + time_msec, focus->resource, fingers); + } +} + +void wlr_pointer_gestures_v1_send_hold_end( + struct wlr_pointer_gestures_v1 *gestures, + struct wlr_seat *seat, + uint32_t time_msec, + bool cancelled) { + struct wlr_surface *focus = seat->pointer_state.focused_surface; + struct wlr_seat_client *focus_seat_client = + seat->pointer_state.focused_client; + if (focus == NULL || focus_seat_client == NULL) { + return; + } + + struct wl_client *focus_client = focus_seat_client->client; + uint32_t serial = wlr_seat_client_next_serial(focus_seat_client); + + struct wl_resource *gesture; + wl_resource_for_each(gesture, &gestures->holds) { + struct wlr_seat *gesture_seat = seat_from_pointer_resource(gesture); + struct wl_client *gesture_client = wl_resource_get_client(gesture); + if (gesture_seat != seat || gesture_client != focus_client) { + continue; + } + zwp_pointer_gesture_hold_v1_send_end(gesture, serial, + time_msec, cancelled); + } +} + +static const struct zwp_pointer_gesture_hold_v1_interface hold_impl = { + .destroy = resource_handle_destroy, +}; + +static void get_hold_gesture(struct wl_client *client, + struct wl_resource *gestures_resource, + uint32_t id, + struct wl_resource *pointer_resource) { + struct wlr_seat_client *seat_client = + wlr_seat_client_from_pointer_resource(pointer_resource); + struct wlr_seat *seat = NULL; + + if (seat_client != NULL) { + seat = seat_client->seat; + } + // Otherwise, the resource will be inert + // (NULL seat, so all seat comparisons will fail) + + struct wlr_pointer_gestures_v1 *gestures = + pointer_gestures_from_resource(gestures_resource); + + struct wl_resource *gesture = wl_resource_create(client, + &zwp_pointer_gesture_hold_v1_interface, + wl_resource_get_version(gestures_resource), + id); + if (gesture == NULL) { + wl_client_post_no_memory(client); + return; + } + + wl_resource_set_implementation(gesture, &hold_impl, seat, + resource_remove_from_list); + wl_list_insert(&gestures->holds, wl_resource_get_link(gesture)); +} + +static const struct zwp_pointer_gestures_v1_interface gestures_impl = { + .get_swipe_gesture = get_swipe_gesture, + .get_pinch_gesture = get_pinch_gesture, + .release = pointer_gestures_release, + .get_hold_gesture = get_hold_gesture, +}; + +static void pointer_gestures_v1_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_pointer_gestures_v1 *gestures = data; + + struct wl_resource *resource = wl_resource_create(wl_client, + &zwp_pointer_gestures_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + + wl_resource_set_implementation(resource, + &gestures_impl, gestures, NULL); +} + +static void pointer_gestures_v1_destroy(struct wlr_pointer_gestures_v1 *gestures, + bool destroy_global_safe) { + wl_signal_emit_mutable(&gestures->events.destroy, NULL); + + assert(wl_list_empty(&gestures->events.destroy.listener_list)); + + wl_list_remove(&gestures->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(gestures->global); + } else { + wl_global_destroy(gestures->global); + } + free(gestures); +} + +void wlr_pointer_gestures_v1_destroy(struct wlr_pointer_gestures_v1 *gestures, + bool destroy_global_safe) { + pointer_gestures_v1_destroy(gestures, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_pointer_gestures_v1 *gestures = + wl_container_of(listener, gestures, display_destroy); + pointer_gestures_v1_destroy(gestures, false); +} + +struct wlr_pointer_gestures_v1 *wlr_pointer_gestures_v1_create( + struct wl_display *display) { + struct wlr_pointer_gestures_v1 *gestures = calloc(1, sizeof(*gestures)); + if (!gestures) { + return NULL; + } + + wl_list_init(&gestures->swipes); + wl_list_init(&gestures->pinches); + wl_list_init(&gestures->holds); + + gestures->global = wl_global_create(display, + &zwp_pointer_gestures_v1_interface, POINTER_GESTURES_VERSION, + gestures, pointer_gestures_v1_bind); + if (gestures->global == NULL) { + free(gestures); + return NULL; + } + + wl_signal_init(&gestures->events.destroy); + + gestures->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &gestures->display_destroy); + + return gestures; +} diff --git a/3rdparty/wlroots/types/wlr_presentation_time.c b/3rdparty/wlroots/types/wlr_presentation_time.c new file mode 100644 index 0000000000..c3676d7b3d --- /dev/null +++ b/3rdparty/wlroots/types/wlr_presentation_time.c @@ -0,0 +1,354 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "presentation-time-protocol.h" +#include "util/global.h" + +#define PRESENTATION_VERSION 2 + +struct wlr_presentation_surface_state { + struct wlr_presentation_feedback *feedback; +}; + +struct wlr_presentation_surface { + struct wlr_presentation_surface_state current, pending; + + struct wlr_addon addon; // wlr_surface.addons + struct wlr_surface_synced synced; +}; + +static void feedback_handle_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void feedback_resource_send_presented( + struct wl_resource *feedback_resource, + const struct wlr_presentation_event *event) { + struct wl_client *client = wl_resource_get_client(feedback_resource); + struct wl_resource *output_resource; + wl_resource_for_each(output_resource, &event->output->resources) { + if (wl_resource_get_client(output_resource) == client) { + wp_presentation_feedback_send_sync_output(feedback_resource, + output_resource); + } + } + + uint32_t tv_sec_hi = event->tv_sec >> 32; + uint32_t tv_sec_lo = event->tv_sec & 0xFFFFFFFF; + uint32_t seq_hi = event->seq >> 32; + uint32_t seq_lo = event->seq & 0xFFFFFFFF; + wp_presentation_feedback_send_presented(feedback_resource, + tv_sec_hi, tv_sec_lo, event->tv_nsec, event->refresh, + seq_hi, seq_lo, event->flags); + + wl_resource_destroy(feedback_resource); +} + +static void feedback_resource_send_discarded( + struct wl_resource *feedback_resource) { + wp_presentation_feedback_send_discarded(feedback_resource); + wl_resource_destroy(feedback_resource); +} + +static const struct wlr_addon_interface presentation_surface_addon_impl; + +static void presentation_surface_addon_destroy(struct wlr_addon *addon) { + struct wlr_presentation_surface *p_surface = + wl_container_of(addon, p_surface, addon); + + wlr_addon_finish(addon); + wlr_surface_synced_finish(&p_surface->synced); + + free(p_surface); +} + +static const struct wlr_addon_interface presentation_surface_addon_impl = { + .name = "wlr_presentation_surface", + .destroy = presentation_surface_addon_destroy, +}; + +static void surface_synced_finish_state(void *_state) { + struct wlr_presentation_surface_state *state = _state; + wlr_presentation_feedback_destroy(state->feedback); +} + +static void surface_synced_move_state(void *_dst, void *_src) { + struct wlr_presentation_surface_state *dst = _dst, *src = _src; + surface_synced_finish_state(dst); + dst->feedback = src->feedback; + src->feedback = NULL; +} + +static const struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(struct wlr_presentation_surface_state), + .finish_state = surface_synced_finish_state, + .move_state = surface_synced_move_state, +}; + +static void presentation_handle_feedback(struct wl_client *client, + struct wl_resource *presentation_resource, + struct wl_resource *surface_resource, uint32_t id) { + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + + struct wlr_addon *addon = + wlr_addon_find(&surface->addons, NULL, &presentation_surface_addon_impl); + struct wlr_presentation_surface *p_surface = NULL; + if (addon != NULL) { + p_surface = wl_container_of(addon, p_surface, addon); + } else { + p_surface = calloc(1, sizeof(*p_surface)); + if (p_surface == NULL) { + wl_client_post_no_memory(client); + return; + } + wlr_addon_init(&p_surface->addon, &surface->addons, + NULL, &presentation_surface_addon_impl); + if (!wlr_surface_synced_init(&p_surface->synced, surface, + &surface_synced_impl, &p_surface->pending, &p_surface->current)) { + free(p_surface); + wl_client_post_no_memory(client); + return; + } + } + + struct wlr_presentation_feedback *feedback = p_surface->pending.feedback; + if (feedback == NULL) { + feedback = calloc(1, sizeof(*feedback)); + if (feedback == NULL) { + wl_client_post_no_memory(client); + return; + } + + wl_list_init(&feedback->resources); + p_surface->pending.feedback = feedback; + } + + uint32_t version = wl_resource_get_version(presentation_resource); + struct wl_resource *resource = wl_resource_create(client, + &wp_presentation_feedback_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, NULL, feedback, + feedback_handle_resource_destroy); + + wl_list_insert(&feedback->resources, wl_resource_get_link(resource)); +} + +static void presentation_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wp_presentation_interface presentation_impl = { + .feedback = presentation_handle_feedback, + .destroy = presentation_handle_destroy, +}; + +static void presentation_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wl_resource *resource = wl_resource_create(client, + &wp_presentation_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &presentation_impl, NULL, NULL); + + wp_presentation_send_clock_id(resource, CLOCK_MONOTONIC); +} + +static void presentation_destroy(struct wlr_presentation *presentation, + bool destroy_global_safe) { + wl_signal_emit_mutable(&presentation->events.destroy, presentation); + + assert(wl_list_empty(&presentation->events.destroy.listener_list)); + + wl_list_remove(&presentation->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(presentation->global); + } else { + wl_global_destroy(presentation->global); + } + free(presentation); +} + +void wlr_presentation_destroy(struct wlr_presentation *presentation, bool destroy_global_safe) { + presentation_destroy(presentation, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_presentation *presentation = + wl_container_of(listener, presentation, display_destroy); + presentation_destroy(presentation, false); +} + +struct wlr_presentation *wlr_presentation_create(struct wl_display *display, + struct wlr_backend *backend, uint32_t version) { + assert(version <= PRESENTATION_VERSION); + + struct wlr_presentation *presentation = calloc(1, sizeof(*presentation)); + if (presentation == NULL) { + return NULL; + } + + presentation->global = wl_global_create(display, &wp_presentation_interface, + version, NULL, presentation_bind); + if (presentation->global == NULL) { + free(presentation); + return NULL; + } + + wl_signal_init(&presentation->events.destroy); + + presentation->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &presentation->display_destroy); + + return presentation; +} + +void wlr_presentation_feedback_send_presented( + struct wlr_presentation_feedback *feedback, + const struct wlr_presentation_event *event) { + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &feedback->resources) { + feedback_resource_send_presented(resource, event); + } +} + +struct wlr_presentation_feedback *wlr_presentation_surface_sampled( + struct wlr_surface *surface) { + struct wlr_addon *addon = + wlr_addon_find(&surface->addons, NULL, &presentation_surface_addon_impl); + if (addon != NULL) { + struct wlr_presentation_surface *p_surface = + wl_container_of(addon, p_surface, addon); + struct wlr_presentation_feedback *sampled = + p_surface->current.feedback; + p_surface->current.feedback = NULL; + return sampled; + } + return NULL; +} + +static void feedback_unset_output(struct wlr_presentation_feedback *feedback); + +void wlr_presentation_feedback_destroy( + struct wlr_presentation_feedback *feedback) { + if (feedback == NULL) { + return; + } + + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &feedback->resources) { + feedback_resource_send_discarded(resource); + } + assert(wl_list_empty(&feedback->resources)); + + feedback_unset_output(feedback); + free(feedback); +} + +void wlr_presentation_event_from_output(struct wlr_presentation_event *event, + const struct wlr_output_event_present *output_event) { + *event = (struct wlr_presentation_event){ + .output = output_event->output, + .tv_sec = (uint64_t)output_event->when.tv_sec, + .tv_nsec = (uint32_t)output_event->when.tv_nsec, + .refresh = (uint32_t)output_event->refresh, + .seq = (uint64_t)output_event->seq, + .flags = output_event->flags, + }; +} + +static void feedback_unset_output(struct wlr_presentation_feedback *feedback) { + if (feedback->output == NULL) { + return; + } + + feedback->output = NULL; + wl_list_remove(&feedback->output_commit.link); + wl_list_remove(&feedback->output_present.link); + wl_list_remove(&feedback->output_destroy.link); +} + +static void feedback_handle_output_commit(struct wl_listener *listener, + void *data) { + struct wlr_presentation_feedback *feedback = + wl_container_of(listener, feedback, output_commit); + if (feedback->output_committed) { + return; + } + feedback->output_committed = true; + feedback->output_commit_seq = feedback->output->commit_seq; +} + +static void feedback_handle_output_present(struct wl_listener *listener, + void *data) { + struct wlr_presentation_feedback *feedback = + wl_container_of(listener, feedback, output_present); + struct wlr_output_event_present *output_event = data; + + if (!feedback->output_committed || + output_event->commit_seq != feedback->output_commit_seq) { + return; + } + + if (output_event->presented) { + struct wlr_presentation_event event = {0}; + wlr_presentation_event_from_output(&event, output_event); + struct wl_resource *resource = wl_resource_from_link(feedback->resources.next); + if (wl_resource_get_version(resource) == 1 && + event.output->adaptive_sync_status == WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED) { + event.refresh = 0; + } + if (!feedback->zero_copy) { + event.flags &= ~WP_PRESENTATION_FEEDBACK_KIND_ZERO_COPY; + } + wlr_presentation_feedback_send_presented(feedback, &event); + } + wlr_presentation_feedback_destroy(feedback); +} + +static void feedback_handle_output_destroy(struct wl_listener *listener, + void *data) { + struct wlr_presentation_feedback *feedback = + wl_container_of(listener, feedback, output_destroy); + wlr_presentation_feedback_destroy(feedback); +} + +static void presentation_surface_queued_on_output(struct wlr_surface *surface, + struct wlr_output *output, bool zero_copy) { + struct wlr_presentation_feedback *feedback = + wlr_presentation_surface_sampled(surface); + if (feedback == NULL) { + return; + } + + assert(feedback->output == NULL); + feedback->output = output; + feedback->zero_copy = zero_copy; + + feedback->output_commit.notify = feedback_handle_output_commit; + wl_signal_add(&output->events.commit, &feedback->output_commit); + feedback->output_present.notify = feedback_handle_output_present; + wl_signal_add(&output->events.present, &feedback->output_present); + feedback->output_destroy.notify = feedback_handle_output_destroy; + wl_signal_add(&output->events.destroy, &feedback->output_destroy); +} + +void wlr_presentation_surface_textured_on_output(struct wlr_surface *surface, + struct wlr_output *output) { + return presentation_surface_queued_on_output(surface, output, false); +} + +void wlr_presentation_surface_scanned_out_on_output(struct wlr_surface *surface, + struct wlr_output *output) { + return presentation_surface_queued_on_output(surface, output, true); +} diff --git a/3rdparty/wlroots/types/wlr_primary_selection.c b/3rdparty/wlroots/types/wlr_primary_selection.c new file mode 100644 index 0000000000..1940a2d82b --- /dev/null +++ b/3rdparty/wlroots/types/wlr_primary_selection.c @@ -0,0 +1,105 @@ +#include +#include +#include +#include + +void wlr_primary_selection_source_init( + struct wlr_primary_selection_source *source, + const struct wlr_primary_selection_source_impl *impl) { + assert(impl->send); + *source = (struct wlr_primary_selection_source){ + .impl = impl, + }; + wl_array_init(&source->mime_types); + + wl_signal_init(&source->events.destroy); +} + +void wlr_primary_selection_source_destroy( + struct wlr_primary_selection_source *source) { + if (source == NULL) { + return; + } + + wl_signal_emit_mutable(&source->events.destroy, source); + + assert(wl_list_empty(&source->events.destroy.listener_list)); + + char **p; + wl_array_for_each(p, &source->mime_types) { + free(*p); + } + wl_array_release(&source->mime_types); + + if (source->impl->destroy) { + source->impl->destroy(source); + } else { + free(source); + } +} + +void wlr_primary_selection_source_send( + struct wlr_primary_selection_source *source, const char *mime_type, + int32_t fd) { + source->impl->send(source, mime_type, fd); +} + + +void wlr_seat_request_set_primary_selection(struct wlr_seat *seat, + struct wlr_seat_client *client, + struct wlr_primary_selection_source *source, uint32_t serial) { + if (client && !wlr_seat_client_validate_event_serial(client, serial)) { + wlr_log(WLR_DEBUG, "Rejecting set_primary_selection request, " + "serial %"PRIu32" was never given to client", serial); + return; + } + + if (seat->primary_selection_source && + serial - seat->primary_selection_serial > UINT32_MAX / 2) { + wlr_log(WLR_DEBUG, "Rejecting set_primary_selection request, " + "serial indicates superseded (%"PRIu32" < %"PRIu32")", + serial, seat->primary_selection_serial); + return; + } + + struct wlr_seat_request_set_primary_selection_event event = { + .source = source, + .serial = serial, + }; + wl_signal_emit_mutable(&seat->events.request_set_primary_selection, &event); +} + +static void seat_handle_primary_selection_source_destroy( + struct wl_listener *listener, void *data) { + struct wlr_seat *seat = + wl_container_of(listener, seat, primary_selection_source_destroy); + wl_list_remove(&seat->primary_selection_source_destroy.link); + seat->primary_selection_source = NULL; + wl_signal_emit_mutable(&seat->events.set_primary_selection, seat); +} + +void wlr_seat_set_primary_selection(struct wlr_seat *seat, + struct wlr_primary_selection_source *source, uint32_t serial) { + if (seat->primary_selection_source == source) { + seat->primary_selection_serial = serial; + return; + } + + if (seat->primary_selection_source != NULL) { + wl_list_remove(&seat->primary_selection_source_destroy.link); + wlr_primary_selection_source_destroy(seat->primary_selection_source); + seat->primary_selection_source = NULL; + } + + seat->primary_selection_source = source; + seat->primary_selection_serial = serial; + + if (source != NULL) { + seat->primary_selection_source_destroy.notify = + seat_handle_primary_selection_source_destroy; + wl_signal_add(&source->events.destroy, + &seat->primary_selection_source_destroy); + } + + wl_signal_emit_mutable(&seat->events.set_primary_selection, seat); +} diff --git a/3rdparty/wlroots/types/wlr_primary_selection_v1.c b/3rdparty/wlroots/types/wlr_primary_selection_v1.c new file mode 100644 index 0000000000..771a06db00 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_primary_selection_v1.c @@ -0,0 +1,512 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "primary-selection-unstable-v1-protocol.h" +#include "util/global.h" + +#define DEVICE_MANAGER_VERSION 1 + +static const struct zwp_primary_selection_offer_v1_interface offer_impl; + +static struct wlr_primary_selection_v1_device *device_from_offer_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwp_primary_selection_offer_v1_interface, &offer_impl)); + return wl_resource_get_user_data(resource); +} + +static void offer_handle_receive(struct wl_client *client, + struct wl_resource *resource, const char *mime_type, int32_t fd) { + struct wlr_primary_selection_v1_device *device = + device_from_offer_resource(resource); + if (device == NULL || device->seat->primary_selection_source == NULL) { + close(fd); + return; + } + + wlr_primary_selection_source_send(device->seat->primary_selection_source, + mime_type, fd); +} + +static void offer_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwp_primary_selection_offer_v1_interface offer_impl = { + .receive = offer_handle_receive, + .destroy = offer_handle_destroy, +}; + +static void offer_handle_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static struct wlr_primary_selection_v1_device *device_from_resource( + struct wl_resource *resource); + +static void create_offer(struct wl_resource *device_resource, + struct wlr_primary_selection_source *source) { + struct wlr_primary_selection_v1_device *device = + device_from_resource(device_resource); + assert(device != NULL); + + struct wl_client *client = wl_resource_get_client(device_resource); + uint32_t version = wl_resource_get_version(device_resource); + struct wl_resource *resource = wl_resource_create(client, + &zwp_primary_selection_offer_v1_interface, version, 0); + if (resource == NULL) { + wl_resource_post_no_memory(device_resource); + return; + } + wl_resource_set_implementation(resource, &offer_impl, device, + offer_handle_resource_destroy); + + wl_list_insert(&device->offers, wl_resource_get_link(resource)); + + zwp_primary_selection_device_v1_send_data_offer(device_resource, resource); + + char **p; + wl_array_for_each(p, &source->mime_types) { + zwp_primary_selection_offer_v1_send_offer(resource, *p); + } + + zwp_primary_selection_device_v1_send_selection(device_resource, resource); +} + +static void destroy_offer(struct wl_resource *resource) { + if (device_from_offer_resource(resource) == NULL) { + return; + } + + // Make the offer inert + wl_resource_set_user_data(resource, NULL); + + struct wl_list *link = wl_resource_get_link(resource); + wl_list_remove(link); + wl_list_init(link); +} + + +struct client_data_source { + struct wlr_primary_selection_source source; + struct wl_resource *resource; + bool finalized; +}; + +static void client_source_send( + struct wlr_primary_selection_source *wlr_source, + const char *mime_type, int fd) { + struct client_data_source *source = wl_container_of(wlr_source, source, source); + zwp_primary_selection_source_v1_send_send(source->resource, mime_type, fd); + close(fd); +} + +static void client_source_destroy( + struct wlr_primary_selection_source *wlr_source) { + struct client_data_source *source = wl_container_of(wlr_source, source, source); + zwp_primary_selection_source_v1_send_cancelled(source->resource); + // Make the source resource inert + wl_resource_set_user_data(source->resource, NULL); + free(source); +} + +static const struct wlr_primary_selection_source_impl client_source_impl = { + .send = client_source_send, + .destroy = client_source_destroy, +}; + +static const struct zwp_primary_selection_source_v1_interface source_impl; + +static struct client_data_source *client_data_source_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwp_primary_selection_source_v1_interface, &source_impl)); + return wl_resource_get_user_data(resource); +} + +static void source_handle_offer(struct wl_client *client, + struct wl_resource *resource, const char *mime_type) { + struct client_data_source *source = + client_data_source_from_resource(resource); + if (source == NULL) { + return; + } + if (source->finalized) { + wlr_log(WLR_DEBUG, "Offering additional MIME type after set_selection"); + } + + const char **mime_type_ptr; + wl_array_for_each(mime_type_ptr, &source->source.mime_types) { + if (strcmp(*mime_type_ptr, mime_type) == 0) { + wlr_log(WLR_DEBUG, "Ignoring duplicate MIME type offer %s", + mime_type); + return; + } + } + + char *dup_mime_type = strdup(mime_type); + if (dup_mime_type == NULL) { + wl_resource_post_no_memory(resource); + return; + } + + char **p = wl_array_add(&source->source.mime_types, sizeof(*p)); + if (p == NULL) { + free(dup_mime_type); + wl_resource_post_no_memory(resource); + return; + } + + *p = dup_mime_type; +} + +static void source_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwp_primary_selection_source_v1_interface source_impl = { + .offer = source_handle_offer, + .destroy = source_handle_destroy, +}; + +static void source_resource_handle_destroy(struct wl_resource *resource) { + struct client_data_source *source = + client_data_source_from_resource(resource); + if (source == NULL) { + return; + } + wlr_primary_selection_source_destroy(&source->source); +} + + +static const struct zwp_primary_selection_device_v1_interface device_impl; + +static struct wlr_primary_selection_v1_device *device_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwp_primary_selection_device_v1_interface, &device_impl)); + return wl_resource_get_user_data(resource); +} + +static void device_handle_set_selection(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *source_resource, + uint32_t serial) { + struct wlr_primary_selection_v1_device *device = + device_from_resource(resource); + if (device == NULL) { + return; + } + + struct client_data_source *client_source = NULL; + if (source_resource != NULL) { + client_source = client_data_source_from_resource(source_resource); + } + + struct wlr_primary_selection_source *source = NULL; + if (client_source != NULL) { + client_source->finalized = true; + source = &client_source->source; + } + + struct wlr_seat_client *seat_client = + wlr_seat_client_for_wl_client(device->seat, client); + + wlr_seat_request_set_primary_selection(device->seat, seat_client, source, serial); +} + +static void device_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwp_primary_selection_device_v1_interface device_impl = { + .set_selection = device_handle_set_selection, + .destroy = device_handle_destroy, +}; + +static void device_handle_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + + +static void device_resource_send_selection(struct wl_resource *resource, + struct wlr_primary_selection_source *source) { + assert(device_from_resource(resource) != NULL); + + if (source != NULL) { + create_offer(resource, source); + } else { + zwp_primary_selection_device_v1_send_selection(resource, NULL); + } +} + +static void device_send_selection( + struct wlr_primary_selection_v1_device *device) { + struct wlr_seat_client *seat_client = + device->seat->keyboard_state.focused_client; + if (seat_client == NULL) { + return; + } + + struct wl_resource *resource; + wl_resource_for_each(resource, &device->resources) { + if (wl_resource_get_client(resource) == seat_client->client) { + device_resource_send_selection(resource, + device->seat->primary_selection_source); + } + } +} + +static void device_destroy(struct wlr_primary_selection_v1_device *device); + +static void device_handle_seat_destroy(struct wl_listener *listener, + void *data) { + struct wlr_primary_selection_v1_device *device = + wl_container_of(listener, device, seat_destroy); + device_destroy(device); +} + +static void device_handle_seat_focus_change(struct wl_listener *listener, + void *data) { + struct wlr_primary_selection_v1_device *device = + wl_container_of(listener, device, seat_focus_change); + // TODO: maybe make previous offers inert, or set a NULL selection for + // previous client? + device_send_selection(device); +} + +static void device_handle_seat_set_primary_selection( + struct wl_listener *listener, void *data) { + struct wlr_primary_selection_v1_device *device = + wl_container_of(listener, device, seat_set_primary_selection); + + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &device->offers) { + destroy_offer(resource); + } + + device_send_selection(device); +} + +static struct wlr_primary_selection_v1_device *get_or_create_device( + struct wlr_primary_selection_v1_device_manager *manager, + struct wlr_seat *seat) { + struct wlr_primary_selection_v1_device *device; + wl_list_for_each(device, &manager->devices, link) { + if (device->seat == seat) { + return device; + } + } + + device = calloc(1, sizeof(*device)); + if (device == NULL) { + return NULL; + } + device->manager = manager; + device->seat = seat; + + wl_list_init(&device->resources); + wl_list_insert(&manager->devices, &device->link); + + wl_list_init(&device->offers); + + device->seat_destroy.notify = device_handle_seat_destroy; + wl_signal_add(&seat->events.destroy, &device->seat_destroy); + + device->seat_focus_change.notify = device_handle_seat_focus_change; + wl_signal_add(&seat->keyboard_state.events.focus_change, + &device->seat_focus_change); + + device->seat_set_primary_selection.notify = + device_handle_seat_set_primary_selection; + wl_signal_add(&seat->events.set_primary_selection, + &device->seat_set_primary_selection); + + return device; +} + +static void device_destroy(struct wlr_primary_selection_v1_device *device) { + if (device == NULL) { + return; + } + wl_list_remove(&device->link); + wl_list_remove(&device->seat_destroy.link); + wl_list_remove(&device->seat_focus_change.link); + wl_list_remove(&device->seat_set_primary_selection.link); + struct wl_resource *resource, *resource_tmp; + wl_resource_for_each_safe(resource, resource_tmp, &device->offers) { + destroy_offer(resource); + } + wl_resource_for_each_safe(resource, resource_tmp, &device->resources) { + // Make the resource inert + wl_resource_set_user_data(resource, NULL); + + struct wl_list *link = wl_resource_get_link(resource); + wl_list_remove(link); + wl_list_init(link); + } + free(device); +} + + +static const struct zwp_primary_selection_device_manager_v1_interface + device_manager_impl; + +static struct wlr_primary_selection_v1_device_manager *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwp_primary_selection_device_manager_v1_interface, &device_manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void device_manager_handle_create_source(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id) { + struct client_data_source *source = calloc(1, sizeof(*source)); + if (source == NULL) { + wl_client_post_no_memory(client); + return; + } + wlr_primary_selection_source_init(&source->source, &client_source_impl); + + uint32_t version = wl_resource_get_version(manager_resource); + source->resource = wl_resource_create(client, + &zwp_primary_selection_source_v1_interface, version, id); + if (source->resource == NULL) { + free(source); + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(source->resource, &source_impl, source, + source_resource_handle_destroy); +} + +static void device_manager_handle_get_device(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + struct wl_resource *seat_resource) { + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat_resource); + struct wlr_primary_selection_v1_device_manager *manager = + manager_from_resource(manager_resource); + + uint32_t version = wl_resource_get_version(manager_resource); + struct wl_resource *resource = wl_resource_create(client, + &zwp_primary_selection_device_v1_interface, version, id); + if (resource == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + wl_resource_set_implementation(resource, &device_impl, NULL, + device_handle_resource_destroy); + wl_list_init(wl_resource_get_link(resource)); + if (seat_client == NULL) { + return; + } + + struct wlr_primary_selection_v1_device *device = + get_or_create_device(manager, seat_client->seat); + if (device == NULL) { + wl_resource_destroy(resource); + wl_resource_post_no_memory(manager_resource); + return; + } + wl_resource_set_user_data(resource, device); + wl_list_insert(&device->resources, wl_resource_get_link(resource)); + + if (device->seat->keyboard_state.focused_client == seat_client) { + device_resource_send_selection(resource, + device->seat->primary_selection_source); + } +} + +static void device_manager_handle_destroy(struct wl_client *client, + struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static const struct zwp_primary_selection_device_manager_v1_interface + device_manager_impl = { + .create_source = device_manager_handle_create_source, + .get_device = device_manager_handle_get_device, + .destroy = device_manager_handle_destroy, +}; + + +static void primary_selection_device_manager_bind(struct wl_client *client, + void *data, uint32_t version, uint32_t id) { + struct wlr_primary_selection_v1_device_manager *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &zwp_primary_selection_device_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &device_manager_impl, manager, + NULL); +} + +static void primary_selection_v1_device_manager_destroy( + struct wlr_primary_selection_v1_device_manager *manager, + bool destroy_global_safe) { + struct wlr_primary_selection_v1_device *device, *tmp; + wl_list_for_each_safe(device, tmp, &manager->devices, link) { + device_destroy(device); + } + + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_primary_selection_v1_device_manager_destroy( + struct wlr_primary_selection_v1_device_manager *manager, bool destroy_global_safe) { + primary_selection_v1_device_manager_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_primary_selection_v1_device_manager *manager = + wl_container_of(listener, manager, display_destroy); + primary_selection_v1_device_manager_destroy(manager, false); +} + +struct wlr_primary_selection_v1_device_manager * + wlr_primary_selection_v1_device_manager_create( + struct wl_display *display) { + struct wlr_primary_selection_v1_device_manager *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + manager->global = wl_global_create(display, + &zwp_primary_selection_device_manager_v1_interface, DEVICE_MANAGER_VERSION, + manager, primary_selection_device_manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + wl_list_init(&manager->devices); + + wl_signal_init(&manager->events.destroy); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_region.c b/3rdparty/wlroots/types/wlr_region.c new file mode 100644 index 0000000000..59f6dfc6fb --- /dev/null +++ b/3rdparty/wlroots/types/wlr_region.c @@ -0,0 +1,75 @@ +#include +#include +#include +#include +#include +#include +#include "types/wlr_region.h" + +static const struct wl_region_interface region_impl; + +static pixman_region32_t *region_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_region_interface, + ®ion_impl)); + return wl_resource_get_user_data(resource); +} + +const pixman_region32_t *wlr_region_from_resource(struct wl_resource *resource) { + return region_from_resource(resource); +} + +static void region_add(struct wl_client *client, struct wl_resource *resource, + int32_t x, int32_t y, int32_t width, int32_t height) { + pixman_region32_t *region = region_from_resource(resource); + pixman_region32_union_rect(region, region, x, y, width, height); +} + +static void region_subtract(struct wl_client *client, struct wl_resource *resource, + int32_t x, int32_t y, int32_t width, int32_t height) { + pixman_region32_t *region = region_from_resource(resource); + pixman_region32_union_rect(region, region, x, y, width, height); + + pixman_region32_t rect; + pixman_region32_init_rect(&rect, x, y, width, height); + pixman_region32_subtract(region, region, &rect); + pixman_region32_fini(&rect); +} + +static void region_destroy(struct wl_client *client, struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wl_region_interface region_impl = { + .destroy = region_destroy, + .add = region_add, + .subtract = region_subtract, +}; + +static void region_handle_resource_destroy(struct wl_resource *resource) { + pixman_region32_t *reg = region_from_resource(resource); + pixman_region32_fini(reg); + free(reg); +} + +struct wl_resource *region_create(struct wl_client *client, + uint32_t version, uint32_t id) { + pixman_region32_t *region = calloc(1, sizeof(*region)); + if (region == NULL) { + wl_client_post_no_memory(client); + return NULL; + } + + pixman_region32_init(region); + + struct wl_resource *region_resource = wl_resource_create(client, + &wl_region_interface, version, id); + if (region_resource == NULL) { + free(region); + wl_client_post_no_memory(client); + return NULL; + } + wl_resource_set_implementation(region_resource, ®ion_impl, region, + region_handle_resource_destroy); + + return region_resource; +} diff --git a/3rdparty/wlroots/types/wlr_relative_pointer_v1.c b/3rdparty/wlroots/types/wlr_relative_pointer_v1.c new file mode 100644 index 0000000000..bb72ad072e --- /dev/null +++ b/3rdparty/wlroots/types/wlr_relative_pointer_v1.c @@ -0,0 +1,225 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "relative-pointer-unstable-v1-protocol.h" +#include "util/global.h" + +#define RELATIVE_POINTER_MANAGER_VERSION 1 + +static const struct zwp_relative_pointer_manager_v1_interface relative_pointer_manager_v1_impl; +static const struct zwp_relative_pointer_v1_interface relative_pointer_v1_impl; + +struct wlr_relative_pointer_v1 *wlr_relative_pointer_v1_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwp_relative_pointer_v1_interface, + &relative_pointer_v1_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_relative_pointer_manager_v1 *relative_pointer_manager_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwp_relative_pointer_manager_v1_interface, + &relative_pointer_manager_v1_impl)); + return wl_resource_get_user_data(resource); +} + +static void relative_pointer_destroy(struct wlr_relative_pointer_v1 *relative_pointer) { + wl_signal_emit_mutable(&relative_pointer->events.destroy, relative_pointer); + + assert(wl_list_empty(&relative_pointer->events.destroy.listener_list)); + + wl_list_remove(&relative_pointer->link); + wl_list_remove(&relative_pointer->seat_destroy.link); + wl_list_remove(&relative_pointer->pointer_destroy.link); + + wl_resource_set_user_data(relative_pointer->resource, NULL); + free(relative_pointer); +} + +static void relative_pointer_v1_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_relative_pointer_v1 *relative_pointer = + wlr_relative_pointer_v1_from_resource(resource); + if (relative_pointer == NULL) { + return; + } + relative_pointer_destroy(relative_pointer); +} + +static void relative_pointer_v1_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void relative_pointer_handle_seat_destroy(struct wl_listener *listener, + void *data) { + struct wlr_relative_pointer_v1 *relative_pointer = + wl_container_of(listener, relative_pointer, seat_destroy); + + relative_pointer_destroy(relative_pointer); +} + +static void relative_pointer_handle_pointer_destroy(struct wl_listener *listener, + void *data) { + struct wlr_relative_pointer_v1 *relative_pointer = + wl_container_of(listener, relative_pointer, pointer_destroy); + + relative_pointer_destroy(relative_pointer); +} + +static void relative_pointer_manager_v1_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void relative_pointer_manager_v1_handle_get_relative_pointer(struct wl_client *client, + struct wl_resource *resource, uint32_t id, struct wl_resource *pointer) { + struct wlr_relative_pointer_manager_v1 *manager = + relative_pointer_manager_from_resource(resource); + struct wlr_seat_client *seat_client = + wlr_seat_client_from_pointer_resource(pointer); + + struct wl_resource *relative_pointer_resource = wl_resource_create(client, + &zwp_relative_pointer_v1_interface, wl_resource_get_version(resource), id); + if (relative_pointer_resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(relative_pointer_resource, &relative_pointer_v1_impl, + NULL, relative_pointer_v1_handle_resource_destroy); + + if (seat_client == NULL) { + // Leave the resource inert + return; + } + + struct wlr_relative_pointer_v1 *relative_pointer = calloc(1, sizeof(*relative_pointer)); + if (relative_pointer == NULL) { + wl_client_post_no_memory(client); + return; + } + + relative_pointer->resource = relative_pointer_resource; + relative_pointer->pointer_resource = pointer; + + relative_pointer->seat = seat_client->seat; + wl_signal_add(&relative_pointer->seat->events.destroy, + &relative_pointer->seat_destroy); + relative_pointer->seat_destroy.notify = relative_pointer_handle_seat_destroy; + + wl_signal_init(&relative_pointer->events.destroy); + + wl_resource_set_user_data(relative_pointer_resource, relative_pointer); + + wl_list_insert(&manager->relative_pointers, &relative_pointer->link); + + wl_resource_add_destroy_listener(relative_pointer->pointer_resource, + &relative_pointer->pointer_destroy); + relative_pointer->pointer_destroy.notify = relative_pointer_handle_pointer_destroy; + + wl_signal_emit_mutable(&manager->events.new_relative_pointer, + relative_pointer); +} + +static void relative_pointer_manager_v1_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_relative_pointer_manager_v1 *manager = data; + + struct wl_resource *manager_resource = wl_resource_create(wl_client, + &zwp_relative_pointer_manager_v1_interface, version, id); + if (manager_resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + + wl_resource_set_implementation(manager_resource, &relative_pointer_manager_v1_impl, + manager, NULL); +} + +static void relative_pointer_manager_v1_destroy(struct wlr_relative_pointer_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + assert(wl_list_empty(&manager->events.new_relative_pointer.listener_list)); + + wl_list_remove(&manager->display_destroy_listener.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_relative_pointer_manager_v1_destroy(struct wlr_relative_pointer_manager_v1 *manager, + bool destroy_global_safe) { + relative_pointer_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_relative_pointer_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy_listener); + relative_pointer_manager_v1_destroy(manager, false); +} + +static const struct zwp_relative_pointer_manager_v1_interface relative_pointer_manager_v1_impl = { + .destroy = relative_pointer_manager_v1_handle_destroy, + .get_relative_pointer = relative_pointer_manager_v1_handle_get_relative_pointer, +}; + +static const struct zwp_relative_pointer_v1_interface relative_pointer_v1_impl = { + .destroy = relative_pointer_v1_handle_destroy, +}; + +struct wlr_relative_pointer_manager_v1 *wlr_relative_pointer_manager_v1_create(struct wl_display *display) { + struct wlr_relative_pointer_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + wl_list_init(&manager->relative_pointers); + + manager->global = wl_global_create(display, + &zwp_relative_pointer_manager_v1_interface, RELATIVE_POINTER_MANAGER_VERSION, + manager, relative_pointer_manager_v1_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + wl_signal_init(&manager->events.destroy); + wl_signal_init(&manager->events.new_relative_pointer); + + manager->display_destroy_listener.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy_listener); + + return manager; +} + +void wlr_relative_pointer_manager_v1_send_relative_motion( + struct wlr_relative_pointer_manager_v1 *manager, struct wlr_seat *seat, + uint64_t time_usec, double dx, double dy, + double dx_unaccel, double dy_unaccel) { + struct wlr_seat_client *focused = seat->pointer_state.focused_client; + if (focused == NULL) { + return; + } + + struct wlr_relative_pointer_v1 *pointer; + wl_list_for_each(pointer, &manager->relative_pointers, link) { + struct wlr_seat_client *seat_client = + wlr_seat_client_from_pointer_resource(pointer->pointer_resource); + if (!pointer->seat || seat != pointer->seat || focused != seat_client) { + continue; + } + + zwp_relative_pointer_v1_send_relative_motion(pointer->resource, + (uint32_t)(time_usec >> 32), (uint32_t)time_usec, + wl_fixed_from_double(dx), wl_fixed_from_double(dy), + wl_fixed_from_double(dx_unaccel), wl_fixed_from_double(dy_unaccel)); + } +} diff --git a/3rdparty/wlroots/types/wlr_screencopy_v1.c b/3rdparty/wlroots/types/wlr_screencopy_v1.c new file mode 100644 index 0000000000..24dc37ed46 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_screencopy_v1.c @@ -0,0 +1,739 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "wlr-screencopy-unstable-v1-protocol.h" +#include "render/pixel_format.h" +#include "render/wlr_renderer.h" +#include "util/global.h" + +#define SCREENCOPY_MANAGER_VERSION 3 + +struct screencopy_damage { + struct wl_list link; + struct wlr_output *output; + struct pixman_region32 damage; + struct wl_listener output_precommit; + struct wl_listener output_destroy; +}; + +static const struct zwlr_screencopy_frame_v1_interface frame_impl; + +static struct screencopy_damage *screencopy_damage_find( + struct wlr_screencopy_v1_client *client, + struct wlr_output *output) { + struct screencopy_damage *damage; + + wl_list_for_each(damage, &client->damages, link) { + if (damage->output == output) { + return damage; + } + } + + return NULL; +} + +static void screencopy_damage_accumulate(struct screencopy_damage *damage, + const struct wlr_output_state *state) { + struct pixman_region32 *region = &damage->damage; + struct wlr_output *output = damage->output; + + if (state->committed & WLR_OUTPUT_STATE_DAMAGE) { + // If the compositor submitted damage, copy it over + pixman_region32_union(region, region, &state->damage); + pixman_region32_intersect_rect(region, region, 0, 0, + output->width, output->height); + } else if (state->committed & WLR_OUTPUT_STATE_BUFFER) { + // If the compositor did not submit damage but did submit a buffer + // damage everything + pixman_region32_union_rect(region, region, 0, 0, + output->width, output->height); + } +} + +static void screencopy_damage_handle_output_precommit( + struct wl_listener *listener, void *data) { + struct screencopy_damage *damage = + wl_container_of(listener, damage, output_precommit); + const struct wlr_output_event_precommit *event = data; + screencopy_damage_accumulate(damage, event->state); +} + +static void screencopy_damage_destroy(struct screencopy_damage *damage) { + wl_list_remove(&damage->output_destroy.link); + wl_list_remove(&damage->output_precommit.link); + wl_list_remove(&damage->link); + pixman_region32_fini(&damage->damage); + free(damage); +} + +static void screencopy_damage_handle_output_destroy( + struct wl_listener *listener, void *data) { + struct screencopy_damage *damage = + wl_container_of(listener, damage, output_destroy); + screencopy_damage_destroy(damage); +} + +static struct screencopy_damage *screencopy_damage_create( + struct wlr_screencopy_v1_client *client, + struct wlr_output *output) { + struct screencopy_damage *damage = calloc(1, sizeof(*damage)); + if (!damage) { + return NULL; + } + + damage->output = output; + pixman_region32_init_rect(&damage->damage, 0, 0, output->width, + output->height); + wl_list_insert(&client->damages, &damage->link); + + wl_signal_add(&output->events.precommit, &damage->output_precommit); + damage->output_precommit.notify = + screencopy_damage_handle_output_precommit; + + wl_signal_add(&output->events.destroy, &damage->output_destroy); + damage->output_destroy.notify = screencopy_damage_handle_output_destroy; + + return damage; +} + +static struct screencopy_damage *screencopy_damage_get_or_create( + struct wlr_screencopy_v1_client *client, + struct wlr_output *output) { + struct screencopy_damage *damage = screencopy_damage_find(client, output); + return damage ? damage : screencopy_damage_create(client, output); +} + +static void client_unref(struct wlr_screencopy_v1_client *client) { + assert(client->ref > 0); + + if (--client->ref != 0) { + return; + } + + struct screencopy_damage *damage, *tmp_damage; + wl_list_for_each_safe(damage, tmp_damage, &client->damages, link) { + screencopy_damage_destroy(damage); + } + + free(client); +} + +static struct wlr_screencopy_frame_v1 *frame_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_screencopy_frame_v1_interface, &frame_impl)); + return wl_resource_get_user_data(resource); +} + +static void frame_destroy(struct wlr_screencopy_frame_v1 *frame) { + if (frame == NULL) { + return; + } + if (frame->output != NULL && frame->buffer != NULL) { + wlr_output_lock_attach_render(frame->output, false); + if (frame->cursor_locked) { + wlr_output_lock_software_cursors(frame->output, false); + } + } + wl_list_remove(&frame->link); + wl_list_remove(&frame->output_commit.link); + wl_list_remove(&frame->output_destroy.link); + // Make the frame resource inert + wl_resource_set_user_data(frame->resource, NULL); + wlr_buffer_unlock(frame->buffer); + client_unref(frame->client); + free(frame); +} + +static void frame_send_damage(struct wlr_screencopy_frame_v1 *frame) { + if (!frame->with_damage) { + return; + } + + struct screencopy_damage *damage = + screencopy_damage_get_or_create(frame->client, frame->output); + if (damage == NULL) { + return; + } + + int n_boxes; + const pixman_box32_t *boxes = pixman_region32_rectangles(&damage->damage, &n_boxes); + for (int i = 0; i < n_boxes; i++) { + const pixman_box32_t *box = &boxes[i]; + + int damage_x = box->x1; + int damage_y = box->y1; + int damage_width = box->x2 - box->x1; + int damage_height = box->y2 - box->y1; + + zwlr_screencopy_frame_v1_send_damage(frame->resource, + damage_x, damage_y, damage_width, damage_height); + } + + pixman_region32_clear(&damage->damage); +} + +static void frame_send_ready(struct wlr_screencopy_frame_v1 *frame, + struct timespec *when) { + time_t tv_sec = when->tv_sec; + uint32_t tv_sec_hi = (sizeof(tv_sec) > 4) ? tv_sec >> 32 : 0; + uint32_t tv_sec_lo = tv_sec & 0xFFFFFFFF; + zwlr_screencopy_frame_v1_send_ready(frame->resource, + tv_sec_hi, tv_sec_lo, when->tv_nsec); +} + +static bool frame_shm_copy(struct wlr_screencopy_frame_v1 *frame, + struct wlr_buffer *src_buffer) { + struct wlr_output *output = frame->output; + struct wlr_renderer *renderer = output->renderer; + assert(renderer); + + void *data; + uint32_t format; + size_t stride; + if (!wlr_buffer_begin_data_ptr_access(frame->buffer, + WLR_BUFFER_DATA_PTR_ACCESS_WRITE, &data, &format, &stride)) { + return false; + } + + bool ok = false; + + struct wlr_texture *texture = wlr_texture_from_buffer(renderer, src_buffer); + if (!texture) { + wlr_log(WLR_DEBUG, "Failed to grab a texture from a buffer during shm screencopy"); + goto out; + } + + ok = wlr_texture_read_pixels(texture, &(struct wlr_texture_read_pixels_options) { + .data = data, + .format = format, + .stride = stride, + .src_box = frame->box, + }); + + wlr_texture_destroy(texture); + +out: + wlr_buffer_end_data_ptr_access(frame->buffer); + + if (!ok) { + wlr_log(WLR_DEBUG, "Failed to copy to destination during shm screencopy"); + } + + return ok; +} + +static bool frame_dma_copy(struct wlr_screencopy_frame_v1 *frame, + struct wlr_buffer *src_buffer) { + struct wlr_buffer *dst_buffer = frame->buffer; + struct wlr_output *output = frame->output; + struct wlr_renderer *renderer = output->renderer; + assert(renderer); + + struct wlr_texture *src_tex = + wlr_texture_from_buffer(renderer, src_buffer); + if (src_tex == NULL) { + wlr_log(WLR_DEBUG, "Failed to grab a texture from a buffer during dma screencopy"); + return false; + } + + bool ok = false; + + struct wlr_render_pass *pass = + wlr_renderer_begin_buffer_pass(renderer, dst_buffer, NULL); + if (!pass) { + goto out; + } + + wlr_render_pass_add_texture(pass, &(struct wlr_render_texture_options) { + .texture = src_tex, + .blend_mode = WLR_RENDER_BLEND_MODE_NONE, + .dst_box = (struct wlr_box){ + .width = dst_buffer->width, + .height = dst_buffer->height, + }, + .src_box = (struct wlr_fbox){ + .x = frame->box.x, + .y = frame->box.y, + .width = frame->box.width, + .height = frame->box.height, + }, + }); + + ok = wlr_render_pass_submit(pass); + +out: + wlr_texture_destroy(src_tex); + + if (!ok) { + wlr_log(WLR_DEBUG, "Failed to render to destination during dma screencopy"); + } + + return ok; +} + +static void frame_handle_output_commit(struct wl_listener *listener, + void *data) { + struct wlr_screencopy_frame_v1 *frame = + wl_container_of(listener, frame, output_commit); + struct wlr_output_event_commit *event = data; + struct wlr_output *output = frame->output; + + if (event->state->committed & WLR_OUTPUT_STATE_ENABLED && !output->enabled) { + goto err; + } + + if (!(event->state->committed & WLR_OUTPUT_STATE_BUFFER)) { + return; + } + + if (!frame->buffer) { + return; + } + + if (frame->with_damage) { + struct screencopy_damage *damage = + screencopy_damage_get_or_create(frame->client, output); + if (damage && pixman_region32_empty(&damage->damage)) { + return; + } + } + + wl_list_remove(&frame->output_commit.link); + wl_list_init(&frame->output_commit.link); + + struct wlr_buffer *src_buffer = event->state->buffer; + if (frame->box.x < 0 || frame->box.y < 0 || + frame->box.x + frame->box.width > src_buffer->width || + frame->box.y + frame->box.height > src_buffer->height) { + goto err; + } + + switch (frame->buffer_cap) { + case WLR_BUFFER_CAP_DMABUF: + if (!frame_dma_copy(frame, src_buffer)) { + goto err; + } + break; + case WLR_BUFFER_CAP_DATA_PTR: + if (!frame_shm_copy(frame, src_buffer)) { + goto err; + } + break; + default: + abort(); // unreachable + } + + zwlr_screencopy_frame_v1_send_flags(frame->resource, 0); + frame_send_damage(frame); + frame_send_ready(frame, &event->when); + frame_destroy(frame); + return; + +err: + zwlr_screencopy_frame_v1_send_failed(frame->resource); + frame_destroy(frame); +} + +static void frame_handle_output_destroy(struct wl_listener *listener, + void *data) { + struct wlr_screencopy_frame_v1 *frame = + wl_container_of(listener, frame, output_destroy); + zwlr_screencopy_frame_v1_send_failed(frame->resource); + frame_destroy(frame); +} + +static void frame_handle_copy(struct wl_client *wl_client, + struct wl_resource *frame_resource, + struct wl_resource *buffer_resource) { + struct wlr_screencopy_frame_v1 *frame = frame_from_resource(frame_resource); + if (frame == NULL) { + return; + } + + struct wlr_output *output = frame->output; + + if (!output->enabled) { + zwlr_screencopy_frame_v1_send_failed(frame->resource); + frame_destroy(frame); + return; + } + + struct wlr_buffer *buffer = wlr_buffer_try_from_resource(buffer_resource); + if (buffer == NULL) { + wl_resource_post_error(frame->resource, + ZWLR_SCREENCOPY_FRAME_V1_ERROR_INVALID_BUFFER, + "invalid buffer"); + return; + } + + if (buffer->width != frame->box.width || buffer->height != frame->box.height) { + wl_resource_post_error(frame->resource, + ZWLR_SCREENCOPY_FRAME_V1_ERROR_INVALID_BUFFER, + "invalid buffer dimensions"); + return; + } + + if (frame->buffer != NULL) { + wl_resource_post_error(frame->resource, + ZWLR_SCREENCOPY_FRAME_V1_ERROR_ALREADY_USED, + "frame already used"); + return; + } + + enum wlr_buffer_cap cap; + struct wlr_dmabuf_attributes dmabuf; + void *data; + uint32_t format; + size_t stride; + if (wlr_buffer_get_dmabuf(buffer, &dmabuf)) { + cap = WLR_BUFFER_CAP_DMABUF; + + if (dmabuf.format != frame->dmabuf_format) { + wl_resource_post_error(frame->resource, + ZWLR_SCREENCOPY_FRAME_V1_ERROR_INVALID_BUFFER, + "invalid buffer format"); + return; + } + } else if (wlr_buffer_begin_data_ptr_access(buffer, + WLR_BUFFER_DATA_PTR_ACCESS_WRITE, &data, &format, &stride)) { + wlr_buffer_end_data_ptr_access(buffer); + + cap = WLR_BUFFER_CAP_DATA_PTR; + + if (format != frame->shm_format) { + wl_resource_post_error(frame->resource, + ZWLR_SCREENCOPY_FRAME_V1_ERROR_INVALID_BUFFER, + "invalid buffer format"); + return; + } + if (stride != (size_t)frame->shm_stride) { + wl_resource_post_error(frame->resource, + ZWLR_SCREENCOPY_FRAME_V1_ERROR_INVALID_BUFFER, + "invalid buffer stride"); + return; + } + } else { + wl_resource_post_error(frame->resource, + ZWLR_SCREENCOPY_FRAME_V1_ERROR_INVALID_BUFFER, + "unsupported buffer type"); + return; + } + + frame->buffer = buffer; + frame->buffer_cap = cap; + + wl_signal_add(&output->events.commit, &frame->output_commit); + frame->output_commit.notify = frame_handle_output_commit; + + // Request a frame because we can't assume that the current front buffer is still usable. It may + // have been released already, and we shouldn't lock it here because compositors want to render + // into the least damaged buffer. + wlr_output_update_needs_frame(output); + + wlr_output_lock_attach_render(output, true); + if (frame->overlay_cursor) { + wlr_output_lock_software_cursors(output, true); + frame->cursor_locked = true; + } +} + +static void frame_handle_copy_with_damage(struct wl_client *wl_client, + struct wl_resource *frame_resource, + struct wl_resource *buffer_resource) { + struct wlr_screencopy_frame_v1 *frame = frame_from_resource(frame_resource); + if (frame == NULL) { + return; + } + frame->with_damage = true; + frame_handle_copy(wl_client, frame_resource, buffer_resource); +} + +static void frame_handle_destroy(struct wl_client *wl_client, + struct wl_resource *frame_resource) { + wl_resource_destroy(frame_resource); +} + +static const struct zwlr_screencopy_frame_v1_interface frame_impl = { + .copy = frame_handle_copy, + .destroy = frame_handle_destroy, + .copy_with_damage = frame_handle_copy_with_damage, +}; + +static void frame_handle_resource_destroy(struct wl_resource *frame_resource) { + struct wlr_screencopy_frame_v1 *frame = frame_from_resource(frame_resource); + frame_destroy(frame); +} + + +static const struct zwlr_screencopy_manager_v1_interface manager_impl; + +static struct wlr_screencopy_v1_client *client_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_screencopy_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void capture_output(struct wl_client *wl_client, + struct wlr_screencopy_v1_client *client, uint32_t version, + uint32_t id, int32_t overlay_cursor, struct wlr_output *output, + const struct wlr_box *box) { + struct wlr_screencopy_frame_v1 *frame = calloc(1, sizeof(*frame)); + if (frame == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + frame->output = output; + frame->overlay_cursor = !!overlay_cursor; + + frame->resource = wl_resource_create(wl_client, + &zwlr_screencopy_frame_v1_interface, version, id); + if (frame->resource == NULL) { + free(frame); + wl_client_post_no_memory(wl_client); + return; + } + wl_resource_set_implementation(frame->resource, &frame_impl, frame, + frame_handle_resource_destroy); + + if (output == NULL || !output->enabled) { + wl_resource_set_user_data(frame->resource, NULL); + zwlr_screencopy_frame_v1_send_failed(frame->resource); + free(frame); + return; + } + + frame->client = client; + client->ref++; + + wl_list_insert(&client->manager->frames, &frame->link); + + wl_list_init(&frame->output_commit.link); + + wl_signal_add(&output->events.destroy, &frame->output_destroy); + frame->output_destroy.notify = frame_handle_output_destroy; + + struct wlr_renderer *renderer = output->renderer; + assert(renderer); + + if (!wlr_output_configure_primary_swapchain(output, NULL, &output->swapchain)) { + goto error; + } + + struct wlr_buffer *buffer = wlr_swapchain_acquire(output->swapchain); + if (buffer == NULL) { + goto error; + } + + struct wlr_texture *texture = wlr_texture_from_buffer(renderer, buffer); + wlr_buffer_unlock(buffer); + if (!texture) { + goto error; + } + + frame->shm_format = wlr_texture_preferred_read_format(texture); + wlr_texture_destroy(texture); + + if (frame->shm_format == DRM_FORMAT_INVALID) { + wlr_log(WLR_ERROR, + "Failed to capture output: no read format supported by renderer"); + goto error; + } + const struct wlr_pixel_format_info *shm_info = + drm_get_pixel_format_info(frame->shm_format); + if (!shm_info) { + wlr_log(WLR_ERROR, + "Failed to capture output: no pixel format info matching read format"); + goto error; + } + + if (output->allocator && + (output->allocator->buffer_caps & WLR_BUFFER_CAP_DMABUF)) { + frame->dmabuf_format = output->render_format; + } else { + frame->dmabuf_format = DRM_FORMAT_INVALID; + } + + struct wlr_box buffer_box = {0}; + if (box == NULL) { + buffer_box.width = output->width; + buffer_box.height = output->height; + } else { + int ow, oh; + wlr_output_effective_resolution(output, &ow, &oh); + + buffer_box = *box; + + wlr_box_transform(&buffer_box, &buffer_box, + wlr_output_transform_invert(output->transform), ow, oh); + buffer_box.x *= output->scale; + buffer_box.y *= output->scale; + buffer_box.width *= output->scale; + buffer_box.height *= output->scale; + } + + frame->box = buffer_box; + frame->shm_stride = pixel_format_info_min_stride(shm_info, buffer_box.width); + + zwlr_screencopy_frame_v1_send_buffer(frame->resource, + convert_drm_format_to_wl_shm(frame->shm_format), + buffer_box.width, buffer_box.height, frame->shm_stride); + + if (version >= 3) { + if (frame->dmabuf_format != DRM_FORMAT_INVALID) { + zwlr_screencopy_frame_v1_send_linux_dmabuf( + frame->resource, frame->dmabuf_format, + buffer_box.width, buffer_box.height); + } + + zwlr_screencopy_frame_v1_send_buffer_done(frame->resource); + } + + return; + +error: + zwlr_screencopy_frame_v1_send_failed(frame->resource); + frame_destroy(frame); +} + +static void manager_handle_capture_output(struct wl_client *wl_client, + struct wl_resource *manager_resource, uint32_t id, + int32_t overlay_cursor, struct wl_resource *output_resource) { + struct wlr_screencopy_v1_client *client = + client_from_resource(manager_resource); + uint32_t version = wl_resource_get_version(manager_resource); + struct wlr_output *output = wlr_output_from_resource(output_resource); + + capture_output(wl_client, client, version, id, overlay_cursor, output, + NULL); +} + +static void manager_handle_capture_output_region(struct wl_client *wl_client, + struct wl_resource *manager_resource, uint32_t id, + int32_t overlay_cursor, struct wl_resource *output_resource, + int32_t x, int32_t y, int32_t width, int32_t height) { + struct wlr_screencopy_v1_client *client = + client_from_resource(manager_resource); + uint32_t version = wl_resource_get_version(manager_resource); + struct wlr_output *output = wlr_output_from_resource(output_resource); + + struct wlr_box box = { + .x = x, + .y = y, + .width = width, + .height = height, + }; + capture_output(wl_client, client, version, id, overlay_cursor, output, + &box); +} + +static void manager_handle_destroy(struct wl_client *wl_client, + struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static const struct zwlr_screencopy_manager_v1_interface manager_impl = { + .capture_output = manager_handle_capture_output, + .capture_output_region = manager_handle_capture_output_region, + .destroy = manager_handle_destroy, +}; + +static void manager_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_screencopy_v1_client *client = + client_from_resource(resource); + client_unref(client); +} + +static void manager_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_screencopy_manager_v1 *manager = data; + + struct wlr_screencopy_v1_client *client = calloc(1, sizeof(*client)); + if (client == NULL) { + goto failure; + } + + struct wl_resource *resource = wl_resource_create(wl_client, + &zwlr_screencopy_manager_v1_interface, version, id); + if (resource == NULL) { + goto failure; + } + + client->ref = 1; + client->manager = manager; + wl_list_init(&client->damages); + + wl_resource_set_implementation(resource, &manager_impl, client, + manager_handle_resource_destroy); + wl_list_init(wl_resource_get_link(resource)); + if (manager == NULL) { + return; + } + + + return; +failure: + free(client); + wl_client_post_no_memory(wl_client); +} + +static void screencopy_manager_v1_destroy(struct wlr_screencopy_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_screencopy_manager_v1_destroy(struct wlr_screencopy_manager_v1 *manager, + bool destroy_global_safe) { + screencopy_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_screencopy_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + screencopy_manager_v1_destroy(manager, false); +} + +struct wlr_screencopy_manager_v1 *wlr_screencopy_manager_v1_create( + struct wl_display *display) { + struct wlr_screencopy_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + manager->global = wl_global_create(display, + &zwlr_screencopy_manager_v1_interface, SCREENCOPY_MANAGER_VERSION, + manager, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + wl_list_init(&manager->frames); + + wl_signal_init(&manager->events.destroy); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_security_context_v1.c b/3rdparty/wlroots/types/wlr_security_context_v1.c new file mode 100644 index 0000000000..58d0856d47 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_security_context_v1.c @@ -0,0 +1,466 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "security-context-v1-protocol.h" +#include "util/fd.h" +#include "util/global.h" + +#define SECURITY_CONTEXT_MANAGER_V1_VERSION 1 + +struct wlr_security_context_v1 { + struct wlr_security_context_manager_v1 *manager; + struct wlr_security_context_v1_state state; + struct wl_list link; // wlr_security_context_manager_v1.contexts + int listen_fd, close_fd; + struct wl_event_source *listen_source, *close_source; +}; + +struct wlr_security_context_v1_client { + struct wlr_security_context_v1_state state; + struct wl_listener destroy; +}; + +static void resource_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wp_security_context_manager_v1_interface manager_impl; +static const struct wp_security_context_v1_interface security_context_impl; + +static struct wlr_security_context_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_security_context_manager_v1_interface, &manager_impl)); + struct wlr_security_context_manager_v1 *manager = + wl_resource_get_user_data(resource); + assert(manager != NULL); + return manager; +} + +/** + * Get a struct wlr_security_context_v1 from a struct wl_resource. + * + * NULL is returned if the security context has been committed. + */ +static struct wlr_security_context_v1 *security_context_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_security_context_v1_interface, &security_context_impl)); + return wl_resource_get_user_data(resource); +} + +static void security_context_state_finish(struct wlr_security_context_v1_state *state) { + free(state->app_id); + free(state->sandbox_engine); + free(state->instance_id); +} + +static bool copy_state_field(char **dst, const char *src) { + if (src == NULL) { + return true; + } + *dst = strdup(src); + return *dst != NULL; +} + +static bool security_context_state_copy(struct wlr_security_context_v1_state *dst, + const struct wlr_security_context_v1_state *src) { + bool ok = copy_state_field(&dst->app_id, src->app_id) && + copy_state_field(&dst->sandbox_engine, src->sandbox_engine) && + copy_state_field(&dst->instance_id, src->instance_id); + if (!ok) { + security_context_state_finish(dst); + } + return ok; +} + +static void security_context_destroy( + struct wlr_security_context_v1 *security_context) { + if (security_context == NULL) { + return; + } + + if (security_context->listen_source != NULL) { + wl_event_source_remove(security_context->listen_source); + } + if (security_context->close_source != NULL) { + wl_event_source_remove(security_context->close_source); + } + + close(security_context->listen_fd); + close(security_context->close_fd); + + security_context_state_finish(&security_context->state); + wl_list_remove(&security_context->link); + free(security_context); +} + +static void security_context_client_destroy( + struct wlr_security_context_v1_client *security_context_client) { + wl_list_remove(&security_context_client->destroy.link); + security_context_state_finish(&security_context_client->state); + free(security_context_client); +} + +static void security_context_client_handle_destroy(struct wl_listener *listener, + void *data) { + struct wlr_security_context_v1_client *security_context_client = + wl_container_of(listener, security_context_client, destroy); + security_context_client_destroy(security_context_client); +} + +static int security_context_handle_listen_fd_event(int listen_fd, uint32_t mask, + void *data) { + struct wlr_security_context_v1 *security_context = data; + + if (mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR)) { + security_context_destroy(security_context); + return 0; + } + + if (mask & WL_EVENT_READABLE) { + int client_fd = accept(listen_fd, NULL, NULL); + if (client_fd < 0) { + wlr_log_errno(WLR_ERROR, "accept failed"); + return 0; + } + + if (!set_cloexec(client_fd, true)) { + close(client_fd); + return 0; + } + + struct wlr_security_context_v1_client *security_context_client = + calloc(1, sizeof(*security_context_client)); + if (security_context_client == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + close(client_fd); + return 0; + } + + struct wl_display *display = + wl_global_get_display(security_context->manager->global); + struct wl_client *client = wl_client_create(display, client_fd); + if (client == NULL) { + wlr_log(WLR_ERROR, "wl_client_create failed"); + close(client_fd); + free(security_context_client); + return 0; + } + + security_context_client->destroy.notify = security_context_client_handle_destroy; + wl_client_add_destroy_listener(client, &security_context_client->destroy); + + if (!security_context_state_copy(&security_context_client->state, + &security_context->state)) { + security_context_client_destroy(security_context_client); + wl_client_post_no_memory(client); + return 0; + } + } + + return 0; +} + +static int security_context_handle_close_fd_event(int fd, uint32_t mask, + void *data) { + struct wlr_security_context_v1 *security_context = data; + + if (mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR)) { + security_context_destroy(security_context); + } + + return 0; +} + +static void security_context_handle_commit(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_security_context_v1 *security_context = + security_context_from_resource(resource); + if (security_context == NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_V1_ERROR_ALREADY_USED, + "Security context has already been committed"); + return; + } + + // In theory the compositor should prevent this with a global filter, but + // let's make sure it doesn't happen. + if (wlr_security_context_manager_v1_lookup_client(security_context->manager, + client) != NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_MANAGER_V1_ERROR_NESTED, + "Nested security contexts are forbidden"); + return; + } + + struct wl_display *display = wl_client_get_display(client); + struct wl_event_loop *loop = wl_display_get_event_loop(display); + + security_context->listen_source = wl_event_loop_add_fd(loop, + security_context->listen_fd, WL_EVENT_READABLE, + security_context_handle_listen_fd_event, security_context); + if (security_context->listen_source == NULL) { + wl_resource_post_no_memory(resource); + return; + } + + security_context->close_source = wl_event_loop_add_fd(loop, + security_context->close_fd, 0, security_context_handle_close_fd_event, + security_context); + if (security_context->close_source == NULL) { + wl_resource_post_no_memory(resource); + return; + } + + wl_resource_set_user_data(resource, NULL); + + struct wlr_security_context_v1_commit_event event = { + .state = &security_context->state, + .parent_client = client, + }; + wl_signal_emit_mutable(&security_context->manager->events.commit, &event); +} + +static void security_context_handle_set_sandbox_engine(struct wl_client *client, + struct wl_resource *resource, const char *sandbox_engine) { + struct wlr_security_context_v1 *security_context = + security_context_from_resource(resource); + if (security_context == NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_V1_ERROR_ALREADY_USED, + "Security context has already been committed"); + return; + } + + if (security_context->state.sandbox_engine != NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_V1_ERROR_ALREADY_SET, + "Sandbox engine has already been set"); + return; + } + + security_context->state.sandbox_engine = strdup(sandbox_engine); + if (security_context->state.sandbox_engine == NULL) { + wl_resource_post_no_memory(resource); + } +} + +static void security_context_handle_set_app_id(struct wl_client *client, + struct wl_resource *resource, const char *app_id) { + struct wlr_security_context_v1 *security_context = + security_context_from_resource(resource); + if (security_context == NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_V1_ERROR_ALREADY_USED, + "Security context has already been committed"); + return; + } + + if (security_context->state.app_id != NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_V1_ERROR_ALREADY_SET, + "App ID has already been set"); + return; + } + + security_context->state.app_id = strdup(app_id); + if (security_context->state.app_id == NULL) { + wl_resource_post_no_memory(resource); + } +} + +static void security_context_handle_set_instance_id(struct wl_client *client, + struct wl_resource *resource, const char *instance_id) { + struct wlr_security_context_v1 *security_context = + security_context_from_resource(resource); + if (security_context == NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_V1_ERROR_ALREADY_USED, + "Security context has already been committed"); + return; + } + + if (security_context->state.instance_id != NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_V1_ERROR_ALREADY_SET, + "Instance ID has already been set"); + return; + } + + security_context->state.instance_id = strdup(instance_id); + if (security_context->state.instance_id == NULL) { + wl_resource_post_no_memory(resource); + } +} + +static const struct wp_security_context_v1_interface security_context_impl = { + .destroy = resource_handle_destroy, + .commit = security_context_handle_commit, + .set_sandbox_engine = security_context_handle_set_sandbox_engine, + .set_app_id = security_context_handle_set_app_id, + .set_instance_id = security_context_handle_set_instance_id, +}; + +static void security_context_resource_destroy(struct wl_resource *resource) { + struct wlr_security_context_v1 *security_context = + security_context_from_resource(resource); + security_context_destroy(security_context); +} + +static void manager_handle_create_listener(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + int listen_fd, int close_fd) { + struct wlr_security_context_manager_v1 *manager = + manager_from_resource(manager_resource); + + struct stat stat_buf = {0}; + if (fstat(listen_fd, &stat_buf) != 0) { + wlr_log_errno(WLR_ERROR, "fstat failed on listen FD"); + wl_resource_post_error(manager_resource, + WP_SECURITY_CONTEXT_MANAGER_V1_ERROR_INVALID_LISTEN_FD, + "Invalid listen_fd"); + return; + } else if (!S_ISSOCK(stat_buf.st_mode)) { + wl_resource_post_error(manager_resource, + WP_SECURITY_CONTEXT_MANAGER_V1_ERROR_INVALID_LISTEN_FD, + "listen_fd is not a socket"); + return; + } + + int accept_conn = 0; + socklen_t accept_conn_size = sizeof(accept_conn); + if (getsockopt(listen_fd, SOL_SOCKET, SO_ACCEPTCONN, &accept_conn, + &accept_conn_size) != 0) { + wlr_log_errno(WLR_ERROR, "getsockopt failed on listen FD"); + wl_resource_post_error(manager_resource, + WP_SECURITY_CONTEXT_MANAGER_V1_ERROR_INVALID_LISTEN_FD, + "Invalid listen_fd"); + return; + } else if (accept_conn == 0) { + wl_resource_post_error(manager_resource, + WP_SECURITY_CONTEXT_MANAGER_V1_ERROR_INVALID_LISTEN_FD, + "listen_fd is not a listening socket"); + return; + } + + struct wlr_security_context_v1 *security_context = + calloc(1, sizeof(*security_context)); + if (security_context == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + + security_context->manager = manager; + security_context->listen_fd = listen_fd; + security_context->close_fd = close_fd; + + uint32_t version = wl_resource_get_version(manager_resource); + struct wl_resource *resource = wl_resource_create(client, + &wp_security_context_v1_interface, version, id); + if (resource == NULL) { + free(security_context); + wl_resource_post_no_memory(manager_resource); + return; + } + wl_resource_set_implementation(resource, &security_context_impl, + security_context, security_context_resource_destroy); + + wl_list_insert(&manager->contexts, &security_context->link); +} + +static const struct wp_security_context_manager_v1_interface manager_impl = { + .destroy = resource_handle_destroy, + .create_listener = manager_handle_create_listener, +}; + +static void manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_security_context_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &wp_security_context_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, manager, NULL); +} + +static void security_context_manager_v1_destroy(struct wlr_security_context_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + assert(wl_list_empty(&manager->events.commit.listener_list)); + + struct wlr_security_context_v1 *security_context, *tmp; + wl_list_for_each_safe(security_context, tmp, &manager->contexts, link) { + security_context_destroy(security_context); + } + + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + wl_list_remove(&manager->display_destroy.link); + free(manager); +} + +void wlr_security_context_manager_v1_destroy(struct wlr_security_context_manager_v1 *manager, + bool destroy_global_safe) { + security_context_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_security_context_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + security_context_manager_v1_destroy(manager, false); +} + +struct wlr_security_context_manager_v1 *wlr_security_context_manager_v1_create( + struct wl_display *display) { + struct wlr_security_context_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + manager->global = wl_global_create(display, + &wp_security_context_manager_v1_interface, + SECURITY_CONTEXT_MANAGER_V1_VERSION, manager, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + wl_list_init(&manager->contexts); + + wl_signal_init(&manager->events.destroy); + wl_signal_init(&manager->events.commit); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} + +const struct wlr_security_context_v1_state *wlr_security_context_manager_v1_lookup_client( + struct wlr_security_context_manager_v1 *manager, const struct wl_client *client) { + struct wl_listener *listener = wl_client_get_destroy_listener((struct wl_client *)client, + security_context_client_handle_destroy); + if (listener == NULL) { + return NULL; + } + + struct wlr_security_context_v1_client *security_context_client = + wl_container_of(listener, security_context_client, destroy); + return &security_context_client->state; +} diff --git a/3rdparty/wlroots/types/wlr_server_decoration.c b/3rdparty/wlroots/types/wlr_server_decoration.c new file mode 100644 index 0000000000..a403dbc440 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_server_decoration.c @@ -0,0 +1,225 @@ +#include +#include +#include +#include +#include +#include +#include "server-decoration-protocol.h" +#include "util/global.h" + +static const struct org_kde_kwin_server_decoration_interface + server_decoration_impl; + +static struct wlr_server_decoration *decoration_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &org_kde_kwin_server_decoration_interface, &server_decoration_impl)); + return wl_resource_get_user_data(resource); +} + +static void server_decoration_handle_release(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void server_decoration_handle_request_mode(struct wl_client *client, + struct wl_resource *resource, uint32_t mode) { + struct wlr_server_decoration *decoration = + decoration_from_resource(resource); + if (decoration == NULL || decoration->mode == mode) { + return; + } + decoration->mode = mode; + wl_signal_emit_mutable(&decoration->events.mode, decoration); + org_kde_kwin_server_decoration_send_mode(decoration->resource, + decoration->mode); +} + +static void server_decoration_destroy( + struct wlr_server_decoration *decoration) { + wl_signal_emit_mutable(&decoration->events.destroy, decoration); + + assert(wl_list_empty(&decoration->events.destroy.listener_list)); + assert(wl_list_empty(&decoration->events.mode.listener_list)); + + wl_list_remove(&decoration->surface_destroy_listener.link); + wl_resource_set_user_data(decoration->resource, NULL); + wl_list_remove(&decoration->link); + free(decoration); +} + +static void server_decoration_destroy_resource(struct wl_resource *resource) { + struct wlr_server_decoration *decoration = + decoration_from_resource(resource); + if (decoration != NULL) { + server_decoration_destroy(decoration); + } +} + +static void server_decoration_handle_surface_destroy( + struct wl_listener *listener, void *data) { + struct wlr_server_decoration *decoration = + wl_container_of(listener, decoration, surface_destroy_listener); + server_decoration_destroy(decoration); +} + +static const struct org_kde_kwin_server_decoration_interface + server_decoration_impl = { + .release = server_decoration_handle_release, + .request_mode = server_decoration_handle_request_mode, +}; + +static const struct org_kde_kwin_server_decoration_manager_interface + server_decoration_manager_impl; + +static struct wlr_server_decoration_manager *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &org_kde_kwin_server_decoration_manager_interface, + &server_decoration_manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void server_decoration_manager_handle_create(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + struct wl_resource *surface_resource) { + struct wlr_server_decoration_manager *manager = + manager_from_resource(manager_resource); + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + + struct wlr_server_decoration *decoration = calloc(1, sizeof(*decoration)); + if (decoration == NULL) { + wl_client_post_no_memory(client); + return; + } + decoration->surface = surface; + decoration->mode = manager->default_mode; + + int version = wl_resource_get_version(manager_resource); + decoration->resource = wl_resource_create(client, + &org_kde_kwin_server_decoration_interface, version, id); + if (decoration->resource == NULL) { + free(decoration); + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(decoration->resource, + &server_decoration_impl, decoration, + server_decoration_destroy_resource); + + wlr_log(WLR_DEBUG, "new server_decoration %p (res %p)", decoration, + decoration->resource); + + wl_signal_init(&decoration->events.destroy); + wl_signal_init(&decoration->events.mode); + + wl_signal_add(&surface->events.destroy, + &decoration->surface_destroy_listener); + decoration->surface_destroy_listener.notify = + server_decoration_handle_surface_destroy; + + wl_list_insert(&manager->decorations, &decoration->link); + + org_kde_kwin_server_decoration_send_mode(decoration->resource, + decoration->mode); + + wl_signal_emit_mutable(&manager->events.new_decoration, decoration); +} + +static const struct org_kde_kwin_server_decoration_manager_interface + server_decoration_manager_impl = { + .create = server_decoration_manager_handle_create, +}; + +void wlr_server_decoration_manager_set_default_mode( + struct wlr_server_decoration_manager *manager, uint32_t default_mode) { + manager->default_mode = default_mode; + + struct wl_resource *resource; + wl_resource_for_each(resource, &manager->resources) { + org_kde_kwin_server_decoration_manager_send_default_mode(resource, + manager->default_mode); + } +} + +static void server_decoration_manager_destroy_resource( + struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void server_decoration_manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_server_decoration_manager *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &org_kde_kwin_server_decoration_manager_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &server_decoration_manager_impl, + manager, server_decoration_manager_destroy_resource); + wl_list_init(wl_resource_get_link(resource)); + if (manager == NULL) { + return; + } + + + wl_list_insert(&manager->resources, wl_resource_get_link(resource)); + + org_kde_kwin_server_decoration_manager_send_default_mode(resource, + manager->default_mode); +} + +static void server_decoration_manager_destroy(struct wlr_server_decoration_manager *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.new_decoration.listener_list)); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_server_decoration_manager_destroy(struct wlr_server_decoration_manager *manager, + bool destroy_global_safe) { + server_decoration_manager_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_server_decoration_manager *manager = + wl_container_of(listener, manager, display_destroy); + server_decoration_manager_destroy(manager, false); +} + +struct wlr_server_decoration_manager *wlr_server_decoration_manager_create( + struct wl_display *display) { + struct wlr_server_decoration_manager *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + manager->global = wl_global_create(display, + &org_kde_kwin_server_decoration_manager_interface, 1, manager, + server_decoration_manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + manager->default_mode = ORG_KDE_KWIN_SERVER_DECORATION_MANAGER_MODE_NONE; + wl_list_init(&manager->resources); + wl_list_init(&manager->decorations); + + wl_signal_init(&manager->events.new_decoration); + wl_signal_init(&manager->events.destroy); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_session_lock_v1.c b/3rdparty/wlroots/types/wlr_session_lock_v1.c new file mode 100644 index 0000000000..124e0b4c3b --- /dev/null +++ b/3rdparty/wlroots/types/wlr_session_lock_v1.c @@ -0,0 +1,494 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "ext-session-lock-v1-protocol.h" +#include "util/global.h" + +// Note: ext_session_lock_surface_v1 objects become inert +// when the corresponding ext_session_lock_v1 is destroyed + +#define SESSION_LOCK_VERSION 1 + +static void resource_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct ext_session_lock_manager_v1_interface lock_manager_implementation; +static const struct ext_session_lock_v1_interface lock_implementation; +static const struct ext_session_lock_surface_v1_interface lock_surface_implementation; + +static void lock_surface_destroy(struct wlr_session_lock_surface_v1 *lock_surface) { + wlr_surface_unmap(lock_surface->surface); + + wl_signal_emit_mutable(&lock_surface->events.destroy, NULL); + + wl_list_remove(&lock_surface->link); + + struct wlr_session_lock_surface_v1_configure *configure, *tmp; + wl_list_for_each_safe(configure, tmp, &lock_surface->configure_list, link) { + wl_list_remove(&configure->link); + free(configure); + } + + assert(wl_list_empty(&lock_surface->events.destroy.listener_list)); + + wl_list_remove(&lock_surface->output_destroy.link); + wlr_surface_synced_finish(&lock_surface->synced); + wl_resource_set_user_data(lock_surface->resource, NULL); + free(lock_surface); +} + +static struct wlr_session_lock_manager_v1 *lock_manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_session_lock_manager_v1_interface, &lock_manager_implementation)); + struct wlr_session_lock_manager_v1 *lock_manager = + wl_resource_get_user_data(resource); + assert(lock_manager != NULL); + return lock_manager; +} + +static struct wlr_session_lock_v1 *lock_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_session_lock_v1_interface, &lock_implementation)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_session_lock_surface_v1 *lock_surface_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_session_lock_surface_v1_interface, &lock_surface_implementation)); + return wl_resource_get_user_data(resource); +} + +static const struct wlr_surface_role lock_surface_role; + +struct wlr_session_lock_surface_v1 *wlr_session_lock_surface_v1_try_from_wlr_surface( + struct wlr_surface *surface) { + if (surface->role != &lock_surface_role || surface->role_resource == NULL) { + return NULL; + } + return lock_surface_from_resource(surface->role_resource); +} + +uint32_t wlr_session_lock_surface_v1_configure( + struct wlr_session_lock_surface_v1 *lock_surface, + uint32_t width, uint32_t height) { + struct wlr_session_lock_surface_v1_configure *configure = calloc(1, sizeof(*configure)); + if (configure == NULL) { + wl_resource_post_no_memory(lock_surface->resource); + return lock_surface->pending.configure_serial; + } + + struct wl_display *display = + wl_client_get_display(wl_resource_get_client(lock_surface->resource)); + + configure->width = width; + configure->height = height; + configure->serial = wl_display_next_serial(display); + + wl_list_insert(lock_surface->configure_list.prev, &configure->link); + + ext_session_lock_surface_v1_send_configure(lock_surface->resource, + configure->serial, configure->width, configure->height); + + return configure->serial; +} + +static void lock_surface_handle_ack_configure(struct wl_client *client, + struct wl_resource *resource, uint32_t serial) { + struct wlr_session_lock_surface_v1 *lock_surface = + lock_surface_from_resource(resource); + if (lock_surface == NULL) { + return; + } + + // First find the ack'ed configure + bool found = false; + struct wlr_session_lock_surface_v1_configure *configure, *tmp; + wl_list_for_each(configure, &lock_surface->configure_list, link) { + if (configure->serial == serial) { + found = true; + break; + } + } + if (!found) { + wl_resource_post_error(resource, + EXT_SESSION_LOCK_SURFACE_V1_ERROR_INVALID_SERIAL, + "ack_configure serial %" PRIu32 + " does not match any configure serial", serial); + return; + } + // Then remove old configures from the list + wl_list_for_each_safe(configure, tmp, &lock_surface->configure_list, link) { + if (configure->serial == serial) { + break; + } + wl_list_remove(&configure->link); + free(configure); + } + + lock_surface->pending.configure_serial = configure->serial; + lock_surface->pending.width = configure->width; + lock_surface->pending.height = configure->height; + + lock_surface->configured = true; + + wl_list_remove(&configure->link); + free(configure); +} + +static const struct ext_session_lock_surface_v1_interface lock_surface_implementation = { + .destroy = resource_handle_destroy, + .ack_configure = lock_surface_handle_ack_configure, +}; + +static void lock_surface_role_client_commit(struct wlr_surface *surface) { + struct wlr_session_lock_surface_v1 *lock_surface = + wlr_session_lock_surface_v1_try_from_wlr_surface(surface); + if (lock_surface == NULL) { + return; + } + + if (!wlr_surface_state_has_buffer(&surface->pending)) { + wlr_surface_reject_pending(surface, lock_surface->resource, + EXT_SESSION_LOCK_SURFACE_V1_ERROR_NULL_BUFFER, + "session lock surface is committed with a null buffer"); + return; + } + + if (!lock_surface->configured) { + wlr_surface_reject_pending(surface, lock_surface->resource, + EXT_SESSION_LOCK_SURFACE_V1_ERROR_COMMIT_BEFORE_FIRST_ACK, + "session lock surface has never been configured"); + return; + } + + if ((uint32_t)surface->pending.width != lock_surface->pending.width || + (uint32_t)surface->pending.height != lock_surface->pending.height) { + wlr_surface_reject_pending(surface, lock_surface->resource, + EXT_SESSION_LOCK_SURFACE_V1_ERROR_DIMENSIONS_MISMATCH, + "committed surface dimensions do not match last acked configure"); + return; + } +} + +static void lock_surface_role_commit(struct wlr_surface *surface) { + struct wlr_session_lock_surface_v1 *lock_surface = + wlr_session_lock_surface_v1_try_from_wlr_surface(surface); + if (lock_surface == NULL) { + return; + } + + wlr_surface_map(surface); +} + +static void lock_surface_role_destroy(struct wlr_surface *surface) { + struct wlr_session_lock_surface_v1 *lock_surface = + wlr_session_lock_surface_v1_try_from_wlr_surface(surface); + if (lock_surface == NULL) { + return; + } + lock_surface_destroy(lock_surface); +} + +static const struct wlr_surface_role lock_surface_role = { + .name = "ext_session_lock_surface_v1", + .client_commit = lock_surface_role_client_commit, + .commit = lock_surface_role_commit, + .destroy = lock_surface_role_destroy, +}; + +static const struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(struct wlr_session_lock_surface_v1_state), +}; + +static void lock_surface_handle_output_destroy(struct wl_listener *listener, + void *data) { + struct wlr_session_lock_surface_v1 *lock_surface = + wl_container_of(listener, lock_surface, output_destroy); + lock_surface_destroy(lock_surface); +} + +static void lock_handle_get_lock_surface(struct wl_client *client, + struct wl_resource *lock_resource, uint32_t id, + struct wl_resource *surface_resource, + struct wl_resource *output_resource) { + // We always need to create a lock surface resource to stay in sync + // with the client, even if the lock resource or output resource is + // inert. For example, if the compositor denies the lock and immediately + // calls wlr_session_lock_v1_destroy() the client may have already sent + // get_lock_surface requests. + struct wl_resource *lock_surface_resource = wl_resource_create( + client, &ext_session_lock_surface_v1_interface, + wl_resource_get_version(lock_resource), id); + if (lock_surface_resource == NULL) { + wl_client_post_no_memory(client); + return; + } + + // Leave the lock surface resource inert for now, we will set the + // user data at the end of this function if everything is successful. + wl_resource_set_implementation(lock_surface_resource, + &lock_surface_implementation, NULL, NULL); + + struct wlr_session_lock_v1 *lock = lock_from_resource(lock_resource); + if (lock == NULL) { + return; + } + + struct wlr_output *output = wlr_output_from_resource(output_resource); + if (output == NULL) { + return; + } + + struct wlr_session_lock_surface_v1 *other; + wl_list_for_each(other, &lock->surfaces, link) { + if (other->output == output) { + wl_resource_post_error(lock_resource, + EXT_SESSION_LOCK_V1_ERROR_DUPLICATE_OUTPUT, + "session lock surface already created for the given output"); + return; + } + } + + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + + if (wlr_surface_has_buffer(surface)) { + wl_resource_post_error(lock_resource, + EXT_SESSION_LOCK_V1_ERROR_ALREADY_CONSTRUCTED, + "surface already has a buffer attached"); + return; + } + + struct wlr_session_lock_surface_v1 *lock_surface = calloc(1, sizeof(*lock_surface)); + if (lock_surface == NULL) { + wl_client_post_no_memory(client); + return; + } + + if (!wlr_surface_set_role(surface, &lock_surface_role, + lock_resource, EXT_SESSION_LOCK_V1_ERROR_ROLE)) { + free(lock_surface); + return; + } + + if (!wlr_surface_synced_init(&lock_surface->synced, surface, + &surface_synced_impl, &lock_surface->pending, &lock_surface->current)) { + free(lock_surface); + wl_client_post_no_memory(client); + return; + } + + lock_surface->resource = lock_surface_resource; + wl_resource_set_user_data(lock_surface_resource, lock_surface); + + wlr_surface_set_role_object(surface, lock_surface_resource); + + wl_list_insert(&lock->surfaces, &lock_surface->link); + + lock_surface->output = output; + lock_surface->surface = surface; + + wl_list_init(&lock_surface->configure_list); + + wl_signal_init(&lock_surface->events.destroy); + + wl_signal_add(&output->events.destroy, &lock_surface->output_destroy); + lock_surface->output_destroy.notify = lock_surface_handle_output_destroy; + + wl_signal_emit_mutable(&lock->events.new_surface, lock_surface); +} + +static void lock_handle_unlock_and_destroy(struct wl_client *client, + struct wl_resource *lock_resource) { + struct wlr_session_lock_v1 *lock = lock_from_resource(lock_resource); + if (lock == NULL) { + // This can happen if the compositor sent the locked event and + // later the finished event as the lock is destroyed when the + // finished event is sent. + wl_resource_destroy(lock_resource); + return; + } + + if (!lock->locked_sent) { + wl_resource_post_error(lock_resource, + EXT_SESSION_LOCK_V1_ERROR_INVALID_UNLOCK, + "the locked event was never sent"); + return; + } + + wl_signal_emit_mutable(&lock->events.unlock, NULL); + + wl_resource_destroy(lock_resource); +} + +static void lock_handle_destroy(struct wl_client *client, + struct wl_resource *lock_resource) { + struct wlr_session_lock_v1 *lock = lock_from_resource(lock_resource); + if (lock == NULL) { + // The compositor sent the finished event and destroyed the lock. + wl_resource_destroy(lock_resource); + return; + } + + if (lock->locked_sent) { + wl_resource_post_error(lock_resource, + EXT_SESSION_LOCK_V1_ERROR_INVALID_DESTROY, + "the session lock may not be destroyed while locked"); + } else { + wl_resource_post_error(lock_resource, + EXT_SESSION_LOCK_V1_ERROR_INVALID_DESTROY, + "the finished event was never sent"); + } +} + +static const struct ext_session_lock_v1_interface lock_implementation = { + .destroy = lock_handle_destroy, + .get_lock_surface = lock_handle_get_lock_surface, + .unlock_and_destroy = lock_handle_unlock_and_destroy, +}; + +void wlr_session_lock_v1_send_locked(struct wlr_session_lock_v1 *lock) { + assert(!lock->locked_sent); + lock->locked_sent = true; + ext_session_lock_v1_send_locked(lock->resource); +} + +static void lock_destroy(struct wlr_session_lock_v1 *lock) { + struct wlr_session_lock_surface_v1 *lock_surface, *tmp; + wl_list_for_each_safe(lock_surface, tmp, &lock->surfaces, link) { + lock_surface_destroy(lock_surface); + } + assert(wl_list_empty(&lock->surfaces)); + + wl_signal_emit_mutable(&lock->events.destroy, NULL); + + assert(wl_list_empty(&lock->events.new_surface.listener_list)); + assert(wl_list_empty(&lock->events.unlock.listener_list)); + assert(wl_list_empty(&lock->events.destroy.listener_list)); + + wl_resource_set_user_data(lock->resource, NULL); + free(lock); +} + +void wlr_session_lock_v1_destroy(struct wlr_session_lock_v1 *lock) { + ext_session_lock_v1_send_finished(lock->resource); + lock_destroy(lock); +} + +static void lock_resource_destroy(struct wl_resource *lock_resource) { + struct wlr_session_lock_v1 *lock = lock_from_resource(lock_resource); + if (lock != NULL) { + lock_destroy(lock); + } +} + +static void lock_manager_handle_lock(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id) { + struct wlr_session_lock_manager_v1 *lock_manager = + lock_manager_from_resource(manager_resource); + + struct wlr_session_lock_v1 *lock = calloc(1, sizeof(*lock)); + if (lock == NULL) { + wl_client_post_no_memory(client); + return; + } + + lock->resource = wl_resource_create(client, &ext_session_lock_v1_interface, + wl_resource_get_version(manager_resource), id); + if (lock->resource == NULL) { + free(lock); + wl_client_post_no_memory(client); + return; + } + + wl_list_init(&lock->surfaces); + + wl_signal_init(&lock->events.new_surface); + wl_signal_init(&lock->events.unlock); + wl_signal_init(&lock->events.destroy); + + wl_resource_set_implementation(lock->resource, &lock_implementation, + lock, lock_resource_destroy); + + wl_signal_emit_mutable(&lock_manager->events.new_lock, lock); +} + +static const struct ext_session_lock_manager_v1_interface lock_manager_implementation = { + .destroy = resource_handle_destroy, + .lock = lock_manager_handle_lock, +}; + +static void lock_manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_session_lock_manager_v1 *lock_manager = data; + + struct wl_resource *resource = wl_resource_create( + client, &ext_session_lock_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &lock_manager_implementation, + lock_manager, NULL); +} + +static void session_lock_manager_v1_destroy(struct wlr_session_lock_manager_v1 *lock_manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&lock_manager->events.destroy, NULL); + wl_list_remove(&lock_manager->display_destroy.link); + + if (destroy_global_safe) { + wlr_global_destroy_safe(lock_manager->global); + } else { + wl_global_destroy(lock_manager->global); + } + + assert(wl_list_empty(&lock_manager->events.new_lock.listener_list)); + assert(wl_list_empty(&lock_manager->events.destroy.listener_list)); + + free(lock_manager); +} + +void wlr_session_lock_manager_v1_destroy(struct wlr_session_lock_manager_v1 *lock_manager, + bool destroy_global_safe) { + session_lock_manager_v1_destroy(lock_manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_session_lock_manager_v1 *lock_manager = + wl_container_of(listener, lock_manager, display_destroy); + session_lock_manager_v1_destroy(lock_manager, false); +} + +struct wlr_session_lock_manager_v1 *wlr_session_lock_manager_v1_create(struct wl_display *display) { + struct wlr_session_lock_manager_v1 *lock_manager = calloc(1, sizeof(*lock_manager)); + if (lock_manager == NULL) { + return NULL; + } + + struct wl_global *global = wl_global_create(display, + &ext_session_lock_manager_v1_interface, SESSION_LOCK_VERSION, + lock_manager, lock_manager_bind); + if (global == NULL) { + free(lock_manager); + return NULL; + } + lock_manager->global = global; + + wl_signal_init(&lock_manager->events.new_lock); + wl_signal_init(&lock_manager->events.destroy); + + lock_manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &lock_manager->display_destroy); + + return lock_manager; +} diff --git a/3rdparty/wlroots/types/wlr_shm.c b/3rdparty/wlroots/types/wlr_shm.c new file mode 100644 index 0000000000..109c0a8f9b --- /dev/null +++ b/3rdparty/wlroots/types/wlr_shm.c @@ -0,0 +1,605 @@ +#include +#undef _POSIX_C_SOURCE +#define _DEFAULT_SOURCE // for MAP_ANONYMOUS +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "render/pixel_format.h" +#include "util/global.h" + +#ifdef __STDC_NO_ATOMICS__ +#error "C11 atomics are required" +#endif +#if ATOMIC_POINTER_LOCK_FREE == 0 +#error "Lock-free C11 atomic pointers are required" +#endif + +#define SHM_VERSION 2 + +struct wlr_shm_pool { + struct wl_resource *resource; // may be NULL + struct wlr_shm *shm; + struct wl_list buffers; // wlr_shm_buffer.link + int fd; + struct wlr_shm_mapping *mapping; +}; + +/** + * A mapped space to a client-owned file. + * + * Clients may resize pools via wl_shm_pool.resize, in which case we need to + * re-map the FD with a larger size. However we might be at the same time still + * accessing the old mapping (via wlr_buffer_begin_data_ptr_access()). We need + * to keep the old mapping alive in that case. + */ +struct wlr_shm_mapping { + void *data; + size_t size; + bool dropped; // false while a wlr_shm_pool references this mapping +}; + +struct wlr_shm_sigbus_data { + struct wlr_shm_mapping *mapping; + struct sigaction prev_action; + struct wlr_shm_sigbus_data *_Atomic next; +}; + +struct wlr_shm_buffer { + struct wlr_buffer base; + struct wlr_shm_pool *pool; + uint32_t drm_format; + int32_t stride; + off_t offset; + struct wl_list link; // wlr_shm_pool.buffers + struct wl_resource *resource; // may be NULL + + struct wl_listener release; + + struct wlr_shm_sigbus_data sigbus_data; +}; + +// Needs to be a lock-free atomic because it's accessed from a signal handler +static struct wlr_shm_sigbus_data *_Atomic sigbus_data = NULL; + +static const struct wl_buffer_interface wl_buffer_impl; +static const struct wl_shm_pool_interface pool_impl; +static const struct wl_shm_interface shm_impl; + +static bool buffer_resource_is_instance(struct wl_resource *resource) { + return wl_resource_instance_of(resource, &wl_buffer_interface, + &wl_buffer_impl); +} + +static struct wlr_shm_buffer *buffer_from_resource(struct wl_resource *resource) { + assert(buffer_resource_is_instance(resource)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_buffer *buffer_base_from_resource(struct wl_resource *resource) { + return &buffer_from_resource(resource)->base; +} + +static struct wlr_shm_pool *pool_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_shm_pool_interface, + &pool_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_shm *shm_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_shm_interface, &shm_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_shm_mapping *mapping_create(int fd, size_t size) { + void *data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (data == MAP_FAILED) { + wlr_log_errno(WLR_DEBUG, "mmap failed"); + return NULL; + } + + struct wlr_shm_mapping *mapping = calloc(1, sizeof(*mapping)); + if (mapping == NULL) { + munmap(data, size); + return NULL; + } + + mapping->data = data; + mapping->size = size; + return mapping; +} + +static void mapping_consider_destroy(struct wlr_shm_mapping *mapping) { + if (!mapping->dropped) { + return; + } + + for (struct wlr_shm_sigbus_data *cur = sigbus_data; cur != NULL; cur = cur->next) { + if (cur->mapping == mapping) { + return; + } + } + + munmap(mapping->data, mapping->size); + free(mapping); +} + +/** + * Indicate that this mapping is no longer used by its wlr_shm_pool owner. + * + * May destroy the mapping. + */ +static void mapping_drop(struct wlr_shm_mapping *mapping) { + if (mapping == NULL) { + return; + } + + mapping->dropped = true; + mapping_consider_destroy(mapping); +} + +static const struct wlr_buffer_resource_interface buffer_resource_interface = { + .name = "wl_shm", + .is_instance = buffer_resource_is_instance, + .from_resource = buffer_base_from_resource, +}; + +static void pool_consider_destroy(struct wlr_shm_pool *pool); + +static void buffer_destroy(struct wlr_buffer *wlr_buffer) { + struct wlr_shm_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + wl_list_remove(&buffer->release.link); + + wlr_buffer_finish(wlr_buffer); + + assert(buffer->resource == NULL); + wl_list_remove(&buffer->link); + pool_consider_destroy(buffer->pool); + free(buffer); +} + +static bool buffer_get_shm(struct wlr_buffer *wlr_buffer, + struct wlr_shm_attributes *attrs) { + struct wlr_shm_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + *attrs = (struct wlr_shm_attributes){ + .fd = buffer->pool->fd, + .format = buffer->drm_format, + .width = buffer->base.width, + .height = buffer->base.height, + .stride = buffer->stride, + .offset = buffer->offset, + }; + return true; +} + +static void handle_sigbus(int sig, siginfo_t *info, void *context) { + assert(sigbus_data != NULL); + struct sigaction prev_action = sigbus_data->prev_action; + + // Check whether the offending address is inside of the wl_shm_pool's mapped + // space + uintptr_t addr = (uintptr_t)info->si_addr; + struct wlr_shm_mapping *mapping = NULL; + for (struct wlr_shm_sigbus_data *data = sigbus_data; data != NULL; data = data->next) { + uintptr_t mapping_start = (uintptr_t)data->mapping->data; + size_t mapping_size = data->mapping->size; + if (addr >= mapping_start && addr < mapping_start + mapping_size) { + mapping = data->mapping; + break; + } + } + if (mapping == NULL) { + goto reraise; + } + + // Replace the mapping with a new one which won't cause SIGBUS (instead, it + // will read as zeroes). Technically mmap() isn't part of the + // async-signal-safe functions... + if (mmap(mapping->data, mapping->size, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0) == MAP_FAILED) { + goto reraise; + } + + return; + +reraise: + if (prev_action.sa_flags & SA_SIGINFO) { + prev_action.sa_sigaction(sig, info, context); + } else { + prev_action.sa_handler(sig); + } +} + +static bool buffer_begin_data_ptr_access(struct wlr_buffer *wlr_buffer, + uint32_t flags, void **data, uint32_t *format, size_t *stride) { + struct wlr_shm_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + + if (!atomic_is_lock_free(&sigbus_data)) { + wlr_log(WLR_ERROR, "Lock-free atomic pointers are required"); + return false; + } + + // Install a SIGBUS handler. SIGBUS is triggered if the client shrinks the + // backing file, and then we try to access the mapping. + struct sigaction prev_action; + if (sigbus_data == NULL) { + struct sigaction new_action = { + .sa_sigaction = handle_sigbus, + .sa_flags = SA_SIGINFO | SA_NODEFER, + }; + if (sigaction(SIGBUS, &new_action, &prev_action) != 0) { + wlr_log_errno(WLR_ERROR, "sigaction failed"); + return false; + } + } else { + prev_action = sigbus_data->prev_action; + } + + struct wlr_shm_mapping *mapping = buffer->pool->mapping; + + buffer->sigbus_data = (struct wlr_shm_sigbus_data){ + .mapping = mapping, + .prev_action = prev_action, + .next = sigbus_data, + }; + sigbus_data = &buffer->sigbus_data; + + *data = (char *)mapping->data + buffer->offset; + *format = buffer->drm_format; + *stride = buffer->stride; + return true; +} + +static void buffer_end_data_ptr_access(struct wlr_buffer *wlr_buffer) { + struct wlr_shm_buffer *buffer = wl_container_of(wlr_buffer, buffer, base); + + if (sigbus_data == &buffer->sigbus_data) { + sigbus_data = buffer->sigbus_data.next; + } else { + for (struct wlr_shm_sigbus_data *cur = sigbus_data; cur != NULL; cur = cur->next) { + if (cur->next == &buffer->sigbus_data) { + cur->next = buffer->sigbus_data.next; + break; + } + } + } + + if (sigbus_data == NULL) { + if (sigaction(SIGBUS, &buffer->sigbus_data.prev_action, NULL) != 0) { + wlr_log_errno(WLR_ERROR, "sigaction failed"); + } + } + + mapping_consider_destroy(buffer->sigbus_data.mapping); +} + +static const struct wlr_buffer_impl buffer_impl = { + .destroy = buffer_destroy, + .get_shm = buffer_get_shm, + .begin_data_ptr_access = buffer_begin_data_ptr_access, + .end_data_ptr_access = buffer_end_data_ptr_access, +}; + +static void destroy_resource(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wl_buffer_interface wl_buffer_impl = { + .destroy = destroy_resource, +}; + +static void buffer_handle_release(struct wl_listener *listener, void *data) { + struct wlr_shm_buffer *buffer = wl_container_of(listener, buffer, release); + if (buffer->resource != NULL) { + wl_buffer_send_release(buffer->resource); + } +} + +static void buffer_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_shm_buffer *buffer = buffer_from_resource(resource); + buffer->resource = NULL; + wlr_buffer_drop(&buffer->base); +} + +static bool shm_has_format(struct wlr_shm *shm, uint32_t shm_format); + +static void pool_handle_create_buffer(struct wl_client *client, + struct wl_resource *pool_resource, uint32_t id, int32_t offset, + int32_t width, int32_t height, int32_t stride, uint32_t shm_format) { + struct wlr_shm_pool *pool = pool_from_resource(pool_resource); + + // Convert to uint64_t to avoid integer overflow + if (offset < 0 || width <= 0 || height <= 0 || stride < width || + offset + (uint64_t)stride * height > pool->mapping->size) { + wl_resource_post_error(pool_resource, WL_SHM_ERROR_INVALID_STRIDE, + "Invalid width, height or stride (%dx%d, %d)", + width, height, stride); + return; + } + + if (!shm_has_format(pool->shm, shm_format)) { + wl_resource_post_error(pool_resource, WL_SHM_ERROR_INVALID_FORMAT, + "Unsupported format"); + return; + } + + uint32_t drm_format = convert_wl_shm_format_to_drm(shm_format); + const struct wlr_pixel_format_info *format_info = + drm_get_pixel_format_info(drm_format); + if (format_info == NULL) { + wl_resource_post_error(pool_resource, WL_SHM_ERROR_INVALID_FORMAT, + "Unknown format"); + return; + } + if (!pixel_format_info_check_stride(format_info, stride, width)) { + wl_resource_post_error(pool_resource, WL_SHM_ERROR_INVALID_STRIDE, + "Invalid stride (%d)", stride); + return; + } + + struct wlr_shm_buffer *buffer = calloc(1, sizeof(*buffer)); + if (buffer == NULL) { + wl_resource_post_no_memory(pool_resource); + return; + } + + buffer->resource = wl_resource_create(client, &wl_buffer_interface, 1, id); + if (buffer->resource == NULL) { + free(buffer); + wl_resource_post_no_memory(pool_resource); + return; + } + + buffer->pool = pool; + buffer->offset = offset; + buffer->stride = stride; + buffer->drm_format = drm_format; + wlr_buffer_init(&buffer->base, &buffer_impl, width, height); + wl_resource_set_implementation(buffer->resource, + &wl_buffer_impl, buffer, buffer_handle_resource_destroy); + + wl_list_insert(&pool->buffers, &buffer->link); + + buffer->release.notify = buffer_handle_release; + wl_signal_add(&buffer->base.events.release, &buffer->release); +} + +static void pool_handle_resize(struct wl_client *client, + struct wl_resource *pool_resource, int32_t size) { + struct wlr_shm_pool *pool = pool_from_resource(pool_resource); + + if (size <= 0 || (size_t)size < pool->mapping->size) { + wl_resource_post_error(pool_resource, WL_SHM_ERROR_INVALID_STRIDE, + "Shrinking a pool (%zu to %d) is forbidden", + pool->mapping->size, size); + return; + } + + struct wlr_shm_mapping *mapping = mapping_create(pool->fd, size); + if (mapping == NULL) { + wl_resource_post_error(pool_resource, WL_SHM_ERROR_INVALID_FD, + "Failed to create memory mapping"); + return; + } + + mapping_drop(pool->mapping); + pool->mapping = mapping; +} + +static const struct wl_shm_pool_interface pool_impl = { + .create_buffer = pool_handle_create_buffer, + .destroy = destroy_resource, + .resize = pool_handle_resize, +}; + +static void pool_consider_destroy(struct wlr_shm_pool *pool) { + if (pool->resource != NULL || !wl_list_empty(&pool->buffers)) { + return; + } + + mapping_drop(pool->mapping); + close(pool->fd); + free(pool); +} + +static void pool_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_shm_pool *pool = pool_from_resource(resource); + pool->resource = NULL; + pool_consider_destroy(pool); +} + +static void shm_handle_create_pool(struct wl_client *client, + struct wl_resource *shm_resource, uint32_t id, int fd, int32_t size) { + struct wlr_shm *shm = shm_from_resource(shm_resource); + + if (size <= 0) { + wl_resource_post_error(shm_resource, WL_SHM_ERROR_INVALID_STRIDE, + "Invalid size (%d)", size); + goto error_fd; + } + + struct wlr_shm_mapping *mapping = mapping_create(fd, size); + if (mapping == NULL) { + wl_resource_post_error(shm_resource, WL_SHM_ERROR_INVALID_FD, + "Failed to create memory mapping"); + goto error_fd; + } + + struct wlr_shm_pool *pool = calloc(1, sizeof(*pool)); + if (pool == NULL) { + wl_resource_post_no_memory(shm_resource); + goto error_mapping; + } + + uint32_t version = wl_resource_get_version(shm_resource); + pool->resource = + wl_resource_create(client, &wl_shm_pool_interface, version, id); + if (pool->resource == NULL) { + wl_resource_post_no_memory(shm_resource); + goto error_pool; + } + wl_resource_set_implementation(pool->resource, &pool_impl, pool, + pool_handle_resource_destroy); + + pool->mapping = mapping; + pool->shm = shm; + pool->fd = fd; + wl_list_init(&pool->buffers); + return; + +error_pool: + free(pool); +error_mapping: + mapping_drop(mapping); +error_fd: + close(fd); +} + +static void shm_handle_release(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wl_shm_interface shm_impl = { + .create_pool = shm_handle_create_pool, + .release = shm_handle_release, +}; + +static void shm_bind(struct wl_client *client, void *data, uint32_t version, + uint32_t id) { + struct wlr_shm *shm = data; + + struct wl_resource *resource = wl_resource_create(client, &wl_shm_interface, + version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &shm_impl, shm, NULL); + wl_list_init(wl_resource_get_link(resource)); + if (shm == NULL) { + return; + } + + + for (size_t i = 0; i < shm->formats_len; i++) { + wl_shm_send_format(resource, shm->formats[i]); + } +} + +static void shm_destroy(struct wlr_shm *shm, + bool destroy_global_safe) { + wl_list_remove(&shm->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(shm->global); + } else { + wl_global_destroy(shm->global); + } + free(shm->formats); + free(shm); +} + +void wlr_shm_destroy(struct wlr_shm *shm, bool destroy_global_safe) { + shm_destroy(shm, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_shm *shm = wl_container_of(listener, shm, display_destroy); + shm_destroy(shm, false); +} + +struct wlr_shm *wlr_shm_create(struct wl_display *display, uint32_t version, + const uint32_t *formats, size_t formats_len) { + assert(version <= SHM_VERSION); + + // ARGB8888 and XRGB8888 must be supported per the wl_shm spec + bool has_argb8888 = false, has_xrgb8888 = false; + for (size_t i = 0; i < formats_len; i++) { + switch (formats[i]) { + case DRM_FORMAT_ARGB8888: + has_argb8888 = true; + break; + case DRM_FORMAT_XRGB8888: + has_xrgb8888 = true; + break; + } + } + assert(has_argb8888 && has_xrgb8888); + + struct wlr_shm *shm = calloc(1, sizeof(*shm)); + if (shm == NULL) { + wlr_log(WLR_ERROR, "Allocation failed"); + return NULL; + } + + shm->formats_len = formats_len; + shm->formats = malloc(formats_len * sizeof(uint32_t)); + if (shm->formats == NULL) { + wlr_log(WLR_ERROR, "Allocation failed"); + free(shm); + return NULL; + } + for (size_t i = 0; i < formats_len; i++) { + shm->formats[i] = convert_drm_format_to_wl_shm(formats[i]); + } + + shm->global = wl_global_create(display, &wl_shm_interface, version, + shm, shm_bind); + if (shm->global == NULL) { + wlr_log(WLR_ERROR, "wl_global_create failed"); + free(shm->formats); + free(shm); + return NULL; + } + + shm->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &shm->display_destroy); + + wlr_buffer_register_resource_interface(&buffer_resource_interface); + + return shm; +} + +struct wlr_shm *wlr_shm_create_with_renderer(struct wl_display *display, + uint32_t version, struct wlr_renderer *renderer) { + const struct wlr_drm_format_set *format_set = + wlr_renderer_get_texture_formats(renderer, WLR_BUFFER_CAP_DATA_PTR); + if (format_set == NULL || format_set->len == 0) { + wlr_log(WLR_ERROR, "Failed to initialize wl_shm: " + "cannot get renderer formats"); + return NULL; + } + + size_t formats_len = format_set->len; + uint32_t *formats = calloc(formats_len, sizeof(formats[0])); + if (formats == NULL) { + return NULL; + } + + for (size_t i = 0; i < format_set->len; i++) { + formats[i] = format_set->formats[i].format; + } + + struct wlr_shm *shm = wlr_shm_create(display, version, formats, formats_len); + free(formats); + return shm; +} + +static bool shm_has_format(struct wlr_shm *shm, uint32_t shm_format) { + for (size_t i = 0; i < shm->formats_len; i++) { + if (shm->formats[i] == shm_format) { + return true; + } + } + return false; +} diff --git a/3rdparty/wlroots/types/wlr_single_pixel_buffer_v1.c b/3rdparty/wlroots/types/wlr_single_pixel_buffer_v1.c new file mode 100644 index 0000000000..916b9babe2 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_single_pixel_buffer_v1.c @@ -0,0 +1,202 @@ +#include +#include +#include +#include +#include +#include +#include +#include "single-pixel-buffer-v1-protocol.h" +#include "util/global.h" + +#define SINGLE_PIXEL_MANAGER_VERSION 1 + +static void destroy_resource(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct wl_buffer_interface wl_buffer_impl = { + .destroy = destroy_resource, +}; + +static const struct wlr_buffer_impl buffer_impl; + +static bool buffer_resource_is_instance(struct wl_resource *resource) { + return wl_resource_instance_of(resource, &wl_buffer_interface, + &wl_buffer_impl); +} + +static struct wlr_single_pixel_buffer_v1 *single_pixel_buffer_v1_from_resource( + struct wl_resource *resource) { + assert(buffer_resource_is_instance(resource)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_buffer *buffer_from_resource( + struct wl_resource *resource) { + return &single_pixel_buffer_v1_from_resource(resource)->base; +} + +static const struct wlr_buffer_resource_interface buffer_resource_interface = { + .name = "single_pixel_buffer_v1", + .is_instance = buffer_resource_is_instance, + .from_resource = buffer_from_resource, +}; + +static void buffer_destroy(struct wlr_buffer *wlr_buffer) { + struct wlr_single_pixel_buffer_v1 *buffer = + wl_container_of(wlr_buffer, buffer, base); + wl_list_remove(&buffer->release.link); + + wlr_buffer_finish(wlr_buffer); + + if (buffer->resource != NULL) { + wl_resource_set_user_data(buffer->resource, NULL); + } + free(buffer); +} + +static bool buffer_begin_data_ptr_access(struct wlr_buffer *wlr_buffer, + uint32_t flags, void **data, uint32_t *format, size_t *stride) { + struct wlr_single_pixel_buffer_v1 *buffer = + wl_container_of(wlr_buffer, buffer, base); + if (flags & ~WLR_BUFFER_DATA_PTR_ACCESS_READ) { + return false; // the buffer is read-only + } + *data = &buffer->argb8888; + *format = DRM_FORMAT_ARGB8888; + *stride = sizeof(buffer->argb8888); + return true; +} + +static void buffer_end_data_ptr_access(struct wlr_buffer *wlr_buffer) { + // This space is intentionally left blank +} + +static const struct wlr_buffer_impl buffer_impl = { + .destroy = buffer_destroy, + .begin_data_ptr_access = buffer_begin_data_ptr_access, + .end_data_ptr_access = buffer_end_data_ptr_access, +}; + +static void buffer_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_single_pixel_buffer_v1 *buffer = single_pixel_buffer_v1_from_resource(resource); + buffer->resource = NULL; + wlr_buffer_drop(&buffer->base); +} + +static void buffer_handle_release(struct wl_listener *listener, void *data) { + struct wlr_single_pixel_buffer_v1 *buffer = wl_container_of(listener, buffer, release); + if (buffer->resource != NULL) { + wl_buffer_send_release(buffer->resource); + } +} + +static void manager_handle_create_u32_rgba_buffer(struct wl_client *client, + struct wl_resource *resource, uint32_t id, uint32_t r, uint32_t g, + uint32_t b, uint32_t a) { + struct wlr_single_pixel_buffer_v1 *buffer = calloc(1, sizeof(*buffer)); + if (buffer == NULL) { + wl_client_post_no_memory(client); + return; + } + + buffer->resource = wl_resource_create(client, &wl_buffer_interface, 1, id); + if (buffer->resource == NULL) { + wl_client_post_no_memory(client); + free(buffer); + return; + } + + wlr_buffer_init(&buffer->base, &buffer_impl, 1, 1); + wl_resource_set_implementation(buffer->resource, + &wl_buffer_impl, buffer, buffer_handle_resource_destroy); + + buffer->r = r; + buffer->g = g; + buffer->b = b; + buffer->a = a; + + double f = (double)0xFF / 0xFFFFFFFF; + buffer->argb8888[0] = (uint8_t)((double)buffer->b * f); + buffer->argb8888[1] = (uint8_t)((double)buffer->g * f); + buffer->argb8888[2] = (uint8_t)((double)buffer->r * f); + buffer->argb8888[3] = (uint8_t)((double)buffer->a * f); + + buffer->release.notify = buffer_handle_release; + wl_signal_add(&buffer->base.events.release, &buffer->release); +} + +static const struct wp_single_pixel_buffer_manager_v1_interface manager_impl = { + .destroy = destroy_resource, + .create_u32_rgba_buffer = manager_handle_create_u32_rgba_buffer, +}; + +static void manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wl_resource *resource = wl_resource_create(client, + &wp_single_pixel_buffer_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, NULL, NULL); +} + +static void single_pixel_buffer_manager_v1_destroy( + struct wlr_single_pixel_buffer_manager_v1 *manager, + bool destroy_global_safe) { + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + wl_list_remove(&manager->display_destroy.link); + free(manager); +} + +void wlr_single_pixel_buffer_manager_v1_destroy( + struct wlr_single_pixel_buffer_manager_v1 *manager, bool destroy_global_safe) { + single_pixel_buffer_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_single_pixel_buffer_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + single_pixel_buffer_manager_v1_destroy(manager, false); +} + +struct wlr_single_pixel_buffer_manager_v1 *wlr_single_pixel_buffer_manager_v1_create( + struct wl_display *display) { + struct wlr_single_pixel_buffer_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + manager->global = wl_global_create(display, + &wp_single_pixel_buffer_manager_v1_interface, + SINGLE_PIXEL_MANAGER_VERSION, + NULL, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + wlr_buffer_register_resource_interface(&buffer_resource_interface); + + return manager; +} + +struct wlr_single_pixel_buffer_v1 *wlr_single_pixel_buffer_v1_try_from_buffer( + struct wlr_buffer *buffer) { + + if (buffer->impl != &buffer_impl) { + return NULL; + } + + return wl_container_of(buffer, + (struct wlr_single_pixel_buffer_v1 *)NULL, base); +} diff --git a/3rdparty/wlroots/types/wlr_subcompositor.c b/3rdparty/wlroots/types/wlr_subcompositor.c new file mode 100644 index 0000000000..805f6a9f9a --- /dev/null +++ b/3rdparty/wlroots/types/wlr_subcompositor.c @@ -0,0 +1,454 @@ +#include +#include +#include +#include +#include +#include +#include "types/wlr_region.h" +#include "types/wlr_subcompositor.h" +#include "util/global.h" + +// Note: wl_subsurface becomes inert on parent surface destroy + +#define SUBCOMPOSITOR_VERSION 1 + +static bool subsurface_is_synchronized(struct wlr_subsurface *subsurface) { + while (subsurface != NULL) { + if (subsurface->synchronized) { + return true; + } + + subsurface = wlr_subsurface_try_from_wlr_surface(subsurface->parent); + } + + return false; +} + +static const struct wl_subsurface_interface subsurface_implementation; + +static void subsurface_destroy(struct wlr_subsurface *subsurface) { + if (subsurface->has_cache) { + wlr_surface_unlock_cached(subsurface->surface, subsurface->cached_seq); + } + + wlr_surface_unmap(subsurface->surface); + + wl_signal_emit_mutable(&subsurface->events.destroy, subsurface); + + assert(wl_list_empty(&subsurface->events.destroy.listener_list)); + + wlr_surface_synced_finish(&subsurface->parent_synced); + + wl_list_remove(&subsurface->surface_client_commit.link); + wl_list_remove(&subsurface->parent_destroy.link); + + wl_resource_set_user_data(subsurface->resource, NULL); + free(subsurface); +} + +/** + * Get a wlr_subsurface from a wl_subsurface resource. + * + * Returns NULL if the subsurface is inert (e.g. the wl_surface object or the + * parent surface got destroyed). + */ +static struct wlr_subsurface *subsurface_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wl_subsurface_interface, + &subsurface_implementation)); + return wl_resource_get_user_data(resource); +} + +static void subsurface_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void subsurface_handle_set_position(struct wl_client *client, + struct wl_resource *resource, int32_t x, int32_t y) { + struct wlr_subsurface *subsurface = subsurface_from_resource(resource); + if (subsurface == NULL) { + return; + } + + subsurface->pending.x = x; + subsurface->pending.y = y; +} + +static struct wlr_subsurface *subsurface_find_sibling( + struct wlr_subsurface *subsurface, struct wlr_surface *surface) { + struct wlr_surface *parent = subsurface->parent; + + struct wlr_subsurface *sibling; + wl_list_for_each(sibling, &parent->pending.subsurfaces_below, pending.link) { + if (sibling->surface == surface && sibling != subsurface) { + return sibling; + } + } + wl_list_for_each(sibling, &parent->pending.subsurfaces_above, pending.link) { + if (sibling->surface == surface && sibling != subsurface) { + return sibling; + } + } + + return NULL; +} + +static void subsurface_handle_place_above(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *sibling_resource) { + struct wlr_subsurface *subsurface = subsurface_from_resource(resource); + if (subsurface == NULL) { + return; + } + + struct wlr_surface *sibling_surface = + wlr_surface_from_resource(sibling_resource); + + struct wl_list *node; + if (sibling_surface == subsurface->parent) { + node = &subsurface->parent->pending.subsurfaces_above; + } else { + struct wlr_subsurface *sibling = + subsurface_find_sibling(subsurface, sibling_surface); + if (!sibling) { + wl_resource_post_error(subsurface->resource, + WL_SUBSURFACE_ERROR_BAD_SURFACE, + "%s: wl_surface@%" PRIu32 "is not a parent or sibling", + "place_above", wl_resource_get_id(sibling_resource)); + return; + } + node = &sibling->pending.link; + } + + wl_list_remove(&subsurface->pending.link); + wl_list_insert(node, &subsurface->pending.link); +} + +static void subsurface_handle_place_below(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *sibling_resource) { + struct wlr_subsurface *subsurface = subsurface_from_resource(resource); + if (subsurface == NULL) { + return; + } + + struct wlr_surface *sibling_surface = + wlr_surface_from_resource(sibling_resource); + + struct wl_list *node; + if (sibling_surface == subsurface->parent) { + node = &subsurface->parent->pending.subsurfaces_below; + } else { + struct wlr_subsurface *sibling = + subsurface_find_sibling(subsurface, sibling_surface); + if (!sibling) { + wl_resource_post_error(subsurface->resource, + WL_SUBSURFACE_ERROR_BAD_SURFACE, + "%s: wl_surface@%" PRIu32 " is not a parent or sibling", + "place_below", wl_resource_get_id(sibling_resource)); + return; + } + node = &sibling->pending.link; + } + + wl_list_remove(&subsurface->pending.link); + wl_list_insert(node->prev, &subsurface->pending.link); +} + +static void subsurface_handle_set_sync(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_subsurface *subsurface = subsurface_from_resource(resource); + if (subsurface == NULL) { + return; + } + + subsurface->synchronized = true; +} + +static void subsurface_handle_set_desync(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_subsurface *subsurface = subsurface_from_resource(resource); + if (subsurface == NULL) { + return; + } + + if (subsurface->synchronized) { + subsurface->synchronized = false; + + if (!subsurface_is_synchronized(subsurface) && + subsurface->has_cache) { + wlr_surface_unlock_cached(subsurface->surface, + subsurface->cached_seq); + subsurface->has_cache = false; + } + } +} + +static const struct wl_subsurface_interface subsurface_implementation = { + .destroy = subsurface_handle_destroy, + .set_position = subsurface_handle_set_position, + .place_above = subsurface_handle_place_above, + .place_below = subsurface_handle_place_below, + .set_sync = subsurface_handle_set_sync, + .set_desync = subsurface_handle_set_desync, +}; + +const struct wlr_surface_role subsurface_role; + +void subsurface_consider_map(struct wlr_subsurface *subsurface) { + if (subsurface->added && subsurface->parent->mapped && + wlr_surface_has_buffer(subsurface->surface)) { + wlr_surface_map(subsurface->surface); + } +} + +static void subsurface_role_commit(struct wlr_surface *surface) { + struct wlr_subsurface *subsurface = wlr_subsurface_try_from_wlr_surface(surface); + if (subsurface == NULL) { + return; + } + + subsurface_consider_map(subsurface); +} + +static void subsurface_role_destroy(struct wlr_surface *surface) { + struct wlr_subsurface *subsurface = wlr_subsurface_try_from_wlr_surface(surface); + if (subsurface == NULL) { + return; + } + + subsurface_destroy(subsurface); +} + +const struct wlr_surface_role subsurface_role = { + .name = "wl_subsurface", + .commit = subsurface_role_commit, + .destroy = subsurface_role_destroy, +}; + +static void surface_synced_init_state(void *_state) { + struct wlr_subsurface_parent_state *state = _state; + wl_list_init(&state->link); +} + +static void surface_synced_finish_state(void *_state) { + struct wlr_subsurface_parent_state *state = _state; + wl_list_remove(&state->link); +} + +static void surface_synced_move_state(void *_dst, void *_src) { + struct wlr_subsurface_parent_state *dst = _dst, *src = _src; + dst->x = src->x; + dst->y = src->y; + dst->synced = src->synced; + + // For the sake of simplicity, copying the position in list is done by the + // parent itself +} + +static struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(struct wlr_subsurface_parent_state), + .init_state = surface_synced_init_state, + .finish_state = surface_synced_finish_state, + .move_state = surface_synced_move_state, +}; + +static void subsurface_handle_parent_destroy(struct wl_listener *listener, + void *data) { + struct wlr_subsurface *subsurface = + wl_container_of(listener, subsurface, parent_destroy); + // Once the parent is destroyed, the client has no way to use the + // wl_subsurface object anymore, so we can destroy it. + subsurface_destroy(subsurface); +} + +static void subsurface_handle_surface_client_commit( + struct wl_listener *listener, void *data) { + struct wlr_subsurface *subsurface = + wl_container_of(listener, subsurface, surface_client_commit); + struct wlr_surface *surface = subsurface->surface; + + if (subsurface_is_synchronized(subsurface)) { + if (subsurface->has_cache) { + // We already lock a previous commit. The prevents any future + // commit to be applied before we release the previous commit. + return; + } + subsurface->has_cache = true; + subsurface->cached_seq = wlr_surface_lock_pending(surface); + } else if (subsurface->has_cache) { + wlr_surface_unlock_cached(surface, subsurface->cached_seq); + subsurface->has_cache = false; + } +} + +void subsurface_handle_parent_commit(struct wlr_subsurface *subsurface) { + if (subsurface->synchronized && subsurface->has_cache) { + wlr_surface_unlock_cached(subsurface->surface, subsurface->cached_seq); + subsurface->has_cache = false; + } + + if (!subsurface->added) { + subsurface->added = true; + wl_signal_emit_mutable(&subsurface->parent->events.new_subsurface, + subsurface); + subsurface_consider_map(subsurface); + } +} + +struct wlr_subsurface *wlr_subsurface_try_from_wlr_surface(struct wlr_surface *surface) { + if (surface->role != &subsurface_role || surface->role_resource == NULL) { + return NULL; + } + return subsurface_from_resource(surface->role_resource); +} + +static void subcompositor_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void subcompositor_handle_get_subsurface(struct wl_client *client, + struct wl_resource *resource, uint32_t id, + struct wl_resource *surface_resource, + struct wl_resource *parent_resource) { + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + struct wlr_surface *parent = wlr_surface_from_resource(parent_resource); + + struct wlr_subsurface *subsurface = calloc(1, sizeof(*subsurface)); + if (!subsurface) { + wl_client_post_no_memory(client); + return; + } + + if (!wlr_surface_set_role(surface, &subsurface_role, + resource, WL_SUBCOMPOSITOR_ERROR_BAD_SURFACE)) { + free(subsurface); + return; + } + + if (wlr_surface_get_root_surface(parent) == surface) { + wl_resource_post_error(resource, + WL_SUBCOMPOSITOR_ERROR_BAD_PARENT, + "wl_subsurface@%" PRIu32 + " cannot be a parent of itself or its ancestor", id); + free(subsurface); + return; + } + + if (!wlr_surface_synced_init(&subsurface->parent_synced, parent, &surface_synced_impl, + &subsurface->pending, &subsurface->current)) { + free(subsurface); + wl_client_post_no_memory(client); + return; + } + + subsurface->synchronized = true; + subsurface->surface = surface; + subsurface->resource = wl_resource_create(client, &wl_subsurface_interface, + wl_resource_get_version(resource), id); + if (subsurface->resource == NULL) { + wlr_surface_synced_finish(&subsurface->parent_synced); + free(subsurface); + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(subsurface->resource, + &subsurface_implementation, subsurface, NULL); + + // In surface_state_move() we commit sub-surface order. To do so we need to + // iterate over the list of sub-surfaces from a struct wlr_surface_state. + // Store a pointer to struct wlr_surface_synced to facilitate this. + subsurface->pending.synced = &subsurface->parent_synced; + subsurface->current.synced = &subsurface->parent_synced; + + struct wlr_surface_state *cached; + wl_list_for_each(cached, &parent->cached, cached_state_link) { + struct wlr_subsurface_parent_state *sub_state = + wlr_surface_synced_get_state(&subsurface->parent_synced, cached); + sub_state->synced = &subsurface->parent_synced; + } + + wlr_surface_set_role_object(surface, subsurface->resource); + + wl_signal_init(&subsurface->events.destroy); + + wl_signal_add(&surface->events.client_commit, + &subsurface->surface_client_commit); + subsurface->surface_client_commit.notify = + subsurface_handle_surface_client_commit; + + // link parent + subsurface->parent = parent; + wl_signal_add(&parent->events.destroy, &subsurface->parent_destroy); + subsurface->parent_destroy.notify = subsurface_handle_parent_destroy; + + wl_list_remove(&subsurface->pending.link); + wl_list_insert(parent->pending.subsurfaces_above.prev, + &subsurface->pending.link); +} + +static const struct wl_subcompositor_interface subcompositor_impl = { + .destroy = subcompositor_handle_destroy, + .get_subsurface = subcompositor_handle_get_subsurface, +}; + +static void subcompositor_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_subcompositor *subcompositor = data; + struct wl_resource *resource = + wl_resource_create(client, &wl_subcompositor_interface, 1, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &subcompositor_impl, + subcompositor, NULL); +} + +static void subcompositor_destroy(struct wlr_subcompositor *subcompositor, + bool destroy_global_safe) { + wl_signal_emit_mutable(&subcompositor->events.destroy, NULL); + + assert(wl_list_empty(&subcompositor->events.destroy.listener_list)); + + wl_list_remove(&subcompositor->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(subcompositor->global); + } else { + wl_global_destroy(subcompositor->global); + } + free(subcompositor); +} + +void wlr_subcompositor_destroy(struct wlr_subcompositor *subcompositor, bool destroy_global_safe) { + subcompositor_destroy(subcompositor, destroy_global_safe); +} + +static void subcompositor_handle_display_destroy( + struct wl_listener *listener, void *data) { + struct wlr_subcompositor *subcompositor = + wl_container_of(listener, subcompositor, display_destroy); + subcompositor_destroy(subcompositor, false); +} + +struct wlr_subcompositor *wlr_subcompositor_create(struct wl_display *display) { + struct wlr_subcompositor *subcompositor = calloc(1, sizeof(*subcompositor)); + if (!subcompositor) { + return NULL; + } + + subcompositor->global = wl_global_create(display, + &wl_subcompositor_interface, SUBCOMPOSITOR_VERSION, + subcompositor, subcompositor_bind); + if (!subcompositor->global) { + free(subcompositor); + return NULL; + } + + wl_signal_init(&subcompositor->events.destroy); + + subcompositor->display_destroy.notify = subcompositor_handle_display_destroy; + wl_display_add_destroy_listener(display, &subcompositor->display_destroy); + + return subcompositor; +} diff --git a/3rdparty/wlroots/types/wlr_switch.c b/3rdparty/wlroots/types/wlr_switch.c new file mode 100644 index 0000000000..439c293337 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_switch.c @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include +#include + +#include "interfaces/wlr_input_device.h" + +struct wlr_switch *wlr_switch_from_input_device( + struct wlr_input_device *input_device) { + assert(input_device->type == WLR_INPUT_DEVICE_SWITCH); + return wl_container_of(input_device, (struct wlr_switch *)NULL, base); +} + +void wlr_switch_init(struct wlr_switch *switch_device, + const struct wlr_switch_impl *impl, const char *name) { + *switch_device = (struct wlr_switch){ + .impl = impl, + }; + wlr_input_device_init(&switch_device->base, WLR_INPUT_DEVICE_SWITCH, name); + + wl_signal_init(&switch_device->events.toggle); +} + +void wlr_switch_finish(struct wlr_switch *switch_device) { + wlr_input_device_finish(&switch_device->base); + + assert(wl_list_empty(&switch_device->events.toggle.listener_list)); +} diff --git a/3rdparty/wlroots/types/wlr_tablet_pad.c b/3rdparty/wlroots/types/wlr_tablet_pad.c new file mode 100644 index 0000000000..bfe17e68d8 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_tablet_pad.c @@ -0,0 +1,51 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "interfaces/wlr_input_device.h" + +struct wlr_tablet_pad *wlr_tablet_pad_from_input_device( + struct wlr_input_device *input_device) { + assert(input_device->type == WLR_INPUT_DEVICE_TABLET_PAD); + return wl_container_of(input_device, (struct wlr_tablet_pad *)NULL, base); +} + +void wlr_tablet_pad_init(struct wlr_tablet_pad *pad, + const struct wlr_tablet_pad_impl *impl, const char *name) { + *pad = (struct wlr_tablet_pad){ + .impl = impl, + }; + wlr_input_device_init(&pad->base, WLR_INPUT_DEVICE_TABLET_PAD, name); + + wl_signal_init(&pad->events.button); + wl_signal_init(&pad->events.ring); + wl_signal_init(&pad->events.strip); + wl_signal_init(&pad->events.attach_tablet); + + wl_list_init(&pad->groups); + wl_array_init(&pad->paths); +} + +void wlr_tablet_pad_finish(struct wlr_tablet_pad *pad) { + wlr_input_device_finish(&pad->base); + + assert(wl_list_empty(&pad->events.button.listener_list)); + assert(wl_list_empty(&pad->events.ring.listener_list)); + assert(wl_list_empty(&pad->events.strip.listener_list)); + assert(wl_list_empty(&pad->events.attach_tablet.listener_list)); + + char **path_ptr; + wl_array_for_each(path_ptr, &pad->paths) { + free(*path_ptr); + } + wl_array_release(&pad->paths); + + /* TODO: wlr_tablet_pad should own its wlr_tablet_pad_group */ + if (!wl_list_empty(&pad->groups)) { + wlr_log(WLR_ERROR, "wlr_tablet_pad groups is not empty"); + } +} diff --git a/3rdparty/wlroots/types/wlr_tablet_tool.c b/3rdparty/wlroots/types/wlr_tablet_tool.c new file mode 100644 index 0000000000..2b15f57eed --- /dev/null +++ b/3rdparty/wlroots/types/wlr_tablet_tool.c @@ -0,0 +1,44 @@ +#include +#include +#include +#include +#include +#include + +#include "interfaces/wlr_input_device.h" + +struct wlr_tablet *wlr_tablet_from_input_device( + struct wlr_input_device *input_device) { + assert(input_device->type == WLR_INPUT_DEVICE_TABLET); + return wl_container_of(input_device, (struct wlr_tablet *)NULL, base); +} + +void wlr_tablet_init(struct wlr_tablet *tablet, + const struct wlr_tablet_impl *impl, const char *name) { + *tablet = (struct wlr_tablet){ + .impl = impl, + }; + wlr_input_device_init(&tablet->base, WLR_INPUT_DEVICE_TABLET, name); + + wl_signal_init(&tablet->events.axis); + wl_signal_init(&tablet->events.proximity); + wl_signal_init(&tablet->events.tip); + wl_signal_init(&tablet->events.button); + + wl_array_init(&tablet->paths); +} + +void wlr_tablet_finish(struct wlr_tablet *tablet) { + wlr_input_device_finish(&tablet->base); + + assert(wl_list_empty(&tablet->events.axis.listener_list)); + assert(wl_list_empty(&tablet->events.proximity.listener_list)); + assert(wl_list_empty(&tablet->events.tip.listener_list)); + assert(wl_list_empty(&tablet->events.button.listener_list)); + + char **path_ptr; + wl_array_for_each(path_ptr, &tablet->paths) { + free(*path_ptr); + } + wl_array_release(&tablet->paths); +} diff --git a/3rdparty/wlroots/types/wlr_tearing_control_v1.c b/3rdparty/wlroots/types/wlr_tearing_control_v1.c new file mode 100644 index 0000000000..9f5e29796a --- /dev/null +++ b/3rdparty/wlroots/types/wlr_tearing_control_v1.c @@ -0,0 +1,244 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "tearing-control-v1-protocol.h" +#include "util/global.h" + +#define TEARING_CONTROL_MANAGER_VERSION 1 + +static const struct wp_tearing_control_manager_v1_interface tearing_impl; +static const struct wp_tearing_control_v1_interface tearing_control_impl; + +static struct wlr_tearing_control_manager_v1 *tearing_manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wp_tearing_control_manager_v1_interface, + &tearing_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_tearing_control_v1 *tearing_surface_hint_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wp_tearing_control_v1_interface, + &tearing_control_impl)); + return wl_resource_get_user_data(resource); +} + +static void destroy_tearing_hint(struct wlr_tearing_control_v1 *hint) { + if (hint == NULL) { + return; + } + + wl_signal_emit_mutable(&hint->events.destroy, NULL); + + assert(wl_list_empty(&hint->events.set_hint.listener_list)); + assert(wl_list_empty(&hint->events.destroy.listener_list)); + + wl_list_remove(&hint->link); + wl_resource_set_user_data(hint->resource, NULL); + + wlr_addon_finish(&hint->addon); + wlr_surface_synced_finish(&hint->synced); + wl_list_remove(&hint->surface_commit.link); + + free(hint); +} + +static void surface_addon_destroy(struct wlr_addon *addon) { + struct wlr_tearing_control_v1 *hint = wl_container_of(addon, hint, addon); + + destroy_tearing_hint(hint); +} + +static const struct wlr_addon_interface surface_addon_impl = { + .name = "wp_tearing_control_v1", + .destroy = surface_addon_destroy, +}; + +static void resource_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void destroy_tearing_resource_impl(struct wl_resource *resource) { + struct wlr_tearing_control_v1 *hint = tearing_surface_hint_from_resource(resource); + destroy_tearing_hint(hint); +} + +static void tearing_control_handle_set_presentation_hint(struct wl_client *client, + struct wl_resource *resource, uint32_t hint) { + struct wlr_tearing_control_v1 *surface_hint = + tearing_surface_hint_from_resource(resource); + surface_hint->pending = hint; +} + +static const struct wp_tearing_control_v1_interface tearing_control_impl = { + .destroy = resource_handle_destroy, + .set_presentation_hint = tearing_control_handle_set_presentation_hint, +}; + +static const struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(enum wp_tearing_control_v1_presentation_hint), +}; + +static void hint_handle_surface_commit(struct wl_listener *listener, void *data) { + struct wlr_tearing_control_v1 *hint = wl_container_of(listener, hint, surface_commit); + + if (hint->current != hint->previous) { + wl_signal_emit_mutable(&hint->events.set_hint, NULL); + } + + hint->previous = hint->current; +} + +static void tearing_control_manager_handle_get_tearing_control( + struct wl_client *client, struct wl_resource *resource, uint32_t id, + struct wl_resource *surface_resource) { + struct wlr_tearing_control_manager_v1 *manager = tearing_manager_from_resource(resource); + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + + if (wlr_addon_find(&surface->addons, manager, &surface_addon_impl) != NULL) { + wl_resource_post_error(resource, + WP_TEARING_CONTROL_MANAGER_V1_ERROR_TEARING_CONTROL_EXISTS, + "Tearing control object already exists!"); + return; + } + + struct wlr_tearing_control_v1 *hint = calloc(1, sizeof(*hint)); + if (!hint) { + wl_client_post_no_memory(client); + return; + } + + if (!wlr_surface_synced_init(&hint->synced, surface, + &surface_synced_impl, &hint->pending, &hint->current)) { + free(hint); + wl_client_post_no_memory(client); + return; + } + + struct wl_resource *created_resource = + wl_resource_create(client, &wp_tearing_control_v1_interface, + wl_resource_get_version(resource), id); + + if (created_resource == NULL) { + free(hint); + wl_resource_post_no_memory(resource); + return; + } + + wl_resource_set_implementation(created_resource, &tearing_control_impl, + hint, destroy_tearing_resource_impl); + + hint->client = client; + hint->resource = created_resource; + hint->surface = surface; + wlr_addon_init(&hint->addon, &hint->surface->addons, manager, &surface_addon_impl); + + wl_signal_init(&hint->events.set_hint); + wl_signal_init(&hint->events.destroy); + + hint->surface_commit.notify = hint_handle_surface_commit; + wl_signal_add(&surface->events.commit, &hint->surface_commit); + + wl_list_insert(&manager->surface_hints, &hint->link); + + wl_signal_emit_mutable(&manager->events.new_object, hint); +} + +static const struct wp_tearing_control_manager_v1_interface tearing_impl = { + .destroy = resource_handle_destroy, + .get_tearing_control = tearing_control_manager_handle_get_tearing_control, +}; + +static void tearing_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_tearing_control_manager_v1 *manager = data; + + struct wl_resource *wl_resource = wl_resource_create(wl_client, + &wp_tearing_control_manager_v1_interface, version, id); + if (wl_resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + wl_resource_set_implementation(wl_resource, &tearing_impl, manager, NULL); +} + +static void tearing_control_manager_v1_destroy(struct wlr_tearing_control_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, NULL); + + assert(wl_list_empty(&manager->events.new_object.listener_list)); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + struct wlr_tearing_control_v1 *hint, *tmp; + wl_list_for_each_safe(hint, tmp, &manager->surface_hints, link) { + destroy_tearing_hint(hint); + } + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_tearing_control_manager_v1_destroy(struct wlr_tearing_control_manager_v1 *manager, + bool destroy_global_safe) { + tearing_control_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_tearing_control_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + tearing_control_manager_v1_destroy(manager, false); +} + +struct wlr_tearing_control_manager_v1 *wlr_tearing_control_manager_v1_create( + struct wl_display *display, uint32_t version) { + assert(version <= TEARING_CONTROL_MANAGER_VERSION); + + struct wlr_tearing_control_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (!manager) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + return NULL; + } + + wl_signal_init(&manager->events.new_object); + wl_signal_init(&manager->events.destroy); + + wl_list_init(&manager->surface_hints); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + manager->global = wl_global_create(display, &wp_tearing_control_manager_v1_interface, + version, manager, tearing_bind); + + if (manager->global == NULL) { + wl_list_remove(&manager->display_destroy.link); + free(manager); + return NULL; + } + return manager; +} + +enum wp_tearing_control_v1_presentation_hint +wlr_tearing_control_manager_v1_surface_hint_from_surface(struct wlr_tearing_control_manager_v1 *manager, + struct wlr_surface *surface) { + struct wlr_addon *addon = + wlr_addon_find(&surface->addons, manager, &surface_addon_impl); + if (addon == NULL) { + return WP_TEARING_CONTROL_V1_PRESENTATION_HINT_VSYNC; + } + + struct wlr_tearing_control_v1 *hint = wl_container_of(addon, hint, addon); + + return hint->current; +} diff --git a/3rdparty/wlroots/types/wlr_text_input_v3.c b/3rdparty/wlroots/types/wlr_text_input_v3.c new file mode 100644 index 0000000000..0898503dd5 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_text_input_v3.c @@ -0,0 +1,366 @@ +#include +#include +#include +#include +#include +#include +#include +#include "text-input-unstable-v3-protocol.h" +#include "util/global.h" + +static void text_input_clear_focused_surface(struct wlr_text_input_v3 *text_input) { + wl_list_remove(&text_input->surface_destroy.link); + wl_list_init(&text_input->surface_destroy.link); + text_input->focused_surface = NULL; +} + +static const struct zwp_text_input_v3_interface text_input_impl; + +static struct wlr_text_input_v3 *text_input_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zwp_text_input_v3_interface, + &text_input_impl)); + return wl_resource_get_user_data(resource); +} + +void wlr_text_input_v3_send_enter(struct wlr_text_input_v3 *text_input, + struct wlr_surface *surface) { + assert(wl_resource_get_client(text_input->resource) + == wl_resource_get_client(surface->resource)); + assert(text_input->focused_surface == NULL); + text_input->focused_surface = surface; + wl_signal_add(&text_input->focused_surface->events.destroy, + &text_input->surface_destroy); + zwp_text_input_v3_send_enter(text_input->resource, + text_input->focused_surface->resource); +} + +void wlr_text_input_v3_send_leave(struct wlr_text_input_v3 *text_input) { + assert(text_input->focused_surface != NULL); + zwp_text_input_v3_send_leave(text_input->resource, + text_input->focused_surface->resource); + text_input_clear_focused_surface(text_input); +} + +void wlr_text_input_v3_send_preedit_string(struct wlr_text_input_v3 *text_input, + const char *text, int32_t cursor_begin, int32_t cursor_end) { + zwp_text_input_v3_send_preedit_string(text_input->resource, text, + cursor_begin, cursor_end); +} + +void wlr_text_input_v3_send_commit_string(struct wlr_text_input_v3 *text_input, + const char *text) { + zwp_text_input_v3_send_commit_string(text_input->resource, text); +} + +void wlr_text_input_v3_send_delete_surrounding_text( + struct wlr_text_input_v3 *text_input, uint32_t before_length, + uint32_t after_length) { + zwp_text_input_v3_send_delete_surrounding_text(text_input->resource, + before_length, after_length); +} + +void wlr_text_input_v3_send_done(struct wlr_text_input_v3 *text_input) { + zwp_text_input_v3_send_done(text_input->resource, + text_input->current_serial); +} + +static void wlr_text_input_destroy(struct wlr_text_input_v3 *text_input) { + wl_signal_emit_mutable(&text_input->events.destroy, NULL); + + assert(wl_list_empty(&text_input->events.enable.listener_list)); + assert(wl_list_empty(&text_input->events.commit.listener_list)); + assert(wl_list_empty(&text_input->events.disable.listener_list)); + assert(wl_list_empty(&text_input->events.destroy.listener_list)); + + text_input_clear_focused_surface(text_input); + wl_list_remove(&text_input->seat_destroy.link); + // remove from manager.text_inputs + wl_list_remove(&text_input->link); + free(text_input->current.surrounding.text); + free(text_input->pending.surrounding.text); + free(text_input); +} + +static void text_input_resource_destroy(struct wl_resource *resource) { + struct wlr_text_input_v3 *text_input = text_input_from_resource(resource); + if (!text_input) { + return; + } + wlr_text_input_destroy(text_input); +} + +static void text_input_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void text_input_enable(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_text_input_v3 *text_input = text_input_from_resource(resource); + if (!text_input) { + return; + } + struct wlr_text_input_v3_state defaults = {0}; + free(text_input->pending.surrounding.text); + text_input->pending = defaults; + text_input->pending_enabled = true; +} + +static void text_input_disable(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_text_input_v3 *text_input = text_input_from_resource(resource); + if (!text_input) { + return; + } + text_input->pending_enabled = false; +} + +static void text_input_set_surrounding_text(struct wl_client *client, + struct wl_resource *resource, const char *text, int32_t cursor, + int32_t anchor) { + struct wlr_text_input_v3 *text_input = text_input_from_resource(resource); + if (!text_input) { + return; + } + free(text_input->pending.surrounding.text); + text_input->pending.surrounding.text = strdup(text); + if (!text_input->pending.surrounding.text) { + wl_client_post_no_memory(client); + } + text_input->pending.features |= WLR_TEXT_INPUT_V3_FEATURE_SURROUNDING_TEXT; + text_input->pending.surrounding.cursor = cursor; + text_input->pending.surrounding.anchor = anchor; +} + +static void text_input_set_text_change_cause(struct wl_client *client, + struct wl_resource *resource, uint32_t cause) { + struct wlr_text_input_v3 *text_input = text_input_from_resource(resource); + if (!text_input) { + return; + } + text_input->pending.text_change_cause = cause; +} + +static void text_input_set_content_type(struct wl_client *client, + struct wl_resource *resource, uint32_t hint, uint32_t purpose) { + struct wlr_text_input_v3 *text_input = text_input_from_resource(resource); + if (!text_input) { + return; + } + text_input->pending.features |= WLR_TEXT_INPUT_V3_FEATURE_CONTENT_TYPE; + text_input->pending.content_type.hint = hint; + text_input->pending.content_type.purpose = purpose; +} + +static void text_input_set_cursor_rectangle(struct wl_client *client, + struct wl_resource *resource, int32_t x, int32_t y, int32_t width, + int32_t height) { + struct wlr_text_input_v3 *text_input = text_input_from_resource(resource); + if (!text_input) { + return; + } + text_input->pending.features |= WLR_TEXT_INPUT_V3_FEATURE_CURSOR_RECTANGLE; + text_input->pending.cursor_rectangle.x = x; + text_input->pending.cursor_rectangle.y = y; + text_input->pending.cursor_rectangle.width = width; + text_input->pending.cursor_rectangle.height = height; +} + +static void text_input_commit(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_text_input_v3 *text_input = text_input_from_resource(resource); + if (!text_input) { + return; + } + free(text_input->current.surrounding.text); + text_input->current = text_input->pending; + if (text_input->pending.surrounding.text) { + text_input->current.surrounding.text = + strdup(text_input->pending.surrounding.text); + if (text_input->current.surrounding.text == NULL) { + wl_client_post_no_memory(client); + return; + } + } + + bool old_enabled = text_input->current_enabled; + text_input->current_enabled = text_input->pending_enabled; + text_input->current_serial++; + + if (text_input->focused_surface == NULL) { + wlr_log(WLR_DEBUG, "Text input commit received without focus"); + } + + if (!old_enabled && text_input->current_enabled) { + text_input->active_features = text_input->current.features; + wl_signal_emit_mutable(&text_input->events.enable, NULL); + } else if (old_enabled && !text_input->current_enabled) { + text_input->active_features = 0; + wl_signal_emit_mutable(&text_input->events.disable, NULL); + } else { // including never enabled + wl_signal_emit_mutable(&text_input->events.commit, NULL); + } +} + +static const struct zwp_text_input_v3_interface text_input_impl = { + .destroy = text_input_destroy, + .enable = text_input_enable, + .disable = text_input_disable, + .set_surrounding_text = text_input_set_surrounding_text, + .set_text_change_cause = text_input_set_text_change_cause, + .set_content_type = text_input_set_content_type, + .set_cursor_rectangle = text_input_set_cursor_rectangle, + .commit = text_input_commit, +}; + +static const struct zwp_text_input_manager_v3_interface text_input_manager_impl; + +static struct wlr_text_input_manager_v3 *text_input_manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwp_text_input_manager_v3_interface, &text_input_manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void text_input_manager_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void text_input_handle_seat_destroy(struct wl_listener *listener, + void *data) { + struct wlr_text_input_v3 *text_input = wl_container_of(listener, text_input, + seat_destroy); + struct wl_resource *resource = text_input->resource; + wlr_text_input_destroy(text_input); + wl_resource_set_user_data(resource, NULL); +} + +static void text_input_handle_focused_surface_destroy( + struct wl_listener *listener, void *data) { + struct wlr_text_input_v3 *text_input = wl_container_of(listener, text_input, + surface_destroy); + text_input_clear_focused_surface(text_input); +} + +static void text_input_manager_get_text_input(struct wl_client *client, + struct wl_resource *resource, uint32_t id, struct wl_resource *seat) { + int version = wl_resource_get_version(resource); + struct wl_resource *text_input_resource = wl_resource_create(client, + &zwp_text_input_v3_interface, version, id); + if (text_input_resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(text_input_resource, &text_input_impl, + NULL, text_input_resource_destroy); + + struct wlr_seat_client *seat_client = wlr_seat_client_from_resource(seat); + if (seat_client == NULL) { + return; + } + + struct wlr_text_input_v3 *text_input = calloc(1, sizeof(*text_input)); + if (text_input == NULL) { + wl_client_post_no_memory(client); + return; + } + + wl_signal_init(&text_input->events.enable); + wl_signal_init(&text_input->events.commit); + wl_signal_init(&text_input->events.disable); + wl_signal_init(&text_input->events.destroy); + + text_input->resource = text_input_resource; + wl_resource_set_user_data(text_input_resource, text_input); + + struct wlr_seat *wlr_seat = seat_client->seat; + text_input->seat = wlr_seat; + wl_signal_add(&seat_client->events.destroy, + &text_input->seat_destroy); + text_input->seat_destroy.notify = + text_input_handle_seat_destroy; + text_input->surface_destroy.notify = + text_input_handle_focused_surface_destroy; + wl_list_init(&text_input->surface_destroy.link); + + struct wlr_text_input_manager_v3 *manager = + text_input_manager_from_resource(resource); + wl_list_insert(&manager->text_inputs, &text_input->link); + + wl_signal_emit_mutable(&manager->events.new_text_input, text_input); +} + +static const struct zwp_text_input_manager_v3_interface + text_input_manager_impl = { + .destroy = text_input_manager_destroy, + .get_text_input = text_input_manager_get_text_input, +}; + +static void text_input_manager_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_text_input_manager_v3 *manager = data; + + struct wl_resource *resource = wl_resource_create(wl_client, + &zwp_text_input_manager_v3_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + wl_resource_set_implementation(resource, &text_input_manager_impl, + manager, NULL); +} + +static void text_input_manager_v3_destroy(struct wlr_text_input_manager_v3 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, NULL); + + assert(wl_list_empty(&manager->events.new_text_input.listener_list)); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_text_input_manager_v3_destroy(struct wlr_text_input_manager_v3 *manager, + bool destroy_global_safe) { + text_input_manager_v3_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_text_input_manager_v3 *manager = + wl_container_of(listener, manager, display_destroy); + text_input_manager_v3_destroy(manager, false); +} + +struct wlr_text_input_manager_v3 *wlr_text_input_manager_v3_create( + struct wl_display *display) { + struct wlr_text_input_manager_v3 *manager = calloc(1, sizeof(*manager)); + if (!manager) { + return NULL; + } + + wl_list_init(&manager->text_inputs); + + wl_signal_init(&manager->events.new_text_input); + wl_signal_init(&manager->events.destroy); + + manager->global = wl_global_create(display, + &zwp_text_input_manager_v3_interface, 1, manager, + text_input_manager_bind); + if (!manager->global) { + free(manager); + return NULL; + } + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_touch.c b/3rdparty/wlroots/types/wlr_touch.c new file mode 100644 index 0000000000..f8c4175fbb --- /dev/null +++ b/3rdparty/wlroots/types/wlr_touch.c @@ -0,0 +1,40 @@ +#include +#include +#include +#include +#include +#include + +#include "interfaces/wlr_input_device.h" + +struct wlr_touch *wlr_touch_from_input_device( + struct wlr_input_device *input_device) { + assert(input_device->type == WLR_INPUT_DEVICE_TOUCH); + return wl_container_of(input_device, (struct wlr_touch *)NULL, base); +} + +void wlr_touch_init(struct wlr_touch *touch, + const struct wlr_touch_impl *impl, const char *name) { + *touch = (struct wlr_touch){ + .impl = impl, + }; + wlr_input_device_init(&touch->base, WLR_INPUT_DEVICE_TOUCH, name); + + wl_signal_init(&touch->events.down); + wl_signal_init(&touch->events.up); + wl_signal_init(&touch->events.motion); + wl_signal_init(&touch->events.cancel); + wl_signal_init(&touch->events.frame); +} + +void wlr_touch_finish(struct wlr_touch *touch) { + wlr_input_device_finish(&touch->base); + + assert(wl_list_empty(&touch->events.down.listener_list)); + assert(wl_list_empty(&touch->events.up.listener_list)); + assert(wl_list_empty(&touch->events.motion.listener_list)); + assert(wl_list_empty(&touch->events.cancel.listener_list)); + assert(wl_list_empty(&touch->events.frame.listener_list)); + + free(touch->output_name); +} diff --git a/3rdparty/wlroots/types/wlr_transient_seat_v1.c b/3rdparty/wlroots/types/wlr_transient_seat_v1.c new file mode 100644 index 0000000000..fef88eebd6 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_transient_seat_v1.c @@ -0,0 +1,182 @@ +#include +#include +#include +#include +#include +#include +#include "ext-transient-seat-v1-protocol.h" +#include "util/global.h" + +static const struct ext_transient_seat_manager_v1_interface manager_impl; +static const struct ext_transient_seat_v1_interface transient_seat_impl; + +static struct wlr_transient_seat_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_transient_seat_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static struct wlr_transient_seat_v1 *transient_seat_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_transient_seat_v1_interface, &transient_seat_impl)); + return wl_resource_get_user_data(resource); +} + +static void transient_seat_destroy(struct wlr_transient_seat_v1 *seat) { + wl_list_remove(&seat->seat_destroy.link); + wlr_seat_destroy(seat->seat); + free(seat); +} + +static void transient_seat_handle_resource_destroy( + struct wl_resource *resource) { + struct wlr_transient_seat_v1 *seat = + transient_seat_from_resource(resource); + transient_seat_destroy(seat); +} + +static void transient_seat_handle_destroy(struct wl_client *client, + struct wl_resource *seat_resource) { + wl_resource_destroy(seat_resource); +} + +static const struct ext_transient_seat_v1_interface transient_seat_impl = { + .destroy = transient_seat_handle_destroy, +}; + +static void manager_create_transient_seat(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id) { + struct wlr_transient_seat_manager_v1 *manager = + manager_from_resource(manager_resource); + + struct wlr_transient_seat_v1 *seat = calloc(1, sizeof(*seat)); + if (!seat) { + goto failure; + } + + int version = wl_resource_get_version(manager_resource); + seat->resource = wl_resource_create(client, + &ext_transient_seat_v1_interface, version, id); + if (!seat->resource) { + goto failure; + } + + wl_resource_set_implementation(seat->resource, &transient_seat_impl, + seat, transient_seat_handle_resource_destroy); + + wl_list_init(&seat->seat_destroy.link); + wl_signal_emit_mutable(&manager->events.create_seat, seat); + + return; + +failure: + free(seat); + wl_client_post_no_memory(client); +} + +static void transient_seat_handle_seat_destroy(struct wl_listener *listener, + void *data) { + struct wlr_transient_seat_v1 *seat = wl_container_of(listener, seat, + seat_destroy); + seat->seat = NULL; + wl_resource_set_user_data(seat->resource, NULL); + transient_seat_destroy(seat); +} + +void wlr_transient_seat_v1_ready(struct wlr_transient_seat_v1 *seat, + struct wlr_seat *wlr_seat) { + assert(wlr_seat); + + seat->seat = wlr_seat; + + seat->seat_destroy.notify = transient_seat_handle_seat_destroy; + wl_signal_add(&wlr_seat->events.destroy, &seat->seat_destroy); + + struct wl_client *client = wl_resource_get_client(seat->resource); + uint32_t global_name = wl_global_get_name(seat->seat->global, client); + assert(global_name != 0); + ext_transient_seat_v1_send_ready(seat->resource, global_name); +} + +void wlr_transient_seat_v1_deny(struct wlr_transient_seat_v1 *seat) { + ext_transient_seat_v1_send_denied(seat->resource); +} + +static void manager_handle_destroy(struct wl_client *client, + struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static const struct ext_transient_seat_manager_v1_interface manager_impl = { + .create = manager_create_transient_seat, + .destroy = manager_handle_destroy, +}; + +static void transient_seat_manager_v1_destroy(struct wlr_transient_seat_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, NULL); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + assert(wl_list_empty(&manager->events.create_seat.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_transient_seat_manager_v1_destroy(struct wlr_transient_seat_manager_v1 *manager, + bool destroy_global_safe) { + transient_seat_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_transient_seat_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + transient_seat_manager_v1_destroy(manager, false); +} + +static void transient_seat_manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_transient_seat_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &ext_transient_seat_manager_v1_interface, version, id); + + if (!resource) { + wl_client_post_no_memory(client); + return; + } + + wl_resource_set_implementation(resource, &manager_impl, manager, NULL); +} + +struct wlr_transient_seat_manager_v1 *wlr_transient_seat_manager_v1_create( + struct wl_display *display) { + struct wlr_transient_seat_manager_v1 *manager = + calloc(1, sizeof(*manager)); + if (!manager) { + return NULL; + } + + manager->global = wl_global_create(display, + &ext_transient_seat_manager_v1_interface, 1, manager, + transient_seat_manager_bind); + if (!manager->global) { + free(manager); + return NULL; + } + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + wl_signal_init(&manager->events.destroy); + wl_signal_init(&manager->events.create_seat); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_viewporter.c b/3rdparty/wlroots/types/wlr_viewporter.c new file mode 100644 index 0000000000..f7eb57d398 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_viewporter.c @@ -0,0 +1,275 @@ +#include +#include +#include +#include +#include +#include +#include +#include "viewporter-protocol.h" +#include "util/global.h" + +#define VIEWPORTER_VERSION 1 + +struct wlr_viewport { + struct wl_resource *resource; + struct wlr_surface *surface; + + struct wlr_addon addon; + + struct wl_listener surface_client_commit; +}; + +static const struct wp_viewport_interface viewport_impl; + +// Returns NULL if the viewport is inert +static struct wlr_viewport *viewport_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &wp_viewport_interface, + &viewport_impl)); + return wl_resource_get_user_data(resource); +} + +static void viewport_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void viewport_handle_set_source(struct wl_client *client, + struct wl_resource *resource, wl_fixed_t x_fixed, wl_fixed_t y_fixed, + wl_fixed_t width_fixed, wl_fixed_t height_fixed) { + struct wlr_viewport *viewport = viewport_from_resource(resource); + if (viewport == NULL) { + wl_resource_post_error(resource, WP_VIEWPORT_ERROR_NO_SURFACE, + "wp_viewport.set_source sent after wl_surface has been destroyed"); + return; + } + + struct wlr_surface_state *pending = &viewport->surface->pending; + + double x = wl_fixed_to_double(x_fixed); + double y = wl_fixed_to_double(y_fixed); + double width = wl_fixed_to_double(width_fixed); + double height = wl_fixed_to_double(height_fixed); + + if (x == -1.0 && y == -1.0 && width == -1.0 && height == -1.0) { + pending->viewport.has_src = false; + } else if (x < 0 || y < 0 || width <= 0 || height <= 0) { + wl_resource_post_error(resource, WP_VIEWPORT_ERROR_BAD_VALUE, + "wl_viewport.set_source sent with invalid values"); + return; + } else { + pending->viewport.has_src = true; + } + + pending->viewport.src.x = x; + pending->viewport.src.y = y; + pending->viewport.src.width = width; + pending->viewport.src.height = height; + + pending->committed |= WLR_SURFACE_STATE_VIEWPORT; +} + +static void viewport_handle_set_destination(struct wl_client *client, + struct wl_resource *resource, int32_t width, int32_t height) { + struct wlr_viewport *viewport = viewport_from_resource(resource); + if (viewport == NULL) { + wl_resource_post_error(resource, WP_VIEWPORT_ERROR_NO_SURFACE, + "wp_viewport.set_destination sent after wl_surface has been destroyed"); + return; + } + + struct wlr_surface_state *pending = &viewport->surface->pending; + + if (width == -1 && height == -1) { + pending->viewport.has_dst = false; + } else if (width <= 0 || height <= 0) { + wl_resource_post_error(resource, WP_VIEWPORT_ERROR_BAD_VALUE, + "wl_viewport.set_destination sent with invalid values"); + return; + } else { + pending->viewport.has_dst = true; + } + + pending->viewport.dst_width = width; + pending->viewport.dst_height = height; + + pending->committed |= WLR_SURFACE_STATE_VIEWPORT; +} + +static const struct wp_viewport_interface viewport_impl = { + .destroy = viewport_handle_destroy, + .set_source = viewport_handle_set_source, + .set_destination = viewport_handle_set_destination, +}; + +static void viewport_destroy(struct wlr_viewport *viewport) { + if (viewport == NULL) { + return; + } + + struct wlr_surface_state *pending = &viewport->surface->pending; + pending->viewport.has_src = false; + pending->viewport.has_dst = false; + pending->committed |= WLR_SURFACE_STATE_VIEWPORT; + + wlr_addon_finish(&viewport->addon); + + wl_resource_set_user_data(viewport->resource, NULL); + wl_list_remove(&viewport->surface_client_commit.link); + free(viewport); +} + +static void surface_addon_destroy(struct wlr_addon *addon) { + struct wlr_viewport *viewport = wl_container_of(addon, viewport, addon); + viewport_destroy(viewport); +} + +static const struct wlr_addon_interface surface_addon_impl = { + .name = "wlr_viewport", + .destroy = surface_addon_destroy, +}; + +static void viewport_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_viewport *viewport = viewport_from_resource(resource); + viewport_destroy(viewport); +} + +static bool check_src_buffer_bounds(const struct wlr_surface_state *state) { + int width = state->buffer_width / state->scale; + int height = state->buffer_height / state->scale; + wlr_output_transform_coords(state->transform, &width, &height); + + struct wlr_fbox box = state->viewport.src; + return box.x + box.width <= width && box.y + box.height <= height; +} + +static void viewport_handle_surface_client_commit(struct wl_listener *listener, + void *data) { + struct wlr_viewport *viewport = + wl_container_of(listener, viewport, surface_client_commit); + + struct wlr_surface_state *state = &viewport->surface->pending; + + if (!state->viewport.has_dst && + (floor(state->viewport.src.width) != state->viewport.src.width || + floor(state->viewport.src.height) != state->viewport.src.height)) { + wlr_surface_reject_pending(viewport->surface, + viewport->resource, WP_VIEWPORT_ERROR_BAD_SIZE, + "wl_viewport.set_source width and height must be integers " + "when the destination rectangle is unset"); + return; + } + + if (state->viewport.has_src && wlr_surface_state_has_buffer(state) && + !check_src_buffer_bounds(state)) { + wlr_surface_reject_pending(viewport->surface, + viewport->resource, WP_VIEWPORT_ERROR_OUT_OF_BUFFER, + "source rectangle out of buffer bounds"); + return; + } +} + +static void viewporter_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void viewporter_handle_get_viewport(struct wl_client *client, + struct wl_resource *resource, uint32_t id, + struct wl_resource *surface_resource) { + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + + if (wlr_addon_find(&surface->addons, NULL, &surface_addon_impl) != NULL) { + wl_resource_post_error(resource, WP_VIEWPORTER_ERROR_VIEWPORT_EXISTS, + "wp_viewport for this surface already exists"); + return; + } + + struct wlr_viewport *viewport = calloc(1, sizeof(*viewport)); + if (viewport == NULL) { + wl_client_post_no_memory(client); + return; + } + + uint32_t version = wl_resource_get_version(resource); + viewport->resource = wl_resource_create(client, &wp_viewport_interface, + version, id); + if (viewport->resource == NULL) { + wl_client_post_no_memory(client); + free(viewport); + return; + } + wl_resource_set_implementation(viewport->resource, &viewport_impl, + viewport, viewport_handle_resource_destroy); + + viewport->surface = surface; + + wlr_addon_init(&viewport->addon, &surface->addons, NULL, &surface_addon_impl); + + viewport->surface_client_commit.notify = viewport_handle_surface_client_commit; + wl_signal_add(&surface->events.client_commit, &viewport->surface_client_commit); +} + +static const struct wp_viewporter_interface viewporter_impl = { + .destroy = viewporter_handle_destroy, + .get_viewport = viewporter_handle_get_viewport, +}; + +static void viewporter_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_viewporter *viewporter = data; + + struct wl_resource *resource = wl_resource_create(client, + &wp_viewporter_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &viewporter_impl, viewporter, NULL); +} + +static void viewporter_destroy(struct wlr_viewporter *viewporter, + bool destroy_global_safe) { + wl_signal_emit_mutable(&viewporter->events.destroy, NULL); + + assert(wl_list_empty(&viewporter->events.destroy.listener_list)); + + if (destroy_global_safe) { + wlr_global_destroy_safe(viewporter->global); + } else { + wl_global_destroy(viewporter->global); + } + wl_list_remove(&viewporter->display_destroy.link); + free(viewporter); +} + +void wlr_viewporter_destroy(struct wlr_viewporter *viewporter, bool destroy_global_safe) { + viewporter_destroy(viewporter, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_viewporter *viewporter = + wl_container_of(listener, viewporter, display_destroy); + viewporter_destroy(viewporter, false); +} + +struct wlr_viewporter *wlr_viewporter_create(struct wl_display *display) { + struct wlr_viewporter *viewporter = calloc(1, sizeof(*viewporter)); + if (viewporter == NULL) { + return NULL; + } + + viewporter->global = wl_global_create(display, &wp_viewporter_interface, + VIEWPORTER_VERSION, viewporter, viewporter_bind); + if (viewporter->global == NULL) { + free(viewporter); + return NULL; + } + + wl_signal_init(&viewporter->events.destroy); + + viewporter->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &viewporter->display_destroy); + + return viewporter; +} diff --git a/3rdparty/wlroots/types/wlr_virtual_keyboard_v1.c b/3rdparty/wlroots/types/wlr_virtual_keyboard_v1.c new file mode 100644 index 0000000000..f5999c92ac --- /dev/null +++ b/3rdparty/wlroots/types/wlr_virtual_keyboard_v1.c @@ -0,0 +1,275 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "virtual-keyboard-unstable-v1-protocol.h" +#include "util/global.h" + +static const struct wlr_keyboard_impl keyboard_impl = { + .name = "virtual-keyboard", +}; + +static const struct zwp_virtual_keyboard_v1_interface virtual_keyboard_impl; + +struct wlr_virtual_keyboard_v1 *wlr_virtual_keyboard_v1_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwp_virtual_keyboard_v1_interface, &virtual_keyboard_impl)); + return wl_resource_get_user_data(resource); +} + +struct wlr_virtual_keyboard_v1 *wlr_input_device_get_virtual_keyboard( + struct wlr_input_device *wlr_dev) { + if (wlr_dev->type != WLR_INPUT_DEVICE_KEYBOARD) { + return NULL; + } + struct wlr_keyboard *wlr_keyboard = wlr_keyboard_from_input_device(wlr_dev); + if (wlr_keyboard->impl != &keyboard_impl) { + return NULL; + } + return wl_container_of(wlr_keyboard, + (struct wlr_virtual_keyboard_v1 *)NULL, keyboard); +} + +static void virtual_keyboard_keymap(struct wl_client *client, + struct wl_resource *resource, uint32_t format, int32_t fd, + uint32_t size) { + struct wlr_virtual_keyboard_v1 *keyboard = + wlr_virtual_keyboard_v1_from_resource(resource); + if (keyboard == NULL) { + return; + } + + struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + if (!context) { + goto context_fail; + } + void *data = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0); + if (data == MAP_FAILED) { + goto fd_fail; + } + struct xkb_keymap *keymap = xkb_keymap_new_from_buffer(context, data, size, + XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS); + munmap(data, size); + if (!keymap) { + goto keymap_fail; + } + wlr_keyboard_set_keymap(&keyboard->keyboard, keymap); + keyboard->has_keymap = true; + xkb_keymap_unref(keymap); + xkb_context_unref(context); + close(fd); + return; +keymap_fail: +fd_fail: + xkb_context_unref(context); +context_fail: + wl_client_post_no_memory(client); + close(fd); +} + +static void virtual_keyboard_key(struct wl_client *client, + struct wl_resource *resource, uint32_t time, uint32_t key, + uint32_t state) { + struct wlr_virtual_keyboard_v1 *keyboard = + wlr_virtual_keyboard_v1_from_resource(resource); + if (keyboard == NULL) { + return; + } + if (!keyboard->has_keymap) { + wl_resource_post_error(resource, + ZWP_VIRTUAL_KEYBOARD_V1_ERROR_NO_KEYMAP, + "Cannot send a keypress before defining a keymap"); + return; + } + struct wlr_keyboard_key_event event = { + .time_msec = time, + .keycode = key, + .update_state = false, + .state = state, + }; + wlr_keyboard_notify_key(&keyboard->keyboard, &event); +} + +static void virtual_keyboard_modifiers(struct wl_client *client, + struct wl_resource *resource, uint32_t mods_depressed, + uint32_t mods_latched, uint32_t mods_locked, uint32_t group) { + struct wlr_virtual_keyboard_v1 *keyboard = + wlr_virtual_keyboard_v1_from_resource(resource); + if (keyboard == NULL) { + return; + } + if (!keyboard->has_keymap) { + wl_resource_post_error(resource, + ZWP_VIRTUAL_KEYBOARD_V1_ERROR_NO_KEYMAP, + "Cannot send a modifier state before defining a keymap"); + return; + } + wlr_keyboard_notify_modifiers(&keyboard->keyboard, + mods_depressed, mods_latched, mods_locked, group); +} + +static void virtual_keyboard_destroy(struct wlr_virtual_keyboard_v1 *virtual_keyboard) { + wlr_keyboard_finish(&virtual_keyboard->keyboard); + wl_resource_set_user_data(virtual_keyboard->resource, NULL); + wl_list_remove(&virtual_keyboard->seat_destroy.link); + wl_list_remove(&virtual_keyboard->link); + free(virtual_keyboard); +} + +static void virtual_keyboard_destroy_resource(struct wl_resource *resource) { + struct wlr_virtual_keyboard_v1 *virtual_keyboard = + wlr_virtual_keyboard_v1_from_resource(resource); + if (virtual_keyboard == NULL) { + return; + } + virtual_keyboard_destroy(virtual_keyboard); +} + +static void virtual_keyboard_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwp_virtual_keyboard_v1_interface virtual_keyboard_impl = { + .keymap = virtual_keyboard_keymap, + .key = virtual_keyboard_key, + .modifiers = virtual_keyboard_modifiers, + .destroy = virtual_keyboard_handle_destroy, +}; + +static const struct zwp_virtual_keyboard_manager_v1_interface manager_impl; + +static struct wlr_virtual_keyboard_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwp_virtual_keyboard_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void virtual_keyboard_handle_seat_destroy(struct wl_listener *listener, + void *data) { + struct wlr_virtual_keyboard_v1 *virtual_keyboard = wl_container_of(listener, virtual_keyboard, + seat_destroy); + virtual_keyboard_destroy(virtual_keyboard); +} + +static void virtual_keyboard_manager_create_virtual_keyboard( + struct wl_client *client, struct wl_resource *resource, + struct wl_resource *seat, uint32_t id) { + struct wlr_virtual_keyboard_manager_v1 *manager = + manager_from_resource(resource); + struct wlr_seat_client *seat_client = wlr_seat_client_from_resource(seat); + + struct wl_resource *keyboard_resource = wl_resource_create(client, + &zwp_virtual_keyboard_v1_interface, wl_resource_get_version(resource), + id); + if (!keyboard_resource) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(keyboard_resource, &virtual_keyboard_impl, + NULL, virtual_keyboard_destroy_resource); + if (seat_client == NULL) { + return; + } + + struct wlr_virtual_keyboard_v1 *virtual_keyboard = calloc(1, sizeof(*virtual_keyboard)); + if (!virtual_keyboard) { + wl_client_post_no_memory(client); + return; + } + + wlr_keyboard_init(&virtual_keyboard->keyboard, &keyboard_impl, + "wlr_virtual_keyboard_v1"); + + virtual_keyboard->resource = keyboard_resource; + virtual_keyboard->seat = seat_client->seat; + wl_resource_set_user_data(keyboard_resource, virtual_keyboard); + + wl_signal_add(&seat_client->events.destroy, &virtual_keyboard->seat_destroy); + virtual_keyboard->seat_destroy.notify = virtual_keyboard_handle_seat_destroy; + + wl_list_insert(&manager->virtual_keyboards, &virtual_keyboard->link); + + wl_signal_emit_mutable(&manager->events.new_virtual_keyboard, + virtual_keyboard); +} + +static const struct zwp_virtual_keyboard_manager_v1_interface manager_impl = { + .create_virtual_keyboard = virtual_keyboard_manager_create_virtual_keyboard, +}; + +static void virtual_keyboard_manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_virtual_keyboard_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &zwp_virtual_keyboard_manager_v1_interface, version, id); + if (!resource) { + wl_client_post_no_memory(client); + return; + } + + wl_resource_set_implementation(resource, &manager_impl, manager, NULL); +} + +static void virtual_keyboard_manager_v1_destroy(struct wlr_virtual_keyboard_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.new_virtual_keyboard.listener_list)); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_virtual_keyboard_manager_v1_destroy(struct wlr_virtual_keyboard_manager_v1 *manager, + bool destroy_global_safe) { + virtual_keyboard_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_virtual_keyboard_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + virtual_keyboard_manager_v1_destroy(manager, false); +} + +struct wlr_virtual_keyboard_manager_v1* + wlr_virtual_keyboard_manager_v1_create( + struct wl_display *display) { + struct wlr_virtual_keyboard_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (!manager) { + return NULL; + } + + manager->global = wl_global_create(display, + &zwp_virtual_keyboard_manager_v1_interface, 1, manager, + virtual_keyboard_manager_bind); + if (!manager->global) { + free(manager); + return NULL; + } + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + wl_list_init(&manager->virtual_keyboards); + + wl_signal_init(&manager->events.new_virtual_keyboard); + wl_signal_init(&manager->events.destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_virtual_pointer_v1.c b/3rdparty/wlroots/types/wlr_virtual_pointer_v1.c new file mode 100644 index 0000000000..caea80c798 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_virtual_pointer_v1.c @@ -0,0 +1,367 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "wlr-virtual-pointer-unstable-v1-protocol.h" +#include "util/global.h" + +static const struct wlr_pointer_impl pointer_impl = { + .name = "virtual-pointer", +}; + +static const struct zwlr_virtual_pointer_v1_interface virtual_pointer_impl; + +static struct wlr_virtual_pointer_v1 *virtual_pointer_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_virtual_pointer_v1_interface, &virtual_pointer_impl)); + return wl_resource_get_user_data(resource); +} + +static void virtual_pointer_motion(struct wl_client *client, + struct wl_resource *resource, uint32_t time, + wl_fixed_t dx, wl_fixed_t dy) { + struct wlr_virtual_pointer_v1 *pointer = + virtual_pointer_from_resource(resource); + if (pointer == NULL) { + return; + } + struct wlr_pointer_motion_event event = { + .pointer = &pointer->pointer, + .time_msec = time, + .delta_x = wl_fixed_to_double(dx), + .delta_y = wl_fixed_to_double(dy), + .unaccel_dx = wl_fixed_to_double(dx), + .unaccel_dy = wl_fixed_to_double(dy), + }; + wl_signal_emit_mutable(&pointer->pointer.events.motion, &event); +} + +static void virtual_pointer_motion_absolute(struct wl_client *client, + struct wl_resource *resource, uint32_t time, uint32_t x, uint32_t y, + uint32_t x_extent, uint32_t y_extent) { + struct wlr_virtual_pointer_v1 *pointer = + virtual_pointer_from_resource(resource); + if (pointer == NULL) { + return; + } + if (x_extent == 0 || y_extent == 0) { + return; + } + struct wlr_pointer_motion_absolute_event event = { + .pointer = &pointer->pointer, + .time_msec = time, + .x = (double)x / x_extent, + .y = (double)y / y_extent, + }; + wl_signal_emit_mutable(&pointer->pointer.events.motion_absolute, &event); +} + +static void virtual_pointer_button(struct wl_client *client, + struct wl_resource *resource, uint32_t time, uint32_t button, + uint32_t state) { + struct wlr_virtual_pointer_v1 *pointer = + virtual_pointer_from_resource(resource); + if (pointer == NULL) { + return; + } + struct wlr_pointer_button_event event = { + .pointer = &pointer->pointer, + .time_msec = time, + .button = button, + .state = state ? WL_POINTER_BUTTON_STATE_PRESSED : WL_POINTER_BUTTON_STATE_RELEASED, + }; + wlr_pointer_notify_button(&pointer->pointer, &event); +} + +static void virtual_pointer_axis(struct wl_client *client, + struct wl_resource *resource, uint32_t time, uint32_t axis, + wl_fixed_t value) { + if (axis > WL_POINTER_AXIS_HORIZONTAL_SCROLL) { + wl_resource_post_error(resource, + ZWLR_VIRTUAL_POINTER_V1_ERROR_INVALID_AXIS, + "Invalid enumeration value %" PRIu32, axis); + return; + } + struct wlr_virtual_pointer_v1 *pointer = + virtual_pointer_from_resource(resource); + if (pointer == NULL) { + return; + } + pointer->axis = axis; + pointer->axis_valid[pointer->axis] = true; + pointer->axis_event[pointer->axis].pointer = &pointer->pointer; + pointer->axis_event[pointer->axis].time_msec = time; + pointer->axis_event[pointer->axis].orientation = axis; + pointer->axis_event[pointer->axis].delta = wl_fixed_to_double(value); +} + +static void virtual_pointer_frame(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_virtual_pointer_v1 *pointer = + virtual_pointer_from_resource(resource); + if (pointer == NULL) { + return; + } + + for (size_t i = 0; + i < sizeof(pointer->axis_valid) / sizeof(pointer->axis_valid[0]); + ++i) { + if (pointer->axis_valid[i]) { + /* Deliver pending axis event */ + wl_signal_emit_mutable(&pointer->pointer.events.axis, + &pointer->axis_event[i]); + pointer->axis_event[i] = (struct wlr_pointer_axis_event){0}; + pointer->axis_valid[i] = false; + } + } + + wl_signal_emit_mutable(&pointer->pointer.events.frame, &pointer->pointer); +} + +static void virtual_pointer_axis_source(struct wl_client *client, + struct wl_resource *resource, uint32_t source) { + if (source > WL_POINTER_AXIS_SOURCE_WHEEL_TILT) { + wl_resource_post_error(resource, + ZWLR_VIRTUAL_POINTER_V1_ERROR_INVALID_AXIS_SOURCE, + "Invalid enumeration value %" PRIu32, source); + return; + } + struct wlr_virtual_pointer_v1 *pointer = + virtual_pointer_from_resource(resource); + if (pointer == NULL) { + return; + } + int n_axis = sizeof(pointer->axis_event) / sizeof(pointer->axis_event[0]); + for (int i = 0; i < n_axis; i++) { + pointer->axis_event[i].pointer = &pointer->pointer; + pointer->axis_event[i].source = source; + } +} + +static void virtual_pointer_axis_stop(struct wl_client *client, + struct wl_resource *resource, uint32_t time, uint32_t axis) { + if (axis > WL_POINTER_AXIS_HORIZONTAL_SCROLL) { + wl_resource_post_error(resource, + ZWLR_VIRTUAL_POINTER_V1_ERROR_INVALID_AXIS, + "Invalid enumeration value %" PRIu32, axis); + return; + } + struct wlr_virtual_pointer_v1 *pointer = + virtual_pointer_from_resource(resource); + if (pointer == NULL) { + return; + } + pointer->axis = axis; + pointer->axis_valid[pointer->axis] = true; + pointer->axis_event[pointer->axis].pointer = &pointer->pointer; + pointer->axis_event[pointer->axis].time_msec = time; + pointer->axis_event[pointer->axis].orientation = axis; + pointer->axis_event[pointer->axis].delta = 0; + pointer->axis_event[pointer->axis].delta_discrete = 0; +} + +static void virtual_pointer_axis_discrete(struct wl_client *client, + struct wl_resource *resource, uint32_t time, uint32_t axis, + wl_fixed_t value, int32_t discrete) { + if (axis > WL_POINTER_AXIS_HORIZONTAL_SCROLL) { + wl_resource_post_error(resource, + ZWLR_VIRTUAL_POINTER_V1_ERROR_INVALID_AXIS, + "Invalid enumeration value %" PRIu32, axis); + return; + } + struct wlr_virtual_pointer_v1 *pointer = + virtual_pointer_from_resource(resource); + if (pointer == NULL) { + return; + } + pointer->axis = axis; + pointer->axis_valid[pointer->axis] = true; + pointer->axis_event[pointer->axis].pointer = &pointer->pointer; + pointer->axis_event[pointer->axis].time_msec = time; + pointer->axis_event[pointer->axis].orientation = axis; + pointer->axis_event[pointer->axis].delta = wl_fixed_to_double(value); + pointer->axis_event[pointer->axis].delta_discrete = discrete * + WLR_POINTER_AXIS_DISCRETE_STEP; +} + +static void virtual_pointer_destroy_resource(struct wl_resource *resource) { + struct wlr_virtual_pointer_v1 *pointer = + virtual_pointer_from_resource(resource); + if (pointer == NULL) { + return; + } + + wlr_pointer_finish(&pointer->pointer); + + wl_resource_set_user_data(pointer->resource, NULL); + wl_list_remove(&pointer->link); + free(pointer); +} + +static void virtual_pointer_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwlr_virtual_pointer_v1_interface virtual_pointer_impl = { + .motion = virtual_pointer_motion, + .motion_absolute = virtual_pointer_motion_absolute, + .button = virtual_pointer_button, + .axis = virtual_pointer_axis, + .frame = virtual_pointer_frame, + .axis_source = virtual_pointer_axis_source, + .axis_stop = virtual_pointer_axis_stop, + .axis_discrete = virtual_pointer_axis_discrete, + .destroy = virtual_pointer_destroy, +}; + +static const struct zwlr_virtual_pointer_manager_v1_interface manager_impl; + +static struct wlr_virtual_pointer_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zwlr_virtual_pointer_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void virtual_pointer_manager_create_virtual_pointer_with_output( + struct wl_client *client, struct wl_resource *resource, + struct wl_resource *seat, struct wl_resource *output, + uint32_t id) { + struct wlr_virtual_pointer_manager_v1 *manager = manager_from_resource(resource); + + struct wlr_virtual_pointer_v1 *virtual_pointer = calloc(1, sizeof(*virtual_pointer)); + if (!virtual_pointer) { + wl_client_post_no_memory(client); + return; + } + + wlr_pointer_init(&virtual_pointer->pointer, &pointer_impl, + "wlr_virtual_pointer_v1"); + + struct wl_resource *pointer_resource = wl_resource_create(client, + &zwlr_virtual_pointer_v1_interface, wl_resource_get_version(resource), + id); + if (!pointer_resource) { + free(virtual_pointer); + wl_client_post_no_memory(client); + return; + } + + wl_resource_set_implementation(pointer_resource, &virtual_pointer_impl, + virtual_pointer, virtual_pointer_destroy_resource); + + struct wlr_virtual_pointer_v1_new_pointer_event event = { + .new_pointer = virtual_pointer, + }; + + if (seat) { + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat); + event.suggested_seat = seat_client != NULL ? seat_client->seat : NULL; + } + + if (output) { + struct wlr_output *wlr_output = wlr_output_from_resource(output); + event.suggested_output = wlr_output; + } + + virtual_pointer->resource = pointer_resource; + + wl_list_insert(&manager->virtual_pointers, &virtual_pointer->link); + wl_signal_emit_mutable(&manager->events.new_virtual_pointer, &event); +} + +static void virtual_pointer_manager_create_virtual_pointer( + struct wl_client *client, struct wl_resource *resource, + struct wl_resource *seat, uint32_t id) { + virtual_pointer_manager_create_virtual_pointer_with_output(client, + resource, seat, NULL, id); +} +static void virtual_pointer_manager_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zwlr_virtual_pointer_manager_v1_interface manager_impl = { + .create_virtual_pointer = virtual_pointer_manager_create_virtual_pointer, + .create_virtual_pointer_with_output = virtual_pointer_manager_create_virtual_pointer_with_output, + .destroy = virtual_pointer_manager_destroy, +}; + +static void virtual_pointer_manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_virtual_pointer_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &zwlr_virtual_pointer_manager_v1_interface, version, id); + + if (!resource) { + wl_client_post_no_memory(client); + return; + } + + wl_resource_set_implementation(resource, &manager_impl, manager, NULL); +} + +static void virtual_pointer_manager_v1_destroy(struct wlr_virtual_pointer_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.new_virtual_pointer.listener_list)); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + struct wlr_virtual_pointer_v1 *pointer, *pointer_tmp; + wl_list_for_each_safe(pointer, pointer_tmp, + &manager->virtual_pointers, link) { + wl_resource_destroy(pointer->resource); + } + free(manager); +} + +void wlr_virtual_pointer_manager_v1_destroy(struct wlr_virtual_pointer_manager_v1 *manager, + bool destroy_global_safe) { + virtual_pointer_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_virtual_pointer_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + virtual_pointer_manager_v1_destroy(manager, false); +} + +struct wlr_virtual_pointer_manager_v1* wlr_virtual_pointer_manager_v1_create( + struct wl_display *display) { + struct wlr_virtual_pointer_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (!manager) { + return NULL; + } + + wl_list_init(&manager->virtual_pointers); + + wl_signal_init(&manager->events.new_virtual_pointer); + wl_signal_init(&manager->events.destroy); + + manager->global = wl_global_create(display, + &zwlr_virtual_pointer_manager_v1_interface, 2, manager, + virtual_pointer_manager_bind); + if (!manager->global) { + free(manager); + return NULL; + } + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_xcursor_manager.c b/3rdparty/wlroots/types/wlr_xcursor_manager.c new file mode 100644 index 0000000000..b45dcd7b1e --- /dev/null +++ b/3rdparty/wlroots/types/wlr_xcursor_manager.c @@ -0,0 +1,65 @@ +#include +#include +#include + +struct wlr_xcursor_manager *wlr_xcursor_manager_create(const char *name, + uint32_t size) { + struct wlr_xcursor_manager *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + if (name != NULL) { + manager->name = strdup(name); + } + manager->size = size; + wl_list_init(&manager->scaled_themes); + return manager; +} + +void wlr_xcursor_manager_destroy(struct wlr_xcursor_manager *manager) { + if (manager == NULL) { + return; + } + struct wlr_xcursor_manager_theme *theme, *tmp; + wl_list_for_each_safe(theme, tmp, &manager->scaled_themes, link) { + wl_list_remove(&theme->link); + wlr_xcursor_theme_destroy(theme->theme); + free(theme); + } + free(manager->name); + free(manager); +} + +bool wlr_xcursor_manager_load(struct wlr_xcursor_manager *manager, + float scale) { + struct wlr_xcursor_manager_theme *theme; + wl_list_for_each(theme, &manager->scaled_themes, link) { + if (theme->scale == scale) { + return true; + } + } + + theme = calloc(1, sizeof(*theme)); + if (theme == NULL) { + return false; + } + theme->scale = scale; + theme->theme = wlr_xcursor_theme_load(manager->name, manager->size * scale); + if (theme->theme == NULL) { + free(theme); + return false; + } + wl_list_insert(&manager->scaled_themes, &theme->link); + return true; +} + +struct wlr_xcursor *wlr_xcursor_manager_get_xcursor( + struct wlr_xcursor_manager *manager, const char *name, float scale) { + struct wlr_xcursor_manager_theme *theme; + wl_list_for_each(theme, &manager->scaled_themes, link) { + if (theme->scale == scale) { + return wlr_xcursor_theme_get_cursor(theme->theme, name); + } + } + return NULL; +} diff --git a/3rdparty/wlroots/types/wlr_xdg_activation_v1.c b/3rdparty/wlroots/types/wlr_xdg_activation_v1.c new file mode 100644 index 0000000000..bc3c9ad410 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_xdg_activation_v1.c @@ -0,0 +1,451 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "util/token.h" +#include "xdg-activation-v1-protocol.h" +#include "util/global.h" + +#define XDG_ACTIVATION_V1_VERSION 1 + +static const struct xdg_activation_token_v1_interface token_impl; + +static struct wlr_xdg_activation_token_v1 *token_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &xdg_activation_token_v1_interface, &token_impl)); + return wl_resource_get_user_data(resource); +} + +void wlr_xdg_activation_token_v1_destroy( + struct wlr_xdg_activation_token_v1 *token) { + if (token == NULL) { + return; + } + if (token->resource != NULL) { + wl_resource_set_user_data(token->resource, NULL); // make inert + } + if (token->timeout != NULL) { + wl_event_source_remove(token->timeout); + } + + wl_signal_emit_mutable(&token->events.destroy, NULL); + + assert(wl_list_empty(&token->events.destroy.listener_list)); + + wl_list_remove(&token->link); + wl_list_remove(&token->seat_destroy.link); + wl_list_remove(&token->surface_destroy.link); + free(token->app_id); + free(token->token); + free(token); +} + +static int token_handle_timeout(void *data) { + struct wlr_xdg_activation_token_v1 *token = data; + wlr_log(WLR_DEBUG, "Activation token '%s' has expired", token->token); + wlr_xdg_activation_token_v1_destroy(token); + return 0; +} + +static void token_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_xdg_activation_token_v1 *token = token_from_resource(resource); + wlr_xdg_activation_token_v1_destroy(token); +} + +static void token_handle_destroy(struct wl_client *client, + struct wl_resource *token_resource) { + wl_resource_destroy(token_resource); +} + +static bool token_init( struct wlr_xdg_activation_token_v1 *token) { + char token_str[TOKEN_SIZE] = {0}; + if (!generate_token(token_str)) { + return false; + } + + token->token = strdup(token_str); + if (token->token == NULL) { + return false; + } + + if (token->activation->token_timeout_msec > 0) { + // Needs wayland > 1.19 + // struct wl_display *display = wl_global_get_display(activation->global); + struct wl_display *display = token->activation->display; + struct wl_event_loop *loop = wl_display_get_event_loop(display); + token->timeout = + wl_event_loop_add_timer(loop, token_handle_timeout, token); + if (token->timeout == NULL) { + return false; + } + wl_event_source_timer_update(token->timeout, + token->activation->token_timeout_msec); + } + + assert(wl_list_empty(&token->link)); + wl_list_insert(&token->activation->tokens, &token->link); + return true; +} + +static void token_handle_commit(struct wl_client *client, + struct wl_resource *token_resource) { + struct wlr_xdg_activation_token_v1 *token = + token_from_resource(token_resource); + if (token == NULL) { + wl_resource_post_error(token_resource, + XDG_ACTIVATION_TOKEN_V1_ERROR_ALREADY_USED, + "The activation token has already been used"); + return; + } + + // Make the token resource inert + wl_resource_set_user_data(token->resource, NULL); + token->resource = NULL; + + if (token->seat != NULL) { + struct wlr_seat_client *seat_client = + wlr_seat_client_for_wl_client(token->seat, client); + if (seat_client == NULL || + !wlr_seat_client_validate_event_serial(seat_client, token->serial)) { + wlr_log(WLR_DEBUG, "Rejecting token commit request: " + "serial %"PRIu32" was never given to client", token->serial); + goto error; + } + + if (token->surface != NULL && + token->surface != token->seat->keyboard_state.focused_surface && + token->surface != token->seat->pointer_state.focused_surface) { + wlr_log(WLR_DEBUG, "Rejecting token commit request: " + "surface doesn't have focus"); + goto error; + } + } + + if (!token_init(token)) { + wl_client_post_no_memory(client); + return; + } + + wl_signal_emit_mutable(&token->activation->events.new_token, token); + + xdg_activation_token_v1_send_done(token_resource, token->token); + + return; + +error:; + // Here we send a generated token, but it's invalid and can't be used to + // request activation. + char token_str[TOKEN_SIZE] = {0}; + if (!generate_token(token_str)) { + wl_client_post_no_memory(client); + return; + } + + xdg_activation_token_v1_send_done(token_resource, token_str); + wlr_xdg_activation_token_v1_destroy(token); +} + +static void token_handle_set_app_id(struct wl_client *client, + struct wl_resource *token_resource, const char *app_id) { + struct wlr_xdg_activation_token_v1 *token = + token_from_resource(token_resource); + if (token == NULL) { + wl_resource_post_error(token_resource, + XDG_ACTIVATION_TOKEN_V1_ERROR_ALREADY_USED, + "The activation token has already been used"); + return; + } + + free(token->app_id); + token->app_id = strdup(app_id); +} + +static void token_handle_seat_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_activation_token_v1 *token = + wl_container_of(listener, token, seat_destroy); + wl_list_remove(&token->seat_destroy.link); + wl_list_init(&token->seat_destroy.link); + token->serial = 0; + token->seat = NULL; +} + +static void token_handle_set_serial(struct wl_client *client, + struct wl_resource *token_resource, uint32_t serial, + struct wl_resource *seat_resource) { + struct wlr_xdg_activation_token_v1 *token = + token_from_resource(token_resource); + if (token == NULL) { + wl_resource_post_error(token_resource, + XDG_ACTIVATION_TOKEN_V1_ERROR_ALREADY_USED, + "The activation token has already been used"); + return; + } + + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat_resource); + if (seat_client == NULL) { + wlr_log(WLR_DEBUG, "Rejecting token set_serial request: seat is inert"); + return; + } + + token->seat = seat_client->seat; + token->serial = serial; + + token->seat_destroy.notify = token_handle_seat_destroy; + wl_list_remove(&token->seat_destroy.link); + wl_signal_add(&token->seat->events.destroy, &token->seat_destroy); +} + +static void token_handle_surface_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_activation_token_v1 *token = + wl_container_of(listener, token, surface_destroy); + wl_list_remove(&token->surface_destroy.link); + wl_list_init(&token->surface_destroy.link); + token->surface = NULL; +} + +static void token_handle_set_surface(struct wl_client *client, + struct wl_resource *token_resource, + struct wl_resource *surface_resource) { + struct wlr_xdg_activation_token_v1 *token = + token_from_resource(token_resource); + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + if (token == NULL) { + wl_resource_post_error(token_resource, + XDG_ACTIVATION_TOKEN_V1_ERROR_ALREADY_USED, + "The activation token has already been used"); + return; + } + + token->surface = surface; + + token->surface_destroy.notify = token_handle_surface_destroy; + wl_list_remove(&token->surface_destroy.link); + wl_signal_add(&surface->events.destroy, &token->surface_destroy); +} + +static const struct xdg_activation_token_v1_interface token_impl = { + .destroy = token_handle_destroy, + .commit = token_handle_commit, + .set_app_id = token_handle_set_app_id, + .set_serial = token_handle_set_serial, + .set_surface = token_handle_set_surface, +}; + +static const struct xdg_activation_v1_interface activation_impl; + +static struct wlr_xdg_activation_v1 *activation_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &xdg_activation_v1_interface, &activation_impl)); + return wl_resource_get_user_data(resource); +} + +static void activation_handle_destroy(struct wl_client *client, + struct wl_resource *activation_resource) { + wl_resource_destroy(activation_resource); +} + +static struct wlr_xdg_activation_token_v1 *activation_token_create( + struct wlr_xdg_activation_v1 *activation) { + struct wlr_xdg_activation_token_v1 *token = calloc(1, sizeof(*token)); + if (token == NULL) { + return NULL; + } + wl_list_init(&token->link); + wl_list_init(&token->seat_destroy.link); + wl_list_init(&token->surface_destroy.link); + + wl_signal_init(&token->events.destroy); + + token->activation = activation; + + return token; +} + +static void activation_handle_get_activation_token(struct wl_client *client, + struct wl_resource *activation_resource, uint32_t id) { + struct wlr_xdg_activation_v1 *activation = + activation_from_resource(activation_resource); + + struct wlr_xdg_activation_token_v1 *token = activation_token_create(activation); + if (token == NULL) { + wl_client_post_no_memory(client); + return; + } + + uint32_t version = wl_resource_get_version(activation_resource); + token->resource = wl_resource_create(client, + &xdg_activation_token_v1_interface, version, id); + if (token->resource == NULL) { + free(token); + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(token->resource, &token_impl, token, + token_handle_resource_destroy); +} + +static void activation_handle_activate(struct wl_client *client, + struct wl_resource *activation_resource, const char *token_str, + struct wl_resource *surface_resource) { + struct wlr_xdg_activation_v1 *activation = + activation_from_resource(activation_resource); + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + + struct wlr_xdg_activation_token_v1 *token; + bool found = false; + wl_list_for_each(token, &activation->tokens, link) { + if (strcmp(token_str, token->token) == 0) { + found = true; + break; + } + } + if (!found) { + wlr_log(WLR_DEBUG, "Rejecting activate request: unknown token"); + return; + } + + struct wlr_xdg_activation_v1_request_activate_event event = { + .activation = activation, + .token = token, + .surface = surface, + }; + wl_signal_emit_mutable(&activation->events.request_activate, &event); + + wlr_xdg_activation_token_v1_destroy(token); +} + +static const struct xdg_activation_v1_interface activation_impl = { + .destroy = activation_handle_destroy, + .get_activation_token = activation_handle_get_activation_token, + .activate = activation_handle_activate, +}; + +static void activation_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_xdg_activation_v1 *activation = data; + + struct wl_resource *resource = wl_resource_create(client, + &xdg_activation_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &activation_impl, activation, NULL); +} + +static void xdg_activation_v1_destroy(struct wlr_xdg_activation_v1 *activation, + bool destroy_global_safe) { + wl_signal_emit_mutable(&activation->events.destroy, NULL); + + assert(wl_list_empty(&activation->events.destroy.listener_list)); + assert(wl_list_empty(&activation->events.request_activate.listener_list)); + assert(wl_list_empty(&activation->events.new_token.listener_list)); + + struct wlr_xdg_activation_token_v1 *token, *token_tmp; + wl_list_for_each_safe(token, token_tmp, &activation->tokens, link) { + wlr_xdg_activation_token_v1_destroy(token); + } + + wl_list_remove(&activation->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(activation->global); + } else { + wl_global_destroy(activation->global); + } + free(activation); +} + +void wlr_xdg_activation_v1_destroy(struct wlr_xdg_activation_v1 *activation, + bool destroy_global_safe) { + xdg_activation_v1_destroy(activation, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_activation_v1 *activation = + wl_container_of(listener, activation, display_destroy); + xdg_activation_v1_destroy(activation, false); +} + +struct wlr_xdg_activation_v1 *wlr_xdg_activation_v1_create( + struct wl_display *display) { + struct wlr_xdg_activation_v1 *activation = calloc(1, sizeof(*activation)); + if (activation == NULL) { + return NULL; + } + + activation->token_timeout_msec = 30000; // 30s + wl_list_init(&activation->tokens); + + wl_signal_init(&activation->events.destroy); + wl_signal_init(&activation->events.request_activate); + wl_signal_init(&activation->events.new_token); + + activation->global = wl_global_create(display, + &xdg_activation_v1_interface, XDG_ACTIVATION_V1_VERSION, activation, + activation_bind); + if (activation->global == NULL) { + free(activation); + return NULL; + } + + activation->display = display; + + activation->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &activation->display_destroy); + + return activation; +} + +struct wlr_xdg_activation_token_v1 *wlr_xdg_activation_token_v1_create( + struct wlr_xdg_activation_v1 *activation) { + struct wlr_xdg_activation_token_v1 *token = activation_token_create(activation); + + if (token == NULL) { + return NULL; + } + + if (!token_init(token)) { + wlr_xdg_activation_token_v1_destroy(token); + return NULL; + } + + return token; +} + +struct wlr_xdg_activation_token_v1 *wlr_xdg_activation_v1_find_token( + struct wlr_xdg_activation_v1 *activation, const char *token_str) { + struct wlr_xdg_activation_token_v1 *token; + wl_list_for_each(token, &activation->tokens, link) { + if (strcmp(token_str, token->token) == 0) { + return token; + } + } + return NULL; +} + +const char *wlr_xdg_activation_token_v1_get_name( + struct wlr_xdg_activation_token_v1 *token) { + return token->token; +} + +struct wlr_xdg_activation_token_v1 *wlr_xdg_activation_v1_add_token( + struct wlr_xdg_activation_v1 *activation, const char *token_str) { + assert(token_str); + + struct wlr_xdg_activation_token_v1 *token = activation_token_create(activation); + if (token == NULL) { + return NULL; + } + token->token = strdup(token_str); + + wl_list_insert(&activation->tokens, &token->link); + + return token; +} diff --git a/3rdparty/wlroots/types/wlr_xdg_decoration_v1.c b/3rdparty/wlroots/types/wlr_xdg_decoration_v1.c new file mode 100644 index 0000000000..a63d4d5938 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_xdg_decoration_v1.c @@ -0,0 +1,310 @@ +#include +#include +#include +#include +#include +#include "xdg-decoration-unstable-v1-protocol.h" +#include "util/global.h" + +#define DECORATION_MANAGER_VERSION 1 + +static const struct zxdg_toplevel_decoration_v1_interface + toplevel_decoration_impl; + +static struct wlr_xdg_toplevel_decoration_v1 *toplevel_decoration_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zxdg_toplevel_decoration_v1_interface, &toplevel_decoration_impl)); + return wl_resource_get_user_data(resource); +} + +static void toplevel_decoration_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void toplevel_decoration_handle_set_mode(struct wl_client *client, + struct wl_resource *resource, + enum zxdg_toplevel_decoration_v1_mode mode) { + struct wlr_xdg_toplevel_decoration_v1 *decoration = + toplevel_decoration_from_resource(resource); + + decoration->requested_mode = + (enum wlr_xdg_toplevel_decoration_v1_mode)mode; + wl_signal_emit_mutable(&decoration->events.request_mode, decoration); +} + +static void toplevel_decoration_handle_unset_mode(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_xdg_toplevel_decoration_v1 *decoration = + toplevel_decoration_from_resource(resource); + + decoration->requested_mode = WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_NONE; + wl_signal_emit_mutable(&decoration->events.request_mode, decoration); +} + +static const struct zxdg_toplevel_decoration_v1_interface + toplevel_decoration_impl = { + .destroy = toplevel_decoration_handle_destroy, + .set_mode = toplevel_decoration_handle_set_mode, + .unset_mode = toplevel_decoration_handle_unset_mode, +}; + +uint32_t wlr_xdg_toplevel_decoration_v1_set_mode( + struct wlr_xdg_toplevel_decoration_v1 *decoration, + enum wlr_xdg_toplevel_decoration_v1_mode mode) { + assert(mode != WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_NONE); + decoration->scheduled_mode = mode; + return wlr_xdg_surface_schedule_configure(decoration->toplevel->base); +} + +static void toplevel_decoration_handle_resource_destroy( + struct wl_resource *resource) { + struct wlr_xdg_toplevel_decoration_v1 *decoration = + toplevel_decoration_from_resource(resource); + wl_signal_emit_mutable(&decoration->events.destroy, decoration); + + assert(wl_list_empty(&decoration->events.destroy.listener_list)); + assert(wl_list_empty(&decoration->events.request_mode.listener_list)); + + wlr_surface_synced_finish(&decoration->synced); + wl_list_remove(&decoration->toplevel_destroy.link); + wl_list_remove(&decoration->surface_configure.link); + wl_list_remove(&decoration->surface_ack_configure.link); + struct wlr_xdg_toplevel_decoration_v1_configure *configure, *tmp; + wl_list_for_each_safe(configure, tmp, &decoration->configure_list, link) { + free(configure); + } + wl_list_remove(&decoration->link); + free(decoration); +} + +static void toplevel_decoration_handle_toplevel_destroy( + struct wl_listener *listener, void *data) { + struct wlr_xdg_toplevel_decoration_v1 *decoration = + wl_container_of(listener, decoration, toplevel_destroy); + + wl_resource_post_error(decoration->resource, + ZXDG_TOPLEVEL_DECORATION_V1_ERROR_ORPHANED, + "xdg_toplevel destroyed before xdg_toplevel_decoration"); + + wl_resource_destroy(decoration->resource); +} + +static void toplevel_decoration_handle_surface_configure( + struct wl_listener *listener, void *data) { + struct wlr_xdg_toplevel_decoration_v1 *decoration = + wl_container_of(listener, decoration, surface_configure); + struct wlr_xdg_surface_configure *surface_configure = data; + + if (decoration->pending.mode == decoration->scheduled_mode) { + return; + } + + struct wlr_xdg_toplevel_decoration_v1_configure *configure = calloc(1, sizeof(*configure)); + if (configure == NULL) { + return; + } + configure->surface_configure = surface_configure; + configure->mode = decoration->scheduled_mode; + wl_list_insert(decoration->configure_list.prev, &configure->link); + + zxdg_toplevel_decoration_v1_send_configure(decoration->resource, + configure->mode); +} + +static void toplevel_decoration_handle_surface_ack_configure( + struct wl_listener *listener, void *data) { + struct wlr_xdg_toplevel_decoration_v1 *decoration = + wl_container_of(listener, decoration, surface_ack_configure); + struct wlr_xdg_surface_configure *surface_configure = data; + + // First find the ack'ed configure + bool found = false; + struct wlr_xdg_toplevel_decoration_v1_configure *configure, *tmp; + wl_list_for_each(configure, &decoration->configure_list, link) { + if (configure->surface_configure == surface_configure) { + found = true; + break; + } + } + if (!found) { + return; + } + // Then remove old configures from the list + wl_list_for_each_safe(configure, tmp, &decoration->configure_list, link) { + if (configure->surface_configure == surface_configure) { + break; + } + wl_list_remove(&configure->link); + free(configure); + } + + decoration->pending.mode = configure->mode; + + wl_list_remove(&configure->link); + free(configure); +} + +static const struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(struct wlr_xdg_toplevel_decoration_v1_state), +}; + +static const struct zxdg_decoration_manager_v1_interface decoration_manager_impl; + +static struct wlr_xdg_decoration_manager_v1 * + decoration_manager_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &zxdg_decoration_manager_v1_interface, + &decoration_manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void decoration_manager_handle_destroy( + struct wl_client *client, struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static void decoration_manager_handle_get_toplevel_decoration( + struct wl_client *client, struct wl_resource *manager_resource, + uint32_t id, struct wl_resource *toplevel_resource) { + struct wlr_xdg_decoration_manager_v1 *manager = + decoration_manager_from_resource(manager_resource); + struct wlr_xdg_toplevel *toplevel = + wlr_xdg_toplevel_from_resource(toplevel_resource); + + if (wlr_surface_has_buffer(toplevel->base->surface)) { + wl_resource_post_error(manager_resource, + ZXDG_TOPLEVEL_DECORATION_V1_ERROR_UNCONFIGURED_BUFFER, + "xdg_toplevel_decoration must not have a buffer at creation"); + return; + } + + struct wlr_xdg_toplevel_decoration_v1 *existing; + wl_list_for_each(existing, &manager->decorations, link) { + if (existing->toplevel == toplevel) { + wl_resource_post_error(manager_resource, + ZXDG_TOPLEVEL_DECORATION_V1_ERROR_ALREADY_CONSTRUCTED, + "xdg_toplevel already has a decoration object"); + return; + } + } + + struct wlr_xdg_toplevel_decoration_v1 *decoration = calloc(1, sizeof(*decoration)); + if (decoration == NULL) { + wl_client_post_no_memory(client); + return; + } + decoration->manager = manager; + decoration->toplevel = toplevel; + + if (!wlr_surface_synced_init(&decoration->synced, toplevel->base->surface, + &surface_synced_impl, &decoration->pending, &decoration->current)) { + free(decoration); + wl_client_post_no_memory(client); + return; + } + + uint32_t version = wl_resource_get_version(manager_resource); + decoration->resource = wl_resource_create(client, + &zxdg_toplevel_decoration_v1_interface, version, id); + if (decoration->resource == NULL) { + wlr_surface_synced_finish(&decoration->synced); + free(decoration); + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(decoration->resource, + &toplevel_decoration_impl, decoration, + toplevel_decoration_handle_resource_destroy); + + wlr_log(WLR_DEBUG, "new xdg_toplevel_decoration %p (res %p)", decoration, + decoration->resource); + + wl_list_init(&decoration->configure_list); + + wl_signal_init(&decoration->events.destroy); + wl_signal_init(&decoration->events.request_mode); + + wl_signal_add(&toplevel->events.destroy, &decoration->toplevel_destroy); + decoration->toplevel_destroy.notify = toplevel_decoration_handle_toplevel_destroy; + wl_signal_add(&toplevel->base->events.configure, &decoration->surface_configure); + decoration->surface_configure.notify = toplevel_decoration_handle_surface_configure; + wl_signal_add(&toplevel->base->events.ack_configure, &decoration->surface_ack_configure); + decoration->surface_ack_configure.notify = toplevel_decoration_handle_surface_ack_configure; + + wl_list_insert(&manager->decorations, &decoration->link); + + wl_signal_emit_mutable(&manager->events.new_toplevel_decoration, decoration); +} + +static const struct zxdg_decoration_manager_v1_interface + decoration_manager_impl = { + .destroy = decoration_manager_handle_destroy, + .get_toplevel_decoration = decoration_manager_handle_get_toplevel_decoration, +}; + +static void decoration_manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_xdg_decoration_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &zxdg_decoration_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &decoration_manager_impl, + manager, NULL); +} + +static void xdg_decoration_manager_v1_destroy(struct wlr_xdg_decoration_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.new_toplevel_decoration.listener_list)); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_xdg_decoration_manager_v1_destroy(struct wlr_xdg_decoration_manager_v1 *manager, + bool destroy_global_safe) { + xdg_decoration_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_decoration_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + xdg_decoration_manager_v1_destroy(manager, false); +} + +struct wlr_xdg_decoration_manager_v1 * + wlr_xdg_decoration_manager_v1_create(struct wl_display *display) { + struct wlr_xdg_decoration_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + manager->global = wl_global_create(display, + &zxdg_decoration_manager_v1_interface, DECORATION_MANAGER_VERSION, + manager, decoration_manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + wl_list_init(&manager->decorations); + + wl_signal_init(&manager->events.new_toplevel_decoration); + wl_signal_init(&manager->events.destroy); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_xdg_dialog_v1.c b/3rdparty/wlroots/types/wlr_xdg_dialog_v1.c new file mode 100644 index 0000000000..7df3ec49f2 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_xdg_dialog_v1.c @@ -0,0 +1,216 @@ +#include +#include +#include + +#include +#include + +#include "xdg-dialog-v1-protocol.h" +#include "util/global.h" + +// NOTE: xdg_dialog_v1 becomes inert when the corresponding xdg_toplevel is destroyed + +#define XDG_WM_DIALOG_V1_VERSION 1 + +static const struct xdg_dialog_v1_interface dialog_impl; + +static struct wlr_xdg_dialog_v1 *dialog_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &xdg_dialog_v1_interface, &dialog_impl)); + return wl_resource_get_user_data(resource); +} + +static const struct xdg_wm_dialog_v1_interface wm_impl; + +static struct wlr_xdg_wm_dialog_v1 *wm_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &xdg_wm_dialog_v1_interface, &wm_impl)); + return wl_resource_get_user_data(resource); +} + +static void resource_destroy(struct wl_client *client, struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void surface_addon_destroy(struct wlr_addon *addon) { + // As wlr_xdg_toplevel is always destroyed before the surface, this should + // never be reached. + abort(); +} + +static const struct wlr_addon_interface surface_addon_impl = { + .name = "xdg_wm_dialog_v1", + .destroy = surface_addon_destroy, +}; + +static void set_modal(struct wlr_xdg_dialog_v1 *dialog, bool modal) { + if (dialog->modal == modal) { + return; + } + dialog->modal = modal; + wl_signal_emit_mutable(&dialog->events.set_modal, NULL); +} + +static void dialog_handle_set_modal(struct wl_client *client, struct wl_resource *resource) { + struct wlr_xdg_dialog_v1 *dialog = dialog_from_resource(resource); + if (dialog == NULL) { + return; + } + set_modal(dialog, true); +} + +static void dialog_handle_unset_modal(struct wl_client *client, struct wl_resource *resource) { + struct wlr_xdg_dialog_v1 *dialog = dialog_from_resource(resource); + if (dialog == NULL) { + return; + } + set_modal(dialog, false); +}; + +static const struct xdg_dialog_v1_interface dialog_impl = { + .destroy = resource_destroy, + .set_modal = dialog_handle_set_modal, + .unset_modal = dialog_handle_unset_modal, +}; + +static void dialog_destroy(struct wlr_xdg_dialog_v1 *dialog) { + if (dialog == NULL) { + return; + } + + wl_signal_emit_mutable(&dialog->events.destroy, NULL); + + assert(wl_list_empty(&dialog->events.destroy.listener_list)); + assert(wl_list_empty(&dialog->events.set_modal.listener_list)); + + wlr_addon_finish(&dialog->surface_addon); + wl_list_remove(&dialog->xdg_toplevel_destroy.link); + + wl_resource_set_user_data(dialog->resource, NULL); + free(dialog); +} + +static void handle_xdg_toplevel_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_dialog_v1 *dialog = wl_container_of(listener, dialog, xdg_toplevel_destroy); + dialog_destroy(dialog); +} + +static void handle_resource_destroy(struct wl_resource *resource) { + struct wlr_xdg_dialog_v1 *dialog = dialog_from_resource(resource); + dialog_destroy(dialog); +} + +static void wm_get_xdg_dialog(struct wl_client *client, struct wl_resource *wm_resource, + uint32_t id, struct wl_resource *toplevel_resource) { + struct wlr_xdg_wm_dialog_v1 *wm = wm_from_resource(wm_resource); + struct wlr_xdg_toplevel *xdg_toplevel = wlr_xdg_toplevel_from_resource(toplevel_resource); + + struct wlr_addon_set *addon_set = &xdg_toplevel->base->surface->addons; + + if (wlr_addon_find(addon_set, NULL, &surface_addon_impl) != NULL) { + wl_resource_post_error(wm_resource, XDG_WM_DIALOG_V1_ERROR_ALREADY_USED, + "the xdg_toplevel object has already been used to create a xdg_dialog_v1"); + return; + } + + struct wlr_xdg_dialog_v1 *dialog = calloc(1, sizeof(*dialog)); + if (dialog == NULL) { + wl_resource_post_no_memory(wm_resource); + return; + } + + dialog->resource = wl_resource_create(client, &xdg_dialog_v1_interface, + wl_resource_get_version(wm_resource), id); + if (dialog->resource == NULL) { + free(dialog); + wl_resource_post_no_memory(wm_resource); + return; + } + wl_resource_set_implementation(dialog->resource, &dialog_impl, + dialog, handle_resource_destroy); + + dialog->xdg_toplevel = xdg_toplevel; + wlr_addon_init(&dialog->surface_addon, addon_set, NULL, &surface_addon_impl); + + dialog->xdg_toplevel_destroy.notify = handle_xdg_toplevel_destroy; + wl_signal_add(&xdg_toplevel->events.destroy, &dialog->xdg_toplevel_destroy); + + wl_signal_init(&dialog->events.destroy); + wl_signal_init(&dialog->events.set_modal); + + wl_signal_emit_mutable(&wm->events.new_dialog, dialog); +} + +static const struct xdg_wm_dialog_v1_interface wm_impl = { + .destroy = resource_destroy, + .get_xdg_dialog = wm_get_xdg_dialog, +}; + +static void wm_bind(struct wl_client *client, void *data, uint32_t version, uint32_t id) { + struct wlr_xdg_wm_dialog_v1 *wm = data; + struct wl_resource *resource = + wl_resource_create(client, &xdg_wm_dialog_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &wm_impl, wm, NULL); +} + +static void xdg_wm_dialog_v1_destroy(struct wlr_xdg_wm_dialog_v1 *wm, + bool destroy_global_safe) { + wl_signal_emit_mutable(&wm->events.destroy, NULL); + + assert(wl_list_empty(&wm->events.destroy.listener_list)); + assert(wl_list_empty(&wm->events.new_dialog.listener_list)); + + wl_list_remove(&wm->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(wm->global); + } else { + wl_global_destroy(wm->global); + } + free(wm); +} + +void wlr_xdg_wm_dialog_v1_destroy(struct wlr_xdg_wm_dialog_v1 *wm, bool destroy_global_safe) { + xdg_wm_dialog_v1_destroy(wm, destroy_global_safe); +} + +static void xdg_wm_dialog_handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_wm_dialog_v1 *wm = wl_container_of(listener, wm, display_destroy); + xdg_wm_dialog_v1_destroy(wm, false); +} + +struct wlr_xdg_dialog_v1 *wlr_xdg_dialog_v1_try_from_wlr_xdg_toplevel( + struct wlr_xdg_toplevel *xdg_toplevel) { + struct wlr_addon *addon = + wlr_addon_find(&xdg_toplevel->base->surface->addons, NULL, &surface_addon_impl); + if (addon == NULL) { + return NULL; + } + struct wlr_xdg_dialog_v1 *dialog = wl_container_of(addon, dialog, surface_addon); + return dialog; +} + +struct wlr_xdg_wm_dialog_v1 *wlr_xdg_wm_dialog_v1_create(struct wl_display *display, + uint32_t version) { + assert(version <= XDG_WM_DIALOG_V1_VERSION); + + struct wlr_xdg_wm_dialog_v1 *wm = calloc(1, sizeof(*wm)); + if (wm == NULL) { + return NULL; + } + + wm->global = wl_global_create(display, &xdg_wm_dialog_v1_interface, version, wm, wm_bind); + if (wm->global == NULL) { + free(wm); + return NULL; + } + + wm->display_destroy.notify = xdg_wm_dialog_handle_display_destroy; + wl_display_add_destroy_listener(display, &wm->display_destroy); + + wl_signal_init(&wm->events.destroy); + wl_signal_init(&wm->events.new_dialog); + + return wm; +} diff --git a/3rdparty/wlroots/types/wlr_xdg_foreign_registry.c b/3rdparty/wlroots/types/wlr_xdg_foreign_registry.c new file mode 100644 index 0000000000..62dbcc59da --- /dev/null +++ b/3rdparty/wlroots/types/wlr_xdg_foreign_registry.c @@ -0,0 +1,87 @@ +#include +#include "util/token.h" +#include +#include +#include + +bool wlr_xdg_foreign_exported_init( + struct wlr_xdg_foreign_exported *exported, + struct wlr_xdg_foreign_registry *registry) { + do { + if (!generate_token(exported->handle)) { + return false; + } + } while (wlr_xdg_foreign_registry_find_by_handle(registry, exported->handle) != NULL); + + exported->registry = registry; + wl_list_insert(®istry->exported_surfaces, &exported->link); + + wl_signal_init(&exported->events.destroy); + + return true; +} + +struct wlr_xdg_foreign_exported *wlr_xdg_foreign_registry_find_by_handle( + struct wlr_xdg_foreign_registry *registry, const char *handle) { + if (handle == NULL || strlen(handle) >= WLR_XDG_FOREIGN_HANDLE_SIZE) { + return NULL; + } + + struct wlr_xdg_foreign_exported *exported; + wl_list_for_each(exported, ®istry->exported_surfaces, link) { + if (strcmp(handle, exported->handle) == 0) { + return exported; + } + } + + return NULL; +} + +void wlr_xdg_foreign_exported_finish(struct wlr_xdg_foreign_exported *surface) { + wl_signal_emit_mutable(&surface->events.destroy, NULL); + + assert(wl_list_empty(&surface->events.destroy.listener_list)); + + surface->registry = NULL; + wl_list_remove(&surface->link); + wl_list_init(&surface->link); +} + +void wlr_xdg_foreign_registry_destroy(struct wlr_xdg_foreign_registry *registry, + bool destroy_global_safe) { + (void)destroy_global_safe; // The registry has no globals. + + wl_signal_emit_mutable(®istry->events.destroy, NULL); + + assert(wl_list_empty(®istry->events.destroy.listener_list)); + + // Implementations are supposed to remove all surfaces + assert(wl_list_empty(®istry->exported_surfaces)); + wl_list_remove(®istry->display_destroy.link); + free(registry); +} + +static void foreign_registry_handle_display_destroy(struct wl_listener *listener, + void *data) { + struct wlr_xdg_foreign_registry *registry = + wl_container_of(listener, registry, display_destroy); + wlr_xdg_foreign_registry_destroy(registry, false); +} + + +struct wlr_xdg_foreign_registry *wlr_xdg_foreign_registry_create( + struct wl_display *display) { + struct wlr_xdg_foreign_registry *registry = calloc(1, sizeof(*registry)); + if (!registry) { + return NULL; + } + + registry->display_destroy.notify = foreign_registry_handle_display_destroy; + wl_display_add_destroy_listener(display, ®istry->display_destroy); + + wl_list_init(®istry->exported_surfaces); + + wl_signal_init(®istry->events.destroy); + + return registry; +} diff --git a/3rdparty/wlroots/types/wlr_xdg_foreign_v1.c b/3rdparty/wlroots/types/wlr_xdg_foreign_v1.c new file mode 100644 index 0000000000..b4b675bd39 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_xdg_foreign_v1.c @@ -0,0 +1,427 @@ +#include +#include +#include +#include +#include +#include +#include +#include "xdg-foreign-unstable-v1-protocol.h" +#include "util/global.h" + +#define FOREIGN_V1_VERSION 1 + +static const struct zxdg_exported_v1_interface xdg_exported_impl; +static const struct zxdg_imported_v1_interface xdg_imported_impl; +static const struct zxdg_exporter_v1_interface xdg_exporter_impl; +static const struct zxdg_importer_v1_interface xdg_importer_impl; + +static struct wlr_xdg_imported_v1 *xdg_imported_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zxdg_imported_v1_interface, + &xdg_imported_impl)); + return wl_resource_get_user_data(resource); +} + +static void xdg_imported_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static struct wlr_xdg_toplevel *get_toplevel(struct wl_resource *resource, + struct wlr_surface *surface) { + // Note: xdg_surface and xdg_toplevel are never inert, so if this fails, + // the surface isn't a toplevel + struct wlr_xdg_toplevel *toplevel = wlr_xdg_toplevel_try_from_wlr_surface(surface); + if (toplevel == NULL) { + wl_resource_post_error(resource, -1, "surface must be an xdg_toplevel"); + return NULL; + } + + return toplevel; +} + +static void destroy_imported_child(struct wlr_xdg_imported_child_v1 *child) { + wl_list_remove(&child->xdg_toplevel_set_parent.link); + wl_list_remove(&child->xdg_toplevel_destroy.link); + wl_list_remove(&child->link); + free(child); +} + +static void handle_child_xdg_toplevel_destroy( + struct wl_listener *listener, void *data) { + struct wlr_xdg_imported_child_v1 *child = + wl_container_of(listener, child, xdg_toplevel_destroy); + destroy_imported_child(child); +} + +static void handle_child_xdg_toplevel_set_parent( + struct wl_listener *listener, void *data) { + struct wlr_xdg_imported_child_v1 *child = + wl_container_of(listener, child, xdg_toplevel_set_parent); + destroy_imported_child(child); +} + +static void xdg_imported_handle_set_parent_of(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *child_resource) { + struct wlr_xdg_imported_v1 *imported = + xdg_imported_from_resource(resource); + if (imported == NULL) { + return; + } + + struct wlr_xdg_toplevel *toplevel = imported->exported->toplevel; + struct wlr_surface *child_surface = wlr_surface_from_resource(child_resource); + + struct wlr_xdg_toplevel *child_toplevel = get_toplevel(resource, child_surface); + if (!child_toplevel) { + return; + } + + if (!toplevel->base->surface->mapped) { + wlr_xdg_toplevel_set_parent(child_toplevel, NULL); + return; + } + + struct wlr_xdg_imported_child_v1 *child; + wl_list_for_each(child, &imported->children, link) { + if (child->toplevel == child_toplevel) { + return; + } + } + + child = calloc(1, sizeof(*child)); + if (child == NULL) { + wl_client_post_no_memory(client); + return; + } + + child->toplevel = child_toplevel; + child->xdg_toplevel_destroy.notify = handle_child_xdg_toplevel_destroy; + child->xdg_toplevel_set_parent.notify = handle_child_xdg_toplevel_set_parent; + + if (!wlr_xdg_toplevel_set_parent(child_toplevel, toplevel)) { + wl_resource_post_error(toplevel->resource, + XDG_TOPLEVEL_ERROR_INVALID_PARENT, + "a toplevel cannot be a parent of itself or its ancestor"); + free(child); + return; + } + + wl_signal_add(&child_toplevel->events.destroy, &child->xdg_toplevel_destroy); + wl_signal_add(&child_toplevel->events.set_parent, &child->xdg_toplevel_set_parent); + + wl_list_insert(&imported->children, &child->link); +} + +static const struct zxdg_imported_v1_interface xdg_imported_impl = { + .destroy = xdg_imported_handle_destroy, + .set_parent_of = xdg_imported_handle_set_parent_of +}; + +static struct wlr_xdg_exported_v1 *xdg_exported_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zxdg_exported_v1_interface, + &xdg_exported_impl)); + return wl_resource_get_user_data(resource); +} + +static void xdg_exported_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zxdg_exported_v1_interface xdg_exported_impl = { + .destroy = xdg_exported_handle_destroy +}; + +static void xdg_exporter_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static struct wlr_xdg_foreign_v1 *xdg_foreign_from_exporter_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zxdg_exporter_v1_interface, + &xdg_exporter_impl)); + return wl_resource_get_user_data(resource); +} + +static void destroy_imported(struct wlr_xdg_imported_v1 *imported) { + imported->exported = NULL; + struct wlr_xdg_imported_child_v1 *child, *child_tmp; + wl_list_for_each_safe(child, child_tmp, &imported->children, link) { + wlr_xdg_toplevel_set_parent(child->toplevel, NULL); + } + + wl_list_remove(&imported->exported_destroyed.link); + wl_list_init(&imported->exported_destroyed.link); + + wl_list_remove(&imported->link); + wl_list_init(&imported->link); + wl_resource_set_user_data(imported->resource, NULL); + free(imported); +} + +static void destroy_exported(struct wlr_xdg_exported_v1 *exported) { + wlr_xdg_foreign_exported_finish(&exported->base); + + wl_list_remove(&exported->xdg_toplevel_destroy.link); + wl_list_remove(&exported->link); + wl_resource_set_user_data(exported->resource, NULL); + free(exported); +} + +static void xdg_exported_handle_resource_destroy( + struct wl_resource *resource) { + struct wlr_xdg_exported_v1 *exported = + xdg_exported_from_resource(resource); + + if (exported) { + destroy_exported(exported); + } +} + +static void handle_xdg_toplevel_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_exported_v1 *exported = + wl_container_of(listener, exported, xdg_toplevel_destroy); + + destroy_exported(exported); +} + +static void xdg_exporter_handle_export(struct wl_client *wl_client, + struct wl_resource *client_resource, uint32_t id, struct wl_resource *surface_resource) { + struct wlr_xdg_foreign_v1 *foreign = + xdg_foreign_from_exporter_resource(client_resource); + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + + struct wlr_xdg_toplevel *xdg_toplevel = get_toplevel(client_resource, surface); + if (!xdg_toplevel) { + return; + } + + struct wlr_xdg_exported_v1 *exported = calloc(1, sizeof(*exported)); + if (exported == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + + if (!wlr_xdg_foreign_exported_init(&exported->base, foreign->registry)) { + wl_client_post_no_memory(wl_client); + free(exported); + return; + } + + exported->base.toplevel = xdg_toplevel; + exported->resource = wl_resource_create(wl_client, &zxdg_exported_v1_interface, + wl_resource_get_version(client_resource), id); + if (exported->resource == NULL) { + wlr_xdg_foreign_exported_finish(&exported->base); + wl_client_post_no_memory(wl_client); + free(exported); + return; + } + + wl_resource_set_implementation(exported->resource, &xdg_exported_impl, + exported, xdg_exported_handle_resource_destroy); + + wl_list_insert(&foreign->exporter.objects, &exported->link); + + zxdg_exported_v1_send_handle(exported->resource, exported->base.handle); + + exported->xdg_toplevel_destroy.notify = handle_xdg_toplevel_destroy; + wl_signal_add(&xdg_toplevel->base->events.destroy, &exported->xdg_toplevel_destroy); +} + +static const struct zxdg_exporter_v1_interface xdg_exporter_impl = { + .destroy = xdg_exporter_handle_destroy, + .export = xdg_exporter_handle_export +}; + +static void xdg_exporter_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_xdg_foreign_v1 *foreign = data; + + struct wl_resource *exporter_resource = + wl_resource_create(wl_client, &zxdg_exporter_v1_interface, version, id); + if (exporter_resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + + wl_resource_set_implementation(exporter_resource, &xdg_exporter_impl, + foreign, NULL); +} + +static struct wlr_xdg_foreign_v1 *xdg_foreign_from_importer_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zxdg_importer_v1_interface, + &xdg_importer_impl)); + return wl_resource_get_user_data(resource); +} + +static void xdg_importer_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void xdg_imported_handle_resource_destroy( + struct wl_resource *resource) { + struct wlr_xdg_imported_v1 *imported = xdg_imported_from_resource(resource); + if (!imported) { + return; + } + + destroy_imported(imported); +} + +static void xdg_imported_handle_exported_destroy(struct wl_listener *listener, + void *data) { + struct wlr_xdg_imported_v1 *imported = + wl_container_of(listener, imported, exported_destroyed); + zxdg_imported_v1_send_destroyed(imported->resource); + destroy_imported(imported); +} + +static void xdg_importer_handle_import(struct wl_client *wl_client, + struct wl_resource *client_resource, uint32_t id, const char *handle) { + struct wlr_xdg_foreign_v1 *foreign = + xdg_foreign_from_importer_resource(client_resource); + + struct wlr_xdg_imported_v1 *imported = calloc(1, sizeof(*imported)); + if (imported == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + + imported->exported = wlr_xdg_foreign_registry_find_by_handle( + foreign->registry, handle); + imported->resource = wl_resource_create(wl_client, &zxdg_imported_v1_interface, + wl_resource_get_version(client_resource), id); + if (imported->resource == NULL) { + wl_client_post_no_memory(wl_client); + free(imported); + return; + } + + wl_resource_set_implementation(imported->resource, &xdg_imported_impl, + imported, xdg_imported_handle_resource_destroy); + + if (imported->exported == NULL) { + wl_resource_set_user_data(imported->resource, NULL); + zxdg_imported_v1_send_destroyed(imported->resource); + free(imported); + return; + } + + wl_list_init(&imported->children); + wl_list_insert(&foreign->importer.objects, &imported->link); + + imported->exported_destroyed.notify = xdg_imported_handle_exported_destroy; + wl_signal_add(&imported->exported->events.destroy, &imported->exported_destroyed); +} + +static const struct zxdg_importer_v1_interface xdg_importer_impl = { + .destroy = xdg_importer_handle_destroy, + .import = xdg_importer_handle_import +}; + +static void xdg_importer_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_xdg_foreign_v1 *foreign = data; + + struct wl_resource *importer_resource = + wl_resource_create(wl_client, &zxdg_importer_v1_interface, version, id); + + if (importer_resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + + wl_resource_set_implementation(importer_resource, &xdg_importer_impl, + foreign, NULL); +} + +static void xdg_foreign_v1_destroy(struct wlr_xdg_foreign_v1 *foreign, + bool destroy_global_safe) { + if (!foreign) { + return; + } + + wl_signal_emit_mutable(&foreign->events.destroy, NULL); + + assert(wl_list_empty(&foreign->events.destroy.listener_list)); + + wl_list_remove(&foreign->foreign_registry_destroy.link); + wl_list_remove(&foreign->display_destroy.link); + + if (destroy_global_safe) { + wlr_global_destroy_safe(foreign->exporter.global); + } else { + wl_global_destroy(foreign->exporter.global); + } + if (destroy_global_safe) { + wlr_global_destroy_safe(foreign->importer.global); + } else { + wl_global_destroy(foreign->importer.global); + } + free(foreign); +} + +void wlr_xdg_foreign_v1_destroy(struct wlr_xdg_foreign_v1 *foreign, bool destroy_global_safe) { + xdg_foreign_v1_destroy(foreign, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_foreign_v1 *foreign = + wl_container_of(listener, foreign, display_destroy); + xdg_foreign_v1_destroy(foreign, false); +} + +static void handle_foreign_registry_destroy(struct wl_listener *listener, + void *data) { + struct wlr_xdg_foreign_v1 *foreign = + wl_container_of(listener, foreign, foreign_registry_destroy); + wlr_xdg_foreign_v1_destroy(foreign, true); +} + +struct wlr_xdg_foreign_v1 *wlr_xdg_foreign_v1_create( + struct wl_display *display, struct wlr_xdg_foreign_registry *registry) { + struct wlr_xdg_foreign_v1 *foreign = calloc(1, sizeof(*foreign)); + if (!foreign) { + return NULL; + } + + foreign->exporter.global = wl_global_create(display, + &zxdg_exporter_v1_interface, + FOREIGN_V1_VERSION, foreign, + xdg_exporter_bind); + if (!foreign->exporter.global) { + free(foreign); + return NULL; + } + + foreign->importer.global = wl_global_create(display, + &zxdg_importer_v1_interface, + FOREIGN_V1_VERSION, foreign, + xdg_importer_bind); + if (!foreign->importer.global) { + wl_global_destroy(foreign->exporter.global); + free(foreign); + return NULL; + } + + foreign->registry = registry; + + wl_signal_init(&foreign->events.destroy); + + wl_list_init(&foreign->exporter.objects); + wl_list_init(&foreign->importer.objects); + + foreign->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &foreign->display_destroy); + + foreign->foreign_registry_destroy.notify = handle_foreign_registry_destroy; + wl_signal_add(®istry->events.destroy, &foreign->foreign_registry_destroy); + + return foreign; +} diff --git a/3rdparty/wlroots/types/wlr_xdg_foreign_v2.c b/3rdparty/wlroots/types/wlr_xdg_foreign_v2.c new file mode 100644 index 0000000000..931e49c444 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_xdg_foreign_v2.c @@ -0,0 +1,429 @@ +#include +#include +#include +#include +#include +#include +#include +#include "xdg-foreign-unstable-v2-protocol.h" +#include "util/global.h" + +#define FOREIGN_V2_VERSION 1 + +static const struct zxdg_exported_v2_interface xdg_exported_impl; +static const struct zxdg_imported_v2_interface xdg_imported_impl; +static const struct zxdg_exporter_v2_interface xdg_exporter_impl; +static const struct zxdg_importer_v2_interface xdg_importer_impl; + +static struct wlr_xdg_imported_v2 *xdg_imported_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zxdg_imported_v2_interface, + &xdg_imported_impl)); + return wl_resource_get_user_data(resource); +} + +static void xdg_imported_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static struct wlr_xdg_toplevel *get_toplevel(struct wl_resource *resource, + struct wlr_surface *surface) { + // Note: xdg_surface and xdg_toplevel are never inert, so if this fails, + // the surface isn't a toplevel + struct wlr_xdg_toplevel *toplevel = wlr_xdg_toplevel_try_from_wlr_surface(surface); + if (toplevel == NULL) { + // Note: the error codes are the same for zxdg_exporter_v2 and + // zxdg_importer_v2 + wl_resource_post_error(resource, ZXDG_EXPORTER_V2_ERROR_INVALID_SURFACE, + "surface must be an xdg_toplevel"); + return NULL; + } + + return toplevel; +} + +static void destroy_imported_child(struct wlr_xdg_imported_child_v2 *child) { + wl_list_remove(&child->xdg_toplevel_set_parent.link); + wl_list_remove(&child->xdg_toplevel_destroy.link); + wl_list_remove(&child->link); + free(child); +} + +static void handle_child_xdg_toplevel_destroy( + struct wl_listener *listener, void *data) { + struct wlr_xdg_imported_child_v2 *child = + wl_container_of(listener, child, xdg_toplevel_destroy); + destroy_imported_child(child); +} + +static void handle_child_xdg_toplevel_set_parent( + struct wl_listener *listener, void *data) { + struct wlr_xdg_imported_child_v2 *child = + wl_container_of(listener, child, xdg_toplevel_set_parent); + destroy_imported_child(child); +} + +static void xdg_imported_handle_set_parent_of(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *child_resource) { + struct wlr_xdg_imported_v2 *imported = + xdg_imported_from_resource(resource); + if (imported == NULL) { + return; + } + + struct wlr_xdg_toplevel *toplevel = imported->exported->toplevel; + struct wlr_surface *child_surface = wlr_surface_from_resource(child_resource); + + struct wlr_xdg_toplevel *child_toplevel = get_toplevel(resource, child_surface); + if (!child_toplevel) { + return; + } + + if (!toplevel->base->surface->mapped) { + wlr_xdg_toplevel_set_parent(child_toplevel, NULL); + return; + } + + struct wlr_xdg_imported_child_v2 *child; + wl_list_for_each(child, &imported->children, link) { + if (child->toplevel == child_toplevel) { + return; + } + } + + child = calloc(1, sizeof(*child)); + if (child == NULL) { + wl_client_post_no_memory(client); + return; + } + child->toplevel = child_toplevel; + child->xdg_toplevel_destroy.notify = handle_child_xdg_toplevel_destroy; + child->xdg_toplevel_set_parent.notify = handle_child_xdg_toplevel_set_parent; + + if (!wlr_xdg_toplevel_set_parent(child_toplevel, toplevel)) { + wl_resource_post_error(toplevel->resource, + XDG_TOPLEVEL_ERROR_INVALID_PARENT, + "a toplevel cannot be a parent of itself or its ancestor"); + free(child); + return; + } + + wl_signal_add(&child_toplevel->events.destroy, &child->xdg_toplevel_destroy); + wl_signal_add(&child_toplevel->events.set_parent, &child->xdg_toplevel_set_parent); + + wl_list_insert(&imported->children, &child->link); +} + +static const struct zxdg_imported_v2_interface xdg_imported_impl = { + .destroy = xdg_imported_handle_destroy, + .set_parent_of = xdg_imported_handle_set_parent_of +}; + +static struct wlr_xdg_exported_v2 *xdg_exported_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zxdg_exported_v2_interface, + &xdg_exported_impl)); + return wl_resource_get_user_data(resource); +} + +static void xdg_exported_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zxdg_exported_v2_interface xdg_exported_impl = { + .destroy = xdg_exported_handle_destroy +}; + +static void xdg_exporter_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static struct wlr_xdg_foreign_v2 *xdg_foreign_from_exporter_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zxdg_exporter_v2_interface, + &xdg_exporter_impl)); + return wl_resource_get_user_data(resource); +} + +static void destroy_imported(struct wlr_xdg_imported_v2 *imported) { + imported->exported = NULL; + struct wlr_xdg_imported_child_v2 *child, *child_tmp; + wl_list_for_each_safe(child, child_tmp, &imported->children, link) { + wlr_xdg_toplevel_set_parent(child->toplevel, NULL); + } + + wl_list_remove(&imported->exported_destroyed.link); + wl_list_init(&imported->exported_destroyed.link); + + wl_list_remove(&imported->link); + wl_list_init(&imported->link); + wl_resource_set_user_data(imported->resource, NULL); + free(imported); +} + +static void destroy_exported(struct wlr_xdg_exported_v2 *exported) { + wlr_xdg_foreign_exported_finish(&exported->base); + + wl_list_remove(&exported->xdg_toplevel_destroy.link); + wl_list_remove(&exported->link); + wl_resource_set_user_data(exported->resource, NULL); + free(exported); +} + +static void xdg_exported_handle_resource_destroy( + struct wl_resource *resource) { + struct wlr_xdg_exported_v2 *exported = + xdg_exported_from_resource(resource); + + if (exported) { + destroy_exported(exported); + } +} + +static void handle_xdg_toplevel_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_exported_v2 *exported = + wl_container_of(listener, exported, xdg_toplevel_destroy); + + destroy_exported(exported); +} + +static void xdg_exporter_handle_export(struct wl_client *wl_client, + struct wl_resource *client_resource, uint32_t id, struct wl_resource *surface_resource) { + struct wlr_xdg_foreign_v2 *foreign = + xdg_foreign_from_exporter_resource(client_resource); + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + + struct wlr_xdg_toplevel *xdg_toplevel = get_toplevel(client_resource, surface); + if (!xdg_toplevel) { + return; + } + + struct wlr_xdg_exported_v2 *exported = calloc(1, sizeof(*exported)); + if (exported == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + + if (!wlr_xdg_foreign_exported_init(&exported->base, foreign->registry)) { + wl_client_post_no_memory(wl_client); + free(exported); + return; + } + + exported->base.toplevel = xdg_toplevel; + exported->resource = wl_resource_create(wl_client, &zxdg_exported_v2_interface, + wl_resource_get_version(client_resource), id); + if (exported->resource == NULL) { + wlr_xdg_foreign_exported_finish(&exported->base); + wl_client_post_no_memory(wl_client); + free(exported); + return; + } + + wl_resource_set_implementation(exported->resource, &xdg_exported_impl, + exported, xdg_exported_handle_resource_destroy); + + wl_list_insert(&foreign->exporter.objects, &exported->link); + + zxdg_exported_v2_send_handle(exported->resource, exported->base.handle); + + exported->xdg_toplevel_destroy.notify = handle_xdg_toplevel_destroy; + wl_signal_add(&xdg_toplevel->base->events.destroy, &exported->xdg_toplevel_destroy); +} + +static const struct zxdg_exporter_v2_interface xdg_exporter_impl = { + .destroy = xdg_exporter_handle_destroy, + .export_toplevel = xdg_exporter_handle_export +}; + +static void xdg_exporter_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_xdg_foreign_v2 *foreign = data; + + struct wl_resource *exporter_resource = + wl_resource_create(wl_client, &zxdg_exporter_v2_interface, version, id); + if (exporter_resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + + wl_resource_set_implementation(exporter_resource, &xdg_exporter_impl, + foreign, NULL); +} + +static struct wlr_xdg_foreign_v2 *xdg_foreign_from_importer_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &zxdg_importer_v2_interface, + &xdg_importer_impl)); + return wl_resource_get_user_data(resource); +} + +static void xdg_importer_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void xdg_imported_handle_resource_destroy( + struct wl_resource *resource) { + struct wlr_xdg_imported_v2 *imported = xdg_imported_from_resource(resource); + if (!imported) { + return; + } + + destroy_imported(imported); +} + +static void xdg_imported_handle_exported_destroy(struct wl_listener *listener, + void *data) { + struct wlr_xdg_imported_v2 *imported = + wl_container_of(listener, imported, exported_destroyed); + zxdg_imported_v2_send_destroyed(imported->resource); + destroy_imported(imported); +} + +static void xdg_importer_handle_import(struct wl_client *wl_client, + struct wl_resource *client_resource, uint32_t id, const char *handle) { + struct wlr_xdg_foreign_v2 *foreign = + xdg_foreign_from_importer_resource(client_resource); + + struct wlr_xdg_imported_v2 *imported = calloc(1, sizeof(*imported)); + if (imported == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + + imported->exported = wlr_xdg_foreign_registry_find_by_handle( + foreign->registry, handle); + imported->resource = wl_resource_create(wl_client, &zxdg_imported_v2_interface, + wl_resource_get_version(client_resource), id); + if (imported->resource == NULL) { + wl_client_post_no_memory(wl_client); + free(imported); + return; + } + + wl_resource_set_implementation(imported->resource, &xdg_imported_impl, + imported, xdg_imported_handle_resource_destroy); + + if (imported->exported == NULL) { + wl_resource_set_user_data(imported->resource, NULL); + zxdg_imported_v2_send_destroyed(imported->resource); + free(imported); + return; + } + + wl_list_init(&imported->children); + wl_list_insert(&foreign->importer.objects, &imported->link); + + imported->exported_destroyed.notify = xdg_imported_handle_exported_destroy; + wl_signal_add(&imported->exported->events.destroy, &imported->exported_destroyed); +} + +static const struct zxdg_importer_v2_interface xdg_importer_impl = { + .destroy = xdg_importer_handle_destroy, + .import_toplevel = xdg_importer_handle_import +}; + +static void xdg_importer_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_xdg_foreign_v2 *foreign = data; + + struct wl_resource *importer_resource = + wl_resource_create(wl_client, &zxdg_importer_v2_interface, version, id); + + if (importer_resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + + wl_resource_set_implementation(importer_resource, &xdg_importer_impl, + foreign, NULL); +} + +static void xdg_foreign_v2_destroy(struct wlr_xdg_foreign_v2 *foreign, + bool destroy_global_safe) { + if (!foreign) { + return; + } + + wl_signal_emit_mutable(&foreign->events.destroy, NULL); + + assert(wl_list_empty(&foreign->events.destroy.listener_list)); + + wl_list_remove(&foreign->foreign_registry_destroy.link); + wl_list_remove(&foreign->display_destroy.link); + + if (destroy_global_safe) { + wlr_global_destroy_safe(foreign->exporter.global); + } else { + wl_global_destroy(foreign->exporter.global); + } + if (destroy_global_safe) { + wlr_global_destroy_safe(foreign->importer.global); + } else { + wl_global_destroy(foreign->importer.global); + } + free(foreign); +} + +void wlr_xdg_foreign_v2_destroy(struct wlr_xdg_foreign_v2 *foreign, bool destroy_global_safe) { + xdg_foreign_v2_destroy(foreign, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_foreign_v2 *foreign = + wl_container_of(listener, foreign, display_destroy); + xdg_foreign_v2_destroy(foreign, false); +} + +static void handle_foreign_registry_destroy(struct wl_listener *listener, + void *data) { + struct wlr_xdg_foreign_v2 *foreign = + wl_container_of(listener, foreign, foreign_registry_destroy); + wlr_xdg_foreign_v2_destroy(foreign, true); +} + +struct wlr_xdg_foreign_v2 *wlr_xdg_foreign_v2_create( + struct wl_display *display, struct wlr_xdg_foreign_registry *registry) { + struct wlr_xdg_foreign_v2 *foreign = calloc(1, sizeof(*foreign)); + if (!foreign) { + return NULL; + } + + foreign->exporter.global = wl_global_create(display, + &zxdg_exporter_v2_interface, + FOREIGN_V2_VERSION, foreign, + xdg_exporter_bind); + if (!foreign->exporter.global) { + free(foreign); + return NULL; + } + + foreign->importer.global = wl_global_create(display, + &zxdg_importer_v2_interface, + FOREIGN_V2_VERSION, foreign, + xdg_importer_bind); + if (!foreign->importer.global) { + wl_global_destroy(foreign->exporter.global); + free(foreign); + return NULL; + } + + foreign->registry = registry; + + wl_signal_init(&foreign->events.destroy); + + wl_list_init(&foreign->exporter.objects); + wl_list_init(&foreign->importer.objects); + + foreign->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &foreign->display_destroy); + + foreign->foreign_registry_destroy.notify = handle_foreign_registry_destroy; + wl_signal_add(®istry->events.destroy, &foreign->foreign_registry_destroy); + + return foreign; +} diff --git a/3rdparty/wlroots/types/wlr_xdg_output_v1.c b/3rdparty/wlroots/types/wlr_xdg_output_v1.c new file mode 100644 index 0000000000..ea781c05cd --- /dev/null +++ b/3rdparty/wlroots/types/wlr_xdg_output_v1.c @@ -0,0 +1,308 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "xdg-output-unstable-v1-protocol.h" +#include "util/global.h" + +#define OUTPUT_MANAGER_VERSION 3 +#define OUTPUT_DONE_DEPRECATED_SINCE_VERSION 3 +#define OUTPUT_DESCRIPTION_MUTABLE_SINCE_VERSION 3 + +static void output_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zxdg_output_v1_interface output_implementation = { + .destroy = output_handle_destroy, +}; + +static void output_handle_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void output_send_details(struct wlr_xdg_output_v1 *xdg_output, + struct wl_resource *resource) { + zxdg_output_v1_send_logical_position(resource, + xdg_output->x, xdg_output->y); + zxdg_output_v1_send_logical_size(resource, + xdg_output->width, xdg_output->height); + if (wl_resource_get_version(resource) < OUTPUT_DONE_DEPRECATED_SINCE_VERSION) { + zxdg_output_v1_send_done(resource); + } +} + +static void output_update(struct wlr_xdg_output_v1 *xdg_output) { + struct wlr_output_layout_output *layout_output = xdg_output->layout_output; + bool updated = false; + + if (layout_output->x != xdg_output->x || layout_output->y != xdg_output->y) { + xdg_output->x = layout_output->x; + xdg_output->y = layout_output->y; + updated = true; + } + + int width, height; + wlr_output_effective_resolution(layout_output->output, &width, &height); + if (xdg_output->width != width || xdg_output->height != height) { + xdg_output->width = width; + xdg_output->height = height; + updated = true; + } + + if (updated) { + struct wl_resource *resource; + wl_resource_for_each(resource, &xdg_output->resources) { + output_send_details(xdg_output, resource); + } + + wlr_output_schedule_done(xdg_output->layout_output->output); + } +} + +static void output_destroy(struct wlr_xdg_output_v1 *output) { + struct wl_resource *resource, *tmp; + wl_resource_for_each_safe(resource, tmp, &output->resources) { + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + } + wl_list_remove(&output->destroy.link); + wl_list_remove(&output->description.link); + wl_list_remove(&output->link); + free(output); +} + + +static void output_manager_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct zxdg_output_manager_v1_interface + output_manager_implementation; + +static void output_manager_handle_get_xdg_output(struct wl_client *client, + struct wl_resource *resource, uint32_t id, + struct wl_resource *output_resource) { + assert(wl_resource_instance_of(resource, &zxdg_output_manager_v1_interface, + &output_manager_implementation)); + + struct wlr_xdg_output_manager_v1 *manager = + wl_resource_get_user_data(resource); + struct wlr_output_layout *layout = manager->layout; + struct wlr_output *output = wlr_output_from_resource(output_resource); + + struct wl_resource *xdg_output_resource = wl_resource_create(client, + &zxdg_output_v1_interface, wl_resource_get_version(resource), id); + if (!xdg_output_resource) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(xdg_output_resource, &output_implementation, + NULL, output_handle_resource_destroy); + + if (output == NULL) { + wl_list_init(wl_resource_get_link(xdg_output_resource)); + return; + } + + struct wlr_output_layout_output *layout_output = + wlr_output_layout_get(layout, output); + assert(layout_output); + + struct wlr_xdg_output_v1 *_xdg_output, *xdg_output = NULL; + wl_list_for_each(_xdg_output, &manager->outputs, link) { + if (_xdg_output->layout_output == layout_output) { + xdg_output = _xdg_output; + break; + } + } + assert(xdg_output); + + + wl_list_insert(&xdg_output->resources, + wl_resource_get_link(xdg_output_resource)); + + // Name and description should only be sent once per output + uint32_t xdg_version = wl_resource_get_version(xdg_output_resource); + if (xdg_version >= ZXDG_OUTPUT_V1_NAME_SINCE_VERSION) { + zxdg_output_v1_send_name(xdg_output_resource, output->name); + } + if (xdg_version >= ZXDG_OUTPUT_V1_DESCRIPTION_SINCE_VERSION && + output->description != NULL) { + zxdg_output_v1_send_description(xdg_output_resource, + output->description); + } + + output_send_details(xdg_output, xdg_output_resource); + + uint32_t wl_version = wl_resource_get_version(output_resource); + if (wl_version >= WL_OUTPUT_DONE_SINCE_VERSION && + xdg_version >= OUTPUT_DONE_DEPRECATED_SINCE_VERSION) { + wl_output_send_done(output_resource); + } +} + +static const struct zxdg_output_manager_v1_interface + output_manager_implementation = { + .destroy = output_manager_handle_destroy, + .get_xdg_output = output_manager_handle_get_xdg_output, +}; + +static void output_manager_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_xdg_output_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(wl_client, + &zxdg_output_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + wl_resource_set_implementation(resource, &output_manager_implementation, + manager, NULL); +} + +static void handle_output_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_output_v1 *output = wl_container_of(listener, output, destroy); + output_destroy(output); +} + +static void handle_output_description(struct wl_listener *listener, + void *data) { + struct wlr_xdg_output_v1 *xdg_output = + wl_container_of(listener, xdg_output, description); + struct wlr_output *output = xdg_output->layout_output->output; + + if (output->description == NULL) { + return; + } + + struct wl_resource *resource; + wl_resource_for_each(resource, &xdg_output->resources) { + if (wl_resource_get_version(resource) >= + OUTPUT_DESCRIPTION_MUTABLE_SINCE_VERSION) { + zxdg_output_v1_send_description(resource, output->description); + } + } +} + +static void add_output(struct wlr_xdg_output_manager_v1 *manager, + struct wlr_output_layout_output *layout_output) { + struct wlr_xdg_output_v1 *output = calloc(1, sizeof(*output)); + if (output == NULL) { + return; + } + wl_list_init(&output->resources); + output->manager = manager; + output->layout_output = layout_output; + output->destroy.notify = handle_output_destroy; + wl_signal_add(&layout_output->events.destroy, &output->destroy); + output->description.notify = handle_output_description; + wl_signal_add(&layout_output->output->events.description, + &output->description); + wl_list_insert(&manager->outputs, &output->link); + output_update(output); +} + +static void output_manager_send_details( + struct wlr_xdg_output_manager_v1 *manager) { + struct wlr_xdg_output_v1 *output; + wl_list_for_each(output, &manager->outputs, link) { + output_update(output); + } +} + +static void handle_layout_add(struct wl_listener *listener, void *data) { + struct wlr_xdg_output_manager_v1 *manager = + wl_container_of(listener, manager, layout_add); + struct wlr_output_layout_output *layout_output = data; + add_output(manager, layout_output); +} + +static void handle_layout_change(struct wl_listener *listener, void *data) { + struct wlr_xdg_output_manager_v1 *manager = + wl_container_of(listener, manager, layout_change); + output_manager_send_details(manager); +} + +static void xdg_output_manager_v1_destroy(struct wlr_xdg_output_manager_v1 *manager, + bool destroy_global_safe) { + struct wlr_xdg_output_v1 *output, *tmp; + wl_list_for_each_safe(output, tmp, &manager->outputs, link) { + output_destroy(output); + } + + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + wl_list_remove(&manager->layout_add.link); + wl_list_remove(&manager->layout_change.link); + wl_list_remove(&manager->layout_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_xdg_output_manager_v1_destroy(struct wlr_xdg_output_manager_v1 *manager, + bool destroy_global_safe) { + xdg_output_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_layout_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_output_manager_v1 *manager = + wl_container_of(listener, manager, layout_destroy); + wlr_xdg_output_manager_v1_destroy(manager, true); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_output_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + xdg_output_manager_v1_destroy(manager, false); +} + +struct wlr_xdg_output_manager_v1 *wlr_xdg_output_manager_v1_create( + struct wl_display *display, struct wlr_output_layout *layout) { + struct wlr_xdg_output_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + manager->layout = layout; + manager->global = wl_global_create(display, + &zxdg_output_manager_v1_interface, OUTPUT_MANAGER_VERSION, manager, + output_manager_bind); + if (!manager->global) { + free(manager); + return NULL; + } + + wl_list_init(&manager->outputs); + struct wlr_output_layout_output *layout_output; + wl_list_for_each(layout_output, &layout->outputs, link) { + add_output(manager, layout_output); + } + + wl_signal_init(&manager->events.destroy); + + manager->layout_add.notify = handle_layout_add; + wl_signal_add(&layout->events.add, &manager->layout_add); + manager->layout_change.notify = handle_layout_change; + wl_signal_add(&layout->events.change, &manager->layout_change); + manager->layout_destroy.notify = handle_layout_destroy; + wl_signal_add(&layout->events.destroy, &manager->layout_destroy); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_xdg_system_bell_v1.c b/3rdparty/wlroots/types/wlr_xdg_system_bell_v1.c new file mode 100644 index 0000000000..9903d9bc25 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_xdg_system_bell_v1.c @@ -0,0 +1,104 @@ +#include +#include +#include +#include +#include +#include "xdg-system-bell-v1-protocol.h" +#include "util/global.h" + +#define XDG_SYSTEM_BELL_V1_VERSION 1 + +static const struct xdg_system_bell_v1_interface bell_impl; + +static struct wlr_xdg_system_bell_v1 *bell_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &xdg_system_bell_v1_interface, &bell_impl)); + return wl_resource_get_user_data(resource); +} + +static void bell_handle_destroy(struct wl_client *client, struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void bell_handle_ring(struct wl_client *client, + struct wl_resource *bell_resource, struct wl_resource *surface_resource) { + struct wlr_xdg_system_bell_v1 *bell = bell_from_resource(bell_resource); + + struct wlr_surface *surface = NULL; + if (surface_resource != NULL) { + surface = wlr_surface_from_resource(surface_resource); + } + + struct wlr_xdg_system_bell_v1_ring_event event = { + .client = client, + .surface = surface, + }; + wl_signal_emit_mutable(&bell->events.ring, &event); +} + +static const struct xdg_system_bell_v1_interface bell_impl = { + .destroy = bell_handle_destroy, + .ring = bell_handle_ring, +}; + +static void bell_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_xdg_system_bell_v1 *bell = data; + + struct wl_resource *resource = wl_resource_create(client, + &xdg_system_bell_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &bell_impl, bell, NULL); +} + +static void xdg_system_bell_v1_destroy(struct wlr_xdg_system_bell_v1 *bell, + bool destroy_global_safe) { + wl_signal_emit_mutable(&bell->events.destroy, NULL); + + assert(wl_list_empty(&bell->events.destroy.listener_list)); + assert(wl_list_empty(&bell->events.ring.listener_list)); + + wl_list_remove(&bell->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(bell->global); + } else { + wl_global_destroy(bell->global); + } + free(bell); +} + +void wlr_xdg_system_bell_v1_destroy(struct wlr_xdg_system_bell_v1 *bell, bool destroy_global_safe) { + xdg_system_bell_v1_destroy(bell, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_system_bell_v1 *bell = wl_container_of(listener, bell, display_destroy); + xdg_system_bell_v1_destroy(bell, false); +} + +struct wlr_xdg_system_bell_v1 *wlr_xdg_system_bell_v1_create(struct wl_display *display, + uint32_t version) { + assert(version <= XDG_SYSTEM_BELL_V1_VERSION); + + struct wlr_xdg_system_bell_v1 *bell = calloc(1, sizeof(*bell)); + if (bell == NULL) { + return NULL; + } + + bell->global = wl_global_create(display, &xdg_system_bell_v1_interface, + version, bell, bell_bind); + if (bell->global == NULL) { + free(bell); + return NULL; + } + + bell->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &bell->display_destroy); + + wl_signal_init(&bell->events.destroy); + wl_signal_init(&bell->events.ring); + + return bell; +} diff --git a/3rdparty/wlroots/types/wlr_xdg_toplevel_icon_v1.c b/3rdparty/wlroots/types/wlr_xdg_toplevel_icon_v1.c new file mode 100644 index 0000000000..f64c03cf6d --- /dev/null +++ b/3rdparty/wlroots/types/wlr_xdg_toplevel_icon_v1.c @@ -0,0 +1,316 @@ +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include "xdg-toplevel-icon-v1-protocol.h" +#include "util/global.h" + +#define MANAGER_VERSION 1 + +static const struct xdg_toplevel_icon_v1_interface icon_impl; + +static struct wlr_xdg_toplevel_icon_v1 *icon_from_resource(struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &xdg_toplevel_icon_v1_interface, &icon_impl)); + return wl_resource_get_user_data(resource); +} + +static void icon_destroy(struct wlr_xdg_toplevel_icon_v1 *icon) { + struct wlr_xdg_toplevel_icon_v1_buffer *icon_buffer, *tmp; + wl_list_for_each_safe(icon_buffer, tmp, &icon->buffers, link) { + wlr_buffer_unlock(icon_buffer->buffer); + wl_list_remove(&icon_buffer->link); + free(icon_buffer); + } + + free(icon->name); + free(icon); +} + +static void icon_handle_destroy(struct wl_client *client, struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void icon_handle_set_name(struct wl_client *client, struct wl_resource *resource, + const char *name) { + struct wlr_xdg_toplevel_icon_v1 *icon = icon_from_resource(resource); + if (icon->immutable) { + wl_resource_post_error(resource, XDG_TOPLEVEL_ICON_V1_ERROR_IMMUTABLE, + "the icon has already been assigned to a toplevel and must not be changed"); + return; + } + + char *dup = strdup(name); + if (dup == NULL) { + wl_resource_post_no_memory(resource); + return; + } + + free(icon->name); + icon->name = dup; +} + +static void icon_handle_add_buffer(struct wl_client *client, struct wl_resource *resource, + struct wl_resource *buffer_resource, int32_t scale) { + struct wlr_xdg_toplevel_icon_v1 *icon = icon_from_resource(resource); + if (icon->immutable) { + wl_resource_post_error(resource, XDG_TOPLEVEL_ICON_V1_ERROR_IMMUTABLE, + "the icon has already been assigned to a toplevel and must not be changed"); + return; + } + + struct wlr_buffer *buffer = wlr_buffer_try_from_resource(buffer_resource); + + const char *bad_buffer_msg = NULL; + + struct wlr_shm_attributes shm_attribs; + if (!wlr_buffer_get_shm(buffer, &shm_attribs)) { + bad_buffer_msg = "not backed by wl_shm"; + } else if (buffer->width != buffer->height) { + bad_buffer_msg = "not square"; + } + + if (bad_buffer_msg != NULL) { + wl_resource_post_error(resource, XDG_TOPLEVEL_ICON_V1_ERROR_INVALID_BUFFER, + "the provided buffer does not satisfy requirements: %s", bad_buffer_msg); + wlr_buffer_unlock(buffer); + return; + } + + struct wlr_xdg_toplevel_icon_v1_buffer *icon_buffer; + wl_list_for_each(icon_buffer, &icon->buffers, link) { + if (icon_buffer->buffer->width == buffer->width && icon_buffer->scale == scale) { + wlr_buffer_unlock(icon_buffer->buffer); + icon_buffer->buffer = buffer; + return; + } + } + + icon_buffer = calloc(1, sizeof(*icon_buffer)); + if (icon_buffer == NULL) { + wl_resource_post_no_memory(resource); + } + + icon_buffer->buffer = buffer; + icon_buffer->scale = scale; + + wl_list_insert(&icon->buffers, &icon_buffer->link); +} + +static const struct xdg_toplevel_icon_v1_interface icon_impl = { + .destroy = icon_handle_destroy, + .set_name = icon_handle_set_name, + .add_buffer = icon_handle_add_buffer, +}; + +static void icon_handle_resource_destroy(struct wl_resource *resource) { + wlr_xdg_toplevel_icon_v1_unref(icon_from_resource(resource)); +} + +struct wlr_xdg_toplevel_icon_v1 *wlr_xdg_toplevel_icon_v1_ref( + struct wlr_xdg_toplevel_icon_v1 *icon) { + ++icon->n_refs; + return icon; +} + +void wlr_xdg_toplevel_icon_v1_unref(struct wlr_xdg_toplevel_icon_v1 *icon) { + if (icon == NULL) { + return; + } + + assert(icon->n_refs > 0); + --icon->n_refs; + if (icon->n_refs == 0) { + icon_destroy(icon); + }; +} + +static const struct xdg_toplevel_icon_manager_v1_interface manager_impl; + +static struct wlr_xdg_toplevel_icon_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &xdg_toplevel_icon_manager_v1_interface, + &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void manager_handle_destroy(struct wl_client *client, struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void manager_handle_create_icon(struct wl_client *client, struct wl_resource *resource, + uint32_t id) { + struct wlr_xdg_toplevel_icon_v1 *icon = calloc(1, sizeof(*icon)); + if (icon == NULL) { + wl_client_post_no_memory(client); + return; + } + + struct wl_resource *icon_resource = wl_resource_create(client, + &xdg_toplevel_icon_v1_interface, wl_resource_get_version(resource), id); + if (icon_resource == NULL) { + wl_client_post_no_memory(client); + free(icon); + return; + } + + wl_list_init(&icon->buffers); + icon->n_refs = 1; + + wl_resource_set_implementation(icon_resource, &icon_impl, icon, icon_handle_resource_destroy); +} + +static void manager_handle_set_icon(struct wl_client *client, struct wl_resource *resource, + struct wl_resource *toplevel_resource, struct wl_resource *icon_resource) { + struct wlr_xdg_toplevel_icon_manager_v1 *manager = manager_from_resource(resource); + struct wlr_xdg_toplevel *toplevel = wlr_xdg_toplevel_from_resource(toplevel_resource); + + struct wlr_xdg_toplevel_icon_v1 *icon = NULL; + if (icon_resource != NULL) { + icon = icon_from_resource(icon_resource); + icon->immutable = true; + + if (icon->name == NULL && wl_list_empty(&icon->buffers)) { + // Same as supplying null icon + icon = NULL; + } + } + + struct wlr_xdg_toplevel_icon_manager_v1_set_icon_event event = { + .toplevel = toplevel, + .icon = icon, + }; + + wl_signal_emit_mutable(&manager->events.set_icon, &event); +} + +static const struct xdg_toplevel_icon_manager_v1_interface manager_impl = { + .destroy = manager_handle_destroy, + .create_icon = manager_handle_create_icon, + .set_icon = manager_handle_set_icon, +}; + +static void manager_send_sizes(struct wlr_xdg_toplevel_icon_manager_v1 *manager, + struct wl_resource *resource) { + for (size_t i = 0; i < manager->n_sizes; i++) { + xdg_toplevel_icon_manager_v1_send_icon_size(resource, manager->sizes[i]); + } + xdg_toplevel_icon_manager_v1_send_done(resource); +} + +static void manager_handle_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void manager_bind(struct wl_client *client, void *data, uint32_t version, uint32_t id) { + struct wlr_xdg_toplevel_icon_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &xdg_toplevel_icon_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, manager, manager_handle_resource_destroy); + wl_list_init(wl_resource_get_link(resource)); + if (manager == NULL) { + return; + } + + + wl_list_insert(&manager->resources, wl_resource_get_link(resource)); + + manager_send_sizes(manager, resource); +} + +static void xdg_toplevel_icon_manager_v1_destroy(struct wlr_xdg_toplevel_icon_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, NULL); + + assert(wl_list_empty(&manager->events.set_icon.listener_list)); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + + wl_list_remove(&manager->resources); + + free(manager->sizes); + free(manager); +} + +void wlr_xdg_toplevel_icon_manager_v1_destroy(struct wlr_xdg_toplevel_icon_manager_v1 *manager, + bool destroy_global_safe) { + xdg_toplevel_icon_manager_v1_destroy(manager, destroy_global_safe); +} + +static void manager_handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_toplevel_icon_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + xdg_toplevel_icon_manager_v1_destroy(manager, false); +} + +void wlr_xdg_toplevel_icon_manager_v1_set_sizes(struct wlr_xdg_toplevel_icon_manager_v1 *manager, + int *sizes, size_t n_sizes) { + if (n_sizes != manager->n_sizes) { + int *dup_sizes = NULL; + if (n_sizes > 0) { + dup_sizes = calloc(n_sizes, sizeof(*dup_sizes)); + if (dup_sizes == NULL) { + wlr_log(WLR_ERROR, "Allocation failed"); + return; + } + } + + free(manager->sizes); + manager->sizes = dup_sizes; + manager->n_sizes = n_sizes; + } + + for (size_t i = 0; i < n_sizes; i++) { + manager->sizes[i] = sizes[i]; + } + + struct wl_resource *resource; + wl_resource_for_each(resource, &manager->resources) { + manager_send_sizes(manager, resource); + } +} + +struct wlr_xdg_toplevel_icon_manager_v1 *wlr_xdg_toplevel_icon_manager_v1_create( + struct wl_display *display, uint32_t version) { + assert(version <= MANAGER_VERSION); + + struct wlr_xdg_toplevel_icon_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + manager->global = wl_global_create(display, &xdg_toplevel_icon_manager_v1_interface, + version, manager, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + wl_signal_init(&manager->events.set_icon); + wl_signal_init(&manager->events.destroy); + + wl_list_init(&manager->resources); + + manager->display_destroy.notify = manager_handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/wlr_xdg_toplevel_tag_v1.c b/3rdparty/wlroots/types/wlr_xdg_toplevel_tag_v1.c new file mode 100644 index 0000000000..d477fc49c5 --- /dev/null +++ b/3rdparty/wlroots/types/wlr_xdg_toplevel_tag_v1.c @@ -0,0 +1,119 @@ +#include +#include +#include + +#include +#include + +#include "xdg-toplevel-tag-v1-protocol.h" +#include "util/global.h" + +#define MANAGER_VERSION 1 + +static const struct xdg_toplevel_tag_manager_v1_interface manager_impl; + +static struct wlr_xdg_toplevel_tag_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &xdg_toplevel_tag_manager_v1_interface, &manager_impl)); + return wl_resource_get_user_data(resource); +} + +static void manager_handle_set_tag(struct wl_client *client, struct wl_resource *manager_resource, + struct wl_resource *toplevel_resource, const char *tag) { + struct wlr_xdg_toplevel_tag_manager_v1 *manager = manager_from_resource(manager_resource); + struct wlr_xdg_toplevel *toplevel = wlr_xdg_toplevel_from_resource(toplevel_resource); + + struct wlr_xdg_toplevel_tag_manager_v1_set_tag_event event = { + .toplevel = toplevel, + .tag = tag, + }; + wl_signal_emit_mutable(&manager->events.set_tag, &event); +} + +static void manager_handle_set_description(struct wl_client *client, struct wl_resource *manager_resource, + struct wl_resource *toplevel_resource, const char *description) { + struct wlr_xdg_toplevel_tag_manager_v1 *manager = manager_from_resource(manager_resource); + struct wlr_xdg_toplevel *toplevel = wlr_xdg_toplevel_from_resource(toplevel_resource); + + struct wlr_xdg_toplevel_tag_manager_v1_set_description_event event = { + .toplevel = toplevel, + .description = description, + }; + wl_signal_emit_mutable(&manager->events.set_description, &event); +} + +static void manager_handle_destroy(struct wl_client *client, struct wl_resource *manager_resource) { + wl_resource_destroy(manager_resource); +} + +static const struct xdg_toplevel_tag_manager_v1_interface manager_impl = { + .destroy = manager_handle_destroy, + .set_toplevel_tag = manager_handle_set_tag, + .set_toplevel_description = manager_handle_set_description, +}; + +static void manager_bind(struct wl_client *client, void *data, uint32_t version, uint32_t id) { + struct wlr_xdg_toplevel_tag_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(client, + &xdg_toplevel_tag_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, manager, NULL); +} + +static void xdg_toplevel_tag_manager_v1_destroy(struct wlr_xdg_toplevel_tag_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, NULL); + + assert(wl_list_empty(&manager->events.set_tag.listener_list)); + assert(wl_list_empty(&manager->events.set_description.listener_list)); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + wl_list_remove(&manager->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + free(manager); +} + +void wlr_xdg_toplevel_tag_manager_v1_destroy(struct wlr_xdg_toplevel_tag_manager_v1 *manager, + bool destroy_global_safe) { + xdg_toplevel_tag_manager_v1_destroy(manager, destroy_global_safe); +} + +static void manager_handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_toplevel_tag_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + xdg_toplevel_tag_manager_v1_destroy(manager, false); +} + +struct wlr_xdg_toplevel_tag_manager_v1 *wlr_xdg_toplevel_tag_manager_v1_create( + struct wl_display *display, uint32_t version) { + assert(version <= MANAGER_VERSION); + + struct wlr_xdg_toplevel_tag_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + manager->global = wl_global_create(display, &xdg_toplevel_tag_manager_v1_interface, + version, manager, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + wl_signal_init(&manager->events.set_tag); + wl_signal_init(&manager->events.set_description); + wl_signal_init(&manager->events.destroy); + + manager->display_destroy.notify = manager_handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} diff --git a/3rdparty/wlroots/types/xdg_shell/wlr_xdg_popup.c b/3rdparty/wlroots/types/xdg_shell/wlr_xdg_popup.c new file mode 100644 index 0000000000..87bb78c743 --- /dev/null +++ b/3rdparty/wlroots/types/xdg_shell/wlr_xdg_popup.c @@ -0,0 +1,594 @@ +#include +#include +#include +#include +#include "types/wlr_xdg_shell.h" + +void handle_xdg_popup_ack_configure( + struct wlr_xdg_popup *popup, + struct wlr_xdg_popup_configure *configure) { + popup->pending.geometry = configure->geometry; + popup->pending.reactive = configure->rules.reactive; +} + +struct wlr_xdg_popup_configure *send_xdg_popup_configure( + struct wlr_xdg_popup *popup) { + struct wlr_xdg_popup_configure *configure = calloc(1, sizeof(*configure)); + if (configure == NULL) { + wl_resource_post_no_memory(popup->resource); + return NULL; + } + *configure = popup->scheduled; + + uint32_t version = wl_resource_get_version(popup->resource); + + if ((configure->fields & WLR_XDG_POPUP_CONFIGURE_REPOSITION_TOKEN) && + version >= XDG_POPUP_REPOSITIONED_SINCE_VERSION) { + xdg_popup_send_repositioned(popup->resource, + configure->reposition_token); + } + + struct wlr_box *geometry = &configure->geometry; + assert(geometry->width > 0 && geometry->height > 0); + xdg_popup_send_configure(popup->resource, + geometry->x, geometry->y, + geometry->width, geometry->height); + + popup->scheduled.fields = 0; + + return configure; +} + +static void xdg_popup_grab_end(struct wlr_xdg_popup_grab *popup_grab) { + struct wlr_xdg_popup *popup, *tmp; + wl_list_for_each_safe(popup, tmp, &popup_grab->popups, grab_link) { + xdg_popup_send_popup_done(popup->resource); + } + + wlr_seat_pointer_end_grab(popup_grab->seat); + wlr_seat_keyboard_end_grab(popup_grab->seat); + wlr_seat_touch_end_grab(popup_grab->seat); +} + +static void xdg_pointer_grab_enter(struct wlr_seat_pointer_grab *grab, + struct wlr_surface *surface, double sx, double sy) { + struct wlr_xdg_popup_grab *popup_grab = grab->data; + struct wlr_seat *seat = grab->seat; + + // Forward to drag grab if active + if (seat->drag && seat->drag->pointer_grab.interface && + seat->drag->pointer_grab.interface->enter) { + if (grab != &seat->drag->pointer_grab) { + seat->drag->pointer_grab.interface->enter(&seat->drag->pointer_grab, + surface, sx, sy); + } + return; + } + + if (wl_resource_get_client(surface->resource) == popup_grab->client) { + wlr_seat_pointer_enter(grab->seat, surface, sx, sy); + } else { + wlr_seat_pointer_clear_focus(grab->seat); + } +} + +static void xdg_pointer_grab_clear_focus(struct wlr_seat_pointer_grab *grab) { + wlr_seat_pointer_clear_focus(grab->seat); +} + +static void xdg_pointer_grab_motion(struct wlr_seat_pointer_grab *grab, + uint32_t time, double sx, double sy) { + struct wlr_seat *seat = grab->seat; + + if (seat->drag && seat->drag->pointer_grab.interface && + seat->drag->pointer_grab.interface->motion) { + if (grab != &seat->drag->pointer_grab) { + seat->drag->pointer_grab.interface->motion(&seat->drag->pointer_grab, + time, sx, sy); + } + return; + } + + wlr_seat_pointer_send_motion(grab->seat, time, sx, sy); +} + +static uint32_t xdg_pointer_grab_button(struct wlr_seat_pointer_grab *grab, + uint32_t time, uint32_t button, uint32_t state) { + struct wlr_seat *seat = grab->seat; + + if (seat->drag && seat->drag->pointer_grab.interface && + seat->drag->pointer_grab.interface->button) { + if (grab != &seat->drag->pointer_grab) { + return seat->drag->pointer_grab.interface->button(&seat->drag->pointer_grab, + time, button, state); + } + } + + uint32_t serial = wlr_seat_pointer_send_button(grab->seat, time, button, state); + if (serial) { + return serial; + } else { + xdg_popup_grab_end(grab->data); + return 0; + } +} + +static void xdg_pointer_grab_axis(struct wlr_seat_pointer_grab *grab, + uint32_t time, enum wl_pointer_axis orientation, double value, + int32_t value_discrete, enum wl_pointer_axis_source source, + enum wl_pointer_axis_relative_direction relative_direction) { + struct wlr_seat *seat = grab->seat; + + if (seat->drag && seat->drag->pointer_grab.interface && + seat->drag->pointer_grab.interface->axis) { + if (grab != &seat->drag->pointer_grab) { + seat->drag->pointer_grab.interface->axis(&seat->drag->pointer_grab, + time, orientation, value, value_discrete, source, relative_direction); + } + return; + } + + wlr_seat_pointer_send_axis(grab->seat, time, orientation, value, + value_discrete, source, relative_direction); +} + +static void xdg_pointer_grab_frame(struct wlr_seat_pointer_grab *grab) { + struct wlr_seat *seat = grab->seat; + + if (seat->drag && seat->drag->pointer_grab.interface && + seat->drag->pointer_grab.interface->frame) { + if (grab != &seat->drag->pointer_grab) { + seat->drag->pointer_grab.interface->frame(&seat->drag->pointer_grab); + } + return; + } + + wlr_seat_pointer_send_frame(grab->seat); +} + +static void xdg_pointer_grab_cancel(struct wlr_seat_pointer_grab *grab) { + xdg_popup_grab_end(grab->data); +} + +static const struct wlr_pointer_grab_interface xdg_pointer_grab_impl = { + .enter = xdg_pointer_grab_enter, + .clear_focus = xdg_pointer_grab_clear_focus, + .motion = xdg_pointer_grab_motion, + .button = xdg_pointer_grab_button, + .cancel = xdg_pointer_grab_cancel, + .axis = xdg_pointer_grab_axis, + .frame = xdg_pointer_grab_frame, +}; + +static void xdg_keyboard_grab_enter(struct wlr_seat_keyboard_grab *grab, + struct wlr_surface *surface, const uint32_t keycodes[], size_t num_keycodes, + const struct wlr_keyboard_modifiers *modifiers) { + // keyboard focus should remain on the popup + if (grab->seat->drag) { + return; + } + + wlr_seat_keyboard_enter(grab->seat, surface, keycodes, num_keycodes, modifiers); +} + +static void xdg_keyboard_grab_clear_focus(struct wlr_seat_keyboard_grab *grab) { + // keyboard focus should remain on the popup +} + +static void xdg_keyboard_grab_key(struct wlr_seat_keyboard_grab *grab, uint32_t time, + uint32_t key, uint32_t state) { + wlr_seat_keyboard_send_key(grab->seat, time, key, state); +} + +static void xdg_keyboard_grab_modifiers(struct wlr_seat_keyboard_grab *grab, + const struct wlr_keyboard_modifiers *modifiers) { + wlr_seat_keyboard_send_modifiers(grab->seat, modifiers); +} + +static void xdg_keyboard_grab_cancel(struct wlr_seat_keyboard_grab *grab) { + wlr_seat_pointer_end_grab(grab->seat); +} + +static const struct wlr_keyboard_grab_interface xdg_keyboard_grab_impl = { + .enter = xdg_keyboard_grab_enter, + .clear_focus = xdg_keyboard_grab_clear_focus, + .key = xdg_keyboard_grab_key, + .modifiers = xdg_keyboard_grab_modifiers, + .cancel = xdg_keyboard_grab_cancel, +}; + +static uint32_t xdg_touch_grab_down(struct wlr_seat_touch_grab *grab, + uint32_t time, struct wlr_touch_point *point) { + struct wlr_xdg_popup_grab *popup_grab = grab->data; + + if (wl_resource_get_client(point->surface->resource) != popup_grab->client) { + xdg_popup_grab_end(grab->data); + return 0; + } + + return wlr_seat_touch_send_down(grab->seat, point->surface, time, + point->touch_id, point->sx, point->sy); +} + +static uint32_t xdg_touch_grab_up(struct wlr_seat_touch_grab *grab, + uint32_t time, struct wlr_touch_point *point) { + return wlr_seat_touch_send_up(grab->seat, time, point->touch_id); +} + +static void xdg_touch_grab_motion(struct wlr_seat_touch_grab *grab, + uint32_t time, struct wlr_touch_point *point) { + wlr_seat_touch_send_motion(grab->seat, time, point->touch_id, point->sx, + point->sy); +} + +static void xdg_touch_grab_enter(struct wlr_seat_touch_grab *grab, + uint32_t time, struct wlr_touch_point *point) { +} + +static void xdg_touch_grab_frame(struct wlr_seat_touch_grab *grab) { + wlr_seat_touch_send_frame(grab->seat); +} + +static void xdg_touch_grab_cancel(struct wlr_seat_touch_grab *grab) { + wlr_seat_touch_end_grab(grab->seat); +} + +static void xdg_touch_grab_clear_focus(struct wlr_seat_touch_grab *grab, uint32_t time_msec, + struct wlr_touch_point *point) { + wlr_seat_touch_point_clear_focus(grab->seat, time_msec, point->touch_id); +} + +static const struct wlr_touch_grab_interface xdg_touch_grab_impl = { + .down = xdg_touch_grab_down, + .up = xdg_touch_grab_up, + .motion = xdg_touch_grab_motion, + .enter = xdg_touch_grab_enter, + .frame = xdg_touch_grab_frame, + .cancel = xdg_touch_grab_cancel, + .clear_focus = xdg_touch_grab_clear_focus, +}; + +static void destroy_xdg_popup_grab(struct wlr_xdg_popup_grab *xdg_grab) { + if (xdg_grab == NULL) { + return; + } + + wl_list_remove(&xdg_grab->seat_destroy.link); + + struct wlr_xdg_popup *popup, *tmp; + wl_list_for_each_safe(popup, tmp, &xdg_grab->popups, grab_link) { + wlr_xdg_popup_destroy(popup); + } + + wl_list_remove(&xdg_grab->link); + free(xdg_grab); +} + +static void xdg_popup_grab_handle_seat_destroy( + struct wl_listener *listener, void *data) { + struct wlr_xdg_popup_grab *xdg_grab = + wl_container_of(listener, xdg_grab, seat_destroy); + destroy_xdg_popup_grab(xdg_grab); +} + +static struct wlr_xdg_popup_grab *get_xdg_shell_popup_grab_from_seat( + struct wlr_xdg_shell *shell, struct wlr_seat *seat) { + struct wlr_xdg_popup_grab *xdg_grab; + wl_list_for_each(xdg_grab, &shell->popup_grabs, link) { + if (xdg_grab->seat == seat) { + return xdg_grab; + } + } + + xdg_grab = calloc(1, sizeof(*xdg_grab)); + if (!xdg_grab) { + return NULL; + } + + xdg_grab->pointer_grab.data = xdg_grab; + xdg_grab->pointer_grab.interface = &xdg_pointer_grab_impl; + xdg_grab->keyboard_grab.data = xdg_grab; + xdg_grab->keyboard_grab.interface = &xdg_keyboard_grab_impl; + xdg_grab->touch_grab.data = xdg_grab; + xdg_grab->touch_grab.interface = &xdg_touch_grab_impl; + + wl_list_init(&xdg_grab->popups); + + wl_list_insert(&shell->popup_grabs, &xdg_grab->link); + xdg_grab->seat = seat; + + xdg_grab->seat_destroy.notify = xdg_popup_grab_handle_seat_destroy; + wl_signal_add(&seat->events.destroy, &xdg_grab->seat_destroy); + + return xdg_grab; +} + +void handle_xdg_popup_client_commit(struct wlr_xdg_popup *popup) { + if (!popup->parent) { + wlr_surface_reject_pending(popup->base->surface, popup->base->resource, + XDG_SURFACE_ERROR_NOT_CONSTRUCTED, "xdg_popup has no parent"); + return; + } +} + +static const struct xdg_popup_interface xdg_popup_implementation; + +struct wlr_xdg_popup *wlr_xdg_popup_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &xdg_popup_interface, + &xdg_popup_implementation)); + return wl_resource_get_user_data(resource); +} + +struct wlr_xdg_popup *wlr_xdg_popup_try_from_wlr_surface(struct wlr_surface *surface) { + struct wlr_xdg_surface *xdg_surface = wlr_xdg_surface_try_from_wlr_surface(surface); + if (xdg_surface == NULL || xdg_surface->role != WLR_XDG_SURFACE_ROLE_POPUP) { + return NULL; + } + return xdg_surface->popup; +} + +static void xdg_popup_handle_grab(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *seat_resource, + uint32_t serial) { + struct wlr_xdg_popup *popup = + wlr_xdg_popup_from_resource(resource); + if (!popup) { + return; + } + + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat_resource); + if (seat_client == NULL) { + wlr_xdg_popup_destroy(popup); + return; + } + if (popup->base->surface->mapped) { + wl_resource_post_error(popup->resource, + XDG_POPUP_ERROR_INVALID_GRAB, + "xdg_popup is already mapped"); + return; + } + + struct wlr_xdg_popup_grab *popup_grab = get_xdg_shell_popup_grab_from_seat( + popup->base->client->shell, seat_client->seat); + + if (!wl_list_empty(&popup->base->popups)) { + wl_resource_post_error(popup->base->client->resource, + XDG_WM_BASE_ERROR_NOT_THE_TOPMOST_POPUP, + "xdg_popup was not created on the topmost popup"); + return; + } + + popup_grab->client = popup->base->client->client; + popup->seat = seat_client->seat; + + wl_list_insert(&popup_grab->popups, &popup->grab_link); + + wlr_seat_pointer_start_grab(seat_client->seat, + &popup_grab->pointer_grab); + wlr_seat_keyboard_start_grab(seat_client->seat, + &popup_grab->keyboard_grab); + wlr_seat_touch_start_grab(seat_client->seat, + &popup_grab->touch_grab); +} + +static void xdg_popup_handle_reposition( + struct wl_client *client, struct wl_resource *resource, + struct wl_resource *positioner_resource, uint32_t token) { + struct wlr_xdg_popup *popup = + wlr_xdg_popup_from_resource(resource); + if (!popup) { + return; + } + + struct wlr_xdg_positioner *positioner = wlr_xdg_positioner_from_resource(positioner_resource); + if (!wlr_xdg_positioner_is_complete(positioner)) { + wl_resource_post_error(popup->base->client->resource, + XDG_WM_BASE_ERROR_INVALID_POSITIONER, "positioner object is not complete"); + return; + } + + wlr_xdg_positioner_rules_get_geometry( + &positioner->rules, &popup->scheduled.geometry); + popup->scheduled.rules = positioner->rules; + + popup->scheduled.fields |= WLR_XDG_POPUP_CONFIGURE_REPOSITION_TOKEN; + popup->scheduled.reposition_token = token; + + wlr_xdg_surface_schedule_configure(popup->base); + + wl_signal_emit_mutable(&popup->events.reposition, NULL); +} + +static void xdg_popup_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_xdg_popup *popup = + wlr_xdg_popup_from_resource(resource); + + if (popup && !wl_list_empty(&popup->base->popups)) { + wl_resource_post_error(popup->base->client->resource, + XDG_WM_BASE_ERROR_NOT_THE_TOPMOST_POPUP, + "xdg_popup was destroyed while it was not the topmost popup"); + return; + } + + wl_resource_destroy(resource); +} + +static const struct xdg_popup_interface xdg_popup_implementation = { + .destroy = xdg_popup_handle_destroy, + .grab = xdg_popup_handle_grab, + .reposition = xdg_popup_handle_reposition, +}; + +static const struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(struct wlr_xdg_popup_state), +}; + +void create_xdg_popup(struct wlr_xdg_surface *surface, struct wlr_xdg_surface *parent, + struct wlr_xdg_positioner *positioner, uint32_t id) { + if (!wlr_xdg_positioner_is_complete(positioner)) { + wl_resource_post_error(surface->client->resource, + XDG_WM_BASE_ERROR_INVALID_POSITIONER, "positioner object is not complete"); + return; + } + + if (!set_xdg_surface_role(surface, WLR_XDG_SURFACE_ROLE_POPUP)) { + return; + } + + if (parent != NULL && parent->role == WLR_XDG_SURFACE_ROLE_NONE) { + wl_resource_post_error(surface->client->resource, XDG_WM_BASE_ERROR_INVALID_POPUP_PARENT, + "a popup parent must have a role"); + return; + } + + assert(surface->popup == NULL); + surface->popup = calloc(1, sizeof(*surface->popup)); + if (!surface->popup) { + wl_resource_post_no_memory(surface->resource); + return; + } + surface->popup->base = surface; + + if (!wlr_surface_synced_init(&surface->popup->synced, surface->surface, + &surface_synced_impl, &surface->popup->pending, + &surface->popup->current)) { + goto error_popup; + } + + surface->popup->resource = wl_resource_create( + surface->client->client, &xdg_popup_interface, + wl_resource_get_version(surface->resource), id); + if (surface->popup->resource == NULL) { + goto error_synced; + } + wl_resource_set_implementation(surface->popup->resource, + &xdg_popup_implementation, surface->popup, NULL); + + surface->role = WLR_XDG_SURFACE_ROLE_POPUP; + + wlr_xdg_positioner_rules_get_geometry( + &positioner->rules, &surface->popup->scheduled.geometry); + surface->popup->scheduled.rules = positioner->rules; + + wl_signal_init(&surface->popup->events.destroy); + wl_signal_init(&surface->popup->events.reposition); + + if (parent) { + surface->popup->parent = parent->surface; + wl_list_insert(&parent->popups, &surface->popup->link); + } else { + wl_list_init(&surface->popup->link); + } + + set_xdg_surface_role_object(surface, surface->popup->resource); + + wl_signal_emit_mutable(&surface->client->shell->events.new_popup, surface->popup); + if (parent) { + wl_signal_emit_mutable(&parent->events.new_popup, surface->popup); + } + + return; + +error_synced: + wlr_surface_synced_finish(&surface->popup->synced); +error_popup: + free(surface->popup); + surface->popup = NULL; + wl_resource_post_no_memory(surface->resource); +} + +void reset_xdg_popup(struct wlr_xdg_popup *popup) { + if (popup->seat != NULL) { + struct wlr_xdg_popup_grab *grab = + get_xdg_shell_popup_grab_from_seat( + popup->base->client->shell, popup->seat); + + wl_list_remove(&popup->grab_link); + + if (wl_list_empty(&grab->popups)) { + if (grab->seat->pointer_state.grab == &grab->pointer_grab) { + wlr_seat_pointer_end_grab(grab->seat); + } + if (grab->seat->keyboard_state.grab == &grab->keyboard_grab) { + wlr_seat_keyboard_end_grab(grab->seat); + } + if (grab->seat->touch_state.grab == &grab->touch_grab) { + wlr_seat_touch_end_grab(grab->seat); + } + + destroy_xdg_popup_grab(grab); + } + + popup->seat = NULL; + } +} + +void destroy_xdg_popup(struct wlr_xdg_popup *popup) { + wlr_surface_unmap(popup->base->surface); + reset_xdg_popup(popup); + + wl_signal_emit_mutable(&popup->events.destroy, NULL); + + assert(wl_list_empty(&popup->events.destroy.listener_list)); + assert(wl_list_empty(&popup->events.reposition.listener_list)); + + wlr_surface_synced_finish(&popup->synced); + popup->base->popup = NULL; + wl_list_remove(&popup->link); + wl_resource_set_user_data(popup->resource, NULL); + free(popup); +} + +void wlr_xdg_popup_destroy(struct wlr_xdg_popup *popup) { + if (popup == NULL) { + return; + } + + struct wlr_xdg_popup *child, *child_tmp; + wl_list_for_each_safe(child, child_tmp, &popup->base->popups, link) { + wlr_xdg_popup_destroy(child); + } + + xdg_popup_send_popup_done(popup->resource); + destroy_xdg_popup(popup); +} + +void wlr_xdg_popup_get_toplevel_coords(struct wlr_xdg_popup *popup, + int popup_sx, int popup_sy, int *toplevel_sx, int *toplevel_sy) { + struct wlr_surface *parent = popup->parent; + struct wlr_xdg_surface *xdg_surface; + while ((xdg_surface = wlr_xdg_surface_try_from_wlr_surface(parent))) { + if (xdg_surface->role == WLR_XDG_SURFACE_ROLE_POPUP && xdg_surface->popup != NULL) { + popup_sx += xdg_surface->popup->current.geometry.x; + popup_sy += xdg_surface->popup->current.geometry.y; + parent = xdg_surface->popup->parent; + } else { + popup_sx += xdg_surface->geometry.x; + popup_sy += xdg_surface->geometry.y; + break; + } + } + assert(parent); + + *toplevel_sx = popup_sx; + *toplevel_sy = popup_sy; +} + +void wlr_xdg_popup_unconstrain_from_box(struct wlr_xdg_popup *popup, + const struct wlr_box *toplevel_space_box) { + int toplevel_sx, toplevel_sy; + wlr_xdg_popup_get_toplevel_coords(popup, + 0, 0, &toplevel_sx, &toplevel_sy); + struct wlr_box popup_constraint = { + .x = toplevel_space_box->x - toplevel_sx, + .y = toplevel_space_box->y - toplevel_sy, + .width = toplevel_space_box->width, + .height = toplevel_space_box->height, + }; + wlr_xdg_positioner_rules_unconstrain_box(&popup->scheduled.rules, + &popup_constraint, &popup->scheduled.geometry); + wlr_xdg_surface_schedule_configure(popup->base); +} diff --git a/3rdparty/wlroots/types/xdg_shell/wlr_xdg_positioner.c b/3rdparty/wlroots/types/xdg_shell/wlr_xdg_positioner.c new file mode 100644 index 0000000000..e980091870 --- /dev/null +++ b/3rdparty/wlroots/types/xdg_shell/wlr_xdg_positioner.c @@ -0,0 +1,518 @@ +#include +#include +#include +#include "types/wlr_xdg_shell.h" + +static const struct xdg_positioner_interface xdg_positioner_implementation; + +struct wlr_xdg_positioner *wlr_xdg_positioner_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &xdg_positioner_interface, + &xdg_positioner_implementation)); + return wl_resource_get_user_data(resource); +} + +static void xdg_positioner_handle_set_size(struct wl_client *client, + struct wl_resource *resource, int32_t width, int32_t height) { + struct wlr_xdg_positioner *positioner = + wlr_xdg_positioner_from_resource(resource); + + if (width < 1 || height < 1) { + wl_resource_post_error(resource, + XDG_POSITIONER_ERROR_INVALID_INPUT, + "width and height must be positive and non-zero"); + return; + } + + positioner->rules.size.width = width; + positioner->rules.size.height = height; +} + +static void xdg_positioner_handle_set_anchor_rect(struct wl_client *client, + struct wl_resource *resource, int32_t x, int32_t y, int32_t width, + int32_t height) { + struct wlr_xdg_positioner *positioner = + wlr_xdg_positioner_from_resource(resource); + + if (width < 0 || height < 0) { + wl_resource_post_error(resource, + XDG_POSITIONER_ERROR_INVALID_INPUT, + "width and height must be positive"); + return; + } + + positioner->rules.anchor_rect.x = x; + positioner->rules.anchor_rect.y = y; + positioner->rules.anchor_rect.width = width; + positioner->rules.anchor_rect.height = height; +} + +static void xdg_positioner_handle_set_anchor(struct wl_client *client, + struct wl_resource *resource, uint32_t anchor) { + struct wlr_xdg_positioner *positioner = + wlr_xdg_positioner_from_resource(resource); + + uint32_t version = wl_resource_get_version(resource); + if (!xdg_positioner_anchor_is_valid(anchor, version)) { + wl_resource_post_error(resource, + XDG_POSITIONER_ERROR_INVALID_INPUT, + "invalid anchor value"); + return; + } + + positioner->rules.anchor = anchor; +} + +static void xdg_positioner_handle_set_gravity(struct wl_client *client, + struct wl_resource *resource, uint32_t gravity) { + struct wlr_xdg_positioner *positioner = + wlr_xdg_positioner_from_resource(resource); + + uint32_t version = wl_resource_get_version(resource); + if (!xdg_positioner_gravity_is_valid(gravity, version)) { + wl_resource_post_error(resource, + XDG_POSITIONER_ERROR_INVALID_INPUT, + "invalid gravity value"); + return; + } + + positioner->rules.gravity = gravity; +} + +static void xdg_positioner_handle_set_constraint_adjustment( + struct wl_client *client, struct wl_resource *resource, + uint32_t constraint_adjustment) { + struct wlr_xdg_positioner *positioner = + wlr_xdg_positioner_from_resource(resource); + + uint32_t version = wl_resource_get_version(resource); + if (!xdg_positioner_constraint_adjustment_is_valid(constraint_adjustment, version)) { + wl_resource_post_error(resource, + XDG_POSITIONER_ERROR_INVALID_INPUT, + "invalid constraint_adjustment value"); + return; + } + + positioner->rules.constraint_adjustment = constraint_adjustment; +} + +static void xdg_positioner_handle_set_offset(struct wl_client *client, + struct wl_resource *resource, int32_t x, int32_t y) { + struct wlr_xdg_positioner *positioner = + wlr_xdg_positioner_from_resource(resource); + + positioner->rules.offset.x = x; + positioner->rules.offset.y = y; +} + +static void xdg_positioner_handle_set_reactive( + struct wl_client *client, struct wl_resource *resource) { + struct wlr_xdg_positioner *positioner = + wlr_xdg_positioner_from_resource(resource); + + positioner->rules.reactive = true; +} + +static void xdg_positioner_handle_set_parent_configure( + struct wl_client *client, struct wl_resource *resource, + uint32_t serial) { + struct wlr_xdg_positioner *positioner = + wlr_xdg_positioner_from_resource(resource); + + positioner->rules.has_parent_configure_serial = true; + positioner->rules.parent_configure_serial = serial; +} + +static void xdg_positioner_handle_set_parent_size(struct wl_client *client, + struct wl_resource *resource, + int32_t parent_width, int32_t parent_height) { + struct wlr_xdg_positioner *positioner = + wlr_xdg_positioner_from_resource(resource); + + positioner->rules.parent_size.width = parent_width; + positioner->rules.parent_size.height = parent_height; +} + +static void xdg_positioner_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct xdg_positioner_interface + xdg_positioner_implementation = { + .destroy = xdg_positioner_handle_destroy, + .set_size = xdg_positioner_handle_set_size, + .set_anchor_rect = xdg_positioner_handle_set_anchor_rect, + .set_anchor = xdg_positioner_handle_set_anchor, + .set_gravity = xdg_positioner_handle_set_gravity, + .set_constraint_adjustment = + xdg_positioner_handle_set_constraint_adjustment, + .set_offset = xdg_positioner_handle_set_offset, + .set_reactive = xdg_positioner_handle_set_reactive, + .set_parent_size = xdg_positioner_handle_set_parent_size, + .set_parent_configure = xdg_positioner_handle_set_parent_configure, +}; + +static void xdg_positioner_handle_resource_destroy( + struct wl_resource *resource) { + struct wlr_xdg_positioner *positioner = + wlr_xdg_positioner_from_resource(resource); + free(positioner); +} + +void create_xdg_positioner(struct wlr_xdg_client *client, uint32_t id) { + struct wlr_xdg_positioner *positioner = calloc(1, sizeof(*positioner)); + if (positioner == NULL) { + wl_client_post_no_memory(client->client); + return; + } + + positioner->resource = wl_resource_create(client->client, + &xdg_positioner_interface, + wl_resource_get_version(client->resource), + id); + if (positioner->resource == NULL) { + free(positioner); + wl_client_post_no_memory(client->client); + return; + } + wl_resource_set_implementation(positioner->resource, + &xdg_positioner_implementation, + positioner, xdg_positioner_handle_resource_destroy); +} + +static uint32_t xdg_positioner_anchor_to_wlr_edges( + enum xdg_positioner_anchor anchor) { + switch (anchor) { + case XDG_POSITIONER_ANCHOR_NONE: + return WLR_EDGE_NONE; + case XDG_POSITIONER_ANCHOR_TOP: + return WLR_EDGE_TOP; + case XDG_POSITIONER_ANCHOR_TOP_LEFT: + return WLR_EDGE_TOP | WLR_EDGE_LEFT; + case XDG_POSITIONER_ANCHOR_TOP_RIGHT: + return WLR_EDGE_TOP | WLR_EDGE_RIGHT; + case XDG_POSITIONER_ANCHOR_BOTTOM: + return WLR_EDGE_BOTTOM; + case XDG_POSITIONER_ANCHOR_BOTTOM_LEFT: + return WLR_EDGE_BOTTOM | WLR_EDGE_LEFT; + case XDG_POSITIONER_ANCHOR_BOTTOM_RIGHT: + return WLR_EDGE_BOTTOM | WLR_EDGE_RIGHT; + case XDG_POSITIONER_ANCHOR_LEFT: + return WLR_EDGE_LEFT; + case XDG_POSITIONER_ANCHOR_RIGHT: + return WLR_EDGE_RIGHT; + } + + abort(); // Unreachable +} + +static uint32_t xdg_positioner_gravity_to_wlr_edges( + enum xdg_positioner_gravity gravity) { + // Gravity and edge enums are the same + return xdg_positioner_anchor_to_wlr_edges((enum xdg_positioner_anchor)gravity); +} + +bool wlr_xdg_positioner_is_complete(struct wlr_xdg_positioner *positioner) { + struct wlr_xdg_positioner_rules *rules = &positioner->rules; + return rules->size.width > 0 && rules->anchor_rect.width > 0; +} + +void wlr_xdg_positioner_rules_get_geometry( + const struct wlr_xdg_positioner_rules *rules, struct wlr_box *box) { + box->x = rules->offset.x; + box->y = rules->offset.y; + box->width = rules->size.width; + box->height = rules->size.height; + + uint32_t edges = xdg_positioner_anchor_to_wlr_edges(rules->anchor); + + if (edges & WLR_EDGE_TOP) { + box->y += rules->anchor_rect.y; + } else if (edges & WLR_EDGE_BOTTOM) { + box->y += rules->anchor_rect.y + rules->anchor_rect.height; + } else { + box->y += rules->anchor_rect.y + rules->anchor_rect.height / 2; + } + + if (edges & WLR_EDGE_LEFT) { + box->x += rules->anchor_rect.x; + } else if (edges & WLR_EDGE_RIGHT) { + box->x += rules->anchor_rect.x + rules->anchor_rect.width; + } else { + box->x += rules->anchor_rect.x + rules->anchor_rect.width / 2; + } + + edges = xdg_positioner_gravity_to_wlr_edges(rules->gravity); + + if (edges & WLR_EDGE_TOP) { + box->y -= box->height; + } else if (~edges & WLR_EDGE_BOTTOM) { + box->y -= box->height / 2; + } + + if (edges & WLR_EDGE_LEFT) { + box->x -= box->width; + } else if (~edges & WLR_EDGE_RIGHT) { + box->x -= box->width / 2; + } +} + +static enum xdg_positioner_anchor xdg_positioner_anchor_invert_x( + enum xdg_positioner_anchor anchor) { + switch (anchor) { + case XDG_POSITIONER_ANCHOR_LEFT: + return XDG_POSITIONER_ANCHOR_RIGHT; + case XDG_POSITIONER_ANCHOR_RIGHT: + return XDG_POSITIONER_ANCHOR_LEFT; + case XDG_POSITIONER_ANCHOR_TOP_LEFT: + return XDG_POSITIONER_ANCHOR_TOP_RIGHT; + case XDG_POSITIONER_ANCHOR_TOP_RIGHT: + return XDG_POSITIONER_ANCHOR_TOP_LEFT; + case XDG_POSITIONER_ANCHOR_BOTTOM_LEFT: + return XDG_POSITIONER_ANCHOR_BOTTOM_RIGHT; + case XDG_POSITIONER_ANCHOR_BOTTOM_RIGHT: + return XDG_POSITIONER_ANCHOR_BOTTOM_LEFT; + default: + return anchor; + } +} + +static enum xdg_positioner_gravity xdg_positioner_gravity_invert_x( + enum xdg_positioner_gravity gravity) { + // gravity and edge enums are the same + return (enum xdg_positioner_gravity)xdg_positioner_anchor_invert_x( + (enum xdg_positioner_anchor)gravity); +} + +static enum xdg_positioner_anchor xdg_positioner_anchor_invert_y( + enum xdg_positioner_anchor anchor) { + switch (anchor) { + case XDG_POSITIONER_ANCHOR_TOP: + return XDG_POSITIONER_ANCHOR_BOTTOM; + case XDG_POSITIONER_ANCHOR_BOTTOM: + return XDG_POSITIONER_ANCHOR_TOP; + case XDG_POSITIONER_ANCHOR_TOP_LEFT: + return XDG_POSITIONER_ANCHOR_BOTTOM_LEFT; + case XDG_POSITIONER_ANCHOR_BOTTOM_LEFT: + return XDG_POSITIONER_ANCHOR_TOP_LEFT; + case XDG_POSITIONER_ANCHOR_TOP_RIGHT: + return XDG_POSITIONER_ANCHOR_BOTTOM_RIGHT; + case XDG_POSITIONER_ANCHOR_BOTTOM_RIGHT: + return XDG_POSITIONER_ANCHOR_TOP_RIGHT; + default: + return anchor; + } +} + +static enum xdg_positioner_gravity xdg_positioner_gravity_invert_y( + enum xdg_positioner_gravity gravity) { + // gravity and edge enums are the same + return (enum xdg_positioner_gravity)xdg_positioner_anchor_invert_y( + (enum xdg_positioner_anchor)gravity); +} + +/** + * Distances from each edge of the box to the corresponding edge of + * the anchor rect. Each distance is positive if the edge is outside + * the anchor rect, and negative if the edge is inside it. + */ +struct constraint_offsets { + int top; + int bottom; + int left; + int right; +}; + +static bool is_unconstrained(const struct constraint_offsets *offsets) { + return offsets->top <= 0 && offsets->bottom <= 0 && + offsets->left <= 0 && offsets->right <= 0; +} + +static void get_constrained_box_offsets(const struct wlr_box *constraint, + const struct wlr_box *box, struct constraint_offsets *offsets) { + offsets->left = constraint->x - box->x; + offsets->right = box->x + box->width - constraint->x - constraint->width; + offsets->top = constraint->y - box->y; + offsets->bottom = box->y + box->height - constraint->y - constraint->height; +} + +static bool xdg_positioner_rules_unconstrain_by_flip( + const struct wlr_xdg_positioner_rules *rules, + const struct wlr_box *constraint, struct wlr_box *box, + struct constraint_offsets *offsets) { + // If none of the edges are constrained, no need to flip. + // If both edges are constrained, the box is bigger than + // the anchor rect and flipping won't help anyway. + bool flip_x = ((offsets->left > 0) ^ (offsets->right > 0)) && + (rules->constraint_adjustment & XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_X); + bool flip_y = ((offsets->top > 0) ^ (offsets->bottom > 0)) && + (rules->constraint_adjustment & XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_FLIP_Y); + + if (!flip_x && !flip_y) { + return false; + } + + struct wlr_xdg_positioner_rules flipped = *rules; + if (flip_x) { + flipped.anchor = xdg_positioner_anchor_invert_x(flipped.anchor); + flipped.gravity = xdg_positioner_gravity_invert_x(flipped.gravity); + } + if (flip_y) { + flipped.anchor = xdg_positioner_anchor_invert_y(flipped.anchor); + flipped.gravity = xdg_positioner_gravity_invert_y(flipped.gravity); + } + + struct wlr_box flipped_box; + wlr_xdg_positioner_rules_get_geometry(&flipped, &flipped_box); + struct constraint_offsets flipped_offsets; + get_constrained_box_offsets(constraint, &flipped_box, &flipped_offsets); + + // Only apply flipping if it helps + if (flipped_offsets.left <= 0 && flipped_offsets.right <= 0) { + box->x = flipped_box.x; + offsets->left = flipped_offsets.left; + offsets->right = flipped_offsets.right; + } + if (flipped_offsets.top <= 0 && flipped_offsets.bottom <= 0) { + box->y = flipped_box.y; + offsets->top = flipped_offsets.top; + offsets->bottom = flipped_offsets.bottom; + } + + return is_unconstrained(offsets); +} + +static bool xdg_positioner_rules_unconstrain_by_slide( + const struct wlr_xdg_positioner_rules *rules, + const struct wlr_box *constraint, struct wlr_box *box, + struct constraint_offsets *offsets) { + uint32_t gravity = xdg_positioner_gravity_to_wlr_edges(rules->gravity); + + bool slide_x = (offsets->left > 0 || offsets->right > 0) && + (rules->constraint_adjustment & XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_X); + bool slide_y = (offsets->top > 0 || offsets->bottom > 0) && + (rules->constraint_adjustment & XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_SLIDE_Y); + + if (!slide_x && !slide_y) { + return false; + } + + if (slide_x) { + if (offsets->left > 0 && offsets->right > 0) { + // The protocol states: "First try to slide towards the direction of + // the gravity [...] Then try to slide towards the opposite direction + // of the gravity". The only situation where this order matters is when + // the box is bigger than the anchor rect and completely includes it. + // In this case, the second slide will fail immediately, so simply + // slide towards the direction of the gravity. + // Note that the protocol doesn't specify the behavior when there is no + // gravity on the axis (which is what e.g. GTK tooltips use). In this + // case, fall back to sliding the box to the right/bottom, which is what + // GTK X11 popup adjustment code does. + if (gravity & WLR_EDGE_LEFT) { + box->x -= offsets->right; + } else { + box->x += offsets->left; + } + } else { + // If at least one edge is already unconstrained, the order of slide + // attempts doesn't matter. Slide for the minimal distance needed to + // satisfy the requirement of constraining one edge or unconstraining + // another. + int abs_left = offsets->left > 0 ? offsets->left : -offsets->left; + int abs_right = offsets->right > 0 ? offsets->right : -offsets->right; + if (abs_left < abs_right) { + box->x += offsets->left; + } else { + box->x -= offsets->right; + } + } + } + if (slide_y) { + if (offsets->top > 0 && offsets->bottom > 0) { + if (gravity & WLR_EDGE_TOP) { + box->y -= offsets->bottom; + } else { + box->y += offsets->top; + } + } else { + int abs_top = offsets->top > 0 ? offsets->top : -offsets->top; + int abs_bottom = offsets->bottom > 0 ? offsets->bottom : -offsets->bottom; + if (abs_top < abs_bottom) { + box->y += offsets->top; + } else { + box->y -= offsets->bottom; + } + } + } + + get_constrained_box_offsets(constraint, box, offsets); + return is_unconstrained(offsets); +} + +static bool xdg_positioner_rules_unconstrain_by_resize( + const struct wlr_xdg_positioner_rules *rules, + const struct wlr_box *constraint, struct wlr_box *box, + struct constraint_offsets *offsets) { + bool resize_x = (offsets->left > 0 || offsets->right > 0) && + (rules->constraint_adjustment & XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_X); + bool resize_y = (offsets->top > 0 || offsets->bottom > 0) && + (rules->constraint_adjustment & XDG_POSITIONER_CONSTRAINT_ADJUSTMENT_RESIZE_Y); + + if (!resize_x && !resize_y) { + return false; + } + + if (offsets->left < 0) { + offsets->left = 0; + } + if (offsets->right < 0) { + offsets->right = 0; + } + if (offsets->top < 0) { + offsets->top = 0; + } + if (offsets->bottom < 0) { + offsets->bottom = 0; + } + + // Try to satisfy the constraints by clipping the box. + struct wlr_box resized_box = *box; + if (resize_x) { + resized_box.x += offsets->left; + resized_box.width -= offsets->left + offsets->right; + } + if (resize_y) { + resized_box.y += offsets->top; + resized_box.height -= offsets->top + offsets->bottom; + } + + if (wlr_box_empty(&resized_box)) { + return false; + } + + *box = resized_box; + get_constrained_box_offsets(constraint, box, offsets); + return is_unconstrained(offsets); +} + +void wlr_xdg_positioner_rules_unconstrain_box( + const struct wlr_xdg_positioner_rules *rules, + const struct wlr_box *constraint, struct wlr_box *box) { + struct constraint_offsets offsets; + get_constrained_box_offsets(constraint, box, &offsets); + if (is_unconstrained(&offsets)) { + // Already unconstrained + return; + } + if (xdg_positioner_rules_unconstrain_by_flip(rules, constraint, box, &offsets)) { + return; + } + if (xdg_positioner_rules_unconstrain_by_slide(rules, constraint, box, &offsets)) { + return; + } + if (xdg_positioner_rules_unconstrain_by_resize(rules, constraint, box, &offsets)) { + return; + } +} diff --git a/3rdparty/wlroots/types/xdg_shell/wlr_xdg_shell.c b/3rdparty/wlroots/types/xdg_shell/wlr_xdg_shell.c new file mode 100644 index 0000000000..6e50a1cd5c --- /dev/null +++ b/3rdparty/wlroots/types/xdg_shell/wlr_xdg_shell.c @@ -0,0 +1,195 @@ +#include +#include +#include +#include "types/wlr_xdg_shell.h" +#include "util/global.h" + +#define WM_BASE_VERSION 7 + +static const struct xdg_wm_base_interface xdg_shell_impl; + +static struct wlr_xdg_client *xdg_client_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &xdg_wm_base_interface, + &xdg_shell_impl)); + return wl_resource_get_user_data(resource); +} + +static void xdg_shell_handle_create_positioner(struct wl_client *wl_client, + struct wl_resource *resource, uint32_t id) { + struct wlr_xdg_client *client = + xdg_client_from_resource(resource); + create_xdg_positioner(client, id); +} + +static void xdg_shell_handle_get_xdg_surface(struct wl_client *wl_client, + struct wl_resource *client_resource, uint32_t id, + struct wl_resource *surface_resource) { + struct wlr_xdg_client *client = + xdg_client_from_resource(client_resource); + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + create_xdg_surface(client, surface, id); +} + +static void xdg_shell_handle_pong(struct wl_client *wl_client, + struct wl_resource *resource, uint32_t serial) { + struct wlr_xdg_client *client = xdg_client_from_resource(resource); + + if (client->ping_serial != serial) { + return; + } + + wl_event_source_timer_update(client->ping_timer, 0); + client->ping_serial = 0; +} + +static void xdg_shell_handle_destroy(struct wl_client *wl_client, + struct wl_resource *resource) { + struct wlr_xdg_client *client = xdg_client_from_resource(resource); + + if (!wl_list_empty(&client->surfaces)) { + wl_resource_post_error(client->resource, + XDG_WM_BASE_ERROR_DEFUNCT_SURFACES, + "xdg_wm_base was destroyed before children"); + return; + } + + wl_resource_destroy(resource); +} + +static const struct xdg_wm_base_interface xdg_shell_impl = { + .destroy = xdg_shell_handle_destroy, + .create_positioner = xdg_shell_handle_create_positioner, + .get_xdg_surface = xdg_shell_handle_get_xdg_surface, + .pong = xdg_shell_handle_pong, +}; + +static void xdg_client_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_xdg_client *client = xdg_client_from_resource(resource); + + struct wlr_xdg_surface *surface, *tmp = NULL; + wl_list_for_each_safe(surface, tmp, &client->surfaces, link) { + destroy_xdg_surface(surface); + } + + if (client->ping_timer != NULL) { + wl_event_source_remove(client->ping_timer); + } + + wl_list_remove(&client->link); + free(client); +} + +static int xdg_client_ping_timeout(void *user_data) { + struct wlr_xdg_client *client = user_data; + + struct wlr_xdg_surface *surface; + wl_list_for_each(surface, &client->surfaces, link) { + wl_signal_emit_mutable(&surface->events.ping_timeout, NULL); + } + + client->ping_serial = 0; + return 1; +} + +static void xdg_shell_bind(struct wl_client *wl_client, void *data, + uint32_t version, uint32_t id) { + struct wlr_xdg_shell *xdg_shell = data; + + struct wlr_xdg_client *client = calloc(1, sizeof(*client)); + if (client == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + + wl_list_init(&client->surfaces); + + client->resource = + wl_resource_create(wl_client, &xdg_wm_base_interface, version, id); + if (client->resource == NULL) { + free(client); + wl_client_post_no_memory(wl_client); + return; + } + client->client = wl_client; + client->shell = xdg_shell; + + wl_resource_set_implementation(client->resource, &xdg_shell_impl, client, + xdg_client_handle_resource_destroy); + wl_list_init(&client->link); + if (xdg_shell == NULL) { + return; + } + + wl_list_insert(&xdg_shell->clients, &client->link); + + struct wl_display *display = wl_client_get_display(client->client); + struct wl_event_loop *loop = wl_display_get_event_loop(display); + client->ping_timer = wl_event_loop_add_timer(loop, + xdg_client_ping_timeout, client); + if (client->ping_timer == NULL) { + wl_client_post_no_memory(client->client); + } +} + +static void xdg_shell_destroy(struct wlr_xdg_shell *xdg_shell, + bool destroy_global_safe) { + wl_signal_emit_mutable(&xdg_shell->events.destroy, xdg_shell); + + assert(wl_list_empty(&xdg_shell->events.new_surface.listener_list)); + assert(wl_list_empty(&xdg_shell->events.new_toplevel.listener_list)); + assert(wl_list_empty(&xdg_shell->events.new_popup.listener_list)); + assert(wl_list_empty(&xdg_shell->events.destroy.listener_list)); + + wl_list_remove(&xdg_shell->display_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(xdg_shell->global); + } else { + wl_global_destroy(xdg_shell->global); + } + free(xdg_shell); +} + +void wlr_xdg_shell_destroy(struct wlr_xdg_shell *xdg_shell, bool destroy_global_safe) { + xdg_shell_destroy(xdg_shell, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_shell *xdg_shell = + wl_container_of(listener, xdg_shell, display_destroy); + xdg_shell_destroy(xdg_shell, false); +} + +struct wlr_xdg_shell *wlr_xdg_shell_create(struct wl_display *display, + uint32_t version) { + assert(version <= WM_BASE_VERSION); + + struct wlr_xdg_shell *xdg_shell = calloc(1, sizeof(*xdg_shell)); + if (!xdg_shell) { + return NULL; + } + + xdg_shell->version = version; + xdg_shell->ping_timeout = 10000; + + wl_list_init(&xdg_shell->clients); + wl_list_init(&xdg_shell->popup_grabs); + + struct wl_global *global = wl_global_create(display, + &xdg_wm_base_interface, version, xdg_shell, xdg_shell_bind); + if (!global) { + free(xdg_shell); + return NULL; + } + xdg_shell->global = global; + + wl_signal_init(&xdg_shell->events.new_surface); + wl_signal_init(&xdg_shell->events.new_toplevel); + wl_signal_init(&xdg_shell->events.new_popup); + wl_signal_init(&xdg_shell->events.destroy); + + xdg_shell->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &xdg_shell->display_destroy); + + return xdg_shell; +} diff --git a/3rdparty/wlroots/types/xdg_shell/wlr_xdg_surface.c b/3rdparty/wlroots/types/xdg_shell/wlr_xdg_surface.c new file mode 100644 index 0000000000..8a252d2f80 --- /dev/null +++ b/3rdparty/wlroots/types/xdg_shell/wlr_xdg_surface.c @@ -0,0 +1,655 @@ +#include +#include +#include +#include +#include +#include "types/wlr_xdg_shell.h" + +static void xdg_surface_configure_destroy( + struct wlr_xdg_surface_configure *configure) { + if (configure == NULL) { + return; + } + wl_list_remove(&configure->link); + free(configure->toplevel_configure); + free(configure); +} + +// An xdg_surface implementation is reset, when: +// 1) a surface is unmapped due to a commit with NULL buffer, or +// 2) the xdg_surface role object is destroyed, or +// 3) wlr_xdg_surface is destroyed +// An xdg_surface role object implementation is reset, when: +// 1) a surface is unmapped due to a commit with NULL buffer, or +// 2) the xdg_surface role object implementation is destroyed + +static void reset_xdg_surface(struct wlr_xdg_surface *surface) { + surface->configured = false; + surface->initialized = false; + + struct wlr_xdg_popup *popup, *popup_tmp; + wl_list_for_each_safe(popup, popup_tmp, &surface->popups, link) { + wlr_xdg_popup_destroy(popup); + } + + struct wlr_xdg_surface_configure *configure, *tmp; + wl_list_for_each_safe(configure, tmp, &surface->configure_list, link) { + xdg_surface_configure_destroy(configure); + } + + if (surface->configure_idle) { + wl_event_source_remove(surface->configure_idle); + surface->configure_idle = NULL; + } +} + +static void reset_xdg_surface_role_object(struct wlr_xdg_surface *surface) { + switch (surface->role) { + case WLR_XDG_SURFACE_ROLE_TOPLEVEL: + if (surface->toplevel != NULL) { + reset_xdg_toplevel(surface->toplevel); + } + break; + case WLR_XDG_SURFACE_ROLE_POPUP: + if (surface->popup != NULL) { + reset_xdg_popup(surface->popup); + } + break; + case WLR_XDG_SURFACE_ROLE_NONE: + break; + } +} + +static void xdg_surface_handle_ack_configure(struct wl_client *client, + struct wl_resource *resource, uint32_t serial) { + struct wlr_xdg_surface *surface = wlr_xdg_surface_from_resource(resource); + if (surface == NULL) { + return; + } + + if (surface->role == WLR_XDG_SURFACE_ROLE_NONE) { + wl_resource_post_error(surface->resource, + XDG_SURFACE_ERROR_NOT_CONSTRUCTED, + "xdg_surface must have a role"); + return; + } + + // First find the ack'ed configure + bool found = false; + struct wlr_xdg_surface_configure *configure, *tmp; + wl_list_for_each(configure, &surface->configure_list, link) { + if (configure->serial == serial) { + found = true; + break; + } + } + if (!found) { + wl_resource_post_error(surface->client->resource, + XDG_WM_BASE_ERROR_INVALID_SURFACE_STATE, + "wrong configure serial: %u", serial); + return; + } + // Then remove old configures from the list + wl_list_for_each_safe(configure, tmp, &surface->configure_list, link) { + if (configure->serial == serial) { + break; + } + wl_signal_emit_mutable(&surface->events.ack_configure, configure); + xdg_surface_configure_destroy(configure); + } + + switch (surface->role) { + case WLR_XDG_SURFACE_ROLE_NONE: + assert(0 && "not reached"); + break; + case WLR_XDG_SURFACE_ROLE_TOPLEVEL: + if (surface->toplevel != NULL) { + handle_xdg_toplevel_ack_configure(surface->toplevel, + configure->toplevel_configure); + } + break; + case WLR_XDG_SURFACE_ROLE_POPUP: + if (surface->popup != NULL) { + handle_xdg_popup_ack_configure(surface->popup, + configure->popup_configure); + } + break; + } + + surface->configured = true; + surface->pending.configure_serial = serial; + + wl_signal_emit_mutable(&surface->events.ack_configure, configure); + xdg_surface_configure_destroy(configure); +} + +static void surface_send_configure(void *user_data) { + struct wlr_xdg_surface *surface = user_data; + + surface->configure_idle = NULL; + + struct wlr_xdg_surface_configure *configure = calloc(1, sizeof(*configure)); + if (configure == NULL) { + wl_client_post_no_memory(surface->client->client); + return; + } + + wl_list_insert(surface->configure_list.prev, &configure->link); + configure->serial = surface->scheduled_serial; + configure->surface = surface; + + switch (surface->role) { + case WLR_XDG_SURFACE_ROLE_NONE: + assert(0 && "not reached"); + break; + case WLR_XDG_SURFACE_ROLE_TOPLEVEL: + if (surface->toplevel != NULL) { + configure->toplevel_configure = + send_xdg_toplevel_configure(surface->toplevel); + } + break; + case WLR_XDG_SURFACE_ROLE_POPUP: + if (surface->popup != NULL) { + configure->popup_configure = + send_xdg_popup_configure(surface->popup); + } + break; + } + + wl_signal_emit_mutable(&surface->events.configure, configure); + + xdg_surface_send_configure(surface->resource, configure->serial); +} + +uint32_t wlr_xdg_surface_schedule_configure(struct wlr_xdg_surface *surface) { + struct wl_display *display = wl_client_get_display(surface->client->client); + struct wl_event_loop *loop = wl_display_get_event_loop(display); + + assert(surface->initialized); + + if (surface->configure_idle == NULL) { + surface->scheduled_serial = wl_display_next_serial(display); + surface->configure_idle = wl_event_loop_add_idle(loop, + surface_send_configure, surface); + if (surface->configure_idle == NULL) { + wl_client_post_no_memory(surface->client->client); + } + } + return surface->scheduled_serial; +} + +static void xdg_surface_handle_get_popup(struct wl_client *client, + struct wl_resource *resource, uint32_t id, + struct wl_resource *parent_resource, + struct wl_resource *positioner_resource) { + struct wlr_xdg_surface *xdg_surface = + wlr_xdg_surface_from_resource(resource); + assert(xdg_surface != NULL); + struct wlr_xdg_surface *parent = NULL; + if (parent_resource != NULL) { + parent = wlr_xdg_surface_from_resource(parent_resource); + } + struct wlr_xdg_positioner *positioner = + wlr_xdg_positioner_from_resource(positioner_resource); + create_xdg_popup(xdg_surface, parent, positioner, id); +} + +static void xdg_surface_handle_get_toplevel(struct wl_client *client, + struct wl_resource *resource, uint32_t id) { + struct wlr_xdg_surface *xdg_surface = + wlr_xdg_surface_from_resource(resource); + assert(xdg_surface != NULL); + create_xdg_toplevel(xdg_surface, id); +} + +static void xdg_surface_handle_set_window_geometry(struct wl_client *client, + struct wl_resource *resource, int32_t x, int32_t y, int32_t width, + int32_t height) { + struct wlr_xdg_surface *surface = wlr_xdg_surface_from_resource(resource); + assert(surface != NULL); + + if (surface->role == WLR_XDG_SURFACE_ROLE_NONE) { + wl_resource_post_error(surface->resource, + XDG_SURFACE_ERROR_NOT_CONSTRUCTED, + "xdg_surface must have a role"); + return; + } + + if (width <= 0 || height <= 0) { + wl_resource_post_error(resource, XDG_SURFACE_ERROR_INVALID_SIZE, + "Tried to set invalid xdg-surface geometry"); + return; + } + + surface->pending.committed |= WLR_XDG_SURFACE_STATE_WINDOW_GEOMETRY; + surface->pending.geometry.x = x; + surface->pending.geometry.y = y; + surface->pending.geometry.width = width; + surface->pending.geometry.height = height; +} + +static void xdg_surface_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_xdg_surface *surface = wlr_xdg_surface_from_resource(resource); + if (surface == NULL) { + return; + } + + if (surface->role_resource != NULL) { + wl_resource_post_error(resource, + XDG_SURFACE_ERROR_DEFUNCT_ROLE_OBJECT, + "surface was destroyed before its role object"); + return; + } + + wl_resource_destroy(resource); +} + +static const struct xdg_surface_interface xdg_surface_implementation = { + .destroy = xdg_surface_handle_destroy, + .get_toplevel = xdg_surface_handle_get_toplevel, + .get_popup = xdg_surface_handle_get_popup, + .ack_configure = xdg_surface_handle_ack_configure, + .set_window_geometry = xdg_surface_handle_set_window_geometry, +}; + +// The window geometry is updated on commit, unless the commit is going to map +// the surface, in which case it's updated on map, so that subsurfaces are +// mapped and surface extents are computed correctly. +static void update_geometry(struct wlr_xdg_surface *surface) { + if (!wlr_box_empty(&surface->current.geometry)) { + if ((surface->current.committed & WLR_XDG_SURFACE_STATE_WINDOW_GEOMETRY) != 0) { + struct wlr_box *geom = &surface->geometry; + wlr_surface_get_extents(surface->surface, geom); + + wlr_box_intersection(geom, geom, &surface->current.geometry); + if (wlr_box_empty(geom)) { + wlr_log(WLR_INFO, + "A client has committed an invalid effective window geometry (%d,%d %dx%d); " + "this will result in client disconnection in the future", + geom->x, geom->y, geom->width, geom->height); + + // Fall back to the explicitly set window geometry as extents could be empty which + // would result in strange state when the client commits a buffer later + *geom = surface->current.geometry; + } + } + } else { + wlr_surface_get_extents(surface->surface, &surface->geometry); + } +} + +static void xdg_surface_role_client_commit(struct wlr_surface *wlr_surface) { + struct wlr_xdg_surface *surface = wlr_xdg_surface_try_from_wlr_surface(wlr_surface); + assert(surface != NULL); + + if (wlr_surface_state_has_buffer(&wlr_surface->pending) && !surface->configured) { + wlr_surface_reject_pending(wlr_surface, surface->resource, + XDG_SURFACE_ERROR_UNCONFIGURED_BUFFER, "xdg_surface has never been configured"); + return; + } + + if (surface->role_resource == NULL) { + wlr_surface_reject_pending(wlr_surface, surface->resource, + XDG_SURFACE_ERROR_NOT_CONSTRUCTED, "xdg_surface must have a role object"); + return; + } + + switch (surface->role) { + case WLR_XDG_SURFACE_ROLE_NONE: + assert(0 && "not reached"); + return; + case WLR_XDG_SURFACE_ROLE_TOPLEVEL: + if (surface->toplevel != NULL) { + handle_xdg_toplevel_client_commit(surface->toplevel); + } + break; + case WLR_XDG_SURFACE_ROLE_POPUP: + if (surface->popup != NULL) { + handle_xdg_popup_client_commit(surface->popup); + } + break; + } +} + +static void xdg_surface_role_commit(struct wlr_surface *wlr_surface) { + struct wlr_xdg_surface *surface = wlr_xdg_surface_try_from_wlr_surface(wlr_surface); + assert(surface != NULL); + + if (surface->surface->unmap_commit) { + reset_xdg_surface_role_object(surface); + reset_xdg_surface(surface); + + assert(!surface->initial_commit); + surface->initial_commit = false; + } else { + surface->initial_commit = !surface->initialized; + surface->initialized = true; + } + + switch (surface->role) { + case WLR_XDG_SURFACE_ROLE_NONE: + assert(0 && "not reached"); + return; + case WLR_XDG_SURFACE_ROLE_TOPLEVEL: + if (surface->toplevel == NULL) { + return; + } + break; + case WLR_XDG_SURFACE_ROLE_POPUP: + if (surface->popup == NULL) { + return; + } + break; + } + + if (!wlr_surface->mapped && wlr_surface_has_buffer(wlr_surface)) { + wlr_surface_map(wlr_surface); + } else { + update_geometry(surface); + } +} + +static void xdg_surface_role_map(struct wlr_surface *wlr_surface) { + struct wlr_xdg_surface *surface = wlr_xdg_surface_try_from_wlr_surface(wlr_surface); + assert(surface != NULL); + + update_geometry(surface); +} + +static void xdg_surface_role_destroy(struct wlr_surface *wlr_surface) { + struct wlr_xdg_surface *surface = wlr_xdg_surface_try_from_wlr_surface(wlr_surface); + if (surface == NULL) { + // This is the only time xdg_surface can be inert + return; + } + + destroy_xdg_surface(surface); +} + +static const struct wlr_surface_role xdg_surface_role = { + .name = "xdg_surface", + .client_commit = xdg_surface_role_client_commit, + .commit = xdg_surface_role_commit, + .map = xdg_surface_role_map, + .destroy = xdg_surface_role_destroy, +}; + +static void surface_synced_move_state(void *_dst, void *_src) { + struct wlr_xdg_surface_state *dst = _dst, *src = _src; + *dst = *src; + src->committed = 0; +} + +static const struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(struct wlr_xdg_surface_state), + .move_state = surface_synced_move_state, +}; + +struct wlr_xdg_surface *wlr_xdg_surface_try_from_wlr_surface( + struct wlr_surface *surface) { + if (surface->role != &xdg_surface_role || surface->role_resource == NULL) { + return NULL; + } + return wlr_xdg_surface_from_resource(surface->role_resource); +} + +void create_xdg_surface(struct wlr_xdg_client *client, struct wlr_surface *wlr_surface, + uint32_t id) { + if (!wlr_surface_set_role(wlr_surface, &xdg_surface_role, client->resource, + XDG_WM_BASE_ERROR_ROLE)) { + return; + } + + if (wlr_surface_has_buffer(wlr_surface)) { + wl_resource_post_error(client->resource, + XDG_SURFACE_ERROR_UNCONFIGURED_BUFFER, + "xdg_surface must not have a buffer at creation"); + return; + } + + struct wlr_xdg_surface *surface = calloc(1, sizeof(*surface)); + if (surface == NULL) { + wl_client_post_no_memory(client->client); + return; + } + + if (!wlr_surface_synced_init(&surface->synced, wlr_surface, + &surface_synced_impl, &surface->pending, &surface->current)) { + goto error_surface; + } + + surface->client = client; + surface->role = WLR_XDG_SURFACE_ROLE_NONE; + surface->surface = wlr_surface; + surface->resource = wl_resource_create(client->client, + &xdg_surface_interface, wl_resource_get_version(client->resource), + id); + if (surface->resource == NULL) { + goto error_synced; + } + + wl_list_init(&surface->configure_list); + wl_list_init(&surface->popups); + + wl_signal_init(&surface->events.destroy); + wl_signal_init(&surface->events.ping_timeout); + wl_signal_init(&surface->events.new_popup); + wl_signal_init(&surface->events.configure); + wl_signal_init(&surface->events.ack_configure); + + wlr_log(WLR_DEBUG, "new xdg_surface %p (res %p)", surface, + surface->resource); + wl_resource_set_implementation(surface->resource, + &xdg_surface_implementation, surface, NULL); + wl_list_insert(&client->surfaces, &surface->link); + + wlr_surface_set_role_object(wlr_surface, surface->resource); + + wl_signal_emit_mutable(&surface->client->shell->events.new_surface, surface); + + return; + +error_synced: + wlr_surface_synced_finish(&surface->synced); +error_surface: + free(surface); + wl_client_post_no_memory(client->client); +} + +bool set_xdg_surface_role(struct wlr_xdg_surface *surface, enum wlr_xdg_surface_role role) { + assert(role != WLR_XDG_SURFACE_ROLE_NONE); + + static const char *role_names[] = { + [WLR_XDG_SURFACE_ROLE_TOPLEVEL] = "xdg_toplevel", + [WLR_XDG_SURFACE_ROLE_POPUP] = "xdg_popup", + }; + + if (surface->role != WLR_XDG_SURFACE_ROLE_NONE && surface->role != role) { + wl_resource_post_error(surface->client->resource, XDG_WM_BASE_ERROR_ROLE, + "Cannot assign role %s to xdg_surface@%" PRIu32 ", already has role %s", + role_names[role], wl_resource_get_id(surface->resource), + role_names[surface->role]); + return false; + } + if (surface->role_resource != NULL) { + wl_resource_post_error(surface->client->resource, XDG_WM_BASE_ERROR_ROLE, + "Cannot reassign role %s to xdg_surface@%" PRIu32 ", role object still exists", + role_names[role], wl_resource_get_id(surface->resource)); + return false; + } + + surface->role = role; + return true; +} + +static void destroy_xdg_surface_role_object(struct wlr_xdg_surface *surface) { + if (surface->role_resource == NULL) { + return; + } + + switch (surface->role) { + case WLR_XDG_SURFACE_ROLE_NONE: + assert(0 && "not reached"); + break; + case WLR_XDG_SURFACE_ROLE_TOPLEVEL: + if (surface->toplevel != NULL) { + destroy_xdg_toplevel(surface->toplevel); + } + break; + case WLR_XDG_SURFACE_ROLE_POPUP: + if (surface->popup != NULL) { + destroy_xdg_popup(surface->popup); + } + break; + } + + surface->role_resource = NULL; + wl_list_remove(&surface->role_resource_destroy.link); + wl_list_init(&surface->role_resource_destroy.link); +} + +static void xdg_surface_handle_role_resource_destroy(struct wl_listener *listener, void *data) { + struct wlr_xdg_surface *surface = wl_container_of(listener, surface, role_resource_destroy); + destroy_xdg_surface_role_object(surface); + reset_xdg_surface(surface); +} + +void set_xdg_surface_role_object(struct wlr_xdg_surface *surface, + struct wl_resource *role_resource) { + assert(surface->role != WLR_XDG_SURFACE_ROLE_NONE); + assert(surface->role_resource == NULL); + assert(role_resource != NULL); + surface->role_resource = role_resource; + surface->role_resource_destroy.notify = xdg_surface_handle_role_resource_destroy; + wl_resource_add_destroy_listener(role_resource, &surface->role_resource_destroy); +} + +void destroy_xdg_surface(struct wlr_xdg_surface *surface) { + destroy_xdg_surface_role_object(surface); + reset_xdg_surface(surface); + + wl_signal_emit_mutable(&surface->events.destroy, NULL); + + assert(wl_list_empty(&surface->events.destroy.listener_list)); + assert(wl_list_empty(&surface->events.ping_timeout.listener_list)); + assert(wl_list_empty(&surface->events.new_popup.listener_list)); + assert(wl_list_empty(&surface->events.configure.listener_list)); + assert(wl_list_empty(&surface->events.ack_configure.listener_list)); + + wl_list_remove(&surface->link); + wlr_surface_synced_finish(&surface->synced); + wl_resource_set_user_data(surface->resource, NULL); + free(surface); +} + +struct wlr_xdg_surface *wlr_xdg_surface_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &xdg_surface_interface, + &xdg_surface_implementation)); + return wl_resource_get_user_data(resource); +} + +void wlr_xdg_surface_ping(struct wlr_xdg_surface *surface) { + if (surface->client->ping_serial != 0) { + // already pinged + return; + } + + surface->client->ping_serial = + wl_display_next_serial(wl_client_get_display(surface->client->client)); + wl_event_source_timer_update(surface->client->ping_timer, + surface->client->shell->ping_timeout); + xdg_wm_base_send_ping(surface->client->resource, + surface->client->ping_serial); +} + +void wlr_xdg_popup_get_position(struct wlr_xdg_popup *popup, + double *popup_sx, double *popup_sy) { + struct wlr_xdg_surface *parent = wlr_xdg_surface_try_from_wlr_surface(popup->parent); + assert(parent != NULL); + *popup_sx = parent->geometry.x + popup->current.geometry.x - popup->base->geometry.x; + *popup_sy = parent->geometry.y + popup->current.geometry.y - popup->base->geometry.y; +} + +struct wlr_surface *wlr_xdg_surface_surface_at( + struct wlr_xdg_surface *surface, double sx, double sy, + double *sub_x, double *sub_y) { + struct wlr_surface *sub = wlr_xdg_surface_popup_surface_at(surface, sx, sy, + sub_x, sub_y); + if (sub != NULL) { + return sub; + } + return wlr_surface_surface_at(surface->surface, sx, sy, sub_x, sub_y); +} + +struct wlr_surface *wlr_xdg_surface_popup_surface_at( + struct wlr_xdg_surface *surface, double sx, double sy, + double *sub_x, double *sub_y) { + struct wlr_xdg_popup *popup; + wl_list_for_each(popup, &surface->popups, link) { + if (!popup->base->surface->mapped) { + continue; + } + + double popup_sx, popup_sy; + wlr_xdg_popup_get_position(popup, &popup_sx, &popup_sy); + + struct wlr_surface *sub = wlr_xdg_surface_surface_at( + popup->base, sx - popup_sx, sy - popup_sy, + sub_x, sub_y); + if (sub != NULL) { + return sub; + } + } + + return NULL; +} + +struct xdg_surface_iterator_data { + wlr_surface_iterator_func_t user_iterator; + void *user_data; + int x, y; +}; + +static void xdg_surface_iterator(struct wlr_surface *surface, + int sx, int sy, void *data) { + struct xdg_surface_iterator_data *iter_data = data; + iter_data->user_iterator(surface, iter_data->x + sx, iter_data->y + sy, + iter_data->user_data); +} + +static void xdg_surface_for_each_popup_surface(struct wlr_xdg_surface *surface, + int x, int y, wlr_surface_iterator_func_t iterator, void *user_data) { + struct wlr_xdg_popup *popup; + wl_list_for_each(popup, &surface->popups, link) { + if (!popup->base->surface->mapped) { + continue; + } + + double popup_sx, popup_sy; + wlr_xdg_popup_get_position(popup, &popup_sx, &popup_sy); + + struct xdg_surface_iterator_data data = { + .user_iterator = iterator, + .user_data = user_data, + .x = x + popup_sx, .y = y + popup_sy, + }; + wlr_surface_for_each_surface(popup->base->surface, + xdg_surface_iterator, &data); + + xdg_surface_for_each_popup_surface(popup->base, + x + popup_sx, y + popup_sy, iterator, user_data); + } +} + +void wlr_xdg_surface_for_each_surface(struct wlr_xdg_surface *surface, + wlr_surface_iterator_func_t iterator, void *user_data) { + wlr_surface_for_each_surface(surface->surface, iterator, user_data); + xdg_surface_for_each_popup_surface(surface, 0, 0, iterator, user_data); +} + +void wlr_xdg_surface_for_each_popup_surface(struct wlr_xdg_surface *surface, + wlr_surface_iterator_func_t iterator, void *user_data) { + xdg_surface_for_each_popup_surface(surface, 0, 0, iterator, user_data); +} diff --git a/3rdparty/wlroots/types/xdg_shell/wlr_xdg_toplevel.c b/3rdparty/wlroots/types/xdg_shell/wlr_xdg_toplevel.c new file mode 100644 index 0000000000..1b33916e7e --- /dev/null +++ b/3rdparty/wlroots/types/xdg_shell/wlr_xdg_toplevel.c @@ -0,0 +1,666 @@ +#include +#include +#include +#include +#include +#include +#include "types/wlr_xdg_shell.h" +#include "util/utf8.h" + +void handle_xdg_toplevel_ack_configure( + struct wlr_xdg_toplevel *toplevel, + struct wlr_xdg_toplevel_configure *configure) { + toplevel->pending.maximized = configure->maximized; + toplevel->pending.fullscreen = configure->fullscreen; + toplevel->pending.resizing = configure->resizing; + toplevel->pending.activated = configure->activated; + toplevel->pending.tiled = configure->tiled; + toplevel->pending.constrained = configure->constrained; + toplevel->pending.suspended = configure->suspended; + + toplevel->pending.width = configure->width; + toplevel->pending.height = configure->height; +} + +struct wlr_xdg_toplevel_configure *send_xdg_toplevel_configure( + struct wlr_xdg_toplevel *toplevel) { + struct wlr_xdg_toplevel_configure *configure = + calloc(1, sizeof(*configure)); + if (configure == NULL) { + wlr_log(WLR_ERROR, "Allocation failed"); + wl_resource_post_no_memory(toplevel->resource); + return NULL; + } + *configure = toplevel->scheduled; + + uint32_t version = wl_resource_get_version(toplevel->resource); + + if ((configure->fields & WLR_XDG_TOPLEVEL_CONFIGURE_BOUNDS) && + version >= XDG_TOPLEVEL_CONFIGURE_BOUNDS_SINCE_VERSION) { + xdg_toplevel_send_configure_bounds(toplevel->resource, + configure->bounds.width, configure->bounds.height); + } + + if ((configure->fields & WLR_XDG_TOPLEVEL_CONFIGURE_WM_CAPABILITIES) && + version >= XDG_TOPLEVEL_WM_CAPABILITIES_SINCE_VERSION) { + size_t caps_len = 0; + uint32_t caps[32]; + if (configure->wm_capabilities & WLR_XDG_TOPLEVEL_WM_CAPABILITIES_WINDOW_MENU) { + caps[caps_len++] = XDG_TOPLEVEL_WM_CAPABILITIES_WINDOW_MENU; + } + if (configure->wm_capabilities & WLR_XDG_TOPLEVEL_WM_CAPABILITIES_MAXIMIZE) { + caps[caps_len++] = XDG_TOPLEVEL_WM_CAPABILITIES_MAXIMIZE; + } + if (configure->wm_capabilities & WLR_XDG_TOPLEVEL_WM_CAPABILITIES_FULLSCREEN) { + caps[caps_len++] = XDG_TOPLEVEL_WM_CAPABILITIES_FULLSCREEN; + } + if (configure->wm_capabilities & WLR_XDG_TOPLEVEL_WM_CAPABILITIES_MINIMIZE) { + caps[caps_len++] = XDG_TOPLEVEL_WM_CAPABILITIES_MINIMIZE; + } + assert(caps_len <= sizeof(caps) / sizeof(caps[0])); + + struct wl_array caps_array = { + .size = caps_len * sizeof(caps[0]), + .data = caps, + }; + xdg_toplevel_send_wm_capabilities(toplevel->resource, &caps_array); + } + + size_t nstates = 0; + uint32_t states[32]; + if (configure->maximized) { + states[nstates++] = XDG_TOPLEVEL_STATE_MAXIMIZED; + } + if (configure->fullscreen) { + states[nstates++] = XDG_TOPLEVEL_STATE_FULLSCREEN; + } + if (configure->resizing) { + states[nstates++] = XDG_TOPLEVEL_STATE_RESIZING; + } + if (configure->activated) { + states[nstates++] = XDG_TOPLEVEL_STATE_ACTIVATED; + } + if (configure->tiled && version >= XDG_TOPLEVEL_STATE_TILED_LEFT_SINCE_VERSION) { + static const struct { + enum wlr_edges edge; + enum xdg_toplevel_state state; + } tiled[] = { + { WLR_EDGE_LEFT, XDG_TOPLEVEL_STATE_TILED_LEFT }, + { WLR_EDGE_RIGHT, XDG_TOPLEVEL_STATE_TILED_RIGHT }, + { WLR_EDGE_TOP, XDG_TOPLEVEL_STATE_TILED_TOP }, + { WLR_EDGE_BOTTOM, XDG_TOPLEVEL_STATE_TILED_BOTTOM }, + }; + + for (size_t i = 0; i < sizeof(tiled) / sizeof(tiled[0]); ++i) { + if ((configure->tiled & tiled[i].edge) == 0) { + continue; + } + states[nstates++] = tiled[i].state; + } + } + if (configure->suspended && version >= XDG_TOPLEVEL_STATE_SUSPENDED_SINCE_VERSION) { + states[nstates++] = XDG_TOPLEVEL_STATE_SUSPENDED; + } + if (configure->constrained && version >= XDG_TOPLEVEL_STATE_CONSTRAINED_LEFT_SINCE_VERSION) { + static const struct { + enum wlr_edges edge; + enum xdg_toplevel_state state; + } constrained[] = { + { WLR_EDGE_LEFT, XDG_TOPLEVEL_STATE_CONSTRAINED_LEFT }, + { WLR_EDGE_RIGHT, XDG_TOPLEVEL_STATE_CONSTRAINED_RIGHT }, + { WLR_EDGE_TOP, XDG_TOPLEVEL_STATE_CONSTRAINED_TOP }, + { WLR_EDGE_BOTTOM, XDG_TOPLEVEL_STATE_CONSTRAINED_BOTTOM }, + }; + + for (size_t i = 0; i < sizeof(constrained) / sizeof(constrained[0]); ++i) { + if ((configure->constrained & constrained[i].edge) == 0) { + continue; + } + states[nstates++] = constrained[i].state; + } + } + assert(nstates <= sizeof(states) / sizeof(states[0])); + + int32_t width = configure->width; + int32_t height = configure->height; + struct wl_array wl_states = { + .size = nstates * sizeof(states[0]), + .data = states, + }; + xdg_toplevel_send_configure(toplevel->resource, + width, height, &wl_states); + + toplevel->scheduled.fields = 0; + + return configure; +} + +void handle_xdg_toplevel_client_commit(struct wlr_xdg_toplevel *toplevel) { + struct wlr_xdg_toplevel_state *pending = &toplevel->pending; + + // 1) Negative values are prohibited + // 2) If both min and max are set (aren't 0), min ≤ max + if (pending->min_width < 0 || pending->min_height < 0 || + pending->max_width < 0 || pending->max_height < 0 || + (pending->max_width != 0 && pending->max_width < pending->min_width) || + (pending->max_height != 0 && pending->max_height < pending->min_height)) { + wlr_surface_reject_pending(toplevel->base->surface, toplevel->resource, + XDG_TOPLEVEL_ERROR_INVALID_SIZE, "client provided an invalid min or max size"); + return; + } +} + +static const struct xdg_toplevel_interface xdg_toplevel_implementation; + +struct wlr_xdg_toplevel *wlr_xdg_toplevel_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, &xdg_toplevel_interface, + &xdg_toplevel_implementation)); + return wl_resource_get_user_data(resource); +} + +struct wlr_xdg_toplevel *wlr_xdg_toplevel_try_from_wlr_surface(struct wlr_surface *surface) { + struct wlr_xdg_surface *xdg_surface = wlr_xdg_surface_try_from_wlr_surface(surface); + if (xdg_surface == NULL || xdg_surface->role != WLR_XDG_SURFACE_ROLE_TOPLEVEL) { + return NULL; + } + return xdg_surface->toplevel; +} + +static void handle_parent_unmap(struct wl_listener *listener, void *data) { + struct wlr_xdg_toplevel *toplevel = + wl_container_of(listener, toplevel, parent_unmap); + if (!wlr_xdg_toplevel_set_parent(toplevel, toplevel->parent->parent)) { + assert(0 && "Unreachable"); + } +} + +bool wlr_xdg_toplevel_set_parent(struct wlr_xdg_toplevel *toplevel, + struct wlr_xdg_toplevel *parent) { + // Check for a loop + struct wlr_xdg_toplevel *iter = parent; + while (iter != NULL) { + if (iter == toplevel) { + return false; + } + iter = iter->parent; + } + + if (toplevel->parent != NULL) { + wl_list_remove(&toplevel->parent_unmap.link); + } + + if (parent != NULL && parent->base->surface->mapped) { + toplevel->parent = parent; + toplevel->parent_unmap.notify = handle_parent_unmap; + wl_signal_add(&toplevel->parent->base->surface->events.unmap, + &toplevel->parent_unmap); + } else { + toplevel->parent = NULL; + } + + wl_signal_emit_mutable(&toplevel->events.set_parent, NULL); + return true; +} + +static void xdg_toplevel_handle_set_parent(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *parent_resource) { + struct wlr_xdg_toplevel *toplevel = + wlr_xdg_toplevel_from_resource(resource); + struct wlr_xdg_toplevel *parent = NULL; + + if (parent_resource != NULL) { + parent = wlr_xdg_toplevel_from_resource(parent_resource); + } + + if (!wlr_xdg_toplevel_set_parent(toplevel, parent)) { + wl_resource_post_error(resource, XDG_TOPLEVEL_ERROR_INVALID_PARENT, + "a toplevel cannot be a parent of itself or its ancestor"); + } +} + +static void xdg_toplevel_handle_set_title(struct wl_client *client, + struct wl_resource *resource, const char *title) { + struct wlr_xdg_toplevel *toplevel = + wlr_xdg_toplevel_from_resource(resource); + char *tmp; + + if (!is_utf8(title)) { + // TODO: update when xdg_toplevel has a dedicated error code for this + wl_resource_post_error(resource, (uint32_t)-1, "xdg_toplevel title is not valid UTF-8"); + return; + } + + tmp = strdup(title); + if (tmp == NULL) { + wl_resource_post_no_memory(resource); + return; + } + + free(toplevel->title); + toplevel->title = tmp; + wl_signal_emit_mutable(&toplevel->events.set_title, NULL); +} + +static void xdg_toplevel_handle_set_app_id(struct wl_client *client, + struct wl_resource *resource, const char *app_id) { + struct wlr_xdg_toplevel *toplevel = + wlr_xdg_toplevel_from_resource(resource); + char *tmp; + + tmp = strdup(app_id); + if (tmp == NULL) { + wl_resource_post_no_memory(resource); + return; + } + + free(toplevel->app_id); + toplevel->app_id = tmp; + wl_signal_emit_mutable(&toplevel->events.set_app_id, NULL); +} + +static void xdg_toplevel_handle_show_window_menu(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *seat_resource, + uint32_t serial, int32_t x, int32_t y) { + struct wlr_xdg_toplevel *toplevel = + wlr_xdg_toplevel_from_resource(resource); + struct wlr_seat_client *seat = + wlr_seat_client_from_resource(seat_resource); + + if (!toplevel->base->configured) { + wl_resource_post_error(toplevel->base->resource, + XDG_SURFACE_ERROR_NOT_CONSTRUCTED, + "surface has not been configured yet"); + return; + } + + struct wlr_xdg_toplevel_show_window_menu_event event = { + .toplevel = toplevel, + .seat = seat, + .serial = serial, + .x = x, + .y = y, + }; + + wl_signal_emit_mutable(&toplevel->events.request_show_window_menu, &event); +} + +static void xdg_toplevel_handle_move(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *seat_resource, + uint32_t serial) { + struct wlr_xdg_toplevel *toplevel = + wlr_xdg_toplevel_from_resource(resource); + struct wlr_seat_client *seat = + wlr_seat_client_from_resource(seat_resource); + + if (!toplevel->base->configured) { + wl_resource_post_error(toplevel->base->resource, + XDG_SURFACE_ERROR_NOT_CONSTRUCTED, + "surface has not been configured yet"); + return; + } + + struct wlr_xdg_toplevel_move_event event = { + .toplevel = toplevel, + .seat = seat, + .serial = serial, + }; + + wl_signal_emit_mutable(&toplevel->events.request_move, &event); +} + +static void xdg_toplevel_handle_resize(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *seat_resource, + uint32_t serial, uint32_t edges) { + struct wlr_xdg_toplevel *toplevel = + wlr_xdg_toplevel_from_resource(resource); + struct wlr_seat_client *seat = + wlr_seat_client_from_resource(seat_resource); + + uint32_t version = wl_resource_get_version(toplevel->base->resource); + if (!xdg_toplevel_resize_edge_is_valid(edges, version)) { + wl_resource_post_error(toplevel->base->resource, + XDG_TOPLEVEL_ERROR_INVALID_RESIZE_EDGE, + "provided value is not a valid variant of the resize_edge enum"); + return; + } + + if (!toplevel->base->configured) { + wl_resource_post_error(toplevel->base->resource, + XDG_SURFACE_ERROR_NOT_CONSTRUCTED, + "surface has not been configured yet"); + return; + } + + struct wlr_xdg_toplevel_resize_event event = { + .toplevel = toplevel, + .seat = seat, + .serial = serial, + .edges = edges, + }; + + wl_signal_emit_mutable(&toplevel->events.request_resize, &event); +} + +static void xdg_toplevel_handle_set_max_size(struct wl_client *client, + struct wl_resource *resource, int32_t width, int32_t height) { + struct wlr_xdg_toplevel *toplevel = + wlr_xdg_toplevel_from_resource(resource); + toplevel->pending.max_width = width; + toplevel->pending.max_height = height; +} + +static void xdg_toplevel_handle_set_min_size(struct wl_client *client, + struct wl_resource *resource, int32_t width, int32_t height) { + struct wlr_xdg_toplevel *toplevel = + wlr_xdg_toplevel_from_resource(resource); + toplevel->pending.min_width = width; + toplevel->pending.min_height = height; +} + +static void xdg_toplevel_handle_set_maximized(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_xdg_toplevel *toplevel = + wlr_xdg_toplevel_from_resource(resource); + toplevel->requested.maximized = true; + wl_signal_emit_mutable(&toplevel->events.request_maximize, NULL); +} + +static void xdg_toplevel_handle_unset_maximized(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_xdg_toplevel *toplevel = + wlr_xdg_toplevel_from_resource(resource); + toplevel->requested.maximized = false; + wl_signal_emit_mutable(&toplevel->events.request_maximize, NULL); +} + +static void handle_fullscreen_output_destroy(struct wl_listener *listener, + void *data) { + struct wlr_xdg_toplevel_requested *req = + wl_container_of(listener, req, fullscreen_output_destroy); + req->fullscreen_output = NULL; + wl_list_remove(&req->fullscreen_output_destroy.link); +} + +static void store_fullscreen_requested(struct wlr_xdg_toplevel *toplevel, + bool fullscreen, struct wlr_output *output) { + struct wlr_xdg_toplevel_requested *req = &toplevel->requested; + req->fullscreen = fullscreen; + if (req->fullscreen_output) { + wl_list_remove(&req->fullscreen_output_destroy.link); + } + req->fullscreen_output = output; + if (req->fullscreen_output) { + req->fullscreen_output_destroy.notify = + handle_fullscreen_output_destroy; + wl_signal_add(&req->fullscreen_output->events.destroy, + &req->fullscreen_output_destroy); + } +} + +static void xdg_toplevel_handle_set_fullscreen(struct wl_client *client, + struct wl_resource *resource, struct wl_resource *output_resource) { + struct wlr_xdg_toplevel *toplevel = + wlr_xdg_toplevel_from_resource(resource); + + struct wlr_output *output = NULL; + if (output_resource != NULL) { + output = wlr_output_from_resource(output_resource); + } + + store_fullscreen_requested(toplevel, true, output); + + wl_signal_emit_mutable(&toplevel->events.request_fullscreen, NULL); +} + +static void xdg_toplevel_handle_unset_fullscreen(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_xdg_toplevel *toplevel = + wlr_xdg_toplevel_from_resource(resource); + + store_fullscreen_requested(toplevel, false, NULL); + + wl_signal_emit_mutable(&toplevel->events.request_fullscreen, NULL); +} + +static void xdg_toplevel_handle_set_minimized(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_xdg_toplevel *toplevel = + wlr_xdg_toplevel_from_resource(resource); + toplevel->requested.minimized = true; + wl_signal_emit_mutable(&toplevel->events.request_minimize, NULL); +} + +static void xdg_toplevel_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct xdg_toplevel_interface xdg_toplevel_implementation = { + .destroy = xdg_toplevel_handle_destroy, + .set_parent = xdg_toplevel_handle_set_parent, + .set_title = xdg_toplevel_handle_set_title, + .set_app_id = xdg_toplevel_handle_set_app_id, + .show_window_menu = xdg_toplevel_handle_show_window_menu, + .move = xdg_toplevel_handle_move, + .resize = xdg_toplevel_handle_resize, + .set_max_size = xdg_toplevel_handle_set_max_size, + .set_min_size = xdg_toplevel_handle_set_min_size, + .set_maximized = xdg_toplevel_handle_set_maximized, + .unset_maximized = xdg_toplevel_handle_unset_maximized, + .set_fullscreen = xdg_toplevel_handle_set_fullscreen, + .unset_fullscreen = xdg_toplevel_handle_unset_fullscreen, + .set_minimized = xdg_toplevel_handle_set_minimized, +}; + +static const struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(struct wlr_xdg_toplevel_state), +}; + +void create_xdg_toplevel(struct wlr_xdg_surface *surface, + uint32_t id) { + if (!set_xdg_surface_role(surface, WLR_XDG_SURFACE_ROLE_TOPLEVEL)) { + return; + } + + assert(surface->toplevel == NULL); + surface->toplevel = calloc(1, sizeof(*surface->toplevel)); + if (surface->toplevel == NULL) { + wl_resource_post_no_memory(surface->resource); + return; + } + surface->toplevel->base = surface; + + wl_signal_init(&surface->toplevel->events.destroy); + wl_signal_init(&surface->toplevel->events.request_maximize); + wl_signal_init(&surface->toplevel->events.request_fullscreen); + wl_signal_init(&surface->toplevel->events.request_minimize); + wl_signal_init(&surface->toplevel->events.request_move); + wl_signal_init(&surface->toplevel->events.request_resize); + wl_signal_init(&surface->toplevel->events.request_show_window_menu); + wl_signal_init(&surface->toplevel->events.set_parent); + wl_signal_init(&surface->toplevel->events.set_title); + wl_signal_init(&surface->toplevel->events.set_app_id); + + if (!wlr_surface_synced_init(&surface->toplevel->synced, surface->surface, + &surface_synced_impl, &surface->toplevel->pending, &surface->toplevel->current)) { + goto error_toplevel; + } + + surface->toplevel->resource = wl_resource_create( + surface->client->client, &xdg_toplevel_interface, + wl_resource_get_version(surface->resource), id); + if (surface->toplevel->resource == NULL) { + goto error_synced; + } + wl_resource_set_implementation(surface->toplevel->resource, + &xdg_toplevel_implementation, surface->toplevel, NULL); + + set_xdg_surface_role_object(surface, surface->toplevel->resource); + + if (surface->client->shell->version >= XDG_TOPLEVEL_WM_CAPABILITIES_SINCE_VERSION) { + // The first configure event must carry WM capabilities + surface->toplevel->scheduled.wm_capabilities = + WLR_XDG_TOPLEVEL_WM_CAPABILITIES_WINDOW_MENU | + WLR_XDG_TOPLEVEL_WM_CAPABILITIES_MAXIMIZE | + WLR_XDG_TOPLEVEL_WM_CAPABILITIES_FULLSCREEN | + WLR_XDG_TOPLEVEL_WM_CAPABILITIES_MINIMIZE; + surface->toplevel->scheduled.fields |= WLR_XDG_TOPLEVEL_CONFIGURE_WM_CAPABILITIES; + } + + wl_signal_emit_mutable(&surface->client->shell->events.new_toplevel, surface->toplevel); + + return; + +error_synced: + wlr_surface_synced_finish(&surface->toplevel->synced); +error_toplevel: + free(surface->toplevel); + surface->toplevel = NULL; + wl_resource_post_no_memory(surface->resource); +} + +void reset_xdg_toplevel(struct wlr_xdg_toplevel *toplevel) { + if (toplevel->parent) { + wl_list_remove(&toplevel->parent_unmap.link); + toplevel->parent = NULL; + } + free(toplevel->title); + toplevel->title = NULL; + free(toplevel->app_id); + toplevel->app_id = NULL; + + if (toplevel->requested.fullscreen_output) { + wl_list_remove(&toplevel->requested.fullscreen_output_destroy.link); + toplevel->requested.fullscreen_output = NULL; + } + toplevel->requested.fullscreen = false; + toplevel->requested.maximized = false; + toplevel->requested.minimized = false; +} + +void destroy_xdg_toplevel(struct wlr_xdg_toplevel *toplevel) { + wlr_surface_unmap(toplevel->base->surface); + reset_xdg_toplevel(toplevel); + + wl_signal_emit_mutable(&toplevel->events.destroy, NULL); + + assert(wl_list_empty(&toplevel->events.destroy.listener_list)); + assert(wl_list_empty(&toplevel->events.request_maximize.listener_list)); + assert(wl_list_empty(&toplevel->events.request_fullscreen.listener_list)); + assert(wl_list_empty(&toplevel->events.request_minimize.listener_list)); + assert(wl_list_empty(&toplevel->events.request_move.listener_list)); + assert(wl_list_empty(&toplevel->events.request_resize.listener_list)); + assert(wl_list_empty(&toplevel->events.request_show_window_menu.listener_list)); + assert(wl_list_empty(&toplevel->events.set_parent.listener_list)); + assert(wl_list_empty(&toplevel->events.set_title.listener_list)); + assert(wl_list_empty(&toplevel->events.set_app_id.listener_list)); + + wlr_surface_synced_finish(&toplevel->synced); + toplevel->base->toplevel = NULL; + wl_resource_set_user_data(toplevel->resource, NULL); + free(toplevel); +} + +void wlr_xdg_toplevel_send_close(struct wlr_xdg_toplevel *toplevel) { + xdg_toplevel_send_close(toplevel->resource); +} + +uint32_t wlr_xdg_toplevel_configure(struct wlr_xdg_toplevel *toplevel, + const struct wlr_xdg_toplevel_configure *configure) { + toplevel->scheduled.width = configure->width; + toplevel->scheduled.height = configure->height; + toplevel->scheduled.maximized = configure->maximized; + toplevel->scheduled.fullscreen = configure->fullscreen; + toplevel->scheduled.resizing = configure->resizing; + toplevel->scheduled.activated = configure->activated; + toplevel->scheduled.suspended = configure->suspended; + toplevel->scheduled.tiled = configure->tiled; + + if (configure->fields & WLR_XDG_TOPLEVEL_CONFIGURE_BOUNDS) { + toplevel->scheduled.fields |= WLR_XDG_TOPLEVEL_CONFIGURE_BOUNDS; + toplevel->scheduled.bounds = configure->bounds; + } + + if (configure->fields & WLR_XDG_TOPLEVEL_CONFIGURE_WM_CAPABILITIES) { + toplevel->scheduled.fields |= WLR_XDG_TOPLEVEL_CONFIGURE_WM_CAPABILITIES; + toplevel->scheduled.wm_capabilities = configure->wm_capabilities; + } + + return wlr_xdg_surface_schedule_configure(toplevel->base); +} + +uint32_t wlr_xdg_toplevel_set_size(struct wlr_xdg_toplevel *toplevel, + int32_t width, int32_t height) { + assert(width >= 0 && height >= 0); + toplevel->scheduled.width = width; + toplevel->scheduled.height = height; + return wlr_xdg_surface_schedule_configure(toplevel->base); +} + +uint32_t wlr_xdg_toplevel_set_activated(struct wlr_xdg_toplevel *toplevel, + bool activated) { + toplevel->scheduled.activated = activated; + return wlr_xdg_surface_schedule_configure(toplevel->base); +} + +uint32_t wlr_xdg_toplevel_set_maximized(struct wlr_xdg_toplevel *toplevel, + bool maximized) { + toplevel->scheduled.maximized = maximized; + return wlr_xdg_surface_schedule_configure(toplevel->base); +} + +uint32_t wlr_xdg_toplevel_set_fullscreen(struct wlr_xdg_toplevel *toplevel, + bool fullscreen) { + toplevel->scheduled.fullscreen = fullscreen; + return wlr_xdg_surface_schedule_configure(toplevel->base); +} + +uint32_t wlr_xdg_toplevel_set_resizing(struct wlr_xdg_toplevel *toplevel, + bool resizing) { + toplevel->scheduled.resizing = resizing; + return wlr_xdg_surface_schedule_configure(toplevel->base); +} + +uint32_t wlr_xdg_toplevel_set_tiled(struct wlr_xdg_toplevel *toplevel, + uint32_t tiled) { + assert(toplevel->base->client->shell->version >= + XDG_TOPLEVEL_STATE_TILED_LEFT_SINCE_VERSION); + toplevel->scheduled.tiled = tiled; + return wlr_xdg_surface_schedule_configure(toplevel->base); +} + +uint32_t wlr_xdg_toplevel_set_bounds(struct wlr_xdg_toplevel *toplevel, + int32_t width, int32_t height) { + assert(toplevel->base->client->shell->version >= + XDG_TOPLEVEL_CONFIGURE_BOUNDS_SINCE_VERSION); + assert(width >= 0 && height >= 0); + toplevel->scheduled.fields |= WLR_XDG_TOPLEVEL_CONFIGURE_BOUNDS; + toplevel->scheduled.bounds.width = width; + toplevel->scheduled.bounds.height = height; + return wlr_xdg_surface_schedule_configure(toplevel->base); +} + +uint32_t wlr_xdg_toplevel_set_wm_capabilities(struct wlr_xdg_toplevel *toplevel, + uint32_t caps) { + assert(toplevel->base->client->shell->version >= + XDG_TOPLEVEL_WM_CAPABILITIES_SINCE_VERSION); + toplevel->scheduled.fields |= WLR_XDG_TOPLEVEL_CONFIGURE_WM_CAPABILITIES; + toplevel->scheduled.wm_capabilities = caps; + return wlr_xdg_surface_schedule_configure(toplevel->base); +} + +uint32_t wlr_xdg_toplevel_set_suspended(struct wlr_xdg_toplevel *toplevel, + bool suspended) { + assert(toplevel->base->client->shell->version >= + XDG_TOPLEVEL_STATE_SUSPENDED_SINCE_VERSION); + toplevel->scheduled.suspended = suspended; + return wlr_xdg_surface_schedule_configure(toplevel->base); +} + +uint32_t wlr_xdg_toplevel_set_constrained(struct wlr_xdg_toplevel *toplevel, uint32_t constrained) { + assert(toplevel->base->client->shell->version >= + XDG_TOPLEVEL_STATE_CONSTRAINED_LEFT_SINCE_VERSION); + toplevel->scheduled.constrained = constrained; + return wlr_xdg_surface_schedule_configure(toplevel->base); +} diff --git a/3rdparty/wlroots/util/addon.c b/3rdparty/wlroots/util/addon.c new file mode 100644 index 0000000000..63bcb5b6e6 --- /dev/null +++ b/3rdparty/wlroots/util/addon.c @@ -0,0 +1,55 @@ +#include +#include +#include +#include +#include +#include + +void wlr_addon_set_init(struct wlr_addon_set *set) { + *set = (struct wlr_addon_set){0}; + wl_list_init(&set->addons); +} + +void wlr_addon_set_finish(struct wlr_addon_set *set) { + while (!wl_list_empty(&set->addons)) { + struct wl_list *link = set->addons.next; + struct wlr_addon *addon = wl_container_of(link, addon, link); + const struct wlr_addon_interface *impl = addon->impl; + addon->impl->destroy(addon); + if (set->addons.next == link) { + wlr_log(WLR_ERROR, "Dangling addon: %s", impl->name); + abort(); + } + } +} + +void wlr_addon_init(struct wlr_addon *addon, struct wlr_addon_set *set, + const void *owner, const struct wlr_addon_interface *impl) { + assert(impl); + *addon = (struct wlr_addon){ + .impl = impl, + .owner = owner, + }; + struct wlr_addon *iter; + wl_list_for_each(iter, &set->addons, link) { + if (iter->owner == addon->owner && iter->impl == addon->impl) { + assert(0 && "Can't have two addons of the same type with the same owner"); + } + } + wl_list_insert(&set->addons, &addon->link); +} + +void wlr_addon_finish(struct wlr_addon *addon) { + wl_list_remove(&addon->link); +} + +struct wlr_addon *wlr_addon_find(struct wlr_addon_set *set, const void *owner, + const struct wlr_addon_interface *impl) { + struct wlr_addon *addon; + wl_list_for_each(addon, &set->addons, link) { + if (addon->owner == owner && addon->impl == impl) { + return addon; + } + } + return NULL; +} diff --git a/3rdparty/wlroots/util/array.c b/3rdparty/wlroots/util/array.c new file mode 100644 index 0000000000..d4771e817f --- /dev/null +++ b/3rdparty/wlroots/util/array.c @@ -0,0 +1,40 @@ +#include "util/array.h" +#include +#include + +void array_remove_at(struct wl_array *arr, size_t offset, size_t size) { + assert(arr->size >= offset + size); + + char *data = arr->data; + memmove(&data[offset], &data[offset + size], arr->size - offset - size); + arr->size -= size; +} + +bool array_realloc(struct wl_array *arr, size_t size) { + // If the size is less than 1/4th of the allocation size, we shrink it. + // 1/4th is picked to provide hysteresis, without which an array with size + // arr->alloc would constantly reallocate if an element is added and then + // removed continuously. + size_t alloc; + if (arr->alloc > 0 && size > arr->alloc / 4) { + alloc = arr->alloc; + } else { + alloc = 16; + } + + while (alloc < size) { + alloc *= 2; + } + + if (alloc == arr->alloc) { + return true; + } + + void *data = realloc(arr->data, alloc); + if (data == NULL) { + return false; + } + arr->data = data; + arr->alloc = alloc; + return true; +} diff --git a/3rdparty/wlroots/util/box.c b/3rdparty/wlroots/util/box.c new file mode 100644 index 0000000000..489c5ad2e4 --- /dev/null +++ b/3rdparty/wlroots/util/box.c @@ -0,0 +1,245 @@ +#include +#include +#include +#include +#include + +static int max(int a, int b) { + return a > b ? a : b; +} + +static int min(int a, int b) { + return a < b ? a : b; +} + +void wlr_box_closest_point(const struct wlr_box *box, double x, double y, + double *dest_x, double *dest_y) { + // if box is empty, then it contains no points, so no closest point either + if (wlr_box_empty(box)) { + *dest_x = NAN; + *dest_y = NAN; + return; + } + + // Note: the width and height of the box are exclusive; that is, + // for a 100x100 box at (0,0), the point (99.9,99.9) is inside it + // while the point (100,100) is outside it. + // + // In order to be consistent with e.g. wlr_box_contains_point(), + // this function returns a point inside the bottom and right edges + // of the box by at least 1/256 of a unit (pixel). 1/256 is + // small enough to avoid a "dead zone" with high-resolution mice + // but large enough to avoid rounding to zero in wl_fixed_from_double(). + + // find the closest x point + if (x < box->x) { + *dest_x = box->x; + } else if (x > box->x + box->width - 1/256.0) { + *dest_x = box->x + box->width - 1/256.0; + } else { + *dest_x = x; + } + + // find closest y point + if (y < box->y) { + *dest_y = box->y; + } else if (y > box->y + box->height - 1/256.0) { + *dest_y = box->y + box->height - 1/256.0; + } else { + *dest_y = y; + } +} + +bool wlr_box_empty(const struct wlr_box *box) { + return box == NULL || box->width <= 0 || box->height <= 0; +} + +bool wlr_box_intersection(struct wlr_box *dest, const struct wlr_box *box_a, + const struct wlr_box *box_b) { + bool a_empty = wlr_box_empty(box_a); + bool b_empty = wlr_box_empty(box_b); + + if (a_empty || b_empty) { + *dest = (struct wlr_box){0}; + return false; + } + + int x1 = max(box_a->x, box_b->x); + int y1 = max(box_a->y, box_b->y); + int x2 = min(box_a->x + box_a->width, box_b->x + box_b->width); + int y2 = min(box_a->y + box_a->height, box_b->y + box_b->height); + + dest->x = x1; + dest->y = y1; + dest->width = x2 - x1; + dest->height = y2 - y1; + + if (wlr_box_empty(dest)) { + *dest = (struct wlr_box){0}; + return false; + } + + return true; +} + +bool wlr_box_contains_point(const struct wlr_box *box, double x, double y) { + if (wlr_box_empty(box)) { + return false; + } else { + return x >= box->x && x < box->x + box->width && + y >= box->y && y < box->y + box->height; + } +} + +bool wlr_box_contains_box(const struct wlr_box *bigger, const struct wlr_box *smaller) { + if (wlr_box_empty(bigger) || wlr_box_empty(smaller)) { + return false; + } + + return smaller->x >= bigger->x && + smaller->x + smaller->width <= bigger->x + bigger->width && + smaller->y >= bigger->y && + smaller->y + smaller->height <= bigger->y + bigger->height; +} + +void wlr_box_transform(struct wlr_box *dest, const struct wlr_box *box, + enum wl_output_transform transform, int width, int height) { + struct wlr_box src = {0}; + if (box != NULL) { + src = *box; + } + + if (transform % 2 == 0) { + dest->width = src.width; + dest->height = src.height; + } else { + dest->width = src.height; + dest->height = src.width; + } + + switch (transform) { + case WL_OUTPUT_TRANSFORM_NORMAL: + dest->x = src.x; + dest->y = src.y; + break; + case WL_OUTPUT_TRANSFORM_90: + dest->x = height - src.y - src.height; + dest->y = src.x; + break; + case WL_OUTPUT_TRANSFORM_180: + dest->x = width - src.x - src.width; + dest->y = height - src.y - src.height; + break; + case WL_OUTPUT_TRANSFORM_270: + dest->x = src.y; + dest->y = width - src.x - src.width; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED: + dest->x = width - src.x - src.width; + dest->y = src.y; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED_90: + dest->x = src.y; + dest->y = src.x; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED_180: + dest->x = src.x; + dest->y = height - src.y - src.height; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED_270: + dest->x = height - src.y - src.height; + dest->y = width - src.x - src.width; + break; + } +} + +bool wlr_fbox_empty(const struct wlr_fbox *box) { + return box == NULL || box->width <= 0 || box->height <= 0; +} + +void wlr_fbox_transform(struct wlr_fbox *dest, const struct wlr_fbox *box, + enum wl_output_transform transform, double width, double height) { + struct wlr_fbox src = {0}; + if (box != NULL) { + src = *box; + } + + if (transform % 2 == 0) { + dest->width = src.width; + dest->height = src.height; + } else { + dest->width = src.height; + dest->height = src.width; + } + + switch (transform) { + case WL_OUTPUT_TRANSFORM_NORMAL: + dest->x = src.x; + dest->y = src.y; + break; + case WL_OUTPUT_TRANSFORM_90: + dest->x = height - src.y - src.height; + dest->y = src.x; + break; + case WL_OUTPUT_TRANSFORM_180: + dest->x = width - src.x - src.width; + dest->y = height - src.y - src.height; + break; + case WL_OUTPUT_TRANSFORM_270: + dest->x = src.y; + dest->y = width - src.x - src.width; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED: + dest->x = width - src.x - src.width; + dest->y = src.y; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED_90: + dest->x = src.y; + dest->y = src.x; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED_180: + dest->x = src.x; + dest->y = height - src.y - src.height; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED_270: + dest->x = height - src.y - src.height; + dest->y = width - src.x - src.width; + break; + } +} + +#ifdef WLR_USE_UNSTABLE + +bool wlr_box_equal(const struct wlr_box *a, const struct wlr_box *b) { + if (wlr_box_empty(a)) { + a = NULL; + } + if (wlr_box_empty(b)) { + b = NULL; + } + + if (a == NULL || b == NULL) { + return a == b; + } + + return a->x == b->x && a->y == b->y && + a->width == b->width && a->height == b->height; +} + +bool wlr_fbox_equal(const struct wlr_fbox *a, const struct wlr_fbox *b) { + if (wlr_fbox_empty(a)) { + a = NULL; + } + if (wlr_fbox_empty(b)) { + b = NULL; + } + + if (a == NULL || b == NULL) { + return a == b; + } + + return a->x == b->x && a->y == b->y && + a->width == b->width && a->height == b->height; +} + +#endif diff --git a/3rdparty/wlroots/util/env.c b/3rdparty/wlroots/util/env.c new file mode 100644 index 0000000000..77911a227e --- /dev/null +++ b/3rdparty/wlroots/util/env.c @@ -0,0 +1,38 @@ +#include +#include +#include +#include "util/env.h" + +bool env_parse_bool(const char *option) { + const char *env = getenv(option); + if (env) { + wlr_log(WLR_INFO, "Loading %s option: %s", option, env); + } + + if (!env || strcmp(env, "0") == 0) { + return false; + } else if (strcmp(env, "1") == 0) { + return true; + } + + wlr_log(WLR_ERROR, "Unknown %s option: %s", option, env); + return false; +} + +size_t env_parse_switch(const char *option, const char **switches) { + const char *env = getenv(option); + if (env) { + wlr_log(WLR_INFO, "Loading %s option: %s", option, env); + } else { + return 0; + } + + for (ssize_t i = 0; switches[i]; i++) { + if (strcmp(env, switches[i]) == 0) { + return i; + } + } + + wlr_log(WLR_ERROR, "Unknown %s option: %s", option, env); + return 0; +} diff --git a/3rdparty/wlroots/util/fd.c b/3rdparty/wlroots/util/fd.c new file mode 100644 index 0000000000..3dff5396f7 --- /dev/null +++ b/3rdparty/wlroots/util/fd.c @@ -0,0 +1,22 @@ +#include +#include + +#include "util/fd.h" + +bool set_cloexec(int fd, bool cloexec) { + int flags = fcntl(fd, F_GETFD); + if (flags == -1) { + wlr_log_errno(WLR_ERROR, "fcntl failed"); + return false; + } + if (cloexec) { + flags = flags | FD_CLOEXEC; + } else { + flags = flags & ~FD_CLOEXEC; + } + if (fcntl(fd, F_SETFD, flags) == -1) { + wlr_log_errno(WLR_ERROR, "fcntl failed"); + return false; + } + return true; +} diff --git a/3rdparty/wlroots/util/global.c b/3rdparty/wlroots/util/global.c new file mode 100644 index 0000000000..93636a8984 --- /dev/null +++ b/3rdparty/wlroots/util/global.c @@ -0,0 +1,57 @@ +#include +#include "util/global.h" + +struct destroy_global_data { + struct wl_global *global; + struct wl_event_source *event_source; + struct wl_listener display_destroy; +}; + +static void destroy_global(struct destroy_global_data *data) { + wl_list_remove(&data->display_destroy.link); + wl_global_destroy(data->global); + wl_event_source_remove(data->event_source); + free(data); +} + +static int handle_timer_event(void *data) { + destroy_global(data); + return 0; +} + +static void handle_display_destroy(struct wl_listener *listener, void *_data) { + struct destroy_global_data *data = + wl_container_of(listener, data, display_destroy); + destroy_global(data); +} + +void wlr_global_destroy_safe(struct wl_global *global) { + // Don't destroy the global immediately. If the global has been created + // recently, clients might try to bind to it after we've destroyed it. + // Instead, remove the global so that clients stop seeing it and wait an + // arbitrary amount of time before destroying the global as a workaround. + // See: https://gitlab.freedesktop.org/wayland/wayland/issues/10 + + wl_global_remove(global); + wl_global_set_user_data(global, NULL); // safety net + + struct wl_display *display = wl_global_get_display(global); + struct wl_event_loop *event_loop = wl_display_get_event_loop(display); + struct destroy_global_data *data = calloc(1, sizeof(*data)); + if (data == NULL) { + wl_global_destroy(global); + return; + } + data->global = global; + data->event_source = + wl_event_loop_add_timer(event_loop, handle_timer_event, data); + if (data->event_source == NULL) { + free(data); + wl_global_destroy(global); + return; + } + wl_event_source_timer_update(data->event_source, 5000); + + data->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &data->display_destroy); +} diff --git a/3rdparty/wlroots/util/log.c b/3rdparty/wlroots/util/log.c new file mode 100644 index 0000000000..a329b43be0 --- /dev/null +++ b/3rdparty/wlroots/util/log.c @@ -0,0 +1,107 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "util/time.h" + +static bool colored = true; +static enum wlr_log_importance log_importance = WLR_ERROR; +static struct timespec start_time = {-1}; + +static const char *verbosity_colors[] = { + [WLR_SILENT] = "", + [WLR_ERROR] = "\x1B[1;31m", + [WLR_INFO] = "\x1B[1;34m", + [WLR_DEBUG] = "\x1B[1;90m", +}; + +static const char *verbosity_headers[] = { + [WLR_SILENT] = "", + [WLR_ERROR] = "[ERROR]", + [WLR_INFO] = "[INFO]", + [WLR_DEBUG] = "[DEBUG]", +}; + +static void init_start_time(void) { + if (start_time.tv_sec >= 0) { + return; + } + clock_gettime(CLOCK_MONOTONIC, &start_time); +} + +static void log_stderr(enum wlr_log_importance verbosity, const char *fmt, + va_list args) { + init_start_time(); + + if (verbosity > log_importance) { + return; + } + + struct timespec ts = {0}; + clock_gettime(CLOCK_MONOTONIC, &ts); + timespec_sub(&ts, &ts, &start_time); + + fprintf(stderr, "%02d:%02d:%02d.%03ld ", (int)(ts.tv_sec / 60 / 60), + (int)(ts.tv_sec / 60 % 60), (int)(ts.tv_sec % 60), + ts.tv_nsec / 1000000); + + unsigned c = (verbosity < WLR_LOG_IMPORTANCE_LAST) ? verbosity : WLR_LOG_IMPORTANCE_LAST - 1; + + if (colored && isatty(STDERR_FILENO)) { + fprintf(stderr, "%s", verbosity_colors[c]); + } else { + fprintf(stderr, "%s ", verbosity_headers[c]); + } + + vfprintf(stderr, fmt, args); + + if (colored && isatty(STDERR_FILENO)) { + fprintf(stderr, "\x1B[0m"); + } + fprintf(stderr, "\n"); +} + +static wlr_log_func_t log_callback = log_stderr; + +static void log_wl(const char *fmt, va_list args) { + static char wlr_fmt[1024]; + int n = snprintf(wlr_fmt, sizeof(wlr_fmt), "[wayland] %s", fmt); + size_t len = strlen(wlr_fmt); + if (n > 0 && wlr_fmt[len - 1] == '\n') { + wlr_fmt[len - 1] = '\0'; + } + _wlr_vlog(WLR_INFO, wlr_fmt, args); +} + +void wlr_log_init(enum wlr_log_importance verbosity, wlr_log_func_t callback) { + init_start_time(); + + if (verbosity < WLR_LOG_IMPORTANCE_LAST) { + log_importance = verbosity; + } + if (callback) { + log_callback = callback; + } + + wl_log_set_handler_server(log_wl); +} + +void _wlr_vlog(enum wlr_log_importance verbosity, const char *fmt, va_list args) { + log_callback(verbosity, fmt, args); +} + +void _wlr_log(enum wlr_log_importance verbosity, const char *fmt, ...) { + va_list args; + va_start(args, fmt); + log_callback(verbosity, fmt, args); + va_end(args); +} + +enum wlr_log_importance wlr_log_get_verbosity(void) { + return log_importance; +} diff --git a/3rdparty/wlroots/util/matrix.c b/3rdparty/wlroots/util/matrix.c new file mode 100644 index 0000000000..640787c955 --- /dev/null +++ b/3rdparty/wlroots/util/matrix.c @@ -0,0 +1,165 @@ +#include +#include +#include +#include +#include "util/matrix.h" + +void wlr_matrix_identity(float mat[static 9]) { + static const float identity[9] = { + 1.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 1.0f, + }; + memcpy(mat, identity, sizeof(identity)); +} + +void wlr_matrix_multiply(float mat[static 9], const float a[static 9], + const float b[static 9]) { + float product[9]; + + product[0] = a[0]*b[0] + a[1]*b[3] + a[2]*b[6]; + product[1] = a[0]*b[1] + a[1]*b[4] + a[2]*b[7]; + product[2] = a[0]*b[2] + a[1]*b[5] + a[2]*b[8]; + + product[3] = a[3]*b[0] + a[4]*b[3] + a[5]*b[6]; + product[4] = a[3]*b[1] + a[4]*b[4] + a[5]*b[7]; + product[5] = a[3]*b[2] + a[4]*b[5] + a[5]*b[8]; + + product[6] = a[6]*b[0] + a[7]*b[3] + a[8]*b[6]; + product[7] = a[6]*b[1] + a[7]*b[4] + a[8]*b[7]; + product[8] = a[6]*b[2] + a[7]*b[5] + a[8]*b[8]; + + memcpy(mat, product, sizeof(product)); +} + +void wlr_matrix_translate(float mat[static 9], float x, float y) { + float translate[9] = { + 1.0f, 0.0f, x, + 0.0f, 1.0f, y, + 0.0f, 0.0f, 1.0f, + }; + wlr_matrix_multiply(mat, mat, translate); +} + +void wlr_matrix_scale(float mat[static 9], float x, float y) { + float scale[9] = { + x, 0.0f, 0.0f, + 0.0f, y, 0.0f, + 0.0f, 0.0f, 1.0f, + }; + wlr_matrix_multiply(mat, mat, scale); +} + +static const float transforms[][9] = { + [WL_OUTPUT_TRANSFORM_NORMAL] = { + 1.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 1.0f, + }, + [WL_OUTPUT_TRANSFORM_90] = { + 0.0f, 1.0f, 0.0f, + -1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, + }, + [WL_OUTPUT_TRANSFORM_180] = { + -1.0f, 0.0f, 0.0f, + 0.0f, -1.0f, 0.0f, + 0.0f, 0.0f, 1.0f, + }, + [WL_OUTPUT_TRANSFORM_270] = { + 0.0f, -1.0f, 0.0f, + 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, + }, + [WL_OUTPUT_TRANSFORM_FLIPPED] = { + -1.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 1.0f, + }, + [WL_OUTPUT_TRANSFORM_FLIPPED_90] = { + 0.0f, 1.0f, 0.0f, + 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, + }, + [WL_OUTPUT_TRANSFORM_FLIPPED_180] = { + 1.0f, 0.0f, 0.0f, + 0.0f, -1.0f, 0.0f, + 0.0f, 0.0f, 1.0f, + }, + [WL_OUTPUT_TRANSFORM_FLIPPED_270] = { + 0.0f, -1.0f, 0.0f, + -1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, + }, +}; + +void wlr_matrix_transform(float mat[static 9], + enum wl_output_transform transform) { + wlr_matrix_multiply(mat, mat, transforms[transform]); +} + +void matrix_projection(float mat[static 9], int width, int height, + enum wl_output_transform transform) { + memset(mat, 0, sizeof(*mat) * 9); + + const float *t = transforms[transform]; + float x = 2.0f / width; + float y = 2.0f / height; + + // Rotation + reflection + mat[0] = x * t[0]; + mat[1] = x * t[1]; + mat[3] = y * -t[3]; + mat[4] = y * -t[4]; + + // Translation + mat[2] = -copysign(1.0f, mat[0] + mat[1]); + mat[5] = -copysign(1.0f, mat[3] + mat[4]); + + // Identity + mat[8] = 1.0f; +} + +void wlr_matrix_project_box(float mat[static 9], const struct wlr_box *box, + enum wl_output_transform transform, const float projection[static 9]) { + int x = box->x; + int y = box->y; + int width = box->width; + int height = box->height; + + wlr_matrix_identity(mat); + wlr_matrix_translate(mat, x, y); + + wlr_matrix_scale(mat, width, height); + + if (transform != WL_OUTPUT_TRANSFORM_NORMAL) { + wlr_matrix_translate(mat, 0.5, 0.5); + wlr_matrix_transform(mat, transform); + wlr_matrix_translate(mat, -0.5, -0.5); + } + + wlr_matrix_multiply(mat, projection, mat); +} + +void matrix_invert(float out[static 9], float m[static 9]) { + float a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5], g = m[6], h = m[7], i = m[8]; + + // See: https://en.wikipedia.org/wiki/Determinant + float det = a*e*i + b*f*g + c*d*h - c*e*g - b*d*i - a*f*h; + assert(det != 0); + float inv_det = 1 / det; + + // See: https://en.wikipedia.org/wiki/Invertible_matrix#Inversion_of_3_%C3%97_3_matrices + float result[] = { + inv_det * (e*i - f*h), + inv_det * -(b*i - c*h), + inv_det * (b*f - c*e), + inv_det * -(d*i - f*g), + inv_det * (a*i - c*g), + inv_det * -(a*f - c*d), + inv_det * (d*h - e*g), + inv_det * -(a*h - b*g), + inv_det * (a*e - b*d), + }; + memcpy(out, result, sizeof(result)); +} diff --git a/3rdparty/wlroots/util/mem.c b/3rdparty/wlroots/util/mem.c new file mode 100644 index 0000000000..cfd2f80e46 --- /dev/null +++ b/3rdparty/wlroots/util/mem.c @@ -0,0 +1,16 @@ +#include +#include +#include + +#include "util/mem.h" + +bool memdup(void *out, const void *src, size_t size) { + void *dst = malloc(size); + if (dst == NULL) { + return false; + } + memcpy(dst, src, size); + void **dst_ptr = out; + *dst_ptr = dst; + return true; +} diff --git a/3rdparty/wlroots/util/meson.build b/3rdparty/wlroots/util/meson.build new file mode 100644 index 0000000000..7d3f39d28a --- /dev/null +++ b/3rdparty/wlroots/util/meson.build @@ -0,0 +1,20 @@ +wlr_files += files( + 'addon.c', + 'array.c', + 'box.c', + 'env.c', + 'fd.c', + 'global.c', + 'log.c', + 'matrix.c', + 'mem.c', + 'rect_union.c', + 'region.c', + 'set.c', + 'shm.c', + 'time.c', + 'token.c', + 'transform.c', + 'utf8.c', + 'version.c', +) diff --git a/3rdparty/wlroots/util/rect_union.c b/3rdparty/wlroots/util/rect_union.c new file mode 100644 index 0000000000..8cd26d7617 --- /dev/null +++ b/3rdparty/wlroots/util/rect_union.c @@ -0,0 +1,91 @@ +#include +#include "util/rect_union.h" + +static void box_union(pixman_box32_t *dst, pixman_box32_t box) { + dst->x1 = dst->x1 < box.x1 ? dst->x1 : box.x1; + dst->y1 = dst->y1 < box.y1 ? dst->y1 : box.y1; + dst->x2 = dst->x2 > box.x2 ? dst->x2 : box.x2; + dst->y2 = dst->y2 > box.y2 ? dst->y2 : box.y2; +} + +static bool box_empty_or_invalid(pixman_box32_t box) { + return box.x1 >= box.x2 || box.y1 >= box.y2; +} + +void rect_union_init(struct rect_union *ru) { + *ru = (struct rect_union) { + .alloc_failure = false, + .bounding_box = (pixman_box32_t) { + .x1 = INT_MAX, + .x2 = INT_MIN, + .y1 = INT_MAX, + .y2 = INT_MIN, + } + }; + pixman_region32_init(&ru->region); + wl_array_init(&ru->unsorted); +}; + +void rect_union_finish(struct rect_union *ru) { + pixman_region32_fini(&ru->region); + wl_array_release(&ru->unsorted); +} + +static void handle_alloc_failure(struct rect_union *ru) { + ru->alloc_failure = true; + wl_array_release(&ru->unsorted); + wl_array_init(&ru->unsorted); +} + +void rect_union_add(struct rect_union *ru, pixman_box32_t box) { + if (box_empty_or_invalid(box)) { + return; + } + + box_union(&ru->bounding_box, box); + + if (!ru->alloc_failure) { + pixman_box32_t *entry = wl_array_add(&ru->unsorted, sizeof(*entry)); + if (entry) { + *entry = box; + } else { + handle_alloc_failure(ru); + } + } +} + +const pixman_region32_t *rect_union_evaluate(struct rect_union *ru) { + if (ru->alloc_failure) { + goto bounding_box; + } + + int nrects = (int)(ru->unsorted.size / sizeof(pixman_box32_t)); + pixman_region32_t reg; + bool ok = pixman_region32_init_rects(®, ru->unsorted.data, nrects); + if (!ok) { + handle_alloc_failure(ru); + goto bounding_box; + } + ok = pixman_region32_union(®, ®, &ru->region); + if (!ok) { + pixman_region32_fini(®); + handle_alloc_failure(ru); + goto bounding_box; + } + pixman_region32_fini(&ru->region); + // pixman_region32_t is safe to move + ru->region = reg; + wl_array_release(&ru->unsorted); + wl_array_init(&ru->unsorted); + + return &ru->region; +bounding_box: + pixman_region32_fini(&ru->region); + if (box_empty_or_invalid(ru->bounding_box)) { + pixman_region32_init(&ru->region); + } else { + pixman_region32_init_with_extents(&ru->region, &ru->bounding_box); + } + return &ru->region; +} + diff --git a/3rdparty/wlroots/util/region.c b/3rdparty/wlroots/util/region.c new file mode 100644 index 0000000000..b74c55e549 --- /dev/null +++ b/3rdparty/wlroots/util/region.c @@ -0,0 +1,256 @@ +#include +#include +#include +#include +#include + +void wlr_region_scale(pixman_region32_t *dst, const pixman_region32_t *src, + float scale) { + wlr_region_scale_xy(dst, src, scale, scale); +} + +void wlr_region_scale_xy(pixman_region32_t *dst, const pixman_region32_t *src, + float scale_x, float scale_y) { + if (scale_x == 1.0 && scale_y == 1.0) { + pixman_region32_copy(dst, src); + return; + } + + int nrects; + const pixman_box32_t *src_rects = pixman_region32_rectangles(src, &nrects); + + pixman_box32_t *dst_rects = malloc(nrects * sizeof(pixman_box32_t)); + if (dst_rects == NULL) { + return; + } + + for (int i = 0; i < nrects; ++i) { + dst_rects[i].x1 = floor(src_rects[i].x1 * scale_x); + dst_rects[i].x2 = ceil(src_rects[i].x2 * scale_x); + dst_rects[i].y1 = floor(src_rects[i].y1 * scale_y); + dst_rects[i].y2 = ceil(src_rects[i].y2 * scale_y); + } + + pixman_region32_fini(dst); + pixman_region32_init_rects(dst, dst_rects, nrects); + free(dst_rects); +} + +void wlr_region_transform(pixman_region32_t *dst, const pixman_region32_t *src, + enum wl_output_transform transform, int width, int height) { + if (transform == WL_OUTPUT_TRANSFORM_NORMAL) { + pixman_region32_copy(dst, src); + return; + } + + int nrects; + const pixman_box32_t *src_rects = pixman_region32_rectangles(src, &nrects); + + pixman_box32_t *dst_rects = malloc(nrects * sizeof(pixman_box32_t)); + if (dst_rects == NULL) { + return; + } + + for (int i = 0; i < nrects; ++i) { + switch (transform) { + case WL_OUTPUT_TRANSFORM_NORMAL: + dst_rects[i].x1 = src_rects[i].x1; + dst_rects[i].y1 = src_rects[i].y1; + dst_rects[i].x2 = src_rects[i].x2; + dst_rects[i].y2 = src_rects[i].y2; + break; + case WL_OUTPUT_TRANSFORM_90: + dst_rects[i].x1 = height - src_rects[i].y2; + dst_rects[i].y1 = src_rects[i].x1; + dst_rects[i].x2 = height - src_rects[i].y1; + dst_rects[i].y2 = src_rects[i].x2; + break; + case WL_OUTPUT_TRANSFORM_180: + dst_rects[i].x1 = width - src_rects[i].x2; + dst_rects[i].y1 = height - src_rects[i].y2; + dst_rects[i].x2 = width - src_rects[i].x1; + dst_rects[i].y2 = height - src_rects[i].y1; + break; + case WL_OUTPUT_TRANSFORM_270: + dst_rects[i].x1 = src_rects[i].y1; + dst_rects[i].y1 = width - src_rects[i].x2; + dst_rects[i].x2 = src_rects[i].y2; + dst_rects[i].y2 = width - src_rects[i].x1; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED: + dst_rects[i].x1 = width - src_rects[i].x2; + dst_rects[i].y1 = src_rects[i].y1; + dst_rects[i].x2 = width - src_rects[i].x1; + dst_rects[i].y2 = src_rects[i].y2; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED_90: + dst_rects[i].x1 = src_rects[i].y1; + dst_rects[i].y1 = src_rects[i].x1; + dst_rects[i].x2 = src_rects[i].y2; + dst_rects[i].y2 = src_rects[i].x2; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED_180: + dst_rects[i].x1 = src_rects[i].x1; + dst_rects[i].y1 = height - src_rects[i].y2; + dst_rects[i].x2 = src_rects[i].x2; + dst_rects[i].y2 = height - src_rects[i].y1; + break; + case WL_OUTPUT_TRANSFORM_FLIPPED_270: + dst_rects[i].x1 = height - src_rects[i].y2; + dst_rects[i].y1 = width - src_rects[i].x2; + dst_rects[i].x2 = height - src_rects[i].y1; + dst_rects[i].y2 = width - src_rects[i].x1; + break; + } + } + + pixman_region32_fini(dst); + pixman_region32_init_rects(dst, dst_rects, nrects); + free(dst_rects); +} + +void wlr_region_expand(pixman_region32_t *dst, const pixman_region32_t *src, + int distance) { + assert(distance >= 0); + + if (distance == 0) { + pixman_region32_copy(dst, src); + return; + } + + int nrects; + const pixman_box32_t *src_rects = pixman_region32_rectangles(src, &nrects); + + pixman_box32_t *dst_rects = malloc(nrects * sizeof(pixman_box32_t)); + if (dst_rects == NULL) { + return; + } + + for (int i = 0; i < nrects; ++i) { + dst_rects[i].x1 = src_rects[i].x1 - distance; + dst_rects[i].x2 = src_rects[i].x2 + distance; + dst_rects[i].y1 = src_rects[i].y1 - distance; + dst_rects[i].y2 = src_rects[i].y2 + distance; + } + + pixman_region32_fini(dst); + pixman_region32_init_rects(dst, dst_rects, nrects); + free(dst_rects); +} + +void wlr_region_rotated_bounds(pixman_region32_t *dst, const pixman_region32_t *src, + float rotation, int ox, int oy) { + if (rotation == 0) { + pixman_region32_copy(dst, src); + return; + } + + int nrects; + const pixman_box32_t *src_rects = pixman_region32_rectangles(src, &nrects); + + pixman_box32_t *dst_rects = malloc(nrects * sizeof(pixman_box32_t)); + if (dst_rects == NULL) { + return; + } + + for (int i = 0; i < nrects; ++i) { + double x1 = src_rects[i].x1 - ox; + double y1 = src_rects[i].y1 - oy; + double x2 = src_rects[i].x2 - ox; + double y2 = src_rects[i].y2 - oy; + + double rx1 = x1 * cos(rotation) - y1 * sin(rotation); + double ry1 = x1 * sin(rotation) + y1 * cos(rotation); + + double rx2 = x2 * cos(rotation) - y1 * sin(rotation); + double ry2 = x2 * sin(rotation) + y1 * cos(rotation); + + double rx3 = x2 * cos(rotation) - y2 * sin(rotation); + double ry3 = x2 * sin(rotation) + y2 * cos(rotation); + + double rx4 = x1 * cos(rotation) - y2 * sin(rotation); + double ry4 = x1 * sin(rotation) + y2 * cos(rotation); + + x1 = fmin(fmin(rx1, rx2), fmin(rx3, rx4)); + y1 = fmin(fmin(ry1, ry2), fmin(ry3, ry4)); + x2 = fmax(fmax(rx1, rx2), fmax(rx3, rx4)); + y2 = fmax(fmax(ry1, ry2), fmax(ry3, ry4)); + + dst_rects[i].x1 = floor(ox + x1); + dst_rects[i].x2 = ceil(ox + x2); + dst_rects[i].y1 = floor(oy + y1); + dst_rects[i].y2 = ceil(oy + y2); + } + + pixman_region32_fini(dst); + pixman_region32_init_rects(dst, dst_rects, nrects); + free(dst_rects); +} + +static void region_confine(const pixman_region32_t *region, double x1, double y1, double x2, + double y2, double *x2_out, double *y2_out, pixman_box32_t box) { + double x_clamped = fmax(fmin(x2, box.x2 - 1), box.x1); + double y_clamped = fmax(fmin(y2, box.y2 - 1), box.y1); + + // If the target coordinates are above box.{x,y}2 - 1, but less than + // box.{x,y}2, then they are still within the box. + if (floor(x_clamped) == floor(x2) && floor(y_clamped) == floor(y2)) { + *x2_out = x2; + *y2_out = y2; + return; + } + + double dx = x2 - x1; + double dy = y2 - y1; + + // We use fabs to avoid negative zeroes and thus avoid a bug + // with negative infinity. + double delta = fmin(fabs(x_clamped - x1) / fabs(dx), fabs(y_clamped - y1) / fabs(dy)); + + // We clamp it again due to precision errors. + double x = fmax(fmin(delta * dx + x1, box.x2 - 1), box.x1); + double y = fmax(fmin(delta * dy + y1, box.y2 - 1), box.y1); + + // Go one unit past the boundary to find an adjacent box. + int x_ext = floor(x) + (dx == 0 ? 0 : dx > 0 ? 1 : -1); + int y_ext = floor(y) + (dy == 0 ? 0 : dy > 0 ? 1 : -1); + + if (pixman_region32_contains_point(region, x_ext, y_ext, &box)) { + return region_confine(region, x, y, x2, y2, x2_out, y2_out, box); + } else if (dx == 0 || dy == 0) { + *x2_out = x; + *y2_out = y; + } else { + bool bordering_x = x == box.x1 || x == box.x2 - 1; + bool bordering_y = y == box.y1 || y == box.y2 - 1; + + if (bordering_x == bordering_y) { + double x2_potential, y2_potential; + double tmp1, tmp2; + region_confine(region, x, y, x, y2, &tmp1, &y2_potential, box); + region_confine(region, x, y, x2, y, &x2_potential, &tmp2, box); + if (fabs(x2_potential - x) > fabs(y2_potential - y)) { + *x2_out = x2_potential; + *y2_out = y; + } else { + *x2_out = x; + *y2_out = y2_potential; + } + } else if (bordering_x) { + return region_confine(region, x, y, x, y2, x2_out, y2_out, box); + } else if (bordering_y) { + return region_confine(region, x, y, x2, y, x2_out, y2_out, box); + } + } +} + +bool wlr_region_confine(const pixman_region32_t *region, double x1, double y1, double x2, + double y2, double *x2_out, double *y2_out) { + pixman_box32_t box; + if (pixman_region32_contains_point(region, floor(x1), floor(y1), &box)) { + region_confine(region, x1, y1, x2, y2, x2_out, y2_out, box); + return true; + } else { + return false; + } +} diff --git a/3rdparty/wlroots/util/set.c b/3rdparty/wlroots/util/set.c new file mode 100644 index 0000000000..1366d04f8f --- /dev/null +++ b/3rdparty/wlroots/util/set.c @@ -0,0 +1,25 @@ +#include "util/set.h" + +ssize_t set_add(uint32_t values[], size_t *len, size_t cap, uint32_t target) { + for (uint32_t i = 0; i < *len; ++i) { + if (values[i] == target) { + return i; + } + } + if (*len == cap) { + return -1; + } + values[*len] = target; + return (*len)++; +} + +ssize_t set_remove(uint32_t values[], size_t *len, size_t cap, uint32_t target) { + for (uint32_t i = 0; i < *len; ++i) { + if (values[i] == target) { + --(*len); + values[i] = values[*len]; + return i; + } + } + return -1; +} diff --git a/3rdparty/wlroots/util/shm.c b/3rdparty/wlroots/util/shm.c new file mode 100644 index 0000000000..5eb87bb89f --- /dev/null +++ b/3rdparty/wlroots/util/shm.c @@ -0,0 +1,97 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "util/shm.h" + +#define RANDNAME_PATTERN "/wlroots-XXXXXX" + +static void randname(char *buf) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + long r = ts.tv_nsec; + for (int i = 0; i < 6; ++i) { + buf[i] = 'A'+(r&15)+(r&16)*2; + r >>= 5; + } +} + +static int excl_shm_open(char *name) { + int retries = 100; + do { + randname(name + strlen(RANDNAME_PATTERN) - 6); + + --retries; + // CLOEXEC is guaranteed to be set by shm_open + int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); + if (fd >= 0) { + return fd; + } + } while (retries > 0 && errno == EEXIST); + + return -1; +} + +int allocate_shm_file(size_t size) { + char name[] = RANDNAME_PATTERN; + int fd = excl_shm_open(name); + if (fd < 0) { + return -1; + } + shm_unlink(name); + + int ret; + do { + ret = ftruncate(fd, size); + } while (ret < 0 && errno == EINTR); + if (ret < 0) { + close(fd); + return -1; + } + + return fd; +} + +bool allocate_shm_file_pair(size_t size, int *rw_fd_ptr, int *ro_fd_ptr) { + char name[] = RANDNAME_PATTERN; + int rw_fd = excl_shm_open(name); + if (rw_fd < 0) { + return false; + } + + // CLOEXEC is guaranteed to be set by shm_open + int ro_fd = shm_open(name, O_RDONLY, 0); + if (ro_fd < 0) { + shm_unlink(name); + close(rw_fd); + return false; + } + + shm_unlink(name); + + // Make sure the file cannot be re-opened in read-write mode (e.g. via + // "/proc/self/fd/" on Linux) + if (fchmod(rw_fd, 0) != 0) { + close(rw_fd); + close(ro_fd); + return false; + } + + int ret; + do { + ret = ftruncate(rw_fd, size); + } while (ret < 0 && errno == EINTR); + if (ret < 0) { + close(rw_fd); + close(ro_fd); + return false; + } + + *rw_fd_ptr = rw_fd; + *ro_fd_ptr = ro_fd; + return true; +} diff --git a/3rdparty/wlroots/util/time.c b/3rdparty/wlroots/util/time.c new file mode 100644 index 0000000000..1a8f32969c --- /dev/null +++ b/3rdparty/wlroots/util/time.c @@ -0,0 +1,33 @@ +#include +#include + +#include "util/time.h" + +int64_t timespec_to_msec(const struct timespec *a) { + return (int64_t)a->tv_sec * 1000 + a->tv_nsec / 1000000; +} + +int64_t timespec_to_nsec(const struct timespec *a) { + return (int64_t)a->tv_sec * NSEC_PER_SEC + a->tv_nsec; +} + +void timespec_from_nsec(struct timespec *r, int64_t nsec) { + r->tv_sec = nsec / NSEC_PER_SEC; + r->tv_nsec = nsec % NSEC_PER_SEC; +} + +int64_t get_current_time_msec(void) { + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + return timespec_to_msec(&now); +} + +void timespec_sub(struct timespec *r, const struct timespec *a, + const struct timespec *b) { + r->tv_sec = a->tv_sec - b->tv_sec; + r->tv_nsec = a->tv_nsec - b->tv_nsec; + if (r->tv_nsec < 0) { + r->tv_sec--; + r->tv_nsec += NSEC_PER_SEC; + } +} diff --git a/3rdparty/wlroots/util/token.c b/3rdparty/wlroots/util/token.c new file mode 100644 index 0000000000..2d58d16986 --- /dev/null +++ b/3rdparty/wlroots/util/token.c @@ -0,0 +1,39 @@ +#include "util/token.h" +#include "wlr/util/log.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +bool generate_token(char out[static TOKEN_SIZE]) { + static FILE *urandom = NULL; + uint64_t data[2]; + + if (!urandom) { + int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC); + if (fd < 0) { + wlr_log_errno(WLR_ERROR, "Failed to open random device"); + return false; + } + if (!(urandom = fdopen(fd, "r"))) { + wlr_log_errno(WLR_ERROR, "fdopen failed"); + close(fd); + return false; + } + } + if (fread(data, sizeof(data), 1, urandom) != 1) { + wlr_log_errno(WLR_ERROR, "Failed to read from random device"); + return false; + } + if (snprintf(out, TOKEN_SIZE, "%016" PRIx64 "%016" PRIx64, data[0], data[1]) != TOKEN_SIZE - 1) { + wlr_log_errno(WLR_ERROR, "Failed to format hex string token"); + return false; + } + return true; +} + diff --git a/3rdparty/wlroots/util/transform.c b/3rdparty/wlroots/util/transform.c new file mode 100644 index 0000000000..de3f8ef4e3 --- /dev/null +++ b/3rdparty/wlroots/util/transform.c @@ -0,0 +1,33 @@ +#include + +enum wl_output_transform wlr_output_transform_invert( + enum wl_output_transform tr) { + if ((tr & WL_OUTPUT_TRANSFORM_90) && !(tr & WL_OUTPUT_TRANSFORM_FLIPPED)) { + tr ^= WL_OUTPUT_TRANSFORM_180; + } + return tr; +} + +enum wl_output_transform wlr_output_transform_compose( + enum wl_output_transform tr_a, enum wl_output_transform tr_b) { + uint32_t flipped = (tr_a ^ tr_b) & WL_OUTPUT_TRANSFORM_FLIPPED; + uint32_t rotation_mask = WL_OUTPUT_TRANSFORM_90 | WL_OUTPUT_TRANSFORM_180; + uint32_t rotated; + if (tr_b & WL_OUTPUT_TRANSFORM_FLIPPED) { + // When a rotation of k degrees is followed by a flip, the + // equivalent transform is a flip followed by a rotation of + // -k degrees. + rotated = (tr_b - tr_a) & rotation_mask; + } else { + rotated = (tr_a + tr_b) & rotation_mask; + } + return flipped | rotated; +} + +void wlr_output_transform_coords(enum wl_output_transform tr, int *x, int *y) { + if (tr & WL_OUTPUT_TRANSFORM_90) { + int tmp = *x; + *x = *y; + *y = tmp; + } +} diff --git a/3rdparty/wlroots/util/utf8.c b/3rdparty/wlroots/util/utf8.c new file mode 100644 index 0000000000..802fd010cd --- /dev/null +++ b/3rdparty/wlroots/util/utf8.c @@ -0,0 +1,66 @@ +#include +#include "util/utf8.h" + +static bool in_range(char x, uint8_t low, uint8_t high) { + uint8_t v = (uint8_t)x; + return low <= v && v <= high; +} + +bool is_utf8(const char *string) { + /* Returns true iff the string is 'well-formed', as defined by + * Unicode Standard 15.0.0. See Chapter 3, D92 and Table 3.7. + * + * UTF-8 strings are sequences of code points encoded in one of the + * following ways. The first byte determines the pattern. + * + * 00..7F + * C2..DF 80..BF + * E0 A0..BF 80..BF + * E1..EC 80..BF 80..BF + * ED 80..9F 80..BF + * EE..EF 80..BF 80..BF + * F0 90..BF 80..BF 80..BF + * F1..F3 80..BF 80..BF 80..BF + * F4 80..8F 80..BF 80..BF + */ + uint8_t range_table[9][8] = { + {0x00, 0x7F}, + {0xC2, 0xDF, 0x80, 0xBF}, + {0xE0, 0xE0, 0xA0, 0xBF, 0x80, 0xBF}, + {0xE1, 0xEC, 0x80, 0xBF, 0x80, 0xBF}, + {0xED, 0xED, 0x80, 0x9F, 0x80, 0xBF}, + {0xEE, 0xEF, 0x80, 0xBF, 0x80, 0xBF}, + {0xF0, 0xF0, 0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}, + {0xF1, 0xF3, 0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}, + {0xF4, 0xF4, 0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}, + }; + int lengths[9] = { + 1, 2, 3, 3, 3, 3, 4, 4, 4 + }; + + while (string[0]) { + bool accept = false; + for (int i = 0; i < 9; i++) { + if (!in_range(string[0], range_table[i][0], + range_table[i][1])) { + continue; + } + for (int j = 1; j < lengths[i]; j++) { + if (!in_range(string[j], range_table[i][2 * j], + range_table[i][2 * j + 1])) { + // Early exit is necessary to avoid + // reading past the null terminator + return false; + } + } + string += lengths[i]; + accept = true; + break; + } + if (!accept) { + return false; + } + } + + return true; +} diff --git a/3rdparty/wlroots/util/version.c b/3rdparty/wlroots/util/version.c new file mode 100644 index 0000000000..081146bd5a --- /dev/null +++ b/3rdparty/wlroots/util/version.c @@ -0,0 +1,13 @@ +#include "wlr/version.h" + +int wlr_version_get_major(void) { + return WLR_VERSION_MAJOR; +} + +int wlr_version_get_minor(void) { + return WLR_VERSION_MINOR; +} + +int wlr_version_get_micro(void) { + return WLR_VERSION_MICRO; +} diff --git a/3rdparty/wlroots/wlroots.syms b/3rdparty/wlroots/wlroots.syms new file mode 100644 index 0000000000..4b65b12a12 --- /dev/null +++ b/3rdparty/wlroots/wlroots.syms @@ -0,0 +1,8 @@ +{ + global: + wlr_*; + _wlr_*; + waylib_*; + local: + *; +}; diff --git a/3rdparty/wlroots/xcursor/meson.build b/3rdparty/wlroots/xcursor/meson.build new file mode 100644 index 0000000000..cf3718f70e --- /dev/null +++ b/3rdparty/wlroots/xcursor/meson.build @@ -0,0 +1,10 @@ +icondir = get_option('icon_directory') +if icondir == '' + icondir = get_option('prefix') / get_option('datadir') / 'icons' +endif +internal_config.set_quoted('ICONDIR', icondir) + +wlr_files += files( + 'wlr_xcursor.c', + 'xcursor.c', +) diff --git a/3rdparty/wlroots/xcursor/wlr_xcursor.c b/3rdparty/wlroots/xcursor/wlr_xcursor.c new file mode 100644 index 0000000000..3b4d25cffb --- /dev/null +++ b/3rdparty/wlroots/xcursor/wlr_xcursor.c @@ -0,0 +1,373 @@ +/* + * Copyright © 2012 Intel Corporation + * + * 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 (including the + * next paragraph) 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "types/wlr_buffer.h" +#include "xcursor/xcursor.h" + +#include "xcursor/cursor_data.h" + +static void xcursor_destroy(struct wlr_xcursor *cursor) { + for (size_t i = 0; i < cursor->image_count; i++) { + readonly_data_buffer_drop(cursor->images[i]->readonly_buffer); + free(cursor->images[i]->buffer); + free(cursor->images[i]); + } + + free(cursor->images); + free(cursor->name); + free(cursor); +} + +static struct wlr_xcursor_image *xcursor_image_create(uint32_t width, uint32_t height, + uint32_t hotspot_x, uint32_t hotspot_y, uint32_t delay, const void *buffer) { + struct wlr_xcursor_image *image = calloc(1, sizeof(*image)); + if (image == NULL) { + return NULL; + } + + image->width = width; + image->height = height; + image->hotspot_x = hotspot_x; + image->hotspot_y = hotspot_y; + image->delay = delay; + + size_t stride = width * sizeof(uint32_t); + size_t size = stride * height; + image->buffer = malloc(size); + if (image->buffer == NULL) { + goto err_image; + } + + memcpy(image->buffer, buffer, size); + + image->readonly_buffer = readonly_data_buffer_create(DRM_FORMAT_ARGB8888, + stride, width, height, image->buffer); + if (image->readonly_buffer == NULL) { + goto err_buffer; + } + + return image; + +err_buffer: + free(image->buffer); +err_image: + free(image); + return NULL; +} + +static struct wlr_xcursor *xcursor_create_from_data( + const struct cursor_metadata *metadata, struct wlr_xcursor_theme *theme) { + struct wlr_xcursor *cursor = calloc(1, sizeof(*cursor)); + if (!cursor) { + return NULL; + } + + cursor->image_count = 1; + cursor->images = calloc(1, sizeof(*cursor->images)); + if (!cursor->images) { + goto err_free_cursor; + } + + cursor->name = strdup(metadata->name); + cursor->total_delay = 0; + + struct wlr_xcursor_image *image = xcursor_image_create(metadata->width, metadata->height, + metadata->hotspot_x, metadata->hotspot_y, 0, cursor_data + metadata->offset); + if (!image) { + goto err_free_images; + } + + cursor->images[0] = image; + + return cursor; + +err_free_images: + free(cursor->name); + free(cursor->images); + +err_free_cursor: + free(cursor); + return NULL; +} + +static void load_default_theme(struct wlr_xcursor_theme *theme) { + free(theme->name); + theme->name = strdup("default"); + + size_t cursor_count = sizeof(cursor_metadata) / sizeof(cursor_metadata[0]); + theme->cursor_count = 0; + theme->cursors = malloc(cursor_count * sizeof(*theme->cursors)); + if (theme->cursors == NULL) { + return; + } + + for (uint32_t i = 0; i < cursor_count; ++i) { + theme->cursors[i] = xcursor_create_from_data(&cursor_metadata[i], theme); + if (theme->cursors[i] == NULL) { + break; + } + ++theme->cursor_count; + } +} + +static struct wlr_xcursor *xcursor_create_from_xcursor_images( + struct xcursor_images *images, struct wlr_xcursor_theme *theme) { + struct wlr_xcursor *cursor = calloc(1, sizeof(*cursor)); + if (!cursor) { + return NULL; + } + + cursor->images = calloc(images->nimage, sizeof(cursor->images[0])); + if (!cursor->images) { + free(cursor); + return NULL; + } + + cursor->name = strdup(images->name); + cursor->total_delay = 0; + + for (int i = 0; i < images->nimage; i++) { + const struct xcursor_image *data = images->images[i]; + struct wlr_xcursor_image *image = xcursor_image_create(data->width, data->height, + data->xhot, data->yhot, data->delay, data->pixels); + if (image == NULL) { + break; + } + + cursor->total_delay += image->delay; + cursor->images[i] = image; + cursor->image_count++; + } + + if (cursor->image_count == 0) { + free(cursor->name); + free(cursor->images); + free(cursor); + return NULL; + } + + return cursor; +} + +static struct wlr_xcursor *xcursor_theme_get_cursor(struct wlr_xcursor_theme *theme, + const char *name); + +static void load_callback(struct xcursor_images *images, void *data) { + struct wlr_xcursor_theme *theme = data; + + if (xcursor_theme_get_cursor(theme, images->name)) { + xcursor_images_destroy(images); + return; + } + + struct wlr_xcursor *cursor = xcursor_create_from_xcursor_images(images, theme); + if (cursor) { + theme->cursor_count++; + struct wlr_xcursor **cursors = realloc(theme->cursors, + theme->cursor_count * sizeof(theme->cursors[0])); + if (cursors == NULL) { + theme->cursor_count--; + xcursor_destroy(cursor); + } else { + theme->cursors = cursors; + theme->cursors[theme->cursor_count - 1] = cursor; + } + } + + xcursor_images_destroy(images); +} + +struct wlr_xcursor_theme *wlr_xcursor_theme_load(const char *name, int size) { + struct wlr_xcursor_theme *theme = calloc(1, sizeof(*theme)); + if (!theme) { + return NULL; + } + + if (!name) { + name = "default"; + } + + theme->name = strdup(name); + if (!theme->name) { + goto out_error_name; + } + theme->size = size; + theme->cursor_count = 0; + theme->cursors = NULL; + + xcursor_load_theme(name, size, load_callback, theme); + + if (theme->cursor_count == 0) { + load_default_theme(theme); + } + + wlr_log(WLR_DEBUG, "Loaded cursor theme '%s' at size %d (%d available cursors)", + theme->name, size, theme->cursor_count); + + return theme; + +out_error_name: + free(theme); + return NULL; +} + +void wlr_xcursor_theme_destroy(struct wlr_xcursor_theme *theme) { + for (unsigned int i = 0; i < theme->cursor_count; i++) { + xcursor_destroy(theme->cursors[i]); + } + + free(theme->name); + free(theme->cursors); + free(theme); +} + +static struct wlr_xcursor *xcursor_theme_get_cursor(struct wlr_xcursor_theme *theme, + const char *name) { + for (unsigned int i = 0; i < theme->cursor_count; i++) { + if (strcmp(name, theme->cursors[i]->name) == 0) { + return theme->cursors[i]; + } + } + + return NULL; +} + +struct wlr_xcursor *wlr_xcursor_theme_get_cursor(struct wlr_xcursor_theme *theme, + const char *name) { + struct wlr_xcursor *xcursor = xcursor_theme_get_cursor(theme, name); + if (xcursor) { + return xcursor; + } + + // Try the legacy name as a fallback + const char *fallback; + if (strcmp(name, "default") == 0) { + fallback = "left_ptr"; + } else if (strcmp(name, "text") == 0) { + fallback = "xterm"; + } else if (strcmp(name, "pointer") == 0) { + fallback = "hand1"; + } else if (strcmp(name, "wait") == 0) { + fallback = "watch"; + } else if (strcmp(name, "all-scroll") == 0) { + fallback = "grabbing"; + } else if (strcmp(name, "sw-resize") == 0) { + fallback = "bottom_left_corner"; + } else if (strcmp(name, "se-resize") == 0) { + fallback = "bottom_right_corner"; + } else if (strcmp(name, "s-resize") == 0) { + fallback = "bottom_side"; + } else if (strcmp(name, "w-resize") == 0) { + fallback = "left_side"; + } else if (strcmp(name, "e-resize") == 0) { + fallback = "right_side"; + } else if (strcmp(name, "nw-resize") == 0) { + fallback = "top_left_corner"; + } else if (strcmp(name, "ne-resize") == 0) { + fallback = "top_right_corner"; + } else if (strcmp(name, "n-resize") == 0) { + fallback = "top_side"; + } else { + return NULL; + } + return xcursor_theme_get_cursor(theme, fallback); +} + +static int xcursor_frame_and_duration(struct wlr_xcursor *cursor, + uint32_t time, uint32_t *duration) { + if (cursor->image_count == 1) { + if (duration) { + *duration = 0; + } + return 0; + } + + int i = 0; + uint32_t t = time % cursor->total_delay; + + /* If there is a 0 delay in the image set then this + * loop breaks on it and we display that cursor until + * time % cursor->total_delay wraps again. + * Since a 0 delay is silly, and we've never actually + * seen one in a cursor file, we haven't bothered to + * "fix" this. + */ + while (t - cursor->images[i]->delay < t) { + t -= cursor->images[i++]->delay; + } + + if (!duration) { + return i; + } + + /* Make sure we don't accidentally tell the caller this is + * a static cursor image. + */ + if (t >= cursor->images[i]->delay) { + *duration = 1; + } else { + *duration = cursor->images[i]->delay - t; + } + + return i; +} + +int wlr_xcursor_frame(struct wlr_xcursor *_cursor, uint32_t time) { + return xcursor_frame_and_duration(_cursor, time, NULL); +} + +struct wlr_buffer *wlr_xcursor_image_get_buffer(struct wlr_xcursor_image *image) { + return &image->readonly_buffer->base; +} + +const char *wlr_xcursor_get_resize_name(enum wlr_edges edges) { + if (edges & WLR_EDGE_TOP) { + if (edges & WLR_EDGE_RIGHT) { + return "ne-resize"; + } else if (edges & WLR_EDGE_LEFT) { + return "nw-resize"; + } + return "n-resize"; + } else if (edges & WLR_EDGE_BOTTOM) { + if (edges & WLR_EDGE_RIGHT) { + return "se-resize"; + } else if (edges & WLR_EDGE_LEFT) { + return "sw-resize"; + } + return "s-resize"; + } else if (edges & WLR_EDGE_RIGHT) { + return "e-resize"; + } else if (edges & WLR_EDGE_LEFT) { + return "w-resize"; + } + return "se-resize"; // fallback +} diff --git a/3rdparty/wlroots/xcursor/xcursor.c b/3rdparty/wlroots/xcursor/xcursor.c new file mode 100644 index 0000000000..6627fb6cd7 --- /dev/null +++ b/3rdparty/wlroots/xcursor/xcursor.c @@ -0,0 +1,823 @@ +/* + * Copyright © 2002 Keith Packard + * + * 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 (including the + * next paragraph) 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. + */ + +#undef _POSIX_C_SOURCE +#define _DEFAULT_SOURCE // for d_type in struct dirent +#include +#include +#include +#include +#include +#include "config.h" +#include "xcursor/xcursor.h" + +/* + * Cursor files start with a header. The header + * contains a magic number, a version number and a + * table of contents which has type and offset information + * for the remaining tables in the file. + * + * File minor versions increment for compatible changes + * File major versions increment for incompatible changes (never, we hope) + * + * Chunks of the same type are always upward compatible. Incompatible + * changes are made with new chunk types; the old data can remain under + * the old type. Upward compatible changes can add header data as the + * header lengths are specified in the file. + * + * File: + * FileHeader + * LISTofChunk + * + * FileHeader: + * CARD32 magic magic number + * CARD32 header bytes in file header + * CARD32 version file version + * CARD32 ntoc number of toc entries + * LISTofFileToc toc table of contents + * + * FileToc: + * CARD32 type entry type + * CARD32 subtype entry subtype (size for images) + * CARD32 position absolute file position + */ + +#define XCURSOR_MAGIC 0x72756358 /* "Xcur" LSBFirst */ + +/* + * This version number is stored in cursor files; changes to the + * file format require updating this version number + */ +#define XCURSOR_FILE_MAJOR 1 +#define XCURSOR_FILE_MINOR 0 +#define XCURSOR_FILE_VERSION ((XCURSOR_FILE_MAJOR << 16) | (XCURSOR_FILE_MINOR)) +#define XCURSOR_FILE_HEADER_LEN (4 * 4) +#define XCURSOR_FILE_TOC_LEN (3 * 4) + +struct xcursor_file_toc { + uint32_t type; /* chunk type */ + uint32_t subtype; /* subtype (size for images) */ + uint32_t position; /* absolute position in file */ +}; + +struct xcursor_file_header { + uint32_t magic; /* magic number */ + uint32_t header; /* byte length of header */ + uint32_t version; /* file version number */ + uint32_t ntoc; /* number of toc entries */ + struct xcursor_file_toc *tocs; /* table of contents */ +}; + +/* + * The rest of the file is a list of chunks, each tagged by type + * and version. + * + * Chunk: + * ChunkHeader + * + * + * + * ChunkHeader: + * CARD32 header bytes in chunk header + type header + * CARD32 type chunk type + * CARD32 subtype chunk subtype + * CARD32 version chunk type version + */ + +#define XCURSOR_CHUNK_HEADER_LEN (4 * 4) + +struct xcursor_chunk_header { + uint32_t header; /* bytes in chunk header */ + uint32_t type; /* chunk type */ + uint32_t subtype; /* chunk subtype (size for images) */ + uint32_t version; /* version of this type */ +}; + +/* + * Each cursor image occupies a separate image chunk. + * The length of the image header follows the chunk header + * so that future versions can extend the header without + * breaking older applications + * + * Image: + * ChunkHeader header chunk header + * CARD32 width actual width + * CARD32 height actual height + * CARD32 xhot hot spot x + * CARD32 yhot hot spot y + * CARD32 delay animation delay + * LISTofCARD32 pixels ARGB pixels + */ + +#define XCURSOR_IMAGE_TYPE 0xfffd0002 +#define XCURSOR_IMAGE_VERSION 1 +#define XCURSOR_IMAGE_HEADER_LEN (XCURSOR_CHUNK_HEADER_LEN + (5*4)) +#define XCURSOR_IMAGE_MAX_SIZE 0x7fff /* 32767x32767 max cursor size */ + +/* + * From libXcursor/src/file.c + */ + +static struct xcursor_image * +xcursor_image_create(int width, int height) +{ + struct xcursor_image *image; + + if (width < 0 || height < 0) + return NULL; + if (width > XCURSOR_IMAGE_MAX_SIZE || height > XCURSOR_IMAGE_MAX_SIZE) + return NULL; + + image = malloc(sizeof(*image) + + width * height * sizeof(uint32_t)); + if (!image) + return NULL; + image->version = XCURSOR_IMAGE_VERSION; + image->pixels = (uint32_t *) (image + 1); + image->size = width > height ? width : height; + image->width = width; + image->height = height; + image->delay = 0; + return image; +} + +static void +xcursor_image_destroy(struct xcursor_image *image) +{ + free(image); +} + +static struct xcursor_images * +xcursor_images_create(int size) +{ + struct xcursor_images *images; + + images = malloc(sizeof(*images) + + size * sizeof(struct xcursor_image *)); + if (!images) + return NULL; + images->nimage = 0; + images->images = (struct xcursor_image **) (images + 1); + images->name = NULL; + return images; +} + +void +xcursor_images_destroy(struct xcursor_images *images) +{ + int n; + + if (!images) + return; + + for (n = 0; n < images->nimage; n++) + xcursor_image_destroy(images->images[n]); + free(images->name); + free(images); +} + +static bool +xcursor_read_uint(FILE *file, uint32_t *u) +{ + unsigned char bytes[4]; + + if (!file || !u) + return false; + + if (fread(bytes, 1, 4, file) != 4) + return false; + + *u = ((uint32_t)(bytes[0]) << 0) | + ((uint32_t)(bytes[1]) << 8) | + ((uint32_t)(bytes[2]) << 16) | + ((uint32_t)(bytes[3]) << 24); + return true; +} + +static void +xcursor_file_header_destroy(struct xcursor_file_header *file_header) +{ + free(file_header); +} + +static struct xcursor_file_header * +xcursor_file_header_create(uint32_t ntoc) +{ + struct xcursor_file_header *file_header; + + if (ntoc > 0x10000) + return NULL; + file_header = malloc(sizeof(*file_header) + + ntoc * sizeof(struct xcursor_file_toc)); + if (!file_header) + return NULL; + file_header->magic = XCURSOR_MAGIC; + file_header->header = XCURSOR_FILE_HEADER_LEN; + file_header->version = XCURSOR_FILE_VERSION; + file_header->ntoc = ntoc; + file_header->tocs = (struct xcursor_file_toc *) (file_header + 1); + return file_header; +} + +static struct xcursor_file_header * +xcursor_read_file_header(FILE *file) +{ + struct xcursor_file_header head, *file_header; + uint32_t skip; + unsigned int n; + + if (!file) + return NULL; + + if (!xcursor_read_uint(file, &head.magic)) + return NULL; + if (head.magic != XCURSOR_MAGIC) + return NULL; + if (!xcursor_read_uint(file, &head.header)) + return NULL; + if (!xcursor_read_uint(file, &head.version)) + return NULL; + if (!xcursor_read_uint(file, &head.ntoc)) + return NULL; + skip = head.header - XCURSOR_FILE_HEADER_LEN; + if (skip) + if (fseek(file, skip, SEEK_CUR) == EOF) + return NULL; + file_header = xcursor_file_header_create(head.ntoc); + if (!file_header) + return NULL; + file_header->magic = head.magic; + file_header->header = head.header; + file_header->version = head.version; + file_header->ntoc = head.ntoc; + for (n = 0; n < file_header->ntoc; n++) { + if (!xcursor_read_uint(file, &file_header->tocs[n].type)) + break; + if (!xcursor_read_uint(file, &file_header->tocs[n].subtype)) + break; + if (!xcursor_read_uint(file, &file_header->tocs[n].position)) + break; + } + if (n != file_header->ntoc) { + xcursor_file_header_destroy(file_header); + return NULL; + } + return file_header; +} + +static bool +xcursor_seek_to_toc(FILE *file, + struct xcursor_file_header *file_header, + int toc) +{ + if (!file || !file_header || + fseek(file, file_header->tocs[toc].position, SEEK_SET) == EOF) + return false; + return true; +} + +static bool +xcursor_file_read_chunk_header(FILE *file, + struct xcursor_file_header *file_header, + int toc, + struct xcursor_chunk_header *chunk_header) +{ + if (!file || !file_header || !chunk_header) + return false; + if (!xcursor_seek_to_toc(file, file_header, toc)) + return false; + if (!xcursor_read_uint(file, &chunk_header->header)) + return false; + if (!xcursor_read_uint(file, &chunk_header->type)) + return false; + if (!xcursor_read_uint(file, &chunk_header->subtype)) + return false; + if (!xcursor_read_uint(file, &chunk_header->version)) + return false; + /* sanity check */ + if (chunk_header->type != file_header->tocs[toc].type || + chunk_header->subtype != file_header->tocs[toc].subtype) + return false; + return true; +} + +static uint32_t +dist(uint32_t a, uint32_t b) +{ + return a > b ? a - b : b - a; +} + +static uint32_t +xcursor_file_best_size(struct xcursor_file_header *file_header, + uint32_t size, int *nsizesp) +{ + unsigned int n; + int nsizes = 0; + uint32_t best_size = 0; + uint32_t this_size; + + if (!file_header || !nsizesp) + return 0; + + for (n = 0; n < file_header->ntoc; n++) { + if (file_header->tocs[n].type != XCURSOR_IMAGE_TYPE) + continue; + this_size = file_header->tocs[n].subtype; + if (!best_size || dist(this_size, size) < dist(best_size, size)) { + best_size = this_size; + nsizes = 1; + } else if (this_size == best_size) { + nsizes++; + } + } + *nsizesp = nsizes; + return best_size; +} + +static int +xcursor_find_image_toc(struct xcursor_file_header *file_header, + uint32_t size, int count) +{ + unsigned int toc; + uint32_t this_size; + + if (!file_header) + return 0; + + for (toc = 0; toc < file_header->ntoc; toc++) { + if (file_header->tocs[toc].type != XCURSOR_IMAGE_TYPE) + continue; + this_size = file_header->tocs[toc].subtype; + if (this_size != size) + continue; + if (!count) + break; + count--; + } + if (toc == file_header->ntoc) + return -1; + return toc; +} + +static struct xcursor_image * +xcursor_read_image(FILE *file, + struct xcursor_file_header *file_header, + int toc) +{ + struct xcursor_chunk_header chunk_header; + struct xcursor_image head; + struct xcursor_image *image; + int n; + uint32_t *p; + + if (!file || !file_header) + return NULL; + + if (!xcursor_file_read_chunk_header(file, file_header, toc, &chunk_header)) + return NULL; + if (!xcursor_read_uint(file, &head.width)) + return NULL; + if (!xcursor_read_uint(file, &head.height)) + return NULL; + if (!xcursor_read_uint(file, &head.xhot)) + return NULL; + if (!xcursor_read_uint(file, &head.yhot)) + return NULL; + if (!xcursor_read_uint(file, &head.delay)) + return NULL; + /* sanity check data */ + if (head.width > XCURSOR_IMAGE_MAX_SIZE || + head.height > XCURSOR_IMAGE_MAX_SIZE) + return NULL; + if (head.width == 0 || head.height == 0) + return NULL; + if (head.xhot > head.width || head.yhot > head.height) + return NULL; + + /* Create the image and initialize it */ + image = xcursor_image_create(head.width, head.height); + if (image == NULL) + return NULL; + if (chunk_header.version < image->version) + image->version = chunk_header.version; + image->size = chunk_header.subtype; + image->xhot = head.xhot; + image->yhot = head.yhot; + image->delay = head.delay; + n = image->width * image->height; + p = image->pixels; + while (n--) { + if (!xcursor_read_uint(file, p)) { + xcursor_image_destroy(image); + return NULL; + } + p++; + } + return image; +} + +static struct xcursor_images * +xcursor_xc_file_load_images(FILE *file, int size) +{ + struct xcursor_file_header *file_header; + uint32_t best_size; + int nsize; + struct xcursor_images *images; + int n; + int toc; + + if (!file || size < 0) + return NULL; + file_header = xcursor_read_file_header(file); + if (!file_header) + return NULL; + best_size = xcursor_file_best_size(file_header, (uint32_t) size, &nsize); + if (!best_size) { + xcursor_file_header_destroy(file_header); + return NULL; + } + images = xcursor_images_create(nsize); + if (!images) { + xcursor_file_header_destroy(file_header); + return NULL; + } + for (n = 0; n < nsize; n++) { + toc = xcursor_find_image_toc(file_header, best_size, n); + if (toc < 0) + break; + images->images[images->nimage] = xcursor_read_image(file, file_header, + toc); + if (!images->images[images->nimage]) + break; + images->nimage++; + } + xcursor_file_header_destroy(file_header); + if (images->nimage != nsize) { + xcursor_images_destroy(images); + images = NULL; + } + return images; +} + +/* + * From libXcursor/src/library.c + */ + +#ifndef ICONDIR +#define ICONDIR "/usr/X11R6/lib/X11/icons" +#endif + +#ifndef XCURSORPATH +#define XCURSORPATH "~/.icons:/usr/share/icons:/usr/share/pixmaps:~/.cursors:/usr/share/cursors/xorg-x11:"ICONDIR +#endif + +#define XDG_DATA_HOME_FALLBACK "~/.local/share" +#define CURSORDIR "/icons" + +/** Get search path for cursor themes + * + * This function builds the list of directories to look for cursor + * themes in. The format is PATH-like: directories are separated by + * colons. + * + * The memory block returned by this function is allocated on the heap + * and must be freed by the caller. + */ +static char * +xcursor_library_path(void) +{ + const char *env_var, *suffix; + char *path; + size_t path_size; + + env_var = getenv("XCURSOR_PATH"); + if (env_var) + return strdup(env_var); + + env_var = getenv("XDG_DATA_HOME"); + if (!env_var || env_var[0] != '/') + env_var = XDG_DATA_HOME_FALLBACK; + + suffix = CURSORDIR ":" XCURSORPATH; + path_size = strlen(env_var) + strlen(suffix) + 1; + path = malloc(path_size); + if (!path) + return NULL; + snprintf(path, path_size, "%s%s", env_var, suffix); + return path; +} + +static char * +xcursor_build_theme_dir(const char *dir, const char *theme) +{ + const char *colon; + const char *tcolon; + char *full; + const char *home, *homesep; + size_t dirlen; + size_t homelen; + size_t themelen; + size_t full_size; + + if (!dir || !theme) + return NULL; + + colon = strchr(dir, ':'); + if (!colon) + colon = dir + strlen(dir); + + dirlen = colon - dir; + + tcolon = strchr(theme, ':'); + if (!tcolon) + tcolon = theme + strlen(theme); + + themelen = tcolon - theme; + + home = ""; + homelen = 0; + homesep = ""; + if (*dir == '~') { + home = getenv("HOME"); + if (!home) + return NULL; + homelen = strlen(home); + homesep = "/"; + dir++; + dirlen--; + } + + /* + * add space for any needed directory separators, one per component, + * and one for the trailing null + */ + full_size = 1 + homelen + 1 + dirlen + 1 + themelen + 1; + full = malloc(full_size); + if (!full) + return NULL; + snprintf(full, full_size, "%s%s%.*s/%.*s", home, homesep, + (int)dirlen, dir, (int)themelen, theme); + return full; +} + +static char * +xcursor_build_fullname(const char *dir, const char *subdir, const char *file) +{ + char *full; + size_t full_size; + + if (!dir || !subdir || !file) + return NULL; + + full_size = strlen(dir) + 1 + strlen(subdir) + 1 + strlen(file) + 1; + full = malloc(full_size); + if (!full) + return NULL; + snprintf(full, full_size, "%s/%s/%s", dir, subdir, file); + return full; +} + +static const char * +xcursor_next_path(const char *path) +{ + const char *colon = strchr(path, ':'); + + if (!colon) + return NULL; + return colon + 1; +} + +static bool +xcursor_white(char c) +{ + return c == ' ' || c == '\t' || c == '\n'; +} + +static bool +xcursor_sep(char c) +{ + return c == ';' || c == ','; +} + +static char * +xcursor_theme_inherits(const char *full) +{ + char *line = NULL; + size_t line_size = 0; + char *result = NULL; + FILE *f; + + if (!full) + return NULL; + + f = fopen(full, "r"); + if (!f) + return NULL; + + while (getline(&line, &line_size, f) >= 0) { + const char *l; + char *r; + + if (strncmp(line, "Inherits", 8)) + continue; + + l = line + 8; + while (*l == ' ') + l++; + if (*l != '=') + continue; + l++; + while (*l == ' ') + l++; + result = malloc(strlen(l) + 1); + if (!result) + break; + + r = result; + while (*l) { + while (xcursor_sep(*l) || xcursor_white(*l)) + l++; + if (!*l) + break; + if (r != result) + *r++ = ':'; + while (*l && !xcursor_white(*l) && !xcursor_sep(*l)) + *r++ = *l++; + } + *r++ = '\0'; + + break; + } + + fclose(f); + free(line); + + return result; +} + +static void +load_all_cursors_from_dir(const char *path, int size, + void (*load_callback)(struct xcursor_images *, void *), + void *user_data) +{ + FILE *f; + DIR *dir = opendir(path); + struct dirent *ent; + char *full; + struct xcursor_images *images; + + if (!dir) + return; + + for (ent = readdir(dir); ent; ent = readdir(dir)) { +#ifdef _DIRENT_HAVE_D_TYPE + if (ent->d_type != DT_UNKNOWN && + ent->d_type != DT_REG && + ent->d_type != DT_LNK) + continue; +#endif + + full = xcursor_build_fullname(path, "", ent->d_name); + if (!full) + continue; + + f = fopen(full, "r"); + if (!f) { + free(full); + continue; + } + + images = xcursor_xc_file_load_images(f, size); + + if (images) { + images->name = strdup(ent->d_name); + load_callback(images, user_data); + } + + fclose(f); + free(full); + } + + closedir(dir); +} + +struct xcursor_nodelist { + size_t nodelen; + const char *node; + struct xcursor_nodelist *next; +}; + +static bool +nodelist_contains(struct xcursor_nodelist *nodelist, const char *s, size_t ss) { + struct xcursor_nodelist *vi; + for (vi = nodelist; vi && vi->node; vi = vi->next) { + if (vi->nodelen == ss && !strncmp(s, vi->node, vi->nodelen)) + return true; + } + return false; +} + +static void +xcursor_load_theme_protected(const char *theme, + int size, + void (*load_callback)(struct xcursor_images *, void *), + void *user_data, + struct xcursor_nodelist *visited_nodes) +{ + char *full, *dir; + char *inherits = NULL; + const char *path, *i; + char *xcursor_path; + size_t si; + struct xcursor_nodelist current_node; + + if (!theme) + theme = "default"; + + current_node.next = visited_nodes; + current_node.node = theme; + current_node.nodelen = strlen(theme); + visited_nodes = ¤t_node; + + xcursor_path = xcursor_library_path(); + for (path = xcursor_path; + path; + path = xcursor_next_path(path)) { + dir = xcursor_build_theme_dir(path, theme); + if (!dir) + continue; + + full = xcursor_build_fullname(dir, "cursors", ""); + if (full) { + load_all_cursors_from_dir(full, size, load_callback, + user_data); + free(full); + } + + if (!inherits) { + full = xcursor_build_fullname(dir, "", "index.theme"); + inherits = xcursor_theme_inherits(full); + free(full); + } + + free(dir); + } + + for (i = inherits; i; i = xcursor_next_path(i)) { + si = strlen(i); + if (nodelist_contains(visited_nodes, i, si)) + continue; + xcursor_load_theme_protected(i, size, load_callback, user_data, visited_nodes); + } + + free(inherits); + free(xcursor_path); +} + +/** Load all the cursor of a theme + * + * This function loads all the cursor images of a given theme and its + * inherited themes. Each cursor is loaded into an struct xcursor_images object + * which is passed to the caller's load callback. If a cursor appears + * more than once across all the inherited themes, the load callback + * will be called multiple times, with possibly different struct xcursor_images + * object which have the same name. The user is expected to destroy the + * struct xcursor_images objects passed to the callback with + * xcursor_images_destroy(). + * + * \param theme The name of theme that should be loaded + * \param size The desired size of the cursor images + * \param load_callback A callback function that will be called + * for each cursor loaded. The first parameter is the struct xcursor_images + * object representing the loaded cursor and the second is a pointer + * to data provided by the user. + * \param user_data The data that should be passed to the load callback + */ +void +xcursor_load_theme(const char *theme, int size, + void (*load_callback)(struct xcursor_images *, void *), + void *user_data) { + return xcursor_load_theme_protected(theme, size, load_callback, user_data, NULL); +} diff --git a/3rdparty/wlroots/xwayland/meson.build b/3rdparty/wlroots/xwayland/meson.build new file mode 100644 index 0000000000..795bdce58d --- /dev/null +++ b/3rdparty/wlroots/xwayland/meson.build @@ -0,0 +1,97 @@ +xwayland_libs = [] +xwayland_required = { + 'xcb': [], + 'xcb-composite': [], + 'xcb-ewmh': [], + 'xcb-icccm': [], + 'xcb-render': [], + 'xcb-res': [], + 'xcb-xfixes': '>=1.15', + 'xcb-shape': [], +} +xwayland_optional = { + 'xcb-errors': 'Required for printing X11 errors.', +} + +msg = [] +if get_option('xwayland').enabled() + msg += 'Install "@0@" or pass "-Dxwayland=disabled".' +endif +if not get_option('xwayland').disabled() + msg += 'Required for Xwayland support.' +endif + +xwayland = dependency( + 'xwayland', + required: get_option('xwayland'), + fallback: 'xserver', + default_options: [ + 'werror=false', + 'xorg=false', + 'xephyr=false', + 'xwayland=true', + 'xnest=false', + 'xvfb=false', + ], +) +if not xwayland.found() + subdir_done() +endif + +foreach lib, version : xwayland_required + dep = dependency(lib, + version: version, + required: get_option('xwayland'), + not_found_message: '\n'.join(msg).format(lib), + ) + if not dep.found() + subdir_done() + endif + + xwayland_libs += dep +endforeach + +foreach lib, desc : xwayland_optional + msg = [] + if get_option(lib).enabled() + msg += 'Install "@0@" or pass "-D@0@=disabled".' + endif + if not get_option(lib).disabled() + msg += desc + endif + + dep = dependency(lib, + required: get_option(lib), + not_found_message: '\n'.join(msg).format(lib), + ) + + internal_features += { lib: dep.found() } + xwayland_libs += dep +endforeach + +xwayland_feature_names = [ + 'listenfd', + 'no_touch_pointer_emulation', + 'force_xrandr_emulation', + 'terminate_delay', +] + +internal_config.set_quoted('XWAYLAND_PATH', xwayland.get_variable('xwayland')) +foreach name : xwayland_feature_names + have = xwayland.get_variable('have_' + name, default_value: 'false') == 'true' + internal_config.set10('HAVE_XWAYLAND_' + name.to_upper(), have) +endforeach + +wlr_files += files( + 'selection/dnd.c', + 'selection/incoming.c', + 'selection/outgoing.c', + 'selection/selection.c', + 'server.c', + 'shell.c', + 'sockets.c', + 'xwayland.c', + 'xwm.c', +) +wlr_deps += xwayland_libs +features += { 'xwayland': true } diff --git a/3rdparty/wlroots/xwayland/selection/dnd.c b/3rdparty/wlroots/xwayland/selection/dnd.c new file mode 100644 index 0000000000..f80a55d4d4 --- /dev/null +++ b/3rdparty/wlroots/xwayland/selection/dnd.c @@ -0,0 +1,393 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "xwayland/xwm.h" +#include "xwayland/selection.h" + +static xcb_atom_t data_device_manager_dnd_action_to_atom( + struct wlr_xwm *xwm, enum wl_data_device_manager_dnd_action action) { + if (action & WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY) { + return xwm->atoms[DND_ACTION_COPY]; + } else if (action & WL_DATA_DEVICE_MANAGER_DND_ACTION_MOVE) { + return xwm->atoms[DND_ACTION_MOVE]; + } else if (action & WL_DATA_DEVICE_MANAGER_DND_ACTION_ASK) { + return xwm->atoms[DND_ACTION_ASK]; + } + return XCB_ATOM_NONE; +} + +static enum wl_data_device_manager_dnd_action + data_device_manager_dnd_action_from_atom(struct wlr_xwm *xwm, + xcb_atom_t atom) { + if (atom == xwm->atoms[DND_ACTION_COPY] || + atom == xwm->atoms[DND_ACTION_PRIVATE]) { + return WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY; + } else if (atom == xwm->atoms[DND_ACTION_MOVE]) { + return WL_DATA_DEVICE_MANAGER_DND_ACTION_MOVE; + } else if (atom == xwm->atoms[DND_ACTION_ASK]) { + return WL_DATA_DEVICE_MANAGER_DND_ACTION_ASK; + } + return WL_DATA_DEVICE_MANAGER_DND_ACTION_NONE; +} + +static void xwm_dnd_send_event(struct wlr_xwm *xwm, xcb_atom_t type, + xcb_client_message_data_t *data) { + struct wlr_xwayland_surface *dest = xwm->drag_focus; + assert(dest != NULL); + + xcb_client_message_event_t event = { + .response_type = XCB_CLIENT_MESSAGE, + .format = 32, + .sequence = 0, + .window = dest->window_id, + .type = type, + .data = *data, + }; + + xwm_send_event_with_size(xwm->xcb_conn, + 0, // propagate + dest->window_id, + XCB_EVENT_MASK_NO_EVENT, + &event, + sizeof(event)); + xwm_schedule_flush(xwm); +} + +static void xwm_dnd_send_enter(struct wlr_xwm *xwm) { + struct wlr_drag *drag = xwm->drag; + assert(drag != NULL); + struct wl_array *mime_types = &drag->source->mime_types; + + xcb_client_message_data_t data = { 0 }; + data.data32[0] = xwm->dnd_selection.window; + data.data32[1] = XDND_VERSION << 24; + + // If we have 3 MIME types or less, we can send them directly in the + // DND_ENTER message + size_t n = mime_types->size / sizeof(char *); + if (n <= 3) { + size_t i = 0; + char **mime_type_ptr; + wl_array_for_each(mime_type_ptr, mime_types) { + char *mime_type = *mime_type_ptr; + data.data32[2+i] = xwm_mime_type_to_atom(xwm, mime_type); + ++i; + } + } else { + // Let the client know that targets are not contained in the message + // data and must be retrieved with the DND_TYPE_LIST property + data.data32[1] |= 1; + + xcb_atom_t *targets = malloc(n * sizeof(targets[0])); + if (targets == NULL) { + wlr_log(WLR_ERROR, "Allocation failed"); + return; + } + + size_t i = 0; + char **mime_type_ptr; + wl_array_for_each(mime_type_ptr, mime_types) { + char *mime_type = *mime_type_ptr; + targets[i] = xwm_mime_type_to_atom(xwm, mime_type); + ++i; + } + + xcb_change_property(xwm->xcb_conn, + XCB_PROP_MODE_REPLACE, + xwm->dnd_selection.window, + xwm->atoms[DND_TYPE_LIST], + XCB_ATOM_ATOM, + 32, // format + n, targets); + + free(targets); + } + + xwm_dnd_send_event(xwm, xwm->atoms[DND_ENTER], &data); +} + +static void xwm_dnd_send_position(struct wlr_xwm *xwm, uint32_t time, int16_t x, + int16_t y) { + struct wlr_drag *drag = xwm->drag; + assert(drag != NULL); + + xcb_client_message_data_t data = { 0 }; + data.data32[0] = xwm->dnd_selection.window; + data.data32[2] = (x << 16) | y; + data.data32[3] = time; + data.data32[4] = + data_device_manager_dnd_action_to_atom(xwm, drag->source->actions); + + xwm_dnd_send_event(xwm, xwm->atoms[DND_POSITION], &data); +} + +static void xwm_dnd_send_drop(struct wlr_xwm *xwm, uint32_t time) { + struct wlr_drag *drag = xwm->drag; + assert(drag != NULL); + struct wlr_xwayland_surface *dest = xwm->drag_focus; + assert(dest != NULL); + + xcb_client_message_data_t data = { 0 }; + data.data32[0] = xwm->dnd_selection.window; + data.data32[2] = time; + + xwm_dnd_send_event(xwm, xwm->atoms[DND_DROP], &data); +} + +static void xwm_dnd_send_leave(struct wlr_xwm *xwm) { + struct wlr_drag *drag = xwm->drag; + assert(drag != NULL); + struct wlr_xwayland_surface *dest = xwm->drag_focus; + assert(dest != NULL); + + xcb_client_message_data_t data = { 0 }; + data.data32[0] = xwm->dnd_selection.window; + + xwm_dnd_send_event(xwm, xwm->atoms[DND_LEAVE], &data); +} + +/*static void xwm_dnd_send_finished(struct wlr_xwm *xwm) { + struct wlr_drag *drag = xwm->drag; + assert(drag != NULL); + struct wlr_xwayland_surface *dest = xwm->drag_focus; + assert(dest != NULL); + + xcb_client_message_data_t data = { 0 }; + data.data32[0] = xwm->dnd_selection.window; + data.data32[1] = drag->source->accepted; + + if (drag->source->accepted) { + data.data32[2] = data_device_manager_dnd_action_to_atom(xwm, + drag->source->current_dnd_action); + } + + xwm_dnd_send_event(xwm, xwm->atoms[DND_FINISHED], &data); +}*/ + +int xwm_handle_selection_client_message(struct wlr_xwm *xwm, + xcb_client_message_event_t *ev) { + if (ev->type == xwm->atoms[DND_STATUS]) { + if (xwm->drag == NULL) { + wlr_log(WLR_DEBUG, "ignoring XdndStatus client message because " + "there's no drag"); + return 1; + } + + xcb_client_message_data_t *data = &ev->data; + xcb_window_t target_window = data->data32[0]; + bool accepted = data->data32[1] & 1; + xcb_atom_t action_atom = data->data32[4]; + + if (xwm->drag_focus == NULL || + target_window != xwm->drag_focus->window_id) { + wlr_log(WLR_DEBUG, "ignoring XdndStatus client message because " + "it doesn't match the current drag focus window ID"); + return 1; + } + + enum wl_data_device_manager_dnd_action action = + data_device_manager_dnd_action_from_atom(xwm, action_atom); + + struct wlr_drag *drag = xwm->drag; + assert(drag != NULL); + + drag->source->accepted = accepted; + wlr_data_source_dnd_action(drag->source, action); + + wlr_log(WLR_DEBUG, "DND_STATUS window=%" PRIu32 " accepted=%d action=%d", + target_window, accepted, action); + return 1; + } else if (ev->type == xwm->atoms[DND_FINISHED]) { + // This should only happen after the drag has ended, but before the drag + // source is destroyed + if (xwm->seat == NULL || xwm->seat->drag_source == NULL || + xwm->drag != NULL) { + wlr_log(WLR_DEBUG, "ignoring XdndFinished client message because " + "there's no finished drag"); + return 1; + } + + struct wlr_data_source *source = xwm->seat->drag_source; + + xcb_client_message_data_t *data = &ev->data; + xcb_window_t target_window = data->data32[0]; + bool performed = data->data32[1] & 1; + xcb_atom_t action_atom = data->data32[2]; + + if (xwm->drop_focus == NULL || + target_window != xwm->drop_focus->window_id) { + wlr_log(WLR_DEBUG, "ignoring XdndFinished client message because " + "it doesn't match the finished drop focus window ID"); + return 1; + } + + enum wl_data_device_manager_dnd_action action = + data_device_manager_dnd_action_from_atom(xwm, action_atom); + + wlr_data_source_dnd_finish(source); + wlr_log(WLR_DEBUG, "DND_FINISH window=%" PRIu32 " performed=%d action=%d", + target_window, performed, action); + return 1; + } else { + return 0; + } +} + +static void xwm_set_drag_focus(struct wlr_xwm *xwm, struct wlr_xwayland_surface *focus); + +static void drag_focus_handle_destroy(struct wl_listener *listener, void *data) { + struct wlr_xwm *xwm = wl_container_of(listener, xwm, drag_focus_destroy); + xwm_set_drag_focus(xwm, NULL); +} + +static void drop_focus_handle_destroy(struct wl_listener *listener, void *data) { + struct wlr_xwm *xwm = wl_container_of(listener, xwm, drop_focus_destroy); + wl_list_remove(&xwm->drop_focus_destroy.link); + wl_list_init(&xwm->drop_focus_destroy.link); + xwm->drop_focus = NULL; +} + +static void xwm_set_drag_focus(struct wlr_xwm *xwm, struct wlr_xwayland_surface *focus) { + if (focus == xwm->drag_focus) { + return; + } + + if (xwm->drag_focus != NULL) { + wlr_data_source_dnd_action(xwm->drag->source, + WL_DATA_DEVICE_MANAGER_DND_ACTION_NONE); + xwm_dnd_send_leave(xwm); + } + + wl_list_remove(&xwm->drag_focus_destroy.link); + wl_list_init(&xwm->drag_focus_destroy.link); + + xwm->drag_focus = focus; + + if (xwm->drag_focus != NULL) { + xwm->drag_focus_destroy.notify = drag_focus_handle_destroy; + wl_signal_add(&xwm->drag_focus->events.destroy, &xwm->drag_focus_destroy); + + xwm_dnd_send_enter(xwm); + } +} + +static void seat_handle_drag_focus(struct wl_listener *listener, void *data) { + struct wlr_drag *drag = data; + struct wlr_xwm *xwm = wl_container_of(listener, xwm, seat_drag_focus); + + struct wlr_xwayland_surface *focus = NULL; + if (drag->focus != NULL) { + focus = wlr_xwayland_surface_try_from_wlr_surface(drag->focus); + } + + xwm_set_drag_focus(xwm, focus); +} + +static void seat_handle_drag_motion(struct wl_listener *listener, void *data) { + struct wlr_xwm *xwm = wl_container_of(listener, xwm, seat_drag_motion); + struct wlr_drag_motion_event *event = data; + struct wlr_xwayland_surface *surface = xwm->drag_focus; + + if (surface == NULL) { + return; // No xwayland surface focused + } + + xwm_dnd_send_position(xwm, event->time, surface->x + (int16_t)event->sx, + surface->y + (int16_t)event->sy); +} + +static void seat_handle_drag_drop(struct wl_listener *listener, void *data) { + struct wlr_xwm *xwm = wl_container_of(listener, xwm, seat_drag_drop); + struct wlr_drag_drop_event *event = data; + + if (xwm->drag_focus == NULL) { + return; // No xwayland surface focused + } + + wlr_log(WLR_DEBUG, "Wayland drag dropped over an Xwayland window"); + + xwm->drop_focus = xwm->drag_focus; + xwm->drop_focus_destroy.notify = drop_focus_handle_destroy; + wl_list_remove(&xwm->drop_focus_destroy.link); + wl_signal_add(&xwm->drop_focus->events.destroy, &xwm->drop_focus_destroy); + + xwm_dnd_send_drop(xwm, event->time); +} + +static void seat_handle_drag_destroy(struct wl_listener *listener, void *data) { + struct wlr_xwm *xwm = wl_container_of(listener, xwm, seat_drag_destroy); + + // Don't reset drag focus yet because the target will read the drag source + // right after + if (xwm->drag_focus != NULL && !xwm->drag->source->accepted) { + wlr_log(WLR_DEBUG, "Wayland drag cancelled over an Xwayland window"); + xwm_dnd_send_leave(xwm); + } + + wl_list_remove(&xwm->seat_drag_focus.link); + wl_list_remove(&xwm->seat_drag_motion.link); + wl_list_remove(&xwm->seat_drag_drop.link); + wl_list_remove(&xwm->seat_drag_destroy.link); + xwm->drag = NULL; +} + +static void seat_handle_drag_source_destroy(struct wl_listener *listener, + void *data) { + struct wlr_xwm *xwm = + wl_container_of(listener, xwm, seat_drag_source_destroy); + + wl_list_remove(&xwm->seat_drag_source_destroy.link); + wl_list_init(&xwm->seat_drag_source_destroy.link); + wl_list_remove(&xwm->drag_focus_destroy.link); + wl_list_init(&xwm->drag_focus_destroy.link); + xwm->drag_focus = NULL; + + wl_list_remove(&xwm->drop_focus_destroy.link); + wl_list_init(&xwm->drop_focus_destroy.link); + xwm->drop_focus = NULL; +} + +void xwm_seat_handle_start_drag(struct wlr_xwm *xwm, struct wlr_drag *drag) { + wl_list_remove(&xwm->drag_focus_destroy.link); + wl_list_init(&xwm->drag_focus_destroy.link); + wl_list_remove(&xwm->drop_focus_destroy.link); + wl_list_init(&xwm->drop_focus_destroy.link); + + xwm->drag = drag; + xwm->drag_focus = NULL; + xwm->drop_focus = NULL; + + if (drag != NULL) { + wl_signal_add(&drag->events.focus, &xwm->seat_drag_focus); + xwm->seat_drag_focus.notify = seat_handle_drag_focus; + wl_signal_add(&drag->events.motion, &xwm->seat_drag_motion); + xwm->seat_drag_motion.notify = seat_handle_drag_motion; + wl_signal_add(&drag->events.drop, &xwm->seat_drag_drop); + xwm->seat_drag_drop.notify = seat_handle_drag_drop; + wl_signal_add(&drag->events.destroy, &xwm->seat_drag_destroy); + xwm->seat_drag_destroy.notify = seat_handle_drag_destroy; + + wl_signal_add(&drag->source->events.destroy, + &xwm->seat_drag_source_destroy); + xwm->seat_drag_source_destroy.notify = seat_handle_drag_source_destroy; + } +} + +void xwm_seat_unlink_drag_handlers(struct wlr_xwm *xwm) { + wl_list_remove(&xwm->seat_drag_source_destroy.link); + wl_list_remove(&xwm->drag_focus_destroy.link); + wl_list_remove(&xwm->drop_focus_destroy.link); + + if (!xwm->drag) { + return; + } + wl_list_remove(&xwm->seat_drag_focus.link); + wl_list_remove(&xwm->seat_drag_motion.link); + wl_list_remove(&xwm->seat_drag_drop.link); + wl_list_remove(&xwm->seat_drag_destroy.link); +} diff --git a/3rdparty/wlroots/xwayland/selection/incoming.c b/3rdparty/wlroots/xwayland/selection/incoming.c new file mode 100644 index 0000000000..97a889617f --- /dev/null +++ b/3rdparty/wlroots/xwayland/selection/incoming.c @@ -0,0 +1,542 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "xwayland/selection.h" +#include "xwayland/xwm.h" + +static struct wlr_xwm_selection_transfer * +xwm_selection_transfer_create_incoming(struct wlr_xwm_selection *selection) { + struct wlr_xwm_selection_transfer *transfer = calloc(1, sizeof(*transfer)); + if (!transfer) { + return NULL; + } + + xwm_selection_transfer_init(transfer, selection); + + wl_list_insert(&selection->incoming, &transfer->link); + + struct wlr_xwm *xwm = selection->xwm; + transfer->incoming_window = xcb_generate_id(xwm->xcb_conn); + xcb_create_window( + xwm->xcb_conn, + XCB_COPY_FROM_PARENT, + transfer->incoming_window, + xwm->screen->root, + 0, 0, + 10, 10, + 0, + XCB_WINDOW_CLASS_INPUT_OUTPUT, + xwm->screen->root_visual, + XCB_CW_EVENT_MASK, (uint32_t[]){ + XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_PROPERTY_CHANGE + } + ); + xwm_schedule_flush(xwm); + + return transfer; +} + +struct wlr_xwm_selection_transfer * +xwm_selection_find_incoming_transfer_by_window( + struct wlr_xwm_selection *selection, xcb_window_t window) { + struct wlr_xwm_selection_transfer *transfer; + wl_list_for_each(transfer, &selection->incoming, link) { + if (transfer->incoming_window == window) { + return transfer; + } + } + + return NULL; +} + +static bool xwm_selection_transfer_get_incoming_selection_property( + struct wlr_xwm_selection_transfer *transfer, bool delete) { + struct wlr_xwm *xwm = transfer->selection->xwm; + + xcb_get_property_cookie_t cookie = xcb_get_property( + xwm->xcb_conn, + delete, + transfer->incoming_window, + xwm->atoms[WL_SELECTION], + XCB_GET_PROPERTY_TYPE_ANY, + 0, // offset + 0x1fffffff // length + ); + + transfer->property_start = 0; + transfer->property_reply = + xcb_get_property_reply(xwm->xcb_conn, cookie, NULL); + + if (!transfer->property_reply) { + wlr_log(WLR_ERROR, "cannot get selection property"); + return false; + } + + return true; +} + +static void xwm_notify_ready_for_next_incr_chunk( + struct wlr_xwm_selection_transfer *transfer) { + struct wlr_xwm *xwm = transfer->selection->xwm; + assert(transfer->incr); + + wlr_log(WLR_DEBUG, "deleting property"); + xcb_delete_property(xwm->xcb_conn, transfer->incoming_window, + xwm->atoms[WL_SELECTION]); + xwm_schedule_flush(xwm); + + xwm_selection_transfer_remove_event_source(transfer); + xwm_selection_transfer_destroy_property_reply(transfer); +} + +/** + * Write the X11 selection to a Wayland client. Returns a nonzero value if the + * Wayland client might become writeable again in the future. + */ +static int write_selection_property_to_wl_client(int fd, uint32_t mask, + void *data) { + struct wlr_xwm_selection_transfer *transfer = data; + + const char *property = xcb_get_property_value(transfer->property_reply); + int remainder = xcb_get_property_value_length(transfer->property_reply) - + transfer->property_start; + + ssize_t len = write(fd, property + transfer->property_start, remainder); + if (len == -1) { + wlr_log_errno(WLR_ERROR, "write error to target fd %d", fd); + xwm_selection_transfer_destroy(transfer); + return 0; + } + + wlr_log(WLR_DEBUG, + "wrote %zd (total %zd, remaining %d) of %d bytes to fd %d", + len, transfer->property_start + len, remainder, + xcb_get_property_value_length(transfer->property_reply), fd); + + if (len < remainder) { + transfer->property_start += len; + return 1; + } else if (transfer->incr) { + xwm_notify_ready_for_next_incr_chunk(transfer); + } else { + wlr_log(WLR_DEBUG, "transfer complete"); + xwm_selection_transfer_destroy(transfer); + } + + return 0; +} + +static void xwm_write_selection_property_to_wl_client( + struct wlr_xwm_selection_transfer *transfer) { + if (transfer->incr && transfer->wl_client_fd < 0) { + // Wayland client closed its pipe prematurely before the X11 client finished + // its incremental transfer. Continue draining the X11 client. + xwm_notify_ready_for_next_incr_chunk(transfer); + return; + } + + bool wl_client_finished_consuming = !write_selection_property_to_wl_client( + transfer->wl_client_fd, WL_EVENT_WRITABLE, transfer); + if (!wl_client_finished_consuming) { + // Wrote out part of the property to the Wayland client, but the client was + // unable to accept all of it. Schedule an event to asynchronously complete + // the transfer. + struct wl_event_loop *loop = + wl_display_get_event_loop(transfer->selection->xwm->xwayland->wl_display); + transfer->event_source = wl_event_loop_add_fd(loop, + transfer->wl_client_fd, WL_EVENT_WRITABLE, + write_selection_property_to_wl_client, transfer); + } +} + +void xwm_get_incr_chunk(struct wlr_xwm_selection_transfer *transfer) { + wlr_log(WLR_DEBUG, "xwm_get_incr_chunk"); + + if (transfer->property_reply) { + wlr_log(WLR_ERROR, "X11 client offered a new property before we deleted"); + return; + } + + if (!xwm_selection_transfer_get_incoming_selection_property(transfer, false)) { + return; + } + + if (xcb_get_property_value_length(transfer->property_reply) > 0) { + xwm_write_selection_property_to_wl_client(transfer); + } else { + wlr_log(WLR_DEBUG, "incremental transfer complete"); + xwm_selection_transfer_destroy(transfer); + } +} + +static void xwm_selection_transfer_get_data( + struct wlr_xwm_selection_transfer *transfer) { + struct wlr_xwm *xwm = transfer->selection->xwm; + + if (!xwm_selection_transfer_get_incoming_selection_property(transfer, true)) { + return; + } + + if (transfer->property_reply->type == xwm->atoms[INCR]) { + transfer->incr = true; + xwm_selection_transfer_destroy_property_reply(transfer); + } else { + // Reply's ownership is transferred to wm, which is responsible for freeing + // it. + xwm_write_selection_property_to_wl_client(transfer); + } +} + +static void source_send(struct wlr_xwm_selection *selection, + struct wl_array *mime_types, struct wl_array *mime_types_atoms, + const char *requested_mime_type, int fd) { + struct wlr_xwm *xwm = selection->xwm; + + xcb_atom_t *atoms = mime_types_atoms->data; + bool found = false; + xcb_atom_t mime_type_atom; + char **mime_type_ptr; + size_t i = 0; + wl_array_for_each(mime_type_ptr, mime_types) { + char *mime_type = *mime_type_ptr; + if (strcmp(mime_type, requested_mime_type) == 0) { + found = true; + mime_type_atom = atoms[i]; + break; + } + ++i; + } + if (!found) { + wlr_log(WLR_DEBUG, "Cannot send X11 selection to Wayland: " + "unsupported MIME type"); + close(fd); + return; + } + + struct wlr_xwm_selection_transfer *transfer = + xwm_selection_transfer_create_incoming(selection); + if (!transfer) { + wlr_log(WLR_ERROR, "Cannot create transfer"); + close(fd); + return; + } + + xcb_convert_selection(xwm->xcb_conn, + transfer->incoming_window, + selection->atom, + mime_type_atom, + xwm->atoms[WL_SELECTION], + XCB_TIME_CURRENT_TIME); + + xwm_schedule_flush(xwm); + + fcntl(fd, F_SETFL, O_WRONLY | O_NONBLOCK); + transfer->wl_client_fd = fd; +} + +struct x11_data_source { + struct wlr_data_source base; + struct wlr_xwm_selection *selection; + struct wl_array mime_types_atoms; +}; + +static const struct wlr_data_source_impl data_source_impl; + +bool data_source_is_xwayland( + struct wlr_data_source *wlr_source) { + return wlr_source->impl == &data_source_impl; +} + +static struct x11_data_source *data_source_from_wlr_data_source( + struct wlr_data_source *wlr_source) { + assert(data_source_is_xwayland(wlr_source)); + struct x11_data_source *source = wl_container_of(wlr_source, source, base); + return source; +} + +static void data_source_send(struct wlr_data_source *wlr_source, + const char *mime_type, int32_t fd) { + struct x11_data_source *source = + data_source_from_wlr_data_source(wlr_source); + struct wlr_xwm_selection *selection = source->selection; + + source_send(selection, &wlr_source->mime_types, &source->mime_types_atoms, + mime_type, fd); +} + +static void data_source_destroy(struct wlr_data_source *wlr_source) { + struct x11_data_source *source = + data_source_from_wlr_data_source(wlr_source); + wl_array_release(&source->mime_types_atoms); + free(source); +} + +static const struct wlr_data_source_impl data_source_impl = { + .send = data_source_send, + .destroy = data_source_destroy, +}; + +struct x11_primary_selection_source { + struct wlr_primary_selection_source base; + struct wlr_xwm_selection *selection; + struct wl_array mime_types_atoms; +}; + +static const struct wlr_primary_selection_source_impl + primary_selection_source_impl; + +bool primary_selection_source_is_xwayland( + struct wlr_primary_selection_source *wlr_source) { + return wlr_source->impl == &primary_selection_source_impl; +} + +static void primary_selection_source_send( + struct wlr_primary_selection_source *wlr_source, + const char *mime_type, int fd) { + struct x11_primary_selection_source *source = wl_container_of(wlr_source, source, base); + struct wlr_xwm_selection *selection = source->selection; + + source_send(selection, &wlr_source->mime_types, &source->mime_types_atoms, + mime_type, fd); +} + +static void primary_selection_source_destroy( + struct wlr_primary_selection_source *wlr_source) { + struct x11_primary_selection_source *source = wl_container_of(wlr_source, source, base); + wl_array_release(&source->mime_types_atoms); + free(source); +} + +static const struct wlr_primary_selection_source_impl + primary_selection_source_impl = { + .send = primary_selection_source_send, + .destroy = primary_selection_source_destroy, +}; + +static bool source_get_targets(struct wlr_xwm_selection *selection, + struct wl_array *mime_types, struct wl_array *mime_types_atoms) { + struct wlr_xwm *xwm = selection->xwm; + + xcb_get_property_cookie_t cookie = xcb_get_property(xwm->xcb_conn, + 1, // delete + selection->window, + xwm->atoms[WL_SELECTION], + XCB_GET_PROPERTY_TYPE_ANY, + 0, // offset + 4096 // length + ); + + xcb_get_property_reply_t *reply = + xcb_get_property_reply(xwm->xcb_conn, cookie, NULL); + if (reply == NULL) { + return false; + } + + if (reply->type != XCB_ATOM_ATOM) { + free(reply); + return false; + } + + const xcb_atom_t *value = xcb_get_property_value(reply); + uint32_t value_len = xcb_get_property_value_length(reply) / sizeof(value[0]); + for (uint32_t i = 0; i < value_len; i++) { + char *mime_type = NULL; + + if (value[i] == xwm->atoms[UTF8_STRING]) { + mime_type = strdup("text/plain;charset=utf-8"); + } else if (value[i] == xwm->atoms[TEXT]) { + mime_type = strdup("text/plain"); + } else if (value[i] != xwm->atoms[TARGETS] && + value[i] != xwm->atoms[TIMESTAMP]) { + xcb_get_atom_name_cookie_t name_cookie = + xcb_get_atom_name(xwm->xcb_conn, value[i]); + xcb_get_atom_name_reply_t *name_reply = + xcb_get_atom_name_reply(xwm->xcb_conn, name_cookie, NULL); + if (name_reply == NULL) { + continue; + } + size_t len = xcb_get_atom_name_name_length(name_reply); + char *name = xcb_get_atom_name_name(name_reply); // not a C string + if (memchr(name, '/', len) != NULL) { + mime_type = malloc((len + 1) * sizeof(char)); + if (mime_type == NULL) { + free(name_reply); + continue; + } + memcpy(mime_type, name, len); + mime_type[len] = '\0'; + } + free(name_reply); + } + + if (mime_type != NULL) { + char **mime_type_ptr = + wl_array_add(mime_types, sizeof(*mime_type_ptr)); + if (mime_type_ptr == NULL) { + free(mime_type); + break; + } + + xcb_atom_t *atom_ptr = + wl_array_add(mime_types_atoms, sizeof(*atom_ptr)); + if (atom_ptr == NULL) { + mime_types->size -= sizeof(*mime_type_ptr); + free(mime_type); + break; + } + *mime_type_ptr = mime_type; + *atom_ptr = value[i]; + } + } + + free(reply); + return true; +} + +static void xwm_selection_get_targets(struct wlr_xwm_selection *selection) { + // set the wayland selection to the X11 selection + struct wlr_xwm *xwm = selection->xwm; + + if (selection == &xwm->clipboard_selection) { + struct x11_data_source *source = calloc(1, sizeof(*source)); + if (source == NULL) { + return; + } + wlr_data_source_init(&source->base, &data_source_impl); + + source->selection = selection; + wl_array_init(&source->mime_types_atoms); + + bool ok = source_get_targets(selection, &source->base.mime_types, + &source->mime_types_atoms); + if (ok) { + wlr_seat_request_set_selection(xwm->seat, NULL, &source->base, + wl_display_next_serial(xwm->xwayland->wl_display)); + } else { + wlr_data_source_destroy(&source->base); + } + } else if (selection == &xwm->primary_selection) { + struct x11_primary_selection_source *source = calloc(1, sizeof(*source)); + if (source == NULL) { + return; + } + wlr_primary_selection_source_init(&source->base, + &primary_selection_source_impl); + + source->selection = selection; + wl_array_init(&source->mime_types_atoms); + + bool ok = source_get_targets(selection, &source->base.mime_types, + &source->mime_types_atoms); + if (ok) { + wlr_seat_set_primary_selection(xwm->seat, &source->base, + wl_display_next_serial(xwm->xwayland->wl_display)); + } else { + wlr_primary_selection_source_destroy(&source->base); + } + } else if (selection == &xwm->dnd_selection) { + // TODO + } +} + +void xwm_handle_selection_notify(struct wlr_xwm *xwm, + xcb_selection_notify_event_t *event) { + wlr_log(WLR_DEBUG, "XCB_SELECTION_NOTIFY (selection=%u, property=%u, target=%u)", + event->selection, event->property, + event->target); + + struct wlr_xwm_selection *selection = + xwm_get_selection(xwm, event->selection); + if (selection == NULL) { + return; + } + + struct wlr_xwm_selection_transfer *transfer = + xwm_selection_find_incoming_transfer_by_window(selection, event->requestor); + + if (event->property == XCB_ATOM_NONE) { + if (transfer) { + wlr_log(WLR_ERROR, "convert selection failed"); + xwm_selection_transfer_destroy(transfer); + } + } else if (event->target == xwm->atoms[TARGETS]) { + // No xwayland surface focused, deny access to clipboard + if (xwm->focus_surface == NULL) { + wlr_log(WLR_DEBUG, "denying write access to clipboard: " + "no xwayland surface focused"); + return; + } + + // This sets the Wayland clipboard (by calling wlr_seat_set_selection) + xwm_selection_get_targets(selection); + } else if (transfer) { + xwm_selection_transfer_get_data(transfer); + } +} + +int xwm_handle_xfixes_selection_notify(struct wlr_xwm *xwm, + xcb_xfixes_selection_notify_event_t *event) { + wlr_log(WLR_DEBUG, "XCB_XFIXES_SELECTION_NOTIFY (selection=%u, owner=%u)", + event->selection, event->owner); + + struct wlr_xwm_selection *selection = + xwm_get_selection(xwm, event->selection); + if (selection == NULL) { + return 0; + } + + if (event->owner == XCB_WINDOW_NONE) { + if (selection->owner != selection->window) { + // A real X client selection went away, not our proxy selection + if (selection == &xwm->clipboard_selection) { + wlr_seat_request_set_selection(xwm->seat, NULL, NULL, + wl_display_next_serial(xwm->xwayland->wl_display)); + } else if (selection == &xwm->primary_selection) { + wlr_seat_request_set_primary_selection(xwm->seat, NULL, NULL, + wl_display_next_serial(xwm->xwayland->wl_display)); + } else if (selection == &xwm->dnd_selection) { + // TODO: DND + } else { + wlr_log(WLR_DEBUG, "X11 selection has been cleared, but cannot " + "clear Wayland selection"); + } + } + + selection->owner = XCB_WINDOW_NONE; + return 1; + } + + if (selection->owner == selection->window && + event->owner != selection->owner) { + wlr_log(WLR_DEBUG, "proxy window lost selection ownership"); + } + + selection->owner = event->owner; + + if (selection->owner == selection->window) { + // We have to use XCB_TIME_CURRENT_TIME when we claim the selection, so + // grab the actual timestamp here so we can answer TIMESTAMP conversion + // requests correctly. + selection->timestamp = event->timestamp; + return 1; + } + + // doing this will give a selection notify where we actually handle the sync + xcb_convert_selection( + xwm->xcb_conn, + selection->window, + selection->atom, + xwm->atoms[TARGETS], + xwm->atoms[WL_SELECTION], + event->timestamp + ); + xwm_schedule_flush(xwm); + + return 1; +} diff --git a/3rdparty/wlroots/xwayland/selection/outgoing.c b/3rdparty/wlroots/xwayland/selection/outgoing.c new file mode 100644 index 0000000000..a58c92e3e9 --- /dev/null +++ b/3rdparty/wlroots/xwayland/selection/outgoing.c @@ -0,0 +1,483 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "xwayland/selection.h" +#include "xwayland/xwm.h" + +static void xwm_selection_send_notify(struct wlr_xwm *xwm, + xcb_selection_request_event_t *req, bool success) { + xcb_selection_notify_event_t selection_notify = { + .response_type = XCB_SELECTION_NOTIFY, + .sequence = 0, + .time = req->time, + .requestor = req->requestor, + .selection = req->selection, + .target = req->target, + .property = success ? req->property : XCB_ATOM_NONE, + }; + + wlr_log(WLR_DEBUG, "SendEvent destination=%" PRIu32 " SelectionNotify(31) time=%" PRIu32 + " requestor=%" PRIu32 " selection=%" PRIu32 " target=%" PRIu32 " property=%" PRIu32, + req->requestor, req->time, req->requestor, req->selection, req->target, + selection_notify.property); + xwm_send_event_with_size(xwm->xcb_conn, + 0, // propagate + req->requestor, + XCB_EVENT_MASK_NO_EVENT, + &selection_notify, + sizeof(selection_notify)); + xwm_schedule_flush(xwm); +} + +static int xwm_selection_flush_source_data( + struct wlr_xwm_selection_transfer *transfer) { + xcb_change_property(transfer->selection->xwm->xcb_conn, + XCB_PROP_MODE_REPLACE, + transfer->request.requestor, + transfer->request.property, + transfer->request.target, + 8, // format + transfer->source_data.size, + transfer->source_data.data); + xwm_schedule_flush(transfer->selection->xwm); + transfer->property_set = true; + size_t length = transfer->source_data.size; + transfer->source_data.size = 0; + return length; +} + +static void xwm_selection_transfer_start_outgoing( + struct wlr_xwm_selection_transfer *transfer); + +void xwm_selection_transfer_destroy_outgoing( + struct wlr_xwm_selection_transfer *transfer) { + wl_list_remove(&transfer->link); + wlr_log(WLR_DEBUG, "Destroying transfer %p", transfer); + + xwm_selection_transfer_remove_event_source(transfer); + xwm_selection_transfer_close_wl_client_fd(transfer); + wl_array_release(&transfer->source_data); + free(transfer); +} + +static int xwm_data_source_read(int fd, uint32_t mask, void *data) { + struct wlr_xwm_selection_transfer *transfer = data; + struct wlr_xwm *xwm = transfer->selection->xwm; + + void *p; + size_t current = transfer->source_data.size; + if (transfer->source_data.size < INCR_CHUNK_SIZE) { + p = wl_array_add(&transfer->source_data, INCR_CHUNK_SIZE); + if (p == NULL) { + wlr_log(WLR_ERROR, "Could not allocate selection source_data"); + goto error_out; + } + } else { + p = (char *)transfer->source_data.data + transfer->source_data.size; + } + + size_t available = transfer->source_data.alloc - current; + ssize_t len = read(fd, p, available); + if (len == -1) { + wlr_log_errno(WLR_ERROR, "read error from data source"); + goto error_out; + } + + wlr_log(WLR_DEBUG, "read %zd bytes (available %zu, mask 0x%x)", len, + available, mask); + + transfer->source_data.size = current + len; + if (transfer->source_data.size >= INCR_CHUNK_SIZE) { + if (!transfer->incr) { + wlr_log(WLR_DEBUG, "got %zu bytes, starting incr", + transfer->source_data.size); + + size_t incr_chunk_size = INCR_CHUNK_SIZE; + xcb_change_property(xwm->xcb_conn, + XCB_PROP_MODE_REPLACE, + transfer->request.requestor, + transfer->request.property, + xwm->atoms[INCR], + 32, /* format */ + 1, &incr_chunk_size); + transfer->incr = true; + transfer->property_set = true; + transfer->flush_property_on_delete = true; + xwm_selection_transfer_remove_event_source(transfer); + xwm_selection_send_notify(xwm, &transfer->request, true); + } else if (transfer->property_set) { + wlr_log(WLR_DEBUG, "got %zu bytes, waiting for property delete", + transfer->source_data.size); + + transfer->flush_property_on_delete = true; + xwm_selection_transfer_remove_event_source(transfer); + } else { + wlr_log(WLR_DEBUG, "got %zu bytes, property deleted, setting new " + "property", transfer->source_data.size); + xwm_selection_flush_source_data(transfer); + } + } else if (len == 0 && !transfer->incr) { + wlr_log(WLR_DEBUG, "non-incr transfer complete"); + xwm_selection_flush_source_data(transfer); + xwm_selection_send_notify(xwm, &transfer->request, true); + xwm_selection_transfer_destroy_outgoing(transfer); + } else if (len == 0 && transfer->incr) { + wlr_log(WLR_DEBUG, "incr transfer complete"); + + transfer->flush_property_on_delete = true; + if (transfer->property_set) { + wlr_log(WLR_DEBUG, "got %zu bytes, waiting for property delete", + transfer->source_data.size); + } else { + wlr_log(WLR_DEBUG, "got %zu bytes, property deleted, setting new " + "property", transfer->source_data.size); + xwm_selection_flush_source_data(transfer); + } + xwm_selection_transfer_remove_event_source(transfer); + xwm_selection_transfer_close_wl_client_fd(transfer); + } else { + wlr_log(WLR_DEBUG, "nothing happened, buffered the bytes"); + } + + return 1; + +error_out: + xwm_selection_send_notify(xwm, &transfer->request, false); + xwm_selection_transfer_destroy_outgoing(transfer); + return 0; +} + +void xwm_send_incr_chunk(struct wlr_xwm_selection_transfer *transfer) { + wlr_log(WLR_DEBUG, "property deleted"); + + transfer->property_set = false; + if (transfer->flush_property_on_delete) { + wlr_log(WLR_DEBUG, "setting new property, %zu bytes", + transfer->source_data.size); + transfer->flush_property_on_delete = false; + int length = xwm_selection_flush_source_data(transfer); + + if (transfer->wl_client_fd >= 0) { + xwm_selection_transfer_start_outgoing(transfer); + } else if (length > 0) { + /* Transfer is all done, but queue a flush for + * the delete of the last chunk so we can set + * the 0 sized property to signal the end of + * the transfer. */ + transfer->flush_property_on_delete = true; + wl_array_release(&transfer->source_data); + wl_array_init(&transfer->source_data); + } else { + xwm_selection_transfer_destroy_outgoing(transfer); + } + } +} + +static void xwm_selection_source_send(struct wlr_xwm_selection *selection, + const char *mime_type, int32_t fd) { + if (selection == &selection->xwm->clipboard_selection) { + struct wlr_data_source *source = + selection->xwm->seat->selection_source; + if (source != NULL) { + wlr_data_source_send(source, mime_type, fd); + return; + } + } else if (selection == &selection->xwm->primary_selection) { + struct wlr_primary_selection_source *source = + selection->xwm->seat->primary_selection_source; + if (source != NULL) { + wlr_primary_selection_source_send(source, mime_type, fd); + return; + } + } else if (selection == &selection->xwm->dnd_selection) { + struct wlr_data_source *source = + selection->xwm->seat->drag_source; + if (source != NULL) { + wlr_data_source_send(source, mime_type, fd); + return; + } + } + + wlr_log(WLR_DEBUG, "not sending selection: no selection source available"); +} + +static void xwm_selection_transfer_start_outgoing( + struct wlr_xwm_selection_transfer *transfer) { + struct wlr_xwm *xwm = transfer->selection->xwm; + struct wl_event_loop *loop = + wl_display_get_event_loop(xwm->xwayland->wl_display); + wlr_log(WLR_DEBUG, "Starting transfer %p", transfer); + transfer->event_source = wl_event_loop_add_fd(loop, transfer->wl_client_fd, + WL_EVENT_READABLE, xwm_data_source_read, transfer); +} + +static struct wl_array *xwm_selection_source_get_mime_types( + struct wlr_xwm_selection *selection) { + if (selection == &selection->xwm->clipboard_selection) { + struct wlr_data_source *source = + selection->xwm->seat->selection_source; + if (source != NULL) { + return &source->mime_types; + } + } else if (selection == &selection->xwm->primary_selection) { + struct wlr_primary_selection_source *source = + selection->xwm->seat->primary_selection_source; + if (source != NULL) { + return &source->mime_types; + } + } else if (selection == &selection->xwm->dnd_selection) { + struct wlr_data_source *source = + selection->xwm->seat->drag_source; + if (source != NULL) { + return &source->mime_types; + } + } + return NULL; +} + +/** + * Read the Wayland selection and send it to an Xwayland client. + */ +static bool xwm_selection_send_data(struct wlr_xwm_selection *selection, + xcb_selection_request_event_t *req, const char *mime_type) { + // Check MIME type + struct wl_array *mime_types = + xwm_selection_source_get_mime_types(selection); + if (mime_types == NULL) { + wlr_log(WLR_ERROR, "not sending selection: no MIME type list available"); + return false; + } + + bool found = false; + char **mime_type_ptr; + wl_array_for_each(mime_type_ptr, mime_types) { + char *t = *mime_type_ptr; + if (strcmp(t, mime_type) == 0) { + found = true; + break; + } + } + if (!found) { + wlr_log(WLR_ERROR, "not sending selection: " + "requested an unsupported MIME type %s", mime_type); + return false; + } + + struct wlr_xwm_selection_transfer *transfer = calloc(1, sizeof(*transfer)); + if (transfer == NULL) { + wlr_log(WLR_ERROR, "Allocation failed"); + return false; + } + + xwm_selection_transfer_init(transfer, selection); + transfer->request = *req; + wl_array_init(&transfer->source_data); + + int p[2]; + if (pipe(p) == -1) { + wlr_log_errno(WLR_ERROR, "pipe() failed"); + wl_array_release(&transfer->source_data); + free(transfer); + return false; + } + + fcntl(p[0], F_SETFD, FD_CLOEXEC); + fcntl(p[0], F_SETFL, O_NONBLOCK); + fcntl(p[1], F_SETFD, FD_CLOEXEC); + fcntl(p[1], F_SETFL, O_NONBLOCK); + + transfer->wl_client_fd = p[0]; + + wlr_log(WLR_DEBUG, "Sending Wayland selection %u to Xwayland window with " + "MIME type %s, target %u, transfer %p", req->target, mime_type, + req->target, transfer); + xwm_selection_source_send(selection, mime_type, p[1]); + + // It seems that if we ever try to reply to a selection request after + // another has been sent by the same requestor, the requestor never reads + // from it. It appears to only ever read from the latest, so purge stale + // transfers to prevent clipboard hangs. + struct wlr_xwm_selection_transfer *outgoing, *tmp; + wl_list_for_each_safe(outgoing, tmp, &selection->outgoing, link) { + if (transfer->request.requestor == outgoing->request.requestor) { + wlr_log(WLR_DEBUG, "Destroying stale transfer %p", outgoing); + xwm_selection_send_notify(selection->xwm, &outgoing->request, false); + xwm_selection_transfer_destroy_outgoing(outgoing); + } else { + wlr_log(WLR_DEBUG, "Transfer %p still running", outgoing); + } + } + + wl_list_insert(&selection->outgoing, &transfer->link); + + xwm_selection_transfer_start_outgoing(transfer); + + return true; +} + +static void xwm_selection_send_targets(struct wlr_xwm_selection *selection, + xcb_selection_request_event_t *req) { + struct wlr_xwm *xwm = selection->xwm; + + struct wl_array *mime_types = + xwm_selection_source_get_mime_types(selection); + if (mime_types == NULL) { + wlr_log(WLR_ERROR, "not sending selection targets: " + "no selection source available"); + xwm_selection_send_notify(selection->xwm, req, false); + return; + } + + size_t n = 2 + mime_types->size / sizeof(char *); + xcb_atom_t *targets = malloc(n * sizeof(targets[0])); + if (targets == NULL) { + wlr_log(WLR_ERROR, "Allocation failure"); + return; + } + targets[0] = xwm->atoms[TIMESTAMP]; + targets[1] = xwm->atoms[TARGETS]; + + size_t i = 0; + char **mime_type_ptr; + wl_array_for_each(mime_type_ptr, mime_types) { + char *mime_type = *mime_type_ptr; + targets[2+i] = xwm_mime_type_to_atom(xwm, mime_type); + ++i; + } + + xcb_change_property(xwm->xcb_conn, + XCB_PROP_MODE_REPLACE, + req->requestor, + req->property, + XCB_ATOM_ATOM, + 32, // format + n, targets); + + free(targets); + + xwm_selection_send_notify(selection->xwm, req, true); +} + +static void xwm_selection_send_timestamp(struct wlr_xwm_selection *selection, + xcb_selection_request_event_t *req) { + xcb_change_property(selection->xwm->xcb_conn, + XCB_PROP_MODE_REPLACE, + req->requestor, + req->property, + XCB_ATOM_INTEGER, + 32, // format + 1, &selection->timestamp); + + xwm_selection_send_notify(selection->xwm, req, true); +} + +void xwm_handle_selection_request(struct wlr_xwm *xwm, + xcb_selection_request_event_t *req) { + wlr_log(WLR_DEBUG, "XCB_SELECTION_REQUEST (time=%u owner=%u, requestor=%u " + "selection=%u, target=%u, property=%u)", + req->time, req->owner, req->requestor, req->selection, req->target, + req->property); + + if (req->selection == xwm->atoms[CLIPBOARD_MANAGER]) { + // The wlroots clipboard should already have grabbed the first target, + // so just send selection notify now. This isn't synchronized with the + // clipboard finishing getting the data, so there's a race here. + xwm_selection_send_notify(xwm, req, true); + return; + } + + struct wlr_xwm_selection *selection = + xwm_get_selection(xwm, req->selection); + if (selection == NULL) { + wlr_log(WLR_DEBUG, "received selection request for unknown selection"); + goto fail_notify_requestor; + } + + if (req->requestor == selection->window) { + wlr_log(WLR_ERROR, "selection request should have been caught before"); + goto fail_notify_requestor; + } + + if (selection->window != req->owner) { + if (req->time != XCB_CURRENT_TIME && req->time < selection->timestamp) { + wlr_log(WLR_DEBUG, "ignored old request from timestamp %d; expected > %d", + req->time, selection->timestamp); + goto fail_notify_requestor; + } + + wlr_log(WLR_DEBUG, "received selection request with invalid owner"); + // Don't fail (`goto fail_notify_requestor`) the selection request if we're + // no longer the selection owner. + return; + } + + bool dnd_allowed = selection == &xwm->dnd_selection + && (xwm->drag_focus != NULL || xwm->drop_focus != NULL); + + // No xwayland surface focused, deny access to clipboard + if (xwm->focus_surface == NULL && !dnd_allowed) { + if (wlr_log_get_verbosity() >= WLR_DEBUG) { + char *selection_name = xwm_get_atom_name(xwm, selection->atom); + wlr_log(WLR_DEBUG, "denying read access to selection %u (%s): " + "no xwayland surface focused", selection->atom, selection_name); + free(selection_name); + } + goto fail_notify_requestor; + } + + if (req->target == xwm->atoms[TARGETS]) { + xwm_selection_send_targets(selection, req); + } else if (req->target == xwm->atoms[TIMESTAMP]) { + xwm_selection_send_timestamp(selection, req); + } else if (req->target == xwm->atoms[DELETE]) { + xwm_selection_send_notify(selection->xwm, req, true); + } else { + // Send data + char *mime_type = xwm_mime_type_from_atom(xwm, req->target); + if (mime_type == NULL) { + wlr_log(WLR_ERROR, "ignoring selection request: unknown atom %u", + req->target); + goto fail_notify_requestor; + } + + bool send_success = xwm_selection_send_data(selection, req, mime_type); + free(mime_type); + if (!send_success) { + goto fail_notify_requestor; + } + } + + return; + +fail_notify_requestor: + // Something went wrong, and there won't be any data being sent to the + // requestor, so let them know. + xwm_selection_send_notify(xwm, req, false); +} + +void xwm_handle_selection_destroy_notify(struct wlr_xwm *xwm, + xcb_destroy_notify_event_t *event) { + struct wlr_xwm_selection *selections[] = { + &xwm->clipboard_selection, + &xwm->primary_selection, + &xwm->dnd_selection, + }; + + for (size_t i = 0; i < sizeof(selections)/sizeof(selections[0]); ++i) { + struct wlr_xwm_selection *selection = selections[i]; + + struct wlr_xwm_selection_transfer *outgoing, *tmp; + wl_list_for_each_safe(outgoing, tmp, &selection->outgoing, link) { + if (event->window == outgoing->request.requestor) { + xwm_selection_transfer_destroy_outgoing(outgoing); + } + } + } +} diff --git a/3rdparty/wlroots/xwayland/selection/selection.c b/3rdparty/wlroots/xwayland/selection/selection.c new file mode 100644 index 0000000000..deb695e24b --- /dev/null +++ b/3rdparty/wlroots/xwayland/selection/selection.c @@ -0,0 +1,345 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "xwayland/selection.h" +#include "xwayland/xwm.h" + +void xwm_selection_transfer_remove_event_source( + struct wlr_xwm_selection_transfer *transfer) { + if (transfer->event_source != NULL) { + wl_event_source_remove(transfer->event_source); + transfer->event_source = NULL; + } +} + +void xwm_selection_transfer_close_wl_client_fd( + struct wlr_xwm_selection_transfer *transfer) { + if (transfer->wl_client_fd >= 0) { + close(transfer->wl_client_fd); + transfer->wl_client_fd = -1; + } +} + +void xwm_selection_transfer_destroy_property_reply( + struct wlr_xwm_selection_transfer *transfer) { + free(transfer->property_reply); + transfer->property_reply = NULL; +} + +void xwm_selection_transfer_init(struct wlr_xwm_selection_transfer *transfer, + struct wlr_xwm_selection *selection) { + *transfer = (struct wlr_xwm_selection_transfer){ + .selection = selection, + .wl_client_fd = -1, + }; +} + +void xwm_selection_transfer_destroy( + struct wlr_xwm_selection_transfer *transfer) { + if (!transfer) { + return; + } + + xwm_selection_transfer_destroy_property_reply(transfer); + xwm_selection_transfer_remove_event_source(transfer); + xwm_selection_transfer_close_wl_client_fd(transfer); + + if (transfer->incoming_window) { + struct wlr_xwm *xwm = transfer->selection->xwm; + xcb_destroy_window(xwm->xcb_conn, transfer->incoming_window); + xwm_schedule_flush(xwm); + } + + wl_list_remove(&transfer->link); + free(transfer); +} + +xcb_atom_t xwm_mime_type_to_atom(struct wlr_xwm *xwm, char *mime_type) { + if (strcmp(mime_type, "text/plain;charset=utf-8") == 0) { + return xwm->atoms[UTF8_STRING]; + } else if (strcmp(mime_type, "text/plain") == 0) { + return xwm->atoms[TEXT]; + } + + xcb_intern_atom_cookie_t cookie = + xcb_intern_atom(xwm->xcb_conn, 0, strlen(mime_type), mime_type); + xcb_intern_atom_reply_t *reply = + xcb_intern_atom_reply(xwm->xcb_conn, cookie, NULL); + if (reply == NULL) { + return XCB_ATOM_NONE; + } + xcb_atom_t atom = reply->atom; + free(reply); + return atom; +} + +char *xwm_mime_type_from_atom(struct wlr_xwm *xwm, xcb_atom_t atom) { + if (atom == xwm->atoms[UTF8_STRING]) { + return strdup("text/plain;charset=utf-8"); + } else if (atom == xwm->atoms[TEXT]) { + return strdup("text/plain"); + } else { + return xwm_get_atom_name(xwm, atom); + } +} + +struct wlr_xwm_selection *xwm_get_selection(struct wlr_xwm *xwm, + xcb_atom_t selection_atom) { + if (selection_atom == xwm->atoms[CLIPBOARD]) { + return &xwm->clipboard_selection; + } else if (selection_atom == xwm->atoms[PRIMARY]) { + return &xwm->primary_selection; + } else if (selection_atom == xwm->atoms[DND_SELECTION]) { + return &xwm->dnd_selection; + } else { + return NULL; + } +} + +static int xwm_handle_selection_property_notify(struct wlr_xwm *xwm, + xcb_property_notify_event_t *event) { + struct wlr_xwm_selection *selections[] = { + &xwm->clipboard_selection, + &xwm->primary_selection, + &xwm->dnd_selection, + }; + + for (size_t i = 0; i < sizeof(selections)/sizeof(selections[0]); ++i) { + struct wlr_xwm_selection *selection = selections[i]; + + if (event->state == XCB_PROPERTY_NEW_VALUE && + event->atom == xwm->atoms[WL_SELECTION]) { + struct wlr_xwm_selection_transfer *transfer = + xwm_selection_find_incoming_transfer_by_window(selection, + event->window); + if (transfer) { + if (transfer->incr) { + xwm_get_incr_chunk(transfer); + } + + return 1; + } + } + + struct wlr_xwm_selection_transfer *outgoing; + wl_list_for_each(outgoing, &selection->outgoing, link) { + if (event->window == outgoing->request.requestor) { + if (event->state == XCB_PROPERTY_DELETE && + event->atom == outgoing->request.property && + outgoing->incr) { + xwm_send_incr_chunk(outgoing); + } + return 1; + } + } + } + + return 0; +} + +int xwm_handle_selection_event(struct wlr_xwm *xwm, + xcb_generic_event_t *event) { + if (xwm->seat == NULL) { + wlr_log(WLR_DEBUG, "not handling selection events: " + "no seat assigned to xwayland"); + return 0; + } + + switch (event->response_type & XCB_EVENT_RESPONSE_TYPE_MASK) { + case XCB_SELECTION_NOTIFY: + xwm_handle_selection_notify(xwm, (xcb_selection_notify_event_t *)event); + return 1; + case XCB_PROPERTY_NOTIFY: + return xwm_handle_selection_property_notify(xwm, + (xcb_property_notify_event_t *)event); + case XCB_SELECTION_REQUEST: + xwm_handle_selection_request(xwm, + (xcb_selection_request_event_t *)event); + return 1; + } + + switch (event->response_type - xwm->xfixes->first_event) { + case XCB_XFIXES_SELECTION_NOTIFY: + // an X11 window has copied something to the clipboard + return xwm_handle_xfixes_selection_notify(xwm, + (xcb_xfixes_selection_notify_event_t *)event); + } + + return 0; +} + +void xwm_selection_init(struct wlr_xwm_selection *selection, + struct wlr_xwm *xwm, xcb_atom_t atom) { + *selection = (struct wlr_xwm_selection){ + .xwm = xwm, + .atom = atom, + .window = xcb_generate_id(xwm->xcb_conn), + }; + wl_list_init(&selection->incoming); + wl_list_init(&selection->outgoing); + + if (atom == xwm->atoms[DND_SELECTION]) { + xcb_create_window( + xwm->xcb_conn, + XCB_COPY_FROM_PARENT, + selection->window, + xwm->screen->root, + 0, 0, + 8192, 8192, + 0, + XCB_WINDOW_CLASS_INPUT_ONLY, + xwm->screen->root_visual, + XCB_CW_EVENT_MASK, + (uint32_t[]){ + XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_PROPERTY_CHANGE + } + ); + + xcb_change_property( + xwm->xcb_conn, + XCB_PROP_MODE_REPLACE, + selection->window, + xwm->atoms[DND_AWARE], + XCB_ATOM_ATOM, + 32, // format + 1, + &(uint32_t){XDND_VERSION} + ); + } else { + xcb_create_window( + xwm->xcb_conn, + XCB_COPY_FROM_PARENT, + selection->window, + xwm->screen->root, + 0, 0, + 10, 10, + 0, + XCB_WINDOW_CLASS_INPUT_OUTPUT, + xwm->screen->root_visual, + XCB_CW_EVENT_MASK, + (uint32_t[]){ + XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | XCB_EVENT_MASK_PROPERTY_CHANGE + } + ); + + if (atom == xwm->atoms[CLIPBOARD]) { + xcb_set_selection_owner(xwm->xcb_conn, selection->window, + xwm->atoms[CLIPBOARD_MANAGER], XCB_TIME_CURRENT_TIME); + } else { + assert(atom == xwm->atoms[PRIMARY]); + } + } + + uint32_t mask = + XCB_XFIXES_SELECTION_EVENT_MASK_SET_SELECTION_OWNER | + XCB_XFIXES_SELECTION_EVENT_MASK_SELECTION_WINDOW_DESTROY | + XCB_XFIXES_SELECTION_EVENT_MASK_SELECTION_CLIENT_CLOSE; + xcb_xfixes_select_selection_input(xwm->xcb_conn, selection->window, + selection->atom, mask); +} + +void xwm_selection_finish(struct wlr_xwm_selection *selection) { + if (!selection) { + return; + } + + struct wlr_xwm_selection_transfer *outgoing, *tmp; + wl_list_for_each_safe(outgoing, tmp, &selection->outgoing, link) { + wlr_log(WLR_INFO, "destroyed pending transfer %p", outgoing); + xwm_selection_transfer_destroy_outgoing(outgoing); + } + + struct wlr_xwm_selection_transfer *incoming; + wl_list_for_each_safe(incoming, tmp, &selection->incoming, link) { + xwm_selection_transfer_destroy(incoming); + } + + xcb_destroy_window(selection->xwm->xcb_conn, selection->window); +} + +static void xwm_selection_set_owner(struct wlr_xwm_selection *selection, + bool set) { + if (set) { + xcb_set_selection_owner(selection->xwm->xcb_conn, + selection->window, + selection->atom, + XCB_TIME_CURRENT_TIME); + xwm_schedule_flush(selection->xwm); + } else { + if (selection->owner == selection->window) { + xcb_set_selection_owner(selection->xwm->xcb_conn, + XCB_WINDOW_NONE, + selection->atom, + selection->timestamp); + xwm_schedule_flush(selection->xwm); + } + } +} + +static void handle_seat_set_selection(struct wl_listener *listener, + void *data) { + struct wlr_seat *seat = data; + struct wlr_xwm *xwm = + wl_container_of(listener, xwm, seat_set_selection); + struct wlr_data_source *source = seat->selection_source; + + if (source != NULL && data_source_is_xwayland(source)) { + return; + } + + xwm_selection_set_owner(&xwm->clipboard_selection, source != NULL); +} + +static void handle_seat_set_primary_selection(struct wl_listener *listener, + void *data) { + struct wlr_seat *seat = data; + struct wlr_xwm *xwm = + wl_container_of(listener, xwm, seat_set_primary_selection); + struct wlr_primary_selection_source *source = + seat->primary_selection_source; + + if (source != NULL && primary_selection_source_is_xwayland(source)) { + return; + } + + xwm_selection_set_owner(&xwm->primary_selection, source != NULL); +} + +static void seat_handle_start_drag(struct wl_listener *listener, void *data) { + struct wlr_xwm *xwm = wl_container_of(listener, xwm, seat_start_drag); + struct wlr_drag *drag = data; + + xwm_selection_set_owner(&xwm->dnd_selection, drag != NULL); + xwm_seat_handle_start_drag(xwm, drag); +} + +void xwm_set_seat(struct wlr_xwm *xwm, struct wlr_seat *seat) { + if (xwm->seat != NULL) { + wl_list_remove(&xwm->seat_set_selection.link); + wl_list_remove(&xwm->seat_set_primary_selection.link); + wl_list_remove(&xwm->seat_start_drag.link); + xwm->seat = NULL; + } + + if (seat == NULL) { + return; + } + + xwm->seat = seat; + + wl_signal_add(&seat->events.set_selection, &xwm->seat_set_selection); + xwm->seat_set_selection.notify = handle_seat_set_selection; + wl_signal_add(&seat->events.set_primary_selection, + &xwm->seat_set_primary_selection); + xwm->seat_set_primary_selection.notify = handle_seat_set_primary_selection; + wl_signal_add(&seat->events.start_drag, &xwm->seat_start_drag); + xwm->seat_start_drag.notify = seat_handle_start_drag; + + handle_seat_set_selection(&xwm->seat_set_selection, seat); + handle_seat_set_primary_selection(&xwm->seat_set_primary_selection, seat); +} diff --git a/3rdparty/wlroots/xwayland/server.c b/3rdparty/wlroots/xwayland/server.c new file mode 100644 index 0000000000..8401c9e619 --- /dev/null +++ b/3rdparty/wlroots/xwayland/server.c @@ -0,0 +1,520 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "config.h" +#include "sockets.h" +#include "util/fd.h" + +static void safe_close(int fd) { + if (fd >= 0) { + close(fd); + } +} + +noreturn static void exec_xwayland(struct wlr_xwayland_server *server, + int notify_fd) { + if (!set_cloexec(server->x_fd[0], false) || + !set_cloexec(server->x_fd[1], false) || + !set_cloexec(server->wl_fd[1], false)) { + wlr_log(WLR_ERROR, "Failed to unset CLOEXEC on FD"); + _exit(EXIT_FAILURE); + } + if (server->options.enable_wm && !set_cloexec(server->wm_fd[1], false)) { + wlr_log(WLR_ERROR, "Failed to unset CLOEXEC on FD"); + _exit(EXIT_FAILURE); + } + + char *argv[64] = {0}; + size_t i = 0; + + char listenfd0[16], listenfd1[16], displayfd[16]; + snprintf(listenfd0, sizeof(listenfd0), "%d", server->x_fd[0]); + snprintf(listenfd1, sizeof(listenfd1), "%d", server->x_fd[1]); + snprintf(displayfd, sizeof(displayfd), "%d", notify_fd); + + argv[i++] = "Xwayland"; + argv[i++] = server->display_name; + argv[i++] = "-rootless"; + argv[i++] = "-core"; + + argv[i++] = "-terminate"; +#if HAVE_XWAYLAND_TERMINATE_DELAY + char terminate_delay[16]; + if (server->options.terminate_delay > 0) { + snprintf(terminate_delay, sizeof(terminate_delay), "%d", + server->options.terminate_delay); + argv[i++] = terminate_delay; + } +#endif + +#if HAVE_XWAYLAND_LISTENFD + argv[i++] = "-listenfd"; + argv[i++] = listenfd0; + argv[i++] = "-listenfd"; + argv[i++] = listenfd1; +#else + argv[i++] = "-listen"; + argv[i++] = listenfd0; + argv[i++] = "-listen"; + argv[i++] = listenfd1; +#endif + argv[i++] = "-displayfd"; + argv[i++] = displayfd; + + char wmfd[16]; + if (server->options.enable_wm) { + snprintf(wmfd, sizeof(wmfd), "%d", server->wm_fd[1]); + argv[i++] = "-wm"; + argv[i++] = wmfd; + } + +#if HAVE_XWAYLAND_NO_TOUCH_POINTER_EMULATION + if (server->options.no_touch_pointer_emulation) { + argv[i++] = "-noTouchPointerEmulation"; + } +#else + server->options.no_touch_pointer_emulation = false; +#endif + +#if HAVE_XWAYLAND_FORCE_XRANDR_EMULATION + if (server->options.force_xrandr_emulation) { + argv[i++] = "-force-xrandr-emulation"; + } +#else + server->options.force_xrandr_emulation = false; +#endif + + argv[i++] = NULL; + + assert(i <= sizeof(argv) / sizeof(argv[0])); + + char wayland_socket_str[16]; + snprintf(wayland_socket_str, sizeof(wayland_socket_str), "%d", server->wl_fd[1]); + setenv("WAYLAND_SOCKET", wayland_socket_str, true); + + wlr_log(WLR_INFO, "Starting Xwayland on :%d", server->display); + + // Closes stdout/stderr depending on log verbosity + enum wlr_log_importance verbosity = wlr_log_get_verbosity(); + int devnull = open("/dev/null", O_WRONLY | O_CREAT | O_CLOEXEC, 0666); + if (devnull < 0) { + wlr_log_errno(WLR_ERROR, "XWayland: failed to open /dev/null"); + _exit(EXIT_FAILURE); + } + if (verbosity < WLR_INFO) { + dup2(devnull, STDOUT_FILENO); + } + if (verbosity < WLR_ERROR) { + dup2(devnull, STDERR_FILENO); + } + + const char *xwayland_path = getenv("WLR_XWAYLAND"); + if (xwayland_path) { + wlr_log(WLR_INFO, "Using Xwayland binary '%s' due to WLR_XWAYLAND", + xwayland_path); + } else { + xwayland_path = XWAYLAND_PATH; + } + + // This returns if and only if the call fails + execvp(xwayland_path, argv); + + wlr_log_errno(WLR_ERROR, "failed to exec %s", xwayland_path); + close(devnull); + _exit(EXIT_FAILURE); +} + +static void server_finish_process(struct wlr_xwayland_server *server) { + if (!server || server->display == -1) { + return; + } + + if (server->x_fd_read_event[0]) { + wl_event_source_remove(server->x_fd_read_event[0]); + wl_event_source_remove(server->x_fd_read_event[1]); + + server->x_fd_read_event[0] = server->x_fd_read_event[1] = NULL; + } + + if (server->client) { + wl_list_remove(&server->client_destroy.link); + wl_client_destroy(server->client); + } + if (server->pipe_source) { + wl_event_source_remove(server->pipe_source); + } + + safe_close(server->wl_fd[0]); + safe_close(server->wl_fd[1]); + safe_close(server->wm_fd[0]); + safe_close(server->wm_fd[1]); + memset(server, 0, offsetof(struct wlr_xwayland_server, display)); + server->wl_fd[0] = server->wl_fd[1] = -1; + server->wm_fd[0] = server->wm_fd[1] = -1; + + /* We do not kill the Xwayland process, it dies to broken pipe + * after we close our side of the wm/wl fds. This is more reliable + * than trying to kill something that might no longer be Xwayland. + */ +} + +static void server_finish_display(struct wlr_xwayland_server *server) { + if (!server) { + return; + } + + wl_list_remove(&server->display_destroy.link); + wl_list_init(&server->display_destroy.link); + + if (server->display == -1) { + return; + } + + safe_close(server->x_fd[0]); + safe_close(server->x_fd[1]); + server->x_fd[0] = server->x_fd[1] = -1; + + unlink_display_sockets(server->display); + server->display = -1; + server->display_name[0] = '\0'; +} + +static bool server_start(struct wlr_xwayland_server *server); +static bool server_start_lazy(struct wlr_xwayland_server *server); + +static void handle_client_destroy(struct wl_listener *listener, void *data) { + struct wlr_xwayland_server *server = + wl_container_of(listener, server, client_destroy); + + if (server->pipe_source) { + // Xwayland failed to start, let the readiness handler deal with it + return; + } + + // Don't call client destroy: it's being destroyed already + server->client = NULL; + wl_list_remove(&server->client_destroy.link); + + server_finish_process(server); + + if (time(NULL) - server->server_start > 5) { + if (server->options.lazy) { + wlr_log(WLR_INFO, "Restarting Xwayland (lazy)"); + server_start_lazy(server); + } else { + wlr_log(WLR_INFO, "Restarting Xwayland"); + server_start(server); + } + } +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_xwayland_server *server = + wl_container_of(listener, server, display_destroy); + + // Don't call client destroy: the display is being destroyed, it's too late + if (server->client) { + server->client = NULL; + wl_list_remove(&server->client_destroy.link); + } + + wlr_xwayland_server_destroy(server); +} + +static int xserver_handle_ready(int fd, uint32_t mask, void *data) { + struct wlr_xwayland_server *server = data; + + if (mask & WL_EVENT_READABLE) { + /* Xwayland writes to the pipe twice, so if we close it too early + * it's possible the second write will fail and Xwayland shuts down. + * Make sure we read until end of line marker to avoid this. + */ + char buf[64]; + ssize_t n = read(fd, buf, sizeof(buf)); + if (n < 0 && errno != EINTR) { + /* Clear mask to signal start failure after reaping child */ + wlr_log_errno(WLR_ERROR, "read from Xwayland display_fd failed"); + mask = 0; + } else if (n <= 0 || buf[n-1] != '\n') { + /* Returning 1 here means recheck and call us again if required. */ + return 1; + } + } + + while (waitpid(server->pid, NULL, 0) < 0) { + if (errno == EINTR) { + continue; + } + + /* If some application has installed a SIGCHLD handler, they + * may race and waitpid() on our child, which will cause this + * waitpid() to fail. We have a signal from the + * notify pipe that things are ready, so this waitpid() is only + * to prevent zombies, which will have already been reaped by + * the application's SIGCHLD handler. + */ + if (errno == ECHILD) { + break; + } + wlr_log_errno(WLR_ERROR, "waitpid for Xwayland fork failed"); + goto error; + } + /* Xwayland will only write on the fd once it has finished its + * initial setup. Getting an event here without READABLE means + * the server end failed. + */ + if (!(mask & WL_EVENT_READABLE)) { + assert(mask & WL_EVENT_HANGUP); + wlr_log(WLR_ERROR, "Xwayland startup failed, not setting up xwm"); + goto error; + } + wlr_log(WLR_DEBUG, "Xserver is ready"); + + close(fd); + wl_event_source_remove(server->pipe_source); + server->pipe_source = NULL; + server->ready = true; + + struct wlr_xwayland_server_ready_event event = { + .server = server, + .wm_fd = server->wm_fd[0], + }; + wl_signal_emit_mutable(&server->events.ready, &event); + + /* We removed the source, so don't need recheck */ + return 0; + +error: + /* clean up */ + close(fd); + server_finish_process(server); + server_finish_display(server); + return 0; +} + +static bool server_start_display(struct wlr_xwayland_server *server, + struct wl_display *wl_display) { + server->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(wl_display, &server->display_destroy); + + server->display = open_display_sockets(server->x_fd); + if (server->display < 0) { + server_finish_display(server); + return false; + } + + snprintf(server->display_name, sizeof(server->display_name), + ":%d", server->display); + return true; +} + +static bool server_start(struct wlr_xwayland_server *server) { + if (socketpair(AF_UNIX, SOCK_STREAM, 0, server->wl_fd) != 0) { + wlr_log_errno(WLR_ERROR, "socketpair failed"); + server_finish_process(server); + return false; + } + if (!set_cloexec(server->wl_fd[0], true) || + !set_cloexec(server->wl_fd[1], true)) { + wlr_log(WLR_ERROR, "Failed to set O_CLOEXEC on socket"); + server_finish_process(server); + return false; + } + if (server->options.enable_wm) { + if (socketpair(AF_UNIX, SOCK_STREAM, 0, server->wm_fd) != 0) { + wlr_log_errno(WLR_ERROR, "socketpair failed"); + server_finish_process(server); + return false; + } + if (!set_cloexec(server->wm_fd[0], true) || + !set_cloexec(server->wm_fd[1], true)) { + wlr_log(WLR_ERROR, "Failed to set O_CLOEXEC on socket"); + server_finish_process(server); + return false; + } + } + + server->server_start = time(NULL); + + server->client = wl_client_create(server->wl_display, server->wl_fd[0]); + if (!server->client) { + wlr_log_errno(WLR_ERROR, "wl_client_create failed"); + server_finish_process(server); + return false; + } + + server->wl_fd[0] = -1; /* not ours anymore */ + + server->client_destroy.notify = handle_client_destroy; + wl_client_add_destroy_listener(server->client, &server->client_destroy); + + int notify_fd[2]; + if (pipe(notify_fd) == -1) { + wlr_log_errno(WLR_ERROR, "pipe failed"); + server_finish_process(server); + return false; + } + if (!set_cloexec(notify_fd[0], true)) { + wlr_log(WLR_ERROR, "Failed to set CLOEXEC on FD"); + close(notify_fd[0]); + close(notify_fd[1]); + server_finish_process(server); + return false; + } + + struct wl_event_loop *loop = wl_display_get_event_loop(server->wl_display); + server->pipe_source = wl_event_loop_add_fd(loop, notify_fd[0], + WL_EVENT_READABLE, xserver_handle_ready, server); + + wl_signal_emit_mutable(&server->events.start, NULL); + + server->pid = fork(); + if (server->pid < 0) { + wlr_log_errno(WLR_ERROR, "fork failed"); + close(notify_fd[0]); + close(notify_fd[1]); + server_finish_process(server); + return false; + } else if (server->pid == 0) { + pid_t pid = fork(); + if (pid < 0) { + wlr_log_errno(WLR_ERROR, "second fork failed"); + _exit(EXIT_FAILURE); + } else if (pid == 0) { + exec_xwayland(server, notify_fd[1]); + } + + _exit(EXIT_SUCCESS); + } + + /* close child fds */ + /* remain managing x sockets for lazy start */ + close(notify_fd[1]); + close(server->wl_fd[1]); + safe_close(server->wm_fd[1]); + server->wl_fd[1] = server->wm_fd[1] = -1; + + return true; +} + +static int xwayland_socket_connected(int fd, uint32_t mask, void *data) { + struct wlr_xwayland_server *server = data; + + wl_event_source_remove(server->x_fd_read_event[0]); + wl_event_source_remove(server->x_fd_read_event[1]); + server->x_fd_read_event[0] = server->x_fd_read_event[1] = NULL; + + server_start(server); + + return 0; +} + +static bool server_start_lazy(struct wlr_xwayland_server *server) { + struct wl_event_loop *loop = wl_display_get_event_loop(server->wl_display); + + if (!(server->x_fd_read_event[0] = wl_event_loop_add_fd(loop, server->x_fd[0], + WL_EVENT_READABLE, xwayland_socket_connected, server))) { + return false; + } + + if (!(server->x_fd_read_event[1] = wl_event_loop_add_fd(loop, server->x_fd[1], + WL_EVENT_READABLE, xwayland_socket_connected, server))) { + wl_event_source_remove(server->x_fd_read_event[0]); + server->x_fd_read_event[0] = NULL; + return false; + } + + return true; +} + +static void handle_idle(void *data) { + struct wlr_xwayland_server *server = data; + server->idle_source = NULL; + server_start(server); +} + +void wlr_xwayland_server_destroy(struct wlr_xwayland_server *server) { + if (!server) { + return; + } + + if (server->idle_source != NULL) { + wl_event_source_remove(server->idle_source); + } + server_finish_process(server); + server_finish_display(server); + + wl_signal_emit_mutable(&server->events.destroy, NULL); + + assert(wl_list_empty(&server->events.start.listener_list)); + assert(wl_list_empty(&server->events.ready.listener_list)); + assert(wl_list_empty(&server->events.destroy.listener_list)); + + free(server); +} + +struct wlr_xwayland_server *wlr_xwayland_server_create( + struct wl_display *wl_display, + struct wlr_xwayland_server_options *options) { + if (!getenv("WLR_XWAYLAND") && access(XWAYLAND_PATH, X_OK) != 0) { + wlr_log(WLR_ERROR, "Cannot find Xwayland binary \"%s\"", XWAYLAND_PATH); + return NULL; + } + + struct wlr_xwayland_server *server = calloc(1, sizeof(*server)); + if (!server) { + return NULL; + } + + server->wl_display = wl_display; + server->options = *options; + +#if !HAVE_XWAYLAND_TERMINATE_DELAY + server->options.terminate_delay = 0; +#endif + + server->x_fd[0] = server->x_fd[1] = -1; + server->wl_fd[0] = server->wl_fd[1] = -1; + server->wm_fd[0] = server->wm_fd[1] = -1; + + wl_signal_init(&server->events.start); + wl_signal_init(&server->events.ready); + wl_signal_init(&server->events.destroy); + + if (!server_start_display(server, wl_display)) { + goto error_alloc; + } + + if (server->options.lazy) { + if (!server_start_lazy(server)) { + goto error_display; + } + } else { + struct wl_event_loop *loop = wl_display_get_event_loop(wl_display); + server->idle_source = wl_event_loop_add_idle(loop, handle_idle, server); + if (server->idle_source == NULL) { + goto error_display; + } + } + + return server; + +error_display: + server_finish_display(server); +error_alloc: + free(server); + return NULL; +} diff --git a/3rdparty/wlroots/xwayland/shell.c b/3rdparty/wlroots/xwayland/shell.c new file mode 100644 index 0000000000..f048eb6279 --- /dev/null +++ b/3rdparty/wlroots/xwayland/shell.c @@ -0,0 +1,241 @@ +#include +#include +#include +#include + +#include "xwayland-shell-v1-protocol.h" + +#define SHELL_VERSION 1 + +static void destroy_resource(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static const struct xwayland_shell_v1_interface shell_impl; +static const struct xwayland_surface_v1_interface xwl_surface_impl; + +static void xwl_surface_destroy(struct wlr_xwayland_surface_v1 *xwl_surface) { + wl_list_remove(&xwl_surface->link); + wl_resource_set_user_data(xwl_surface->resource, NULL); // make inert + free(xwl_surface); +} + +/** + * Get a struct wlr_xwayland_shell_v1 from a resource. + */ +static struct wlr_xwayland_shell_v1 *shell_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &xwayland_shell_v1_interface, &shell_impl)); + return wl_resource_get_user_data(resource); +} + +/** + * Get a struct wlr_xwayland_surface_v1 from a resource. + * + * Returns NULL if the Xwayland surface is inert. + */ +static struct wlr_xwayland_surface_v1 *xwl_surface_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &xwayland_surface_v1_interface, &xwl_surface_impl)); + return wl_resource_get_user_data(resource); +} + +static void xwl_surface_role_commit(struct wlr_surface *surface) { + struct wlr_xwayland_surface_v1 *xwl_surface = xwl_surface_from_resource(surface->role_resource); + if (xwl_surface == NULL) { + return; + } + + if (xwl_surface->serial != 0 && !xwl_surface->added) { + xwl_surface->added = true; + wl_signal_emit_mutable(&xwl_surface->shell->events.new_surface, + xwl_surface); + } +} + +static void xwl_surface_role_destroy(struct wlr_surface *surface) { + struct wlr_xwayland_surface_v1 *xwl_surface = xwl_surface_from_resource(surface->role_resource); + if (xwl_surface == NULL) { + return; + } + + xwl_surface_destroy(xwl_surface); +} + +static const struct wlr_surface_role xwl_surface_role = { + .name = "xwayland_surface_v1", + .commit = xwl_surface_role_commit, + .destroy = xwl_surface_role_destroy, +}; + +static void xwl_surface_handle_set_serial(struct wl_client *client, + struct wl_resource *resource, uint32_t serial_lo, uint32_t serial_hi) { + struct wlr_xwayland_surface_v1 *xwl_surface = + xwl_surface_from_resource(resource); + if (xwl_surface == NULL) { + return; + } + + if (xwl_surface->serial != 0) { + wl_resource_post_error(resource, + XWAYLAND_SURFACE_V1_ERROR_ALREADY_ASSOCIATED, + "xwayland_surface_v1 is already associated with another X11 serial"); + return; + } + + xwl_surface->serial = ((uint64_t)serial_hi << 32) | serial_lo; +} + +static const struct xwayland_surface_v1_interface xwl_surface_impl = { + .destroy = destroy_resource, + .set_serial = xwl_surface_handle_set_serial, +}; + +static void shell_handle_get_xwayland_surface(struct wl_client *client, + struct wl_resource *shell_resource, uint32_t id, + struct wl_resource *surface_resource) { + struct wlr_xwayland_shell_v1 *shell = shell_from_resource(shell_resource); + struct wlr_surface *surface = wlr_surface_from_resource(surface_resource); + + struct wlr_xwayland_surface_v1 *xwl_surface = calloc(1, sizeof(*xwl_surface)); + if (xwl_surface == NULL) { + wl_client_post_no_memory(client); + return; + } + + if (!wlr_surface_set_role(surface, &xwl_surface_role, + shell_resource, XWAYLAND_SHELL_V1_ERROR_ROLE)) { + free(xwl_surface); + return; + } + + xwl_surface->surface = surface; + xwl_surface->shell = shell; + + uint32_t version = wl_resource_get_version(shell_resource); + xwl_surface->resource = wl_resource_create(client, + &xwayland_surface_v1_interface, version, id); + if (xwl_surface->resource == NULL) { + free(xwl_surface); + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(xwl_surface->resource, &xwl_surface_impl, + xwl_surface, NULL); + + wl_list_insert(&shell->surfaces, &xwl_surface->link); + + wlr_surface_set_role_object(surface, xwl_surface->resource); +} + +static const struct xwayland_shell_v1_interface shell_impl = { + .destroy = destroy_resource, + .get_xwayland_surface = shell_handle_get_xwayland_surface, +}; + +static void shell_bind(struct wl_client *client, void *data, uint32_t version, + uint32_t id) { + struct wlr_xwayland_shell_v1 *shell = data; + + if (client != shell->client) { + wl_client_post_implementation_error(client, + "Permission denied to bind to %s", xwayland_shell_v1_interface.name); + return; + } + + struct wl_resource *resource = wl_resource_create(client, + &xwayland_shell_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &shell_impl, shell, NULL); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_xwayland_shell_v1 *shell = + wl_container_of(listener, shell, display_destroy); + wlr_xwayland_shell_v1_destroy(shell); +} + +struct wlr_xwayland_shell_v1 *wlr_xwayland_shell_v1_create( + struct wl_display *display, uint32_t version) { + assert(version <= SHELL_VERSION); + + struct wlr_xwayland_shell_v1 *shell = calloc(1, sizeof(*shell)); + if (shell == NULL) { + return NULL; + } + + shell->global = wl_global_create(display, &xwayland_shell_v1_interface, + version, shell, shell_bind); + if (shell->global == NULL) { + free(shell); + return NULL; + } + + wl_list_init(&shell->surfaces); + + wl_signal_init(&shell->events.new_surface); + wl_signal_init(&shell->events.destroy); + + shell->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &shell->display_destroy); + + wl_list_init(&shell->client_destroy.link); + + return shell; +} + +void wlr_xwayland_shell_v1_destroy(struct wlr_xwayland_shell_v1 *shell) { + if (shell == NULL) { + return; + } + + wl_signal_emit_mutable(&shell->events.destroy, NULL); + + assert(wl_list_empty(&shell->events.new_surface.listener_list)); + assert(wl_list_empty(&shell->events.destroy.listener_list)); + + struct wlr_xwayland_surface_v1 *xwl_surface, *tmp; + wl_list_for_each_safe(xwl_surface, tmp, &shell->surfaces, link) { + xwl_surface_destroy(xwl_surface); + } + + wl_list_remove(&shell->display_destroy.link); + wl_list_remove(&shell->client_destroy.link); + wl_global_destroy(shell->global); + free(shell); +} + +static void shell_handle_client_destroy(struct wl_listener *listener, void *data) { + struct wlr_xwayland_shell_v1 *shell = + wl_container_of(listener, shell, client_destroy); + wlr_xwayland_shell_v1_set_client(shell, NULL); +} + +void wlr_xwayland_shell_v1_set_client(struct wlr_xwayland_shell_v1 *shell, + struct wl_client *client) { + wl_list_remove(&shell->client_destroy.link); + shell->client = client; + if (client != NULL) { + shell->client_destroy.notify = shell_handle_client_destroy; + wl_client_add_destroy_listener(client, &shell->client_destroy); + } else { + wl_list_init(&shell->client_destroy.link); + } +} + +struct wlr_surface *wlr_xwayland_shell_v1_surface_from_serial( + struct wlr_xwayland_shell_v1 *shell, uint64_t serial) { + struct wlr_xwayland_surface_v1 *xwl_surface; + wl_list_for_each(xwl_surface, &shell->surfaces, link) { + if (xwl_surface->serial == serial) { + return xwl_surface->surface; + } + } + return NULL; +} diff --git a/3rdparty/wlroots/xwayland/sockets.c b/3rdparty/wlroots/xwayland/sockets.c new file mode 100644 index 0000000000..364fbc4773 --- /dev/null +++ b/3rdparty/wlroots/xwayland/sockets.c @@ -0,0 +1,205 @@ +#undef _POSIX_C_SOURCE +#define _XOPEN_SOURCE 700 // for S_ISVTX +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "sockets.h" +#include "util/fd.h" + +static const char lock_fmt[] = "/tmp/.X%d-lock"; +static const char socket_dir[] = "/tmp/.X11-unix"; +static const char socket_fmt[] = "/tmp/.X11-unix/X%d"; +#ifndef __linux__ +static const char socket_fmt2[] = "/tmp/.X11-unix/X%d_"; +#endif + +static int open_socket(struct sockaddr_un *addr, size_t path_size) { + int fd, rc; + socklen_t size = offsetof(struct sockaddr_un, sun_path) + path_size + 1; + + fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (fd < 0) { + wlr_log_errno(WLR_ERROR, "Failed to create socket %c%s", + addr->sun_path[0] ? addr->sun_path[0] : '@', + addr->sun_path + 1); + return -1; + } + if (!set_cloexec(fd, true)) { + close(fd); + return -1; + } + + if (addr->sun_path[0]) { + unlink(addr->sun_path); + } + if (bind(fd, (struct sockaddr*)addr, size) < 0) { + rc = errno; + wlr_log_errno(WLR_ERROR, "Failed to bind socket %c%s", + addr->sun_path[0] ? addr->sun_path[0] : '@', + addr->sun_path + 1); + goto cleanup; + } + if (listen(fd, 1) < 0) { + rc = errno; + wlr_log_errno(WLR_ERROR, "Failed to listen to socket %c%s", + addr->sun_path[0] ? addr->sun_path[0] : '@', + addr->sun_path + 1); + goto cleanup; + } + + return fd; + +cleanup: + close(fd); + if (addr->sun_path[0]) { + unlink(addr->sun_path); + } + errno = rc; + return -1; +} + +static bool check_socket_dir(void) { + struct stat buf; + + if (lstat(socket_dir, &buf)) { + wlr_log_errno(WLR_ERROR, "Failed to stat %s", socket_dir); + return false; + } + if (!(buf.st_mode & S_IFDIR)) { + wlr_log(WLR_ERROR, "%s is not a directory", socket_dir); + return false; + } + if (!((buf.st_uid == 0) || (buf.st_uid == getuid()))) { + wlr_log(WLR_ERROR, "%s not owned by root or us", socket_dir); + return false; + } + if (!(buf.st_mode & S_ISVTX)) { + /* we can deal with no sticky bit... */ + if ((buf.st_mode & (S_IWGRP | S_IWOTH))) { + /* but not if other users can mess with our sockets */ + wlr_log(WLR_ERROR, "sticky bit not set on %s", socket_dir); + return false; + } + } + return true; +} + +static bool open_sockets(int socks[2], int display) { + struct sockaddr_un addr = { .sun_family = AF_UNIX }; + size_t path_size; + + if (mkdir(socket_dir, 0755) == 0) { + wlr_log(WLR_INFO, "Created %s ourselves -- other users will " + "be unable to create X11 UNIX sockets of their own", + socket_dir); + } else if (errno != EEXIST) { + wlr_log_errno(WLR_ERROR, "Unable to mkdir %s", socket_dir); + return false; + } else if (!check_socket_dir()) { + return false; + } + +#ifdef __linux__ + addr.sun_path[0] = 0; + path_size = snprintf(addr.sun_path + 1, sizeof(addr.sun_path) - 1, socket_fmt, display); +#else + path_size = snprintf(addr.sun_path, sizeof(addr.sun_path), socket_fmt2, display); +#endif + socks[0] = open_socket(&addr, path_size); + if (socks[0] < 0) { + return false; + } + + path_size = snprintf(addr.sun_path, sizeof(addr.sun_path), socket_fmt, display); + socks[1] = open_socket(&addr, path_size); + if (socks[1] < 0) { + close(socks[0]); + socks[0] = -1; + return false; + } + + return true; +} + +void unlink_display_sockets(int display) { + char sun_path[64]; + + snprintf(sun_path, sizeof(sun_path), socket_fmt, display); + unlink(sun_path); + +#ifndef __linux__ + snprintf(sun_path, sizeof(sun_path), socket_fmt2, display); + unlink(sun_path); +#endif + + snprintf(sun_path, sizeof(sun_path), lock_fmt, display); + unlink(sun_path); +} + +int open_display_sockets(int socks[2]) { + int lock_fd, display; + char lock_name[64]; + + for (display = 0; display <= 32; display++) { + snprintf(lock_name, sizeof(lock_name), lock_fmt, display); + if ((lock_fd = open(lock_name, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0444)) >= 0) { + if (!open_sockets(socks, display)) { + unlink(lock_name); + close(lock_fd); + continue; + } + char pid[12]; + snprintf(pid, sizeof(pid), "%10d", getpid()); + if (write(lock_fd, pid, sizeof(pid) - 1) != sizeof(pid) - 1) { + unlink(lock_name); + close(lock_fd); + continue; + } + close(lock_fd); + break; + } + + if ((lock_fd = open(lock_name, O_RDONLY | O_CLOEXEC)) < 0) { + continue; + } + + char pid[12] = { 0 }, *end_pid; + ssize_t bytes = read(lock_fd, pid, sizeof(pid) - 1); + close(lock_fd); + + if (bytes != sizeof(pid) - 1) { + continue; + } + long int read_pid; + read_pid = strtol(pid, &end_pid, 10); + if (read_pid < 0 || read_pid > INT32_MAX || end_pid != pid + sizeof(pid) - 2) { + continue; + } + errno = 0; + if (kill((pid_t)read_pid, 0) != 0 && errno == ESRCH) { + if (unlink(lock_name) != 0) { + continue; + } + // retry + display--; + continue; + } + } + + if (display > 32) { + wlr_log(WLR_ERROR, "No display available in the first 33"); + return -1; + } + + return display; +} diff --git a/3rdparty/wlroots/xwayland/sockets.h b/3rdparty/wlroots/xwayland/sockets.h new file mode 100644 index 0000000000..b068dff2e1 --- /dev/null +++ b/3rdparty/wlroots/xwayland/sockets.h @@ -0,0 +1,9 @@ +#ifndef XWAYLAND_SOCKETS_H +#define XWAYLAND_SOCKETS_H + +#include + +void unlink_display_sockets(int display); +int open_display_sockets(int socks[2]); + +#endif diff --git a/3rdparty/wlroots/xwayland/xwayland.c b/3rdparty/wlroots/xwayland/xwayland.c new file mode 100644 index 0000000000..300b582ea9 --- /dev/null +++ b/3rdparty/wlroots/xwayland/xwayland.c @@ -0,0 +1,213 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "xwayland/xwm.h" + +static void handle_server_destroy(struct wl_listener *listener, void *data) { + struct wlr_xwayland *xwayland = + wl_container_of(listener, xwayland, server_destroy); + // Server is being destroyed so avoid destroying it once again. + xwayland->server = NULL; + wlr_xwayland_destroy(xwayland); +} + +static void handle_server_start(struct wl_listener *listener, void *data) { + struct wlr_xwayland *xwayland = + wl_container_of(listener, xwayland, server_start); + if (xwayland->shell_v1 != NULL) { + wlr_xwayland_shell_v1_set_client(xwayland->shell_v1, xwayland->server->client); + } +} + +static void xwayland_mark_ready(struct wlr_xwayland *xwayland) { + assert(xwayland->server->wm_fd[0] >= 0); + xwayland->xwm = xwm_create(xwayland, xwayland->server->wm_fd[0]); + // xwm_create takes ownership of wm_fd[0] under all circumstances + xwayland->server->wm_fd[0] = -1; + + if (!xwayland->xwm) { + return; + } + + if (xwayland->seat) { + xwm_set_seat(xwayland->xwm, xwayland->seat); + } + + if (xwayland->cursor_buffer != NULL) { + xwm_set_cursor(xwayland->xwm, xwayland->cursor_buffer, + xwayland->cursor_hotspot.x, xwayland->cursor_hotspot.y); + } + + wl_signal_emit_mutable(&xwayland->events.ready, NULL); +} + +static void handle_server_ready(struct wl_listener *listener, void *data) { + struct wlr_xwayland *xwayland = + wl_container_of(listener, xwayland, server_ready); + xwayland_mark_ready(xwayland); +} + +static void handle_shell_destroy(struct wl_listener *listener, void *data) { + struct wlr_xwayland *xwayland = + wl_container_of(listener, xwayland, shell_destroy); + xwayland->shell_v1 = NULL; + wl_list_remove(&xwayland->shell_destroy.link); + // Will remove this list in handle_shell_destroy(). + // This ensures the link is always initialized and + // avoids the need to keep check conditions in sync. + wl_list_init(&xwayland->shell_destroy.link); +} + +void wlr_xwayland_destroy(struct wlr_xwayland *xwayland) { + if (!xwayland) { + return; + } + + wl_signal_emit_mutable(&xwayland->events.destroy, NULL); + + assert(wl_list_empty(&xwayland->events.destroy.listener_list)); + assert(wl_list_empty(&xwayland->events.new_surface.listener_list)); + assert(wl_list_empty(&xwayland->events.ready.listener_list)); + assert(wl_list_empty(&xwayland->events.remove_startup_info.listener_list)); + + wl_list_remove(&xwayland->server_destroy.link); + wl_list_remove(&xwayland->server_start.link); + wl_list_remove(&xwayland->server_ready.link); + wl_list_remove(&xwayland->shell_destroy.link); + wlr_buffer_unlock(xwayland->cursor_buffer); + + wlr_xwayland_set_seat(xwayland, NULL); + if (xwayland->own_server) { + wlr_xwayland_server_destroy(xwayland->server); + } + xwayland->server = NULL; + wlr_xwayland_shell_v1_destroy(xwayland->shell_v1); + xwm_destroy(xwayland->xwm); + free(xwayland); +} + +struct wlr_xwayland *wlr_xwayland_create_with_server(struct wl_display *wl_display, + struct wlr_compositor *compositor, struct wlr_xwayland_server *server) { + struct wlr_xwayland *xwayland = calloc(1, sizeof(*xwayland)); + if (!xwayland) { + return NULL; + } + + xwayland->wl_display = wl_display; + xwayland->compositor = compositor; + + wl_signal_init(&xwayland->events.destroy); + wl_signal_init(&xwayland->events.new_surface); + wl_signal_init(&xwayland->events.ready); + wl_signal_init(&xwayland->events.remove_startup_info); + + xwayland->server = server; + xwayland->display_name = xwayland->server->display_name; + + xwayland->server_destroy.notify = handle_server_destroy; + wl_signal_add(&xwayland->server->events.destroy, &xwayland->server_destroy); + + xwayland->server_start.notify = handle_server_start; + wl_signal_add(&xwayland->server->events.start, &xwayland->server_start); + + xwayland->server_ready.notify = handle_server_ready; + wl_signal_add(&xwayland->server->events.ready, &xwayland->server_ready); + + wl_list_init(&xwayland->shell_destroy.link); + + if (server->ready) { + xwayland_mark_ready(xwayland); + } + + return xwayland; +} + +struct wlr_xwayland *wlr_xwayland_create(struct wl_display *wl_display, + struct wlr_compositor *compositor, bool lazy) { + struct wlr_xwayland_shell_v1 *shell_v1 = wlr_xwayland_shell_v1_create(wl_display, 1); + if (shell_v1 == NULL) { + return NULL; + } + + struct wlr_xwayland_server_options options = { + .lazy = lazy, + .enable_wm = true, + .terminate_delay = lazy ? 10 : 0, + }; + struct wlr_xwayland_server *server = wlr_xwayland_server_create(wl_display, &options); + if (server == NULL) { + goto error_shell_v1; + } + + struct wlr_xwayland *xwayland = wlr_xwayland_create_with_server(wl_display, compositor, server); + if (xwayland == NULL) { + goto error_server; + } + + xwayland->shell_v1 = shell_v1; + xwayland->own_server = true; + + xwayland->shell_destroy.notify = handle_shell_destroy; + wl_signal_add(&xwayland->shell_v1->events.destroy, &xwayland->shell_destroy); + + return xwayland; + +error_server: + wlr_xwayland_server_destroy(server); +error_shell_v1: + wlr_xwayland_shell_v1_destroy(shell_v1); + return NULL; +} + +void wlr_xwayland_set_cursor(struct wlr_xwayland *xwayland, + struct wlr_buffer *buffer, int32_t hotspot_x, int32_t hotspot_y) { + if (xwayland->xwm != NULL) { + xwm_set_cursor(xwayland->xwm, buffer, hotspot_x, hotspot_y); + return; + } + + wlr_buffer_unlock(xwayland->cursor_buffer); + xwayland->cursor_buffer = wlr_buffer_lock(buffer); + xwayland->cursor_hotspot.x = hotspot_x; + xwayland->cursor_hotspot.y = hotspot_y; +} + +static void xwayland_handle_seat_destroy(struct wl_listener *listener, + void *data) { + struct wlr_xwayland *xwayland = + wl_container_of(listener, xwayland, seat_destroy); + + wlr_xwayland_set_seat(xwayland, NULL); +} + +void wlr_xwayland_set_seat(struct wlr_xwayland *xwayland, + struct wlr_seat *seat) { + if (xwayland->seat) { + wl_list_remove(&xwayland->seat_destroy.link); + } + + xwayland->seat = seat; + + if (xwayland->xwm) { + xwm_set_seat(xwayland->xwm, seat); + } + + if (seat == NULL) { + return; + } + + xwayland->seat_destroy.notify = xwayland_handle_seat_destroy; + wl_signal_add(&seat->events.destroy, &xwayland->seat_destroy); +} diff --git a/3rdparty/wlroots/xwayland/xwm.c b/3rdparty/wlroots/xwayland/xwm.c new file mode 100644 index 0000000000..1b826e08ae --- /dev/null +++ b/3rdparty/wlroots/xwayland/xwm.c @@ -0,0 +1,3127 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "xwayland/xwm.h" + +static const char *const atom_map[ATOM_LAST] = { + [WL_SURFACE_ID] = "WL_SURFACE_ID", + [WL_SURFACE_SERIAL] = "WL_SURFACE_SERIAL", + [WM_DELETE_WINDOW] = "WM_DELETE_WINDOW", + [WM_PROTOCOLS] = "WM_PROTOCOLS", + [WM_HINTS] = "WM_HINTS", + [WM_NORMAL_HINTS] = "WM_NORMAL_HINTS", + [WM_SIZE_HINTS] = "WM_SIZE_HINTS", + [WM_WINDOW_ROLE] = "WM_WINDOW_ROLE", + [MOTIF_WM_HINTS] = "_MOTIF_WM_HINTS", + [UTF8_STRING] = "UTF8_STRING", + [WM_S0] = "WM_S0", + [NET_SUPPORTED] = "_NET_SUPPORTED", + [NET_WM_CM_S0] = "_NET_WM_CM_S0", + [NET_WM_PID] = "_NET_WM_PID", + [NET_WM_NAME] = "_NET_WM_NAME", + [NET_WM_STATE] = "_NET_WM_STATE", + [NET_WM_STRUT_PARTIAL] = "_NET_WM_STRUT_PARTIAL", + [NET_WM_WINDOW_TYPE] = "_NET_WM_WINDOW_TYPE", + [NET_WM_ICON] = "_NET_WM_ICON", + [WM_TAKE_FOCUS] = "WM_TAKE_FOCUS", + [WINDOW] = "WINDOW", + [NET_ACTIVE_WINDOW] = "_NET_ACTIVE_WINDOW", + [NET_CLOSE_WINDOW] = "_NET_CLOSE_WINDOW", + [NET_WM_MOVERESIZE] = "_NET_WM_MOVERESIZE", + [NET_SUPPORTING_WM_CHECK] = "_NET_SUPPORTING_WM_CHECK", + [NET_WM_STATE_FOCUSED] = "_NET_WM_STATE_FOCUSED", + [NET_WM_STATE_MODAL] = "_NET_WM_STATE_MODAL", + [NET_WM_STATE_FULLSCREEN] = "_NET_WM_STATE_FULLSCREEN", + [NET_WM_STATE_MAXIMIZED_VERT] = "_NET_WM_STATE_MAXIMIZED_VERT", + [NET_WM_STATE_MAXIMIZED_HORZ] = "_NET_WM_STATE_MAXIMIZED_HORZ", + [NET_WM_STATE_HIDDEN] = "_NET_WM_STATE_HIDDEN", + [NET_WM_STATE_STICKY] = "_NET_WM_STATE_STICKY", + [NET_WM_STATE_SHADED] = "_NET_WM_STATE_SHADED", + [NET_WM_STATE_SKIP_TASKBAR] = "_NET_WM_STATE_SKIP_TASKBAR", + [NET_WM_STATE_SKIP_PAGER] = "_NET_WM_STATE_SKIP_PAGER", + [NET_WM_STATE_ABOVE] = "_NET_WM_STATE_ABOVE", + [NET_WM_STATE_BELOW] = "_NET_WM_STATE_BELOW", + [NET_WM_STATE_DEMANDS_ATTENTION] = "_NET_WM_STATE_DEMANDS_ATTENTION", + [NET_WM_PING] = "_NET_WM_PING", + [WM_CHANGE_STATE] = "WM_CHANGE_STATE", + [WM_STATE] = "WM_STATE", + [CLIPBOARD] = "CLIPBOARD", + [PRIMARY] = "PRIMARY", + [WL_SELECTION] = "_WL_SELECTION", + [TARGETS] = "TARGETS", + [CLIPBOARD_MANAGER] = "CLIPBOARD_MANAGER", + [INCR] = "INCR", + [TEXT] = "TEXT", + [TIMESTAMP] = "TIMESTAMP", + [DELETE] = "DELETE", + [NET_STARTUP_ID] = "_NET_STARTUP_ID", + [NET_STARTUP_INFO] = "_NET_STARTUP_INFO", + [NET_STARTUP_INFO_BEGIN] = "_NET_STARTUP_INFO_BEGIN", + [NET_WM_WINDOW_OPACITY] = "_NET_WM_WINDOW_OPACITY", + [NET_WM_WINDOW_TYPE_NORMAL] = "_NET_WM_WINDOW_TYPE_NORMAL", + [NET_WM_WINDOW_TYPE_UTILITY] = "_NET_WM_WINDOW_TYPE_UTILITY", + [NET_WM_WINDOW_TYPE_TOOLTIP] = "_NET_WM_WINDOW_TYPE_TOOLTIP", + [NET_WM_WINDOW_TYPE_DND] = "_NET_WM_WINDOW_TYPE_DND", + [NET_WM_WINDOW_TYPE_DROPDOWN_MENU] = "_NET_WM_WINDOW_TYPE_DROPDOWN_MENU", + [NET_WM_WINDOW_TYPE_POPUP_MENU] = "_NET_WM_WINDOW_TYPE_POPUP_MENU", + [NET_WM_WINDOW_TYPE_COMBO] = "_NET_WM_WINDOW_TYPE_COMBO", + [NET_WM_WINDOW_TYPE_MENU] = "_NET_WM_WINDOW_TYPE_MENU", + [NET_WM_WINDOW_TYPE_NOTIFICATION] = "_NET_WM_WINDOW_TYPE_NOTIFICATION", + [NET_WM_WINDOW_TYPE_SPLASH] = "_NET_WM_WINDOW_TYPE_SPLASH", + [NET_WM_WINDOW_TYPE_DESKTOP] = "_NET_WM_WINDOW_TYPE_DESKTOP", + [NET_WM_WINDOW_TYPE_DOCK] = "_NET_WM_WINDOW_TYPE_DOCK", + [NET_WM_WINDOW_TYPE_TOOLBAR] = "_NET_WM_WINDOW_TYPE_TOOLBAR", + [NET_WM_WINDOW_TYPE_DIALOG] = "_NET_WM_WINDOW_TYPE_DIALOG", + [DND_SELECTION] = "XdndSelection", + [DND_AWARE] = "XdndAware", + [DND_STATUS] = "XdndStatus", + [DND_POSITION] = "XdndPosition", + [DND_ENTER] = "XdndEnter", + [DND_LEAVE] = "XdndLeave", + [DND_DROP] = "XdndDrop", + [DND_FINISHED] = "XdndFinished", + [DND_PROXY] = "XdndProxy", + [DND_TYPE_LIST] = "XdndTypeList", + [DND_ACTION_MOVE] = "XdndActionMove", + [DND_ACTION_COPY] = "XdndActionCopy", + [DND_ACTION_ASK] = "XdndActionAsk", + [DND_ACTION_PRIVATE] = "XdndActionPrivate", + [NET_CLIENT_LIST] = "_NET_CLIENT_LIST", + [NET_CLIENT_LIST_STACKING] = "_NET_CLIENT_LIST_STACKING", + [NET_WORKAREA] = "_NET_WORKAREA", +}; + +#define STARTUP_INFO_REMOVE_PREFIX "remove: ID=" +struct pending_startup_id { + char *msg; + size_t len; + xcb_window_t window; + struct wl_list link; +}; + +static const struct wlr_addon_interface surface_addon_impl; + +struct wlr_xwayland_surface *wlr_xwayland_surface_try_from_wlr_surface( + struct wlr_surface *surface) { + struct wlr_addon *addon = wlr_addon_find(&surface->addons, NULL, &surface_addon_impl); + if (addon == NULL) { + return NULL; + } + struct wlr_xwayland_surface *xsurface = wl_container_of(addon, xsurface, surface_addon); + return xsurface; +} + +// TODO: replace this with hash table? +static struct wlr_xwayland_surface *lookup_surface(struct wlr_xwm *xwm, + xcb_window_t window_id) { + struct wlr_xwayland_surface *surface; + wl_list_for_each(surface, &xwm->surfaces, link) { + if (surface->window_id == window_id) { + return surface; + } + } + return NULL; +} + +void wlr_xwayland_surface_get_input_region(const struct wlr_xwayland_surface *xsurface, + pixman_region32_t *region) { + pixman_region32_copy(region, &xsurface->surface->input_region); + pixman_region32_intersect_rect(region, region, 0, 0, + xsurface->width, xsurface->height); + if (xsurface->has_input_shape) { + pixman_region32_intersect(region, region, &xsurface->input_shape); + } +} + +bool wlr_xwayland_surface_point_accepts_input( + const struct wlr_xwayland_surface *xsurface, double sx, double sy) { + if (sx < 0 || sx >= xsurface->width || + sy < 0 || sy >= xsurface->height || + !wlr_surface_point_accepts_input(xsurface->surface, sx, sy)) { + return false; + } + + return !xsurface->has_input_shape || + pixman_region32_contains_point(&xsurface->input_shape, + floor(sx), floor(sy), NULL); +} + +static bool read_surface_shape_region(struct wlr_xwm *xwm, + xcb_shape_get_rectangles_cookie_t cookie, pixman_region32_t *region) { + xcb_shape_get_rectangles_reply_t *reply = + xcb_shape_get_rectangles_reply(xwm->xcb_conn, cookie, NULL); + if (reply == NULL) { + return false; + } + + int len = xcb_shape_get_rectangles_rectangles_length(reply); + xcb_rectangle_t *rects = xcb_shape_get_rectangles_rectangles(reply); + for (int i = 0; i < len; i++) { + pixman_region32_union_rect(region, region, rects[i].x, rects[i].y, + rects[i].width, rects[i].height); + } + + free(reply); + return true; +} + +static void xwm_update_surface_shape(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, xcb_shape_sk_t changed_kind) { + if (changed_kind != XCB_SHAPE_SK_BOUNDING && + changed_kind != XCB_SHAPE_SK_INPUT) { + return; + } + + const xcb_shape_sk_t kinds[] = {XCB_SHAPE_SK_BOUNDING, XCB_SHAPE_SK_INPUT}; + for (size_t i = 0; i < sizeof(kinds) / sizeof(kinds[0]); i++) { + xcb_shape_sk_t shape_sk = kinds[i]; + if ((shape_sk == XCB_SHAPE_SK_BOUNDING && + changed_kind != XCB_SHAPE_SK_BOUNDING) || + (shape_sk == XCB_SHAPE_SK_INPUT && !xwm->shape_input_supported)) { + continue; + } + + bool is_input = shape_sk == XCB_SHAPE_SK_INPUT; + bool *has_shape = is_input ? + &xsurface->has_input_shape : &xsurface->has_clip_shape; + pixman_region32_t *region = is_input ? + &xsurface->input_shape : &xsurface->clip_shape; + struct wl_signal *signal = is_input ? + &xsurface->events.set_input_shape : &xsurface->events.set_clip_shape; + bool has_new_shape = true; + if (shape_sk == XCB_SHAPE_SK_BOUNDING) { + xcb_shape_query_extents_cookie_t cookie = + xcb_shape_query_extents(xwm->xcb_conn, xsurface->window_id); + xcb_shape_query_extents_reply_t *reply = + xcb_shape_query_extents_reply(xwm->xcb_conn, cookie, NULL); + if (reply == NULL) { + continue; + } + has_new_shape = reply->bounding_shaped; + free(reply); + } + + pixman_region32_t new_region; + pixman_region32_init(&new_region); + if (has_new_shape) { + xcb_shape_get_rectangles_cookie_t cookie = + xcb_shape_get_rectangles(xwm->xcb_conn, xsurface->window_id, shape_sk); + xcb_shape_get_rectangles_cookie_t bounding_cookie = {0}; + if (shape_sk == XCB_SHAPE_SK_INPUT) { + bounding_cookie = xcb_shape_get_rectangles(xwm->xcb_conn, + xsurface->window_id, XCB_SHAPE_SK_BOUNDING); + } + bool shape_ok = read_surface_shape_region(xwm, cookie, &new_region); + if (shape_sk == XCB_SHAPE_SK_INPUT) { + pixman_region32_t bounding_region; + pixman_region32_init(&bounding_region); + bool bounding_ok = read_surface_shape_region(xwm, bounding_cookie, + &bounding_region); + // Input is constrained by both the input and bounding regions. + pixman_region32_intersect(&new_region, &new_region, &bounding_region); + pixman_region32_fini(&bounding_region); + if (!shape_ok || !bounding_ok) { + pixman_region32_fini(&new_region); + continue; + } + + pixman_region32_t full_region; + pixman_region32_init_rect(&full_region, 0, 0, + xsurface->width, xsurface->height); + has_new_shape = !pixman_region32_equal(&new_region, &full_region); + pixman_region32_fini(&full_region); + } else if (!shape_ok) { + pixman_region32_fini(&new_region); + continue; + } + } + + // Rendering caches the client bounding region; the caller applies the + // size-dependent default region. ShapeClip does not clip the visible border. + bool changed = *has_shape != has_new_shape || + (has_new_shape && !pixman_region32_equal(region, &new_region)); + if (changed) { + *has_shape = has_new_shape; + if (has_new_shape) { + pixman_region32_copy(region, &new_region); + } else { + pixman_region32_clear(region); + } + } + pixman_region32_fini(&new_region); + if (changed) { + wl_signal_emit_mutable(signal, NULL); + } + } +} + +static int xwayland_surface_handle_ping_timeout(void *data) { + struct wlr_xwayland_surface *surface = data; + + wl_signal_emit_mutable(&surface->events.ping_timeout, NULL); + surface->pinging = false; + return 1; +} + +static void read_surface_client_id(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, + xcb_res_query_client_ids_cookie_t cookie) { + xcb_res_query_client_ids_reply_t *reply = xcb_res_query_client_ids_reply( + xwm->xcb_conn, cookie, NULL); + if (reply == NULL) { + return; + } + + uint32_t *pid = NULL; + xcb_res_client_id_value_iterator_t iter = + xcb_res_query_client_ids_ids_iterator(reply); + while (iter.rem > 0) { + if (iter.data->spec.mask & XCB_RES_CLIENT_ID_MASK_LOCAL_CLIENT_PID && + xcb_res_client_id_value_value_length(iter.data) > 0) { + pid = xcb_res_client_id_value_value(iter.data); + break; + } + xcb_res_client_id_value_next(&iter); + } + if (pid == NULL) { + free(reply); + return; + } + xsurface->pid = *pid; + free(reply); +} + +static struct wlr_xwayland_surface *xwayland_surface_create( + struct wlr_xwm *xwm, xcb_window_t window_id, int16_t x, int16_t y, + uint16_t width, uint16_t height, bool override_redirect) { + struct wlr_xwayland_surface *surface = calloc(1, sizeof(*surface)); + if (!surface) { + wlr_log(WLR_ERROR, "Could not allocate wlr xwayland surface"); + return NULL; + } + + xcb_get_geometry_cookie_t geometry_cookie = + xcb_get_geometry(xwm->xcb_conn, window_id); + + xcb_res_query_client_ids_cookie_t client_id_cookie = { 0 }; + if (xwm->xres) { + xcb_res_client_id_spec_t spec = { + .client = window_id, + .mask = XCB_RES_CLIENT_ID_MASK_LOCAL_CLIENT_PID + }; + client_id_cookie = xcb_res_query_client_ids(xwm->xcb_conn, 1, &spec); + } + + uint32_t values[1]; + values[0] = + XCB_EVENT_MASK_FOCUS_CHANGE | + XCB_EVENT_MASK_PROPERTY_CHANGE; + xcb_change_window_attributes(xwm->xcb_conn, window_id, + XCB_CW_EVENT_MASK, values); + + surface->xwm = xwm; + surface->window_id = window_id; + surface->x = x; + surface->y = y; + surface->width = width; + surface->height = height; + surface->override_redirect = override_redirect; + surface->opacity = 1.0; + wl_list_init(&surface->children); + wl_list_init(&surface->stack_link); + wl_list_init(&surface->parent_link); + wl_list_init(&surface->unpaired_link); + pixman_region32_init(&surface->input_shape); + pixman_region32_init(&surface->clip_shape); + + wl_signal_init(&surface->events.destroy); + wl_signal_init(&surface->events.request_configure); + wl_signal_init(&surface->events.request_move); + wl_signal_init(&surface->events.request_resize); + wl_signal_init(&surface->events.request_minimize); + wl_signal_init(&surface->events.request_maximize); + wl_signal_init(&surface->events.request_fullscreen); + wl_signal_init(&surface->events.request_activate); + wl_signal_init(&surface->events.request_close); + wl_signal_init(&surface->events.request_sticky); + wl_signal_init(&surface->events.request_shaded); + wl_signal_init(&surface->events.request_skip_taskbar); + wl_signal_init(&surface->events.request_skip_pager); + wl_signal_init(&surface->events.request_above); + wl_signal_init(&surface->events.request_below); + wl_signal_init(&surface->events.request_demands_attention); + wl_signal_init(&surface->events.associate); + wl_signal_init(&surface->events.dissociate); + wl_signal_init(&surface->events.set_class); + wl_signal_init(&surface->events.set_role); + wl_signal_init(&surface->events.set_title); + wl_signal_init(&surface->events.set_parent); + wl_signal_init(&surface->events.set_startup_id); + wl_signal_init(&surface->events.set_window_type); + wl_signal_init(&surface->events.set_hints); + wl_signal_init(&surface->events.set_size_hints); + wl_signal_init(&surface->events.set_decorations); + wl_signal_init(&surface->events.set_strut_partial); + wl_signal_init(&surface->events.set_override_redirect); + wl_signal_init(&surface->events.set_geometry); + wl_signal_init(&surface->events.set_opacity); + wl_signal_init(&surface->events.set_icon); + wl_signal_init(&surface->events.set_input_shape); + wl_signal_init(&surface->events.set_clip_shape); + wl_signal_init(&surface->events.focus_in); + wl_signal_init(&surface->events.grab_focus); + wl_signal_init(&surface->events.map_request); + wl_signal_init(&surface->events.ping_timeout); + + xcb_get_geometry_reply_t *geometry_reply = + xcb_get_geometry_reply(xwm->xcb_conn, geometry_cookie, NULL); + if (geometry_reply != NULL) { + surface->has_alpha = geometry_reply->depth == 32; + } + free(geometry_reply); + + if (xwm->shape != NULL && xwm->shape->present) { + xcb_shape_select_input(xwm->xcb_conn, window_id, true); + xwm_update_surface_shape(xwm, surface, XCB_SHAPE_SK_BOUNDING); + } + + struct wl_display *display = xwm->xwayland->wl_display; + struct wl_event_loop *loop = wl_display_get_event_loop(display); + surface->ping_timer = wl_event_loop_add_timer(loop, + xwayland_surface_handle_ping_timeout, surface); + if (surface->ping_timer == NULL) { + pixman_region32_fini(&surface->input_shape); + pixman_region32_fini(&surface->clip_shape); + free(surface); + wlr_log(WLR_ERROR, "Could not add timer to event loop"); + return NULL; + } + + wl_list_insert(&xwm->surfaces, &surface->link); + + if (xwm->xres) { + read_surface_client_id(xwm, surface, client_id_cookie); + } + + wl_signal_emit_mutable(&xwm->xwayland->events.new_surface, surface); + + return surface; +} + +static void xwm_set_net_active_window(struct wlr_xwm *xwm, + xcb_window_t window) { + xcb_change_property(xwm->xcb_conn, XCB_PROP_MODE_REPLACE, + xwm->screen->root, xwm->atoms[NET_ACTIVE_WINDOW], + xwm->atoms[WINDOW], 32, 1, &window); +} + +/* + * Wrapper for xcb_send_event, which ensures that the event data is 32 byte big. + */ +xcb_void_cookie_t xwm_send_event_with_size(xcb_connection_t *c, + uint8_t propagate, xcb_window_t destination, + uint32_t event_mask, const void *event, uint32_t length) { + if (length == 32) { + return xcb_send_event(c, propagate, destination, event_mask, event); + } else if (length < 32) { + char buf[32]; + memcpy(buf, event, length); + memset(buf + length, 0, 32 - length); + return xcb_send_event(c, propagate, destination, event_mask, buf); + } else { + assert(false && "Event too long"); + } +} + +static void xwm_send_wm_message(struct wlr_xwayland_surface *surface, + xcb_client_message_data_t *data, uint32_t event_mask) { + struct wlr_xwm *xwm = surface->xwm; + + xcb_client_message_event_t event = { + .response_type = XCB_CLIENT_MESSAGE, + .format = 32, + .sequence = 0, + .window = surface->window_id, + .type = xwm->atoms[WM_PROTOCOLS], + .data = *data, + }; + + xwm_send_event_with_size(xwm->xcb_conn, + 0, // propagate + surface->window_id, + event_mask, + &event, + sizeof(event)); + xwm_schedule_flush(xwm); +} + +static void xwm_set_net_client_list(struct wlr_xwm *xwm) { + // FIXME: _NET_CLIENT_LIST is expected to be ordered by map time, but the + // order of surfaces in `xwm->surfaces` is by creation time. The order of + // windows _NET_CLIENT_LIST exposed by wlroots is wrong. + + size_t mapped_surfaces = 0; + struct wlr_xwayland_surface *surface; + wl_list_for_each(surface, &xwm->surfaces, link) { + if (surface->surface != NULL && surface->surface->mapped) { + mapped_surfaces++; + } + } + + xcb_window_t *windows = NULL; + if (mapped_surfaces > 0) { + windows = malloc(sizeof(*windows) * mapped_surfaces); + if (!windows) { + return; + } + + size_t index = 0; + wl_list_for_each(surface, &xwm->surfaces, link) { + if (surface->surface != NULL && surface->surface->mapped) { + windows[index++] = surface->window_id; + } + } + } + + xcb_change_property(xwm->xcb_conn, XCB_PROP_MODE_REPLACE, + xwm->screen->root, xwm->atoms[NET_CLIENT_LIST], + XCB_ATOM_WINDOW, 32, mapped_surfaces, windows); + free(windows); +} + +static void xwm_set_net_client_list_stacking(struct wlr_xwm *xwm) { + size_t num_surfaces = wl_list_length(&xwm->surfaces_in_stack_order); + xcb_window_t *windows = malloc(sizeof(xcb_window_t) * num_surfaces); + if (!windows) { + return; + } + + size_t i = 0; + struct wlr_xwayland_surface *xsurface; + wl_list_for_each(xsurface, &xwm->surfaces_in_stack_order, stack_link) { + windows[i++] = xsurface->window_id; + } + + xcb_change_property(xwm->xcb_conn, XCB_PROP_MODE_REPLACE, xwm->screen->root, + xwm->atoms[NET_CLIENT_LIST_STACKING], XCB_ATOM_WINDOW, 32, num_surfaces, + windows); + free(windows); +} + +static void xsurface_set_net_wm_state(struct wlr_xwayland_surface *xsurface); + +// Gives input (keyboard) focus to a window. +// Normally followed by xwm_set_focused_window(). +static void xwm_focus_window(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface) { + + // We handle cases where focus_surface == xsurface because we + // want to be able to deny FocusIn events. + if (!xsurface) { + // XCB_POINTER_ROOT is described in xcb documentation but isn't + // actually defined in the headers. It's distinct from XCB_NONE + // (which disables keyboard input entirely and causes issues + // with keyboard grabs for e.g. popups). + xcb_set_input_focus_checked(xwm->xcb_conn, + XCB_INPUT_FOCUS_POINTER_ROOT, + 1L /*XCB_POINTER_ROOT*/, XCB_CURRENT_TIME); + return; + } + + if (xsurface->override_redirect) { + return; + } + + xcb_client_message_data_t message_data = { 0 }; + message_data.data32[0] = xwm->atoms[WM_TAKE_FOCUS]; + message_data.data32[1] = XCB_TIME_CURRENT_TIME; + + if (xsurface->hints && !xsurface->hints->input) { + // if the surface doesn't allow the focus request, we will send him + // only the take focus event. It will get the focus by itself. + xwm_send_wm_message(xsurface, &message_data, XCB_EVENT_MASK_NO_EVENT); + } else { + xwm_send_wm_message(xsurface, &message_data, XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT); + + xcb_void_cookie_t cookie = xcb_set_input_focus(xwm->xcb_conn, + XCB_INPUT_FOCUS_POINTER_ROOT, xsurface->window_id, XCB_CURRENT_TIME); + xwm->last_focus_seq = cookie.sequence; + } +} + +// Updates _NET_ACTIVE_WINDOW and _NET_WM_STATE when focus changes. +static void xwm_set_focused_window(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface) { + struct wlr_xwayland_surface *unfocus_surface = xwm->focus_surface; + + if (xsurface && xsurface->override_redirect) { + return; + } + + xwm->focus_surface = xsurface; + // cancel any pending focus offer + xwm->offered_focus = xsurface; + + if (xsurface == unfocus_surface) { + return; + } + + if (unfocus_surface) { + xsurface_set_net_wm_state(unfocus_surface); + } + + if (xsurface) { + xsurface_set_net_wm_state(xsurface); + xwm_set_net_active_window(xwm, xsurface->window_id); + } else { + xwm_set_net_active_window(xwm, xwm->no_focus_window); + } +} + +void wlr_xwayland_surface_offer_focus(struct wlr_xwayland_surface *xsurface) { + if (!xsurface || xsurface->override_redirect) { + return; + } + + struct wlr_xwm *xwm = xsurface->xwm; + if (!xwm_atoms_contains(xwm, xsurface->protocols, + xsurface->protocols_len, WM_TAKE_FOCUS)) { + return; + } + + xwm->offered_focus = xsurface; + + xcb_client_message_data_t message_data = { 0 }; + message_data.data32[0] = xwm->atoms[WM_TAKE_FOCUS]; + message_data.data32[1] = XCB_TIME_CURRENT_TIME; + xwm_send_wm_message(xsurface, &message_data, XCB_EVENT_MASK_NO_EVENT); + + xcb_flush(xwm->xcb_conn); +} + +static void xwm_surface_activate(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface) { + if (xsurface && xsurface->override_redirect) { + return; + } + + if (xsurface != xwm->focus_surface && xsurface != xwm->offered_focus) { + xwm_focus_window(xwm, xsurface); + } + + xwm_set_focused_window(xwm, xsurface); + xwm_schedule_flush(xwm); +} + +static void xsurface_set_net_wm_state(struct wlr_xwayland_surface *xsurface) { + struct wlr_xwm *xwm = xsurface->xwm; + + // EWMH says _NET_WM_STATE should be unset if the window is withdrawn + if (xsurface->withdrawn) { + xcb_delete_property(xwm->xcb_conn, + xsurface->window_id, + xwm->atoms[NET_WM_STATE]); + return; + } + + uint32_t property[13]; + size_t i = 0; + if (xsurface->modal) { + property[i++] = xwm->atoms[NET_WM_STATE_MODAL]; + } + if (xsurface->fullscreen) { + property[i++] = xwm->atoms[NET_WM_STATE_FULLSCREEN]; + } + if (xsurface->maximized_vert) { + property[i++] = xwm->atoms[NET_WM_STATE_MAXIMIZED_VERT]; + } + if (xsurface->maximized_horz) { + property[i++] = xwm->atoms[NET_WM_STATE_MAXIMIZED_HORZ]; + } + if (xsurface->minimized) { + property[i++] = xwm->atoms[NET_WM_STATE_HIDDEN]; + } + if (xsurface->sticky) { + property[i++] = xwm->atoms[NET_WM_STATE_STICKY]; + } + if (xsurface->shaded) { + property[i++] = xwm->atoms[NET_WM_STATE_SHADED]; + } + if (xsurface->skip_taskbar) { + property[i++] = xwm->atoms[NET_WM_STATE_SKIP_TASKBAR]; + } + if (xsurface->skip_pager) { + property[i++] = xwm->atoms[NET_WM_STATE_SKIP_PAGER]; + } + if (xsurface->above) { + property[i++] = xwm->atoms[NET_WM_STATE_ABOVE]; + } + if (xsurface->below) { + property[i++] = xwm->atoms[NET_WM_STATE_BELOW]; + } + if (xsurface->demands_attention) { + property[i++] = xwm->atoms[NET_WM_STATE_DEMANDS_ATTENTION]; + } + if (xsurface == xwm->focus_surface) { + property[i++] = xwm->atoms[NET_WM_STATE_FOCUSED]; + } + assert(i <= sizeof(property) / sizeof(property[0])); + + xcb_change_property(xwm->xcb_conn, + XCB_PROP_MODE_REPLACE, + xsurface->window_id, + xwm->atoms[NET_WM_STATE], + XCB_ATOM_ATOM, + 32, // format + i, property); +} + +static void xwayland_surface_dissociate(struct wlr_xwayland_surface *xsurface) { + if (xsurface->surface != NULL) { + wlr_surface_unmap(xsurface->surface); + wl_signal_emit_mutable(&xsurface->events.dissociate, NULL); + + wl_list_remove(&xsurface->surface_commit.link); + wl_list_remove(&xsurface->surface_map.link); + wl_list_remove(&xsurface->surface_unmap.link); + wlr_addon_finish(&xsurface->surface_addon); + xsurface->surface = NULL; + } + + // Make sure we're not on the unpaired surface list or we + // could be assigned a surface during surface creation that + // was mapped before this unmap request. + wl_list_remove(&xsurface->unpaired_link); + wl_list_init(&xsurface->unpaired_link); + xsurface->surface_id = 0; + xsurface->serial = 0; + + wl_list_remove(&xsurface->stack_link); + wl_list_init(&xsurface->stack_link); + xwm_set_net_client_list_stacking(xsurface->xwm); +} + +static void xwayland_surface_destroy(struct wlr_xwayland_surface *xsurface) { + xwayland_surface_dissociate(xsurface); + + wl_signal_emit_mutable(&xsurface->events.destroy, NULL); + + assert(wl_list_empty(&xsurface->events.destroy.listener_list)); + assert(wl_list_empty(&xsurface->events.request_configure.listener_list)); + assert(wl_list_empty(&xsurface->events.request_move.listener_list)); + assert(wl_list_empty(&xsurface->events.request_resize.listener_list)); + assert(wl_list_empty(&xsurface->events.request_minimize.listener_list)); + assert(wl_list_empty(&xsurface->events.request_maximize.listener_list)); + assert(wl_list_empty(&xsurface->events.request_fullscreen.listener_list)); + assert(wl_list_empty(&xsurface->events.request_activate.listener_list)); + assert(wl_list_empty(&xsurface->events.request_close.listener_list)); + assert(wl_list_empty(&xsurface->events.request_sticky.listener_list)); + assert(wl_list_empty(&xsurface->events.request_shaded.listener_list)); + assert(wl_list_empty(&xsurface->events.request_skip_taskbar.listener_list)); + assert(wl_list_empty(&xsurface->events.request_skip_pager.listener_list)); + assert(wl_list_empty(&xsurface->events.request_above.listener_list)); + assert(wl_list_empty(&xsurface->events.request_below.listener_list)); + assert(wl_list_empty(&xsurface->events.request_demands_attention.listener_list)); + assert(wl_list_empty(&xsurface->events.associate.listener_list)); + assert(wl_list_empty(&xsurface->events.dissociate.listener_list)); + assert(wl_list_empty(&xsurface->events.set_class.listener_list)); + assert(wl_list_empty(&xsurface->events.set_role.listener_list)); + assert(wl_list_empty(&xsurface->events.set_title.listener_list)); + assert(wl_list_empty(&xsurface->events.set_parent.listener_list)); + assert(wl_list_empty(&xsurface->events.set_startup_id.listener_list)); + assert(wl_list_empty(&xsurface->events.set_window_type.listener_list)); + assert(wl_list_empty(&xsurface->events.set_hints.listener_list)); + assert(wl_list_empty(&xsurface->events.set_size_hints.listener_list)); + assert(wl_list_empty(&xsurface->events.set_decorations.listener_list)); + assert(wl_list_empty(&xsurface->events.set_strut_partial.listener_list)); + assert(wl_list_empty(&xsurface->events.set_override_redirect.listener_list)); + assert(wl_list_empty(&xsurface->events.set_geometry.listener_list)); + assert(wl_list_empty(&xsurface->events.set_opacity.listener_list)); + assert(wl_list_empty(&xsurface->events.set_icon.listener_list)); + assert(wl_list_empty(&xsurface->events.set_input_shape.listener_list)); + assert(wl_list_empty(&xsurface->events.set_clip_shape.listener_list)); + assert(wl_list_empty(&xsurface->events.focus_in.listener_list)); + assert(wl_list_empty(&xsurface->events.grab_focus.listener_list)); + assert(wl_list_empty(&xsurface->events.map_request.listener_list)); + assert(wl_list_empty(&xsurface->events.ping_timeout.listener_list)); + + if (xsurface == xsurface->xwm->focus_surface) { + xwm_surface_activate(xsurface->xwm, NULL); + } + if (xsurface == xsurface->xwm->offered_focus) { + xsurface->xwm->offered_focus = NULL; + } + + wl_list_remove(&xsurface->link); + wl_list_remove(&xsurface->parent_link); + + struct wlr_xwayland_surface *child, *next; + wl_list_for_each_safe(child, next, &xsurface->children, parent_link) { + wl_list_remove(&child->parent_link); + wl_list_init(&child->parent_link); + child->parent = NULL; + wl_signal_emit_mutable(&child->events.set_parent, NULL); + } + + wl_list_remove(&xsurface->unpaired_link); + + wl_event_source_remove(xsurface->ping_timer); + + free(xsurface->wm_name); + free(xsurface->net_wm_name); + free(xsurface->class); + free(xsurface->instance); + free(xsurface->role); + free(xsurface->window_type); + free(xsurface->protocols); + free(xsurface->startup_id); + free(xsurface->hints); + free(xsurface->size_hints); + free(xsurface->strut_partial); + pixman_region32_fini(&xsurface->input_shape); + pixman_region32_fini(&xsurface->clip_shape); + free(xsurface); +} + +static void read_surface_class(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *surface, xcb_get_property_reply_t *reply) { + if (reply->type != XCB_ATOM_STRING && reply->type != xwm->atoms[UTF8_STRING] && + reply->type != XCB_ATOM_NONE) { + wlr_log(WLR_DEBUG, "Invalid WM_CLASS property type"); + return; + } + + size_t len = xcb_get_property_value_length(reply); + const char *class = xcb_get_property_value(reply); + + // Unpack two sequentially stored strings: instance, class + size_t instance_len = strnlen(class, len); + free(surface->instance); + if (len > 0 && instance_len < len) { + surface->instance = strndup(class, instance_len); + class += instance_len + 1; + len -= instance_len + 1; + } else { + surface->instance = NULL; + } + free(surface->class); + if (len > 0) { + surface->class = strndup(class, len); + } else { + surface->class = NULL; + } + + wl_signal_emit_mutable(&surface->events.set_class, NULL); +} + +static void read_surface_startup_id(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, + xcb_get_property_reply_t *reply) { + if (reply->type != XCB_ATOM_STRING && reply->type != xwm->atoms[UTF8_STRING] && + reply->type != XCB_ATOM_NONE) { + wlr_log(WLR_DEBUG, "Invalid NET_STARTUP_ID property type"); + return; + } + + size_t len = xcb_get_property_value_length(reply); + const char *startup_id = xcb_get_property_value(reply); + + free(xsurface->startup_id); + if (len > 0) { + xsurface->startup_id = strndup(startup_id, len); + } else { + xsurface->startup_id = NULL; + } + + wlr_log(WLR_DEBUG, "XCB_ATOM_NET_STARTUP_ID: %s", + xsurface->startup_id ? xsurface->startup_id: "(null)"); + wl_signal_emit_mutable(&xsurface->events.set_startup_id, NULL); +} + +static void read_surface_opacity(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, + xcb_get_property_reply_t *reply) { + if (reply->type == XCB_ATOM_NONE) { + xsurface->opacity = 1.0; + wl_signal_emit_mutable(&xsurface->events.set_opacity, NULL); + return; + } + + if (reply->type != XCB_ATOM_CARDINAL || reply->format != 32 || + xcb_get_property_value_length(reply) != sizeof(uint32_t)) { + wlr_log(WLR_DEBUG, "Invalid NET_WINDOW_OPACITY property type"); + return; + } + + const uint32_t *val = xcb_get_property_value(reply); + xsurface->opacity = (double)*val / UINT32_MAX; + wl_signal_emit_mutable(&xsurface->events.set_opacity, NULL); +} + +static void read_surface_role(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, + xcb_get_property_reply_t *reply) { + if (reply->type != XCB_ATOM_STRING && reply->type != xwm->atoms[UTF8_STRING] && + reply->type != XCB_ATOM_NONE) { + wlr_log(WLR_DEBUG, "Invalid WM_WINDOW_ROLE property type"); + return; + } + + size_t len = xcb_get_property_value_length(reply); + const char *role = xcb_get_property_value(reply); + + free(xsurface->role); + if (len > 0) { + xsurface->role = strndup(role, len); + } else { + xsurface->role = NULL; + } + + wl_signal_emit_mutable(&xsurface->events.set_role, NULL); +} + +static void read_surface_title(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, xcb_atom_t property, + xcb_get_property_reply_t *reply) { + if (reply->type != XCB_ATOM_STRING && reply->type != xwm->atoms[UTF8_STRING] && + reply->type != XCB_ATOM_NONE) { + wlr_log(WLR_DEBUG, "Invalid WM_NAME/NET_WM_NAME property type"); + return; + } + + size_t len = xcb_get_property_value_length(reply); + const char *title_buffer = xcb_get_property_value(reply); + char *title = NULL; + if (len > 0) { + title = strndup(title_buffer, len); + } + + if (property == XCB_ATOM_WM_NAME) { + free(xsurface->wm_name); + xsurface->wm_name = title; + } else if (property == xwm->atoms[NET_WM_NAME]) { + free(xsurface->net_wm_name); + xsurface->net_wm_name = title; + } else { + abort(); // unreachable + } + + // Prefer _NET_WM_NAME over WM_NAME if available + if (xsurface->net_wm_name != NULL) { + xsurface->title = xsurface->net_wm_name; + } else if (xsurface->wm_name != NULL) { + xsurface->title = xsurface->wm_name; + } else { + xsurface->title = NULL; + } + + wl_signal_emit_mutable(&xsurface->events.set_title, NULL); +} + +static bool has_parent(struct wlr_xwayland_surface *parent, + struct wlr_xwayland_surface *child) { + while (parent) { + if (child == parent) { + return true; + } + + parent = parent->parent; + } + + return false; +} + +static void read_surface_parent(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, + xcb_get_property_reply_t *reply) { + if (reply->type != XCB_ATOM_WINDOW && reply->type != XCB_ATOM_NONE) { + wlr_log(WLR_DEBUG, "Invalid WM_TRANSIENT_FOR property type"); + return; + } + + struct wlr_xwayland_surface *found_parent = NULL; + if (reply->type != XCB_ATOM_NONE) { + if (xcb_get_property_value_length(reply) != sizeof(xcb_window_t)) { + wlr_log(WLR_DEBUG, "Invalid WM_TRANSIENT_FOR property length"); + return; + } + const xcb_window_t *xid = xcb_get_property_value(reply); + found_parent = lookup_surface(xwm, *xid); + if (!has_parent(found_parent, xsurface)) { + xsurface->parent = found_parent; + } else { + wlr_log(WLR_INFO, "%p with %p would create a loop", xsurface, + found_parent); + } + } else { + xsurface->parent = NULL; + } + + wl_list_remove(&xsurface->parent_link); + if (xsurface->parent != NULL) { + wl_list_insert(&xsurface->parent->children, &xsurface->parent_link); + } else { + wl_list_init(&xsurface->parent_link); + } + + wl_signal_emit_mutable(&xsurface->events.set_parent, NULL); +} + +static void read_surface_window_type(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, + xcb_get_property_reply_t *reply) { + if (reply->type != XCB_ATOM_ATOM && reply->type != XCB_ATOM_NONE) { + wlr_log(WLR_DEBUG, "Invalid NET_WM_WINDOW_TYPE property type"); + return; + } + + const xcb_atom_t *atoms = xcb_get_property_value(reply); + size_t atoms_len = xcb_get_property_value_length(reply) / sizeof(atoms[0]); + size_t atoms_size = sizeof(atoms[0]) * atoms_len; + + free(xsurface->window_type); + if (atoms_len > 0) { + xsurface->window_type = malloc(atoms_size); + if (xsurface->window_type == NULL) { + return; + } + memcpy(xsurface->window_type, atoms, atoms_size); + } else { + xsurface->window_type = NULL; + } + xsurface->window_type_len = atoms_len; + + wl_signal_emit_mutable(&xsurface->events.set_window_type, NULL); +} + +static void read_surface_protocols(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, + xcb_get_property_reply_t *reply) { + if (reply->type != XCB_ATOM_ATOM && reply->type != XCB_ATOM_NONE) { + wlr_log(WLR_DEBUG, "Invalid WM_PROTOCOLS property type"); + return; + } + + const xcb_atom_t *atoms = xcb_get_property_value(reply); + size_t atoms_len = xcb_get_property_value_length(reply) / sizeof(atoms[0]); + size_t atoms_size = sizeof(atoms[0]) * atoms_len; + + free(xsurface->protocols); + if (atoms_len > 0) { + xsurface->protocols = malloc(atoms_size); + if (xsurface->protocols == NULL) { + return; + } + memcpy(xsurface->protocols, atoms, atoms_size); + } else { + xsurface->protocols = NULL; + } + xsurface->protocols_len = atoms_len; +} + +static void read_surface_hints(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, + xcb_get_property_reply_t *reply) { + // According to the docs, reply->type == xwm->atoms[WM_HINTS] + // In practice, reply->type == XCB_ATOM_ATOM + if (reply->type != xwm->atoms[WM_HINTS] && reply->type != XCB_ATOM_ATOM && + reply->type != XCB_ATOM_NONE) { + wlr_log(WLR_DEBUG, "Invalid WM_HINTS property type"); + return; + } + + free(xsurface->hints); + if (xcb_get_property_value_length(reply) > 0) { + xsurface->hints = calloc(1, sizeof(*xsurface->hints)); + if (xsurface->hints == NULL) { + return; + } + xcb_icccm_get_wm_hints_from_reply(xsurface->hints, reply); + + if (!(xsurface->hints->flags & XCB_ICCCM_WM_HINT_INPUT)) { + // The client didn't specify whether it wants input. + // Assume it does. + xsurface->hints->input = true; + } + } else { + xsurface->hints = NULL; + } + + wl_signal_emit_mutable(&xsurface->events.set_hints, NULL); +} + +static void read_surface_normal_hints(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, + xcb_get_property_reply_t *reply) { + if (reply->type != xwm->atoms[WM_SIZE_HINTS] && reply->type != XCB_ATOM_NONE) { + wlr_log(WLR_DEBUG, "Invalid WM_NORMAL_HINTS property type"); + return; + } + + free(xsurface->size_hints); + xsurface->size_hints = NULL; + + if (xcb_get_property_value_length(reply) == 0) { + return; + } + + xsurface->size_hints = calloc(1, sizeof(*xsurface->size_hints)); + if (xsurface->size_hints == NULL) { + return; + } + xcb_icccm_get_wm_size_hints_from_reply(xsurface->size_hints, reply); + + int32_t flags = xsurface->size_hints->flags; + bool has_min_size_hints = (flags & XCB_ICCCM_SIZE_HINT_P_MIN_SIZE) != 0; + bool has_base_size_hints = (flags & XCB_ICCCM_SIZE_HINT_BASE_SIZE) != 0; + /* ICCCM says that if absent, min size is equal to base size and vice versa */ + if (!has_min_size_hints && !has_base_size_hints) { + xsurface->size_hints->min_width = -1; + xsurface->size_hints->min_height = -1; + xsurface->size_hints->base_width = -1; + xsurface->size_hints->base_height = -1; + } else if (!has_base_size_hints) { + xsurface->size_hints->base_width = xsurface->size_hints->min_width; + xsurface->size_hints->base_height = xsurface->size_hints->min_height; + } else if (!has_min_size_hints) { + xsurface->size_hints->min_width = xsurface->size_hints->base_width; + xsurface->size_hints->min_height = xsurface->size_hints->base_height; + } + + if ((flags & XCB_ICCCM_SIZE_HINT_P_MAX_SIZE) == 0) { + xsurface->size_hints->max_width = -1; + xsurface->size_hints->max_height = -1; + } + + wl_signal_emit_mutable(&xsurface->events.set_size_hints, NULL); +} + +#define MWM_HINTS_FLAGS_FIELD 0 +#define MWM_HINTS_DECORATIONS_FIELD 2 + +#define MWM_HINTS_DECORATIONS (1 << 1) + +#define MWM_DECOR_ALL (1 << 0) +#define MWM_DECOR_BORDER (1 << 1) +#define MWM_DECOR_TITLE (1 << 3) + +static void read_surface_motif_hints(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, + xcb_get_property_reply_t *reply) { + if (xcb_get_property_value_length(reply) == 0) { + xsurface->decorations = 0; + wl_signal_emit_mutable(&xsurface->events.set_decorations, NULL); + return; + } + + const uint32_t *motif_hints = xcb_get_property_value(reply); + int motif_hints_len = xcb_get_property_value_length(reply) / sizeof(motif_hints[0]); + if (motif_hints_len < 5) { + wlr_log(WLR_DEBUG, "Invalid MOTIF_WM_HINTS property type"); + return; + } + + if (motif_hints[MWM_HINTS_FLAGS_FIELD] & MWM_HINTS_DECORATIONS) { + xsurface->decorations = WLR_XWAYLAND_SURFACE_DECORATIONS_ALL; + uint32_t decorations = motif_hints[MWM_HINTS_DECORATIONS_FIELD]; + if ((decorations & MWM_DECOR_ALL) == 0) { + if ((decorations & MWM_DECOR_BORDER) == 0) { + xsurface->decorations |= + WLR_XWAYLAND_SURFACE_DECORATIONS_NO_BORDER; + } + if ((decorations & MWM_DECOR_TITLE) == 0) { + xsurface->decorations |= + WLR_XWAYLAND_SURFACE_DECORATIONS_NO_TITLE; + } + } + wl_signal_emit_mutable(&xsurface->events.set_decorations, NULL); + } +} + +static void read_surface_strut_partial(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, + xcb_get_property_reply_t *reply) { + free(xsurface->strut_partial); + xsurface->strut_partial = NULL; + + if (reply->type == XCB_ATOM_NONE) { + wl_signal_emit_mutable(&xsurface->events.set_strut_partial, NULL); + return; + } + + if (reply->type != XCB_ATOM_CARDINAL || reply->format != 32 || + xcb_get_property_value_length(reply) != + sizeof(xcb_ewmh_wm_strut_partial_t)) { + wlr_log(WLR_DEBUG, "Invalid NET_WM_STRUT_PARTIAL property type"); + return; + } + + xsurface->strut_partial = calloc(1, sizeof(*xsurface->strut_partial)); + if (xsurface->strut_partial == NULL) { + return; + } + xcb_ewmh_get_wm_strut_partial_from_reply(xsurface->strut_partial, reply); + wl_signal_emit_mutable(&xsurface->events.set_strut_partial, NULL); +} + +static void read_surface_net_wm_state(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, + xcb_get_property_reply_t *reply) { + xsurface->fullscreen = 0; + const xcb_atom_t *atoms = xcb_get_property_value(reply); + uint32_t atoms_len = xcb_get_property_value_length(reply) / sizeof(atoms[0]); + for (uint32_t i = 0; i < atoms_len; i++) { + if (atoms[i] == xwm->atoms[NET_WM_STATE_MODAL]) { + xsurface->modal = true; + } else if (atoms[i] == xwm->atoms[NET_WM_STATE_FULLSCREEN]) { + xsurface->fullscreen = true; + } else if (atoms[i] == xwm->atoms[NET_WM_STATE_MAXIMIZED_VERT]) { + xsurface->maximized_vert = true; + } else if (atoms[i] == xwm->atoms[NET_WM_STATE_MAXIMIZED_HORZ]) { + xsurface->maximized_horz = true; + } else if (atoms[i] == xwm->atoms[NET_WM_STATE_HIDDEN]) { + xsurface->minimized = true; + } else if (atoms[i] == xwm->atoms[NET_WM_STATE_STICKY]) { + xsurface->sticky = true; + } else if (atoms[i] == xwm->atoms[NET_WM_STATE_SHADED]) { + xsurface->shaded = true; + } else if (atoms[i] == xwm->atoms[NET_WM_STATE_SKIP_TASKBAR]) { + xsurface->skip_taskbar = true; + } else if (atoms[i] == xwm->atoms[NET_WM_STATE_SKIP_PAGER]) { + xsurface->skip_pager = true; + } else if (atoms[i] == xwm->atoms[NET_WM_STATE_ABOVE]) { + xsurface->above = true; + } else if (atoms[i] == xwm->atoms[NET_WM_STATE_BELOW]) { + xsurface->below = true; + } else if (atoms[i] == xwm->atoms[NET_WM_STATE_DEMANDS_ATTENTION]) { + xsurface->demands_attention = true; + } + } +} + +char *xwm_get_atom_name(struct wlr_xwm *xwm, xcb_atom_t atom) { + xcb_get_atom_name_cookie_t name_cookie = + xcb_get_atom_name(xwm->xcb_conn, atom); + xcb_get_atom_name_reply_t *name_reply = + xcb_get_atom_name_reply(xwm->xcb_conn, name_cookie, NULL); + if (name_reply == NULL) { + return NULL; + } + size_t len = xcb_get_atom_name_name_length(name_reply); + char *buf = xcb_get_atom_name_name(name_reply); // not a C string + char *name = strndup(buf, len); + free(name_reply); + return name; +} + +static void read_surface_property(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, xcb_atom_t property, + xcb_get_property_reply_t *reply) { + if (property == XCB_ATOM_WM_CLASS) { + read_surface_class(xwm, xsurface, reply); + } else if (property == XCB_ATOM_WM_NAME || + property == xwm->atoms[NET_WM_NAME]) { + read_surface_title(xwm, xsurface, property, reply); + } else if (property == XCB_ATOM_WM_TRANSIENT_FOR) { + read_surface_parent(xwm, xsurface, reply); + } else if (property == xwm->atoms[NET_WM_PID]) { + // intentionally ignored + } else if (property == xwm->atoms[NET_WM_WINDOW_TYPE]) { + read_surface_window_type(xwm, xsurface, reply); + } else if (property == xwm->atoms[NET_WM_ICON]) { + wl_signal_emit_mutable(&xsurface->events.set_icon, NULL); + } else if (property == xwm->atoms[WM_PROTOCOLS]) { + read_surface_protocols(xwm, xsurface, reply); + } else if (property == xwm->atoms[NET_WM_STATE]) { + read_surface_net_wm_state(xwm, xsurface, reply); + } else if (property == xwm->atoms[WM_HINTS]) { + read_surface_hints(xwm, xsurface, reply); + } else if (property == xwm->atoms[WM_NORMAL_HINTS]) { + read_surface_normal_hints(xwm, xsurface, reply); + } else if (property == xwm->atoms[MOTIF_WM_HINTS]) { + read_surface_motif_hints(xwm, xsurface, reply); + } else if (property == xwm->atoms[NET_WM_STRUT_PARTIAL]) { + read_surface_strut_partial(xwm, xsurface, reply); + } else if (property == xwm->atoms[WM_WINDOW_ROLE]) { + read_surface_role(xwm, xsurface, reply); + } else if (property == xwm->atoms[NET_STARTUP_ID]) { + read_surface_startup_id(xwm, xsurface, reply); + } else if (property == xwm->atoms[NET_WM_WINDOW_OPACITY]) { + read_surface_opacity(xwm, xsurface, reply); + } else if (wlr_log_get_verbosity() >= WLR_DEBUG) { + char *prop_name = xwm_get_atom_name(xwm, property); + wlr_log(WLR_DEBUG, "unhandled X11 property %" PRIu32 " (%s) for window %" PRIu32, + property, prop_name ? prop_name : "(null)", xsurface->window_id); + free(prop_name); + } +} + +static void xwayland_surface_handle_commit(struct wl_listener *listener, void *data) { + struct wlr_xwayland_surface *xsurface = wl_container_of(listener, xsurface, surface_commit); + if (wlr_surface_has_buffer(xsurface->surface)) { + wlr_surface_map(xsurface->surface); + } +} + +static void xwayland_surface_handle_map(struct wl_listener *listener, void *data) { + struct wlr_xwayland_surface *xsurface = wl_container_of(listener, xsurface, surface_map); + xwm_set_net_client_list(xsurface->xwm); +} + +static void xwayland_surface_handle_unmap(struct wl_listener *listener, void *data) { + struct wlr_xwayland_surface *xsurface = wl_container_of(listener, xsurface, surface_unmap); + xwm_set_net_client_list(xsurface->xwm); +} + +static void xwayland_surface_handle_addon_destroy(struct wlr_addon *addon) { + struct wlr_xwayland_surface *xsurface = wl_container_of(addon, xsurface, surface_addon); + xwayland_surface_dissociate(xsurface); +} + +static const struct wlr_addon_interface surface_addon_impl = { + .name = "wlr_xwayland_surface", + .destroy = xwayland_surface_handle_addon_destroy, +}; + +bool wlr_xwayland_surface_fetch_icon( + const struct wlr_xwayland_surface *xsurface, + xcb_ewmh_get_wm_icon_reply_t *icon_reply) { + struct wlr_xwm *xwm = xsurface->xwm; + + xcb_get_property_cookie_t cookie = xcb_get_property(xwm->xcb_conn, 0, + xsurface->window_id, xwm->atoms[NET_WM_ICON], XCB_ATOM_CARDINAL, + 0, UINT32_MAX); + xcb_get_property_reply_t *reply = + xcb_get_property_reply(xwm->xcb_conn, cookie, NULL); + if (!reply) { + return false; + } + + if (!xcb_ewmh_get_wm_icon_from_reply(icon_reply, reply)) { + free(reply); + return false; + } + + return true; +} + +static xcb_get_property_cookie_t get_property(struct wlr_xwm *xwm, + xcb_window_t window_id, xcb_atom_t atom) { + uint32_t len = 2048; + if (atom == xwm->atoms[NET_WM_ICON]) { + /* Compositors need to fetch icon data wlr_xwayland_surface_fetch_icon() */ + len = 0; + } + return xcb_get_property(xwm->xcb_conn, 0, window_id, atom, XCB_ATOM_ANY, 0, len); +} + +static void xwayland_surface_associate(struct wlr_xwm *xwm, + struct wlr_xwayland_surface *xsurface, struct wlr_surface *surface) { + assert(xsurface->surface == NULL); + + wl_list_remove(&xsurface->unpaired_link); + wl_list_init(&xsurface->unpaired_link); + xsurface->surface_id = 0; + + xsurface->surface = surface; + wlr_addon_init(&xsurface->surface_addon, &surface->addons, NULL, &surface_addon_impl); + + xsurface->surface_commit.notify = xwayland_surface_handle_commit; + wl_signal_add(&surface->events.commit, &xsurface->surface_commit); + + xsurface->surface_map.notify = xwayland_surface_handle_map; + wl_signal_add(&surface->events.map, &xsurface->surface_map); + + xsurface->surface_unmap.notify = xwayland_surface_handle_unmap; + wl_signal_add(&surface->events.unmap, &xsurface->surface_unmap); + + // read all surface properties + const xcb_atom_t props[] = { + XCB_ATOM_WM_CLASS, + XCB_ATOM_WM_NAME, + XCB_ATOM_WM_TRANSIENT_FOR, + xwm->atoms[WM_PROTOCOLS], + xwm->atoms[WM_HINTS], + xwm->atoms[WM_NORMAL_HINTS], + xwm->atoms[MOTIF_WM_HINTS], + xwm->atoms[NET_STARTUP_ID], + xwm->atoms[NET_WM_STATE], + xwm->atoms[NET_WM_STRUT_PARTIAL], + xwm->atoms[NET_WM_WINDOW_TYPE], + xwm->atoms[NET_WM_NAME], + xwm->atoms[NET_WM_ICON], + }; + + xcb_get_property_cookie_t cookies[sizeof(props) / sizeof(props[0])] = {0}; + for (size_t i = 0; i < sizeof(props) / sizeof(props[0]); i++) { + cookies[i] = get_property(xwm, xsurface->window_id, props[i]); + } + + for (size_t i = 0; i < sizeof(props) / sizeof(props[0]); i++) { + xcb_get_property_reply_t *reply = + xcb_get_property_reply(xwm->xcb_conn, cookies[i], NULL); + if (reply == NULL) { + wlr_log(WLR_ERROR, "Failed to get window property"); + continue; + } + read_surface_property(xwm, xsurface, props[i], reply); + free(reply); + } + + wl_signal_emit_mutable(&xsurface->events.associate, NULL); +} + +static void xwm_handle_create_notify(struct wlr_xwm *xwm, + xcb_create_notify_event_t *ev) { + if (ev->window == xwm->window || + ev->window == xwm->primary_selection.window || + ev->window == xwm->clipboard_selection.window || + ev->window == xwm->dnd_selection.window) { + return; + } + + xwayland_surface_create(xwm, ev->window, ev->x, ev->y, + ev->width, ev->height, ev->override_redirect); +} + +static void xwm_handle_destroy_notify(struct wlr_xwm *xwm, + xcb_destroy_notify_event_t *ev) { + struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window); + if (xsurface == NULL) { + return; + } + xwayland_surface_destroy(xsurface); + xwm_handle_selection_destroy_notify(xwm, ev); +} + +static void xwm_handle_configure_request(struct wlr_xwm *xwm, + xcb_configure_request_event_t *ev) { + struct wlr_xwayland_surface *surface = lookup_surface(xwm, ev->window); + if (surface == NULL) { + return; + } + + // TODO: handle ev->{parent,sibling}? + + uint16_t mask = ev->value_mask; + uint16_t geo_mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y | + XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT; + if ((mask & geo_mask) == 0) { + return; + } + + struct wlr_xwayland_surface_configure_event wlr_event = { + .surface = surface, + .x = mask & XCB_CONFIG_WINDOW_X ? ev->x : surface->x, + .y = mask & XCB_CONFIG_WINDOW_Y ? ev->y : surface->y, + .width = mask & XCB_CONFIG_WINDOW_WIDTH ? ev->width : surface->width, + .height = mask & XCB_CONFIG_WINDOW_HEIGHT ? ev->height : surface->height, + .mask = mask, + }; + + wl_signal_emit_mutable(&surface->events.request_configure, &wlr_event); +} + +static void xwm_update_override_redirect(struct wlr_xwayland_surface *xsurface, + bool override_redirect) { + if (xsurface->override_redirect == override_redirect) { + return; + } + xsurface->override_redirect = override_redirect; + + if (override_redirect) { + wl_list_remove(&xsurface->stack_link); + wl_list_init(&xsurface->stack_link); + xwm_set_net_client_list_stacking(xsurface->xwm); + } else if (xsurface->surface != NULL && xsurface->surface->mapped) { + wlr_xwayland_surface_restack(xsurface, NULL, XCB_STACK_MODE_BELOW); + } + + wl_signal_emit_mutable(&xsurface->events.set_override_redirect, NULL); +} + +static void xwm_handle_configure_notify(struct wlr_xwm *xwm, + xcb_configure_notify_event_t *ev) { + struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window); + if (!xsurface) { + return; + } + + bool geometry_changed = + (xsurface->x != ev->x || xsurface->y != ev->y || + xsurface->width != ev->width || xsurface->height != ev->height); + + if (geometry_changed) { + xsurface->x = ev->x; + xsurface->y = ev->y; + xsurface->width = ev->width; + xsurface->height = ev->height; + } + + xwm_update_override_redirect(xsurface, ev->override_redirect); + + if (geometry_changed) { + wl_signal_emit_mutable(&xsurface->events.set_geometry, NULL); + } +} + +static void xwm_handle_shape_notify(struct wlr_xwm *xwm, + xcb_shape_notify_event_t *ev) { + struct wlr_xwayland_surface *xsurface = + lookup_surface(xwm, ev->affected_window); + if (xsurface == NULL) { + return; + } + + xwm_update_surface_shape(xwm, xsurface, ev->shape_kind); +} + +static void xsurface_set_wm_state(struct wlr_xwayland_surface *xsurface) { + struct wlr_xwm *xwm = xsurface->xwm; + uint32_t property[] = { XCB_ICCCM_WM_STATE_NORMAL, XCB_WINDOW_NONE }; + + if (xsurface->withdrawn) { + property[0] = XCB_ICCCM_WM_STATE_WITHDRAWN; + } else if (xsurface->minimized) { + property[0] = XCB_ICCCM_WM_STATE_ICONIC; + } else { + property[0] = XCB_ICCCM_WM_STATE_NORMAL; + } + + xcb_change_property(xwm->xcb_conn, + XCB_PROP_MODE_REPLACE, + xsurface->window_id, + xwm->atoms[WM_STATE], + xwm->atoms[WM_STATE], + 32, // format + sizeof(property) / sizeof(property[0]), property); +} + +void wlr_xwayland_surface_restack(struct wlr_xwayland_surface *xsurface, + struct wlr_xwayland_surface *sibling, enum xcb_stack_mode_t mode) { + struct wlr_xwm *xwm = xsurface->xwm; + uint32_t values[2]; + size_t idx = 0; + uint32_t flags = XCB_CONFIG_WINDOW_STACK_MODE; + + assert(!xsurface->override_redirect); + + // X11 clients expect their override_redirect windows to stay on top. + // Avoid interfering by restacking above the topmost managed surface. + if (mode == XCB_STACK_MODE_ABOVE && !sibling) { + sibling = wl_container_of(xwm->surfaces_in_stack_order.prev, sibling, stack_link); + } + + if (sibling == xsurface) { + return; + } + + if (sibling != NULL) { + values[idx++] = sibling->window_id; + flags |= XCB_CONFIG_WINDOW_SIBLING; + } + values[idx++] = mode; + + xcb_configure_window(xwm->xcb_conn, xsurface->window_id, flags, values); + + wl_list_remove(&xsurface->stack_link); + + struct wl_list *node; + if (mode == XCB_STACK_MODE_ABOVE) { + node = &sibling->stack_link; + } else if (mode == XCB_STACK_MODE_BELOW) { + if (sibling) { + node = sibling->stack_link.prev; + } else { + node = &xwm->surfaces_in_stack_order; + } + } else { + // Not implementing XCB_STACK_MODE_TOP_IF | XCB_STACK_MODE_BOTTOM_IF | + // XCB_STACK_MODE_OPPOSITE. + abort(); + } + + wl_list_insert(node, &xsurface->stack_link); + xwm_set_net_client_list_stacking(xwm); + xwm_schedule_flush(xwm); +} + +static void xwm_handle_map_request(struct wlr_xwm *xwm, + xcb_map_request_event_t *ev) { + struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window); + if (!xsurface) { + return; + } + + wl_signal_emit_mutable(&xsurface->events.map_request, NULL); + xcb_map_window(xwm->xcb_conn, ev->window); +} + +static void xwm_handle_map_notify(struct wlr_xwm *xwm, + xcb_map_notify_event_t *ev) { + struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window); + if (!xsurface) { + return; + } + + xwm_update_override_redirect(xsurface, ev->override_redirect); + + if (!xsurface->override_redirect) { + wlr_xwayland_surface_set_withdrawn(xsurface, false); + wlr_xwayland_surface_restack(xsurface, NULL, XCB_STACK_MODE_BELOW); + } +} + +static void xwm_handle_unmap_notify(struct wlr_xwm *xwm, + xcb_unmap_notify_event_t *ev) { + struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window); + if (xsurface == NULL) { + return; + } + + xwayland_surface_dissociate(xsurface); + + if (!xsurface->override_redirect) { + wlr_xwayland_surface_set_withdrawn(xsurface, true); + } +} + +static void xwm_handle_property_notify(struct wlr_xwm *xwm, + xcb_property_notify_event_t *ev) { + struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window); + if (xsurface == NULL) { + return; + } + + xcb_get_property_cookie_t cookie = get_property(xwm, xsurface->window_id, ev->atom); + xcb_get_property_reply_t *reply = + xcb_get_property_reply(xwm->xcb_conn, cookie, NULL); + if (reply == NULL) { + wlr_log(WLR_ERROR, "Failed to get window property"); + return; + } + + read_surface_property(xwm, xsurface, ev->atom, reply); + free(reply); +} + +static void xwm_handle_surface_id_message(struct wlr_xwm *xwm, + xcb_client_message_event_t *ev) { + struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window); + if (xsurface == NULL) { + wlr_log(WLR_DEBUG, + "Received client message WL_SURFACE_ID but no X11 window %u", + ev->window); + return; + } + if (xsurface->surface != NULL) { + wlr_log(WLR_DEBUG, "Received multiple client messages WL_SURFACE_ID " + "for an already-associated X11 window %u", ev->window); + return; + } + + uint32_t id = ev->data.data32[0]; + + // Because the X11 and Wayland connections are separate sockets, the + // WL_SURFACE_ID and wl_compositor.create_surface messages may be received + // in any order. + struct wl_resource *resource = + wl_client_get_object(xwm->xwayland->server->client, id); + if (resource) { + if (wl_resource_get_interface(resource) != &wl_surface_interface) { + wlr_log(WLR_DEBUG, "Received client message WL_SURFACE_ID " + "for X11 window %u but Wayland object is not a wl_surface", + ev->window); + return; + } + + struct wlr_surface *surface = wlr_surface_from_resource(resource); + xwayland_surface_associate(xwm, xsurface, surface); + } else { + xsurface->surface_id = id; + wl_list_remove(&xsurface->unpaired_link); + wl_list_insert(&xwm->unpaired_surfaces, &xsurface->unpaired_link); + } +} + +static void xwm_handle_surface_serial_message(struct wlr_xwm *xwm, + xcb_client_message_event_t *ev) { + struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window); + if (xsurface == NULL) { + wlr_log(WLR_DEBUG, + "Received client message WL_SURFACE_SERIAL but no X11 window %u", + ev->window); + return; + } + if (xsurface->serial != 0) { + wlr_log(WLR_DEBUG, "Received multiple client messages WL_SURFACE_SERIAL " + "for the same X11 window %u", ev->window); + return; + } + + uint32_t serial_lo = ev->data.data32[0]; + uint32_t serial_hi = ev->data.data32[1]; + xsurface->serial = ((uint64_t)serial_hi << 32) | serial_lo; + + struct wlr_surface *surface = wlr_xwayland_shell_v1_surface_from_serial( + xwm->xwayland->shell_v1, xsurface->serial); + if (surface != NULL) { + xwayland_surface_associate(xwm, xsurface, surface); + } else { + wl_list_remove(&xsurface->unpaired_link); + wl_list_insert(&xwm->unpaired_surfaces, &xsurface->unpaired_link); + } +} + +#define _NET_WM_MOVERESIZE_SIZE_TOPLEFT 0 +#define _NET_WM_MOVERESIZE_SIZE_TOP 1 +#define _NET_WM_MOVERESIZE_SIZE_TOPRIGHT 2 +#define _NET_WM_MOVERESIZE_SIZE_RIGHT 3 +#define _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT 4 +#define _NET_WM_MOVERESIZE_SIZE_BOTTOM 5 +#define _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT 6 +#define _NET_WM_MOVERESIZE_SIZE_LEFT 7 +#define _NET_WM_MOVERESIZE_MOVE 8 // movement only +#define _NET_WM_MOVERESIZE_SIZE_KEYBOARD 9 // size via keyboard +#define _NET_WM_MOVERESIZE_MOVE_KEYBOARD 10 // move via keyboard +#define _NET_WM_MOVERESIZE_CANCEL 11 // cancel operation + +static enum wlr_edges net_wm_edges_to_wlr(uint32_t net_wm_edges) { + switch(net_wm_edges) { + case _NET_WM_MOVERESIZE_SIZE_TOPLEFT: + return WLR_EDGE_TOP | WLR_EDGE_LEFT; + case _NET_WM_MOVERESIZE_SIZE_TOP: + return WLR_EDGE_TOP; + case _NET_WM_MOVERESIZE_SIZE_TOPRIGHT: + return WLR_EDGE_TOP | WLR_EDGE_RIGHT; + case _NET_WM_MOVERESIZE_SIZE_RIGHT: + return WLR_EDGE_RIGHT; + case _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT: + return WLR_EDGE_BOTTOM | WLR_EDGE_RIGHT; + case _NET_WM_MOVERESIZE_SIZE_BOTTOM: + return WLR_EDGE_BOTTOM; + case _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT: + return WLR_EDGE_BOTTOM | WLR_EDGE_LEFT; + case _NET_WM_MOVERESIZE_SIZE_LEFT: + return WLR_EDGE_LEFT; + default: + return WLR_EDGE_NONE; + } +} + +static void xwm_handle_net_wm_moveresize_message(struct wlr_xwm *xwm, + xcb_client_message_event_t *ev) { + struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window); + if (!xsurface) { + return; + } + + int detail = ev->data.data32[2]; + switch (detail) { + case _NET_WM_MOVERESIZE_MOVE: + wl_signal_emit_mutable(&xsurface->events.request_move, NULL); + break; + case _NET_WM_MOVERESIZE_SIZE_TOPLEFT: + case _NET_WM_MOVERESIZE_SIZE_TOP: + case _NET_WM_MOVERESIZE_SIZE_TOPRIGHT: + case _NET_WM_MOVERESIZE_SIZE_RIGHT: + case _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT: + case _NET_WM_MOVERESIZE_SIZE_BOTTOM: + case _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT: + case _NET_WM_MOVERESIZE_SIZE_LEFT:; + struct wlr_xwayland_resize_event resize_event = { + .surface = xsurface, + .edges = net_wm_edges_to_wlr(detail), + }; + wl_signal_emit_mutable(&xsurface->events.request_resize, &resize_event); + break; + case _NET_WM_MOVERESIZE_CANCEL: + // handled by the compositor + break; + } +} + +#define _NET_WM_STATE_REMOVE 0 +#define _NET_WM_STATE_ADD 1 +#define _NET_WM_STATE_TOGGLE 2 + +static bool update_state(int action, bool *state) { + int new_state, changed; + + switch (action) { + case _NET_WM_STATE_REMOVE: + new_state = false; + break; + case _NET_WM_STATE_ADD: + new_state = true; + break; + case _NET_WM_STATE_TOGGLE: + new_state = !*state; + break; + default: + return false; + } + + changed = (*state != new_state); + *state = new_state; + + return changed; +} + +static void xwm_handle_net_wm_state_message(struct wlr_xwm *xwm, + xcb_client_message_event_t *client_message) { + struct wlr_xwayland_surface *xsurface = + lookup_surface(xwm, client_message->window); + if (!xsurface) { + return; + } + if (client_message->format != 32) { + return; + } + + bool fullscreen = xsurface->fullscreen; + bool maximized_vert = xsurface->maximized_vert; + bool maximized_horz = xsurface->maximized_horz; + bool minimized = xsurface->minimized; + bool sticky = xsurface->sticky; + bool shaded = xsurface->shaded; + bool skip_taskbar = xsurface->skip_taskbar; + bool skip_pager = xsurface->skip_pager; + bool above = xsurface->above; + bool below = xsurface->below; + bool demands_attention = xsurface->demands_attention; + + uint32_t action = client_message->data.data32[0]; + for (size_t i = 0; i < 2; ++i) { + xcb_atom_t property = client_message->data.data32[1 + i]; + + bool changed = false; + if (property == xwm->atoms[NET_WM_STATE_MODAL]) { + changed = update_state(action, &xsurface->modal); + } else if (property == xwm->atoms[NET_WM_STATE_FULLSCREEN]) { + changed = update_state(action, &xsurface->fullscreen); + } else if (property == xwm->atoms[NET_WM_STATE_MAXIMIZED_VERT]) { + changed = update_state(action, &xsurface->maximized_vert); + } else if (property == xwm->atoms[NET_WM_STATE_MAXIMIZED_HORZ]) { + changed = update_state(action, &xsurface->maximized_horz); + } else if (property == xwm->atoms[NET_WM_STATE_HIDDEN]) { + changed = update_state(action, &xsurface->minimized); + } else if (property == xwm->atoms[NET_WM_STATE_STICKY]) { + changed = update_state(action, &xsurface->sticky); + } else if (property == xwm->atoms[NET_WM_STATE_SHADED]) { + changed = update_state(action, &xsurface->shaded); + } else if (property == xwm->atoms[NET_WM_STATE_SKIP_TASKBAR]) { + changed = update_state(action, &xsurface->skip_taskbar); + } else if (property == xwm->atoms[NET_WM_STATE_SKIP_PAGER]) { + changed = update_state(action, &xsurface->skip_pager); + } else if (property == xwm->atoms[NET_WM_STATE_ABOVE]) { + changed = update_state(action, &xsurface->above); + } else if (property == xwm->atoms[NET_WM_STATE_BELOW]) { + changed = update_state(action, &xsurface->below); + } else if (property == xwm->atoms[NET_WM_STATE_DEMANDS_ATTENTION]) { + changed = update_state(action, &xsurface->demands_attention); + } else if (property != XCB_ATOM_NONE && wlr_log_get_verbosity() >= WLR_DEBUG) { + char *prop_name = xwm_get_atom_name(xwm, property); + wlr_log(WLR_DEBUG, "Unhandled NET_WM_STATE property change " + "%"PRIu32" (%s)", property, prop_name ? prop_name : "(null)"); + free(prop_name); + } + + if (changed) { + xsurface_set_net_wm_state(xsurface); + } + } + // client_message->data.data32[3] is the source indication + // all other values are set to 0 + + if (fullscreen != xsurface->fullscreen) { + wl_signal_emit_mutable(&xsurface->events.request_fullscreen, NULL); + } + + if (maximized_vert != xsurface->maximized_vert + || maximized_horz != xsurface->maximized_horz) { + wl_signal_emit_mutable(&xsurface->events.request_maximize, NULL); + } + + if (minimized != xsurface->minimized) { + struct wlr_xwayland_minimize_event minimize_event = { + .surface = xsurface, + .minimize = xsurface->minimized, + }; + wl_signal_emit_mutable(&xsurface->events.request_minimize, &minimize_event); + } + + if (sticky != xsurface->sticky) { + wl_signal_emit_mutable(&xsurface->events.request_sticky, NULL); + } + + if (shaded != xsurface->shaded) { + wl_signal_emit_mutable(&xsurface->events.request_shaded, NULL); + } + + if (skip_taskbar != xsurface->skip_taskbar) { + wl_signal_emit_mutable(&xsurface->events.request_skip_taskbar, NULL); + } + + if (skip_pager != xsurface->skip_pager) { + wl_signal_emit_mutable(&xsurface->events.request_skip_pager, NULL); + } + + if (above != xsurface->above) { + wl_signal_emit_mutable(&xsurface->events.request_above, NULL); + } + + if (below != xsurface->below) { + wl_signal_emit_mutable(&xsurface->events.request_below, NULL); + } + + if (demands_attention != xsurface->demands_attention) { + wl_signal_emit_mutable(&xsurface->events.request_demands_attention, NULL); + } +} + +static void xwm_handle_wm_protocols_message(struct wlr_xwm *xwm, + xcb_client_message_event_t *ev) { + xcb_atom_t type = ev->data.data32[0]; + + if (type == xwm->atoms[NET_WM_PING]) { + xcb_window_t window_id = ev->data.data32[2]; + + struct wlr_xwayland_surface *surface = lookup_surface(xwm, window_id); + if (surface == NULL) { + return; + } + + if (!surface->pinging) { + return; + } + + wl_event_source_timer_update(surface->ping_timer, 0); + surface->pinging = false; + } else if (wlr_log_get_verbosity() >= WLR_DEBUG) { + char *type_name = xwm_get_atom_name(xwm, type); + wlr_log(WLR_DEBUG, "unhandled WM_PROTOCOLS client message %" PRIu32 " (%s)", + type, type_name ? type_name : "(null)"); + free(type_name); + } +} + +static void xwm_handle_net_active_window_message(struct wlr_xwm *xwm, + xcb_client_message_event_t *ev) { + struct wlr_xwayland_surface *surface = lookup_surface(xwm, ev->window); + if (surface == NULL) { + return; + } + wl_signal_emit_mutable(&surface->events.request_activate, NULL); +} + +static void xwm_handle_net_close_window_message(struct wlr_xwm *xwm, + xcb_client_message_event_t *ev) { + struct wlr_xwayland_surface *surface = lookup_surface(xwm, ev->window); + if (surface == NULL) { + return; + } + wl_signal_emit_mutable(&surface->events.request_close, NULL); +} + +static void pending_startup_id_destroy(struct pending_startup_id *pending) { + wl_list_remove(&pending->link); + free(pending->msg); + free(pending); +} + +static void xwm_handle_net_startup_info_message(struct wlr_xwm *xwm, + xcb_client_message_event_t *ev) { + struct pending_startup_id *pending, *curr = NULL; + wl_list_for_each(pending, &xwm->pending_startup_ids, link) { + if (pending->window == ev->window) { + curr = pending; + break; + } + } + + char *start; + size_t buf_len = sizeof(ev->data); + if (curr) { + char *msg = realloc(curr->msg, curr->len + buf_len); + if (!msg) { + pending_startup_id_destroy(curr); + return; + } + curr->msg = msg; + start = curr->msg + curr->len; + curr->len += buf_len; + } else { + curr = calloc(1, sizeof(*curr)); + if (!curr) + return; + curr->window = ev->window; + curr->msg = malloc(buf_len); + if (!curr->msg) { + free(curr); + return; + } + start = curr->msg; + curr->len = buf_len; + wl_list_insert(&xwm->pending_startup_ids, &curr->link); + } + + char *id = NULL; + const char *data = (const char *)ev->data.data8; + for (size_t i = 0; i < buf_len; i++) { + start[i] = data[i]; + if (start[i] == '\0') { + if (strncmp(curr->msg, STARTUP_INFO_REMOVE_PREFIX, + strlen(STARTUP_INFO_REMOVE_PREFIX)) == 0 && + strlen(curr->msg) > strlen(STARTUP_INFO_REMOVE_PREFIX)) { + id = curr->msg + strlen(STARTUP_INFO_REMOVE_PREFIX); + break; + } else { + wlr_log(WLR_ERROR, "Unhandled message '%s'\n", curr->msg); + pending_startup_id_destroy(curr); + return; + } + } + } + + if (id) { + struct wlr_xwayland_remove_startup_info_event data = { id, ev->window }; + wlr_log(WLR_DEBUG, "Got startup id: %s", id); + wl_signal_emit_mutable(&xwm->xwayland->events.remove_startup_info, &data); + pending_startup_id_destroy(curr); + } +} + +static void xwm_handle_wm_change_state_message(struct wlr_xwm *xwm, + xcb_client_message_event_t *ev) { + struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->window); + uint32_t detail = ev->data.data32[0]; + + if (xsurface == NULL) { + return; + } + + bool minimize; + if (detail == XCB_ICCCM_WM_STATE_ICONIC) { + minimize = true; + } else if (detail == XCB_ICCCM_WM_STATE_NORMAL) { + minimize = false; + } else { + wlr_log(WLR_DEBUG, "unhandled wm_change_state event %u", detail); + return; + } + + struct wlr_xwayland_minimize_event minimize_event = { + .surface = xsurface, + .minimize = minimize, + }; + wl_signal_emit_mutable(&xsurface->events.request_minimize, &minimize_event); +} + +static void xwm_handle_client_message(struct wlr_xwm *xwm, + xcb_client_message_event_t *ev) { + if (ev->type == xwm->atoms[WL_SURFACE_ID]) { + xwm_handle_surface_id_message(xwm, ev); + } else if (ev->type == xwm->atoms[WL_SURFACE_SERIAL]) { + xwm_handle_surface_serial_message(xwm, ev); + } else if (ev->type == xwm->atoms[NET_WM_STATE]) { + xwm_handle_net_wm_state_message(xwm, ev); + } else if (ev->type == xwm->atoms[NET_WM_MOVERESIZE]) { + xwm_handle_net_wm_moveresize_message(xwm, ev); + } else if (ev->type == xwm->atoms[WM_PROTOCOLS]) { + xwm_handle_wm_protocols_message(xwm, ev); + } else if (ev->type == xwm->atoms[NET_ACTIVE_WINDOW]) { + xwm_handle_net_active_window_message(xwm, ev); + } else if (ev->type == xwm->atoms[NET_CLOSE_WINDOW]) { + xwm_handle_net_close_window_message(xwm, ev); + } else if (ev->type == xwm->atoms[NET_STARTUP_INFO] || + ev->type == xwm->atoms[NET_STARTUP_INFO_BEGIN]) { + xwm_handle_net_startup_info_message(xwm, ev); + } else if (ev->type == xwm->atoms[WM_CHANGE_STATE]) { + xwm_handle_wm_change_state_message(xwm, ev); + } else if (!xwm_handle_selection_client_message(xwm, ev) && + wlr_log_get_verbosity() >= WLR_DEBUG) { + char *type_name = xwm_get_atom_name(xwm, ev->type); + wlr_log(WLR_DEBUG, "unhandled x11 client message %" PRIu32 " (%s)", ev->type, + type_name ? type_name : "(null)"); + free(type_name); + } +} + +static bool validate_focus_serial(uint16_t last_focus_seq, uint16_t event_seq) { + uint16_t rev_dist = event_seq - last_focus_seq; + if (rev_dist >= UINT16_MAX / 2) { + // Probably overflow or too old + return false; + } + + return true; +} + +static void xwm_handle_focus_in(struct wlr_xwm *xwm, + xcb_focus_in_event_t *ev) { + // Ignore pointer focus change events + if (ev->detail == XCB_NOTIFY_DETAIL_POINTER) { + return; + } + + // Do not interfere with keyboard grabs, but notify the + // compositor. Note that many legitimate X11 applications use + // keyboard grabs to "steal" focus for e.g. popup menus. + struct wlr_xwayland_surface *xsurface = lookup_surface(xwm, ev->event); + if (ev->mode == XCB_NOTIFY_MODE_GRAB) { + if (xsurface) { + wl_signal_emit_mutable(&xsurface->events.grab_focus, NULL); + } + return; + } + if (ev->mode == XCB_NOTIFY_MODE_UNGRAB) { + /* Do we need an ungrab_focus event? */ + return; + } + + // Ignore any out-of-date FocusIn event (older than the last + // known WM-initiated focus change) to avoid race conditions. + // https://github.com/swaywm/wlroots/issues/2324 + if (!validate_focus_serial(xwm->last_focus_seq, ev->sequence)) { + return; + } + + if (xsurface == NULL || xsurface->surface == NULL) { + return; + } + + // Allow focus changes between surfaces belonging to the same + // application. Steam for example relies on this: + // https://github.com/swaywm/sway/issues/1865 + bool same_pid = ((xwm->focus_surface && xsurface->pid == xwm->focus_surface->pid) || + (xwm->offered_focus && xsurface->pid == xwm->offered_focus->pid)); + bool related_to_focused_window = xwm->focus_surface && + (ev->detail == XCB_NOTIFY_DETAIL_ANCESTOR || + ev->detail == XCB_NOTIFY_DETAIL_INFERIOR); + if (same_pid || related_to_focused_window) { + xwm_set_focused_window(xwm, xsurface); + wl_signal_emit_mutable(&xsurface->events.focus_in, NULL); + } else { + // Try to prevent clients from changing focus between + // applications, by refocusing the previous surface. + xwm_focus_window(xwm, xwm->focus_surface); + } +} + +static void xwm_handle_xcb_error(struct wlr_xwm *xwm, xcb_value_error_t *ev) { +#if HAVE_XCB_ERRORS + const char *major_name = + xcb_errors_get_name_for_major_code(xwm->errors_context, + ev->major_opcode); + if (!major_name) { + wlr_log(WLR_DEBUG, "xcb error happened, but could not get major name"); + goto log_raw; + } + + const char *minor_name = + xcb_errors_get_name_for_minor_code(xwm->errors_context, + ev->major_opcode, ev->minor_opcode); + + const char *extension; + const char *error_name = + xcb_errors_get_name_for_error(xwm->errors_context, + ev->error_code, &extension); + if (!error_name) { + wlr_log(WLR_DEBUG, "xcb error happened, but could not get error name"); + goto log_raw; + } + + wlr_log(WLR_ERROR, "xcb error: op %s (%s), code %s (%s), sequence %"PRIu16", value %"PRIu32, + major_name, minor_name ? minor_name : "no minor", + error_name, extension ? extension : "no extension", + ev->sequence, ev->bad_value); + + return; +log_raw: +#endif + wlr_log(WLR_ERROR, + "xcb error: op %"PRIu8":%"PRIu16", code %"PRIu8", sequence %"PRIu16", value %"PRIu32, + ev->major_opcode, ev->minor_opcode, ev->error_code, + ev->sequence, ev->bad_value); + +} + +static void xwm_handle_unhandled_event(struct wlr_xwm *xwm, xcb_generic_event_t *ev) { +#if HAVE_XCB_ERRORS + const char *extension; + const char *event_name = + xcb_errors_get_name_for_xcb_event(xwm->errors_context, + ev, &extension); + if (!event_name) { + wlr_log(WLR_DEBUG, "no name for unhandled event: %u", + ev->response_type); + return; + } + + wlr_log(WLR_DEBUG, "unhandled X11 event: %s (%u)", event_name, ev->response_type); +#else + wlr_log(WLR_DEBUG, "unhandled X11 event: %u", ev->response_type); +#endif +} + +static int read_x11_events(struct wlr_xwm *xwm) { + int count = 0; + + xcb_generic_event_t *event; + while ((event = xcb_poll_for_event(xwm->xcb_conn))) { + count++; + + if (xwm->xwayland->user_event_handler && + xwm->xwayland->user_event_handler(xwm->xwayland, event)) { + free(event); + continue; + } + + if (xwm_handle_selection_event(xwm, event)) { + free(event); + continue; + } + + if (xwm->shape != NULL && xwm->shape->present && + (event->response_type & XCB_EVENT_RESPONSE_TYPE_MASK) == + xwm->shape->first_event + XCB_SHAPE_NOTIFY) { + xwm_handle_shape_notify(xwm, (xcb_shape_notify_event_t *)event); + free(event); + continue; + } + + switch (event->response_type & XCB_EVENT_RESPONSE_TYPE_MASK) { + case XCB_CREATE_NOTIFY: + xwm_handle_create_notify(xwm, (xcb_create_notify_event_t *)event); + break; + case XCB_DESTROY_NOTIFY: + xwm_handle_destroy_notify(xwm, (xcb_destroy_notify_event_t *)event); + break; + case XCB_CONFIGURE_REQUEST: + xwm_handle_configure_request(xwm, + (xcb_configure_request_event_t *)event); + break; + case XCB_CONFIGURE_NOTIFY: + xwm_handle_configure_notify(xwm, + (xcb_configure_notify_event_t *)event); + break; + case XCB_MAP_REQUEST: + xwm_handle_map_request(xwm, (xcb_map_request_event_t *)event); + break; + case XCB_MAP_NOTIFY: + xwm_handle_map_notify(xwm, (xcb_map_notify_event_t *)event); + break; + case XCB_UNMAP_NOTIFY: + xwm_handle_unmap_notify(xwm, (xcb_unmap_notify_event_t *)event); + break; + case XCB_PROPERTY_NOTIFY: + xwm_handle_property_notify(xwm, + (xcb_property_notify_event_t *)event); + break; + case XCB_CLIENT_MESSAGE: + xwm_handle_client_message(xwm, (xcb_client_message_event_t *)event); + break; + case XCB_FOCUS_IN: + xwm_handle_focus_in(xwm, (xcb_focus_in_event_t *)event); + break; + case 0: + xwm_handle_xcb_error(xwm, (xcb_value_error_t *)event); + break; + default: + xwm_handle_unhandled_event(xwm, event); + break; + } + free(event); + } + + return count; +} + +static int x11_event_handler(int fd, uint32_t mask, void *data) { + struct wlr_xwm *xwm = data; + + if ((mask & WL_EVENT_HANGUP) || (mask & WL_EVENT_ERROR)) { + xwm_destroy(xwm); + return 0; + } + + int count = 0; + if (mask & WL_EVENT_READABLE) { + count = read_x11_events(xwm); + if (count) { + xwm_schedule_flush(xwm); + } + } + + if (mask & WL_EVENT_WRITABLE) { + // xcb_flush() always blocks until it's written all pending requests, + // but it's the only thing we have + xcb_flush(xwm->xcb_conn); + wl_event_source_fd_update(xwm->event_source, WL_EVENT_READABLE); + } + + return count; +} + +static void handle_compositor_new_surface(struct wl_listener *listener, + void *data) { + struct wlr_xwm *xwm = + wl_container_of(listener, xwm, compositor_new_surface); + struct wlr_surface *surface = data; + + struct wl_client *client = wl_resource_get_client(surface->resource); + if (client != xwm->xwayland->server->client) { + return; + } + + wlr_log(WLR_DEBUG, "New xwayland surface: %p", surface); + + uint32_t surface_id = wl_resource_get_id(surface->resource); + struct wlr_xwayland_surface *xsurface; + wl_list_for_each(xsurface, &xwm->unpaired_surfaces, unpaired_link) { + if (xsurface->surface_id == surface_id) { + xwayland_surface_associate(xwm, xsurface, surface); + xwm_schedule_flush(xwm); + return; + } + } +} + +static void handle_compositor_destroy(struct wl_listener *listener, + void *data) { + struct wlr_xwm *xwm = + wl_container_of(listener, xwm, compositor_destroy); + wl_list_remove(&xwm->compositor_new_surface.link); + wl_list_remove(&xwm->compositor_destroy.link); + wl_list_init(&xwm->compositor_new_surface.link); + wl_list_init(&xwm->compositor_destroy.link); +} + +static void handle_shell_v1_new_surface(struct wl_listener *listener, + void *data) { + struct wlr_xwm *xwm = wl_container_of(listener, xwm, shell_v1_new_surface); + struct wlr_xwayland_surface_v1 *shell_surface = data; + + struct wlr_xwayland_surface *xsurface; + wl_list_for_each(xsurface, &xwm->unpaired_surfaces, unpaired_link) { + if (xsurface->serial == shell_surface->serial) { + xwayland_surface_associate(xwm, xsurface, shell_surface->surface); + return; + } + } +} + +static void handle_shell_v1_destroy(struct wl_listener *listener, + void *data) { + struct wlr_xwm *xwm = + wl_container_of(listener, xwm, shell_v1_destroy); + wl_list_remove(&xwm->shell_v1_new_surface.link); + wl_list_remove(&xwm->shell_v1_destroy.link); + wl_list_init(&xwm->shell_v1_new_surface.link); + wl_list_init(&xwm->shell_v1_destroy.link); +} + +void wlr_xwayland_surface_activate(struct wlr_xwayland_surface *xsurface, + bool activated) { + struct wlr_xwayland_surface *focused = xsurface->xwm->focus_surface; + if (activated) { + xwm_surface_activate(xsurface->xwm, xsurface); + } else if (focused == xsurface) { + xwm_surface_activate(xsurface->xwm, NULL); + } +} + +void wlr_xwayland_surface_configure(struct wlr_xwayland_surface *xsurface, + int16_t x, int16_t y, uint16_t width, uint16_t height) { + int old_w = xsurface->width; + int old_h = xsurface->height; + + xsurface->x = x; + xsurface->y = y; + xsurface->width = width; + xsurface->height = height; + + struct wlr_xwm *xwm = xsurface->xwm; + uint32_t mask = XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y | + XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT | + XCB_CONFIG_WINDOW_BORDER_WIDTH; + uint32_t values[] = {x, y, width, height, 0}; + xcb_configure_window(xwm->xcb_conn, xsurface->window_id, mask, values); + + // If the window size did not change, then we cannot rely on + // the X server to generate a ConfigureNotify event. Instead, + // we are supposed to send a synthetic event. See ICCCM part + // 4.1.5. But we ignore override-redirect windows as ICCCM does + // not apply to them. + if (width == old_w && height == old_h && !xsurface->override_redirect) { + xcb_configure_notify_event_t configure_notify = { + .response_type = XCB_CONFIGURE_NOTIFY, + .event = xsurface->window_id, + .window = xsurface->window_id, + .x = x, + .y = y, + .width = width, + .height = height, + }; + + xwm_send_event_with_size(xwm->xcb_conn, 0, xsurface->window_id, + XCB_EVENT_MASK_STRUCTURE_NOTIFY, + &configure_notify, + sizeof(configure_notify)); + } + + xwm_schedule_flush(xwm); + + if ((width != old_w || height != old_h) && xsurface->has_clip_shape) { + wl_signal_emit_mutable(&xsurface->events.set_clip_shape, NULL); + } +} + +void wlr_xwayland_surface_close(struct wlr_xwayland_surface *xsurface) { + struct wlr_xwm *xwm = xsurface->xwm; + + bool supports_delete = false; + for (size_t i = 0; i < xsurface->protocols_len; i++) { + if (xsurface->protocols[i] == xwm->atoms[WM_DELETE_WINDOW]) { + supports_delete = true; + break; + } + } + + if (supports_delete) { + xcb_client_message_data_t message_data = {0}; + message_data.data32[0] = xwm->atoms[WM_DELETE_WINDOW]; + message_data.data32[1] = XCB_CURRENT_TIME; + xwm_send_wm_message(xsurface, &message_data, XCB_EVENT_MASK_NO_EVENT); + } else { + xcb_kill_client(xwm->xcb_conn, xsurface->window_id); + xwm_schedule_flush(xwm); + } +} + +void xwm_destroy(struct wlr_xwm *xwm) { + if (!xwm) { + return; + } + + xwm_selection_finish(&xwm->clipboard_selection); + xwm_selection_finish(&xwm->primary_selection); + xwm_selection_finish(&xwm->dnd_selection); + + xwm_seat_unlink_drag_handlers(xwm); + + if (xwm->seat) { + if (xwm->seat->selection_source && + data_source_is_xwayland(xwm->seat->selection_source)) { + wlr_seat_set_selection(xwm->seat, NULL, + wl_display_next_serial(xwm->xwayland->wl_display)); + } + + if (xwm->seat->primary_selection_source && + primary_selection_source_is_xwayland( + xwm->seat->primary_selection_source)) { + wlr_seat_set_primary_selection(xwm->seat, NULL, + wl_display_next_serial(xwm->xwayland->wl_display)); + } + + wlr_xwayland_set_seat(xwm->xwayland, NULL); + } + + if (xwm->cursor) { + xcb_free_cursor(xwm->xcb_conn, xwm->cursor); + } + if (xwm->colormap) { + xcb_free_colormap(xwm->xcb_conn, xwm->colormap); + } + if (xwm->no_focus_window) { + xcb_destroy_window(xwm->xcb_conn, xwm->no_focus_window); + } + if (xwm->window) { + xcb_destroy_window(xwm->xcb_conn, xwm->window); + } + if (xwm->event_source) { + wl_event_source_remove(xwm->event_source); + } +#if HAVE_XCB_ERRORS + if (xwm->errors_context) { + xcb_errors_context_free(xwm->errors_context); + } +#endif + struct wlr_xwayland_surface *xsurface, *tmp; + wl_list_for_each_safe(xsurface, tmp, &xwm->surfaces, link) { + xwayland_surface_destroy(xsurface); + } + wl_list_for_each_safe(xsurface, tmp, &xwm->unpaired_surfaces, unpaired_link) { + xwayland_surface_destroy(xsurface); + } + wl_list_remove(&xwm->compositor_new_surface.link); + wl_list_remove(&xwm->compositor_destroy.link); + wl_list_remove(&xwm->shell_v1_new_surface.link); + wl_list_remove(&xwm->shell_v1_destroy.link); + xcb_disconnect(xwm->xcb_conn); + + struct pending_startup_id *pending, *next; + wl_list_for_each_safe(pending, next, &xwm->pending_startup_ids, link) { + pending_startup_id_destroy(pending); + } + + xwm->xwayland->xwm = NULL; + free(xwm); +} + +static void xwm_get_resources(struct wlr_xwm *xwm) { + xcb_prefetch_extension_data(xwm->xcb_conn, &xcb_xfixes_id); + xcb_prefetch_extension_data(xwm->xcb_conn, &xcb_composite_id); + xcb_prefetch_extension_data(xwm->xcb_conn, &xcb_res_id); + xcb_prefetch_extension_data(xwm->xcb_conn, &xcb_shape_id); + + size_t i; + xcb_intern_atom_cookie_t cookies[ATOM_LAST]; + + for (i = 0; i < ATOM_LAST; i++) { + cookies[i] = + xcb_intern_atom(xwm->xcb_conn, 0, strlen(atom_map[i]), atom_map[i]); + } + for (i = 0; i < ATOM_LAST; i++) { + xcb_generic_error_t *error; + xcb_intern_atom_reply_t *reply = + xcb_intern_atom_reply(xwm->xcb_conn, cookies[i], &error); + if (reply && !error) { + xwm->atoms[i] = reply->atom; + } + free(reply); + + if (error) { + wlr_log(WLR_ERROR, "could not resolve atom %s, x11 error code %d", + atom_map[i], error->error_code); + free(error); + return; + } + } + + xwm->xfixes = xcb_get_extension_data(xwm->xcb_conn, &xcb_xfixes_id); + + if (!xwm->xfixes || !xwm->xfixes->present) { + wlr_log(WLR_DEBUG, "xfixes not available"); + } + + xcb_xfixes_query_version_cookie_t xfixes_cookie; + xcb_xfixes_query_version_reply_t *xfixes_reply; + xfixes_cookie = + xcb_xfixes_query_version(xwm->xcb_conn, XCB_XFIXES_MAJOR_VERSION, + XCB_XFIXES_MINOR_VERSION); + xfixes_reply = + xcb_xfixes_query_version_reply(xwm->xcb_conn, xfixes_cookie, NULL); + + wlr_log(WLR_DEBUG, "xfixes version: %" PRIu32 ".%" PRIu32, + xfixes_reply->major_version, xfixes_reply->minor_version); + xwm->xfixes_major_version = xfixes_reply->major_version; + + free(xfixes_reply); + + xwm->shape = xcb_get_extension_data(xwm->xcb_conn, &xcb_shape_id); + if (!xwm->shape || !xwm->shape->present) { + wlr_log(WLR_DEBUG, "shape not available"); + } else { + xcb_shape_query_version_cookie_t shape_cookie = + xcb_shape_query_version(xwm->xcb_conn); + xcb_shape_query_version_reply_t *shape_reply = + xcb_shape_query_version_reply(xwm->xcb_conn, shape_cookie, NULL); + if (shape_reply != NULL) { + wlr_log(WLR_DEBUG, "shape version: %" PRIu16 ".%" PRIu16, + shape_reply->major_version, shape_reply->minor_version); + // Input regions were added in Shape version 1.1. + xwm->shape_input_supported = shape_reply->major_version > 1 || + (shape_reply->major_version == 1 && + shape_reply->minor_version >= 1); + } + free(shape_reply); + if (!xwm->shape_input_supported) { + wlr_log(WLR_DEBUG, "shape input regions are not supported"); + } + } + + const xcb_query_extension_reply_t *xres = + xcb_get_extension_data(xwm->xcb_conn, &xcb_res_id); + if (!xres || !xres->present) { + return; + } + + xcb_res_query_version_cookie_t xres_cookie = + xcb_res_query_version(xwm->xcb_conn, XCB_RES_MAJOR_VERSION, + XCB_RES_MINOR_VERSION); + xcb_res_query_version_reply_t *xres_reply = + xcb_res_query_version_reply(xwm->xcb_conn, xres_cookie, NULL); + if (xres_reply == NULL) { + return; + } + + wlr_log(WLR_DEBUG, "xres version: %" PRIu32 ".%" PRIu32, + xres_reply->server_major, xres_reply->server_minor); + if (xres_reply->server_major > 1 || + (xres_reply->server_major == 1 && xres_reply->server_minor >= 2)) { + xwm->xres = xres; + } + free(xres_reply); +} + +static void xwm_create_wm_window(struct wlr_xwm *xwm) { + static const char name[] = "wlroots wm"; + + xwm->window = xcb_generate_id(xwm->xcb_conn); + + xcb_create_window(xwm->xcb_conn, + XCB_COPY_FROM_PARENT, + xwm->window, + xwm->screen->root, + 0, 0, + 10, 10, + 0, + XCB_WINDOW_CLASS_INPUT_OUTPUT, + xwm->screen->root_visual, + 0, NULL); + + xcb_change_property(xwm->xcb_conn, + XCB_PROP_MODE_REPLACE, + xwm->window, + xwm->atoms[NET_WM_NAME], + xwm->atoms[UTF8_STRING], + 8, // format + strlen(name), name); + + xcb_change_property(xwm->xcb_conn, + XCB_PROP_MODE_REPLACE, + xwm->screen->root, + xwm->atoms[NET_SUPPORTING_WM_CHECK], + XCB_ATOM_WINDOW, + 32, // format + 1, &xwm->window); + + xcb_change_property(xwm->xcb_conn, + XCB_PROP_MODE_REPLACE, + xwm->window, + xwm->atoms[NET_SUPPORTING_WM_CHECK], + XCB_ATOM_WINDOW, + 32, // format + 1, &xwm->window); + + xcb_set_selection_owner(xwm->xcb_conn, + xwm->window, + xwm->atoms[WM_S0], + XCB_CURRENT_TIME); + + xcb_set_selection_owner(xwm->xcb_conn, + xwm->window, + xwm->atoms[NET_WM_CM_S0], + XCB_CURRENT_TIME); +} + +static void xwm_create_no_focus_window(struct wlr_xwm *xwm) { + xwm->no_focus_window = xcb_generate_id(xwm->xcb_conn); + + uint32_t values[2] = { + 1, + XCB_EVENT_MASK_KEY_PRESS | + XCB_EVENT_MASK_KEY_RELEASE | + XCB_EVENT_MASK_FOCUS_CHANGE + }; + xcb_create_window(xwm->xcb_conn, + XCB_COPY_FROM_PARENT, + xwm->no_focus_window, + xwm->screen->root, + -100, -100, + 1, 1, + 0, + XCB_WINDOW_CLASS_COPY_FROM_PARENT, + XCB_COPY_FROM_PARENT, + XCB_CW_OVERRIDE_REDIRECT | + XCB_CW_EVENT_MASK, + values); + + xcb_map_window(xwm->xcb_conn, xwm->no_focus_window); +} + +// TODO use me to support 32 bit color somehow +static void xwm_get_visual_and_colormap(struct wlr_xwm *xwm) { + xcb_depth_iterator_t d_iter; + xcb_visualtype_iterator_t vt_iter; + xcb_visualtype_t *visualtype; + + d_iter = xcb_screen_allowed_depths_iterator(xwm->screen); + visualtype = NULL; + while (d_iter.rem > 0) { + if (d_iter.data->depth == 32) { + vt_iter = xcb_depth_visuals_iterator(d_iter.data); + visualtype = vt_iter.data; + break; + } + + xcb_depth_next(&d_iter); + } + + if (visualtype == NULL) { + wlr_log(WLR_DEBUG, "No 32 bit visualtype\n"); + return; + } + + xwm->visual_id = visualtype->visual_id; + xwm->colormap = xcb_generate_id(xwm->xcb_conn); + xcb_create_colormap(xwm->xcb_conn, + XCB_COLORMAP_ALLOC_NONE, + xwm->colormap, + xwm->screen->root, + xwm->visual_id); +} + +static void xwm_get_render_format(struct wlr_xwm *xwm) { + xcb_render_query_pict_formats_cookie_t cookie = + xcb_render_query_pict_formats(xwm->xcb_conn); + xcb_render_query_pict_formats_reply_t *reply = + xcb_render_query_pict_formats_reply(xwm->xcb_conn, cookie, NULL); + if (!reply) { + wlr_log(WLR_ERROR, "Did not get any reply from xcb_render_query_pict_formats"); + return; + } + xcb_render_pictforminfo_iterator_t iter = + xcb_render_query_pict_formats_formats_iterator(reply); + xcb_render_pictforminfo_t *format = NULL; + while (iter.rem > 0) { + if (iter.data->depth == 32) { + format = iter.data; + break; + } + + xcb_render_pictforminfo_next(&iter); + } + + if (format == NULL) { + wlr_log(WLR_DEBUG, "No 32 bit render format"); + free(reply); + return; + } + + xwm->render_format_id = format->id; + free(reply); +} + +void xwm_set_cursor(struct wlr_xwm *xwm, struct wlr_buffer *buffer, + int32_t hotspot_x, int32_t hotspot_y) { + if (!xwm->render_format_id) { + wlr_log(WLR_ERROR, "Cannot set xwm cursor: no render format available"); + return; + } + if (xwm->cursor) { + xcb_free_cursor(xwm->xcb_conn, xwm->cursor); + } + + void *pixels = NULL; + uint32_t format = DRM_FORMAT_INVALID; + size_t stride = 0; + if (!wlr_buffer_begin_data_ptr_access(buffer, WLR_BUFFER_DATA_PTR_ACCESS_READ, + &pixels, &format, &stride)) { + return; + } + + if (format != DRM_FORMAT_ARGB8888) { + wlr_buffer_end_data_ptr_access(buffer); + wlr_log(WLR_ERROR, "Only ARGB8888 is supported for Xwayland cursors"); + return; + } + int depth = 32; + + xcb_pixmap_t pix = xcb_generate_id(xwm->xcb_conn); + xcb_create_pixmap(xwm->xcb_conn, depth, pix, xwm->screen->root, buffer->width, + buffer->height); + + xcb_render_picture_t pic = xcb_generate_id(xwm->xcb_conn); + xcb_render_create_picture(xwm->xcb_conn, pic, pix, xwm->render_format_id, + 0, 0); + + xcb_gcontext_t gc = xcb_generate_id(xwm->xcb_conn); + xcb_create_gc(xwm->xcb_conn, gc, pix, 0, NULL); + + xcb_put_image(xwm->xcb_conn, XCB_IMAGE_FORMAT_Z_PIXMAP, pix, gc, + buffer->width, buffer->height, 0, 0, 0, depth, stride * buffer->height, + pixels); + xcb_free_gc(xwm->xcb_conn, gc); + + wlr_buffer_end_data_ptr_access(buffer); + + xwm->cursor = xcb_generate_id(xwm->xcb_conn); + xcb_render_create_cursor(xwm->xcb_conn, xwm->cursor, pic, hotspot_x, + hotspot_y); + xcb_free_pixmap(xwm->xcb_conn, pix); + xcb_render_free_picture(xwm->xcb_conn, pic); + + uint32_t values[] = {xwm->cursor}; + xcb_change_window_attributes(xwm->xcb_conn, xwm->screen->root, + XCB_CW_CURSOR, values); + xwm_schedule_flush(xwm); +} + +struct wlr_xwm *xwm_create(struct wlr_xwayland *xwayland, int wm_fd) { + struct wlr_xwm *xwm = calloc(1, sizeof(*xwm)); + if (xwm == NULL) { + close(wm_fd); + return NULL; + } + + xwm->xwayland = xwayland; + wl_list_init(&xwm->surfaces); + wl_list_init(&xwm->surfaces_in_stack_order); + wl_list_init(&xwm->unpaired_surfaces); + wl_list_init(&xwm->pending_startup_ids); + wl_list_init(&xwm->seat_drag_source_destroy.link); + wl_list_init(&xwm->drag_focus_destroy.link); + wl_list_init(&xwm->drop_focus_destroy.link); + + xwm->ping_timeout = 10000; + + // xcb_connect_to_fd takes ownership of the FD regardless of success/failure + xwm->xcb_conn = xcb_connect_to_fd(wm_fd, NULL); + + int rc = xcb_connection_has_error(xwm->xcb_conn); + if (rc) { + wlr_log(WLR_ERROR, "xcb connect failed: %d", rc); + xcb_disconnect(xwm->xcb_conn); + free(xwm); + return NULL; + } + +#if HAVE_XCB_ERRORS + if (xcb_errors_context_new(xwm->xcb_conn, &xwm->errors_context)) { + wlr_log(WLR_ERROR, "Could not allocate error context"); + xwm_destroy(xwm); + return NULL; + } +#endif + + xcb_screen_iterator_t screen_iterator = + xcb_setup_roots_iterator(xcb_get_setup(xwm->xcb_conn)); + xwm->screen = screen_iterator.data; + + struct wl_event_loop *event_loop = + wl_display_get_event_loop(xwayland->wl_display); + xwm->event_source = wl_event_loop_add_fd(event_loop, wm_fd, + WL_EVENT_READABLE, x11_event_handler, xwm); + wl_event_source_check(xwm->event_source); + + xwm_get_resources(xwm); + xwm_get_visual_and_colormap(xwm); + xwm_get_render_format(xwm); + + uint32_t values[] = { + XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY | + XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT | + XCB_EVENT_MASK_PROPERTY_CHANGE, + }; + xcb_change_window_attributes(xwm->xcb_conn, + xwm->screen->root, + XCB_CW_EVENT_MASK, + values); + + xcb_composite_redirect_subwindows(xwm->xcb_conn, + xwm->screen->root, + XCB_COMPOSITE_REDIRECT_MANUAL); + + xcb_atom_t supported[] = { + xwm->atoms[NET_WM_STATE], + xwm->atoms[NET_ACTIVE_WINDOW], + xwm->atoms[NET_CLOSE_WINDOW], + xwm->atoms[NET_WM_MOVERESIZE], + xwm->atoms[NET_WM_STATE_FOCUSED], + xwm->atoms[NET_WM_STATE_MODAL], + xwm->atoms[NET_WM_STATE_FULLSCREEN], + xwm->atoms[NET_WM_STATE_MAXIMIZED_VERT], + xwm->atoms[NET_WM_STATE_MAXIMIZED_HORZ], + xwm->atoms[NET_WM_STATE_HIDDEN], + xwm->atoms[NET_WM_STATE_STICKY], + xwm->atoms[NET_WM_STATE_SHADED], + xwm->atoms[NET_WM_STATE_SKIP_TASKBAR], + xwm->atoms[NET_WM_STATE_SKIP_PAGER], + xwm->atoms[NET_WM_STATE_ABOVE], + xwm->atoms[NET_WM_STATE_BELOW], + xwm->atoms[NET_WM_STATE_DEMANDS_ATTENTION], + xwm->atoms[NET_CLIENT_LIST], + xwm->atoms[NET_CLIENT_LIST_STACKING], + }; + xcb_change_property(xwm->xcb_conn, + XCB_PROP_MODE_REPLACE, + xwm->screen->root, + xwm->atoms[NET_SUPPORTED], + XCB_ATOM_ATOM, + 32, + sizeof(supported)/sizeof(*supported), + supported); + + if (xwm->xwayland->server->options.terminate_delay > 0 && + xwm->xfixes_major_version >= 6) { + xcb_xfixes_set_client_disconnect_mode(xwm->xcb_conn, + XCB_XFIXES_CLIENT_DISCONNECT_FLAGS_TERMINATE); + } + + xcb_flush(xwm->xcb_conn); + + xwm_set_net_active_window(xwm, XCB_WINDOW_NONE); + + xwm_selection_init(&xwm->clipboard_selection, xwm, xwm->atoms[CLIPBOARD]); + xwm_selection_init(&xwm->primary_selection, xwm, xwm->atoms[PRIMARY]); + xwm_selection_init(&xwm->dnd_selection, xwm, xwm->atoms[DND_SELECTION]); + + xwm->compositor_new_surface.notify = handle_compositor_new_surface; + wl_signal_add(&xwayland->compositor->events.new_surface, + &xwm->compositor_new_surface); + xwm->compositor_destroy.notify = handle_compositor_destroy; + wl_signal_add(&xwayland->compositor->events.destroy, + &xwm->compositor_destroy); + + xwm->shell_v1_new_surface.notify = handle_shell_v1_new_surface; + wl_signal_add(&xwayland->shell_v1->events.new_surface, + &xwm->shell_v1_new_surface); + xwm->shell_v1_destroy.notify = handle_shell_v1_destroy; + wl_signal_add(&xwayland->shell_v1->events.destroy, + &xwm->shell_v1_destroy); + + xwm_create_wm_window(xwm); + xwm_create_no_focus_window(xwm); + + xcb_flush(xwm->xcb_conn); + + return xwm; +} + +void wlr_xwayland_surface_set_withdrawn(struct wlr_xwayland_surface *surface, + bool withdrawn) { + surface->withdrawn = withdrawn; + xsurface_set_wm_state(surface); + xsurface_set_net_wm_state(surface); + xwm_schedule_flush(surface->xwm); +} + +void wlr_xwayland_surface_set_minimized(struct wlr_xwayland_surface *surface, + bool minimized) { + surface->minimized = minimized; + xsurface_set_wm_state(surface); + xsurface_set_net_wm_state(surface); + xwm_schedule_flush(surface->xwm); +} + +void wlr_xwayland_surface_set_maximized(struct wlr_xwayland_surface *surface, + bool maximized_horz, bool maximized_vert) { + surface->maximized_horz = maximized_horz; + surface->maximized_vert = maximized_vert; + xsurface_set_net_wm_state(surface); + xwm_schedule_flush(surface->xwm); +} + +void wlr_xwayland_surface_set_fullscreen(struct wlr_xwayland_surface *surface, + bool fullscreen) { + surface->fullscreen = fullscreen; + xsurface_set_net_wm_state(surface); + xwm_schedule_flush(surface->xwm); +} + +void wlr_xwayland_surface_set_sticky(struct wlr_xwayland_surface *surface, bool sticky) { + surface->sticky = sticky; + xsurface_set_net_wm_state(surface); + xwm_schedule_flush(surface->xwm); +} + +void wlr_xwayland_surface_set_shaded(struct wlr_xwayland_surface *surface, bool shaded) { + surface->shaded = shaded; + xsurface_set_net_wm_state(surface); + xwm_schedule_flush(surface->xwm); +} + +void wlr_xwayland_surface_set_skip_taskbar(struct wlr_xwayland_surface *surface, + bool skip_taskbar) { + surface->skip_taskbar = skip_taskbar; + xsurface_set_net_wm_state(surface); + xwm_schedule_flush(surface->xwm); +} + +void wlr_xwayland_surface_set_skip_pager(struct wlr_xwayland_surface *surface, + bool skip_pager) { + surface->skip_pager = skip_pager; + xsurface_set_net_wm_state(surface); + xwm_schedule_flush(surface->xwm); +} + +void wlr_xwayland_surface_set_above(struct wlr_xwayland_surface *surface, bool above) { + surface->above = above; + xsurface_set_net_wm_state(surface); + xwm_schedule_flush(surface->xwm); +} + +void wlr_xwayland_surface_set_below(struct wlr_xwayland_surface *surface, bool below) { + surface->below = below; + xsurface_set_net_wm_state(surface); + xwm_schedule_flush(surface->xwm); +} + +void wlr_xwayland_surface_set_demands_attention(struct wlr_xwayland_surface *surface, + bool demands_attention) { + surface->demands_attention = demands_attention; + xsurface_set_net_wm_state(surface); + xwm_schedule_flush(surface->xwm); +} + +bool xwm_atoms_contains(struct wlr_xwm *xwm, xcb_atom_t *atoms, + size_t num_atoms, enum atom_name needle) { + xcb_atom_t atom = xwm->atoms[needle]; + + for (size_t i = 0; i < num_atoms; ++i) { + if (atom == atoms[i]) { + return true; + } + } + + return false; +} + +void wlr_xwayland_surface_ping(struct wlr_xwayland_surface *surface) { + xcb_client_message_data_t data = { 0 }; + data.data32[0] = surface->xwm->atoms[NET_WM_PING]; + data.data32[1] = XCB_CURRENT_TIME; + data.data32[2] = surface->window_id; + + xwm_send_wm_message(surface, &data, XCB_EVENT_MASK_NO_EVENT); + + wl_event_source_timer_update(surface->ping_timer, + surface->xwm->ping_timeout); + surface->pinging = true; +} + +bool wlr_xwayland_surface_has_window_type( + const struct wlr_xwayland_surface *xsurface, + enum wlr_xwayland_net_wm_window_type window_type) { + static const enum atom_name atom_names[] = { + [WLR_XWAYLAND_NET_WM_WINDOW_TYPE_DESKTOP] = NET_WM_WINDOW_TYPE_DESKTOP, + [WLR_XWAYLAND_NET_WM_WINDOW_TYPE_DOCK] = NET_WM_WINDOW_TYPE_DOCK, + [WLR_XWAYLAND_NET_WM_WINDOW_TYPE_TOOLBAR] = NET_WM_WINDOW_TYPE_TOOLBAR, + [WLR_XWAYLAND_NET_WM_WINDOW_TYPE_MENU] = NET_WM_WINDOW_TYPE_MENU, + [WLR_XWAYLAND_NET_WM_WINDOW_TYPE_UTILITY] = NET_WM_WINDOW_TYPE_UTILITY, + [WLR_XWAYLAND_NET_WM_WINDOW_TYPE_SPLASH] = NET_WM_WINDOW_TYPE_SPLASH, + [WLR_XWAYLAND_NET_WM_WINDOW_TYPE_DIALOG] = NET_WM_WINDOW_TYPE_DIALOG, + [WLR_XWAYLAND_NET_WM_WINDOW_TYPE_DROPDOWN_MENU] = NET_WM_WINDOW_TYPE_DROPDOWN_MENU, + [WLR_XWAYLAND_NET_WM_WINDOW_TYPE_POPUP_MENU] = NET_WM_WINDOW_TYPE_POPUP_MENU, + [WLR_XWAYLAND_NET_WM_WINDOW_TYPE_TOOLTIP] = NET_WM_WINDOW_TYPE_TOOLTIP, + [WLR_XWAYLAND_NET_WM_WINDOW_TYPE_NOTIFICATION] = NET_WM_WINDOW_TYPE_NOTIFICATION, + [WLR_XWAYLAND_NET_WM_WINDOW_TYPE_COMBO] = NET_WM_WINDOW_TYPE_COMBO, + [WLR_XWAYLAND_NET_WM_WINDOW_TYPE_DND] = NET_WM_WINDOW_TYPE_DND, + [WLR_XWAYLAND_NET_WM_WINDOW_TYPE_NORMAL] = NET_WM_WINDOW_TYPE_NORMAL, + }; + + if (window_type >= 0 && window_type < sizeof(atom_names) / sizeof(atom_names[0])) { + return xwm_atoms_contains(xsurface->xwm, xsurface->window_type, + xsurface->window_type_len, atom_names[window_type]); + } + + return false; +} + +bool wlr_xwayland_surface_override_redirect_wants_focus( + const struct wlr_xwayland_surface *xsurface) { + static const enum atom_name needles[] = { + NET_WM_WINDOW_TYPE_COMBO, + NET_WM_WINDOW_TYPE_DND, + NET_WM_WINDOW_TYPE_DROPDOWN_MENU, + NET_WM_WINDOW_TYPE_MENU, + NET_WM_WINDOW_TYPE_NOTIFICATION, + NET_WM_WINDOW_TYPE_POPUP_MENU, + NET_WM_WINDOW_TYPE_SPLASH, + NET_WM_WINDOW_TYPE_DESKTOP, + NET_WM_WINDOW_TYPE_TOOLTIP, + NET_WM_WINDOW_TYPE_UTILITY, + }; + + for (size_t i = 0; i < sizeof(needles) / sizeof(needles[0]); ++i) { + if (xwm_atoms_contains(xsurface->xwm, xsurface->window_type, + xsurface->window_type_len, needles[i])) { + return false; + } + } + + return true; +} + +enum wlr_xwayland_icccm_input_model wlr_xwayland_surface_icccm_input_model( + const struct wlr_xwayland_surface *xsurface) { + bool take_focus = xwm_atoms_contains(xsurface->xwm, + xsurface->protocols, xsurface->protocols_len, + WM_TAKE_FOCUS); + + if (!xsurface->hints || xsurface->hints->input) { + if (take_focus) { + return WLR_ICCCM_INPUT_MODEL_LOCAL; + } + return WLR_ICCCM_INPUT_MODEL_PASSIVE; + } else { + if (take_focus) { + return WLR_ICCCM_INPUT_MODEL_GLOBAL; + } + } + return WLR_ICCCM_INPUT_MODEL_NONE; +} + +void wlr_xwayland_set_workareas(struct wlr_xwayland *wlr_xwayland, + const struct wlr_box *workareas, size_t num_workareas) { + uint32_t *data = malloc(4 * sizeof(uint32_t) * num_workareas); + if (!data) { + return; + } + + for (size_t i = 0; i < num_workareas; i++) { + data[4 * i] = workareas[i].x; + data[4 * i + 1] = workareas[i].y; + data[4 * i + 2] = workareas[i].width; + data[4 * i + 3] = workareas[i].height; + } + + struct wlr_xwm *xwm = wlr_xwayland->xwm; + xcb_change_property(xwm->xcb_conn, XCB_PROP_MODE_REPLACE, + xwm->screen->root, xwm->atoms[NET_WORKAREA], + XCB_ATOM_CARDINAL, 32, 4 * num_workareas, data); + free(data); +} + +xcb_connection_t *wlr_xwayland_get_xwm_connection( + struct wlr_xwayland *wlr_xwayland) { + return wlr_xwayland->xwm ? wlr_xwayland->xwm->xcb_conn : NULL; +} + +void xwm_schedule_flush(struct wlr_xwm *xwm) { + struct pollfd pollfd = { + .fd = xcb_get_file_descriptor(xwm->xcb_conn), + .events = POLLOUT, + }; + if (poll(&pollfd, 1, 0) < 0) { + wlr_log(WLR_ERROR, "poll() failed"); + return; + } + + // If we can write immediately, do so + if (pollfd.revents & POLLOUT) { + xcb_flush(xwm->xcb_conn); + return; + } + + wl_event_source_fd_update(xwm->event_source, WL_EVENT_READABLE | WL_EVENT_WRITABLE); +} diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000000..6c6cb95337 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,63 @@ +# Treeland 智能体指南 + +## 全局认识 +- `treeland` 是基于 `wlroots` + Qt6/QtQuick(Scene Graph 渲染)的 Wayland 合成器。 +- `wlroots` 以源码内联方式引入:上游源码在 `3rdparty/wlroots`,由 `wlroots/CMakeLists.txt` 编译成 CMake 模块(目标 `Wlroots::wlroots`)。waylib 直接调用 wlroots 的 C API —— 用 ``,不要 include 单个 `` 头文件 —— 并在此之上提供 Qt/C++ 的对象与生命周期层(`WObject`/`WServerInterface`、`WPointer`、作用域化的 `wl_signal` 监听)。 +- `waylib/` 建立在 `wlroots` 之上,提供对 QtQuick 友好的合成器框架(output 对应 `QQuickWindow`,surface 对应 `QQuickItem`)。 +- Treeland 自身的策略代码在 `src/`(workspace/seat/input/output、plugin/module、XWayland 集成)。 + +## Skills +开始任务前先读对应 skill,不要等到第一次尝试失败再读。 + +| Skill | 适用场景 | 何时读 | +|-------|----------|--------| +| [treeland-build](.agents/skills/treeland-build/SKILL.md) | CMake preset、Debug 构建、安装到 `/usr`、配置选项 | 配置、编译或安装前 | +| [treeland-protocol](.agents/skills/treeland-protocol/SKILL.md) | treeland 自有 `treeland_*` xml、`QtWaylandServer::*`、`src/modules/*` | 新增或调试私有协议 | +| [treeland-protocol-upstream](.agents/skills/treeland-protocol-upstream/SKILL.md) | standard/ext/unstable/wlr 协议、waylib `WServerInterface` 封装 | 新增或调试上游协议 | +| [treeland-protocol-test](.agents/skills/treeland-protocol-test/SKILL.md) | `tests/protocols/`、C 版 Wayland 客户端、CTest 协议测试目标 | 新增或修复协议测试 | +| [treeland-logging](.agents/skills/treeland-logging/SKILL.md) | `treelandlogging.*` / `wayliblogging.*`、日志级别 | 新增、修改或评审日志 | +| [treeland-dconfig](.agents/skills/treeland-dconfig/SKILL.md) | `misc/dconfig/*.json`、生成的配置封装类 | 新增或修改配置项 | +| [treeland-debug](.agents/skills/treeland-debug/SKILL.md) | `treeland-debug` CLI、运行时状态、运行日志 | 复现或诊断运行中的合成器 | + +## 代码在哪里 +- `src/core/`:生命周期与 QML 引擎胶水(例如 `src/core/qmlengine.*`、`src/core/treeland.*`)。 +- `src/surface/`:surface/window 封装、状态/可见性/几何(例如 `src/surface/surfacewrapper.cpp`)。 +- `src/seat/`:合成器 seat 管理。桌面启动、协议组装与 Wayland 运行时在 `src/core/waylandserver.*`。 +- `src/input/`:输入管理、seat 设备、按用户区分的 seat 配置。 +- `src/workspace/`:workspace 模型与切换。 +- `src/dconfig/`:`DConfigManager` 与生成的配置封装类。 +- `src/plugins/` + `src/modules/`:集成点与功能组合。 +- `src/common/treelandlogging.*`:treeland 集中式日志分类。 +- `tests/protocols/`:协议集成测试,每个协议一个目录。 + +## 构建与测试 +```bash +cmake --preset ci +cmake --build --preset ci +ctest --preset ci +``` + +- 日常开发优先用 `ci` preset:它对齐 CI 的 `-Wall -Wextra -Werror` 编译选项,能在本地提前发现会导致 CI 失败的告警。`CMakePresets.json` 里其他 preset:`default`、`clang`、`ci-clang`。 +- `WITH_SUBMODULE_WAYLIB=ON|OFF` 选择使用子模块 waylib 还是系统 waylib,默认偏好 `ON`。 +- 协议测试在 `BUILD_TREELAND_PROTOCOL_TESTS=ON`(默认值)时构建,用 `ctest --test-dir build -L protocols` 运行。`TREELAND_ENABLE_GPU_PROTOCOL_TESTS`(DMA-BUF 渲染器)默认 `OFF`;需要 `/dev/uinput` 或 `dde-seatd` 的用例始终会构建,运行时自动 skip。 + +Debug 构建(`-DCMAKE_BUILD_TYPE=Debug`)、安装到 `/usr`、全部配置选项与常见问题见 `.agents/skills/treeland-build/SKILL.md`。 + +## 项目规则 +- 只用 C++20 和 Qt6。 +- `connect()` 与信号监听优先用成员函数指针;lambda 仅转发给单个成员函数时不要用 lambda。 +- 避免复杂 lambda;lambda 体超过几行就抽成具名成员函数。 +- 保持 diff 最小:只碰与任务相关的文件和符号。 +- 不要做与任务无关的大范围重构、重命名或重新格式化。 +- 新增源文件必须带与仓库一致的 SPDX 行,通常是 `SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only`。非源码文件(配置、资源、翻译、打包)由 `REUSE.toml` 覆盖,不需要逐文件声明。 +- 日志相关改动必须遵循 `.agents/skills/treeland-logging/SKILL.md`。 +- 如果实际任务中发现仓库内的 skill 有错、过期或不完整,要主动更新该 skill,不要沿用已知错误的指引。 + +## Wayland 协议路由 +协议类改动需要一个实现类 skill;当行为可在协议线上观察时,再加测试 skill: + +- Treeland 私有协议:`.agents/skills/treeland-protocol/SKILL.md` +- 上游 wlroots/waylib 协议:`.agents/skills/treeland-protocol-upstream/SKILL.md` +- 协议测试:`.agents/skills/treeland-protocol-test/SKILL.md` + +除非任务本身就是重构边界,否则不要在同一次改动里混用两条实现路径。 diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000000..ebcbaff397 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,204 @@ +cmake_minimum_required(VERSION 3.25.0) + +project(Treeland + VERSION 0.12.0 + LANGUAGES CXX C) + +set(CMAKE_INCLUDE_CURRENT_DIR ON) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_C_STANDARD 23) # Unnamed parameters in function definition is a C23 extension feature. +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# Standard installation paths +include(GNUInstallDirs) +# Macros +include(FeatureSummary) + +include(cmake/DefineTarget.cmake) + +option(WITH_SUBMODULE_WAYLIB "Use the waylib from git submodule" ON) +add_feature_info(submodule_waylib WITH_SUBMODULE_WAYLIB "Use waylib from submodule") + +option(ADDRESS_SANITIZER "Enable address sanitizer" OFF) +add_feature_info(ASanSupport ADDRESS_SANITIZER "https://github.com/google/sanitizers/wiki/AddressSanitizer") + +option(BUILD_TREELAND_EXAMPLES "Build clients demo to test treeland" OFF) +add_feature_info(DemoClents BUILD_TEST_CLIENTS "clients demo for testing") + +option(BUILD_TREELAND_PROTOCOL_TESTS "Build Treeland Wayland protocol tests" ON) + +option(USE_BUILD_TREE_WALLPAPER_FACTORY + "Use the wallpaper factory executable from the build tree" + OFF) +add_feature_info(build_tree_wallpaper_factory + USE_BUILD_TREE_WALLPAPER_FACTORY + "Use the wallpaper factory executable from the build tree") + +option(DISABLE_DDM "Disable DDM and greeter" OFF) + +if (DISABLE_DDM) + add_compile_definitions("DISABLE_DDM") +endif() + +option(DISABLE_XWAYLAND "Disable the xwayland support" OFF) +if (DISABLE_XWAYLAND) + add_compile_definitions("DISABLE_XWAYLAND") + add_feature_info(xwayland_support OFF "XWayland support") +else() + add_feature_info(xwayland_support ON "XWayland support") +endif() + +# Alternative lock mechanism: Wayland ext-session-lock +option(EXT_SESSION_LOCK_V1 "Enable Wayland ext-session-lock support (alternative to DDM)" ON) +add_feature_info(ext_session_lock_v1 EXT_SESSION_LOCK_V1 "Enable ext-session-lock-v1 protocol support in Treeland") + +if (EXT_SESSION_LOCK_V1) + add_compile_definitions("EXT_SESSION_LOCK_V1") +endif() +# Heads-up if both are enabled: ext-session-lock is intended as an alternative to DDM +if (NOT EXT_SESSION_LOCK_V1 AND DISABLE_DDM) + message(WARNING "no ext-session-lock support and no DDM, treeland will not have session locking ability.") +endif() + +option(TREELAND_INSTALL_DEV "Install development files (headers, CMake config, pkg-config, .so symlinks)" OFF) +add_feature_info(treeland_install_dev TREELAND_INSTALL_DEV "Install development files for external consumers") + +if (ADDRESS_SANITIZER) + add_compile_options(-fsanitize=address -fno-optimize-sibling-calls -fno-omit-frame-pointer) + add_link_options(-fsanitize=address) +endif() + +# Socket base names for the treeland-debug remote-object channel. +# Debug builds use a distinct name so a debug-compiled treeland can run +# alongside a release one in the same runtime directory. A debug-built +# treeland-debug client prefers the debug instance and falls back to the +# release instance when the debug one is unreachable. +set(TREELAND_DEBUG_SOCKET_RELEASE "org.deepin.dde.treeland.debug") +set(TREELAND_DEBUG_SOCKET_DEV "org.deepin.dde.treeland.debug-dev") +# Use generator expressions so multi-config generators (Ninja Multi-Config, +# Visual Studio) also select the debug socket for Debug configurations. +add_compile_definitions( + "TREELAND_DEBUG_SOCKET_RELEASE=\"${TREELAND_DEBUG_SOCKET_RELEASE}\"" + "$<$:TREELAND_DEBUG_DEV_BUILD>" + "$<$:TREELAND_DEBUG_SOCKET=\"${TREELAND_DEBUG_SOCKET_DEV}\">" + "$<$>:TREELAND_DEBUG_SOCKET=\"${TREELAND_DEBUG_SOCKET_RELEASE}\">" +) + +# NOTE: Qt keywords conflict with wlroots. but dtksystemsettings still uses it. +# add_definitions("-DQT_NO_KEYWORDS") + +# NOTE: Enable Qt logging with context. +add_definitions("-DQT_MESSAGELOGCONTEXT") + +set(LOCAL_QML_IMPORT_PATH "${PROJECT_BINARY_DIR}/qt/qml") + +if(WITH_SUBMODULE_WAYLIB) + include(${CMAKE_CURRENT_SOURCE_DIR}/waylib/cmake/WaylandScannerHelpers.cmake) + # Vendored wlroots must be available before waylib consumers. + # Scaffold in wlroots/; upstream sources under 3rdparty/wlroots. + add_subdirectory(wlroots) + add_subdirectory(waylib) + list(APPEND LOCAL_QML_IMPORT_PATH "${PROJECT_BINARY_DIR}/waylib/src/server") +else() + # Consume the wlroots library exported by the installed Waylib package + # instead of building a second vendored copy (dual-link/ODR risk). + find_package(Waylib REQUIRED Server) + if(NOT DISABLE_XWAYLAND) + # The installed headers can disable Xwayland independently of our + # cache option. Reject that mismatch before selecting X11 modules. + include(CMakePushCheckState) + include(CheckCXXSourceCompiles) + cmake_push_check_state(RESET) + set(CMAKE_REQUIRED_LIBRARIES Waylib::WaylibServer) + unset(TREELAND_SYSTEM_WAYLIB_HAS_XWAYLAND CACHE) + check_cxx_source_compiles(" +#include +#ifdef DISABLE_XWAYLAND +#error Installed Waylib has no Xwayland support +#endif +int main() { return 0; } +" TREELAND_SYSTEM_WAYLIB_HAS_XWAYLAND) + cmake_pop_check_state() + if(NOT TREELAND_SYSTEM_WAYLIB_HAS_XWAYLAND) + message(FATAL_ERROR + "The installed Waylib could not be used with Xwayland enabled. " + "Configure with -DDISABLE_XWAYLAND=ON for a Waylib without " + "Xwayland support, or install an Xwayland-enabled Waylib. " + "See the CMake configure log for the probe error.") + endif() + endif() + if(NOT TARGET Wlroots::wlroots) + if(TARGET Waylib::waylib-wlroots) + add_library(Wlroots::wlroots ALIAS Waylib::waylib-wlroots) + else() + pkg_check_modules(WLR_INSTALLED REQUIRED IMPORTED_TARGET waylib-wlroots) + add_library(Wlroots::wlroots ALIAS PkgConfig::WLR_INSTALLED) + endif() + endif() + # The capture module generates protocol code with ws_generate(); load + # the vendored helpers so external builds do not depend on the scanner + # helpers being exported by the installed Waylib package. + include(${CMAKE_CURRENT_SOURCE_DIR}/waylib/cmake/WaylandScannerHelpers.cmake) +endif() + +set(QML_IMPORT_PATH "${LOCAL_QML_IMPORT_PATH}" CACHE STRING "For LSP" FORCE) + +# PKG-CONFIG +find_package(PkgConfig REQUIRED) +find_package(TreelandProtocols 0.8.0 CONFIG REQUIRED) +find_package(Qt6 CONFIG REQUIRED Core DBus Gui Qml Quick QuickControls2 LinguistTools Test QuickTest) + +qt_standard_project_setup(REQUIRES 6.8) + +# Set constants +set(TREELAND_DATA_DIR "${CMAKE_INSTALL_DATADIR}/treeland/" CACHE PATH "treeland data install directory") +set(TREELAND_COMPONENTS_TRANSLATION_DIR "${TREELAND_DATA_DIR}/translations" CACHE PATH "Components translations directory") +set(TREELAND_PLUGINS_OUTPUT_PATH "${CMAKE_BINARY_DIR}/lib/plugins" CACHE PATH "treeland plugins output directory") +set(TREELAND_PLUGINS_INSTALL_PATH "${CMAKE_INSTALL_LIBDIR}/treeland/plugins" CACHE PATH "treeland plugins install directory") + +GNUInstallDirs_get_absolute_install_dir( + TREELAND_FULL_DATA_DIR + TREELAND_DATA_DIR + DATADIR +) + +GNUInstallDirs_get_absolute_install_dir( + TREELAND_FULL_PLUGINS_INSTALL_PATH + TREELAND_PLUGINS_INSTALL_PATH + LIBDIR +) + +GNUInstallDirs_get_absolute_install_dir( + TREELAND_FULL_COMPONENTS_TRANSLATION_DIR + TREELAND_COMPONENTS_TRANSLATION_DIR + DATADIR +) + +set(TREELAND_SYSCONFDIR "${CMAKE_INSTALL_FULL_SYSCONFDIR}/treeland" CACHE PATH "treeland system config directory") + +add_compile_definitions("TREELAND_DATA_DIR=\"${TREELAND_FULL_DATA_DIR}\"") +# NOTE:: remove force assert before stable version +add_compile_definitions("QT_FORCE_ASSERTS") + +add_compile_definitions("TREELAND_PLUGINS_INSTALL_PATH=\"${TREELAND_FULL_PLUGINS_INSTALL_PATH}\"") +add_compile_definitions("TREELAND_PLUGINS_OUTPUT_PATH=\"${TREELAND_PLUGINS_OUTPUT_PATH}\"") + +add_compile_definitions("TREELAND_COMPONENTS_TRANSLATION_DIR=\"${TREELAND_FULL_COMPONENTS_TRANSLATION_DIR}\"") + +set(PROJECT_RESOURCES_DIR "${CMAKE_SOURCE_DIR}/misc") + +enable_testing(true) + +add_subdirectory(src) +add_subdirectory(tools) +add_subdirectory(misc) +add_subdirectory(tests) +add_subdirectory(wallpaper-factory) + +if (BUILD_TREELAND_EXAMPLES) + add_subdirectory(examples) +endif() + +# Display feature summary +feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 0000000000..2fa502327c --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,83 @@ +{ + "version": 6, + "cmakeMinimumRequired": { + "major": 3, + "minor": 23, + "patch": 0 + }, + "include": [], + "configurePresets": [ + { + "name": "default", + "displayName": "Default Config", + "description": "Default build using Ninja generator", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build" + }, + { + "name": "clang", + "displayName": "Default Config for clang", + "description": "Default build using Ninja generator", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build", + "cacheVariables": { + "CMAKE_C_COMPILER": "clang", + "CMAKE_CXX_COMPILER": "clang++" + } + }, + { + "name": "ci", + "displayName": "CI Build Config", + "description": "Build configuration with warnings as errors", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build", + "cacheVariables": { + "CMAKE_CXX_FLAGS": "-Wall -Wextra -Werror -Wno-stringop-overflow -Wno-sfinae-incomplete", + "CMAKE_C_FLAGS": "-Wall -Wextra -Werror -Wno-stringop-overflow" + } + }, + { + "name": "ci-clang", + "displayName": "CI Build Config for clang", + "description": "Build configuration with warnings as errors", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build", + "cacheVariables": { + "CMAKE_C_COMPILER": "clang", + "CMAKE_CXX_COMPILER": "clang++", + "CMAKE_CXX_FLAGS": "-Wall -Wextra -Werror -Wno-shift-overflow -Wno-overloaded-virtual", + "CMAKE_C_FLAGS": "-Wall -Wextra -Werror -Wno-shift-overflow -Wno-overloaded-virtual" + } + } + ], + "buildPresets": [ + { + "name": "default", + "configurePreset": "default" + }, + { + "name": "clang", + "configurePreset": "clang" + }, + { + "name": "ci", + "configurePreset": "ci" + }, + { + "name": "ci-clang", + "configurePreset": "ci-clang" + } + ], + "testPresets": [ + { + "name": "ci", + "configurePreset": "ci", + "output": { + "outputOnFailure": true + }, + "execution": { + "noTestsAction": "error" + } + } + ] +} diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000000..137069b823 --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/LICENSES/CC-BY-4.0.txt b/LICENSES/CC-BY-4.0.txt new file mode 100644 index 0000000000..13ca539f37 --- /dev/null +++ b/LICENSES/CC-BY-4.0.txt @@ -0,0 +1,156 @@ +Creative Commons Attribution 4.0 International + + Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. + +Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors. + +Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public. + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +Section 1 – Definitions. + + a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + + d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. + + g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. + + i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. + +Section 2 – Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: + + A. reproduce and Share the Licensed Material, in whole or in part; and + + B. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. + + 3. Term. The term of this Public License is specified in Section 6(a). + + 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. + + 5. Downstream recipients. + + A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. + + B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. + + 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). + +b. Other rights. + + 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this Public License. + + 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. + +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified form), You must: + + A. retain the following if it is supplied by the Licensor with the Licensed Material: + + i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + + v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + + B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and + + C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. + + 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. + +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; + + b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. + + a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. + + b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. + + c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. + +Section 6 – Term and Termination. + + a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + + c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + + d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. + + e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +Section 7 – Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. + +Section 8 – Interpretation. + + a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. + + c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. + + d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. + +Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt new file mode 100644 index 0000000000..0e259d42c9 --- /dev/null +++ b/LICENSES/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/LICENSES/GPL-2.0-only.txt b/LICENSES/GPL-2.0-only.txt new file mode 100644 index 0000000000..17cb286430 --- /dev/null +++ b/LICENSES/GPL-2.0-only.txt @@ -0,0 +1,117 @@ +GNU GENERAL PUBLIC LICENSE +Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) 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 this service 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 make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. 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. + +We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. + +Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. + +1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. + + c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. + +4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. + +6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. + +7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +9. The Free Software Foundation may publish revised and/or new versions of the 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 a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. + +10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE 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. + +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 convey 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 an idea of what it does. Copyright (C) yyyy 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 2 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author Gnomovision 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, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. + +signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice diff --git a/LICENSES/GPL-3.0-only.txt b/LICENSES/GPL-3.0-only.txt new file mode 100644 index 0000000000..f6cdd22a6c --- /dev/null +++ b/LICENSES/GPL-3.0-only.txt @@ -0,0 +1,232 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 . + +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 . diff --git a/LICENSES/HPND.txt b/LICENSES/HPND.txt new file mode 120000 index 0000000000..2c9e1934c0 --- /dev/null +++ b/LICENSES/HPND.txt @@ -0,0 +1 @@ +../waylib/LICENSES/HPND.txt \ No newline at end of file diff --git a/LICENSES/LGPL-2.1-or-later.txt b/LICENSES/LGPL-2.1-or-later.txt new file mode 100644 index 0000000000..c6487f4fdf --- /dev/null +++ b/LICENSES/LGPL-2.1-or-later.txt @@ -0,0 +1,176 @@ +GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. + +GNU LESSER GENERAL PUBLIC LICENSE +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. + + e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. + + b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). + +To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library's name and an idea of what it does. + Copyright (C) year name of author + + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. + + This library 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 Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in +the library `Frob' (a library for tweaking knobs) written +by James Random Hacker. + +signature of Ty Coon, 1 April 1990 +Ty Coon, President of Vice +That's all there is to it! diff --git a/LICENSES/LGPL-3.0-only.txt b/LICENSES/LGPL-3.0-only.txt new file mode 100644 index 0000000000..513d1c01fe --- /dev/null +++ b/LICENSES/LGPL-3.0-only.txt @@ -0,0 +1,304 @@ +GNU LESSER GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. + +0. Additional Definitions. + +As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. + +"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. + +An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. + +A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". + +The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. + +The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. + +1. Exception to Section 3 of the GNU GPL. +You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. + +2. Conveying Modified Versions. +If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: + + a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. + +3. Object Code Incorporating Material from Library Header Files. +The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license document. + +4. Combined Works. +You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: + + a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license document. + + c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. + + e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) + +5. Combined Libraries. +You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +6. Revised Versions of the GNU Lesser General Public License. +The Free Software Foundation may publish revised and/or new versions of the GNU Lesser 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 Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. + +If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. + +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 . + +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 . diff --git a/LICENSES/LicenseRef-Qt-Commercial.txt b/LICENSES/LicenseRef-Qt-Commercial.txt new file mode 100644 index 0000000000..825b1f358b --- /dev/null +++ b/LICENSES/LicenseRef-Qt-Commercial.txt @@ -0,0 +1,8 @@ +Licensees holding valid commercial Qt licenses may use this software in +accordance with the the terms contained in a written agreement between +you and The Qt Company. Alternatively, the terms and conditions that were +accepted by the licensee when buying and/or downloading the +software do apply. + +For the latest licensing terms and conditions, see https://www.qt.io/terms-conditions. +For further information use the contact form at https://www.qt.io/contact-us. diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 0000000000..f7abf7e963 --- /dev/null +++ b/LICENSES/MIT.txt @@ -0,0 +1,23 @@ +MIT License + +Copyright (c) 2017, 2018 Drew DeVault +Copyright (c) 2014 Jari Vetoniemi +Copyright (c) 2023 The wlroots contributors + +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. diff --git a/README.md b/README.md new file mode 100644 index 0000000000..7a32acfc99 --- /dev/null +++ b/README.md @@ -0,0 +1,386 @@ +# Treeland + +treeland is a wayland compositor based on wlroots and QtQuick, designed to provide efficient and flexible graphical interface support. + +## Dependencies + +Check the `debian/control` file to understand specific build and runtime dependencies, or use `cmake` to check for missing necessary components. + +Core build dependencies: + +- [waylib](https://github.com/vioken/waylib): A Wayland compositor development library based on wlroots and QtQuick + - Qt >= 6.8.0 + - wlroots = 0.20 +- [treeland-protocols](https://github.com/linuxdeepin/treeland-protocols): Private Wayland protocols used by treeland + +Recommended runtime dependencies: + +- [ddm](https://github.com/linuxdeepin/ddm): A display manager optimized for multiple users + +## Building + +Treeland uses cmake for building. The WITH_SUBMODULE_WAYLIB option can force the use of the waylib code from the submodule. If you want to use the system-provided waylib, set this option to OFF. + +Using the system-provided waylib: + +```shell +$ git clone git@github.com:linuxdeepin/treeland.git +$ cd treeland +$ cmake -Bbuild -DWITH_SUBMODULE_WAYLIB=OFF +$ cmake --build build +``` + +Using the waylib from the submodule: + +```shell +$ git clone git@github.com:linuxdeepin/treeland.git --recursive +$ cd treeland +$ cmake -Bbuild -DWITH_SUBMODULE_WAYLIB=ON +$ cmake --build build +``` + +## Packaging + +A `debian` folder is provided to build the package under the *deepin* linux desktop distribution. To build the package, use the following command: + +```shell +$ sudo apt build-dep . # install build dependencies +$ dpkg-buildpackage -uc -us -nc -b # build binary package(s) +``` + +## treeland-debug + +`treeland-debug` is an adb-style command-line inspector and controller for the +running Treeland compositor. It connects to Treeland's debug Remote Object over +Qt Remote Objects and exposes subcommands for inspecting the window tree, +controlling windows, injecting input events and grabbing screenshots. Like `adb`, +it runs in two modes: + +- **Non-shell (one-shot) mode** — the default: `treeland-debug [args]`. +- **Shell mode** — an interactive REPL: `treeland-debug shell`. + +The client builds as part of the normal Treeland build (it is on by default; pass +`-DBUILD_TREELAND_DEBUG=OFF` to skip it): + +```bash +cmake -B build +cmake --build build --target treeland-debug +sudo cmake --install build --component treeland-debug +``` + +### Enabling the debug source + +The debug Remote Object is off by default: it hands out window contents and +input injection, which a compositor running inside a user session must not offer +unasked. `remoteDebug` is Treeland's master switch for it. While the switch is +on, Treeland publishes its debug socket and serves the window tree remote source +to clients that pass the socket's access checks -- the source is a thin QObject +that only does work per call, so it costs nothing when no client is attached. +Turn the switch off to forbid debugging entirely; the socket then disappears +too. Release builds keep the socket root-only (mode 0000). A Debug development +build instead ignores the switch and publishes its `-dev` socket in +`/tmp/treeland-debug-` (directory mode 0700, socket mode 0600). Other +unprivileged UIDs cannot reach the socket; root retains privileged access. +Running the Debug client as that same UID needs no polkit prompt. The separate `-dev` name keeps such an instance apart from a +release one. Release session instances use `$XDG_RUNTIME_DIR`, which stays 0700 +like Qt requires; Debug builds use their UID-specific `/tmp` directory even in +user mode. + +The root restriction of a release build can be lifted for a while over the +debug protocol itself: `treeland-debug no-auth` (the `requestNoAuth` method of +`WindowTreeRemote`) asks the compositor to open its debug directory (0711) and +its socket (0666) to every local user. Only a caller that already got through the +sealed socket can ask, and in a release build that is root alone: mode 0000 +blocks the compositor's own user as well, and only `CAP_DAC_OVERRIDE` passes. So +that connection is the authentication -- opening the window therefore costs root +one `pkexec` prompt, and everyone who connects during those 30 minutes needs +none. The window closes 30 minutes later; every remote call while it is open +pushes it out again, so a forgotten request cannot leave the channel open for +longer than an idle half hour. Closing it also drops the connections that were +opened while it was open, so the window cannot be kept alive by holding a +client connected. + +Only the global service gets this window, and only for a directory of its own: +`/run/treeland-debug` (`RuntimeDirectory=treeland-debug`), never its +`$XDG_RUNTIME_DIR` (`/run/treeland`) -- Qt insists that one stays 0700 and would +move new sessions' wayland sockets to `$TMPDIR` otherwise. A session instance +runs inside `/run/user/`, which also holds the session bus and other +per-session sockets, so Treeland leaves that directory alone there and root +stays required. + +The window is held in memory only, so nothing outlives the compositor: a crash +or a restart comes back root-only, and every socket is sealed on startup even if +the previous process died with the window open. The directory itself is widened +once (0711, traverse but not list) and stays that way until the process exits, +because several instances may share it and one closing its window must not cut +off a peer's; a restart under systemd recreates it 0700. Access is gated by the +socket modes alone. Any number of clients can attach at once while it is open. +If no socket is published, either the switch is off or Treeland is not running -- +the client says so on stderr and points at the switch. Toggling `remoteDebug` +takes effect immediately: the remote source is created or destroyed on the fly, +no restart needed. + +Flip the switch with `treeland-debug debug on` / `treeland-debug debug off` +(`debug` without an argument reports the current state). The switch is a +per-user DConfig key that Treeland reads for the user it runs as, so the command +finds that user through the running compositor and escalates through `pkexec` +when it is not you; `--no-escalate` reports the requirement instead of prompting. +Underneath it runs, as root, the equivalent of: + +```bash +dde-dconfig -u set \ + -a org.deepin.dde.treeland \ + -r org.deepin.dde.treeland \ + -k remoteDebug \ + -v true +``` + +All commands below are run as the `dde` user, e.g. +`sudo -u dde -- treeland-debug windows`. + +### Socket naming and connection + +Treeland publishes the debug source on a local socket whose default name is +`org.deepin.dde.treeland.debug`, bound at an absolute path in a directory of +its own: `/run/treeland-debug/org.deepin.dde.treeland.debug` for the global +Release service (`RuntimeDirectory=treeland-debug`) and `/run/user//...` +(i.e. `$XDG_RUNTIME_DIR`) for a Release session. Debug development builds use +`/tmp/treeland-debug-/...` by default (directory mode 0700, socket mode +0600), including in user mode; this avoids writing into the host's `/run`. +`$TREELAND_DEBUG_DIR` explicitly overrides the development/test directory. The +global Release directory is created 0700 by systemd and is not its +`$XDG_RUNTIME_DIR`, because the no-auth window widens it to 0711 and Qt requires +a runtime directory to stay 0700. + +Clients probe the Debug build's own dev directory first, then the shared global +and legacy locations, then that client's own runtime directory. Debug clients +do not enumerate other UIDs' runtime directories. Release root clients retain +the search of every `/run/user/` directory they can list. +When the name is already taken +by another running treeland (global service, session service, local build), +a numeric suffix is appended (`org.deepin.dde.treeland.debug-1`, `-2`, …), +selected with a non-blocking advisory lock (the same approach libwayland uses +for Wayland sockets). A stale socket file left by a crashed instance is +reclaimed, and a live old-build instance (one without a lock file) is probed +and left alone. + +Debug builds use a distinct base name (`org.deepin.dde.treeland.debug-dev`) +so a debug-compiled treeland can run alongside a release one. A debug-built +treeland-debug client automatically prefers its own UID's dev instance and +falls back to shared/release locations when it is unreachable; a release-built +client uses the release instance. The socket is chosen in this order: `--url`, +then `$TREELAND_DEBUG_SOCKET` (a socket path or a bare name, treated like +`local:`; a value with a scheme is used as-is), then the probing above. +An explicit URL always overrides this with no implicit processing -- that is +also the way to reach a socket published by an older treeland, which still +lives at the pre-migration `/tmp/` path: +`--url local:/tmp/org.deepin.dde.treeland.debug`. + +### Global options + +| Option | Default | Description | +| --- | --- | --- | +| `--url ` | `$TREELAND_DEBUG_SOCKET`, else auto: debug socket (debug build) with release fallback, else release socket | Remote object host URL. | +| `--name ` | `WindowTree` | Remote object name. | +| `--timeout-ms ` | `30000` | Request timeout in ms (non-negative integer). | +| `--json` | off | Emit machine-readable JSON for `tree`/`cursor`/`windows`/`clients`. | +| `--preview` | auto | Force inline image preview in terminal (auto-detected by default). | +| `--no-preview` | off | Disable inline image preview. | +| `-h, --help` | — | Show help. | +| `-v, --version` | — | Show version. | +| `--tree` / `--cursor` | — | Backward-compatible aliases for the `tree` / `cursor` commands. | + +### Command reference + +Window-control commands accept a target given by **numeric `id`** (printed by +`windows` / `clients` / `top`) or by **`appId`** (the first matching window is +used). + +#### Inspection + +| Command | Arguments | Output | +| --- | --- | --- | +| `tree` | _(none, default)_ | Layout tree (human-readable; `--json` for JSON). | +| `cursor` | _(none)_ | Cursor position `x=… y=…` (`--json` for `{"x","y"}`). | +| `windows` | _(none)_ | Window table; `--json` for a JSON array. | +| `clients` | _(none)_ | Client + window table; `--json` for a JSON array. | +| `shortcuts` | _(none)_ | Registered shortcuts (keys and gestures); `--json` for a JSON array. | +| `top` | `[interval-ms]` (default 1000) | Live, `top`-like refreshing client view (Ctrl+C to quit). | + +#### Window control + +| Command | Arguments | Output | +| --- | --- | --- | +| `activate` | `` | `ok` / `failed`. | +| `close` | `` | `ok` / `failed`. | +| `minimize` | `` | `ok` / `failed`. | +| `maximize` | `` | `ok` / `failed` (toggles maximized). | +| `fullscreen` | `` | `ok` / `failed` (toggles fullscreen). | +| `move` | ` ` | `ok` / `failed`. | +| `resize` | ` ` | `ok` / `failed`. | +| `workspace` | ` ` | `ok` / `failed` (move window to a workspace). | + +#### Input / event injection + +| Command | Arguments | Output | +| --- | --- | --- | +| `move-cursor` | ` ` | `ok` / `failed`. | +| `event motion` | ` ` | `ok` / `failed`. | +| `event button` | ` [press\|release\|click]` | `ok` / `failed` (default `click`). | +| `event key` | ` [press\|release\|tap]` | `ok` / `failed` (default `tap`). | + +Pointer buttons use Linux input codes (`left`=0x110, `right`=0x111, +`middle`=0x112, or a numeric code). Keyboard keys use Linux evdev keycodes; +common names are recognised (`esc`, `enter`, `space`, `tab`, `a`–`z`, `0`–`9`, +arrow keys, `f1`–`f12`, `home`/`end`/`pageup`/`pagedown`/`insert`/`del`, …) or a +raw code may be passed. Keys are delivered to the keyboard-focused surface — +`activate` a window first to target it; pointer buttons go to the surface under +the cursor. + +#### Image capture + +Screenshots are rendered server-side and returned to the `treeland-debug` +client as PNG bytes; the client writes them to a file and prints the path. +The compositor itself never touches the filesystem. If `file` is omitted a +path under `/tmp` is generated. + +| Command | Arguments | Output | +| --- | --- | --- | +| `screenshot output` | `[name] [file]` | PNG file path (stdout). | +| `screenshot window` | ` [file]` | PNG file path (stdout). | + +#### Interactive + +| Command | Arguments | Output | +| --- | --- | --- | +| `shell` | _(none)_ | REPL (`treeland>`) accepting all commands plus `help`/`exit`. | +| `help` | _(none)_ | Full help text. | + +### Output formats + +`tree` and `cursor` print a human-readable format by default; pass `--json` for +machine-readable JSON. `windows` and `clients` also default to human-readable +tables and use `--json` for JSON. +Window JSON object (`WindowInfo`): + +| Field | Type | Notes | +| --- | --- | --- | +| `id` | integer | Stable window id (the wl_surface wl_resource pointer); globally unique, accepted by control commands. | +| `appId` | string | Application id. | +| `title` | string | Window title. | +| `output` | string | Output name. | +| `container` | string | Container name. | +| `workspace` | integer | Workspace id. | +| `layer` | integer | Layer id. | +| `z` | integer | Z order. | +| `type` | integer | Window type. | +| `state` | integer | `0` Normal, `1` Maximized, `2` Minimized, `3` Fullscreen, `4` Tiling. | +| `visible` | boolean | Visibility. | +| `active` | boolean | Active / focused flag. | +| `geometry` | object | `{"x","y","width","height"}`. | +| `titlebarGeometry` | object | Same shape. | +| `boundingRect` | object | Same shape. | +| `iconGeometry` | object | Same shape. | +| `position` | object | `{"x","y"}`. | +| `frames` | integer | Number of committed frames (from `wlr_surface`). | +| `damage` | object | Last committed buffer-damage rectangle `{"x","y","width","height"}`. | +| `inputRegion` | array of object | Input region as surface-local boxes (`[{"x","y","width","height"}, ...]`), already clipped to the surface size. An unset (`NULL`) input region is *infinite* per protocol and therefore reads back as one box covering the whole surface; the list is empty only when the client committed an empty region (the surface then accepts no input) or before the surface has committed a buffer. | +| `opaqueRegion` | array of object | Opaque region as surface-local boxes, same shape. Empty means the client declared no opaque area — the protocol default, and also the value before the first commit. It is a repaint optimization hint, not a statement that the window is actually transparent. | + +Client JSON object (`ClientInfo`): `id` (integer), `appId` (string), `pid` +(integer, `0` when unavailable), `executable` (string), `windows` (array of +`WindowInfo`). + +The `tree` JSON is +`{"currentMode": str, "layers": [{"name", "layer", "windows": [WindowInfo], "workspaces": [{"id", "isActive", "windows": [WindowInfo]}]}]}`. + +### Exit codes + +`0` on success; `1` on connection failure, RPC failure, an unknown command, or a +control command that returns `failed`. + +### Usage examples + +All commands run as the `dde` user: + +```bash +# Inspect the window tree (human-readable, default command) +sudo -u dde -- treeland-debug tree + +# Cursor position (xdotool getmouselocation style) +sudo -u dde -- treeland-debug cursor +# → x:960 y:540 window:93824992268800 + +# List windows (one row each; TYPE is the shell surface type) +sudo -u dde -- treeland-debug windows + +# One window in full, xwininfo-style +sudo -u dde -- treeland-debug window 93824992268800 + +# List clients and their windows +sudo -u dde -- treeland-debug clients + +# Live refreshing top view (1 s interval) +sudo -u dde -- treeland-debug top +# (Ctrl+C to quit) + +# Activate a window by id +sudo -u dde -- treeland-debug activate 1407374883553280 + +# Activate a window by appId +sudo -u dde -- treeland-debug activate dde-file-manager + +# Move a window +sudo -u dde -- treeland-debug move 1407374883553280 100 200 + +# Resize a window +sudo -u dde -- treeland-debug resize 1407374883553280 800 600 + +# Move a window to workspace 2 +sudo -u dde -- treeland-debug workspace 1407374883553280 2 + +# Move cursor +sudo -u dde -- treeland-debug move-cursor 960 540 + +# Send a pointer click +sudo -u dde -- treeland-debug event button left click + +# Send a key tap +sudo -u dde -- treeland-debug event key enter tap + +# Screenshot the primary output to a file +sudo -u dde -- treeland-debug screenshot output /tmp/ss.png + +# Screenshot a window (with terminal preview if supported) +sudo -u dde -- treeland-debug screenshot window 1407374883553280 + +# Interactive shell mode +sudo -u dde -- treeland-debug shell +treeland> help +treeland> windows +treeland> exit + +# Machine-readable JSON output +sudo -u dde -- treeland-debug --json windows +sudo -u dde -- treeland-debug --json cursor +``` + +The `top` view refreshes every `interval-ms` (default 1000 ms) using a QTimer. +Each cycle calls `getClients()` via Qt Remote Objects, clears the terminal +(`\033[2J\033[H`), and re-prints a header with the current timestamp and +client count, followed by the client + window table. Press Ctrl+C to stop. +## GitHub Actions / CI + +This project uses GitHub Actions for continuous integration. The following workflows are configured: + +- **waylib builds**: Triggered when `waylib/**` files are modified +- **treeland builds**: Main project builds + +## Getting Involved + +- [Code contribution via GitHub](https://github.com/linuxdeepin/treeland/) +- [Submit bug or suggestions to GitHub Issues or GitHub Discussions](https://github.com/linuxdeepin/developer-center/issues/new/choose) + +## License + +treeland is licensed under Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only. diff --git a/README.zh_CN.md b/README.zh_CN.md new file mode 100644 index 0000000000..3d67bcda07 --- /dev/null +++ b/README.zh_CN.md @@ -0,0 +1,346 @@ +# Treeland + +treeland 是一个基于 wlroots 和 QtQuick 开发的 Wayland 合成器,旨在提供高效且灵活的图形界面支持。 + +## 依赖 + +查看 `debian/control` 文件来了解具体的构建与运行时依赖,或者使用 `cmake` 检查缺失的必要组件。 + +核心构建依赖: + +- [waylib](https://github.com/vioken/waylib) 整合 wlroots 和 QtQuick 的 Wayland 合成器开发库 + - Qt >= 6.8.0 + - wlroots = 0.20 +- [treeland-protocols](https://github.com/linuxdeepin/treeland-protocols) treeland 使用的私有 wayland 协议 + +推荐的运行时依赖: + +- [ddm](https://github.com/linuxdeepin/ddm) 为多用户优化的登录管理器 + +## 构建 + +treeland 使用 cmake 进行构建,`WITH_SUBMODULE_WAYLIB` 选项可以强制使用子模块中的 `waylib` 代码,如果希望使用系统提供的 `waylib` 应该设置为 `OFF`。 + +使用系统库提供的 `waylib`: + +```shell +$ git clone git@github.com:linuxdeepin/treeland.git +$ cd treeland +$ cmake -Bbuild -DWITH_SUBMODULE_WAYLIB=OFF +$ cmake --build build +``` +使用子模块中的 `waylib`: + +```shell +$ git clone git@github.com:linuxdeepin/treeland.git --recursive +$ cd treeland +$ cmake -Bbuild -DWITH_SUBMODULE_WAYLIB=ON +$ cmake --build build +``` + +## 打包 + +在 *deepin* 桌面发行版进行此软件包的构建,我们还提供了一个 `debian` 目录。若要构建软件包,可参照下面的命令进行构建: + +```shell +$ sudo apt build-dep . # 安装构建依赖 +$ dpkg-buildpackage -uc -us -nc -b # 构建二进制软件包 +``` + +## treeland-debug + +`treeland-debug` 是面向运行中 Treeland 合成器的 adb 式命令行检查与控制工具。它通过 +Qt Remote Objects 连接到 Treeland 的调试 Remote Object,提供检查窗口树、控制窗口、 +注入输入事件、抓取截图等子命令。类似 `adb`,它有两种模式: + +- **非 shell(单次执行)模式** —— 默认:`treeland-debug [args]`。 +- **shell 模式** —— 交互式 REPL:`treeland-debug shell`。 + +客户端随 Treeland 正常构建一起编译(默认开启;传 `-DBUILD_TREELAND_DEBUG=OFF` 可跳过): + +```bash +cmake -B build +cmake --build build --target treeland-debug +sudo cmake --install build --component treeland-debug +``` + +### 开启调试 source + +调试 Remote Object 默认关闭:它会把窗口内容和输入注入能力交出去,跑在用户会话里的合成器 +不应默认提供。`remoteDebug` 是它的总开关:开关为开时,Treeland 会 +发布调试 socket,并给连上来的客户端提供窗口树远程数据源——该数据源是个薄 QObject, +只在每次调用时干活,没有客户端连着时不占资源。把开关关掉就完全禁止调试,socket 也会 +一起消失。Release 构建中 socket 只允许 root 连接(权限 0000);Debug 构建 +(`CMAKE_BUILD_TYPE=Debug`)忽略这个开关,始终发布 `-dev` socket 到 +`/tmp/treeland-debug-`(目录 0700,socket 0600),只允许合成器所属 UID 访问。 +以同一 UID 运行 Debug 客户端即可连接,不需要 polkit;Debug 构建即使处于 user mode +也使用这个 dev 目录。`TREELAND_DEBUG_DIR` 可显式覆盖开发目录。Release 会话实例的 +socket 仍位于 `$XDG_RUNTIME_DIR`,在那里只有所属用户(和 root)能连接。 + +Release 构建的 root 限制可以通过调试协议本身临时放开:`treeland-debug no-auth` +(即 `WindowTreeRemote` 的 `requestNoAuth` 方法)请求合成器把它自己的调试目录开到 0711、 +socket 开到 0666,任意本机用户都能连上。只有已经穿过 0000 socket 的调用者才能发这个 +请求,而在 Release 构建里那只有 root:0000 连合成器用户自己也挡住,只有 +`CAP_DAC_OVERRIDE` 能过。这次连接本身就是鉴权——所以开窗总要 root 过一次 `pkexec` 认证, +而窗口期内连上来的用户全程无需密码。窗口 30 分钟后自动关闭; +开着的每一次远程调用都会把窗口重新推后 30 分钟,所以忘记关闭也不会比「闲置半小时」敞开 +更久。关闭时窗口期内建立的连接也会被一并断开,所以挂着一个客户端并不能把窗口留住。 + +只有全局服务会得到这个窗口,而且只放宽它自己的目录:`/run/treeland-debug` +(`RuntimeDirectory=treeland-debug`),绝不是它的 `$XDG_RUNTIME_DIR`(`/run/treeland`)—— +Qt 要求后者保持 0700,否则新会话的 wayland socket 会落到 `$TMPDIR`。会话模式下 +Treeland 位于 `/run/user/` 里,该目录同时还放着会话总线和其它会话 socket,因此 +那里不会放宽目录权限,仍然需要 root。 + +窗口只存在于内存里,进程不在就什么都不剩:崩溃或重启回来就是 root-only,即使上一个 +进程带着打开的窗口死掉,启动时也会重新收回每个 socket。目录本身只在第一次开窗时放宽一次 +(0711,可穿越不可列目录),之后一直保持到进程退出——多个实例可能共用这个目录,一个实例 +收窗不能把另一个还在开窗的实例切断;systemd 下次启动时会把目录重建为 0700。实际把门的是 +socket 自身的权限位。窗口开着时可以同时挂多个客户端。如果读不到 socket,要么 +开关被关了,要么 Treeland 没在运行——客户端会直接在 stderr 上说明并指向这个开关。 +切换 `remoteDebug` 即时生效:远程源会动态创建或销毁,无需重启。 + +用 `treeland-debug debug on` / `treeland-debug debug off` 切换(不带参数的 `debug` +打印当前状态)。开关是按用户存放的 DConfig 键,Treeland 只读自己运行用户的那个,因此该 +命令会从运行中的合成器查到这个用户,不是你本人时通过 `pkexec` 提权(`--no-escalate` +只报告需要提权而不弹认证)。它在底层以 root 执行等价于: + +```bash +dde-dconfig -u <合成器 uid> set \ + -a org.deepin.dde.treeland \ + -r org.deepin.dde.treeland \ + -k remoteDebug \ + -v true +``` + +下文所有命令均以 `dde` 用户运行,例如 `sudo -u dde -- treeland-debug windows`。 + +### socket 命名与连接 + +Treeland 在本地 socket 上发布调试源,默认名为 `org.deepin.dde.treeland.debug`,绑定在 +合成器自己的目录里的绝对路径上:全局 Release 服务为 +`/run/treeland-debug/org.deepin.dde.treeland.debug`,Release 会话模式为 +`/run/user//...`(即 `$XDG_RUNTIME_DIR`)。Debug dev 构建(包括 user mode)默认使用 +`/tmp/treeland-debug-/...`(目录 0700、socket 0600),普通用户只有所属 UID 可访问; +root 仍保留特权访问。这样可以避免写入宿主 `/run`;`TREELAND_DEBUG_DIR` 是显式开发/测试 +覆盖项。全局 Release 目录由 systemd 以 0700 创建,且刻意不使用 `$XDG_RUNTIME_DIR`—— +免鉴权窗口会把它开到 0711,而 Qt 要求 runtime 目录保持 0700。 + +Debug 客户端先探测自己的 dev 目录,再探测共享的 `/run/treeland-debug`、legacy +`/run/treeland` 和自己的 runtime 目录,不枚举其他 UID 的 runtime socket。Release root +客户端保留原有探测顺序,并可列出每个 `/run/user/` 目录。 +当该名称已被另一个正在运行的 treeland(全局服务、会话服务、本地构建)占用时,会自动追加数字 +后缀(`org.deepin.dde.treeland.debug-1`、`-2`…),通过非阻塞 advisory lock 选择 +(与 libwayland 选择 Wayland socket 的方式一致)。崩溃实例残留的 socket 文件会被 +回收,而无锁文件的旧版本实例会被探测并跳过。 + +Debug 构建使用不同的默认名(`org.deepin.dde.treeland.debug-dev`),因此调试版与正式版 +treeland 可同时运行。Debug 构建的 treeland-debug 客户端自动优先连接调试实例,连不上时 +回退到正式版实例;Release 构建的客户端连接正式版实例。socket 的选择顺序是:`--url`、 +`$TREELAND_DEBUG_SOCKET`(socket 路径或裸名,等价于 `local:<值>`;带 scheme 的值原样使用)、 +然后是上面的自动探测。显式 URL 始终优先,不做任何隐式处理 —— 它也是连接旧版 treeland +留在迁移前 `/tmp/` 的 socket 的方式:`--url local:/tmp/org.deepin.dde.treeland.debug`。 + +每次建立连接的运行结束时都会在 stderr 上说明数据来自哪个 socket(`treeland-debug: connected to +local:...`),shell 模式则在进入时以 login 信息的形式给出同一句话,所以粘贴出来的输出 +始终能看出属于哪个实例。`help`、`--version`、`debug`、`listen` 不建立调试连接,不会输出这行。 +`(fallback from ...)` 属于客户端自身的探测细节,只有 +`--log-level debug` 才会输出。 + +### 全局选项 + +| 选项 | 默认值 | 说明 | +| --- | --- | --- | +| `--url ` | `$TREELAND_DEBUG_SOCKET`,否则自动:Debug 构建优先调试 socket 并回退到正式版 socket,再否则正式版 socket | Remote object host URL。 | +| `--name ` | `WindowTree` | Remote object 名称。 | +| `--timeout-ms ` | `30000` | 请求超时(毫秒,非负整数)。 | +| `--json` | 关 | 为 `tree`/`cursor`/`windows`/`clients` 输出机器可读 JSON。 | +| `--preview` | 自动 | 强制在终端内联显示截图预览(默认自动检测终端)。 | +| `--no-preview` | 关 | 关闭终端内联截图预览。 | +| `--log-level ` | `info` | 本客户端自身 stderr 诊断的详细程度:`error`、`warning`、`info`、`debug`。目前只有 `info` 与 `debug` 有实际差别:`debug` 额外说明回退连接来自哪个 socket;`error`/`warning` 暂时没有更安静的效果。 | +| `-h, --help` | — | 显示帮助。 | +| `-v, --version` | — | 显示版本。 | +| `--tree` / `--cursor` | — | `tree` / `cursor` 命令的向后兼容别名。 | + +### 命令参考 + +窗口控制命令的目标可用**数字 `id`**(由 `windows`/`clients`/`top` 打印)或 **`appId`** +(取第一个匹配的窗口)指定。 + +#### 检查 + +| 命令 | 参数 | 输出 | +| --- | --- | --- | +| `tree` | _(无,默认)_ | 布局树(人读格式;`--json` 输出 JSON)。 | +| `cursor` | _(无)_ | 光标位置,xdotool 风格 `x:… y:… window:…`(`--json` 输出 `{"x","y","window"}`)。 | +| `windows` | _(无)_ | 窗口表格,含 shell 类型 `TYPE` 列;`--json` 输出 JSON 数组。 | +| `window` | `` | 单个窗口的完整信息(xwininfo 风格 `Key: value` 块);`--json` 输出该窗口的 JSON。 | +| `clients` | _(无)_ | 客户端 + 窗口表格;`--json` 输出 JSON 数组。 | +| `top` | `[interval-ms]`(默认 1000) | 实时刷新的 top 式客户端视图(Ctrl+C 退出)。 | + +#### 窗口控制 + +| 命令 | 参数 | 输出 | +| --- | --- | --- | +| `activate` | `` | `ok` / `failed`。 | +| `close` | `` | `ok` / `failed`。 | +| `minimize` | `` | `ok` / `failed`。 | +| `maximize` | `` | `ok` / `failed`(切换最大化)。 | +| `fullscreen` | `` | `ok` / `failed`(切换全屏)。 | +| `move` | ` ` | `ok` / `failed`。 | +| `resize` | ` ` | `ok` / `failed`。 | +| `workspace` | ` ` | `ok` / `failed`(移动窗口到工作区)。 | + +#### 输入 / 事件注入 + +| 命令 | 参数 | 输出 | +| --- | --- | --- | +| `move-cursor` | ` ` | `ok` / `failed`。 | +| `event motion` | ` ` | `ok` / `failed`。 | +| `event button` | ` [press\|release\|click]` | `ok` / `failed`(默认 `click`)。 | +| `event key` | ` [press\|release\|tap]` | `ok` / `failed`(默认 `tap`)。 | + +指针按键使用 Linux input 码(`left`=0x110、`right`=0x111、`middle`=0x112,或数字码)。 +键盘按键使用 Linux evdev 键码;支持常见名称(`esc`、`enter`、`space`、`tab`、`a`–`z`、 +`0`–`9`、方向键、`f1`–`f12`、`home`/`end`/`pageup`/`pagedown`/`insert`/`del` 等),也可直接传 +原始码。按键发送到当前键盘焦点 surface——先用 `activate` 激活目标窗口;指针按键发送到 +光标所在 surface。 + +#### 图像抓取 + +截图在服务端渲染后以 PNG 字节返回给 `treeland-debug` 客户端,由客户端写入文件并打印路径;合成器本身不碰文件系统。省略 `file` 时在 `/tmp` 下自动生成路径。 + +| 命令 | 参数 | 输出 | +| --- | --- | --- | +| `screenshot output` | `[name] [file]` | PNG 文件路径(stdout)。 | +| `screenshot window` | ` [file]` | PNG 文件路径(stdout)。 | + +#### 交互 + +| 命令 | 参数 | 输出 | +| --- | --- | --- | +| `shell` | _(无)_ | REPL(`treeland>`),接受所有命令及 `help`/`exit`。 | +| `help` | _(无)_ | 完整帮助文本。 | + +### 输出格式 + +`tree` 和 `cursor` 默认输出人读格式;传 `--json` 输出机器可读 JSON。`windows` 和 +`clients` 同样默认输出人读表格,加 `--json` 输出 JSON 数组。 + +窗口 JSON 对象(`WindowInfo`): + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `id` | integer | 稳定窗口 id(wl_surface 的 wl_resource 指针),全局唯一,可被控制命令使用。 | +| `appId` | string | 应用 id。 | +| `title` | string | 窗口标题。 | +| `output` | string | 输出名。 | +| `container` | string | 容器名。 | +| `workspace` | integer | 工作区 id。 | +| `layer` | integer | 层 id。 | +| `z` | integer | Z 序。 | +| `type` | integer | 窗口类型。 | +| `state` | integer | `0` Normal、`1` Maximized、`2` Minimized、`3` Fullscreen、`4` Tiling。 | +| `visible` | boolean | 可见性。 | +| `active` | boolean | 是否激活/聚焦。 | +| `geometry` | object | `{"x","y","width","height"}`。 | +| `titlebarGeometry` | object | 同上结构。 | +| `boundingRect` | object | 同上结构。 | +| `iconGeometry` | object | 同上结构。 | +| `position` | object | `{"x","y"}`。 | +| `frames` | integer | 已提交帧数(取自 `wlr_surface`)。 | +| `damage` | object | 上次提交的缓冲区刷新区域 `{"x","y","width","height"}`。 | +| `inputRegion` | array of object | 输入区域,surface 局部坐标的 box 列表(`[{"x","y","width","height"}, ...]`),已按 surface 尺寸裁剪。按协议,未设置(`NULL`)的输入区域是**无穷大**,因此读回来是覆盖整面的一个 box;只有客户端提交了空 region(表示该 surface 不接受输入)或 surface 尚未提交过 buffer 时,列表才为空。 | +| `opaqueRegion` | array of object | 不透明区域,结构同上;为空表示客户端没有声明不透明区域(协议默认值,首次 commit 前也是这个值);它只是重绘优化提示,不代表窗口真的透明。 | + +客户端 JSON 对象(`ClientInfo`):`id`(integer)、`appId`(string)、`pid`(integer,不可用时为 `0`)、 +`executable`(string)、`windows`(`WindowInfo` 数组)。 + +`tree` JSON 结构为 +`{"currentMode": str, "layers": [{"name", "layer", "windows": [WindowInfo], "workspaces": [{"id", "isActive", "windows": [WindowInfo]}]}]}`。 + +### 退出码 + +成功返回 `0`;连接失败、RPC 失败、未知命令或控制命令返回 `failed` 时返回 `1`。 + +### 使用示例 + +以下命令均以 `dde` 用户运行: + +```bash +# 查看窗口树(人读格式,默认命令) +sudo -u dde -- treeland-debug tree + +# 光标位置(xdotool 风格) +sudo -u dde -- treeland-debug cursor +# → x:960 y:540 window:93824992268800 + +# 列出窗口 +sudo -u dde -- treeland-debug windows + +# 列出客户端及其窗口 +sudo -u dde -- treeland-debug clients + +# 实时刷新的 top 视图(1 秒间隔) +sudo -u dde -- treeland-debug top +# (Ctrl+C 退出) + +# 按 id 激活窗口 +sudo -u dde -- treeland-debug activate 1407374883553280 + +# 按 appId 激活窗口 +sudo -u dde -- treeland-debug activate dde-file-manager + +# 移动窗口 +sudo -u dde -- treeland-debug move 1407374883553280 100 200 + +# 调整窗口大小 +sudo -u dde -- treeland-debug resize 1407374883553280 800 600 + +# 移动窗口到工作区 2 +sudo -u dde -- treeland-debug workspace 1407374883553280 2 + +# 移动光标 +sudo -u dde -- treeland-debug move-cursor 960 540 + +# 发送一次指针点击 +sudo -u dde -- treeland-debug event button left click + +# 发送一次按键 +sudo -u dde -- treeland-debug event key enter tap + +# 截图主输出到文件 +sudo -u dde -- treeland-debug screenshot output /tmp/ss.png + +# 截取窗口(终端支持时内联预览) +sudo -u dde -- treeland-debug screenshot window 1407374883553280 + +# 交互式 shell 模式 +sudo -u dde -- treeland-debug shell +treeland> help +treeland> windows +treeland> exit + +# 机器可读 JSON 输出 +sudo -u dde -- treeland-debug --json windows +sudo -u dde -- treeland-debug --json cursor +``` + +`top` 视图使用 QTimer 按 `interval-ms`(默认 1000 毫秒)周期刷新。每个周期通过 +Qt Remote Objects 调用 `getClients()`,清屏(`\033[2J\033[H`)后重新打印带当前 +时间戳与客户端数量的表头,随后是客户端 + 窗口表格。按 Ctrl+C 退出。 +## GitHub Actions / 持续集成 + +本项目使用 GitHub Actions 进行持续集成。配置了以下工作流: + +- **waylib 构建**:当 `waylib/**` 文件被修改时触发 +- **treeland 构建**:主项目构建 + +## 参与贡献 + +- [通过 GitHub 发起代码贡献](https://github.com/linuxdeepin/treeland/) +- [通过 GitHub Issues 与 GitHub Discussions 汇报缺陷与反馈建议](https://github.com/linuxdeepin/developer-center/issues/new/choose) + +## 许可协议 + +**Treeland** 使用 Apache-2.0, LGPL-3.0-only, GPL-2.0-only 或 GPL-3.0-only 许可协议进行发布。 diff --git a/REUSE.toml b/REUSE.toml new file mode 100644 index 0000000000..0649b565e8 --- /dev/null +++ b/REUSE.toml @@ -0,0 +1,241 @@ +version = 1 +SPDX-PackageName = "treeland" +SPDX-PackageDownloadLocation = "https://github.com/linuxdeepin/treeland" + +[[annotations]] +path = [".github/**", ".obs/**.yml", "garnix.yaml", ".tx/*"] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = [".clang-format", ".editorconfig", "**.frag", "**.ui", "**.vert", "**/qmldir"] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = ["debian/**", "rpm/**", "archlinux/**"] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = ["**.nix", ".envrc", "flake.lock", "renovate.json"] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = ["translations/**", "po/**", "**.qm", "**.ts"] +precedence = "aggregate" +SPDX-FileCopyrightText = "UnionTech Software Technology Co., Ltd." +SPDX-License-Identifier = "GPL-2.0-only" + +[[annotations]] +path = ["**.svg", "**.png", "**.jpg", "**.jpeg", "**.webp", "**.dci", "**.gif"] +precedence = "aggregate" +SPDX-FileCopyrightText = "UnionTech Software Technology Co., Ltd." +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = ["REUSE.toml", "**.json", "**.service", "**.txt", "**.ini", "**.sh", "**.html", ".gitignore", ".gitmodules", "INSTALL.md", "**.desktop", "**.css", "**.ttf", "**.conf", "**.xml", ".release.json"] +precedence = "aggregate" +SPDX-FileCopyrightText = "UnionTech Software Technology Co., Ltd." +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = ["**.md", "README.md", "README.zh_CN.md", "CONTRIBUTING.md", "ChangeLog", "CONTRIBUTORS"] +precedence = "aggregate" +SPDX-FileCopyrightText = "UnionTech Software Technology Co., Ltd." +SPDX-License-Identifier = "CC-BY-4.0" + +[[annotations]] +path = ["**.cmake", "CMakeLists.txt", "**.in", "**.qrc", "misc/**", "services/**", "releng/create_changelog.pl"] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "GPL-2.0-only" + +# ===== 3RDPARTY wlroots (vendored upstream) REUSE Configuration ===== +# wlroots upstream ships NO per-file SPDX headers; it relies on a root MIT +# LICENSE plus textual copyright blocks in xcursor/ and protocol/*.xml. +# In a single REUSE.toml, reuse resolves multiple matching [[annotations]] +# blocks by LAST-match-wins (it returns the last matching block in file +# order, not the most path-specific one). Therefore the broad MIT fallback +# is listed FIRST, and the narrower exception blocks are listed AFTER it so +# they take precedence for their specific files. + +# General fallback for the rest of vendored wlroots (MIT). +[[annotations]] +path = ["3rdparty/wlroots/**"] +precedence = "aggregate" +SPDX-FileCopyrightText = "wlroots contributors" +SPDX-License-Identifier = "MIT" + +# tinywl example: CC0 / public domain (tinywl/LICENSE) +[[annotations]] +path = ["3rdparty/wlroots/tinywl/**"] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "CC0-1.0" + +# server-decoration.xml: KDE/KWin protocol (LGPL-2.1-or-later, Martin Gräßlin) +[[annotations]] +path = ["3rdparty/wlroots/protocol/server-decoration.xml"] +precedence = "aggregate" +SPDX-FileCopyrightText = "2015 Martin Gräßlin" +SPDX-License-Identifier = "LGPL-2.1-or-later" + +# HPND-style protocol XMLs ("Permission to use, copy, modify, distribute, and sell ... without fee") +[[annotations]] +path = [ + "3rdparty/wlroots/protocol/drm.xml", + "3rdparty/wlroots/protocol/wlr-data-control-unstable-v1.xml", + "3rdparty/wlroots/protocol/wlr-foreign-toplevel-management-unstable-v1.xml", + "3rdparty/wlroots/protocol/wlr-gamma-control-unstable-v1.xml", + "3rdparty/wlroots/protocol/wlr-layer-shell-unstable-v1.xml", + "3rdparty/wlroots/protocol/wlr-output-management-unstable-v1.xml", +] +precedence = "aggregate" +SPDX-FileCopyrightText = "wlroots contributors" +SPDX-License-Identifier = "HPND" + +[[annotations]] +path = ["src/greeter/**.h", "src/greeter/**.cpp"] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "GPL-2.0-only" + +# ===== WAYLIB REUSE Configuration ===== +# CI and build files for waylib +[[annotations]] +path = ["waylib/.github/**", "waylib/.obs/**.yml", "waylib/renovate.json"] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "CC0-1.0" + +# Gitignore and git modules for waylib +[[annotations]] +path = ["waylib/.gitignore", "waylib/.gitmodules"] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "CC0-1.0" + +# Project files for waylib +[[annotations]] +path = ["waylib/**.cmake", "waylib/*CMakeLists.txt", "waylib/**.pc.in", "waylib/**cmake.in"] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "CC0-1.0" + +# README for waylib +[[annotations]] +path = ["waylib/README.md", "waylib/README.zh_CN.md"] +precedence = "aggregate" +SPDX-FileCopyrightText = "JiDe Zhang" +SPDX-License-Identifier = "CC-BY-4.0" + +# Nix Develop files for waylib +[[annotations]] +path = ["waylib/**.nix", "waylib/.envrc", "waylib/flake.lock"] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "CC0-1.0" + +# Debian package for waylib +[[annotations]] +path = ["waylib/debian/**"] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "CC0-1.0" + +# C++ pch files for waylib +[[annotations]] +path = ["waylib/src/server/pch/pch.hxx"] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "CC0-1.0" + +# Core waylib files +[[annotations]] +path = [ + "waylib/examples/tinywl/qml.qrc", + "waylib/tests/manual/cursor/cursor.qrc", + "waylib/src/server/kernel/WBackend", + "waylib/src/server/kernel/WCursor", + "waylib/src/server/kernel/WInputDevice", + "waylib/src/server/kernel/WInputEvent", + "waylib/src/server/kernel/WOutput", + "waylib/src/server/kernel/WSeat", + "waylib/src/server/kernel/WEvent", + "waylib/src/server/kernel/WServer", + "waylib/src/server/kernel/WServerInterface", + "waylib/src/server/kernel/WSurface", + "waylib/src/server/kernel/WSurfaceLayout", + "waylib/src/server/kernel/WSubsurface", + "waylib/src/server/kernel/WTexture", + "waylib/src/server/kernel/WXdgShell", + "waylib/src/server/kernel/WXdgSurface", + "waylib/src/server/kernel/WLayerSurface", + "waylib/src/server/qtquick/WQuickRenderControl", + "waylib/src/server/qtquick/WSurfaceItem", + "waylib/src/server/utils/WSignalConnector", + "waylib/src/server/utils/WThreadUtils", + "waylib/src/server/utils/WCursorImage", + "waylib/src/server/utils/WWrapPointer", + "waylib/tests/main.cpp", + "waylib/tests/test.h" +] +precedence = "aggregate" +SPDX-FileCopyrightText = "JiDe Zhang" +SPDX-License-Identifier = "Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only" + +# Waylib protocol files +[[annotations]] +path = [ + "waylib/src/server/protocols/WCursorShapeManagerV1", + "waylib/src/server/protocols/WForeignToplevel", + "waylib/src/server/protocols/WInputMethodHelper", + "waylib/src/server/protocols/WLayerSurface", + "waylib/src/server/protocols/WOutputManagerV1", + "waylib/src/server/protocols/WRelativePointerManagerV1", + "waylib/src/server/protocols/WXdgOutput", + "waylib/src/server/protocols/WXdgShell", + "waylib/src/server/protocols/WXdgSurface", + "waylib/src/server/protocols/WLayerShell", + "waylib/src/server/protocols/WInputPopupSurface", + "waylib/src/server/protocols/WXWayland", + "waylib/src/server/protocols/WXWaylandSurface", + "waylib/src/server/protocols/WXdgDecorationManager", + "waylib/src/server/protocols/WSessionLock", + "waylib/src/server/protocols/WSessionLockManager", + "waylib/src/server/protocols/WSessionLockSurface", + "waylib/src/server/protocols/WPointerConstraintsV1", +] +precedence = "aggregate" +SPDX-FileCopyrightText = "UnionTech Software Technology Co., Ltd." +SPDX-License-Identifier = "Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only" + +# Misc files for waylib +[[annotations]] +path = [ + "waylib/tests/manual/cursor/res/HandCursor.png", + "waylib/examples/tinywl/res/xx.jpg" +] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "CC0-1.0" + +# Protocol files with HPND license for waylib +[[annotations]] +path = ["waylib/src/server/protocols/private/text-input-unstable-v2.xml"] +precedence = "aggregate" +SPDX-FileCopyrightText = "None" +SPDX-License-Identifier = "HPND" + +# Vendored wlroots extra files for waylib (MIT, upstream wlroots) +[[annotations]] +path = ["waylib/src/server/wlroots_extra/**"] +precedence = "aggregate" +SPDX-FileCopyrightText = "wlroots contributors" +SPDX-License-Identifier = "MIT" diff --git a/cmake/DefineTarget.cmake b/cmake/DefineTarget.cmake new file mode 100644 index 0000000000..d153102cee --- /dev/null +++ b/cmake/DefineTarget.cmake @@ -0,0 +1,60 @@ +include(CMakeParseArguments) + +function(impl_treeland) + set(one_value_args NAME) + set(multi_value_args SOURCE INCLUDE LINK) + + cmake_parse_arguments( + PARSE_ARG_PREFIX + "" + "${one_value_args}" + "${multi_value_args}" + ${ARGN} + ) + + if(NOT PARSE_ARG_PREFIX_NAME) + message(FATAL_ERROR "NAME is a required argument!") + endif() + + add_library(${PARSE_ARG_PREFIX_NAME} INTERFACE) + + target_sources(${PARSE_ARG_PREFIX_NAME} + INTERFACE + ${PARSE_ARG_PREFIX_SOURCE} + ) + + target_include_directories(${PARSE_ARG_PREFIX_NAME} + INTERFACE + ${PARSE_ARG_PREFIX_INCLUDE} + $ + $ + $ + $ + ) + + target_link_libraries(${PARSE_ARG_PREFIX_NAME} + INTERFACE + ${PARSE_ARG_PREFIX_LINK} + + # TODO: remove this + Dtk6::Core + Dtk6::Declarative + Dtk6::SystemSettings + Waylib::WaylibServer + Qt6::Quick + Qt6::QuickControls2 + Qt6::QuickPrivate + Qt6::DBus + Qt6::Concurrent + PkgConfig::PIXMAN + PkgConfig::WAYLAND + PkgConfig::LIBINPUT + # TODO: end remove + ) + + target_link_libraries(libtreeland + PRIVATE + ${PARSE_ARG_PREFIX_NAME} + ) +endfunction() + diff --git a/cmake/TranslationUtils.cmake b/cmake/TranslationUtils.cmake new file mode 100644 index 0000000000..0bd97e4be8 --- /dev/null +++ b/cmake/TranslationUtils.cmake @@ -0,0 +1,62 @@ +# TranslationUtils.cmake +# Provides common functions for handling translation files + +function(setup_translations TARGET_NAME TRANSLATION_PREFIX) + # Automatically discover all translation files + file(GLOB TS_FILES "${CMAKE_CURRENT_SOURCE_DIR}/translations/${TRANSLATION_PREFIX}.*.ts") + + # Filter out non-translation files (if any) + list(FILTER TS_FILES INCLUDE REGEX ".*\\.ts$") + + # Set translation files variable + set(TRANSLATED_FILES) + + # Add lupdate target + qt_add_lupdate( + SOURCE_TARGETS ${TARGET_NAME} + TS_FILES ${TS_FILES} + NO_GLOBAL_TARGET + ) + + # Add lrelease target + qt_add_lrelease( + TS_FILES ${TS_FILES} + QM_FILES_OUTPUT_VARIABLE TRANSLATED_FILES + ) + + # Install translation files + install(FILES ${TRANSLATED_FILES} DESTINATION ${TREELAND_COMPONENTS_TRANSLATION_DIR}) + + # Set TRANSLATED_FILES variable to parent scope + set(TRANSLATED_FILES ${TRANSLATED_FILES} PARENT_SCOPE) +endfunction() + +function(setup_main_translations TARGET_NAME) + # Automatically discover all main translation files + file(GLOB TS_FILES "${CMAKE_SOURCE_DIR}/translations/treeland.*.ts") + + # Filter out non-translation files (if any) + list(FILTER TS_FILES INCLUDE REGEX ".*\\.ts$") + + # Set translation files variable + set(TRANSLATED_FILES) + + # Add lupdate target + qt_add_lupdate( + SOURCE_TARGETS ${TARGET_NAME} + TS_FILES ${TS_FILES} + NO_GLOBAL_TARGET + ) + + # Add lrelease target + qt_add_lrelease( + TS_FILES ${TS_FILES} + QM_FILES_OUTPUT_VARIABLE TRANSLATED_FILES + ) + + # Install translation files + install(FILES ${TRANSLATED_FILES} DESTINATION ${TREELAND_COMPONENTS_TRANSLATION_DIR}) + + # Set TRANSLATED_FILES variable to parent scope + set(TRANSLATED_FILES ${TRANSLATED_FILES} PARENT_SCOPE) +endfunction() diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 0000000000..18cb38bf02 --- /dev/null +++ b/debian/changelog @@ -0,0 +1,1052 @@ +treeland (0.12.0) unstable; urgency=medium + + * test(foreign-toplevel): disable geometry animation in protocol test + * feat(dockpreview): take the preview radii from DTK's menu and + tooltip + * feat(dock-preview): add scroll hints to preview thumbnail and list + * fix: prevent protocol test timeouts from leaked services + * fix(shortcut): drop emptied key combination from key map + * refactor(session): tidy up session components + * refactor(surface): centralize window frame geometry and clipping + * fix: login fails after retrying with the correct password + * fix: show the lock icon only on the locked user's lockscreen + * fix(input): restore input to remote subsurfaces + * fix: Relayout multitask thumbnails when the dock resizes + * fix(dock-preview): hide close-all while hovering a thumbnail slot + * refactor(glass): drop redundant itemSize handling in the shader + * fix(input): prevent duplicate pointer gestures globals across + sessions + + -- rewine Wed, 18 Nov 2026 13:20:58 +0800 + +treeland (0.11.0) unstable; urgency=medium + + * fix(treeland-debug): fall back to the compositor runtime directory when + the global debug socket directory is not writable + * fix(treeland-debug): put development sockets in per-uid /tmp directories + * fix(session): store logind session id as string to avoid collision + * fix(input-method): forward empty preedit to clear composing + * feat(dde-shell): adapt to dde-shell-unstable-v2 protocol + * feat(snap-target): add treeland-snap-target-unstable-v1 module + * fix(shell): only start interactive resize for resizable surfaces + * refactor(modules): drop redundant wl_resource type checks + * fix(xwayland): refresh user Xauthority after Xwayland restart + * fix(lockscreen): correct lock screen item layer ordering + * feat(compositor-action): add shared shell-action execution for + compositor & shortcuts + * fix(output): wait for output DConfig before adding outputs + * feat: add XKB settings to input manager + * fix(greeter): dedup users and resolve accounts by uid + * feat(input): support per-seat user DConfig + + -- rewine Sat, 10 Oct 2026 11:34:34 +0800 + +treeland (0.10.0) unstable; urgency=medium + + * feat(foreign-toplevel): adapt to treeland-foreign-toplevel-manager + v2 + * refactor: adapt window-management to treeland-show-desktop-v1 + protocol + * fix(shell): keep close animation in place on activation transfer + * fix(xwayland): allow cross-UID MIT-SHM via + AmbientCapabilities=CAP_IPC_OWNER + * fix(screensaver): release inhibit silently in destroy + * refactor: adapt to treeland-protocols unstable-v2 and wine naming + * fix(xwayland): synchronize transient window stacking + * fix: track exported surface lifetime natively to prevent bad object + crash + * fix(xwayland): preserve compositor-controlled resize geometry + * fix(surface): avoid null shell surface on XWayland teardown + * fix(surface): retarget pending state animations + + -- rewine Thu, 10 Sep 2026 19:42:05 +0800 + +treeland (0.9.1) unstable; urgency=medium + + * feat(greeter): support undecided state waiting for DDM decision + * test(protocols): forcibly reap test service helpers + * refactor: replace hardcoded etc path with CMake variable + * fix(xwayland): honor client resize configure requests + * refactor: extract set_region lambda to member function + * refactor(surface): drop redundant fullscreen re-arrangement + * feat(keyboard-shortcuts-inhibit): implement + zwp_keyboard_shortcuts_inhibit_v1 server + * refactor(surface): move quick tile logic into SurfaceWrapper + * fix(xwayland): handle size hint updates + * fix(tests): remove unused protocols subdirectory build + * fix(protocol): correct output manager protocol path + * fix(xwayland): acknowledge client configure requests + * refactor(multi-output): rename primary/copy outputs to source/mirror + * feat: support wp_single_pixel_buffer_manager_v1 protocol + * fix: avoid invalid pointer constraint warp + * fix(surface): set maximized on initial surface commit + * feat(multi-output): forward client fullscreen output to surface + handler + * fix: extract protocol interface versions into static constexpr + InterfaceVersion + * fix: avoid QGuiApplication static destruction crash + + -- rewine Fri, 28 Aug 2026 10:48:49 +0800 + +treeland (0.9.0) unstable; urgency=medium + + * feat: support pointer-constraints protocol + * feat: support relative pointer motion + * feat: gate dev file installation behind TREELAND_INSTALL_DEV option + (default OFF) + * chore: update wlroots to 0.20.0 + * fix: use WPointer for cursorClient and skip redundant cursor updates + + -- rewine Fri, 21 Aug 2026 14:49:32 +0800 + +treeland (0.8.18) unstable; urgency=medium + + * fix(output): skip configuration callbacks on initialization failure + * fix(xwayland): synchronize EWMH desktop properties + * fix(xwayland): displayed incorrectly when maximized during + initialization + * feat: remove qwlroots dependency, use wlroots C API directly + * fix: remove WBackend::activateSession/deactivateSession hack + * fix(xsettings): format XResources with tab separators + * refactor(output): centralize output ID generation + * fix(multitaskview): skip hover-driven focus during animation and + exit + * fix(lockscreen): add Vulkan-specific Blur placeholder + * fix(waylib): fix Vulkan scanout RT via wlroots render_buffer + * fix(greeter): fall back to NSS when logged-in user missing from + UserModel + * feat: add containerOf utility for struct member offset calculation + * feat(shortcut): add TileLeft/TileRight shortcuts + * fix(tile): reposition window under cursor when de-tiling on move + begin + + -- rewine Fri, 14 Aug 2026 15:07:39 +0800 + +treeland (0.8.17) unstable; urgency=medium + + * fix(seat): restore group keyboard when virtual keyboard is destroyed + * fix(gesture): fix workspace gesture issues and add lock screen + guards + * fix(input): update cursor from DnD action + * fix(output): avoid enabling output before restoring topology + * fix(glass): pull refraction to lip and retune glass defaults + * fix(animation): smooth minimize transitions + * feat(glass): implement Liquid Glass effect with smooth corner + deformation + * fix(multitaskview): resolve transition, gesture and workspace + switching issues + * fix(output): prevent repeated repositioning of child windows across + outputs + * fix(surface): child may remain below parent after XdgToplevel + set_parent + * fix(task-switcher): restore surface state after interrupted exit + * fix(surface): fix skipSwitcher/skipMultitaskView for X11 surfaces + * feat(waylib): add _NET_WM_WINDOW_TYPE_DIALOG support for XWayland + * fix(surface): add m_wrapperAboutToRemove guard to updateBoundingRect + + -- rewine Fri, 31 Jul 2026 10:50:39 +0800 + +treeland (0.8.16) unstable; urgency=medium + + * fix(waylib/xwayland): deny Activate for surfaces without Focus + capability + * fix(workspace): activate focus on touchpad gesture workspace switch + * feat: set fcitx input method environment in session service + * fix(input): trigger hold gesture immediately with configurable + timeout + * fix(input): filter hold gestures by finger count at start + * fix(output): restore configured topology after output reconnect + * fix: fix XWayland cursor truncation on fractional-scaled multi- + monitor + * fix: resolve sfinae and qml type registration warnings + * fix(task-switcher): preserve surface positions during exit + * fix(surface): remove cached subsurface state + * fix(surface): distinguish popup/IME/drag keyboard grabs + * fix(surface): track subsurface teardown independently + * fix(taskswitch): reset currentMode when dismissed by mouse click + * fix(output): detach proxy hardware layers before output teardown + * fix(lockscreen): reposition caps indicator and center password input + * feat(wm): implement show-desktop via taskbar click + + -- rewine Fri, 24 Jul 2026 11:21:58 +0800 + +treeland (0.8.15) unstable; urgency=medium + + * fix(lockscreen): accept numpad Enter key for password submission + * fix(seat): clear keyboard focus for all seats on internal QML focus + * fix(greeter): reconnect to DDM on service changes + * refactor(surface): merge PopupFocusManager into SeatSurfaceManager + * fix(tools): replace Python WindowTree client replace + * refactor: use Q_ENUM reflection for ShortcutAction name logging + * refactor: remove built-in shortcut daemon (treeland-shortcut) + * fix: improve shortcut event dispatch and Alt+Tab task switch + reliability + * fix(workspace): reload workspace config after DConfig initialized + * fix(seat): add keyboardFocusPriority check in + setKeyboardFocusSurface + * fix(activation): pass seat through activation pipeline for multi- + seat + * fix: avoid writes when querying personalization state + * refactor(keyboard-focus): unify focus management path + * fix: correct shadow rendering during layer shell window animations + * fix: allow Video Bus brightness shortcuts + * fix(wallpaper): resend all wallpapers after output reconnect + * refactor: consolidate surface capability init + * fix: auto-wake DPMS-off outputs on input events + * fix(wallpaper): restore wallpapers after output reconnect + * fix(effects): tune liquid glass defaults and disable dispersion + * fix(effects): smooth glass edges and optimize liquidglass shader + + -- rewine Fri, 17 Jul 2026 13:02:47 +0800 + +treeland (0.8.14) unstable; urgency=medium + + * fix(output): ignore saved disabled state during restore + * fix(greeter): activate DDM user sessions atomically + * feat(effects): implement iOS 26 Liquid Glass effect with reusable + components + * refactor(seat): unify surface activation paths and add per-seat + support + * feat(popup): replace mouse-intercept popup handling with keyboard + grab tracking + * fix: unify layer surface focus handling + * fix: refactor keyboard focus handling logic + * refactor: consolidate active capability checks + * fix(shortcut): clear app filter for all-app task switch + * fix(xwayland): X11 apps cannot connect after treeland restart + * fix(input): keep num lock synchronized across keyboard devices + * fix(im-candidate): correct position offset with contentGeometry + * fix(shortcut): keep same-app task switch filter in QML + * fix(dconfig): remove global flag from all items + * fix: allow lockscreen shortcut in multitaskview + * feat: implement xdg-dialog-v1 protocol with KWin-style modal linkage + * refactor: remove redundant PrepareForSleep D-Bus handling + * fix(output): persist output state with dconfig + * fix(activation): validate seat in set_serial and pass seat to + trustedSurfaceChecker + * fix: fix z-order issues in wine window management + * fix: keep oversized surfaces on target output + + -- rewine Fri, 10 Jul 2026 16:47:31 +0800 + +treeland (0.8.13) unstable; urgency=medium + + * fix(shortcut): avoid exiting task switch on partial modifier release + * fix(wallpaper): pause video playback after slowdown + * fix(output): avoid wrong rearrange on exclusive zone removal + * fix(xwayland): synchronize the primary output + * fix(waylib): prevent stale subsurface access + * fix(output): migrate surfaces when any non-last screen is removed + * fix: broadcast output state after applying config + * fix(workspace): implement addOutput to update surface ownsOutput + after VT switch + * fix(personalization): clean up stale Personalization on surface + teardown + * fix(wallpaper): show wallpaper for newly created workspace + * fix(multitaskview): properly handle surface unmapped and deduplicate + model data + * fix: improve surface wrapper handling and cleanup + + -- rewine Fri, 26 Jun 2026 13:39:17 +0800 + +treeland (0.8.12) unstable; urgency=medium + + * fix(taskswitch): fix window visibility issues and race condition in + TaskSwitcher + * fix(wallpaper): switching wallpapers is too slow. + * fix(seat): check mapped and hasInitializeContainer for activation + guard + * feat(xwayland): add async X11 property reading for IM candidate + panel + * feat(im-candidate-panel): support tag-based and xprop-based IM + candidate panel + * fix: arrange exclusive layer surfaces first + * fix(workspace): prevent window titlebar from being obscured by dock + * fix: correct active state handling on window minimize + + -- rewine Mon, 22 Jun 2026 15:37:45 +0800 + +treeland (0.8.11) unstable; urgency=medium + + * fix(workspace): refine window edge constraints + * fix: avoid focus fallback for inactive surfaces + * fix(qtquick): disconnect positionChanged before cursor cleanup + * fix(capture): prevent proxy surface from being added to + SurfaceContainer + * refactor: clarify SurfaceWrapper request naming + * fix: remove invalid minimize request connection + * fix(wallpaper): bump WallpaperProduceV1 version to 2 + * fix: emit configChanged when user config is rebuilt + * fix: apply cursor settings without restart + * fix: improve hardware cursor size selection for large cursors + * fix: add idle event dispatch to resolve lock screen time refresh + issue + + -- rewine Wed, 17 Jun 2026 11:31:08 +0800 + +treeland (0.8.10) unstable; urgency=medium + + * chore: add TREELAND_INPUT_ENHANCE environment variable + * fix(qtquick): create RHI textures from DRM formats + * fix: build failed on archlinux + * feat(systemd): raise Treeland service to highest normal priority + * [skip CI] Translate lockscreen.en_US.ts in es + + -- Guo Lin Mon, 15 Jun 2026 11:03:17 +0800 + +treeland (0.8.9) unstable; urgency=medium + + * feat: disable maximize for non-maximizable windows + * fix(lockscreen): fix lockscreen display after TTY switch + * feat(input): distinguishing between libinput mouse and touchpad + functions + * fix(taskswitch): snapshot surface position before exit animation to + avoid state pollution + * fix(shortcut): rewrite Alt+Tab task switch with multi-modifier + release detection + * feat(input): add libinput NaturalScroll detection + * fix(input): allow layer shell windows to receive keyboard focus on + click + * fix(surface): fullscreen window size reduced by titlebar height + * fix(keyboard-state-notify): use keyboardGroupKeyboard() to prevent + crash + * fix: decouple title bar palette from DTK style constants + * fix(input): allow Esc key to cancel move/resize operation + * fix(foreign-toplevel): remove redundant output_leave connection on + output destroy + * feat(input): support virtual keyboard in keyboard group + * feat(keyboard-state-notify): use the keyboard in the keyboard-group + * fix(surface): keep subsurface registry in sync + * feat(input): add keyboard group support to WSeat + + -- rewine Fri, 12 Jun 2026 15:46:37 +0800 + +treeland (0.8.8) unstable; urgency=medium + + * fix: skip update on destroyed xwayland parent + * feat(input-manager): update default configuration values ​​for input + devices. + * fix: correct xwayland child change detection logic + * fix(debian): avoid restarting treeland on upgrade + * fix(surface): improve output geometry handling for maximized state + * chore(shortcut): add option to disable built-in shortcut daemon + * feat: implement on-demand hierarchical window tree via Qt Remote + Object + * fix(vt): switch VT through wlroots session (#913) + * fix: resolve splash transition size issue + * refactor(foreign-toplevel): remove globals and encapsulate handles + * feat(foreign-toplevel): localize manager-owned registries and idle + scheduling + * refactor(foreign-toplevel): multi-client handles via SurfaceEntry + * refactor: migrate foreign-toplevel protocol to qtwayland scanner + * feat(keystate): remove the implementation and examples of the kde- + keystate protocol + * feat(keyboard-state-notify): added implementation logic for treeland- + keyboard-state-notify-unstable + * fix: SSD fallback without PersonalizationV1 + * refactor: rename and split surface destruction logic + * fix: use safe xwayland surface signals + * feat(dconfig): add seat-level input device DConfig + * fix: null check in input method grab + * refactor: unify shortcut validation logic + * fix: drain residual key release after capture shortcut + * fix: add serial to configure position response + * fix(dockpreview): drop invalidated wrappers from preview + * fix: guard against null surface/WSurface in idle inhibitor handling + * feat(wayland): add treeland-input-manager-unstable-v1 protocol + implementation + + -- rewine Thu, 04 Jun 2026 20:57:21 +0800 + +treeland (0.8.7) unstable; urgency=medium + + * refactor(virtual-output): use QStringList join for output name + serialization + * fix(output): fix crash on screen copy mode when hot-plugging + * fix(shortcut): task switch shortcuts not responding to key hold auto- + repeat + * fix(wsocket): fix WClient::get() returning null during client + teardown + * ci: add unit test step to archlinux build workflows + * fix(debian): promote treeland-wallpaper-factory to a hard dependency + * fix: remove unused lambda capture in live test + * refactor(platformplugin): remove unused isMaster/proxy QPA mode + * refactor: replace #define-private-public hacks with template + accessor pattern + * fix(activation): address PR review findings + * feat: add token validation and expiration to xdg-activation + * fix: clear attention on activation + * feat: differentiate activation token disposition + * feat: add attention state to foreign-toplevel + * feat: implement xdg-activation-v1 with treeland private protocol + * fix(render): fix texture copy crash when window partially off-screen + * fix(woutputrenderwindow): destroy wlr layers before invalidating + output on removal + * fix: avoid crash on invalid image capture buffer + * fix: fix build errors with GCC 16.1.1 and Qt 6.11.1 on Arch Linux + * fix(virtual-output): move beforeDestroy signal to destroy method + * fix: skip redundant minimize requests + * fix: crash caused by treeland capture + * chore: fix compile warnings reported by clang + * fix(capture): avoid double wl_resource_destroy on client teardown + * chore(agents): introduce AI agent instructions and skills + * docs: migrate logging guidelines to agent skill + * feat: add other user login support + * feat: refactor treeland-ddm-v1 protocol implementation + * fix(build): add missing headers for gcc 16 compatibility + + -- rewine Fri, 22 May 2026 10:02:44 +0800 + +treeland (0.8.6) unstable; urgency=medium + + * fix: fix multiple crashes caused by thread affinity and use-after- + free issues + * fix(surface): avoid SurfaceWrapper assert on QObject child + destruction + * refactor: remove redundant m_alive flag + * refactor: enforce SurfaceWrapper cleanup via markWrapperToRemoved + * refactor: simplify wine window data structures + * feat: add Wine window management protocol module + * refactor(shellhandler): consolidate compositor protocol startup into + single-shot init + * feat(modules): introduce WineWindowState protocol module and wire + initial integration + * fix: deepin ci failed + * Revert "fix: disconnect socket signals when shell surface is + removed" + * feat: refactor treeland-screensaver-v1 protocol implementation + * fix: 'wallpaper changed' events could not be sent or received + * fix: disconnect socket signals when shell surface is removed + * feat: refactor treeland-personalization-manager protocol + implementation + * fix: capturev1 resource destroy callbacks: use deleteLater() to + avoid UAF + * refactor: Remove manual resource tracking in interface + implementations + * refactor: Make `interfaceName()` public in WServerInterface + implementations + * fix: prevent crash during Wayland client destruction + * feat: rename qtwaylandscanner Resource object name + * fix: Remove redundant 'delete' operations in `destroy_global` + * refactor: privatize generated protocol implementations + * fix: use globalRemove to implement WServerInterface::destroy + * feat: refactor treeland-virtual-output-manager-v1 protocol + implementation + * [skip CI] Translate treeland.en_US.ts in pt_BR + * fix: prevent deadlock during Wayland client destruction + * fix: Gradia-like capture causes treeland crashed, and update + copyright to 2026 + * feat: refactor wallpaper-color protocol implementation + * feat: refactor window-management protocol implementation + * fix: avoid set zero implicit size during splash transition + * chore: refine decoration handling logic + + -- rewine Sat, 09 May 2026 18:04:20 +0800 + +treeland (0.8.5) unstable; urgency=medium + + * fix: correct CMake config name for submodule build + * fix: qw_buffer metatype handling for Clang builds + * chore: add org.freedesktop.ScreenSaver test for test_idle_inhibit_v1 + * fix: add wl_display_flush for treeland_screensaver request + * chore: update translations for project TreeLand + * fix: fix renaming of treeland_screensaver_v1 protocol + * feat: add treeland-wallpaper-factory as recommended dependency + * fix: fix wallpaper scaling and clipping issues + * feat: improve prelaunch splash screen layout and styling + * feat(examples): add idle inhibit v1 test client + * fix: suppress unused parameter warnings in WallpaperLauncher + * fix: fix dconfig initialization check compatibility + * feat: implement wallpaper switching with smooth transitions + * fix: prevent crash by delaying output assignment until surface + mapped + * feat: implement wallpaper management system + + -- rewine Fri, 06 Mar 2026 09:44:57 +0800 + +treeland (0.8.4) unstable; urgency=medium + + * refactor: optimize PrelaunchSplash animation and destruction logic + * feat: add prelaunch splash v2 protocol support + * fix: fix cannot unlock session after crash recovery + * fix: memory leak in prelaunch splash + * feat: listen to the Lock/Unlock signal of + org.freedesktop.login1.Session + * chore: clean up the logic of greeter and lockscreen + * fix: WBufferRenderer missing disconnect during QQuickItem destructor + * refactor: move dock preview management to ShellHandler + * feat: make splash screens visible and closable via foreign-toplevel + protocol + * feat: implement video slow down and playback control + * feat: enhance wallpaper setting with file type detection + * fix: prevent crash when updateActiveState called on uninitialized + shell surface + * fix: keybinding to quit treeland + * fix: Treeland destruction timing + * fix: SessionManager: correct destruction routine of WXWayland + instances + * fix: qwlroots: expose qw_xwayland::destroy() + * fix: waylib: release renderers before scene graph invalidation + * fix: fix splash screen activation and keyboard focus handling + * feat: improve splash screen active state handling + + -- rewine Sat, 28 Feb 2026 14:03:33 +0800 + +treeland (0.8.3) unstable; urgency=medium + + * chore: refactor treeland screensaver to persistent daemon + * fix(xwayland): prevent use-after-free in xauth file path + construction + * fix: lower classed QML element waylib being non-addressable in QML + * feat: Add wallpaper producer support for Treeland Wayland compositor + * fix: resolve Qt 6.12 compilation errors + * chore: disable restrictive systemd security options + * fix: improve Qt6 private module compatibility + * fix: fix corner radius clipping when no compositor decoration + * refactor: move session related functionality out of Helper + * chore: enable prelaunch splash by default + * fix: add missing rendering flags to WSGRenderFootprintNode + + -- rewine Wed, 04 Feb 2026 16:06:58 +0800 + +treeland (0.8.2) unstable; urgency=medium + + * refactor: use const iterators for QVector in signal connector + * Revert "chore: temporary disable TreelandUserConfig smart pointer" + * fix: crash on session removal (logout) window active + * fix: fix compatibility with older dconfig versions + * fix: align dconfig theme type values with wayland protocol + * chore: remove splash theme type configuration + * refactor: extract prelaunch splash creation logic + * fix: fix splash screen icon buffer leak and size validation + * chore: apply clang-format code style cleanup + * fix: prevent icon buffer destruction during dconfig initialization + * refactor: clean up splash dconfig logic + * feat: add per-app prelaunch splash configuration + * feat: add splash screen theme color customization + * refactor: rename WindowSizeStore to WindowConfigStore + * fix: fix splash size incorrect due to dconfig async initialization + * feat: add splash screen theme support and adjust default window size + * feat: migrate window size storage to dconfig + * feat: Add wallpaper producer client for Treeland Wayland compositor + * feat: replace assert with runtime error handling for output commit + * fix: clean up all treeland originated warnings on treeland startup + * feat: expose a method to move XWayland window position relative to + wl_surface + * fix(WSurfaceItem): add subsurfaces.clear() after deleteLater + * chore: remove obsolete dconfig usage in personalization + * feat: add dconfig option to allow setting Numlock state on startup + * feat: add minimal wallpaper setting test client + * fix: use systemd sd-login API for session info query instead of D- + Bus + * fix: clean up warnings on treeland startup + * fix: decoration assert crash when proxy decoration is not created + * fix: remove unused DDM headers in treeland.cpp + * fix: compilation issues due to update in treeland-dde-shell-v1 + protocol + + -- rewine Fri, 30 Jan 2026 09:51:46 +0800 + +treeland (0.8.1) unstable; urgency=medium + + * fix: update treeland-protocol structure names (#690) + * fix: systemd warnings caused by invalid directives in socket units. + * fix: fix user mistakenly marked as logged in when login happened + outside ddm + * fix: fix user cannot login after logout once + * fix: missing license LGPL-2.1-or-later for kde keystate protocol + * feat: adopt kde-keystate-v5 to expose states of stateful keys + * fix: fix treeland crash on virtual machine + + -- rewine Thu, 15 Jan 2026 11:07:00 +0800 + +treeland (0.8.0) unstable; urgency=medium + + * chore: temporary disable TreelandUserConfig smart pointer + * fix: improve surface proxy handling for splash screens + * fix: avoid double removal on session destroy by requesting surface + close + * fix: send events after activate if available + * fix: optimize surface arrangement calls + * fix: fix timing issue in Workspace::addSurface + * fix: Fix possible stuck on DBus when user logging in + * fix: fix Wayland compositor crash resolver cleanup + * fix: add window validity checks in releaseResources methods + * fix: resolve multiple critical crashes in Qt Quick rendering + * fix: shortcuts not recovered after session crash recovery + * feat: Apply systemd.exec sandbox options + * fix: forward appId changes in fallback mode + * refactor: use qtwayland scanner for treeland-output-manager-v1 + protocol + * fix: Remove unused config references + * fix: clang compiler warnings + * docs: add GitHub Copilot repository instructions + * Remove unused module + * fix: correct workspace change detection logic + * fix: support placeSmartCascaded for SplashScreen + * refactor: rename Undetermined surface type to SplashScreen + * fix: Support layer surfaces on proxy outputs in Copy Mode + * refactor: use qtwayland scanner for treeland-shortcut-manager-v2 + protocol implementation + * feat: Add display mode recording and automatic restoration system + * fix: fix splash screen launch animation + * fix: resolve code review issues + * fix: Correct typo in variable name from wpModle to wpModel + * fix: correct dock preview skip logic for surface types + * feat: optimize prelaunch splash handling and logging + * refactor: reorganize dconfig file structure + * fix: fix QList remove usage and clean up app ID resolver + * refactor: simplify buffer property handling in WBufferItem + * fix: fix various memory and resource management issues + * feat: add configurable timeout for prelaunch splash screens + * chore: cleanup build configuration and xwayland code + * fix: fix multiple code review issues + * feat: add debug logging and QVariant buffer property + * feat: simplify prelaunch splash icon path + * feat: add global configuration for prelaunch splash feature + * feat: enable window open animation + * fix: prevent crash when passing non-QML context objects as parent + * feat: add prelaunch splash configuration option + * chore: remove ExecStop commands and adjust treeland-session-helper + service + * chore: apply clang format to app-id-resolver and prelaunch-splash + modules + * refactor: adapt to new protocol with sandbox engine parameter + * fix: handle undetermined surface type in session checks + * fix: fix potential crash in moveResizeState surface handling + * refactor: replace dynamic property with member variable for appId + * fix: handle surface null case in setOutputs + * fix: fix corner radius and memory leak issues + * refactor: extract common surface container update logic + * fix: avoid flash when prelauncher disappears + * fix: prevent crash when surface destroyed before async AppId resolve + * refactor: simplify pidfd retrieval from surface + * chore: update systemd service dependencies and surface wrapper setup + * refactor: reorganize initialization order and cleanup comments + * fix: improve surface wrapper matching and container management + * fix: simplify prelaunch splash transition and cleanup + * feat: move test_app_id_resolver_helper to tools + * chore: Implement splash screen + * feat: make protocol generation targets unique per consumer + * refactor: remove redundant virtual qualifiers from lockscreen + interface + * fix: fix dde-session not started after ddm restart or crash recover + * fix: normaize registration and handling of all-modifier keybindings + * feat: introduce ShortcutManagerV2 and refactor shortcut handling + * fix: correct primary output disable handling in copy mode + * feat: Support Xauthority access control for Xwayland + * fix: Pass keyboard modifiers directly to keyboard_enter + * feat: sync Xresouces and xsettings scale with treeland scale changes + * fix: reload cursor image when scale changes + * feat: add Deepin CI build workflows + * fix: fix unused parameter + * fix: support screen rotation in copy mode + * feat: Support org.freedesktop.ScreenSaver specification + * fix: fix crash on logout & hiding of wayland surface on user switch + * fix: Display issues with scaling and resolution switching in copy + mode + * fix: load vulkan library with version number + + -- rewine Sun, 04 Jan 2026 14:20:38 +0800 + +treeland (0.7.8) unstable; urgency=medium + + * [skip CI] Translate multitaskview.en_US.ts in tr + * feat: optimize taskbar preview animation effects + * fix: resolve window remove/resize blur on fractional DPR displays + * fix: connect Helper::Session with Logind session + * fix: synchronize wl_client destruction with WClient destruction + * feat: Add logout cleanup + * feat: support setting brightness & color temperature through + treeland-output-manager-v1 + * chore: update find_package calls for Qt private modules for building + with Qt 6.10 + + -- rewine Fri, 14 Nov 2025 11:35:06 +0800 + +treeland (0.7.7) unstable; urgency=medium + + * fix: mark animation as finished when skipping slide animation + * fix: temporarily disable DockPreview animations + * fix: resolve surface position drift during scale changes + * refactor: Use swap member function instead of std::swap + + -- rewine Fri, 07 Nov 2025 16:07:54 +0800 + +treeland (0.7.6) unstable; urgency=medium + + * refactor: implement atomic multi-output configuration + * fix: occasional crash during recording toplevel + * fix: use safeConnect for aboutToBeInvalidated + * i18n: Updates for project TreeLand (#601) + * refactor: Convert Session to shared_ptr and simplify session + lifecycle + * chore: Remove unused code & Add document + * feat: Manage per-user Wayland/XWayland sessions via Helper::Session + * feat: Add per-user XWayland session management + * chore: add ASAN environment variables + * feat: Expose XWayland surface process ID + * chore: change Debian build environment to unstable + * refactor: remove branch filter for workflow triggers + * fix: fix build when treeland examples are enabled + * fix: fix build failure on Arch Linux + * fix: Disable minimize / maximize animation for window that doesn't + belongs to current user + * fix: fix private module inclusion on lower version of Qt + * fix: compile errors on Arch for forward declared class + * fix: include Qt private modules for Qt 6.11 + * feat: add real-time FPS display + * feat: support start sessions other than treeland + * feat: implement ext-session-lock-v1 support + * feat(waylib): implement ext-session-lock-v1 protocol support + * fix(waylib): Add missing override specifier in wlayersurface + * fix(qwlroots): allow server side destruction of qw_session_lock_v1 + * fix: Delete useless display text in copy mode + * fix: enhance output validation in restore copy mode + * fix: use separate TreelandConfig for each user + * fix: Ensure proper object destruction before app exit + * fix: improve resource management for RenderControl + * fix: fix heap-use-after-free on exit + + -- rewine Thu, 30 Oct 2025 14:04:56 +0800 + +treeland (0.7.3) unstable; urgency=medium + + * fix: fix WorkspaceSelectionList animation's highlight border size + * fix: fix MultitaskView display problem + * refactor: reduce cursor-related log verbosity + * fix: fix MultitaskView display problem caused by refactoring + TreelandConfig + * Updates for project TreeLand (#563) + + -- rewine Tue, 23 Sep 2025 17:24:35 +0800 + +treeland (0.7.2) unstable; urgency=medium + + * fix: crash on startup due to uninitialized m_config pointer + + -- rewine Fri, 19 Sep 2025 10:06:51 +0800 + +treeland (0.7.1) unstable; urgency=medium + + * fix: Fix socket blocking issue in Wayland server connection handling + * fix: correct window title visibility condition + * fix: Fix client crash when created via security context + * feat: add security-context support + * fix: Separate DConfig object creation to another thread to avoid + blocking + * fix: move DBus call to separate thread to avoid blocking + * fix: fixing some trivial memory management bugs. + * feat(core): Add support for XDG toplevel surface and XDG shell in + RootSurfaceContainer + * fix: correct refresh rate on multi-monitor + * fix: redraw when frame callback list updates + + -- rewine Thu, 18 Sep 2025 11:46:00 +0800 + +treeland (0.7.0) unstable; urgency=medium + + * fix: fix treeland get stuck in lockscreen after crash recovery + * fix: occasional crash during stop preview item handling + * refactor: improve code robustness + * fix: occasional crash when closing x window + * fix: resolve brief black screen during standby + * chore: remove dde portal screen cast configuration + * fix: correct log category and add null check for surface activation + * fix: resolve window resize crash during image capture + * fix: fix wrong display render issue when switching VT too quickly + * Totally disable lockscreen animation when switching TTY to prevent + stuck for switching too quickly + * feat: Support TTY switching with DDM + * Updates for project TreeLand (#515) + * feat(waylib): add WBufferDumper utility for dumping buffer contents + to image files + * refactor: use unified CI build preset with Werror + * build: enable -Werror compiler flag + * fix: prevent crash during preview item handling (#512) + * fix: prevent cursor flicker during screen recording + * docs: add comprehensive logging guidelines and update module logging + * feat: add centralized logging system and standardize log usage + * feat: ssd title bar displays the window title information + * fix: maximize/restore icon in the SSD title bar displays incorrectly + * fix: resolve multiple compiler warnings + * fix(waylib): prevent duplicate signal connections using + Qt::UniqueConnection + * fix(waylib): prevent crash by safely managing textureChanged + connection + * fix: use exec to replace process and avoid duplicate logs in + treeland.sh + * fix(waylib): Occasional crash when moving the cursor + + -- rewine Fri, 29 Aug 2025 10:23:45 +0800 + +treeland (0.6.2) unstable; urgency=medium + + * fix: resolve library versioning and installation path issues + + -- rewine Mon, 04 Aug 2025 17:42:40 +0800 + +treeland (0.6.1) unstable; urgency=medium + + * fix: improve D-Bus connection handling and QML hover visibility + * feat: CLI option: switch from --disable-debug-view to --enable-debug- + view + * fix(waylib): Specify required rendering flags in + WSGRenderFootprintNode + + -- rewine Fri, 01 Aug 2025 13:33:07 +0800 + +treeland (0.6.0) unstable; urgency=medium + + * fix: improve image capture error handling and code structure + * feat: add foreign toplevel image capture support + * feat: add image capture source support + * fix: remove unused quit full button and add helper activation + * fix: prevent title bar and window buttons from stealing focus + * feat: add wl_drm support + * feat: create ext-data-control manager + * fix: Handle VT switching keys (#469) + * feat: add Nix flake support for project configuration + * fix: prevent workspace moveSurfaceTo crash on null wrapper + * fix: remove redundant submodule options and configs + * chore: update nix dependencies and clean up configurations + * fix: Scaling animation not shown while return from shutdown page + * chore: Force Ninja build during deb packaging + * fix: add timeout to protocol tests + * feat: Upload build artifacts as zip archives + * chore: fix CI and enable independent builds + * refactor: merge qwlroots and waylib source code into treeland + * chore: Use treeland-specific seatd service + * feat: implement ext-foreign-toplevel-list + * i18n: Updates for project TreeLand (#440) + * chore: remove polkit rules for login1 + * feat: add support for alpha modifier protocol + * fix: cannot export dbus services + * Revert "fix: should not maximize when client set maxsize" + * Updates for project TreeLand (#431) + * fix: Treeland does not exit when logging out of session + * fix: cannot use treeland user session mode + * fix: add [[maybe_unused]] attribute to unused parameters + * chore: improvement fixes the translation configuration + * feat: add popup surface container for handling popup windows + * chore: configure translation files and update Chinese translations + * chore: configure transifex translation files + * feat: adapt to wlroots-0.19 + * refactor: remove jemalloc dependency + + -- rewine Thu, 31 Jul 2025 20:40:50 +0800 + +treeland (0.5.21) unstable; urgency=medium + + * fix: inputted password and capsIndicator button are covered + + -- rewine Thu, 17 Apr 2025 15:17:48 +0800 + +treeland (0.5.20) unstable; urgency=medium + + * fix: activeColor not saved to dconfig + * fix: send error output enter for layer shell + * chore: input popup should not use radius + + -- rewine Mon, 10 Mar 2025 16:20:35 +0800 + +treeland (0.5.19) unstable; urgency=medium + + * fix: can't set output's postion + * fix: layer shell's popup not enter popup container + + -- rewine Sat, 15 Feb 2025 15:30:10 +0800 + +treeland (0.5.18) unstable; urgency=medium + + * fix: the tooltip text may disappear unexpectedly + * fix: can't start on VirtualBox + * feat: cache outputs settings + + -- rewine Fri, 14 Feb 2025 10:31:38 +0800 + +treeland (0.5.17) unstable; urgency=medium + + * fix: nix ci for build + * Fix missing treeland's translations + + -- Groveer Wed, 15 Jan 2025 11:02:18 +0800 + +treeland (0.5.16) unstable; urgency=medium + + * fix: crashed at accessing surface + * Fix crash at QStyleHints + + -- zhangkun Tue, 14 Jan 2025 16:16:43 +0800 + +treeland (0.5.15) unstable; urgency=medium + + * chore: update default window corner size + + -- zhangkun Tue, 14 Jan 2025 11:45:30 +0800 + +treeland (0.5.14) unstable; urgency=medium + + * Fix crash at PersonalizationAttached::noTitlebar + * Add a background color for DockPreview + + -- JiDe Zhang Mon, 13 Jan 2025 18:13:21 +0800 + +treeland (0.5.13) unstable; urgency=medium + + * feat: add ctrl-alt-del shortcut key + * Add TREELAND_SESSION_ENVIRONMENTS env + * fix: popup of screen recorder is below it's parent + * Fix typo + * Ignore window rounded radius when maximized + + -- JiDe Zhang Mon, 13 Jan 2025 11:02:32 +0800 + +treeland (0.5.12) unstable; urgency=medium + + * Fix maybe freeze when display DockPreview + * feat: update default values + * fix: adjust UI for greeter + + -- Groveer Wed, 08 Jan 2025 11:22:31 +0800 + +treeland (0.5.11) unstable; urgency=medium + + * bump version to 0.5.11 + + -- Groveer Wed, 25 Dec 2024 18:47:45 +0800 + +treeland (0.5.10) unstable; urgency=medium + + * bump version to 0.5.10 + + -- Groveer Fri, 20 Dec 2024 16:04:58 +0800 + +treeland (0.5.9) unstable; urgency=medium + + * bump version to 0.5.9 + + -- Groveer Tue, 17 Dec 2024 21:04:15 +0800 + +treeland (0.5.8) unstable; urgency=medium + + * bump version to 0.5.8 + + -- Groveer Fri, 13 Dec 2024 14:14:01 +0800 + +treeland (0.5.7) unstable; urgency=medium + + * bump version to 0.5.7 + + -- Groveer Tue, 10 Dec 2024 18:29:02 +0800 + +treeland (0.5.6) unstable; urgency=medium + + * bump version to 0.5.6 + + -- rewine Fri, 06 Dec 2024 15:05:05 +0800 + +treeland (0.5.5) unstable; urgency=medium + + * bump version to 0.5.5 + + -- Groveer Thu, 05 Dec 2024 21:22:32 +0800 + +treeland (0.5.4) unstable; urgency=medium + + * bump version to 0.5.4 + + -- Groveer Sat, 30 Nov 2024 15:52:51 +0800 + +treeland (0.5.3) unstable; urgency=medium + + * bump version to 0.5.3 + + -- Groveer Fri, 29 Nov 2024 15:58:26 +0800 + +treeland (0.5.2) unstable; urgency=medium + + * bump version to 0.5.2 + + -- Groveer Tue, 26 Nov 2024 15:01:56 +0800 + +treeland (0.5.1) unstable; urgency=medium + + * bump version to 0.5.1 + + -- Groveer Fri, 22 Nov 2024 18:10:04 +0800 + +treeland (0.5.0) unstable; urgency=medium + + * bump version to 0.5.0 + + -- Groveer Thu, 21 Nov 2024 17:02:20 +0800 + +treeland (0.4.4) unstable; urgency=medium + + * bump version to 0.4.4 + + -- Groveer Fri, 15 Nov 2024 14:15:57 +0800 + +treeland (0.4.3) unstable; urgency=medium + + * bump version to 0.4.3 + + -- Groveer Mon, 11 Nov 2024 19:10:14 +0800 + +treeland (0.4.1) unstable; urgency=medium + + * update appearance protocol + + -- Dingyuan Zhang Thu, 01 Nov 2024 11:20:00 +0800 + +treeland (0.4) unstable; urgency=medium + + * update workspace + + -- Dingyuan Zhang Thu, 01 Nov 2024 11:20:00 +0800 + +treeland (0.3) unstable; urgency=medium + + * support windows animation + + -- Dingyuan Zhang Thu, 25 Jul 2024 18:20:00 +0800 + +treeland (0.2.3) unstable; urgency=medium + + * refactor protocol from qml to c++ + + -- Dingyuan Zhang Thu, 27 Jun 2024 14:27:40 +0800 + +treeland (0.2.2) unstable; urgency=medium + + * fix user list not refresh + * fix greeter in multi output + + -- Dingyuan Zhang Fri, 26 Jan 2024 15:18:40 +0800 + +treeland (0.2.1) unstable; urgency=medium + + * fix cannot set wallpaper + + -- Dingyuan Zhang Thu, 25 Jan 2024 09:29:40 +0800 + +treeland (0.2.0) unstable; urgency=medium + + * Support dock preview + * New shortcut config + * Add back to normal function + + -- Dingyuan Zhang Mon, 8 Jan 2024 18:37:40 +0800 + +treeland (0.1.1) unstable; urgency=medium + + * fix user session not set XDG_CURRENT_DESKTOP + + -- Dingyuan Zhang Tue, 25 Dec 2023 13:07:40 +0800 + +treeland (0.1.0) unstable; urgency=medium + + * Initial release + + -- Dingyuan Zhang Tue, 12 Dec 2023 13:07:40 +0800 diff --git a/debian/control b/debian/control new file mode 100644 index 0000000000..43d7c02c70 --- /dev/null +++ b/debian/control @@ -0,0 +1,131 @@ +Source: treeland +Priority: optional +Maintainer: rewine +Build-Depends: cmake (>= 3.25.0), + debhelper-compat (= 13), + ninja-build, + extra-cmake-modules (>= 1.4.0~), + libddm-dev (>= 0.5.0), + libdtk6core-bin, + libdtk6core-dev, + libdtk6declarative-dev, + libdtk6gui-dev, + libdtk6systemsettings-dev, + libdtkcommon-dev, + libsystemd-dev [linux-any], + systemd, + libwayland-dev (>= 1.23.1), + libxkbcommon-dev, + libudev-dev, + libseat-dev, + libdisplay-info-dev (>= 0.1.1), + libliftoff-dev (>= 0.4.1), + liblcms2-dev, + libinput-dev, + libegl1-mesa-dev, + libegl-dev, + libgbm-dev, + libgles2-mesa-dev, + libvulkan-dev, + glslang-tools, + hwdata, + libcap-dev, + libcairo2-dev, + libdrm-dev (>= 2.4.122), + libpixman-1-dev (>= 0.43.0), + libpng-dev, + libx11-xcb-dev, + libxcb1-dev, + libxcb-composite0-dev, + libxcb-dri3-dev, + libxcb-errors-dev, + libxcb-ewmh-dev, + libxcb-icccm4-dev, + libxcb-image0-dev, + libxcb-present-dev, + libxcb-render0-dev, + libxcb-render-util0-dev, + libxcb-res0-dev, + libxcb-shm0-dev, + libxcb-xfixes0-dev, + libxcb-xinput-dev, + pkg-config, + qml6-module-qtquick-templates, + qml6-module-qtquick-effects, + qml6-module-qtquick-window, + qt6-base-dev (>= 6.8.0), + qt6-base-private-dev (>= 6.8.0), + qt6-base-dev-tools (>= 6.8.0), + qt6-declarative-dev (>= 6.8.0), + qt6-declarative-private-dev (>= 6.8.0), + qt6-shadertools-dev, + qt6-tools-dev, + qt6-tools-dev-tools (>= 6.8.0), + qt6-wayland, + qt6-wayland-dev, + qt6-wayland-private-dev, + qt6-remoteobjects-dev, + qt6-httpserver-dev, + qt6-websockets-dev, + wayland-protocols, + wlr-protocols, + treeland-protocols (>= 0.8.0), + libpam0g-dev, + libmpv-dev, + libxcb-randr0-dev, + xwayland, + libxcb-shape0-dev, +Standards-Version: 4.6.0 +Section: dde +Homepage: https://github.com/linuxdeepin/treeland.git +#Vcs-Browser: https://salsa.debian.org/debian/treeland +#Vcs-Git: https://salsa.debian.org/debian/treeland.git +Rules-Requires-Root: no + +Package: treeland +Section: dde +Architecture: any +Multi-Arch: same +Depends: qml6-module-qtquick-layouts, + qml6-module-qtquick-effects, + qml6-module-qtquick-particles, + treeland-data (= ${source:Version}), + xwayland, + treeland-wallpaper-factory, + ${misc:Depends}, + ${shlibs:Depends}, +# The former qwlroots binary package owned the same libwaylib-wlroots +# install paths; keep the transition guards until it is safely superseded. +Conflicts: libwaylib, qwlroots +Replaces: libwaylib, qwlroots +Recommends: ddm (>= 0.5.0), +Description: a Wayland compositor based on wlroots and QML, designed with an attractive and elegant appearance. + +Package: treeland-examples +Section: dde +Architecture: any +Multi-Arch: same +Depends: ${misc:Depends}, + ${shlibs:Depends}, +Description: examples for treeland. + +Package: treeland-data +Section: dde +Architecture: all +Depends: ${misc:Depends}, +Description: data files of treeland. + +Package: treeland-wayland-session +Section: dde +Architecture: all +Depends: ${misc:Depends}, + treeland (= ${source:Version}), +Description: treeland user session files of treeland. + +Package: treeland-wallpaper-factory +Section: dde +Architecture: any +Depends: ${misc:Depends}, + ${shlibs:Depends}, + treeland (= ${source:Version}), +Description: Treeland wallpaper factory client. diff --git a/debian/copyright b/debian/copyright new file mode 100644 index 0000000000..ad61b77b1a --- /dev/null +++ b/debian/copyright @@ -0,0 +1,75 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: treeland +Source: https://github.com/linuxdeepin/treeland + +Files: .github/* .obs/*.yml garnix.yaml +Copyright: None +License: CC0-1.0 + +Files: .clang-format + .editorconfig + *.frag + *.ui + *.vert + **/qmldir +Copyright: None +License: CC0-1.0 + +Files: debian/* rpm/* archlinux/* +Copyright: None +License: CC0-1.0 + +Files: *.nix .envrc flake.lock renovate.json +Copyright: None +License: CC0-1.0 + +Files: translations/* po/* *.qm *.ts +Copyright: UnionTech Software Technology Co., Ltd. +License: GPL-2.0-only + +Files: *.svg *.png *.jpg *.jpeg *.webp *.dci *.gif +Copyright: UnionTech Software Technology Co., Ltd. +License: CC0-1.0 + +Files: *.json + *.service + *.txt + *.sh + *.html + .gitignore + .gitmodules + INSTALL.md + *.desktop + *.css + *.ttf + *.conf + *.xml + .release.json +Copyright: UnionTech Software Technology Co., Ltd. +License: CC0-1.0 + +Files: *.md + README.md + README.zh_CN.md + CONTRIBUTING.md + ChangeLog + CONTRIBUTORS +Copyright: UnionTech Software Technology Co., Ltd. +License: CC-BY-4.0 + +Files: *.cmake + CMakeLists.txt + *.in *.qrc + misc/* + services/* + releng/create_changelog.pl +Copyright: None +License: GPL-2.0-only + +Files: src/greeter/*.h src/greeter/*.cpp +Copyright: None +License: GPL-2.0-only + +Files: src/*.h src/*.cpp src/*.qml tests/*.cpp tests/*.h tests/*.qml +Copyright: UnionTech Software Technology Co., Ltd. +License: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only diff --git a/debian/rules b/debian/rules new file mode 100755 index 0000000000..4e106992f8 --- /dev/null +++ b/debian/rules @@ -0,0 +1,23 @@ +#!/usr/bin/make -f +# See debhelper(7) (uncomment to enable) +# output every command that modifies files on the build system. +#export DH_VERBOSE = 1 + +# see FEATURE AREAS in dpkg-buildflags(1) +export DEB_BUILD_MAINT_OPTIONS = hardening=+all + +# see ENVIRONMENT in dpkg-buildflags(1) +# package maintainers to append CFLAGS +export DEB_CFLAGS_MAINT_APPEND = -Wall -Wextra -Werror -Wno-error=stringop-overflow +export DEB_CXXFLAGS_MAINT_APPEND = -Wall -Wextra -Werror -Wno-error=stringop-overflow +# package maintainers to append LDFLAGS +export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed + +%: + dh $@ --buildsystem=cmake+ninja + +override_dh_auto_configure: + dh_auto_configure -- -DBUILD_TREELAND_EXAMPLES=ON -DTREELAND_INSTALL_DEV=OFF -DBUILD_TREELAND_PROTOCOL_TESTS=$(BUILD_TREELAND_PROTOCOL_TESTS) + +override_dh_installsystemd: + dh_installsystemd --no-start --no-stop-on-upgrade diff --git a/debian/source/format b/debian/source/format new file mode 100644 index 0000000000..89ae9db8f8 --- /dev/null +++ b/debian/source/format @@ -0,0 +1 @@ +3.0 (native) diff --git a/debian/treeland-data.install b/debian/treeland-data.install new file mode 100644 index 0000000000..a9cc2832af --- /dev/null +++ b/debian/treeland-data.install @@ -0,0 +1,3 @@ +usr/share/dsg/configs/* +usr/share/wayland-sessions/treeland.desktop +usr/share/dbus-1/interfaces/org.freedesktop.ScreenSaver.xml diff --git a/debian/treeland-examples.install b/debian/treeland-examples.install new file mode 100644 index 0000000000..9b19d744ef --- /dev/null +++ b/debian/treeland-examples.install @@ -0,0 +1 @@ +usr/bin/test* diff --git a/debian/treeland-wallpaper-factory.install b/debian/treeland-wallpaper-factory.install new file mode 100644 index 0000000000..95d602bccd --- /dev/null +++ b/debian/treeland-wallpaper-factory.install @@ -0,0 +1 @@ +usr/bin/treeland-wallpaper-factory diff --git a/debian/treeland-wayland-session.install b/debian/treeland-wayland-session.install new file mode 100644 index 0000000000..e04dcbfab5 --- /dev/null +++ b/debian/treeland-wayland-session.install @@ -0,0 +1,2 @@ +usr/share/wayland-sessions/treeland-user.desktop +usr/bin/treeland-user-wrapper diff --git a/debian/treeland.install b/debian/treeland.install new file mode 100644 index 0000000000..5d53973b79 --- /dev/null +++ b/debian/treeland.install @@ -0,0 +1,14 @@ +usr/bin/treeland +usr/bin/treeland-debug +usr/bin/treeland.sh +usr/lib/systemd/user/* +usr/lib/systemd/system/* +usr/libexec/* +usr/share/*/translations/* +usr/share/dbus-1/system.d/* +usr/lib/*/lib*.so.* +usr/lib/*/treeland/plugins/lib*.so +usr/share/polkit-1/actions/org.deepin.dde.treeland-debug.policy +usr/share/bash-completion/completions/treeland-debug +usr/share/zsh/site-functions/_treeland-debug +usr/share/fish/vendor_completions.d/treeland-debug.fish diff --git a/default.nix b/default.nix new file mode 100644 index 0000000000..d01edff067 --- /dev/null +++ b/default.nix @@ -0,0 +1,21 @@ +{ + pkgs ? import { }, + nix-filter, + ddm, + treeland-protocols, +}: +rec { + waylib = pkgs.qt6Packages.callPackage ./waylib/nix { + inherit nix-filter; + makeTest = import (pkgs.path + "/nixos/tests/make-test-python.nix"); + }; + + treeland = pkgs.qt6Packages.callPackage ./nix { + inherit + nix-filter + ddm + treeland-protocols + waylib + ; + }; +} diff --git a/docs/liquid-glass-dispersion.md b/docs/liquid-glass-dispersion.md new file mode 100644 index 0000000000..dffdb4241f --- /dev/null +++ b/docs/liquid-glass-dispersion.md @@ -0,0 +1,147 @@ +# Liquid Glass 色散(Chromatic Dispersion)实现说明 + +> 文档记录删除前的实现方式,供后续重做时查阅。 +> **当前代码库已移除色散功能**;玻璃仅保留单通道折射 + Fresnel 高光。 + +## 1. 目标观感 + +希望边缘出现由**折射后的背景**被「拉开」形成的蓝/青/紫细边,而不是: + +- 在玻璃轮廓上描固定色边 +- 对未折射底图做大位移 RGB 错位(露底、叠红) +- 轴对齐矩形色带 + +理想结构: + +```text +玻璃外缘 (SDF) ──弧形环带── 折射后的内容轮廓 + ↑ + 色散主要出现在这里 +``` + +## 2. 整体管线(删除前) + +```text +1) 圆角矩形 SDF → 外形裁切 + AA +2) bezel 剖面 surfaceHeight(t) → 边缘斜率 slopeMag +3) 平面法线 n2(圆角连续旋转) +4) 单通道主折射: + inward = -n2 + magG = Snell 楔形幅度 * contentRamp + uvG = texCoord + inward * magG / size +5) 色散(可选): + 在 distFromEdge < dispersionWidth 的环带内 + 对 R/G/B 使用略不同的 mag(同一 inward 方向) + color = mix(sG, vec3(sR.r, sG.g, sB.b), fringeMask) +6) Fresnel 式边缘高光 + tint +``` + +## 3. 主折射(与色散共用的场) + +### 3.1 几何 + +| 量 | 含义 | +|----|------| +| `distFromEdge` | SDF 内侧距离(像素) | +| `bezel` | 厚度从 0→满的过渡带宽度 | +| `t = clamp(distFromEdge/bezel,0,1)` | 在 bezel 内的归一化位置 | +| `h = surfaceHeight(t)` | squircle 剖面相对高度 | +| `H = h * thickness` | 有效光学高度 | +| `n2` | 圆角矩形连续平面法线(指向外侧) | +| `inward = -n2` | 内容采样方向(向内拉) | + +### 3.2 幅度(Snell 薄楔近似) + +```text +slopeMag = min(|dh| * thickness/bezel, refractionMaxTan) +slopeAngle = atan(slopeMag) +eta = 1/ior +sinI = slopeMag / sqrt(slopeMag²+1) +mag = H * contentRamp * max(tan(slopeAngle) - tan(asin(eta*sinI)), 0) +mag = min(mag, maxDisp) +off = inward * mag +uv = texCoord + off/size +``` + +### 3.3 contentRamp(贴边 vs 折射强度) + +```text +contentRamp = mix(contentEdgePull, 1.0, smoothstep(0, contentRampEnd, t)) +``` + +- **contentEdgePull**:贴边保留多少折射位移(默认 0.42) +- **contentRampEnd**:bezel 内 t 到多少拉满(默认 0.50) +- 用于减轻「图标被拽进内侧、外圈大黑缝」,与色散正交,删除色散后仍可保留。 + +## 4. 色散算法(已删除部分) + +### 4.1 参数 + +| Uniform / API | 默认 | 含义 | +|---------------|------|------| +| `dispersion` / `dispersionPx` | 5 | 最大通道分离(像素量级) | +| `dispersionWidth` | 6 | 环带宽度(从玻璃外缘向内,px);0=关 | +| `dispersionBlend` | 0.75 | 混入强度 | + +DConfig:`glassDispersionPx` / `glassDispersionWidth` / `glassDispersionBlend`。 + +### 4.2 空间 mask + +```text +fringeMask = smoothstep 从外缘向内 width 像素 +fringeMask = fringeMask² * blend +``` + +仅在此外圈环带做 CA;带外只用 G 路径单次采样。 + +### 4.3 分通道折射幅度 + +```text +di ∝ dispersion * fringeMask +iorR = ior - di, iorG = ior, iorB = ior + di // 蓝光 n 更大 +magR, magG, magB = 各自 Snell 幅度 +// 保证最小分离,避免 di 太小时看不出 CA: +if (magB - magR < dispersion*fringeMask) + 以 magG 为中心强制拉开 minSplit +uvR/G/B = texCoord + inward * magR/G/B / size +color = mix(sG, vec3(sR.r, sG.g, sB.b), fringeMask) +``` + +要点: + +- **方向相同**(都是 `inward`),只变 \|pull\| +- **不**用未折射的 `texCoord` 单独作为 R 通道(避免露底叠红) +- 结果色来自背景采样差,不是固定调色板 + +### 4.4 与错误实现的对比 + +| 错误 | 后果 | +|------|------| +| R 采 `texCoord`(位移 0),B 大位移 | 露底图 + 叠红 | +| 固定蓝/青 `mix` 染色 | 像描边不是色散 | +| CA 强度绑整块 displacement | 整个折射区都在色散,width 失效 | +| 轴对齐大 offset | 矩形色带,不贴圆角弧 | + +## 5. 已知局限(删除原因) + +1. 环带锚在 **玻璃 SDF 外缘**,不是严格的「折射后图标轮廓」;易与目标效果的「贴小圆角的弧形膜」不一致。 +2. 最小 px 分离与 Snell 微差混用,大 thickness 时仍可能脏边、黑点(远处深色被拉开)。 +3. 多次调参仍难稳定达到「细、柔、青蓝、弧形填缝」观感。 +4. 产品决策:**去掉色散**,只保留单通道折射玻璃。 + +## 6. 删除后的代码状态 + +- Shader:仅 `magG` 单次折射采样 + Fresnel 高光 +- 移除 uniforms / QML / dconfig / test_glass 滑条 / 色散单测 +- **保留** `contentEdgePull` / `contentRampEnd` / `refractionMaxTan`(折射塑形,与色散无关) + +## 7. 若将来重做,建议顺序 + +1. 先把单通道 distortion 做到:直线进圆角连续弯、内容贴边、无大黑缝 +2. 再在**折射 UV**上做 1–3px 级 CA,mask 跟折射梯度或内容轮廓走 +3. 最后才加 Fresnel/Bloom +4. 验收以 QQ 顶弧是否「细青蓝膜」为准,而不是 RGB 分离是否「够大」 + +--- + +*文档对应删除前工作树中的 `liquidglass.frag` 实现;删除提交见后续 git history。* diff --git a/docs/session-architecture.md b/docs/session-architecture.md new file mode 100644 index 0000000000..a4c715e532 --- /dev/null +++ b/docs/session-architecture.md @@ -0,0 +1,159 @@ +# DesktopEnvironment 多用户对象框架 + +隔离单位是 Session,一个 Session 对应一个用户;合成器共用同一个 wl_display。 +Session 负责身份、客户端连接、协议归属和生命周期。DesktopEnvironment 是用户业务对象的 +组装入口,其公开 API 不提供 Session、用户名或 activeSession 查询。 + +```text +共享运行时:WServer / backend / renderer / 物理 output / 物理 input + │ + └── SessionCoordinator(目前由 SessionManager 承担) + ├── Session A ── DesktopEnvironment A + └── Session B ── DesktopEnvironment B + +DesktopEnvironment +├── config / 配置 providers(构造时固定) +├── surfaces(完整 surface 集合,包括 LayerSurface) +├── windows(顶层窗口集合) / Workspace +├── InputManager +├── WallpaperManager +├── SessionOutputManager / 逻辑输出 +├── SessionSwitcher / ShortcutRunner +└── viewRoot + ├── DockPreview(独立实例、固定绑定) + └── TaskSwitcher(按需创建、固定绑定) +``` + +## 依赖与生命周期 + +InputManager、WallpaperManager、SessionSwitcher、ShortcutRunner 和 SessionOutputManager +均为普通 QObject,不再继承 SessionComponent,也不接收 Session。配置、工作区、逻辑 seat、 +设备目录、壁纸资源服务由组装入口注入;输出参数注入共享系统配置。业务对象不查询当前用户,也不遍历其他 Session。 + +SessionManager 在登录身份确定后创建完整对象树。Session::setActive 只通知桌面启用/停用; +DesktopEnvironment 切换 UI 根节点和快捷键订阅;SessionInputChannel 负责输入硬件订阅。ShortcutRunner 直接使用 +自己的工作区和切换器,不通过全局 taskSwitcher 取得另一套桌面的 UI。 + +配置初始化失败时使用生成默认值;尚未初始化时等待完成通知。配置回调重新处理本对象的 +逻辑 seat,即使回调跨过一次用户切换,也不会按新的活动用户解释旧请求。 + +## 硬件边界 + +SessionOutputChannel 是身份相关的适配层,负责 primary、缩放、颜色提交 +和输出协议配置请求的授权。显示模式使用 TreelandConfig,每屏参数使用共享 OutputConfig。 +SessionOutputManager 发布实际硬件状态的独立协议视图,不保存个人显示参数,不在切换时恢复模式。 +需要修改物理设置时调用通道;只有通道判断硬件是否接通。逻辑输出的 surface 校验使用所属桌面的完整 surface +集合,不能用顶层窗口列表,否则会错误拒绝任务栏等 LayerSurface。 + +物理 Output 是共享设备投影,只通过 WaylandServer 的桌面目录访问逻辑输出,不解析 Session。 +物理输出调试 UI 的缩放命令通过运行时命令入口转发,不在 QML 查询当前用户。 + +## QML 边界 + +TaskSwitcher 和 DockPreview 使用 `required property DesktopEnvironment desktop`,创建时 +注入并固定;切换用户不改写其依赖,也不重新连接 DockPreview 的协议对象。 +窗口通过 `surface.desktop` 提供固定业务模型,不向 QML 暴露 `surface.session`。 +标题栏使用所属桌面的配置;WorkspaceSwitcher 注入自己的 Workspace;WorkspaceProxy 从 +WorkspaceModel.workspaceManager 获取所属工作区,包括“所有工作区”窗口列表。 + +Session 的业务 Q_PROPERTY、SurfaceWrapper.session 和运行时的 activeSession QML 属性已移除;C++ 边界接口保留。业务 QML 不应添加 session/activeSession 查询,也不应 +新增对 WaylandServer.config/workspace 等活动桌面兼容入口的依赖。 + +## 迁移范围与限制 + +本轮完成上述业务对象、独立 DockPreview/TaskSwitcher、窗口与工作区预览入口的迁移。 +部分共享运行时、协议安全边界和旧插件(例如多任务视图、锁屏)仍保留兼容访问;它们尚未 +全部迁为独立桌面对象。本轮不代表所有 Wayland 协议的资源隔离已经完成,剩余边界见 +[协议隔离审计](session-protocol-isolation.md)。 + +未进行编译、QML 编译或运行时测试。协议隔离 fixture 已增加真实对象树、父对象归属和 +QML desktop 属性固定绑定的源码断言,等待在允许构建的环境执行。 + +## SessionInputChannel + +输入启停与边界状态集中在 src/session/sessioninputchannel.*,业务对象不查询 Session。 +每个通道独立持有 CompositorInputFilter、GestureManager/GestureRecognizer 和 +ShortcutController,并将过滤器固定绑定到本用户的逻辑 WSeat。共享运行时仅保留启动过滤器 +和按实际 seat 发送的 relative-pointer transport;用户桌面启用后启动过滤器停用。 + +停用顺序为关闭事件入口、取消 swipe、停止 hold 计时器、断开输入设置硬件订阅、取消本通道 +的快捷键捕获,然后关闭桌面 UI 与快捷键动作订阅。后台通道销毁不会取消前台用户的捕获。 +启用时清理旧过滤键状态,对切换前按住的键和按钮进行隔离;旧序列的 release/update/end +不能触发新用户动作。逻辑 seat 清除键盘窗口焦点时停止自动重复。 + +过滤器在 beforeDispose、beforeHandle 和 afterHandle/unaccepted 阶段检查入口是否启用、 +设备是否确属事件 seat;目标 surface 通过逻辑 seat 的固定协议域验证。活动通知使用事件 +seat,不能使用全局默认 seat。ShortcutRunner 只订阅自己的过滤器 modifier-release 信号。 + +每个 SessionInputChannel 还持有独立的 ShortcutManagerV3 协议实例,使用 Session::attachInterface +固定客户端作用域。绑定、解绑、捕获和通知始终作用于同一个控制器;后台用户的请求立即 +更新自己的对象。用户切换不再更换协议内部的 controller,也不清空、缓存或回放绑定。 +ShortcutRunner 的通知和修饰键查询直接使用注入的协议及控制器。 + +CompositorInputFilter 只依赖 InputContext,不再持有 WaylandServer。SessionInputContext +作为边界适配器验证 seat 归属,并从本用户的 surface 模型解析窗口;焦点和边缘平铺请求 +经过该边界。锁屏模式、VT 切换和调试视图属于共享运行时能力,由适配器提供。 +输入过滤器、快捷键协议与 QML 无需查找当前 Session。 + +每个控制器只在注入的 GestureManager 注册手势。不同桌面不再共享识别器、hold +计时器、累计 swipe delta 或按键动作表。TogglableGesture 也支持显式注入手势管理器。 + +新增真实对象状态断言检查 A/B 通道、过滤器、手势管理器、控制器、协议及逻辑 seat 绑定独立。 +双 Session C 客户端还检查同名绑定各自生效、后台 upsert 后解绑不保留旧绑定、切换保留绑定。 +本次没有引入独立的通用 SessionInputRouter 或完整输入序列代次机制;物理设备交接仍由 +SeatManager 与 SessionInputChannel 配合完成。屏幕选择捕获、空闲与输出唤醒、relative-pointer +传输及 shortcuts-inhibit 仍共享基础设施,本次不代表这些服务已经全部完成 Session 化。 +未编译或运行测试;需要真机验证 A 持续按键、鼠标拖动、三指滑动/长按期间切换 B,确认 +尾部事件与旧用户计时回调不触发 B 的动作。 + +## 系统显示配置 + +主屏、单屏、复制模式及复制输出组只使用 TreelandConfig。每块屏幕的分辨率、刷新率、 +缩放、旋转、位置和颜色参数只使用 `DConfigManager::outputConfig(outputId)` 的系统路径。 +旧 `//outputs/` 不再读写,也不会在切换时导入或恢复;已有系统路径 +和键名保持不变。用户文件中的五个显示模式键已撤回。 + +每个 Session 仍有独立 output-management 协议对象和 SessionOutput,协议快照同步同一份 +实际硬件状态;窗口列表、LayerSurface 和专属区域独立计算。活动通道授权硬件修改, +用户切换仅切换授权与桌面,不能修改系统显示模式。系统缩放更新同时同步所有已创建 +XWayland 的 XSettings,光标等个人偏好仍按所属用户同步。 + +已调整双 Session 回归用例:A/B 同读系统缩放 1.5,切换不回滚,B 的现有 head 收到变更, +A/B 面板仍分别占用 40/60。以上改动未编译、未运行测试。 + +## 窗口创建与启动匹配 + +SessionPrelaunch 为每用户持有独立的预启动协议、appId 解析协议、等待请求、闪屏及关闭 +记录。ShellHandler 仅根据真实 surface 客户端所属 Session 路由;不能按全局 appId 查找、 +关闭或转换其他用户窗口。配置初始化回调固定使用请求所属 Session,附带请求代次; +旧请求回调、重复请求和旧闪屏超时不得删除新请求或已转换的正常窗口。协议 close 使用 +appId 与 instanceId 匹配本用户请求。应用历史配置的持久化仍使用现有 WindowConfigStore +路径,本轮未改变其 appId 级存储归属。 + +窗口可见性缓存固定监听所属 Session 的根 WSocket,而不是 XWayland 的子 socket。 +后台完成创建的窗口在根 socket 恢复时必须更新,纯闪屏也使用同一条通知路径。 +SurfaceWrapper 一旦绑定 Session,Release 路径同样禁止重新绑定到另一个用户。 + +新增回归检查同 appId 闪屏的独立创建和关闭,以及真实子 socket 的后台窗口在激活后恢复 +可见、切回原用户时原窗口仍存在。本轮只做源码静态检查,未编译或运行;子 socket 用例 +覆盖与 XWayland 相同的 socket 层级,不等于两个真实 XWayland 应用的真机复现证据。 + +## Session 展示域 + +SessionScene 是所有所属 surface 的统一展示边界,不只管理顶层窗口列表。普通用户停用后, +其窗口、弹窗、LayerShell、输入法窗口、闪屏及子 surface 的内容均不可展示或接收输入。 +窗口代理跟随源窗口权限,不能用预览 live 开关重新启用后台内容。QML 只读取中性的 +`renderingEnabled` 属性,不解析 Session。独立登录服务 dde 的锁屏/系统覆盖层维持专门 +系统通道;普通用户的 privileged 标记不能绕过停用。 + +停用时隐藏并禁用 item,给 surface 设置 NonLive,清退独立动画与离屏内容,释放过渡源。 +延迟动画回调及后台新建窗口同样受控。退出动画即使已从用户窗口模型移除,其 wrapper +仍由 SessionScene 跟踪到销毁,避免切换后继续显示上一用户画面。 + +切回时只恢复 Session 展示权限,再依据 mapped、最小化、工作区、显示桌面和锁屏状态 +计算最终可见性;不修改这些状态来强行显示所有窗口。底层输入入口按子 surface 的根窗口 +再次确认展示许可,并保留逻辑 seat 和客户端域校验。系统显示模式不随该展示开关恢复。 + +新增断言检查停用用户全部已注册 surface 的 renderingEnabled、visible、enabled 和 NonLive, +覆盖顶层窗口及 LayerShell;后台子 socket 用例也检查同一状态。尚未编译或运行;未覆盖 +真实 GPU 帧计数、所有弹窗/输入法类型、切换期间每种动画与输入事件的真机验证。 diff --git a/docs/session-protocol-isolation.md b/docs/session-protocol-isolation.md new file mode 100644 index 0000000000..cff8164407 --- /dev/null +++ b/docs/session-protocol-isolation.md @@ -0,0 +1,84 @@ +# Session 协议隔离边界审计 + +本文记录源码审计结果和需要确认的协议域设计;不表示已实现或验证全量隔离。 +已确认的约束是单进程、共享同一个 WServer/wl_display;采用协议级隔离。 +SessionProtocols 是每个 Session 的协议集合,Session::attachInterface 通过 setOwnsSocket(socket) 设置不可变的 socket 所有权边界。 +未编译、未运行测试。 + +## 当前源码中的共享边界 + +| 协议/对象 | 当前入口 | 问题或必须检查的边界 | +| --- | --- | --- | +| xdg-shell、layer-shell | ShellHandler::init | 已迁入 SessionProtocols 独立实例;资源行为和子窗口关系的新增回归未运行 | +| xdg decoration/dialog/tag | SurfaceProtocolController::installDecoration | 已迁入 SessionProtocols;使用所属 xdg-shell 协议域 | +| prelaunch-splash / app-id-resolver | SessionPrelaunch | 协议、解析客户端、pending/closed appId 状态均固定到 Session;配置回调不使用活动用户;新增回归未运行 | +| Wine | SurfaceProtocolController::initializeSession | manager 已独立;仍需核对每条请求、窗口标识和事件目标 | +| XWayland | SessionManager::ensureSession | 进程和逻辑 seat 已独立,桌面/workarea 从所属 SessionOutput 计算;仍共享 output/xdg-output 公告 | +| wl_output / xdg-output | WOutput / WXdgOutputManager | 仍从物理输出/布局发布,后台客户端可能获得其他用户的状态变化 | +| wlr-output-management | SessionOutputManager | 独立协议对象发布共享系统硬件快照;切用户不恢复显示参数,新增三屏往返测试未运行 | +| wl_seat / input / text-input / input-method | SeatManager / WSeat / WInputMethodHelper | SessionSeatManager 独立持有逻辑 WSeat、serial、IME;活动 SeatManager 仅投影物理设备,新增回归未运行 | +| data-device / primary-selection / data-control / drag | WServerPrivate::init、installCommonProtocols、WSeat | 四组 manager 已迁入 SessionProtocols,selection 和拖放由所属逻辑 seat 保存;新增回归未运行 | +| xdg-foreign | installCommonProtocols | 每个 Session 使用独立 registry;exporter/importer 各有一个接口对象和 global,绑定相同所属 socket | +| personalization / appearance | WaylandServer / SurfaceProtocolController | personalization/appearance 已改为独立实例和固定配置,旧全局 appearance context 广播已移除;show-desktop 全局已随协议废弃删除,改由 compositor-action 触发 | +| capture / screencopy / session-lock / activation | CaptureManager / LockScreenManager / FocusController | activation 与窗口过渡 token 表已迁入 Session;捕获授权、输出枚举/结果及锁屏权限仍需迁移 | +| core compositor / subcompositor / shm / dmabuf 等 | WServer 及 renderer | 即便协议本身主要服务单客户端,也必须固定于资源所属协议域,不能默认绕过用户边界 | + +## 已选择:共享 wl_display 的协议级隔离 + +所有有状态协议必须迁移到固定 Session,不能用活动用户替代请求者。 +SessionProtocols 目前包含 shell、xdg 装饰/对话框/标签、personalization、appearance 等实例; +Wine、foreign-toplevel、output-management 等通过同一 Session::attachInterface 入口绑定所有权。 + +接口的 setOwnsSocket 只能设定一次,不会被协议自身 setFilter 替换;registry/bind 同时满足 +socket 所有权、协议自身过滤和服务器过滤。归属检查沿客户端 socket 的 parentSocket 链查找, +包含 XWayland/沙箱子 socket。Session 先关闭客户端,再解除协议,最后销毁所属 socket; +协议对象的生命周期不得超出所属 socket。Scoped global 在 detach 前撤下,防止原生对象 +随 display 延迟销毁期间变成无归属 global。未知 Session 的连接无法绑定 scoped global。 + +### 已选择:一个 wl_display、每协议实例和逻辑资源按 Session 路由 + +全部有状态协议分别实例化;wl_output、wl_seat 等基础 global 也必须提供用户独立的逻辑对象。 +显式登记可共享的无用户状态能力;未登记协议默认不向普通 Session 发布。 +所有绑定策略同时满足服务器策略和接口策略,不能使用早返回绕过全局边界。 + +公共资源上下文记录不可变 Session,子资源继承它;对象参数、窗口 ID、token、输出和 seat +都在所属上下文查询;事件只能遍历所属实例的资源集合。异步任务携带 Session 和激活代次。 +同一客户端的新 registry 和重新 bind 不能改变原连接的 Session。 + +这种设计仍要求逐协议迁移原生 wlroots/waylib 全局,不能靠统一 registry filter 自动约束 +已经绑定的资源,也不能通过冻结客户端进程代替事件隔离。 + +## 公共代码已发现并修正的缺口 + +WServer 的 globalFilter 原先在接口 filter 返回 true 时直接返回,跳过服务器级策略。 +现改为两层过滤都必须通过,xwayland_shell 的特定客户端检查也不能绕过服务器策略。 +新增 socket 所有权是独立于协议 filter 的固定约束;这仍不代表未迁移协议的资源/事件已完成隔离。 + +## 迁移验收 + +1. 为每个协议登记所有权、资源创建入口、请求域、事件域、异步任务和销毁路径。 +2. 从 shell/output/seat/selection 迁移基础资源,再迁移依赖它们的协议族。 +3. 每个协议族使用真实的两个用户连接,断言私人窗口/输入操作不改变另一 Session 的模型或私有事件;系统显示变更则通知各 Session,并保持协议对象和 head 身份稳定。 +4. 覆盖同一连接多次切换、重新绑定、新增用户、退出重登、热插拔和延迟回调。 +5. 验证用户退出只销毁自己的协议域,合成器退出不回调已销毁硬件服务。 + +## 逻辑 seat 的硬件投影 + +SessionSeatManager 在创建时取得固定 Session;每个 Session 都拥有独立的 WSeat/native seat, +seat 名称可相同但对象绝不复用。InputMethodHelper 通过 Session::attachInterface 创建五种 +协议工厂;同一 Session 的多个 helper 共享这些工厂,以实际 seat 对象路由,而非比较名称。 +候选框管理器、XWayland seat 和 IME helper 不随其他用户切换改写归属。 + +SeatManager 只保留活动域的投影。切换先清除旧焦点、结束 pointer/keyboard/touch grab, +再转移 backend 的物理设备及硬件光标;用户虚拟键盘、selection/primary selection、资源和 +serial 留在原 Session。后台 seat 没有合成器窗口焦点,不能将虚拟键盘事件注入活动桌面。 +移除 seat 时同步释放 SeatSurfaceManager 的 native listeners,然后才销毁 native seat。 + +wl_data_device_manager、primary-selection、wlr/ext data-control 均为 Session 内实例。 +xdg-foreign 的 importer/exporter 共用本 Session 的 registry,不再共用 display 级 token 表。 +WServerInterface 支持协议族的多个 globals,创建时过滤和 detach 时撤下均覆盖所有 globals。 + +仍未完成:wl_output/xdg-output 的逻辑公告;捕获、输出 power/gamma、部分私有 +协议和共享桌面控制器。不能将本次 seat/selection 迁移当作全量隔离已完成。未编译、未运行测试。 + +激活协议通过 FocusController::registerSession 创建固定域实例;pending transition rect 表由 SessionProtocols 持有。请求处理核对目标/来源的 Session,再查本用户 token 表。 diff --git a/docs/waylandserver-architecture.md b/docs/waylandserver-architecture.md new file mode 100644 index 0000000000..ce91599322 --- /dev/null +++ b/docs/waylandserver-architecture.md @@ -0,0 +1,68 @@ +# WaylandServer composition + +`WaylandServer` is the `Treeland.WaylandServer` QML singleton and the +C++ desktop entry point. It composes the Wayland runtime and feature managers. +The former `Helper` compatibility class has been removed; production C++, QML, +plugins and protocol fixtures now refer directly to `WaylandServer`. +Its properties, enums, signals, invokables and slots retain their behavior. + +## Responsibilities + +| Component | Responsibility | +| --- | --- | +| `WaylandServer` | Owns the Wayland runtime and QtQuick scene, creates globals, composes feature services, coordinates desktop modes and applies ready user settings. | +| `CompositorInputFilter` | Preserves the ordered input dispatch path, event-seat scope, gestures, shortcuts and relative pointer forwarding. | +| `FocusController` | Implements activation policy and activation protocol requests; delegates per-seat focus state to `SeatSurfaceManager`. | +| `SurfaceProtocolController` | Binds surface lifecycle to decoration, personalization, foreign-toplevel and region-watch protocols. | +| `DragController` | Owns per-seat drag listener bundles and forwards existing drag notifications. | +| `IdleManager` (`src/idle/`) | Owns idle protocol listeners and evaluates the existing inhibition policy. | +| `CaptureManager` (`src/capture/`) | Binds capture protocols, manages the selection UI and handles foreign-toplevel capture requests. | +| `ShowDesktop` (`src/showdesktop/`) | Owns show-desktop state, transitions and focus restoration. | +| `LockScreenManager` (`src/lockscreen/`) | Binds lock-screen implementations, logind notifications and external session locks. | +| `DConfigManager` (`src/dconfig/`) | Owns cached configuration objects, waits for active-user/seat configuration initialization and discards stale user-switch completions. | + +Existing `SeatManager`, `OutputManager`, `ShellHandler`, `SessionManager`, +`InputManager` and `WallpaperManager` retain their responsibilities. +The new feature controllers receive dependencies explicitly and do not look up +`WaylandServer::instance()`. Callers use the WaylandServer API directly. + +## Startup order + +`WaylandServer::init()` composes the following stages: + +1. Connect application/session signals and obtain QML singleton models. +2. Set up the scene, backend and seat manager. +3. `installDesktopProtocols()` registers the protocols and QML types installed + before starting the display. +4. Start the `WServer` display. +5. `initializeSeatsAndShell()` installs the input filter, assigns devices and + initializes the shell. +6. `installRuntimeProtocols()` creates rendering resources and installs the + remaining capture, surface, input, session-lock and desktop protocols. +7. Start the backend and notify `OutputManager` that its initial scan has started. + +This extraction preserves the original ordering, protocol versions, failure +branches and asynchronous output/configuration handling. Starting the display +still does not mean output initialization has completed. + +## Lifetime boundaries + +`WaylandServer` owns `WServer` as a QObject child and owns the renderer and +allocator handles through `WUniquePointer`, which invokes their wlroots destroy +functions. It observes the display-owned compositor handle through `WPointer`; +`WPointer` does not transfer ownership. + +Feature controllers own their listener state. `IdleManager` and +`CaptureManager` detach their top-level native listeners before scene teardown. +The shell and root scene are removed while feature bindings still exist. Remaining +controller state is then released, before QObject child cleanup destroys the +Wayland runtime. Drag listener ownership remains grouped by `WListenerOwner`. + +QML properties and desktop methods forward to the corresponding controller. +Desktop mode remains coordinated by `WaylandServer`; per-seat focus state +remains in `SeatSurfaceManager`. `DConfigManager::configReady` feeds the +existing configuration-application path, including `configChanged()` and input, +wallpaper, cursor and workspace synchronization. + +This is an architectural extraction. It does not add new compositor behavior, +change existing policies, or add a runtime restart contract. diff --git a/docs/window-decoration-matrix.md b/docs/window-decoration-matrix.md new file mode 100644 index 0000000000..69b692774b --- /dev/null +++ b/docs/window-decoration-matrix.md @@ -0,0 +1,236 @@ +# 窗口装饰器 / 圆角 / 默认值一览 + +> 状态:2026-11-11 更新。本文汇总 `SurfaceWrapper` 各窗口类型下「是否画装饰器(SSD 边框 + +> 阴影)、是否画标题栏、默认圆角」的实际行为,以及目前散落在各处的特判。 +> +> 核心代码位置: +> - 类型定义:`src/surface/surfacewrapper.h`(`enum class Type`) +> - 构造默认值:`src/surface/surfacewrapper.cpp`(三个构造函数初始化列表) +> - 装饰器/标题栏创建:`SurfaceWrapper::setNoDecoration()` / `updateDecoration()` / +> `updateTitleBar()` +> - 请求半径:`SurfaceWrapper::radius()` / `setRadius()` / `setNoCornerRadius()` +> - 实际几何:`SurfaceWrapper::frameGeometry()` / `src/surface/framegeometry.*` +> - 圆角渲染(裁剪):`src/core/qml/FrameClip.qml` +> - 输入裁剪与 resize:`src/surface/frameinputmask.*` +> - 边框 + 阴影渲染:`src/core/qml/Decoration.qml`(`XdgShadow` + `Border`) +> - 协议仲裁:`src/core/surfaceprotocolcontroller.cpp`(`onSurfaceWrapperAdded`) +> - DConfig 默认值:`misc/dconfig/org.deepin.dde.treeland.user.json` + +--- + +## 1. 关键不变量(先记住这三条) + +1. **装饰器默认是「关」的。** 所有 `SurfaceWrapper` 构造函数里 `m_noDecoration = true`、 + `m_noTitleBar = true`。只有某条路径显式调用 `setNoDecoration(false)` / + `setNoTitleBar(false)`,才会创建 SSD 边框 + 阴影 / 标题栏。 +2. **`noTitleBar()` 已经包含 `noDecoration`。** getter 返回 + `m_noTitleBar || m_noDecoration`(全屏时恒为 true)。所以「无边框」的窗口**不可能**有 + 标题栏,`setNoTitleBar(false)` 也不会让无边框窗口凭空长出标题栏。 +3. **实际圆角只由 `SurfaceWrapper::frameGeometry` 决定。** 有装饰器、装饰可见、 + 未设置 `noCornerRadius` 且不是软件渲染时,才使用请求半径;其余情况实际半径为 0。 + 标题栏、客户区、边框、阴影和输入不能再各自推导实际圆角。 + +### 全局默认值(DConfig) + +| 项 | 默认值 | 位置 | +| --- | --- | --- | +| 窗口圆角 `windowRadius` | **12** | `org.deepin.dde.treeland.user.json` | +| 标题栏高度 `windowTitlebarHeight` | **40** | 同上 | +| 阴影 | blur 40、offset (0,10)、rgba(0,0,0,0.4)、可见 | `SurfaceWrapper` 成员默认值 | +| 边框 | width 1、rgba(0,0,0,0.1)、可见 | 同上 | + +--- + +## 2. 各类型矩阵 + +| Type | 装饰器(边框+阴影) | 标题栏 | 默认圆角 | 说明 | +| --- | --- | --- | --- | --- | +| `XdgToplevel` | 取决于 xdg-decoration(见 §3) | 取决于 personalization / decoration 协议 | DConfig `windowRadius`(12) | 唯一常规「有标题栏」的类型 | +| `XdgPopup` | 跟随 parent;treeland-decoration 调用后强制有 | ❌ 无 | **8**(硬编码) | 无尺寸调整 MouseArea | +| `XWayland` | 取决于 X11 装饰 hints | 取决于 X11 装饰 hints | DConfig `windowRadius`(12) | 默认有边框 + 标题栏 | +| `Layer` | ❌ 无(默认 `true`);treeland-decoration 调用后强制有 | ❌ 无 | **0** | 不参与 DConfig 圆角回退;quick-launchpad 有兼容特判 | +| `InputPopup` | ❌ 无 | ❌ 无 | **0** | `isInputPopupLike()` | +| `LockScreen` | ❌ 无(显式 `setNoDecoration(true)`) | ❌ 无 | 名义 12,但无装饰器故不生效 | 全屏锁屏面 | +| `SplashScreen`(prelaunch) | ✅ 有(`setNoDecoration(false)`) | ❌ 无 | DConfig `windowRadius`(12) | `updateDecoration()` 显式跳过标题栏;未指定尺寸时默认 800×600 | +| IM 候选面板(flag) | ❌ 无(强制 `setNoDecoration(true)`) | ❌ 无 | **0** | `m_isIMCandidatePanel` → `isInputPopupLike()` | +| 截图 mask | ❌ 无 | ❌ 无 | **0** | `setNoCornerRadius(true)` + `setNoDecoration(true)` | + +> 「名义 12,但无装饰器故不生效」:`LockScreen` 的 `radius()` 会命中 DConfig 回退返回 12, +> 但因为 `m_noDecoration = true`,`SurfaceContent.qml` 的裁剪条件不满足,实际渲染是直角。 + +--- + +## 3. XdgToplevel 装饰器 / 标题栏的仲裁逻辑 + +这是最复杂的路径,集中在 `SurfaceProtocolController::onSurfaceWrapperAdded`。 + +### 3.1 装饰器(SSD 边框 + 阴影) + +由 **xdg-decoration 协商结果**决定,与标题栏是两个独立轴: + +```cpp +wrapper->setNoDecoration(mode != WXdgDecorationManager::Server); +``` + +`mode` 取值(`WXdgDecorationManager::DecorationMode`): + +| mode | 含义 | 装饰器 | +| --- | --- | --- | +| `Server` | 客户端要求服务端装饰 | ✅ 有 | +| `Client` | 客户端要求自绘(CSD) | ❌ 无 | +| `None` | 客户端发送 "unset" | 回退到 `preferredMode`(默认 `Server`)→ ✅ 有 | +| `Undefined` | 客户端从未创建 decoration | ❌ 无(当作 CSD) | + +> 注意:**客户端不主动协商 xdg-decoration 时默认无 SSD 边框**,符合现代合成器惯例。 +> 有两条写入路径:全局 `onSurfaceModeChanged()`(容器查找)负责注册后的实时变化; +> `onSurfaceWrapperAdded` 里的初始回放负责「协商发生在 wrapper 注册之前」的竞态。 + +### 3.2 标题栏 + +由两个协议源合并仲裁(单一写入点 `updateNoTitlebar`): + +```cpp +setNoTitleBar(attached->noTitlebar() || decorationHides); +``` + +- `attached->noTitlebar()`:旧 personalization 协议(`set_titlebar(disable)` → NoTitleBar)。 +- `decorationHides`:新 decoration 协议(`set_titlebar_mode(hide)`)。 +- 两个源任一为 true → 无标题栏;都为 false → 有标题栏(前提是有装饰器,见不变量 2)。 + +> 默认行为总结:客户端**完全不协商任何协议**时,xdg-decoration mode 为 `Undefined` +> (无装饰器),标题栏虽被 `setNoTitleBar(false)` 请求,但被不变量 2 拦下——实际结果是 +> **无边框、无标题栏**。只有 xdg-decoration 协商到 `Server`(或 `preferredMode` 回退) +> 后,标题栏才会真正出现。 + +### 3.3 状态切换(最大化 / 全屏 / 平铺) + +`SurfaceWrapper::applySurfaceState()`: + +```cpp +setVisibleDecoration(newSurfaceState == State::Normal); // 非 Normal 隐藏装饰器 +setNoCornerRadius(Maximized || Fullscreen || Tiling); // 非 Normal 无圆角 +``` + +所以最大化 / 全屏 / 平铺窗口**直角 + 隐藏阴影边框**,恢复 Normal 后回到圆角。 + +--- + +## 4. 现有特判清单(改动装饰器 / 圆角 / 标题栏的地方) + +| # | 特判 | 代码位置 | 行为 | +| --- | --- | --- | --- | +| 1 | `XdgPopup` | `surfaceprotocolcontroller.cpp` popup 分支 | `setNoTitleBar(true)`;装饰器跟随 parent(`parentSurface()->noDecoration()`),treeland-decoration 调用后强制有。圆角固定 8 | +| 2 | **quick-launchpad 兼容**(COMPAT) | `surfaceprotocolcontroller.cpp` | 旧 personalization 协议仍驱动 quick-launchpad;`isQuickLaunchpad() && noTitlebar()` 时 `setNoDecoration(false)` 恢复边框。**TODO:dde-shell 迁移到新 decoration 协议后连同旧协议一起删** | +| 3 | 大启动器 cover | `surfaceprotocolcontroller.cpp` | `isLaunchpad()` → `setCoverEnabled(true)`(`LaunchpadCover.qml` 壁纸背景) | +| 4 | 启动器层级 | `shellhandler.cpp` | layer Top 的 `isLaunchpad() \|\| isQuickLaunchpad()` → `setZ(-1)` | +| 5 | 桌面层级 | `shellhandler.cpp` | layer Background 的 `isDesktop()` → `setZ(1)` | +| 6 | XWayland 装饰 | `surfaceprotocolcontroller.cpp` xwayland 分支 | 按 X11 的 `NoTitle` / `NoBorder` hints 设置标题栏与边框 | +| 7 | IM 候选面板 | `imcandidatepanelmanager.cpp` | `setIMCandidatePanel(true)` + `setNoDecoration(true)`;`isInputPopupLike()` 使圆角归 0 | +| 8 | 截图 mask | `capture.cpp` | `setNoTitleBar(true)` + `setNoCornerRadius(true)` + `setNoDecoration(true)` | +| 9 | 锁屏面 | `lockscreen.cpp` | `setNoDecoration(true)` + skip switcher/multitask | +| 10 | prelaunch splash | `surfacewrapper.cpp` 构造函数 | `setNoDecoration(false)` 给启动画面画边框阴影;`updateDecoration()` 对 SplashScreen 跳过标题栏 | +| 11 | 全屏/最大化/平铺 | `applySurfaceState()` | 隐藏装饰器 + 无圆角(见 §3.3) | +| 12 | treeland-decoration 强制装饰器 | `decorationmanagerinterfacev1.cpp` | 非 toplevel(popup/layer)一旦调用 decoration 协议任意接口,即 `setNoDecoration(false)` 启用合成器边框,**不可撤销**(popup 的 parent 跟随需在 Decoration 之前完成,见下方注);其 `set_titlebar_mode` 被忽略 | + +> 注(顺序敏感):`onSurfaceWrapperAdded` 里 popup 的「跟随 parent 装饰状态」分支必须 +> 在 `new Decoration(...)` 之前执行。`Decoration` 构造会应用已存在的 decoration context, +> 该 opt-in 必须覆盖 popup 的 parent 跟随默认值。不要把 popup 分支移到 Decoration 之后。 + +--- + +## 5. 圆角计算细节 + +`SurfaceWrapper::radius()`: + +```cpp +if (isInputPopupLike()) return 0; // InputPopup / IM 候选面板 +if (m_type == Type::XdgPopup) return 8; // popup 固定 8 +qreal radius = m_radius; +if (radius < 1 && m_type != Type::Layer) + radius = ...windowRadius(); // DConfig,默认 12 +return radius; +``` + +- `m_radius >= 1` 表示有 per-window 显式覆盖(旧 personalization `set_corner_radius` 或新 + decoration `set_corner_radius`),直接使用(`radius < 1` 时才回退到 DConfig)。 +- `Type::Layer` 被**排除**在 DConfig 回退之外 → layer(含启动器)默认圆角 0,compositor 不 + 给 layer 画圆角;如需合成器圆角,layer 必须显式请求,不能依赖用户配置回退。 +- 两种协议的 corner radius 写入**未仲裁**(见代码 NOTE:客户端只应使用其中一种,后到的 + signal 覆盖先到的)。 + +### 实际几何与坐标系 + +上述 `radius()` 是请求值,`frameGeometry.radius` 才是实际值:满足装饰和渲染条件时, +限制在 `[0, min(frameWidth, frameHeight) / 2]`;其余情况为 0。非法/空尺寸不可命中。 + +- `frameGeometry.rect` 使用 `frameItem` 的逻辑坐标,包含标题栏,不包含阴影。 +- 普通窗口的 `frameItem` 是 `surfaceItem`;预启动时是 splash。 +- 客户区通过 content container 的位置、缩放映射几何;bufferSourceRect 只影响纹理采样。 +- 大圆角按整窗尺寸归一化。标题栏和客户区使用同一轮廓的切片,不能按局部高度再次限制半径。 +- 尺寸、装饰、半径和窗口状态变化更新几何;`setSession()` 后订阅所属 Desktop 的固定 DConfig 对象, + 活动用户切换不改变已有窗口的配置归属,无需监听 `WaylandServer::configChanged`。 +- splash 消费实时几何;proxy 的显式半径覆盖保留,其阴影采用代理实际半径乘显示缩放。 + +### 输入契约 + +`FrameInputMask` 把目标 Item 的局部点映射到外框坐标,采用有限、左上包含右下排除的边界。 + +- 客户区:native input_region 与合成器圆角取交集;圆角关闭时移除额外 mask。 +- 标题栏:自身矩形与整窗轮廓取交集,子控件也受局部裁剪约束。 +- resize:外扩轮廓减去窗口内部;角上返回两条边,零半径保留矩形角点行为。 +- mask、光标和 resize 请求统一使用 `edgesAt()`,不能各用一套算法。 +- 带 X11 input shape 的窗口不额外制造 resize 外沿。native X Shape 判断不变。 +- 阴影参数不参与输入;不对整个 subsurface/popup 子树附加窗口裁剪。 +- 已经开始的鼠标/触摸 grab 不因移动到圆角外而转交给下层。 + +`FrameClip.qml` 复用同一几何进行渲染,GLSL 使用相同的外框尺寸、位置和半径; +抗锯齿像素不是新的输入区域,命中时不读取纹理或生成路径。 + +### 多任务缩略图高亮 + +- 普通窗口保留原有展示形状;最大化/全屏窗口按下述缩略图策略补圆角。高亮框本身不增加裁剪,也不修改原窗口状态。 +- 合成器管理的外框读取 `SurfaceProxy::effectiveRadius`:代理展示几何的有效半径乘代理显示缩放。 +- 完全客户端自绘(`noDecoration`)的窗口无法读取真实圆角,且非最大化时它的圆角与阴影都画在 buffer 边距里(在 `frameGeometry` 之外): + 因此这类窗口的**裁剪轮廓保持直角**(`SurfaceProxy::keepsClientSideMargins()` → `radius()` 返回 0,`FrameClip` 不激活,客户端的自绘阴影不被裁掉), + 高亮框用一个固定的 6 个缩略图逻辑像素展示值(`effectiveRadius`)。 +- 最大化/全屏的 CSD 窗口已经丢掉边距(没有自绘角与阴影),缩略图可以裁圆角。 +- 最大化/全屏窗口(CSD 与 SSD 一样)用**展示半径**:窗口半径不再乘缩略图缩放,直接沿用 `windowRadius` 的显示像素值 + (按窗口半径等比缩小后只剩几像素,看起来仍是直角),高亮框跟随该半径。 +- 有 padding 背景时,高亮包围的是背景卡片,沿用卡片自身的圆角。 +- 高亮外框在非零半径上加边框宽度;零半径仍为 0,不能因外扩又产生小圆角。 +--- + +## 6. 标题栏高度 + +- 标题栏高度来自 DConfig `windowTitlebarHeight`(默认 40),由 `TitleBar.qml` 消费, + 变化通过 personalization appearance 协议推送。 +- `updateTitleBar()` 创建标题栏后设置 `m_surfaceItem->setTopPadding(m_titleBar->height())`, + 内容区下移。 +- 代理借用源窗口所属 Desktop 的配置,标题栏保持相同逻辑高度,再随整窗缩放; + 不注册为真实窗口,也不改变源窗口配置。代理的显式半径(包括 0)不回退到 DConfig。 + +--- + +## 7. 回归测试 + +- `test_frame_geometry`:半径归一化、有限外沿、跨标题栏的圆弧、非零原点、 + 1×/1.25×/2× 鼠标/触摸、原生 input_region 空洞、grab 保持和 mask 生命周期; + 直接加载六个生产窗口动画验证展示半径绑定;加载 `WindowHighlight.qml` 验证传入半径 + (含直角 0 与 CSD 展示值 6)、padding 卡片和动态属性更新。 +- `test_effect_glass`:直接加载生产 `FrameClip.qml`,比较裁剪像素与 CPU 命中, + 覆盖标题栏/客户区切片、缩放和非零纹理裁剪偏移;另验证 Glass 使用整窗坐标。 + +```bash +cmake --build --preset ci --target treeland test_frame_geometry test_effect_glass +ctest --test-dir build --output-on-failure -R '^(test_frame_geometry|test_effect_glass)$' +``` + +## 8. 修改这类代码时的检查清单 + +- [ ] 改了 `noDecoration` / `noTitleBar` 的赋值,确认有没有破坏「装饰器默认关」的不变量。 +- [ ] 确认 `noTitleBar()` getter 的 `m_noTitleBar || m_noDecoration` 语义:无边框窗口永无标题栏。 +- [ ] 新增窗口类型时补全矩阵:装饰器 / 标题栏 / 圆角三列都要说明。 +- [ ] 涉及 `Type::Layer` 的圆角时,记得它**不参与** DConfig 回退。 +- [ ] 旧 personalization 协议的 quick-launchpad COMPAT 块(§4 #2)是临时迁移代码, + TODO:dde-shell 迁移到新 decoration 协议后连同旧协议一起删。 +- [ ] 圆角渲染依赖 `decoration && visibleDecoration`,只设 radius 不设 decoration 不生效。 diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt new file mode 100644 index 0000000000..2423f98444 --- /dev/null +++ b/examples/CMakeLists.txt @@ -0,0 +1,29 @@ +set(MODULE_PATH ${PROJECT_SOURCE_DIR}/src/modules) + +add_subdirectory(test_window_blur) +add_subdirectory(test_wallpaper_color) +add_subdirectory(test_compositor-action) +add_subdirectory(test_xdgport_wallpaper) +add_subdirectory(test_output_manager) +add_subdirectory(test_pinch_handler) +add_subdirectory(test_hide_window) +add_subdirectory(test_data_control_manager) +add_subdirectory(test_region_watch) +add_subdirectory(test_capture) +add_subdirectory(test_snap_target) +add_subdirectory(test_window_appearance) +add_subdirectory(test_decoration) +add_subdirectory(test_dde_shell) +add_subdirectory(test_monitor_active_event) +add_subdirectory(test_shortcut_manager) +add_subdirectory(test_shortcut_capture) +add_subdirectory(test_set_wallpaper) +add_subdirectory(test_set_xwindow_position) +add_subdirectory(test_idle_inhibit_v1) +add_subdirectory(test_toplevel_tag) +add_subdirectory(test_im_candidate_panel_tag) +add_subdirectory(test_im_candidate_panel_xprop) +add_subdirectory(test_input_manager) +add_subdirectory(test_keyboard_state_notify) +add_subdirectory(test_glass) +add_subdirectory(test-window-transition) diff --git a/examples/test-window-transition/CMakeLists.txt b/examples/test-window-transition/CMakeLists.txt new file mode 100644 index 0000000000..39b51fbbbd --- /dev/null +++ b/examples/test-window-transition/CMakeLists.txt @@ -0,0 +1,30 @@ +find_package(Qt6 REQUIRED COMPONENTS Gui WaylandClient Widgets) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS GuiPrivate WaylandClientPrivate) +endif() +find_package(PkgConfig REQUIRED) +pkg_get_variable(WAYLAND_PROTOCOLS_DATADIR wayland-protocols pkgdatadir) +find_package(TreelandProtocols REQUIRED) + +set(BIN_NAME test-window-transition) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${WAYLAND_PROTOCOLS_DATADIR}/staging/xdg-activation/xdg-activation-v1.xml + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-window-transition-unstable-v1.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::Widgets + Qt6::WaylandClient + Qt6::GuiPrivate + Qt6::WaylandClientPrivate +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test-window-transition/main.cpp b/examples/test-window-transition/main.cpp new file mode 100644 index 0000000000..51da4cc9fe --- /dev/null +++ b/examples/test-window-transition/main.cpp @@ -0,0 +1,676 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "qwayland-treeland-window-transition-unstable-v1.h" +#include "qwayland-xdg-activation-v1.h" + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// --------------------------------------------------------------------------- +// Protocol client wrappers — managers (globals) +// --------------------------------------------------------------------------- + +class XdgActivationManager + : public QWaylandClientExtensionTemplate + , public QtWayland::xdg_activation_v1 +{ + Q_OBJECT +public: + explicit XdgActivationManager() + : QWaylandClientExtensionTemplate(1) + { + } + + ~XdgActivationManager() override + { + if (isInitialized()) + destroy(); + } +}; + +class WindowTransitionManager + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_window_transition_manager_v1 +{ + Q_OBJECT +public: + explicit WindowTransitionManager() + : QWaylandClientExtensionTemplate(1) + { + } + + ~WindowTransitionManager() override + { + if (isInitialized()) + destroy(); + } +}; + +// --------------------------------------------------------------------------- +// Per-object wrappers +// --------------------------------------------------------------------------- + +class ActivationToken + : public QObject + , public QtWayland::xdg_activation_token_v1 +{ + Q_OBJECT +public: + explicit ActivationToken(::xdg_activation_token_v1 *obj, QObject *parent = nullptr) + : QObject(parent) + , QtWayland::xdg_activation_token_v1(obj) + { + } + + QString tokenString() const + { + return m_token; + } + +protected: + void xdg_activation_token_v1_done(const QString &token) override + { + m_token = token; + Q_EMIT done(token); + } + +Q_SIGNALS: + void done(const QString &token); + +private: + QString m_token; +}; + +class WindowTransitionRect + : public QObject + , public QtWayland::treeland_window_transition_rect_v1 +{ + Q_OBJECT +public: + explicit WindowTransitionRect(::treeland_window_transition_rect_v1 *obj, + QObject *parent = nullptr) + : QObject(parent) + , QtWayland::treeland_window_transition_rect_v1(obj) + { + } + + void setSourceImage(QtWaylandClient::QWaylandDisplay *display, const QPixmap &pixmap) + { + if (!display || !display->compositor()) + return; + + if (!m_sourceSurface) + m_sourceSurface = display->compositor()->create_surface(); + + delete m_shmBuffer; + m_shmBuffer = new QtWaylandClient::QWaylandShmBuffer(display, + pixmap.size(), + QImage::Format_ARGB32_Premultiplied); + QImage *image = m_shmBuffer->image(); + image->fill(Qt::transparent); + QPainter p(image); + p.drawPixmap(0, 0, pixmap); + p.end(); + + // The compositor renders this surface live during the transition, so + // it must be kept alive with valid content until closed. + wl_surface_attach(m_sourceSurface, m_shmBuffer->buffer(), 0, 0); + wl_surface_damage(m_sourceSurface, 0, 0, pixmap.width(), pixmap.height()); + wl_surface_commit(m_sourceSurface); + + set_source_surface(m_sourceSurface); + } + + void clearSourceImage() + { + set_source_surface(nullptr); + } + + ~WindowTransitionRect() override + { + if (m_sourceSurface) + wl_surface_destroy(m_sourceSurface); + delete m_shmBuffer; + } + +protected: + void treeland_window_transition_rect_v1_closed() override + { + Q_EMIT closed(); + } + +Q_SIGNALS: + void closed(); + +private: + ::wl_surface *m_sourceSurface = nullptr; + QtWaylandClient::QWaylandShmBuffer *m_shmBuffer = nullptr; +}; + +// --------------------------------------------------------------------------- +// Test image / icon palette +// --------------------------------------------------------------------------- + +struct IconPalette +{ + QColor from; + QColor to; +}; + +static constexpr int kPaletteCount = 2; +static const IconPalette kIconPalettes[kPaletteCount] = { + { QColor(63, 81, 181), QColor(33, 150, 243) }, // indigo -> blue + { QColor(76, 175, 80), QColor(0, 150, 136) }, // green -> teal +}; + +static QPixmap +createTestImage(const QString &text, const QColor &from, const QColor &to, int w, int h) +{ + QPixmap pm(w, h); + QPainter p(&pm); + QLinearGradient grad(0, 0, w, h); + grad.setColorAt(0, from); + grad.setColorAt(1, to); + p.fillRect(0, 0, w, h, grad); + p.setPen(QPen(QColor(255, 255, 255, 200), 4)); + p.drawRoundedRect(10, 10, w - 20, h - 20, 20, 20); + p.setPen(Qt::white); + QFont f = p.font(); + f.setPointSize(28); + f.setBold(true); + p.setFont(f); + p.drawText(QRect(0, 0, w, h), Qt::AlignCenter, text); + return pm; +} + +// --------------------------------------------------------------------------- +// Image / icon widget +// --------------------------------------------------------------------------- + +class IconWidget : public QWidget +{ +public: + explicit IconWidget(const QPixmap &pixmap, QWidget *parent = nullptr) + : QWidget(parent) + , m_pixmap(pixmap) + { + } + + void setPixmap(const QPixmap &pixmap) + { + m_pixmap = pixmap; + update(); + } + + void paintEvent(QPaintEvent *) override + { + QPainter p(this); + p.drawPixmap( + 0, + 0, + m_pixmap.scaled(size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation)); + } + +private: + QPixmap m_pixmap; +}; + +// --------------------------------------------------------------------------- +// Helper: get wl_surface from a widget +// --------------------------------------------------------------------------- + +static ::wl_surface *getWlSurface(QWidget *widget) +{ + QWindow *handle = widget->windowHandle(); + if (!handle || !handle->handle()) + return nullptr; + auto *waylandWindow = static_cast(handle->handle()); + return waylandWindow ? waylandWindow->surface() : nullptr; +} + +// --------------------------------------------------------------------------- +// Helper: get the wayland display behind a widget +// --------------------------------------------------------------------------- + +static QtWaylandClient::QWaylandDisplay *getWlDisplay(QWidget *widget) +{ + QWindow *handle = widget->windowHandle(); + if (!handle || !handle->handle()) + return nullptr; + auto *waylandWindow = static_cast(handle->handle()); + return waylandWindow ? waylandWindow->display() : nullptr; +} + +// --------------------------------------------------------------------------- +// Sender (Application A) +// --------------------------------------------------------------------------- + +class SenderWindow : public QMainWindow +{ + Q_OBJECT +public: + SenderWindow(XdgActivationManager *actMgr, WindowTransitionManager *transitionMgr) + : m_actMgr(actMgr) + , m_transitionMgr(transitionMgr) + { + setWindowTitle("Window Transition - Sender (press Space / .)"); + + auto *central = new QWidget(this); + auto *layout = new QVBoxLayout(central); + + auto *iconsLayout = new QHBoxLayout; + iconsLayout->setSpacing(24); + for (int i = 0; i < kIconCount; ++i) { + auto *column = new QVBoxLayout; + auto *icon = new IconWidget(iconPixmap(i), central); + icon->setFixedSize(200, 200); + column->addWidget(icon, 0, Qt::AlignCenter); + + auto *caption = new QLabel(m_iconCaptions.at(i), central); + caption->setAlignment(Qt::AlignCenter); + column->addWidget(caption); + + iconsLayout->addLayout(column); + m_iconWidgets.append(icon); + } + layout->addLayout(iconsLayout); + + auto *label = new QLabel("SPACE: launch receiver from icon 1 (new process)\n" + ".: launch receiver from icon 2 (new process)\n" + "ENTER: launch modal from icon 1 (same process)\n" + "0: toggle disable animation (hide icons)\n" + "B: toggle commit source surface\n" + "P: toggle icon color", + central); + label->setAlignment(Qt::AlignCenter); + layout->addWidget(label); + + m_sourceBufferIndicator = new QLabel("Commit source surface: ON", central); + m_sourceBufferIndicator->setAlignment(Qt::AlignCenter); + layout->addWidget(m_sourceBufferIndicator); + + setCentralWidget(central); + resize(560, 400); + } + + ~SenderWindow() override + { + // Destroy all rect objects so the compositor falls back + // to the default close animation once sender is gone. + for (auto &live : std::as_const(m_rects)) { + live.rect->destroy(); + } + m_rects.clear(); + } + +protected: + void keyPressEvent(QKeyEvent *event) override + { + if (event->key() == Qt::Key_Space) + launchReceiver(0); + else if (event->key() == Qt::Key_Period) + launchReceiver(1); + else if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) + launchModal(0); + else if (event->key() == Qt::Key_0) + toggleAnimation(); + else if (event->key() == Qt::Key_B) + toggleSourceBuffer(); + else if (event->key() == Qt::Key_P) + toggleIconPalette(); + QMainWindow::keyPressEvent(event); + } + + void resizeEvent(QResizeEvent *event) override + { + // The icon widgets are centered in the layout, so resizing the main + // window moves them. Re-set the persistent rect(s) with the updated + // geometry so the open/close animation follows the new position. + updateRectGeometries(); + QMainWindow::resizeEvent(event); + } + +private: + static constexpr int kIconCount = 2; + + QPixmap iconPixmap(int iconIndex) const + { + const auto &palette = kIconPalettes[m_paletteIndex]; + return createTestImage(m_iconCaptions.at(iconIndex), palette.from, palette.to, 200, 200); + } + + // Geometry (relative to this sender surface) of the icon widget that is + // the source of the window transition. + QRect animationRect(int iconIndex) const + { + auto *icon = m_iconWidgets.at(iconIndex); + const QPoint iconPos = icon->mapTo(this, QPoint(0, 0)); + return QRect(iconPos, icon->size()); + } + + void toggleAnimation() + { + m_animationDisabled = !m_animationDisabled; + for (auto *icon : std::as_const(m_iconWidgets)) + icon->setVisible(!m_animationDisabled); + // Hiding/showing the icons reflows the layout; force it before reading + // back the icon geometry. + centralWidget()->layout()->activate(); + updateRectGeometries(); + } + + void toggleSourceBuffer() + { + m_commitSourceBuffer = !m_commitSourceBuffer; + if (m_sourceBufferIndicator) + m_sourceBufferIndicator->setText(m_commitSourceBuffer ? "Commit source surface: ON" + : "Commit source surface: OFF"); + + auto *display = getWlDisplay(this); + for (auto &live : std::as_const(m_rects)) { + if (m_commitSourceBuffer && display) + live.rect->setSourceImage(display, iconPixmap(live.iconIndex)); + else + live.rect->clearSourceImage(); + } + } + + void toggleIconPalette() + { + m_paletteIndex = (m_paletteIndex + 1) % kPaletteCount; + + for (int i = 0; i < kIconCount; ++i) + m_iconWidgets.at(i)->setPixmap(iconPixmap(i)); + + // Re-commit the live source surfaces so a running transition shows the + // new color immediately, exercising the live-source path. + if (!m_commitSourceBuffer) + return; + auto *display = getWlDisplay(this); + if (!display) + return; + for (auto &live : std::as_const(m_rects)) + live.rect->setSourceImage(display, iconPixmap(live.iconIndex)); + } + + void updateRectGeometries() + { + if (m_rects.isEmpty()) + return; + // When disabled, keep setting a 0x0 rect so the compositor stays in + // the disabled state; a resize must not re-enable it. + for (auto &live : std::as_const(m_rects)) { + const QRect rect = m_animationDisabled ? QRect() : animationRect(live.iconIndex); + live.rect->set_geometry(rect.x(), rect.y(), rect.width(), rect.height()); + } + } + + ActivationToken *createLaunchToken() + { + if (!m_actMgr || !m_actMgr->isInitialized()) { + qWarning() << "xdg_activation_v1 not available"; + return nullptr; + } + + ::wl_surface *surface = getWlSurface(this); + if (!surface) { + qWarning() << "Cannot get wl_surface"; + return nullptr; + } + + // Create the activation token, identify the originating surface and + // commit it. The token string is delivered by the done event, after + // which the window transition rect can be created for it. + auto *rawToken = m_actMgr->get_activation_token(); + if (!rawToken) { + qWarning() << "Failed to create activation token"; + return nullptr; + } + auto *token = new ActivationToken(rawToken, this); + token->set_surface(surface); + token->commit(); + return token; + } + + void createTransitionRect(const QString &tokenStr, int iconIndex) + { + if (!m_transitionMgr || !m_transitionMgr->isInitialized()) + return; + + const QRect rectGeo = m_animationDisabled ? QRect() : animationRect(iconIndex); + auto *rawRect = m_transitionMgr->get_window_transition_rect(tokenStr); + if (!rawRect) + return; + + // Each launched window gets its own persistent rect. The rect + // stays alive (associated with that window) so it can drive + // that window's close animation. We must NOT destroy a + // previous rect here: doing so clears the close animation of + // a still-open earlier window. + auto *rect = new WindowTransitionRect(rawRect, this); + // When the compositor reports that the rect's target window + // has closed, the rect is useless: destroy it and drop it + // from our list. + connect(rect, &WindowTransitionRect::closed, this, [this, rect] { + for (int i = 0; i < m_rects.size(); ++i) { + if (m_rects.at(i).rect == rect) { + m_rects.removeAt(i); + break; + } + } + rect->destroy(); + }); + rect->set_geometry(rectGeo.x(), rectGeo.y(), rectGeo.width(), rectGeo.height()); + // Attach the icon image as a live source surface. The + // compositor renders it as the starting visual of the open + // animation (and the ending visual of the close animation). + auto *display = getWlDisplay(this); + if (display) { + if (m_commitSourceBuffer) + rect->setSourceImage(display, iconPixmap(iconIndex)); + else + rect->clearSourceImage(); + } + m_rects.append(LiveRect{ rect, iconIndex }); + + // Make sure the rect and its geometry reach the compositor before the + // token is handed to the target window, which may activate as soon as + // it starts. + if (display) + display->flushRequests(); + } + + void launchReceiver(int iconIndex) + { + auto *token = createLaunchToken(); + if (!token) + return; + connect(token, &ActivationToken::done, this, [this, iconIndex](const QString &tokenStr) { + createTransitionRect(tokenStr, iconIndex); + onReceiverToken(tokenStr); + }); + } + + void launchModal(int iconIndex) + { + auto *token = createLaunchToken(); + if (!token) + return; + connect(token, &ActivationToken::done, this, [this, iconIndex](const QString &tokenStr) { + createTransitionRect(tokenStr, iconIndex); + onModalToken(tokenStr); + }); + } + + void onReceiverToken(const QString &tokenStr) + { + qInfo() << "Got activation token, launching receiver..."; + + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + env.insert("XDG_ACTIVATION_TOKEN", tokenStr); + + // Do NOT parent the QProcess to this window: QProcess kills its + // child on destruction, so closing the sender would tear down the + // launched receiver along with it. Keep it parentless and let it + // self-clean once the receiver exits. + auto *proc = new QProcess; + proc->setProcessEnvironment(env); + connect(proc, &QProcess::finished, proc, &QProcess::deleteLater); + proc->start(QCoreApplication::applicationFilePath(), { "--receiver" }); + } + + void onModalToken(const QString &tokenStr) + { + qInfo() << "Got activation token, showing modal..."; + + if (!m_actMgr || !m_actMgr->isInitialized()) { + qWarning() << "xdg_activation_v1 not available"; + return; + } + + // A modal QDialog maps to an xdg_toplevel with set_parent + xdg_dialog + // set_modal. WA_ShowWithoutActivating makes Qt skip its own + // requestActivateOnShow, so we drive activation (and thus the window + // transition) with the token we just created, mirroring the receiver. + auto *dlg = new QDialog(this); + dlg->setWindowTitle("Modal (Enter)"); + dlg->setModal(true); + dlg->setAttribute(Qt::WA_ShowWithoutActivating, true); + dlg->setAttribute(Qt::WA_DeleteOnClose, true); + + auto *layout = new QVBoxLayout(dlg); + auto *label = new QLabel("Modal launched via xdg_activation + window transition rect", dlg); + label->setAlignment(Qt::AlignCenter); + layout->addWidget(label); + dlg->resize(400, 300); + + dlg->show(); + + ::wl_surface *surface = getWlSurface(dlg); + if (!surface) { + qWarning() << "Cannot get wl_surface for modal"; + return; + } + m_actMgr->activate(tokenStr, surface); + } + + XdgActivationManager *m_actMgr; + WindowTransitionManager *m_transitionMgr; + + struct LiveRect + { + WindowTransitionRect *rect; + int iconIndex; + }; + + QList m_rects; + QList m_iconWidgets; + QList m_iconCaptions{ QStringLiteral("SPACE"), QStringLiteral(".") }; + int m_paletteIndex = 0; + QLabel *m_sourceBufferIndicator = nullptr; + bool m_commitSourceBuffer = true; + bool m_animationDisabled = false; +}; + +// --------------------------------------------------------------------------- +// Receiver (Application B) +// --------------------------------------------------------------------------- + +class ReceiverWindow : public QMainWindow +{ + Q_OBJECT +public: + explicit ReceiverWindow(XdgActivationManager *actMgr) + : m_actMgr(actMgr) + , m_image(createTestImage("Window\nTransition", + QColor(63, 81, 181), + QColor(33, 150, 243), + 800, + 600)) + { + setWindowTitle("Window Transition - Receiver"); + resize(800, 600); + + auto *central = new IconWidget(m_image, this); + setCentralWidget(central); + } + + void activateWithToken() + { + QByteArray tokenEnv = qgetenv("XDG_ACTIVATION_TOKEN"); + if (tokenEnv.isEmpty()) { + qWarning() << "No XDG_ACTIVATION_TOKEN set"; + return; + } + qputenv("XDG_ACTIVATION_TOKEN", ""); + + if (!m_actMgr || !m_actMgr->isInitialized()) { + qWarning() << "xdg_activation_v1 not available"; + return; + } + + ::wl_surface *surface = getWlSurface(this); + if (!surface) { + qWarning() << "Cannot get wl_surface for receiver"; + return; + } + + qInfo() << "Activating with token..."; + m_actMgr->activate(QString::fromUtf8(tokenEnv), surface); + } + +private: + XdgActivationManager *m_actMgr; + QPixmap m_image; +}; + +// --------------------------------------------------------------------------- +// Main +// --------------------------------------------------------------------------- + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + bool receiverMode = false; + for (int i = 1; i < argc; ++i) { + if (qstrcmp(argv[i], "--receiver") == 0) + receiverMode = true; + } + + XdgActivationManager actMgr; + WindowTransitionManager transitionMgr; + + if (receiverMode) { + ReceiverWindow window(&actMgr); + window.show(); + window.activateWithToken(); + return app.exec(); + } else { + SenderWindow window(&actMgr, &transitionMgr); + window.show(); + return app.exec(); + } +} + +#include "main.moc" diff --git a/examples/test_capture/CMakeLists.txt b/examples/test_capture/CMakeLists.txt new file mode 100644 index 0000000000..2a05972279 --- /dev/null +++ b/examples/test_capture/CMakeLists.txt @@ -0,0 +1,49 @@ +find_package(PkgConfig REQUIRED) +find_package(Qt6 REQUIRED COMPONENTS Core Gui WaylandClient Quick) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS WaylandClientPrivate QuickPrivate) +endif() +find_package(TreelandProtocols REQUIRED) +pkg_check_modules(EGL REQUIRED IMPORTED_TARGET egl gl) +qt_add_executable(test-capture + main.cpp +) +qt_add_qml_module(test-capture + URI capture + VERSION 2.0 + SOURCES + capture.h + capture.cpp + subwindow.h + subwindow.cpp + player.h + player.cpp + QML_FILES + Main.qml +) + +qt_add_resources(test-capture "test_capture_assets" + PREFIX "/" + BASE ${CMAKE_CURRENT_LIST_DIR}/images + FILES + ${CMAKE_CURRENT_LIST_DIR}/images/watermark.png +) + +qt6_generate_wayland_protocol_client_sources(test-capture + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-capture-unstable-v1.xml +) + +target_link_libraries(test-capture + PRIVATE + Qt6::Core + Qt6::Gui + Qt6::WaylandClient + Qt6::WaylandClientPrivate + Qt6::Quick + Qt6::QuickPrivate + Qt6::QuickControls2 + PkgConfig::EGL +) + +install(TARGETS test-capture RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_capture/Main.qml b/examples/test_capture/Main.qml new file mode 100644 index 0000000000..53b8354bdb --- /dev/null +++ b/examples/test_capture/Main.qml @@ -0,0 +1,80 @@ +// Copyright (C) 2024 Dingyuan Zhang . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Controls +import capture + +Window { + id: canvas + width: 600 + height: 400 + visible: !TreelandCaptureManager.recordStarted + color: "transparent" + flags: regionReady ? 0 : Qt.WindowTransparentForInput + property rect captureRegion: TreelandCaptureManager.context?.captureRegion ?? Qt.rect(0, 0, 0, 0) + property bool regionReady: captureRegion.width !== 0 && captureRegion.height !== 0 + + Image { + id: watermark + visible: false + source: "qrc:/watermark.png" + sourceSize: Qt.size(100, 100) + fillMode: Image.Tile + x: captureRegion.x + y: captureRegion.y + width: captureRegion.width + height: captureRegion.height + } + + SubWindow { + id: toolBar + parent: canvas + visible: regionReady + x: captureRegion.x + y: Math.min(captureRegion.bottom, canvas.height - 2 * height) + width: row.width + height: row.height + color: "transparent" + Row { + id: row + Button { + width: 100 + height: 30 + text: watermark.visible ? "Hide watermark" : "Show watermark" + onClicked: { + watermark.visible = !watermark.visible + } + } + Button { + width: 100 + height: 30 + text: TreelandCaptureManager.record ? "Screenshot" : "Record" + onClicked: { + TreelandCaptureManager.record = !TreelandCaptureManager.record + } + } + Button { + width: 100 + height: 30 + text: "Finish" + onClicked: { + TreelandCaptureManager.finishSelect() + } + } + } + } + Window { + id: playerWindow + visible: TreelandCaptureManager.recordStarted + width: player.width + height: player.height + color: "black" + Player { + id: player + width: 100 + height: 100 + captureContext: TreelandCaptureManager.context + } + } +} diff --git a/examples/test_capture/capture.cpp b/examples/test_capture/capture.cpp new file mode 100644 index 0000000000..55f384e797 --- /dev/null +++ b/examples/test_capture/capture.cpp @@ -0,0 +1,291 @@ +// SPDX-FileCopyrightText: 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "capture.h" + +#include +#include +#include + +#include +#include + +inline QtWaylandClient::QWaylandIntegration *waylandIntegration() +{ + return dynamic_cast( + QGuiApplicationPrivate::platformIntegration()); +} + +inline QPointer waylandDisplay() +{ + return waylandIntegration()->display(); +} + +TreelandCaptureManager *TreelandCaptureManager::instance() +{ + static TreelandCaptureManager manager; + return &manager; +} + +TreelandCaptureManager *TreelandCaptureManager::create(QQmlEngine *, QJSEngine *) +{ + auto manager = instance(); + QQmlEngine::setObjectOwnership(manager, QQmlEngine::CppOwnership); + return manager; +} + +TreelandCaptureManager::TreelandCaptureManager() + : QWaylandClientExtensionTemplate(1) + , QtWayland::treeland_capture_manager_v1() +{ + connect(this, &TreelandCaptureManager::activeChanged, this, [this] { + if (!isActive()) { + delete m_context; + } + }); +} + +TreelandCaptureContext *TreelandCaptureManager::ensureContext() +{ + if (m_context) + return m_context; + auto context = get_context(); + m_context = new TreelandCaptureContext(context, this); + connect(m_context, &TreelandCaptureContext::destroyed, this, [this] { + m_context = nullptr; + Q_EMIT contextChanged(); + }); + Q_EMIT contextChanged(); + return m_context; +} + +void TreelandCaptureContext::treeland_capture_context_v1_source_ready(int32_t region_x, + int32_t region_y, + uint32_t region_width, + uint32_t region_height, + uint32_t source_type) +{ + m_captureRegion = QRect(region_x, region_y, region_width, region_height); + m_sourceType = static_cast(source_type); + Q_EMIT captureRegionChanged(); + Q_EMIT sourceReady(QRect(region_x, region_y, region_width, region_height), source_type); +} + +void TreelandCaptureContext::treeland_capture_context_v1_source_failed(uint32_t reason) +{ + Q_EMIT sourceFailed(reason); +} + +TreelandCaptureFrame *TreelandCaptureContext::ensureFrame() +{ + if (m_frame) + return m_frame; + auto object = QtWayland::treeland_capture_context_v1::capture(); + m_frame = new TreelandCaptureFrame(object, this); + connect(m_frame, &TreelandCaptureFrame::destroyed, this, [this] { + m_frame = nullptr; + Q_EMIT frameChanged(); + }); + Q_EMIT frameChanged(); + return m_frame; +} + +TreelandCaptureContext::TreelandCaptureContext(::treeland_capture_context_v1 *object, + QObject *parent) + : QObject(parent) + , QtWayland::treeland_capture_context_v1(object) +{ +} + +TreelandCaptureContext::~TreelandCaptureContext() +{ + delete m_frame; + delete m_session; + destroy(); +} + +void TreelandCaptureContext::selectSource(uint32_t sourceHint, + bool freeze, + bool withCursor, + ::wl_surface *mask) +{ + select_source(sourceHint, freeze, withCursor, mask); +} + +TreelandCaptureSession *TreelandCaptureContext::ensureSession() +{ + if (m_session) + return m_session; + auto object = create_session(); + m_session = new TreelandCaptureSession(object, this); + connect(m_session, &TreelandCaptureSession::destroyed, this, [this] { + m_session = nullptr; + Q_EMIT sessionChanged(); + }); + Q_EMIT sessionChanged(); + return m_session; +} + +TreelandCaptureFrame::TreelandCaptureFrame(::treeland_capture_frame_v1 *object, QObject *parent) + : QObject(parent) + , QtWayland::treeland_capture_frame_v1(object) + , m_shmBuffer(nullptr) + , m_pendingShmBuffer(nullptr) +{ +} + +TreelandCaptureFrame::~TreelandCaptureFrame() +{ + delete m_shmBuffer; + delete m_pendingShmBuffer; + destroy(); +} + +void TreelandCaptureFrame::treeland_capture_frame_v1_buffer(uint32_t format, + uint32_t width, + uint32_t height, + uint32_t stride) +{ + if (stride != width * 4) { + qDebug() << "Receive a buffer format which is not compatible with " + "QWaylandShmBuffer." + << "format:" << format << "width:" << width << "height:" << height + << "stride:" << stride; + return; + } + if (m_pendingShmBuffer) + return; // We only need one supported format + m_pendingShmBuffer = new QtWaylandClient::QWaylandShmBuffer( + waylandDisplay(), + QSize(width, height), + QtWaylandClient::QWaylandShm::formatFrom(static_cast<::wl_shm_format>(format))); + copy(m_pendingShmBuffer->buffer()); +} + +void TreelandCaptureFrame::treeland_capture_frame_v1_flags(uint32_t flags) +{ + m_flags = flags; +} + +void TreelandCaptureFrame::treeland_capture_frame_v1_ready() +{ + if (m_shmBuffer) + delete m_shmBuffer; + m_shmBuffer = m_pendingShmBuffer; + m_pendingShmBuffer = nullptr; + Q_EMIT ready(*m_shmBuffer->image()); +} + +void TreelandCaptureFrame::treeland_capture_frame_v1_failed() +{ + Q_EMIT failed(); +} + +TreelandCaptureSession::TreelandCaptureSession(::treeland_capture_session_v1 *object, + QObject *parent) + : QObject(parent) + , QtWayland::treeland_capture_session_v1(object) +{ +} + +TreelandCaptureSession::~TreelandCaptureSession() +{ + destroy(); +} + +void TreelandCaptureSession::start() +{ + QtWayland::treeland_capture_session_v1::start(); + m_started = true; + Q_EMIT startedChanged(); +} + +void TreelandCaptureSession::doneFrame() +{ + // Note: Must close all fds here in the client. + for (const auto &object : std::as_const(objects())) { + close(object.fd); + } + m_objects.clear(); + frame_done(m_tvSecHi, m_tvSecLo, m_tvUsec); + m_frameValid = false; + Q_EMIT invalid(); +} + +void TreelandCaptureSession::treeland_capture_session_v1_frame(int32_t offset_x, + int32_t offset_y, + uint32_t width, + uint32_t height, + uint32_t buffer_flags, + uint32_t flags, + uint32_t format, + uint32_t mod_high, + uint32_t mod_low, + uint32_t num_objects) +{ + m_objects.clear(); + m_objects.reserve(num_objects); + m_offset = { offset_x, offset_y }; + m_bufferWidth = width; + m_bufferHeight = height; + m_bufferFlags = buffer_flags; + m_bufferFormat = format; + m_flags = static_cast(flags); + m_modifierUnion.modLow = mod_low; + m_modifierUnion.modHigh = mod_high; +} + +void TreelandCaptureSession::treeland_capture_session_v1_object(uint32_t index, + int32_t fd, + uint32_t size, + uint32_t offset, + uint32_t stride, + uint32_t plane_index) +{ + m_objects.push_back({ .index = index, + .fd = fd, + .size = size, + .offset = offset, + .stride = stride, + .planeIndex = plane_index }); +} + +void TreelandCaptureSession::treeland_capture_session_v1_ready(uint32_t tv_sec_hi, + uint32_t tv_sec_lo, + uint32_t tv_nsec) +{ + m_tvSecHi = tv_sec_hi; + m_tvSecLo = tv_sec_lo; + m_tvUsec = tv_nsec; + m_frameValid = true; + Q_EMIT ready(); +} + +void TreelandCaptureSession::treeland_capture_session_v1_cancel(uint32_t reason) +{ + if (reason == QtWayland::treeland_capture_session_v1::cancel_reason_permanent) { + for (const auto &object : std::as_const(objects())) { + close(object.fd); + } + m_objects.clear(); + } else { + doneFrame(); + } +} + +void TreelandCaptureManager::setRecord(bool newRecord) +{ + if (m_record == newRecord) + return; + m_record = newRecord; + Q_EMIT recordChanged(); +} + +bool TreelandCaptureManager::recordStarted() const +{ + if (m_context && m_context->session()) { + return m_context->session()->started(); + } else { + return false; + } +} diff --git a/examples/test_capture/capture.h b/examples/test_capture/capture.h new file mode 100644 index 0000000000..ad0c0f9084 --- /dev/null +++ b/examples/test_capture/capture.h @@ -0,0 +1,273 @@ +// SPDX-FileCopyrightText: 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "qwayland-treeland-capture-unstable-v1.h" + +#include +#include + +#include +#include + +class TreelandCaptureFrame + : public QObject + , public QtWayland::treeland_capture_frame_v1 +{ + Q_OBJECT + QML_ANONYMOUS +public: + TreelandCaptureFrame(struct ::treeland_capture_frame_v1 *object, QObject *parent = nullptr); + ~TreelandCaptureFrame() override; + + inline uint flags() const + { + return m_flags; + } + +Q_SIGNALS: + void ready(QImage image); + void failed(); + +protected: + void treeland_capture_frame_v1_buffer(uint32_t format, + uint32_t width, + uint32_t height, + uint32_t stride) override; + void treeland_capture_frame_v1_flags(uint32_t flags) override; + void treeland_capture_frame_v1_ready() override; + void treeland_capture_frame_v1_failed() override; + +private: + QtWaylandClient::QWaylandShmBuffer *m_shmBuffer{ nullptr }; + QtWaylandClient::QWaylandShmBuffer *m_pendingShmBuffer{ nullptr }; + uint m_flags; +}; + +struct FrameObject +{ + uint32_t index; + int32_t fd; + uint32_t size; + uint32_t offset; + uint32_t stride; + uint32_t planeIndex; +}; + +union ModifierUnion +{ + struct + { + uint32_t modLow; + uint32_t modHigh; + }; + + uint64_t modifier; +}; + +class TreelandCaptureSession + : public QObject + , public QtWayland::treeland_capture_session_v1 +{ + Q_OBJECT + QML_ANONYMOUS + Q_PROPERTY(bool started READ started NOTIFY startedChanged FINAL) + +public: + explicit TreelandCaptureSession(::treeland_capture_session_v1 *object, + QObject *parent = nullptr); + ~TreelandCaptureSession() override; + + inline uint bufferWidth() const + { + return m_bufferWidth; + } + + inline uint bufferHeight() const + { + return m_bufferHeight; + } + + inline uint bufferFormat() const + { + return m_bufferFormat; + } + + inline uint bufferFlags() const + { + return m_bufferFlags; + } + + inline const QList &objects() const + { + return m_objects; + } + + inline ModifierUnion modifierUnion() const + { + return m_modifierUnion; + } + + inline bool started() const + { + return m_started; + } + + void start(); + void doneFrame(); + + inline bool frameValid() const + { + return m_frameValid; + } + +Q_SIGNALS: + void invalid(); + void ready(); + void startedChanged(); + +protected: + void treeland_capture_session_v1_frame(int32_t offset_x, + int32_t offset_y, + uint32_t width, + uint32_t height, + uint32_t buffer_flags, + uint32_t flags, + uint32_t format, + uint32_t mod_high, + uint32_t mod_low, + uint32_t num_objects) override; + void treeland_capture_session_v1_object(uint32_t index, + int32_t fd, + uint32_t size, + uint32_t offset, + uint32_t stride, + uint32_t plane_index) override; + void treeland_capture_session_v1_ready(uint32_t tv_sec_hi, + uint32_t tv_sec_lo, + uint32_t tv_nsec) override; + void treeland_capture_session_v1_cancel(uint32_t reason) override; + +private: + QPoint m_offset; + uint m_bufferWidth; + uint m_bufferHeight; + uint m_bufferFlags; + uint m_bufferFormat; + ModifierUnion m_modifierUnion; + QList m_objects; + QtWayland::treeland_capture_session_v1::flags m_flags; + bool m_started{ false }; + uint32_t m_tvSecHi; + uint32_t m_tvSecLo; + uint32_t m_tvUsec; + bool m_frameValid{ false }; +}; + +class TreelandCaptureContext + : public QObject + , public QtWayland::treeland_capture_context_v1 +{ + Q_OBJECT + QML_ANONYMOUS + Q_PROPERTY(TreelandCaptureFrame* frame READ frame NOTIFY frameChanged FINAL) + Q_PROPERTY(TreelandCaptureSession* session READ session NOTIFY sessionChanged FINAL) + Q_PROPERTY(QRectF captureRegion READ captureRegion NOTIFY captureRegionChanged FINAL) + QML_UNCREATABLE("Managed by C++.") + +public: + using QtWayland::treeland_capture_context_v1::source_type; + explicit TreelandCaptureContext(struct ::treeland_capture_context_v1 *object, + QObject *parent = nullptr); + ~TreelandCaptureContext() override; + + inline QRectF captureRegion() const + { + return m_captureRegion; + } + + inline QtWayland::treeland_capture_context_v1::source_type sourceType() const + { + return m_sourceType; + } + + inline TreelandCaptureFrame *frame() const + { + return m_frame; + } + + inline TreelandCaptureSession *session() const + { + return m_session; + } + + void selectSource(uint32_t sourceHint, bool freeze, bool withCursor, ::wl_surface *mask); + TreelandCaptureFrame *ensureFrame(); + TreelandCaptureSession *ensureSession(); + +Q_SIGNALS: + void sourceReady(QRect region, uint32_t sourceType); + void sourceFailed(uint32_t reason); + void frameChanged(); + void sessionChanged(); + void captureRegionChanged(); + +protected: + void treeland_capture_context_v1_source_ready(int32_t region_x, + int32_t region_y, + uint32_t region_width, + uint32_t region_height, + uint32_t source_type) override; + void treeland_capture_context_v1_source_failed(uint32_t reason) override; + +private: + QRect m_captureRegion; + QtWayland::treeland_capture_context_v1::source_type m_sourceType; + TreelandCaptureFrame *m_frame{ nullptr }; + TreelandCaptureSession *m_session{ nullptr }; +}; + +class TreelandCaptureManager + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_capture_manager_v1 +{ + Q_OBJECT + QML_ELEMENT + QML_SINGLETON + QML_UNCREATABLE("Managed by C++.") + Q_PROPERTY(TreelandCaptureContext* context READ context NOTIFY contextChanged FINAL) + Q_PROPERTY(bool record READ record WRITE setRecord NOTIFY recordChanged FINAL) + Q_PROPERTY(bool recordStarted READ recordStarted NOTIFY recordStartedChanged FINAL) + +public: + static TreelandCaptureManager *instance(); + static TreelandCaptureManager *create(QQmlEngine *, QJSEngine *); + + inline TreelandCaptureContext *context() const + { + return m_context; + } + + TreelandCaptureContext *ensureContext(); + + inline bool record() const + { + return m_record; + } + + void setRecord(bool newRecord); + bool recordStarted() const; + +Q_SIGNALS: + void contextChanged(); + void recordChanged(); + void finishSelect(); + void recordStartedChanged(); + +private: + TreelandCaptureManager(); + + TreelandCaptureContext *m_context{ nullptr }; + bool m_record{ false }; +}; diff --git a/examples/test_capture/images/watermark.png b/examples/test_capture/images/watermark.png new file mode 100644 index 0000000000..e0b538e453 Binary files /dev/null and b/examples/test_capture/images/watermark.png differ diff --git a/examples/test_capture/main.cpp b/examples/test_capture/main.cpp new file mode 100644 index 0000000000..e06be5dcab --- /dev/null +++ b/examples/test_capture/main.cpp @@ -0,0 +1,109 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "capture.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) +{ + QGuiApplication::setAttribute(Qt::AA_ShareOpenGLContexts); + QQuickStyle::setStyle("Material"); + QGuiApplication app(argc, argv); + QQmlApplicationEngine engine; + auto manager = TreelandCaptureManager::instance(); + QObject::connect( + &engine, + &QQmlApplicationEngine::objectCreationFailed, + &app, + []() { + QCoreApplication::exit(-1); + }, + Qt::QueuedConnection); + auto captureWithMask = [&app, manager](::wl_surface *mask) { + auto captureContext = manager->ensureContext(); + if (!captureContext) { + app.exit(-1); + Q_UNREACHABLE(); + } + captureContext->selectSource(TreelandCaptureContext::source_type_output + | TreelandCaptureContext::source_type_window + | TreelandCaptureContext::source_type_region, + true, + false, + mask); + + QObject::connect( + manager, + &TreelandCaptureManager::finishSelect, + manager, + [&app, captureContext, manager] { + if (manager->record()) { + auto session = captureContext->ensureSession(); + session->start(); + QTimer::singleShot(1000, manager, [manager] { + Q_EMIT manager->recordStartedChanged(); + }); + } else { + auto frame = captureContext->ensureFrame(); + QImage result; + QEventLoop loop; + QObject::connect(frame, + &TreelandCaptureFrame::ready, + &app, + [&result, &loop](QImage image) { + result = image; + loop.quit(); + }); + QObject::connect(frame, &TreelandCaptureFrame::failed, &app, [&loop] { + loop.quit(); + }); + loop.exec(); + if (result.isNull()) + app.exit(-1); + auto saveBasePath = + QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); + QDir saveBaseDir(saveBasePath); + if (!saveBaseDir.exists()) + app.exit(-1); + QString picName = + "portal screenshot - " + QDateTime::currentDateTime().toString() + ".png"; + if (result.save(saveBaseDir.absoluteFilePath(picName), "PNG")) { + qDebug() << saveBaseDir.absoluteFilePath(picName); + delete TreelandCaptureManager::instance()->context(); + app.quit(); + } else { + delete TreelandCaptureManager::instance()->context(); + app.exit(-1); + } + } + }); + }; + QObject::connect(&engine, + &QQmlApplicationEngine::objectCreated, + manager, + [manager, captureWithMask](QObject *object, const QUrl &) { + if (auto canvasWindow = qobject_cast(object)) { + auto waylandWindow = static_cast( + canvasWindow->handle()); + auto mask = waylandWindow ? waylandWindow->surface() : nullptr; + if (manager->isActive()) { + captureWithMask(mask); + } else { + QObject::connect(manager, + &TreelandCaptureManager::activeChanged, + manager, + std::bind(captureWithMask, mask)); + } + } + }); + engine.loadFromModule("capture", "Main"); + return app.exec(); +} diff --git a/examples/test_capture/player.cpp b/examples/test_capture/player.cpp new file mode 100644 index 0000000000..d50633cdd0 --- /dev/null +++ b/examples/test_capture/player.cpp @@ -0,0 +1,365 @@ +// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "player.h" + +#include "capture.h" + +#include +#include +#include +#include +#include + +#include +#include + +#include + +Player::Player() +{ + setFlag(QQuickItem::ItemHasContents); +} + +TreelandCaptureContext *Player::captureContext() const +{ + return m_captureContext; +} + +void Player::setCaptureContext(TreelandCaptureContext *context) +{ + if (context == m_captureContext) + return; + if (m_captureContext) { + m_captureContext->disconnect(this); + } + m_captureContext = context; + if (m_captureContext) { + connect(m_captureContext.data(), + &TreelandCaptureContext::destroyed, + this, + std::bind(&Player::setCaptureContext, this, nullptr)); + if (m_captureContext->session()) { + connect(m_captureContext->session(), + &TreelandCaptureSession::ready, + this, + &Player::update); + } else { + connect(m_captureContext, &TreelandCaptureContext::sessionChanged, this, [this] { + if (m_captureContext->session()) + connect(m_captureContext->session(), + &TreelandCaptureSession::ready, + this, + &Player::update); + }); + } + connect(m_captureContext.data(), + &TreelandCaptureContext::sourceReady, + this, + &Player::updateGeometry); + } + Q_EMIT captureContextChanged(); +} + +QSGNode *Player::updatePaintNode(QSGNode *old, [[maybe_unused]] UpdatePaintNodeData *data) +{ + ensureDebugLogger(); + if (!m_captureContext || !m_captureContext->session() + || !m_captureContext->session()->started()) + return nullptr; + updateTexture(); + auto node = static_cast(old); + if (Q_UNLIKELY(!node) && m_rhiTexture != nullptr) { + node = window()->createImageNode(); + node->setOwnsTexture(false); + node->setTexture(&m_texture); + } else if (m_rhiTexture != nullptr) { + node->markDirty(QSGNode::DirtyMaterial); + } else { + return nullptr; + } + QRectF sourceRect; + if (m_captureContext->sourceType() + == QtWayland::treeland_capture_context_v1::source_type_window) { + sourceRect = QRectF({ 0, 0 }, m_texture.textureSize()); + } else { + sourceRect = m_captureContext->captureRegion(); + } + qInfo() << "sourceRect" << sourceRect << "textureSize" << m_texture.textureSize(); + node->setSourceRect(sourceRect); + node->setRect(boundingRect()); + node->setFiltering(QSGTexture::Linear); + node->setMipmapFiltering(QSGTexture::None); + return node; +} + +#define CASE_STR(value) \ + case value: \ + return #value; + +static const char *eglGetErrorString(EGLint error) +{ + switch (error) { + CASE_STR(EGL_SUCCESS) + CASE_STR(EGL_NOT_INITIALIZED) + CASE_STR(EGL_BAD_ACCESS) + CASE_STR(EGL_BAD_ALLOC) + CASE_STR(EGL_BAD_ATTRIBUTE) + CASE_STR(EGL_BAD_CONTEXT) + CASE_STR(EGL_BAD_CONFIG) + CASE_STR(EGL_BAD_CURRENT_SURFACE) + CASE_STR(EGL_BAD_DISPLAY) + CASE_STR(EGL_BAD_SURFACE) + CASE_STR(EGL_BAD_MATCH) + CASE_STR(EGL_BAD_PARAMETER) + CASE_STR(EGL_BAD_NATIVE_PIXMAP) + CASE_STR(EGL_BAD_NATIVE_WINDOW) + CASE_STR(EGL_CONTEXT_LOST) + default: + return "Unknown"; + } +} + +[[maybe_unused]] static const char *drmFormatString(int fourcc) +{ + switch (fourcc) { + CASE_STR(DRM_FORMAT_R8) + CASE_STR(DRM_FORMAT_RG88) + CASE_STR(DRM_FORMAT_GR88) + CASE_STR(DRM_FORMAT_R16) + CASE_STR(DRM_FORMAT_GR1616) + CASE_STR(DRM_FORMAT_RGB332) + CASE_STR(DRM_FORMAT_BGR233) + CASE_STR(DRM_FORMAT_XRGB4444) + CASE_STR(DRM_FORMAT_XBGR4444) + CASE_STR(DRM_FORMAT_RGBX4444) + CASE_STR(DRM_FORMAT_BGRX4444) + CASE_STR(DRM_FORMAT_ARGB4444) + CASE_STR(DRM_FORMAT_ABGR4444) + CASE_STR(DRM_FORMAT_RGBA4444) + CASE_STR(DRM_FORMAT_BGRA4444) + CASE_STR(DRM_FORMAT_XRGB1555) + CASE_STR(DRM_FORMAT_XBGR1555) + CASE_STR(DRM_FORMAT_RGBX5551) + CASE_STR(DRM_FORMAT_BGRX5551) + CASE_STR(DRM_FORMAT_ARGB1555) + CASE_STR(DRM_FORMAT_ABGR1555) + CASE_STR(DRM_FORMAT_RGBA5551) + CASE_STR(DRM_FORMAT_BGRA5551) + CASE_STR(DRM_FORMAT_RGB565) + CASE_STR(DRM_FORMAT_BGR565) + CASE_STR(DRM_FORMAT_RGB888) + CASE_STR(DRM_FORMAT_BGR888) + CASE_STR(DRM_FORMAT_XRGB8888) + CASE_STR(DRM_FORMAT_XBGR8888) + CASE_STR(DRM_FORMAT_RGBX8888) + CASE_STR(DRM_FORMAT_BGRX8888) + CASE_STR(DRM_FORMAT_ARGB8888) + CASE_STR(DRM_FORMAT_ABGR8888) + CASE_STR(DRM_FORMAT_RGBA8888) + CASE_STR(DRM_FORMAT_BGRA8888) + CASE_STR(DRM_FORMAT_XRGB2101010) + CASE_STR(DRM_FORMAT_XBGR2101010) + CASE_STR(DRM_FORMAT_RGBX1010102) + CASE_STR(DRM_FORMAT_BGRX1010102) + CASE_STR(DRM_FORMAT_ARGB2101010) + CASE_STR(DRM_FORMAT_ABGR2101010) + CASE_STR(DRM_FORMAT_RGBA1010102) + CASE_STR(DRM_FORMAT_BGRA1010102) + CASE_STR(DRM_FORMAT_ABGR16161616) + CASE_STR(DRM_FORMAT_XBGR16161616) + CASE_STR(DRM_FORMAT_XBGR16161616F) + CASE_STR(DRM_FORMAT_ABGR16161616F) + CASE_STR(DRM_FORMAT_YUYV) + CASE_STR(DRM_FORMAT_YVYU) + CASE_STR(DRM_FORMAT_UYVY) + CASE_STR(DRM_FORMAT_VYUY) + CASE_STR(DRM_FORMAT_AYUV) + CASE_STR(DRM_FORMAT_XYUV8888) + CASE_STR(DRM_FORMAT_Y210) + CASE_STR(DRM_FORMAT_Y212) + CASE_STR(DRM_FORMAT_Y216) + CASE_STR(DRM_FORMAT_Y410) + CASE_STR(DRM_FORMAT_Y412) + CASE_STR(DRM_FORMAT_Y416) + CASE_STR(DRM_FORMAT_NV12) + CASE_STR(DRM_FORMAT_NV21) + CASE_STR(DRM_FORMAT_NV16) + CASE_STR(DRM_FORMAT_NV61) + CASE_STR(DRM_FORMAT_P010) + CASE_STR(DRM_FORMAT_P012) + CASE_STR(DRM_FORMAT_P016) + CASE_STR(DRM_FORMAT_P030) + CASE_STR(DRM_FORMAT_YUV410) + CASE_STR(DRM_FORMAT_YVU410) + CASE_STR(DRM_FORMAT_YUV411) + CASE_STR(DRM_FORMAT_YVU411) + CASE_STR(DRM_FORMAT_YUV420) + CASE_STR(DRM_FORMAT_YVU420) + CASE_STR(DRM_FORMAT_YUV422) + CASE_STR(DRM_FORMAT_YVU422) + CASE_STR(DRM_FORMAT_YUV444) + CASE_STR(DRM_FORMAT_YVU444) + default: + return "Unknown"; + } +} + +#undef CASE_STR + +void Player::updateTexture() +{ + if (!m_captureContext->session()->frameValid()) + return; + auto glContext = QOpenGLContext::currentContext(); + Q_ASSERT(glContext); + auto eglContext = glContext->nativeInterface(); + Q_ASSERT(eglContext); + EGLImage eglImage; + EGLAttrib attribs[47]; + int atti = 0; + attribs[atti++] = EGL_WIDTH; + attribs[atti++] = m_captureContext->session()->bufferWidth(); + attribs[atti++] = EGL_HEIGHT; + attribs[atti++] = m_captureContext->session()->bufferHeight(); + attribs[atti++] = EGL_LINUX_DRM_FOURCC_EXT; + attribs[atti++] = m_captureContext->session()->bufferFormat(); + + auto objects = m_captureContext->session()->objects(); + auto nPlanes = objects.size(); + if (nPlanes > 0) { + attribs[atti++] = EGL_DMA_BUF_PLANE0_FD_EXT; + attribs[atti++] = objects[0].fd; + attribs[atti++] = EGL_DMA_BUF_PLANE0_OFFSET_EXT; + attribs[atti++] = objects[0].offset; + attribs[atti++] = EGL_DMA_BUF_PLANE0_PITCH_EXT; + attribs[atti++] = objects[0].stride; + if (m_captureContext->session()->modifierUnion().modifier) { + attribs[atti++] = EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT; + attribs[atti++] = m_captureContext->session()->modifierUnion().modLow; + attribs[atti++] = EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT; + attribs[atti++] = m_captureContext->session()->modifierUnion().modHigh; + } + } + + if (nPlanes > 1) { + attribs[atti++] = EGL_DMA_BUF_PLANE1_FD_EXT; + attribs[atti++] = objects[1].fd; + attribs[atti++] = EGL_DMA_BUF_PLANE1_OFFSET_EXT; + attribs[atti++] = objects[1].offset; + attribs[atti++] = EGL_DMA_BUF_PLANE1_PITCH_EXT; + attribs[atti++] = objects[1].stride; + if (m_captureContext->session()->modifierUnion().modifier) { + attribs[atti++] = EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT; + attribs[atti++] = m_captureContext->session()->modifierUnion().modLow; + attribs[atti++] = EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT; + attribs[atti++] = m_captureContext->session()->modifierUnion().modHigh; + } + } + + if (nPlanes > 2) { + attribs[atti++] = EGL_DMA_BUF_PLANE2_FD_EXT; + attribs[atti++] = objects[2].fd; + attribs[atti++] = EGL_DMA_BUF_PLANE2_OFFSET_EXT; + attribs[atti++] = objects[2].offset; + attribs[atti++] = EGL_DMA_BUF_PLANE2_PITCH_EXT; + attribs[atti++] = objects[2].stride; + if (m_captureContext->session()->modifierUnion().modifier) { + attribs[atti++] = EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT; + attribs[atti++] = m_captureContext->session()->modifierUnion().modLow; + attribs[atti++] = EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT; + attribs[atti++] = m_captureContext->session()->modifierUnion().modHigh; + } + } + + if (nPlanes > 3) { + attribs[atti++] = EGL_DMA_BUF_PLANE3_FD_EXT; + attribs[atti++] = objects[3].fd; + attribs[atti++] = EGL_DMA_BUF_PLANE3_OFFSET_EXT; + attribs[atti++] = objects[3].offset; + attribs[atti++] = EGL_DMA_BUF_PLANE3_PITCH_EXT; + attribs[atti++] = objects[3].stride; + if (m_captureContext->session()->modifierUnion().modifier) { + attribs[atti++] = EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT; + attribs[atti++] = m_captureContext->session()->modifierUnion().modLow; + attribs[atti++] = EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT; + attribs[atti++] = m_captureContext->session()->modifierUnion().modHigh; + } + } + + attribs[atti++] = EGL_NONE; + eglImage = + eglCreateImage(eglContext->display(), EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, 0, attribs); + if (eglImage == EGL_NO_IMAGE) { + qWarning() << eglGetErrorString(eglGetError()); + m_captureContext->session()->doneFrame(); + return; + } + Q_ASSERT_X(window(), __func__, "Window should be ready for rhi."); + if (m_rhiTexture) { + m_texture.setTexture(nullptr); + delete m_rhiTexture; + } + m_rhiTexture = + window()->rhi()->newTexture(QRhiTexture::RGBA8, + QSize{ int(m_captureContext->session()->bufferWidth()), + int(m_captureContext->session()->bufferHeight()) }, + 1, + QRhiTexture::TextureArray); + glBindTexture(GL_TEXTURE_2D, m_rhiTexture->nativeTexture().object); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, eglImage); + m_texture.setTexture(m_rhiTexture); + m_texture.setTextureSize(QSize{ int(m_captureContext->session()->bufferWidth()), + int(m_captureContext->session()->bufferHeight()) }); + m_texture.setOwnsTexture(false); + glBindTexture(GL_TEXTURE_2D, 0); + eglDestroyImage(eglContext->display(), eglImage); + m_captureContext->session()->doneFrame(); +} + +void Player::updateGeometry() +{ + Q_ASSERT(m_captureContext); + setWidth(m_captureContext->captureRegion().width()); + setHeight(m_captureContext->captureRegion().height()); +} + +static void EGLAPIENTRY debugCallback(EGLenum error, + [[maybe_unused]] const char *command, + [[maybe_unused]] EGLint messageType, + [[maybe_unused]] EGLLabelKHR threadLabel, + [[maybe_unused]] EGLLabelKHR objectLabel, + const char *message) +{ + qInfo() << "EGL Debug:" << message << "(Error Code:" << error << ")"; +} + +void Player::ensureDebugLogger() +{ + if (m_loggerInitialized) + return; + if (QOpenGLContext::currentContext()->hasExtension(QByteArrayLiteral("GL_KHR_debug"))) { + const EGLAttrib debugAttribs[] = { + EGL_DEBUG_MSG_CRITICAL_KHR, + EGL_TRUE, + EGL_DEBUG_MSG_ERROR_KHR, + EGL_TRUE, + EGL_DEBUG_MSG_WARN_KHR, + EGL_TRUE, + EGL_DEBUG_MSG_INFO_KHR, + EGL_TRUE, + EGL_NONE, + }; + PFNEGLDEBUGMESSAGECONTROLKHRPROC eglDebugMessageControlKHR = + (PFNEGLDEBUGMESSAGECONTROLKHRPROC)eglGetProcAddress("eglDebugMessageControlKHR"); + if (eglDebugMessageControlKHR) { + eglDebugMessageControlKHR(debugCallback, debugAttribs); + } else { + qCritical() << "Failed to get eglDebugMessageControlKHR function."; + } + } else { + qCritical() << "GL_KHR_debug is not supported."; + } + m_loggerInitialized = true; +} diff --git a/examples/test_capture/player.h b/examples/test_capture/player.h new file mode 100644 index 0000000000..479afbe372 --- /dev/null +++ b/examples/test_capture/player.h @@ -0,0 +1,38 @@ +// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include + +#include +class QSGPlainTexture; +class QRhiTexture; +class TreelandCaptureContext; + +class Player : public QQuickItem +{ + Q_OBJECT + QML_ELEMENT + Q_PROPERTY(TreelandCaptureContext* captureContext READ captureContext WRITE setCaptureContext NOTIFY captureContextChanged FINAL) +public: + Player(); + + TreelandCaptureContext *captureContext() const; + void setCaptureContext(TreelandCaptureContext *context); + +Q_SIGNALS: + void captureContextChanged(); + +protected: + QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *) override; + +private: + void updateTexture(); + void updateGeometry(); + void ensureDebugLogger(); + + QSGPlainTexture m_texture; + QRhiTexture *m_rhiTexture{ nullptr }; + QPointer m_captureContext{}; + bool m_loggerInitialized{ false }; +}; diff --git a/examples/test_capture/subwindow.cpp b/examples/test_capture/subwindow.cpp new file mode 100644 index 0000000000..b2f24485b4 --- /dev/null +++ b/examples/test_capture/subwindow.cpp @@ -0,0 +1,16 @@ +// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "subwindow.h" + +SubWindow::SubWindow() { } + +QQuickWindow *SubWindow::parent() const +{ + return qobject_cast(QWindow::parent()); +} + +void SubWindow::setParent(QQuickWindow *w) +{ + QWindow::setParent(w); + Q_EMIT parentChanged(); +} diff --git a/examples/test_capture/subwindow.h b/examples/test_capture/subwindow.h new file mode 100644 index 0000000000..039c618015 --- /dev/null +++ b/examples/test_capture/subwindow.h @@ -0,0 +1,21 @@ +// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include +#include +#include + +class SubWindow : public QQuickWindow +{ + Q_OBJECT + QML_ELEMENT + Q_PROPERTY(QQuickWindow *parent READ parent WRITE setParent NOTIFY parentChanged FINAL) +Q_SIGNALS: + void parentChanged(); + +public: + SubWindow(); + QQuickWindow *parent() const; + void setParent(QQuickWindow *w); +}; diff --git a/examples/test_compositor-action/CMakeLists.txt b/examples/test_compositor-action/CMakeLists.txt new file mode 100644 index 0000000000..16a5c935b0 --- /dev/null +++ b/examples/test_compositor-action/CMakeLists.txt @@ -0,0 +1,26 @@ +find_package(Qt6 REQUIRED COMPONENTS WaylandClient Widgets) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS GuiPrivate WaylandClientPrivate) +endif() +find_package(TreelandProtocols 0.7.0 REQUIRED) + +set(BIN_NAME test-compositor-action) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-compositor-action-unstable-v1.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Widgets + Qt6::WaylandClient + Qt6::GuiPrivate + Qt6::WaylandClientPrivate +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_compositor-action/main.cpp b/examples/test_compositor-action/main.cpp new file mode 100644 index 0000000000..7bb552022b --- /dev/null +++ b/examples/test_compositor-action/main.cpp @@ -0,0 +1,286 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// Test client for the treeland-compositor-action-unstable-v1 protocol. +// +// Usage: +// test-compositor-action launch the GUI and click buttons +// test-compositor-action list print all action names and values +// test-compositor-action trigger one action and exit, e.g. +// ./test-compositor-action workspace_2 +// ./test-compositor-action show_desktop +// ./test-compositor-action 23 (lockscreen) +// +// The protocol is fire-and-forget: the compositor sends no reply, so the +// client just triggers the action (and flushes the request to the socket). + +#include "qwayland-treeland-compositor-action-unstable-v1.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include + +class CompositorAction + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_compositor_action_v1 +{ + Q_OBJECT +public: + explicit CompositorAction() + : QWaylandClientExtensionTemplate(1) + { + } +}; + +struct ActionName { + const char *name; + uint32_t value; +}; + +// Keep in sync with the action enum of treeland-compositor-action-unstable-v1. +static const ActionName kActions[] = { + { "workspace_1", CompositorAction::action_workspace_1 }, + { "workspace_2", CompositorAction::action_workspace_2 }, + { "workspace_3", CompositorAction::action_workspace_3 }, + { "workspace_4", CompositorAction::action_workspace_4 }, + { "workspace_5", CompositorAction::action_workspace_5 }, + { "workspace_6", CompositorAction::action_workspace_6 }, + { "workspace_7", CompositorAction::action_workspace_7 }, + { "workspace_8", CompositorAction::action_workspace_8 }, + { "workspace_9", CompositorAction::action_workspace_9 }, + { "workspace_10", CompositorAction::action_workspace_10 }, + { "workspace_11", CompositorAction::action_workspace_11 }, + { "workspace_12", CompositorAction::action_workspace_12 }, + { "prev_workspace", CompositorAction::action_prev_workspace }, + { "next_workspace", CompositorAction::action_next_workspace }, + { "show_desktop", CompositorAction::action_show_desktop }, + { "open_multitask_view", CompositorAction::action_open_multitask_view }, + { "close_multitask_view", CompositorAction::action_close_multitask_view }, + { "toggle_multitask_view", CompositorAction::action_toggle_multitask_view }, + { "zoom_in", CompositorAction::action_zoom_in }, + { "zoom_out", CompositorAction::action_zoom_out }, + { "zoom_reset", CompositorAction::action_zoom_reset }, + { "toggle_fps_display", CompositorAction::action_toggle_fps_display }, + { "lockscreen", CompositorAction::action_lockscreen }, + { "shutdown_menu", CompositorAction::action_shutdown_menu }, + { "show_user_switch", CompositorAction::action_show_user_switch }, + { "shutdown_menu_power_off", CompositorAction::action_shutdown_menu_power_off }, + { "shutdown_menu_reboot", CompositorAction::action_shutdown_menu_reboot }, + { "shutdown_menu_suspend", CompositorAction::action_shutdown_menu_suspend }, + { "shutdown_menu_hibernate", CompositorAction::action_shutdown_menu_hibernate }, + { "shutdown_menu_log_out", CompositorAction::action_shutdown_menu_log_out }, +}; + +static void printActions() +{ + printf("Available actions:\n"); + for (const auto &action : kActions) + printf(" %-26s %u\n", action.name, action.value); +} + +static bool resolveAction(const char *argument, uint32_t *value) +{ + for (const auto &action : kActions) { + if (std::strcmp(action.name, argument) == 0) { + *value = action.value; + return true; + } + } + + char *end = nullptr; + const long parsed = std::strtol(argument, &end, 10); + if (end != argument && *end == '\0' && parsed > 0 && parsed < 1000) { + *value = static_cast(parsed); + return true; + } + return false; +} + +// --------------------------------------------------------------------------- +// GUI +// --------------------------------------------------------------------------- + +// Flushes the pending trigger() request to the compositor socket. The protocol +// is fire-and-forget (no reply event), so without an explicit flush the request +// could stay buffered in the client library. +static void flushWayland() +{ + if (auto *waylandApp = qGuiApp->nativeInterface()) + wl_display_flush(waylandApp->display()); +} + +static QPushButton *addActionButton(CompositorAction *action, + QLabel *status, + const char *label, + uint32_t value) +{ + auto *button = new QPushButton(QString::fromLatin1(label)); + QObject::connect(button, &QPushButton::clicked, button, [action, status, label, value] { + action->trigger(value); + flushWayland(); + status->setText(QStringLiteral("triggered %1 (%2)") + .arg(QString::fromLatin1(label)) + .arg(value)); + }); + return button; +} + +static QWidget *buildGui(CompositorAction *action) +{ + auto *window = new QWidget; + window->setWindowTitle(QStringLiteral("WaylandServer Action Client")); + window->setAttribute(Qt::WA_DeleteOnClose); + + auto *vbox = new QVBoxLayout(window); + + // Status line: the protocol is fire-and-forget (no reply event), so this + // is the only feedback the user gets for a click. + auto *status = new QLabel(QStringLiteral("connected to treeland_compositor_action_v1")); + status->setWordWrap(true); + vbox->addWidget(status); + + // ---- Workspace switching ---- + auto *workspaceBox = new QGroupBox(QStringLiteral("Workspace")); + auto *workspaceGrid = new QGridLayout(workspaceBox); + static const char *workspaceButtons[] = { + "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", + }; + for (int i = 0; i < 12; ++i) { + const uint32_t value = CompositorAction::action_workspace_1 + i; + workspaceGrid->addWidget(addActionButton(action, status, workspaceButtons[i], value), i / 6, i % 6); + } + workspaceGrid->addWidget(addActionButton(action, status, "prev", CompositorAction::action_prev_workspace), 2, 0); + workspaceGrid->addWidget(addActionButton(action, status, "next", CompositorAction::action_next_workspace), 2, 1); + vbox->addWidget(workspaceBox); + + // ---- Show desktop / multitask ---- + auto *desktopBox = new QGroupBox(QStringLiteral("Show desktop / Multitask")); + auto *desktopRow = new QHBoxLayout(desktopBox); + desktopRow->addWidget(addActionButton(action, status, "show_desktop", CompositorAction::action_show_desktop)); + // Opening the multitask view covers this window, so the close button would + // be unreachable. Open it, then auto-close 5s later so the client stays usable. + auto *openButton = new QPushButton(QStringLiteral("open_multitask (auto-close 5s)")); + QObject::connect(openButton, &QPushButton::clicked, openButton, [action, status] { + action->trigger(CompositorAction::action_open_multitask_view); + flushWayland(); + status->setText(QStringLiteral("opened multitask view — auto-close in 5s")); + QTimer::singleShot(5000, status, [action, status] { + action->trigger(CompositorAction::action_close_multitask_view); + flushWayland(); + status->setText(QStringLiteral("closed multitask view")); + }); + }); + desktopRow->addWidget(openButton); + desktopRow->addWidget(addActionButton(action, status, "close_multitask", CompositorAction::action_close_multitask_view)); + desktopRow->addWidget(addActionButton(action, status, "toggle_multitask", CompositorAction::action_toggle_multitask_view)); + vbox->addWidget(desktopBox); + + // ---- Screen zoom ---- + auto *zoomBox = new QGroupBox(QStringLiteral("Screen zoom")); + auto *zoomRow = new QHBoxLayout(zoomBox); + zoomRow->addWidget(addActionButton(action, status, "zoom_in", CompositorAction::action_zoom_in)); + zoomRow->addWidget(addActionButton(action, status, "zoom_out", CompositorAction::action_zoom_out)); + zoomRow->addWidget(addActionButton(action, status, "zoom_reset", CompositorAction::action_zoom_reset)); + vbox->addWidget(zoomBox); + + // ---- System / session ---- + auto *sessionBox = new QGroupBox(QStringLiteral("System / Session")); + auto *sessionRow = new QHBoxLayout(sessionBox); + sessionRow->addWidget(addActionButton(action, status, "toggle_fps", CompositorAction::action_toggle_fps_display)); + sessionRow->addWidget(addActionButton(action, status, "lockscreen", CompositorAction::action_lockscreen)); + sessionRow->addWidget(addActionButton(action, status, "shutdown_menu", CompositorAction::action_shutdown_menu)); + sessionRow->addWidget(addActionButton(action, status, "user_switch", CompositorAction::action_show_user_switch)); + vbox->addWidget(sessionBox); + + // ---- Focused shutdown-menu variants ---- + auto *shutdownBox = new QGroupBox(QStringLiteral("Shutdown menu (focused variant)")); + auto *shutdownGrid = new QGridLayout(shutdownBox); + shutdownGrid->addWidget(addActionButton(action, status, "power_off", CompositorAction::action_shutdown_menu_power_off), 0, 0); + shutdownGrid->addWidget(addActionButton(action, status, "reboot", CompositorAction::action_shutdown_menu_reboot), 0, 1); + shutdownGrid->addWidget(addActionButton(action, status, "suspend", CompositorAction::action_shutdown_menu_suspend), 0, 2); + shutdownGrid->addWidget(addActionButton(action, status, "hibernate", CompositorAction::action_shutdown_menu_hibernate), 1, 0); + shutdownGrid->addWidget(addActionButton(action, status, "log_out", CompositorAction::action_shutdown_menu_log_out), 1, 1); + vbox->addWidget(shutdownBox); + + return window; +} + +// --------------------------------------------------------------------------- +// main +// --------------------------------------------------------------------------- + +int main(int argc, char *argv[]) +{ + qputenv("QT_QPA_PLATFORM", "wayland"); + QApplication app(argc, argv); + + if (argc > 2) { + fprintf(stderr, "Usage: %s [|list]\n", argv[0]); + printActions(); + return 1; + } + + if (argc == 2 && std::strcmp(argv[1], "list") == 0) { + printActions(); + return 0; + } + + CompositorAction action; + + // The protocol has no bind feedback: if the compositor never advertises + // the global (rejected as non-privileged), fail instead of hanging. + QTimer::singleShot(3000, &action, [&action] { + if (!action.isActive()) { + fprintf(stderr, "treeland_compositor_action_v1 not advertised: " + "bind rejected or compositor does not support it\n"); + QCoreApplication::exit(1); + } + }); + + QObject::connect(&action, &CompositorAction::activeChanged, &action, [&action, argc, argv] { + if (!action.isActive()) { + fprintf(stderr, "treeland_compositor_action_v1 not available: " + "the compositor rejected the bind (not privileged?)\n"); + QCoreApplication::exit(1); + return; + } + + if (argc == 2) { + // One-shot CLI mode: trigger a single action and exit. + uint32_t value = 0; + if (!resolveAction(argv[1], &value)) { + fprintf(stderr, "Unknown action: %s\n", argv[1]); + printActions(); + QCoreApplication::exit(1); + return; + } + printf("Triggering action %u\n", value); + action.trigger(value); + flushWayland(); + QCoreApplication::exit(0); + return; + } + + buildGui(&action)->show(); + }); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/test_data_control_manager/CMakeLists.txt b/examples/test_data_control_manager/CMakeLists.txt new file mode 100644 index 0000000000..27717ed5b2 --- /dev/null +++ b/examples/test_data_control_manager/CMakeLists.txt @@ -0,0 +1,28 @@ +set(BIN_NAME test-data-control-manager) + +find_package(Qt6 REQUIRED COMPONENTS Core Gui WaylandClient) +find_package(PkgConfig REQUIRED) +pkg_check_modules(WLR_PROTOCOLS REQUIRED IMPORTED_TARGET wlr-protocols) +pkg_get_variable(WLR_PROTOCOLS_DATADIR wlr-protocols pkgdatadir) + +qt_add_executable(${BIN_NAME} + main.cpp + clipboard.h + clipboard.cpp + datacontrolmanagerv1.h + datacontrolmanagerv1.cpp +) + +qt6_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${WLR_PROTOCOLS_DATADIR}/unstable/wlr-data-control-unstable-v1.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Core + Qt6::Gui + Qt6::WaylandClient +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_data_control_manager/clipboard.cpp b/examples/test_data_control_manager/clipboard.cpp new file mode 100644 index 0000000000..a45f9efe95 --- /dev/null +++ b/examples/test_data_control_manager/clipboard.cpp @@ -0,0 +1,79 @@ +// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "clipboard.h" + +#include +#include + +Clipboard::Clipboard(QObject *parent) + : QObject{ parent } +{ + m_manager.reset(new DataControlDeviceV1ManagerV1); + QObject::connect(m_manager.get(), &DataControlDeviceV1ManagerV1::activeChanged, this, [this]() { + if (m_manager->isActive()) { + auto waylandApp = qGuiApp->nativeInterface(); + if (!waylandApp) { + return; + } + auto seat = waylandApp->seat(); + + if (!seat) + qFatal("Failed to get wl_seat frome QtWayland QPA!"); + + m_device.reset(new DataControlDeviceV1(m_manager->get_data_device(seat))); + + connect(m_device.get(), &DataControlDeviceV1::receivedSelectionChanged, this, [this]() { + if (!m_device->selection()) { + Q_EMIT changed(QClipboard::Clipboard); + + if (m_device->m_receivedSelection) { + DataControlOfferV1 *offer = m_device->m_receivedSelection.get(); + for (auto type : offer->formats()) { + QVariant data = offer->retrieveData(type); + qWarning() << "----------" + "receivedSelectionChanged---" + << "type:=" << type << "data:= " << data; + } + } + } + }); + connect(m_device.get(), &DataControlDeviceV1::selectionChanged, this, [this]() { + Q_EMIT changed(QClipboard::Clipboard); + }); + + connect(m_device.get(), + &DataControlDeviceV1::receivedPrimarySelectionChanged, + this, + [this]() { + if (!m_device->primarySelection()) { + Q_EMIT changed(QClipboard::Selection); + + if (m_device->m_receivedPrimarySelection) { + DataControlOfferV1 *offer = + m_device->m_receivedPrimarySelection.get(); + for (auto type : offer->formats()) { + QVariant data = offer->retrieveData(type); + qWarning() << "----------" + "receivedPrimarySelectionChanged" + << "type:=" << type << "data:= " << data; + } + } + } + }); + connect(m_device.get(), &DataControlDeviceV1::primarySelectionChanged, this, [this]() { + Q_EMIT changed(QClipboard::Selection); + }); + + } else { + m_device.reset(); + } + }); + + m_manager->instantiate(); +} + +bool Clipboard::isValid() +{ + return m_manager && m_manager->isInitialized(); +} diff --git a/examples/test_data_control_manager/clipboard.h b/examples/test_data_control_manager/clipboard.h new file mode 100644 index 0000000000..198070a424 --- /dev/null +++ b/examples/test_data_control_manager/clipboard.h @@ -0,0 +1,25 @@ +// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "datacontrolmanagerv1.h" + +#include +#include + +class Clipboard : public QObject +{ + Q_OBJECT +public: + explicit Clipboard(QObject *parent = nullptr); + ~Clipboard() = default; + + bool isValid(); + +Q_SIGNALS: + void changed(QClipboard::Mode mode); + +private: + std::unique_ptr m_manager; + std::unique_ptr m_device; +}; diff --git a/examples/test_data_control_manager/datacontrolmanagerv1.cpp b/examples/test_data_control_manager/datacontrolmanagerv1.cpp new file mode 100644 index 0000000000..ab525d1c23 --- /dev/null +++ b/examples/test_data_control_manager/datacontrolmanagerv1.cpp @@ -0,0 +1,390 @@ +// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "datacontrolmanagerv1.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#define ZWLRDATACONTROLMANAGERV1VERSION 2 + +static const QString QtXImageLiteral QStringLiteral("application/x-qt-image"); +static const QString utf8Text QStringLiteral("text/plain;charset=utf-8"); +static const QString textPlain QStringLiteral("text/plain"); + +static QStringList imageMimeFormats(const QList &imageFormats) +{ + QStringList formats; + formats.reserve(imageFormats.size()); + for (const auto &format : imageFormats) + formats.append(QLatin1String("image/") + QLatin1String(format.toLower())); + + int pngIndex = formats.indexOf(QLatin1String("image/png")); + if (pngIndex != -1 && pngIndex != 0) + formats.move(pngIndex, 0); + return formats; +} + +static inline QStringList imageReadMimeFormats() +{ + return imageMimeFormats(QImageReader::supportedImageFormats()); +} + +static inline QStringList imageWriteMimeFormats() +{ + return imageMimeFormats(QImageWriter::supportedImageFormats()); +} + +DataControlDeviceV1ManagerV1::DataControlDeviceV1ManagerV1() + : QWaylandClientExtensionTemplate(ZWLRDATACONTROLMANAGERV1VERSION) +{ +} + +DataControlDeviceV1ManagerV1::~DataControlDeviceV1ManagerV1() +{ + if (isInitialized()) { + destroy(); + } +} + +void DataControlDeviceV1ManagerV1::instantiate() +{ + initialize(); +} + +DataControlOfferV1::DataControlOfferV1(struct ::zwlr_data_control_offer_v1 *id) + : QtWayland::zwlr_data_control_offer_v1(id) +{ +} + +DataControlOfferV1::~DataControlOfferV1() +{ + destroy(); +} + +QStringList DataControlOfferV1::formats() const +{ + return m_receivedFormats; +} + +bool DataControlOfferV1::containsImageData() const +{ + if (m_receivedFormats.contains(QtXImageLiteral)) { + return true; + } + const auto formats = imageReadMimeFormats(); + for (const auto &receivedFormat : m_receivedFormats) { + if (formats.contains(receivedFormat)) { + return true; + } + } + return false; +} + +bool DataControlOfferV1::hasFormat(const QString &mimeType) const +{ + if (mimeType == textPlain && m_receivedFormats.contains(utf8Text)) { + return true; + } + if (m_receivedFormats.contains(mimeType)) { + return true; + } + + if (containsImageData()) { + const QStringList imageFormats = imageWriteMimeFormats(); + for (const QString &imageFormat : imageFormats) { + if (imageFormat == mimeType) { + return true; + } + } + if (mimeType == QtXImageLiteral) { + return true; + } + } + + return false; +} + +void DataControlOfferV1::zwlr_data_control_offer_v1_offer(const QString &mime_type) +{ + m_receivedFormats << mime_type; + + QVariant data = retrieveData(mime_type); + qWarning() << "------------------- offer changed---" + << "type:=" << mime_type << "data:= " << data; +} + +QVariant DataControlOfferV1::retrieveData(const QString &mimeType) const +{ + QString mime; + if (!m_receivedFormats.contains(mimeType)) { + if (mimeType == textPlain && m_receivedFormats.contains(utf8Text)) { + mime = utf8Text; + } else if (mimeType == QtXImageLiteral) { + const auto writeFormats = imageWriteMimeFormats(); + for (const auto &receivedFormat : m_receivedFormats) { + if (writeFormats.contains(receivedFormat)) { + mime = receivedFormat; + break; + } + } + if (mime.isEmpty()) { + mime = QStringLiteral("image/png"); + } + } + + if (mime.isEmpty()) { + return QVariant(); + } + } else { + mime = mimeType; + } + + int pipeFds[2]; + if (pipe(pipeFds) != 0) { + return QVariant(); + } + + auto t = const_cast(this); + t->receive(mime, pipeFds[1]); + + close(pipeFds[1]); + + auto waylandApp = qGuiApp->nativeInterface(); + auto display = waylandApp->display(); + + wl_display_flush(display); + + QFile readPipe; + if (readPipe.open(pipeFds[0], QIODevice::ReadOnly)) { + QByteArray data; + if (readData(pipeFds[0], data)) { + close(pipeFds[0]); + + if (mimeType == QtXImageLiteral) { + QImage img = QImage::fromData( + data, + mime.mid(mime.indexOf(QLatin1Char('/')) + 1).toLatin1().toUpper().data()); + if (!img.isNull()) { + return img; + } + } + return data; + } + close(pipeFds[0]); + } + return QVariant(); +} + +bool DataControlOfferV1::readData(int fd, QByteArray &data) +{ + pollfd pfds[1]; + pfds[0].fd = fd; + pfds[0].events = POLLIN; + + while (true) { + const int ready = poll(pfds, 1, 1000); + if (ready < 0) { + if (errno != EINTR) { + qWarning("DataControlOfferV1: poll() failed: %s", strerror(errno)); + return false; + } + } else if (ready == 0) { + qWarning("DataControlOfferV1: timeout reading from pipe"); + return false; + } else { + char buf[4096]; + int n = read(fd, buf, sizeof buf); + + if (n < 0) { + qWarning("DataControlOfferV1: read() failed: %s", strerror(errno)); + return false; + } else if (n == 0) { + return true; + } else if (n > 0) { + data.append(buf, n); + } + } + } +} + +DataControlSourceV1::DataControlSourceV1(struct ::zwlr_data_control_source_v1 *id, + QMimeData *mimeData) + : QtWayland::zwlr_data_control_source_v1(id) + , m_mimeData(mimeData) +{ + const auto formats = mimeData->formats(); + for (const QString &format : formats) { + offer(format); + } + if (mimeData->hasText()) { + offer(utf8Text); + } + + if (mimeData->hasImage()) { + const QStringList imageFormats = imageWriteMimeFormats(); + for (const QString &imageFormat : imageFormats) { + if (!formats.contains(imageFormat)) { + offer(imageFormat); + } + } + } +} + +DataControlSourceV1::~DataControlSourceV1() +{ + destroy(); +} + +QMimeData *DataControlSourceV1::mimeData() +{ + return m_mimeData.get(); +} + +std::unique_ptr DataControlSourceV1::releaseMimeData() +{ + return std::move(m_mimeData); +} + +void DataControlSourceV1::zwlr_data_control_source_v1_send(const QString &mime_type, int32_t fd) +{ + QString send_mime_type = mime_type; + if (send_mime_type == utf8Text) { + send_mime_type = textPlain; + } + + QByteArray ba; + if (m_mimeData->hasImage()) { + if (mime_type == QtXImageLiteral) { + QImage image = qvariant_cast(m_mimeData->imageData()); + QBuffer buf(&ba); + buf.open(QBuffer::WriteOnly); + image.save(&buf, "PNG"); + + } else if (mime_type.startsWith(QLatin1String("image/"))) { + QImage image = qvariant_cast(m_mimeData->imageData()); + QBuffer buf(&ba); + buf.open(QBuffer::WriteOnly); + image.save( + &buf, + mime_type.mid(mime_type.indexOf(QLatin1Char('/')) + 1).toLatin1().toUpper().data()); + } + } else { + ba = m_mimeData->data(send_mime_type); + } + + struct sigaction action, oldAction; + action.sa_handler = SIG_IGN; + sigemptyset(&action.sa_mask); + action.sa_flags = 0; + sigaction(SIGPIPE, &action, &oldAction); + const ssize_t expected = static_cast(ba.size()); + const ssize_t written = write(fd, ba.constData(), static_cast(ba.size())); + if (written < 0) { + qWarning() << "failed to write clipboard data:" << strerror(errno); + } else if (written != expected) { + qWarning() << "failed to write clipboard data: short write"; + } + sigaction(SIGPIPE, &oldAction, nullptr); + close(fd); +} + +void DataControlSourceV1::zwlr_data_control_source_v1_cancelled() +{ + qWarning() << "-------------------cancelled"; + Q_EMIT cancelled(); +} + +DataControlDeviceV1::DataControlDeviceV1(struct ::zwlr_data_control_device_v1 *id) + : QtWayland::zwlr_data_control_device_v1(id) +{ +} + +DataControlDeviceV1::~DataControlDeviceV1() +{ + destroy(); +} + +void DataControlDeviceV1::setSelection(std::unique_ptr selection) +{ + m_selection = std::move(selection); + connect(m_selection.get(), &DataControlSourceV1::cancelled, this, [this]() { + m_selection.reset(); + }); + set_selection(m_selection->object()); + Q_EMIT selectionChanged(); +} + +QMimeData *DataControlDeviceV1::receivedSelection() +{ + return m_receivedSelection.get(); +} + +QMimeData *DataControlDeviceV1::selection() +{ + return m_selection ? m_selection->mimeData() : nullptr; +} + +void DataControlDeviceV1::setPrimarySelection(std::unique_ptr selection) +{ + m_primarySelection = std::move(selection); + connect(m_primarySelection.get(), &DataControlSourceV1::cancelled, this, [this]() { + m_primarySelection.reset(); + }); + + if (zwlr_data_control_device_v1_get_version(object()) + >= ZWLR_DATA_CONTROL_DEVICE_V1_SET_PRIMARY_SELECTION_SINCE_VERSION) { + set_primary_selection(m_primarySelection->object()); + Q_EMIT primarySelectionChanged(); + } +} + +QMimeData *DataControlDeviceV1::receivedPrimarySelection() +{ + return m_receivedPrimarySelection.get(); +} + +QMimeData *DataControlDeviceV1::primarySelection() +{ + return m_primarySelection ? m_primarySelection->mimeData() : nullptr; +} + +void DataControlDeviceV1::zwlr_data_control_device_v1_data_offer(zwlr_data_control_offer_v1 *id) +{ + new DataControlOfferV1(id); +} + +void DataControlDeviceV1::zwlr_data_control_device_v1_selection(zwlr_data_control_offer_v1 *id) +{ + if (!id) { + m_receivedSelection.reset(); + } else { + auto derivated = QtWayland::zwlr_data_control_offer_v1::fromObject(id); + auto offer = dynamic_cast(derivated); + m_receivedSelection.reset(offer); + } + + Q_EMIT receivedSelectionChanged(); +} + +void DataControlDeviceV1::zwlr_data_control_device_v1_primary_selection( + zwlr_data_control_offer_v1 *id) +{ + if (!id) { + m_receivedPrimarySelection.reset(); + } else { + auto derivated = QtWayland::zwlr_data_control_offer_v1::fromObject(id); + auto offer = dynamic_cast(derivated); + m_receivedPrimarySelection.reset(offer); + } + Q_EMIT receivedPrimarySelectionChanged(); +} diff --git a/examples/test_data_control_manager/datacontrolmanagerv1.h b/examples/test_data_control_manager/datacontrolmanagerv1.h new file mode 100644 index 0000000000..f502841ce8 --- /dev/null +++ b/examples/test_data_control_manager/datacontrolmanagerv1.h @@ -0,0 +1,111 @@ +// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "qwayland-wlr-data-control-unstable-v1.h" + +#include +#include +#include + +class Clipboard; + +class DataControlDeviceV1ManagerV1 + : public QWaylandClientExtensionTemplate + , public QtWayland::zwlr_data_control_manager_v1 +{ + Q_OBJECT +public: + DataControlDeviceV1ManagerV1(); + ~DataControlDeviceV1ManagerV1(); + + void instantiate(); +}; + +class DataControlOfferV1 + : public QMimeData + , public QtWayland::zwlr_data_control_offer_v1 +{ + Q_OBJECT +public: + DataControlOfferV1(struct ::zwlr_data_control_offer_v1 *id); + ~DataControlOfferV1(); + + QStringList formats() const override; + bool containsImageData() const; + bool hasFormat(const QString &mimeType) const override; + QVariant retrieveData(const QString &mimeType) const; + +protected: + void zwlr_data_control_offer_v1_offer(const QString &mime_type) override; + +private: + static bool readData(int fd, QByteArray &data); + QStringList m_receivedFormats; + + friend class DataControlDeviceV1; +}; + +class DataControlSourceV1 + : public QObject + , public QtWayland::zwlr_data_control_source_v1 +{ + Q_OBJECT +public: + DataControlSourceV1(struct ::zwlr_data_control_source_v1 *id, QMimeData *mimeData); + DataControlSourceV1() = default; + ~DataControlSourceV1(); + + QMimeData *mimeData(); + std::unique_ptr releaseMimeData(); + +Q_SIGNALS: + void cancelled(); + +protected: + void zwlr_data_control_source_v1_send(const QString &mime_type, int32_t fd) override; + void zwlr_data_control_source_v1_cancelled() override; + +private: + std::unique_ptr m_mimeData; +}; + +class DataControlDeviceV1 + : public QObject + , public QtWayland::zwlr_data_control_device_v1 +{ + Q_OBJECT +public: + DataControlDeviceV1(struct ::zwlr_data_control_device_v1 *id); + ~DataControlDeviceV1(); + + void setSelection(std::unique_ptr selection); + QMimeData *receivedSelection(); + QMimeData *selection(); + + void setPrimarySelection(std::unique_ptr selection); + QMimeData *receivedPrimarySelection(); + QMimeData *primarySelection(); + +Q_SIGNALS: + void receivedSelectionChanged(); + void selectionChanged(); + + void receivedPrimarySelectionChanged(); + void primarySelectionChanged(); + +protected: + void zwlr_data_control_device_v1_data_offer(struct ::zwlr_data_control_offer_v1 *id) override; + void zwlr_data_control_device_v1_selection(struct ::zwlr_data_control_offer_v1 *id) override; + void zwlr_data_control_device_v1_primary_selection( + struct ::zwlr_data_control_offer_v1 *id) override; + +private: + std::unique_ptr m_selection; + std::unique_ptr m_receivedSelection; + + std::unique_ptr m_primarySelection; + std::unique_ptr m_receivedPrimarySelection; + + friend class Clipboard; +}; diff --git a/examples/test_data_control_manager/main.cpp b/examples/test_data_control_manager/main.cpp new file mode 100644 index 0000000000..cc629655dc --- /dev/null +++ b/examples/test_data_control_manager/main.cpp @@ -0,0 +1,14 @@ +// SPDX-FileCopyrightText: 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "clipboard.h" + +#include + +int main(int argc, char *argv[]) +{ + QGuiApplication app(argc, argv); + Clipboard board; + + return app.exec(); +} diff --git a/examples/test_dde_shell/CMakeLists.txt b/examples/test_dde_shell/CMakeLists.txt new file mode 100644 index 0000000000..521517c5a2 --- /dev/null +++ b/examples/test_dde_shell/CMakeLists.txt @@ -0,0 +1,30 @@ +find_package(Qt6 REQUIRED COMPONENTS Gui WaylandClient Widgets) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS WaylandClientPrivate) +endif() +find_package(TreelandProtocols REQUIRED) + +set(BIN_NAME test-dde-shell) + +qt_add_executable(${BIN_NAME} + main.cpp + ddeshellwayland.h ddeshellwayland.cpp + ddeshelsurfacewindow.h ddeshelsurfacewindow.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + NO_INCLUDE_CORE_ONLY + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-dde-shell-unstable-v2.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::Widgets + Qt6::WaylandClient + Qt6::WaylandClientPrivate +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") + diff --git a/examples/test_dde_shell/ddeshellwayland.cpp b/examples/test_dde_shell/ddeshellwayland.cpp new file mode 100644 index 0000000000..f30f43f43d --- /dev/null +++ b/examples/test_dde_shell/ddeshellwayland.cpp @@ -0,0 +1,290 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "ddeshellwayland.h" + +#include + +#include +#include +#include + +#include +#include + +#define TREELANDDDESHELLMANAGERV2VERSION 2 + +class DDEShellManageV2 + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_dde_shell_manager_v2 +{ +public: + DDEShellManageV2() + : QWaylandClientExtensionTemplate(TREELANDDDESHELLMANAGERV2VERSION) + { + initialize(); + } +}; + +class DDEShellSurface : public QtWayland::treeland_dde_shell_surface_v2 +{ +public: + DDEShellSurface(struct ::treeland_dde_shell_surface_v2 *id, + std::function onRole) + : QtWayland::treeland_dde_shell_surface_v2(id) + , m_onRole(std::move(onRole)) + { + } + + ~DDEShellSurface() + { + destroy(); + } + +protected: + void treeland_dde_shell_surface_v2_role(uint32_t role) override + { + m_onRole(static_cast(role)); + } + +private: + std::function m_onRole; +}; + +class ShellIntegrationSingleton +{ +public: + ShellIntegrationSingleton(); + std::unique_ptr shellManager; + QHash windows; +}; + +ShellIntegrationSingleton::ShellIntegrationSingleton() +{ + shellManager = std::make_unique(); +} + +Q_GLOBAL_STATIC(ShellIntegrationSingleton, s_waylandIntegration) + +DDEShellWayland *DDEShellWayland::get(QWindow *window) +{ + DDEShellWayland *&it = s_waylandIntegration->windows[window]; + if (!it) { + it = new DDEShellWayland(window); + } + return it; +} + +DDEShellWayland::~DDEShellWayland() +{ + s_waylandIntegration->windows.remove(m_window); +} + +DDEShellWayland::DDEShellWayland(QWindow *window) + : QObject(window) + , m_window(window) +{ + m_window->installEventFilter(this); + + // The QWaylandClientExtension binds the global asynchronously: at first + // construction it is usually not active yet. Retry creating the shell + // surface once the manager becomes active, otherwise requests sent before + // activation would only be cached locally and never reach the compositor. + connect(s_waylandIntegration->shellManager.get(), + &DDEShellManageV2::activeChanged, + this, + &DDEShellWayland::surfaceCreated); + + platformSurfaceCreated(window); +} + +bool DDEShellWayland::eventFilter(QObject *watched, QEvent *event) +{ + auto window = qobject_cast(watched); + if (!window) { + return false; + } + if (event->type() == QEvent::PlatformSurface) { + auto surfaceEvent = static_cast(event); + if (surfaceEvent->surfaceEventType() == QPlatformSurfaceEvent::SurfaceCreated) { + platformSurfaceCreated(window); + } else if (surfaceEvent->surfaceEventType() + == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed) { + // The v2 protocol requires the shell surface to be destroyed + // before the wl_surface. Destroy it now; otherwise the shell + // surface proxy would outlive the wl_surface and the compositor + // rejects the stale object ("invalid object") on teardown. + surfaceDestroyed(); + } + } + return false; +} + +void DDEShellWayland::setPosition(const QPoint &position) +{ + if (position == m_position) { + return; + } + + m_position = position; + m_cursorPlacement.reset(); + if (m_shellSurface) { + // v2 position hint is output-relative; passing a null output anchors + // the coordinates at the primary output origin. + m_shellSurface->set_position_hint(nullptr, position.x(), position.y()); + } +} + +void DDEShellWayland::setRole(Role role) +{ + // Applying the same request again must work after a compositor-side change. + m_role = role; + if (m_shellSurface && (role != Role::role_always_on_top || protocolVersion() >= 2)) { + m_shellSurface->set_role(role); + } +} + +void DDEShellWayland::setEffectiveRole(Role role) +{ + m_effectiveRole = role; + Q_EMIT roleStateChanged(); +} + +uint32_t DDEShellWayland::protocolVersion() const +{ + return m_shellSurface ? m_shellSurface->version() : 0; +} + +void DDEShellWayland::setCursorPlacement(int32_t xOffset, int32_t yOffset) +{ + const QPoint offset(xOffset, yOffset); + if (offset == m_cursorPlacement) { + return; + } + + m_cursorPlacement = offset; + m_position.reset(); + if (m_shellSurface) { + m_shellSurface->set_cursor_placement_hint(xOffset, yOffset); + } +} + +void DDEShellWayland::setSkipSwitcher(uint32_t skip) +{ + m_skipFlags = skip ? (m_skipFlags | QtWayland::treeland_dde_shell_surface_v2::skip_flag_switcher) + : (m_skipFlags & ~QtWayland::treeland_dde_shell_surface_v2::skip_flag_switcher); + if (m_shellSurface) { + m_shellSurface->set_skip_flags(m_skipFlags); + } +} + +void DDEShellWayland::setSkipDockPreview(uint32_t skip) +{ + m_skipFlags = skip ? (m_skipFlags | QtWayland::treeland_dde_shell_surface_v2::skip_flag_dock_preview) + : (m_skipFlags & ~QtWayland::treeland_dde_shell_surface_v2::skip_flag_dock_preview); + if (m_shellSurface) { + m_shellSurface->set_skip_flags(m_skipFlags); + } +} + +void DDEShellWayland::setSkipMutiTaskView(uint32_t skip) +{ + m_skipFlags = skip ? (m_skipFlags | QtWayland::treeland_dde_shell_surface_v2::skip_flag_multitask_view) + : (m_skipFlags & ~QtWayland::treeland_dde_shell_surface_v2::skip_flag_multitask_view); + if (m_shellSurface) { + m_shellSurface->set_skip_flags(m_skipFlags); + } +} + +void DDEShellWayland::setAcceptKeyboardFocus(uint32_t accept) +{ + if (accept == m_acceptKeyboardFocus) { + return; + } + + m_acceptKeyboardFocus = accept; + if (m_shellSurface) { + m_shellSurface->set_accept_keyboard_focus(accept); + } +} + +void DDEShellWayland::platformSurfaceCreated(QWindow *window) +{ + auto waylandWindow = window->nativeInterface(); + if (!waylandWindow) { + return; + } + connect(waylandWindow, + &QNativeInterface::Private::QWaylandWindow::surfaceCreated, + this, + &DDEShellWayland::surfaceCreated); + connect(waylandWindow, + &QNativeInterface::Private::QWaylandWindow::surfaceDestroyed, + this, + &DDEShellWayland::surfaceDestroyed); + if (waylandWindow->surface()) { + surfaceCreated(); + } +} + +void DDEShellWayland::surfaceCreated() +{ + if (!s_waylandIntegration->shellManager || !s_waylandIntegration->shellManager->isActive()) { + return; + } + + // Already created for the current wayland surface: avoid binding the same + // wl_surface twice (the compositor raises already_shell_surface for a + // second attempt). activeChanged and surfaceCreated may both fire. + if (m_shellSurface) { + return; + } + + struct wl_surface *surface = nullptr; + if (auto waylandWindow = + m_window->nativeInterface()) { + surface = waylandWindow->surface(); + } + + if (!surface) { + return; + } + + auto *id = s_waylandIntegration->shellManager->get_shell_surface(surface); + if (!id) { + return; + } + + m_shellSurface = std::make_unique(id, [this](Role role) { + setEffectiveRole(role); + }); + m_effectiveRole.reset(); + if (m_role) { + setRole(*m_role); + } + + if (m_position) { + m_shellSurface->set_position_hint(nullptr, m_position->x(), m_position->y()); + } + + if (m_cursorPlacement) { + m_shellSurface->set_cursor_placement_hint(m_cursorPlacement->x(), m_cursorPlacement->y()); + } + + m_shellSurface->set_skip_flags(m_skipFlags); + + if (!m_acceptKeyboardFocus) { + m_shellSurface->set_accept_keyboard_focus(m_acceptKeyboardFocus); + } + Q_EMIT roleStateChanged(); +} + +void DDEShellWayland::surfaceDestroyed() +{ + if (!m_shellSurface) { + return; + } + m_shellSurface.reset(); + m_effectiveRole.reset(); + Q_EMIT roleStateChanged(); +} diff --git a/examples/test_dde_shell/ddeshellwayland.h b/examples/test_dde_shell/ddeshellwayland.h new file mode 100644 index 0000000000..f503a913e5 --- /dev/null +++ b/examples/test_dde_shell/ddeshellwayland.h @@ -0,0 +1,54 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "qwayland-treeland-dde-shell-unstable-v2.h" + +#include +#include + +#include + +class DDEShellSurface; + +class DDEShellWayland : public QObject +{ + Q_OBJECT +public: + using Role = QtWayland::treeland_dde_shell_surface_v2::role; + + static DDEShellWayland *get(QWindow *window); + ~DDEShellWayland(); + + void setPosition(const QPoint &position); + void setRole(Role role); + std::optional effectiveRole() const { return m_effectiveRole; } + uint32_t protocolVersion() const; + void setCursorPlacement(int32_t xOffset, int32_t yOffset); + void setSkipSwitcher(uint32_t skip); + void setSkipDockPreview(uint32_t skip); + void setSkipMutiTaskView(uint32_t skip); + void setAcceptKeyboardFocus(uint32_t accept); + bool eventFilter(QObject *watched, QEvent *event) override; + +Q_SIGNALS: + void roleStateChanged(); + +private: + DDEShellWayland(QWindow *window); + void platformSurfaceCreated(QWindow *window); + void surfaceCreated(); + void surfaceDestroyed(); + void setEffectiveRole(Role role); + + QWindow *m_window = nullptr; + std::optional m_position; + std::optional m_role; + std::optional m_effectiveRole; + std::optional m_cursorPlacement; + uint32_t m_skipFlags = 0; + bool m_acceptKeyboardFocus = true; + + std::unique_ptr m_shellSurface; +}; diff --git a/examples/test_dde_shell/ddeshelsurfacewindow.cpp b/examples/test_dde_shell/ddeshelsurfacewindow.cpp new file mode 100644 index 0000000000..62c1c36f23 --- /dev/null +++ b/examples/test_dde_shell/ddeshelsurfacewindow.cpp @@ -0,0 +1,175 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "ddeshelsurfacewindow.h" + +#include "ddeshellwayland.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { +using ShellSurface = QtWayland::treeland_dde_shell_surface_v2; + +QString roleName(DDEShellWayland::Role role) +{ + switch (role) { + case ShellSurface::role_normal: + return QStringLiteral("normal"); + case ShellSurface::role_overlay: + return QStringLiteral("overlay"); + case ShellSurface::role_always_on_top: + return QStringLiteral("always_on_top"); + } + return QStringLiteral("未知角色 (%1)").arg(static_cast(role)); +} +} + +DDEShelSurfaceWindow::DDEShelSurfaceWindow(TestMode mode, QWidget *parent) + : QWidget{ parent } + , m_mode(mode) +{ + setWindowTitle(QStringLiteral("treeland_dde_shell_unstable_v2 示例")); + resize(520, 460); + + auto *title = new QLabel(QStringLiteral("

treeland_dde_shell_unstable_v2 示例

" + "测试 DDE Shell surface 的 role / skip 位域 / 键盘焦点")); + title->setWordWrap(true); + + // role 选择 + m_roleCombo = new QComboBox; + m_roleCombo->addItem(QStringLiteral("role_overlay(overlay 层,位于普通窗口之上)"), int(QtWayland::treeland_dde_shell_surface_v2::role_overlay)); + m_roleCombo->addItem(QStringLiteral("role_normal(普通窗口层)"), int(QtWayland::treeland_dde_shell_surface_v2::role_normal)); + m_roleCombo->addItem(QStringLiteral("role_always_on_top(始终置顶)"), + int(ShellSurface::role_always_on_top)); + + // skip 位域 + auto *skipGroup = new QGroupBox(QStringLiteral("set_skip_flags 位域")); + auto *skipLayout = new QVBoxLayout(skipGroup); + m_skipSwitcher = new QCheckBox(QStringLiteral("skip_flag_switcher (0x1)")); + m_skipDockPreview = new QCheckBox(QStringLiteral("skip_flag_dock_preview (0x2)")); + m_skipMultitask = new QCheckBox(QStringLiteral("skip_flag_multitask_view (0x4)")); + skipLayout->addWidget(m_skipSwitcher); + skipLayout->addWidget(m_skipDockPreview); + skipLayout->addWidget(m_skipMultitask); + + // 键盘焦点 + auto *focusGroup = new QGroupBox(QStringLiteral("set_accept_keyboard_focus")); + auto *focusLayout = new QVBoxLayout(focusGroup); + m_acceptFocus = new QCheckBox(QStringLiteral("接受键盘焦点")); + m_acceptFocus->setChecked(true); + m_focusProbe = new QLineEdit; + m_focusProbe->setPlaceholderText(QStringLiteral("点击此处验证是否能获得键盘焦点")); + focusLayout->addWidget(m_acceptFocus); + focusLayout->addWidget(m_focusProbe); + + m_applyButton = new QPushButton(QStringLiteral("应用")); + m_statusLabel = new QLabel; + m_statusLabel->setWordWrap(true); + m_statusLabel->setTextInteractionFlags(Qt::TextSelectableByMouse); + + auto *layout = new QVBoxLayout(this); + layout->addWidget(title); + layout->addWidget(m_roleCombo); + layout->addWidget(skipGroup); + layout->addWidget(focusGroup); + layout->addWidget(m_applyButton); + layout->addWidget(m_statusLabel); + + connect(m_roleCombo, &QComboBox::currentIndexChanged, this, [this] { + DDEShellWayland::get(windowHandle()) + ->setRole(static_cast( + m_roleCombo->currentData().toInt())); + updateStatusLabel(); + }); + connect(m_applyButton, &QPushButton::clicked, this, &DDEShelSurfaceWindow::apply); + connect(m_acceptFocus, &QCheckBox::toggled, this, [this](bool on) { + DDEShellWayland::get(windowHandle())->setAcceptKeyboardFocus(on); + updateStatusLabel(); + }); + connect(m_skipSwitcher, &QCheckBox::toggled, this, [this](bool on) { + DDEShellWayland::get(windowHandle())->setSkipSwitcher(on); + updateStatusLabel(); + }); + connect(m_skipDockPreview, &QCheckBox::toggled, this, [this](bool on) { + DDEShellWayland::get(windowHandle())->setSkipDockPreview(on); + updateStatusLabel(); + }); + connect(m_skipMultitask, &QCheckBox::toggled, this, [this](bool on) { + DDEShellWayland::get(windowHandle())->setSkipMutiTaskView(on); + updateStatusLabel(); + }); + + updateStatusLabel(); +} + +void DDEShelSurfaceWindow::showEvent([[maybe_unused]] QShowEvent *event) +{ + if (isVisible()) { + apply(); + } +} + +void DDEShelSurfaceWindow::updateStatusLabel() +{ + const QString modeText = (m_mode == TestSetPosition) + ? QStringLiteral("set_position_hint (x=%1, y=%2)").arg(m_position.x()).arg(m_position.y()) + : QStringLiteral("set_cursor_placement_hint (x=%1, y=%2)").arg(m_cursorOffset.x()).arg(m_cursorOffset.y()); + + const int skip = (m_skipSwitcher->isChecked() ? 0x1 : 0) + | (m_skipDockPreview->isChecked() ? 0x2 : 0) + | (m_skipMultitask->isChecked() ? 0x4 : 0); + + const auto requestedRole = static_cast(m_roleCombo->currentData().toInt()); + QString effectiveRoleText = QStringLiteral("等待 role 事件"); + if (auto *window = windowHandle()) { + const auto *dde = DDEShellWayland::get(window); + if (const auto effectiveRole = dde->effectiveRole()) { + effectiveRoleText = roleName(*effectiveRole); + } else if (dde->protocolVersion() == 1) { + effectiveRoleText = QStringLiteral("接口版本 1 不支持 role 事件"); + } + } + + m_statusLabel->setText( + QStringLiteral("当前配置:%1\n" + "请求角色: %2\n" + "实际角色(服务端): %3\n" + "skip_flags: 0x%4\n" + "accept_keyboard_focus: %5") + .arg(modeText, roleName(requestedRole), effectiveRoleText) + .arg(skip, 0, 16) + .arg(m_acceptFocus->isChecked() ? QStringLiteral("true") : QStringLiteral("false"))); +} + +void DDEShelSurfaceWindow::apply() +{ + auto *dde = DDEShellWayland::get(windowHandle()); + connect(dde, &DDEShellWayland::roleStateChanged, + this, &DDEShelSurfaceWindow::updateStatusLabel, Qt::UniqueConnection); + + dde->setRole(static_cast(m_roleCombo->currentData().toInt())); + + if (m_mode == TestSetPosition) { + // 1 ---- Convenient for the client to set the position of the surface + dde->setPosition(m_position); + // ---------------------------------------------------------------- + } else { + // 2. Place the surface relative to the cursor.-------------------- + dde->setCursorPlacement(m_cursorOffset.x(), m_cursorOffset.y()); + // --------------------------------------------------------------- + } + + // Setting these bits will indicate that the window prefers not to be + // listed in a switcher/dock-preview/mutitask-view. The skip flags are + // applied immediately via their toggled handlers; the apply button only + // (re)sends role / position / cursor placement / keyboard focus. + dde->setAcceptKeyboardFocus(m_acceptFocus->isChecked()); + + updateStatusLabel(); +} diff --git a/examples/test_dde_shell/ddeshelsurfacewindow.h b/examples/test_dde_shell/ddeshelsurfacewindow.h new file mode 100644 index 0000000000..d41507fd07 --- /dev/null +++ b/examples/test_dde_shell/ddeshelsurfacewindow.h @@ -0,0 +1,50 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +class QCheckBox; +class QComboBox; +class QLabel; +class QLineEdit; +class QPushButton; + +class DDEShelSurfaceWindow : public QWidget +{ + Q_OBJECT +public: + enum TestMode + { + TestSetPosition, + TestSetCursorPlacement + }; + + explicit DDEShelSurfaceWindow(TestMode mode, QWidget *parent = nullptr); + + void setPositionHint(QPoint pos) { m_position = pos; } + void setCursorOffset(QPoint offset) { m_cursorOffset = offset; } + +protected: + void showEvent(QShowEvent *event) override; + +private: + void apply(); + void updateStatusLabel(); + +private: + TestMode m_mode; + QPoint m_position{ 100, 100 }; + QPoint m_cursorOffset{ 0, 30 }; + + QComboBox *m_roleCombo = nullptr; + QCheckBox *m_skipSwitcher = nullptr; + QCheckBox *m_skipDockPreview = nullptr; + QCheckBox *m_skipMultitask = nullptr; + QCheckBox *m_acceptFocus = nullptr; + QLineEdit *m_focusProbe = nullptr; + QPushButton *m_applyButton = nullptr; + QLabel *m_statusLabel = nullptr; +}; diff --git a/examples/test_dde_shell/main.cpp b/examples/test_dde_shell/main.cpp new file mode 100644 index 0000000000..216c237afe --- /dev/null +++ b/examples/test_dde_shell/main.cpp @@ -0,0 +1,61 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "ddeshelsurfacewindow.h" + +#include +#include +#include + +#include + +int main(int argc, char *argv[]) +{ + qputenv("QT_QPA_PLATFORM", "wayland"); + QApplication app(argc, argv); + + QCommandLineParser parser; + QCommandLineOption positionOption( + QStringList{ QStringLiteral("pos") }, + QStringLiteral("set_position_hint 的坐标 (x,y),默认 100,100"), + QStringLiteral("x,y")); + QCommandLineOption cursorOffsetOption( + QStringList{ QStringLiteral("offset") }, + QStringLiteral("set_cursor_placement_hint 的光标偏移 (x,y),默认 0,30"), + QStringLiteral("x,y")); + parser.setApplicationDescription( + QStringLiteral("treeland_dde_shell_unstable_v2 示例。\n" + "--pos 使用 set_position_hint(固定坐标)模式,\n" + "--offset 使用 set_cursor_placement_hint(相对光标放置)模式,\n" + "两者互斥,只能指定其一;都不指定时默认固定坐标模式。")); + parser.addHelpOption(); + parser.addOption(positionOption); + parser.addOption(cursorOffsetOption); + parser.process(app); + + if (parser.isSet(positionOption) && parser.isSet(cursorOffsetOption)) { + fputs("error: --pos and --offset are mutually exclusive\n", stderr); + return 1; + } + + DDEShelSurfaceWindow::TestMode mode = DDEShelSurfaceWindow::TestMode::TestSetPosition; + if (parser.isSet(cursorOffsetOption)) + mode = DDEShelSurfaceWindow::TestMode::TestSetCursorPlacement; + + DDEShelSurfaceWindow window(mode); + + if (parser.isSet(positionOption)) { + const QStringList parts = parser.value(positionOption).split(QLatin1Char(',')); + if (parts.size() == 2) + window.setPositionHint(QPoint(parts[0].toInt(), parts[1].toInt())); + } + if (parser.isSet(cursorOffsetOption)) { + const QStringList parts = parser.value(cursorOffsetOption).split(QLatin1Char(',')); + if (parts.size() == 2) + window.setCursorOffset(QPoint(parts[0].toInt(), parts[1].toInt())); + } + + window.show(); + + return app.exec(); +} diff --git a/examples/test_decoration/CMakeLists.txt b/examples/test_decoration/CMakeLists.txt new file mode 100644 index 0000000000..d545a463a5 --- /dev/null +++ b/examples/test_decoration/CMakeLists.txt @@ -0,0 +1,30 @@ +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +find_package(Qt6 REQUIRED COMPONENTS Gui WaylandClient Widgets) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS GuiPrivate WaylandClientPrivate) +endif() +find_package(TreelandProtocols REQUIRED) + +set(BIN_NAME test-decoration) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-decoration-unstable-v1.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::Widgets + Qt6::WaylandClient + Qt6::GuiPrivate + Qt6::WaylandClientPrivate +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_decoration/main.cpp b/examples/test_decoration/main.cpp new file mode 100644 index 0000000000..e928886303 --- /dev/null +++ b/examples/test_decoration/main.cpp @@ -0,0 +1,256 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "qwayland-treeland-decoration-unstable-v1.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +// --------------------------------------------------------------------------- +// treeland_decoration_manager_v1 (client-side) +// --------------------------------------------------------------------------- + +class DecorationManager + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_decoration_manager_v1 +{ + Q_OBJECT +public: + explicit DecorationManager(); +}; + +DecorationManager::DecorationManager() + : QWaylandClientExtensionTemplate(1) +{ +} + +// --------------------------------------------------------------------------- +// treeland_decoration_context_v1 (client-side) +// --------------------------------------------------------------------------- + +class DecorationContext + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_decoration_context_v1 +{ + Q_OBJECT +public: + explicit DecorationContext(struct ::treeland_decoration_context_v1 *object); +}; + +DecorationContext::DecorationContext(struct ::treeland_decoration_context_v1 *object) + : QWaylandClientExtensionTemplate(1) + , QtWayland::treeland_decoration_context_v1(object) +{ +} + +// --------------------------------------------------------------------------- +// Input helpers +// --------------------------------------------------------------------------- + +static bool readUInt32(QLineEdit *edit, uint32_t *out, const char *name) +{ + bool ok = false; + const qulonglong value = edit->text().toULongLong(&ok); + if (!ok || value > std::numeric_limits::max()) { + qWarning() << "invalid" << name << ":" << edit->text(); + return false; + } + *out = static_cast(value); + return true; +} + +static bool readInt32(QLineEdit *edit, int32_t *out, const char *name) +{ + bool ok = false; + const qlonglong value = edit->text().toLongLong(&ok); + if (!ok || value < std::numeric_limits::min() + || value > std::numeric_limits::max()) { + qWarning() << "invalid" << name << ":" << edit->text(); + return false; + } + *out = static_cast(value); + return true; +} + +/// Adds a "label + QLineEdit" pair to @p grid at the given logical column. +static QLineEdit *addField(QGridLayout *grid, int row, int col, const QString &label, + const QString &placeholder) +{ + grid->addWidget(new QLabel(label), row, col * 2); + auto *edit = new QLineEdit; + edit->setPlaceholderText(placeholder); + grid->addWidget(edit, row, col * 2 + 1); + return edit; +} + +// --------------------------------------------------------------------------- +// main +// --------------------------------------------------------------------------- + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + DecorationManager manager; + + QObject::connect(&manager, &DecorationManager::activeChanged, &manager, [&manager] { + if (!manager.isActive()) + return; + + static QPointer window; + if (window) + return; + + window = new QWidget; + window->setWindowTitle("Decoration Client (treeland-decoration-unstable-v1)"); + window->setAttribute(Qt::WA_DeleteOnClose); + window->setMinimumWidth(720); + + auto *vbox = new QVBoxLayout(window); + + // ---- Corner radius ---- + vbox->addWidget(new QLabel("Corner radius")); + auto *radiusGrid = new QGridLayout; + QLineEdit *radiusEdit = addField(radiusGrid, 0, 0, "radius", "0 = square"); + radiusEdit->setText("12"); + auto *radiusButton = new QPushButton("Set radius"); + vbox->addLayout(radiusGrid); + vbox->addWidget(radiusButton); + + // ---- Shadow (radius, offset_x, offset_y, r, g, b, a) ---- + vbox->addWidget(new QLabel("Shadow")); + auto *shadowGrid = new QGridLayout; + QLineEdit *shadowRadius = addField(shadowGrid, 0, 0, "radius", "0 = off"); + shadowRadius->setText("40"); + QLineEdit *shadowOx = addField(shadowGrid, 0, 1, "offset_x", "pixels"); + shadowOx->setText("0"); + QLineEdit *shadowOy = addField(shadowGrid, 0, 2, "offset_y", "pixels"); + shadowOy->setText("10"); + QLineEdit *shadowR = addField(shadowGrid, 0, 3, "r", "0-255"); + shadowR->setText("0"); + QLineEdit *shadowG = addField(shadowGrid, 1, 0, "g", "0-255"); + shadowG->setText("0"); + QLineEdit *shadowB = addField(shadowGrid, 1, 1, "b", "0-255"); + shadowB->setText("0"); + QLineEdit *shadowA = addField(shadowGrid, 1, 2, "a", "0-255"); + shadowA->setText("102"); + auto *shadowButton = new QPushButton("Set shadow"); + vbox->addLayout(shadowGrid); + vbox->addWidget(shadowButton); + + // ---- Border (width, r, g, b, a) ---- + vbox->addWidget(new QLabel("Border")); + auto *borderGrid = new QGridLayout; + QLineEdit *borderWidth = addField(borderGrid, 0, 0, "width", "0 = off"); + borderWidth->setText("1"); + QLineEdit *borderR = addField(borderGrid, 0, 1, "r", "0-255"); + borderR->setText("0"); + QLineEdit *borderG = addField(borderGrid, 0, 2, "g", "0-255"); + borderG->setText("0"); + QLineEdit *borderB = addField(borderGrid, 0, 3, "b", "0-255"); + borderB->setText("0"); + QLineEdit *borderA = addField(borderGrid, 1, 0, "a", "0-255"); + borderA->setText("26"); + auto *borderButton = new QPushButton("Set border"); + vbox->addLayout(borderGrid); + vbox->addWidget(borderButton); + + // ---- Titlebar mode ---- + auto *modeRow = new QHBoxLayout; + auto *modeCombo = new QComboBox; + modeCombo->addItem("show", 0); + modeCombo->addItem("hide", 1); + auto *modeButton = new QPushButton("Set titlebar"); + modeRow->addWidget(new QLabel("Titlebar mode")); + modeRow->addWidget(modeCombo, 1); + modeRow->addWidget(modeButton); + vbox->addLayout(modeRow); + + window->show(); + + // The controls live in the same window as the decorated surface. + QWindow *qWindow = window->windowHandle(); + if (!qWindow || !qWindow->handle()) { + qWarning() << "no Wayland window handle"; + return; + } + auto *waylandWindow = static_cast(qWindow->handle()); + struct wl_surface *surface = waylandWindow->wlSurface(); + if (!surface) { + qWarning() << "no wl_surface"; + return; + } + auto *context = new DecorationContext(manager.get_decoration_context(surface)); + + QObject::connect(radiusButton, &QPushButton::clicked, radiusButton, [context, radiusEdit] { + uint32_t radius = 0; + if (!readUInt32(radiusEdit, &radius, "radius")) + return; + context->set_corner_radius(radius); + qDebug() << "set_corner_radius(" << radius << ")"; + }); + + QObject::connect(shadowButton, &QPushButton::clicked, shadowButton, + [context, shadowRadius, shadowOx, shadowOy, shadowR, shadowG, shadowB, + shadowA] { + uint32_t radius = 0; + int32_t ox = 0; + int32_t oy = 0; + uint32_t r = 0; + uint32_t g = 0; + uint32_t b = 0; + uint32_t a = 0; + if (!readUInt32(shadowRadius, &radius, "shadow radius") + || !readInt32(shadowOx, &ox, "shadow offset_x") + || !readInt32(shadowOy, &oy, "shadow offset_y") + || !readUInt32(shadowR, &r, "shadow r") + || !readUInt32(shadowG, &g, "shadow g") + || !readUInt32(shadowB, &b, "shadow b") + || !readUInt32(shadowA, &a, "shadow a")) + return; + context->set_shadow(radius, ox, oy, r, g, b, a); + qDebug() << "set_shadow(" << radius << ox << oy << r << g << b << a + << ")"; + }); + + QObject::connect(borderButton, &QPushButton::clicked, borderButton, + [context, borderWidth, borderR, borderG, borderB, borderA] { + uint32_t width = 0; + uint32_t r = 0; + uint32_t g = 0; + uint32_t b = 0; + uint32_t a = 0; + if (!readUInt32(borderWidth, &width, "border width") + || !readUInt32(borderR, &r, "border r") + || !readUInt32(borderG, &g, "border g") + || !readUInt32(borderB, &b, "border b") + || !readUInt32(borderA, &a, "border a")) + return; + context->set_border(width, r, g, b, a); + qDebug() << "set_border(" << width << r << g << b << a << ")"; + }); + + QObject::connect(modeButton, &QPushButton::clicked, modeButton, [context, modeCombo] { + const uint32_t mode = uint32_t(modeCombo->currentData().toUInt()); + context->set_titlebar_mode(mode); + qDebug() << "set_titlebar_mode(" << modeCombo->currentText() << ")"; + }); + }); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/test_glass/CMakeLists.txt b/examples/test_glass/CMakeLists.txt new file mode 100644 index 0000000000..327a2f886a --- /dev/null +++ b/examples/test_glass/CMakeLists.txt @@ -0,0 +1,100 @@ +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +find_package(Qt6 COMPONENTS Quick QuickControls2 ShaderTools REQUIRED) +qt_standard_project_setup(REQUIRES 6.4) + +if(QT_KNOWN_POLICY_QTP0001) # this policy was introduced in Qt 6.5 + qt_policy(SET QTP0001 NEW) + # the RESOURCE_PREFIX argument for qt_add_qml_module() defaults to ":/qt/qml/" +endif() +if(POLICY CMP0071) + # https://cmake.org/cmake/help/latest/policy/CMP0071.html + cmake_policy(SET CMP0071 NEW) +endif() + +set(QML_IMPORT_PATH "${PROJECT_BINARY_DIR}/src/server;${QML_IMPORT_PATH}" CACHE STRING "For LSP" FORCE) + +find_package(PkgConfig REQUIRED) +pkg_search_module(PIXMAN REQUIRED IMPORTED_TARGET pixman-1) +pkg_search_module(WAYLAND REQUIRED IMPORTED_TARGET wayland-server) + +set(GLASS_LIQUIDGLASS_SHADER_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../misc/shaders") +set(GLASS_EFFECT_QML "${CMAKE_CURRENT_SOURCE_DIR}/../../src/core/qml/Effects/GlassEffect.qml") +set(GLASS_BLUR_QML "${CMAKE_CURRENT_SOURCE_DIR}/../../src/core/qml/Effects/Blur.qml") +set(LOCKSCREEN_ROUNDBLUR_QML "${CMAKE_CURRENT_SOURCE_DIR}/../../src/plugins/lockscreen/qml/RoundBlur.qml") +set_source_files_properties(${GLASS_EFFECT_QML} + PROPERTIES + QT_RESOURCE_ALIAS "GlassEffect.qml" +) +set_source_files_properties(${GLASS_BLUR_QML} + PROPERTIES + QT_RESOURCE_ALIAS "Blur.qml" +) +set_source_files_properties(${LOCKSCREEN_ROUNDBLUR_QML} + PROPERTIES + QT_RESOURCE_ALIAS "RoundBlur.qml" +) + +# ── Stub Treeland QML module ───────────────────────────────────────────── +# Provides a minimal Helper singleton with default-valued glass config so +# the upstream Blur.qml / RoundBlur.qml — which read `Helper.config.*` and +# `import Treeland` — work inside the standalone demo without libtreeland. +qt_add_library(treeland_stub SHARED) +qt_add_qml_module(treeland_stub + URI Treeland + VERSION "2.0" + QML_FILES + ${GLASS_EFFECT_QML} + ${GLASS_BLUR_QML} + ${LOCKSCREEN_ROUNDBLUR_QML} + SOURCES + helper.h + helper.cpp +) +qt_add_shaders(treeland_stub "treeland_stub_liquidglass_shaders" + PRECOMPILE + OPTIMIZED + PREFIX + "/shaders" + BASE + ${GLASS_LIQUIDGLASS_SHADER_DIR} + FILES + ${GLASS_LIQUIDGLASS_SHADER_DIR}/liquidglass.vert + ${GLASS_LIQUIDGLASS_SHADER_DIR}/liquidglass.frag +) +target_compile_definitions(treeland_stub PRIVATE WLR_USE_UNSTABLE) +target_link_libraries(treeland_stub PUBLIC + Qt6::Quick + Waylib::WaylibServer + PkgConfig::PIXMAN + PkgConfig::WAYLAND +) + +# ── test-glass executable ──────────────────────────────────────────────── +add_executable(test-glass + main.cpp +) +qt_add_qml_module(test-glass + URI GlassExample + VERSION "1.0" + QML_FILES + Main.qml + RESOURCES + assets/default-glass-background.jpg +) +target_compile_definitions(test-glass + PRIVATE + SOURCE_DIR="${CMAKE_CURRENT_SOURCE_DIR}" + $<$:START_DEMO> + WLR_USE_UNSTABLE +) +target_link_libraries(test-glass + PRIVATE + Qt6::Quick + Qt6::QuickControls2 + treeland_stub + PkgConfig::PIXMAN + PkgConfig::WAYLAND +) +install(TARGETS test-glass DESTINATION ${CMAKE_INSTALL_BINDIR}) diff --git a/examples/test_glass/Main.qml b/examples/test_glass/Main.qml new file mode 100644 index 0000000000..8305675e42 --- /dev/null +++ b/examples/test_glass/Main.qml @@ -0,0 +1,498 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import QtQuick.Effects +import Waylib.Server +import GlassExample +import Treeland + +Item { + id :root + + readonly property url wallpaperSource: Helper.wallpaperSource + + property bool glassMode: true + property real effectWidth: 300 + property real effectHeight: 200 + property real effectRadius: 12 + property real glassThickness: 30 + property real glassBezelWidth: 30 + property real glassIor: 1.33 + property bool glassBlurEnabled: true + property int glassBlurMax: 64 + property real glassBlurAmount: 0.6 + property real glassBlurMultiplier: 0.0 + property real glassSpecular: 0.0 + property real glassTint: 0.0 + property real glassRefractionMaxTan: 3.3 + property real glassContentEdgePull: 0.0 + property real glassContentRampEnd: 0.0 + property real glassProfilePower: 2.0 + property real glassInnerShadow: 0.0 + property real glassBrightness: 0.0 + property real glassContrast: 0.0 + property real glassSaturation: 0.0 + property bool advancedExpanded: false + + + + Shortcut { + sequences: [StandardKey.Quit] + context: Qt.ApplicationShortcut + onActivated: { + Qt.quit() + } + } + + OutputRenderWindow { + id: renderWindow + + width: outputsContainer.implicitWidth + height: outputsContainer.implicitHeight + color: "black" + + Row { + id: outputsContainer + + anchors.fill: parent + + DynamicCreatorComponent { + id: outputDelegateCreator + creator: Helper.outputCreator + + OutputItem { + id: rootOutputItem + required property WaylandOutput waylandOutput + readonly property OutputViewport onscreenViewport: outputViewport + + output: waylandOutput + devicePixelRatio: waylandOutput.scale + + cursorDelegate: Cursor { + id: cursorItem + + required property QtObject outputCursor + readonly property point position: parent.mapFromGlobal(cursor.position.x, cursor.position.y) + + cursor: outputCursor.cursor + output: outputCursor.output.output + x: position.x - hotSpot.x + y: position.y - hotSpot.y + visible: valid && outputCursor.visible + OutputLayer.enabled: true + OutputLayer.keepLayer: true + OutputLayer.flags: OutputLayer.Cursor + OutputLayer.cursorHotSpot: hotSpot + OutputLayer.outputs: [outputViewport] + } + + OutputViewport { + id: outputViewport + + output: waylandOutput + devicePixelRatio: parent.devicePixelRatio + anchors.centerIn: parent + + RotationAnimation { + id: rotationAnimator + + target: outputViewport + duration: 200 + alwaysRunToEnd: true + } + + Timer { + id: setTransform + + property var scheduleTransform + onTriggered: onscreenViewport.rotateOutput(scheduleTransform) + interval: rotationAnimator.duration / 2 + } + + function rotationOutput(orientation) { + setTransform.scheduleTransform = orientation + setTransform.start() + + switch(orientation) { + case WaylandOutput.R90: + rotationAnimator.to = 90 + break + case WaylandOutput.R180: + rotationAnimator.to = 180 + break + case WaylandOutput.R270: + rotationAnimator.to = -90 + break + default: + rotationAnimator.to = 0 + break + } + + rotationAnimator.from = rotation + rotationAnimator.start() + } + } + + Image { + id: background + source: root.wallpaperSource + fillMode: Image.PreserveAspectFit + asynchronous: true + anchors.fill: parent + smooth: true + } + + Column { + id: controlColumn + anchors { + bottom: parent.bottom + left: parent.left + margins: 10 + } + + spacing: 10 + + // ── Action buttons ────────────────────────── + Row { + spacing: 10 + Button { + text: root.glassMode ? "Switch to Blur" : "Switch to Glass" + onClicked: root.glassMode = !root.glassMode + } + Button { + text: "Grab Glass" + onClicked: { + effectPanel.grabToImage(function(result) { + const path = "/tmp/treeland-liquid-glass-grab.png" + if (result.saveToFile(path)) { + console.log("Liquid Glass grab saved", path, result.image.size) + } else { + console.warn("Liquid Glass grab failed", path) + } + }) + } + } + Button { + text: root.glassBlurEnabled ? "Blur: on" : "Blur: off" + onClicked: root.glassBlurEnabled = !root.glassBlurEnabled + } + } + + GridLayout { + columns: 2 + columnSpacing: 14 + rowSpacing: 4 + + Column { + spacing: 2 + Label { text: "radius " + Math.round(root.effectRadius); color: "white" } + Slider { from: 0; to: 120; value: root.effectRadius; onMoved: root.effectRadius = value } + } + Column { + spacing: 2 + Label { text: "blur max " + root.glassBlurMax; color: "white" } + Slider { from: 0; to: 128; stepSize: 1; value: root.glassBlurMax; onMoved: root.glassBlurMax = value } + } + } + + Button { + text: (root.advancedExpanded ? "▼" : "▶") + " Advanced" + onClicked: root.advancedExpanded = !root.advancedExpanded + } + + GridLayout { + visible: root.advancedExpanded + columns: 4 + columnSpacing: 14 + rowSpacing: 4 + + Column { + spacing: 2 + Label { text: "width " + Math.round(root.effectWidth); color: "white" } + Slider { from: 30; to: 700; value: root.effectWidth; onMoved: root.effectWidth = value } + } + Column { + spacing: 2 + Label { text: "height " + Math.round(root.effectHeight); color: "white" } + Slider { from: 30; to: 800; value: root.effectHeight; onMoved: root.effectHeight = value } + } + Column { + spacing: 2 + Label { text: "thickness " + Math.round(root.glassThickness); color: "white" } + Slider { from: 10; to: 200; value: root.glassThickness; onMoved: root.glassThickness = value } + } + Column { + spacing: 2 + Label { text: "bezel " + Math.round(root.glassBezelWidth); color: "white" } + Slider { from: 2; to: 60; value: root.glassBezelWidth; onMoved: root.glassBezelWidth = value } + } + Column { + spacing: 2 + Label { text: "ior " + root.glassIor.toFixed(2); color: "white" } + Slider { from: 1.0; to: 3.0; stepSize: 0.05; value: root.glassIor; onMoved: root.glassIor = value } + } + Column { + spacing: 2 + Label { text: "blurAmount " + root.glassBlurAmount.toFixed(2); color: "white" } + Slider { from: 0; to: 1; stepSize: 0.05; value: root.glassBlurAmount; onMoved: root.glassBlurAmount = value } + } + Column { + spacing: 2 + Label { text: "blurMultiplier " + root.glassBlurMultiplier.toFixed(2); color: "white" } + Slider { from: 0; to: 4; stepSize: 0.05; value: root.glassBlurMultiplier; onMoved: root.glassBlurMultiplier = value } + } + Label { + text: "Optics / Profile" + color: "white" + font.bold: true + Layout.columnSpan: 4 + } + Column { + spacing: 2 + Label { text: "specular " + root.glassSpecular.toFixed(2); color: "white" } + Slider { from: 0; to: 1; stepSize: 0.05; value: root.glassSpecular; onMoved: root.glassSpecular = value } + } + Column { + spacing: 2 + Label { text: "tint " + Math.round(root.glassTint * 100) + "%"; color: "white" } + Slider { from: 0; to: 0.4; stepSize: 0.01; value: root.glassTint; onMoved: root.glassTint = value } + } + Column { + spacing: 2 + Label { text: "max tan " + root.glassRefractionMaxTan.toFixed(2); color: "white" } + Slider { from: 0.5; to: 20; stepSize: 0.05; value: root.glassRefractionMaxTan; onMoved: root.glassRefractionMaxTan = value } + } + Column { + spacing: 2 + Label { text: "edge pull " + root.glassContentEdgePull.toFixed(2); color: "white" } + Slider { from: 0; to: 1; stepSize: 0.05; value: root.glassContentEdgePull; onMoved: root.glassContentEdgePull = value } + } + Column { + spacing: 2 + Label { text: "ramp end " + root.glassContentRampEnd.toFixed(2); color: "white" } + Slider { from: 0.05; to: 1; stepSize: 0.05; value: root.glassContentRampEnd; onMoved: root.glassContentRampEnd = value } + } + Column { + spacing: 2 + Label { text: "profilePower " + root.glassProfilePower.toFixed(2); color: "white" } + Slider { from: 1; to: 10; stepSize: 0.1; value: root.glassProfilePower; onMoved: root.glassProfilePower = value } + } + Column { + spacing: 2 + Label { text: "innerShadow " + root.glassInnerShadow.toFixed(2); color: "white" } + Slider { from: 0; to: 1; stepSize: 0.05; value: root.glassInnerShadow; onMoved: root.glassInnerShadow = value } + } + Column { + spacing: 2 + Label { text: "brightness " + root.glassBrightness.toFixed(2); color: "white" } + Slider { from: -1; to: 1; stepSize: 0.05; value: root.glassBrightness; onMoved: root.glassBrightness = value } + } + Column { + spacing: 2 + Label { text: "contrast " + root.glassContrast.toFixed(2); color: "white" } + Slider { from: -1; to: 1; stepSize: 0.05; value: root.glassContrast; onMoved: root.glassContrast = value } + } + Column { + spacing: 2 + Label { text: "saturation " + root.glassSaturation.toFixed(2); color: "white" } + Slider { from: -1; to: 1; stepSize: 0.05; value: root.glassSaturation; onMoved: root.glassSaturation = value } + } + } + } + + Column { + anchors { + bottom: parent.bottom + right: parent.right + margins: 10 + } + + spacing: 10 + + Button { + text: "1X" + onClicked: { + onscreenViewport.setOutputScale(1) + } + } + + Button { + text: "1.5X" + onClicked: { + onscreenViewport.setOutputScale(1.5) + } + } + + Button { + text: "Normal" + onClicked: { + outputViewport.rotationOutput(WaylandOutput.Normal) + } + } + + Button { + text: "R90" + onClicked: { + outputViewport.rotationOutput(WaylandOutput.R90) + } + } + + Button { + text: "R270" + onClicked: { + outputViewport.rotationOutput(WaylandOutput.R270) + } + } + + Button { + text: "Quit" + onClicked: { + Qt.quit() + } + } + } + + Text { + anchors.centerIn: parent + text: "'Ctrl+Q' quit" + font.pointSize: 40 + color: "white" + + SequentialAnimation on rotation { + id: ani + running: true + PauseAnimation { duration: 1500 } + NumberAnimation { from: 0; to: 360; duration: 5000; easing.type: Easing.InOutCubic } + loops: Animation.Infinite + } + } + + + function setTransform(transform) { + onscreenViewport.rotationOutput(transform) + } + + function setScale(scale) { + onscreenViewport.setOutputScale(scale) + } + + function invalidate() { + onscreenViewport.invalidate() + } + } + } + } + + Item { + id: effectPanel + width: root.effectWidth + height: root.effectHeight + x: (parent.width - width) / 2 + y: (parent.height - height) / 2 + + MouseArea { + anchors.fill: parent + enabled: true + drag.target: effectPanel + drag.axis: Drag.XAndYAxis + drag.minimumX: 0 + drag.maximumX: parent.parent.width - effectPanel.width + drag.minimumY: 0 + drag.maximumY: parent.parent.height - effectPanel.height + } + + Loader { + anchors.fill: parent + sourceComponent: root.glassMode ? globalGlassComponent : globalBlurComponent + } + + Component { + id: globalGlassComponent + RenderBufferBlitter { + id: blitter + anchors.fill: parent + smooth: true + GlassEffect { + anchors.fill: parent + source: blitter.content + radius: root.effectRadius + blurEnabled: root.glassBlurEnabled + blurMax: root.glassBlurMax + blurAmount: root.glassBlurAmount + blurMultiplier: root.glassBlurMultiplier + bezelWidth: root.glassBezelWidth + thickness: root.glassThickness + ior: root.glassIor + specular: root.glassSpecular + tint: root.glassTint + refractionMaxTan: root.glassRefractionMaxTan + contentEdgePull: root.glassContentEdgePull + contentRampEnd: root.glassContentRampEnd + profilePower: root.glassProfilePower + innerShadow: root.glassInnerShadow + smooth: true + brightness: root.glassBrightness + contrast: root.glassContrast + saturation: root.glassSaturation + } + } + } + + + Component { + id: globalBlurComponent + RenderBufferBlitter { + id: blitter + anchors.fill: parent + MultiEffect { + anchors.fill: parent + source: blitter.content + autoPaddingEnabled: false + blurEnabled: true + blur: 1.0 + blurMax: 64 + saturation: 0.2 + } + } + } + } + + // ── Draggable RoundBlur demo ──────────────────────────────────── + // Uses the real RoundBlur component (Blur subclass) from the + // GlassExample QML module, which reads glass parameters from + // Helper.config. Drag to reposition. + Item { + id: roundBlurPanel + width: 30 + height: 30 + x: (parent.width - width) / 2 + 260 + y: (parent.height - height) / 2 - 180 + + MouseArea { + anchors.fill: parent + drag.target: roundBlurPanel + drag.axis: Drag.XAndYAxis + drag.minimumX: 0 + drag.maximumX: parent.parent.width - roundBlurPanel.width + drag.minimumY: 0 + drag.maximumY: parent.parent.height - roundBlurPanel.height + } + + RoundBlur { + anchors.fill: parent + radius: root.effectRadius + } + + Text { + anchors.left: parent.right + text: "RoundBlur\n(drag me)" + color: "white" + font.pixelSize: 14 + horizontalAlignment: Text.AlignHCenter + } + } + } +} diff --git a/examples/test_glass/assets/default-glass-background.jpg b/examples/test_glass/assets/default-glass-background.jpg new file mode 100644 index 0000000000..d6cac6116e Binary files /dev/null and b/examples/test_glass/assets/default-glass-background.jpg differ diff --git a/examples/test_glass/helper.cpp b/examples/test_glass/helper.cpp new file mode 100644 index 0000000000..25e943c27e --- /dev/null +++ b/examples/test_glass/helper.cpp @@ -0,0 +1,122 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "helper.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +GlassConfig::GlassConfig(QObject *parent) + : QObject(parent) +{ +} + +Helper::Helper(QObject *parent) + : QObject(parent) + , m_server(new WServer(this)) + , m_outputCreator(new WQmlCreator(this)) + , m_outputLayout(new WQuickOutputLayout(m_server)) + , m_cursor(new WCursor(this)) +{ + m_seat = m_server->attach(); + m_seat->setCursor(m_cursor); + m_cursor->setLayout(m_outputLayout); +} + +QString Helper::wallpaperSource() const +{ + return m_wallpaperSource; +} + +void Helper::setWallpaperSource(const QString &wallpaperSource) +{ + if (m_wallpaperSource == wallpaperSource) + return; + + m_wallpaperSource = wallpaperSource; + Q_EMIT wallpaperSourceChanged(); +} + +void Helper::initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine) +{ + m_backend = m_server->attach(); + m_server->start(); + + m_renderer = WRenderHelper::createRenderer(m_backend->handle()); + + if (!m_renderer) { + qFatal("Failed to create renderer"); + } + + connect(m_backend, &WBackend::outputAdded, this, [this, qmlEngine] (WOutput *output) { + auto initProperties = qmlEngine->newObject(); + initProperties.setProperty("waylandOutput", qmlEngine->toScriptValue(output)); + initProperties.setProperty("layout", qmlEngine->toScriptValue(m_outputLayout)); + initProperties.setProperty("x", qmlEngine->toScriptValue(m_outputLayout->implicitWidth())); + + m_outputCreator->add(output, initProperties); + }); + + connect(m_backend, &WBackend::outputRemoved, this, [this] (WOutput *output) { + m_outputCreator->removeByOwner(output); + }); + + connect(m_backend, &WBackend::inputAdded, this, [this] (WInputDevice *device) { + m_seat->attachInputDevice(device); + }); + + connect(m_backend, &WBackend::inputRemoved, this, [this] (WInputDevice *device) { + m_seat->detachInputDevice(device); + }); + + m_allocator = wlr_allocator_autocreate(m_backend->handle(), m_renderer); + wlr_renderer_init_wl_display(m_renderer, m_server->handle()); + + // free follow display + m_compositor = wlr_compositor_create(m_server->handle(), 6, m_renderer); + wlr_subcompositor_create(m_server->handle()); + + connect(window, &WOutputRenderWindow::outputViewportInitialized, this, [] (WOutputViewport *viewport) { + // Trigger QWOutput::frame signal in order to ensure WOutputHelper::renderable + // property is true, OutputRenderWindow when will render this output in next frame. + { + WOutput *output = viewport->output(); + + // Enable on default + // Don't care for WOutput::isEnabled, must do WOutput::commit here, + // In order to ensure the frame signal fires so WOutputRenderWindow + // renders this output in the next frame. + // Keep the "already enabled" marker on the WOutput object itself: + // it is released with the output, so a recycled wlr_output address + // is never mistaken for an already-enabled output. + if (!output->property("_Enabled").toBool()) { + output->setProperty("_Enabled", true); + auto *wlrOutput = output->handle(); + wlr_output_state newState; + wlr_output_state_init(&newState); + + if (!wlrOutput->current_mode) { + auto mode = wlr_output_preferred_mode(wlrOutput); + if (mode) + wlr_output_state_set_mode(&newState, mode); + } + wlr_output_state_set_enabled(&newState, true); + if (!wlr_output_commit_state(wlrOutput, &newState)) { + qCritical("commit failed on output %s", wlrOutput->name); + } + wlr_output_state_finish(&newState); + } + } + }); + window->init(m_renderer, m_allocator); + + wlr_backend_start(m_backend->handle()); +} diff --git a/examples/test_glass/helper.h b/examples/test_glass/helper.h new file mode 100644 index 0000000000..88516bb26b --- /dev/null +++ b/examples/test_glass/helper.h @@ -0,0 +1,174 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include +#include +#include + +// Minimal glass-effect configuration exposed to QML so that the upstream +// Blur.qml / RoundBlur.qml — which read `Helper.config.*` — work inside the +// standalone demo without the full treeland DConfig stack. +class GlassConfig : public QObject { + Q_OBJECT + QML_ELEMENT + QML_SINGLETON + + // Global Liquid Glass vs legacy MultiEffect dispatch + Q_PROPERTY(bool glassEnabled READ glassEnabled WRITE setGlassEnabled NOTIFY glassEnabledChanged) + // Blur tuning + Q_PROPERTY(int blurStrength READ blurStrength WRITE setBlurStrength NOTIFY blurStrengthChanged) + Q_PROPERTY(qreal blurAmount READ blurAmount WRITE setBlurAmount NOTIFY blurAmountChanged) + Q_PROPERTY(qreal blurMultiplier READ blurMultiplier WRITE setBlurMultiplier NOTIFY blurMultiplierChanged) + // Glass material parameters + Q_PROPERTY(qreal glassBezel READ glassBezel WRITE setGlassBezel NOTIFY glassBezelChanged) + Q_PROPERTY(qreal glassThickness READ glassThickness WRITE setGlassThickness NOTIFY glassThicknessChanged) + Q_PROPERTY(qreal glassIor READ glassIor WRITE setGlassIor NOTIFY glassIorChanged) + Q_PROPERTY(qreal glassSpecular READ glassSpecular WRITE setGlassSpecular NOTIFY glassSpecularChanged) + Q_PROPERTY(qreal glassTint READ glassTint WRITE setGlassTint NOTIFY glassTintChanged) + Q_PROPERTY(qreal glassContentEdgePull READ glassContentEdgePull WRITE setGlassContentEdgePull NOTIFY glassContentEdgePullChanged) + Q_PROPERTY(qreal glassContentRampEnd READ glassContentRampEnd WRITE setGlassContentRampEnd NOTIFY glassContentRampEndChanged) + Q_PROPERTY(qreal glassRefractionMaxTan READ glassRefractionMaxTan WRITE setGlassRefractionMaxTan NOTIFY glassRefractionMaxTanChanged) + Q_PROPERTY(qreal glassProfilePower READ glassProfilePower WRITE setGlassProfilePower NOTIFY glassProfilePowerChanged) + Q_PROPERTY(qreal glassInnerShadow READ glassInnerShadow WRITE setGlassInnerShadow NOTIFY glassInnerShadowChanged) + Q_PROPERTY(qreal glassBrightness READ glassBrightness WRITE setGlassBrightness NOTIFY glassBrightnessChanged) + Q_PROPERTY(qreal glassContrast READ glassContrast WRITE setGlassContrast NOTIFY glassContrastChanged) + Q_PROPERTY(qreal glassSaturation READ glassSaturation WRITE setGlassSaturation NOTIFY glassSaturationChanged) + +public: + explicit GlassConfig(QObject *parent = nullptr); + + static GlassConfig *create(QQmlEngine *, QJSEngine *) { return new GlassConfig; } + + bool glassEnabled() const { return m_glassEnabled; } + void setGlassEnabled(bool v) { if (m_glassEnabled != v) { m_glassEnabled = v; Q_EMIT glassEnabledChanged(); } } + int blurStrength() const { return m_blurStrength; } + void setBlurStrength(int v) { if (m_blurStrength != v) { m_blurStrength = v; Q_EMIT blurStrengthChanged(); } } + qreal blurAmount() const { return m_blurAmount; } + void setBlurAmount(qreal v) { if (m_blurAmount != v) { m_blurAmount = v; Q_EMIT blurAmountChanged(); } } + qreal blurMultiplier() const { return m_blurMultiplier; } + void setBlurMultiplier(qreal v) { if (m_blurMultiplier != v) { m_blurMultiplier = v; Q_EMIT blurMultiplierChanged(); } } + qreal glassBezel() const { return m_glassBezel; } + void setGlassBezel(qreal v) { if (m_glassBezel != v) { m_glassBezel = v; Q_EMIT glassBezelChanged(); } } + qreal glassThickness() const { return m_glassThickness; } + void setGlassThickness(qreal v) { if (m_glassThickness != v) { m_glassThickness = v; Q_EMIT glassThicknessChanged(); } } + qreal glassIor() const { return m_glassIor; } + void setGlassIor(qreal v) { if (m_glassIor != v) { m_glassIor = v; Q_EMIT glassIorChanged(); } } + qreal glassSpecular() const { return m_glassSpecular; } + void setGlassSpecular(qreal v) { if (m_glassSpecular != v) { m_glassSpecular = v; Q_EMIT glassSpecularChanged(); } } + qreal glassTint() const { return m_glassTint; } + void setGlassTint(qreal v) { if (m_glassTint != v) { m_glassTint = v; Q_EMIT glassTintChanged(); } } + qreal glassContentEdgePull() const { return m_glassContentEdgePull; } + void setGlassContentEdgePull(qreal v) { if (m_glassContentEdgePull != v) { m_glassContentEdgePull = v; Q_EMIT glassContentEdgePullChanged(); } } + qreal glassContentRampEnd() const { return m_glassContentRampEnd; } + void setGlassContentRampEnd(qreal v) { if (m_glassContentRampEnd != v) { m_glassContentRampEnd = v; Q_EMIT glassContentRampEndChanged(); } } + qreal glassRefractionMaxTan() const { return m_glassRefractionMaxTan; } + void setGlassRefractionMaxTan(qreal v) { if (m_glassRefractionMaxTan != v) { m_glassRefractionMaxTan = v; Q_EMIT glassRefractionMaxTanChanged(); } } + qreal glassProfilePower() const { return m_glassProfilePower; } + void setGlassProfilePower(qreal v) { if (m_glassProfilePower != v) { m_glassProfilePower = v; Q_EMIT glassProfilePowerChanged(); } } + qreal glassInnerShadow() const { return m_glassInnerShadow; } + void setGlassInnerShadow(qreal v) { if (m_glassInnerShadow != v) { m_glassInnerShadow = v; Q_EMIT glassInnerShadowChanged(); } } + qreal glassBrightness() const { return m_glassBrightness; } + void setGlassBrightness(qreal v) { if (m_glassBrightness != v) { m_glassBrightness = v; Q_EMIT glassBrightnessChanged(); } } + qreal glassContrast() const { return m_glassContrast; } + void setGlassContrast(qreal v) { if (m_glassContrast != v) { m_glassContrast = v; Q_EMIT glassContrastChanged(); } } + qreal glassSaturation() const { return m_glassSaturation; } + void setGlassSaturation(qreal v) { if (m_glassSaturation != v) { m_glassSaturation = v; Q_EMIT glassSaturationChanged(); } } + +Q_SIGNALS: + void glassEnabledChanged(); + void blurStrengthChanged(); + void blurAmountChanged(); + void blurMultiplierChanged(); + void glassBezelChanged(); + void glassThicknessChanged(); + void glassIorChanged(); + void glassSpecularChanged(); + void glassTintChanged(); + void glassContentEdgePullChanged(); + void glassContentRampEndChanged(); + void glassRefractionMaxTanChanged(); + void glassProfilePowerChanged(); + void glassInnerShadowChanged(); + void glassBrightnessChanged(); + void glassContrastChanged(); + void glassSaturationChanged(); + +private: + bool m_glassEnabled = true; + int m_blurStrength = 60; + qreal m_blurAmount = 0.6; + qreal m_blurMultiplier = 0.0; + qreal m_glassBezel = 30; + qreal m_glassThickness = 30; + qreal m_glassIor = 1.33; + qreal m_glassSpecular = 0.0; + qreal m_glassTint = 0.0; + qreal m_glassContentEdgePull = 0.0; + qreal m_glassContentRampEnd = 0.0; + qreal m_glassRefractionMaxTan = 3.3; + qreal m_glassProfilePower = 2.0; + qreal m_glassInnerShadow = 0.0; + qreal m_glassBrightness = 0.0; + qreal m_glassContrast = 0.0; + qreal m_glassSaturation = 0.0; +}; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WServer; +class WOutputRenderWindow; +class WQuickOutputLayout; +class WCursor; +class WSeat; +class WBackend; +WAYLIB_SERVER_END_NAMESPACE + +struct wlr_renderer; +struct wlr_allocator; +struct wlr_compositor; + +WAYLIB_SERVER_USE_NAMESPACE + +class Helper : public QObject +{ + Q_OBJECT + Q_PROPERTY(WQmlCreator* outputCreator MEMBER m_outputCreator CONSTANT) + Q_PROPERTY(QString wallpaperSource READ wallpaperSource WRITE setWallpaperSource NOTIFY wallpaperSourceChanged) + Q_PROPERTY(GlassConfig* config READ config CONSTANT) + QML_ELEMENT + QML_SINGLETON + +public: + explicit Helper(QObject *parent = nullptr); + + void initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine); + + QString wallpaperSource() const; + void setWallpaperSource(const QString &wallpaperSource); + GlassConfig *config() const { return m_config; } +Q_SIGNALS: + void wallpaperSourceChanged(); + +public: + inline WBackend *backend() const { + return m_backend; + } + +private: + QString m_wallpaperSource; + WServer *m_server = nullptr; + WQmlCreator *m_outputCreator = nullptr; + GlassConfig *m_config = new GlassConfig(this); + + WBackend *m_backend = nullptr; + wlr_renderer *m_renderer = nullptr; + wlr_allocator *m_allocator = nullptr; + wlr_compositor *m_compositor = nullptr; + WQuickOutputLayout *m_outputLayout = nullptr; + WCursor *m_cursor = nullptr; + QPointer m_seat; +}; diff --git a/examples/test_glass/main.cpp b/examples/test_glass/main.cpp new file mode 100644 index 0000000000..5bfa7918c7 --- /dev/null +++ b/examples/test_glass/main.cpp @@ -0,0 +1,64 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "helper.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +int main(int argc, char *argv[]) { + WLog::init(); + WServer::initializeQPA(); +// QQuickStyle::setStyle("Material"); + + QGuiApplication::setAttribute(Qt::AA_UseOpenGLES); + QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); + QGuiApplication::setQuitOnLastWindowClosed(false); + QGuiApplication app(argc, argv); + + QCommandLineParser parser; + parser.setApplicationDescription(QStringLiteral("Waylib blur and glass effect demo")); + parser.addHelpOption(); + const QCommandLineOption wallpaperOption( + { QStringLiteral("w"), QStringLiteral("wallpaper") }, + QStringLiteral("Wallpaper image path or URL."), + QStringLiteral("path")); + parser.addOption(wallpaperOption); + parser.process(app); + + QString wallpaperSource = + QStringLiteral("qrc:/qt/qml/GlassExample/assets/default-glass-background.jpg"); + const QString wallpaperOverride = parser.value(wallpaperOption); + if (!wallpaperOverride.isEmpty()) { + wallpaperSource = QUrl::fromUserInput( + wallpaperOverride, QDir::currentPath(), QUrl::AssumeLocalFile).toString(); + } + + QQmlApplicationEngine waylandEngine; + waylandEngine.loadFromModule("GlassExample", "Main"); + + Helper *helper = waylandEngine.singletonInstance("Treeland", "Helper"); + Q_ASSERT(helper); + helper->setWallpaperSource(wallpaperSource); + + auto window = waylandEngine.rootObjects().first()->findChild(); + Q_ASSERT(window); + + helper->initProtocols(window, &waylandEngine); + + return app.exec(); +} diff --git a/examples/test_hide_window/CMakeLists.txt b/examples/test_hide_window/CMakeLists.txt new file mode 100644 index 0000000000..0d8be9df2d --- /dev/null +++ b/examples/test_hide_window/CMakeLists.txt @@ -0,0 +1,15 @@ +find_package(Qt6 REQUIRED COMPONENTS Gui Widgets) + +set(BIN_NAME test-hide-window) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::Widgets +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_hide_window/main.cpp b/examples/test_hide_window/main.cpp new file mode 100644 index 0000000000..b55b872a00 --- /dev/null +++ b/examples/test_hide_window/main.cpp @@ -0,0 +1,46 @@ +// Copyright (C) 2024 groveer . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include +#include +#include + +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + MainWindow(QWidget *parent = nullptr) + : QMainWindow(parent) + { + QPushButton *button = new QPushButton("hide", this); + setCentralWidget(button); + connect(button, &QPushButton::clicked, this, &MainWindow::hideWindow); + } + +private Q_SLOTS: + + void hideWindow() + { + this->hide(); + QTimer::singleShot(3000, this, &MainWindow::showWindow); + } + + void showWindow() + { + this->show(); + } +}; + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + MainWindow window; + window.show(); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/test_idle_inhibit_v1/CMakeLists.txt b/examples/test_idle_inhibit_v1/CMakeLists.txt new file mode 100644 index 0000000000..ab7e5723ab --- /dev/null +++ b/examples/test_idle_inhibit_v1/CMakeLists.txt @@ -0,0 +1,38 @@ +set(BIN_NAME test-idle-inhibit-v1) + +find_package(Qt6 REQUIRED COMPONENTS Core Gui Widgets WaylandClient) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS GuiPrivate WaylandClientPrivate) +endif() +find_package(PkgConfig REQUIRED) +pkg_check_modules(WAYLAND_PROTOCOLS REQUIRED IMPORTED_TARGET wayland-protocols) +pkg_get_variable(WAYLAND_PROTOCOLS_DATADIR wayland-protocols pkgdatadir) + +qt_add_executable(${BIN_NAME} + main.cpp + idleclient.h + idleclient.cpp + idleinhibitv1.h + idleinhibitv1.cpp + idlenotifyv1.h + idlenotifyv1.cpp +) + +qt6_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${WAYLAND_PROTOCOLS_DATADIR}/unstable/idle-inhibit/idle-inhibit-unstable-v1.xml + ${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-idle-notify/ext-idle-notify-v1.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Core + Qt6::DBus + Qt6::Gui + Qt6::Widgets + Qt6::WaylandClient + Qt6::GuiPrivate + Qt6::WaylandClientPrivate +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_idle_inhibit_v1/idleclient.cpp b/examples/test_idle_inhibit_v1/idleclient.cpp new file mode 100644 index 0000000000..c87f2ee6df --- /dev/null +++ b/examples/test_idle_inhibit_v1/idleclient.cpp @@ -0,0 +1,242 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "idleclient.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +IdleClient::IdleClient(QObject *parent) + : QObject(parent) + , m_inhibitWindow(new QWidget()) +{ +} + +IdleClient::~IdleClient() +{ + m_inhibitWindow->deleteLater(); +} + +bool IdleClient::initialize(uint32_t idleTimeout, + uint32_t inhibitDuration, + uint32_t dbusInhibitDuration, + const QString &execCommand) +{ + m_idleTimeout = idleTimeout; + m_inhibitDuration = inhibitDuration; + m_dbusInhibitDuration = dbusInhibitDuration; + m_execCommand = execCommand; + + auto waylandApp = qGuiApp->nativeInterface(); + if (!waylandApp) { + qWarning("Not a Wayland application"); + return false; + } + + auto seat = waylandApp->seat(); + if (!seat) { + qWarning("Failed to get wl_seat from QtWayland QPA"); + return false; + } + + m_notifier.reset(new IdleNotifierV1); + m_notifier->instantiate(); + + if (!m_notifier->isInitialized()) { + qWarning("Failed to initialize IdleNotifierV1"); + return false; + } + + m_notification = m_notifier->getIdleNotification(m_idleTimeout, seat); + if (!m_notification) { + qWarning("Failed to create IdleNotificationV1"); + return false; + } + + connect(m_notification.get(), &IdleNotificationV1::idled, this, &IdleClient::onIdled); + connect(m_notification.get(), &IdleNotificationV1::resumed, this, &IdleClient::onResumed); + + if (m_inhibitDuration > 0) { + m_inhibitManager.reset(new IdleInhibitManagerV1); + m_inhibitManager->instantiate(); + + if (!m_inhibitManager->isInitialized()) { + qWarning("Failed to initialize IdleInhibitManagerV1"); + } + + m_inhibitTimer = new QTimer(this); + m_inhibitTimer->setSingleShot(true); + connect(m_inhibitTimer, &QTimer::timeout, this, &IdleClient::releaseInhibit); + + setupInhibit(); + qInfo() << "Idle inhibitor created at startup, will be released after" << m_inhibitDuration + << "ms"; + m_inhibitTimer->start(m_inhibitDuration); + } else if (m_dbusInhibitDuration > 0) { + m_inhibitTimer = new QTimer(this); + m_inhibitTimer->setSingleShot(true); + connect(m_inhibitTimer, &QTimer::timeout, this, &IdleClient::releaseDBusInhibit); + + setupDBusInhibit(); + qInfo() << "Idle inhibitor created at startup using org.freedesktop.ScreenSaver D-Bus " + "interface, will be released after" + << m_dbusInhibitDuration << "ms"; + m_inhibitTimer->start(m_dbusInhibitDuration); + } + + qInfo() << "IdleClient initialized with timeout:" << m_idleTimeout << "ms, inhibit duration:" + << (m_inhibitDuration > 0 ? m_inhibitDuration : m_dbusInhibitDuration) << "ms"; + if (!m_execCommand.isEmpty()) { + qInfo() << "Exec command on idle:" << m_execCommand; + } + return true; +} + +bool IdleClient::isValid() const +{ + return m_notifier && m_notifier->isInitialized() && m_notification; +} + +void IdleClient::onIdled() +{ + m_isIdle = true; + qInfo() << "System is now idle"; + Q_EMIT idleStateChanged(true); + + if (!m_execCommand.isEmpty()) { + executeCommand(); + } +} + +void IdleClient::onResumed() +{ + m_isIdle = false; + qInfo() << "System resumed from idle"; + Q_EMIT idleStateChanged(false); +} + +void IdleClient::setupInhibit() +{ + if (m_inhibitor) { + return; + } + + m_inhibitWindow->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus); + m_inhibitWindow->setWindowTitle("Idle Inhibitor"); + m_inhibitWindow->resize(100, 100); + + QVBoxLayout *layout = new QVBoxLayout(m_inhibitWindow); + QLabel *label = new QLabel("Idle Inhibitor", m_inhibitWindow); + label->setAlignment(Qt::AlignCenter); + layout->addWidget(label); + + m_inhibitWindow->show(); + + QMetaObject::invokeMethod( + this, + [this]() { + QWidget *widget = m_inhibitWindow; + + QWindow *window = widget->windowHandle(); + + if (!window || !window->handle()) { + qWarning() << "Window handle not available"; + return; + } + + QtWaylandClient::QWaylandWindow *waylandWindow = + static_cast(window->handle()); + struct ::wl_surface *surface = waylandWindow->wlSurface(); + + if (!surface) { + qWarning() << "Failed to get wl_surface for window"; + return; + } + + m_inhibitor = m_inhibitManager->createInhibitor(surface); + if (m_inhibitor) { + m_inhibitActive = true; + qInfo() << "Idle inhibitor created successfully (QWidget with content)"; + } else { + qWarning() << "Failed to create idle inhibitor"; + } + }, + Qt::QueuedConnection); +} + +void IdleClient::releaseInhibit() +{ + if (m_inhibitor) { + m_inhibitor.reset(); + m_inhibitActive = false; + qInfo() << "Idle inhibitor released"; + } +} + +void IdleClient::setupDBusInhibit() +{ + QDBusInterface interface("org.freedesktop.ScreenSaver", + "/org/freedesktop/ScreenSaver", + "org.freedesktop.ScreenSaver", + QDBusConnection::sessionBus()); + if (!interface.isValid()) { + qWarning() << "Failed to connect to org.freedesktop.ScreenSaver:" + << QDBusConnection::sessionBus().lastError().message(); + return; + } + QDBusReply reply = + interface.call("Inhibit", "test-idle-inhibit-v1", "Testing idle inhibit"); + if (reply.isValid()) { + m_dbusInhibitCookie = reply.value(); + qInfo() << "Inhibited successfully using org.freedesktop.ScreenSaver D-Bus interface. Cookie:" << m_dbusInhibitCookie; + } else { + qWarning() << "Failed to call Inhibit:" << reply.error().message(); + } +} + +void IdleClient::releaseDBusInhibit() +{ + if (m_dbusInhibitCookie > 0) { + QDBusInterface interface("org.freedesktop.ScreenSaver", + "/org/freedesktop/ScreenSaver", + "org.freedesktop.ScreenSaver", + QDBusConnection::sessionBus()); + if (!interface.isValid()) { + qWarning() << "Failed to connect to org.freedesktop.ScreenSaver:" + << QDBusConnection::sessionBus().lastError().message(); + return; + } + QDBusReply reply = interface.call("UnInhibit", m_dbusInhibitCookie); + if (reply.isValid()) { + qInfo() << "Idle inhibitor released using org.freedesktop.ScreenSaver D-Bus interface."; + m_dbusInhibitCookie = 0; + } else { + qWarning() << "Failed to call UnInhibit:" << reply.error().message(); + } + } +} + +void IdleClient::executeCommand() +{ + qInfo() << "Executing command:" << m_execCommand; + + QProcess *process = new QProcess(this); + connect(process, + QOverload::of(&QProcess::finished), + this, + [](int exitCode, QProcess::ExitStatus exitStatus) { + qInfo() << "Command finished with exit code:" << exitCode; + if (exitStatus == QProcess::CrashExit) { + qWarning() << "Command crashed"; + } + }); + + process->start(QStringLiteral("/bin/sh"), { QStringLiteral("-c"), m_execCommand }); +} diff --git a/examples/test_idle_inhibit_v1/idleclient.h b/examples/test_idle_inhibit_v1/idleclient.h new file mode 100644 index 0000000000..86c9faf0ab --- /dev/null +++ b/examples/test_idle_inhibit_v1/idleclient.h @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "idleinhibitv1.h" +#include "idlenotifyv1.h" + +#include + +class QWidget; +class QTimer; + +class IdleClient : public QObject +{ + Q_OBJECT +public: + explicit IdleClient(QObject *parent = nullptr); + ~IdleClient(); + + bool initialize(uint32_t idleTimeout, + uint32_t inhibitDuration, + uint32_t dbusInhibitDuration, + const QString &execCommand); + + bool isValid() const; + +Q_SIGNALS: + void idleStateChanged(bool idle); + +private Q_SLOTS: + void onIdled(); + void onResumed(); + +private: + void setupInhibit(); + void releaseInhibit(); + void setupDBusInhibit(); + void releaseDBusInhibit(); + void executeCommand(); + +private: + std::unique_ptr m_notifier; + std::unique_ptr m_notification; + std::unique_ptr m_inhibitManager; + std::unique_ptr m_inhibitor; + + uint32_t m_idleTimeout = 0; + uint32_t m_inhibitDuration = 0; + uint32_t m_dbusInhibitDuration = 0; + bool m_isIdle = false; + bool m_inhibitActive = false; + + QString m_execCommand; + QTimer *m_inhibitTimer = nullptr; + QWidget *m_inhibitWindow = nullptr; + uint32_t m_dbusInhibitCookie = 0; +}; diff --git a/examples/test_idle_inhibit_v1/idleinhibitv1.cpp b/examples/test_idle_inhibit_v1/idleinhibitv1.cpp new file mode 100644 index 0000000000..36127835a4 --- /dev/null +++ b/examples/test_idle_inhibit_v1/idleinhibitv1.cpp @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "idleinhibitv1.h" + +#define IDLE_INHIBIT_MANAGER_V1_VERSION 1 + +IdleInhibitManagerV1::IdleInhibitManagerV1() + : QWaylandClientExtensionTemplate(IDLE_INHIBIT_MANAGER_V1_VERSION) +{ +} + +IdleInhibitManagerV1::~IdleInhibitManagerV1() +{ + if (isInitialized()) { + destroy(); + } +} + +void IdleInhibitManagerV1::instantiate() +{ + initialize(); +} + +std::unique_ptr IdleInhibitManagerV1::createInhibitor(struct ::wl_surface *surface) +{ + if (!isInitialized() || !surface) { + return nullptr; + } + auto inhibitor = create_inhibitor(surface); + if (!inhibitor) { + return nullptr; + } + return std::make_unique(inhibitor); +} + +IdleInhibitorV1::IdleInhibitorV1(struct ::zwp_idle_inhibitor_v1 *id) + : QtWayland::zwp_idle_inhibitor_v1(id) +{ +} + +IdleInhibitorV1::~IdleInhibitorV1() +{ + destroy(); +} diff --git a/examples/test_idle_inhibit_v1/idleinhibitv1.h b/examples/test_idle_inhibit_v1/idleinhibitv1.h new file mode 100644 index 0000000000..922ed27d6d --- /dev/null +++ b/examples/test_idle_inhibit_v1/idleinhibitv1.h @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "qwayland-idle-inhibit-unstable-v1.h" + +#include +#include +#include + +class IdleInhibitorV1; + +class IdleInhibitManagerV1 + : public QWaylandClientExtensionTemplate + , public QtWayland::zwp_idle_inhibit_manager_v1 +{ + Q_OBJECT +public: + IdleInhibitManagerV1(); + ~IdleInhibitManagerV1(); + + void instantiate(); + + std::unique_ptr createInhibitor(struct ::wl_surface *surface); +}; + +class IdleInhibitorV1 + : public QObject + , public QtWayland::zwp_idle_inhibitor_v1 +{ + Q_OBJECT +public: + explicit IdleInhibitorV1(struct ::zwp_idle_inhibitor_v1 *id); + ~IdleInhibitorV1(); +}; diff --git a/examples/test_idle_inhibit_v1/idlenotifyv1.cpp b/examples/test_idle_inhibit_v1/idlenotifyv1.cpp new file mode 100644 index 0000000000..3f929000ab --- /dev/null +++ b/examples/test_idle_inhibit_v1/idlenotifyv1.cpp @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "idlenotifyv1.h" + +#define EXT_IDLE_NOTIFIER_V1_VERSION 1 + +IdleNotifierV1::IdleNotifierV1() + : QWaylandClientExtensionTemplate(EXT_IDLE_NOTIFIER_V1_VERSION) +{ +} + +IdleNotifierV1::~IdleNotifierV1() +{ + if (isInitialized()) { + destroy(); + } +} + +void IdleNotifierV1::instantiate() +{ + initialize(); +} + +std::unique_ptr IdleNotifierV1::getIdleNotification(uint32_t timeout, + struct ::wl_seat *seat) +{ + if (!isInitialized() || !seat) { + return nullptr; + } + auto notification = get_idle_notification(timeout, seat); + if (!notification) { + return nullptr; + } + return std::make_unique(notification); +} + +IdleNotificationV1::IdleNotificationV1(struct ::ext_idle_notification_v1 *id) + : QtWayland::ext_idle_notification_v1(id) +{ +} + +IdleNotificationV1::~IdleNotificationV1() +{ + destroy(); +} + +void IdleNotificationV1::ext_idle_notification_v1_idled() +{ + Q_EMIT idled(); +} + +void IdleNotificationV1::ext_idle_notification_v1_resumed() +{ + Q_EMIT resumed(); +} diff --git a/examples/test_idle_inhibit_v1/idlenotifyv1.h b/examples/test_idle_inhibit_v1/idlenotifyv1.h new file mode 100644 index 0000000000..78a42f1d10 --- /dev/null +++ b/examples/test_idle_inhibit_v1/idlenotifyv1.h @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "qwayland-ext-idle-notify-v1.h" + +#include +#include + +class IdleNotificationV1; + +class IdleNotifierV1 + : public QWaylandClientExtensionTemplate + , public QtWayland::ext_idle_notifier_v1 +{ + Q_OBJECT +public: + IdleNotifierV1(); + ~IdleNotifierV1(); + + void instantiate(); + + std::unique_ptr getIdleNotification(uint32_t timeout, + struct ::wl_seat *seat); +}; + +class IdleNotificationV1 + : public QObject + , public QtWayland::ext_idle_notification_v1 +{ + Q_OBJECT +public: + explicit IdleNotificationV1(struct ::ext_idle_notification_v1 *id); + ~IdleNotificationV1(); + +Q_SIGNALS: + void idled(); + void resumed(); + +protected: + void ext_idle_notification_v1_idled() override; + void ext_idle_notification_v1_resumed() override; +}; diff --git a/examples/test_idle_inhibit_v1/main.cpp b/examples/test_idle_inhibit_v1/main.cpp new file mode 100644 index 0000000000..493e8e63d7 --- /dev/null +++ b/examples/test_idle_inhibit_v1/main.cpp @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "idleclient.h" + +#include +#include +#include + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QCommandLineParser parser; + parser.setApplicationDescription("Idle client test tool"); + parser.addHelpOption(); + + QCommandLineOption idleTimeoutOption(QStringList() << "t" << "idle-timeout", + "Set idle timeout in milliseconds", + "timeout", + "3000"); + parser.addOption(idleTimeoutOption); + + QCommandLineOption inhibitDurationOption(QStringList() << "i" << "inhibit-duration", + "Set inhibit duration in milliseconds (0 to disable)", + "duration", + "0"); + parser.addOption(inhibitDurationOption); + + QCommandLineOption execOption( + QStringList() << "e" << "exec", + "Command to execute when idle (after inhibit duration if enabled)", + "command"); + parser.addOption(execOption); + + QCommandLineOption dbusInhibitDurationOption( + QStringList() << "d" << "dbus-inhibit-duration", + "Set inhibit duration in milliseconds using org.freedesktop.ScreenSaver D-Bus interface (0 to disable). Conflict with -i option.", + "duration", + "0"); + parser.addOption(dbusInhibitDurationOption); + + parser.process(app); + + uint32_t idleTimeout = parser.value(idleTimeoutOption).toUInt(); + uint32_t inhibitDuration = parser.value(inhibitDurationOption).toUInt(); + uint32_t dbusInhibitDuration = parser.value(dbusInhibitDurationOption).toUInt(); + QString execCommand = parser.value(execOption); + + IdleClient client; + if (!client.initialize(idleTimeout, inhibitDuration, dbusInhibitDuration, execCommand)) { + qCritical("Failed to initialize idle client"); + return 1; + } + + qInfo() << "Idle client started. Press Ctrl+C to exit."; + qInfo() << "Monitoring idle state with timeout:" << idleTimeout << "ms"; + if (inhibitDuration > 0) { + qInfo() << "Will inhibit idle for" << inhibitDuration << "ms when system goes idle"; + } + if (!execCommand.isEmpty()) { + qInfo() << "Will execute command on idle:" << execCommand; + } + + return app.exec(); +} diff --git a/examples/test_im_candidate_panel_tag/CMakeLists.txt b/examples/test_im_candidate_panel_tag/CMakeLists.txt new file mode 100644 index 0000000000..f3211112b2 --- /dev/null +++ b/examples/test_im_candidate_panel_tag/CMakeLists.txt @@ -0,0 +1,44 @@ +find_package(PkgConfig REQUIRED) +pkg_get_variable(WAYLAND_PROTOCOLS_DATADIR wayland-protocols pkgdatadir) +find_program(WAYLAND_SCANNER wayland-scanner REQUIRED) + +pkg_check_modules(WAYLAND_CLIENT REQUIRED wayland-client) + +set(PROTOCOL_DIR ${CMAKE_CURRENT_BINARY_DIR}) + +# Generate xdg-toplevel-tag-v1 client code +set(TAG_PROTOCOL ${WAYLAND_PROTOCOLS_DATADIR}/staging/xdg-toplevel-tag/xdg-toplevel-tag-v1.xml) +set(TAG_CLIENT_H ${PROTOCOL_DIR}/xdg-toplevel-tag-v1-client-protocol.h) +set(TAG_CLIENT_CODE ${PROTOCOL_DIR}/xdg-toplevel-tag-v1-client-protocol.c) + +add_custom_command( + OUTPUT ${TAG_CLIENT_H} ${TAG_CLIENT_CODE} + COMMAND ${WAYLAND_SCANNER} private-code < ${TAG_PROTOCOL} > ${TAG_CLIENT_CODE} + COMMAND ${WAYLAND_SCANNER} client-header < ${TAG_PROTOCOL} > ${TAG_CLIENT_H} + DEPENDS ${TAG_PROTOCOL} + COMMENT "Generating xdg-toplevel-tag-v1 protocol" + VERBATIM +) + +# Generate xdg-shell client code +set(XDG_SHELL_PROTOCOL ${WAYLAND_PROTOCOLS_DATADIR}/stable/xdg-shell/xdg-shell.xml) +set(XDG_SHELL_CLIENT_H ${PROTOCOL_DIR}/xdg-shell-client-protocol.h) +set(XDG_SHELL_CLIENT_CODE ${PROTOCOL_DIR}/xdg-shell-client-protocol.c) + +add_custom_command( + OUTPUT ${XDG_SHELL_CLIENT_H} ${XDG_SHELL_CLIENT_CODE} + COMMAND ${WAYLAND_SCANNER} private-code < ${XDG_SHELL_PROTOCOL} > ${XDG_SHELL_CLIENT_CODE} + COMMAND ${WAYLAND_SCANNER} client-header < ${XDG_SHELL_PROTOCOL} > ${XDG_SHELL_CLIENT_H} + DEPENDS ${XDG_SHELL_PROTOCOL} + COMMENT "Generating xdg-shell protocol" + VERBATIM +) + +set(BIN_NAME test-im-candidate-panel-tag) + +add_executable(${BIN_NAME} main.c ${TAG_CLIENT_CODE} ${XDG_SHELL_CLIENT_CODE}) + +target_include_directories(${BIN_NAME} PRIVATE ${PROTOCOL_DIR}) +target_link_libraries(${BIN_NAME} PRIVATE ${WAYLAND_CLIENT_LIBRARIES}) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_im_candidate_panel_tag/main.c b/examples/test_im_candidate_panel_tag/main.c new file mode 100644 index 0000000000..e74a7ed4bb --- /dev/null +++ b/examples/test_im_candidate_panel_tag/main.c @@ -0,0 +1,186 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#define _GNU_SOURCE +#include "xdg-shell-client-protocol.h" +#include "xdg-toplevel-tag-v1-client-protocol.h" + +#include + +#include +#include +#include +#include +#include +#include + +static struct wl_display *display = NULL; +static struct wl_surface *surface = NULL; +static struct xdg_surface *xdg_surface = NULL; +static struct xdg_toplevel *xdg_toplevel = NULL; +static struct wl_buffer *buffer = NULL; + +static void cleanup(void) +{ + if (buffer) + wl_buffer_destroy(buffer); + if (xdg_toplevel) + xdg_toplevel_destroy(xdg_toplevel); + if (xdg_surface) + xdg_surface_destroy(xdg_surface); + if (surface) + wl_surface_destroy(surface); + if (display) + wl_display_disconnect(display); +} + +static struct wl_compositor *compositor = NULL; +static struct xdg_wm_base *wm_base = NULL; +static struct xdg_toplevel_tag_manager_v1 *tag_manager = NULL; +static struct wl_shm *shm = NULL; + +static int create_shm_fd(int size) +{ + int fd = memfd_create("wayland-shm", MFD_CLOEXEC); + if (fd < 0) + return -1; + if (ftruncate(fd, size) < 0) { + close(fd); + return -1; + } + return fd; +} + +static struct wl_buffer *create_shm_buffer(int width, int height) +{ + int stride = width * 4; + int size = stride * height; + int fd = create_shm_fd(size); + if (fd < 0) { + fprintf(stderr, "Failed to create shm fd\n"); + return NULL; + } + + uint32_t *data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (data == MAP_FAILED) { + close(fd); + return NULL; + } + + for (int i = 0; i < width * height; i++) + data[i] = 0xFF2266AA; + + struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, size); + struct wl_buffer *buffer = + wl_shm_pool_create_buffer(pool, 0, width, height, stride, WL_SHM_FORMAT_XRGB8888); + wl_shm_pool_destroy(pool); + munmap(data, size); + close(fd); + return buffer; +} + +static void xdg_surface_configure([[maybe_unused]] void *data, + struct xdg_surface *xdg_surface, + uint32_t serial) +{ + xdg_surface_ack_configure(xdg_surface, serial); +} + +static const struct xdg_surface_listener xdg_surface_listener = { + .configure = xdg_surface_configure, +}; + +static void xdg_wm_base_ping([[maybe_unused]] void *data, + struct xdg_wm_base *xdg_wm_base, + uint32_t serial) +{ + xdg_wm_base_pong(xdg_wm_base, serial); +} + +static const struct xdg_wm_base_listener xdg_wm_base_listener = { + .ping = xdg_wm_base_ping, +}; + +static void registry_global([[maybe_unused]] void *data, + struct wl_registry *registry, + uint32_t id, + const char *interface, + uint32_t version) +{ + if (strcmp(interface, wl_compositor_interface.name) == 0) { + compositor = wl_registry_bind(registry, id, &wl_compositor_interface, version); + } else if (strcmp(interface, xdg_wm_base_interface.name) == 0) { + wm_base = wl_registry_bind(registry, id, &xdg_wm_base_interface, version); + xdg_wm_base_add_listener(wm_base, &xdg_wm_base_listener, NULL); + } else if (strcmp(interface, xdg_toplevel_tag_manager_v1_interface.name) == 0) { + tag_manager = wl_registry_bind(registry, id, &xdg_toplevel_tag_manager_v1_interface, 1); + } else if (strcmp(interface, wl_shm_interface.name) == 0) { + shm = wl_registry_bind(registry, id, &wl_shm_interface, version); + } +} + +static void registry_global_remove([[maybe_unused]] void *data, + [[maybe_unused]] struct wl_registry *registry, + [[maybe_unused]] uint32_t id) +{ +} + +static const struct wl_registry_listener registry_listener = { + .global = registry_global, + .global_remove = registry_global_remove, +}; + +int main() +{ + display = wl_display_connect(NULL); + if (!display) { + fprintf(stderr, "Failed to connect to wayland display\n"); + return 1; + } + + struct wl_registry *registry = wl_display_get_registry(display); + wl_registry_add_listener(registry, ®istry_listener, NULL); + wl_display_roundtrip(display); + + if (!compositor || !wm_base || !tag_manager || !shm) { + fprintf(stderr, "Missing required interfaces\n"); + wl_display_disconnect(display); + return 1; + } + + int width = 400, height = 100; + surface = wl_compositor_create_surface(compositor); + + xdg_surface = xdg_wm_base_get_xdg_surface(wm_base, surface); + xdg_surface_add_listener(xdg_surface, &xdg_surface_listener, NULL); + + xdg_toplevel = xdg_surface_get_toplevel(xdg_surface); + xdg_toplevel_set_title(xdg_toplevel, "IM Candidate Panel Tag Test"); + xdg_toplevel_set_app_id(xdg_toplevel, "im-candidate-panel-tag"); + + buffer = create_shm_buffer(width, height); + if (!buffer) { + fprintf(stderr, "Failed to create buffer\n"); + cleanup(); + return 1; + } + + // Set tag BEFORE the first commit + xdg_toplevel_tag_manager_v1_set_toplevel_tag(tag_manager, + xdg_toplevel, + "org.deepin.treeland.im-candidate-panel"); + fprintf(stderr, "Tag set: org.deepin.treeland.im-candidate-panel\n"); + + // First commit: initial commit without buffer, wait for configure + wl_surface_commit(surface); + wl_display_roundtrip(display); + + // Attach buffer after configure is acked + wl_surface_attach(surface, buffer, 0, 0); + wl_surface_commit(surface); + + while (wl_display_dispatch(display) != -1) { } + + cleanup(); + return 0; +} diff --git a/examples/test_im_candidate_panel_xprop/CMakeLists.txt b/examples/test_im_candidate_panel_xprop/CMakeLists.txt new file mode 100644 index 0000000000..31038bef34 --- /dev/null +++ b/examples/test_im_candidate_panel_xprop/CMakeLists.txt @@ -0,0 +1,14 @@ +find_package(Qt6 REQUIRED COMPONENTS Widgets) +find_package(PkgConfig REQUIRED) +pkg_check_modules(XCB REQUIRED xcb) + +set(BIN_NAME test-im-candidate-panel-xprop) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +target_include_directories(${BIN_NAME} PRIVATE ${XCB_INCLUDE_DIRS}) +target_link_libraries(${BIN_NAME} PRIVATE Qt6::Widgets ${XCB_LIBRARIES}) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_im_candidate_panel_xprop/main.cpp b/examples/test_im_candidate_panel_xprop/main.cpp new file mode 100644 index 0000000000..f2cbb05fd0 --- /dev/null +++ b/examples/test_im_candidate_panel_xprop/main.cpp @@ -0,0 +1,86 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include + +#include +#include +#include +#include +#include + +int main(int argc, char **argv) +{ + // Force X11 platform + qputenv("QT_QPA_PLATFORM", "xcb"); + + QApplication app(argc, argv); + + QMainWindow window; + window.setWindowTitle("IM Candidate Panel XProp Test"); + window.resize(400, 100); + + auto *label = new QLabel("example im-candidate-panel/xprop", &window); + label->setAlignment(Qt::AlignCenter); + window.setCentralWidget(label); + + // Force platform window creation before show, so we can set xprop + WId wid = window.winId(); + + // Set _DEEPIN_IM_CANDIDATE_PANEL xprop: type=CARDINAL, value=1 + xcb_connection_t *conn = xcb_connect(nullptr, nullptr); + if (xcb_connection_has_error(conn)) { + qWarning() << "Failed to connect to X server"; + return 1; + } + + xcb_intern_atom_cookie_t atom_cookie = xcb_intern_atom(conn, + 0, + strlen("_DEEPIN_IM_CANDIDATE_PANEL"), + "_DEEPIN_IM_CANDIDATE_PANEL"); + xcb_intern_atom_reply_t *atom_reply = xcb_intern_atom_reply(conn, atom_cookie, nullptr); + if (!atom_reply) { + qWarning() << "Failed to intern atom"; + xcb_disconnect(conn); + return 1; + } + xcb_atom_t atom = atom_reply->atom; + + xcb_intern_atom_cookie_t cardinal_cookie = + xcb_intern_atom(conn, 0, strlen("CARDINAL"), "CARDINAL"); + xcb_intern_atom_reply_t *cardinal_reply = xcb_intern_atom_reply(conn, cardinal_cookie, nullptr); + if (!cardinal_reply) { + qWarning() << "Failed to intern CARDINAL atom"; + free(atom_reply); + xcb_disconnect(conn); + return 1; + } + xcb_atom_t cardinal = cardinal_reply->atom; + + uint32_t value = 1; + xcb_void_cookie_t change_cookie = xcb_change_property_checked(conn, + XCB_PROP_MODE_REPLACE, + wid, + atom, + cardinal, + 32, + 1, + &value); + xcb_flush(conn); + + xcb_generic_error_t *error = xcb_request_check(conn, change_cookie); + if (error) { + qWarning() << "xcb_change_property failed: error_code=" << error->error_code; + free(error); + } else { + qDebug() << "Set _DEEPIN_IM_CANDIDATE_PANEL=1 on window" << wid; + } + + free(cardinal_reply); + free(atom_reply); + xcb_disconnect(conn); + + window.show(); + + return app.exec(); +} diff --git a/examples/test_input_manager/CMakeLists.txt b/examples/test_input_manager/CMakeLists.txt new file mode 100644 index 0000000000..352aeca9c6 --- /dev/null +++ b/examples/test_input_manager/CMakeLists.txt @@ -0,0 +1,29 @@ +find_package(Qt6 COMPONENTS REQUIRED Gui WaylandClient) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 COMPONENTS GuiPrivate WaylandClientPrivate REQUIRED) +endif() + +find_package(TreelandProtocols REQUIRED) + +set(BIN_NAME test-input-manager) + +qt_add_executable(${BIN_NAME} + main.cpp + inputmanagerclient.h + inputmanagerclient.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-input-manager-unstable-v1.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::GuiPrivate + Qt6::WaylandClient + Qt6::WaylandClientPrivate +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_input_manager/inputmanagerclient.cpp b/examples/test_input_manager/inputmanagerclient.cpp new file mode 100644 index 0000000000..78ed1f74ac --- /dev/null +++ b/examples/test_input_manager/inputmanagerclient.cpp @@ -0,0 +1,287 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "inputmanagerclient.h" + +#include +#include + +TreelandInputManagerV1::TreelandInputManagerV1() + : QWaylandClientExtensionTemplate(InterfaceVersion) + , QtWayland::treeland_input_manager_v1() +{ +} + +TreelandInputManagerV1::~TreelandInputManagerV1() +{ + if (isInitialized()) + destroy(); +} + +void TreelandInputManagerV1::instantiate() +{ + initialize(); +} + +void TreelandInputManagerV1::treeland_input_manager_v1_capability_available(uint32_t type, struct ::wl_seat *seat) +{ + m_seat = seat; + m_capabilities |= type; + + QStringList devices; + if (type & device_type_mouse) + devices << "mouse"; + if (type & device_type_touchpad) + devices << "touchpad"; + if (type & device_type_keyboard) + devices << "keyboard"; + + qWarning() << "capability available (0x" << Qt::hex << type << Qt::dec << "):" + << (devices.isEmpty() ? "(none)" : devices.join(", ")); +} + +void TreelandInputManagerV1::treeland_input_manager_v1_capability_unavailable(uint32_t type, struct ::wl_seat *seat) +{ + Q_UNUSED(seat); + m_capabilities &= ~type; + + QStringList devices; + if (type & device_type_mouse) + devices << "mouse"; + if (type & device_type_touchpad) + devices << "touchpad"; + if (type & device_type_keyboard) + devices << "keyboard"; + + qWarning() << "capability unavailable (0x" << Qt::hex << type << Qt::dec << "):" + << (devices.isEmpty() ? "(none)" : devices.join(", ")); +} + +bool TreelandInputManagerV1::hasMouse() const +{ + return (m_capabilities & device_type_mouse) != 0; +} + +bool TreelandInputManagerV1::hasTouchpad() const +{ + return (m_capabilities & device_type_touchpad) != 0; +} + +bool TreelandInputManagerV1::hasKeyboard() const +{ + return (m_capabilities & device_type_keyboard) != 0; +} + +struct ::wl_seat *TreelandInputManagerV1::seat() const +{ + return m_seat; +} + +TreelandPointerDeviceConfigurationV1::TreelandPointerDeviceConfigurationV1( + struct ::treeland_pointer_device_configuration_v1 *object, + DeviceType type) + : QtWayland::treeland_pointer_device_configuration_v1(object) + , m_deviceType(type) +{ +} + +TreelandPointerDeviceConfigurationV1::~TreelandPointerDeviceConfigurationV1() +{ + destroy(); +} + +bool TreelandPointerDeviceConfigurationV1::hasFeature(uint32_t flag) const +{ + return (m_features & flag) != 0; +} + +void TreelandPointerDeviceConfigurationV1::treeland_pointer_device_configuration_v1_feature(uint32_t feature) +{ + m_features = feature; + + QStringList flags; + if (feature & feature_scroll_factor) + flags << "scroll_factor"; + if (feature & feature_handed_mode) + flags << "handed_mode"; + if (feature & feature_accel_speed) + flags << "accel_speed"; + if (feature & feature_acceleration_profile) + flags << "acceleration_profile"; + if (feature & feature_send_events_mode) + flags << "send_events_mode"; + if (feature & feature_natural_scroll) + flags << "natural_scroll"; + if (feature & feature_disable_while_typing) + flags << "disable_while_typing"; + if (feature & feature_tap_to_click) + flags << "tap_to_click"; + + const char *deviceName = (m_deviceType == DeviceType::Mouse) ? "mouse" : "touchpad"; + qWarning() << deviceName << "supported features (0x" << Qt::hex << feature << Qt::dec << "):" << (flags.isEmpty() ? "(none)" : flags.join(", ")); +} + +void TreelandPointerDeviceConfigurationV1::treeland_pointer_device_configuration_v1_scroll_factor(wl_fixed_t factor) +{ + qWarning() << "scroll_factor:" << wl_fixed_to_double(factor); +} + +void TreelandPointerDeviceConfigurationV1::treeland_pointer_device_configuration_v1_handed_mode(uint32_t mode) +{ + if (mode == handed_mode_right) + qWarning() << "handed_mode: right"; + else if (mode == handed_mode_left) + qWarning() << "handed_mode: left"; + else + qWarning() << "handed_mode: unknown(" << mode << ")"; +} + +void TreelandPointerDeviceConfigurationV1::treeland_pointer_device_configuration_v1_accel_speed(wl_fixed_t accel_speed) +{ + qWarning() << "accel_speed:" << wl_fixed_to_double(accel_speed); +} + +void TreelandPointerDeviceConfigurationV1::treeland_pointer_device_configuration_v1_acceleration_profile(uint32_t profile) +{ + QStringList profiles; + switch (profile) { + case acceleration_profile_none: + profiles << "none"; + break; + case acceleration_profile_flat: + profiles << "flat"; + break; + case acceleration_profile_adaptive: + profiles << "adaptive"; + break; + case acceleration_profile_custom: + profiles << "custom"; + break; + default: + break; + } + + qWarning() << "acceleration_profile (0x" << Qt::hex << profile << Qt::dec << "):" << (profiles.isEmpty() ? "(none)" : profiles.join("|")); +} + +void TreelandPointerDeviceConfigurationV1::treeland_pointer_device_configuration_v1_send_events_mode(uint32_t mode) +{ + if (mode == send_events_mode_enabled) + qWarning() << "send_events_mode: enabled"; + else if (mode == send_events_mode_disabled) + qWarning() << "send_events_mode: disabled"; + else if (mode == send_events_mode_disabled_on_external_mouse) + qWarning() << "send_events_mode: disabled_on_external_mouse"; + else + qWarning() << "send_events_mode: unknown(" << mode << ")"; +} + +void TreelandPointerDeviceConfigurationV1::treeland_pointer_device_configuration_v1_natural_scroll(uint32_t state) +{ + qWarning() << "natural_scroll:" << (state ? "enabled" : "disabled"); +} + +void TreelandPointerDeviceConfigurationV1::treeland_pointer_device_configuration_v1_disable_while_typing(uint32_t state) +{ + qWarning() << "disable_while_typing:" << (state ? "enabled" : "disabled"); +} + +void TreelandPointerDeviceConfigurationV1::treeland_pointer_device_configuration_v1_tap_to_click(uint32_t state) +{ + qWarning() << "tap_to_click:" << (state ? "enabled" : "disabled"); +} + +void TreelandPointerDeviceConfigurationV1::treeland_pointer_device_configuration_v1_failed() +{ + qWarning() << "pointer device configuration: apply failed"; +} + +void TreelandPointerDeviceConfigurationV1::treeland_pointer_device_configuration_v1_done(uint32_t serial) +{ + const char *deviceName = (m_deviceType == DeviceType::Mouse) ? "mouse" : "touchpad"; + qWarning() << deviceName << "done, serial:" << serial; + qWarning() << ""; +} + +TreelandKeyboardSettingsV1::TreelandKeyboardSettingsV1( + struct ::treeland_keyboard_settings_v1 *object) + : QtWayland::treeland_keyboard_settings_v1(object) +{ +} + +TreelandKeyboardSettingsV1::~TreelandKeyboardSettingsV1() +{ + destroy(); +} + +bool TreelandKeyboardSettingsV1::hasFeature(uint32_t flag) const +{ + return (m_features & flag) != 0; +} + +void TreelandKeyboardSettingsV1::treeland_keyboard_settings_v1_feature(uint32_t feature) +{ + m_features = feature; + + QStringList flags; + if (feature & feature_num_lock) + flags << "num_lock"; + + qWarning() << "keyboard supported features (0x" << Qt::hex << feature << Qt::dec << "):" << (flags.isEmpty() ? "(none)" : flags.join(", ")); +} + +void TreelandKeyboardSettingsV1::configureAndApply(int32_t rate, int32_t delay) +{ + set_repeat(rate, delay); + apply(); + qWarning() << "Keyboard configuration applied, rate:" << rate + << "delay:" << delay; +} + +void TreelandKeyboardSettingsV1::configureXkbRulesAndApply(const QString &layout, + const QString &model, + const QString &variant, + const QString &options) +{ + set_xkb_rules(layout, model, variant, options); + apply(); + qWarning() << "Keyboard XKB rules applied:" + << "layout:" << layout + << "model:" << model + << "variant:" << variant + << "options:" << options; +} + +void TreelandKeyboardSettingsV1::treeland_keyboard_settings_v1_repeat(int32_t rate, int32_t delay) +{ + qWarning() << "repeat rate:" << rate << "delay:" << delay; +} + +void TreelandKeyboardSettingsV1::treeland_keyboard_settings_v1_num_lock(uint32_t state) +{ + qWarning() << "num_lock:" << (state ? "on" : "off"); +} + +void TreelandKeyboardSettingsV1::treeland_keyboard_settings_v1_failed() +{ + qWarning() << "keyboard settings: apply failed"; +} + +void TreelandKeyboardSettingsV1::treeland_keyboard_settings_v1_done() +{ + qWarning() << "keyboard settings: done"; + qWarning() << ""; +} + +void TreelandKeyboardSettingsV1::treeland_keyboard_settings_v1_xkb_rules( + const QString &layout, + const QString &model, + const QString &variant, + const QString &options) +{ + qWarning() << "xkb_rules:" + << "layout:" << layout + << "model:" << model + << "variant:" << variant + << "options:" << options; +} diff --git a/examples/test_input_manager/inputmanagerclient.h b/examples/test_input_manager/inputmanagerclient.h new file mode 100644 index 0000000000..2030a1c640 --- /dev/null +++ b/examples/test_input_manager/inputmanagerclient.h @@ -0,0 +1,96 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "qwayland-treeland-input-manager-unstable-v1.h" + +#include + +class QCommandLineParser; + +class TreelandInputManagerV1 + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_input_manager_v1 +{ + Q_OBJECT +public: + static constexpr int InterfaceVersion = 2; + explicit TreelandInputManagerV1(); + ~TreelandInputManagerV1() override; + + void instantiate(); + + bool hasMouse() const; + bool hasTouchpad() const; + bool hasKeyboard() const; + struct ::wl_seat *seat() const; + +protected: + void treeland_input_manager_v1_capability_available(uint32_t type, struct ::wl_seat *seat) override; + void treeland_input_manager_v1_capability_unavailable(uint32_t type, struct ::wl_seat *seat) override; + +private: + struct ::wl_seat *m_seat = nullptr; + uint32_t m_capabilities = 0; +}; + +class TreelandPointerDeviceConfigurationV1 + : public QtWayland::treeland_pointer_device_configuration_v1 +{ +public: + enum class DeviceType { Mouse, Touchpad }; + + explicit TreelandPointerDeviceConfigurationV1( + struct ::treeland_pointer_device_configuration_v1 *object, + DeviceType type); + ~TreelandPointerDeviceConfigurationV1() override; + + bool hasFeature(uint32_t flag) const; + +protected: + void treeland_pointer_device_configuration_v1_feature(uint32_t feature) override; + void treeland_pointer_device_configuration_v1_scroll_factor(wl_fixed_t factor) override; + void treeland_pointer_device_configuration_v1_handed_mode(uint32_t mode) override; + void treeland_pointer_device_configuration_v1_accel_speed(wl_fixed_t accel_speed) override; + void treeland_pointer_device_configuration_v1_acceleration_profile(uint32_t profile) override; + void treeland_pointer_device_configuration_v1_send_events_mode(uint32_t mode) override; + void treeland_pointer_device_configuration_v1_natural_scroll(uint32_t state) override; + void treeland_pointer_device_configuration_v1_disable_while_typing(uint32_t state) override; + void treeland_pointer_device_configuration_v1_tap_to_click(uint32_t state) override; + void treeland_pointer_device_configuration_v1_failed() override; + void treeland_pointer_device_configuration_v1_done(uint32_t serial) override; + +private: + DeviceType m_deviceType; + uint32_t m_features = 0; +}; + +class TreelandKeyboardSettingsV1 + : public QtWayland::treeland_keyboard_settings_v1 +{ +public: + explicit TreelandKeyboardSettingsV1(struct ::treeland_keyboard_settings_v1 *object); + ~TreelandKeyboardSettingsV1() override; + + bool hasFeature(uint32_t flag) const; + void configureAndApply(int32_t rate, int32_t delay); + void configureXkbRulesAndApply(const QString &layout, + const QString &model, + const QString &variant, + const QString &options); + +protected: + void treeland_keyboard_settings_v1_feature(uint32_t feature) override; + void treeland_keyboard_settings_v1_repeat(int32_t rate, int32_t delay) override; + void treeland_keyboard_settings_v1_num_lock(uint32_t state) override; + void treeland_keyboard_settings_v1_failed() override; + void treeland_keyboard_settings_v1_done() override; + void treeland_keyboard_settings_v1_xkb_rules(const QString &layout, + const QString &model, + const QString &variant, + const QString &options) override; + +private: + uint32_t m_features = 0; +}; diff --git a/examples/test_input_manager/main.cpp b/examples/test_input_manager/main.cpp new file mode 100644 index 0000000000..d0f231caf8 --- /dev/null +++ b/examples/test_input_manager/main.cpp @@ -0,0 +1,384 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "inputmanagerclient.h" + +#include +#include +#include + +#include +#include +#include + +using Manager = QtWayland::treeland_input_manager_v1; +using PointerConfig = QtWayland::treeland_pointer_device_configuration_v1; + +static void roundtrip() { + auto *integration = + static_cast( + QGuiApplicationPrivate::platformIntegration()); + wl_display_dispatch(integration->display()->wl_display()); + wl_display_roundtrip(integration->display()->wl_display()); +} + +static void configureMouseSettings(QtWayland::treeland_mouse_settings_v1 *mouseSettings, + const QCommandLineParser &parser) +{ + auto *rawConfig = mouseSettings->get_pointer_configuration(0); + if (!rawConfig) { + qWarning() << "Failed to get pointer configuration for mouse"; + return; + } + + auto *config = new TreelandPointerDeviceConfigurationV1(rawConfig, TreelandPointerDeviceConfigurationV1::DeviceType::Mouse); + roundtrip(); + bool anySet = false; + + if (parser.isSet("mouse-scroll-factor") && config->hasFeature(PointerConfig::feature_scroll_factor)) { + bool ok = false; + double factor = parser.value("mouse-scroll-factor").toDouble(&ok); + if (ok) { + config->set_scroll_factor(wl_fixed_from_double(factor)); + anySet = true; + } + } + if (parser.isSet("mouse-accel-speed") && config->hasFeature(PointerConfig::feature_accel_speed)) { + bool ok = false; + double speed = parser.value("mouse-accel-speed").toDouble(&ok); + if (ok) { + config->set_accel_speed(wl_fixed_from_double(speed)); + anySet = true; + } + } + if (parser.isSet("mouse-accel-profile") && config->hasFeature(PointerConfig::feature_acceleration_profile)) { + auto profileStr = parser.value("mouse-accel-profile"); + uint32_t profile = PointerConfig::acceleration_profile_adaptive; + if (profileStr == "none") + profile = PointerConfig::acceleration_profile_none; + else if (profileStr == "flat") + profile = PointerConfig::acceleration_profile_flat; + else if (profileStr == "custom") + profile = PointerConfig::acceleration_profile_custom; + config->set_acceleration_profile(profile); + anySet = true; + } + if (parser.isSet("mouse-handed-mode") && config->hasFeature(PointerConfig::feature_handed_mode)) { + auto modeStr = parser.value("mouse-handed-mode"); + uint32_t mode = TreelandPointerDeviceConfigurationV1::handed_mode::handed_mode_right; + if (modeStr == "left") + mode = TreelandPointerDeviceConfigurationV1::handed_mode::handed_mode_left; + config->set_handed_mode(mode); + anySet = true; + } + if (parser.isSet("mouse-natural-scroll") && config->hasFeature(PointerConfig::feature_natural_scroll)) { + uint32_t state = parser.value("mouse-natural-scroll") == "disabled" + ? Manager::state_disabled : Manager::state_enabled; + config->set_natural_scroll(state); + anySet = true; + } + + if (anySet) { + config->apply(); + qDebug() << "Mouse configuration applied"; + } +} + +static void configureTouchpadSettings(QtWayland::treeland_touchpad_settings_v1 *touchpadSettings, + const QCommandLineParser &parser) +{ + auto *rawConfig = touchpadSettings->get_pointer_configuration(0); + if (!rawConfig) { + qWarning() << "Failed to get pointer configuration for touchpad"; + return; + } + + auto *config = new TreelandPointerDeviceConfigurationV1(rawConfig, TreelandPointerDeviceConfigurationV1::DeviceType::Touchpad); + roundtrip(); + bool anySet = false; + + if (parser.isSet("touchpad-accel-speed") && config->hasFeature(PointerConfig::feature_accel_speed)) { + bool ok = false; + double speed = parser.value("touchpad-accel-speed").toDouble(&ok); + if (ok) { + config->set_accel_speed(wl_fixed_from_double(speed)); + anySet = true; + } + } + if (parser.isSet("touchpad-accel-profile") && config->hasFeature(PointerConfig::feature_acceleration_profile)) { + auto profileStr = parser.value("touchpad-accel-profile"); + uint32_t profile = PointerConfig::acceleration_profile_adaptive; + if (profileStr == "none") + profile = PointerConfig::acceleration_profile_none; + else if (profileStr == "flat") + profile = PointerConfig::acceleration_profile_flat; + else if (profileStr == "custom") + profile = PointerConfig::acceleration_profile_custom; + config->set_acceleration_profile(profile); + anySet = true; + } + if (parser.isSet("touchpad-send-events-mode") && config->hasFeature(PointerConfig::feature_send_events_mode)) { + auto modeStr = parser.value("touchpad-send-events-mode"); + uint32_t mode = PointerConfig::send_events_mode_enabled; + if (modeStr == "disabled") + mode = PointerConfig::send_events_mode_disabled; + else if (modeStr == "disabled-on-external-mouse") + mode = PointerConfig::send_events_mode_disabled_on_external_mouse; + config->set_send_events_mode(mode); + anySet = true; + } + if (parser.isSet("touchpad-natural-scroll") && config->hasFeature(PointerConfig::feature_natural_scroll)) { + uint32_t state = parser.value("touchpad-natural-scroll") == "disabled" + ? Manager::state_disabled : Manager::state_enabled; + config->set_natural_scroll(state); + anySet = true; + } + if (parser.isSet("touchpad-disable-while-typing") && config->hasFeature(PointerConfig::feature_disable_while_typing)) { + uint32_t state = parser.value("touchpad-disable-while-typing") == "disabled" + ? Manager::state_disabled : Manager::state_enabled; + config->set_disable_while_typing(state); + anySet = true; + } + if (parser.isSet("touchpad-tap-to-click") && config->hasFeature(PointerConfig::feature_tap_to_click)) { + uint32_t state = parser.value("touchpad-tap-to-click") == "disabled" + ? Manager::state_disabled : Manager::state_enabled; + config->set_tap_to_click(state); + anySet = true; + } + + if (anySet) { + config->apply(); + qDebug() << "Touchpad configuration applied"; + } +} + +int main(int argc, char *argv[]) +{ + if (qEnvironmentVariableIsEmpty("QT_QPA_PLATFORM")) + qputenv("QT_QPA_PLATFORM", "wayland"); + + QGuiApplication app(argc, argv); + + QCommandLineParser parser; + parser.setApplicationDescription(QStringLiteral("Treeland Input Manager Client")); + parser.addHelpOption(); + + // Mouse options + QCommandLineOption mouseScrollFactorOption( + QStringLiteral("mouse-scroll-factor"), + QStringLiteral("Mouse scroll factor (e.g. 1.0)."), + QStringLiteral("factor") + ); + parser.addOption(mouseScrollFactorOption); + + QCommandLineOption mouseAccelSpeedOption( + QStringLiteral("mouse-accel-speed"), + QStringLiteral("Mouse acceleration speed (e.g. 0.0)."), + QStringLiteral("speed") + ); + parser.addOption(mouseAccelSpeedOption); + + QCommandLineOption mouseAccelProfileOption( + QStringLiteral("mouse-accel-profile"), + QStringLiteral("Mouse acceleration profile: none | flat | adaptive | custom."), + QStringLiteral("profile") + ); + parser.addOption(mouseAccelProfileOption); + + QCommandLineOption mouseNaturalScrollOption( + QStringLiteral("mouse-natural-scroll"), + QStringLiteral("Mouse natural scrolling: enabled | disabled."), + QStringLiteral("state") + ); + parser.addOption(mouseNaturalScrollOption); + + QCommandLineOption mouseHandedModeOption( + QStringLiteral("mouse-handed-mode"), + QStringLiteral("Mouse handed mode: left | right."), + QStringLiteral("mode") + ); + parser.addOption(mouseHandedModeOption); + + // Touchpad options + QCommandLineOption touchpadAccelSpeedOption( + QStringLiteral("touchpad-accel-speed"), + QStringLiteral("Touchpad acceleration speed (e.g. 0.0)."), + QStringLiteral("speed") + ); + parser.addOption(touchpadAccelSpeedOption); + + QCommandLineOption touchpadAccelProfileOption( + QStringLiteral("touchpad-accel-profile"), + QStringLiteral("Touchpad acceleration profile: none | flat | adaptive | custom."), + QStringLiteral("profile") + ); + parser.addOption(touchpadAccelProfileOption); + + QCommandLineOption touchpadNaturalScrollOption( + QStringLiteral("touchpad-natural-scroll"), + QStringLiteral("Touchpad natural scrolling: enabled | disabled."), + QStringLiteral("state") + ); + parser.addOption(touchpadNaturalScrollOption); + + QCommandLineOption touchpadDisableWhileTypingOption( + QStringLiteral("touchpad-disable-while-typing"), + QStringLiteral("Touchpad disable-while-typing: enabled | disabled."), + QStringLiteral("state") + ); + parser.addOption(touchpadDisableWhileTypingOption); + + QCommandLineOption touchpadTapToClickOption( + QStringLiteral("touchpad-tap-to-click"), + QStringLiteral("Touchpad tap-to-click: enabled | disabled."), + QStringLiteral("state") + ); + parser.addOption(touchpadTapToClickOption); + + QCommandLineOption touchpadSendEventsModeOption( + QStringLiteral("touchpad-send-events-mode"), + QStringLiteral("Touchpad send events mode: enabled | disabled | disabled-on-external-mouse."), + QStringLiteral("mode") + ); + parser.addOption(touchpadSendEventsModeOption); + + // Keyboard options + QCommandLineOption keyboardRepeatRateOption( + QStringLiteral("keyboard-repeat-rate"), + QStringLiteral("Keyboard repeat rate in characters per second (e.g. 25)."), + QStringLiteral("rate") + ); + parser.addOption(keyboardRepeatRateOption); + + QCommandLineOption keyboardRepeatDelayOption( + QStringLiteral("keyboard-repeat-delay"), + QStringLiteral("Keyboard repeat delay in milliseconds (e.g. 300)."), + QStringLiteral("delay") + ); + parser.addOption(keyboardRepeatDelayOption); + + QCommandLineOption keyboardNumLockOption( + QStringLiteral("keyboard-num-lock"), + QStringLiteral("Keyboard num lock state: enabled | disabled."), + QStringLiteral("state") + ); + parser.addOption(keyboardNumLockOption); + + QCommandLineOption keyboardXkbLayoutOption( + QStringLiteral("keyboard-xkb-layout"), + QStringLiteral("Comma-separated XKB keyboard layouts (e.g. us or cz,us)."), + QStringLiteral("layout") + ); + parser.addOption(keyboardXkbLayoutOption); + + QCommandLineOption keyboardXkbModelOption( + QStringLiteral("keyboard-xkb-model"), + QStringLiteral("XKB keyboard model (e.g. pc104 or pc105)."), + QStringLiteral("model") + ); + parser.addOption(keyboardXkbModelOption); + + QCommandLineOption keyboardXkbVariantOption( + QStringLiteral("keyboard-xkb-variant"), + QStringLiteral("Comma-separated XKB keyboard variants (e.g. ,dvorak)."), + QStringLiteral("variant") + ); + parser.addOption(keyboardXkbVariantOption); + + QCommandLineOption keyboardXkbOptionsOption( + QStringLiteral("keyboard-xkb-options"), + QStringLiteral("Comma-separated XKB keyboard options (e.g. grp:win_space_toggle)."), + QStringLiteral("options") + ); + parser.addOption(keyboardXkbOptionsOption); + + parser.process(app); + + auto *manager = new TreelandInputManagerV1; + + manager->instantiate(); + roundtrip(); + + if (!manager->isActive()) { + qCritical() << "treeland_input_manager_v1 not available"; + return EXIT_FAILURE; + } + + auto *seat = manager->seat(); + if (!seat) { + qCritical() << "No seat received from capability events"; + return EXIT_FAILURE; + } + + qWarning() << "Available capabilities:" + << "mouse:" << manager->hasMouse() + << "touchpad:" << manager->hasTouchpad() + << "keyboard:" << manager->hasKeyboard(); + + if (manager->hasMouse()) { + auto *mouseObj = manager->get_mouse_settings(seat); + if (mouseObj) { + auto *mouseSettings = new QtWayland::treeland_mouse_settings_v1(mouseObj); + configureMouseSettings(mouseSettings, parser); + } else { + qWarning() << "Failed to get mouse settings"; + } + } else { + qWarning() << "No mouse capability, skipping mouse settings"; + } + + if (manager->hasTouchpad()) { + auto *touchpadObj = manager->get_touchpad_settings(seat); + if (touchpadObj) { + auto *touchpadSettings = new QtWayland::treeland_touchpad_settings_v1(touchpadObj); + configureTouchpadSettings(touchpadSettings, parser); + } else { + qWarning() << "Failed to get touchpad settings"; + } + } else { + qWarning() << "No touchpad capability, skipping touchpad settings"; + } + + if (manager->hasKeyboard()) { + auto *keyboardObj = manager->get_keyboard_settings(seat); + if (keyboardObj) { + auto *keyboardSettings = new TreelandKeyboardSettingsV1(keyboardObj); + roundtrip(); + + if (parser.isSet("keyboard-repeat-rate") || parser.isSet("keyboard-repeat-delay")) { + int32_t rate = parser.isSet("keyboard-repeat-rate") + ? parser.value("keyboard-repeat-rate").toInt() : 25; + int32_t delay = parser.isSet("keyboard-repeat-delay") + ? parser.value("keyboard-repeat-delay").toInt() : 300; + + keyboardSettings->configureAndApply(rate, delay); + } + + if (parser.isSet("keyboard-num-lock") && keyboardSettings->hasFeature(QtWayland::treeland_keyboard_settings_v1::feature_num_lock)) { + uint32_t state = parser.value("keyboard-num-lock") == "disabled" + ? QtWayland::treeland_keyboard_settings_v1::toggle_state_off + : QtWayland::treeland_keyboard_settings_v1::toggle_state_on; + keyboardSettings->set_num_lock(state); + keyboardSettings->apply(); + qDebug() << "Keyboard num lock applied:" << (state ? "on" : "off"); + } + + if (parser.isSet("keyboard-xkb-layout") + || parser.isSet("keyboard-xkb-model") + || parser.isSet("keyboard-xkb-variant") + || parser.isSet("keyboard-xkb-options")) { + keyboardSettings->configureXkbRulesAndApply( + parser.value("keyboard-xkb-layout"), + parser.value("keyboard-xkb-model"), + parser.value("keyboard-xkb-variant"), + parser.value("keyboard-xkb-options")); + } + } else { + qWarning() << "Failed to get keyboard settings"; + } + } else { + qWarning() << "No keyboard capability, skipping keyboard settings"; + } + + return app.exec(); +} diff --git a/examples/test_keyboard_state_notify/CMakeLists.txt b/examples/test_keyboard_state_notify/CMakeLists.txt new file mode 100644 index 0000000000..df5f14093f --- /dev/null +++ b/examples/test_keyboard_state_notify/CMakeLists.txt @@ -0,0 +1,21 @@ +find_package(Qt6 REQUIRED COMPONENTS Gui WaylandClient) +find_package(TreelandProtocols REQUIRED) + +set(BIN_NAME test-keyboard-state-notify) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-keyboard-state-notify-unstable-v1.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::WaylandClient +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_keyboard_state_notify/main.cpp b/examples/test_keyboard_state_notify/main.cpp new file mode 100644 index 0000000000..66f8f2e54d --- /dev/null +++ b/examples/test_keyboard_state_notify/main.cpp @@ -0,0 +1,210 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// Test application for treeland_keyboard_state_notify_manager_v1 +// (treeland-keyboard-state-notify-unstable-v1). +// Creates a keyboard state watcher that monitors specified lock modifiers and prints +// their state transitions (locked/unlocked) to the console. +// +// Usage: test-key-notify --modifier [,...] [--watch locked|unlocked|all] +// e.g. test-key-notify --modifier caps_lock,num_lock --watch locked +// test-key-notify --modifier caps_lock --modifier num_lock,scroll_lock --watch all + +#include "qwayland-treeland-keyboard-state-notify-unstable-v1.h" + +#include +#include +#include +#include + +static QString modifierName(uint32_t modifier) +{ + if (modifier == QtWayland::treeland_keyboard_state_watcher_v1::modifier_caps_lock) + return QStringLiteral("Caps Lock"); + if (modifier == QtWayland::treeland_keyboard_state_watcher_v1::modifier_num_lock) + return QStringLiteral("Num Lock"); + return QStringLiteral("Unknown(0x") + QString::number(modifier, 16) + ')'; +} + +class KeyboardStateWatcher + : public QObject + , public QtWayland::treeland_keyboard_state_watcher_v1 +{ + Q_OBJECT +public: + explicit KeyboardStateWatcher(struct ::treeland_keyboard_state_watcher_v1 *watcher, + QObject *parent = nullptr) + : QObject(parent) + , QtWayland::treeland_keyboard_state_watcher_v1(watcher) + { + } + + ~KeyboardStateWatcher() override + { + destroy(); + } + +Q_SIGNALS: + void modifierLocked(uint32_t modifier); + void modifierUnlocked(uint32_t modifier); + +protected: + void treeland_keyboard_state_watcher_v1_current_state(uint32_t modifier, uint32_t state) override + { + if (state == QtWayland::treeland_keyboard_state_watcher_v1::modifier_state_locked) { + qWarning() << "current_state: [Locked]" << modifierName(modifier); + return; + } + else if (state == QtWayland::treeland_keyboard_state_watcher_v1::modifier_state_unlocked) { + qWarning() << "current_state: [Unlocked]" << modifierName(modifier); + } + } + + void treeland_keyboard_state_watcher_v1_state_changed(uint32_t modifier, uint32_t state) override + { + if (state == QtWayland::treeland_keyboard_state_watcher_v1::modifier_state_locked) { + qWarning() << "state_changed: [Locked]" << modifierName(modifier); + return; + } + else if (state == QtWayland::treeland_keyboard_state_watcher_v1::modifier_state_unlocked) { + qWarning() << "state_changed: [Unlocked]" << modifierName(modifier); + } + } +}; + +class KeyboardStateNotifyManagerV1 + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_keyboard_state_notify_manager_v1 +{ + Q_OBJECT +public: + static constexpr int InterfaceVersion = 1; + + explicit KeyboardStateNotifyManagerV1() + : QWaylandClientExtensionTemplate(InterfaceVersion) + { + } + + KeyboardStateWatcher *createWatcher(struct ::wl_seat *seat = nullptr, + QObject *parent = nullptr) + { + auto *raw = get_keyboard_state_watcher(seat); + if (!raw) + return nullptr; + return new KeyboardStateWatcher(raw, parent); + } +}; + +static bool parseModifier(const QString &name, uint32_t &out) +{ + if (name.compare(QLatin1String("caps_lock"), Qt::CaseInsensitive) == 0) { + out = QtWayland::treeland_keyboard_state_watcher_v1::modifier_caps_lock; + return true; + } + if (name.compare(QLatin1String("num_lock"), Qt::CaseInsensitive) == 0) { + out = QtWayland::treeland_keyboard_state_watcher_v1::modifier_num_lock; + return true; + } + return false; +} + +int main(int argc, char *argv[]) +{ + qputenv("QT_QPA_PLATFORM", "wayland"); + QGuiApplication app(argc, argv); + + QCommandLineParser parser; + parser.setApplicationDescription(QStringLiteral("Treeland Keyboard State Notify Test Client")); + parser.addHelpOption(); + + QCommandLineOption modifierOption( + QStringLiteral("modifier"), + QStringLiteral("Lock modifier to watch: caps_lock,num_lock. Can be repeated."), + QStringLiteral("modifier-name")); + parser.addOption(modifierOption); + + QCommandLineOption watchOption( + QStringLiteral("watch"), + QStringLiteral("Which transitions to watch: locked, unlocked, or all (default: all)."), + QStringLiteral("mode"), + QStringLiteral("all")); + parser.addOption(watchOption); + parser.process(app); + + uint32_t modifiers = 0; + const auto modifierArgs = parser.values(modifierOption); + if (modifierArgs.isEmpty()) { + qCritical() << "No modifiers specified. Use --modifier to specify lock modifiers to watch."; + parser.showHelp(EXIT_FAILURE); + } + + for (const auto &raw : modifierArgs) { + for (const auto &name : raw.split(',')) { + const auto trimmed = name.trimmed(); + if (trimmed.isEmpty()) + continue; + + uint32_t mod = 0; + if (!parseModifier(trimmed, mod)) { + qWarning() << "Unknown modifier:" << trimmed + << "(expected: caps_lock, num_lock)"; + continue; + } + modifiers |= mod; + } + } + + if (modifiers == 0) { + qCritical() << "No valid modifiers to watch."; + return EXIT_FAILURE; + } + + QStringList watchingNames; + if (modifiers & QtWayland::treeland_keyboard_state_watcher_v1::modifier_caps_lock) + watchingNames << "Caps Lock"; + if (modifiers & QtWayland::treeland_keyboard_state_watcher_v1::modifier_num_lock) + watchingNames << "Num Lock"; + qDebug() << "Watching modifiers:" << watchingNames.join(", "); + + auto *manager = new KeyboardStateNotifyManagerV1(); + + QObject::connect(manager, &KeyboardStateNotifyManagerV1::activeChanged, manager, [&]() { + if (!manager->isActive()) { + qWarning() << "Protocol not available."; + return; + } + + qDebug() << "Protocol active, creating keyboard state watcher..."; + + auto *watcher = manager->createWatcher(nullptr, manager); + if (!watcher) { + qCritical() << "Failed to create keyboard state watcher."; + qApp->exit(EXIT_FAILURE); + return; + } + + watcher->set_modifiers(modifiers); + + const QString watchMode = parser.value(watchOption); + uint32_t flags = 0; + if (watchMode == QLatin1String("locked") || watchMode == QLatin1String("all")) + flags |= QtWayland::treeland_keyboard_state_watcher_v1::watch_flag_locked; + if (watchMode == QLatin1String("unlocked") || watchMode == QLatin1String("all")) + flags |= QtWayland::treeland_keyboard_state_watcher_v1::watch_flag_unlocked; + + if (flags == 0) { + qCritical() << "Invalid --watch value:" << watchMode << "(expected: locked, unlocked, all)"; + qApp->exit(EXIT_FAILURE); + return; + } + + watcher->set_flags(flags); + watcher->apply(); + + qDebug() << "Keyboard state watcher created. Press Ctrl+C to quit."; + }); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/test_monitor_active_event/CMakeLists.txt b/examples/test_monitor_active_event/CMakeLists.txt new file mode 100644 index 0000000000..a6b9de9fcc --- /dev/null +++ b/examples/test_monitor_active_event/CMakeLists.txt @@ -0,0 +1,23 @@ +find_package(Qt6 REQUIRED COMPONENTS WaylandClient) +find_package(TreelandProtocols REQUIRED) + +set(BIN_NAME test-monitor-active-event) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + NO_INCLUDE_CORE_ONLY + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-active-notify-unstable-v1.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::WaylandClient +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") + diff --git a/examples/test_monitor_active_event/main.cpp b/examples/test_monitor_active_event/main.cpp new file mode 100644 index 0000000000..6c5633c0ae --- /dev/null +++ b/examples/test_monitor_active_event/main.cpp @@ -0,0 +1,120 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// Test application for treeland_active_notify_manager_v1 +// (treeland-active-notify-unstable-v1). Creates a seat activity notifier +// for the current seat and prints activity_changed / drag_changed events +// to the console. + +#include "qwayland-treeland-active-notify-unstable-v1.h" + +#include +#include +#include +#include + +class ActiveNotify + : public QObject + , public QtWayland::treeland_active_notify_v1 +{ + Q_OBJECT +public: + explicit ActiveNotify(struct ::treeland_active_notify_v1 *id, QObject *parent = nullptr) + : QObject(parent) + , QtWayland::treeland_active_notify_v1(id) + { + } + + ~ActiveNotify() override + { + destroy(); + } + +protected: + void treeland_active_notify_v1_activity_changed(uint32_t reason, uint32_t state) override + { + const QString reasonName = reason == QtWayland::treeland_active_notify_v1::reason_mouse + ? QStringLiteral("mouse") + : QStringLiteral("wheel"); + const QString stateName = state == QtWayland::treeland_active_notify_v1::activity_state_active + ? QStringLiteral("active") + : QStringLiteral("inactive"); + qWarning() << "activity_changed:" << reasonName << stateName; + } + + void treeland_active_notify_v1_drag_changed(uint32_t state) override + { + QString stateName; + switch (state) { + case QtWayland::treeland_active_notify_v1::drag_state_started: + stateName = QStringLiteral("started"); + break; + case QtWayland::treeland_active_notify_v1::drag_state_dropped: + stateName = QStringLiteral("dropped"); + break; + case QtWayland::treeland_active_notify_v1::drag_state_cancelled: + stateName = QStringLiteral("cancelled"); + break; + default: + stateName = QStringLiteral("unknown"); + break; + } + qWarning() << "drag_changed:" << stateName; + } +}; + +class TreelandActiveNotifyManagerV1 + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_active_notify_manager_v1 +{ + Q_OBJECT +public: + static constexpr int InterfaceVersion = 1; + + explicit TreelandActiveNotifyManagerV1() + : QWaylandClientExtensionTemplate(InterfaceVersion) + { + } + + ActiveNotify *createActiveNotify(struct ::wl_seat *seat, QObject *parent = nullptr) + { + if (m_activeNotify) + return m_activeNotify; + auto *raw = get_active_notify(seat); + if (!raw) + return nullptr; + m_activeNotify = new ActiveNotify(raw, parent); + return m_activeNotify; + } + +private: + QPointer m_activeNotify; +}; + +int main(int argc, char *argv[]) +{ + qputenv("QT_QPA_PLATFORM", "wayland"); + QGuiApplication app(argc, argv); + + auto *manager = new TreelandActiveNotifyManagerV1; + QObject::connect(manager, &TreelandActiveNotifyManagerV1::activeChanged, manager, [manager] { + if (!manager->isActive()) { + return; + } + + auto waylandApp = qGuiApp->nativeInterface(); + if (!waylandApp) { + return; + } + auto seat = waylandApp->seat(); + + if (!seat) + qFatal("Failed to get wl_seat from QtWayland QPA!"); + + [[maybe_unused]] ActiveNotify *notify = manager->createActiveNotify(seat, manager); + }); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/test_output_manager/CMakeLists.txt b/examples/test_output_manager/CMakeLists.txt new file mode 100644 index 0000000000..8f88dfad5b --- /dev/null +++ b/examples/test_output_manager/CMakeLists.txt @@ -0,0 +1,51 @@ +find_package(Qt6 REQUIRED COMPONENTS Gui WaylandClient Widgets) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS GuiPrivate WaylandClientPrivate) +endif() +find_package(TreelandProtocols REQUIRED) + +set(BIN_NAME test-output-manager) + +qt_add_executable(${BIN_NAME} + main.cpp + outputgroup.h + outputgroup.cpp + outputgroupmanager.h + outputgroupmanager.cpp + outputuuid.h + outputuuid.cpp + virtualclient.h + virtualclient.cpp + wlroutputmanager.h + wlroutputmanager.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-output-group-manager-unstable-v1.xml + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-output-manager-unstable-v2.xml + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-output-uuid-unstable-v1.xml + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-output-uuid-head-unstable-v1.xml + ${CMAKE_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-output-management-unstable-v1.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::Widgets + Qt6::WaylandClient + Qt6::GuiPrivate + Qt6::WaylandClientPrivate +) + +# The head protocol creates treeland_output_uuid_v1 objects, but defines neither +# that interface nor treeland_output_uuid_v1_interface. The generated wrapper for +# it is compiled on its own, so it needs the uuid protocol header force-included +# to get the missing declaration. +set_source_files_properties( + ${CMAKE_CURRENT_BINARY_DIR}/qwayland-treeland-output-uuid-head-unstable-v1.cpp + PROPERTIES + COMPILE_OPTIONS "-include;wayland-treeland-output-uuid-unstable-v1-client-protocol.h" +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_output_manager/main.cpp b/examples/test_output_manager/main.cpp new file mode 100644 index 0000000000..af2db5643d --- /dev/null +++ b/examples/test_output_manager/main.cpp @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "outputuuid.h" +#include "virtualclient.h" + +#include +#include + +// Output management example: the GUI drives primary output selection, picture +// control (brightness / color temperature), screen configuration and virtual +// (mirrored) outputs; --uuid runs the one-shot uuid probe instead. +int main(int argc, char *argv[]) +{ + qputenv("QT_QPA_PLATFORM", "wayland"); + QApplication app(argc, argv); + + QCommandLineParser parser; + parser.setApplicationDescription( + "Output management example: primary output, picture control, screen configuration, " + "virtual outputs, and the stable per-output uuid from treeland-output-uuid-unstable-v1."); + parser.addHelpOption(); + + QCommandLineOption uuidOption("uuid", + "Print the stable uuid of every output through both the " + "wl_output and zwlr_output_head_v1 entry points, then exit."); + parser.addOption(uuidOption); + + QCommandLineOption timeoutOption(QStringList() << "t" << "timeout", + "Milliseconds to wait for the compositor in --uuid mode.", + "timeout", + "2000"); + parser.addOption(timeoutOption); + parser.process(app); + + if (parser.isSet(uuidOption)) { + bool ok = false; + const int timeoutMs = parser.value(timeoutOption).toInt(&ok); + auto *probe = new UuidProbe(ok ? timeoutMs : 2000, &app); + probe->start(); + return app.exec(); + } + + VirtualClient client; + return app.exec(); +} diff --git a/examples/test_output_manager/outputgroup.cpp b/examples/test_output_manager/outputgroup.cpp new file mode 100644 index 0000000000..15f872c4fa --- /dev/null +++ b/examples/test_output_manager/outputgroup.cpp @@ -0,0 +1,92 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "outputgroup.h" + +#include + +OutputGroup::OutputGroup(struct ::treeland_output_group_v1 *object) + : QtWayland::treeland_output_group_v1(object) +{ +} + +OutputGroup::~OutputGroup() +{ + if (isInitialized()) + destroy(); +} + +void OutputGroup::requestSource(const QString &uuid) +{ + if (isInitialized()) + set_source(uuid); +} + +void OutputGroup::requestAddMirror(const QString &uuid) +{ + if (isInitialized()) + add_output(uuid); +} + +void OutputGroup::requestRemoveOutput(const QString &uuid) +{ + if (isInitialized()) + remove_output(uuid); +} + +void OutputGroup::commit() +{ + if (isInitialized()) + QtWayland::treeland_output_group_v1::commit(); +} + +void OutputGroup::dissolve() +{ + if (m_dissolved || !isInitialized()) + return; + m_dissolved = true; + QtWayland::treeland_output_group_v1::dissolve(); +} + +void OutputGroup::treeland_output_group_v1_name(const QString &name) +{ + m_name = name; + Q_EMIT nameAssigned(name); +} + +void OutputGroup::treeland_output_group_v1_done() +{ +} + +void OutputGroup::treeland_output_group_v1_state(const QString &source, + uint32_t count, + wl_array *uuids) +{ + QStringList mirrors; + if (count > 0 && uuids && uuids->size >= static_cast(count)) { + const size_t length = uuids->size / count; + const char *cursor = static_cast(uuids->data); + for (uint32_t i = 0; i < count; ++i) { + mirrors << QString::fromUtf8(cursor, static_cast(length)); + cursor += length; + } + } + // The server sends an initial (empty) state even when the create request + // is rejected, and a create that succeeds but whose add_output is later + // rejected reports a source but no mirror. A group we just created counts + // as established only once the state carries both a source and a mirror. + if (m_pending && !source.isEmpty() && !mirrors.isEmpty()) { + m_pending = false; + } + Q_EMIT stateChanged(source, mirrors); +} + +void OutputGroup::treeland_output_group_v1_removed() +{ + m_dissolved = true; + Q_EMIT removed(); +} + +void OutputGroup::treeland_output_group_v1_operation_failed(uint32_t code, const QString &uuid) +{ + Q_EMIT operationFailed(code, uuid); +} diff --git a/examples/test_output_manager/outputgroup.h b/examples/test_output_manager/outputgroup.h new file mode 100644 index 0000000000..83a9b1cb6e --- /dev/null +++ b/examples/test_output_manager/outputgroup.h @@ -0,0 +1,50 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "qwayland-treeland-output-group-manager-unstable-v1.h" + +#include +#include + +class OutputGroup + : public QObject + , public QtWayland::treeland_output_group_v1 +{ + Q_OBJECT +public: + explicit OutputGroup(struct ::treeland_output_group_v1 *object); + ~OutputGroup() override; + + QString name() const { return m_name; } + bool isValid() const { return m_valid; } + bool isPending() const { return m_pending; } + void setPending(bool pending) { m_pending = pending; } + + void requestSource(const QString &uuid); + void requestAddMirror(const QString &uuid); + void requestRemoveOutput(const QString &uuid); + void commit(); + void dissolve(); + +Q_SIGNALS: + void nameAssigned(const QString &name); + void stateChanged(const QString &sourceUuid, const QStringList &mirrorUuids); + void removed(); + void operationFailed(uint32_t code, const QString &uuid); + +protected: + void treeland_output_group_v1_name(const QString &name) override; + void treeland_output_group_v1_done() override; + void treeland_output_group_v1_state(const QString &source, + uint32_t count, + wl_array *uuids) override; + void treeland_output_group_v1_removed() override; + void treeland_output_group_v1_operation_failed(uint32_t code, const QString &uuid) override; + +private: + QString m_name; + bool m_valid = true; + bool m_pending = false; + bool m_dissolved = false; +}; diff --git a/examples/test_output_manager/outputgroupmanager.cpp b/examples/test_output_manager/outputgroupmanager.cpp new file mode 100644 index 0000000000..ed9919d0ca --- /dev/null +++ b/examples/test_output_manager/outputgroupmanager.cpp @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "outputgroupmanager.h" + +OutputGroupManager::OutputGroupManager() + : QWaylandClientExtensionTemplate(1) +{ +} + +OutputGroupManager::~OutputGroupManager() +{ + if (isInitialized()) + destroy(); +} + +void OutputGroupManager::instantiate() +{ + initialize(); +} + +struct ::treeland_output_group_v1 *OutputGroupManager::createGroup(const QString &sourceUuid) +{ + if (!isInitialized()) + return nullptr; + return create_group(sourceUuid); +} + +struct ::treeland_output_group_v1 *OutputGroupManager::getGroup(const QString &name) +{ + if (!isInitialized()) + return nullptr; + return get_group(name); +} + +void OutputGroupManager::treeland_output_group_manager_v1_group_added(const QString &name) +{ + Q_EMIT groupAdded(name); +} + +void OutputGroupManager::treeland_output_group_manager_v1_groups_done() +{ + Q_EMIT groupsDone(); +} + +void OutputGroupManager::treeland_output_group_manager_v1_group_removed(const QString &name) +{ + Q_EMIT groupRemoved(name); +} diff --git a/examples/test_output_manager/outputgroupmanager.h b/examples/test_output_manager/outputgroupmanager.h new file mode 100644 index 0000000000..efc203c120 --- /dev/null +++ b/examples/test_output_manager/outputgroupmanager.h @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "qwayland-treeland-output-group-manager-unstable-v1.h" + +#include +#include + +class OutputGroupManager + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_output_group_manager_v1 +{ + Q_OBJECT +public: + explicit OutputGroupManager(); + ~OutputGroupManager() override; + + void instantiate(); + + struct ::treeland_output_group_v1 *createGroup(const QString &sourceUuid); + struct ::treeland_output_group_v1 *getGroup(const QString &name); + +Q_SIGNALS: + void groupAdded(const QString &name); + void groupsDone(); + void groupRemoved(const QString &name); + +protected: + void treeland_output_group_manager_v1_group_added(const QString &name) override; + void treeland_output_group_manager_v1_groups_done() override; + void treeland_output_group_manager_v1_group_removed(const QString &name) override; +}; diff --git a/examples/test_output_manager/outputuuid.cpp b/examples/test_output_manager/outputuuid.cpp new file mode 100644 index 0000000000..e161541f68 --- /dev/null +++ b/examples/test_output_manager/outputuuid.cpp @@ -0,0 +1,323 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "outputuuid.h" + +#include +#include +#include + +#include + +namespace { + +constexpr int kUuidManagerVersion = 1; +constexpr int kWlrOutputManagerVersion = 4; +constexpr int kDefaultTimeoutMs = 2000; + +// treeland reports QUuid::WithoutBraces: 32 hex digits and no dashes. +constexpr int kExpectedUuidLength = 32; + +const QLatin1String kSourceOutput("wl_output"); +const QLatin1String kSourceHead("zwlr_output_head_v1"); + +wl_output *wlOutputForScreen(QScreen *screen) +{ + auto *native = screen->nativeInterface(); + return native ? native->output() : nullptr; +} + +} // namespace + +OutputUuidV1::OutputUuidV1(struct ::treeland_output_uuid_v1 *object, + const QString &source, + const QString &name, + bool enabled, + QObject *parent) + : QObject(parent) + , QtWayland::treeland_output_uuid_v1(object) + , m_source(source) + , m_name(name) + , m_enabled(enabled) +{ +} + +void OutputUuidV1::treeland_output_uuid_v1_uuid(const QString &uuid) +{ + if (m_reported) { + return; + } + m_reported = true; + m_uuid = uuid; + Q_EMIT uuidReceived(this, uuid); +} + +OutputUuidManagerV1::OutputUuidManagerV1() + : QWaylandClientExtensionTemplate(kUuidManagerVersion) +{ +} + +void OutputUuidManagerV1::instantiate() +{ + initialize(); +} + +OutputUuidHeadManagerV1::OutputUuidHeadManagerV1() + : QWaylandClientExtensionTemplate(kUuidManagerVersion) +{ +} + +void OutputUuidHeadManagerV1::instantiate() +{ + initialize(); +} + +HeadTracker::HeadTracker(struct ::zwlr_output_head_v1 *object) + : QtWayland::zwlr_output_head_v1(object) +{ +} + +HeadTracker::~HeadTracker() +{ + if (!m_finished && isInitialized()) { + release(); + } +} + +void HeadTracker::zwlr_output_head_v1_name(const QString &name) +{ + this->name = name; +} + +void HeadTracker::zwlr_output_head_v1_enabled(int32_t enabled) +{ + this->enabled = enabled != 0; +} + +void HeadTracker::zwlr_output_head_v1_finished() +{ + m_finished = true; + finished = true; + release(); +} + +HeadCollector::HeadCollector() + : QWaylandClientExtensionTemplate(kWlrOutputManagerVersion) +{ +} + +void HeadCollector::instantiate() +{ + initialize(); +} + +QList HeadCollector::heads() const +{ + QList result; + for (const auto &tracker : m_heads) { + if (tracker->finished || tracker->name.isEmpty()) { + continue; + } + result.append({tracker->name, tracker->enabled, tracker->object()}); + } + return result; +} + +void HeadCollector::zwlr_output_manager_v1_head(struct ::zwlr_output_head_v1 *head) +{ + m_heads.push_back(std::make_unique(head)); +} + +void HeadCollector::zwlr_output_manager_v1_done(uint32_t serial) +{ + Q_UNUSED(serial); + m_heads.erase(std::remove_if(m_heads.begin(), + m_heads.end(), + [](const std::unique_ptr &tracker) { + return tracker->finished; + }), + m_heads.end()); + Q_EMIT headsChanged(); +} + +UuidProbe::UuidProbe(int timeoutMs, QObject *parent) + : QObject(parent) + , m_timeoutMs(timeoutMs) +{ + m_manager.setParent(this); + m_headManager.setParent(this); + m_headCollector.setParent(this); + + connect(&m_manager, &OutputUuidManagerV1::activeChanged, this, &UuidProbe::onStateChanged); + connect(&m_headManager, + &OutputUuidHeadManagerV1::activeChanged, + this, + &UuidProbe::onStateChanged); + connect(&m_headCollector, &HeadCollector::activeChanged, this, &UuidProbe::onStateChanged); + connect(&m_headCollector, &HeadCollector::headsChanged, this, &UuidProbe::onHeadsChanged); + connect(&m_timeout, &QTimer::timeout, this, &UuidProbe::onTimeout); +} + +void UuidProbe::start() +{ + m_manager.instantiate(); + m_headManager.instantiate(); + m_headCollector.instantiate(); + m_timeout.setSingleShot(true); + m_timeout.start(m_timeoutMs); +} + +void UuidProbe::onStateChanged() +{ + maybeQuery(); +} + +void UuidProbe::onHeadsChanged() +{ + m_headsEnumerated = true; + maybeQuery(); +} + +void UuidProbe::maybeQuery() +{ + if (m_queried || !m_headsEnumerated) { + return; + } + if (!m_manager.isActive() && !m_headManager.isActive()) { + return; + } + query(); +} + +void UuidProbe::query() +{ + m_queried = true; + + if (m_manager.isActive()) { + const auto screens = QGuiApplication::screens(); + for (QScreen *screen : screens) { + auto *output = wlOutputForScreen(screen); + if (!output) { + continue; + } + addQuery(m_manager.get_uuid(output), kSourceOutput, screen->name(), true); + } + } else { + qWarning() << "treeland_output_uuid_manager_v1 is not available"; + } + + if (m_headManager.isActive()) { + const auto heads = m_headCollector.heads(); + for (const HeadCollector::Head &head : heads) { + addQuery(m_headManager.get_uuid(head.object), + kSourceHead, + head.name, + head.enabled); + } + } else { + qWarning() << "treeland_output_uuid_head_manager_v1 is not available"; + } + + if (m_pending == 0) { + qWarning() << "No output to query."; + finish(); + } +} + +void UuidProbe::addQuery(struct ::treeland_output_uuid_v1 *object, + const QString &source, + const QString &name, + bool enabled) +{ + if (!object) { + return; + } + auto *probe = new OutputUuidV1(object, source, name, enabled, this); + connect(probe, &OutputUuidV1::uuidReceived, this, &UuidProbe::onUuidReceived); + m_entries.append(probe); + ++m_pending; +} + +void UuidProbe::onUuidReceived(OutputUuidV1 *self, const QString &uuid) +{ + Q_UNUSED(self); + Q_UNUSED(uuid); + if (--m_pending == 0) { + finish(); + } +} + +void UuidProbe::onTimeout() +{ + if (!m_queried) { + qWarning() << "Timed out waiting for the compositor; reporting what is available."; + query(); + return; + } + qWarning() << "Timed out waiting for" << m_pending << "uuid event(s)."; + finish(); +} + +void UuidProbe::finish() +{ + m_timeout.stop(); + report(); + QGuiApplication::quit(); +} + +void UuidProbe::report() const +{ + QList entries = m_entries; + std::sort(entries.begin(), entries.end(), [](OutputUuidV1 *lhs, OutputUuidV1 *rhs) { + if (lhs->source() != rhs->source()) { + return lhs->source() < rhs->source(); + } + return lhs->name() < rhs->name(); + }); + + for (const OutputUuidV1 *entry : entries) { + if (entry->uuid().length() != kExpectedUuidLength) { + qWarning().nospace() << "unexpected uuid " << entry->uuid() << " for " + << entry->name(); + } + qInfo().nospace() << entry->source().leftJustified(20) << entry->name().leftJustified(10) + << (entry->enabled() ? "enabled " : "disabled ") << entry->uuid(); + } + + reportConsistency(); +} + +// Both entry points must report the same uuid for the same physical output, +// including outputs that are disabled and only have a head. +void UuidProbe::reportConsistency() const +{ + auto uuidFor = [this](const QString &source, const QString &name) { + for (const OutputUuidV1 *entry : m_entries) { + if (entry->source() == source && entry->name() == name) { + return entry->uuid(); + } + } + return QString(); + }; + + int compared = 0; + for (const OutputUuidV1 *entry : m_entries) { + if (entry->source() != kSourceOutput) { + continue; + } + const QString headUuid = uuidFor(kSourceHead, entry->name()); + if (headUuid.isEmpty()) { + continue; + } + ++compared; + if (headUuid == entry->uuid()) { + qInfo().nospace() << "consistent: " << entry->name(); + } else { + qWarning().nospace() << "mismatch: " << entry->name() << " wl_output=" << entry->uuid() + << " head=" << headUuid; + } + } + + qInfo().nospace() << compared << " output(s) compared across both entry points, " + << m_entries.size() << " uuid(s) reported."; +} diff --git a/examples/test_output_manager/outputuuid.h b/examples/test_output_manager/outputuuid.h new file mode 100644 index 0000000000..b9367c9dbb --- /dev/null +++ b/examples/test_output_manager/outputuuid.h @@ -0,0 +1,173 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +// treeland_output_uuid_v1 is defined by treeland-output-uuid-unstable-v1 and only +// referenced by the head protocol, so the uuid header must come first: it is what +// declares treeland_output_uuid_v1_interface, which the head header uses. +#include "qwayland-treeland-output-uuid-unstable-v1.h" +#include "qwayland-treeland-output-uuid-head-unstable-v1.h" +#include "qwayland-wlr-output-management-unstable-v1.h" + +#include +#include +#include +#include +#include + +#include +#include + +// Wraps one treeland_output_uuid_v1 object. The compositor emits the uuid event +// once right after the object is created. +class OutputUuidV1 + : public QObject + , public QtWayland::treeland_output_uuid_v1 +{ + Q_OBJECT +public: + OutputUuidV1(struct ::treeland_output_uuid_v1 *object, + const QString &source, + const QString &name, + bool enabled, + QObject *parent = nullptr); + + QString source() const + { + return m_source; + } + QString name() const + { + return m_name; + } + bool enabled() const + { + return m_enabled; + } + QString uuid() const + { + return m_uuid; + } + +Q_SIGNALS: + void uuidReceived(OutputUuidV1 *self, const QString &uuid); + +protected: + void treeland_output_uuid_v1_uuid(const QString &uuid) override; + +private: + QString m_source; + QString m_name; + QString m_uuid; + bool m_enabled = true; + bool m_reported = false; +}; + +class OutputUuidManagerV1 + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_output_uuid_manager_v1 +{ + Q_OBJECT +public: + explicit OutputUuidManagerV1(); + + void instantiate(); +}; + +class OutputUuidHeadManagerV1 + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_output_uuid_head_manager_v1 +{ + Q_OBJECT +public: + explicit OutputUuidHeadManagerV1(); + + void instantiate(); +}; + +// Keeps the name and enabled state of one zwlr_output_head_v1 so the head can be +// identified in the report. Heads are advertised even when the output is off, so +// they cover outputs that have no live wl_output global. +class HeadTracker : public QtWayland::zwlr_output_head_v1 +{ +public: + explicit HeadTracker(struct ::zwlr_output_head_v1 *object); + ~HeadTracker() override; + + QString name; + bool enabled = false; + bool finished = false; + +protected: + void zwlr_output_head_v1_name(const QString &name) override; + void zwlr_output_head_v1_enabled(int32_t enabled) override; + void zwlr_output_head_v1_finished() override; + +private: + bool m_finished = false; +}; + +class HeadCollector + : public QWaylandClientExtensionTemplate + , public QtWayland::zwlr_output_manager_v1 +{ + Q_OBJECT +public: + struct Head + { + QString name; + bool enabled = false; + struct ::zwlr_output_head_v1 *object = nullptr; + }; + + explicit HeadCollector(); + + void instantiate(); + QList heads() const; + +Q_SIGNALS: + void headsChanged(); + +protected: + void zwlr_output_manager_v1_head(struct ::zwlr_output_head_v1 *head) override; + void zwlr_output_manager_v1_done(uint32_t serial) override; + +private: + std::vector> m_heads; +}; + +// One-shot diagnostic: prints the uuid of every output reachable through the +// wl_output and zwlr_output_head_v1 entry points, then quits the application. +class UuidProbe : public QObject +{ + Q_OBJECT +public: + explicit UuidProbe(int timeoutMs, QObject *parent = nullptr); + + void start(); + +private: + void onStateChanged(); + void onHeadsChanged(); + void maybeQuery(); + void query(); + void addQuery(struct ::treeland_output_uuid_v1 *object, + const QString &source, + const QString &name, + bool enabled); + void onUuidReceived(OutputUuidV1 *self, const QString &uuid); + void onTimeout(); + void finish(); + void report() const; + void reportConsistency() const; + + int m_timeoutMs; + bool m_queried = false; + bool m_headsEnumerated = false; + int m_pending = 0; + QTimer m_timeout; + OutputUuidManagerV1 m_manager; + OutputUuidHeadManagerV1 m_headManager; + HeadCollector m_headCollector; + QList m_entries; +}; diff --git a/examples/test_output_manager/virtualclient.cpp b/examples/test_output_manager/virtualclient.cpp new file mode 100644 index 0000000000..4b89391694 --- /dev/null +++ b/examples/test_output_manager/virtualclient.cpp @@ -0,0 +1,1044 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "virtualclient.h" +#include "outputgroup.h" +#include "outputgroupmanager.h" +#include "wlroutputmanager.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + + +TreelandOutputManager::TreelandOutputManager() + : QWaylandClientExtensionTemplate(1) +{ +} + +TreelandOutputManager::~TreelandOutputManager() +{ + if (isInitialized()) + destroy(); +} + +void TreelandOutputManager::instantiate() +{ + initialize(); +} + +struct ::treeland_output_picture_control_v2 *TreelandOutputManager::getPictureControl(const QString &uuid) +{ + if (!isInitialized()) + return nullptr; + return get_picture_control(uuid); +} + + +class ColorControl : public QObject, public QtWayland::treeland_output_picture_control_v2 +{ + Q_OBJECT +public: + ColorControl(struct ::treeland_output_picture_control_v2 *obj, QObject *parent = nullptr) + : QObject(parent) + , QtWayland::treeland_output_picture_control_v2(obj) + { + } + ~ColorControl() override + { + if (isInitialized()) + destroy(); + } + +Q_SIGNALS: + void brightnessChanged(int percent); + void colorTemperatureChanged(uint32_t kelvin); + +protected: + void treeland_output_picture_control_v2_brightness(wl_fixed_t b) override + { + Q_EMIT brightnessChanged(static_cast(std::round(wl_fixed_to_double(b)))); + } + void treeland_output_picture_control_v2_color_temperature(uint32_t t) override + { + Q_EMIT colorTemperatureChanged(t); + } + void treeland_output_picture_control_v2_result(uint32_t result) override + { + // Carried over from the removed test-color-control example: report what + // the compositor answered for the last commit. + QString text; + switch (result) { + case commit_result_success: + text = "success"; + break; + case commit_result_failed: + text = "failed"; + break; + case commit_result_unsupported: + text = "unsupported"; + break; + case commit_result_invalid_output: + text = "invalid_output"; + break; + default: + text = QString::number(result); + break; + } + qInfo() << "picture control commit result:" << text; + } +}; + +VirtualClient::VirtualClient(QObject *parent) + : QObject(parent) +{ + m_groupManager = std::make_unique(); + m_treelandManager = std::make_unique(); + m_wlrManager = std::make_unique(); + m_uuidManager = std::make_unique(); + + connect(m_groupManager.get(), &OutputGroupManager::activeChanged, this, [this]() { + if (m_groupManager->isActive()) + setupUi(); + }); + connect(m_groupManager.get(), &OutputGroupManager::groupAdded, + this, &VirtualClient::onGroupAdded); + connect(m_groupManager.get(), &OutputGroupManager::groupsDone, + this, &VirtualClient::onGroupsDone); + connect(m_groupManager.get(), &OutputGroupManager::groupRemoved, + this, &VirtualClient::onGroupRemoved); + + connect(m_treelandManager.get(), &TreelandOutputManager::primaryOutputChanged, + this, &VirtualClient::onPrimaryOutputChanged); + + connect(m_wlrManager.get(), &WlrOutputManager::headsChanged, this, &VirtualClient::onWlrHeadsChanged); + connect(m_wlrManager.get(), &WlrOutputManager::applyFinished, this, &VirtualClient::onWlrApplyFinished); + + connect(m_uuidManager.get(), &OutputUuidManagerV1::activeChanged, this, [this]() { + if (m_uuidManager->isActive()) + refreshUuids(); + }); + + m_groupManager->instantiate(); + m_treelandManager->instantiate(); + m_wlrManager->instantiate(); + m_uuidManager->instantiate(); +} + +VirtualClient::~VirtualClient() +{ + delete m_colorControl; +} + +bool VirtualClient::eventFilter(QObject *watched, QEvent *event) +{ + if (event->type() == QEvent::Hide && watched == mirrorComboPopup()) { + if (m_mirrorComboDirty) { + m_mirrorComboDirty = false; + refreshMirrorCombo(); + } + } + return QObject::eventFilter(watched, event); +} + +QWidget *VirtualClient::mirrorComboPopup() const +{ + if (!m_mirrorCombo) + return nullptr; + QAbstractItemView *view = m_mirrorCombo->view(); + return view ? view->window() : nullptr; +} + +void VirtualClient::setupUi() +{ + if (m_widget) + return; + + m_widget = new QWidget; + m_widget->resize(640, 700); + + auto *mainLayout = new QVBoxLayout(m_widget); + mainLayout->setSpacing(8); + + m_infoLabel = new QLabel("Loading screen info..."); + m_infoLabel->setWordWrap(true); + mainLayout->addWidget(m_infoLabel); + + auto *selRow = new QHBoxLayout; + selRow->addWidget(new QLabel("Screen:")); + m_screenCombo = new QComboBox; + m_screenCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + selRow->addWidget(m_screenCombo); + + m_primaryBtn = new QPushButton("Primary"); + connect(m_primaryBtn, &QPushButton::clicked, this, &VirtualClient::onPrimaryClicked); + selRow->addWidget(m_primaryBtn); + + m_primaryLabel = new QLabel("Primary: —"); + m_primaryLabel->setStyleSheet("color: #4a90d9;"); + selRow->addWidget(m_primaryLabel); + + m_disableBtn = new QPushButton("Disable"); + connect(m_disableBtn, &QPushButton::clicked, this, &VirtualClient::onDisableClicked); + selRow->addWidget(m_disableBtn); + selRow->addWidget(new QLabel("Mirror:")); + m_mirrorCombo = new QComboBox; + m_mirrorCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + selRow->addWidget(m_mirrorCombo); + mainLayout->addLayout(selRow); + + auto *settingsGroup = new QGroupBox("Screen Settings"); + auto *form = new QFormLayout(settingsGroup); + form->setSpacing(6); + + m_brightnessSlider = new QSlider(Qt::Horizontal); + m_brightnessSlider->setRange(0, 100); + m_brightnessSlider->setValue(100); + m_brightnessLabel = new QLabel("100%"); + // valueChanged only refreshes the local label; the actual commit is + // debounced (and also fired on sliderReleased) so dragging the slider does + // not flood the compositor with one commit per intermediate value. + connect(m_brightnessSlider, &QSlider::valueChanged, this, &VirtualClient::onBrightnessChanged); + connect(m_brightnessSlider, &QSlider::sliderReleased, this, &VirtualClient::onBrightnessSliderReleased); + m_brightnessCommitTimer = new QTimer(this); + m_brightnessCommitTimer->setSingleShot(true); + m_brightnessCommitTimer->setInterval(120); + connect(m_brightnessCommitTimer, &QTimer::timeout, this, &VirtualClient::commitBrightness); + auto *brightRow = new QHBoxLayout; + brightRow->addWidget(m_brightnessSlider); + brightRow->addWidget(m_brightnessLabel); + form->addRow("Brightness:", brightRow); + + m_colorTempSlider = new QSlider(Qt::Horizontal); + m_colorTempSlider->setRange(1000, 20000); + m_colorTempSlider->setValue(6500); + m_colorTempLabel = new QLabel("6500K"); + connect(m_colorTempSlider, &QSlider::valueChanged, this, &VirtualClient::onColorTempChanged); + connect(m_colorTempSlider, &QSlider::sliderReleased, this, &VirtualClient::onColorTempSliderReleased); + m_colorTempCommitTimer = new QTimer(this); + m_colorTempCommitTimer->setSingleShot(true); + m_colorTempCommitTimer->setInterval(120); + connect(m_colorTempCommitTimer, &QTimer::timeout, this, &VirtualClient::commitColorTemp); + auto *ctRow = new QHBoxLayout; + ctRow->addWidget(m_colorTempSlider); + ctRow->addWidget(m_colorTempLabel); + form->addRow("Color Temp:", ctRow); + + m_posX = new QSpinBox; + m_posX->setRange(-99999, 99999); + m_posY = new QSpinBox; + m_posY->setRange(-99999, 99999); + auto *posRow = new QHBoxLayout; + posRow->addWidget(new QLabel("X:")); + posRow->addWidget(m_posX); + posRow->addWidget(new QLabel("Y:")); + posRow->addWidget(m_posY); + form->addRow("Position:", posRow); + + m_resolutionCombo = new QComboBox; + form->addRow("Resolution:", m_resolutionCombo); + + m_refreshCombo = new QComboBox; + form->addRow("Refresh:", m_refreshCombo); + + m_rotationCombo = new QComboBox; + m_rotationCombo->addItem("Normal", 0); + m_rotationCombo->addItem("90°", 1); + m_rotationCombo->addItem("180°", 2); + m_rotationCombo->addItem("270°", 3); + m_rotationCombo->addItem("Flipped", 4); + m_rotationCombo->addItem("Flipped 90°", 5); + m_rotationCombo->addItem("Flipped 180°", 6); + m_rotationCombo->addItem("Flipped 270°", 7); + form->addRow("Rotation:", m_rotationCombo); + + m_scaleCombo = new QComboBox; + for (double s : {0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0}) + m_scaleCombo->addItem(QString::number(s, 'f', 2), s); + m_scaleCombo->setCurrentText("1.00"); + form->addRow("Scale:", m_scaleCombo); + + mainLayout->addWidget(settingsGroup); + + mainLayout->addStretch(); + + connect(m_screenCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &VirtualClient::onScreenChanged); + connect(m_mirrorCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &VirtualClient::onMirrorChanged); + connect(m_resolutionCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &VirtualClient::onResolutionChanged); + + connect(m_posX, QOverload::of(&QSpinBox::valueChanged), + this, &VirtualClient::applyCurrentSettings); + connect(m_posY, QOverload::of(&QSpinBox::valueChanged), + this, &VirtualClient::applyCurrentSettings); + connect(m_resolutionCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &VirtualClient::applyCurrentSettings); + connect(m_refreshCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &VirtualClient::applyCurrentSettings); + connect(m_rotationCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &VirtualClient::applyCurrentSettings); + connect(m_scaleCombo, QOverload::of(&QComboBox::currentIndexChanged), + this, &VirtualClient::applyCurrentSettings); + m_widget->show(); + + // Refresh once the popup is dismissed if an async refresh was deferred + // while the Mirror dropdown popup was visible. Mutating a QComboBox's + // model while its Qt::Popup container is visible closes the popup without + // QComboBox noticing, after which it can no longer be reopened. + if (QWidget *popup = mirrorComboPopup()) + popup->installEventFilter(this); + + refreshScreenInfo(); +} + +void VirtualClient::refreshUuids() +{ + if (!m_uuidManager->isActive()) + return; + + for (QScreen *screen : QGuiApplication::screens()) { + const QString name = screen->name(); + if (name.isEmpty() || m_uuidObjects.contains(name)) + continue; + + auto *native = screen->nativeInterface(); + if (!native || !native->output()) + continue; + + auto *object = m_uuidManager->get_uuid(native->output()); + if (!object) + continue; + + auto *probe = new OutputUuidV1(object, QStringLiteral("wl_output"), name, true, this); + connect(probe, &OutputUuidV1::uuidReceived, this, + [this, name](OutputUuidV1 *, const QString &uuid) { + onUuidReceived(name, uuid); + }); + m_uuidObjects.insert(name, probe); + } +} + +void VirtualClient::onUuidReceived(const QString &name, const QString &uuid) +{ + m_uuidByName[name] = uuid; + updatePrimaryLabel(); + updatePrimaryButtonText(); + // A pending mirror request was waiting for this uuid (or the one of the + // screen being mirrored); re-run it now that the mapping is known. + if (!m_pendingMirrorScreen.isEmpty()) + QMetaObject::invokeMethod(this, &VirtualClient::updateMirrorGroup, Qt::QueuedConnection); + if (m_screenCombo && m_screenCombo->currentText() == name) + acquireColorControl(name); +} + +QString VirtualClient::uuidForScreen(const QString &name) const +{ + return m_uuidByName.value(name); +} + +QString VirtualClient::screenForUuid(const QString &uuid) const +{ + if (uuid.isEmpty()) + return QString(); + for (auto it = m_uuidByName.cbegin(); it != m_uuidByName.cend(); ++it) { + if (it.value() == uuid) + return it.key(); + } + return QString(); +} + +void VirtualClient::refreshScreenInfo() +{ + if (!m_widget) + return; + + QString info; + info += "Physical Screens:
"; + + const auto screens = QGuiApplication::screens(); + for (auto *screen : screens) { + info += QString(" %1 — %2x%3 @ %4Hz, pos(%5,%6), scale %7
") + .arg(screen->name(), + QString::number(screen->geometry().width()), + QString::number(screen->geometry().height()), + QString::number(screen->refreshRate(), 'f', 1), + QString::number(screen->geometry().x()), + QString::number(screen->geometry().y()), + QString::number(screen->devicePixelRatio(), 'f', 1)); + } + + auto wlrHeads = m_wlrManager->heads(); + if (!wlrHeads.isEmpty()) { + info += "
Wlr Heads:
"; + for (const auto &h : wlrHeads) { + info += QString(" %1 — %2x%3 @ %4, pos(%5,%6), scale %7, rot %8
") + .arg(h.name, + h.currentMode >= 0 && h.currentMode < h.modes.size() + ? QString::number(h.modes[h.currentMode].size.width()) + : "?", + h.currentMode >= 0 && h.currentMode < h.modes.size() + ? QString::number(h.modes[h.currentMode].size.height()) + : "?", + h.currentMode >= 0 && h.currentMode < h.modes.size() + ? QString::number(h.modes[h.currentMode].refresh / 1000.0, 'f', 1) + : "?", + QString::number(h.position.x()), + QString::number(h.position.y()), + QString::number(h.scale, 'f', 2), + QString::number(h.transform)); + } + } + + info += "
Mirror Groups:
"; + if (m_mirrorGroups.isEmpty()) { + info += " (none)
"; + } else { + for (auto it = m_mirrorGroups.begin(); it != m_mirrorGroups.end(); ++it) { + const auto &outputs = it.value(); + if (outputs.size() >= 2) { + QStringList mirrors; + for (int i = 1; i < outputs.size(); ++i) + mirrors << outputs[i]; + info += QString(" %1 ← %2
").arg(outputs.first(), mirrors.join(", ")); + } + } + } + + m_infoLabel->setText(info); + + QStringList live; + for (auto *screen : QGuiApplication::screens()) { + const QString n = screen->name().trimmed(); + if (!n.isEmpty() && n != QLatin1String("screen")) + live << n; + } + for (const auto &h : m_wlrManager->heads()) { + if (!h.name.isEmpty() && !live.contains(h.name)) + live << h.name; + } + m_screenNames = live; + const QStringList names = m_screenNames; + + QStringList existing; + for (int i = 0; i < m_screenCombo->count(); ++i) + existing << m_screenCombo->itemText(i); + if (!names.isEmpty() && existing != names) { + QString current = m_screenCombo->currentText(); + m_screenCombo->blockSignals(true); + m_screenCombo->clear(); + for (const auto &n : names) + m_screenCombo->addItem(n); + if (!current.isEmpty()) + m_screenCombo->setCurrentText(current); + m_screenCombo->blockSignals(false); + if (m_screenCombo->currentIndex() < 0 && m_screenCombo->count() > 0) + m_screenCombo->setCurrentIndex(0); + } + refreshMirrorCombo(); + + if (m_resolutionCombo->count() == 0 && m_screenCombo->currentIndex() >= 0) + onScreenChanged(m_screenCombo->currentIndex()); + + refreshUuids(); + + // Re-acquire here: disable/enable can rebind the output while wl_output stays the same. + if (m_screenCombo->currentIndex() >= 0) + acquireColorControl(m_screenCombo->currentText()); +} + +void VirtualClient::onGroupAdded(const QString &name) +{ + if (!name.isEmpty() && !m_groupNames.contains(name)) + m_groupNames << name; +} + +void VirtualClient::attachGroup(const QString &name) +{ + if (name.isEmpty() || m_groups.contains(name)) + return; + + auto *obj = m_groupManager->getGroup(name); + if (!obj) + return; + + auto *group = new OutputGroup(obj); + group->setParent(this); + m_groups.insert(name, group); + connect(group, &OutputGroup::stateChanged, this, + &VirtualClient::onGroupStateChanged); + connect(group, &OutputGroup::removed, this, &VirtualClient::onGroupObjectRemoved); + connect(group, &OutputGroup::operationFailed, this, + &VirtualClient::onGroupOperationFailed); +} + +void VirtualClient::onGroupNameAssigned(const QString &name) +{ + auto *group = qobject_cast(sender()); + if (!group) + return; + m_groupNames << name; + m_groups.insert(name, group); +} + +void VirtualClient::onGroupStateChanged(const QString &sourceUuid, + const QStringList &mirrorUuids) +{ + auto *group = qobject_cast(sender()); + if (!group) + return; + onGroupState(group->name(), sourceUuid, mirrorUuids); +} + +void VirtualClient::onGroupOperationFailed(uint32_t code, const QString &uuid) +{ + auto *group = qobject_cast(sender()); + if (!group) { + qWarning() << " Output group operation failed:" << code << uuid; + return; + } + + const QString name = group->name(); + qWarning() << " Output group operation failed (code" << code << ", uuid" << uuid + << ") on group" << name; + + // A failed request on a group we just created (the create itself, or the + // queued add_output right after it) must not leave a ghost group in the + // UI: the compositor rejected the mirror, so continuing to operate on the + // half-created object would show a mirror that does not exist. An + // established group merely reports the failure and keeps its state. + if (!group->isPending()) + return; + + // Undo the optimistic local maps, including the mirror combo which still + // shows the rejected mirror: without resetting it the user cannot retry + // the same item because currentIndexChanged would not fire again. + group->setPending(false); + m_groupNames.removeAll(name); + if (!name.isEmpty()) { + m_groups.remove(name); + m_mirrorGroups.remove(name); + } + m_pendingMirrorScreen.clear(); + updateScreenToGroup(); + refreshScreenInfo(); + if (m_mirrorCombo) { + m_mirrorCombo->blockSignals(true); + m_mirrorCombo->setCurrentIndex(0); // "None (no mirror)" + m_mirrorCombo->blockSignals(false); + } + + // The server may still hold the group (only the add_output was rejected + // after a successful create). Dissolve it so other clients stop seeing the + // group we abandon; dissolve() is idempotent, so the removed event that + // may already be queued cannot trigger a second one. + group->dissolve(); +} + +void VirtualClient::onGroupObjectRemoved() +{ + auto *group = qobject_cast(sender()); + if (!group) + return; + group->setPending(false); + const QString name = group->name(); + if (!name.isEmpty()) + m_groups.remove(name); + group->deleteLater(); +} + +void VirtualClient::onGroupsDone() +{ + for (auto it = m_groups.begin(); it != m_groups.end();) { + if (!m_groupNames.contains(it.key())) { + it.value()->deleteLater(); + it = m_groups.erase(it); + continue; + } + ++it; + } + + m_groupNames.removeDuplicates(); + for (const auto &name : std::as_const(m_groupNames)) + attachGroup(name); + + refreshScreenInfo(); +} + +void VirtualClient::onGroupRemoved(const QString &name) +{ + if (auto *group = m_groups.take(name)) + group->deleteLater(); + m_groupNames.removeAll(name); + m_mirrorGroups.remove(name); + updateScreenToGroup(); + refreshScreenInfo(); +} + +void VirtualClient::onGroupState(const QString &groupName, + const QString &sourceUuid, + const QStringList &mirrorUuids) +{ + if (groupName.isEmpty()) + return; + + QStringList screens; + const QString source = screenForUuid(sourceUuid); + if (!source.isEmpty()) + screens << source; + for (const auto &uuid : std::as_const(mirrorUuids)) { + const QString screen = screenForUuid(uuid); + if (!screen.isEmpty()) + screens << screen; + } + + m_mirrorGroups[groupName] = screens; + updateScreenToGroup(); + refreshScreenInfo(); +} + +void VirtualClient::updateScreenToGroup() +{ + m_screenToGroup.clear(); + for (auto it = m_mirrorGroups.begin(); it != m_mirrorGroups.end(); ++it) { + for (const auto &screen : it.value()) + m_screenToGroup.insert(screen, it.key()); + } +} + +void VirtualClient::refreshMirrorCombo() +{ + QString sel = m_screenCombo->currentText(); + const QString prev = m_mirrorCombo->currentData().toString(); + + QStringList items; + QList datas; + items << "None (no mirror)"; + datas << QVariant(); + for (int i = 0; i < m_screenCombo->count(); ++i) { + const QString name = m_screenCombo->itemText(i); + if (name != sel) { + items << name; + datas << name; + } + } + + // Rebuilding the model while the popup is visible closes the popup + // (without QComboBox noticing) and prevents it from ever reopening, so + // defer the refresh until the popup has been dismissed. + if (QWidget *popup = mirrorComboPopup(); popup && popup->isVisible()) { + m_mirrorComboDirty = true; + return; + } + + if (m_mirrorCombo->count() == items.size()) { + bool same = true; + for (int i = 0; i < items.size(); ++i) { + if (m_mirrorCombo->itemText(i) != items.at(i) + || m_mirrorCombo->itemData(i).toString() != datas.at(i).toString()) { + same = false; + break; + } + } + if (same) { + const int idx = m_mirrorCombo->findData(prev); + const int want = idx >= 0 ? idx : 0; + if (m_mirrorCombo->currentIndex() != want) { + m_mirrorCombo->blockSignals(true); + m_mirrorCombo->setCurrentIndex(want); + m_mirrorCombo->blockSignals(false); + } + return; + } + } + + m_mirrorCombo->blockSignals(true); + m_mirrorCombo->clear(); + m_mirrorCombo->addItem("None (no mirror)", QString()); + for (int i = 1; i < items.size(); ++i) + m_mirrorCombo->addItem(items.at(i), datas.at(i)); + const int idx = m_mirrorCombo->findData(prev); + m_mirrorCombo->setCurrentIndex(idx >= 0 ? idx : 0); + m_mirrorCombo->blockSignals(false); +} + +void VirtualClient::onScreenChanged(int index) +{ + if (index < 0) + return; + const QString name = m_screenCombo->itemText(index); + + m_updatingUi = true; + + auto wlrHeads = m_wlrManager->heads(); + for (const auto &h : wlrHeads) { + if (h.name == name) { + m_posX->setValue(h.position.x()); + m_posY->setValue(h.position.y()); + m_disableBtn->setText(h.enabled ? "Disable" : "Enable"); + m_resolutionCombo->blockSignals(true); + m_resolutionCombo->clear(); + int preferredIdx = 0; + int currentIdx = 0; + QSize currentModeSize; + if (h.currentMode >= 0 && h.currentMode < h.modes.size()) + currentModeSize = h.modes[h.currentMode].size; + QSet seenSizes; + for (int i = 0; i < h.modes.size(); ++i) { + const auto &mode = h.modes[i]; + if (seenSizes.contains(mode.size)) + continue; + seenSizes.insert(mode.size); + QString label = QString("%1x%2").arg(mode.size.width()).arg(mode.size.height()); + if (mode.preferred) { + label += " (preferred)"; + preferredIdx = m_resolutionCombo->count(); + } + if (mode.size == currentModeSize) + currentIdx = m_resolutionCombo->count(); + m_resolutionCombo->addItem(label, i); + } + m_resolutionCombo->setCurrentIndex(h.currentMode >= 0 ? currentIdx : preferredIdx); + m_resolutionCombo->blockSignals(false); + + onResolutionChanged(m_resolutionCombo->currentIndex()); + + m_rotationCombo->setCurrentIndex(h.transform); + + int scaleIdx = m_scaleCombo->findText(QString::number(h.scale, 'f', 2)); + if (scaleIdx >= 0) + m_scaleCombo->setCurrentIndex(scaleIdx); + + break; + } + } + + acquireColorControl(name); + + refreshMirrorCombo(); + if (m_screenToGroup.contains(name)) { + QString groupName = m_screenToGroup[name]; + auto outputs = m_mirrorGroups.value(groupName); + if (outputs.size() >= 2 && outputs.first() != name) { + m_mirrorCombo->blockSignals(true); + m_mirrorCombo->setCurrentText(outputs.first()); + m_mirrorCombo->blockSignals(false); + } + } + m_primaryBtn->setEnabled(m_mirrorCombo->currentData().toString().isEmpty()); + updatePrimaryButtonText(); + m_updatingUi = false; +} + +void VirtualClient::onResolutionChanged(int resIndex) +{ + QString name = m_screenCombo->currentText(); + m_refreshCombo->blockSignals(true); + m_refreshCombo->clear(); + if (resIndex < 0 || name.isEmpty()) { + m_refreshCombo->blockSignals(false); + return; + } + + int modeIdx = m_resolutionCombo->currentData().toInt(); + auto wlrHeads = m_wlrManager->heads(); + for (const auto &h : wlrHeads) { + if (h.name == name && modeIdx >= 0 && modeIdx < h.modes.size()) { + const auto &selMode = h.modes[modeIdx]; + QList refreshList; + int currentRefresh = -1; + QSet seenRefresh; + for (int i = 0; i < h.modes.size(); ++i) { + const auto &mode = h.modes[i]; + if (mode.size != selMode.size) + continue; + if (seenRefresh.contains(mode.refresh)) + continue; + seenRefresh.insert(mode.refresh); + m_refreshCombo->addItem(QString::number(mode.refresh / 1000.0, 'f', 2) + "Hz", mode.refresh); + if (i == h.currentMode) + currentRefresh = mode.refresh; + refreshList.append(mode.refresh); + } + if (currentRefresh >= 0) { + int idx = refreshList.indexOf(currentRefresh); + if (idx >= 0) + m_refreshCombo->setCurrentIndex(idx); + } + break; + } + } + m_refreshCombo->blockSignals(false); +} + + +void VirtualClient::onMirrorChanged(int index) +{ + Q_UNUSED(index); + updateMirrorGroup(); + m_primaryBtn->setEnabled(m_mirrorCombo->currentData().toString().isEmpty()); + updatePrimaryButtonText(); +} + +void VirtualClient::onBrightnessChanged(int value) +{ + m_brightnessLabel->setText(QString("%1%").arg(value)); + // Debounce the commit: restarts the single-shot timer on every intermediate + // value so only the final settled value is pushed to the compositor. + m_brightnessCommitTimer->start(); +} + +void VirtualClient::onColorTempChanged(int value) +{ + m_colorTempLabel->setText(QString("%1K").arg(value)); + m_colorTempCommitTimer->start(); +} + +void VirtualClient::onBrightnessSliderReleased() +{ + // Commit immediately on release and cancel any pending debounce. + m_brightnessCommitTimer->stop(); + commitBrightness(); +} + +void VirtualClient::onColorTempSliderReleased() +{ + m_colorTempCommitTimer->stop(); + commitColorTemp(); +} + +void VirtualClient::commitBrightness() +{ + if (m_colorControl) { + m_colorControl->set_brightness(wl_fixed_from_double(m_brightnessSlider->value())); + m_colorControl->commit(); + } +} + +void VirtualClient::commitColorTemp() +{ + if (m_colorControl) { + m_colorControl->set_color_temperature(static_cast(m_colorTempSlider->value())); + m_colorControl->commit(); + } +} + +void VirtualClient::onColorControlBrightness(int percent) +{ + m_brightnessSlider->blockSignals(true); + m_brightnessSlider->setValue(percent); + m_brightnessSlider->blockSignals(false); + m_brightnessLabel->setText(QString("%1%").arg(percent)); +} + +void VirtualClient::onColorControlColorTemp(uint32_t kelvin) +{ + m_colorTempSlider->blockSignals(true); + m_colorTempSlider->setValue(static_cast(kelvin)); + m_colorTempSlider->blockSignals(false); + m_colorTempLabel->setText(QString("%1K").arg(kelvin)); +} + +void VirtualClient::acquireColorControl(const QString &screenName) +{ + if (m_colorControl) { + m_colorControl->destroy(); + delete m_colorControl; + m_colorControl = nullptr; + } + if (!m_treelandManager->isActive()) + return; + const QString uuid = uuidForScreen(screenName); + if (uuid.isEmpty()) + return; + auto *cc = m_treelandManager->getPictureControl(uuid); + if (!cc) + return; + m_colorControl = new ColorControl(cc, this); + connect(m_colorControl, &ColorControl::brightnessChanged, + this, &VirtualClient::onColorControlBrightness); + connect(m_colorControl, &ColorControl::colorTemperatureChanged, + this, &VirtualClient::onColorControlColorTemp); +} +void VirtualClient::applyCurrentSettings() +{ + if (m_updatingUi) + return; + QString name = m_screenCombo->currentText(); + if (name.isEmpty()) + return; + + int x = m_posX->value(); + int y = m_posY->value(); + + QSize modeSize; + int refresh = 0; + int modeIdx = m_resolutionCombo->currentData().toInt(); + auto wlrHeads = m_wlrManager->heads(); + for (const auto &h : wlrHeads) { + if (h.name == name) { + if (modeIdx >= 0 && modeIdx < h.modes.size()) { + modeSize = h.modes[modeIdx].size; + refresh = m_refreshCombo->currentData().toInt(); + } + break; + } + } + + int transform = m_rotationCombo->currentData().toInt(); + double scale = m_scaleCombo->currentData().toDouble(); + + m_wlrManager->applyConfig(name, true, QPoint(x, y), modeSize, refresh, transform, scale); +} + +void VirtualClient::onDisableClicked() +{ + QString name = m_screenCombo->currentText(); + if (name.isEmpty()) + return; + + bool enabled = false; + const auto wlrHeads = m_wlrManager->heads(); + for (const auto &h : wlrHeads) { + if (h.name == name) { + enabled = h.enabled; + break; + } + } + + if (enabled) { + m_wlrManager->applyConfig(name, false, QPoint(), QSize(), 0, 0, 1.0); + m_disableBtn->setText("Enable"); + } else { + applyCurrentSettings(); + m_disableBtn->setText("Disable"); + } +} + +void VirtualClient::onPrimaryClicked() +{ + QString name = m_screenCombo->currentText(); + if (name.isEmpty()) + return; + if (!m_treelandManager->isActive()) + return; + const QString uuid = uuidForScreen(name); + if (uuid.isEmpty()) { + qWarning() << "No uuid known for" << name << "yet"; + return; + } + m_treelandManager->set_primary_output(uuid); +} + +void VirtualClient::onPrimaryOutputChanged(const QString &uuid) +{ + m_primaryUuid = uuid; + updatePrimaryLabel(); + updatePrimaryButtonText(); +} + +void VirtualClient::updatePrimaryLabel() +{ + if (!m_primaryLabel) + return; + const QString name = screenForUuid(m_primaryUuid); + m_primaryLabel->setText(QString("Primary: %1").arg(name.isEmpty() ? QStringLiteral("—") : name)); +} + +void VirtualClient::updatePrimaryButtonText() +{ + if (m_primaryBtn) { + const QString current = m_screenCombo ? m_screenCombo->currentText() : QString(); + const bool isPrimary = !m_primaryUuid.isEmpty() && !current.isEmpty() + && uuidForScreen(current) == m_primaryUuid; + m_primaryBtn->setText(isPrimary ? "Primary ✓" : "Primary"); + } +} +void VirtualClient::onWlrHeadsChanged() +{ + // Groups are pushed through group_added/group_removed; the output group + // protocol has no list request. + refreshScreenInfo(); +} + +void VirtualClient::onWlrApplyFinished(bool ok) +{ + Q_UNUSED(ok); + + refreshScreenInfo(); +} + +void VirtualClient::updateMirrorGroup() +{ + const QString screen = m_screenCombo->currentText(); + const QString mirror = m_mirrorCombo->currentData().toString(); + + if (screen.isEmpty()) + return; + + // Leaving a group is explicit: dissolve the group the screen belongs to. + // The server-side removed event (onGroupObjectRemoved) then destroys the + // proxy and cleans up; dissolve() is idempotent so a late operation_failed + // cannot trigger a second dissolve request. + if (m_screenToGroup.contains(screen)) { + const QString oldGroup = m_screenToGroup[screen]; + if (auto *group = m_groups.take(oldGroup)) + group->dissolve(); + m_groupNames.removeAll(oldGroup); + m_mirrorGroups.remove(oldGroup); + updateScreenToGroup(); + } + if (!mirror.isEmpty()) { + const QString sourceUuid = uuidForScreen(screen); + const QString mirrorUuid = uuidForScreen(mirror); + if (sourceUuid.isEmpty() || mirrorUuid.isEmpty()) { + // The uuid arrives asynchronously; retry once it is known. + m_pendingMirrorScreen = mirror; + refreshUuids(); + refreshScreenInfo(); + return; + } + m_pendingMirrorScreen.clear(); + + // The compositor assigns the group name; the state of the group is + // reported as soon as it exists, so the mirror is queued right away. + // The group stays pending until the server reports a state with both a + // source and a mirror; a create/add request the server rejects must + // roll the optimistic local maps back instead of leaving a ghost group. + auto *group = new OutputGroup(m_groupManager->createGroup(sourceUuid)); + group->setParent(this); + group->setPending(true); + connect(group, &OutputGroup::nameAssigned, this, + &VirtualClient::onGroupNameAssigned); + connect(group, &OutputGroup::stateChanged, this, + &VirtualClient::onGroupStateChanged); + connect(group, &OutputGroup::removed, this, + &VirtualClient::onGroupObjectRemoved); + connect(group, &OutputGroup::operationFailed, this, + &VirtualClient::onGroupOperationFailed); + group->requestAddMirror(mirrorUuid); + group->commit(); + } + + refreshScreenInfo(); +} + +#include "virtualclient.moc" diff --git a/examples/test_output_manager/virtualclient.h b/examples/test_output_manager/virtualclient.h new file mode 100644 index 0000000000..9b04728655 --- /dev/null +++ b/examples/test_output_manager/virtualclient.h @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "outputuuid.h" +#include "qwayland-treeland-output-manager-unstable-v2.h" + +#include +#include +#include +#include +#include + +class QWidget; +class QLabel; +class QComboBox; +class QSlider; +class QSpinBox; +class QPushButton; +class QTimer; +class OutputGroupManager; +class OutputGroup; +class WlrOutputManager; +class ColorControl; + +// v2 addresses outputs by the uuid served by treeland-output-uuid-v1. +class TreelandOutputManager + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_output_manager_v2 +{ + Q_OBJECT +public: + explicit TreelandOutputManager(); + ~TreelandOutputManager() override; + + void instantiate(); + + struct ::treeland_output_picture_control_v2 *getPictureControl(const QString &uuid); + +Q_SIGNALS: + void primaryOutputChanged(const QString &uuid); + +protected: + void treeland_output_manager_v2_primary_output(const QString &uuid) override + { + Q_EMIT primaryOutputChanged(uuid); + } + +private: +}; + +class VirtualClient : public QObject +{ + Q_OBJECT +public: + explicit VirtualClient(QObject *parent = nullptr); + ~VirtualClient() override; + + bool eventFilter(QObject *watched, QEvent *event) override; + +private: + void setupUi(); + void refreshScreenInfo(); + void refreshMirrorCombo(); + void onScreenChanged(int index); + void onMirrorChanged(int index); + void onDisableClicked(); + void onPrimaryClicked(); + void onResolutionChanged(int resIndex); + void onBrightnessChanged(int value); + void onColorTempChanged(int value); + void onBrightnessSliderReleased(); + void onColorTempSliderReleased(); + void commitBrightness(); + void commitColorTemp(); + void onPrimaryOutputChanged(const QString &uuid); + void updatePrimaryButtonText(); + void applyCurrentSettings(); + void onColorControlBrightness(int percent); + void onColorControlColorTemp(uint32_t kelvin); + void acquireColorControl(const QString &screenName); + void refreshUuids(); + void onUuidReceived(const QString &name, const QString &uuid); + QString uuidForScreen(const QString &name) const; + QString screenForUuid(const QString &uuid) const; + void updatePrimaryLabel(); + void onWlrHeadsChanged(); + void onWlrApplyFinished(bool ok); + + void onGroupAdded(const QString &name); + void onGroupsDone(); + void onGroupRemoved(const QString &name); + void onGroupNameAssigned(const QString &name); + void onGroupStateChanged(const QString &sourceUuid, const QStringList &mirrorUuids); + void onGroupOperationFailed(uint32_t code, const QString &uuid); + void onGroupObjectRemoved(); + void onGroupState(const QString &groupName, + const QString &sourceUuid, + const QStringList &mirrorUuids); + + void updateMirrorGroup(); + void attachGroup(const QString &name); + void updateScreenToGroup(); + QWidget *mirrorComboPopup() const; + + std::unique_ptr m_groupManager; + std::unique_ptr m_treelandManager; + std::unique_ptr m_wlrManager; + std::unique_ptr m_uuidManager; + + QWidget *m_widget = nullptr; + QLabel *m_infoLabel = nullptr; + QComboBox *m_screenCombo = nullptr; + QComboBox *m_mirrorCombo = nullptr; + QPushButton *m_disableBtn = nullptr; + QPushButton *m_primaryBtn = nullptr; + QLabel *m_primaryLabel = nullptr; + + QSlider *m_brightnessSlider = nullptr; + QLabel *m_brightnessLabel = nullptr; + QSlider *m_colorTempSlider = nullptr; + QLabel *m_colorTempLabel = nullptr; + QTimer *m_brightnessCommitTimer = nullptr; + QTimer *m_colorTempCommitTimer = nullptr; + QSpinBox *m_posX = nullptr; + QSpinBox *m_posY = nullptr; + QComboBox *m_resolutionCombo = nullptr; + QComboBox *m_refreshCombo = nullptr; + QComboBox *m_rotationCombo = nullptr; + QComboBox *m_scaleCombo = nullptr; + ColorControl *m_colorControl = nullptr; + QStringList m_screenNames; + QString m_primaryUuid; + QHash m_uuidObjects; + QHash m_uuidByName; + bool m_updatingUi = false; + QMap m_mirrorGroups; + QMap m_screenToGroup; + QMap m_groups; + QStringList m_groupNames; + QString m_pendingMirrorScreen; + bool m_mirrorComboDirty = false; +}; diff --git a/examples/test_output_manager/wlroutputmanager.cpp b/examples/test_output_manager/wlroutputmanager.cpp new file mode 100644 index 0000000000..1e97c75214 --- /dev/null +++ b/examples/test_output_manager/wlroutputmanager.cpp @@ -0,0 +1,313 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wlroutputmanager.h" + +#include "qwayland-wlr-output-management-unstable-v1.h" + +#include + +#include +#include + +#include + +struct ModeEntry { + struct ::zwlr_output_mode_v1 *object = nullptr; + QSize size; + int refresh = 0; + bool preferred = false; +}; + +class ModeTracker : public QtWayland::zwlr_output_mode_v1 +{ +public: + ModeTracker(struct ::zwlr_output_mode_v1 *obj, ModeEntry *entry) + : QtWayland::zwlr_output_mode_v1(obj) + , m_entry(entry) + { + } + + ~ModeTracker() override + { + if (!m_finished && isInitialized()) + release(); + } + +protected: + void zwlr_output_mode_v1_size(int32_t width, int32_t height) override + { + m_entry->size = QSize(width, height); + } + void zwlr_output_mode_v1_refresh(int32_t refresh) override + { + m_entry->refresh = refresh; + } + void zwlr_output_mode_v1_preferred() override + { + m_entry->preferred = true; + } + void zwlr_output_mode_v1_finished() override + { + m_finished = true; + m_entry->object = nullptr; + release(); + } + +private: + ModeEntry *m_entry = nullptr; + bool m_finished = false; +}; + +// Kept in an anonymous namespace to give it internal linkage: the example links +// several .cpp files together, and outputuuid.h also defines a global-scope +// HeadTracker with a different set of overridden events. Two external-linkage +// classes with the same name in one program is an ODR violation whose weak +// vtable symbols get merged by the linker, causing virtual dispatch to the +// wrong override set (and here, a crash in WlrOutputManager::heads()). +namespace { +class HeadTracker : public QtWayland::zwlr_output_head_v1 +{ +public: + HeadTracker(struct ::zwlr_output_head_v1 *obj) + : QtWayland::zwlr_output_head_v1(obj) + { + } + + ~HeadTracker() override + { + if (!m_finished && isInitialized()) + release(); + } + + QString name; + QString description; + bool enabled = false; + QPoint position; + int transform = 0; + double scale = 1.0; + QSize physicalSize; + std::vector> modes; + std::vector> modeTrackers; + int currentModeIndex = -1; + bool finished = false; + +protected: + void zwlr_output_head_v1_name(const QString &name) override { this->name = name; } + void zwlr_output_head_v1_description(const QString &desc) override { this->description = desc; } + void zwlr_output_head_v1_physical_size(int32_t w, int32_t h) override + { + physicalSize = QSize(w, h); + } + void zwlr_output_head_v1_mode(struct ::zwlr_output_mode_v1 *mode) override + { + auto entry = std::make_unique(); + entry->object = mode; + modeTrackers.push_back(std::make_unique(mode, entry.get())); + modes.push_back(std::move(entry)); + } + void zwlr_output_head_v1_enabled(int32_t e) override { enabled = e != 0; } + void zwlr_output_head_v1_current_mode(struct ::zwlr_output_mode_v1 *mode) override + { + for (size_t i = 0; i < modes.size(); ++i) { + if (modes[i]->object == mode) { + currentModeIndex = static_cast(i); + return; + } + } + } + void zwlr_output_head_v1_position(int32_t x, int32_t y) override { position = QPoint(x, y); } + void zwlr_output_head_v1_transform(int32_t t) override { transform = t; } + void zwlr_output_head_v1_scale(wl_fixed_t s) override { scale = wl_fixed_to_double(s); } + void zwlr_output_head_v1_finished() override + { + m_finished = true; + finished = true; + release(); + } + void zwlr_output_head_v1_make(const QString &) override { /* not needed */ } + void zwlr_output_head_v1_model(const QString &) override { /* not needed */ } + void zwlr_output_head_v1_serial_number(const QString &) override { /* not needed */ } + void zwlr_output_head_v1_adaptive_sync(uint32_t) override { /* not needed */ } + +private: + bool m_finished = false; +}; +} // namespace + +class ConfigWatcher : public QObject, public QtWayland::zwlr_output_configuration_v1 +{ + Q_OBJECT +public: + ConfigWatcher(struct ::zwlr_output_configuration_v1 *obj, QObject *parent) + : QObject(parent) + , QtWayland::zwlr_output_configuration_v1(obj) + { + } + +Q_SIGNALS: + void result(bool ok); + +protected: + void zwlr_output_configuration_v1_succeeded() override + { + Q_EMIT result(true); + destroy(); + deleteLater(); + } + void zwlr_output_configuration_v1_failed() override + { + Q_EMIT result(false); + destroy(); + deleteLater(); + } + void zwlr_output_configuration_v1_cancelled() override + { + Q_EMIT result(false); + destroy(); + deleteLater(); + } +}; + + +class WlrOutputManagerPrivate +{ +public: + std::vector> heads; + uint32_t serial = 0; + bool finished = false; +}; + + +WlrOutputManager::WlrOutputManager() + : QWaylandClientExtensionTemplate(4) + , d(std::make_unique()) +{ +} + +WlrOutputManager::~WlrOutputManager() = default; + +void WlrOutputManager::instantiate() +{ + initialize(); +} + +QVector WlrOutputManager::heads() const +{ + QVector result; + for (const auto &ht : d->heads) { + if (ht->name.isEmpty()) + continue; + Head h; + h.name = ht->name; + h.description = ht->description; + h.enabled = ht->enabled; + h.position = ht->position; + h.transform = ht->transform; + h.scale = ht->scale; + h.physicalSize = ht->physicalSize; + int newIdx = 0; + h.currentMode = -1; + for (size_t i = 0; i < ht->modes.size(); ++i) { + const auto &m = ht->modes[i]; + if (!m->object) + continue; + if (static_cast(i) == ht->currentModeIndex) + h.currentMode = newIdx; + h.modes.append({m->size, m->refresh, m->preferred}); + ++newIdx; + } + result.append(h); + } + return result; +} + + +uint32_t WlrOutputManager::serial() const { return d->serial; } +void WlrOutputManager::applyConfig(const QString &headName, + bool enabled, + const QPoint &position, + const QSize &modeSize, + int refresh, + int transform, + double scale) +{ + if (!isActive() || d->heads.empty() || d->finished) { + qWarning() << "WlrOutputManager: applyConfig skipped (manager inactive/finished or no heads)"; + return; + } + + struct ::zwlr_output_configuration_v1 *configObj = create_configuration(d->serial); + if (!configObj) + return; + + auto *watcher = new ConfigWatcher(configObj, this); + connect(watcher, &ConfigWatcher::result, this, &WlrOutputManager::applyFinished); + + for (const auto &ht : d->heads) { + if (ht->name.isEmpty()) + continue; + if (ht->name == headName) { + if (!enabled) { + watcher->disable_head(ht->object()); + } else { + auto *cfgHead = watcher->enable_head(ht->object()); + QtWayland::zwlr_output_configuration_head_v1 cfg(cfgHead); + cfg.set_position(position.x(), position.y()); + bool modeSet = false; + for (const auto &mode : ht->modes) { + if (mode->object && mode->size == modeSize && (refresh <= 0 || mode->refresh == refresh)) { + cfg.set_mode(mode->object); + modeSet = true; + break; + } + } + if (!modeSet && !modeSize.isEmpty()) { + cfg.set_custom_mode(modeSize.width(), modeSize.height(), refresh); + } else if (!modeSet && ht->currentModeIndex >= 0 + && static_cast(ht->currentModeIndex) < ht->modes.size()) { + auto *mObj = ht->modes[ht->currentModeIndex]->object; + if (mObj) + cfg.set_mode(mObj); + } + cfg.set_transform(transform); + cfg.set_scale(wl_fixed_from_double(scale)); + } + } else if (ht->enabled) { + auto *cfgHead = watcher->enable_head(ht->object()); + QtWayland::zwlr_output_configuration_head_v1 cfg(cfgHead); + cfg.set_position(ht->position.x(), ht->position.y()); + if (ht->currentModeIndex >= 0 && static_cast(ht->currentModeIndex) < ht->modes.size()) { + auto *mObj = ht->modes[ht->currentModeIndex]->object; + if (mObj) + cfg.set_mode(mObj); + } + cfg.set_transform(ht->transform); + cfg.set_scale(wl_fixed_from_double(ht->scale)); + } else { + watcher->disable_head(ht->object()); + } + } + watcher->apply(); +} + +void WlrOutputManager::zwlr_output_manager_v1_head(struct ::zwlr_output_head_v1 *head) +{ + d->heads.push_back(std::make_unique(head)); +} + +void WlrOutputManager::zwlr_output_manager_v1_done(uint32_t serial) +{ + d->serial = serial; + d->heads.erase(std::remove_if(d->heads.begin(), d->heads.end(), + [](const auto &ht) { return ht->finished; }), + d->heads.end()); + Q_EMIT headsChanged(); +} + +void WlrOutputManager::zwlr_output_manager_v1_finished() +{ + d->finished = true; +} + +#include "wlroutputmanager.moc" \ No newline at end of file diff --git a/examples/test_output_manager/wlroutputmanager.h b/examples/test_output_manager/wlroutputmanager.h new file mode 100644 index 0000000000..c798d82103 --- /dev/null +++ b/examples/test_output_manager/wlroutputmanager.h @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "qwayland-wlr-output-management-unstable-v1.h" + +#include +#include +#include +#include + +#include + +class WlrOutputManagerPrivate; + +class WlrOutputManager + : public QWaylandClientExtensionTemplate + , public QtWayland::zwlr_output_manager_v1 +{ + Q_OBJECT +public: + struct Mode { + QSize size; + int refresh = 0; + bool preferred = false; + }; + + struct Head { + QString name; + QString description; + bool enabled = false; + QPoint position; + int transform = 0; + double scale = 1.0; + QSize physicalSize; + QVector modes; + int currentMode = -1; + }; + + explicit WlrOutputManager(); + ~WlrOutputManager() override; + + void instantiate(); + + QVector heads() const; + uint32_t serial() const; + + void applyConfig(const QString &headName, + bool enabled, + const QPoint &position, + const QSize &modeSize, + int refresh, + int transform, + double scale); + +Q_SIGNALS: + void headsChanged(); + void applyFinished(bool ok); + +protected: + void zwlr_output_manager_v1_head(struct ::zwlr_output_head_v1 *head) override; + void zwlr_output_manager_v1_done(uint32_t serial) override; + void zwlr_output_manager_v1_finished() override; + +private: + std::unique_ptr d; +}; \ No newline at end of file diff --git a/examples/test_pinch_handler/CMakeLists.txt b/examples/test_pinch_handler/CMakeLists.txt new file mode 100644 index 0000000000..76d454a643 --- /dev/null +++ b/examples/test_pinch_handler/CMakeLists.txt @@ -0,0 +1,24 @@ +set(BIN_NAME test-pinch-handler) + +find_package(Qt6 REQUIRED COMPONENTS Gui Quick) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +qt_add_qml_module(${BIN_NAME} + URI pinchhandler + VERSION 1.0 + QML_FILES Main.qml + SOURCES eventitem.cpp +) + +target_link_libraries(${BIN_NAME} + PRIVATE Qt6::Gui + Qt6::Quick +) + +install(TARGETS ${BIN_NAME} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) diff --git a/examples/test_pinch_handler/Main.qml b/examples/test_pinch_handler/Main.qml new file mode 100644 index 0000000000..f78bd477ca --- /dev/null +++ b/examples/test_pinch_handler/Main.qml @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Window +import QtQuick.Controls +import pinchhandler + +Window { + width: 1000 + height: 800 + visible: true + title: handler.persistentRotation.toFixed(1) + "° " + + handler.persistentTranslation.x.toFixed(1) + ", " + + handler.persistentTranslation.y.toFixed(1) + " " + + (handler.persistentScale * 100).toFixed(1) + "%" + + Flickable { + id: flickable + anchors.fill: parent + contentWidth: map.width * handler.persistentScale + contentHeight: map.height * handler.persistentScale + clip: true + + Rectangle { + id: map + color: "aqua" + width: 1000 + height: 1000 + + border.width: 1 + border.color: "black" + gradient: Gradient { + GradientStop { position: 0.0; color: "blue" } + GradientStop { position: 1.0; color: "green" } + } + Text { + text: qsTr("This is a PinchHandler Demo!") + color: "white" + anchors.centerIn: parent + } + } + } + + PinchHandler { + id: handler + target: map + onScaleChanged: { + flickable.contentWidth = map.width * handler.persistentScale + flickable.contentHeight = map.height * handler.persistentScale + } + onTranslationChanged: { + flickable.contentX = handler.persistentTranslation.x + flickable.contentY = handler.persistentTranslation.y + } + onActiveChanged: { + if (!active) { + flickable.returnToBounds() + } + } + } + + EventItem { + id: eventItem + anchors.fill: parent + } + +} diff --git a/examples/test_pinch_handler/eventitem.cpp b/examples/test_pinch_handler/eventitem.cpp new file mode 100644 index 0000000000..1f283b4f90 --- /dev/null +++ b/examples/test_pinch_handler/eventitem.cpp @@ -0,0 +1,68 @@ +// Copyright (C) 2024 groveer . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "eventitem.h" + +EventItem::EventItem(QQuickItem *parent) + : QQuickItem(parent) +{ + setAcceptHoverEvents(true); + setAcceptTouchEvents(true); + setAcceptedMouseButtons(Qt::AllButtons); + setFlag(QQuickItem::ItemClipsChildrenToShape, true); +} + +bool EventItem::event(QEvent *event) +{ + qWarning() << "EventItem::event: " << event->type(); + switch (event->type()) { + using enum QEvent::Type; + // Don't insert events before MouseButtonPress + case MouseButtonPress: + Q_FALLTHROUGH(); + case MouseButtonRelease: + Q_FALLTHROUGH(); + case MouseMove: + if (static_cast(event)->source() != Qt::MouseEventNotSynthesized) + return true; // The non-native events don't send to WSeat + Q_FALLTHROUGH(); + case HoverMove: + Q_FALLTHROUGH(); + case HoverEnter: + Q_FALLTHROUGH(); + case HoverLeave: + Q_FALLTHROUGH(); + case KeyPress: + Q_FALLTHROUGH(); + case KeyRelease: + Q_FALLTHROUGH(); + case Wheel: + Q_FALLTHROUGH(); + case TouchBegin: + Q_FALLTHROUGH(); + case TouchUpdate: + Q_FALLTHROUGH(); + case TouchEnd: + Q_FALLTHROUGH(); + case TouchCancel: { + auto e = static_cast(event); + Q_ASSERT(e); + // We may receive HoverLeave when WSurfaceItem was destroying + break; + } + case NativeGesture: { + auto e = static_cast(event); + Q_ASSERT(e); + // We may receive HoverLeave when WSurfaceItem was destroying + qWarning() << "received app type: " << e->gestureType() << " delta: " << e->delta() + << "value:" << e->value(); + break; + } + // No need to process focusOut, see [PR + // 282](https://github.com/vioken/waylib/pull/282) + default: + break; + } + + return QQuickItem::event(event); +} diff --git a/examples/test_pinch_handler/eventitem.h b/examples/test_pinch_handler/eventitem.h new file mode 100644 index 0000000000..30f562df75 --- /dev/null +++ b/examples/test_pinch_handler/eventitem.h @@ -0,0 +1,20 @@ +// Copyright (C) 2024 groveer . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include + +class Q_DECL_HIDDEN EventItem : public QQuickItem +{ + Q_OBJECT + QML_NAMED_ELEMENT(EventItem) +public: + explicit EventItem(QQuickItem *parent = nullptr); + + inline bool isValid() const + { + return parent(); + } + +private: + bool event(QEvent *event) override; +}; diff --git a/examples/test_pinch_handler/main.cpp b/examples/test_pinch_handler/main.cpp new file mode 100644 index 0000000000..5cb4be5b2b --- /dev/null +++ b/examples/test_pinch_handler/main.cpp @@ -0,0 +1,27 @@ +// Copyright (C) 2023 rewine . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include + +int main(int argc, char *argv[]) +{ + qputenv("QT_QPA_PLATFORM", "wayland"); + + QGuiApplication app(argc, argv); + + QQmlApplicationEngine engine; + using namespace Qt::StringLiterals; + const QUrl url(u"qrc:/qt/qml/pinchhandler/Main.qml"_s); + QObject::connect( + &engine, + &QQmlApplicationEngine::objectCreationFailed, + &app, + []() { + QCoreApplication::exit(-1); + }, + Qt::QueuedConnection); + engine.load(url); + + return app.exec(); +} diff --git a/examples/test_region_watch/CMakeLists.txt b/examples/test_region_watch/CMakeLists.txt new file mode 100644 index 0000000000..0107246bdd --- /dev/null +++ b/examples/test_region_watch/CMakeLists.txt @@ -0,0 +1,21 @@ +find_package(Qt6 REQUIRED COMPONENTS Gui WaylandClient) +find_package(TreelandProtocols REQUIRED) + +set(BIN_NAME test-region-watch) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-region-watch-unstable-v1.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::WaylandClient +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_region_watch/main.cpp b/examples/test_region_watch/main.cpp new file mode 100644 index 0000000000..8ea19962ab --- /dev/null +++ b/examples/test_region_watch/main.cpp @@ -0,0 +1,197 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// Test application for treeland_region_watch_manager_v1 +// (treeland-region-watch-unstable-v1). +// Monitors an edge-anchored region of the first screen and prints +// enter/leave/output_removed transitions to the console. +// +// Usage: test-region-watch [--anchor top|bottom|left|right] [--width W] [--height H] [--screen NAME] + +#include "qwayland-treeland-region-watch-unstable-v1.h" + +#include +#include +#include +#include + +#include + +static QNativeInterface::QWaylandScreen *waylandScreenFor(const QString &name) +{ + const auto screens = QGuiApplication::screens(); + for (QScreen *screen : screens) { + if (!name.isEmpty() && QString::compare(screen->name(), name, Qt::CaseInsensitive) != 0) + continue; + if (auto *waylandScreen = screen->nativeInterface()) + return waylandScreen; + } + return nullptr; +} + +static QString anchorName(uint32_t anchor) +{ + switch (anchor) { + case QtWayland::treeland_region_watch_v1::anchor_top: + return QStringLiteral("top"); + case QtWayland::treeland_region_watch_v1::anchor_bottom: + return QStringLiteral("bottom"); + case QtWayland::treeland_region_watch_v1::anchor_left: + return QStringLiteral("left"); + case QtWayland::treeland_region_watch_v1::anchor_right: + return QStringLiteral("right"); + } + return QStringLiteral("unknown"); +} + +class RegionWatchV1 : public QtWayland::treeland_region_watch_v1 +{ +public: + explicit RegionWatchV1(struct ::treeland_region_watch_v1 *object) + : QtWayland::treeland_region_watch_v1(object) + { + } + + ~RegionWatchV1() override + { + destroy(); + } + +protected: + void treeland_region_watch_v1_enter() override + { + qWarning() << "enter: region is overlapped by a toplevel window"; + } + + void treeland_region_watch_v1_leave() override + { + qWarning() << "leave: region is clear"; + } + + void treeland_region_watch_v1_output_removed() override + { + qWarning() << "output_removed: watcher is inert until the next set_region"; + } +}; + +class RegionWatchManagerV1 + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_region_watch_manager_v1 +{ + Q_OBJECT +public: + static constexpr int InterfaceVersion = 1; + + explicit RegionWatchManagerV1() + : QWaylandClientExtensionTemplate(InterfaceVersion) + { + } +}; + +int main(int argc, char *argv[]) +{ + qputenv("QT_QPA_PLATFORM", "wayland"); + QGuiApplication app(argc, argv); + + QCommandLineParser parser; + parser.setApplicationDescription(QStringLiteral("Treeland Region Watch Test Client")); + parser.addHelpOption(); + + QCommandLineOption anchorOption( + QStringList() << "a" << "anchor", + QStringLiteral("Edge to anchor the region to: top, bottom, left, right (default: top)."), + QStringLiteral("edge"), + QStringLiteral("top")); + parser.addOption(anchorOption); + + QCommandLineOption widthOption( + QStringList() << "w" << "width", + QStringLiteral("Thickness in the anchored direction for left/right (default: 40)."), + QStringLiteral("pixels"), + QStringLiteral("40")); + parser.addOption(widthOption); + + QCommandLineOption heightOption( + QStringList() << "H" << "height", + QStringLiteral("Thickness in the anchored direction for top/bottom (default: 40)."), + QStringLiteral("pixels"), + QStringLiteral("40")); + parser.addOption(heightOption); + + QCommandLineOption screenOption( + QStringList() << "s" << "screen", + QStringLiteral("Screen name to monitor (default: first screen)."), + QStringLiteral("name")); + parser.addOption(screenOption); + + parser.process(app); + + uint32_t anchor = QtWayland::treeland_region_watch_v1::anchor_top; + const QString anchorValue = parser.value(anchorOption).toLower(); + if (anchorValue == QLatin1String("top")) { + anchor = QtWayland::treeland_region_watch_v1::anchor_top; + } else if (anchorValue == QLatin1String("bottom")) { + anchor = QtWayland::treeland_region_watch_v1::anchor_bottom; + } else if (anchorValue == QLatin1String("left")) { + anchor = QtWayland::treeland_region_watch_v1::anchor_left; + } else if (anchorValue == QLatin1String("right")) { + anchor = QtWayland::treeland_region_watch_v1::anchor_right; + } else { + qCritical() << "Unknown anchor:" << anchorValue + << "(expected: top, bottom, left, right)"; + return EXIT_FAILURE; + } + + bool widthOk = false; + const int width = parser.value(widthOption).toInt(&widthOk); + if (!widthOk || width <= 0) { + qCritical() << "Invalid --width:" << parser.value(widthOption); + return EXIT_FAILURE; + } + + bool heightOk = false; + const int height = parser.value(heightOption).toInt(&heightOk); + if (!heightOk || height <= 0) { + qCritical() << "Invalid --height:" << parser.value(heightOption); + return EXIT_FAILURE; + } + + auto *manager = new RegionWatchManagerV1(); + + QObject::connect(manager, &RegionWatchManagerV1::activeChanged, manager, + [manager, anchor, width, height, screen = parser.value(screenOption)]() { + if (!manager->isActive()) { + qWarning() << "Protocol not available."; + return; + } + + auto *waylandScreen = waylandScreenFor(screen); + if (!waylandScreen) { + qCritical() << "Screen not found:" << screen; + qApp->exit(EXIT_FAILURE); + return; + } + + auto *raw = manager->get_region_watch(); + if (!raw) { + qCritical() << "Failed to create region watch."; + qApp->exit(EXIT_FAILURE); + return; + } + + auto *watch = new RegionWatchV1(raw); + QObject::connect(qGuiApp, &QCoreApplication::aboutToQuit, qGuiApp, [watch] { + delete watch; + }); + + watch->set_region(width, height, anchor, waylandScreen->output()); + + qWarning() << "Watching region: anchor" << anchorName(anchor) + << "width" << width << "height" << height + << "screen" << (screen.isEmpty() ? QStringLiteral("") : screen); + }); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/test_set_wallpaper/CMakeLists.txt b/examples/test_set_wallpaper/CMakeLists.txt new file mode 100644 index 0000000000..6ed4a9e674 --- /dev/null +++ b/examples/test_set_wallpaper/CMakeLists.txt @@ -0,0 +1,30 @@ +find_package(Qt6 COMPONENTS REQUIRED Gui DBus WaylandClient) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 COMPONENTS GuiPrivate WaylandClientPrivate REQUIRED) +endif() + +find_package(TreelandProtocols REQUIRED) + +set(BIN_NAME test-set-wallpaper) + +qt_add_executable(${BIN_NAME} + main.cpp + treelandwallpapermanagerclient.h + treelandwallpapermanagerclient.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wallpaper-manager-unstable-v1.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::GuiPrivate + Qt6::WaylandClient + Qt6::WaylandClientPrivate +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") + diff --git a/examples/test_set_wallpaper/main.cpp b/examples/test_set_wallpaper/main.cpp new file mode 100644 index 0000000000..c21970580b --- /dev/null +++ b/examples/test_set_wallpaper/main.cpp @@ -0,0 +1,164 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "treelandwallpapermanagerclient.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static QScreen *findScreenByName(const QString &name) +{ + if (name.isEmpty()) + return nullptr; + + const auto screens = QGuiApplication::screens(); + for (QScreen *screen : screens) { + if (screen->name() == name) + return screen; + } + + return nullptr; +} + +static bool isImageFile(const QString &path) +{ + static QMimeDatabase db; + const QMimeType mime = db.mimeTypeForFile(path, QMimeDatabase::MatchContent); + return mime.isValid() && mime.name().startsWith("image/"); +} + +static bool isVideoFile(const QString &path) +{ + static QMimeDatabase db; + const QMimeType mime = db.mimeTypeForFile(path, QMimeDatabase::MatchContent); + return mime.isValid() && mime.name().startsWith("video/"); +} + +static uint32_t +parseRole(const QString &role) +{ + using Role = QtWayland::treeland_wallpaper_v1::wallpaper_role; + + if (role == "desktop") + return Role::wallpaper_role_desktop; + if (role == "lockscreen") + return Role::wallpaper_role_lockscreen; + if (role == "both") + return Role::wallpaper_role_desktop | Role::wallpaper_role_lockscreen; + + return Role::wallpaper_role_desktop; // default +} + +int main(int argc, char *argv[]) +{ + if (qEnvironmentVariableIsEmpty("QT_QPA_PLATFORM")) + qputenv("QT_QPA_PLATFORM", "wayland"); + + QGuiApplication app(argc, argv); + + QCommandLineParser parser; + parser.setApplicationDescription(QStringLiteral("Treeland Wallpaper Client")); + parser.addHelpOption(); + + QCommandLineOption outputNameOption( + QStringLiteral("output"), + QStringLiteral("Wayland output name (e.g. eDP-1, HDMI-1). Same as wlr-randr output name."), + QStringLiteral("output-name") + ); + parser.addOption(outputNameOption); + QCommandLineOption pathOption( + QStringLiteral("path"), + QStringLiteral("Wallpaper path (image or video)."), + QStringLiteral("file-path") + ); + parser.addOption(pathOption); + + QCommandLineOption roleOption( + QStringLiteral("role"), + QStringLiteral("Wallpaper role: desktop | lockscreen | both."), + QStringLiteral("role"), + QStringLiteral("desktop") + ); + parser.addOption(roleOption); + parser.process(app); + + const QString outputName = parser.value(outputNameOption); + QScreen *targetScreen = findScreenByName(outputName); + + if (!targetScreen) { + qCritical().noquote() + << "Cannot find QScreen for output:" << outputName + << "\nAvailable outputs are:"; + const auto screens = QGuiApplication::screens(); + for (QScreen *screen : screens) + qCritical() << " -" << screen->name(); + return EXIT_FAILURE; + } + + const QString wallpaperPath = parser.value(pathOption); + const QString roleString = parser.value(roleOption); + + if (wallpaperPath.isEmpty()) { + qCritical() << "--path is required"; + return EXIT_FAILURE; + } + + TreelandWallpaperManagerV1 *wallpaperManager = new TreelandWallpaperManagerV1; + QObject::connect(wallpaperManager, &TreelandWallpaperManagerV1::activeChanged, [&] { + if (wallpaperManager->isActive()) { + if (!targetScreen) { + qWarning() << "createWallpaper called with null QScreen"; + qApp->exit(EXIT_FAILURE); + return; + } + + auto *nativeInterface = qGuiApp->platformNativeInterface(); + if (!nativeInterface) { + qCritical() << "No QPlatformNativeInterface available"; + qApp->exit(EXIT_FAILURE); + return; + } + + wl_output *wlOutput = static_cast( + nativeInterface->nativeResourceForScreen( + QByteArrayLiteral("output"), targetScreen)); + + if (!wlOutput) { + qCritical() << "Failed to get wl_output for screen:" << targetScreen->name(); + qApp->exit(EXIT_FAILURE); + return; + } + + auto *object = wallpaperManager->get_treeland_wallpaper(wlOutput, nullptr); + if (!object) { + qCritical() << "treeland_wallpaper_manager_v1 returned null object"; + qApp->exit(EXIT_FAILURE); + return; + } + TreelandWallpaperV1 *wallpaper = new TreelandWallpaperV1(object); + const uint32_t role = parseRole(roleString); + if (isImageFile(wallpaperPath)) { + wallpaper->set_image_source(wallpaperPath, role); + } else if (isVideoFile(wallpaperPath)) { + wallpaper->set_video_source(wallpaperPath, role); + } else { + qCritical() << "Unsupported wallpaper file type:" << wallpaperPath; + delete wallpaper; + delete wallpaperManager; + qApp->exit(EXIT_FAILURE); + return; + } + } + }); + wallpaperManager->instantiate(); + + return app.exec(); +} diff --git a/examples/test_set_wallpaper/treelandwallpapermanagerclient.cpp b/examples/test_set_wallpaper/treelandwallpapermanagerclient.cpp new file mode 100644 index 0000000000..f18a9d1cc4 --- /dev/null +++ b/examples/test_set_wallpaper/treelandwallpapermanagerclient.cpp @@ -0,0 +1,48 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "treelandwallpapermanagerclient.h" + +#include + +TreelandWallpaperManagerV1::TreelandWallpaperManagerV1() + : QWaylandClientExtensionTemplate(InterfaceVersion) + , QtWayland::treeland_wallpaper_manager_v1() +{ +} + +TreelandWallpaperManagerV1::~TreelandWallpaperManagerV1() +{ + if (isInitialized()) + destroy(); +} + +void TreelandWallpaperManagerV1::instantiate() +{ + initialize(); +} + +TreelandWallpaperV1::TreelandWallpaperV1(struct ::treeland_wallpaper_v1 *object) + : QtWayland::treeland_wallpaper_v1(object) +{ +} + +TreelandWallpaperV1::~TreelandWallpaperV1() +{ + destroy(); +} + +void TreelandWallpaperV1::treeland_wallpaper_v1_failed(const QString &source, uint32_t error) +{ + qWarning() << "treeland_wallpaper_v1_failed:" << source << error; +} + +void TreelandWallpaperV1::treeland_wallpaper_v1_changed(uint32_t role, + uint32_t sourceType, + const QString &fileSource) +{ + qWarning() << "treeland_wallpaper_v1_changed, role:" + << role << ", source type:" + << sourceType << ", file:" + << fileSource; +} diff --git a/examples/test_set_wallpaper/treelandwallpapermanagerclient.h b/examples/test_set_wallpaper/treelandwallpapermanagerclient.h new file mode 100644 index 0000000000..cbaeb406f4 --- /dev/null +++ b/examples/test_set_wallpaper/treelandwallpapermanagerclient.h @@ -0,0 +1,36 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "qwayland-treeland-wallpaper-manager-unstable-v1.h" + +#include + +class TreelandWallpaperV1; + +class TreelandWallpaperManagerV1 + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_wallpaper_manager_v1 +{ + Q_OBJECT +public: + static constexpr int InterfaceVersion = 1; + explicit TreelandWallpaperManagerV1(); + ~TreelandWallpaperManagerV1() override; + + void instantiate(); +}; + +class TreelandWallpaperV1 : public QtWayland::treeland_wallpaper_v1 +{ +public: + explicit TreelandWallpaperV1(struct ::treeland_wallpaper_v1 *object); + ~TreelandWallpaperV1() override; + +protected: + void treeland_wallpaper_v1_failed(const QString &source, uint32_t error) override; + void treeland_wallpaper_v1_changed(uint32_t role, + uint32_t sourceType, + const QString &fileSource) override; +}; diff --git a/examples/test_set_xwindow_position/CMakeLists.txt b/examples/test_set_xwindow_position/CMakeLists.txt new file mode 100644 index 0000000000..69af348c64 --- /dev/null +++ b/examples/test_set_xwindow_position/CMakeLists.txt @@ -0,0 +1,25 @@ +find_package(Qt6 COMPONENTS REQUIRED Gui WaylandClient Widgets) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 COMPONENTS GuiPrivate WaylandClientPrivate REQUIRED) +endif() +find_package(TreelandProtocols REQUIRED) + +qt_add_executable(test-set-xwindow-position + main.cpp +) + +qt_generate_wayland_protocol_client_sources(test-set-xwindow-position + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-xwindow-control-unstable-v1.xml + NO_INCLUDE_CORE_ONLY +) + +target_link_libraries(test-set-xwindow-position + PRIVATE + Qt6::Gui + Qt6::GuiPrivate + Qt6::Widgets + Qt6::WaylandClient +) + +install(TARGETS test-set-xwindow-position RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_set_xwindow_position/main.cpp b/examples/test_set_xwindow_position/main.cpp new file mode 100644 index 0000000000..a7eea92a96 --- /dev/null +++ b/examples/test_set_xwindow_position/main.cpp @@ -0,0 +1,113 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include + +class XWindowControlV1 + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_xwindow_control_v1 +{ + Q_OBJECT +public: + XWindowControlV1() + : QWaylandClientExtensionTemplate( + treeland_xwindow_control_v1_interface.version) + { + } +}; + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + auto runCommand = [](const char *cmd, const char *desc) { + const int rc = std::system(cmd); + if (rc == -1) { + qCritical() << "Failed to execute command:" << desc; + return; + } + if (rc != 0) + qWarning() << "Command exited with non-zero status:" << desc << rc; + }; + + qWarning() + << "In this example, an xeyes will be launched. Its window will be moved to (0, 0) " + "first using X API. Then, A test window of size 640x480 will be created. The xeyes " + "window will be moved to the top-right of the test window once per second using " + "set_xwindow_position_relative().\n\n" + "xeyes should be installed to run this example (sudo apt install x11-apps)."; + + runCommand("bash -c \"pkill xeyes; xeyes & disown\"", "start xeyes"); + sleep(1); + runCommand("xdotool search --name \"xeyes\" windowmove 0 0", "move xeyes to (0,0)"); + sleep(1); + runCommand("xdotool search --name \"xeyes\" > /tmp/xeyes_wid.txt", "write xeyes wid"); + + QWidget *window = new QWidget(); + window->resize(640, 480); + window->setWindowTitle("Test set xwindow position"); + window->show(); + + uint32_t wid = 0; + QFile file("/tmp/xeyes_wid.txt"); + if (file.open(QIODevice::ReadWrite)) { + wid = file.readLine().trimmed().toUInt(); + file.close(); + file.remove(); + } else { + qCritical() << "Failed to open /tmp/xeyes_wid.txt"; + return 1; + } + + XWindowControlV1 control; + + struct wl_callback_listener callback_listener = { .done = []([[maybe_unused]] void *data, + wl_callback *callback, + uint32_t ok) { + wl_callback_destroy(callback); + if (ok != 0) + qCritical() << "Failed to set xwindow position relative!"; + else + qWarning() << "Successfully set xwindow position relative. Check screen for result."; + } }; + + QTimer timer; + QObject::connect(&timer, &QTimer::timeout, [&] { + if (!control.isActive()) { + qCritical() << "XWindowControlV1 is not active!"; + return; + } + struct wl_surface *surface = static_cast( + QGuiApplication::platformNativeInterface()->nativeResourceForWindow( + QStringLiteral("surface").toLocal8Bit(), + window->windowHandle())); + + wl_fixed_t dx = wl_fixed_from_int(640); + wl_fixed_t dy = wl_fixed_from_int(0); + + wl_callback *callback = control.set_xwindow_position_relative(wid, surface, dx, dy); + if (!callback) { + qCritical() << "Failed to send set_xwindow_position_relative request!"; + return; + } + wl_callback_add_listener(callback, &callback_listener, nullptr); + qWarning() << "Setting xwindow position relative, wait for result..."; + }); + timer.start(1000); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/test_shortcut_capture/CMakeLists.txt b/examples/test_shortcut_capture/CMakeLists.txt new file mode 100644 index 0000000000..eb3b9918f3 --- /dev/null +++ b/examples/test_shortcut_capture/CMakeLists.txt @@ -0,0 +1,27 @@ +find_package(Qt6 REQUIRED COMPONENTS Gui WaylandClient Widgets) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS GuiPrivate WaylandClientPrivate) +endif() +find_package(TreelandProtocols REQUIRED) + +set(BIN_NAME test-shortcut-capture) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-shortcut-manager-unstable-v3.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::Widgets + Qt6::WaylandClient + Qt6::GuiPrivate + Qt6::WaylandClientPrivate +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_shortcut_capture/main.cpp b/examples/test_shortcut_capture/main.cpp new file mode 100644 index 0000000000..7dd4c0f4ea --- /dev/null +++ b/examples/test_shortcut_capture/main.cpp @@ -0,0 +1,164 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// Test application for treeland_shortcut_capture_v3 (treeland-shortcut-manager-unstable-v3, version 1). +// A window with a single button: click to request one-shot shortcut capture. +// The captured key sequence or failure reason is shown below the button. + +#include "qwayland-treeland-shortcut-manager-unstable-v3.h" + +#include + +#include +#include +#include +#include +#include +#include + +// Wraps the treeland_shortcut_capture_v3 Wayland object and emits Qt signals. +class ShortcutCapture + : public QObject + , public QtWayland::treeland_shortcut_capture_v3 +{ + Q_OBJECT +public: + explicit ShortcutCapture(struct ::treeland_shortcut_capture_v3 *capture, + QObject *parent = nullptr) + : QObject(parent) + , QtWayland::treeland_shortcut_capture_v3(capture) + { + } + + ~ShortcutCapture() override + { + destroy(); + } + +Q_SIGNALS: + void captured(const QString &key); + void failed(uint32_t reason); + +protected: + void treeland_shortcut_capture_v3_captured(const QString &key) override + { + Q_EMIT captured(key); + deleteLater(); + } + + void treeland_shortcut_capture_v3_failed(uint32_t reason) override + { + Q_EMIT failed(reason); + deleteLater(); + } +}; + +class ShortcutManagerV3 + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_shortcut_manager_v3 +{ + Q_OBJECT +public: + explicit ShortcutManagerV3() + : QWaylandClientExtensionTemplate(1) + { + } + + // Request one-shot shortcut capture for the given window surface. + // Returns a ShortcutCapture object whose signals deliver the result. + ShortcutCapture *captureNextShortcut(QWindow *window, QObject *parent = nullptr) + { + if (!window || !window->handle()) + return nullptr; + auto *waylandWindow = + static_cast(window->handle()); + auto *wlSurface = waylandWindow->wlSurface(); + if (!wlSurface) + return nullptr; + + auto *raw = capture_next_shortcut(wlSurface, nullptr); + if (!raw) + return nullptr; + return new ShortcutCapture(raw, parent); + } +}; + +static QString cancelReasonText(uint32_t reason) +{ + using R = QtWayland::treeland_shortcut_capture_v3; + switch (static_cast(reason)) { + case R::failed_reason_busy: + return QStringLiteral("Another capture is already in progress (busy)"); + case R::failed_reason_aborted: + return QStringLiteral("The compositor aborted the capture (aborted)"); + case R::failed_reason_not_active: + return QStringLiteral("The window is not active (not_active)"); + case R::failed_reason_interrupted: + return QStringLiteral("Capture was interrupted by non-shortcut input (interrupted)"); + default: + return QStringLiteral("Unknown reason (%1)").arg(reason); + } +} + +int main(int argc, char *argv[]) +{ + qputenv("QT_QPA_PLATFORM", "wayland"); + QApplication app(argc, argv); + + ShortcutManagerV3 manager; + + // Main window + QWidget window; + window.setWindowTitle(QStringLiteral("Shortcut Capture Test")); + window.resize(360, 160); + + QVBoxLayout *layout = new QVBoxLayout(&window); + + QPushButton *btn = new QPushButton(QStringLiteral("Request Shortcut Capture"), &window); + QLabel *statusLabel = new QLabel(QStringLiteral("Click the button, then press any shortcut..."), &window); + statusLabel->setAlignment(Qt::AlignCenter); + statusLabel->setWordWrap(true); + + layout->addWidget(btn); + layout->addWidget(statusLabel); + + // Disable button until the protocol is available + btn->setEnabled(false); + QObject::connect(&manager, &ShortcutManagerV3::activeChanged, btn, [&] { + btn->setEnabled(manager.isActive()); + }); + + QObject::connect(btn, &QPushButton::clicked, &window, [&] { + if (!manager.isActive()) { + statusLabel->setText(QStringLiteral("Protocol is not ready yet, please try again later.")); + return; + } + + btn->setEnabled(false); + statusLabel->setText(QStringLiteral("Waiting for shortcut input...")); + + ShortcutCapture *capture = manager.captureNextShortcut(window.windowHandle(), &window); + if (!capture) { + statusLabel->setText(QStringLiteral("Failed to create capture object (Wayland surface not ready?)")); + btn->setEnabled(true); + return; + } + + QObject::connect(capture, &ShortcutCapture::captured, &window, + [statusLabel, btn](const QString &key) { + statusLabel->setText(QStringLiteral("Captured shortcut: %1").arg(key)); + btn->setEnabled(true); + }); + + QObject::connect(capture, &ShortcutCapture::failed, &window, + [statusLabel, btn](uint32_t reason) { + statusLabel->setText(QStringLiteral("Capture failed: %1").arg(cancelReasonText(reason))); + btn->setEnabled(true); + }); + }); + + window.show(); + return app.exec(); +} + +#include "main.moc" diff --git a/examples/test_shortcut_manager/CMakeLists.txt b/examples/test_shortcut_manager/CMakeLists.txt new file mode 100644 index 0000000000..654d06145a --- /dev/null +++ b/examples/test_shortcut_manager/CMakeLists.txt @@ -0,0 +1,22 @@ +find_package(Qt6 REQUIRED COMPONENTS Gui WaylandClient Widgets) +find_package(TreelandProtocols REQUIRED) + +set(BIN_NAME test-shortcut-manager) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-shortcut-manager-unstable-v3.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::Widgets + Qt6::WaylandClient +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_shortcut_manager/main.cpp b/examples/test_shortcut_manager/main.cpp new file mode 100644 index 0000000000..e6a58115cb --- /dev/null +++ b/examples/test_shortcut_manager/main.cpp @@ -0,0 +1,267 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// Simple GUI test application for the Treeland Shortcut Manager V3 protocol. +// +// A window lists a set of hardcoded default shortcuts and touchpad gestures (the same compositor +// actions shipped under /usr/share/dsg/configs/org.deepin.dde.keybinding). +// Ticking a checkbox binds the shortcut with the compositor; unticking it +// unbinds the shortcut. There is no JSON input: the shortcuts are hardcoded +// below so the tool can be run without any external configuration. + +#include "qwayland-treeland-shortcut-manager-unstable-v3.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +// Wraps treeland_shortcut_manager_v3 and re-emits its events as Qt signals. +class ShortcutManagerV3 + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_shortcut_manager_v3 +{ + Q_OBJECT +public: + explicit ShortcutManagerV3() + : QWaylandClientExtensionTemplate(1) + { + } + + void bindShortcut(const QString &name, const QString &key, uint32_t flags, uint32_t action) + { + bind_key(name, key, flags, action); + } + + void unbindShortcut(const QString &name) + { + unbind(name); + } + +Q_SIGNALS: + void activated(const QString &name, uint32_t flags); + void bindFailed(const QString &name, uint32_t error); + +protected: + void treeland_shortcut_manager_v3_activated(const QString &name, uint32_t flags) override + { + Q_EMIT activated(name, flags); + } + + void treeland_shortcut_manager_v3_bind_failure(const QString &name, uint32_t error) override + { + Q_EMIT bindFailed(name, error); + } +}; + +namespace { + +using Action = QtWayland::treeland_shortcut_manager_v3::action; +using Direction = QtWayland::treeland_shortcut_manager_v3::direction; +using Flag = QtWayland::treeland_shortcut_manager_v3::keybind_flag; + +struct ShortcutDef +{ + const char *name; + const char *key; + Action action; + uint32_t flags; +}; + +// Hardcoded defaults mirroring the compositor actions shipped in +// /usr/share/dsg/configs/org.deepin.dde.keybinding (triggerType == 3). +// Action values here are already the V3 protocol enum values. +const ShortcutDef kShortcuts[] = { + { "show-desktop", "Meta+D", Action::action_show_desktop, Flag::keybind_flag_key_release }, + { "maximize", "Meta+Up", Action::action_maximize, Flag::keybind_flag_key_release }, + { "cancel-maximize", "Meta+Down", Action::action_cancel_maximize, Flag::keybind_flag_key_release }, + { "minimize", "Meta+N", Action::action_minimize, Flag::keybind_flag_key_release }, + { "close-window", "Alt+F4", Action::action_close_window, Flag::keybind_flag_key_release }, + { "move-window", "Alt+F7", Action::action_move_window, Flag::keybind_flag_key_release }, + { "resize-window", "Alt+F8", Action::action_resize_window, Flag::keybind_flag_key_release }, + { "show-window-menu", "Alt+Space", Action::action_show_window_menu, Flag::keybind_flag_key_release }, + { "toggle-multitaskview", "Meta+S", Action::action_toggle_multitask_view, Flag::keybind_flag_key_release }, + { "toggle-fpsdisplay", "Meta+F11", Action::action_toggle_fps_display, Flag::keybind_flag_key_release }, + { "workspace-1", "Meta+1", Action::action_workspace_1, Flag::keybind_flag_key_release }, + { "workspace-2", "Meta+2", Action::action_workspace_2, Flag::keybind_flag_key_release }, + { "workspace-3", "Meta+3", Action::action_workspace_3, Flag::keybind_flag_key_release }, + { "workspace-4", "Meta+4", Action::action_workspace_4, Flag::keybind_flag_key_release }, + { "prev-workspace", "Meta+Ctrl+Left", Action::action_prev_workspace, Flag::keybind_flag_key_release }, + { "next-workspace", "Meta+Ctrl+Right", Action::action_next_workspace, Flag::keybind_flag_key_release }, + { "tile-left", "Meta+Left", Action::action_tile_left, Flag::keybind_flag_key_release }, + { "tile-right", "Meta+Right", Action::action_tile_right, Flag::keybind_flag_key_release }, + { "taskswitch-next", "Alt+Tab", Action::action_taskswitch_next, Flag::keybind_flag_key_press | Flag::keybind_flag_repeat }, + { "taskswitch-prev", "Alt+Shift+Tab", Action::action_taskswitch_prev, Flag::keybind_flag_key_press | Flag::keybind_flag_repeat }, + { "zoom-in", "Meta+=", Action::action_zoom_in, Flag::keybind_flag_key_release }, + { "zoom-out", "Meta+-", Action::action_zoom_out, Flag::keybind_flag_key_release }, + { "zoom-reset", "Meta+0", Action::action_zoom_reset, Flag::keybind_flag_key_release }, +}; + +struct GestureDef +{ + const char *name; + const char *description; + uint32_t fingers; + uint32_t direction; // Zero denotes a hold gesture. + Action action; +}; + +// Search and launcher toggles are client actions, so they only emit activated. +const GestureDef kGestures[] = { + { "three-finger-up", "3 fingers up: maximize", 3, Direction::direction_up, Action::action_maximize }, + { "three-finger-down", "3 fingers down: restore", 3, Direction::direction_down, Action::action_cancel_maximize }, + { "three-finger-left", "3 fingers left: tile left", 3, Direction::direction_left, Action::action_tile_left }, + { "three-finger-right", "3 fingers right: tile right", 3, Direction::direction_right, Action::action_tile_right }, + { "three-finger-hold", "3 fingers hold: toggle search", 3, 0, Action::action_notify }, + { "four-finger-up", "4 fingers up: show multitask", 4, Direction::direction_up, Action::action_open_multitask_view }, + { "four-finger-down", "4 fingers down: hide multitask", 4, Direction::direction_down, Action::action_close_multitask_view }, + { "four-finger-left", "4 fingers left: prev workspace", 4, Direction::direction_left, Action::action_prev_workspace }, + { "four-finger-right", "4 fingers right: next workspace", 4, Direction::direction_right, Action::action_next_workspace }, + { "four-finger-hold", "4 fingers hold: toggle launcher", 4, 0, Action::action_notify }, +}; + +void applyGestureBinding(ShortcutManagerV3 &manager, const GestureDef &def, bool checked) +{ + const QString name = QString::fromLatin1(def.name); + if (!checked) + manager.unbindShortcut(name); + else if (def.direction == 0) + manager.bind_hold_gesture(name, def.fingers, def.action); + else + manager.bind_swipe_gesture(name, def.fingers, def.direction, def.action); +} + +} // namespace + +int main(int argc, char *argv[]) +{ + qputenv("QT_QPA_PLATFORM", "wayland"); + QApplication app(argc, argv); + + ShortcutManagerV3 manager; + + QWidget window; + window.setWindowTitle(QStringLiteral("Shortcut Manager V3 Test")); + window.resize(520, 720); + + auto *layout = new QVBoxLayout(&window); + + auto *statusLabel = new QLabel(&window); + statusLabel->setWordWrap(true); + layout->addWidget(statusLabel); + + auto *log = new QPlainTextEdit(&window); + log->setReadOnly(true); + layout->addWidget(log, 1); + + // One checkbox per hardcoded shortcut, laid out in two columns. + // Checked == bound; all shortcuts start checked (bound) by default. + const int shortcutCount = static_cast(std::size(kShortcuts)); + auto *grid = new QGridLayout; + constexpr int columns = 2; + QList boxes; + for (int i = 0; i < shortcutCount; ++i) { + const ShortcutDef &def = kShortcuts[i]; + auto *box = new QCheckBox( + QStringLiteral("%1 (%2)").arg(QString::fromLatin1(def.name), QString::fromLatin1(def.key)), + &window); + box->setChecked(true); + grid->addWidget(box, i / columns, i % columns); + boxes.append(box); + } + layout->addLayout(grid); + + layout->addWidget(new QLabel(QStringLiteral("Touchpad gestures"), &window)); + const int gestureCount = static_cast(std::size(kGestures)); + auto *gestureGrid = new QGridLayout; + QList gestureBoxes; + for (int i = 0; i < gestureCount; ++i) { + auto *box = new QCheckBox(QString::fromLatin1(kGestures[i].description), &window); + box->setChecked(true); + gestureGrid->addWidget(box, i / columns, i % columns); + gestureBoxes.append(box); + } + layout->addLayout(gestureGrid); + + // (Re)apply every checkbox to the compositor. Used when the protocol + // becomes active so previously checked shortcuts are re-bound after a + // disconnect/reconnect of the extension. + const auto applyBindings = [&]() { + for (int i = 0; i < shortcutCount; ++i) { + const ShortcutDef &def = kShortcuts[i]; + if (boxes.at(i)->isChecked()) + manager.bindShortcut(QString::fromLatin1(def.name), + QString::fromLatin1(def.key), + def.flags, + def.action); + else + manager.unbindShortcut(QString::fromLatin1(def.name)); + } + for (int i = 0; i < gestureCount; ++i) + applyGestureBinding(manager, kGestures[i], gestureBoxes.at(i)->isChecked()); + }; + + QObject::connect(&manager, &ShortcutManagerV3::activeChanged, &window, [&]() { + const bool active = manager.isActive(); + statusLabel->setText(active + ? QStringLiteral("Protocol active — acquired, bindings applied.") + : QStringLiteral("Protocol inactive.")); + if (!active) + return; + manager.acquire(); + applyBindings(); + }); + + for (int i = 0; i < shortcutCount; ++i) { + const ShortcutDef &def = kShortcuts[i]; + QObject::connect(boxes.at(i), &QCheckBox::toggled, &window, [&, i](bool checked) { + if (checked) + manager.bindShortcut(QString::fromLatin1(def.name), + QString::fromLatin1(def.key), + def.flags, + def.action); + else + manager.unbindShortcut(QString::fromLatin1(def.name)); + log->appendPlainText(QStringLiteral("%1 %2") + .arg(checked ? QStringLiteral("bound") : QStringLiteral("unbound"), + QString::fromLatin1(def.name))); + }); + } + + for (int i = 0; i < gestureCount; ++i) { + QObject::connect(gestureBoxes.at(i), &QCheckBox::toggled, &window, [&, i](bool checked) { + if (!manager.isActive()) + return; + applyGestureBinding(manager, kGestures[i], checked); + log->appendPlainText(QStringLiteral("%1 %2") + .arg(checked ? QStringLiteral("bound") : QStringLiteral("unbound"), + QString::fromLatin1(kGestures[i].name))); + }); + } + + QObject::connect(&manager, &ShortcutManagerV3::activated, &window, + [log](const QString &name, uint32_t flags) { + log->appendPlainText( + QStringLiteral("activated: %1 (flags=0x%2)") + .arg(name, QString::number(flags, 16))); + }); + + QObject::connect(&manager, &ShortcutManagerV3::bindFailed, &window, + [log](const QString &name, uint32_t error) { + log->appendPlainText( + QStringLiteral("bind failure: %1 (error=%2)") + .arg(name, QString::number(error))); + }); + + window.show(); + return app.exec(); +} + +#include "main.moc" diff --git a/examples/test_snap_target/CMakeLists.txt b/examples/test_snap_target/CMakeLists.txt new file mode 100644 index 0000000000..559f44f350 --- /dev/null +++ b/examples/test_snap_target/CMakeLists.txt @@ -0,0 +1,56 @@ +find_package(PkgConfig REQUIRED) +find_package(Qt6 REQUIRED COMPONENTS Core Gui WaylandClient Quick) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS WaylandClientPrivate) +endif() +find_package(TreelandProtocols REQUIRED) +pkg_get_variable(WAYLAND_PROTOCOLS_DATADIR wayland-protocols pkgdatadir) + +set(BIN_NAME test-snap-target) + +qt_add_executable(${BIN_NAME} + main.cpp + screencapture.cpp + snapproxy.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-foreign-toplevel-list/ext-foreign-toplevel-list-v1.xml + ${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-image-capture-source/ext-image-capture-source-v1.xml + ${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-image-copy-capture/ext-image-copy-capture-v1.xml +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-snap-target-unstable-v1.xml +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${WAYLAND_PROTOCOLS_DATADIR}/staging/xdg-toplevel-tag/xdg-toplevel-tag-v1.xml +) + +# xdg-toplevel-tag references xdg_toplevel_interface from xdg-shell +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${WAYLAND_PROTOCOLS_DATADIR}/stable/xdg-shell/xdg-shell.xml +) + +qt_add_qml_module(${BIN_NAME} + URI TestSnapTarget + VERSION 1.0 + QML_FILES + Main.qml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Core + Qt6::Gui + Qt6::WaylandClient + Qt6::WaylandClientPrivate + Qt6::Quick +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_snap_target/Main.qml b/examples/test_snap_target/Main.qml new file mode 100644 index 0000000000..66046bf380 --- /dev/null +++ b/examples/test_snap_target/Main.qml @@ -0,0 +1,180 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + +// One instance per output. `snapController` is injected as a per-window +// context property so that each window tracks its own output origin while +// sharing the process-wide snap session. +Window { + id: root + visible: true + flags: Qt.FramelessWindowHint + color: "transparent" + width: snapController.screenWidth + height: snapController.screenHeight + + // Press Escape to quit the demo + Shortcut { + sequence: "Escape" + onActivated: snapController.quit() + } + + // Frozen snapshot of this output, captured before any mask window was + // mapped. Only present when started with --background. + Image { + id: backgroundImage + anchors.fill: parent + fillMode: Image.Stretch + source: snapController.backgroundSource + visible: snapController.backgroundEnabled + } + + Rectangle { + id: snapHighlight + color: Qt.rgba(0.2, 0.6, 1.0, 0.1) + border.color: "#3399FF" + border.width: 3 + visible: snapController.snapVisible && !snapController.confirmed + x: snapController.snapX + y: snapController.snapY + width: snapController.snapWidth + height: snapController.snapHeight + radius: 4 + } + + // Frozen selection highlight after confirmation + Rectangle { + id: frozenSelection + color: Qt.rgba(0.2, 0.6, 1.0, 0.15) + border.color: "#3399FF" + border.width: 4 + visible: snapController.confirmed + x: snapController.snapX + y: snapController.snapY + width: snapController.snapWidth + height: snapController.snapHeight + radius: 4 + } + + // Full-screen click area — only active before confirmation + MouseArea { + id: clickCatcher + anchors.fill: parent + enabled: !snapController.confirmed + cursorShape: Qt.CrossCursor + onClicked: snapController.confirmSelection() + } + + // Demo toolbar (non-functional) shown after confirmation + Rectangle { + id: toolbar + z: 9 + visible: snapController.confirmed + color: "#2B2B2B" + border.color: "#555555" + border.width: 1 + radius: 6 + height: 48 + width: 260 + + // Center toolbar above the frozen selection, clamped to this output + x: snapController.confirmed + ? Math.max(8, Math.min(root.width - width - 8, + snapController.snapX + snapController.snapWidth / 2 - width / 2)) + : 0 + y: snapController.confirmed + ? (snapController.snapY - height - 8 >= 8 + ? snapController.snapY - height - 8 + : Math.min(root.height - height - 8, + snapController.snapY + snapController.snapHeight + 8)) + : 0 + + Row { + anchors.centerIn: parent + spacing: 10 + + Repeater { + model: [ + { icon: "✎", label: "Annotate" }, + { icon: "⌨", label: "Text" }, + { icon: "⏲", label: "Delay" }, + { icon: "💾", label: "Save" } + ] + + Rectangle { + width: 52 + height: 36 + color: "transparent" + radius: 4 + + Text { + anchors.top: parent.top + anchors.horizontalCenter: parent.horizontalCenter + anchors.topMargin: 2 + text: modelData.icon + font.pixelSize: 18 + color: "#FFFFFF" + } + + Text { + anchors.bottom: parent.bottom + anchors.horizontalCenter: parent.horizontalCenter + anchors.bottomMargin: 2 + text: modelData.label + font.pixelSize: 9 + color: "#AAAAAA" + } + + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + onClicked: { + // Demo only - no actual functionality + } + } + } + } + } + + // Close button on the toolbar's right edge + Rectangle { + anchors.right: parent.right + anchors.rightMargin: 6 + anchors.verticalCenter: parent.verticalCenter + width: 24 + height: 24 + radius: 12 + color: "transparent" + + Text { + anchors.centerIn: parent + text: "×" + font.pixelSize: 18 + color: "#FFFFFF" + } + + MouseArea { + anchors.fill: parent + cursorShape: Qt.PointingHandCursor + onClicked: snapController.quit() + } + } + } + + // Debug overlay - one per output + Text { + z: 10 + x: 10 + y: 10 + text: "confirmed=" + snapController.confirmed + + " vis=" + snapController.snapVisible + + " region=(" + snapController.snapX + "," + snapController.snapY + + " " + snapController.snapWidth + "x" + snapController.snapHeight + ")" + + " proc=" + snapController.processName + + " output=(" + snapController.screenX + "," + snapController.screenY + + " " + root.width + "x" + root.height + ")" + color: "red" + font.pixelSize: 14 + } +} diff --git a/examples/test_snap_target/main.cpp b/examples/test_snap_target/main.cpp new file mode 100644 index 0000000000..4d3d6cd0c9 --- /dev/null +++ b/examples/test_snap_target/main.cpp @@ -0,0 +1,153 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "screencapture.h" +#include "snapproxy.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +class BackgroundImageProvider : public QQuickImageProvider +{ +public: + BackgroundImageProvider() + : QQuickImageProvider(QQuickImageProvider::Image) + { + } + + QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize) override + { + Q_UNUSED(requestedSize); + const QImage image = m_images.value(id); + if (size) + *size = image.size(); + return image; + } + + static QString idForGeometry(const QRect &geometry) + { + return QStringLiteral("%1_%2_%3_%4") + .arg(geometry.x()) + .arg(geometry.y()) + .arg(geometry.width()) + .arg(geometry.height()); + } + + void addImage(const QRect &geometry, const QImage &image) + { + m_images.insert(idForGeometry(geometry), image); + } + + bool hasImage(const QString &id) const + { + return m_images.contains(id); + } + +private: + QHash m_images; +}; + +int main(int argc, char *argv[]) +{ + QGuiApplication app(argc, argv); + + QCommandLineParser parser; + parser.setApplicationDescription("Treeland snap-target demo client"); + parser.addHelpOption(); + const QCommandLineOption backgroundOption( + QStringLiteral("background"), + QStringLiteral("Capture each output with ext-image-copy-capture before showing the " + "selection UI and use the per-output images as window backgrounds.")); + parser.addOption(backgroundOption); + parser.process(app); + + // Capture backgrounds before any mask surface is mapped, so the masks do + // not show up in their own screenshots. + QList capturedOutputs; + if (parser.isSet(backgroundOption)) { + ScreenCapture capture; + capturedOutputs = capture.captureOutputs(); + if (capturedOutputs.isEmpty()) + qWarning() << "Background capture failed, falling back to a transparent background"; + } + + // One snap session per process, shared by every per-output mask window. + SnapSession session; + + auto *backgroundProvider = new BackgroundImageProvider; + for (const auto &output : std::as_const(capturedOutputs)) + backgroundProvider->addImage(output.logicalGeometry, output.image); + + QQmlApplicationEngine engine; + engine.addImageProvider("captureBackground", backgroundProvider); + + QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/qt/qml/TestSnapTarget/Main.qml"))); + if (component.isError()) { + qWarning() << component.errors(); + return -1; + } + + const QList screens = QGuiApplication::screens(); + if (screens.isEmpty()) { + qWarning() << "No outputs available"; + return -1; + } + + struct MaskWindow + { + SnapController *controller = nullptr; + QQuickWindow *window = nullptr; + QScreen *screen = nullptr; + }; + + QList masks; + for (QScreen *screen : screens) { + auto *controller = new SnapController(&session, &session); + auto *context = new QQmlContext(engine.rootContext()); + context->setContextProperty(QStringLiteral("snapController"), controller); + + QObject *object = component.create(context); + auto *window = qobject_cast(object); + if (!window) { + qWarning() << "Failed to create mask window for output" << screen->name() + << component.errors(); + delete object; + continue; + } + + window->setScreen(screen); + + if (parser.isSet(backgroundOption)) { + const QString id = BackgroundImageProvider::idForGeometry(screen->geometry()); + if (backgroundProvider->hasImage(id)) { + controller->setBackgroundSource(QStringLiteral("image://captureBackground/") + id); + controller->setBackgroundEnabled(true); + } + } + + masks.append({ controller, window, screen }); + } + + if (masks.isEmpty()) + return -1; + + QTimer::singleShot(0, [&session, masks]() { + for (const MaskWindow &mask : masks) + mask.controller->setup(mask.window, mask.screen); + session.start(); + }); + + return app.exec(); +} diff --git a/examples/test_snap_target/screencapture.cpp b/examples/test_snap_target/screencapture.cpp new file mode 100644 index 0000000000..1a033d8141 --- /dev/null +++ b/examples/test_snap_target/screencapture.cpp @@ -0,0 +1,257 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "screencapture.h" + +#include + +#include +#include + +#include +#include +#include +#include + +QImage::Format ScreenCapture::qimageFormatForShm(uint32_t format) +{ + switch (format) { + case WL_SHM_FORMAT_ARGB8888: + case WL_SHM_FORMAT_BGRA8888: + return QImage::Format_ARGB32; + case WL_SHM_FORMAT_XRGB8888: + case WL_SHM_FORMAT_BGRX8888: + return QImage::Format_RGB32; + case WL_SHM_FORMAT_XBGR8888: + return QImage::Format_RGBX8888; + default: + return QImage::Format_Invalid; + } +} + +ScreenCapture::~ScreenCapture() +{ + for (Output *output : std::as_const(m_outputs)) { + cleanupOutput(output); + if (output->xdgOutput.isInitialized()) + output->xdgOutput.destroy(); + if (output->wlOutput.isInitialized()) + output->wlOutput.release(); + delete output; + } +} + +void ScreenCapture::cleanupOutput(Output *output) +{ + if (output->frame.isInitialized()) + output->frame.destroy(); + if (output->buffer.isInitialized()) + output->buffer.destroy(); + if (output->shmPool.isInitialized()) + output->shmPool.destroy(); + if (output->shmData) { + munmap(output->shmData, output->bufferH * output->bufferW * 4); + output->shmData = nullptr; + } + if (output->shmFd >= 0) { + close(output->shmFd); + output->shmFd = -1; + } + if (output->session.isInitialized()) + output->session.destroy(); +} + +void ScreenCapture::Registry::registry_global(uint32_t name, + const QString &interface, + uint32_t version) +{ + auto *self = owner; + if (interface == QLatin1String("wl_shm")) { + self->m_shm.init(self->m_registry.object(), name, version); + } else if (interface == QLatin1String("zxdg_output_manager_v1")) { + self->m_xdgOutputManager.init(self->m_registry.object(), name, version); + } else if (interface == QLatin1String("ext_output_image_capture_source_manager_v1")) { + self->m_extSourceManager.init(self->m_registry.object(), name, version); + } else if (interface == QLatin1String("ext_image_copy_capture_manager_v1")) { + self->m_extCopyManager.init(self->m_registry.object(), name, version); + } else if (interface == QLatin1String("wl_output")) { + auto *output = new Output; + output->wlOutput.init(self->m_registry.object(), name, version); + self->m_outputs.append(output); + } +} + +void ScreenCapture::Registry::registry_global_remove(uint32_t name) +{ + Q_UNUSED(name); +} + +void ScreenCapture::XdgOutput::zxdg_output_v1_logical_position(int32_t x, int32_t y) +{ + output->logicalX = x; + output->logicalY = y; +} + +void ScreenCapture::XdgOutput::zxdg_output_v1_logical_size(int32_t width, int32_t height) +{ + output->logicalW = width; + output->logicalH = height; +} + +void ScreenCapture::Session::ext_image_copy_capture_session_v1_buffer_size(uint32_t width, + uint32_t height) +{ + output->bufferW = width; + output->bufferH = height; +} + +void ScreenCapture::Session::ext_image_copy_capture_session_v1_shm_format(uint32_t format) +{ + if (output->imageFormat != QImage::Format_Invalid) + return; + output->imageFormat = qimageFormatForShm(format); + if (output->imageFormat != QImage::Format_Invalid) + output->shmFormat = format; +} + +void ScreenCapture::Session::ext_image_copy_capture_session_v1_done() +{ + output->constraintsDone = true; +} + +void ScreenCapture::Frame::ext_image_copy_capture_frame_v1_ready() +{ + auto *output = this->output; + if (!output->shmData || output->bufferW <= 0 || output->bufferH <= 0 + || output->imageFormat == QImage::Format_Invalid) { + output->captureFailed = true; + } else { + QImage image(static_cast(output->shmData), + output->bufferW, + output->bufferH, + output->bufferW * 4, + output->imageFormat); + output->image = image.copy(); + output->captureReady = true; + } + destroy(); +} + +void ScreenCapture::Frame::ext_image_copy_capture_frame_v1_failed(uint32_t reason) +{ + Q_UNUSED(reason); + output->captureFailed = true; + destroy(); +} + +QList ScreenCapture::captureOutputs() +{ + m_outputs.clear(); + + auto *app = qGuiApp; + auto *waylandApp = + app ? app->nativeInterface() : nullptr; + if (!waylandApp) + return { }; + m_display = waylandApp->display(); + if (!m_display) + return { }; + + m_registry.owner = this; + m_registry.init(wl_display_get_registry(m_display)); + wl_display_roundtrip(m_display); + + if (!m_shm.isInitialized() || !m_extSourceManager.isInitialized() + || !m_extCopyManager.isInitialized() || m_outputs.isEmpty()) { + return { }; + } + + if (m_xdgOutputManager.isInitialized()) { + for (Output *output : std::as_const(m_outputs)) { + output->xdgOutput.output = output; + output->xdgOutput.init(m_xdgOutputManager.get_xdg_output(output->wlOutput.object())); + } + wl_display_roundtrip(m_display); + } + + for (Output *output : std::as_const(m_outputs)) { + output->session.output = output; + auto *source = m_extSourceManager.create_source(output->wlOutput.object()); + auto *session = m_extCopyManager.create_session(source, 0); + ext_image_capture_source_v1_destroy(source); + output->session.init(session); + } + wl_display_roundtrip(m_display); + + static int serial = 0; + int framesSent = 0; + QVector pendingOutputs; + for (Output *output : std::as_const(m_outputs)) { + if (!output->constraintsDone || output->imageFormat == QImage::Format_Invalid) + continue; + + const int stride = output->bufferW * 4; + const int size = stride * output->bufferH; + + QByteArray name = QByteArrayLiteral("/treeland-snap-target-") + + QByteArray::number(static_cast(getpid())) + QByteArrayLiteral("-") + + QByteArray::number(serial++); + int fd = shm_open(name.constData(), O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0600); + if (fd < 0) + continue; + shm_unlink(name.constData()); + if (ftruncate(fd, size) < 0) { + close(fd); + continue; + } + auto *data = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (data == MAP_FAILED) { + close(fd); + continue; + } + + output->shmFd = fd; + output->shmData = data; + output->shmPool.init(m_shm.create_pool(fd, size)); + output->buffer.init(output->shmPool.create_buffer(0, + output->bufferW, + output->bufferH, + stride, + output->shmFormat)); + + output->frame.output = output; + auto *frame = output->session.create_frame(); + output->frame.init(frame); + output->frame.attach_buffer(output->buffer.object()); + output->frame.damage_buffer(0, 0, INT32_MAX, INT32_MAX); + output->frame.capture(); + ++framesSent; + pendingOutputs.append(output); + } + + if (framesSent > 0) { + bool pending = true; + while (pending) { + if (wl_display_dispatch(m_display) < 0) + break; + pending = false; + for (Output *output : std::as_const(pendingOutputs)) { + if (!output->captureReady && !output->captureFailed) { + pending = true; + break; + } + } + } + } + + QList result; + for (Output *output : std::as_const(m_outputs)) { + if (!output->captureReady || output->image.isNull()) + continue; + const int w = output->logicalW > 0 ? output->logicalW : output->bufferW; + const int h = output->logicalH > 0 ? output->logicalH : output->bufferH; + result.append({ QRect(output->logicalX, output->logicalY, w, h), output->image }); + } + + return result; +} diff --git a/examples/test_snap_target/screencapture.h b/examples/test_snap_target/screencapture.h new file mode 100644 index 0000000000..7f09b53f19 --- /dev/null +++ b/examples/test_snap_target/screencapture.h @@ -0,0 +1,120 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef SCREENCAPTURE_H +#define SCREENCAPTURE_H + +#include "qwayland-ext-image-capture-source-v1.h" +#include "qwayland-ext-image-copy-capture-v1.h" + +#include +#include +#include +#include +#include +#include + +class ScreenCapture +{ +public: + ScreenCapture() = default; + ~ScreenCapture(); + + // One captured output: its logical geometry (xdg-output coordinates) and + // the raw captured image (buffer pixel size). + struct CapturedOutput + { + QRect logicalGeometry; + QImage image; + }; + + // Captures every output separately via ext-image-copy-capture. Returns an + // empty list on failure. + QList captureOutputs(); + +private: + struct Output; + + class Registry : public QtWayland::wl_registry + { + public: + ScreenCapture *owner = nullptr; + + protected: + void registry_global(uint32_t name, const QString &interface, uint32_t version) override; + void registry_global_remove(uint32_t name) override; + }; + + class XdgOutput : public QtWayland::zxdg_output_v1 + { + public: + Output *output = nullptr; + + protected: + void zxdg_output_v1_logical_position(int32_t x, int32_t y) override; + void zxdg_output_v1_logical_size(int32_t width, int32_t height) override; + }; + + class Session : public QtWayland::ext_image_copy_capture_session_v1 + { + public: + Output *output = nullptr; + + protected: + void ext_image_copy_capture_session_v1_buffer_size(uint32_t width, + uint32_t height) override; + void ext_image_copy_capture_session_v1_shm_format(uint32_t format) override; + void ext_image_copy_capture_session_v1_done() override; + }; + + class Frame : public QtWayland::ext_image_copy_capture_frame_v1 + { + public: + Output *output = nullptr; + + protected: + void ext_image_copy_capture_frame_v1_ready() override; + void ext_image_copy_capture_frame_v1_failed(uint32_t reason) override; + }; + + struct Output + { + QtWayland::wl_output wlOutput; + XdgOutput xdgOutput; + int logicalX = 0; + int logicalY = 0; + int logicalW = 0; + int logicalH = 0; + + Session session; + Frame frame; + QtWayland::wl_shm_pool shmPool; + QtWayland::wl_buffer buffer; + + int bufferW = 0; + int bufferH = 0; + uint32_t shmFormat = 0; + QImage::Format imageFormat = QImage::Format_Invalid; + bool constraintsDone = false; + + int shmFd = -1; + void *shmData = nullptr; + + QImage image; + bool captureReady = false; + bool captureFailed = false; + }; + + static QImage::Format qimageFormatForShm(uint32_t format); + void cleanupOutput(Output *output); + + Registry m_registry; + QtWayland::wl_shm m_shm; + QtWayland::zxdg_output_manager_v1 m_xdgOutputManager; + QtWayland::ext_output_image_capture_source_manager_v1 m_extSourceManager; + QtWayland::ext_image_copy_capture_manager_v1 m_extCopyManager; + QVector m_outputs; + wl_display *m_display = nullptr; +}; + +#endif // SCREENCAPTURE_H diff --git a/examples/test_snap_target/snapproxy.cpp b/examples/test_snap_target/snapproxy.cpp new file mode 100644 index 0000000000..700ac095e5 --- /dev/null +++ b/examples/test_snap_target/snapproxy.cpp @@ -0,0 +1,412 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "snapproxy.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace { + +constexpr auto SnapMaskTag = "org.deepin.treeland.snap-mask"; + +QString processNameForPidfd(int pidfd) +{ + QFile fdinfo(QStringLiteral("/proc/self/fdinfo/%1").arg(pidfd)); + if (!fdinfo.open(QIODevice::ReadOnly)) + return { }; + + qint64 pid = 0; + const QByteArray content = fdinfo.readAll(); + const QList lines = content.split('\n'); + for (const QByteArray &line : lines) { + if (line.startsWith("Pid:")) { + pid = line.mid(4).trimmed().toLongLong(); + break; + } + } + if (pid <= 0) + return { }; + + QFile comm(QStringLiteral("/proc/%1/comm").arg(pid)); + if (!comm.open(QIODevice::ReadOnly)) + return { }; + + return QString::fromLocal8Bit(comm.readAll()).trimmed(); +} + +void seatRegistryGlobal(void *data, + wl_registry *registry, + uint32_t name, + const char *interface, + uint32_t version) +{ + auto **seat = static_cast(data); + if (*seat || qstrcmp(interface, wl_seat_interface.name) != 0) + return; + *seat = static_cast( + wl_registry_bind(registry, name, &wl_seat_interface, qMin(version, 9))); +} + +void seatRegistryGlobalRemove(void *data, wl_registry *registry, uint32_t name) +{ + Q_UNUSED(data); + Q_UNUSED(registry); + Q_UNUSED(name); +} + +const wl_registry_listener seatRegistryListener = { + seatRegistryGlobal, + seatRegistryGlobalRemove, +}; + +} // namespace + +ToplevelTagManager::ToplevelTagManager() + : QWaylandClientExtensionTemplate(1) +{ +} + +ToplevelTagManager::~ToplevelTagManager() +{ + if (isActive()) + destroy(); +} + +Snap::Snap() + : QWaylandClientExtensionTemplate(1) +{ +} + +Snap::~Snap() +{ + if (isActive()) + destroy(); +} + +void Snap::treeland_snap_target_v1_snap_region(int32_t x, + int32_t y, + uint32_t width, + uint32_t height) +{ + Q_EMIT snapRegion(static_cast(x), + static_cast(y), + static_cast(width), + static_cast(height)); +} + +void Snap::treeland_snap_target_v1_pidfd(int32_t pidfd) +{ + Q_EMIT this->pidfd(static_cast(pidfd)); +} + +void Snap::treeland_snap_target_v1_failed(uint32_t reason) +{ + Q_EMIT failed(static_cast(reason)); +} + +struct ::xdg_toplevel *getXdgToplevel(QWindow *window) +{ + if (!window || !window->handle()) + return nullptr; + + auto *ww = static_cast(window->handle()); + if (!ww) + return nullptr; + + auto *ss = ww->shellSurface(); + if (!ss) + return nullptr; + + std::any role = ss->surfaceRole(); + try { + return std::any_cast(role); + } catch (const std::bad_any_cast &) { + } + return nullptr; +} + +SnapSession::SnapSession(QObject *parent) + : QObject(parent) +{ + if (auto *waylandApp = + qGuiApp ? qGuiApp->nativeInterface() : nullptr) { + if (auto *display = waylandApp->display()) { + m_seatRegistry = wl_display_get_registry(display); + wl_registry_add_listener(m_seatRegistry, &seatRegistryListener, &m_seat); + wl_display_roundtrip(display); + } + } + + connect(&m_tagManager, + &QWaylandClientExtension::activeChanged, + this, + &SnapSession::maybeInitialize); + connect(&m_snap, &QWaylandClientExtension::activeChanged, this, &SnapSession::maybeInitialize); +} + +SnapSession::~SnapSession() +{ + clearPendingPidfd(); + if (m_seat) { + wl_seat_destroy(m_seat); + m_seat = nullptr; + } + if (m_seatRegistry) { + wl_registry_destroy(m_seatRegistry); + m_seatRegistry = nullptr; + } +} + +void SnapSession::registerWindow(QWindow *window) +{ + if (!window || m_windows.contains(window)) + return; + m_windows.append(window); + if (m_tagManager.isActive()) + tagWindow(window); +} + +void SnapSession::start() +{ + m_startRequested = true; + if (!m_initialized || m_started) + return; + m_started = true; + m_snap.start(m_seat, TREELAND_SNAP_TARGET_V1_EVENT_TYPE_PIDFD); +} + +void SnapSession::maybeInitialize() +{ + if (m_initialized) + return; + if (!m_tagManager.isActive() || !m_snap.isActive()) + return; + + m_initialized = true; + + for (const auto &window : std::as_const(m_windows)) { + if (window) + tagWindow(window); + } + + connect(&m_snap, &Snap::snapRegion, this, &SnapSession::onSnapRegion); + connect(&m_snap, &Snap::pidfd, this, &SnapSession::onPidfd); + connect(&m_snap, &Snap::failed, this, &SnapSession::onFailed); + + if (m_startRequested) + start(); +} + +void SnapSession::tagWindow(QWindow *window) +{ + auto *toplevel = getXdgToplevel(window); + if (!toplevel) { + qWarning() << "Could not obtain xdg_toplevel from window surface role"; + return; + } + m_tagManager.set_toplevel_tag(toplevel, SnapMaskTag); +} + +void SnapSession::onPidfd(int pidfd) +{ + clearPendingPidfd(); + if (pidfd < 0) + return; + + // The event fd is owned by this client and remains valid until we close + // it, so keep it directly until the committing snap_region event arrives. + m_pendingPidfd = pidfd; +} + +void SnapSession::onSnapRegion(int x, int y, quint32 width, quint32 height) +{ + // snap_region commits the target: consume the pidfd received before it. + if (m_pendingPidfd >= 0) + setProcessName(processNameForPidfd(m_pendingPidfd)); + else + setProcessName(QString()); + clearPendingPidfd(); + + if (width != 0 && height != 0) + m_region = QRect(x, y, static_cast(width), static_cast(height)); + else + m_region = QRect(); + + Q_EMIT regionChanged(); +} + +void SnapSession::onFailed(quint32 reason) +{ + const char *reasonStr = "unknown"; + switch (reason) { + case QtWayland::treeland_snap_target_v1::failure_reason_snap_busy: + reasonStr = "snap_busy"; + break; + } + qWarning() << "Snap failed:" << reasonStr; + QCoreApplication::quit(); +} + +void SnapSession::confirmSelection() +{ + if (m_confirmed) + return; + m_confirmed = true; + Q_EMIT confirmedChanged(); + + m_snap.stop(); +} + +void SnapSession::quit() +{ + QCoreApplication::quit(); +} + +void SnapSession::setProcessName(const QString &name) +{ + if (m_processName == name) + return; + m_processName = name; + Q_EMIT processNameChanged(); +} + +void SnapSession::clearPendingPidfd() +{ + if (m_pendingPidfd < 0) + return; + ::close(m_pendingPidfd); + m_pendingPidfd = -1; +} + +SnapController::SnapController(SnapSession *session, QObject *parent) + : QObject(parent) + , m_session(session) +{ + connect(m_session, &SnapSession::regionChanged, this, &SnapController::onSessionRegionChanged); + connect(m_session, + &SnapSession::processNameChanged, + this, + &SnapController::onSessionProcessNameChanged); + connect(m_session, + &SnapSession::confirmedChanged, + this, + &SnapController::onSessionConfirmedChanged); +} + +SnapController::~SnapController() = default; + +void SnapController::setup(QWindow *window, QScreen *screen) +{ + m_window = window; + m_screen = screen; + + if (m_window) { + if (m_screen) { + m_window->setScreen(m_screen); + m_window->setVisibility(QWindow::FullScreen); + } + m_session->registerWindow(m_window); + } + + Q_EMIT screenGeometryChanged(); +} + +void SnapController::confirmSelection() +{ + m_session->confirmSelection(); +} + +void SnapController::quit() +{ + m_session->quit(); +} + +QString SnapController::processName() const +{ + return m_session->processName(); +} + +bool SnapController::confirmed() const +{ + return m_session->confirmed(); +} + +void SnapController::setBackgroundEnabled(bool enabled) +{ + if (m_backgroundEnabled == enabled) + return; + m_backgroundEnabled = enabled; + Q_EMIT backgroundEnabledChanged(); +} + +void SnapController::setBackgroundSource(const QString &source) +{ + if (m_backgroundSource == source) + return; + m_backgroundSource = source; + Q_EMIT backgroundSourceChanged(); +} + +int SnapController::screenX() const +{ + return m_screen ? m_screen->geometry().x() : 0; +} + +int SnapController::screenY() const +{ + return m_screen ? m_screen->geometry().y() : 0; +} + +int SnapController::screenWidth() const +{ + return m_screen ? m_screen->geometry().width() : 0; +} + +int SnapController::screenHeight() const +{ + return m_screen ? m_screen->geometry().height() : 0; +} + +void SnapController::onSessionRegionChanged() +{ + const QRect global = m_session->region(); + const QPoint origin = m_screen ? m_screen->geometry().topLeft() : QPoint(0, 0); + + // Only remember the geometry of non-empty snap targets so that the + // frozen selection / toolbar after confirmation still reflects the last + // valid region the user hovered over. + if (global.isValid() && !global.isEmpty()) { + m_x = global.x() - origin.x(); + m_y = global.y() - origin.y(); + m_w = global.width(); + m_h = global.height(); + } + m_visible = global.isValid() && !global.isEmpty(); + + Q_EMIT snapRegionChanged(); +} + +void SnapController::onSessionProcessNameChanged() +{ + Q_EMIT processNameChanged(); +} + +void SnapController::onSessionConfirmedChanged() +{ + Q_EMIT confirmedChanged(); +} diff --git a/examples/test_snap_target/snapproxy.h b/examples/test_snap_target/snapproxy.h new file mode 100644 index 0000000000..fba7d1bfe9 --- /dev/null +++ b/examples/test_snap_target/snapproxy.h @@ -0,0 +1,219 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef SNAPPROXY_H +#define SNAPPROXY_H + +#include "qwayland-treeland-snap-target-unstable-v1.h" +#include "qwayland-xdg-shell.h" +#include "qwayland-xdg-toplevel-tag-v1.h" + +#include +#include +#include +#include +#include +#include + +class QScreen; +class QWindow; + +struct wl_registry; +struct wl_seat; + +class ToplevelTagManager + : public QWaylandClientExtensionTemplate + , public QtWayland::xdg_toplevel_tag_manager_v1 +{ + Q_OBJECT +public: + ToplevelTagManager(); + ~ToplevelTagManager() override; +}; + +class Snap + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_snap_target_v1 +{ + Q_OBJECT +public: + Snap(); + ~Snap() override; + +Q_SIGNALS: + void snapRegion(int x, int y, quint32 width, quint32 height); + void pidfd(int pidfd); + void failed(quint32 reason); + +protected: + void treeland_snap_target_v1_snap_region(int32_t x, + int32_t y, + uint32_t width, + uint32_t height) override; + void treeland_snap_target_v1_pidfd(int32_t pidfd) override; + void treeland_snap_target_v1_failed(uint32_t reason) override; +}; + +struct ::xdg_toplevel *getXdgToplevel(QWindow *window); + +// Process-wide snap session. There is a single treeland_snap_target_v1 object +// per client, shared by every per-output mask window. +class SnapSession : public QObject +{ + Q_OBJECT +public: + explicit SnapSession(QObject *parent = nullptr); + ~SnapSession() override; + + void registerWindow(QWindow *window); + void start(); + + QRect region() const + { + return m_region; + } + + QString processName() const + { + return m_processName; + } + + bool confirmed() const + { + return m_confirmed; + } + + void confirmSelection(); + void quit(); + +Q_SIGNALS: + void regionChanged(); + void processNameChanged(); + void confirmedChanged(); + +private: + void maybeInitialize(); + void tagWindow(QWindow *window); + void onSnapRegion(int x, int y, quint32 width, quint32 height); + void onPidfd(int pidfd); + void onFailed(quint32 reason); + void setProcessName(const QString &name); + void clearPendingPidfd(); + + ToplevelTagManager m_tagManager; + Snap m_snap; + + wl_registry *m_seatRegistry = nullptr; + wl_seat *m_seat = nullptr; + + QList> m_windows; + bool m_initialized = false; + bool m_startRequested = false; + bool m_started = false; + bool m_confirmed = false; + QRect m_region; + QString m_processName; + int m_pendingPidfd = -1; +}; + +// Per-output mask window controller, exposed to QML as `snapController`. +class SnapController : public QObject +{ + Q_OBJECT + Q_PROPERTY(int snapX READ snapX NOTIFY snapRegionChanged) + Q_PROPERTY(int snapY READ snapY NOTIFY snapRegionChanged) + Q_PROPERTY(int snapWidth READ snapWidth NOTIFY snapRegionChanged) + Q_PROPERTY(int snapHeight READ snapHeight NOTIFY snapRegionChanged) + Q_PROPERTY(bool snapVisible READ snapVisible NOTIFY snapRegionChanged) + Q_PROPERTY(QString processName READ processName NOTIFY processNameChanged) + Q_PROPERTY(bool confirmed READ confirmed NOTIFY confirmedChanged) + Q_PROPERTY(bool backgroundEnabled READ backgroundEnabled WRITE setBackgroundEnabled + NOTIFY backgroundEnabledChanged) + Q_PROPERTY(QString backgroundSource READ backgroundSource WRITE setBackgroundSource + NOTIFY backgroundSourceChanged) + Q_PROPERTY(int screenX READ screenX NOTIFY screenGeometryChanged) + Q_PROPERTY(int screenY READ screenY NOTIFY screenGeometryChanged) + Q_PROPERTY(int screenWidth READ screenWidth NOTIFY screenGeometryChanged) + Q_PROPERTY(int screenHeight READ screenHeight NOTIFY screenGeometryChanged) + +public: + explicit SnapController(SnapSession *session, QObject *parent = nullptr); + ~SnapController() override; + + void setup(QWindow *window, QScreen *screen); + Q_INVOKABLE void confirmSelection(); + Q_INVOKABLE void quit(); + + int snapX() const + { + return m_x; + } + + int snapY() const + { + return m_y; + } + + int snapWidth() const + { + return m_w; + } + + int snapHeight() const + { + return m_h; + } + + bool snapVisible() const + { + return m_visible; + } + + QString processName() const; + bool confirmed() const; + + bool backgroundEnabled() const + { + return m_backgroundEnabled; + } + + void setBackgroundEnabled(bool enabled); + + QString backgroundSource() const + { + return m_backgroundSource; + } + + void setBackgroundSource(const QString &source); + int screenX() const; + int screenY() const; + int screenWidth() const; + int screenHeight() const; + +Q_SIGNALS: + void snapRegionChanged(); + void processNameChanged(); + void confirmedChanged(); + void backgroundEnabledChanged(); + void backgroundSourceChanged(); + void screenGeometryChanged(); + +private: + void onSessionRegionChanged(); + void onSessionProcessNameChanged(); + void onSessionConfirmedChanged(); + + SnapSession *m_session = nullptr; + QPointer m_window; + QPointer m_screen; + + int m_x = 0; + int m_y = 0; + int m_w = 0; + int m_h = 0; + bool m_visible = false; + bool m_backgroundEnabled = false; + QString m_backgroundSource; +}; + +#endif // SNAPPROXY_H diff --git a/examples/test_toplevel_tag/CMakeLists.txt b/examples/test_toplevel_tag/CMakeLists.txt new file mode 100644 index 0000000000..4ac6580648 --- /dev/null +++ b/examples/test_toplevel_tag/CMakeLists.txt @@ -0,0 +1,35 @@ +find_package(Qt6 REQUIRED COMPONENTS Gui WaylandClient Widgets) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS GuiPrivate WaylandClientPrivate) +endif() +find_package(PkgConfig REQUIRED) +pkg_get_variable(WAYLAND_PROTOCOLS_DATADIR wayland-protocols pkgdatadir) + + +set(BIN_NAME test-toplevel-tag) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${WAYLAND_PROTOCOLS_DATADIR}/staging/xdg-toplevel-tag/xdg-toplevel-tag-v1.xml +) + +# xdg-toplevel-tag references xdg_toplevel_interface from xdg-shell +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${WAYLAND_PROTOCOLS_DATADIR}/stable/xdg-shell/xdg-shell.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::Widgets + Qt6::WaylandClient + Qt6::GuiPrivate + Qt6::WaylandClientPrivate +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_toplevel_tag/main.cpp b/examples/test_toplevel_tag/main.cpp new file mode 100644 index 0000000000..9097441b96 --- /dev/null +++ b/examples/test_toplevel_tag/main.cpp @@ -0,0 +1,145 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "qwayland-xdg-toplevel-tag-v1.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class XdgToplevelTagManager + : public QWaylandClientExtensionTemplate + , public QtWayland::xdg_toplevel_tag_manager_v1 +{ + Q_OBJECT +public: + explicit XdgToplevelTagManager() + : QWaylandClientExtensionTemplate(1) + { + } +}; + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + XdgToplevelTagManager manager; + + QMainWindow window; + window.setWindowTitle("Toplevel Tag Test"); + window.resize(400, 300); + + auto *central = new QWidget(&window); + auto *layout = new QVBoxLayout(central); + + auto *tagEdit = new QLineEdit("main-window", central); + tagEdit->setPlaceholderText("Enter tag..."); + auto *descEdit = new QLineEdit("Main Window", central); + descEdit->setPlaceholderText("Enter description..."); + auto *setTagBtn = new QPushButton("Set Tag", central); + auto *setDescBtn = new QPushButton("Set Description", central); + auto *fullscreenBtn = new QPushButton("Fullscreen", central); + auto *restoreBtn = new QPushButton("Restore", central); + auto *tagLabel = new QLabel("Supported Tags:", central); + auto *tagCombo = new QComboBox(central); + tagCombo->addItem("test:invalid tag"); + tagCombo->addItem("org.deepin.treeland.im-candidate-panel"); + tagCombo->addItem("org.deepin.treeland.privileged-overlay"); + auto *statusLabel = new QLabel(central); + + layout->addWidget(tagEdit); + layout->addWidget(descEdit); + layout->addWidget(tagLabel); + layout->addWidget(tagCombo); + layout->addWidget(setTagBtn); + layout->addWidget(setDescBtn); + layout->addWidget(fullscreenBtn); + layout->addWidget(restoreBtn); + layout->addWidget(statusLabel); + window.setCentralWidget(central); + + window.show(); + + QTimer::singleShot(500, &window, [&] { + if (!manager.isActive()) { + statusLabel->setText("Error: compositor does not support xdg_toplevel_tag_manager_v1"); + qWarning() << "xdg_toplevel_tag_manager_v1 not available"; + return; + } + + QWindow *handle = window.windowHandle(); + if (!handle || !handle->handle()) { + qWarning() << "window handle not ready"; + return; + } + + auto *waylandWindow = static_cast(handle->handle()); + auto *shell = waylandWindow->shellSurface(); + if (!shell) { + qWarning() << "no shell surface"; + return; + } + + auto role = shell->surfaceRole(); + auto *rawValue = std::any_cast(&role); + if (!rawValue || !*rawValue) { + qWarning() << "failed to get xdg_toplevel from surfaceRole"; + return; + } + auto *raw = *rawValue; + qDebug() << "xdg_toplevel ready:" << (void *)raw; + + QObject::connect(setTagBtn, + &QPushButton::clicked, + &window, + [raw, &manager, tagEdit, statusLabel] { + const QString tag = tagEdit->text(); + if (!tag.isEmpty()) { + manager.set_toplevel_tag(raw, tag); + statusLabel->setText(QString("Tag set: %1").arg(tag)); + } + }); + + QObject::connect(setDescBtn, + &QPushButton::clicked, + &window, + [raw, &manager, descEdit, statusLabel] { + const QString desc = descEdit->text(); + if (!desc.isEmpty()) { + manager.set_toplevel_description(raw, desc); + statusLabel->setText(QString("Description set: %1").arg(desc)); + } + }); + + QObject::connect(fullscreenBtn, &QPushButton::clicked, + &window, &QWidget::showFullScreen); + + QObject::connect(restoreBtn, &QPushButton::clicked, + &window, &QWidget::showNormal); + + QObject::connect(tagCombo, + &QComboBox::currentIndexChanged, + &window, + [tagCombo, tagEdit](int index) { + const QString text = tagCombo->itemText(index); + if (!text.isEmpty()) { + tagEdit->setText(text); + } + }); + + statusLabel->setText("Ready"); + }); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/test_wallpaper_color/CMakeLists.txt b/examples/test_wallpaper_color/CMakeLists.txt new file mode 100644 index 0000000000..f8e9979b11 --- /dev/null +++ b/examples/test_wallpaper_color/CMakeLists.txt @@ -0,0 +1,21 @@ +find_package(Qt6 REQUIRED COMPONENTS Core Gui WaylandClient) +find_package(TreelandProtocols REQUIRED) + +set(BIN_NAME test-wallpaper-color) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wallpaper-color-v1.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::WaylandClient +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_wallpaper_color/main.cpp b/examples/test_wallpaper_color/main.cpp new file mode 100644 index 0000000000..ecf26c2e51 --- /dev/null +++ b/examples/test_wallpaper_color/main.cpp @@ -0,0 +1,48 @@ +// Copyright (C) 2024 rewine . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "qwayland-treeland-wallpaper-color-v1.h" + +#include +#include +#include + +class WallpaperColorManager + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_wallpaper_color_manager_v1 +{ + Q_OBJECT +public: + explicit WallpaperColorManager(); + + void treeland_wallpaper_color_manager_v1_output_color(const QString &output, + uint32_t isdark) override + { + qInfo() << "Output(" << output << ") wallpaper is dark type: " << isdark; + } +}; + +WallpaperColorManager::WallpaperColorManager() + : QWaylandClientExtensionTemplate(1) +{ +} + +int main(int argc, char *argv[]) +{ + qputenv("QT_QPA_PLATFORM", "wayland"); + QGuiApplication app(argc, argv); + WallpaperColorManager manager; + + QObject::connect(&manager, &WallpaperColorManager::activeChanged, &manager, [&manager] { + qDebug() << "personalzation manager init: " << manager.isActive(); + const auto screens = QGuiApplication::screens(); + for (auto *screen : screens) { + qDebug() << "watch: " << screen->name(); + manager.watch(screen->name()); + } + }); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/test_window_appearance/CMakeLists.txt b/examples/test_window_appearance/CMakeLists.txt new file mode 100644 index 0000000000..71a008587f --- /dev/null +++ b/examples/test_window_appearance/CMakeLists.txt @@ -0,0 +1,28 @@ +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +find_package(Qt6 REQUIRED COMPONENTS WaylandClient Gui Widgets) +find_package(TreelandProtocols REQUIRED) + +set(BIN_NAME test-window-appearance) + +qt_add_executable(${BIN_NAME} + main.cpp + appearance_manager.h + appearance_manager.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-appearance-unstable-v1.xml + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-appearance-manager-unstable-v1.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::Widgets + Qt6::WaylandClient +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_window_appearance/appearance_manager.cpp b/examples/test_window_appearance/appearance_manager.cpp new file mode 100644 index 0000000000..2ab965024a --- /dev/null +++ b/examples/test_window_appearance/appearance_manager.cpp @@ -0,0 +1,73 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "appearance_manager.h" + +QT_BEGIN_NAMESPACE + +AppearanceObserver::AppearanceObserver() + : QWaylandClientExtensionTemplate(1) +{ +} + +void AppearanceObserver::treeland_appearance_v1_cursor_theme(const QString &name) +{ + Q_EMIT cursorThemeChanged(name); +} + +void AppearanceObserver::treeland_appearance_v1_cursor_size(uint32_t width, uint32_t height) +{ + Q_EMIT cursorSizeChanged(width, height); +} + +void AppearanceObserver::treeland_appearance_v1_font(const QString &font_name) +{ + Q_EMIT fontChanged(font_name); +} + +void AppearanceObserver::treeland_appearance_v1_monospace_font(const QString &font_name) +{ + Q_EMIT monospaceFontChanged(font_name); +} + +void AppearanceObserver::treeland_appearance_v1_font_size(uint32_t size) +{ + Q_EMIT fontSizeChanged(size); +} + +void AppearanceObserver::treeland_appearance_v1_icon_theme(const QString &theme_name) +{ + Q_EMIT iconThemeChanged(theme_name); +} + +void AppearanceObserver::treeland_appearance_v1_accent_color(uint32_t r, uint32_t g, uint32_t b) +{ + Q_EMIT accentColorChanged(r, g, b); +} + +void AppearanceObserver::treeland_appearance_v1_window_opacity(wl_fixed_t opacity) +{ + Q_EMIT windowOpacityChanged(opacity); +} + +void AppearanceObserver::treeland_appearance_v1_color_scheme(uint32_t scheme) +{ + Q_EMIT colorSchemeChanged(scheme); +} + +void AppearanceObserver::treeland_appearance_v1_titlebar_height(uint32_t height) +{ + Q_EMIT titlebarHeightChanged(height); +} + +void AppearanceObserver::treeland_appearance_v1_corner_radius(uint32_t radius) +{ + Q_EMIT cornerRadiusChanged(radius); +} + +AppearanceManager::AppearanceManager() + : QWaylandClientExtensionTemplate(1) +{ +} + +QT_END_NAMESPACE diff --git a/examples/test_window_appearance/appearance_manager.h b/examples/test_window_appearance/appearance_manager.h new file mode 100644 index 0000000000..1fcf133744 --- /dev/null +++ b/examples/test_window_appearance/appearance_manager.h @@ -0,0 +1,66 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef APPEARANCE_MANAGER_H +#define APPEARANCE_MANAGER_H + +#include "qwayland-treeland-appearance-unstable-v1.h" +#include "qwayland-treeland-appearance-manager-unstable-v1.h" + +#include + +QT_BEGIN_NAMESPACE + +// Read-only observer for user-level appearance settings. Any client may bind +// this global; the compositor pushes the current value of every setting +// immediately after bind and broadcasts an event whenever a setting changes. +class AppearanceObserver + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_appearance_v1 +{ + Q_OBJECT +public: + explicit AppearanceObserver(); + +Q_SIGNALS: + void cursorThemeChanged(const QString &name); + void cursorSizeChanged(uint32_t width, uint32_t height); + void fontChanged(const QString &font_name); + void monospaceFontChanged(const QString &font_name); + void fontSizeChanged(uint32_t size); + void iconThemeChanged(const QString &theme_name); + void accentColorChanged(uint32_t r, uint32_t g, uint32_t b); + void windowOpacityChanged(wl_fixed_t opacity); + void colorSchemeChanged(uint32_t scheme); + void titlebarHeightChanged(uint32_t height); + void cornerRadiusChanged(uint32_t radius); + +protected: + void treeland_appearance_v1_cursor_theme(const QString &name) override; + void treeland_appearance_v1_cursor_size(uint32_t width, uint32_t height) override; + void treeland_appearance_v1_font(const QString &font_name) override; + void treeland_appearance_v1_monospace_font(const QString &font_name) override; + void treeland_appearance_v1_font_size(uint32_t size) override; + void treeland_appearance_v1_icon_theme(const QString &theme_name) override; + void treeland_appearance_v1_accent_color(uint32_t r, uint32_t g, uint32_t b) override; + void treeland_appearance_v1_window_opacity(wl_fixed_t opacity) override; + void treeland_appearance_v1_color_scheme(uint32_t scheme) override; + void treeland_appearance_v1_titlebar_height(uint32_t height) override; + void treeland_appearance_v1_corner_radius(uint32_t radius) override; +}; + +// Privileged manager for modifying user-level appearance settings. Binding +// without compositor-level authorization may result in requests being +// silently ignored or the connection being terminated. +class AppearanceManager + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_appearance_manager_v1 +{ + Q_OBJECT +public: + explicit AppearanceManager(); +}; + +QT_END_NAMESPACE + +#endif // APPEARANCE_MANAGER_H diff --git a/examples/test_window_appearance/main.cpp b/examples/test_window_appearance/main.cpp new file mode 100644 index 0000000000..d436948b4f --- /dev/null +++ b/examples/test_window_appearance/main.cpp @@ -0,0 +1,224 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "appearance_manager.h" + +#include +#include +#include +#include +#include +#include + +#include + +class TestWindow : public QWidget +{ + Q_OBJECT +public: + TestWindow() + : m_observer(new AppearanceObserver) + , m_manager(new AppearanceManager) + { + setWindowTitle("Appearance Client (0.6.0)"); + + m_mainLayout = new QVBoxLayout; + + // ---- Color scheme ---- + auto *scheme = addSettingRow("color scheme", {}, {}); + scheme->edit->hide(); + auto *lightBtn = new QPushButton("light"); + auto *darkBtn = new QPushButton("dark"); + for (auto *button : { lightBtn, darkBtn }) + scheme->layout->addWidget(button); + connect(lightBtn, &QPushButton::clicked, this, &TestWindow::setLightScheme); + connect(darkBtn, &QPushButton::clicked, this, &TestWindow::setDarkScheme); + connect(m_observer, &AppearanceObserver::colorSchemeChanged, this, [this, scheme](uint32_t value) { + updateRow(*scheme, value == QtWayland::treeland_appearance_v1::color_scheme_dark + ? "dark" : "light"); + }); + + // ---- Titlebar height ---- + auto *titlebar = addSettingRow( + "titlebar height", "titlebar height in pixels", [this](const QString &text) { + m_manager->set_titlebar_height(text.toUInt()); + }); + connect(m_observer, &AppearanceObserver::titlebarHeightChanged, this, [this, titlebar](uint32_t height) { + updateRow(*titlebar, QString::number(height)); + }); + + // ---- Corner radius ---- + auto *radius = addSettingRow("corner radius", "corner radius in pixels", [this](const QString &text) { + m_manager->set_corner_radius(text.toUInt()); + }); + connect(m_observer, &AppearanceObserver::cornerRadiusChanged, this, [this, radius](uint32_t value) { + updateRow(*radius, QString::number(value)); + }); + + // ---- Cursor theme ---- + auto *cursorTheme = addSettingRow("cursor theme", "cursor theme name", [this](const QString &text) { + m_manager->set_cursor_theme(text); + }); + connect(m_observer, &AppearanceObserver::cursorThemeChanged, this, [this, cursorTheme](const QString &name) { + updateRow(*cursorTheme, name); + }); + + // ---- Cursor size ---- + auto *cursorSize = addSettingRow("cursor size", "cursor size in pixels", [this](const QString &text) { + const uint32_t size = text.toUInt(); + m_manager->set_cursor_size(size, size); + }); + connect(m_observer, &AppearanceObserver::cursorSizeChanged, this, [this, cursorSize](uint32_t width, uint32_t height) { + updateRow(*cursorSize, QString("%1x%2").arg(width).arg(height)); + }); + + // ---- Font ---- + auto *font = addSettingRow("font", "font family name", [this](const QString &text) { + m_manager->set_font(text); + }); + connect(m_observer, &AppearanceObserver::fontChanged, this, [this, font](const QString &name) { + updateRow(*font, name); + }); + + // ---- Monospace font ---- + auto *monoFont = addSettingRow("monospace font", "monospace font family name", [this](const QString &text) { + m_manager->set_monospace_font(text); + }); + connect(m_observer, &AppearanceObserver::monospaceFontChanged, this, [this, monoFont](const QString &name) { + updateRow(*monoFont, name); + }); + + // ---- Font size ---- + auto *fontSize = addSettingRow("font size", "font size in points", [this](const QString &text) { + m_manager->set_font_size(text.toUInt()); + }); + connect(m_observer, &AppearanceObserver::fontSizeChanged, this, [this, fontSize](uint32_t size) { + updateRow(*fontSize, QString::number(size)); + }); + + // ---- Icon theme ---- + auto *iconTheme = addSettingRow("icon theme", "icon theme name", [this](const QString &text) { + m_manager->set_icon_theme(text); + }); + connect(m_observer, &AppearanceObserver::iconThemeChanged, this, [this, iconTheme](const QString &name) { + updateRow(*iconTheme, name); + }); + + // ---- Accent color ---- + auto *accentColor = addSettingRow( + "accent color", "r,g,b (each 0-255), e.g. 44,119,222", + [this](const QString &text) { + const auto parts = text.split(','); + if (parts.size() != 3) { + qWarning() << "accent color must be 3 comma-separated values"; + return; + } + m_manager->set_accent_color(parts[0].toUInt(), parts[1].toUInt(), + parts[2].toUInt()); + }); + connect(m_observer, &AppearanceObserver::accentColorChanged, this, [this, accentColor](uint32_t r, uint32_t g, uint32_t b) { + updateRow(*accentColor, QString("%1,%2,%3").arg(r).arg(g).arg(b)); + }); + + // ---- Window opacity ---- + auto *opacity = addSettingRow( + "window opacity", "opacity [0.0, 1.0], e.g. 0.8", [this](const QString &text) { + bool ok = false; + const double value = text.toDouble(&ok); + if (!ok || value < 0.0 || value > 1.0) { + qWarning() << "window opacity must be in [0.0, 1.0]:" << text; + return; + } + m_manager->set_window_opacity(wl_fixed_from_double(value)); + }); + connect(m_observer, &AppearanceObserver::windowOpacityChanged, this, [this, opacity](wl_fixed_t value) { + updateRow(*opacity, QString::number(wl_fixed_to_double(value), 'f', 2)); + }); + + m_mainLayout->addStretch(); + + qDebug() << "appearance observer active:" << m_observer->isActive() + << "manager active:" << m_manager->isActive(); + + setLayout(m_mainLayout); + setMinimumSize(480, 560); + } + +private: + struct SettingRow + { + QLabel *label = nullptr; + QLineEdit *edit = nullptr; + QHBoxLayout *layout = nullptr; + QString title; + }; + + // Creates a row of "title: " plus an editable field and an + // apply button wired to `apply`. The returned row's label/edit is kept in + // sync by the corresponding observer-signal connection at the call site. + SettingRow *addSettingRow(const QString &title, const QString &placeholder, + const std::function &apply) + { + auto *label = new QLabel(QString("%1: -").arg(title)); + auto *edit = new QLineEdit; + edit->setPlaceholderText(placeholder); + auto *button = new QPushButton(QString("set %1").arg(title)); + + auto *rowLayout = new QHBoxLayout; + rowLayout->addWidget(label, 1); + rowLayout->addWidget(edit, 2); + + // Rows are owned by unique_ptr so that their addresses stay stable + // as more rows are added; observer connections capture the pointer. + auto row = std::make_unique( + SettingRow { label, edit, rowLayout, title }); + auto *rowPtr = row.get(); + m_rows.push_back(std::move(row)); + rowLayout->addWidget(button); + + m_mainLayout->addLayout(rowLayout); + + if (apply) { + connect(button, &QPushButton::clicked, this, [this, edit, apply] { apply(edit->text()); }); + } else { + button->hide(); + } + + return rowPtr; + } + + void updateRow(SettingRow &row, const QString &value) + { + row.label->setText(QString("%1: %2").arg(row.title, value)); + row.edit->blockSignals(true); + row.edit->setText(value); + row.edit->blockSignals(false); + } + + void setLightScheme() + { + m_manager->set_color_scheme(QtWayland::treeland_appearance_manager_v1::color_scheme_light); + } + + void setDarkScheme() + { + m_manager->set_color_scheme(QtWayland::treeland_appearance_manager_v1::color_scheme_dark); + } + + std::vector> m_rows; + QVBoxLayout *m_mainLayout = nullptr; + AppearanceObserver *m_observer = nullptr; + AppearanceManager *m_manager = nullptr; +}; + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + TestWindow window; + window.show(); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/test_window_blur/CMakeLists.txt b/examples/test_window_blur/CMakeLists.txt new file mode 100644 index 0000000000..5047025d41 --- /dev/null +++ b/examples/test_window_blur/CMakeLists.txt @@ -0,0 +1,28 @@ +find_package(Qt6 REQUIRED COMPONENTS Gui WaylandClient Widgets) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS GuiPrivate WaylandClientPrivate) +endif() +find_package(PkgConfig REQUIRED) +pkg_get_variable(WAYLAND_PROTOCOLS_DATADIR wayland-protocols pkgdatadir) + +set(BIN_NAME test-window-blur) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-background-effect/ext-background-effect-v1.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Gui + Qt6::Widgets + Qt6::WaylandClient + Qt6::GuiPrivate + Qt6::WaylandClientPrivate +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_window_blur/main.cpp b/examples/test_window_blur/main.cpp new file mode 100644 index 0000000000..87a302b31b --- /dev/null +++ b/examples/test_window_blur/main.cpp @@ -0,0 +1,253 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// This demo is modeled after quickshell's background_effect implementation: +// https://github.com/quickshell-mirror/quickshell/tree/master/src/wayland/background_effect +// (surface lifecycle handling, capability checks, HiDPI region scaling and +// client-side margin handling follow the same approach used there.) + +#include "qwayland-ext-background-effect-v1.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +using QtWaylandClient::QWaylandWindow; + +class BackgroundEffectManager + : public QWaylandClientExtensionTemplate + , public QtWayland::ext_background_effect_manager_v1 +{ + Q_OBJECT +public: + explicit BackgroundEffectManager() + : QWaylandClientExtensionTemplate(1) + { + initialize(); + } + + bool blurAvailable() const { return isActive() && m_blurAvailable; } + +protected: + void ext_background_effect_manager_v1_capabilities(uint32_t flags) override + { + m_blurAvailable = flags & capability_blur; + } + +private: + bool m_blurAvailable = false; +}; + +class BackgroundEffectSurface : public QtWayland::ext_background_effect_surface_v1 +{ +public: + explicit BackgroundEffectSurface(struct ::ext_background_effect_surface_v1 *surface) + : QtWayland::ext_background_effect_surface_v1(surface) + { + } + + ~BackgroundEffectSurface() override + { + if (isInitialized()) + destroy(); + } + + void setBlurRegion(const QRegion ®ion) + { + if (!isInitialized()) + return; + + if (region.isEmpty()) { + // NULL region removes the effect. + set_blur_region(nullptr); + return; + } + + auto *display = QtWaylandClient::QWaylandIntegration::instance()->display(); + struct ::wl_region *wlRegion = display->createRegion(region); + set_blur_region(wlRegion); + // set_blur_region has copy semantics, safe to destroy immediately. + wl_region_destroy(wlRegion); + } +}; + +class BlurWindow : public QWidget +{ + Q_OBJECT +public: + explicit BlurWindow() + { + setWindowTitle("Window Blur Test"); + // The window itself must be translucent so that the background + // behind it can be seen and blurred. + setAttribute(Qt::WA_TranslucentBackground); + resize(640, 480); + + auto *layout = new QVBoxLayout(this); + + m_statusLabel = new QLabel("Blur region: off", this); + layout->addWidget(m_statusLabel); + + auto *toggleButton = new QPushButton("Toggle blur region", this); + layout->addWidget(toggleButton); + connect(toggleButton, &QPushButton::clicked, this, &BlurWindow::toggleBlur); + } + +protected: + // The platform surface (and with it the wl_surface) may be created after + // showEvent, so the event filter is the earliest reliable hook. When the + // window is hidden the wl_surface is destroyed; keep the effect in sync + // with that lifecycle so it is re-created on the next show. + bool eventFilter(QObject *watched, QEvent *event) override + { + if (event->type() == QEvent::PlatformSurface) { + auto *surfaceEvent = static_cast(event); + if (surfaceEvent->surfaceEventType() == QPlatformSurfaceEvent::SurfaceCreated) { + attachWaylandWindow(); + } else if (surfaceEvent->surfaceEventType() + == QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed) { + detachWaylandWindow(); + } + } + return QWidget::eventFilter(watched, event); + } + + void showEvent(QShowEvent *event) override + { + QWidget::showEvent(event); + if (!windowHandle()->parent()) + windowHandle()->installEventFilter(this); + // The platform surface may already exist when re-showing. + attachWaylandWindow(); + } + + void resizeEvent(QResizeEvent *event) override + { + QWidget::resizeEvent(event); + // The blur region is surface-local state; keep it in sync with the + // window size so it always covers the whole surface. + applyBlurRegion(); + } + +private: + void toggleBlur() + { + m_blurEnabled = !m_blurEnabled; + createEffectSurface(); + applyBlurRegion(); + m_statusLabel->setText(m_blurEnabled ? "Blur region: on" : "Blur region: off"); + } + + void attachWaylandWindow() + { + auto *waylandWindow = dynamic_cast(windowHandle()->handle()); + if (waylandWindow == m_waylandWindow) + return; + + if (m_waylandWindow) { + disconnect(m_waylandWindow, nullptr, this, nullptr); + m_effect.reset(); + } + + m_waylandWindow = waylandWindow; + if (!m_waylandWindow) + return; + + connect(m_waylandWindow, + &QWaylandWindow::surfaceCreated, + this, + &BlurWindow::createEffectSurface); + connect(m_waylandWindow, + &QWaylandWindow::surfaceDestroyed, + this, + &BlurWindow::onWaylandSurfaceDestroyed); + + // The wl_surface may already exist when the filter installs late. + if (m_waylandWindow->surface()) + createEffectSurface(); + } + + void detachWaylandWindow() + { + if (m_waylandWindow) { + disconnect(m_waylandWindow, nullptr, this, nullptr); + m_waylandWindow = nullptr; + } + m_effect.reset(); + } + + void createEffectSurface() + { + if (m_effect || !m_blurEnabled || !m_waylandWindow) + return; + + if (!m_manager.blurAvailable()) { + qWarning() << "ext-background-effect-v1 blur is not supported by the compositor"; + return; + } + + if (!m_waylandWindow->surface()) + return; + + m_effect = std::make_unique( + m_manager.get_background_effect(m_waylandWindow->surface())); + applyBlurRegion(); + } + + void onWaylandSurfaceDestroyed() + { + m_effect.reset(); + } + + void applyBlurRegion() + { + if (!m_effect) + return; + + QRegion region; + if (m_blurEnabled) { + region = QRegion(0, 0, width(), height()); + + // Blur region is specified in surface-local (native) coordinates: + // scale logical pixels by the device pixel ratio and offset by the + // client-side frame margins, mirroring quickshell's handling. + const auto scale = QHighDpiScaling::factor(windowHandle()); + if (!qFuzzyCompare(scale, 1.0)) + region = QHighDpi::scale(region, scale); + + const auto margins = m_waylandWindow->clientSideMargins(); + region.translate(margins.left(), margins.top()); + } + + m_effect->setBlurRegion(region); + } + + BackgroundEffectManager m_manager; + QLabel *m_statusLabel = nullptr; + QWaylandWindow *m_waylandWindow = nullptr; + std::unique_ptr m_effect; + bool m_blurEnabled = false; +}; + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + BlurWindow window; + window.show(); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/test_xdgport_wallpaper/CMakeLists.txt b/examples/test_xdgport_wallpaper/CMakeLists.txt new file mode 100644 index 0000000000..6ee65c48a5 --- /dev/null +++ b/examples/test_xdgport_wallpaper/CMakeLists.txt @@ -0,0 +1,21 @@ +set(CMAKE_AUTOUIC ON) + +set(BIN_NAME test-xdg-wallpaper) + +find_package(Qt6 REQUIRED COMPONENTS Gui Widgets) +find_package(TreelandProtocols REQUIRED) + +qt_add_executable(${BIN_NAME} + main.cpp + mainwindow.cpp + mainwindow.h + mainwindow.ui +) + +target_link_libraries(${BIN_NAME} PRIVATE + Qt6::Gui + Qt6::Widgets + Qt6::DBus +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/examples/test_xdgport_wallpaper/main.cpp b/examples/test_xdgport_wallpaper/main.cpp new file mode 100644 index 0000000000..40dba79f74 --- /dev/null +++ b/examples/test_xdgport_wallpaper/main.cpp @@ -0,0 +1,14 @@ +// Copyright (C) 2024 rewine . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "mainwindow.h" + +#include + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + MainWindow w; + w.show(); + return a.exec(); +} diff --git a/examples/test_xdgport_wallpaper/mainwindow.cpp b/examples/test_xdgport_wallpaper/mainwindow.cpp new file mode 100644 index 0000000000..e3daabb677 --- /dev/null +++ b/examples/test_xdgport_wallpaper/mainwindow.cpp @@ -0,0 +1,60 @@ +// Copyright (C) 2024 rewine . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "mainwindow.h" + +#include "ui_mainwindow.h" + +#include +#include +#include +#include +#include +#include + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent) + , ui(new Ui::MainWindow) +{ + ui->setupUi(this); + connect(ui->setButton, &QPushButton::clicked, this, &MainWindow::setWallpaper); + + interface = new QDBusInterface("org.freedesktop.portal.Desktop", + "/org/freedesktop/portal/desktop", + "org.freedesktop.portal.Wallpaper", + QDBusConnection::sessionBus(), + this); +} + +MainWindow::~MainWindow() +{ + delete ui; +} + +void MainWindow::setWallpaper() +{ + QString app_id = "G4"; + QString parent_window = ""; + QString config = "test_config.ini"; + QSettings settings(config, QSettings::IniFormat); + QString uri = + settings.value("Wallpaper/path", "/home/uos/Pictures/Wallpapers/abc-123.jpg").toString(); + qDebug() << "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=========" << uri; + + QVariantMap options; + options.insert("output", "X11-2"); + options.insert("set-on", "background"); + + QDBusMessage reply = + interface->call("SetWallpaperURI", parent_window, uri, QVariant::fromValue(options)); + + // 检查返回值 + if (reply.type() == QDBusMessage::ErrorMessage) { + qWarning() << "Failed to set wallpaper:" << reply.errorMessage(); + return; + } + + // 处理返回值 + uint response = reply.arguments().at(0).toUInt(); + qDebug() << "Wallpaper set with response code:" << response; +} diff --git a/examples/test_xdgport_wallpaper/mainwindow.h b/examples/test_xdgport_wallpaper/mainwindow.h new file mode 100644 index 0000000000..f4a7a56987 --- /dev/null +++ b/examples/test_xdgport_wallpaper/mainwindow.h @@ -0,0 +1,35 @@ +// Copyright (C) 2024 rewine . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace Ui { +class MainWindow; +} + +QT_END_NAMESPACE + +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + MainWindow(QWidget *parent = nullptr); + ~MainWindow(); + +private Q_SLOTS: + void setWallpaper(); + +private: + Ui::MainWindow *ui; + QDBusInterface *interface; +}; + +#endif // MAINWINDOW_H diff --git a/examples/test_xdgport_wallpaper/mainwindow.ui b/examples/test_xdgport_wallpaper/mainwindow.ui new file mode 100644 index 0000000000..e140314c72 --- /dev/null +++ b/examples/test_xdgport_wallpaper/mainwindow.ui @@ -0,0 +1,45 @@ + + + MainWindow + + + + 0 + 0 + 800 + 600 + + + + MainWindow + + + + + + 310 + 150 + 106 + 36 + + + + Set Wallpaper + + + + + + + 0 + 0 + 800 + 35 + + + + + + + + diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000000..b5fbc86614 --- /dev/null +++ b/flake.lock @@ -0,0 +1,131 @@ +{ + "nodes": { + "ddm": { + "inputs": { + "flake-utils": [ + "flake-utils" + ], + "nix-filter": [ + "nix-filter" + ], + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1753066592, + "narHash": "sha256-jtFBL0yT1fBwatqvRuCvp0LjKOChU4YGmZvMpIIrAmE=", + "owner": "linuxdeepin", + "repo": "ddm", + "rev": "e3a27b23cefe51adbfab973043b26959136ea4ad", + "type": "github" + }, + "original": { + "owner": "linuxdeepin", + "repo": "ddm", + "type": "github" + } + }, + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1731533236, + "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "nix-filter": { + "locked": { + "lastModified": 1731533336, + "narHash": "sha256-oRam5PS1vcrr5UPgALW0eo1m/5/pls27Z/pabHNy2Ms=", + "owner": "numtide", + "repo": "nix-filter", + "rev": "f7653272fd234696ae94229839a99b73c9ab7de0", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "nix-filter", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1752950548, + "narHash": "sha256-NS6BLD0lxOrnCiEOcvQCDVPXafX1/ek1dfJHX1nUIzc=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "c87b95e25065c028d31a94f06a62927d18763fdf", + "type": "github" + }, + "original": { + "owner": "NixOS", + "ref": "nixos-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "ddm": "ddm", + "flake-utils": "flake-utils", + "nix-filter": "nix-filter", + "nixpkgs": "nixpkgs", + "treeland-protocols": "treeland-protocols" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + }, + "treeland-protocols": { + "inputs": { + "flake-utils": [ + "flake-utils" + ], + "nix-filter": [ + "nix-filter" + ], + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1737101824, + "narHash": "sha256-keu/J/mEW7VIQ2Nyo9SaOreUYoDdgxONb66c6XN3Gnc=", + "owner": "linuxdeepin", + "repo": "treeland-protocols", + "rev": "b087c563ad5b07f61ebbe2417251839ef6876d45", + "type": "github" + }, + "original": { + "owner": "linuxdeepin", + "repo": "treeland-protocols", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000000..e33efdd4da --- /dev/null +++ b/flake.nix @@ -0,0 +1,215 @@ +{ + description = "A basic flake to help develop treeland"; + + inputs = { + nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; + flake-utils.url = "github:numtide/flake-utils"; + nix-filter.url = "github:numtide/nix-filter"; + ddm = { + url = "github:linuxdeepin/ddm"; + inputs.nixpkgs.follows = "nixpkgs"; + inputs.flake-utils.follows = "flake-utils"; + inputs.nix-filter.follows = "nix-filter"; + }; + treeland-protocols = { + url = "github:linuxdeepin/treeland-protocols"; + inputs.nixpkgs.follows = "nixpkgs"; + inputs.flake-utils.follows = "flake-utils"; + inputs.nix-filter.follows = "nix-filter"; + }; + }; + + outputs = { self, nixpkgs, flake-utils, nix-filter, ddm, treeland-protocols }@input: + flake-utils.lib.eachSystem [ "x86_64-linux" "aarch64-linux" "riscv64-linux" ] + (system: + let + pkgs = nixpkgs.legacyPackages.${system}; + in + rec { + nixosConfigurations.vm = nixpkgs.lib.nixosSystem { + inherit system; + modules = [ + { + imports = [ "${nixpkgs}/nixos/modules/virtualisation/qemu-vm.nix" ]; + + environment.systemPackages = with pkgs; [ + foot + gdb + seatd + sdnotify-wrapper + treeland + ]; + + security.pam.services = { + ddm.text = '' + auth substack login + account include login + password substack login + session include login + ''; + + ddm-greeter.text = '' + auth required pam_succeed_if.so audit quiet_success user = dde + auth optional pam_permit.so + account required pam_succeed_if.so audit quiet_success user = dde + account sufficient pam_unix.so + password required pam_deny.so + session required pam_succeed_if.so audit quiet_success user = dde + session required pam_env.so conffile=/etc/pam/environment readenv=0 + session optional ${pkgs.systemd}/lib/security/pam_systemd.so + session optional pam_keyinit.so force revoke + session optional pam_permit.so + ''; + + ddm-autologin.text = '' + auth requisite pam_nologin.so + auth required pam_succeed_if.so uid >= 1000 quiet + auth required pam_permit.so + account include system-local-login + password include system-local-login + session include system-local-login + ''; + }; + + # services.xserver.displayManager.defaultSession = "Treeland"; + # services.xserver.displayManager.sessionPackages = [ treeland ]; + environment.etc."ddm.conf".text = '' + [General] + DisplayServer=single + HaltCommand=/run/current-system/systemd/bin/systemctl poweroff + Numlock=none + RebootCommand=/run/current-system/systemd/bin/systemctl reboot + [Users] + HideShells=/run/current-system/sw/bin/nologin + HideUsers=nixbld1,nixbld10,nixbld11,nixbld12,nixbld13,nixbld14,nixbld15,nixbld16,nixbld17,nixbld18,nixbld19,nixbld2,nixbld20,nixbld21,nixbld22,nixbld23,nixbld24,nixbld25,nixbld26,nixbld27,nixbld28,nixbld29,nixbld3,nixbld30,nixbld31,nixbld32,nixbld4,nixbld5,nixbld6,nixbld7,nixbld8,nixbld9 + MaximumUid=30000 + [Wayland] + SessionDir=${treeland}/share/wayland-sessions + [Single] + CompositorCommand=treeland + SessionDir=${treeland}/share/wayland-sessions + ''; + environment.pathsToLink = [ "/share/ddm" ]; + + users.groups.dde = { }; + users.users.dde = { + home = "/var/lib/ddm"; + group = "dde"; + isSystemUser = true; + }; + services.deepin.dde-daemon.enable = true; # DDM + + services.dbus.packages = [ treeland ]; + systemd.tmpfiles.packages = [ treeland ]; + # systemd.packages = [ treeland ]; + systemd.services.display-manager.after = [ + "systemd-user-sessions.service" + "getty@tty7.service" + "plymouth-quit.service" + "systemd-logind.service" + ]; + systemd.services.display-manager.conflicts = [ + "getty@tty7.service" + ]; + + systemd.services.display-manager.enable = true; + + services.xserver.enable = true; + services.xserver.displayManager.job = { + execCmd = "exec /run/current-system/sw/bin/ddm"; + }; + # To enable user switching, allow sddm to allocate TTYs/displays dynamically. + services.xserver.tty = null; + services.xserver.display = null; + + services.accounts-daemon.enable = true; + + hardware.opengl.enable = true; + programs.xwayland.enable = true; + security.polkit.enable = true; + + services.dbus.enable = true; + services.openssh.enable = true; + services.xserver.displayManager.lightdm.enable = false; + + users.users.test = { + isNormalUser = true; + uid = 1000; + extraGroups = [ "wheel" "networkmanager" "sound" "video" "input" "tty" "ssh" ]; + password = "test"; + }; + + users.users.test2 = { + isNormalUser = true; + uid = 1001; + password = "test2"; + }; + + virtualisation = { + qemu.options = [ "-vga virtio -device virtio-gpu-pci" ]; + cores = 8; + memorySize = 8192; + diskSize = 16384; + resolution = { x = 1920; y = 1080; }; + }; + system.stateVersion = "25.05"; + } + ]; + }; + + + packages = (import ./default.nix { + inherit pkgs nix-filter; + ddm = ddm.packages.${system}.default; + treeland-protocols = treeland-protocols.packages.${system}.default; + }) // { + qemu = self.nixosConfigurations.${system}.vm.config.system.build.vm; + }; + + treeland = packages.default; + + apps.qemu = { + type = "app"; + program = "${self.packages.${system}.qemu}/bin/run-nixos-vm"; + }; + + devShells.default = pkgs.mkShell { + packages = with pkgs; [ + # For submodule waylib and vendored wlroots + wayland + wayland-protocols + wlr-protocols + vulkan-loader + xorg.libXdmcp + xorg.xcbutilerrors + seatd + mesa + libdrm + vulkan-loader + seatd + ]; + + inputsFrom = [ + self.packages.${system}.treeland.override { + #It's submodule, prevent infinite loop calls + waylib = null; + qwlroot = null; + } + ]; + + shellHook = + let + makeQtpluginPath = pkgs.lib.makeSearchPathOutput "out" pkgs.qt6.qtbase.qtPluginPrefix; + makeQmlpluginPath = pkgs.lib.makeSearchPathOutput "out" pkgs.qt6.qtbase.qtQmlPrefix; + in + '' + #export QT_LOGGING_RULES="*.debug=true;qt.*.debug=false" + #export WAYLAND_DEBUG=1 + export QT_PLUGIN_PATH=${makeQtpluginPath (with pkgs.qt6; [ qtbase qtdeclarative qtimageformats qtwayland qtsvg ])} + export QML2_IMPORT_PATH=${makeQmlpluginPath (with pkgs; with qt6; [ qtdeclarative deepin.dtk6declarative ] )} + export QML_IMPORT_PATH=$QML2_IMPORT_PATH + ''; + }; + } + ); +} diff --git a/garnix.yaml b/garnix.yaml new file mode 100644 index 0000000000..aac3532a6b --- /dev/null +++ b/garnix.yaml @@ -0,0 +1,4 @@ +builds: + exclude: + - 'nixosConfigurations.*' + - 'packages.*.qemu' diff --git a/misc/CMakeLists.txt b/misc/CMakeLists.txt new file mode 100644 index 0000000000..b7b17cb03f --- /dev/null +++ b/misc/CMakeLists.txt @@ -0,0 +1,6 @@ +add_subdirectory(dbus) +add_subdirectory(dconfig) +add_subdirectory(systemd) +add_subdirectory(wayland-sessions) +add_subdirectory(cmake) +add_subdirectory(polkit) diff --git a/misc/cmake/CMakeLists.txt b/misc/cmake/CMakeLists.txt new file mode 100644 index 0000000000..248bf14226 --- /dev/null +++ b/misc/cmake/CMakeLists.txt @@ -0,0 +1,13 @@ +include(CMakePackageConfigHelpers) + +if(TREELAND_INSTALL_DEV) + configure_package_config_file( + ${CMAKE_CURRENT_SOURCE_DIR}/TreelandConfig.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/TreelandConfig.cmake + INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/treeland + ) + + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/TreelandConfig.cmake + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/treeland + ) +endif() diff --git a/misc/cmake/TreelandConfig.cmake.in b/misc/cmake/TreelandConfig.cmake.in new file mode 100644 index 0000000000..cb3fa0b4fe --- /dev/null +++ b/misc/cmake/TreelandConfig.cmake.in @@ -0,0 +1,3 @@ +@PACKAGE_INIT@ + +include("${CMAKE_CURRENT_LIST_DIR}/TreelandTargets.cmake") diff --git a/misc/dbus/CMakeLists.txt b/misc/dbus/CMakeLists.txt new file mode 100644 index 0000000000..d55d693713 --- /dev/null +++ b/misc/dbus/CMakeLists.txt @@ -0,0 +1,4 @@ +install(FILES + "org.deepin.compositor1.conf" + DESTINATION "${CMAKE_INSTALL_DATADIR}/dbus-1/system.d" +) diff --git a/misc/dbus/org.deepin.compositor1.conf b/misc/dbus/org.deepin.compositor1.conf new file mode 100644 index 0000000000..69a6012ae3 --- /dev/null +++ b/misc/dbus/org.deepin.compositor1.conf @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + diff --git a/misc/dbus/org.deepin.compositor1.xml b/misc/dbus/org.deepin.compositor1.xml new file mode 100644 index 0000000000..e2e0312f72 --- /dev/null +++ b/misc/dbus/org.deepin.compositor1.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/misc/dconfig/CMakeLists.txt b/misc/dconfig/CMakeLists.txt new file mode 100644 index 0000000000..85ff557b9a --- /dev/null +++ b/misc/dconfig/CMakeLists.txt @@ -0,0 +1,9 @@ +install(FILES + "org.deepin.dde.treeland.json" + "org.deepin.dde.treeland.app.json" + "org.deepin.dde.treeland.animation.json" + "org.deepin.dde.treeland.user.json" + "org.deepin.dde.treeland.output.json" + "org.deepin.dde.treeland.user.seat.json" + DESTINATION "${CMAKE_INSTALL_DATADIR}/dsg/configs/org.deepin.dde.treeland" +) diff --git a/misc/dconfig/org.deepin.dde.treeland.animation.json b/misc/dconfig/org.deepin.dde.treeland.animation.json new file mode 100644 index 0000000000..f417bee470 --- /dev/null +++ b/misc/dconfig/org.deepin.dde.treeland.animation.json @@ -0,0 +1,303 @@ +{ + "magic": "dsg.config.meta", + "version": "1.0", + "contents": { + "lockscreen": { + "value": true, + "serial": 0, + "flags": [], + "name": "Login and lock screen", + "name[zh_CN]": "登录与锁屏界面", + "description": "Control content slides, background transitions and control button resizing on login and lock screens.", + "description[zh_CN]": "统一控制登录与锁屏界面的内容滑动、背景过渡和控制按钮尺寸变化。", + "permissions": "readwrite", + "visibility": "public" + }, + "windowOpen": { + "value": true, + "serial": 0, + "flags": [], + "name": "Window open animation", + "name[zh_CN]": "窗口打开动画", + "description": "Animate normal window opening. Disabling opens the window immediately.", + "description[zh_CN]": "控制普通窗口打开动画;关闭时窗口立即显示。", + "permissions": "readwrite", + "visibility": "public" + }, + "windowClose": { + "value": true, + "serial": 0, + "flags": [], + "name": "Window close animation", + "name[zh_CN]": "窗口关闭动画", + "description": "Animate normal window closing. Disabling closes the window immediately.", + "description[zh_CN]": "控制普通窗口关闭动画;关闭时窗口立即关闭。", + "permissions": "readwrite", + "visibility": "public" + }, + "launchpadOpenFullscreen": { + "value": true, + "serial": 0, + "flags": [], + "name": "Launcher open animation", + "name[zh_CN]": "启动器打开动画", + "description": "Animate launcher layer surface opening. Disabling shows it immediately.", + "description[zh_CN]": "控制启动器图层打开动画;关闭时立即显示。", + "permissions": "readwrite", + "visibility": "public" + }, + "launchpadCloseFullscreen": { + "value": true, + "serial": 0, + "flags": [], + "name": "Launcher close animation", + "name[zh_CN]": "启动器关闭动画", + "description": "Animate launcher layer surface closing. Disabling hides it immediately.", + "description[zh_CN]": "控制启动器图层关闭动画;关闭时立即隐藏。", + "permissions": "readwrite", + "visibility": "public" + }, + "layerShellOpen": { + "value": true, + "serial": 0, + "flags": [], + "name": "Layer shell open animation", + "name[zh_CN]": "图层窗口打开动画", + "description": "Animate anchored layer shell surfaces opening. Disabling shows them immediately.", + "description[zh_CN]": "控制贴边图层窗口打开动画;关闭时立即显示。", + "permissions": "readwrite", + "visibility": "public" + }, + "layerShellClose": { + "value": true, + "serial": 0, + "flags": [], + "name": "Layer shell close animation", + "name[zh_CN]": "图层窗口关闭动画", + "description": "Animate anchored layer shell surfaces closing. Disabling hides them immediately.", + "description[zh_CN]": "控制贴边图层窗口关闭动画;关闭时立即隐藏。", + "permissions": "readwrite", + "visibility": "public" + }, + "maximize": { + "value": true, + "serial": 0, + "flags": [], + "name": "Maximize animation", + "name[zh_CN]": "最大化动画", + "description": "Animate the geometry change when maximizing. Disabling applies the maximized geometry immediately.", + "description[zh_CN]": "控制最大化几何变化动画;关闭时立即应用最大化几何。", + "permissions": "readwrite", + "visibility": "public" + }, + "fullscreen": { + "value": true, + "serial": 0, + "flags": [], + "name": "Fullscreen animation", + "name[zh_CN]": "全屏动画", + "description": "Animate the geometry change when entering fullscreen. Disabling applies the fullscreen geometry immediately.", + "description[zh_CN]": "控制进入全屏的几何变化动画;关闭时立即应用全屏几何。", + "permissions": "readwrite", + "visibility": "public" + }, + "restoreWindow": { + "value": true, + "serial": 0, + "flags": [], + "name": "Restore window animation", + "name[zh_CN]": "窗口还原动画", + "description": "Animate the geometry change when restoring from maximized or fullscreen. Disabling applies the restored geometry immediately.", + "description[zh_CN]": "控制从最大化或全屏还原的几何变化动画;关闭时立即应用还原几何。", + "permissions": "readwrite", + "visibility": "public" + }, + "minimize": { + "value": true, + "serial": 0, + "flags": [], + "name": "Minimize animation", + "name[zh_CN]": "最小化动画", + "description": "Animate minimizing a window. Disabling minimizes immediately without the shrink transition.", + "description[zh_CN]": "控制窗口最小化动画;关闭时立即最小化,不播放缩小过渡。", + "permissions": "readwrite", + "visibility": "public" + }, + "restoreMinimized": { + "value": true, + "serial": 0, + "flags": [], + "name": "Restore minimized animation", + "name[zh_CN]": "最小化恢复动画", + "description": "Animate restoring a minimized window. Disabling restores immediately.", + "description[zh_CN]": "控制最小化窗口的恢复动画;关闭时立即恢复。", + "permissions": "readwrite", + "visibility": "public" + }, + "showDesktop": { + "value": true, + "serial": 0, + "flags": [], + "name": "Show desktop animation", + "name[zh_CN]": "显示桌面动画", + "description": "Animate hiding windows when showing the desktop. Disabling hides them immediately.", + "description[zh_CN]": "控制显示桌面时隐藏窗口的动画;关闭时立即隐藏。", + "permissions": "readwrite", + "visibility": "public" + }, + "restoreShowDesktop": { + "value": true, + "serial": 0, + "flags": [], + "name": "Restore from desktop animation", + "name[zh_CN]": "退出显示桌面动画", + "description": "Animate restoring windows when leaving show-desktop. Disabling restores them immediately.", + "description[zh_CN]": "控制退出显示桌面时恢复窗口的动画;关闭时立即恢复。", + "permissions": "readwrite", + "visibility": "public" + }, + "launchpadCover": { + "value": true, + "serial": 0, + "flags": [], + "name": "Launcher cover animation", + "name[zh_CN]": "启动器覆盖动画", + "description": "Animate the launcher cover wallpaper zoom and fade. Disabling applies the final state immediately.", + "description[zh_CN]": "控制启动器覆盖层的壁纸缩放与淡入淡出;关闭时立即应用最终状态。", + "permissions": "readwrite", + "visibility": "public" + }, + "wallpaperScale": { + "value": true, + "serial": 0, + "flags": [], + "name": "Wallpaper scale animation", + "name[zh_CN]": "壁纸缩放动画", + "description": "Animate wallpaper scaling on launcher and lock screen transitions. Disabling applies the target scale immediately.", + "description[zh_CN]": "控制启动器和锁屏切换时的壁纸缩放动画;关闭时立即应用目标缩放。", + "permissions": "readwrite", + "visibility": "public" + }, + "workspaceSwitch": { + "value": true, + "serial": 0, + "flags": [], + "name": "Workspace switch animation", + "name[zh_CN]": "工作区切换动画", + "description": "Animate sliding between workspaces. Disabling switches workspaces immediately.", + "description[zh_CN]": "控制工作区之间的滑动切换动画;关闭时立即切换。", + "permissions": "readwrite", + "visibility": "public" + }, + "workspaceVisibility": { + "value": true, + "serial": 0, + "flags": [], + "name": "Workspace visibility animation", + "name[zh_CN]": "工作区显隐动画", + "description": "Animate the workspace scale and opacity on lock screen entry and exit. Disabling applies the final scale and opacity immediately.", + "description[zh_CN]": "控制锁屏进入和退出时工作区的缩放与透明度动画;关闭时立即应用最终缩放和透明度。", + "permissions": "readwrite", + "visibility": "public" + }, + "workspaceBounce": { + "value": true, + "serial": 0, + "flags": [], + "name": "Workspace edge bounce animation", + "name[zh_CN]": "工作区边界回弹动画", + "description": "Animate the bounce when switching past the first or last workspace. Disabling skips the bounce.", + "description[zh_CN]": "控制切换到首个或最后一个工作区时的边界回弹动画;关闭时不播放回弹。", + "permissions": "readwrite", + "visibility": "public" + }, + "taskSwitcher": { + "value": true, + "serial": 0, + "flags": [], + "name": "Task switcher", + "name[zh_CN]": "任务切换", + "description": "Control mask, panel, thumbnails, highlight and window restoration transitions for the task switcher.", + "description[zh_CN]": "统一控制任务切换的遮罩、面板、缩略图、高亮和窗口恢复过渡。", + "permissions": "readwrite", + "visibility": "public" + }, + "multitaskview": { + "value": true, + "serial": 0, + "flags": [], + "name": "Multitask view", + "name[zh_CN]": "多任务视图", + "description": "Control entry, exit, window layout, empty hint and workspace thumbnail reordering transitions. Gesture following is preserved.", + "description[zh_CN]": "统一控制多任务视图进入、退出、窗口布局、空窗口提示和工作区缩略图重排过渡,保留手势跟随。", + "permissions": "readwrite", + "visibility": "public" + }, + "outputRotation": { + "value": true, + "serial": 0, + "flags": [], + "name": "Output rotation animation", + "name[zh_CN]": "主输出旋转动画", + "description": "Animate rotating the primary output. Disabling applies the rotation and transform immediately.", + "description[zh_CN]": "控制主输出旋转动画;关闭时立即应用旋转和实际 transform。", + "permissions": "readwrite", + "visibility": "public" + }, + "mirrorOutputRotation": { + "value": true, + "serial": 0, + "flags": [], + "name": "Mirror output rotation animation", + "name[zh_CN]": "镜像输出旋转动画", + "description": "Animate rotating a mirror output. Disabling applies the rotation and transform immediately.", + "description[zh_CN]": "控制镜像输出旋转动画;关闭时立即应用旋转和实际 transform。", + "permissions": "readwrite", + "visibility": "public" + }, + "wallpaperCrossFade": { + "value": true, + "serial": 0, + "flags": [], + "name": "Wallpaper cross fade animation", + "name[zh_CN]": "壁纸交叉渐变动画", + "description": "Cross fade between wallpapers. Disabling switches as soon as the new wallpaper is ready.", + "description[zh_CN]": "控制壁纸之间的交叉渐变;关闭时在新壁纸就绪后立即切换。", + "permissions": "readwrite", + "visibility": "public" + }, + "dockPreview": { + "value": true, + "serial": 0, + "flags": [], + "name": "Dock preview", + "name[zh_CN]": "Dock 预览", + "description": "Animate dock preview. Disabled transitions apply their final state directly.", + "description[zh_CN]": "控制Dock 预览动画;禁用时直接应用目标状态。", + "permissions": "readwrite", + "visibility": "public" + }, + "captureToolbar": { + "value": true, + "serial": 0, + "flags": [], + "name": "Capture toolbar", + "name[zh_CN]": "截图工具条", + "description": "Animate capture toolbar. Disabled transitions apply their final state directly.", + "description[zh_CN]": "控制截图工具条动画;禁用时直接应用目标状态。", + "permissions": "readwrite", + "visibility": "public" + }, + "edgeTilePreview": { + "value": true, + "serial": 0, + "flags": [], + "name": "Edge tile preview", + "name[zh_CN]": "边缘平铺预览", + "description": "Animate edge tile preview. Disabled transitions apply their final state directly.", + "description[zh_CN]": "控制边缘平铺预览动画;禁用时直接应用目标状态。", + "permissions": "readwrite", + "visibility": "public" + } + } +} diff --git a/misc/dconfig/org.deepin.dde.treeland.app.json b/misc/dconfig/org.deepin.dde.treeland.app.json new file mode 100644 index 0000000000..85ed0c8dca --- /dev/null +++ b/misc/dconfig/org.deepin.dde.treeland.app.json @@ -0,0 +1,83 @@ +{ + "magic": "dsg.config.meta", + "version": "1.0", + "contents": { + "enablePrelaunchSplash": { + "value": true, + "serial": 0, + "flags": [], + "name": "Enable Prelaunch Splash", + "name[zh_CN]": "启用预启动闪屏", + "description": "Whether to show prelaunch splash for this app", + "description[zh_CN]": "是否为此应用显示预启动闪屏", + "permissions": "readwrite", + "visibility": "public" + }, + "lastWindowWidth": { + "value": 800, + "serial": 0, + "flags": [], + "name": "Last Window Width", + "name[zh_CN]": "上次关闭时的窗口宽度", + "description": "Window width saved when the window was last closed", + "description[zh_CN]": "记录窗口上次关闭时的宽度", + "permissions": "readwrite", + "visibility": "public" + }, + "lastWindowHeight": { + "value": 600, + "serial": 0, + "flags": [], + "name": "Last Window Height", + "name[zh_CN]": "上次关闭时的窗口高度", + "description": "Window height saved when the window was last closed", + "description[zh_CN]": "记录窗口上次关闭时的高度", + "permissions": "readwrite", + "visibility": "public" + }, + "splashThemeType": { + "value": 0, + "serial": 0, + "flags": [], + "name": "Splash Theme Type", + "name[zh_CN]": "闪屏主题类型", + "description": "Splash theme preference: 0 follow system, 1 light, 2 dark", + "description[zh_CN]": "闪屏主题偏好:0 跟随系统,1 亮色,2 暗色", + "permissions": "readwrite", + "visibility": "public" + }, + "splashDarkPalette": { + "value": "#181818", + "serial": 0, + "flags": [], + "name": "Splash Dark Palette", + "name[zh_CN]": "闪屏暗色配色", + "description": "Background color used when splash theme is dark", + "description[zh_CN]": "闪屏使用暗色主题时的背景色", + "permissions": "readwrite", + "visibility": "public" + }, + "splashLightPalette": { + "value": "#FFFFFF", + "serial": 0, + "flags": [], + "name": "Splash Light Palette", + "name[zh_CN]": "闪屏亮色配色", + "description": "Background color used when splash theme is light", + "description[zh_CN]": "闪屏使用亮色主题时的背景色", + "permissions": "readwrite", + "visibility": "public" + }, + "prelaunchSplashMismatchCount": { + "value": 0, + "serial": 0, + "flags": [], + "name": "Prelaunch Splash Mismatch Count", + "name[zh_CN]": "预启动闪屏不匹配次数", + "description": "Consecutive splash match failure count for this app, persisted across restarts; reset to 0 on a successful match, and also reset to 0 when the count reaches the threshold and splash is auto-disabled. 0 means no failure recorded.", + "description[zh_CN]": "该应用连续闪屏匹配失败次数,持久化保存(重启后保留);匹配成功时重置为0,达到阈值自动禁用闪屏时同样重置为0。0 表示无失败记录。", + "permissions": "readwrite", + "visibility": "private" + } + } +} diff --git a/misc/dconfig/org.deepin.dde.treeland.json b/misc/dconfig/org.deepin.dde.treeland.json new file mode 100644 index 0000000000..fe1f420e98 --- /dev/null +++ b/misc/dconfig/org.deepin.dde.treeland.json @@ -0,0 +1,127 @@ +{ + "magic": "dsg.config.meta", + "version": "1.0", + "contents": { + "quickSwitchTimeout": { + "value": 120, + "serial": 0, + "flags": [], + "name": "Quick Switch Timeout (ms)", + "name[zh_CN]": "快速切换超时(毫秒)", + "description": "Timeout to distinguish a quick Alt+Tab toggle from the full task switcher", + "description[zh_CN]": "区分快速 Alt+Tab 切换与完整任务切换器的超时时长", + "permissions": "readwrite", + "visibility": "public" + }, + "forceSoftwareCursor": { + "value": false, + "serial": 0, + "flags": [], + "name": "Force Software Cursor", + "name[zh_CN]": "强制软光标渲染", + "description": "Force software cursor rendering", + "description[zh_CN]": "强制使用软光标进行渲染", + "permissions": "readwrite", + "visibility": "public" + }, + "enablePrelaunchSplash": { + "value": true, + "serial": 0, + "flags": [], + "name": "Enable Prelaunch Splash", + "name[zh_CN]": "启用预启动闪屏", + "description": "Enable showing prelaunch splash screens during application startup", + "description[zh_CN]": "启用应用程序启动期间显示预启动闪屏服务", + "permissions": "readwrite", + "visibility": "public" + }, + "prelaunchSplashTimeoutMs": { + "value": 5000, + "serial": 0, + "flags": [], + "name": "Prelaunch Splash Timeout (ms)", + "name[zh_CN]": "预启动闪屏超时(毫秒)", + "description": "Timeout before destroying unmatched prelaunch splash wrappers", + "description[zh_CN]": "在未匹配到窗口时销毁预启动闪屏的超时时长", + "permissions": "readwrite", + "visibility": "public" + }, + "remoteDebug": { + "value": false, + "serial": 0, + "flags": [], + "name": "Allow Debugging", + "name[zh_CN]": "允许调试", + "description": "Allow debugging tools to connect. Off by default: debugging hands out window contents and input injection, which a session-level compositor must not offer unasked. While this is on, treeland publishes its debug socket and serves the window tree remote source on demand, collecting everything per call (the only session-scoped resource, input-event capture, is armed only while a client polls for events). Release builds only let root connect. Turn it on with `treeland-debug debug on`. A debug build (CMAKE_BUILD_TYPE=Debug) always publishes its `-dev` socket, ignores this key, and allows the compositor's UID to connect without polkit (root retains privileged access).", + "description[zh_CN]": "允许调试工具连接。默认关闭:调试会交出窗口内容与输入注入能力,会话级运行的合成器不应默认提供。开启时 treeland 会发布调试 socket,窗口树远程源按需提供服务、数据在每次调用时现场采集(唯一的会话级资源是输入事件捕获,只在客户端轮询事件时才挂上);Release 构建仅允许 root 连接。用 `treeland-debug debug on` 打开。Debug 构建(CMAKE_BUILD_TYPE=Debug)始终发布自己的 `-dev` socket、忽略本开关,并且允许合成器所属 UID 无需 polkit 连接(root 仍具备特权访问能力)。", + "permissions": "readwrite", + "visibility": "private" + }, + "showOtherUserOption": { + "value": false, + "serial": 0, + "flags": [], + "name": "Show Other User Option", + "name[zh_CN]": "显示其他用户选项", + "description": "Show the 'Other...' entry in the login user list to allow logging in as an unlisted (e.g. LDAP/NSS) user", + "description[zh_CN]": "在登录用户列表中显示 Other... 选项,允许以未列出的用户(如 LDAP/NSS 用户)登录", + "permissions": "readwrite", + "visibility": "public" + }, + "primaryOutputId": { + "value": "", + "serial": 0, + "flags": [], + "name": "Primary Output ID", + "name[zh_CN]": "主屏幕 ID", + "description": "Output id recorded as the primary output. Empty means no primary output has been saved.", + "description[zh_CN]": "记录为主屏幕的输出 ID。空字符串表示未保存主屏幕。", + "permissions": "readwrite", + "visibility": "public" + }, + "keyboardNumLock": { + "value": true, + "serial": 0, + "flags": [], + "name": "Keyboard Num Lock", + "name[zh_CN]": "键盘数字锁定", + "description": "Whether the Num Lock state is enabled by default on keyboards that have a numeric keypad. When enabled, the numeric keypad inputs numbers.", + "description[zh_CN]": "是否默认在带有数字小键盘的键盘上启用数字锁定。启用时数字小键盘输入数字。", + "permissions": "readwrite", + "visibility": "public" + }, + "singleOutputId": { + "value": "", + "serial": 0, + "flags": [], + "name": "Single Output ID", + "name[zh_CN]": "单屏显示输出 ID", + "description": "Output ID used for single-output display. Empty means multiple outputs may be enabled. This selection is independent of copy and extension mode.", + "description[zh_CN]": "单屏显示时使用的输出 ID。空字符串表示可启用多个输出。此选择与复制和扩展模式相互独立。", + "permissions": "readwrite", + "visibility": "public" + }, + "outputGroups": { + "value": "", + "serial": 0, + "flags": [], + "name": "Output Groups", + "name[zh_CN]": "输出分组列表", + "description": "Semicolon-separated list of persisted output group names. Group membership is stored on each output's own configuration.", + "description[zh_CN]": "持久化的输出分组名称列表,以分号分隔。分组成员信息存放在每个输出自己的配置中。", + "permissions": "readwrite", + "visibility": "public" + }, + "prelaunchSplashMaxMismatchCount": { + "value": 4, + "serial": 0, + "flags": [], + "name": "Prelaunch Splash Max Mismatch Count", + "name[zh_CN]": "预启动闪屏最大不匹配次数", + "description": "Maximum consecutive splash match failures before disabling splash for an app. 0 means never auto-disable.", + "description[zh_CN]": "连续闪屏匹配失败达到此次数后禁用该应用的闪屏功能。0 表示永不自动禁用。", + "permissions": "readwrite", + "visibility": "public" + } + } +} diff --git a/misc/dconfig/org.deepin.dde.treeland.output.json b/misc/dconfig/org.deepin.dde.treeland.output.json new file mode 100644 index 0000000000..73755c84a9 --- /dev/null +++ b/misc/dconfig/org.deepin.dde.treeland.output.json @@ -0,0 +1,160 @@ +{ + "magic": "dsg.config.meta", + "version": "1.0", + "contents": { + "brightness": { + "value": 1.0e0, + "serial": 0, + "flags": [], + "name": "Brightness", + "name[zh_CN]": "亮度", + "description": "Brightness of this Output (in range 0.0 - 1.0)", + "description[zh_CN]": "当前输出的亮度", + "permissions": "readwrite", + "visibility": "public" + }, + "colorTemperature": { + "value": 6600, + "serial": 0, + "flags": [], + "name": "Color Temperature", + "name[zh_CN]": "色温", + "description": "Color temperature of this Output (in Kelvin)", + "description[zh_CN]": "当前输出的色温", + "permissions": "readwrite", + "visibility": "public" + }, + "x": { + "value": 0, + "serial": 0, + "flags": [], + "name": "X Position", + "name[zh_CN]": "X 坐标", + "description": "Last applied x position of this output in the global compositor space.", + "description[zh_CN]": "当前输出上次应用到全局合成器空间的 X 坐标。", + "permissions": "readwrite", + "visibility": "public" + }, + "y": { + "value": 0, + "serial": 0, + "flags": [], + "name": "Y Position", + "name[zh_CN]": "Y 坐标", + "description": "Last applied y position of this output in the global compositor space.", + "description[zh_CN]": "当前输出上次应用到全局合成器空间的 Y 坐标。", + "permissions": "readwrite", + "visibility": "public" + }, + "width": { + "value": 0, + "serial": 0, + "flags": [], + "name": "Width", + "name[zh_CN]": "宽度", + "description": "Last committed output mode width in pixels. 0 means no output mode has been saved.", + "description[zh_CN]": "上次提交的输出模式宽度,单位为像素。0 表示未保存输出模式。", + "permissions": "readwrite", + "visibility": "public" + }, + "height": { + "value": 0, + "serial": 0, + "flags": [], + "name": "Height", + "name[zh_CN]": "高度", + "description": "Last committed output mode height in pixels. 0 means no output mode has been saved.", + "description[zh_CN]": "上次提交的输出模式高度,单位为像素。0 表示未保存输出模式。", + "permissions": "readwrite", + "visibility": "public" + }, + "refresh": { + "value": 0, + "serial": 0, + "flags": [], + "name": "Refresh Rate", + "name[zh_CN]": "刷新率", + "description": "Last committed output refresh rate in mHz. 0 means no output mode has been saved.", + "description[zh_CN]": "上次提交的输出刷新率,单位为 mHz。0 表示未保存输出模式。", + "permissions": "readwrite", + "visibility": "public" + }, + "transform": { + "value": 0, + "serial": 0, + "flags": [], + "name": "Transform", + "name[zh_CN]": "变换", + "description": "Last committed wl_output_transform enum value for this output.", + "description[zh_CN]": "当前输出上次提交的 wl_output_transform 枚举值。", + "permissions": "readwrite", + "visibility": "public" + }, + "scale": { + "value": 1.0, + "serial": 0, + "flags": [], + "name": "Scale", + "name[zh_CN]": "缩放", + "description": "Last committed output scale. Values must be greater than 0. The default value means no output mode has been saved.", + "description[zh_CN]": "当前输出上次提交的缩放值,必须大于 0。默认值表示未保存输出模式。", + "permissions": "readwrite", + "visibility": "public" + }, + "adaptiveSyncEnabled": { + "value": false, + "serial": 0, + "flags": [], + "name": "Adaptive Sync Enabled", + "name[zh_CN]": "启用自适应同步", + "description": "Whether adaptive sync was enabled in the last committed output state.", + "description[zh_CN]": "当前输出上次提交的状态是否启用了自适应同步。", + "permissions": "readwrite", + "visibility": "public" + }, + "uuid": { + "value": "", + "serial": 0, + "flags": [], + "name": "Output UUID", + "name[zh_CN]": "显示输出设备 UUID", + "description": "Persistent opaque uuid assigned to this display output device. It is generated on first insert and reused across sessions and reconnections. Empty means not yet assigned.", + "description[zh_CN]": "分配给此显示输出设备的持久不透明 uuid。首次插入时生成,并在跨会话和重连时复用。空值表示尚未分配。", + "permissions": "readwrite", + "visibility": "private" + }, + "groupName": { + "value": "", + "serial": 0, + "flags": [], + "name": "Output Group Name", + "name[zh_CN]": "输出分组名称", + "description": "Name of the output group (copy mode) this output belongs to. Empty means the output belongs to no group.", + "description[zh_CN]": "此输出所属的输出分组(拷贝模式)名称。空字符串表示不属于任何分组。", + "permissions": "readwrite", + "visibility": "private" + }, + "lastSetSourceTime": { + "value": 0, + "serial": 0, + "flags": [], + "name": "Last Set Source Time", + "name[zh_CN]": "上次设为源输出的时间", + "description": "Wall-clock time in milliseconds since the epoch when this output was last explicitly designated as its group's source. 0 means it was never designated; the current source is resolved at runtime, not stored.", + "description[zh_CN]": "此输出最后一次被显式指定为分组源输出的墙钟时间(自纪元起的毫秒数)。0 表示从未被指定;当前源输出在运行时决议,不落盘。", + "permissions": "readwrite", + "visibility": "private" + }, + "joinTime": { + "value": 0, + "serial": 0, + "flags": [], + "name": "Group Join Time", + "name[zh_CN]": "加入分组时间", + "description": "Wall-clock time in milliseconds since the epoch when this output joined its current group. Updated only when joining a group; the mirror order of a group is the join order of its members. 0 means the output belongs to no group.", + "description[zh_CN]": "此输出加入当前分组的墙钟时间(自纪元起的毫秒数)。仅在加入分组时更新;分组的镜像顺序即成员加入顺序。0 表示不属于任何分组。", + "permissions": "readwrite", + "visibility": "private" + } + } +} diff --git a/misc/dconfig/org.deepin.dde.treeland.user.json b/misc/dconfig/org.deepin.dde.treeland.user.json new file mode 100644 index 0000000000..dc908e494e --- /dev/null +++ b/misc/dconfig/org.deepin.dde.treeland.user.json @@ -0,0 +1,622 @@ +{ + "magic": "dsg.config.meta", + "version": "1.0", + "contents": { + "showOnLock": { + "value": false, + "serial": 0, + "flags": [], + "name": "Show on lock screen", + "name[zh_CN]": "显示在锁屏之上", + "description": "Allow show context on lock screen", + "description[zh_CN]": "允许在锁屏界面上显示内容", + "permissions": "readwrite", + "visibility": "public" + }, + "lostScreen": { + "value": "MoveToPrimary", + "serial": 0, + "flags": [], + "name": "Behaivor when lost screen", + "name[zh_CN]": "丢失屏幕的行为", + "description": "Behaivor when lost screen, allow value: MoveToPrimary、Minimize", + "description[zh_CN]": "丢失屏幕的行为,可选值为:MoveToPrimary、Minimize", + "permissions": "readwrite", + "visibility": "public" + }, + "font": { + "value": "Source Han Sans SC", + "serial": 0, + "flags": [], + "name": "Font", + "name[zh_CN]": "字体", + "description": "Font Family", + "description[zh_CN]": "字体", + "permissions": "readwrite", + "visibility": "public" + }, + "monoFont": { + "value": "Noto Mono", + "serial": 0, + "flags": [], + "name": "Mono Font", + "name[zh_CN]": "等宽字体", + "description": "Mono Font Family", + "description[zh_CN]": "等宽字体", + "permissions": "readwrite", + "visibility": "public" + }, + "fontSize": { + "value": 105, + "serial": 0, + "flags": [], + "name": "Font Size", + "name[zh_CN]": "字体大小", + "description": "Font Size", + "description[zh_CN]": "字体大小", + "permissions": "readwrite", + "visibility": "public" + }, + "windowRadius": { + "value": 12, + "serial": 0, + "flags": [], + "name": "Round Corner Radius", + "name[zh_CN]": "窗口圆角大小", + "description": "Window Corner Round Radius", + "description[zh_CN]": "设置窗口圆角大小", + "permissions": "readwrite", + "visibility": "public" + }, + "preferDark": { + "value": false, + "serial": 0, + "flags": [], + "name": "Prefer Dark", + "name[zh_CN]": "倾向暗色", + "description": "Color scheme is prefer dark", + "description[zh_CN]": "颜色方案是否倾向暗色", + "permissions": "readwrite", + "visibility": "public" + }, + "iconThemeName": { + "value": "nirvana", + "serial": 0, + "flags": [], + "name": "Icon Theme Name", + "name[zh_CN]": "图标主题名称", + "description": "Icon Theme Name", + "description[zh_CN]": "图标主题名称", + "permissions": "readwrite", + "visibility": "public" + }, + "cursorThemeName": { + "value": "bloom", + "serial": 0, + "flags": [], + "name": "Cursor Theme Name", + "name[zh_CN]": "光标主题名称", + "description": "Cursor Theme Name", + "description[zh_CN]": "光标主题名称", + "permissions": "readwrite", + "visibility": "public" + }, + "cursorSize": { + "value": 24, + "serial": 0, + "flags": [], + "name": "Cursor Size", + "name[zh_CN]": "光标大小", + "description": "Cursor Size", + "description[zh_CN]": "光标大小", + "permissions": "readwrite", + "visibility": "public" + }, + "cursorBlink": { + "value": true, + "serial": 0, + "flags": [], + "name": "Cursor Blink", + "name[zh_CN]": "光标闪烁", + "description": "Whether the cursor should blink", + "description[zh_CN]": "光标是否应闪烁", + "permissions": "readwrite", + "visibility": "public" + }, + "cursorBlinkTime": { + "value": 1200, + "serial": 0, + "flags": [], + "name": "Cursor Blink Time", + "name[zh_CN]": "光标闪烁时间", + "description": "Length of the cursor blink cycle, in milleseconds", + "description[zh_CN]": "光标闪烁周期的长度,以千秒为单位", + "permissions": "readwrite", + "visibility": "public" + }, + "doubleClickTime": { + "value": 250, + "serial": 0, + "flags": [], + "name": "Double Click Time", + "name[zh_CN]": "双击时间", + "description": "Maximum time allowed between two clicks for them to be considered a double click (in milliseconds)", + "description[zh_CN]": "两次单击之间允许被视为双击的最长时间(以毫秒为单位)", + "permissions": "readwrite", + "visibility": "public" + }, + "doubleClickDistance": { + "value": 5, + "serial": 0, + "flags": [], + "name": "Double Click Distance", + "name[zh_CN]": "双击距离", + "description": "Maximum distance allowed between two clicks for them to be considered a double click (in pixels)", + "description[zh_CN]": "两次单击之间允许被视为双击的最大距离(以像素为单位)", + "permissions": "readwrite", + "visibility": "public" + }, + "dndDragThreshold": { + "value": 8, + "serial": 0, + "flags": [], + "name": "Dnd Drag Threshold", + "name[zh_CN]": "拖动阈值", + "description": "Number of pixels the cursor can move before dragging", + "description[zh_CN]": "拖动之前光标可以移动的像素数", + "permissions": "readwrite", + "visibility": "public" + }, + "maxWorkspace": { + "value": 6, + "serial": 0, + "flags": [], + "name": "Max Workspace Count", + "name[zh_CN]": "工作区最大数量", + "description": "Maximum number of workspaces", + "description[zh_CN]": "工作区最大数量", + "permissions": "readwrite", + "visibility": "private" + }, + "numWorkspace": { + "value": 2, + "serial": 0, + "flags": [], + "name": "Number of workspaces", + "name[zh_CN]": "工作区数量", + "description": "Current number of workspaces", + "description[zh_CN]": "当前工作区数量", + "permissions": "readwrite", + "visibility": "private" + }, + "currentWorkspace": { + "value": 0, + "serial": 0, + "flags": [], + "name": "Current workspace", + "name[zh_CN]": "当前工作区", + "description": "Current index of workspace", + "description[zh_CN]": "当前工作区索引", + "permissions": "readwrite", + "visibility": "private" + }, + "activeColor": { + "value": "#1F6EE7", + "serial": 0, + "flags": [], + "name": "Global Window Active Color", + "name[zh_CN]": "全局窗口活动色", + "description": "Set window active color", + "description[zh_CN]": "设置窗口活动色", + "permissions": "readwrite", + "visibility": "public" + }, + "windowOpacity": { + "value": 40, + "serial": 0, + "flags": [], + "name": "Global Window Opacity", + "name[zh_CN]": "全局窗口不透明度", + "description": "Set all window opacity", + "description[zh_CN]": "设置所有窗口的不透明度", + "permissions": "readwrite", + "visibility": "public" + }, + "windowColorScheme": { + "value": 0, + "serial": 1, + "flags": [], + "name": "Global Window Color Scheme", + "name[zh_CN]": "全局窗口配色", + "description": "Color scheme hint: 0 light, 1 dark", + "description[zh_CN]": "配色偏好:0 亮色,1 暗色", + "permissions": "readwrite", + "visibility": "public" + }, + "windowTitlebarHeight": { + "value": 40, + "serial": 0, + "flags": [], + "name": "Global Window titlebar height", + "name[zh_CN]": "全局标题栏高度", + "description": "Set all window default titlebar height", + "description[zh_CN]": "设置所有窗口默认的标题栏高度", + "permissions": "readwrite", + "visibility": "public" + }, + "defaultBackground": { + "value": "/usr/share/backgrounds/default_background.jpg", + "serial": 0, + "flags": [], + "name": "Default background", + "name[zh_CN]": "默认壁纸", + "description": "Set the default displayed wallpaper, when no wallpaper is set", + "description[zh_CN]": "当没有设置壁纸时,设置默认显示的壁纸", + "permissions": "readwrite", + "visibility": "public" + }, + "workspaceThumbHeight": { + "value": 144, + "serial": 0, + "flags": [], + "name": "Workspace thumbnail height", + "name[zh_CN]": "工作区缩略图高度", + "description": "Workspace thumbnail height", + "description[zh_CN]": "工作区缩略图高度", + "permissions": "readonly", + "visibility": "private" + }, + "workspaceThumbMargin": { + "value": 20, + "serial": 0, + "flags": [], + "name": "Workspace thumbnail margin", + "name[zh_CN]": "工作区缩略图边距", + "description": "Workspace thumbnail margin", + "description[zh_CN]": "工作区缩略图边距", + "permissions": "readonly", + "visibility": "private" + }, + "workspaceThumbCornerRadius": { + "value": 8, + "serial": 0, + "flags": [], + "name": "Workspace thumbnail corner radius", + "name[zh_CN]": "工作区缩略图圆角弧度", + "description": "Workspace thumbnail corner radius", + "description[zh_CN]": "工作区缩略图圆角弧度", + "permissions": "readonly", + "visibility": "private" + }, + "highlightBorderWidth": { + "value": 4, + "serial": 0, + "flags": [], + "name": "Highlight border width", + "name[zh_CN]": "高亮边框宽度", + "description": "Highlight border width", + "description[zh_CN]": "高亮边框宽度", + "permissions": "readonly", + "visibility": "private" + }, + "minMultitaskviewSurfaceHeight": { + "value": 232, + "serial": 0, + "flags": [], + "name": "Multitask view surface minimal height", + "name[zh_CN]": "多任务视图表面最小高度", + "description": "Multitask view surface minimal height", + "description[zh_CN]": "多任务视图表面最小高度", + "permissions": "readonly", + "visibility": "private" + }, + "titleBoxCornerRadius": { + "value": 8, + "serial": 0, + "flags": [], + "name": "Title box corner radius", + "name[zh_CN]": "标题框圆角弧度", + "description": "Title box corner radius", + "description[zh_CN]": "标题框圆角弧度", + "permissions": "readonly", + "visibility": "private" + }, + "normalWindowHeight": { + "value": 720, + "serial": 0, + "flags": [], + "name": "Normal window height", + "name[zh_CN]": "正常窗口高度", + "description": "Normal window height", + "description[zh_CN]": "正常窗口高度", + "permissions": "readonly", + "visibility": "private" + }, + "windowHeightStep": { + "value": 15, + "serial": 0, + "flags": [], + "name": "Window height step", + "name[zh_CN]": "窗口高度梯度", + "description": "Window height step", + "description[zh_CN]": "窗口高度梯度", + "permissions": "readonly", + "visibility": "private" + }, + "multitaskviewPaddingOpacity": { + "value": 0.1, + "serial": 0, + "flags": [], + "name": "Multitaskview padding opacity", + "name[zh_CN]": "多任务视图内边距不透明度", + "description": "Multitask view padding opacity", + "description[zh_CN]": "多任务视图内边距不透明度", + "permissions": "readonly", + "visibility": "private" + }, + "multitaskviewAnimationDuration": { + "value": 300, + "serial": 0, + "flags": [], + "name": "Multitaskview animation duration", + "name[zh_CN]": "多任务视图动画时长", + "description": "Multitaskview animation duration", + "description[zh_CN]": "多任务视图动画时长", + "permissions": "readonly", + "visibility": "private" + }, + "multitaskviewEasingCurveType": { + "value": 22, + "serial": 0, + "flags": [], + "name": "Multitaskview easing curve type", + "name[zh_CN]": "多任务视图缓动曲线类型", + "description": "Multitaskview easing curve type, enumerate value of QEasingCurve::Type", + "description[zh_CN]": "多任务视图缓动曲线类型,其值为QEasingCurve::Type类型的枚举值", + "permissions": "readonly", + "visibility": "private" + }, + "multitaskviewTopContentMargin": { + "value": 40, + "serial": 0, + "flags": [], + "name": "Multitaskview top content margin", + "name[zh_CN]": "多任务视图内容顶边距", + "description": "Multitaskview top content margin", + "description[zh_CN]": "多任务视图内容顶边距", + "permissions": "readonly", + "visibility": "private" + }, + "multitaskviewBottomContentMargin": { + "value": 60, + "serial": 0, + "flags": [], + "name": "Multitaskview bottom content margin", + "name[zh_CN]": "多任务视图内容底边距", + "description": "Multitaskview bottom content margin", + "description[zh_CN]": "多任务视图内容底边距", + "permissions": "readonly", + "visibility": "private" + }, + "multitaskviewHorizontalMargin": { + "value": 20, + "serial": 0, + "flags": [], + "name": "Multitaskview horizontal margin", + "name[zh_CN]": "多任务视图横向边距", + "description": "Multitaskview horizontal margin", + "description[zh_CN]": "多任务视图横向边距", + "permissions": "readonly", + "visibility": "private" + }, + "multitaskviewCellPadding": { + "value": 12, + "serial": 0, + "flags": [], + "name": "Multitaskview cell padding", + "name[zh_CN]": "多任务视图单元格间距", + "description": "Multitaskview cell padding", + "description[zh_CN]": "多任务视图单元格间距", + "permissions": "readonly", + "visibility": "private" + }, + "multitaskviewLoadFactor": { + "value": 0.6, + "serial": 0, + "flags": [], + "name": "Multitaskview load factor", + "name[zh_CN]": "多任务视图加载因子", + "description": "Multitaskview load factor", + "description[zh_CN]": "多任务视图加载因子", + "permissions": "readonly", + "visibility": "private" + }, + "wallpaperConfig": { + "value": "", + "serial": 0, + "flags": [], + "name": "Wallpaper Config", + "name[zh_CN]": "壁纸配置", + "description": "A configuration to manage wallpapers used by the system, including desktop and lockscreen wallpapers for each screen and workspace.", + "description[zh_CN]": "用于管理系统当前使用的壁纸配置,包括每个屏幕和工作区的桌面壁纸和锁屏壁纸。", + "permissions": "readwrite", + "visibility": "public" + }, + "glassEnabled": { + "value": false, + "serial": 0, + "flags": [], + "name": "Glass Effect Enabled", + "name[zh_CN]": "液态玻璃效果开关", + "description": "Use the Liquid Glass effect for backdrop blur regions instead of the plain blur. When disabled, the traditional Gaussian blur is used with no side effects.", + "description[zh_CN]": "是否在背景模糊区域使用液态玻璃效果替代普通模糊。关闭时使用传统高斯模糊,无额外副作用。", + "permissions": "readwrite", + "visibility": "public" + }, + "blurStrength": { + "value": 60, + "serial": 0, + "flags": [], + "name": "Blur Strength", + "name[zh_CN]": "模糊强度", + "description": "Maximum blur strength (in pixels) applied to the backdrop blur regions. When set to 0, blur is completely disabled. Range: 0-128.", + "description[zh_CN]": "背景模糊的最大强度(像素)。设置为 0 时将完全关闭模糊效果。范围:0-128。", + "permissions": "readwrite", + "visibility": "public" + }, + "glassBezel": { + "value": 30, + "serial": 0, + "flags": [], + "name": "Glass Bezel Width", + "name[zh_CN]": "玻璃边缘厚度", + "description": "The rounded edge bevel width in pixels for the Liquid Glass effect. Range: 2-60.", + "description[zh_CN]": "液态玻璃效果的圆角边缘倒角宽度(像素)。范围:2-60。", + "permissions": "readwrite", + "visibility": "public" + }, + "glassThickness": { + "value": 30, + "serial": 0, + "flags": [], + "name": "Glass Base Thickness", + "name[zh_CN]": "玻璃基础厚度", + "description": "The glass thickness in pixels for Liquid Glass refraction. Range: 10.0-200.0.", + "description[zh_CN]": "液态玻璃折射使用的玻璃厚度(像素)。范围:10.0-200.0。", + "permissions": "readwrite", + "visibility": "public" + }, + "blurAmount": { + "value": 0.6, + "serial": 0, + "flags": [], + "name": "Blur Amount", + "name[zh_CN]": "模糊量", + "description": "Normalized blur amount applied by Qt MultiEffect. 0 disables the blur contribution while keeping the effect item alive; default 0.6 uses 60% of the configured blur strength. Range: 0.0-1.0.", + "description[zh_CN]": "Qt MultiEffect 使用的归一化模糊量。0 表示关闭模糊贡献但保留效果项;默认 0.6 表示使用配置模糊强度的 60%。范围:0.0-1.0。", + "permissions": "readwrite", + "visibility": "public" + }, + "blurMultiplier": { + "value": 0.0, + "serial": 0, + "flags": [], + "name": "Blur Multiplier", + "name[zh_CN]": "模糊倍率", + "description": "Multiplier applied to extend the backdrop blur radius. 0 keeps Qt MultiEffect's default-quality blur radius; larger values extend the radius but reduce quality. Range: 0.0-4.0.", + "description[zh_CN]": "用于扩展背景模糊半径的倍率。0 表示使用 Qt MultiEffect 的默认质量模糊半径;值越大会扩展半径但降低质量。范围:0.0-4.0。", + "permissions": "readwrite", + "visibility": "public" + }, + "glassSaturation": { + "value": 0.0, + "serial": 0, + "flags": [], + "name": "Glass Saturation", + "name[zh_CN]": "玻璃饱和度", + "description": "Saturation adjustment applied by Qt MultiEffect before Liquid Glass refraction. Range: -1.0-1.0.", + "description[zh_CN]": "液态玻璃折射前由 Qt MultiEffect 应用的饱和度调节。范围:-1.0-1.0。", + "permissions": "readwrite", + "visibility": "public" + }, + "glassSpecular": { + "value": 0.0, + "serial": 0, + "flags": [], + "name": "Glass Specular", + "name[zh_CN]": "玻璃高光强度", + "description": "Specular highlight intensity for the Liquid Glass rim and Fresnel response. 0 disables specular highlights. Range: 0.0-1.0.", + "description[zh_CN]": "液态玻璃边缘高光与菲涅尔响应强度。0 表示关闭高光。范围:0.0-1.0。", + "permissions": "readwrite", + "visibility": "public" + }, + "glassProfilePower": { + "value": 2.0, + "serial": 0, + "flags": [], + "name": "Glass Profile Power", + "name[zh_CN]": "玻璃轮廓幂次", + "description": "Surface profile exponent controlling the super-ellipse shape. 2 produces a rounder profile; higher values sharpen the bezel transition. Range: 1.0-10.0.", + "description[zh_CN]": "控制超椭圆形状的表面轮廓指数。2 产生更圆的轮廓;值越高边缘过渡越尖锐。范围:1.0-10.0。", + "permissions": "readwrite", + "visibility": "public" + }, + "lockscreenWallpaperDimEnabled": { + "value": true, + "serial": 0, + "flags": [], + "name": "Lock Screen Wallpaper Dim", + "name[zh_CN]": "锁屏壁纸压暗", + "description": "Dim the lock screen and shutdown menu wallpaper so the login UI stays legible. When disabled the wallpaper is drawn untouched. The strength is controlled by lockscreenWallpaperDimRatio.", + "description[zh_CN]": "压暗锁屏与电源/关机菜单壁纸,以保证登录界面清晰可读。关闭时壁纸原样显示,压暗强度由 lockscreenWallpaperDimRatio 控制。", + "permissions": "readwrite", + "visibility": "public" + }, + "lockscreenWallpaperDimRatio": { + "value": 0.25, + "serial": 0, + "flags": [], + "name": "Lock Screen Wallpaper Dim Ratio", + "name[zh_CN]": "锁屏壁纸压暗比例", + "description": "Maximum dimming ratio applied to the lock screen and shutdown menu wallpaper when lockscreenWallpaperDimEnabled is on. The wallpaper is scaled by (1 - ratio * luma), so highlights are dimmed while hue and saturation are preserved. Set to 0 to disable dimming entirely. Range: 0.0-1.0.", + "description[zh_CN]": "lockscreenWallpaperDimEnabled 开启时,锁屏与电源/关机菜单壁纸的最大压暗比例。壁纸按 (1 - 比例 * 亮度) 缩放,压暗高光的同时保持色相与饱和度不变。设置为 0 可完全关闭压暗效果。范围:0.0-1.0。", + "permissions": "readwrite", + "visibility": "public" + }, + "edgeSideTriggerDistance": { + "value": 20, + "serial": 0, + "flags": [], + "name": "Edge Side Trigger Distance", + "name[zh_CN]": "左右边缘触发距离", + "description": "Distance in pixels from the left/right screen edge at which half-screen tiling triggers", + "description[zh_CN]": "距离屏幕左/右边缘多少像素时触发半屏平铺", + "permissions": "readwrite", + "visibility": "public" + }, + "edgeTopTriggerDistance": { + "value": 5, + "serial": 0, + "flags": [], + "name": "Edge Top Trigger Distance", + "name[zh_CN]": "顶部边缘触发距离", + "description": "Distance in pixels from the top screen edge at which maximize triggers", + "description[zh_CN]": "距离屏幕顶部边缘多少像素时触发最大化", + "permissions": "readwrite", + "visibility": "public" + }, + "edgeQuadrantZoneRatio": { + "value": 0.25, + "serial": 0, + "flags": [], + "name": "Edge Quadrant Zone Ratio", + "name[zh_CN]": "四分之一屏触发区域比例", + "description": "Ratio of the edge length forming the corner (quadrant) tiling zone. Cursor within this ratio of the top/bottom of a side edge tiles to the corner quadrant, the middle zone keeps half-screen tiling. Range: 0.0-0.5", + "description[zh_CN]": "边缘长度中形成四分之一屏(角落)平铺区域的比值。光标位于左右边缘的上/下该比例范围内时平铺到对应角落象限,中间区域保持半屏平铺。范围:0.0-0.5。", + "permissions": "readwrite", + "visibility": "public" + }, + "edgeInnerDelayMs": { + "value": 250, + "serial": 0, + "flags": [], + "name": "Edge Inner Delay", + "name[zh_CN]": "内边延迟", + "description": "Delay in milliseconds before activating edge tiling on an inner edge between screens", + "description[zh_CN]": "多屏内边延迟激活边缘平铺的毫秒数", + "permissions": "readwrite", + "visibility": "public" + }, + "x11GtkIMModule": { + "value": "fcitx", + "serial": 0, + "flags": [], + "name": "GTK Input Method Module (X11)", + "name[zh_CN]": "GTK 输入法模块(X11)", + "description": "GTK input method module published through the XSettings Gtk/IMModule property, applied by GTK2/3/4 applications running on X11, including XWayland. Wayland GTK applications pick their input method through the Wayland text-input protocol and ignore this value. A colon separated list of modules is allowed. An empty value does not remove the property: GTK then falls back to locale based automatic selection and ignores gtk-im-module from the user's settings.ini.", + "description[zh_CN]": "通过 XSettings 的 Gtk/IMModule 属性发布的 GTK 输入法模块,作用于运行在 X11(含 XWayland)上的 GTK2/3/4 应用。Wayland 下的 GTK 应用通过 text-input 协议获取输入法,不使用该值。允许以冒号分隔多个模块。空字符串并不会移除该属性:此时 GTK 回退为按 locale 自动选择,用户 settings.ini 中的 gtk-im-module 不会生效。", + "permissions": "readwrite", + "visibility": "public" + } + } +} diff --git a/misc/dconfig/org.deepin.dde.treeland.user.seat.json b/misc/dconfig/org.deepin.dde.treeland.user.seat.json new file mode 100644 index 0000000000..378fecf3cc --- /dev/null +++ b/misc/dconfig/org.deepin.dde.treeland.user.seat.json @@ -0,0 +1,215 @@ +{ + "magic": "dsg.config.meta", + "version": "1.0", + "contents": { + "keyboardNumLock": { + "value": true, + "serial": 0, + "flags": [], + "name": "Keyboard Num Lock", + "name[zh_CN]": "键盘数字锁定", + "description": "Whether the Num Lock state is enabled by default on keyboards that have a numeric keypad. When enabled, the numeric keypad inputs numbers.", + "description[zh_CN]": "是否默认在带有数字小键盘的键盘上启用数字锁定。启用时数字小键盘输入数字。", + "permissions": "readwrite", + "visibility": "public" + }, + "pointerScrollFactor": { + "value": 1.0, + "serial": 0, + "flags": [], + "name": "Pointer Scroll Factor", + "name[zh_CN]": "指针滚动因子", + "description": "Scaling factor applied to continuous scroll axis deltas generated by pointer devices such as mice and trackballs. A value of 1.0 means no change; values greater than 1.0 amplify scrolling speed; values between 0 and 1.0 reduce scrolling speed. This factor does not affect discrete scroll button events.", + "description[zh_CN]": "应用于鼠标、轨迹球等指针设备连续滚动轴增量的缩放因子。1.0 表示不改变;大于 1.0 加快滚动速度;0 到 1.0 之间减慢滚动速度。此因子不影响离散滚动按钮事件。", + "permissions": "readwrite", + "visibility": "public" + }, + "pointerHandMode": { + "value": "Right", + "serial": 0, + "flags": [], + "name": "Pointer Hand Mode", + "name[zh_CN]": "指针惯用手模式", + "description": "Configures the primary button mapping for pointer devices. \"Right\" means the left physical button is the primary button (default for right-handed users); \"Left\" means the right physical button is the primary button (for left-handed users).", + "description[zh_CN]": "配置指针设备的主按钮映射。\"Right\" 表示左侧物理按键为主按钮(右撇子默认);\"Left\" 表示右侧物理按键为主按钮(左撇子适用)。", + "permissions": "readwrite", + "visibility": "public" + }, + "mouseAccelSpeed": { + "value": 0.333333, + "serial": 0, + "flags": [], + "name": "Mouse Acceleration Speed", + "name[zh_CN]": "鼠标加速速度", + "description": "Controls the cursor acceleration sensitivity for mice. The valid range is -1.0 to 1.0, where 0.0 is the neutral default meaning no acceleration adjustment. Negative values reduce acceleration (cursor moves more slowly at higher speeds), positive values increase acceleration (cursor moves faster at higher speeds).", + "description[zh_CN]": "控制鼠标光标加速灵敏度。有效范围为 -1.0 到 1.0,0.0 为默认中性值,表示不做加速调整。负值降低加速(高速移动时光标变慢),正值增加加速(高速移动时光标变快)。", + "permissions": "readwrite", + "visibility": "public" + }, + "mouseAccelerationProfile": { + "value": 2, + "serial": 0, + "flags": [], + "name": "Mouse Acceleration Profile", + "name[zh_CN]": "鼠标加速配置", + "description": "Mouse acceleration profile, corresponding to libinput acceleration profiles. Valid values: 0 (None, use device default), 1 (Flat, cursor speed is directly proportional to physical movement with no acceleration), 2 (Adaptive, acceleration increases with cursor speed, this is the libinput default), 4 (Custom).", + "description[zh_CN]": "鼠标加速配置,对应 libinput 加速配置文件。可选值:0(None,使用设备默认值)、1(Flat,光标速度与物理移动成正比,无加速)、2(Adaptive,加速随光标速度递增,为 libinput 默认值)、4(Custom,自定义)。", + "permissions": "readwrite", + "visibility": "public" + }, + "mouseNaturalScroll": { + "value": false, + "serial": 0, + "flags": [], + "name": "Mouse Natural Scroll", + "name[zh_CN]": "鼠标自然滚动", + "description": "Whether natural scrolling is enabled for mice. When enabled, scrolling content moves in the same direction as the finger movement on the mouse wheel (e.g., scrolling down moves the content downward). When disabled, the traditional behavior is used (scrolling down moves the viewport upward).", + "description[zh_CN]": "是否为鼠标启用自然滚动。启用后,内容滚动方向与鼠标滚轮拨动方向一致(例如向下拨动滚轮时内容向下移动)。禁用时使用传统行为(向下拨动滚轮时视口向上移动)。", + "permissions": "readwrite", + "visibility": "public" + }, + "touchpadAccelSpeed": { + "value": 0.333333, + "serial": 0, + "flags": [], + "name": "Touchpad Acceleration Speed", + "name[zh_CN]": "触控板加速速度", + "description": "Controls the cursor acceleration sensitivity for touchpads. The valid range is -1.0 to 1.0, where 0.0 is the neutral default meaning no acceleration adjustment. Negative values reduce acceleration (cursor moves more slowly at higher speeds), positive values increase acceleration (cursor moves faster at higher speeds).", + "description[zh_CN]": "控制触控板光标加速灵敏度。有效范围为 -1.0 到 1.0,0.0 为默认中性值,表示不做加速调整。负值降低加速(高速移动时光标变慢),正值增加加速(高速移动时光标变快)。", + "permissions": "readwrite", + "visibility": "public" + }, + "touchpadAccelerationProfile": { + "value": 1, + "serial": 0, + "flags": [], + "name": "Touchpad Acceleration Profile", + "name[zh_CN]": "触控板加速配置", + "description": "Touchpad acceleration profile, corresponding to libinput acceleration profiles. Valid values: 0 (None, use device default), 1 (Flat, cursor speed is directly proportional to physical movement with no acceleration), 2 (Adaptive, acceleration increases with cursor speed, this is the libinput default), 4 (Custom).", + "description[zh_CN]": "触控板加速配置,对应 libinput 加速配置文件。可选值:0(None,使用设备默认值)、1(Flat,光标速度与物理移动成正比,无加速)、2(Adaptive,加速随光标速度递增,为 libinput 默认值)、4(Custom,自定义)。", + "permissions": "readwrite", + "visibility": "public" + }, + "touchpadDisableWhileTyping": { + "value": true, + "serial": 0, + "flags": [], + "name": "Touchpad Disable While Typing", + "name[zh_CN]": "触控板打字时禁用", + "description": "When enabled, the touchpad is temporarily disabled while keyboard input is detected to prevent accidental cursor movement or clicks caused by palm contact during typing.", + "description[zh_CN]": "启用后,在检测到键盘输入时将暂时禁用触控板,以防止打字时因手掌接触触控板而导致意外光标移动或点击。", + "permissions": "readwrite", + "visibility": "public" + }, + "touchpadTapToClick": { + "value": true, + "serial": 0, + "flags": [], + "name": "Touchpad Tap To Click", + "name[zh_CN]": "触控板轻触点击", + "description": "When enabled, a tap or short touch on the touchpad surface is treated as a left button click, allowing users to click without pressing the physical touchpad button.", + "description[zh_CN]": "启用后,在触控板表面轻触或短按会被视为左键点击,允许用户无需按下物理按键即可完成点击操作。", + "permissions": "readwrite", + "visibility": "public" + }, + "touchpadNaturalScroll": { + "value": true, + "serial": 0, + "flags": [], + "name": "Touchpad Natural Scroll", + "name[zh_CN]": "触控板自然滚动", + "description": "Whether natural scrolling is enabled for touchpads. When enabled, scrolling content moves in the same direction as the finger movement on the touchpad surface (e.g., swiping up moves the content upward). When disabled, the traditional behavior is used (swiping up moves the viewport downward).", + "description[zh_CN]": "是否为触控板启用自然滚动。启用后,内容滚动方向与触控板表面手指滑动方向一致(例如向上滑动时内容向上移动)。禁用时使用传统行为(向上滑动时视口向下移动)。", + "permissions": "readwrite", + "visibility": "public" + }, + "touchpadSendEventsMode": { + "value": 0, + "serial": 0, + "flags": [], + "name": "Touchpad Send Events Mode", + "name[zh_CN]": "触控板发送事件模式", + "description": "Controls whether the touchpad sends input events. Valid values: 0 (Enabled, touchpad sends events normally), 1 (Disabled, touchpad is completely disabled and will not send any events), 2 (DisabledOnExternalMouse, touchpad is disabled only when an external mouse is connected). Corresponds to libinput send events modes.", + "description[zh_CN]": "控制触控板是否发送输入事件。可选值:0(Enabled,触控板正常发送事件)、1(Disabled,触控板完全禁用,不发送任何事件)、2(DisabledOnExternalMouse,仅在连接外部鼠标时禁用触控板)。对应 libinput 的事件发送模式。", + "permissions": "readwrite", + "visibility": "public" + }, + "keyboardRate": { + "value": 20, + "serial": 0, + "flags": [], + "name": "Keyboard Repeat Rate", + "name[zh_CN]": "键盘重复速率", + "description": "Key repeat rate in characters per second when a key is held down. Higher values result in faster key repeat. The typical valid range is 2 to 1000. A value of 0 effectively disables key repeat.", + "description[zh_CN]": "按住按键时每秒重复输入的字符数。值越大重复越快。有效范围通常为 2 到 1000。设为 0 时实际等同于禁用按键重复。", + "permissions": "readwrite", + "visibility": "public" + }, + "keyboardDelay": { + "value": 250, + "serial": 0, + "flags": [], + "name": "Keyboard Repeat Delay", + "name[zh_CN]": "键盘重复延迟", + "description": "Delay in milliseconds before a held key begins to repeat. Lower values result in a shorter wait before key repeat starts. The typical valid range is 0 to 1000 milliseconds.", + "description[zh_CN]": "按住按键后开始重复输入前的等待时间(以毫秒为单位)。值越低等待时间越短。有效范围通常为 0 到 1000 毫秒。", + "permissions": "readwrite", + "visibility": "public" + }, + "touchpadHoldTimeoutMs": { + "value": 0, + "serial": 0, + "flags": [], + "name": "Touchpad Hold Gesture Timeout", + "name[zh_CN]": "触控板长按手势超时", + "description": "Duration in milliseconds to wait after a libinput HOLD BEGIN event before triggering the hold gesture action.", + "description[zh_CN]": "收到 libinput HOLD BEGIN 事件后等待多少毫秒再触发 hold 手势动作。", + "permissions": "readwrite", + "visibility": "public" + }, + "xkbLayout": { + "value": "", + "serial": 0, + "flags": [], + "name": "Keyboard Layout", + "name[zh_CN]": "键盘布局", + "description": "XKB keyboard layout(s). Comma-separated list for multiple layouts, e.g. \"us\" or \"cz,us\". Empty string means XKB default (\"us\").", + "description[zh_CN]": "XKB 键盘布局。多个布局用逗号分隔,如 \"us\" 或 \"cz,us\"。空字符串表示 XKB 默认值(\"us\")。", + "permissions": "readwrite", + "visibility": "public" + }, + "xkbModel": { + "value": "", + "serial": 0, + "flags": [], + "name": "Keyboard Model", + "name[zh_CN]": "键盘型号", + "description": "XKB keyboard model, e.g. \"pc104\" or \"pc105\". Empty string means XKB default.", + "description[zh_CN]": "XKB 键盘型号,如 \"pc104\" 或 \"pc105\"。空字符串表示 XKB 默认值。", + "permissions": "readwrite", + "visibility": "public" + }, + "xkbVariant": { + "value": "", + "serial": 0, + "flags": [], + "name": "Keyboard Variant", + "name[zh_CN]": "键盘变体", + "description": "XKB keyboard variant(s). Comma-separated list matching the layouts, e.g. \"\" or \",dvorak\". Empty string means no variant (XKB default).", + "description[zh_CN]": "XKB 键盘变体。用逗号分隔以对应各个布局,如 \"\" 或 \",dvorak\"。空字符串表示无变体(XKB 默认值)。", + "permissions": "readwrite", + "visibility": "public" + }, + "xkbOptions": { + "value": "", + "serial": 0, + "flags": [], + "name": "Keyboard Options", + "name[zh_CN]": "键盘选项", + "description": "XKB keyboard options, comma-separated, e.g. \"grp:win_space_toggle\". Empty string means no extra options.", + "description[zh_CN]": "XKB 键盘选项,逗号分隔,如 \"grp:win_space_toggle\"。空字符串表示无额外选项。", + "permissions": "readwrite", + "visibility": "public" + } + } +} diff --git a/misc/icons/add.dci b/misc/icons/add.dci new file mode 100644 index 0000000000..cf1bfdc83e Binary files /dev/null and b/misc/icons/add.dci differ diff --git a/misc/icons/backToLightdm.dci b/misc/icons/backToLightdm.dci new file mode 100644 index 0000000000..fc6e85ab80 Binary files /dev/null and b/misc/icons/backToLightdm.dci differ diff --git a/misc/icons/close.dci b/misc/icons/close.dci new file mode 100644 index 0000000000..f35910a6e2 Binary files /dev/null and b/misc/icons/close.dci differ diff --git a/misc/icons/gezi.png b/misc/icons/gezi.png new file mode 100644 index 0000000000..677dcf6c93 Binary files /dev/null and b/misc/icons/gezi.png differ diff --git a/misc/icons/login_capslock.dci b/misc/icons/login_capslock.dci new file mode 100644 index 0000000000..3073cbc297 Binary files /dev/null and b/misc/icons/login_capslock.dci differ diff --git a/misc/icons/login_display_password.dci b/misc/icons/login_display_password.dci new file mode 100644 index 0000000000..daa688f398 Binary files /dev/null and b/misc/icons/login_display_password.dci differ diff --git a/misc/icons/login_hibernate.dci b/misc/icons/login_hibernate.dci new file mode 100644 index 0000000000..eca76d2761 Binary files /dev/null and b/misc/icons/login_hibernate.dci differ diff --git a/misc/icons/login_hidden_password.dci b/misc/icons/login_hidden_password.dci new file mode 100644 index 0000000000..3e2beccc44 Binary files /dev/null and b/misc/icons/login_hidden_password.dci differ diff --git a/misc/icons/login_hint.dci b/misc/icons/login_hint.dci new file mode 100644 index 0000000000..ffa7eed7c9 Binary files /dev/null and b/misc/icons/login_hint.dci differ diff --git a/misc/icons/login_keyboard.dci b/misc/icons/login_keyboard.dci new file mode 100644 index 0000000000..b6922530f9 Binary files /dev/null and b/misc/icons/login_keyboard.dci differ diff --git a/misc/icons/login_lock.dci b/misc/icons/login_lock.dci new file mode 100644 index 0000000000..973a3bc8e9 Binary files /dev/null and b/misc/icons/login_lock.dci differ diff --git a/misc/icons/login_logout.dci b/misc/icons/login_logout.dci new file mode 100644 index 0000000000..aa9ef9e199 Binary files /dev/null and b/misc/icons/login_logout.dci differ diff --git a/misc/icons/login_open.dci b/misc/icons/login_open.dci new file mode 100644 index 0000000000..59fef0e23e Binary files /dev/null and b/misc/icons/login_open.dci differ diff --git a/misc/icons/login_power.dci b/misc/icons/login_power.dci new file mode 100644 index 0000000000..0613cf56fb Binary files /dev/null and b/misc/icons/login_power.dci differ diff --git a/misc/icons/login_reboot.dci b/misc/icons/login_reboot.dci new file mode 100644 index 0000000000..3c527c4372 Binary files /dev/null and b/misc/icons/login_reboot.dci differ diff --git a/misc/icons/login_shutdown.dci b/misc/icons/login_shutdown.dci new file mode 100644 index 0000000000..5e2addfddf Binary files /dev/null and b/misc/icons/login_shutdown.dci differ diff --git a/misc/icons/login_suspend.dci b/misc/icons/login_suspend.dci new file mode 100644 index 0000000000..5237fc5e43 Binary files /dev/null and b/misc/icons/login_suspend.dci differ diff --git a/misc/icons/login_switchuser.dci b/misc/icons/login_switchuser.dci new file mode 100644 index 0000000000..08d1af3e11 Binary files /dev/null and b/misc/icons/login_switchuser.dci differ diff --git a/misc/icons/login_update_reboot.dci b/misc/icons/login_update_reboot.dci new file mode 100644 index 0000000000..a4251c21a3 Binary files /dev/null and b/misc/icons/login_update_reboot.dci differ diff --git a/misc/icons/login_update_shutdown.dci b/misc/icons/login_update_shutdown.dci new file mode 100644 index 0000000000..73d39b1dbd Binary files /dev/null and b/misc/icons/login_update_shutdown.dci differ diff --git a/misc/icons/login_user.dci b/misc/icons/login_user.dci new file mode 100644 index 0000000000..e4a7c1bf8a Binary files /dev/null and b/misc/icons/login_user.dci differ diff --git a/misc/icons/logo.svg b/misc/icons/logo.svg new file mode 100644 index 0000000000..d832968f87 --- /dev/null +++ b/misc/icons/logo.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/misc/icons/multitaskview_close.dci b/misc/icons/multitaskview_close.dci new file mode 100644 index 0000000000..0781584916 Binary files /dev/null and b/misc/icons/multitaskview_close.dci differ diff --git a/misc/icons/select_output.dci b/misc/icons/select_output.dci new file mode 100644 index 0000000000..f98b5824b5 Binary files /dev/null and b/misc/icons/select_output.dci differ diff --git a/misc/icons/select_region.dci b/misc/icons/select_region.dci new file mode 100644 index 0000000000..1d24dd2f89 Binary files /dev/null and b/misc/icons/select_region.dci differ diff --git a/misc/icons/select_window.dci b/misc/icons/select_window.dci new file mode 100644 index 0000000000..b86be59359 Binary files /dev/null and b/misc/icons/select_window.dci differ diff --git a/misc/interfaces/org.deepin.DisplayManager.xml b/misc/interfaces/org.deepin.DisplayManager.xml new file mode 100644 index 0000000000..4b3b3db0b7 --- /dev/null +++ b/misc/interfaces/org.deepin.DisplayManager.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/misc/interfaces/org.freedesktop.DisplayManager.Seat.xml b/misc/interfaces/org.freedesktop.DisplayManager.Seat.xml new file mode 100644 index 0000000000..d2650eb50b --- /dev/null +++ b/misc/interfaces/org.freedesktop.DisplayManager.Seat.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/misc/interfaces/org.freedesktop.DisplayManager.Session.xml b/misc/interfaces/org.freedesktop.DisplayManager.Session.xml new file mode 100644 index 0000000000..2d7f194696 --- /dev/null +++ b/misc/interfaces/org.freedesktop.DisplayManager.Session.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/misc/interfaces/org.freedesktop.DisplayManager.xml b/misc/interfaces/org.freedesktop.DisplayManager.xml new file mode 100644 index 0000000000..45595eeea2 --- /dev/null +++ b/misc/interfaces/org.freedesktop.DisplayManager.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/misc/interfaces/org.freedesktop.login1.Manager.xml b/misc/interfaces/org.freedesktop.login1.Manager.xml new file mode 100644 index 0000000000..800d2bc356 --- /dev/null +++ b/misc/interfaces/org.freedesktop.login1.Manager.xml @@ -0,0 +1,220 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/misc/interfaces/org.freedesktop.login1.Seat.xml b/misc/interfaces/org.freedesktop.login1.Seat.xml new file mode 100644 index 0000000000..a73a6b3130 --- /dev/null +++ b/misc/interfaces/org.freedesktop.login1.Seat.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/misc/interfaces/org.freedesktop.login1.Session.xml b/misc/interfaces/org.freedesktop.login1.Session.xml new file mode 100644 index 0000000000..eb450d1eab --- /dev/null +++ b/misc/interfaces/org.freedesktop.login1.Session.xml @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/misc/interfaces/org.freedesktop.login1.User.xml b/misc/interfaces/org.freedesktop.login1.User.xml new file mode 100644 index 0000000000..643d4423d7 --- /dev/null +++ b/misc/interfaces/org.freedesktop.login1.User.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/misc/polkit/CMakeLists.txt b/misc/polkit/CMakeLists.txt new file mode 100644 index 0000000000..6a7177dfad --- /dev/null +++ b/misc/polkit/CMakeLists.txt @@ -0,0 +1,12 @@ +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/org.deepin.dde.treeland-debug.policy.in + ${CMAKE_CURRENT_BINARY_DIR}/org.deepin.dde.treeland-debug.policy + @ONLY +) + +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/org.deepin.dde.treeland-debug.policy + DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/polkit-1/actions" +) diff --git a/misc/polkit/org.deepin.dde.treeland-debug.policy.in b/misc/polkit/org.deepin.dde.treeland-debug.policy.in new file mode 100644 index 0000000000..46c2d745b0 --- /dev/null +++ b/misc/polkit/org.deepin.dde.treeland-debug.policy.in @@ -0,0 +1,25 @@ + + + + + UnionTech Software Technology Co., Ltd. + https://www.uniontech.com + + + Run treeland-debug with elevated privileges + 以管理员权限运行 treeland-debug + Authentication is required to run treeland-debug + 运行 treeland-debug 需要管理员认证 + treeland-debug + + no + auth_admin + auth_admin + + @CMAKE_INSTALL_FULL_BINDIR@/treeland-debug + true + + + diff --git a/misc/shaders/liquidglass.frag b/misc/shaders/liquidglass.frag new file mode 100644 index 0000000000..f2062f9136 --- /dev/null +++ b/misc/shaders/liquidglass.frag @@ -0,0 +1,496 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#version 440 + +layout(location = 0) in vec2 texCoord; +layout(location = 0) out vec4 fragColor; + +layout(std140, binding = 0) uniform buf { + mat4 qt_Matrix; + float qt_Opacity; + vec2 itemSize; + vec4 frameRect; + vec2 lightDirection; + float radius; + float bezelWidth; + float thickness; + float ior; + float specular; + float tint; + float contentEdgePull; // fraction of optical pull kept at the glass lip (0–1) + float contentRampEnd; // t in bezel where content pull reaches full (0–1) + float refractionMaxTan; // cap on geometric slope tan(theta) + float profilePower; // surface profile exponent (default 4.0 = squircle) + float innerShadow; // inner shadow intensity (0–1, default 0.25) +} ubuf; + +layout(binding = 1) uniform sampler2D source; + +const float kSqrt2 = 1.4142135623730951; +const float kInvSqrt2 = 0.7071067811865476; + +vec2 halfSize = ubuf.frameRect.zw * 0.5; + +float sdRoundedRect(vec2 p, vec2 halfSize, float r) +{ + float rr = min(max(r, 0.0), min(halfSize.x, halfSize.y)); + vec2 q = abs(p) - halfSize + rr; + return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - rr; +} + +// Analytic gradient of sdRoundedRect w.r.t. p (outward-pointing, unit length on the surface). +vec2 sdRoundedRectGrad(vec2 p, vec2 halfSize, float r) +{ + float rr = min(max(r, 0.0), min(halfSize.x, halfSize.y)); + vec2 ap = abs(p); + vec2 q = ap - halfSize + rr; + vec2 s = vec2(p.x < 0.0 ? -1.0 : 1.0, p.y < 0.0 ? -1.0 : 1.0); + + if (min(q.x, q.y) > 0.0) { + float ql = length(q); + return s * (q / max(ql, 1e-6)); + } + + // Flat / interior: sd = max(q.x, q.y) - rr when inside the expanded rect. + if (q.x > q.y) + return vec2(s.x, 0.0); + if (q.y > q.x) + return vec2(0.0, s.y); + // Tie on the diagonal — any convex combination is a subgradient; pick the bisector. + return s * kInvSqrt2; +} + +// ── Linear bezel field ──────────────────────────────────────────────── +float fieldBezel() +{ + float limit = min(halfSize.x, halfSize.y); + return clamp(ubuf.bezelWidth, 1.0, max(limit - 1.0, 1.0)); +} + +float fieldT(vec2 p, float rr) +{ + float limit = min(halfSize.x, halfSize.y); + float r = clamp(rr, 0.0, limit); + float b = fieldBezel(); + return clamp(-sdRoundedRect(p, halfSize, r) / b, 0.0, 1.0); +} + +// Outward unit normal of the bezel field (matches previous -normalize(∇fieldT)). +vec2 fieldNormal(vec2 p, float rr) +{ + vec2 g = sdRoundedRectGrad(p, halfSize, rr); + float len = length(g); + return len > 1e-5 ? (g / len) : vec2(0.0); +} + +// ── Rounded-square Coons map (actual → virtual) ─────────────────────── +struct BoundaryResult { + vec2 point; + vec2 derivative; +}; + +struct RoundedMapResult { + vec2 point; + vec4 jacobian; +}; + +float cornerQuintic(float value) +{ + float s = clamp(value, 0.0, 1.0); + return s * s * s * (s * (s * 6.0 - 15.0) + 10.0); +} + +float cornerQuinticDerivative(float value) +{ + float s = clamp(value, 0.0, 1.0); + return 30.0 * s * s * (s - 1.0) * (s - 1.0); +} + +float cornerArcParameter(float value) +{ + float s = clamp(value, 0.0, 1.0); + float tangent = kSqrt2; + float s2 = s * s; + float s3 = s2 * s; + return (s3 - 2.0 * s2 + s) * tangent + + (-2.0 * s3 + 3.0 * s2) + + (s3 - s2) * tangent; +} + +float cornerArcParameterDerivative(float value) +{ + float s = clamp(value, 0.0, 1.0); + float tangent = kSqrt2; + return (3.0 * s * s - 4.0 * s + 1.0) * tangent + + (-6.0 * s * s + 6.0 * s) + + (3.0 * s * s - 2.0 * s) * tangent; +} + +BoundaryResult cornerUnitArc(vec2 start, vec2 end, float parameter, float parameterDerivative) +{ + vec2 delta = end - start; + vec2 raw = start + delta * parameter; + float rawLength = length(raw); + vec2 direction = raw / rawLength; + vec2 rawDerivative = delta * parameterDerivative; + float parallel = dot(direction, rawDerivative); + BoundaryResult result; + result.point = direction; + result.derivative = (rawDerivative - direction * parallel) / rawLength; + return result; +} + +BoundaryResult cornerTopBoundary(float value, float alpha) +{ + BoundaryResult result; + if (alpha <= 1e-5 || value <= 1.0 - alpha) { + result.point = vec2(value, 1.0); + result.derivative = vec2(1.0, 0.0); + return result; + } + float local = (value - (1.0 - alpha)) / alpha; + BoundaryResult arc = cornerUnitArc(vec2(0.0, 1.0), vec2(kInvSqrt2), + cornerArcParameter(local), cornerArcParameterDerivative(local)); + result.point = vec2(1.0 - alpha) + alpha * arc.point; + result.derivative = arc.derivative; + return result; +} + +BoundaryResult cornerRightBoundary(float value, float alpha) +{ + BoundaryResult result; + if (alpha <= 1e-5 || value <= 1.0 - alpha) { + result.point = vec2(1.0, value); + result.derivative = vec2(0.0, 1.0); + return result; + } + float local = (value - (1.0 - alpha)) / alpha; + BoundaryResult arc = cornerUnitArc(vec2(1.0, 0.0), vec2(kInvSqrt2), + cornerArcParameter(local), cornerArcParameterDerivative(local)); + result.point = vec2(1.0 - alpha) + alpha * arc.point; + result.derivative = arc.derivative; + return result; +} + +RoundedMapResult roundedSquareMap(vec2 canonical, float alpha) +{ + float u = canonical.x; + float v = canonical.y; + BoundaryResult top = cornerTopBoundary(u, alpha); + BoundaryResult right = cornerRightBoundary(v, alpha); + vec2 topDelta = top.point - vec2(u, 1.0); + vec2 rightDelta = right.point - vec2(1.0, v); + float cornerDelta = alpha * (kInvSqrt2 - 1.0); + float hu = cornerQuintic(u); + float hv = cornerQuintic(v); + float dhu = cornerQuinticDerivative(u); + float dhv = cornerQuinticDerivative(v); + vec2 topDerivative = top.derivative - vec2(1.0, 0.0); + vec2 rightDerivative = right.derivative - vec2(0.0, 1.0); + RoundedMapResult result; + result.point = canonical + + hv * topDelta + + hu * rightDelta + - hu * hv * vec2(cornerDelta); + result.jacobian = vec4( + 1.0 + hv * topDerivative.x + dhu * rightDelta.x - dhu * hv * cornerDelta, + dhv * topDelta.x + hu * rightDerivative.x - hu * dhv * cornerDelta, + hv * topDerivative.y + dhu * rightDelta.y - dhu * hv * cornerDelta, + 1.0 + dhv * topDelta.y + hu * rightDerivative.y - hu * dhv * cornerDelta + ); + return result; +} + +vec4 inverseCornerJacobian(vec4 jacobian) +{ + float determinant = jacobian.x * jacobian.w - jacobian.y * jacobian.z; + return vec4(jacobian.w, -jacobian.y, -jacobian.z, jacobian.x) / determinant; +} + +vec2 cornerDiscToSquare(vec2 point) +{ + float root2 = kSqrt2; + float a = 2.0 + point.x * point.x - point.y * point.y; + float b = 2.0 - point.x * point.x + point.y * point.y; + return 0.5 * vec2( + sqrt(max(a + 2.0 * root2 * point.x, 0.0)) + - sqrt(max(a - 2.0 * root2 * point.x, 0.0)), + sqrt(max(b + 2.0 * root2 * point.y, 0.0)) + - sqrt(max(b - 2.0 * root2 * point.y, 0.0)) + ); +} + +vec2 invertRoundedSquare(vec2 point, float alpha) +{ + float corner = 1.0 - alpha + alpha * kInvSqrt2; + if (distance(point, vec2(corner)) <= 1e-5) + return vec2(1.0); + vec2 discInitial = cornerDiscToSquare(point); + vec2 canonical = clamp(mix(point, discInitial, alpha), vec2(0.0), vec2(1.0)); + // Good disc initial guess typically converges in 3–4 steps; keep 5 with error exit. + for (int iteration = 0; iteration < 5; ++iteration) { + RoundedMapResult mapped = roundedSquareMap(canonical, alpha); + vec2 error = mapped.point - point; + if (dot(error, error) <= 1e-10) + break; + vec4 inverse = inverseCornerJacobian(mapped.jacobian); + canonical = clamp( + canonical - vec2(inverse.x * error.x + inverse.y * error.y, + inverse.z * error.x + inverse.w * error.y), + vec2(0.0), vec2(1.0) + ); + } + return canonical; +} + +vec2 mapActualToVirtualPoint(vec2 p, float fromR, float toR, float bezel) +{ + float limit = min(halfSize.x, halfSize.y); + float from = clamp(fromR, 0.0, limit); + float to = clamp(toR, 0.0, limit); + if (abs(from - to) <= 1e-4) + return p; + + float extent = min(max(max(max(bezel, from), to), 1.0), limit); + vec2 pointSign = vec2(p.x < 0.0 ? -1.0 : 1.0, p.y < 0.0 ? -1.0 : 1.0); + vec2 distanceFromEdge = halfSize - abs(p); + if (distanceFromEdge.x >= extent || distanceFromEdge.y >= extent) + return p; + + vec2 normalized = vec2(1.0) - distanceFromEdge / extent; + vec2 canonical = invertRoundedSquare(normalized, from / extent); + vec2 target = roundedSquareMap(canonical, to / extent).point; + return pointSign * (halfSize - vec2(extent) + target * extent); +} + +// ── Corner-depth preservation ───────────────────────────────────────── +float postprocessCornerDepth(float xProgress, float yProgress) +{ + float x = clamp(xProgress, 0.0, 1.0); + float y = clamp(yProgress, 0.0, 1.0); + float lower = min(x, y); + float difference = abs(x - y); + float blendWidth = 6.0 * x * y * (1.0 - x) * (1.0 - y); + if (blendWidth <= 1e-5 || difference >= blendWidth) + return lower; + float blendProgress = difference / blendWidth; + float remaining = 1.0 - blendProgress; + return clamp(lower + 0.5 * difference * remaining * remaining, 0.0, 1.0); +} + +float arcOuter(float d, float r) +{ + return d < r ? r - sqrt(max(0.0, d * (2.0 * r - d))) : 0.0; +} + +float sourcePostprocessDepth(vec2 p, float rr, float bezel) +{ + if (rr >= bezel) + return fieldT(p, rr); + vec2 d = halfSize - abs(p); + float topProgress = clamp((d.y - arcOuter(d.x, rr)) / bezel, 0.0, 1.0); + float sideProgress = clamp((d.x - arcOuter(d.y, rr)) / bezel, 0.0, 1.0); + return postprocessCornerDepth(topProgress, sideProgress); +} + +vec2 preservePostprocessDepth(vec2 actualPoint, vec2 mappedPoint, float actualRadius, float opticalRadius, float bezel) +{ + float strength = clamp((opticalRadius - actualRadius) / max(bezel, 1.0), 0.0, 1.0); + if (strength <= 1e-5) + return mappedPoint; + + float extent = min(max(max(max(bezel, actualRadius), opticalRadius), 1.0), min(halfSize.x, halfSize.y)); + vec2 edgeDistance = halfSize - abs(actualPoint); + if (edgeDistance.x >= extent || edgeDistance.y >= extent) + return mappedPoint; + + float baseT = fieldT(mappedPoint, opticalRadius); + float sourceT = sourcePostprocessDepth(actualPoint, actualRadius, bezel); + float targetT = mix(baseT, sourceT, strength); + vec2 result = mappedPoint; + float b = fieldBezel(); + for (int iteration = 0; iteration < 3; ++iteration) { + float sdVal = sdRoundedRect(result, halfSize, opticalRadius); + float currentT = clamp(-sdVal / b, 0.0, 1.0); + float error = currentT - targetT; + if (abs(error) <= 1e-5) + break; + + // ∇fieldT ≈ -∇sd / bezel inside the unclamped band; sd is 1-Lipschitz. + vec2 gsd = sdRoundedRectGrad(result, halfSize, opticalRadius); + vec2 g = -gsd / b; + float gradientSquared = dot(g, g); + if (gradientSquared <= 1e-10) + break; + float stepLength = clamp(error / gradientSquared, -bezel * bezel, bezel * bezel); + result -= g * stepLength; + } + return result; +} + +// ── Surface profile ─────────────────────────────────────────────────── +vec2 surfaceProfile(float t) +{ + float pp = max(ubuf.profilePower, 1.0); + float s = 1.0 - clamp(t, 0.0, 1.0); + float sp = pow(s, pp); + float inside = max(1.0 - sp, 1e-4); + float height = pow(inside, 1.0 / pp); + float derivative = pow(s, pp - 1.0) * height / inside; + return vec2(height, derivative); +} + +vec3 sampleBg(vec2 uv) +{ + return texture(source, clamp(uv, vec2(0.002), vec2(0.998))).rgb; +} + +// Stretch-aware 5-tap filter. radiusPx≈0 collapses to a single sample. +vec3 sampleBgSoft(vec2 uv, vec2 resolution, float radiusPx) +{ + if (radiusPx < 0.01) + return sampleBg(uv); + + vec2 px = vec2(radiusPx) / max(resolution, vec2(1.0)); + vec3 color = sampleBg(uv) * 0.36; + color += sampleBg(uv + vec2(px.x, 0.0)) * 0.16; + color += sampleBg(uv - vec2(px.x, 0.0)) * 0.16; + color += sampleBg(uv + vec2(0.0, px.y)) * 0.16; + color += sampleBg(uv - vec2(0.0, px.y)) * 0.16; + return color; +} + +vec4 finishColor(vec3 color, float shapeAlpha) +{ + if (ubuf.tint > 1e-4) + color = mix(color, vec3(1.0), clamp(ubuf.tint, 0.0, 1.0)); + float alpha = shapeAlpha * ubuf.qt_Opacity; + return vec4(clamp(color, 0.0, 1.0) * alpha, alpha); +} + +// ── Main ────────────────────────────────────────────────────────────── +void main() +{ + vec2 frameCenter = ubuf.frameRect.xy + halfSize; + vec2 p = texCoord * ubuf.itemSize - frameCenter; + + float outerRadius = min(max(ubuf.radius, 0.0), min(halfSize.x, halfSize.y)); + float sd = sdRoundedRect(p, halfSize, outerRadius); + + // Anti-aliased shape edge. + float scale = length(vec2(dFdx(sd), dFdy(sd))); + float edgeAA = max(scale * 2.0, 2.0); + float shapeAlpha = smoothstep(edgeAA, -edgeAA, sd); + + if (shapeAlpha <= 0.0) { + fragColor = vec4(0.0); + return; + } + + float configuredBezel = max(ubuf.bezelWidth, 1.0); + float maxSizeBezel = max(min(halfSize.x, halfSize.y) - 1.0, 1.0); + float bezel = min(configuredBezel, maxSizeBezel); + // virtualRadius is private: radius < bezel → follow bezel, else follow radius. + float opticalRadius = clamp(max(outerRadius, bezel), 0.0, min(halfSize.x, halfSize.y)); + + float effectExtent = bezel; + if (ubuf.specular > 1e-4) + effectExtent = max(effectExtent, 5.0); + + // Parameterized ring margin so the cheap center path never skips pixels that + // mapping/preserve could still pull into the bezel effect band. + // + // radiusLift = opticalRadius - outerRadius (0 when radius >= bezel). + // Bounds used (all scale with lift; zero when mapping is identity): + // • fixed-p SDF shrink when r rises: (√2 - 1) * lift + // • Coons corner boundary displacement: (1 - 1/√2) * lift + // • preserve depth correction travel: lift + // Sum = lift * (1 + 1/√2). + float radiusLift = max(opticalRadius - outerRadius, 0.0); + float safetyMargin = radiusLift * (1.0 + kInvSqrt2); + + float actualDistFromEdge = -sd; + if (actualDistFromEdge > effectExtent + safetyMargin) { + fragColor = finishColor(sampleBg(texCoord), shapeAlpha); + return; + } + + // Deform actual coordinates to virtual optical coordinates. + vec2 mappedPoint = mapActualToVirtualPoint(p, outerRadius, opticalRadius, bezel); + vec2 shadePoint = preservePostprocessDepth(p, mappedPoint, outerRadius, opticalRadius, bezel); + float opticalDistFromEdge = -sdRoundedRect(shadePoint, halfSize, opticalRadius); + + if (opticalDistFromEdge > effectExtent) { + fragColor = finishColor(sampleBg(texCoord), shapeAlpha); + return; + } + + float t = fieldT(shadePoint, opticalRadius); + vec2 n2 = fieldNormal(shadePoint, opticalRadius); + + float maxTan = max(ubuf.refractionMaxTan, 0.1); + + vec2 profile = surfaceProfile(t); + // Path length stays slab-like (not h*thickness). Profile height collapsed + // to ~0 at the lip and left an unrefracted ring inside the outline. + float thick = max(ubuf.thickness, 0.0); + float edgePull = clamp(ubuf.contentEdgePull, 0.0, 1.0); + float rawTan = profile.y * (thick / max(bezel, 1.0)); + float slopeMag = min(rawTan, maxTan); + + float H = thick; + + float rampEnd = clamp(ubuf.contentRampEnd, 0.001, 1.0); + // edgePull=0 → contentRamp = smoothstep(0, rampEnd, t); keep exact mix for pull>0. + float contentRamp = (edgePull <= 1e-5) + ? smoothstep(0.0, rampEnd, t) + : mix(edgePull, 1.0, smoothstep(0.0, rampEnd, t)); + float maxDisp = min(min(bezel * 0.85, thick * 0.75), 48.0) + * max(maxTan / 2.75, 1.0); + + float iorG = max(ubuf.ior, 1.0001); + + float incidentInvLen = inversesqrt(slopeMag * slopeMag + 1.0); + float sinI = slopeMag * incidentInvLen; + float sinT = clamp(sinI / iorG, 0.0, 0.999); + float tanT = sinT * inversesqrt(max(1.0 - sinT * sinT, 1e-4)); + // Cap the geometric Snell term first, then apply contentRamp so edgePull + // still controls the lip when thickness would otherwise slam into maxDisp. + float magG = min(H * max(slopeMag - tanT, 0.0), maxDisp) * contentRamp; + vec2 inward = -n2; + vec2 offG = inward * magG; + + vec2 sampleUv = (shadePoint + frameCenter + offG) / ubuf.itemSize; + // Soften only where UV stretch exceeds ~1px (curved warp jaggies). + float filterPx = 0.0; + if (magG > 0.5) { + float stretchX = length(vec2(dFdx(sampleUv.x), dFdy(sampleUv.x))) * ubuf.itemSize.x; + float stretchY = length(vec2(dFdx(sampleUv.y), dFdy(sampleUv.y))) * ubuf.itemSize.y; + filterPx = clamp(max(max(stretchX, stretchY) - 1.0, 0.0) * 0.85, 0.0, 2.5); + } + vec3 color = sampleBgSoft(sampleUv, ubuf.itemSize, filterPx); + + if (ubuf.specular > 1e-4) { + vec3 N = normalize(vec3(n2 * slopeMag, 1.0)); + float oneMinusCos = 1.0 - clamp(N.z, 0.0, 1.0); + float oneMinusCos2 = oneMinusCos * oneMinusCos; + float fresnel = 0.04 + 0.96 * oneMinusCos2 * oneMinusCos2 * oneMinusCos; + vec2 lightDir = normalize(ubuf.lightDirection); + float rimDot = abs(dot(n2, lightDir)); + float rimFalloff = 1.0 - smoothstep(0.0, bezel * 0.45, opticalDistFromEdge); + float specHighlight = fresnel * pow(rimDot * rimFalloff, 1.35); + color += vec3(specHighlight * clamp(ubuf.specular, 0.0, 1.0)); + + float innerRim = smoothstep(0.0, 2.0, opticalDistFromEdge) + * (1.0 - smoothstep(2.0, 5.0, opticalDistFromEdge)); + color += vec3(innerRim * 0.12 * clamp(ubuf.specular, 0.0, 1.0)); + } + + if (ubuf.innerShadow > 1e-4) { + float innerShadowMask = 1.0 - smoothstep(0.0, bezel * 0.6, opticalDistFromEdge); + color *= mix(1.0, 0.75, innerShadowMask * clamp(ubuf.innerShadow, 0.0, 1.0)); + } + + fragColor = finishColor(color, shapeAlpha); +} diff --git a/misc/shaders/liquidglass.vert b/misc/shaders/liquidglass.vert new file mode 100644 index 0000000000..2c32300ca0 --- /dev/null +++ b/misc/shaders/liquidglass.vert @@ -0,0 +1,22 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#version 440 + +layout(location = 0) in vec4 qt_Vertex; +layout(location = 1) in vec2 qt_MultiTexCoord0; + +layout(location = 0) out vec2 texCoord; + +layout(std140, binding = 0) uniform vert_buf { + mat4 qt_Matrix; + float qt_Opacity; +} vbuf; + +out gl_PerVertex { vec4 gl_Position; }; + +void main() +{ + texCoord = qt_MultiTexCoord0; + gl_Position = vbuf.qt_Matrix * qt_Vertex; +} diff --git a/misc/shaders/wallpaper_luma_dim.frag b/misc/shaders/wallpaper_luma_dim.frag new file mode 100644 index 0000000000..478c29d180 --- /dev/null +++ b/misc/shaders/wallpaper_luma_dim.frag @@ -0,0 +1,43 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// Lockscreen Luma-Adaptive Dimming (reverse-engineered empirical fit) +// - Derives the perceptual luma Y with the BT.709 weights (0.2126, 0.7152, 0.0722). +// - Scales all three RGB channels by (1 - u_dimRatio * Y), which keeps the RGB +// ratio (and therefore hue/saturation) exactly intact while dimming highlights. +// - u_strength blends between the original image (0.0, desktop) and the dimmed +// image (1.0, greeter), replacing the previous opacity-based fade-in. +#version 440 + +layout(location = 0) in vec2 qt_TexCoord0; +layout(location = 0) out vec4 fragColor; + +layout(std140, binding = 0) uniform buf { + mat4 qt_Matrix; + float qt_Opacity; + float u_dimRatio; // Maximum dimming ratio applied to pure white + float u_strength; // Effect blend strength, animated 0.0 (desktop) ↔ 1.0 (greeter) +} ubuf; + +layout(binding = 1) uniform sampler2D source; + +// Scale all RGB channels by (1 - ratio * Y) using BT.709 luma, preserving the +// exact RGB ratio so hue and saturation stay untouched. The ratio is clamped to +// [0, 1] so an out-of-range uniform cannot make the factor negative on bright +// pixels (inverting their RGB) or brighten the wallpaper instead of dimming it. +vec3 apply_luma_adaptive_dim(vec3 color) { + float ratio = clamp(ubuf.u_dimRatio, 0.0, 1.0); + float y = dot(color, vec3(0.2126, 0.7152, 0.0722)); + float factor = 1.0 - ratio * y; + return color * factor; +} + +void main() { + vec4 texColor = texture(source, qt_TexCoord0); + vec3 baseColor = texColor.rgb; + + vec3 processedColor = apply_luma_adaptive_dim(baseColor); + vec3 finalColor = mix(baseColor, processedColor, ubuf.u_strength); + + fragColor = vec4(finalColor, texColor.a) * ubuf.qt_Opacity; +} diff --git a/misc/shaders/window_transition.frag b/misc/shaders/window_transition.frag new file mode 100644 index 0000000000..01ebeef6b1 --- /dev/null +++ b/misc/shaders/window_transition.frag @@ -0,0 +1,30 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// Single-pass cross-fade for the icon-to-window transition. Both layers are +// blended in one fragment so their combined coverage stays 1 wherever the +// window is painted: cross-fading two independently translucent items would +// let the desktop through as progress * (1 - progress). +// +// Both textures cover the animation item exactly, so plain UV sampling is +// enough. The shadow is drawn by the animation item, not captured. +#version 440 + +layout(location = 0) in vec2 qt_TexCoord0; +layout(location = 0) out vec4 fragColor; + +layout(std140, binding = 0) uniform buf { + mat4 qt_Matrix; + float qt_Opacity; + float progress; // 0: icon only, 1: window content only +} ubuf; + +layout(binding = 1) uniform sampler2D windowTexture; +layout(binding = 2) uniform sampler2D iconTexture; + +void main() +{ + vec4 icon = texture(iconTexture, qt_TexCoord0); + vec4 window = texture(windowTexture, qt_TexCoord0); + fragColor = mix(icon, window, ubuf.progress) * ubuf.qt_Opacity; +} diff --git a/misc/systemd/CMakeLists.txt b/misc/systemd/CMakeLists.txt new file mode 100644 index 0000000000..e08cdec30e --- /dev/null +++ b/misc/systemd/CMakeLists.txt @@ -0,0 +1,64 @@ +if (NOT DEFINED SYSTEMD_SYSTEM_UNIT_DIR) + find_package(PkgConfig REQUIRED) + pkg_check_modules(Systemd REQUIRED systemd) + pkg_get_variable(SYSTEMD_SYSTEM_UNIT_DIR systemd systemdsystemunitdir) +endif() + +if (NOT DEFINED SYSTEMD_USER_UNIT_DIR) + find_package(PkgConfig REQUIRED) + pkg_check_modules(Systemd REQUIRED systemd) + pkg_get_variable(SYSTEMD_USER_UNIT_DIR systemd systemduserunitdir) +endif() + +macro(install_symlink filepath wantsdir) + file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/link/${wantsdir}/) + execute_process(COMMAND ${CMAKE_COMMAND} -E create_symlink ${CMAKE_INSTALL_PREFIX}/lib/systemd/user/${filepath} ${PROJECT_BINARY_DIR}/link/${wantsdir}/${filepath}) + install(FILES ${PROJECT_BINARY_DIR}/link/${wantsdir}/${filepath} DESTINATION ${SYSTEMD_USER_UNIT_DIR}/${wantsdir}/) +endmacro(install_symlink) + +configure_file("dde-session-pre.target.wants/treeland-sd.service.in" "dde-session-pre.target.wants/treeland-sd.service" IMMEDIATE @ONLY) +if (NOT DISABLE_XWAYLAND) + configure_file("dde-session-pre.target.wants/treeland-xwayland.service.in" "dde-session-pre.target.wants/treeland-xwayland.service" IMMEDIATE @ONLY) + install(FILES treeland.service.d/xwayland.conf + DESTINATION ${SYSTEMD_USER_UNIT_DIR}/treeland.service.d) +else() + configure_file(remove-xwayland-units.cmake.in + remove-xwayland-units.cmake @ONLY) + install(SCRIPT "${CMAKE_CURRENT_BINARY_DIR}/remove-xwayland-units.cmake") +endif() +configure_file("dde-session-pre.target.wants/treeland.service.in" "dde-session-pre.target.wants/treeland.service" IMMEDIATE @ONLY) +configure_file("treeland-session-helper.service.in" "treeland-session-helper.service" IMMEDIATE @ONLY) +configure_file("treeland-screensaver.service.in" "treeland-screensaver.service" IMMEDIATE @ONLY) +configure_file("treeland.service.in" "treeland.service" IMMEDIATE @ONLY) + +install(FILES ${SERVICES} DESTINATION ${SYSTEMD_USER_UNIT_DIR}) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/treeland.service DESTINATION ${SYSTEMD_SYSTEM_UNIT_DIR}) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/treeland-session-helper.service DESTINATION ${SYSTEMD_USER_UNIT_DIR}) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/treeland-screensaver.service DESTINATION ${SYSTEMD_USER_UNIT_DIR}) + +install(DIRECTORY DESTINATION ${SYSTEMD_USER_UNIT_DIR}/dde-session-pre.target.wants/) +install(DIRECTORY DESTINATION ${SYSTEMD_USER_UNIT_DIR}/dde-session-shutdown.target.wants/) +set(DDE_SESSION_PRE_WANTS + dde-session-pre.target.wants/treeland-sd.socket + dde-session-shutdown.target.wants/treeland-session-shutdown.service + ${CMAKE_CURRENT_BINARY_DIR}/dde-session-pre.target.wants/treeland-sd.service + ${CMAKE_CURRENT_BINARY_DIR}/dde-session-pre.target.wants/treeland.service +) +if (NOT DISABLE_XWAYLAND) + list(APPEND DDE_SESSION_PRE_WANTS + dde-session-pre.target.wants/treeland-xwayland.socket + ${CMAKE_CURRENT_BINARY_DIR}/dde-session-pre.target.wants/treeland-xwayland.service + ) +endif() + +install(FILES ${DDE_SESSION_PRE_WANTS} DESTINATION ${SYSTEMD_USER_UNIT_DIR}) +install_symlink(treeland-sd.socket dde-session-pre.target.wants) +install_symlink(treeland-sd.service dde-session-pre.target.wants) +if (NOT DISABLE_XWAYLAND) + install_symlink(treeland-xwayland.socket dde-session-pre.target.wants) + install_symlink(treeland-xwayland.service dde-session-pre.target.wants) +endif() +install_symlink(treeland.service dde-session-pre.target.wants) +install_symlink(treeland-session-shutdown.service dde-session-shutdown.target.wants) +install_symlink(treeland-session-helper.service treeland.service.wants) +install_symlink(treeland-screensaver.service treeland.service.wants) diff --git a/misc/systemd/dde-session-pre.target.wants/treeland-sd.service.in b/misc/systemd/dde-session-pre.target.wants/treeland-sd.service.in new file mode 100644 index 0000000000..b41c5eb106 --- /dev/null +++ b/misc/systemd/dde-session-pre.target.wants/treeland-sd.service.in @@ -0,0 +1,35 @@ +[Unit] +Description=Treeland socket helper service +CollectMode=inactive-or-failed + +Requires=treeland.service +PartOf=treeland.service +After=treeland.service + +Requires=treeland-sd.socket +PartOf=treeland-sd.socket +After=treeland-sd.socket + +Requisite=dde-session-pre.target +PartOf=dde-session-pre.target +Before=dde-session-pre.target + +[Service] +ExecCondition=/bin/sh -c 'test "$XDG_SESSION_DESKTOP" = "Treeland" || exit 2' +Type=notify +Sockets=treeland-sd.socket +UnsetEnvironment=DISPLAY +UnsetEnvironment=WAYLAND_DISPLAY +ExecStart=@CMAKE_INSTALL_FULL_LIBEXECDIR@/treeland-sd --type wayland +ExecStartPost=-/usr/bin/systemctl --user set-environment WAYLAND_DISPLAY=treeland.socket +ExecStartPost=-/usr/bin/systemctl --user set-environment QT_IM_MODULE=fcitx +ExecStartPost=-/usr/bin/systemctl --user set-environment QT_IM_MODULES=wayland;fcitx +ExecStartPost=-/usr/bin/systemctl --user set-environment SDL_IM_MODULE=fcitx +ExecStartPost=-/usr/bin/systemctl --user set-environment XMODIFIERS=@im=fcitx +ExecStop=-/usr/bin/systemctl --user unset-environment XMODIFIERS +ExecStop=-/usr/bin/systemctl --user unset-environment SDL_IM_MODULE +ExecStop=-/usr/bin/systemctl --user unset-environment QT_IM_MODULES +ExecStop=-/usr/bin/systemctl --user unset-environment QT_IM_MODULE +ExecStop=-/usr/bin/systemctl --user unset-environment WAYLAND_DISPLAY +Slice=session.slice +RestartSec=1s diff --git a/misc/systemd/dde-session-pre.target.wants/treeland-sd.socket b/misc/systemd/dde-session-pre.target.wants/treeland-sd.socket new file mode 100644 index 0000000000..d45ec91026 --- /dev/null +++ b/misc/systemd/dde-session-pre.target.wants/treeland-sd.socket @@ -0,0 +1,12 @@ +[Unit] +Description=User Compositor Socket +PartOf=treeland-sd.service + +Requisite=dde-session-pre.target +PartOf=dde-session-pre.target +Before=dde-session-pre.target + +[Socket] +ListenStream=%t/treeland.socket +RemoveOnStop=true +FileDescriptorName=Treeland diff --git a/misc/systemd/dde-session-pre.target.wants/treeland-xwayland.service.in b/misc/systemd/dde-session-pre.target.wants/treeland-xwayland.service.in new file mode 100644 index 0000000000..c84e4e4132 --- /dev/null +++ b/misc/systemd/dde-session-pre.target.wants/treeland-xwayland.service.in @@ -0,0 +1,24 @@ +[Unit] +Description=Treeland socket helper service +CollectMode=inactive-or-failed + +Requires=treeland-xwayland.socket +PartOf=treeland-xwayland.socket +After=treeland-xwayland.socket + +Before=dde-display.service + +Requisite=dde-session-pre.target +PartOf=dde-session-pre.target +Before=dde-session-pre.target + +[Service] +ExecCondition=/bin/sh -c 'test "$XDG_SESSION_DESKTOP" = "Treeland" || exit 2' +Type=notify +Sockets=treeland-xwayland.socket +UnsetEnvironment=DISPLAY +ExecStart=@CMAKE_INSTALL_FULL_LIBEXECDIR@/treeland-sd --type xwayland +ExecStop=-/usr/bin/systemctl --user unset-environment DISPLAY +Restart=on-failure +RestartSec=3s +Slice=session.slice diff --git a/misc/systemd/dde-session-pre.target.wants/treeland-xwayland.socket b/misc/systemd/dde-session-pre.target.wants/treeland-xwayland.socket new file mode 100644 index 0000000000..3f194dcdf7 --- /dev/null +++ b/misc/systemd/dde-session-pre.target.wants/treeland-xwayland.socket @@ -0,0 +1,12 @@ +[Unit] +Description=User XWayland Socket +PartOf=treeland-xwayland.service + +Requisite=dde-session-pre.target +PartOf=dde-session-pre.target +Before=dde-session-pre.target + +[Socket] +ListenStream=%t/treeland-xwayland +RemoveOnStop=true +FileDescriptorName=Treeland-Xwayland diff --git a/misc/systemd/dde-session-pre.target.wants/treeland.service.in b/misc/systemd/dde-session-pre.target.wants/treeland.service.in new file mode 100644 index 0000000000..49c10cfea8 --- /dev/null +++ b/misc/systemd/dde-session-pre.target.wants/treeland.service.in @@ -0,0 +1,45 @@ +[Unit] +Description=Treeland session service +StartLimitBurst=60 +CollectMode=inactive-or-failed + +Wants=treeland-sd.socket +After=treeland-sd.socket + +Wants=treeland-sd.service +Before=treeland-sd.service + +@TREELAND_SHORTCUT_SERVICE_DEPS@ + +Requisite=dde-session-pre.target +PartOf=dde-session-pre.target +Before=dde-session-pre.target + +[Service] +ExecCondition=/bin/sh -c 'test "$TREELAND_RUN_MODE" = "user" || exit 2' +Type=dbus +BusName=org.deepin.Compositor1 +UnsetEnvironment=DISPLAY +UnsetEnvironment=WAYLAND_DISPLAY +ExecStart=@CMAKE_INSTALL_FULL_BINDIR@/treeland +ExecStartPost=-/usr/bin/systemctl --user set-environment XDG_SESSION_DESKTOP=Treeland +ExecStop=-/usr/bin/systemctl --user unset-environment XDG_SESSION_DESKTOP +Slice=session.slice +Restart=on-failure +RestartSec=1s + +NoNewPrivileges=true +OOMScoreAdjust=-300 +Nice=-15 +# Enable MemoryDenyWriteExecute will cause Treeland crash in certain +# condition (observed on arm64 virtual machine). The coredump indicate +# that it happened in libgallium.so, which is involved by +# qwoutput->commit_state() call inside Output::enable(). +# +# MemoryDenyWriteExecute=true +# Failed to set up mount namespacing: /dev/mqueue: Operation not permitted +# PrivateIPC=true +# [xwayland/sockets.c:100] /tmp/.X11-unix not owned by root or us +# ProtectSystem=full +ProtectProc=invisible +RestrictSUIDSGID=true diff --git a/misc/systemd/dde-session-shutdown.target.wants/treeland-session-shutdown.service b/misc/systemd/dde-session-shutdown.target.wants/treeland-session-shutdown.service new file mode 100644 index 0000000000..de1559f962 --- /dev/null +++ b/misc/systemd/dde-session-shutdown.target.wants/treeland-session-shutdown.service @@ -0,0 +1,10 @@ +[Unit] +Description=Treeland shutdown session service + +[Service] +ExecCondition=/bin/sh -c 'test "$TREELAND_RUN_MODE" = "user" || exit 2' +Type=oneshot +ExecStart=/usr/bin/systemctl --user unset-environment XDG_SESSION_DESKTOP +ExecStart=/usr/bin/systemctl --user unset-environment DESKTOP_SESSION +ExecStart=/usr/bin/systemctl --user unset-environment XDG_SESSION_TYPE +ExecStart=/usr/bin/systemctl --user unset-environment TREELAND_RUN_MODE diff --git a/misc/systemd/remove-xwayland-units.cmake.in b/misc/systemd/remove-xwayland-units.cmake.in new file mode 100644 index 0000000000..b294cee49a --- /dev/null +++ b/misc/systemd/remove-xwayland-units.cmake.in @@ -0,0 +1,11 @@ +# Remove only files installed by the Xwayland-enabled build. Preserve user +# overrides in /etc and honor staging so package builds never touch the host. +foreach(relative_path IN ITEMS + treeland.service.d/xwayland.conf + treeland-xwayland.service + treeland-xwayland.socket + dde-session-pre.target.wants/treeland-xwayland.service + dde-session-pre.target.wants/treeland-xwayland.socket +) + file(REMOVE "$ENV{DESTDIR}@SYSTEMD_USER_UNIT_DIR@/${relative_path}") +endforeach() diff --git a/misc/systemd/treeland-screensaver.service.in b/misc/systemd/treeland-screensaver.service.in new file mode 100644 index 0000000000..ef237be40c --- /dev/null +++ b/misc/systemd/treeland-screensaver.service.in @@ -0,0 +1,18 @@ +[Unit] +Description=Treeland ScreenSaver D-Bus Service +CollectMode=inactive-or-failed + +PartOf=dde-session-pre.target +Before=dde-session-pre.target + +Requisite=treeland-sd.service +After=treeland-sd.service + +[Service] +ExecCondition=/bin/sh -c 'test "$XDG_SESSION_DESKTOP" = "Treeland" || exit 2' +Type=dbus +BusName=org.freedesktop.ScreenSaver +ExecStart=@CMAKE_INSTALL_FULL_LIBEXECDIR@/treeland-screensaver +Slice=session.slice +Restart=on-failure +RestartSec=1s diff --git a/misc/systemd/treeland-session-helper.service.in b/misc/systemd/treeland-session-helper.service.in new file mode 100644 index 0000000000..81c23ed07f --- /dev/null +++ b/misc/systemd/treeland-session-helper.service.in @@ -0,0 +1,18 @@ +[Unit] +Description=Treeland Session Helper +CollectMode=inactive-or-failed + +PartOf=dde-session-pre.target +Before=dde-session-pre.target + +Requisite=treeland-sd.service +After=treeland-sd.service + +[Service] +ExecCondition=/bin/sh -c 'test "$XDG_SESSION_DESKTOP" = "Treeland" || exit 2' +Type=simple +ExecStart=@CMAKE_INSTALL_FULL_LIBEXECDIR@/treeland-session-helper +Slice=session.slice +Restart=on-failure +RestartSec=1s + diff --git a/misc/systemd/treeland.service.d/xwayland.conf b/misc/systemd/treeland.service.d/xwayland.conf new file mode 100644 index 0000000000..96216ac80e --- /dev/null +++ b/misc/systemd/treeland.service.d/xwayland.conf @@ -0,0 +1,3 @@ +[Unit] +Wants=treeland-xwayland.service +Before=treeland-xwayland.service diff --git a/misc/systemd/treeland.service.in b/misc/systemd/treeland.service.in new file mode 100644 index 0000000000..4be3c6565d --- /dev/null +++ b/misc/systemd/treeland.service.in @@ -0,0 +1,70 @@ +[Unit] +Description=Treeland global wayland compositor service, only running on DDM. +PartOf=graphical.target +StartLimitIntervalSec=30 +StartLimitBurst=2 + +Requires=dde-seatd.service +After=dde-seatd.service + +[Service] +User=dde +# The debug socket lives in a directory of its own: its no-auth window widens that +# directory to 0711, which must never be %t/treeland -- Qt requires XDG_RUNTIME_DIR +# to stay 0700 and moves new sessions' wayland sockets to $TMPDIR otherwise. +RuntimeDirectory=treeland treeland-debug +RuntimeDirectoryMode=0700 +Environment="XDG_RUNTIME_DIR=%t/treeland" +Environment=LIBSEAT_BACKEND=seatd +Environment=SEATD_SOCK=/run/dde-seatd.sock +Environment=DSG_APP_ID=org.deepin.dde.treeland +Environment=ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolizer +# For Debug: if enable asan, you can't get it's log from journalctl, so ensure the log to a file +Environment=ASAN_OPTIONS=log_path=/tmp/treeland-asan:detect_leaks=0:abort_on_error=1:symbolize=1 +Environment=DDM_DISPLAY_MANAGER=1 +Environment=TREELAND_INPUT_ENHANCE=1 +# Kill orphaned Xwayland processes from previous treeland instance. +# When treeland crashes, its Xwayland child processes may become orphans +# because the cleanup code in Session::~Session() is not executed. +ExecStartPre=-/usr/bin/pkill -9 -u dde -f '^Xwayland[[:space:]]+:[0-9]+' +ExecStart=@CMAKE_INSTALL_FULL_BINDIR@/treeland.sh --lockscreen +Restart=on-failure +RestartSec=1s +# Disable logs from treeland.sh to avoid duplicate entries in journalctl +# since exec replaces the process, logs would appear from both treeland.sh and treeland +StandardOutput=null +StandardError=null + +# NoNewPrivileges must stay false: treeland runs as user dde and the +# NVIDIA driver relies on the setuid bit of nvidia-modprobe to +# auto-create /dev/nvidia* nodes on demand. With NoNewPrivileges=true +# the setuid bit is dropped, EGL init fails and treeland falls back to +# software rendering. +NoNewPrivileges=false +OOMScoreAdjust=-1000 +Nice=-20 +CPUWeight=10000 +CPUSchedulingPolicy=rr +CPUSchedulingPriority=20 +IOWeight=10000 +IOSchedulingClass=realtime +IOSchedulingPriority=0 + +# Enable MemoryDenyWriteExecute will cause Treeland crash in certain +# condition (observed on arm64 virtual machine). The coredump indicate +# that it happened in libgallium.so, which is involved by +# qwoutput->commit_state() call inside Output::enable(). +# +# TODO: check if it is an internal mistake that used W^X memory there. +# +# MemoryDenyWriteExecute=true + +PrivateIPC=false +AmbientCapabilities=CAP_IPC_OWNER +ProtectSystem=full +ProtectHome=true +ProtectClock=true +ProtectProc=invisible +ProtectKernelTunables=true +ProtectKernelModules=true +RestrictSUIDSGID=true diff --git a/misc/wayland-sessions/CMakeLists.txt b/misc/wayland-sessions/CMakeLists.txt new file mode 100644 index 0000000000..0fa43fa9d6 --- /dev/null +++ b/misc/wayland-sessions/CMakeLists.txt @@ -0,0 +1,18 @@ +configure_file(treeland-user.desktop.in treeland-user.desktop) +configure_file(treeland.desktop.in treeland.desktop) +configure_file(treeland-user-wrapper.in treeland-user-wrapper) + +install(FILES + ${CMAKE_CURRENT_BINARY_DIR}/treeland.desktop + DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/wayland-sessions" +) + +install(FILES + ${CMAKE_CURRENT_BINARY_DIR}/treeland-user.desktop + DESTINATION "${CMAKE_INSTALL_DATAROOTDIR}/wayland-sessions" +) + +install(PROGRAMS + ${CMAKE_CURRENT_BINARY_DIR}/treeland-user-wrapper + DESTINATION "${CMAKE_INSTALL_BINDIR}" +) diff --git a/misc/wayland-sessions/treeland-user-wrapper.in b/misc/wayland-sessions/treeland-user-wrapper.in new file mode 100644 index 0000000000..7ece7d78f9 --- /dev/null +++ b/misc/wayland-sessions/treeland-user-wrapper.in @@ -0,0 +1,5 @@ +#!/bin/bash + +export TREELAND_RUN_MODE=user + +exec ${CMAKE_INSTALL_FULL_BINDIR}/dde-session diff --git a/misc/wayland-sessions/treeland-user.desktop.in b/misc/wayland-sessions/treeland-user.desktop.in new file mode 100644 index 0000000000..48e35d3388 --- /dev/null +++ b/misc/wayland-sessions/treeland-user.desktop.in @@ -0,0 +1,7 @@ +[Desktop Entry] +Name=Treeland User +Comment=This session is DDE single wayland +Exec=${CMAKE_INSTALL_FULL_BINDIR}/treeland-user-wrapper +TryExec=${CMAKE_INSTALL_FULL_BINDIR}/treeland +Type=Application +DesktopNames=Treeland diff --git a/misc/wayland-sessions/treeland.desktop.in b/misc/wayland-sessions/treeland.desktop.in new file mode 100644 index 0000000000..776dba5237 --- /dev/null +++ b/misc/wayland-sessions/treeland.desktop.in @@ -0,0 +1,9 @@ +[Desktop Entry] +Name=Treeland +Comment=This session is a single wayland +Exec=${CMAKE_INSTALL_FULL_BINDIR}/dde-session +TryExec=${CMAKE_INSTALL_FULL_BINDIR}/dde-session +Type=Application +DesktopNames=Treeland +Hidden=true +X-DDE-SINGLE-WAYLAND=true diff --git a/nix/default.nix b/nix/default.nix new file mode 100644 index 0000000000..904a3d820f --- /dev/null +++ b/nix/default.nix @@ -0,0 +1,116 @@ +{ + stdenv, + lib, + nix-filter, + cmake, + ninja, + extra-cmake-modules, + pkg-config, + wayland-scanner, + qttools, + wrapQtAppsHook, + qtbase, + qtdeclarative, + qtimageformats, + qtwayland, + qtsvg, + ddm, + deepin, + wayland, + wayland-protocols, + wlr-protocols, + treeland-protocols, + pixman, + pam, + libxcrypt, + libinput, + nixos-artwork, + waylib, +}: + +stdenv.mkDerivation (finalAttrs: { + pname = "treeland"; + version = "0.8.17"; + + src = nix-filter.lib.filter { + root = ./..; + + exclude = [ + ".git" + "debian" + "LICENSES" + "README.md" + "README.zh_CN.md" + (nix-filter.lib.matchExt "nix") + ]; + }; + + postPatch = '' + for file in $(grep -rl "/usr/share/wallpapers/deepin/desktop.jpg") + do + substituteInPlace $file \ + --replace-fail "/usr/share/wallpapers/deepin/desktop.jpg" \ + "${nixos-artwork.wallpapers.simple-blue}/share/backgrounds/nixos/nix-wallpaper-simple-blue.png" + done + ''; + + depsBuildBuild = [ pkg-config ]; + + nativeBuildInputs = [ + cmake + ninja + extra-cmake-modules + pkg-config + wayland-scanner + qttools + wrapQtAppsHook + ]; + + buildInputs = [ + qtbase + qtdeclarative + qtimageformats + qtwayland + qtsvg + ddm + deepin.dtk6core + deepin.dtk6declarative + deepin.dtk6systemsettings + wayland + wayland-protocols + wlr-protocols + treeland-protocols + pixman + pam + libxcrypt + libinput + waylib + ]; + + cmakeFlags = [ + (lib.cmakeFeature "QT_IMPORTS_DIR" "${placeholder "out"}/${qtbase.qtQmlPrefix}") + (lib.cmakeFeature "CMAKE_INSTALL_SYSCONFDIR" "${placeholder "out"}/etc") + (lib.cmakeFeature "SYSTEMD_SYSTEM_UNIT_DIR" "${placeholder "out"}/lib/systemd/system") + (lib.cmakeFeature "SYSTEMD_SYSUSERS_DIR" "${placeholder "out"}/lib/sysusers.d") + (lib.cmakeFeature "SYSTEMD_TMPFILES_DIR" "${placeholder "out"}/lib/tmpfiles.d") + (lib.cmakeFeature "DBUS_CONFIG_DIR" "${placeholder "out"}/share/dbus-1/system.d") + (lib.cmakeBool "WITH_SUBMODULE_WAYLIB" false) + ]; + + env.PKG_CONFIG_SYSTEMD_SYSTEMDUSERUNITDIR = "${placeholder "out"}/lib/systemd/user"; + + # RPATH of binary /nix/store/.../bin/... contains a forbidden reference to /build/ + noAuditTmpdir = true; + + meta = { + description = "Wayland compositor based on wlroots and QtQuick"; + homepage = "https://github.com/linuxdeepin/treeland"; + license = with lib.licenses; [ + gpl3Only + lgpl3Only + asl20 + ]; + platforms = lib.platforms.linux; + maintainers = with lib.maintainers; [ rewine ]; + }; +}) diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000000..74ea94844f --- /dev/null +++ b/renovate.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": [ + "config:recommended" + ], + "lockFileMaintenance": { + "enabled": true, + "extends": [ + "schedule:daily" + ] + }, + "nix": { + "enabled": true + }, + "git-submodules": { + "enabled": true + } +} diff --git a/scripts/pre-commit.sh b/scripts/pre-commit.sh new file mode 100755 index 0000000000..85a4f2519d --- /dev/null +++ b/scripts/pre-commit.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +# +# Pre-commit hook: check staged C/C++ files with git-clang-format +# Only checks the staged diff rather than the entire file for efficiency. +# +# Installation: +# 1. Manual: ln -sf ../../scripts/pre-commit.sh .git/hooks/pre-commit +# 2. (Legacy) CMake configure — the script is retained as a local +# convenience; enforcement is handled by the clang-format CI +# workflow on every push / pull request. + +set -e + +cd "$(git rev-parse --show-toplevel)" + +# Verify git-clang-format is available +if ! command -v git-clang-format &> /dev/null; then + echo "Warning: git-clang-format not found — format check skipped." + echo " Formatting is still enforced by CI on every push / pull request." + exit 0 +fi + +# Verify .clang-format configuration exists +if [[ ! -f .clang-format ]]; then + echo "ERROR: .clang-format configuration file not found." + exit 1 +fi + +# Capture exit code so real tool failures are not masked. +rc=0 +output=$(git clang-format --staged --extensions 'c,h,cpp,cc,cxx' --diff 2>&1) || rc=$? + +if [[ $rc -ne 0 ]]; then + echo "ERROR: git-clang-format failed (exit code ${rc})." + echo "" + echo "${output}" + exit 1 +fi + +# Determine whether formatting is needed +if [[ "$output" == *"no modified files to format"* ]]; then exit 0; fi +if [[ "$output" == *"clang-format did not modify any files"* ]]; then exit 0; fi +if [[ -z "$output" ]]; then exit 0; fi + +echo "ERROR: Unformatted code detected. Please format first:" +echo "" +echo " git clang-format --staged --extensions 'c,h,cpp,cc,cxx' # format staged changes" +echo " git clang-format --staged --extensions 'c,h,cpp,cc,cxx' --diff # preview format diff" +echo "" +echo "Skip check (not recommended): git commit --no-verify" +exit 1 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000000..012388665a --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,595 @@ +if(QT_KNOWN_POLICY_QTP0001) + qt_policy(SET QTP0001 NEW) + # the RESOURCE_PREFIX argument for qt_add_qml_module() defaults to ":/qt/qml/" +endif() +if(POLICY CMP0071) + # https://cmake.org/cmake/help/latest/policy/CMP0071.html + cmake_policy(SET CMP0071 NEW) +endif() + +# Include translation utilities +include(${CMAKE_SOURCE_DIR}/cmake/TranslationUtils.cmake) + +find_package(Dtk6 REQUIRED COMPONENTS Core Declarative SystemSettings Tools) +if (NOT DISABLE_DDM) + find_package(DDM 0.5.0 REQUIRED COMPONENTS Common) +endif() +find_package(QT NAMES Qt6 COMPONENTS Core REQUIRED) +find_package(Qt6 CONFIG REQUIRED ShaderTools Concurrent RemoteObjects Network) +find_package(Qt6 COMPONENTS Quick QuickControls2 REQUIRED) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS QuickPrivate QuickTemplates2Private) +endif() +pkg_search_module(PIXMAN REQUIRED IMPORTED_TARGET pixman-1) +pkg_search_module(WAYLAND REQUIRED IMPORTED_TARGET wayland-server) +pkg_search_module(LIBINPUT REQUIRED IMPORTED_TARGET libinput) +pkg_search_module(XCB REQUIRED IMPORTED_TARGET xcb) +if (NOT DISABLE_XWAYLAND) + pkg_search_module(XCB_RANDR REQUIRED IMPORTED_TARGET xcb-randr) +endif() +pkg_check_modules(PAM REQUIRED IMPORTED_TARGET pam) +pkg_check_modules(Systemd REQUIRED IMPORTED_TARGET libsystemd) +# qt_finalize_target will collect all executable's private dependencies that are CMake targets + +configure_file("common/constants.h.in" "common/constants.h" IMMEDIATE @ONLY) + +set_source_files_properties("${CMAKE_SOURCE_DIR}/misc/interfaces/org.freedesktop.DisplayManager.xml" PROPERTIES + NO_NAMESPACE ON + CLASSNAME DisplayManager +) +set_source_files_properties("${CMAKE_SOURCE_DIR}/misc/interfaces/org.freedesktop.DisplayManager.Seat.xml" PROPERTIES + NO_NAMESPACE ON + CLASSNAME DisplaySeat +) + +set_source_files_properties("${CMAKE_SOURCE_DIR}/misc/interfaces/org.freedesktop.DisplayManager.Session.xml" PROPERTIES + NO_NAMESPACE ON + CLASSNAME DisplaySession +) + +set_source_files_properties("${CMAKE_SOURCE_DIR}/misc/interfaces/org.freedesktop.login1.Manager.xml" PROPERTIES + INCLUDE "loginddbustypes.h" +) +set_source_files_properties("${CMAKE_SOURCE_DIR}/misc/interfaces/org.freedesktop.login1.Seat.xml" PROPERTIES + INCLUDE "loginddbustypes.h" +) + +set_source_files_properties("${CMAKE_SOURCE_DIR}/misc/interfaces/org.freedesktop.login1.Session.xml" PROPERTIES + INCLUDE "loginddbustypes.h" +) + +set_source_files_properties("${CMAKE_SOURCE_DIR}/misc/interfaces/org.freedesktop.login1.User.xml" PROPERTIES + INCLUDE "loginddbustypes.h" +) + +qt_add_dbus_interface(DDM_DBUS_SOURCES "${CMAKE_SOURCE_DIR}/misc/interfaces/org.freedesktop.DisplayManager.xml" DisplayManager) +qt_add_dbus_interface(DDM_DBUS_SOURCES "${CMAKE_SOURCE_DIR}/misc/interfaces/org.freedesktop.DisplayManager.Seat.xml" DisplayManagerSeat) +qt_add_dbus_interface(DDM_DBUS_SOURCES "${CMAKE_SOURCE_DIR}/misc/interfaces/org.freedesktop.DisplayManager.Session.xml" DisplayManagerSession) +qt_add_dbus_interface(DDM_DBUS_SOURCES "${CMAKE_SOURCE_DIR}/misc/interfaces/org.deepin.DisplayManager.xml" DDMDisplayManager) +qt_add_dbus_interface(DBUS_INTERFACE "${CMAKE_SOURCE_DIR}/misc/interfaces/org.freedesktop.login1.Manager.xml" Login1Manager) +qt_add_dbus_interface(DBUS_INTERFACE "${CMAKE_SOURCE_DIR}/misc/interfaces/org.freedesktop.login1.Seat.xml" Login1Seat) +qt_add_dbus_interface(DBUS_INTERFACE "${CMAKE_SOURCE_DIR}/misc/interfaces/org.freedesktop.login1.Session.xml" Login1Session) +qt_add_dbus_interface(DBUS_INTERFACE "${CMAKE_SOURCE_DIR}/misc/interfaces/org.freedesktop.login1.User.xml" Login1User) + +dtk_add_config_to_cpp( + TREELAND_CONFIG + "${PROJECT_SOURCE_DIR}/misc/dconfig/org.deepin.dde.treeland.json" + OUTPUT_FILE_NAME "treelandconfig.hpp" + CLASS_NAME "TreelandConfig" +) + +dtk_add_config_to_cpp( + TREELAND_USER_CONFIG + "${PROJECT_SOURCE_DIR}/misc/dconfig/org.deepin.dde.treeland.user.json" + OUTPUT_FILE_NAME "treelanduserconfig.hpp" + CLASS_NAME "TreelandUserConfig" +) + +dtk_add_config_to_cpp( + ANIMATION_CONFIG + "${PROJECT_SOURCE_DIR}/misc/dconfig/org.deepin.dde.treeland.animation.json" + OUTPUT_FILE_NAME "animationconfig.hpp" + CLASS_NAME "AnimationConfig" +) + +dtk_add_config_to_cpp( + OUTPUT_CONFIG + "${PROJECT_SOURCE_DIR}/misc/dconfig/org.deepin.dde.treeland.output.json" + OUTPUT_FILE_NAME "outputconfig.hpp" + CLASS_NAME "OutputConfig" +) + +dtk_add_config_to_cpp( + SEAT_USER_CONFIG + "${PROJECT_SOURCE_DIR}/misc/dconfig/org.deepin.dde.treeland.user.seat.json" + OUTPUT_FILE_NAME "seatuserconfig.hpp" + CLASS_NAME "SeatUserDConfig" +) + +dtk_add_config_to_cpp( + APP_CONFIG + "${PROJECT_SOURCE_DIR}/misc/dconfig/org.deepin.dde.treeland.app.json" + OUTPUT_FILE_NAME "appconfig.hpp" + CLASS_NAME "AppConfig" +) + +qt_add_library(libtreeland SHARED) +target_compile_definitions(libtreeland PUBLIC + $<$:DISABLE_XWAYLAND> +) + +set_target_properties(libtreeland PROPERTIES + OUTPUT_NAME "treeland" + VERSION ${CMAKE_PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} +) + +# PopoverStyle is a singleton +set_source_files_properties(core/qml/PopoverStyle.qml + PROPERTIES QT_QML_SINGLETON_TYPE TRUE +) + +qt_add_qml_module(libtreeland + URI Treeland + VERSION "2.0" + IMPORTS Waylib.Server + + SOURCES + ${DDM_DBUS_SOURCES} + ${DBUS_INTERFACE} + ${TREELAND_CONFIG} + ${TREELAND_USER_CONFIG} + ${ANIMATION_CONFIG} + ${OUTPUT_CONFIG} + ${APP_CONFIG} + ${SEAT_USER_CONFIG} + capture/capturemanager.cpp + capture/capturemanager.h + common/treelandlogging.cpp + common/treelandlogging.h + common/shellaction.cpp + common/shellaction.h + common/windowdecorations.h + dconfig/dconfigmanager.cpp + dconfig/dconfigmanager.h + core/layersurfacecontainer.cpp + core/layersurfacecontainer.h + core/qmlengine.cpp + core/qmlengine.h + core/rootsurfacecontainer.cpp + core/rootsurfacecontainer.h + core/imcandidatepanelmanager.cpp + core/imcandidatepanelmanager.h + core/shellhandler.cpp + core/shellhandler.h + core/treelandinit.cpp + core/waylandserver.cpp + core/waylandserver.h + core/focuscontroller.cpp + core/focuscontroller.h + lockscreen/lockscreenmanager.cpp + lockscreen/lockscreenmanager.h + core/surfaceprotocolcontroller.cpp + core/surfaceprotocolcontroller.h + core/treeland.cpp + core/treeland.h + core/windowconfigstore.cpp + core/windowconfigstore.h + $<$>,$>:lockscreen/lockscreen.h> + $<$>,$>:lockscreen/lockscreen.cpp> + $<$>:greeter/greeterproxy.cpp> + $<$>:greeter/greeterproxy.h> + $<$>:greeter/loginstatequery.cpp> + $<$>:greeter/loginstatequery.h> + $<$>:greeter/sessionmodel.cpp> + $<$>:greeter/sessionmodel.h> + $<$>:greeter/user.cpp> + $<$>:greeter/user.h> + $<$>:greeter/usermodel.cpp> + $<$>:greeter/usermodel.h> + idle/idlemanager.cpp + idle/idlemanager.h + input/gesturemanager.cpp + input/gesturemanager.h + input/gestures.cpp + input/gestures.h + input/swipegesture.cpp + input/swipegesture.h + input/holdgesture.cpp + input/holdgesture.h + input/gesturerecognizer.cpp + input/gesturerecognizer.h + input/libinputconfig.cpp + input/libinputconfig.h + input/togglablegesture.cpp + input/togglablegesture.h + input/compositorinputfilter.cpp + input/inputcontext.h + input/compositorinputfilter.h + input/inputmanager.cpp + input/inputmanager.h + interfaces/baseplugininterface.h + interfaces/lockscreeninterface.h + interfaces/multitaskviewinterface.h + interfaces/plugininterface.h + interfaces/proxyinterface.h + interfaces/windowtransition.h + modules/resource/treelandremotesource.cpp + modules/resource/treelandremotesource.h + modules/resource/treelanddebugsocket.cpp + modules/resource/treelanddebugsocket.h + output/output.cpp + output/output.h + output/backlight.h + output/backlight.cpp + output/outputmanager.cpp + output/outputmanager.h + seat/dragcontroller.cpp + seat/dragcontroller.h + seat/pointerconstraintsmanager.cpp + seat/pointerconstraintsmanager.h + seat/seatmanager.cpp + seat/seatmanager.h + showdesktop/showdesktop.cpp + showdesktop/showdesktop.h + session/sessionseatmanager.cpp + session/sessionseatmanager.h + desktop/desktopenvironment.cpp + desktop/desktopenvironment.h + session/session.cpp + session/session.h + session/sessionmanager.cpp + session/sessionmanager.h + session/sessionprotocols.cpp + session/sessionprelaunch.cpp + session/sessionprelaunch.h + session/sessionprotocols.h + session/toplevelcapturesource.cpp + session/toplevelcapturesource.h + session/toplevelcaptureviewport.cpp + session/toplevelcaptureviewport.h + session/sessioncomponent.cpp + session/sessioncomponent.h + session/sessionworkspace.cpp + session/sessionworkspace.h + session/sessionmultitaskview.cpp + session/sessionmultitaskview.h + session/sessionscene.cpp + session/sessionscene.h + session/sessionswitcher.cpp + session/sessionswitcher.h + session/sessioninputchannel.cpp + session/sessioninputchannel.h + session/sessioninputcontext.cpp + session/sessioninputcontext.h + session/sessionoutputchannel.cpp + session/sessionoutputchannel.h + session/sessionoutputmanager.cpp + session/sessionoutputmanager.h + surface/framegeometry.cpp + surface/framegeometry.h + surface/frameinputmask.cpp + surface/frameinputmask.h + surface/surfacecontainer.cpp + surface/surfacecontainer.h + surface/seatsurfacemanager.cpp + surface/seatsurfacemanager.h + surface/surfacefilterproxymodel.cpp + surface/surfacefilterproxymodel.h + surface/surfaceproxy.cpp + surface/surfaceproxy.h + surface/surfacewrapper.cpp + surface/surfacewrapper.h + surface/surfacewindowtransition.cpp + surface/surfacewindowtransition.h + utils/cmdline.cpp + utils/cmdline.h + utils/propertymonitor.cpp + utils/propertymonitor.h + utils/loginddbustypes.h + utils/loginddbustypes.cpp + utils/fpsdisplaymanager.cpp + utils/fpsdisplaymanager.h + utils/graphicsplatform.cpp + utils/graphicsplatform.h + utils/scriptrunner.cpp + utils/scriptrunner.h + wallpaper/wallpapersurface.h + wallpaper/wallpapersurface.cpp + wallpaper/wallpaperitem.cpp + wallpaper/wallpaperitem.h + wallpaper/wallpapermanager.cpp + wallpaper/wallpapermanager.h + wallpaper/wallpaperconfig.h + wallpaper/wallpaperconfig.cpp + wallpaper/wallpaperlauncher.h + wallpaper/wallpaperlauncher.cpp + wallpaper/wallpaperswitcheritem.cpp + wallpaper/wallpaperswitcheritem.h + workspace/workspace.cpp + workspace/workspace.h + workspace/workspaceanimationcontroller.cpp + workspace/workspaceanimationcontroller.h + workspace/workspacemodel.cpp + workspace/workspacemodel.h + $<$>:xsettings/abstractsettings.h> + $<$>:xsettings/abstractsettings.cpp> + $<$>:xsettings/xsettings.h> + $<$>:xsettings/xsettings.cpp> + $<$>:xsettings/xresource.h> + $<$>:xsettings/xresource.cpp> + $<$>:xsettings/settingmanager.h> + $<$>:xsettings/settingmanager.cpp> + + QML_FILES + core/qml/SourceOutput.qml + core/qml/MirrorOutput.qml + core/qml/TitleBar.qml + core/qml/Decoration.qml + core/qml/FrameClip.qml + core/qml/WindowMenu.qml + core/qml/TaskBar.qml + core/qml/SurfaceContent.qml + core/qml/CaptureSurfaceContent.qml + core/qml/XdgShadow.qml + core/qml/Border.qml + core/qml/OutputMenuBar.qml + core/qml/WorkspaceSwitcher.qml + core/qml/WorkspaceProxy.qml + core/qml/FpsDisplay.qml + core/qml/Animations/GeometryAnimation.qml + core/qml/Animations/WindowTransition.qml + core/qml/Animations/NewAnimation.qml + core/qml/Animations/MinimizeAnimation.qml + core/qml/Animations/ShowDesktopAnimation.qml + core/qml/Animations/LaunchpadAnimation.qml + core/qml/Animations/LayerShellAnimation.qml + core/qml/Effects/Blur.qml + core/qml/Effects/+vulkan/Blur.qml + core/qml/Effects/GlassEffect.qml + core/qml/Effects/LaunchpadCover.qml + core/qml/TaskSwitcher.qml + core/qml/TaskWindowPreview.qml + core/qml/SwitchViewDelegate.qml + core/qml/SwitchViewHighlightDelegate.qml + core/qml/PopoverStyle.qml + core/qml/DockPreview.qml + core/qml/DockPreview/DockPreviewCloseButton.qml + core/qml/DockPreview/DockPreviewListLayer.qml + core/qml/DockPreview/DockPreviewListPresent.qml + core/qml/DockPreview/DockPreviewListRow.qml + core/qml/DockPreview/DockPreviewScrollHint.qml + core/qml/DockPreview/DockPreviewSlot.qml + core/qml/DockPreview/DockPreviewSurface.qml + core/qml/DockPreview/DockPreviewThumbnailPresent.qml + core/qml/DockPreview/DockPreviewTooltipLayer.qml + core/qml/DockPreview/DockPreviewTooltipPresent.qml + core/qml/FadeBehavior.qml + core/qml/CaptureSelectorLayer.qml + core/qml/EdgeTilePreview.qml + core/qml/LockScreenFallback.qml + core/qml/PrelaunchSplash.qml + RESOURCE_PREFIX + /qt/qml + OUTPUT_DIRECTORY + ${PROJECT_BINARY_DIR}/qt/qml/Treeland +) + +qt_add_repc_sources(libtreeland + modules/resource/treelandwindowtree.rep +) + +target_compile_definitions(libtreeland + PRIVATE + WLR_USE_UNSTABLE + "TREELAND_SYSCONFDIR=\"${TREELAND_SYSCONFDIR}\"" +) + +if (USE_BUILD_TREE_WALLPAPER_FACTORY) + target_compile_definitions(libtreeland + PRIVATE + TREELAND_USE_BUILD_TREE_WALLPAPER_FACTORY + "TREELAND_WALLPAPER_FACTORY_OUTPUT_PATH=\"${CMAKE_BINARY_DIR}/wallpaper-factory/treeland-wallpaper-factory\"" + ) +endif() + + +# Liquid Glass shaders are used with ShaderEffect, not custom QSGGeometry, +# so BATCHABLE is unnecessary (it only adds an unused batchable variant). +qt_add_shaders(libtreeland "treeland_liquidglass_shaders" + PRECOMPILE + OPTIMIZED + PREFIX + "/shaders" + BASE + ${PROJECT_RESOURCES_DIR}/shaders + FILES + ${PROJECT_RESOURCES_DIR}/shaders/liquidglass.vert + ${PROJECT_RESOURCES_DIR}/shaders/liquidglass.frag +) + +# Lock screen wallpaper dimming shader (used with ShaderEffect in the greeter). +# BT.709 luma-adaptive dimming blended in by u_strength. +qt_add_shaders(libtreeland "treeland_wallpaper_luma_dim_shaders" + BATCHABLE + PRECOMPILE + PREFIX + "/shaders" + BASE + ${PROJECT_RESOURCES_DIR}/shaders + FILES + ${PROJECT_RESOURCES_DIR}/shaders/wallpaper_luma_dim.frag +) + +# Cross-fades the icon and the window content of a window transition in a +# single pass, so the two layers never let the desktop through. +qt_add_shaders(libtreeland "treeland_window_transition_shaders" + PRECOMPILE + OPTIMIZED + PREFIX + "/shaders" + BASE + ${PROJECT_RESOURCES_DIR}/shaders + FILES + ${PROJECT_RESOURCES_DIR}/shaders/window_transition.frag +) + +set_source_files_properties(core/qml/overridable/InWindowBlur.qml + PROPERTIES + QT_RESOURCE_ALIAS "+treeland/InWindowBlur.qml" +) +qt_add_resources(libtreeland "override_dtkdeclarative_qml" + PREFIX "/dtk/declarative/qml/overridable" + FILES + core/qml/overridable/InWindowBlur.qml +) + +qt_add_resources(libtreeland "treeland_assets" + PREFIX "/dsg/icons" + BASE ${PROJECT_RESOURCES_DIR}/icons + FILES + ${PROJECT_RESOURCES_DIR}/icons/close.dci + ${PROJECT_RESOURCES_DIR}/icons/add.dci + ${PROJECT_RESOURCES_DIR}/icons/select_output.dci + ${PROJECT_RESOURCES_DIR}/icons/select_window.dci + ${PROJECT_RESOURCES_DIR}/icons/select_region.dci + ${PROJECT_RESOURCES_DIR}/icons/login_capslock.dci + ${PROJECT_RESOURCES_DIR}/icons/login_display_password.dci + ${PROJECT_RESOURCES_DIR}/icons/login_hidden_password.dci + ${PROJECT_RESOURCES_DIR}/icons/login_keyboard.dci + ${PROJECT_RESOURCES_DIR}/icons/login_lock.dci + ${PROJECT_RESOURCES_DIR}/icons/login_open.dci + ${PROJECT_RESOURCES_DIR}/icons/login_power.dci + ${PROJECT_RESOURCES_DIR}/icons/login_reboot.dci + ${PROJECT_RESOURCES_DIR}/icons/login_hibernate.dci + ${PROJECT_RESOURCES_DIR}/icons/login_user.dci + ${PROJECT_RESOURCES_DIR}/icons/login_hint.dci + ${PROJECT_RESOURCES_DIR}/icons/login_logout.dci + ${PROJECT_RESOURCES_DIR}/icons/login_shutdown.dci + ${PROJECT_RESOURCES_DIR}/icons/login_suspend.dci + ${PROJECT_RESOURCES_DIR}/icons/login_switchuser.dci + ${PROJECT_RESOURCES_DIR}/icons/login_update_reboot.dci + ${PROJECT_RESOURCES_DIR}/icons/login_update_shutdown.dci + ${PROJECT_RESOURCES_DIR}/icons/backToLightdm.dci + ${PROJECT_RESOURCES_DIR}/icons/logo.svg +) + +# Use translation utilities to setup main translations +setup_main_translations(libtreeland) + +target_include_directories(libtreeland + PUBLIC + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ +) + +target_link_libraries(libtreeland + PUBLIC + Dtk6::Core + Dtk6::Declarative + Dtk6::SystemSettings + Waylib::WaylibServer + PRIVATE + Qt6::GuiPrivate + Qt6::Quick + Qt6::QuickControls2 + Qt6::QuickPrivate + Qt6::QuickTemplates2Private + Qt6::DBus + Qt6::Concurrent + Qt6::RemoteObjects + Qt6::Network + PkgConfig::PIXMAN + PkgConfig::WAYLAND + PkgConfig::LIBINPUT + PkgConfig::XCB + $<$>:PkgConfig::XCB_RANDR> + $<$>:DDM::Common> + $<$>:PkgConfig::PAM> + $<$>:PkgConfig::Systemd> +) + +add_subdirectory(plugins) +add_subdirectory(modules) +add_subdirectory(treeland-screensaver) + +set(BIN_NAME treeland) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +target_include_directories(${BIN_NAME} PRIVATE + $ + $ +) + +target_link_libraries(${BIN_NAME} PRIVATE + libtreeland + Qt6::GuiPrivate + Qt6::QuickControls2 +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") +install(PROGRAMS treeland.sh DESTINATION "${CMAKE_INSTALL_BINDIR}") +install(TARGETS libtreeland + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + NAMELINK_SKIP +) +if(TREELAND_INSTALL_DEV) + install(TARGETS libtreeland + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + NAMELINK_ONLY + ) + install(FILES + common/shellaction.h + common/windowdecorations.h + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/treeland/common") +endif() + +## systemd socket + +qt_add_executable(treeland-sd + systemd-socket.cpp +) + +target_link_libraries(treeland-sd + PRIVATE + Qt6::DBus + PkgConfig::Systemd +) + +install(TARGETS treeland-sd RUNTIME DESTINATION "${CMAKE_INSTALL_LIBEXECDIR}") + +## XWayland wrapper + +if (NOT DISABLE_XWAYLAND) + pkg_check_modules(LIBXAU REQUIRED IMPORTED_TARGET "xau") + + qt_add_executable(treeland-xwayland + xwayland.cpp + ) + + target_link_libraries(treeland-xwayland + PRIVATE + Qt6::Core + PkgConfig::LIBXAU + ) + + install(TARGETS treeland-xwayland RUNTIME DESTINATION "${CMAKE_INSTALL_LIBEXECDIR}") +endif() diff --git a/src/capture/capturemanager.cpp b/src/capture/capturemanager.cpp new file mode 100644 index 0000000000..99e00669e4 --- /dev/null +++ b/src/capture/capturemanager.cpp @@ -0,0 +1,51 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "capturemanager.h" +#include "core/qmlengine.h" +#include "core/rootsurfacecontainer.h" +#include "modules/capture/capture.h" + +#include +#include + +CaptureManager::CaptureManager(WServer *server, RootSurfaceContainer *root, QObject *parent) + : QObject(parent) + , m_rootSurfaceContainer(root) + , m_server(server) +{} + +CaptureManager::~CaptureManager() +{ + teardown(); +} + +void CaptureManager::installProtocol(QmlEngine *engine, WOutputRenderWindow *window) +{ + m_engine = engine; + m_captureManagerV1 = m_server->attach(); + m_captureManagerV1->setOutputRenderWindow(window); + connect(m_captureManagerV1, &CaptureManagerV1::contextInSelectionChanged, + this, &CaptureManager::onSelectionChanged); +} + +void CaptureManager::onSelectionChanged() +{ + if (m_captureManagerV1->contextInSelection()) { + m_captureSelector = qobject_cast( + m_engine->createCaptureSelector(m_rootSurfaceContainer, m_captureManagerV1)); + } else if (m_captureSelector) { + m_captureSelector->deleteLater(); + } +} + +bool CaptureManager::isSelecting() const +{ + return m_captureSelector; +} + +void CaptureManager::cancelSelection() +{ + if (m_captureSelector) + m_captureSelector->cancelSelection(); +} diff --git a/src/capture/capturemanager.h b/src/capture/capturemanager.h new file mode 100644 index 0000000000..eca9cc0c3b --- /dev/null +++ b/src/capture/capturemanager.h @@ -0,0 +1,44 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include +#include + +class RootSurfaceContainer; +class QmlEngine; +class CaptureSourceSelector; +class CaptureManagerV1; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WServer; +class WOutputRenderWindow; +class WExtForeignToplevelListV1; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class CaptureManager : public QObject, public WObject +{ + Q_OBJECT +public: + CaptureManager(WServer *server, RootSurfaceContainer *root, QObject *parent = nullptr); + ~CaptureManager() override; + + void installProtocol(QmlEngine *engine, WOutputRenderWindow *window); + bool isSelecting() const; + void cancelSelection(); + +private: + void onSelectionChanged(); + +private: + RootSurfaceContainer *m_rootSurfaceContainer; + QmlEngine *m_engine = nullptr; + CaptureManagerV1 *m_captureManagerV1 = nullptr; + WServer *const m_server; + QPointer m_captureSelector; +}; diff --git a/src/common/constants.h.in b/src/common/constants.h.in new file mode 100644 index 0000000000..3c015f83d8 --- /dev/null +++ b/src/common/constants.h.in @@ -0,0 +1 @@ +#define LIBEXEC_DIR "@CMAKE_INSTALL_FULL_LIBEXECDIR@" diff --git a/src/common/shellaction.cpp b/src/common/shellaction.cpp new file mode 100644 index 0000000000..fbcaeb8c15 --- /dev/null +++ b/src/common/shellaction.cpp @@ -0,0 +1,221 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "shellaction.h" + +#include "common/treelandlogging.h" +#include "interfaces/multitaskviewinterface.h" +#include "output/output.h" +#include "core/waylandserver.h" +#include "showdesktop/showdesktop.h" +#include "surface/surfacewrapper.h" +#include "workspace/workspace.h" + +static SurfaceWrapper::TileMode tileModeFor(ShellAction action) +{ + switch (action) { + case ShellAction::TileLeft: + return SurfaceWrapper::TileMode::Left; + case ShellAction::TileRight: + return SurfaceWrapper::TileMode::Right; + case ShellAction::TileTopLeft: + return SurfaceWrapper::TileMode::TopLeft; + case ShellAction::TileTopRight: + return SurfaceWrapper::TileMode::TopRight; + case ShellAction::TileBottomLeft: + return SurfaceWrapper::TileMode::BottomLeft; + case ShellAction::TileBottomRight: + return SurfaceWrapper::TileMode::BottomRight; + default: + return SurfaceWrapper::TileMode::None; + } +} + +void ShellActionExecutor::execute(ShellAction action) +{ + auto *server = WaylandServer::instance(); + + if (server->currentMode() == WaylandServer::CurrentMode::LockScreen) { + return; + } + + switch (action) { + case ShellAction::Invalid: + break; + case ShellAction::SwitchWorkspace1: + case ShellAction::SwitchWorkspace2: + case ShellAction::SwitchWorkspace3: + case ShellAction::SwitchWorkspace4: + case ShellAction::SwitchWorkspace5: + case ShellAction::SwitchWorkspace6: + case ShellAction::SwitchWorkspace7: + case ShellAction::SwitchWorkspace8: + case ShellAction::SwitchWorkspace9: + case ShellAction::SwitchWorkspace10: + case ShellAction::SwitchWorkspace11: + case ShellAction::SwitchWorkspace12: + // switchTo() ignores out-of-range indexes, as the protocol requires. + server->restoreFromShowDesktop(); + server->workspace()->switchTo(static_cast(action) - static_cast(ShellAction::SwitchWorkspace1)); + break; + case ShellAction::PreviousWorkspace: + server->restoreFromShowDesktop(); + server->workspace()->switchToPrev(); + break; + case ShellAction::NextWorkspace: + server->restoreFromShowDesktop(); + server->workspace()->switchToNext(); + break; + case ShellAction::ToggleShowDesktop: + if (server->currentMode() == WaylandServer::CurrentMode::Multitaskview) { + break; + } + if (server->showDesktopState() == ShowDesktop::State::Normal) { + server->setShowDesktopState(ShowDesktop::State::Show); + } else if (server->showDesktopState() == ShowDesktop::State::Show) { + server->setShowDesktopState(ShowDesktop::State::Normal); + } + break; + case ShellAction::OpenMultitaskView: + if (!server->multitaskView() || !server->isNormalOrMultitaskview() + || server->currentMode() == WaylandServer::CurrentMode::Multitaskview) { + break; + } + server->multitaskView()->setStatus(IMultitaskView::Exited); + server->multitaskView()->toggleMultitaskView(IMultitaskView::ActiveReason::ShortcutKey); + break; + case ShellAction::CloseMultitaskView: + if (!server->multitaskView() || !server->isNormalOrMultitaskview() + || server->currentMode() == WaylandServer::CurrentMode::Normal) { + break; + } + server->multitaskView()->setStatus(IMultitaskView::Active); + server->multitaskView()->toggleMultitaskView(IMultitaskView::ActiveReason::ShortcutKey); + break; + case ShellAction::ToggleMultitaskView: + if (!server->multitaskView() || !server->isNormalOrMultitaskview()) { + break; + } + server->restoreFromShowDesktop(); + server->multitaskView()->toggleMultitaskView(IMultitaskView::ActiveReason::ShortcutKey); + break; + case ShellAction::ToggleFpsDisplay: + server->toggleFpsDisplay(); + break; + case ShellAction::ZoomIn: + case ShellAction::ZoomOut: + case ShellAction::ZoomReset: + // TODO: implement screen zoom. + break; + case ShellAction::LockScreen: + // Rejects the transient WindowSwitch mode, where locking would strand + // the task-switch sequence. + if (server->isNormalOrMultitaskview()) + server->showLockScreen(); + break; + case ShellAction::ShowShutdownMenu: + server->showShutdownMenu(); + break; + case ShellAction::ShowShutdownMenuPowerOff: + server->showShutdownMenu(WaylandServer::ShutdownMenuFocus::PowerOff); + break; + case ShellAction::ShowShutdownMenuReboot: + server->showShutdownMenu(WaylandServer::ShutdownMenuFocus::Reboot); + break; + case ShellAction::ShowShutdownMenuSuspend: + server->showShutdownMenu(WaylandServer::ShutdownMenuFocus::Suspend); + break; + case ShellAction::ShowShutdownMenuHibernate: + server->showShutdownMenu(WaylandServer::ShutdownMenuFocus::Hibernate); + break; + case ShellAction::ShowShutdownMenuLogOut: + server->showShutdownMenu(WaylandServer::ShutdownMenuFocus::LogOut); + break; + case ShellAction::ShowUserSwitch: + server->showSwitchUser(); + break; + case ShellAction::Maximize: { + auto *surface = server->activatedSurface(); + if (surface && surface->isMaximizable()) { + surface->maximize(); + } + break; + } + case ShellAction::CancelMaximize: { + auto *surface = server->activatedSurface(); + if (surface) { + surface->unmaximize(); + } + break; + } + case ShellAction::Minimize: { + auto *surface = server->activatedSurface(); + if (surface) { + surface->minimize(); + } + break; + } + case ShellAction::MoveWindow: { + auto *surface = server->activatedSurface(); + if (surface) { + Q_EMIT surface->moveRequested(); + } + break; + } + case ShellAction::CloseWindow: { + auto *surface = server->activatedSurface(); + if (surface) { + surface->closeSurface(); + } + break; + } + case ShellAction::ShowWindowMenu: { + auto *surface = server->activatedSurface(); + if (surface) { + Q_EMIT surface->windowMenuRequested({ 0, 0 }); + } + break; + } + case ShellAction::TileLeft: + case ShellAction::TileRight: + case ShellAction::TileTopLeft: + case ShellAction::TileTopRight: + case ShellAction::TileBottomLeft: + case ShellAction::TileBottomRight: { + auto *surface = server->activatedSurface(); + if (!surface) { + break; + } + auto *output = surface->ownsOutput(); + if (!output) { + break; + } + surface->applyTileMode(tileModeFor(action), output); + break; + } + case ShellAction::MoveWindowToPrevWorkspace: { + auto *surface = server->activatedSurface(); + if (!surface) { + break; + } + const int target = server->workspace()->getLeftWorkspaceId(surface->workspaceId()); + if (target < 0) { + break; + } + server->workspace()->moveSurfaceTo(surface, target); + break; + } + case ShellAction::MoveWindowToNextWorkspace: { + auto *surface = server->activatedSurface(); + if (!surface) { + break; + } + const int target = server->workspace()->getRightWorkspaceId(surface->workspaceId()); + if (target < 0) { + break; + } + server->workspace()->moveSurfaceTo(surface, target); + break; + } + } +} diff --git a/src/common/shellaction.h b/src/common/shellaction.h new file mode 100644 index 0000000000..95e846784c --- /dev/null +++ b/src/common/shellaction.h @@ -0,0 +1,71 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +// ShellAction is the server-neutral vocabulary both treeland-server- +// action-v1 and treeland-shortcut-manager-v2 map their own action enums onto, +// so each action is implemented once. The protocol enums are independent value +// spaces; this enum is the shared translation target. +enum class ShellAction : uint32_t { + // Sentinel so a default-constructed ShellAction{} is never a real action. + Invalid = 0, + + // Contiguous: the workspace index is action - SwitchWorkspace1. + SwitchWorkspace1, + SwitchWorkspace2, + SwitchWorkspace3, + SwitchWorkspace4, + SwitchWorkspace5, + SwitchWorkspace6, + SwitchWorkspace7, + SwitchWorkspace8, + SwitchWorkspace9, + SwitchWorkspace10, + SwitchWorkspace11, + SwitchWorkspace12, + PreviousWorkspace, + NextWorkspace, + ToggleShowDesktop, + OpenMultitaskView, + CloseMultitaskView, + ToggleMultitaskView, + ToggleFpsDisplay, + ZoomIn, + ZoomOut, + ZoomReset, + LockScreen, + ShowShutdownMenu, + ShowShutdownMenuPowerOff, + ShowShutdownMenuReboot, + ShowShutdownMenuSuspend, + ShowShutdownMenuHibernate, + ShowShutdownMenuLogOut, + ShowUserSwitch, + + // Window-level actions (shortcut-manager only); act on activatedSurface(). + Maximize, + CancelMaximize, + Minimize, + MoveWindow, + CloseWindow, + ShowWindowMenu, + TileLeft, + TileRight, + TileTopLeft, + TileTopRight, + TileBottomLeft, + TileBottomRight, + MoveWindowToPrevWorkspace, + MoveWindowToNextWorkspace, +}; + +// Stateless executor: every call re-reads WaylandServer::instance(). Task switching, +// Notify and Quit stay producer-local (they depend on switch/quit state). +class ShellActionExecutor +{ +public: + static void execute(ShellAction action); +}; diff --git a/src/common/treelandlogging.cpp b/src/common/treelandlogging.cpp new file mode 100644 index 0000000000..608e4c5566 --- /dev/null +++ b/src/common/treelandlogging.cpp @@ -0,0 +1,104 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "common/treelandlogging.h" + +// TreeLand logging category definitions +// Naming convention: lcTl + PascalCase module name +// String ID convention: treeland.[.] + +// Core modules +Q_LOGGING_CATEGORY(lcTlCore, "treeland.core", QtInfoMsg) +Q_LOGGING_CATEGORY(lcTlServer, "treeland.server") +Q_LOGGING_CATEGORY(lcTlCompositor, "treeland.compositor") +Q_LOGGING_CATEGORY(lcTlShell, "treeland.shell") +Q_LOGGING_CATEGORY(lcTlQml, "treeland.qml") + +// Input modules +Q_LOGGING_CATEGORY(lcTlInput, "treeland.input") +Q_LOGGING_CATEGORY(lcTlInputManager, "treeland.input.manager") +Q_LOGGING_CATEGORY(lcTlGestures, "treeland.input.gestures") +Q_LOGGING_CATEGORY(lcTlKeyboardNotify, "treeland.input.keyboard.state.notify") + +// Seat management +Q_LOGGING_CATEGORY(lcTlSeat, "treeland.seat") + +// Output module +Q_LOGGING_CATEGORY(lcTlOutput, "treeland.output", QtInfoMsg) + +// Window management +Q_LOGGING_CATEGORY(lcTlSurface, "treeland.surface") + +// Workspace management +Q_LOGGING_CATEGORY(lcTlWorkspace, "treeland.workspace") + +// Protocol module +Q_LOGGING_CATEGORY(lcTlProtocol, "treeland.protocol") + +// Plugin system +Q_LOGGING_CATEGORY(lcTlPlugin, "treeland.plugin") + +// Configuration management +Q_LOGGING_CATEGORY(lcTlConfig, "treeland.config") + +// Wallpaper system +Q_LOGGING_CATEGORY(lcTlWallpaper, "treeland.wallpaper") +Q_LOGGING_CATEGORY(lcTlWallpaperColor, "treeland.wallpaper.color") + +// Effects system +Q_LOGGING_CATEGORY(lcTlEffect, "treeland.effect") + +// Capture system +Q_LOGGING_CATEGORY(lcTlCapture, "treeland.capture") + +// DBus interface +Q_LOGGING_CATEGORY(lcTlDBus, "treeland.dbus") + +// Utility classes +Q_LOGGING_CATEGORY(lcTlUtils, "treeland.utils") +Q_LOGGING_CATEGORY(lcTlPropertyMonitor, "treeland.property.monitor") + +// Shortcut system +Q_LOGGING_CATEGORY(lcTlShortcut, "treeland.shortcut") +Q_LOGGING_CATEGORY(lcTlKeyboardShortcutsInhibit, "treeland.shortcut.inhibit") + +// Greeter module +Q_LOGGING_CATEGORY(lcTlGreeter, "treeland.greeter") + +// FPS display +Q_LOGGING_CATEGORY(lcTlFpsDisplay, "treeland.fps") + +// xsettings +Q_LOGGING_CATEGORY(lcTlXsettings, "treeland.xsettings") + +// Activation module +Q_LOGGING_CATEGORY(lcTlActivation, "treeland.activation") + +// Window transition module +Q_LOGGING_CATEGORY(lcTlWindowTransition, "treeland.window.transition") + +// App ID resolver +Q_LOGGING_CATEGORY(lcTlAppIdResolver, "treeland.appid.resolver", QtInfoMsg) + +// Prelaunch splash +Q_LOGGING_CATEGORY(lcTlPrelaunchSplash, "treeland.prelaunch.splash", QtInfoMsg) + +// Layer shell extension (compositor-driven layer surface resize) +Q_LOGGING_CATEGORY(lcTlLayerShell, "treeland.shell.layer", QtInfoMsg) + +// XWayland +Q_LOGGING_CATEGORY(lcTlXwayland, "treeland.xwayland") + +// DDM integration +Q_LOGGING_CATEGORY(lcTlDdm, "treeland.ddm") + +// Popup focus management +Q_LOGGING_CATEGORY(lcTlPopupFocus, "treeland.popup.focus") +// XDG shell +Q_LOGGING_CATEGORY(lcTlShellXdg, "treeland.shell.xdg", QtInfoMsg) +// Hook scripts runner +Q_LOGGING_CATEGORY(lcTlHooks, "treeland.hooks") + +// Debug remote source +Q_LOGGING_CATEGORY(lcTlDebug, "treeland.debug") + diff --git a/src/common/treelandlogging.h b/src/common/treelandlogging.h new file mode 100644 index 0000000000..ae5b2e8362 --- /dev/null +++ b/src/common/treelandlogging.h @@ -0,0 +1,109 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef TREELAND_LOGGING_H +#define TREELAND_LOGGING_H + +#include + +// TreeLand Logging Categories +// Naming convention: lcTl + PascalCase module name +// String ID convention: treeland.[.] + +// Core modules +Q_DECLARE_LOGGING_CATEGORY(lcTlCore) +Q_DECLARE_LOGGING_CATEGORY(lcTlServer) +Q_DECLARE_LOGGING_CATEGORY(lcTlCompositor) +Q_DECLARE_LOGGING_CATEGORY(lcTlShell) +Q_DECLARE_LOGGING_CATEGORY(lcTlQml) + +// Input modules +Q_DECLARE_LOGGING_CATEGORY(lcTlInput) +Q_DECLARE_LOGGING_CATEGORY(lcTlInputManager) +Q_DECLARE_LOGGING_CATEGORY(lcTlGestures) +Q_DECLARE_LOGGING_CATEGORY(lcTlKeyboardNotify) + +// Seat management +Q_DECLARE_LOGGING_CATEGORY(lcTlSeat) + +// Output module +Q_DECLARE_LOGGING_CATEGORY(lcTlOutput) + +// Window management +Q_DECLARE_LOGGING_CATEGORY(lcTlSurface) + +// Workspace management +Q_DECLARE_LOGGING_CATEGORY(lcTlWorkspace) + +// Protocol module +Q_DECLARE_LOGGING_CATEGORY(lcTlProtocol) + +// Plugin system +Q_DECLARE_LOGGING_CATEGORY(lcTlPlugin) + +// Configuration management +Q_DECLARE_LOGGING_CATEGORY(lcTlConfig) + +// Wallpaper system +Q_DECLARE_LOGGING_CATEGORY(lcTlWallpaper) +Q_DECLARE_LOGGING_CATEGORY(lcTlWallpaperColor) + +// Effects system +Q_DECLARE_LOGGING_CATEGORY(lcTlEffect) + +// Capture system +Q_DECLARE_LOGGING_CATEGORY(lcTlCapture) + +// DBus interface +Q_DECLARE_LOGGING_CATEGORY(lcTlDBus) + +// Utility classes +Q_DECLARE_LOGGING_CATEGORY(lcTlUtils) +Q_DECLARE_LOGGING_CATEGORY(lcTlPropertyMonitor) + +// Shortcut system +Q_DECLARE_LOGGING_CATEGORY(lcTlShortcut) +Q_DECLARE_LOGGING_CATEGORY(lcTlKeyboardShortcutsInhibit) + +// Greeter module +Q_DECLARE_LOGGING_CATEGORY(lcTlGreeter) + +// FPS display +Q_DECLARE_LOGGING_CATEGORY(lcTlFpsDisplay) + +// xsettings +Q_DECLARE_LOGGING_CATEGORY(lcTlXsettings) + +// Activation module +Q_DECLARE_LOGGING_CATEGORY(lcTlActivation) + +// Window transition module +Q_DECLARE_LOGGING_CATEGORY(lcTlWindowTransition) + +// App ID resolver +Q_DECLARE_LOGGING_CATEGORY(lcTlAppIdResolver) + +// Prelaunch splash +Q_DECLARE_LOGGING_CATEGORY(lcTlPrelaunchSplash) + +// Layer shell extension (compositor-driven layer surface resize) +Q_DECLARE_LOGGING_CATEGORY(lcTlLayerShell) + +// XWayland +Q_DECLARE_LOGGING_CATEGORY(lcTlXwayland) + +// DDM integration +Q_DECLARE_LOGGING_CATEGORY(lcTlDdm) + +// Popup focus management +Q_DECLARE_LOGGING_CATEGORY(lcTlPopupFocus) +// XDG shell +Q_DECLARE_LOGGING_CATEGORY(lcTlShellXdg) + +// Hook scripts runner +Q_DECLARE_LOGGING_CATEGORY(lcTlHooks) + +// Debug remote source +Q_DECLARE_LOGGING_CATEGORY(lcTlDebug) + +#endif // TREELAND_LOGGING_H diff --git a/src/common/windowdecorations.h b/src/common/windowdecorations.h new file mode 100644 index 0000000000..e86c7b31b4 --- /dev/null +++ b/src/common/windowdecorations.h @@ -0,0 +1,35 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +/** + * @brief Drop-shadow parameters for server-side window decoration. + * + * Shared between the deprecated treeland-personalization-manager-v1 + * protocol and the new treeland-decoration-unstable-v1 protocol so that + * both can describe the same physical concept without code duplication. + */ +struct Shadow +{ + int32_t radius; + QPoint offset; + QColor color; + bool operator==(const Shadow &other) const = default; +}; + +/** + * @brief Border parameters for server-side window decoration. + * + * Shared between the deprecated treeland-personalization-manager-v1 + * protocol and the new treeland-decoration-unstable-v1 protocol. + */ +struct Border +{ + int32_t width; + QColor color; + bool operator==(const Border &other) const = default; +}; diff --git a/src/core/focuscontroller.cpp b/src/core/focuscontroller.cpp new file mode 100644 index 0000000000..ea6ecf614b --- /dev/null +++ b/src/core/focuscontroller.cpp @@ -0,0 +1,435 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "focuscontroller.h" +#include "session/sessionmanager.h" +#include "session/session.h" +#include "session/sessionprotocols.h" +#include "waylandserver.h" +#include "showdesktop/showdesktop.h" +#include "rootsurfacecontainer.h" +#include "seat/seatmanager.h" +#include "surface/surfacewrapper.h" +#include "workspace/workspace.h" +#include "common/treelandlogging.h" + +#include +#ifndef DISABLE_XWAYLAND +#include +#endif +#include +#include +#ifndef DISABLE_XWAYLAND +#include +#endif +#include + +#include + +#include + +FocusController::FocusController(WaylandServer *server) + : QObject(server) + , m_server(server) +{} + +void FocusController::activateSurface(SurfaceWrapper *wrapper, + Qt::FocusReason reason, + WSeat *seat, + bool raise) +{ + if (wrapper && !m_server->sessionManager()->isActiveWindow(wrapper)) + return; + if (wrapper && wrapper->session() + && wrapper->session()->workspace() != m_server->workspace() + && wrapper->workspaceId() != -1) + return; + if (wrapper && wrapper->isIMCandidatePanel()) + return; + + if (wrapper && !wrapper->acceptKeyboardFocus()) { + if (raise) { + wrapper->stackToLast(); + } + + return; + } + + // Plain activation: if the deepest modal is minimized, refuse to activate the parent + // entirely. The user must explicitly unminimize the modal first (e.g., click it). + SurfaceWrapper *originalWrapper = wrapper; + if (wrapper) { + if (SurfaceWrapper *modal = wrapper->findModal()) { + if (modal != wrapper) { + if (modal->workspaceId() != wrapper->workspaceId() + && wrapper->workspaceId() != -1) { + m_server->workspace()->moveSurfaceTo(modal, wrapper->workspaceId()); + } + + if (modal->isMinimized()) { + qCCritical(lcTlShell) << "Refusing to activate parent with minimized modal" + << "parent =" << wrapper << "modal =" << modal; + return; + } + + originalWrapper->stackToLast(); + wrapper = modal; + } + } + } + + if (m_server->blockActivateSurface() && wrapper && wrapper->type() != SurfaceWrapper::Type::LockScreen) { + if (wrapper->hasActiveCapability()) { + m_server->workspace()->pushActivedSurface(wrapper); + } + return; + } + + if (!wrapper || wrapper->hasActiveCapability()) { + setActivatedSurface(wrapper, seat, raise); + } else { + qCCritical(lcTlShell) + << "Trying to activate a surface which doesn't have ActiveCapability!"; + } + + if (!wrapper || wrapper->hasFocusCapability()) { + requestKeyboardFocus(wrapper, reason, seat); + } +} + +void FocusController::forceActivateSurface(SurfaceWrapper *wrapper, Qt::FocusReason reason, WSeat *seat) +{ + if (!wrapper) { + qCCritical(lcTlShell) << "Don't force activate to empty surface! do you want `WaylandServer::activeSurface(nullptr)`?"; + return; + } + if (!m_server->sessionManager()->isActiveWindow(wrapper)) + return; + if (!wrapper->shellSurface()) { + qCWarning(lcTlShell) << "Try to force activate a destroyed surface!"; + return; + } + + // Forced activation: the modal's minimized state is irrelevant — the caller explicitly + // requested this surface. However, if the parent itself is minimized, it must be restored + // here because the modal (which may already be unminimized) won't trigger parent linkage. + SurfaceWrapper *originalWrapper = wrapper; + const bool restoreAnimation = + !(reason == Qt::TabFocusReason || reason == Qt::BacktabFocusReason); + if (SurfaceWrapper *modal = wrapper->findModal()) { + if (modal != wrapper) { + if (modal->workspaceId() != wrapper->workspaceId() && wrapper->workspaceId() != -1) { + m_server->workspace()->moveSurfaceTo(modal, wrapper->workspaceId()); + } + if (originalWrapper->isMinimized()) { + originalWrapper->restoreFromMinimized(restoreAnimation); + } + originalWrapper->stackToLast(); + wrapper = modal; + } + } + + m_server->restoreFromShowDesktop(wrapper); + + if (wrapper->isMinimized()) { + wrapper->restoreFromMinimized(restoreAnimation); + } + + if (!wrapper->surface()->mapped()) { + qCWarning(lcTlShell) << "Can't activate unmapped surface: " << wrapper; + return; + } + + if (!wrapper->showOnWorkspace(m_server->workspace()->current()->id())) + m_server->workspace()->switchTo(m_server->workspace()->modelIndexOfSurface(wrapper)); + activateSurface(wrapper, reason, seat); +} + +SurfaceWrapper *FocusController::keyboardFocusSurface() const +{ + auto item = m_server->window()->activeFocusItem(); + if (!item) { + return nullptr; + } + + auto surface = qobject_cast(item->parent()); + if (!surface) { + return nullptr; + } + + return qobject_cast(surface->parent()); +} + +SurfaceWrapper *FocusController::activatedSurface() const +{ + if (!m_server->rootContainer()) + return nullptr; + + auto *seatContainer = m_server->rootContainer()->getSeatContainerOrDefault(m_server->seat()); + return seatContainer ? seatContainer->activatedSurface() : nullptr; +} + +void FocusController::setActivatedSurface(SurfaceWrapper *newActivateSurface, WSeat *seat, bool raise) +{ + if (newActivateSurface && !m_server->sessionManager()->isActiveWindow(newActivateSurface)) + return; + if (!m_server->rootContainer()) { + qCWarning(lcTlCore) << "Cannot set activated surface: root surface container is null"; + return; + } + + WSeat *targetSeat = seat ? seat : m_server->seat(); + auto *seatContainer = m_server->rootContainer()->getSeatContainerOrDefault(targetSeat); + if (!seatContainer) { + qCWarning(lcTlCore) << "Cannot set activated surface: no seat container for seat" + << targetSeat; + return; + } + + if (seatContainer->activatedSurface() == newActivateSurface) { + return; + } + + const bool isPrimarySeat = (targetSeat == m_server->seat()); + auto *oldPrimarySurface = isPrimarySeat ? activatedSurface() : nullptr; + + if (oldPrimarySurface) + oldPrimarySurface->setActivate(false); + + bool wasShowingDesktop = false; + + if (newActivateSurface) { + Q_ASSERT(newActivateSurface->showOnWorkspace(m_server->workspace()->current()->id())); + if (raise) { + newActivateSurface->stackToLast(); +#ifndef DISABLE_XWAYLAND + if (newActivateSurface->type() == SurfaceWrapper::Type::XWayland) { + auto xwaylandSurface = + qobject_cast(newActivateSurface->shellSurface()); + Q_ASSERT(!xwaylandSurface->isBypassManager()); + xwaylandSurface->restack(nullptr, WXWaylandSurface::XCB_STACK_MODE_ABOVE); + } +#endif + } + } + + if (newActivateSurface) { + if (m_server->showDesktopState() == ShowDesktop::State::Show) { + m_server->cancelShowDesktop(newActivateSurface); + newActivateSurface->setHideByShowDesk(true); + wasShowingDesktop = true; + } + + Q_ASSERT(newActivateSurface->hasActiveCapability()); + m_server->workspace()->pushActivedSurface(newActivateSurface); + } + + // SeatSurfaceManager emits activatedSurfaceChanged, and RootSurfaceContainer forwards + // it for the primary seat. Do not emit WaylandServer::activatedSurfaceChanged again here. + seatContainer->setActivatedSurface(newActivateSurface, Qt::OtherFocusReason); + + // This also restores keyboard focus on the other seats; the caller's subsequent + // requestKeyboardFocus() only covers the target seat. + if (wasShowingDesktop) + m_server->restoreShowDesktopFocus(); + + if (isPrimarySeat && newActivateSurface) { + Q_ASSERT(newActivateSurface->hasActiveCapability()); + newActivateSurface->setActivate(true); + } + +} + +void FocusController::onRenderWindowActiveFocusItemChanged() +{ + if (!keyboardFocusSurface()) { + // Keyboard focus moved to a non-client window (e.g. internal QML component). + // Notify all seats to clear the keyboard focus surface. + const auto seats = m_server->seatManager()->seats(); + for (auto *seat : seats) { + if (auto *seatContainer = m_server->rootContainer()->getSeatContainer(seat)) { + if (seatContainer->keyboardFocusSurface()) + seatContainer->setKeyboardFocusSurface(nullptr); + } + } + } +} + +void FocusController::requestKeyboardFocus(SurfaceWrapper *wrapper, Qt::FocusReason reason, WSeat *seat) +{ + if (wrapper && !m_server->sessionManager()->isActiveWindow(wrapper)) + return; + if (wrapper) { + // Pop up through parent hierarchy until we find a non-popup surface or grabbed popup + while (wrapper) { + auto *popupSurface = qobject_cast(wrapper->shellSurface()); + if (!popupSurface) + break; + if (popupSurface->handle()->seat) + break; + wrapper = wrapper->parentSurface(); + } + if (!wrapper || !wrapper->hasFocusCapability()) { + qCDebug(lcTlShell) << "Request keyboard focus for surface without focus capability!" + << "surface =" << wrapper; + return; + } + } + + if (!seat) + seat = m_server->seat(); + + // Delegate to SeatSurfaceManager which handles keyboardFocusPriority checks, + // Qt focus management, Wayland focus, multi-seat arbitration, and interaction metadata. + auto *seatContainer = m_server->rootContainer()->getSeatContainer(seat); + Q_ASSERT(seatContainer); + seatContainer->setKeyboardFocusSurface(wrapper, reason); +} + +WSeat *FocusController::getLastInteractingSeat(SurfaceWrapper *surface) const +{ + if (!surface) { + return nullptr; + } + + auto lastSeatVariant = surface->property("lastInteractingSeat"); + if (lastSeatVariant.isValid()) { + auto seat = lastSeatVariant.value(); + if (m_server->seatManager()->seats().contains(seat)) { + return seat; + } + } + return nullptr; +} + +void FocusController::updateSurfaceSeatInteraction(SurfaceWrapper *surface, WSeat *seat) +{ + if (!surface || !seat) + return; + + surface->setProperty("lastInteractingSeat", QVariant::fromValue(seat)); + surface->setProperty("lastInteractionTime", QDateTime::currentMSecsSinceEpoch()); +} + +void FocusController::registerSession(Session *session) +{ + auto *activation = new ActivationManagerInterfaceV1( + [this, owner = QPointer(session)](WSurface *surface, WSeat *seat) { + return owner && surface && owner->ownsClient(surface->waylandClient()) + && canTransferActivation(surface, seat); + }); + session->attachInterface(activation); + connect(activation, &ActivationManagerInterfaceV1::activateRequested, + this, &FocusController::onActivationRequested); +} +bool FocusController::canTransferActivation(WSurface *surface, WSeat *seat) const +{ + // Determine whether the surface can transfer activation for the same seat + // that produced the serial in set_serial. + if (!seat || !seat->isValid()) { + return false; + } + + auto wrapper = m_server->rootContainer()->getSurface(surface); + if (!wrapper || !m_server->sessionManager()->isActiveWindow(wrapper)) { + return false; + } + + if (seat->keyboardFocusSurface() == surface) { + return true; + } + + if (seat->pointerFocusSurface() == surface) { + return true; + } + + if (wrapper->isActivated() && getLastInteractingSeat(wrapper) == seat) { + return true; + } + + return false; +} +void FocusController::onActivationRequested(const QString &token, + ActivationManagerInterfaceV1::TokenDisposition disposition, + WSurface *wsurface, WSeat *seat, + WSurface *originatingSurface) +{ + auto wrapper = m_server->rootContainer()->getSurface(wsurface); + if (!wrapper) { + qCWarning(lcTlCore) << "Activation request for unknown surface!"; + return; + } + + auto *activation = qobject_cast(sender()); + if (!activation || !activation->ownsSocket() + || !activation->ownsClient(wsurface->waylandClient())) + return; + if (originatingSurface && !activation->ownsClient(originatingSurface->waylandClient())) + return; + auto *transitions = wrapper->session() ? wrapper->session()->protocols()->windowTransitions() : nullptr; + if (transitions && transitions->hasPendingWindowTransitionRect(token)) { + if (!originatingSurface) { + // Without an originating surface the rect cannot be mapped to + // global coordinates, so it will never be used. Close it now + // instead of waiting for the pending sweep. + qCDebug(lcTlWindowTransition) << "Window transition rect discarded: token has no" + << "originating surface" + << "appId:" << wrapper->appId(); + transitions->discardPendingRect(token); + } else if (wsurface->mapped()) { + qCDebug(lcTlWindowTransition) << "Window transition rect discarded: target surface" + << "is already mapped (client activation arrived too late)" + << "appId:" << wrapper->appId(); + // Discard the pending rect object if any. + transitions->discardPendingRect(token); + } else { + auto *originWrapper = m_server->rootContainer()->getSurface(originatingSurface); + if (originWrapper) { + bool associated = transitions->associatePendingRect( + token, wrapper->windowTransition(), originWrapper->windowTransition()); + if (!associated) { + qCDebug(lcTlWindowTransition) + << "Window transition rect was destroyed" + << "before activation, using default animation" + << "appId:" << wrapper->appId(); + } + } else { + qCDebug(lcTlWindowTransition) + << "Window transition: originating surface wrapper" + << "not found, skipping" + << "appId:" << wrapper->appId(); + // Discard the pending rect object. + transitions->discardPendingRect(token); + } + } + } + + // Don't use hasActiveCapability() here — it also checks UnMinimized, + // but minimized windows should be allowed to activate (which unminimizes them). + if (!wsurface->mapped()) { + if (disposition == ActivationManagerInterfaceV1::TokenDisposition::Active) + wrapper->setPendingActivation(seat); + else + qCWarning(lcTlCore) << "Activation request for unmapped surface!"; + return; + } + + if (!wrapper->hasInitializeContainer()) { + qCWarning(lcTlCore) << "Activation request for surface without initialized container:" + << "container =" << wrapper->container(); + return; + } + + switch (disposition) { + case ActivationManagerInterfaceV1::TokenDisposition::Active: + forceActivateSurface(wrapper, Qt::OtherFocusReason, seat); + break; + case ActivationManagerInterfaceV1::TokenDisposition::Attention: + wrapper->setAttention(true); + break; + case ActivationManagerInterfaceV1::TokenDisposition::Invalid: + // Use a relaxed policy: fallback to attention if the token is invalid + wrapper->setAttention(true); + break; + } +} diff --git a/src/core/focuscontroller.h b/src/core/focuscontroller.h new file mode 100644 index 0000000000..237546d8ae --- /dev/null +++ b/src/core/focuscontroller.h @@ -0,0 +1,52 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include "modules/activation/activationmanagerinterfacev1.h" +#include "modules/window-transition/windowtransitionmanagerinterfacev1.h" + +#include + +class Session; +class WaylandServer; +class SurfaceWrapper; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WSeat; +class WServer; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class FocusController : public QObject +{ + Q_OBJECT +public: + explicit FocusController(WaylandServer *server); + + void registerSession(Session *session); + void activateSurface(SurfaceWrapper *wrapper, Qt::FocusReason reason, + WSeat *seat, bool raise = true); + void forceActivateSurface(SurfaceWrapper *wrapper, Qt::FocusReason reason, + WSeat *seat); + void requestKeyboardFocus(SurfaceWrapper *wrapper, Qt::FocusReason reason, + WSeat *seat); + SurfaceWrapper *keyboardFocusSurface() const; + SurfaceWrapper *activatedSurface() const; + void setActivatedSurface(SurfaceWrapper *wrapper, WSeat *seat, bool raise = true); + WSeat *getLastInteractingSeat(SurfaceWrapper *surface) const; + void updateSurfaceSeatInteraction(SurfaceWrapper *surface, WSeat *seat); + void onRenderWindowActiveFocusItemChanged(); + +private: + bool canTransferActivation(WSurface *surface, WSeat *seat) const; + void onActivationRequested(const QString &token, + ActivationManagerInterfaceV1::TokenDisposition disposition, + WSurface *surface, WSeat *seat, + WSurface *originatingSurface); +private: + WaylandServer *m_server; +}; diff --git a/src/core/imcandidatepanelmanager.cpp b/src/core/imcandidatepanelmanager.cpp new file mode 100644 index 0000000000..03b925216b --- /dev/null +++ b/src/core/imcandidatepanelmanager.cpp @@ -0,0 +1,279 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "imcandidatepanelmanager.h" +#include "session/session.h" +#include "common/treelandlogging.h" + +#include "output/output.h" +#include "workspace/workspace.h" +#include "rootsurfacecontainer.h" +#include "shellhandler.h" +#include "surface/surfacewrapper.h" + +#ifndef DISABLE_XWAYLAND +#include +#endif + +#include +#include +#ifndef DISABLE_XWAYLAND +#include +#include +#endif +#include + +const QLatin1String IMCandidatePanelManager::IM_CANDIDATE_PANEL( + "org.deepin.treeland.im-candidate-panel"); + +IMCandidatePanelManager::IMCandidatePanelManager( + ShellHandler *shellHandler, + WAYLIB_SERVER_NAMESPACE::WInputMethodHelper *inputMethodHelper, + QObject *parent) + : QObject(parent) + , m_shellHandler(shellHandler) + , m_inputMethodHelper(inputMethodHelper) +{ + connect(m_shellHandler, + &ShellHandler::surfaceWrapperAboutToRemove, + this, + [this](SurfaceWrapper *wrapper) { + m_imCandidatePanels.removeAll(wrapper); + }); +} + +#ifndef DISABLE_XWAYLAND +bool IMCandidatePanelManager::parseIMCandidatePanelProperty( + const QMap &result, + xcb_atom_t atom) +{ + auto it = result.constFind(atom); + if (it != result.constEnd() && it->size() >= static_cast(sizeof(uint32_t))) { + uint32_t v = 0; + memcpy(&v, it->constData(), sizeof(uint32_t)); + return v == 1; + } + return false; +} + +void IMCandidatePanelManager::setupXWayland(WAYLIB_SERVER_NAMESPACE::WXWayland *xwayland) +{ + m_xwayland = xwayland; + m_imCandidatePanelAtom = xwayland->atom("_DEEPIN_IM_CANDIDATE_PANEL"); + xwayland->setAtomSupported(m_imCandidatePanelAtom, true); + + connect(xwayland, + &WAYLIB_SERVER_NAMESPACE::WXWayland::windowPropertyChanged, + this, + &IMCandidatePanelManager::onXwaylandPropertyChanged); +} +#endif + +bool IMCandidatePanelManager::isIMCandidatePanel(SurfaceWrapper *wrapper) const +{ + return wrapper->isIMCandidatePanel(); +} + +#ifndef DISABLE_XWAYLAND +bool IMCandidatePanelManager::isIMCandidatePanel( + WAYLIB_SERVER_NAMESPACE::WXWaylandSurface *surface) const +{ + if (m_imCandidatePanelAtom == XCB_ATOM_NONE || !m_xwayland) + return false; + + return surface->property("imCandidatePanel").toBool(); +} + +xcb_atom_t IMCandidatePanelManager::imCandidatePanelAtom() const +{ + return m_imCandidatePanelAtom; +} +#endif +bool IMCandidatePanelManager::checkAndApplyIMCandidatePanel(SurfaceWrapper *wrapper) +{ + auto *shellSurface = wrapper->shellSurface(); + if (auto *xdgSurface + = qobject_cast(shellSurface)) { + if (xdgSurface->tag() != IM_CANDIDATE_PANEL) + return false; +#ifndef DISABLE_XWAYLAND + } else if (auto *xwaylandSurface + = qobject_cast(shellSurface)) { + if (!isIMCandidatePanel(xwaylandSurface)) + return false; +#endif + } else { + return false; + } + + if (wrapper->isIMCandidatePanel()) + return false; + applyIMCandidatePanel(wrapper); + + if (auto *xdgSurface = qobject_cast(shellSurface)) { + qCDebug(lcTlShellXdg) << "IM candidate panel applied" << wrapper + << "appId =" << wrapper->appId() + << "tag =" << xdgSurface->tag(); +#ifndef DISABLE_XWAYLAND + } else { + qCDebug(lcTlShellXdg) << "IM candidate panel applied (XWayland)" << wrapper + << "appId =" << wrapper->appId(); +#endif + } + return true; +} + +void IMCandidatePanelManager::applyIMCandidatePanel(SurfaceWrapper *wrapper) +{ + auto *popupContainer = m_shellHandler->popupContainer(); + + auto *currentContainer = wrapper->container(); + if (currentContainer) + currentContainer->removeSurface(wrapper); + + wrapper->setIMCandidatePanel(true); + popupContainer->addSurface(wrapper); + wrapper->setHasInitializeContainer(true); + wrapper->setPositionAutomatic(false); + wrapper->setXwaylandPositionFromSurface(false); + + if (wrapper->surfaceItem()) + wrapper->surfaceItem()->setFocusPolicy(Qt::NoFocus); + + wrapper->setAcceptKeyboardFocus(false); + + if (!wrapper->noDecoration()) + wrapper->setNoDecoration(true); + + if (!wrapper->skipDockPreView()) + wrapper->session()->windowManagement()->removeSurface(wrapper); + + wrapper->disableWindowAnimation(); + + m_imCandidatePanels.append(wrapper); + + connect(wrapper, + &SurfaceWrapper::normalGeometryChanged, + this, + &IMCandidatePanelManager::onIMCandidatePanelGeometryChanged); + + applyInitialPositionAtCursor(); +} + +void IMCandidatePanelManager::setInputMethodHelper(WAYLIB_SERVER_NAMESPACE::WInputMethodHelper *helper) +{ + m_inputMethodHelper = helper; +} + +void IMCandidatePanelManager::applyInitialPositionAtCursor() +{ + if (!m_inputMethodHelper) + return; + auto cursorRect = m_inputMethodHelper->textInputCursorRect(); + if (cursorRect.isEmpty() || m_imCandidatePanels.isEmpty()) + return; + + auto *focusSurface = m_inputMethodHelper->textInputFocusSurface(); + if (!focusSurface) + return; + + auto *rootContainer = m_shellHandler->rootSurfaceContainer(); + auto *focusWrapper = rootContainer->getSurface(focusSurface); + if (!focusWrapper) + return; + + auto *output = focusWrapper->ownsOutput(); + if (!output) + return; + + QPointF pos; + auto wrapperPos = focusWrapper->mapToGlobal(QPointF(0, 0)); + auto *shellSurface = focusWrapper->shellSurface(); + const QPointF contentOffset = shellSurface + ? shellSurface->getContentGeometry().topLeft() : QPointF(0, 0); + pos.setX(wrapperPos.x() + cursorRect.x() - contentOffset.x()); + pos.setY(wrapperPos.y() + cursorRect.y() - contentOffset.y() + + cursorRect.height() + focusWrapper->titlebarGeometry().height()); + + arrangeIMCandidatePanels(output, pos); +} + +void IMCandidatePanelManager::arrangeIMCandidatePanels(Output *output, const QPointF &basePos) +{ + for (auto *wrapper : m_imCandidatePanels) { + auto normalGeo = wrapper->normalGeometry(); + // Wait for geometry to be valid before arranging + if (normalGeo.isEmpty()) + continue; + + auto pos = basePos; + output->adjustToOutputBounds(pos, normalGeo, output->geometry()); + wrapper->moveNormalGeometryInOutput(pos); + } +} + +void IMCandidatePanelManager::onIMCandidatePanelGeometryChanged() +{ + if (m_imCandidatePanels.isEmpty() || !m_inputMethodHelper) + return; + + auto *focusSurface = m_inputMethodHelper->textInputFocusSurface(); + auto *rootContainer = m_shellHandler->rootSurfaceContainer(); + auto *focusWrapper = focusSurface ? rootContainer->getSurface(focusSurface) : nullptr; + if (!focusWrapper) + return; + auto *output = focusWrapper->ownsOutput(); + if (!output) + return; + + QPointF pos; + auto wrapperPos = focusWrapper->mapToGlobal(QPointF(0, 0)); + auto cursorRect = m_inputMethodHelper->textInputCursorRect(); + auto *shellSurface = focusWrapper->shellSurface(); + const QPointF contentOffset = shellSurface + ? shellSurface->getContentGeometry().topLeft() : QPointF(0, 0); + pos.setX(wrapperPos.x() + cursorRect.x() - contentOffset.x()); + pos.setY(wrapperPos.y() + cursorRect.y() - contentOffset.y() + + cursorRect.height() + focusWrapper->titlebarGeometry().height()); + + arrangeIMCandidatePanels(output, pos); +} + +#ifndef DISABLE_XWAYLAND +void IMCandidatePanelManager::onXwaylandPropertyChanged( + WAYLIB_SERVER_NAMESPACE::WXWaylandSurface *surface, + xcb_atom_t atom) +{ + if (atom != m_imCandidatePanelAtom) + return; + + auto *rootContainer = m_shellHandler->rootSurfaceContainer(); + auto *wrapper = rootContainer->getSurface(surface); + + // Async read the property value via readAsyncProperties (non-blocking). + if (!m_xwayland) + return; + + auto windowId = surface->handle()->window_id; + QVector requests = { + { m_imCandidatePanelAtom, XCB_ATOM_CARDINAL } + }; + m_xwayland->readAsyncProperties( + windowId, + requests, + 50, + [self = QPointer(this), + surface = QPointer(surface), + wrapper = QPointer(wrapper), + atom = m_imCandidatePanelAtom](xcb_window_t, const QMap &result) { + auto *s = surface.data(); + if (!s || !self) + return; + bool value = IMCandidatePanelManager::parseIMCandidatePanelProperty(result, atom); + s->setProperty("imCandidatePanel", value); + if (wrapper) { + self->checkAndApplyIMCandidatePanel(wrapper); + } + }); +} +#endif diff --git a/src/core/imcandidatepanelmanager.h b/src/core/imcandidatepanelmanager.h new file mode 100644 index 0000000000..b99f8ae170 --- /dev/null +++ b/src/core/imcandidatepanelmanager.h @@ -0,0 +1,74 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifndef DISABLE_XWAYLAND +#include +#endif + +#include + +#include +#include + +class SurfaceWrapper; +class ShellHandler; +class RootSurfaceContainer; +class Output; + +namespace WAYLIB_SERVER_NAMESPACE { +class WInputMethodHelper; +#ifndef DISABLE_XWAYLAND +class WXWayland; +class WXWaylandSurface; +#endif +} // namespace WAYLIB_SERVER_NAMESPACE + +class IMCandidatePanelManager : public QObject +{ + Q_OBJECT + +public: + explicit IMCandidatePanelManager(ShellHandler *shellHandler, + WAYLIB_SERVER_NAMESPACE::WInputMethodHelper *inputMethodHelper, + QObject *parent = nullptr); + + void setInputMethodHelper(WAYLIB_SERVER_NAMESPACE::WInputMethodHelper *helper); +#ifndef DISABLE_XWAYLAND + void setupXWayland(WAYLIB_SERVER_NAMESPACE::WXWayland *xwayland); +#endif + + bool isIMCandidatePanel(SurfaceWrapper *wrapper) const; +#ifndef DISABLE_XWAYLAND + bool isIMCandidatePanel(WAYLIB_SERVER_NAMESPACE::WXWaylandSurface *surface) const; +#endif + bool checkAndApplyIMCandidatePanel(SurfaceWrapper *wrapper); +#ifndef DISABLE_XWAYLAND + xcb_atom_t imCandidatePanelAtom() const; + + // Parse IM candidate panel property from async result map + static bool parseIMCandidatePanelProperty(const QMap &result, + xcb_atom_t atom); +#endif + +private: + void applyIMCandidatePanel(SurfaceWrapper *wrapper); + void arrangeIMCandidatePanels(Output *output, const QPointF &basePos); + void onIMCandidatePanelGeometryChanged(); + + static const QLatin1String IM_CANDIDATE_PANEL; + void applyInitialPositionAtCursor(); +#ifndef DISABLE_XWAYLAND + void onXwaylandPropertyChanged(WAYLIB_SERVER_NAMESPACE::WXWaylandSurface *surface, + xcb_atom_t atom); +#endif + + ShellHandler *m_shellHandler; + QPointer m_inputMethodHelper; +#ifndef DISABLE_XWAYLAND + QPointer m_xwayland; + xcb_atom_t m_imCandidatePanelAtom = XCB_ATOM_NONE; +#endif + QList m_imCandidatePanels; +}; diff --git a/src/core/layersurfacecontainer.cpp b/src/core/layersurfacecontainer.cpp new file mode 100644 index 0000000000..8f8a993b7d --- /dev/null +++ b/src/core/layersurfacecontainer.cpp @@ -0,0 +1,143 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "layersurfacecontainer.h" + +#include "core/rootsurfacecontainer.h" +#include "output/output.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" +#include "common/treelandlogging.h" + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + + +OutputLayerSurfaceContainer::OutputLayerSurfaceContainer(Output *output, + LayerSurfaceContainer *parent) + : SurfaceContainer(parent) + , m_output(output) +{ +} + +Output *OutputLayerSurfaceContainer::output() const +{ + return m_output; +} + +void OutputLayerSurfaceContainer::addSurface(SurfaceWrapper *surface) +{ + SurfaceContainer::addSurface(surface); + // Only layer-surface is update it's outputs by `OutputLayerSurfaceContainer` + // other types of surfaces are updated in `RootSurfaceContainer`. + // Currently there is no consideration of layer surface spanning multiple outputs + surface->setOutputs({m_output->output()}); + surface->setOwnsOutput(m_output); +} + +void OutputLayerSurfaceContainer::removeSurface(SurfaceWrapper *surface) +{ + SurfaceContainer::removeSurface(surface); + surface->setOutputs({}); + if (surface->ownsOutput() == m_output) + surface->setOwnsOutput(nullptr); +} + +LayerSurfaceContainer::LayerSurfaceContainer(SurfaceContainer *parent) + : SurfaceContainer(parent) +{ +} + +void LayerSurfaceContainer::addOutput(Output *output) +{ + Q_ASSERT(!getSurfaceContainer(output)); + auto container = new OutputLayerSurfaceContainer(output, this); + m_surfaceContainers.append(container); + updateSurfacesContainer(); +} + +void LayerSurfaceContainer::removeOutput(Output *output) +{ + OutputLayerSurfaceContainer *container = getSurfaceContainer(output); + Q_ASSERT(container); + m_surfaceContainers.removeOne(container); + + const auto surfaces = container->surfaces(); + for (SurfaceWrapper *surface : surfaces) { + auto layerSurface = qobject_cast(surface->shellSurface()); + Q_ASSERT(layerSurface); + // Needs to be moved to the new primary output + if (!layerSurface->output() && rootContainer()->primaryOutput()) { + container->removeSurface(surface); + addSurfaceToContainer(surface); + } else { + layerSurface->closed(); + } + } + + container->deleteLater(); +} + +OutputLayerSurfaceContainer *LayerSurfaceContainer::getSurfaceContainer(const Output *output) const +{ + return getSurfaceContainer(output->output()); +} + +OutputLayerSurfaceContainer *LayerSurfaceContainer::getSurfaceContainer(const WOutput *output) const +{ + for (OutputLayerSurfaceContainer *container : std::as_const(m_surfaceContainers)) { + if (container->output()->output() == output) + return container; + } + return nullptr; +} + +void LayerSurfaceContainer::addSurface(SurfaceWrapper *surface) +{ + Q_ASSERT(surface->type() == SurfaceWrapper::Type::Layer); + if (!SurfaceContainer::doAddSurface(surface, false)) + return; + addSurfaceToContainer(surface); + surface->setHasInitializeContainer(true); +} + +void LayerSurfaceContainer::removeSurface(SurfaceWrapper *surface) +{ + if (!SurfaceContainer::doRemoveSurface(surface, false)) + return; + auto shell = qobject_cast(surface->shellSurface()); + auto output = shell->output(); + auto container = getSurfaceContainer(output); + Q_ASSERT(container); + Q_ASSERT(container->surfaces().contains(surface)); + container->removeSurface(surface); + surface->setHasInitializeContainer(false); +} + +void LayerSurfaceContainer::addSurfaceToContainer(SurfaceWrapper *surface) +{ + Q_ASSERT(!surface->container()); + auto shell = qobject_cast(surface->shellSurface()); + auto output = shell->output() ? shell->output() + : rootContainer()->primaryOutput() ? rootContainer()->primaryOutput()->output() + : nullptr; + if (!output) { + qCWarning(lcTlShell) << "No output, will close layer surface!"; + shell->closed(); + return; + } + auto container = getSurfaceContainer(output); + Q_ASSERT(container); + Q_ASSERT(!container->surfaces().contains(surface)); + container->addSurface(surface); +} + +void LayerSurfaceContainer::updateSurfacesContainer() +{ + for (SurfaceWrapper *surface : std::as_const(surfaces())) { + if (!surface->container()) + addSurfaceToContainer(surface); + } +} diff --git a/src/core/layersurfacecontainer.h b/src/core/layersurfacecontainer.h new file mode 100644 index 0000000000..6d202bb088 --- /dev/null +++ b/src/core/layersurfacecontainer.h @@ -0,0 +1,52 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "surface/surfacecontainer.h" + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class LayerSurfaceContainer; + +class OutputLayerSurfaceContainer : public SurfaceContainer +{ + Q_OBJECT +public: + explicit OutputLayerSurfaceContainer(Output *output, LayerSurfaceContainer *parent); + + Output *output() const; + + void addSurface(SurfaceWrapper *surface) override; + void removeSurface(SurfaceWrapper *surface) override; + +private: + Output *m_output; +}; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutput; +WAYLIB_SERVER_END_NAMESPACE + +class LayerSurfaceContainer : public SurfaceContainer +{ + Q_OBJECT +public: + explicit LayerSurfaceContainer(SurfaceContainer *parent); + + void addOutput(Output *output) override; + void removeOutput(Output *output) override; + OutputLayerSurfaceContainer *getSurfaceContainer(const Output *output) const; + OutputLayerSurfaceContainer *getSurfaceContainer(const WOutput *output) const; + + void addSurface(SurfaceWrapper *surface) override; + void removeSurface(SurfaceWrapper *surface) override; + +private: + void addSurfaceToContainer(SurfaceWrapper *surface); + void updateSurfacesContainer(); + + QList m_surfaceContainers; +}; diff --git a/src/core/qml/Animations/GeometryAnimation.qml b/src/core/qml/Animations/GeometryAnimation.qml new file mode 100644 index 0000000000..e823cd6b47 --- /dev/null +++ b/src/core/qml/Animations/GeometryAnimation.qml @@ -0,0 +1,142 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Treeland +import Waylib.Server +import QtQuick.Effects + +Item { + id: root + + required property SurfaceWrapper surface + required property rect fromGeometry + required property rect toGeometry + property int duration: 200 * WaylandServer.animationSpeed + property var enableBlur: false + + signal ready + signal finished + + x: fromGeometry.x + y: fromGeometry.y + width: fromGeometry.width + height: fromGeometry.height + + function start() { + animation.start(); + } + + XdgShadow { + anchors.fill: parent + visible: surface.visibleDecoration && !surface.noDecoration + cornerRadius: surface.presentationFrameGeometry.radius + shadowBlur: surface.shadowBlurRadius + shadowOffsetX: surface.shadowOffsetX + shadowOffsetY: surface.shadowOffsetY + shadowColor: surface.shadowColor + } + + Loader { + active: root.enableBlur + anchors.fill: parent + sourceComponent: Blur { + anchors.fill: parent + radius: surface.presentationFrameGeometry.radius + } + } + + ShaderEffectSource { + id: backgroundEffect + + readonly property real xScale: root.width / surface.width + readonly property real yScale: root.height / surface.height + + live: true + sourceItem: surface + hideSource: true + sourceRect: surface.boundingRect + width: sourceRect.width * xScale + height: sourceRect.height * yScale + x: sourceRect.x * xScale + y: sourceRect.y * yScale + } + + ShaderEffectSource { + id: frontEffect + + readonly property real xScale: root.width / fromGeometry.width + readonly property real yScale: root.height / fromGeometry.height + + live: false + sourceItem: surface + width: sourceRect.width * xScale + height: sourceRect.height * yScale + x: sourceRect.x * xScale + y: sourceRect.y * yScale + + onScheduledUpdateCompleted: { + root.ready(); + } + + Component.onCompleted: { + sourceRect = surface.boundingRect + } + } + + ParallelAnimation { + id: animation + + // Keep position in sync with size and backdrop sampling on the GUI thread. + NumberAnimation { + target: root + property: "x" + duration: root.duration + easing.type: Easing.OutCubic + from: root.fromGeometry.x + to: root.toGeometry.x + } + + NumberAnimation { + target: root + property: "y" + duration: root.duration + easing.type: Easing.OutCubic + from: root.fromGeometry.y + to: root.toGeometry.y + } + + PropertyAnimation { + target: root + property: "width" + duration: root.duration + easing.type: Easing.OutCubic + from: root.fromGeometry.width + to: root.toGeometry.width + } + + PropertyAnimation { + target: root + property: "height" + duration: root.duration + easing.type: Easing.OutCubic + from: root.fromGeometry.height + to: root.toGeometry.height + } + + OpacityAnimator { + target: frontEffect + duration: root.duration / 2 + easing.type: Easing.Linear + from: 1.0 + to: 0.0 + } + + onFinished: { + // Defer the signal emission to avoid deleting animation objects in the same callback stack. + Qt.callLater(function() { + root.finished(); + }) + } + } +} diff --git a/src/core/qml/Animations/LaunchpadAnimation.qml b/src/core/qml/Animations/LaunchpadAnimation.qml new file mode 100644 index 0000000000..45187d9e22 --- /dev/null +++ b/src/core/qml/Animations/LaunchpadAnimation.qml @@ -0,0 +1,94 @@ +// Copyright (C) 2024 justforlxz . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Effects +import Treeland + +Item { + id: root + + enum Direction { + Show = 1, + Hide + } + + signal finished + + visible: false + clip: true + + required property var target + required property var direction + property int duration: 400 * WaylandServer.animationSpeed + + width: target.width + height: target.height + state: "None" + + function start() { + visible = true; + root.state = direction === LaunchpadAnimation.Direction.Show ? "Show" : "Hide" + } + + function stop() { + visible = false; + effect.sourceItem = null; + finished(); + } + + states: [ + State { + name: "None" + }, + State { + name: "Show" + PropertyChanges { + target: effect + opacity: 1 + scale: 1 + } + }, + State { + name: "Hide" + PropertyChanges { + target: effect + opacity: 0 + scale: 0.3 + } + } + ] + + transitions: [ + Transition { + PropertyAnimation { + target: effect + property: "opacity" + duration: root.duration + easing.type: Easing.OutExpo + } + PropertyAnimation { + target: effect + property: "scale" + duration: root.duration + easing.type: Easing.OutExpo + } + onRunningChanged: { + if (!running) { + root.stop() + } + } + } + ] + + ShaderEffectSource { + id: effect + live: root.direction === LaunchpadAnimation.Direction.Show + hideSource: true + sourceItem: root.target + width: root.target.width + height: root.target.height + scale: root.direction === LaunchpadAnimation.Direction.Show ? 0.3 : 1 + opacity: root.direction === LaunchpadAnimation.Direction.Show ? 0 : 1 + } +} diff --git a/src/core/qml/Animations/LayerShellAnimation.qml b/src/core/qml/Animations/LayerShellAnimation.qml new file mode 100644 index 0000000000..b50d8dceef --- /dev/null +++ b/src/core/qml/Animations/LayerShellAnimation.qml @@ -0,0 +1,138 @@ +// Copyright (C) 2024 justforlxz . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Waylib.Server + +Item { + id: root + + enum Direction { + Show = 1, + Hide + } + + signal finished + + visible: false + clip: true + + required property var target + required property var direction + + property var position: WaylandLayerSurface.AnchorType.Bottom + property var enableBlur: false + + readonly property rect sourceRect: target.boundingRect + + x: target.x + sourceRect.x + y: target.y + sourceRect.y + width: sourceRect.width + height: sourceRect.height + + function start() { + visible = true; + sideAnimation.start(); + } + + function stop() { + visible = false; + effect.sourceItem = null; + finished(); + } + + Loader { + active: root.enableBlur + x: effect.x - root.sourceRect.x + y: effect.y - root.sourceRect.y + width: root.target.width + height: root.target.height + sourceComponent: Blur { + anchors.fill: parent + radius: root.target.presentationFrameGeometry.radius + } + } + + ShaderEffectSource { + id: effect + live: root.direction === LayerShellAnimation.Direction.Show + hideSource: true + sourceItem: root.target + sourceRect: root.sourceRect + width: root.width + height: root.height + } + + ParallelAnimation { + id: sideAnimation + + onStopped: { + root.stop(); + } + + PropertyAnimation { + target: effect + property: "x" + duration: 1000 + from: { + if (root.position === WaylandLayerSurface.AnchorType.Top || root.position === WaylandLayerSurface.AnchorType.Bottom) { + return 0; + } + if (root.position === WaylandLayerSurface.AnchorType.Left) { + return root.direction === LayerShellAnimation.Direction.Show ? -effect.width : 0; + } + if (root.position === WaylandLayerSurface.AnchorType.Right) { + return root.direction === LayerShellAnimation.Direction.Show ? effect.width : 0; + } + } + to: { + if (root.position === WaylandLayerSurface.AnchorType.Top || root.position === WaylandLayerSurface.AnchorType.Bottom) { + return 0; + } + if (root.position === WaylandLayerSurface.AnchorType.Left) { + return root.direction !== LayerShellAnimation.Direction.Show ? -effect.width : 0; + } + if (root.position === WaylandLayerSurface.AnchorType.Right) { + return root.direction !== LayerShellAnimation.Direction.Show ? effect.width : 0; + } + } + easing.type: Easing.OutExpo + } + PropertyAnimation { + target: effect + property: "y" + duration: 1000 + from: { + if (root.position === WaylandLayerSurface.AnchorType.Left || root.position === WaylandLayerSurface.AnchorType.Right) { + return 0; + } + if (root.position === WaylandLayerSurface.AnchorType.Top) { + return root.direction === LayerShellAnimation.Direction.Show ? -effect.height : 0; + } + if (root.position === WaylandLayerSurface.AnchorType.Bottom) { + return root.direction === LayerShellAnimation.Direction.Show ? effect.height : 0; + } + } + to: { + if (root.position === WaylandLayerSurface.AnchorType.Left || root.position === WaylandLayerSurface.AnchorType.Right) { + return 0; + } + if (root.position === WaylandLayerSurface.AnchorType.Top) { + return root.direction !== LayerShellAnimation.Direction.Show ? -effect.height : 0; + } + if (root.position === WaylandLayerSurface.AnchorType.Bottom) { + return root.direction !== LayerShellAnimation.Direction.Show ? effect.height : 0; + } + } + easing.type: Easing.OutExpo + } + PropertyAnimation { + target: effect + property: "opacity" + duration: 1000 + from: root.direction === LayerShellAnimation.Direction.Show ? 0.2 : 1 + to: root.direction !== LayerShellAnimation.Direction.Show ? 0.2 : 1 + easing.type: Easing.OutExpo + } + } +} diff --git a/src/core/qml/Animations/MinimizeAnimation.qml b/src/core/qml/Animations/MinimizeAnimation.qml new file mode 100644 index 0000000000..6175a0195b --- /dev/null +++ b/src/core/qml/Animations/MinimizeAnimation.qml @@ -0,0 +1,175 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Effects +import Treeland + +Item { + id: root + + enum Direction { + Show = 1, // UnMinimize + Hide // Minimize + } + + signal finished + + clip: false + + required property var target + required property rect position + required property var direction + property int duration: 400 * WaylandServer.animationSpeed + property int animationDuration: duration + readonly property real minimizedRotation: -30 + readonly property bool showShadow: !target.noDecoration + && target.surfaceState === SurfaceWrapper.State.Normal + + function start() { + configureAnimation(direction === MinimizeAnimation.Direction.Hide + ? Qt.rect(target.x, target.y, target.width, target.height) + : position, + direction === MinimizeAnimation.Direction.Hide + ? position + : Qt.rect(target.x, target.y, target.width, target.height), + direction === MinimizeAnimation.Direction.Hide ? 1 : 0, + direction === MinimizeAnimation.Direction.Hide ? 0 : 1, + direction === MinimizeAnimation.Direction.Hide ? 0 : minimizedRotation, + direction === MinimizeAnimation.Direction.Hide ? minimizedRotation : 0, + duration); + mainAnimation.start(); + } + + function redirect() { + const currentGeometry = Qt.rect(effect.x, effect.y, effect.width, effect.height); + const currentOpacity = effect.opacity; + const currentRotation = effect.rotation; + mainAnimation.stop(); + + const targetGeometry = direction === MinimizeAnimation.Direction.Hide + ? position + : Qt.rect(target.x, target.y, target.width, target.height); + const targetOpacity = direction === MinimizeAnimation.Direction.Hide ? 0 : 1; + const targetRotation = direction === MinimizeAnimation.Direction.Hide + ? minimizedRotation + : 0; + const fullGeometry = Qt.rect(target.x, target.y, target.width, target.height); + const remaining = Math.max( + normalizedDistance(currentGeometry.x, targetGeometry.x, + fullGeometry.x, position.x), + normalizedDistance(currentGeometry.y, targetGeometry.y, + fullGeometry.y, position.y), + normalizedDistance(currentGeometry.width, targetGeometry.width, + fullGeometry.width, position.width), + normalizedDistance(currentGeometry.height, targetGeometry.height, + fullGeometry.height, position.height), + Math.abs(currentOpacity - targetOpacity), + Math.abs(currentRotation - targetRotation) / Math.abs(minimizedRotation)); + + const redirectedDuration = duration > 0 + ? Math.max(1, duration * Math.min(1, remaining)) + : 0; + configureAnimation(currentGeometry, targetGeometry, + currentOpacity, targetOpacity, + currentRotation, targetRotation, + redirectedDuration); + mainAnimation.start(); + } + + function normalizedDistance(value, targetValue, firstEndpoint, secondEndpoint) { + const distance = Math.abs(firstEndpoint - secondEndpoint); + return distance > 0 ? Math.abs(value - targetValue) / distance : 0; + } + + function configureAnimation(fromGeometry, toGeometry, fromOpacity, toOpacity, + fromRotation, toRotation, newDuration) { + animationDuration = newDuration; + xAnimation.from = fromGeometry.x; + xAnimation.to = toGeometry.x; + yAnimation.from = fromGeometry.y; + yAnimation.to = toGeometry.y; + widthAnimation.from = fromGeometry.width; + widthAnimation.to = toGeometry.width; + heightAnimation.from = fromGeometry.height; + heightAnimation.to = toGeometry.height; + opacityAnimation.from = fromOpacity; + opacityAnimation.to = toOpacity; + rotationAnimation.from = fromRotation; + rotationAnimation.to = toRotation; + } + + Item { + id: effect + + XdgShadow { + anchors.fill: parent + visible: root.showShadow + cornerRadius: root.target.presentationFrameGeometry.radius + shadowBlur: root.target.shadowBlurRadius + shadowOffsetX: root.target.shadowOffsetX + shadowOffsetY: root.target.shadowOffsetY + shadowColor: root.target.shadowColor + } + + ShaderEffectSource { + anchors.fill: parent + live: false + hideSource: true + sourceItem: root.target + } + } + + ParallelAnimation { + id: mainAnimation + onFinished: { + // Defer the signal emission to avoid deleting animation objects in the same callback stack. + Qt.callLater(function() { + root.finished(); + }) + } + NumberAnimation { + id: xAnimation + target: effect + property: "x" + easing.type: Easing.OutExpo + duration: root.animationDuration + } + NumberAnimation { + id: yAnimation + target: effect + property: "y" + easing.type: Easing.OutExpo + duration: root.animationDuration + } + NumberAnimation { + id: widthAnimation + target: effect + property: "width" + easing.type: Easing.OutExpo + duration: root.animationDuration + } + NumberAnimation { + id: heightAnimation + target: effect + property: "height" + easing.type: Easing.OutExpo + duration: root.animationDuration + } + NumberAnimation { + id: opacityAnimation + target: effect + property: "opacity" + easing.type: Easing.OutExpo + duration: root.animationDuration + } + NumberAnimation { + id: rotationAnimation + target: effect + property: "rotation" + easing.type: Easing.OutExpo + duration: root.animationDuration + } + } + +} diff --git a/src/core/qml/Animations/NewAnimation.qml b/src/core/qml/Animations/NewAnimation.qml new file mode 100644 index 0000000000..2f5c92a6b1 --- /dev/null +++ b/src/core/qml/Animations/NewAnimation.qml @@ -0,0 +1,104 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Treeland +import Waylib.Server +import QtQuick.Effects + +Item { + id: root + + enum Direction { + Show = 1, + Hide + } + + signal finished + + required property SurfaceWrapper target + required property var direction + property int duration: 400 * WaylandServer.animationSpeed + property var enableBlur: false + + x: target.x + y: target.y + width: target.width + height: target.height + transform: [ + Rotation { + id: rotation + origin.x: width / 2 + origin.y: height / 2 + axis { + x: 1 + y: 0 + z: 0 + } + angle: 0 + } + ] + + function start() { + animation.start(); + } + + Loader { + active: root.enableBlur + anchors.fill: parent + sourceComponent: Blur { + anchors.fill: parent + radius: root.target.presentationFrameGeometry.radius + } + } + + ShaderEffectSource { + id: effect + // 50 > shadow width + x: -50 + y: -50 + width: root.target.width + 100 + height: root.target.height + 100 + anchors.centerIn: parent + live: direction === NewAnimation.Direction.Show + hideSource: true + sourceItem: root.target + sourceRect: Qt.rect(effect.x, effect.y, effect.width, effect.height) + } + + ParallelAnimation { + id: animation + + onFinished: { + // Defer the signal emission to avoid deleting animation objects in the same callback stack. + Qt.callLater(function() { + root.finished(); + }) + } + + PropertyAnimation { + target: rotation + property: "angle" + duration: root.duration + from: root.direction === NewAnimation.Direction.Show ? 75 : 0 + to: root.direction !== NewAnimation.Direction.Show ? 75 : 0 + easing.type: Easing.OutExpo + } + PropertyAnimation { + target: root + property: "scale" + duration: root.duration + from: root.direction === NewAnimation.Direction.Show ? 0.3 : 1 + to: root.direction !== NewAnimation.Direction.Show ? 0.3 : 1 + easing.type: Easing.OutExpo + } + PropertyAnimation { + target: root + property: "opacity" + duration: root.duration + from: root.direction === NewAnimation.Direction.Show ? 0 : 1 + to: root.direction !== NewAnimation.Direction.Show ? 0 : 1 + easing.type: root.direction === NewAnimation.Direction.Show ? Easing.Linear : Easing.OutExpo + } + } +} diff --git a/src/core/qml/Animations/ShowDesktopAnimation.qml b/src/core/qml/Animations/ShowDesktopAnimation.qml new file mode 100644 index 0000000000..51b2942586 --- /dev/null +++ b/src/core/qml/Animations/ShowDesktopAnimation.qml @@ -0,0 +1,75 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Effects +import Treeland + +Item { + id: root + + signal finished + + clip: false + + required property var target + required property bool showDesktop + property int duration: 500 * WaylandServer.animationSpeed //500: Initial design requirements + + // The real Decoration (XdgShadow + Border) is a child of `target` laid out at + // the shadow's bounding rect, which extends beyond the target's + // [0,0,width,height] by the shadow blur margin. ShaderEffectSource only + // captures the target's own rect, so the shadow is clipped out of the + // texture, and `hideSource` simultaneously hides the original shadow. Without + // a replacement the shadow would pop in/out only after the fade animation + // finishes instead of following it. Mirror MinimizeAnimation/GeometryAnimation + // and render a shadow that fades together with the captured content. + readonly property bool showShadow: target.visibleDecoration && !target.noDecoration + + function start() { + animation.start(); + } + + Item { + id: effect + x: root.target.x + y: root.target.y + width: root.target.width + height: root.target.height + + XdgShadow { + anchors.fill: parent + visible: root.showShadow + cornerRadius: root.target.presentationFrameGeometry.radius + shadowBlur: root.target.shadowBlurRadius + shadowOffsetX: root.target.shadowOffsetX + shadowOffsetY: root.target.shadowOffsetY + shadowColor: root.target.shadowColor + } + + ShaderEffectSource { + anchors.fill: parent + live: false + hideSource: true + sourceItem: root.target + } + } + + ParallelAnimation { + id: animation + onFinished: { + // Defer the signal emission to avoid deleting animation objects in the same callback stack. + Qt.callLater(function() { + root.finished(); + }) + } + OpacityAnimator { + target: effect + from: showDesktop ? 0 : 1 + to: showDesktop ? 1 : 0 + easing.type: Easing.OutExpo + duration: root.duration + } + } + +} diff --git a/src/core/qml/Animations/WindowTransition.qml b/src/core/qml/Animations/WindowTransition.qml new file mode 100644 index 0000000000..ceeb37b03a --- /dev/null +++ b/src/core/qml/Animations/WindowTransition.qml @@ -0,0 +1,157 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Treeland +import Waylib.Server +import QtQuick.Effects + +Item { + id: root + + enum Direction { + Show = 1, + Hide + } + + required property SurfaceWrapper surface + required property rect fromGeometry + required property rect toGeometry + property int duration: 400 * WaylandServer.animationSpeed + property var enableBlur: false + property var sourceSurface: null + property int direction: 0 + + readonly property bool opening: direction === WindowTransition.Direction.Show + readonly property bool hasIcon: !!sourceSurface + + property real progress: hasIcon && opening ? 0 : 1 + + signal finished + + x: fromGeometry.x + y: fromGeometry.y + width: fromGeometry.width + height: fromGeometry.height + + function start() { + animation.start(); + } + + XdgShadow { + anchors.fill: parent + visible: surface.visibleDecoration && !surface.noDecoration && surface.shadowVisible + opacity: root.progress + cornerRadius: surface.presentationFrameGeometry.radius + shadowBlur: surface.shadowBlurRadius + shadowOffsetX: surface.shadowOffsetX + shadowOffsetY: surface.shadowOffsetY + shadowColor: surface.shadowColor + } + + Loader { + active: root.enableBlur + anchors.fill: parent + sourceComponent: Blur { + anchors.fill: parent + radius: surface.presentationFrameGeometry.radius + } + } + + ShaderEffectSource { + id: windowSource + + // Sampled by the effect below, never drawn directly. + visible: false + live: true + sourceItem: surface + hideSource: true + anchors.fill: parent + } + + SurfaceItemContent { + id: sourceImage + + width: implicitWidth + height: implicitHeight + visible: root.hasIcon + surface: root.sourceSurface + smooth: true + live: true + } + + ShaderEffectSource { + id: iconSource + + visible: false + live: true + sourceItem: sourceImage + hideSource: true + anchors.fill: parent + } + + ShaderEffect { + anchors.fill: parent + + property real progress: root.progress + property variant windowTexture: windowSource + property variant iconTexture: iconSource + fragmentShader: "qrc:/shaders/window_transition.frag.qsb" + } + + ParallelAnimation { + id: animation + + XAnimator { + target: root + duration: root.duration + easing.type: Easing.OutExpo + from: root.fromGeometry.x + to: root.toGeometry.x + } + + YAnimator { + target: root + duration: root.duration + easing.type: Easing.OutExpo + from: root.fromGeometry.y + to: root.toGeometry.y + } + + PropertyAnimation { + target: root + property: "width" + duration: root.duration + easing.type: Easing.OutExpo + from: root.fromGeometry.width + to: root.toGeometry.width + } + + PropertyAnimation { + target: root + property: "height" + duration: root.duration + easing.type: Easing.OutExpo + from: root.fromGeometry.height + to: root.toGeometry.height + } + + // The window's visible weight follows OutExpo, the icon's follows + // 1 - OutExpo. + NumberAnimation { + target: root + property: "progress" + duration: root.duration + easing.type: Easing.OutExpo + from: root.hasIcon && root.opening ? 0 : 1 + to: root.hasIcon && !root.opening ? 0 : 1 + } + + onFinished: { + // Defer the signal emission to avoid deleting animation objects in the same callback stack. + Qt.callLater(function() { + root.finished(); + }) + } + } +} diff --git a/src/core/qml/Border.qml b/src/core/qml/Border.qml new file mode 100644 index 0000000000..6417b63a13 --- /dev/null +++ b/src/core/qml/Border.qml @@ -0,0 +1,39 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + +Item { + id: root + + property real radius: 0 + property real borderWidth: 1 + property color outsideColor: Qt.rgba(0, 0, 0, 0.1) + property color insideColor: Qt.rgba(255, 255, 255, 0.1) + + Rectangle { + id: outsideBorder + anchors { + fill: parent + margins: -border.width + } + + color: "transparent" + border { + color: outsideColor + width: root.borderWidth + } + radius: root.radius > 0 ? root.radius + border.width : 0 + } + + Rectangle { + id: insideBorder + anchors.fill: parent + color: "transparent" + border { + color: insideColor + width: 1 + } + radius: root.radius + } +} diff --git a/src/core/qml/CaptureSelectorLayer.qml b/src/core/qml/CaptureSelectorLayer.qml new file mode 100644 index 0000000000..b239abf764 --- /dev/null +++ b/src/core/qml/CaptureSelectorLayer.qml @@ -0,0 +1,147 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Controls +import QtQuick.Shapes +import Waylib.Server +import Treeland.Capture +import Treeland +import org.deepin.dtk as D + +CaptureSourceSelector { + id: captureSourceSelector + anchors.fill: parent + component SourceToolButton: Item { + required property string iconName + required property int selectionMode + width: 50 + height: 50 + Rectangle { + id: bg + anchors { + fill: parent + margins: 5 + } + color: captureSourceSelector.selectionMode === selectionMode ? Qt.rgba(0,0,0,0.2) : "transparent" + radius: 8 + D.DciIcon { + anchors.fill: bg + name: iconName + sourceSize { + width: 36 + height: 36 + } + } + TapHandler { + gesturePolicy: TapHandler.WithinBounds + onTapped: { + captureSourceSelector.selectionMode = selectionMode + } + } + } + } + + Shape { + id: bgShape + anchors.fill: parent + ShapePath { + strokeWidth: 0 + fillColor: Qt.rgba(0, 0, 0, 0.3) + startX: 0 + startY: 0 + + // TODO: Use PathRectangle in Qt 6.8 + PathLine { x: bgShape.width; y: 0} + PathLine { x: bgShape.width; y: bgShape.height} + PathLine { x: 0; y: bgShape.height } + PathLine { x: 0; y: 0} + + PathMove { + x: selectionRegion.x + y: selectionRegion.y + } + + PathLine { x: selectionRegion.x; y: selectionRegion.bottom} + PathLine { x: selectionRegion.right; y: selectionRegion.bottom} + PathLine { x: selectionRegion.right; y: selectionRegion.y } + PathLine { x: selectionRegion.x; y: selectionRegion.y} + } + } + + Control { + id: captureToolBar + anchors.bottom: parent.bottom + anchors.horizontalCenter: parent.horizontalCenter + anchors.margins: 10 + visible: toolBarModel.count > 1 + Component.onCompleted: { + if (WaylandServer.animationConfig.captureToolbar) + appearAnimation.start() + } + OpacityAnimator { + id: appearAnimation + target: captureToolBar + from: 0.0 + to: 1.0 + duration: 300 + easing.type: Easing.OutExpo + } + contentItem: Row { + Repeater { + model: toolBarModel + SourceToolButton { } + } + } + background: Item { + Rectangle { + id: bgRect + anchors.fill: parent + color: Qt.rgba(16, 16, 16, .1) + radius: 8 + HoverHandler { + cursorShape: Qt.ArrowCursor + blocking: true + } + } + Blur { + anchors.fill: bgRect + radius: 8 + } + D.BoxShadow { + anchors.fill: parent + visible: true + cornerRadius: 8 + shadowColor: Qt.rgba(0, 0, 0, 0.15) + shadowOffsetY: 8 + shadowBlur: 20 + hollow: true + } + Border { + anchors.fill: parent + radius: 8 + insideColor: Qt.rgba(255, 255, 255, 0.05) + } + } + } + + Shape { + width: selectionRegion.width + height: selectionRegion.height + x: selectionRegion.x + y: selectionRegion.y + ShapePath { + strokeWidth: 2 + strokeColor: "white" + fillColor: "transparent" + strokeStyle: ShapePath.DashLine + dashPattern: [ 1, 4 ] + startX: 0 + startY: 0 + PathLine { x: selectionRegion.width; y: 0 } + PathLine { x: selectionRegion.width; y: selectionRegion.height } + PathLine { x: 0; y: selectionRegion.height } + PathLine { x: 0; y: 0} + } + } +} diff --git a/src/core/qml/CaptureSurfaceContent.qml b/src/core/qml/CaptureSurfaceContent.qml new file mode 100644 index 0000000000..29b05eacbc --- /dev/null +++ b/src/core/qml/CaptureSurfaceContent.qml @@ -0,0 +1,9 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + +SurfaceContent { + wrapper: surface?.shellSurface ? (surface.parent?.sourceSurface ?? null) : null + syncSurfaceSizeRatio: false +} diff --git a/src/core/qml/Decoration.qml b/src/core/qml/Decoration.qml new file mode 100644 index 0000000000..5eff838347 --- /dev/null +++ b/src/core/qml/Decoration.qml @@ -0,0 +1,106 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Effects +import Waylib.Server +import Treeland + +Item { + id: root + + required property SurfaceWrapper surface + + readonly property real edgeSize: 10 + + visible: surface && surface.visibleDecoration && surface.visible + x: shadow.boundingRect.x + y: shadow.boundingRect.y + width: shadow.boundingRect.width + height: shadow.boundingRect.height + + MouseArea { + id: resizeArea + + readonly property XWaylandSurface xwaylandSurface: root.surface.shellSurface as XWaylandSurface + + containmentMask: FrameInputMask { + id: resizeMask + geometry: root.surface.frameGeometry + frameItem: root.surface.frameItem + target: resizeArea + resizeMargin: root.edgeSize + } + + // Do not manufacture a frame around an arbitrary X11 input shape. + enabled: surface.isResizable && !surface.prelaunchSplash + && !(xwaylandSurface && xwaylandSurface.hasInputShape) + && surface.type !== SurfaceWrapper.Type.XdgPopup + && surface.type !== SurfaceWrapper.Type.Layer + && surface.type !== SurfaceWrapper.Type.SplashScreen + property int edges: 0 + + anchors { + fill: shadow + margins: -root.edgeSize + } + + hoverEnabled: true + Cursor.shape: { + switch(edges) { + case Qt.TopEdge: + return CursorShape.TopSide + case Qt.RightEdge: + return CursorShape.RightSide + case Qt.BottomEdge: + return CursorShape.BottomSide + case Qt.LeftEdge: + return CursorShape.LeftSide + case Qt.TopEdge | Qt.LeftEdge: + return CursorShape.TopLeftCorner + case Qt.TopEdge | Qt.RightEdge: + return CursorShape.TopRightCorner + case Qt.BottomEdge | Qt.LeftEdge: + return CursorShape.BottomLeftCorner + case Qt.BottomEdge | Qt.RightEdge: + return CursorShape.BottomRightCorner + } + + return Qt.ArrowCursor; + } + + onPositionChanged: function (event) { + edges = resizeMask.edgesAt(Qt.point(event.x, event.y)) + } + + onPressed: function (event) { + // Touch presses need not have a preceding hover event. + edges = resizeMask.edgesAt(Qt.point(event.x, event.y)) + if (edges) + surface.resizeRequested(edges, /*overrideCursor=*/true) + } + } + + XdgShadow { + id: shadow + width: surface.presentationFrameGeometry.rect.width + height: surface.presentationFrameGeometry.rect.height + cornerRadius: surface.presentationFrameGeometry.radius + anchors.centerIn: parent + visible: surface.shadowVisible + shadowBlur: surface.shadowBlurRadius + shadowOffsetX: surface.shadowOffsetX + shadowOffsetY: surface.shadowOffsetY + shadowColor: surface.shadowColor + } + + Border { + visible: surface.visibleDecoration && surface.borderVisible + parent: surface.prelaunchSplash ? surface.prelaunchSplash : surface.surfaceItem + z: SurfaceItem.ZOrder.ContentItem + 1 + anchors.fill: parent + radius: surface.presentationFrameGeometry.radius + outsideColor: surface.borderColor + borderWidth: surface.borderWidth + } +} diff --git a/src/core/qml/DockPreview.qml b/src/core/qml/DockPreview.qml new file mode 100644 index 0000000000..e6499cd1fa --- /dev/null +++ b/src/core/qml/DockPreview.qml @@ -0,0 +1,820 @@ +// SPDX-FileCopyrightText: 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + +import Treeland +import Treeland.Protocols + +Item { + id: root + required property DesktopEnvironment desktop + property int aniDuration: 350 + property bool enableAnimation: aniDuration > 0 && WaylandServer.animationConfig.dockPreview + // How long the closing window's picture takes to disappear. Every slot and + // layer around it keeps using aniDuration; only the picture goes early. + property int closeContentDuration: 100 + // Gap between two slots; the highlight frame is drawn in it. + property int spacing: PopoverStyle.previewSpacing + + // Inset of the thumbnail content from every panel edge. + readonly property int thumbnailPadding: PopoverStyle.previewPanelPadding + // Corner radii follow the system window radius: the panel uses it as is, + // items and the tooltip use half of it. + readonly property int panelRadius: desktop.config.windowRadius + readonly property int itemRadius: Math.floor(desktop.config.windowRadius / 2) + readonly property int tooltipRadius: itemRadius + readonly property int screenEdgeMargin: 10 + property bool enableBlur: true + property bool enableShadow: GraphicsInfo.api !== GraphicsInfo.Software + property bool enableBorder: true + // set by show() + property var target + property point pos + property int direction + function isHorizontalDirection(direction) { + return direction !== ForeignToplevelManagerInterfaceV3.PreviewDirection.left + && direction !== ForeignToplevelManagerInterfaceV3.PreviewDirection.right; + } + readonly property bool isHorizontal: root.isHorizontalDirection(root.direction) + // auto update by binding + readonly property var outputItem: target?.ownsOutput?.outputItem ?? null + readonly property int screenWidth: outputItem && outputItem.width > 0 ? outputItem.width + : 9999 + readonly property int screenHeight: outputItem && outputItem.height > 0 ? outputItem.height + : 9999 + property size outPutSize: Qt.size(root.screenWidth, root.screenHeight) + property point outPutPos: { + if (!outputItem || !root.parent) + return Qt.point(0, 0); + return outputItem.mapToItem(root.parent, 0, 0); + } + // set by showTooltip(): the client-drawn tooltip surface + property var tooltipSurface: null + onTooltipSurfaceChanged: tooltipPresent.applySurface(root.tooltipSurface) + + property bool isShowing: false + + // The three are peers: the frame holds whichever one was asked for, and a + // switch between any two is a hand-over, not a mode change. + enum Presentation { Tooltip, Thumbnail, List } + property int requestedPresentation: DockPreview.Presentation.Tooltip + // How far each presentation is into the frame. The tooltip has no reveal. + property real thumbnailReveal: 0 + property real listReveal: 0 + // Which side of the frame the preview content stays glued to. + property bool contentPinToLeft: true + // A bottom dock keeps the list growing out of the dock edge. + readonly property bool listPinnedToBottom: + root.direction === ForeignToplevelManagerInterfaceV3.PreviewDirection.bottom + property var desiredSurfaces: [] + onDesiredSurfacesChanged: root.syncSurfaces() + + readonly property real titleRowHeight: PopoverStyle.previewTitleIconSize + readonly property int titleTopPadding: PopoverStyle.previewTitleTopPadding + // Chrome the thumbnail adds above its content; only it carries a header. + readonly property real titleRowChrome: root.titleRowHeight + PopoverStyle.previewTitleGap + + // Picture box of one slot: fixed short side, clamped aspect ratio. + function previewSlotSize(wrapper, horizontal) { + const minSide = PopoverStyle.previewSlotMinSide; + const maxSide = PopoverStyle.previewSlotMaxSide; + const shortSide = PopoverStyle.previewSlotShortSide; + // Whole pixels only. + if (horizontal) { + if (!wrapper || !(wrapper.height > 0)) + return Qt.size(minSide, shortSide); + return Qt.size(Math.round(Math.max(minSide, Math.min(maxSide, + shortSide * wrapper.width / wrapper.height))), + shortSide); + } + if (!wrapper || !(wrapper.width > 0)) + return Qt.size(maxSide, minSide); + return Qt.size(maxSide, Math.round(Math.max(minSide, Math.min(shortSide, + maxSide * wrapper.height / wrapper.width)))); + } + + // Where an item of the given size scales from: the edge of the frame that + // faces the dock, so the popover grows out of it instead of its centre. + function scaleOriginFor(width, height) { + switch (root.direction) { + case ForeignToplevelManagerInterfaceV3.PreviewDirection.left: + return Qt.point(0, height / 2); + case ForeignToplevelManagerInterfaceV3.PreviewDirection.right: + return Qt.point(width, height / 2); + case ForeignToplevelManagerInterfaceV3.PreviewDirection.top: + return Qt.point(width / 2, 0); + default: // bottom + return Qt.point(width / 2, height); + } + } + + // The window's picture fitted into the slot and centered. + function naturalContentSize(slotRect, sourceWidth, sourceHeight) { + if (!slotRect || !(slotRect.width > 0) || !(slotRect.height > 0) + || !(sourceWidth > 0) || !(sourceHeight > 0)) + return Qt.size(0, 0); + + const scale = Math.min(slotRect.width / sourceWidth, + slotRect.height / sourceHeight); + return Qt.size(Math.round(sourceWidth * scale), Math.round(sourceHeight * scale)); + } + + // Where every window sits in the content, in content coordinates. Both the + // natural size and the slot targets read this one rule. + function slotRects(wrappers) { + const rects = [ ]; + let offset = 0; + for (let i = 0; i < wrappers.length; ++i) { + const wrapper = wrappers[i]; + if (!wrapper) + continue; + + const size = root.previewSlotSize(wrapper, root.isHorizontal); + if (rects.length > 0) + offset += root.spacing; + if (root.isHorizontal) { + rects.push(Qt.rect(offset, 0, size.width, size.height)); + offset += size.width; + } else { + rects.push(Qt.rect(0, offset, size.width, size.height)); + offset += size.height; + } + } + return rects; + } + + // Natural size of a preview layout for a given set of surfaces. Pure, so a + // switch can know the final frame size before any layer or slot exists. + function contentSizeFor(wrappers) { + const rects = root.slotRects(wrappers); + if (rects.length === 0) + return Qt.size(0, 0); + + let cross = 0; + for (let i = 0; i < rects.length; ++i) { + const rect = rects[i]; + cross = Math.max(cross, root.isHorizontal ? rect.height : rect.width); + } + + const last = rects[rects.length - 1]; + return root.isHorizontal + ? Qt.size(last.x + last.width, cross) + : Qt.size(cross, last.y + last.height); + } + + readonly property int listPanelWidth: PopoverStyle.listPanelWidth + readonly property int listPanelPadding: PopoverStyle.listPanelPadding + readonly property int listContentWidth: root.listPanelWidth - 2 * root.listPanelPadding + readonly property int listRowHeight: PopoverStyle.listRowHeight + readonly property int listRowSpacing: PopoverStyle.listRowSpacing + readonly property int listMaxFrameHeight: PopoverStyle.listMaxFrameHeight + readonly property int listMaxContentHeight: + Math.max(0, root.listMaxFrameHeight - 2 * root.listPanelPadding) + // What the list can actually show: the frame cap and the output both bound + // it, so a short output never hides rows the scroller cannot reach. + readonly property real listMaxViewportHeight: Math.max(0, + Math.min(root.listMaxContentHeight, + root.outPutSize.height - 2 * root.screenEdgeMargin + - 2 * root.listPanelPadding)) + + function listRowRects(wrappers) { + const rects = [ ]; + let offset = 0; + for (let i = 0; i < wrappers.length; ++i) { + const wrapper = wrappers[i]; + if (!wrapper) + continue; + + if (rects.length > 0) + offset += root.listRowSpacing; + rects.push(Qt.rect(0, offset, root.listContentWidth, root.listRowHeight)); + offset += root.listRowHeight; + } + return rects; + } + + function listRowsHeight(wrappers) { + const rects = root.listRowRects(wrappers); + if (rects.length === 0) + return 0; + const last = rects[rects.length - 1]; + return last.y + last.height; + } + + function listContentSizeFor(wrappers) { + return Qt.size(root.listContentWidth, + Math.min(root.listMaxContentHeight, + root.listRowsHeight(wrappers))); + } + + // What each presentation measures itself from. + readonly property size thumbnailContentSize: { + const content = root.contentSizeFor(root.desiredSurfaces); + return content.width > 0 && content.height > 0 + ? content : root.lastThumbnailContentSize; + } + property size lastThumbnailContentSize: Qt.size(0, 0) + onThumbnailContentSizeChanged: { + if (root.thumbnailContentSize.width > 0) + root.lastThumbnailContentSize = root.thumbnailContentSize; + } + + readonly property size listContentSize: { + const size = root.listContentSizeFor(root.desiredSurfaces); + return size.height > 0 ? size : root.lastListContentSize; + } + property size lastListContentSize: Qt.size(0, 0) + onListContentSizeChanged: { + if (root.listContentSize.height > 0) + root.lastListContentSize = root.listContentSize; + } + + // Natural size of the tooltip the frame is measured from: the one on + // screen, or the one that just left. + readonly property size tooltipSize: tooltipPresent.naturalSize + + function previewFrameSizeFor(contentSize, titleChrome, padding, topPadding) { + const top = topPadding ?? padding; + const maxContentWidth = Math.max(0, root.outPutSize.width + - 2 * root.screenEdgeMargin + - 2 * padding); + const maxContentHeight = Math.max(0, root.outPutSize.height + - 2 * root.screenEdgeMargin + - top + - padding + - titleChrome); + return Qt.size(Math.min(contentSize.width, maxContentWidth) + 2 * padding, + Math.min(contentSize.height, maxContentHeight) + + titleChrome + top + padding); + } + + readonly property size targetFrameSize: + root.requestedPresentation === DockPreview.Presentation.Tooltip + ? root.tooltipSize + : root.requestedPresentation === DockPreview.Presentation.List + ? root.previewFrameSizeFor(root.listContentSize, 0, + PopoverStyle.listPanelPadding) + : root.previewFrameSizeFor(root.thumbnailContentSize, + root.titleRowChrome, + root.thumbnailPadding, + root.titleTopPadding) + + readonly property size previewViewport: { + const frame = root.previewFrameSizeFor(root.thumbnailContentSize, + root.titleRowChrome, + root.thumbnailPadding, + root.titleTopPadding); + return Qt.size(Math.max(0, frame.width - 2 * root.thumbnailPadding), + Math.max(0, frame.height - root.titleTopPadding + - root.thumbnailPadding + - root.titleRowChrome)); + } + + // The frame is the only animated geometry. + property real frameWidth: root.targetFrameSize.width + property real frameHeight: root.targetFrameSize.height + + // Set while a window is resizing: the frame snaps with the strip. + property bool windowResizing: false + function noteWindowResize() { + root.windowResizing = true; + resizeSettle.restart(); + } + + Timer { + id: resizeSettle + interval: 120 + onTriggered: root.windowResizing = false + } + + // Fade of the shell and of the preview content it carries. + // Tooltip layers fade on their own. + property real shellFade: 0 + + function setShowing(showing) { + root.isShowing = showing; + const entersFromNothing = showing && !root.visible; + if (showing) + root.visible = true; + if (entersFromNothing + && root.requestedPresentation !== DockPreview.Presentation.Tooltip) { + // Snap to the start value, then let the assignment below animate. + surface.shellScaleAnimated = false; + surface.shellScale = 0.1; + surface.shellScaleAnimated = true; + } + // The states used to carry these two numbers; the Behaviours act on the + // assignment, so entry and exit read the same here as everywhere else. + root.shellFade = showing ? 1 : 0; + surface.shellScale = showing ? 1 : 0.5; + // Without the fade, nothing would run the completion below. + if (!showing && !root.enableAnimation) + root.finishHide(); + } + + function finishHide() { + if (root.isShowing) + return; + root.visible = false; + root.desiredSurfaces = [ ]; + root.resetPresentations(); + root.tooltipSurface = null; + } + + // The shell fade also owns the popover's lifetime: it hides the item (and + // drops the state it kept alive) once the fade out is over. + Behavior on shellFade { + enabled: root.enableAnimation + SequentialAnimation { + NumberAnimation { + id: shellFadeAnimation + duration: root.aniDuration + easing.type: Easing.OutExpo + } + ScriptAction { + script: root.finishHide() + } + } + } + + NumberAnimation { + id: thumbnailRevealAnimation + target: root + property: "thumbnailReveal" + duration: root.aniDuration + easing.type: Easing.OutExpo + onFinished: root.settlePresentations() + } + + NumberAnimation { + id: listRevealAnimation + target: root + property: "listReveal" + duration: root.aniDuration + easing.type: Easing.OutExpo + onFinished: root.settlePresentations() + } + + // Drive both presentations towards the one that was asked for. One that is + // asked for again while it is still leaving picks up from where it is + // instead of jumping back to where it started. + function updateReveals() { + const animate = root.visible && root.enableAnimation; + root.setReveal(thumbnailRevealAnimation, "thumbnailReveal", + root.requestedPresentation === DockPreview.Presentation.Thumbnail ? 1 : 0, + animate); + root.setReveal(listRevealAnimation, "listReveal", + root.requestedPresentation === DockPreview.Presentation.List ? 1 : 0, + animate); + // A reveal that snapped has no animation to report its end. + if (!animate) + root.settlePresentations(); + } + + function setReveal(animation, propertyName, value, animate) { + if (!animate) { + animation.stop(); + root[propertyName] = value; + return; + } + if (animation.running) { + // The same target is already animating: leave it alone. + if (animation.to === value) + return; + } else if (root[propertyName] === value) { + return; + } + animation.stop(); + animation.from = root[propertyName]; + animation.to = value; + animation.start(); + } + + // A presentation that finished leaving is dropped; once every preview one + // has left, the windows are no longer needed either. + function settlePresentations() { + if (!thumbnailPresent || !listPresent) + return; + if (root.thumbnailReveal === 0 + && root.requestedPresentation !== DockPreview.Presentation.Thumbnail) + thumbnailPresent.clear(); + if (root.listReveal === 0 + && root.requestedPresentation !== DockPreview.Presentation.List) + listPresent.clear(); + if (root.requestedPresentation === DockPreview.Presentation.Tooltip + && root.thumbnailReveal === 0 && root.listReveal === 0 + && root.desiredSurfaces.length > 0) + root.desiredSurfaces = [ ]; + } + + function resetPresentations() { + thumbnailRevealAnimation.stop(); + listRevealAnimation.stop(); + root.thumbnailReveal = 0; + root.listReveal = 0; + root.requestedPresentation = DockPreview.Presentation.Tooltip; + thumbnailPresent.clear(); + listPresent.clear(); + } + + Behavior on frameWidth { + enabled: root.visible && root.enableAnimation && !root.windowResizing + NumberAnimation { + duration: root.aniDuration + easing.type: Easing.OutExpo + } + } + + Behavior on frameHeight { + enabled: root.visible && root.enableAnimation && !root.windowResizing + NumberAnimation { + duration: root.aniDuration + easing.type: Easing.OutExpo + } + } + + // The rect each presentation fills: the frame minus its own padding. + readonly property rect thumbnailContentRect: Qt.rect( + root.thumbnailPadding, + root.titleTopPadding, + Math.max(0, root.frameWidth - 2 * root.thumbnailPadding), + Math.max(0, root.frameHeight - root.titleTopPadding - root.thumbnailPadding)) + readonly property rect listContentRect: Qt.rect( + root.listPanelPadding, + root.listPanelPadding, + Math.max(0, root.frameWidth - 2 * root.listPanelPadding), + Math.max(0, root.frameHeight - 2 * root.listPanelPadding)) + + visible: false + + // Shared with the components that log on behalf of the popover. + readonly property LoggingCategory loggingCategory: qLcDockPreview + + LoggingCategory { + id: qLcDockPreview + name: "treeland.qml.dockpreview" + defaultLogLevel: LoggingCategory.Info + } + + /* --- model begin --- */ + // `desiredSurfaces` is the authority. The slot instances only follow it: + // these helpers edit the list alone, and the change handler syncs them + // afterwards. + function removeSurface(surfaceWrapper) { + if (!surfaceWrapper) + return; + + const index = root.desiredSurfaces.indexOf(surfaceWrapper); + if (index < 0) + return; + + // Copy instead of splice: the assignment is what triggers the change. + const surfaces = root.desiredSurfaces.slice(); + surfaces.splice(index, 1); + root.desiredSurfaces = surfaces; + } + + function activateWindow(surfaceWrapper) { + if (!surfaceWrapper) + return; + console.debug(qLcDockPreview, "activate preview window: ", surfaceWrapper) + root.desktop.activateWindow(surfaceWrapper) + root.desktop.windowManagement.leaveDockPreview(root.target.shellSurface.surface) + root.close(); + } + + function previewWindow(surfaceWrapper) { + if (!surfaceWrapper) + return; + console.debug(qLcDockPreview, "start preview window: ", surfaceWrapper) + root.desktop.workspace.startPreviewing(surfaceWrapper); + } + + function stopPreviewWindow() { + console.debug(qLcDockPreview, "stop preview window") + root.desktop.workspace.stopPreviewing(); + } + + function closeAllWindow() { + console.debug(qLcDockPreview, "close all preview windows") + // Only ask; every slot goes away with the window it shows. + for (const surfaceWrapper of root.desiredSurfaces) { + if (surfaceWrapper && surfaceWrapper.shellSurface) + surfaceWrapper.shellSurface.close(); + } + } + + function closeSpecialWindow(surfaceWrapper) { + if (!surfaceWrapper) + return; + + console.debug(qLcDockPreview, "close a special window: ", surfaceWrapper) + // Only ask; the slot goes away when the window really does. + if (surfaceWrapper.shellSurface) + surfaceWrapper.shellSurface.close() + } + + // The requested presentation owns the instances; it tells us when the + // window list ran empty so the popover can close instead of showing an + // empty frame. + function syncSurfaces() { + if (!thumbnailPresent || !listPresent) + return; + + switch (root.requestedPresentation) { + case DockPreview.Presentation.Thumbnail: + thumbnailPresent.sync(); + break; + case DockPreview.Presentation.List: + listPresent.sync(); + break; + default: + break; + } + } + + function handleEmptied(present) { + // Closing keeps the presentation until the shell has faded out; running + // out of windows while hidden just drops it. + if (root.isShowing && root.requestedPresentation !== DockPreview.Presentation.Tooltip) { + present.freezeForClose(); + root.close(); + return; + } + present.clear(); + } + + function show(surfaces, target, pos, direction, isList) { + console.info(qLcDockPreview, "start show windows: ", surfaces) + // Drop empty entries once, at the only entry that takes an external list. + const windows = []; + for (let i = 0; i < surfaces.length; ++i) { + if (surfaces[i]) + windows.push(surfaces[i]); + } + // A request that resolves to no window has nothing to switch to, so it + // takes the popover down whatever presentation is on screen. + if (windows.length === 0) { + if (root.isShowing) + root.close(); + return; + } + + const wasTooltip = root.requestedPresentation === DockPreview.Presentation.Tooltip; + root.parent = target.parent; + + // Keep the slots anchored to the left as much as possible, many + // animations rely on it. Only a `dock preview` <-> `tooltip` switch may + // anchor them to the other side. + if (root.isShowing && wasTooltip) + root.contentPinToLeft = root.pos?.x - pos?.x <= 0; + else + root.contentPinToLeft = true + + root.pos = pos; + root.direction = direction; + root.target = target; + root.requestedPresentation = isList + ? DockPreview.Presentation.List + : DockPreview.Presentation.Thumbnail; + root.desiredSurfaces = windows; + // A popover that is already on screen switches with a curve; one that is + // entering from nothing lands on the final layout right away. + root.updateReveals(); + root.setShowing(true); + root.tooltipSurface = null; + } + + function showTooltip(surfaceWrapper, target, pos, direction) { + console.info(qLcDockPreview, "start show tooltip: ", surfaceWrapper, target, pos, direction) + root.parent = target.parent; + if (root.isShowing + && root.requestedPresentation !== DockPreview.Presentation.Tooltip) + root.contentPinToLeft = root.pos?.x - pos?.x >= 0; + else + root.contentPinToLeft = true + + root.pos = pos; + root.direction = direction; + root.target = target; + // Publish the surface before the presentation: tooltipSize reads the + // live layer, and switching presentation first would let the frame + // target fall back to the previous tooltip for a moment. + root.tooltipSurface = surfaceWrapper; + root.requestedPresentation = DockPreview.Presentation.Tooltip; + // Same as show(): a switch animates the presentation away, an entry + // from nothing starts with it already collapsed. + root.updateReveals(); + root.setShowing(true); + } + + function close() { + console.info(qLcDockPreview, "stop dock preview") + root.setShowing(false); + root.tooltipSurface = null; + } + /* --- model end --- */ + + /* --- global position begin --- */ + implicitWidth: root.targetFrameSize.width + implicitHeight: root.targetFrameSize.height + + // Where the frame settles in the parent's coordinates. + readonly property real unadjustedFrameX: { + if (!root.target) + return 0; + + const frameWidth = root.targetFrameSize.width; + switch (root.direction) { + case ForeignToplevelManagerInterfaceV3.PreviewDirection.left: + return root.target.x + root.pos.x; + case ForeignToplevelManagerInterfaceV3.PreviewDirection.right: + return root.target.x + root.pos.x - frameWidth; + default: // bottom / top: the frame's center follows the dock icon + return root.target.x + root.pos.x - frameWidth / 2; + } + } + readonly property real unadjustedFrameY: { + if (!root.target) + return 0; + + const frameHeight = root.targetFrameSize.height; + switch (root.direction) { + case ForeignToplevelManagerInterfaceV3.PreviewDirection.bottom: + return root.target.y + root.pos.y - frameHeight; + case ForeignToplevelManagerInterfaceV3.PreviewDirection.top: + return root.target.y + root.pos.y; + default: // left / right: the frame's center follows the dock icon + return root.target.y + root.pos.y - frameHeight / 2; + } + } + + // Keep the settled frame inside the output, with a margin on every side. + readonly property real horizontalCenterOffsetAdjust: { + const leftSpace = root.unadjustedFrameX - root.outPutPos.x; + if (leftSpace < 0) + return -leftSpace + root.screenEdgeMargin; + + const rightSpace = root.outPutPos.x + root.outPutSize.width + - (root.unadjustedFrameX + root.targetFrameSize.width); + if (rightSpace < 0) + return rightSpace - root.screenEdgeMargin; + + return 0; + } + readonly property real verticalCenterOffsetAdjust: { + const topSpace = root.unadjustedFrameY - root.outPutPos.y; + if (topSpace < 0) + return -topSpace + root.screenEdgeMargin; + + const bottomSpace = root.outPutPos.y + root.outPutSize.height + - (root.unadjustedFrameY + root.targetFrameSize.height); + if (bottomSpace < 0) + return bottomSpace - root.screenEdgeMargin; + + return 0; + } + + // The state anchors stay here on purpose: they tie the surface's + // dock-facing edge to root's, which is the one piece of the state that + // spans two items. Everything that only depends on the frame's own size is + // computed by the surface itself. + states: [ + State { + name: "dock_bottom" + when: direction === ForeignToplevelManagerInterfaceV3.PreviewDirection.bottom + AnchorChanges { + target: root + anchors.horizontalCenter: root.target?.horizontalCenter + anchors.bottom: root.target?.top + } + AnchorChanges { + target: surface + anchors.horizontalCenter: root.horizontalCenter + anchors.bottom: root.bottom + } + PropertyChanges { + target: root + anchors.horizontalCenterOffset: root.pos.x - root.target?.width / 2 + horizontalCenterOffsetAdjust + anchors.bottomMargin: -root.pos.y + restoreEntryValues: false + } + }, + State { + name: "dock_left" + when: direction === ForeignToplevelManagerInterfaceV3.PreviewDirection.left + AnchorChanges { + target: root + anchors.verticalCenter: root.target?.verticalCenter + anchors.left: root.target?.left + } + AnchorChanges { + target: surface + anchors.verticalCenter: root.verticalCenter + anchors.left: root.left + } + PropertyChanges { + target: root + anchors.verticalCenterOffset: root.pos.y - root.target?.height / 2 + verticalCenterOffsetAdjust + anchors.leftMargin: root.pos.x + restoreEntryValues: false + } + }, + State { + name: "dock_top" + when: direction === ForeignToplevelManagerInterfaceV3.PreviewDirection.top + AnchorChanges { + target: root + anchors.horizontalCenter: root.target?.horizontalCenter + anchors.top: root.target?.top + } + AnchorChanges { + target: surface + anchors.horizontalCenter: root.horizontalCenter + anchors.top: root.top + } + PropertyChanges { + target: root + anchors.horizontalCenterOffset: root.pos.x - root.target?.width / 2 + horizontalCenterOffsetAdjust + anchors.topMargin: root.pos.y + restoreEntryValues: false + } + }, + State { + name: "dock_right" + when: direction === ForeignToplevelManagerInterfaceV3.PreviewDirection.right + AnchorChanges { + target: root + anchors.verticalCenter: root.target?.verticalCenter + anchors.right: root.target?.left + } + AnchorChanges { + target: surface + anchors.verticalCenter: root.verticalCenter + anchors.right: root.right + } + PropertyChanges { + target: root + anchors.verticalCenterOffset: root.pos.y - root.target?.height / 2 + verticalCenterOffsetAdjust + anchors.rightMargin: -root.pos.x + restoreEntryValues: false + } + } + ] + + Behavior on anchors.horizontalCenterOffset { + enabled: root.visible && root.enableAnimation + NumberAnimation { + duration: root.aniDuration + easing.type: Easing.OutExpo + } + } + + Behavior on anchors.verticalCenterOffset { + enabled: root.visible && root.enableAnimation + NumberAnimation { + duration: root.aniDuration + easing.type: Easing.OutExpo + } + } + /* --- global position end --- */ + + // These parts take the controller as a plain QtObject: a typed reference + // would make the popover files depend on each other's types, which the QML + // loader rejects. + DockPreviewSurface { + id: surface + parent: root.parent + preview: root + } + + // The thumbnail presentation: the title row and the slots, inside the + // surface's content host. + DockPreviewThumbnailPresent { + id: thumbnailPresent + parent: surface.contentHost + preview: root + hovered: surface.titleHovered + onEmptied: root.handleEmptied(thumbnailPresent) + } + + DockPreviewListPresent { + id: listPresent + parent: surface.contentHost + preview: root + onEmptied: root.handleEmptied(listPresent) + } + + // The tooltip presentation: the surface on screen and the layers it left. + DockPreviewTooltipPresent { + id: tooltipPresent + preview: root + host: surface.contentHost + layerComponent: Component { + DockPreviewTooltipLayer { + preview: root + } + } + } +} diff --git a/src/core/qml/DockPreview/DockPreviewCloseButton.qml b/src/core/qml/DockPreview/DockPreviewCloseButton.qml new file mode 100644 index 0000000000..0215d21fe0 --- /dev/null +++ b/src/core/qml/DockPreview/DockPreviewCloseButton.qml @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + +import Treeland +import org.deepin.dtk 1.0 as D + +// The round close button the preview uses, both on a slot and in the title row. +D.ToolButton { + id: closeButton + + property int maximumSize: PopoverStyle.closeButtonMaxSize + // Rounded down to an even number so the circle keeps a whole-pixel centre. + readonly property int diameter: 2 * Math.floor(maximumSize / 2) + + implicitWidth: diameter + implicitHeight: diameter + padding: 0 + icon.name: "close" + icon.width: Math.round(diameter * 0.6) + icon.height: Math.round(diameter * 0.6) + // DTK paints the background as a rounded BoxPanel; half the size is a circle. + Binding { + target: closeButton.background + property: "radius" + value: closeButton.diameter / 2 + when: closeButton.background + } +} diff --git a/src/core/qml/DockPreview/DockPreviewListLayer.qml b/src/core/qml/DockPreview/DockPreviewListLayer.qml new file mode 100644 index 0000000000..d26f91cc1a --- /dev/null +++ b/src/core/qml/DockPreview/DockPreviewListLayer.qml @@ -0,0 +1,241 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + +import Treeland + +// One list instance: the rows for one dock icon. A switch to another icon +// starts a new instance and fades this one out, so the rows never change what +// they show under the pointer. +Item { + id: listLayer + + required property QtObject preview + required property QtObject listPresent + + property var rows: [] + property var fadingRows: [] + property real rowsHeight: 0 + property bool fadingOut: false + + // Input follows the live layer only: an outgoing list keeps drawing while + // it fades, but must not preview or activate windows. + readonly property bool interactive: + preview.requestedPresentation === DockPreview.Presentation.List + && listPresent.liveLayer === listLayer + && !listLayer.fadingOut + + // The rows scroll past this height; the frame never grows for them. + readonly property real viewportHeight: + Math.min(preview.listMaxViewportHeight, listLayer.rowsHeight) + // A settled list draws at its own size so the frame animates around it; + // fitting it would shrink the list every time a row is added or removed. + readonly property bool drawsAtOwnSize: + preview.listReveal === 1 + && listPresent.liveLayer === listLayer + && listPresent.fadingLayers.length === 0 + readonly property real fitScale: { + if (listLayer.drawsAtOwnSize) + return 1; + if (!(width > 0) || !(height > 0)) + return 1; + return Math.max(0, Math.min(1, preview.listContentRect.width / width, + preview.listContentRect.height / height)); + } + + width: preview.listContentWidth + height: listLayer.viewportHeight + // Left aligned. A fitted list also keeps its bottom on the frame's content + // bottom, so it grows out of the dock edge. + y: (listLayer.drawsAtOwnSize || !preview.listPinnedToBottom) + ? 0 + : Math.max(0, preview.listContentRect.height - listLayer.height * listLayer.fitScale) + transform: Scale { + origin.x: 0 + origin.y: 0 + xScale: listLayer.fitScale + yScale: xScale + } + + function createRow() { + return rowComponent.createObject(rowLayer); + } + + function dropRow(row) { + if (!row) + return; + + const index = listLayer.fadingRows.indexOf(row); + if (index >= 0) { + const fading = listLayer.fadingRows.slice(); + fading.splice(index, 1); + listLayer.fadingRows = fading; + } + row.destroy(); + } + + // Height the live layout needs. Rows collapsing out do not count: the frame + // is already shrinking around them. + function refreshHeight() { + let extent = 0; + for (let i = 0; i < listLayer.rows.length; ++i) { + const row = listLayer.rows[i]; + extent = Math.max(extent, row.yTo + row.height); + } + listLayer.rowsHeight = extent; + // A shorter list must not leave the scroller past its end. + const maxContentY = scroller.contentHeight - scroller.height; + scroller.contentY = Math.max(0, Math.min(scroller.contentY, + maxContentY)); + } + + // Bring the rows in line with `wrappers`. A row is never reused for another + // window: the title would change under the pointer. + function sync(wrappers, instant) { + const rects = preview.listRowRects(wrappers); + const previous = listLayer.rows; + const used = new Array(previous.length).fill(false); + const live = [ ]; + + for (let i = 0; i < wrappers.length; ++i) { + let kept = null; + for (let k = 0; k < previous.length; ++k) { + if (!used[k] && previous[k].wrapper === wrappers[i]) { + used[k] = true; + kept = previous[k]; + break; + } + } + if (kept) { + kept.retarget(wrappers[i], rects[i].y); + live.push(kept); + continue; + } + + const created = listLayer.createRow(); + if (!created) { + console.warn(preview.loggingCategory, "failed to create a preview row"); + continue; + } + const startTop = live.length ? live[live.length - 1].y + : rects[i].y; + created.enter(wrappers[i], startTop, rects[i].y, instant); + live.push(created); + } + + const fading = listLayer.fadingRows.slice(); + for (let k = 0; k < previous.length; ++k) { + if (used[k]) + continue; + + // Close into the row that takes its place: the last row always has + // one before it, so `rects` is never empty here. + const row = previous[k]; + const target = rects[Math.min(row.rowIndex, rects.length - 1)].y; + if (row.collapseTo(target)) + fading.push(row); + } + listLayer.fadingRows = fading; + + listLayer.rows = live; + for (let i = 0; i < live.length; ++i) + live[i].rowIndex = i; + + listLayer.refreshHeight(); + } + + // The shell is fading out with no windows left: stop the rows where they + // are and let the fade take them. + function freezePositions() { + for (let i = 0; i < listLayer.rows.length; ++i) + listLayer.rows[i].freezePosition(); + for (let i = 0; i < listLayer.fadingRows.length; ++i) + listLayer.fadingRows[i].freezePosition(); + } + + function fadeIn() { + fadingOut = false; + if (!preview.enableAnimation) { + opacity = 1; + return; + } + opacity = 0; + fadeAnimation.from = 0; + fadeAnimation.to = 1; + fadeAnimation.restart(); + } + + function fadeOut() { + fadingOut = true; + if (!preview.enableAnimation) { + listPresent.dropLayer(listLayer); + return; + } + fadeAnimation.from = opacity; + fadeAnimation.to = 0; + fadeAnimation.restart(); + } + + Flickable { + id: scroller + + width: listLayer.width + height: listLayer.viewportHeight + contentWidth: width + contentHeight: listLayer.rowsHeight + enabled: listLayer.interactive + interactive: contentHeight > height + boundsBehavior: Flickable.StopAtBounds + // The frame is the only clip: a collapsing or scrolled-out row is cut + // there, not by the list. + clip: false + + Item { + id: rowLayer + width: scroller.width + height: scroller.contentHeight + } + + HoverHandler { + enabled: listLayer.interactive + cursorShape: Qt.ArrowCursor + onHoveredChanged: { + if (!hovered) + preview.stopPreviewWindow(); + } + } + } + + // The list only scrolls up and down; a chevron floats over each end that + // still has rows hidden past it. + DockPreviewScrollHint { + view: scroller + horizontal: false + duration: preview.aniDuration + enableAnimation: preview.enableAnimation + enabled: listLayer.interactive + interactive: listLayer.opacity === 1 + } + + Component { + id: rowComponent + + DockPreviewListRow { + preview: listLayer.preview + layerItem: listLayer + } + } + + NumberAnimation { + id: fadeAnimation + target: listLayer + property: "opacity" + duration: preview.aniDuration + easing.type: Easing.OutExpo + onFinished: { + if (listLayer.fadingOut) + listPresent.dropLayer(listLayer); + } + } +} diff --git a/src/core/qml/DockPreview/DockPreviewListPresent.qml b/src/core/qml/DockPreview/DockPreviewListPresent.qml new file mode 100644 index 0000000000..bab03de1d4 --- /dev/null +++ b/src/core/qml/DockPreview/DockPreviewListPresent.qml @@ -0,0 +1,128 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + +Item { + id: root + + objectName: "listPresent" + required property QtObject preview + + property var liveLayer: null + property var fadingLayers: [] + + // A signal instead of a close() call: whether an empty list closes the + // popover or only clears the list is the controller's decision. + signal emptied() + + x: preview.listContentRect.x + y: preview.listContentRect.y + width: preview.listContentRect.width + height: preview.listContentRect.height + // The shell fade covers enter and leave; the reveal adds the hand-over. + opacity: preview.shellFade * preview.listReveal + visible: root.liveLayer !== null || root.fadingLayers.length > 0 + clip: true + + function createLayer() { + return layerComponent.createObject(root); + } + + function dropLayer(layer) { + if (!layer) + return; + + const index = root.fadingLayers.indexOf(layer); + if (index >= 0) { + const fading = root.fadingLayers.slice(); + fading.splice(index, 1); + root.fadingLayers = fading; + } + if (root.liveLayer === layer) + root.liveLayer = null; + layer.destroy(); + } + + // A dock icon keeps its windows when its list is refreshed, and two icons + // never share one. A list with nothing in common with the live one is a + // different icon, not a refreshed list. + function sharesWindow(layer, wrappers) { + for (let i = 0; i < layer.rows.length; ++i) { + const row = layer.rows[i]; + for (let k = 0; k < wrappers.length; ++k) { + if (row.wrapper === wrappers[k]) + return true; + } + } + return false; + } + + function sync() { + const wrappers = [ ]; + const surfaces = preview.desiredSurfaces; + for (let i = 0; i < surfaces.length; ++i) { + if (surfaces[i]) + wrappers.push(surfaces[i]); + } + + if (wrappers.length === 0) { + root.emptied(); + return; + } + + const handover = root.liveLayer + && !root.sharesWindow(root.liveLayer, wrappers); + if (!root.liveLayer || handover) { + const layer = root.createLayer(); + if (!layer) { + console.warn(preview.loggingCategory, "failed to create a preview list"); + return; + } + if (root.liveLayer) + root.demote(root.liveLayer); + + layer.sync(wrappers, true); + root.liveLayer = layer; + if (handover) + layer.fadeIn(); + return; + } + + root.liveLayer.sync(wrappers, false); + } + + function demote(layer) { + if (!layer) + return; + + const fading = root.fadingLayers.slice(); + fading.push(layer); + root.fadingLayers = fading; + layer.fadeOut(); + } + + function freezeForClose() { + if (root.liveLayer) + root.liveLayer.freezePositions(); + } + + function clear() { + const layers = root.fadingLayers.slice(); + if (root.liveLayer) + layers.unshift(root.liveLayer); + root.liveLayer = null; + root.fadingLayers = [ ]; + for (let i = 0; i < layers.length; ++i) + layers[i].destroy(); + } + + Component { + id: layerComponent + + DockPreviewListLayer { + preview: root.preview + listPresent: root + } + } +} diff --git a/src/core/qml/DockPreview/DockPreviewListRow.qml b/src/core/qml/DockPreview/DockPreviewListRow.qml new file mode 100644 index 0000000000..36339a7130 --- /dev/null +++ b/src/core/qml/DockPreview/DockPreviewListRow.qml @@ -0,0 +1,217 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + +import Waylib.Server + +Item { + id: row + + required property QtObject preview + required property QtObject layerItem + + property var wrapper: null + // Where the row is drawn. Only `y` moves; the size and the left edge come + // from the style and the list. + property real yFrom: 0 + property real yTo: 0 + property real progress: 1 + property real reveal: 1 + property bool dropping: false + property int rowIndex: -1 + + readonly property bool hovered: rowHover.hovered + // A row takes input only while its list is live and it is not on its way + // out. + readonly property bool interactive: layerItem.interactive && !row.dropping + readonly property int sidePadding: PopoverStyle.listRowPadding + readonly property int iconSize: PopoverStyle.listIconSize + readonly property int innerSpacing: PopoverStyle.listInnerSpacing + + objectName: "previewListRow" + x: 0 + y: row.yFrom + (row.yTo - row.yFrom) * row.progress + width: preview.listContentWidth + height: preview.listRowHeight + opacity: reveal + + // The only place that writes the position. The new animation always starts + // from where the row is drawn. + function startMove(top) { + const current = y; + if (!preview.enableAnimation) { + yFrom = top; + yTo = top; + progress = 1; + return; + } + yFrom = current; + yTo = top; + progress = 0; + moveAnimation.restart(); + } + + function enter(newWrapper, startTop, top, instant) { + wrapper = newWrapper; + if (instant || !preview.enableAnimation) { + yFrom = top; + yTo = top; + progress = 1; + reveal = 1; + return; + } + yFrom = startTop; + yTo = top; + progress = 0; + moveAnimation.restart(); + reveal = 0; + revealAnimation.stop(); + revealAnimation.from = 0; + revealAnimation.to = 1; + revealAnimation.restart(); + } + + function retarget(newWrapper, top) { + wrapper = newWrapper; + // Already heading there: leave the running animation alone. + if (top === yTo) + return; + startMove(top); + } + + // Dropped from the list: close into the row that takes its place while it + // fades. False means it left at once and the list must not track it any + // more. + function collapseTo(top) { + dropping = true; + if (!preview.enableAnimation) { + layerItem.dropRow(row); + return false; + } + startMove(top); + revealAnimation.stop(); + revealAnimation.from = reveal; + revealAnimation.to = 0; + revealAnimation.restart(); + return true; + } + + function freezePosition() { + moveAnimation.stop(); + revealAnimation.stop(); + } + + Rectangle { + anchors.fill: parent + radius: preview.itemRadius + color: PopoverStyle.itemBackground + visible: row.hovered + } + + Loader { + id: iconLoader + readonly property var iconBuffer: row.wrapper?.appIcon ?? null + x: row.sidePadding + width: row.iconSize + height: row.iconSize + anchors.verticalCenter: parent.verticalCenter + active: !!iconBuffer + visible: active + sourceComponent: Component { + BufferItem { + id: iconItem + width: row.iconSize + height: row.iconSize + smooth: true + + Binding { + target: iconItem + property: "buffer" + value: iconLoader.iconBuffer + when: !!iconLoader.iconBuffer + restoreMode: Binding.RestoreNone + } + } + } + } + + Text { + id: titleText + anchors.left: iconLoader.right + anchors.leftMargin: row.innerSpacing + anchors.right: row.hovered ? closeButton.left : parent.right + anchors.rightMargin: row.hovered ? row.innerSpacing : row.sidePadding + anchors.verticalCenter: parent.verticalCenter + text: row.wrapper && row.wrapper.shellSurface + ? row.wrapper.shellSurface.title : "" + font: PopoverStyle.titleFont + color: PopoverStyle.titleColor + horizontalAlignment: Text.AlignLeft + elide: Text.ElideRight + } + + DockPreviewCloseButton { + id: closeButton + anchors.right: parent.right + anchors.rightMargin: row.sidePadding + anchors.verticalCenter: parent.verticalCenter + maximumSize: PopoverStyle.listRowButtonSize + visible: row.hovered + onClicked: { + // Capture the wrapper now: the deferred callback must not read the + // row's content again, it may have been reused. + const target = row.wrapper; + Qt.callLater(() => preview.closeSpecialWindow(target)); + } + } + + HoverHandler { + id: rowHover + enabled: row.interactive + cursorShape: Qt.ArrowCursor + onHoveredChanged: { + if (hovered && row.wrapper) + preview.previewWindow(row.wrapper); + } + } + + TapHandler { + enabled: row.interactive + onTapped: { + if (row.wrapper) + preview.activateWindow(row.wrapper); + } + } + + // The window went away on its own: the list has to drop it, exactly like a + // closed slot asks the controller to. + Connections { + target: row.wrapper + function onAboutToBeInvalidated() { + preview.removeSurface(row.wrapper); + } + } + + NumberAnimation { + id: moveAnimation + target: row + property: "progress" + from: 0 + to: 1 + duration: preview.aniDuration + easing.type: Easing.OutExpo + } + + NumberAnimation { + id: revealAnimation + target: row + property: "reveal" + duration: preview.aniDuration + easing.type: Easing.OutExpo + onFinished: { + if (row.dropping) + layerItem.dropRow(row); + } + } +} diff --git a/src/core/qml/DockPreview/DockPreviewScrollHint.qml b/src/core/qml/DockPreview/DockPreviewScrollHint.qml new file mode 100644 index 0000000000..b943cc4a6f --- /dev/null +++ b/src/core/qml/DockPreview/DockPreviewScrollHint.qml @@ -0,0 +1,135 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + +import Treeland +import org.deepin.dtk 1.0 as D + +Item { + id: root + + required property Flickable view + required property bool horizontal + property int duration: 350 + property bool enableAnimation: true + property bool interactive: true + // Part of the view that is outside the visible area. + property int inset: 0 + + readonly property real edgeTolerance: 0.5 + readonly property bool moreAtStart: { + const position = root.horizontal ? root.view.contentX : root.view.contentY; + return position > root.edgeTolerance; + } + readonly property bool moreAtEnd: { + const position = root.horizontal ? root.view.contentX : root.view.contentY; + const size = root.horizontal ? root.view.width : root.view.height; + const content = root.horizontal ? root.view.contentWidth + : root.view.contentHeight; + return position + size < content - root.edgeTolerance; + } + + x: root.view.x + y: root.view.y + width: root.view.width + height: root.view.height + scale: root.view.scale + transformOrigin: root.view.transformOrigin + z: 1 + + function stopPage() { + scrollAnimation.stop(); + const current = root.horizontal ? root.view.contentX : root.view.contentY; + scrollAnimation.from = current; + scrollAnimation.to = current; + } + + // One click is half a viewport, never more than what is left to show. + function page(direction) { + const axis = root.horizontal ? "contentX" : "contentY"; + const size = root.horizontal ? root.view.width : root.view.height; + const content = root.horizontal ? root.view.contentWidth + : root.view.contentHeight; + const current = root.view[axis]; + const limit = Math.max(0, content - size); + const target = Math.max(0, Math.min(limit, current + direction * size / 2)); + if (target === current) + return; + + scrollAnimation.stop(); + if (!root.enableAnimation) { + root.view[axis] = target; + return; + } + scrollAnimation.property = axis; + scrollAnimation.from = current; + scrollAnimation.to = target; + scrollAnimation.restart(); + } + + component ScrollButton: D.ToolButton { + id: button + + required property bool horizontal + property string iconName + + width: button.horizontal ? PopoverStyle.scrollHintThickness + : PopoverStyle.scrollHintLength + height: button.horizontal ? PopoverStyle.scrollHintLength + : PopoverStyle.scrollHintThickness + padding: 0 + icon.name: button.iconName + icon.width: PopoverStyle.scrollHintSize + icon.height: PopoverStyle.scrollHintSize + enabled: root.interactive + opacity: 1 + } + + ScrollButton { + horizontal: root.horizontal + iconName: root.horizontal ? "arrow_ordinary_left" : "arrow_ordinary_up" + x: root.horizontal ? root.inset + PopoverStyle.scrollHintMargin + : Math.round((root.width - width) / 2) + y: root.horizontal ? Math.round((root.height - height) / 2) + : root.inset + PopoverStyle.scrollHintMargin + visible: root.moreAtStart + onClicked: root.page(-1) + } + + ScrollButton { + horizontal: root.horizontal + iconName: root.horizontal ? "arrow_ordinary_right" : "arrow_ordinary_down" + x: root.horizontal ? root.width - root.inset - width - PopoverStyle.scrollHintMargin + : Math.round((root.width - width) / 2) + y: root.horizontal ? Math.round((root.height - height) / 2) + : root.height - root.inset - height - PopoverStyle.scrollHintMargin + visible: root.moreAtEnd + onClicked: root.page(1) + } + + // Glide instead of a jump. + PropertyAnimation { + id: scrollAnimation + target: root.view + duration: root.duration + easing.type: Easing.OutCubic + } + + // A hand on the scroller takes over from the glide. + Connections { + target: root.view + + function onMovementStarted() { + root.stopPage(); + } + + function onContentWidthChanged() { + root.stopPage(); + } + + function onContentHeightChanged() { + root.stopPage(); + } + } +} diff --git a/src/core/qml/DockPreview/DockPreviewSlot.qml b/src/core/qml/DockPreview/DockPreviewSlot.qml new file mode 100644 index 0000000000..520f6f324d --- /dev/null +++ b/src/core/qml/DockPreview/DockPreviewSlot.qml @@ -0,0 +1,457 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + +import Treeland +import org.deepin.dtk 1.0 as D + +// One window in the preview view. The slot owns its own rectangle, the size +// its pictures are drawn at, and everything that fades them. +Item { + id: slot + + // The DockPreview controller: model edits, geometry helpers and durations. + required property QtObject preview + // The preview view this slot belongs to: hover, order and the shared radius. + required property QtObject view + + property var wrapper: null + // A var keeps a window after the compositor invalidates it, so the + // slot tracks liveness itself instead of testing `wrapper`. + property bool wrapperAlive: false + property rect fromRect: Qt.rect(0, 0, 0, 0) + property rect toRect: Qt.rect(0, 0, 0, 0) + property real progress: 1 + // Whole-slot opacity: a new slot starts at the tail of the stack, fades + // in as it slides out, and fades out while it collapses. + property real reveal: 1 + // Content cross-fade, like the tooltip layers. + property real contentOpacity: 1 + // Pictures that left this slot and are still fading out, one per + // switch. + property var outgoingLayers: [] + // Size every layer inside the slot is drawn at. A switch animates + // it; the slot box never changes it. + property size contentSize: Qt.size(0, 0) + // Set by setContentSize(): animate this write or snap it. + property bool contentSizeAnimated: false + property bool collapsing: false + // Set when the shell closes with no windows left: the slot keeps + // its last picture while the whole shell fades away. + property bool frozen: false + // True while the picture still follows the window. + readonly property bool pictureLive: wrapperAlive && !collapsing && !frozen + property int slotIndex: -1 + // True while the pointer is over this slot's box, so the view can + // pick the survivor after a move between slots. + readonly property bool hovered: slotHover.hovered + + Behavior on contentSize { + PropertyAnimation { + duration: slot.contentSizeAnimated ? preview.aniDuration : 0 + easing.type: Easing.OutExpo + } + } + + objectName: "previewSlot" + x: fromRect.x + (toRect.x - fromRect.x) * progress + y: fromRect.y + (toRect.y - fromRect.y) * progress + width: fromRect.width + (toRect.width - fromRect.width) * progress + height: fromRect.height + (toRect.height - fromRect.height) * progress + opacity: reveal + + function currentRect() { + return Qt.rect(x, y, width, height) + } + + function equals(a, b) { + return a.x === b.x && a.y === b.y + && a.width === b.width && a.height === b.height; + } + + function setContentSize(newWrapper, rect, animated) { + contentSizeAnimated = animated && preview.enableAnimation; + contentSize = preview.naturalContentSize(rect, + newWrapper ? newWrapper.width : 0, + newWrapper ? newWrapper.height : 0); + } + + // The only place that writes the geometry. The new animation always + // starts from the rect the slot is drawn at, not from where the old + // animation was heading. + function startMove(rect) { + const current = currentRect(); + if (!preview.enableAnimation) { + fromRect = rect; + toRect = rect; + progress = 1; + return; + } + fromRect = current; + toRect = rect; + progress = 0; + moveAnimation.restart(); + } + + function enter(newWrapper, startRect, rect, instant) { + wrapper = newWrapper; + wrapperAlive = true; + frozen = false; + setContentSize(newWrapper, rect, false); + contentOpacity = 1; + clearOutgoing(); + if (instant || !preview.enableAnimation) { + fromRect = rect; + toRect = rect; + progress = 1; + reveal = 1; + return; + } + fromRect = startRect; + toRect = rect; + progress = 0; + moveAnimation.restart(); + // A slot that appears fades in from nothing while it slides out + // from behind the last one, so it never pops into existence. + reveal = 0; + revealAnimation.stop(); + revealAnimation.from = 0; + revealAnimation.to = 1; + revealAnimation.restart(); + } + + // `snap` places the slot without animating the move. + function retarget(newWrapper, rect, snap) { + if (newWrapper !== wrapper) { + swapContent(newWrapper, rect); + } else { + setContentSize(newWrapper, rect, !snap); + if (snap) { + moveAnimation.stop(); + fromRect = rect; + toRect = rect; + progress = 1; + return; + } + } + // Already heading there: leave the running animation alone. + if (equals(rect, toRect)) + return; + startMove(rect); + } + + // A closing slot keeps its own picture. It slides into the rect it is + // given, starting from where it is drawn, and only disappears + // once that is done. The picture is the one thing that goes early; + // the slot and every layer around it stay on the normal duration. + function collapseTo(rect) { + // Freeze the picture at this frame. + collapsing = true; + revealAnimation.stop(); + if (preview.enableAnimation) { + contentReveal.stop(); + closeContentFade.from = contentOpacity; + closeContentFade.to = 0; + closeContentFade.restart(); + } + startMove(rect); + if (!preview.enableAnimation) { + view.dropSlot(slot); + return false; + } + revealAnimation.from = reveal; + revealAnimation.to = 0; + revealAnimation.restart(); + return true; + } + + // The shell closed with no windows left, so nothing takes this + // slot over. Freeze the picture and let the shell fade take it. + function freezePicture() { + if (frozen || collapsing) + return; + frozen = true; + } + + // The list took this slot back before it was gone: turn around from + // where it is drawn right now. + function revive(newWrapper, rect) { + collapsing = false; + frozen = false; + closeContentFade.stop(); + if (newWrapper !== wrapper) { + swapContent(newWrapper, rect); + } else { + setContentSize(newWrapper, rect, true); + // The picture may have started to disappear. + if (contentOpacity < 1) { + if (!preview.enableAnimation) { + contentOpacity = 1; + } else { + contentReveal.stop(); + contentReveal.from = contentOpacity; + contentReveal.to = 1; + contentReveal.restart(); + } + } + } + if (!equals(rect, toRect) || progress < 1) + startMove(rect); + revealAnimation.stop(); + if (!preview.enableAnimation) { + reveal = 1; + return; + } + revealAnimation.from = reveal; + revealAnimation.to = 1; + revealAnimation.restart(); + } + + // Move the picture on screen to a layer of its own. + function demoteContent() { + if (!wrapper || !wrapperAlive) + return; + + const layer = outgoingLayerComponent.createObject(contentClip); + if (!layer) { + console.warn(preview.loggingCategory, "failed to create a slot layer"); + return; + } + layer.wrapper = wrapper; + layer.opacity = contentOpacity; + outgoingLayers.push(layer); + layer.fadeOut(); + } + + function dropOutgoing(layer) { + if (!layer) + return; + + const index = outgoingLayers.indexOf(layer); + if (index >= 0) + outgoingLayers.splice(index, 1); + layer.destroy(); + } + + // Drop every picture the slot used to show. + function clearOutgoing() { + const layers = outgoingLayers; + outgoingLayers = [ ]; + for (let i = 0; i < layers.length; ++i) { + if (layers[i]) + layers[i].destroy(); + } + } + + // The old content leaves on its own snapshot layer, the new one + // fades in. + function swapContent(newWrapper, slotRect) { + demoteContent(); + wrapper = newWrapper; + wrapperAlive = true; + frozen = false; + setContentSize(newWrapper, slotRect, true); + + contentReveal.stop(); + if (!preview.enableAnimation) { + contentOpacity = 1; + clearOutgoing(); + return; + } + contentOpacity = 0; + contentReveal.from = 0; + contentReveal.to = 1; + contentReveal.restart(); + } + + Rectangle { + anchors.fill: parent + radius: view.radius + color: PopoverStyle.itemBackground + } + + // One rounded mask for everything the slot draws. + D.OpacityMask { + anchors.fill: parent + source: contentClip + maskSource: pictureMask + } + + // The rounded contour of the slot. + Rectangle { + id: pictureMask + anchors.fill: parent + radius: view.radius + color: "white" + visible: false + } + + // Source of the mask above; never drawn directly. + Item { + id: contentClip + anchors.fill: parent + visible: false + clip: true + + ShaderEffectSource { + id: contentFeed + anchors.centerIn: parent + implicitWidth: slot.contentSize.width + implicitHeight: slot.contentSize.height + // Sampled by the picture below, never drawn. + visible: false + live: slot.pictureLive + hideSource: false + smooth: true + sourceItem: slot.wrapper + } + + // Mirrors the feed while the window is alive; stops sampling when the + // slot closes so the last frame survives the window. + ShaderEffectSource { + id: contentSource + anchors.centerIn: parent + implicitWidth: slot.contentSize.width + implicitHeight: slot.contentSize.height + opacity: slot.contentOpacity + live: slot.pictureLive + hideSource: false + smooth: true + sourceItem: contentFeed + } + } + + Component { + id: outgoingLayerComponent + + ShaderEffectSource { + id: outgoingLayer + anchors.centerIn: parent + implicitWidth: slot.contentSize.width + implicitHeight: slot.contentSize.height + // Snapshot once; the layer only fades from here on. + live: false + hideSource: false + smooth: true + z: 1 + property var wrapper: null + sourceItem: wrapper + + function fadeOut() { + if (!preview.enableAnimation) { + slot.dropOutgoing(outgoingLayer); + return; + } + fadeAnimation.from = opacity; + fadeAnimation.to = 0; + fadeAnimation.restart(); + } + + NumberAnimation { + id: fadeAnimation + target: outgoingLayer + property: "opacity" + duration: preview.aniDuration + easing.type: Easing.OutExpo + onFinished: slot.dropOutgoing(outgoingLayer) + } + + Connections { + target: outgoingLayer.wrapper + function onAboutToBeInvalidated() { + slot.dropOutgoing(outgoingLayer); + } + } + } + } + + Connections { + target: slot.wrapper + function onAboutToBeInvalidated() { + slot.wrapperAlive = false; + preview.removeSurface(slot.wrapper); + } + function onWidthChanged() { + view.requestRelayout(); + } + function onHeightChanged() { + view.requestRelayout(); + } + } + + HoverHandler { + id: slotHover + enabled: !slot.collapsing + && preview.requestedPresentation === DockPreview.Presentation.Thumbnail + cursorShape: Qt.ArrowCursor + onHoveredChanged: { + if (!hovered) + return; + preview.previewWindow(slot.wrapper); + view.currentSlot = slot.slotIndex; + view.hoveredSlot = slot; + } + } + + TapHandler { + onTapped: preview.activateWindow(slot.wrapper) + } + + // One close button per slot, shown while hovering it. + DockPreviewCloseButton { + anchors { + top: parent.top + right: parent.right + topMargin: PopoverStyle.popupPadding + rightMargin: PopoverStyle.popupPadding + } + visible: slotHover.hovered && !slot.collapsing + onClicked: { + // Capture the wrapper now: the deferred callback must not + // read the slot's content again, it may have been reused. + const target = slot.wrapper; + Qt.callLater(()=>preview.closeSpecialWindow(target)); + } + } + + NumberAnimation { + id: moveAnimation + target: slot + property: "progress" + from: 0 + to: 1 + duration: preview.aniDuration + easing.type: Easing.OutExpo + } + + NumberAnimation { + id: revealAnimation + target: slot + property: "reveal" + duration: preview.aniDuration + easing.type: Easing.OutExpo + onFinished: { + if (slot.collapsing) + view.dropSlot(slot); + } + } + + NumberAnimation { + id: contentReveal + target: slot + property: "contentOpacity" + duration: preview.aniDuration + easing.type: Easing.OutExpo + } + + // Only the closing window's picture goes early. Every layer around + // it keeps using aniDuration. + NumberAnimation { + id: closeContentFade + target: slot + property: "contentOpacity" + duration: preview.closeContentDuration + easing.type: Easing.OutCubic + } +} diff --git a/src/core/qml/DockPreview/DockPreviewSurface.qml b/src/core/qml/DockPreview/DockPreviewSurface.qml new file mode 100644 index 0000000000..e0bb604fae --- /dev/null +++ b/src/core/qml/DockPreview/DockPreviewSurface.qml @@ -0,0 +1,123 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + +import Treeland +import Treeland.Protocols + +// The popover's surface: the frame, the shell painted under the content, and +// the host every content layer draws into. +Rectangle { + id: surface + + // The DockPreview controller: geometry, fades and chrome switches. + required property QtObject preview + + // Scale of the whole popover around `scaleOrigin`. The entry animation + // decides `shellScale`; the dock edge the frame is glued to decides where + // it grows from. + property real shellScale: 1 + property bool shellScaleAnimated: true + // The frame scales towards its dock-facing edge. + readonly property point scaleOrigin: preview.scaleOriginFor(width, height) + + // Where the preview view and the tooltip layers draw. + readonly property alias contentHost: contentHost + // The pointer is over the popover. + readonly property alias titleHovered: titleHover.hovered + + z: preview.z + // Only the frame geometry. + color: "transparent" + width: preview.frameWidth + height: preview.frameHeight + radius: preview.requestedPresentation === DockPreview.Presentation.Tooltip + ? preview.tooltipRadius + : preview.panelRadius + clip: false + visible: preview.visible + + Behavior on radius { + enabled: surface.preview.enableAnimation + NumberAnimation { + id: radiusAnimation + duration: surface.preview.aniDuration + easing.type: Easing.OutExpo + } + } + + transform: Scale { + xScale: surface.shellScale + yScale: xScale + origin.x: surface.scaleOrigin.x + origin.y: surface.scaleOrigin.y + + Behavior on xScale { + enabled: surface.shellScaleAnimated && surface.preview.enableAnimation + NumberAnimation { + id: scaleAnimation + duration: surface.preview.aniDuration + easing.type: Easing.OutExpo + } + } + } + + // Host of every content layer. Each layer owns its opacity, so nothing + // here multiplies into the shell's fade. The shell paints below them. + Item { + id: contentHost + anchors.fill: parent + z: 0 + } + + // The group fades on its own value. + Rectangle { + id: shell + anchors.fill: parent + z: -1 + opacity: surface.preview.shellFade + clip: false + color: PopoverStyle.tintFor(surface.preview.enableBlur && backgroundBlur.blurEnabled) + radius: surface.radius + + XdgShadow { + visible: surface.preview.enableShadow + cornerRadius: surface.radius + shadowBlur: PopoverStyle.shadowBlur + shadowOffsetX: 0 + shadowOffsetY: PopoverStyle.shadowOffsetY + shadowColor: PopoverStyle.shadowColor + } + + Blur { + id: backgroundBlur + anchors.fill: parent + visible: surface.preview.enableBlur + radius: surface.radius + } + + Border { + anchors.fill: parent + visible: surface.preview.enableBorder + radius: surface.radius + outsideColor: PopoverStyle.borderOutsideColor + insideColor: PopoverStyle.borderInsideColor + } + } + + // Covers the whole frame, not only its content: the title row needs the + // pointer too. + HoverHandler { + id: titleHover + enabled: surface.preview.desiredSurfaces.length !== 0 + onHoveredChanged: { + if (!hovered) { + surface.preview.desktop.windowManagement.leaveDockPreview(surface.preview.target.shellSurface.surface) + } else { + surface.preview.desktop.windowManagement.enterDockPreview(surface.preview.target.shellSurface.surface) + } + } + cursorShape: Qt.ArrowCursor + } +} diff --git a/src/core/qml/DockPreview/DockPreviewThumbnailPresent.qml b/src/core/qml/DockPreview/DockPreviewThumbnailPresent.qml new file mode 100644 index 0000000000..826946984a --- /dev/null +++ b/src/core/qml/DockPreview/DockPreviewThumbnailPresent.qml @@ -0,0 +1,511 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Layouts + +import Waylib.Server +import Treeland +import org.deepin.dtk 1.0 as D + +Item { + id: root + + required property QtObject preview + // Whether the pointer is over the popover. + property bool hovered: false + + // Corner radius shared by the slots and the hover frame. + property int radius: preview.itemRadius + // Topmost z of the preview slots. + readonly property int slotZBase: 10000 + // Top of the content the title row takes for itself, in step with its own + // fade. The shared content rect never moves for it. + readonly property real titleSpace: + preview.thumbnailReveal * preview.titleRowChrome + // Slots in view order: live ones first, then the collapsing ones. + property var slots: [] + // List row the title follows. + property int currentSlot: 0 + // The slot under the pointer; drives the frame's opacity. + property var hoveredSlot: null + // The slot the frame is drawn on. Kept after the pointer leaves so the + // frame fades out in place; cleared once that slot is gone. + property var highlightSlot: null + onHoveredSlotChanged: { + if (root.hoveredSlot) + root.highlightSlot = root.hoveredSlot; + } + + // Room the view keeps for the highlight frame; the layout ignores it. + readonly property int frameMargin: PopoverStyle.frameBorderWidth + + // The window the title row describes: the highlighted preview, clamped. + readonly property var currentWrapper: { + const surfaces = preview.desiredSurfaces; + if (surfaces.length === 0) + return null; + const index = Math.min(Math.max(root.currentSlot, 0), surfaces.length - 1); + return surfaces[index] ?? null; + } + + // A signal instead of a close() call: whether an empty list closes the + // popover or only clears the thumbnails is the controller's decision. + signal emptied() + + anchors.fill: parent + visible: preview.thumbnailReveal > 0 + // The shell fade covers enter and leave; the slots add the presentation + // reveal. + opacity: preview.shellFade + + // Keep the last picture of every slot, for a close that fades out with + // nothing taking the windows over. The windows must still be alive. + function freezeForClose() { + const slots = root.slots; + for (let i = 0; i < slots.length; ++i) + slots[i].freezePicture(); + } + + // Pick the slot under the pointer again after the one it was on went away. + function refreshHoveredSlot() { + const slots = root.slots; + let hovered = null; + for (let i = 0; i < slots.length; ++i) { + if (!slots[i].collapsing && slots[i].hovered) { + hovered = slots[i]; + break; + } + } + root.hoveredSlot = hovered; + } + + // Clears the frame's slot before it is destroyed. + function forgetSlot(slot) { + if (root.highlightSlot === slot) + root.highlightSlot = null; + } + + function dropSlot(slot) { + if (!slot) + return; + + const slots = root.slots; + const index = slots.indexOf(slot); + if (index >= 0) { + const next = slots.slice(); + next.splice(index, 1); + root.slots = next; + } + + root.forgetSlot(slot); + slot.destroy(); + } + + // Drop every slot and forget which one was highlighted. + function clear() { + const slots = root.slots; + root.slots = [ ]; + root.hoveredSlot = null; + root.highlightSlot = null; + for (let i = 0; i < slots.length; ++i) + slots[i].destroy(); + } + + function createSlot() { + return slotComponent.createObject(slotLayer); + } + + // Coalesces window size changes into one layout pass. + property bool relayoutPending: false + + function requestRelayout() { + if (root.relayoutPending || !root.visible) + return; + preview.noteWindowResize(); + root.relayoutPending = true; + Qt.callLater(root.runPendingRelayout); + } + + function runPendingRelayout() { + root.relayoutPending = false; + root.sync(true); + } + + // Bring the slot instances in line with the controller's window list. + function sync(snap) { + const wrappers = [ ]; + const surfaces = preview.desiredSurfaces; + for (let i = 0; i < surfaces.length; ++i) { + if (surfaces[i]) + wrappers.push(surfaces[i]); + } + + if (wrappers.length === 0) { + root.currentSlot = 0; + root.emptied(); + return; + } + + // A strip that keeps none of its slots is a new strip: it starts at the + // dock-facing end, whatever asked for it. + const fresh = !root.slots.some(slot => wrappers.includes(slot.wrapper)); + if (fresh) { + root.currentSlot = 0; + scrollHint.stopPage(); + slotView.contentX = 0; + slotView.contentY = 0; + } + + // Target rects: where every window should sit in the view. + const rects = preview.slotRects(wrappers); + // Old instances: the live slots, then the collapsing ones. A + // collapsing slot can still take its window back until it is gone. + const previous = root.slots; + const pool = [ ]; + for (let i = 0; i < previous.length; ++i) + pool.push({ slot: previous[i], retiring: previous[i].collapsing }); + + const assigned = new Array(wrappers.length).fill(-1); + const used = new Array(pool.length).fill(false); + + // Match: a window still in the list keeps its own slot. + for (let i = 0; i < wrappers.length; ++i) { + for (let k = 0; k < pool.length; ++k) { + if (!used[k] && pool[k].slot.wrapper === wrappers[i]) { + assigned[i] = k; + used[k] = true; + break; + } + } + } + + // The rest take the remaining slots in order: content switches. + let next = 0; + for (let i = 0; i < wrappers.length; ++i) { + if (assigned[i] >= 0) + continue; + while (next < pool.length && used[next]) + ++next; + if (next >= pool.length) + break; + assigned[i] = next; + used[next] = true; + } + + // Where every old slot ends up: the rect of the slot it closes into. + // A slot at the front has no slot before it, so the one taking its + // place is what it closes into. + const closeRect = new Array(pool.length).fill(null); + for (let i = 0; i < wrappers.length; ++i) { + if (assigned[i] >= 0) + closeRect[assigned[i]] = rects[i]; + } + + let firstKept = 0; + while (firstKept < pool.length && closeRect[firstKept] === null) + ++firstKept; + + for (let k = 0; k < pool.length; ++k) { + if (closeRect[k] === null) + closeRect[k] = closeRect[k < firstKept ? firstKept : k - 1]; + } + + const lastPooled = pool.length ? pool[pool.length - 1].slot : null; + const entryRect = lastPooled ? lastPooled.currentRect() : null; + const instant = !entryRect; + + // Build the new sequence. + const live = [ ]; + const nextRetiring = [ ]; + + for (let i = 0; i < wrappers.length; ++i) { + const k = assigned[i]; + if (k >= 0) { + const slot = pool[k].slot; + if (pool[k].retiring) { + slot.revive(wrappers[i], rects[i]); + live.push(slot); + } else { + slot.retarget(wrappers[i], rects[i], snap); + live.push(slot); + } + continue; + } + + const created = root.createSlot(); + if (!created) { + console.warn(preview.loggingCategory, "failed to create a preview slot"); + continue; + } + created.enter(wrappers[i], entryRect ? entryRect : rects[i], rects[i], instant); + live.push(created); + } + + // Unclaimed: every one of them collapses forward, into the slot before + // it, and only leaves once that is done. + for (let k = 0; k < pool.length; ++k) { + if (used[k]) + continue; + + const slot = pool[k].slot; + // Already on its way out; its own close is what fades it. + if (pool[k].retiring) { + nextRetiring.push(slot); + continue; + } + if (slot.collapseTo(closeRect[k])) + nextRetiring.push(slot); + } + + // Bookkeeping: slot order, z, current slot, hover. + root.slots = live.concat(nextRetiring); + + for (let i = 0; i < live.length; ++i) { + live[i].slotIndex = i; + // Later slots stay below, so a new one comes out from behind. + live[i].z = root.slotZBase - i; + } + for (let i = 0; i < nextRetiring.length; ++i) + nextRetiring[i].z = 0; + + // The title row follows its slot when the slots renumber. + if (root.hoveredSlot && live.indexOf(root.hoveredSlot) >= 0) + root.currentSlot = root.hoveredSlot.slotIndex; + + if (root.currentSlot >= live.length) + root.currentSlot = Math.max(0, live.length - 1); + // Re-pick the hovered slot once the hover handlers have settled. + if (root.hoveredSlot && live.indexOf(root.hoveredSlot) < 0) { + root.hoveredSlot = null; + Qt.callLater(root.refreshHoveredSlot); + } + if (root.highlightSlot && root.slots.indexOf(root.highlightSlot) < 0) + root.forgetSlot(root.highlightSlot); + } + + // Clip at the frame's content rect: the title row leaves the top free, and + // a slot still moving out is cut by the frame, not by its own slot. + Item { + id: slotClip + + // Clipped one frame margin wider than the content. + x: preview.thumbnailContentRect.x - root.frameMargin + y: preview.thumbnailContentRect.y + root.titleSpace - root.frameMargin + width: preview.thumbnailContentRect.width + 2 * root.frameMargin + height: Math.max(0, preview.thumbnailContentRect.height - root.titleSpace + + 2 * root.frameMargin) + clip: true + + // One slot instance per shown window. + Flickable { + id: slotView + + readonly property bool drawsAtOwnSize: preview.thumbnailReveal === 1 + + enabled: preview.requestedPresentation === DockPreview.Presentation.Thumbnail + interactive: preview.requestedPresentation === DockPreview.Presentation.Thumbnail + // One frame margin on every side, outside the layout. + width: preview.previewViewport.width + 2 * root.frameMargin + height: preview.previewViewport.height + 2 * root.frameMargin + contentWidth: preview.thumbnailContentSize.width + 2 * root.frameMargin + contentHeight: preview.thumbnailContentSize.height + 2 * root.frameMargin + // Only the frame clips, so a slot still moving out is not cut. + clip: false + boundsBehavior: Flickable.StopAtBounds + // A settled preview sits in the content rect; while it unfolds, + // the slots keep their dock-facing edge. + x: (preview.contentPinToLeft || slotView.drawsAtOwnSize) + ? 0 : slotClip.width - width + y: slotView.drawsAtOwnSize ? 0 : slotClip.height - height + transformOrigin: preview.contentPinToLeft ? Item.BottomLeft : Item.BottomRight + scale: { + if (slotView.drawsAtOwnSize) + return 1; + const stripWidth = width - 2 * root.frameMargin; + const stripHeight = height - 2 * root.frameMargin; + if (!(stripWidth > 0) || !(stripHeight > 0)) + return 0; + return Math.max(0, Math.min(1, + (slotClip.width - 2 * root.frameMargin) / stripWidth, + (slotClip.height - 2 * root.frameMargin) / stripHeight)); + } + opacity: preview.thumbnailReveal + + Item { + id: slotLayer + x: root.frameMargin + y: root.frameMargin + width: preview.thumbnailContentSize.width + height: preview.thumbnailContentSize.height + + // One frame for the whole strip, drawn under the pictures. + Rectangle { + id: hoverFrame + + readonly property var slot: root.highlightSlot + // Only slide between two settled slots. + readonly property bool slides: preview.enableAnimation + && slot !== null && slot.progress === 1 + && hoverFrame.opacity > 0 + property rect frameRect: slot + ? Qt.rect(slot.x - border.width, slot.y - border.width, + slot.width + 2 * border.width, + slot.height + 2 * border.width) + : Qt.rect(0, 0, 0, 0) + + z: -1 + visible: slot !== null && opacity > 0 + opacity: root.hoveredSlot !== null ? 1 : 0 + + x: frameRect.x + y: frameRect.y + width: frameRect.width + height: frameRect.height + radius: root.radius + border.width + color: "transparent" + border.width: PopoverStyle.frameBorderWidth + property D.Palette borderPalette: D.Palette { + normal { + common: Qt.rgba(0, 0, 0, 0.2) + } + normalDark { + common: Qt.rgba(1, 1, 1, 0.3) + } + } + border.color: D.ColorSelector.borderPalette + + Behavior on opacity { + enabled: preview.enableAnimation + NumberAnimation { + duration: preview.aniDuration + easing.type: Easing.OutExpo + } + } + + Behavior on frameRect { + enabled: hoverFrame.slides + PropertyAnimation { + duration: preview.aniDuration + easing.type: Easing.OutExpo + } + } + } + } + + HoverHandler { + enabled: preview.requestedPresentation === DockPreview.Presentation.Thumbnail + cursorShape: Qt.ArrowCursor + onHoveredChanged: { + if (hovered) + return; + root.hoveredSlot = null; + preview.stopPreviewWindow(); + } + } + } + + // The strip scrolls sideways on a top or bottom dock and up and down on + // the other two; the hints follow whichever axis it uses. + DockPreviewScrollHint { + id: scrollHint + + view: slotView + horizontal: preview.isHorizontal + duration: preview.aniDuration + enableAnimation: preview.enableAnimation + opacity: preview.thumbnailReveal + interactive: preview.thumbnailReveal === 1 + inset: root.frameMargin + } + } + + Component { + id: slotComponent + + DockPreviewSlot { + preview: root.preview + view: root + } + } + + // The title row: the app icon and title of the highlighted slot, plus the + // close-all button. + RowLayout { + spacing: PopoverStyle.previewTitleIconSpacing + height: preview.titleRowHeight + anchors { + left: parent.left + right: parent.right + top: parent.top + leftMargin: preview.thumbnailPadding + rightMargin: preview.thumbnailPadding + topMargin: preview.titleTopPadding + } + + Loader { + id: appIconLoader + readonly property var iconBuffer: root.currentWrapper?.appIcon ?? null + active: !!iconBuffer + visible: active + Layout.alignment: Qt.AlignVCenter + opacity: preview.thumbnailReveal + sourceComponent: Component { + BufferItem { + id: appIconItem + implicitWidth: preview.titleRowHeight + implicitHeight: preview.titleRowHeight + smooth: true + + Binding { + target: appIconItem + property: "buffer" + value: appIconLoader.iconBuffer + when: !!appIconLoader.iconBuffer + restoreMode: Binding.RestoreNone + } + } + } + } + + Item { + id: titleTextArea + Layout.alignment: Qt.AlignVCenter + Layout.fillWidth: true + Layout.fillHeight: true + implicitWidth: titleText.implicitWidth + + Text { + id: titleText + anchors.left: parent.left + anchors.verticalCenter: parent.verticalCenter + width: parent.width + text: { + const wrapper = root.currentWrapper; + return wrapper && wrapper.shellSurface + ? wrapper.shellSurface.title : ""; + } + font: PopoverStyle.titleFont + color: PopoverStyle.titleColor + horizontalAlignment: Text.AlignLeft + elide: Text.ElideRight + opacity: preview.thumbnailReveal + } + } + + DockPreviewCloseButton { + // Never taller than the title row it appears in. + maximumSize: Math.min(PopoverStyle.closeButtonMaxSize, preview.titleRowHeight) + // Only the thumbnail presentation has a close-all action; the + // list has one per row and the tooltip has none. + // A hovered slot shows its own close button instead. + visible: preview.requestedPresentation === DockPreview.Presentation.Thumbnail + && root.hovered + && !root.hoveredSlot?.hovered + Layout.alignment: Qt.AlignVCenter | Qt.AlignRight + onClicked: { + preview.closeAllWindow(); + } + } + } +} diff --git a/src/core/qml/DockPreview/DockPreviewTooltipLayer.qml b/src/core/qml/DockPreview/DockPreviewTooltipLayer.qml new file mode 100644 index 0000000000..1fdac1a49c --- /dev/null +++ b/src/core/qml/DockPreview/DockPreviewTooltipLayer.qml @@ -0,0 +1,142 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + +import Waylib.Server +import Treeland.Protocols + +// One tooltip surface drawn in the popover. A layer either shows a live surface +// or keeps the last frame of one that already left. +Item { + id: root + + // The DockPreview controller: frame geometry, direction and durations. + required property QtObject preview + + // The frame this layer shows. + property Item surfaceItem: null + property bool fadingOut: false + + readonly property size naturalSize: surfaceItem + ? Qt.size(surfaceItem.implicitWidth, + surfaceItem.implicitHeight) + : Qt.size(0, 0) + + // Where the layer sits inside the frame, for the current direction. + // Position and the scale origin both read the same animated frame on the + // controller, so they cannot disagree. + readonly property real layerX: { + switch (preview.direction) { + case ForeignToplevelManagerInterfaceV3.PreviewDirection.left: + return 0; + case ForeignToplevelManagerInterfaceV3.PreviewDirection.right: + return preview.frameWidth - width; + default: // top / bottom: centred on the dock icon + return (preview.frameWidth - width) / 2; + } + } + + readonly property real layerY: { + switch (preview.direction) { + case ForeignToplevelManagerInterfaceV3.PreviewDirection.top: + return 0; + case ForeignToplevelManagerInterfaceV3.PreviewDirection.bottom: + return preview.frameHeight - height; + default: // left / right: centred on the dock icon + return (preview.frameHeight - height) / 2; + } + } + + // Every layer shrinks towards the edge the tooltip is glued to. + readonly property point scaleOrigin: preview.scaleOriginFor(width, height) + // Fit into the frame without ever stretching it. + readonly property real compressionX: + width > 0 && preview.frameWidth > 0 ? Math.min(1, preview.frameWidth / width) : 1 + readonly property real compressionY: + height > 0 && preview.frameHeight > 0 ? Math.min(1, preview.frameHeight / height) : 1 + + z: 1 + visible: surfaceItem !== null + width: naturalSize.width + height: naturalSize.height + + x: root.layerX + y: root.layerY + + transform: Scale { + origin.x: root.scaleOrigin.x + origin.y: root.scaleOrigin.y + xScale: root.compressionX + yScale: root.compressionY + } + + Component { + id: surfaceComponent + + SurfaceItem { + flags: SurfaceItem.RejectEvent + // Its natural size, never stretched; the owning layer is what gets + // positioned and compressed. + width: implicitWidth + height: implicitHeight + } + } + + // Build the surface item for `surface`, unless it cannot be created. + function setSurface(surface) { + const item = surfaceComponent.createObject(root); + if (!item) { + console.warn(preview.loggingCategory, "failed to create the tooltip surface item"); + return false; + } + // Set the surface on an already completed item, so it is initialized the + // same way the previously static item was, and has its size right away. + item.surface = surface; + surfaceItem = item; + return true; + } + + NumberAnimation { + id: fadeAnimation + target: root + property: "opacity" + duration: preview.aniDuration + easing.type: Easing.OutExpo + onFinished: { + if (root.fadingOut) + root.destroy(); + } + } + + function freeze() { + if (!surfaceItem) + return; + surfaceItem.surface = null; + surfaceItem.enabled = false; + } + + function fadeIn() { + fadingOut = false; + if (!preview.enableAnimation) { + opacity = 1; + return; + } + opacity = 0; + fadeAnimation.from = 0; + fadeAnimation.to = 1; + fadeAnimation.restart(); + } + + // A demoted layer only owns its fade from here on. + function fadeOut() { + fadingOut = true; + if (!preview.enableAnimation) { + root.destroy(); + return; + } + fadeAnimation.from = opacity; + fadeAnimation.to = 0; + fadeAnimation.restart(); + } +} diff --git a/src/core/qml/DockPreview/DockPreviewTooltipPresent.qml b/src/core/qml/DockPreview/DockPreviewTooltipPresent.qml new file mode 100644 index 0000000000..5ca84dfa57 --- /dev/null +++ b/src/core/qml/DockPreview/DockPreviewTooltipPresent.qml @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + +// The tooltip presentation of the popover: the surface on screen and the layers +// it left behind. +QtObject { + id: root + + // The DockPreview controller: logging category. + required property QtObject preview + // Item that owns the tooltip layers. + property Item host: null + // Creates one tooltip layer. + property Component layerComponent: null + + property var liveLayer: null + // Natural size of the tooltip that last left. + property size lastSize: Qt.size(0, 0) + + readonly property size liveSize: liveLayer ? liveLayer.naturalSize : Qt.size(0, 0) + // Natural size of the tooltip on screen, falling back to the one that just + // left: a switch never has to measure a layer that is already fading out. + readonly property size naturalSize: liveSize.width > 0 ? liveSize : lastSize + + // `surface` is the reported tooltip surface; null means it went away. + function applySurface(surface) { + const live = liveLayer; + if (surface) + createLive(surface); + demote(live); + } + + function createLive(surface) { + if (!layerComponent) + return; + + const layer = layerComponent.createObject(host); + if (!layer) { + console.warn(preview.loggingCategory, "failed to create the tooltip layer"); + return; + } + if (!layer.setSurface(surface)) { + layer.destroy(); + return; + } + liveLayer = layer; + layer.fadeIn(); + } + + // Every tooltip the dock stops showing becomes a frozen layer. + function demote(layer) { + if (!layer) + return; + + // Snapshot the size before clearing the live layer: naturalSize falls + // back to lastSize whenever there is no live one, so this keeps the + // frame target from dipping during a switch. + const size = layer.naturalSize; + if (size.width > 0 && size.height > 0) + lastSize = size; + if (liveLayer === layer) + liveLayer = null; + layer.freeze(); + layer.fadeOut(); + } +} diff --git a/src/core/qml/EdgeTilePreview.qml b/src/core/qml/EdgeTilePreview.qml new file mode 100644 index 0000000000..09ac659da9 --- /dev/null +++ b/src/core/qml/EdgeTilePreview.qml @@ -0,0 +1,64 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + +Rectangle { + id: root + visible: false + color: Qt.alpha(WaylandServer.config.activeColor, 0.25) + + // The dragged surface's geometry (starting point) and the target tile + // geometry, set from RootSurfaceContainer::updateEdgeTilePreview(). + property rect sourceGeometry: Qt.rect(0, 0, 0, 0) + property rect targetGeometry: Qt.rect(0, 0, 0, 0) + + // Animation duration mirrors KWin's outline effect (Kirigami longDuration). + property int animationDuration: 250 + // Animations stay disabled until the first show, so the initial transition + // from the dragged surface to the target tile is animated (like KWin's + // outline growing from the window being moved). + property bool animationEnabled: false + readonly property bool animationAllowed: WaylandServer.animationConfig.edgeTilePreview + + function applyGeometry(geometry) { + x = geometry.x + y = geometry.y + width = geometry.width + height = geometry.height + } + + onVisibleChanged: { + if (visible) { + // Jump to the dragged surface first, then animate to the target. + animationEnabled = false + applyGeometry(sourceGeometry) + animationEnabled = true + applyGeometry(targetGeometry) + } else { + animationEnabled = false + } + } + + onTargetGeometryChanged: { + if (visible) + applyGeometry(targetGeometry) + } + + Behavior on x { + enabled: root.animationEnabled && root.animationAllowed + NumberAnimation { duration: root.animationDuration; easing.type: Easing.InOutCubic } + } + Behavior on y { + enabled: root.animationEnabled && root.animationAllowed + NumberAnimation { duration: root.animationDuration; easing.type: Easing.InOutCubic } + } + Behavior on width { + enabled: root.animationEnabled && root.animationAllowed + NumberAnimation { duration: root.animationDuration; easing.type: Easing.InOutCubic } + } + Behavior on height { + enabled: root.animationEnabled && root.animationAllowed + NumberAnimation { duration: root.animationDuration; easing.type: Easing.InOutCubic } + } +} diff --git a/src/core/qml/Effects/+vulkan/Blur.qml b/src/core/qml/Effects/+vulkan/Blur.qml new file mode 100644 index 0000000000..af085f336d --- /dev/null +++ b/src/core/qml/Effects/+vulkan/Blur.qml @@ -0,0 +1,57 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Treeland + +Rectangle { + id: root + + color: Qt.rgba(0.0, 0.0, 0.0, 0.0) + + property bool radiusEnabled: radius > 0 + property rect frameRect: Qt.rect(0, 0, width, height) + property int blurMax: WaylandServer.config.blurStrength + property bool blurEnabled: blurMax > 0 && blurAmount > 0 + property real blurAmount: WaylandServer.config.blurAmount + property real multiplier: WaylandServer.config.blurMultiplier + property real brightness: 0.0 + property real contrast: 0.0 + property real saturation: WaylandServer.config.glassSaturation + property real glassSpecular: WaylandServer.config.glassSpecular + property real glassTint: 0.0 + property bool glassEnabled: WaylandServer.config.glassEnabled + property Item effectContent: effectContentItem + property bool contentOffscreen: false + property bool effectEnabled: true + readonly property Item content: contentContainer + property alias offscreen: root.contentOffscreen + default property alias data: contentContainer.data + + Item { + id: contentContainer + anchors.fill: parent + } + + // frameRect can be offset from and larger than this item, so the fill is + // clipped to the item instead of covering it unconditionally. + Item { + id: effectContentItem + anchors.fill: parent + clip: true + visible: root.effectEnabled && !root.contentOffscreen + z: -1 + + Rectangle { + x: root.frameRect.x + y: root.frameRect.y + width: root.frameRect.width + height: root.frameRect.height + radius: root.radiusEnabled ? root.radius : 0 + color: Qt.rgba(1.0, 1.0, 1.0, 0.15) + } + } + + z: parent.z ? parent.z - 1 : -1 + anchors.fill: parent +} diff --git a/src/core/qml/Effects/Blur.qml b/src/core/qml/Effects/Blur.qml new file mode 100644 index 0000000000..053e46d27c --- /dev/null +++ b/src/core/qml/Effects/Blur.qml @@ -0,0 +1,101 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Effects +import QtQuick.Shapes +import Waylib.Server +import Treeland + +RenderBufferBlitter { + id: blitter + smooth: true + + property real radius: 0 + property rect frameRect: Qt.rect(0, 0, width, height) + property bool radiusEnabled: radius > 0 + property int blurMax: WaylandServer.config.blurStrength + property bool blurEnabled: blurMax > 0 && blurAmount > 0 + property real blurAmount: WaylandServer.config.blurAmount + property real multiplier: WaylandServer.config.blurMultiplier + property real brightness: 0.0 + property real contrast: 0.0 + property real saturation: WaylandServer.config.glassSaturation + property real glassSpecular: WaylandServer.config.glassSpecular + property real glassTint: 0.0 + property bool glassEnabled: WaylandServer.config.glassEnabled + property Item effectContent: contentLoader + property bool contentOffscreen: false + property bool effectEnabled: true + + z: parent.z ? parent.z - 1 : -1 + anchors.fill: parent + + // Dispatch between Liquid Glass and traditional blur via a Loader so only + // the active branch is instantiated. Toggling the DConfig key unloads one + // Component and loads the other. + Loader { + id: contentLoader + anchors.fill: parent + sourceComponent: blitter.glassEnabled ? glassComponent : blurComponent + visible: blitter.effectEnabled && !blitter.contentOffscreen + } + + Component { + id: glassComponent + GlassEffect { + anchors.fill: parent + source: blitter.content + radius: blitter.radiusEnabled ? blitter.radius : 0 + frameRect: blitter.frameRect + blurEnabled: blitter.blurEnabled + blurMax: blitter.blurMax + blurAmount: blitter.blurAmount + blurMultiplier: blitter.multiplier + bezelWidth: WaylandServer.config.glassBezel + thickness: WaylandServer.config.glassThickness + ior: 1.33 + specular: blitter.glassSpecular + tint: blitter.glassTint + brightness: blitter.brightness + contrast: blitter.contrast + saturation: blitter.saturation + contentEdgePull: 0.0 + contentRampEnd: 0.0 + refractionMaxTan: 3.3 + profilePower: WaylandServer.config.glassProfilePower + innerShadow: 0.0 + } + } + + Component { + id: blurComponent + Item { + anchors.fill: parent + + MultiEffect { + id: blur + anchors.fill: parent + layer.enabled: blitter.radiusEnabled + smooth: blitter.radiusEnabled + opacity: blitter.radiusEnabled ? 0 : blitter.opacity + source: blitter.content + autoPaddingEnabled: false + blurEnabled: blitter.blurEnabled + blur: blitter.blurAmount + blurMax: blitter.blurMax + blurMultiplier: blitter.multiplier + saturation: 0.2 + } + + Loader { + anchors.fill: parent + active: blitter.radiusEnabled + sourceComponent: FrameClip { + source: blur + geometry: ({ rect: blitter.frameRect, radius: blitter.radius }) + } + } + } + } +} diff --git a/src/core/qml/Effects/GlassEffect.qml b/src/core/qml/Effects/GlassEffect.qml new file mode 100644 index 0000000000..5db67c92c7 --- /dev/null +++ b/src/core/qml/Effects/GlassEffect.qml @@ -0,0 +1,93 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Effects + +Item { + id: effect + + required property variant source + + // Liquid Glass material controls. + // Blur and shadow stay delegated to Qt Quick MultiEffect / callers. + property real radius: 12 + property rect frameRect: Qt.rect(0, 0, width, height) + property real thickness: 30 + property real bezelWidth: 30 + property real ior: 1.33 + property real specular: 0.0 + property real tint: 0.0 + // Limit the geometric surface slope near the silhouette. + property real refractionMaxTan: 3.3 + property real contentEdgePull: 0.0 + property real contentRampEnd: 0.0 + property real profilePower: 2.0 + property real innerShadow: 0.0 + + // Compatibility inputs kept for existing Blur.qml users. MultiEffect owns + // backdrop blur and colour adjustment before the refraction shader. + property bool blurEnabled: true + property int blurMax: 64 + property real blurAmount: 0.6 + property real blurMultiplier: 0.0 + property real brightness: 0.0 + property real contrast: 0.0 + property real saturation: 0.0 + readonly property vector2d lightDirection: Qt.vector2d(0.5, -0.7) + readonly property bool multiEffectEnabled: + (blurEnabled && blurAmount > 0 && blurMax > 0) + || brightness != 0 || contrast != 0 || saturation != 0 + + + MultiEffect { + id: processedSource + anchors.fill: parent + visible: effect.multiEffectEnabled + source: effect.source + autoPaddingEnabled: false + blurEnabled: effect.blurEnabled + blur: effect.blurAmount + blurMax: effect.blurMax + blurMultiplier: effect.blurMultiplier + brightness: effect.brightness + contrast: effect.contrast + saturation: effect.saturation + } + ShaderEffectSource { + id: processedTexture + anchors.fill: parent + sourceItem: processedSource + hideSource: true + live: true + visible: false + } + + ShaderEffect { + id: glassShader + objectName: "glassShader" + anchors.fill: parent + smooth: true + property variant source: effect.multiEffectEnabled ? processedTexture : effect.source + // Property order MUST match the UBO layout in liquidglass.frag (after qt_Matrix, qt_Opacity) + readonly property vector2d itemSize: Qt.vector2d(Math.max(width, 1), Math.max(height, 1)) + readonly property vector4d frameRect: Qt.vector4d(effect.frameRect.x, effect.frameRect.y, + Math.max(effect.frameRect.width, 1), + Math.max(effect.frameRect.height, 1)) + readonly property vector2d lightDirection: effect.lightDirection + readonly property real radius: effect.radius + readonly property real bezelWidth: effect.bezelWidth + readonly property real thickness: effect.thickness + readonly property real ior: effect.ior + readonly property real specular: Math.max(0, Math.min(1, effect.specular)) + readonly property real tint: Math.max(0, Math.min(1, effect.tint)) + readonly property real contentEdgePull: Math.max(0, Math.min(1, effect.contentEdgePull)) + readonly property real contentRampEnd: Math.max(0.001, Math.min(1, effect.contentRampEnd)) + readonly property real refractionMaxTan: Math.max(0.1, effect.refractionMaxTan) + readonly property real profilePower: Math.max(1, effect.profilePower) + readonly property real innerShadow: Math.max(0, Math.min(1, effect.innerShadow)) + + vertexShader: "qrc:/shaders/liquidglass.vert.qsb" + fragmentShader: "qrc:/shaders/liquidglass.frag.qsb" + } +} diff --git a/src/core/qml/Effects/LaunchpadCover.qml b/src/core/qml/Effects/LaunchpadCover.qml new file mode 100644 index 0000000000..9754f4e2a0 --- /dev/null +++ b/src/core/qml/Effects/LaunchpadCover.qml @@ -0,0 +1,102 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Effects +import Treeland +import Waylib.Server + +Item { + id: root + readonly property bool enableAnimation: WaylandServer.animationConfig.launchpadCover + clip: true + + required property SurfaceWrapper wrapper + required property WaylandOutput output + + property bool mapped: false + + z: (wrapper.z ?? 0) - 1 + anchors.fill: wrapper + + Wallpaper { + id: wallpaper + output: root.output + workspace: root.wrapper.desktop.workspace.current + } + + ShaderEffectSource { + id: wallpaperSource + sourceItem: wallpaper + recursive: true + live: true + smooth: true + anchors.fill: parent + hideSource: false + state: mapped ? "Scale" : "Normal" + states: [ + State { + name: "Normal" + PropertyChanges { + target: wallpaperSource + scale: 1 + } + }, + State { + name: "Scale" + PropertyChanges { + target: wallpaperSource + scale: 1.4 + } + } + ] + + transitions: [ + Transition { + from: "*" + to: "Normal" + enabled: root.enableAnimation + PropertyAnimation { + property: "scale" + duration: 1000 + easing.type: Easing.OutExpo + } + }, + Transition { + from: "*" + to: "Scale" + enabled: root.enableAnimation + PropertyAnimation { + property: "scale" + duration: 1000 + easing.type: Easing.OutExpo + } + } + ] + } + + Blur { + anchors.fill: parent + z: wallpaperSource.z + 1 + } + + Rectangle { + id: cover + anchors.fill: parent + color: 'black' + opacity: 0.6 + } + + opacity: root.mapped ? 1 : 0 + Behavior on opacity { + enabled: root.enableAnimation + PropertyAnimation { + duration: 400 + easing.type: Easing.OutExpo + } + } + + onMappedChanged: { + WaylandServer.setLaunchpadMapped(root.output, root.mapped) + } +} diff --git a/src/core/qml/FadeBehavior.qml b/src/core/qml/FadeBehavior.qml new file mode 100644 index 0000000000..7641602c2e --- /dev/null +++ b/src/core/qml/FadeBehavior.qml @@ -0,0 +1,112 @@ +// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQml + +Behavior { + id: root + + property QtObject fadeTarget: targetProperty.object + property string fadeProperty: "opacity" + property var fadeProperties: [fadeProperty] + property int exitValue: 0 + property int enterValue: exitValue + property int fadeDuration: 300 + property string easingType: "Quad" + property bool delayWhile: false + property bool sequential: false + + onDelayWhileChanged: { + if (!delayWhile) + sequentialAnimation.startExitAnimation(); + } + + readonly property Component shaderEffectSourceWrapperComponent: Item { + property alias shaderEffectSource: shaderEffectSource + property alias sourceItem: shaderEffectSource.sourceItem + parent: sourceItem.parent + x: sourceItem.x + y: sourceItem.y + ShaderEffectSource { + id: shaderEffectSource + transformOrigin: sourceItem.transformOrigin + hideSource: true + live: false + width: sourceItem.width + height: sourceItem.height + } + } + + readonly property Component defaultExitAnimation: NumberAnimation { + properties: root.fadeProperties.join(',') + duration: root.fadeDuration + to: root.exitValue + easing.type: root.easingType === "Linear" ? Easing.Linear : Easing["In"+root.easingType] + } + property Component exitAnimation: defaultExitAnimation + + readonly property Component defaultEnterAnimation: NumberAnimation { + properties: root.fadeProperties.join(',') + duration: root.fadeDuration + from: root.enterValue + to: root.fadeTarget[root.fadeProperties[0]] + easing.type: root.easingType === "Linear" ? Easing.Linear : Easing["Out"+root.easingType] + } + property Component enterAnimation: NumberAnimation { + properties: root.fadeProperties.join(',') + duration: root.fadeDuration + from: root.enterValue + to: root.fadeTarget[root.fadeProperties[0]] + easing.type: root.easingType === "Linear" ? Easing.Linear : Easing["Out"+root.easingType] + } + + SequentialAnimation { + id: sequentialAnimation + signal startEnterAnimation() + signal startExitAnimation() + ScriptAction { + script: { + const exitItem = shaderEffectSourceWrapperComponent.createObject(null, { sourceItem: root.fadeTarget }); + const exitShaderEffectSource = exitItem.shaderEffectSource; + if (exitAnimation === root.defaultExitAnimation) + root.fadeProperties.forEach(p => exitShaderEffectSource[p] = root.fadeTarget[p]); + exitShaderEffectSource.width = root.fadeTarget.width; + exitShaderEffectSource.height = root.fadeTarget.height; + const exitAnimationInstance = exitAnimation.createObject(root, { target: exitItem.shaderEffectSource }); + + sequentialAnimation.startExitAnimation.connect(exitAnimationInstance.start); + if (root.sequential) + exitAnimationInstance.finished.connect(sequentialAnimation.startEnterAnimation); + else + exitAnimationInstance.started.connect(sequentialAnimation.startEnterAnimation); + + exitAnimationInstance.finished.connect(() => { + exitItem.destroy(); + exitAnimationInstance.destroy(); + }); + } + } + PropertyAction {} + ScriptAction { + script: { + const enterItem = shaderEffectSourceWrapperComponent.createObject(null, { sourceItem: root.fadeTarget }); + const enterShaderEffectSource = enterItem.shaderEffectSource; + if (enterAnimation === root.defaultEnterAnimation) + root.fadeProperties.forEach(p => enterShaderEffectSource[p] = root.enterValue); + enterShaderEffectSource.live = true; + const enterAnimationInstance = enterAnimation.createObject(root, { target: enterItem.shaderEffectSource }); + + sequentialAnimation.startEnterAnimation.connect(enterAnimationInstance.start); + + enterAnimationInstance.finished.connect(() => { + enterItem.destroy(); + enterAnimationInstance.destroy(); + }); + + if (!root.delayWhile) + sequentialAnimation.startExitAnimation(); + } + } + } +} diff --git a/src/core/qml/FpsDisplay.qml b/src/core/qml/FpsDisplay.qml new file mode 100644 index 0000000000..ec0d01505a --- /dev/null +++ b/src/core/qml/FpsDisplay.qml @@ -0,0 +1,92 @@ +// Copyright (C) 2025 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Controls +import QtQuick.Window + +Item { + id: root + anchors.fill: parent + + property real scaleFactor: 1.0 + property var targetWindow: null + property alias fpsManager: internalManager + + FpsDisplayManager { + id: internalManager + } + + Component.onCompleted: { + targetWindow = parent && parent.Window ? parent.Window.window : Window.window + } + + onTargetWindowChanged: { + if (internalManager.running) { + internalManager.stop() + } + if (targetWindow) { + internalManager.setTargetWindow(targetWindow) + internalManager.start() + } + } + + Component.onDestruction: { + internalManager.stop() + } + + Rectangle { + id: fpsDisplay + width: Math.max(200 * scaleFactor, 180) + height: Math.max(80 * scaleFactor, 70) + color: "transparent" + radius: 8 * scaleFactor + border.color: "transparent" + border.width: 0 + + anchors { + top: parent.top + right: parent.right + margins: 20 * scaleFactor + } + + Behavior on opacity { + NumberAnimation { duration: 200; easing.type: Easing.OutCubic } + } + + Behavior on scale { + NumberAnimation { duration: 200; easing.type: Easing.OutCubic } + } + + Column { + anchors.centerIn: parent + spacing: 2 * scaleFactor + + Text { + id: currentLabel + text: qsTr("Current FPS: %1").arg(fpsManager ? fpsManager.currentFps : 0) + color: "#000000" + font.pixelSize: Math.max(16 * scaleFactor, 14) + font.weight: Font.Medium + font.family: "monospace" + horizontalAlignment: Text.AlignHCenter + anchors.horizontalCenter: parent.horizontalCenter + style: Text.Raised + styleColor: "#FFFFFF" + } + + Text { + id: maximumLabel + text: qsTr("Maximum FPS: %1").arg(fpsManager ? fpsManager.maximumFps : 0) + color: "#000000" + font.pixelSize: Math.max(16 * scaleFactor, 14) + font.weight: Font.Medium + font.family: "monospace" + horizontalAlignment: Text.AlignHCenter + anchors.horizontalCenter: parent.horizontalCenter + style: Text.Raised + styleColor: "#FFFFFF" + } + } + } +} diff --git a/src/core/qml/FrameClip.qml b/src/core/qml/FrameClip.qml new file mode 100644 index 0000000000..df64ef91ee --- /dev/null +++ b/src/core/qml/FrameClip.qml @@ -0,0 +1,40 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +import QtQuick +import QtQuick.Shapes + +Item { + id: root + + required property Item source + required property var geometry + property real geometryScale: 1 + property point geometryOffset: Qt.point(0, 0) + property rect sourceRect: Qt.rect(0, 0, source.width, source.height) + + anchors.fill: parent + clip: true + + Shape { + anchors.fill: parent + preferredRendererType: Shape.CurveRenderer + ShapePath { + strokeWidth: 0 + fillItem: root.source + fillTransform: Qt.matrix4x4( + root.width / (root.sourceRect.width > 0 ? root.sourceRect.width : 1), 0, 0, + -root.sourceRect.x * root.width / (root.sourceRect.width > 0 ? root.sourceRect.width : 1), + 0, root.height / (root.sourceRect.height > 0 ? root.sourceRect.height : 1), 0, + -root.sourceRect.y * root.height / (root.sourceRect.height > 0 ? root.sourceRect.height : 1), + 0, 0, 1, 0, + 0, 0, 0, 1) + PathRectangle { + x: root.geometry.rect.x * root.geometryScale + root.geometryOffset.x + y: root.geometry.rect.y * root.geometryScale + root.geometryOffset.y + width: root.geometry.rect.width * root.geometryScale + height: root.geometry.rect.height * root.geometryScale + radius: root.geometry.radius * root.geometryScale + } + } + } +} diff --git a/src/core/qml/LockScreenFallback.qml b/src/core/qml/LockScreenFallback.qml new file mode 100644 index 0000000000..9ff77faef9 --- /dev/null +++ b/src/core/qml/LockScreenFallback.qml @@ -0,0 +1,40 @@ +// Copyright (C) 2025 misaka18931 . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick 2.15 + +FocusScope { + id: root + clip: true + required property QtObject outputItem + + // Position and size + x: outputItem.x + y: outputItem.y + width: outputItem.width + height: outputItem.height + + Component.onCompleted: forceActiveFocus() + + Keys.onPressed: event => event.accepted = true + Keys.onReleased: event => event.accepted = true + + MouseArea { + anchors.fill: parent + acceptedButtons: Qt.AllButtons + onPressed: mouse => { mouse.accepted = true; root.forceActiveFocus() } + onReleased: mouse => mouse.accepted = true + onClicked: mouse => mouse.accepted = true + onWheel: wheel => wheel.accepted = true + } + + MultiPointTouchArea { + anchors.fill: parent + onPressed: touchPoints => root.forceActiveFocus() + } + + Rectangle { + anchors.fill: parent + color: "grey" + } +} diff --git a/src/core/qml/MirrorOutput.qml b/src/core/qml/MirrorOutput.qml new file mode 100644 index 0000000000..38aeb4e803 --- /dev/null +++ b/src/core/qml/MirrorOutput.qml @@ -0,0 +1,174 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Treeland +import Waylib.Server + +OutputItem { + id: outputItem + + required property SourceOutput targetOutputItem + // Treeland::Output wrapper, assigned by Output::createCopy(). + property QtObject treelandOutput + property OutputViewport screenViewport: viewport + + property OutputViewport sourceScreenViewport: targetOutputItem.screenViewport + + // Constants for fallback and precision thresholds + readonly property int fallbackSize: 100 + readonly property real sizeMatchTolerance: 0.1 + readonly property real scaleEpsilon: 0.001 + + // WaylandServer property: source screen pixel size (physical size in pixels) + // Formula: pixelSize = effectiveSize * scale + // - output.size returns effectiveSize (logical size) + // - scale is the devicePixelRatio + // - pixelSize is the actual framebuffer size in pixels + // Fallback is used during component initialization or if source output is not ready + readonly property size sourcePixelSize: { + if (!sourceScreenViewport || !sourceScreenViewport.output) { + console.warn("MirrorOutput: Source viewport not ready, using fallback size"); + return Qt.size(fallbackSize, fallbackSize); + } + const effectiveSize = sourceScreenViewport.output.size; + const scale = sourceScreenViewport.output.scale; + const rotatedSize = Qt.size(effectiveSize.width * scale, effectiveSize.height * scale); + + const sourceRotation = sourceScreenViewport.rotation; + const isSourceRotated90or270 = (Math.abs(sourceRotation % 180) === 90); + + if (isSourceRotated90or270) { + return Qt.size(rotatedSize.height, rotatedSize.width); + } + return rotatedSize; + } + + devicePixelRatio: output?.scale ?? devicePixelRatio + + Rectangle { + id: content + anchors.fill: parent + color: "black" + + TextureProxy { + id: proxy + sourceItem: sourceScreenViewport + anchors.centerIn: parent + rotation: targetOutputItem.keepAllOutputRotation ? 0 : sourceScreenViewport.rotation + + width: sourcePixelSize.width + height: sourcePixelSize.height + sourceRect: Qt.rect(0, 0, sourcePixelSize.width, sourcePixelSize.height) + + smooth: true + transformOrigin: Item.Center + + scale: { + if (!sourceScreenViewport || !sourceScreenViewport.output) { + return 1.0; + } + if (!content.width || !content.height) { + return 1.0; + } + // Wait for TextureProxy size to sync with source pixel size + if (Math.abs(width - sourcePixelSize.width) > sizeMatchTolerance || + Math.abs(height - sourcePixelSize.height) > sizeMatchTolerance) { + return 1.0; + } + + const proxyRotation = rotation; + const isRotated90or270 = (Math.abs(proxyRotation % 180) === 90); + const visualWidth = isRotated90or270 ? height : width; + const visualHeight = isRotated90or270 ? width : height; + + if (visualWidth <= 0 || visualHeight <= 0) { + return 1.0; + } + + const scaleX = content.width / visualWidth; + const scaleY = content.height / visualHeight; + const finalScale = Math.min(scaleX, scaleY); + + // Fix floating-point precision issues + return Math.abs(finalScale - 1.0) < scaleEpsilon ? 1.0 : finalScale; + } + } + } + + OutputViewport { + id: viewport + + anchors.centerIn: parent + depends: [sourceScreenViewport] + devicePixelRatio: outputItem.devicePixelRatio + input: content + output: outputItem.output + + RotationAnimation { + id: rotationAnimator + target: viewport + duration: 200 + alwaysRunToEnd: true + } + + Timer { + id: transformTimer + property var scheduleTransform + onTriggered: treelandOutput.setTransform(scheduleTransform) + interval: rotationAnimator.duration / 2 + } + + // Rotation requests (protocol or menu) go through + // Output::rotationOutput(); this handler provides the animation. + Component.onCompleted: { + treelandOutput.rotationOutputHandler = function(transform) { + viewport.rotationOutput(transform) + } + } + + function rotationAngle(orientation) { + switch(orientation) { + case WaylandOutput.R90: + return 90 + case WaylandOutput.R180: + return 180 + case WaylandOutput.R270: + return -90 + default: + return 0 + } + } + + function rotationOutput(orientation) { + transformTimer.stop() + + if (!WaylandServer.animationConfig.mirrorOutputRotation) { + // Apply the visual value and the real transform together instead + // of waiting for the half-way timer. + rotationAnimator.complete() + rotation = rotationAngle(orientation) + treelandOutput.setTransform(orientation) + return + } + + transformTimer.scheduleTransform = orientation + transformTimer.start() + rotationAnimator.to = rotationAngle(orientation) + rotationAnimator.from = rotation + rotationAnimator.start() + } + } + + function setTransform(transform) { + treelandOutput.rotationOutput(transform) + } + + function setScale(scale) { + WaylandServer.setOutputScale(outputItem.output, scale) + } + + function invalidate() { + viewport.invalidate() + } +} diff --git a/src/core/qml/OutputMenuBar.qml b/src/core/qml/OutputMenuBar.qml new file mode 100644 index 0000000000..622716677c --- /dev/null +++ b/src/core/qml/OutputMenuBar.qml @@ -0,0 +1,161 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Controls +import Waylib.Server +import Treeland + +Item { + required property SourceOutput output + + width: output.width + height: menuBar.contentHeight + x: output.x + y: output.y + + ToolBar { + id: menuBar + + width: parent.width + + Row { + anchors.fill: parent + + ToolButton { + text: "Quit" + onClicked: Qt.quit() + } + + ToolButton { + text: "Scale" + onClicked: scaleMenu.popup() + + Menu { + id: scaleMenu + + MenuItem { + text: "100%" + onClicked: { + output.setScale(1) + } + } + + MenuItem { + text: "125%" + onClicked: { + output.setScale(1.25) + } + } + + MenuItem { + text: "150%" + onClicked: { + output.setScale(1.5) + } + } + + MenuItem { + text: "175%" + onClicked: { + output.setScale(1.75) + } + } + + MenuItem { + text: "200%" + onClicked: { + output.setScale(2) + } + } + } + } + + ToolButton { + text: "Rotation" + + onClicked: rotationMenu.popup() + + Menu { + id: rotationMenu + + MenuItem { + text: "Normal" + onClicked: { + output.setTransform(WaylandOutput.Normal) + } + } + + MenuItem { + text: "R90" + onClicked: { + output.setTransform(WaylandOutput.R90) + } + } + + MenuItem { + text: "R270" + onClicked: { + output.setTransform(WaylandOutput.R270) + } + } + } + } + + ToolButton { + text: "New Workspace" + onClicked: WaylandServer.workspace.createModel("Workspace"+Math.random()); + } + + ToolButton { + text: "Delete Workspace" + onClicked: { + if (WaylandServer.workspace.count > 1) + WaylandServer.workspace.removeModel(WaylandServer.workspace.currentIndex); + } + } + + ToolButton { + text: "Prev Workspace" + onClicked: WaylandServer.workspace.switchToPrev(); + } + + ToolButton { + text: "Next Workspace" + onClicked: WaylandServer.workspace.switchToNext(); + } + + Label { + text: WaylandServer.workspace.currentIndex + color: "red" + } + + ToolButton { + text: "Output" + + onClicked: outputMenu.popup() + + Menu { + id: outputMenu + + MenuItem { + text: "Add Output" + onClicked: { + WaylandServer.addOutput() + } + } + + MenuItem { + text: (WaylandServer.outputMode === WaylandServer.OutputMode.Copy) ? "Extension Mode" : "Copy Mode" + onClicked: { + if (WaylandServer.outputMode === WaylandServer.OutputMode.Copy) + WaylandServer.outputMode = WaylandServer.OutputMode.Extension + else + WaylandServer.outputMode = WaylandServer.OutputMode.Copy + } + } + } + } + } + } +} diff --git a/src/core/qml/PopoverStyle.qml b/src/core/qml/PopoverStyle.qml new file mode 100644 index 0000000000..859da5eb5a --- /dev/null +++ b/src/core/qml/PopoverStyle.qml @@ -0,0 +1,92 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +pragma Singleton + +import QtQuick +import org.deepin.dtk 1.0 as D +import org.deepin.dtk.style 1.0 as DS + +// Style for the popovers the compositor draws itself. Mainly referenced from DTK. +QtObject { + id: style + + readonly property bool isDark: D.DTK.themeType === D.ApplicationHelper.DarkType + readonly property int popupPadding: DS.Style.popup.padding + + readonly property color tint: isDark ? DS.Style.behindWindowBlur.darkColor + : DS.Style.behindWindowBlur.lightColor + readonly property color opaqueTint: isDark ? DS.Style.behindWindowBlur.darkNoBlurColor + : DS.Style.behindWindowBlur.lightNoBlurColor + + function tintFor(blurred) { + return blurred ? tint : opaqueTint + } + + readonly property font titleFont: D.DTK.fontManager.t6 + + readonly property color titleColor: D.DTK.palette.windowText + + readonly property int shadowBlur: 20 + readonly property int shadowOffsetY: 6 + readonly property color shadowColor: DS.Style.arrowRectangleBlur.shadowColor + + readonly property color borderOutsideColor: DS.Style.arrowRectangleBlur.outBorderColor + readonly property color borderInsideColor: DS.Style.arrowRectangleBlur.inBorderColor + + // Upper bound for the floating close button, so it can never grow a row it + // is shown in. DTK's own floating button is this size. + readonly property int closeButtonMaxSize: DS.Style.floatingButton.size + + /* --- the preview list --- */ + // Width of the list panel, padding included. + readonly property int listPanelWidth: 200 + // Inset of the list content from every panel edge. + readonly property int listPanelPadding: 6 + // One row of the list. + readonly property int listRowHeight: 26 + readonly property int listRowSpacing: 0 + // Left and right padding of a row. + readonly property int listRowPadding: 8 + // Gap between two things inside a row (icon and title, title and button) + readonly property int listInnerSpacing: DS.Style.control.spacing + // App icon of a row. + readonly property int listIconSize: 16 + readonly property int listRowButtonSize: 20 + // Where a list stops growing and starts scrolling. It caps the frame, not + // the rows, so the panel padding still sits outside the cap. + readonly property int listMaxFrameHeight: 400 + + /* --- the preview scroll hints --- */ + // The arrow that marks content hidden beyond a scroll viewport. The glyph + // itself comes from the icon theme, so only its box is styled here. + readonly property int scrollHintSize: 12 + readonly property int scrollHintThickness: 20 + readonly property int scrollHintLength: 46 + // Gap between the button and the viewport edge it points away from. + readonly property int scrollHintMargin: 3 + + /* --- the preview slots --- */ + // Bounds of the side that follows the window's aspect ratio, and the short + // side of a slot. + readonly property int previewSlotMinSide: 80 + readonly property int previewSlotMaxSide: 240 + readonly property int previewSlotShortSide: 120 + // Spacing inside the thumbnail view. + readonly property int previewSpacing: 10 + // Inset of the thumbnail content from every panel edge. + readonly property int previewPanelPadding: DS.Style.popup.padding + // Title row: icon size, icon to text, panel top and the strip below it. + readonly property int previewTitleIconSize: 24 + readonly property int previewTitleIconSpacing: 5 + readonly property int previewTitleTopPadding: 8 + readonly property int previewTitleGap: 8 + // Width of the highlight frame, drawn outside the slot box. + readonly property int frameBorderWidth: 4 + + // Placeholder behind a preview thumbnail. This is DPalette::ItemBackground, + // which DTK does not export to QML in this version, so the two palette + // values are kept here instead of being inlined in DockPreview.qml. + readonly property color itemBackground: isDark ? Qt.rgba(1, 1, 1, 0.05) + : Qt.rgba(0, 0, 0, 0.03) +} diff --git a/src/core/qml/PrelaunchSplash.qml b/src/core/qml/PrelaunchSplash.qml new file mode 100644 index 0000000000..a9302e27ec --- /dev/null +++ b/src/core/qml/PrelaunchSplash.qml @@ -0,0 +1,71 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Controls +import Waylib.Server 1.0 +import Treeland + +// Pre-launch splash QML item that can be shown before an application's main window appears. +Item { + id: splash + + required property SurfaceWrapper surface + required property var iconBuffer + required property color backgroundColor + readonly property bool isLightBackground: backgroundColor.hslLightness >= 0.5 + + // Fill the entire parent (SurfaceWrapper) + anchors.fill: parent + + Rectangle { + id: background + color: splash.backgroundColor + anchors.fill: parent + radius: splash.surface?.presentationFrameGeometry.radius ?? 0 + + // Centered logo: prefer provided icon buffer; fallback to image / placeholder + Column { + id: contentColumn + anchors.centerIn: parent + spacing: 12 + + Item { + id: logoContainer + width: 88 + height: 88 + anchors.horizontalCenter: parent.horizontalCenter + + BufferItem { + anchors.fill: parent + visible: !!splash.iconBuffer + buffer: splash.iconBuffer + smooth: true + } + + // Fallback placeholder when no icon buffer is provided + Rectangle { + anchors.fill: parent + visible: !splash.iconBuffer + color: "#4CAF50" + radius: width / 2 + + Text { + anchors.centerIn: parent + text: "App" + font.pixelSize: 24 + color: "white" + font.bold: true + } + } + } + + Text { + anchors.horizontalCenter: parent.horizontalCenter + text: qsTr("Loading application...") + color: splash.isLightBackground ? Qt.rgba(0, 0, 0, 0.5) : Qt.rgba(1, 1, 1, 0.5) + font.pixelSize: 16 // TODO:use D.DTK.fontManager.t5 + } + } + } +} diff --git a/src/core/qml/SourceOutput.qml b/src/core/qml/SourceOutput.qml new file mode 100644 index 0000000000..b394b79fbb --- /dev/null +++ b/src/core/qml/SourceOutput.qml @@ -0,0 +1,242 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Controls +import Waylib.Server +import Treeland + +OutputItem { + id: rootOutputItem + readonly property OutputViewport screenViewport: outputViewport + // Treeland::Output wrapper, assigned by Output::create(). + property QtObject treelandOutput + property bool forceSoftwareCursor: false + + devicePixelRatio: output?.scale ?? devicePixelRatio + + cursorDelegate: Cursor { + id: cursorItem + + required property QtObject outputCursor + readonly property point rawPosition: parent.mapFromGlobal(cursor.position.x, cursor.position.y) + readonly property real effectiveScale: rootOutputItem.devicePixelRatio || 1.0 + + // Align cursor position to pixel grid to prevent blur on fractional DPR displays + function alignToPixelGrid(value) { + return Math.round(value * effectiveScale) / effectiveScale + } + + readonly property point position: Qt.point( + alignToPixelGrid(rawPosition.x), + alignToPixelGrid(rawPosition.y) + ) + + cursor: outputCursor.cursor + output: outputCursor.output.output + x: position.x - hotSpot.x + y: position.y - hotSpot.y + visible: valid && outputCursor.visible + OutputLayer.enabled: !outputCursor.output.forceSoftwareCursor + OutputLayer.keepLayer: true + OutputLayer.outputs: [screenViewport] + OutputLayer.flags: OutputLayer.Cursor + OutputLayer.cursorHotSpot: hotSpot + + themeName: WaylandServer.config.cursorThemeName + sourceSize: Qt.size(WaylandServer.config.cursorSize, WaylandServer.config.cursorSize) + } + + OutputViewport { + id: outputViewport + + output: rootOutputItem.output + devicePixelRatio: parent.devicePixelRatio + anchors.centerIn: parent + + RotationAnimation { + id: rotationAnimator + + target: outputViewport + duration: 200 + alwaysRunToEnd: true + } + + Timer { + id: setTransform + + property var scheduleTransform + onTriggered: treelandOutput.setTransform(scheduleTransform) + interval: rotationAnimator.duration / 2 + } + + // Rotation requests (protocol or menu) go through + // Output::rotationOutput(); this handler provides the animation. + Component.onCompleted: { + treelandOutput.rotationOutputHandler = function(transform) { + outputViewport.rotationOutput(transform) + } + } + + function rotationAngle(orientation) { + switch(orientation) { + case WaylandOutput.R90: + return 90 + case WaylandOutput.R180: + return 180 + case WaylandOutput.R270: + return -90 + default: + return 0 + } + } + + function rotationOutput(orientation) { + setTransform.stop() + + if (!WaylandServer.animationConfig.outputRotation) { + // Apply the visual value and the real transform together instead + // of waiting for the half-way timer. + rotationAnimator.complete() + rotation = rotationAngle(orientation) + treelandOutput.setTransform(orientation) + return + } + + setTransform.scheduleTransform = orientation + setTransform.start() + rotationAnimator.to = rotationAngle(orientation) + rotationAnimator.from = rotation + rotationAnimator.start() + } + } + + Item { + clip: true + anchors.fill: parent + WallpaperSwitcher { + id: wallpaper + readonly property bool enableAnimation: WaylandServer.animationConfig.wallpaperScale + + clip: true + anchors.fill: parent + output: rootOutputItem.output + workspace: WaylandServer.workspace.current + + readonly property int duration: 1000 + states: [ + State { + name: "Normal" + PropertyChanges { + target: wallpaper + scale: 1 + } + }, + State { + name: "Scale" + PropertyChanges { + target: wallpaper + scale: 1.4 + } + }, + State { + name: "ScaleTo1.2" + PropertyChanges { + target: wallpaper + scale: 1.2 + } + }, + State { + name: "ScaleWithoutAnimation" + PropertyChanges { + target: wallpaper + scale: 1.4 + } + } + ] + + transitions: [ + Transition { + from: "*" + to: "Normal" + enabled: wallpaper.enableAnimation + PropertyAnimation { + property: "scale" + duration: wallpaper.duration + easing.type: Easing.OutExpo + } + }, + Transition { + from: "*" + to: "Scale" + enabled: wallpaper.enableAnimation + PropertyAnimation { + property: "scale" + duration: wallpaper.duration + easing.type: Easing.OutExpo + } + }, + Transition { + from: "*" + to: "ScaleTo1.2" + enabled: wallpaper.enableAnimation + PropertyAnimation { + property: "scale" + duration: wallpaper.duration + easing.type: Easing.OutExpo + } + }, + Transition { + from: "*" + to: "ScaleWithoutAnimation" + PropertyAnimation { + property: "scale" + duration: 0 + } + } + ] + + Connections { + target: WaylandServer + function onLaunchpadMappedChanged(output, mapped) { + if (output !== rootOutputItem.output) { + return; + } + + wallpaper.state = mapped ? "Scale" : "Normal" + } + + function onShowDesktopRequested(output) { + if (output !== rootOutputItem.output) { + return; + } + + wallpaper.state = "Normal" + wallpaper.play = true + wallpaper.slowDown() + } + + function onStartLockscreened(output, showAnimation) { + if (output !== rootOutputItem.output) { + return; + } + + wallpaper.play = false + wallpaper.state = showAnimation ? "ScaleTo1.2" : "ScaleWithoutAnimation" + } + } + } + } + + function setTransform(transform) { + treelandOutput.rotationOutput(transform) + } + + function setScale(scale) { + WaylandServer.setOutputScale(rootOutputItem.output, scale) + } + + function invalidate() { + screenViewport.invalidate() + } +} diff --git a/src/core/qml/SurfaceContent.qml b/src/core/qml/SurfaceContent.qml new file mode 100644 index 0000000000..d1f17edc9d --- /dev/null +++ b/src/core/qml/SurfaceContent.qml @@ -0,0 +1,140 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Shapes +import Waylib.Server +import Treeland + +Item { + id: root + + required property SurfaceItem surface + // surface?.parent maybe is a `SubsurfaceContainer` + property SurfaceWrapper wrapper: surface?.parent as SurfaceWrapper + property bool syncSurfaceSizeRatio: true + readonly property XWaylandSurface xwaylandSurface: wrapper?.shellSurface as XWaylandSurface + readonly property bool hasClipShape: xwaylandSurface?.hasClipShape ?? false + readonly property real cornerRadius: wrapper?.frameGeometry.radius ?? 0 + readonly property real frameScale: 1 / (surface?.contentItem?.scale ?? 1) + readonly property point frameOffset: Qt.point( + -(surface?.contentItem?.x ?? 0) * frameScale, + -(surface?.contentItem?.y ?? 0) * frameScale) + readonly property rect effectFrameRect: wrapper + ? Qt.rect(frameOffset.x, frameOffset.y, + wrapper.frameGeometry.rect.width * frameScale, + wrapper.frameGeometry.rect.height * frameScale) + : Qt.rect(0, 0, width, height) + + Loader { + id: clientMask + active: root.cornerRadius > 0 + sourceComponent: FrameInputMask { + geometry: root.wrapper.frameGeometry + frameItem: root.wrapper.frameItem + target: root.surface?.eventItem ?? null + } + } + Binding { + target: root.surface?.eventItem ?? null + property: "containmentMask" + value: clientMask.item + when: clientMask.active && target !== null + } + + anchors.fill: parent + opacity: content.alphaModifier + + function clipShapePaths() { + if (!hasClipShape) + return []; + + const geometry = xwaylandSurface.geometry; + if (geometry.width <= 0 || geometry.height <= 0) + return []; + + const scaleX = width / geometry.width; + const scaleY = height / geometry.height; + const paths = []; + for (const contour of xwaylandSurface.clipShape) { + const points = []; + for (const point of contour) + points.push(Qt.point(point.x * scaleX, point.y * scaleY)); + paths.push(points); + } + return paths; + } + + Loader { + anchors.fill: parent + active: wrapper?.blur ?? false + sourceComponent: Blur { + anchors.fill: parent + radiusEnabled: cornerRadius > 0 + radius: root.cornerRadius * root.frameScale + frameRect: root.effectFrameRect + } + } + + SurfaceItemContent { + id: content + surface: root.surface?.surface ?? null + anchors.fill: parent + opacity: (effectLoader.active || shapeLoader.active) ? 0 : parent.opacity + live: root.surface && (root.wrapper?.renderingEnabled ?? true) + && !(root.surface.flags & SurfaceItem.NonLive) + smooth: root.surface?.smooth ?? true + + onDevicePixelRatioChanged: { + // The wrapper outlives a destroyed shell surface during its close + // animation, so there is nothing to keep in sync in that case. + if (root.syncSurfaceSizeRatio && wrapper && wrapper.shellSurface) { + wrapper.updateSurfaceSizeRatio() + } + } + } + + Loader { + id: effectLoader + + anchors.fill: parent + active: root.cornerRadius > 0 + + opacity: shapeLoader.active ? 0 : 1 + layer.enabled: shapeLoader.active + + sourceComponent: FrameClip { + source: content + sourceRect: content.bufferSourceRect + geometry: root.wrapper.frameGeometry + geometryScale: root.frameScale + geometryOffset: root.frameOffset + } + } + + Loader { + id: shapeLoader + + anchors.fill: parent + active: root.hasClipShape && GraphicsInfo.api !== GraphicsInfo.Software + sourceComponent: Shape { + preferredRendererType: Shape.CurveRenderer + ShapePath { + strokeWidth: 0 + fillItem: effectLoader.active ? effectLoader : content + fillTransform: effectLoader.active + ? PlanarTransform.fromScale(1, 1, 0, 0) + : PlanarTransform.fromScale( + content.bufferSourceRect.width > 0 + ? root.width / content.bufferSourceRect.width : 1, + content.bufferSourceRect.height > 0 + ? root.height / content.bufferSourceRect.height : 1, + 0, 0) + fillRule: ShapePath.OddEvenFill + PathMultiline { + paths: root.clipShapePaths() + } + } + } + } +} diff --git a/src/core/qml/SwitchViewDelegate.qml b/src/core/qml/SwitchViewDelegate.qml new file mode 100644 index 0000000000..2b19e78e33 --- /dev/null +++ b/src/core/qml/SwitchViewDelegate.qml @@ -0,0 +1,129 @@ +// Copyright (C) 2024 lbwtw . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Shapes +import Treeland +import QtQuick.Layouts +import org.deepin.dtk 1.0 as D + +Item { + id: windowItem + required property SurfaceWrapper surface + + property real ratio: surface.width / surface.height + property ListView sourceView: ListView.view + property real contanReftWidth: (sourceView.fullheight - sourceView.titleheight - sourceView.vMargin) * ratio + 2 * (sourceView.vSpacing + sourceView.borderMargin) + property bool widthLimit: contanReftWidth > sourceView.delegateMaxWidth + height: sourceView.fullheight + width: contanReftWidth < sourceView.delegateMinWidth ? sourceView.delegateMinWidth + : (contanReftWidth > sourceView.delegateMaxWidth + ? sourceView.delegateMaxWidth : contanReftWidth) + + Item { + id: contentItem + layer.enabled: true + smooth: true + opacity: 0 + + anchors.centerIn: parent + height: sourceView.thumbnailheight + width: parent.width - 2 * (sourceView.vSpacing + sourceView.borderMargin) + + ColumnLayout { + anchors.fill: parent + spacing: 0 + + Item { + Layout.preferredHeight: sourceView.titleheight + Layout.fillWidth: true + + Rectangle { + anchors.fill: parent + opacity: 0.8 + } + + RowLayout { + spacing: 8 + anchors { + fill: parent + leftMargin: sourceView.titleHMargin + rightMargin: sourceView.titleHMargin + } + visible: parent.width > 2 * sourceView.iconSize.width ? true : false + + /* + Rectangle { + Layout.preferredWidth: parent.width > sourceView.iconSize.width ? sourceView.iconSize.width : 0 + Layout.preferredHeight: parent.height > sourceView.iconSize.height ? sourceView.iconSize.height : 0 + Layout.alignment: Qt.AlignVCenter | Qt.AlignHCenter + color: "yellow" + } + */ + Text { + Layout.fillWidth: true + Layout.alignment: Qt.AlignVCenter | Qt.AlignHCenter + text: { + const wrapper = windowItem.surface + const xdg = wrapper.shellSurface + const title = xdg ? xdg.title : "" + return title && title.length > 0 ? title : wrapper.appId + } + elide: Qt.ElideRight + } + } + + Rectangle { + color: "red" + opacity: 0.05 + anchors { + top: parent.bottom + left: parent.left + right: parent.right + } + height: sourceView.separatorHeight + } + } + + Item { + Layout.fillWidth: true + Layout.fillHeight: true + + SurfaceProxy { + id: proxy + live: true + anchors.centerIn: parent + surface: windowItem.surface + maxSize: Qt.size(parent.width, parent.height) + radius: 0 + } + } + } + + Rectangle { + visible: sourceView.enableDelegateBorders + anchors.fill: parent + color: "transparent" + opacity: 0.1 + border { + color: "#000000" + width: 1 + } + } + } + + Shape { + x: contentItem.x + y: contentItem.y + preferredRendererType: Shape.CurveRenderer + ShapePath { + strokeWidth: 0 + fillItem: contentItem + PathRectangle { + width: contentItem.width + height: contentItem.height + radius: sourceView.enableDelegateRadius ? surface.radius : 0 + } + } + } +} diff --git a/src/core/qml/SwitchViewHighlightDelegate.qml b/src/core/qml/SwitchViewHighlightDelegate.qml new file mode 100644 index 0000000000..16c1328125 --- /dev/null +++ b/src/core/qml/SwitchViewHighlightDelegate.qml @@ -0,0 +1,38 @@ +// Copyright (C) 2024 lbwtw . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick + + +Rectangle { + property ListView sourceView: ListView.view + readonly property int aniDuration: 400 + + visible: sourceView.currentItem + x: sourceView.currentItem ? sourceView.currentItem.x + sourceView.borderMargin : 0 + y: sourceView.currentItem ? sourceView.currentItem.y + (sourceView.vMargin / 2 - 2 * sourceView.borderMargin) : 0 + height: sourceView.currentItem ? sourceView.currentItem.height - 2 * (sourceView.vMargin / 2 - 2 * sourceView.borderMargin) : 0 + width: sourceView.currentItem ? sourceView.currentItem.width - 2 * sourceView.vSpacing + 2 * sourceView.borderMargin : 0 + color: "transparent" + radius: sourceView.radius + border { + width: sourceView.borderWidth + color: "#0081FF" + } + + Behavior on x { + enabled: sourceView.enableDelegateAnimation + NumberAnimation { + duration: aniDuration + easing.type: Easing.OutExpo + } + } + + Behavior on width { + enabled: sourceView.enableDelegateAnimation + NumberAnimation { + duration: aniDuration + easing.type: Easing.OutExpo + } + } +} diff --git a/src/core/qml/TaskBar.qml b/src/core/qml/TaskBar.qml new file mode 100644 index 0000000000..7798ee082b --- /dev/null +++ b/src/core/qml/TaskBar.qml @@ -0,0 +1,61 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Waylib.Server +import Treeland + +ListView { + required property QtObject output + readonly property OutputItem outputItem: output.outputItem + + width: 250 + leftMargin + rightMargin + height: Math.min(outputItem.height, contentHeight) + topMargin + bottomMargin + x: outputItem.x + y: (outputItem.height - height) / 2 + spacing: 80 + leftMargin: 40 + rightMargin: 40 + topMargin: 40 + bottomMargin: 40 + model: output.minimizedSurfaces + delegate: Item { + required property SurfaceWrapper surface + + width: proxy.width + height: proxy.height + + SurfaceProxy { + id: proxy + live: true + surface: parent.surface + maxSize: Qt.size(250, 150) + } + + MouseArea { + anchors.fill: parent + onClicked: parent.surface.restoreFromMinimized() + } + } + + transform: Rotation { + angle: 30 + axis { + x: 0 + y: 1 + z: 0 + } + + origin { + x: width / 2 + y: height / 2 + } + } + + layer { + enabled: true + live: true + mipmap: true + smooth: true + } +} diff --git a/src/core/qml/TaskSwitcher.qml b/src/core/qml/TaskSwitcher.qml new file mode 100644 index 0000000000..9f09b0392b --- /dev/null +++ b/src/core/qml/TaskSwitcher.qml @@ -0,0 +1,673 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Layouts +import Treeland +import Waylib.Server +import QtQuick.Effects +import org.deepin.dtk 1.0 as D + +Item { + id: root + visible: false + + property bool switchOn: true + property double lastSwitchTimestamp: 0 + property int focusReason: Qt.TabFocusReason + required property DesktopEnvironment desktop + readonly property QtObject workspace: desktop.workspace + required property QtObject output + readonly property QtObject model: root.workspace.currentFilter + + // control all switch item + property bool enableBlur: GraphicsInfo.api !== GraphicsInfo.Software + property bool enableBorders: true + property bool enableShadows: GraphicsInfo.api !== GraphicsInfo.Software + property bool enableRadius: true + property bool enableAnimation: GraphicsInfo.api !== GraphicsInfo.Software + && WaylandServer.animationConfig.taskSwitcher + readonly property int leftpreferredMargin: 20 + readonly property int rightpreferredMargin: 20 + readonly property int mouseExitInterval: 400 + readonly property real radius: enableRadius ? 18 : 0 + + x: output.outputItem.x + output.validRect.x + y: output.outputItem.y + output.validRect.y + width: output.validRect.width + height: output.validRect.height + + onVisibleChanged: { + if (visible) { + // Navigation belongs to the switcher, independently of the shortcut + // and modifiers used to open it. + root.forceActiveFocus() + mask.opacity = 0.5 + currentContext.loaderStatus = 0 + + if (root.enableAnimation) { + switchItemAnimation.stop() + switchItemAnimation.isInAni = true + switchItemAnimation.start() + } else { + switchItemAnimation.stop() + switchItem.opacity = 1 + } + } + } + + Keys.enabled: root.visible + Keys.onLeftPressed: { + if (!previewWindows.animationRunning) + root.previous() + } + Keys.onRightPressed: { + if (!previewWindows.animationRunning) + root.next() + } + + WheelHandler { + enabled: root.visible + acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad + target: null + blocking: true + + onWheel: function(event) { + event.accepted = true + if (previewWindows.animationRunning) + return + + const delta = event.inverted ? -event.angleDelta.y : event.angleDelta.y + if (delta > 0) + root.previous() + else if (delta < 0) + root.next() + } + } + + Connections { + target: root.workspace.current + + onSurfaceAdded: function(surface) { + if (root.visible && currentContext.visible) { + surface.opacity = 0.0 + } + } + } + + Rectangle { + id: mask + anchors.fill: parent + color: "black" + opacity: 0.0 + + Behavior on opacity { + enabled: root.enableAnimation + + NumberAnimation { + duration: 400 + easing.type: Easing.OutExpo + } + } + + Component.onCompleted: { + Qt.callLater(() => { + mask.opacity = 0.5 + }) + } + } + + MouseArea { + anchors.fill: parent + + onClicked: { + root.exitByMouse() + } + } + + ColumnLayout { + anchors.fill: parent + anchors.topMargin: 20 + anchors.leftMargin: 20 + anchors.rightMargin: 20 + anchors.bottomMargin: 54 + spacing: 20 + + Item { + id: previewItem + + Layout.fillWidth: true + Layout.fillHeight: true + Layout.topMargin: 30 + + TaskWindowPreview { + id: previewContext + visible: previewWindows.count === 0 + + anchors.centerIn: previewItem + sourceComponent: undefined + } + + TaskWindowPreview { + id: currentContext + visible: previewWindows.count === 0 + + sourceSurface: switchView.currentItem ? switchView.currentItem.surface : null + anchors.centerIn: previewItem + sourceComponent: undefined + + onClicked: { + root.exitByMouse() + } + } + } + + Item { + id: switchItem + + clip: true + Layout.preferredHeight: 198 + Layout.preferredWidth: switchView.contentWidth + 2 * switchView.vSpacing + Layout.maximumWidth: parent.width + Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter + Layout.leftMargin: switchView.contentWidth > root.width ? 0 : leftpreferredMargin + Layout.rightMargin: switchView.contentWidth > root.width ? 0 : rightpreferredMargin + + Loader { + enabled: root.enableShadows + anchors.fill: parent + sourceComponent: root.enableShadows ? shadow : undefined + } + + Component { + id: shadow + + D.BoxShadow { + shadowColor: "#000000" + opacity: 0.2 + shadowOffsetY: 2 + shadowBlur: 8 + cornerRadius: root.radius + hollow: true + } + } + + Rectangle { + visible: root.enableBorders + anchors { + fill: parent + margins: 1 + } + color: "transparent" + opacity: 0.1 + radius: root.radius + border { + color: "#000000" + width: 1 + } + } + + Blur { + anchors.fill: parent + visible: root.enableBlur + radius: root.radius + blurEnabled: root.enableBlur + } + + Rectangle { + visible: root.enableBorders + anchors.fill: parent + color: "transparent" + opacity: 0.1 + radius: root.radius + border { + color: "#000000" + width: 1 + } + } + + ListView { + id: switchView + + readonly property real titleheight: 38 + readonly property real fullheight: switchView.height + readonly property real vMargin: 38 + readonly property real thumbnailheight: fullheight - titleheight + readonly property real titleHMargin: 7 + readonly property real borderMargin: 4 + readonly property real vSpacing: 8 + readonly property size iconSize: Qt.size(24, 24) + readonly property real borderWidth: borderMargin + readonly property real delegateMinWidth: 128 + readonly property real delegateMaxWidth: 260 + readonly property real separatorHeight: 1 + readonly property real radius: root.enableRadius ? 20 : 0 + + // control listview delegate and highlight + property bool enableDelegateBlur: root.enableBlur + property bool enableDelegateBorders: root.enableBorders + property bool enableDelegateShadows: root.enableShadows + property bool enableDelegateAnimation: root.enableAnimation + property bool enableDelegateRadius: root.enableRadius + + + boundsBehavior: Flickable.OvershootBounds + orientation: ListView.Horizontal + clip: true + anchors { + fill: parent + leftMargin: vSpacing + rightMargin: vSpacing + } + + model: root.model + delegate: SwitchViewDelegate { + MouseArea { + anchors.fill: parent + onClicked: { + let pos = mapToItem(switchView.contentItem, mouse.x, mouse.y) + let index = switchView.indexAt(pos.x, pos.y) + switchIndex(index) + } + } + } + highlight: SwitchViewHighlightDelegate {} + highlightFollowsCurrentItem: false + + Component.onCompleted: { + if (root.model.activeIndex >= 0 && root.model.activeIndex < switchView.count) + switchView.currentIndex = root.model.activeIndex; + else { + switchView.currentIndex = switchView.count > 1 ? 1 : 0 + } + } + } + } + + Component.onCompleted: { + if (root.enableAnimation) { + switchItemAnimation.fromeY = switchItem.y + switchItemAnimation.stop() + switchItemAnimation.isInAni = true + switchItemAnimation.start() + } else { + switchItemAnimation.fromeY = switchItem.y + switchItem.opacity = 1 + } + } + } + + ParallelAnimation { + id: switchItemAnimation + + property bool isInAni: true + property real fromeY + readonly property int duration: 400 + readonly property real toY: root.height - 60 + + YAnimator { + target: switchItem + from: switchItemAnimation.isInAni ? switchItemAnimation.toY : switchItemAnimation.fromeY + to: switchItemAnimation.isInAni ? switchItemAnimation.fromeY : switchItemAnimation.toY + duration: switchItemAnimation.duration + easing.type: Easing.OutExpo + } + + OpacityAnimator { + target: switchItem + from: switchItemAnimation.isInAni ? 0.0 : 1.0 + to: switchItemAnimation.isInAni ? 1.0 : 0.0 + duration: switchItemAnimation.duration + easing.type: Easing.OutExpo + } + + onStopped: switchItem.y = switchItemAnimation.fromeY + } + + Repeater { + id: previewWindows + + property bool reverse: false + property bool animationRunning: false + property int finishedAnimations: 0 + property int totalAnimations: previewWindows.count + signal startAnimations() + signal restoreSurfaces() + + function beginAnimation(surfaceSnapshot, surface, reason) { + previewWindows.finishedAnimations = 0 + // Repeater creates the delegates synchronously, so every surface state is + // saved by Component.onCompleted before activating the selected surface. + previewWindows.model = surfaceSnapshot + + if (surface) + root.desktop.activateWindow(surface, reason) + + previewWindows.animationRunning = true + previewWindows.startAnimations() + } + + function finishAnimation(interrupted) { + if (!previewWindows.animationRunning) + return + + // stop() can emit finished synchronously. Mark the animation stopped before + // restoring delegates so those callbacks cannot finish it a second time. + previewWindows.animationRunning = false + previewWindows.restoreSurfaces() + previewWindows.model = [] + previewWindows.finishedAnimations = 0 + + if (!interrupted && !previewWindows.reverse) { + showTask(false) + root.switchOn = false + } + } + + delegate: Item { + id: windowItem + required property SurfaceWrapper modelData + readonly property SurfaceWrapper surface: modelData + property real surfaceX: 0 + property real surfaceY: 0 + property int surfaceTransformOrigin: Item.Center + + function animationFinished() { + if (!previewWindows.animationRunning) + return + + previewWindows.finishedAnimations += 1 + if (previewWindows.finishedAnimations === previewWindows.totalAnimations) + previewWindows.finishAnimation(false) + } + + ParallelAnimation { + id: previewAnimation + + property real scaleFrom + property int opacityFrom: 0.0 + property real xFrom + property real yFrom + property real xTo + property real yTo + property int duration: 400 + property Item target + + ScaleAnimator { + target: previewAnimation.target + from: previewWindows.reverse ? 1 : previewAnimation.scaleFrom + to: previewWindows.reverse ? previewAnimation.scaleFrom : 1 + duration: previewAnimation.duration + easing.type: Easing.OutExpo + } + + OpacityAnimator { + loops: surface + && (root.desktop.activatedWindow === surface || surface.visible) ? 1 : 0 + target: previewAnimation.target; + from: previewWindows.reverse ? 1.0 : previewAnimation.opacityFrom + to: previewWindows.reverse ? previewAnimation.opacityFrom : 1.0 + duration: previewAnimation.duration + easing.type: Easing.OutExpo + } + + XAnimator { + target: previewAnimation.target + from: previewWindows.reverse ? previewAnimation.xTo : previewAnimation.xFrom + to: previewWindows.reverse ? previewAnimation.xFrom : previewAnimation.xTo + duration: previewAnimation.duration + easing.type: Easing.OutExpo + } + + YAnimator { + target: previewAnimation.target + from: previewWindows.reverse ? previewAnimation.yTo : previewAnimation.yFrom + to: previewWindows.reverse ? previewAnimation.yFrom : previewAnimation.yTo + duration: previewAnimation.duration + easing.type: Easing.OutExpo + } + + onFinished: windowItem.animationFinished() + } + + Component.onCompleted: { + if (!surface || !surface.shellSurface) + return + + windowItem.surfaceX = surface.x + windowItem.surfaceY = surface.y + windowItem.surfaceTransformOrigin = surface.transformOrigin + + const wh = previewPostion(surface, previewItem) + previewAnimation.target = surface + previewAnimation.xFrom = (40 + previewItem.width - wh.width) / 2.0 + previewAnimation.yFrom = (104 + previewItem.height - wh.height) / 2.0 + previewAnimation.xTo = windowItem.surfaceX + previewAnimation.yTo = windowItem.surfaceY + previewAnimation.scaleFrom = wh.width / surface.width + } + + Connections { + target: previewWindows + + function onStartAnimations() { + if (!surface || !surface.shellSurface) { + // Do not clear the Repeater model while this signal is still being + // delivered to the remaining delegates. + Qt.callLater(function() { + windowItem.animationFinished() + }) + return + } + + if (surface === root.desktop.activatedWindow) { + surface.transformOrigin = Item.TopLeft + previewAnimation.opacityFrom = 1.0 + surface.opacity = 1.0 + } else { + previewAnimation.duration = 500 + surface.x = previewAnimation.xFrom + surface.y = previewAnimation.yFrom + surface.opacity = 0.0 + surface.scale = previewAnimation.scaleFrom + } + + previewAnimation.start() + } + + function onRestoreSurfaces() { + previewAnimation.stop() + + if (!surface || !surface.shellSurface) + return + + surface.x = windowItem.surfaceX + surface.y = windowItem.surfaceY + surface.scale = 1 + surface.transformOrigin = windowItem.surfaceTransformOrigin + } + } + } + } + + function previewPostion(surface, content) { + const hSpacing = 20 + const vSpacing = 20 + let preferredHeight = surface.height < (content.height - 2 * vSpacing) ? + surface.height : (content.height - 2 * vSpacing) + let preferredWidth = surface.width < (content.width - 2 * hSpacing) ? + surface.width : (content.width - 2 * hSpacing) + let refHeight = preferredHeight * surface.width / surface.height < (content.width - 2 * hSpacing) + + return { + width: refHeight ? preferredHeight * surface.width / surface.height : preferredWidth, + height: refHeight ? preferredHeight : preferredWidth * surface.height / surface.width + } + } + + function ensurePreview() { + if (!previewContext.sourceComponent && root.enableAnimation) + previewContext.sourceComponent = previewContext.previewComponent + + if (root.enableAnimation) { + previewContext.loaderStatus = 1 + previewContext.loaderStatus = 0 + } + + if (!currentContext.sourceComponent) + currentContext.sourceComponent = currentContext.previewComponent + + if (root.enableAnimation) { + currentContext.loaderStatus = 0 + currentContext.loaderStatus = 1 + } + } + + function prejudgment(updateTimestamp) { + if (updateTimestamp) + root.lastSwitchTimestamp = Date.now() + + if (previewWindows.animationRunning) { + previewWindows.finishAnimation(true) + showTask(false) + } + + if (switchView.count <= 1) { + if (switchView.count === 1) { + previewContext.sourceSurface = switchView.currentItem.surface + if (!previewContext.sourceComponent && root.enableAnimation) + previewContext.sourceComponent = previewContext.previewComponent + showTask(true); + } + return false; + } + return true; + } + + function previous() { + if (!prejudgment(true)) + return; + + var nextIndex = (switchView.currentIndex - 1 + switchView.count) % switchView.count + + switchView.positionViewAtIndex(nextIndex, ListView.Beginning) + if (switchView.contentWidth > root.width && nextIndex !== 0) + switchView.contentX -= switchView.delegateMinWidth / 2 + + focusReason = Qt.BacktabFocusReason + switchIndex(nextIndex) + } + + function next() { + if (!prejudgment(true)) + return; + + var nextIndex = (switchView.currentIndex + 1) % switchView.count + + switchView.positionViewAtIndex(nextIndex, ListView.End) + if (switchView.contentWidth > root.width && nextIndex !== switchView.count - 1) + switchView.contentX += switchView.delegateMinWidth / 2 + + focusReason = Qt.TabFocusReason + switchIndex(nextIndex) + } + + function previousSameApp() { + if (switchView.currentItem && switchView.currentItem.surface) + root.model.setFilterAppId(switchView.currentItem.surface.appId) + + previous() + } + + function nextSameApp() { + if (switchView.currentItem && switchView.currentItem.surface) + root.model.setFilterAppId(switchView.currentItem.surface.appId) + + next() + } + + function show() { + if (!prejudgment(true)) + return; + + var nextIndex = switchView.currentIndex; + switchView.positionViewAtIndex(nextIndex, ListView.End) + + focusReason = Qt.ActiveWindowFocusReason + switchIndex(nextIndex) + } + + function switchIndex(next) { + if ((next >= 0 && next < switchView.count) && showTask(true)) { + previewContext.sourceSurface = switchView.currentItem.surface + switchView.currentIndex = next + root.model.activeIndex = switchView.currentIndex + + ensurePreview() + } + } + + function showTask(visible) { + if (visible && switchView.count === 0) { + root.visible = false + return false + } + + root.workspace.current.opaque = !visible + root.visible = visible + + return switchView.currentItem && switchView.visible + } + + function exitByMouse() { + if (Date.now() - root.lastSwitchTimestamp >= root.mouseExitInterval) + exit() + } + + function exit() { + if (!root.visible) { + root.switchOn = false + return + } + + if (previewWindows.animationRunning) { + prejudgment(false) + return + } + + if (root.enableAnimation) { + previewContext.loaderStatus = -1 + currentContext.loaderStatus = -1 + } + + if (root.enableAnimation) { + mask.opacity = 0.0 + + switchItemAnimation.stop() + switchItemAnimation.isInAni = false + switchItemAnimation.start() + } + + const playSurfaceAnimation = root.enableAnimation + && switchView.count > 0 && switchView.count <= 18 + const surfaceSnapshot = playSurfaceAnimation ? root.model.surfaceSnapshot() : [] + + const activationSurface = switchView.currentItem + ? switchView.currentItem.surface : null + + if (playSurfaceAnimation && surfaceSnapshot.length > 0) { + previewWindows.reverse = false + previewWindows.beginAnimation(surfaceSnapshot, activationSurface, focusReason) + } else { + previewWindows.reverse = false + previewWindows.finishedAnimations = 0 + previewWindows.model = [] + // Skipping the animation must not skip the selection: beginAnimation() + // activates the chosen window, so the direct path does the same. + if (activationSurface) + WaylandServer.forceActivateSurface(activationSurface, focusReason) + showTask(false) + root.switchOn = false + } + } +} diff --git a/src/core/qml/TaskWindowPreview.qml b/src/core/qml/TaskWindowPreview.qml new file mode 100644 index 0000000000..550f68d2f8 --- /dev/null +++ b/src/core/qml/TaskWindowPreview.qml @@ -0,0 +1,131 @@ +// Copyright (C) 2024 lbwtw . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Effects +import Treeland +import org.deepin.dtk 1.0 as D +import org.deepin.dtk.style 1.0 as DS + +Loader { + id: root + readonly property bool enableAnimation: WaylandServer.animationConfig.taskSwitcher + + signal clicked() + property int loaderStatus: 0 + property SurfaceWrapper sourceSurface + property alias previewComponent: sourceComponent + + transformOrigin: Item.Center + property real preferredHeight: !sourceSurface ? 0 : sourceSurface.height < (parent.height - 2 * vSpacing) ? + sourceSurface.height : (parent.height - 2 * vSpacing) + property real preferredWidth: !sourceSurface ? 0 : sourceSurface.width < (parent.width - 2 * hSpacing) ? + sourceSurface.width : (parent.width - 2 * hSpacing) + property bool refHeight: sourceSurface && preferredHeight * sourceSurface.width / sourceSurface.height < (parent.width - 2 * hSpacing) + readonly property real hSpacing: 20 + readonly property real vSpacing: 20 + + height: !sourceSurface ? 0 : refHeight ? preferredHeight : preferredWidth * sourceSurface.height / sourceSurface.width + width: !sourceSurface ? 0 : refHeight ? preferredHeight * sourceSurface.width / sourceSurface.height : preferredWidth + + onLoaderStatusChanged: { + if (loaderStatus === -1) { + enterAnimation.stop() + exitAnimation.stop() + } + } + + states: [ + State { + name: 'none' + when: root.loaderStatus === 0 + }, + State { + name: 'loaded' + when: root.loaderStatus === 1 + } + ] + transitions: [ + Transition { + from: "none" + to: "loaded" + enabled: root.enableAnimation + + ParallelAnimation { + id: enterAnimation + ScaleAnimator { + target: root + from: 0.5 + to: 1.0 + duration: 400 + easing.type: Easing.OutExpo + } + + OpacityAnimator { + target: root + from: 0.0 + to: 1.0 + duration: 100 + easing.type: Easing.OutExpo + } + } + }, + Transition { + from: "loaded" + to: "none" + enabled: root.enableAnimation + + ParallelAnimation { + id: exitAnimation + ScaleAnimator { + target: root + from: 1.0 + to: 0.5 + duration: 400 + easing.type: Easing.OutExpo + } + + OpacityAnimator { + target: root + from: 1.0 + to: 0.0 + duration: 400 + easing.type: Easing.OutExpo + } + } + } + ] + + Component { + id: sourceComponent + + Item { + anchors.fill: parent + transformOrigin: root.transformOrigin + + SurfaceProxy { + id: preview + + surface: sourceSurface + anchors.centerIn: parent + maxSize: Qt.size(root.width, root.height) + } + + MouseArea { + anchors.fill: parent + acceptedButtons: Qt.LeftButton + onClicked: function(mouse) { + root.clicked() + } + } + + TapHandler { + acceptedButtons: Qt.NoButton + acceptedDevices: PointerDevice.TouchScreen + onDoubleTapped: function(eventPoint, button) { + root.clicked() + } + } + } + } +} diff --git a/src/core/qml/TitleBar.qml b/src/core/qml/TitleBar.qml new file mode 100644 index 0000000000..55eb65de59 --- /dev/null +++ b/src/core/qml/TitleBar.qml @@ -0,0 +1,191 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Controls +import QtQuick.Shapes +import Waylib.Server +import Treeland +import org.deepin.dtk 1.0 as D + +Control { + id: root + + required property SurfaceWrapper surface + readonly property SurfaceItem surfaceItem: surface.surfaceItem + readonly property bool canToggleMaximize: surface.surfaceState === SurfaceWrapper.State.Maximized || surface.isMaximizable + readonly property bool noRadius: surface.frameGeometry.radius === 0 + clip: true + containmentMask: noRadius ? null : titleMask + + FrameInputMask { + id: titleMask + geometry: root.surface.frameGeometry + frameItem: root.surface.frameItem + target: root + } + property D.Palette backgroundColor: D.Palette { + normal: ("#ffffff") + normalDark: ("#282828") + } + property D.Palette textColor: D.Palette { + normal: ("#303030") + normalDark: ("#8c8c8c") + pressed: ("#0081FF") + pressedDark: ("#0081FF") + } + D.ColorSelector.inactived: !surface.isActivated + D.ColorSelector.hovered: false + + height: root.surface.desktop?.config.windowTitlebarHeight ?? 30 + width: surfaceItem.width + + // Ensure title bar does not accept keyboard focus + focusPolicy: Qt.NoFocus + + HoverHandler { + // block hover events to resizing mouse area, avoid cursor change + cursorShape: Qt.ArrowCursor + blocking: true + } + + // Left mouse button handler + TapHandler { + acceptedButtons: Qt.LeftButton + onTapped: { + WaylandServer.activateSurface(surface) + } + onDoubleTapped: { + if (root.canToggleMaximize) + surface.toggleMaximized() + } + } + + DragHandler { + acceptedButtons: Qt.LeftButton + target: null + dragThreshold: Qt.styleHints.startDragDistance + onActiveChanged: { + if (active) + surface.moveRequested() + } + } + + // Right mouse button handler + TapHandler { + acceptedButtons: Qt.RightButton + onTapped: { + surface.windowMenuRequested(eventPoint.position) + } + } + + // Touch screen click + TapHandler { + acceptedButtons: Qt.NoButton + acceptedDevices: PointerDevice.TouchScreen + onDoubleTapped: { + if (root.canToggleMaximize) + surface.toggleMaximized() + } + onLongPressed: surface.windowMenuRequested(point.position) + } + + Rectangle { + id: titlebar + anchors.fill: parent + color: root.D.ColorSelector.backgroundColor + layer.enabled: !root.noRadius + layer.smooth: !root.noRadius + opacity: !root.noRadius ? 0 : parent.opacity + Text { + readonly property int spacenum: 4 + anchors { + fill: parent + leftMargin: spacenum * root.height + rightMargin: spacenum * root.height + } + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + text: surface.shellSurface.title + elide: Text.ElideRight + color: root.D.ColorSelector.textColor + font.family: root.surface.desktop?.config.font ?? Qt.application.font.family + font.pointSize: (root.surface.desktop?.config.fontSize ?? 100) / 10 + font.weight: Font.Medium + } + + Row { + anchors { + verticalCenter: parent.verticalCenter + right: parent.right + rightMargin: root.surface.frameGeometry.radius + } + + Loader { + objectName: "minimizeBtn" + sourceComponent: D.WindowButton { + icon.name: "window_minimize" + textColor: root.textColor + height: root.height + focusPolicy: Qt.NoFocus + D.ColorSelector.inactived: !surface.isActivated + + onClicked: { + surface.minimize() + } + } + } + + Loader { + id: maxOrWindedBtn + objectName: "maxOrWindedBtn" + active: root.canToggleMaximize + sourceComponent: D.WindowButton { + icon.name: surface.shellSurface.isMaximized ? "window_restore" : "window_maximize" + textColor: root.textColor + height: root.height + focusPolicy: Qt.NoFocus + D.ColorSelector.inactived: !surface.isActivated + + onClicked: { + WaylandServer.activateSurface(surface) + surface.toggleMaximized() + } + } + } + + Loader { + objectName: "closeBtn" + sourceComponent: Item { + height: root.height + width: closeBtn.implicitWidth + Rectangle { + anchors.fill: closeBtn + color: closeBtn.hovered ? "red" : "transparent" + } + D.WindowButton { + id: closeBtn + icon.name: "window_close" + textColor: root.textColor + height: parent.height + focusPolicy: Qt.NoFocus + D.ColorSelector.inactived: !surface.isActivated + + onClicked: { + surface.closeSurface() + } + } + } + } + } + } + + Loader { + anchors.fill: parent + active: !root.noRadius + sourceComponent: FrameClip { + source: titlebar + geometry: root.surface.frameGeometry + } + } +} diff --git a/src/core/qml/WindowMenu.qml b/src/core/qml/WindowMenu.qml new file mode 100644 index 0000000000..51d87cc089 --- /dev/null +++ b/src/core/qml/WindowMenu.qml @@ -0,0 +1,104 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import Waylib.Server +import Treeland +import QtQuick.Controls + +Menu { + id: menu + modal: true + + property SurfaceWrapper surface: null + readonly property bool canToggleMaximize: surface + ? surface.surfaceState === SurfaceWrapper.State.Maximized || surface.isMaximizable + : false + + onActiveFocusChanged: { + if (!activeFocus) + close() + } + + onClosed: { + surface = null + } + + function showWindowMenu(surface, pos) { + menu.surface = surface + menu.parent = surface + menu.popup(pos) + } + + MenuItem { + text: qsTr("Minimize") + onTriggered: surface.minimize() + } + + MenuItem { + text: surface?.surfaceState === SurfaceWrapper.State.Maximized ? qsTr("Unmaximize") : qsTr("Maximize") + enabled: menu.canToggleMaximize + onTriggered: surface.toggleMaximized() + } + + MenuItem { + text: qsTr("Move") + onTriggered: surface.moveRequested() + } + + MenuItem { + text: qsTr("Resize") + onTriggered: WaylandServer.fakePressSurfaceBottomRightToReszie(surface) + } + + MenuItem { + readonly property bool isOverlay: menu.surface + ? menu.surface.surfaceRole === SurfaceWrapper.Overlay + || menu.surface.surfaceRole === SurfaceWrapper.PrivilegedOverlay + : false + + text: qsTr("Always on Top") + checkable: true + checked: menu.surface ? isOverlay || menu.surface.alwaysOnTop : false + enabled: menu.surface ? !isOverlay : false + onTriggered: menu.surface.alwaysOnTop = !menu.surface.alwaysOnTop + } + + MenuItem { + checked: surface ? surface.showOnAllWorkspace : false + text: qsTr("Always on Visible Workspace") + onTriggered: { + if (surface.showOnAllWorkspace) { + // Move to current workspace + surface.desktop.workspace.moveSurfaceTo(surface, surface.desktop.workspace.current.id) + } else { + // Move to workspace 0, which is always visible + surface.desktop.workspace.moveSurfaceTo(surface, -2) + } + } + } + + MenuItem { + property int leftWorkspaceId: surface ? surface.desktop.workspace.getLeftWorkspaceId(surface.workspaceId) : -1 + text: qsTr("Move to Left Work Space") + enabled: leftWorkspaceId >= 0 + onTriggered: { + surface.desktop.workspace.moveSurfaceTo(surface, leftWorkspaceId) + WaylandServer.activateSurface(surface.desktop.workspace.current.latestActiveSurface()) + } + } + + MenuItem { + property int rightWorkspaceId: surface ? surface.desktop.workspace.getRightWorkspaceId(surface.workspaceId) : -1 + text: qsTr("Move to Right Work Space") + enabled: rightWorkspaceId >= 0 + onTriggered: { + surface.desktop.workspace.moveSurfaceTo(surface, rightWorkspaceId) + WaylandServer.activateSurface(surface.desktop.workspace.current.latestActiveSurface()) + } + } + + MenuItem { + text: qsTr("Close") + onTriggered: surface.shellSurface.close() + } +} diff --git a/src/core/qml/WorkSpaceMask.qml b/src/core/qml/WorkSpaceMask.qml new file mode 100644 index 0000000000..fc0a059d9a --- /dev/null +++ b/src/core/qml/WorkSpaceMask.qml @@ -0,0 +1,68 @@ +// Copyright (C) 2024 lbwtw . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQml + +Loader { + id: root + + property alias blackComponent: rectComponent + readonly property int aniDuration: 400 + property int loaderStatus: 1 // 0 none ; 1 loaded + property real itemOpacity: 0.5 + + Component { + id: rectComponent + + Rectangle { + anchors.fill: parent + color: "black" + opacity: root.itemOpacity + + states: [ + State { + name: 'none' + when: loaderStatus === 0 + }, + State { + name: 'loaded' + when: loaderStatus === 1 + } + ] + transitions: [ + Transition { + from: "none" + to: "loaded" + + OpacityAnimator { + target: root.item + from: 0.0 + to: 0.5 + duration: root.aniDuration + easing.type: Easing.OutExpo + } + }, + Transition { + from: "loaded" + to: "none" + + onRunningChanged: { + if (running) + return + + root.sourceComponent = undefined + } + + OpacityAnimator { + target: root.item + from: 0.5 + to: 0.0 + duration: root.aniDuration + easing.type: Easing.OutExpo + } + } + ] + } + } +} diff --git a/src/core/qml/WorkspaceProxy.qml b/src/core/qml/WorkspaceProxy.qml new file mode 100644 index 0000000000..524c05ec3b --- /dev/null +++ b/src/core/qml/WorkspaceProxy.qml @@ -0,0 +1,54 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Treeland + +Item { + id: root + required property WorkspaceModel workspace + required property QtObject output + + width: output.outputItem.width + height: output.outputItem.height + clip: true + + Repeater { + model: workspace + delegate: Loader { + id: loader + + required property SurfaceWrapper surface + required property int orderIndex + + x: surface.x - output.outputItem.x + y: surface.y - output.outputItem.y + z: orderIndex + active: surface.ownsOutput === output + && !surface.minimized + sourceComponent: SurfaceProxy { + surface: loader.surface + fullProxy: true + } + } + } + Repeater { + model: root.workspace.workspaceManager.showOnAllWorkspaceModel + delegate: Loader { + id: allLoader + + required property SurfaceWrapper surface + required property int orderIndex + + x: surface.x - output.outputItem.x + y: surface.y - output.outputItem.y + z: orderIndex + active: surface.ownsOutput === output + && !surface.minimized + sourceComponent: SurfaceProxy { + surface: allLoader.surface + fullProxy: true + } + } + } +} diff --git a/src/core/qml/WorkspaceSwitcher.qml b/src/core/qml/WorkspaceSwitcher.qml new file mode 100644 index 0000000000..971371c872 --- /dev/null +++ b/src/core/qml/WorkspaceSwitcher.qml @@ -0,0 +1,55 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Treeland + +Item { + id: root + required property Workspace workspaceManager + anchors.fill: parent + visible: root.workspaceManager.animationController.running + Rectangle { + anchors.fill: parent + color: "black" + } + + Repeater { + model: WaylandServer.rootContainer.outputModel + Item { + id: animationDelegate + + required property int index + required property QtObject output + readonly property real localAnimationScaleFactor: width / root.workspaceManager.animationController.refWidth + clip: true + x: output.outputItem.x + y: output.outputItem.y + width: output.outputItem.width + height: output.outputItem.height + + Row { + x: - root.workspaceManager.animationController.viewportPos * animationDelegate.localAnimationScaleFactor + spacing: root.workspaceManager.animationController.refGap * animationDelegate.localAnimationScaleFactor + Repeater { + model: root.workspaceManager.models + delegate: Item { + width: animationDelegate.output.outputItem.width + height: animationDelegate.output.outputItem.height + id: workspaceDelegate + required property WorkspaceModel workspace + Wallpaper { + workspace: workspaceDelegate.workspace + output: animationDelegate.output.outputItem.output + } + + WorkspaceProxy { + workspace: workspaceDelegate.workspace + output: animationDelegate.output + } + } + } + } + } + } +} diff --git a/src/core/qml/XdgShadow.qml b/src/core/qml/XdgShadow.qml new file mode 100644 index 0000000000..09d08e630d --- /dev/null +++ b/src/core/qml/XdgShadow.qml @@ -0,0 +1,28 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Effects +import org.deepin.dtk 1.0 as D + +D.BoxShadow { + id: shadow + + // boundingRect must cover the blur plus any signed offset. Because this + // item is centered on the surface (anchors.centerIn in Decoration.qml), the + // extents grow symmetrically by |offset| so the shadow stays aligned with + // the surface while never clipping the offset shadow content. + readonly property rect boundingRect: Qt.rect( + -shadow.shadowBlur - Math.abs(shadow.shadowOffsetX), + -shadow.shadowBlur - Math.abs(shadow.shadowOffsetY), + width + 2 * shadow.shadowBlur + 2 * Math.abs(shadow.shadowOffsetX), + height + 2 * shadow.shadowBlur + 2 * Math.abs(shadow.shadowOffsetY)) + + width: parent.width + height: parent.height + shadowColor: Qt.rgba(0, 0, 0, 0.4) + shadowOffsetX: 0 + shadowOffsetY: 10 + shadowBlur: 40 + hollow: true +} diff --git a/src/core/qml/overridable/InWindowBlur.qml b/src/core/qml/overridable/InWindowBlur.qml new file mode 100644 index 0000000000..69f36671cd --- /dev/null +++ b/src/core/qml/overridable/InWindowBlur.qml @@ -0,0 +1,22 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Treeland + +Item { + id: control + + property alias offscreen: blur.contentOffscreen + property alias radius: blur.blurMax + property alias multiplier: blur.multiplier + property alias content: blur.effectContent + default property alias data: blur.data + property alias valid: blur.effectEnabled + + Blur { + id: blur + anchors.fill: parent + glassEnabled: false + } +} diff --git a/src/core/qmlengine.cpp b/src/core/qmlengine.cpp new file mode 100644 index 0000000000..2bd516ec51 --- /dev/null +++ b/src/core/qmlengine.cpp @@ -0,0 +1,314 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "qmlengine.h" +#include "desktop/desktopenvironment.h" + +#include "common/treelandlogging.h" +#include "core/rootsurfacecontainer.h" +#include "modules/capture/capture.h" +#include "output/output.h" +#include "surface/surfacewrapper.h" +#include "workspace/workspace.h" + +#include +#include + +#include +#include +#include + +namespace { + +QObject *installQmlFileSelector(QQmlEngine *engine) +{ + auto selector = new QQmlFileSelector(engine); + const auto api = QQuickWindow::graphicsApi(); + selector->setExtraSelectors({ + QStringLiteral("treeland"), + api == QSGRendererInterface::Vulkan ? QStringLiteral("vulkan") : QStringLiteral("gles"), + }); + return selector; +} + +} // namespace + +QmlEngine::QmlEngine(QObject *parent) + : QQmlApplicationEngine(parent) + , dtkInWindowBlurFileSelector(installQmlFileSelector(this)) + , titleBarComponent(this, "Treeland", "TitleBar") + , decorationComponent(this, "Treeland", "Decoration") + , windowMenuComponent(this, "Treeland", "WindowMenu") + , borderComponent(this, "Treeland", "Border") + , taskBarComponent(this, "Treeland", "TaskBar") + , surfaceContent(this, "Treeland", "SurfaceContent") + , captureSurfaceContent(this, "Treeland", "CaptureSurfaceContent") + , xdgShadowComponent(this, "Treeland", "XdgShadow") + , taskSwitchComponent(this, "Treeland", "TaskSwitcher") + , geometryAnimationComponent(this, "Treeland", "GeometryAnimation") + , windowTransitionComponent(this, "Treeland", "WindowTransition") + , menuBarComponent(this, "Treeland", "OutputMenuBar") + , workspaceSwitcher(this, "Treeland", "WorkspaceSwitcher") + , newAnimationComponent(this, "Treeland", "NewAnimation") +#ifndef DISABLE_DDM + , lockScreenComponent(this, "Treeland", "Greeter") +#endif + , dockPreviewComponent(this, "Treeland", "DockPreview") + , minimizeAnimationComponent(this, "Treeland", "MinimizeAnimation") + , showDesktopAnimatioComponentn(this, "Treeland", "ShowDesktopAnimation") + , captureSelectorComponent(this, "Treeland", "CaptureSelectorLayer") + , edgeTilePreviewComponent(this, "Treeland", "EdgeTilePreview") + , launchpadAnimationComponent(this, "Treeland", "LaunchpadAnimation") + , launchpadCoverComponent(this, "Treeland", "LaunchpadCover") + , layershellAnimationComponent(this, "Treeland", "LayerShellAnimation") + , lockScreenFallbackComponent(this, "Treeland", "LockScreenFallback") + , fpsDisplayComponent(this, "Treeland", "FpsDisplay") + , prelaunchSplashComponent(this, "Treeland", "PrelaunchSplash") +{ +} + +QQuickItem *QmlEngine::createComponent(QQmlComponent &component, + QQuickItem *parent, + const QVariantMap &properties) +{ + auto *context = qmlContext(parent); + if (!context) + context = rootContext(); + auto *obj = component.beginCreate(context); + if (!obj) + qCFatal(lcTlQml) << "Can't create component:" << component.errorString(); + if (!properties.isEmpty()) { + component.setInitialProperties(obj, properties); + } + auto item = qobject_cast(obj); + if (!item) { + qCFatal(lcTlQml) << "Can't create component:" << component.errorString(); + } + QQmlEngine::setObjectOwnership(item, QQmlEngine::objectOwnership(parent)); + item->setParent(parent); + item->setParentItem(parent); + component.completeCreate(); + + return item; +} + +QQuickItem *QmlEngine::createTitleBar(SurfaceWrapper *surface, QQuickItem *parent) +{ + return createComponent(titleBarComponent, + parent, + { { "surface", QVariant::fromValue(surface) } }); +} + +QQuickItem *QmlEngine::createDecoration(SurfaceWrapper *surface, QQuickItem *parent) +{ + return createComponent(decorationComponent, + parent, + { { "surface", QVariant::fromValue(surface) } }); +} + +QObject *QmlEngine::createWindowMenu(QObject *parent) +{ + auto *context = qmlContext(parent); + if (!context) + context = rootContext(); + auto *obj = windowMenuComponent.beginCreate(context); + if (!obj) { + qCFatal(lcTlQml) << "Can't create WindowMenu:" << windowMenuComponent.errorString(); + } + obj->setParent(parent); + windowMenuComponent.completeCreate(); + + return obj; +} + +QQuickItem *QmlEngine::createBorder(QQuickItem *parent) +{ + return createComponent(borderComponent, parent); +} + +QQuickItem *QmlEngine::createTaskBar(Output *output, QQuickItem *parent) +{ + return createComponent(taskBarComponent, parent, { { "output", QVariant::fromValue(output) } }); +} + +QQuickItem *QmlEngine::createXdgShadow(QQuickItem *parent) +{ + return createComponent(xdgShadowComponent, parent); +} + +QQuickItem *QmlEngine::createTaskSwitcher(Output *output, QQuickItem *parent, DesktopEnvironment *desktop) +{ + return createComponent(taskSwitchComponent, + parent, + { { "output", QVariant::fromValue(output) }, + { "desktop", QVariant::fromValue(desktop) } }); +} + +QQuickItem *QmlEngine::createGeometryAnimation(SurfaceWrapper *surface, + const QRectF &startGeo, + const QRectF &endGeo, + QQuickItem *parent) +{ + return createComponent(geometryAnimationComponent, + parent, + { + { "surface", QVariant::fromValue(surface) }, + { "fromGeometry", QVariant::fromValue(startGeo) }, + { "toGeometry", QVariant::fromValue(endGeo) }, + }); +} + +QQuickItem *QmlEngine::createWindowTransition(SurfaceWrapper *surface, + const QRectF &startGeo, + const QRectF &endGeo, + QQuickItem *parent, + WSurface *sourceSurface, + int direction) +{ + return createComponent(windowTransitionComponent, + parent, + { + { "surface", QVariant::fromValue(surface) }, + { "fromGeometry", QVariant::fromValue(startGeo) }, + { "toGeometry", QVariant::fromValue(endGeo) }, + { "sourceSurface", QVariant::fromValue(sourceSurface) }, + { "direction", QVariant::fromValue(direction) }, + }); +} + +QQuickItem *QmlEngine::createMenuBar(WOutputItem *output, QQuickItem *parent) +{ + return createComponent(menuBarComponent, parent, { { "output", QVariant::fromValue(output) } }); +} + +QQuickItem *QmlEngine::createWorkspaceSwitcher(Workspace *parent) +{ + return createComponent(workspaceSwitcher, parent, {{"workspaceManager", QVariant::fromValue(parent)}}); +} + +QQuickItem *QmlEngine::createNewAnimation(SurfaceWrapper *surface, + QQuickItem *parent, + uint direction) +{ + return createComponent(newAnimationComponent, + parent, + { + { "target", QVariant::fromValue(surface) }, + { "direction", QVariant::fromValue(direction) }, + }); +} + +QQuickItem *QmlEngine::createLaunchpadAnimation(SurfaceWrapper *surface, + uint direction, + QQuickItem *parent) +{ + return createComponent(launchpadAnimationComponent, + parent, + { + { "target", QVariant::fromValue(surface) }, + { "direction", QVariant::fromValue(direction) }, + }); +} + +QQuickItem *QmlEngine::createLaunchpadCover(SurfaceWrapper *surface, + Output *output, + QQuickItem *parent) +{ + return createComponent(launchpadCoverComponent, + parent, + { { "wrapper", QVariant::fromValue(surface) }, + { "output", QVariant::fromValue(output->output()) } }); +} + +QQuickItem *QmlEngine::createLayerShellAnimation(SurfaceWrapper *surface, + QQuickItem *parent, + uint direction) +{ + return createComponent(layershellAnimationComponent, + parent, + { + { "target", QVariant::fromValue(surface) }, + { "direction", QVariant::fromValue(direction) }, + }); +} + +QQuickItem *QmlEngine::createDockPreview(QQuickItem *parent, DesktopEnvironment *desktop) +{ + return createComponent(dockPreviewComponent, parent, {{"desktop", QVariant::fromValue(desktop)}}); +} + +QQuickItem *QmlEngine::createLockScreen([[maybe_unused]] Output *output, + [[maybe_unused]] QQuickItem *parent) +{ +#ifndef DISABLE_DDM + return createComponent(lockScreenComponent, + parent, + { { "output", QVariant::fromValue(output->output()) }, + { "outputItem", QVariant::fromValue(output->outputItem()) } }); +#else + Q_UNREACHABLE_RETURN(nullptr); +#endif +} + +QQuickItem *QmlEngine::createMinimizeAnimation(SurfaceWrapper *surface, + QQuickItem *parent, + const QRectF &iconGeometry, + uint direction) +{ + return createComponent(minimizeAnimationComponent, + parent, + { + { "target", QVariant::fromValue(surface) }, + { "position", QVariant::fromValue(iconGeometry) }, + { "direction", QVariant::fromValue(direction) }, + }); +} + +QQuickItem *QmlEngine::createShowDesktopAnimation(SurfaceWrapper *surface, + QQuickItem *parent, + bool show) +{ + return createComponent(showDesktopAnimatioComponentn, + parent, + { + { "target", QVariant::fromValue(surface) }, + { "showDesktop", QVariant::fromValue(show) }, + }); +} + +QQuickItem *QmlEngine::createCaptureSelector(QQuickItem *parent, CaptureManagerV1 *captureManager) +{ + return createComponent( + captureSelectorComponent, + parent, + { { "captureManager", QVariant::fromValue(captureManager) }, + { "z", QVariant::fromValue(RootSurfaceContainer::CaptureLayerZOrder) } }); +} + +QQuickItem *QmlEngine::createEdgeTilePreview(QQuickItem *parent) +{ + return createComponent(edgeTilePreviewComponent, parent); +} + +QQuickItem *QmlEngine::createLockScreenFallback(QQuickItem *parent, const QVariantMap &properties) +{ + return createComponent(lockScreenFallbackComponent, parent, properties); +} + +QQuickItem *QmlEngine::createFpsDisplay(QQuickItem *parent) +{ + return createComponent(fpsDisplayComponent, parent); +} + +QQuickItem *QmlEngine::createPrelaunchSplash(SurfaceWrapper *parent, + wlr_buffer *iconBuffer, + const QColor &backgroundColor) +{ + return createComponent(prelaunchSplashComponent, + parent, + { + { "surface", QVariant::fromValue(parent) }, + { "iconBuffer", QVariant::fromValue(iconBuffer) }, + { "backgroundColor", QVariant::fromValue(backgroundColor) }, + }); +} diff --git a/src/core/qmlengine.h b/src/core/qmlengine.h new file mode 100644 index 0000000000..3e1be2f482 --- /dev/null +++ b/src/core/qmlengine.h @@ -0,0 +1,122 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include +#include +#include + +QT_BEGIN_NAMESPACE +class QQuickItem; +QT_END_NAMESPACE + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutputItem; +class WSurface; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class SurfaceWrapper; +class Output; +class Workspace; +class DesktopEnvironment; +class WorkspaceModel; +class CaptureManagerV1; +class QmlEngine : public QQmlApplicationEngine +{ + Q_OBJECT +public: + explicit QmlEngine(QObject *parent = nullptr); + + QQuickItem *createComponent(QQmlComponent &component, + QQuickItem *parent, + const QVariantMap &properties = QVariantMap()); + QQuickItem *createTitleBar(SurfaceWrapper *surface, QQuickItem *parent); + QQuickItem *createDecoration(SurfaceWrapper *surface, QQuickItem *parent); + QObject *createWindowMenu(QObject *parent); + QQuickItem *createBorder(QQuickItem *parent); + QQuickItem *createTaskBar(Output *output, QQuickItem *parent); + QQuickItem *createXdgShadow(QQuickItem *parent); + QQuickItem *createTaskSwitcher(Output *output, QQuickItem *parent, DesktopEnvironment *desktop); + QQuickItem *createGeometryAnimation(SurfaceWrapper *surface, + const QRectF &startGeo, + const QRectF &endGeo, + QQuickItem *parent); + QQuickItem *createWindowTransition(SurfaceWrapper *surface, + const QRectF &startGeo, + const QRectF &endGeo, + QQuickItem *parent, + WSurface *sourceSurface = nullptr, + int direction = 0); + QQuickItem *createMenuBar(WOutputItem *output, QQuickItem *parent); + QQuickItem *createWorkspaceSwitcher(Workspace *parent); + QQuickItem *createNewAnimation(SurfaceWrapper *surface, QQuickItem *parent, uint direction); + QQuickItem *createLaunchpadAnimation(SurfaceWrapper *surface, + uint direction, + QQuickItem *parent); + QQuickItem *createLaunchpadCover(SurfaceWrapper *surface, Output *output, QQuickItem *parent); + QQuickItem *createLayerShellAnimation(SurfaceWrapper *surface, + QQuickItem *parent, + uint direction); + QQuickItem *createLockScreen(Output *output, QQuickItem *parent); + QQuickItem *createMinimizeAnimation(SurfaceWrapper *surface, + QQuickItem *parent, + const QRectF &iconGeometry, + uint direction); + QQuickItem *createDockPreview(QQuickItem *parent, DesktopEnvironment *desktop); + QQuickItem *createShowDesktopAnimation(SurfaceWrapper *surface, QQuickItem *parent, bool show); + QQuickItem *createCaptureSelector(QQuickItem *parent, CaptureManagerV1 *captureManager); + QQuickItem *createEdgeTilePreview(QQuickItem *parent); + QQuickItem *createLockScreenFallback(QQuickItem *parent, + const QVariantMap &properties = QVariantMap()); + QQuickItem *createFpsDisplay(QQuickItem *parent); + QQuickItem *createPrelaunchSplash(SurfaceWrapper *parent, + wlr_buffer *iconBuffer, + const QColor &backgroundColor); + + QQmlComponent *surfaceContentComponent() + { + return &surfaceContent; + } + + QQmlComponent *captureSurfaceContentComponent() + { + return &captureSurfaceContent; + } + +private: + QObject *const dtkInWindowBlurFileSelector; + QQmlComponent titleBarComponent; + QQmlComponent decorationComponent; + QQmlComponent windowMenuComponent; + QQmlComponent borderComponent; + QQmlComponent taskBarComponent; + QQmlComponent surfaceContent; + QQmlComponent captureSurfaceContent; + QQmlComponent xdgShadowComponent; + QQmlComponent taskSwitchComponent; + QQmlComponent geometryAnimationComponent; + QQmlComponent windowTransitionComponent; + QQmlComponent menuBarComponent; + QQmlComponent workspaceSwitcher; + QQmlComponent newAnimationComponent; +#ifndef DISABLE_DDM + QQmlComponent lockScreenComponent; +#endif + QQmlComponent dockPreviewComponent; + QQmlComponent minimizeAnimationComponent; + QQmlComponent showDesktopAnimatioComponentn; + QQmlComponent captureSelectorComponent; + QQmlComponent edgeTilePreviewComponent; + QQmlComponent launchpadAnimationComponent; + QQmlComponent launchpadCoverComponent; + QQmlComponent layershellAnimationComponent; + QQmlComponent lockScreenFallbackComponent; + QQmlComponent fpsDisplayComponent; + QQmlComponent prelaunchSplashComponent; +}; diff --git a/src/core/rootsurfacecontainer.cpp b/src/core/rootsurfacecontainer.cpp new file mode 100644 index 0000000000..1bce021d7f --- /dev/null +++ b/src/core/rootsurfacecontainer.cpp @@ -0,0 +1,1161 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "rootsurfacecontainer.h" +#include "session/session.h" + +#include "common/treelandlogging.h" +#include "output/output.h" +#include "core/waylandserver.h" +#include "seat/seatmanager.h" +#include "surface/surfacewrapper.h" +#include "treelandconfig.hpp" +#include "treelanduserconfig.hpp" +#include "workspace/workspace.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { + +void setPrimaryOutputConfig(Output *output) +{ + auto *server = WaylandServer::instance(); + if (!server) + return; + + auto *config = server->globalConfig(); + config->setPrimaryOutputId(output->getOutputId()); +} + +} + +OutputListModel::OutputListModel(QObject *parent) + : ObjectListModel("output", parent) +{ +} + +RootSurfaceContainer::RootSurfaceContainer(QQuickItem *parent) + : SurfaceContainer(parent) + , m_outputModel(new OutputListModel(this)) + , m_cursor(new WCursor(this)) +{ + m_cursor->setEventWindow(window()); +} + +RootSurfaceContainer::~RootSurfaceContainer() +{ + // Clean up per-seat containers + qDeleteAll(m_seatContainers); + m_seatContainers.clear(); +} + +void RootSurfaceContainer::init(WServer *server) +{ + m_outputLayout = new WOutputLayout(server); + m_cursor->setLayout(m_outputLayout); + connect(m_outputLayout, &WOutputLayout::implicitWidthChanged, this, [this] { + const auto width = m_outputLayout->implicitWidth(); + window()->setWidth(width); + setWidth(width); + }); + + connect(m_outputLayout, &WOutputLayout::implicitHeightChanged, this, [this] { + const auto height = m_outputLayout->implicitHeight(); + window()->setHeight(height); + setHeight(height); + }); + + // Listen on the native wlr_output_layout change signal (fires on add, + // remove, reposition and commit-triggered reconfiguration), matching the + // baseline qw_output_layout::notify_change wiring. + m_outputLayoutListenerOwner = std::make_unique(); + m_outputLayout->listeners(m_outputLayoutListenerOwner.get())->add( + &m_outputLayout->handle()->events.change, this, [this] { + for (auto output : std::as_const(outputs())) { + output->updatePositionFromLayout(); + } + ensureCursorVisible(); + // The layout may have moved/removed the output under the cursor, so + // refresh the cache even without a cursor motion event. + updateCursorOutput(); + + // for (auto s : m_surfaceContainer->surfaces()) { + // ensureSurfaceNormalPositionValid(s); + // updateSurfaceOutputs(s); + // } + }); + + m_dragSurfaceItem = new WSurfaceItem(window()->contentItem()); + m_dragSurfaceItem->setZ( + static_cast>(WOutputLayout::Layer::Cursor) + - 1); + m_dragSurfaceItem->setFlags(WSurfaceItem::DontCacheLastBuffer); + + QObject::connect(m_cursor, &WCursor::positionChanged, this, [this] { + m_dragSurfaceItem->setPosition(m_cursor->position()); + updateCursorOutput(); + }); + + QObject::connect(m_cursor, &WCursor::requestedDragSurfaceChanged, this, [this] { + m_dragSurfaceItem->setSurface(m_cursor->requestedDragSurface()); + }); + + setupSeatManagement(); +} + +SurfaceWrapper *RootSurfaceContainer::getSurface(WSurface *surface) const +{ + const auto surfaces = this->surfaces(); + for (const auto &wrapper : surfaces) { + if (wrapper->surface() == surface) + return wrapper; + } + return nullptr; +} + +SurfaceWrapper *RootSurfaceContainer::getSurface(WToplevelSurface *surface) const +{ + const auto surfaces = this->surfaces(); + for (const auto &wrapper : surfaces) { + if (wrapper->shellSurface() == surface) + return wrapper; + } + return nullptr; +} + +void RootSurfaceContainer::destroyForSurface(SurfaceWrapper *wrapper) +{ + // Clean up per-seat state for this surface + for (auto *container : std::as_const(m_seatContainers)) { + container->surfaceDestroyed(wrapper); + } + + wrapper->destroy(); +} + +void RootSurfaceContainer::addOutput(Output *output) +{ + m_outputModel->addObject(output); + m_outputLayout->autoAdd(output->output()); + if (!m_primaryOutput) + setPrimaryOutput(output); + + // Register all outputs (including primary and proxy/copy) to ensure + // LayerSurfaceContainer is initialized for every active display. + SurfaceContainer::addOutput(output); + + // Layer surfaces are re-entered by LayerSurfaceContainer::addOutput + // which calls setOutputs. Skip them here to avoid double re-enter. + for (auto s : std::as_const(surfaces())) { + if (s->type() == SurfaceWrapper::Type::Layer) + continue; + updateSurfaceOutputs(s, SurfaceWrapper::OutputsUpdateReason::AddOutput); + } + + // A disabled output is dropped by updateSurfaceOutputs(), and a surface can + // be left with no output at all (e.g. the screen was turned off by DPMS) + // until it is re-enabled. That is not a geometry change, so nothing would + // recompute the outputs: the surface would keep an empty frame pacing output + // and freeze forever. Recompute here once the output is really enabled + // again, which also covers the first enable commit of a newly added output. + // A member slot instead of a lambda: Output is recreated (mirror/extension + // switching) while its WOutput lives on, so the handler must not capture it, + // and UniqueConnection keeps one handler per WOutput however often the + // output is registered again. + QObject::connect(output->output(), + &WOutput::enabledChanged, + this, + &RootSurfaceContainer::onOutputEnabledChanged, + Qt::UniqueConnection); +} + +void RootSurfaceContainer::onOutputEnabledChanged() +{ + // enabledChanged() carries no argument, read the new state from the sender. + // Disabling keeps the previous behaviour (the lists are cleared only when + // something recomputes them); re-enabling is the case that has to heal. + auto *woutput = qobject_cast(sender()); + if (!woutput || !woutput->isEnabled()) + return; + + // Layer surfaces keep the outputs their OutputLayerSurfaceContainer gave + // them: updateSurfaceOutputs() intersects their geometry without filtering + // disabled outputs, so calling it here would put a layer surface back on an + // output that is still off. Skip them here for the same reason as the loop in + // addOutput() above. + for (auto s : std::as_const(surfaces())) { + if (s->type() == SurfaceWrapper::Type::Layer) + continue; + updateSurfaceOutputs(s, SurfaceWrapper::OutputsUpdateReason::EnabledChanged); + } +} + +void RootSurfaceContainer::removeOutput(Output *output) +{ + m_outputModel->removeObject(output); + + // Move the primary output away from the removed one *before* the sub containers + // are torn down: LayerSurfaceContainer::removeOutput() re-homes layer surfaces + // without an explicit output to primaryOutput(), and that must never be the + // output being removed (its OutputLayerSurfaceContainer is already gone by + // then). + movePrimaryOutputAwayFrom(output); + + // Finish any move/resize that grabbed a surface on this output before its + // containers are torn down, so the seats still see them (same order as + // removeBySubContainer()). + for (auto *container : std::as_const(m_seatContainers)) { + if (container->moveResizeSurface() && + container->moveResizeSurface()->ownsOutput() == output) { + container->endMoveResize(); + } + } + + m_outputLayout->remove(output->output()); + SurfaceContainer::removeOutput(output); + + // ensure cursor within output + const auto outputPos = output->outputItem()->position(); + if (output->geometry().contains(m_cursor->position()) && m_primaryOutput) { + const auto posInOutput = m_cursor->position() - outputPos; + const auto newCursorPos = m_primaryOutput->outputItem()->position() + posInOutput; + + if (m_primaryOutput->geometry().contains(newCursorPos)) + WaylandServer::instance()->setCursorPosition(newCursorPos); + else + WaylandServer::instance()->setCursorPosition(m_primaryOutput->geometry().center()); + } +} + +void RootSurfaceContainer::beginMoveResize(SurfaceWrapper *surface, Qt::Edges edges) +{ + // Delegate to default seat (seats.first()) + beginMoveResizeForSeat(nullptr, surface, edges, /*overrideCursor=*/true); +} + +void RootSurfaceContainer::doMoveResize(const QPointF &incrementPos) +{ + // Delegate to default seat (seats.first()) + doMoveResizeForSeat(nullptr, incrementPos); +} + +void RootSurfaceContainer::cancelMoveResize(SurfaceWrapper *surface) +{ + // Check all seat containers + for (auto *container : std::as_const(m_seatContainers)) { + if (container->moveResizeSurface() == surface) { + container->endMoveResize(); + return; + } + } +} + +void RootSurfaceContainer::endMoveResize() +{ + endMoveResizeForSeat(nullptr); +} + +SurfaceWrapper *RootSurfaceContainer::moveResizeSurface() const +{ + return getMoveResizeSurfaceForSeat(nullptr); +} + +bool RootSurfaceContainer::isInMoveResize() const +{ + return isInMoveResizeForSeat(nullptr); +} + +void RootSurfaceContainer::startMove(SurfaceWrapper *surface) +{ + if (beginMoveResizeForSeat(nullptr, surface, Qt::Edges{}, /*overrideCursor=*/false)) + WaylandServer::instance()->activateSurface(surface); +} + +void RootSurfaceContainer::startResize(SurfaceWrapper *surface, Qt::Edges edges) +{ + Q_ASSERT(edges != 0); + if (!surface || !surface->isResizable()) + return; + + if (!beginMoveResizeForSeat(nullptr, surface, edges, /*overrideCursor=*/true)) + return; + + surface->shellSurface()->setResizeing(true); + WaylandServer::instance()->activateSurface(surface); +} + +void RootSurfaceContainer::addSurface(SurfaceWrapper *) +{ + Q_UNREACHABLE_RETURN(); +} + +void RootSurfaceContainer::removeSurface(SurfaceWrapper *) +{ + Q_UNREACHABLE_RETURN(); +} + +void RootSurfaceContainer::addBySubContainer(SurfaceContainer *sub, SurfaceWrapper *surface) +{ + SurfaceContainer::addBySubContainer(sub, surface); + + if (surface->type() != SurfaceWrapper::Type::Layer) { + // RootSurfaceContainer does not have control over layer surface's position and ownsOutput + // All things are done in LayerSurfaceContainer + + setupSurfaceRequestHandlers(surface); + + if (!surface->ownsOutput()) { + auto parentSurface = surface->parentSurface(); + auto output = parentSurface ? parentSurface->ownsOutput() : cursorOutput(); + if (!output) + output = primaryOutput(); + + if (auto xdgPopupSurface = qobject_cast(surface->shellSurface())) { + if (parentSurface->type() != SurfaceWrapper::Type::Layer) { + // If parentSurface is Layer surface, follow parentSurface->ownsOutput + // getPopupPosition() is in the parent's surface coordinates; + // map it through the parent wrapper (content offset + paddings). + auto pos = parentSurface->position() + + parentSurface->mapFromSurface(xdgPopupSurface->getPopupPosition()); + if (auto op = wlr_output_layout_output_at(m_outputLayout->handle(), pos.x(), pos.y())) + output = + WaylandServer::instance()->getOutput(WOutput::fromHandle(op)); + } + } + surface->setOwnsOutput(output); + } + + connect(surface, &SurfaceWrapper::geometryChanged, this, [this, surface] { + updateSurfaceOutputs(surface, SurfaceWrapper::OutputsUpdateReason::GeometryChanged); + }); + + updateSurfaceOutputs(surface, SurfaceWrapper::OutputsUpdateReason::SurfaceAdded); + } +} + +void RootSurfaceContainer::removeBySubContainer(SurfaceContainer *sub, SurfaceWrapper *surface) +{ + // End move/resize for this surface in all containers + for (auto *container : std::as_const(m_seatContainers)) { + if (container->moveResizeSurface() == surface) { + container->endMoveResize(); + } + } + + SurfaceContainer::removeBySubContainer(sub, surface); +} + +bool RootSurfaceContainer::filterSurfaceGeometryChanged(SurfaceWrapper *surface, + QRectF &newGeometry, + [[maybe_unused]] const QRectF &oldGeometry) +{ + // Keep the opposite edge at its position when the drag began. + auto adjustForResize = [](QRectF &geometry, + const QRectF &startGeometry, + Qt::Edges edges) { + if (edges & Qt::RightEdge) + geometry.moveLeft(startGeometry.left()); + if (edges & Qt::BottomEdge) + geometry.moveTop(startGeometry.top()); + if (edges & Qt::LeftEdge) + geometry.moveRight(startGeometry.right()); + if (edges & Qt::TopEdge) + geometry.moveBottom(startGeometry.bottom()); + }; + + // Check all per-seat containers for move/resize state + for (auto *container : std::as_const(m_seatContainers)) { + auto &mrState = container->moveResizeState(); + if (mrState.surface == surface) { + const auto &edges = mrState.edges; + if (edges != 0 && mrState.settingPositionFlag) { + // CRITICAL: Return true ONLY during recursive updates to prevent infinite loops + Q_ASSERT(newGeometry.size() == oldGeometry.size()); + return true; + } + + if (edges != 0) { + QRectF adjustedGeo = newGeometry; + adjustForResize(adjustedGeo, mrState.startGeometry, edges); + + if (adjustedGeo.topLeft() != newGeometry.topLeft()) { + newGeometry = adjustedGeo; + mrState.settingPositionFlag = true; + surface->setPosition(newGeometry.topLeft()); + mrState.settingPositionFlag = false; + } + return false; + } + } + } + + return false; +} + +bool RootSurfaceContainer::filterSurfaceStateChange(SurfaceWrapper *surface, + [[maybe_unused]] SurfaceWrapper::State newState, + [[maybe_unused]] SurfaceWrapper::State oldState) +{ + // Check all per-seat containers for move/resize state + for (auto *container : std::as_const(m_seatContainers)) { + const auto &mrState = container->moveResizeState(); + if (mrState.surface == surface && mrState.edges != 0) + return true; + } + + return false; +} + +WOutputLayout *RootSurfaceContainer::outputLayout() const +{ + return m_outputLayout; +} + +WCursor *RootSurfaceContainer::cursor() const +{ + return m_cursor; +} + +Output *RootSurfaceContainer::cursorOutput() const +{ + Q_ASSERT(m_cursor->layout() == m_outputLayout); + return m_cursorOutput; +} + +void RootSurfaceContainer::updateCursorOutput() +{ + Output *output = outputAt(m_cursor->position()); + if (output == m_cursorOutput) + return; + + m_cursorOutput = output; + Q_EMIT cursorOutputChanged(output); +} + +Output *RootSurfaceContainer::outputAt(const QPointF &pos) const +{ + auto o = wlr_output_layout_output_at(m_outputLayout->handle(), pos.x(), pos.y()); + if (!o) + return nullptr; + + return WaylandServer::instance()->getOutput(WOutput::fromHandle(o)); +} + +Output *RootSurfaceContainer::primaryOutput() const +{ + return m_primaryOutput; +} + +void RootSurfaceContainer::setPrimaryOutput(Output *newPrimaryOutput, bool updateDconfig) +{ + if (m_primaryOutput == newPrimaryOutput) + return; + + m_primaryOutput = newPrimaryOutput; + Q_EMIT primaryOutputChanged(); + if (updateDconfig) + setPrimaryOutputConfig(newPrimaryOutput); +} + +void RootSurfaceContainer::movePrimaryOutputAwayFrom(const Output *output) +{ + if (!output || m_primaryOutput != output) + return; + + // Entries of the layout can be in intermediate states (copy mode replacement, + // pending outputs) where getOutput() cannot resolve them, so skip those instead + // of giving up on the first one. Without a remaining output the primary becomes + // null: layer surfaces created without an explicit output are then closed + // instead of being re-homed to the output being removed. + for (auto *o : m_outputLayout->outputs()) { + if (o == output->output()) { + continue; + } + if (auto *candidate = WaylandServer::instance()->getOutput(o)) { + setPrimaryOutput(candidate); + return; + } + } + + setPrimaryOutput(nullptr); +} + +const QList &RootSurfaceContainer::outputs() const +{ + return m_outputModel->objects(); +} + +void RootSurfaceContainer::ensureCursorVisible() +{ + const auto cursorPos = m_cursor->position(); + if (wlr_output_layout_output_at(m_outputLayout->handle(), cursorPos.x(), cursorPos.y())) + return; + + if (m_primaryOutput) { + WaylandServer::instance()->setCursorPosition(m_primaryOutput->geometry().center()); + } +} + +void RootSurfaceContainer::updateSurfaceOutputs(SurfaceWrapper *surface, + SurfaceWrapper::OutputsUpdateReason reason) +{ + QList outputs; + + const auto &allOutputs = m_outputModel->objects(); + int enabledOutputs = 0; + for (auto *output : allOutputs) { + if (output->output()->isEnabled()) + ++enabledOutputs; + } + + if (surface->type() != SurfaceWrapper::Type::Layer) { + for (auto *output : m_outputModel->objects()) { + if (!output->output()->isEnabled()) + continue; + + outputs.append(output->output()); + if (outputs.size() > 1) + break; + } + + if (outputs.size() != 1) { + const QRectF geometry = surface->geometry(); + outputs = m_outputLayout->getIntersectedOutputs(geometry.toRect()); + outputs.removeIf([](WOutput *output) { + return !output->isEnabled(); + }); + } + } else { + // Unreachable today: every caller skips layer surfaces (see the loops in + // addOutput() and onOutputEnabledChanged()). This branch has no + // isEnabled() filter, so making it reachable needs one first, or a layer + // surface lands back on an output that is still off. + const QRectF geometry = surface->geometry(); + outputs = m_outputLayout->getIntersectedOutputs(geometry.toRect()); + } + // A new window's initial position is (0,0) before placement, so geometry-based + // intersection may not include ownsOutput. Add it to keep outputs consistent. + if (surface->positionAutomatic() && surface->ownsOutput() + && !outputs.contains(surface->ownsOutput()->output())) + outputs.append(surface->ownsOutput()->output()); + surface->noteOutputsUpdate(reason, + enabledOutputs, + static_cast(allOutputs.size()), + static_cast(outputs.size())); + surface->setOutputs(outputs, /*recordDiagnostics=*/true); + + if (auto *ws = WaylandServer::instance()->workspace()) + ws->updateSurfaceOwnsOutput(surface); +} + +static qreal pointToRectMinDistance(const QPointF &pos, const QRectF &rect) +{ + if (rect.contains(pos)) + return 0; + return std::min({ std::abs(rect.x() - pos.x()), + std::abs(rect.y() - pos.y()), + std::abs(rect.right() - pos.x()), + std::abs(rect.bottom() - pos.y()) }); +} + +static QRectF adjustRectToMakePointVisible(const QRectF &inputRect, + const QPointF &absolutePoint, + const QList &visibleAreas) +{ + Q_ASSERT(inputRect.contains(absolutePoint)); + QRectF adjustedRect = inputRect; + + QRectF targetRect; + qreal distanceToTargetRect = std::numeric_limits::max(); + for (const QRectF &area : visibleAreas) { + Q_ASSERT(!area.isEmpty()); + if (area.contains(absolutePoint)) + return adjustedRect; + const auto distance = pointToRectMinDistance(absolutePoint, area); + if (distance < distanceToTargetRect) { + distanceToTargetRect = distance; + targetRect = area; + } + } + Q_ASSERT(!targetRect.isEmpty()); + + if (absolutePoint.x() < targetRect.x()) + adjustedRect.moveLeft(adjustedRect.x() + targetRect.x() - absolutePoint.x()); + else if (absolutePoint.x() > targetRect.right()) + adjustedRect.moveRight(adjustedRect.right() + targetRect.right() - absolutePoint.x()); + + if (absolutePoint.y() < targetRect.y()) + adjustedRect.moveTop(adjustedRect.y() + targetRect.y() - absolutePoint.y()); + else if (absolutePoint.y() > targetRect.bottom()) + adjustedRect.moveBottom(adjustedRect.bottom() + targetRect.bottom() - absolutePoint.y()); + + return adjustedRect; +} + +void RootSurfaceContainer::ensureSurfaceNormalPositionValid(SurfaceWrapper *surface) +{ + if (surface->type() == SurfaceWrapper::Type::Layer) + return; + + auto normalGeo = surface->normalGeometry(); + if (normalGeo.size().isEmpty()) + return; + + auto output = surface->ownsOutput(); + if (!output) + return; + + QList outputRects; + qreal minScreenX = std::numeric_limits::max(); + outputRects.reserve(outputs().size()); + for (auto o : std::as_const(outputs())) { + outputRects << o->validGeometry(); + minScreenX = qMin(minScreenX, o->validGeometry().left()); + } + + // Ensure window is not outside the screen + QPointF mustVisiblePosOfSurface(qMin(normalGeo.right(), normalGeo.x() + 20), + qMin(normalGeo.bottom(), normalGeo.y() + 20)); + + if (normalGeo.x() < minScreenX) { + mustVisiblePosOfSurface.setX(qMax(normalGeo.left(), normalGeo.right() - 20)); + } + + normalGeo = adjustRectToMakePointVisible(normalGeo, mustVisiblePosOfSurface, outputRects); + + // Ensure titlebar is not above the screen + const auto titlebarGeometry = surface->titlebarGeometry().translated(normalGeo.topLeft()); + if (titlebarGeometry.isValid()) { + for (auto r : std::as_const(outputRects)) { + if ((r & titlebarGeometry).isEmpty()) + continue; + if (titlebarGeometry.top() < r.top()) { + normalGeo.moveTop(normalGeo.top() + r.top() - titlebarGeometry.top()); + break; // Only need to adjust once based on the intersected output + } + } + } + + surface->moveNormalGeometryInOutput(normalGeo.topLeft()); +} + +OutputListModel *RootSurfaceContainer::outputModel() const +{ + return m_outputModel; +} + +void RootSurfaceContainer::moveSurfacesToOutput(const QList &surfaces, + Output *targetOutput, + Output *sourceOutput) +{ + if (!surfaces.isEmpty() && targetOutput) { + const QRectF targetGeometry = targetOutput->geometry(); + + for (auto *surface : surfaces) { + if (!surface) + continue; + + const QSizeF size = surface->size(); + QPointF newPos; + + if (surface->ownsOutput() == targetOutput) { + newPos = surface->position(); + } else { + const QRectF sourceGeometry = + sourceOutput ? sourceOutput->geometry() : surface->ownsOutput()->geometry(); + const QPointF relativePos = surface->position() - sourceGeometry.center(); + newPos = targetGeometry.center() + relativePos; + surface->setOwnsOutput(targetOutput); + } + if (newPos.x() + size.width() > targetGeometry.right()) + newPos.setX(targetGeometry.right() - size.width()); + if (newPos.x() < targetGeometry.left()) + newPos.setX(targetGeometry.left()); + + if (newPos.y() + size.height() > targetGeometry.bottom()) + newPos.setY(targetGeometry.bottom() - size.height()); + if (newPos.y() < targetGeometry.top()) + newPos.setY(targetGeometry.top()); + + surface->setPosition(newPos); + } + } +} + +void RootSurfaceContainer::setupSeatManagement() +{ + auto *server = WaylandServer::instance(); + if (!server || !server->seatManager()) { + qCWarning(lcTlCore) << "WaylandServer or seatManager not available for seat management setup"; + return; + } + + auto *seatManager = server->seatManager(); + const auto &seats = seatManager->seats(); + + if (seats.isEmpty()) { + qCWarning(lcTlCore) << "No seats available for seat management setup"; + return; + } + + for (auto *seat : std::as_const(seats)) { + onSeatAdded(seat); + } + + // Connect to seat lifecycle signals + connect(seatManager, &SeatManager::seatAdded, this, &RootSurfaceContainer::onSeatAdded); + connect(seatManager, &SeatManager::seatRemoved, this, &RootSurfaceContainer::onSeatRemoved); +} + +void RootSurfaceContainer::setupSurfaceRequestHandlers(SurfaceWrapper *surface) +{ + connect( + surface, + &SurfaceWrapper::moveRequested, + this, + [this, surface]() { + WSeat *requestingSeat = determineSeatForRequest(surface); + if (!requestingSeat) { + qCWarning(lcTlCore) << "No seat available for move request"; + return; + } + + if (!beginMoveResizeForSeat(requestingSeat, surface, Qt::Edges{}, /*overrideCursor=*/false)) + return; + auto *server = WaylandServer::instance(); + if (server) { + server->activateSurface(surface); + } + }, + Qt::DirectConnection); + + connect( + surface, + &SurfaceWrapper::resizeRequested, + this, + [this, surface](Qt::Edges edges, bool overrideCursor) { + WSeat *requestingSeat = determineSeatForRequest(surface); + if (!requestingSeat) { + qCWarning(lcTlCore) << "No seat available for resize request"; + return; + } + + if (!beginMoveResizeForSeat(requestingSeat, surface, edges, overrideCursor)) + return; + if (auto *sh = surface->shellSurface()) { + sh->setResizeing(true); + } + auto *server = WaylandServer::instance(); + if (server) { + server->activateSurface(surface); + } + }, + Qt::DirectConnection); +} + +WSeat *RootSurfaceContainer::determineSeatForRequest(SurfaceWrapper *surface) +{ + auto *server = WaylandServer::instance(); + if (!server || !server->seatManager()) { + return nullptr; + } + + if (auto *currentEventSeat = server->currentEventSeat()) { + return currentEventSeat; + } + + WSeat *lastInteractingSeat = server->getLastInteractingSeat(surface); + if (lastInteractingSeat) { + return lastInteractingSeat; + } + + const auto &seats = server->seatManager()->seats(); + if (!seats.isEmpty()) { + return seats.first(); + } + + return nullptr; +} + +void RootSurfaceContainer::onSeatAdded(WSeat *seat) +{ + if (m_seatContainers.contains(seat)) + return; + + auto *container = new SeatSurfaceManager(seat, this); + m_seatContainers[seat] = container; + + connect(container, &SeatSurfaceManager::moveResizeChanged, this, &RootSurfaceContainer::moveResizeFinised); + connect(container, &SeatSurfaceManager::activatedSurfaceChanged, this, [seat]() { + auto *server = WaylandServer::instance(); + if (server && server->seat() == seat) { + Q_EMIT server->activatedSurfaceChanged(); + } + }); +} + +void RootSurfaceContainer::onSeatRemoved(WSeat *seat) +{ + auto *container = m_seatContainers.take(seat); + if (container) { + qCDebug(lcTlCore) << "Removing SeatContainer for seat:" << seat; + delete container; + } +} + +SeatSurfaceManager *RootSurfaceContainer::getSeatContainer(WSeat *seat) const +{ + return m_seatContainers.value(seat, nullptr); +} + +WSeat *RootSurfaceContainer::getDefaultSeat() const +{ + auto *server = WaylandServer::instance(); + if (!server || !server->seatManager()) { + qCWarning(lcTlCore) << "WaylandServer or seatManager not available"; + return nullptr; + } + + auto *seatManager = server->seatManager(); + + // Prefer the explicitly designated fallback/primary seat + if (WSeat *fallback = seatManager->fallbackSeat()) { + return fallback; + } + + // Fallback: use first from list (QMap order, not predictable — warn) + const auto &seats = seatManager->seats(); + if (seats.isEmpty()) { + qCCritical(lcTlCore) << "No seats available - this should not happen in Wayland!"; + return nullptr; + } + qCWarning(lcTlCore) << "fallbackSeat() is null, using first seat from seats() as default"; + return seats.first(); +} + +SeatSurfaceManager *RootSurfaceContainer::getSeatContainerOrDefault(WSeat *seat) const +{ + if (!seat) { + seat = getDefaultSeat(); + if (!seat) { + qCCritical(lcTlCore) << "Cannot get default seat"; + return nullptr; + } + } + + auto *container = m_seatContainers.value(seat, nullptr); + if (!container) { + qCWarning(lcTlCore) << "No container for seat:" << seat; + } + + return container; +} + +void RootSurfaceContainer::dismissAllPopups() +{ + for (auto *container : std::as_const(m_seatContainers)) { + container->dismissPopups(); + } +} + +void RootSurfaceContainer::givePopupFocus(SurfaceWrapper *popupWrapper) +{ + if (!popupWrapper) + return; + + // Route to the correct seat based on wlr_xdg_popup->seat. + auto *popupSurface = qobject_cast(popupWrapper->shellSurface()); + if (!popupSurface) + return; + + auto *wlrPopup = popupSurface->handle(); + if (!wlrPopup || !wlrPopup->seat) + return; + + for (auto it = m_seatContainers.constBegin(); it != m_seatContainers.constEnd(); ++it) { + if (it.key()->handle() == wlrPopup->seat) { + it.value()->givePopupFocus(popupWrapper); + return; + } + } +} + +bool RootSurfaceContainer::beginMoveResizeForSeat(WSeat *seat, SurfaceWrapper *surface, Qt::Edges edges, + bool overrideCursor) +{ + if (!surface) + return false; + + auto *container = getSeatContainerOrDefault(seat); + if (!container) + return false; + + // Geometry changes can only use one seat's drag state for a given surface. + for (auto *other : std::as_const(m_seatContainers)) { + if (other != container && other->moveResizeSurface() == surface) + return false; + } + + if (container->moveResizeState().surface && + container->moveResizeState().surface != surface) { + container->endMoveResize(); + } + + const auto state = surface->surfaceState(); + const bool wasTiled = edges == Qt::Edges() + && (state == SurfaceWrapper::State::Tiling || state == SurfaceWrapper::State::Maximized); + const QRectF tiledGeo = wasTiled ? surface->geometry() : QRectF(); + + container->beginMoveResize(surface, edges, overrideCursor); + if (container->moveResizeSurface() != surface) + return false; + + WSeat *actualSeat = seat ? seat : getDefaultSeat(); + const bool hasCursor = actualSeat && actualSeat->cursor(); + const QPointF cursor = hasCursor ? actualSeat->cursor()->position() : QPointF(); + + // De-tile: restore saved size, reposition so the cursor stays at the same + // relative grab ratio within the window + if (wasTiled && !tiledGeo.isEmpty() && hasCursor) { + const QSizeF restoredSize = surface->normalGeometry().isValid() + ? surface->normalGeometry().size() + : tiledGeo.size(); + const qreal fx = + tiledGeo.width() > 0 ? (cursor.x() - tiledGeo.left()) / tiledGeo.width() : 0; + const qreal fy = + tiledGeo.height() > 0 ? (cursor.y() - tiledGeo.top()) / tiledGeo.height() : 0; + QPointF newPos(cursor.x() - fx * restoredSize.width(), + cursor.y() - fy * restoredSize.height()); + newPos = surface->alignToPixelGrid(newPos); + surface->setPosition(newPos); + container->moveResizeState().startGeometry = QRectF(newPos, restoredSize); + } + + if (actualSeat && actualSeat->cursor()) + container->moveResizeState().initialPosition = cursor; + + return true; +} + +void RootSurfaceContainer::doMoveResizeForSeat(WSeat *seat, const QPointF &delta) +{ + auto *container = getSeatContainerOrDefault(seat); + if (container) { + container->doMoveResize(delta); + } +} + +QQuickItem *RootSurfaceContainer::ensureEdgeTilePreview() +{ + if (m_edgeTilePreview) + return m_edgeTilePreview; + + auto *engine = WaylandServer::instance()->qmlEngine(); + if (!engine) + return nullptr; + + m_edgeTilePreview = engine->createEdgeTilePreview(this); + if (m_edgeTilePreview) + m_edgeTilePreview->setZ(OverlayZOrder); + return m_edgeTilePreview; +} + +void RootSurfaceContainer::updateEdgeTilePreview(SurfaceWrapper::TileMode mode, Output *out, WSeat *seat) +{ + auto *preview = ensureEdgeTilePreview(); + if (!preview) + return; + + if (mode == SurfaceWrapper::TileMode::None || !out) { + preview->setVisible(false); + return; + } + + const QRectF geo = out->tileGeometry(mode); + if (!geo.isValid()) { + preview->setVisible(false); + return; + } + + // Use the dragged surface's current geometry as the animation starting + // point, so the preview grows from the window (mirrors KWin's outline). + QRectF sourceGeo; + if (auto *container = getSeatContainerOrDefault(seat)) { + if (SurfaceWrapper *surface = container->moveResizeSurface()) + sourceGeo = surface->geometry(); + } + + preview->setProperty("sourceGeometry", QVariant::fromValue(sourceGeo)); + preview->setProperty("targetGeometry", QVariant::fromValue(geo)); + preview->setVisible(true); +} + +void RootSurfaceContainer::detectEdgeTilingForSeat(WSeat *seat) +{ + auto *container = getSeatContainerOrDefault(seat); + if (!container) + return; + + auto *cfg = WaylandServer::instance()->config(); + const qreal sideTrigger = cfg ? qreal(cfg->edgeSideTriggerDistance()) : 20.0; + const qreal topTrigger = cfg ? qreal(cfg->edgeTopTriggerDistance()) : 5.0; + const qreal quadRatio = cfg ? qBound(0.0, qreal(cfg->edgeQuadrantZoneRatio()), 0.5) : 0.25; + auto &mrState = container->moveResizeState(); + SurfaceWrapper::TileMode mode = SurfaceWrapper::TileMode::None; + Output *out = nullptr; + bool innerBorder = false; + + if (mrState.surface && mrState.edges == Qt::Edges()) { + WSeat *actualSeat = seat ? seat : getDefaultSeat(); + WCursor *cursor = actualSeat ? actualSeat->cursor() : nullptr; + const QPointF pos = cursor ? cursor->position() : QPointF(); + out = outputAt(pos); + if (out) { + const QRectF area = out->validGeometry(); + const qreal quadTop = area.top() + area.height() * quadRatio; + const qreal quadBottom = area.bottom() - area.height() * quadRatio; + if (pos.x() <= area.left() + sideTrigger) { + // Left edge: the top/bottom quadrant zones tile to the corner. + if (pos.y() <= quadTop) + mode = SurfaceWrapper::TileMode::TopLeft; + else if (pos.y() >= quadBottom) + mode = SurfaceWrapper::TileMode::BottomLeft; + else + mode = SurfaceWrapper::TileMode::Left; + } else if (pos.x() >= area.right() - sideTrigger) { + // Right edge: the top/bottom quadrant zones tile to the corner. + if (pos.y() <= quadTop) + mode = SurfaceWrapper::TileMode::TopRight; + else if (pos.y() >= quadBottom) + mode = SurfaceWrapper::TileMode::BottomRight; + else + mode = SurfaceWrapper::TileMode::Right; + } else if (pos.y() <= area.top() + topTrigger) { + // Top edge: maximize only; quadrant zones are exclusive to + // the left/right edges. + mode = SurfaceWrapper::TileMode::Maximize; + } + + if (mode != SurfaceWrapper::TileMode::None + && !mrState.surface->supportsTileMode(mode)) { + mode = SurfaceWrapper::TileMode::None; + } + + // Multi-screen inner-edge detection: + // Sample 1px outside the edge; if another output covers that + // point, this is an inner edge + if (mode != SurfaceWrapper::TileMode::None) { + QPointF samplePt; + switch (mode) { + case SurfaceWrapper::TileMode::Maximize: + samplePt = QPointF(pos.x(), area.top() - 1.0); + break; + case SurfaceWrapper::TileMode::Left: + case SurfaceWrapper::TileMode::TopLeft: + case SurfaceWrapper::TileMode::BottomLeft: + samplePt = QPointF(area.left() - 1.0, pos.y()); + break; + case SurfaceWrapper::TileMode::Right: + case SurfaceWrapper::TileMode::TopRight: + case SurfaceWrapper::TileMode::BottomRight: + samplePt = QPointF(area.right(), pos.y()); + break; + case SurfaceWrapper::TileMode::None: + break; + } + for (Output *o : outputs()) { + if (o == out) + continue; + if (o->geometry().contains(samplePt)) { + innerBorder = true; + break; + } + } + } + } + } + + // Re-evaluate when the edge state changes, or when the cursor crosses to + // a different output while the preview is active + if (mrState.detectedTileMode != mode || mrState.edgeTileInnerBorder != innerBorder + || out != mrState.detectedTileOutput) { + mrState.detectedTileMode = mode; + mrState.edgeTileInnerBorder = innerBorder; + mrState.detectedTileOutput = out; + + if (mode == SurfaceWrapper::TileMode::None) { + container->stopEdgeTileDelay(); + mrState.edgeTilePreviewActive = false; + updateEdgeTilePreview(SurfaceWrapper::TileMode::None, nullptr); + } else if (innerBorder) { + container->stopEdgeTileDelay(); + mrState.edgeTilePreviewActive = false; + updateEdgeTilePreview(SurfaceWrapper::TileMode::None, nullptr); + container->startEdgeTileDelay(); + } else { + container->stopEdgeTileDelay(); + mrState.edgeTilePreviewActive = true; + updateEdgeTilePreview(mode, out, seat); + } + } +} + +void RootSurfaceContainer::endMoveResizeForSeat(WSeat *seat) +{ + auto *container = getSeatContainerOrDefault(seat); + if (container) { + container->endMoveResize(/*alignLayerPosition=*/true); + } + updateEdgeTilePreview(SurfaceWrapper::TileMode::None, nullptr); +} + +void RootSurfaceContainer::cancelMoveResizeForSeat(WSeat *seat) +{ + auto *container = getSeatContainerOrDefault(seat); + if (container) { + container->cancelMoveResize(); + } + updateEdgeTilePreview(SurfaceWrapper::TileMode::None, nullptr); +} + +SurfaceWrapper *RootSurfaceContainer::getMoveResizeSurfaceForSeat(WSeat *seat) const +{ + auto *container = getSeatContainerOrDefault(seat); + return container ? container->moveResizeSurface() : nullptr; +} + +bool RootSurfaceContainer::isInMoveResizeForSeat(WSeat *seat) const +{ + auto *container = getSeatContainer(seat); + return container && container->moveResizeState().surface; +} + +void RootSurfaceContainer::setActivatedSurfaceForSeat(WSeat *seat, SurfaceWrapper *surface, + Qt::FocusReason reason) +{ + auto *container = getSeatContainer(seat); + if (container) { + container->setActivatedSurface(surface, reason); + } +} + +SurfaceWrapper *RootSurfaceContainer::getActivatedSurfaceForSeat(WSeat *seat) const +{ + auto *container = getSeatContainer(seat); + if (container) { + return container->activatedSurface(); + } + return nullptr; +} diff --git a/src/core/rootsurfacecontainer.h b/src/core/rootsurfacecontainer.h new file mode 100644 index 0000000000..15ed435578 --- /dev/null +++ b/src/core/rootsurfacecontainer.h @@ -0,0 +1,174 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include +#include "surface/surfacecontainer.h" +#include "surface/seatsurfacemanager.h" + +#include + +Q_MOC_INCLUDE() + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WSurface; +class WSurfaceItem; +class WToplevelSurface; +class WOutputLayout; +class WCursor; +class WSeat; +class WInputDevice; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class Output; + +class OutputListModel : public ObjectListModel +{ + Q_OBJECT + QML_ANONYMOUS + +public: + explicit OutputListModel(QObject *parent = nullptr); +}; + +class RootSurfaceContainer : public SurfaceContainer +{ + Q_OBJECT + Q_PROPERTY(WAYLIB_SERVER_NAMESPACE::WOutputLayout *outputLayout READ outputLayout CONSTANT FINAL) + Q_PROPERTY(WAYLIB_SERVER_NAMESPACE::WCursor *cursor READ cursor CONSTANT FINAL) + Q_PROPERTY(Output *primaryOutput READ primaryOutput WRITE setPrimaryOutput NOTIFY primaryOutputChanged FINAL) + Q_PROPERTY(OutputListModel* outputModel READ outputModel CONSTANT FINAL) + +public: + explicit RootSurfaceContainer(QQuickItem *parent); + ~RootSurfaceContainer() override; + + enum ContainerZOrder + { + BackgroundZOrder = -2, + BottomZOrder = -1, + NormalZOrder = 0, + MultitaskviewZOrder = 1, + TopZOrder = 2, + OverlayZOrder = 3, + TaskBarZOrder = 4, + MenuBarZOrder = 4, + PopupZOrder = 5, + CaptureLayerZOrder = 6, + LockScreenZOrder = 7, + GlobalOverlayZOrder = 100, + SnapMaskLayerZOrder = 180, + PrivilegedOverlayZOrder = 200, // Privileged overlay, above lock screen & lock screen popups + }; + + void init(WServer *server); + + SurfaceWrapper *getSurface(WSurface *surface) const; + SurfaceWrapper *getSurface(WToplevelSurface *surface) const; + void destroyForSurface(SurfaceWrapper *wrapper); + + SeatSurfaceManager *getSeatContainer(WSeat *seat) const; + WSeat *getDefaultSeat() const; + SeatSurfaceManager *getSeatContainerOrDefault(WSeat *seat = nullptr) const; + + bool beginMoveResizeForSeat(WSeat *seat, SurfaceWrapper *surface, Qt::Edges edges, + bool overrideCursor); + void doMoveResizeForSeat(WSeat *seat, const QPointF &delta); + void detectEdgeTilingForSeat(WSeat *seat); + void endMoveResizeForSeat(WSeat *seat); + void cancelMoveResizeForSeat(WSeat *seat); + SurfaceWrapper *getMoveResizeSurfaceForSeat(WSeat *seat) const; + bool isInMoveResizeForSeat(WSeat *seat) const; + void setActivatedSurfaceForSeat(WSeat *seat, SurfaceWrapper *surface, + Qt::FocusReason reason); + SurfaceWrapper *getActivatedSurfaceForSeat(WSeat *seat) const; + void setupSeatManagement(); + void dismissAllPopups(); + void givePopupFocus(SurfaceWrapper *popupWrapper); + + WOutputLayout *outputLayout() const; + WCursor *cursor() const; + + Output *cursorOutput() const; + Output *outputAt(const QPointF &pos) const; + void updateEdgeTilePreview(SurfaceWrapper::TileMode mode, Output *out, WSeat *seat = nullptr); + Output *primaryOutput() const; + void setPrimaryOutput(Output *newPrimaryOutput, bool updateDconfig = false); + // Moves the primary output off `output` when it is the current primary. + // Must run before the per-output surface containers of `output` are torn down. + void movePrimaryOutputAwayFrom(const Output *output); + const QList &outputs() const; + + void addOutput(Output *output) override; + void removeOutput(Output *output) override; + + // TODO(Lyn): These global move/resize interfaces should eventually be moved into the Seat + // object (or SeatSurfaceManager), since move/resize state is inherently per-seat. + void beginMoveResize(SurfaceWrapper *surface, Qt::Edges edges); + void doMoveResize(const QPointF &incrementPos); + void endMoveResize(); + SurfaceWrapper *moveResizeSurface() const; + bool isInMoveResize() const; + + OutputListModel *outputModel() const; + void moveSurfacesToOutput(const QList &surfaces, + Output *targetOutput, + Output *sourceOutput = nullptr); + void ensureSurfaceNormalPositionValid(SurfaceWrapper *surface); + +public Q_SLOTS: + void startMove(SurfaceWrapper *surface); + void startResize(SurfaceWrapper *surface, Qt::Edges edges); + void cancelMoveResize(SurfaceWrapper *surface); + +Q_SIGNALS: + void primaryOutputChanged(); + void cursorOutputChanged(Output *output); + void moveResizeFinised(SurfaceWrapper *surface); + +private: + void addSurface(SurfaceWrapper *surface) override; + void removeSurface(SurfaceWrapper *surface) override; + + void addBySubContainer(SurfaceContainer *, SurfaceWrapper *surface) override; + void removeBySubContainer(SurfaceContainer *, SurfaceWrapper *surface) override; + + bool filterSurfaceGeometryChanged(SurfaceWrapper *surface, + QRectF &newGeometry, + const QRectF &oldGeometry) override; + bool filterSurfaceStateChange(SurfaceWrapper *surface, + [[maybe_unused]] SurfaceWrapper::State newState, + [[maybe_unused]] SurfaceWrapper::State oldState) override; + + void ensureCursorVisible(); + void updateCursorOutput(); + // `reason` names the trigger and is reported by treeland-debug: GeometryChanged + // and AddOutput are the shapes that empty the list, EnabledChanged is the one + // that refills it. + void updateSurfaceOutputs(SurfaceWrapper *surface, SurfaceWrapper::OutputsUpdateReason reason); + // Recomputes the outputs of every window after an output became enabled: a + // surface that left all outputs would otherwise never be re-entered. + void onOutputEnabledChanged(); + QQuickItem *ensureEdgeTilePreview(); + void onSeatAdded(WSeat *seat); + void onSeatRemoved(WSeat *seat); + + void setupSurfaceRequestHandlers(SurfaceWrapper *surface); + WSeat *determineSeatForRequest(SurfaceWrapper *surface); + + WOutputLayout *m_outputLayout = nullptr; + std::unique_ptr m_outputLayoutListenerOwner; + OutputListModel *m_outputModel = nullptr; + QPointer m_primaryOutput; + QPointer m_cursorOutput; + WCursor *m_cursor = nullptr; + WSurfaceItem *m_dragSurfaceItem = nullptr; + QPointer m_edgeTilePreview; + + // Per-seat state management + QMap m_seatContainers; +}; + +Q_DECLARE_OPAQUE_POINTER(WAYLIB_SERVER_NAMESPACE::WOutputLayout *) diff --git a/src/core/shellhandler.cpp b/src/core/shellhandler.cpp new file mode 100644 index 0000000000..5268d082e7 --- /dev/null +++ b/src/core/shellhandler.cpp @@ -0,0 +1,1350 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "shellhandler.h" +#include "session/sessionprelaunch.h" +#include "session/sessionmanager.h" + +#include "common/treelandlogging.h" +#include "core/imcandidatepanelmanager.h" +#include "core/qmlengine.h" +#include "core/windowconfigstore.h" +#include "layersurfacecontainer.h" +#include "modules/snap-target/snaphandler.h" +#include "modules/dde-shell/ddeshellmanagerinterfacev1.h" +#include "modules/dde-shell/ddeshellmanagerinterfacev2.h" +#include "modules/foreign-toplevel/foreigntoplevelmanagerv3.h" +#include "modules/layer-shell-extension/layershellextensionmanagerinterfacev1.h" +#include "modules/wine-window-management/winewindowmanagement.h" +#include "modules/wine-window-state/winewindowstate.h" +#include "output/output.h" +#include "rootsurfacecontainer.h" +#include "core/waylandserver.h" +#include "showdesktop/showdesktop.h" +#include "seat/seatmanager.h" +#include "session/session.h" +#include "session/sessionseatmanager.h" +#include "session/sessionoutputmanager.h" +#include "session/sessionprotocols.h" +#include "surface/seatsurfacemanager.h" +#include "surface/surfacewrapper.h" +#include "treelandconfig.hpp" +#include "treelanduserconfig.hpp" +#include "wallpapershellinterfacev1.h" +#include "workspace/workspace.h" +#include "workspace/workspacemodel.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef DISABLE_XWAYLAND +#include +#include +#include +#endif + +#include +#include +#include +#include + +#include +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +const QLatin1String PRIVILEGED_OVERLAY_TAG("org.deepin.treeland.privileged-overlay"); +const QLatin1String SNAP_MASK_TAG("org.deepin.treeland.snap-mask"); + +using SurfaceRole = SurfaceWrapper::SurfaceRole; +using ProtocolRole = DDEShellSurfaceV2::Role; + +static_assert( + static_cast(SurfaceRole::Normal) == ProtocolRole::NORMAL && + static_cast(SurfaceRole::Overlay) == ProtocolRole::OVERLAY && + static_cast(SurfaceRole::AlwaysOnTop) == ProtocolRole::ALWAYS_ON_TOP, + "DDE Shell v2 role values must match SurfaceWrapper::SurfaceRole"); + +ShellHandler::ShellHandler(RootSurfaceContainer *rootContainer, [[maybe_unused]] WServer *server) + : m_rootSurfaceContainer(rootContainer) + , m_backgroundContainer(new LayerSurfaceContainer(rootContainer)) + , m_bottomContainer(new LayerSurfaceContainer(rootContainer)) + , m_workspace(new Workspace(rootContainer, WaylandServer::instance()->config())) + , m_topContainer(new LayerSurfaceContainer(rootContainer)) + , m_overlayContainer(new LayerSurfaceContainer(rootContainer)) + , m_popupContainer(new SurfaceContainer(rootContainer)) + , m_privilegedOverlayContainer(new SurfaceContainer(rootContainer)) + , m_snapMaskContainer(new SurfaceContainer(rootContainer)) + , m_windowConfigStore(new WindowConfigStore(this)) +{ + qmlRegisterUncreatableType( + "Treeland.Protocols", 1, 0, "ForeignToplevelManagerInterfaceV3", + "Owned by Session"); + qRegisterMetaType(); + + m_backgroundContainer->setZ(RootSurfaceContainer::BackgroundZOrder); + m_backgroundContainer->setObjectName(QStringLiteral("BackgroundContainer")); + m_bottomContainer->setZ(RootSurfaceContainer::BottomZOrder); + m_bottomContainer->setObjectName(QStringLiteral("BottomContainer")); + m_workspace->setZ(RootSurfaceContainer::NormalZOrder); + m_workspace->setObjectName(QStringLiteral("WorkspaceContainer")); + m_topContainer->setZ(RootSurfaceContainer::TopZOrder); + m_topContainer->setObjectName(QStringLiteral("TopContainer")); + m_overlayContainer->setZ(RootSurfaceContainer::OverlayZOrder); + m_overlayContainer->setObjectName(QStringLiteral("OverlayContainer")); + m_popupContainer->setZ(RootSurfaceContainer::PopupZOrder); + m_popupContainer->setObjectName(QStringLiteral("PopupContainer")); + m_privilegedOverlayContainer->setZ(RootSurfaceContainer::PrivilegedOverlayZOrder); + m_privilegedOverlayContainer->setObjectName(QStringLiteral("PrivilegedOverlayContainer")); + m_snapMaskContainer->setZ(RootSurfaceContainer::SnapMaskLayerZOrder); + m_snapMaskContainer->setObjectName(QStringLiteral("SnapMaskContainer")); +#ifndef DISABLE_XWAYLAND + connect(m_rootSurfaceContainer->outputModel(), + &QAbstractItemModel::rowsInserted, + this, + [this] { + for (auto *output : m_rootSurfaceContainer->outputs()) { + watchXWaylandDesktopOutput(output); + } + updateXWaylandDesktopProperties(); + }); + connect(m_rootSurfaceContainer->outputModel(), + &QAbstractItemModel::rowsRemoved, + this, + &ShellHandler::updateXWaylandDesktopProperties); + connect(m_workspace, &Workspace::currentIndexChanged, + this, &ShellHandler::updateXWaylandDesktopProperties); + connect(WaylandServer::instance(), &WaylandServer::showDesktopStateChanged, + this, &ShellHandler::updateXWaylandDesktopProperties); + connect(m_workspace, &Workspace::countChanged, this, &ShellHandler::onWorkspaceCountChanged); + watchXWaylandWorkspaceNames(); +#endif + connect(m_workspace, &Workspace::workspaceAdded, this, &ShellHandler::workspaceAdded); +} + +#ifndef DISABLE_XWAYLAND +void ShellHandler::watchXWaylandDesktopOutput(Output *output) +{ + connect(output, + &Output::exclusiveZoneChanged, + this, + &ShellHandler::updateXWaylandDesktopProperties, + Qt::UniqueConnection); + connect(output->outputItem(), + &WOutputItem::geometryChanged, + this, + &ShellHandler::updateXWaylandDesktopProperties, + Qt::UniqueConnection); + connect(output->output(), + &WOutput::enabledChanged, + this, + &ShellHandler::updateXWaylandDesktopProperties, + Qt::UniqueConnection); +} + +void ShellHandler::watchXWaylandWorkspaceNames() +{ + for (int i = 0; i < m_workspace->count(); ++i) { + connect(m_workspace->modelAt(i), + &WorkspaceModel::nameChanged, + this, + &ShellHandler::updateXWaylandDesktopProperties, + Qt::UniqueConnection); + } +} + +void ShellHandler::updateXWaylandDesktopProperties() +{ + auto *outputManager = WaylandServer::instance()->xwaylandOutputManager(); + connect(outputManager, + &WXdgOutputManager::scaleOverrideChanged, + this, + &ShellHandler::updateXWaylandDesktopProperties, + Qt::UniqueConnection); + connect(outputManager->layout(), + &WOutputLayout::outputsChanged, + this, + &ShellHandler::updateXWaylandDesktopProperties, + Qt::UniqueConnection); + + for (auto *xwayland : std::as_const(m_xwaylands)) { + auto session = WaylandServer::instance()->sessionManager()->sessionForXWayland(xwayland); + if (!session) + continue; + auto *workspace = session->workspace(); + const qreal scale = session->outputManager()->effectiveScale(); + QRect geometry; + QRect workarea; + for (auto *output : m_rootSurfaceContainer->outputs()) { + auto *state = session->outputManager()->outputState(output); + const auto logical = state->geometry(); + const auto valid = state->validGeometry(); + geometry = geometry.united(QRect(qFloor(logical.x() * scale), + qFloor(logical.y() * scale), + qCeil(logical.width() * scale), + qCeil(logical.height() * scale))); + workarea = workarea.united(QRect(qFloor(valid.x() * scale), + qFloor(valid.y() * scale), + qCeil(valid.width() * scale), + qCeil(valid.height() * scale))); + } + if (geometry.isEmpty() || workarea.isEmpty()) + continue; + QStringList sessionNames; + for (int i = 0; i < workspace->count(); ++i) + sessionNames.append(workspace->modelAt(i)->name()); + xwayland->setDesktopProperties(workspace->count(), + geometry.size(), + workspace->currentIndex(), + sessionNames, + QVector(workspace->count(), QPoint(0, 0)), + QVector(workspace->count(), workarea), + session->isActive() + && WaylandServer::instance()->showDesktopState() + == ShowDesktop::State::Show); + } +} +#endif + +void ShellHandler::updateWrapperContainer(SurfaceWrapper *wrapper, WSurface *parentSurface) +{ + if (wrapper->parentSurface()) + wrapper->parentSurface()->removeSubSurface(wrapper); + + auto oldContainer = wrapper->container(); + if (parentSurface) { + auto *parent = m_rootSurfaceContainer->getSurface(parentSurface); + if (parent && parent->session() != wrapper->session()) + return; + } +#ifndef DISABLE_XWAYLAND + if (auto *x11Surface = qobject_cast(wrapper->shellSurface()); + x11Surface && x11Surface->isPopupLike()) { + auto *parentWrapper = parentSurface + ? m_rootSurfaceContainer->getSurface(parentSurface) : nullptr; + // Unlike xdg popups, an X11 popup's transient parent is always a + // toplevel in a workspace, so the popup container already stacks above + // it and there is no higher container to follow. + if (parentWrapper) { + parentWrapper->addSubSurface(wrapper); + wrapper->setOwnsOutput(parentWrapper->ownsOutput()); + } + if (oldContainer != m_popupContainer) { + if (oldContainer) + oldContainer->removeSurface(wrapper); + m_popupContainer->addSurface(wrapper); + } + // Plain containers do not initialize surfaces like Workspace does. + wrapper->setHasInitializeContainer(true); + return; + } +#endif + if (parentSurface) { + auto parentWrapper = m_rootSurfaceContainer->getSurface(parentSurface); + if (!parentWrapper) + return; + + auto parentContainer = qobject_cast(parentWrapper->container()); + parentWrapper->addSubSurface(wrapper); + if (oldContainer != parentContainer) { + if (oldContainer) + oldContainer->removeSurface(wrapper); + if (auto ws = qobject_cast(parentContainer)) + ws->addSurface(wrapper, parentWrapper->workspaceId()); + else + parentContainer->addSurface(wrapper); + } + } else { + if (oldContainer) { + if (qobject_cast(oldContainer) == nullptr) { + oldContainer->removeSurface(wrapper); + workspaceForSurface(wrapper)->addSurface(wrapper); + } + // else do nothing, already in workspace + } else { + workspaceForSurface(wrapper)->addSurface(wrapper); + } + } +} + +SessionPrelaunch *ShellHandler::prelaunchForSurface(WToplevelSurface *surface) const +{ + const auto owner = WaylandServer::instance()->sessionManager()->sessionForClient(surface->waylandClient()); + return owner ? owner->prelaunch() : nullptr; +} + +void ShellHandler::initializePrelaunchSurface(SurfaceWrapper *wrapper) +{ + setupSurfaceActiveWatcher(wrapper); + registerSurfaceToForeignToplevel(wrapper); +} + +void ShellHandler::setWorkspace(Workspace *workspace) +{ + Q_ASSERT(workspace); + if (workspace == m_workspace) + return; + workspace->setOpacity(m_workspace->opacity()); + workspace->setScale(m_workspace->scale()); + m_workspace->setEnabled(false); + m_workspace->resetView(); + m_workspace->setVisible(false); + disconnect(m_workspace, nullptr, this, nullptr); + m_workspace = workspace; +#ifndef DISABLE_XWAYLAND + connect(m_workspace, &Workspace::currentIndexChanged, + this, &ShellHandler::updateXWaylandDesktopProperties); +#endif + connect(m_workspace, &Workspace::countChanged, this, &ShellHandler::onWorkspaceCountChanged); + connect(m_workspace, &Workspace::workspaceAdded, this, &ShellHandler::workspaceAdded); + onWorkspaceCountChanged(); + Q_EMIT workspaceChanged(); +} + +void ShellHandler::onWorkspaceCountChanged() +{ +#ifndef DISABLE_XWAYLAND + watchXWaylandWorkspaceNames(); + updateXWaylandDesktopProperties(); +#endif +} + +Workspace *ShellHandler::workspaceForSurface(SurfaceWrapper *wrapper) const +{ + if (auto *session = wrapper->session()) + return session->workspace(); + return m_workspace; +} + +Workspace *ShellHandler::workspace() const +{ + return m_workspace; +} + +SurfaceContainer *ShellHandler::popupContainer() const +{ + return m_popupContainer; +} + +SurfaceContainer *ShellHandler::snapMaskContainer() const +{ + return m_snapMaskContainer; +} + +RootSurfaceContainer *ShellHandler::rootSurfaceContainer() const +{ + return m_rootSurfaceContainer; +} + +ForeignToplevelManagerInterfaceV3 *ShellHandler::foreignToplevel() const +{ + auto *session = WaylandServer::instance()->activeSession(); + return session ? session->windowManagement() : nullptr; +} + +SurfaceContainer *ShellHandler::privilegedOverlayContainer() const +{ + return m_privilegedOverlayContainer; +} + +void ShellHandler::createComponent(QmlEngine *engine, QQuickItem *parentItem) +{ + m_windowMenu = engine->createWindowMenu(WaylandServer::instance()); + QObject::connect(m_windowMenu, SIGNAL(closed()), this, SLOT(onWindowMenuClosed())); + Q_UNUSED(parentItem) + +} + +void ShellHandler::init(WServer *server, WSeat *seat) +{ + Q_ASSERT_X(server, Q_FUNC_INFO, "server must not be null"); + Q_ASSERT_X(seat, Q_FUNC_INFO, "seat must not be null"); + Q_ASSERT_X(!m_wallpaperShell, Q_FUNC_INFO, "Only init once!"); + Q_ASSERT_X(!m_layerShellExtensionManagerInterfaceV1, Q_FUNC_INFO, "Only init once!"); + + m_layerShellExtensionManagerInterfaceV1 = + server->attach(); + + m_snapTarget = server->attach(); + m_snapTarget->setOutputRenderWindow( + qobject_cast(m_rootSurfaceContainer->window())); + + m_wallpaperShell = server->attach(m_wallpaperShell); + if (WaylandServer::instance()->isDDMDisplay()) { + m_wallpaperShell->setFilter([](WClient *client) { + return WaylandServer::instance()->sessionManager()->isDDEUserClient(client); + }); + } + + auto *overlay = QQuickOverlay::overlay(m_rootSurfaceContainer->window()); + overlay->setZ(RootSurfaceContainer::GlobalOverlayZOrder); + overlay->setParentItem(m_rootSurfaceContainer); +} + +#ifndef DISABLE_XWAYLAND +WXWayland *ShellHandler::createXWayland(WServer *server, + WSeat *seat, + wlr_compositor *compositor, + [[maybe_unused]] bool lazy) +{ + auto *xwayland = server->attach(compositor, false); + m_xwaylands.append(xwayland); + xwayland->setSeat(seat); + connect(xwayland, &WXWayland::surfaceAdded, this, &ShellHandler::onXWaylandSurfaceAdded); + // aboutToDissociate never fires when the XWayland instance is torn down. + connect(xwayland, &WXWayland::surfaceRemoved, this, &ShellHandler::onXWaylandSurfaceRemoved); + connect(xwayland, &WXWayland::ready, xwayland, [this, xwayland] { + auto atomPid = xwayland->atom("_NET_WM_PID"); + xwayland->setAtomSupported(atomPid, true); + auto atomNoTitlebar = xwayland->atom("_DEEPIN_NO_TITLEBAR"); + xwayland->setAtomSupported(atomNoTitlebar, true); + + for (auto *output : m_rootSurfaceContainer->outputs()) { + watchXWaylandDesktopOutput(output); + } + updateXWaylandDesktopProperties(); + + auto session = WaylandServer::instance()->sessionManager()->sessionForXWayland(xwayland); + if (auto *panels = candidatePanels(session.get())) + panels->setupXWayland(xwayland); + }); + return xwayland; +} + +void ShellHandler::removeXWayland(WXWayland *xwayland) +{ + m_xwaylands.removeOne(xwayland); + // Ensure xwayland is removed from interfaceList + if (auto server = WServer::from(xwayland)) + server->detach(xwayland); + delete xwayland; +} +#endif + +void ShellHandler::onXdgToplevelSurfaceAdded(WXdgToplevelSurface *surface) +{ + // If there are prelaunch wrappers or closed splash appIds and the resolver is available + // -> attempt async resolve; remaining logic continues in the callback on success + auto *prelaunch = prelaunchForSurface(surface); + if (prelaunch && prelaunch->needsResolution()) { + int pidfd = surface->pidFD(); + if (pidfd >= 0) { + // Register pending before starting async resolve (unified list) + m_pendingAppIdResolveToplevels.append(surface); + + bool started = prelaunch->resolvePidfd( + pidfd, + [this, surface = QPointer(surface)](const QString &appId) { + auto raw = surface.data(); + if (!raw) + return; // surface was deleted before callback + int idx = m_pendingAppIdResolveToplevels.indexOf(raw); + if (idx < 0) + return; // removed before callback + ensureXdgWrapper(raw, appId); + m_pendingAppIdResolveToplevels.removeAt(idx); + }); + if (started) { + qCDebug(lcTlShell) << "AppIdResolver request sent (callback) pidfd=" << pidfd; + return; // async path handles creation + } else { + int idx = m_pendingAppIdResolveToplevels.indexOf(surface); + if (idx >= 0) + m_pendingAppIdResolveToplevels.removeAt(idx); + qCDebug(lcTlShell) + << "AppIdResolverManager present but requestResolve failed pidfd=" << pidfd; + } + } + } + // Async resolve not started or failed -> directly match or create + ensureXdgWrapper(surface, QString()); +} + +#ifndef DISABLE_XWAYLAND +void ShellHandler::onXWaylandSurfaceRemoved(WXWaylandSurface *surface) +{ + auto *wrapper = m_rootSurfaceContainer->getSurface(surface); + if (!wrapper || wrapper->isAboutToRemove()) + return; + if (auto *xwayland = surface->xwayland()) + xwayland->cancelAsyncProperties(surface->handle()->window_id); + Q_EMIT surfaceWrapperAboutToRemove(wrapper); + m_rootSurfaceContainer->destroyForSurface(wrapper); +} +#endif + +void ShellHandler::ensureXdgWrapper(WXdgToplevelSurface *surface, const QString &targetAppId) +{ + auto *prelaunch = prelaunchForSurface(surface); + if (prelaunch && prelaunch->consumeClosed(targetAppId)) { + surface->close(); + return; + } + SurfaceWrapper *wrapper = prelaunch + ? prelaunch->takeSplash(targetAppId, surface, SurfaceWrapper::Type::XdgToplevel) : nullptr; + bool isNewWrapper = !wrapper; + + if (!wrapper) { + wrapper = new SurfaceWrapper(WaylandServer::instance()->qmlEngine(), + surface, + SurfaceWrapper::Type::XdgToplevel, + targetAppId); + workspaceForSurface(wrapper)->addSurface(wrapper); + isNewWrapper = true; // newly created + } + + // Initialize wrapper. Prefer v2 when both are present: the deprecated v1 + // global is kept only for the migration period and dde-shell is expected + // to migrate to v2; a client that binds both is not a supported case. + if (auto *shellSurfaceV2 = DDEShellSurfaceV2::get(surface->surface())) { + handleDdeShellSurfaceV2Added(shellSurfaceV2, wrapper); + } else if (DDEShellSurfaceInterface::get(surface->surface())) { + handleDdeShellSurfaceAdded(surface->surface(), wrapper); + } + auto updateSurfaceWithParentContainer = [this, wrapper, surface] { + if (wrapper->surfaceRole() == SurfaceWrapper::SurfaceRole::PrivilegedOverlay) + return; + updateWrapperContainer(wrapper, surface->parentSurface()); + }; + + QObject::connect(surface, &WXdgToplevelSurface::parentXdgSurfaceChanged, + this, + updateSurfaceWithParentContainer); + updateSurfaceWithParentContainer(); + Q_ASSERT(wrapper->parentItem()); + setupSurfaceWindowMenu(wrapper); + // Only setup active watcher for newly created wrappers; + // prelaunch splash wrappers already have it set up in initializePrelaunchSurface + if (isNewWrapper) { + setupSurfaceActiveWatcher(wrapper); + registerSurfaceToForeignToplevel(wrapper); + } + Q_EMIT surfaceWrapperAdded(wrapper); + + // After surfaceWrapperAdded(): the SSD title bar is arbitrated by its handlers, so an + // earlier apply configures zero padding. + if (surface->isInitialized()) { + const auto initialState = surface->handle()->requested.fullscreen + ? SurfaceWrapper::State::Fullscreen + : surface->handle()->requested.maximized ? SurfaceWrapper::State::Maximized + : SurfaceWrapper::State::Normal; + if (initialState != SurfaceWrapper::State::Normal) + wrapper->setSurfaceStateDirectly(initialState); + } + + // Privileged overlay, IM candidate panel, and snap mask detection via xdg-toplevel-tag + QPointer wrapperPtr(wrapper); + auto applyIfTaggedSurface = [this, wrapperPtr]() { + if (!wrapperPtr) + return; + if (checkAndApplyPrivilegedOverlay(wrapperPtr)) + return; + if (auto *panels = candidatePanels(wrapperPtr->session()); + panels && panels->checkAndApplyIMCandidatePanel(wrapperPtr)) + return; + if (checkAndApplySnapMask(wrapperPtr)) + return; + }; + QObject::connect(surface, &WXdgToplevelSurface::tagChanged, this, applyIfTaggedSurface); + applyIfTaggedSurface(); +} + +bool ShellHandler::checkAndApplyPrivilegedOverlay(SurfaceWrapper *wrapper) +{ + auto *xdgSurface = qobject_cast(wrapper->shellSurface()); + if (!xdgSurface) return false; + if (xdgSurface->tag() != PRIVILEGED_OVERLAY_TAG) { + if (wrapper->surfaceRole() == SurfaceWrapper::SurfaceRole::PrivilegedOverlay) + revokePrivilegedOverlay(wrapper); + return false; + } + applyPrivilegedOverlay(wrapper); + return true; +} + +void ShellHandler::applyPrivilegedOverlay(SurfaceWrapper *wrapper) +{ + qCInfo(lcTlShellXdg) << "Privileged overlay promoted (tag)" + << "wrapper =" << wrapper << "appId =" << wrapper->appId(); + // Move from the original container to the privileged overlay container + if (auto *oldContainer = wrapper->container()) + oldContainer->removeSurface(wrapper); + m_privilegedOverlayContainer->addSurface(wrapper); + wrapper->disableWindowAnimation(); + wrapper->setSurfaceRole(SurfaceWrapper::SurfaceRole::PrivilegedOverlay); + wrapper->setPositionAutomatic(false); + wrapper->setHasInitializeContainer(true); + wrapper->setSkipDockPreView(true); + wrapper->setSkipMutiTaskView(true); +} + +void ShellHandler::revokePrivilegedOverlay(SurfaceWrapper *wrapper) +{ + qCInfo(lcTlShellXdg) << "Privileged overlay revoked (tag removed)" + << "wrapper =" << wrapper << "appId =" << wrapper->appId(); + // Move from the privileged overlay container back to the workspace + if (auto *oldContainer = wrapper->container()) + oldContainer->removeSurface(wrapper); + wrapper->setSurfaceRole(SurfaceWrapper::SurfaceRole::Normal); + wrapper->setPositionAutomatic(true); + wrapper->disableWindowAnimation(false); + wrapper->setSkipDockPreView(false); + wrapper->setSkipMutiTaskView(false); + workspaceForSurface(wrapper)->addSurface(wrapper); +} + +void ShellHandler::onXdgToplevelSurfaceRemoved(WXdgToplevelSurface *surface) +{ + auto wrapper = m_rootSurfaceContainer->getSurface(surface); + + // Remove any attached dde-shell objects before the wrapper-null early + // return: a pending app-id resolve means no wrapper was ever created, yet + // the wl_surface may still hold a shell-surface object. The wl_surface is + // going away, so these objects only need cleanup, not a protocol destroy. + if (auto interfaceV2 = DDEShellSurfaceV2::get(surface->surface())) { + delete interfaceV2; + } + if (auto interface = DDEShellSurfaceInterface::get(surface->surface())) { + delete interface; + } + + // If async resolve still pending, cancel it. If wrapper never created, just return: server + // never exposed this surface (from treeland's perspective). + if (!wrapper) { + if (!m_pendingAppIdResolveToplevels.removeOne(surface)) { + qCWarning(lcTlShell) + << "onXdgToplevelSurfaceRemoved for unknown surface" << surface; + } + return; + } + // Persist the last size of a normal window (prefer normalGeometry) when an appId is present + if (m_windowConfigStore && !wrapper->appId().isEmpty()) { + QSizeF sz = wrapper->normalGeometry().size(); + if ((!sz.isValid() || sz.isEmpty()) && wrapper->isNormal()) { + sz = wrapper->geometry().size(); + } + const QSize s = sz.toSize(); + if (s.isValid() && s.width() > 0 && s.height() > 0) { + m_windowConfigStore->saveLastSize(wrapper->appId(), s); + } + } + Q_EMIT surfaceWrapperAboutToRemove(wrapper); + m_rootSurfaceContainer->destroyForSurface(wrapper); +} + +void ShellHandler::onXdgPopupSurfaceAdded(WXdgPopupSurface *surface) +{ + auto wrapper = new SurfaceWrapper(WaylandServer::instance()->qmlEngine(), + surface, + SurfaceWrapper::Type::XdgPopup); + + auto parent = surface->parentSurface(); + auto parentWrapper = m_rootSurfaceContainer->getSurface(parent); + parentWrapper->addSubSurface(wrapper); + + // When the `parent` is in a specific `container`. for example, when the parent's + // 'container' has a higher z-index than the `popup`, it is necessary to add the `popup` + // to the parent's `container` to ensure that the `popup` displays above it's `parent`. + QQuickItem *ancestorContainer = parentWrapper->container(); + while (ancestorContainer && ancestorContainer->parentItem() != m_popupContainer->parentItem()) { + ancestorContainer = ancestorContainer->parentItem(); + } + if (ancestorContainer && ancestorContainer->z() > m_popupContainer->z()) { + // Set the z-index of the popup itself to ensure it is higher + // than other types of windows within the same container + wrapper->setZ(5); + parentWrapper->container()->addSurface(wrapper); + } else { + m_popupContainer->addSurface(wrapper); + } + // m_popupContainer is a Simple `SurfaceContainer` + // Need to call `setHasInitializeContainer` manually + wrapper->setHasInitializeContainer(true); + wrapper->setOwnsOutput(parentWrapper->ownsOutput()); + setupSurfaceActiveWatcher(wrapper); + + Q_ASSERT(wrapper->parentItem()); + Q_EMIT surfaceWrapperAdded(wrapper); +} + +void ShellHandler::onXdgPopupSurfaceRemoved(WXdgPopupSurface *surface) +{ + auto wrapper = m_rootSurfaceContainer->getSurface(surface); + Q_EMIT surfaceWrapperAboutToRemove(wrapper); + wrapper->setHasInitializeContainer(false); + m_rootSurfaceContainer->destroyForSurface(wrapper); +} + +#ifndef DISABLE_XWAYLAND +void ShellHandler::onXWaylandSurfaceAdded(WXWaylandSurface *surface) +{ + QObject::connect(surface, &WXWaylandSurface::associated, + this, + [this, surface = QPointer(surface)] { + auto raw = surface.data(); + if (!raw) + return; // surface destroyed before callback + // If prelaunch wrappers or closed splash appIds exist and resolver is + // available, attempt async resolve; if started, remaining logic + // handled in callback, then return + auto *prelaunch = prelaunchForSurface(raw); + if (prelaunch && prelaunch->needsResolution()) { + int pidfd = raw->pidFD(); + if (pidfd >= 0) { + m_pendingAppIdResolveToplevels.append(raw); + bool started = prelaunch->resolvePidfd( + pidfd, + [self = QPointer(this), + surface](const QString &appId) { + auto raw = surface.data(); + if (!raw || !self) + return; // surface destroyed before callback + int idx = + self->m_pendingAppIdResolveToplevels.indexOf(raw); + if (idx < 0) + return; // removed before callback + self->fetchInitialProperties(raw, appId); + self->m_pendingAppIdResolveToplevels.removeAt(idx); + }); + if (started) { + qCDebug(lcTlShell) + << "(XWayland) AppIdResolver request sent (callback)"; + return; // async path + } else { + int idx = m_pendingAppIdResolveToplevels.indexOf(raw); + if (idx >= 0) + m_pendingAppIdResolveToplevels.removeAt(idx); + qCDebug(lcTlShell) + << "(XWayland) requestResolve failed pidfd=" << pidfd; + } + } + } + // Async path not taken: directly fetch properties then match/create + fetchInitialProperties(raw, QString()); + }); + QObject::connect(surface, &WXWaylandSurface::aboutToDissociate, this, [this, surface] { + auto wrapper = m_rootSurfaceContainer->getSurface(surface); + qCDebug(lcTlShell) << "WXWayland::aboutToDissociate" << surface << wrapper; + + // Cancel pending async property fetch for this surface. + auto *xwayland = surface->xwayland(); + if (xwayland) { + auto windowId = surface->handle()->window_id; + xwayland->cancelAsyncProperties(windowId); + } + + // Cancel pending async resolve if still present. If wrapper never created, return. + if (!wrapper) { + if (!m_pendingAppIdResolveToplevels.removeOne(surface)) { + qCWarning(lcTlShell) + << "WXWayland::aboutToDissociate for unknown surface" << surface; + } + return; // never created + } + // Persist XWayland window size + if (m_windowConfigStore && !wrapper->appId().isEmpty()) { + QSizeF sz = wrapper->normalGeometry().size(); + if (!sz.isValid() || sz.isEmpty()) { + sz = wrapper->geometry().size(); + } + const QSize s = sz.toSize(); + if (s.isValid() && s.width() > 0 && s.height() > 0) { + m_windowConfigStore->saveLastSize(wrapper->appId(), s); + } + } + Q_EMIT surfaceWrapperAboutToRemove(wrapper); + m_rootSurfaceContainer->destroyForSurface(wrapper); + }); +} + +void ShellHandler::fetchInitialProperties(WXWaylandSurface *surface, const QString &appId) +{ + auto *xwayland = surface->xwayland(); + if (!xwayland) { + ensureXwaylandWrapper(surface, appId); + return; + } + + auto windowId = surface->handle()->window_id; + QVector requests; + auto session = WaylandServer::instance()->sessionManager()->sessionForXWayland(xwayland); + if (auto *panels = candidatePanels(session.get())) + requests.append({ panels->imCandidatePanelAtom(), XCB_ATOM_CARDINAL }); + + if (requests.isEmpty()) { + ensureXwaylandWrapper(surface, appId); + return; + } + + xwayland->readAsyncProperties( + windowId, + requests, + 50, + [self = QPointer(this), + surface = QPointer(surface), + appId](xcb_window_t, const QMap &result) { + auto *raw = surface.data(); + if (!raw || !self) + return; + self->onInitialPropertiesReady(raw, appId, result); + }); +} + +void ShellHandler::onInitialPropertiesReady(WXWaylandSurface *surface, + const QString &appId, + const QMap &result) +{ + auto session = WaylandServer::instance()->sessionManager()->sessionForXWayland(surface->xwayland()); + if (auto *panels = candidatePanels(session.get())) { + bool value = IMCandidatePanelManager::parseIMCandidatePanelProperty( + result, + panels->imCandidatePanelAtom()); + surface->setProperty("imCandidatePanel", value); + } + ensureXwaylandWrapper(surface, appId); +} + +void ShellHandler::ensureXwaylandWrapper(WXWaylandSurface *surface, const QString &targetAppId) +{ + auto *prelaunch = prelaunchForSurface(surface); + if (prelaunch && prelaunch->consumeClosed(targetAppId)) { + surface->close(); + return; + } + SurfaceWrapper *wrapper = prelaunch + ? prelaunch->takeSplash(targetAppId, surface, SurfaceWrapper::Type::XWayland) : nullptr; + bool isNewWrapper = !wrapper; + + if (!wrapper) { + wrapper = new SurfaceWrapper(WaylandServer::instance()->qmlEngine(), + surface, + SurfaceWrapper::Type::XWayland, + targetAppId); + workspaceForSurface(wrapper)->addSurface(wrapper); + isNewWrapper = true; // newly created + } + + // IM candidate panel detection via XWayland xprop + if (auto *panels = candidatePanels(wrapper->session()); + panels && panels->checkAndApplyIMCandidatePanel(wrapper)) { + Q_EMIT surfaceWrapperAdded(wrapper); + return; + } + + // Initialize wrapper + wrapper->setModal(surface->isModal()); + auto surfaceGuard = QPointer(surface); + auto wrapperGuard = QPointer(wrapper); + auto updateSurfaceWithParentContainer = [this, surfaceGuard, wrapperGuard] { + if (!surfaceGuard || !wrapperGuard || wrapperGuard->shellSurface() != surfaceGuard) + return; + + updateWrapperContainer(wrapperGuard, surfaceGuard->parentSurface()); + + if (!surfaceGuard->isBypassManager()) { + if (auto *parent = surfaceGuard->parentXWaylandSurface()) + surfaceGuard->restack(parent, WXWaylandSurface::XCB_STACK_MODE_ABOVE); + } + }; + QObject::connect(surface, + &WXWaylandSurface::parentSurfaceChanged, + wrapper, + updateSurfaceWithParentContainer); + QObject::connect(surface, + &WXWaylandSurface::windowTypesChanged, + wrapper, + updateSurfaceWithParentContainer); + updateSurfaceWithParentContainer(); + Q_ASSERT(wrapper->parentItem()); + const auto initialState = surface->handle()->fullscreen + ? SurfaceWrapper::State::Fullscreen + : (surface->handle()->maximized_horz && surface->handle()->maximized_vert) + ? SurfaceWrapper::State::Maximized : SurfaceWrapper::State::Normal; + if (isNewWrapper && initialState != SurfaceWrapper::State::Normal) { + if (initialState == SurfaceWrapper::State::Fullscreen) + wrapper->enterFullscreen(); + else + wrapper->maximize(); + } + setupSurfaceWindowMenu(wrapper); + // Only setup active watcher for newly created wrappers; + // prelaunch splash wrappers already have it set up in initializePrelaunchSurface + if (isNewWrapper) { + setupSurfaceActiveWatcher(wrapper); + registerSurfaceToForeignToplevel(wrapper); + } + Q_EMIT surfaceWrapperAdded(wrapper); +} +#endif + +void ShellHandler::registerSurfaceToForeignToplevel(SurfaceWrapper *wrapper) +{ + if (!wrapper->skipDockPreView()) { + wrapper->session()->windowManagement()->addSurface(wrapper); + } + connect(wrapper, &SurfaceWrapper::skipDockPreViewChanged, this, [this, wrapper] { + if (wrapper->skipDockPreView()) { + wrapper->session()->windowManagement()->removeSurface(wrapper); + } else { + wrapper->session()->windowManagement()->addSurface(wrapper); + } + }); +} + +bool ShellHandler::checkAndApplySnapMask(SurfaceWrapper *wrapper) +{ + auto *xdgSurface = qobject_cast(wrapper->shellSurface()); + if (!xdgSurface || xdgSurface->tag() != SNAP_MASK_TAG) + return false; + if (wrapper->isSnapMask()) + return true; + + wrapper->setSkipSwitcher(true); + wrapper->setSkipDockPreView(true); + wrapper->setSkipMutiTaskView(true); + wrapper->disableWindowAnimation(); + + if (auto *oldContainer = wrapper->container()) + oldContainer->removeSurface(wrapper); + m_snapMaskContainer->addSurface(wrapper); + + wrapper->setHasInitializeContainer(true); + wrapper->setSnapMask(true); + return true; +} + +void ShellHandler::registerSession(Session *session) +{ + connect(session->prelaunch(), &SessionPrelaunch::splashCreated, + this, &ShellHandler::initializePrelaunchSurface); +#ifndef DISABLE_XWAYLAND + connect(session->outputManager(), &SessionOutputManager::desktopGeometryChanged, + this, &ShellHandler::updateXWaylandDesktopProperties); +#endif + auto *xdgShell = session->protocols()->xdgShell(); + connect(xdgShell, + &WXdgShell::toplevelSurfaceAdded, + this, + &ShellHandler::onXdgToplevelSurfaceAdded); + connect(xdgShell, + &WXdgShell::toplevelSurfaceRemoved, + this, + &::ShellHandler::onXdgToplevelSurfaceRemoved); + connect(xdgShell, &WXdgShell::popupSurfaceAdded, this, &ShellHandler::onXdgPopupSurfaceAdded); + connect(xdgShell, + &WXdgShell::popupSurfaceRemoved, + this, + &ShellHandler::onXdgPopupSurfaceRemoved); + + auto *layerShell = session->protocols()->layerShell(); + connect(layerShell, &WLayerShell::surfaceAdded, this, &ShellHandler::onLayerSurfaceAdded); + connect(layerShell, &WLayerShell::surfaceRemoved, this, &ShellHandler::onLayerSurfaceRemoved); +} + +void ShellHandler::onSurfaceInactivationRequested(SurfaceWrapper *wrapper) +{ + Q_ASSERT(wrapper); + if (wrapper->type() != SurfaceWrapper::Type::Layer) + workspaceForSurface(wrapper)->removeActivedSurface(wrapper); + + auto *server = WaylandServer::instance(); + auto *seatManager = server->seatManager(); + WSeat *primarySeat = server->seat(); + const auto seats = seatManager->seats(); + auto *container = server->rootSurfaceContainer(); + + for (auto *seat : seats) { + auto *seatContainer = container->getSeatContainer(seat); + const bool isKeyboardFocusOwner = seatContainer->keyboardFocusSurface() == wrapper; + const bool isActivatedOwner = seatContainer->activatedSurface() == wrapper; + + if (isKeyboardFocusOwner) { + // Clear the activated state up front instead of relying on activateSurface below: + // the fallback can be refused (e.g. a minimized modal), and the non-primary seat + // path does not activate anything, so a minimized surface must not stay activated. + server->setActivatedSurface(nullptr, seat); + // TODO(multi-seat): non-primary seats should also perform focus fallback once + // per-seat workspace stacking is supported. + if (seat == primarySeat) { + server->activateSurface(m_workspace->current()->latestActiveSurface(), + Qt::OtherFocusReason, + seat, + false); + } else { + server->requestKeyboardFocus(nullptr, Qt::OtherFocusReason, seat); + } + // A refused fallback leaves the focus on this surface; never keep keyboard + // focus on a minimized surface. + if (seatContainer->keyboardFocusSurface() == wrapper) + server->requestKeyboardFocus(nullptr, Qt::OtherFocusReason, seat); + continue; + } + + if (isActivatedOwner) { // not isKeyboardFocusOwner + // Clear the activated state so foreign-toplevel clients do not observe a + // minimized-but-activated window. + server->setActivatedSurface(nullptr, seat); + } + } +} + +void ShellHandler::updateSurfaceAcceptKeyboardFocus(SurfaceWrapper *wrapper, bool accept) +{ + if (accept) { + wrapper->setAcceptKeyboardFocus(true); + return; + } + + // DDE Shell properties may arrive after the surface has already entered + // the activation history. Remove it explicitly instead of treating + // keyboard-focus acceptance as an ActiveControlState capability. + if (wrapper->type() != SurfaceWrapper::Type::Layer && wrapper->workspaceId() != -1) + workspaceForSurface(wrapper)->removeActivedSurface(wrapper); + + auto *server = WaylandServer::instance(); + auto *seatManager = server->seatManager(); + const auto seats = seatManager->seats(); + for (auto *seat : seats) { + auto *seatContainer = server->rootSurfaceContainer()->getSeatContainer(seat); + if (!seatContainer) + continue; + + const bool isActivated = seatContainer->activatedSurface() == wrapper; + const bool hasKeyboardFocus = seatContainer->keyboardFocusSurface() == wrapper; + if (!isActivated && !hasKeyboardFocus) + continue; + + if (seat != server->seat()) { + if (isActivated) + server->setActivatedSurface(nullptr, seat); + if (hasKeyboardFocus) + server->requestKeyboardFocus(nullptr, Qt::OtherFocusReason, seat); + continue; + } + + auto *fallback = seatContainer->keyboardFocusSurface(); + if (!fallback || fallback == wrapper || !fallback->acceptKeyboardFocus()) + fallback = m_workspace->current()->latestActiveSurface(); + if (fallback && !fallback->acceptKeyboardFocus()) + fallback = nullptr; + + if (isActivated) + server->activateSurface(fallback, Qt::OtherFocusReason, seat, false); + else + server->requestKeyboardFocus(fallback, Qt::OtherFocusReason, seat); + } + + wrapper->setAcceptKeyboardFocus(false); +} + +void ShellHandler::setupSurfaceActiveWatcher(SurfaceWrapper *wrapper) +{ + Q_ASSERT_X(wrapper->container(), Q_FUNC_INFO, "Must setContainer at first!"); + + if (wrapper->type() == SurfaceWrapper::Type::XdgPopup) { + // When the popup surface gains focus capability (mapped + grab active), + // move keyboard focus to the popup. SeatSurfaceManager handles + // grab tracking and focus restoration when the grab ends. + connect(wrapper, &SurfaceWrapper::hasFocusCapabilityChanged, this, [this, wrapper]() { + if (!wrapper->hasFocusCapability()) + return; + m_rootSurfaceContainer->givePopupFocus(wrapper); + }); + } else if (wrapper->type() == SurfaceWrapper::Type::Layer) { + connect(wrapper, &SurfaceWrapper::hasFocusCapabilityChanged, this, [this, wrapper]() { + if (wrapper->hasFocusCapability()) { + auto layerSurface = qobject_cast(wrapper->shellSurface()); + Q_ASSERT(layerSurface->keyboardInteractivity() + != WLayerSurface::KeyboardInteractivity::None); + /* + * For OnDemand keyboardInteractivity, only allow surfaces with z-order above + * normal windows (Top/Overlay) to receive keyboard focus, to avoid dock/dde-desktop + * grabbing focus when they restart. + */ + if (layerSurface->layer() >= WLayerSurface::LayerType::Top + || layerSurface->keyboardInteractivity() + == WLayerSurface::KeyboardInteractivity::Exclusive) { + WaylandServer::instance()->cancelShowDesktop(); + WaylandServer::instance()->requestKeyboardFocus(wrapper); + } + } else { + onSurfaceInactivationRequested(wrapper); + } + }); + } else { // Xdgtoplevel or X11 or Splash + connect(wrapper, &SurfaceWrapper::activationRequested, this, [this, wrapper]() { + if (!wrapper->acceptKeyboardFocus()) + return; + + if (WaylandServer::instance()->sessionManager()->isActiveWindow(wrapper) + && wrapper->showOnWorkspace(m_workspace->current()->id())) + WaylandServer::instance()->activateSurface(wrapper); + else + workspaceForSurface(wrapper)->pushActivedSurface(wrapper); + }); + + connect(wrapper, &SurfaceWrapper::inactivationRequested, this, [this, wrapper]() { + onSurfaceInactivationRequested(wrapper); + }); + + if (wrapper->hasActiveCapability() && wrapper->acceptKeyboardFocus()) { + if (WaylandServer::instance()->sessionManager()->isActiveWindow(wrapper) + && wrapper->showOnWorkspace(m_workspace->current()->id())) + WaylandServer::instance()->activateSurface(wrapper); + else + workspaceForSurface(wrapper)->pushActivedSurface(wrapper); + } + } +} + +void ShellHandler::onLayerSurfaceAdded(WLayerSurface *surface) +{ + if (!surface->output() && !m_rootSurfaceContainer->primaryOutput()) { + qCWarning(lcTlShell) << "No output, will close layer surface!"; + surface->closed(); + return; + } + auto wrapper = + new SurfaceWrapper(WaylandServer::instance()->qmlEngine(), surface, SurfaceWrapper::Type::Layer); + + wrapper->setSkipSwitcher(true); + wrapper->setSkipMutiTaskView(true); + updateLayerSurfaceContainer(wrapper); + + connect(surface, &WLayerSurface::layerChanged, this, [this, wrapper] { + updateLayerSurfaceContainer(wrapper); + }); + + setupSurfaceActiveWatcher(wrapper); + Q_ASSERT(wrapper->parentItem()); + Q_EMIT surfaceWrapperAdded(wrapper); +} + +void ShellHandler::onLayerSurfaceRemoved(WLayerSurface *surface) +{ + auto wrapper = m_rootSurfaceContainer->getSurface(surface->surface()); + if (!wrapper) { + qCWarning(lcTlShell) << "A layerSurface that not in any Container is removing!"; + return; + } + Q_EMIT surfaceWrapperAboutToRemove(wrapper); + m_rootSurfaceContainer->destroyForSurface(wrapper); +} + +void ShellHandler::updateLayerSurfaceContainer(SurfaceWrapper *surface) +{ + auto layer = qobject_cast(surface->shellSurface()); + Q_ASSERT(layer); + + if (auto oldContainer = surface->container()) + oldContainer->removeSurface(surface); + + switch (layer->layer()) { + case WLayerSurface::LayerType::Background: + m_backgroundContainer->addSurface(surface); + // wlr-layer-shell leaves the order inside one layer to the compositor. + // Keep the DDE desktop (icon canvas) above other background surfaces, + // such as third-party wallpapers, whatever order they were mapped in. + if (surface->isDesktop()) + surface->setZ(1); + break; + case WLayerSurface::LayerType::Bottom: + m_bottomContainer->addSurface(surface); + break; + case WLayerSurface::LayerType::Top: + m_topContainer->addSurface(surface); + if (surface->isLaunchpad() || surface->isQuickLaunchpad()) + surface->setZ(-1); + break; + case WLayerSurface::LayerType::Overlay: + m_overlayContainer->addSurface(surface); + break; + default: + Q_UNREACHABLE_RETURN(); + } +} + +void ShellHandler::onInputPopupSurfaceV2Added(WInputPopupSurface *surface) +{ + auto wrapper = new SurfaceWrapper(WaylandServer::instance()->qmlEngine(), + surface, + SurfaceWrapper::Type::InputPopup); + auto parent = surface->parentSurface(); + auto parentWrapper = m_rootSurfaceContainer->getSurface(parent); + parentWrapper->addSubSurface(wrapper); + m_popupContainer->addSurface(wrapper); + // m_popupContainer is a simple SurfaceContainer, so input popups need the + // same explicit initialization marker as xdg popups for their first layout. + wrapper->setHasInitializeContainer(true); + wrapper->setOwnsOutput(parentWrapper->ownsOutput()); + Q_ASSERT(wrapper->parentItem()); + Q_EMIT surfaceWrapperAdded(wrapper); +} + +void ShellHandler::onInputPopupSurfaceV2Removed(WInputPopupSurface *surface) +{ + auto wrapper = m_rootSurfaceContainer->getSurface(surface->surface()); + Q_EMIT surfaceWrapperAboutToRemove(wrapper); + wrapper->setHasInitializeContainer(false); + m_rootSurfaceContainer->destroyForSurface(wrapper); +} + +void ShellHandler::setupSurfaceWindowMenu(SurfaceWrapper *wrapper) +{ + Q_ASSERT(m_windowMenu); + connect(wrapper, + &SurfaceWrapper::windowMenuRequested, + m_windowMenu, + [this, wrapper](QPointF pos) { + bool ok = QMetaObject::invokeMethod(m_windowMenu, + "showWindowMenu", + QVariant::fromValue(wrapper), + QVariant::fromValue(pos)); + qCDebug(lcTlShortcut) << "showWindowMenu invokeMethod result=" << ok; + }); +} + +void ShellHandler::onWindowMenuClosed() +{ + WaylandServer::instance()->activateSurface(m_workspace->current()->latestActiveSurface()); +} + +void ShellHandler::handleDdeShellSurfaceAdded(WSurface *surface, SurfaceWrapper *wrapper) +{ + wrapper->setIsDDEShellSurface(true); + auto ddeShellSurface = DDEShellSurfaceInterface::get(surface); + Q_ASSERT(ddeShellSurface); + auto updateLayer = [ddeShellSurface, wrapper] { + if (ddeShellSurface->role().value() == DDEShellSurfaceInterface::OVERLAY) + wrapper->setSurfaceRole(SurfaceWrapper::SurfaceRole::Overlay); + }; + + if (ddeShellSurface->role().has_value()) + updateLayer(); + + connect(ddeShellSurface, &DDEShellSurfaceInterface::roleChanged, this, [updateLayer] { + updateLayer(); + }); + + // Placement hints (set_auto_placement / set_surface_position) only affect + // the initial placement; apply them once here instead of tracking runtime + // changes with ongoing signal connections. + if (ddeShellSurface->yOffset().has_value()) + wrapper->setAutoPlaceCursorOffset(QPoint(0, int(ddeShellSurface->yOffset().value()))); + + if (ddeShellSurface->surfacePos().has_value()) + wrapper->setClientRequstPos(ddeShellSurface->surfacePos().value()); + + if (ddeShellSurface->skipSwitcher().has_value()) + wrapper->setSkipSwitcher(ddeShellSurface->skipSwitcher().value()); + + if (ddeShellSurface->skipDockPreView().has_value()) + wrapper->setSkipDockPreView(ddeShellSurface->skipDockPreView().value()); + + if (ddeShellSurface->skipMutiTaskView().has_value()) + wrapper->setSkipMutiTaskView(ddeShellSurface->skipMutiTaskView().value()); + + updateSurfaceAcceptKeyboardFocus(wrapper, ddeShellSurface->acceptKeyboardFocus()); + + connect(ddeShellSurface, + &DDEShellSurfaceInterface::skipSwitcherChanged, + this, + [wrapper](bool skip) { + wrapper->setSkipSwitcher(skip); + }); + connect(ddeShellSurface, + &DDEShellSurfaceInterface::skipDockPreViewChanged, + this, + [wrapper](bool skip) { + wrapper->setSkipDockPreView(skip); + }); + connect(ddeShellSurface, + &DDEShellSurfaceInterface::skipMutiTaskViewChanged, + this, + [wrapper](bool skip) { + wrapper->setSkipMutiTaskView(skip); + }); + connect(ddeShellSurface, + &DDEShellSurfaceInterface::acceptKeyboardFocusChanged, + this, + [this, wrapper](bool accept) { + updateSurfaceAcceptKeyboardFocus(wrapper, accept); + }); +} + +void ShellHandler::handleDdeShellSurfaceV2Added(DDEShellSurfaceV2 *shellSurface, + SurfaceWrapper *wrapper) +{ + wrapper->setIsDDEShellSurface(true); + + wrapper->setSurfaceRole(static_cast(shellSurface->role())); + connect(shellSurface, &DDEShellSurfaceV2::roleChanged, wrapper, [wrapper](ProtocolRole role) { + wrapper->setSurfaceRole(static_cast(role)); + }); + connect(wrapper, &SurfaceWrapper::surfaceRoleChanged, shellSurface, [wrapper, shellSurface] { + const auto role = wrapper->surfaceRole(); + if (role != SurfaceRole::PrivilegedOverlay) + shellSurface->setRole(static_cast(role)); + }); + + // Placement hints (set_position_hint / set_cursor_placement_hint) only + // affect the initial placement; apply them once here instead of tracking + // runtime changes with ongoing signal connections. + if (auto pos = shellSurface->positionHint()) + wrapper->setClientRequstPos(*pos); + else if (auto offset = shellSurface->cursorPlacementHint()) + wrapper->setAutoPlaceCursorOffset(*offset); + + auto applySkipFlags = [wrapper](quint32 flags) { + wrapper->setSkipSwitcher(flags & DDEShellSurfaceV2::SkipSwitcher); + wrapper->setSkipDockPreView(flags & DDEShellSurfaceV2::SkipDockPreview); + wrapper->setSkipMutiTaskView(flags & DDEShellSurfaceV2::SkipMultitaskView); + }; + applySkipFlags(shellSurface->skipFlags()); + connect(shellSurface, + &DDEShellSurfaceV2::skipFlagsChanged, + this, + applySkipFlags); + + wrapper->setAcceptKeyboardFocus(shellSurface->acceptKeyboardFocus()); + connect(shellSurface, + &DDEShellSurfaceV2::acceptKeyboardFocusChanged, + this, + [wrapper](bool accept) { + wrapper->setAcceptKeyboardFocus(accept); + }); +} + +WInputMethodHelper *ShellHandler::inputMethodHelper(WSeat *seat) const +{ + for (const auto &session : WaylandServer::instance()->sessionManager()->sessions()) { + if (auto *helper = session->seatManager()->inputMethodHelper(seat)) + return helper; + } + return nullptr; +} + +IMCandidatePanelManager *ShellHandler::candidatePanels(Session *session) const +{ + return session ? session->seatManager()->candidatePanels() : nullptr; +} + +void ShellHandler::registerInputMethodHelper(WInputMethodHelper *helper) +{ + connect(helper, &WInputMethodHelper::inputPopupSurfaceV2Added, + this, &ShellHandler::onInputPopupSurfaceV2Added); + connect(helper, &WInputMethodHelper::inputPopupSurfaceV2Removed, + this, &ShellHandler::onInputPopupSurfaceV2Removed); +} diff --git a/src/core/shellhandler.h b/src/core/shellhandler.h new file mode 100644 index 0000000000..61cc8e5d90 --- /dev/null +++ b/src/core/shellhandler.h @@ -0,0 +1,206 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include "modules/foreign-toplevel/foreigntoplevelmanagerv3.h" + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +Q_MOC_INCLUDE("workspace/workspace.h") +Q_MOC_INCLUDE() +Q_MOC_INCLUDE() +#ifndef DISABLE_XWAYLAND +Q_MOC_INCLUDE() +#endif + +class Session; +class TreelandUserConfig; +class WaylandServer; +class SurfaceWrapper; +class RootSurfaceContainer; +class LayerSurfaceContainer; +class Output; +class Workspace; +class SurfaceContainer; +class IMCandidatePanelManager; +class QmlEngine; +class ForeignToplevelManagerInterfaceV3; +class SessionPrelaunch; +class WineWindowStateManager; +class WineWindowManager; +class SnapTargetV1; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WServer; +class WXdgToplevelSurface; +class WXdgPopupSurface; +class WXdgShell; +class WLayerShell; +class WLayerSurface; +#ifndef DISABLE_XWAYLAND +class WXWayland; +#endif +class WToplevelSurface; // forward declare base toplevel +class WInputMethodHelper; +class WInputPopupSurface; +class WSeat; +class WSurface; +#ifndef DISABLE_XWAYLAND +class WXWaylandSurface; +#endif +WAYLIB_SERVER_END_NAMESPACE + +QT_BEGIN_NAMESPACE +class QQuickItem; +class QQuickWindow; +QT_END_NAMESPACE + +class AppIdResolverManager; // forward declare new protocol manager +class WindowConfigStore; // forward declare config store +class TreelandWallpaperShellInterfaceV1; +class TreelandWallpaperSurfaceInterfaceV1; +class LayerShellExtensionManagerInterfaceV1; + +class ShellHandler : public QObject +{ + Q_OBJECT + +public: + explicit ShellHandler(RootSurfaceContainer *rootContainer, + WAYLIB_SERVER_NAMESPACE::WServer *server); + [[nodiscard]] Workspace *workspace() const; + void setWorkspace(Workspace *workspace); + Workspace *workspaceForSurface(SurfaceWrapper *wrapper) const; + [[nodiscard]] LayerSurfaceContainer *backgroundContainer() const { return m_backgroundContainer; } + [[nodiscard]] SurfaceContainer *popupContainer() const; + [[nodiscard]] SurfaceContainer *privilegedOverlayContainer() const; + [[nodiscard]] SurfaceContainer *snapMaskContainer() const; + [[nodiscard]] RootSurfaceContainer *rootSurfaceContainer() const; + [[nodiscard]] ForeignToplevelManagerInterfaceV3 *foreignToplevel() const; + void registerSession(Session *session); + + void createComponent(QmlEngine *engine, QQuickItem *parentItem); + void init(WAYLIB_SERVER_NAMESPACE::WServer *server, WAYLIB_SERVER_NAMESPACE::WSeat *seat); +#ifndef DISABLE_XWAYLAND + [[nodiscard]] WAYLIB_SERVER_NAMESPACE::WXWayland *createXWayland( + WAYLIB_SERVER_NAMESPACE::WServer *server, + WAYLIB_SERVER_NAMESPACE::WSeat *seat, + wlr_compositor *compositor, + bool lazy); + // FIXME: never call removeXWayland in treeland.cpp + void removeXWayland(WAYLIB_SERVER_NAMESPACE::WXWayland *xwayland); + + WAYLIB_SERVER_NAMESPACE::WXWayland *defaultXWaylandSocket() const; +#endif + + TreelandWallpaperShellInterfaceV1 *wallpaperShell() const + { + return m_wallpaperShell; + } + + [[nodiscard]] WAYLIB_SERVER_NAMESPACE::WInputMethodHelper *inputMethodHelper( + WAYLIB_SERVER_NAMESPACE::WSeat *seat) const; + void registerInputMethodHelper(WAYLIB_SERVER_NAMESPACE::WInputMethodHelper *helper); + IMCandidatePanelManager *candidatePanels(Session *session) const; + +Q_SIGNALS: + void workspaceChanged(); + void workspaceAdded(); + void surfaceWrapperAdded(SurfaceWrapper *wrapper); + void surfaceWrapperAboutToRemove(SurfaceWrapper *wrapper); + +private Q_SLOTS: + void onXdgToplevelSurfaceAdded(WAYLIB_SERVER_NAMESPACE::WXdgToplevelSurface *surface); + void onXdgToplevelSurfaceRemoved(WAYLIB_SERVER_NAMESPACE::WXdgToplevelSurface *surface); + + void onXdgPopupSurfaceAdded(WAYLIB_SERVER_NAMESPACE::WXdgPopupSurface *surface); + void onXdgPopupSurfaceRemoved(WAYLIB_SERVER_NAMESPACE::WXdgPopupSurface *surface); + +#ifndef DISABLE_XWAYLAND + void onXWaylandSurfaceAdded(WAYLIB_SERVER_NAMESPACE::WXWaylandSurface *surface); + void onXWaylandSurfaceRemoved(WAYLIB_SERVER_NAMESPACE::WXWaylandSurface *surface); +#endif + + void onLayerSurfaceAdded(WAYLIB_SERVER_NAMESPACE::WLayerSurface *surface); + void onLayerSurfaceRemoved(WAYLIB_SERVER_NAMESPACE::WLayerSurface *surface); + + void onInputPopupSurfaceV2Added(WAYLIB_SERVER_NAMESPACE::WInputPopupSurface *surface); + + void onInputPopupSurfaceV2Removed(WAYLIB_SERVER_NAMESPACE::WInputPopupSurface *surface); + void onWindowMenuClosed(); + +private: + void setupSurfaceActiveWatcher(SurfaceWrapper *wrapper); + void onSurfaceInactivationRequested(SurfaceWrapper *wrapper); + void updateSurfaceAcceptKeyboardFocus(SurfaceWrapper *wrapper, bool accept); + void setupSurfaceWindowMenu(SurfaceWrapper *wrapper); + void updateLayerSurfaceContainer(SurfaceWrapper *surface); + void registerSurfaceToForeignToplevel(SurfaceWrapper *wrapper); + bool checkAndApplySnapMask(SurfaceWrapper *wrapper); + void handleDdeShellSurfaceAdded(WAYLIB_SERVER_NAMESPACE::WSurface *surface, + SurfaceWrapper *wrapper); + void handleDdeShellSurfaceV2Added(class DDEShellSurfaceV2 *shellSurface, + SurfaceWrapper *wrapper); +#ifndef DISABLE_XWAYLAND + void updateXWaylandDesktopProperties(); + void watchXWaylandDesktopOutput(Output *output); + void watchXWaylandWorkspaceNames(); +#endif + void onWorkspaceCountChanged(); + // Resolve launch state from the fixed client domain, never the active desktop. + SessionPrelaunch *prelaunchForSurface(WAYLIB_SERVER_NAMESPACE::WToplevelSurface *surface) const; + void initializePrelaunchSurface(SurfaceWrapper *wrapper); + void ensureXdgWrapper(WAYLIB_SERVER_NAMESPACE::WXdgToplevelSurface *surface, + const QString &targetAppId); +#ifndef DISABLE_XWAYLAND + void ensureXwaylandWrapper(WAYLIB_SERVER_NAMESPACE::WXWaylandSurface *surface, + const QString &targetAppId); +#endif + void updateWrapperContainer(SurfaceWrapper *wrapper, + WAYLIB_SERVER_NAMESPACE::WSurface *parentSurface); +#ifndef DISABLE_XWAYLAND + // Async X11 property fetch for XWayland surfaces + void fetchInitialProperties(WAYLIB_SERVER_NAMESPACE::WXWaylandSurface *surface, + const QString &appId); + void onInitialPropertiesReady(WAYLIB_SERVER_NAMESPACE::WXWaylandSurface *surface, + const QString &appId, + const QMap &result); +#endif + bool checkAndApplyPrivilegedOverlay(SurfaceWrapper *wrapper); + void applyPrivilegedOverlay(SurfaceWrapper *wrapper); + void revokePrivilegedOverlay(SurfaceWrapper *wrapper); + TreelandWallpaperShellInterfaceV1 *m_wallpaperShell = nullptr; +#ifndef DISABLE_XWAYLAND + QList m_xwaylands; +#endif + + QPointer m_rootSurfaceContainer; + LayerSurfaceContainer *m_backgroundContainer = nullptr; + LayerSurfaceContainer *m_bottomContainer = nullptr; + Workspace *m_workspace = nullptr; + LayerSurfaceContainer *m_topContainer = nullptr; + LayerSurfaceContainer *m_overlayContainer = nullptr; + SurfaceContainer *m_popupContainer = nullptr; + SurfaceContainer *m_privilegedOverlayContainer = nullptr; + SurfaceContainer *m_snapMaskContainer = nullptr; + QObject *m_windowMenu = nullptr; + // Dock preview QML object + // Pending toplevel surfaces (XDG or XWayland) awaiting async AppId resolve; callbacks continue + // only if the pointer remains in this list + QList m_pendingAppIdResolveToplevels; + LayerShellExtensionManagerInterfaceV1 *m_layerShellExtensionManagerInterfaceV1 = nullptr; + WindowConfigStore *m_windowConfigStore = nullptr; + SnapTargetV1 *m_snapTarget = nullptr; +}; diff --git a/src/core/surfaceprotocolcontroller.cpp b/src/core/surfaceprotocolcontroller.cpp new file mode 100644 index 0000000000..14debeda16 --- /dev/null +++ b/src/core/surfaceprotocolcontroller.cpp @@ -0,0 +1,360 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "surfaceprotocolcontroller.h" +#include "session/sessionmanager.h" +#include "waylandserver.h" +#include "showdesktop/showdesktop.h" +#include "rootsurfacecontainer.h" +#include "shellhandler.h" +#include "session/session.h" +#include "session/sessionprotocols.h" +#include "input/inputmanager.h" +#include "modules/output-manager/outputmanagement.h" +#include "modules/wine-window-management/winewindowmanagement.h" +#include "modules/wine-window-state/winewindowstate.h" +#include "wallpaper/wallpapermanager.h" +#include "modules/wallpaper/wallpapermanagerinterfacev1.h" +#include "surface/surfacewrapper.h" +#include "workspace/workspace.h" +#include "modules/personalization/personalizationmanagerinterfacev1.h" +#include "modules/decoration/decorationmanagerinterfacev1.h" +#include "modules/region-watch/regionwatchmanagerinterfacev1.h" +#include "common/treelandlogging.h" +#include "modules/dde-shell/ddeshellattached.h" + +#include +#include +#include +#include +#include +#include +#ifndef DISABLE_XWAYLAND +#include +#endif +#include +#include + +#include + +SurfaceProtocolController::SurfaceProtocolController(WaylandServer *server) + : QObject(server), + m_server(server) +{} + +void SurfaceProtocolController::installRegionWatch(WServer *server) +{ + m_regionWatchManagerInterfaceV1 = server->attach(); +} + +void SurfaceProtocolController::installToplevels(ShellHandler *shell) +{ + connect(shell, + &ShellHandler::surfaceWrapperAdded, + this, + &SurfaceProtocolController::onSurfaceWrapperAdded); + + connect(shell, + &ShellHandler::surfaceWrapperAboutToRemove, + this, + &SurfaceProtocolController::onSurfaceWrapperAboutToRemove); +} + +void SurfaceProtocolController::connectForeignToplevel(WForeignToplevel *manager) +{ + connect(manager, &WForeignToplevel::requestActivate, this, + [this](WToplevelSurface *surface) { + if (auto *wrapper = m_server->rootContainer()->getSurface(surface)) + m_server->forceActivateSurface(wrapper, Qt::OtherFocusReason); + }); + connect(manager, &WForeignToplevel::requestMaximize, this, + [this](WToplevelSurface *surface, bool maximized) { + if (auto *wrapper = m_server->rootContainer()->getSurface(surface)) { + if (maximized) + wrapper->maximize(); + else + wrapper->unmaximize(); + } + }); + connect(manager, &WForeignToplevel::requestMinimize, this, + [this](WToplevelSurface *surface, bool minimized) { + auto *wrapper = m_server->rootContainer()->getSurface(surface); + if (!wrapper) + return; + if (m_server->showDesktopState() == ShowDesktop::State::Show) { + m_server->forceActivateSurface(wrapper); + } else if (minimized) { + wrapper->minimize(); + } else { + wrapper->restoreFromMinimized(); + } + }); + connect(manager, &WForeignToplevel::requestFullscreen, this, + [this](WToplevelSurface *surface, bool fullscreen) { + if (auto *wrapper = m_server->rootContainer()->getSurface(surface)) { + if (fullscreen) + wrapper->enterFullscreen(); + else + wrapper->leaveFullscreen(); + } + }); + connect(manager, &WForeignToplevel::requestClose, this, + [this](WToplevelSurface *surface) { + if (auto *wrapper = m_server->rootContainer()->getSurface(surface)) + wrapper->close(); + }); +} + +void SurfaceProtocolController::initializeSession(Session *session) +{ + auto *xdgDecoration = session->protocols()->xdgDecoration(); + connect(xdgDecoration, + &WXdgDecorationManager::surfaceModeChanged, + this, + &SurfaceProtocolController::onSurfaceModeChanged); + + auto *xdgDialog = session->protocols()->xdgDialog(); + connect(xdgDialog, + &WXdgDialogManagerV1::surfaceModalChanged, + this, + [this](WXdgToplevelSurface *toplevel, bool modal) { + if (auto *wrapper = m_server->rootContainer()->getSurface(toplevel)) { + wrapper->setModal(modal); + } else { + qCWarning(lcTlShell) << "xdg-dialog-v1: no wrapper for toplevel" << toplevel; + } + }); + + auto *foreign = new WForeignToplevel; + auto *list = new WExtForeignToplevelListV1; + session->attachInterface(foreign); + session->attachInterface(list); + connectForeignToplevel(foreign); + session->m_foreignToplevel = foreign; + session->m_toplevelList = list; + auto *windowManagement = new ForeignToplevelManagerInterfaceV3(session); + session->m_windowManagement = windowManagement; + session->attachInterface(windowManagement); + auto *inputProtocol = new TreelandInputManagerInterfaceV1; + session->attachInterface(inputProtocol); + connect(inputProtocol, &TreelandInputManagerInterfaceV1::mouseSettingsCreated, + session->inputManager(), &InputManager::onMouseSettingsCreated); + connect(inputProtocol, &TreelandInputManagerInterfaceV1::touchpadSettingsCreated, + session->inputManager(), &InputManager::onTouchpadSettingsCreated); + connect(inputProtocol, &TreelandInputManagerInterfaceV1::keyboardSettingsCreated, + session->inputManager(), &InputManager::onKeyboardSettingsCreated); + auto *wallpaperProtocol = new TreelandWallpaperManagerInterfaceV1(session); + session->attachInterface(wallpaperProtocol); + connect(wallpaperProtocol, &TreelandWallpaperManagerInterfaceV1::wallpaperCreated, + session->wallpaperManager(), &WallpaperManager::onWallpaperAdded); + session->attachInterface(new OutputManagerV2(session)); + session->attachInterface(new WineWindowManager); + session->attachInterface(new WineWindowStateManager); + m_server->shellHandler()->registerSession(session); +} + +void SurfaceProtocolController::onSurfaceModeChanged(WSurface *surface, WXdgDecorationManager::DecorationMode mode) +{ + auto s = m_server->rootContainer()->getSurface(surface); + if (!s) { + return; + } + + s->setNoDecoration(mode != WXdgDecorationManager::Server); +} + +void SurfaceProtocolController::addForeignToplevel(SurfaceWrapper *wrapper) +{ + if (auto *session = wrapper->session()) { + session->foreignToplevel()->addSurface(wrapper->shellSurface()); + session->toplevelList()->addSurface(wrapper->shellSurface()); + } +} + +void SurfaceProtocolController::removeForeignToplevel(SurfaceWrapper *wrapper) +{ + if (auto *session = wrapper->session()) { + session->foreignToplevel()->removeSurface(wrapper->shellSurface()); + session->toplevelList()->removeSurface(wrapper->shellSurface()); + } +} + +void SurfaceProtocolController::onSurfaceWrapperAdded(SurfaceWrapper *wrapper) +{ + if (wrapper->isIMCandidatePanel() || !wrapper->session()) + return; + auto *protocols = wrapper->session()->protocols(); + auto *xdgDecoration = protocols->xdgDecoration(); + + bool isXdgToplevel = wrapper->type() == SurfaceWrapper::Type::XdgToplevel; + bool isXdgPopup = wrapper->type() == SurfaceWrapper::Type::XdgPopup; + bool isXwayland = wrapper->type() == SurfaceWrapper::Type::XWayland; + bool isLayer = wrapper->type() == SurfaceWrapper::Type::Layer; + + connect(wrapper->session(), + &Session::aboutToBeDestroyed, + wrapper, + &SurfaceWrapper::closeSurface); + + if (isXdgToplevel || isXdgPopup || isLayer) { + auto *attached = + new Personalization(wrapper->shellSurface(), protocols->personalization(), wrapper); + connect(wrapper, &SurfaceWrapper::aboutToBeInvalidated, + attached, &Personalization::deleteLater); + + // New SSD personalization protocol (treeland-decoration-unstable-v1). + // The frozen Personalization above handles the deprecated + // treeland-personalization-manager-v1 window context; per-window + // customization for the new protocol is applied via Decoration. + // + // An xdg popup negotiates no xdg-decoration and has no titlebar of its + // own: its frame follows the parent's decoration state. This must run + // BEFORE the Decoration adapter below — its constructor applies an + // existing decoration context, and that opt-in must win over the + // parent-following default. + if (isXdgPopup) { + wrapper->setNoTitleBar(true); + wrapper->setNoDecoration(wrapper->parentSurface() + && wrapper->parentSurface()->noDecoration()); + } + + auto *decoration = + new Decoration(wrapper->shellSurface(), protocols->decoration(), wrapper); + connect(wrapper, &SurfaceWrapper::aboutToBeInvalidated, + decoration, &Decoration::deleteLater); + + // COMPAT: dde-shell still drives the quick launchpad through the + // deprecated personalization protocol, whose NoTitleBar state used to + // switch the wrapper back to compositor decoration (SSD frame). Keep + // that side effect only for the quick launchpad so it keeps drawing + // its frame during the migration period. + // TODO: drop once dde-shell migrates the quick launchpad to the new + // treeland-decoration protocol (together with the deprecated + // personalization protocol). + if (wrapper->isQuickLaunchpad() && attached->noTitlebar()) { + wrapper->setNoDecoration(false); + } + + auto updateBlur = [attached] { + attached->surfaceWrapper()->setBlurPersonalization(attached->backgroundType() == Personalization::BackgroundType::Blur); + }; + connect(attached, &Personalization::backgroundTypeChanged, this, updateBlur); + + // NOTE: corner radius is written by BOTH the deprecated personalization + // protocol (here) and the new decoration protocol (Decoration::applyContext). + // The two are not arbitrated; if a client uses both, the last signal to + // arrive wins. This is intentional: clients are expected to use only one + // of the two protocols. When the deprecated personalization protocol is + // removed, drop this block and its setRadius() call — the decoration + // protocol already drives SurfaceWrapper::setRadius() on its own. + auto updateCornerRadius = [attached] { + // The deprecated protocol has no "unset" state, so its 0 keeps meaning + // "use the compositor default" rather than "square corners". + const auto radius = attached->cornerRadius(); + attached->surfaceWrapper()->setRadius(radius > 0 ? radius : -1); + }; + connect(attached, &Personalization::cornerRadiusChanged, this, updateCornerRadius); + updateCornerRadius(); + updateBlur(); + if (wrapper->isLaunchpad()) + wrapper->setCoverEnabled(true); + + // Titlebar arbitration: only toplevels have an SSD titlebar. + // Popups and layer shells never draw one, so they never reach here. + if (isXdgToplevel) { + auto updateNoTitlebar = [attached, decoration] { + const bool decorationHides = decoration->hasTitlebarOverride() + && decoration->titlebarHidden(); + + attached->surfaceWrapper()->setNoTitleBar(attached->noTitlebar() + || decorationHides); + }; + + connect(attached, &Personalization::windowStateChanged, this, updateNoTitlebar); + connect(decoration, &Decoration::titlebarOverrideChanged, this, updateNoTitlebar); + updateNoTitlebar(); + + // Replay the mode in case xdg-decoration was negotiated before this + // wrapper existed; later changes go through onSurfaceModeChanged(). + wrapper->setNoDecoration(xdgDecoration->modeBySurface(wrapper->surface()) + != WXdgDecorationManager::Server); + } + } + + if (isXwayland) { +#ifndef DISABLE_XWAYLAND + auto xwaylandSurface = qobject_cast(wrapper->shellSurface()); + auto updateDecorationTitleBar = [wrapper, xwaylandSurface, sessionManager = m_server->sessionManager()]() { + auto *xwayland = xwaylandSurface->xwayland(); + const auto session = xwayland + ? sessionManager->sessionForXWayland(xwayland) + : std::shared_ptr(); + xcb_atom_t noTitlebarAtom = XCB_ATOM_NONE; + if (session) + noTitlebarAtom = session->noTitlebarAtom(); + const auto flags = xwaylandSurface->effectiveDecorationsFlags(noTitlebarAtom); + wrapper->setNoTitleBar(flags & WXWaylandSurface::DecorationsNoTitle); + wrapper->setNoDecoration(flags & WXWaylandSurface::DecorationsNoBorder); + }; + // When x11 surface dissociate, SurfaceWrapper will be destroyed immediately + // but WXWaylandSurface will not, so must connect to `wrapper` + QObject::connect(xwaylandSurface, &WXWaylandSurface::bypassManagerChanged, + wrapper, + updateDecorationTitleBar); + QObject::connect(xwaylandSurface, &WXWaylandSurface::decorationsFlagsChanged, + wrapper, + updateDecorationTitleBar); + updateDecorationTitleBar(); + + wrapper->setHideByWorkspace(!m_server->surfaceBelongsToCurrentSession(wrapper)); +#endif + } + + if (!isLayer) { + [[maybe_unused]] auto windowOverlapChecker = new WindowOverlapChecker(wrapper, wrapper); + + if (m_regionWatchManagerInterfaceV1) + m_regionWatchManagerInterfaceV1->addSurface(wrapper); + } + +#ifndef DISABLE_DDM + if (isLayer) { + connect(m_server, &WaylandServer::currentModeChanged, wrapper, [this, wrapper] { + wrapper->setHideByLockScreen(m_server->currentMode() == WaylandServer::CurrentMode::LockScreen); + }); + wrapper->setHideByLockScreen(m_server->currentMode() == WaylandServer::CurrentMode::LockScreen); + } +#endif + + if (!wrapper->skipDockPreView()) { + addForeignToplevel(wrapper); + } + connect(wrapper, &SurfaceWrapper::skipDockPreViewChanged, this, [this, wrapper] { + if (wrapper->skipDockPreView()) { + removeForeignToplevel(wrapper); + } else { + addForeignToplevel(wrapper); + } + }); +} + +void SurfaceProtocolController::onSurfaceWrapperAboutToRemove(SurfaceWrapper *wrapper) +{ + if (wrapper->isIMCandidatePanel()) + return; + + if (m_regionWatchManagerInterfaceV1) + m_regionWatchManagerInterfaceV1->removeSurface(wrapper); + + if (!wrapper->skipDockPreView()) { + removeForeignToplevel(wrapper); + } + // Ensure the wrapper is removed from active history early to avoid cascading on half-invalid entries + if (wrapper && wrapper->workspaceId() != -1) { + auto ws = qobject_cast(wrapper->container()); + if (ws) { + Q_ASSERT(ws == wrapper->container()); + ws->removeActivedSurface(wrapper); + } + } +} diff --git a/src/core/surfaceprotocolcontroller.h b/src/core/surfaceprotocolcontroller.h new file mode 100644 index 0000000000..2cab5077d7 --- /dev/null +++ b/src/core/surfaceprotocolcontroller.h @@ -0,0 +1,51 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include + +#include + +class WaylandServer; +class Session; +class ShellHandler; +class SurfaceWrapper; +class PersonalizationManagerInterfaceV1; +class DecorationManagerInterfaceV1; +class TreelandRegionWatchManagerInterfaceV1; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WServer; +class WForeignToplevel; +class WExtForeignToplevelListV1; +class WXdgDialogManagerV1; +class WXdgToplevelTagManagerV1; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class SurfaceProtocolController : public QObject +{ + Q_OBJECT +public: + explicit SurfaceProtocolController(WaylandServer *server); + + void installRegionWatch(WServer *server); + void installToplevels(ShellHandler *shell); + void initializeSession(Session *session); +private: + void onSurfaceModeChanged(WSurface *surface, WXdgDecorationManager::DecorationMode mode); + void connectForeignToplevel(WForeignToplevel *manager); + void addForeignToplevel(SurfaceWrapper *wrapper); + void removeForeignToplevel(SurfaceWrapper *wrapper); + void onSurfaceWrapperAdded(SurfaceWrapper *wrapper); + void onSurfaceWrapperAboutToRemove(SurfaceWrapper *wrapper); + +private: + WaylandServer *m_server = nullptr; + TreelandRegionWatchManagerInterfaceV1 *m_regionWatchManagerInterfaceV1 = nullptr; +}; diff --git a/src/core/treeland.cpp b/src/core/treeland.cpp new file mode 100644 index 0000000000..b7716ce455 --- /dev/null +++ b/src/core/treeland.cpp @@ -0,0 +1,699 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "treeland.h" +#include "session/sessionmanager.h" + +#include "core/qmlengine.h" +#include "dconfig/dconfigmanager.h" +#include "greeter/usermodel.h" +#ifndef DISABLE_DDM +#include "greeter/greeterproxy.h" +#include "greeter/loginstatequery.h" +#endif +#include "interfaces/multitaskviewinterface.h" +#include "interfaces/plugininterface.h" +#include "core/waylandserver.h" +#include "seatuserconfig.hpp" +#include "seat/seatmanager.h" +#include "session/session.h" +#include "treelanduserconfig.hpp" +#include "utils/cmdline.h" +#include "utils/scriptrunner.h" +#include "common/treelandlogging.h" +#include "common/constants.h" + +#include + +#if !defined(DISABLE_DDM) || defined(EXT_SESSION_LOCK_V1) +#include "interfaces/lockscreeninterface.h" +#endif + +#include +#include +#ifndef DISABLE_XWAYLAND +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +DCORE_USE_NAMESPACE + +namespace Treeland { + +class TreelandPrivate : public QObject +{ + Q_OBJECT + Q_DECLARE_PUBLIC(Treeland) +public: + explicit TreelandPrivate(Treeland *parent) + : QObject(parent) + , q_ptr(parent) +#ifndef DISABLE_DDM + , socket(new QLocalSocket(this)) +#endif + { + } + + void init(std::function onInitialized) + { + qmlEngine = new QmlEngine(this); + qmlEngine->addImportPath(QString("%1/qt/qml").arg(QCoreApplication::applicationDirPath())); + for (const auto &item : + QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation)) { + qmlEngine->addImportPath(item + "/treeland/qml"); + } + + W_Q(Treeland); + // Use QueuedConnection to avoid + // assert(wlroots: assert(wl_list_empty(&cur->events.button.listener_list))) + // failed during quit(If the quit call is from the cursor's button press/release event) + connect(qmlEngine, &QQmlEngine::quit, q, &Treeland::quit, Qt::QueuedConnection); + +#ifndef DISABLE_DDM + auto userModel = qmlEngine->singletonInstance("Treeland", "UserModel"); + const QString initialUserName = userModel && !userModel->currentUserName().isEmpty() + ? userModel->currentUserName() + : QStringLiteral("dde"); +#else + const QString initialUserName = QStringLiteral("dde"); +#endif + auto initializeTreeland = [this, q, onInitialized = std::move(onInitialized)] { + server = qmlEngine->singletonInstance("Treeland", "WaylandServer"); + connect(server, &WaylandServer::requestQuit, q, &Treeland::quit, Qt::QueuedConnection); + +#ifndef DISABLE_XWAYLAND + if (qEnvironmentVariableIsEmpty("WLR_XWAYLAND")) + qputenv("WLR_XWAYLAND", QByteArray(LIBEXEC_DIR) + "/treeland-xwayland"); +#endif + server->init(q); + +#ifndef DISABLE_DDM + connect(server, + &WaylandServer::configChanged, + this, + &TreelandPrivate::onCurrentUserChanged); + onCurrentUserChanged(); +#endif + onInitialized(); + }; + + auto *configManager = DConfigManager::instance(); + if (!configManager || configManager->initializeUserConfigs(initialUserName)) { + qCInfo(lcTlConfig) << "Initial user DConfig is ready for" << initialUserName; + initializeTreeland(); + return; + } + + qCInfo(lcTlConfig) << "Waiting for initial user DConfig initialization for" + << initialUserName; + + auto *userConfig = configManager->initialUserConfig(); + auto *seatConfig = configManager->userSeatConfig(initialUserName, QStringLiteral(DEFAULT_SEAT_NAME)); + auto initialized = std::make_shared(false); + auto initializeWhenReady = [initializeTreeland, + userConfig, + seatConfig, + initialized, + initialUserName] { + if (*initialized) { + return; + } + + const bool userSucceeded = userConfig && userConfig->isInitializeSucceeded(); + const bool seatSucceeded = seatConfig && seatConfig->isInitializeSucceeded(); + const bool userFinished = !userConfig || userSucceeded + || userConfig->isInitializeFailed(); + const bool seatFinished = !seatConfig || seatSucceeded + || seatConfig->isInitializeFailed(); + if (!userFinished || !seatFinished) { + return; + } + + *initialized = true; + if (!userSucceeded || !seatSucceeded) { + qCWarning(lcTlConfig) + << "Initial user DConfig initialization failed; Treeland will continue with generated defaults."; + } else { + qCInfo(lcTlConfig) << "Initial user DConfig initialization completed for" + << initialUserName; + } + initializeTreeland(); + }; + + if (userConfig) { + connect(userConfig, + &TreelandUserConfig::configInitializeSucceed, + this, + initializeWhenReady, + Qt::SingleShotConnection); + connect(userConfig, + &TreelandUserConfig::configInitializeFailed, + this, + initializeWhenReady, + Qt::SingleShotConnection); + } + if (seatConfig) { + connect(seatConfig, + &SeatUserDConfig::configInitializeSucceed, + this, + initializeWhenReady, + Qt::SingleShotConnection); + connect(seatConfig, + &SeatUserDConfig::configInitializeFailed, + this, + initializeWhenReady, + Qt::SingleShotConnection); + } + initializeWhenReady(); + } + + ~TreelandPrivate() + { + for (auto plugin : plugins) { + plugin->shutdown(); + delete plugin; + } + + plugins.clear(); + + for (auto it = pluginTs.begin(); it != pluginTs.end();) { + QCoreApplication::removeTranslator(it->second); + it->second->deleteLater(); + pluginTs.erase(it++); + } + // UserModel must be deleted before WaylandServer, to remove client surfaces before rendering ends. + delete qmlEngine->singletonInstance("Treeland", "UserModel"); + // WaylandServer must be deleted before QmlEngine, for surfaces to be cleanly removed. + qmlEngine->clearSingletons(); + } + +#ifndef DISABLE_DDM + void onCurrentUserChanged() + { + auto userModel = + qmlEngine->singletonInstance("Treeland", "UserModel"); + auto user = userModel->currentUser(); + onCurrentChanged(user ? user->UID() : getuid()); + } + + void onCurrentChanged(uid_t uid) + { + auto userModel = + server->qmlEngine()->singletonInstance("Treeland", "UserModel"); + auto user = userModel->getUser(uid); + if (!user) { + qCWarning(lcTlDBus) << "user " << uid << " has been added but couldn't find it."; + return; + } + + auto locale = user->locale(); + qCInfo(lcTlDBus) << "current locale:" << locale.language(); + + do { + auto *newTrans = new QTranslator{ this }; + if (newTrans + ->load(locale, "treeland", ".", TREELAND_COMPONENTS_TRANSLATION_DIR, ".qm")) { + if (lastTrans) { + QCoreApplication::removeTranslator(lastTrans); + lastTrans->deleteLater(); + } + lastTrans = newTrans; + QCoreApplication::installTranslator(lastTrans); + qmlEngine->retranslate(); + break; + } + newTrans->deleteLater(); + qCWarning(lcTlDBus) << "failed to load new translator"; + } while (false); + } + + void updatePluginTs(PluginInterface *plugin, const QString &scope) + { + auto userModel = + server->qmlEngine()->singletonInstance("Treeland", "UserModel"); + auto user = userModel->currentUser(); + if (!user) { + return; + } + + auto locale = userModel->currentUser()->locale(); + qCInfo(lcTlDBus) << "current locale:" << locale.language(); + QTranslator *newTrans = new QTranslator; + + if (newTrans->load(locale, scope, ".", TREELAND_COMPONENTS_TRANSLATION_DIR, ".qm")) { + for (auto it = pluginTs.begin(); it != pluginTs.end(); ++it) { + if (it->first == plugin) { + QCoreApplication::removeTranslator(it->second); + pluginTs.erase(it); + break; + } + } + + pluginTs[plugin] = newTrans; + QCoreApplication::installTranslator(pluginTs[plugin]); + qmlEngine->retranslate(); + } else { + qCWarning(lcTlDBus) << "failed to load plugin translator: " << scope; + } + } +#endif + + void loadPlugin(const QString &path) + { + Q_Q(Treeland); + + QDir pluginsDir(path); + + if (!pluginsDir.exists()) { + return; + } + + const QStringList pluginFiles = pluginsDir.entryList(QDir::Files | QDir::NoDotAndDotDot); + for (const QString &pluginFile : pluginFiles) { + QString filePath = pluginsDir.absoluteFilePath(pluginFile); + qCDebug(lcTlPlugin) << "Attempting to load plugin:" << filePath; + + QPluginLoader loader(filePath); + QObject *pluginInstance = loader.instance(); + + if (!pluginInstance) { + qCWarning(lcTlPlugin) << "Failed to load plugin:" << loader.errorString(); + continue; + } + + PluginInterface *plugin = qobject_cast(pluginInstance); + if (!plugin) { + qCWarning(lcTlPlugin) << "Plugin does not implement PluginInterface."; + } + + qCDebug(lcTlPlugin) << "Loaded plugin: " << plugin->name() + << ", enabled: " << plugin->enabled() + << ", metadata: " << loader.metaData(); + // TODO: use scheduler to run + plugin->initialize(q); + plugins.push_back(plugin); + + const QString scope{ + loader.metaData().value("MetaData").toObject().value("translate").toString() + }; + qCDebug(lcTlPlugin) << "Plugin translate scope:" << scope; + +#ifndef DISABLE_DDM + connect(server->qmlEngine()->singletonInstance("Treeland", "UserModel"), + &UserModel::currentUserNameChanged, + pluginInstance, + [this, plugin, scope] { + updatePluginTs(plugin, scope); + }); + + updatePluginTs(plugin, scope); +#endif + + if (auto *multitaskview = qobject_cast(pluginInstance)) { + qCDebug(lcTlPlugin) << "Get MultitaskView Instance."; + connect(pluginInstance, &QObject::destroyed, this, [this] { + server->setMultitaskViewFactory(nullptr); + }); + server->setMultitaskViewFactory(multitaskview); + } + +#if !defined(DISABLE_DDM) || defined(EXT_SESSION_LOCK_V1) + if (auto *lockscreen = qobject_cast(pluginInstance)) { + qCDebug(lcTlPlugin) << "Get LockScreen Instance."; + connect(pluginInstance, &QObject::destroyed, this, [this] { + server->setLockScreenImpl(nullptr); + }); + server->setLockScreenImpl(lockscreen); + } +#endif + } + } + +private: + Treeland *q_ptr; +#ifndef DISABLE_DDM + Dtk::Accounts::DAccountsManager manager; + QLocalSocket *socket{ nullptr }; +#endif + QTranslator *lastTrans{ nullptr }; + QmlEngine *qmlEngine{ nullptr }; + std::vector plugins; + QLocalSocket *helperSocket{ nullptr }; + WaylandServer *server{ nullptr }; + QMap> userDisplayFds; + ScriptRunner *m_scriptRunner{ nullptr }; + std::vector shortcuts; + std::map pluginTs; +}; + + +class Compositor1Adaptor: public QDBusAbstractAdaptor +{ + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "org.deepin.Compositor1") + Q_CLASSINFO("D-Bus Introspection", + " \n" + " \n" + " \n" + " \n" + " \n" +#ifndef DISABLE_XWAYLAND + " \n" + " \n" + " \n" + " \n" +#endif + " \n" + " \n" + " \n" + "") +public: + Compositor1Adaptor(Treeland *parent) + : QDBusAbstractAdaptor(parent) + { + setAutoRelaySignals(true); + } + + inline Treeland *parent() const + { return static_cast(QObject::parent()); } + +public Q_SLOTS: // METHODS + + bool ActivateWayland(const QDBusUnixFileDescriptor &fd) + { + return parent()->ActivateWayland(fd); + } + +#ifndef DISABLE_XWAYLAND + void XWaylandName() + { + parent()->XWaylandName(); + } +#endif + +Q_SIGNALS: // SIGNALS + void SessionChanged(); + void XWaylandAuthChanged(); +}; + +Treeland::Treeland() + : QObject() + , d_ptr(std::make_unique(this)) +{ + Q_D(Treeland); + + qmlRegisterModule("Treeland.Protocols", 1, 0); + + d->init([this] { initialize(); }); +} + +#ifndef DISABLE_DDM +void Treeland::onLoginStateQueried(bool hasLoggedInUser) +{ + if (hasLoggedInUser) { + continueStartup(); + } else { + runPrestartScripts(); + } +} +#endif + +void Treeland::initialize() +{ + Q_D(Treeland); + + auto globalSession = d->server->sessionManager()->globalSession(); + Q_ASSERT(globalSession); + + if (CmdLine::ref().run().has_value()) { + auto exec = [runCmd = CmdLine::ref().run().value(), d, globalSession] { + qCInfo(lcTlDBus) << "run cmd:" << runCmd; + if (auto cmdline = CmdLine::ref().unescapeExecArgs(runCmd); cmdline) { + auto cmdArgs = cmdline.value(); + + auto envs = QProcessEnvironment::systemEnvironment(); + envs.insert("WAYLAND_DISPLAY", + globalSession->socket()->fullServerName()); +#ifndef DISABLE_XWAYLAND + if (auto currentUserSession = d->server->sessionManager()->sessionForUid(getuid())) { + if (auto *xwayland = currentUserSession->xwayland()) + envs.insert("DISPLAY", xwayland->displayName()); + } else if (auto *current = globalSession->xwayland()) { + envs.insert("DISPLAY", current->displayName()); + } +#endif + envs.insert("XDG_SESSION_DESKTOP", "Treeland"); + + QProcess process; + process.setProgram(cmdArgs.constFirst()); + process.setArguments(cmdArgs.mid(1)); + process.setProcessEnvironment(envs); + process.setStandardInputFile(QProcess::nullDevice()); + process.setStandardOutputFile(QProcess::nullDevice()); + process.setStandardErrorFile(QProcess::nullDevice()); + process.startDetached(); + } + }; + auto con = + connect(d->server->sessionManager(), &SessionManager::socketFileChanged, this, exec, Qt::SingleShotConnection); + + WSocket *defaultSocket = globalSession->socket(); + if (defaultSocket && defaultSocket->isValid()) { + QObject::disconnect(con); + exec(); + } + } + + new Compositor1Adaptor(this); + + // init dbus after QML engine loaded. + QDBusConnection::systemBus().registerService("org.deepin.Compositor1"); + QDBusConnection::systemBus().registerObject("/org/deepin/Compositor1", this); + + QDBusConnection::sessionBus().registerService("org.deepin.Compositor1"); + QDBusConnection::sessionBus().registerObject("/org/deepin/Compositor1", this); +#ifndef DISABLE_DDM + auto *query = new LoginStateQuery(this); + connect(query, &LoginStateQuery::finished, this, &Treeland::onLoginStateQueried); + connect(query, &LoginStateQuery::finished, query, &QObject::deleteLater); + query->start(); +#else + runPrestartScripts(); +#endif +} + +void Treeland::runPrestartScripts() +{ + Q_D(Treeland); + auto globalSession = d->server->sessionManager()->globalSession(); + + auto *runner = new ScriptRunner(globalSession->socket()->fullServerName(), d); + d->m_scriptRunner = runner; + connect(runner, &ScriptRunner::blockingFinished, + this, &Treeland::continueStartup); + connect(runner, &ScriptRunner::blockingFinished, + runner, &ScriptRunner::startNonBlocking); + + const auto dataDirs = QStandardPaths::standardLocations(QStandardPaths::AppDataLocation); + for (const auto &dataDir : dataDirs) { + runner->append(QDir(dataDir).filePath(QStringLiteral("prestart.d/blocking")), ScriptRunner::Blocking); + runner->append(QDir(dataDir).filePath(QStringLiteral("prestart.d/non-blocking")), ScriptRunner::NonBlocking); + } + + runner->start(); +} + +void Treeland::continueStartup() +{ + Q_D(Treeland); + + QDir dir(QStringLiteral(TREELAND_PLUGINS_OUTPUT_PATH)); + if (dir.exists() && dir.isReadable()) { + d->loadPlugin(QStringLiteral(TREELAND_PLUGINS_OUTPUT_PATH)); + } else { + qCInfo(lcTlPlugin) << "The Treeland plugin build directory is inaccessible, " + "falling back to the installation directory"; + d->loadPlugin(QStringLiteral(TREELAND_PLUGINS_INSTALL_PATH)); + } +#ifndef DISABLE_DDM + auto *greeter = d->qmlEngine->singletonInstance("Treeland", "GreeterProxy"); + greeter->enableHandshake(); +#else + d->server->initializeWallpaper(); +#endif +} + +Treeland::~Treeland() +{ + +} + +bool Treeland::debugMode() const +{ +#ifdef QT_DEBUG + return true; +#endif + + return qEnvironmentVariableIsSet("TREELAND_ENABLE_DEBUG"); +} + +QmlEngine *Treeland::qmlEngine() const +{ + Q_D(const Treeland); + + return d->qmlEngine; +} + +Workspace *Treeland::workspace() const +{ + Q_D(const Treeland); + + return d->server->workspace(); +} + +RootSurfaceContainer *Treeland::rootSurfaceContainer() const +{ + Q_D(const Treeland); + + return d->server->rootSurfaceContainer(); +} + +bool Treeland::ActivateWayland(QDBusUnixFileDescriptor _fd) +{ + Q_D(Treeland); + + if (!_fd.isValid()) { + return false; + } + + auto fd = std::make_shared(); + fd->swap(_fd); + + auto uid = connection().interface()->serviceUid(message().service()); + auto session = d->server->sessionManager()->sessionForUid(uid); + + WSocket *sessionSocket = session ? session->socket() : nullptr; + if (!sessionSocket) + return false; + auto userModel = + d->server->qmlEngine()->singletonInstance("Treeland", "UserModel"); + const QString user = session->username(); + auto u = userModel->getUser(user); + if (!u) + return false; + + struct stat incomingStat {}; + if (fstat(fd->fileDescriptor(), &incomingStat) < 0) + return false; + + // SessionChanged makes treeland-sd submit the same listening socket again. + // Keep its WSocket and clients alive instead of replacing the connection owner. + if (auto existing = u->waylandSocket(); existing && existing->parentSocket() == sessionSocket) { + struct stat existingStat {}; + if (fstat(existing->socketFd(), &existingStat) == 0 + && existingStat.st_dev == incomingStat.st_dev + && existingStat.st_ino == incomingStat.st_ino) { + return true; + } + } + + // WSocket::create owns its fd; do not share ownership with the DBus wrapper. + const int socketFd = fcntl(fd->fileDescriptor(), F_DUPFD_CLOEXEC, 0); + if (socketFd < 0) + return false; + std::shared_ptr socket = std::make_shared(sessionSocket); + + if (!socket->create(socketFd, false)) { + ::close(socketFd); + return false; + } + + u->setWaylandSocket(socket); + + socket->setEnabled(userModel->currentUserName() == user, + WaylandServer::instance()->sessionManager()->globalSession()->socket()); + + d->server->addSocket(socket.get()); + + d->userDisplayFds[user] = fd; + + // Only the connection that supplied this socket may trigger its cleanup. + auto *watcher = new QDBusServiceWatcher(message().service(), connection(), + QDBusServiceWatcher::WatchForUnregistration, + socket.get()); + connect(watcher, &QDBusServiceWatcher::serviceUnregistered, socket.get(), + [user, userModel, d] { + d->userDisplayFds.remove(user); + if (auto u = userModel->getUser(user)) + u->setWaylandSocket(nullptr); + }); + + return true; +} + +#ifndef DISABLE_XWAYLAND +void Treeland::XWaylandName() +{ + Q_D(Treeland); + + setDelayedReply(true); + + auto m = message(); + auto conn = connection(); + + auto uid = connection().interface()->serviceUid(message().service()); + auto session = d->server->sessionManager()->sessionForUid(uid); + auto *xwayland = session ? session->xwayland() : nullptr; + if (!xwayland) { + auto reply = m.createErrorReply(QDBusError::InternalError, + "Failed to prepare XWayland session"); + conn.send(reply); + return; + } + const QString &display = xwayland->displayName(); + + QFile authFile(QStringLiteral("/tmp/.xauth_%1").arg(display)); + if (!authFile.open(QIODevice::ReadOnly)) { + conn.send(m.createErrorReply(QDBusError::InternalError, "Failed to open xauth file")); + return; + } + + QVariantList result; + result << QVariant(display) << QVariant(authFile.readAll()); + conn.send(m.createReply(result)); + return; +} +#endif + +void Treeland::quit() +{ + // make sure all deleted before app exit + d_ptr.reset(); + qApp->quit(); + // TODO: release drm master and return tty to text mode +} + +} // namespace Treeland + +#include "treeland.moc" diff --git a/src/core/treeland.h b/src/core/treeland.h new file mode 100644 index 0000000000..cd8195ffa8 --- /dev/null +++ b/src/core/treeland.h @@ -0,0 +1,66 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "interfaces/proxyinterface.h" + +#include +#include + +#include +#include +#include + +#include + +class QmlEngine; +class QLocalSocket; +class WaylandServer; +class PluginInterface; + +namespace Treeland { + +class TreelandPrivate; + +class Treeland + : public QObject + , protected QDBusContext + , TreelandProxyInterface +{ + Q_OBJECT + Q_DECLARE_PRIVATE(Treeland) + +public: + explicit Treeland(); + ~Treeland(); + + bool debugMode() const; + + QmlEngine *qmlEngine() const override; + Workspace *workspace() const override; + RootSurfaceContainer *rootSurfaceContainer() const override; + +Q_SIGNALS: + void socketDisconnected(); + void SessionChanged(); + void XWaylandAuthChanged(); + +public Q_SLOTS: + bool ActivateWayland(QDBusUnixFileDescriptor fd); +#ifndef DISABLE_XWAYLAND + void XWaylandName(); +#endif + +private: + void initialize(); + void runPrestartScripts(); + void continueStartup(); + void quit(); +#ifndef DISABLE_DDM + void onLoginStateQueried(bool hasLoggedInUser); +#endif + + std::unique_ptr d_ptr; +}; +} // namespace Treeland diff --git a/src/core/treelandinit.cpp b/src/core/treelandinit.cpp new file mode 100644 index 0000000000..13647f0ed9 --- /dev/null +++ b/src/core/treelandinit.cpp @@ -0,0 +1,76 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treelandinit.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#if QT_VERSION >= QT_VERSION_CHECK(6, 10, 0) +# include +#else +# include +#endif + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE +DCORE_USE_NAMESPACE + +namespace Treeland { + +namespace { +class QDeepinTheme : public QGenericUnixTheme +{ +public: + const QPalette *palette(QPlatformTheme::Palette type) const override + { + if (type != QPlatformTheme::SystemPalette) + return QGenericUnixTheme::palette(type); + static QPalette palette; + palette = Dtk::Gui::DGuiApplicationHelper::instance()->applicationPalette(); + return &palette; + } +}; +} + +std::unique_ptr preInit(int &argc, char *argv[]) +{ + WLog::init(); + DTK_GUI_NAMESPACE::DGuiApplicationHelper::setAttribute( + DTK_GUI_NAMESPACE::DGuiApplicationHelper::DontSaveApplicationTheme, true); + WServer::initializeQPA({}, [](const QString &) { + return static_cast(new QDeepinTheme()); + }); + QGuiApplication::setAttribute(Qt::AA_UseOpenGLES); + QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); + QGuiApplication::setQuitOnLastWindowClosed(false); + QQuickStyle::setStyle("Chameleon"); + + auto application = std::make_unique(argc, argv); + application->setOrganizationName("deepin"); + application->setApplicationName("treeland"); + return application; +} + +void initTestServer(WServer *server) +{ + auto *backend = server->attach(); + auto *renderer = WRenderHelper::createRenderer(backend->handle()); + wlr_compositor_create(server->handle(), 6, renderer); + wlr_subcompositor_create(server->handle()); +} + +void postInit() +{ + WRenderHelper::setupRendererBackend(); +} + +} diff --git a/src/core/treelandinit.h b/src/core/treelandinit.h new file mode 100644 index 0000000000..a6a31e6a3d --- /dev/null +++ b/src/core/treelandinit.h @@ -0,0 +1,19 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once +#include + +#include + +class QGuiApplication; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WServer; +WAYLIB_SERVER_END_NAMESPACE + +namespace Treeland { +std::unique_ptr preInit(int &argc, char *argv[]); +void postInit(); +void initTestServer(WAYLIB_SERVER_NAMESPACE::WServer *server); +} diff --git a/src/core/waylandserver.cpp b/src/core/waylandserver.cpp new file mode 100644 index 0000000000..6788f2d5ec --- /dev/null +++ b/src/core/waylandserver.cpp @@ -0,0 +1,1405 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "waylandserver.h" +#include "session/sessionmanager.h" +#include "session/sessionmultitaskview.h" +#include "lockscreen/lockscreenmanager.h" +#include "showdesktop/showdesktop.h" +#include "surfaceprotocolcontroller.h" +#include "focuscontroller.h" +#include "input/compositorinputfilter.h" +#include "input/gesturemanager.h" +#include "session/sessioninputchannel.h" +#include "session/sessioninputcontext.h" +#include "idle/idlemanager.h" +#include "capture/capturemanager.h" +#include "seat/dragcontroller.h" +#include "pointerconstraintsmanager.h" +#include "seatmanager.h" +#include "common/treelandlogging.h" +#include "common/shellaction.h" +#include "core/qmlengine.h" +#include "core/rootsurfacecontainer.h" +#include "core/shellhandler.h" +#include "dconfig/dconfigmanager.h" +#include "core/treeland.h" +#include "greeter/greeterproxy.h" +#include "greeter/sessionmodel.h" +#include "greeter/usermodel.h" +#include "inputmanager.h" +#include "interfaces/multitaskviewinterface.h" +#include "modules/capture/capture.h" +#include "modules/dde-shell/ddeshellattached.h" +#include "modules/dde-shell/ddeshellmanagerinterfacev1.h" +#include "modules/dde-shell/ddeshellmanagerinterfacev2.h" +#include "modules/ddm/ddminterfacev1.h" +#include "modules/input-manager/inputmanagerinterfacev1.h" +#include "modules/keyboard-shortcuts-inhibit/keyboardshortcutsinhibitmanager.h" +#include "modules/keyboard-state-notify/keyboardstatenotifymanagerinterfacev1.h" +#include "modules/active-notify/activenotifymanagerinterfacev1.h" +#include "modules/output-manager/outputmanagement.h" +#include "modules/output-uuid/outputuuidmanagerinterfacev1.h" +#include "modules/personalization/personalizationmanagerinterfacev1.h" +#include "modules/appearance/appearanceinterfacev1.h" +#include "modules/appearance/appearancemanagerinterfacev1.h" +#include "modules/compositor-action/compositoractioninterfacev1.h" +#include "modules/resource/treelandremotesource.h" +#include "modules/screensaver/screensaverinterfacev2.h" +#include "modules/shortcut/shortcutcontroller.h" +#include "modules/shortcut/shortcutmanager.h" +#include "modules/shortcut/shortcutrunner.h" +#include "modules/wallpaper-color/wallpapercolorinterfacev1.h" +#include "modules/output-group/outputgroupmanagerinterfacev1.h" +#include "output/output.h" +#include "output/outputmanager.h" +#include "seatuserconfig.hpp" +#include "session/session.h" +#include "session/sessionoutputmanager.h" +#include "session/sessionswitcher.h" +#include "surface/surfacecontainer.h" +#include "surface/surfacewrapper.h" +#include "treelandconfig.hpp" +#include "treelanduserconfig.hpp" +#include "animationconfig.hpp" +#include "utils/fpsdisplaymanager.h" +#include "utils/graphicsplatform.h" +#include "wallpaper/wallpapermanager.h" +#include "wallpapershellinterfacev1.h" +#include "workspace/workspace.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef DISABLE_XWAYLAND +#include +#include +#endif + +#include + +#include +#include +#include +#include + +#include +#include + +#define WLR_FRACTIONAL_SCALE_V1_VERSION 1 +#define EXT_BACKGROUND_EFFECT_MANAGER_V1_VERSION 1 + +WaylandServer *WaylandServer::m_instance = nullptr; + +WaylandServer::WaylandServer(QObject *parent) + : QObject(parent) + , WObject() + , m_sessionManager(new SessionManager(this)) + , m_renderWindow(new WOutputRenderWindow(this)) + , m_server(new WServer(this)) + , m_rootSurfaceContainer(new RootSurfaceContainer(m_renderWindow->contentItem())) +{ + m_idleManager = new IdleManager(this); + m_captureManager = new CaptureManager(m_server, m_rootSurfaceContainer, this); + m_isDDMDisplay = qEnvironmentVariableIsSet("DDM_DISPLAY_MANAGER"); + Q_ASSERT(!m_instance); + m_instance = this; + + if (auto *configManager = DConfigManager::instance()) { + m_config = configManager->initialUserConfig(); + setAnimationConfig(configManager->initialAnimationConfig()); + m_globalConfig = configManager->globalConfig(); + } + + Q_ASSERT(m_config); + Q_ASSERT(m_globalConfig); + + m_renderWindow->setColor(Qt::black); + m_rootSurfaceContainer->setFlag(QQuickItem::ItemIsFocusScope, true); + m_rootSurfaceContainer->setFocusPolicy(Qt::StrongFocus); + + m_shellHandler = new ShellHandler(m_rootSurfaceContainer, server()); + m_focusController = new FocusController(this); + connect(m_sessionManager, &SessionManager::sessionChanged, this, &WaylandServer::activeSessionChanged); + connect(m_sessionManager, &SessionManager::sessionChanged, this, &WaylandServer::desktopChanged); + connect(m_sessionManager, &SessionManager::sessionChanged, this, &WaylandServer::applyActiveSessionConfig); + connect(DConfigManager::instance(), &DConfigManager::configReady, + this, &WaylandServer::applyCurrentUserConfig); + m_lockScreenManager = new LockScreenManager(this); + connect(m_lockScreenManager, &LockScreenManager::lockScreenAvailableChanged, + this, &WaylandServer::lockScreenAvailableChanged); + m_surfaceProtocols = new SurfaceProtocolController(this); + connect(m_shellHandler, &ShellHandler::workspaceChanged, this, &WaylandServer::onWorkspaceChanged); + connect(m_shellHandler, &ShellHandler::workspaceAdded, this, &WaylandServer::workspaceAdded); + // Follow the remoteDebug master switch (off by default in release builds, + // always on in debug builds -- see misc/dconfig/org.deepin.dde.treeland.json), + // so the debug socket appears and disappears with it instead of only at + // startup. The stored value arrives asynchronously -- dtk reports + // configInitializeSucceed later -- so watch for changes first and only then + // read the value: reading it now would publish the socket for a user who + // stored `false`, until the value arrives. + connect(m_globalConfig, + &TreelandConfig::remoteDebugChanged, + this, + &WaylandServer::tryInitRemoteSource); + if (DConfigManager::instance()->isInitializeSucceeded()) + tryInitRemoteSource(); + else + connect(DConfigManager::instance(), + &DConfigManager::initializeSucceed, + this, + &WaylandServer::tryInitRemoteSource); + + m_outputManager = new OutputManager(m_rootSurfaceContainer, + m_globalConfig, + m_renderWindow, + this); + connect(m_outputManager, &OutputManager::modeChanged, this, &WaylandServer::outputModeChanged); + m_showDesktop = new ShowDesktop(this, m_outputManager); + connect(m_showDesktop, &ShowDesktop::stateChanged, + this, &WaylandServer::showDesktopStateChanged); + m_bootstrapInputFilter = new CompositorInputFilter( + new SessionInputContext(nullptr, this, this), this, m_idleManager, m_captureManager, m_outputManager); + connect(m_bootstrapInputFilter, &CompositorInputFilter::modifierKeyReleased, + this, &WaylandServer::modifierKeyReleased); + + m_workspaceScaleAnimation = new QPropertyAnimation(m_shellHandler->workspace(), "scale", this); + m_workspaceOpacityAnimation = + new QPropertyAnimation(m_shellHandler->workspace(), "opacity", this); + + m_workspaceScaleAnimation->setDuration(1000); + m_workspaceOpacityAnimation->setDuration(1000); + m_workspaceScaleAnimation->setEasingCurve(QEasingCurve::OutExpo); + m_workspaceOpacityAnimation->setEasingCurve(QEasingCurve::OutExpo); + + connect(m_renderWindow, + &QQuickWindow::activeFocusItemChanged, + this, + &WaylandServer::onRenderWindowActiveFocusItemChanged); +} + +WaylandServer::~WaylandServer() +{ + Q_ASSERT(m_instance == this); + teardown(); + + m_captureManager->teardown(); + m_idleManager->teardown(); + m_instance = nullptr; + if (m_renderWindow) { + m_renderWindow->disconnect(); + } + + if (backend()) { + backend()->disconnect(); + } + + // destroy before m_rootSurfaceContainer + delete m_shellHandler; + if (m_rootSurfaceContainer) { + for (auto s : std::as_const(m_rootSurfaceContainer->surfaces())) { + if (auto c = s->container()) + c->removeSurface(s); + } + delete m_rootSurfaceContainer; + m_rootSurfaceContainer = nullptr; + } + if (auto *configManager = DConfigManager::instance()) + configManager->stopActiveUserConfig(); + delete m_lockScreenManager; + delete m_surfaceProtocols; + delete m_dragController; + delete m_captureManager; + delete m_idleManager; +} + +WaylandServer *WaylandServer::instance() +{ + return m_instance; +} + +AnimationConfig *WaylandServer::animationConfig() const +{ + return m_animationConfig; +} + +void WaylandServer::setAnimationConfig(AnimationConfig *config) +{ + if (m_animationConfig == config) + return; + + if (m_animationConfig) + disconnect(m_animationConfig, nullptr, this, nullptr); + m_animationConfig = config; + if (config) { + connect(config, &AnimationConfig::configInitializeSucceed, + this, &WaylandServer::animationConfigChanged); + connect(config, &AnimationConfig::configInitializeFailed, + this, &WaylandServer::animationConfigChanged); + } + Q_EMIT animationConfigChanged(); +} + +TreelandUserConfig *WaylandServer::config() +{ + return m_config; +} + +TreelandConfig *WaylandServer::globalConfig() +{ + return m_globalConfig; +} + +void WaylandServer::syncPaletteTypeWithWindowColorScheme(int32_t colorScheme) +{ + auto *guiHelper = DTK_GUI_NAMESPACE::DGuiApplicationHelper::instance(); + if (!guiHelper) { + qCCritical(lcTlConfig) << "DGuiApplicationHelper instance not available, cannot sync " + "palette type with window color scheme."; + return; + } + + qCDebug(lcTlConfig) << "Syncing palette type with window color scheme:" << colorScheme; + + switch (colorScheme) { + case 1: + guiHelper->setPaletteType(Dtk::Gui::DGuiApplicationHelper::DarkType); + break; + case 0: + guiHelper->setPaletteType(Dtk::Gui::DGuiApplicationHelper::LightType); + break; + default: + qCWarning(lcTlConfig) << "Unknown windowColorScheme:" << colorScheme + << ", fallback to light."; + guiHelper->setPaletteType(Dtk::Gui::DGuiApplicationHelper::LightType); + break; + } +} + +void WaylandServer::tryInitRemoteSource() +{ + // remoteDebug is a master switch -- off by default in release builds, so + // nothing is exposed until someone asks for it, and on means "serve + // debuggers". Toggling it creates or destroys the remote source without + // restarting the server. The source itself is a thin QObject that only does + // work per call, so keeping it while the switch is on costs nothing when no + // client is attached. + // + // A debug build never looks at the switch: that instance is the thing being + // developed, so waiting for a per-user key to be flipped there only costs + // time (and a stale `false` left by an earlier session looks like "debug is + // broken"). Its socket is the `-dev` one, so this cannot open a release + // instance's channel. +#ifdef TREELAND_DEBUG_DEV_BUILD + const bool remoteDebug = true; +#else + const bool remoteDebug = m_globalConfig->remoteDebug(); +#endif + if (m_treelandRemoteSource) { + if (!remoteDebug) { + delete m_treelandRemoteSource; + m_treelandRemoteSource = nullptr; + } + } else if (remoteDebug) { + auto *source = new TreelandRemoteSource(this); + // Binding or publishing can fail while the switch stays on; keep it + // retryable rather than caching an object that never published. + if (!source->isPublished()) { + delete source; + return; + } + m_treelandRemoteSource = source; + } +} + +void WaylandServer::setWorkspaceVisible(bool visible) +{ + for (auto *surface : std::as_const(m_rootSurfaceContainer->surfaces())) { + if (surface->type() == SurfaceWrapper::Type::Layer) { + surface->setHideByLockScreen(m_currentMode == CurrentMode::LockScreen); + } + } + + // Client workspace visibility is immediate; wallpaper rendering is separate. + m_workspaceScaleAnimation->stop(); + m_workspaceOpacityAnimation->stop(); + m_shellHandler->workspace()->setScale(1.0); + m_shellHandler->workspace()->setOpacity(visible ? 1.0 : 0.0); +} + +QmlEngine *WaylandServer::qmlEngine() const +{ + return qobject_cast(::qmlEngine(this)); +} + +WOutputRenderWindow *WaylandServer::window() const +{ + return m_renderWindow; +} + +GraphicsPlatform *WaylandServer::graphicsPlatform() const +{ + return m_graphicsPlatform.get(); +} + +SessionManager *WaylandServer::sessionManager() const +{ + return m_sessionManager; +} + +ShellHandler *WaylandServer::shellHandler() const +{ + return m_shellHandler; +} + +void WaylandServer::initializeSessionProtocols(Session *session) +{ + m_surfaceProtocols->initializeSession(session); + session->desktop()->attachWindowManagement(session->windowManagement()); + m_focusController->registerSession(session); + connect(session, &Session::activeChanged, this, [this, session](bool active) { + disconnect(session->wallpaperManager(), &WallpaperManager::updateWallpaper, + this, &WaylandServer::wallpaperChanged); + if (active) { + connect(session->wallpaperManager(), &WallpaperManager::updateWallpaper, + this, &WaylandServer::wallpaperChanged); + Q_EMIT wallpaperChanged(); + } + }); +} + +TreelandWallpaperNotifierInterfaceV1 *WaylandServer::wallpaperNotifier() const +{ + return m_wallpaperNotifierInterfaceV1; +} + +OutputManager *WaylandServer::outputHardware() const +{ + return m_outputManager; +} + +WallpaperManager *WaylandServer::wallpaperManager() const +{ + return activeSession() ? activeSession()->wallpaperManager() : nullptr; +} + +void WaylandServer::onWallpaperNotifierBound(wl_resource *resource) +{ + // The wallpaper factory is a shared, privileged resource consumer. + for (const auto &session : m_sessionManager->sessions()) + session->wallpaperManager()->onWallpaperNotifierBound(resource); +} + +void WaylandServer::onWallpaperSurfaceAdded(TreelandWallpaperSurfaceInterfaceV1 *surface) +{ + if (auto *manager = wallpaperManager()) + manager->handleWallpaperSurfaceAdded(surface); +} + +Session *WaylandServer::activeSession() const +{ + return m_sessionManager->activeSessionObject(); +} + +Workspace *WaylandServer::workspace() const +{ + return m_shellHandler->workspace(); +} + +bool WaylandServer::surfaceBelongsToCurrentSession(SurfaceWrapper *wrapper) +{ + if (wrapper->session()) + return m_sessionManager->isActiveWindow(wrapper); + if (wrapper->type() == SurfaceWrapper::Type::SplashScreen) + return false; + WClient *client = wrapper->surface()->waylandClient(); + WSocket *socket = client ? client->socket()->rootSocket() : nullptr; + return socket && socket->isEnabled(); +} + +void WaylandServer::onWorkspaceChanged() +{ + if (auto *view = multitaskView()) + view->immediatelyExit(); + if (m_currentMode == CurrentMode::Multitaskview) + setCurrentMode(CurrentMode::Normal); + deleteTaskSwitch(); + m_workspaceScaleAnimation->stop(); + m_workspaceOpacityAnimation->stop(); + if (m_currentMode != CurrentMode::LockScreen) { + workspace()->setOpacity(1.0); + workspace()->setScale(1.0); + } + m_workspaceScaleAnimation->setTargetObject(workspace()); + m_workspaceOpacityAnimation->setTargetObject(workspace()); + Q_EMIT workspaceChanged(); +} + +QQuickItem *WaylandServer::taskSwitcher() const +{ + return activeSession() ? activeSession()->switcher()->taskSwitcher() : nullptr; +} + +void WaylandServer::setOutputScale(WOutput *output, qreal scale) +{ + if (auto *owner = activeSession()) + owner->outputManager()->setScale(output, scale); +} + +void WaylandServer::ensureTaskSwitcher() +{ + auto *output = m_rootSurfaceContainer->cursorOutput(); + if (!output) + output = m_rootSurfaceContainer->primaryOutput(); + activeSession()->switcher()->ensureTaskSwitcher(output); +} + +void WaylandServer::deleteTaskSwitch() +{ + if (auto *session = activeSession()) + session->switcher()->close(); + if (m_currentMode == CurrentMode::WindowSwitch) { + setCurrentMode(CurrentMode::Normal); + } +} + +void WaylandServer::initializeWallpaper() +{ + if (m_wallpaperInitialized) { + return; + } + + m_wallpaperInitialized = true; +#ifndef DISABLE_DDM + const QString userName = m_userModel->currentUserName(); + if (!userName.isEmpty() + && DConfigManager::instance()->userConfig(userName) != m_config) { + // LastLogin selected another user whose configuration is still loading. + // applyCurrentUserConfig() will update the wallpaper once it is ready. + return; + } +#endif + if (auto *manager = wallpaperManager()) + manager->loadWallpaperConfig(); +} + +void WaylandServer::applyActiveSessionConfig() +{ + auto *session = activeSession(); + if (!session || !session->config()->isInitializeSucceeded()) + return; + auto *seatConfig = DConfigManager::instance()->userSeatConfig(session->username(), seat()->name()); + applyCurrentUserConfig(session->username(), session->config(), + seatConfig->isInitializeSucceeded() ? seatConfig : nullptr); +} + +void WaylandServer::applyCurrentUserConfig(const QString &userName, + TreelandUserConfig *config, + SeatUserDConfig *seatConfig) +{ + // DConfig can be ready before installRuntimeProtocols() creates the initial + // session. sessionChanged will apply its configuration once it exists. + auto *session = activeSession(); + if (!session || !config || m_userModel->currentUserName() != userName + || session->username() != userName) { + return; + } + + if (auto *manager = DConfigManager::instance()) + setAnimationConfig(manager->animationConfig(userName)); + + const bool configPointerChanged = config != m_config; + if (configPointerChanged) { + if (m_config) { + disconnect(m_config, + &TreelandUserConfig::cursorThemeNameChanged, + m_sessionManager, + &SessionManager::syncActiveSessionXSettings); + disconnect(m_config, + &TreelandUserConfig::cursorSizeChanged, + m_sessionManager, + &SessionManager::syncActiveSessionXSettings); + disconnect(m_config, + &TreelandUserConfig::x11GtkIMModuleChanged, + m_sessionManager, + &SessionManager::syncActiveSessionXSettings); + } + m_config = config; + Q_EMIT configChanged(); + } + + connect(m_config, + &TreelandUserConfig::cursorThemeNameChanged, + m_sessionManager, + &SessionManager::syncActiveSessionXSettings, + Qt::UniqueConnection); + connect(m_config, + &TreelandUserConfig::cursorSizeChanged, + m_sessionManager, + &SessionManager::syncActiveSessionXSettings, + Qt::UniqueConnection); + connect(m_config, + &TreelandUserConfig::x11GtkIMModuleChanged, + m_sessionManager, + &SessionManager::syncActiveSessionXSettings, + Qt::UniqueConnection); + + if (m_wallpaperInitialized) { + wallpaperManager()->loadWallpaperConfig(); + } + if (userName == "dde") { + return; + } + + if (seatConfig) { + session->inputManager()->refresh(); + } + m_sessionManager->syncActiveSessionXSettings(); + syncPaletteTypeWithWindowColorScheme(m_config->windowColorScheme()); + tryInitRemoteSource(); + session->workspace()->reloadFromConfig(); +} + +void WaylandServer::createBackend() +{ + m_backend = m_server->attach(); +} + +void WaylandServer::startDisplay() +{ + m_server->start(); +} + +void WaylandServer::initializeRendering() +{ + m_renderer.reset(WRenderHelper::createRenderer(m_backend->handle())); + if (!m_renderer) { + qCFatal(lcTlCore) << "Failed to create renderer"; + } + + m_allocator.reset(wlr_allocator_autocreate(m_backend->handle(), m_renderer.get())); + if (!m_allocator) { + qCFatal(lcTlCore) << "Failed to create allocator"; + } + + if (!wlr_renderer_init_wl_display(m_renderer.get(), m_server->handle())) { + qCFatal(lcTlCore) << "Failed to initialize renderer wl_display"; + } + + if (!wlr_drm_create(m_server->handle(), m_renderer.get())) { + qCCritical(lcTlCore) << "Failed to create DRM lease manager"; + } + + m_compositor = wlr_compositor_create(m_server->handle(), 6, m_renderer.get()); + if (!m_compositor) { + qCFatal(lcTlCore) << "Failed to create server"; + } + + if (!wlr_subcompositor_create(m_server->handle())) { + qCCritical(lcTlCore) << "Failed to create subcompositor"; + } +} + +void WaylandServer::initializeRenderWindow() +{ + m_renderWindow->init(m_renderer.get(), m_allocator.get()); + + // The QRhi only exists once the render window is initialized, so detect the + // GPU here once and share the result instead of probing it at every use site. + m_graphicsPlatform = std::make_unique(m_renderWindow->rhi()); + qCInfo(lcTlCore) << "Graphics platform:" << m_graphicsPlatform->toString(); +} + +void WaylandServer::installPointerProtocols() +{ + m_server->attach(); + m_server->attach(); +} + +void WaylandServer::installCommonProtocols() +{ + if (!wlr_viewporter_create(m_server->handle())) { + qCCritical(lcTlCore) << "Failed to create viewporter"; + } + + if (!wlr_single_pixel_buffer_manager_v1_create(m_server->handle())) { + qCCritical(lcTlCore) << "Failed to create single pixel buffer manager"; + } + + wlr_fractional_scale_manager_v1_create(m_server->handle(), WLR_FRACTIONAL_SCALE_V1_VERSION); + if (!wlr_ext_background_effect_manager_v1_create(m_server->handle(), + EXT_BACKGROUND_EFFECT_MANAGER_V1_VERSION, + EXT_BACKGROUND_EFFECT_MANAGER_V1_CAPABILITY_BLUR)) { + qCWarning(lcTlCore) << "Failed to create ext-background-effect-manager-v1, blur will be unavailable"; + } + wlr_alpha_modifier_v1_create(m_server->handle()); +} + +void WaylandServer::startBackend() +{ + wlr_backend_start(m_backend->handle()); +} + +void WaylandServer::init(Treeland::Treeland *treeland) +{ + m_treeland = treeland; + connect(m_sessionManager, &SessionManager::sessionChanged, treeland, &Treeland::Treeland::SessionChanged); + connect(m_sessionManager, + &SessionManager::xwaylandAuthChanged, + treeland, + &Treeland::Treeland::XWaylandAuthChanged); + + auto engine = qmlEngine(); +#ifndef DISABLE_DDM + m_greeterProxy = engine->singletonInstance("Treeland", "GreeterProxy"); + connect(m_greeterProxy, &GreeterProxy::initialUserSelected, + this, &WaylandServer::initializeWallpaper); + m_lockScreenManager->setGreeterProxy(m_greeterProxy); + m_userModel = engine->singletonInstance("Treeland", "UserModel"); + m_sessionModel = engine->singletonInstance("Treeland", "SessionModel"); + // The lockscreen shows one user at a time; switching the shown user changes + // whether it is a locked session or the login screen. + connect(m_userModel, + &UserModel::currentUserNameChanged, + m_greeterProxy, + &GreeterProxy::syncHasActiveSession); +#endif + + engine->setContextForObject(m_renderWindow, engine->rootContext()); + engine->setContextForObject(m_renderWindow->contentItem(), engine->rootContext()); + m_rootSurfaceContainer->setQmlEngine(engine); + m_rootSurfaceContainer->init(server()); + + createBackend(); + m_seatManager = new SeatManager(server(), this); + m_dragController = new DragController(m_seatManager, this); + + auto *xdgOutputManager = installDesktopProtocols(engine); + + startDisplay(); + + if (!initializeSeatsAndShell()) + return; + + installRuntimeProtocols(xdgOutputManager); + + // start() synchronously reports the initially available outputs. Their + // per-output DConfig objects initialize asynchronously, so finish the scan + // only after every reported output has either loaded its config or failed + // initialization and fallen back to defaults. + startBackend(); + m_outputManager->backendStarted(); +} + +SeatManager *WaylandServer::seatManager() const +{ + return m_seatManager; +} + +WSeat *WaylandServer::getSeatForEvent(QInputEvent *event) const +{ + return m_seatManager->getSeatForEvent(event); +} + +RootSurfaceContainer *WaylandServer::rootSurfaceContainer() const +{ + return m_rootSurfaceContainer; +} + +WServer *WaylandServer::server() const +{ + return m_server; +} + +void WaylandServer::fakePressSurfaceBottomRightToReszie(SurfaceWrapper *surface) +{ + auto position = surface->geometry().bottomRight(); + m_fakelastPressedPosition = position; + seat()->setCursorPosition(position); + Q_EMIT surface->resizeRequested(Qt::BottomEdge | Qt::RightEdge, /*overrideCursor=*/true); +} + +void WaylandServer::setCursorPosition(const QPointF &position) +{ + const auto seats = m_seatManager->seats(); + for (auto *seat : seats) { + m_rootSurfaceContainer->endMoveResizeForSeat(seat); + } + seat()->setCursorPosition(position); +} + +void WaylandServer::handleCompositorAction(uint32_t action) +{ + const auto shellAction = CompositorActionInterfaceV1::mapCompositorAction(action); + if (!shellAction) { + // Mapped at the protocol boundary: unsupported and unknown actions are + // ignored (never fatal), per protocol. + qCDebug(lcTlProtocol) << "Ignoring unsupported server action:" << action; + return; + } + + ShellActionExecutor::execute(*shellAction); +} + +Output *WaylandServer::getOutput(WOutput *output) const +{ + return m_outputManager->outputFor(output); +} + +Output *WaylandServer::getOutputByUuid(const QString &uuid) const +{ + return m_outputManager->findOutputByUuid(uuid); +} + +const QList &WaylandServer::outputs() const +{ + return m_outputManager->outputs(); +} + +void WaylandServer::addOutput() +{ + m_outputManager->requestAdditionalOutputs(); +} + +void WaylandServer::setOutputMode(OutputMode mode) +{ + m_outputManager->applyMode( + mode == OutputMode::Copy ? OutputManager::Mode::Copy : OutputManager::Mode::Extension); +} + +float WaylandServer::animationSpeed() const +{ + return m_animationSpeed; +} + +void WaylandServer::setAnimationSpeed(float newAnimationSpeed) +{ + if (qFuzzyCompare(m_animationSpeed, newAnimationSpeed)) + return; + m_animationSpeed = newAnimationSpeed; + Q_EMIT animationSpeedChanged(); +} + +WaylandServer::OutputMode WaylandServer::outputMode() const +{ + return m_outputManager->mode() == OutputManager::Mode::Copy + ? OutputMode::Copy + : OutputMode::Extension; +} + +/** + * Add a WSocket to the Wayland server. + * This function is used by Treeland::ActivateWayland. + * + * @param socket WSocket to add + */ +void WaylandServer::addSocket(WSocket *socket) +{ + m_server->addSocket(socket); +} + +bool WaylandServer::toggleDebugMenuBar() +{ + bool ok = false; + + const auto outputs = rootSurfaceContainer()->outputs(); + if (outputs.isEmpty()) + return false; + + bool firstOutputDebugMenuBarIsVisible = false; + if (auto menuBar = outputs.first()->debugMenuBar()) { + firstOutputDebugMenuBarIsVisible = menuBar->isVisible(); + } + + for (const auto &output : outputs) { + if (output->debugMenuBar()) { + output->debugMenuBar()->setVisible(!firstOutputDebugMenuBarIsVisible); + ok = true; + } + } + + return ok; +} + +ShowDesktop::State WaylandServer::showDesktopState() const +{ + return m_showDesktop->state(); +} + +WXdgOutputManager *WaylandServer::xwaylandOutputManager() const +{ + return m_outputManager->xwaylandOutputManager(); +} + +void WaylandServer::setLaunchpadMapped(WOutput *output, bool mapped) +{ + Q_EMIT launchpadMappedChanged(output, mapped); +} + +void WaylandServer::showDesktop(WOutput *output) +{ + Q_EMIT showDesktopRequested(output); +} + +void WaylandServer::startLockscreen(WOutput *output, bool showAnimation) +{ + Q_EMIT startLockscreened(output, showAnimation); +} + +QString WaylandServer::currentWorkspaceWallpaper(WOutput *output) +{ + return wallpaperManager()->currentWorkspaceWallpaper(output); +} + +QString WaylandServer::currentLockScreenWallpaper(WOutput *output) +{ + return wallpaperManager()->currentLockScreenWallpaper(output); +} + +void WaylandServer::setMultitaskViewFactory(IMultitaskViewFactory *factory) +{ + if (m_multitaskViewFactory == factory) + return; + for (const auto &owner : m_sessionManager->sessions()) + owner->multitaskView()->immediatelyExit(); + m_multitaskViewFactory = factory; +} + +QQuickItem *WaylandServer::createMultitaskView(DesktopEnvironment *desktop) +{ + return m_multitaskViewFactory ? m_multitaskViewFactory->createMultitaskView(desktop) : nullptr; +} + +IMultitaskView *WaylandServer::multitaskView() const +{ + auto *owner = activeSession(); + return owner ? owner->multitaskView() : nullptr; +} + +void WaylandServer::setCurrentMode(CurrentMode mode) +{ + if (m_currentMode == mode) + return; + + setBlockActivateSurface(mode != CurrentMode::Normal && mode != CurrentMode::Multitaskview); + + m_currentMode = mode; + + // Deactivate pointer constraints when leaving Normal mode (modal shell state). + if (m_currentMode != CurrentMode::Normal && m_pointerConstraintsManager) + m_pointerConstraintsManager->deactivateAll(); + + Q_EMIT currentModeChanged(); +} + +void WaylandServer::prepareLockScreenTransition(bool isShutdownView) +{ + if (auto *view = multitaskView()) { + view->immediatelyExit(); + } + deleteTaskSwitch(); + m_rootSurfaceContainer->dismissAllPopups(); + if (isShutdownView) { + return; + } + setCurrentMode(CurrentMode::LockScreen); + setWorkspaceVisible(false); +} + +WSeat *WaylandServer::seat() const +{ + return m_seatManager->fallbackSeat(); +} + +ShortcutController *WaylandServer::shortcutController() const +{ + auto *current = desktop(); + return current ? current->inputChannel()->shortcuts() : nullptr; +} + +Output *WaylandServer::getOutputAtCursor() const +{ + return m_outputManager->outputAtCursor(); +} + +DDMInterfaceV1 *WaylandServer::ddmInterfaceV1() const { + return m_ddmInterfaceV1; +} + +bool WaylandServer::activateUserSession(const QString &username, const QString &sessionId) +{ + if (!m_userModel->getUser(username)) + return false; + + const auto update = m_sessionManager->prepareActiveUserSession(username, sessionId); + if (!update) + return false; + + m_userModel->setCurrentUserName(username); + m_sessionManager->commitActiveUserSession(update); + return true; +} + +void WaylandServer::enableRender() { + m_renderWindow->setRenderEnabled(true); +} + +void WaylandServer::disableRender() { + m_renderWindow->setRenderEnabled(false); +} + +void WaylandServer::setBlockActivateSurface(bool block) +{ + if (block == m_blockActivateSurface) + return; + m_blockActivateSurface = block; + Q_EMIT blockActivateSurfaceChanged(); +} + +bool WaylandServer::blockActivateSurface() const +{ + return m_blockActivateSurface; +} + +bool WaylandServer::noAnimation() const { + return m_noAnimation; +} + +void WaylandServer::setNoAnimation(bool noAnimation) { + if (m_noAnimation == noAnimation) + return; + m_noAnimation = noAnimation; + Q_EMIT noAnimationChanged(); +} + +void WaylandServer::toggleFpsDisplay() +{ + if (m_fpsDisplay) { + m_fpsDisplay->deleteLater(); + m_fpsDisplay = nullptr; + return; + } + + m_fpsDisplay = qmlEngine()->createFpsDisplay(m_renderWindow->contentItem()); +} + +#ifndef DISABLE_XWAYLAND +/** + * Move a XWayland window's surface corresponding to wid, to a + * position relative to a WSurface. Top-left point is always used. + * + * @param wid X Window ID for the XWayland surface + * @param anchor The anchor WSurface to be relative to + * @param dx Horizontal distance between the top-left point of anchor and the destination + * @param dy Vertical distance between the top-left point of anchor and the destination + */ +bool WaylandServer::setXWindowPositionRelative(uint wid, WSurface *anchor, wl_fixed_t dx, wl_fixed_t dy) const +{ + SurfaceWrapper *ach = m_rootSurfaceContainer->getSurface(anchor); + if (!ach) { + qCWarning(lcTlCore) << "setXWindowPositionRelative: Failed to get SurfaceWrapper from WSurface"; + return false; + } + + SurfaceWrapper *target = nullptr; + for (SurfaceWrapper *wrapper : std::as_const(rootSurfaceContainer()->surfaces())) { + if (wrapper->type() == SurfaceWrapper::Type::XWayland + && wrapper->session() == ach->session()) { + wlr_xwayland_surface *surface = + wlr_xwayland_surface_try_from_wlr_surface(wrapper->surface()->handle()); + if (surface && surface->window_id == static_cast(wid)) { + target = wrapper; + break; + } + } + } + if (!target) { + qCWarning(lcTlCore) << "setXWindowPositionRelative: XWayland surface corresponding to WID" << wid << "not found!"; + return false; + } + + QRectF rect(ach->position(), target->size()); + rect.translate(wl_fixed_to_double(dx), wl_fixed_to_double(dy)); + + // For XWayland surfaces, setting wrapper position while following + // implicit surface position may get overwritten by feedback updates. + // Temporarily switch to compositor-driven position so moveTo() sends + // configure with the new coordinates. + target->setXwaylandPositionFromSurface(false); + target->setPosition(rect.topLeft()); + target->setXwaylandPositionFromSurface(true); + return true; +} + +WXWayland *WaylandServer::createXWayland(WSeat *seat) +{ + return shellHandler()->createXWayland(server(), seat, m_compositor, false); +} +#endif + +WSeat *WaylandServer::findSeatForSurface(SurfaceWrapper *wrapper) const +{ + return getLastInteractingSeat(wrapper); +} + +void WaylandServer::switchWorkspaceForSeat(WSeat *seat, int index) +{ + if (!seat) { + return; + } + + workspace()->switchTo(index); +} + +void WaylandServer::updateIdleInhibitor() +{ + m_idleManager->updateIdleInhibitor(); +} + +WBackend *WaylandServer::backend() const +{ + return m_backend; +} + +void WaylandServer::activateSurface(SurfaceWrapper *wrapper, Qt::FocusReason reason, + WSeat *seat, bool raise) +{ + m_focusController->activateSurface(wrapper, reason, seat, raise); +} + +void WaylandServer::forceActivateSurface(SurfaceWrapper *wrapper, Qt::FocusReason reason, + WSeat *seat) +{ + m_focusController->forceActivateSurface(wrapper, reason, seat); +} + +void WaylandServer::requestKeyboardFocus(SurfaceWrapper *wrapper, Qt::FocusReason reason, + WSeat *seat) +{ + m_focusController->requestKeyboardFocus(wrapper, reason, seat); +} + +SurfaceWrapper *WaylandServer::keyboardFocusSurface() const +{ + return m_focusController->keyboardFocusSurface(); +} + +SurfaceWrapper *WaylandServer::activatedSurface() const +{ + return m_focusController->activatedSurface(); +} + +void WaylandServer::setActivatedSurface(SurfaceWrapper *surface, WSeat *seat, bool raise) +{ + m_focusController->setActivatedSurface(surface, seat, raise); +} + +void WaylandServer::onRenderWindowActiveFocusItemChanged() +{ + m_focusController->onRenderWindowActiveFocusItemChanged(); +} + +WSeat *WaylandServer::getLastInteractingSeat(SurfaceWrapper *surface) const +{ + return m_focusController->getLastInteractingSeat(surface); +} + +void WaylandServer::updateSurfaceSeatInteraction(SurfaceWrapper *surface, WSeat *seat) +{ + m_focusController->updateSurfaceSeatInteraction(surface, seat); +} + +WSeat *WaylandServer::currentEventSeat() const +{ + auto *current = desktop(); + return current ? current->inputChannel()->filter()->currentEventSeat() : m_bootstrapInputFilter->currentEventSeat(); +} + +void WaylandServer::cancelShowDesktop(SurfaceWrapper *surface) +{ + m_showDesktop->cancelShowDesktop(surface); +} + +void WaylandServer::restoreFromShowDesktop(SurfaceWrapper *surface) +{ + m_showDesktop->restoreFromShowDesktop(surface); +} + +void WaylandServer::restoreShowDesktopFocus() +{ + m_showDesktop->restoreShowDesktopFocus(); +} + +void WaylandServer::setShowDesktopState(ShowDesktop::State state) +{ + m_showDesktop->setState(state); +} + +void WaylandServer::setLockScreenImpl(ILockScreen *impl) +{ + m_lockScreenManager->setLockScreenImpl(impl); +} + +void WaylandServer::showLockScreen(bool switchToGreeter) +{ + m_lockScreenManager->showLockScreen(switchToGreeter); +} + +bool WaylandServer::isLockScreenAvailable() const +{ + return m_lockScreenManager->isLockScreenAvailable(); +} + +void WaylandServer::showShutdownMenu(ShutdownMenuFocus focus) +{ + m_lockScreenManager->showShutdownMenu(focus); +} + +void WaylandServer::showSwitchUser() +{ + m_lockScreenManager->showSwitchUser(); +} + +void WaylandServer::finishLockScreenTransition() +{ + setCurrentMode(CurrentMode::Normal); + setWorkspaceVisible(true); +#ifdef EXT_SESSION_LOCK_V1 + setNoAnimation(false); +#endif + if (auto *surface = activatedSurface()) { + if (surface->hasFocusCapability()) + requestKeyboardFocus(surface, Qt::NoFocusReason); + } else { + activateSurface(workspace()->current()->latestActiveSurface(), Qt::NoFocusReason); + } +} + +WXdgOutputManager *WaylandServer::installDesktopProtocols(QmlEngine *engine) +{ + m_ddmInterfaceV1 = server()->attach(); + + m_outputManager->setBackend(backend()); + + m_ddeShellV1 = server()->attach(); + + m_surfaceProtocols->installRegionWatch(server()); + + connect(m_ddeShellV1, &DDEShellManagerInterfaceV1::toggleMultitaskview, this, [this] { + if (auto *view = multitaskView()) { + view->toggleMultitaskView(IMultitaskView::ActiveReason::ShortcutKey); + } + }); + connect(m_ddeShellV1, + &DDEShellManagerInterfaceV1::lockScreenCreated, + m_lockScreenManager, + &LockScreenManager::handleLockScreen); + + m_ddeShellV2 = server()->attach(); + + m_compositorActionInterfaceV1 = server()->attach(); + connect(m_compositorActionInterfaceV1, + &CompositorActionInterfaceV1::triggered, + this, + &WaylandServer::handleCompositorAction); + m_shellHandler->createComponent(engine, m_renderWindow->contentItem()); + + m_surfaceProtocols->installToplevels(m_shellHandler); + m_bootstrapInputFilter->installRelativePointer(server(), m_seatManager); + + auto *xdgOutputManager = + server()->attach(m_rootSurfaceContainer->outputLayout()); + + server()->attach(); + server()->attach(); + connect(m_rootSurfaceContainer, + &RootSurfaceContainer::primaryOutputChanged, + m_sessionManager, + &SessionManager::syncActiveSessionXWaylandPrimaryOutput); + m_wallpaperColorV1 = server()->attach(); +#ifndef DISABLE_XWAYLAND + m_xWindowControlInterfaceV1 = server()->attach(); +#endif + auto *outputGroupInterface = server()->attach(); + m_outputManager->setOutputGroupInterface(outputGroupInterface); + + m_captureManager->installProtocol(engine, m_renderWindow); + + // New protocols (treeland-protocols 0.6.0) + + DConfigManager::instance()->initializeActiveUserConfig(this); + + qmlRegisterUncreatableType("Treeland.Protocols", + 1, + 0, + "Personalization", + "Only for Enum"); + + qmlRegisterUncreatableType("Treeland.Protocols", + 1, + 0, + "DDEShellHelper", + "Only for attached"); + qmlRegisterUncreatableType("Treeland.Protocols", + 1, + 0, + "CaptureSource", + "An abstract class"); + qmlRegisterType("Treeland.Protocols", 1, 0, "CaptureContextV1"); + qmlRegisterType("Treeland.Protocols", 1, 0, "CaptureSourceSelector"); + + server()->attach(); + + return xdgOutputManager; +} + +bool WaylandServer::initializeSeatsAndShell() +{ + // Initialize seats from configuration + m_primarySeat = + m_seatManager->initializeFromConfig(QStringLiteral(TREELAND_SYSCONFDIR "/seats.json"), server()); + if (!m_primarySeat) { + qCCritical(lcTlCore) << "Failed to initialize seats!"; + return false; + } + + // Setup all seats (cursor, keyboard focus, event filter) + m_seatManager->setupAllSeats(m_renderWindow, + m_rootSurfaceContainer->outputLayout(), + m_bootstrapInputFilter, + m_rootSurfaceContainer->cursor()); + + // Connect device signals and handle device lifecycle + m_seatManager->connectBackendSignals(backend()); + connect(m_seatManager, &SeatManager::deviceAdded, this, [this](WInputDevice *device) { + m_seatManager->assignDevice(device, + m_renderWindow, + m_rootSurfaceContainer->outputLayout(), + seat()); + }); + + m_dragController->initialize(m_ddeShellV1 != nullptr); + + // Assign existing devices + m_seatManager->assignExistingDevices(backend()); + + if (m_rootSurfaceContainer) { + m_rootSurfaceContainer->setupSeatManagement(); + } + + if (!m_primarySeat) { + qCCritical(lcTlCore) << "No seat available after initialization, cannot continue"; + return false; + } + m_shellHandler->init(server(), m_primarySeat); + + connect(m_shellHandler->wallpaperShell(), + &TreelandWallpaperShellInterfaceV1::wallpaperSurfaceAdded, + this, + &WaylandServer::onWallpaperSurfaceAdded); + + return true; +} + +void WaylandServer::installRuntimeProtocols(WXdgOutputManager *xdgOutputManager) +{ + initializeRendering(); + initializeRenderWindow(); + +#ifndef DISABLE_XWAYLAND + auto *xwaylandOutputManager = + server()->attach(m_rootSurfaceContainer->outputLayout()); + m_outputManager->setXdgOutputManagers( + xdgOutputManager, xwaylandOutputManager, m_sessionManager); +#else + m_outputManager->setXdgOutputManagers(xdgOutputManager, nullptr, m_sessionManager); +#endif + // User dde does not has a real Logind session, so just pass "0" as id + m_sessionManager->updateActiveUserSession(QStringLiteral("dde"), QStringLiteral("0")); + m_bootstrapInputFilter->setEnabled(false); + connect(m_userModel, &UserModel::userLoggedIn, m_sessionManager, &SessionManager::updateActiveUserSession); + + auto gammaControlManager = wlr_gamma_control_manager_v1_create(server()->handle()); + m_outputManager->setGammaControlManager(gammaControlManager); + + installPointerProtocols(); + m_pointerConstraintsV1 = server()->attach(); + m_pointerConstraintsManager = new PointerConstraintsManager(m_pointerConstraintsV1, this, this); + + installCommonProtocols(); + m_idleManager->initialize(server()); + + m_screensaverInterfaceV2 = server()->attach(); + m_idleManager->setScreensaver(m_screensaverInterfaceV2); + + auto *outputPowerManager = wlr_output_power_manager_v1_create(server()->handle()); + m_outputManager->setOutputPowerManager(outputPowerManager); + m_lockScreenManager->installSessionLock(server()); + + m_wallpaperNotifierInterfaceV1 = server()->attach(); + if (isDDMDisplay()) { + m_wallpaperNotifierInterfaceV1->setFilter([this](WClient *client) { return m_sessionManager->isDDEUserClient(client); }); + } + connect(m_wallpaperNotifierInterfaceV1, + &TreelandWallpaperNotifierInterfaceV1::bound, + this, + &WaylandServer::onWallpaperNotifierBound); + + m_keyboardStateNotifyManagerInterfaceV1 = server()->attach(); + m_activeNotifyManagerInterfaceV1 = server()->attach(); + m_keyboardShortcutsInhibitManagerV1 = server()->attach(); + m_bootstrapInputFilter->setShortcutProtocols(nullptr, m_keyboardShortcutsInhibitManagerV1); + for (const auto &owner : m_sessionManager->sessions()) + configureInputFilter(owner->desktop()->inputChannel()->filter(), + owner->desktop()->inputChannel()->shortcutProtocol()); +} + +DesktopEnvironment *WaylandServer::desktop() const +{ + auto *owner = activeSession(); + return owner ? owner->desktop() : nullptr; +} + +QList WaylandServer::desktopEnvironments() const +{ + QList result; + for (const auto &owner : m_sessionManager->sessions()) + result.append(owner->desktop()); + return result; +} + +CompositorInputFilter *WaylandServer::createInputFilter(InputContext *context, GestureManager *gestures, + ShortcutController *controller, QObject *parent) +{ + auto *filter = new CompositorInputFilter(context, parent, m_idleManager, + m_captureManager, m_outputManager); + filter->setGestureManager(gestures); + filter->setController(controller); + configureInputFilter(filter); + connect(filter, &CompositorInputFilter::modifierKeyReleased, + this, &WaylandServer::modifierKeyReleased); + return filter; +} + +void WaylandServer::configureInputFilter(CompositorInputFilter *filter, ShortcutManagerV3 *shortcuts) const +{ + filter->setShortcutProtocols(shortcuts, m_keyboardShortcutsInhibitManagerV1); +} diff --git a/src/core/waylandserver.h b/src/core/waylandserver.h new file mode 100644 index 0000000000..48550bb7e0 --- /dev/null +++ b/src/core/waylandserver.h @@ -0,0 +1,513 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include "core/qmlengine.h" +#include "modules/activation/activationmanagerinterfacev1.h" +#include "modules/wallpaper/wallpapermanagerinterfacev1.h" +#include "modules/wallpaper/wallpapernotifierinterfacev1.h" +#include "showdesktop/showdesktop.h" +#ifndef DISABLE_XWAYLAND +#include "modules/xwindow-control/xwindowcontrolinterfacev1.h" +#endif +#include "utils/fpsdisplaymanager.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +class QJsonObject; +class SeatUserDConfig; + +Q_MOC_INCLUDE() +Q_MOC_INCLUDE() +Q_MOC_INCLUDE() +Q_MOC_INCLUDE() +Q_MOC_INCLUDE() +Q_MOC_INCLUDE("core/rootsurfacecontainer.h") +Q_MOC_INCLUDE("modules/capture/capture.h") +Q_MOC_INCLUDE("modules/wallpaper/wallpapershellinterfacev1.h") +Q_MOC_INCLUDE("surface/surfacewrapper.h") +Q_MOC_INCLUDE("workspace/workspace.h") +Q_MOC_INCLUDE("treelandconfig.hpp") +Q_MOC_INCLUDE("treelanduserconfig.hpp") +Q_MOC_INCLUDE("animationconfig.hpp") + +QT_BEGIN_NAMESPACE +class QDBusObjectPath; +class QQuickItem; +QT_END_NAMESPACE + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WBackend; +class WClientPrivate; +class WCursor; +class WExtForeignToplevelListV1; +class WForeignToplevel; +class WOutput; +class WOutputRenderWindow; +class WServer; +class WSessionLock; +class WSessionLockManager; +class WSocket; +class WSurface; +class WSurfaceItem; +class WToplevelSurface; +class WXdgDecorationManager; +class WXdgOutputManager; +#ifndef DISABLE_XWAYLAND +class WXWayland; +#endif +class WPointerConstraintsV1; + +class WForeignToplevel; +class WExtForeignToplevelListV1; +class WRelativePointerManagerV1; +class WSessionLockManager; +class WSessionLock; +WAYLIB_SERVER_END_NAMESPACE + +class ShowDesktop; +class LockScreenManager; +class IdleManager; +class CaptureManager; +class DragController; +class GestureManager; +class InputContext; +class CompositorInputFilter; +class FocusController; +class SurfaceProtocolController; +class SeatManager; +class PointerConstraintsManager; + +WAYLIB_SERVER_USE_NAMESPACE + +class CaptureSourceSelector; +class DDEShellManagerInterfaceV1; +class DDEShellManagerInterfaceV2; +class DDMInterfaceV1; +class ForeignToplevelManagerInterfaceV3; +class FpsDisplayManager; +class GraphicsPlatform; +class GreeterProxy; +class ILockScreen; +class IMultitaskView; +class IMultitaskViewFactory; +class LockScreen; +class LockScreenInterface; +class Multitaskview; +class Output; +class OutputManager; +class PersonalizationManagerInterfaceV1; +class AppearanceInterfaceV1; +class AppearanceManagerInterfaceV1; +class CompositorActionInterfaceV1; +class DecorationManagerInterfaceV1; +class RootSurfaceContainer; +class ScreensaverInterfaceV2; +class SessionManager; +class SessionModel; +class ShellHandler; +class ShellActionExecutor; +class ShortcutController; +class ShortcutManagerV3; +class ShortcutRunner; +class SurfaceContainer; +class SurfaceWrapper; +class TreelandConfig; +class AnimationConfig; +class TreelandUserConfig; +class TreelandRemoteSource; +class Session; +class DesktopEnvironment; +Q_MOC_INCLUDE("session/session.h") +Q_MOC_INCLUDE("session/sessionmanager.h") +class UserModel; +class WallpaperColorInterfaceV1; +class TreelandKeyboardStateNotifyManagerInterfaceV1; +class TreelandActiveNotifyManagerInterfaceV1; +class TreelandRegionWatchManagerInterfaceV1; +class KeyboardShortcutsInhibitManagerV1; +class TreelandWallpaperSurfaceInterfaceV1; +class WallpaperManager; +class WallpaperItem; +class TreelandInputManagerInterfaceV1; +class InputManager; + +namespace Treeland { +class Treeland; +} + +class WaylandServer : public QObject, public WAYLIB_SERVER_NAMESPACE::WObject +{ + Q_OBJECT + QML_ELEMENT + QML_SINGLETON + Q_PROPERTY(RootSurfaceContainer* rootSurfaceContainer READ rootSurfaceContainer CONSTANT FINAL) + Q_PROPERTY(float animationSpeed READ animationSpeed WRITE setAnimationSpeed NOTIFY animationSpeedChanged FINAL) + Q_PROPERTY(OutputMode outputMode READ outputMode WRITE setOutputMode NOTIFY outputModeChanged FINAL) + Q_PROPERTY(SurfaceWrapper* activatedSurface READ activatedSurface NOTIFY activatedSurfaceChanged FINAL) + Q_PROPERTY(Workspace* workspace READ workspace NOTIFY workspaceChanged FINAL) + Q_PROPERTY(AnimationConfig* animationConfig READ animationConfig NOTIFY animationConfigChanged FINAL) + Q_PROPERTY(TreelandUserConfig* config READ config NOTIFY configChanged FINAL) + Q_PROPERTY(TreelandConfig* globalConfig READ globalConfig CONSTANT FINAL) + Q_PROPERTY(bool blockActivateSurface READ blockActivateSurface WRITE setBlockActivateSurface NOTIFY blockActivateSurfaceChanged FINAL) + Q_PROPERTY(bool noAnimation READ noAnimation WRITE setNoAnimation NOTIFY noAnimationChanged FINAL) + Q_PROPERTY(RootSurfaceContainer* rootContainer READ rootContainer CONSTANT FINAL) + +public: + explicit WaylandServer(QObject *parent = nullptr); + ~WaylandServer() override; + + static void syncPaletteTypeWithWindowColorScheme(int32_t colorScheme); + + enum class OutputMode + { + Copy, + Extension + }; + Q_ENUM(OutputMode) + + enum class CurrentMode + { + Normal, + LockScreen, + WindowSwitch, + Multitaskview + }; + Q_ENUM(CurrentMode) + + // Which button the shutdown menu gives the keyboard focus to when it + // opens. None leaves the choice to the menu, which focuses lock. + enum class ShutdownMenuFocus + { + None, + PowerOff, + Reboot, + Suspend, + Hibernate, + LogOut, + }; + Q_ENUM(ShutdownMenuFocus) + + static WaylandServer *instance(); + bool isAvailable() const { return m_instance != nullptr; } + AnimationConfig *animationConfig() const; + TreelandUserConfig *config(); + TreelandConfig *globalConfig(); + + SurfaceWrapper *activatedSurface() const; + SessionManager *sessionManager() const; + QmlEngine *qmlEngine() const; + WOutputRenderWindow *window() const; + GraphicsPlatform *graphicsPlatform() const; + ShellHandler *shellHandler() const; + Session *activeSession() const; + DesktopEnvironment *desktop() const; + QList desktopEnvironments() const; + WallpaperManager *wallpaperManager() const; + TreelandWallpaperNotifierInterfaceV1 *wallpaperNotifier() const; + OutputManager *outputHardware() const; + CompositorInputFilter *createInputFilter(InputContext *context, GestureManager *gestures, + ShortcutController *controller, QObject *parent); + void configureInputFilter(CompositorInputFilter *filter, ShortcutManagerV3 *shortcuts = nullptr) const; + QQuickItem *taskSwitcher() const; + void ensureTaskSwitcher(); + Q_INVOKABLE void setOutputScale(WOutput *output, qreal scale); + void initializeSessionProtocols(Session *session); + Workspace *workspace() const; + WXdgOutputManager *xwaylandOutputManager() const; + + void init(Treeland::Treeland *treeland); + + RootSurfaceContainer *rootSurfaceContainer() const; + WServer *server() const; + Output *getOutput(WOutput *output) const; + Output *getOutputByUuid(const QString &uuid) const; + const QList &outputs() const; + + float animationSpeed() const; + void setAnimationSpeed(float newAnimationSpeed); + + OutputMode outputMode() const; + void setOutputMode(OutputMode mode); + Q_INVOKABLE void addOutput(); + + void addSocket(WSocket *socket); +#ifndef DISABLE_XWAYLAND + [[nodiscard]] WXWayland *createXWayland(WSeat *seat); +#endif + + WSeat *seat() const; + + // The shortcut manager's controller, i.e. the live registry of bound + // shortcuts. Exposed for the debug remote source; null before init. + ShortcutController *shortcutController() const; + + // Moves the primary seat cursor to @p position, first ending any + // in-progress interactive move/resize for every seat so the motion is + // not fed into an active transaction. Exposed for the debug control API. + void setCursorPosition(const QPointF &position); + + bool toggleDebugMenuBar(); + + ShowDesktop::State showDesktopState() const; + void setShowDesktopState(ShowDesktop::State state); + + Q_INVOKABLE void setLaunchpadMapped(WOutput *output, bool mapped); + Q_INVOKABLE void showDesktop(WOutput *output); + Q_INVOKABLE void cancelShowDesktop(SurfaceWrapper *excludeSurface = nullptr); + Q_INVOKABLE void startLockscreen(WOutput *output, bool showAnimation); + Q_INVOKABLE QString currentWorkspaceWallpaper(WOutput *output); + Q_INVOKABLE QString currentLockScreenWallpaper(WOutput *output); + + void setMultitaskViewFactory(IMultitaskViewFactory *factory); + QQuickItem *createMultitaskView(DesktopEnvironment *desktop); + IMultitaskView *multitaskView() const; + void setLockScreenImpl(ILockScreen *impl); + + CurrentMode currentMode() const + { + return m_currentMode; + } + + void setCurrentMode(CurrentMode mode); + + bool isNormalOrMultitaskview() const + { + return m_currentMode == CurrentMode::Normal || m_currentMode == CurrentMode::Multitaskview; + } + + bool isLockScreenAvailable() const; + + // When @p isShutdownView is true the current mode is left untouched, so the + // standalone shutdown menu does not hide layer surfaces (desktop icons, + // dock, panels) via setHideByLockScreen(). + void prepareLockScreenTransition(bool isShutdownView = false); + void finishLockScreenTransition(); + void setNoAnimation(bool noAnimation); + + void showLockScreen(bool switchToGreeter = true); + void showShutdownMenu(ShutdownMenuFocus focus = ShutdownMenuFocus::None); + void showSwitchUser(); + + Output* getOutputAtCursor() const; + + inline UserModel *userModel() const { return m_userModel; }; + inline SessionModel *sessionModel() const { return m_sessionModel; }; + DDMInterfaceV1 *ddmInterfaceV1() const; + + bool activateUserSession(const QString &username, const QString &sessionId); + void enableRender(); + void disableRender(); + + void setBlockActivateSurface(bool block); + bool blockActivateSurface() const; + bool noAnimation() const; + void toggleFpsDisplay(); + + void updateIdleInhibitor(); + // Idle state and inhibit sources, as reported by the treeland-debug + // ``idle`` command. Never null after initialization. + IdleManager *idleManager() const { return m_idleManager; } + void restoreFromShowDesktop(SurfaceWrapper *activeSurface = nullptr); + void restoreShowDesktopFocus(); + +#ifndef DISABLE_XWAYLAND + bool setXWindowPositionRelative(uint wid, WSurface *anchor, wl_fixed_t dx, wl_fixed_t dy) const; +#endif + SeatManager *seatManager() const; + + WSeat *getSeatForEvent(QInputEvent *event) const; + WSeat *findSeatForSurface(SurfaceWrapper *wrapper) const; + WSeat *getLastInteractingSeat(SurfaceWrapper *surface) const; + WSeat *currentEventSeat() const; + + bool isDDMDisplay() const { return m_isDDMDisplay; } + + RootSurfaceContainer *rootContainer() const { return m_rootSurfaceContainer; } + WBackend *backend() const; +public Q_SLOTS: + void initializeWallpaper(); + void activateSurface(SurfaceWrapper *wrapper, + Qt::FocusReason reason = Qt::OtherFocusReason, + WSeat *seat = nullptr, + bool raise = true); + void forceActivateSurface(SurfaceWrapper *wrapper, + Qt::FocusReason reason = Qt::OtherFocusReason, + WSeat *seat = nullptr); + void requestKeyboardFocus(SurfaceWrapper *wrapper, + Qt::FocusReason reason = Qt::OtherFocusReason, + WSeat *seat = nullptr); + void fakePressSurfaceBottomRightToReszie(SurfaceWrapper *surface); + bool surfaceBelongsToCurrentSession(SurfaceWrapper *wrapper); + +Q_SIGNALS: + void wallpaperChanged(); + void activeSessionChanged(); + void workspaceChanged(); + void workspaceAdded(); + void animationConfigChanged(); + void configChanged(); + void primaryOutputChanged(); + void activatedSurfaceChanged(); + void desktopChanged(); + + void animationSpeedChanged(); + void outputModeChanged(); + + void currentModeChanged(); + void noAnimationChanged(); + + void blockActivateSurfaceChanged(); + void requestQuit(); + + void launchpadMappedChanged(WOutput *output, bool mapped); + void showDesktopRequested(WOutput *output); + void showDesktopStateChanged(); + void startLockscreened(WOutput *output, bool showAnimation); + void modifierKeyReleased(QKeyEvent *event); + void lockScreenAvailableChanged(); + +private Q_SLOTS: + void deleteTaskSwitch(); + void onWorkspaceChanged(); + void applyActiveSessionConfig(); + void onWallpaperNotifierBound(wl_resource *resource); + void onWallpaperSurfaceAdded(TreelandWallpaperSurfaceInterfaceV1 *surface); + +private: + WXdgOutputManager *installDesktopProtocols(QmlEngine *engine); + bool initializeSeatsAndShell(); + void installRuntimeProtocols(WXdgOutputManager *xdgOutputManager); + void createBackend(); + void startDisplay(); + void initializeRendering(); + void initializeRenderWindow(); + void installPointerProtocols(); + void installCommonProtocols(); + void startBackend(); + void handleCompositorAction(uint32_t action); + void applyCurrentUserConfig(const QString &userName, + TreelandUserConfig *config, + SeatUserDConfig *seatConfig); + SurfaceWrapper *keyboardFocusSurface() const; + void setActivatedSurface(SurfaceWrapper *newActivateSurface, + WSeat *seat = nullptr, + bool raise = true); + void setWorkspaceVisible(bool visible); + void updateSurfaceSeatInteraction(SurfaceWrapper *surface, WSeat *seat); + void switchWorkspaceForSeat(WSeat *seat, int index); + +private Q_SLOTS: + void onRenderWindowActiveFocusItemChanged(); + +private: + friend class PointerConstraintsManager; + friend class SessionManager; + friend class SessionInputContext; + friend class TreelandWallpaperSurfaceInterfaceV1; + friend class WallpaperManager; + friend class WallpaperItem; + friend class WallpaperSwitcherItem; + friend class InputManager; + friend class RootSurfaceContainer; + friend class ShellHandler; + friend class ShortcutRunner; + friend class ShellActionExecutor; + + static WaylandServer *m_instance; + void setAnimationConfig(AnimationConfig *config); + AnimationConfig *m_animationConfig = nullptr; + TreelandUserConfig *m_config = nullptr; + TreelandConfig *m_globalConfig = nullptr; + Treeland::Treeland *m_treeland = nullptr; + FpsDisplayManager *m_fpsManager = nullptr; + SessionManager *m_sessionManager = nullptr; + bool m_wallpaperInitialized = false; + + CurrentMode m_currentMode{ CurrentMode::Normal }; + + // QtQuick scene and presentation + WOutputRenderWindow *m_renderWindow = nullptr; + std::unique_ptr m_graphicsPlatform; + QQuickItem *m_dockPreview = nullptr; + QQuickItem *m_fpsDisplay = nullptr; + + // Wayland runtime and scene root + WServer *m_server = nullptr; + WBackend *m_backend = nullptr; + WUniquePointer m_renderer; + WUniquePointer m_allocator; + WPointer m_compositor; + RootSurfaceContainer *m_rootSurfaceContainer = nullptr; + + // Seat and desktop protocol adapters + WSeat *m_primarySeat = nullptr; + ShellHandler *m_shellHandler = nullptr; + WPointerConstraintsV1 *m_pointerConstraintsV1 = nullptr; + PointerConstraintsManager *m_pointerConstraintsManager = nullptr; + CompositorActionInterfaceV1 *m_compositorActionInterfaceV1 = nullptr; + WallpaperColorInterfaceV1 *m_wallpaperColorV1 = nullptr; +#ifndef DISABLE_XWAYLAND + XWindowControlInterfaceV1 *m_xWindowControlInterfaceV1 = nullptr; +#endif + DDEShellManagerInterfaceV1 *m_ddeShellV1 = nullptr; + DDEShellManagerInterfaceV2 *m_ddeShellV2 = nullptr; + DDMInterfaceV1 *m_ddmInterfaceV1 = nullptr; + ScreensaverInterfaceV2 *m_screensaverInterfaceV2 = nullptr; + TreelandWallpaperNotifierInterfaceV1 *m_wallpaperNotifierInterfaceV1 = nullptr; + TreelandKeyboardStateNotifyManagerInterfaceV1 *m_keyboardStateNotifyManagerInterfaceV1 = nullptr; + TreelandActiveNotifyManagerInterfaceV1 *m_activeNotifyManagerInterfaceV1 = nullptr; + KeyboardShortcutsInhibitManagerV1 *m_keyboardShortcutsInhibitManagerV1 = nullptr; + // Desktop presentation state + OutputManager *m_outputManager = nullptr; + + float m_animationSpeed = 1.0; + std::optional m_fakelastPressedPosition; + + QPropertyAnimation *m_workspaceScaleAnimation{ nullptr }; + QPropertyAnimation *m_workspaceOpacityAnimation{ nullptr }; + + IMultitaskViewFactory *m_multitaskViewFactory{ nullptr }; + UserModel *m_userModel{ nullptr }; + SessionModel *m_sessionModel{ nullptr }; + GreeterProxy *m_greeterProxy{ nullptr }; + + bool m_blockActivateSurface{ false }; + + bool m_noAnimation{ false }; + bool m_isDDMDisplay{ false }; + void tryInitRemoteSource(); + + TreelandRemoteSource *m_treelandRemoteSource = nullptr; + + SeatManager *m_seatManager = nullptr; + SurfaceProtocolController *m_surfaceProtocols = nullptr; + ShowDesktop *m_showDesktop = nullptr; + LockScreenManager *m_lockScreenManager = nullptr; + FocusController *m_focusController = nullptr; + // Startup filter and relative-pointer transport; user seats use their input channel. + CompositorInputFilter *m_bootstrapInputFilter = nullptr; + IdleManager *m_idleManager = nullptr; + CaptureManager *m_captureManager = nullptr; + DragController *m_dragController = nullptr; +}; diff --git a/src/core/windowconfigstore.cpp b/src/core/windowconfigstore.cpp new file mode 100644 index 0000000000..d3159e2082 --- /dev/null +++ b/src/core/windowconfigstore.cpp @@ -0,0 +1,185 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "core/windowconfigstore.h" + +#include "dconfig/dconfigmanager.h" +#include "appconfig.hpp" +#include "treelandconfig.hpp" +#include "common/treelandlogging.h" + +#include + +WindowConfigStore::WindowConfigStore(QObject *parent) + : QObject(parent) +{ +} + +AppConfig *WindowConfigStore::configForApp(const QString &appId) const +{ + if (appId.isEmpty()) { + return nullptr; + } + + auto *configManager = DConfigManager::instance(); + Q_ASSERT(configManager); + return configManager->appConfig(appId); +} + +void WindowConfigStore::saveLastSize(const QString &appId, const QSize &size) +{ + if (appId.isEmpty() || !size.isValid()) { + qCWarning(lcTlCore) << "WindowConfigStore: saveLastSize invalid parameters for" << appId + << size; + return; + } + + auto *config = configForApp(appId); + if (!config) { + qCWarning(lcTlCore) << "WindowConfigStore: saveLastSize no config for" << appId; + return; + } + + qCDebug(lcTlCore) << "WindowConfigStore: save size for" << appId << "as" << size; + config->setLastWindowWidth(size.width()); + config->setLastWindowHeight(size.height()); +} + +void WindowConfigStore::withSplashConfigFor(const QString &appId, + QObject *context, + std::function callback, + std::function skipCallback) const +{ + Q_ASSERT_X(callback, Q_FUNC_INFO, "callback must be provided"); + Q_ASSERT_X(skipCallback, Q_FUNC_INFO, "skipCallback must be provided"); + qCDebug(lcTlCore) << "WindowConfigStore: withSplashConfigFor requested for" << appId; + auto *config = configForApp(appId); + if (!config) { + skipCallback(); + return; + } +#if APPCONFIG_DCONFIG_FILE_VERSION_MINOR > 0 + if (config->isInitializeSucceeded()) { +#else + if (config->isInitializeSucceed()) { +#endif + if (!config->enablePrelaunchSplash()) { + skipCallback(); + return; + } + qCDebug(lcTlCore) << "WindowConfigStore: configInitializeSucceeded for" << appId + << config->lastWindowWidth() << config->lastWindowHeight(); + const QSize size(static_cast(config->lastWindowWidth()), + static_cast(config->lastWindowHeight())); + const QSize validatedSize = size.isValid() ? size : QSize(); + callback(validatedSize, + config->splashDarkPalette(), + config->splashLightPalette(), + config->splashThemeType()); + return; + } + + if (config->isInitializeFailed()) { + qCWarning(lcTlCore) << "WindowConfigStore: configInitializeFailed for" << appId; + skipCallback(); + return; + } + + auto *ctx = context ? context : const_cast(this); + const QPointer configGuard(config); + connect( + config, + &AppConfig::configInitializeSucceed, + ctx, + [appId, callback, skipCallback, configGuard](DTK_CORE_NAMESPACE::DConfig *) { + if (!configGuard) { + qCWarning(lcTlCore) + << "WindowConfigStore: configInitializeSucceed but config deleted for" << appId; + skipCallback(); + return; + } + + if (!configGuard->enablePrelaunchSplash()) { + skipCallback(); + return; + } + + qCDebug(lcTlCore) << "WindowConfigStore: configInitializeSucceed for" << appId + << configGuard->lastWindowWidth() + << configGuard->lastWindowHeight(); + const QSize size(static_cast(configGuard->lastWindowWidth()), + static_cast(configGuard->lastWindowHeight())); + const QSize validatedSize = size.isValid() ? size : QSize(); + callback(validatedSize, + configGuard->splashDarkPalette(), + configGuard->splashLightPalette(), + configGuard->splashThemeType()); + }, + Qt::SingleShotConnection); + connect( + config, + &AppConfig::configInitializeFailed, + ctx, + [skipCallback]() { + qCCritical(lcTlCore) << "WindowConfigStore: configInitializeFailed callback"; + skipCallback(); + }, + Qt::SingleShotConnection); +} + +void WindowConfigStore::recordSplashMismatch(const QString &appId) +{ + if (appId.isEmpty()) { + return; + } + + auto *globalConfig = DConfigManager::instance()->globalConfig(); + Q_ASSERT(globalConfig); + const int maxMismatchCount = + static_cast(globalConfig->prelaunchSplashMaxMismatchCount()); + if (maxMismatchCount <= 0) { + return; + } + + auto *config = configForApp(appId); + if (!config || !config->isInitializeSucceeded()) { + qCWarning(lcTlCore) << "WindowConfigStore: recordSplashMismatch skipped, config " + "unavailable or not initialized for" + << appId; + return; + } + + int count = static_cast(config->prelaunchSplashMismatchCount()) + 1; + config->setPrelaunchSplashMismatchCount(count); + qCInfo(lcTlCore) << "WindowConfigStore: splash mismatch count for" << appId << "is now" + << count; + if (count >= maxMismatchCount) { + config->setEnablePrelaunchSplash(false); + config->setPrelaunchSplashMismatchCount(0); + qCWarning(lcTlCore) << "WindowConfigStore: auto-disabled prelaunch splash for" << appId + << "after" << count << "consecutive mismatches"; + } +} + +void WindowConfigStore::resetSplashMismatchCount(const QString &appId) +{ + if (appId.isEmpty()) { + return; + } + + auto *config = configForApp(appId); + if (!config || !config->isInitializeSucceeded()) { + qCWarning(lcTlCore) << "WindowConfigStore: resetSplashMismatchCount skipped, config " + "unavailable or not initialized for" + << appId; + return; + } + + if (config->prelaunchSplashMismatchCount() != 0) { + config->setPrelaunchSplashMismatchCount(0); + qCDebug(lcTlCore) << "WindowConfigStore: reset splash mismatch count for" << appId; + } +} diff --git a/src/core/windowconfigstore.h b/src/core/windowconfigstore.h new file mode 100644 index 0000000000..21e4d8fb7d --- /dev/null +++ b/src/core/windowconfigstore.h @@ -0,0 +1,36 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include +#include +#include + +#include + +class AppConfig; + +// Window configuration persistence backed by dconfig +class WindowConfigStore : public QObject +{ + Q_OBJECT +public: + explicit WindowConfigStore(QObject *parent = nullptr); + + void saveLastSize(const QString &appId, const QSize &size); + + void withSplashConfigFor( + const QString &appId, + QObject *context, + std::function callback, + std::function skipCallback) const; + + void recordSplashMismatch(const QString &appId); + void resetSplashMismatchCount(const QString &appId); + +private: + AppConfig *configForApp(const QString &appId) const; +}; diff --git a/src/dconfig/dconfigmanager.cpp b/src/dconfig/dconfigmanager.cpp new file mode 100644 index 0000000000..f305aae1fb --- /dev/null +++ b/src/dconfig/dconfigmanager.cpp @@ -0,0 +1,352 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "dconfigmanager.h" +#include "core/waylandserver.h" +#include "greeter/usermodel.h" + +#include "animationconfig.hpp" +#include "appconfig.hpp" +#include "outputconfig.hpp" +#include "seatuserconfig.hpp" +#include "treelandconfig.hpp" +#include "treelanduserconfig.hpp" + +#include "common/treelandlogging.h" +#include "seat/seatmanager.h" + +#include + +#include + +namespace { + +static bool userConfigInitializationFinished(TreelandUserConfig *config) +{ + return config && (config->isInitializeSucceeded() || config->isInitializeFailed()); +} + +static bool seatConfigInitializationFinished(SeatUserDConfig *config) +{ + return config && (config->isInitializeSucceeded() || config->isInitializeFailed()); +} + + +QString configSubpath(const QString &name) +{ + return QStringLiteral("/") + name; +} + +QString seatConfigSubpath(const QString &userName, const QString &seatName) +{ + return configSubpath(userName) + QStringLiteral("/") + seatName; +} + +} + +DConfigManager *DConfigManager::s_instance = nullptr; + +DConfigManager::DConfigManager(QObject *parent) + : QObject(parent) +{ + Q_ASSERT(!s_instance); + s_instance = this; + + m_globalConfig = TreelandConfig::create(QStringLiteral("org.deepin.dde.treeland"), + QString(), + this); + Q_ASSERT(m_globalConfig); + + connect(m_globalConfig, + &TreelandConfig::configInitializeSucceed, + this, + &DConfigManager::onGlobalConfigInitializeSucceed, + Qt::SingleShotConnection); + connect(m_globalConfig, + &TreelandConfig::configInitializeFailed, + this, + &DConfigManager::onGlobalConfigInitializeFailed, + Qt::SingleShotConnection); + + qCInfo(lcTlConfig) << "DConfig manager created; waiting for global configuration initialization"; +} + +DConfigManager::~DConfigManager() +{ + if (s_instance == this) { + s_instance = nullptr; + } +} + +DConfigManager *DConfigManager::instance() +{ + return s_instance; +} + +void DConfigManager::onGlobalConfigInitializeSucceed(DTK_CORE_NAMESPACE::DConfig *) +{ + qCInfo(lcTlConfig) << "Global DConfig initialization succeeded"; + Q_EMIT initializeSucceed(); +} + +void DConfigManager::onGlobalConfigInitializeFailed() +{ + qCCritical(lcTlConfig) << "Global DConfig initialization failed"; + Q_EMIT initializeFailed(); +} + +bool DConfigManager::isInitializeSucceeded() const +{ + return m_globalConfig && m_globalConfig->isInitializeSucceeded(); +} + +bool DConfigManager::isInitializeFailed() const +{ + return !m_globalConfig || m_globalConfig->isInitializeFailed(); +} + +TreelandConfig *DConfigManager::globalConfig() const +{ + return m_globalConfig; +} + +AnimationConfig *DConfigManager::animationConfig(const QString &userName) +{ + if (userName.isEmpty()) + return nullptr; + + if (auto *config = m_animationConfigs.value(userName)) + return config; + + auto *config = AnimationConfig::createByName(QStringLiteral("org.deepin.dde.treeland.animation"), + QStringLiteral("org.deepin.dde.treeland"), + configSubpath(userName), + this); + m_animationConfigs.insert(userName, config); + return config; +} + +AnimationConfig *DConfigManager::initialAnimationConfig() const +{ + return m_initialAnimationConfig; +} + +TreelandUserConfig *DConfigManager::userConfig(const QString &userName) +{ + if (userName.isEmpty()) { + return nullptr; + } + + if (auto *config = m_userConfigs.value(userName)) { + return config; + } + + auto *config = TreelandUserConfig::createByName(QStringLiteral("org.deepin.dde.treeland.user"), + QStringLiteral("org.deepin.dde.treeland"), + configSubpath(userName), + this); + m_userConfigs.insert(userName, config); + return config; +} + +SeatUserDConfig *DConfigManager::userSeatConfig(const QString &userName, const QString &seatName) +{ + if (userName.isEmpty() || seatName.isEmpty()) { + return nullptr; + } + + const auto key = seatConfigSubpath(userName, seatName); + if (auto *config = m_seatUserConfigs.value(key)) { + return config; + } + + auto *config = SeatUserDConfig::createByName( + QStringLiteral("org.deepin.dde.treeland.user.seat"), + QStringLiteral("org.deepin.dde.treeland"), + seatConfigSubpath(userName, seatName), + this); + m_seatUserConfigs.insert(key, config); + return config; +} + +OutputConfig *DConfigManager::outputConfig(const QString &outputName) +{ + if (outputName.isEmpty()) { + return nullptr; + } + + if (auto *config = m_outputConfigs.value(outputName)) { + return config; + } + + auto *config = OutputConfig::createByName(QStringLiteral("org.deepin.dde.treeland.output"), + QStringLiteral("org.deepin.dde.treeland"), + configSubpath(outputName), + this); + m_outputConfigs.insert(outputName, config); + return config; +} + +AppConfig *DConfigManager::appConfig(const QString &appId) +{ + if (appId.isEmpty()) { + return nullptr; + } + + if (auto *config = m_appConfigs.value(appId)) { + return config; + } + + auto *config = AppConfig::create(QStringLiteral("org.deepin.dde.treeland"), + configSubpath(appId), + this); + m_appConfigs.insert(appId, config); + return config; +} + +bool DConfigManager::initializeUserConfigs(const QString &userName) +{ + m_initialAnimationConfig = animationConfig(userName); + m_initialUserConfig = userConfig(userName); + if (!m_initialUserConfig || !m_initialUserConfig->isInitializeSucceeded()) + return false; + + const auto seats = WaylandServer::instance()->seatManager()->seats(); + for (WSeat *seat : seats) { + const auto *seatConfig = userSeatConfig(userName, seat->name()); + if (!seatConfig || !seatConfig->isInitializeSucceeded()) + return false; + } + + return true; +} + +TreelandUserConfig *DConfigManager::initialUserConfig() const +{ + return m_initialUserConfig; +} + +void DConfigManager::initializeActiveUserConfig(WaylandServer *server) +{ + m_server = server; + m_currentUserChangedConnection = connect(m_server->userModel(), &UserModel::currentUserNameChanged, + this, &DConfigManager::updateCurrentUser); + updateCurrentUser(); +} + +void DConfigManager::stopActiveUserConfig() +{ + QObject::disconnect(m_currentUserChangedConnection); + if (m_pendingUserConfig) + QObject::disconnect(static_cast(m_pendingUserConfig), nullptr, this, nullptr); + if (m_pendingSeatConfig) + QObject::disconnect(static_cast(m_pendingSeatConfig), nullptr, this, nullptr); + m_pendingUserName.clear(); + m_pendingUserConfig = nullptr; + m_pendingSeatConfig = nullptr; + m_server = nullptr; +} + +void DConfigManager::updateCurrentUser() +{ + if (!m_server) + return; + + const QString userName = m_server->userModel()->currentUserName(); + auto *configManager = DConfigManager::instance(); + auto *userConfig = configManager ? configManager->userConfig(userName) : m_server->config(); + WSeat *defaultSeat = m_server->seatManager()->getSeat(DEFAULT_SEAT_NAME); + const QString seatName = defaultSeat ? defaultSeat->name() : QStringLiteral(DEFAULT_SEAT_NAME); + auto *seatConfig = configManager ? configManager->userSeatConfig(userName, seatName) : nullptr; + if (!userConfig) { + qCWarning(lcTlConfig) << "Cannot switch to user" << userName + << "because its DConfig object is unavailable"; + return; + } + + if (userConfig == m_server->config() && (!seatConfig || seatConfig == m_pendingSeatConfig)) { + Q_EMIT configReady(userName, userConfig, seatConfig); + return; + } + + if (m_pendingUserConfig) { + QObject::disconnect(static_cast(m_pendingUserConfig), + nullptr, + this, + nullptr); + } + if (m_pendingSeatConfig) { + QObject::disconnect(static_cast(m_pendingSeatConfig), + nullptr, + this, + nullptr); + } + + m_pendingUserName = userName; + m_pendingUserConfig = userConfig; + m_pendingSeatConfig = seatConfig; + + if (!userConfigInitializationFinished(userConfig)) { + connect(userConfig, + &TreelandUserConfig::configInitializeSucceed, + this, + &DConfigManager::onPendingUserConfigInitialized, + Qt::SingleShotConnection); + connect(userConfig, + &TreelandUserConfig::configInitializeFailed, + this, + &DConfigManager::onPendingUserConfigInitialized, + Qt::SingleShotConnection); + } + if (seatConfig && !seatConfigInitializationFinished(seatConfig)) { + connect(seatConfig, + &SeatUserDConfig::configInitializeSucceed, + this, + &DConfigManager::onPendingUserConfigInitialized, + Qt::SingleShotConnection); + connect(seatConfig, + &SeatUserDConfig::configInitializeFailed, + this, + &DConfigManager::onPendingUserConfigInitialized, + Qt::SingleShotConnection); + } + + qCInfo(lcTlConfig) << "Waiting for user DConfig initialization before switching to" + << userName; + onPendingUserConfigInitialized(); +} + +void DConfigManager::onPendingUserConfigInitialized() +{ + if (!m_server) + return; + + if (sender() && sender() != m_pendingUserConfig && sender() != m_pendingSeatConfig) { + return; + } + + if (!userConfigInitializationFinished(m_pendingUserConfig) + || (m_pendingSeatConfig && !seatConfigInitializationFinished(m_pendingSeatConfig))) { + return; + } + + const QString userName = m_pendingUserName; + auto *userConfig = m_pendingUserConfig; + auto *seatConfig = m_pendingSeatConfig; + m_pendingUserName.clear(); + m_pendingUserConfig = nullptr; + m_pendingSeatConfig = nullptr; + + if (m_server->userModel()->currentUserName() != userName) { + qCInfo(lcTlConfig) << "Discarding stale user DConfig initialization for" << userName; + return; + } + + qCInfo(lcTlConfig) << "User DConfig initialization finished for" << userName + << "; applying user configuration"; + if (userConfig->isInitializeFailed() + || (seatConfig && seatConfig->isInitializeFailed())) { + qCWarning(lcTlConfig) << "Using generated defaults for user DConfig" << userName; + } + Q_EMIT configReady(userName, userConfig, seatConfig); +} diff --git a/src/dconfig/dconfigmanager.h b/src/dconfig/dconfigmanager.h new file mode 100644 index 0000000000..4bdb5d830b --- /dev/null +++ b/src/dconfig/dconfigmanager.h @@ -0,0 +1,87 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include + +#include + +class WaylandServer; +class AnimationConfig; +class AppConfig; +class OutputConfig; +class SeatUserDConfig; +class TreelandConfig; +class TreelandUserConfig; + +Q_MOC_INCLUDE("treelanduserconfig.hpp") +Q_MOC_INCLUDE("seatuserconfig.hpp") + +template +bool configurationReady(Config *config) +{ + return config && (config->isInitializeSucceeded() || config->isInitializeFailed()); +} + +class DConfigManager : public QObject +{ + Q_OBJECT +public: + explicit DConfigManager(QObject *parent = nullptr); + ~DConfigManager() override; + + static DConfigManager *instance(); + + bool isInitializeSucceeded() const; + bool isInitializeFailed() const; + + TreelandConfig *globalConfig() const; + AnimationConfig *animationConfig(const QString &userName); + AnimationConfig *initialAnimationConfig() const; + TreelandUserConfig *userConfig(const QString &userName); + SeatUserDConfig *userSeatConfig(const QString &userName, const QString &seatName); + OutputConfig *outputConfig(const QString &outputName); + AppConfig *appConfig(const QString &appId); + + // Creates and caches the initial user's configs. Returns true only when both + // configs have already finished successfully; callers should listen for + // their initialization signals when this returns false. + bool initializeUserConfigs(const QString &userName); + TreelandUserConfig *initialUserConfig() const; + + // Observes active-user changes; the desktop remains responsible for applying + // the ready configuration to input, wallpaper, cursor and workspace services. + void initializeActiveUserConfig(WaylandServer *server); + void stopActiveUserConfig(); + +Q_SIGNALS: + void configReady(const QString &username, TreelandUserConfig *config, SeatUserDConfig *seatConfig); + void initializeSucceed(); + void initializeFailed(); + +private: + void updateCurrentUser(); + void onPendingUserConfigInitialized(); + void onGlobalConfigInitializeSucceed(DTK_CORE_NAMESPACE::DConfig *config); + void onGlobalConfigInitializeFailed(); + + static DConfigManager *s_instance; + + TreelandConfig *m_globalConfig = nullptr; + QHash m_animationConfigs; + AnimationConfig *m_initialAnimationConfig = nullptr; + QHash m_userConfigs; + QHash m_seatUserConfigs; + QHash m_outputConfigs; + QHash m_appConfigs; + TreelandUserConfig *m_initialUserConfig = nullptr; + + WaylandServer *m_server = nullptr; + QMetaObject::Connection m_currentUserChangedConnection; + TreelandUserConfig *m_pendingUserConfig = nullptr; + SeatUserDConfig *m_pendingSeatConfig = nullptr; + QString m_pendingUserName; +}; diff --git a/src/desktop/desktopenvironment.cpp b/src/desktop/desktopenvironment.cpp new file mode 100644 index 0000000000..0606de6dc6 --- /dev/null +++ b/src/desktop/desktopenvironment.cpp @@ -0,0 +1,185 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include "desktopenvironment.h" +#include "core/waylandserver.h" +#include "core/qmlengine.h" +#include "core/shellhandler.h" +#include "core/rootsurfacecontainer.h" +#include "session/sessionswitcher.h" +#include "session/sessioninputchannel.h" +#include "session/sessionoutputmanager.h" +#include "modules/foreign-toplevel/foreigntoplevelmanagerv3.h" +#include "surface/surfacewrapper.h" +#include "workspace/workspace.h" +#include + +DesktopEnvironment::DesktopEnvironment(TreelandUserConfig *config, Workspace *workspace, + WaylandServer *runtime, + InputManager::ConfigProvider seatConfiguration, + InputManager::SeatProvider seats, + WallpaperManager::LibraryProvider library, QObject *parent) + : QObject(parent) + , m_config(config) + , m_workspace(workspace) + , m_runtime(runtime) + , m_windows(new DesktopSurfaceModel(this)) + , m_surfaces(new DesktopSurfaceModel(this)) + , m_input(new InputManager(std::move(seatConfiguration), std::move(seats), runtime->seatManager(), runtime->backend(), this)) + , m_wallpaper(new WallpaperManager(config, workspace, { + std::move(library), + [runtime]() -> const QList & { return runtime->outputs(); }, + [runtime] { return runtime->wallpaperNotifier(); }, + runtime->shellHandler()->wallpaperShell() + }, this)) + , m_switcher(new SessionSwitcher(workspace, runtime->qmlEngine(), runtime, this)) + , m_viewRoot(new QQuickItem(runtime->rootSurfaceContainer())) +{ + m_workspace->setWallpaperManager(m_wallpaper); + m_viewRoot->setParent(this); + auto *engine = runtime->qmlEngine(); + // C++ visual parents have no QML creation context unless explicitly set. + engine->setContextForObject(m_viewRoot, engine->rootContext()); + QQmlEngine::setObjectOwnership(m_viewRoot, QQmlEngine::CppOwnership); + m_viewRoot->setZ(RootSurfaceContainer::NormalZOrder); + m_viewRoot->setVisible(false); + m_viewRoot->setEnabled(false); + connect(runtime, &WaylandServer::activatedSurfaceChanged, + this, &DesktopEnvironment::updateActivatedWindow); +} + +DesktopEnvironment::~DesktopEnvironment() +{ + delete m_viewRoot; +} + +TreelandUserConfig *DesktopEnvironment::config() const { return m_config; } +Workspace *DesktopEnvironment::workspace() const { return m_workspace; } +DesktopSurfaceModel *DesktopEnvironment::windows() const { return m_windows; } +InputManager *DesktopEnvironment::input() const { return m_input; } +WallpaperManager *DesktopEnvironment::wallpaper() const { return m_wallpaper; } +SessionSwitcher *DesktopEnvironment::switcher() const { return m_switcher; } +SessionMultitaskView *DesktopEnvironment::multitaskView() const { return m_multitaskView; } + + +SessionOutputManager *DesktopEnvironment::outputs() const { return m_outputs; } +ForeignToplevelManagerInterfaceV3 *DesktopEnvironment::windowManagement() const { return m_windowManagement; } +SurfaceWrapper *DesktopEnvironment::activatedWindow() const { return m_activatedWindow; } +QQuickItem *DesktopEnvironment::viewRoot() const { return m_viewRoot; } + +void DesktopEnvironment::attachMultitaskView(SessionMultitaskView *view) +{ + Q_ASSERT(!m_multitaskView && view); + m_multitaskView = view; +} + +void DesktopEnvironment::attachOutputs(SessionOutputManager *outputs) +{ + Q_ASSERT(!m_outputs && outputs); + m_outputs = outputs; + outputs->setParent(this); +} + +void DesktopEnvironment::attachWindowManagement(ForeignToplevelManagerInterfaceV3 *manager) +{ + Q_ASSERT(!m_windowManagement && manager); + m_windowManagement = manager; + // Views are permanently wired to this desktop's models and protocol. + m_dockPreview = m_runtime->qmlEngine()->createDockPreview(m_viewRoot, this); + connect(manager, &ForeignToplevelManagerInterfaceV3::requestDockClose, + this, &DesktopEnvironment::closeDockPreview); + connect(manager, &ForeignToplevelManagerInterfaceV3::requestDockPreview, + this, &DesktopEnvironment::showDockPreview); + connect(manager, &ForeignToplevelManagerInterfaceV3::requestDockPreviewTooltip, + this, &DesktopEnvironment::showDockTooltip); +} + +void DesktopEnvironment::activate() +{ + m_viewRoot->setEnabled(true); + m_viewRoot->setVisible(true); + m_switcher->activate(); + m_wallpaper->refresh(); + updateActivatedWindow(); +} + +void DesktopEnvironment::deactivate() +{ + m_switcher->deactivate(); + closeDockPreview(); + m_viewRoot->setEnabled(false); + m_viewRoot->setVisible(false); +} + +void DesktopEnvironment::activateWindow(SurfaceWrapper *window, int reason) +{ + if (m_windows->hasObject(window)) + m_runtime->forceActivateSurface(window, static_cast(reason)); +} + +void DesktopEnvironment::updateActivatedWindow() +{ + auto *window = m_runtime->activatedSurface(); + if (!m_windows->hasObject(window)) + window = nullptr; + if (m_activatedWindow == window) + return; + m_activatedWindow = window; + Q_EMIT activatedWindowChanged(); +} + +void DesktopEnvironment::closeDockPreview() +{ + if (m_dockPreview) + QMetaObject::invokeMethod(m_dockPreview, "close"); +} + +void DesktopEnvironment::showDockPreview(std::vector surfaces, WSurface *target, + QPoint position, ForeignToplevelManagerInterfaceV3::PreviewDirection direction, + ForeignToplevelManagerInterfaceV3::PreviewLayout layout) +{ + auto *window = m_runtime->rootContainer()->getSurface(target); + if (!m_surfaces->hasObject(window)) + return; + QMetaObject::invokeMethod(m_dockPreview, "show", QVariant::fromValue(surfaces), + QVariant::fromValue(window), QVariant::fromValue(position), QVariant::fromValue(direction), + QVariant::fromValue(layout == ForeignToplevelManagerInterfaceV3::PreviewLayout::list)); +} + +void DesktopEnvironment::showDockTooltip(WSurface *surface, WSurface *target, QPoint position, + ForeignToplevelManagerInterfaceV3::PreviewDirection direction) +{ + auto *window = m_runtime->rootContainer()->getSurface(target); + if (!m_surfaces->hasObject(window)) + return; + QMetaObject::invokeMethod(m_dockPreview, "showTooltip", QVariant::fromValue(surface), + QVariant::fromValue(window), QVariant::fromValue(position), QVariant::fromValue(direction)); +} + +void DesktopEnvironment::registerWindow(SurfaceWrapper *window) +{ + m_windows->addObject(window); +} + +void DesktopEnvironment::unregisterWindow(SurfaceWrapper *window) +{ + m_windows->removeObject(window); + m_surfaces->removeObject(window); + if (m_activatedWindow == window) { + m_activatedWindow = nullptr; + Q_EMIT activatedWindowChanged(); + } +} + +DesktopSurfaceModel *DesktopEnvironment::surfaces() const { return m_surfaces; } +void DesktopEnvironment::registerSurface(SurfaceWrapper *surface) { m_surfaces->addObject(surface); } + +SessionInputChannel *DesktopEnvironment::inputChannel() const { return m_inputChannel; } +void DesktopEnvironment::attachInputChannel(SessionInputChannel *channel) +{ + Q_ASSERT(!m_inputChannel && channel); + m_inputChannel = channel; + m_switcher->setInputFilter(channel->filter()); + m_switcher->setShortcutController(channel->shortcuts(), channel->shortcutProtocol()); +} diff --git a/src/desktop/desktopenvironment.h b/src/desktop/desktopenvironment.h new file mode 100644 index 0000000000..ffa65063cc --- /dev/null +++ b/src/desktop/desktopenvironment.h @@ -0,0 +1,108 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "surface/surfacecontainer.h" +#include "input/inputmanager.h" +#include "wallpaper/wallpapermanager.h" +#include "modules/foreign-toplevel/foreigntoplevelmanagerv3.h" +#include + +class Workspace; +class QmlEngine; +class WaylandServer; +class TreelandUserConfig; +class SessionSwitcher; +class SessionMultitaskView; +class SessionInputChannel; +class SessionOutputManager; +class ForeignToplevelManagerInterfaceV3; +class Output; +Q_MOC_INCLUDE("workspace/workspace.h") +Q_MOC_INCLUDE("treelanduserconfig.hpp") +Q_MOC_INCLUDE("session/sessionswitcher.h") +Q_MOC_INCLUDE("session/sessionoutputmanager.h") +Q_MOC_INCLUDE("modules/foreign-toplevel/foreigntoplevelmanagerv3.h") + +class DesktopSurfaceModel : public ObjectListModel +{ + Q_OBJECT + QML_ANONYMOUS +public: + explicit DesktopSurfaceModel(QObject *parent) : ObjectListModel("surface", parent) {} +}; + +// One complete desktop, assembled once with fixed dependencies. Business code +// and QML receive this object; login identity stays outside its public API. +class DesktopEnvironment : public QObject +{ + Q_OBJECT + QML_NAMED_ELEMENT(DesktopEnvironment) + QML_UNCREATABLE("Created by the desktop composition root") + Q_PROPERTY(TreelandUserConfig *config READ config CONSTANT FINAL) + Q_PROPERTY(Workspace *workspace READ workspace CONSTANT FINAL) + Q_PROPERTY(DesktopSurfaceModel *windows READ windows CONSTANT FINAL) + Q_PROPERTY(InputManager *input READ input CONSTANT FINAL) + Q_PROPERTY(WallpaperManager *wallpaper READ wallpaper CONSTANT FINAL) + Q_PROPERTY(SessionSwitcher *switcher READ switcher CONSTANT FINAL) + Q_PROPERTY(SessionOutputManager *outputs READ outputs CONSTANT FINAL) + Q_PROPERTY(ForeignToplevelManagerInterfaceV3 *windowManagement READ windowManagement CONSTANT FINAL) + Q_PROPERTY(SurfaceWrapper *activatedWindow READ activatedWindow NOTIFY activatedWindowChanged FINAL) +public: + DesktopEnvironment(TreelandUserConfig *config, Workspace *workspace, WaylandServer *runtime, + InputManager::ConfigProvider seatConfiguration, InputManager::SeatProvider seats, + WallpaperManager::LibraryProvider library, QObject *parent); + ~DesktopEnvironment() override; + TreelandUserConfig *config() const; + Workspace *workspace() const; + DesktopSurfaceModel *windows() const; + DesktopSurfaceModel *surfaces() const; + void registerSurface(SurfaceWrapper *surface); + InputManager *input() const; + WallpaperManager *wallpaper() const; + SessionSwitcher *switcher() const; + SessionMultitaskView *multitaskView() const; + void attachMultitaskView(SessionMultitaskView *view); + SessionOutputManager *outputs() const; + ForeignToplevelManagerInterfaceV3 *windowManagement() const; + SurfaceWrapper *activatedWindow() const; + QQuickItem *viewRoot() const; + SessionInputChannel *inputChannel() const; + void attachInputChannel(SessionInputChannel *channel); + void attachOutputs(SessionOutputManager *outputs); + void attachWindowManagement(ForeignToplevelManagerInterfaceV3 *manager); + void registerWindow(SurfaceWrapper *window); + void unregisterWindow(SurfaceWrapper *window); + void activate(); + void deactivate(); + Q_INVOKABLE void activateWindow(SurfaceWrapper *window, int reason = Qt::OtherFocusReason); + +Q_SIGNALS: + void activatedWindowChanged(); + +private: + void updateActivatedWindow(); + void closeDockPreview(); + void showDockPreview(std::vector surfaces, + WAYLIB_SERVER_NAMESPACE::WSurface *target, QPoint position, + ForeignToplevelManagerInterfaceV3::PreviewDirection direction, + ForeignToplevelManagerInterfaceV3::PreviewLayout layout); + void showDockTooltip(WAYLIB_SERVER_NAMESPACE::WSurface *surface, WAYLIB_SERVER_NAMESPACE::WSurface *target, QPoint position, + ForeignToplevelManagerInterfaceV3::PreviewDirection direction); + TreelandUserConfig *const m_config; + QPointer m_workspace; + WaylandServer *const m_runtime; + DesktopSurfaceModel *const m_windows; + DesktopSurfaceModel *const m_surfaces; + InputManager *const m_input; + WallpaperManager *const m_wallpaper; + SessionSwitcher *const m_switcher; + SessionMultitaskView *m_multitaskView = nullptr; + SessionInputChannel *m_inputChannel = nullptr; + SessionOutputManager *m_outputs = nullptr; + QPointer m_windowManagement; + QPointer m_viewRoot; + QPointer m_dockPreview; + QPointer m_activatedWindow; +}; diff --git a/src/greeter/greeterproxy.cpp b/src/greeter/greeterproxy.cpp new file mode 100644 index 0000000000..ae435c2aee --- /dev/null +++ b/src/greeter/greeterproxy.cpp @@ -0,0 +1,753 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "greeterproxy.h" +#include "session/sessionmanager.h" + +// Treeland +#include "greeter/sessionmodel.h" +#include "greeter/usermodel.h" +#include "core/waylandserver.h" +#include "session/session.h" +#include "common/treelandlogging.h" +#include "utils/cmdline.h" +#include "lockscreen/lockscreen.h" +#include "lockscreen/lockscreenmanager.h" + +// DDM +#include +#include +#include + +// Qt +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Waylib +#include + +// System +#include +#include +#include + +#include + +#include + +using namespace DDM; + +///////////////////// +// Local Functions // +///////////////////// + +static bool localValidation(const QString &user, const QString &password) +{ + auto utf8Password = password.toUtf8(); + struct pam_conv conv = { + []([[maybe_unused]] int num_msg, + [[maybe_unused]] const struct pam_message **msg, + struct pam_response **resp, + void *appdata_ptr) { + // pam uses free, we must malloc + auto *reply = static_cast(malloc(sizeof(pam_response))); + reply->resp = strdup(static_cast(appdata_ptr)); // Send password to PAM + reply->resp_retcode = 0; + *resp = reply; + return PAM_SUCCESS; + }, + static_cast(utf8Password.data()), + }; + + pam_handle_t *pamh = nullptr; + + int retval = pam_start("login", user.toUtf8().data(), &conv, &pamh); + if (retval != PAM_SUCCESS) { + return false; + } + + retval = pam_authenticate(pamh, 0); + pam_end(pamh, retval); + + return retval == PAM_SUCCESS; +} + +static bool isUserDesktopSession(const QString &id) +{ + const auto encodedId = id.toLocal8Bit(); + const auto *sessionId = encodedId.constData(); + if (sd_session_is_remote(sessionId) != 0) + return false; + + char *type = nullptr; + char *sessionClass = nullptr; + const auto cleanup = qScopeGuard([&] { + free(type); + free(sessionClass); + }); + if (sd_session_get_type(sessionId, &type) < 0 || std::string_view(type) != "wayland") + return false; + if (sd_session_get_class(sessionId, &sessionClass) < 0) + return false; + + const std::string_view desktopClass(sessionClass); + return desktopClass == "user" || desktopClass == "user-early"; +} + +static inline UserModel *userModel() +{ + return WaylandServer::instance()->userModel(); +} + +static inline SessionModel *sessionModel() +{ + return WaylandServer::instance()->sessionModel(); +} + +///////////////////////////////// +// Constructor & Deconstructor // +///////////////////////////////// + +GreeterProxy::GreeterProxy(QObject *parent) + : QObject(parent) +{ + m_socket = new QLocalSocket(this); + auto conn = QDBusConnection::systemBus(); + auto *displayManagerWatcher = + new QDBusServiceWatcher(QStringLiteral("org.deepin.DisplayManager"), + conn, + QDBusServiceWatcher::WatchForRegistration + | QDBusServiceWatcher::WatchForUnregistration, + this); + connect(displayManagerWatcher, + &QDBusServiceWatcher::serviceRegistered, + this, + [this](const QString &) { + qCInfo(lcTlGreeter) << "Display manager service registered"; + updateAuthSocket(); + }); + connect(displayManagerWatcher, + &QDBusServiceWatcher::serviceUnregistered, + this, + [this](const QString &) { + qCWarning(lcTlGreeter) << "Display manager service unregistered"; + m_socket->abort(); + }); + + // connect signals + connect(m_socket, &QLocalSocket::connected, this, &GreeterProxy::connected); + connect(m_socket, &QLocalSocket::disconnected, this, &GreeterProxy::disconnected); + connect(m_socket, &QLocalSocket::readyRead, this, &GreeterProxy::readyRead); + connect(m_socket, &QLocalSocket::errorOccurred, this, &GreeterProxy::error); + + // Fallback: if DDM never decides (ShowGreeter / UserActivateMessage), show + // the greeter after a grace period instead of staying on the wallpaper. + m_undecidedTimer = new QTimer(this); + m_undecidedTimer->setSingleShot(true); + m_undecidedTimer->setInterval(5000); + connect(m_undecidedTimer, &QTimer::timeout, this, [this] { + if (m_undecided) { + qCWarning(lcTlGreeter) << "DDM did not decide in time, showing greeter by fallback"; + lock(); + } + }); + m_undecided = CmdLine::ref().useLockScreen(); + + conn.connect(Logind::serviceName(), + Logind::managerPath(), + Logind::managerIfaceName(), + "SessionNew", + this, + SLOT(onSessionNew(QString, QDBusObjectPath))); + conn.connect(Logind::serviceName(), + Logind::managerPath(), + Logind::managerIfaceName(), + "SessionRemoved", + this, + SLOT(onSessionRemoved(QString, QDBusObjectPath))); + conn.connect(Logind::serviceName(), + Logind::managerPath(), + Logind::managerIfaceName(), + "PrepareForSleep", + this, + SLOT(onPrepareForSleep(bool))); + conn.connect("org.deepin.DisplayManager", + "/org/deepin/DisplayManager", + "org.deepin.DisplayManager", + "AuthInfoChanged", + this, + SLOT(updateAuthSocket())); + + updateAuthSocket(); +} + +GreeterProxy::~GreeterProxy() { } + +//////////////////////// +// Properties setters // +//////////////////////// + +void GreeterProxy::setShowShutdownView(bool show) { + if (m_showShutdownView != show) { + m_showShutdownView = show; + Q_EMIT showShutdownViewChanged(show); + // The focus belongs to one showing of the menu: drop it when the menu + // closes so a later open never inherits this request. + if (!show) + setShutdownMenuFocus(WaylandServer::ShutdownMenuFocus::None); + } +} + +void GreeterProxy::setShutdownMenuFocus(WaylandServer::ShutdownMenuFocus focus) { + if (m_shutdownMenuFocus != focus) { + m_shutdownMenuFocus = focus; + Q_EMIT shutdownMenuFocusChanged(focus); + } +} + +void GreeterProxy::bindLockScreenManager(LockScreenManager *manager) +{ + connect(manager, &LockScreenManager::sessionLockStateRequested, + this, &GreeterProxy::updateLockState, Qt::UniqueConnection); + connect(manager, &LockScreenManager::sessionRelockRequested, + this, &GreeterProxy::onSessionRelockRequested, Qt::UniqueConnection); +} + +void GreeterProxy::updateLockState(bool isLocked) +{ + if (isLocked && !m_isLocked) { + m_isLocked = true; + if (m_undecided) { + m_undecided = false; + m_undecidedTimer->stop(); + Q_EMIT undecidedChanged(false); + } + if (m_lockScreen && !m_lockScreen->isVisible()) + m_lockScreen->lock(); + Q_EMIT lockChanged(true); + } else if (!isLocked && m_isLocked) { + m_failedAttempts = 0; + Q_EMIT failedAttemptsChanged(0); + m_isLocked = false; + if (m_lockScreen && m_lockScreen->isVisible()) + Q_EMIT m_lockScreen->unlock(); + Q_EMIT lockChanged(false); + } + if (m_showShutdownView) + setShowShutdownView(false); +} + +void GreeterProxy::beginAuthentication(const QString &user) +{ + m_authenticationUser = user; + Q_EMIT authPendingChanged(); +} + +void GreeterProxy::finishAuthentication() +{ + if (!authPending()) + return; + + m_authenticationUser.clear(); + Q_EMIT authPendingChanged(); +} + +/////////// +// Slots // +/////////// + +void GreeterProxy::powerOff() +{ + SocketWriter(m_socket) << quint32(GreeterMessages::PowerOff); +} + +void GreeterProxy::reboot() +{ + SocketWriter(m_socket) << quint32(GreeterMessages::Reboot); +} + +void GreeterProxy::suspend() +{ + SocketWriter(m_socket) << quint32(GreeterMessages::Suspend); +} + +void GreeterProxy::hibernate() +{ + SocketWriter(m_socket) << quint32(GreeterMessages::Hibernate); +} + +void GreeterProxy::hybridSleep() +{ + SocketWriter(m_socket) << quint32(GreeterMessages::HybridSleep); +} + +void GreeterProxy::login(const QString &user, const QString &password, const int sessionIndex) +{ + if (authPending()) + return; + + if (!m_socket->isValid()) { + qCDebug(lcTlGreeter) << "Socket is not valid. Local password check."; + if (localValidation(user, password)) { + updateLockState(false); + } else { + Q_EMIT failedAttemptsChanged(++m_failedAttempts); + } + return; + } + + // get model index + QModelIndex index = sessionModel()->index(sessionIndex, 0); + + // send command to the daemon + QString name = sessionModel()->data(index, SessionModel::FileRole).toString(); + qCInfo(lcTlGreeter) << "Logging user" << user << "in with session" << name; + beginAuthentication(user); + SocketWriter(m_socket) << quint32(GreeterMessages::Login) << user << password << name; +} + +void GreeterProxy::unlock(const QString &user, const QString &password) +{ + if (authPending()) + return; + + if (!m_socket->isValid()) { + qCDebug(lcTlGreeter) << "Socket is not valid. Local password check."; + if (localValidation(user, password)) { + updateLockState(false); + } else { + Q_EMIT failedAttemptsChanged(++m_failedAttempts); + } + return; + } + + auto userInfo = userModel()->get(user); + if (userInfo.isValid()) { + qCInfo(lcTlGreeter) << "Unlocking user" << user; + beginAuthentication(user); + SocketWriter(m_socket) << quint32(GreeterMessages::Unlock) << user << password; + } +} + +void GreeterProxy::logout() +{ + auto session = WaylandServer::instance()->sessionManager()->activeSession().lock(); + qCInfo(lcTlGreeter) << "Logging user" << session->username() << "out with session id" << session->id(); + SocketWriter(m_socket) << quint32(GreeterMessages::Logout) << session->id(); +} + +void GreeterProxy::lock() +{ + auto session = WaylandServer::instance()->sessionManager()->activeSession().lock(); + if (!session || session->username() == "dde") { + qCInfo(lcTlGreeter) << "Trying to lock when no user session active, show lockscreen directly."; + updateLockState(true); + return; + } + qCInfo(lcTlGreeter) << "Locking user" << session->username() << "with session id" << session->id(); + SocketWriter(m_socket) << quint32(GreeterMessages::Lock) << session->id(); +} + +void GreeterProxy::onSessionRelockRequested(const QString &id) +{ + SocketWriter(m_socket) << quint32(GreeterMessages::Lock) << id; +} + +////////////////////////////// +// Logind session listeners // +////////////////////////////// + +void GreeterProxy::onSessionNew(const QString &id, const QDBusObjectPath &path) +{ + QByteArray sessionBa = id.toLocal8Bit(); + const char *session = sessionBa.constData(); + char *username = nullptr; + char *service = nullptr; + auto guard = qScopeGuard([&]() { + if (username) + free(username); + if (service) + free(service); + }); + if (sd_session_get_username(session, &username) < 0) { + qCWarning(lcTlGreeter) << "sd_session_get_username() failed for session id:" << id; + return; + } + if (sd_session_get_service(session, &service) < 0) { + qCWarning(lcTlGreeter) << "sd_session_get_service() failed for session id:" << id; + return; + } + + if (strncmp(service, "ddm", 3) == 0 && isUserDesktopSession(id)) { + const QString user = QString::fromLocal8Bit(username); + auto *sessions = WaylandServer::instance()->sessionManager(); + const auto desktop = sessions->ensureSession(id, user); + if (!desktop || !desktop->subscribeLogind(path.path())) { + qCWarning(lcTlGreeter) << "Cannot bind logind path to new desktop:" << id << path.path(); + return; + } + + qCInfo(lcTlGreeter) << "New session added: id=" << id << ", user=" << user; + userModel()->updateUserLoginState(user, true); + + // Activate the desktop after its logind listeners are installed. + Q_EMIT userModel()->userLoggedIn(user, id); + + if (userModel()->currentUserName() == user) + updateLockState(false); + syncHasActiveSession(); + } +} + +void GreeterProxy::restoreLogindPath(const QString &id) +{ + const auto session = WaylandServer::instance()->sessionManager()->sessionForId(id); + if (!session || !session->logindPath().isEmpty()) + return; + auto request = QDBusMessage::createMethodCall(Logind::serviceName(), + Logind::managerPath(), Logind::managerIfaceName(), + QStringLiteral("GetSession")); + request << id; + auto *watcher = new QDBusPendingCallWatcher(QDBusConnection::systemBus().asyncCall(request), this); + connect(watcher, &QDBusPendingCallWatcher::finished, this, + [this, expected = std::weak_ptr(session)](QDBusPendingCallWatcher *reply) { + onLogindPathRestored(reply, expected); + }); +} + +void GreeterProxy::onLogindPathRestored(QDBusPendingCallWatcher *watcher, + const std::weak_ptr &expected) +{ + const QDBusPendingReply reply = *watcher; + watcher->deleteLater(); + const auto session = expected.lock(); + if (!session || WaylandServer::instance()->sessionManager()->sessionForId(session->id()) != session + || !session->logindPath().isEmpty()) + return; + if (reply.isError()) { + qCWarning(lcTlGreeter) << "Cannot restore logind path:" << session->id() << reply.error().message(); + return; + } + if (isUserDesktopSession(session->id()) + && !session->subscribeLogind(reply.value().path())) + qCWarning(lcTlGreeter) << "Cannot bind restored logind path:" << session->id() << reply.value().path(); +} + +void GreeterProxy::onSessionRemoved(const QString &id, const QDBusObjectPath &path) +{ + auto *sessionManager = WaylandServer::instance()->sessionManager(); + auto session = sessionManager->sessionForId(id); + if (session && (session->logindPath().isEmpty() || session->logindPath() == path.path())) { + QString username = session->username(); + qCInfo(lcTlGreeter) << "Session removed: id=" << id << ", user=" << username; + const bool wasActive = sessionManager->activeSession().lock() == session; + userModel()->updateUserLoginState(username, false); + sessionManager->removeSession(session); + // Update before showing the greeter, so the lockscreen is not painted + // as locked for one frame. + syncHasActiveSession(); + if (wasActive) + updateLockState(true); + } +} + +void GreeterProxy::onPrepareForSleep(bool preparing) +{ + if (preparing) + Q_EMIT prepareForSleep(); +} + +bool GreeterProxy::currentUserHasSession() const +{ + const QString user = userModel()->currentUserName(); + // The "dde" sentinel session belongs to the greeter, not to a logged-in user. + if (user.isEmpty() || user == QLatin1String("dde")) + return false; + return WaylandServer::instance()->sessionManager()->sessionForUser(user) != nullptr; +} + +void GreeterProxy::syncHasActiveSession() +{ + const bool hasActiveSession = currentUserHasSession(); + if (m_hasActiveSession == hasActiveSession) + return; + m_hasActiveSession = hasActiveSession; + Q_EMIT hasActiveSessionChanged(hasActiveSession); +} + +/////////////////////// +// DDM Communication // +/////////////////////// + +bool GreeterProxy::isConnected() const +{ + return m_socket->state() == QLocalSocket::ConnectedState; +} + +void GreeterProxy::connected() +{ + qCInfo(lcTlGreeter) << "Connected to the ddm"; + + sendConnect(); +} + +void GreeterProxy::enableHandshake() +{ + if (m_handshakeEnabled) { + return; + } + + m_handshakeEnabled = true; + if (m_undecided) { + m_undecidedTimer->start(); + } + sendConnect(); +} + +void GreeterProxy::sendConnect() +{ + if (!m_handshakeEnabled || !isConnected()) { + return; + } + + SocketWriter(m_socket) + << quint32(GreeterMessages::Connect) + << WaylandServer::instance()->sessionManager()->globalSession()->socket()->fullServerName(); +} + +void GreeterProxy::disconnected() +{ + qCWarning(lcTlGreeter) << "Disconnected from the ddm"; + + finishAuthentication(); + Q_EMIT socketDisconnected(); +} + +void GreeterProxy::error() +{ + qCCritical(lcTlGreeter) << "Socket error: " << m_socket->errorString(); + finishAuthentication(); +} + +void GreeterProxy::readyRead() +{ + // input stream + QDataStream input(m_socket); + + while (input.device()->bytesAvailable()) { + input.startTransaction(); + + // read message + quint32 message = 0; + input >> message; + + switch (DaemonMessages(message)) { + case DaemonMessages::Capabilities: { + // log message + qCDebug(lcTlGreeter) << "Message received from daemon: Capabilities"; + + // read capabilities + quint32 capabilities = 0; + input >> capabilities; + if (!input.commitTransaction()) + return; + + // parse capabilities + m_canPowerOff = capabilities & Capability::PowerOff; + m_canReboot = capabilities & Capability::Reboot; + m_canSuspend = capabilities & Capability::Suspend; + m_canHibernate = capabilities & Capability::Hibernate; + m_canHybridSleep = capabilities & Capability::HybridSleep; + + // Q_EMIT signals + Q_EMIT canPowerOffChanged(m_canPowerOff); + Q_EMIT canRebootChanged(m_canReboot); + Q_EMIT canSuspendChanged(m_canSuspend); + Q_EMIT canHibernateChanged(m_canHibernate); + Q_EMIT canHybridSleepChanged(m_canHybridSleep); + } break; + case DaemonMessages::HostName: { + qCDebug(lcTlGreeter) << "Message received from daemon: HostName"; + + // read host name + input >> m_hostName; + if (!input.commitTransaction()) + return; + + // Q_EMIT signal + Q_EMIT hostNameChanged(m_hostName); + } break; + case DaemonMessages::LastLogin: { + qCDebug(lcTlGreeter) << "Message received from daemon: LastLogin"; + + QString lastUser, lastSession; + input >> lastUser >> lastSession; + if (!input.commitTransaction()) + return; + + userModel()->setLastUser(lastUser); + sessionModel()->setLastSession(lastSession); + Q_EMIT initialUserSelected(); + } break; + case DaemonMessages::SessionDirs: { + qCDebug(lcTlGreeter) << "Message received from daemon: SessionDirs"; + + // read the directories the sessions are installed in + QStringList waylandSessionDirs, x11SessionDirs; + input >> waylandSessionDirs >> x11SessionDirs; + if (!input.commitTransaction()) + return; + + sessionModel()->setSessionDirs(waylandSessionDirs, x11SessionDirs); + } break; + case DaemonMessages::LoginFailed: { + QString user; + input >> user; + if (!input.commitTransaction()) + return; + + qCDebug(lcTlGreeter) << "Message received from daemon: LoginFailed" << user; + + finishAuthentication(); + Q_EMIT failedAttemptsChanged(++m_failedAttempts); + } break; + case DaemonMessages::InformationMessage: { + QString message; + input >> message; + if (!input.commitTransaction()) + return; + + qCDebug(lcTlGreeter) << "Information Message received from daemon: " << message; + Q_EMIT informationMessage(message); + } break; + case DaemonMessages::SwitchToGreeter: { + if (!input.commitTransaction()) + return; + + qCInfo(lcTlGreeter) << "switch to greeter"; + lock(); + } break; + case DaemonMessages::ShowGreeter: { + if (!input.commitTransaction()) + return; + + qCInfo(lcTlGreeter) << "show greeter"; + // Full lock screen transition (LockScreen mode, hidden workspace), + // matching the previous startup behavior of showLockScreen(). + WaylandServer::instance()->showLockScreen(false); + } break; + case DaemonMessages::UserActivateMessage: { + QString user; + QString sessionId; + input >> user >> sessionId; + if (!input.commitTransaction()) + return; + + if (user == m_authenticationUser) + finishAuthentication(); + + // NOTE: maybe DDM will active dde user. + if (!userModel()->getUser(user)) { + qCInfo(lcTlGreeter) << "activate user, but switch to greeter"; + lock(); + break; + } + + if (!WaylandServer::instance()->activateUserSession(user, sessionId)) + break; + + restoreLogindPath(sessionId); + qCInfo(lcTlGreeter) << "activate successfully: " << user << ", XDG_SESSION_ID: " << sessionId; + syncHasActiveSession(); + + updateLockState(false); + + // DDM drives the direct login (autologin / unlock), so the greeter + // must hide unconditionally. onSessionNew's updateLockState(false) may never + // fire (currentUserName mismatch / session service not "ddm"). When + // still in the undecided state, the lock screen surface is visible + // (wallpaper) but not locked, so updateLockState(false) alone would no-op: + // restore the desktop mode and hide the surface explicitly. + if (m_undecided) { + m_undecided = false; + m_undecidedTimer->stop(); + Q_EMIT undecidedChanged(false); + if (m_lockScreen && m_lockScreen->isVisible()) { + Q_EMIT m_lockScreen->unlock(); + m_lockScreen->setVisible(false); + } + } + } break; + case DaemonMessages::UserLoggedIn: { + QString user; + QString sessionId; + input >> user >> sessionId; + if (!input.commitTransaction()) + return; + + // This will happen after a crash recovery of treeland + qCInfo(lcTlGreeter) << "User " << user << " is already logged in"; + auto userPtr = userModel()->getUser(user); + + // TODO: persist users entered via "Other" so they survive in UserModel; then remove + // this fallback + if (!userPtr && userModel()->tryAddNssUser(user)) { + userPtr = userModel()->getUser(user); + } else if (!userPtr) { + // account already listed under another name form (user@domain); match by uid + if (const passwd *pw = ::getpwnam(user.toLocal8Bit().constData())) { + userPtr = userModel()->getUser(static_cast(pw->pw_uid)); + } + } + + if (userPtr) { + userModel()->updateUserLoginState(user, true); + Q_EMIT userModel()->userLoggedIn(user, sessionId); + // Logind does not report the session again after a crash recovery. + syncHasActiveSession(); + restoreLogindPath(sessionId); + } else { + qCWarning(lcTlGreeter) << "User " << user << " logged in but not found"; + } + } break; + default: { + if (!input.commitTransaction()) + return; + qCWarning(lcTlGreeter) << "Unknown message received from daemon." << message; + return; + } + } + } +} + +void GreeterProxy::updateAuthSocket() +{ + QThreadPool::globalInstance()->start([this]() { + QDBusInterface manager("org.deepin.DisplayManager", + "/org/deepin/DisplayManager", + "org.deepin.DisplayManager", + QDBusConnection::systemBus()); + QDBusReply reply = manager.call("AuthInfo"); + if (!reply.isValid()) { + qCWarning(lcTlGreeter) << "Failed to get auth info from display manager:" << reply.error().message(); + return; + } + const QString &socket = reply.value(); + QMetaObject::invokeMethod(this, [this, socket] { + if (m_socket->state() == QLocalSocket::ConnectedState) + m_socket->disconnectFromServer(); + + m_socket->connectToServer(socket); + }); + }); +} diff --git a/src/greeter/greeterproxy.h b/src/greeter/greeterproxy.h new file mode 100644 index 0000000000..c2e0396789 --- /dev/null +++ b/src/greeter/greeterproxy.h @@ -0,0 +1,421 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "QDBusContext" +#include "core/waylandserver.h" +#include +#include +#include +#include + +class QDBusPendingCallWatcher; +class Session; +class QLocalSocket; +class QTimer; + +class LockScreen; +class LockScreenManager; + +class GreeterProxy + : public QObject + , protected QDBusContext +{ + Q_OBJECT + Q_DISABLE_COPY(GreeterProxy) + + QML_NAMED_ELEMENT(GreeterProxy) + QML_SINGLETON + + //////////////// + // Properties // + //////////////// + + Q_PROPERTY(QString hostName READ hostName NOTIFY hostNameChanged) + Q_PROPERTY(bool canPowerOff READ canPowerOff NOTIFY canPowerOffChanged) + Q_PROPERTY(bool canReboot READ canReboot NOTIFY canRebootChanged) + Q_PROPERTY(bool canSuspend READ canSuspend NOTIFY canSuspendChanged) + Q_PROPERTY(bool canHibernate READ canHibernate NOTIFY canHibernateChanged) + Q_PROPERTY(bool canHybridSleep READ canHybridSleep NOTIFY canHybridSleepChanged) + + Q_PROPERTY(bool isLocked READ isLocked NOTIFY lockChanged) + Q_PROPERTY(bool undecided READ undecided NOTIFY undecidedChanged) + Q_PROPERTY(int failedAttempts READ failedAttempts NOTIFY failedAttemptsChanged) + Q_PROPERTY(bool authPending READ authPending NOTIFY authPendingChanged) + Q_PROPERTY(bool showShutdownView READ showShutdownView WRITE setShowShutdownView NOTIFY showShutdownViewChanged) + Q_PROPERTY(WaylandServer::ShutdownMenuFocus shutdownMenuFocus READ shutdownMenuFocus NOTIFY shutdownMenuFocusChanged) + Q_PROPERTY(bool showAnimation READ showAnimation NOTIFY showAnimationChanged) + Q_PROPERTY(bool hasActiveSession READ hasActiveSession NOTIFY hasActiveSessionChanged) + +public: + explicit GreeterProxy(QObject *parent = nullptr); + ~GreeterProxy(); + + void enableHandshake(); + + ////////////////////// + // Property getters // + ////////////////////// + + /** + * @brief Get the host name + * @return Host name + */ + inline const QString &hostName() const { return m_hostName; }; + + /** + * @brief Get the power off capability + * @return true if can power off + */ + inline bool canPowerOff() const { return m_canPowerOff; }; + + /** + * @brief Get the reboot capability + * @return true if can reboot + */ + inline bool canReboot() const { return m_canReboot; }; + + /** + * @brief Get the suspend capability + * @return true if can suspend + */ + inline bool canSuspend() const { return m_canSuspend; }; + + /** + * @brief Get the hibernate capability + * @return true if can hibernate + */ + inline bool canHibernate() const { return m_canHibernate; }; + + /** + * @brief Get the hybrid sleep capability + * @return true if can hybrid sleep + */ + inline bool canHybridSleep() const { return m_canHybridSleep; }; + + /** + * @brief Get the greeter's lock state + * QML elements should listen to this property to show/hide the lock screen + * + * @return true if is locked + */ + inline bool isLocked() const { return m_isLocked; }; + + /** + * @brief Get whether DDM has not decided yet whether to show the greeter + * or to log in directly. The greeter surface (wallpaper) is shown but the + * login UI stays hidden until DDM sends ShowGreeter / UserActivateMessage, + * or the fallback timer fires. + * + * @return true if DDM has not decided yet + */ + inline bool undecided() const { return m_undecided; }; + + /** + * @brief Get the number of failed login attempts (password incorrect) + * The value is reset to 0 when unlocked successfully + * QML elements should listen to this property to detect failed login/unlock attempts + * + * @return Number of failed attempts + */ + inline int failedAttempts() const { return m_failedAttempts; }; + + /** + * @brief Get whether DDM authentication is pending + * QML uses this property to disable the password field and login buttons. + * + * @return true if a login or unlock request is awaiting a result + */ + inline bool authPending() const { return !m_authenticationUser.isEmpty(); }; + + /** + * @brief Get whether the shutdown view is shown + * QML elements should listen to this property to show/hide the shutdown view + * + * @return true if shutdown view is shown + */ + inline bool showShutdownView() const { return m_showShutdownView; }; + + /** + * @brief Get the button the shutdown view should focus when it opens + * QML elements should listen to this property to pick the initial focus. + * + * @return The focus target, WaylandServer::ShutdownMenuFocus::None for no + * preference + */ + inline WaylandServer::ShutdownMenuFocus shutdownMenuFocus() const + { + return m_shutdownMenuFocus; + }; + + /** + * @brief Get whether to show animation on lock/unlock + * QML elements should listen to this property to enable/disable animation + * + * @return true if show animation + */ + inline bool showAnimation() const { return m_showAnimation; }; + + /** + * @brief Get whether the user shown by the lockscreen has a session + * QML elements should listen to this property to show/hide session related UI + * The "dde" sentinel session of the greeter does not count. + * + * @return true if the current user has a session + */ + inline bool hasActiveSession() const { return m_hasActiveSession; }; + + ///////////////////////////// + // Public property setters // + ///////////////////////////// + + /** + * @brief Set whether to show the shutdown view + * QML elements should set this property to show/hide the shutdown view + * + * @param show true to show shutdown view, false to hide + */ + void setShowShutdownView(bool show); + + /** + * @brief Set the button the shutdown view should focus when it opens + * + * @param focus The focus target, WaylandServer::ShutdownMenuFocus::None for + * no preference + */ + void setShutdownMenuFocus(WaylandServer::ShutdownMenuFocus focus); + + //////////////////// + // Public methods // + //////////////////// + + /** + * @brief Check if the DDM socket is connected + * @return true if connected + */ + bool isConnected() const; + + /** + * @brief Set the LockScreen instance + * This is necessary for the GreeterProxy to control the lock screen visibility + * + * @param lockScreen LockScreen instance + */ + inline void setLockScreen(LockScreen *lockScreen) { m_lockScreen = lockScreen; }; + + /** + * @brief Recompute hasActiveSession and emit the change if it flipped + */ + void syncHasActiveSession(); + + void bindLockScreenManager(LockScreenManager *manager); + +public Q_SLOTS: + + ///////////// + // Actions // + ///////////// + + /** @brief Power off the system. Need to be connected with DDM. */ + void powerOff(); + + /** @brief Reboot the system. Need to be connected with DDM. */ + void reboot(); + + /** @brief Suspend the system. Need to be connected with DDM. */ + void suspend(); + + /** @brief Hibernate the system. Need to be connected with DDM. */ + void hibernate(); + + /** @brief Hybrid sleep the system. Need to be connected with DDM. */ + void hybridSleep(); + + /** @brief Login given user with given password for given desktop session. + * This function will call DDM to perform the login. + * + * Listen to org.freedesktop.login1.Manager.SessionNew signal to + * detect if new sessions successfully logged in, and listen to + * failedAttempts property to detect failed login attempts. + * + * @param user Username + * @param password Password + * @param sessionIndex Index of the desktop session in the session model + */ + void login(const QString &user, const QString &password, int sessionIndex); + + /** @brief Lock the current active session. + * This function will call DDM to perform the lock. + * + * Listen to org.freedesktop.login1.Session.Lock signal to detect + * if the session is successfully locked. + */ + void lock(); + + /** @brief Unlock given user with given password. + * This function will call DDM to perform the unlock. + * + * Listen to org.freedesktop.login1.Session.Unlock signal to + * detect if the session is successfully unlocked, and listen to + * failedAttempts property to detect failed unlock attempts. + * + * @param user Username + * @param password Password + */ + void unlock(const QString &user, const QString &password); + + /** @brief Logout the current active session. + * This function will call DDM to perform the logout. + * + * Listen to org.freedesktop.login1.Manager.SessionRemoved signal to + * detect if the session is successfully logged out. + */ + void logout(); + +private Q_SLOTS: + + /////////////////////// + // DDM Communication // + /////////////////////// + + void connected(); + void disconnected(); + void readyRead(); + void error(); + + ////////////////////////////// + // Logind session listeners // + ////////////////////////////// + + /** @brief Listener for org.freederktop.login1.Manager.SessionNew */ + void onSessionNew(const QString &id, const QDBusObjectPath &session); + + /** @brief Listener for org.freederktop.login1.Manager.SessionRemoved */ + void onSessionRemoved(const QString &id, const QDBusObjectPath &session); + + /** @brief Listener for org.freedesktop.login1.Manager.PrepareForSleep */ + void onPrepareForSleep(bool preparing); +Q_SIGNALS: + void informationMessage(const QString &message); + + void switchUser(); + void prepareForSleep(); + + void socketDisconnected(); + void initialUserSelected(); + + ///////////////////////////// + // Property change signals // + ///////////////////////////// + + /** @brief Emitted when host name changes. See hostName() */ + void hostNameChanged(const QString &hostName); + + /** @brief Emitted when power off capability changes. See canPowerOff() */ + void canPowerOffChanged (bool canPowerOff); + + /** @brief Emitted when reboot capability changes. See canReboot() */ + void canRebootChanged (bool canReboot); + + /** @brief Emitted when suspend capability changes. See canSuspend() */ + void canSuspendChanged (bool canSuspend); + + /** @brief Emitted when hibernate capability changes. See canHibernate() */ + void canHibernateChanged (bool canHibernate); + + /** @brief Emitted when hybrid sleep capability changes. See canHybridSleep() */ + void canHybridSleepChanged (bool canHybridSleep); + + /** @brief Emitted when lock state changes. See isLocked() */ + void lockChanged (bool isLocked); + + /** @brief Emitted when undecided state changes. See undecided() */ + void undecidedChanged (bool undecided); + + /** @brief Emitted when failed attempts changes. See failedAttempts() */ + void failedAttemptsChanged (int failedAttempts); + + /** @brief Emitted when the authentication pending state changes. See authPending() */ + void authPendingChanged(); + + /** @brief Emitted when showShutdownView changes. See showShutdownView() */ + void showShutdownViewChanged (bool showShutdownView); + + /** @brief Emitted when shutdownMenuFocus changes. See shutdownMenuFocus() */ + void shutdownMenuFocusChanged(WaylandServer::ShutdownMenuFocus focus); + + /** @brief Emitted when showAnimation changes. See showAnimation() */ + void showAnimationChanged (bool showAnimation); + + /** @brief Emitted when hasActiveSession changes. See hasActiveSession() */ + void hasActiveSessionChanged (bool hasActiveSession); + +private: + + ///////////////////// + // Private methods // + ///////////////////// + + /** + * @brief Set the lock state + * This is the internal method to set the lock state (lockscreen + * visibility, etc.) directly without calling DDM and + * communicating with systemd-logind. + * + * @param isLocked true to set locked, false to set unlocked + */ + void updateLockState(bool isLocked); + + void onSessionRelockRequested(const QString &id); + + /** + * @brief Start waiting for the given user's authentication result. + * + * @param user Username submitted in the login or unlock request + */ + void beginAuthentication(const QString &user); + + /** @brief Clear the pending authentication request, if any. */ + void finishAuthentication(); + + /** + * @brief Update the DDM communication socket + */ + void updateAuthSocket(); + void sendConnect(); + void restoreLogindPath(const QString &id); + void onLogindPathRestored(QDBusPendingCallWatcher *watcher, + const std::weak_ptr &expected); + + /** + * @brief Check whether the user shown by the lockscreen has a session + */ + bool currentUserHasSession() const; + + ///////////////////// + // Property values // + ///////////////////// + + QLocalSocket *m_socket{ nullptr }; + LockScreen *m_lockScreen{ nullptr }; + + QString m_hostName{}; + + bool m_canPowerOff { false }; + bool m_canReboot { false }; + bool m_canSuspend { false }; + bool m_canHibernate { false }; + bool m_canHybridSleep { false }; + + bool m_isLocked { false }; + bool m_undecided { true }; + QTimer *m_undecidedTimer{ nullptr }; + int m_failedAttempts { 0 }; + QString m_authenticationUser; + bool m_showShutdownView { false }; + WaylandServer::ShutdownMenuFocus m_shutdownMenuFocus { WaylandServer::ShutdownMenuFocus::None }; + bool m_showAnimation { true }; + bool m_hasActiveSession { false }; + bool m_handshakeEnabled { false }; +}; diff --git a/src/greeter/loginstatequery.cpp b/src/greeter/loginstatequery.cpp new file mode 100644 index 0000000000..9ff718769e --- /dev/null +++ b/src/greeter/loginstatequery.cpp @@ -0,0 +1,112 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "loginstatequery.h" + +#include "common/treelandlogging.h" +#include "utils/loginddbustypes.h" + +#include +#include +#include +#include +#include + +LoginStateQuery::LoginStateQuery(QObject *parent) + : QObject(parent) +{ +} + +void LoginStateQuery::start() +{ + if (m_started) { + return; + } + + m_started = true; + + auto message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.login1"), + QStringLiteral("/org/freedesktop/login1"), + QStringLiteral("org.freedesktop.login1.Manager"), + QStringLiteral("ListSessions")); + auto *watcher = new QDBusPendingCallWatcher( + QDBusConnection::systemBus().asyncCall(message), this); + connect(watcher, &QDBusPendingCallWatcher::finished, this, &LoginStateQuery::onSessionsQueried); +} + +void LoginStateQuery::onSessionsQueried(QDBusPendingCallWatcher *watcher) +{ + watcher->deleteLater(); + if (m_finished) { + return; + } + + const QDBusPendingReply reply = *watcher; + if (reply.isError()) { + qCWarning(lcTlHooks) << "Cannot query logind sessions; running prestart scripts:" + << reply.error().message(); + finish(false); + return; + } + + const auto sessions = reply.value(); + m_pendingSessionQueries = sessions.size(); + if (sessions.isEmpty()) { + finish(false); + return; + } + + // Query session properties in parallel. + for (const auto &session : sessions) { + auto message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.login1"), + session.sessionPath.path(), + QStringLiteral("org.freedesktop.DBus.Properties"), + QStringLiteral("GetAll")); + message << QStringLiteral("org.freedesktop.login1.Session"); + auto *propertiesWatcher = new QDBusPendingCallWatcher( + QDBusConnection::systemBus().asyncCall(message), this); + propertiesWatcher->setProperty("sessionId", session.sessionId); + connect(propertiesWatcher, &QDBusPendingCallWatcher::finished, + this, &LoginStateQuery::onSessionPropertiesQueried); + } +} + +void LoginStateQuery::onSessionPropertiesQueried(QDBusPendingCallWatcher *watcher) +{ + watcher->deleteLater(); + if (m_finished) { + return; + } + + const QDBusPendingReply reply = *watcher; + if (reply.isError()) { + qCWarning(lcTlHooks) << "Cannot query logind session properties:" + << watcher->property("sessionId").toString() + << reply.error().message(); + } else { + const auto properties = reply.value(); + const auto type = properties.value(QStringLiteral("Type")).toString(); + const auto state = properties.value(QStringLiteral("State")).toString(); + if ((type == QLatin1String("wayland") || type == QLatin1String("x11")) + && (state == QLatin1String("active") || state == QLatin1String("online"))) { + qCInfo(lcTlHooks) << "Logind graphical session exists; skipping prestart scripts:" + << watcher->property("sessionId").toString() << type << state; + finish(true); + return; + } + } + + if (--m_pendingSessionQueries == 0) { + finish(false); + } +} + +void LoginStateQuery::finish(bool hasLoggedInUser) +{ + if (m_finished) { + return; + } + + m_finished = true; + Q_EMIT finished(hasLoggedInUser); +} diff --git a/src/greeter/loginstatequery.h b/src/greeter/loginstatequery.h new file mode 100644 index 0000000000..5463e5b967 --- /dev/null +++ b/src/greeter/loginstatequery.h @@ -0,0 +1,30 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +class QDBusPendingCallWatcher; + +class LoginStateQuery : public QObject +{ + Q_OBJECT +public: + explicit LoginStateQuery(QObject *parent = nullptr); + + void start(); + +Q_SIGNALS: + // False also covers an unsuccessful query. + void finished(bool hasLoggedInUser); + +private: + void onSessionsQueried(QDBusPendingCallWatcher *watcher); + void onSessionPropertiesQueried(QDBusPendingCallWatcher *watcher); + void finish(bool hasLoggedInUser); + + qsizetype m_pendingSessionQueries{ 0 }; + bool m_started{ false }; + bool m_finished{ false }; +}; diff --git a/src/greeter/sessionmodel.cpp b/src/greeter/sessionmodel.cpp new file mode 100644 index 0000000000..9aa61abedd --- /dev/null +++ b/src/greeter/sessionmodel.cpp @@ -0,0 +1,221 @@ +/*************************************************************************** + * Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. + * Copyright (c) 2015-2016 Pier Luigi Fiorini + * Copyright (c) 2013 Abdurrahman AVCI + * + * 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 2 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, write to the + * Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + ***************************************************************************/ + +#include "sessionmodel.h" + +#include + +#include +#include +#include +#include +#include + +namespace { + QStringList sessionFiles(const QStringList &dirPaths) + { + QStringList files; + QSet taken; + for (const auto &dirPath : dirPaths) { + QDir dir(dirPath); + dir.setNameFilters(QStringList() << QStringLiteral("*.desktop")); + dir.setFilter(QDir::Files); + for (const QString &entry : dir.entryList()) { + if (taken.contains(entry)) + continue; + taken.insert(entry); + files += dir.absoluteFilePath(entry); + } + } + return files; + } + + // TryExec names a program that must be available for the session to be + // offered: an absolute path, or a name looked up in $PATH. An empty + // TryExec does not restrict the session. + bool tryExecAllowed(const QString &tryExec) + { + if (tryExec.isEmpty()) + return true; + + QFileInfo fi(tryExec); + if (fi.isAbsolute()) + return fi.exists() && fi.isExecutable(); + + const QStringList pathList = QProcessEnvironment::systemEnvironment() + .value(QStringLiteral("PATH")) + .split(QLatin1Char(':')); + for (const QString &path : pathList) { + fi.setFile(QDir(path), tryExec); + if (fi.exists() && fi.isExecutable()) + return true; + } + return false; + } +} + +SessionModel::SessionModel(QObject *parent) + : QAbstractListModel(parent) +{ +} + +void SessionModel::setSessionDirs(const QStringList &waylandSessionDirs, + const QStringList &x11SessionDirs) +{ + m_waylandSessionDirs = waylandSessionDirs; + m_x11SessionDirs = x11SessionDirs; + + reload(); +} + +void SessionModel::setLastSession(const QString &filePath) +{ + m_lastSession = filePath; + + const int index = indexOfSession(filePath); + if (index >= 0) + setCurrentIndex(index); +} + +void SessionModel::reload() +{ + // Recheck for flag to show Wayland sessions + const bool dri_active = QFileInfo::exists(QStringLiteral("/dev/dri")); + + // Keep the session the user selected across reloads, e.g. when a package + // installs or removes a session file. + QString currentSession; + if (m_currentIndex >= 0 && m_currentIndex < m_sessions.size()) + currentSession = m_sessions.at(m_currentIndex).filePath; + + beginResetModel(); + m_sessions.clear(); + m_displayNames.clear(); + m_currentIndex = 0; + if (dri_active) + populate(true, m_waylandSessionDirs); + populate(false, m_x11SessionDirs); + + int index = indexOfSession(currentSession); + if (index < 0) + index = indexOfSession(m_lastSession); + if (index >= 0) + m_currentIndex = index; + + endResetModel(); + Q_EMIT currentIndexChanged(m_currentIndex); +} + +int SessionModel::indexOfSession(const QString &filePath) const +{ + if (filePath.isEmpty()) + return -1; + + for (int i = 0; i < m_sessions.size(); ++i) { + if (m_sessions.at(i).filePath == filePath) + return i; + } + return -1; +} + +QHash SessionModel::roleNames() const +{ + // set role names + QHash roleNames; + roleNames[DirectoryRole] = QByteArrayLiteral("directory"); + roleNames[FileRole] = QByteArrayLiteral("file"); + roleNames[NameRole] = QByteArrayLiteral("name"); + roleNames[ExecRole] = QByteArrayLiteral("exec"); + roleNames[CommentRole] = QByteArrayLiteral("comment"); + + return roleNames; +} + +void SessionModel::setCurrentIndex(int index) +{ + if (m_currentIndex != index) { + m_currentIndex = index; + Q_EMIT currentIndexChanged(index); + } +} + +int SessionModel::rowCount(const QModelIndex &parent) const +{ + return parent.isValid() ? 0 : static_cast(m_sessions.length()); +} + +QVariant SessionModel::data(const QModelIndex &index, int role) const +{ + if (index.row() < 0 || index.row() >= m_sessions.count()) + return QVariant(); + + // get session + const SessionEntry &session = m_sessions.at(index.row()); + + // return correct value + switch (role) { + case DirectoryRole: + return QFileInfo(session.filePath).absolutePath(); + case FileRole: + return session.filePath; + case NameRole: + if (m_displayNames.count(session.displayName) > 1 && session.wayland) + return tr("%1 (Wayland)").arg(session.displayName); + return session.displayName; + case ExecRole: + return session.exec; + case CommentRole: + return session.comment; + default: + break; + } + + // return empty value + return QVariant(); +} + +void SessionModel::populate(bool wayland, const QStringList &dirPaths) +{ + for (const QString &filePath : sessionFiles(dirPaths)) { + // read session + const Dtk::Core::DDesktopEntry entry(filePath); + if (entry.status() != Dtk::Core::DDesktopEntry::NoError) + continue; + + SessionEntry session; + session.wayland = wayland; + session.filePath = filePath; + session.displayName = entry.name(); + session.exec = entry.rawValue(QStringLiteral("Exec")); + session.comment = entry.comment(); + session.tryExec = entry.rawValue(QStringLiteral("TryExec")); + + if (!tryExecAllowed(session.tryExec)) + continue; + + // add to sessions list + m_displayNames.append(session.displayName); + if (session.displayName == QStringLiteral("Treeland")) + m_sessions.prepend(session); + else + m_sessions.push_back(session); + } +} diff --git a/src/greeter/sessionmodel.h b/src/greeter/sessionmodel.h new file mode 100644 index 0000000000..2d66bb814b --- /dev/null +++ b/src/greeter/sessionmodel.h @@ -0,0 +1,96 @@ +/************************************************************************** + * Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. + * Copyright (c) 2015-2016 Pier Luigi Fiorini + * Copyright (c) 2013 Abdurrahman AVCI + * + * 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 2 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, write to the + * Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + ***************************************************************************/ + +#pragma once + +#include +#include +#include + +class SessionModel : public QAbstractListModel +{ + Q_OBJECT + Q_DISABLE_COPY(SessionModel) + Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged) + QML_NAMED_ELEMENT(SessionModel) + QML_SINGLETON + +public: + enum SessionRole + { + DirectoryRole = Qt::UserRole + 1, + FileRole, + NameRole, + ExecRole, + CommentRole + }; + Q_ENUM(SessionRole) + + SessionModel(QObject *parent = nullptr); + + QHash roleNames() const override; + + inline int currentIndex() const { return m_currentIndex; }; + void setCurrentIndex(int index); + + // Directories the sessions are installed in, sent by DDM when the greeter + // connects. Sessions are listed for them, nothing is listed before. + void setSessionDirs(const QStringList &waylandSessionDirs, const QStringList &x11SessionDirs); + + // Session of the last successful login, sent by DDM. Applied whenever the + // model is populated or the value arrives after the dirs. + void setLastSession(const QString &filePath); + + // Re-reads the session files. Called by the greeter each time the session + // list is about to be shown, so no filesystem watching is needed. + Q_INVOKABLE void reload(); + + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + +Q_SIGNALS: + void currentIndexChanged(int index); + +private: + // A session desktop file, parsed for the fields the greeter shows and + // reports back to DDM. + struct SessionEntry + { + bool wayland; // listed from the Wayland session directories + QString filePath; // absolute path of the desktop file + QString displayName; + QString exec; + QString comment; + QString tryExec; + }; + + void populate(bool wayland, const QStringList &dirPaths); + int indexOfSession(const QString &filePath) const; + + int m_currentIndex{ 0 }; + QString m_lastSession{}; + QStringList m_displayNames{}; + QList m_sessions{}; + QStringList m_waylandSessionDirs{}; + QStringList m_x11SessionDirs{}; +}; + +QML_DECLARE_TYPE(SessionModel) diff --git a/src/greeter/user.cpp b/src/greeter/user.cpp new file mode 100644 index 0000000000..443d2ff7d2 --- /dev/null +++ b/src/greeter/user.cpp @@ -0,0 +1,201 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "user.h" + +#include "common/treelandlogging.h" + +#include +#include + +struct UserPrivate +{ + bool loggedIn{ false }; + bool noPasswdLogin{ false }; + quint64 uid{ 0 }; + quint64 gid{ 0 }; + qint64 createdTime{ 0 }; + QString userName; + QString fullName; + QString homeDir; + QUrl icon; + QLocale locale; + AccountTypes identity; + QString passwordHint; + QString limitTime; + AccountsUserPtr inter{ nullptr }; + std::shared_ptr waylandSocket; + + void updateUserData(); +}; + +void UserPrivate::updateUserData() +{ + noPasswdLogin = inter->noPasswdLogin(); + identity = inter->accountType(); + uid = inter->UID(); + gid = inter->GID(); + userName = inter->userName(); + fullName = inter->fullName(); + homeDir = inter->homeDir(); + icon = inter->iconFile(); + passwordHint = inter->passwordHint(); + locale = QLocale{ inter->locale() }; +} + +User::User(AccountsUserPtr ptr) + : d(new UserPrivate{}) +{ + d->inter = std::move(ptr); + + if (!d->inter) { + qCFatal(lcTlGreeter) << "connect to AccountService Failed"; + } + + connect(d->inter.data(), &DAccountsUser::userDataChanged, this, &User::updateUserData); + connect(d->inter.data(), &DAccountsUser::iconFileChanged, this, [this](const QUrl &icon) { + if (d->icon == icon) + return; + + d->icon = icon; + }); + + d->updateUserData(); + const auto createdTime = d->inter->createdTime(); + if (createdTime.isValid()) + d->createdTime = qMax(0, createdTime.toSecsSinceEpoch()); +} + +User::User(const QString &userName, uid_t uid, gid_t gid, + const QString &homeDir, const QString &fullName) + : d(new UserPrivate{}) +{ + d->userName = userName; + d->uid = uid; + d->gid = gid; + d->homeDir = homeDir; + d->fullName = fullName; + d->identity = AccountTypes::Default; + d->noPasswdLogin = false; +} + +User::~User() +{ + delete d; +} + +void User::updateUserData() +{ + d->updateUserData(); +} + +bool User::noPasswdLogin() const noexcept +{ + return d->noPasswdLogin; +} + +QString User::identity() const noexcept +{ + return toString(d->identity); +} + +quint64 User::UID() const noexcept +{ + return d->uid; +} + +qint64 User::createdTime() const noexcept +{ + return d->createdTime; +} + +quint64 User::GID() const noexcept +{ + return d->gid; +} + +const QString &User::userName() const noexcept +{ + return d->userName; +} + +const QString &User::fullName() const noexcept +{ + return d->fullName; +} + +const QString &User::homeDir() const noexcept +{ + return d->homeDir; +} + +const QUrl &User::iconFile() const noexcept +{ + return d->icon; +} + +const QString &User::passwordHint() const noexcept +{ + return d->passwordHint; +} + +const QLocale &User::locale() const noexcept +{ + return d->locale; +} + +bool User::loggedIn() const noexcept +{ + return d->loggedIn; +} + +void User::setLoggedIn(bool newState) const noexcept +{ + d->loggedIn = newState; +} + +void User::updateLimitTime(const QString &time) noexcept +{ + d->limitTime = time; + Q_EMIT limitTimeChanged(time); +} + +void User::setWaylandSocket(std::shared_ptr socket) +{ + d->waylandSocket = socket; +} + +void User::merge(const User &other) +{ + if (!other.d->inter) { + return; + } + + if (other.d->createdTime != 0) + d->createdTime = other.d->createdTime; + d->icon = other.d->icon; + d->passwordHint = other.d->passwordHint; + d->locale = other.d->locale; + d->identity = other.d->identity; + d->noPasswdLogin = other.d->noPasswdLogin; +} + +std::shared_ptr User::waylandSocket() const +{ + return d->waylandSocket; +} + +QString User::toString(AccountTypes type) noexcept +{ + DACCOUNTS_USE_NAMESPACE + switch (type) { + case AccountTypes::Admin: + return tr("Administrator"); + case AccountTypes::Default: + return tr("Standard User"); + default: + qCWarning(lcTlGreeter) << "ignore other types."; + } + + return {}; +} diff --git a/src/greeter/user.h b/src/greeter/user.h new file mode 100644 index 0000000000..6b7ffa8510 --- /dev/null +++ b/src/greeter/user.h @@ -0,0 +1,56 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef USER_H +#define USER_H + +#include + +#include +#include +#include + +DACCOUNTS_USE_NAMESPACE + +struct UserPrivate; + +class User : public QObject +{ + Q_OBJECT +public: + explicit User(AccountsUserPtr ptr); + explicit User(const QString &userName, uid_t uid, gid_t gid, + const QString &homeDir, const QString &fullName = {}); + ~User() override; + + [[nodiscard]] bool noPasswdLogin() const noexcept; + [[nodiscard]] QString identity() const noexcept; + [[nodiscard]] quint64 UID() const noexcept; + [[nodiscard]] qint64 createdTime() const noexcept; + [[nodiscard]] quint64 GID() const noexcept; + [[nodiscard]] const QString &userName() const noexcept; + [[nodiscard]] const QString &fullName() const noexcept; + [[nodiscard]] const QString &homeDir() const noexcept; + [[nodiscard]] const QUrl &iconFile() const noexcept; + [[nodiscard]] const QString &passwordHint() const noexcept; + [[nodiscard]] bool loggedIn() const noexcept; + [[nodiscard]] const QLocale &locale() const noexcept; + [[nodiscard]] static QString toString(AccountTypes type) noexcept; + void setLoggedIn(bool newState) const noexcept; + void updateLimitTime(const QString &time) noexcept; + + void setWaylandSocket(std::shared_ptr); + std::shared_ptr waylandSocket() const; + + void merge(const User &other); + +Q_SIGNALS: + void limitTimeChanged(const QString &time); + +private: + void updateUserData(); + + UserPrivate *d{ nullptr }; +}; + +#endif diff --git a/src/greeter/usermodel.cpp b/src/greeter/usermodel.cpp new file mode 100644 index 0000000000..961a7c82ad --- /dev/null +++ b/src/greeter/usermodel.cpp @@ -0,0 +1,445 @@ +/*************************************************************************** + * Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. + * Copyright (c) 2013 Abdurrahman AVCI + * + * 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 2 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, write to the + * Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + ***************************************************************************/ + +#include "usermodel.h" +#include "session/sessionmanager.h" + +#include "common/treelandlogging.h" +#include "core/waylandserver.h" +#include "session/session.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +DACCOUNTS_USE_NAMESPACE + +struct UserModelPrivate +{ + bool containsAllUsers{ true }; + int lastIndex{ 0 }; + QString lastUserName; + QString currentUserName; + DAccountsManager manager; + QTranslator *lastTrans{ nullptr }; + QList users; +}; + +UserModel::UserModel(QObject *parent) + : QAbstractListModel(parent) + , d(new UserModelPrivate()) +{ + connect(&d->manager, &DAccountsManager::UserAdded, this, &UserModel::onUserAdded); + connect(&d->manager, &DAccountsManager::UserDeleted, this, &UserModel::onUserDeleted); + + auto userList = d->manager.userList(); + if (!userList) { + qFatal() << userList.error(); + } + + const auto uids = userList.value(); + for (auto uid : uids) { + auto user = d->manager.findUserById(uid); + if (!user) { + qCWarning(lcTlGreeter) << "Failed to find user by ID:" << user.error(); + continue; + } + + addUser(std::make_unique(std::move(user).value())); + } + + // The last user is sent by DDM once the greeter connects; until then + // fall back to the running user or the first available one. + if (d->currentUserName.isEmpty()) { + QString runningUser; + uid_t runningUid = 0; + if (const passwd *pw = getpwuid(getuid())) { + runningUser = QString::fromLocal8Bit(pw->pw_name); + runningUid = pw->pw_uid; + } + + if (runningUser != QLatin1String("dde") && runningUid != 0) { + UserPtr record = getUser(runningUid); + if (!record && tryAddNssUser(runningUser)) { + record = getUser(runningUid); + } + if (record) { + d->currentUserName = record->userName(); + d->lastIndex = d->users.indexOf(record); + } + } + if (d->currentUserName.isEmpty() && !d->users.isEmpty()) { + d->currentUserName = d->users.first()->userName(); + } + + qCWarning(lcTlGreeter) << "No last user state, greeter starts with" << d->currentUserName; + } +} + +UserModel::~UserModel() +{ + delete d; +} + +QHash UserModel::roleNames() const +{ + // set role names + QHash names; + names[NameRole] = QByteArrayLiteral("name"); + names[RealNameRole] = QByteArrayLiteral("realName"); + names[HomeDirRole] = QByteArrayLiteral("homeDir"); + names[IconRole] = QByteArrayLiteral("icon"); + names[NoPasswordRole] = QByteArrayLiteral("noPassword"); + names[LoggedInRole] = QByteArrayLiteral("loggedIn"); + names[IdentityRole] = QByteArrayLiteral("identity"); + names[PasswordHintRole] = QByteArrayLiteral("passwordHint"); + names[LocaleRole] = QByteArrayLiteral("locale"); + return names; +} + +int UserModel::lastIndex() const +{ + return d->lastIndex; +} + +QString UserModel::lastUser() const +{ + return d->lastUserName; +} + +int UserModel::rowCount(const QModelIndex &parent) const +{ + return parent.isValid() ? 0 : static_cast(d->users.length()); +} + +bool UserModel::addUser(UserPtr user) +{ + const QString userName = user->userName(); + if (userName.isEmpty() || getUser(userName) || (user->UID() != 0 && getUser(user->UID()))) { + qCInfo(lcTlGreeter) << "User" << userName << "already listed, merge richer data"; + UserPtr existing = getUser(userName); + if (!existing) { + existing = getUser(user->UID()); + } + if (existing) { + if (user->createdTime() != 0 && user->createdTime() != existing->createdTime()) { + beginResetModel(); + existing->merge(*user); + sortUsers(); + endResetModel(); + return false; + } + const int row = static_cast(d->users.indexOf(existing)); + existing->merge(*user); + Q_EMIT dataChanged(index(row), index(row)); + } + return false; + } + + beginResetModel(); + d->users.emplace_back(std::move(user)); + sortUsers(); + endResetModel(); + + Q_EMIT countChanged(); + return true; +} + +void UserModel::sortUsers() +{ + std::sort(d->users.begin(), d->users.end(), [](const UserPtr &u1, const UserPtr &u2) { + const auto t1 = u1->createdTime(); + const auto t2 = u2->createdTime(); + if (t1 == 0 || t2 == 0) + return t1 != 0; + return t1 < t2; + }); +} + +void UserModel::updateUserLoginState(const QString &username, bool loggedIn) +{ + // TODO: May remove once UserModel is guaranteed to resolve every loggable + // user (consider whether users not manually added can still log in directly). + UserPtr target = getUser(username); + if (!target && loggedIn && tryAddNssUser(username)) { + target = getUser(username); + } + if (!target) { + if (const passwd *pw = ::getpwnam(username.toLocal8Bit().constData())) { + target = getUser(static_cast(pw->pw_uid)); + } + } + if (!target && loggedIn) { + qCWarning(lcTlGreeter) << "User" << username << "not found when updating login state"; + } + + if (target) { + target->setLoggedIn(loggedIn); + const int row = static_cast(d->users.indexOf(target)); + Q_EMIT dataChanged(index(row), index(row)); + } + + Q_EMIT layoutChanged(); +} + +void UserModel::clearUserLoginState() +{ + for (auto &user : std::as_const(d->users)) { + user->setLoggedIn(false); + } + + Q_EMIT layoutChanged(); +} + +QVariant UserModel::data(const QModelIndex &index, int role) const +{ + if (index.row() < 0 || index.row() >= d->users.count()) { + return {}; + } + + // get user + UserPtr user = d->users[index.row()]; + + // return correct value + switch (role) { + case NameRole: + return user->userName(); + case RealNameRole: + return user->fullName(); + case HomeDirRole: + return user->homeDir(); + case IconRole: + return user->iconFile(); + case NoPasswordRole: + return user->noPasswdLogin(); + case LoggedInRole: + return user->loggedIn(); + case IdentityRole: + return user->identity(); + case PasswordHintRole: + return user->passwordHint(); + case LocaleRole: + return user->locale(); + default: + return {}; + } +} + +bool UserModel::containsAllUsers() const +{ + return d->containsAllUsers; +} + +QVariant UserModel::get(const QString &username) const +{ + QVariantMap map; + for (const auto &user : d->users) { + if (user->userName() == username or user->fullName() == username) { + map["name"] = user->userName(); + map["icon"] = user->iconFile(); + map["realName"] = user->fullName(); + map["homeDir"] = user->homeDir(); + map["noPassword"] = user->noPasswdLogin(); + map["loggedIn"] = user->loggedIn(); + map["identity"] = user->identity(); + map["passwordHint"] = user->passwordHint(); + map["locale"] = user->locale(); + break; + } + } + + return map; +} + +QVariant UserModel::get(int index) const +{ + QVariantMap map; + if (index < 0 or index >= d->users.count()) { + return {}; + } + + auto user = d->users.at(index); + map["name"] = user->userName(); + map["icon"] = user->iconFile(); + map["realName"] = user->fullName(); + map["homeDir"] = user->homeDir(); + map["noPassword"] = user->noPasswdLogin(); + map["loggedIn"] = user->loggedIn(); + map["identity"] = user->identity(); + map["passwordHint"] = user->passwordHint(); + map["locale"] = user->locale(); + + return map; +} + +UserPtr UserModel::getUser(const QString &username) const noexcept +{ + for (const auto &user : d->users) { + if (user->userName() == username) { + return user; + } + } + return nullptr; +} + +UserPtr UserModel::getUser(uid_t uid) const noexcept +{ + for (const auto &user : d->users) { + if (user->UID() == uid) { + return user; + } + } + return nullptr; +} + +QString UserModel::currentUserName() const noexcept +{ + return d->currentUserName; +} + +UserPtr UserModel::currentUser() const +{ + return getUser(d->currentUserName); +} + +void UserModel::updateUserLimits(const QString &userName, const QString &time) const noexcept +{ + for (const auto &user : d->users) { + if (user->userName() == userName) { + user->updateLimitTime(time); + break; + } + } +} + +void UserModel::setCurrentUserName(const QString &userName) noexcept +{ + d->currentUserName = userName; + + for (const auto &user : d->users) { + if (user->waylandSocket()) { + user->waylandSocket()->setEnabled(user->userName() == userName, + WaylandServer::instance()->sessionManager()->globalSession()->socket()); + } + } + + Q_EMIT currentUserNameChanged(); +} + +void UserModel::setLastUser(const QString &userName) +{ + if (userName.isEmpty()) + return; + + if (d->lastUserName != userName) { + d->lastUserName = userName; + Q_EMIT lastUserChanged(); + } + + UserPtr user = getUser(userName); + if (!user && tryAddNssUser(userName)) + user = getUser(userName); + if (!user) + return; + + const int index = d->users.indexOf(user); + if (d->lastIndex != index) { + d->lastIndex = index; + Q_EMIT lastIndexChanged(); + } + + if (d->currentUserName != user->userName()) + setCurrentUserName(user->userName()); +} + +void UserModel::onUserAdded(quint64 uid) +{ + auto newUser = d->manager.findUserById(uid); + if (!newUser) { + qCWarning(lcTlGreeter) << "User" << uid << "has been added but couldn't find it."; + return; + } + + addUser(std::make_unique(std::move(newUser).value())); +} + +void UserModel::onUserDeleted(quint64 uid) +{ + beginResetModel(); + d->users.removeIf([uid](const UserPtr &user) { + return user->UID() == uid; + }); + endResetModel(); + + Q_EMIT countChanged(); +} + +bool UserModel::tryAddNssUser(const QString &userName) +{ + if (userName.isEmpty()) { + return false; + } + + // Already in model? + if (getUser(userName)) { + qCInfo(lcTlGreeter) << "NSS user already in model:" << userName; + return true; + } + + // TODO: getpwnam is synchronous and may block on slow NSS/LDAP backends; + // consider moving to an async worker thread in a future iteration. + struct passwd *pw = ::getpwnam(userName.toLocal8Bit().constData()); + if (!pw) { + qCInfo(lcTlGreeter) << "NSS user not found:" << userName; + return false; + } + + // pw_gecos is comma-separated ("Full Name,Room,Work,Home,Other"); use only the first field. + QString fullName = QString::fromLocal8Bit(pw->pw_gecos).section(QLatin1Char(','), 0, 0); + + // Copy the NSS fields before calling into the account service. + const auto uid = static_cast(pw->pw_uid); + const auto gid = static_cast(pw->pw_gid); + const auto homeDir = QString::fromLocal8Bit(pw->pw_dir); + + auto account = d->manager.findUserById(uid); + if (account && QString::fromUtf8(account.value()->userName()) == userName) + return addUser(std::make_unique(std::move(account).value())); + + qCInfo(lcTlGreeter) << "Adding NSS/LDAP user to model:" << userName; + return addUser(std::make_unique( + userName, + uid, + gid, + homeDir, + fullName)); +} diff --git a/src/greeter/usermodel.h b/src/greeter/usermodel.h new file mode 100644 index 0000000000..a94fcf92e4 --- /dev/null +++ b/src/greeter/usermodel.h @@ -0,0 +1,105 @@ +/*************************************************************************** + * Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. + * Copyright (c) 2013 Abdurrahman AVCI + * + * 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 2 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, write to the + * Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + ***************************************************************************/ + +#ifndef SDDM_USERMODEL_H +#define SDDM_USERMODEL_H + +#include "greeter/user.h" + +#include +#include +#include + +struct UserModelPrivate; + +using UserPtr = std::shared_ptr; + +class UserModel : public QAbstractListModel +{ + Q_OBJECT + Q_PROPERTY(QString currentUserName READ currentUserName WRITE setCurrentUserName NOTIFY + currentUserNameChanged) + Q_PROPERTY(int lastIndex READ lastIndex NOTIFY lastIndexChanged) + Q_PROPERTY(QString lastUser READ lastUser NOTIFY lastUserChanged) + Q_PROPERTY(int count READ rowCount NOTIFY countChanged) + Q_PROPERTY(bool containsAllUsers READ containsAllUsers CONSTANT) + QML_NAMED_ELEMENT(UserModel) + QML_SINGLETON + +public: + enum UserRoles + { + NameRole = Qt::UserRole + 1, + RealNameRole, + HomeDirRole, + IconRole, + NoPasswordRole, + LoggedInRole, + IdentityRole, + PasswordHintRole, + LocaleRole + }; + Q_ENUM(UserRoles) + + UserModel(const UserModel &) = delete; + UserModel &operator=(const UserModel &) = delete; + explicit UserModel(QObject *parent = nullptr); + ~UserModel() override; + + [[nodiscard]] QHash roleNames() const override; + [[nodiscard]] int lastIndex() const; + [[nodiscard]] QString lastUser() const; + [[nodiscard]] int rowCount(const QModelIndex &parent = QModelIndex()) const override; + [[nodiscard]] Q_INVOKABLE QVariant data(const QModelIndex &index, + int role = Qt::DisplayRole) const override; + [[nodiscard]] Q_INVOKABLE QVariant get(const QString &username) const; + [[nodiscard]] Q_INVOKABLE QVariant get(int index) const; + [[nodiscard]] UserPtr getUser(const QString &username) const noexcept; + [[nodiscard]] UserPtr getUser(uid_t uid) const noexcept; + [[nodiscard]] QString currentUserName() const noexcept; + UserPtr currentUser() const; + void updateUserLimits(const QString &userName, const QString &time) const noexcept; + void setCurrentUserName(const QString &userName) noexcept; + void setLastUser(const QString &userName); + void updateUserLoginState(const QString &username, bool loggedIn); + void clearUserLoginState(); + [[nodiscard]] bool containsAllUsers() const; + [[nodiscard]] Q_INVOKABLE bool tryAddNssUser(const QString &userName); + +Q_SIGNALS: + void currentUserNameChanged(); + void lastIndexChanged(); + void lastUserChanged(); + void updateTranslations(const QLocale &locale); + void countChanged(); + void userLoggedIn(const QString &username, const QString &sessionId); + +private Q_SLOTS: + void onUserAdded(quint64 uid); + void onUserDeleted(quint64 uid); + +private: + bool addUser(UserPtr user); + void sortUsers(); + + UserModelPrivate *d{ nullptr }; +}; + +#endif // USERMODEL_H diff --git a/src/idle/idlemanager.cpp b/src/idle/idlemanager.cpp new file mode 100644 index 0000000000..9fbf28ef92 --- /dev/null +++ b/src/idle/idlemanager.cpp @@ -0,0 +1,245 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "idlemanager.h" +#include "modules/screensaver/screensaverinterfacev2.h" +#include "common/treelandlogging.h" + +#include +#include +#ifndef DISABLE_XWAYLAND +#include +#endif +#include +#include +#include + +#include + +#include +#include + +IdleManager::IdleManager(QObject *parent) + : QObject(parent) +{ + m_sinceActivity.start(); +} + +IdleManager::~IdleManager() +{ + teardown(); +} + +void IdleManager::initialize(WServer *server) +{ + m_idleNotifier = wlr_idle_notifier_v1_create(server->handle()); + m_idleInhibitManager = wlr_idle_inhibit_v1_create(server->handle()); + listeners()->add(&m_idleInhibitManager->events.new_inhibitor, + this, &IdleManager::onNewIdleInhibitor); +} + +void IdleManager::setScreensaver(ScreensaverInterfaceV2 *screensaver) +{ + m_screensaver = screensaver; +} + +void IdleManager::notifyActivity(WSeat *seat) +{ + wlr_idle_notifier_v1_notify_activity(m_idleNotifier, seat->handle()); + m_sinceActivity.restart(); +} + +bool IdleManager::isScreensaverInhibited() const +{ + return m_screensaver && m_screensaver->isInhibited(); +} + +qint64 IdleManager::idleMs() const +{ + return m_sinceActivity.isValid() ? m_sinceActivity.elapsed() : 0; +} + +// A zwp_idle_inhibit surface only counts while it is mapped and, for an xdg +// toplevel, not minimized. +static bool inhibitorIsActive(wlr_idle_inhibitor_v1 *inhibitor) +{ + if (!inhibitor->surface) + return false; + + auto *wsurface = WSurface::fromHandle(inhibitor->surface); + if (!wsurface) + return false; + + bool active = wsurface->mapped(); + auto *toplevel = WXdgToplevelSurface::fromSurface(wsurface); + if (toplevel) + active &= !toplevel->isMinimized(); + return active; +} + +QList IdleManager::inhibitors() const +{ + QList result; + + for (const auto &entry : idleInhibitorEntries) { + auto *inhibitor = entry.inhibitor; + // wlroots destroys the inhibitor together with its surface, so this + // should never be null; keep the same defence as onNewIdleInhibitor(). + if (!inhibitor->surface) + continue; + + auto *wsurface = WSurface::fromHandle(inhibitor->surface); + + Inhibitor info; + info.kind = QStringLiteral("idle-inhibit"); + info.surface = inhibitor->surface; + info.active = inhibitorIsActive(inhibitor); + // The window's own app id is the one `windows` reports; a session + // client has no socket security context, so WClient::appId() alone + // would leave this empty. Socket identity is the fallback. + if (wsurface) { + if (auto *toplevel = WXdgToplevelSurface::fromSurface(wsurface)) { + info.title = toplevel->title(); + info.appId = toplevel->appId(); +#ifndef DISABLE_XWAYLAND + } else if (auto *xwayland = WXWaylandSurface::fromSurface(wsurface)) { + info.title = xwayland->title(); + info.appId = xwayland->appId(); +#endif + } + } + if (auto *client = inhibitor->resource ? wl_resource_get_client(inhibitor->resource) + : nullptr) { + if (info.appId.isEmpty()) { + if (auto *wclient = WClient::get(client)) + info.appId = QString::fromUtf8(wclient->appId()); + } + if (auto creds = WClient::getCredentials(client)) + info.pid = creds->pid; + } + info.heldMs = static_cast(entry.age.isValid() ? entry.age.elapsed() : 0); + result.append(info); + } + + if (m_screensaver) { + for (const auto &inhibit : m_screensaver->inhibits()) { + Inhibitor info; + info.kind = QStringLiteral("screensaver"); + info.appId = inhibit.appId; + info.pid = inhibit.pid; + info.appName = inhibit.applicationName; + info.reason = inhibit.reason; + info.active = true; + info.heldMs = inhibit.heldMs; + result.append(info); + } + } + + return result; +} + +int IdleManager::indexOfIdleInhibitor(wlr_idle_inhibitor_v1 *inhibitor) const +{ + const auto it = std::find_if(idleInhibitorEntries.cbegin(), idleInhibitorEntries.cend(), + [inhibitor](const auto &entry) { + return entry.inhibitor == inhibitor; + }); + return it == idleInhibitorEntries.cend() + ? -1 + : static_cast(std::distance(idleInhibitorEntries.cbegin(), it)); +} + +void IdleManager::bindIdleInhibitorSurface(IdleInhibitorEntry &entry) +{ + Q_ASSERT(entry.connections.isEmpty()); + + auto *wsurface = entry.inhibitor->surface + ? WSurface::fromHandle(entry.inhibitor->surface) + : nullptr; + if (!wsurface) + return; + + entry.connections << connect(wsurface, &WSurface::mappedChanged, + this, &IdleManager::updateIdleInhibitor); + if (auto *toplevel = WXdgToplevelSurface::fromSurface(wsurface)) { + entry.connections << connect(toplevel, &WXdgToplevelSurface::minimizeChanged, + this, &IdleManager::updateIdleInhibitor); + } + entry.commitListener.disconnect(); + entry.mapListener.disconnect(); +} + +void IdleManager::rebindIdleInhibitorSurface(wlr_idle_inhibitor_v1 *inhibitor) +{ + const int index = indexOfIdleInhibitor(inhibitor); + if (index < 0) + return; + + bindIdleInhibitorSurface(idleInhibitorEntries[index]); + updateIdleInhibitor(); +} + +void IdleManager::onNewIdleInhibitor(wlr_idle_inhibitor_v1 *wlr_inhibitor) +{ + if (!wlr_inhibitor->surface) { + qCInfo(lcTlCore) << "Ignoring idle inhibitor with null surface"; + return; + } + + IdleInhibitorEntry entry; + entry.inhibitor = wlr_inhibitor; + entry.age.start(); + // Single destroy signal: keep a WScopedListener on the entry itself + // (equivalent to the old QObject context / QMetaObject::Connection). + // Erasing the entry disconnects the listener via RAII. + entry.destroyListener.init(&wlr_inhibitor->events.destroy, [this, wlr_inhibitor] (void *) { + const int index = indexOfIdleInhibitor(wlr_inhibitor); + if (index >= 0) { + auto connections = std::move(idleInhibitorEntries[index].connections); + idleInhibitorEntries.erase(idleInhibitorEntries.begin() + index); + for (const auto &connection : connections) + QObject::disconnect(connection); + } + updateIdleInhibitor(); + }); + + // The WSurface wrapper (and with it mapped/minimized state) only exists + // once the surface gets a shell role, which a client may request after + // creating the inhibitor. Register anyway -- `active` is live-computed and + // stays false meanwhile -- and retry on the surface's own commit and map. + // Both are needed: a synchronized subsurface's cached commit is applied + // while its parent commits, before wlroots emits new_subsurface and waylib + // creates the wrapper, and the map that immediately follows needs no + // further commit of the child. + bindIdleInhibitorSurface(entry); + if (entry.connections.isEmpty()) { + entry.commitListener.init(&wlr_inhibitor->surface->events.commit, + [this, wlr_inhibitor] (void *) { + rebindIdleInhibitorSurface(wlr_inhibitor); + }); + entry.mapListener.init(&wlr_inhibitor->surface->events.map, + [this, wlr_inhibitor] (void *) { + rebindIdleInhibitorSurface(wlr_inhibitor); + }); + } + + idleInhibitorEntries.push_back(std::move(entry)); + + updateIdleInhibitor(); +} + +void IdleManager::updateIdleInhibitor() +{ + m_inhibited = isScreensaverInhibited(); + + if (!m_inhibited) { + for (const auto &entry : idleInhibitorEntries) { + if (inhibitorIsActive(entry.inhibitor)) { + m_inhibited = true; + break; + } + } + } + + wlr_idle_notifier_v1_set_inhibited(m_idleNotifier, m_inhibited); +} diff --git a/src/idle/idlemanager.h b/src/idle/idlemanager.h new file mode 100644 index 0000000000..15ae1a2fa6 --- /dev/null +++ b/src/idle/idlemanager.h @@ -0,0 +1,86 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include + +#include +#include +#include + +struct wlr_surface; + +struct wlr_idle_notifier_v1; +struct wlr_idle_inhibit_manager_v1; +struct wlr_idle_inhibitor_v1; +class ScreensaverInterfaceV2; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WServer; +class WSeat; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class IdleManager : public QObject, public WObject +{ + Q_OBJECT +public: + explicit IdleManager(QObject *parent = nullptr); + ~IdleManager() override; + + void initialize(WServer *server); + void setScreensaver(ScreensaverInterfaceV2 *screensaver); + void notifyActivity(WSeat *seat); + void updateIdleInhibitor(); + + // One source currently holding idle off, either a + // zwp_idle_inhibit_manager_v1 surface or a treeland_screensaver_v2 + // inhibit. Exposed to the treeland-debug ``idle`` command. + struct Inhibitor { + QString kind; // "idle-inhibit" or "screensaver" + wlr_surface *surface = nullptr; // idle-inhibit only + QString appId; + QString title; + int pid = 0; + QString appName; // screensaver only (client-provided) + QString reason; // screensaver only (client-provided) + bool active = false; // this source alone counts as inhibiting + quint64 heldMs = 0; // how long the source has been held + }; + + // True while idle notification is suppressed by any source. + bool isIdleInhibited() const { return m_inhibited; } + bool isScreensaverInhibited() const; + // Milliseconds since the last input activity on any seat; counted from + // compositor start until the first activity is seen. + qint64 idleMs() const; + QList inhibitors() const; + +private: + struct IdleInhibitorEntry { + wlr_idle_inhibitor_v1 *inhibitor = nullptr; + QElapsedTimer age; + WScopedListener destroyListener; + // Watch the native surface until it gets a WSurface wrapper (see + // bindIdleInhibitorSurface()); both disconnected once bound. + WScopedListener commitListener; + WScopedListener mapListener; + QList connections; + }; + + void onNewIdleInhibitor(wlr_idle_inhibitor_v1 *inhibitor); + int indexOfIdleInhibitor(wlr_idle_inhibitor_v1 *inhibitor) const; + void bindIdleInhibitorSurface(IdleInhibitorEntry &entry); + void rebindIdleInhibitorSurface(wlr_idle_inhibitor_v1 *inhibitor); + + ScreensaverInterfaceV2 *m_screensaver = nullptr; + wlr_idle_notifier_v1 *m_idleNotifier = nullptr; + WPointer m_idleInhibitManager; + bool m_inhibited = false; + QElapsedTimer m_sinceActivity; + std::vector idleInhibitorEntries; +}; diff --git a/src/input/compositorinputfilter.cpp b/src/input/compositorinputfilter.cpp new file mode 100644 index 0000000000..86a6db4bf0 --- /dev/null +++ b/src/input/compositorinputfilter.cpp @@ -0,0 +1,428 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include "compositorinputfilter.h" +#include "inputcontext.h" +#include "idle/idlemanager.h" +#include "capture/capturemanager.h" +#include "surface/seatsurfacemanager.h" +#include "output/output.h" +#include "output/outputmanager.h" +#include "seat/seatmanager.h" +#include "surface/surfacewrapper.h" +#include "gesturemanager.h" +#include "modules/shortcut/shortcutmanager.h" +#include "modules/shortcut/shortcutcontroller.h" +#include "modules/keyboard-shortcuts-inhibit/keyboardshortcutsinhibitmanager.h" +#include "modules/dde-shell/ddeshellmanagerinterfacev1.h" +#include "modules/active-notify/activenotifymanagerinterfacev1.h" +#include "common/treelandlogging.h" + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +CompositorInputFilter::CompositorInputFilter(InputContext *context, QObject *parent, + IdleManager *idleManager, CaptureManager *captureManager, OutputManager *outputManager) + : WSeatEventFilter(parent) + , m_context(context) + , m_idleManager(idleManager) + , m_captureManager(captureManager) + , m_outputManager(outputManager) +{} + +void CompositorInputFilter::setShortcutProtocols(ShortcutManagerV3 *shortcuts, + KeyboardShortcutsInhibitManagerV1 *inhibitor) +{ + m_shortcutManager = shortcuts; + m_keyboardShortcutsInhibitManagerV1 = inhibitor; +} + +bool CompositorInputFilter::beforeDisposeEvent(WSeat *seat, QWindow *targetWindow, QInputEvent *event) +{ + if (!acceptsEvent(seat, event) || (m_admission && !m_admission(seat, event))) + return true; + if (!m_context->available()) { + return false; + } + + if (Q_UNLIKELY(!targetWindow || !event)) { + return false; + } + + if (event->isInputEvent()) { + m_idleManager->notifyActivity(seat); + + // Only wake outputs disabled through output-power management. + m_outputManager->wakePoweredOffOutputs(); + } + + if (event->type() == QEvent::KeyPress) { + auto kevent = static_cast(event); + const auto modifiers = kevent->modifiers(); + const auto ctrlAlt = Qt::ControlModifier | Qt::AltModifier; + if ((modifiers & ctrlAlt) == ctrlAlt) { + const auto key = kevent->key(); + if (key >= Qt::Key_F1 && key <= Qt::Key_F12) { + const int vtnr = key - Qt::Key_F1 + 1; + m_context->switchVirtualTerminal(vtnr); + return true; + } + } + } + + WSeat *targetSeat = seat; + m_currentEventSeat = targetSeat; + [[maybe_unused]] auto clearEventSeat = qScopeGuard([this] { m_currentEventSeat = nullptr; }); + + // Clear the record on release before the early returns below can bypass the + // tracked block, otherwise the entry would linger until WSeat::destroy(). + // Auto-repeats are skipped: only the real release ends the press. + if (seat == m_context->primarySeat() && event->type() == QEvent::KeyRelease) { + const auto *kevent = static_cast(event); + const uint32_t evdevKeycode = kevent->nativeVirtualKey(); + if (!kevent->isAutoRepeat() && seat->isKeyFiltered(evdevKeycode)) + seat->removeFilteredKey(evdevKeycode); + } + + // Dismiss the popup grab when the user presses a button outside the popup + // (e.g. on the desktop or another client). wlroots' xdg popup keyboard grab + // redirects keyboard focus back to the popup, so it must be ended explicitly. + if (event->type() == QEvent::MouseButtonPress) { + if (auto *seatContainer = m_context->seatContainer(targetSeat)) { + if (seatContainer->hasPopupGrab()) { + auto *focused = targetSeat->handle()->pointer_state.focused_surface; + bool clickOnPopup = false; + if (focused) { + if (auto *wSurface = WSurface::fromHandle(focused)) { + if (auto *wrapper = m_context->surface(wSurface)) + clickOnPopup = (wrapper->type() == SurfaceWrapper::Type::XdgPopup); + } + } + // seat->drag is non-null during an active DnD drag, which also + // installs a keyboard grab; never end that grab here. + if (!clickOnPopup && !targetSeat->handle()->drag) + seatContainer->dismissPopups(); + } + } + } + if (seat == m_context->primarySeat()) { + if (event->type() == QEvent::KeyPress) { + auto kevent = static_cast(event); + switch (kevent->key()) { + case Qt::Key_Meta: + case Qt::Key_Super_L: + case Qt::Key_Super_R: + if (auto *seatContainer = m_context->seatContainer(seat)) + seatContainer->setMetaKeyPressed(true); + break; + default: + if (auto *seatContainer = m_context->seatContainer(seat)) + seatContainer->setMetaKeyPressed(false); + break; + } + } + + if (event->type() == QEvent::KeyPress) { + auto kevent = static_cast(event); + +#ifndef QT_NO_DEBUG + if (QKeySequence(kevent->keyCombination()) == + QKeySequence(Qt::MetaModifier | Qt::Key_F12)) { + std::terminate(); + } + // The debug view shortcut should always handled first + if (QKeySequence(kevent->keyCombination()) + == QKeySequence(Qt::ControlModifier | Qt::ShiftModifier | Qt::MetaModifier | Qt::Key_F11)) { + if (m_context->toggleDebugView()) + return true; + } +#endif + + if (m_captureManager->isSelecting()) { + if (event->modifiers() == Qt::NoModifier && kevent->key() == Qt::Key_Escape) + m_captureManager->cancelSelection(); + } + } + + if (event->type() == QEvent::KeyRelease && !m_captureManager->isSelecting()) { + auto kevent = static_cast(event); + const int key = kevent->key(); + if (key == Qt::Key_Alt || key == Qt::Key_Control || key == Qt::Key_Shift + || key == Qt::Key_Meta) { + Q_EMIT modifierKeyReleased(kevent); + } + } + } + + if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease) { + handleLeftButtonStateChanged(event); + } + + if (event->type() == QEvent::Wheel) { + handleWhellValueChanged(event); + } + + if (event->type() == QEvent::MouseMove || event->type() == QEvent::MouseButtonPress) { + seat->cursor()->setVisible(true); + } else if (event->type() == QEvent::TouchBegin) { + seat->cursor()->setVisible(false); + } + + if (m_gestures && !m_context->locked()) + doGesture(event); + + // Per-seat move/resize handling + auto *seatContainer = m_context->seatContainer(seat); + if (seatContainer && seatContainer->moveResizeState().surface) { + if (Q_LIKELY(event->type() == QEvent::MouseMove || event->type() == QEvent::TouchUpdate)) { + auto cursor = seat->cursor(); + Q_ASSERT(cursor); + QMouseEvent *ev = static_cast(event); + + const auto &moveResizeState = seatContainer->moveResizeState(); + auto ownsOutput = moveResizeState.surface->ownsOutput(); + if (!ownsOutput) { + m_context->endMoveResize(seat); + return false; + } + + auto increment_pos = ev->globalPosition() - moveResizeState.initialPosition; + m_context->moveResize(seat, increment_pos); + // Edge-tiling detection during move (resize is not tiled). + if (moveResizeState.edges == Qt::Edges()) + m_context->detectEdgeTiling(seat); + + return true; + } else if (event->type() == QEvent::KeyPress + && static_cast(event)->key() == Qt::Key_Escape) { + m_context->cancelMoveResize(seat); + return true; + } else if (event->type() == QEvent::MouseButtonRelease + || event->type() == QEvent::TouchEnd) { + m_context->endMoveResize(seat); + } + } + + // Suppress compositor shortcuts when a keyboard shortcuts inhibitor is active + if (m_context->normal()) { + auto *focusSurface = seat->keyboardFocusSurface(); + if (focusSurface && m_keyboardShortcutsInhibitManagerV1 + && m_keyboardShortcutsInhibitManagerV1->isInhibited(seat->handle(), + focusSurface->handle())) + return false; + } + + // Capture mode: intercept key events before dispatchKeyEvent + if (m_shortcutManager && m_shortcutManager->isCaptureActive() && m_shortcutManager->tryHandleCaptureEvent(seat, event)) + return true; + + if (seat == m_context->primarySeat() && !m_captureManager->isSelecting() && !m_context->locked() + && (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease)) { + auto kevent = static_cast(event); + auto *seatContainer = m_context->seatContainer(seat); + + // Meta: consume press as modifier; suppress release when used in combo + if (kevent->key() == Qt::Key_Meta || kevent->key() == Qt::Key_Super_L || kevent->key() == Qt::Key_Super_R) { + if (kevent->type() == QEvent::KeyPress) { + return true; + } + if (kevent->type() == QEvent::KeyRelease && seatContainer && !seatContainer->metaKeyPressed()) { + return false; + } + } + + auto *controller = m_controller; + if (!controller) + return false; + const uint32_t evdevKeycode = kevent->nativeVirtualKey(); + const bool isAutoRepeat = kevent->isAutoRepeat(); + + if (!isAutoRepeat && kevent->type() == QEvent::KeyPress + && controller->matchesShortcut(kevent)) + seat->addFilteredKey(evdevKeycode); + + if (controller->dispatchKeyEvent(kevent)) + return true; + } + + return false; +} + +bool CompositorInputFilter::afterHandleEvent(WSeat *seat, + WSurface *watched, + QObject *surfaceItem, + QObject *, + QInputEvent *event) +{ + if (!acceptsEvent(seat, event)) + return true; + + if (!m_context->available()) + return false; + + if (event->isSinglePointEvent() && static_cast(event)->isBeginEvent()) { + // surfaceItem is qml type: XdgSurfaceItem or LayerSurfaceItem + auto *item = qobject_cast(surfaceItem); + auto *toplevelSurface = item ? item->shellSurface() : nullptr; + if (!toplevelSurface) + return false; + Q_ASSERT(toplevelSurface->surface() == watched); + + m_context->activateSurface(watched, seat, Qt::MouseFocusReason); + } + + return false; +} + +bool CompositorInputFilter::unacceptedEvent(WSeat *seat, QWindow *, QInputEvent *event) +{ + if (!acceptsEvent(seat, event)) + return true; + if (!m_context->available()) + return false; + + if (event->isSinglePointEvent() && static_cast(event)->isBeginEvent()) { + m_context->activateSurface(nullptr, seat, Qt::OtherFocusReason); + } + + return false; +} + +bool CompositorInputFilter::doGesture(QInputEvent *event) +{ + if (event->type() == QEvent::NativeGesture) { + auto e = static_cast(event); + switch (e->gestureType()) { + case Qt::BeginNativeGesture: + if (e->libInputGestureType() == WGestureEvent::WLibInputGestureType::SwipeGesture) + m_gestures->processSwipeStart(e->fingerCount()); + + if (e->libInputGestureType() == WGestureEvent::WLibInputGestureType::HoldGesture) + m_gestures->processHoldStart(e->fingerCount()); + break; + case Qt::EndNativeGesture: + if (e->libInputGestureType() == WGestureEvent::WLibInputGestureType::SwipeGesture) { + if (e->cancelled()) + m_gestures->processSwipeCancel(); + else + m_gestures->processSwipeEnd(); + } + if (e->libInputGestureType() == WGestureEvent::WLibInputGestureType::HoldGesture) + m_gestures->processHoldEnd(); + break; + case Qt::PanNativeGesture: + if (e->libInputGestureType() == WGestureEvent::WLibInputGestureType::SwipeGesture) + m_gestures->processSwipeUpdate(e->delta()); + case Qt::ZoomNativeGesture: + case Qt::SmartZoomNativeGesture: + case Qt::RotateNativeGesture: + case Qt::SwipeNativeGesture: + default: + break; + } + } + return false; +} + +void CompositorInputFilter::handleLeftButtonStateChanged(const QInputEvent *event) +{ + Q_ASSERT(m_context->primarySeat()); + WSeat *seat = m_currentEventSeat ? m_currentEventSeat : m_context->primarySeat(); + const QMouseEvent *me = static_cast(event); + if (me->button() == Qt::LeftButton) { + if (event->type() == QEvent::MouseButtonPress) { + DDEActiveInterface::sendActiveIn(DDEActiveInterface::Mouse, seat); + ActiveNotifyV1::sendActivityChanged(ActiveNotifyV1::Mouse, + ActiveNotifyV1::Active, + seat); + } else { + DDEActiveInterface::sendActiveOut(DDEActiveInterface::Mouse, seat); + ActiveNotifyV1::sendActivityChanged(ActiveNotifyV1::Mouse, + ActiveNotifyV1::Inactive, + seat); + } + } +} + +void CompositorInputFilter::handleWhellValueChanged(const QInputEvent *event) +{ + Q_ASSERT(m_context->primarySeat()); + WSeat *seat = m_currentEventSeat ? m_currentEventSeat : m_context->primarySeat(); + const QWheelEvent *we = static_cast(event); + QPoint delta = we->angleDelta(); + if (delta.x() + delta.y() < 0) { + DDEActiveInterface::sendActiveOut(DDEActiveInterface::Wheel, seat); + ActiveNotifyV1::sendActivityChanged(ActiveNotifyV1::Wheel, + ActiveNotifyV1::Inactive, + seat); + } + if (delta.x() + delta.y() > 0) { + DDEActiveInterface::sendActiveIn(DDEActiveInterface::Wheel, seat); + ActiveNotifyV1::sendActivityChanged(ActiveNotifyV1::Wheel, + ActiveNotifyV1::Active, + seat); + } +} + +void CompositorInputFilter::installRelativePointer(WServer *server, SeatManager *seatManager) +{ + m_relativePointerManager = server->attach(); + connect(seatManager, &SeatManager::seatAdded, this, &CompositorInputFilter::trackSeat); +} + +void CompositorInputFilter::trackSeat(WSeat *seat) +{ + disconnect(seat, &WSeat::relativePointerMotion, this, nullptr); + connect(seat, &WSeat::relativePointerMotion, this, + [this, seat](uint32_t ts, QPointF delta, QPointF unaccelerated) { + if (!seat->cursor()) + return; + m_relativePointerManager->sendRelativeMotion(seat, ts, delta, unaccelerated); + }); +} + +void CompositorInputFilter::setEnabled(bool enabled) +{ + m_enabled = enabled; + m_currentEventSeat = nullptr; +} + +void CompositorInputFilter::setAdmission(std::function admission) +{ + m_admission = std::move(admission); +} + +void CompositorInputFilter::setGestureManager(GestureManager *gestures) { m_gestures = gestures; } +void CompositorInputFilter::setController(ShortcutController *controller) { m_controller = controller; } + +bool CompositorInputFilter::acceptsEvent(WSeat *seat, QInputEvent *event) const +{ + if (!m_enabled || !seat || !event || !m_context->available() || seat->eventFilter() != this) + return false; + if (event->device()) { + if (auto *device = WInputDevice::from(event->device())) + return device->seat() == seat; + } + return true; +} + +bool CompositorInputFilter::beforeHandleEvent(WSeat *seat, WSurface *watched, QObject *, + QObject *, QInputEvent *event) +{ + if (!acceptsEvent(seat, event)) + return true; + if (watched && !seat->ownsClient(watched->waylandClient())) + return true; + return watched && !m_context->surface(watched); +} diff --git a/src/input/compositorinputfilter.h b/src/input/compositorinputfilter.h new file mode 100644 index 0000000000..5da3f60b7b --- /dev/null +++ b/src/input/compositorinputfilter.h @@ -0,0 +1,75 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include + +class SeatManager; +class InputContext; +class GestureManager; +class ShortcutController; +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WServer; +class WRelativePointerManagerV1; +WAYLIB_SERVER_END_NAMESPACE + +class IdleManager; +class CaptureManager; +class OutputManager; +class ShortcutManagerV3; +class KeyboardShortcutsInhibitManagerV1; + +WAYLIB_SERVER_USE_NAMESPACE + +class CompositorInputFilter : public WSeatEventFilter +{ + Q_OBJECT +public: + CompositorInputFilter(InputContext *context, QObject *parent, + IdleManager *idleManager, CaptureManager *captureManager, + OutputManager *outputManager); + + void setEnabled(bool enabled); + void setAdmission(std::function admission); + void setGestureManager(GestureManager *gestures); + void setController(ShortcutController *controller); + void installRelativePointer(WServer *server, SeatManager *seatManager); + void setShortcutProtocols(ShortcutManagerV3 *shortcuts, + KeyboardShortcutsInhibitManagerV1 *inhibitor); + WSeat *currentEventSeat() const { return m_currentEventSeat; } + +Q_SIGNALS: + void modifierKeyReleased(QKeyEvent *event); + +private: + void trackSeat(WSeat *seat); + bool beforeHandleEvent(WSeat *seat, WSurface *watched, QObject *shellObject, + QObject *eventObject, QInputEvent *event) override; + bool acceptsEvent(WSeat *seat, QInputEvent *event) const; + WRelativePointerManagerV1 *m_relativePointerManager = nullptr; + bool beforeDisposeEvent(WSeat *seat, QWindow *window, QInputEvent *event) override; + bool afterHandleEvent(WSeat *seat, WSurface *watched, QObject *shellObject, + QObject *eventObject, QInputEvent *event) override; + bool unacceptedEvent(WSeat *seat, QWindow *window, QInputEvent *event) override; + bool doGesture(QInputEvent *event); + void handleLeftButtonStateChanged(const QInputEvent *event); + void handleWhellValueChanged(const QInputEvent *event); + +private: + bool m_enabled = true; + std::function m_admission; + GestureManager *m_gestures = nullptr; + ShortcutController *m_controller = nullptr; + InputContext *const m_context; + IdleManager *m_idleManager = nullptr; + CaptureManager *m_captureManager = nullptr; + OutputManager *m_outputManager = nullptr; + ShortcutManagerV3 *m_shortcutManager = nullptr; + KeyboardShortcutsInhibitManagerV1 *m_keyboardShortcutsInhibitManagerV1 = nullptr; + WSeat *m_currentEventSeat = nullptr; +}; diff --git a/src/input/gesturemanager.cpp b/src/input/gesturemanager.cpp new file mode 100644 index 0000000000..8ddb0bbf3c --- /dev/null +++ b/src/input/gesturemanager.cpp @@ -0,0 +1,144 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include "gesturemanager.h" +#include "gesturerecognizer.h" + +#define MIN_SWIPE_FINGERS 3 + +GestureManager::GestureManager(QObject *parent) + : QObject(parent) + , m_touchpadRecognizer(new GestureRecognizer(this)) +{ +} + +GestureManager::~GestureManager() = default; + +void GestureManager::cancel() +{ + m_touchpadRecognizer->cancelSwipeGesture(); + m_touchpadRecognizer->cancelHoldGesture(); + m_touchpadFingerCount = 0; + m_sequence = Sequence::None; +} + +[[maybe_unused]] SwipeGesture * GestureManager::registerTouchpadSwipe(const SwipeFeedBack &feed_back) +{ + auto swipe_gesture = new SwipeGesture(this); + swipe_gesture->setDirection(feed_back.direction); + swipe_gesture->setMinimumDelta(QPointF(200, 200)); + swipe_gesture->setMaximumFingerCount(feed_back.fingerCount); + swipe_gesture->setMinimumFingerCount(feed_back.fingerCount); + + if (feed_back.actionCallback) { + QObject::connect(swipe_gesture, &SwipeGesture::triggered, [fb = feed_back.actionCallback]() { + fb(true); + }); + QObject::connect(swipe_gesture, &SwipeGesture::cancelled, [fb = feed_back.actionCallback]() { + fb(false); + }); + } + + if (feed_back.progressCallback) { + QObject::connect(swipe_gesture, &SwipeGesture::progress, feed_back.progressCallback); + } + + m_touchpadRecognizer->registerSwipeGesture(swipe_gesture); + return swipe_gesture; +} + +[[maybe_unused]] HoldGesture * GestureManager::registerTouchpadHold(const HoldFeedBack &feed) +{ + auto hold_gesture = new HoldGesture(this); + hold_gesture->setMinimumFingerCount(feed.fingerCount); + hold_gesture->setMaximumFingerCount(feed.fingerCount); + + if (feed.actionCallback) { + QObject::connect(hold_gesture, &HoldGesture::cancelled, feed.actionCallback); + } + + if (feed.longProcessCallback) { + QObject::connect(hold_gesture, &HoldGesture::longPressed, feed.longProcessCallback); + } + + m_touchpadRecognizer->registerHoldGesture(hold_gesture); + return hold_gesture; +} + +void GestureManager::unregisterTouchpadSwipe(SwipeGesture *gesture) +{ + m_touchpadRecognizer->unregisterSwipeGesture(gesture); +} + +void GestureManager::unregisterTouchpadHold(HoldGesture *gesture) +{ + m_touchpadRecognizer->unregisterHoldGesture(gesture); +} + +void GestureManager::processSwipeStart(uint finger) +{ + cancel(); + m_sequence = Sequence::Swipe; + m_touchpadFingerCount = finger; + if (m_touchpadFingerCount >= MIN_SWIPE_FINGERS) { + m_touchpadRecognizer->startSwipeGesture(finger); + } +} + +void GestureManager::processSwipeUpdate(const QPointF &delta) +{ + if (m_sequence != Sequence::Swipe) + return; + if (m_touchpadFingerCount >= MIN_SWIPE_FINGERS) { + m_touchpadRecognizer->updateSwipeGesture(delta); + } +} + +void GestureManager::processSwipeCancel() +{ + if (m_sequence != Sequence::Swipe) + return; + if (m_touchpadFingerCount >= MIN_SWIPE_FINGERS) { + m_touchpadRecognizer->cancelSwipeGesture(); + } + m_touchpadFingerCount = 0; + m_sequence = Sequence::None; +} + +void GestureManager::processSwipeEnd() +{ + if (m_sequence != Sequence::Swipe) + return; + if (m_touchpadFingerCount >= MIN_SWIPE_FINGERS) { + m_touchpadRecognizer->endSwipeGesture(); + } + m_touchpadFingerCount = 0; + m_sequence = Sequence::None; +} + +void GestureManager::processHoldStart(uint finger) +{ + cancel(); + m_sequence = Sequence::Hold; + m_touchpadFingerCount = finger; + if (m_touchpadFingerCount >= MIN_SWIPE_FINGERS) { + m_touchpadRecognizer->startHoldGesture(finger); + } +} + +void GestureManager::processHoldEnd() +{ + if (m_sequence != Sequence::Hold) + return; + if (m_touchpadFingerCount >= MIN_SWIPE_FINGERS) { + m_touchpadRecognizer->endHoldGesture(); + } + m_touchpadFingerCount = 0; + m_sequence = Sequence::None; +} + +void GestureManager::setHoldTimeout(int msec) +{ + m_touchpadRecognizer->setHoldTimeout(msec); +} diff --git a/src/input/gesturemanager.h b/src/input/gesturemanager.h new file mode 100644 index 0000000000..61f9189eab --- /dev/null +++ b/src/input/gesturemanager.h @@ -0,0 +1,60 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "swipegesture.h" +#include "holdgesture.h" + +#include +#include + +class GestureRecognizer; + +struct SwipeFeedBack +{ + SwipeGesture::Direction direction; + uint fingerCount; + std::function actionCallback; + std::function progressCallback; +}; + +struct HoldFeedBack +{ + uint fingerCount; + std::function actionCallback; + std::function longProcessCallback; +}; + +class GestureManager : public QObject +{ +public: + explicit GestureManager(QObject *parent = nullptr); + ~GestureManager() override; + void cancel(); + + GestureManager(const GestureManager &) = delete; + GestureManager &operator=(const GestureManager &) = delete; + + SwipeGesture *registerTouchpadSwipe(const SwipeFeedBack &feed_back); + HoldGesture *registerTouchpadHold(const HoldFeedBack &feed); + + void unregisterTouchpadSwipe(SwipeGesture *gesture); + void unregisterTouchpadHold(HoldGesture *gesture); + + void processSwipeStart(uint finger); + void processSwipeUpdate(const QPointF &delta); + void processSwipeCancel(); + void processSwipeEnd(); + + void processHoldStart(uint finger); + void processHoldEnd(); + void setHoldTimeout(int msec); + +private: + std::unique_ptr m_touchpadRecognizer; + enum class Sequence { None, Swipe, Hold }; + Sequence m_sequence = Sequence::None; + uint m_touchpadFingerCount = 0; +}; + diff --git a/src/input/gesturerecognizer.cpp b/src/input/gesturerecognizer.cpp new file mode 100644 index 0000000000..42ec4ddaa8 --- /dev/null +++ b/src/input/gesturerecognizer.cpp @@ -0,0 +1,260 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "gesturerecognizer.h" + +#include "common/treelandlogging.h" + +#include +#include +#include + +// The minimum delta required to recognize a swipe gesture +#define SWIPE_MINIMUM_DELTA 5 + +GestureRecognizer::GestureRecognizer(QObject *parent) + : QObject(parent) +{ +} + +void GestureRecognizer::registerSwipeGesture(SwipeGesture *gesture) +{ + Q_ASSERT(!m_swipeGestures.contains(gesture)); + connect(gesture, &QObject::destroyed, this, [this, gesture] { + m_swipeGestures.removeOne(gesture); + m_activeSwipeGestures.removeOne(gesture); + }); + m_swipeGestures << gesture; +} + +void GestureRecognizer::unregisterSwipeGesture(SwipeGesture *gesture) +{ + m_swipeGestures.removeOne(gesture); + if (m_activeSwipeGestures.removeOne(gesture)) { + Q_EMIT gesture->cancelled(); + } + gesture->deleteLater(); +} + +int GestureRecognizer::startSwipeGesture(uint fingerCount) +{ + return startSwipeGesture(fingerCount, QPointF(), GestureRecognizer::Irrelevant); +} + +int GestureRecognizer::startSwipeGesture(const QPointF &startPos) +{ + return startSwipeGesture(1, startPos, GestureRecognizer::Relevant); +} + +void GestureRecognizer::updateSwipeGesture(const QPointF &delta) +{ + m_currentDelta += delta; + + SwipeGesture::Direction direction; + Axis swipeAxis; + + if (m_currentSwipeAxis == Axis::None) { + if (std::abs(m_currentDelta.x()) >= std::abs(m_currentDelta.y())) { + swipeAxis = Axis::Horizontal; + direction = m_currentDelta.x() < 0 ? SwipeGesture::Left : SwipeGesture::Right; + } else { + swipeAxis = Axis::Vertical; + direction = m_currentDelta.y() < 0 ? SwipeGesture::Up : SwipeGesture::Down; + } + if (std::abs(m_currentDelta.x()) >= SWIPE_MINIMUM_DELTA + || std::abs(m_currentDelta.y()) >= SWIPE_MINIMUM_DELTA) { + m_currentSwipeAxis = swipeAxis; + } + } else { + swipeAxis = m_currentSwipeAxis; + } + + switch (swipeAxis) { + case Axis::Vertical: + direction = m_currentDelta.y() < 0 ? SwipeGesture::Up : SwipeGesture::Down; + break; + case Axis::Horizontal: + direction = m_currentDelta.x() < 0 ? SwipeGesture::Left : SwipeGesture::Right; + break; + default: + qCWarning(lcTlGestures) << "Invalid swipe axis"; + return; + } + + // Eliminating wrong gestures requires two iterations + for (int i = 0; i < 2; i++) { + if (m_activeSwipeGestures.isEmpty()) { + startSwipeGesture(m_currentFingerCount); + } + + m_activeSwipeGestures.erase(std::remove_if(m_activeSwipeGestures.begin(), + m_activeSwipeGestures.end(), + [direction](SwipeGesture *g) { + return g->direction() != direction; + }), + m_activeSwipeGestures.end()); + } + + for (auto &&gesture : std::as_const(m_activeSwipeGestures)) { + Q_EMIT gesture->progress(gesture->deltaToProgress(m_currentDelta)); + Q_EMIT gesture->deltaProgress(m_currentDelta); + } +} + +void GestureRecognizer::cancelSwipeGesture() +{ + cancelSwipeActiveGestures(); + m_currentFingerCount = 0; + m_currentDelta = QPointF(0, 0); + m_currentSwipeAxis = Axis::None; +} + +void GestureRecognizer::endSwipeGesture() +{ + const QPointF delta = m_currentDelta; + for (auto &&gesture : std::as_const(m_activeSwipeGestures)) { + if (gesture->minimumDeltaReached(delta)) { + Q_EMIT gesture->triggered(); + } else { + Q_EMIT gesture->cancelled(); + } + } + m_activeSwipeGestures.clear(); + m_currentFingerCount = 0; + m_currentDelta = QPointF(0, 0); + m_currentSwipeAxis = Axis::None; +} + +void GestureRecognizer::cancelSwipeActiveGestures() +{ + for (auto &&gesture : std::as_const(m_activeSwipeGestures)) { + Q_EMIT gesture->cancelled(); + } + m_activeSwipeGestures.clear(); + m_currentDelta = QPointF(0, 0); + m_currentSwipeAxis = Axis::None; +} + +int GestureRecognizer::startSwipeGesture(uint fingerCount, + const QPointF &start_pos, + StartPositionBehavior behavior) +{ + m_currentFingerCount = fingerCount; + if (!m_activeSwipeGestures.isEmpty()) { + return 0; + } + int count = 0; + for (auto &&gesture : std::as_const(m_swipeGestures)) { + if ((gesture->minimumFingerCountIsRelevant() && gesture->minimumFingerCount() > fingerCount) + || (gesture->maximumFingerCountIsRelevant() + && gesture->maximumFingerCount() < fingerCount)) { + continue; + } + if (behavior == StartPositionBehavior::Relevant) { + if ((gesture->minimumXIsRelevant() && gesture->minimumX() > start_pos.x()) + || (gesture->maximumXIsRelevant() && gesture->maximumX() < start_pos.x()) + || (gesture->minimumYIsRelevant() && gesture->minimumY() > start_pos.y()) + || (gesture->maximumYIsRelevant() && gesture->maximumY() < start_pos.y())) { + continue; + } + } + // Axis not yet locked — skip all gestures. The first updateSwipeGesture + // will lock the axis, then the two-pass loop rebuilds the active list + // with only matching-direction gestures. + if (m_currentSwipeAxis == Axis::None) { + continue; + } + + switch (gesture->direction()) { + case SwipeGesture::Up: + [[fallthrough]]; + case SwipeGesture::Down: + if (m_currentSwipeAxis == Axis::Horizontal) { + continue; + } + break; + case SwipeGesture::Left: + [[fallthrough]]; + case SwipeGesture::Right: + if (m_currentSwipeAxis == Axis::Vertical) { + continue; + } + break; + case SwipeGesture::Invalid: + qCWarning(lcTlGestures) << "Invalid swipe direction"; + continue; + } + + m_activeSwipeGestures << gesture; + count++; + Q_EMIT gesture->started(); + } + return count; +} + +void GestureRecognizer::registerHoldGesture(HoldGesture *gesture) +{ + Q_ASSERT(!m_holdGestures.contains(gesture)); + connect(gesture, &QObject::destroyed, this, [this, gesture] { + m_holdGestures.removeOne(gesture); + m_activeHoldGestures.removeOne(gesture); + }); + gesture->setInterval(m_holdTimeout); + m_holdGestures << gesture; +} + +void GestureRecognizer::setHoldTimeout(int msec) +{ + m_holdTimeout = msec; + for (auto &&gesture : std::as_const(m_holdGestures)) { + gesture->setInterval(msec); + } +} + +void GestureRecognizer::unregisterHoldGesture(HoldGesture *gesture) +{ + m_holdGestures.removeOne(gesture); + if (m_activeHoldGestures.removeOne(gesture)) { + Q_EMIT gesture->cancelled(); + } + gesture->deleteLater(); +} + +void GestureRecognizer::startHoldGesture(uint fingerCount) +{ + m_currentFingerCount = fingerCount; + for (auto &&gesture : std::as_const(m_holdGestures)) { + if (gesture->isActive()) + continue; + + if ((gesture->minimumFingerCountIsRelevant() && gesture->minimumFingerCount() > fingerCount) + || (gesture->maximumFingerCountIsRelevant() + && gesture->maximumFingerCount() < fingerCount)) + continue; + + gesture->startTimer(); + m_activeHoldGestures << gesture; + } +} + +void GestureRecognizer::endHoldGesture() +{ + for (auto &&gesture : std::as_const(m_activeHoldGestures)) { + if (gesture->isActive()) { + gesture->stopTimer(); + } + Q_EMIT gesture->cancelled(); + } + m_activeHoldGestures.clear(); + m_currentFingerCount = 0; +} + +void GestureRecognizer::cancelHoldGesture() +{ + // Cancel the sequence without emitting a release/hold action during a + // desktop handoff. No timer may call back into the old desktop afterwards. + for (auto *gesture : std::as_const(m_activeHoldGestures)) + gesture->stopTimer(); + m_activeHoldGestures.clear(); + m_currentFingerCount = 0; +} diff --git a/src/input/gesturerecognizer.h b/src/input/gesturerecognizer.h new file mode 100644 index 0000000000..4fce4dc3a9 --- /dev/null +++ b/src/input/gesturerecognizer.h @@ -0,0 +1,68 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "swipegesture.h" +#include "holdgesture.h" + +#include +#include +#include + +class GestureRecognizer : public QObject +{ + Q_OBJECT +public: + explicit GestureRecognizer(QObject *parent = nullptr); + + enum StartPositionBehavior + { + Relevant, + Irrelevant, + }; + + enum Axis + { + Horizontal, + Vertical, + None, + }; + + Q_ENUM(StartPositionBehavior) + Q_ENUM(Axis) + + void registerSwipeGesture(SwipeGesture *gesture); + void unregisterSwipeGesture(SwipeGesture *gesture); + + void registerHoldGesture(HoldGesture *gesture); + void unregisterHoldGesture(HoldGesture *gesture); + + int startSwipeGesture(uint fingerCount); + int startSwipeGesture(const QPointF &startPos); + + void updateSwipeGesture(const QPointF &delta); + void cancelSwipeGesture(); + void endSwipeGesture(); + + void startHoldGesture(uint fingerCount); + void endHoldGesture(); + void cancelHoldGesture(); + void setHoldTimeout(int msec); + +private: + void cancelSwipeActiveGestures(); + int startSwipeGesture(uint fingerCount, + const QPointF &start_pos, + StartPositionBehavior behavior); + + QList m_swipeGestures; + QList m_activeSwipeGestures; + QList m_holdGestures; + QList m_activeHoldGestures; + + QPointF m_currentDelta = QPointF(0, 0); + uint m_currentFingerCount = 0; + int m_holdTimeout = 0; + GestureRecognizer::Axis m_currentSwipeAxis = GestureRecognizer::None; +}; diff --git a/src/input/gestures.cpp b/src/input/gestures.cpp new file mode 100644 index 0000000000..19261fce07 --- /dev/null +++ b/src/input/gestures.cpp @@ -0,0 +1,9 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "gestures.h" + +Gesture::Gesture(QObject *parent) + : QObject(parent) +{ +} diff --git a/src/input/gestures.h b/src/input/gestures.h new file mode 100644 index 0000000000..9c6476d8be --- /dev/null +++ b/src/input/gestures.h @@ -0,0 +1,19 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +class Gesture : public QObject +{ + Q_OBJECT +public: + Gesture(QObject *parent = nullptr); + +Q_SIGNALS: + void started(); + void triggered(); + void cancelled(); + void longPressed(); +}; diff --git a/src/input/holdgesture.cpp b/src/input/holdgesture.cpp new file mode 100644 index 0000000000..78b4115c55 --- /dev/null +++ b/src/input/holdgesture.cpp @@ -0,0 +1,79 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "holdgesture.h" + +#include + +HoldGesture::HoldGesture(QObject *parent) + : Gesture(parent) + , m_holdTimer(new QTimer(this)) +{ + m_holdTimer->setSingleShot(true); + connect(m_holdTimer, &QTimer::timeout, this, &HoldGesture::longPressed); +} + +bool HoldGesture::minimumFingerCountIsRelevant() const +{ + return m_minimumFingerCountRelevant; +} + +void HoldGesture::setMinimumFingerCount(uint count) +{ + if (count == m_minimumFingerCount) { + return; + } + m_minimumFingerCount = count; + m_minimumFingerCountRelevant = true; +} + +uint HoldGesture::minimumFingerCount() const +{ + return m_minimumFingerCount; +} + +bool HoldGesture::maximumFingerCountIsRelevant() const +{ + return m_maximumFingerCountRelevant; +} + +void HoldGesture::setMaximumFingerCount(uint count) +{ + if (count == m_maximumFingerCount) { + return; + } + m_maximumFingerCount = count; + m_maximumFingerCountRelevant = true; +} + +uint HoldGesture::maximumFingerCount() const +{ + return m_maximumFingerCount; +} + +HoldGesture::~HoldGesture() +{ + if (m_holdTimer != nullptr) { + m_holdTimer->stop(); + } +} + +void HoldGesture::startTimer() +{ + m_holdTimer->start(); +} + +void HoldGesture::setInterval(int msec) +{ + m_holdTimer->setInterval(msec); +} + +void HoldGesture::stopTimer() +{ + m_holdTimer->stop(); +} + +bool HoldGesture::isActive() const +{ + return m_holdTimer->isActive(); +} diff --git a/src/input/holdgesture.h b/src/input/holdgesture.h new file mode 100644 index 0000000000..4153618ef0 --- /dev/null +++ b/src/input/holdgesture.h @@ -0,0 +1,36 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "gestures.h" + +class QTimer; + +class HoldGesture : public Gesture +{ + Q_OBJECT +public: + explicit HoldGesture(QObject *parent = nullptr); + ~HoldGesture(); + + void setInterval(int msec); + void startTimer(); + void stopTimer(); + bool isActive() const; + + bool minimumFingerCountIsRelevant() const; + void setMinimumFingerCount(uint count); + uint minimumFingerCount() const; + + bool maximumFingerCountIsRelevant() const; + void setMaximumFingerCount(uint count); + uint maximumFingerCount() const; + +private: + QTimer *m_holdTimer; + bool m_minimumFingerCountRelevant = false; + uint m_minimumFingerCount = 0; + bool m_maximumFingerCountRelevant = false; + uint m_maximumFingerCount = 0; +}; diff --git a/src/input/inputcontext.h b/src/input/inputcontext.h new file mode 100644 index 0000000000..1791ec0f27 --- /dev/null +++ b/src/input/inputcontext.h @@ -0,0 +1,37 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include + +class SeatSurfaceManager; +class SurfaceWrapper; +WAYLIB_SERVER_BEGIN_NAMESPACE +class WSeat; +class WSurface; +WAYLIB_SERVER_END_NAMESPACE + +// Fixed capabilities of one desktop. Input workers cannot look up another +// desktop or switch the owner of these capabilities. +class InputContext +{ +public: + virtual ~InputContext() = default; + virtual bool available() const = 0; + virtual bool locked() const = 0; + virtual bool normal() const = 0; + virtual bool switchVirtualTerminal(int number) = 0; + virtual bool toggleDebugView() = 0; + virtual WAYLIB_SERVER_NAMESPACE::WSeat *primarySeat() const = 0; + virtual SeatSurfaceManager *seatContainer(WAYLIB_SERVER_NAMESPACE::WSeat *seat) const = 0; + virtual SurfaceWrapper *surface(WAYLIB_SERVER_NAMESPACE::WSurface *surface) const = 0; + virtual void activateSurface(WAYLIB_SERVER_NAMESPACE::WSurface *surface, + WAYLIB_SERVER_NAMESPACE::WSeat *seat, Qt::FocusReason reason) = 0; + virtual void moveResize(WAYLIB_SERVER_NAMESPACE::WSeat *seat, const QPointF &delta) = 0; + virtual void endMoveResize(WAYLIB_SERVER_NAMESPACE::WSeat *seat) = 0; + virtual void cancelMoveResize(WAYLIB_SERVER_NAMESPACE::WSeat *seat) = 0; + virtual void detectEdgeTiling(WAYLIB_SERVER_NAMESPACE::WSeat *seat) = 0; +}; diff --git a/src/input/inputmanager.cpp b/src/input/inputmanager.cpp new file mode 100644 index 0000000000..c01dec3f09 --- /dev/null +++ b/src/input/inputmanager.cpp @@ -0,0 +1,576 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include "inputmanager.h" +#include "dconfig/dconfigmanager.h" +#include "seatuserconfig.hpp" +#include "libinputconfig.h" +#include "gesturemanager.h" +#include "common/treelandlogging.h" +#include "modules/input-manager/inputmanagerinterfacev1.h" +#include "seat/seatmanager.h" + +#include +#include + +#include + +#include +#include +#include +#include + +InputManager::InputManager(ConfigProvider configuration, SeatProvider seats, SeatManager *hardware, + WBackend *backend, QObject *parent) + : QObject(parent) + , m_configuration(std::move(configuration)) + , m_seats(std::move(seats)) + , m_hardware(hardware) + , m_backend(backend) +{ +} + +InputManager::~InputManager() +{ +} + +void InputManager::activate() +{ + m_attached = true; + auto *seats = m_hardware; + connect(seats, &SeatManager::seatAdded, this, &InputManager::setupSeat, Qt::UniqueConnection); + connect(seats, &SeatManager::seatRemoved, this, &InputManager::onSeatRemoved, Qt::UniqueConnection); + connect(seats, &SeatManager::deviceAssigned, this, &InputManager::onInputAssigned, Qt::UniqueConnection); + connect(this, &InputManager::settingsChanged, this, &InputManager::setupSeat, Qt::UniqueConnection); + refresh(); +} + +void InputManager::deactivate() +{ + m_attached = false; + disconnect(m_hardware, nullptr, this, nullptr); + disconnect(this, &InputManager::settingsChanged, this, &InputManager::setupSeat); +} + +void InputManager::refresh() +{ + for (auto *seat : m_seats()) + setupSeat(seat); +} + +SeatUserDConfig *InputManager::seatUserConfig(WSeat *seat) const +{ + auto *config = m_configuration(seat->name()); + Q_ASSERT(config); + + return config; +} + +void InputManager::setupSeat(WSeat *seat) +{ + auto *config = seatUserConfig(seat); + connect(config, &SeatUserDConfig::valueChanged, + this, &InputManager::refresh, Qt::UniqueConnection); + if (!configurationReady(config)) { + connect(config, &SeatUserDConfig::configInitializeSucceed, + this, &InputManager::refresh, Qt::UniqueConnection); + connect(config, &SeatUserDConfig::configInitializeFailed, + this, &InputManager::refresh, Qt::UniqueConnection); + return; + } + if (auto *cursor = seat->cursor()) + cursor->setScrollFactor(config->pointerScrollFactor()); + + if (m_gestures) + m_gestures->setHoldTimeout(config->touchpadHoldTimeoutMs()); + + applyXkbConfigForSeat(seat); + + const auto devices = seat->deviceList(); + for (WInputDevice *device : devices) + onInputAssigned(device); + + applyNumLockToKeyboards(); +} + +void InputManager::onMouseSettingsCreated(MouseSettingsInterfaceV1 *interface) +{ + connect(interface, + &MouseSettingsInterfaceV1::pointerDeviceConfigurationCreated, + this, + &InputManager::onMousePointerConfigCreated); +} + +void InputManager::onTouchpadSettingsCreated(TouchpadSettingsInterfaceV1 *interface) +{ + connect(interface, + &TouchpadSettingsInterfaceV1::pointerDeviceConfigurationCreated, + this, + &InputManager::onTouchpadPointerConfigCreated); +} + +void InputManager::onKeyboardSettingsCreated(KeyboardSettingsInterfaceV1 *interface) +{ + initializeKeyboardSettings(interface); +} + +bool InputManager::initializeKeyboardSettings(KeyboardSettingsInterfaceV1 *interface) +{ + if (interface->property("_treelandKeyboardSettingsInitialized").toBool()) + return true; + + auto *seatConfig = seatUserConfig(interface->wSeat()); + + if (!configurationReady(seatConfig)) { + const auto initialize = [this, interface = QPointer(interface)] { + if (interface) + initializeKeyboardSettings(interface); + }; + connect(seatConfig, &SeatUserDConfig::configInitializeSucceed, this, initialize); + connect(seatConfig, &SeatUserDConfig::configInitializeFailed, this, initialize); + return false; + } + + KeyboardSettingsInterfaceV1::FeatureFlags features; + const auto inputDevices = m_backend->inputDeviceList(); + for (WInputDevice *device : std::as_const(inputDevices)) { + if (!wlr_input_device_is_libinput(device->handle())) { + continue; + } + + if (device->type() != WInputDevice::Type::Keyboard) + continue; + + if (device->handle()->type != WLR_INPUT_DEVICE_KEYBOARD) + continue; + + auto *wlrKeyboard = wlr_keyboard_from_input_device(device->handle()); + if (!wlrKeyboard || !wlrKeyboard->keymap) + continue; + + if (xkb_map_mod_get_index(wlrKeyboard->keymap, XKB_MOD_NAME_NUM) != XKB_MOD_INVALID) { + features.setFlag(KeyboardSettingsInterfaceV1::NumLock); + break; + } + } + + interface->sendFeature(features, true); + interface->sendNumLock(seatConfig->keyboardNumLock(), true); + interface->sendRepeat(seatConfig->keyboardRate(), seatConfig->keyboardDelay(), true); + interface->sendXkbRules(seatConfig->xkbLayout(), + seatConfig->xkbModel(), + seatConfig->xkbVariant(), + seatConfig->xkbOptions(), + true); + interface->sendDone(); + + connect(interface, + &KeyboardSettingsInterfaceV1::applied, + this, + &InputManager::onKeyboardSettingsApplied); + + interface->setProperty("_treelandKeyboardSettingsInitialized", true); + + return true; +} + +void InputManager::onMousePointerConfigCreated(PointerDeviceConfigurationV1 *config) +{ + auto *ownerConfig = seatUserConfig(config->wSeat()); + if (!configurationReady(ownerConfig)) { + const auto initialize = [this, interface = QPointer(config)] { + if (interface) + onMousePointerConfigCreated(interface); + }; + connect(ownerConfig, &SeatUserDConfig::configInitializeSucceed, this, initialize); + connect(ownerConfig, &SeatUserDConfig::configInitializeFailed, this, initialize); + return; + } + auto *seatConfig = seatUserConfig(config->wSeat()); + + PointerDeviceConfigurationV1::FeatureFlags features; + features.setFlag(PointerDeviceConfigurationV1::ScrollFactor); + features.setFlag(PointerDeviceConfigurationV1::EventsMode); + + const auto inputDevices = m_backend->inputDeviceList(); + for (WInputDevice *device : std::as_const(inputDevices)) { + if (!wlr_input_device_is_libinput(device->handle())) { + continue; + } + + if (device->type() != WInputDevice::Type::Pointer) { + continue; + } + + struct libinput_device *inputDevice = wlr_libinput_get_device_handle(device->handle()); + struct udev_device *udevDevice = + libinput_device_get_udev_device(inputDevice); + if (!udev_device_get_property_value(udevDevice, "ID_INPUT_MOUSE")) { + continue; + } + + if (libinput_device_config_scroll_has_natural_scroll(inputDevice)) { + features.setFlag(PointerDeviceConfigurationV1::NaturalScroll); + } + + if (libinput_device_config_left_handed_is_available(inputDevice)) { + features.setFlag(PointerDeviceConfigurationV1::HandMode); + } + + if (libinput_device_config_accel_is_available(inputDevice)) { + features.setFlag(PointerDeviceConfigurationV1::AccelProfile); + features.setFlag(PointerDeviceConfigurationV1::AccelSpeed); + } + + if (libinput_device_config_tap_get_finger_count(inputDevice) > 0) { + features.setFlag(PointerDeviceConfigurationV1::TapToClick); + } + + if (libinput_device_config_dwt_is_available(inputDevice)) { + features.setFlag(PointerDeviceConfigurationV1::DisableWhileTyping); + } + } + + config->sendFeature(features, true); + config->sendScrollFactor(seatConfig->pointerScrollFactor(), true); + + auto handModeStr = seatConfig->pointerHandMode(); + auto handMode = (handModeStr == "Left") + ? PointerDeviceConfigurationV1::Left + : PointerDeviceConfigurationV1::Right; + config->sendHandedMode(handMode, true); + + config->sendAccelSpeed(seatConfig->mouseAccelSpeed(), true); + config->sendAccelerationProfile(static_cast(seatConfig->mouseAccelerationProfile()), true); + config->sendNaturalScroll(seatConfig->mouseNaturalScroll(), true); + config->sendDone(0); + + connect(config, + &PointerDeviceConfigurationV1::applied, + this, + &InputManager::onMousePointerConfigApplied); +} + +void InputManager::onMousePointerConfigApplied(PointerDeviceConfigurationV1::ChangeFlags changes) +{ + auto *interface = static_cast(sender()); + auto *seatConfig = seatUserConfig(interface->wSeat()); + + if (changes.testFlag(PointerDeviceConfigurationV1::ScrollFactorChanged)) { + seatConfig->setPointerScrollFactor(interface->scrollFactor()); + } + + if (changes.testFlag(PointerDeviceConfigurationV1::HandedModeChanged)) { + seatConfig->setPointerHandMode(interface->handedMode() == PointerDeviceConfigurationV1::Left + ? QStringLiteral("Left") + : QStringLiteral("Right")); + } + + if (changes.testFlag(PointerDeviceConfigurationV1::AccelSpeedChanged)) { + seatConfig->setMouseAccelSpeed(interface->accelSpeed()); + } + + if (changes.testFlag(PointerDeviceConfigurationV1::AccelerationProfileChanged)) { + seatConfig->setMouseAccelerationProfile(interface->accelerationProfile()); + } + + if (changes.testFlag(PointerDeviceConfigurationV1::NaturalScrollChanged)) { + seatConfig->setMouseNaturalScroll(interface->naturalScroll()); + } + + Q_EMIT settingsChanged(interface->wSeat()); +} + +void InputManager::onTouchpadPointerConfigCreated(PointerDeviceConfigurationV1 *config) +{ + auto *ownerConfig = seatUserConfig(config->wSeat()); + if (!configurationReady(ownerConfig)) { + const auto initialize = [this, interface = QPointer(config)] { + if (interface) + onTouchpadPointerConfigCreated(interface); + }; + connect(ownerConfig, &SeatUserDConfig::configInitializeSucceed, this, initialize); + connect(ownerConfig, &SeatUserDConfig::configInitializeFailed, this, initialize); + return; + } + PointerDeviceConfigurationV1::FeatureFlags features; + features.setFlag(PointerDeviceConfigurationV1::ScrollFactor); + features.setFlag(PointerDeviceConfigurationV1::EventsMode); + + const auto inputDevices = m_backend->inputDeviceList(); + for (WInputDevice *device : std::as_const(inputDevices)) { + if (!wlr_input_device_is_libinput(device->handle())) { + continue; + } + + if (device->type() != WInputDevice::Type::Pointer) { + continue; + } + + struct libinput_device *inputDevice = wlr_libinput_get_device_handle(device->handle()); + struct udev_device *udevDevice = + libinput_device_get_udev_device(inputDevice); + if (!udev_device_get_property_value(udevDevice, "ID_INPUT_TOUCHPAD")) { + continue; + } + + if (libinput_device_config_scroll_has_natural_scroll(inputDevice)) { + features.setFlag(PointerDeviceConfigurationV1::NaturalScroll); + } + + if (libinput_device_config_left_handed_is_available(inputDevice)) { + features.setFlag(PointerDeviceConfigurationV1::HandMode); + } + + if (libinput_device_config_accel_is_available(inputDevice)) { + features.setFlag(PointerDeviceConfigurationV1::AccelProfile); + features.setFlag(PointerDeviceConfigurationV1::AccelSpeed); + } + + if (libinput_device_config_tap_get_finger_count(inputDevice) > 0) { + features.setFlag(PointerDeviceConfigurationV1::TapToClick); + } + + if (libinput_device_config_dwt_is_available(inputDevice)) { + features.setFlag(PointerDeviceConfigurationV1::DisableWhileTyping); + } + } + + auto *seatConfig = seatUserConfig(config->wSeat()); + + config->sendFeature(features, true); + config->sendScrollFactor(seatConfig->pointerScrollFactor(), true); + config->sendAccelSpeed(seatConfig->touchpadAccelSpeed(), true); + config->sendAccelerationProfile(static_cast(seatConfig->touchpadAccelerationProfile()), true); + config->sendNaturalScroll(seatConfig->touchpadNaturalScroll(), true); + config->sendSendEventsMode(PointerDeviceConfigurationV1::SendEventsModes::fromInt(seatConfig->touchpadSendEventsMode()), true); + config->sendDisableWhileTyping(seatConfig->touchpadDisableWhileTyping(), true); + config->sendTapToClick(seatConfig->touchpadTapToClick(), true); + config->sendDone(0); + + connect(config, + &PointerDeviceConfigurationV1::applied, + this, + &InputManager::onTouchpadPointerConfigApplied); +} + +void InputManager::onTouchpadPointerConfigApplied(PointerDeviceConfigurationV1::ChangeFlags changes) +{ + auto *interface = static_cast(sender()); + auto *seatConfig = seatUserConfig(interface->wSeat()); + + if (changes.testFlag(PointerDeviceConfigurationV1::ScrollFactorChanged)) { + seatConfig->setPointerScrollFactor(interface->scrollFactor()); + } + + if (changes.testFlag(PointerDeviceConfigurationV1::AccelSpeedChanged)) { + seatConfig->setTouchpadAccelSpeed(interface->accelSpeed()); + } + + if (changes.testFlag(PointerDeviceConfigurationV1::NaturalScrollChanged)) { + seatConfig->setTouchpadNaturalScroll(interface->naturalScroll()); + } + + if (changes.testFlag(PointerDeviceConfigurationV1::SendEventsModeChanged)) { + seatConfig->setTouchpadSendEventsMode(interface->sendEventsMode().toInt()); + } + + if (changes.testFlag(PointerDeviceConfigurationV1::DisableWhileTypingChanged)) { + seatConfig->setTouchpadDisableWhileTyping(interface->disableWhileTyping()); + } + + if (changes.testFlag(PointerDeviceConfigurationV1::TapToClickChanged)) { + seatConfig->setTouchpadTapToClick(interface->tapToClick()); + } + + if (changes.testFlag(PointerDeviceConfigurationV1::AccelerationProfileChanged)) + seatConfig->setTouchpadAccelerationProfile(interface->accelerationProfile()); + Q_EMIT settingsChanged(interface->wSeat()); +} + +void InputManager::onKeyboardSettingsApplied(KeyboardSettingsInterfaceV1::ChangeFlags changes) +{ + KeyboardSettingsInterfaceV1 *interface = + static_cast(sender()); + auto *seatConfig = seatUserConfig(interface->wSeat()); + + if (!seatConfig->isInitializeSucceeded()) { + interface->sendFailed(); + return; + } + + if (changes.testFlag(KeyboardSettingsInterfaceV1::NumLockChanged)) { + seatConfig->setKeyboardNumLock(interface->numLock()); + } + + if (changes.testFlag(KeyboardSettingsInterfaceV1::RepeatChanged)) { + seatConfig->setKeyboardDelay(interface->repeatDelay()); + seatConfig->setKeyboardRate(interface->repeatRate()); + } + + if (changes.testFlag(KeyboardSettingsInterfaceV1::XkbRulesChanged)) { + seatConfig->setXkbLayout(interface->xkbLayout()); + seatConfig->setXkbModel(interface->xkbModel()); + seatConfig->setXkbVariant(interface->xkbVariant()); + seatConfig->setXkbOptions(interface->xkbOptions()); + } + + Q_EMIT settingsChanged(interface->wSeat()); +} + +void InputManager::applyNumLockToKeyboards() +{ + const auto seats = m_seats(); + for (WSeat *seat : seats) { + auto *config = seatUserConfig(seat); + if (configurationReady(config)) + setNumLockForSeat(seat, config->keyboardNumLock()); + } +} + +void InputManager::applyXkbConfigForSeat(WSeat *seat) +{ + if (!m_seats().contains(seat)) { + return; + } + + auto *seatConfig = seatUserConfig(seat); + + applyXkbConfig(seat, + seatConfig->xkbLayout(), + seatConfig->xkbModel(), + seatConfig->xkbVariant(), + seatConfig->xkbOptions()); +} + +void InputManager::applyXkbConfig(WSeat *seat, + const QString &layoutName, + const QString &modelName, + const QString &variantName, + const QString &optionsName) +{ + Q_ASSERT(seat); + + struct xkb_rule_names rules = {}; + QByteArray layout = layoutName.toUtf8(); + QByteArray model = modelName.toUtf8(); + QByteArray variant = variantName.toUtf8(); + QByteArray options = optionsName.toUtf8(); + rules.layout = layout.constData(); + rules.model = model.constData(); + rules.variant = variant.constData(); + rules.options = options.constData(); + + seat->setXkbRuleNames(rules); + + applyNumLockToKeyboards(); +} + +void InputManager::setNumLockForSeat(WSeat *seat, bool enabled) +{ + if (!seat) + return; + + const auto devices = seat->deviceList(); + for (auto *device : devices) { + if (device->type() == WInputDevice::Type::Keyboard) + setNumLockForDevice(device, enabled); + } + + setNumLockForDevice(seat->keyboardGroupKeyboard(), enabled); +} + +void InputManager::setNumLockForDevice(WInputDevice *device, bool enabled) +{ + if (!device || device->type() != WInputDevice::Type::Keyboard) + return; + + if (device->handle()->type != WLR_INPUT_DEVICE_KEYBOARD) + return; + auto *wlrKeyboard = wlr_keyboard_from_input_device(device->handle()); + if (!wlrKeyboard || !wlrKeyboard->keymap || !wlrKeyboard->xkb_state) + return; + + xkb_mod_index_t numlock = xkb_keymap_mod_get_index(wlrKeyboard->keymap, XKB_MOD_NAME_NUM); + if (numlock == XKB_MOD_INVALID) + return; + + xkb_mod_mask_t locked = xkb_state_serialize_mods(wlrKeyboard->xkb_state, XKB_STATE_MODS_LOCKED); + if (enabled) { + locked |= (1u << numlock); + } else { + locked &= ~(1u << numlock); + } + const auto depressed = xkb_state_serialize_mods(wlrKeyboard->xkb_state, XKB_STATE_MODS_DEPRESSED); + const auto latched = xkb_state_serialize_mods(wlrKeyboard->xkb_state, XKB_STATE_MODS_LATCHED); + const auto group = xkb_state_serialize_layout(wlrKeyboard->xkb_state, XKB_STATE_LAYOUT_EFFECTIVE); + wlr_keyboard_notify_modifiers(wlrKeyboard, depressed, latched, locked, group); +} + +void InputManager::onInputAssigned(WInputDevice *input) +{ + auto *seat = input->seat(); + Q_ASSERT(seat); + auto *seatConfig = seatUserConfig(seat); + + if (!configurationReady(seatConfig)) { + connect(seatConfig, &SeatUserDConfig::configInitializeSucceed, + this, &InputManager::refresh, Qt::UniqueConnection); + connect(seatConfig, &SeatUserDConfig::configInitializeFailed, + this, &InputManager::refresh, Qt::UniqueConnection); + return; + } + + if (input->type() == WInputDevice::Type::Keyboard) { + if (input->handle()->type == WLR_INPUT_DEVICE_KEYBOARD) { + auto *keyboard = wlr_keyboard_from_input_device(input->handle()); + wlr_keyboard_set_repeat_info(keyboard, seatConfig->keyboardRate(), seatConfig->keyboardDelay()); + } + setNumLockForSeat(seat, seatConfig->keyboardNumLock()); + } + + if (!wlr_input_device_is_libinput(input->handle())) { + return; + } + + struct libinput_device *inputDevice = wlr_libinput_get_device_handle(input->handle()); + struct udev_device *udevDevice = libinput_device_get_udev_device(inputDevice); + bool leftHanded = (seatConfig->pointerHandMode() == "Left"); + + + if (udev_device_get_property_value(udevDevice, "ID_INPUT_MOUSE")) { + configLeftHanded(inputDevice, leftHanded); + configAccelSpeed(inputDevice, seatConfig->mouseAccelSpeed()); + configAccelProfile(inputDevice, static_cast(seatConfig->mouseAccelerationProfile())); + configNaturalScroll(inputDevice, seatConfig->mouseNaturalScroll()); + } + + if (udev_device_get_property_value(udevDevice, "ID_INPUT_TOUCHPAD")) { + configLeftHanded(inputDevice, leftHanded); + configAccelSpeed(inputDevice, seatConfig->touchpadAccelSpeed()); + configAccelProfile(inputDevice, static_cast(seatConfig->touchpadAccelerationProfile())); + configNaturalScroll(inputDevice, seatConfig->touchpadNaturalScroll()); + configSendEventsMode(inputDevice, seatConfig->touchpadSendEventsMode()); + configDwtEnabled(inputDevice, seatConfig->touchpadDisableWhileTyping() + ? LIBINPUT_CONFIG_DWT_ENABLED + : LIBINPUT_CONFIG_DWT_DISABLED); + configTapEnabled(inputDevice, seatConfig->touchpadTapToClick() + ? LIBINPUT_CONFIG_TAP_ENABLED + : LIBINPUT_CONFIG_TAP_DISABLED); + } +} + +void InputManager::onSeatRemoved(WSeat *seat) +{ + auto *config = seatUserConfig(seat); + disconnect(config, nullptr, this, nullptr); +} + +bool InputManager::hardwareAttached() const { return m_attached; } + +void InputManager::setGestureManager(GestureManager *gestures) +{ + Q_ASSERT(!m_gestures); + m_gestures = gestures; +} diff --git a/src/input/inputmanager.h b/src/input/inputmanager.h new file mode 100644 index 0000000000..5facb104f5 --- /dev/null +++ b/src/input/inputmanager.h @@ -0,0 +1,83 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "modules/input-manager/inputmanagerinterfacev1.h" +Q_MOC_INCLUDE("seatuserconfig.hpp") + +#include + +#include +#include +#include +#include + +#include + +class SeatUserDConfig; +class SeatManager; +class GestureManager; +WAYLIB_SERVER_BEGIN_NAMESPACE +class WBackend; +WAYLIB_SERVER_END_NAMESPACE + +class InputManager : public QObject +{ + Q_OBJECT + QML_ANONYMOUS +public: + using ConfigProvider = std::function; + using SeatProvider = std::function()>; + InputManager(ConfigProvider configuration, SeatProvider seats, SeatManager *hardware, + WAYLIB_SERVER_NAMESPACE::WBackend *backend, + QObject *parent = nullptr); + bool hardwareAttached() const; + void setGestureManager(GestureManager *gestures); + ~InputManager() override; + + static void setNumLockForDevice(WInputDevice *device, bool enabled); + + void refresh(); + +Q_SIGNALS: + void settingsChanged(WSeat *seat); + +public: + void activate(); + void deactivate(); + +public Q_SLOTS: + void onMouseSettingsCreated(MouseSettingsInterfaceV1 *interface); + void onTouchpadSettingsCreated(TouchpadSettingsInterfaceV1 *interface); + void onKeyboardSettingsCreated(KeyboardSettingsInterfaceV1 *interface); + void onMousePointerConfigCreated(PointerDeviceConfigurationV1 *config); + void onTouchpadPointerConfigCreated(PointerDeviceConfigurationV1 *config); + +private Q_SLOTS: + void onMousePointerConfigApplied(PointerDeviceConfigurationV1::ChangeFlags changes); + void onTouchpadPointerConfigApplied(PointerDeviceConfigurationV1::ChangeFlags changes); + void onKeyboardSettingsApplied(KeyboardSettingsInterfaceV1::ChangeFlags changes); + void onInputAssigned(WInputDevice *input); + void onSeatRemoved(WSeat *seat); + +private: + const ConfigProvider m_configuration; + const SeatProvider m_seats; + SeatManager *const m_hardware; + WAYLIB_SERVER_NAMESPACE::WBackend *const m_backend; + GestureManager *m_gestures = nullptr; + bool m_attached = false; + bool initializeKeyboardSettings(KeyboardSettingsInterfaceV1 *interface); + SeatUserDConfig *seatUserConfig(WSeat *seat) const; + void setupSeat(WSeat *seat); + void applyNumLockToKeyboards(); + void applyXkbConfigForSeat(WSeat *seat); + void applyXkbConfig(WSeat *seat, + const QString &layout, + const QString &model, + const QString &variant, + const QString &options); + static void setNumLockForSeat(WSeat *seat, bool enabled); + +}; diff --git a/src/input/libinputconfig.cpp b/src/input/libinputconfig.cpp new file mode 100644 index 0000000000..468ab84c13 --- /dev/null +++ b/src/input/libinputconfig.cpp @@ -0,0 +1,345 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "libinputconfig.h" +#include "common/treelandlogging.h" + +#include + +#include + +static bool ensureStatus(libinput_config_status status) +{ + if (status != LIBINPUT_CONFIG_STATUS_SUCCESS) { + qCCritical(lcTlInput) << "Failed to apply libinput config: " + << libinput_config_status_to_str(status); + return false; + } + + return true; +} + +bool configSendEventsMode(libinput_device *device, uint32_t mode) +{ + if (libinput_device_config_send_events_get_mode(device) == mode) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_send_events_set_mode " << mode; + enum libinput_config_status status = libinput_device_config_send_events_set_mode(device, mode); + + return ensureStatus(status); +} + +bool configTapEnabled(libinput_device *device, libinput_config_tap_state tap) +{ + if (libinput_device_config_tap_get_finger_count(device) <= 0) { + qCCritical(lcTlInput) << "libinput_device_config_tap_set_enabled is invalid"; + + return false; + } + + if (libinput_device_config_tap_get_enabled(device) == tap) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_tap_set_enabled: " << tap; + enum libinput_config_status status = libinput_device_config_tap_set_enabled(device, tap); + + return ensureStatus(status); +} + +bool configTapButtonMap(libinput_device *device, libinput_config_tap_button_map map) +{ + if (libinput_device_config_tap_get_finger_count(device) <= 0) { + qCCritical(lcTlInput) << "libinput_device_config_tap_set_button_map is invalid"; + + return false; + } + + if (libinput_device_config_tap_get_button_map(device) == map) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_tap_set_button_map: " << map; + enum libinput_config_status status = libinput_device_config_tap_set_button_map(device, map); + + return ensureStatus(status); +} + +bool configTapDragEnabled(libinput_device *device, libinput_config_drag_state drag) +{ + if (libinput_device_config_tap_get_finger_count(device) <= 0) { + qCCritical(lcTlInput) << "libinput_device_config_tap_set_drag_enabled is invalid"; + + return false; + } + + if (libinput_device_config_tap_get_drag_enabled(device) == drag) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_tap_set_drag_enabled: " << drag; + enum libinput_config_status status = libinput_device_config_tap_set_drag_enabled(device, drag); + + return ensureStatus(status); +} + +bool configTapDragLockEnabled(libinput_device *device, libinput_config_drag_lock_state lock) +{ + if (libinput_device_config_tap_get_finger_count(device) <= 0) { + qCCritical(lcTlInput) << "libinput_device_config_tap_set_drag_enabled is invalid"; + + return false; + } + + if (libinput_device_config_tap_get_drag_lock_enabled(device) == lock) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_tap_set_drag_lock_enabled: " << lock; + enum libinput_config_status status = + libinput_device_config_tap_set_drag_lock_enabled(device, lock); + + return ensureStatus(status); +} + +bool configAccelSpeed(libinput_device *device, double speed) +{ + if (!libinput_device_config_accel_is_available(device)) { + qCCritical(lcTlInput) << "libinput_device_config_accel_set_speed is invalid"; + + return false; + } + + if (libinput_device_config_accel_get_speed(device) == speed) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_accel_set_speed: " << speed; + enum libinput_config_status status = libinput_device_config_accel_set_speed(device, speed); + + return ensureStatus(status); +} + +bool configRotationAngle(libinput_device *device, double angle) +{ + if (!libinput_device_config_rotation_is_available(device)) { + qCCritical(lcTlInput) << "libinput_device_config_rotation_set_angle is invalid"; + + return false; + } + + if (libinput_device_config_rotation_get_angle(device) == angle) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_rotation_set_angle: " << angle; + enum libinput_config_status status = libinput_device_config_rotation_set_angle(device, angle); + + return ensureStatus(status); +} + +bool configAccelProfile(libinput_device *device, libinput_config_accel_profile profile) +{ + if (!libinput_device_config_accel_is_available(device)) { + qCCritical(lcTlInput) << "libinput_device_config_accel_set_profile is invalid"; + + return false; + } + + if (libinput_device_config_accel_get_profile(device) == profile) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_accel_set_profile: " << profile; + enum libinput_config_status status = libinput_device_config_accel_set_profile(device, profile); + + return ensureStatus(status); +} + +bool configNaturalScroll(libinput_device *device, bool natural) +{ + if (!libinput_device_config_scroll_has_natural_scroll(device)) { + qCCritical(lcTlInput) << "libinput_device_config_scroll_set_natural_scroll_enabled is invalid"; + + return false; + } + + if (libinput_device_config_scroll_get_natural_scroll_enabled(device) == natural) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_scroll_set_natural_scroll_enabled: " << natural; + enum libinput_config_status status = + libinput_device_config_scroll_set_natural_scroll_enabled(device, natural); + + return ensureStatus(status); +} + +bool configLeftHanded(libinput_device *device, bool left) +{ + if (!libinput_device_config_left_handed_is_available(device)) { + qCCritical(lcTlInput) << "libinput_device_config_left_handed_set is invalid"; + + return false; + } + + if (libinput_device_config_left_handed_get(device) == left) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_left_handed_set: " << left; + enum libinput_config_status status = libinput_device_config_left_handed_set(device, left); + + return ensureStatus(status); +} + +bool configClickMethod(libinput_device *device, libinput_config_click_method method) +{ + uint32_t click = libinput_device_config_click_get_methods(device); + if ((click & ~LIBINPUT_CONFIG_CLICK_METHOD_NONE) == 0 + || libinput_device_config_click_get_method(device) == method) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_click_set_method: " << method; + enum libinput_config_status status = libinput_device_config_click_set_method(device, method); + + return ensureStatus(status); +} + +bool configMiddleEmulation(libinput_device *device, + libinput_config_middle_emulation_state mid) +{ + if (!libinput_device_config_middle_emulation_is_available(device)) { + qCCritical(lcTlInput) << "libinput_device_config_middle_emulation_set_enabled is invalid"; + + return false; + } + + if (libinput_device_config_middle_emulation_get_enabled(device) == mid) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_middle_emulation_set_enabled: " << mid; + enum libinput_config_status status = + libinput_device_config_middle_emulation_set_enabled(device, mid); + + return ensureStatus(status); +} + +bool configScrollMethod(libinput_device *device, libinput_config_scroll_method method) +{ + uint32_t scroll = libinput_device_config_scroll_get_methods(device); + if ((scroll & ~LIBINPUT_CONFIG_SCROLL_NO_SCROLL) == 0 + || libinput_device_config_scroll_get_method(device) == method) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_scroll_set_method: " << method; + enum libinput_config_status status = libinput_device_config_scroll_set_method(device, method); + + return ensureStatus(status); +} + +bool configScrollButton(libinput_device *device, uint32_t button) +{ + uint32_t scroll = libinput_device_config_scroll_get_methods(device); + if ((scroll & ~LIBINPUT_CONFIG_SCROLL_NO_SCROLL) == 0 + || libinput_device_config_scroll_get_button(device) == button) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_scroll_set_button: " << button; + enum libinput_config_status status = libinput_device_config_scroll_set_button(device, button); + + return ensureStatus(status); +} + +bool configScrollButtonLock(libinput_device *device, + libinput_config_scroll_button_lock_state lock) +{ + uint32_t scroll = libinput_device_config_scroll_get_methods(device); + if ((scroll & ~LIBINPUT_CONFIG_SCROLL_NO_SCROLL) == 0 + || libinput_device_config_scroll_get_button_lock(device) == lock) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_scroll_set_button: " << lock; + enum libinput_config_status status = + libinput_device_config_scroll_set_button_lock(device, lock); + + return ensureStatus(status); +} + +bool configDwtEnabled(libinput_device *device, enum libinput_config_dwt_state enable) +{ + if (!libinput_device_config_dwt_is_available(device)) { + qCCritical(lcTlInput) << "libinput_device_config_dwt_set_enabled is invalid"; + + return false; + } + if (libinput_device_config_dwt_get_enabled(device) == enable) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_dwt_set_enabled: " << enable; + enum libinput_config_status status = libinput_device_config_dwt_set_enabled(device, enable); + + return ensureStatus(status); +} + +bool configDwtpEnabled(libinput_device *device, enum libinput_config_dwtp_state enable) +{ + if (!libinput_device_config_dwtp_is_available(device)) { + qCCritical(lcTlInput) << "libinput_device_config_dwtp_set_enabled is invalid"; + + return false; + } + + if (libinput_device_config_dwtp_get_enabled(device) == enable) { + return false; + } + + qCDebug(lcTlInput) << "libinput_device_config_dwt_set_enabled: " << enable; + enum libinput_config_status status = libinput_device_config_dwtp_set_enabled(device, enable); + + return ensureStatus(status); +} + +bool configCalibrationMatrix(libinput_device *device, float mat[]) +{ + if (!libinput_device_config_calibration_has_matrix(device)) { + qCCritical(lcTlInput) << "setCalibrationMatrix mat is invalid"; + return false; + } + bool changed = false; + float current[6]; + libinput_device_config_calibration_get_matrix(device, current); + enum libinput_config_status status = LIBINPUT_CONFIG_STATUS_UNSUPPORTED; + for (int i = 0; i < 6; i++) { + if (current[i] != mat[i]) { + changed = true; + break; + } + } + if (changed) { + qCDebug(lcTlInput, + "libinput_device_config_calibration_set_matrix(%f, %f, %f, %f, " + "%f, %f)", + mat[0], + mat[1], + mat[2], + mat[3], + mat[4], + mat[5]); + status = libinput_device_config_calibration_set_matrix(device, mat); + } + return changed && ensureStatus(status); +} + +libinput_device *libinput_device_handle(wlr_input_device *handle) +{ + return wlr_libinput_get_device_handle(handle); +} diff --git a/src/input/libinputconfig.h b/src/input/libinputconfig.h new file mode 100644 index 0000000000..615c6d5a1d --- /dev/null +++ b/src/input/libinputconfig.h @@ -0,0 +1,29 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +struct wlr_input_device; + +bool configSendEventsMode(libinput_device *device, uint32_t mode); +bool configTapEnabled(libinput_device *device, libinput_config_tap_state tap); +bool configTapButtonMap(libinput_device *device, libinput_config_tap_button_map map); +bool configTapDragEnabled(libinput_device *device, libinput_config_drag_state drag); +bool configTapDragLockEnabled(libinput_device *device, libinput_config_drag_lock_state lock); +bool configAccelSpeed(libinput_device *device, double speed); +bool configRotationAngle(libinput_device *device, double angle); +bool configAccelProfile(libinput_device *device, libinput_config_accel_profile profile); +bool configNaturalScroll(libinput_device *device, bool natural); +bool configLeftHanded(libinput_device *device, bool left); +bool configClickMethod(libinput_device *device, libinput_config_click_method method); +bool configMiddleEmulation(libinput_device *device, libinput_config_middle_emulation_state mid); +bool configScrollMethod(libinput_device *device, libinput_config_scroll_method method); +bool configScrollButton(libinput_device *device, uint32_t button); +bool configScrollButtonLock(libinput_device *device, libinput_config_scroll_button_lock_state lock); +bool configDwtEnabled(libinput_device *device, enum libinput_config_dwt_state enable); +bool configDwtpEnabled(libinput_device *device, enum libinput_config_dwtp_state enable); +bool configCalibrationMatrix(libinput_device *device, float mat[]); + +libinput_device *libinput_device_handle(wlr_input_device *handle); diff --git a/src/input/swipegesture.cpp b/src/input/swipegesture.cpp new file mode 100644 index 0000000000..eb8dcf4547 --- /dev/null +++ b/src/input/swipegesture.cpp @@ -0,0 +1,181 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "swipegesture.h" + +#include +#include + +SwipeGesture::SwipeGesture(QObject *parent) + : Gesture(parent) +{ +} + +bool SwipeGesture::minimumFingerCountIsRelevant() const +{ + return m_minimumFingerCountRelevant; +} + +void SwipeGesture::setMinimumFingerCount(uint count) +{ + m_minimumFingerCount = count; + m_minimumFingerCountRelevant = true; +} + +uint SwipeGesture::minimumFingerCount() +{ + return m_minimumFingerCount; +} + +bool SwipeGesture::maximumFingerCountIsRelevant() const +{ + return m_maximumFingerCountRelevant; +} + +void SwipeGesture::setMaximumFingerCount(uint count) +{ + + m_maximumFingerCount = count; + m_maximumFingerCountRelevant = true; +} + +uint SwipeGesture::maximumFingerCount() +{ + return m_maximumFingerCount; +} + +SwipeGesture::Direction SwipeGesture::direction() const +{ + return m_direction; +} + +void SwipeGesture::setDirection(SwipeGesture::Direction direction) +{ + m_direction = direction; +} + +void SwipeGesture::setMinimumX(int x) +{ + m_minimumX = x; + m_minimumXRelevant = true; +} + +int SwipeGesture::minimumX() const +{ + return m_minimumX; +} + +bool SwipeGesture::minimumXIsRelevant() const +{ + return m_minimumXRelevant; +} + +void SwipeGesture::setMinimumY(int y) +{ + m_minimumY = y; + m_minimumYRelevant = true; +} + +int SwipeGesture::minimumY() const +{ + return m_minimumY; +} + +bool SwipeGesture::minimumYIsRelevant() const +{ + return m_minimumYRelevant; +} + +void SwipeGesture::setMaximumX(int x) +{ + m_maximumX = x; + m_maximumXRelevant = true; +} + +int SwipeGesture::maximumX() const +{ + return m_maximumX; +} + +bool SwipeGesture::maximumXIsRelevant() const +{ + return m_maximumXRelevant; +} + +void SwipeGesture::setMaximumY(int y) +{ + m_maximumY = y; + m_maximumYRelevant = true; +} + +int SwipeGesture::maximumY() const +{ + return m_maximumY; +} + +bool SwipeGesture::maximumYIsRelevant() const +{ + return m_maximumYRelevant; +} + +void SwipeGesture::setStartGeometry(const QRect &geometry) +{ + setMinimumX(geometry.x()); + setMinimumY(geometry.y()); + setMaximumX(geometry.right()); + setMaximumY(geometry.bottom()); + + Q_ASSERT(m_maximumX >= m_minimumX); + Q_ASSERT(m_maximumY >= m_minimumY); +} + +QPointF SwipeGesture::minimumDelta() const +{ + return m_minimumDelta; +} + +void SwipeGesture::setMinimumDelta(const QPointF &delta) +{ + m_minimumDelta = delta; + m_minimumDeltaRelevant = true; +} + +qreal SwipeGesture::deltaToProgress(const QPointF &delta) const +{ + if (!m_minimumDeltaRelevant && m_minimumDelta.isNull()) { + return 1.0; + } + + switch (m_direction) { + case SwipeGesture::Up: + case SwipeGesture::Down: + return std::min(std::abs(delta.y()) / std::abs(m_minimumDelta.y()), 1.0); + case SwipeGesture::Left: + case SwipeGesture::Right: + return std::min(std::abs(delta.x()) / std::abs(m_minimumDelta.x()), 1.0); + default: + Q_UNREACHABLE(); + } +} + +bool SwipeGesture::minimumDeltaReached(const QPointF &delta) const +{ + return deltaToProgress(delta) >= 1.0; +} + +SwipeGesture::Direction SwipeGesture::opposite(SwipeGesture::Direction direction) +{ + switch (direction) { + case SwipeGesture::Invalid: + return SwipeGesture::Invalid; + case SwipeGesture::Down: + return SwipeGesture::Up; + case SwipeGesture::Up: + return SwipeGesture::Down; + case SwipeGesture::Left: + return SwipeGesture::Right; + case SwipeGesture::Right: + return SwipeGesture::Left; + } + return SwipeGesture::Invalid; +} diff --git a/src/input/swipegesture.h b/src/input/swipegesture.h new file mode 100644 index 0000000000..93d899eddb --- /dev/null +++ b/src/input/swipegesture.h @@ -0,0 +1,80 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "gestures.h" + +#include +#include + +class SwipeGesture : public Gesture +{ + Q_OBJECT +public: + explicit SwipeGesture(QObject *parent = nullptr); + + enum Direction + { + Invalid, + Down, + Left, + Up, + Right, + }; + + static Direction opposite(Direction direction); + + bool minimumFingerCountIsRelevant() const; + void setMinimumFingerCount(uint count); + uint minimumFingerCount(); + + bool maximumFingerCountIsRelevant() const; + void setMaximumFingerCount(uint count); + uint maximumFingerCount(); + + Direction direction() const; + void setDirection(Direction direction); + + void setMinimumX(int x); + int minimumX() const; + bool minimumXIsRelevant() const; + void setMinimumY(int y); + int minimumY() const; + bool minimumYIsRelevant() const; + + void setMaximumX(int x); + int maximumX() const; + bool maximumXIsRelevant() const; + void setMaximumY(int y); + int maximumY() const; + bool maximumYIsRelevant() const; + void setStartGeometry(const QRect &geometry); + + QPointF minimumDelta() const; + void setMinimumDelta(const QPointF &delta); + + qreal deltaToProgress(const QPointF &delta) const; + bool minimumDeltaReached(const QPointF &delta) const; + +Q_SIGNALS: + void progress(qreal); + void deltaProgress(const QPointF &delta); + +private: + bool m_minimumFingerCountRelevant = false; + uint m_minimumFingerCount = 0; + bool m_maximumFingerCountRelevant = false; + uint m_maximumFingerCount = 0; + SwipeGesture::Direction m_direction = SwipeGesture::Down; + bool m_minimumXRelevant = false; + int m_minimumX = 0; + bool m_minimumYRelevant = false; + int m_minimumY = 0; + bool m_maximumXRelevant = false; + int m_maximumX = 0; + bool m_maximumYRelevant = false; + int m_maximumY = 0; + bool m_minimumDeltaRelevant = false; + QPointF m_minimumDelta; +}; diff --git a/src/input/togglablegesture.cpp b/src/input/togglablegesture.cpp new file mode 100644 index 0000000000..d3cec97df5 --- /dev/null +++ b/src/input/togglablegesture.cpp @@ -0,0 +1,209 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include "togglablegesture.h" + +#include "input/gesturemanager.h" + +TogglableGesture::TogglableGesture(QObject *parent, GestureManager *gestures) + : QObject(parent) + , m_gestureManager(gestures ? gestures : new GestureManager(this)) +{ +} + +TogglableGesture::~TogglableGesture() +{ + for (auto *gesture : std::as_const(m_registeredGestures)) { + if (auto *swipe = qobject_cast(gesture)) + m_gestureManager->unregisterTouchpadSwipe(swipe); + else if (auto *hold = qobject_cast(gesture)) + m_gestureManager->unregisterTouchpadHold(hold); + } +} + +bool TogglableGesture::inProgress() const +{ + return m_inProgress; +} + +void TogglableGesture::setInProgress(bool gesture) +{ + if (m_inProgress != gesture) { + m_inProgress = gesture; + Q_EMIT inProgressChanged(); + } +} + +void TogglableGesture::setPartialGestureFactor(qreal factor) +{ + if (m_partialGestureFactor != factor) { + m_partialGestureFactor = factor; + Q_EMIT partialGestureFactorChanged(factor); + } +} + +void TogglableGesture::activate(bool on) +{ + setInProgress(false); + setPartialGestureFactor(1.0); + setStatus(Status::Active, on); +} + +void TogglableGesture::deactivate(bool on) +{ + setInProgress(false); + setPartialGestureFactor(0.0); + setStatus(Status::Inactive, on); +} + +void TogglableGesture::toggle(bool on) +{ + if (m_status != Status::Active) { + activate(on); + if (on) + Q_EMIT activated(); + } else { + deactivate(on); + if (on) + Q_EMIT deactivated(); + } +} + +void TogglableGesture::stop() +{ + setInProgress(false); + setPartialGestureFactor(0.0); + setStatus(Status::Stopped); +} + +void TogglableGesture::setStatus(Status status, bool on) +{ + if (m_status != status) { + m_status = status; + if (on) + Q_EMIT statusChanged(status); + } +} + +std::function TogglableGesture::progressCallback() +{ + return [this](qreal progress) { + setProgress(progress); + }; +} + +std::function TogglableGesture::regressCallback() +{ + return [this](qreal progress) { + setRegress(progress); + }; +} + +void TogglableGesture::setProgress(qreal progress) +{ + if (m_status == Status::Stopped) { + return; + } + + switch (m_status) { + case Status::Inactive: + case Status::Activating: { + setStatus(Status::Activating); + setInProgress(true); + setPartialGestureFactor(progress); + break; + } + default: + break; + } +} + +void TogglableGesture::setRegress(qreal regress) +{ + if (m_status == Status::Stopped) { + return; + } + + switch (m_status) { + case Status::Active: + case Status::Deactivating: + setStatus(Status::Deactivating); + setInProgress(true); + setPartialGestureFactor(1.0 - regress); + break; + default: + break; + } +} + +std::function TogglableGesture::activeTriggeredCallback() +{ + return [this](bool) { + activeTriggered(); + }; +} + +std::function TogglableGesture::deactivateTriggeredCallback() +{ + return [this](bool) { + deactivateTriggered(); + }; +} + +void TogglableGesture::activeTriggered() +{ + if (m_status == Status::Activating) { + if (m_partialGestureFactor > 0.5) { + activate(); + Q_EMIT activated(); + } else { + deactivate(); + Q_EMIT deactivated(); + } + } +} + +void TogglableGesture::deactivateTriggered() +{ + if (m_status == Status::Deactivating) { + if (m_partialGestureFactor < 0.5) { + deactivate(); + Q_EMIT deactivated(); + } else { + activate(); + Q_EMIT activated(); + } + } +} + +void TogglableGesture::addTouchpadSwipeGesture(SwipeGesture::Direction direction, uint finger) +{ + if (direction == SwipeGesture::Invalid) + return; + + m_registeredGestures.append(m_gestureManager->registerTouchpadSwipe( + SwipeFeedBack{ direction, + finger, + this->activeTriggeredCallback(), + this->progressCallback() })); + + m_registeredGestures.append(m_gestureManager->registerTouchpadSwipe( + SwipeFeedBack{ SwipeGesture::opposite(direction), + finger, + this->deactivateTriggeredCallback(), + this->regressCallback() })); +} + +void TogglableGesture::addTouchpadHoldGesture(uint finger) +{ + const auto pressed = [this]() { + Q_EMIT longPressed(); + }; + + const auto trigger = [this]() { + Q_EMIT hold(); + }; + + m_registeredGestures.append(m_gestureManager->registerTouchpadHold(HoldFeedBack{ finger, trigger, pressed })); +} diff --git a/src/input/togglablegesture.h b/src/input/togglablegesture.h new file mode 100644 index 0000000000..3c55776380 --- /dev/null +++ b/src/input/togglablegesture.h @@ -0,0 +1,88 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "swipegesture.h" + +#include +#include + +class GestureManager; + +class TogglableGesture : public QObject +{ + Q_OBJECT + Q_PROPERTY(bool inProgress READ inProgress WRITE setInProgress NOTIFY inProgressChanged FINAL) + Q_PROPERTY(qreal partialGestureFactor READ partialGestureFactor WRITE setPartialGestureFactor NOTIFY partialGestureFactorChanged FINAL) + Q_PROPERTY(Status status READ status WRITE setStatus NOTIFY statusChanged FINAL) +public: + enum Status + { + Inactive, + Activating, + Deactivating, + Active, + Stopped + }; + + Q_ENUM(Status); + + TogglableGesture(QObject *parent = nullptr, GestureManager *gestures = nullptr); + ~TogglableGesture(); + + bool inProgress() const; + void setInProgress(bool gesture); + + void setPartialGestureFactor(qreal factor); + + qreal partialGestureFactor() const + { + return m_partialGestureFactor; + } + + void setStatus(Status status, bool on = true); + + Status status() const + { + return m_status; + } + + void activate(bool on = true); + void deactivate(bool on = true); + + Q_INVOKABLE void toggle(bool on = true); + Q_INVOKABLE void stop(); + + void addTouchpadSwipeGesture(SwipeGesture::Direction direction, uint fingerCount); + void addTouchpadHoldGesture(uint fingerCount); + +Q_SIGNALS: + void inProgressChanged(); + void partialGestureFactorChanged(qreal factor); + void activated(); + void deactivated(); + void hold(); + void longPressed(); + void statusChanged(Status status); + +protected: + std::function progressCallback(); + std::function regressCallback(); + void setProgress(qreal progress); + void setRegress(qreal regress); + + std::function activeTriggeredCallback(); + std::function deactivateTriggeredCallback(); + void activeTriggered(); + void deactivateTriggered(); + +private: + GestureManager *const m_gestureManager; + QList m_registeredGestures; + Status m_status = Status::Inactive; + bool m_inProgress = false; + qreal m_partialGestureFactor; +}; + +Q_DECLARE_METATYPE(TogglableGesture *) diff --git a/src/interfaces/baseplugininterface.h b/src/interfaces/baseplugininterface.h new file mode 100644 index 0000000000..24e41ae1b3 --- /dev/null +++ b/src/interfaces/baseplugininterface.h @@ -0,0 +1,10 @@ +// Copyright (C) 2024 Dingyuan Zhang . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +class BasePluginInterface +{ +public: + virtual ~BasePluginInterface() = default; +}; diff --git a/src/interfaces/lockscreeninterface.h b/src/interfaces/lockscreeninterface.h new file mode 100644 index 0000000000..64ae3ad81a --- /dev/null +++ b/src/interfaces/lockscreeninterface.h @@ -0,0 +1,22 @@ +// Copyright (C) 2024 Dingyuan Zhang . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "baseplugininterface.h" + +#include + +class Output; +class QQuickItem; + +class ILockScreen : public virtual BasePluginInterface +{ +public: + virtual ~ILockScreen() = default; + + virtual QQuickItem *createLockScreen(Output *output, QQuickItem *parent) = 0; + virtual QQuickItem *createLockView(QQuickItem *parent) = 0; +}; + +Q_DECLARE_INTERFACE(ILockScreen, "org.deepin.treeland.v1.LockScreenInterface") diff --git a/src/interfaces/multitaskviewinterface.h b/src/interfaces/multitaskviewinterface.h new file mode 100644 index 0000000000..59f82e4efa --- /dev/null +++ b/src/interfaces/multitaskviewinterface.h @@ -0,0 +1,48 @@ +// Copyright (C) 2024 Dingyuan Zhang . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "baseplugininterface.h" + +#include + +class IMultitaskView : public virtual BasePluginInterface +{ +public: + virtual ~IMultitaskView() = default; + + enum ActiveReason + { + ShortcutKey = 1, + Gesture + }; + + enum Status + { + Uninitialized, + Initialized, + Active, + Exited + }; + + virtual qreal partialFactor() const = 0; + virtual void setStatus(IMultitaskView::Status status) = 0; + virtual void toggleMultitaskView(IMultitaskView::ActiveReason reason) = 0; + virtual void updatePartialFactor(qreal progress) = 0; + virtual void immediatelyExit() = 0; + virtual void commitGesture(bool triggered) = 0; +}; + +Q_DECLARE_INTERFACE(IMultitaskView, "org.deepin.treeland.v1.MultitaskViewInterface") + +class DesktopEnvironment; +class QQuickItem; + +class IMultitaskViewFactory : public virtual BasePluginInterface +{ +public: + virtual QQuickItem *createMultitaskView(DesktopEnvironment *desktop) = 0; +}; + +Q_DECLARE_INTERFACE(IMultitaskViewFactory, "org.deepin.treeland.v1.MultitaskViewFactoryInterface") diff --git a/src/interfaces/plugininterface.h b/src/interfaces/plugininterface.h new file mode 100644 index 0000000000..728ca063cf --- /dev/null +++ b/src/interfaces/plugininterface.h @@ -0,0 +1,24 @@ +// Copyright (C) 2024 Dingyuan Zhang . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "baseplugininterface.h" + +#include + +class TreelandProxyInterface; + +class PluginInterface : public virtual BasePluginInterface +{ +public: + virtual ~PluginInterface() { } + + virtual QString name() const = 0; + virtual QString description() const = 0; + virtual void initialize(TreelandProxyInterface *proxy) = 0; + virtual void shutdown() = 0; + virtual bool enabled() const = 0; +}; + +Q_DECLARE_INTERFACE(PluginInterface, "org.deepin.treeland.v1.PluginInterface") diff --git a/src/interfaces/proxyinterface.h b/src/interfaces/proxyinterface.h new file mode 100644 index 0000000000..10888af349 --- /dev/null +++ b/src/interfaces/proxyinterface.h @@ -0,0 +1,22 @@ +// Copyright (C) 2024 Dingyuan Zhang . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +class Workspace; +class QmlEngine; + +class RootSurfaceContainer; + +class TreelandProxyInterface +{ +public: + virtual ~TreelandProxyInterface() { } + + virtual QmlEngine *qmlEngine() const = 0; + virtual Workspace *workspace() const = 0; + + virtual RootSurfaceContainer *rootSurfaceContainer() const = 0; +}; diff --git a/src/interfaces/windowtransition.h b/src/interfaces/windowtransition.h new file mode 100644 index 0000000000..d945d9cc04 --- /dev/null +++ b/src/interfaces/windowtransition.h @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include +#include +#include +#include + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutput; +class WSurface; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +// Refcounted handle to a client-provided window-transition source surface. +class WindowTransitionSource : public QObject +{ + Q_OBJECT +public: + using QObject::QObject; + + virtual WSurface *surface() const = 0; + + virtual void retain(const QList &outputs) = 0; + virtual void release(const QList &outputs) = 0; +}; + +class WindowTransitionTarget : public QObject +{ + Q_OBJECT +public: + using QObject::QObject; + + virtual void setWindowTransitionRect(const QRectF &localRect, + WindowTransitionTarget *origin) = 0; + virtual void updateWindowTransitionRect(const QRectF &localRect) = 0; + + virtual void setWindowTransitionSource(WindowTransitionSource *source) = 0; + // Drop the live source only + virtual void clearWindowTransitionSource() = 0; + // Drop the whole transition and notify the client that the rect is done. + virtual void resetWindowTransition() = 0; + + virtual std::optional mapTransitionPointToGlobal( + const QPointF &surfacePoint) const = 0; + +Q_SIGNALS: + void windowTransitionFinished(); +}; diff --git a/src/lockscreen/lockscreen.cpp b/src/lockscreen/lockscreen.cpp new file mode 100644 index 0000000000..bf07f7c71a --- /dev/null +++ b/src/lockscreen/lockscreen.cpp @@ -0,0 +1,459 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "lockscreen.h" + +#include "interfaces/lockscreeninterface.h" +#include "output/output.h" +#include "core/waylandserver.h" +#include "utils/cmdline.h" +#include "common/treelandlogging.h" +#include "greeter/greeterproxy.h" + +#include + +#ifdef EXT_SESSION_LOCK_V1 +#include "core/rootsurfacecontainer.h" +#include "surface/surfacewrapper.h" +#include "workspace/workspace.h" + +#include +#include +#endif + +WAYLIB_SERVER_USE_NAMESPACE + +LockScreen::LockScreen(ILockScreen *impl, SurfaceContainer *parent, GreeterProxy *greeterProxy) + : SurfaceContainer(parent) + , m_impl(impl) + , m_greeterProxy(greeterProxy) + , m_delayTimer(std::make_unique(new QTimer)) +{ + connect(m_delayTimer.get(), &QTimer::timeout, this, &LockScreen::unlock); + + m_delayTimer->setSingleShot(true); + // Display desktop animation after lock screen animation with a delay of 300ms + m_delayTimer->setInterval(300); + + // The global login view is lazily created when this container becomes + // visible (locked) and destroyed when it hides (unlocked). Track the + // output under the cursor so the login UI follows the mouse without + // recomputing the output on every cursor motion. + connect(this, &QQuickItem::visibleChanged, this, &LockScreen::onLoginViewVisibleChanged); + connect(rootContainer(), + &RootSurfaceContainer::cursorOutputChanged, + this, + &LockScreen::repositionLoginView); +} + +void LockScreen::lock() +{ + // Do not early-return on isVisible(): the greeter may start in the + // undecided state (surface visible, not yet locked), so lock() must + // still flip the lock state afterwards. + setVisible(true); + + if (!m_greeterProxy->isLocked()) + m_greeterProxy->lock(); +} + +void LockScreen::shutdown(WaylandServer::ShutdownMenuFocus focus) +{ + // ext_session_lock_v1 does not support shutdown + if (!m_impl) { + qCWarning(lcTlShell) << "Attempt to shutdown with no compatible lockscreen implementation!"; + Q_EMIT unlock(); + return; + } + + // Set before the menu shows: the view picks its initial focus as it loads. + // A repeat request while the menu is already up only moves that focus. + m_greeterProxy->setShutdownMenuFocus(focus); + + if (!isVisible()) + setVisible(true); + + if (!m_greeterProxy->showShutdownView()) + m_greeterProxy->setShowShutdownView(true); +} + +void LockScreen::switchUser() +{ + // ext_session_lock_v1 does not support user switching + if (!m_impl) { + qCWarning(lcTlShell) << "Attempt to switch user with no compatible lockscreen implementation!"; + Q_EMIT unlock(); + return; + } + + if (isVisible()) { + return; + } + + setVisible(true); + + Q_EMIT m_greeterProxy->switchUser(); +} + +void LockScreen::addOutput(Output *output) +{ + qCDebug(lcTlShell) << "Adding output to lock screen:" << output; + + SurfaceContainer::addOutput(output); + auto outputItem = output->outputItem(); + connect(outputItem, &WOutputItem::geometryChanged, this, &LockScreen::repositionLoginView); + +#if EXT_SESSION_LOCK_V1 + connect(outputItem, &WOutputItem::geometryChanged, this, &LockScreen::onOutputGeometryChanged); + const auto &[_, ok] = m_lockSurfaces.emplace(outputItem, nullptr); + Q_ASSERT(ok); +#endif + + if (!m_impl) { + return; + } + + auto *item = m_impl->createLockScreen(output, this); + if (!item) { + qCWarning(lcTlShell) << "Failed to create lock screen item for output" << output; + return; + } + item->setZ(GreeterZOrder); + + connect(item, SIGNAL(hideAnimationFinished()), this, SLOT(onHideAnimationFinished())); + + m_components.insert( + { output, std::unique_ptr(item, [](QQuickItem *item) { + item->deleteLater(); + }) }); + + repositionLoginView(); +} + +bool LockScreen::isLocked() const +{ + return isVisible(); +} + +void LockScreen::removeOutput(Output *output) +{ + qCDebug(lcTlShell) << "Removing output from lock screen:" << output; + + SurfaceContainer::removeOutput(output); + auto outputItem = output->outputItem(); + disconnect(outputItem, &WOutputItem::geometryChanged, this, &LockScreen::repositionLoginView); + +#if EXT_SESSION_LOCK_V1 + disconnect(outputItem, + &WOutputItem::geometryChanged, + this, + &LockScreen::onOutputGeometryChanged); + m_lockSurfaces.erase(outputItem); + m_fallbackItems.erase(outputItem); + + if (!m_impl) { + return; + } +#endif + m_components.erase(output); + repositionLoginView(); +} + +void LockScreen::onAnimationPlayed() +{ + if (!m_delayTimer->isActive()) { + m_delayTimer->start(); + } +} + +void LockScreen::onAnimationPlayFinished() +{ + auto *item = qobject_cast(sender()); + Q_ASSERT(item); + + setVisible(false); +} + +void LockScreen::onHideAnimationFinished() +{ + if (isVisible() && !m_greeterProxy->isLocked() && !m_greeterProxy->showShutdownView()) + setVisible(false); +} + +bool LockScreen::available() const +{ + return m_impl != nullptr; +} + +void LockScreen::onLoginViewVisibleChanged() +{ + if (isVisible()) { + createLoginView(); + } else { + destroyLoginView(); + } +} + +void LockScreen::createLoginView() +{ + if (!m_impl || m_loginView) { + return; + } + + qCDebug(lcTlShell) << "Creating global login view for lock screen"; + auto *item = m_impl->createLockView(this); + if (!item) { + qCWarning(lcTlShell) << "Failed to create global login view"; + return; + } + + connect(item, SIGNAL(animationPlayed()), this, SLOT(onAnimationPlayed())); + connect(item, SIGNAL(animationPlayFinished()), this, SLOT(onAnimationPlayFinished())); + + m_loginView = item; + m_loginView->setZ(LoginViewZOrder); + repositionLoginView(); +} + +void LockScreen::destroyLoginView() +{ + if (!m_loginView) { + return; + } + qCDebug(lcTlShell) << "Destroying global login view for lock screen"; + m_loginView->deleteLater(); + m_loginView = nullptr; +} + +Output *LockScreen::followerOutput() const +{ + auto *root = rootContainer(); + if (auto *out = root->cursorOutput()) { + return out; + } + return root->primaryOutput(); +} + +void LockScreen::repositionLoginView() +{ + if (!m_loginView) { + return; + } + + auto *out = followerOutput(); + if (!out) { + return; + } + + const auto pos = out->outputItem()->position(); + const auto size = out->outputItem()->size(); + + m_loginView->setX(pos.x()); + m_loginView->setY(pos.y()); + m_loginView->setWidth(size.width()); + m_loginView->setHeight(size.height()); +} +#if EXT_SESSION_LOCK_V1 +// ext_session_lock_v1 capabilities + +void LockScreen::doRemoveLockSurface(WSessionLockSurface *surface) +{ + if (!surface) { + return; + } + + auto wrapper = rootContainer()->getSurface(surface); + if (!wrapper) { + qCWarning(lcTlShell) << "Removing lock surface with no container attached"; + return; + } + rootContainer()->destroyForSurface(wrapper); +} + + +void LockScreen::onLockSurfaceAdded(WSessionLockSurface *surface) +{ + if (!m_sessionLock) { + return; + } + auto output = WaylandServer::instance()->getOutput(surface->output()); + + if (!output) { + qCWarning(lcTlShell) << "Lock surface added with no output!"; + return; + } + + auto outputItem = output->outputItem(); + + m_fallbackItems.erase(outputItem); + // protocol error if multiple surfaces for one output + Q_ASSERT(!m_lockSurfaces[outputItem]); + m_lockSurfaces[outputItem] = std::unique_ptr>(surface, [this](WSessionLockSurface* s) { + doRemoveLockSurface(s); + }); + + // Configure the lock surface to match the output's full size + surface->configureSize(outputItem->size().toSize()); + + auto wrapper = new SurfaceWrapper( + WaylandServer::instance()->qmlEngine(), surface, SurfaceWrapper::Type::LockScreen); + + wrapper->setNoDecoration(true); + wrapper->setSkipMutiTaskView(true); + wrapper->setSkipSwitcher(true); + wrapper->setOwnsOutput(output); + wrapper->setPosition(outputItem->position()); + + addSurface(wrapper); + + wrapper->setHasInitializeContainer(true); + + // Lock surfaces have no Activate capability, so ask for focus directly + // once mapped; its INT_MAX priority keeps lower-priority surfaces from + // taking it back. + connect(wrapper, &SurfaceWrapper::hasFocusCapabilityChanged, this, [wrapper] { + if (wrapper->hasFocusCapability()) + WaylandServer::instance()->requestKeyboardFocus(wrapper); + }); +} + +void LockScreen::onLockSurfaceRemoved(WSessionLockSurface *surface) +{ + if (!m_sessionLock) { + return; + } + auto output = WaylandServer::instance()->getOutput(surface->output()); + if (!output) { + qCWarning(lcTlShell) << "removing lock surface with no output!"; + return; + } + + auto outputItem = output->outputItem(); + + if (m_lockSurfaces[outputItem]) { + if (isLocked()) { + // display a solid color for output + createFallbackItem(outputItem); + } + m_lockSurfaces[outputItem].reset(); + } +} + +void LockScreen::onOutputGeometryChanged() +{ + WOutputItem *outputItem = qobject_cast(QObject::sender()); + const auto it = m_lockSurfaces.find(outputItem); + if (it == m_lockSurfaces.end()) { + return; + } + + auto *lockSurface = it->second.get(); + if (lockSurface) { + // Resize the lock surface to match the new output size + lockSurface->configureSize(outputItem->size().toSize()); + + auto wrapper = rootContainer()->getSurface(lockSurface); + if (wrapper) { + wrapper->setPosition(outputItem->position()); + } + } +} + +void LockScreen::onExternalLock(WSessionLock *lock) +{ + if (isVisible()) { + lock->finish(); + return; + } + + m_sessionLock = lock; + + QObject::connect(lock, &WSessionLock::surfaceAdded, this, &LockScreen::onLockSurfaceAdded); + QObject::connect(lock, &WSessionLock::surfaceRemoved, this, &LockScreen::onLockSurfaceRemoved); + QObject::connect(lock, &WSessionLock::unlocked, this, &LockScreen::onExternalUnlock); + QObject::connect(lock, &WSessionLock::canceled, this, &LockScreen::onExternalUnlock); + QObject::connect(lock, &WSessionLock::abandoned, this, &LockScreen::onExternalLockAbandoned); + + setVisible(true); + + // Snapshot the focused surface and clear focus until the lock surface maps. + // primary seat only, upgrade when lock surfaces become per-seat. + auto *server = WaylandServer::instance(); + m_lockFocusRestoreSurface = server->activatedSurface(); + server->requestKeyboardFocus(nullptr); +} + +void LockScreen::onExternalUnlock() { + if (!m_sessionLock || !isLocked()) { + qCCritical(lcTlShell) << "Session lock identified as unlocked but screen is not externally locked?"; + return; + } + setVisible(false); + for (auto &[_, surface] : m_lockSurfaces) { + surface.reset(); + } + m_fallbackItems.clear(); + m_sessionLock = nullptr; + Q_EMIT unlock(); + // After finishLockScreenTransition() so the snapshot wins over its generic restore. + restoreLockedSessionFocus(); +} + +void LockScreen::restoreLockedSessionFocus() +{ + auto *server = WaylandServer::instance(); + auto *restore = m_lockFocusRestoreSurface.data(); + + // Fall back to the latest active window when the snapshot is gone/unfocusable. + if (!restore || !restore->hasFocusCapability()) + restore = server->workspace()->current()->latestActiveSurface(); + + if (restore) + server->requestKeyboardFocus(restore, Qt::NoFocusReason); + + m_lockFocusRestoreSurface.clear(); +} + +void LockScreen::onExternalLockAbandoned() { + if (!m_impl || !m_sessionLock) { + return; + } + if (!isLocked()) { + qCCritical(lcTlShell) << "Session lock identified as abandoned but screen is not locked?"; + return; + } + + qCWarning(lcTlShell) << "locking client likely died"; + + m_sessionLock = nullptr; + + for (auto &[_, surface] : m_lockSurfaces) { + surface.reset(); + } + m_fallbackItems.clear(); + + m_greeterProxy->lock(); +} + +void LockScreen::createFallbackItem(WOutputItem *outputItem) +{ + if (!outputItem || m_fallbackItems.find(outputItem) != m_fallbackItems.end()) { + return; + } + + auto *engine = WaylandServer::instance()->qmlEngine(); + Q_ASSERT(engine); + + auto *fallbackItem = engine->createLockScreenFallback(this, { + {"outputItem", QVariant::fromValue(outputItem)} + }); + Q_ASSERT(fallbackItem); + + m_fallbackItems[outputItem] = std::unique_ptr>( + fallbackItem, [](QQuickItem *item) { + if (item) { + item->deleteLater(); + } + }); +} +#endif diff --git a/src/lockscreen/lockscreen.h b/src/lockscreen/lockscreen.h new file mode 100644 index 0000000000..1f8c62e89a --- /dev/null +++ b/src/lockscreen/lockscreen.h @@ -0,0 +1,102 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "surface/surfacecontainer.h" +#include "core/waylandserver.h" +#include "wglobal.h" +#include +#include +#include + +class GreeterProxy; +class QTimer; +class ILockScreen; + +#ifdef EXT_SESSION_LOCK_V1 +WAYLIB_SERVER_BEGIN_NAMESPACE +class WSessionLock; +class WSessionLockSurface; +class WOutputItem; +WAYLIB_SERVER_END_NAMESPACE +Q_MOC_INCLUDE() +Q_MOC_INCLUDE() +#endif + +class LockScreen : public SurfaceContainer +{ + Q_OBJECT + QML_ANONYMOUS + +public: + enum ZOrder + { + GreeterZOrder = 0, + LoginViewZOrder = 1, + }; + + enum class CurrentMode + { + Lock = 1, + Shutdown = 2, + SwitchUser = 3 + }; + Q_ENUM(CurrentMode) + + explicit LockScreen(ILockScreen *impl, SurfaceContainer *parent, GreeterProxy *greeterProxy); + + bool available() const; + bool isLocked() const; + void lock(); + void shutdown(WaylandServer::ShutdownMenuFocus focus = + WaylandServer::ShutdownMenuFocus::None); + void switchUser(); + +Q_SIGNALS: + void unlock(); + +public Q_SLOTS: + void onAnimationPlayed(); + void onAnimationPlayFinished(); + void onHideAnimationFinished(); +#ifdef EXT_SESSION_LOCK_V1 + void onExternalLock(WSessionLock *lock); + +private: + void onOutputGeometryChanged(); + void doRemoveLockSurface(WSessionLockSurface *surface); + void createFallbackItem(WOutputItem *outputItem); + void restoreLockedSessionFocus(); + +private Q_SLOTS: + void onLockSurfaceAdded(WSessionLockSurface *surface); + void onLockSurfaceRemoved(WSessionLockSurface *surface); + void onExternalLockAbandoned(); + void onExternalUnlock(); +#endif + +public: + void addOutput(Output *output) override; + void removeOutput(Output *output) override; + +private: + void onLoginViewVisibleChanged(); + void createLoginView(); + void destroyLoginView(); + void repositionLoginView(); + Output *followerOutput() const; + + ILockScreen *m_impl{ nullptr }; + GreeterProxy *m_greeterProxy{ nullptr }; + std::map> m_components; + std::unique_ptr m_delayTimer; +#ifdef EXT_SESSION_LOCK_V1 + std::map>> m_lockSurfaces; + std::map>> m_fallbackItems; + WSessionLock* m_sessionLock{ nullptr }; + // The surface focused when the session was locked, restored on unlock. + QPointer m_lockFocusRestoreSurface; +#endif + QQuickItem *m_loginView{ nullptr }; +}; diff --git a/src/lockscreen/lockscreenmanager.cpp b/src/lockscreen/lockscreenmanager.cpp new file mode 100644 index 0000000000..dc4f4e2264 --- /dev/null +++ b/src/lockscreen/lockscreenmanager.cpp @@ -0,0 +1,239 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "lockscreenmanager.h" +#include "core/waylandserver.h" +#include "core/rootsurfacecontainer.h" +#include "lockscreen.h" +#include "greeter/greeterproxy.h" +#include "session/sessionmanager.h" +#include "interfaces/lockscreeninterface.h" +#include "modules/dde-shell/ddeshellmanagerinterfacev1.h" +#include "utils/cmdline.h" +#include "common/treelandlogging.h" + +#include +#include +#include + +#include +#include +#include +#include + +#include + +LockScreenManager::LockScreenManager(WaylandServer *server) + : QObject(server), + m_server(server) +{ +#ifdef EXT_SESSION_LOCK_V1 + m_lockScreenGraceTimer = new QTimer(this); + m_lockScreenGraceTimer->setInterval(300); + m_lockScreenGraceTimer->setSingleShot(true); +#endif + connect(server->sessionManager(), &SessionManager::sessionLock, + this, &LockScreenManager::onSessionLock); + connect(server->sessionManager(), &SessionManager::sessionUnlock, + this, &LockScreenManager::onSessionUnlock); +} + +LockScreenManager::~LockScreenManager() = default; + +void LockScreenManager::setGreeterProxy(GreeterProxy *greeter) +{ +#ifndef DISABLE_DDM + if (m_greeterProxy) { + disconnect(this, &LockScreenManager::sessionLockStateRequested, m_greeterProxy, nullptr); + disconnect(this, &LockScreenManager::sessionRelockRequested, m_greeterProxy, nullptr); + } +#endif + m_greeterProxy = greeter; +#ifndef DISABLE_DDM + if (greeter) + greeter->bindLockScreenManager(this); +#endif +} + +void LockScreenManager::installSessionLock(WServer *server) +{ +#ifdef EXT_SESSION_LOCK_V1 + auto *manager = server->attach(); + if (!m_lockScreen) + setLockScreenImpl(nullptr); + connect(manager, &WSessionLockManager::lockCreated, + this, &LockScreenManager::onExtSessionLock); +#else + Q_UNUSED(server) +#endif +} + +void LockScreenManager::handleLockScreen(LockScreenInterface *lockScreen) +{ + connect(lockScreen, &LockScreenInterface::shutdown, this, &LockScreenManager::onLockScreenShutdown); + connect(lockScreen, &LockScreenInterface::lock, this, [this]() { + if (m_server->isNormalOrMultitaskview()) + showLockScreen(false); + }); + connect(lockScreen, &LockScreenInterface::switchUser, this, &LockScreenManager::showSwitchUser); +} + +void LockScreenManager::onSessionLock(Session *session) +{ +#ifndef DISABLE_DDM + if (!session || !m_greeterProxy || !isLockScreenAvailable() + || m_server->sessionManager()->activeSession().lock().get() != session) + return; + + const bool wasLocked = m_greeterProxy->isLocked(); + m_server->prepareLockScreenTransition(); + Q_EMIT sessionLockStateRequested(true); + if (!wasLocked) + requestSwitchToGreeter(); +#else + Q_UNUSED(session) +#endif +} + +void LockScreenManager::onSessionUnlock(Session *session) +{ +#ifndef DISABLE_DDM + if (!session || !m_greeterProxy) + return; + + if (m_server->sessionManager()->activeSession().lock().get() != session) { + Q_EMIT sessionRelockRequested(session->id()); + return; + } + + Q_EMIT sessionLockStateRequested(false); +#else + Q_UNUSED(session) +#endif +} + +void LockScreenManager::requestSwitchToGreeter() +{ + const auto request = QDBusMessage::createMethodCall("org.freedesktop.DisplayManager", + "/org/freedesktop/DisplayManager/Seat0", + "org.freedesktop.DisplayManager.Seat", + "SwitchToGreeter"); + QDBusConnection::systemBus().asyncCall(request); +} + +void LockScreenManager::onExtSessionLock(WSessionLock *lock) +{ +#ifdef EXT_SESSION_LOCK_V1 + if (!m_lockScreen || m_lockScreen->isLocked()) { + lock->finish(); + return; + } + + m_lockScreen->onExternalLock(lock); + + m_server->prepareLockScreenTransition(); + + QObject::connect(lock, &WSessionLock::abandoned, this, [this]() { + m_lockScreenGraceTimer->stop(); + m_server->setNoAnimation(false); + }); + + QObject::connect(lock, &WSessionLock::canceled, this, [this]() { + m_lockScreenGraceTimer->stop(); + }); + + m_lockScreenGraceTimer->disconnect(); + // grace 300ms for possible client to + connect(m_lockScreenGraceTimer, &QTimer::timeout, this, [this, lock]() { + m_server->setNoAnimation(true); + lock->lock(); + }); + m_lockScreenGraceTimer->start(); +#endif +} + +void LockScreenManager::setLockScreenImpl(ILockScreen *impl) +{ +#if !defined(DISABLE_DDM) || defined(EXT_SESSION_LOCK_V1) + if (!impl) { + if (m_lockScreen) { + delete m_lockScreen; + m_lockScreen = nullptr; + Q_EMIT lockScreenAvailableChanged(); + } + return; + } + + m_lockScreen = new LockScreen(impl, m_server->rootContainer(), m_greeterProxy); + m_lockScreen->setZ(RootSurfaceContainer::LockScreenZOrder); + m_lockScreen->setObjectName(QStringLiteral("LockScreenContainer")); + m_lockScreen->setVisible(false); + + m_greeterProxy->setLockScreen(m_lockScreen); + + for (auto *output : std::as_const(m_server->rootContainer()->outputs())) { + m_lockScreen->addOutput(output); + } + + connect(m_lockScreen, &LockScreen::unlock, + m_server, &WaylandServer::finishLockScreenTransition); + Q_EMIT lockScreenAvailableChanged(); + if (CmdLine::ref().useLockScreen()) { + // Start in the undecided state: make the lock screen surface (wallpaper) + // visible but keep the login UI hidden until DDM decides (ShowGreeter / + // UserActivateMessage) or the fallback timeout in GreeterProxy fires. + m_lockScreen->setVisible(true); + } +#else + Q_UNUSED(impl) +#endif +} + +void LockScreenManager::showLockScreen(bool switchToGreeter) +{ + if (!isLockScreenAvailable()) { + return; + } + // LockScreen::isLocked() is isVisible(), which is also true in the + // undecided state (surface shown, not yet locked), so check the real + // lock state instead. + if (m_greeterProxy->isLocked()) { + return; + } + + m_server->prepareLockScreenTransition(); + m_lockScreen->lock(); + + if (switchToGreeter) + requestSwitchToGreeter(); +} + +bool LockScreenManager::isLockScreenAvailable() const +{ + return m_lockScreen && m_lockScreen->available(); +} + +void LockScreenManager::onLockScreenShutdown() +{ + showShutdownMenu(); +} + +void LockScreenManager::showShutdownMenu(WaylandServer::ShutdownMenuFocus focus) +{ + if (!isLockScreenAvailable() || !m_server->isNormalOrMultitaskview()) { + return; + } + + m_server->prepareLockScreenTransition(true); + m_lockScreen->shutdown(focus); +} + +void LockScreenManager::showSwitchUser() +{ + if (!isLockScreenAvailable() || !m_server->isNormalOrMultitaskview()) { + return; + } + + m_server->prepareLockScreenTransition(); + m_lockScreen->switchUser(); +} diff --git a/src/lockscreen/lockscreenmanager.h b/src/lockscreen/lockscreenmanager.h new file mode 100644 index 0000000000..ce537c80f7 --- /dev/null +++ b/src/lockscreen/lockscreenmanager.h @@ -0,0 +1,66 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include "core/waylandserver.h" + +#include + +class LockScreen; +class LockScreenInterface; +class ILockScreen; +class GreeterProxy; +class QTimer; +class Session; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WServer; +class WSessionLock; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class LockScreenManager : public QObject +{ + Q_OBJECT +public: + explicit LockScreenManager(WaylandServer *server); + ~LockScreenManager() override; + + void setGreeterProxy(GreeterProxy *greeter); + void installSessionLock(WServer *server); + void handleLockScreen(LockScreenInterface *lockScreen); + void setLockScreenImpl(ILockScreen *impl); + void showLockScreen(bool switchToGreeter = true); + bool isLockScreenAvailable() const; + void showShutdownMenu(WaylandServer::ShutdownMenuFocus focus = + WaylandServer::ShutdownMenuFocus::None); + void showSwitchUser(); + +Q_SIGNALS: + // Emitted when the LockScreen implementation becomes available or unavailable. + void lockScreenAvailableChanged(); + void sessionLockStateRequested(bool locked); + void sessionRelockRequested(const QString &id); + +private Q_SLOTS: + // The lock screen interface asks for the menu without a focus preference. + void onLockScreenShutdown(); + +private: + void onSessionLock(Session *session); + void onSessionUnlock(Session *session); + void requestSwitchToGreeter(); + void onExtSessionLock(WSessionLock *lock); + +private: + WaylandServer *m_server = nullptr; + GreeterProxy *m_greeterProxy = nullptr; + LockScreen *m_lockScreen = nullptr; +#ifdef EXT_SESSION_LOCK_V1 + QTimer *m_lockScreenGraceTimer = nullptr; +#endif +}; diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000000..804883d457 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,81 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "common/treelandlogging.h" +#include "dconfig/dconfigmanager.h" +#include "core/treeland.h" +#include "core/treelandinit.h" +#include "utils/cmdline.h" + +#include + +#include + +#include +#include + +#include + +int main(int argc, char *argv[]) +{ + auto application = Treeland::preInit(argc, argv); + +#ifdef QT_DEBUG + DLogManager::registerConsoleAppender(); +#endif + CmdLine::ref(); +#ifndef QT_DEBUG + if (CmdLine::ref().consoleLog()) + DLogManager::registerConsoleAppender(); +#endif + DLogManager::registerJournalAppender(); + + Treeland::postInit(); + + if (CmdLine::ref().tryExec()) + return 0; + Q_ASSERT(waylib_buffer_get_count() == 0); + + int quitCode = 0; + { + DConfigManager dConfigManager(application.get()); + std::unique_ptr treeland; + + auto startTreeland = [&treeland] { + if (!treeland) { + qCInfo(lcTlConfig) << "DConfig initialization completed; starting Treeland"; + treeland = std::make_unique(); + } + }; + + QObject::connect(&dConfigManager, + &DConfigManager::initializeSucceed, + application.get(), + startTreeland); + QObject::connect(&dConfigManager, + &DConfigManager::initializeFailed, + application.get(), + [application = application.get()] { + qCCritical(lcTlCore) + << "Global DConfig initialization failed; aborting Treeland startup."; + application->exit(1); + }); + + if (dConfigManager.isInitializeFailed()) { + qCCritical(lcTlCore) + << "Global DConfig initialization failed before the event loop started."; + quitCode = 1; + } else { + if (dConfigManager.isInitializeSucceeded()) { + startTreeland(); + } else { + qCInfo(lcTlConfig) << "Waiting for global DConfig initialization before starting Treeland"; + } + + quitCode = application->exec(); + } + } + Q_ASSERT(waylib_buffer_get_count() == 0); + + return quitCode; +} diff --git a/src/modules/CMakeLists.txt b/src/modules/CMakeLists.txt new file mode 100644 index 0000000000..429fcfe53f --- /dev/null +++ b/src/modules/CMakeLists.txt @@ -0,0 +1,58 @@ +pkg_search_module(WAYLAND_SERVER REQUIRED IMPORTED_TARGET wayland-server) + +function(ws_generate_local type input_file output_name) + find_package(PkgConfig REQUIRED) + pkg_get_variable(WAYLAND_SCANNER wayland-scanner wayland_scanner) + execute_process(COMMAND ${WAYLAND_SCANNER} + ${type}-header + ${input_file} + ${WAYLAND_PROTOCOLS_OUTPUTDIR}/${output_name}.h + ) + + execute_process(COMMAND ${WAYLAND_SCANNER} + public-code + ${input_file} + ${WAYLAND_PROTOCOLS_OUTPUTDIR}/${output_name}.c + ) +endfunction() + +link_libraries( + PkgConfig::WAYLAND_SERVER +) + +# xdg-shell protocol code is compiled into libwaylibserver (waylib's +# ws_generate); compiling it again here would duplicate global symbols +# (xdg_*_interface) across the two shared libraries. + +add_subdirectory(foreign-toplevel) +add_subdirectory(output-manager) +add_subdirectory(personalization) +add_subdirectory(decoration) +add_subdirectory(appearance) +add_subdirectory(compositor-action) +add_subdirectory(shortcut) +add_subdirectory(wallpaper-color) +if (NOT DISABLE_XWAYLAND) + add_subdirectory(xwindow-control) +endif() +add_subdirectory(output-group) +add_subdirectory(dde-shell) +add_subdirectory(active-notify) +add_subdirectory(region-watch) +add_subdirectory(capture) +add_subdirectory(snap-target) +add_subdirectory(output-uuid) +add_subdirectory(item-selector) +add_subdirectory(ddm) +add_subdirectory(screensaver) +add_subdirectory(prelaunch-splash) +add_subdirectory(app-id-resolver) +add_subdirectory(wine-window-state) +add_subdirectory(wine-window-management) +add_subdirectory(wallpaper) +add_subdirectory(activation) +add_subdirectory(window-transition) +add_subdirectory(input-manager) +add_subdirectory(keyboard-state-notify) +add_subdirectory(keyboard-shortcuts-inhibit) +add_subdirectory(layer-shell-extension) diff --git a/src/modules/activation/CMakeLists.txt b/src/modules/activation/CMakeLists.txt new file mode 100644 index 0000000000..993f6fdfbd --- /dev/null +++ b/src/modules/activation/CMakeLists.txt @@ -0,0 +1,16 @@ +pkg_get_variable(WAYLAND_PROTOCOLS_DATADIR wayland-protocols pkgdatadir) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${WAYLAND_PROTOCOLS_DATADIR}/staging/xdg-activation/xdg-activation-v1.xml + BASENAME xdg-activation-v1 +) + +impl_treeland( + NAME + module_activation + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/activation/activationmanagerinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/activation/activationmanagerinterfacev1.cpp + INCLUDE + $ +) diff --git a/src/modules/activation/activationmanagerinterfacev1.cpp b/src/modules/activation/activationmanagerinterfacev1.cpp new file mode 100644 index 0000000000..63a3e9fdc2 --- /dev/null +++ b/src/modules/activation/activationmanagerinterfacev1.cpp @@ -0,0 +1,334 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "activationmanagerinterfacev1.h" +#include "common/treelandlogging.h" +#include "qwayland-server-xdg-activation-v1.h" + +#include +#include +#include + +#include +#include +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE +using namespace Qt::StringLiterals; + +// --------------------------------------------------------------------------- +// Forward declaration +// --------------------------------------------------------------------------- + +class ActivationManagerInterfaceV1Private; + +// --------------------------------------------------------------------------- +// Token context — manages one in-progress token object +// --------------------------------------------------------------------------- + +/** + * Represents a single xdg_activation_token_v1 resource. + * + * The client calls set_serial / set_surface / set_app_id (all optional) and + * then commit() to obtain the token string. After commit() the object is + * inert. The object self-destructs via destroy_resource(). + */ +class TokenContext : public QtWaylandServer::xdg_activation_token_v1 +{ +public: + TokenContext(ActivationManagerInterfaceV1Private *manager, + struct ::wl_resource *resource) + : QtWaylandServer::xdg_activation_token_v1(resource) + , m_manager(manager) + { + } + +protected: + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void destroy_resource(Resource *) override + { + delete this; + } + + void set_serial(Resource * /*resource*/, + uint32_t serial, + struct ::wl_resource *seat) override + { + if (m_committed) + return; + + auto *seatClient = seat ? wlr_seat_client_from_resource(seat) : nullptr; + if (!seatClient) { + qCWarning(lcTlActivation) << "set_serial: invalid seat resource, ignoring serial" << serial; + m_serial.reset(); + m_seat.clear(); + return; + } + + auto *wseat = WSeat::fromHandle(seatClient->seat); + if (!wseat) { + qCWarning(lcTlActivation) << "set_serial: no WSeat for seat resource, ignoring serial" << serial; + m_serial.reset(); + m_seat.clear(); + return; + } + + m_serial = serial; + m_seat = wseat; + } + + void set_surface(Resource * /*resource*/, + struct ::wl_resource *surface) override; + + void set_app_id(Resource * /*resource*/, const QString &app_id) override + { + if (m_committed) + return; + m_appId = app_id; + } + + void commit(Resource *resource) override; + +private: + ActivationManagerInterfaceV1Private *m_manager; + QString m_appId; + std::optional m_serial; + bool m_committed = false; + QPointer m_seat; // set by set_serial; null if not called or seat destroyed + QPointer m_surface; // set by set_surface; null if not called or surface destroyed +}; + +// --------------------------------------------------------------------------- +// Manager private +// --------------------------------------------------------------------------- + +struct TokenInfo +{ + QString token; + QString appId; + wl_client *requestingClient = nullptr; + std::optional serial; + bool fromTrustedSurface = false; // set_surface called and surface was active at commit time + QDeadlineTimer expiry; // invalidated 60 s after registration + QPointer seat; // seat associated with the token via set_serial + QPointer originatingSurface; // surface set via set_surface +}; + +class ActivationManagerInterfaceV1Private + : public QtWaylandServer::xdg_activation_v1 +{ +public: + explicit ActivationManagerInterfaceV1Private(ActivationManagerInterfaceV1 *q, + std::function trustedSurfaceChecker) + : QtWaylandServer::xdg_activation_v1() + , q(q) + , m_trustedSurfaceChecker(std::move(trustedSurfaceChecker)) + { + } + + wl_global *globalHandle() const + { + return m_global; + } + + /** + * Called by TokenContext::commit() to register a new valid token. + * Returns the generated token string. + */ + QString registerToken(const QString &appId, + wl_client *client, + std::optional serial, + bool fromTrustedSurface, + WSeat *seat, + WSurface *originatingSurface) + { + const QString token = QUuid::createUuid().toString(QUuid::WithoutBraces); + m_tokens.append(TokenInfo{ token, + appId, + client, + serial, + fromTrustedSurface, + QDeadlineTimer(TokenLifetimeMs), + seat, + originatingSurface }); + qCDebug(lcTlActivation) << "Registered activation token" << token.left(8) + u"..."_s + << "for app" << appId + << (fromTrustedSurface ? "" : "(inactive-surface-token-request)"); + return token; + } + + bool isTrustedSurface(WSurface *surface, WSeat *seat) const + { + if (m_trustedSurfaceChecker && seat) + return m_trustedSurfaceChecker(surface, seat); + return false; // conservative: no checker → treat as inactive + } + +protected: + void destroy_global() override + { + qCDebug(lcTlActivation) << "treeland_activation_manager_v1 global destroyed"; + } + + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void get_activation_token(Resource *resource, uint32_t id) override + { + auto *tokenResource = wl_resource_create(resource->client(), + &xdg_activation_token_v1_interface, + resource->version(), + id); + if (!tokenResource) { + wl_resource_post_no_memory(resource->handle); + return; + } + // TokenContext self-destructs in destroy_resource() + new TokenContext(this, tokenResource); + } + + void activate(Resource * /*resource*/, + const QString &token, + struct ::wl_resource *surface) override + { + sweepExpiredTokens(); + + auto *wlrSurface = wlr_surface_from_resource(surface); + if (!wlrSurface) { + qCWarning(lcTlActivation) << "activate: invalid surface resource"; + return; + } + + auto *wsurface = WSurface::fromHandle(wlrSurface); + if (!wsurface) { + qCWarning(lcTlActivation) << "activate: no WSurface for wlr_surface"; + return; + } + + auto disposition = ActivationManagerInterfaceV1::TokenDisposition::Invalid; + WSeat *tokenSeat = nullptr; + WSurface *originatingSurface = nullptr; + + auto it = std::find_if(m_tokens.begin(), m_tokens.end(), + [&token](const TokenInfo &t) { return t.token == token; }); + if (it != m_tokens.end()) { + tokenSeat = it->seat.data(); + originatingSurface = it->originatingSurface; + disposition = it->fromTrustedSurface + ? (it->serial.has_value() + ? ActivationManagerInterfaceV1::TokenDisposition::Active + : ActivationManagerInterfaceV1::TokenDisposition::Attention) + : ActivationManagerInterfaceV1::TokenDisposition::Attention; + } + + qCInfo(lcTlActivation) << "activate: emitting activateRequested for token" + << token.left(8) + u"..."_s << "with disposition" << disposition; + + // Keep token one-shot semantics + if (it != m_tokens.end()) { + m_tokens.erase(it); + } + + Q_EMIT q->activateRequested(token, disposition, wsurface, tokenSeat, originatingSurface); + } + +private: + void sweepExpiredTokens() + { + auto it = m_tokens.begin(); + while (it != m_tokens.end()) { + if (it->expiry.hasExpired()) { + qCDebug(lcTlActivation) << "Sweeping expired token for app" << it->appId; + it = m_tokens.erase(it); + } else { + ++it; + } + } + } + + ActivationManagerInterfaceV1 *q; + QList m_tokens; + std::function m_trustedSurfaceChecker; + + static constexpr int TokenLifetimeMs = 60'000; +}; + +// --------------------------------------------------------------------------- +// TokenContext methods — defined after ActivationManagerInterfaceV1Private +// --------------------------------------------------------------------------- + +void TokenContext::set_surface(Resource * /*resource*/, struct ::wl_resource *surface) +{ + if (m_committed) + return; + auto *wlrSurface = wlr_surface_from_resource(surface); + m_surface = wlrSurface ? WSurface::fromHandle(wlrSurface) : nullptr; +} + +void TokenContext::commit(Resource *resource) +{ + if (m_committed) { + wl_resource_post_error(resource->handle, + error_already_used, + "commit() called a second time on this token"); + return; + } + m_committed = true; + + // fromTrustedSurface: set_surface was called, surface still alive, and currently active + const bool fromTrustedSurface = m_surface && m_manager->isTrustedSurface(m_surface, m_seat); + + const QString token = m_manager->registerToken(m_appId, + resource->client(), + m_serial, + fromTrustedSurface, + m_seat, + m_surface); + + send_done(token); +} + +// --------------------------------------------------------------------------- +// Public class +// --------------------------------------------------------------------------- + +ActivationManagerInterfaceV1::ActivationManagerInterfaceV1( + std::function trustedSurfaceChecker, + QObject *parent) + : QObject(parent) + , WServerInterface() + , d(new ActivationManagerInterfaceV1Private(this, std::move(trustedSurfaceChecker))) +{ +} + +ActivationManagerInterfaceV1::~ActivationManagerInterfaceV1() = default; + +QByteArrayView ActivationManagerInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} + +void ActivationManagerInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void ActivationManagerInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *ActivationManagerInterfaceV1::global() const +{ + return d->globalHandle(); +} + diff --git a/src/modules/activation/activationmanagerinterfacev1.h b/src/modules/activation/activationmanagerinterfacev1.h new file mode 100644 index 0000000000..e7acbca375 --- /dev/null +++ b/src/modules/activation/activationmanagerinterfacev1.h @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include +#include + +#include +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WSurface; +class WSeat; +WAYLIB_SERVER_END_NAMESPACE + +class ActivationManagerInterfaceV1Private; + +class ActivationManagerInterfaceV1 : public QObject, public WAYLIB_SERVER_NAMESPACE::WServerInterface +{ + Q_OBJECT +public: + enum class TokenDisposition + { + Invalid, + Attention, + Active, + }; + Q_ENUM(TokenDisposition) + + explicit ActivationManagerInterfaceV1( + std::function trustedSurfaceChecker, + QObject *parent = nullptr); + ~ActivationManagerInterfaceV1() override; + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; + +Q_SIGNALS: + // The server emits one signal with precomputed disposition for policy handling. + // token is the committed activation token string. + // seat is the WSeat associated with the token via set_serial, or null. + // originatingSurface is the WSurface that was set via set_surface on the + // token (the surface that initiated the launch), or null. + void activateRequested(const QString &token, + TokenDisposition disposition, + WAYLIB_SERVER_NAMESPACE::WSurface *surface, + WAYLIB_SERVER_NAMESPACE::WSeat *seat, + WAYLIB_SERVER_NAMESPACE::WSurface *originatingSurface); + +protected: + void create(WAYLIB_SERVER_NAMESPACE::WServer *server) override; + void destroy(WAYLIB_SERVER_NAMESPACE::WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; diff --git a/src/modules/active-notify/CMakeLists.txt b/src/modules/active-notify/CMakeLists.txt new file mode 100644 index 0000000000..d511bd114e --- /dev/null +++ b/src/modules/active-notify/CMakeLists.txt @@ -0,0 +1,16 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-active-notify-unstable-v1.xml + BASENAME treeland-active-notify-unstable-v1 +) + +impl_treeland( + NAME + module_active_notify + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/active-notify/activenotifymanagerinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/active-notify/activenotifymanagerinterfacev1.cpp + INCLUDE + $ +) diff --git a/src/modules/active-notify/activenotifymanagerinterfacev1.cpp b/src/modules/active-notify/activenotifymanagerinterfacev1.cpp new file mode 100644 index 0000000000..6bcae59b82 --- /dev/null +++ b/src/modules/active-notify/activenotifymanagerinterfacev1.cpp @@ -0,0 +1,176 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "activenotifymanagerinterfacev1.h" + +#include "qwayland-server-treeland-active-notify-unstable-v1.h" + +static QList s_notifies; + +struct TreelandActiveNotifyManagerInterfaceV1Private + : public QtWaylandServer::treeland_active_notify_manager_v1 +{ +public: + explicit TreelandActiveNotifyManagerInterfaceV1Private(TreelandActiveNotifyManagerInterfaceV1 *_q); + + wl_global *global() const; + + TreelandActiveNotifyManagerInterfaceV1 *q; + +protected: + void destroy(Resource *resource) override; + void get_active_notify(Resource *resource, + uint32_t id, + struct ::wl_resource *seat) override; +}; + +TreelandActiveNotifyManagerInterfaceV1Private::TreelandActiveNotifyManagerInterfaceV1Private( + TreelandActiveNotifyManagerInterfaceV1 *_q) + : q(_q) +{ +} + +wl_global *TreelandActiveNotifyManagerInterfaceV1Private::global() const +{ + return m_global; +} + +void TreelandActiveNotifyManagerInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void TreelandActiveNotifyManagerInterfaceV1Private::get_active_notify(Resource *resource, + uint32_t id, + struct ::wl_resource *seat) +{ + struct wlr_seat_client *seat_client = wlr_seat_client_from_resource(seat); + if (!seat_client) { + wl_resource_post_error(resource->handle, 0, "seat resource is inert!"); + return; + } + WSeat *wseat = WSeat::fromHandle(seat_client->seat); + if (!wseat) { + wl_resource_post_error(resource->handle, 0, "seat resource has no WSeat!"); + return; + } + + wl_resource *notifyResource = wl_resource_create(resource->client(), + &treeland_active_notify_v1_interface, + resource->version(), + id); + if (!notifyResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto notify = new ActiveNotifyV1(notifyResource, wseat); + s_notifies.append(notify); + + QObject::connect(notify, &QObject::destroyed, [notify]() { + s_notifies.removeOne(notify); + }); + + Q_EMIT q->activeNotifyCreated(notify); +} + +TreelandActiveNotifyManagerInterfaceV1::TreelandActiveNotifyManagerInterfaceV1(QObject *parent) + : QObject(parent) + , d(new TreelandActiveNotifyManagerInterfaceV1Private(this)) +{ +} + +TreelandActiveNotifyManagerInterfaceV1::~TreelandActiveNotifyManagerInterfaceV1() = default; + +void TreelandActiveNotifyManagerInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void TreelandActiveNotifyManagerInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *TreelandActiveNotifyManagerInterfaceV1::global() const +{ + return d->global(); +} + +QByteArrayView TreelandActiveNotifyManagerInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} + +class ActiveNotifyV1Private : public QtWaylandServer::treeland_active_notify_v1 +{ +public: + ActiveNotifyV1Private(ActiveNotifyV1 *_q, wl_resource *_resource, WSeat *_seat); + + ActiveNotifyV1 *q; + QPointer wseat; + +protected: + void destroy_resource([[maybe_unused]] Resource *resource) override; + void destroy([[maybe_unused]] Resource *resource) override; +}; + +ActiveNotifyV1Private::ActiveNotifyV1Private(ActiveNotifyV1 *_q, + wl_resource *_resource, + WSeat *_seat) + : QtWaylandServer::treeland_active_notify_v1(_resource) + , q(_q) + , wseat(_seat) +{ +} + +void ActiveNotifyV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void ActiveNotifyV1Private::destroy([[maybe_unused]] Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +ActiveNotifyV1::ActiveNotifyV1(wl_resource *resource, WSeat *seat, QObject *parent) + : QObject(parent) + , d(new ActiveNotifyV1Private(this, resource, seat)) +{ +} + +ActiveNotifyV1::~ActiveNotifyV1() = default; + +WSeat *ActiveNotifyV1::wSeat() const +{ + return d->wseat; +} + +void ActiveNotifyV1::sendActivityChanged(Reason reason, ActivityState state) +{ + d->send_activity_changed(reason, state); +} + +void ActiveNotifyV1::sendDragChanged(DragState state) +{ + d->send_drag_changed(state); +} + +void ActiveNotifyV1::sendActivityChanged(Reason reason, ActivityState state, const WSeat *seat) +{ + for (auto notify : std::as_const(s_notifies)) { + if (notify->wSeat() == seat) { + notify->sendActivityChanged(reason, state); + } + } +} + +void ActiveNotifyV1::sendDragChanged(DragState state, const WSeat *seat) +{ + for (auto notify : std::as_const(s_notifies)) { + if (notify->wSeat() == seat) { + notify->sendDragChanged(state); + } + } +} diff --git a/src/modules/active-notify/activenotifymanagerinterfacev1.h b/src/modules/active-notify/activenotifymanagerinterfacev1.h new file mode 100644 index 0000000000..8cf9ca5b3e --- /dev/null +++ b/src/modules/active-notify/activenotifymanagerinterfacev1.h @@ -0,0 +1,81 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class ActiveNotifyV1Private; +class ActiveNotifyV1; +class TreelandActiveNotifyManagerInterfaceV1Private; + +class TreelandActiveNotifyManagerInterfaceV1 : public QObject, public WServerInterface +{ + Q_OBJECT +public: + explicit TreelandActiveNotifyManagerInterfaceV1(QObject *parent = nullptr); + ~TreelandActiveNotifyManagerInterfaceV1() override; + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; + +Q_SIGNALS: + void activeNotifyCreated(ActiveNotifyV1 *notify); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; + +class ActiveNotifyV1 : public QObject +{ + Q_OBJECT +public: + ~ActiveNotifyV1() override; + + enum Reason { + Mouse = 0, + Wheel = 1, + }; + Q_ENUM(Reason) + + enum ActivityState { + Inactive = 0, + Active = 1, + }; + Q_ENUM(ActivityState) + + enum DragState { + Started = 0, + Dropped = 1, + Cancelled = 2, + }; + Q_ENUM(DragState) + + WSeat *wSeat() const; + + void sendActivityChanged(Reason reason, ActivityState state); + void sendDragChanged(DragState state); + + static void sendActivityChanged(Reason reason, ActivityState state, const WSeat *seat); + static void sendDragChanged(DragState state, const WSeat *seat); + +private: + explicit ActiveNotifyV1(wl_resource *resource, WSeat *seat, QObject *parent = nullptr); + + friend class TreelandActiveNotifyManagerInterfaceV1Private; + std::unique_ptr d; +}; diff --git a/src/modules/app-id-resolver/CMakeLists.txt b/src/modules/app-id-resolver/CMakeLists.txt new file mode 100644 index 0000000000..320f98df64 --- /dev/null +++ b/src/modules/app-id-resolver/CMakeLists.txt @@ -0,0 +1,18 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-app-id-resolver-unstable-v2.xml + BASENAME treeland-app-id-resolver-unstable-v2 +) + +impl_treeland( + NAME + module_app_id_resolver + SOURCE + appidresolver.h + appidresolver.cpp + INCLUDE + $ + LINK + Qt6::Core +) diff --git a/src/modules/app-id-resolver/appidresolver.cpp b/src/modules/app-id-resolver/appidresolver.cpp new file mode 100644 index 0000000000..11e11fabc8 --- /dev/null +++ b/src/modules/app-id-resolver/appidresolver.cpp @@ -0,0 +1,197 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "appidresolver.h" + +#include "common/treelandlogging.h" +#include "qwayland-server-treeland-app-id-resolver-unstable-v2.h" + +#include + +#include + +#include +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class AppIdResolver + : public QObject + , public QtWaylandServer::treeland_app_id_resolver_v2 +{ +public: + AppIdResolver(QObject *parent, wl_client *client, int version, uint32_t id) + : QObject(parent) + , QtWaylandServer::treeland_app_id_resolver_v2(client, id, version) + { + } + + uint32_t requestResolve(int pidfd) + { + if (!m_alive || pidfd < 0) + return 0; + int dupfd = fcntl(pidfd, F_DUPFD_CLOEXEC, 0); + if (dupfd < 0) + return 0; + uint32_t id = m_nextRequestId++; + send_identify_request(id, dupfd); + return id; + } + + std::function onResolved; + std::function onDisconnected; + +protected: + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void destroy_resource([[maybe_unused]] Resource *resource) override + { + m_alive = false; + if (onDisconnected) + onDisconnected(); + } + + void respond([[maybe_unused]] Resource *resource, + uint32_t request_id, + const QString &app_id, + [[maybe_unused]] const QString &sandboxEngineName) override + { + if (onResolved) + onResolved(request_id, app_id); + } + +private: + bool m_alive = true; + uint32_t m_nextRequestId = 1; +}; + +class AppIdResolverManagerPrivate : public QtWaylandServer::treeland_app_id_resolver_manager_v2 +{ +public: + explicit AppIdResolverManagerPrivate(AppIdResolverManager *_q) + : QtWaylandServer::treeland_app_id_resolver_manager_v2() + , q(_q) + { + } + + bool resolvePidfd(int pidfd, std::function callback) + { + if (!m_resolver) + return false; + uint32_t id = m_resolver->requestResolve(pidfd); + if (id == 0) + return false; + m_callbacks.insert(id, std::move(callback)); + return true; + } + + wl_global *globalHandle() const + { + return m_global; + } + +private: + AppIdResolverManager *q = nullptr; + AppIdResolver *m_resolver = nullptr; + QHash> m_callbacks; + + void resolverGone() + { + if (!m_resolver) + return; + // All pending requests return empty appId when resolver disappears. + auto callbacks = m_callbacks.values(); + m_callbacks.clear(); + for (auto &cb : std::as_const(callbacks)) { + if (cb) + cb(QString()); + } + QObject::disconnect(m_resolver, nullptr, q, nullptr); + m_resolver->deleteLater(); + m_resolver = nullptr; + Q_EMIT q->availableChanged(); + } + + void handleResolved(uint32_t id, const QString &appId) + { + auto it = m_callbacks.find(id); + if (it == m_callbacks.end()) + return; + + auto cb = it.value(); + m_callbacks.erase(it); + if (cb) + cb(appId); + } + +protected: + void destroy_global() override + { + qCDebug(lcTlAppIdResolver) << "AppIdResolverManager global destroyed"; + } + + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void get_resolver(Resource *resource, uint32_t id) override + { + qCDebug(lcTlAppIdResolver) << "get_resolver called (client id):" << id; + if (m_resolver) { + wl_resource_post_error(resource->handle, + WL_DISPLAY_ERROR_INVALID_OBJECT, + "resolver already exists"); + return; + } + + m_resolver = new AppIdResolver(q, resource->client(), resource->version(), id); + m_resolver->onResolved = [this](uint32_t requestId, const QString &appId) { + handleResolved(requestId, appId); + }; + m_resolver->onDisconnected = [this]() { + resolverGone(); + }; + Q_EMIT q->availableChanged(); + qCDebug(lcTlAppIdResolver) << "Resolver bound"; + } +}; + +AppIdResolverManager::AppIdResolverManager(QObject *parent) + : QObject(parent) + , d(new AppIdResolverManagerPrivate(this)) +{ +} + +AppIdResolverManager::~AppIdResolverManager() = default; + +bool AppIdResolverManager::resolvePidfd(int pidfd, std::function callback) +{ + return d->resolvePidfd(pidfd, std::move(callback)); +} + +void AppIdResolverManager::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); + qCDebug(lcTlAppIdResolver) << "AppIdResolverManager global created"; +} + +void AppIdResolverManager::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); + qCDebug(lcTlAppIdResolver) << "AppIdResolverManager global removal scheduled"; +} + +wl_global *AppIdResolverManager::global() const +{ + return d->globalHandle(); +} + +QByteArrayView AppIdResolverManager::interfaceName() const +{ + return QtWaylandServer::treeland_app_id_resolver_manager_v2::interfaceName(); +} diff --git a/src/modules/app-id-resolver/appidresolver.h b/src/modules/app-id-resolver/appidresolver.h new file mode 100644 index 0000000000..71eae07655 --- /dev/null +++ b/src/modules/app-id-resolver/appidresolver.h @@ -0,0 +1,43 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include + +#include + +#include +#include + +class AppIdResolverManagerPrivate; + +class AppIdResolverManager + : public QObject + , public WAYLIB_SERVER_NAMESPACE::WServerInterface +{ + Q_OBJECT +public: + explicit AppIdResolverManager(QObject *parent = nullptr); + ~AppIdResolverManager() override; + static constexpr int InterfaceVersion = 1; + + // Callback-based API: returns true if request started, false if no resolver or dup fd failed + // Callback is invoked asynchronously on the Wayland (main) thread; empty string if resolver + // disconnects + bool resolvePidfd(int pidfd, std::function callback); + QByteArrayView interfaceName() const override; + +Q_SIGNALS: + void availableChanged(); + +protected: // WServerInterface overrides + void create(WAYLIB_SERVER_NAMESPACE::WServer *server) override; + void destroy(WAYLIB_SERVER_NAMESPACE::WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; diff --git a/src/modules/appearance/CMakeLists.txt b/src/modules/appearance/CMakeLists.txt new file mode 100644 index 0000000000..951da5483e --- /dev/null +++ b/src/modules/appearance/CMakeLists.txt @@ -0,0 +1,36 @@ +find_package(TreelandProtocols 0.6.0 REQUIRED) + +# --- New protocols (treeland-protocols 0.6.0) --- +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-appearance-unstable-v1.xml + BASENAME treeland-appearance-unstable-v1 +) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-appearance-manager-unstable-v1.xml + BASENAME treeland-appearance-manager-unstable-v1 +) + +set(PUBLIC_HEADERS + ${CMAKE_SOURCE_DIR}/src/modules/appearance/appearanceinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/appearance/appearancemanagerinterfacev1.h +) + +set(SRCS + ${CMAKE_SOURCE_DIR}/src/modules/appearance/appearanceinterfacev1.cpp + ${CMAKE_SOURCE_DIR}/src/modules/appearance/appearancemanagerinterfacev1.cpp +) + +impl_treeland( + NAME + module_appearance + SOURCE + ${PUBLIC_HEADERS} + ${SRCS} + INCLUDE + $ +) + +if(TREELAND_INSTALL_DEV) + install(FILES ${PUBLIC_HEADERS} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/treeland/modules/appearance") +endif() diff --git a/src/modules/appearance/appearanceinterfacev1.cpp b/src/modules/appearance/appearanceinterfacev1.cpp new file mode 100644 index 0000000000..8abcf68b62 --- /dev/null +++ b/src/modules/appearance/appearanceinterfacev1.cpp @@ -0,0 +1,261 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "appearanceinterfacev1.h" + +#include "qwayland-server-treeland-appearance-unstable-v1.h" + +#include "common/treelandlogging.h" +#include "treelanduserconfig.hpp" + +#include + +#include + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +namespace { + +/// DConfig windowColorScheme (0=light, 1=dark) → protocol color_scheme (0=light, 1=dark) +/// Values are aligned, so this only validates and forwards. +uint32_t dconfigToColorScheme(int32_t type) +{ + switch (type) { + case TREELAND_APPEARANCE_V1_COLOR_SCHEME_LIGHT: + case TREELAND_APPEARANCE_V1_COLOR_SCHEME_DARK: + return static_cast(type); + default: + qCWarning(lcTlConfig) << "Unknown dconfig windowColorScheme:" << type + << ", fallback to light."; + return TREELAND_APPEARANCE_V1_COLOR_SCHEME_LIGHT; + } +} + +/// Parse "#RRGGBB" hex string to RGB components. +struct Rgb { uint32_t r, g, b; }; +Rgb hexToRgb(const QString &hex) +{ + QColor c(hex); + if (!c.isValid()) { + qCWarning(lcTlConfig) << "Invalid color string:" << hex; + return {0, 0, 0}; + } + return {static_cast(c.red()), + static_cast(c.green()), + static_cast(c.blue())}; +} + +} // namespace + +// --------------------------------------------------------------------------- +// AppearanceInterfaceV1Private +// --------------------------------------------------------------------------- + +class AppearanceInterfaceV1Private + : public QtWaylandServer::treeland_appearance_v1 +{ +public: + explicit AppearanceInterfaceV1Private(AppearanceInterfaceV1 *_q); + ~AppearanceInterfaceV1Private() override = default; + + wl_global *global() const { return m_global; } + + AppearanceInterfaceV1 *q = nullptr; + +protected: + void destroy(Resource *resource) override; + void bind_resource(Resource *resource) override; +}; + +AppearanceInterfaceV1Private::AppearanceInterfaceV1Private(AppearanceInterfaceV1 *_q) + : QtWaylandServer::treeland_appearance_v1() + , q(_q) +{ +} + +void AppearanceInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void AppearanceInterfaceV1Private::bind_resource(Resource *resource) +{ + // Push model: send the current value of every setting immediately on bind. + // If async config initialization hasn't finished (or failed), the getters + // return DConfig default values, so push those instead of skipping. + q->sendAll(resource->handle); +} + +// --------------------------------------------------------------------------- +// AppearanceInterfaceV1 +// --------------------------------------------------------------------------- + +struct AppearanceInterfaceV1::Private +{ + std::unique_ptr server; + QList configConnections; +}; + +AppearanceInterfaceV1::AppearanceInterfaceV1(TreelandUserConfig *config, QObject *parent) + : QObject(parent) + , WServerInterface() + , m_config(config) + , d(std::make_unique()) +{ + d->server = std::make_unique(this); + + setupConfigConnections(); + if (m_config) { + connect(m_config, &TreelandUserConfig::configInitializeSucceed, + this, &AppearanceInterfaceV1::onConfigChanged); + connect(m_config, &TreelandUserConfig::configInitializeFailed, + this, &AppearanceInterfaceV1::onConfigChanged); + } +} + +AppearanceInterfaceV1::~AppearanceInterfaceV1() +{ + for (const auto &conn : std::as_const(d->configConnections)) + QObject::disconnect(conn); +} + +void AppearanceInterfaceV1::onConfigChanged() +{ + setupConfigConnections(); + for (const auto &resource : d->server->resourceMap()) + sendAll(resource->handle); +} + +void AppearanceInterfaceV1::setupConfigConnections() +{ + // Rebuild subscriptions to this instance's fixed user configuration. + for (const auto &conn : std::as_const(d->configConnections)) + QObject::disconnect(conn); + d->configConnections.clear(); + + if (!m_config) + return; + + // Settings change signals. Initialization completion is not watched: + // bind_resource() and onConfigChanged() push this user's values, and + // uninitialized getters return DConfig defaults. + d->configConnections.append( + connect(m_config, &TreelandUserConfig::cursorThemeNameChanged, this, [this] { + const auto name = m_config->cursorThemeName(); + for (const auto &resource : d->server->resourceMap()) + d->server->send_cursor_theme(resource->handle, name); + })); + d->configConnections.append( + connect(m_config, &TreelandUserConfig::cursorSizeChanged, this, [this] { + const auto size = m_config->cursorSize(); + for (const auto &resource : d->server->resourceMap()) + d->server->send_cursor_size(resource->handle, size, size); + })); + d->configConnections.append( + connect(m_config, &TreelandUserConfig::fontChanged, this, [this] { + const auto font = m_config->font(); + for (const auto &resource : d->server->resourceMap()) + d->server->send_font(resource->handle, font); + })); + d->configConnections.append( + connect(m_config, &TreelandUserConfig::monoFontChanged, this, [this] { + const auto font = m_config->monoFont(); + for (const auto &resource : d->server->resourceMap()) + d->server->send_monospace_font(resource->handle, font); + })); + d->configConnections.append( + connect(m_config, &TreelandUserConfig::fontSizeChanged, this, [this] { + const auto size = static_cast(m_config->fontSize()); + for (const auto &resource : d->server->resourceMap()) + d->server->send_font_size(resource->handle, size); + })); + d->configConnections.append( + connect(m_config, &TreelandUserConfig::iconThemeNameChanged, this, [this] { + const auto theme = m_config->iconThemeName(); + for (const auto &resource : d->server->resourceMap()) + d->server->send_icon_theme(resource->handle, theme); + })); + d->configConnections.append( + connect(m_config, &TreelandUserConfig::activeColorChanged, this, [this] { + const auto rgb = hexToRgb(m_config->activeColor()); + for (const auto &resource : d->server->resourceMap()) + d->server->send_accent_color(resource->handle, rgb.r, rgb.g, rgb.b); + })); + d->configConnections.append( + connect(m_config, &TreelandUserConfig::windowOpacityChanged, this, [this] { + const auto opacity = wl_fixed_from_double( + m_config->windowOpacity() / 100.0); + for (const auto &resource : d->server->resourceMap()) + d->server->send_window_opacity(resource->handle, opacity); + })); + d->configConnections.append( + connect(m_config, &TreelandUserConfig::windowColorSchemeChanged, this, [this] { + const auto scheme = dconfigToColorScheme( + m_config->windowColorScheme()); + for (const auto &resource : d->server->resourceMap()) + d->server->send_color_scheme(resource->handle, scheme); + })); + d->configConnections.append( + connect(m_config, &TreelandUserConfig::windowTitlebarHeightChanged, this, [this] { + const auto height = static_cast( + m_config->windowTitlebarHeight()); + for (const auto &resource : d->server->resourceMap()) + d->server->send_titlebar_height(resource->handle, height); + })); + d->configConnections.append( + connect(m_config, &TreelandUserConfig::windowRadiusChanged, this, [this] { + const auto radius = static_cast( + m_config->windowRadius()); + for (const auto &resource : d->server->resourceMap()) + d->server->send_corner_radius(resource->handle, radius); + })); +} + +void AppearanceInterfaceV1::sendAll(wl_resource *resource) +{ + auto *config = m_config; + if (!config) + return; + + d->server->send_cursor_theme(resource, config->cursorThemeName()); + const int cursorSize = config->cursorSize(); + d->server->send_cursor_size(resource, cursorSize, cursorSize); + d->server->send_font(resource, config->font()); + d->server->send_monospace_font(resource, config->monoFont()); + d->server->send_font_size(resource, static_cast(config->fontSize())); + d->server->send_icon_theme(resource, config->iconThemeName()); + + const auto rgb = hexToRgb(config->activeColor()); + d->server->send_accent_color(resource, rgb.r, rgb.g, rgb.b); + + d->server->send_window_opacity(resource, + wl_fixed_from_double(config->windowOpacity() / 100.0)); + + d->server->send_color_scheme(resource, dconfigToColorScheme(config->windowColorScheme())); + d->server->send_titlebar_height(resource, + static_cast(config->windowTitlebarHeight())); + d->server->send_corner_radius(resource, + static_cast(config->windowRadius())); +} + +QByteArrayView AppearanceInterfaceV1::interfaceName() const +{ + return d->server->interfaceName(); +} + +void AppearanceInterfaceV1::create(WServer *server) +{ + d->server->init(server->handle(), InterfaceVersion); +} + +void AppearanceInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->server->globalRemove(); +} + +wl_global *AppearanceInterfaceV1::global() const +{ + return d->server->global(); +} diff --git a/src/modules/appearance/appearanceinterfacev1.h b/src/modules/appearance/appearanceinterfacev1.h new file mode 100644 index 0000000000..9f648b3ac1 --- /dev/null +++ b/src/modules/appearance/appearanceinterfacev1.h @@ -0,0 +1,53 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include +#include + +class TreelandUserConfig; + +WAYLIB_SERVER_USE_NAMESPACE + +/** + * @brief Server implementation of treeland_appearance_unstable_v1. + * + * Read-only global that pushes user-level appearance settings to all + * bound clients. On bind the current value of every setting is sent + * immediately; afterwards events are broadcast whenever a setting + * changes (either via the privileged AppearanceManagerInterfaceV1 or + * via DConfig). + */ +class AppearanceInterfaceV1 : public QObject, public WServerInterface +{ + Q_OBJECT + QML_ANONYMOUS + +public: + explicit AppearanceInterfaceV1(TreelandUserConfig *config, QObject *parent = nullptr); + TreelandUserConfig *config() const { return m_config; } + ~AppearanceInterfaceV1() override; + + QByteArrayView interfaceName() const override; + + /// Push the current value of every setting to @p resource. + void sendAll(wl_resource *resource); + + static constexpr int InterfaceVersion = 1; + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + void setupConfigConnections(); + void onConfigChanged(); + + struct Private; + TreelandUserConfig *const m_config; + std::unique_ptr d; +}; diff --git a/src/modules/appearance/appearancemanagerinterfacev1.cpp b/src/modules/appearance/appearancemanagerinterfacev1.cpp new file mode 100644 index 0000000000..16c6618d22 --- /dev/null +++ b/src/modules/appearance/appearancemanagerinterfacev1.cpp @@ -0,0 +1,239 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "appearancemanagerinterfacev1.h" + +#include "qwayland-server-treeland-appearance-manager-unstable-v1.h" + +#include "common/treelandlogging.h" +#include "core/waylandserver.h" +#include "session/session.h" +#include "treelanduserconfig.hpp" + +#include + +#include +#include + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +namespace { + +/// Protocol color_scheme (0=light, 1=dark) → DConfig windowColorScheme (0=light, 1=dark) +/// Values are aligned, so this only validates and forwards. +int32_t colorSchemeToDConfig(uint32_t scheme) +{ + switch (scheme) { + case TREELAND_APPEARANCE_MANAGER_V1_COLOR_SCHEME_LIGHT: + case TREELAND_APPEARANCE_MANAGER_V1_COLOR_SCHEME_DARK: + return static_cast(scheme); + default: + qCWarning(lcTlConfig) << "Unknown color_scheme:" << scheme + << ", ignoring."; + return -1; // caller should check + } +} + +/// Convert RGB components to "#RRGGBB" hex string for DConfig. +QString rgbToHex(uint32_t r, uint32_t g, uint32_t b) +{ + QColor c(static_cast(r), static_cast(g), static_cast(b)); + return c.name(QColor::HexRgb); // #RRGGBB +} + +/// Check whether the user config has completed asynchronous initialization. +bool isUserConfigInitialized(TreelandUserConfig *config) +{ + if (!config) + return false; + return config->isInitializeSucceeded(); +} + +/// Requests always address the immutable config supplied by the owning Session. +/// Drop requests until this configuration has completed initialization. +#define ENSURE_CONFIG() \ + do { \ + if (!q->config()) \ + return; \ + if (!isUserConfigInitialized(q->config())) { \ + qCWarning(lcTlConfig) << "Appearance set_* request dropped:" \ + << "user config not initialized yet"; \ + return; \ + } \ + } while (false) + +} // namespace + +// --------------------------------------------------------------------------- +// AppearanceManagerInterfaceV1Private +// --------------------------------------------------------------------------- + +class AppearanceManagerInterfaceV1Private + : public QtWaylandServer::treeland_appearance_manager_v1 +{ +public: + explicit AppearanceManagerInterfaceV1Private(AppearanceManagerInterfaceV1 *_q); + ~AppearanceManagerInterfaceV1Private() override = default; + + wl_global *global() const { return m_global; } + + AppearanceManagerInterfaceV1 *q = nullptr; + +protected: + void destroy(Resource *resource) override; + void set_cursor_theme(Resource *resource, const QString &name) override; + void set_cursor_size(Resource *resource, uint32_t width, uint32_t height) override; + void set_font(Resource *resource, const QString &font_name) override; + void set_monospace_font(Resource *resource, const QString &font_name) override; + void set_font_size(Resource *resource, uint32_t size) override; + void set_icon_theme(Resource *resource, const QString &theme_name) override; + void set_accent_color(Resource *resource, uint32_t r, uint32_t g, uint32_t b) override; + void set_window_opacity(Resource *resource, wl_fixed_t opacity) override; + void set_color_scheme(Resource *resource, uint32_t scheme) override; + void set_titlebar_height(Resource *resource, uint32_t height) override; + void set_corner_radius(Resource *resource, uint32_t radius) override; +}; + +AppearanceManagerInterfaceV1Private::AppearanceManagerInterfaceV1Private(AppearanceManagerInterfaceV1 *_q) + : QtWaylandServer::treeland_appearance_manager_v1() + , q(_q) +{ +} + +void AppearanceManagerInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void AppearanceManagerInterfaceV1Private::set_cursor_theme([[maybe_unused]] Resource *resource, + const QString &name) +{ + ENSURE_CONFIG(); + q->config()->setCursorThemeName(name); +} + +void AppearanceManagerInterfaceV1Private::set_cursor_size([[maybe_unused]] Resource *resource, + uint32_t width, uint32_t height) +{ + ENSURE_CONFIG(); + if (width != height) + qCWarning(lcTlConfig) << "Non-square cursor size requested:" << width << "x" << height + << ", height is ignored."; + q->config()->setCursorSize(static_cast(width)); +} + +void AppearanceManagerInterfaceV1Private::set_font([[maybe_unused]] Resource *resource, + const QString &font_name) +{ + ENSURE_CONFIG(); + q->config()->setFont(font_name); +} + +void AppearanceManagerInterfaceV1Private::set_monospace_font([[maybe_unused]] Resource *resource, + const QString &font_name) +{ + ENSURE_CONFIG(); + q->config()->setMonoFont(font_name); +} + +void AppearanceManagerInterfaceV1Private::set_font_size([[maybe_unused]] Resource *resource, + uint32_t size) +{ + ENSURE_CONFIG(); + q->config()->setFontSize(static_cast(size)); +} + +void AppearanceManagerInterfaceV1Private::set_icon_theme([[maybe_unused]] Resource *resource, + const QString &theme_name) +{ + ENSURE_CONFIG(); + q->config()->setIconThemeName(theme_name); +} + +void AppearanceManagerInterfaceV1Private::set_accent_color([[maybe_unused]] Resource *resource, + uint32_t r, uint32_t g, uint32_t b) +{ + ENSURE_CONFIG(); + q->config()->setActiveColor(rgbToHex(r, g, b)); +} + +void AppearanceManagerInterfaceV1Private::set_window_opacity([[maybe_unused]] Resource *resource, + wl_fixed_t opacity) +{ + ENSURE_CONFIG(); + const double value = wl_fixed_to_double(opacity); + if (value < 0.0 || value > 1.0) { + qCWarning(lcTlConfig) << "window_opacity out of range [0.0, 1.0]:" << value; + return; + } + q->config()->setWindowOpacity(static_cast(std::lround(value * 100.0))); +} + +void AppearanceManagerInterfaceV1Private::set_color_scheme([[maybe_unused]] Resource *resource, + uint32_t scheme) +{ + ENSURE_CONFIG(); + const auto dconfigType = colorSchemeToDConfig(scheme); + if (dconfigType < 0) + return; // invalid scheme, silently ignored per protocol spec + q->config()->setWindowColorScheme(dconfigType); + auto *server = WaylandServer::instance(); + if (server && server->activeSession() && server->activeSession()->config() == q->config()) + WaylandServer::syncPaletteTypeWithWindowColorScheme(dconfigType); +} + +void AppearanceManagerInterfaceV1Private::set_titlebar_height([[maybe_unused]] Resource *resource, + uint32_t height) +{ + ENSURE_CONFIG(); + q->config()->setWindowTitlebarHeight(static_cast(height)); +} + +void AppearanceManagerInterfaceV1Private::set_corner_radius([[maybe_unused]] Resource *resource, + uint32_t radius) +{ + ENSURE_CONFIG(); + q->config()->setWindowRadius(static_cast(radius)); +} + +// --------------------------------------------------------------------------- +// AppearanceManagerInterfaceV1 +// --------------------------------------------------------------------------- + +struct AppearanceManagerInterfaceV1::Private +{ + std::unique_ptr server; +}; + +AppearanceManagerInterfaceV1::AppearanceManagerInterfaceV1(TreelandUserConfig *config, QObject *parent) + : QObject(parent) + , WServerInterface() + , m_config(config) + , d(std::make_unique()) +{ + d->server = std::make_unique(this); +} + +AppearanceManagerInterfaceV1::~AppearanceManagerInterfaceV1() = default; + +QByteArrayView AppearanceManagerInterfaceV1::interfaceName() const +{ + return d->server->interfaceName(); +} + +void AppearanceManagerInterfaceV1::create(WServer *server) +{ + d->server->init(server->handle(), InterfaceVersion); +} + +void AppearanceManagerInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->server->globalRemove(); +} + +wl_global *AppearanceManagerInterfaceV1::global() const +{ + return d->server->global(); +} diff --git a/src/modules/appearance/appearancemanagerinterfacev1.h b/src/modules/appearance/appearancemanagerinterfacev1.h new file mode 100644 index 0000000000..17b7aed305 --- /dev/null +++ b/src/modules/appearance/appearancemanagerinterfacev1.h @@ -0,0 +1,46 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include +#include + +class TreelandUserConfig; + +WAYLIB_SERVER_USE_NAMESPACE + +/** + * @brief Server implementation of treeland_appearance_manager_unstable_v1. + * + * Privileged global that allows the control center / system settings + * to modify user-level appearance settings. Each set_* request applies + * the change immediately to DConfig and broadcasts the new value to all + * clients bound to AppearanceInterfaceV1. + */ +class AppearanceManagerInterfaceV1 : public QObject, public WServerInterface +{ + Q_OBJECT + QML_ANONYMOUS + +public: + explicit AppearanceManagerInterfaceV1(TreelandUserConfig *config, QObject *parent = nullptr); + TreelandUserConfig *config() const { return m_config; } + ~AppearanceManagerInterfaceV1() override; + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + struct Private; + TreelandUserConfig *const m_config; + std::unique_ptr d; +}; diff --git a/src/modules/capture/CMakeLists.txt b/src/modules/capture/CMakeLists.txt new file mode 100644 index 0000000000..69452a862a --- /dev/null +++ b/src/modules/capture/CMakeLists.txt @@ -0,0 +1,78 @@ +set(MODULE_NAME capture) + +find_package(TreelandProtocols REQUIRED) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS QuickPrivate) +endif() + +ws_generate_local(server ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-capture-unstable-v1.xml treeland-capture-unstable-v1-protocol) + +ws_generate( + server + wayland-protocols + staging/color-management/color-management-v1.xml + color-management-v1-protocol +) + +qt_add_library(${MODULE_NAME} SHARED) + +set_target_properties(${MODULE_NAME} PROPERTIES + OUTPUT_NAME "treeland-protocol-capture-v1" + VERSION ${CMAKE_PROJECT_VERSION} + SOVERSION ${PROJECT_VERSION_MAJOR} +) + +qt_add_qml_module(${MODULE_NAME} + URI Treeland.Capture + VERSION 1.0 + NO_PLUGIN + SOURCES + ${CMAKE_SOURCE_DIR}/src/modules/capture/capture.h + ${CMAKE_SOURCE_DIR}/src/modules/capture/capture.cpp + ${CMAKE_SOURCE_DIR}/src/modules/capture/impl/capturev1impl.h + ${CMAKE_SOURCE_DIR}/src/modules/capture/impl/capturev1impl.cpp + ${WAYLAND_PROTOCOLS_OUTPUTDIR}/treeland-capture-unstable-v1-protocol.c + RESOURCE_PREFIX + /qt/qml + OUTPUT_DIRECTORY + ${PROJECT_BINARY_DIR}/qt/qml/Treeland/Capture +) + +target_compile_definitions(${MODULE_NAME} + PRIVATE + WLR_USE_UNSTABLE +) + +target_include_directories(${MODULE_NAME} +PRIVATE + $ + $ +) + +target_link_libraries(${MODULE_NAME} + PRIVATE + Wlroots::wlroots + Waylib::WaylibServer + Qt6::Core + Qt6::Gui + Qt6::Quick + Qt6::QuickPrivate +) + +impl_treeland( + NAME + module_capture + LINK + ${MODULE_NAME} +) + +install(TARGETS ${MODULE_NAME} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + NAMELINK_SKIP +) +if(TREELAND_INSTALL_DEV) + install(TARGETS ${MODULE_NAME} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + NAMELINK_ONLY + ) +endif() diff --git a/src/modules/capture/capture.cpp b/src/modules/capture/capture.cpp new file mode 100644 index 0000000000..cee6da7d4a --- /dev/null +++ b/src/modules/capture/capture.cpp @@ -0,0 +1,1282 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "capture.h" + +#include "modules/capture/impl/capturev1impl.h" +#include "modules/item-selector/itemselector.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" +#include "surface/surfaceproxy.h" +#include "workspace/workspace.h" +#include "common/treelandlogging.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +static inline QRectF scaledRect(const QRectF &rect, qreal devicePixelRatio) +{ + return { rect.x() * devicePixelRatio, + rect.y() * devicePixelRatio, + rect.width() * devicePixelRatio, + rect.height() * devicePixelRatio }; +} + +CaptureSource *CaptureContextV1::source() const +{ + return m_captureSource; +} + +static inline uint32_t captureSourceTypeToProtocol(CaptureSource::CaptureSourceType type) +{ + switch (type) { + case CaptureSource::Output: + return 0x1; + case CaptureSource::Window: + case CaptureSource::Surface: + return 0x2; + case CaptureSource::Region: + return 0x4; + default: + Q_UNREACHABLE_RETURN(0); + } +} + +void CaptureContextV1::setSource(CaptureSource *source, const QRect &captureRegion) +{ + if (m_captureSource == source && m_captureRegion == captureRegion) + return; + if (m_captureSource) { + m_captureSource->disconnect(this); + if (session()) { + m_captureSource->disconnect(session()); + } + } + m_captureSource = source; + m_captureRegion = captureRegion; + connect(m_captureSource, + &CaptureSource::targetDestroyed, + this, + &CaptureContextV1::handleSourceDestroyed); + m_handle->sendSourceReady(this->captureRegion(), + captureSourceTypeToProtocol(source->sourceType())); + Q_EMIT sourceChanged(); +} + +void CaptureContextV1::cancelSelect() +{ + sendSourceFailed(UserCancel); +} + +WSurface *CaptureContextV1::mask() const +{ + return m_handle->mask; +} + +bool CaptureContextV1::freeze() const +{ + return m_handle->freeze; +} + +bool CaptureContextV1::withCursor() const +{ + return m_handle->withCursor; +} + +CaptureSource::CaptureSourceHint CaptureContextV1::sourceHint() const +{ + return { m_handle->sourceHint }; +} + +CaptureContextV1::CaptureContextV1(treeland_capture_context_v1 *h, + WOutputRenderWindow *outputRenderWindow, + QObject *parent) + : QObject(parent) + , m_handle(h) + , m_outputRenderWindow(outputRenderWindow) +{ + connect(h, &treeland_capture_context_v1::selectSource, this, &CaptureContextV1::onSelectSource); + connect(h, &treeland_capture_context_v1::capture, this, &CaptureContextV1::onCapture); + connect(h, &treeland_capture_context_v1::newSession, this, &CaptureContextV1::onCreateSession); +} + +void CaptureContextV1::onSelectSource() +{ + auto context = qobject_cast(sender()); + Q_ASSERT(context); // Sender must be context. + Q_EMIT selectInfoReady(); +} + +void CaptureContextV1::onCapture(treeland_capture_frame_v1 *frame) +{ + if (m_frame) { + wl_client_post_implementation_error(wl_resource_get_client(m_handle->resource), + "Cannot capture frame twice!"); + return; + } + if (!m_captureSource) { + wl_client_post_implementation_error(wl_resource_get_client(m_handle->resource), + "Source is not ready."); + return; + } + m_frame = frame; + auto notifyBuffer = [this] { + m_frame->sendBuffer( + WTools::drmToShmFormat(WTools::toDrmFormat(m_captureSource->image().format())), + source()->cropRect().width(), + source()->cropRect().height(), + source()->cropRect().width() * 4); + m_frame->sendBufferDone(); + connect(m_frame, + &treeland_capture_frame_v1::copy, + this, + &CaptureContextV1::handleFrameCopy, + Qt::UniqueConnection); + connect(m_frame, &treeland_capture_frame_v1::beforeDestroy, this, [this] { + m_frame = nullptr; + }); + }; + if (m_captureSource->imageValid()) { + notifyBuffer(); + } else { + connect(m_captureSource, &CaptureSource::imageReady, this, notifyBuffer); + } + Q_EMIT finishSelect(); +} + +void CaptureContextV1::handleFrameCopy(wlr_buffer *buffer) +{ + if (m_captureSource) { + m_captureSource->copyBuffer(buffer); + m_frame->sendReady(); + } else { + wl_client_post_implementation_error(wl_resource_get_client(m_handle->resource), + "Source is not ready, cannot capture."); + } +} + +void CaptureContextV1::sendSourceFailed(SourceFailure failure) +{ + m_handle->sendSourceFailed(failure); +} + +void CaptureContextV1::onCreateSession(treeland_capture_session_v1 *session) +{ + if (m_session) { + wl_client_post_implementation_error(wl_resource_get_client(m_handle->resource), + "Cannot create session twice!"); + return; + } + if (!m_captureSource) { + wl_client_post_implementation_error(wl_resource_get_client(m_handle->resource), + "Source is not ready."); + return; + } + m_session = session; + connect(m_session, + &treeland_capture_session_v1::start, + this, + &CaptureContextV1::handleSessionStart); + connect(m_session, + &treeland_capture_session_v1::frameDone, + this, + &CaptureContextV1::handleFrameDone); + connect(m_session, &treeland_capture_session_v1::beforeDestroy, this, [this] { + disconnect(outputRenderWindow(), + &WOutputRenderWindow::renderEnd, + this, + &CaptureContextV1::handleRenderEnd); + }); + ensureSourceSessionConnection(); + Q_EMIT finishSelect(); +} + +void CaptureContextV1::ensureSourceSessionConnection() +{ + Q_ASSERT(session() && source()); + connect(source(), + &CaptureSource::bufferDestroyed, + session(), + &treeland_capture_session_v1::sendProduceMoreCancel, + Qt::UniqueConnection); + connect(source(), + &CaptureSource::targetDestroyed, + session(), + &treeland_capture_session_v1::sendSourceDestroyCancel, + Qt::UniqueConnection); + connect(source(), + &CaptureSource::targetResized, + session(), + &treeland_capture_session_v1::sendSourceResizeCancel, + Qt::UniqueConnection); +} + +void CaptureContextV1::handleSourceDestroyed() +{ + sendSourceFailed(SourceDestroyed); +} + +void CaptureContextV1::handleSessionStart() +{ + m_currentFrameData.acked = true; + auto conn = connect(outputRenderWindow(), + &WOutputRenderWindow::renderEnd, + this, + &CaptureContextV1::handleRenderEnd, + Qt::AutoConnection); + if (!conn) { + qCWarning(lcTlCapture) << "Cannot connect to render end of output render window."; + } + if (!outputRenderWindow()->inRendering()) { + QMetaObject::invokeMethod(this, &CaptureContextV1::handleRenderEnd, Qt::AutoConnection); + } +} + +void CaptureContextV1::handleFrameDone(uint32_t tvSecHi, uint32_t tvSecLo, uint32_t tvUsec) +{ + if (m_currentFrameData.readyAt.tvSecHi == tvSecHi + && m_currentFrameData.readyAt.tvSecLo == tvSecLo + && m_currentFrameData.readyAt.tvUsec == tvUsec) { + // Note: dmabuf attributes is exported from output backing buffer, fds will be + // closed as soon as backing buffer is destroyed. We should not close fd here. + m_currentFrameData.acked = true; + } else { + qCWarning(lcTlCapture) + << "Receive a frame done event that is not corresponding to current frame timestamp."; + } +} + +QPointer CaptureContextV1::session() const +{ + return m_session; +} + +QPointer CaptureContextV1::captureSource() const +{ + return m_captureSource; +} + +QPointer CaptureContextV1::outputRenderWindow() const +{ + return m_outputRenderWindow; +} + +void CaptureContextV1::handleRenderEnd() +{ + if (!session() || !m_currentFrameData.acked) + return; + auto source = captureSource(); + Q_ASSERT(source); + auto dmabuf = source->sourceDMABuffer(); + if (!dmabuf) { + qCWarning(lcTlCapture) << "Source has been invalid while connection still exists."; + return; + } + m_currentFrameData = {}; + wlr_buffer_get_dmabuf(dmabuf, &m_currentFrameData.attribs); + + union + { + uint64_t modifier; + + struct + { + uint32_t mod_low; + uint32_t mod_high; + }; + } modifierUnion(m_currentFrameData.attribs.modifier); + + qCInfo(lcTlCapture) << "Session:" << session(); + qCInfo(lcTlCapture) << "Session resource:" << session()->resource; + treeland_capture_session_v1_send_frame(session()->resource, + source->cropRect().x(), + source->cropRect().y(), + m_currentFrameData.attribs.width, + m_currentFrameData.attribs.height, + 0, + 0, + m_currentFrameData.attribs.format, + modifierUnion.mod_high, + modifierUnion.mod_low, + m_currentFrameData.attribs.n_planes); + for (auto i = 0; i < m_currentFrameData.attribs.n_planes; ++i) { + treeland_capture_session_v1_send_object(session()->resource, + i, + m_currentFrameData.attribs.fd[i], + m_currentFrameData.attribs.stride[i] + * m_currentFrameData.attribs.height, + m_currentFrameData.attribs.offset[i], + m_currentFrameData.attribs.stride[i], + i); + } + gettimeofday(&m_currentFrameData.readyAt.tv, nullptr); + treeland_capture_session_v1_send_ready(session()->resource, + m_currentFrameData.readyAt.tvSecHi, + m_currentFrameData.readyAt.tvSecLo, + m_currentFrameData.readyAt.tvUsec); +} + +CaptureManagerV1::CaptureManagerV1(QObject *parent) + : QObject(parent) + , m_manager(nullptr) + , m_captureContextModel(new CaptureContextModel(this)) + , m_contextInSelection(nullptr) +{ +} + +void CaptureManagerV1::setSelector(CaptureSourceSelector *selector) +{ + if (selector == m_selector) + return; + m_selector = selector; + Q_EMIT selectorChanged(); +} + +WOutputRenderWindow *CaptureManagerV1::outputRenderWindow() const +{ + return m_outputRenderWindow; +} + +void CaptureManagerV1::setOutputRenderWindow(WOutputRenderWindow *renderWindow) +{ + if (m_outputRenderWindow == renderWindow) { + return; + } + m_outputRenderWindow = renderWindow; +} + +QByteArrayView CaptureManagerV1::interfaceName() const +{ + return treeland_capture_manager_v1_interface.name; +} + +QPointer CaptureManagerV1::maskShellSurface() const +{ + return m_maskShellSurface; +} + +QPointer CaptureManagerV1::maskSurfaceWrapper() const +{ + return m_maskSurfaceWrapper; +} + +void CaptureManagerV1::create(WServer *server) +{ + m_manager = new treeland_capture_manager_v1(server->handle(), this); + connect(m_manager, + &treeland_capture_manager_v1::newCaptureContext, + this, + [this](treeland_capture_context_v1 *context) { + auto quickContext = new CaptureContextV1(context, outputRenderWindow(), this); + m_captureContextModel->addContext(quickContext); + connect(context, + &treeland_capture_context_v1::beforeDestroy, + quickContext, + [this, quickContext] { + m_captureContextModel->removeContext(quickContext); + handleContextBeforeDestroy(quickContext); + quickContext->deleteLater(); + }); + connect(quickContext, + &CaptureContextV1::selectInfoReady, + this, + &CaptureManagerV1::onCaptureContextSelectSource); + }); +} + +void CaptureManagerV1::destroy([[maybe_unused]] WServer *server) +{ + this->disconnect(); +} + +void CaptureManagerV1::onCaptureContextSelectSource() +{ + CaptureContextV1 *context = qobject_cast(sender()); + Q_ASSERT(context); // Sender must be context. + if (contextInSelection()) { + context->sendSourceFailed(CaptureContextV1::SelectorBusy); + return; + } + m_contextInSelection = context; + if (context->freeze()) { + freezeAllCapturedSurface(true, context->mask()); + } + Q_EMIT contextInSelectionChanged(); +} + +void CaptureManagerV1::clearContextInSelection(CaptureContextV1 *context) +{ + if (m_contextInSelection == context) { + if (m_contextInSelection->freeze()) { + freezeAllCapturedSurface(false, context->mask()); + } + m_contextInSelection = nullptr; + Q_EMIT contextInSelectionChanged(); + } +} + +WSurfaceItem *closestSurfaceItem(QQuickItem *content) +{ + while (content) { + auto item = qobject_cast(content); + if (item) + return item; + content = content->parentItem(); + } + return nullptr; +} + +void CaptureManagerV1::freezeAllCapturedSurface(bool freeze, WSurface *mask) +{ + // Exclude cursor surface item and the mask + Q_ASSERT(m_outputRenderWindow); + const auto isMaskOrSubsurface = [mask](WSurface *surface) { + if (!mask) + return false; + if (surface == mask) + return true; + const auto subsurfaces = mask->subsurfaces(); + return std::any_of(subsurfaces.cbegin(), subsurfaces.cend(), [surface](WSubsurface *subsurface) { + return subsurface->surface() == surface; + }); + }; + + QQueue nodes; + nodes.enqueue(m_outputRenderWindow->contentItem()); + while (!nodes.isEmpty()) { + auto node = nodes.dequeue(); + if (auto content = qobject_cast(node)) { + if (auto cursor = qobject_cast(node->parentItem())) { + if (freeze) + m_frozenCursorPos = cursor->position(); // Just store position for cursor + } else if (!isMaskOrSubsurface(content->surface())) { + content->setLive(!freeze); + } else if (content->surface() == mask) { + auto surfaceItem = closestSurfaceItem(content); + auto parentItem = surfaceItem->parentItem(); + // If parentItem is m_proxySurface (created by SurfaceProxy), skip it. + // The actual surface will be found when we traverse to it later. + // + // Note: Surface capture/record windows should not appear in multitask view, + // but currently we can't filter them at protocol level (e.g., through + // appId or surface type). We need to adjust the protocol so window + // manager can identify them before xdg-toplevel is shown. + if (auto wrapper = qobject_cast(parentItem)) { + if (qobject_cast(wrapper->parent())) { + // This is m_proxySurface, skip it + qCWarning(lcTlCapture) + << "Surface capture/record window found in multitask view," + << "protocol needs adjustment to filter it earlier"; + continue; + } + } + m_maskSurfaceWrapper = qobject_cast(parentItem); + if (m_maskSurfaceWrapper) { + // TODO: Set skipSwitcher, skipDockPreView, skipMutiTaskView here + // after adjusting protocol to identify capture windows early + m_maskSurfaceWrapper->setNoTitleBar(true); + m_maskSurfaceWrapper->setNoCornerRadius(true); + m_maskSurfaceWrapper->setNoDecoration(true); + m_maskSurfaceWrapper->disableWindowAnimation(); + m_maskSurfaceWrapper->setPositionAutomatic(false); + } + m_maskShellSurface = surfaceItem->shellSurface(); + } + } + auto childItems = node->childItems(); + for (const auto &child : std::as_const(childItems)) { + nodes.enqueue(child); + } + } +} + +void CaptureManagerV1::handleContextBeforeDestroy(CaptureContextV1 *context) +{ + clearContextInSelection(context); +} + +CaptureContextModel::CaptureContextModel(QObject *parent) + : QAbstractListModel(parent) +{ +} + +int CaptureContextModel::rowCount([[maybe_unused]] const QModelIndex &parent) const +{ + return m_captureContexts.size(); +} + +QVariant CaptureContextModel::data(const QModelIndex &index, int role) const +{ + if (index.row() < 0 || index.row() >= m_captureContexts.size()) + return {}; + switch (role) { + case ContextRole: + return QVariant::fromValue(m_captureContexts.at(index.row())); + } + return {}; +} + +QHash CaptureContextModel::roleNames() const +{ + return QHash{ { ContextRole, QByteArrayLiteral("context") } }; +} + +void CaptureContextModel::addContext(CaptureContextV1 *context) +{ + beginInsertRows(QModelIndex(), m_captureContexts.size(), m_captureContexts.size() + 1); + m_captureContexts.push_back(context); + endInsertRows(); +} + +void CaptureContextModel::removeContext(CaptureContextV1 *context) +{ + auto index = m_captureContexts.indexOf(context); + beginRemoveRows(QModelIndex(), index, index); + m_captureContexts.remove(index); + endRemoveRows(); +} + +CaptureSourceSelector::CaptureSourceSelector(QQuickItem *parent) + : SurfaceContainer(parent) + , m_internalContentItem(new QQuickItem(this)) + , m_itemSelector(new ItemSelector(m_internalContentItem)) + , m_canvasContainer(new SurfaceContainer(this)) + , m_toolBarModel(new ToolBarModel(this)) +{ + QQuickItemPrivate::get(m_internalContentItem)->anchors()->setFill(this); + m_internalContentItem->setZ(1); + QQuickItemPrivate::get(m_canvasContainer)->anchors()->setFill(this); + m_canvasContainer->setZ(2); + updateCursorShape(); + setAcceptedMouseButtons(Qt::LeftButton); + setActiveFocusOnTab(false); + connect(m_itemSelector, + &ItemSelector::hoveredItemChanged, + this, + &CaptureSourceSelector::hoveredItemChanged, + Qt::UniqueConnection); + connect(m_itemSelector, + &ItemSelector::selectionRegionChanged, + this, + &CaptureSourceSelector::handleItemSelectorSelectionRegionChanged, + Qt::UniqueConnection); + m_itemSelector->addCustomFilter([this](QQuickItem *item, + [[maybe_unused]] ItemSelector::ItemTypes selectionHint) -> bool { + if (auto surfaceItemContent = qobject_cast(item)) { + return surfaceItemContent->surface() != captureManager()->contextInSelection()->mask(); + } else if (auto surfaceItem = qobject_cast(item)) { + // The desktop (icon canvas) is a layer-shell surface: keep it out of + // the selectable capture sources. + auto layerSurface = qobject_cast(surfaceItem->shellSurface()); + if (layerSurface && layerSurface->scope() == SurfaceWrapper::DesktopScope) { + return false; + } + return surfaceItem->surface() != captureManager()->contextInSelection()->mask(); + } else { + return true; + } + }); +} + +CaptureSourceSelector::~CaptureSourceSelector() { } + +void CaptureSourceSelector::doneSelection() +{ + // Selection is done, begin to construct selection source + connect(renderWindow(), + &WOutputRenderWindow::renderEnd, + this, + &CaptureSourceSelector::createImage); + m_internalContentItem->setVisible(false); + // m_canvas may be null when no mask surface exists (e.g. capture via + // xdg-desktop-portal without a mask). Guard against null dereference. + if (m_canvas && m_canvas->surfaceItem()) + m_canvas->surfaceItem()->setSubsurfacesVisible(false); +} + +void CaptureSourceSelector::cancelSelection() +{ + if (captureManager() && captureManager()->contextInSelection()) { + releaseMaskSurface(); + captureManager()->contextInSelection()->sendSourceFailed(CaptureContextV1::UserCancel); + captureManager()->clearContextInSelection(captureManager()->contextInSelection()); + } +} + +void CaptureSourceSelector::updateCursorShape() +{ + if (m_selectionMode == SelectionMode::SelectOutput + || m_selectionMode == SelectionMode::SelectWindow) { + setCursor(Qt::PointingHandCursor); + } else if (m_selectionMode == SelectionMode::SelectRegion) { + setCursor(Qt::CrossCursor); + } else { + setCursor(Qt::ArrowCursor); + } +} + +wl_global *CaptureManagerV1::global() const +{ + return m_manager->global; +} + +QQuickItem *CaptureSourceSelector::hoveredItem() const +{ + return m_itemSelector->hoveredItem(); +} + +bool CaptureSourceSelector::itemSelectionMode() const +{ + return m_itemSelectionMode; +} + +void CaptureSourceSelector::setItemSelectionMode(bool itemSelection) +{ + if (m_itemSelectionMode == itemSelection) + return; + m_itemSelectionMode = itemSelection; + if (m_itemSelectionMode) { + // Let item selector do the job + connect(m_itemSelector, + &ItemSelector::selectionRegionChanged, + this, + &CaptureSourceSelector::handleItemSelectorSelectionRegionChanged, + Qt::UniqueConnection); + } else { + disconnect(m_itemSelector, + &ItemSelector::selectionRegionChanged, + this, + &CaptureSourceSelector::handleItemSelectorSelectionRegionChanged); + } + updateItemSelectorItemTypes(); +} + +void CaptureSourceSelector::updateItemSelectorItemTypes() +{ + if (m_itemSelectionMode) { + m_itemSelector->setSelectionTypeHint(selectionModeToItemTypes(m_selectionMode)); + } else { + // Always item select output in non-item selection mode + m_itemSelector->setSelectionTypeHint(ItemSelector::Output); + } +} + +WOutputRenderWindow *CaptureSourceSelector::renderWindow() const +{ + return qobject_cast(window()); +} + +void CaptureSourceSelector::createImage() +{ + disconnect(renderWindow(), + &WOutputRenderWindow::renderEnd, + this, + &CaptureSourceSelector::createImage); + if (m_selectedSource) { + m_selectedSource->createImage(); + if (m_selectedSource->imageValid()) { + releaseMaskSurface(); + } else { + connect(m_selectedSource, + &CaptureSource::imageReady, + this, + &CaptureSourceSelector::releaseMaskSurface); + } + } else { + releaseMaskSurface(); + } + captureManager()->clearContextInSelection(captureManager()->contextInSelection()); +} + +CaptureManagerV1 *CaptureSourceSelector::captureManager() const +{ + return m_captureManager; +} + +void CaptureSourceSelector::setCaptureManager(CaptureManagerV1 *newCaptureManager) +{ + if (m_captureManager == newCaptureManager) + return; + m_captureManager = newCaptureManager; + if (captureSourceHint().toInt() == 0 || captureSourceHint().testFlag(CaptureSource::Region)) { + // Default case, no hint means all hint internally. + doSetSelectionMode(SelectionMode::SelectRegion); + } else if (captureSourceHint().testAnyFlags( + { CaptureSource::Window | CaptureSource::Surface })) { + doSetSelectionMode(SelectionMode::SelectWindow); + } else { + doSetSelectionMode(SelectionMode::SelectOutput); + } + m_captureManager->setSelector(this); + m_toolBarModel->updateModel(); + Q_ASSERT(captureManager()->contextInSelection()); + connect(captureManager()->contextInSelection(), + &CaptureContextV1::finishSelect, + this, + &CaptureSourceSelector::doneSelection, + Qt::UniqueConnection); + Q_EMIT captureManagerChanged(); +} + +void CaptureSourceSelector::mouseMoveEvent(QMouseEvent *event) +{ + if (m_selectionMode == SelectionMode::SelectRegion) { + auto pos = event->position(); + auto distance = pos - m_selectionAnchor; + if (distance.manhattanLength() > 2) { + setItemSelectionMode(false); + m_doNotFinish = true; + QRectF newRegion; + newRegion.setLeft(qMin(m_selectionAnchor.x(), pos.x())); + newRegion.setRight(qMax(m_selectionAnchor.x(), pos.x())); + newRegion.setTop(qMin(m_selectionAnchor.y(), pos.y())); + newRegion.setBottom(qMax(m_selectionAnchor.y(), pos.y())); + setSelectionRegion(newRegion); + } + } +} + +[[maybe_unused]] static inline WSurfaceItemContent *findItemContent(QQuickItem *item) +{ + QQueue q; + q.enqueue(item); + while (!q.empty()) { + auto node = q.dequeue(); + if (auto content = qobject_cast(node)) + return content; + q.append(node->childItems()); + } + return nullptr; +} + +CaptureSourceSurface::CaptureSourceSurface(WSurfaceItemContent *surfaceItemContent, + qreal devicePixelRatio) + : CaptureSource(surfaceItemContent, devicePixelRatio, nullptr) + , m_surfaceItemContent(surfaceItemContent) +{ +} + +wlr_buffer *CaptureSourceSurface::internalBuffer() +{ + Q_ASSERT(m_sourceList.size() == 1); + if (!m_surfaceItemContent) { + // The captured window was destroyed while the capture session is + // still active; treat the source as invalidated. + qCWarning(lcTlCapture) + << "CaptureSourceSurface: surface item content destroyed while session is active"; + return nullptr; + } + auto *surface = m_surfaceItemContent->surface(); + auto *buffer = surface ? surface->buffer() : nullptr; + if (m_sourceList.first().first && surface && buffer) { + if (auto clientBuffer = wlr_client_buffer_get(buffer)) + return clientBuffer->source; + return buffer; + } + qCWarning(lcTlCapture) + << "CaptureSourceSurface: no usable buffer" + << "(sourceValid=" << bool(m_sourceList.first().first) + << ", surface=" << surface + << ", buffer=" << buffer << ")"; + return nullptr; +} + +CaptureSource::CaptureSourceType CaptureSourceSurface::sourceType() +{ + return CaptureSource::Surface; +} + +QRect CaptureSourceSurface::cropRect() const +{ + return m_surfaceItemContent + ? scaledRect(m_surfaceItemContent->boundingRect(), m_devicePixelRatio).toRect() + : QRect{}; +} + +QSize CaptureSourceSurface::sourceSize() const +{ + return m_surfaceItemContent ? (m_surfaceItemContent->size() * m_devicePixelRatio).toSize() + : QSize{}; +} + +CaptureSource *CaptureSourceSelector::selectedSource() const +{ + return m_selectedSource; +} + +void CaptureSourceSelector::selectSurface(WSurfaceItemContent *surfaceItemContent) +{ + if (!surfaceItemContent) + return; + + const QRect region = surfaceItemContent + ->mapRectToItem(this, surfaceItemContent->boundingRect()) + .toRect(); + setSelectedSource(new CaptureSourceSurface(surfaceItemContent, + surfaceItemContent->devicePixelRatio()), + region); +} + +void CaptureSourceSelector::setSelectedSource(CaptureSource *newSelectedSource, const QRect ®ion) +{ + if (m_selectedSource == newSelectedSource) + return; + qCDebug(lcTlCapture) << "Set selected source to" << newSelectedSource; + m_selectedSource = newSelectedSource; + if (m_selectedSource) { + m_captureManager->contextInSelection()->setSource(m_selectedSource, region); + } + Q_EMIT selectedSourceChanged(); +} + +QDebug operator<<(QDebug debug, CaptureSource &captureSource) +{ + debug << "CaptureSource(" << captureSource.sourceType() << "," << &captureSource << ")"; + return debug; +} + +void CaptureSourceSelector::componentComplete() +{ + // Notify mask size now + if (captureManager()->maskShellSurface() && captureManager()->maskSurfaceWrapper()) { + m_canvas = captureManager()->maskSurfaceWrapper(); + // QPointer only clears when the wrapper QObject is destroyed; the + // wrapper can be invalidated (native surface gone) earlier. Forget it + // at aboutToBeInvalidated so an invalidated canvas is never + // re-enqueued into m_savedContainer by releaseMaskSurface(). + connect(m_canvas, &SurfaceWrapper::aboutToBeInvalidated, this, [this]() { + m_canvas = nullptr; + }); + m_captureManager->maskShellSurface()->resize(size().toSize()); + if (m_captureManager->maskSurfaceWrapper()->container()) { + m_savedContainer = m_captureManager->maskSurfaceWrapper()->container(); + m_captureManager->maskSurfaceWrapper()->container()->removeSurface( + m_captureManager->maskSurfaceWrapper()); + } + m_canvasContainer->addSurface(m_captureManager->maskSurfaceWrapper()); + m_canvas->setX(0); + m_canvas->setY(0); + } + QQuickItem::componentComplete(); +} + +void CaptureSourceSelector::mousePressEvent(QMouseEvent *event) +{ + // Only handle pressed event in SelectRegion selection. + if (selectionMode() == SelectionMode::SelectRegion && event->button() == Qt::LeftButton) { + m_selectionAnchor = event->position(); + } +} + +void CaptureSourceSelector::mouseReleaseEvent([[maybe_unused]] QMouseEvent *event) +{ + switch (selectionMode()) { + case SelectionMode::SelectRegion: { + auto viewport = + m_itemSelector->outputItem()->property("screenViewport").value(); + if (viewport) { + setSelectedSource( + new CaptureSourceRegion(viewport, + mapRectToItem(viewport, selectionRegion()).toRect()), + selectionRegion().toRect()); + } + // Exit item selection mode after first click + setItemSelectionMode(false); + break; + } + case SelectionMode::SelectWindow: { + if (auto surfaceItemContent = qobject_cast(hoveredItem())) { + selectSurface(surfaceItemContent); + } + break; + } + case SelectionMode::SelectOutput: { + if (auto outputItem = qobject_cast(hoveredItem())) { + auto viewport = outputItem->property("screenViewport").value(); + if (viewport) { + setSelectedSource(new CaptureSourceOutput(viewport), selectionRegion().toRect()); + } + } + break; + } + } +} + +QRectF CaptureSourceSelector::selectionRegion() const +{ + return m_selectionRegion; +} + +void CaptureSourceSelector::setSelectionRegion(const QRectF &newSelectionRegion) +{ + if (m_selectionRegion == newSelectionRegion) + return; + m_selectionRegion = newSelectionRegion; + Q_EMIT selectionRegionChanged(); +} + +void CaptureSourceSelector::handleItemSelectorSelectionRegionChanged() +{ + setSelectionRegion(m_itemSelector->selectionRegion()); +} + +bool CaptureSource::imageValid() const +{ + return !m_image.isNull(); +} + +QImage CaptureSource::image() const +{ + return m_image; +} + +void CaptureSource::createImage() +{ + if (m_sourceList.size() == 1 && m_sourceList.first().first) { + auto grabber = new WTextureCapturer(m_sourceList.first().second, this); + grabber->grabToImage() + .then([this](QImage image) { + m_image = std::move(image); + Q_EMIT imageReady(); + }) + .onFailed([](const std::exception &e) { + qCCritical(lcTlCapture) << e.what(); + }); + } else { + // TODO: support multiple sources + } +} + +wlr_buffer *CaptureSource::sourceDMABuffer() +{ + auto buffer = internalBuffer(); + // Re-bind the destroy listener whenever the buffer identity changes; + // a stale binding would stop bufferDestroyed -> sendProduceMoreCancel + // from firing and leave the capture session stuck. + if (buffer != m_sourceBuffer) { + m_bufferDestroyListener.disconnect(); + m_sourceBuffer = nullptr; + if (buffer) { + m_sourceBuffer = buffer; + m_bufferDestroyListener.init(&buffer->events.destroy, [this] { + m_sourceBuffer = nullptr; + m_bufferDestroyListener.disconnect(); + Q_EMIT bufferDestroyed(); + }); + } + } + return buffer; +} + +void CaptureSource::copyBuffer(wlr_buffer *buffer) +{ + Q_ASSERT(imageValid()); + auto width = cropRect().width(); + auto height = cropRect().height(); + uint32_t format; + size_t stride; + void *data; + wlr_buffer_begin_data_ptr_access(buffer, WLR_BUFFER_DATA_PTR_ACCESS_WRITE, &data, &format, &stride); + Q_ASSERT(stride == static_cast(width) * 4); // For QImage + QImage img = image().copy(cropRect()); + auto bufFormat = WTools::toImageFormat(format); + if (image().format() != bufFormat) { + img = image().convertToFormat(bufFormat); + } + memcpy(data, img.constBits(), stride * height); + wlr_buffer_end_data_ptr_access(buffer); +} + +CaptureSourceOutput::CaptureSourceOutput(WOutputViewport *viewport) + : CaptureSource(viewport, viewport->devicePixelRatio(), nullptr) + , m_outputViewport(viewport) +{ +} + +wlr_buffer *CaptureSourceOutput::internalBuffer() +{ + Q_ASSERT(m_sourceList.size() == 1); + if (m_sourceList.first().first && m_outputViewport->wTextureProvider()) + return m_outputViewport->wTextureProvider()->wlrBuffer(); + else + return nullptr; +} + +QRect CaptureSourceOutput::cropRect() const +{ + return m_outputViewport + ? scaledRect(m_outputViewport->boundingRect(), m_outputViewport->devicePixelRatio()) + .toRect() + : QRect{}; +} + +QSize CaptureSourceOutput::sourceSize() const +{ + return m_outputViewport ? (m_outputViewport->size() * m_devicePixelRatio).toSize() : QSize{}; +} + +CaptureSource::CaptureSourceType CaptureSourceOutput::sourceType() +{ + return CaptureSource::Output; +} + +CaptureSourceRegion::CaptureSourceRegion(WOutputViewport *viewport, const QRect ®ion) + : CaptureSource(viewport, viewport->devicePixelRatio(), nullptr) +{ + m_viewportRegions.push_back({ viewport, region }); +} + +wlr_buffer *CaptureSourceRegion::internalBuffer() +{ + if (m_sourceList.size() == 1 && m_sourceList.first().first + && m_sourceList.first().second->wTextureProvider()) { + return m_sourceList.first().second->wTextureProvider()->wlrBuffer(); + } else { + return nullptr; + } +} + +CaptureSource::CaptureSourceType CaptureSourceRegion::sourceType() +{ + return CaptureSource::Region; +} + +QRect CaptureSourceRegion::cropRect() const +{ + QRect result{}; + WOutputViewport *ref = nullptr; + for (const auto &[viewport, region] : std::as_const(m_viewportRegions)) { + if (!viewport) + continue; + if (!ref) { + result = scaledRect(region, viewport->devicePixelRatio()).toRect(); + ref = viewport; + } else { + auto mapped = + scaledRect(ref->mapRectFromItem(viewport, region), viewport->devicePixelRatio()) + .toRect(); // FIXME: firstly map or firstly scale? + result = result.united(mapped); + } + } + return result; +} + +QSize CaptureSourceRegion::sourceSize() const +{ + QRect result{}; + WOutputViewport *ref = nullptr; + for (const auto &[viewport, region] : std::as_const(m_viewportRegions)) { + if (!viewport) + continue; + if (!ref) { + result = scaledRect(viewport->boundingRect(), viewport->devicePixelRatio()).toRect(); + ref = viewport; + } else { + auto mapped = ref->mapRectFromItem( + viewport, + scaledRect(viewport->boundingRect(), viewport->devicePixelRatio())) + .toRect(); // FIXME: firstly map or firstly scale? + result = result.united(mapped); + } + } + return result.size(); +} + +bool CaptureSourceRegion::addViewportRegion(WOutputViewport *viewport, const QRect ®ion) +{ + auto scenePos = viewport->mapToScene({ 0, 0 }); + int insertIndex; + for (insertIndex = 0; insertIndex < m_viewportRegions.size(); ++insertIndex) { + auto &[v, _] = m_viewportRegions[insertIndex]; + auto vScenePos = v->mapToScene({ 0, 0 }); + if (vScenePos.x() > scenePos.x()) { + break; + } + } + m_viewportRegions.insert(insertIndex, { viewport, region }); + return true; +} + +void CaptureSourceSelector::geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry) +{ + if (m_captureManager->maskShellSurface()) { + m_captureManager->maskShellSurface()->resize(newGeometry.size().toSize()); + } + SurfaceContainer::geometryChange(newGeometry, oldGeometry); +} + +CaptureSourceSelector::SelectionMode CaptureSourceSelector::selectionMode() const +{ + return m_selectionMode; +} + +void CaptureSourceSelector::setSelectionMode(const SelectionMode &newSelectionMode) +{ + if (captureSourceHint().toInt() == 0 + || captureSourceHint().testAnyFlags(selectionModeHint(newSelectionMode))) { + doSetSelectionMode(newSelectionMode); + } else { + qCWarning(lcTlCapture) << "Trying to set selection mode not support, discarded."; + } +} + +void CaptureSourceSelector::doSetSelectionMode(const SelectionMode &newSelectionMode) +{ + if (m_selectionMode == newSelectionMode) + return; + m_selectionMode = newSelectionMode; + updateCursorShape(); + setItemSelectionMode(true); + updateItemSelectorItemTypes(); + Q_EMIT selectionModeChanged(); +} + +CaptureSource::CaptureSourceHint CaptureSourceSelector::selectionModeHint( + const SelectionMode &selectionMode) +{ + switch (selectionMode) { + case SelectionMode::SelectOutput: + return CaptureSource::Output; + case SelectionMode::SelectRegion: + return CaptureSource::Region; + case SelectionMode::SelectWindow: + return { CaptureSource::Window | CaptureSource::Surface }; + default: + Q_UNREACHABLE(); + } +} + +ItemSelector::ItemTypes CaptureSourceSelector::selectionModeToItemTypes( + const SelectionMode &selectionMode) const +{ + switch (selectionMode) { + case SelectionMode::SelectOutput: + return ItemSelector::Output; + case SelectionMode::SelectRegion: + return ItemSelector::Output | ItemSelector::Window | ItemSelector::Surface; + case SelectionMode::SelectWindow: + return ItemSelector::Surface; + default: + Q_UNREACHABLE(); + } +} + +QQmlListProperty CaptureSourceSelector::contents() const +{ + return QQuickItemPrivate::get(m_internalContentItem)->data(); +} + +void CaptureSourceSelector::itemChange(ItemChange change, const ItemChangeData &data) +{ + switch (change) { + case QQuickItem::ItemChange::ItemParentHasChanged: + Q_ASSERT_X(parentContainer(), + __func__, + "CaptureSourceSelector must be attached to a SurfaceContainer."); + ensureQmlContext(); + break; + default: + break; + } + + SurfaceContainer::itemChange(change, data); +} + +ToolBarModel::ToolBarModel(CaptureSourceSelector *selector) + : QAbstractListModel(selector) +{ + updateModel(); +} + +void ToolBarModel::updateModel() +{ + beginResetModel(); + m_data.clear(); + auto sourceHint = selector()->captureSourceHint(); + if (sourceHint.testFlag(CaptureSource::Region)) { + m_data.push_back({ "select_region", CaptureSourceSelector::SelectionMode::SelectRegion }); + } + if (sourceHint.testAnyFlags({ CaptureSource::Surface | CaptureSource::Window })) { + m_data.push_back({ "select_window", CaptureSourceSelector::SelectionMode::SelectWindow }); + } + if (sourceHint.testFlag(CaptureSource::Output)) { + m_data.push_back({ "select_output", CaptureSourceSelector::SelectionMode::SelectOutput }); + } + Q_EMIT countChanged(); + endResetModel(); +} + +CaptureSourceSelector *ToolBarModel::selector() const +{ + return static_cast(parent()); +} + +int ToolBarModel::rowCount(const QModelIndex &) const +{ + return m_data.size(); +} + +QVariant ToolBarModel::data(const QModelIndex &index, int role) const +{ + if (index.row() < 0 || index.row() >= rowCount()) + return {}; + switch (role) { + case IconNameRole: + return QVariant::fromValue(m_data[index.row()].first); + case SelectionModeRole: + return QVariant::fromValue(m_data[index.row()].second); + default: + return {}; + } +} + +QHash ToolBarModel::roleNames() const +{ + return { { IconNameRole, "iconName" }, { SelectionModeRole, "selectionMode" } }; +} + +ToolBarModel *CaptureSourceSelector::toolBarModel() const +{ + return m_toolBarModel; +} + +void CaptureSourceSelector::releaseMaskSurface() +{ + // Mask surface should be reparented before destruction. + // If reparent in destructor, it's already marked as deleted in qml + disconnect(m_selectedSource, + &CaptureSource::imageReady, + this, + &CaptureSourceSelector::releaseMaskSurface); + if (m_savedContainer) { + QQueue> q; + q.enqueue(m_canvas); + while (!q.isEmpty()) { + auto node = q.dequeue(); + if (node) { + m_canvasContainer->removeSurface(node); + m_savedContainer->addSurface(node); + for (const auto &child : std::as_const(node->subSurfaces())) { + q.enqueue(child); + } + } + } + } +} diff --git a/src/modules/capture/capture.h b/src/modules/capture/capture.h new file mode 100644 index 0000000000..98ce679896 --- /dev/null +++ b/src/modules/capture/capture.h @@ -0,0 +1,474 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "modules/capture/impl/capturev1impl.h" +#include "modules/item-selector/itemselector.h" +#include "surface/surfacecontainer.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutputRenderWindow; +class WOutputViewport; +class WToplevelSurface; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE +class SurfaceWrapper; +class ItemSelector; + +template +concept IsCaptureSourceTarget = + std::is_base_of_v && std::is_base_of_v; + +class CaptureSource : public QObject +{ + Q_OBJECT +public: + enum CaptureSourceType + { + Output = 0x1, + Window = 0x2, + Region = 0x4, + Surface = 0x8, + }; + Q_FLAG(CaptureSourceType) + Q_DECLARE_FLAGS(CaptureSourceHint, CaptureSourceType) + + template + CaptureSource(T *ptr, qreal devicePixelRatio, QObject *parent) + : QObject(parent) + , m_devicePixelRatio(devicePixelRatio) + { + m_sourceList.push_back( + { { static_cast(ptr) }, static_cast(ptr) }); + connect(m_sourceList.first().first.data(), + &QQuickItem::destroyed, + this, + &CaptureSource::targetDestroyed); + connect(m_sourceList.first().first.data(), + &QQuickItem::widthChanged, + this, + &CaptureSource::targetResized); + connect(m_sourceList.first().first.data(), + &QQuickItem::heightChanged, + this, + &CaptureSource::targetResized); + } + +Q_SIGNALS: + void imageReady(); + void bufferDestroyed(); + void targetDestroyed(); + void targetResized(); + +public: + bool imageValid() const; + + // Get an image that is already cropped. + QImage image() const; + + void createImage(); + + /** + * @brief DMA buffer of source, there are three cases + * 1. output - output's dma buffer + * 2. window - window's dma buffer + * 3. region - output's dma buffer + * + * @return wlr_buffer* + */ + wlr_buffer *sourceDMABuffer(); + + /** + * @brief copyBuffer render captured contents to a buffer + * @param buffer buffer prepared by client + */ + void copyBuffer(wlr_buffer *buffer); + + // Cropped area of source + virtual QRect cropRect() const = 0; + + // Buffer size of the source + virtual QSize sourceSize() const = 0; + + virtual CaptureSourceType sourceType() = 0; + +protected: + virtual wlr_buffer *internalBuffer() = 0; + + template + void addTarget(T *target) + { + m_sourceList.push_back({ { static_cast(target) }, + static_cast(target) }); + connect(m_sourceList.last().first.data(), + &QQuickItem::destroyed, + this, + &CaptureSource::targetDestroyed); + connect(m_sourceList.last().first.data(), + &QQuickItem::widthChanged, + this, + &CaptureSource::targetResized); + connect(m_sourceList.last().first.data(), + &QQuickItem::heightChanged, + this, + &CaptureSource::targetResized); + } + + friend QDebug operator<<(QDebug debug, CaptureSource &captureSource); + QImage m_image; + // Destroy listener for the buffer currently tracked by m_sourceBuffer + // (observer; the buffer itself is owned by the surface). WPointer only + // nulls the handle; this listener emits bufferDestroyed(). + WAYLIB_SERVER_NAMESPACE::WScopedListener m_bufferDestroyListener; + WPointer m_sourceBuffer; + QList, WTextureProviderProvider *>> m_sourceList; + qreal m_devicePixelRatio; +}; + +#define CaptureSource_iid "org.deepin.treeland.CaptureSource" +Q_DECLARE_INTERFACE(CaptureSource, CaptureSource_iid) + +class CaptureContextV1; + +class CaptureContextModel : public QAbstractListModel +{ + Q_OBJECT +public: + CaptureContextModel(QObject *parent = nullptr); + + enum CaptureContextRole + { + ContextRole = Qt::UserRole + 1 + }; + Q_ENUM(CaptureContextRole) + int rowCount(const QModelIndex &parent) const override; + QVariant data(const QModelIndex &index, int role) const override; + QHash roleNames() const override; + void addContext(CaptureContextV1 *context); + void removeContext(CaptureContextV1 *context); + +private: + QList m_captureContexts; +}; + +class CaptureContextV1 : public QObject +{ + Q_OBJECT + Q_PROPERTY(WSurface *mask READ mask NOTIFY selectInfoReady FINAL) + Q_PROPERTY(bool freeze READ freeze NOTIFY selectInfoReady FINAL) + Q_PROPERTY(bool withCursor READ withCursor NOTIFY selectInfoReady FINAL) + Q_PROPERTY(CaptureSource::CaptureSourceHint sourceHint READ sourceHint NOTIFY selectInfoReady FINAL) + +public: + union FrameTime + { + timeval tv; + + struct + { + uint32_t tvSecLo; + uint32_t tvSecHi; + uint32_t tvUsec; + }; + }; + + struct FrameData + { + FrameTime readyAt{}; + wlr_dmabuf_attributes attribs{}; + bool acked{ false }; + bool canceled{ false }; + }; + + CaptureSource *source() const; + void setSource(CaptureSource *source, const QRect &captureRegion); + + void cancelSelect(); + + WSurface *mask() const; + bool freeze() const; + bool withCursor() const; + CaptureSource::CaptureSourceHint sourceHint() const; + QPointer session() const; + QPointer captureSource() const; + QPointer outputRenderWindow() const; + + enum SourceFailure + { + SelectorBusy = 1, + UserCancel, + SourceDestroyed, + Other, + }; + Q_ENUM(SourceFailure) + + CaptureContextV1(treeland_capture_context_v1 *h, + WOutputRenderWindow *outputRenderWindow, + QObject *parent = nullptr); + void sendSourceFailed(SourceFailure failure); + + inline QRect captureRegion() const + { + return m_captureRegion; + } + +Q_SIGNALS: + void sourceChanged(); + void finishSelect(); + void selectInfoReady(); + +private: + void onSelectSource(); + void onCapture(treeland_capture_frame_v1 *frame); + void onCreateSession(treeland_capture_session_v1 *session); + void handleFrameCopy(wlr_buffer *buffer); + void handleSessionStart(); + void handleFrameDone(uint32_t tvSecHi, uint32_t tvSecLo, uint32_t tvUsec); + void handleRenderEnd(); + + void ensureSourceSessionConnection(); + void handleSourceDestroyed(); + + treeland_capture_context_v1 *const m_handle; + CaptureSource *m_captureSource{ nullptr }; + QPointer m_frame{ nullptr }; + QPointer m_session{ nullptr }; + const QPointer m_outputRenderWindow; + FrameData m_currentFrameData{}; + QRect m_captureRegion; +}; +class CaptureSourceSelector; + +class CaptureManagerV1 + : public QObject + , public WServerInterface +{ + Q_OBJECT + Q_PROPERTY(CaptureContextV1 *contextInSelection READ contextInSelection NOTIFY contextInSelectionChanged FINAL) + +public: + explicit CaptureManagerV1(QObject *parent = nullptr); + + CaptureContextModel *contextModel() const + { + return m_captureContextModel; + } + + CaptureContextV1 *contextInSelection() const + { + return m_contextInSelection; + } + + CaptureSourceSelector *selector() const + { + return m_selector; + } + + void setSelector(CaptureSourceSelector *selector); + + WOutputRenderWindow *outputRenderWindow() const; + void setOutputRenderWindow(WOutputRenderWindow *renderWindow); + QByteArrayView interfaceName() const override; + QPointer maskShellSurface() const; + QPointer maskSurfaceWrapper() const; + void clearContextInSelection(CaptureContextV1 *context); +Q_SIGNALS: + void contextInSelectionChanged(); + void newCaptureContext(CaptureContextV1 *context); + void selectorChanged(); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private Q_SLOTS: + void onCaptureContextSelectSource(); + void freezeAllCapturedSurface(bool freeze, WAYLIB_SERVER_NAMESPACE::WSurface *maskItem); + void handleContextBeforeDestroy(CaptureContextV1 *context); + +private: + treeland_capture_manager_v1 *m_manager; + CaptureContextModel *m_captureContextModel; + CaptureContextV1 *m_contextInSelection; + WOutputRenderWindow *m_outputRenderWindow; + QPointF m_frozenCursorPos; + QPointer m_maskShellSurface; + QPointer m_maskSurfaceWrapper; + CaptureSourceSelector *m_selector; +}; + +class CaptureSourceSurface : public CaptureSource +{ + Q_OBJECT +public: + explicit CaptureSourceSurface(WSurfaceItemContent *surfaceItemContent, qreal devicePixelRatio); + wlr_buffer *internalBuffer() override; + CaptureSourceType sourceType() override; + QRect cropRect() const override; + QSize sourceSize() const override; + +private: + const QPointer m_surfaceItemContent; +}; + +class CaptureSourceOutput : public CaptureSource +{ + Q_OBJECT +public: + explicit CaptureSourceOutput(WOutputViewport *viewport); + wlr_buffer *internalBuffer() override; + CaptureSourceType sourceType() override; + QRect cropRect() const override; + QSize sourceSize() const override; + +private: + const QPointer m_outputViewport; +}; + +class CaptureSourceRegion : public CaptureSource +{ + Q_OBJECT +public: + CaptureSourceRegion(WOutputViewport *viewport, const QRect ®ion); + wlr_buffer *internalBuffer() override; + CaptureSourceType sourceType() override; + QRect cropRect() const override; + QSize sourceSize() const override; + bool addViewportRegion(WOutputViewport *viewport, const QRect ®ion); + +private: + QList, QRect>> m_viewportRegions; +}; +class ToolBarModel; + +class CaptureSourceSelector : public SurfaceContainer +{ + Q_OBJECT + Q_PROPERTY(CaptureManagerV1* captureManager READ captureManager WRITE setCaptureManager NOTIFY captureManagerChanged REQUIRED FINAL) + Q_PROPERTY(QRectF selectionRegion READ selectionRegion NOTIFY selectionRegionChanged FINAL) + Q_PROPERTY(SelectionMode selectionMode READ selectionMode WRITE setSelectionMode NOTIFY selectionModeChanged FINAL) + Q_PROPERTY(QQmlListProperty contents READ contents CONSTANT DESIGNABLE false) + Q_PROPERTY(ToolBarModel* toolBarModel READ toolBarModel CONSTANT FINAL) + Q_CLASSINFO("DefaultProperty", "contents") + QML_ELEMENT + +public: + enum class SelectionMode + { + SelectOutput, + SelectWindow, + SelectRegion + }; + Q_ENUM(SelectionMode); + explicit CaptureSourceSelector(QQuickItem *parent = nullptr); + ~CaptureSourceSelector() override; + CaptureManagerV1 *captureManager() const; + void setCaptureManager(CaptureManagerV1 *newCaptureManager); + + SelectionMode selectionMode() const; + void setSelectionMode(const SelectionMode &newSelectionMode); + void doSetSelectionMode(const SelectionMode &newSelectionMode); + static CaptureSource::CaptureSourceHint selectionModeHint(const SelectionMode &selectionMode); + ItemSelector::ItemTypes selectionModeToItemTypes(const SelectionMode &selectionMode) const; + QQmlListProperty contents() const; + + inline CaptureSource::CaptureSourceHint captureSourceHint() const + { + return captureManager() ? captureManager()->contextInSelection()->sourceHint() + : CaptureSource::CaptureSourceHint(); + } + + ToolBarModel *toolBarModel() const; + void doneSelection(); + void cancelSelection(); + void selectSurface(WSurfaceItemContent *surfaceItemContent); + +Q_SIGNALS: + void hoveredItemChanged(); + void selectedSourceChanged(); + void captureManagerChanged(); + void selectionRegionChanged(); + void selectionModeChanged(); + +protected: + void componentComplete() override; + void mouseMoveEvent(QMouseEvent *event) override; + void mousePressEvent(QMouseEvent *event) override; + void mouseReleaseEvent(QMouseEvent *event) override; + void geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry) override; + void itemChange(ItemChange change, const ItemChangeData &data) override; + +private: + QQuickItem *hoveredItem() const; + QRectF selectionRegion() const; + void setSelectionRegion(const QRectF &newSelectionRegion); + bool itemSelectionMode() const; + void setItemSelectionMode(bool itemSelection); + CaptureSource *selectedSource() const; + void setSelectedSource(CaptureSource *newSelectedSource, const QRect ®ion); + void handleItemSelectorSelectionRegionChanged(); + WOutputRenderWindow *renderWindow() const; + void createImage(); + void releaseMaskSurface(); + + void updateItemSelectorItemTypes(); + void updateCursorShape(); + + QPointer m_internalContentItem{}; + QPointer m_itemSelector{}; + QPointer m_canvasContainer{}; + CaptureSource *m_selectedSource{ nullptr }; + QPointer m_captureManager{ nullptr }; + QRectF m_selectionRegion{}; + QPointF m_selectionAnchor{}; + bool m_itemSelectionMode{ true }; + SelectionMode m_selectionMode = SelectionMode::SelectRegion; + bool m_doNotFinish{ false }; + QPointer m_savedContainer{}; + QPointer m_canvas{}; + ToolBarModel *m_toolBarModel{ nullptr }; +}; + +class ToolBarModel : public QAbstractListModel +{ + Q_OBJECT + Q_PROPERTY(uint count READ rowCount NOTIFY countChanged FINAL) +public: + enum ToolBarRole + { + IconNameRole, + SelectionModeRole + }; + Q_ENUM(ToolBarRole) + explicit ToolBarModel(CaptureSourceSelector *selector); + void updateModel(); + CaptureSourceSelector *selector() const; + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + QVariant data(const QModelIndex &index, int role) const override; + QHash roleNames() const override; +Q_SIGNALS: + void countChanged(); + +private: + QList> m_data; +}; diff --git a/src/modules/capture/impl/capturev1impl.cpp b/src/modules/capture/impl/capturev1impl.cpp new file mode 100644 index 0000000000..ed4830d95b --- /dev/null +++ b/src/modules/capture/impl/capturev1impl.cpp @@ -0,0 +1,362 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "capturev1impl.h" + +#include +#include + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +static const struct treeland_capture_session_v1_interface session_impl = { + .destroy = handle_treeland_capture_session_v1_destroy, + .start = handle_treeland_capture_session_v1_start, + .frame_done = handle_treeland_capture_session_v1_frame_done +}; + +static const struct treeland_capture_manager_v1_interface manager_impl = { + .destroy = handle_treeland_capture_manager_v1_destroy, + .get_context = handle_treeland_capture_manager_v1_get_context +}; + +static const struct treeland_capture_context_v1_interface context_impl = { + .destroy = handle_treeland_capture_context_v1_destroy, + .select_source = handle_treeland_capture_context_v1_select_source, + .capture = handle_treeland_capture_context_v1_capture, + .create_session = handle_treeland_capture_context_v1_create_session +}; + +static const struct treeland_capture_frame_v1_interface frame_impl = { + .destroy = handle_treeland_capture_frame_v1_destroy, + .copy = handle_treeland_capture_frame_v1_copy +}; + +void handle_treeland_capture_context_v1_destroy([[maybe_unused]] wl_client *client, + wl_resource *resource) +{ + wl_resource_destroy(resource); +} +struct treeland_capture_context_v1 *capture_context_from_resource(struct wl_resource *resource); + +treeland_capture_manager_v1 *capture_manager_from_resource(wl_resource *resource) +{ + Q_ASSERT( + wl_resource_instance_of(resource, &treeland_capture_manager_v1_interface, &manager_impl)); + return static_cast(wl_resource_get_user_data(resource)); +} + +void handle_treeland_capture_manager_v1_destroy([[maybe_unused]] struct wl_client *client, + struct wl_resource *resource) +{ + auto manager = capture_manager_from_resource(resource); + manager->destroyClientResource(WClient::get(client), resource); +} + +treeland_capture_session_v1 *capture_session_from_resource(wl_resource *resource) +{ + Q_ASSERT( + wl_resource_instance_of(resource, &treeland_capture_session_v1_interface, &session_impl)); + return static_cast(wl_resource_get_user_data(resource)); +} + +treeland_capture_context_v1 *capture_context_from_resource(wl_resource *resource) +{ + Q_ASSERT( + wl_resource_instance_of(resource, &treeland_capture_context_v1_interface, &context_impl)); + return static_cast(wl_resource_get_user_data(resource)); +} + +treeland_capture_frame_v1 *capture_frame_from_resource(wl_resource *resource) +{ + Q_ASSERT(wl_resource_instance_of(resource, &treeland_capture_frame_v1_interface, &frame_impl)); + return static_cast(wl_resource_get_user_data(resource)); +} + +void capture_session_resource_destroy(struct wl_resource *resource) +{ + auto session = capture_session_from_resource(resource); + if (!session) { + return; + } + Q_EMIT session->beforeDestroy(); + // Use deleteLater() instead of delete to avoid re-entrant QObject destruction + // when this callback is triggered from within a WClient::destroyed slot (which + // fires from ~QObject of the WClient). Immediate deletion would free the Qt + // Connection object that doActivate() is currently iterating, causing a UAF + // crash in QBasicAtomicPointer::loadRelaxed (qobject.cpp:4317). + session->resource = nullptr; // resource is being freed; prevent double-destroy + session->deleteLater(); +} + +void capture_context_resource_destroy(struct wl_resource *resource) +{ + struct treeland_capture_context_v1 *context = capture_context_from_resource(resource); + if (!context) { + return; + } + Q_EMIT context->beforeDestroy(); + context->resource = nullptr; + context->deleteLater(); +} + +void capture_frame_resource_destroy(struct wl_resource *resource) +{ + struct treeland_capture_frame_v1 *frame = capture_frame_from_resource(resource); + if (!frame) { + return; + } + Q_EMIT frame->beforeDestroy(); + frame->resource = nullptr; + frame->deleteLater(); +} + +void treeland_capture_manager_bind(wl_client *client, void *data, uint32_t version, uint32_t id) +{ + auto *manager = static_cast(data); + Q_ASSERT(client && manager); + wl_resource *resource = + wl_resource_create(client, &treeland_capture_manager_v1_interface, version, id); + if (!resource) { + wl_client_post_no_memory(client); + return; + } + manager->addClientResource(client, resource); + wl_resource_set_implementation(resource, &manager_impl, manager, nullptr); +} + +treeland_capture_manager_v1::treeland_capture_manager_v1(wl_display *display, QObject *parent) + : QObject(parent) + , global(wl_global_create(display, + &treeland_capture_manager_v1_interface, + 1, + this, + treeland_capture_manager_bind)) +{ +} + +void treeland_capture_manager_v1::addClientResource(wl_client *client, wl_resource *resource) +{ + WClient *wClient = WClient::get(client); + clientResources.push_back({ wClient, resource }); +} + +void treeland_capture_manager_v1::destroyClientResource(WClient *client, wl_resource *resource) +{ + for (const auto &pair : clientResources) { + if (pair.first == client && pair.second == resource) { + wl_resource_destroy(pair.second); + clientResources.removeOne(pair); + } + } +} + +void handle_treeland_capture_session_v1_destroy([[maybe_unused]] wl_client *client, wl_resource *resource) +{ + wl_resource_destroy(resource); +} + +void handle_treeland_capture_session_v1_start([[maybe_unused]] wl_client *client, + wl_resource *resource) +{ + struct treeland_capture_session_v1 *session = capture_session_from_resource(resource); + Q_ASSERT(session); + Q_EMIT session->start(); +} + +void handle_treeland_capture_manager_v1_get_context(wl_client *client, + wl_resource *resource, + uint32_t context) +{ + struct treeland_capture_manager_v1 *manager = capture_manager_from_resource(resource); + Q_ASSERT(manager); + auto *capture_context = new treeland_capture_context_v1; + + int version = wl_resource_get_version(resource); + + struct wl_resource *context_resource = + wl_resource_create(client, &treeland_capture_context_v1_interface, version, context); + + if (!context_resource) { + wl_client_post_no_memory(client); + delete capture_context; + return; + } + wl_resource_set_implementation(context_resource, + &context_impl, + capture_context, + capture_context_resource_destroy); + + capture_context->resource = context_resource; + Q_EMIT manager->newCaptureContext(capture_context); +} + +void handle_treeland_capture_context_v1_create_session(wl_client *client, + wl_resource *resource, + uint32_t session) +{ + struct treeland_capture_context_v1 *context = capture_context_from_resource(resource); + Q_ASSERT(context); + + auto *capture_session = new treeland_capture_session_v1; + + int version = wl_resource_get_version(resource); + + struct wl_resource *capture_session_resource = + wl_resource_create(client, &treeland_capture_session_v1_interface, version, session); + if (!capture_session_resource) { + wl_client_post_no_memory(client); + delete capture_session; + return; + } + capture_session->resource = capture_session_resource; + wl_resource_set_implementation(capture_session_resource, + &session_impl, + capture_session, + capture_session_resource_destroy); + + Q_EMIT context->newSession(capture_session); +} + +void handle_treeland_capture_context_v1_select_source([[maybe_unused]] wl_client *client, + wl_resource *resource, + uint32_t source_hint, + uint32_t freeze, + uint32_t with_cursor, + wl_resource *mask) +{ + struct treeland_capture_context_v1 *context = capture_context_from_resource(resource); + Q_ASSERT(context); + if (source_hint) { + context->sourceHint = source_hint; + } else { + context->sourceHint = 0x7; // Contains all source type + } + context->freeze = freeze; + context->withCursor = with_cursor; + if (mask) { + context->mask = WSurface::fromHandle(wlr_surface_from_resource(mask)); + Q_ASSERT(context->mask); + } + Q_EMIT context->selectSource(); +} + +void handle_treeland_capture_context_v1_capture(wl_client *client, + wl_resource *resource, + uint32_t frame) +{ + treeland_capture_context_v1 *context = capture_context_from_resource(resource); + Q_ASSERT(context); + auto *capture_frame = new treeland_capture_frame_v1; + + int version = wl_resource_get_version(resource); + struct wl_resource *capture_frame_resource = + wl_resource_create(client, &treeland_capture_frame_v1_interface, version, frame); + + if (!capture_frame_resource) { + wl_client_post_no_memory(client); + delete capture_frame; + return; + } + + capture_frame->resource = capture_frame_resource; + + wl_resource_set_implementation(capture_frame_resource, + &frame_impl, + capture_frame, + capture_frame_resource_destroy); + + Q_EMIT context->capture(capture_frame); +} + +void treeland_capture_context_v1::sendSourceFailed(uint32_t reason) +{ + Q_ASSERT(resource); + treeland_capture_context_v1_send_source_failed(resource, reason); +} + +void treeland_capture_context_v1::sendSourceReady(QRect region, uint32_t source_type) +{ + Q_ASSERT(resource); + treeland_capture_context_v1_send_source_ready(resource, + region.x(), + region.y(), + region.width(), + region.height(), + source_type); +} + +void handle_treeland_capture_frame_v1_destroy([[maybe_unused]] wl_client *client, + wl_resource *resource) +{ + wl_resource_destroy(resource); +} + +void handle_treeland_capture_frame_v1_copy(wl_client *client, + wl_resource *resource, + wl_resource *buffer) +{ + treeland_capture_frame_v1 *frame = capture_frame_from_resource(resource); + Q_ASSERT(frame); + wlr_buffer *wlrBuffer = wlr_buffer_try_from_resource(buffer); + if (!wlrBuffer) { + wl_client_post_implementation_error(client, "Buffer not created!"); + return; + } + Q_EMIT frame->copy(wlrBuffer); +} + +void treeland_capture_session_v1::sendProduceMoreCancel() +{ + treeland_capture_session_v1_send_cancel(resource, + TREELAND_CAPTURE_SESSION_V1_CANCEL_REASON_TEMPORARY); +} + +void treeland_capture_session_v1::sendSourceDestroyCancel() +{ + treeland_capture_session_v1_send_cancel(resource, + TREELAND_CAPTURE_SESSION_V1_CANCEL_REASON_PERMANENT); +} + +void treeland_capture_session_v1::sendSourceResizeCancel() +{ + treeland_capture_session_v1_send_cancel(resource, + TREELAND_CAPTURE_SESSION_V1_CANCEL_REASON_RESIZING); +} + +void treeland_capture_frame_v1::sendBuffer(uint32_t format, + uint32_t width, + uint32_t height, + uint32_t stride) +{ + treeland_capture_frame_v1_send_buffer(resource, format, width, height, stride); +} + +void treeland_capture_frame_v1::sendBufferDone() +{ + treeland_capture_frame_v1_send_buffer_done(resource); +} + +void treeland_capture_frame_v1::sendReady() +{ + treeland_capture_frame_v1_send_ready(resource); +} + +void treeland_capture_frame_v1::sendFailed() +{ + treeland_capture_frame_v1_send_failed(resource); +} + +void handle_treeland_capture_session_v1_frame_done(wl_client *, + wl_resource *resource, + uint32_t tv_sec_hi, + uint32_t tv_sec_lo, + uint32_t tv_usec) +{ + auto session = capture_session_from_resource(resource); + Q_ASSERT(session); + Q_EMIT session->frameDone(tv_sec_hi, tv_sec_lo, tv_usec); +} diff --git a/src/modules/capture/impl/capturev1impl.h b/src/modules/capture/impl/capturev1impl.h new file mode 100644 index 0000000000..fa030d458b --- /dev/null +++ b/src/modules/capture/impl/capturev1impl.h @@ -0,0 +1,124 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "treeland-capture-unstable-v1-protocol.h" + +#include +#include + +#include +#include + +Q_MOC_INCLUDE() +WAYLIB_SERVER_BEGIN_NAMESPACE +class WSurface; +class WClient; +WAYLIB_SERVER_END_NAMESPACE + +void handle_treeland_capture_context_v1_destroy([[maybe_unused]] wl_client *client, + wl_resource *resource); + +void handle_treeland_capture_context_v1_capture(wl_client *client, + wl_resource *resource, + uint32_t frame); +void handle_treeland_capture_context_v1_create_session(wl_client *client, + wl_resource *resource, + uint32_t session); +void handle_treeland_capture_context_v1_select_source(wl_client *client, + wl_resource *resource, + uint32_t source_hint, + uint32_t freeze, + uint32_t with_cursor, + wl_resource *mask); + +struct treeland_capture_context_v1 : public QObject +{ + Q_OBJECT +public: + struct wl_resource *resource{ nullptr }; + bool withCursor{ false }; + bool freeze{ false }; + uint32_t sourceHint{ 0 }; + QPointer mask{ nullptr }; + // mask should be created so there must exist a wsurface + + void sendSourceFailed(uint32_t reason); + void sendSourceReady(QRect region, uint32_t source_type); + void setResource(wl_client *client, wl_resource *resource); + +Q_SIGNALS: + void beforeDestroy(); + void newSession(treeland_capture_session_v1 *session); + void selectSource(); + void capture(treeland_capture_frame_v1 *frame); +}; + +void handle_treeland_capture_frame_v1_destroy([[maybe_unused]] wl_client *client, + wl_resource *resource); +void handle_treeland_capture_frame_v1_copy(wl_client *client, + wl_resource *resource, + wl_resource *buffer); + +struct treeland_capture_frame_v1 : public QObject +{ + Q_OBJECT +public: + wl_resource *resource{ nullptr }; + void setResource(wl_client *client, wl_resource *resource); + void sendBuffer(uint32_t format, uint32_t width, uint32_t height, uint32_t stride); + void sendBufferDone(); + void sendReady(); + void sendFailed(); + +Q_SIGNALS: + void copy(wlr_buffer *buffer); + void beforeDestroy(); +}; + +void handle_treeland_capture_session_v1_destroy(struct wl_client *client, + struct wl_resource *resource); +void handle_treeland_capture_session_v1_start([[maybe_unused]] struct wl_client *client, + struct wl_resource *resource); +void handle_treeland_capture_session_v1_frame_done(wl_client *client, + wl_resource *resource, + uint32_t tv_sec_hi, + uint32_t tv_sec_lo, + uint32_t tv_usec); + +struct treeland_capture_session_v1 : public QObject +{ + Q_OBJECT +public: + wl_resource *resource{ nullptr }; + + void setResource(wl_client *client, wl_resource *resource); + void sendProduceMoreCancel(); + void sendSourceDestroyCancel(); + void sendSourceResizeCancel(); + +Q_SIGNALS: + void beforeDestroy(); + void start(); + void frameDone(uint32_t tvSecHi, uint32_t tvSecLo, uint32_t tvUsec); +}; + +void handle_treeland_capture_manager_v1_destroy([[maybe_unused]] wl_client *client, + wl_resource *resource); +void handle_treeland_capture_manager_v1_get_context(wl_client *client, + wl_resource *resource, + uint32_t context); + +struct treeland_capture_manager_v1 : public QObject +{ + Q_OBJECT +public: + wl_global *global; + QList> clientResources; + explicit treeland_capture_manager_v1(wl_display *display, QObject *parent = nullptr); + void addClientResource(wl_client *client, wl_resource *resource); + void destroyClientResource(WAYLIB_SERVER_NAMESPACE::WClient *client, wl_resource *resource); +Q_SIGNALS: + void newCaptureContext(treeland_capture_context_v1 *context); +}; diff --git a/src/modules/compositor-action/CMakeLists.txt b/src/modules/compositor-action/CMakeLists.txt new file mode 100644 index 0000000000..c361850bc0 --- /dev/null +++ b/src/modules/compositor-action/CMakeLists.txt @@ -0,0 +1,28 @@ +find_package(TreelandProtocols 0.7.0 REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-compositor-action-unstable-v1.xml + BASENAME treeland-compositor-action-unstable-v1 +) + +set(PUBLIC_HEADERS + ${CMAKE_SOURCE_DIR}/src/modules/compositor-action/compositoractioninterfacev1.h +) + +set(SRCS + ${CMAKE_SOURCE_DIR}/src/modules/compositor-action/compositoractioninterfacev1.cpp +) + +impl_treeland( + NAME + module_compositor_action + SOURCE + ${PUBLIC_HEADERS} + ${SRCS} + INCLUDE + $ +) + +if(TREELAND_INSTALL_DEV) + install(FILES ${PUBLIC_HEADERS} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/treeland/modules/compositor-action") +endif() diff --git a/src/modules/compositor-action/compositoractioninterfacev1.cpp b/src/modules/compositor-action/compositoractioninterfacev1.cpp new file mode 100644 index 0000000000..dcecfb1aea --- /dev/null +++ b/src/modules/compositor-action/compositoractioninterfacev1.cpp @@ -0,0 +1,150 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "compositoractioninterfacev1.h" + +#include "qwayland-server-treeland-compositor-action-unstable-v1.h" + +#include + +std::optional CompositorActionInterfaceV1::mapCompositorAction(uint32_t protocolAction) +{ + using Action = QtWaylandServer::treeland_compositor_action_v1::action; + + switch (protocolAction) { + case Action::action_workspace_1: + return ShellAction::SwitchWorkspace1; + case Action::action_workspace_2: + return ShellAction::SwitchWorkspace2; + case Action::action_workspace_3: + return ShellAction::SwitchWorkspace3; + case Action::action_workspace_4: + return ShellAction::SwitchWorkspace4; + case Action::action_workspace_5: + return ShellAction::SwitchWorkspace5; + case Action::action_workspace_6: + return ShellAction::SwitchWorkspace6; + case Action::action_workspace_7: + return ShellAction::SwitchWorkspace7; + case Action::action_workspace_8: + return ShellAction::SwitchWorkspace8; + case Action::action_workspace_9: + return ShellAction::SwitchWorkspace9; + case Action::action_workspace_10: + return ShellAction::SwitchWorkspace10; + case Action::action_workspace_11: + return ShellAction::SwitchWorkspace11; + case Action::action_workspace_12: + return ShellAction::SwitchWorkspace12; + case Action::action_prev_workspace: + return ShellAction::PreviousWorkspace; + case Action::action_next_workspace: + return ShellAction::NextWorkspace; + case Action::action_show_desktop: + return ShellAction::ToggleShowDesktop; + case Action::action_open_multitask_view: + return ShellAction::OpenMultitaskView; + case Action::action_close_multitask_view: + return ShellAction::CloseMultitaskView; + case Action::action_toggle_multitask_view: + return ShellAction::ToggleMultitaskView; + case Action::action_toggle_fps_display: + return ShellAction::ToggleFpsDisplay; + case Action::action_zoom_in: + return ShellAction::ZoomIn; + case Action::action_zoom_out: + return ShellAction::ZoomOut; + case Action::action_zoom_reset: + return ShellAction::ZoomReset; + case Action::action_lockscreen: + return ShellAction::LockScreen; + case Action::action_shutdown_menu: + return ShellAction::ShowShutdownMenu; + case Action::action_shutdown_menu_power_off: + return ShellAction::ShowShutdownMenuPowerOff; + case Action::action_shutdown_menu_reboot: + return ShellAction::ShowShutdownMenuReboot; + case Action::action_shutdown_menu_suspend: + return ShellAction::ShowShutdownMenuSuspend; + case Action::action_shutdown_menu_hibernate: + return ShellAction::ShowShutdownMenuHibernate; + case Action::action_shutdown_menu_log_out: + return ShellAction::ShowShutdownMenuLogOut; + case Action::action_show_user_switch: + return ShellAction::ShowUserSwitch; + default: + // Unknown values are ignored per protocol. + return std::nullopt; + } +} + +// --------------------------------------------------------------------------- +// CompositorActionInterfaceV1Private +// --------------------------------------------------------------------------- + +class CompositorActionInterfaceV1Private + : public QtWaylandServer::treeland_compositor_action_v1 +{ +public: + explicit CompositorActionInterfaceV1Private(CompositorActionInterfaceV1 *_q); + ~CompositorActionInterfaceV1Private() override = default; + + wl_global *global() const { return m_global; } + + CompositorActionInterfaceV1 *q = nullptr; + +protected: + void destroy(Resource *resource) override; + void trigger(Resource *resource, uint32_t action) override; +}; + +CompositorActionInterfaceV1Private::CompositorActionInterfaceV1Private(CompositorActionInterfaceV1 *_q) + : QtWaylandServer::treeland_compositor_action_v1() + , q(_q) +{ +} + +void CompositorActionInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void CompositorActionInterfaceV1Private::trigger([[maybe_unused]] Resource *resource, + uint32_t action) +{ + // Fire-and-forget: forward the raw value, no reply is sent. + Q_EMIT q->triggered(action); +} + +// --------------------------------------------------------------------------- +// CompositorActionInterfaceV1 +// --------------------------------------------------------------------------- + +CompositorActionInterfaceV1::CompositorActionInterfaceV1(QObject *parent) + : QObject(parent) + , WServerInterface() + , d(std::make_unique(this)) +{ +} + +CompositorActionInterfaceV1::~CompositorActionInterfaceV1() = default; + +QByteArrayView CompositorActionInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} + +void CompositorActionInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void CompositorActionInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *CompositorActionInterfaceV1::global() const +{ + return d->global(); +} diff --git a/src/modules/compositor-action/compositoractioninterfacev1.h b/src/modules/compositor-action/compositoractioninterfacev1.h new file mode 100644 index 0000000000..2e396ae372 --- /dev/null +++ b/src/modules/compositor-action/compositoractioninterfacev1.h @@ -0,0 +1,54 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "common/shellaction.h" + +#include + +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class CompositorActionInterfaceV1Private; + +/** + * @brief Server implementation of treeland_compositor_action_unstable_v1. + * + * Privileged global that lets a DDE shell client (dock, shutdown applet, + * greeter, ...) trigger window-independent compositor actions one-shot, + * such as workspace switching, show-desktop, the multitask overview, + * lockscreen and the shutdown menu. + */ +class CompositorActionInterfaceV1 : public QObject, public WServerInterface +{ + Q_OBJECT + QML_ANONYMOUS + +public: + explicit CompositorActionInterfaceV1(QObject *parent = nullptr); + ~CompositorActionInterfaceV1() override; + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; + + // Maps a treeland-compositor-action-v1 protocol action value (see the + // action enum of the generated QtWaylandServer type) onto a ShellAction. + [[nodiscard]] static std::optional mapCompositorAction(uint32_t protocolAction); + +Q_SIGNALS: + void triggered(uint32_t action); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; diff --git a/src/modules/dde-shell/CMakeLists.txt b/src/modules/dde-shell/CMakeLists.txt new file mode 100644 index 0000000000..a3c3466669 --- /dev/null +++ b/src/modules/dde-shell/CMakeLists.txt @@ -0,0 +1,29 @@ +find_package(TreelandProtocols REQUIRED) + +# --- Deprecated v1 protocol (kept for transition until dde-shell migrates) --- +# TODO: Remove the v1 protocol and its module sources +# (ddeshellmanagerinterfacev1.*, ddeshellattached.*) in a future release +# once dde-shell has migrated to treeland-dde-shell-unstable-v2. +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-dde-shell-v1.xml + BASENAME treeland-dde-shell-v1 +) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-dde-shell-unstable-v2.xml + BASENAME treeland-dde-shell-unstable-v2 +) + +impl_treeland( + NAME + module_ddeshell + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/dde-shell/ddeshellmanagerinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/dde-shell/ddeshellattached.h + ${CMAKE_SOURCE_DIR}/src/modules/dde-shell/ddeshellmanagerinterfacev1.cpp + ${CMAKE_SOURCE_DIR}/src/modules/dde-shell/ddeshellattached.cpp + ${CMAKE_SOURCE_DIR}/src/modules/dde-shell/ddeshellmanagerinterfacev2.h + ${CMAKE_SOURCE_DIR}/src/modules/dde-shell/ddeshellmanagerinterfacev2.cpp + INCLUDE + $ +) diff --git a/src/modules/dde-shell/ddeshellattached.cpp b/src/modules/dde-shell/ddeshellattached.cpp new file mode 100644 index 0000000000..32fd09faec --- /dev/null +++ b/src/modules/dde-shell/ddeshellattached.cpp @@ -0,0 +1,99 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "ddeshellattached.h" + +// DEPRECATED: The treeland-dde-shell-v1 protocol is deprecated. Use +// treeland-dde-shell-unstable-v2 (ddeshellmanagerinterfacev2.h/.cpp) instead. +// TODO: Remove this module in a future release once dde-shell has migrated +// to v2. + +#include "ddeshellmanagerinterfacev1.h" + +#include + +#include + +DDEShellAttached::DDEShellAttached(QQuickItem *target, QObject *parent) + : QObject(parent) + , m_target(target) +{ +} + +WindowOverlapChecker::WindowOverlapChecker(QQuickItem *target, QObject *parent) + : DDEShellAttached(target, parent) +{ + QTimer *timer = new QTimer(this); + timer->setSingleShot(true); + timer->setInterval(300); + + connect(timer, &QTimer::timeout, this, &WindowOverlapChecker::updateOverlapRegion); + + auto update = [timer] { + if (!timer->isActive()) { + timer->start(); + } + }; + + connect(target, &QQuickItem::xChanged, update); + connect(target, &QQuickItem::yChanged, update); + connect(target, &QQuickItem::heightChanged, update); + connect(target, &QQuickItem::widthChanged, update); + connect(target, &QQuickItem::visibleChanged, update); + connect(target, &QQuickItem::destroyed, this, [this] { + if (s_checkers.removeOne(this)) { + notifyOverlapChange(); + } + }); + + s_checkers.append(this); + timer->start(); +} + +WindowOverlapChecker::~WindowOverlapChecker() +{ + if (s_checkers.removeOne(this)) { + notifyOverlapChange(); + } +} + +void WindowOverlapChecker::updateOverlapRegion() +{ + m_rect = m_target->isVisible() + ? QRectF{ m_target->x(), m_target->y(), m_target->width(), m_target->height() }.toRect() + : QRect(); + + notifyOverlapChange(); +} + +void WindowOverlapChecker::notifyOverlapChange() +{ + QList windowRects; + windowRects.reserve(s_checkers.size()); + for (const WindowOverlapChecker *checker : std::as_const(s_checkers)) { + if (!checker->m_rect.isEmpty()) { + windowRects.append(checker->m_rect); + } + } + + WindowOverlapCheckerInterface::checkRegionalConflict(windowRects); +} + +void WindowOverlapChecker::setOverlapped(bool overlapped) +{ + if (m_overlapped == overlapped) { + return; + } + + m_overlapped = overlapped; + Q_EMIT overlappedChanged(); +} + +DDEShellAttached *DDEShellHelper::qmlAttachedProperties(QObject *target) +{ + if (auto *item = qobject_cast(target)) { + return new WindowOverlapChecker(item); + } + + return nullptr; +} diff --git a/src/modules/dde-shell/ddeshellattached.h b/src/modules/dde-shell/ddeshellattached.h new file mode 100644 index 0000000000..69e2e1e834 --- /dev/null +++ b/src/modules/dde-shell/ddeshellattached.h @@ -0,0 +1,67 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +// DEPRECATED: The treeland-dde-shell-v1 protocol is deprecated. Use +// treeland-dde-shell-unstable-v2 (ddeshellmanagerinterfacev2.h/.cpp) instead. +// TODO: Remove this module in a future release once dde-shell has migrated +// to v2. + +#include + +class DDEShellAttached : public QObject +{ + Q_OBJECT + QML_ANONYMOUS +public: + DDEShellAttached(QQuickItem *target, QObject *parent = nullptr); + +protected: + QQuickItem *m_target; +}; + +class WindowOverlapChecker : public DDEShellAttached +{ + Q_OBJECT + QML_ANONYMOUS + // Deprecated: superseded by the treeland-region-watch-unstable-v1 + // protocol (TreelandRegionWatchManagerInterfaceV1 / RegionWatchV1). + Q_PROPERTY(bool overlapped READ overlapped WRITE setOverlapped NOTIFY overlappedChanged) + +public: + WindowOverlapChecker(QQuickItem *target, QObject *parent = nullptr); + ~WindowOverlapChecker(); + + inline bool overlapped() const + { + return m_overlapped; + } + +Q_SIGNALS: + void overlappedChanged(); + +private: + void setOverlapped(bool overlapped); + void updateOverlapRegion(); + static void notifyOverlapChange(); + + bool m_overlapped{ false }; + QRect m_rect; + + inline static QList s_checkers; +}; + +class DDEShellHelper : public QObject +{ + Q_OBJECT + QML_NAMED_ELEMENT(DDEShell) + QML_UNCREATABLE("Only use for the attached.") + QML_ATTACHED(DDEShellAttached) + +public: + using QObject::QObject; + ~DDEShellHelper() override = default; + + static DDEShellAttached *qmlAttachedProperties(QObject *target); +}; diff --git a/src/modules/dde-shell/ddeshellmanagerinterfacev1.cpp b/src/modules/dde-shell/ddeshellmanagerinterfacev1.cpp new file mode 100644 index 0000000000..6ef539696f --- /dev/null +++ b/src/modules/dde-shell/ddeshellmanagerinterfacev1.cpp @@ -0,0 +1,783 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "ddeshellmanagerinterfacev1.h" + +// DEPRECATED: The treeland-dde-shell-v1 protocol is deprecated. Use +// treeland-dde-shell-unstable-v2 (ddeshellmanagerinterfacev2.h/.cpp) instead. +// TODO: Remove this module in a future release once dde-shell has migrated +// to v2. + +#include "qwayland-server-treeland-dde-shell-v1.h" + +#include "core/waylandserver.h" + +#include + +#include + +#include + +static QList s_shellSurfaces; +static QList s_ddeActives; +static QList s_OverlapCheckers; +static QList s_multiTaskViews; +static QList s_lockScreens; +static QMap s_conflictList; + +class DDEShellManagerInterfaceV1Private : public QtWaylandServer::treeland_dde_shell_manager_v1 +{ +public: + explicit DDEShellManagerInterfaceV1Private(DDEShellManagerInterfaceV1 *_q); + wl_global *global() const; + + DDEShellManagerInterfaceV1 *q; + +protected: + void get_window_overlap_checker(Resource *resource, uint32_t id) override; + void get_shell_surface(Resource *resource, uint32_t id, struct ::wl_resource *surface) override; + void get_treeland_dde_active(Resource *resource, uint32_t id, struct ::wl_resource *seat) override; + void get_treeland_multitaskview(Resource *resource, uint32_t id) override; + void get_treeland_lockscreen(Resource *resource, uint32_t id) override; + void set_xwindow_position_relative(Resource *resource, uint32_t callback, uint32_t wid, + struct ::wl_resource *anchor, wl_fixed_t dx, wl_fixed_t dy) override; +}; + +void DDEShellManagerInterfaceV1Private::get_treeland_lockscreen(Resource *resource, + uint32_t id) +{ + wl_resource *lockscreen_resource = wl_resource_create(resource->client(), + &treeland_lockscreen_v1_interface, + resource->version(), + id); + if (!lockscreen_resource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto lockScreen = new LockScreenInterface(lockscreen_resource); + s_lockScreens.append(lockScreen); + + QObject::connect(lockScreen, &QObject::destroyed, [lockScreen]() { + s_lockScreens.removeOne(lockScreen); + }); + Q_EMIT q->lockScreenCreated(lockScreen); +} + +void DDEShellManagerInterfaceV1Private::set_xwindow_position_relative(Resource *resource, + uint32_t callback, + uint32_t wid, + struct ::wl_resource *anchor, + wl_fixed_t dx, + wl_fixed_t dy) +{ + uint32_t ok = 1; +#ifndef DISABLE_XWAYLAND + WSurface *wsurface = WSurface::fromHandle(wlr_surface_from_resource(anchor)); + ok = (wsurface && WaylandServer::instance()->setXWindowPositionRelative(wid, wsurface, dx, dy)) ? 0 : 1; +#else + Q_UNUSED(wid); + Q_UNUSED(anchor); + Q_UNUSED(dx); + Q_UNUSED(dy); +#endif + wl_resource *cb = wl_resource_create(resource->client(), &wl_callback_interface, 1, callback); + if (!cb) { + wl_client_post_no_memory(resource->client()); + return; + } + wl_callback_send_done(cb, ok); + wl_resource_destroy(cb); +} + +DDEShellManagerInterfaceV1Private::DDEShellManagerInterfaceV1Private(DDEShellManagerInterfaceV1 *_q) + : QtWaylandServer::treeland_dde_shell_manager_v1() + , q(_q) +{ +} + +wl_global *DDEShellManagerInterfaceV1Private::global() const +{ + return m_global; +} + +void DDEShellManagerInterfaceV1Private::get_window_overlap_checker(Resource *resource, + uint32_t id) +{ + // Deprecated: superseded by the treeland-region-watch-unstable-v1 + // protocol. Kept registered in parallel during the transition. + wl_resource *checker_resource = wl_resource_create(resource->client(), + &treeland_window_overlap_checker_interface, + resource->version(), + id); + if (!checker_resource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto overlapChecker = new WindowOverlapCheckerInterface(checker_resource); + s_OverlapCheckers.append(overlapChecker); + + QObject::connect(overlapChecker, &QObject::destroyed, [overlapChecker]() { + s_OverlapCheckers.removeOne(overlapChecker); + }); + + Q_EMIT q->windowOverlapCheckerCreated(overlapChecker); +} + +void DDEShellManagerInterfaceV1Private::get_shell_surface(Resource *resource, + uint32_t id, + wl_resource *surface) +{ + if (!surface) { + wl_resource_post_error(resource->handle, 0, "surface resource is NULL!"); + return; + } + + if (DDEShellSurfaceInterface::get(surface)) { + wl_resource_post_error(resource->handle, 0, "treeland_dde_shell_surface_v1 already exists"); + return; + } + + wl_resource *shell_resource = wl_resource_create(resource->client(), + &treeland_dde_shell_surface_v1_interface, + resource->version(), + id); + if (!shell_resource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto shellSurface = new DDEShellSurfaceInterface(surface, shell_resource); + s_shellSurfaces.append(shellSurface); + + QObject::connect(shellSurface, &QObject::destroyed, [shellSurface]() { + s_shellSurfaces.removeOne(shellSurface); + }); + + Q_EMIT q->surfaceCreated(shellSurface); +} + +void DDEShellManagerInterfaceV1Private::get_treeland_dde_active(Resource *resource, + uint32_t id, + struct ::wl_resource *seat) +{ + if (!seat) { + wl_resource_post_error(resource->handle, 0, "seat resource is NULL!"); + return; + } + + wl_resource *active_resource = wl_resource_create(resource->client(), + &treeland_dde_active_v1_interface, + resource->version(), + id); + + if (!active_resource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto active = new DDEActiveInterface(seat, active_resource); + s_ddeActives.append(active); + + QObject::connect(active, &QObject::destroyed, [active]() { + s_ddeActives.removeOne(active); + }); + + Q_EMIT q->activeCreated(active); +} + +void DDEShellManagerInterfaceV1Private::get_treeland_multitaskview(Resource *resource, + uint32_t id) +{ + wl_resource *multiTaskViewResource = wl_resource_create(resource->client(), + &treeland_multitaskview_v1_interface, + resource->version(), + id); + + if (!multiTaskViewResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto multiTaskView = new MultiTaskViewInterface(multiTaskViewResource); + s_multiTaskViews.append(multiTaskView); + + QObject::connect(multiTaskView, &QObject::destroyed, [multiTaskView]() { + s_multiTaskViews.removeOne(multiTaskView); + }); + QObject::connect(multiTaskView, + &MultiTaskViewInterface::toggle, + q, + &DDEShellManagerInterfaceV1::toggleMultitaskview); + + Q_EMIT q->multiTaskViewsCreated(multiTaskView); +} + +DDEShellManagerInterfaceV1::DDEShellManagerInterfaceV1(QObject *parent) + : QObject(parent) + , d(new DDEShellManagerInterfaceV1Private(this)) +{ +} + +DDEShellManagerInterfaceV1::~DDEShellManagerInterfaceV1() = default; + +void DDEShellManagerInterfaceV1::checkRegionalConflict([[maybe_unused]] const QRegion ®ion) { } + +void DDEShellManagerInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void DDEShellManagerInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *DDEShellManagerInterfaceV1::global() const +{ + return d->global(); +} + +QByteArrayView DDEShellManagerInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} + +class DDEShellSurfaceInterfacePrivate : public QtWaylandServer::treeland_dde_shell_surface_v1 +{ +public: + DDEShellSurfaceInterfacePrivate(DDEShellSurfaceInterface *_q, + wl_resource *surface, + wl_resource *resource); + + DDEShellSurfaceInterface *q; + wl_resource *surfaceResource{ nullptr }; + std::optional surfacePos; + std::optional role; + // if m_yOffset has_value, preventing surface from being displayed beyond + // the edge of the output. + std::optional yOffset; + std::optional skipSwitcher; + std::optional skipDockPreView; + std::optional skipMutiTaskView; + bool acceptKeyboardFocus = true; + +protected: + void destroy_resource([[maybe_unused]] Resource *resource) override; + void destroy([[maybe_unused]] Resource *resource) override; + void set_surface_position([[maybe_unused]] Resource *resource, + int32_t x, + int32_t y) override; + void set_role(Resource *resource, uint32_t value) override; + void set_auto_placement([[maybe_unused]] Resource *resource, + uint32_t y_offset) override; + void set_skip_switcher([[maybe_unused]] Resource *resource, + uint32_t skip) override; + void set_skip_dock_preview([[maybe_unused]] Resource *resource, + uint32_t skip) override; + void set_skip_muti_task_view([[maybe_unused]] Resource *resource, + uint32_t skip) override; + void set_accept_keyboard_focus([[maybe_unused]] Resource *resource, + uint32_t accept) override; +}; + +DDEShellSurfaceInterfacePrivate::DDEShellSurfaceInterfacePrivate(DDEShellSurfaceInterface *_q, + wl_resource *surface, + wl_resource *resource) + : QtWaylandServer::treeland_dde_shell_surface_v1(resource) + , q(_q) + , surfaceResource(surface) +{ +} + +void DDEShellSurfaceInterfacePrivate::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void DDEShellSurfaceInterfacePrivate::destroy([[maybe_unused]] Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void DDEShellSurfaceInterfacePrivate::set_surface_position([[maybe_unused]] Resource *resource, + int32_t x, + int32_t y) +{ + QPoint pos(x, y); + + if (surfacePos == pos) { + return; + } + + surfacePos = pos; + Q_EMIT q->positionChanged(pos); +} + +void DDEShellSurfaceInterfacePrivate::set_role(Resource *resource, + uint32_t value) +{ + DDEShellSurfaceInterface::Role newRole; + switch (value) { + case QtWaylandServer::treeland_dde_shell_surface_v1::role::role_overlay: + newRole = DDEShellSurfaceInterface::OVERLAY; + break; + default: + wl_resource_post_error(resource->handle, + 0, + "Invalid treeland_dde_shell_surface_v1::role: %u", + value); + return; + } + + if (role.has_value() && role.value() == newRole) { + return; + } + + role = newRole; + Q_EMIT q->roleChanged(newRole); +} + +void DDEShellSurfaceInterfacePrivate::set_auto_placement([[maybe_unused]] Resource *resource, + uint32_t y_offset) +{ + if (y_offset == yOffset) { + return; + } + + yOffset = y_offset; + Q_EMIT q->yOffsetChanged(y_offset); +} + +void DDEShellSurfaceInterfacePrivate::set_skip_switcher([[maybe_unused]] Resource *resource, + uint32_t skip) +{ + if (skip == skipSwitcher) { + return; + } + + skipSwitcher = skip; + Q_EMIT q->skipSwitcherChanged(skip); +} + +void DDEShellSurfaceInterfacePrivate::set_skip_dock_preview([[maybe_unused]] Resource *resource, + uint32_t skip) +{ + if (skip == skipDockPreView) { + return; + } + + skipDockPreView = skip; + Q_EMIT q->skipDockPreViewChanged(skip); +} + +void DDEShellSurfaceInterfacePrivate::set_skip_muti_task_view([[maybe_unused]] Resource *resource, + uint32_t skip) +{ + if (skip == skipMutiTaskView) { + return; + } + + skipMutiTaskView = skip; + Q_EMIT q->skipMutiTaskViewChanged(skip); +} + +void DDEShellSurfaceInterfacePrivate::set_accept_keyboard_focus([[maybe_unused]] Resource *resource, + uint32_t accept) +{ + if (accept == acceptKeyboardFocus) { + return; + } + + acceptKeyboardFocus = accept; + Q_EMIT q->acceptKeyboardFocusChanged(accept); +} + +DDEShellSurfaceInterface::DDEShellSurfaceInterface(wl_resource *surface, wl_resource *resource) + : d(new DDEShellSurfaceInterfacePrivate(this, surface, resource)) +{ +} + +DDEShellSurfaceInterface::~DDEShellSurfaceInterface() = default; + +WSurface *DDEShellSurfaceInterface::wSurface() const +{ + return WSurface::fromHandle(wlr_surface_from_resource(d->surfaceResource)); +} + +bool DDEShellSurfaceInterface::ddeShellSurfaceIsMappedToWsurface(const WSurface *surface) +{ + return wSurface() == surface; +} + +std::optional DDEShellSurfaceInterface::surfacePos() const +{ + return d->surfacePos; +} + +std::optional DDEShellSurfaceInterface::role() const +{ + return d->role; +} + +std::optional DDEShellSurfaceInterface::yOffset() const +{ + return d->yOffset; +} + +std::optional DDEShellSurfaceInterface::skipSwitcher() const +{ + return d->skipSwitcher; +} + +std::optional DDEShellSurfaceInterface::skipDockPreView() const +{ + return d->skipDockPreView; +} + +std::optional DDEShellSurfaceInterface::skipMutiTaskView() const +{ + return d->skipMutiTaskView; +} + +bool DDEShellSurfaceInterface::acceptKeyboardFocus() const +{ + return d->acceptKeyboardFocus; +} + +DDEShellSurfaceInterface *DDEShellSurfaceInterface::get(wl_resource *native) +{ + WSurface *surface = WSurface::fromHandle(wlr_surface_from_resource(native)); + if (surface) { + return DDEShellSurfaceInterface::get(surface); + } + + return nullptr; +} + +DDEShellSurfaceInterface *DDEShellSurfaceInterface::get(WSurface *surface) +{ + for (DDEShellSurfaceInterface *shellSurface : std::as_const(s_shellSurfaces)) { + if (shellSurface->wSurface() == surface) { + return shellSurface; + } + } + + return nullptr; +} + +class DDEActiveInterfacePrivate : public QtWaylandServer::treeland_dde_active_v1 +{ +public: + DDEActiveInterfacePrivate(DDEActiveInterface *_q, wl_resource *_seat, wl_resource *resource); + + DDEActiveInterface *q; + wl_resource *seatResouce{ nullptr }; + +protected: + void destroy_resource([[maybe_unused]] Resource *resource) override; + void destroy([[maybe_unused]] Resource *resource) override; +}; + +DDEActiveInterfacePrivate::DDEActiveInterfacePrivate(DDEActiveInterface *_q, + wl_resource *_seat, + wl_resource *resource) + : QtWaylandServer::treeland_dde_active_v1(resource) + , q(_q) + , seatResouce(_seat) +{ +} + +void DDEActiveInterfacePrivate::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void DDEActiveInterfacePrivate::destroy([[maybe_unused]] Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +DDEActiveInterface::DDEActiveInterface(wl_resource *seat, wl_resource *resource) + : d(new DDEActiveInterfacePrivate(this, seat, resource)) +{ +} + +DDEActiveInterface::~DDEActiveInterface() = default; + +WSeat *DDEActiveInterface::seat() const +{ + auto wlrSeat = + static_cast(wl_resource_get_user_data(d->seatResouce))->seat; + return WSeat::fromHandle(wlrSeat); +} + +void DDEActiveInterface::sendActiveIn(uint32_t reason) +{ + d->send_active_in(reason); +} + +void DDEActiveInterface::sendActiveOut(uint32_t reason) +{ + d->send_active_out(reason); +} + +void DDEActiveInterface::sendStartDrag() +{ + d->send_start_drag(); +} + +void DDEActiveInterface::sendDrop() +{ + d->send_drop(); +} + +void DDEActiveInterface::sendActiveIn(uint32_t reason, const WSeat *seat) +{ + for (auto interface : std::as_const(s_ddeActives)) { + if (interface->seat() == seat) { + interface->sendActiveIn(reason); + } + } +} + +void DDEActiveInterface::sendActiveOut(uint32_t reason, const WSeat *seat) +{ + for (auto interface : std::as_const(s_ddeActives)) { + if (interface->seat() == seat) { + interface->sendActiveOut(reason); + } + } +} + +void DDEActiveInterface::sendStartDrag(const WSeat *seat) +{ + for (auto interface : std::as_const(s_ddeActives)) { + if (interface->seat() == seat) { + interface->sendStartDrag(); + } + } +} + +void DDEActiveInterface::sendDrop(const WSeat *seat) +{ + for (auto interface : std::as_const(s_ddeActives)) { + if (interface->seat() == seat) { + interface->sendDrop(); + } + } +} + +class WindowOverlapCheckerInterfacePrivate : public QtWaylandServer::treeland_window_overlap_checker +{ +public: + WindowOverlapCheckerInterfacePrivate(WindowOverlapCheckerInterface *_q, wl_resource *resource); + + WindowOverlapCheckerInterface *q; + + struct wlr_output *output = nullptr; + QSize size; + bool alreadySend{ false }; + bool overlapped{ false }; + +protected: + void destroy_resource([[maybe_unused]] Resource *resource) override; + void update(Resource *resource, + int32_t width, + int32_t height, + uint32_t anchor, + struct ::wl_resource *output) override; + void destroy(Resource *resource) override; +}; + +WindowOverlapCheckerInterface::WindowOverlapCheckerInterface(wl_resource *resource) + : d(new WindowOverlapCheckerInterfacePrivate(this, resource)) +{ +} + +WindowOverlapCheckerInterface::~WindowOverlapCheckerInterface() = default; + +void WindowOverlapCheckerInterface::sendOverlapped(bool overlapped) +{ + if (d->alreadySend && overlapped == d->overlapped) { + d->alreadySend = true; + return; + } + + d->overlapped = overlapped; + d->alreadySend = false; + + if (d->overlapped) { + d->send_enter(); + } else { + d->send_leave(); + } +} + +void WindowOverlapCheckerInterface::checkRegionalConflict(const QList &windowRects) +{ + for (auto &&[interface, checkRect] : s_conflictList.asKeyValueRange()) { + bool overlapped = false; + for (const QRect &rect : windowRects) { + if (rect.intersects(checkRect)) { + overlapped = true; + break; + } + } + interface->sendOverlapped(overlapped); + } +} + +WindowOverlapCheckerInterfacePrivate::WindowOverlapCheckerInterfacePrivate( + WindowOverlapCheckerInterface *_q, + wl_resource *resource) + : QtWaylandServer::treeland_window_overlap_checker(resource) + , q(_q) +{ +} + +void WindowOverlapCheckerInterfacePrivate::destroy_resource([[maybe_unused]] Resource *resource) +{ + s_conflictList.remove(q); + delete q; +} + +void WindowOverlapCheckerInterfacePrivate::update(Resource *resource, + int32_t width, + int32_t height, + uint32_t anchor, + wl_resource *o) +{ + output = wlr_output_from_resource(o); + size = QSize(width, height); + + auto *wOutput = WOutput::fromHandle(output); + QSizeF wSize = wOutput->size() / wOutput->scale(); + QRegion region(0, 0, wOutput->size().width(), wOutput->size().height()); + QRect checkRect; + switch (anchor) { + case WindowOverlapCheckerInterface::Anchor::TOP: + checkRect = QRect(0, 0, wSize.width(), size.height()); + break; + case WindowOverlapCheckerInterface::Anchor::RIGHT: + checkRect = QRect(wSize.width() - size.width(), 0, size.width(), wSize.height()); + break; + case WindowOverlapCheckerInterface::Anchor::BOTTOM: + checkRect = QRect(0, wSize.height() - size.height(), wSize.width(), size.height()); + break; + case WindowOverlapCheckerInterface::Anchor::LEFT: + checkRect = QRect(0, 0, size.width(), wSize.height()); + break; + default: + wl_resource_post_error(resource->handle, + 0, + "Invalid treeland_window_overlap_checker::anchor: %u", + anchor); + return; + } + + s_conflictList.insert(q, checkRect); + Q_EMIT q->refresh(); +} + +void WindowOverlapCheckerInterfacePrivate::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +class MultiTaskViewInterfacePrivate : public QtWaylandServer::treeland_multitaskview_v1 +{ +public: + MultiTaskViewInterfacePrivate(MultiTaskViewInterface *_q, wl_resource *resource); + + MultiTaskViewInterface *q; + +protected: + void destroy_resource([[maybe_unused]] Resource *resource) override; + void destroy([[maybe_unused]] Resource *resource) override; + void toggle([[maybe_unused]] Resource *resource) override; +}; + +MultiTaskViewInterfacePrivate::MultiTaskViewInterfacePrivate(MultiTaskViewInterface *_q, + wl_resource *resource) + : QtWaylandServer::treeland_multitaskview_v1(resource) + , q(_q) +{ +} + +void MultiTaskViewInterfacePrivate::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void MultiTaskViewInterfacePrivate::destroy([[maybe_unused]] Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void MultiTaskViewInterfacePrivate::toggle([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->toggle(); +} + +MultiTaskViewInterface::~MultiTaskViewInterface() { } + +MultiTaskViewInterface::MultiTaskViewInterface(wl_resource *resource) + : d(new MultiTaskViewInterfacePrivate(this, resource)) +{ +} + +class LockScreenInterfacePrivate : public QtWaylandServer::treeland_lockscreen_v1 +{ +public: + LockScreenInterfacePrivate(LockScreenInterface *_q, wl_resource *resource); + + LockScreenInterface *q; + +protected: + void destroy_resource([[maybe_unused]] Resource *resource) override; + void destroy([[maybe_unused]] Resource *resource) override; + void lock([[maybe_unused]] Resource *resource) override; + void shutdown([[maybe_unused]] Resource *resource) override; + void switch_user([[maybe_unused]] Resource *resource) override; +}; + +void LockScreenInterfacePrivate::lock([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->lock(); +} + +void LockScreenInterfacePrivate::shutdown([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->shutdown(); +} + +void LockScreenInterfacePrivate::switch_user([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->switchUser(); +} + +LockScreenInterfacePrivate::LockScreenInterfacePrivate(LockScreenInterface *_q, + wl_resource *resource) + : QtWaylandServer::treeland_lockscreen_v1(resource) + , q(_q) +{ +} + +void LockScreenInterfacePrivate::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void LockScreenInterfacePrivate::destroy([[maybe_unused]] Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +LockScreenInterface::~LockScreenInterface() { } + +LockScreenInterface::LockScreenInterface(wl_resource *resource) + : d(new LockScreenInterfacePrivate(this, resource)) +{ +} diff --git a/src/modules/dde-shell/ddeshellmanagerinterfacev1.h b/src/modules/dde-shell/ddeshellmanagerinterfacev1.h new file mode 100644 index 0000000000..099710fdbd --- /dev/null +++ b/src/modules/dde-shell/ddeshellmanagerinterfacev1.h @@ -0,0 +1,200 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +// DEPRECATED: The treeland-dde-shell-v1 protocol is deprecated. Use +// treeland-dde-shell-unstable-v2 (ddeshellmanagerinterfacev2.h/.cpp) instead. +// TODO: Remove this module in a future release once dde-shell has migrated +// to v2. + +#include +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class DDEShellManagerInterfaceV1Private; +class DDEShellSurfaceInterface; +class DDEActiveInterface; +class WindowOverlapCheckerInterface; +class MultiTaskViewInterface; +class LockScreenInterface; + +class DDEShellManagerInterfaceV1 : public QObject , public WServerInterface +{ + Q_OBJECT +public: + explicit DDEShellManagerInterfaceV1(QObject *parent = nullptr); + ~DDEShellManagerInterfaceV1() override; + + // Deprecated: superseded by TreelandRegionWatchManagerInterfaceV1 + // (treeland-region-watch-unstable-v1). Kept registered in parallel + // during the transition; new code must use the region-watch global. + void checkRegionalConflict(const QRegion ®ion); + + QByteArrayView interfaceName() const override; + static constexpr int InterfaceVersion = 1; +Q_SIGNALS: + void surfaceCreated(DDEShellSurfaceInterface *interface); + void activeCreated(DDEActiveInterface *interface); + // Deprecated: superseded by TreelandRegionWatchManagerInterfaceV1::regionWatchCreated. + void windowOverlapCheckerCreated(WindowOverlapCheckerInterface *interface); + void multiTaskViewsCreated(MultiTaskViewInterface *interface); + void lockScreenCreated(LockScreenInterface *interface); + + void toggleMultitaskview(); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; + +class DDEShellSurfaceInterfacePrivate; +class DDEShellSurfaceInterface : public QObject +{ + Q_OBJECT +public: + enum Role { + OVERLAY, + }; + + ~DDEShellSurfaceInterface() override; + + WSurface *wSurface() const; + bool ddeShellSurfaceIsMappedToWsurface(const WSurface *surface); + std::optional surfacePos() const; + std::optional role() const; + std::optional yOffset() const; + std::optional skipSwitcher() const; + std::optional skipDockPreView() const; + std::optional skipMutiTaskView() const; + bool acceptKeyboardFocus() const; + + static DDEShellSurfaceInterface *get(wl_resource *native); + static DDEShellSurfaceInterface *get(WSurface *surface); + +Q_SIGNALS: + void positionChanged(QPoint pos); + void roleChanged(DDEShellSurfaceInterface::Role role); + void yOffsetChanged(uint32_t offset); + void skipSwitcherChanged(bool skip); + void skipDockPreViewChanged(bool skip); + void skipMutiTaskViewChanged(bool skip); + void acceptKeyboardFocusChanged(bool accept); + +private: + explicit DDEShellSurfaceInterface(wl_resource *surface, wl_resource *resource); + +private: + friend class DDEShellManagerInterfaceV1Private; + std::unique_ptr d; +}; + +class DDEActiveInterfacePrivate; +class DDEActiveInterface : public QObject +{ + Q_OBJECT +public: + enum ActiveReason { + Mouse = 0, + Wheel = 1, + }; + + ~DDEActiveInterface() override; + + WSeat *seat() const; + + void sendActiveIn(uint32_t reason); + void sendActiveOut(uint32_t reason); + void sendStartDrag(); + void sendDrop(); + + static void sendActiveIn(uint32_t reason, const WSeat *seat); + static void sendActiveOut(uint32_t reason, const WSeat *seat); + static void sendStartDrag(const WSeat *seat); + static void sendDrop(const WSeat *seat); + +private: + explicit DDEActiveInterface(wl_resource *seat, wl_resource *resource); + +private: + friend class DDEShellManagerInterfaceV1Private; + std::unique_ptr d; +}; + +// Deprecated: superseded by TreelandRegionWatchManagerInterfaceV1 / RegionWatchV1 +// (treeland-region-watch-unstable-v1). Kept registered in parallel during the +// transition; new code must use the region-watch protocol. +class WindowOverlapCheckerInterfacePrivate; +class WindowOverlapCheckerInterface : public QObject +{ + Q_OBJECT +public: + enum Anchor + { + TOP = 1, + BOTTOM = 2, + LEFT = 4, + RIGHT = 8, + }; + Q_ENUM(Anchor) + + ~WindowOverlapCheckerInterface() override; + void sendOverlapped(bool overlapped); + + static void checkRegionalConflict(const QList &windowRects); + +Q_SIGNALS: + void refresh(); + +private: + explicit WindowOverlapCheckerInterface(wl_resource *resource); + +private: + friend class DDEShellManagerInterfaceV1Private; + std::unique_ptr d; +}; + +class MultiTaskViewInterfacePrivate; +class MultiTaskViewInterface : public QObject +{ + Q_OBJECT +public: + ~MultiTaskViewInterface() override; + +Q_SIGNALS: + void toggle(); + +private: + explicit MultiTaskViewInterface(wl_resource *resource); + +private: + friend class DDEShellManagerInterfaceV1Private; + std::unique_ptr d; +}; + +class LockScreenInterfacePrivate; +class LockScreenInterface : public QObject +{ + Q_OBJECT +public: + ~LockScreenInterface() override; +Q_SIGNALS: + void lock(); + void shutdown(); + void switchUser(); + +private: + explicit LockScreenInterface(wl_resource *resource); + +private: + friend class DDEShellManagerInterfaceV1Private; + std::unique_ptr d; +}; diff --git a/src/modules/dde-shell/ddeshellmanagerinterfacev2.cpp b/src/modules/dde-shell/ddeshellmanagerinterfacev2.cpp new file mode 100644 index 0000000000..db098e054e --- /dev/null +++ b/src/modules/dde-shell/ddeshellmanagerinterfacev2.cpp @@ -0,0 +1,350 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "ddeshellmanagerinterfacev2.h" + +#include "qwayland-server-treeland-dde-shell-unstable-v2.h" + +#include "core/waylandserver.h" +#include "output.h" +#include "rootsurfacecontainer.h" + +#include + +#include + +#include + +#include + +#define MAX_CURSOR_PLACEMENT_OFFSET 10000 + +static QList s_shellSurfacesV2; + +class DDEShellManagerInterfaceV2Private : public QtWaylandServer::treeland_dde_shell_manager_v2 +{ +public: + explicit DDEShellManagerInterfaceV2Private(DDEShellManagerInterfaceV2 *_q); + wl_global *global() const; + + DDEShellManagerInterfaceV2 *q; + +protected: + void destroy(Resource *resource) override; + void get_shell_surface(Resource *resource, uint32_t id, struct ::wl_resource *surface) override; +}; + +DDEShellManagerInterfaceV2Private::DDEShellManagerInterfaceV2Private(DDEShellManagerInterfaceV2 *_q) + : QtWaylandServer::treeland_dde_shell_manager_v2() + , q(_q) +{ +} + +wl_global *DDEShellManagerInterfaceV2Private::global() const +{ + return m_global; +} + +void DDEShellManagerInterfaceV2Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void DDEShellManagerInterfaceV2Private::get_shell_surface(Resource *resource, + uint32_t id, + wl_resource *surface) +{ + if (DDEShellSurfaceV2::getByWlrSurface(wlr_surface_from_resource(surface))) { + ++q->m_alreadyShellSurfaceErrors; + wl_resource_post_error(resource->handle, + error_already_shell_surface, + "the wl_surface already has a shell surface object"); + return; + } + + wl_resource *shell_resource = wl_resource_create(resource->client(), + &treeland_dde_shell_surface_v2_interface, + resource->version(), + id); + if (!shell_resource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto shellSurface = new DDEShellSurfaceV2(surface, shell_resource); + s_shellSurfacesV2.append(shellSurface); + + QObject::connect(shellSurface, &QObject::destroyed, [shellSurface]() { + s_shellSurfacesV2.removeOne(shellSurface); + }); + + if (wl_resource_get_version(shell_resource) >= TREELAND_DDE_SHELL_SURFACE_V2_ROLE_SINCE_VERSION) + treeland_dde_shell_surface_v2_send_role(shell_resource, shellSurface->role()); + + Q_EMIT q->surfaceCreated(shellSurface); +} + +DDEShellManagerInterfaceV2::DDEShellManagerInterfaceV2(QObject *parent) + : QObject(parent) + , d(new DDEShellManagerInterfaceV2Private(this)) +{ +} + +DDEShellManagerInterfaceV2::~DDEShellManagerInterfaceV2() = default; + +int DDEShellManagerInterfaceV2::alreadyShellSurfaceErrorCount() const +{ + return m_alreadyShellSurfaceErrors; +} + +void DDEShellManagerInterfaceV2::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void DDEShellManagerInterfaceV2::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *DDEShellManagerInterfaceV2::global() const +{ + return d->global(); +} + +QByteArrayView DDEShellManagerInterfaceV2::interfaceName() const +{ + return d->interfaceName(); +} + +class DDEShellSurfaceV2Private : public QtWaylandServer::treeland_dde_shell_surface_v2 +{ +public: + DDEShellSurfaceV2Private(DDEShellSurfaceV2 *_q, + wl_resource *surface, + wl_resource *resource); + ~DDEShellSurfaceV2Private() override; + + DDEShellSurfaceV2 *q; + wl_resource *surfaceResource{ nullptr }; + DDEShellSurfaceV2::Role role = DDEShellSurfaceV2::OVERLAY; + // Exactly one of the two placement hints has a value: the most recently + // sent request decides the placement mode. + std::optional positionHint; + std::optional cursorPlacementHint; + uint32_t skipFlags = 0; + bool acceptKeyboardFocus = true; + +protected: + void destroy_resource([[maybe_unused]] Resource *resource) override; + void destroy([[maybe_unused]] Resource *resource) override; + void set_role([[maybe_unused]] Resource *resource, uint32_t value) override; + void set_position_hint([[maybe_unused]] Resource *resource, + struct ::wl_resource *output, + int32_t x, + int32_t y) override; + void set_cursor_placement_hint([[maybe_unused]] Resource *resource, + int32_t x_offset, + int32_t y_offset) override; + void set_skip_flags([[maybe_unused]] Resource *resource, uint32_t flags) override; + void set_accept_keyboard_focus([[maybe_unused]] Resource *resource, uint32_t accept) override; +}; + +DDEShellSurfaceV2Private::DDEShellSurfaceV2Private(DDEShellSurfaceV2 *_q, + wl_resource *surface, + wl_resource *resource) + : QtWaylandServer::treeland_dde_shell_surface_v2(resource) + , q(_q) + , surfaceResource(surface) +{ +} + +DDEShellSurfaceV2Private::~DDEShellSurfaceV2Private() = default; + +void DDEShellSurfaceV2Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void DDEShellSurfaceV2Private::destroy([[maybe_unused]] Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void DDEShellSurfaceV2Private::set_role(Resource *resource, uint32_t value) +{ + if (!treeland_dde_shell_surface_v2_role_is_valid(value, resource->version())) { + wl_resource_post_error(resource->handle, + 0, + "Invalid treeland_dde_shell_surface_v2::role: %u", + value); + return; + } + + q->setRole(static_cast(value)); +} + +void DDEShellSurfaceV2Private::set_position_hint([[maybe_unused]] Resource *resource, + wl_resource *output, + int32_t x, + int32_t y) +{ + QPoint anchor; + if (output) { + auto *wOutput = WOutput::fromHandle(wlr_output_from_resource(output)); + if (!wOutput) { + wl_resource_post_error(resource->handle, 0, "invalid wl_output resource"); + return; + } + anchor = wOutput->position(); + } else { + // A null output anchors the coordinates at the primary output origin. + if (auto *primary = WaylandServer::instance()->rootContainer()->primaryOutput()) + anchor = primary->geometry().topLeft().toPoint(); + } + + const bool modeSwitched = cursorPlacementHint.has_value(); + cursorPlacementHint.reset(); + + const QPoint globalPos = anchor + QPoint(x, y); + if (positionHint == globalPos && !modeSwitched) { + return; + } + + positionHint = globalPos; + Q_EMIT q->positionHintChanged(globalPos); +} + +void DDEShellSurfaceV2Private::set_cursor_placement_hint([[maybe_unused]] Resource *resource, + int32_t x_offset, + int32_t y_offset) +{ + // Reject out-of-range offsets so a bad client request cannot wrap into a + // bogus placement or misplace the surface beyond any screen. Negative + // offsets are valid (e.g. placing the surface above the cursor). + if (x_offset < -MAX_CURSOR_PLACEMENT_OFFSET || x_offset > MAX_CURSOR_PLACEMENT_OFFSET + || y_offset < -MAX_CURSOR_PLACEMENT_OFFSET || y_offset > MAX_CURSOR_PLACEMENT_OFFSET) { + wl_resource_post_error(resource->handle, + 0, + "Invalid cursor placement hint offset: %d,%d", + x_offset, + y_offset); + return; + } + + const bool modeSwitched = positionHint.has_value(); + positionHint.reset(); + + const QPoint offset(x_offset, y_offset); + if (cursorPlacementHint == offset && !modeSwitched) { + return; + } + + cursorPlacementHint = offset; + Q_EMIT q->cursorPlacementHintChanged(offset); +} + +void DDEShellSurfaceV2Private::set_skip_flags([[maybe_unused]] Resource *resource, + uint32_t flags) +{ + if (skipFlags == flags) { + return; + } + + skipFlags = flags; + Q_EMIT q->skipFlagsChanged(flags); +} + +void DDEShellSurfaceV2Private::set_accept_keyboard_focus([[maybe_unused]] Resource *resource, + uint32_t accept) +{ + const bool newAccept = accept != 0; + if (acceptKeyboardFocus == newAccept) { + return; + } + + acceptKeyboardFocus = newAccept; + Q_EMIT q->acceptKeyboardFocusChanged(newAccept); +} + +DDEShellSurfaceV2::DDEShellSurfaceV2(wl_resource *surface, wl_resource *resource) + : d(new DDEShellSurfaceV2Private(this, surface, resource)) +{ +} + +DDEShellSurfaceV2::~DDEShellSurfaceV2() = default; + +WSurface *DDEShellSurfaceV2::wSurface() const +{ + return WSurface::fromHandle(wlr_surface_from_resource(d->surfaceResource)); +} + +DDEShellSurfaceV2::Role DDEShellSurfaceV2::role() const +{ + return d->role; +} + +void DDEShellSurfaceV2::setRole(Role role) +{ + if (d->role == role) + return; + + d->role = role; + Q_EMIT roleChanged(role); + if (d->resource()->version() >= TREELAND_DDE_SHELL_SURFACE_V2_ROLE_SINCE_VERSION) + d->send_role(d->role); +} + +std::optional DDEShellSurfaceV2::positionHint() const +{ + return d->positionHint; +} + +std::optional DDEShellSurfaceV2::cursorPlacementHint() const +{ + return d->cursorPlacementHint; +} + +uint32_t DDEShellSurfaceV2::skipFlags() const +{ + return d->skipFlags; +} + +bool DDEShellSurfaceV2::acceptKeyboardFocus() const +{ + return d->acceptKeyboardFocus; +} + +DDEShellSurfaceV2 *DDEShellSurfaceV2::get(wl_resource *native) +{ + // wlr_surface_from_resource asserts on a null or non-wl_surface resource; + // validate first so callers inspecting another resource get null instead + // of aborting the server. + if (!native || strcmp(wl_resource_get_class(native), wl_surface_interface.name) != 0) + return nullptr; + + WSurface *surface = WSurface::fromHandle(wlr_surface_from_resource(native)); + if (surface) { + return DDEShellSurfaceV2::get(surface); + } + + return nullptr; +} + +DDEShellSurfaceV2 *DDEShellSurfaceV2::get(WSurface *surface) +{ + if (!surface) + return nullptr; + return getByWlrSurface(surface->handle()); +} + +DDEShellSurfaceV2 *DDEShellSurfaceV2::getByWlrSurface(wlr_surface *handle) +{ + for (DDEShellSurfaceV2 *shellSurface : std::as_const(s_shellSurfacesV2)) { + if (wlr_surface_from_resource(shellSurface->d->surfaceResource) == handle) { + return shellSurface; + } + } + + return nullptr; +} diff --git a/src/modules/dde-shell/ddeshellmanagerinterfacev2.h b/src/modules/dde-shell/ddeshellmanagerinterfacev2.h new file mode 100644 index 0000000000..f35d9fd78b --- /dev/null +++ b/src/modules/dde-shell/ddeshellmanagerinterfacev2.h @@ -0,0 +1,105 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include + +#include +#include +#include + +struct wlr_surface; + +WAYLIB_SERVER_USE_NAMESPACE + +class DDEShellManagerInterfaceV2Private; +class DDEShellSurfaceV2; + +class DDEShellManagerInterfaceV2 : public QObject , public WServerInterface +{ + Q_OBJECT +public: + explicit DDEShellManagerInterfaceV2(QObject *parent = nullptr); + ~DDEShellManagerInterfaceV2() override; + + QByteArrayView interfaceName() const override; + static constexpr int InterfaceVersion = 2; + // Number of already_shell_surface protocol errors raised on this global; + // used by the protocol test to assert the duplicate path server-side, + // since the error tears down the client connection before it can read + // the code. + int alreadyShellSurfaceErrorCount() const; +Q_SIGNALS: + void surfaceCreated(DDEShellSurfaceV2 *interface); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + friend class DDEShellManagerInterfaceV2Private; + std::unique_ptr d; + int m_alreadyShellSurfaceErrors = 0; +}; + +class DDEShellSurfaceV2Private; +class DDEShellSurfaceV2 : public QObject +{ + Q_OBJECT +public: + // treeland_dde_shell_surface_v2.role, values match the protocol enum + enum Role { + NORMAL = 0, + OVERLAY = 1, + ALWAYS_ON_TOP = 2, + }; + + // treeland_dde_shell_surface_v2.skip_flag bitfield + enum SkipFlag { + SkipSwitcher = 0x1, + SkipDockPreview = 0x2, + SkipMultitaskView = 0x4, + }; + + ~DDEShellSurfaceV2() override; + + WSurface *wSurface() const; + DDEShellSurfaceV2::Role role() const; + void setRole(Role role); + // Global-space position hint, resolved at request time from the + // output-relative coordinates of set_position_hint. Has a value iff the + // most recent placement hint was set_position_hint. + std::optional positionHint() const; + // (x_offset, y_offset) from the cursor, as sent by + // set_cursor_placement_hint. Has a value iff the most recent placement + // hint was set_cursor_placement_hint. + std::optional cursorPlacementHint() const; + uint32_t skipFlags() const; + bool acceptKeyboardFocus() const; + + static DDEShellSurfaceV2 *get(wl_resource *native); + static DDEShellSurfaceV2 *get(WSurface *surface); + // Uniqueness must be tracked by the native wl_surface (a wl_surface may + // not have a waylib wrapper yet, which would make wSurface() null and + // poison any pointer-based duplicate check). + static DDEShellSurfaceV2 *getByWlrSurface(struct wlr_surface *handle); + +Q_SIGNALS: + void roleChanged(DDEShellSurfaceV2::Role role); + void positionHintChanged(QPoint pos); + void cursorPlacementHintChanged(QPoint offset); + void skipFlagsChanged(quint32 flags); + void acceptKeyboardFocusChanged(bool accept); + +private: + explicit DDEShellSurfaceV2(wl_resource *surface, wl_resource *resource); + +private: + friend class DDEShellManagerInterfaceV2Private; + friend class DDEShellSurfaceV2Private; + std::unique_ptr d; +}; diff --git a/src/modules/ddm/CMakeLists.txt b/src/modules/ddm/CMakeLists.txt new file mode 100644 index 0000000000..64ac819f57 --- /dev/null +++ b/src/modules/ddm/CMakeLists.txt @@ -0,0 +1,16 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-ddm-v1.xml + BASENAME treeland-ddm-v1 +) + +impl_treeland( + NAME + module_ddm + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/ddm/ddminterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/ddm/ddminterfacev1.cpp + INCLUDE + $ +) diff --git a/src/modules/ddm/ddminterfacev1.cpp b/src/modules/ddm/ddminterfacev1.cpp new file mode 100644 index 0000000000..7e2f2f1eef --- /dev/null +++ b/src/modules/ddm/ddminterfacev1.cpp @@ -0,0 +1,118 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "ddminterfacev1.h" +#include "common/treelandlogging.h" +#include "core/waylandserver.h" +#include "usermodel.h" +#include "qwayland-server-treeland-ddm-v1.h" + +#include +#include +#include + +#include + +class DDMInterfaceV1Private : public QtWaylandServer::treeland_ddm_v1 +{ +public: + explicit DDMInterfaceV1Private(DDMInterfaceV1 *_q); + wl_global *global() const; + + DDMInterfaceV1 *q = nullptr; +protected: + void destroy(Resource *resource) override; + void bind_resource(Resource *resource) override; + void switch_to_greeter(Resource *resource) override; + void switch_to_user(Resource *resource, const QString &username) override; + void enable_render(Resource *resource) override; + void disable_render(Resource *resource, uint32_t callback) override; +}; + +DDMInterfaceV1Private::DDMInterfaceV1Private(DDMInterfaceV1 *_q) + : QtWaylandServer::treeland_ddm_v1() + , q(_q) +{ +} + +wl_global *DDMInterfaceV1Private::global() const +{ + return m_global; +} + +void DDMInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void DDMInterfaceV1Private::bind_resource(Resource *resource) +{ + Q_UNUSED(resource) +} + +void DDMInterfaceV1Private::switch_to_greeter([[maybe_unused]] Resource *resource) +{ + qCWarning(lcTlCore) << "DDM protocol: switch_to_greeter"; + WaylandServer::instance()->showLockScreen(false); +} + +void DDMInterfaceV1Private::switch_to_user([[maybe_unused]] Resource *resource, const QString &username) +{ + qCWarning(lcTlCore) << "DDM protocol: switch_to_user" << username; + auto server = WaylandServer::instance(); + if (username == "dde") { + server->showLockScreen(false); + } else if (username != server->userModel()->currentUserName()) { + server->userModel()->setCurrentUserName(username); + server->showLockScreen(false); + } +} + +void DDMInterfaceV1Private::enable_render([[maybe_unused]] Resource *resource) +{ + qCWarning(lcTlCore) << "DDM protocol: enable_render"; + WaylandServer::instance()->enableRender(); +} + +void DDMInterfaceV1Private::disable_render(Resource *resource, uint32_t id) +{ + WaylandServer::instance()->disableRender(); + auto callback = wl_resource_create(resource->client(), &wl_callback_interface, 1, id); + auto serial = wl_display_get_serial(wl_client_get_display(resource->client())); + wl_callback_send_done(callback, serial); + wl_resource_destroy(callback); +} + +DDMInterfaceV1::DDMInterfaceV1(QObject *parent) + : QObject(parent) + , WServerInterface() + , d(new DDMInterfaceV1Private(this)) +{ +} + +DDMInterfaceV1::~DDMInterfaceV1() = default; + +QByteArrayView DDMInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} + +bool DDMInterfaceV1::isConnected() const +{ + return !d->resourceMap().isEmpty(); +} + +void DDMInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void DDMInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *DDMInterfaceV1::global() const +{ + return d->global(); +} diff --git a/src/modules/ddm/ddminterfacev1.h b/src/modules/ddm/ddminterfacev1.h new file mode 100644 index 0000000000..5e0c7200d7 --- /dev/null +++ b/src/modules/ddm/ddminterfacev1.h @@ -0,0 +1,28 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wserver.h" + +WAYLIB_SERVER_USE_NAMESPACE + +class DDMInterfaceV1Private; +class DDMInterfaceV1 : public QObject , public WServerInterface +{ + Q_OBJECT +public: + explicit DDMInterfaceV1(QObject *parent = nullptr); + ~DDMInterfaceV1() override; + + bool isConnected() const; + + QByteArrayView interfaceName() const override; + static constexpr int InterfaceVersion = 1; + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; diff --git a/src/modules/decoration/CMakeLists.txt b/src/modules/decoration/CMakeLists.txt new file mode 100644 index 0000000000..ed9e7f6474 --- /dev/null +++ b/src/modules/decoration/CMakeLists.txt @@ -0,0 +1,29 @@ +find_package(TreelandProtocols 0.6.0 REQUIRED) + +# --- New protocol (treeland-protocols 0.6.0): per-window SSD customization --- +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-decoration-unstable-v1.xml + BASENAME treeland-decoration-unstable-v1 +) + +set(PUBLIC_HEADERS + ${CMAKE_SOURCE_DIR}/src/modules/decoration/decorationmanagerinterfacev1.h +) + +set(SRCS + ${CMAKE_SOURCE_DIR}/src/modules/decoration/decorationmanagerinterfacev1.cpp +) + +impl_treeland( + NAME + module_decoration + SOURCE + ${PUBLIC_HEADERS} + ${SRCS} + INCLUDE + $ +) + +if(TREELAND_INSTALL_DEV) + install(FILES ${PUBLIC_HEADERS} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/treeland/modules/decoration") +endif() diff --git a/src/modules/decoration/decorationmanagerinterfacev1.cpp b/src/modules/decoration/decorationmanagerinterfacev1.cpp new file mode 100644 index 0000000000..8914c93323 --- /dev/null +++ b/src/modules/decoration/decorationmanagerinterfacev1.cpp @@ -0,0 +1,516 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "decorationmanagerinterfacev1.h" + +#include "qwayland-server-treeland-decoration-unstable-v1.h" + +#include "common/treelandlogging.h" +#include "surface/surfacewrapper.h" + +#include +#include + +#include + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +namespace { + +constexpr uint32_t InvalidTitlebarMode = 2; // only 0 (show) and 1 (hide) are valid + +// Upper bound for the per-window radius / width values (corner radius, +// shadow blur radius, border width). Kept coarse for now; may be split into +// per-property limits later if the compositor's clamping policy changes. +constexpr uint32_t MaxDecorationSize = 1000; + +// Color components are defined as [0, 255] by the protocol. +constexpr uint32_t MaxColorComponent = 255; + +} // namespace + +// --------------------------------------------------------------------------- +// DecorationContextV1Private +// --------------------------------------------------------------------------- + +class DecorationContextV1Private : public QtWaylandServer::treeland_decoration_context_v1 +{ +public: + DecorationContextV1Private(DecorationContextV1 *_q, wl_resource *resource, wlr_surface *surface); + ~DecorationContextV1Private() override; + + static void handleSurfaceDestroyed(struct wl_listener *listener, void *data); + + DecorationContextV1 *q = nullptr; + /// The decorated wl_surface (wlr_surface), used for identity matching. + wlr_surface *surface = nullptr; + /// Set when the underlying wl_surface is destroyed; requests are ignored. + bool inert = false; + struct wl_listener surfaceDestroyListener = {}; + + // "set or default" semantics (see protocol spec, "each property is + // opt-in"): std::optional encodes both the value and the "was set" state + // in one place — nullopt = unset, engaged = client override. + std::optional cornerRadius; + std::optional shadow; + std::optional border; + std::optional titlebarMode; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void set_corner_radius(Resource *resource, uint32_t radius) override; + void set_shadow(Resource *resource, + uint32_t radius, + int32_t offset_x, + int32_t offset_y, + uint32_t r, + uint32_t g, + uint32_t b, + uint32_t a) override; + void set_border(Resource *resource, + uint32_t width, + uint32_t r, + uint32_t g, + uint32_t b, + uint32_t a) override; + void set_titlebar_mode(Resource *resource, uint32_t mode) override; +}; + +void DecorationContextV1Private::handleSurfaceDestroyed(struct wl_listener *listener, + [[maybe_unused]] void *data) +{ + DecorationContextV1Private *d = wl_container_of(listener, d, surfaceDestroyListener); + // Detach the listener as soon as the surface resource is torn down: the + // context may outlive that resource. wl_list_remove() on an already + // disconnected (self-referential) link is a no-op, so this is safe even + // when libwayland's final_emit has already unlinked us. + wl_list_remove(&listener->link); + wl_list_init(&listener->link); + d->inert = true; + d->surface = nullptr; +} + +DecorationContextV1Private::DecorationContextV1Private(DecorationContextV1 *_q, + wl_resource *resource, + wlr_surface *_surface) + : QtWaylandServer::treeland_decoration_context_v1(resource) + , q(_q) + , surface(_surface) +{ + // Match wlroots' wl_resource_add_destroy_listener() convention: init the + // link before attaching it, so wl_list_remove() in the destructor is always + // a well-defined no-op even if the listener was never actually linked. + wl_list_init(&surfaceDestroyListener.link); + surfaceDestroyListener.notify = &DecorationContextV1Private::handleSurfaceDestroyed; + wl_resource_add_destroy_listener(_surface->resource, &surfaceDestroyListener); +} + +DecorationContextV1Private::~DecorationContextV1Private() +{ + // Tolerate an already-disconnected listener: if the surface was destroyed + // first, handleSurfaceDestroyed() has already unlinked and re-initialized + // the link, making this wl_list_remove() a harmless no-op. + wl_list_remove(&surfaceDestroyListener.link); + wl_list_init(&surfaceDestroyListener.link); +} + +void DecorationContextV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void DecorationContextV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void DecorationContextV1Private::set_corner_radius([[maybe_unused]] Resource *resource, + uint32_t radius) +{ + if (inert) + return; + if (radius > MaxDecorationSize) { + qCInfo(lcTlProtocol) << "Decoration set_corner_radius ignored: radius" << radius + << "exceeds max" << MaxDecorationSize; + return; + } + cornerRadius = static_cast(radius); + Q_EMIT q->cornerRadiusChanged(); +} + +void DecorationContextV1Private::set_shadow([[maybe_unused]] Resource *resource, + uint32_t radius, + int32_t offset_x, + int32_t offset_y, + uint32_t r, + uint32_t g, + uint32_t b, + uint32_t a) +{ + if (inert) + return; + if (radius > MaxDecorationSize) { + qCInfo(lcTlProtocol) << "Decoration set_shadow ignored: radius" << radius + << "exceeds max" << MaxDecorationSize; + return; + } + if (r > MaxColorComponent || g > MaxColorComponent || b > MaxColorComponent + || a > MaxColorComponent) { + qCInfo(lcTlProtocol) << "Decoration set_shadow ignored: color component out of [0,255]:" + << r << g << b << a; + return; + } + shadow = Shadow{ static_cast(radius), + QPoint{ offset_x, offset_y }, + QColor{ static_cast(r), static_cast(g), static_cast(b), + static_cast(a) } }; + Q_EMIT q->shadowChanged(); +} + +void DecorationContextV1Private::set_border([[maybe_unused]] Resource *resource, + uint32_t width, + uint32_t r, + uint32_t g, + uint32_t b, + uint32_t a) +{ + if (inert) + return; + if (width > MaxDecorationSize) { + qCInfo(lcTlProtocol) << "Decoration set_border ignored: width" << width + << "exceeds max" << MaxDecorationSize; + return; + } + if (r > MaxColorComponent || g > MaxColorComponent || b > MaxColorComponent + || a > MaxColorComponent) { + qCInfo(lcTlProtocol) << "Decoration set_border ignored: color component out of [0,255]:" + << r << g << b << a; + return; + } + border = Border{ static_cast(width), + QColor{ static_cast(r), static_cast(g), static_cast(b), + static_cast(a) } }; + Q_EMIT q->borderChanged(); +} + +void DecorationContextV1Private::set_titlebar_mode([[maybe_unused]] Resource *resource, + uint32_t mode) +{ + if (inert) + return; + // A mode value outside the titlebar_mode enum range is ignored. + if (mode >= InvalidTitlebarMode) { + qCInfo(lcTlProtocol) << "Decoration set_titlebar_mode ignored: invalid mode" << mode; + return; + } + titlebarMode = mode; + Q_EMIT q->titlebarModeChanged(); +} + +// --------------------------------------------------------------------------- +// DecorationContextV1 +// --------------------------------------------------------------------------- + +static QList s_contexts; + +DecorationContextV1::DecorationContextV1(wl_resource *resource, + wlr_surface *surface, + QObject *parent) + : QObject(parent) + , d(std::make_unique(this, resource, surface)) +{ + s_contexts.append(this); +} + +DecorationContextV1::~DecorationContextV1() +{ + s_contexts.removeOne(this); +} + +wl_resource *DecorationContextV1::resource() const +{ + return d->resource()->handle; +} + +wlr_surface *DecorationContextV1::surface() const +{ + return d->surface; +} + +std::optional DecorationContextV1::cornerRadius() const +{ + return d->cornerRadius; +} + +std::optional DecorationContextV1::shadow() const +{ + return d->shadow; +} + +std::optional DecorationContextV1::border() const +{ + return d->border; +} + +std::optional DecorationContextV1::titlebarMode() const +{ + return d->titlebarMode; +} + +DecorationContextV1 *DecorationContextV1::forSurface(wlr_surface *surface) +{ + for (auto *context : std::as_const(s_contexts)) { + if (context->surface() == surface) + return context; + } + return nullptr; +} + +// --------------------------------------------------------------------------- +// DecorationManagerInterfaceV1Private +// --------------------------------------------------------------------------- + +class DecorationManagerInterfaceV1Private + : public QtWaylandServer::treeland_decoration_manager_v1 +{ +public: + explicit DecorationManagerInterfaceV1Private(DecorationManagerInterfaceV1 *_q); + ~DecorationManagerInterfaceV1Private() override = default; + + wl_global *global() const { return m_global; } + + DecorationManagerInterfaceV1 *q = nullptr; + +protected: + void destroy(Resource *resource) override; + void get_decoration_context(Resource *resource, + uint32_t id, + struct ::wl_resource *surface) override; +}; + +DecorationManagerInterfaceV1Private::DecorationManagerInterfaceV1Private( + DecorationManagerInterfaceV1 *_q) + : QtWaylandServer::treeland_decoration_manager_v1() + , q(_q) +{ +} + +void DecorationManagerInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void DecorationManagerInterfaceV1Private::get_decoration_context(Resource *resource, + uint32_t id, + struct ::wl_resource *surface) +{ + // The surface must be owned by the requesting client. + if (wl_resource_get_client(surface) != resource->client()) { + wl_resource_post_error(resource->handle, + TREELAND_DECORATION_MANAGER_V1_ERROR_INVALID_SURFACE, + "surface is not owned by the requesting client!"); + return; + } + + auto *wlrSurface = wlr_surface_from_resource(surface); + + // At most one active decoration context per surface. + if (DecorationContextV1::forSurface(wlrSurface)) { + wl_resource_post_error(resource->handle, + TREELAND_DECORATION_MANAGER_V1_ERROR_ALREADY_USED, + "a decoration context already exists for this surface!"); + return; + } + + wl_resource *contextResource = wl_resource_create(resource->client(), + &treeland_decoration_context_v1_interface, + resource->version(), + id); + if (!contextResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto *context = new DecorationContextV1(contextResource, wlrSurface); + Q_EMIT q->contextCreated(context); +} + +// --------------------------------------------------------------------------- +// DecorationManagerInterfaceV1 +// --------------------------------------------------------------------------- + +struct DecorationManagerInterfaceV1::Private +{ + std::unique_ptr server; +}; + +DecorationManagerInterfaceV1::DecorationManagerInterfaceV1(QObject *parent) + : QObject(parent) + , WServerInterface() + , d(std::make_unique()) +{ + d->server = std::make_unique(this); +} + +DecorationManagerInterfaceV1::~DecorationManagerInterfaceV1() = default; + +QByteArrayView DecorationManagerInterfaceV1::interfaceName() const +{ + return d->server->interfaceName(); +} + +void DecorationManagerInterfaceV1::create(WServer *server) +{ + d->server->init(server->handle(), InterfaceVersion); +} + +void DecorationManagerInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->server->globalRemove(); +} + +wl_global *DecorationManagerInterfaceV1::global() const +{ + return d->server->global(); +} + +// --------------------------------------------------------------------------- +// Decoration (per-window adapter) +// --------------------------------------------------------------------------- + +Decoration::Decoration(WToplevelSurface *target, + DecorationManagerInterfaceV1 *manager, + SurfaceWrapper *parent) + : QObject(parent) + , m_target(target) + , m_manager(manager) +{ + connect(target, &WToplevelSurface::beforeDestroy, this, [this] { + disconnect(m_manager, &DecorationManagerInterfaceV1::contextCreated, this, nullptr); + }); + + auto update = [this](DecorationContextV1 *context) { + applyContext(context); + }; + + connect(m_manager, &DecorationManagerInterfaceV1::contextCreated, this, update); + + if (auto *context = DecorationContextV1::forSurface(target->surface()->handle())) { + applyContext(context); + } +} + +SurfaceWrapper *Decoration::surfaceWrapper() const +{ + return qobject_cast(parent()); +} + +void Decoration::applyContext(DecorationContextV1 *context) +{ + if (!m_target) + return; + if (context->surface() != m_target->surface()->handle()) + return; + auto *wrapper = surfaceWrapper(); + if (!wrapper) + return; + + // Non-toplevel roles (popup / layer shell) have no xdg-decoration + // negotiation of their own: any decoration request opts them into a + // compositor frame, one-way. Callers must not later call + // setNoDecoration(true) on these wrappers (see the popup parent-follow + // ordering in onSurfaceWrapperAdded). + if (wrapper->type() != SurfaceWrapper::Type::XdgToplevel) { + wrapper->setNoDecoration(false); + } + + // Corner radius: a set value (including 0 = square corners) overrides the + // compositor default; an unset value keeps the wrapper default. + if (auto radius = context->cornerRadius()) { + wrapper->setRadius(*radius); + } + connect(context, &DecorationContextV1::cornerRadiusChanged, this, [wrapper, context] { + if (auto radius = context->cornerRadius()) + wrapper->setRadius(*radius); + }); + + // Shadow: radius 0 disables the shadow; the color components are [0,255]. + if (auto shadow = context->shadow()) { + wrapper->setShadowValues(shadow->radius, shadow->offset.x(), shadow->offset.y(), + shadow->color); + wrapper->setShadowVisible(shadow->radius > 0); + } + connect(context, &DecorationContextV1::shadowChanged, this, [wrapper, context] { + const auto shadow = context->shadow(); + if (!shadow) + return; + wrapper->setShadowValues(shadow->radius, shadow->offset.x(), shadow->offset.y(), + shadow->color); + wrapper->setShadowVisible(shadow->radius > 0); + }); + + // Border: width 0 disables the border. + if (auto border = context->border()) { + wrapper->setBorderValues(border->width, border->color); + wrapper->setBorderVisible(border->width > 0); + } + connect(context, &DecorationContextV1::borderChanged, this, [wrapper, context] { + const auto border = context->border(); + if (!border) + return; + wrapper->setBorderValues(border->width, border->color); + wrapper->setBorderVisible(border->width > 0); + }); + + // Titlebar: hide keeps the rest of the SSD (half-CSD half-SSD). + // + // Only toplevels may toggle the titlebar through this protocol. Popups and + // layer shells have no SSD titlebar, so their set_titlebar_mode requests + // are ignored entirely. + if (wrapper->type() == SurfaceWrapper::Type::XdgToplevel) { + // This adapter only records the override and notifies WaylandServer; the actual + // SurfaceWrapper::noTitleBar write is arbitrated in WaylandServer so the frozen + // personalization path and the new protocol can't clobber each other. + if (auto mode = context->titlebarMode()) { + m_titlebarOverridden = true; + m_noTitleBar = *mode == TREELAND_DECORATION_CONTEXT_V1_TITLEBAR_MODE_HIDE; + Q_EMIT titlebarOverrideChanged(); + } + connect(context, &DecorationContextV1::titlebarModeChanged, this, [this, context] { + const auto mode = context->titlebarMode(); + if (!mode) + return; + m_titlebarOverridden = true; + m_noTitleBar = *mode == TREELAND_DECORATION_CONTEXT_V1_TITLEBAR_MODE_HIDE; + Q_EMIT titlebarOverrideChanged(); + }); + } + + // When the context is destroyed the compositor may revert customized + // properties to their defaults (per protocol spec). + connect(context, &QObject::destroyed, this, &Decoration::resetProperties); +} + +void Decoration::resetProperties() +{ + auto *wrapper = surfaceWrapper(); + if (!wrapper) + return; + + // Revert to the compositor defaults (matching SurfaceWrapper's initial + // state and the standard SSD look). + // + // The titlebar mode is intentionally NOT reverted here: the protocol spec + // only says the compositor "may" revert properties on context destroy, + // and blindly restoring the titlebar would clobber the xdg-decoration + // CSD/SSD negotiation state managed by WaylandServer/Personalization. A client + // that wants the default titlebar back sends set_titlebar_mode(show). + wrapper->setRadius(-1); + wrapper->setShadowValues(40, 0, 10, QColor(0, 0, 0, 102)); // blur 40, offset (0,10), rgba(0,0,0,0.4) + wrapper->setShadowVisible(true); + wrapper->setBorderValues(1, QColor(0, 0, 0, 26)); // width 1, rgba(0,0,0,0.1) + wrapper->setBorderVisible(true); +} diff --git a/src/modules/decoration/decorationmanagerinterfacev1.h b/src/modules/decoration/decorationmanagerinterfacev1.h new file mode 100644 index 0000000000..6a9519907f --- /dev/null +++ b/src/modules/decoration/decorationmanagerinterfacev1.h @@ -0,0 +1,149 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "common/windowdecorations.h" + +class SurfaceWrapper; + +WAYLIB_SERVER_USE_NAMESPACE + +class DecorationManagerInterfaceV1; +class DecorationContextV1; + +/** + * @brief Per-window adapter between treeland_decoration_context_v1 and SurfaceWrapper. + * + * Attached to every toplevel SurfaceWrapper in WaylandServer::onSurfaceWrapperAdded. + * When a decoration context for the wrapped surface appears, its corner + * radius / shadow / border / titlebar settings are applied to the wrapper. + * The old personalization module's Personalization class is frozen; new + * protocol support lives here. + */ +class Decoration : public QObject +{ + Q_OBJECT + QML_ANONYMOUS + +public: + Decoration(WToplevelSurface *target, DecorationManagerInterfaceV1 *manager, SurfaceWrapper *parent); + + SurfaceWrapper *surfaceWrapper() const; + + /// Whether a decoration context has overridden the titlebar visibility. + bool hasTitlebarOverride() const { return m_titlebarOverridden; } + /// The titlebar override value: true = hide, false = show. + bool titlebarHidden() const { return m_noTitleBar; } + +Q_SIGNALS: + /// Emitted when the titlebar override changes (or comes into effect). + /// WaylandServer re-arbitrates SurfaceWrapper::noTitleBar on this signal. + void titlebarOverrideChanged(); + +private: + void applyContext(DecorationContextV1 *context); + void resetProperties(); + + QPointer m_target; + DecorationManagerInterfaceV1 *m_manager = nullptr; + bool m_titlebarOverridden = false; + bool m_noTitleBar = false; +}; + +/** + * @brief Server implementation of treeland_decoration_manager_v1. + * + * Global factory that creates per-surface treeland_decoration_context_v1 + * objects. Each context lets the client override the compositor-drawn + * server-side decorations (SSD) of one toplevel surface: corner radius, + * shadow, border and titlebar visibility. + * + * Requests on a context are applied immediately; the compositor may clamp + * out-of-range values to its supported bounds or ignore a set_* request on a + * surface that has not negotiated SSD (per the protocol spec). + */ +class DecorationManagerInterfaceV1 : public QObject, public WServerInterface +{ + Q_OBJECT + QML_ANONYMOUS + +public: + explicit DecorationManagerInterfaceV1(QObject *parent = nullptr); + ~DecorationManagerInterfaceV1() override; + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; + +Q_SIGNALS: + /// A new per-surface decoration context was created. + void contextCreated(DecorationContextV1 *context); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + friend class DecorationManagerInterfaceV1Private; + struct Private; + std::unique_ptr d; +}; + +/** + * @brief Per-surface SSD customization context. + * + * Holds the four per-window override properties (corner radius, shadow, + * border, titlebar mode) with a "set or default" semantics: a property that + * was never set keeps its compositor default, tracked via std::optional + * (nullopt = unset). The context becomes inert when its wl_surface is + * destroyed; requests on an inert context are ignored. + */ +class DecorationContextV1 : public QObject +{ + Q_OBJECT + QML_ANONYMOUS + +public: + DecorationContextV1(wl_resource *resource, wlr_surface *surface, QObject *parent = nullptr); + ~DecorationContextV1() override; + + wl_resource *resource() const; + wlr_surface *surface() const; + + // std::optional encodes the "set or default" semantics: nullopt means the + // client never sent the request (compositor default applies), an engaged + // value (including 0 / radius 0) means an explicit client override. + std::optional cornerRadius() const; + std::optional shadow() const; + std::optional border() const; + std::optional titlebarMode() const; + + /// Find the live context for @p surface (nullptr if none). + static DecorationContextV1 *forSurface(wlr_surface *surface); + +Q_SIGNALS: + void cornerRadiusChanged(); + void shadowChanged(); + void borderChanged(); + void titlebarModeChanged(); + +private: + friend class DecorationContextV1Private; + std::unique_ptr d; +}; diff --git a/src/modules/foreign-toplevel/CMakeLists.txt b/src/modules/foreign-toplevel/CMakeLists.txt new file mode 100644 index 0000000000..b047dd8466 --- /dev/null +++ b/src/modules/foreign-toplevel/CMakeLists.txt @@ -0,0 +1,18 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-foreign-toplevel-manager-unstable-v3.xml + BASENAME treeland-foreign-toplevel-manager-unstable-v3 +) + +impl_treeland( + NAME + module_foreigntoplevel + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/foreign-toplevel/dockpreviewcontextv3.h + ${CMAKE_SOURCE_DIR}/src/modules/foreign-toplevel/foreigntoplevelhandlev3.h + ${CMAKE_SOURCE_DIR}/src/modules/foreign-toplevel/foreigntoplevelmanagerv3.h + ${CMAKE_SOURCE_DIR}/src/modules/foreign-toplevel/foreigntoplevelmanagerv3.cpp + INCLUDE + $ +) diff --git a/src/modules/foreign-toplevel/dockpreviewcontextv3.h b/src/modules/foreign-toplevel/dockpreviewcontextv3.h new file mode 100644 index 0000000000..e5bdd29c91 --- /dev/null +++ b/src/modules/foreign-toplevel/dockpreviewcontextv3.h @@ -0,0 +1,55 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include "modules/foreign-toplevel/foreigntoplevelmanagerv3.h" + +#include +#include +#include +#include +#include + +Q_MOC_INCLUDE("modules/foreign-toplevel/foreigntoplevelhandlev3.h") + +class ForeignToplevelHandleV3; +class ForeignToplevelManagerInterfaceV3; +class DockPreviewContextV3Private; + +struct wl_resource; +class DockPreviewContextV3 : public QObject +{ + Q_OBJECT +public: + ~DockPreviewContextV3() override; + + WSurface *relativeSurface() const; + + void enter(); + void leave(); + +Q_SIGNALS: + void requestShow(const QPoint &pos, + ForeignToplevelManagerInterfaceV3::PreviewDirection direction, + ForeignToplevelManagerInterfaceV3::PreviewLayout layout, + const QList &toplevels); + void requestShowTooltip(WSurface *surface, + const QPoint &pos, + ForeignToplevelManagerInterfaceV3::PreviewDirection direction); + void requestClose(); + void beforeDestroy(); + +private: + explicit DockPreviewContextV3(wl_resource *resource, + wlr_surface *_relativeSurface, + ForeignToplevelManagerInterfaceV3 *manager); + + wl_resource *resource() const; + + std::unique_ptr d; + + friend class DockPreviewContextV3Private; + friend class ForeignToplevelManagerInterfaceV3Private; +}; diff --git a/src/modules/foreign-toplevel/foreigntoplevelhandlev3.h b/src/modules/foreign-toplevel/foreigntoplevelhandlev3.h new file mode 100644 index 0000000000..27277aed2d --- /dev/null +++ b/src/modules/foreign-toplevel/foreigntoplevelhandlev3.h @@ -0,0 +1,84 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include +#include +#include +#include + +#include + +Q_MOC_INCLUDE() + +class SurfaceEntry; +class ForeignToplevelManagerInterfaceV3; +class ForeignToplevelHandleV3Private; +struct wl_resource; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutput; +class WSeat; +class WSurface; +WAYLIB_SERVER_END_NAMESPACE + +class ForeignToplevelHandleV3 : public QObject, public WAYLIB_SERVER_NAMESPACE::WObject +{ + Q_OBJECT +public: + enum class State + { + Maximized = 1, + Minimized = 2, + Activated = 4, + Fullscreen = 8, + Attention = 16, + }; + Q_ENUM(State) + Q_DECLARE_FLAGS(States, State) + + ~ForeignToplevelHandleV3() override; + + void set_title(const QString &title); + void set_app_id(const QString &app_id); + void set_pid(const pid_t pid); + void set_maximized(bool maximized); + void set_minimized(bool minimized); + void set_activated(bool activated); + void set_fullscreen(bool fullscreen); + void set_attention(bool attention); + void set_parent(ForeignToplevelHandleV3 *parent); + +Q_SIGNALS: + void requestMaximize(bool maximized); + void requestMinimize(bool minimized); + void requestActivate(WAYLIB_SERVER_NAMESPACE::WSeat *seat); + void requestFullscreen(bool fullscreen, WAYLIB_SERVER_NAMESPACE::WOutput *output); + void requestClose(); + void iconGeometryChanged(WAYLIB_SERVER_NAMESPACE::WSurface *surface, const QRect &rect); + +private: + explicit ForeignToplevelHandleV3(ForeignToplevelManagerInterfaceV3 *manager, + wl_resource *resource, + SurfaceEntry *entry); + + wl_resource *resource() const; + SurfaceEntry *entry() const; + void clearEntry(); + void set_identifier(uint32_t identifier); + uint32_t identifier() const; + void send_done(); + void send_closed(); + void send_state(); + void output_enter(WAYLIB_SERVER_NAMESPACE::WOutput *output); + void output_leave(WAYLIB_SERVER_NAMESPACE::WOutput *output); + void send_output(WAYLIB_SERVER_NAMESPACE::WOutput *output, bool enter); + + std::unique_ptr d; + + friend class ForeignToplevelManagerInterfaceV3; + friend class ForeignToplevelManagerInterfaceV3Private; +}; diff --git a/src/modules/foreign-toplevel/foreigntoplevelmanagerv3.cpp b/src/modules/foreign-toplevel/foreigntoplevelmanagerv3.cpp new file mode 100644 index 0000000000..0925472bce --- /dev/null +++ b/src/modules/foreign-toplevel/foreigntoplevelmanagerv3.cpp @@ -0,0 +1,1331 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "dockpreviewcontextv3.h" +#include "foreigntoplevelhandlev3.h" +#include "foreigntoplevelmanagerv3.h" +#include "common/treelandlogging.h" +#include "core/rootsurfacecontainer.h" +#include "core/waylandserver.h" +#include "showdesktop/showdesktop.h" +#include "surface/surfacewrapper.h" +#include "session/session.h" +#include + +#include "qwayland-server-treeland-foreign-toplevel-manager-unstable-v3.h" + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#ifndef DISABLE_XWAYLAND +#include +#endif + +#include +#include + +namespace { +constexpr char DockPreviewContextPropertyName[] = "treelandDockPreviewContextV3"; + +QByteArray encodeStates(ForeignToplevelHandleV3::States states) +{ + QByteArray ba; + auto push = [&](uint32_t v) { + ba.append(reinterpret_cast(&v), sizeof(v)); + }; + + if (states.testFlag(ForeignToplevelHandleV3::State::Maximized)) + push(TREELAND_FOREIGN_TOPLEVEL_HANDLE_V3_STATE_MAXIMIZED); + + if (states.testFlag(ForeignToplevelHandleV3::State::Minimized)) + push(TREELAND_FOREIGN_TOPLEVEL_HANDLE_V3_STATE_MINIMIZED); + + if (states.testFlag(ForeignToplevelHandleV3::State::Activated)) + push(TREELAND_FOREIGN_TOPLEVEL_HANDLE_V3_STATE_ACTIVATED); + + if (states.testFlag(ForeignToplevelHandleV3::State::Fullscreen)) + push(TREELAND_FOREIGN_TOPLEVEL_HANDLE_V3_STATE_FULLSCREEN); + + if (states.testFlag(ForeignToplevelHandleV3::State::Attention)) + push(TREELAND_FOREIGN_TOPLEVEL_HANDLE_V3_STATE_ATTENTION); + + return ba; +} +} + +class SurfaceEntry +{ +public: + SurfaceWrapper *wrapper = nullptr; + QList handles; +}; + +struct foreign_toplevel_output { + WOutput *output = nullptr; + ForeignToplevelHandleV3 *toplevel = nullptr; +}; + +static DockPreviewContextV3 *dockPreviewContextForSurface(WSurface *relativeSurface) +{ + if (!relativeSurface) { + return nullptr; + } + + auto *contextObject = relativeSurface->property(DockPreviewContextPropertyName).value(); + return qobject_cast(contextObject); +} + +class ForeignToplevelManagerInterfaceV3Private + : public QtWaylandServer::treeland_foreign_toplevel_manager_v3 +{ +public: + ForeignToplevelManagerInterfaceV3Private(ForeignToplevelManagerInterfaceV3 *_q); + ~ForeignToplevelManagerInterfaceV3Private() override = default; + + ForeignToplevelManagerInterfaceV3 *q = nullptr; + wl_event_loop *event_loop = nullptr; + + wl_global *global() const; + std::map> m_surfaces; + QList dockPreviewContexts; + QList handles; + uint32_t m_nextIdentifier = 1; + + ForeignToplevelHandleV3 *createHandle(Resource *managerResource, SurfaceEntry *entry); + void setupHandleForWrapper(SurfaceEntry *entry, ForeignToplevelHandleV3 *handle); + ForeignToplevelHandleV3 *findHandleForClient(SurfaceWrapper *wrapper, wl_client *client); + + void releaseHandle(ForeignToplevelHandleV3 *handle); +protected: + void destroy(Resource *resource) override; + void bind_resource(Resource *resource) override; + void stop(Resource *resource) override; + void get_dock_preview_context(Resource *resource, struct ::wl_resource *relative_surface, uint32_t id) override; +}; + +ForeignToplevelManagerInterfaceV3Private::ForeignToplevelManagerInterfaceV3Private(ForeignToplevelManagerInterfaceV3 *_q) + : QtWaylandServer::treeland_foreign_toplevel_manager_v3() + , q(_q) +{ +} + +wl_global *ForeignToplevelManagerInterfaceV3Private::global() const +{ + return m_global; +} + +void ForeignToplevelManagerInterfaceV3Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void ForeignToplevelManagerInterfaceV3Private::stop(Resource *resource) +{ + send_finished(resource->handle); +} + +void ForeignToplevelManagerInterfaceV3Private::get_dock_preview_context(Resource *resource, + struct ::wl_resource *relative_surface, + uint32_t id) +{ + if (!relative_surface) { + wl_resource_post_error(resource->handle, + TREELAND_FOREIGN_TOPLEVEL_MANAGER_V3_ERROR_INVALID_SURFACE, + "relative_surface resource is NULL!"); + return; + } + + if (wl_resource_get_client(relative_surface) != resource->client()) { + wl_resource_post_error(resource->handle, + TREELAND_FOREIGN_TOPLEVEL_MANAGER_V3_ERROR_INVALID_SURFACE, + "relative_surface is not owned by the calling client"); + return; + } + + auto *relativeSurface = wlr_surface_from_resource(relative_surface); + if (!relativeSurface) { + wl_resource_post_error(resource->handle, + TREELAND_FOREIGN_TOPLEVEL_MANAGER_V3_ERROR_INVALID_SURFACE, + "wlr_surface_from_resource failed!"); + return; + } + + // v3 protocol: only one dock preview context may be active per surface at a + // time. If the surface already has an active context, the compositor raises + // the context_already_exists protocol error and does not create the object. + if (auto *relativeSurfaceObject = WSurface::fromHandle(relativeSurface)) { + auto existing = relativeSurfaceObject->property(DockPreviewContextPropertyName).value(); + if (qobject_cast(existing)) { + wl_resource_post_error(resource->handle, + TREELAND_FOREIGN_TOPLEVEL_MANAGER_V3_ERROR_CONTEXT_ALREADY_EXISTS, + "surface already has an active dock preview context; destroy it first"); + return; + } + } + + wl_resource *dockPreviewContextResource = wl_resource_create(resource->client(), + &treeland_dock_preview_context_v3_interface, + resource->version(), + id); + if (!dockPreviewContextResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto *context = new DockPreviewContextV3(dockPreviewContextResource, + relativeSurface, + q); + dockPreviewContexts.append(context); + + QObject::connect(context, + &DockPreviewContextV3::requestShow, + q, + [this, context](const QPoint &pos, + ForeignToplevelManagerInterfaceV3::PreviewDirection direction, + ForeignToplevelManagerInterfaceV3::PreviewLayout layout, + const QList &toplevels) { + std::vector surfaces; + surfaces.reserve(toplevels.size()); + for (auto *handle : toplevels) { + if (auto *entry = handle->entry()) { + surfaces.push_back(entry->wrapper); + } + } + Q_EMIT q->requestDockPreview( + surfaces, context->relativeSurface(), pos, direction, layout); + }); + QObject::connect(context, + &DockPreviewContextV3::requestShowTooltip, + q, + [this, context](WSurface *surface, + const QPoint &pos, + ForeignToplevelManagerInterfaceV3::PreviewDirection direction) { + Q_EMIT q->requestDockPreviewTooltip(surface, + context->relativeSurface(), + pos, + direction); + }); + QObject::connect(context, + &DockPreviewContextV3::requestClose, + q, + &ForeignToplevelManagerInterfaceV3::requestDockClose); + QObject::connect(context, + &DockPreviewContextV3::beforeDestroy, + q, + &ForeignToplevelManagerInterfaceV3::requestDockClose); + + if (auto *relativeSurfaceObject = WSurface::fromHandle(relativeSurface)) { + relativeSurfaceObject->setProperty(DockPreviewContextPropertyName, + QVariant::fromValue(static_cast(context))); + } +} + +ForeignToplevelManagerInterfaceV3::ForeignToplevelManagerInterfaceV3(Session *session) + : SessionComponent(session) + , WServerInterface() + , d(new ForeignToplevelManagerInterfaceV3Private(this)) +{ +} + +ForeignToplevelManagerInterfaceV3::~ForeignToplevelManagerInterfaceV3() = default; + +ForeignToplevelHandleV3 * +ForeignToplevelManagerInterfaceV3Private::createHandle(Resource *managerResource, SurfaceEntry *entry) +{ + struct wl_client *client = wl_resource_get_client(managerResource->handle); + struct wl_resource *resource = wl_resource_create(client, + &treeland_foreign_toplevel_handle_v3_interface, + treeland_foreign_toplevel_handle_v3_interface.version, + 0); + if (!resource) { + qCCritical(lcTlProtocol) << "wl_resource_create failed!"; + wl_client_post_no_memory(client); + return nullptr; + } + + auto *handle = new ForeignToplevelHandleV3(q, resource, entry); + entry->handles.append(handle); + handles.append(handle); + + send_toplevel(managerResource->handle, resource); + handle->set_identifier(m_nextIdentifier++); + + return handle; +} + +void ForeignToplevelManagerInterfaceV3Private::setupHandleForWrapper(SurfaceEntry *entry, + ForeignToplevelHandleV3 *handle) +{ + SurfaceWrapper *wrapper = entry->wrapper; + + QObject::connect(handle, &ForeignToplevelHandleV3::requestClose, wrapper, [wrapper]() { + wrapper->close(); + }); + + // The icon geometry handler only depends on the wrapper, so connect it here for + // both splash and normal handles: a splash is exposed to clients immediately + // and a set_icon_geometry sent during the splash phase must not be dropped. + QObject::connect(handle, + &ForeignToplevelHandleV3::iconGeometryChanged, + wrapper, + [wrapper](WSurface *surface, const QRect &rect) { + auto *dockWrapper = + WaylandServer::instance()->rootSurfaceContainer()->getSurface(surface); + if (!dockWrapper) { + qCWarning(lcTlProtocol) + << "iconGeometryChanged: dock wrapper not found for app" + << wrapper->appId() << "surface=" << surface << "rect=" << rect; + return; + } + const QRect iconGeometry(dockWrapper->x() + rect.x(), + dockWrapper->y() + rect.y(), + rect.width(), + rect.height()); + qCDebug(lcTlProtocol) << "iconGeometryChanged:" << wrapper->appId() + << "rect=" << rect + << "dockPos=" + << QPointF(dockWrapper->x(), dockWrapper->y()) + << "iconGeometry=" << iconGeometry; + wrapper->setIconGeometry(iconGeometry); + }); + + if (wrapper->type() == SurfaceWrapper::Type::SplashScreen) { + // A splash has no real window yet, so no title is sent here: the taskbar would + // otherwise show a placeholder title. initializeToplevelHandle() sends the real + // title once the toplevel surface exists. + handle->set_app_id(wrapper->appId()); + handle->set_minimized(false); + handle->set_maximized(false); + handle->set_fullscreen(false); + handle->set_activated(false); + + QObject::connect(wrapper, &SurfaceWrapper::surfaceItemCreated, handle, [this, wrapper, handle]() { + q->initializeToplevelHandle(wrapper, handle); + }); + return; + } + + q->initializeToplevelHandle(wrapper, handle); +} + +ForeignToplevelHandleV3 * +ForeignToplevelManagerInterfaceV3Private::findHandleForClient(SurfaceWrapper *wrapper, wl_client *client) +{ + auto it = m_surfaces.find(wrapper); + if (it == m_surfaces.end()) { + return nullptr; + } + + for (auto *handle : std::as_const(it->second->handles)) { + if (wl_resource_get_client(handle->resource()) == client) { + return handle; + } + } + + return nullptr; +} + +void ForeignToplevelManagerInterfaceV3::addSurface(SurfaceWrapper *wrapper) +{ + Q_ASSERT(wrapper->session() == session()); + if (d->m_surfaces.contains(wrapper)) { + qCCritical(lcTlProtocol) + << wrapper << " has been add to foreign toplevel twice"; + return; + } + + auto entry = std::make_unique(); + entry->wrapper = wrapper; + auto *entryPtr = entry.get(); + d->m_surfaces.insert({wrapper, std::move(entry)}); + + for (const auto &manager_resource : d->resourceMap()) { + auto *handle = d->createHandle(manager_resource, entryPtr); + if (!handle) + continue; + d->setupHandleForWrapper(entryPtr, handle); + } +} + +void ForeignToplevelManagerInterfaceV3::removeSurface(SurfaceWrapper *wrapper) +{ + auto it = d->m_surfaces.find(wrapper); + if (it == d->m_surfaces.end()) { + qCCritical(lcTlProtocol) << wrapper << " is not registered in foreign toplevel"; + return; + } + + auto *entry = it->second.get(); + auto *surface = wrapper->shellSurface(); + for (auto *handle : std::as_const(entry->handles)) { + if (surface) { + QObject::disconnect(surface, nullptr, handle, nullptr); + if (auto *wsurface = surface->surface()) { + QObject::disconnect(wsurface, nullptr, handle, nullptr); + } + } + QObject::disconnect(wrapper, nullptr, handle, nullptr); + QObject::disconnect(handle, nullptr, wrapper, nullptr); + + handle->send_closed(); + handle->clearEntry(); + } + + d->m_surfaces.erase(it); +} + +void ForeignToplevelManagerInterfaceV3::releaseHandle(ForeignToplevelHandleV3 *handle) +{ + d->handles.removeOne(handle); + d->releaseHandle(handle); +} + +void ForeignToplevelManagerInterfaceV3::releaseDockPreviewContext(DockPreviewContextV3 *context) +{ + d->dockPreviewContexts.removeOne(context); +} + +ForeignToplevelHandleV3 *ForeignToplevelManagerInterfaceV3::handleForIdentifier(uint32_t identifier, + wl_client *client) const +{ + for (auto *handle : std::as_const(d->handles)) { + if (handle->identifier() != identifier + || wl_resource_get_client(handle->resource()) != client) + continue; + auto *entry = handle->entry(); + if (entry) + return handle; + } + return nullptr; +} + +void ForeignToplevelManagerInterfaceV3Private::releaseHandle(ForeignToplevelHandleV3 *handle) +{ + auto *entry = handle->entry(); + if (entry) { + entry->handles.removeOne(handle); + } +} + +void ForeignToplevelManagerInterfaceV3Private::bind_resource(Resource *resource) +{ + for (auto &[wrapper, entry] : m_surfaces) { + auto *handle = createHandle(resource, entry.get()); + if (!handle) + continue; + setupHandleForWrapper(entry.get(), handle); + } +} + +void ForeignToplevelManagerInterfaceV3::enterDockPreview(WSurface *relativeSurface) +{ + if (auto *context = dockPreviewContextForSurface(relativeSurface)) { + context->enter(); + } +} + +void ForeignToplevelManagerInterfaceV3::leaveDockPreview(WSurface *relativeSurface) +{ + if (auto *context = dockPreviewContextForSurface(relativeSurface)) { + context->leave(); + } +} + +wl_event_loop *ForeignToplevelManagerInterfaceV3::eventLoop() const +{ + return d->event_loop; +} + +QByteArrayView ForeignToplevelManagerInterfaceV3::interfaceName() const +{ + return d->interfaceName(); +} + +void ForeignToplevelManagerInterfaceV3::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); + d->event_loop = wl_display_get_event_loop(server->handle()); +} + +void ForeignToplevelManagerInterfaceV3::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *ForeignToplevelManagerInterfaceV3::global() const +{ + return d->global(); +} + +void ForeignToplevelManagerInterfaceV3::initializeToplevelHandle(SurfaceWrapper *wrapper, ForeignToplevelHandleV3 *handle) +{ + Q_ASSERT(wrapper->type() == SurfaceWrapper::Type::XdgToplevel + || wrapper->type() == SurfaceWrapper::Type::XWayland); + auto surface = wrapper->shellSurface(); + qCInfo(lcTlProtocol) << "Register surface to ForeignToplevelManagerInterfaceV3, appId=" << wrapper->appId() + << wrapper->type() << wrapper->skipDockPreView(); + + // initSurface + handle->set_title(surface->title()); + handle->set_app_id(wrapper->appId()); + handle->set_minimized(surface->isMinimized()); + handle->set_maximized(surface->isMaximized()); + handle->set_fullscreen(surface->isFullScreen()); + handle->set_activated(surface->isActivated()); + handle->set_attention(wrapper->attention()); + + QObject::connect(surface, &WToplevelSurface::titleChanged, handle, [handle, surface] { + handle->set_title(surface->title()); + }); + + QObject::connect(surface, &WToplevelSurface::minimizeChanged, handle, [handle, surface] { + handle->set_minimized(surface->isMinimized()); + }); + + QObject::connect(surface, &WToplevelSurface::maximizeChanged, handle, [handle, surface] { + handle->set_maximized(surface->isMaximized()); + }); + + QObject::connect(surface, &WToplevelSurface::fullscreenChanged, handle, [handle, surface] { + handle->set_fullscreen(surface->isFullScreen()); + }); + + QObject::connect(surface, &WToplevelSurface::activateChanged, handle, [handle, surface] { + handle->set_activated(surface->isActivated()); + }); + + connect(wrapper, &SurfaceWrapper::attentionChanged, handle, [handle, wrapper] { + handle->set_attention(wrapper->attention()); + }); + + QObject::connect(surface, &WToplevelSurface::appIdChanged, handle, [handle, wrapper] { + handle->set_app_id(wrapper->appId()); + }); + + QObject::connect(surface->surface(), &WSurface::outputEntered, handle, [handle](WOutput *output) { + handle->output_enter(output); + }); + + QObject::connect(surface->surface(), &WSurface::outputLeave, handle, [handle](WOutput *output) { + handle->output_leave(output); + }); + + connect(handle, &ForeignToplevelHandleV3::requestActivate, wrapper, [wrapper](WSeat *seat) { + WaylandServer::instance()->forceActivateSurface(wrapper, Qt::OtherFocusReason, seat); + }); + + connect(handle, + &ForeignToplevelHandleV3::requestMaximize, + wrapper, + [wrapper](bool maximized) { + if (maximized) + wrapper->maximize(); + else + wrapper->unmaximize(); + }); + + connect(handle, + &ForeignToplevelHandleV3::requestMinimize, + wrapper, + [wrapper](bool minimized) { + if ((WaylandServer::instance()->showDesktopState() + == ShowDesktop::State::Show)) { + WaylandServer::instance()->forceActivateSurface(wrapper); + return; + } + + if (minimized) + wrapper->minimize(); + else + wrapper->restoreFromMinimized(); + }); + + connect(handle, + &ForeignToplevelHandleV3::requestFullscreen, + wrapper, + [wrapper](bool fullscreen, WOutput *output) { + if (fullscreen) + wrapper->enterFullscreen(output); + else + wrapper->leaveFullscreen(); + }); + + if (auto *xdgSurface = qobject_cast(surface)) { + auto client = WClient::get(xdgSurface->handle()->resource->client); + handle->set_pid(client->credentials().get()->pid); + + auto updateSurfaceParent = [this, handle, xdgSurface] { + WXdgToplevelSurface *p = xdgSurface->parentXdgSurface(); + if (!p) { + handle->set_parent(nullptr); + return; + } + wl_client *client = wl_resource_get_client(handle->resource()); + for (const auto &[wrapper, entry] : d->m_surfaces) { + if (wrapper->shellSurface() == p) { + auto *parentHandle = d->findHandleForClient(wrapper, client); + if (parentHandle) { + handle->set_parent(parentHandle); + } + return; + } + } + qCCritical(lcTlProtocol) + << "Xdg toplevel surface " << xdgSurface + << "has set parent surface, but foreign_toplevel_handle for " + "parent surface not " + "found!"; + }; + QObject::connect(xdgSurface, &WXdgToplevelSurface::parentXdgSurfaceChanged, + handle, + updateSurfaceParent); + updateSurfaceParent(); +#ifndef DISABLE_XWAYLAND + } else if (auto *xwaylandSurface = qobject_cast(surface)) { + handle->set_pid(xwaylandSurface->pid()); + + auto updateSurfaceParent = [this, handle, xwaylandSurface] { + WToplevelSurface *p = xwaylandSurface->parentXWaylandSurface(); + if (!p) { + handle->set_parent(nullptr); + return; + } + wl_client *client = wl_resource_get_client(handle->resource()); + for (const auto &[wrapper, entry] : d->m_surfaces) { + if (wrapper->shellSurface() == p) { + auto *parentHandle = d->findHandleForClient(wrapper, client); + if (parentHandle) { + handle->set_parent(parentHandle); + } + return; + } + } + qCCritical(lcTlProtocol) + << "X11 surface " << xwaylandSurface + << "has set parent surface, but foreign_toplevel_handle for " + "parent surface not " + "found!"; + }; + QObject::connect(xwaylandSurface, &WXWaylandSurface::parentXWaylandSurfaceChanged, + handle, + updateSurfaceParent); + updateSurfaceParent(); +#endif + } else { + qCFatal(lcTlProtocol) + << "TreelandForeignToplevelManager only support WXdgSurface or " + "WXWaylandSurface"; + } +} + +namespace { +// A dedicated role keeps the tooltip surface away from every other surface +// user: wlroots refuses to assign another role while this one is set, and never +// clears it, so a surface that once showed a tooltip can only show tooltips. +const struct wlr_surface_role dockTooltipSurfaceRole = { + "treeland_dock_tooltip", + true, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, +}; +} + +class DockPreviewContextV3Private + : public QtWaylandServer::treeland_dock_preview_context_v3 +{ +public: + DockPreviewContextV3Private(DockPreviewContextV3 *_q, + wl_resource *resource, + wlr_surface *_relativeSurface, + ForeignToplevelManagerInterfaceV3 *_manager); + ~DockPreviewContextV3Private() override; + + DockPreviewContextV3 *q = nullptr; + QPointer manager; + QPointer relativeSurface; + + // The surface this context currently shows as its tooltip, if any. The + // surface belongs to the client; the wrapper is ours when nobody else had + // wrapped that surface yet. + QPointer tooltipSurface; + // Owns the native destroy listener of the tooltip surface. The token is + // its own listener target instead of the surface wrapper: the wrapper may + // belong to another dock preview context and be released before the + // surface dies, and the popover still has to be closed in that case. + WListenerOwner m_tooltipDestroyListenerOwner; + // Whether the tooltip, and not the preview, is what the UI displays. + bool tooltipShown = false; + + void setTooltipSurface(wlr_surface *surface); + void releaseTooltipSurface(); + void enterTooltipOutputs(); + void leaveTooltipOutputs(); + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void show(Resource *resource, wl_array *identifiers, int32_t x, int32_t y, uint32_t direction) override; + void show_list(Resource *resource, wl_array *identifiers, int32_t x, int32_t y, uint32_t direction) override; + void show_tooltip_surface(Resource *resource, struct ::wl_resource *surface, int32_t x, int32_t y, uint32_t direction) override; + void close(Resource *resource) override; + +private: + void showPreview(Resource *resource, + wl_array *identifiers, + int32_t x, + int32_t y, + uint32_t direction, + ForeignToplevelManagerInterfaceV3::PreviewLayout layout); + void tooltipSurfaceDestroyed(); + + bool m_ownsTooltipWrapper = false; +}; + +DockPreviewContextV3Private::DockPreviewContextV3Private(DockPreviewContextV3 *_q, + wl_resource *resource, + wlr_surface *_relativeSurface, + ForeignToplevelManagerInterfaceV3 *_manager) + : QtWaylandServer::treeland_dock_preview_context_v3(resource) + , q(_q) + , manager(_manager) + , relativeSurface(WSurface::fromHandle(_relativeSurface)) +{ +} + +DockPreviewContextV3Private::~DockPreviewContextV3Private() +{ + releaseTooltipSurface(); +} + +void DockPreviewContextV3Private::setTooltipSurface(wlr_surface *surface) +{ + if (tooltipSurface && tooltipSurface->handle() == surface) + return; + + releaseTooltipSurface(); + + auto *wrapper = WSurface::fromHandle(surface); + if (wrapper) { + m_ownsTooltipWrapper = false; + } else { + wrapper = new WSurface(surface); + m_ownsTooltipWrapper = true; + } + tooltipSurface = wrapper; + + m_tooltipDestroyListenerOwner.teardown(); + m_tooltipDestroyListenerOwner.listeners()->add( + &surface->events.destroy, + this, + &DockPreviewContextV3Private::tooltipSurfaceDestroyed); +} + +void DockPreviewContextV3Private::releaseTooltipSurface() +{ + leaveTooltipOutputs(); + + // Detach the destroy listener from the surface. + m_tooltipDestroyListenerOwner.teardown(); + + if (m_ownsTooltipWrapper) { + m_ownsTooltipWrapper = false; + // Emits WSurface::beforeDestroy, so the UI drops the pointer before + // the wrapper goes away. + delete tooltipSurface.data(); + } + tooltipSurface = nullptr; +} + +// The compositor renders this surface, so the client has to be told which +// output it is shown on, like any other surface: that is what carries the +// preferred scale and the frame callbacks. +void DockPreviewContextV3Private::enterTooltipOutputs() +{ + if (!tooltipSurface || !relativeSurface) + return; + + for (auto *output : relativeSurface->outputs()) + tooltipSurface->enterOutput(output); +} + +void DockPreviewContextV3Private::leaveTooltipOutputs() +{ + if (!tooltipSurface) + return; + + const auto outputs = tooltipSurface->outputs(); + for (auto *output : outputs) + tooltipSurface->leaveOutput(output); +} + +void DockPreviewContextV3Private::tooltipSurfaceDestroyed() +{ + // Detach first: the native surface is going away. + m_tooltipDestroyListenerOwner.teardown(); + + // The wrapper of a surface the client destroyed must go with it. + if (m_ownsTooltipWrapper) { + m_ownsTooltipWrapper = false; + delete tooltipSurface.data(); + } + tooltipSurface = nullptr; + + if (tooltipShown) { + tooltipShown = false; + Q_EMIT q->requestClose(); + } +} + +void DockPreviewContextV3Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + releaseTooltipSurface(); + if (relativeSurface) { + relativeSurface->setProperty(DockPreviewContextPropertyName, QVariant()); + } + if (manager) { + manager->releaseDockPreviewContext(q); + } + Q_EMIT q->beforeDestroy(); + delete q; +} + +void DockPreviewContextV3Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void DockPreviewContextV3Private::show([[maybe_unused]] Resource *resource, wl_array *identifiers, int32_t x, int32_t y, uint32_t direction) +{ + showPreview(resource, + identifiers, + x, + y, + direction, + ForeignToplevelManagerInterfaceV3::PreviewLayout::thumbnail); +} + +void DockPreviewContextV3Private::show_list([[maybe_unused]] Resource *resource, wl_array *identifiers, int32_t x, int32_t y, uint32_t direction) +{ + showPreview(resource, + identifiers, + x, + y, + direction, + ForeignToplevelManagerInterfaceV3::PreviewLayout::list); +} + +void DockPreviewContextV3Private::showPreview([[maybe_unused]] Resource *resource, + wl_array *identifiers, + int32_t x, + int32_t y, + uint32_t direction, + ForeignToplevelManagerInterfaceV3::PreviewLayout layout) +{ + if (!relativeSurface) + return; + + QList toplevels; + const uint32_t *data = reinterpret_cast(identifiers->data); + const size_t count = identifiers->size / sizeof(uint32_t); + for (size_t i = 0; i != count; ++i) { + if (auto *handle = manager ? manager->handleForIdentifier(data[i], resource->client()) : nullptr) + toplevels.append(handle); + } + + if (!identifiers->size) + qCCritical(lcTlProtocol) << "Got empty identifier list for dock preview!"; + + // The preview replaces the tooltip. + tooltipShown = false; + leaveTooltipOutputs(); + + Q_EMIT q->requestShow(QPoint(x, y), + static_cast(direction), + layout, + toplevels); +} + +void DockPreviewContextV3Private::show_tooltip_surface(Resource *resource, + struct ::wl_resource *surfaceResource, + int32_t x, + int32_t y, + uint32_t direction) +{ + if (!relativeSurface) + return; + + auto *surface = wlr_surface_from_resource(surfaceResource); + if (wl_resource_get_client(surfaceResource) != resource->client() + || surface == relativeSurface->handle()) { + wl_resource_post_error(resource->handle, + error_invalid_surface, + "tooltip surface must belong to the calling client and must not be the anchor surface"); + return; + } + + // A surface without committed content is a client error, and the request + // has no effect. + if (!wlr_surface_get_texture(surface)) + return; + + // Fails and posts the protocol error itself when the surface already has + // another role. + if (!wlr_surface_set_role(surface, + &dockTooltipSurfaceRole, + resource->handle, + error_invalid_surface)) { + return; + } + + setTooltipSurface(surface); + + tooltipShown = true; + enterTooltipOutputs(); + Q_EMIT q->requestShowTooltip( + tooltipSurface.data(), + QPoint(x, y), + static_cast(direction)); +} + +void DockPreviewContextV3Private::close([[maybe_unused]] Resource *resource) +{ + tooltipShown = false; + leaveTooltipOutputs(); + Q_EMIT q->requestClose(); +} + +DockPreviewContextV3::~DockPreviewContextV3() = default; + +wl_resource *DockPreviewContextV3::resource() const +{ + return d->resource()->handle; +} + +WSurface *DockPreviewContextV3::relativeSurface() const +{ + return d->relativeSurface; +} + +void DockPreviewContextV3::enter() +{ + d->send_enter(); +} + +void DockPreviewContextV3::leave() +{ + d->send_leave(); +} + +DockPreviewContextV3::DockPreviewContextV3(wl_resource *resource, + wlr_surface *_relativeSurface, + ForeignToplevelManagerInterfaceV3 *manager) + : QObject(nullptr) + , d(new DockPreviewContextV3Private(this, resource, _relativeSurface, manager)) +{ +} + +class ForeignToplevelHandleV3Private + : public QtWaylandServer::treeland_foreign_toplevel_handle_v3 +{ +public: + ForeignToplevelHandleV3Private(ForeignToplevelHandleV3 *_q, + ForeignToplevelManagerInterfaceV3 *_manager, + wl_resource *resource, + SurfaceEntry *_entry); + ~ForeignToplevelHandleV3Private() override; + + ForeignToplevelHandleV3 *q = nullptr; + QPointer manager; + SurfaceEntry *entry = nullptr; + + wl_event_source *idle_source{ nullptr }; + + QString title; + QString app_id; + uint32_t identifier; + pid_t pid; + + ForeignToplevelHandleV3 *parent{ nullptr }; + QList outputs; + ForeignToplevelHandleV3::States state; + void scheduleDone(); + static void idleSendDone(void *data); +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void set_maximized(Resource *resource) override; + void unset_maximized(Resource *resource) override; + void set_minimized(Resource *resource) override; + void unset_minimized(Resource *resource) override; + void activate(Resource *resource, struct ::wl_resource *seat) override; + void close(Resource *resource) override; + void set_icon_geometry(Resource *resource, struct ::wl_resource *surface, int32_t x, int32_t y, int32_t width, int32_t height) override; + void set_fullscreen(Resource *resource, struct ::wl_resource *output) override; + void unset_fullscreen(Resource *resource) override; +}; + +ForeignToplevelHandleV3Private::ForeignToplevelHandleV3Private(ForeignToplevelHandleV3 *_q, + ForeignToplevelManagerInterfaceV3 *_manager, + wl_resource *resource, + SurfaceEntry *_entry) + : QtWaylandServer::treeland_foreign_toplevel_handle_v3(resource) + , q(_q) + , manager(_manager) + , entry(_entry) +{ +} + +ForeignToplevelHandleV3Private::~ForeignToplevelHandleV3Private() +{ + if (idle_source) { + wl_event_source_remove(idle_source); + idle_source = nullptr; + } + send_done(); +} + +void ForeignToplevelHandleV3Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + if (manager) { + manager->releaseHandle(q); + } + + delete q; +} + +void ForeignToplevelHandleV3Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void ForeignToplevelHandleV3Private::set_maximized([[maybe_unused]] Resource *resource) +{ + if (!entry) + return; + Q_EMIT q->requestMaximize(true); +} + +void ForeignToplevelHandleV3Private::unset_maximized([[maybe_unused]] Resource *resource) +{ + if (!entry) + return; + Q_EMIT q->requestMaximize(false); +} + +void ForeignToplevelHandleV3Private::set_minimized([[maybe_unused]] Resource *resource) +{ + if (!entry) + return; + Q_EMIT q->requestMinimize(true); +} + +void ForeignToplevelHandleV3Private::unset_minimized([[maybe_unused]] Resource *resource) +{ + if (!entry) + return; + Q_EMIT q->requestMinimize(false); +} + +void ForeignToplevelHandleV3Private::activate(Resource *resource, struct ::wl_resource *seat) +{ + if (!entry) + return; + if (wl_resource_get_client(seat) != resource->client()) + return; + const wlr_seat_client *seat_client = wlr_seat_client_from_resource(seat); + if (!seat_client) { + wl_resource_post_error(resource->handle, 0, "wlr_seat_client_from_resource failed!"); + return; + } + + Q_EMIT q->requestActivate(WSeat::fromHandle(seat_client->seat)); +} + +void ForeignToplevelHandleV3Private::close([[maybe_unused]] Resource *resource) +{ + if (!entry) + return; + Q_EMIT q->requestClose(); +} + +void ForeignToplevelHandleV3Private::set_icon_geometry(Resource *resource, struct ::wl_resource *surface, int32_t x, int32_t y, int32_t width, int32_t height) +{ + if (!entry) + return; + if (wl_resource_get_client(surface) != resource->client()) + return; + if (width < 0 || height < 0) { + wl_resource_post_error(resource->handle, + TREELAND_FOREIGN_TOPLEVEL_HANDLE_V3_ERROR_INVALID_GEOMETRY, + "invalid geometry passed to set_icon_geometry: width/height < 0"); + return; + } + + auto *wlrSurface = wlr_surface_from_resource(surface); + auto *surfaceObject = wlrSurface ? WSurface::fromHandle(wlrSurface) : nullptr; + Q_EMIT q->iconGeometryChanged(surfaceObject, QRect(x, y, width, height)); +} + +void ForeignToplevelHandleV3Private::set_fullscreen(Resource *resource, struct ::wl_resource *output) +{ + if (!entry) + return; + WOutput *wrappedOutput = nullptr; + if (output) { + auto *wlrOutput = wlr_output_from_resource(output); + + if (!wlrOutput) { + wl_resource_post_error(resource->handle, 0, "wlr_output_from_resource failed!"); + return; + } + wrappedOutput = WOutput::fromHandle(wlrOutput); + } + + Q_EMIT q->requestFullscreen(true, wrappedOutput); +} + +void ForeignToplevelHandleV3Private::unset_fullscreen([[maybe_unused]] Resource *resource) +{ + if (!entry) + return; + Q_EMIT q->requestFullscreen(false, nullptr); +} + +ForeignToplevelHandleV3::~ForeignToplevelHandleV3() +{ + // Detaches bind listeners registered via output->listeners(this). + teardown(); +} + +wl_resource *ForeignToplevelHandleV3::resource() const +{ + return d->resource()->handle; +} + +void ForeignToplevelHandleV3::set_title(const QString &title) +{ + if (d->title == title) { + return; + } + + d->title = title; + d->send_title(title); + d->scheduleDone(); +} + +void ForeignToplevelHandleV3::set_app_id(const QString &app_id) +{ + if (d->app_id == app_id) { + return; + } + + d->app_id = app_id; + d->send_app_id(app_id); + d->scheduleDone(); +} + +void ForeignToplevelHandleV3::set_pid(const pid_t pid) +{ + d->pid = pid; + d->send_pid(pid); + d->scheduleDone(); +} + +void ForeignToplevelHandleV3::set_identifier(uint32_t identifier) +{ + d->identifier = identifier; + d->send_identifier(identifier); + d->scheduleDone(); +} + +uint32_t ForeignToplevelHandleV3::identifier() const +{ + return d->identifier; +} + +void ForeignToplevelHandleV3::output_enter(WOutput *output) +{ + if (!output) { + return; + } + + auto *wlrOutput = output->handle(); + if (std::any_of(d->outputs.begin(), + d->outputs.end(), + [output](const foreign_toplevel_output &toplevel_output) { + return toplevel_output.output == output; + })) + return; + + auto toplevel_output = foreign_toplevel_output{ .output = output, .toplevel = this }; + d->outputs.append(toplevel_output); + + output->listeners(this)->add(&wlrOutput->events.bind, this, + [toplevel_output] (wlr_output_event_bind *event) { + const wl_client *client = wl_resource_get_client(event->resource); + if (wl_resource_get_client(toplevel_output.toplevel->resource()) == client) { + toplevel_output.toplevel->send_output(toplevel_output.output, true); + } + }); + + send_output(output, true); +} + +void ForeignToplevelHandleV3::output_leave(WOutput *output) +{ + if (!output) { + return; + } + + // Detach the bind listener registered via output->listeners(this). + output->removeListeners(this); + d->outputs.removeIf([output](const foreign_toplevel_output &handle_output) { + return handle_output.output == output; + }); + + send_output(output, false); +} + +void ForeignToplevelHandleV3::set_maximized(bool maximized) +{ + if (d->state.testFlag(State::Maximized) == maximized) { + return; + } + d->state.setFlag(State::Maximized, maximized); + send_state(); +} + +void ForeignToplevelHandleV3::set_minimized(bool minimized) +{ + if (d->state.testFlag(State::Minimized) == minimized) { + return; + } + d->state.setFlag(State::Minimized, minimized); + send_state(); +} + +void ForeignToplevelHandleV3::set_activated(bool activated) +{ + if (d->state.testFlag(State::Activated) == activated) { + return; + } + d->state.setFlag(State::Activated, activated); + send_state(); +} + +void ForeignToplevelHandleV3::set_fullscreen(bool fullscreen) +{ + if (d->state.testFlag(State::Fullscreen) == fullscreen) { + return; + } + d->state.setFlag(State::Fullscreen, fullscreen); + send_state(); +} + +void ForeignToplevelHandleV3::set_attention(bool attention) +{ + if (d->state.testFlag(State::Attention) == attention) { + return; + } + d->state.setFlag(State::Attention, attention); + send_state(); +} + +void ForeignToplevelHandleV3::set_parent(ForeignToplevelHandleV3 *parent) +{ + if (d->parent == parent) { + return; + } + + d->send_parent(parent ? parent->resource() : nullptr); + d->parent = parent; + d->scheduleDone(); +} + +void ForeignToplevelHandleV3::send_done() +{ + d->send_done(); +} + +void ForeignToplevelHandleV3::send_closed() +{ + d->send_closed(); +} + +void ForeignToplevelHandleV3::send_state() +{ + d->send_state(encodeStates(d->state)); + + d->scheduleDone(); +} + +void ForeignToplevelHandleV3::send_output(WOutput *output, bool enter) +{ + if (!output) { + return; + } + + const wl_client *client = wl_resource_get_client(resource()); + struct wl_resource *output_resource; + + wl_resource_for_each(output_resource, &output->handle()->resources) + { + if (wl_resource_get_client(output_resource) == client) { + if (enter) { + treeland_foreign_toplevel_handle_v3_send_output_enter(resource(), output_resource); + } else { + treeland_foreign_toplevel_handle_v3_send_output_leave(resource(), output_resource); + } + } + } + + d->scheduleDone(); +} + +SurfaceEntry *ForeignToplevelHandleV3::entry() const +{ + return d->entry; +} + +void ForeignToplevelHandleV3::clearEntry() +{ + d->entry = nullptr; +} + +ForeignToplevelHandleV3::ForeignToplevelHandleV3(ForeignToplevelManagerInterfaceV3 *manager, + wl_resource *resource, + SurfaceEntry *entry) + : QObject(nullptr) + , WObject() + , d(new ForeignToplevelHandleV3Private(this, manager, resource, entry)) +{ +} + +void ForeignToplevelHandleV3Private::idleSendDone(void *data) +{ + auto *self = static_cast(data); + self->send_done(); + self->idle_source = nullptr; +} + +void ForeignToplevelHandleV3Private::scheduleDone() +{ + if (idle_source || !manager) { + return; + } + + idle_source = wl_event_loop_add_idle(manager->eventLoop(), idleSendDone, this); +} diff --git a/src/modules/foreign-toplevel/foreigntoplevelmanagerv3.h b/src/modules/foreign-toplevel/foreigntoplevelmanagerv3.h new file mode 100644 index 0000000000..7a6d0e04b8 --- /dev/null +++ b/src/modules/foreign-toplevel/foreigntoplevelmanagerv3.h @@ -0,0 +1,90 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include "session/sessioncomponent.h" +#include + +#include +#include +#include +#include +#include + +class SurfaceWrapper; +class DockPreviewContextV3; +class ForeignToplevelHandleV3; +class ForeignToplevelManagerInterfaceV3Private; + +WAYLIB_SERVER_USE_NAMESPACE + +class ForeignToplevelManagerInterfaceV3 + : public SessionComponent + , public WServerInterface +{ + Q_OBJECT + Q_CLASSINFO("RegisterEnumClassesUnscoped", "false") + +public: + enum class PreviewDirection + { + top = 0, + right, + bottom, + left, + }; + Q_ENUM(PreviewDirection) + + enum class PreviewLayout + { + thumbnail = 0, + list, + }; + Q_ENUM(PreviewLayout) + + explicit ForeignToplevelManagerInterfaceV3(Session *session); + ~ForeignToplevelManagerInterfaceV3() override; + + void addSurface(SurfaceWrapper *wrapper); + void removeSurface(SurfaceWrapper *wrapper); + + Q_INVOKABLE void enterDockPreview(WSurface *relativeSurface); + Q_INVOKABLE void leaveDockPreview(WSurface *relativeSurface); + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 2; + +Q_SIGNALS: + void requestDockPreview(std::vector surfaces, + WSurface *target, + QPoint abs, + PreviewDirection direction, + PreviewLayout layout); + void requestDockPreviewTooltip(WSurface *surface, + WSurface *target, + QPoint abs, + PreviewDirection direction); + void requestDockClose(); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + wl_event_loop *eventLoop() const; + ForeignToplevelHandleV3 *handleForIdentifier(uint32_t identifier, wl_client *client) const; + void releaseHandle(ForeignToplevelHandleV3 *handle); + void releaseDockPreviewContext(DockPreviewContextV3 *context); + void initializeToplevelHandle(SurfaceWrapper *wrapper, ForeignToplevelHandleV3 *handle); + + std::unique_ptr d; + + friend class ForeignToplevelManagerInterfaceV3Private; + friend class DockPreviewContextV3; + friend class DockPreviewContextV3Private; + friend class ForeignToplevelHandleV3Private; +}; diff --git a/src/modules/input-manager/CMakeLists.txt b/src/modules/input-manager/CMakeLists.txt new file mode 100644 index 0000000000..6277000f0d --- /dev/null +++ b/src/modules/input-manager/CMakeLists.txt @@ -0,0 +1,16 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-input-manager-unstable-v1.xml + BASENAME treeland-input-manager-unstable-v1 +) + +impl_treeland( + NAME + module_input_manager + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/input-manager/inputmanagerinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/input-manager/inputmanagerinterfacev1.cpp + INCLUDE + $ +) diff --git a/src/modules/input-manager/inputmanagerinterfacev1.cpp b/src/modules/input-manager/inputmanagerinterfacev1.cpp new file mode 100644 index 0000000000..a17b469e87 --- /dev/null +++ b/src/modules/input-manager/inputmanagerinterfacev1.cpp @@ -0,0 +1,1070 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "inputmanagerinterfacev1.h" +#include "qwayland-server-treeland-input-manager-unstable-v1.h" +#include "core/waylandserver.h" +#include "common/treelandlogging.h" + +#include +#include + +#include + +#ifndef WL_DISPLAY_ERROR_NO_OBJECT +// wl_display.error no_object — added in wayland-server 1.23 +#define WL_DISPLAY_ERROR_NO_OBJECT 4 +#endif + +static QList s_mouseSettings; +static QList s_touchpadSettings; +static QList s_keyboardSettings; + +static QString normalizeNullableXkbString(const QString &value) +{ + return value.isNull() ? QStringLiteral("") : value; +} + +class TreelandInputManagerInterfaceV1Private : public QtWaylandServer::treeland_input_manager_v1 +{ +public: + explicit TreelandInputManagerInterfaceV1Private(TreelandInputManagerInterfaceV1 *_q); + wl_global *global() const; + + TreelandInputManagerInterfaceV1 *q = nullptr; +protected: + void destroy(Resource *resource) override; + void bind_resource(Resource *resource) override; + void get_mouse_settings(Resource *resource, uint32_t id, struct ::wl_resource *seat) override; + void get_touchpad_settings(Resource *resource, uint32_t id, struct ::wl_resource *seat) override; + void get_keyboard_settings(Resource *resource, uint32_t id, struct ::wl_resource *seat) override; +}; + +TreelandInputManagerInterfaceV1Private::TreelandInputManagerInterfaceV1Private(TreelandInputManagerInterfaceV1 *_q) + : QtWaylandServer::treeland_input_manager_v1() + , q(_q) +{ +} + +wl_global *TreelandInputManagerInterfaceV1Private::global() const +{ + return m_global; +} + +void TreelandInputManagerInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void TreelandInputManagerInterfaceV1Private::bind_resource(Resource *resource) +{ + TreelandInputManagerInterfaceV1::DeviceTypes types = q->inputDeviceListTypes(); + struct wlr_seat_client *seatClient = wlr_seat_client_for_wl_client(WaylandServer::instance()->seat()->handle(), resource->client()); + if (!seatClient) { + wl_resource_post_error(resource->handle, WL_DISPLAY_ERROR_NO_OBJECT, + "client is not bound to the default seat"); + return; + } + struct wl_resource *clientResource; + wl_resource_for_each(clientResource, &seatClient->resources) { + send_capability_available(resource->handle, types.toInt(), clientResource); + } +} + +void TreelandInputManagerInterfaceV1Private::get_mouse_settings(Resource *resource, uint32_t id, struct ::wl_resource *seat) +{ + if (!seat) { + wl_resource_post_error(resource->handle, 0, "seat resource is NULL!"); + return; + } + + if (!q->inputDeviceListTypes().testAnyFlag(TreelandInputManagerInterfaceV1::DeviceType::Mouse)) { + wl_resource_post_error(resource->handle, 0, "No mouse!"); + return; + } + + wl_resource *mouseResource = wl_resource_create(resource->client(), + &treeland_mouse_settings_v1_interface, + resource->version(), + id); + if (!mouseResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto mouse = new MouseSettingsInterfaceV1(mouseResource, seat); + s_mouseSettings.append(mouse); + + QObject::connect(mouse, &QObject::destroyed, [mouse]() { + s_mouseSettings.removeOne(mouse); + }); + + Q_EMIT q->mouseSettingsCreated(mouse); +} + +void TreelandInputManagerInterfaceV1Private::get_touchpad_settings(Resource *resource, uint32_t id, struct ::wl_resource *seat) +{ + if (!seat) { + wl_resource_post_error(resource->handle, 0, "seat resource is NULL!"); + return; + } + + if (!q->inputDeviceListTypes().testAnyFlag(TreelandInputManagerInterfaceV1::DeviceType::TouchPad)) { + wl_resource_post_error(resource->handle, 0, "No TouchPad!"); + return; + } + + wl_resource *touchpadResource = wl_resource_create(resource->client(), + &treeland_touchpad_settings_v1_interface, + resource->version(), + id); + if (!touchpadResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto touchpad = new TouchpadSettingsInterfaceV1(touchpadResource, seat); + s_touchpadSettings.append(touchpad); + + QObject::connect(touchpad, &QObject::destroyed, [touchpad]() { + s_touchpadSettings.removeOne(touchpad); + }); + + Q_EMIT q->touchpadSettingsCreated(touchpad); +} + +void TreelandInputManagerInterfaceV1Private::get_keyboard_settings(Resource *resource, uint32_t id, struct ::wl_resource *seat) +{ + if (!seat) { + wl_resource_post_error(resource->handle, 0, "seat resource is NULL!"); + return; + } + + if (!q->inputDeviceListTypes().testFlag(TreelandInputManagerInterfaceV1::DeviceType::Keyboard)) { + wl_resource_post_error(resource->handle, 0, "No Keyboard!"); + return; + } + + wl_resource *keyboardResource = wl_resource_create(resource->client(), + &treeland_keyboard_settings_v1_interface, + resource->version(), + id); + if (!keyboardResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto keyboard = new KeyboardSettingsInterfaceV1(keyboardResource, seat); + s_keyboardSettings.append(keyboard); + + QObject::connect(keyboard, &QObject::destroyed, [keyboard]() { + s_keyboardSettings.removeOne(keyboard); + }); + + Q_EMIT q->keyboardSettingsCreated(keyboard); +} + +TreelandInputManagerInterfaceV1::TreelandInputManagerInterfaceV1(QObject *parent) + : QObject(parent) + , d(new TreelandInputManagerInterfaceV1Private(this)) +{ + auto backend = WaylandServer::instance()->backend(); + connect(backend, + &WBackend::inputAdded, + this, + &TreelandInputManagerInterfaceV1::onInputAdded); + connect(backend, + &WBackend::inputRemoved, + this, + &TreelandInputManagerInterfaceV1::onInputRemoved); +} + +void TreelandInputManagerInterfaceV1::sendCapabilityAvailable(TreelandInputManagerInterfaceV1::DeviceTypes types) +{ + for (const auto &resource : d->resourceMap()) { + struct wlr_seat_client *seatClient = + wlr_seat_client_for_wl_client(WaylandServer::instance()->seat()->handle(), resource->client()); + if (!seatClient) + continue; + struct wl_resource *clientResource; + wl_resource_for_each(clientResource, &seatClient->resources) { + d->send_capability_available(resource->handle, types.toInt(), clientResource); + } + } +} + +void TreelandInputManagerInterfaceV1::sendCapabilityUnavailable(TreelandInputManagerInterfaceV1::DeviceTypes types) +{ + for (const auto &resource : d->resourceMap()) { + struct wlr_seat_client *seatClient = + wlr_seat_client_for_wl_client(WaylandServer::instance()->seat()->handle(), resource->client()); + if (!seatClient) + continue; + struct wl_resource *clientResource; + wl_resource_for_each(clientResource, &seatClient->resources) { + d->send_capability_unavailable(resource->handle, types.toInt(), clientResource); + } + } +} + +TreelandInputManagerInterfaceV1::~TreelandInputManagerInterfaceV1() = default; + +void TreelandInputManagerInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void TreelandInputManagerInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *TreelandInputManagerInterfaceV1::global() const +{ + return d->global(); +} + +TreelandInputManagerInterfaceV1::DeviceTypes TreelandInputManagerInterfaceV1::inputDeviceListTypes() const +{ + TreelandInputManagerInterfaceV1::DeviceTypes types; + const auto inputDevices = WaylandServer::instance()->backend()->inputDeviceList(); + for (WInputDevice *device : std::as_const(inputDevices)) { + types |= inputDeviceType(device); + } + + return types; +} + +TreelandInputManagerInterfaceV1::DeviceTypes TreelandInputManagerInterfaceV1::inputDeviceType(WInputDevice *input) const +{ + if (!wlr_input_device_is_libinput(input->handle())) { + return TreelandInputManagerInterfaceV1::DeviceType::Unknown; + } + + if (input->type() == WInputDevice::Type::Keyboard) { + return TreelandInputManagerInterfaceV1::DeviceType::Keyboard; + } + + TreelandInputManagerInterfaceV1::DeviceTypes types; + struct udev_device *device = + libinput_device_get_udev_device(wlr_libinput_get_device_handle(input->handle())); + if (udev_device_get_property_value(device, "ID_INPUT_MOUSE")) { + types |= TreelandInputManagerInterfaceV1::DeviceType::Mouse; + } + + if (udev_device_get_property_value(device, "ID_INPUT_TOUCHPAD")) { + types |= TreelandInputManagerInterfaceV1::DeviceType::TouchPad; + types |= TreelandInputManagerInterfaceV1::DeviceType::Mouse; + } + + return types; +} + +QByteArrayView TreelandInputManagerInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} + +void TreelandInputManagerInterfaceV1::onInputAdded(WInputDevice *input) +{ + TreelandInputManagerInterfaceV1::DeviceTypes types; + const auto inputDevices = WaylandServer::instance()->backend()->inputDeviceList(); + for (WInputDevice *device : std::as_const(inputDevices)) { + if (device == input) { + continue; + } + + types |= inputDeviceType(device); + } + + TreelandInputManagerInterfaceV1::DeviceTypes type = inputDeviceType(input); + if (!types.testAnyFlags(type)) { + for (const auto &resource : d->resourceMap()) { + struct wlr_seat_client *seatClient = + wlr_seat_client_for_wl_client(WaylandServer::instance()->seat()->handle(), resource->client()); + if (!seatClient) + continue; + struct wl_resource *clientResource; + wl_resource_for_each(clientResource, &seatClient->resources) { + d->send_capability_available(resource->handle, type.toInt(), clientResource); + } + } + } +} + +void TreelandInputManagerInterfaceV1::onInputRemoved(WInputDevice *input) +{ + TreelandInputManagerInterfaceV1::DeviceTypes types; + const auto inputDevices = WaylandServer::instance()->backend()->inputDeviceList(); + for (WInputDevice *device : std::as_const(inputDevices)) { + if (device == input) { + continue; + } + + types |= inputDeviceType(device); + } + + TreelandInputManagerInterfaceV1::DeviceTypes type = inputDeviceType(input); + if (!types.testAnyFlags(type)) { + for (const auto &resource : d->resourceMap()) { + struct wlr_seat_client *seatClient = + wlr_seat_client_for_wl_client(WaylandServer::instance()->seat()->handle(), resource->client()); + if (!seatClient) + continue; + struct wl_resource *clientResource; + wl_resource_for_each(clientResource, &seatClient->resources) { + d->send_capability_unavailable(resource->handle, type.toInt(), clientResource); + } + } + } +} + +class PointerDeviceConfigurationV1Private : public QtWaylandServer::treeland_pointer_device_configuration_v1 +{ +public: + PointerDeviceConfigurationV1Private(PointerDeviceConfigurationV1 *_q, + wl_resource *resource, + wl_resource *_seat); + + PointerDeviceConfigurationV1 *q = nullptr; + wl_resource *seat = nullptr; + + PointerDeviceConfigurationV1::ChangeFlags pendingChanges = + PointerDeviceConfigurationV1::NoChange; + + PointerDeviceConfigurationV1::FeatureFlags features = PointerDeviceConfigurationV1::NoFeature; + double scrollFactor = 0; + PointerDeviceConfigurationV1::HandedMode handedMode = PointerDeviceConfigurationV1::Right; + double accelSpeed = 0; + PointerDeviceConfigurationV1::AccelerationProfile accelerationProfile = PointerDeviceConfigurationV1::None; + PointerDeviceConfigurationV1::SendEventsModes sendEventsMode = PointerDeviceConfigurationV1::Enabled; + bool naturalScroll = false; + bool disableWhileTyping = false; + bool tapToClick = false; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void set_scroll_factor(Resource *resource, wl_fixed_t factor) override; + void set_handed_mode(Resource *resource, uint32_t mode) override; + void set_accel_speed(Resource *resource, wl_fixed_t accel_speed) override; + void set_acceleration_profile(Resource *resource, uint32_t profile) override; + void set_send_events_mode(Resource *resource, uint32_t mode) override; + void set_natural_scroll(Resource *resource, uint32_t state) override; + void set_disable_while_typing(Resource *resource, uint32_t state) override; + void set_tap_to_click(Resource *resource, uint32_t state) override; + void apply(Resource *resource) override; +}; + +PointerDeviceConfigurationV1Private::PointerDeviceConfigurationV1Private(PointerDeviceConfigurationV1 *_q, + wl_resource *resource, + wl_resource *_seat) + : QtWaylandServer::treeland_pointer_device_configuration_v1(resource) + , q(_q) + , seat(_seat) +{ +} + +void PointerDeviceConfigurationV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void PointerDeviceConfigurationV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void PointerDeviceConfigurationV1Private::set_scroll_factor([[maybe_unused]] Resource *resource, + wl_fixed_t factor) +{ + scrollFactor = wl_fixed_to_double(factor); + pendingChanges |= PointerDeviceConfigurationV1::ScrollFactorChanged; +} + +void PointerDeviceConfigurationV1Private::set_handed_mode([[maybe_unused]] Resource *resource, + uint32_t mode) +{ + switch (mode) { + case TREELAND_POINTER_DEVICE_CONFIGURATION_V1_HANDED_MODE_RIGHT: + handedMode = PointerDeviceConfigurationV1::Right; + break; + case TREELAND_POINTER_DEVICE_CONFIGURATION_V1_HANDED_MODE_LEFT: + handedMode = PointerDeviceConfigurationV1::Left; + break; + default: + qCCritical(lcTlInputManager, "unknown mode in set_handed_mode request"); + return; + } + pendingChanges |= PointerDeviceConfigurationV1::HandedModeChanged; +} + +void PointerDeviceConfigurationV1Private::set_accel_speed([[maybe_unused]] Resource *resource, + wl_fixed_t speed) +{ + accelSpeed = wl_fixed_to_double(speed); + pendingChanges |= PointerDeviceConfigurationV1::AccelSpeedChanged; +} + +void PointerDeviceConfigurationV1Private::set_acceleration_profile([[maybe_unused]] Resource *resource, + uint32_t profile) +{ + if (!treeland_pointer_device_configuration_v1_acceleration_profile_is_valid(profile, resource->version())) { + qCCritical(lcTlInputManager, "unknown acceleration profile"); + return; + } + + accelerationProfile = PointerDeviceConfigurationV1::AccelerationProfile(profile); + pendingChanges |= PointerDeviceConfigurationV1::AccelerationProfileChanged; +} + +void PointerDeviceConfigurationV1Private::set_send_events_mode([[maybe_unused]] Resource *resource, + uint32_t mode) +{ + if (!treeland_pointer_device_configuration_v1_send_events_mode_is_valid(mode, resource->version())) { + qCCritical(lcTlInputManager, "unknown send_events_mode"); + return; + } + + sendEventsMode = PointerDeviceConfigurationV1::SendEventsModes(mode); + pendingChanges |= PointerDeviceConfigurationV1::SendEventsModeChanged; +} + +void PointerDeviceConfigurationV1Private::set_natural_scroll([[maybe_unused]] Resource *resource, + uint32_t state) +{ + switch (state) { + case TREELAND_INPUT_MANAGER_V1_STATE_ENABLED: + naturalScroll = true; + break; + case TREELAND_INPUT_MANAGER_V1_STATE_DISABLED: + naturalScroll = false; + break; + default: + qCCritical(lcTlInputManager, "unknown state in set_natural_scroll request"); + return; + } + pendingChanges |= PointerDeviceConfigurationV1::NaturalScrollChanged; +} + +void PointerDeviceConfigurationV1Private::set_disable_while_typing([[maybe_unused]] Resource *resource, + uint32_t state) +{ + switch (state) { + case TREELAND_INPUT_MANAGER_V1_STATE_ENABLED: + disableWhileTyping = true; + break; + case TREELAND_INPUT_MANAGER_V1_STATE_DISABLED: + disableWhileTyping = false; + break; + default: + qCCritical(lcTlInputManager, "unknown state in set_disable_while_typing request"); + return; + } + pendingChanges |= PointerDeviceConfigurationV1::DisableWhileTypingChanged; +} + +void PointerDeviceConfigurationV1Private::set_tap_to_click([[maybe_unused]] Resource *resource, + uint32_t state) +{ + switch (state) { + case TREELAND_INPUT_MANAGER_V1_STATE_ENABLED: + tapToClick = true; + break; + case TREELAND_INPUT_MANAGER_V1_STATE_DISABLED: + tapToClick = false; + break; + default: + qCCritical(lcTlInputManager, "unknown state in set_tap_to_click request"); + return; + } + pendingChanges |= PointerDeviceConfigurationV1::TapToClickChanged; +} + +void PointerDeviceConfigurationV1Private::apply([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->applied(pendingChanges); + pendingChanges = PointerDeviceConfigurationV1::NoChange; +} + +PointerDeviceConfigurationV1::PointerDeviceConfigurationV1(wl_resource *resource, + wl_resource *seat, + QObject *parent) + : QObject(parent) + , d(new PointerDeviceConfigurationV1Private(this, resource, seat)) +{ +} + +PointerDeviceConfigurationV1::~PointerDeviceConfigurationV1() = default; + +void PointerDeviceConfigurationV1::sendFeature(FeatureFlags features, bool force) +{ + if (!force && d->features == features) { + return; + } + + d->send_feature(features.toInt()); + d->features = features; +} + +void PointerDeviceConfigurationV1::sendScrollFactor(double factor, bool force) +{ + if (!force && d->scrollFactor == factor) { + return; + } + + d->send_scroll_factor(wl_fixed_from_double(factor)); + d->scrollFactor = factor; +} + +void PointerDeviceConfigurationV1::sendHandedMode(HandedMode mode, bool force) +{ + if (!force && d->handedMode == mode) { + return; + } + + d->send_handed_mode(mode); + d->handedMode = mode; +} + +void PointerDeviceConfigurationV1::sendAccelSpeed(double speed, bool force) +{ + if (!force && d->accelSpeed == speed) { + return; + } + + d->send_accel_speed(wl_fixed_from_double(speed)); + d->accelSpeed = speed; +} + +void PointerDeviceConfigurationV1::sendAccelerationProfile(AccelerationProfile profile, bool force) +{ + if (!force && d->accelerationProfile == profile) { + return; + } + + d->send_acceleration_profile(profile); + d->accelerationProfile = profile; +} + +void PointerDeviceConfigurationV1::sendSendEventsMode(SendEventsModes mode, bool force) +{ + if (!force && d->sendEventsMode == mode) { + return; + } + + d->send_send_events_mode(mode); + d->sendEventsMode = mode; +} + +void PointerDeviceConfigurationV1::sendNaturalScroll(bool enable, bool force) +{ + if (!force && d->naturalScroll == enable) { + return; + } + + d->send_natural_scroll(enable ? + TREELAND_INPUT_MANAGER_V1_STATE_ENABLED : + TREELAND_INPUT_MANAGER_V1_STATE_DISABLED); + d->naturalScroll = enable; +} + +void PointerDeviceConfigurationV1::sendDisableWhileTyping(bool enable, bool force) +{ + if (!force && d->disableWhileTyping == enable) { + return; + } + + d->send_disable_while_typing(enable ? + TREELAND_INPUT_MANAGER_V1_STATE_ENABLED : + TREELAND_INPUT_MANAGER_V1_STATE_DISABLED); + d->disableWhileTyping = enable; +} + +void PointerDeviceConfigurationV1::sendTapToClick(bool enable, bool force) +{ + if (!force && d->tapToClick == enable) { + return; + } + + d->send_tap_to_click(enable ? + TREELAND_INPUT_MANAGER_V1_STATE_ENABLED : + TREELAND_INPUT_MANAGER_V1_STATE_DISABLED); + d->tapToClick = enable; +} + +void PointerDeviceConfigurationV1::sendFailed() +{ + d->send_failed(); +} + +void PointerDeviceConfigurationV1::sendDone(uint32_t serial) +{ + d->send_done(serial); +} + +double PointerDeviceConfigurationV1::scrollFactor() const +{ + return d->scrollFactor; +} + +PointerDeviceConfigurationV1::HandedMode PointerDeviceConfigurationV1::handedMode() const +{ + return d->handedMode; +} + +double PointerDeviceConfigurationV1::accelSpeed() const +{ + return d->accelSpeed; +} + +PointerDeviceConfigurationV1::AccelerationProfile PointerDeviceConfigurationV1::accelerationProfile() const +{ + return d->accelerationProfile; +} + +PointerDeviceConfigurationV1::SendEventsModes PointerDeviceConfigurationV1::sendEventsMode() const +{ + return d->sendEventsMode; +} + +bool PointerDeviceConfigurationV1::naturalScroll() const +{ + return d->naturalScroll; +} + +bool PointerDeviceConfigurationV1::disableWhileTyping() const +{ + return d->disableWhileTyping; +} + +bool PointerDeviceConfigurationV1::tapToClick() const +{ + return d->tapToClick; +} + +wl_resource *PointerDeviceConfigurationV1::seat() const +{ + return d->seat; +} + +WSeat *PointerDeviceConfigurationV1::wSeat() const +{ + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat()); + Q_ASSERT_X(seat_client, __func__, "PointerDeviceConfigurationV1 get wlr_seat_client failed."); + return WSeat::fromHandle(seat_client->seat); +} + +class MouseSettingsInterfaceV1Private : public QtWaylandServer::treeland_mouse_settings_v1 +{ +public: + MouseSettingsInterfaceV1Private(MouseSettingsInterfaceV1 *_q, + wl_resource *_resource, + wl_resource *_seat); + + MouseSettingsInterfaceV1 *q = nullptr; + wl_resource *seat = nullptr; + PointerDeviceConfigurationV1 *activeConfig = nullptr; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void get_pointer_configuration(Resource *resource, uint32_t id, uint32_t serial) override; +}; + +MouseSettingsInterfaceV1Private::MouseSettingsInterfaceV1Private(MouseSettingsInterfaceV1 *_q, + wl_resource *resource, + wl_resource *_seat) + : QtWaylandServer::treeland_mouse_settings_v1(resource) + , q(_q) + , seat(_seat) +{ +} + +void MouseSettingsInterfaceV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void MouseSettingsInterfaceV1Private::destroy(Resource *resource) +{ + if (activeConfig) { + wl_resource_post_error(resource->handle, 0, + "destroying treeland_mouse_settings_v1 while pointer_device_configuration_v1 still exists"); + } + + wl_resource_destroy(resource->handle); +} + +void MouseSettingsInterfaceV1Private::get_pointer_configuration(Resource *resource, + uint32_t id, + [[maybe_unused]] uint32_t serial) +{ + if (activeConfig) { + wl_resource_post_error(resource->handle, 0, + "a treeland_pointer_device_configuration_v1 already exists for this treeland_mouse_settings_v1"); + return; + } + + wl_resource *configResource = wl_resource_create(resource->client(), + &treeland_pointer_device_configuration_v1_interface, + resource->version(), + id); + if (!configResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto *config = new PointerDeviceConfigurationV1(configResource, seat); + activeConfig = config; + + QObject::connect(config, &QObject::destroyed, q, [this]() { + activeConfig = nullptr; + }); + + Q_EMIT q->pointerDeviceConfigurationCreated(config); +} + +MouseSettingsInterfaceV1::MouseSettingsInterfaceV1(wl_resource *resource, + wl_resource *seat, + QObject *parent) + : QObject(parent) + , d(new MouseSettingsInterfaceV1Private(this, resource, seat)) +{ +} + +MouseSettingsInterfaceV1::~MouseSettingsInterfaceV1() = default; + +wl_resource *MouseSettingsInterfaceV1::seat() const +{ + return d->seat; +} + +WSeat *MouseSettingsInterfaceV1::wSeat() const +{ + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat()); + Q_ASSERT_X(seat_client, __func__, "MouseSettingsInterfaceV1 get wlr_seat_client failed."); + return WSeat::fromHandle(seat_client->seat); +} + +class TouchpadSettingsInterfaceV1Private : public QtWaylandServer::treeland_touchpad_settings_v1 +{ +public: + TouchpadSettingsInterfaceV1Private(TouchpadSettingsInterfaceV1 *_q, + wl_resource *resource, + wl_resource *_seat); + + TouchpadSettingsInterfaceV1 *q = nullptr; + wl_resource *seat = nullptr; + PointerDeviceConfigurationV1 *activeConfig = nullptr; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void get_pointer_configuration(Resource *resource, uint32_t id, uint32_t serial) override; +}; + +TouchpadSettingsInterfaceV1Private::TouchpadSettingsInterfaceV1Private(TouchpadSettingsInterfaceV1 *_q, + wl_resource *resource, + wl_resource *_seat) + : QtWaylandServer::treeland_touchpad_settings_v1(resource) + , q(_q) + , seat(_seat) +{ +} + +void TouchpadSettingsInterfaceV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void TouchpadSettingsInterfaceV1Private::destroy(Resource *resource) +{ + if (activeConfig) { + wl_resource_post_error(resource->handle, 0, + "destroying treeland_touchpad_settings_v1 while pointer_device_configuration_v1 still exists"); + } + + wl_resource_destroy(resource->handle); +} + +void TouchpadSettingsInterfaceV1Private::get_pointer_configuration(Resource *resource, + uint32_t id, + [[maybe_unused]] uint32_t serial) +{ + if (activeConfig) { + wl_resource_post_error(resource->handle, 0, + "a treeland_pointer_device_configuration_v1 already exists for this treeland_touchpad_settings_v1"); + return; + } + + wl_resource *configResource = wl_resource_create(resource->client(), + &treeland_pointer_device_configuration_v1_interface, + resource->version(), + id); + if (!configResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto *config = new PointerDeviceConfigurationV1(configResource, seat); + activeConfig = config; + + QObject::connect(config, &QObject::destroyed, q, [this]() { + activeConfig = nullptr; + }); + + Q_EMIT q->pointerDeviceConfigurationCreated(config); +} + +TouchpadSettingsInterfaceV1::TouchpadSettingsInterfaceV1(wl_resource *resource, + wl_resource *seat, + QObject *parent) + : QObject(parent) + , d(new TouchpadSettingsInterfaceV1Private(this, resource, seat)) +{ +} + +TouchpadSettingsInterfaceV1::~TouchpadSettingsInterfaceV1() = default; + +wl_resource *TouchpadSettingsInterfaceV1::seat() const +{ + return d->seat; +} + +WSeat *TouchpadSettingsInterfaceV1::wSeat() const +{ + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat()); + Q_ASSERT_X(seat_client, __func__, "TouchpadSettingsInterfaceV1 get wlr_seat_client failed."); + return WSeat::fromHandle(seat_client->seat); +} + +class KeyboardSettingsInterfaceV1Private : public QtWaylandServer::treeland_keyboard_settings_v1 +{ +public: + KeyboardSettingsInterfaceV1Private(KeyboardSettingsInterfaceV1 *_q, + wl_resource *resource, + wl_resource *_seat); + + KeyboardSettingsInterfaceV1 *q = nullptr; + wl_resource *seat = nullptr; + + KeyboardSettingsInterfaceV1::ChangeFlags pendingChanges = + KeyboardSettingsInterfaceV1::NoChange; + + KeyboardSettingsInterfaceV1::FeatureFlags features = KeyboardSettingsInterfaceV1::NoFeature; + int32_t repeatRate = 0; + int32_t repeatDelay = 0; + bool numLock = false; + QString xkbLayout; + QString xkbModel; + QString xkbVariant; + QString xkbOptions; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void set_repeat(Resource *resource, int32_t rate, int32_t delay) override; + void set_num_lock(Resource *resource, uint32_t state) override; + void apply(Resource *resource) override; + void set_xkb_rules(Resource *resource, + const QString &layout, + const QString &model, + const QString &variant, + const QString &options) override; +}; + +KeyboardSettingsInterfaceV1Private::KeyboardSettingsInterfaceV1Private(KeyboardSettingsInterfaceV1 *_q, + wl_resource *resource, + wl_resource *_seat) + : QtWaylandServer::treeland_keyboard_settings_v1(resource) + , q(_q) + , seat(_seat) +{ +} + +void KeyboardSettingsInterfaceV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void KeyboardSettingsInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void KeyboardSettingsInterfaceV1Private::set_repeat([[maybe_unused]] Resource *resource, + int32_t rate, + int32_t delay) +{ + repeatRate = rate; + repeatDelay = delay; + pendingChanges |= KeyboardSettingsInterfaceV1::RepeatChanged; +} + +void KeyboardSettingsInterfaceV1Private::set_num_lock([[maybe_unused]] Resource *resource, + uint32_t state) +{ + switch (state) { + case TREELAND_KEYBOARD_SETTINGS_V1_TOGGLE_STATE_ON: + numLock = true; + break; + case TREELAND_KEYBOARD_SETTINGS_V1_TOGGLE_STATE_OFF: + numLock = false; + break; + default: + qCCritical(lcTlInputManager, "unknown state in set_num_lock request"); + return; + } + pendingChanges |= KeyboardSettingsInterfaceV1::NumLockChanged; +} + +void KeyboardSettingsInterfaceV1Private::apply([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->applied(pendingChanges); + pendingChanges = KeyboardSettingsInterfaceV1::NoChange; +} + +void KeyboardSettingsInterfaceV1Private::set_xkb_rules([[maybe_unused]] Resource *resource, + const QString &layout, + const QString &model, + const QString &variant, + const QString &options) +{ + xkbLayout = normalizeNullableXkbString(layout); + xkbModel = normalizeNullableXkbString(model); + xkbVariant = normalizeNullableXkbString(variant); + xkbOptions = normalizeNullableXkbString(options); + pendingChanges |= KeyboardSettingsInterfaceV1::XkbRulesChanged; +} + +KeyboardSettingsInterfaceV1::KeyboardSettingsInterfaceV1(wl_resource *resource, + wl_resource *seat, + QObject *parent) + : QObject(parent) + , d(new KeyboardSettingsInterfaceV1Private(this, resource, seat)) +{ +} + +KeyboardSettingsInterfaceV1::~KeyboardSettingsInterfaceV1() = default; + +void KeyboardSettingsInterfaceV1::sendFeature(FeatureFlags features, bool force) +{ + if (!force && d->features == features) { + return; + } + + d->send_feature(features.toInt()); + d->features = features; +} + +void KeyboardSettingsInterfaceV1::sendRepeat(int32_t rate, int32_t delay, bool force) +{ + if (!force && d->repeatRate == rate && d->repeatDelay == delay) { + return; + } + + d->send_repeat(rate, delay); + d->repeatRate = rate; + d->repeatDelay = delay; +} + +void KeyboardSettingsInterfaceV1::sendNumLock(bool enabled, bool force) +{ + if (!force && d->numLock == enabled) { + return; + } + + d->send_num_lock(enabled ? + TREELAND_KEYBOARD_SETTINGS_V1_TOGGLE_STATE_ON : + TREELAND_KEYBOARD_SETTINGS_V1_TOGGLE_STATE_OFF); + d->numLock = enabled; +} + +void KeyboardSettingsInterfaceV1::sendXkbRules(const QString &layout, + const QString &model, + const QString &variant, + const QString &options, + bool force) +{ + const QString normalizedLayout = normalizeNullableXkbString(layout); + const QString normalizedModel = normalizeNullableXkbString(model); + const QString normalizedVariant = normalizeNullableXkbString(variant); + const QString normalizedOptions = normalizeNullableXkbString(options); + + if (d->resource()->version() < XkbVersion + || (!force + && d->xkbLayout == normalizedLayout + && d->xkbModel == normalizedModel + && d->xkbVariant == normalizedVariant + && d->xkbOptions == normalizedOptions)) { + return; + } + + d->send_xkb_rules(normalizedLayout, normalizedModel, normalizedVariant, normalizedOptions); + d->xkbLayout = normalizedLayout; + d->xkbModel = normalizedModel; + d->xkbVariant = normalizedVariant; + d->xkbOptions = normalizedOptions; +} + +void KeyboardSettingsInterfaceV1::sendFailed() +{ + d->send_failed(); +} + +void KeyboardSettingsInterfaceV1::sendDone() +{ + d->send_done(); +} + +int32_t KeyboardSettingsInterfaceV1::repeatRate() const +{ + return d->repeatRate; +} + +int32_t KeyboardSettingsInterfaceV1::repeatDelay() const +{ + return d->repeatDelay; +} + +bool KeyboardSettingsInterfaceV1::numLock() const +{ + return d->numLock; +} + +const QString &KeyboardSettingsInterfaceV1::xkbLayout() const +{ + return d->xkbLayout; +} + +const QString &KeyboardSettingsInterfaceV1::xkbModel() const +{ + return d->xkbModel; +} + +const QString &KeyboardSettingsInterfaceV1::xkbVariant() const +{ + return d->xkbVariant; +} + +const QString &KeyboardSettingsInterfaceV1::xkbOptions() const +{ + return d->xkbOptions; +} + +wl_resource *KeyboardSettingsInterfaceV1::seat() const +{ + return d->seat; +} + +WSeat *KeyboardSettingsInterfaceV1::wSeat() const +{ + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(seat()); + Q_ASSERT_X(seat_client, __func__, "KeyboardSettingsInterfaceV1 get wlr_seat_client failed."); + return WSeat::fromHandle(seat_client->seat); +} diff --git a/src/modules/input-manager/inputmanagerinterfacev1.h b/src/modules/input-manager/inputmanagerinterfacev1.h new file mode 100644 index 0000000000..b6b45631be --- /dev/null +++ b/src/modules/input-manager/inputmanagerinterfacev1.h @@ -0,0 +1,270 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class PointerDeviceConfigurationV1; +class MouseSettingsInterfaceV1; +class TouchpadSettingsInterfaceV1; +class KeyboardSettingsInterfaceV1; +class TreelandInputManagerInterfaceV1Private; + +class TreelandInputManagerInterfaceV1 : public QObject, public WServerInterface +{ + Q_OBJECT +public: + enum class DeviceType { + Unknown = 0, + Mouse = 1 << 0, + TouchPad = 1 << 1, + Keyboard = 1 << 2, + }; + Q_DECLARE_FLAGS(DeviceTypes, DeviceType) + Q_FLAG(DeviceTypes) + + explicit TreelandInputManagerInterfaceV1(QObject *parent = nullptr); + ~TreelandInputManagerInterfaceV1() override; + + void sendCapabilityAvailable(TreelandInputManagerInterfaceV1::DeviceTypes types); + void sendCapabilityUnavailable(TreelandInputManagerInterfaceV1::DeviceTypes types); + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 2; + +Q_SIGNALS: + void mouseSettingsCreated(MouseSettingsInterfaceV1 *interface); + void touchpadSettingsCreated(TouchpadSettingsInterfaceV1 *interface); + void keyboardSettingsCreated(KeyboardSettingsInterfaceV1 *interface); + +private Q_SLOTS: + void onInputAdded(WInputDevice *input); + void onInputRemoved(WInputDevice *input); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + TreelandInputManagerInterfaceV1::DeviceTypes inputDeviceListTypes() const; + TreelandInputManagerInterfaceV1::DeviceTypes inputDeviceType(WInputDevice *input) const; + +private: + friend class TreelandInputManagerInterfaceV1Private; + std::unique_ptr d; +}; +Q_DECLARE_OPERATORS_FOR_FLAGS(TreelandInputManagerInterfaceV1::DeviceTypes) + +class PointerDeviceConfigurationV1Private; +class PointerDeviceConfigurationV1 : public QObject +{ + Q_OBJECT +public: + ~PointerDeviceConfigurationV1() override; + + enum FeatureFlag { + NoFeature = 0, + ScrollFactor = 1 << 0, + HandMode = 1 << 1, + AccelSpeed = 1 << 2, + AccelProfile = 1 << 3, + EventsMode = 1 << 4, + NaturalScroll = 1 << 5, + DisableWhileTyping = 1 << 6, + TapToClick = 1 << 7, + }; + Q_DECLARE_FLAGS(FeatureFlags, FeatureFlag) + Q_FLAG(FeatureFlags) + + enum ChangeFlag { + NoChange = 0, + ScrollFactorChanged = 1 << 0, + HandedModeChanged = 1 << 1, + AccelSpeedChanged = 1 << 2, + AccelerationProfileChanged = 1 << 3, + SendEventsModeChanged = 1 << 4, + NaturalScrollChanged = 1 << 5, + DisableWhileTypingChanged = 1 << 6, + TapToClickChanged = 1 << 7, + }; + Q_DECLARE_FLAGS(ChangeFlags, ChangeFlag) + Q_FLAG(ChangeFlags) + + enum HandedMode { + Right, + Left, + }; + + enum AccelerationProfile { + None = 0, + Flat = 1 << 0, + Adaptive = 1 << 1, + Custom = 1 << 2, + }; + + enum SendEventsMode { + Enabled = 0, + Disabled = 1 << 0, + DisabledOnExternalMouse = 1 << 1, + }; + Q_DECLARE_FLAGS(SendEventsModes, SendEventsMode) + Q_FLAG(SendEventsModes) + + void sendFeature(FeatureFlags features, bool force = false); + void sendScrollFactor(double factor, bool force = false); + void sendHandedMode(HandedMode mode, bool force = false); + void sendAccelSpeed(double speed, bool force = false); + void sendAccelerationProfile(AccelerationProfile profile, bool force = false); + void sendSendEventsMode(SendEventsModes mode, bool force = false); + void sendNaturalScroll(bool enable, bool force = false); + void sendDisableWhileTyping(bool enable, bool force = false); + void sendTapToClick(bool enable, bool force = false); + void sendFailed(); + void sendDone(uint32_t serial); + + double scrollFactor() const; + HandedMode handedMode() const; + double accelSpeed() const; + AccelerationProfile accelerationProfile() const; + SendEventsModes sendEventsMode() const; + bool naturalScroll() const; + bool disableWhileTyping() const; + bool tapToClick() const; + + wl_resource *seat() const; + WSeat *wSeat() const; + +Q_SIGNALS: + void applied(ChangeFlags changes); + +private: + explicit PointerDeviceConfigurationV1(wl_resource *resource, + wl_resource *seat, + QObject *parent = nullptr); + +private: + friend class MouseSettingsInterfaceV1Private; + friend class TouchpadSettingsInterfaceV1Private; + std::unique_ptr d; +}; +Q_DECLARE_OPERATORS_FOR_FLAGS(PointerDeviceConfigurationV1::FeatureFlags) +Q_DECLARE_OPERATORS_FOR_FLAGS(PointerDeviceConfigurationV1::ChangeFlags) + +class MouseSettingsInterfaceV1Private; +class MouseSettingsInterfaceV1 : public QObject +{ + Q_OBJECT +public: + ~MouseSettingsInterfaceV1() override; + + wl_resource *seat() const; + WSeat *wSeat() const; + +Q_SIGNALS: + void pointerDeviceConfigurationCreated(PointerDeviceConfigurationV1 *config); + +private: + explicit MouseSettingsInterfaceV1(wl_resource *resource, + wl_resource *seat, + QObject *parent = nullptr); + +private: + friend class TreelandInputManagerInterfaceV1Private; + std::unique_ptr d; +}; + +class TouchpadSettingsInterfaceV1Private; +class TouchpadSettingsInterfaceV1 : public QObject +{ + Q_OBJECT +public: + ~TouchpadSettingsInterfaceV1() override; + + wl_resource *seat() const; + WSeat *wSeat() const; + +Q_SIGNALS: + void pointerDeviceConfigurationCreated(PointerDeviceConfigurationV1 *config); + +private: + explicit TouchpadSettingsInterfaceV1(wl_resource *resource, + wl_resource *seat, + QObject *parent = nullptr); + +private: + friend class TreelandInputManagerInterfaceV1Private; + std::unique_ptr d; +}; + +class KeyboardSettingsInterfaceV1Private; +class KeyboardSettingsInterfaceV1 : public QObject +{ + Q_OBJECT +public: + static constexpr int XkbVersion = 2; + + ~KeyboardSettingsInterfaceV1() override; + + enum FeatureFlag { + NoFeature = 0, + NumLock = 1 << 0, + }; + Q_DECLARE_FLAGS(FeatureFlags, FeatureFlag) + Q_FLAG(FeatureFlags) + + enum ChangeFlag { + NoChange = 0, + RepeatChanged = 1 << 0, + NumLockChanged = 1 << 1, + XkbRulesChanged = 1 << 2, + }; + Q_DECLARE_FLAGS(ChangeFlags, ChangeFlag) + Q_FLAG(ChangeFlags) + + void sendFeature(FeatureFlags features, bool force = false); + void sendRepeat(int32_t rate, int32_t delay, bool force = false); + void sendNumLock(bool enabled, bool force = false); + void sendXkbRules(const QString &layout, + const QString &model, + const QString &variant, + const QString &options, + bool force = false); + void sendFailed(); + void sendDone(); + + int32_t repeatRate() const; + int32_t repeatDelay() const; + bool numLock() const; + const QString &xkbLayout() const; + const QString &xkbModel() const; + const QString &xkbVariant() const; + const QString &xkbOptions() const; + + wl_resource *seat() const; + WSeat *wSeat() const; + +Q_SIGNALS: + void applied(ChangeFlags changes); + +private: + explicit KeyboardSettingsInterfaceV1(wl_resource *resource, + wl_resource *seat, + QObject *parent = nullptr); + +private: + friend class TreelandInputManagerInterfaceV1Private; + std::unique_ptr d; +}; +Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardSettingsInterfaceV1::FeatureFlags) +Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardSettingsInterfaceV1::ChangeFlags) diff --git a/src/modules/item-selector/CMakeLists.txt b/src/modules/item-selector/CMakeLists.txt new file mode 100644 index 0000000000..89190b7761 --- /dev/null +++ b/src/modules/item-selector/CMakeLists.txt @@ -0,0 +1,7 @@ +impl_treeland( + NAME + module-itemselector + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/item-selector/itemselector.h + ${CMAKE_SOURCE_DIR}/src/modules/item-selector/itemselector.cpp +) diff --git a/src/modules/item-selector/itemselector.cpp b/src/modules/item-selector/itemselector.cpp new file mode 100644 index 0000000000..99c1d56c34 --- /dev/null +++ b/src/modules/item-selector/itemselector.cpp @@ -0,0 +1,174 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "itemselector.h" + +#include + +#include +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +ItemSelector::ItemSelector(QQuickItem *parent) + : QQuickItem(parent) +{ + setAcceptHoverEvents(true); + setFocus(false); + setFocusPolicy(Qt::NoFocus); + setKeepMouseGrab(true); + QQuickItemPrivate::get(this)->anchors()->setFill(parentItem()); + m_defaultFilter = [](QQuickItem *item, ItemSelector::ItemTypes selectionHint) { + if (!item->isVisible()) + return false; + if (qobject_cast(item) && selectionHint.testFlag(ItemType::Output)) { + return true; + } else if (qobject_cast(item) + && selectionHint.testFlag(ItemType::Surface)) { + return true; + } else if (qobject_cast(item) && selectionHint.testFlag(ItemType::Window)) { + return true; + } else { + return false; + } + }; +} + +ItemSelector::~ItemSelector() { } + +QRectF ItemSelector::selectionRegion() const +{ + return m_selectionRegion; +} + +void ItemSelector::setSelectionRegion(const QRectF &newSelectionRegion) +{ + if (m_selectionRegion == newSelectionRegion) + return; + m_selectionRegion = newSelectionRegion; + Q_EMIT selectionRegionChanged(); +} + +QQuickItem *ItemSelector::hoveredItem() const +{ + return m_hoveredItem; +} + +WOutputItem *ItemSelector::outputItem() const +{ + return m_outputItem; +} + +void ItemSelector::setHoveredItem(QQuickItem *newHoveredItem) +{ + if (m_hoveredItem == newHoveredItem) + return; + m_hoveredItem = newHoveredItem; + Q_EMIT hoveredItemChanged(); +} + +ItemSelector::ItemTypes ItemSelector::selectionTypeHint() const +{ + return m_selectionTypeHint; +} + +void ItemSelector::disableDefaultFilter(bool disable) +{ + if (m_defaultFilterEnabled != disable) + return; + m_defaultFilterEnabled = !disable; + updateSelectableItems(); +} + +void ItemSelector::addCustomFilter( + std::function filter) +{ + m_customFilters.append(filter); + updateSelectableItems(); +} + +void ItemSelector::clearCustomFilter() +{ + m_customFilters.clear(); + updateSelectableItems(); +} + +void ItemSelector::setSelectionTypeHint(ItemTypes newSelectionTypeHint) +{ + if (m_selectionTypeHint == newSelectionTypeHint) + return; + m_selectionTypeHint = newSelectionTypeHint; + updateSelectableItems(); + Q_EMIT selectionTypeHintChanged(); +} + +void ItemSelector::updateSelectableItems() +{ + if (!window()) + return; + auto renderWindow = qobject_cast(window()); + m_selectableItems = WOutputRenderWindow::paintOrderItemList( + renderWindow->contentItem(), + [this](QQuickItem *item) -> bool { + if (auto viewport = qobject_cast(item)) { + m_outputItems.append(viewport); + } + if (m_defaultFilterEnabled && !m_defaultFilter(item, m_selectionTypeHint)) { + return false; + } + for (const auto &filter : std::as_const(m_customFilters)) { + if (filter && !filter(item, m_selectionTypeHint)) + return false; + } + return true; + }); + checkHoveredItem(mapFromScene(QCursor::pos())); +} + +void ItemSelector::hoverMoveEvent(QHoverEvent *event) +{ + checkHoveredItem(event->position()); +} + +void ItemSelector::checkHoveredItem(QPointF pos) +{ + decltype(m_selectableItems.crbegin()) it; + for (it = m_selectableItems.crbegin(); it != m_selectableItems.crend(); it++) { + if (!*it) + continue; + auto itemRect = (*it)->mapRectToItem(this, (*it)->boundingRect()); + if (itemRect.contains(pos)) { + setHoveredItem(*it); + setSelectionRegion(itemRect); + break; + } + } + if (it == m_selectableItems.crend()) { + setHoveredItem(nullptr); + setSelectionRegion({}); + } + for (const auto &item : std::as_const(m_outputItems)) { + auto itemRect = item->mapRectToItem(this, item->boundingRect()); + if (itemRect.contains(pos)) { + m_outputItem = item; + break; + } + } +} + +void ItemSelector::itemChange(ItemChange change, const ItemChangeData &data) +{ + switch (change) { + case ItemParentHasChanged: + QQuickItemPrivate::get(this)->anchors()->setFill(data.item); + break; + case ItemSceneChange: + if (data.window) + updateSelectableItems(); + break; + default: + break; + } + QQuickItem::itemChange(change, data); +} diff --git a/src/modules/item-selector/itemselector.h b/src/modules/item-selector/itemselector.h new file mode 100644 index 0000000000..eaa192cbc3 --- /dev/null +++ b/src/modules/item-selector/itemselector.h @@ -0,0 +1,73 @@ +// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once +#include + +#include +#include +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutputItem; +WAYLIB_SERVER_END_NAMESPACE + +class ItemFilter; + +class ItemSelector : public QQuickItem +{ + Q_OBJECT + QML_ELEMENT + Q_PROPERTY(QRectF selectionRegion READ selectionRegion NOTIFY selectionRegionChanged FINAL) + Q_PROPERTY(QQuickItem* hoveredItem READ hoveredItem NOTIFY hoveredItemChanged FINAL) + Q_PROPERTY(ItemTypes selectionTypeHint READ selectionTypeHint WRITE setSelectionTypeHint NOTIFY selectionTypeHintChanged FINAL) + +public: + enum ItemType + { + Output = 0x1, + Window = 0x2, + Surface = 0x4, + }; + + Q_FLAG(ItemType); + Q_DECLARE_FLAGS(ItemTypes, ItemType) + + ItemSelector(QQuickItem *parent = nullptr); + ~ItemSelector(); + + QRectF selectionRegion() const; + QQuickItem *hoveredItem() const; + WAYLIB_SERVER_NAMESPACE::WOutputItem *outputItem() const; + void setSelectionTypeHint(ItemTypes newSelectionTypeHint); + ItemTypes selectionTypeHint() const; + + void disableDefaultFilter(bool disable = true); + // Note: filter is managed by selector. + void addCustomFilter(std::function filter); + void clearCustomFilter(); +Q_SIGNALS: + void selectionRegionChanged(); + void hoveredItemChanged(); + void selectionTypeHintChanged(); + +protected: + void hoverMoveEvent(QHoverEvent *event) override; + void itemChange(ItemChange, const ItemChangeData &) override; + +private: + void setSelectionRegion(const QRectF &newSelectionRegion); + void setHoveredItem(QQuickItem *newHoveredItem); + void updateSelectableItems(); + void checkHoveredItem(QPointF pos); + + QPointer m_hoveredItem{}; + QRectF m_selectionRegion{}; + QList> m_selectableItems{}; + ItemTypes m_selectionTypeHint{ ItemType::Window | ItemType::Output | ItemType::Surface }; + QList> m_outputItems; + QPointer m_outputItem; + bool m_defaultFilterEnabled{ true }; + std::function m_defaultFilter; + QList> m_customFilters; +}; + +Q_DECLARE_OPERATORS_FOR_FLAGS(ItemSelector::ItemTypes) diff --git a/src/modules/keyboard-shortcuts-inhibit/CMakeLists.txt b/src/modules/keyboard-shortcuts-inhibit/CMakeLists.txt new file mode 100644 index 0000000000..b965c0b31e --- /dev/null +++ b/src/modules/keyboard-shortcuts-inhibit/CMakeLists.txt @@ -0,0 +1,9 @@ +impl_treeland( + NAME + module_keyboard_shortcuts_inhibit + SOURCE + keyboardshortcutsinhibitmanager.h + keyboardshortcutsinhibitmanager.cpp + LINK + Qt6::Core +) diff --git a/src/modules/keyboard-shortcuts-inhibit/keyboardshortcutsinhibitmanager.cpp b/src/modules/keyboard-shortcuts-inhibit/keyboardshortcutsinhibitmanager.cpp new file mode 100644 index 0000000000..35c1866522 --- /dev/null +++ b/src/modules/keyboard-shortcuts-inhibit/keyboardshortcutsinhibitmanager.cpp @@ -0,0 +1,211 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "keyboardshortcutsinhibitmanager.h" + +#include "common/treelandlogging.h" +#include "core/waylandserver.h" +#include "seatmanager.h" + +#include +#include +#include + +#include + +#include + +struct InhibitorEntry +{ + wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor = nullptr; + WScopedListener destroyListener; +}; + +class KeyboardShortcutsInhibitManagerV1Private +{ +public: + explicit KeyboardShortcutsInhibitManagerV1Private(KeyboardShortcutsInhibitManagerV1 *q) + : q(q) + { + } + + KeyboardShortcutsInhibitManagerV1 *q = nullptr; + WScopedListener newInhibitorListener; + std::vector inhibitors; + + wlr_keyboard_shortcuts_inhibit_manager_v1 *handle() const + { + return reinterpret_cast(q->handle()); + } + + void onNewInhibitor(wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor); + void onInhibitorDestroy(wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor); +}; + +void KeyboardShortcutsInhibitManagerV1::setupSeatConnections() +{ + if (seatConnectionsSetup) + return; + seatConnectionsSetup = true; + + auto *seatManager = WaylandServer::instance()->seatManager(); + const auto seats = seatManager->seats(); + for (auto *seat : seats) { + onSeatAdded(seat); + } + + QObject::connect(seatManager, + &SeatManager::seatAdded, + this, + &KeyboardShortcutsInhibitManagerV1::onSeatAdded); + QObject::connect(seatManager, + &SeatManager::seatRemoved, + this, + &KeyboardShortcutsInhibitManagerV1::onSeatRemoved); +} + +void KeyboardShortcutsInhibitManagerV1::onSeatAdded(WSeat *seat) +{ + if (seatFocusConnections.contains(seat)) + return; + + auto conn = QObject::connect(seat, &WSeat::keyboardFocusSurfaceChanged, this, [this, seat]() { + onSeatFocusChanged(seat); + }); + seatFocusConnections.insert(seat, conn); + + // Activate inhibitors for surfaces that already have focus on this seat. + onSeatFocusChanged(seat); +} + +void KeyboardShortcutsInhibitManagerV1::onSeatRemoved(WSeat *seat) +{ + auto it = seatFocusConnections.find(seat); + if (it != seatFocusConnections.end()) { + QObject::disconnect(it.value()); + seatFocusConnections.erase(it); + } +} + +void KeyboardShortcutsInhibitManagerV1::onSeatFocusChanged(WSeat *seat) +{ + wlr_seat *wlrSeat = seat->handle(); + auto *focusSurface = seat->keyboardFocusSurface(); + wlr_surface *wlrSurface = focusSurface ? focusSurface->handle() : nullptr; + + for (auto &entry : d->inhibitors) { + if (entry.inhibitor->seat != wlrSeat) + continue; + + if (wlrSurface && entry.inhibitor->surface == wlrSurface) { + wlr_keyboard_shortcuts_inhibitor_v1_activate(entry.inhibitor); + } else if (entry.inhibitor->active) { + entry.inhibitor->active = false; + } + } +} + +void KeyboardShortcutsInhibitManagerV1Private::onNewInhibitor( + wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor) +{ + qCInfo(lcTlKeyboardShortcutsInhibit) + << "New inhibitor created for surface" << inhibitor->surface << "seat" << inhibitor->seat; + + InhibitorEntry entry; + entry.inhibitor = inhibitor; + entry.destroyListener.init(&inhibitor->events.destroy, + this, + &KeyboardShortcutsInhibitManagerV1Private::onInhibitorDestroy); + inhibitors.push_back(std::move(entry)); + + // If the surface already has keyboard focus on this seat, activate the + // inhibitor immediately (sends 'active' to the client). + auto *wSeat = WSeat::fromHandle(inhibitor->seat); + if (wSeat) { + auto *focusSurface = wSeat->keyboardFocusSurface(); + if (focusSurface && focusSurface->handle() == inhibitor->surface) { + wlr_keyboard_shortcuts_inhibitor_v1_activate(inhibitor); + } + } +} + +void KeyboardShortcutsInhibitManagerV1Private::onInhibitorDestroy( + wlr_keyboard_shortcuts_inhibitor_v1 *inhibitor) +{ + qCInfo(lcTlKeyboardShortcutsInhibit) + << "Inhibitor destroyed for surface" << inhibitor->surface << "seat" << inhibitor->seat; + + inhibitors.erase(std::remove_if(inhibitors.begin(), + inhibitors.end(), + [inhibitor](const InhibitorEntry &e) { + return e.inhibitor == inhibitor; + }), + inhibitors.end()); +} + +KeyboardShortcutsInhibitManagerV1::KeyboardShortcutsInhibitManagerV1(QObject *parent) + : QObject(parent) + , d(new KeyboardShortcutsInhibitManagerV1Private(this)) +{ +} + +KeyboardShortcutsInhibitManagerV1::~KeyboardShortcutsInhibitManagerV1() = default; + +QByteArrayView KeyboardShortcutsInhibitManagerV1::interfaceName() const +{ + return "zwp_keyboard_shortcuts_inhibit_manager_v1"; +} + +void KeyboardShortcutsInhibitManagerV1::create(WServer *server) +{ + m_handle = wlr_keyboard_shortcuts_inhibit_v1_create(server->handle()); + if (!m_handle) { + qCWarning(lcTlKeyboardShortcutsInhibit) + << "Failed to create keyboard shortcuts inhibit manager"; + return; + } + + d->newInhibitorListener.init(&d->handle()->events.new_inhibitor, + d.get(), + &KeyboardShortcutsInhibitManagerV1Private::onNewInhibitor); + + setupSeatConnections(); +} + +void KeyboardShortcutsInhibitManagerV1::destroy([[maybe_unused]] WServer *server) +{ + d->newInhibitorListener.disconnect(); + for (auto &entry : d->inhibitors) + entry.destroyListener.disconnect(); + d->inhibitors.clear(); + + for (auto &conn : seatFocusConnections) + QObject::disconnect(conn); + seatFocusConnections.clear(); + seatConnectionsSetup = false; + + m_handle = nullptr; +} + +wl_global *KeyboardShortcutsInhibitManagerV1::global() const +{ + return d->handle() ? d->handle()->global : nullptr; +} + +bool KeyboardShortcutsInhibitManagerV1::isInhibited(wlr_seat *seat, wlr_surface *surface) const +{ + for (const auto &entry : std::as_const(d->inhibitors)) { + if (entry.inhibitor->active && entry.inhibitor->seat == seat + && entry.inhibitor->surface == surface) + return true; + } + return false; +} + +void KeyboardShortcutsInhibitManagerV1::deactivateActiveInhibitor(wlr_seat *seat) +{ + for (auto &entry : d->inhibitors) { + if (entry.inhibitor->seat == seat && entry.inhibitor->active) + wlr_keyboard_shortcuts_inhibitor_v1_deactivate(entry.inhibitor); + } +} diff --git a/src/modules/keyboard-shortcuts-inhibit/keyboardshortcutsinhibitmanager.h b/src/modules/keyboard-shortcuts-inhibit/keyboardshortcutsinhibitmanager.h new file mode 100644 index 0000000000..96f07ebbf4 --- /dev/null +++ b/src/modules/keyboard-shortcuts-inhibit/keyboardshortcutsinhibitmanager.h @@ -0,0 +1,54 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include + +#include +#include + +#include + +struct wlr_keyboard_shortcuts_inhibitor_v1; +struct wlr_keyboard_shortcuts_inhibit_manager_v1; +struct wlr_surface; +struct wlr_seat; + +WAYLIB_SERVER_USE_NAMESPACE + +class KeyboardShortcutsInhibitManagerV1Private; + +class KeyboardShortcutsInhibitManagerV1 + : public QObject + , public WServerInterface +{ + Q_OBJECT + +public: + explicit KeyboardShortcutsInhibitManagerV1(QObject *parent = nullptr); + ~KeyboardShortcutsInhibitManagerV1() override; + + QByteArrayView interfaceName() const override; + + bool isInhibited(wlr_seat *seat, wlr_surface *surface) const; + void deactivateActiveInhibitor(wlr_seat *seat); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + void setupSeatConnections(); + void onSeatAdded(WSeat *seat); + void onSeatRemoved(WSeat *seat); + void onSeatFocusChanged(WSeat *seat); + + QHash seatFocusConnections; + bool seatConnectionsSetup = false; + + std::unique_ptr d; +}; diff --git a/src/modules/keyboard-state-notify/CMakeLists.txt b/src/modules/keyboard-state-notify/CMakeLists.txt new file mode 100644 index 0000000000..ef24dfb214 --- /dev/null +++ b/src/modules/keyboard-state-notify/CMakeLists.txt @@ -0,0 +1,16 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-keyboard-state-notify-unstable-v1.xml + BASENAME treeland-keyboard-state-notify-unstable-v1 +) + +impl_treeland( + NAME + module_keyboard_state_notify + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/keyboard-state-notify/keyboardstatenotifymanagerinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/keyboard-state-notify/keyboardstatenotifymanagerinterfacev1.cpp + INCLUDE + $ +) diff --git a/src/modules/keyboard-state-notify/keyboardstatenotifymanagerinterfacev1.cpp b/src/modules/keyboard-state-notify/keyboardstatenotifymanagerinterfacev1.cpp new file mode 100644 index 0000000000..e67a66ed90 --- /dev/null +++ b/src/modules/keyboard-state-notify/keyboardstatenotifymanagerinterfacev1.cpp @@ -0,0 +1,452 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "keyboardstatenotifymanagerinterfacev1.h" +#include "qwayland-server-treeland-keyboard-state-notify-unstable-v1.h" +#include "core/waylandserver.h" +#include "seatmanager.h" +#include "common/treelandlogging.h" +#include "treelandconfig.hpp" + +#include +#include + +#include + +#include + +#include + +static QList s_watchers; +static QHash s_lastModifiers; + + +struct ModifierInfo { + uint32_t flag; + const char *modName; +}; + +static constexpr ModifierInfo s_modifierInfos[] = { + { KeyboardStateWatcherV1::CapsLock, XKB_MOD_NAME_CAPS }, + { KeyboardStateWatcherV1::NumLock, XKB_MOD_NAME_NUM }, +}; + +static std::optional getSeatKeyboard(WSeat *seat) +{ + if (!seat || !seat->keyboardGroupKeyboard()) + return std::nullopt; + + auto *wlrDevice = seat->keyboardGroupKeyboard()->handle(); + if (wlrDevice->type != WLR_INPUT_DEVICE_KEYBOARD) + return std::nullopt; + auto *keyboard = wlr_keyboard_from_input_device(wlrDevice); + if (!keyboard || !keyboard->keymap) + return std::nullopt; + + return keyboard; +} + +static bool modifiersEqual(const wlr_keyboard_modifiers &a, const wlr_keyboard_modifiers &b) +{ + return a.depressed == b.depressed + && a.latched == b.latched + && a.locked == b.locked + && a.group == b.group; +} + +static uint32_t lockStateBitfield(wlr_keyboard *keyboard, xkb_mod_mask_t locked) +{ + uint32_t state = 0; + for (const auto &info : s_modifierInfos) { + xkb_mod_index_t idx = xkb_keymap_mod_get_index(keyboard->keymap, info.modName); + if (idx != XKB_MOD_INVALID && (locked & (xkb_mod_mask_t(1) << idx))) + state |= info.flag; + } + + return state; +} + +static std::optional getSeatLockState(WSeat *seat) +{ + const auto keyboard = getSeatKeyboard(seat); + if (!keyboard) + return std::nullopt; + + return lockStateBitfield(*keyboard, (*keyboard)->modifiers.locked); +} + +static uint32_t changedLockStateBitfield(wlr_keyboard *keyboard, + const wlr_keyboard_modifiers &previous, + const wlr_keyboard_modifiers ¤t) +{ + return lockStateBitfield(keyboard, previous.locked ^ current.locked); +} + +struct KeyboardConnection { + WScopedListener modifiersListener; + QPointer seat = nullptr; +}; + +class TreelandKeyboardStateNotifyManagerInterfaceV1Private + : public QtWaylandServer::treeland_keyboard_state_notify_manager_v1 +{ +public: + explicit TreelandKeyboardStateNotifyManagerInterfaceV1Private(TreelandKeyboardStateNotifyManagerInterfaceV1 *_q); + + TreelandKeyboardStateNotifyManagerInterfaceV1 *q = nullptr; + + void setupKeyboardConnections(); + void onModifiersEvent(WSeat *seat); + wl_global *global() const; + +protected: + void bind_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void get_keyboard_state_watcher(Resource *resource, + uint32_t id, + struct ::wl_resource *seat) override; + +private: + void handleSeatAdded(WSeat *seat); + void handleSeatDestroy(WSeat *seat); + void connectKeyboardGroup(WSeat *seat, WInputDevice *keyboardDevice); + + QList> m_keyboardConnections; + bool m_keyboardConnectionsSetup = false; +}; + +TreelandKeyboardStateNotifyManagerInterfaceV1Private::TreelandKeyboardStateNotifyManagerInterfaceV1Private( + TreelandKeyboardStateNotifyManagerInterfaceV1 *_q) + : q(_q) +{ +} + +wl_global *TreelandKeyboardStateNotifyManagerInterfaceV1Private::global() const +{ + return m_global; +} + +void TreelandKeyboardStateNotifyManagerInterfaceV1Private::bind_resource([[maybe_unused]] Resource *resource) +{ + setupKeyboardConnections(); +} + +void TreelandKeyboardStateNotifyManagerInterfaceV1Private::connectKeyboardGroup(WSeat *seat, WInputDevice *keyboardDevice) +{ + for (const auto &conn : std::as_const(m_keyboardConnections)) { + if (conn->seat == seat) + return; + } + + if (const auto keyboard = getSeatKeyboard(seat)) + s_lastModifiers[seat] = (*keyboard)->modifiers; + + auto conn = QSharedPointer::create(); + conn->seat = seat; + auto *wlrDevice = keyboardDevice->handle(); + if (wlrDevice->type == WLR_INPUT_DEVICE_KEYBOARD) { + auto *keyboard = wlr_keyboard_from_input_device(wlrDevice); + conn->modifiersListener.init(&keyboard->events.modifiers, q, [this, seat] (void *) { + onModifiersEvent(seat); + }); + } + m_keyboardConnections.push_back(std::move(conn)); +} + +void TreelandKeyboardStateNotifyManagerInterfaceV1Private::setupKeyboardConnections() +{ + if (m_keyboardConnectionsSetup) + return; + m_keyboardConnectionsSetup = true; + + auto *server = WaylandServer::instance(); + const auto seats = server->seatManager()->seats(); + for (auto *seat : seats) { + handleSeatAdded(seat); + } + + QObject::connect(server->seatManager(), &SeatManager::seatAdded, q, [this](WSeat *seat) { + handleSeatAdded(seat); + }); + QObject::connect(server->seatManager(), &SeatManager::seatRemoved, q, [this](WSeat *seat) { + handleSeatDestroy(seat); + }); +} + +void TreelandKeyboardStateNotifyManagerInterfaceV1Private::onModifiersEvent(WSeat *seat) +{ + const auto keyboard = getSeatKeyboard(seat); + if (!keyboard) + return; + + const auto currentModifiers = (*keyboard)->modifiers; + const auto previousModifiers = s_lastModifiers.value(seat, currentModifiers); + s_lastModifiers[seat] = currentModifiers; + + if (modifiersEqual(previousModifiers, currentModifiers)) + return; + + const uint32_t changedLocks = changedLockStateBitfield(*keyboard, previousModifiers, currentModifiers); + if (changedLocks == 0) + return; + + const uint32_t currentLocks = lockStateBitfield(*keyboard, currentModifiers.locked); + + constexpr uint32_t NumLockMask = KeyboardStateWatcherV1::NumLock; + + if (changedLocks & NumLockMask) { + const bool isLocked = currentLocks & NumLockMask; + + if (auto *config = WaylandServer::instance()->globalConfig()) { + config->setKeyboardNumLock(isLocked); + } + } + + if (s_watchers.isEmpty()) + return; + + for (auto *watcher : std::as_const(s_watchers)) { + if (watcher->seat() && watcher->wSeat() != seat) + continue; + + const uint32_t changed = changedLocks & uint32_t(watcher->modifiers()); + if (changed == 0) + continue; + + for (int i = 0; i < 2; ++i) { + uint32_t mod = (1u << i); + if (!(changed & mod)) + continue; + + bool isLocked = (currentLocks & mod) != 0; + if (isLocked && !(watcher->flags() & KeyboardStateWatcherV1::WatchLocked)) + continue; + if (!isLocked && !(watcher->flags() & KeyboardStateWatcherV1::WatchUnlocked)) + continue; + + watcher->sendStateChanged(mod, isLocked ? KeyboardStateWatcherV1::Locked : KeyboardStateWatcherV1::Unlocked); + } + } +} + +void TreelandKeyboardStateNotifyManagerInterfaceV1Private::handleSeatDestroy(WSeat *seat) +{ + m_keyboardConnections.removeIf([seat](const QSharedPointer &conn) { + return conn->seat == seat; + }); + s_lastModifiers.remove(seat); +} + +void TreelandKeyboardStateNotifyManagerInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void TreelandKeyboardStateNotifyManagerInterfaceV1Private::get_keyboard_state_watcher(Resource *resource, + uint32_t id, + struct ::wl_resource *seat) +{ + wl_resource *watcherResource = wl_resource_create(resource->client(), + &treeland_keyboard_state_watcher_v1_interface, + resource->version(), + id); + if (!watcherResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto *watcher = new KeyboardStateWatcherV1(watcherResource, seat); + s_watchers.append(watcher); + + QObject::connect(watcher, &QObject::destroyed, [watcher]() { + s_watchers.removeOne(watcher); + }); + + Q_EMIT q->keyboardStateWatcherCreated(watcher); +} + +void TreelandKeyboardStateNotifyManagerInterfaceV1Private::handleSeatAdded(WSeat *seat) +{ + auto *keyboardevice = seat->keyboardGroupKeyboard(); + if (keyboardevice) { + connectKeyboardGroup(seat, keyboardevice); + } +} + +class KeyboardStateWatcherV1Private : public QtWaylandServer::treeland_keyboard_state_watcher_v1 +{ +public: + explicit KeyboardStateWatcherV1Private(KeyboardStateWatcherV1 *_q, + wl_resource *resource, + wl_resource *_seat); + + KeyboardStateWatcherV1 *q = nullptr; + wl_resource *seat = nullptr; + KeyboardStateWatcherV1::ModifierTypes modifiers; + KeyboardStateWatcherV1::ModifierTypes pendingModifiers; + KeyboardStateWatcherV1::WatchFlags flags; + KeyboardStateWatcherV1::WatchFlags pendingFlags; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void set_modifiers(Resource *resource, uint32_t modifiers) override; + void set_flags(Resource *resource, uint32_t flags) override; + void apply(Resource *resource) override; +}; + +KeyboardStateWatcherV1Private::KeyboardStateWatcherV1Private(KeyboardStateWatcherV1 *_q, + wl_resource *resource, + wl_resource *_seat) + : QtWaylandServer::treeland_keyboard_state_watcher_v1(resource) + , q(_q) + , seat(_seat) +{ +} + +void KeyboardStateWatcherV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void KeyboardStateWatcherV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void KeyboardStateWatcherV1Private::set_modifiers(Resource *resource, uint32_t modifiers) +{ + if (!treeland_keyboard_state_watcher_v1_modifier_is_valid(modifiers, resource->version())) { + qCCritical(lcTlKeyboardNotify, "unknown modifiers"); + return; + } + + pendingModifiers = KeyboardStateWatcherV1::ModifierTypes(modifiers); +} + +void KeyboardStateWatcherV1Private::set_flags(Resource *resource, uint32_t flags) +{ + if (!treeland_keyboard_state_watcher_v1_watch_flag_is_valid(flags, resource->version())) { + qCCritical(lcTlKeyboardNotify, "unknown watch flags"); + return; + } + + pendingFlags = KeyboardStateWatcherV1::WatchFlags(flags); +} + +void KeyboardStateWatcherV1Private::apply([[maybe_unused]] Resource *resource) +{ + if (pendingModifiers == modifiers && pendingFlags == flags) + return; + + modifiers = pendingModifiers; + flags = pendingFlags; + + if (modifiers == 0) + return; + + auto *wSeat = q->wSeat(); + QList seats; + if (wSeat) { + seats.append(wSeat); + } else { + auto *server = WaylandServer::instance(); + if (server) + seats = server->seatManager()->seats(); + } + + for (auto *seat : std::as_const(seats)) { + const auto currentLocks = getSeatLockState(seat); + if (!currentLocks) + continue; + + for (int i = 0; i < 2; ++i) { + uint32_t mod = (1u << i); + if (!(modifiers & mod)) + continue; + + bool isLocked = (*currentLocks & mod) != 0; + if (isLocked && !(flags & KeyboardStateWatcherV1::WatchLocked)) + continue; + if (!isLocked && !(flags & KeyboardStateWatcherV1::WatchUnlocked)) + continue; + + q->sendCurrentState(mod, isLocked ? KeyboardStateWatcherV1::Locked : KeyboardStateWatcherV1::Unlocked); + } + } +} + +TreelandKeyboardStateNotifyManagerInterfaceV1::TreelandKeyboardStateNotifyManagerInterfaceV1(QObject *parent) + : QObject(parent) + , d(new TreelandKeyboardStateNotifyManagerInterfaceV1Private(this)) +{ +} + +TreelandKeyboardStateNotifyManagerInterfaceV1::~TreelandKeyboardStateNotifyManagerInterfaceV1() = default; + +void TreelandKeyboardStateNotifyManagerInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); + d->setupKeyboardConnections(); +} + +void TreelandKeyboardStateNotifyManagerInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *TreelandKeyboardStateNotifyManagerInterfaceV1::global() const +{ + return d->global(); +} + +QByteArrayView TreelandKeyboardStateNotifyManagerInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} + +KeyboardStateWatcherV1::KeyboardStateWatcherV1(wl_resource *resource, + wl_resource *seat, + QObject *parent) + : QObject(parent) + , d(new KeyboardStateWatcherV1Private(this, resource, seat)) +{ +} + +KeyboardStateWatcherV1::~KeyboardStateWatcherV1() = default; + +KeyboardStateWatcherV1::ModifierTypes KeyboardStateWatcherV1::modifiers() const +{ + return d->modifiers; +} + +KeyboardStateWatcherV1::WatchFlags KeyboardStateWatcherV1::flags() const +{ + return d->flags; +} + +wl_resource *KeyboardStateWatcherV1::seat() const +{ + return d->seat; +} + +WSeat *KeyboardStateWatcherV1::wSeat() const +{ + if (!d->seat) + return nullptr; + + struct wlr_seat_client *seat_client = + wlr_seat_client_from_resource(d->seat); + Q_ASSERT_X(seat_client, __func__, "KeyboardStateWatcherV1 get wlr_seat_client failed."); + return WSeat::fromHandle(seat_client->seat); +} + +void KeyboardStateWatcherV1::sendStateChanged(uint32_t modifier, ModifierState state) +{ + d->send_state_changed(modifier, state); +} + +void KeyboardStateWatcherV1::sendCurrentState(uint32_t modifier, ModifierState state) +{ + d->send_current_state(modifier, state); +} diff --git a/src/modules/keyboard-state-notify/keyboardstatenotifymanagerinterfacev1.h b/src/modules/keyboard-state-notify/keyboardstatenotifymanagerinterfacev1.h new file mode 100644 index 0000000000..3ffa5a7ed1 --- /dev/null +++ b/src/modules/keyboard-state-notify/keyboardstatenotifymanagerinterfacev1.h @@ -0,0 +1,88 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class KeyboardStateWatcherV1Private; +class KeyboardStateWatcherV1; +class TreelandKeyboardStateNotifyManagerInterfaceV1Private; + +class TreelandKeyboardStateNotifyManagerInterfaceV1 : public QObject, public WServerInterface +{ + Q_OBJECT +public: + explicit TreelandKeyboardStateNotifyManagerInterfaceV1(QObject *parent = nullptr); + ~TreelandKeyboardStateNotifyManagerInterfaceV1() override; + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; + +Q_SIGNALS: + void keyboardStateWatcherCreated(KeyboardStateWatcherV1 *watcher); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; + +class KeyboardStateWatcherV1 : public QObject +{ + Q_OBJECT +public: + ~KeyboardStateWatcherV1() override; + + enum ModifierType { + CapsLock = 1, + NumLock = 2, + }; + Q_DECLARE_FLAGS(ModifierTypes, ModifierType) + Q_FLAG(ModifierTypes) + + enum WatchFlag { + WatchLocked = 1, + WatchUnlocked = 2, + }; + Q_DECLARE_FLAGS(WatchFlags, WatchFlag) + Q_FLAG(WatchFlags) + + enum ModifierState { + Unlocked = 0, + Locked = 1, + }; + Q_ENUM(ModifierState) + + ModifierTypes modifiers() const; + WatchFlags flags() const; + + wl_resource *seat() const; + WSeat *wSeat() const; + + void sendStateChanged(uint32_t modifier, ModifierState state); + void sendCurrentState(uint32_t modifier, ModifierState state); + +private: + explicit KeyboardStateWatcherV1(wl_resource *resource, + wl_resource *seat, + QObject *parent = nullptr); + +private: + friend class TreelandKeyboardStateNotifyManagerInterfaceV1Private; + std::unique_ptr d; +}; + +Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardStateWatcherV1::ModifierTypes) +Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardStateWatcherV1::WatchFlags) diff --git a/src/modules/layer-shell-extension/CMakeLists.txt b/src/modules/layer-shell-extension/CMakeLists.txt new file mode 100644 index 0000000000..de56884f1c --- /dev/null +++ b/src/modules/layer-shell-extension/CMakeLists.txt @@ -0,0 +1,18 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-layer-shell-extension-unstable-v1.xml + BASENAME treeland-layer-shell-extension-unstable-v1 +) + +impl_treeland( + NAME + module_layer_shell_extension + SOURCE + layershellextensionmanagerinterfacev1.h + layershellextensionmanagerinterfacev1.cpp + INCLUDE + $ + LINK + Qt6::Core +) diff --git a/src/modules/layer-shell-extension/layershellextensionmanagerinterfacev1.cpp b/src/modules/layer-shell-extension/layershellextensionmanagerinterfacev1.cpp new file mode 100644 index 0000000000..8975381c38 --- /dev/null +++ b/src/modules/layer-shell-extension/layershellextensionmanagerinterfacev1.cpp @@ -0,0 +1,416 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "layershellextensionmanagerinterfacev1.h" + +#include "common/treelandlogging.h" +#include "core/rootsurfacecontainer.h" +#include "qwayland-server-treeland-layer-shell-extension-unstable-v1.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" + +#include +#include +#include +#include +#include + +static constexpr struct EdgeMapEntry +{ + uint32_t protocolBit; + Qt::Edge qtEdge; +} kEdgeMap[] = { + { 1, Qt::TopEdge }, // protocol top -> Qt::TopEdge + { 2, Qt::BottomEdge }, // protocol bottom -> Qt::BottomEdge + { 4, Qt::LeftEdge }, // protocol left -> Qt::LeftEdge + { 8, Qt::RightEdge }, // protocol right -> Qt::RightEdge +}; + +// All valid edge bits: top|bottom|left|right. +constexpr uint32_t kValidEdgeBits = 1 | 2 | 4 | 8; // = 15 + +class LayerShellExtensionManagerInterfaceV1Private + : public QtWaylandServer::treeland_layer_shell_extension_manager_v1 +{ +public: + explicit LayerShellExtensionManagerInterfaceV1Private( + LayerShellExtensionManagerInterfaceV1 *_q); + wl_global *global() const; + + LayerShellExtensionManagerInterfaceV1 *q; + + QList m_objects; + void get_layer_shell_extension_object(Resource *resource, + uint32_t id, + struct ::wl_resource *surface) override; +}; + +class LayerShellExtensionObjectV1Private + : public QtWaylandServer::treeland_layer_shell_extension_object_v1 +{ +public: + LayerShellExtensionObjectV1Private(LayerShellExtensionObjectV1 *_q, + wl_resource *surface, + wl_resource *resource); + ~LayerShellExtensionObjectV1Private(); + + LayerShellExtensionObjectV1 *q; + wl_resource *nativeSurface = nullptr; + WSeat *resizingSeat = nullptr; + + bool clampRegistered = false; + void registerClamp(WSeat *seat, qreal minW, qreal maxW, qreal minH, qreal maxH); + void clearClamp(); + + void onSurfaceDestroyed(struct wlr_surface *surface); + WScopedListener m_surfaceDestroy; + + void destroy_resource([[maybe_unused]] Resource *resource) override; + void destroy([[maybe_unused]] Resource *resource) override; + void begin_resize(Resource *resource, + struct ::wl_resource *seat, + uint32_t serial, + uint32_t edges, + int32_t min_width, + int32_t min_height, + int32_t max_width, + int32_t max_height) override; +}; + +LayerShellExtensionManagerInterfaceV1Private::LayerShellExtensionManagerInterfaceV1Private( + LayerShellExtensionManagerInterfaceV1 *_q) + : QtWaylandServer::treeland_layer_shell_extension_manager_v1() + , q(_q) +{ +} + +wl_global *LayerShellExtensionManagerInterfaceV1Private::global() const +{ + return m_global; +} + +LayerShellExtensionManagerInterfaceV1::LayerShellExtensionManagerInterfaceV1(QObject *parent) + : QObject(parent) + , d(new LayerShellExtensionManagerInterfaceV1Private(this)) +{ +} + +LayerShellExtensionManagerInterfaceV1::~LayerShellExtensionManagerInterfaceV1() = default; + +void LayerShellExtensionManagerInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void LayerShellExtensionManagerInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *LayerShellExtensionManagerInterfaceV1::global() const +{ + return d->global(); +} + +QByteArrayView LayerShellExtensionManagerInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} + +void LayerShellExtensionManagerInterfaceV1Private::get_layer_shell_extension_object( + Resource *resource, + uint32_t id, + struct ::wl_resource *surface) +{ + if (!surface || !wlr_surface_from_resource(surface)) { + qCWarning(lcTlLayerShell) << "get_object: invalid surface resource"; + wl_resource_post_error(resource->handle, + error_wl_surface_invalid, + "surface resource is invalid!"); + return; + } + + for (auto *objectSurface : std::as_const(m_objects)) { + if (objectSurface->nativeSurface() == surface) { + qCWarning(lcTlLayerShell) + << "get_object: extension object already exists for this wl_surface"; + wl_resource_post_error( + resource->handle, + error_layer_shell_extension_exists, + "treeland_layer_shell_extension_object_v1 already exists for this wl_surface"); + return; + } + } + + wl_resource *objectResource = + wl_resource_create(resource->client(), + &treeland_layer_shell_extension_object_v1_interface, + resource->version(), + id); + if (!objectResource) { + qCWarning(lcTlLayerShell) << "get_object: failed to create object resource (OOM)"; + wl_client_post_no_memory(resource->client()); + return; + } + + auto *objectSurface = new LayerShellExtensionObjectV1(surface, objectResource); + m_objects.append(objectSurface); + + QObject::connect(objectSurface, &QObject::destroyed, q, [this, objectSurface]() { + m_objects.removeOne(objectSurface); + }); + + Q_EMIT q->objectCreated(objectSurface); +} + +void LayerShellExtensionObjectV1Private::onSurfaceDestroyed(struct wlr_surface *surface) +{ + Q_UNUSED(surface); + + m_surfaceDestroy.disconnect(); + q->endResize(); + nativeSurface = nullptr; +} + +LayerShellExtensionObjectV1Private::LayerShellExtensionObjectV1Private( + LayerShellExtensionObjectV1 *_q, + wl_resource *surface, + wl_resource *resource) + : QtWaylandServer::treeland_layer_shell_extension_object_v1(resource) + , q(_q) + , nativeSurface(surface) +{ + if (auto *wlrSurface = wlr_surface_from_resource(surface)) { + m_surfaceDestroy.init(&wlrSurface->events.destroy, + this, + &LayerShellExtensionObjectV1Private::onSurfaceDestroyed); + } + + auto *container = WaylandServer::instance()->rootSurfaceContainer(); + if (container) { + QObject::connect(container, + &RootSurfaceContainer::moveResizeFinised, + q, + [this](SurfaceWrapper *wrapper) { + if (!resizingSeat || !wrapper) + return; + + if (auto *wlrSurface = wlr_surface_from_resource(nativeSurface)) { + if (wrapper->surface() == WSurface::fromHandle(wlrSurface)) { + q->endResize(); + } + } + }); + } +} + +LayerShellExtensionObjectV1Private::~LayerShellExtensionObjectV1Private() = default; + +void LayerShellExtensionObjectV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void LayerShellExtensionObjectV1Private::destroy([[maybe_unused]] Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void LayerShellExtensionObjectV1Private::registerClamp(WSeat *seat, + qreal minW, + qreal maxW, + qreal minH, + qreal maxH) +{ + if (clampRegistered) + clearClamp(); + + auto *container = WaylandServer::instance()->rootSurfaceContainer(); + if (!container) + return; + auto *seatContainer = container->getSeatContainerOrDefault(seat); + if (!seatContainer) + return; + + // The limits are per-drag session state, stored inside the SeatSurfaceManager + // and torn down when the drag ends; they are not properties of the surface. + seatContainer->setResizeClamp(minW, maxW, minH, maxH); + clampRegistered = true; + resizingSeat = seat; +} + +void LayerShellExtensionObjectV1Private::clearClamp() +{ + if (!clampRegistered) + return; + + auto *container = WaylandServer::instance()->rootSurfaceContainer(); + if (container) { + auto *seatContainer = container->getSeatContainerOrDefault(resizingSeat); + if (seatContainer) + seatContainer->clearResizeClamp(); + } + clampRegistered = false; + resizingSeat = nullptr; +} + +void LayerShellExtensionObjectV1Private::begin_resize(Resource *resource, + struct ::wl_resource *seatResource, + uint32_t serial, + uint32_t edges, + int32_t min_width, + int32_t min_height, + int32_t max_width, + int32_t max_height) +{ + const qreal minW = qMax(qreal(0), qreal(min_width)); + const qreal maxW = qMax(qreal(0), qreal(max_width)); + const qreal minH = qMax(qreal(0), qreal(min_height)); + const qreal maxH = qMax(qreal(0), qreal(max_height)); + + // A dimension's min/max range is valid unless it is inverted with a + // non-zero max; an inverted range is dropped, leaving that axis + // unconstrained. + const bool validW = !(minW > maxW && maxW != 0); + const bool validH = !(minH > maxH && maxH != 0); + if (!validW || !validH) { + qCWarning(lcTlLayerShell) << "begin_resize: invalid size limits ignored:" << min_width + << min_height << max_width << max_height; + } + // Derive the effective limits, zeroing a dimension whose range is + // inverted (min>max) so the clamp leaves it unrestricted. + const qreal effectiveMinW = validW ? minW : 0; + const qreal effectiveMaxW = validW ? maxW : 0; + const qreal effectiveMinH = validH ? minH : 0; + const qreal effectiveMaxH = validH ? maxH : 0; + + auto *seatClient = wlr_seat_client_from_resource(seatResource); + if (!seatClient || !seatClient->seat) { + qCWarning(lcTlLayerShell) << "begin_resize REJECTED: invalid seat client/resource"; + send_resize_rejected(resource->handle, resize_error_bad_seat); + return; + } + WSeat *seat = WSeat::fromHandle(seatClient->seat); + if (!seat) { + qCWarning(lcTlLayerShell) << "begin_resize REJECTED: no WSeat for seat client"; + send_resize_rejected(resource->handle, resize_error_bad_seat); + return; + } + + wlr_surface *origin = nativeSurface ? wlr_surface_from_resource(nativeSurface) : nullptr; + if (!origin) { + qCWarning(lcTlLayerShell) << "begin_resize REJECTED: native surface invalid/destroyed"; + send_resize_rejected(resource->handle, resize_error_bad_surface); + return; + } + if (!wlr_seat_validate_pointer_grab_serial(seatClient->seat, origin, serial)) { + qCWarning(lcTlLayerShell) << "begin_resize REJECTED: serial invalid, serial =" << serial; + send_resize_rejected(resource->handle, resize_error_bad_serial); + return; + } + + // Edge must be a non-zero combination of valid edge bits + if (edges == 0 || (edges & ~kValidEdgeBits) != 0) { + qCWarning(lcTlLayerShell) << "begin_resize REJECTED: bad edges =" << edges; + send_resize_rejected(resource->handle, resize_error_bad_edges); + return; + } + + auto *container = WaylandServer::instance()->rootSurfaceContainer(); + auto *wrapper = container->getSurface(WSurface::fromHandle(origin)); + if (!wrapper || wrapper->type() != SurfaceWrapper::Type::Layer) { + qCWarning(lcTlLayerShell) << "begin_resize REJECTED: no Layer wrapper for surface, type =" + << (wrapper ? int(wrapper->type()) : -1); + send_resize_rejected(resource->handle, resize_error_bad_surface); + return; + } + + if (wrapper->surfaceState() != SurfaceWrapper::State::Normal || wrapper->isAnimationRunning()) { + qCWarning(lcTlLayerShell) << "begin_resize REJECTED: state/animation, state =" + << int(wrapper->surfaceState()) + << "animRunning =" << wrapper->isAnimationRunning(); + send_resize_rejected(resource->handle, resize_error_inactive); + return; + } + + auto *layerSurface = qobject_cast(wrapper->shellSurface()); + if (!layerSurface) { + qCWarning(lcTlLayerShell) << "begin_resize REJECTED: wrapper has no layer shell surface"; + send_resize_rejected(resource->handle, resize_error_bad_surface); + return; + } + const auto anchor = layerSurface->ancher(); + if (edges & uint32_t(anchor)) { + qCWarning(lcTlLayerShell) << "begin_resize REJECTED: resize edge overlaps anchor" + << "edges =" << edges << "anchor =" << int(anchor); + send_resize_rejected(resource->handle, resize_error_bad_edges); + return; + } + + if (resizingSeat) { + qCWarning(lcTlLayerShell) + << "begin_resize REJECTED: layer surface is already being resized"; + send_resize_rejected(resource->handle, resize_error_inactive); + return; + } + + Qt::Edges qtEdges; + for (const auto &entry : kEdgeMap) { + if (edges & entry.protocolBit) + qtEdges |= entry.qtEdge; + } + container->beginMoveResizeForSeat(seat, wrapper, qtEdges, /*overrideCursor=*/false); + + auto *seatContainer = container->getSeatContainerOrDefault(seat); + if (!seatContainer || seatContainer->moveResizeState().surface != wrapper) { + qCWarning(lcTlLayerShell) << "begin_resize REJECTED: server did not take over resize"; + send_resize_rejected(resource->handle, resize_error_inactive); + return; + } + registerClamp(seat, effectiveMinW, effectiveMaxW, effectiveMinH, effectiveMaxH); + + qCDebug(lcTlLayerShell) << "begin_resize accepted: edges =" << edges << "limits min=" << effectiveMinW + << "x" << effectiveMinH << "max=" << effectiveMaxW << "x" << effectiveMaxH; + send_resizing(resource->handle, 1); +} + +LayerShellExtensionObjectV1::LayerShellExtensionObjectV1(wl_resource *surface, + wl_resource *resource) + : d(new LayerShellExtensionObjectV1Private(this, surface, resource)) +{ +} + +LayerShellExtensionObjectV1::~LayerShellExtensionObjectV1() +{ + Q_EMIT beforeDestroy(); + WSeat *seat = d->resizingSeat; + if (seat) { + d->clearClamp(); + auto *container = WaylandServer::instance()->rootSurfaceContainer(); + if (container) + container->cancelMoveResizeForSeat(seat); + } +} + +WSurface *LayerShellExtensionObjectV1::wSurface() const +{ + return WSurface::fromHandle(wlr_surface_from_resource(d->nativeSurface)); +} + +wl_resource *LayerShellExtensionObjectV1::nativeSurface() const +{ + return d->nativeSurface; +} + +void LayerShellExtensionObjectV1::sendResizing(uint32_t resizing) +{ + d->send_resizing(resizing); +} + +void LayerShellExtensionObjectV1::endResize() +{ + if (!d->resizingSeat) + return; + d->send_resizing(0); + d->clearClamp(); +} diff --git a/src/modules/layer-shell-extension/layershellextensionmanagerinterfacev1.h b/src/modules/layer-shell-extension/layershellextensionmanagerinterfacev1.h new file mode 100644 index 0000000000..7e98dc37d5 --- /dev/null +++ b/src/modules/layer-shell-extension/layershellextensionmanagerinterfacev1.h @@ -0,0 +1,63 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class LayerShellExtensionManagerInterfaceV1Private; +class LayerShellExtensionObjectV1Private; +class LayerShellExtensionObjectV1; + +class LayerShellExtensionManagerInterfaceV1 + : public QObject + , public WServerInterface +{ + Q_OBJECT +public: + explicit LayerShellExtensionManagerInterfaceV1(QObject *parent = nullptr); + ~LayerShellExtensionManagerInterfaceV1() override; + + QByteArrayView interfaceName() const override; + static constexpr int InterfaceVersion = 1; + +Q_SIGNALS: + void objectCreated(LayerShellExtensionObjectV1 *interface); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; + +class LayerShellExtensionObjectV1 : public QObject +{ + Q_OBJECT +public: + ~LayerShellExtensionObjectV1() override; + + WSurface *wSurface() const; + wl_resource *nativeSurface() const; + + void sendResizing(uint32_t resizing); + void endResize(); + +Q_SIGNALS: + void beforeDestroy(); + +private: + explicit LayerShellExtensionObjectV1(wl_resource *surface, wl_resource *resource); + +private: + friend class LayerShellExtensionManagerInterfaceV1Private; + std::unique_ptr d; +}; diff --git a/src/modules/output-group/CMakeLists.txt b/src/modules/output-group/CMakeLists.txt new file mode 100644 index 0000000000..c5d29ccaa5 --- /dev/null +++ b/src/modules/output-group/CMakeLists.txt @@ -0,0 +1,20 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-output-group-manager-unstable-v1.xml + BASENAME treeland-output-group-manager-unstable-v1 +) + +impl_treeland( + NAME + module_outputgroup + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/output-group/outputgroupmanagerinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/output-group/outputgroupmanagerinterfacev1.cpp + LINK + Wlroots::wlroots + Waylib::WaylibServer + Qt6::Core + Qt6::Gui + Qt6::Quick +) diff --git a/src/modules/output-group/outputgroupmanagerinterfacev1.cpp b/src/modules/output-group/outputgroupmanagerinterfacev1.cpp new file mode 100644 index 0000000000..41ef12d8cc --- /dev/null +++ b/src/modules/output-group/outputgroupmanagerinterfacev1.cpp @@ -0,0 +1,925 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "outputgroupmanagerinterfacev1.h" + +#include "common/treelandlogging.h" +#include "dconfig/dconfigmanager.h" +#include "treelandconfig.hpp" + +#include +#include +#include +#include + +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { + +// Group names are generated by the compositor as "output-group--" +// and never contain ';', so the registry can be persisted as a plain +// semicolon-separated list instead of a JSON array. +constexpr QChar kGroupNameSeparator = u';'; + +// The state event carries the mirror uuids as one flat byte array: every uuid +// has a fixed length and never contains NUL, so no separators are needed. +QByteArray concatenateUuids(const QStringList &uuids) +{ + QByteArray result; + for (const auto &uuid : std::as_const(uuids)) { + result.append(uuid.toUtf8()); + } + return result; +} + +// Resolves the effective source of one group from its connected members: the +// member with the most recent explicit set_source wins; when no member was +// ever designated, the earliest joined member is promoted temporarily (no +// configuration is written, so a returning designated source takes over +// again). Ties are broken by uuid for a stable result. +QString resolveGroupSource(const QList &members) +{ + const OutputGroupMemberInfo *designated = nullptr; + for (const auto &member : members) { + if (member.lastSetSourceTime <= 0) { + continue; + } + if (!designated || member.lastSetSourceTime > designated->lastSetSourceTime + || (member.lastSetSourceTime == designated->lastSetSourceTime + && member.uuid < designated->uuid)) { + designated = &member; + } + } + if (designated) { + return designated->uuid; + } + + const OutputGroupMemberInfo *earliest = nullptr; + for (const auto &member : members) { + if (!earliest || member.joinTime < earliest->joinTime + || (member.joinTime == earliest->joinTime && member.uuid < earliest->uuid)) { + earliest = &member; + } + } + return earliest ? earliest->uuid : QString(); +} + +// Mirrors follow the join order of the members; ties are broken by uuid. +QStringList resolveGroupMirrors(const QList &members, + const QString &sourceUuid) +{ + QList mirrors; + for (const auto &member : members) { + if (member.uuid != sourceUuid) { + mirrors.append(member); + } + } + std::sort(mirrors.begin(), mirrors.end(), [](const auto &a, const auto &b) { + return a.joinTime != b.joinTime ? a.joinTime < b.joinTime : a.uuid < b.uuid; + }); + + QStringList uuids; + uuids.reserve(mirrors.size()); + for (const auto &member : std::as_const(mirrors)) { + uuids.append(member.uuid); + } + return uuids; +} + +} // namespace + +class OutputGroupInterfaceV1Private; + +class OutputGroupManagerInterfaceV1Private + : public QtWaylandServer::treeland_output_group_manager_v1 +{ +public: + explicit OutputGroupManagerInterfaceV1Private(OutputGroupManagerInterfaceV1 *q); + + wl_global *globalHandle() const { return m_global; } + + struct PendingRequest + { + enum Type + { + SetSource, + AddOutput, + RemoveOutput, + }; + Type type; + QString uuid; + }; + + OutputGroupManagerInterfaceV1 *q; + OutputGroupHost *host = nullptr; + + QStringList groupNames; + QHash effective; + QHash> handles; + bool groupsLoaded = false; + bool recomputing = false; + + QString nextGroupName(); + QString groupOwningOutput(const QString &uuid, const QString &exceptGroup = {}) const; + + void loadPersistedGroupsIfReady(); + void loadPersistedGroups(); + void persistGroupRegistry(); + + OutputGroupInterfaceV1Private *createHandle(Resource *managerResource, + uint32_t id, + const QString &name, + bool valid); + + void sendInitialState(OutputGroupInterfaceV1Private *handle); + void recomputeEffectiveState(); + void broadcastGroupAdded(const QString &name, wl_resource *skipClient); + void broadcastGroupRemoved(const QString &name); + void dissolveGroup(const QString &name); + void commitGroup(OutputGroupInterfaceV1Private *handle); + bool writableGroupName(OutputGroupInterfaceV1Private *handle) const; + +protected: + void bind_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void create_group(Resource *resource, uint32_t id, const QString &source) override; + void get_group(Resource *resource, uint32_t id, const QString &name) override; +}; + +class OutputGroupInterfaceV1Private : public QtWaylandServer::treeland_output_group_v1 +{ +public: + OutputGroupInterfaceV1Private(OutputGroupManagerInterfaceV1Private *_manager, + wl_resource *resource, + const QString &_name, + bool _valid); + + void sendName(); + void sendState(const OutputGroupRuntime &state); + void sendFailure(uint32_t code, const QString &uuid); + void sendDone(); + void sendRemoved(); + void postAlreadyDissolved(); + + OutputGroupManagerInterfaceV1Private *manager; + QString name; + bool valid = true; + bool dissolved = false; + bool nameSent = false; + bool doneSent = false; + bool hasState = false; + QString lastSource; + QStringList lastMirrors; + QList pending; + +protected: + void destroy(Resource *resource) override; + void destroy_resource(Resource *resource) override; + void set_source(Resource *resource, const QString &uuid) override; + void add_output(Resource *resource, const QString &uuid) override; + void remove_output(Resource *resource, const QString &uuid) override; + void commit(Resource *resource) override; + void dissolve(Resource *resource) override; +}; + +OutputGroupInterfaceV1Private::OutputGroupInterfaceV1Private(OutputGroupManagerInterfaceV1Private *_manager, + wl_resource *resource, + const QString &_name, + bool _valid) + : QtWaylandServer::treeland_output_group_v1(resource) + , manager(_manager) + , name(_name) + , valid(_valid) +{ +} + +void OutputGroupInterfaceV1Private::sendName() +{ + if (!valid || nameSent || dissolved) { + return; + } + nameSent = true; + send_name(resource()->handle, name); +} + +void OutputGroupInterfaceV1Private::sendState(const OutputGroupRuntime &state) +{ + if (!valid || dissolved) { + return; + } + if (hasState && lastSource == state.sourceUuid && lastMirrors == state.mirrorUuids) { + return; + } + hasState = true; + lastSource = state.sourceUuid; + lastMirrors = state.mirrorUuids; + + send_state(resource()->handle, + state.sourceUuid, + static_cast(state.mirrorUuids.size()), + concatenateUuids(state.mirrorUuids)); +} + +void OutputGroupInterfaceV1Private::sendFailure(uint32_t code, const QString &uuid) +{ + if (dissolved) { + return; + } + send_operation_failed(resource()->handle, code, uuid); +} + +void OutputGroupInterfaceV1Private::sendDone() +{ + if (dissolved || doneSent) { + return; + } + doneSent = true; + send_done(resource()->handle); +} + +void OutputGroupInterfaceV1Private::sendRemoved() +{ + if (dissolved) { + return; + } + dissolved = true; + pending.clear(); + send_removed(resource()->handle); +} + +void OutputGroupInterfaceV1Private::postAlreadyDissolved() +{ + wl_resource_post_error(resource()->handle, + QtWaylandServer::treeland_output_group_v1::error_already_dissolved, + "The output group has been dissolved"); +} + +void OutputGroupInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void OutputGroupInterfaceV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + if (auto it = manager->handles.find(name); it != manager->handles.end()) { + it->removeOne(this); + if (it->isEmpty()) { + manager->handles.erase(it); + } + } + delete this; +} + +void OutputGroupInterfaceV1Private::set_source([[maybe_unused]] Resource *resource, const QString &uuid) +{ + if (dissolved) { + postAlreadyDissolved(); + return; + } + if (!valid) { + sendFailure(QtWaylandServer::treeland_output_group_v1::failure_invalid_name, QString()); + return; + } + pending.append({ OutputGroupManagerInterfaceV1Private::PendingRequest::SetSource, uuid }); +} + +void OutputGroupInterfaceV1Private::add_output([[maybe_unused]] Resource *resource, const QString &uuid) +{ + if (dissolved) { + postAlreadyDissolved(); + return; + } + if (!valid) { + sendFailure(QtWaylandServer::treeland_output_group_v1::failure_invalid_name, QString()); + return; + } + pending.append({ OutputGroupManagerInterfaceV1Private::PendingRequest::AddOutput, uuid }); +} + +void OutputGroupInterfaceV1Private::remove_output([[maybe_unused]] Resource *resource, const QString &uuid) +{ + if (dissolved) { + postAlreadyDissolved(); + return; + } + if (!valid) { + sendFailure(QtWaylandServer::treeland_output_group_v1::failure_invalid_name, QString()); + return; + } + pending.append({ OutputGroupManagerInterfaceV1Private::PendingRequest::RemoveOutput, uuid }); +} + +void OutputGroupInterfaceV1Private::commit([[maybe_unused]] Resource *resource) +{ + if (dissolved) { + postAlreadyDissolved(); + return; + } + if (!valid) { + sendFailure(QtWaylandServer::treeland_output_group_v1::failure_invalid_name, QString()); + return; + } + manager->commitGroup(this); +} + +void OutputGroupInterfaceV1Private::dissolve([[maybe_unused]] Resource *resource) +{ + if (dissolved) { + postAlreadyDissolved(); + return; + } + if (!valid) { + sendFailure(QtWaylandServer::treeland_output_group_v1::failure_invalid_name, QString()); + return; + } + manager->dissolveGroup(name); +} + +OutputGroupManagerInterfaceV1Private::OutputGroupManagerInterfaceV1Private( + OutputGroupManagerInterfaceV1 *_q) + : QtWaylandServer::treeland_output_group_manager_v1() + , q(_q) +{ +} + +QString OutputGroupManagerInterfaceV1Private::nextGroupName() +{ + auto taken = [this](const QString &name) { + return groupNames.contains(name) || handles.contains(name); + }; + + // Readable, unique and never reused while it exists: epoch seconds make it + // sortable, the random component avoids collisions between groups created + // within the same second. + QString name; + do { + name = QStringLiteral("output-group-%1-%2") + .arg(QDateTime::currentSecsSinceEpoch()) + .arg(QRandomGenerator::global()->generate()); + } while (taken(name)); + return name; +} + +QString OutputGroupManagerInterfaceV1Private::groupOwningOutput(const QString &uuid, + const QString &exceptGroup) const +{ + if (uuid.isEmpty() || !host) { + return {}; + } + + // Only connected outputs have a readable membership record; an unplugged + // output cannot be claimed anyway because it is not available. + const auto members = host->outputGroupMembers(); + for (const auto &member : members) { + if (member.uuid == uuid && !member.groupName.isEmpty() + && member.groupName != exceptGroup) { + return member.groupName; + } + } + return {}; +} + +void OutputGroupManagerInterfaceV1Private::loadPersistedGroupsIfReady() +{ + if (groupsLoaded) { + return; + } + + auto *manager = DConfigManager::instance(); + if (!manager || !manager->globalConfig()) { + return; + } + + auto *global = manager->globalConfig(); + if (global->isInitializeSucceeded()) { + loadPersistedGroups(); + return; + } + if (global->isInitializeFailed()) { + groupsLoaded = true; + return; + } + + QObject::connect( + global, + &TreelandConfig::configInitializeSucceed, + q, + [this](auto *) { loadPersistedGroups(); }, + Qt::SingleShotConnection); + QObject::connect( + global, + &TreelandConfig::configInitializeFailed, + q, + [this]() { groupsLoaded = true; }, + Qt::SingleShotConnection); +} + +void OutputGroupManagerInterfaceV1Private::loadPersistedGroups() +{ + if (groupsLoaded) { + return; + } + groupsLoaded = true; + + auto *manager = DConfigManager::instance(); + if (!manager || !manager->globalConfig()) { + return; + } + + // The registry is the single authority on which groups exist. Membership + // is restored lazily: recomputeEffectiveState() groups the connected + // outputs by their own persisted groupName, and clears membership records + // that point at a group which is no longer registered. + const auto names = manager->globalConfig()->outputGroups().split(kGroupNameSeparator, Qt::SkipEmptyParts); + for (const auto &name : names) { + if (name.isEmpty()) { + continue; + } + if (groupNames.contains(name)) { + // A group was created before the persisted configuration became + // readable and took the same name; the in-memory one wins. + qCWarning(lcTlOutput) << "Not restoring persisted output group" << name + << "because a group with that name already exists"; + continue; + } + + groupNames.append(name); + qCInfo(lcTlOutput) << "Restored output group" << name; + // Clients that bound before the configuration was readable already got + // their groups_done dump; announce the restored groups to them as well + // instead of leaving them permanently invisible. + broadcastGroupAdded(name, nullptr); + } + + recomputeEffectiveState(); +} + +void OutputGroupManagerInterfaceV1Private::persistGroupRegistry() +{ + auto *manager = DConfigManager::instance(); + if (!manager || !manager->globalConfig()) { + return; + } + + manager->globalConfig()->setOutputGroups(groupNames.join(kGroupNameSeparator)); +} + +OutputGroupInterfaceV1Private *OutputGroupManagerInterfaceV1Private::createHandle( + Resource *managerResource, uint32_t id, const QString &name, bool valid) +{ + wl_resource *outputResource = wl_resource_create(managerResource->client(), + &treeland_output_group_v1_interface, + managerResource->version(), + id); + if (!outputResource) { + wl_client_post_no_memory(managerResource->client()); + return nullptr; + } + + auto *handle = new OutputGroupInterfaceV1Private(this, outputResource, name, valid); + if (valid) { + handles[name].append(handle); + handle->sendName(); + } + return handle; +} + +void OutputGroupManagerInterfaceV1Private::sendInitialState(OutputGroupInterfaceV1Private *handle) +{ + if (!handle || !handle->valid) { + return; + } + if (!effective.contains(handle->name)) { + OutputGroupRuntime runtime; + runtime.name = handle->name; + effective.insert(handle->name, runtime); + } + handle->sendState(effective.value(handle->name)); +} + +void OutputGroupManagerInterfaceV1Private::recomputeEffectiveState() +{ + if (recomputing || !host) { + return; + } + + QScopeGuard resetGuard([this] { recomputing = false; }); + recomputing = true; + + const auto members = host->outputGroupMembers(); + + // Lazy cleanup: a membership record pointing at a group that is no longer + // registered is stale (the group was dissolved while the output was + // unplugged), clear it instead of resurrecting the group. + for (const auto &member : members) { + if (!member.groupName.isEmpty() && !groupNames.contains(member.groupName)) { + host->writeOutputGroupMembership(member.uuid, QString(), 0, 0); + } + } + + for (const auto &groupName : std::as_const(groupNames)) { + OutputGroupRuntime runtime; + runtime.name = groupName; + + QList groupMembers; + for (const auto &member : members) { + // Only available (connected and enabled) outputs take part in the + // effective state; a switched-off or unplugged member keeps its + // persisted membership but drops out of the runtime state. + if (member.groupName == groupName && host->isOutputAvailable(member.uuid)) { + groupMembers.append(member); + } + } + + runtime.sourceUuid = resolveGroupSource(groupMembers); + runtime.mirrorUuids = resolveGroupMirrors(groupMembers, runtime.sourceUuid); + + auto it = effective.find(groupName); + if (it == effective.end()) { + effective.insert(groupName, runtime); + } else if (it->sourceUuid != runtime.sourceUuid + || it->mirrorUuids != runtime.mirrorUuids) { + *it = runtime; + } + } + + // Report the effective state to every bound group object. + for (const auto &groupName : std::as_const(groupNames)) { + if (auto it = handles.find(groupName); it != handles.end()) { + for (auto *handle : std::as_const(*it)) { + handle->sendState(effective.value(groupName)); + } + } + } + + // Always let the host re-apply: a caller may have torn copy mode down + // while applying an output configuration without changing the effective + // state, and the reported state must stay consistent with what is + // rendered. applyOutputGroups() is idempotent. + host->applyOutputGroups(); +} + +void OutputGroupManagerInterfaceV1Private::broadcastGroupAdded(const QString &name, + wl_resource *skipClient) +{ + for (auto *resource : resourceMap()) { + if (skipClient && resource->handle == skipClient) { + continue; + } + send_group_added(resource->handle, name); + } +} + +void OutputGroupManagerInterfaceV1Private::broadcastGroupRemoved(const QString &name) +{ + for (auto *resource : resourceMap()) { + send_group_removed(resource->handle, name); + } +} + +void OutputGroupManagerInterfaceV1Private::dissolveGroup(const QString &name) +{ + for (int i = 0; i < groupNames.size(); ++i) { + if (groupNames.at(i) == name) { + groupNames.removeAt(i); + break; + } + } + + if (auto it = handles.find(name); it != handles.end()) { + const auto groupHandles = *it; + handles.erase(it); + for (auto *handle : groupHandles) { + handle->sendRemoved(); + } + } + + effective.remove(name); + + // Clear the membership of the connected members; unplugged members keep + // their stale records until they come back and are cleaned up lazily by + // recomputeEffectiveState(). + if (host) { + const auto members = host->outputGroupMembers(); + for (const auto &member : members) { + if (member.groupName == name) { + host->writeOutputGroupMembership(member.uuid, QString(), 0, 0); + } + } + } + + persistGroupRegistry(); + broadcastGroupRemoved(name); + recomputeEffectiveState(); +} + +bool OutputGroupManagerInterfaceV1Private::writableGroupName( + OutputGroupInterfaceV1Private *handle) const +{ + return handle && handle->valid && !handle->dissolved + && groupNames.contains(handle->name); +} + +void OutputGroupManagerInterfaceV1Private::commitGroup(OutputGroupInterfaceV1Private *handle) +{ + if (!writableGroupName(handle)) { + handle->sendFailure(QtWaylandServer::treeland_output_group_v1::failure_invalid_name, QString()); + return; + } + const QString &name = handle->name; + if (!host) { + handle->pending.clear(); + return; + } + + const auto pending = std::exchange(handle->pending, {}); + + // Snapshot of the connected outputs' membership; writes below go through + // the host and update the snapshot, so later requests in the same batch + // observe the earlier ones. + QHash membersByUuid; + const auto members = host->outputGroupMembers(); + for (const auto &member : members) { + membersByUuid.insert(member.uuid, member); + } + auto writeMembership = [this, &membersByUuid](const QString &uuid, + const QString &groupName, + qlonglong joinTime, + qlonglong lastSetSourceTime) { + host->writeOutputGroupMembership(uuid, groupName, joinTime, lastSetSourceTime); + membersByUuid.insert(uuid, { uuid, groupName, joinTime, lastSetSourceTime }); + }; + + // A later set_source replaces an earlier uncommitted one: only the most + // recent source designation in the queue is applied, the others are + // dropped silently (no operation_failed for them either). + int lastSetSource = -1; + for (int i = 0; i < pending.size(); ++i) { + if (pending.at(i).type == PendingRequest::SetSource) { + lastSetSource = i; + } + } + + for (int i = 0; i < pending.size(); ++i) { + const auto &request = pending.at(i); + if (request.type == PendingRequest::SetSource && i != lastSetSource) { + continue; + } + + switch (request.type) { + case PendingRequest::SetSource: { + const auto memberIt = membersByUuid.constFind(request.uuid); + if (request.uuid.isEmpty() || memberIt == membersByUuid.cend() + || !host->isOutputAvailable(request.uuid)) { + handle->sendFailure(QtWaylandServer::treeland_output_group_v1::failure_invalid_output, + request.uuid); + break; + } + if (!memberIt->groupName.isEmpty() && memberIt->groupName != name) { + handle->sendFailure(QtWaylandServer::treeland_output_group_v1::failure_output_in_use, + request.uuid); + break; + } + + // Pin the output as the source: it joins the group when it was + // not a member yet. The designation only has to be strictly more + // recent than every other member's marker, so resolveGroupSource() + // picks this member; older markers are left untouched. Clamp the + // timestamp so a same-millisecond or clock-adjusted designation + // still wins. + const qlonglong now = QDateTime::currentMSecsSinceEpoch(); + qlonglong sourceTime = now; + for (const auto &member : std::as_const(membersByUuid)) { + if (member.groupName == name && member.uuid != request.uuid + && member.lastSetSourceTime >= sourceTime) { + sourceTime = member.lastSetSourceTime + 1; + } + } + const bool joinsGroup = memberIt->groupName.isEmpty(); + writeMembership(request.uuid, + name, + joinsGroup ? now : memberIt->joinTime, + sourceTime); + break; + } + case PendingRequest::AddOutput: { + const auto memberIt = membersByUuid.constFind(request.uuid); + if (request.uuid.isEmpty() || memberIt == membersByUuid.cend() + || !host->isOutputAvailable(request.uuid)) { + handle->sendFailure(QtWaylandServer::treeland_output_group_v1::failure_invalid_output, + request.uuid); + break; + } + if (memberIt->groupName == name) { + handle->sendFailure(QtWaylandServer::treeland_output_group_v1::failure_duplicate_output, + request.uuid); + break; + } + if (!memberIt->groupName.isEmpty()) { + handle->sendFailure(QtWaylandServer::treeland_output_group_v1::failure_output_in_use, + request.uuid); + break; + } + writeMembership(request.uuid, + name, + QDateTime::currentMSecsSinceEpoch(), + 0); + break; + } + case PendingRequest::RemoveOutput: { + const auto memberIt = membersByUuid.constFind(request.uuid); + if (memberIt != membersByUuid.cend() && memberIt->groupName == name) { + writeMembership(request.uuid, QString(), 0, 0); + } else { + handle->sendFailure(QtWaylandServer::treeland_output_group_v1::failure_not_in_group, + request.uuid); + } + break; + } + } + } + + recomputeEffectiveState(); +} + +void OutputGroupManagerInterfaceV1Private::bind_resource(Resource *resource) +{ + loadPersistedGroupsIfReady(); + + for (const auto &groupName : std::as_const(groupNames)) { + send_group_added(resource->handle, groupName); + } + send_groups_done(resource->handle); +} + +void OutputGroupManagerInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void OutputGroupManagerInterfaceV1Private::create_group(Resource *resource, + uint32_t id, + const QString &source) +{ + const QString name = nextGroupName(); + + QString failedUuid; + uint32_t failure = 0; + if (!source.isEmpty()) { + if (!host || !host->isOutputAvailable(source)) { + failedUuid = source; + failure = QtWaylandServer::treeland_output_group_v1::failure_invalid_output; + } else if (!groupOwningOutput(source).isEmpty()) { + failedUuid = source; + failure = QtWaylandServer::treeland_output_group_v1::failure_output_in_use; + } else { + const qlonglong now = QDateTime::currentMSecsSinceEpoch(); + host->writeOutputGroupMembership(source, name, now, now); + } + } + + groupNames.append(name); + persistGroupRegistry(); + // Compute the effective state before the new object exists, so its initial + // batch carries the state the create request produced. An empty-source + // group needs no host validation, and recomputeEffectiveState() is a no-op + // until the host is attached: setHost() recomputes on attach, so the group + // is picked up then. + recomputeEffectiveState(); + + auto *handle = createHandle(resource, id, name, true); + if (handle) { + sendInitialState(handle); + if (failure != 0) { + handle->sendFailure(failure, failedUuid); + } + handle->sendDone(); + } + + broadcastGroupAdded(name, resource->handle); +} + +void OutputGroupManagerInterfaceV1Private::get_group(Resource *resource, + uint32_t id, + const QString &name) +{ + if (name.isEmpty() || !groupNames.contains(name)) { + auto *handle = createHandle(resource, id, name, false); + if (handle) { + handle->sendFailure(QtWaylandServer::treeland_output_group_v1::failure_invalid_name, QString()); + handle->sendDone(); + } + return; + } + + recomputeEffectiveState(); + + auto *handle = createHandle(resource, id, name, true); + if (handle) { + sendInitialState(handle); + handle->sendDone(); + } +} + +OutputGroupManagerInterfaceV1::OutputGroupManagerInterfaceV1(QObject *parent) + : QObject(parent) + , d(new OutputGroupManagerInterfaceV1Private(this)) +{ +} + +OutputGroupManagerInterfaceV1::~OutputGroupManagerInterfaceV1() = default; + +void OutputGroupManagerInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); + d->loadPersistedGroupsIfReady(); +} + +void OutputGroupManagerInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *OutputGroupManagerInterfaceV1::global() const +{ + return d->globalHandle(); +} + +QByteArrayView OutputGroupManagerInterfaceV1::interfaceName() const +{ + return QtWaylandServer::treeland_output_group_manager_v1::interfaceName(); +} + +void OutputGroupManagerInterfaceV1::setHost(OutputGroupHost *host) +{ + d->host = host; + d->loadPersistedGroupsIfReady(); + d->recomputeEffectiveState(); +} + +QList OutputGroupManagerInterfaceV1::effectiveGroups() const +{ + QList result; + result.reserve(d->groupNames.size()); + for (const auto &groupName : std::as_const(d->groupNames)) { + result.append(d->effective.value(groupName)); + } + return result; +} + +void OutputGroupManagerInterfaceV1::notifyOutputAvailabilityChanged() +{ + d->recomputeEffectiveState(); +} + +QString OutputGroupManagerInterfaceV1::createGroup(const QString &sourceUuid, + const QStringList &mirrorUuids) +{ + if (!d->host) { + return {}; + } + + // This entry point behaves like a client using the protocol, so it applies + // the same rules: members must be connected, enabled and claimed by no + // other group. + if (sourceUuid.isEmpty() || !d->host->isOutputAvailable(sourceUuid) + || !d->groupOwningOutput(sourceUuid).isEmpty()) { + return {}; + } + + QStringList acceptedMirrors; + for (const auto &uuid : mirrorUuids) { + if (d->host->isOutputAvailable(uuid) && d->groupOwningOutput(uuid).isEmpty() + && uuid != sourceUuid && !acceptedMirrors.contains(uuid)) { + acceptedMirrors.append(uuid); + } + } + + const QString name = d->nextGroupName(); + + const qlonglong now = QDateTime::currentMSecsSinceEpoch(); + d->host->writeOutputGroupMembership(sourceUuid, name, now, now); + for (const auto &uuid : std::as_const(acceptedMirrors)) { + d->host->writeOutputGroupMembership(uuid, name, now, 0); + } + + d->groupNames.append(name); + d->persistGroupRegistry(); + d->broadcastGroupAdded(name, nullptr); + d->recomputeEffectiveState(); + return name; +} + +bool OutputGroupManagerInterfaceV1::dissolveGroup(const QString &name) +{ + if (!d->groupNames.contains(name)) { + return false; + } + d->dissolveGroup(name); + return true; +} diff --git a/src/modules/output-group/outputgroupmanagerinterfacev1.h b/src/modules/output-group/outputgroupmanagerinterfacev1.h new file mode 100644 index 0000000000..d49ee9d473 --- /dev/null +++ b/src/modules/output-group/outputgroupmanagerinterfacev1.h @@ -0,0 +1,95 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include +#include +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +// Membership state of one connected output, persisted in the output's own +// configuration: the group it belongs to, when it joined the group and when +// it was last explicitly designated as the source (0 = never). The effective +// source is resolved from these records at runtime, never stored. +struct OutputGroupMemberInfo +{ + QString uuid; + QString groupName; + qlonglong joinTime = 0; + qlonglong lastSetSourceTime = 0; +}; + +// Effective runtime state of one output group as seen by clients. +struct OutputGroupRuntime +{ + QString name; + QString sourceUuid; + QStringList mirrorUuids; +}; + +// Compositor side of the protocol: the group manager decides what the groups +// mean, this class only keeps the protocol state and forwards the effective +// configuration to the host which applies copy mode to the outputs. +class OutputGroupHost +{ +public: + virtual ~OutputGroupHost() = default; + + // Output is connected and enabled, so it may take part in copy mode. + virtual bool isOutputAvailable(const QString &uuid) const = 0; + // Membership of every connected output whose configuration is readable. + virtual QList outputGroupMembers() const = 0; + // Persist the membership fields of one connected output. + virtual void writeOutputGroupMembership(const QString &uuid, + const QString &groupName, + qlonglong joinTime, + qlonglong lastSetSourceTime) = 0; + // Apply the effective group state to the outputs. + virtual void applyOutputGroups() = 0; +}; + +class OutputGroupManagerInterfaceV1Private; +class OutputGroupManagerInterfaceV1 + : public QObject + , public WServerInterface +{ + Q_OBJECT + +public: + explicit OutputGroupManagerInterfaceV1(QObject *parent = nullptr); + ~OutputGroupManagerInterfaceV1() override; + + static constexpr int InterfaceVersion = 1; + + QByteArrayView interfaceName() const override; + + void setHost(OutputGroupHost *host); + QList effectiveGroups() const; + + // Output availability changed (hotplug, enable, disable): recompute the + // effective state and re-apply copy mode. + void notifyOutputAvailabilityChanged(); + + // Debug/menu-bar entry points, they behave like a client using the + // protocol: one group whose source is sourceUuid. Returns the + // compositor-assigned name of the created group, or an empty string when + // no group was created. + QString createGroup(const QString &sourceUuid, const QStringList &mirrorUuids); + bool dissolveGroup(const QString &name); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + friend class OutputGroupManagerInterfaceV1Private; + std::unique_ptr d; +}; diff --git a/src/modules/output-manager/CMakeLists.txt b/src/modules/output-manager/CMakeLists.txt new file mode 100644 index 0000000000..2b00ac6efe --- /dev/null +++ b/src/modules/output-manager/CMakeLists.txt @@ -0,0 +1,16 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-output-manager-unstable-v2.xml + BASENAME treeland-output-manager-unstable-v2 +) + +impl_treeland( + NAME + module_outputmanager + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/output-manager/outputmanagement.h + ${CMAKE_SOURCE_DIR}/src/modules/output-manager/outputmanagement.cpp + INCLUDE + $ +) diff --git a/src/modules/output-manager/outputmanagement.cpp b/src/modules/output-manager/outputmanagement.cpp new file mode 100644 index 0000000000..8db05cf4a3 --- /dev/null +++ b/src/modules/output-manager/outputmanagement.cpp @@ -0,0 +1,397 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "qwayland-server-treeland-output-manager-unstable-v2.h" + +#include "outputmanagement.h" +#include "session/session.h" +#include "session/sessionoutputmanager.h" +#include "outputconfig.hpp" +#include "rootsurfacecontainer.h" +#include "core/waylandserver.h" +#include "output.h" + +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class PictureControlV2Private : public QtWaylandServer::treeland_output_picture_control_v2 +{ +public: + explicit PictureControlV2Private(PictureControlV2 *_q, wl_resource *resource, const QString &uuid, SessionOutputManager *owner); + + PictureControlV2 *q; + + // v2: invalid_output is terminal. Once it has been delivered on this object + // (at creation time or in response to a commit) the object is permanently + // inert: only destroy stays valid, no further result, color_temperature or + // brightness event is emitted, and it never recovers even if an output + // with this uuid is connected later. The client must destroy it and call + // get_picture_control again to get a usable object. + bool inert = false; + + SessionOutputManager *const owner; + QString uuid; + QPointer controlOutput; + + // Pending protocol values accumulated since the last commit; nullopt means + // "not set". Color temperature valid range [1000, 20000], brightness + // [0.0, 100.0]. Out-of-range set_* values are rejected with a fatal + // protocol error and never reach the pending state. + std::optional pendingColorTemperature; + std::optional pendingBrightness; + + void send_brightness(qreal brightness); + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + + void set_color_temperature(Resource *resource, uint32_t temperature) override; + void set_brightness(Resource *resource, wl_fixed_t brightness) override; + void commit(Resource *resource) override; + +private: + void resolveOutput(); + void attachOutput(Output *output); + void detachOutput(); + void becomeInert(); + + QList modelConnections; + QList configConnections; +}; + +PictureControlV2Private::PictureControlV2Private(PictureControlV2 *_q, wl_resource *resource, const QString &_uuid, SessionOutputManager *owner) + : treeland_output_picture_control_v2(resource) + , q(_q) + , owner(owner) + , uuid(_uuid) +{ + // The uuid must identify a live enabled output at creation time. Otherwise + // the object is still created, but v2 requires an immediate result + // (invalid_output) instead of the initial values, and the object is inert + // from the start: no output model tracking, no recovery. + auto *output = WaylandServer::instance()->getOutputByUuid(uuid); + if (!output || !output->output()->isEnabled()) { + send_result(commit_result_invalid_output); + becomeInert(); + return; + } + + // Commits and value events follow the output that currently carries this + // uuid, so re-resolve whenever the output model changes. + auto *model = WaylandServer::instance()->rootSurfaceContainer()->outputModel(); + modelConnections = { + QObject::connect(model, &QAbstractItemModel::rowsInserted, q, [this] { + resolveOutput(); + }), + QObject::connect(model, &QAbstractItemModel::rowsRemoved, q, [this] { + resolveOutput(); + }), + }; + + attachOutput(output); +} + +void PictureControlV2Private::resolveOutput() +{ + attachOutput(WaylandServer::instance()->getOutputByUuid(uuid)); +} + +void PictureControlV2Private::detachOutput() +{ + for (const auto &connection : std::as_const(configConnections)) + QObject::disconnect(connection); + configConnections.clear(); + controlOutput = nullptr; +} + +void PictureControlV2Private::becomeInert() +{ + if (inert) + return; + + inert = true; + + // An inert object stops following the output model: it must not pick up an + // output that appears later with the same uuid. + for (const auto &connection : std::as_const(modelConnections)) + QObject::disconnect(connection); + modelConnections.clear(); + + detachOutput(); +} + +void PictureControlV2Private::attachOutput(Output *output) +{ + if (inert || controlOutput == output) + return; + + detachOutput(); + + controlOutput = output; + if (!controlOutput) + return; + + auto *outputConfig = owner->config(controlOutput->getOutputId()); + send_brightness(outputConfig->brightness()); + send_color_temperature(outputConfig->colorTemperature()); + + configConnections = { + QObject::connect(outputConfig, + &OutputConfig::colorTemperatureChanged, + q, + [this, outputConfig] { + send_color_temperature(outputConfig->colorTemperature()); + }), + QObject::connect(outputConfig, + &OutputConfig::brightnessChanged, + q, + [this, outputConfig] { + send_brightness(outputConfig->brightness()); + }), + }; +} + +void PictureControlV2Private::destroy_resource(Resource *resource) +{ + Q_UNUSED(resource); + q->deleteLater(); +} + +void PictureControlV2Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void PictureControlV2Private::set_color_temperature(Resource *resource, + uint32_t temperature) +{ + if (temperature < 1000 || temperature > 20000) { + wl_resource_post_error(resource->handle, + error_invalid_color_temperature, + "Color temperature must be between 1000K and 20000K"); + return; + } + // v2: range validation is a fatal protocol error on the request itself and + // stays valid on an inert object; only the pending state is dropped, and no + // event is ever emitted for it. + if (inert) + return; + pendingColorTemperature = temperature; +} + +void PictureControlV2Private::set_brightness(Resource *resource, + wl_fixed_t wl_brightness) +{ + const qreal brightness = wl_fixed_to_double(wl_brightness); + if (brightness < 0.0 || brightness > 100.0) { + wl_resource_post_error(resource->handle, + error_invalid_brightness, + "Brightness must be between 0.0 and 100.0"); + return; + } + // See set_color_temperature: keep the fatal range check, drop the value. + if (inert) + return; + pendingBrightness = brightness; +} + +void PictureControlV2Private::send_brightness(qreal brightness) +{ + // brightness is internal [0.0, 1.0]; protocol range is [0.0, 100.0] (wl_fixed_t). + // wl_fixed_from_double() rounds, so full brightness maps to exactly 100.0 + // and stays inside the range the client may send back. + treeland_output_picture_control_v2::send_brightness(wl_fixed_from_double(brightness * 100.0)); +} + +void PictureControlV2Private::commit(Resource *resource) +{ + Q_UNUSED(resource); + // v2: an inert object only accepts destroy; commit produces no event at all. + if (inert) + return; + + // v2: range validation happens on the set_* requests with a fatal protocol + // error, so a commit only fails for output-related reasons + // (invalid_output, unsupported, failed). + if (!controlOutput || !controlOutput->output()->isEnabled()) { + pendingColorTemperature.reset(); + pendingBrightness.reset(); + // invalid_output is the last event this object ever sends: it becomes + // permanently inert right after, whether the output was missing from + // the start or was unplugged/disabled between two commits. + send_result(commit_result_invalid_output); + becomeInert(); + return; + } + + // Nothing to commit — report success immediately. + if (!pendingColorTemperature && !pendingBrightness) { + send_result(commit_result_success); + return; + } + + // Convert protocol values to treeland internal values. + // Brightness: protocol [0.0, 100.0] → treeland [0.0, 1.0]. + // -1 / 0 sentinel means "not requested" for setOutputColor. + qreal treelandBrightness = pendingBrightness ? *pendingBrightness / 100.0 : -1; + uint32_t treelandColorTemp = pendingColorTemperature ? *pendingColorTemperature : 0; + + QPointer guard(q); + owner->applyColor(controlOutput, treelandBrightness, treelandColorTemp, [guard, this](Output::CommitColorResult result) { + if (!guard) + return; + switch (result) { + case Output::CommitColorResult::Success: + send_result(commit_result_success); + break; + case Output::CommitColorResult::Unsupported: + send_result(commit_result_unsupported); + break; + case Output::CommitColorResult::Failed: + send_result(commit_result_failed); + break; + } + }); + pendingColorTemperature.reset(); + pendingBrightness.reset(); +} + +PictureControlV2::PictureControlV2(wl_resource *resource, const QString &uuid, SessionOutputManager *owner, QObject *parent) + : QObject(parent) + , d(new PictureControlV2Private(this, resource, uuid, owner)) +{ +} + +PictureControlV2::~PictureControlV2() +{ +} + +class OutputManagerV2Private : public QtWaylandServer::treeland_output_manager_v2 +{ +public: + explicit OutputManagerV2Private(OutputManagerV2 *_q); + wl_global *global() const; + + OutputManagerV2 *q; + +protected: + void bind_resource(Resource *resource) override; + void destroy(Resource *resource) override; + + void set_primary_output(Resource *resource, const QString &uuid) override; + void get_picture_control(Resource *resource, uint32_t id, const QString &uuid) override; +}; + +OutputManagerV2Private::OutputManagerV2Private(OutputManagerV2 *_q) + : QtWaylandServer::treeland_output_manager_v2() + , q(_q) +{ +} + +wl_global *OutputManagerV2Private::global() const +{ + return m_global; +} + +void OutputManagerV2Private::bind_resource(Resource *resource) +{ + // v2: emit primary_output immediately after bind, carrying the uuid of the + // current primary output (empty when none is available). + auto *primaryOutput = WaylandServer::instance()->rootSurfaceContainer()->primaryOutput(); + send_primary_output(resource->handle, primaryOutput ? primaryOutput->uuid() : QString()); +} + +void OutputManagerV2Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void OutputManagerV2Private::set_primary_output(Resource *resource, const QString &uuid) +{ + auto *o = WaylandServer::instance()->getOutputByUuid(uuid); + // v2: an empty or unknown uuid, and a disabled output, are rejected via + // primary_output_failed instead of a protocol error. + if (!q->isActive() || !o || !o->output()->isEnabled()) { + send_primary_output_failed(resource->handle, primary_output_failed_reason_invalid_output); + return; + } + + auto *container = WaylandServer::instance()->rootSurfaceContainer(); + // setPrimaryOutput() is a no-op when the output is already primary, but v2 + // requires a primary_output event to confirm every set_primary_output + // request, so confirm same-value requests explicitly. + const bool changed = container->primaryOutput() != o; + q->session()->outputManager()->setPrimaryOutput(o->output()->name()); + if (!changed) + q->onPrimaryOutputChanged(); +} + +void OutputManagerV2Private::get_picture_control(Resource *resource, + uint32_t id, + const QString &uuid) +{ + // The object is always created, even for an empty or unknown uuid. When the + // uuid does not identify a live enabled output, PictureControlV2 reports + // result(invalid_output) immediately and becomes permanently inert; the + // client must destroy it and call this request again. + auto *picture_control_res = wl_resource_create(resource->client(), + QtWaylandServer::treeland_output_picture_control_v2::interface(), + OutputManagerV2::PictureControlInterfaceVersion, + id); + if (!picture_control_res) { + wl_resource_post_no_memory(resource->handle); + return; + } + + // The PictureControlV2 object is owned by its wl_resource: destroy_resource() + // schedules q->deleteLater(). It must not be deleted here or leaked. + auto pictureControl = new PictureControlV2(picture_control_res, uuid, q->session()->outputManager(), q); + Q_UNUSED(pictureControl); +} + +OutputManagerV2::OutputManagerV2(Session *session) + : SessionComponent(session) + , d(new OutputManagerV2Private(this)) +{ + connect(WaylandServer::instance()->rootSurfaceContainer(), + &RootSurfaceContainer::primaryOutputChanged, + this, &OutputManagerV2::onPrimaryOutputChanged); +} + +OutputManagerV2::~OutputManagerV2() +{ +} + +void OutputManagerV2::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void OutputManagerV2::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *OutputManagerV2::global() const +{ + return d->global(); +} + +QByteArrayView OutputManagerV2::interfaceName() const +{ + return d->interfaceName(); +} + +void OutputManagerV2::onPrimaryOutputChanged() +{ + auto *primaryOutput = WaylandServer::instance()->rootSurfaceContainer()->primaryOutput(); + for (const auto &resource : d->resourceMap()) { + d->send_primary_output(resource->handle, + primaryOutput ? primaryOutput->uuid() : QString()); + } +} diff --git a/src/modules/output-manager/outputmanagement.h b/src/modules/output-manager/outputmanagement.h new file mode 100644 index 0000000000..d96b022108 --- /dev/null +++ b/src/modules/output-manager/outputmanagement.h @@ -0,0 +1,54 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include "session/sessioncomponent.h" + +#include + +struct treeland_output_manager_v2; +struct treeland_output_picture_control_v2; +WAYLIB_SERVER_USE_NAMESPACE + +class SessionOutputManager; +class PictureControlV2Private; +class OutputManagerV2Private; + +class PictureControlV2 : public QObject +{ + Q_OBJECT +public: + ~PictureControlV2() override; + +private: + explicit PictureControlV2(wl_resource *resource, const QString &uuid, SessionOutputManager *owner, QObject *parent); + friend OutputManagerV2Private; + std::unique_ptr d; +}; + +class OutputManagerV2 + : public SessionComponent + , public WServerInterface +{ + Q_OBJECT +public: + explicit OutputManagerV2(Session *session); + ~OutputManagerV2() override; + static constexpr int InterfaceVersion = 1; + static constexpr int PictureControlInterfaceVersion = 1; + + QByteArrayView interfaceName() const override; + +public Q_SLOTS: + void onPrimaryOutputChanged(); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; diff --git a/src/modules/output-uuid/CMakeLists.txt b/src/modules/output-uuid/CMakeLists.txt new file mode 100644 index 0000000000..5d25ede862 --- /dev/null +++ b/src/modules/output-uuid/CMakeLists.txt @@ -0,0 +1,30 @@ +find_package(TreelandProtocols 0.7.0 REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-output-uuid-unstable-v1.xml + BASENAME treeland-output-uuid-unstable-v1 +) + +# treeland-output-uuid-head-unstable-v1 takes a zwlr_output_head_v1 argument, so +# its generated code needs zwlr_output_head_v1_interface. waylib-wlroots only +# exports wlr_*/waylib_* (see 3rdparty/wlroots/wlroots.syms), which hides that +# symbol, so generate the wlr-output-management protocol into libtreeland too. +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${CMAKE_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-output-management-unstable-v1.xml + BASENAME wlr-output-management-unstable-v1 +) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-output-uuid-head-unstable-v1.xml + BASENAME treeland-output-uuid-head-unstable-v1 +) + +impl_treeland( + NAME + module_output_uuid + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/output-uuid/outputuuidmanagerinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/output-uuid/outputuuidmanagerinterfacev1.cpp + INCLUDE + $ +) diff --git a/src/modules/output-uuid/outputuuidmanagerinterfacev1.cpp b/src/modules/output-uuid/outputuuidmanagerinterfacev1.cpp new file mode 100644 index 0000000000..7045b50ba8 --- /dev/null +++ b/src/modules/output-uuid/outputuuidmanagerinterfacev1.cpp @@ -0,0 +1,207 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "outputuuidmanagerinterfacev1.h" + +#include "core/waylandserver.h" +#include "output.h" +#include "qwayland-server-treeland-output-uuid-unstable-v1.h" +#include "qwayland-server-treeland-output-uuid-head-unstable-v1.h" + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class OutputUuidV1 : public QtWaylandServer::treeland_output_uuid_v1 +{ +public: + OutputUuidV1(wl_resource *resource, const QString &uuid) + : QtWaylandServer::treeland_output_uuid_v1(resource) + { + send_uuid(resource, uuid); + } + +protected: + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void destroy_resource(Resource *resource) override + { + Q_UNUSED(resource); + delete this; + } +}; + +class OutputUuidManagerV1Private + : public QObject + , public QtWaylandServer::treeland_output_uuid_manager_v1 +{ + Q_OBJECT +public: + explicit OutputUuidManagerV1Private(QObject *parent = nullptr) + : QObject(parent) + , QtWaylandServer::treeland_output_uuid_manager_v1() + { + } + + wl_global *globalHandle() const + { + return m_global; + } + +protected: + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void get_uuid(Resource *resource, uint32_t id, struct ::wl_resource *output) override + { + auto *wlr_o = wlr_output_from_resource(output); + if (!wlr_o) { + wl_resource_post_error(resource->handle, + WL_DISPLAY_ERROR_INVALID_OBJECT, + "Invalid wl_output resource"); + return; + } + + auto *o = WaylandServer::instance()->getOutput(WOutput::fromHandle(wlr_o)); + if (!o) { + wl_resource_post_error(resource->handle, + WL_DISPLAY_ERROR_INVALID_OBJECT, + "Output not found"); + return; + } + + auto *objRes = wl_resource_create(resource->client(), + QtWaylandServer::treeland_output_uuid_v1::interface(), + resource->version(), + id); + if (!objRes) { + wl_resource_post_no_memory(resource->handle); + return; + } + + new OutputUuidV1(objRes, o->uuid()); // sends uuid during construction + } +}; + +class OutputUuidHeadManagerV1Private + : public QObject + , public QtWaylandServer::treeland_output_uuid_head_manager_v1 +{ + Q_OBJECT +public: + explicit OutputUuidHeadManagerV1Private(QObject *parent = nullptr) + : QObject(parent) + , QtWaylandServer::treeland_output_uuid_head_manager_v1() + { + } + + wl_global *globalHandle() const + { + return m_global; + } + +protected: + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void get_uuid(Resource *resource, uint32_t id, struct ::wl_resource *head) override + { + // wlroots stores the owning wlr_output_head_v1 as the head resource user data; + // a destroyed/inert head has it reset to NULL, caught by the !headObj check. + auto *headObj = static_cast(wl_resource_get_user_data(head)); + if (!headObj || !headObj->state.output) { + wl_resource_post_error(resource->handle, + WL_DISPLAY_ERROR_INVALID_OBJECT, + "Invalid wlr output head resource"); + return; + } + + auto *o = WaylandServer::instance()->getOutput( + WOutput::fromHandle(headObj->state.output)); + if (!o) { + wl_resource_post_error(resource->handle, + WL_DISPLAY_ERROR_INVALID_OBJECT, + "Output not found"); + return; + } + + auto *objRes = wl_resource_create(resource->client(), + QtWaylandServer::treeland_output_uuid_v1::interface(), + resource->version(), + id); + if (!objRes) { + wl_resource_post_no_memory(resource->handle); + return; + } + + new OutputUuidV1(objRes, o->uuid()); // sends uuid during construction + } +}; + +OutputUuidManagerV1::OutputUuidManagerV1(QObject *parent) + : QObject(parent) + , WServerInterface() + , d(std::make_unique()) +{ +} + +OutputUuidManagerV1::~OutputUuidManagerV1() = default; + +QByteArrayView OutputUuidManagerV1::interfaceName() const +{ + return QtWaylandServer::treeland_output_uuid_manager_v1::interfaceName(); +} + +void OutputUuidManagerV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void OutputUuidManagerV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *OutputUuidManagerV1::global() const +{ + return d->globalHandle(); +} + +OutputUuidHeadManagerV1::OutputUuidHeadManagerV1(QObject *parent) + : QObject(parent) + , WServerInterface() + , d(std::make_unique()) +{ +} + +OutputUuidHeadManagerV1::~OutputUuidHeadManagerV1() = default; + +QByteArrayView OutputUuidHeadManagerV1::interfaceName() const +{ + return QtWaylandServer::treeland_output_uuid_head_manager_v1::interfaceName(); +} + +void OutputUuidHeadManagerV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void OutputUuidHeadManagerV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *OutputUuidHeadManagerV1::global() const +{ + return d->globalHandle(); +} + +#include "outputuuidmanagerinterfacev1.moc" diff --git a/src/modules/output-uuid/outputuuidmanagerinterfacev1.h b/src/modules/output-uuid/outputuuidmanagerinterfacev1.h new file mode 100644 index 0000000000..47076dca32 --- /dev/null +++ b/src/modules/output-uuid/outputuuidmanagerinterfacev1.h @@ -0,0 +1,59 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class OutputUuidManagerV1Private; +class OutputUuidHeadManagerV1Private; + +class OutputUuidManagerV1 + : public QObject + , public WServerInterface +{ + Q_OBJECT +public: + explicit OutputUuidManagerV1(QObject *parent = nullptr); + ~OutputUuidManagerV1() override; + + static constexpr int InterfaceVersion = 1; + + QByteArrayView interfaceName() const override; + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; + +class OutputUuidHeadManagerV1 + : public QObject + , public WServerInterface +{ + Q_OBJECT +public: + explicit OutputUuidHeadManagerV1(QObject *parent = nullptr); + ~OutputUuidHeadManagerV1() override; + + static constexpr int InterfaceVersion = 1; + + QByteArrayView interfaceName() const override; + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; diff --git a/src/modules/personalization/CMakeLists.txt b/src/modules/personalization/CMakeLists.txt new file mode 100644 index 0000000000..b617902fb2 --- /dev/null +++ b/src/modules/personalization/CMakeLists.txt @@ -0,0 +1,50 @@ +# ============================================================================ +# DEPRECATED: treeland-personalization-manager-v1 +# +# This module is frozen. The old treeland-personalization-manager-v1 protocol +# has been split into separate protocols in treeland-protocols 0.6.0: +# - treeland-appearance-unstable-v1 → src/modules/appearance/ +# - treeland-appearance-manager-unstable-v1 → src/modules/appearance/ +# - treeland-decoration-unstable-v1 → (not yet implemented) +# +# No new features will be added here. New code should use the new modules. +# This module is kept only for backward compatibility during the transition. +# ============================================================================ + +find_package(TreelandProtocols REQUIRED) + +# --- Deprecated protocol (kept for backward compatibility) --- +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-personalization-manager-v1.xml + BASENAME treeland-personalization-manager-v1 +) + +find_package(Dtk6Core REQUIRED) + +set(PUBLIC_HEADERS + ${CMAKE_SOURCE_DIR}/src/modules/personalization/personalizationmanagerinterfacev1.h +) + +set(SRCS + ${CMAKE_SOURCE_DIR}/src/modules/personalization/personalizationmanagerinterfacev1.cpp +) + +impl_treeland( + NAME + module_personalization + SOURCE + ${PUBLIC_HEADERS} + ${SRCS} + INCLUDE + $ +) + +qt_add_resources(libtreeland "default_background" + PREFIX "/" + FILES + desktop.webp +) + +if(TREELAND_INSTALL_DEV) + install(FILES ${PUBLIC_HEADERS} DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/treeland/modules/personalization") +endif() diff --git a/src/modules/personalization/desktop.webp b/src/modules/personalization/desktop.webp new file mode 100644 index 0000000000..6f7b2e70cf Binary files /dev/null and b/src/modules/personalization/desktop.webp differ diff --git a/src/modules/personalization/personalizationmanagerinterfacev1.cpp b/src/modules/personalization/personalizationmanagerinterfacev1.cpp new file mode 100644 index 0000000000..a65a88d9d1 --- /dev/null +++ b/src/modules/personalization/personalizationmanagerinterfacev1.cpp @@ -0,0 +1,1180 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "personalizationmanagerinterfacev1.h" +#include "session/session.h" + +// DEPRECATED: This module is frozen. Use treeland-appearance-unstable-v1 and +// treeland-appearance-manager-unstable-v1 (src/modules/appearance/) instead. +// No new features will be added to this protocol. +#include "surfacewrapper.h" + +#include "qwayland-server-treeland-personalization-manager-v1.h" + +#include "core/waylandserver.h" +#include "common/treelandlogging.h" +#include "treelanduserconfig.hpp" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +DCORE_USE_NAMESPACE + +static QList s_windowContexts; +static QList s_cursorContexts; +static QList s_fontContexts; +static QList s_appearanceContexts; + +// Protocol theme_type (auto=1, light=2, dark=4) → DConfig windowColorScheme (0=light, 1=dark) +static std::optional protocolThemeTypeToDConfig(uint32_t type) +{ + switch (type) { + case TREELAND_PERSONALIZATION_APPEARANCE_CONTEXT_V1_THEME_TYPE_LIGHT: + return 0; + case TREELAND_PERSONALIZATION_APPEARANCE_CONTEXT_V1_THEME_TYPE_DARK: + return 1; + case TREELAND_PERSONALIZATION_APPEARANCE_CONTEXT_V1_THEME_TYPE_AUTO: + qCCritical(lcTlConfig) + << "Protocol window theme type AUTO is not supported by dconfig."; + return std::nullopt; + default: + qCWarning(lcTlConfig) << "Unknown protocol window theme type:" << type; + return std::nullopt; + } +} + +// DConfig windowColorScheme (0=light, 1=dark) → protocol theme_type (auto=1, light=2, dark=4) +static uint32_t dconfigToProtocolThemeType(int32_t type) +{ + switch (type) { + case 0: + return TREELAND_PERSONALIZATION_APPEARANCE_CONTEXT_V1_THEME_TYPE_LIGHT; + case 1: + return TREELAND_PERSONALIZATION_APPEARANCE_CONTEXT_V1_THEME_TYPE_DARK; + default: + qCWarning(lcTlConfig) + << "Unknown dconfig windowColorScheme:" << type << ", fallback to light."; + return TREELAND_PERSONALIZATION_APPEARANCE_CONTEXT_V1_THEME_TYPE_LIGHT; + } +} + +class PersonalizationManagerInterfaceV1Private + : public QtWaylandServer::treeland_personalization_manager_v1 +{ +public: + PersonalizationManagerInterfaceV1Private(PersonalizationManagerInterfaceV1 *_q); + ~PersonalizationManagerInterfaceV1Private() override = default; + + wl_global *global() const; + + uid_t userId = 0; + QString cacheDirectory; + QString settingFile; + QString iniMetaData; + PersonalizationManagerInterfaceV1 *q; + +protected: + void get_window_context(Resource *resource, uint32_t id, struct ::wl_resource *surface) override; + void get_cursor_context(Resource *resource, uint32_t id) override; + void get_font_context(Resource *resource, uint32_t id) override; + void get_appearance_context(Resource *resource, uint32_t id) override; +}; + +PersonalizationManagerInterfaceV1Private::PersonalizationManagerInterfaceV1Private(PersonalizationManagerInterfaceV1 *_q) + : QtWaylandServer::treeland_personalization_manager_v1() + , q(_q) +{ +} + +wl_global *PersonalizationManagerInterfaceV1Private::global() const +{ + return m_global; +} + +void PersonalizationManagerInterfaceV1Private::get_window_context(Resource *resource, + uint32_t id, + struct ::wl_resource *surface) +{ + if (!surface) { + wl_resource_post_error(resource->handle, 0, "surface resource is NULL!"); + return; + } + auto *wlrSurface = wlr_surface_from_resource(surface); + + wl_resource *windowContextResource = wl_resource_create(resource->client(), + &treeland_personalization_window_context_v1_interface, + resource->version(), + id); + if (!windowContextResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto *context = new PersonalizationWindowContextV1(windowContextResource, + wlrSurface); + s_windowContexts.append(context); + QObject::connect(context, &QObject::destroyed, [context]() { + s_windowContexts.removeOne(context); + }); + + Q_EMIT q->windowContextCreated(context); +} + +void PersonalizationManagerInterfaceV1Private::get_cursor_context(Resource *resource, uint32_t id) +{ + wl_resource *cursorContextResource = wl_resource_create(resource->client(), + &treeland_personalization_cursor_context_v1_interface, + resource->version(), + id); + if (!cursorContextResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto *context = new PersonalizationCursorContextV1(cursorContextResource); + s_cursorContexts.append(context); + QObject::connect(context, &QObject::destroyed, [context]() { + s_cursorContexts.removeOne(context); + }); + + Q_EMIT q->onCursorContextCreated(context); +} + +void PersonalizationManagerInterfaceV1Private::get_font_context(Resource *resource, uint32_t id) +{ + wl_resource *fontContextResource = wl_resource_create(resource->client(), + &treeland_personalization_font_context_v1_interface, + resource->version(), + id); + if (!fontContextResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto *context = new PersonalizationFontContextV1(fontContextResource); + + s_fontContexts.append(context); + QObject::connect(context, &QObject::destroyed, [context]() { + s_fontContexts.removeOne(context); + }); + + Q_EMIT q->onFontContextCreated(context); +} + +void PersonalizationManagerInterfaceV1Private::get_appearance_context(Resource *resource, uint32_t id) +{ + wl_resource *appearanceContextResource = wl_resource_create(resource->client(), + &treeland_personalization_appearance_context_v1_interface, + resource->version(), + id); + if (!appearanceContextResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto *context = new PersonalizationAppearanceContextV1(appearanceContextResource); + + s_appearanceContexts.append(context); + QObject::connect(context, &QObject::destroyed, [context]() { + s_appearanceContexts.removeOne(context); + }); + + Q_EMIT q->onAppearanceContextCreated(context); +} + +class PersonalizationWindowContextV1Private + : public QtWaylandServer::treeland_personalization_window_context_v1 +{ +public: + PersonalizationWindowContextV1Private(PersonalizationWindowContextV1 *_q, + wl_resource *resource, + wlr_surface *surface); + ~PersonalizationWindowContextV1Private() override = default; + + PersonalizationWindowContextV1 *q = nullptr; + wlr_surface *surface = nullptr; + + int32_t backgroundType = 0; + int32_t cornerRadius = 0; + Shadow shadow; + Border border; + PersonalizationWindowContextV1::WindowStates states; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void set_blend_mode(Resource *resource, int32_t type) override; + void set_round_corner_radius(Resource *resource, int32_t radius) override; + void set_shadow(Resource *resource, int32_t radius, int32_t offset_x, int32_t offset_y, int32_t r, int32_t g, int32_t b, int32_t a) override; + void set_border(Resource *resource, int32_t width, int32_t r, int32_t g, int32_t b, int32_t a) override; + void set_titlebar(Resource *resource, int32_t mode) override; +}; + +PersonalizationWindowContextV1Private::PersonalizationWindowContextV1Private( + PersonalizationWindowContextV1 *_q, + wl_resource *resource, + wlr_surface *_surface) + : QtWaylandServer::treeland_personalization_window_context_v1(resource) + , q(_q) + , surface(_surface) +{ +} + +void PersonalizationWindowContextV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void PersonalizationWindowContextV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void PersonalizationWindowContextV1Private::set_blend_mode([[maybe_unused]] Resource *resource, int32_t type) +{ + backgroundType = type; + Q_EMIT q->backgroundTypeChanged(); +} + +void PersonalizationWindowContextV1Private::set_round_corner_radius([[maybe_unused]] Resource *resource, int32_t radius) +{ + cornerRadius = radius; + Q_EMIT q->cornerRadiusChanged(); +} + +void PersonalizationWindowContextV1Private::set_shadow([[maybe_unused]] Resource *resource, + int32_t radius, + int32_t offset_x, + int32_t offset_y, + int32_t r, + int32_t g, + int32_t b, + int32_t a) +{ + shadow = Shadow{ radius, QPoint{ offset_x, offset_y }, QColor{ r, g, b, a } }; + Q_EMIT q->shadowChanged(); +} + +void PersonalizationWindowContextV1Private::set_border([[maybe_unused]] Resource *resource, + int32_t width, + int32_t r, + int32_t g, + int32_t b, + int32_t a) +{ + border = Border{ width, QColor{ r, g, b, a } }; + Q_EMIT q->borderChanged(); +} + +void PersonalizationWindowContextV1Private::set_titlebar([[maybe_unused]] Resource *resource, int32_t mode) +{ + states.setFlag( + PersonalizationWindowContextV1::WindowState::NoTitleBar, + mode == TREELAND_PERSONALIZATION_WINDOW_CONTEXT_V1_ENABLE_MODE_DISABLE); + Q_EMIT q->windowStateChanged(); +} + +PersonalizationWindowContextV1::PersonalizationWindowContextV1( + wl_resource *resource, + wlr_surface *surface) + : QObject(nullptr) + , d(new PersonalizationWindowContextV1Private(this, resource, surface)) +{ +} + +PersonalizationWindowContextV1::~PersonalizationWindowContextV1() = default; + +wl_resource *PersonalizationWindowContextV1::resource() const +{ + return d->resource()->handle; +} + +wlr_surface *PersonalizationWindowContextV1::surface() const +{ + return d->surface; +} + +int32_t PersonalizationWindowContextV1::backgroundType() const +{ + return d->backgroundType; +} + +int32_t PersonalizationWindowContextV1::cornerRadius() const +{ + return d->cornerRadius; +} + +Shadow PersonalizationWindowContextV1::shadow() const +{ + return d->shadow; +} + +Border PersonalizationWindowContextV1::border() const +{ + return d->border; +} + +PersonalizationWindowContextV1 *PersonalizationWindowContextV1::get(wl_resource *resource) +{ + for (auto *context : std::as_const(s_windowContexts)) { + if (context->resource() == resource) { + return context; + } + } + + return nullptr; +} + +PersonalizationWindowContextV1 *PersonalizationWindowContextV1::getWindowContext(WSurface *surface) +{ + for (auto *context : std::as_const(s_windowContexts)) { + if (context->surface() == surface->handle()) { + return context; + } + } + + return nullptr; +} + +PersonalizationWindowContextV1::WindowStates PersonalizationWindowContextV1::states() const +{ + return d->states; +} + +class PersonalizationCursorContextV1Private + : public QtWaylandServer::treeland_personalization_cursor_context_v1 +{ +public: + PersonalizationCursorContextV1Private(PersonalizationCursorContextV1 *_q, + wl_resource *resource); + ~PersonalizationCursorContextV1Private() override = default; + + PersonalizationCursorContextV1 *q = nullptr; + + QSize size; + QString theme; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void set_theme(Resource *resource, const QString &name) override; + void get_theme(Resource *resource) override; + void set_size(Resource *resource, uint32_t size) override; + void get_size(Resource *resource) override; + void commit(Resource *resource) override; +}; + +PersonalizationCursorContextV1Private::PersonalizationCursorContextV1Private( + PersonalizationCursorContextV1 *_q, wl_resource *resource) + : QtWaylandServer::treeland_personalization_cursor_context_v1(resource) + , q(_q) +{ +} + +void PersonalizationCursorContextV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void PersonalizationCursorContextV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void PersonalizationCursorContextV1Private::set_theme([[maybe_unused]] Resource *resource, const QString &name) +{ + theme = name; +} + +void PersonalizationCursorContextV1Private::get_theme([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->getTheme(); +} + +void PersonalizationCursorContextV1Private::set_size([[maybe_unused]] Resource *resource, uint32_t _size) +{ + size = QSize(_size, _size); +} + +void PersonalizationCursorContextV1Private::get_size([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->getSize(); +} + +void PersonalizationCursorContextV1Private::commit([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->commit(q); +} + +PersonalizationCursorContextV1::PersonalizationCursorContextV1(wl_resource *resource) + : QObject(nullptr) + , d(new PersonalizationCursorContextV1Private(this, resource)) +{ +} + +PersonalizationCursorContextV1::~PersonalizationCursorContextV1() = default; + +wl_resource *PersonalizationCursorContextV1::resource() const +{ + return d->resource()->handle; +} + +QSize PersonalizationCursorContextV1::size() const +{ + return d->size; +} + +QString PersonalizationCursorContextV1::theme() const +{ + return d->theme; +} + +void PersonalizationCursorContextV1::setTheme(const QString &theme) +{ + if (d->theme == theme) { + return; + } + + d->theme = theme; +} + +void PersonalizationCursorContextV1::setSize(const QSize &size) +{ + if (d->size == size) { + return; + } + + d->size = size; +} + +void PersonalizationCursorContextV1::verify(bool verified) +{ + d->send_verfity(verified); +} + +void PersonalizationCursorContextV1::sendTheme() +{ + d->send_theme(d->theme); +} + +void PersonalizationCursorContextV1::sendSize() +{ + d->send_size(d->size.width()); +} + +PersonalizationCursorContextV1 *PersonalizationCursorContextV1::get(wl_resource *resource) +{ + for (auto *context : std::as_const(s_cursorContexts)) { + if (context->resource() == resource) { + return context; + } + } + + return nullptr; +} + +class PersonalizationAppearanceContextV1Private + : public QtWaylandServer::treeland_personalization_appearance_context_v1 +{ +public: + PersonalizationAppearanceContextV1Private(PersonalizationAppearanceContextV1 *_q, + wl_resource *resource); + ~PersonalizationAppearanceContextV1Private() override = default; + + PersonalizationAppearanceContextV1 *q = nullptr; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void set_round_corner_radius(Resource *resource, int32_t radius) override; + void get_round_corner_radius(Resource *resource) override; + void set_icon_theme(Resource *resource, const QString &theme_name) override; + void get_icon_theme(Resource *resource) override; + void set_active_color(Resource *resource, const QString &color) override; + void get_active_color(Resource *resource) override; + void set_window_opacity(Resource *resource, uint32_t opacity) override; + void get_window_opacity(Resource *resource) override; + void set_window_theme_type(Resource *resource, uint32_t type) override; + void get_window_theme_type(Resource *resource) override; + void set_window_titlebar_height(Resource *resource, uint32_t height) override; + void get_window_titlebar_height(Resource *resource) override; +}; + +PersonalizationAppearanceContextV1Private::PersonalizationAppearanceContextV1Private( + PersonalizationAppearanceContextV1 *_q, + wl_resource *resource) + : QtWaylandServer::treeland_personalization_appearance_context_v1(resource) + , q(_q) +{ +} + +void PersonalizationAppearanceContextV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void PersonalizationAppearanceContextV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void PersonalizationAppearanceContextV1Private::set_round_corner_radius([[maybe_unused]] Resource *resource, int32_t radius) +{ + Q_EMIT q->roundCornerRadiusChanged(radius); +} + +void PersonalizationAppearanceContextV1Private::get_round_corner_radius([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->requestRoundCornerRadius(); +} + +void PersonalizationAppearanceContextV1Private::set_icon_theme([[maybe_unused]] Resource *resource, const QString &theme_name) +{ + Q_EMIT q->iconThemeChanged(theme_name); +} + +void PersonalizationAppearanceContextV1Private::get_icon_theme([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->requestIconTheme(); +} + +void PersonalizationAppearanceContextV1Private::set_active_color([[maybe_unused]] Resource *resource, const QString &color) +{ + Q_EMIT q->activeColorChanged(color); +} + +void PersonalizationAppearanceContextV1Private::get_active_color([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->requestActiveColor(); +} + +void PersonalizationAppearanceContextV1Private::set_window_opacity([[maybe_unused]] Resource *resource, uint32_t opacity) +{ + Q_EMIT q->windowOpacityChanged(opacity); +} + +void PersonalizationAppearanceContextV1Private::get_window_opacity([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->requestWindowOpacity(); +} + +void PersonalizationAppearanceContextV1Private::set_window_theme_type([[maybe_unused]] Resource *resource, uint32_t type) +{ + Q_EMIT q->windowThemeTypeChanged(type); +} + +void PersonalizationAppearanceContextV1Private::get_window_theme_type([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->requestWindowThemeType(); +} + +void PersonalizationAppearanceContextV1Private::set_window_titlebar_height([[maybe_unused]] Resource *resource, uint32_t height) +{ + Q_EMIT q->titlebarHeightChanged(height); +} + +void PersonalizationAppearanceContextV1Private::get_window_titlebar_height([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->requestWindowTitlebarHeight(); +} + +PersonalizationAppearanceContextV1::PersonalizationAppearanceContextV1(wl_resource *resource) + : QObject(nullptr) + , d(new PersonalizationAppearanceContextV1Private(this, resource)) +{ +} + +PersonalizationAppearanceContextV1::~PersonalizationAppearanceContextV1() = default; + +wl_resource *PersonalizationAppearanceContextV1::resource() const +{ + return d->resource()->handle; +} + +void PersonalizationAppearanceContextV1::setRoundCornerRadius(int32_t radius) +{ + Q_EMIT roundCornerRadiusChanged(radius); +} + +void PersonalizationAppearanceContextV1::sendRoundCornerRadius(int32_t radius) +{ + d->send_round_corner_radius(radius); +} + +void PersonalizationAppearanceContextV1::setIconTheme(const QString &theme) +{ + Q_EMIT iconThemeChanged(theme); +} + +void PersonalizationAppearanceContextV1::sendIconTheme(const QString &theme) +{ + d->send_icon_theme(theme); +} + +void PersonalizationAppearanceContextV1::setActiveColor(const QString &color) +{ + Q_EMIT activeColorChanged(color); +} + +void PersonalizationAppearanceContextV1::sendActiveColor(const QString &color) +{ + d->send_active_color(color); +} + +void PersonalizationAppearanceContextV1::setWindowOpacity(uint32_t opacity) +{ + Q_EMIT windowOpacityChanged(opacity); +} + +void PersonalizationAppearanceContextV1::sendWindowOpacity(uint32_t opacity) +{ + d->send_window_opacity(opacity); +} + +void PersonalizationAppearanceContextV1::setWindowThemeType(uint32_t type) +{ + Q_EMIT windowThemeTypeChanged(type); +} + +void PersonalizationAppearanceContextV1::sendWindowThemeType(uint32_t type) +{ + d->send_window_theme_type(type); +} + +void PersonalizationAppearanceContextV1::setWindowTitlebarHeight(uint32_t height) +{ + Q_EMIT titlebarHeightChanged(height); +} + +void PersonalizationAppearanceContextV1::sendWindowTitlebarHeight(uint32_t height) +{ + d->send_window_titlebar_height(height); +} + +PersonalizationAppearanceContextV1 *PersonalizationAppearanceContextV1::get(wl_resource *resource) +{ + for (auto *context : std::as_const(s_appearanceContexts)) { + if (context->resource() == resource) { + return context; + } + } + + return nullptr; +} + +class PersonalizationFontContextV1Private + : public QtWaylandServer::treeland_personalization_font_context_v1 +{ +public: + PersonalizationFontContextV1Private(PersonalizationFontContextV1 *_q, wl_resource *resource); + ~PersonalizationFontContextV1Private() override = default; + + PersonalizationFontContextV1 *q = nullptr; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void set_font(Resource *resource, const QString &font) override; + void get_font(Resource *resource) override; + void set_monospace_font(Resource *resource, const QString &font) override; + void get_monospace_font(Resource *resource) override; + void set_font_size(Resource *resource, uint32_t size) override; + void get_font_size(Resource *resource) override; +}; + +PersonalizationFontContextV1Private::PersonalizationFontContextV1Private( + PersonalizationFontContextV1 *_q, + wl_resource *resource) + : QtWaylandServer::treeland_personalization_font_context_v1(resource) + , q(_q) +{ +} + +void PersonalizationFontContextV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void PersonalizationFontContextV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void PersonalizationFontContextV1Private::set_font([[maybe_unused]] Resource *resource, const QString &font) +{ + Q_EMIT q->fontChanged(font); +} + +void PersonalizationFontContextV1Private::get_font([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->requestFont(); +} + +void PersonalizationFontContextV1Private::set_monospace_font([[maybe_unused]] Resource *resource, const QString &font) +{ + Q_EMIT q->monoFontChanged(font); +} + +void PersonalizationFontContextV1Private::get_monospace_font([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->requestMonoFont(); +} + +void PersonalizationFontContextV1Private::set_font_size([[maybe_unused]] Resource *resource, uint32_t size) +{ + Q_EMIT q->fontSizeChanged(size); +} + +void PersonalizationFontContextV1Private::get_font_size([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->requestFontSize(); +} + +PersonalizationFontContextV1::PersonalizationFontContextV1(wl_resource *resource) + : QObject(nullptr) + , d(new PersonalizationFontContextV1Private(this, resource)) +{ +} + +PersonalizationFontContextV1::~PersonalizationFontContextV1() = default; + +wl_resource *PersonalizationFontContextV1::resource() const +{ + return d->resource()->handle; +} + +void PersonalizationFontContextV1::sendFont(const QString &font) +{ + d->send_font(font); +} + +void PersonalizationFontContextV1::sendMonospaceFont(const QString &font) +{ + d->send_monospace_font(font); +} + +void PersonalizationFontContextV1::sendFontSize(uint32_t size) +{ + d->send_font_size(size); +} + +PersonalizationFontContextV1 *PersonalizationFontContextV1::get(wl_resource *resource) +{ + for (auto *context : std::as_const(s_fontContexts)) { + if (context->resource() == resource) { + return context; + } + } + + return nullptr; +} + +PersonalizationManagerInterfaceV1::PersonalizationManagerInterfaceV1(Session *session) + : QObject(session) + , WServerInterface() + , m_session(session) + , m_config(session->config()) + , d(new PersonalizationManagerInterfaceV1Private(this)) +{ + Q_INIT_RESOURCE(default_background); + + d->userId = session->uid(); +} + +PersonalizationManagerInterfaceV1::~PersonalizationManagerInterfaceV1() +{ + Q_CLEANUP_RESOURCE(default_background); +} + +void PersonalizationManagerInterfaceV1::onCursorContextCreated(PersonalizationCursorContextV1 *context) +{ + connect(context, + &PersonalizationCursorContextV1::commit, + this, + &PersonalizationManagerInterfaceV1::onCursorCommit); + connect(context, + &PersonalizationCursorContextV1::getTheme, + context, + &PersonalizationCursorContextV1::sendTheme); + connect(context, + &PersonalizationCursorContextV1::getSize, + context, + &PersonalizationCursorContextV1::sendSize); + + context->blockSignals(true); + context->setTheme(m_config->cursorThemeName()); + auto size = m_config->cursorSize(); + context->setSize(QSize(size, size)); + connect(m_config, + &TreelandUserConfig::cursorThemeNameChanged, + context, + [context, config = m_config]() { + context->setTheme(config->cursorThemeName()); + }); + connect(m_config, + &TreelandUserConfig::cursorSizeChanged, + context, + [context, config = m_config]() { + auto size = config->cursorSize(); + context->setSize(QSize(size, size)); + }); + context->blockSignals(false); +} + +void PersonalizationManagerInterfaceV1::onRadiusChanged(int32_t radius) +{ + m_config->setWindowRadius(radius); + for (auto *c : std::as_const(m_appearanceContexts)) { + c->sendRoundCornerRadius(radius); + } +} + +void PersonalizationManagerInterfaceV1::onIconThemeChanged(const QString &theme) +{ + m_config->setIconThemeName(theme); + for (auto *c : std::as_const(m_appearanceContexts)) { + c->sendIconTheme(theme); + } +} + +void PersonalizationManagerInterfaceV1::onActiveColorChanged(const QString &color) +{ + m_config->setActiveColor(color); + for (auto *c : std::as_const(m_appearanceContexts)) { + c->sendActiveColor(color); + } +} + +void PersonalizationManagerInterfaceV1::onOpacityChanged(uint32_t opacity) +{ + m_config->setWindowOpacity(opacity); + for (auto *c : std::as_const(m_appearanceContexts)) { + c->sendWindowOpacity(opacity); + } +} + +void PersonalizationManagerInterfaceV1::onThemeTypeChanged(uint32_t type) +{ + const auto dconfigType = protocolThemeTypeToDConfig(type); + if (dconfigType.has_value()) { + m_config->setWindowColorScheme(*dconfigType); + if (m_session && m_session->isActive()) + WaylandServer::syncPaletteTypeWithWindowColorScheme(*dconfigType); + } + for (auto *c : std::as_const(m_appearanceContexts)) { + c->sendWindowThemeType(type); + } +} + +void PersonalizationManagerInterfaceV1::onTitlebarHeightChanged(uint32_t height) +{ + m_config->setWindowTitlebarHeight(height); + for (auto *c : std::as_const(m_appearanceContexts)) { + c->sendWindowTitlebarHeight(height); + } +} + +void PersonalizationManagerInterfaceV1::onAppearanceContextCreated(PersonalizationAppearanceContextV1 *context) +{ + m_appearanceContexts.append(context); + connect(context, &QObject::destroyed, this, [this, context] { + m_appearanceContexts.removeAll(context); + }); + connect(context, &PersonalizationAppearanceContextV1::roundCornerRadiusChanged, + this, &PersonalizationManagerInterfaceV1::onRadiusChanged); + connect(context, &PersonalizationAppearanceContextV1::iconThemeChanged, + this, &PersonalizationManagerInterfaceV1::onIconThemeChanged); + connect(context, &PersonalizationAppearanceContextV1::activeColorChanged, + this, &PersonalizationManagerInterfaceV1::onActiveColorChanged); + connect(context, &PersonalizationAppearanceContextV1::windowOpacityChanged, + this, &PersonalizationManagerInterfaceV1::onOpacityChanged); + connect(context, &PersonalizationAppearanceContextV1::windowThemeTypeChanged, + this, &PersonalizationManagerInterfaceV1::onThemeTypeChanged); + connect(context, &PersonalizationAppearanceContextV1::titlebarHeightChanged, + this, &PersonalizationManagerInterfaceV1::onTitlebarHeightChanged); + + connect(context, &PersonalizationAppearanceContextV1::requestRoundCornerRadius, context, [context, config = m_config] { + context->sendRoundCornerRadius(config->windowRadius()); + }); + + connect(context, &PersonalizationAppearanceContextV1::requestIconTheme, context, [context, config = m_config] { + context->sendIconTheme(config->iconThemeName()); + }); + + connect(context, &PersonalizationAppearanceContextV1::requestActiveColor, context, [context, config = m_config] { + context->sendActiveColor(config->activeColor()); + }); + + connect(context, &PersonalizationAppearanceContextV1::requestWindowOpacity, context, [context, config = m_config] { + context->sendWindowOpacity(config->windowOpacity()); + }); + + connect(context, &PersonalizationAppearanceContextV1::requestWindowThemeType, context, [context, config = m_config] { + const auto protocolType = dconfigToProtocolThemeType( + config->windowColorScheme()); + context->sendWindowThemeType(protocolType); + }); + + connect(context, &PersonalizationAppearanceContextV1::requestWindowTitlebarHeight, context, [context, config = m_config] { + context->sendWindowTitlebarHeight(config->windowTitlebarHeight()); + }); + + context->sendRoundCornerRadius(m_config->windowRadius()); + context->sendIconTheme(m_config->iconThemeName()); + context->sendActiveColor(m_config->activeColor()); + context->sendWindowOpacity(m_config->windowOpacity()); + context->sendWindowThemeType(dconfigToProtocolThemeType( + m_config->windowColorScheme())); + context->sendWindowTitlebarHeight(m_config->windowTitlebarHeight()); +} + +void PersonalizationManagerInterfaceV1::onFontContextCreated(PersonalizationFontContextV1 *context) +{ + connect(m_config, &TreelandUserConfig::fontChanged, context, [context, config = m_config] { + context->sendFont(config->font()); + }); + connect(m_config, &TreelandUserConfig::monoFontChanged, context, [context, config = m_config] { + context->sendMonospaceFont(config->monoFont()); + }); + connect(m_config, &TreelandUserConfig::fontSizeChanged, context, [context, config = m_config] { + context->sendFontSize(config->fontSize()); + }); + + connect(context, &PersonalizationFontContextV1::requestFont, context, [context, config = m_config] { + context->sendFont(config->font()); + }); + connect(context, &PersonalizationFontContextV1::requestMonoFont, context, [context, config = m_config] { + context->sendMonospaceFont(config->monoFont()); + }); + connect(context, &PersonalizationFontContextV1::requestFontSize, context, [context, config = m_config] { + context->sendFontSize(config->fontSize()); + }); + + connect(context, &PersonalizationFontContextV1::fontChanged, m_config, &TreelandUserConfig::setFont); + connect(context, &PersonalizationFontContextV1::monoFontChanged, m_config, &TreelandUserConfig::setMonoFont); + connect(context, &PersonalizationFontContextV1::fontSizeChanged, m_config, &TreelandUserConfig::setFontSize); + + context->blockSignals(true); + + context->sendFont(m_config->font()); + context->sendMonospaceFont(m_config->monoFont()); + context->sendFontSize(m_config->fontSize()); + + context->blockSignals(false); +} + +void PersonalizationManagerInterfaceV1::onCursorCommit(PersonalizationCursorContextV1 *context) +{ + if (!context->size().isValid() || context->theme().isEmpty()) { + context->verify(false); + } + + setCursorTheme(context->theme()); + setCursorSize(context->size()); + + context->verify(true); +} + +uid_t PersonalizationManagerInterfaceV1::userId() +{ + return d->userId; +} + +QString PersonalizationManagerInterfaceV1::cursorTheme() +{ + return m_config->cursorThemeName(); +} + +void PersonalizationManagerInterfaceV1::setCursorTheme(const QString &name) +{ + m_config->setCursorThemeName(name); + + Q_EMIT cursorThemeChanged(name); +} + +QSize PersonalizationManagerInterfaceV1::cursorSize() +{ + int size = m_config->cursorSize(); + + return QSize(size, size); +} + +void PersonalizationManagerInterfaceV1::setCursorSize(const QSize &size) +{ + m_config->setCursorSize(size.width()); + + Q_EMIT cursorSizeChanged(size); +} + +int32_t PersonalizationManagerInterfaceV1::windowRadius() const +{ + return m_config->windowRadius(); +} + +QString PersonalizationManagerInterfaceV1::iconTheme() const +{ + return m_config->iconThemeName(); +} + +Personalization::Personalization(WToplevelSurface *target, + PersonalizationManagerInterfaceV1 *manager, + SurfaceWrapper *parent) + : QObject(parent) + , m_target(target) + , m_manager(manager) +{ + connect(target, &WToplevelSurface::beforeDestroy, this, [this] { + disconnect(m_manager, &PersonalizationManagerInterfaceV1::windowContextCreated, this, nullptr); + }); + + auto update = [this](PersonalizationWindowContextV1 *context) { + assert(context); + + if (context->surface() != m_target->surface()->handle()) { + return; + } + + connect(context, + &PersonalizationWindowContextV1::backgroundTypeChanged, + this, + [this, context] { + setBackgroundType(static_cast(context->backgroundType())); + }); + connect(context, + &PersonalizationWindowContextV1::cornerRadiusChanged, + this, + [this, context] { + setCornerRadius(context->cornerRadius()); + }); + + connect(context, &PersonalizationWindowContextV1::shadowChanged, this, [this, context] { + setShadow(context->shadow()); + }); + + connect(context, &PersonalizationWindowContextV1::borderChanged, this, [this, context] { + setBorder(context->border()); + }); + + connect(context, + &PersonalizationWindowContextV1::windowStateChanged, + this, + [this, context] { + setWindowStates(context->states()); + }); + + setBackgroundType(static_cast(context->backgroundType())); + setCornerRadius(context->cornerRadius()); + setShadow(context->shadow()); + setBorder(context->border()); + setWindowStates(context->states()); + }; + + connect(m_manager, &PersonalizationManagerInterfaceV1::windowContextCreated, this, update); + + if (auto *context = PersonalizationWindowContextV1::getWindowContext(m_target->surface())) { + update(context); + } +} + +void Personalization::resetProperties() +{ + setBackgroundType(Personalization::BackgroundType::Normal); + setCornerRadius(0); + setShadow({}); + setBorder({}); + setWindowStates({}); +} + +SurfaceWrapper *Personalization::surfaceWrapper() const +{ + return qobject_cast(parent()); +} + +Personalization::BackgroundType Personalization::backgroundType() const +{ + return m_backgroundType; +} + +bool Personalization::noTitlebar() const +{ + if (qobject_cast(m_target)) { + return true; + } + + return m_states.testFlag(PersonalizationWindowContextV1::NoTitleBar); +} + +void Personalization::setBackgroundType(BackgroundType type) +{ + if (m_backgroundType == type) + return; + m_backgroundType = type; + Q_EMIT backgroundTypeChanged(); +} + +void Personalization::setCornerRadius(int32_t radius) +{ + if (m_cornerRadius == radius) + return; + m_cornerRadius = radius; + Q_EMIT cornerRadiusChanged(); +} + +void Personalization::setShadow(const Shadow &shadow) +{ + if (m_shadow == shadow) + return; + m_shadow = shadow; + Q_EMIT shadowChanged(); +} + +void Personalization::setBorder(const Border &border) +{ + if (m_border == border) + return; + m_border = border; + Q_EMIT borderChanged(); +} + +void Personalization::setWindowStates(PersonalizationWindowContextV1::WindowStates states) +{ + if (m_states == states) + return; + m_states = states; + Q_EMIT windowStateChanged(); +} + +void PersonalizationManagerInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void PersonalizationManagerInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *PersonalizationManagerInterfaceV1::global() const +{ + return d->global(); +} + +QByteArrayView PersonalizationManagerInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} diff --git a/src/modules/personalization/personalizationmanagerinterfacev1.h b/src/modules/personalization/personalizationmanagerinterfacev1.h new file mode 100644 index 0000000000..6b4db512ee --- /dev/null +++ b/src/modules/personalization/personalizationmanagerinterfacev1.h @@ -0,0 +1,313 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +// DEPRECATED: This module is frozen. Use treeland-appearance-unstable-v1 and +// treeland-appearance-manager-unstable-v1 (src/modules/appearance/) instead. +// No new features will be added to this protocol. + +#include +#include + +#include +#include +#include +#include + +#include "common/windowdecorations.h" + +class Session; +class TreelandUserConfig; +class SurfaceWrapper; +class PersonalizationManagerInterfaceV1; + +WAYLIB_SERVER_USE_NAMESPACE + +class PersonalizationManagerInterfaceV1Private; +class PersonalizationWindowContextV1Private; +class PersonalizationWindowContextV1 : public QObject +{ + Q_OBJECT +public: + enum WindowState + { + NoTitleBar = 1, + }; + Q_ENUM(WindowState) + Q_DECLARE_FLAGS(WindowStates, WindowState) + + ~PersonalizationWindowContextV1() override; + + wl_resource *resource() const; + wlr_surface *surface() const; + int32_t backgroundType() const; + int32_t cornerRadius() const; + Shadow shadow() const; + Border border() const; + WindowStates states() const; + + static PersonalizationWindowContextV1 *get(wl_resource *resource); + static PersonalizationWindowContextV1 *getWindowContext(WSurface *surface); +Q_SIGNALS: + void backgroundTypeChanged(); + void cornerRadiusChanged(); + void shadowChanged(); + void borderChanged(); + void windowStateChanged(); + +private: + explicit PersonalizationWindowContextV1(wl_resource *resource, + wlr_surface *surface); + +private: + std::unique_ptr d; + + friend class PersonalizationManagerInterfaceV1Private; +}; + +Q_DECLARE_OPERATORS_FOR_FLAGS(PersonalizationWindowContextV1::WindowStates) + +class PersonalizationCursorContextV1Private; +class PersonalizationCursorContextV1 : public QObject +{ + Q_OBJECT +public: + ~PersonalizationCursorContextV1() override; + + wl_resource *resource() const; + QSize size() const; + QString theme() const; + + void setTheme(const QString &theme); + void setSize(const QSize &size); + void verify(bool verified); + + void sendTheme(); + void sendSize(); + + static PersonalizationCursorContextV1 *get(wl_resource *resource); + +Q_SIGNALS: + void commit(PersonalizationCursorContextV1 *context); + void getSize(); + void getTheme(); + +private: + explicit PersonalizationCursorContextV1(wl_resource *resource); + +private: + std::unique_ptr d; + + friend class PersonalizationManagerInterfaceV1Private; +}; + +class PersonalizationAppearanceContextV1Private; +class PersonalizationAppearanceContextV1 : public QObject +{ + Q_OBJECT +public: + ~PersonalizationAppearanceContextV1() override; + + wl_resource *resource() const; + void setRoundCornerRadius(int32_t radius); + void sendRoundCornerRadius(int32_t radius); + + void setIconTheme(const QString &theme); + void sendIconTheme(const QString &theme); + + void setActiveColor(const QString &color); + void sendActiveColor(const QString &color); + + void setWindowOpacity(uint32_t opacity); + void sendWindowOpacity(uint32_t opacity); + + void setWindowThemeType(uint32_t type); + void sendWindowThemeType(uint32_t type); + + void setWindowTitlebarHeight(uint32_t height); + void sendWindowTitlebarHeight(uint32_t height); + + static PersonalizationAppearanceContextV1 *get(wl_resource *resource); + +Q_SIGNALS: + void roundCornerRadiusChanged(int32_t radius); + void iconThemeChanged(const QString &iconTheme); + void activeColorChanged(const QString &color); + void windowOpacityChanged(uint32_t opacity); + void windowThemeTypeChanged(uint32_t type); + void titlebarHeightChanged(uint32_t height); + + void requestRoundCornerRadius(); + void requestIconTheme(); + void requestActiveColor(); + void requestWindowOpacity(); + void requestWindowThemeType(); + void requestWindowTitlebarHeight(); + +private: + explicit PersonalizationAppearanceContextV1(wl_resource *resource); + +private: + std::unique_ptr d; + + friend class PersonalizationManagerInterfaceV1Private; +}; + +class PersonalizationFontContextV1Private; +class PersonalizationFontContextV1 : public QObject +{ + Q_OBJECT +public: + ~PersonalizationFontContextV1() override; + + wl_resource *resource() const; + void sendFont(const QString &font); + void sendMonospaceFont(const QString &font); + void sendFontSize(uint32_t size); + + static PersonalizationFontContextV1 *get(wl_resource *resource); + +Q_SIGNALS: + void fontChanged(const QString &font); + void monoFontChanged(const QString &font); + void fontSizeChanged(uint32_t size); + void requestFont(); + void requestMonoFont(); + void requestFontSize(); + +private: + explicit PersonalizationFontContextV1(wl_resource *resource); + +private: + std::unique_ptr d; + + friend class PersonalizationManagerInterfaceV1Private; +}; + +class Personalization : public QObject +{ + Q_OBJECT + QML_ANONYMOUS + Q_PROPERTY(BackgroundType backgroundType READ backgroundType NOTIFY backgroundTypeChanged) + Q_PROPERTY(int32_t cornerRadius READ cornerRadius NOTIFY cornerRadiusChanged) + Q_PROPERTY(bool noTitlebar READ noTitlebar NOTIFY windowStateChanged) + +public: + enum BackgroundType + { + Normal, + Wallpaper, + Blur + }; + Q_ENUM(BackgroundType) + + Personalization(WToplevelSurface *target, + PersonalizationManagerInterfaceV1 *manager, + SurfaceWrapper *parent); + + SurfaceWrapper *surfaceWrapper() const; + Personalization::BackgroundType backgroundType() const; + + int32_t cornerRadius() const + { + return m_cornerRadius; + } + + Shadow shadow() const + { + return m_shadow; + } + + Border border() const + { + return m_border; + } + + bool noTitlebar() const; + +Q_SIGNALS: + void backgroundTypeChanged(); + void cornerRadiusChanged(); + void shadowChanged(); + void borderChanged(); + void windowStateChanged(); + +private Q_SLOTS: + void resetProperties(); + +private: + void setBackgroundType(BackgroundType type); + void setCornerRadius(int32_t radius); + void setShadow(const Shadow &shadow); + void setBorder(const Border &border); + void setWindowStates(PersonalizationWindowContextV1::WindowStates states); + +private: + QPointer m_target; + PersonalizationManagerInterfaceV1 *m_manager = nullptr; + BackgroundType m_backgroundType = BackgroundType::Normal; + int32_t m_cornerRadius = 0; + Shadow m_shadow {}; + Border m_border {}; + PersonalizationWindowContextV1::WindowStates m_states {}; +}; + +class PersonalizationManagerInterfaceV1 : public QObject, public WServerInterface +{ + Q_OBJECT + + Q_PROPERTY(uid_t userId READ userId CONSTANT FINAL) + Q_PROPERTY(QString cursorTheme READ cursorTheme WRITE setCursorTheme NOTIFY cursorThemeChanged FINAL) + Q_PROPERTY(QSize cursorSize READ cursorSize WRITE setCursorSize NOTIFY cursorSizeChanged FINAL) + +public: + explicit PersonalizationManagerInterfaceV1(Session *session); + ~PersonalizationManagerInterfaceV1() override; + + void onCursorContextCreated(PersonalizationCursorContextV1 *context); + void onAppearanceContextCreated(PersonalizationAppearanceContextV1 *context); + void onFontContextCreated(PersonalizationFontContextV1 *context); + + void onWindowPersonalizationChanged(); + + void onCursorCommit(PersonalizationCursorContextV1 *context); + + uid_t userId(); + + QString cursorTheme(); + void setCursorTheme(const QString &name); + + QSize cursorSize(); + void setCursorSize(const QSize &size); + + int32_t windowRadius() const; + + QString iconTheme() const; + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; +Q_SIGNALS: + void lockscreenChanged(); + void cursorThemeChanged(const QString &name); + void cursorSizeChanged(const QSize &size); + void windowContextCreated(PersonalizationWindowContextV1 *context); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + void onRadiusChanged(int32_t radius); + void onIconThemeChanged(const QString &theme); + void onActiveColorChanged(const QString &color); + void onOpacityChanged(uint32_t opacity); + void onThemeTypeChanged(uint32_t type); + void onTitlebarHeightChanged(uint32_t height); + QPointer m_session; + TreelandUserConfig *const m_config; + QList m_appearanceContexts; + std::unique_ptr d; +}; diff --git a/src/modules/prelaunch-splash/CMakeLists.txt b/src/modules/prelaunch-splash/CMakeLists.txt new file mode 100644 index 0000000000..f37e9f2dc3 --- /dev/null +++ b/src/modules/prelaunch-splash/CMakeLists.txt @@ -0,0 +1,18 @@ +find_package(TreelandProtocols 0.5.5 REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-prelaunch-splash-unstable-v2.xml + BASENAME treeland-prelaunch-splash-unstable-v2 +) + +impl_treeland( + NAME + module_prelaunch_splash + SOURCE + prelaunchsplash.h + prelaunchsplash.cpp + INCLUDE + $ + LINK + Qt6::Core +) diff --git a/src/modules/prelaunch-splash/prelaunchsplash.cpp b/src/modules/prelaunch-splash/prelaunchsplash.cpp new file mode 100644 index 0000000000..609ceb206d --- /dev/null +++ b/src/modules/prelaunch-splash/prelaunchsplash.cpp @@ -0,0 +1,144 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "prelaunchsplash.h" + +#include "common/treelandlogging.h" +#include "qwayland-server-treeland-prelaunch-splash-unstable-v2.h" + +#include + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class SplashResource : public QtWaylandServer::treeland_prelaunch_splash_v2 +{ +public: + SplashResource(PrelaunchSplash *owner, + struct ::wl_resource *resource, + const QString &appId, + const QString &instanceId) + : QtWaylandServer::treeland_prelaunch_splash_v2(resource) + , m_owner(owner) + , m_appId(appId) + , m_instanceId(instanceId) + { + } + + QString appId() const + { + return m_appId; + } + + QString instanceId() const + { + return m_instanceId; + } + +protected: + void destroy(Resource *resource) override + { + qCInfo(lcTlPrelaunchSplash) << "Client destroy splash appId=" << m_appId + << " instanceId=" << m_instanceId; + wl_resource_destroy(resource->handle); + } + + void destroy_resource(Resource *) override + { + // Covers both explicit destroy() and client crash/disconnect + Q_EMIT m_owner->splashCloseRequested(m_appId, m_instanceId); + delete this; + } + +private: + PrelaunchSplash *m_owner; + QString m_appId; + QString m_instanceId; +}; + +class PrelaunchSplashPrivate : public QtWaylandServer::treeland_prelaunch_splash_manager_v2 +{ +public: + explicit PrelaunchSplashPrivate(PrelaunchSplash *_q) + : QtWaylandServer::treeland_prelaunch_splash_manager_v2() + , q(_q) + { + } + + wl_global *globalHandle() const + { + return m_global; + } + +protected: + void destroy_global() override + { + qCDebug(lcTlPrelaunchSplash) << "PrelaunchSplash v2 global destroyed"; + } + + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void create_splash(Resource *resource, + uint32_t id, + const QString &app_id, + const QString &instance_id, + const QString &sandboxEngineName, + struct ::wl_resource *icon_buffer) override + { + qCInfo(lcTlPrelaunchSplash) << "create_splash request sandbox=" << sandboxEngineName + << " app_id=" << app_id << " instance_id=" << instance_id; + + auto *splashResource = wl_resource_create(resource->client(), + &treeland_prelaunch_splash_v2_interface, + wl_resource_get_version(resource->handle), + id); + if (!splashResource) { + wl_resource_post_no_memory(resource->handle); + return; + } + + // SplashResource self-destructs via destroy_resource callback + new SplashResource(q, splashResource, app_id, instance_id); + + auto qb = icon_buffer ? wlr_buffer_try_from_resource(icon_buffer) : nullptr; + Q_EMIT q->splashRequested(app_id, instance_id, qb); + } + +private: + PrelaunchSplash *q; +}; + +PrelaunchSplash::PrelaunchSplash(QObject *parent) + : QObject(parent) + , d(new PrelaunchSplashPrivate(this)) +{ +} + +PrelaunchSplash::~PrelaunchSplash() = default; + +void PrelaunchSplash::create(WAYLIB_SERVER_NAMESPACE::WServer *server) +{ + d->init(server->handle(), InterfaceVersion); + qCDebug(lcTlPrelaunchSplash) << "PrelaunchSplash v2 global created"; +} + +void PrelaunchSplash::destroy([[maybe_unused]] WAYLIB_SERVER_NAMESPACE::WServer *server) +{ + d->globalRemove(); + qCDebug(lcTlPrelaunchSplash) << "PrelaunchSplash v2 global removal scheduled"; +} + +wl_global *PrelaunchSplash::global() const +{ + return d->globalHandle(); +} + +QByteArrayView PrelaunchSplash::interfaceName() const +{ + return QtWaylandServer::treeland_prelaunch_splash_manager_v2::interfaceName(); +} diff --git a/src/modules/prelaunch-splash/prelaunchsplash.h b/src/modules/prelaunch-splash/prelaunchsplash.h new file mode 100644 index 0000000000..a045814a34 --- /dev/null +++ b/src/modules/prelaunch-splash/prelaunchsplash.h @@ -0,0 +1,41 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include + +#include + +class PrelaunchSplashPrivate; + +class PrelaunchSplash + : public QObject + , public WAYLIB_SERVER_NAMESPACE::WServerInterface +{ + Q_OBJECT +public: + explicit PrelaunchSplash(QObject *parent = nullptr); + ~PrelaunchSplash() override; + static constexpr int InterfaceVersion = 1; + + QByteArrayView interfaceName() const override; +Q_SIGNALS: + void splashRequested(const QString &appId, + const QString &instanceId, + wlr_buffer *iconBuffer); + void splashCloseRequested(const QString &appId, const QString &instanceId); + +protected: // WServerInterface + void create(WAYLIB_SERVER_NAMESPACE::WServer *server) override; + void destroy(WAYLIB_SERVER_NAMESPACE::WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; + +Q_DECLARE_OPAQUE_POINTER(wlr_buffer *) diff --git a/src/modules/region-watch/CMakeLists.txt b/src/modules/region-watch/CMakeLists.txt new file mode 100644 index 0000000000..eb601e7642 --- /dev/null +++ b/src/modules/region-watch/CMakeLists.txt @@ -0,0 +1,20 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-region-watch-unstable-v1.xml + BASENAME treeland-region-watch-unstable-v1 +) + +impl_treeland( + NAME + module_region_watch + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/region-watch/regionwatchmanagerinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/region-watch/regionwatchmanagerinterfacev1.cpp + LINK + Wlroots::wlroots + Waylib::WaylibServer + Qt6::Core + Qt6::Gui + Qt6::Quick +) diff --git a/src/modules/region-watch/regionwatchmanagerinterfacev1.cpp b/src/modules/region-watch/regionwatchmanagerinterfacev1.cpp new file mode 100644 index 0000000000..b9ca75133e --- /dev/null +++ b/src/modules/region-watch/regionwatchmanagerinterfacev1.cpp @@ -0,0 +1,369 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "regionwatchmanagerinterfacev1.h" +#include "qwayland-server-treeland-region-watch-unstable-v1.h" +#include "surface/surfacewrapper.h" + +#include + +#include + +#include +#include + +// Errors of treeland_region_watch_v1, mirroring the protocol XML. +enum RegionWatchError { + InvalidAnchor = 0, + InvalidSize = 1, +}; + +class RegionWatchV1Private : public QtWaylandServer::treeland_region_watch_v1 +{ +public: + explicit RegionWatchV1Private(RegionWatchV1 *_q, wl_resource *resource) + : QtWaylandServer::treeland_region_watch_v1(resource) + , q(_q) + { + } + + RegionWatchV1 *q = nullptr; + + void evaluate(const QList &windowRects); + void onOutputDestroyed(); + + // Monitored region in global layout coordinates (output position + + // strip); empty when the watcher is + // inert (no successful set_region yet, or the associated output was + // removed). + QRect region; + QMetaObject::Connection outputDestroyConnection; + // Overlap state tracking. stateSent is cleared by set_region (the + // protocol requires sending the current state after each set_region) + // and on output removal; afterwards events are only sent on changes. + bool stateSent = false; + bool lastOverlapped = false; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void set_region(Resource *resource, + int32_t width, + int32_t height, + uint32_t anchor, + struct ::wl_resource *output) override; +}; + +void RegionWatchV1Private::evaluate(const QList &windowRects) +{ + if (region.isEmpty()) + return; + + bool overlapped = false; + for (const QRect &rect : windowRects) { + if (rect.intersects(region)) { + overlapped = true; + break; + } + } + + if (stateSent && overlapped == lastOverlapped) + return; + + stateSent = true; + lastOverlapped = overlapped; + + if (overlapped) + send_enter(); + else + send_leave(); +} + +void RegionWatchV1Private::onOutputDestroyed() +{ + // The associated output is gone: the watcher becomes inert and must + // not send enter/leave/output_removed until the next set_region. + region = QRect(); + stateSent = false; + lastOverlapped = false; + QObject::disconnect(outputDestroyConnection); + outputDestroyConnection = QMetaObject::Connection(); + send_output_removed(); +} + +void RegionWatchV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + // The list entry is removed by the QObject::destroyed lambda registered + // in get_region_watch. + delete q; +} + +void RegionWatchV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void RegionWatchV1Private::set_region(Resource *resource, + int32_t width, + int32_t height, + uint32_t anchor, + wl_resource *outputResource) +{ + if (width <= 0 || height <= 0) { + wl_resource_post_error(resource->handle, + InvalidSize, + "invalid treeland_region_watch_v1::set_region size: %dx%d", + width, + height); + return; + } + + struct wlr_output *output = wlr_output_from_resource(outputResource); + auto *wOutput = output ? WOutput::fromHandle(output) : nullptr; + if (!wOutput) { + wl_resource_post_error(resource->handle, + InvalidAnchor, + "wlr_output_from_resource failed in treeland_region_watch_v1::set_region"); + return; + } + + const QSizeF wSize = wOutput->size() / wOutput->scale(); + switch (anchor) { + case RegionWatchV1::Anchor::Top: + region = QRect(0, 0, wSize.width(), height); + break; + case RegionWatchV1::Anchor::Bottom: + region = QRect(0, wSize.height() - height, wSize.width(), height); + break; + case RegionWatchV1::Anchor::Left: + region = QRect(0, 0, width, wSize.height()); + break; + case RegionWatchV1::Anchor::Right: + region = QRect(wSize.width() - width, 0, width, wSize.height()); + break; + default: + wl_resource_post_error(resource->handle, + InvalidAnchor, + "invalid treeland_region_watch_v1::set_region anchor: %u", + anchor); + return; + } + + // Window rects are tracked in global layout coordinates (SurfaceWrapper + // positions), so translate the output-local strip by the output's + // position in the layout. + region.translate(wOutput->position()); + + if (outputDestroyConnection) { + QObject::disconnect(outputDestroyConnection); + outputDestroyConnection = QMetaObject::Connection(); + } + outputDestroyConnection = + QObject::connect(wOutput, &WOutput::beforeDestroy, q, &RegionWatchV1::onOutputDestroyed); + + // The protocol requires evaluating the overlap state right after each + // set_region and sending the matching enter/leave event. + stateSent = false; + if (auto *manager = q->manager()) + manager->recheck(); +} + +class TreelandRegionWatchManagerInterfaceV1Private + : public QtWaylandServer::treeland_region_watch_manager_v1 +{ +public: + explicit TreelandRegionWatchManagerInterfaceV1Private(TreelandRegionWatchManagerInterfaceV1 *_q) + : q(_q) + { + } + + TreelandRegionWatchManagerInterfaceV1 *q = nullptr; + + wl_global *global() const + { + return m_global; + } + + void checkConflict(const QList &windowRects); + void addSurface(SurfaceWrapper *wrapper); + void removeSurface(SurfaceWrapper *wrapper); + QList windowRects() const; + void scheduleRecheck(); + + QTimer recheckTimer; + QList surfaces; + QList regionWatches; + +protected: + void destroy(Resource *resource) override; + void get_region_watch(Resource *resource, uint32_t id) override; +}; + +void TreelandRegionWatchManagerInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void TreelandRegionWatchManagerInterfaceV1Private::get_region_watch(Resource *resource, + uint32_t id) +{ + wl_resource *watchResource = wl_resource_create(resource->client(), + &treeland_region_watch_v1_interface, + resource->version(), + id); + if (!watchResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto watch = new RegionWatchV1(watchResource); + watch->m_manager = q; + regionWatches.append(watch); + + QObject::connect(watch, &QObject::destroyed, [this, watch]() { + regionWatches.removeOne(watch); + }); + + Q_EMIT q->regionWatchCreated(watch); +} + +void TreelandRegionWatchManagerInterfaceV1Private::checkConflict(const QList &windowRects) +{ + for (auto *watch : std::as_const(regionWatches)) { + watch->d->evaluate(windowRects); + } +} + +void TreelandRegionWatchManagerInterfaceV1Private::addSurface(SurfaceWrapper *wrapper) +{ + if (!wrapper || surfaces.contains(wrapper)) + return; + + // The protocol reports overlap with xdg-shell toplevels and the + // pre-launch splash screen; popups and other transient surfaces must + // not trigger enter/leave. + const bool trackedType = wrapper->type() == SurfaceWrapper::Type::XdgToplevel + || wrapper->type() == SurfaceWrapper::Type::XWayland + || wrapper->type() == SurfaceWrapper::Type::SplashScreen; + if (!trackedType) + return; + + surfaces.append(wrapper); + QObject::connect(wrapper, &QQuickItem::xChanged, q, [this] { scheduleRecheck(); }); + QObject::connect(wrapper, &QQuickItem::yChanged, q, [this] { scheduleRecheck(); }); + QObject::connect(wrapper, &QQuickItem::widthChanged, q, [this] { scheduleRecheck(); }); + QObject::connect(wrapper, &QQuickItem::heightChanged, q, [this] { scheduleRecheck(); }); + QObject::connect(wrapper, &QQuickItem::visibleChanged, q, [this] { scheduleRecheck(); }); + QObject::connect(wrapper, &SurfaceWrapper::aboutToBeInvalidated, q, [this, wrapper] { + surfaces.removeOne(wrapper); + scheduleRecheck(); + }); + scheduleRecheck(); +} + +void TreelandRegionWatchManagerInterfaceV1Private::removeSurface(SurfaceWrapper *wrapper) +{ + if (surfaces.removeOne(wrapper)) + scheduleRecheck(); +} + +QList TreelandRegionWatchManagerInterfaceV1Private::windowRects() const +{ + QList rects; + rects.reserve(surfaces.size()); + for (const auto wrapper : std::as_const(surfaces)) { + if (wrapper->isVisible()) { + rects.append(QRectF{ wrapper->x(), wrapper->y(), + wrapper->width(), wrapper->height() }.toRect()); + } + } + return rects; +} + +void TreelandRegionWatchManagerInterfaceV1Private::scheduleRecheck() +{ + // Recheck once per burst of geometry changes instead of on every + // intermediate position, matching the overlap-check debounce. + if (!recheckTimer.isActive()) + recheckTimer.start(); +} + +TreelandRegionWatchManagerInterfaceV1::TreelandRegionWatchManagerInterfaceV1(QObject *parent) + : QObject(parent) + , d(new TreelandRegionWatchManagerInterfaceV1Private(this)) +{ + d->recheckTimer.setSingleShot(true); + d->recheckTimer.setInterval(300); + connect(&d->recheckTimer, &QTimer::timeout, this, [this] { + d->checkConflict(d->windowRects()); + }); +} + +TreelandRegionWatchManagerInterfaceV1::~TreelandRegionWatchManagerInterfaceV1() = default; + +void TreelandRegionWatchManagerInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void TreelandRegionWatchManagerInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *TreelandRegionWatchManagerInterfaceV1::global() const +{ + return d->global(); +} + +QByteArrayView TreelandRegionWatchManagerInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} + +void TreelandRegionWatchManagerInterfaceV1::checkOverlapConflict(const QList &windowRects) +{ + d->checkConflict(windowRects); +} + +void TreelandRegionWatchManagerInterfaceV1::addSurface(SurfaceWrapper *wrapper) +{ + d->addSurface(wrapper); +} + +void TreelandRegionWatchManagerInterfaceV1::removeSurface(SurfaceWrapper *wrapper) +{ + d->removeSurface(wrapper); +} + +void TreelandRegionWatchManagerInterfaceV1::recheck() +{ + d->checkConflict(d->windowRects()); +} + +void TreelandRegionWatchManagerInterfaceV1::scheduleRecheck() +{ + d->scheduleRecheck(); +} + +RegionWatchV1::RegionWatchV1(wl_resource *resource) + : d(new RegionWatchV1Private(this, resource)) +{ +} + +RegionWatchV1::~RegionWatchV1() = default; + +void RegionWatchV1::onOutputDestroyed() +{ + d->onOutputDestroyed(); +} + +TreelandRegionWatchManagerInterfaceV1 *RegionWatchV1::manager() const +{ + return m_manager; +} + +QRect RegionWatchV1::region() const +{ + return d->region; +} diff --git a/src/modules/region-watch/regionwatchmanagerinterfacev1.h b/src/modules/region-watch/regionwatchmanagerinterfacev1.h new file mode 100644 index 0000000000..82cd67c714 --- /dev/null +++ b/src/modules/region-watch/regionwatchmanagerinterfacev1.h @@ -0,0 +1,89 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class RegionWatchV1Private; +class RegionWatchV1; +class TreelandRegionWatchManagerInterfaceV1Private; +class SurfaceWrapper; + +class TreelandRegionWatchManagerInterfaceV1 : public QObject, public WServerInterface +{ + Q_OBJECT +public: + explicit TreelandRegionWatchManagerInterfaceV1(QObject *parent = nullptr); + ~TreelandRegionWatchManagerInterfaceV1() override; + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; + + // Recomputes the overlap state of every watcher against the given + // per-window rect list (or, via recheck(), the internally tracked list). + void checkOverlapConflict(const QList &windowRects); + + // Track a non-layer surface whose geometry/visibility changes must + // trigger a debounced overlap re-evaluation. + void addSurface(SurfaceWrapper *wrapper); + void removeSurface(SurfaceWrapper *wrapper); + + // Immediately re-evaluate every watcher against the currently tracked + // window rects (set_region semantics and protocol tests). + void recheck(); + +Q_SIGNALS: + void regionWatchCreated(RegionWatchV1 *watch); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + void scheduleRecheck(); + + std::unique_ptr d; +}; + +class RegionWatchV1 : public QObject +{ + Q_OBJECT +public: + enum Anchor { + Top = 0, + Bottom = 1, + Left = 2, + Right = 3, + }; + Q_ENUM(Anchor) + + ~RegionWatchV1() override; + + // Monitored region in global layout coordinates (output position + + // strip); empty when the watcher is + // inert (no successful set_region yet, or the associated output was + // removed). + QRect region() const; + + TreelandRegionWatchManagerInterfaceV1 *manager() const; + +private: + explicit RegionWatchV1(wl_resource *resource); + void onOutputDestroyed(); + +private: + friend class TreelandRegionWatchManagerInterfaceV1Private; + friend class RegionWatchV1Private; + TreelandRegionWatchManagerInterfaceV1 *m_manager = nullptr; + std::unique_ptr d; +}; diff --git a/src/modules/resource/treelanddebugsocket.cpp b/src/modules/resource/treelanddebugsocket.cpp new file mode 100644 index 0000000000..c192d7d241 --- /dev/null +++ b/src/modules/resource/treelanddebugsocket.cpp @@ -0,0 +1,542 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "treelanddebugsocket.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +namespace { + +// Where the global service binds its debug socket: a directory of its own, NOT +// the process's XDG_RUNTIME_DIR. Widening the runtime directory to 0711 makes +// QStandardPaths::RuntimeLocation reject it (Qt requires 0700) and fall back to +// "$TMPDIR/runtime-", which is where sessions created during the window +// would then put their wayland sockets. systemd creates this one +// (RuntimeDirectory= in misc/systemd/treeland.service.in) and recreates it 0700 +// whenever treeland restarts, so nothing but the debug socket lives in it. +QString globalSocketDir() +{ + // Development and test hook: lets a run use a directory it can write, and + // the caller who controls treeland's environment already controls treeland. + const QString override = qEnvironmentVariable("TREELAND_DEBUG_DIR"); + if (!override.isEmpty()) + return QDir::cleanPath(override); + return QStringLiteral("/run/treeland-debug"); +} + +// The runtime directory of this process, as QStandardPaths reports it +// ($XDG_RUNTIME_DIR): "/run/treeland" for the global service (see +// RuntimeDirectory= in misc/systemd/treeland.service.in) and +// "/run/user/" for a session. Qt creates it with mode 0700 owned by the +// caller when missing and rejects one owned by somebody else, so the directory +// itself is the privacy boundary. When the variable is unset or unusable Qt +// falls back to "$TMPDIR/runtime-" -- that is /tmp again, which is what +// this socket must stay out of, so such a fallback counts as "no runtime +// directory". +QString runtimeSocketDir() +{ + const QString envDir = QFile::decodeName(qgetenv("XDG_RUNTIME_DIR")); + if (envDir.isEmpty()) + return {}; + const QString dir = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation); + if (dir.isEmpty() || !dir.startsWith(QLatin1Char('/'))) + return {}; + // Anything but the configured directory means QStandardPaths substituted + // its temp-dir fallback. + if (QDir::cleanPath(dir) != QDir::cleanPath(envDir)) + return {}; + return dir; +} +#ifdef TREELAND_DEBUG_DEV_BUILD +// Development builds use a UID-specific directory under /tmp so a nested +// compositor never publishes its socket in the host's /run namespace. The +// sticky /tmp parent protects creation; the owned 0700 child is private to the +// compositor's UID. +QString developmentSocketDir() +{ + const QString override = qEnvironmentVariable("TREELAND_DEBUG_DIR"); + if (!override.isEmpty()) + return QDir::cleanPath(override); + + const uid_t uid = ::geteuid(); + const QString dir = QStringLiteral("/tmp/treeland-debug-%1") + .arg(static_cast(uid)); + const QByteArray path = QFile::encodeName(dir); + if (::mkdir(path.constData(), 0700) < 0 && errno != EEXIST) + return {}; + + struct stat st {}; + if (::lstat(path.constData(), &st) < 0 || !S_ISDIR(st.st_mode) || st.st_uid != uid + || (st.st_mode & (S_ISVTX | S_IWOTH))) { + return {}; + } + if ((st.st_mode & 0777) != 0700 && ::chmod(path.constData(), 0700) < 0) + return {}; + if (::lstat(path.constData(), &st) < 0 || !S_ISDIR(st.st_mode) || st.st_uid != uid + || (st.st_mode & 0777) != 0700) { + return {}; + } + return dir; +} +#endif + + +// "local:" + absolute socket path, the form both QRemoteObjectHost and a +// client outside the compositor's runtime directory can resolve. +QString socketUrl(const QString &dir, const QString &name) +{ + return QStringLiteral("local:%1/%2").arg(dir, name); +} + +} // namespace + +QString treelandDebugDefaultSocketName() +{ + return QStringLiteral(TREELAND_DEBUG_SOCKET); +} + +QString treelandDebugGlobalSocketDir() +{ + return globalSocketDir(); +} + +QString treelandDebugSocketDir() +{ +#ifdef TREELAND_DEBUG_DEV_BUILD + // The development instance is deliberately separate from the system-wide + // socket directory. Its CLI discovers this same per-user /tmp directory. + if (qEnvironmentVariable("TREELAND_DEBUG_DIR").isEmpty()) + return developmentSocketDir(); +#endif + // A session instance keeps its socket in its own runtime directory: it must + // not bind in the global service's directory (not its own, likely absent or + // not writable), and it never widens anything there anyway. + if (qEnvironmentVariable("TREELAND_RUN_MODE") == QLatin1String("user")) + return runtimeSocketDir(); + + const QString globalDir = globalSocketDir(); + const QFileInfo globalInfo(globalDir); + if (globalInfo.isDir()) { + const QFile::Permissions searchBits = + QFile::ExeOwner | QFile::ExeGroup | QFile::ExeOther; + const bool hasSearchPermission = + (globalInfo.permissions() & searchBits) != QFile::Permissions{}; + if (globalInfo.isWritable() && globalInfo.isExecutable() && hasSearchPermission) + return globalDir; + return runtimeSocketDir(); + } + if (QDir().mkpath(globalDir)) { + const QByteArray encodedDir = QFile::encodeName(globalDir); + if (::chmod(encodedDir.constData(), 0700) == 0) { + const QFileInfo createdInfo(globalDir); + if (createdInfo.isWritable() && createdInfo.isExecutable()) + return globalDir; + } + } + return runtimeSocketDir(); +} + +// A client probes its own development/runtime directories before the shared +// global and legacy locations. Debug clients never enumerate another UID's +// runtime directory; Release root clients retain the existing session scan. +QStringList treelandDebugSocketDirs() +{ + QStringList dirs; + const QString own = treelandDebugSocketDir(); + if (!own.isEmpty()) + dirs << own; + const QString globalDir = globalSocketDir(); + if (!dirs.contains(globalDir)) + dirs << globalDir; + const QString legacyGlobalDir = QStringLiteral("/run/treeland"); + if (!dirs.contains(legacyGlobalDir)) + dirs << legacyGlobalDir; +#ifdef TREELAND_DEBUG_DEV_BUILD + const QString runtimeDir = runtimeSocketDir(); + if (!runtimeDir.isEmpty() && !dirs.contains(runtimeDir)) + dirs << runtimeDir; +#else + const QDir sessions(QStringLiteral("/run/user")); + const QStringList sessionIds = sessions.entryList(QDir::Dirs | QDir::NoDotAndDotDot, + QDir::Name); + for (const QString &sessionId : sessionIds) { + const QString dir = sessions.filePath(sessionId); + if (!dirs.contains(dir)) + dirs << dir; + } +#endif + return dirs; +} + +QString treelandDebugReleaseSocketName() +{ + return QStringLiteral(TREELAND_DEBUG_SOCKET_RELEASE); +} + +// A bare name is resolved by Qt against QDir::tempPath(); our own URLs always +// carry an absolute path, so this only affects hand-written --url values. +QString treelandDebugSocketPath(const QString &socketName) +{ + if (socketName.startsWith(QLatin1Char('/'))) + return socketName; + return QDir::cleanPath(QDir::tempPath()) + QLatin1Char('/') + socketName; +} + +// A socket path or bare name becomes a local: URL. Other schemes are explicit +// remote endpoints and are left untouched. +QString treelandDebugSocketUrlFromEnv() +{ + const QString value = qEnvironmentVariable("TREELAND_DEBUG_SOCKET"); + if (value.isEmpty()) + return {}; + if (value.contains(QLatin1Char(':'))) + return value; + return QStringLiteral("local:") + value; +} + +QStringList treelandDebugCandidateSocketUrls() +{ +#ifdef TREELAND_DEBUG_DEV_BUILD + const QStringList names{ treelandDebugDefaultSocketName(), + treelandDebugReleaseSocketName() }; +#else + const QStringList names{ treelandDebugDefaultSocketName() }; +#endif + const QStringList dirs = treelandDebugSocketDirs(); + QStringList urls; + for (const QString &name : names) { + for (const QString &dir : dirs) + urls << socketUrl(dir, name); + } + return urls; +} + + +// ── TreelandDebugSocketLock ────────────────────────────────────────────── + +namespace { + +// Returns true if a server is actively accepting connections on @p socketName. +// Used only after the flock is acquired, to avoid clobbering a live +// old-build instance that doesn't hold a lock file. For local (AF_UNIX) +// sockets, QLocalSocket::connectToServer completes synchronously — a live +// server is in ConnectedState immediately, a stale/absent socket is in +// UnconnectedState with an error. No waitForConnected() is needed, so this +// never blocks the compositor startup path. +bool socketIsLive(const QString &socketName) +{ + QLocalSocket probe; + probe.connectToServer(socketName); + return probe.state() == QLocalSocket::ConnectedState; +} + +} // namespace + +QString treelandDebugSocketPathForUrl(const QString &url) +{ + constexpr auto prefix = "local:"; + if (!url.startsWith(QLatin1String(prefix))) + return {}; + const QString name = url.mid(static_cast(qstrlen(prefix))); + if (name.isEmpty()) + return {}; + // Same resolution Qt applies to a bare server name. + return treelandDebugSocketPath(name); +} + +namespace { + +// QFileInfo has no socket test, and only a socket can be connected to. +bool isSocketPath(const QString &path) +{ + struct stat st {}; + return ::stat(QFile::encodeName(path).constData(), &st) == 0 && S_ISSOCK(st.st_mode); +} + +// A process names itself whatever it likes (/proc//comm, up to 15 bytes), so +// control bytes in that name would land on the terminal and let the process that +// owns the socket rewrite this diagnostic -- clear the screen, hide the real +// lines, spoof another program's message. Keep the name readable instead. +QString printableProcessName(const QString &name) +{ + QString printable; + printable.reserve(name.size()); + for (const QChar character : name.left(64)) { + // C0, DEL and the C1 block: fromLatin1() maps the bytes 0x80-0x9f to + // U+0080-U+009F, which terminals that decode C1 still act on. + const ushort code = character.unicode(); + const bool control = code < 0x20 || (code >= 0x7f && code <= 0x9f); + printable.append(control ? QLatin1Char('?') : character); + } + return printable; +} + +} // namespace + +QString treelandDebugSocketPeerText(const QLocalSocket &socket) +{ + struct ucred cred {}; + socklen_t length = sizeof(cred); + const qintptr descriptor = socket.socketDescriptor(); + if (descriptor < 0 + || ::getsockopt(static_cast(descriptor), SOL_SOCKET, SO_PEERCRED, &cred, &length) < 0) { + return {}; + } + + const QString uid = QStringLiteral("uid %1").arg(cred.uid); + QFile comm(QStringLiteral("/proc/%1/comm").arg(cred.pid)); + const QString name = comm.open(QIODevice::ReadOnly) + ? printableProcessName(QString::fromLatin1(comm.readAll()).trimmed()) + : QString(); + return name.isEmpty() ? QStringLiteral("pid %1, %2").arg(cred.pid).arg(uid) + : QStringLiteral("pid %1 (%2), %3").arg(cred.pid).arg(name).arg(uid); +} + +QStringList treelandDebugPublishedSocketPaths(const QString &url) +{ + const QString path = treelandDebugSocketPathForUrl(url); + if (path.isEmpty()) + return {}; + + QStringList paths; + // Only real sockets: a plain file someone else dropped at the name is not a + // published debug channel, and counting it would make the diagnostics name + // it as one. + if (isSocketPath(path)) + paths << path; + + // QLocalServer falls back to "-" when the base name is taken. + // Only digits count: "-dev" belongs to the other build type, and a + // partial match such as "-1.bak" is not a socket of this name. + const QFileInfo info(path); + const QDir dir(info.absolutePath()); + const QString prefix = info.fileName() + QLatin1Char('-'); + const QStringList siblings = dir.entryList({ prefix + QStringLiteral("[0-9]*") }, + QDir::Files | QDir::System | QDir::Hidden); + for (const QString &sibling : siblings) { + bool numbered = false; + sibling.mid(prefix.size()).toUInt(&numbered); + const QString siblingPath = dir.filePath(sibling); + if (numbered && isSocketPath(siblingPath)) + paths << siblingPath; + } + return paths; +} + +bool treelandDebugSocketPublished(const QString &url) +{ + return !treelandDebugPublishedSocketPaths(url).isEmpty(); +} + +QStringList treelandDebugExistingSocketUrls(const QStringList &urls) +{ + QStringList existing; + for (const QString &url : urls) { + const QString path = treelandDebugSocketPathForUrl(url); + if (path.isEmpty() || QFileInfo::exists(path)) + existing << url; + } + return existing.isEmpty() ? urls : existing; +} + +QStringList treelandDebugInstanceSocketUrls(const QStringList &candidateUrls) +{ + QStringList urls; + for (const QString &candidate : candidateUrls) { + // A candidate's own suffixed instances follow it, so the build-type + // preference (debug before release) wins over the base name. + QStringList group{ candidate }; + // A bare name in a "local:" URL resolves under QDir::tempPath(), so an + // absolute candidate (local:/dir/name) must hand out absolute instance + // names too -- otherwise the directory is dropped and the client probes a + // same-named socket somewhere else. + const bool absolute = candidate.startsWith(QStringLiteral("local:/")); + // Bound what one candidate contributes: the directory is writable by its + // owner, so a run of numbered sockets must not turn the privileged + // client's discovery into a string of probes. + constexpr int maxInstances = 8; + int added = 0; + for (const QString &path : treelandDebugPublishedSocketPaths(candidate)) { + if (added == maxInstances) + break; + const QString url = QStringLiteral("local:") + + (absolute ? path : QFileInfo(path).fileName()); + if (group.contains(url)) + continue; + group << url; + ++added; + } + for (const QString &url : std::as_const(group)) { + if (!urls.contains(url)) + urls << url; + } + } + return urls; +} + +TreelandDebugSocketLock::~TreelandDebugSocketLock() { release(); } + +TreelandDebugSocketLock::TreelandDebugSocketLock(TreelandDebugSocketLock &&other) noexcept +{ + std::swap(m_fd, other.m_fd); + std::swap(m_lockPath, other.m_lockPath); +} + +TreelandDebugSocketLock &TreelandDebugSocketLock::operator=(TreelandDebugSocketLock &&other) noexcept +{ + if (this != &other) { + release(); + std::swap(m_fd, other.m_fd); + std::swap(m_lockPath, other.m_lockPath); + } + return *this; +} + +bool TreelandDebugSocketLock::tryAcquire(const QString &socketName) +{ + release(); + // Resolve the full path so the lock file sits next to the socket, and use + // that path for every Qt call below: a bare name would be resolved by + // QLocalServer/QLocalSocket against the process' temp dir, not the socket + // directory. + const QString fullPath = treelandDebugSocketPath(socketName); + m_lockPath = QFile::encodeName(fullPath + QStringLiteral(".lock")); + m_fd = ::open(m_lockPath.constData(), O_CREAT | O_CLOEXEC | O_RDWR, + S_IRUSR | S_IWUSR); + if (m_fd < 0) { + m_lockPath.clear(); + return false; + } + if (::flock(m_fd, LOCK_EX | LOCK_NB) < 0) { + ::close(m_fd); + m_fd = -1; + m_lockPath.clear(); + return false; + } + // The flock rules out any other new-build treeland (they all use this + // lock). But a pre-existing old-build instance may be listening on this + // socket without holding a lock file; reclaiming it would delete its + // socket path and break its clients. Probe liveness first and, if a live + // server answers, leave the name to it and fail so the caller moves on to + // a suffixed name. A stale file left by a crash (no live server) is still + // reclaimed. For local (AF_UNIX) sockets the connect completes + // synchronously, so this probe returns immediately. + if (socketIsLive(fullPath)) { + release(); + return false; + } + QLocalServer::removeServer(fullPath); + return true; +} + +void TreelandDebugSocketLock::release() +{ + // Unlink the lock file while the fd is still open (flock held), then + // close — mirrors wl_socket_destroy() ordering. + if (!m_lockPath.isEmpty()) { + ::unlink(m_lockPath.constData()); + m_lockPath.clear(); + } + if (m_fd >= 0) { + ::close(m_fd); + m_fd = -1; + } +} + +bool TreelandDebugSocketLock::isHeld() const +{ + return m_fd >= 0; +} + +QString treelandDebugPickFreeSocketName( + TreelandDebugSocketLock &lock, + const QString &base) +{ + // @p base is the absolute socket path from the caller; a bare name here + // would be resolved by Qt against the temp dir, so it is not supported. + if (!base.startsWith(QLatin1Char('/'))) + return {}; + + lock.release(); + for (int i = 0; i < 100; ++i) { + const QString candidate = (i == 0) + ? base + : QStringLiteral("%1-%2").arg(base).arg(i); + if (lock.tryAcquire(candidate)) + return candidate; + } + return {}; +} + +// ── access policy ──────────────────────────────────────────────────────── + +namespace { + +bool chmodPath(const QString &path, mode_t mode) +{ + return ::chmod(QFile::encodeName(path).constData(), mode) == 0; +} + +} // namespace + +bool treelandDebugSetSocketAccess(const QString &socketPath, bool anyUser) +{ + if (socketPath.isEmpty()) + return false; + + const QString dir = QFileInfo(socketPath).absolutePath(); + // The global service may widen only its dedicated directory. The dev + // instance owns a UID-specific private /tmp directory; it is never widened + // or rewritten here. Session and arbitrary directories stay untouched. + const QString globalDir = QFileInfo(treelandDebugGlobalSocketDir()).canonicalFilePath(); + const bool ownsDir = !globalDir.isEmpty() + && QFileInfo(dir).canonicalFilePath() == globalDir; +#ifdef TREELAND_DEBUG_DEV_BUILD + const QString devDir = QFileInfo(developmentSocketDir()).canonicalFilePath(); + const bool ownsDevDir = !devDir.isEmpty() + && QFileInfo(dir).canonicalFilePath() == devDir; +#else + const bool ownsDevDir = false; +#endif + if (anyUser && !ownsDir && !ownsDevDir) { + errno = EACCES; // callers log qt_error_string() on failure + return false; + } + if (anyUser) { + // Only directories owned by this compositor and not sticky or + // world-writable are eligible. + struct stat dirSt {}; + const bool safeOwnerDir = ::stat(QFile::encodeName(dir).constData(), &dirSt) == 0 + && dirSt.st_uid == ::geteuid() + && !(dirSt.st_mode & (S_ISVTX | S_IWOTH)); + if (!safeOwnerDir) { + errno = EACCES; + return false; + } + } + + // Only the socket is toggled on close. The global directory is widened once, + // when a window first opens, and stays 0711 until the process exits: several + // compositor instances can share it. The dev directory stays private; its + // socket is owner-only, which is sufficient for the same-UID dev client. + // systemd recreates the global directory as 0700 on the next start. + const mode_t socketMode = anyUser ? (ownsDevDir ? 0600 : 0666) : 0; + bool ok = chmodPath(socketPath, socketMode); + if (ownsDir && !ownsDevDir && anyUser) + ok = chmodPath(dir, 0711) && ok; + return ok; +} diff --git a/src/modules/resource/treelanddebugsocket.h b/src/modules/resource/treelanddebugsocket.h new file mode 100644 index 0000000000..4c48ec4570 --- /dev/null +++ b/src/modules/resource/treelanddebugsocket.h @@ -0,0 +1,190 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +// +// Shared socket-naming logic for the treeland-debug remote-object channel. +// +// The global Release service binds in /run/treeland-debug; Release session +// instances use their per-user runtime directory. Debug development builds +// instead use the UID-specific /tmp/treeland-debug- directory (mode 0700), +// avoiding the host's /run namespace while keeping local discovery deterministic. +// It is not placed directly in world-writable /tmp, where a socket name could be +// squatted. TREELAND_DEBUG_DIR is an explicit override. Clients probe the +// compositor's own dev/runtime directory first and retain shared global/legacy +// fallbacks. +// +// When the default name is already held by a live instance, a numeric suffix +// is chosen using a non-blocking advisory lock, mirroring libwayland's +// wl_display_add_socket_auto (see waylib/src/server/kernel/wsocket.cpp). +// Debug-compiled treeland uses a distinct base name so it can run alongside a +// release build; a debug-built treeland-debug client prefers the debug socket +// and falls back to the release socket. + +#pragma once + +#include +#include +#include + +class QLocalSocket; + +// Provided by CMake as a compile definition (see top-level CMakeLists.txt). +#ifndef TREELAND_DEBUG_SOCKET +# error "TREELAND_DEBUG_SOCKET must be provided by CMake (see top-level CMakeLists.txt)" +#endif + +// Build-specific socket base name (bare name, no path, no "local:" scheme). +QString treelandDebugDefaultSocketName(); + +// Directory of the global service's debug socket: a directory of its own +// (/run/treeland-debug, created by RuntimeDirectory= in +// misc/systemd/treeland.service.in), never the process's XDG_RUNTIME_DIR -- +// Qt requires that one to stay 0700 and would move new sessions' wayland +// sockets to $TMPDIR if it were widened. $TREELAND_DEBUG_DIR overrides it, for +// development and tests; the no-auth window still only opens this directory. +QString treelandDebugGlobalSocketDir(); + +// Directory this process binds its socket in: Debug builds use +// /tmp/treeland-debug- unless TREELAND_DEBUG_DIR explicitly overrides it. +// Release global services use their dedicated directory (created 0700 if +// missing); user-mode processes or processes without access to that directory +// fall back to their runtime directory. Empty when neither is usable. +QString treelandDebugSocketDir(); + +// Candidate directories, most-preferred first: this process' own directory, +// then the global service directory and legacy /run/treeland. Debug builds +// probe only their own runtime directory; Release root clients also probe each +// /run/user/ session directory they can list. +// Pure: no directory is created or probed here. +QStringList treelandDebugSocketDirs(); + +// Release-build socket base name (always defined so a debug-built client can +// fall back to a release instance). +#ifndef TREELAND_DEBUG_SOCKET_RELEASE +# error "TREELAND_DEBUG_SOCKET_RELEASE must be provided by CMake (see top-level CMakeLists.txt)" +#endif +QString treelandDebugReleaseSocketName(); + +// Full filesystem path of a socket name, resolved exactly like +// QLocalServerPrivate::fullServerName: a bare name lives in QDir::tempPath(), +// an absolute path is used as-is. Our own URLs always carry the absolute path, +// so this only decides what a hand-written `--url local:` means -- for +// both the connection and the diagnostics, which is why it has to follow Qt. +QString treelandDebugSocketPath(const QString &socketName); + +// Candidate socket URLs for the treeland-debug client, in preference order: +// every socket name below, in each directory from treelandDebugSocketDirs(). +// A debug-built client prefers the debug instance and falls back to the +// release instance; a release-built client only uses the release instance. +// An explicit --url always overrides this list (handled by the caller). +QStringList treelandDebugCandidateSocketUrls(); + +// Full path of the local-socket file behind a "local:" host URL, or an +// empty string when @p url is not a local socket URL. +QString treelandDebugSocketPathForUrl(const QString &url); + +// Host URL from $TREELAND_DEBUG_SOCKET, or empty when the variable is unset. +// A plain socket path (or a bare socket name) is turned into a "local:" URL; a +// value that already carries a scheme is used verbatim. The client applies it +// only when `--url` was not given, and only before falling back to its own +// probing -- so the priority is: command line, then this variable, then +// treelandDebugCandidateSocketUrls(). +QString treelandDebugSocketUrlFromEnv(); + +// Paths of the sockets published for @p url: the exact name when it exists, plus +// every "-" sibling (Qt appends a numeric suffix when the name is +// taken). Only Unix-domain sockets count -- a plain file that merely occupies +// the name is not a published channel. A differently built instance +// ("-dev") is never included. More +// than one entry means several instances or a stale file left by a crash, which +// a caller reporting a connection failure should say verbatim instead of +// guessing. Empty when nothing is published. +QStringList treelandDebugPublishedSocketPaths(const QString &url); + +// True when treelandDebugPublishedSocketPaths() finds a socket for @p url. +bool treelandDebugSocketPublished(const QString &url); + +// @p urls without the local candidates whose socket file is absent: connecting to +// one cannot succeed, so probing it would only spend a probe timeout. A list +// whose every local candidate is absent is returned unchanged, so a caller's +// failure diagnostics can still name every place that was searched. +QStringList treelandDebugExistingSocketUrls(const QStringList &urls); + +// Candidate URLs plus every instance published for them: each candidate is +// followed by its own "-" instances, so the candidate order (debug +// before release) still decides which build type is preferred. A socket on the +// base name that belongs to someone else (or a stale file) must not make the +// client report a failure while an instance of this build is answering. +QStringList treelandDebugInstanceSocketUrls(const QStringList &candidateUrls); + +// Describes the process on the other end of a connected @p socket, e.g. +// "pid 4711 (treeland), uid 1000", from the kernel's SO_PEERCRED: each side of a +// Unix socket knows its peer's credentials, so this works for another user's +// process without reading /proc. The command name is omitted when +// /proc//comm is unreadable (hidepid, restricted container). Empty when the +// socket is not connected. Used only on the connection-failure path, where +// naming the process replaces guessing whether the socket belongs to another +// instance. +QString treelandDebugSocketPeerText(const QLocalSocket &socket); + +// Applies the socket's access policy: @p anyUser requests the global Release +// no-auth mode (0666); Debug development sockets remain owner-only (0600). +// Otherwise the socket is sealed (mode 0000). A socket is only reachable from +// inside a traversable directory. +// +// The global Release directory may be widened to 0711 and is not narrowed on +// close because other instances may share it. A Debug build's UID-specific +// /tmp directory stays private (0700). Session and arbitrary directories are +// refused before they are touched, since they may contain resources the +// compositor does not own. Returns false when policy cannot be applied. +// +// Called with @p anyUser by the Release no-auth window and, once at startup, by +// a Debug build. +bool treelandDebugSetSocketAccess(const QString &socketPath, bool anyUser); + +// RAII lock that claims a local-socket name, mirroring wl_socket_lock() in +// libwayland. An exclusive flock on ".lock" (placed next to the socket) +// is held for the lifetime of the +// QLocalServer, so two treeland instances can never silently steal each +// other's socket — QLocalServer::listen(), unlike raw bind(), replaces an +// existing socket file instead of failing with EADDRINUSE, so the flock is +// the real ownership guard. +// +// The destroy ordering matches wl_socket_destroy(): the lock file is unlinked +// *while* the fd (and thus the flock) is still held, so no other process can +// open the same inode and race the release. +class TreelandDebugSocketLock +{ +public: + TreelandDebugSocketLock() = default; + ~TreelandDebugSocketLock(); + + TreelandDebugSocketLock(const TreelandDebugSocketLock &) = delete; + TreelandDebugSocketLock &operator=(const TreelandDebugSocketLock &) = delete; + TreelandDebugSocketLock(TreelandDebugSocketLock &&other) noexcept; + TreelandDebugSocketLock &operator=(TreelandDebugSocketLock &&other) noexcept; + + bool tryAcquire(const QString &socketName); + void release(); + bool isHeld() const; + +private: + int m_fd = -1; + QByteArray m_lockPath; +}; + +// Returns the first free socket, Wayland-style: tries @p base, then +// "-1", "-2", ... up to "-99". For each candidate a lock +// file is acquired with flock(LOCK_EX|LOCK_NB); if the lock is already held +// by another process the name is in use and the next candidate is tried. +// +// On success @p lock holds the lock — the caller MUST keep it alive for the +// lifetime of the QLocalServer so the name stays claimed. On failure (all +// names locked) returns an empty string and @p lock is released. +// +// @p base is the absolute socket path to claim (treelandDebugSocketDir() plus +// the socket name) and the result is that path plus a numeric suffix: the +// caller turns it into "local:" so server and client agree regardless of +// their own environment. +QString treelandDebugPickFreeSocketName( + TreelandDebugSocketLock &lock, + const QString &base); diff --git a/src/modules/resource/treelandremotesource.cpp b/src/modules/resource/treelandremotesource.cpp new file mode 100644 index 0000000000..dc50742539 --- /dev/null +++ b/src/modules/resource/treelandremotesource.cpp @@ -0,0 +1,1402 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "treelandremotesource.h" + +#include "core/rootsurfacecontainer.h" +#include "core/shellhandler.h" +#include "idle/idlemanager.h" +#include "modules/shortcut/shortcutcontroller.h" +#include "output/output.h" +#include "core/waylandserver.h" +#include "surface/surfacecontainer.h" +#include "surface/surfacewrapper.h" +#include "workspace/workspace.h" +#include "workspace/workspacemodel.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "treelanddebugsocket.h" +#include "common/treelandlogging.h" +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { + +// A requested no-auth window closes when it went this long without a single +// call, and every call pushes it out again. +constexpr int NoAuthIdleTimeout = 30 * 60 * 1000; + +QString executableForPid(int pid) +{ + if (pid <= 0) + return {}; + // /proc//exe is a symlink to the real executable path. Use + // QFileInfo::symLinkTarget() so the read is cross-platform and returns + // an empty string when the link is unreadable (e.g. another user's pid). + return QFileInfo(QStringLiteral("/proc/%1/exe").arg(pid)).symLinkTarget(); +} + +QString commandForPid(int pid) +{ + if (pid <= 0) + return {}; + // /proc//cmdline is the full command line with arguments separated + // by NUL bytes. Join them with spaces for a human/debug-friendly string. + QFile cmdline(QStringLiteral("/proc/%1/cmdline").arg(pid)); + if (!cmdline.open(QIODevice::ReadOnly)) + return {}; + const QByteArray raw = cmdline.readAll(); + const QList args = raw.split('\0'); + QStringList parts; + for (const auto &arg : args) { + if (!arg.isEmpty()) + parts << QString::fromUtf8(arg); + } + return parts.join(' '); +} + +// Build the same covered area without assuming that Qt and pixman retain +// the same rectangle decomposition (as WTools::fromPixmanRegion does). +QRegion regionFromPixman(const pixman_region32_t *region) +{ + int count = 0; + const pixman_box32_t *boxes = pixman_region32_rectangles(region, &count); + QRegion result; + for (int i = 0; i < count; ++i) { + result += QRect(QPoint(boxes[i].x1, boxes[i].y1), + QPoint(boxes[i].x2 - 1, boxes[i].y2 - 1)); + } + return result; +} + +// Encodes a grabbed frame as PNG bytes. The server never writes to disk; +// the treeland-debug client owns the file. Returns an empty array on failure. +QByteArray encodeImage(const QImage &image) +{ + if (image.isNull()) + return {}; + QByteArray bytes; + QBuffer buffer(&bytes); + if (!buffer.open(QIODevice::WriteOnly)) + return {}; + if (!image.save(&buffer, "png")) + return {}; + return bytes; +} + +// Recursively searches a QQuickItem subtree for the first surface content +// item (a WTextureProviderProvider). Used as a fallback in captureWindow when +// a surface's own findItemContent() returns null (e.g. menus/popups whose +// content lives in a child item). +WSurfaceItemContent *findContentInSubtree(QQuickItem *item) +{ + if (!item) + return nullptr; + if (auto *content = qobject_cast(item)) + return content; + const auto children = item->childItems(); + for (auto *child : children) { + if (auto *content = findContentInSubtree(child)) + return content; + } + return nullptr; +} + + +// Appends one line per QQuickItem in the subtree rooted at @p item, indented +// by depth, describing the item's type/objectName/geometry/visibility. Used +// by getSceneTree() to expose the live QtQuick scene graph to treeland-debug. +void dumpSceneTree(QQuickItem *item, int depth, QString &out) +{ + if (!item) + return; + const QString indent(depth * 2, ' '); + QString line = indent + QString::fromUtf8(item->metaObject()->className()); + const QString name = item->objectName(); + if (!name.isEmpty()) + line += QStringLiteral(" \"%1\"").arg(name); + line += QStringLiteral(" [%1,%2 %3x%4]") + .arg(QString::number(item->x(), 'f', 1)) + .arg(QString::number(item->y(), 'f', 1)) + .arg(QString::number(item->width(), 'f', 1)) + .arg(QString::number(item->height(), 'f', 1)); + if (!item->isVisible()) + line += QStringLiteral(" hidden"); + line += QStringLiteral(" z=%1 op=%2") + .arg(QString::number(item->z(), 'f', 1)) + .arg(QString::number(item->opacity(), 'f', 2)); + out += line + '\n'; + const auto children = item->childItems(); + for (auto *child : children) + dumpSceneTree(child, depth + 1, out); +} + +// Stable window id: the wl_resource pointer of the surface's underlying +// wl_surface. The wl_resource *id* is only unique per wl_client, so two +// windows from different clients can share an id — unsafe for write +// operations (close/move/...) that could target the wrong window. The +// pointer value is unique across the whole server for the lifetime of +// the surface, which is good enough for a single-machine debug tool. +qint64 surfaceId(WSurface *ws) +{ + if (!ws || !ws->handle() || !ws->handle()->resource) + return 0; + return reinterpret_cast(ws->handle()->resource); +} + +// Converts a Qt::Key value to a Linux evdev keycode using the keyboard's +// current xkb keymap. Returns 0 if no keycode produces this key. +// The evdev/keysym conversion lives on the server side (where wlr_seat needs +// the code) while the client talks in portable Qt::Key values. +int qtKeyToEvdev(int qtKey, wlr_keyboard *keyboard) +{ + if (!keyboard || !keyboard->xkb_state) + return 0; + + // Walk the live keymap and return the first keycode whose level-0 symbol + // Qt maps back to the requested Qt::Key value, via Qt's own + // QXkbCommon::keysymToQtKey (the same table used by XWayland), so we never + // need a hand-maintained Qt::Key name -> keysym alias table. + xkb_keymap *keymap = xkb_state_get_keymap(keyboard->xkb_state); + const xkb_keycode_t min_kc = xkb_keymap_min_keycode(keymap); + const xkb_keycode_t max_kc = xkb_keymap_max_keycode(keymap); + for (xkb_keycode_t kc = min_kc; kc <= max_kc; ++kc) { + const xkb_keysym_t *syms = nullptr; + const int count = xkb_keymap_key_get_syms_by_level(keymap, kc, 0, 0, &syms); + for (int i = 0; i < count; ++i) { + if (QXkbCommon::keysymToQtKey(syms[i], Qt::NoModifier, keyboard->xkb_state, kc) == qtKey) + return kc; + } + } + return 0; +} + +} // namespace + +TreelandRemoteSource::TreelandRemoteSource(QObject *parent) + : WindowTreeRemoteSource(parent) +{ + // Pick a conflict-free socket path. Release instances bind in their own + // directory; a Debug development instance uses its UID-private /tmp + // directory. A concurrent instance takes a numeric suffix, selected with + // a non-blocking advisory lock. + const QString socketDir = treelandDebugSocketDir(); + if (socketDir.isEmpty()) { +#ifdef TREELAND_DEBUG_DEV_BUILD + const QString override = qEnvironmentVariable("TREELAND_DEBUG_DIR"); + const QString expectedDir = override.isEmpty() + ? QStringLiteral("/tmp/treeland-debug-%1") + .arg(static_cast(::geteuid())) + : override; + qCWarning(lcTlDebug) << "No usable development debug socket directory" + << expectedDir << "; debug remote source disabled"; +#else + qCWarning(lcTlDebug) << "No usable debug socket directory;" + "debug remote source disabled"; +#endif + return; + } + const QString socketPath = treelandDebugPickFreeSocketName( + m_debugSocketLock, + socketDir + QLatin1Char('/') + treelandDebugDefaultSocketName()); + if (socketPath.isEmpty()) { + // All 100 candidate names are already locked — extremely unlikely + // for a debug channel, but don't bind an invalid URL; leave the debug + // source unpublished. + qCWarning(lcTlDebug) << "No free debug socket name available; " + "debug remote source disabled"; + return; + } + + if (!bindHost(socketPath)) { + m_debugSocketLock.release(); + return; + } + + // Release no-auth mode is a temporary debugging window requested over the + // debug protocol itself (WindowTreeRemote::requestNoAuth): its socket opens + // to every local user, and a call-free half hour closes it again. + m_debugSocketPath = socketPath; + m_noAuthIdleTimer = new QTimer(this); + m_noAuthIdleTimer->setSingleShot(true); + m_noAuthIdleTimer->setInterval(NoAuthIdleTimeout); + connect(m_noAuthIdleTimer, &QTimer::timeout, + this, &TreelandRemoteSource::closeNoAuthWindow); + + // Seal the socket here rather than trusting what startup found: a crash + // during a no-auth window leaves the socket and directory open with no + // record of it, so the state is written, not restored. + closeNoAuthWindow(); +#ifdef TREELAND_DEBUG_DEV_BUILD + // Same-UID access is sufficient for local development and needs no polkit. + // Keep the dev socket owner-only; the global Release no-auth policy is + // separate and remains explicitly requested over the debug protocol. + if (!treelandDebugSetSocketAccess(m_debugSocketPath, true)) { + qCWarning(lcTlDebug) << "Cannot set owner-only access on the debug socket:" + << m_debugSocketPath << ':' << qt_error_string(); + } +#endif + + m_published = true; +} + +TreelandRemoteSource::~TreelandRemoteSource() +{ + stopEventCapture(); + // The window may still be open (remoteDebug turned off, or shutdown): seal it + // now instead of leaving it to the timer. No rebinding here -- the host is + // destroyed below, which drops every peer anyway. + if (m_noAuthIdleTimer) + m_noAuthIdleTimer->stop(); + if (m_socketRootOnly && !treelandDebugSetSocketAccess(m_debugSocketPath, false)) + qCWarning(lcTlDebug) << "Cannot seal the debug socket again:" << m_debugSocketPath + << ':' << qt_error_string(); + // Destroy the host (parent-owned child) before the socket lock member + // releases, so the socket stops listening while we still hold the lock. + // Otherwise a concurrent instance could acquire the lock and remove the + // socket path while the old host is still alive. + delete findChild(); +} + +bool TreelandRemoteSource::bindHost(const QString &socketPath) +{ + auto *host = new QRemoteObjectHost(this); + // Either way the host must bind the socket itself: enableRemoting() is a + // no-op until the host has a hostUrl, so an externally managed + // QLocalServer + addHostSideConnection() advertises nothing (#WM-693). +#ifdef TREELAND_DEBUG_DEV_BUILD + // Debug builds: allow all users to connect (requirement: debug builds + // are unrestricted). WorldAccessOption sets the socket to 0666. + QRemoteObjectHost::setLocalServerOptions(QLocalServer::WorldAccessOption); + if (!host->setHostUrl(QUrl(QStringLiteral("local:%1").arg(socketPath)))) { + qCWarning(lcTlDebug) << "Failed to listen on debug socket" << socketPath; + delete host; + return false; + } +#else + // Release builds: only root may connect. The host binds with + // UserAccessOption (0600, owned by dde) and the socket is then chmod'd to + // 0000: connect() checks the socket inode's write permission, so dde and + // every other non-root user get EACCES while root passes via + // CAP_DAC_OVERRIDE. Same policy as the previous SO_PEERCRED server, but + // with the socket owned by the QtRO host, which enableRemoting() needs. + QRemoteObjectHost::setLocalServerOptions(QLocalServer::UserAccessOption); + if (!host->setHostUrl(QUrl(QStringLiteral("local:%1").arg(socketPath)))) { + qCWarning(lcTlDebug) << "Failed to listen on debug socket" << socketPath; + delete host; + return false; + } + if (::chmod(QFile::encodeName(socketPath).constData(), 0) < 0) { + qCWarning(lcTlDebug) << "Failed to restrict debug socket" << socketPath << ':' + << qt_error_string(); + delete host; // unlinks the socket file, so no reachable-but-deaf socket stays + return false; + } + m_socketRootOnly = true; +#endif + if (!host->enableRemoting(this, QStringLiteral("WindowTree"))) { + qCWarning(lcTlDebug) << "Failed to enable remoting for WindowTree on socket" + << socketPath; + delete host; + return false; + } + return true; +} + +bool TreelandRemoteSource::requestNoAuth() +{ + // A debug build opens the directory and the socket at startup, so there is + // nothing left to open -- but the caller asked for the window, and it is + // there. + if (!m_socketRootOnly) + return true; + + if (!treelandDebugSetSocketAccess(m_debugSocketPath, true)) { + // Only a directory of Treeland's own can be widened, so a session + // instance lands here and keeps requiring root. + qCWarning(lcTlDebug) << "Cannot open the debug socket to every user:" + << m_debugSocketPath << ':' << qt_error_string() + << "(only the global service's own debug directory can be opened)"; + return false; + } + m_noAuthWindowOpen = true; + m_noAuthIdleTimer->start(); + return true; +} + +void TreelandRemoteSource::closeNoAuthWindow() +{ + // The constructor creates the timer last, so every early return (no runtime + // directory, no free socket name, bind/chmod/enableRemoting failure) leaves + // it null -- and such a source is deleted by WaylandServer to be retried. + if (!m_noAuthIdleTimer) + return; + m_noAuthIdleTimer->stop(); + if (!m_socketRootOnly) + return; // a debug build opens it at startup, for good; there is no window + + const bool windowWasOpen = std::exchange(m_noAuthWindowOpen, false); + if (windowWasOpen) { + // chmod 0000 only refuses *new* connects: a peer that got in during the + // window keeps its socket and could stay privileged forever. Rebuilding + // the host closes every connection that was opened while it was open; the + // seal below then closes the fresh socket and the directory again. + if (auto *host = findChild()) { + delete host; + if (!bindHost(m_debugSocketPath)) + qCWarning(lcTlDebug) << "Cannot rebind the debug socket" << m_debugSocketPath + << "; the debug channel stays closed until the next start"; + } + } + + if (!treelandDebugSetSocketAccess(m_debugSocketPath, false)) { + qCWarning(lcTlDebug) << "Cannot seal the debug socket again:" << m_debugSocketPath + << ':' << qt_error_string(); + } +} + +void TreelandRemoteSource::noteActivity() const +{ + // Only a call-free stretch closes the window: every call restarts it, and + // the timer runs only while the window is open. + if (m_noAuthIdleTimer && m_noAuthIdleTimer->isActive()) + m_noAuthIdleTimer->start(); +} + +QPointF TreelandRemoteSource::cursorPosition() const +{ + // The replica fetches this property when it connects, which is a request on + // the debug socket like any other (treeland-debug cursor opens a connection + // for every invocation), so it keeps the no-auth window alive too. + noteActivity(); + // Read the live cursor position on demand. We deliberately do NOT keep a + // WCursor::positionChanged connection alive between requests, so there is + // zero per-pointer-motion overhead when no treeland-debug client is + // connected. The READONLY property is only ever read on replica connect, + // which is exactly when a client asked for it. + if (auto *root = WaylandServer::instance()->rootSurfaceContainer(); root && root->cursor()) + return root->cursor()->position(); + return {}; +} + +TreelandInfo TreelandRemoteSource::getTreelandInfo() +{ + noteActivity(); + TreelandInfo info; + + auto mode = WaylandServer::instance()->currentMode(); + info.setCurrentMode(QString::fromUtf8(QMetaEnum::fromType().valueToKey(static_cast(mode)))); + + if (auto *root = WaylandServer::instance()->rootSurfaceContainer()) { + QList layers; + const auto subcontainers = root->subContainers(); + for (auto *container : subcontainers) { + if (!container) + continue; + layers.append(buildLayerInfo(container)); + } + info.setLayers(layers); + } + return info; +} + +// The rep field stays a string: treeland-debug prints it and a name reads better +// than a number in the JSON. This is the only place the enum becomes text, and +// the names below are the wire contract: camelCase on purpose, so +// QMetaEnum::valueToKey() (which would answer GeometryChanged) cannot be used. +static QString outputsUpdateReasonName(SurfaceWrapper::OutputsUpdateReason reason) +{ + switch (reason) { + case SurfaceWrapper::OutputsUpdateReason::GeometryChanged: + return QStringLiteral("geometryChanged"); + case SurfaceWrapper::OutputsUpdateReason::SurfaceAdded: + return QStringLiteral("surfaceAdded"); + case SurfaceWrapper::OutputsUpdateReason::AddOutput: + return QStringLiteral("addOutput"); + case SurfaceWrapper::OutputsUpdateReason::EnabledChanged: + return QStringLiteral("enabledChanged"); + case SurfaceWrapper::OutputsUpdateReason::Unknown: + break; + } + return {}; +} + +WindowInfo TreelandRemoteSource::buildWindowInfo(SurfaceWrapper *surface, + int layer, + const QString &containerName, + int z) const +{ + WindowInfo info; + info.setId(surfaceId(surface->surface())); + info.setAppId(surface->appId()); + info.setWorkspace(surface->workspaceId()); + info.setLayer(layer); + info.setZ(z); + info.setContainer(containerName); + info.setGeometry(surface->geometry()); + info.setTitlebarGeometry(surface->titlebarGeometry()); + info.setBoundingRect(surface->boundingRect()); + info.setIconGeometry(QRectF(surface->iconGeometry())); + info.setPosition(surface->position()); + info.setVisible(surface->isVisible()); + info.setActive(surface->isActivated()); + info.setMinimized(surface->isMinimized()); + info.setType(static_cast(surface->type())); + info.setState(static_cast(surface->surfaceState())); + + QString outputName; + if (auto *output = surface->ownsOutput(); output && output->output()) { + outputName = output->output()->name(); + } + info.setOutput(outputName); + + // The outputs the window is on, and the one that drives its frame + // callbacks. A window can span several outputs, so the single owner name + // above is not enough to tell where it is drawn. Take the wrapper's list, + // not the wl_surface's: a splash window has no entered outputs yet. + QStringList outputNames; + for (auto *output : surface->outputs()) { + if (output) + outputNames.append(output->name()); + } + info.setOutputs(outputNames); + + QString framePacingOutputName; + if (auto *w = surface->surface()) { + if (auto *pacingOutput = w->framePacingOutput()) + framePacingOutputName = pacingOutput->name(); + } + info.setFramePacingOutput(framePacingOutputName); + + const auto &diag = surface->outputsDiagnostics(); + info.setLastLeaveOutput(diag.lastLeaveOutput); + info.setLastLeaveOutputEnabled(diag.lastLeaveOutputEnabled); + info.setLastLeaveEmptiedOutputs(diag.lastLeaveEmptiedOutputs); + info.setLastOutputsUpdateReason(outputsUpdateReasonName(diag.updateReason)); + info.setLastOutputsUpdateEnabled(diag.updateEnabledOutputs); + info.setLastOutputsUpdateTotal(diag.updateTotalOutputs); + info.setLastOutputsUpdateComputed(diag.updateComputedOutputs); + info.setLastOutputsUpdateAutomatic(diag.updateAutomatic); + + QString title; + if (auto *shellSurface = surface->shellSurface()) { + title = shellSurface->property("title").toString(); + } + info.setTitle(title); + + // Frame/damage statistics from the underlying wlr_surface. + if (auto *w = surface->surface()) { + if (auto *wlr = w->handle()) { + info.setFrames(static_cast(wlr->current.seq)); + const auto *extents = pixman_region32_extents(&wlr->current.buffer_damage); + if (extents) + info.setDamage(QRectF(extents->x1, extents->y1, + extents->x2 - extents->x1, + extents->y2 - extents->y1)); + // wlroots already clipped both regions to the surface size. + info.setInputRegion(regionFromPixman(&wlr->input_region)); + info.setOpaqueRegion(regionFromPixman(&wlr->opaque_region)); + } + } + return info; +} + +void TreelandRemoteSource::collectSurfaceInfos(QList &infos, + SurfaceWrapper *surface, + int layer, + const QString &containerName, + int z) const +{ + infos.append(buildWindowInfo(surface, layer, containerName, z)); + const auto subSurfaces = surface->subSurfaces(); + for (auto *child : subSurfaces) { + if (child) { + collectSurfaceInfos(infos, child, layer, containerName, z); + } + } +} + +void TreelandRemoteSource::collectWorkspaceModelWindows(QList &infos, + WorkspaceModel *workspaceModel, + int layer, + const QString &containerName) const +{ + if (!workspaceModel) + return; + + const QList workspaceSurfaces = workspaceModel->surfaces(); + for (int index = 0; index < workspaceSurfaces.size(); ++index) { + auto *surface = workspaceSurfaces.at(index); + if (surface && !surface->parentSurface()) { + collectSurfaceInfos(infos, surface, layer, containerName, index); + } + } +} + +void TreelandRemoteSource::collectCurrentWorkspaceModelWindows(QList &infos, + WorkspaceModel *workspaceModel, + int layer, + const QString &containerName) const +{ + if (!workspaceModel) + return; + + QList workspaceSurfaces; + int currentId = workspaceModel->id(); + WOutputRenderWindow::paintOrderItemList( + WaylandServer::instance()->workspace(), + [&workspaceSurfaces, currentId](QQuickItem *item) -> bool { + auto surfaceWrapper = qobject_cast(item); + if (surfaceWrapper && surfaceWrapper->showOnWorkspace(currentId)) { + workspaceSurfaces.append(surfaceWrapper); + return true; + } else { + return false; + } + }); + + for (int index = 0; index < workspaceSurfaces.size(); ++index) { + auto *surface = workspaceSurfaces.at(index); + if (surface && !surface->parentSurface()) { + collectSurfaceInfos(infos, surface, layer, containerName, index); + } + } +} + +LayerInfo TreelandRemoteSource::buildLayerInfo(SurfaceContainer *container) const +{ + LayerInfo layerInfo; + const int layer = static_cast(container->z()); + const QString containerName = container->objectName(); + + layerInfo.setName(containerName); + layerInfo.setLayer(layer); + + if (auto *workspace = qobject_cast(container)) { + QList workspaces; + for (auto *workspaceModel : workspace->models()->objects()) { + WorkspaceInfo workspaceInfo; + workspaceInfo.setId(workspaceModel->id()); + workspaceInfo.setIsActive(workspaceModel == workspace->current()); + QList windows; + if (workspaceInfo.isActive()) { + collectCurrentWorkspaceModelWindows(windows, workspaceModel, layer, containerName); + } else { + collectWorkspaceModelWindows(windows, workspaceModel, layer, containerName); + } + workspaceInfo.setWindows(windows); + workspaces.append(workspaceInfo); + } + layerInfo.setWorkspaces(workspaces); + } else { + QList windows; + const QList surfaces = container->surfaces(); + for (int index = 0; index < surfaces.size(); ++index) { + auto *surface = surfaces.at(index); + if (surface && !surface->parentSurface()) { + collectSurfaceInfos(windows, surface, layer, containerName, index); + } + } + layerInfo.setWindows(windows); + } + + return layerInfo; +} + +void TreelandRemoteSource::collectAllToplevelSurfaces(QList &out) const +{ + auto *root = WaylandServer::instance()->rootSurfaceContainer(); + if (!root) + return; + + QSet seen; + const auto appendTop = [&out, &seen](SurfaceWrapper *surface) { + if (surface && !surface->parentSurface() && !seen.contains(surface)) { + seen.insert(surface); + out.append(surface); + } + }; + + for (auto *container : root->subContainers()) { + if (!container) + continue; + if (auto *workspace = qobject_cast(container)) { + if (auto *models = workspace->models()) { + for (auto *model : models->objects()) { + if (!model) + continue; + for (auto *surface : model->surfaces()) + appendTop(surface); + } + } + } else { + for (auto *surface : container->surfaces()) + appendTop(surface); + } + } +} + +SurfaceWrapper *TreelandRemoteSource::findSurfaceById(qint64 id) const +{ + QList surfaces; + collectAllToplevelSurfaces(surfaces); + for (auto *surface : surfaces) { + if (surfaceId(surface->surface()) == id) + return surface; + } + return nullptr; +} + +QList TreelandRemoteSource::getWindows() +{ + noteActivity(); + QList surfaces; + collectAllToplevelSurfaces(surfaces); + + QList infos; + infos.reserve(surfaces.size()); + for (auto *surface : surfaces) { + auto *container = surface->container(); + const QString containerName = container ? container->objectName() : QString(); + const int layer = container ? static_cast(container->z()) : 0; + infos.append(buildWindowInfo(surface, layer, containerName, static_cast(surface->z()))); + } + return infos; +} + +namespace { + +// Shortcut names come from Wayland clients; keep them from forging extra lines +// or terminal escapes in the debug stream. Covers C0 (incl. \n and ESC), DEL +// and C1, which some terminals still interpret as escape introducers. +QString sanitizedName(const QString &name) +{ + QString safe = name; + for (auto &ch : safe) { + const ushort code = ch.unicode(); + if (code < 0x20 || (code >= 0x7f && code <= 0x9f)) + ch = QLatin1Char('?'); + } + return safe; +} + +QString shortcutFlagsText(ShortcutController::KeyFlags flags) +{ + QStringList parts; + if (flags.testFlag(ShortcutController::KeyPress)) + parts << QStringLiteral("press"); + if (flags.testFlag(ShortcutController::KeyRelease)) + parts << QStringLiteral("release"); + if (flags.testFlag(ShortcutController::Repeat)) + parts << QStringLiteral("repeat"); + if (parts.isEmpty()) + parts << QStringLiteral("none"); + return parts.join('|'); +} + +QString swipeDirectionName(SwipeGesture::Direction direction) +{ + switch (direction) { + case SwipeGesture::Direction::Down: + return QStringLiteral("down"); + case SwipeGesture::Direction::Left: + return QStringLiteral("left"); + case SwipeGesture::Direction::Up: + return QStringLiteral("up"); + case SwipeGesture::Direction::Right: + return QStringLiteral("right"); + default: + return {}; + } +} + +// One-line description of a bound shortcut, shared by the `shortcuts` listing +// and the registration event stream. +QString shortcutDetail(const ShortcutController::Binding &binding) +{ + const QString action = QString::fromUtf8(ShortcutController::actionName(binding.action)); + switch (binding.type) { + case ShortcutController::Binding::Key: + return QStringLiteral("\"%1\" = %2 -> %3 [%4]") + .arg(sanitizedName(binding.name), + binding.key, + action, + shortcutFlagsText(binding.flags)); + // Every placeholder is filled in one arg() pass: a client-provided name + // containing "%2" must not be substituted by the next chained arg(). + case ShortcutController::Binding::Swipe: + return QStringLiteral("\"%1\" = swipe %2-finger %3 -> %4") + .arg(sanitizedName(binding.name), + QString::number(binding.fingers), + swipeDirectionName(binding.direction), + action); + case ShortcutController::Binding::Hold: + return QStringLiteral("\"%1\" = hold %2-finger -> %3") + .arg(sanitizedName(binding.name), QString::number(binding.fingers), action); + } + return {}; +} + +} // namespace + +QList TreelandRemoteSource::getShortcuts() +{ + QList result; + auto *server = WaylandServer::instance(); + auto *controller = server ? server->shortcutController() : nullptr; + if (!controller) + return result; + + const auto bindings = controller->bindings(); + result.reserve(bindings.size()); + for (const auto &binding : bindings) { + ShortcutInfo info; + info.setName(sanitizedName(binding.name)); + info.setType(binding.type); + info.setKey(binding.key); + info.setFlags(binding.flags); + info.setAction(QString::fromUtf8(ShortcutController::actionName(binding.action))); + info.setFingers(binding.fingers); + info.setDirection(swipeDirectionName(binding.direction)); + result.append(info); + } + return result; +} + +QList TreelandRemoteSource::getClients() +{ + noteActivity(); + QList result; + auto *server = WaylandServer::instance(); + auto *nativeServer = server ? server->server() : nullptr; + auto *display = nativeServer ? nativeServer->handle() : nullptr; + + struct ClientEntry { + qint64 id = 0; + QString appId; + int pid = 0; + QString executable; + QString command; + QList windows; + }; + QList entries; + QHash indexByClient; + + const auto ensureEntry = [&](wl_client *client) -> int { + if (!client) + return -1; + auto it = indexByClient.constFind(client); + if (it != indexByClient.constEnd()) + return it.value(); + ClientEntry entry; + entry.id = reinterpret_cast(client); + // Use WClient's own credential/appId accessors instead of reaching + // into libwayland directly. + if (auto *wclient = WClient::get(client)) { + if (auto creds = wclient->credentials()) + entry.pid = creds->pid; + entry.appId = QString::fromUtf8(wclient->appId()); + } else if (auto creds = WClient::getCredentials(client)) { + entry.pid = creds->pid; + } + entry.executable = executableForPid(entry.pid); + entry.command = commandForPid(entry.pid); + indexByClient.insert(client, entries.size()); + entries.append(entry); + return entries.size() - 1; + }; + + // Group toplevel windows by their owning Wayland client. + QList surfaces; + collectAllToplevelSurfaces(surfaces); + for (auto *surface : surfaces) { + auto *wsurface = surface->surface(); + if (!wsurface || !wsurface->handle()) + continue; + wl_client *client = wl_resource_get_client(wsurface->handle()->resource); + const int index = ensureEntry(client); + if (index < 0) + continue; + auto *container = surface->container(); + const QString containerName = container ? container->objectName() : QString(); + const int layer = container ? static_cast(container->z()) : 0; + entries[index].windows.append( + buildWindowInfo(surface, layer, containerName, static_cast(surface->z()))); + } + + // Also include connected clients that own no toplevel window. + if (display) { + struct wl_list *clientList = wl_display_get_client_list(display); + wl_client *client = nullptr; + wl_client_for_each(client, clientList) + { + ensureEntry(client); + } + } + + for (const auto &entry : std::as_const(entries)) { + ClientInfo info; + info.setId(entry.id); + info.setAppId(entry.appId); + info.setPid(entry.pid); + info.setExecutable(entry.executable); + info.setCommand(entry.command); + info.setWindows(entry.windows); + result.append(info); + } + return result; +} + +IdleInfo TreelandRemoteSource::getIdleInfo() +{ + noteActivity(); + IdleInfo info; + auto *server = WaylandServer::instance(); + auto *idle = server ? server->idleManager() : nullptr; + if (!idle) + return info; + + info.setInhibited(idle->isIdleInhibited()); + info.setScreensaverInhibited(idle->isScreensaverInhibited()); + info.setIdleMs(static_cast(qMax(idle->idleMs(), 0))); + + QList inhibitors; + for (const auto &source : idle->inhibitors()) { + IdleInhibitor entry; + // Same id scheme as the window list, so an inhibitor surface shows up + // in ``windows``/``top`` and can be used as a control target — but only + // when the inhibitor is held on a toplevel surface. Layer-shell and + // subsurface inhibitors (common for video players) report the raw + // surface id, which the window list does not contain. + entry.setSurfaceId(source.surface ? reinterpret_cast(source.surface->resource) : 0); + entry.setKind(source.kind); + entry.setAppId(source.appId); + entry.setTitle(source.title); + entry.setPid(source.pid); + entry.setExecutable(executableForPid(source.pid)); + entry.setCommand(commandForPid(source.pid)); + entry.setAppName(source.appName); + entry.setReason(source.reason); + entry.setActive(source.active); + entry.setHeldMs(source.heldMs); + inhibitors.append(entry); + } + info.setInhibitors(inhibitors); + + return info; +} + +bool TreelandRemoteSource::activateWindow(qint64 id) +{ + noteActivity(); + auto *surface = findSurfaceById(id); + if (!surface) + return false; + WaylandServer::instance()->forceActivateSurface(surface); + return true; +} + +bool TreelandRemoteSource::closeWindow(qint64 id) +{ + noteActivity(); + auto *surface = findSurfaceById(id); + if (!surface) + return false; + surface->close(); + return true; +} + +bool TreelandRemoteSource::minimizeWindow(qint64 id) +{ + noteActivity(); + auto *surface = findSurfaceById(id); + if (!surface) + return false; + surface->minimize(false); + return true; +} + +bool TreelandRemoteSource::toggleMaximized(qint64 id) +{ + noteActivity(); + auto *surface = findSurfaceById(id); + if (!surface) + return false; + surface->toggleMaximized(); + return true; +} + +bool TreelandRemoteSource::toggleFullscreen(qint64 id) +{ + noteActivity(); + auto *surface = findSurfaceById(id); + if (!surface) + return false; + if (surface->surfaceState() == SurfaceWrapper::State::Fullscreen) + surface->leaveFullscreen(); + else + surface->enterFullscreen(); + return true; +} + +bool TreelandRemoteSource::moveWindow(qint64 id, int x, int y) +{ + noteActivity(); + auto *surface = findSurfaceById(id); + if (!surface) + return false; + surface->moveNormalGeometryInOutput(QPointF(x, y)); + return true; +} + +bool TreelandRemoteSource::resizeWindow(qint64 id, int w, int h) +{ + noteActivity(); + auto *surface = findSurfaceById(id); + if (!surface || w <= 0 || h <= 0) + return false; + return surface->resize(QSizeF(w, h)); +} + +bool TreelandRemoteSource::setWindowWorkspace(qint64 id, int workspaceId) +{ + noteActivity(); + auto *surface = findSurfaceById(id); + if (!surface) + return false; + auto *workspace = WaylandServer::instance()->workspace(); + if (!workspace || !workspace->modelFromId(workspaceId)) + return false; + // moveSurfaceTo() Q_ASSERTs that the surface already belongs to a workspace + // model (workspaceId() != -1); layer-shell surfaces (workspaceId == -1) + // live outside workspaces and must not be moved this way, so reject them + // up front. ShowOnAllWorkspaceId (-2) is fully supported by moveSurfaceTo. + if (surface->workspaceId() == -1) + return false; + workspace->moveSurfaceTo(surface, workspaceId); + return true; +} + +bool TreelandRemoteSource::moveCursor(QPointF pos) +{ + noteActivity(); + auto *server = WaylandServer::instance(); + if (!server) + return false; + // Use the high-level WaylandServer API: it ends any in-progress interactive + // move/resize for every seat before moving the cursor, so injected motion + // is never accidentally fed into an active move/resize transaction. + server->setCursorPosition(pos); + return true; +} + +bool TreelandRemoteSource::sendPointerButton(int button, bool pressed) +{ + noteActivity(); + auto *seat = WaylandServer::instance()->seat(); + if (!seat || !seat->handle()) + return false; + wlr_seat_pointer_notify_button(seat->handle(), QDateTime::currentMSecsSinceEpoch(), + static_cast(button), + pressed ? WL_POINTER_BUTTON_STATE_PRESSED + : WL_POINTER_BUTTON_STATE_RELEASED); + wlr_seat_pointer_notify_frame(seat->handle()); + return true; +} + +bool TreelandRemoteSource::sendKey(int qtKey, bool pressed) +{ + noteActivity(); + auto *seat = WaylandServer::instance()->seat(); + if (!seat || !seat->handle()) + return false; + // Make sure the seat has a keyboard bound so the key event is delivered. + wlr_keyboard *keyboard = nullptr; + if (auto *kbdDevice = seat->keyboardGroupKeyboard()) { + if (kbdDevice->handle() + && kbdDevice->handle()->type == WLR_INPUT_DEVICE_KEYBOARD) { + keyboard = wlr_keyboard_from_input_device(kbdDevice->handle()); + if (keyboard) + wlr_seat_set_keyboard(seat->handle(), keyboard); + } + } + // Convert the portable Qt::Key value to a Linux evdev keycode using the + // keyboard's current xkb keymap. The client sends Qt::Key values (resolved + // from names like "Escape" via QMetaEnum); the evdev conversion lives here + // on the server side where wlr_seat expects evdev codes. + const int evdevCode = qtKeyToEvdev(qtKey, keyboard); + if (evdevCode == 0) + return false; + wlr_seat_keyboard_notify_key(seat->handle(), QDateTime::currentMSecsSinceEpoch(), + static_cast(evdevCode), + pressed ? 1u : 0u); + return true; +} + +void TreelandRemoteSource::captureOutput(QString outputName) +{ + noteActivity(); + auto *root = WaylandServer::instance()->rootSurfaceContainer(); + if (!root) { + Q_EMIT captureResult({}); + return; + } + + WOutputViewport *viewport = nullptr; + if (outputName.isEmpty()) { + // No name given: prefer the primary output, else the first available. + if (auto *primary = root->primaryOutput()) + viewport = primary->screenViewport(); + if (!viewport) { + for (auto *output : root->outputs()) { + if (output && output->screenViewport()) { + viewport = output->screenViewport(); + break; + } + } + } + } else { + for (auto *output : root->outputs()) { + if (!output || !output->screenViewport()) + continue; + if (output->getOutputId() == outputName + || (output->output() && output->output()->name() == outputName)) { + viewport = output->screenViewport(); + break; + } + } + } + if (!viewport) { + Q_EMIT captureResult({}); + return; + } + + // Async texture grab: start the GPU read-back and return immediately. + // The server main thread is never blocked; the encoded PNG bytes are + // delivered via the captureResult signal when the future completes. + auto *capturer = new WTextureCapturer(viewport); + auto *watcher = new QFutureWatcher(this); + connect(watcher, &QFutureWatcher::finished, this, [this, watcher, capturer]() { + const QByteArray bytes = encodeImage(watcher->result()); + capturer->deleteLater(); + watcher->deleteLater(); + Q_EMIT captureResult(bytes); + }); + watcher->setFuture(capturer->grabToImage()); +} + +void TreelandRemoteSource::captureWindow(qint64 id) +{ + noteActivity(); + auto *surface = findSurfaceById(id); + if (!surface || !surface->surfaceItem()) { + Q_EMIT captureResult({}); + return; + } + auto *surfaceItem = surface->surfaceItem(); + // Prefer the surface's own texture-backed content. Some surfaces + // (menus/popups) do not expose a content item via findItemContent(), so + // search the item subtree for any WSurfaceItemContent and grab that. + WSurfaceItemContent *content = surfaceItem->findItemContent(); + if (!content) + content = findContentInSubtree(surfaceItem); + + if (content) { + // Async texture grab — same pattern as captureOutput. + auto *capturer = new WTextureCapturer(content); + auto *watcher = new QFutureWatcher(this); + connect(watcher, &QFutureWatcher::finished, this, [this, watcher, capturer]() { + const QByteArray bytes = encodeImage(watcher->result()); + capturer->deleteLater(); + watcher->deleteLater(); + Q_EMIT captureResult(bytes); + }); + watcher->setFuture(capturer->grabToImage()); + } else { + // Fallback: ask QtQuick to rasterise the whole item subtree into an + // offscreen texture. This is also async — the ready signal fires + // when the render is done. The QSharedPointer keeps the grab result + // alive until the lambda completes. + QSharedPointer grab = surfaceItem->grabToImage(); + if (!grab) { + Q_EMIT captureResult({}); + return; + } + connect(grab.data(), &QQuickItemGrabResult::ready, this, [this, grab]() { + Q_EMIT captureResult(encodeImage(grab->image())); + }); + } +} + +QList TreelandRemoteSource::getEvents(quint64 afterSeq) +{ + noteActivity(); + // A live poller keeps the event filter installed; if no poller calls + // within the idle window the filter is removed and the ring buffer freed, + // so there is zero per-event overhead when nobody is monitoring. + startEventCapture(); + if (!m_eventIdleTimer) { + m_eventIdleTimer = new QTimer(this); + m_eventIdleTimer->setSingleShot(true); + connect(m_eventIdleTimer, &QTimer::timeout, this, [this] { stopEventCapture(); }); + } + constexpr int EventCaptureIdleMs = 5000; + m_eventIdleTimer->start(EventCaptureIdleMs); + + QList result; + for (const auto &e : m_events) { + if (e.seq() > afterSeq) + result.append(e); + } + return result; +} + +qint64 TreelandRemoteSource::focusedWindowId() +{ + noteActivity(); + auto *seat = WaylandServer::instance()->seat(); + if (!seat) return 0; + return surfaceId(seat->keyboardFocusSurface()); +} + +qint64 TreelandRemoteSource::windowUnderCursor() +{ + noteActivity(); + auto *seat = WaylandServer::instance()->seat(); + if (!seat) return 0; + return surfaceId(seat->pointerFocusSurface()); +} + +QString TreelandRemoteSource::getSceneTree(qint64 id) +{ + noteActivity(); + QQuickItem *root = nullptr; + if (id != 0) { + auto *surface = findSurfaceById(id); + if (!surface) + return QStringLiteral("No window with id %1.\n").arg(id); + root = surface->surfaceItem(); + if (!root) + return QStringLiteral("Window %1 has no scene item.\n").arg(id); + } else { + auto *window = WaylandServer::instance() ? WaylandServer::instance()->window() : nullptr; + if (!window) + return QStringLiteral("No render window available.\n"); + root = window->contentItem(); + if (!root) + return QStringLiteral("Render window has no content item.\n"); + } + QString out; + dumpSceneTree(root, 0, out); + if (out.isEmpty()) + return QStringLiteral("(empty scene)\n"); + return out; +} + +void TreelandRemoteSource::startEventCapture() +{ + if (m_eventCaptureActive) + return; + auto *window = WaylandServer::instance() ? WaylandServer::instance()->window() : nullptr; + if (!window) + return; + window->installEventFilter(this); + m_eventCaptureActive = true; + + // Shortcut registrations and triggers are taken from the controller's + // signals: a bound shortcut may swallow the key before it ever reaches the + // render window, so the input filter would miss it. + connect(WaylandServer::instance(), &WaylandServer::desktopChanged, + this, &TreelandRemoteSource::bindShortcutController); + bindShortcutController(); +} + +void TreelandRemoteSource::bindShortcutController() +{ + if (m_shortcutController) { + m_shortcutController->setTriggerTargetProvider({}); + disconnect(m_shortcutController, nullptr, this, nullptr); + } + m_shortcutController = WaylandServer::instance()->shortcutController(); + if (!m_shortcutController) + return; + connect(m_shortcutController, + &ShortcutController::shortcutRegistered, + this, + &TreelandRemoteSource::onShortcutRegistered); + connect(m_shortcutController, + &ShortcutController::shortcutUnregistered, + this, + &TreelandRemoteSource::onShortcutUnregistered); + connect(m_shortcutController, + &ShortcutController::actionTriggered, + this, + &TreelandRemoteSource::onShortcutTriggered); + connect(m_shortcutController, + &ShortcutController::actionFinished, + this, + &TreelandRemoteSource::onShortcutFinished); + // Guarded: the controller outlives this source when remoteDebug is toggled, + // and a provider left installed must not touch a destroyed source. + const QPointer guardedThis(this); + m_shortcutController->setTriggerTargetProvider( + [guardedThis] { return guardedThis ? guardedThis->focusedWindowId() : 0; }); +} + +void TreelandRemoteSource::onShortcutRegistered(const ShortcutController::Binding &binding) +{ + appendEvent(6, 0, QStringLiteral("shortcut registered: ") + shortcutDetail(binding)); +} + +void TreelandRemoteSource::onShortcutUnregistered(const QString &name) +{ + appendEvent(7, 0, QStringLiteral("shortcut unregistered: \"%1\"").arg(sanitizedName(name))); +} + +void TreelandRemoteSource::onShortcutTriggered(ShortcutAction action, + const QString &name, + bool isGesture, + ShortcutController::KeyFlags keyFlags) +{ + // Gestures have no keyboard-focus target (a swipe while the lockscreen is + // up would otherwise blame an unrelated window), so they report 0. For keys + // the target was sampled before the action ran: a workspace/task switch + // would otherwise report the destination window instead of the origin. + const qint64 target = isGesture || !m_shortcutController + ? 0 + : m_shortcutController->lastTriggerTarget(); + const QString trigger = isGesture + ? QStringLiteral(" (gesture)") + : QStringLiteral(" [%1]").arg(shortcutFlagsText(keyFlags)); + appendEvent(8, + target, + QStringLiteral("shortcut triggered: \"%1\" -> %2%3") + .arg(sanitizedName(name), + QString::fromUtf8(ShortcutController::actionName(action)), + trigger)); +} + +void TreelandRemoteSource::onShortcutFinished(ShortcutAction action, + const QString &name, + bool isTriggered) +{ + // Only swipe gestures emit actionFinished(); key and hold triggers arrive + // through actionTriggered(), so there is no double counting. + if (!isTriggered) + return; + appendEvent(8, + 0, + QStringLiteral("shortcut triggered: \"%1\" -> %2 (gesture)") + .arg(sanitizedName(name), + QString::fromUtf8(ShortcutController::actionName(action)))); +} + +void TreelandRemoteSource::stopEventCapture() +{ + if (!m_eventCaptureActive) + return; + if (auto *window = WaylandServer::instance() ? WaylandServer::instance()->window() : nullptr) + window->removeEventFilter(this); + if (auto *server = WaylandServer::instance()) + disconnect(server, &WaylandServer::desktopChanged, + this, &TreelandRemoteSource::bindShortcutController); + if (m_shortcutController) { + m_shortcutController->setTriggerTargetProvider({}); + disconnect(m_shortcutController, nullptr, this, nullptr); + m_shortcutController = nullptr; + } + m_eventCaptureActive = false; + m_events.clear(); // release the ring buffer while idle +} + +void TreelandRemoteSource::appendEvent(int type, qint64 target, const QString &detail) +{ + if (!m_eventCaptureActive) + return; + DebugEvent e; + e.setSeq(m_nextEventSeq++); + e.setType(type); + e.setTarget(target); + e.setDetail(detail); + e.setTimestampMs(static_cast(QDateTime::currentMSecsSinceEpoch())); + m_events.append(e); + if (m_events.size() > MAX_EVENTS) + m_events.removeFirst(); +} + +bool TreelandRemoteSource::eventFilter(QObject *watched, QEvent *event) +{ + Q_UNUSED(watched) + // The filter is installed only while a treeland-debug client is actively + // polling getEvents(). The target surface is read from the seat's current + // focus, so on a focus transition it may reflect the previous event — + // acceptable for a debug stream. + auto *seat = WaylandServer::instance() ? WaylandServer::instance()->seat() : nullptr; + switch (event->type()) { + case QEvent::MouseMove: { + auto *me = static_cast(event); + appendEvent(1, surfaceId(seat ? seat->pointerFocusSurface() : nullptr), + QStringLiteral("motion %1,%2").arg(me->position().x()).arg(me->position().y())); + break; + } + case QEvent::MouseButtonPress: + case QEvent::MouseButtonRelease: { + auto *me = static_cast(event); + appendEvent(2, surfaceId(seat ? seat->pointerFocusSurface() : nullptr), + QStringLiteral("button %1 %2 @%3,%4") + .arg(me->button()) + .arg(event->type() == QEvent::MouseButtonPress ? "press" : "release") + .arg(me->position().x()).arg(me->position().y())); + break; + } + case QEvent::KeyPress: + case QEvent::KeyRelease: { + auto *ke = static_cast(event); + appendEvent(3, surfaceId(seat ? seat->keyboardFocusSurface() : nullptr), + QStringLiteral("key %1 %2") + .arg(ke->key()) + .arg(event->type() == QEvent::KeyPress ? "press" : "release")); + break; + } + default: + break; + } + return false; // never consume — only observe +} diff --git a/src/modules/resource/treelandremotesource.h b/src/modules/resource/treelandremotesource.h new file mode 100644 index 0000000000..71fc5c0ed4 --- /dev/null +++ b/src/modules/resource/treelandremotesource.h @@ -0,0 +1,170 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "modules/shortcut/shortcutcontroller.h" +#include "rep_treelandwindowtree_source.h" +#include "treelanddebugsocket.h" + + +#include +#include +#include + +class SurfaceWrapper; +class SurfaceContainer; +class WorkspaceModel; + +class TreelandRemoteSource : public WindowTreeRemoteSource +{ + Q_OBJECT + +public: + explicit TreelandRemoteSource(QObject *parent = nullptr); + ~TreelandRemoteSource() override; + + // False when construction gave up (no free socket name, bind or chmod + // failed, or the source could not be published), which lets the caller + // discard the object and retry later instead of caching a dead one. + bool isPublished() const { return m_published; } + + QPointF cursorPosition() const override; + TreelandInfo getTreelandInfo() override; + + // ---- access ---- + // The Release no-auth window opens the debug socket to every local user for + // 30 minutes; every later remote call extends it. Only a caller that already + // passed the sealed socket can ask, and in a release build that is root alone: + // mode 0000 blocks the compositor's own user too, only CAP_DAC_OVERRIDE passes. + bool requestNoAuth() override; + + // ---- inspection ---- + QList getWindows() override; + QList getClients() override; + IdleInfo getIdleInfo() override; + + // ---- window control ---- + bool activateWindow(qint64 id) override; + bool closeWindow(qint64 id) override; + bool minimizeWindow(qint64 id) override; + bool toggleMaximized(qint64 id) override; + bool toggleFullscreen(qint64 id) override; + bool moveWindow(qint64 id, int x, int y) override; + bool resizeWindow(qint64 id, int w, int h) override; + bool setWindowWorkspace(qint64 id, int workspaceId) override; + + // ---- input / event injection ---- + bool moveCursor(QPointF pos) override; + bool sendPointerButton(int button, bool pressed) override; + bool sendKey(int qtKey, bool pressed) override; + + // ---- image capture (asynchronous) ---- + // Starts an async grab; the encoded PNG bytes are delivered via the + // captureResult signal. The compositor main thread is never blocked. + void captureOutput(QString outputName) override; + void captureWindow(qint64 id) override; + + // ---- real-time monitoring ---- + QList getEvents(quint64 afterSeq) override; + // ---- shortcut registry ---- + QList getShortcuts() override; + qint64 focusedWindowId() override; + qint64 windowUnderCursor() override; + // ---- QtQuick scene inspection ---- + // Dumps the QQuickItem hierarchy of a window (id != 0) or the whole + // render window (id == 0) as a pre-formatted text tree. + QString getSceneTree(qint64 id) override; + +protected: + // Observes input events delivered to the render window. Installed lazily + // only while a treeland-debug client is actively polling getEvents(), so + // there is zero per-event overhead when nobody is monitoring. + bool eventFilter(QObject *watched, QEvent *event) override; + +private Q_SLOTS: + void bindShortcutController(); + // Feed the shortcut registration/trigger stream into the event ring + // buffer while capture is armed. + void onShortcutRegistered(const ShortcutController::Binding &binding); + void onShortcutUnregistered(const QString &name); + void onShortcutTriggered(ShortcutAction action, const QString &name, bool isGesture, + ShortcutController::KeyFlags keyFlags); + // Swipe gestures report only actionFinished() — never actionTriggered(). + void onShortcutFinished(ShortcutAction action, const QString &name, bool isTriggered); + +private: + void collectSurfaceInfos(QList &infos, + SurfaceWrapper *surface, + int layer, + const QString &containerName, + int z) const; + void collectWorkspaceModelWindows(QList &infos, + WorkspaceModel *workspaceModel, + int layer, + const QString &containerName) const; + void collectCurrentWorkspaceModelWindows(QList &infos, + WorkspaceModel *workspaceModel, + int layer, + const QString &containerName) const; + WindowInfo buildWindowInfo(SurfaceWrapper *surface, + int layer, + const QString &containerName, + int z) const; + LayerInfo buildLayerInfo(SurfaceContainer *container) const; + + // Collects every toplevel SurfaceWrapper (no parent surface) reachable from + // the root container, in a stable display order. Used by the flat window + // list, the client grouping and the id -> surface lookup. + void collectAllToplevelSurfaces(QList &out) const; + + // Resolves a surface id (the wl_surface wl_resource id) to a live + // SurfaceWrapper, or nullptr if no current surface matches. + SurfaceWrapper *findSurfaceById(qint64 id) const; + + // Starts/stops capturing input events into m_events. Capturing is gated on + // a live treeland-debug poller: it is armed on every getEvents() call and + // torn down after a short idle interval, guaranteeing no overhead when no + // client is connected. + void startEventCapture(); + void stopEventCapture(); + void appendEvent(int type, qint64 target, const QString &detail); + + // Closes the no-auth window: the timer expired, or the source is being torn + // down. Idempotent -- a closed socket and a 0700 directory are the target + // state, not a transition. Rebinding the host is what revokes the + // connections a peer opened while the window was open. + void closeNoAuthWindow(); + // Binds the debug socket and publishes WindowTree on it. Used by the + // constructor and by closeNoAuthWindow() when it has to drop peers. + bool bindHost(const QString &socketPath); + // Called by every remote method: a call is what keeps no-auth mode alive. + void noteActivity() const; + + // Event ring buffer for real-time monitoring; populated only while a client + // is actively polling getEvents(). + QList m_events; + quint64 m_nextEventSeq = 1; + static constexpr int MAX_EVENTS = 2000; + bool m_eventCaptureActive = false; + QTimer *m_eventIdleTimer = nullptr; + // Controller whose shortcut signals feed the event ring buffer while + // capture is armed (null when capture is off). Guarded: the source can + // outlive the manager's controller when remoteDebug is toggled. + QPointer m_shortcutController; + // Held for the lifetime of the QRemoteObjectHost so the socket name + // claimed in the constructor stays ours (Wayland-style flock lock file, + // see TreelandDebugSocketLock). + TreelandDebugSocketLock m_debugSocketLock; + QString m_debugSocketPath; + // Release builds are the only ones that restrict the socket, so they are + // also the only ones the access policy has to touch. + bool m_socketRootOnly = false; + // Turns no-auth mode off after a call-free window, so a forgotten request + // cannot leave the debug channel open. + QTimer *m_noAuthIdleTimer = nullptr; + // True while the socket is open to every local user, so the teardown knows + // whether peers may be holding a connection that has to be revoked. + bool m_noAuthWindowOpen = false; + bool m_published = false; +}; diff --git a/src/modules/resource/treelandwindowtree.rep b/src/modules/resource/treelandwindowtree.rep new file mode 100644 index 0000000000..5b1a7941a1 --- /dev/null +++ b/src/modules/resource/treelandwindowtree.rep @@ -0,0 +1,184 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include +#include +#include + +POD WindowInfo( + qint64 id, + QString appId, + QString title, + QString output, + QString container, + int workspace, + int layer, + int z, + int type, + int state, + bool visible, + bool active, + bool minimized, + QRectF geometry, + QRectF titlebarGeometry, + QRectF boundingRect, + QRectF iconGeometry, + QPointF position, + qint64 frames, + QRectF damage, + // Every output the window is on, and the output driving its frame + // callbacks: the entered output with the highest refresh rate, the first + // entered one on a tie. + QList outputs, + QString framePacingOutput, + // Why the window is on no output at all. lastLeave fields: the most recent + // leave caused by an output recompute, its output name, whether that output + // was enabled then, and whether the surface was left without outputs. + // lastOutputsUpdate fields: the last updateSurfaceOutputs call, its trigger + // -- geometryChanged, surfaceAdded, addOutput or enabledChanged -- how many + // outputs the compositor had enabled vs total in its output model then, the + // size of the list handed to setOutputs, and positionAutomatic at that + // moment. Total counts output model entries: a mirrored screen is two of + // them, not two connectors. The bools have no never-happened value, so read + // an empty lastLeaveOutput or lastOutputsUpdateReason as nothing recorded. + QString lastLeaveOutput, + bool lastLeaveOutputEnabled, + bool lastLeaveEmptiedOutputs, + QString lastOutputsUpdateReason, + int lastOutputsUpdateEnabled, + int lastOutputsUpdateTotal, + int lastOutputsUpdateComputed, + bool lastOutputsUpdateAutomatic, + // Input and opaque regions of the wlr_surface, in surface-local + // coordinates. + QRegion inputRegion, + QRegion opaqueRegion +) + +POD WorkspaceInfo( + int id, + bool isActive, + QList windows +) + +POD LayerInfo( + QString name, + int layer, + QList windows, // normal layer + QList workspaces // if is workspace +) + +POD TreelandInfo( + QString currentMode, + QList layers +) + +// A connected Wayland client (pid 0 when not available) together with the +// toplevel windows it owns. Used by the ``treeland-debug top`` / ``clients`` +// commands to present an adb-style overview of the compositor state. +POD ClientInfo( + qint64 id, + QString appId, + int pid, + QString executable, + QString command, + QList windows +) + +// A registered shortcut (key binding or touchpad gesture), as reported by +// the compositor's shortcut manager. `type`: 0=key 1=swipe 2=hold. `key` is the +// portable-text key sequence for key bindings (empty for gestures), `flags` the +// keybind flag mask (1=press 2=release 4=repeat), and `fingers`/`direction` +// describe gestures. +POD ShortcutInfo( + QString name, + int type, + QString key, + uint flags, + QString action, + uint fingers, + QString direction +) + +// Real-time debug event: input events, window state changes, etc. +// type: 1=pointerMotion 2=pointerButton 3=keyboardKey 4=focusChanged 5=cursorWindowChanged +// 6=shortcutRegistered 7=shortcutUnregistered 8=shortcutTriggered +POD DebugEvent( + quint64 seq, + int type, + qint64 target, // target window id, 0 = desktop / no target + QString detail, // human-readable description + quint64 timestampMs +) + +// Idle state and one idle-inhibit source, used by the ``treeland-debug idle`` +// command. kind is "idle-inhibit" (zwp_idle_inhibit_manager_v1 surface; +// surfaceId/title/heldMs identify it) or "screensaver" +// (treeland_screensaver_v2 inhibit; appName/reason are the client-provided +// strings). active means this source alone counts as inhibiting right now. +POD IdleInhibitor( + qint64 surfaceId, + QString kind, + QString appId, + QString title, + int pid, + QString executable, + QString command, + QString appName, + QString reason, + bool active, + quint64 heldMs +) + +// Snapshot of the compositor idle state. idleMs is the time since the last +// input activity on any seat; inhibited is whether idle notification is +// currently suppressed (by any source below, or by the screensaver). +POD IdleInfo( + bool inhibited, + bool screensaverInhibited, + quint64 idleMs, + QList inhibitors +) + +class WindowTreeRemote { + // Release no-auth opens the debug socket to every local user for 30 minutes, + // extended by each remote call; closing the window also closes connections + // opened during it. Only a caller that already passed the socket can request + // it, and in a Release build that is root alone (mode 0000 blocks the + // compositor's own user too; only CAP_DAC_OVERRIDE passes), so the sealed + // socket is the authentication. Returns false when the directory is not one + // Treeland may widen (a session instance). + SLOT(bool requestNoAuth()); + SLOT(TreelandInfo getTreelandInfo()); + SLOT(QList getWindows()); + SLOT(QList getClients()); + SLOT(IdleInfo getIdleInfo()); + SLOT(QList getShortcuts()); + SLOT(bool activateWindow(qint64 id)); + SLOT(bool closeWindow(qint64 id)); + SLOT(bool minimizeWindow(qint64 id)); + SLOT(bool toggleMaximized(qint64 id)); + SLOT(bool toggleFullscreen(qint64 id)); + SLOT(bool moveWindow(qint64 id, int x, int y)); + SLOT(bool resizeWindow(qint64 id, int w, int h)); + SLOT(bool setWindowWorkspace(qint64 id, int workspaceId)); + SLOT(bool moveCursor(QPointF pos)); + SLOT(bool sendPointerButton(int button, bool pressed)); + SLOT(bool sendKey(int qtKey, bool pressed)); // qtKey = Qt::Key enum value; server converts to evdev + // Image capture is asynchronous: the compositor starts the grab and + // returns immediately; the encoded PNG bytes are delivered via the + // captureResult signal. This avoids blocking the compositor main thread + // on GPU read-back. + SLOT(void captureOutput(QString outputName)); + SLOT(void captureWindow(qint64 id)); + SIGNAL(captureResult(QByteArray data)); + SLOT(QList getEvents(quint64 afterSeq)); + SLOT(qint64 focusedWindowId()); + SLOT(qint64 windowUnderCursor()); + // Dumps the underlying QtQuick scene tree (QQuickItem hierarchy) for a + // window (id != 0) or the whole render window (id == 0) as a pre-formatted + // text tree: className / objectName / geometry / visible / opacity. + SLOT(QString getSceneTree(qint64 id)); + PROP(QPointF cursorPosition READONLY) +}; diff --git a/src/modules/screensaver/CMakeLists.txt b/src/modules/screensaver/CMakeLists.txt new file mode 100644 index 0000000000..474389cca7 --- /dev/null +++ b/src/modules/screensaver/CMakeLists.txt @@ -0,0 +1,16 @@ +find_package(TreelandProtocols 0.6.0 REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-screensaver-unstable-v2.xml + BASENAME treeland-screensaver-unstable-v2 +) + +impl_treeland( + NAME + module_screensaver + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/screensaver/screensaverinterfacev2.h + ${CMAKE_SOURCE_DIR}/src/modules/screensaver/screensaverinterfacev2.cpp + INCLUDE + $ +) diff --git a/src/modules/screensaver/screensaverinterfacev2.cpp b/src/modules/screensaver/screensaverinterfacev2.cpp new file mode 100644 index 0000000000..ddb345e1a6 --- /dev/null +++ b/src/modules/screensaver/screensaverinterfacev2.cpp @@ -0,0 +1,159 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "screensaverinterfacev2.h" +#include "qwayland-server-treeland-screensaver-unstable-v2.h" +#include "core/waylandserver.h" + +#include + +#include +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class ScreensaverInterfaceV2Private : public QtWaylandServer::treeland_screensaver_v2 +{ +public: + explicit ScreensaverInterfaceV2Private(ScreensaverInterfaceV2 *_q); + wl_global *global() const; + + struct InhibitEntry { + QString applicationName; + QString reason; + QElapsedTimer age; + }; + + ScreensaverInterfaceV2 *q = nullptr; + QHash inhibits; +protected: + void inhibit(Resource *resource, const QString &application_name, const QString &reason_for_inhibit) override; + void uninhibit(Resource *resource) override; + void destroy(Resource *resource) override; + void destroy_resource(Resource *resource) override; +}; + +ScreensaverInterfaceV2Private::ScreensaverInterfaceV2Private(ScreensaverInterfaceV2 *_q) + : QtWaylandServer::treeland_screensaver_v2() + , q(_q) +{ +} + +wl_global *ScreensaverInterfaceV2Private::global() const +{ + return m_global; +} + +// WaylandServer clears its singleton before the remaining clients are torn +// down, so an inhibit change arriving during shutdown must not dereference it. +static void updateIdleInhibitor() +{ + if (auto *server = WaylandServer::instance()) + server->updateIdleInhibitor(); +} + +void ScreensaverInterfaceV2Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void ScreensaverInterfaceV2Private::destroy_resource(Resource *resource) +{ + // The only hook that runs for every Resource destruction -- the destroy + // request above, but also a client disconnect or crash. Release any + // active inhibit silently (the protocol says disconnect auto-releases + // it). Do NOT call uninhibit() here, which would post NOT_YET_INHIBITED + // when the client already uninhibited before destroying the object. + if (inhibits.remove(resource->handle)) + updateIdleInhibitor(); +} + +void ScreensaverInterfaceV2Private::inhibit(Resource *resource, const QString &application_name, const QString &reason_for_inhibit) +{ + wl_resource *res = resource->handle; + if (inhibits.contains(res)) { + wl_resource_post_error(res, TREELAND_SCREENSAVER_V2_ERROR_ALREADY_INHIBITED, + "Trying to inhibit with an existing inhibit active"); + return; + } + + InhibitEntry entry; + entry.applicationName = application_name; + entry.reason = reason_for_inhibit; + entry.age.start(); + inhibits.insert(res, entry); + updateIdleInhibitor(); +} + +void ScreensaverInterfaceV2Private::uninhibit(Resource *resource) +{ + wl_resource *res = resource->handle; + if (!inhibits.contains(res)) { + wl_resource_post_error(res, TREELAND_SCREENSAVER_V2_ERROR_NOT_YET_INHIBITED, + "Trying to uninhibit but no active inhibit existed"); + return; + } + + inhibits.remove(res); + updateIdleInhibitor(); +} + +ScreensaverInterfaceV2::ScreensaverInterfaceV2(QObject *parent) + : QObject(parent) + , WServerInterface() + , d(new ScreensaverInterfaceV2Private(this)) +{ +} + +ScreensaverInterfaceV2::~ScreensaverInterfaceV2() = default; + +QByteArrayView ScreensaverInterfaceV2::interfaceName() const +{ + return d->interfaceName(); +} + +bool ScreensaverInterfaceV2::isInhibited() const +{ + return !d->inhibits.isEmpty(); +} + +QList ScreensaverInterfaceV2::inhibits() const +{ + QList result; + result.reserve(d->inhibits.size()); + + for (auto it = d->inhibits.constBegin(); it != d->inhibits.constEnd(); ++it) { + InhibitInfo info; + info.applicationName = it.value().applicationName; + info.reason = it.value().reason; + info.heldMs = static_cast(it.value().age.isValid() ? it.value().age.elapsed() : 0); + + if (auto *client = wl_resource_get_client(it.key())) { + if (auto *wclient = WClient::get(client)) + info.appId = QString::fromUtf8(wclient->appId()); + if (auto creds = WClient::getCredentials(client)) + info.pid = creds->pid; + } + result.append(info); + } + + return result; +} + +void ScreensaverInterfaceV2::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void ScreensaverInterfaceV2::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *ScreensaverInterfaceV2::global() const +{ + return d->global(); +} diff --git a/src/modules/screensaver/screensaverinterfacev2.h b/src/modules/screensaver/screensaverinterfacev2.h new file mode 100644 index 0000000000..2d82a1acd3 --- /dev/null +++ b/src/modules/screensaver/screensaverinterfacev2.h @@ -0,0 +1,40 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wserver.h" + +WAYLIB_SERVER_USE_NAMESPACE + +class ScreensaverInterfaceV2Private; +class ScreensaverInterfaceV2 : public QObject , public WServerInterface +{ + Q_OBJECT +public: + explicit ScreensaverInterfaceV2(QObject *parent = nullptr); + ~ScreensaverInterfaceV2() override; + + QByteArrayView interfaceName() const override; + bool isInhibited() const; + + // One active treeland_screensaver_v2 inhibit: the client-provided + // application name / reason, the owning client identity and how long the + // inhibit has been held. Consumed by the treeland-debug ``idle`` command. + struct InhibitInfo { + QString applicationName; + QString reason; + QString appId; + int pid = 0; + quint64 heldMs = 0; + }; + QList inhibits() const; + + static constexpr int InterfaceVersion = 1; + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; diff --git a/src/modules/shortcut/CMakeLists.txt b/src/modules/shortcut/CMakeLists.txt new file mode 100644 index 0000000000..c489620d3f --- /dev/null +++ b/src/modules/shortcut/CMakeLists.txt @@ -0,0 +1,26 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-shortcut-manager-unstable-v3.xml + BASENAME treeland-shortcut-manager-unstable-v3 +) + +impl_treeland( + NAME + module_shortcut + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/shortcut/shortcutmanager.h + ${CMAKE_SOURCE_DIR}/src/modules/shortcut/shortcutmanager.cpp + ${CMAKE_SOURCE_DIR}/src/modules/shortcut/shortcutrunner.h + ${CMAKE_SOURCE_DIR}/src/modules/shortcut/shortcutrunner.cpp + ${CMAKE_SOURCE_DIR}/src/modules/shortcut/shortcutcontroller.h + ${CMAKE_SOURCE_DIR}/src/modules/shortcut/shortcutcontroller.cpp + INCLUDE + $ + LINK + Wlroots::wlroots + Waylib::WaylibServer + Qt6::Core + Qt6::Gui + Qt6::Quick +) diff --git a/src/modules/shortcut/shortcutcontroller.cpp b/src/modules/shortcut/shortcutcontroller.cpp new file mode 100644 index 0000000000..e25acd1f06 --- /dev/null +++ b/src/modules/shortcut/shortcutcontroller.cpp @@ -0,0 +1,466 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "shortcutcontroller.h" + +#include "qwayland-server-treeland-shortcut-manager-unstable-v3.h" + +#include "common/treelandlogging.h" +#include "input/gesturemanager.h" +#include "input/swipegesture.h" + +#include +#include +#include +#include + +static_assert( + static_cast(ShortcutController::KeyPress) == + QtWaylandServer::treeland_shortcut_manager_v3:: + keybind_flag_key_press && + static_cast(ShortcutController::KeyRelease) == + QtWaylandServer::treeland_shortcut_manager_v3:: + keybind_flag_key_release && + static_cast(ShortcutController::Repeat) == + QtWaylandServer::treeland_shortcut_manager_v3::keybind_flag_repeat, + "treeland-shortcut-manager-v3: protocol's keybind_flag disagree with " + "Treeland in value"); + +using BindError = QtWaylandServer::treeland_shortcut_manager_v3::bind_error; + +ShortcutController::ShortcutController(QObject *parent, GestureManager *gestures) + : QObject(parent) + , m_gestureManager(gestures ? gestures : new GestureManager(this)) +{ +} + +ShortcutController::~ShortcutController() +{ + m_destroying = true; + clear(); +} + +const char *ShortcutController::actionName(ShortcutAction action) +{ + const auto meta = QMetaEnum::fromType(); + const char *key = meta.valueToKey(static_cast(action)); + return key ? key : "Unknown"; +} + +void ShortcutController::unregisterKey(int combined, ShortcutAction action) +{ + auto entry = m_keyMap.find(combined); + if (entry == m_keyMap.end()) + return; + + entry->remove(action); + // An emptied key combination must not stay in the map: matchesShortcut() + // reads the map keys, so a stale entry would still match the event. + if (entry->isEmpty()) + m_keyMap.erase(entry); + m_actionCombinedMap.remove(action); +} + +uint ShortcutController::registerKey(const QString &name, const QString& key, ShortcutController::KeyFlags keybindFlags, ShortcutAction action) +{ + const int combined = normalizedKeyCombinedFor(key); + if (combined == 0) { + return BindError::bind_error_invalid_argument; + } + auto keyComb = QKeyCombination::fromCombined(combined); + if (!isValidShortcutCombination(keyComb)) { + return BindError::bind_error_invalid_argument; + } + + if (keybindFlags & ~ShortcutController::KeyFlag::All) { + return BindError::bind_error_invalid_argument; + } + + auto &entry = m_keyMap[combined]; + // Per the v3 protocol, bind_key upserts when the same key sequence and + // action already exists (updating its flags) instead of failing. Re-binding + // the same name to the same trigger is therefore an in-place flag update, + // not a name_conflict; name_conflict only applies when the name is already + // used by a different key+action binding. + if (entry.contains(action)) { + const auto &[prevName, flags] = entry[action]; + if (name != prevName && m_deleters.contains(name)) { + return BindError::bind_error_name_conflict; + } + m_deleters.remove(prevName); + if (prevName != name) + Q_EMIT shortcutUnregistered(prevName); + qCInfo(lcTlShortcut).noquote() << "Overriding existing key binding of" + << keyComb << "for action" << actionName(action) + << "by name" << prevName << "with new name" << name << "and flags" << keybindFlags; + } else if (m_deleters.contains(name)) { + return BindError::bind_error_name_conflict; + } + m_keyMap[combined][action] = std::make_pair(name, keybindFlags); + m_actionCombinedMap[action] = combined; + m_deleters[name] = [this, combined, action]() { unregisterKey(combined, action); }; + if (lcTlShortcut().isInfoEnabled()) { + QStringList flagNames; + if (keybindFlags.testFlag(ShortcutController::KeyPress)) flagNames << "KeyPress"; + if (keybindFlags.testFlag(ShortcutController::KeyRelease)) flagNames << "KeyRelease"; + if (keybindFlags.testFlag(ShortcutController::Repeat)) flagNames << "Repeat"; + if (flagNames.isEmpty()) flagNames << "None"; + qCInfo(lcTlShortcut).noquote() << "register shortcut:" << key << "->" << name + << "flags:" << flagNames.join('|'); + } + Q_EMIT shortcutRegistered(Binding{Binding::Key, + name, + QKeySequence(keyComb).toString(QKeySequence::PortableText), + keybindFlags, + action}); + return 0; +} + +uint ShortcutController::registerSwipeGesture(const QString &name, uint finger, SwipeGesture::Direction direction, ShortcutAction action) +{ + if (m_deleters.contains(name)) { + return BindError::bind_error_name_conflict; + } + + if (direction == SwipeGesture::Direction::Invalid || finger == 0) { + return BindError::bind_error_invalid_argument; + } + + auto gestureKey = std::make_pair(finger, direction); + + if (!m_gestures.contains(gestureKey)) { + auto gesture = m_gestureManager->registerTouchpadSwipe( + SwipeFeedBack { + direction, + finger, + [this, gestureKey](bool triggered) { + for (const auto& [act, nm] : std::as_const(m_gesturemap[gestureKey]).asKeyValueRange()) { + Q_EMIT actionFinished(act, nm, triggered); + } + }, + [this, gestureKey](qreal progress) { + for (const auto& [act, nm] : std::as_const(m_gesturemap[gestureKey]).asKeyValueRange()) { + Q_EMIT actionProgress(act, progress, nm); + } + } + }); + + if (!gesture) { + return BindError::bind_error_internal_error; + } + + m_gestures[gestureKey] = gesture; + } + + auto &entry = m_gesturemap[gestureKey]; + + if (entry.contains(action)) { + return BindError::bind_error_duplicate_binding; + } + + entry.insert(action, name); + m_deleters[name] = [this, gestureKey, action]() { + auto &entry = m_gesturemap[gestureKey]; + entry.remove(action); + if (entry.isEmpty()) { + auto gesture = qobject_cast(m_gestures.take(gestureKey)); + if (gesture) { + m_gestureManager->unregisterTouchpadSwipe(gesture); + } + } + }; + + if (lcTlShortcut().isInfoEnabled()) { + static const char *dirNames[] = {"Invalid", "Down", "Left", "Up", "Right"}; + qCInfo(lcTlShortcut).noquote() << "register swipe gesture:" << name + << "finger:" << finger + << "direction:" << dirNames[direction] + << "action:" << actionName(action); + } + Q_EMIT shortcutRegistered( + Binding{Binding::Swipe, name, {}, {}, action, finger, direction}); + return 0; +} + +uint ShortcutController::registerHoldGesture(const QString &name, uint finger, ShortcutAction action) +{ + if (m_deleters.contains(name)) { + return BindError::bind_error_name_conflict; + } + + if (finger == 0) { + return BindError::bind_error_invalid_argument; + } + + auto gestureKey = std::make_pair(finger, SwipeGesture::Direction::Invalid); + + if (!m_gestures.contains(gestureKey)) { + auto gesture = m_gestureManager->registerTouchpadHold( + HoldFeedBack { + finger, + nullptr, + [this, gestureKey]() { + for (const auto& [act, nm] : std::as_const(m_gesturemap[gestureKey]).asKeyValueRange()) { + Q_EMIT actionTriggered(act, nm, true); + } + } + }); + + if (!gesture) { + return BindError::bind_error_internal_error; + } + + m_gestures[gestureKey] = gesture; + } + + auto &entry = m_gesturemap[gestureKey]; + + if (entry.contains(action)) { + return BindError::bind_error_duplicate_binding; + } + + entry.insert(action, name); + m_deleters[name] = [this, gestureKey, action]() { + auto &entry = m_gesturemap[gestureKey]; + entry.remove(action); + if (entry.isEmpty()) { + auto gesture = qobject_cast(m_gestures.take(gestureKey)); + if (gesture) { + m_gestureManager->unregisterTouchpadHold(gesture); + } + } + }; + + if (lcTlShortcut().isInfoEnabled()) { + qCInfo(lcTlShortcut).noquote() << "register hold gesture:" << name + << "finger:" << finger + << "action:" << actionName(action); + } + Q_EMIT shortcutRegistered(Binding{Binding::Hold, + name, + {}, + {}, + action, + finger, + SwipeGesture::Direction::Invalid}); + return 0; +} + +void ShortcutController::setTriggerTargetProvider(TriggerTargetProvider provider) +{ + m_triggerTargetProvider = std::move(provider); +} + +void ShortcutController::unregisterShortcut(const QString &name) +{ + if (m_deleters.contains(name)) { + m_deleters.take(name)(); + Q_EMIT shortcutUnregistered(name); + } +} + +QList ShortcutController::bindings() const +{ + QList result; + for (const auto &[combined, actions] : m_keyMap.asKeyValueRange()) { + for (const auto &[action, entry] : actions.asKeyValueRange()) { + const auto &[name, flags] = entry; + result.append(Binding{Binding::Key, + name, + QKeySequence(QKeyCombination::fromCombined(combined)) + .toString(QKeySequence::PortableText), + flags, + action}); + } + } + for (const auto &[gestureKey, actions] : m_gesturemap.asKeyValueRange()) { + const auto &[finger, direction] = gestureKey; + for (const auto &[action, name] : actions.asKeyValueRange()) { + result.append(Binding{direction == SwipeGesture::Direction::Invalid ? Binding::Hold + : Binding::Swipe, + name, + {}, + {}, + action, + finger, + direction}); + } + } + return result; +} + +bool ShortcutController::matchesShortcut(const QKeyEvent *event) const +{ + return m_keyMap.contains(normalizeKeyCombination(event->keyCombination()).toCombined()); +} + +bool ShortcutController::dispatchKeyEvent(const QKeyEvent *kevent) +{ + auto combined = normalizeKeyCombination(kevent->keyCombination()).toCombined(); + ShortcutController::KeyFlags keyFlags = (kevent->isAutoRepeat() ? ShortcutController::Repeat : ShortcutController::None) + | (kevent->type() == QEvent::KeyPress ? ShortcutController::KeyPress : ShortcutController::None) + | (kevent->type() == QEvent::KeyRelease ? ShortcutController::KeyRelease : ShortcutController::None); + + bool matched = matchesShortcut(kevent); + if (matched) { + qCInfo(lcTlShortcut).noquote() + << "shortcut match:" << QKeySequence(kevent->keyCombination()).toString(QKeySequence::PortableText) + << (kevent->type() == QEvent::KeyPress ? "press" : "release") + << (kevent->isAutoRepeat() ? "repeat" : ""); + } + if (!matched) + return false; + + // Sample the focus before emitting: the action may switch workspaces or + // tasks and move the keyboard focus away from the origin window. + m_lastTriggerTarget = m_triggerTargetProvider ? m_triggerTargetProvider() : 0; + + for (const auto &[action, keybind] : std::as_const(m_keyMap[combined]).asKeyValueRange()) { + const auto& [name, bindFlags] = keybind; + // Match if the event flags are a subset of the binding flags. + // Each shortcut's behavior is determined by its registration flags: + // KeyPress-only → triggers on press, + // KeyRelease-only → triggers on release, + // Both → triggers on both. + if ((bindFlags & keyFlags) != keyFlags) { + continue; + } + Q_EMIT actionTriggered(action, name, false, keyFlags); + } + return true; +} + +Qt::KeyboardModifiers ShortcutController::modifierForAction(ShortcutAction action) const +{ + auto it = m_actionCombinedMap.find(action); + if (it != m_actionCombinedMap.end()) { + return QKeyCombination::fromCombined(it.value()).keyboardModifiers() + & (Qt::AltModifier | Qt::MetaModifier | Qt::ControlModifier | Qt::ShiftModifier); + } + return Qt::NoModifier; +} + +void ShortcutController::clear() +{ + for (const auto& [name, deleter] : m_deleters.asKeyValueRange()) { + deleter(); + // Dropping the whole registry (session switch) must be visible in the + // registration stream too, otherwise old bindings look permanently + // registered. Skip while destructing: receivers may already be gone. + if (!m_destroying) + Q_EMIT shortcutUnregistered(name); + } + m_deleters.clear(); + m_actionCombinedMap.clear(); +} + +int ShortcutController::normalizedKeyCombinedFor(const QString &key) +{ + // For all-modifier bindings: Ctrl is a valid modifier but not a valid key. + const auto seq = QKeySequence::fromString(key.endsWith("+Ctrl") ? key + "+Control" : key, + QKeySequence::PortableText); + if (seq.count() != 1) + return 0; + return normalizeKeyCombination(seq[0]).toCombined(); +} + +QKeyCombination ShortcutController::normalizeKeyCombination(QKeyCombination combination) { + Qt::KeyboardModifiers mods = combination.keyboardModifiers(); + Qt::Key key = combination.key(), nornalizedKey = Qt::Key_unknown; + + switch (key) { + case Qt::Key_Control: + mods |= Qt::ControlModifier; + break; + case Qt::Key_Shift: + mods |= Qt::ShiftModifier; + break; + case Qt::Key_Alt: + mods |= Qt::AltModifier; + break; + case Qt::Key_Meta: + case Qt::Key_Super_L: + case Qt::Key_Super_R: + mods |= Qt::MetaModifier; + break; + case Qt::Key_Backtab: + // Shift+Tab's keysym is ISO_Left_Tab; Qt's QXkbCommon::keysymToQtKey() + // (waylib only forwards the event) turns it into Key_Backtab, while + // bindings spell the combination "Shift+Tab". Fold both to one + // identity so such shortcuts can match. + mods |= Qt::ShiftModifier; + nornalizedKey = Qt::Key_Tab; + break; + default: + nornalizedKey = key; + break; + } + + return QKeyCombination(mods, nornalizedKey); +} + + +// Decide whether a normalized (modifiers + key) combination is accepted as a +// valid shortcut. Mirrors dde-daemon's IsGood()/isGoodNoMods()/isGoodModShift(). +bool ShortcutController::isValidShortcutCombination(QKeyCombination combination) +{ + const auto normalized = normalizeKeyCombination(combination); + const Qt::KeyboardModifiers mods = normalized.keyboardModifiers() + & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier | Qt::ShiftModifier); + const Qt::Key key = normalized.key(); + + // Modifier-only combinations: only Meta is accepted as a standalone shortcut. + if (key == Qt::Key_unknown) + return mods == Qt::MetaModifier; + + // Rule 1: Ctrl / Alt / Meta + any non-modifier key. + if (mods & (Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier)) + return true; + + // Rule 2: Function keys. + if (key >= Qt::Key_F1 && key <= Qt::Key_F35) + return true; + + // Rule 3: Misc function keys. + switch (key) { + case Qt::Key_Delete: + case Qt::Key_Backspace: + case Qt::Key_Pause: + case Qt::Key_Print: + case Qt::Key_Insert: + case Qt::Key_Help: + case Qt::Key_Menu: + case Qt::Key_Cancel: + return true; + default: + break; + } + + // Rule 4: Shift + selected special/navigation keys. + if (mods == Qt::ShiftModifier) { + switch (key) { + case Qt::Key_Space: + case Qt::Key_Escape: + case Qt::Key_Tab: + return true; + default: + break; + } + + if ((key >= Qt::Key_Home && key <= Qt::Key_PageDown) + || (key >= Qt::Key_Left && key <= Qt::Key_Down)) + return true; + } + + // Rule 5: Media / browser / hardware keys without modifiers. + if (mods == Qt::NoModifier) { + if (key >= Qt::Key_Back && key <= Qt::Key_KeyboardBrightnessDown) + return true; + if (key >= Qt::Key_LaunchMail && key <= Qt::Key_Launch9) + return true; + if (key >= Qt::Key_MediaPlay && key <= Qt::Key_MediaLast) + return true; + } + + return false; +} diff --git a/src/modules/shortcut/shortcutcontroller.h b/src/modules/shortcut/shortcutcontroller.h new file mode 100644 index 0000000000..79ca466e79 --- /dev/null +++ b/src/modules/shortcut/shortcutcontroller.h @@ -0,0 +1,156 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "input/swipegesture.h" +#include "modules/shortcut/qwayland-server-treeland-shortcut-manager-unstable-v3.h" + +#include +#include + +class Gesture; +class QKeyEvent; + +class GestureManager; + +class ShortcutController : public QObject +{ + Q_OBJECT +public: + // Internal action vocabulary. Values are taken directly from the + // treeland-shortcut-manager-unstable-v3 protocol enum so they cannot + // drift; the PascalCase names keep the Qt-facing API readable. + enum class ShortcutAction : uint32_t { + Notify = QtWaylandServer::treeland_shortcut_manager_v3::action_notify, + Workspace1 = QtWaylandServer::treeland_shortcut_manager_v3::action_workspace_1, + Workspace2 = QtWaylandServer::treeland_shortcut_manager_v3::action_workspace_2, + Workspace3 = QtWaylandServer::treeland_shortcut_manager_v3::action_workspace_3, + Workspace4 = QtWaylandServer::treeland_shortcut_manager_v3::action_workspace_4, + Workspace5 = QtWaylandServer::treeland_shortcut_manager_v3::action_workspace_5, + Workspace6 = QtWaylandServer::treeland_shortcut_manager_v3::action_workspace_6, + Workspace7 = QtWaylandServer::treeland_shortcut_manager_v3::action_workspace_7, + Workspace8 = QtWaylandServer::treeland_shortcut_manager_v3::action_workspace_8, + Workspace9 = QtWaylandServer::treeland_shortcut_manager_v3::action_workspace_9, + Workspace10 = QtWaylandServer::treeland_shortcut_manager_v3::action_workspace_10, + Workspace11 = QtWaylandServer::treeland_shortcut_manager_v3::action_workspace_11, + Workspace12 = QtWaylandServer::treeland_shortcut_manager_v3::action_workspace_12, + PrevWorkspace = QtWaylandServer::treeland_shortcut_manager_v3::action_prev_workspace, + NextWorkspace = QtWaylandServer::treeland_shortcut_manager_v3::action_next_workspace, + Maximize = QtWaylandServer::treeland_shortcut_manager_v3::action_maximize, + CancelMaximize = QtWaylandServer::treeland_shortcut_manager_v3::action_cancel_maximize, + Minimize = QtWaylandServer::treeland_shortcut_manager_v3::action_minimize, + MoveWindow = QtWaylandServer::treeland_shortcut_manager_v3::action_move_window, + ResizeWindow = QtWaylandServer::treeland_shortcut_manager_v3::action_resize_window, + CloseWindow = QtWaylandServer::treeland_shortcut_manager_v3::action_close_window, + ShowWindowMenu = QtWaylandServer::treeland_shortcut_manager_v3::action_show_window_menu, + MoveWindowToPrevWorkspace = QtWaylandServer::treeland_shortcut_manager_v3::action_move_window_to_prev_workspace, + MoveWindowToNextWorkspace = QtWaylandServer::treeland_shortcut_manager_v3::action_move_window_to_next_workspace, + ShowDesktop = QtWaylandServer::treeland_shortcut_manager_v3::action_show_desktop, + OpenMultiTaskView = QtWaylandServer::treeland_shortcut_manager_v3::action_open_multitask_view, + CloseMultiTaskView = QtWaylandServer::treeland_shortcut_manager_v3::action_close_multitask_view, + ToggleMultitaskView = QtWaylandServer::treeland_shortcut_manager_v3::action_toggle_multitask_view, + TaskSwitchNext = QtWaylandServer::treeland_shortcut_manager_v3::action_taskswitch_next, + TaskSwitchPrev = QtWaylandServer::treeland_shortcut_manager_v3::action_taskswitch_prev, + TaskSwitchSameAppNext = QtWaylandServer::treeland_shortcut_manager_v3::action_taskswitch_sameapp_next, + TaskSwitchSameAppPrev = QtWaylandServer::treeland_shortcut_manager_v3::action_taskswitch_sameapp_prev, + TileLeft = QtWaylandServer::treeland_shortcut_manager_v3::action_tile_left, + TileRight = QtWaylandServer::treeland_shortcut_manager_v3::action_tile_right, + TileTop = QtWaylandServer::treeland_shortcut_manager_v3::action_tile_top, + TileBottom = QtWaylandServer::treeland_shortcut_manager_v3::action_tile_bottom, + TileTopLeft = QtWaylandServer::treeland_shortcut_manager_v3::action_tile_top_left, + TileTopRight = QtWaylandServer::treeland_shortcut_manager_v3::action_tile_top_right, + TileBottomLeft = QtWaylandServer::treeland_shortcut_manager_v3::action_tile_bottom_left, + TileBottomRight = QtWaylandServer::treeland_shortcut_manager_v3::action_tile_bottom_right, + ZoomIn = QtWaylandServer::treeland_shortcut_manager_v3::action_zoom_in, + ZoomOut = QtWaylandServer::treeland_shortcut_manager_v3::action_zoom_out, + ZoomReset = QtWaylandServer::treeland_shortcut_manager_v3::action_zoom_reset, + ToggleFpsDisplay = QtWaylandServer::treeland_shortcut_manager_v3::action_toggle_fps_display, + Lockscreen = QtWaylandServer::treeland_shortcut_manager_v3::action_lockscreen, + ShutdownMenu = QtWaylandServer::treeland_shortcut_manager_v3::action_shutdown_menu, + }; + Q_ENUM(ShortcutAction) + static const char *actionName(ShortcutAction action); + + enum KeyFlag : uint32_t { + None = 0, + KeyPress = 0x1, + KeyRelease = 0x2, + Repeat = 0x4, + All = KeyPress | KeyRelease | Repeat + }; + Q_DECLARE_FLAGS(KeyFlags, KeyFlag) + + // A bound shortcut as reported to the debug interface (treeland-debug + // `shortcuts`): a key binding (Key) or a touchpad swipe/hold gesture. + struct Binding + { + enum Type { Key = 0, Swipe = 1, Hold = 2 }; + + Type type = Key; + QString name; + QString key; // portable-text key sequence, empty for gestures + KeyFlags flags; + ShortcutAction action = ShortcutAction::Notify; + uint fingers = 0; // gestures + SwipeGesture::Direction direction = SwipeGesture::Direction::Invalid; // gestures + }; + // Every currently bound shortcut, for the debug interface. + QList bindings() const; + + // Debug interface only: resolves the window that currently has keyboard + // focus. Sampled when a key shortcut is dispatched, so an observer sees the + // window the shortcut was pressed on even when the action moves the focus. + using TriggerTargetProvider = std::function; + void setTriggerTargetProvider(TriggerTargetProvider provider); + qint64 lastTriggerTarget() const { return m_lastTriggerTarget; } + + explicit ShortcutController(QObject *parent = nullptr, GestureManager *gestures = nullptr); + ~ShortcutController() override; + + uint registerKey(const QString &name, const QString& key, KeyFlags keybindFlags, ShortcutAction action); + uint registerSwipeGesture(const QString &name, uint finger, SwipeGesture::Direction direction, ShortcutAction action); + uint registerHoldGesture(const QString &name, uint finger, ShortcutAction action); + void unregisterShortcut(const QString &name); + + void clear(); + bool dispatchKeyEvent(const QKeyEvent *event); + + bool matchesShortcut(const QKeyEvent *event) const; + static QKeyCombination normalizeKeyCombination(QKeyCombination combination); + static bool isValidShortcutCombination(QKeyCombination combination); + // Normalizes a portable-text key string to the (combined-key) identity + // registerKey() upserts on, or 0 when the string does not parse to exactly + // one combination. Single source of truth for the bind_key cache identity. + static int normalizedKeyCombinedFor(const QString &key); + Qt::KeyboardModifiers modifierForAction(ShortcutAction action) const; + +Q_SIGNALS: + void actionTriggered(ShortcutAction action, const QString &name, bool isGesture, KeyFlags keyFlags = {}); + // Emitted when a binding appears or disappears, so treeland-debug can + // stream shortcut registration without polling. + void shortcutRegistered(const ShortcutController::Binding &binding); + void shortcutUnregistered(const QString &name); + void actionProgress(ShortcutAction action, qreal progress, const QString &name); + void actionFinished(ShortcutAction action, const QString &name, bool isTriggered); + +private: + + void unregisterKey(int combined, ShortcutAction action); + + GestureManager *const m_gestureManager; + QMap>> m_keyMap; + QMap, QMap> m_gesturemap; + QMap, QObject*> m_gestures; + QMap> m_deleters; + QMap m_actionCombinedMap; + // Suppresses shortcutUnregistered() while the object is being destroyed. + bool m_destroying = false; + TriggerTargetProvider m_triggerTargetProvider; + qint64 m_lastTriggerTarget = 0; +}; + +// Convenience alias so existing bare `ShortcutAction` references keep working +using ShortcutAction = ShortcutController::ShortcutAction; + +Q_DECLARE_OPERATORS_FOR_FLAGS(ShortcutController::KeyFlags) diff --git a/src/modules/shortcut/shortcutmanager.cpp b/src/modules/shortcut/shortcutmanager.cpp new file mode 100644 index 0000000000..c750a892e1 --- /dev/null +++ b/src/modules/shortcut/shortcutmanager.cpp @@ -0,0 +1,614 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include +#include "shortcutmanager.h" + +#include "common/treelandlogging.h" +#include "input/swipegesture.h" +#include "qwayland-server-treeland-shortcut-manager-unstable-v3.h" +#include "shortcutcontroller.h" + +#include +#include + +#include + +#include +#include +#include + +struct KeyShortcut { + ShortcutController::KeyFlags keybindFlags; + QString name; + QString key; + ShortcutAction action; +}; + +struct SwipeShortcut { + QString name; + uint finger; + SwipeGesture::Direction direction; + ShortcutAction action; +}; + +struct HoldShortcut { + QString name; + uint finger; + ShortcutAction action; +}; + +// Returns true when the action value is one of the defined ShortcutAction +// enum values. Uses QMetaEnum instead of a range check so it stays correct +// even if the enum gains holes or is reordered in the future. +static bool isValidAction(ShortcutAction action) +{ + const auto meta = QMetaEnum::fromType(); + return meta.valueToKey(static_cast(action)) != nullptr; +} + +// Forward declaration +class ShortcutManagerV3Private; + +// Returns true if the key itself is a pure modifier key that can never be a valid +// shortcut on its own (Ctrl/Alt/Shift/Hyper/AltGr/lock keys). +// +// NOTE: Qt::Key_Meta, Qt::Key_Super_L, Qt::Key_Super_R are intentionally NOT listed — +// on Linux/Wayland the Win key maps to one of these, and pressing it alone IS a valid +// standalone shortcut (dde-daemon isGoodNoMods() explicitly includes XK_Super_L/R). +static bool isPureModifierKey(Qt::Key key) +{ + switch (key) { + case Qt::Key_Shift: + case Qt::Key_Control: + case Qt::Key_Alt: + case Qt::Key_Hyper_L: + case Qt::Key_Hyper_R: + case Qt::Key_AltGr: + case Qt::Key_CapsLock: + case Qt::Key_NumLock: + case Qt::Key_ScrollLock: + return true; + default: + return false; + } +} + +class ShortcutCaptureV3 : public QtWaylandServer::treeland_shortcut_capture_v3 +{ +public: + ShortcutCaptureV3(ShortcutManagerV3Private *manager, + wl_client *client, + uint32_t id, + int version) + : QtWaylandServer::treeland_shortcut_capture_v3(client, id, version) + , m_manager(manager) + , m_pending(true) + { + } + + bool isPending() const + { + return m_pending; + } + + void sendCaptured(const QString &key) + { + m_pending = false; + send_captured(key); + } + + void sendFailed(uint32_t reason) + { + m_pending = false; + send_failed(reason); + } + +protected: + // Defined after ShortcutManagerV3Private + void destroy(Resource *resource) override; + + // Called both when the client sends destroy and when the client disconnects. + // Must clean up m_pendingCapture to avoid a dangling pointer. + void destroy_resource(Resource *resource) override; + +private: + ShortcutManagerV3Private *m_manager; + bool m_pending; +}; + +static SwipeGesture::Direction toSwipeDirection(uint32_t direction) +{ + using Direction = QtWaylandServer::treeland_shortcut_manager_v3::direction; + switch (direction) { + case Direction::direction_down: + return SwipeGesture::Direction::Down; + case Direction::direction_left: + return SwipeGesture::Direction::Left; + case Direction::direction_up: + return SwipeGesture::Direction::Up; + case Direction::direction_right: + return SwipeGesture::Direction::Right; + default: + return SwipeGesture::Direction::Invalid; + } +} + +class ShortcutManagerV3Private : public QtWaylandServer::treeland_shortcut_manager_v3 +{ +public: + explicit ShortcutManagerV3Private(ShortcutManagerV3::SeatProvider seats); + + wl_global *global() const; + + void sendActivated(const QString &name, ShortcutController::KeyFlags keyFlags); + void sendBindFailure(const QString &name, uint error); + uint registerKey(const KeyShortcut &ks); + uint registerSwipe(const SwipeShortcut &ss); + uint registerHold(const HoldShortcut &hs); + + QPointer m_controller; + Resource *m_owner = nullptr; + const ShortcutManagerV3::SeatProvider m_seats; + + ShortcutCaptureV3 *m_pendingCapture = nullptr; + // Seat whose keyboard focus was validated at capture start. + // Events from other seats are ignored during capture. + WSeat *m_pendingSeat = nullptr; + Qt::Key m_drainKey = Qt::Key_unknown; + WSeat *m_drainSeat = nullptr; + // Target surface that requested the capture. Capture must fail once it loses focus. + QPointer m_pendingSurface; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void acquire(Resource *resource) override; + void bind_key(Resource *resource, + const QString &name, + const QString &key_sequence, + uint32_t flags, + uint32_t action) override; + void bind_swipe_gesture(Resource *resource, + const QString &name, + uint32_t finger, + uint32_t direction, + uint32_t action) override; + void bind_hold_gesture(Resource *resource, + const QString &name, + uint32_t finger, + uint32_t action) override; + void unbind(Resource *resource, const QString &name) override; + void capture_next_shortcut(Resource *resource, + struct ::wl_resource *surface, + struct ::wl_resource *seat, + uint32_t capture) override; + +private: + // Clears all capture-related state and returns the previously pending capture object. + // The caller is responsible for sending a terminal event on the returned object. + ShortcutCaptureV3 *resetCaptureState(); + +public: + void cancelCapture(); + void onCaptureDestroyed(ShortcutCaptureV3 *c); + bool tryHandleCaptureEvent(WSeat *seat, QInputEvent *event); +}; + +ShortcutManagerV3Private::ShortcutManagerV3Private(ShortcutManagerV3::SeatProvider seats) + : m_seats(std::move(seats)) +{ +} + +wl_global *ShortcutManagerV3Private::global() const +{ + return m_global; +} + +uint ShortcutManagerV3Private::registerKey(const KeyShortcut &ks) +{ + if (!isValidAction(ks.action)) + return QtWaylandServer::treeland_shortcut_manager_v3::bind_error_invalid_argument; + return m_controller->registerKey(ks.name, ks.key, ks.keybindFlags, ks.action); +} + +uint ShortcutManagerV3Private::registerSwipe(const SwipeShortcut &ss) +{ + if (!isValidAction(ss.action)) + return QtWaylandServer::treeland_shortcut_manager_v3::bind_error_invalid_argument; + return m_controller->registerSwipeGesture(ss.name, ss.finger, ss.direction, ss.action); +} + +uint ShortcutManagerV3Private::registerHold(const HoldShortcut &hs) +{ + if (!isValidAction(hs.action)) + return QtWaylandServer::treeland_shortcut_manager_v3::bind_error_invalid_argument; + return m_controller->registerHoldGesture(hs.name, hs.finger, hs.action); +} + +void ShortcutManagerV3Private::sendActivated(const QString &name, ShortcutController::KeyFlags keyFlags) +{ + if (m_owner) + send_activated(m_owner->handle, name, keyFlags.toInt()); +} + +void ShortcutManagerV3Private::sendBindFailure(const QString &name, uint error) +{ + if (m_owner) + send_bind_failure(m_owner->handle, name, error); +} + +void ShortcutManagerV3Private::destroy_resource(Resource *resource) +{ + if (m_owner == resource) { + m_owner = nullptr; + if (m_controller) + m_controller->clear(); + cancelCapture(); + } +} + +void ShortcutManagerV3Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void ShortcutManagerV3Private::acquire(Resource *resource) +{ + if (m_owner) { + wl_resource_post_error(resource->handle, + error_occupied, + "Another client has already acquired the shortcut manager."); + return; + } + m_controller->clear(); + m_owner = resource; +} + +void ShortcutManagerV3Private::bind_key(Resource *resource, + const QString &name, + const QString &key_sequence, + uint32_t flags, + uint32_t action) +{ + if (m_owner != resource) { + wl_resource_post_error(resource->handle, + error_not_acquired, + "Client has not acquired the shortcut manager."); + return; + } + + KeyShortcut ks{ + .keybindFlags = ShortcutController::KeyFlags::fromInt(flags), + .name = name, + .key = key_sequence, + .action = static_cast(action), + }; + + const uint status = registerKey(ks); + if (status) + sendBindFailure(name, status); +} + +void ShortcutManagerV3Private::bind_swipe_gesture(Resource *resource, + const QString &name, + uint32_t finger, + uint32_t direction, + uint32_t action) +{ + if (m_owner != resource) { + wl_resource_post_error(resource->handle, + error_not_acquired, + "Client has not acquired the shortcut manager."); + return; + } + + SwipeShortcut ss{ + .name = name, + .finger = finger, + .direction = toSwipeDirection(direction), + .action = static_cast(action), + }; + + const uint status = registerSwipe(ss); + if (status) + sendBindFailure(name, status); +} + +void ShortcutManagerV3Private::bind_hold_gesture(Resource *resource, + const QString &name, + uint32_t finger, + uint32_t action) +{ + if (m_owner != resource) { + wl_resource_post_error(resource->handle, + error_not_acquired, + "Client has not acquired the shortcut manager."); + return; + } + + HoldShortcut hs{ + .name = name, + .finger = finger, + .action = static_cast(action), + }; + + const uint status = registerHold(hs); + if (status) + sendBindFailure(name, status); +} + +void ShortcutManagerV3Private::unbind(Resource *resource, const QString &name) +{ + if (m_owner != resource) { + wl_resource_post_error(resource->handle, + error_not_acquired, + "Client has not acquired the shortcut manager."); + return; + } + + m_controller->unregisterShortcut(name); +} + +void ShortcutCaptureV3::destroy(Resource *resource) +{ + // destroy_resource() handles cleanup; just trigger it. + wl_resource_destroy(resource->handle); +} + +void ShortcutCaptureV3::destroy_resource(Resource *) +{ + if (m_pending) + m_manager->onCaptureDestroyed(this); + delete this; +} + +void ShortcutManagerV3Private::capture_next_shortcut(Resource *resource, + struct ::wl_resource *surface, + struct ::wl_resource *seat_resource, + uint32_t capture) +{ + // Validate surface ownership: the surface must belong to the requesting client. + if (wl_resource_get_client(surface) != wl_resource_get_client(resource->handle)) { + wl_resource_post_error(resource->handle, + error_invalid_surface, + "Surface does not belong to the requesting client."); + return; + } + + // Create the capture resource. + auto *captureObj = + new ShortcutCaptureV3(this, resource->client(), capture, resource->version()); + + // Check if another capture is already in progress. + if (m_pendingCapture || m_drainKey != Qt::Key_unknown) { + captureObj->sendFailed(ShortcutCaptureV3::failed_reason_busy); + return; + } + + // Resolve the target surface first so it can be used for focus-based seat lookup. + auto *wlrSurface = wlr_surface_from_resource(surface); + auto *wSurface = wlrSurface ? WSurface::fromHandle(wlrSurface) : nullptr; + + WSeat *requestedSeat = nullptr; + if (seat_resource) { + // Client specified a seat: resolve it directly. + auto *wlrSeatClient = wlr_seat_client_from_resource(seat_resource); + if (wlrSeatClient) + requestedSeat = WSeat::fromHandle(wlrSeatClient->seat); + } else if (m_seats) { + // Resolve focus only within this protocol instance's seat domain. + const auto seats = m_seats(); + for (auto *seat : seats) { + if (seat->keyboardFocusSurface() == wSurface) { + requestedSeat = seat; + break; + } + } + } + + if (requestedSeat && m_seats && !m_seats().contains(requestedSeat)) { + captureObj->sendFailed(ShortcutCaptureV3::failed_reason_not_active); + return; + } + + // Validate surface focus / active state. + auto *focusedSurface = requestedSeat ? requestedSeat->keyboardFocusSurface() : nullptr; + if (!focusedSurface || focusedSurface != wSurface) { + captureObj->sendFailed(ShortcutCaptureV3::failed_reason_not_active); + return; + } + + m_pendingCapture = captureObj; + m_pendingSeat = requestedSeat; + m_pendingSurface = wSurface; +} + +void ShortcutManagerV3Private::onCaptureDestroyed(ShortcutCaptureV3 *c) +{ + if (m_pendingCapture == c) + resetCaptureState(); +} + +ShortcutCaptureV3 *ShortcutManagerV3Private::resetCaptureState() +{ + auto *c = m_pendingCapture; + m_pendingCapture = nullptr; + m_pendingSeat = nullptr; + m_pendingSurface.clear(); + return c; +} + +// Capture event filter — called from CompositorInputFilter while a +// one-shot shortcut capture is in progress. +// +// Trigger semantics: +// KeyPress (regular non-modifier) → TERMINATE capture immediately +// (captured or failed). +// KeyRelease (Meta/Super only) → used for standalone Win key capture. +// +// Key categories: +// pure modifier (Ctrl/Alt/Shift/…) — consumed on press; KeyRelease → always fail. +// Win key (Super_L/R or Meta) — consumed on press; KeyRelease → emit "Meta" if +// no other modifier is held (any regular key pressed +// while Win is held terminates capture on KeyPress). +// all other keys — terminate on KeyPress via +// ShortcutController::isValidShortcutCombination(). +bool ShortcutManagerV3Private::tryHandleCaptureEvent(WSeat *seat, QInputEvent *event) +{ + // Drain the captured key's residual KeyRelease to avoid triggering + // a newly bound shortcut with KeyRelease trigger semantics. + if (m_drainKey != Qt::Key_unknown && seat == m_drainSeat + && event->type() == QEvent::KeyRelease) { + auto *ke = static_cast(event); + if (static_cast(ke->key()) == m_drainKey) { + m_drainKey = Qt::Key_unknown; + m_drainSeat = nullptr; + return true; + } + } + + if (!m_pendingCapture) + return false; + + // Seat filter: ignore events from seats other than the one used to validate focus. + if (seat != m_pendingSeat) + return false; + + // If the requesting surface lost focus, abort capture but do not consume the + // current event, so input can continue to the newly focused target. + if (!m_pendingSurface || m_pendingSeat->keyboardFocusSurface() != m_pendingSurface) { + resetCaptureState()->sendFailed(ShortcutCaptureV3::failed_reason_aborted); + return false; + } + + // Pointer button or wheel: cancel immediately. + const auto type = event->type(); + if (type == QEvent::MouseButtonPress || type == QEvent::MouseButtonRelease + || type == QEvent::Wheel) { + resetCaptureState()->sendFailed(ShortcutCaptureV3::failed_reason_interrupted); + return true; + } + + if (type != QEvent::KeyPress && type != QEvent::KeyRelease) + return false; + + auto *kevent = static_cast(event); + + // Auto-repeat: consume silently without updating state. + if (kevent->isAutoRepeat()) + return true; + + Qt::Key key = static_cast(kevent->key()); + + if (type == QEvent::KeyPress) { + if (isPureModifierKey(key)) { + // Pure modifier (Ctrl/Alt/Shift/…): consume and keep waiting. + // A previously stored candidate stays valid. + return true; + } + + if (key == Qt::Key_Super_L || key == Qt::Key_Super_R || key == Qt::Key_Meta) { + // Win/Super key: at KeyPress time we cannot yet tell whether the user + // intends it alone ("Meta") or combined with another key ("Meta+X"). + // Treat it like a modifier — consume and wait. The KeyRelease path + // below will emit "Meta" if no other key was pressed in between. + return true; + } + + // Regular non-modifier key: terminate capture immediately on KeyPress. + if (ShortcutController::isValidShortcutCombination(kevent->keyCombination())) { + // Arm drain before resetting (resetCaptureState clears m_pendingSeat). + m_drainKey = key; + m_drainSeat = m_pendingSeat; + auto keyComb = ShortcutController::normalizeKeyCombination(kevent->keyCombination()); + auto captured = QKeySequence(keyComb).toString(QKeySequence::PortableText); + resetCaptureState()->sendCaptured(captured); + } else { + // Invalid combo: fail immediately. + resetCaptureState()->sendFailed(ShortcutCaptureV3::failed_reason_interrupted); + } + } else { // KeyRelease, only needed for modifier-only paths. + if (isPureModifierKey(key)) { + // Pure modifier released without any regular key press. + resetCaptureState()->sendFailed(ShortcutCaptureV3::failed_reason_interrupted); + } else if (key == Qt::Key_Super_L || key == Qt::Key_Super_R || key == Qt::Key_Meta) { + // Win/Super is only valid when pressed alone (no other modifiers held). + if ((kevent->modifiers() & ~Qt::MetaModifier) == Qt::NoModifier) + resetCaptureState()->sendCaptured(QStringLiteral("Meta")); + else + resetCaptureState()->sendFailed(ShortcutCaptureV3::failed_reason_interrupted); + } else { + // With press-trigger semantics, regular non-modifier release should not + // normally reach here. Be defensive and fail-safe if it does. + resetCaptureState()->sendFailed(ShortcutCaptureV3::failed_reason_interrupted); + } + } + return true; +} + +ShortcutManagerV3::ShortcutManagerV3(QObject *parent, ShortcutController *controller, + SeatProvider seats) + : QObject(parent) + , d(std::make_unique(std::move(seats))) +{ + d->m_controller = controller ? controller : new ShortcutController(this); +} + +ShortcutManagerV3::~ShortcutManagerV3() = default; + +void ShortcutManagerV3::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void ShortcutManagerV3::destroy(WServer *server) +{ + Q_UNUSED(server); + d->globalRemove(); + Q_EMIT before_destroy(); +} + +wl_global *ShortcutManagerV3::global() const +{ + return d->global(); +} + +bool ShortcutManagerV3::tryHandleCaptureEvent(WSeat *seat, QInputEvent *event) +{ + return d->tryHandleCaptureEvent(seat, event); +} + +bool ShortcutManagerV3::isCaptureActive() const +{ + return d->m_pendingCapture || d->m_drainKey != Qt::Key_unknown; +} + +QByteArrayView ShortcutManagerV3::interfaceName() const +{ + return "treeland_shortcut_manager_v3"; +} + +ShortcutController* ShortcutManagerV3::controller() +{ + return d->m_controller; +} + +void ShortcutManagerV3::sendActivated(const QString& name, ShortcutController::KeyFlags keyFlags) +{ + d->sendActivated(name, keyFlags); +} + +void ShortcutManagerV3Private::cancelCapture() +{ + if (m_pendingCapture) + resetCaptureState()->sendFailed(ShortcutCaptureV3::failed_reason_aborted); + m_drainKey = Qt::Key_unknown; + m_drainSeat = nullptr; +} + +void ShortcutManagerV3::cancelCapture() +{ + d->cancelCapture(); +} diff --git a/src/modules/shortcut/shortcutmanager.h b/src/modules/shortcut/shortcutmanager.h new file mode 100644 index 0000000000..478568c937 --- /dev/null +++ b/src/modules/shortcut/shortcutmanager.h @@ -0,0 +1,56 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "shortcutcontroller.h" + +#include + +#include +#include +#include +#include +#include + +class ShortcutManagerV3Private; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WServer; +class WSeat; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class ShortcutManagerV3 + : public QObject + , public WAYLIB_SERVER_NAMESPACE::WServerInterface +{ + Q_OBJECT + +public: + using SeatProvider = std::function()>; + explicit ShortcutManagerV3(QObject *parent = nullptr, ShortcutController *controller = nullptr, + SeatProvider seats = {}); + ~ShortcutManagerV3() override; + QByteArrayView interfaceName() const override; + static constexpr int InterfaceVersion = 1; + + ShortcutController* controller(); + void sendActivated(const QString& name, ShortcutController::KeyFlags keyFlags); + + bool tryHandleCaptureEvent(WAYLIB_SERVER_NAMESPACE::WSeat *seat, QInputEvent *event); + bool isCaptureActive() const; + void cancelCapture(); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +Q_SIGNALS: + void before_destroy(); + +private: + std::unique_ptr d; +}; diff --git a/src/modules/shortcut/shortcutrunner.cpp b/src/modules/shortcut/shortcutrunner.cpp new file mode 100644 index 0000000000..92c03f5f11 --- /dev/null +++ b/src/modules/shortcut/shortcutrunner.cpp @@ -0,0 +1,473 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "shortcutrunner.h" +#include "input/compositorinputfilter.h" +#include "session/sessionswitcher.h" +#include "session/sessionmultitaskview.h" + +#include "common/shellaction.h" +#include "core/qmlengine.h" +#include "core/rootsurfacecontainer.h" +#include "interfaces/multitaskviewinterface.h" +#include "core/waylandserver.h" +#include "shortcutcontroller.h" +#include "shortcutmanager.h" +#include "treelandconfig.hpp" +#include "workspace/workspace.h" +#include "workspaceanimationcontroller.h" +#include "woutputrenderwindow.h" + +#include + +// Maps the shortcut-manager action enum (ShortcutAction) onto the shared +// ShellAction vocabulary. Notify and the task-switch stepping actions are +// producer-local and return std::nullopt. +static std::optional mapShortcutAction(ShortcutAction action) +{ + switch (action) { + case ShortcutAction::Workspace1: + return ShellAction::SwitchWorkspace1; + case ShortcutAction::Workspace2: + return ShellAction::SwitchWorkspace2; + case ShortcutAction::Workspace3: + return ShellAction::SwitchWorkspace3; + case ShortcutAction::Workspace4: + return ShellAction::SwitchWorkspace4; + case ShortcutAction::Workspace5: + return ShellAction::SwitchWorkspace5; + case ShortcutAction::Workspace6: + return ShellAction::SwitchWorkspace6; + case ShortcutAction::Workspace7: + return ShellAction::SwitchWorkspace7; + case ShortcutAction::Workspace8: + return ShellAction::SwitchWorkspace8; + case ShortcutAction::Workspace9: + return ShellAction::SwitchWorkspace9; + case ShortcutAction::Workspace10: + return ShellAction::SwitchWorkspace10; + case ShortcutAction::Workspace11: + return ShellAction::SwitchWorkspace11; + case ShortcutAction::Workspace12: + return ShellAction::SwitchWorkspace12; + case ShortcutAction::PrevWorkspace: + return ShellAction::PreviousWorkspace; + case ShortcutAction::NextWorkspace: + return ShellAction::NextWorkspace; + case ShortcutAction::ShowDesktop: + return ShellAction::ToggleShowDesktop; + case ShortcutAction::OpenMultiTaskView: + return ShellAction::OpenMultitaskView; + case ShortcutAction::CloseMultiTaskView: + return ShellAction::CloseMultitaskView; + case ShortcutAction::ToggleMultitaskView: + return ShellAction::ToggleMultitaskView; + case ShortcutAction::ToggleFpsDisplay: + return ShellAction::ToggleFpsDisplay; + case ShortcutAction::Lockscreen: + return ShellAction::LockScreen; + case ShortcutAction::ShutdownMenu: + return ShellAction::ShowShutdownMenu; + case ShortcutAction::Maximize: + return ShellAction::Maximize; + case ShortcutAction::CancelMaximize: + return ShellAction::CancelMaximize; + case ShortcutAction::Minimize: + return ShellAction::Minimize; + case ShortcutAction::MoveWindow: + return ShellAction::MoveWindow; + case ShortcutAction::CloseWindow: + return ShellAction::CloseWindow; + case ShortcutAction::ShowWindowMenu: + return ShellAction::ShowWindowMenu; + case ShortcutAction::TileLeft: + return ShellAction::TileLeft; + case ShortcutAction::TileRight: + return ShellAction::TileRight; + case ShortcutAction::TileTopLeft: + return ShellAction::TileTopLeft; + case ShortcutAction::TileTopRight: + return ShellAction::TileTopRight; + case ShortcutAction::TileBottomLeft: + return ShellAction::TileBottomLeft; + case ShortcutAction::TileBottomRight: + return ShellAction::TileBottomRight; + case ShortcutAction::ZoomIn: + return ShellAction::ZoomIn; + case ShortcutAction::ZoomOut: + return ShellAction::ZoomOut; + case ShortcutAction::ZoomReset: + return ShellAction::ZoomReset; + case ShortcutAction::MoveWindowToPrevWorkspace: + return ShellAction::MoveWindowToPrevWorkspace; + case ShortcutAction::MoveWindowToNextWorkspace: + return ShellAction::MoveWindowToNextWorkspace; + // Intentionally unsupported for now: producer-local notify, task-switch + // stepping, and actions whose execution plumbing has not landed yet. + // Kept as explicit cases so -Wswitch fires when the enum gains a member. + case ShortcutAction::Notify: + case ShortcutAction::ResizeWindow: + case ShortcutAction::TileTop: + case ShortcutAction::TileBottom: + case ShortcutAction::TaskSwitchNext: + case ShortcutAction::TaskSwitchPrev: + case ShortcutAction::TaskSwitchSameAppNext: + case ShortcutAction::TaskSwitchSameAppPrev: + return std::nullopt; + } + return std::nullopt; +} + +ShortcutRunner::ShortcutRunner(Workspace *workspace, SessionSwitcher *switcher, + ShortcutController *controller, SessionMultitaskView *multitaskView, + WaylandServer *runtime, + CompositorInputFilter *inputFilter, ShortcutManagerV3 *protocol) + : QObject(switcher) + , m_workspace(workspace) + , m_switcher(switcher) + , m_multitaskView(multitaskView) + , m_runtime(runtime) + , m_inputFilter(inputFilter) + , m_controller(controller) + , m_protocol(protocol) +{ + m_quickSwitchTimer = new QTimer(this); + m_quickSwitchTimer->setSingleShot(true); + connect(m_quickSwitchTimer, &QTimer::timeout, this, &ShortcutRunner::onQuickSwitchTimeout); +} + +void ShortcutRunner::start() +{ + connect(m_controller, &ShortcutController::actionTriggered, this, &ShortcutRunner::onActionTrigger, Qt::UniqueConnection); + connect(m_controller, &ShortcutController::actionProgress, this, &ShortcutRunner::onActionProgress, Qt::UniqueConnection); + connect(m_controller, &ShortcutController::actionFinished, this, &ShortcutRunner::onActionFinish, Qt::UniqueConnection); + connect(m_inputFilter, &CompositorInputFilter::modifierKeyReleased, + this, &ShortcutRunner::onModifierReleased, Qt::UniqueConnection); +} + +void ShortcutRunner::stop() +{ + disconnect(m_controller, nullptr, this, nullptr); + disconnect(m_inputFilter, &CompositorInputFilter::modifierKeyReleased, + this, &ShortcutRunner::onModifierReleased); + m_quickSwitchTimer->stop(); + m_quickSwitchPending = false; + m_taskAltCount = 0; + m_slideEnable = false; +} + +void ShortcutRunner::onActionTrigger(ShortcutAction action, const QString &name, bool isGesture, ShortcutController::KeyFlags keyFlags) +{ + if (!m_workspace->isEnabled()) + return; + + Q_UNUSED(isGesture) + auto *server = m_runtime; + + if (server->currentMode() == WaylandServer::CurrentMode::LockScreen) { + return; + } + + m_currentAction = action; + + if (const auto shellAction = mapShortcutAction(action)) { + ShellActionExecutor::execute(*shellAction); + return; + } + + switch (action) { + case ShortcutAction::Notify: + m_protocol->sendActivated(name, keyFlags); + break; + case ShortcutAction::TaskSwitchNext: + case ShortcutAction::TaskSwitchPrev: + case ShortcutAction::TaskSwitchSameAppNext: + case ShortcutAction::TaskSwitchSameAppPrev: { + if (keyFlags.testFlag(ShortcutController::Repeat) + && server->currentMode() == WaylandServer::CurrentMode::Normal + && !m_quickSwitchPending) { + return; + } + + const bool isSameApp = (action == ShortcutAction::TaskSwitchSameAppNext || action == ShortcutAction::TaskSwitchSameAppPrev); + const bool isPrev = (action == ShortcutAction::TaskSwitchPrev || action == ShortcutAction::TaskSwitchSameAppPrev); + taskswitchAction(keyFlags.testFlag(ShortcutController::Repeat), isSameApp, isPrev); + break; + } + default: + break; + } +} + +void ShortcutRunner::onActionProgress(ShortcutAction action, qreal progress, const QString &name) +{ + if (!m_workspace->isEnabled()) + return; + + Q_UNUSED(name); + switch (action) { + case ShortcutAction::PrevWorkspace: + updateWorkspaceSwipe(-progress); + break; + case ShortcutAction::NextWorkspace: + updateWorkspaceSwipe(progress); + break; + case ShortcutAction::OpenMultiTaskView: + { + auto server = m_runtime; + if (!m_multitaskView || !server->isNormalOrMultitaskview()) + break; + if (server->currentMode() == WaylandServer::CurrentMode::Normal + && qFuzzyIsNull(m_multitaskView->partialFactor())) { + m_multitaskView->toggleMultitaskView(IMultitaskView::ActiveReason::Gesture); + } + if (server->currentMode() == WaylandServer::CurrentMode::Multitaskview) { + break; + } + m_multitaskView->updatePartialFactor(progress); + break; + } + case ShortcutAction::CloseMultiTaskView: + { + auto server = m_runtime; + if (!m_multitaskView || !server->isNormalOrMultitaskview()) + break; + if (server->currentMode() != WaylandServer::CurrentMode::Multitaskview) { + break; + } + m_multitaskView->updatePartialFactor(1 - progress); + break; + } + default: + break; + } +} + +void ShortcutRunner::onActionFinish(ShortcutAction action, const QString &name, bool isTriggered) +{ + if (!m_workspace->isEnabled()) + return; + + Q_UNUSED(name); + switch (action) { + case ShortcutAction::PrevWorkspace: + case ShortcutAction::NextWorkspace: + finishWorkspaceSwipe(); + break; + case ShortcutAction::OpenMultiTaskView: + { + auto server = m_runtime; + if (!m_multitaskView || !server->isNormalOrMultitaskview()) + break; + const bool triggered = m_multitaskView->partialFactor() > 0.5; + m_multitaskView->setStatus(triggered ? IMultitaskView::Active + : IMultitaskView::Exited); + m_multitaskView->toggleMultitaskView(IMultitaskView::ActiveReason::Gesture); + m_multitaskView->commitGesture(triggered); + break; + } + case ShortcutAction::CloseMultiTaskView: + { + auto server = m_runtime; + if (!m_multitaskView || !server->isNormalOrMultitaskview()) + break; + const bool triggered = (1.0 - m_multitaskView->partialFactor()) > 0.5; + if (qFuzzyCompare(m_multitaskView->partialFactor(), 0.0) + && server->currentMode() != WaylandServer::CurrentMode::Multitaskview) + break; + m_multitaskView->setStatus(triggered ? IMultitaskView::Exited + : IMultitaskView::Active); + m_multitaskView->toggleMultitaskView(IMultitaskView::ActiveReason::Gesture); + m_multitaskView->commitGesture(!triggered); + break; + } + default: + if (isTriggered) { + onActionTrigger(action, name, true, ShortcutController::KeyFlag::None); + } + break; + } +} + +void ShortcutRunner::updateWorkspaceSwipe(qreal cb) +{ + if (qFuzzyCompare(cb, m_desktopOffset)) + return; + + Q_ASSERT(m_workspace); + + WorkspaceAnimationController *controller = m_workspace->animationController(); + Q_ASSERT(controller); + + m_desktopOffset = cb; + + if (!m_slideEnable) { + m_slideEnable = true; + m_fromId = m_workspace->currentIndex(); + controller->slideNormal(m_fromId); + m_workspace->createSwitcher(); + controller->setRunning(true); + } + + controller->startGestureSlide( + cb, + isWorkspaceBounce(cb, m_workspace->currentIndex(), m_workspace->count())); +} + +void ShortcutRunner::finishWorkspaceSwipe() +{ + if (!m_slideEnable) + return; + m_slideEnable = false; + int currentIdx = m_workspace->currentIndex(); + int wsCount = m_workspace->count(); + + // determine target based on offset threshold, but never cross boundary + m_toId = currentIdx; + if (m_desktopOffset > 0.3) { + if (!isWorkspaceBounce(m_desktopOffset, currentIdx, wsCount)) + m_toId = currentIdx + 1; + } else if (m_desktopOffset <= -0.3) { + if (!isWorkspaceBounce(m_desktopOffset, currentIdx, wsCount)) + m_toId = currentIdx - 1; + } + + // final safety bounds check + m_toId = qBound(0, m_toId, wsCount - 1); + + auto controller = m_workspace->animationController(); + controller->slideRunning(m_toId); + controller->startSlideAnimation(); + m_workspace->switchTo(m_toId, false); +} + +void ShortcutRunner::taskswitchAction(bool isRepeat, bool isSameApp, bool isPrev) +{ + auto *server = m_runtime; + const auto modeBefore = server->currentMode(); + if (modeBefore != WaylandServer::CurrentMode::Normal && modeBefore != WaylandServer::CurrentMode::WindowSwitch) + return; + + if (!isRepeat && !isSameApp && modeBefore == WaylandServer::CurrentMode::Normal) { + auto *current = m_workspace->current(); + if (current) { + auto nextSurface = current->findNextActivedSurface(); + if (nextSurface) + server->forceActivateSurface(nextSurface, Qt::TabFocusReason); + } + m_quickSwitchTimer->start(server->globalConfig()->quickSwitchTimeout()); + m_quickSwitchPending = true; + return; + } + + if (!m_switcher->taskSwitcher()) { + auto *output = server->rootSurfaceContainer()->cursorOutput(); + if (!output) + output = server->rootSurfaceContainer()->primaryOutput(); + m_switcher->ensureTaskSwitcher(output); + server->restoreFromShowDesktop(); + } + + if (isRepeat) { + m_taskAltCount++; + } else { + m_taskAltCount = 3; + } + + if (m_taskAltCount < 3) + return; + + m_taskAltCount = 0; + server->setCurrentMode(WaylandServer::CurrentMode::WindowSwitch); + + if (m_quickSwitchPending) { + m_quickSwitchTimer->stop(); + m_quickSwitchPending = false; + } + + if (isSameApp) { + QMetaObject::invokeMethod(m_switcher->taskSwitcher(), isPrev ? "previousSameApp" : "nextSameApp"); + } else { + auto filter = m_workspace->currentFilter(); + filter->setFilterAppId({}); + QMetaObject::invokeMethod(m_switcher->taskSwitcher(), isPrev ? "previous" : "next"); + } +} + +void ShortcutRunner::onQuickSwitchTimeout() +{ + auto *server = m_runtime; + if (server->currentMode() != WaylandServer::CurrentMode::Normal) { + m_quickSwitchPending = false; + return; + } + + if (!m_switcher->taskSwitcher()) { + auto *output = server->rootSurfaceContainer()->cursorOutput(); + if (!output) + output = server->rootSurfaceContainer()->primaryOutput(); + m_switcher->ensureTaskSwitcher(output); + server->restoreFromShowDesktop(); + } + server->setCurrentMode(WaylandServer::CurrentMode::WindowSwitch); + + QMetaObject::invokeMethod(m_switcher->taskSwitcher(), "show"); +} + +void ShortcutRunner::onModifierReleased(QKeyEvent *event) +{ + auto *server = m_runtime; + + const QList taskSwitchActions = { + ShortcutAction::TaskSwitchNext, + ShortcutAction::TaskSwitchPrev, + ShortcutAction::TaskSwitchSameAppNext, + ShortcutAction::TaskSwitchSameAppPrev, + }; + + if (taskSwitchActions.contains(m_currentAction)) { + auto *controller = m_controller; + const auto currentModifiers = controller->modifierForAction(m_currentAction); + + constexpr auto supportedModifiers = + Qt::AltModifier | Qt::MetaModifier | Qt::ControlModifier | Qt::ShiftModifier; + + auto keyCombination = QKeyCombination(Qt::NoModifier,static_cast(event->key())); + const auto releasedModifier = ShortcutController::normalizeKeyCombination(keyCombination).keyboardModifiers() & supportedModifiers; + + if (!(currentModifiers & releasedModifier)) + return; + + auto remainingModifiers = event->modifiers() & supportedModifiers; + remainingModifiers &= ~releasedModifier; + + const bool hasActiveTaskSwitchModifiers = + std::any_of(taskSwitchActions.cbegin(), taskSwitchActions.cend(), [ + controller, + currentModifiers, + remainingModifiers](auto action) { + const auto modifiers = controller->modifierForAction(action); + if (modifiers == Qt::NoModifier) + return false; + if ((modifiers & currentModifiers) != modifiers) + return false; + return (remainingModifiers & modifiers) == modifiers; + }); + if (hasActiveTaskSwitchModifiers) + return; + + if (m_quickSwitchPending && server->currentMode() == WaylandServer::CurrentMode::Normal) { + m_quickSwitchTimer->stop(); + m_quickSwitchPending = false; + return; + } + + if (server->currentMode() == WaylandServer::CurrentMode::WindowSwitch && m_switcher->taskSwitcher()) { + auto filter = m_workspace->currentFilter(); + filter->setFilterAppId(""); + server->setCurrentMode(WaylandServer::CurrentMode::Normal); + m_quickSwitchPending = false; + QMetaObject::invokeMethod(m_switcher->taskSwitcher(), "exit"); + } + } +} diff --git a/src/modules/shortcut/shortcutrunner.h b/src/modules/shortcut/shortcutrunner.h new file mode 100644 index 0000000000..d1f5f49c66 --- /dev/null +++ b/src/modules/shortcut/shortcutrunner.h @@ -0,0 +1,64 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include +#include "shortcutcontroller.h" + +class Workspace; +class SessionSwitcher; +class SessionMultitaskView; +class WaylandServer; +class CompositorInputFilter; +class ShortcutManagerV3; + +class ShortcutRunner : public QObject +{ + Q_OBJECT +public: + ShortcutRunner(Workspace *workspace, SessionSwitcher *switcher, ShortcutController *controller, + SessionMultitaskView *multitaskView, WaylandServer *runtime, + CompositorInputFilter *inputFilter, ShortcutManagerV3 *protocol); + void start(); + void stop(); + +public Q_SLOTS: + void onActionTrigger(ShortcutAction action, const QString &name, bool isGesture, ShortcutController::KeyFlags keyFlags = {}); + void onActionProgress(ShortcutAction action, qreal progress, const QString &name); + void onActionFinish(ShortcutAction action, const QString &name, bool isTriggered); + +private Q_SLOTS: + void onModifierReleased(QKeyEvent *event); + void onQuickSwitchTimeout(); + +private: + void updateWorkspaceSwipe(qreal cb); + void finishWorkspaceSwipe(); + void taskswitchAction(bool isRepeat, bool isSameApp, bool isPrev); + + // dynamic bounce check: true when cb pushes beyond workspace boundary + inline bool isWorkspaceBounce(qreal cb, int currentIndex, int wsCount) const + { + return (cb > 0 && currentIndex >= wsCount - 1) || (cb < 0 && currentIndex <= 0); + } + + Workspace *const m_workspace; + SessionSwitcher *const m_switcher; + SessionMultitaskView *const m_multitaskView; + WaylandServer *const m_runtime; + CompositorInputFilter *const m_inputFilter; + ShortcutController *const m_controller; + ShortcutManagerV3 *const m_protocol; + qreal m_desktopOffset = 0; + int m_fromId = 0; + int m_toId = 0; + bool m_slideEnable = false; + + QTimer *m_quickSwitchTimer = nullptr; + ShortcutAction m_currentAction; + bool m_quickSwitchPending = false; + quint32 m_taskAltCount = 0; +}; diff --git a/src/modules/snap-target/CMakeLists.txt b/src/modules/snap-target/CMakeLists.txt new file mode 100644 index 0000000000..aeea45a499 --- /dev/null +++ b/src/modules/snap-target/CMakeLists.txt @@ -0,0 +1,19 @@ +find_package(TreelandProtocols REQUIRED) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS QuickPrivate) +endif() + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-snap-target-unstable-v1.xml + BASENAME treeland-snap-target-unstable-v1 +) + +impl_treeland( + NAME + module_snap_target + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/snap-target/snaphandler.h + ${CMAKE_SOURCE_DIR}/src/modules/snap-target/snaphandler.cpp + INCLUDE + $ +) diff --git a/src/modules/snap-target/snaphandler.cpp b/src/modules/snap-target/snaphandler.cpp new file mode 100644 index 0000000000..46c1fbfdde --- /dev/null +++ b/src/modules/snap-target/snaphandler.cpp @@ -0,0 +1,317 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "snaphandler.h" + +#include "qwayland-server-treeland-snap-target-unstable-v1.h" +#include "surface/surfacewrapper.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +struct SnappableTarget +{ + QRectF rect; + QPointer shellSurface; + + bool operator==(const SnappableTarget &other) const + { + return rect == other.rect && shellSurface == other.shellSurface; + } +}; + +SurfaceWrapper *snapMaskWrapperFor(QQuickItem *item) +{ + for (QQuickItem *parent = item; parent; parent = parent->parentItem()) { + if (auto *wrapper = qobject_cast(parent)) + return wrapper; + } + return nullptr; +} + +QList collectSnappableTargets(WOutputRenderWindow *renderWindow) +{ + QList result; + if (!renderWindow || !renderWindow->contentItem()) + return result; + + QList> outputItems; + + auto items = + WOutputRenderWindow::paintOrderItemList(renderWindow->contentItem(), + [&outputItems](QQuickItem *item) -> bool { + if (!item->isVisible()) + return false; + if (qobject_cast(item)) { + outputItems.append(item); + return false; + } + if (qobject_cast(item)) + return true; + return false; + }); + + for (auto it = items.crbegin(); it != items.crend(); ++it) { + if (!*it) + continue; + auto surfaceItem = qobject_cast(*it); + if (!surfaceItem) + continue; + // Snap-mask surfaces are overlay masks and never snap targets. + if (auto *wrapper = snapMaskWrapperFor(surfaceItem); wrapper && wrapper->isSnapMask()) + continue; + SnappableTarget target; + target.rect = surfaceItem->mapRectToScene(surfaceItem->boundingRect()); + target.shellSurface = surfaceItem->shellSurface(); + result.append(target); + } + + for (const auto &item : std::as_const(outputItems)) { + if (!item) + continue; + SnappableTarget target; + target.rect = item->mapRectToScene(item->boundingRect()); + result.append(target); + } + + return result; +} + +SnappableTarget hitTestSnappableTarget(const QPointF &cursorPos, + const QList &snapshot) +{ + for (const auto &target : snapshot) { + if (target.rect.contains(cursorPos)) + return target; + } + return { }; +} +} // namespace + +class SnapTargetV1Private + : public QObject + , public QtWaylandServer::treeland_snap_target_v1 +{ +public: + explicit SnapTargetV1Private(QObject *parent = nullptr) + : QObject(parent) + , QtWaylandServer::treeland_snap_target_v1() + { + } + + ~SnapTargetV1Private() override + { + stopSnapping(); + } + + wl_global *globalHandle() const + { + return m_global; + } + + WOutputRenderWindow *renderWindow() const + { + return m_renderWindow; + } + + void setRenderWindow(WOutputRenderWindow *renderWindow) + { + m_renderWindow = renderWindow; + } + +protected: + void start(Resource *resource, struct ::wl_resource *seatResource, uint32_t events) override; + void stop(Resource *resource) override; + void destroy(Resource *resource) override; + void destroy_resource(Resource *resource) override; + +private: + void updateSnappableTarget(); + void sendSnappableTarget(const SnappableTarget &target); + void stopSnapping(); + + QPointer m_renderWindow; + QPointer m_seat; + + Resource *m_activeResource = nullptr; + bool m_pidfdEnabled = false; + QMetaObject::Connection m_cursorConn; + QList m_snapshot; + SnappableTarget m_lastTarget; +}; + +void SnapTargetV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void SnapTargetV1Private::destroy_resource(Resource *resource) +{ + if (m_activeResource == resource) + stopSnapping(); +} + +void SnapTargetV1Private::start(Resource *resource, + struct ::wl_resource *seatResource, + uint32_t events) +{ + // Only one snap session may be active across all clients. start on an + // already active snap object is ignored; start by another client fails + // with the snap_busy reason. + if (m_activeResource) { + if (m_activeResource != resource) + send_failed(resource->handle, failure_reason_snap_busy); + return; + } + + WSeat *seat = nullptr; + if (seatResource) { + auto *seatClient = wlr_seat_client_from_resource(seatResource); + if (seatClient) + seat = WSeat::fromHandle(seatClient->seat); + } + + m_activeResource = resource; + m_seat = seat; + m_pidfdEnabled = events & event_type_pidfd; + + m_snapshot = collectSnappableTargets(m_renderWindow); + + if (seat && seat->cursor()) { + m_cursorConn = connect(seat->cursor(), + &WCursor::positionChanged, + this, + &SnapTargetV1Private::updateSnappableTarget); + } + + updateSnappableTarget(); +} + +void SnapTargetV1Private::stop(Resource *resource) +{ + if (m_activeResource != resource) + return; + stopSnapping(); +} + +void SnapTargetV1Private::stopSnapping() +{ + if (!m_activeResource) + return; + + m_activeResource = nullptr; + m_seat = nullptr; + m_pidfdEnabled = false; + + if (m_cursorConn) { + disconnect(m_cursorConn); + m_cursorConn = QMetaObject::Connection(); + } + + m_snapshot.clear(); + m_lastTarget = SnappableTarget(); +} + +void SnapTargetV1Private::updateSnappableTarget() +{ + if (!m_activeResource) + return; + + auto seat = m_seat; + if (!seat || !seat->cursor()) + return; + + auto cursorPos = seat->cursor()->position(); + auto target = hitTestSnappableTarget(cursorPos, m_snapshot); + + if (target == m_lastTarget) + return; + + m_lastTarget = target; + sendSnappableTarget(target); +} + +void SnapTargetV1Private::sendSnappableTarget(const SnappableTarget &target) +{ + if (!m_activeResource) + return; + + // The pidfd event is sent only when the client enabled it and the target + // has a determinable owning process; it always precedes the snap_region + // event that commits it. + if (m_pidfdEnabled && !target.rect.isEmpty() && target.shellSurface) { + int pidfd = target.shellSurface->pidFD(); + if (pidfd >= 0) + send_pidfd(m_activeResource->handle, pidfd); + } + + const QRectF ®ion = target.rect; + if (region.isValid() && !region.isEmpty()) { + send_snap_region(m_activeResource->handle, + static_cast(region.x()), + static_cast(region.y()), + static_cast(region.width()), + static_cast(region.height())); + } else { + send_snap_region(m_activeResource->handle, 0, 0, 0, 0); + } +} + +SnapTargetV1::SnapTargetV1(QObject *parent) + : QObject(parent) + , WServerInterface() + , d(std::make_unique()) +{ +} + +SnapTargetV1::~SnapTargetV1() = default; + +WOutputRenderWindow *SnapTargetV1::outputRenderWindow() const +{ + return d->renderWindow(); +} + +void SnapTargetV1::setOutputRenderWindow(WOutputRenderWindow *renderWindow) +{ + d->setRenderWindow(renderWindow); +} + +QByteArrayView SnapTargetV1::interfaceName() const +{ + return QtWaylandServer::treeland_snap_target_v1::interfaceName(); +} + +void SnapTargetV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void SnapTargetV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *SnapTargetV1::global() const +{ + return d->globalHandle(); +} diff --git a/src/modules/snap-target/snaphandler.h b/src/modules/snap-target/snaphandler.h new file mode 100644 index 0000000000..72f0d63434 --- /dev/null +++ b/src/modules/snap-target/snaphandler.h @@ -0,0 +1,44 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutputRenderWindow; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class SnapTargetV1Private; + +class SnapTargetV1 + : public QObject + , public WServerInterface +{ + Q_OBJECT +public: + explicit SnapTargetV1(QObject *parent = nullptr); + ~SnapTargetV1() override; + + static constexpr int InterfaceVersion = 1; + + WOutputRenderWindow *outputRenderWindow() const; + void setOutputRenderWindow(WOutputRenderWindow *renderWindow); + + QByteArrayView interfaceName() const override; + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; diff --git a/src/modules/wallpaper-color/CMakeLists.txt b/src/modules/wallpaper-color/CMakeLists.txt new file mode 100644 index 0000000000..5ce74e9c28 --- /dev/null +++ b/src/modules/wallpaper-color/CMakeLists.txt @@ -0,0 +1,20 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wallpaper-color-v1.xml + BASENAME treeland-wallpaper-color-v1 +) + +impl_treeland( + NAME + module_wallpapercolor + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/wallpaper-color/wallpapercolorinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/wallpaper-color/wallpapercolorinterfacev1.cpp + LINK + Wlroots::wlroots + Waylib::WaylibServer + Qt6::Core + Qt6::Gui + Qt6::Quick +) diff --git a/src/modules/wallpaper-color/wallpapercolorinterfacev1.cpp b/src/modules/wallpaper-color/wallpapercolorinterfacev1.cpp new file mode 100644 index 0000000000..5b3bff2e07 --- /dev/null +++ b/src/modules/wallpaper-color/wallpapercolorinterfacev1.cpp @@ -0,0 +1,118 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wallpapercolorinterfacev1.h" +#include "common/treelandlogging.h" +#include "qwayland-server-treeland-wallpaper-color-v1.h" + +#include +#include + +#include +#include +#include +#include + +class WallpaperColorInterfaceV1Private : public QtWaylandServer::treeland_wallpaper_color_manager_v1 +{ +public: + WallpaperColorInterfaceV1Private(WallpaperColorInterfaceV1 *_q); + wl_global *global() const; + + WallpaperColorInterfaceV1 *q; + QMap> watch_lists; + QMap color_map; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void watch(Resource *resource, const QString &output) override; + void unwatch(Resource *resource, const QString &output) override; +}; + +WallpaperColorInterfaceV1Private::WallpaperColorInterfaceV1Private(WallpaperColorInterfaceV1 *_q) + : QtWaylandServer::treeland_wallpaper_color_manager_v1() + , q(_q) +{ +} + +wl_global *WallpaperColorInterfaceV1Private::global() const +{ + return m_global; +} + +void WallpaperColorInterfaceV1Private::destroy_resource(Resource *resource) +{ + watch_lists.remove(resource->handle); +} + +void WallpaperColorInterfaceV1Private::destroy(Resource *resource) { + wl_resource_destroy(resource->handle); +} + +void WallpaperColorInterfaceV1Private::watch(Resource *resource, const QString &output) +{ + if (!color_map.contains(output)) { + qCWarning(lcTlWallpaperColor) + << QString("Wallpaper info for output:(%1) never set, will ignore " + "this requset!") + .arg(output); + return; + } + + auto isDark = color_map[output]; + qCDebug(lcTlWallpaperColor) << QString("New watch requset for output:(%1), it's wallpaper is %2") + .arg(output, isDark ? "dark" : "light"); + send_output_color(resource->handle, output, isDark); + watch_lists[resource->handle].append(output); +} + +void WallpaperColorInterfaceV1Private::unwatch(Resource *resource, const QString &output) +{ + watch_lists[resource->handle].removeOne(output); +} + +WallpaperColorInterfaceV1::WallpaperColorInterfaceV1(QObject *parent) + : QObject(parent) + , d(new WallpaperColorInterfaceV1Private(this)) +{ +} + +WallpaperColorInterfaceV1::~WallpaperColorInterfaceV1() = default; + +void WallpaperColorInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void WallpaperColorInterfaceV1::destroy([[maybe_unused]] WServer *server) { + d->globalRemove(); +} + +wl_global *WallpaperColorInterfaceV1::global() const +{ + return d->global(); +} + +void WallpaperColorInterfaceV1::updateWallpaperColor(const QString &output, bool isDarkType) +{ + if (d->color_map.contains(output)) { + if (d->color_map[output] == isDarkType) + return; + } + qCDebug(lcTlWallpaperColor) + << QString("Wallpaper info for output:(%1) changed, it's wallpaper is %2") + .arg(output, isDarkType ? "dark" : "light"); + + d->color_map[output] = isDarkType; + for (auto i = d->watch_lists.cbegin(), end = d->watch_lists.cend(); i != end; ++i) + if (i.value().contains(output)) + d->send_output_color(i.key(), + output, + isDarkType); +} + +QByteArrayView WallpaperColorInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} diff --git a/src/modules/wallpaper-color/wallpapercolorinterfacev1.h b/src/modules/wallpaper-color/wallpapercolorinterfacev1.h new file mode 100644 index 0000000000..15e8b260ab --- /dev/null +++ b/src/modules/wallpaper-color/wallpapercolorinterfacev1.h @@ -0,0 +1,35 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class WallpaperColorInterfaceV1Private; +class WallpaperColorInterfaceV1 + : public QObject + , public WAYLIB_SERVER_NAMESPACE::WServerInterface +{ + Q_OBJECT + +public: + explicit WallpaperColorInterfaceV1(QObject *parent = nullptr); + ~WallpaperColorInterfaceV1() override; + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; + Q_INVOKABLE void updateWallpaperColor(const QString &output, bool isDarkType); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; diff --git a/src/modules/wallpaper/CMakeLists.txt b/src/modules/wallpaper/CMakeLists.txt new file mode 100644 index 0000000000..0bd88a7b98 --- /dev/null +++ b/src/modules/wallpaper/CMakeLists.txt @@ -0,0 +1,25 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wallpaper-manager-unstable-v1.xml + BASENAME treeland-wallpaper-manager-unstable-v1 +) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wallpaper-shell-unstable-v1.xml + BASENAME treeland-wallpaper-shell-unstable-v1 +) + +impl_treeland( + NAME + module_wallpaper + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/wallpaper/wallpapermanagerinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/wallpaper/wallpapermanagerinterfacev1.cpp + ${CMAKE_SOURCE_DIR}/src/modules/wallpaper/wallpapershellinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/wallpaper/wallpapershellinterfacev1.cpp + ${CMAKE_SOURCE_DIR}/src/modules/wallpaper/wallpapernotifierinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/wallpaper/wallpapernotifierinterfacev1.cpp + INCLUDE + $ +) diff --git a/src/modules/wallpaper/wallpapermanagerinterfacev1.cpp b/src/modules/wallpaper/wallpapermanagerinterfacev1.cpp new file mode 100644 index 0000000000..3196697366 --- /dev/null +++ b/src/modules/wallpaper/wallpapermanagerinterfacev1.cpp @@ -0,0 +1,246 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wallpapermanagerinterfacev1.h" +#include "session/session.h" +#include "qwayland-server-treeland-wallpaper-manager-unstable-v1.h" +#include "workspace.h" +#include "core/waylandserver.h" + +#include +#include +#include +#include + +#include +#include + +#include + +static QList s_wallpapers; + +static WOutput *outputFromResource(wl_resource *resource) +{ + if (!resource) + return nullptr; + + auto *nativeOutput = wlr_output_from_resource(resource); + if (!nativeOutput) + return nullptr; + + return WOutput::fromHandle(nativeOutput); +} + +class TreelandWallpaperManagerInterfaceV1Private : public QtWaylandServer::treeland_wallpaper_manager_v1 +{ +public: + explicit TreelandWallpaperManagerInterfaceV1Private(TreelandWallpaperManagerInterfaceV1 *_q); + wl_global *global() const; + + TreelandWallpaperManagerInterfaceV1 *q = nullptr; +protected: + void destroy(Resource *resource) override; + void get_treeland_wallpaper(Resource *resource, + uint32_t id, + struct ::wl_resource *output, + struct ::wl_resource *surface) override; + +}; + +TreelandWallpaperManagerInterfaceV1Private::TreelandWallpaperManagerInterfaceV1Private(TreelandWallpaperManagerInterfaceV1 *_q) + : QtWaylandServer::treeland_wallpaper_manager_v1() + , q(_q) +{ +} + +wl_global *TreelandWallpaperManagerInterfaceV1Private::global() const +{ + return m_global; +} + +void TreelandWallpaperManagerInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void TreelandWallpaperManagerInterfaceV1Private::get_treeland_wallpaper(Resource *resource, + uint32_t id, + struct ::wl_resource *output, + struct ::wl_resource *surface) +{ + auto *wOutput = outputFromResource(output); + if (!wOutput) { + wl_resource_post_error(resource->handle, + WL_DISPLAY_ERROR_INVALID_OBJECT, + "Invalid output resource"); + return; + } + + wl_resource *wallpaperResource = wl_resource_create(resource->client(), + &treeland_wallpaper_v1_interface, + resource->version(), + id); + if (!wallpaperResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto wallpaper = new TreelandWallpaperInterfaceV1( + wOutput, q->session()->username(), wallpaperResource, surface, q); + s_wallpapers.append(wallpaper); + + QObject::connect(wallpaper, &QObject::destroyed, [wallpaper]() { + s_wallpapers.removeOne(wallpaper); + }); + + Q_EMIT q->wallpaperCreated(wallpaper); +} + +TreelandWallpaperManagerInterfaceV1::TreelandWallpaperManagerInterfaceV1(Session *session) + : SessionComponent(session) + , d(new TreelandWallpaperManagerInterfaceV1Private(this)) +{ +} + +TreelandWallpaperManagerInterfaceV1::~TreelandWallpaperManagerInterfaceV1() = default; + +void TreelandWallpaperManagerInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void TreelandWallpaperManagerInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *TreelandWallpaperManagerInterfaceV1::global() const +{ + return d->global(); +} + +QByteArrayView TreelandWallpaperManagerInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} + +class TreelandWallpaperInterfaceV1Private : public QtWaylandServer::treeland_wallpaper_v1 +{ +public: + TreelandWallpaperInterfaceV1Private(TreelandWallpaperInterfaceV1 *_q, + WOutput *output, + const QString &name, + wl_resource *_resource, + wl_resource *refsurface); + + TreelandWallpaperInterfaceV1 *q = nullptr; + QPointer wOutput; + QString userName; + wl_resource *resource = nullptr; + wl_resource *refSurfaceResource = nullptr; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void set_image_source(Resource *resource, const QString &fileSource, uint32_t nativeRole) override; + void set_video_source(Resource *resource, const QString &fileSource, uint32_t nativeRole) override; +}; + +TreelandWallpaperInterfaceV1Private::TreelandWallpaperInterfaceV1Private(TreelandWallpaperInterfaceV1 *_q, + WOutput *output, + const QString &name, + wl_resource *_resource, + wl_resource *refsurface) + : QtWaylandServer::treeland_wallpaper_v1(_resource) + , q(_q) + , wOutput(output) + , userName(name) + , resource(_resource) + , refSurfaceResource(refsurface) +{ +} + +void TreelandWallpaperInterfaceV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + delete q; +} + +void TreelandWallpaperInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void TreelandWallpaperInterfaceV1Private::set_image_source([[maybe_unused]] Resource *resource, + const QString &fileSource, + uint32_t nativeRole) +{ + TreelandWallpaperInterfaceV1::WallpaperRoles roles = + static_cast(nativeRole); + Workspace *workspace = static_cast(q->parent())->session()->workspace(); + Q_ASSERT(workspace); + Q_EMIT q->imageSourceChanged(workspace->currentIndex(), fileSource, roles); +} + +void TreelandWallpaperInterfaceV1Private::set_video_source([[maybe_unused]] Resource *resource, + const QString &fileSource, + uint32_t nativeRole) +{ + TreelandWallpaperInterfaceV1::WallpaperRoles roles = + static_cast(nativeRole); + Workspace *workspace = static_cast(q->parent())->session()->workspace(); + Q_ASSERT(workspace); + Q_EMIT q->videoSourceChanged(workspace->currentIndex(), fileSource, roles); +} + +TreelandWallpaperInterfaceV1::TreelandWallpaperInterfaceV1(WOutput *output, + const QString &userName, + wl_resource *resource, + wl_resource *refsurface, + QObject *parent) + : QObject(parent) + , d(new TreelandWallpaperInterfaceV1Private(this, output, userName, resource, refsurface)) +{ +} + +TreelandWallpaperInterfaceV1::~TreelandWallpaperInterfaceV1() = default; + +WSurface *TreelandWallpaperInterfaceV1::referenceWSurface() const +{ + if (!d->refSurfaceResource) { + return nullptr; + } + + return WSurface::fromHandle(wlr_surface_from_resource(d->refSurfaceResource)); +} + +QString TreelandWallpaperInterfaceV1::userName() const +{ + return d->userName; +} + +WOutput *TreelandWallpaperInterfaceV1::wOutput() const +{ + auto *output = d->wOutput.data(); + return output && output->handle() ? output : nullptr; +} + +void TreelandWallpaperInterfaceV1::sendError(const QString &source, Error error) +{ + d->send_failed(source, error); +} + +void TreelandWallpaperInterfaceV1::sendChanged(WallpaperRoles roles, WallpaperType type, const QString &source) +{ + d->send_changed(roles, type, source); +} + +TreelandWallpaperInterfaceV1 *TreelandWallpaperInterfaceV1::getReferenceWallpaperInterfaceFromSurface(WSurface *surface) +{ + for (TreelandWallpaperInterfaceV1 *wallpaperInterface : std::as_const(s_wallpapers)) { + if (wallpaperInterface->referenceWSurface() == surface) { + return wallpaperInterface; + } + } + + return nullptr; +} diff --git a/src/modules/wallpaper/wallpapermanagerinterfacev1.h b/src/modules/wallpaper/wallpapermanagerinterfacev1.h new file mode 100644 index 0000000000..823805d1f0 --- /dev/null +++ b/src/modules/wallpaper/wallpapermanagerinterfacev1.h @@ -0,0 +1,93 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include +#include + +#include "session/sessioncomponent.h" +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class TreelandWallpaperInterfaceV1; +class TreelandWallpaperManagerInterfaceV1Private; +class TreelandWallpaperManagerInterfaceV1 : public SessionComponent , public WServerInterface +{ + Q_OBJECT +public: + explicit TreelandWallpaperManagerInterfaceV1(Session *session); + ~TreelandWallpaperManagerInterfaceV1() override; + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; + +Q_SIGNALS: + void wallpaperCreated(TreelandWallpaperInterfaceV1 *interface); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; + +class TreelandWallpaperInterfaceV1Private; +class TreelandWallpaperInterfaceV1 : public QObject +{ + Q_OBJECT +public: + enum Error { + AlreadyUsed = 0, + InvalidSource = 1, + PermissionDenied = 2, + }; + + enum WallpaperType { + Image = 0, + Video = 1, + }; + + enum WallpaperRole { + Desktop = 0x1, + Lockscreen = 0x2 + }; + Q_DECLARE_FLAGS(WallpaperRoles, WallpaperRole) + Q_FLAG(WallpaperRoles) + + ~TreelandWallpaperInterfaceV1() override; + + WSurface *referenceWSurface() const; + QString userName() const; + WOutput *wOutput() const; + + void sendError(const QString &source, Error error); + void sendChanged(WallpaperRoles roles, WallpaperType type, const QString &source); + + static TreelandWallpaperInterfaceV1 *getReferenceWallpaperInterfaceFromSurface(WSurface *surface); + +Q_SIGNALS: + void imageSourceChanged(int workspaceIndex, + const QString &fileSource, + WallpaperRoles roles); + void videoSourceChanged(int workspaceIndex, + const QString &fileSource, + WallpaperRoles roles); + +private: + explicit TreelandWallpaperInterfaceV1(WOutput *output, + const QString &userName, + wl_resource *resource, + wl_resource *refsurface, + QObject *parent = nullptr); + +private: + friend class TreelandWallpaperManagerInterfaceV1Private; + std::unique_ptr d; +}; diff --git a/src/modules/wallpaper/wallpapernotifierinterfacev1.cpp b/src/modules/wallpaper/wallpapernotifierinterfacev1.cpp new file mode 100644 index 0000000000..07c0015a09 --- /dev/null +++ b/src/modules/wallpaper/wallpapernotifierinterfacev1.cpp @@ -0,0 +1,86 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wallpapernotifierinterfacev1.h" +#include "qwayland-server-treeland-wallpaper-shell-unstable-v1.h" + +class TreelandWallpaperNotifierInterfaceV1Private : public QtWaylandServer::treeland_wallpaper_notifier_v1 +{ +public: + TreelandWallpaperNotifierInterfaceV1Private(TreelandWallpaperNotifierInterfaceV1 *_q); + wl_global *global() const; + + TreelandWallpaperNotifierInterfaceV1 *q = nullptr; + +protected: + void bind_resource(Resource *resource) override; + void destroy(Resource *resource) override; +}; + +TreelandWallpaperNotifierInterfaceV1Private::TreelandWallpaperNotifierInterfaceV1Private(TreelandWallpaperNotifierInterfaceV1 *_q) + : QtWaylandServer::treeland_wallpaper_notifier_v1() + , q(_q) +{ +} + +wl_global *TreelandWallpaperNotifierInterfaceV1Private::global() const +{ + return m_global; +} + +void TreelandWallpaperNotifierInterfaceV1Private::bind_resource(Resource *resource) +{ + Q_EMIT q->bound(resource->handle); +} + +void TreelandWallpaperNotifierInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +TreelandWallpaperNotifierInterfaceV1::TreelandWallpaperNotifierInterfaceV1(QObject *parent) + : QObject(parent) + , d(new TreelandWallpaperNotifierInterfaceV1Private(this)) +{ +} + +void TreelandWallpaperNotifierInterfaceV1::sendAdd(TreelandWallpaperInterfaceV1::WallpaperType type, const QString &fileSource) +{ + for (const auto &resource : d->resourceMap()) { + d->send_add(resource->handle, type, fileSource); + } +} + +void TreelandWallpaperNotifierInterfaceV1::sendRemove(const QString &fileSource) +{ + for (const auto &resource : d->resourceMap()) { + d->send_remove(resource->handle, fileSource); + } +} + +TreelandWallpaperNotifierInterfaceV1::~TreelandWallpaperNotifierInterfaceV1() = default; + +void TreelandWallpaperNotifierInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void TreelandWallpaperNotifierInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *TreelandWallpaperNotifierInterfaceV1::global() const +{ + return d->global(); +} + +QByteArrayView TreelandWallpaperNotifierInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} + +void TreelandWallpaperNotifierInterfaceV1::sendAddForResource(wl_resource *resource, TreelandWallpaperInterfaceV1::WallpaperType type, const QString &fileSource) +{ + d->send_add(resource, type, fileSource); +} diff --git a/src/modules/wallpaper/wallpapernotifierinterfacev1.h b/src/modules/wallpaper/wallpapernotifierinterfacev1.h new file mode 100644 index 0000000000..103113fa50 --- /dev/null +++ b/src/modules/wallpaper/wallpapernotifierinterfacev1.h @@ -0,0 +1,43 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "wallpapermanagerinterfacev1.h" + +#include +#include +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class TreelandWallpaperNotifierInterfaceV1Private; +class TreelandWallpaperNotifierInterfaceV1 : public QObject , public WServerInterface +{ + Q_OBJECT +public: + explicit TreelandWallpaperNotifierInterfaceV1(QObject *parent = nullptr); + ~TreelandWallpaperNotifierInterfaceV1() override; + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; + + void sendAddForResource(wl_resource *resource, TreelandWallpaperInterfaceV1::WallpaperType type, const QString &fileSource); + void sendAdd(TreelandWallpaperInterfaceV1::WallpaperType type, const QString &fileSource); + void sendRemove(const QString &fileSource); + +Q_SIGNALS: + void bound(wl_resource *resource); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; diff --git a/src/modules/wallpaper/wallpapershellinterfacev1.cpp b/src/modules/wallpaper/wallpapershellinterfacev1.cpp new file mode 100644 index 0000000000..b6e2238756 --- /dev/null +++ b/src/modules/wallpaper/wallpapershellinterfacev1.cpp @@ -0,0 +1,253 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wallpapersurface.h" +#include "wallpapershellinterfacev1.h" +#include "qwayland-server-treeland-wallpaper-shell-unstable-v1.h" + +static QList s_wallpaperSurfaces; + +class TreelandWallpaperShellInterfaceV1Private : public QtWaylandServer::treeland_wallpaper_shell_v1 +{ +public: + TreelandWallpaperShellInterfaceV1Private(TreelandWallpaperShellInterfaceV1 *_q); + wl_global *global() const; + + TreelandWallpaperShellInterfaceV1 *q = nullptr; + QList producedWallpapers; + +protected: + void destroy(Resource *resource) override; + void get_treeland_wallpaper_surface(Resource *resource, + uint32_t id, + struct ::wl_resource *surface, + const QString &file_source) override; +}; + +TreelandWallpaperShellInterfaceV1Private::TreelandWallpaperShellInterfaceV1Private(TreelandWallpaperShellInterfaceV1 *_q) + : QtWaylandServer::treeland_wallpaper_shell_v1() + , q(_q) +{ +} + +wl_global *TreelandWallpaperShellInterfaceV1Private::global() const +{ + return m_global; +} + +void TreelandWallpaperShellInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void TreelandWallpaperShellInterfaceV1Private::get_treeland_wallpaper_surface(Resource *resource, + uint32_t id, + wl_resource *surface, + const QString &file_source) +{ + if (!surface) { + wl_resource_post_error(resource->handle, 0, "surface resource is NULL!"); + return; + } + + producedWallpapers.append(file_source); + wl_resource *surfaceResource = wl_resource_create(resource->client(), + &treeland_wallpaper_surface_v1_interface, + resource->version(), + id); + if (!surfaceResource) { + wl_client_post_no_memory(resource->client()); + return; + } + + auto wallpaperSurface = new TreelandWallpaperSurfaceInterfaceV1(surface, file_source, surfaceResource); + s_wallpaperSurfaces.append(wallpaperSurface); + + QObject::connect(wallpaperSurface, &TreelandWallpaperSurfaceInterfaceV1::beforeDestroy, [wallpaperSurface, this]() { + s_wallpaperSurfaces.removeOne(wallpaperSurface); + producedWallpapers.removeOne(wallpaperSurface->source()); + }); + + Q_EMIT q->wallpaperSurfaceAdded(wallpaperSurface); +} + +TreelandWallpaperShellInterfaceV1::TreelandWallpaperShellInterfaceV1(QObject *parent) + : QObject(parent) + , d(new TreelandWallpaperShellInterfaceV1Private(this)) +{ +} + +QList TreelandWallpaperShellInterfaceV1::producedWallpapers() const +{ + return d->producedWallpapers; +} + +TreelandWallpaperShellInterfaceV1::~TreelandWallpaperShellInterfaceV1() = default; + +void TreelandWallpaperShellInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void TreelandWallpaperShellInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *TreelandWallpaperShellInterfaceV1::global() const +{ + return d->global(); +} + +QByteArrayView TreelandWallpaperShellInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} + +class TreelandWallpaperSurfaceInterfaceV1Private : public QtWaylandServer::treeland_wallpaper_surface_v1 +{ +public: + TreelandWallpaperSurfaceInterfaceV1Private(TreelandWallpaperSurfaceInterfaceV1 *_q, + const QString &source, + wl_resource *surface, + wl_resource *_resource); + + TreelandWallpaperSurfaceInterfaceV1 *q; + wl_resource *surfaceResource = nullptr; + wl_resource *resource = nullptr; + WallpaperSurface *surface = nullptr; + QString wallpaperSource; + bool wallpaperReady = false; + +protected: + void destroy_resource(Resource *resource) override; + void destroy(Resource *resource) override; + void source_failed(Resource *resource, + uint32_t error) override; + void ready(Resource *resource) override; +}; + +TreelandWallpaperSurfaceInterfaceV1Private::TreelandWallpaperSurfaceInterfaceV1Private(TreelandWallpaperSurfaceInterfaceV1 *_q, + const QString &source, + wl_resource *surface, + wl_resource *_resource) + : QtWaylandServer::treeland_wallpaper_surface_v1(_resource) + , q(_q) + , surfaceResource(surface) + , resource(_resource) + , wallpaperSource(source) +{ +} + +void TreelandWallpaperSurfaceInterfaceV1Private::destroy_resource([[maybe_unused]] Resource *resource) +{ + Q_EMIT q->beforeDestroy(); + delete q; +} + +void TreelandWallpaperSurfaceInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void TreelandWallpaperSurfaceInterfaceV1Private::source_failed([[maybe_unused]] Resource *resource, + uint32_t error) +{ + Q_EMIT q->failed(error); +} + +void TreelandWallpaperSurfaceInterfaceV1Private::ready([[maybe_unused]] Resource *resource) +{ + if (wallpaperReady) { + return; + } + + const auto markReady = [this] { + wallpaperReady = true; + Q_EMIT q->ready(); + }; + + if (q->wSurface()->mapped() || !q->wSurface()->bufferSize().isEmpty()) { + markReady(); + } else { + QObject::connect(q->wSurface(), &WSurface::commit, q, [markReady](quint32) { + markReady(); + }, Qt::SingleShotConnection); + } +} + +TreelandWallpaperSurfaceInterfaceV1::~TreelandWallpaperSurfaceInterfaceV1() +{ + // Owner rule: this object created the WallpaperSurface, release it (no + // QObject parent anymore). + delete d->surface; +} + +WSurface *TreelandWallpaperSurfaceInterfaceV1::wSurface() const +{ + return WSurface::fromHandle(wlr_surface_from_resource(d->surfaceResource)); +} + +QString TreelandWallpaperSurfaceInterfaceV1::source() const +{ + return d->wallpaperSource; +} + +wl_client *TreelandWallpaperSurfaceInterfaceV1::client() +{ + return d->resource->client; +} + +wl_resource *TreelandWallpaperSurfaceInterfaceV1::surfaceResource() +{ + return d->surfaceResource; +} + +TreelandWallpaperSurfaceInterfaceV1 *TreelandWallpaperSurfaceInterfaceV1::get(WSurface *surface) +{ + for (TreelandWallpaperSurfaceInterfaceV1 *surfaceInterface : std::as_const(s_wallpaperSurfaces)) { + if (surfaceInterface->wSurface() == surface) { + return surfaceInterface; + } + } + + return nullptr; +} + +TreelandWallpaperSurfaceInterfaceV1 *TreelandWallpaperSurfaceInterfaceV1::get(const QString &source) +{ + for (TreelandWallpaperSurfaceInterfaceV1 *surfaceInterface : std::as_const(s_wallpaperSurfaces)) { + if (surfaceInterface->source() == source) { + return surfaceInterface; + } + } + + return nullptr; +} + +void TreelandWallpaperSurfaceInterfaceV1::setPlay(bool value) +{ + if (value) { + d->send_play(); + } else { + d->send_pause(); + } +} + +void TreelandWallpaperSurfaceInterfaceV1::slowDown(uint32_t duration) +{ + d->send_slow_down(duration); +} + +bool TreelandWallpaperSurfaceInterfaceV1::wallpaperReady() +{ + return d->wallpaperReady; +} + +TreelandWallpaperSurfaceInterfaceV1::TreelandWallpaperSurfaceInterfaceV1(wl_resource *surface, + const QString &source, + wl_resource *resource) + : d(new TreelandWallpaperSurfaceInterfaceV1Private(this, source, surface, resource)) +{ + d->surface = new WallpaperSurface(this); +} diff --git a/src/modules/wallpaper/wallpapershellinterfacev1.h b/src/modules/wallpaper/wallpapershellinterfacev1.h new file mode 100644 index 0000000000..bbcb3f65f5 --- /dev/null +++ b/src/modules/wallpaper/wallpapershellinterfacev1.h @@ -0,0 +1,71 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class TreelandWallpaperSurfaceInterfaceV1; +class TreelandWallpaperShellInterfaceV1Private; +class TreelandWallpaperShellInterfaceV1 : public QObject , public WServerInterface +{ + Q_OBJECT +public: + explicit TreelandWallpaperShellInterfaceV1(QObject *parent = nullptr); + ~TreelandWallpaperShellInterfaceV1() override; + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; + QList producedWallpapers() const; + +Q_SIGNALS: + void wallpaperSurfaceAdded(TreelandWallpaperSurfaceInterfaceV1 *interface); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; + +class TreelandWallpaperSurfaceInterfaceV1Private; +class TreelandWallpaperSurfaceInterfaceV1 : public QObject +{ + Q_OBJECT +public: + ~TreelandWallpaperSurfaceInterfaceV1() override; + WSurface *wSurface() const; + QString source() const; + wl_client *client(); + wl_resource *surfaceResource(); + + static TreelandWallpaperSurfaceInterfaceV1 *get(WSurface *surface); + static TreelandWallpaperSurfaceInterfaceV1 *get(const QString &source); + void setPlay(bool value); + void slowDown(uint32_t duration = 3000); + bool wallpaperReady(); + +Q_SIGNALS: + void beforeDestroy(); + void failed(uint32_t error); + void ready(); + +private: + explicit TreelandWallpaperSurfaceInterfaceV1(wl_resource *surface, + const QString &source, + wl_resource *resource); + +private: + friend class TreelandWallpaperShellInterfaceV1Private; + std::unique_ptr d; +}; diff --git a/src/modules/window-transition/CMakeLists.txt b/src/modules/window-transition/CMakeLists.txt new file mode 100644 index 0000000000..65ae1c1676 --- /dev/null +++ b/src/modules/window-transition/CMakeLists.txt @@ -0,0 +1,18 @@ +find_package(TreelandProtocols 0.7.0 REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-window-transition-unstable-v1.xml + BASENAME treeland-window-transition-unstable-v1 +) + +impl_treeland( + NAME + module_window_transition + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/window-transition/windowtransitionmanagerinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/window-transition/windowtransitionmanagerinterfacev1.cpp + INCLUDE + $ + LINK + Qt6::Core +) diff --git a/src/modules/window-transition/windowtransitionmanagerinterfacev1.cpp b/src/modules/window-transition/windowtransitionmanagerinterfacev1.cpp new file mode 100644 index 0000000000..e944f1ad8a --- /dev/null +++ b/src/modules/window-transition/windowtransitionmanagerinterfacev1.cpp @@ -0,0 +1,458 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "windowtransitionmanagerinterfacev1.h" + +#include "common/treelandlogging.h" +#include "interfaces/windowtransition.h" +#include "qwayland-server-treeland-window-transition-unstable-v1.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE +using namespace Qt::StringLiterals; + +namespace { +constexpr int kPendingRectLifetimeMs = 60'000; +} // namespace + +class WindowTransitionManagerInterfaceV1Private; + +static const wlr_surface_role transitionSourceRole = { + .name = "treeland_window_transition_source_v1", + .no_object = true, + .client_commit = nullptr, + .commit = nullptr, + .map = nullptr, + .unmap = nullptr, + .destroy = nullptr, +}; + +class WindowTransitionSourceImpl : public WindowTransitionSource +{ +public: + explicit WindowTransitionSourceImpl(wlr_surface *handle) + : WindowTransitionSource() + , m_wrapper(new WSurface(handle)) + { + } + + ~WindowTransitionSourceImpl() override + { + const auto outputs = m_refs.keys(); + for (auto *output : outputs) + m_wrapper->leaveOutput(output); + delete m_wrapper; + } + + WSurface *surface() const override + { + return m_wrapper; + } + + void retain(const QList &outputs) override + { + for (auto *output : outputs) { + if (++m_refs[output] == 1) + m_wrapper->enterOutput(output); + } + m_wrapper->notifyFrameDone(); + } + + void release(const QList &outputs) override + { + for (auto *output : outputs) { + auto it = m_refs.find(output); + if (it == m_refs.end()) + continue; + if (--it.value() <= 0) { + m_refs.erase(it); + m_wrapper->leaveOutput(output); + } + } + } + +private: + WSurface *m_wrapper; + QHash m_refs; +}; + +struct SourceSurfaceEntry +{ + wlr_surface *handle = nullptr; + WindowTransitionSourceImpl *source = nullptr; + // Owns the native destroy listener registered on the source surface + // wrapper; destroying the entry detaches it automatically. + std::unique_ptr listenerOwner; +}; + +class WindowTransitionRectV1 : public QtWaylandServer::treeland_window_transition_rect_v1 +{ + friend class WindowTransitionManagerInterfaceV1; + +public: + WindowTransitionRectV1(WindowTransitionManagerInterfaceV1Private *manager, + const QString &token, + wl_resource *resource) + : QtWaylandServer::treeland_window_transition_rect_v1(resource) + , m_manager(manager) + , m_token(token) + , m_expiry(QDeadlineTimer(kPendingRectLifetimeMs)) + { + } + + ~WindowTransitionRectV1(); + + void notifyDiscarded() + { + if (m_closed) + return; + m_closed = true; + send_closed(); + } + + void detachManager() + { + m_manager = nullptr; + } + + bool isExpired() const + { + return m_expiry.hasExpired(); + } + + void associate(WindowTransitionTarget *target, WindowTransitionTarget *origin) + { + m_target = target; + if (m_target) { + m_target->setWindowTransitionRect(m_rect, origin); + m_target->setWindowTransitionSource(m_source.data()); + m_targetTransitionFinishedConnection = + QObject::connect(m_target.data(), + &WindowTransitionTarget::windowTransitionFinished, + [this] { + notifyDiscarded(); + }); + } + } + +protected: + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void destroy_resource(Resource *) override + { + delete this; + } + + void set_geometry(Resource * /*resource*/, + int32_t x, + int32_t y, + int32_t width, + int32_t height) override; + void set_source_surface(Resource * /*resource*/, struct ::wl_resource *surface) override; + +private: + void clearSourceSurface(); + void releaseSourceSurface(); + + WindowTransitionManagerInterfaceV1Private *m_manager; + QString m_token; + QDeadlineTimer m_expiry; + QRectF m_rect; + QMetaObject::Connection m_targetTransitionFinishedConnection; + QPointer m_target; + bool m_closed = false; + + // Owned by the manager, not by this rect; only a weak reference. + QPointer m_source; +}; + +class WindowTransitionManagerInterfaceV1Private + : public QtWaylandServer::treeland_window_transition_manager_v1 +{ +public: + explicit WindowTransitionManagerInterfaceV1Private(WindowTransitionManagerInterfaceV1 *q) + : QtWaylandServer::treeland_window_transition_manager_v1() + , q(q) + { + } + + ~WindowTransitionManagerInterfaceV1Private(); + + wl_global *globalHandle() const + { + return m_global; + } + + // Returns the shared handle for a transition source surface, creating and + // taking ownership of it on first use. + WindowTransitionSource *acquireSourceSurface(wlr_surface *surface); + + WindowTransitionManagerInterfaceV1 *q; + QHash m_pendingRects; + QHash m_sourceSurfaces; + +protected: + void destroy_global() override + { + qCDebug(lcTlWindowTransition) << "treeland_window_transition_manager_v1 global destroyed"; + } + + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void get_window_transition_rect(Resource *resource, + uint32_t rect_id, + const QString &token) override + { + auto *rectResource = wl_resource_create(resource->client(), + &treeland_window_transition_rect_v1_interface, + resource->version(), + rect_id); + if (!rectResource) { + wl_resource_post_no_memory(resource->handle); + return; + } + auto *rect = new WindowTransitionRectV1(this, token, rectResource); + // One rectangle per token: close an earlier one so the client can + // release it. + if (auto *previous = m_pendingRects.take(token)) + previous->notifyDiscarded(); + m_pendingRects.insert(token, rect); + q->ensurePendingSweepRunning(); + } +}; + +WindowTransitionManagerInterfaceV1Private::~WindowTransitionManagerInterfaceV1Private() +{ + for (auto *rect : std::as_const(m_pendingRects)) + rect->detachManager(); + m_pendingRects.clear(); + + // Deleting an entry destroys its listenerOwner, which detaches the + // surface destroy listener registered on the wrapper. + const auto entries = m_sourceSurfaces; + m_sourceSurfaces.clear(); + for (auto *entry : entries) { + delete entry->source; + delete entry; + } +} + +WindowTransitionSource *WindowTransitionManagerInterfaceV1Private::acquireSourceSurface( + wlr_surface *surface) +{ + if (auto *entry = m_sourceSurfaces.value(surface)) + return entry->source; + + auto *entry = new SourceSurfaceEntry; + entry->handle = surface; + entry->source = new WindowTransitionSourceImpl(surface); + entry->listenerOwner = std::make_unique(); + + // Track the native surface's destruction through the wrapper's listener + // graph instead of a hand-rolled wl_listener. Registering on the wrapper + // with the entry's owner token means destroying either side detaches the + // listener; the callback itself is safe to delete the entry from. + entry->source->surface() + ->listeners(entry->listenerOwner.get()) + ->add(&surface->events.destroy, this, [this, entry] { + m_sourceSurfaces.remove(entry->handle); + delete entry->source; + delete entry; + }); + + m_sourceSurfaces.insert(surface, entry); + return entry->source; +} + +WindowTransitionRectV1::~WindowTransitionRectV1() +{ + if (m_targetTransitionFinishedConnection) + QObject::disconnect(m_targetTransitionFinishedConnection); + + if (m_target) { + m_target->resetWindowTransition(); + } + + releaseSourceSurface(); + + if (m_manager && m_manager->m_pendingRects.value(m_token) == this) + m_manager->m_pendingRects.remove(m_token); +} + +void WindowTransitionRectV1::set_geometry(Resource *resource, + int32_t x, + int32_t y, + int32_t width, + int32_t height) +{ + if (width < 0 || height < 0) { + wl_resource_post_error(resource->handle, + error_invalid_geometry, + "set_geometry with negative size %dx%d", + width, + height); + return; + } + m_rect = QRectF(x, y, width, height); + + if (m_target) + m_target->updateWindowTransitionRect(m_rect); + + if (m_source) + m_source->surface()->notifyFrameDone(); +} + +void WindowTransitionRectV1::set_source_surface(Resource *resource, + struct ::wl_resource *surfaceResource) +{ + if (!surfaceResource) { + clearSourceSurface(); + return; + } + + wlr_surface *surface = wlr_surface_from_resource(surfaceResource); + if (!surface + || wl_resource_get_client(surfaceResource) != wl_resource_get_client(resource->handle)) { + wl_resource_post_error(resource->handle, + error_invalid_surface, + "set_source_surface: surface is not a wl_surface of this client"); + return; + } + + if (m_source && m_source->surface()->handle() == surface) + return; + + // The surface must not already carry a role. + if (!wlr_surface_set_role(surface, + &transitionSourceRole, + resource->handle, + error_invalid_surface)) { + return; + } + + releaseSourceSurface(); + + auto *source = m_manager->acquireSourceSurface(surface); + m_source = source; + + if (m_target) + m_target->setWindowTransitionSource(source); + + source->surface()->notifyFrameDone(); +} + +void WindowTransitionRectV1::clearSourceSurface() +{ + releaseSourceSurface(); + if (m_target) + m_target->clearWindowTransitionSource(); +} + +void WindowTransitionRectV1::releaseSourceSurface() +{ + // The handle is owned by the manager; only drop our weak reference. + m_source = nullptr; +} + +WindowTransitionManagerInterfaceV1::WindowTransitionManagerInterfaceV1(QObject *parent) + : QObject(parent) + , WServerInterface() + , d(new WindowTransitionManagerInterfaceV1Private(this)) + , m_pendingSweepTimer(this) +{ + m_pendingSweepTimer.setInterval(kPendingRectLifetimeMs / 2); + connect(&m_pendingSweepTimer, + &QTimer::timeout, + this, + &WindowTransitionManagerInterfaceV1::sweepPendingRects); +} + +WindowTransitionManagerInterfaceV1::~WindowTransitionManagerInterfaceV1() = default; + +QByteArrayView WindowTransitionManagerInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} + +void WindowTransitionManagerInterfaceV1::ensurePendingSweepRunning() +{ + if (!d->m_pendingRects.isEmpty() && !m_pendingSweepTimer.isActive()) + m_pendingSweepTimer.start(); +} + +void WindowTransitionManagerInterfaceV1::sweepPendingRects() +{ + for (auto it = d->m_pendingRects.begin(); it != d->m_pendingRects.end();) { + if (it.value()->isExpired()) { + it.value()->notifyDiscarded(); + it = d->m_pendingRects.erase(it); + } else { + ++it; + } + } + if (d->m_pendingRects.isEmpty()) + m_pendingSweepTimer.stop(); +} + +bool WindowTransitionManagerInterfaceV1::hasPendingWindowTransitionRect(const QString &token) const +{ + return d->m_pendingRects.contains(token); +} + +bool WindowTransitionManagerInterfaceV1::associatePendingRect(const QString &token, + WindowTransitionTarget *target, + WindowTransitionTarget *origin) +{ + auto it = d->m_pendingRects.find(token); + if (it == d->m_pendingRects.end()) + return false; + auto *rectObj = it.value(); + d->m_pendingRects.erase(it); + rectObj->associate(target, origin); + return true; +} + +void WindowTransitionManagerInterfaceV1::discardPendingRect(const QString &token) +{ + auto it = d->m_pendingRects.find(token); + if (it == d->m_pendingRects.end()) + return; + auto *rectObj = it.value(); + d->m_pendingRects.erase(it); + rectObj->notifyDiscarded(); +} + +void WindowTransitionManagerInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void WindowTransitionManagerInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *WindowTransitionManagerInterfaceV1::global() const +{ + return d->globalHandle(); +} diff --git a/src/modules/window-transition/windowtransitionmanagerinterfacev1.h b/src/modules/window-transition/windowtransitionmanagerinterfacev1.h new file mode 100644 index 0000000000..a13133f026 --- /dev/null +++ b/src/modules/window-transition/windowtransitionmanagerinterfacev1.h @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include +#include +#include + +#include + +class WindowTransitionTarget; +class WindowTransitionManagerInterfaceV1Private; + +class WindowTransitionManagerInterfaceV1 + : public QObject + , public WAYLIB_SERVER_NAMESPACE::WServerInterface +{ + Q_OBJECT +public: + explicit WindowTransitionManagerInterfaceV1(QObject *parent = nullptr); + ~WindowTransitionManagerInterfaceV1() override; + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; + + void discardPendingRect(const QString &token); + bool hasPendingWindowTransitionRect(const QString &token) const; + bool associatePendingRect(const QString &token, + WindowTransitionTarget *target, + WindowTransitionTarget *origin); + +protected: + void create(WAYLIB_SERVER_NAMESPACE::WServer *server) override; + void destroy(WAYLIB_SERVER_NAMESPACE::WServer *server) override; + wl_global *global() const override; + +private: + friend class WindowTransitionRectV1; + friend class WindowTransitionManagerInterfaceV1Private; + std::unique_ptr d; + QTimer m_pendingSweepTimer; + void ensurePendingSweepRunning(); + void sweepPendingRects(); +}; diff --git a/src/modules/wine-window-management/CMakeLists.txt b/src/modules/wine-window-management/CMakeLists.txt new file mode 100644 index 0000000000..f5f1b46b32 --- /dev/null +++ b/src/modules/wine-window-management/CMakeLists.txt @@ -0,0 +1,18 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wine-window-management-unstable-v1.xml + BASENAME treeland-wine-window-management-unstable-v1 +) + +impl_treeland( + NAME + module_wine_window_management + SOURCE + winewindowmanagement.h + winewindowmanagement.cpp + INCLUDE + $ + LINK + Qt6::Core +) diff --git a/src/modules/wine-window-management/winewindowmanagement.cpp b/src/modules/wine-window-management/winewindowmanagement.cpp new file mode 100644 index 0000000000..7097123d82 --- /dev/null +++ b/src/modules/wine-window-management/winewindowmanagement.cpp @@ -0,0 +1,415 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "winewindowmanagement.h" + +#include "common/treelandlogging.h" +#include "core/rootsurfacecontainer.h" +#include "qwayland-server-treeland-wine-window-management-unstable-v1.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class WineWindowControl; + +class WineWindowManagerPrivate : public QtWaylandServer::treeland_wine_window_manager_v1 +{ +public: + explicit WineWindowManagerPrivate(WineWindowManager *q) + : q(q) + { + } + + wl_global *globalHandle() const + { + return m_global; + } + + uint32_t nextWindowId() + { + return ++m_nextId; + } + + WineWindowControl *controlForId(uint32_t id) const + { + for (const auto &entry : m_controls) + if (entry.id == id) + return entry.control; + return nullptr; + } + + void registerControl(uint32_t id, WXdgToplevelSurface *toplevel, WineWindowControl *control) + { + m_controls.append({ id, toplevel, control }); + } + + void removeControl(WineWindowControl *control) + { + for (auto it = m_controls.begin(); it != m_controls.end(); ++it) { + if (it->control == control) { + m_controls.erase(it); + return; + } + } + } + +protected: + void destroy_global() override + { + qCDebug(lcTlProtocol) << "WineWindowManager global destroyed"; + } + + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void get_window_control(Resource *resource, + uint32_t id, + struct ::wl_resource *toplevelResource) override; + +private: + struct ControlEntry + { + uint32_t id; + WXdgToplevelSurface *toplevel{ nullptr }; + WineWindowControl *control{ nullptr }; + }; + + WineWindowManager *q{ nullptr }; + uint32_t m_nextId = 0; + QList m_controls; +}; + +class WineWindowControl + : public QObject + , public QtWaylandServer::treeland_wine_window_control_v1 +{ +public: + WineWindowControl(QObject *parent, + WineWindowManagerPrivate *manager, + uint32_t windowId, + SurfaceWrapper *wrapper, + wl_client *client, + int version, + uint32_t id) + : QObject(parent) + , QtWaylandServer::treeland_wine_window_control_v1(client, id, version) + , m_manager(manager) + , m_windowId(windowId) + , m_wrapper(wrapper) + { + Q_ASSERT_X(m_wrapper, Q_FUNC_INFO, "wrapper must not be null"); + Q_ASSERT_X(m_wrapper->shellSurface(), + Q_FUNC_INFO, + "wrapper->shellSurface() must not be null"); + + connect(m_wrapper, &SurfaceWrapper::aboutToBeInvalidated, this, [this] { + if (m_manager) { + m_manager->removeControl(this); + m_manager = nullptr; + } + m_wrapper = nullptr; + }); + connect(m_wrapper, &QQuickItem::xChanged, this, [this] { + if (!m_suppressPositionEvents) + sendConfigurePosition(); + }); + connect(m_wrapper, &QQuickItem::yChanged, this, [this] { + if (!m_suppressPositionEvents) + sendConfigurePosition(); + }); + connect(m_wrapper, &SurfaceWrapper::alwaysOnTopChanged, this, [this] { + sendConfigureStacking(); + }); + + // Initial event sequence: window_id → configure_position → configure_stacking + send_window_id(m_windowId); + sendConfigurePosition(); + sendConfigureStacking(); + } + + uint32_t windowId() const + { + return m_windowId; + } + + SurfaceWrapper *wrapper() const + { + return m_wrapper; + } + +protected: + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void destroy_resource([[maybe_unused]] Resource *resource) override + { + if (m_manager) { + m_manager->removeControl(this); + m_manager = nullptr; + } + delete this; + } + + void set_position([[maybe_unused]] Resource *resource, + int32_t x, + int32_t y, + uint32_t serial) override + { + if (!m_wrapper) { + return; + } + + qCDebug(lcTlProtocol) << "set_position serial" << x << y << serial << "for window_id" + << m_windowId; + + m_wrapper->setPositionAutomatic(false); + // Suppress only this class's xChanged/yChanged handlers to avoid + // emitting a serial=0 event alongside the client-requested one. + m_suppressPositionEvents = true; + m_wrapper->setPosition(QPointF(x, y)); + m_suppressPositionEvents = false; + // Echo the client serial back in configure_position + sendConfigurePosition(serial); + } + + void set_z_order([[maybe_unused]] Resource *resource, uint32_t op, uint32_t sibling_id) override + { + if (!m_wrapper) { + return; + } + + const auto zOrderOp = + static_cast(op); + + // Validate sibling_id: must be 0 for non-insert_after ops + if (op != z_order_op_hwnd_insert_after && sibling_id != 0) { + wl_resource_post_error(resource->handle, + error_invalid_sibling, + "sibling_id must be 0 for op %u", + op); + return; + } + + switch (zOrderOp) { + case z_order_op_hwnd_top: + applyHwndTop(); + // hwnd_top does not change tier → no configure_stacking + break; + case z_order_op_hwnd_bottom: + applyHwndBottom(); + break; + case z_order_op_hwnd_topmost: + m_wrapper->setAlwaysOnTop(true); + applyHwndTop(); + break; + case z_order_op_hwnd_notopmost: + m_wrapper->setAlwaysOnTop(false); + applyHwndTop(); + break; + case z_order_op_hwnd_insert_after: + applyHwndInsertAfter(sibling_id); + // hwnd_insert_after does not change tier → no configure_stacking + break; + } + } + +private: + // serial=0 means compositor-initiated (not in response to a client set_position) + void sendConfigurePosition(uint32_t serial = 0) + { + if (m_wrapper) { + send_configure_position(static_cast(m_wrapper->x()), + static_cast(m_wrapper->y()), + serial); + } else { + send_configure_position(0, 0, serial); + } + } + + void sendConfigureStacking() + { + bool topmost = m_wrapper && m_wrapper->alwaysOnTop(); + send_configure_stacking(topmost ? 1u : 0u); + } + + // Raise to top of current stacking tier (no tier change) + void applyHwndTop() + { + if (!m_wrapper) + return; + m_wrapper->stackToLast(); + } + + // Lower to absolute bottom, clear topmost tier. + void applyHwndBottom() + { + if (!m_wrapper) + return; + m_wrapper->setAlwaysOnTop(false); + m_wrapper->stackToFirst(); + } + + // Place this window directly below the identified sibling. + // Matches Windows SetWindowPos semantics: top-level windows may only be + // ordered relative to other top-level peers, and child windows only + // relative to same-parent siblings. Cross-group requests are ignored. + void applyHwndInsertAfter(uint32_t siblingId) + { + if (!m_manager || !m_wrapper) + return; + + WineWindowControl *sibling = m_manager->controlForId(siblingId); + if (sibling && sibling->resource()->client() != resource()->client()) + return; + // If sibling is not found, the request has no effect (e.g. the + // sibling window was destroyed before this message arrived). + if (!sibling || !sibling->wrapper()) + return; + if (sibling == this) + return; + + SurfaceWrapper *siblingWrapper = sibling->wrapper(); + + // Protocol set_z_order: child windows may only be ordered relative to + // same-parent siblings. An independent top-level has no parentSurface, + // so the check only fires when m_wrapper is a child and its top-level + // ancestor differs from the sibling's. + if (m_wrapper->parentSurface() + && topLevelSurface(m_wrapper) != topLevelSurface(siblingWrapper)) { + qCWarning(lcTlProtocol) + << "hwnd_insert_after: child window" << m_windowId << "and sibling_id" << siblingId + << "belong to different top-level groups; ignoring"; + return; + } + + // Protocol set_z_order: hwnd_insert_after must not mix tiers. + if (m_wrapper->effectiveAlwaysOnTop() != siblingWrapper->effectiveAlwaysOnTop()) { + qCWarning(lcTlProtocol) << "hwnd_insert_after: window" << m_windowId << "and sibling_id" + << siblingId << "belong to different tiers; ignoring"; + return; + } + + // Safety check: both windows must share the same Qt parent container. + if (!m_wrapper->parentItem() || siblingWrapper->parentItem() != m_wrapper->parentItem()) { + qCWarning(lcTlProtocol) << "hwnd_insert_after: window" << m_windowId << "and sibling_id" + << siblingId << "do not share a parent container; ignoring"; + return; + } + + // Place this window before the sibling (visually below sibling). + if (!m_wrapper->stackBefore(siblingWrapper)) { + qCWarning(lcTlProtocol) << "hwnd_insert_after: stackBefore failed for window" + << m_windowId << "(sibling_id =" << siblingId << ")"; + } + } + + static SurfaceWrapper *topLevelSurface(SurfaceWrapper *wrapper) + { + while (wrapper && wrapper->parentSurface()) + wrapper = wrapper->parentSurface(); + return wrapper; + } + +private: + WineWindowManagerPrivate *m_manager = nullptr; + uint32_t m_windowId = 0; + SurfaceWrapper *m_wrapper = nullptr; + bool m_suppressPositionEvents = false; +}; + +void WineWindowManagerPrivate::get_window_control(Resource *resource, + uint32_t id, + struct ::wl_resource *toplevelResource) +{ + if (wl_resource_get_client(toplevelResource) != resource->client()) { + wl_resource_post_error(resource->handle, + TREELAND_WINE_WINDOW_MANAGER_V1_ERROR_DEFUNCT_TOPLEVEL, + "toplevel belongs to another client"); + return; + } + auto *qXdgToplevel = wlr_xdg_toplevel_from_resource(toplevelResource); + if (!qXdgToplevel) { + wl_resource_post_error(resource->handle, + TREELAND_WINE_WINDOW_MANAGER_V1_ERROR_DEFUNCT_TOPLEVEL, + "invalid or defunct toplevel"); + return; + } + + auto *xdgToplevel = WXdgToplevelSurface::fromHandle(qXdgToplevel); + auto *server = WaylandServer::instance(); + auto *root = server ? server->rootSurfaceContainer() : nullptr; + auto *wrapper = (root && xdgToplevel) ? root->getSurface(xdgToplevel) : nullptr; + + if (!xdgToplevel || !wrapper || !wrapper->shellSurface()) { + wl_resource_post_error(resource->handle, + TREELAND_WINE_WINDOW_MANAGER_V1_ERROR_DEFUNCT_TOPLEVEL, + "invalid or defunct toplevel"); + return; + } + + const bool alreadyControlled = [&] { + for (const auto &e : m_controls) + if (e.toplevel == xdgToplevel) + return true; + return false; + }(); + if (alreadyControlled) { + wl_resource_post_error(resource->handle, + TREELAND_WINE_WINDOW_MANAGER_V1_ERROR_TOPLEVEL_ALREADY_CONTROLLED, + "toplevel already controlled"); + return; + } + + uint32_t windowId = nextWindowId(); + auto *control = new WineWindowControl(q, + this, + windowId, + wrapper, + resource->client(), + resource->version(), + id); + registerControl(windowId, xdgToplevel, control); + + qCDebug(lcTlProtocol) << "Created WineWindowControl for toplevel, window_id =" << windowId; +} + +// --------------------------------------------------------------------------- +// WineWindowManager public interface +// --------------------------------------------------------------------------- + +WineWindowManager::WineWindowManager(QObject *parent) + : QObject(parent) + , d(std::make_unique(this)) +{ +} + +WineWindowManager::~WineWindowManager() = default; + +void WineWindowManager::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void WineWindowManager::destroy(WServer * /*server*/) +{ + d->globalRemove(); +} + +wl_global *WineWindowManager::global() const +{ + return d->globalHandle(); +} + +QByteArrayView WineWindowManager::interfaceName() const +{ + return QtWaylandServer::treeland_wine_window_manager_v1::interfaceName(); +} diff --git a/src/modules/wine-window-management/winewindowmanagement.h b/src/modules/wine-window-management/winewindowmanagement.h new file mode 100644 index 0000000000..29bcb86f40 --- /dev/null +++ b/src/modules/wine-window-management/winewindowmanagement.h @@ -0,0 +1,34 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include + +#include + +#include + +class WineWindowManagerPrivate; + +class WineWindowManager + : public QObject + , public WAYLIB_SERVER_NAMESPACE::WServerInterface +{ + Q_OBJECT +public: + explicit WineWindowManager(QObject *parent = nullptr); + ~WineWindowManager() override; + static constexpr int InterfaceVersion = 1; + +protected: + void create(WAYLIB_SERVER_NAMESPACE::WServer *server) override; + void destroy(WAYLIB_SERVER_NAMESPACE::WServer *server) override; + wl_global *global() const override; + QByteArrayView interfaceName() const override; + +private: + std::unique_ptr d; +}; diff --git a/src/modules/wine-window-state/CMakeLists.txt b/src/modules/wine-window-state/CMakeLists.txt new file mode 100644 index 0000000000..f70f351d91 --- /dev/null +++ b/src/modules/wine-window-state/CMakeLists.txt @@ -0,0 +1,18 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wine-window-state-unstable-v1.xml + BASENAME treeland-wine-window-state-unstable-v1 +) + +impl_treeland( + NAME + module_wine_window_state + SOURCE + winewindowstate.h + winewindowstate.cpp + INCLUDE + $ + LINK + Qt6::Core +) diff --git a/src/modules/wine-window-state/winewindowstate.cpp b/src/modules/wine-window-state/winewindowstate.cpp new file mode 100644 index 0000000000..eac3c09f43 --- /dev/null +++ b/src/modules/wine-window-state/winewindowstate.cpp @@ -0,0 +1,285 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "winewindowstate.h" + +#include "common/treelandlogging.h" +#include "core/rootsurfacecontainer.h" +#include "qwayland-server-treeland-wine-window-state-unstable-v1.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" + +#include + +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class WineWindowState; + +class WineWindowStateManagerPrivate : public QtWaylandServer::treeland_wine_window_state_manager_v1 +{ +public: + explicit WineWindowStateManagerPrivate(WineWindowStateManager *q) + : q(q) + { + } + + wl_global *globalHandle() const + { + return m_global; + } + + void removeState(WineWindowState *state); + +private: + struct StateEntry + { + WXdgToplevelSurface *toplevel{ nullptr }; + WineWindowState *state{ nullptr }; + }; + + WineWindowStateManager *q = nullptr; + QList m_states; + + void bindState(WXdgToplevelSurface *toplevel, WineWindowState *state) + { + m_states.append({ toplevel, state }); + } + +protected: + void destroy_global() override + { + qCDebug(lcTlProtocol) << "WineWindowStateManager global destroyed"; + } + + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void get_window_state(Resource *resource, + uint32_t id, + struct ::wl_resource *toplevelResource) override; +}; + +class WineWindowState + : public QObject + , public QtWaylandServer::treeland_wine_window_state_v1 +{ +public: + WineWindowState(QObject *parent, + WineWindowStateManagerPrivate *manager, + SurfaceWrapper *wrapper, + wl_client *client, + int version, + uint32_t id) + : QObject(parent) + , QtWaylandServer::treeland_wine_window_state_v1(client, id, version) + , m_manager(manager) + , m_wrapper(wrapper) + { + Q_ASSERT_X(m_wrapper, Q_FUNC_INFO, "wrapper must not be null"); + Q_ASSERT_X(m_wrapper->shellSurface(), + Q_FUNC_INFO, + "wrapper->shellSurface() must not be null"); + + QObject::connect(m_wrapper->shellSurface(), &WToplevelSurface::minimizeChanged, this, [this] { + sendStateChanged(); + }); + connect(m_wrapper, &SurfaceWrapper::attentionChanged, this, [this] { + sendStateChanged(); + }); + connect(m_wrapper, &SurfaceWrapper::aboutToBeInvalidated, this, [this] { + if (m_manager) { + m_manager->removeState(this); + m_manager = nullptr; + } + m_wrapper = nullptr; + }); + + sendStateChanged(); + } + +protected: + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void destroy_resource([[maybe_unused]] Resource *resource) override + { + if (m_manager) { + m_manager->removeState(this); + m_manager = nullptr; + } + delete this; + } + + void unminimize([[maybe_unused]] Resource *resource) override + { + if (!m_wrapper) + return; + if (m_wrapper->isMinimized()) + m_wrapper->restoreFromMinimized(); + } + + void activate([[maybe_unused]] Resource *resource, + uint32_t serial, + [[maybe_unused]] uint32_t reason, + [[maybe_unused]] struct ::wl_resource *seat) override + { + if (!m_wrapper || !m_wrapper->shellSurface() || !m_wrapper->surface()) { + send_activate_denied(serial); + return; + } + + auto *server = WaylandServer::instance(); + if (!m_wrapper->hasActiveCapability()) { + send_activate_denied(serial); + return; + } + + server->forceActivateSurface(m_wrapper); + } + + void set_attention([[maybe_unused]] Resource *resource, + [[maybe_unused]] uint32_t count, + uint32_t timeoutMs) override + { + if (!m_wrapper) + return; + m_wrapper->setAttention(true); + if (timeoutMs > 0) { + if (!m_attentionTimer) { + m_attentionTimer = new QTimer(this); + m_attentionTimer->setSingleShot(true); + connect(m_attentionTimer, &QTimer::timeout, this, [this] { + if (m_wrapper) + m_wrapper->setAttention(false); + }); + } + m_attentionTimer->start(static_cast(timeoutMs)); + } else if (m_attentionTimer) { + m_attentionTimer->stop(); + } + } + + void clear_attention([[maybe_unused]] Resource *resource) override + { + if (!m_wrapper) + return; + if (m_attentionTimer) + m_attentionTimer->stop(); + m_wrapper->setAttention(false); + } + +private: + void sendStateChanged() + { + if (!m_wrapper) + return; + + uint32_t state = 0; + if (m_wrapper->isMinimized()) + state |= TREELAND_WINE_WINDOW_STATE_V1_STATE_MINIMIZED; + if (m_wrapper->attention()) + state |= TREELAND_WINE_WINDOW_STATE_V1_STATE_ATTENTION; + + send_state_changed(state); + } + +private: + WineWindowStateManagerPrivate *m_manager = nullptr; + SurfaceWrapper *m_wrapper = nullptr; + QTimer *m_attentionTimer = nullptr; +}; + +void WineWindowStateManagerPrivate::removeState(WineWindowState *state) +{ + for (auto it = m_states.begin(); it != m_states.end(); ++it) { + if (it->state == state) { + m_states.erase(it); + return; + } + } +} + +void WineWindowStateManagerPrivate::get_window_state(Resource *resource, + uint32_t id, + struct ::wl_resource *toplevelResource) +{ + if (wl_resource_get_client(toplevelResource) != resource->client()) { + wl_resource_post_error(resource->handle, + TREELAND_WINE_WINDOW_STATE_MANAGER_V1_ERROR_DEFUNCT_TOPLEVEL, + "toplevel belongs to another client"); + return; + } + auto *qXdgToplevel = wlr_xdg_toplevel_from_resource(toplevelResource); + if (!qXdgToplevel) { + wl_resource_post_error(resource->handle, + TREELAND_WINE_WINDOW_STATE_MANAGER_V1_ERROR_DEFUNCT_TOPLEVEL, + "invalid or defunct toplevel"); + return; + } + + auto *xdgToplevel = WXdgToplevelSurface::fromHandle(qXdgToplevel); + auto *server = WaylandServer::instance(); + auto *root = server ? server->rootSurfaceContainer() : nullptr; + auto *wrapper = (root && xdgToplevel) ? root->getSurface(xdgToplevel) : nullptr; + + if (!xdgToplevel || !wrapper || !wrapper->shellSurface()) { + wl_resource_post_error(resource->handle, + TREELAND_WINE_WINDOW_STATE_MANAGER_V1_ERROR_DEFUNCT_TOPLEVEL, + "invalid or defunct toplevel"); + return; + } + + const bool alreadyBound = std::ranges::any_of( + m_states, + [&](const WXdgToplevelSurface *t) { + return t == xdgToplevel; + }, + &StateEntry::toplevel); + if (alreadyBound) { + wl_resource_post_error(resource->handle, + TREELAND_WINE_WINDOW_STATE_MANAGER_V1_ERROR_TOPLEVEL_ALREADY_BOUND, + "toplevel already bound"); + return; + } + + auto *state = + new WineWindowState(q, this, wrapper, resource->client(), resource->version(), id); + bindState(xdgToplevel, state); +} + +WineWindowStateManager::WineWindowStateManager(QObject *parent) + : QObject(parent) + , d(new WineWindowStateManagerPrivate(this)) +{ +} + +WineWindowStateManager::~WineWindowStateManager() = default; + +void WineWindowStateManager::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void WineWindowStateManager::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *WineWindowStateManager::global() const +{ + return d->globalHandle(); +} + +QByteArrayView WineWindowStateManager::interfaceName() const +{ + return QtWaylandServer::treeland_wine_window_state_manager_v1::interfaceName(); +} diff --git a/src/modules/wine-window-state/winewindowstate.h b/src/modules/wine-window-state/winewindowstate.h new file mode 100644 index 0000000000..4ded2222e6 --- /dev/null +++ b/src/modules/wine-window-state/winewindowstate.h @@ -0,0 +1,34 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include + +#include + +#include + +class WineWindowStateManagerPrivate; + +class WineWindowStateManager + : public QObject + , public WAYLIB_SERVER_NAMESPACE::WServerInterface +{ + Q_OBJECT +public: + explicit WineWindowStateManager(QObject *parent = nullptr); + ~WineWindowStateManager() override; + static constexpr int InterfaceVersion = 1; + +protected: + void create(WAYLIB_SERVER_NAMESPACE::WServer *server) override; + void destroy(WAYLIB_SERVER_NAMESPACE::WServer *server) override; + wl_global *global() const override; + QByteArrayView interfaceName() const override; + +private: + std::unique_ptr d; +}; diff --git a/src/modules/xwindow-control/CMakeLists.txt b/src/modules/xwindow-control/CMakeLists.txt new file mode 100644 index 0000000000..85704de450 --- /dev/null +++ b/src/modules/xwindow-control/CMakeLists.txt @@ -0,0 +1,20 @@ +find_package(TreelandProtocols REQUIRED) + +waylib_generate_qtwayland_server_protocol(libtreeland + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-xwindow-control-unstable-v1.xml + BASENAME treeland-xwindow-control-unstable-v1 +) + +impl_treeland( + NAME + module_xwindow_control + SOURCE + ${CMAKE_SOURCE_DIR}/src/modules/xwindow-control/xwindowcontrolinterfacev1.h + ${CMAKE_SOURCE_DIR}/src/modules/xwindow-control/xwindowcontrolinterfacev1.cpp + LINK + Wlroots::wlroots + Waylib::WaylibServer + Qt6::Core + Qt6::Gui + Qt6::Quick +) diff --git a/src/modules/xwindow-control/xwindowcontrolinterfacev1.cpp b/src/modules/xwindow-control/xwindowcontrolinterfacev1.cpp new file mode 100644 index 0000000000..e03cc6fe5e --- /dev/null +++ b/src/modules/xwindow-control/xwindowcontrolinterfacev1.cpp @@ -0,0 +1,90 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "xwindowcontrolinterfacev1.h" +#include "qwayland-server-treeland-xwindow-control-unstable-v1.h" + +#include "core/waylandserver.h" + +#include +#include + +#include + +class XWindowControlInterfaceV1Private : public QtWaylandServer::treeland_xwindow_control_v1 +{ +public: + XWindowControlInterfaceV1Private(XWindowControlInterfaceV1 *_q); + wl_global *global() const; + + XWindowControlInterfaceV1 *q; + +protected: + void destroy(Resource *resource) override; + void set_xwindow_position_relative(Resource *resource, uint32_t callback, uint32_t wid, + struct ::wl_resource *anchor, wl_fixed_t dx, wl_fixed_t dy) override; +}; + +XWindowControlInterfaceV1Private::XWindowControlInterfaceV1Private(XWindowControlInterfaceV1 *_q) + : QtWaylandServer::treeland_xwindow_control_v1() + , q(_q) +{ +} + +wl_global *XWindowControlInterfaceV1Private::global() const +{ + return m_global; +} + +void XWindowControlInterfaceV1Private::destroy(Resource *resource) +{ + wl_resource_destroy(resource->handle); +} + +void XWindowControlInterfaceV1Private::set_xwindow_position_relative(Resource *resource, + uint32_t callback, + uint32_t wid, + struct ::wl_resource *anchor, + wl_fixed_t dx, + wl_fixed_t dy) +{ + // libwayland dispatch already guarantees a genuine wl_surface. + auto *wsurface = wl_resource_get_client(anchor) == resource->client() + ? WSurface::fromHandle(wlr_surface_from_resource(anchor)) : nullptr; + uint32_t ok = (wsurface && WaylandServer::instance()->setXWindowPositionRelative(wid, wsurface, dx, dy)) ? 0 : 1; + wl_resource *cb = wl_resource_create(resource->client(), &wl_callback_interface, 1, callback); + if (!cb) { + wl_client_post_no_memory(resource->client()); + return; + } + wl_callback_send_done(cb, ok); + wl_resource_destroy(cb); +} + +XWindowControlInterfaceV1::XWindowControlInterfaceV1(QObject *parent) + : QObject(parent) + , d(new XWindowControlInterfaceV1Private(this)) +{ +} + +XWindowControlInterfaceV1::~XWindowControlInterfaceV1() = default; + +void XWindowControlInterfaceV1::create(WServer *server) +{ + d->init(server->handle(), InterfaceVersion); +} + +void XWindowControlInterfaceV1::destroy([[maybe_unused]] WServer *server) +{ + d->globalRemove(); +} + +wl_global *XWindowControlInterfaceV1::global() const +{ + return d->global(); +} + +QByteArrayView XWindowControlInterfaceV1::interfaceName() const +{ + return d->interfaceName(); +} diff --git a/src/modules/xwindow-control/xwindowcontrolinterfacev1.h b/src/modules/xwindow-control/xwindowcontrolinterfacev1.h new file mode 100644 index 0000000000..b8703c6da9 --- /dev/null +++ b/src/modules/xwindow-control/xwindowcontrolinterfacev1.h @@ -0,0 +1,34 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class XWindowControlInterfaceV1Private; +class XWindowControlInterfaceV1 + : public QObject + , public WAYLIB_SERVER_NAMESPACE::WServerInterface +{ + Q_OBJECT + +public: + explicit XWindowControlInterfaceV1(QObject *parent = nullptr); + ~XWindowControlInterfaceV1() override; + + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + std::unique_ptr d; +}; diff --git a/src/output/backlight.cpp b/src/output/backlight.cpp new file mode 100644 index 0000000000..c3a934fa5a --- /dev/null +++ b/src/output/backlight.cpp @@ -0,0 +1,94 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "backlight.h" + +#include "woutput.h" + +#include "common/treelandlogging.h" + +Backlight::Backlight(const QString &name) + : m_name(name) +{ + QFile maxBrightnessFile(QString("/sys/class/backlight/%1/max_brightness").arg(name)); + Q_ASSERT(maxBrightnessFile.open(QIODevice::ReadOnly)); + + bool ok = false; + m_maxBrightness = maxBrightnessFile.readLine().trimmed().toLongLong(&ok); + maxBrightnessFile.close(); + Q_ASSERT(ok); + Q_ASSERT(m_maxBrightness > 0); + + QFile brightnessFile(QString("/sys/class/backlight/%1/brightness").arg(name)); + Q_ASSERT(brightnessFile.open(QIODevice::ReadOnly)); + + m_brightnessLevel = brightnessFile.readLine().trimmed().toLongLong(&ok); + brightnessFile.close(); + Q_ASSERT(ok); +} + +Backlight::~Backlight() +{ + +} + +qreal Backlight::brightness() const +{ + return m_brightnessLevel / static_cast(m_maxBrightness); +} + +qreal Backlight::setBrightness(qreal brightness) +{ + qlonglong brightnessLevel = qMin(qCeil(brightness * m_maxBrightness), m_maxBrightness); + + if (brightnessLevel == m_brightnessLevel) { + return this->brightness(); + } + + QFile brightnessFile(QString("/sys/class/backlight/%1/brightness").arg(m_name)); + if (!brightnessFile.open(QIODevice::WriteOnly)) { + qCWarning(lcTlOutput) << "Output" << m_name << ": Failed to open backlight brightness file for writing."; + return this->brightness(); + } + + QByteArray brightnessStr = QByteArray::number(brightnessLevel); + qint64 written = brightnessFile.write(brightnessStr); + brightnessFile.close(); + Q_ASSERT(written == brightnessStr.size()); + + m_brightnessLevel = brightnessLevel; + return this->brightness(); +} + + +Backlight* Backlight::createForOutput(WOutput* output) +{ + // query backlight driver through drm connector id + if (wlr_output_is_drm(output->handle())) { + QDirIterator backlightIter("/sys/class/backlight", QDir::Dirs | QDir::NoDot); + uint connectorId = wlr_drm_connector_get_id(output->handle()); + QString dirname; + uint backlightCount = 0; + while (backlightIter.hasNext()) { + backlightCount++; + backlightIter.next(); + dirname = backlightIter.fileName(); + auto idFile = QFile("/sys/class/backlight/" + dirname + "/device/connector_id"); + if (!idFile.exists() || !idFile.open(QIODevice::ReadOnly)) + continue; + bool ok = false; + uint id = idFile.readLine().toUInt(&ok); + idFile.close(); + if (!ok) + continue; + if (connectorId == id) + return new Backlight(dirname); + } + + // heuristic: map the only backlight driver to internal panel + if (output->name() == "eDP-1" && backlightCount == 1) { + return new Backlight(dirname); + } + } + return nullptr; +} diff --git a/src/output/backlight.h b/src/output/backlight.h new file mode 100644 index 0000000000..d23c7448aa --- /dev/null +++ b/src/output/backlight.h @@ -0,0 +1,26 @@ +// Copyright (C) 2025 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutput; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class Backlight +{ +public: + Backlight(const QString &name); + ~Backlight(); + static Backlight* createForOutput(WOutput* output); + qreal brightness() const; + qreal setBrightness(qreal brightness); +private: + qlonglong m_maxBrightness; + qlonglong m_brightnessLevel; + QString m_name; +}; diff --git a/src/output/output.cpp b/src/output/output.cpp new file mode 100644 index 0000000000..1bbb52c4f8 --- /dev/null +++ b/src/output/output.cpp @@ -0,0 +1,1366 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include "output.h" +#include "desktop/desktopenvironment.h" +#include "session/sessionoutputmanager.h" + +#include "cmdline.h" +#include "common/treelandlogging.h" +#include "core/rootsurfacecontainer.h" +#include "dconfig/dconfigmanager.h" +#include "outputconfig.hpp" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" +#include "treelandconfig.hpp" +#include "treelanduserconfig.hpp" +#include "workspace/workspace.h" +#include "wallpapermanager.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#define SAME_APP_OFFSET_FACTOR 1.0 +#define DIFF_APP_OFFSET_FACTOR 2.0 +#define POPUP_EDGE_MARGIN 10 + +QString Output::getOutputId(wlr_output *output) +{ + const QString model = QString::fromUtf8(output->model); + const QString serial = QString::fromUtf8(output->serial); + if (!model.isEmpty() && !serial.isEmpty()) { + return model + serial; + } + + return QString::fromUtf8(output->name); +} + +QString Output::getOutputId() +{ + return getOutputId(output()->handle()); +} + +Output *Output::create(WOutput *output, QQmlEngine *engine, QObject *parent) +{ + auto *config = WaylandServer::instance()->globalConfig(); + auto *o = new Output(output, parent); + o->m_type = Type::Source; + + QQmlComponent delegate(engine, "Treeland", "SourceOutput"); + QObject *obj = delegate.beginCreate(engine->rootContext()); + if (Q_UNLIKELY(!obj)) { + qCFatal(lcTlOutput) << "Can't create SourceOutput:" << delegate.errorString(); + } + delegate.setInitialProperties(obj, { + { "forceSoftwareCursor", config->forceSoftwareCursor() }, + { "treelandOutput", QVariant::fromValue(o) }, + }); + delegate.completeCreate(); + WOutputItem *outputItem = qobject_cast(obj); + Q_ASSERT(outputItem); + QQmlEngine::setObjectOwnership(outputItem, QQmlEngine::CppOwnership); + + auto contentItem = WaylandServer::instance()->window()->contentItem(); + outputItem->setParentItem(contentItem); + outputItem->setOutput(output); + o->setOutputItem(outputItem); + + connect(WaylandServer::instance()->globalConfig(), + &TreelandConfig::forceSoftwareCursorChanged, + obj, + [obj, config]() { + auto forceSoftwareCursor = config->forceSoftwareCursor(); + qCInfo(lcTlOutput) << "forceSoftwareCursor changed to" << forceSoftwareCursor; + obj->setProperty("forceSoftwareCursor", forceSoftwareCursor); + }); + + obj->setParent(o); + + // Triggering layout updates using a queue helps reduce window jitter. + // When the screen scaling factor changes, the scale of WOutput is updated first, + // causing the size of WOutputItem to change. However, at this point, the + // effectiveDevicePixelRatio of QWindow has not yet been updated. + // This results in the size of maximized windows being updated prematurely. + // Xwayland windows use the effectiveDevicePixelRatio to set the surfaceSizeRatio. + // By updating within a queue, it ensures that the surfaceSizeRatio used when + // resizing maximized Xwayland windows is accurate, avoiding multiple rapid + // size changes to Xwayland windows in a short period. + o->connect(outputItem, + &WOutputItem::geometryChanged, + o, + &Output::arrangeAllSurfaces, + Qt::QueuedConnection); + + + // reset output color to config value + o->applyOutputColorConfig(); + + if (CmdLine::ref().enableDebugView()) { + o->m_debugMenuBar = WaylandServer::instance()->qmlEngine()->createMenuBar(outputItem, contentItem); + o->m_debugMenuBar->setZ(RootSurfaceContainer::MenuBarZOrder); +#ifndef QT_DEBUG + o->m_debugMenuBar->setVisible(false); +#endif + connect(o->m_debugMenuBar, &QQuickItem::visibleChanged, o, &Output::arrangeAllSurfaces); + connect(o->m_debugMenuBar, &QQuickItem::heightChanged, o, &Output::arrangeAllSurfaces); + o->arrangeAllSurfaces(); + } + + return o; +} + +Output *Output::createCopy(WOutput *output, Output *proxy, QQmlEngine *engine, QObject *parent) +{ + auto *o = new Output(output, parent); + o->m_type = Type::Mirror; + o->m_proxy = proxy; + + QQmlComponent delegate(engine, "Treeland", "MirrorOutput"); + QObject *obj = delegate.createWithInitialProperties( + { + { "targetOutputItem", QVariant::fromValue(proxy->outputItem()) }, + { "treelandOutput", QVariant::fromValue(o) }, + }, + engine->rootContext()); + if (Q_UNLIKELY(!obj)) { + qCFatal(lcTlOutput) << "Can't create MirrorOutput:" << delegate.errorString(); + } + WOutputItem *outputItem = qobject_cast(obj); + Q_ASSERT(outputItem); + QQmlEngine::setObjectOwnership(outputItem, QQmlEngine::CppOwnership); + + auto contentItem = WaylandServer::instance()->window()->contentItem(); + outputItem->setParentItem(contentItem); + outputItem->setOutput(output); + o->setOutputItem(outputItem); + obj->setParent(o); + + o->updateOutputHardwareLayers(); + connect(proxy->screenViewport(), + &WOutputViewport::hardwareLayersChanged, + o, + &Output::updateOutputHardwareLayers); + + return o; +} + +Output::Output(WOutput *output, QObject *parent) + : SurfaceListModel(parent) + , m_backlight(Backlight::createForOutput(output)) +{ + QString outputName = Output::getOutputId(output->handle()); + auto *configManager = DConfigManager::instance(); + Q_ASSERT(configManager); + m_config = configManager ? configManager->outputConfig(outputName) : nullptr; + connect(WaylandServer::instance(), &WaylandServer::desktopChanged, this, &Output::configChanged); + connect(WaylandServer::instance(), &WaylandServer::desktopChanged, + this, &Output::minimizedSurfacesChanged); + connect(WaylandServer::instance(), &WaylandServer::desktopChanged, + this, &Output::arrangeAllSurfaces); +} + +void Output::setOutputItem(WOutputItem *item) +{ + Q_ASSERT(item); + Q_ASSERT(!m_item); + m_item = item; + m_outputViewport = item->property("screenViewport").value(); +} + +Output::~Output() +{ + // Mirror outputs reuse the source output's hardware layers. Detach them + // explicitly before destroying the viewport so that the output gets a new + // frame and stale hardware-plane contents (notably the cursor) are cleared. + if (m_type == Type::Mirror && m_outputViewport) { + for (auto *layer : std::as_const(m_hardwareLayersOfSourceOutput)) { + WaylandServer::instance()->window()->detach(layer, m_outputViewport); + } + m_hardwareLayersOfSourceOutput.clear(); + } + + if (m_debugMenuBar) { + delete m_debugMenuBar; + m_debugMenuBar = nullptr; + } + + if (m_item) { + delete m_item; + m_item = nullptr; + } +} + +bool Output::isSource() const +{ + return m_type == Type::Source; +} + +void Output::updatePositionFromLayout() +{ + WOutputLayout *layout = output()->layout(); + if (!layout) { + return; + } + + auto *layoutOutput = wlr_output_layout_get(layout->handle(), output()->handle()); + if (!layoutOutput) { + return; + } + + QPointF pos(layoutOutput->x, layoutOutput->y); + m_item->setPosition(pos); +} + +QQuickItem *Output::debugMenuBar() const +{ + return m_debugMenuBar; +} + +std::pair Output::getOutputItemProperty() +{ + WOutputViewport *viewportCopy = + outputItem()->findChild({}, Qt::FindDirectChildrenOnly); + Q_ASSERT(viewportCopy); + auto textureProxy = outputItem()->findChild(); + Q_ASSERT(textureProxy); + return std::make_pair(viewportCopy, textureProxy); +} + +void Output::moveSurfaceWithTitlebarClamp(SurfaceWrapper *surface, const QPointF &pos) +{ + const auto validGeo = validGeometryForSurface(surface); + QRectF candidateGeo(pos, surface->normalGeometry().size()); + + QRectF titlebarGeometry = surface->titlebarGeometry(); + if (!titlebarGeometry.isValid()) { + qreal titleHeight = WaylandServer::instance()->config()->windowTitlebarHeight(); + titlebarGeometry = QRectF(0, 0, candidateGeo.width(), titleHeight); + } + titlebarGeometry.translate(candidateGeo.topLeft()); + + if ((titlebarGeometry & validGeo).isEmpty()) { + if (titlebarGeometry.top() < validGeo.top()) { + candidateGeo.moveTop(candidateGeo.top() + validGeo.top() - titlebarGeometry.top()); + } else if (titlebarGeometry.bottom() > validGeo.bottom()) { + candidateGeo.moveBottom(candidateGeo.bottom() + - (titlebarGeometry.bottom() - validGeo.bottom())); + } + // moveTop/moveBottom do not change left/right, so titlebarGeometry's + // horizontal extent is still valid for the check below. + if (titlebarGeometry.left() < validGeo.left()) { + candidateGeo.moveLeft(candidateGeo.left() + validGeo.left() - titlebarGeometry.left()); + } else if (titlebarGeometry.right() > validGeo.right()) { + candidateGeo.moveRight(candidateGeo.right() + - (titlebarGeometry.right() - validGeo.right())); + } + } + + if (candidateGeo.topLeft() == surface->normalGeometry().topLeft()) { + // Final clamped position is unchanged; skip no-op move. + return; + } + + surface->moveNormalGeometryInOutput(candidateGeo.topLeft()); +} + +void Output::placeUnderCursor(SurfaceWrapper *surface) +{ + QSizeF cursorSize; + QRectF normalGeo = surface->normalGeometry(); + WCursor *wCursor = WaylandServer::instance()->seat()->cursor(); + if (!surface->ownsOutput()->outputItem()->cursorItems().isEmpty()) + cursorSize = surface->ownsOutput()->outputItem()->cursorItems()[0]->size(); + + // Surface center sits at the cursor center plus the x offset, the surface + // top at the cursor bottom plus the y offset. + const QPoint offset = surface->autoPlaceCursorOffset().value_or(QPoint()); + normalGeo.moveLeft(wCursor->position().x() + cursorSize.width() / 2 + + offset.x() - surface->width() / 2); + normalGeo.moveTop(wCursor->position().y() + cursorSize.height() + offset.y()); + moveSurfaceWithTitlebarClamp(surface, normalGeo.topLeft()); +} + +void Output::placeClientRequstPos(SurfaceWrapper *surface, QPoint clientRequstPos) +{ + QRectF normalGeo = surface->normalGeometry(); + normalGeo.moveLeft(clientRequstPos.x()); + normalGeo.moveTop(clientRequstPos.y()); + moveSurfaceWithTitlebarClamp(surface, normalGeo.topLeft()); +} + +void Output::placeCentered(SurfaceWrapper *surface) +{ + const auto validGeo = validGeometryForSurface(surface); + QRectF normalGeo = surface->normalGeometry(); + normalGeo.moveCenter(validGeo.center()); + normalGeo.moveTop(qMax(normalGeo.top(), validGeo.top())); + normalGeo.moveLeft(qMax(normalGeo.left(), validGeo.left())); + moveSurfaceWithTitlebarClamp(surface, normalGeo.topLeft()); +} + +void Output::placeSmartCascaded(SurfaceWrapper *surface) +{ + auto *workspace = surface->desktop() ? surface->desktop()->workspace() + : WaylandServer::instance()->workspace(); + auto wpModel = workspace->modelFromId(surface->workspaceId()); + Q_ASSERT(wpModel); + /* + The execution of Output::placeSmartCascaded and the surface obtaining focus occur almost + simultaneously after the window is mapped for the first time; the order is not currently + guaranteed. + */ + auto latestActiveSurface = wpModel->latestActiveSurface(); + if (latestActiveSurface == surface) + latestActiveSurface = wpModel->activePenultimateWindow(); + + if (!latestActiveSurface) { + placeCentered(surface); + return; + } + + const auto validGeo = validGeometryForSurface(surface); + QRectF normalGeo = surface->normalGeometry(); + QRectF latestActiveSurfaceGeo = latestActiveSurface->normalGeometry(); + + qreal factor = + (latestActiveSurface->appId() != surface->appId()) + ? DIFF_APP_OFFSET_FACTOR + : SAME_APP_OFFSET_FACTOR; + const QRectF titleBarGeometry = latestActiveSurface->titlebarGeometry(); + qreal offset = (titleBarGeometry.isNull() ? WaylandServer::instance()->config()->windowTitlebarHeight() + : titleBarGeometry.height()) + * factor; + + QPointF newPos; + if (m_nextPlaceDirection == PlaceDirection::BottomRight) { + newPos = calculateBottomRightPosition(latestActiveSurfaceGeo, + normalGeo, + validGeo, + QSizeF(offset, offset)); + } else { + newPos = calculateTopLeftPosition(latestActiveSurfaceGeo, + normalGeo, + validGeo, + QSizeF(offset, offset)); + } + + newPos = constrainToValidArea(newPos, normalGeo.size(), validGeo); + moveSurfaceWithTitlebarClamp(surface, newPos); +} + +QPointF Output::calculateBottomRightPosition(const QRectF &activeGeo, + const QRectF &normalGeo, + const QRectF &validGeo, + const QSizeF &offset) +{ + QPointF bottomRight(activeGeo.left() + offset.width(), activeGeo.top() + offset.height()); + + if (bottomRight.x() + normalGeo.width() <= validGeo.right() + && bottomRight.y() + normalGeo.height() <= validGeo.bottom()) { + return bottomRight; + } + + m_nextPlaceDirection = PlaceDirection::TopLeft; + return QPointF(qMax(validGeo.left(), activeGeo.right() - normalGeo.width() - offset.width()), + qMax(validGeo.top(), activeGeo.bottom() - normalGeo.height() - offset.height())); +} + +QPointF Output::calculateTopLeftPosition(const QRectF &activeGeo, + const QRectF &normalGeo, + const QRectF &validGeo, + const QSizeF &offset) +{ + QPointF topLeft(activeGeo.right() - normalGeo.width() - offset.width(), + activeGeo.bottom() - normalGeo.height() - offset.height()); + + if (topLeft.x() >= validGeo.left() && topLeft.y() >= validGeo.top()) { + return topLeft; + } + + m_nextPlaceDirection = PlaceDirection::BottomRight; + return QPointF(qMin(validGeo.right() - normalGeo.width(), activeGeo.left() + offset.width()), + qMin(validGeo.bottom() - normalGeo.height(), activeGeo.top() + offset.height())); +} + +QPointF Output::constrainToValidArea(const QPointF &pos, + const QSizeF &windowSize, + const QRectF &validGeo) +{ + QPointF newPos = pos; + + newPos.setX(qMax(newPos.x(), validGeo.left())); + newPos.setX(qMin(newPos.x(), validGeo.right() - windowSize.width())); + newPos.setY(qMax(newPos.y(), validGeo.top())); + newPos.setY(qMin(newPos.y(), validGeo.bottom() - windowSize.height())); + + return newPos; +} + +double Output::calcPreferredScale(double widthPx, double heightPx, double widthMm, double heightMm) +{ + if (widthPx <= 0 || heightPx <= 0 || widthMm <= 0 || heightMm <= 0) { + return 1.0; + } + + const double lenPx = std::hypot(widthPx, heightPx); + const double lenMm = std::hypot(widthMm, heightMm); + + // A standard scale=1.0 display + const double lenPxStd = std::hypot(1920.0, 1080.0); + const double lenMmStd = std::hypot(477.0, 268.0); + + // This magic number is from startdde, I don't know why. + const double a = 0.00158; + // The scaling factor should be adjusted according to the size + // of the standard screen. Even if the PPI is the same, the larger + // the screen, the larger the scaling factor should be. Otherwise, + // the scaling factor should be smaller, as this better aligns with + // the visual needs of the human eye. + const double fix = (lenMm - lenMmStd) * (lenPx / lenPxStd) * a; + + const double scaleFactor = (lenPx / lenMm) / (lenPxStd / lenMmStd) + fix; + + // Ensure step is within 0.25 + return std::round(scaleFactor * 4) / 4.0; +} + +qreal Output::preferredScaleFactor(const QSize &pixelSize) const +{ + auto o = output()->handle(); + return calcPreferredScale(pixelSize.width(), pixelSize.height(), o->phys_width, o->phys_height); +} + +void Output::applyGeometry(const QSize &modePixels, WOutput::Transform transform, qreal scale) +{ + if (!modePixels.isValid() || modePixels.isEmpty() || !std::isfinite(scale) || scale <= 0.0) + return; + + QSize logical = modePixels; + if (int(transform) % 2 != 0) + logical.transpose(); + if (m_item) { + m_item->setWidth(logical.width() / scale); + m_item->setHeight(logical.height() / scale); + } + if (m_outputViewport) { + m_outputViewport->setWidth(modePixels.width() / scale); + m_outputViewport->setHeight(modePixels.height() / scale); + } +} + +bool Output::setTransform(WOutput::Transform transform) +{ + auto *handle = output() ? output()->handle() : nullptr; + if (!handle || handle->width <= 0 || handle->height <= 0) + return false; + + auto extra = extraState(); + if (!extra) + extra = WOutputHelper::ExtraState(); + wlr_output_state_set_transform(extra.get(), + static_cast(transform)); + if (!setExtraState(extra)) + return false; + + // The rotation animation owns the viewport rotation, so only the geometry + // is resynced here. + applyPendingGeometry(false); + return true; +} + +void Output::setViewportRotation(WOutput::Transform transform) +{ + if (!m_outputViewport) + return; + + // Same mapping as the rotation animation in SourceOutput.qml. + int angle = 0; + switch (transform) { + case WOutput::Transform::R90: + angle = 90; + break; + case WOutput::Transform::R180: + angle = 180; + break; + case WOutput::Transform::R270: + angle = -90; + break; + default: + break; + } + m_outputViewport->setRotation(angle); +} + +QJSValue Output::rotationOutputHandler() const +{ + return m_rotationOutputHandler; +} + +void Output::setRotationOutputHandler(const QJSValue &handler) +{ + if (m_rotationOutputHandler.equals(handler)) + return; + m_rotationOutputHandler = handler; + Q_EMIT rotationOutputHandlerChanged(); +} + +void Output::rotationOutput(WOutput::Transform transform) +{ + if (m_rotationOutputHandler.isCallable()) { + QJSValueList args; + args << QJSValue(static_cast(transform)); + m_rotationOutputHandler.call(args); + return; + } + + setViewportRotation(transform); + setTransform(transform); +} + +void Output::applyPendingGeometry(bool rotateViewport) +{ + auto *handle = output() ? output()->handle() : nullptr; + if (!handle) + return; + + QSize mode = handle->current_mode + ? QSize(handle->current_mode->width, handle->current_mode->height) + : QSize(handle->width, handle->height); + auto transform = output()->orientation(); + qreal scale = output()->scale(); + + // A staged mode/transform/scale is not committed yet, but the QML item and + // viewport must already match it, otherwise the frame that commits the new + // state draws at the old size. + if (auto extra = extraState()) { + if (extra->committed & WLR_OUTPUT_STATE_MODE) { + if (extra->mode_type == WLR_OUTPUT_STATE_MODE_FIXED && extra->mode) { + mode = QSize(extra->mode->width, extra->mode->height); + } else if (extra->mode_type == WLR_OUTPUT_STATE_MODE_CUSTOM) { + mode = QSize(extra->custom_mode.width, extra->custom_mode.height); + } + } + if (extra->committed & WLR_OUTPUT_STATE_TRANSFORM) + transform = static_cast(extra->transform); + if (extra->committed & WLR_OUTPUT_STATE_SCALE) + scale = extra->scale; + } + + applyGeometry(mode, transform, scale); + if (rotateViewport) + setViewportRotation(transform); +} + +bool Output::setExtraState(WOutputHelper::ExtraState state) +{ + auto *window = m_outputViewport ? m_outputViewport->outputRenderWindow() : nullptr; + auto *helper = window ? window->getOutputHelper(m_outputViewport) : nullptr; + if (!helper || !helper->setExtraState(state)) + return false; + if (auto *woutput = output()) + woutput->scheduleFrame(); + return true; +} + +WOutputHelper::ExtraState Output::extraState() const +{ + auto *window = m_outputViewport ? m_outputViewport->outputRenderWindow() : nullptr; + auto *helper = window ? window->getOutputHelper(m_outputViewport) : nullptr; + if (!helper) + return {}; + return helper->extraState(); +} + +void Output::enable() +{ + // Enable on default + auto wlrOutput = output()->handle(); + WOutputStateGuard newState; + // Don't care for WOutput::isEnabled, must do WOutput::commit here, + // In order to ensure trigger wlr_output frame signal, WOutputRenderWindow + // needs this signal to render next frame. Because the frame signal + // may be emitted before WOutputRenderWindow::attach, if no commit here, + // WOutputRenderWindow will ignore this output on render. + const bool cachedEnabled = output()->property("_Enabled").toBool(); + const bool outputEnabled = wlrOutput->enabled; + if (!cachedEnabled || !outputEnabled) { + if (!wlrOutput->current_mode) { + auto mode = wlr_output_preferred_mode(wlrOutput); + if (mode) { + wlr_output_state_set_mode(newState.get(), mode); + + // TODO: read user config + wlr_output_state_set_scale(newState.get(), preferredScaleFactor({ mode->width, mode->height })); + } + } else { + // TODO: read user config + wlr_output_state_set_scale(newState.get(), preferredScaleFactor(output()->size())); + } + wlr_output_state_set_enabled(newState.get(), true); + const bool commitOk = wlr_output_commit_state(wlrOutput, newState.get()); + if (!commitOk) { + qCCritical(lcTlCore, "commit failed on output %s", wlrOutput->name); + return; + } + applyPendingGeometry(); + output()->setProperty("_Enabled", true); + qCInfo(lcTlOutput) << "Enabled output" << wlrOutput->name + << "cached:" << cachedEnabled + << "was enabled:" << outputEnabled; + } +} + +void Output::updateOutputHardwareLayers() +{ + WOutputViewport *viewportPrimary = m_proxy->screenViewport(); + std::pair copyOutput = getOutputItemProperty(); + const auto layers = viewportPrimary->hardwareLayers(); + for (auto layer : layers) { + if (m_hardwareLayersOfSourceOutput.removeOne(layer)) + continue; + WaylandServer::instance()->window()->attach(layer, + copyOutput.first, + viewportPrimary, + copyOutput.second); + } + for (auto oldLayer : std::as_const(m_hardwareLayersOfSourceOutput)) { + WaylandServer::instance()->window()->detach(oldLayer, copyOutput.first); + } + m_hardwareLayersOfSourceOutput = layers; +} + +void Output::addSurface(SurfaceWrapper *surface) +{ + Q_ASSERT(!hasSurface(surface)); + SurfaceListModel::addSurface(surface); + if (auto *desktop = surface->desktop()) + desktop->outputs()->outputState(this)->addSurface(surface); + + if (surface->type() == SurfaceWrapper::Type::Layer) { + auto layer = qobject_cast(surface->shellSurface()); + QObject::connect(layer, &WLayerSurface::layerPropertiesChanged, + this, + &Output::arrangeLayerSurfaces); + + arrangeLayerSurfaces(); + } else { + auto layoutSurface = [surface, this] { + if (!surface->hasInitializeContainer()) + return; + arrangeNonLayerSurface(surface, ArrangeReason::InitialPlacement); + }; + + connect(surface, &SurfaceWrapper::widthChanged, this, layoutSurface); + connect(surface, &SurfaceWrapper::heightChanged, this, layoutSurface); + connect(surface, &SurfaceWrapper::hasInitializeContainerChanged, this, layoutSurface); + layoutSurface(); + + if (surface->type() == SurfaceWrapper::Type::XdgPopup) { + auto xdgPopupSurfaceItem = qobject_cast(surface->surfaceItem()); + connect(xdgPopupSurfaceItem, &WXdgPopupSurfaceItem::implicitPositionChanged, this, [surface, this] { + // Reposition should ignore positionAutomatic + arrangePopupSurface(surface); + }); + } else if (surface->type() == SurfaceWrapper::Type::InputPopup) { + auto inputPopupSurfaceItem = qobject_cast(surface->surfaceItem()); + connect(inputPopupSurfaceItem, &WInputPopupSurfaceItem::referenceRectChanged, this, [surface, this] { + // Reposition should ignore positionAutomatic + arrangePopupSurface(surface); + }); + } + } +} + +void Output::removeSurface(SurfaceWrapper *surface) +{ + clearPopupCache(surface); + m_initialWindowPositionRatio.remove(surface); + Q_ASSERT(hasSurface(surface)); + SurfaceListModel::removeSurface(surface); + if (auto *desktop = surface->desktop()) + desktop->outputs()->outputState(this)->removeSurface(surface); + surface->disconnect(this); + + if (surface->type() == SurfaceWrapper::Type::Layer) { + if (auto *shell = surface->shellSurface()) + shell->disconnect(this); + arrangeLayerSurfaces(); + } +} + +WOutput *Output::output() const +{ + auto o = m_item->output(); + Q_ASSERT(o); + return o; +} + +WOutputItem *Output::outputItem() const +{ + return m_item; +} + +Output *Output::proxyOutput() const +{ + return m_proxy; +} + +void Output::arrangeLayerSurfaces() +{ + const auto previous = m_exclusiveZone; + auto *server = WaylandServer::instance(); + // Each logical output computes its own layout, including inactive users. + // This physical output only publishes the active user's available area. + for (auto *desktop : server->desktopEnvironments()) + desktop->outputs()->outputState(this)->arrangeLayerSurfaces(); + auto *active = server->desktop(); + m_exclusiveZone = active ? active->outputs()->outputState(this)->exclusiveZone() + : compositorExclusiveZone(); + arrangeNonLayerSurfaces(ArrangeReason::ExclusiveZoneChanged); + if (previous != m_exclusiveZone) + Q_EMIT exclusiveZoneChanged(); +} + +void Output::arrangeNonLayerSurface(SurfaceWrapper *surface, ArrangeReason reason) +{ + Q_ASSERT(surface->type() != SurfaceWrapper::Type::Layer); + if (surface->isIMCandidatePanel()) + return; + // Output::addSurface() hooks width/height/hasInitializeContainer straight to + // this function, bypassing the arrangeNonLayerSurfaces() filter. A lock surface + // must cover the whole output: arranging it would shrink it to validGeometry() + // (exclusive zone removed) and center it, i.e. the maximized rect. + if (surface->type() == SurfaceWrapper::Type::LockScreen) + return; + + const auto fullGeometry = surface->desktop() + ? surface->desktop()->outputs()->outputState(this)->geometry() : geometry(); + surface->setFullscreenGeometry(fullGeometry); + const auto validGeo = validGeometryForSurface(surface); + surface->setMaximizedGeometry(validGeo); + + QRectF normalGeo = surface->normalGeometry(); + + if (surface->positionAutomatic()) { + if (normalGeo.isEmpty()) + return; + + // NOTE: Xwayland popups don't have parents + SurfaceWrapper *parentSurfaceWrapper = surface->parentSurface(); + + if (parentSurfaceWrapper) { + if (surface->type() == SurfaceWrapper::Type::XdgPopup + || surface->type() == SurfaceWrapper::Type::InputPopup) { + arrangePopupSurface(surface); + return; + } + QPointF dPos{ (parentSurfaceWrapper->width() - surface->width()) / 2, + (parentSurfaceWrapper->height() - surface->height()) / 2 }; + QPointF topLeft; + topLeft.setX(parentSurfaceWrapper->x() + dPos.x()); + topLeft.setY(parentSurfaceWrapper->y() + dPos.y()); + if (parentSurfaceWrapper->ownsOutput() != this) { + // Parent is on a different output: follow it without clamping + // to this output's validGeo. + surface->moveNormalGeometryInOutput(topLeft); + } else { + // Parent and child share this output: apply the titlebar clamp + // so near-edge dialogs remain accessible. + moveSurfaceWithTitlebarClamp(surface, topLeft); + } + } else { + if (reason != ArrangeReason::InitialPlacement) { + auto constrained = + constrainToValidArea(normalGeo.topLeft(), normalGeo.size(), validGeo); + if (constrained != normalGeo.topLeft()) + moveSurfaceWithTitlebarClamp(surface, constrained); + } else { + auto outputValidGeometry = surface->ownsOutput()->validGeometryForSurface(surface); + if (normalGeo.width() > outputValidGeometry.width() + || normalGeo.height() > outputValidGeometry.height()) + surface->resize(outputValidGeometry.size()); + if (surface->type() == SurfaceWrapper::Type::XdgToplevel + || surface->type() == SurfaceWrapper::Type::SplashScreen) { + placeSmartCascaded(surface); + } else { + placeCentered(surface); + } + } + } + } else if (reason == ArrangeReason::OutputGeometryChanged) { + if (!m_initialWindowPositionRatio.contains(surface)) { + qreal xRatio = 0.5, yRatio = 0.5; // Default center position + if (validGeo.width() > normalGeo.width()) { + xRatio = (normalGeo.x() - validGeo.x()) / (validGeo.width() - normalGeo.width()); + xRatio = qBound(0.0, xRatio, 1.0); + } + if (validGeo.height() > normalGeo.height()) { + yRatio = (normalGeo.y() - validGeo.y()) / (validGeo.height() - normalGeo.height()); + yRatio = qBound(0.0, yRatio, 1.0); + } + m_initialWindowPositionRatio[surface] = QPointF(xRatio, yRatio); + } + + QPointF ratio = m_initialWindowPositionRatio[surface]; + QPointF pos; + pos.setX(validGeo.x() + ratio.x() * (validGeo.width() - normalGeo.width())); + pos.setY(validGeo.y() + ratio.y() * (validGeo.height() - normalGeo.height())); + + // Boundary protection ensures that at least 30% of the window remains within the screen. + const qreal minVisibleRatio = 0.3; + const int minVisibleX = qMin(100, int(normalGeo.width() * minVisibleRatio)); + const int minVisibleY = qMin(100, int(normalGeo.height() * minVisibleRatio)); + pos.setX(qBound(validGeo.left() - normalGeo.width() + minVisibleX, + pos.x(), + validGeo.right() - minVisibleX)); + pos.setY(qBound(validGeo.top() - normalGeo.height() + minVisibleY, + pos.y(), + validGeo.bottom() - minVisibleY)); + moveSurfaceWithTitlebarClamp(surface, pos); + } else { + // (0,0) is a valid fixed position, so presence of a position request + // is tracked explicitly, not via QPoint::isNull(). + if (const auto pos = surface->clientRequstPos()) { + placeClientRequstPos(surface, *pos); + } else if (surface->autoPlaceCursorOffset().has_value() + && reason == ArrangeReason::InitialPlacement) { + // Cursor placement is compositor-driven and only affects the + // initial layout (per dde-shell-v2 semantics). + placeUnderCursor(surface); + } else if (reason == ArrangeReason::LayerSurfaceRemoved + || reason == ArrangeReason::ExclusiveZoneChanged) { + // validGeo has changed (panel added/removed); re-run the titlebar + // clamp so the titlebar remains visible in the updated work area. + // The window position itself is preserved — only clamped if needed. + moveSurfaceWithTitlebarClamp(surface, normalGeo.topLeft()); + } + // For InitialPlacement with non-automatic positioning the server + // deliberately does not move the window: client geometry is authoritative. + } +} + +namespace { +// Get the popup position (dPos) in the parent surface's coordinate space. +// Both popup kinds report surface coordinates: implicitPosition comes from +// wlr_xdg_popup_get_position(), and cursorRect is the IME client's raw surface +// rect. calculateBasePosition() maps that space onto the parent wrapper. +std::optional popupDPos(SurfaceWrapper *surface) +{ + using Type = SurfaceWrapper::Type; + if (surface->type() == Type::XdgPopup) { + auto *item = qobject_cast(surface->surfaceItem()); + if (item) + return item->implicitPosition(); + } + + if (surface->type() == Type::InputPopup) { + auto *shell = qobject_cast(surface->shellSurface()); + if (shell) + return shell->cursorRect().bottomLeft(); + } + + qCWarning(lcTlOutput) << " Invalid popup surface type:" << surface->type(); + return std::nullopt; +} +} // namespace + +QPointF Output::calculateBasePosition(SurfaceWrapper *surface, const QPointF &dPos) const +{ + auto parent = surface->parentSurface(); + if (!parent || !parent->surfaceItem()) { + qCWarning(lcTlOutput) << " Invalid parent surface or surface item!"; + return QPointF(); + } + + // dPos is expressed in the parent's surface coordinates: xdg-shell positions + // a popup relative to the parent's window geometry, and wlr reports it with + // the popup's own window geometry offset subtracted, so dPos carries both + // the parent's CSD margins and the popup's. The wrapper is positioned at + // its own item origin; mapFromSurface() folds in the content geometry + // offset (CSD margins) and paddings (SSD titlebar) to land the anchor on + // the parent's content area, and the popup's own offsets are cancelled + // below so the wrapper lands on the anchor the client requested. + const QPointF parentContentPos = parent->mapFromSurface(dPos); + + QPointF ownContentOffset; + if (auto *shell = surface->shellSurface()) + ownContentOffset = QPointF(shell->getContentGeometry().topLeft()); + if (auto *item = surface->surfaceItem()) + ownContentOffset -= QPointF(item->leftPadding(), item->topPadding()); + + return QPointF(parent->x() + parentContentPos.x() + ownContentOffset.x(), + parent->y() + parentContentPos.y() + ownContentOffset.y()); +} + +void Output::adjustToOutputBounds(QPointF &pos, const QRectF &normalGeo, const QRectF &outputRect) const +{ + if (pos.x() + normalGeo.width() > outputRect.right() - POPUP_EDGE_MARGIN) { + pos.setX(outputRect.right() - normalGeo.width() - POPUP_EDGE_MARGIN); + } + if (pos.x() < outputRect.left() + POPUP_EDGE_MARGIN) { + pos.setX(outputRect.left() + POPUP_EDGE_MARGIN); + } + + if (pos.y() + normalGeo.height() > outputRect.bottom() - POPUP_EDGE_MARGIN) { + pos.setY(outputRect.bottom() - normalGeo.height() - POPUP_EDGE_MARGIN); + } + if (pos.y() < outputRect.top() + POPUP_EDGE_MARGIN) { + pos.setY(outputRect.top() + POPUP_EDGE_MARGIN); + } +} + +void Output::handleLayerShellPopup(SurfaceWrapper *surface, const QRectF &normalGeo) +{ + if (!surface->parentSurface() || !surface->parentSurface()->ownsOutput()) { + qCWarning(lcTlOutput) << " Invalid LayerShell parent surface!"; + return; + } + + auto parentOutput = surface->parentSurface()->ownsOutput()->outputItem(); + auto dPos = popupDPos(surface); + if (!dPos.has_value()) + return; + + QPointF pos = calculateBasePosition(surface, dPos.value()); + if (pos.isNull()) { + return; + } + + QRectF outputRect(parentOutput->position(), parentOutput->size()); + adjustToOutputBounds(pos, normalGeo, outputRect); + surface->moveNormalGeometryInOutput(pos); +} + +void Output::handleRegularPopup(SurfaceWrapper *surface, const QRectF &normalGeo, WOutputItem *targetOutput) +{ + if (normalGeo.isEmpty()) { + return; + } + + auto dPos = popupDPos(surface); + if (!dPos.has_value()) + return; + + QPointF pos = calculateBasePosition(surface, dPos.value()); + if (pos.isNull()) { + return; + } + + QRectF outputRect(targetOutput->position(), targetOutput->size()); + + // TODO: Use xdg_positioner::constraint_adjustment to properly respect client's positioning constraints + if (pos.x() < outputRect.left()) { + pos.setX(outputRect.left()); + } + if (pos.x() + normalGeo.width() > outputRect.right()) { + pos.setX(outputRect.right() - normalGeo.width()); + } + + adjustToOutputBounds(pos, normalGeo, outputRect); + + QRectF newGeo = normalGeo; + newGeo.moveTopLeft(pos); + m_positionCache[surface] = qMakePair(pos, newGeo); + surface->moveNormalGeometryInOutput(pos); +} + +void Output::clearPopupCache(SurfaceWrapper *surface) +{ + if (!surface || m_positionCache.isEmpty()) { + return; + } + + if (surface->type() == SurfaceWrapper::Type::XdgPopup || surface->isInputPopupLike()) { + m_positionCache.remove(surface); + } +} + +void Output::arrangePopupSurface(SurfaceWrapper *surface) +{ + SurfaceWrapper *parentSurfaceWrapper = surface->parentSurface(); + if (!parentSurfaceWrapper) { + // When an input popup is still alive while its parent text-input client is being torn down, + // arrangePopupSurface() can run in a transient state where parentSurface is temporarily unavailable. + qCWarning(lcTlSurface) << "[popup] skip arrangePopupSurface: missing parent surface" + << "surface=" << surface; + return; + } + + QRectF normalGeo = surface->normalGeometry(); + if (normalGeo.isEmpty()) { + return; + } + + WOutputItem *targetOutput = nullptr; + // TODO: Consider determining the targetOutput based on the upper left corner or overlapping area + if (surface->type() == SurfaceWrapper::Type::XdgPopup) { + auto *outputAtCursor = WaylandServer::instance()->getOutputAtCursor(); + targetOutput = outputAtCursor ? outputAtCursor->outputItem() : nullptr; + } else if (surface->isInputPopupLike()) { + auto *parentOutput = parentSurfaceWrapper->ownsOutput(); + targetOutput = parentOutput ? parentOutput->outputItem() : nullptr; + } + + if (!targetOutput) { + qCInfo(lcTlSurface) << "[popup] skip arrangePopupSurface: missing target output" + << "surface=" << surface + << "parentSurface=" << parentSurfaceWrapper; + return; + } + + if (parentSurfaceWrapper->type() == SurfaceWrapper::Type::Layer) { + handleLayerShellPopup(surface, normalGeo); + } else { + handleRegularPopup(surface, normalGeo, targetOutput); + } +} + +void Output::arrangeNonLayerSurfaces(ArrangeReason reason) +{ + for (SurfaceWrapper *surface : std::as_const(surfaces())) { + if (surface->type() == SurfaceWrapper::Type::Layer || surface->isInputPopupLike() + || !surface->hasInitializeContainer()) + continue; + arrangeNonLayerSurface(surface, reason); + } +} + +void Output::arrangeAllSurfaces() +{ + arrangeLayerSurfaces(); + arrangeNonLayerSurfaces(ArrangeReason::OutputGeometryChanged); +} + +SurfaceListModel *Output::minimizedSurfaces() const +{ + auto *desktop = WaylandServer::instance()->desktop(); + return desktop ? desktop->outputs()->outputState(const_cast(this))->minimizedSurfaces() + : nullptr; +} + +QMargins Output::exclusiveZone() const +{ + return m_exclusiveZone; +} + +QRectF Output::rect() const +{ + return QRectF(QPointF(0, 0), m_item->size()); +} + +QRectF Output::geometry() const +{ + return QRectF(m_item->position(), m_item->size()); +} + +QRectF Output::validRect() const +{ + return rect().marginsRemoved(m_exclusiveZone); +} + +WOutputViewport *Output::screenViewport() const +{ + return m_outputViewport; +} + +QMargins Output::compositorExclusiveZone() const +{ + // The compositor's optional debug bar is shared infrastructure, not a + // client's LayerSurface. Reserve it independently of user panels. + const int top = m_debugMenuBar && m_debugMenuBar->isVisible() ? m_debugMenuBar->height() : 0; + return QMargins(0, top, 0, 0); +} + +QRectF Output::validGeometryForSurface(SurfaceWrapper *surface) const +{ + if (auto *desktop = surface->desktop()) + return desktop->outputs()->outputState(const_cast(this))->validGeometry(); + return validGeometry(); +} + +QRectF Output::validGeometry() const +{ + return geometry().marginsRemoved(m_exclusiveZone); +} + +QRectF Output::tileGeometry(SurfaceWrapper::TileMode mode, SurfaceWrapper *surface) const +{ + if (mode == SurfaceWrapper::TileMode::None) + return QRectF(); + + const QRectF area = surface ? validGeometryForSurface(surface) : validGeometry(); + const QSizeF half(area.width() / 2, area.height()); + const QSizeF quad(area.width() / 2, area.height() / 2); + switch (mode) { + case SurfaceWrapper::TileMode::Left: + return QRectF(area.topLeft(), half); + case SurfaceWrapper::TileMode::Right: + return QRectF(QPointF(area.left() + area.width() / 2, area.top()), half); + case SurfaceWrapper::TileMode::Maximize: + return area; + case SurfaceWrapper::TileMode::TopLeft: + return QRectF(area.topLeft(), quad); + case SurfaceWrapper::TileMode::TopRight: + return QRectF(QPointF(area.left() + area.width() / 2, area.top()), quad); + case SurfaceWrapper::TileMode::BottomLeft: + return QRectF(QPointF(area.left(), area.top() + area.height() / 2), quad); + case SurfaceWrapper::TileMode::BottomRight: + return QRectF(QPointF(area.left() + area.width() / 2, area.top() + area.height() / 2), quad); + case SurfaceWrapper::TileMode::None: + break; + } + return QRectF(); +} + +// do not use config()->setBrightness or config()->setColorTemperature to set color temperature or brightness +// as doing so will have no effect. +// use Output::setOutputColor instead +OutputConfig *Output::config() const +{ + return m_config; +} + +QString Output::uuid() const +{ + return m_config ? m_config->uuid() : QString(); +} + +void Output::applyOutputColorConfig() +{ + auto *outputConfig = config(); + auto applyConfig = [this, outputConfig] { + if (config() != outputConfig) + return; + // Color temperature is implemented with the gamma LUT. When the output + // has no LUT the value can never be applied, so do not request it: + // setOutputColor() would report Unsupported and return before the + // backlight is touched, dropping the brightness restore as well. That + // leaves the panel at hardware defaults (full backlight, no + // compensation) after a compositor restart or an output rebuild, even + // though the brightness is in the persisted config. Restoring the + // brightness alone is as much as this hardware can honour. + const bool colorTemperatureSupported = + wlr_output_get_gamma_size(output()->handle()) > 0; + setOutputColor(outputConfig->brightness(), + colorTemperatureSupported + ? static_cast(outputConfig->colorTemperature()) + : 0); + }; + + if (outputConfig->isInitializeSucceeded() || outputConfig->isInitializeFailed()) { + applyConfig(); + return; + } + + connect(outputConfig, + &OutputConfig::configInitializeSucceed, + this, + applyConfig, + Qt::SingleShotConnection); + connect(outputConfig, + &OutputConfig::configInitializeFailed, + this, + applyConfig, + Qt::SingleShotConnection); +} + +namespace { +static inline void kelvinToRGB(double kelvin, double &r, double &g, double &b) +{ + kelvin = std::clamp(kelvin, 1000.0, 20000.0) / 100.0; + + if (kelvin <= 66.0) r = 1.0; + else r = std::clamp(329.698727446 * std::pow(kelvin - 60.0, -0.1332047592) / 255.0, 0.0, 1.0); + + if (kelvin <= 66.0) + g = std::clamp((99.4708025861 * std::log(kelvin) - 161.1195681661) / 255.0, 0.0, 1.0); + else + g = std::clamp(288.1221695283 * std::pow(kelvin - 60.0, -0.0755148492) / 255.0, 0.0, 1.0); + + if (kelvin >= 66.0) b = 1.0; + else if (kelvin <= 19.0) b = 0.0; + else b = std::clamp((138.5177312231 * std::log(kelvin - 10.0) - 305.0447927307) / 255.0, 0.0, 1.0); +} + +static inline void generateGammaLUT(uint32_t colorTemperature, + qreal brightness, + size_t gammaSize, + QVector &r, + QVector &g, + QVector &b) +{ + if (gammaSize == 0) { + return; + } + + double cr, cg, cb; + kelvinToRGB(static_cast(colorTemperature), cr, cg, cb); + for (size_t i = 0; i < gammaSize; ++i) { + double normalized = static_cast(i) / static_cast(gammaSize - 1); + + double rValue = std::clamp(normalized * cr * brightness, 0.0, 1.0); + double gValue = std::clamp(normalized * cg * brightness, 0.0, 1.0); + double bValue = std::clamp(normalized * cb * brightness, 0.0, 1.0); + r[i] = static_cast(std::round(rValue * 65535.0)); + g[i] = static_cast(std::round(gValue * 65535.0)); + b[i] = static_cast(std::round(bValue * 65535.0)); + } +} + +} + +// TODO: better Chromatic Adaptation algorithms can be implemented when the wlr_color_transform +// api is available. For now RGB scaling is used due to limitation of gamma LUT table. +// see: http://www.brucelindbloom.com/index.html?ChromAdaptEval.html +void Output::setOutputColor(qreal brightness, + uint32_t colorTemperature, + std::function resultCallback) +{ + auto *targetConfig = config(); + const bool brightnessRequested = brightness >= 0; + const bool colorTemperatureRequested = colorTemperature != 0; + + if (!brightnessRequested) + brightness = config()->brightness(); + if (!colorTemperatureRequested) + colorTemperature = config()->colorTemperature(); + + brightness = qBound(0.0, brightness, 1.0); + colorTemperature = std::clamp(colorTemperature, 1000u, 20000u); + + const size_t gammaSize = wlr_output_get_gamma_size(output()->handle()); + if (gammaSize == 0 && colorTemperatureRequested) { + // No gamma LUT: a requested color temperature cannot be applied at all. + // Report unsupported before touching backlight or config so that the + // protocol promise "settings remain unchanged" holds. + if (resultCallback) + resultCallback(CommitColorResult::Unsupported); + qCWarning(lcTlOutput) << " Output " << output()->name() + << " does not support gamma LUT! Brightness and color temperature adjustments through gamma will have no effect."; + return; + } + + // No-op fast path: when the requested values already match what is applied, + // skip the backlight sysfs write, the gamma LUT regeneration and the full + // output commit. Rapid slider drags otherwise queue one heavy commit per + // intermediate value and stall the compositor. Compare against the applied + // values, not config(): config() holds the persisted value, which still has + // to be pushed to the hardware when the output starts or is hotplugged. + const bool brightnessUnchanged = + !brightnessRequested + || (m_appliedBrightness >= 0 && qFuzzyCompare(brightness, m_appliedBrightness)); + const bool colorTemperatureUnchanged = + !colorTemperatureRequested + || (m_appliedColorTemperature != 0 + && colorTemperature == m_appliedColorTemperature); + if (brightnessUnchanged && colorTemperatureUnchanged) { + if (resultCallback) + resultCallback(CommitColorResult::Success); + return; + } + + qreal brightnessCorrection = 1.0; + bool backlightApplied = false; + + if (m_backlight) { + qreal backlightBrightness = m_backlight->setBrightness(brightness); + backlightApplied = qFuzzyCompare(backlightBrightness, brightness); + if (backlightBrightness != 0) + brightnessCorrection = qBound(0.0, brightness / backlightBrightness, 1.0); + } else { + brightnessCorrection = brightness; + } + + if (gammaSize == 0) { + if (backlightApplied) { + targetConfig->setBrightness(brightness); + m_appliedBrightness = brightness; + } + if (resultCallback) + resultCallback(backlightApplied ? CommitColorResult::Success + : CommitColorResult::Failed); + qCWarning(lcTlOutput) << " Output " << output()->name() + << " does not support gamma LUT! Brightness and color temperature adjustments through gamma will have no effect."; + return; + } + + QVector r(gammaSize); + QVector g(gammaSize); + QVector b(gammaSize); + + generateGammaLUT(colorTemperature, + brightnessCorrection, + gammaSize, + r, + g, + b); + + // Keep mode/scale/transform that is already staged for this output; a + // colour-only replacement would silently drop it. + WOutputHelper::ExtraState newState = extraState(); + if (!newState) + newState = WOutputHelper::ExtraState(); + auto *viewport = screenViewport(); + auto *renderWindow = screenViewport()->outputRenderWindow(); + auto *tr = wlr_color_transform_init_lut_3x1d(gammaSize, + r.constData(), + g.constData(), + b.constData()); + if (!tr) { + qCWarning(lcTlOutput) << "Failed to create color transform for lut_3x1d on output" << output()->name(); + if (resultCallback) + resultCallback(CommitColorResult::Failed); + return; + } + wlr_output_state_set_color_transform(newState.get(), tr); + wlr_color_transform_unref(tr); + + auto *outputHelper = renderWindow->getOutputHelper(viewport); + outputHelper->setExtraState(newState); + + outputHelper->scheduleCommitJob([this, targetConfig, brightness, colorTemperature, newState, resultCallback](bool success, WOutputHelper::ExtraState state) { + if (state == newState) { + if (config() != targetConfig) { + if (resultCallback) + resultCallback(CommitColorResult::Failed); + applyOutputColorConfig(); + return; + } + if (resultCallback) + resultCallback(success ? CommitColorResult::Success : CommitColorResult::Failed); + if (!success) { + qCWarning(lcTlOutput) << "Failed to apply brightness and color temperature settings to output" + << output()->name(); + } else { + targetConfig->setBrightness(brightness); + targetConfig->setColorTemperature(colorTemperature); + m_appliedBrightness = brightness; + m_appliedColorTemperature = colorTemperature; + } + } else { + if (resultCallback) + resultCallback(CommitColorResult::Failed); + qCWarning(lcTlOutput) << "Commit callback received unexpected state pointer!" + << "Expected:" << newState.get() + << "Got:" << state.get(); + } + }, WOutputHelper::AfterCommitStage); + renderWindow->update(viewport); +} diff --git a/src/output/output.h b/src/output/output.h new file mode 100644 index 0000000000..6d1ff024e6 --- /dev/null +++ b/src/output/output.h @@ -0,0 +1,237 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "surface/surfacecontainer.h" +#include "backlight.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +Q_MOC_INCLUDE() +Q_MOC_INCLUDE("outputconfig.hpp") + +struct wlr_output; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutput; +class WOutputItem; +class WOutputViewport; +class WOutputLayout; +class WOutputLayer; +class WQuickTextureProxy; +class WSeat; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class SurfaceWrapper; +class OutputConfig; + +class Output : public SurfaceListModel +{ + Q_OBJECT + QML_ANONYMOUS + Q_PROPERTY(QMargins exclusiveZone READ exclusiveZone NOTIFY exclusiveZoneChanged FINAL) + Q_PROPERTY(QRectF validRect READ validRect NOTIFY exclusiveZoneChanged FINAL) + Q_PROPERTY(WOutputItem* outputItem MEMBER m_item CONSTANT) + Q_PROPERTY(SurfaceListModel* minimizedSurfaces READ minimizedSurfaces NOTIFY minimizedSurfacesChanged FINAL) + Q_PROPERTY(WOutputViewport* screenViewport MEMBER m_outputViewport CONSTANT) + Q_PROPERTY(OutputConfig* config READ config NOTIFY configChanged FINAL) + +public: + enum class Type + { + Source, + Mirror + }; + + enum class PlaceDirection + { + TopLeft, + BottomRight, + }; + + enum class ArrangeReason + { + InitialPlacement, + ExclusiveZoneChanged, + LayerSurfaceRemoved, + OutputGeometryChanged, + }; + + // Result of an Output::setOutputColor() apply, reported to the optional + // result callback. Lets the caller distinguish a hardware capability gap + // (unsupported) from a transient failure (failed). + enum class CommitColorResult + { + Success, // settings were applied + Unsupported, // hardware cannot apply the requested adjustment + // (e.g. no gamma LUT when changing color temperature) + Failed, // the commit could not be applied for a transient or + // unknown reason; settings remain unchanged + }; + + static Output *create(WOutput *output, QQmlEngine *engine, QObject *parent = nullptr); + static Output *createCopy(WOutput *output, + Output *proxy, + QQmlEngine *engine, + QObject *parent = nullptr); + static QString getOutputId(wlr_output *output); + QString getOutputId(); + + explicit Output(WOutput *output, QObject *parent = nullptr); + // Bind the QML item created for this output. Called once, right after the + // item exists and before anything else touches the output. + void setOutputItem(WOutputItem *item); + ~Output() override; + + bool isSource() const; + + void addSurface(SurfaceWrapper *surface) override; + void removeSurface(SurfaceWrapper *surface) override; + + WOutput *output() const; + WOutputItem *outputItem() const; + + SurfaceListModel *minimizedSurfaces() const; + QMargins exclusiveZone() const; + QRectF rect() const; + QRectF geometry() const; + QRectF validRect() const; + QRectF validGeometry() const; + QRectF tileGeometry(SurfaceWrapper::TileMode mode, SurfaceWrapper *surface = nullptr) const; + WOutputViewport *screenViewport() const; + void updatePositionFromLayout(); + void applyOutputColorConfig(); + QQuickItem *debugMenuBar() const; + + static double calcPreferredScale(double widthPx, + double heightPx, + double widthMm, + double heightMm); + qreal preferredScaleFactor(const QSize &pixelSize) const; + // Sync the QML item and viewport to this geometry. Does not touch + // wlr_output_state. Viewport size is the unrotated mode. Item size is the + // logical size after transform and scale. + void applyGeometry(const QSize &modePixels, WOutput::Transform transform, qreal scale); + // Request a rotation of this output. The output QML registers a handler + // (rotationOutputHandler) that animates the viewport and commits the + // transform at its halfway point; without a handler the rotation is + // applied immediately. + Q_INVOKABLE void rotationOutput(WOutput::Transform transform); + // QML only: called by the rotation animation at its halfway point. C++ + // callers must use rotationOutput() instead, so the visual and the state + // stay in sync. (QML cannot invoke a private Q_INVOKABLE.) + Q_INVOKABLE bool setTransform(WOutput::Transform transform); + Q_PROPERTY(QJSValue rotationOutputHandler READ rotationOutputHandler + WRITE setRotationOutputHandler NOTIFY rotationOutputHandlerChanged) + QJSValue rotationOutputHandler() const; + void setRotationOutputHandler(const QJSValue &handler); + // Resync item/viewport from the pending output state, falling back to the + // committed mode/orientation/scale for fields that are not staged. + // rotateViewport is false only for the animated rotation, which owns the + // viewport rotation itself and commits at its halfway point. + void applyPendingGeometry(bool rotateViewport = true); + bool setExtraState(WOutputHelper::ExtraState state); + WOutputHelper::ExtraState extraState() const; + + OutputConfig* config() const; + QString uuid() const; + Output *proxyOutput() const; + + void adjustToOutputBounds(QPointF &pos, + const QRectF &normalGeo, + const QRectF &outputRect) const; + +Q_SIGNALS: + void rotationOutputHandlerChanged(); + void configChanged(); + void exclusiveZoneChanged(); + void minimizedSurfacesChanged(); + void moveResizeFinised(); + void brightnessChanged(); + void colorTemperatureChanged(); + +public Q_SLOTS: + void enable(); + void updateOutputHardwareLayers(); + void setOutputColor(qreal brightness, + uint32_t colorTemperature, + std::function resultCallback = nullptr); + +private: + friend class SurfaceWrapper; + friend class SessionOutput; + + QMargins compositorExclusiveZone() const; + QRectF validGeometryForSurface(SurfaceWrapper *surface) const; + void arrangeLayerSurfaces(); + void arrangeNonLayerSurface(SurfaceWrapper *surface, ArrangeReason reason); + void arrangePopupSurface(SurfaceWrapper *surface); + void arrangeNonLayerSurfaces(ArrangeReason reason); + void arrangeAllSurfaces(); + std::pair getOutputItemProperty(); + void placeUnderCursor(SurfaceWrapper *surface); + void placeClientRequstPos(SurfaceWrapper *surface, QPoint clientRequstPos); + void placeCentered(SurfaceWrapper *surface); + void placeSmartCascaded(SurfaceWrapper *surface); + QPointF calculateBottomRightPosition(const QRectF &activeGeo, + const QRectF &normalGeo, + const QRectF &validGeo, + const QSizeF &offset); + QPointF calculateTopLeftPosition(const QRectF &activeGeo, + const QRectF &normalGeo, + const QRectF &validGeo, + const QSizeF &offset); + QPointF constrainToValidArea(const QPointF &pos, + const QSizeF &windowSize, + const QRectF &validGeo); + // Move surface to pos and then clamp it so that its titlebar remains + // visible within this output's validGeometry. Always prefer this helper + // over calling surface->moveNormalGeometryInOutput() directly when the + // window is expected to stay on this output. + void moveSurfaceWithTitlebarClamp(SurfaceWrapper *surface, const QPointF &pos); + qreal preferredScaleFactor() const; + // Rotate the QML viewport to match an output transform. The buffer is + // rotated at scanout, so the viewport carries the opposing rotation. + void setViewportRotation(WOutput::Transform transform); + + QPointF calculateBasePosition(SurfaceWrapper *surface, const QPointF &dPos) const; + void handleLayerShellPopup(SurfaceWrapper *surface, const QRectF &normalGeo); + void handleRegularPopup(SurfaceWrapper *surface, const QRectF &normalGeo, WOutputItem *targetOutput); + void clearPopupCache(SurfaceWrapper *surface); + + QJSValue m_rotationOutputHandler; + Type m_type; + WOutputItem *m_item = nullptr; + Output *m_proxy = nullptr; + QPointer m_debugMenuBar; + WOutputViewport *m_outputViewport = nullptr; + + QMargins m_exclusiveZone; + + QList m_hardwareLayersOfSourceOutput; + PlaceDirection m_nextPlaceDirection = PlaceDirection::BottomRight; + + QMap> m_positionCache; + QHash m_initialWindowPositionRatio; + + std::unique_ptr m_backlight = nullptr; + OutputConfig *m_config; + // Values last applied to the hardware, as opposed to config() which holds + // the persisted value that still has to be restored on start and hotplug. + // The negative / zero defaults mean "never applied". + qreal m_appliedBrightness = -1; + uint32_t m_appliedColorTemperature = 0; +}; + +Q_DECLARE_OPAQUE_POINTER(WAYLIB_SERVER_NAMESPACE::WOutputItem *) diff --git a/src/output/outputmanager.cpp b/src/output/outputmanager.cpp new file mode 100644 index 0000000000..c6e0add044 --- /dev/null +++ b/src/output/outputmanager.cpp @@ -0,0 +1,2132 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include "session/sessionmanager.h" +#include "outputmanager.h" + +#include "common/treelandlogging.h" +#include "dconfig/dconfigmanager.h" +#include "core/rootsurfacecontainer.h" +#include "core/waylandserver.h" +#include "utils/graphicsplatform.h" +#include "modules/output-group/outputgroupmanagerinterfacev1.h" +#include "output.h" +#include "outputconfig.hpp" +#include "session/session.h" +#include "session/sessionoutputmanager.h" +#include "surface/surfacewrapper.h" +#include "treelandconfig.hpp" +#include "wallpaper/wallpapermanager.h" +#include "workspace/workspace.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#ifndef DISABLE_XWAYLAND +#include +#endif +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace { +bool hasSavedOutputState(OutputConfig *config) +{ + return config && (!config->widthIsDefaultValue() + || !config->heightIsDefaultValue() + || !config->refreshIsDefaultValue() + || !config->scaleIsDefaultValue() + || !config->transformIsDefaultValue() + || !config->adaptiveSyncEnabledIsDefaultValue()); +} + +bool outputConfigInitializationFinished(OutputConfig *config) +{ + return config && (config->isInitializeSucceeded() || config->isInitializeFailed()); +} + +bool outputMatchesId(Output *output, const QString &outputId) +{ + return output && output->output() && output->output()->isEnabled() + && output->getOutputId() == outputId; +} + +bool currentPrimaryMatchesId(RootSurfaceContainer *rootContainer, const QString &outputId) +{ + return rootContainer && outputMatchesId(rootContainer->primaryOutput(), outputId); +} + +wlr_output_mode *closestOutputMode(WAYLIB_SERVER_NAMESPACE::WOutput *output, + int width, + int height, + int refresh) +{ + if (!output || !output->handle()) { + return nullptr; + } + + wlr_output_mode *mode = nullptr; + wlr_output_mode *closestMode = nullptr; + qint64 closestResolutionDistance = std::numeric_limits::max(); + qint64 closestRefreshDistance = std::numeric_limits::max(); + wl_list_for_each(mode, &output->handle()->modes, link) { + const qint64 resolutionDistance = std::abs(static_cast(mode->width) - width) + + std::abs(static_cast(mode->height) - height); + const qint64 refreshDistance = std::abs(static_cast(mode->refresh) - refresh); + if (resolutionDistance < closestResolutionDistance + || (resolutionDistance == closestResolutionDistance + && refreshDistance < closestRefreshDistance)) { + closestMode = mode; + closestResolutionDistance = resolutionDistance; + closestRefreshDistance = refreshDistance; + } + if (resolutionDistance == 0 && refreshDistance == 0) { + break; + } + } + return closestMode; +} + +bool stageOutputConfig(Output *output, + int width, + int height, + int refresh, + qlonglong transform, + double scale, + bool adaptiveSync) +{ + if (!output || width <= 0 || height <= 0 || refresh <= 0 || scale <= 0.0) + return false; + + qCInfo(lcTlOutput) << "Restoring output" << output->output()->name() + << "mode" << QSize(width, height) << "@" << refresh + << "scale" << scale << "transform" << transform; + + WOutputHelper::ExtraState extra; + // Restoring an output means bringing it up: during the initial scan the + // output may be temporarily disabled, and a commit without ENABLED would + // leave the restored mode/scale unapplied until something else enables it. + wlr_output_state_set_enabled(extra.get(), true); + if (auto *mode = closestOutputMode(output->output(), width, height, refresh)) + wlr_output_state_set_mode(extra.get(), mode); + else + wlr_output_state_set_custom_mode(extra.get(), width, height, refresh); + wlr_output_state_set_transform(extra.get(), static_cast(transform)); + wlr_output_state_set_scale(extra.get(), scale); + wlr_output_state_set_adaptive_sync_enabled(extra.get(), adaptiveSync); + if (!output->setExtraState(extra)) + return false; + + output->applyPendingGeometry(); + return true; +} + +} // namespace + +OutputManager::OutputManager(RootSurfaceContainer *rootContainer, + TreelandConfig *config, + WOutputRenderWindow *renderWindow, + QObject *parent) + : QObject(parent) + , m_rootContainer(rootContainer) + , m_config(config) + , m_renderWindow(renderWindow) +{ + Q_ASSERT(m_rootContainer); + Q_ASSERT(m_config); + Q_ASSERT(m_renderWindow); + connect(m_config, &TreelandConfig::configInitializeSucceed, + this, &OutputManager::finishInitialOutputScanIfReady); + connect(m_config, &TreelandConfig::configInitializeFailed, + this, &OutputManager::finishInitialOutputScanIfReady); + connect(m_rootContainer, &RootSurfaceContainer::primaryOutputChanged, + this, &OutputManager::configurationChanged); + connect(this, &OutputManager::modeChanged, this, &OutputManager::configurationChanged); +} + +void OutputManager::setBackend(WBackend *backend) +{ + Q_ASSERT(!m_backend); + m_backend = backend; + connect(m_backend, &WBackend::outputAdded, this, &OutputManager::outputAdded); + connect(m_backend, &WBackend::outputRemoved, this, &OutputManager::outputRemoved); +} + +void OutputManager::selectSession(Session *session) +{ + ++m_sessionGeneration; + for (auto *output : std::as_const(m_outputs)) { + auto *viewport = ownOutputViewport(output->output()); + auto *window = viewport ? viewport->outputRenderWindow() : nullptr; + if (auto *helper = window ? window->getOutputHelper(viewport) : nullptr) + helper->setExtraState({}); + } + if (m_pendingOutputConfig.config && m_pendingOutputConfig.protocol) { + m_pendingOutputConfig.protocol->sendResult(m_pendingOutputConfig.config, false); + } + m_pendingOutputConfig = {}; + m_session = session; +} + +void OutputManager::setScale(WOutput *target, qreal scale) +{ + auto *output = outputFor(target); + if (!output || !std::isfinite(scale) || scale <= 0 + || !configurationReady(output->config())) + return; + auto extra = output->extraState(); + if (!extra) + extra = WOutputHelper::ExtraState(); + wlr_output_state_set_scale(extra.get(), scale); + if (!output->setExtraState(extra)) + return; + output->applyPendingGeometry(); + output->config()->setScale(scale); + Q_EMIT configurationChanged(); +} + +void OutputManager::setOutputGroupInterface(OutputGroupManagerInterfaceV1 *interface) +{ + Q_ASSERT(!m_outputGroupManager); + m_outputGroupManager = interface; + if (m_outputGroupManager) { + m_outputGroupManager->setHost(this); + } +} + +void OutputManager::setGammaControlManager(wlr_gamma_control_manager_v1 *manager) +{ + m_gammaControlListenerOwner.teardown(); + m_gammaControlListenerOwner.listeners()->add( + &manager->events.set_gamma, this, &OutputManager::setGamma); + m_gammaControlListenerOwner.listeners()->add( + &manager->events.destroy, this, [this](void *) { + m_gammaControlListenerOwner.removeListeners(&m_gammaControlListenerOwner); + }); +} + +void OutputManager::setOutputPowerManager(wlr_output_power_manager_v1 *manager) +{ + m_outputPowerListenerOwner.teardown(); + m_outputPowerListenerOwner.listeners()->add( + &manager->events.set_mode, this, &OutputManager::setPowerMode); + m_outputPowerListenerOwner.listeners()->add( + &manager->events.destroy, this, [this](void *) { + m_outputPowerListenerOwner.removeListeners(&m_outputPowerListenerOwner); + }); +} + +void OutputManager::setXdgOutputManagers(WXdgOutputManager *manager, + WXdgOutputManager *xwaylandManager, + SessionManager *sessionManager) +{ + Q_ASSERT(!m_xwaylandOutputManager); + +#ifndef DISABLE_XWAYLAND + m_xwaylandOutputManager = xwaylandManager; + m_xwaylandOutputManager->setScaleOverride(1.0); + + const auto isXWaylandClient = [sessionManager = QPointer(sessionManager)](WClient *client) { + if (!sessionManager) + return false; + + for (const auto &session : std::as_const(sessionManager->sessions())) { + if (session && session->xwayland() + && session->xwayland()->waylandClient() == client) { + return true; + } + } + return false; + }; + manager->setFilter([isXWaylandClient](WClient *client) { + return !isXWaylandClient(client); + }); + m_xwaylandOutputManager->setFilter(isXWaylandClient); + + // XWayland perceives screen geometry in physical-pixel space scaled by + // maxDPR so root-window and xrandr geometry match client coordinates. + auto updateXWaylandOutputScale = [this] { + m_xwaylandOutputManager->setScaleOverride( + m_renderWindow->effectiveDevicePixelRatio()); + }; + connect(m_renderWindow, + &WOutputRenderWindow::effectiveDevicePixelRatioChanged, + this, + updateXWaylandOutputScale); + updateXWaylandOutputScale(); +#else + Q_UNUSED(manager); + Q_UNUSED(xwaylandManager); + Q_UNUSED(sessionManager); +#endif +} + +WXdgOutputManager *OutputManager::xwaylandOutputManager() const +{ + return m_xwaylandOutputManager; +} + +void OutputManager::processOutputAdded(WOutput *output) +{ + auto *outputConfig = DConfigManager::instance()->outputConfig(Output::getOutputId(output->handle())); + if (outputConfig && outputConfig->uuid().isEmpty()) { + outputConfig->setUuid(QUuid::createUuid().toString(QUuid::WithoutBraces)); + } + allowNonDrmOutputAutoChangeMode(output); + Output *o = nullptr; + const bool isInitialOutput = !m_initialOutputScanFinished; + qCInfo(lcTlOutput) << "Output added" << output->name() + << "id:" << Output::getOutputId(output->handle()) + << "scan complete:" << m_initialOutputScanFinished + << "mode:" << static_cast(m_mode); + + // Every output enters as a normal output; the group reconciler turns it + // into a mirror when a group claims it. The initial scan collects the + // normal outputs first and copy mode is applied once backend start has + // reported all outputs and the persisted groups are known. + o = createNormalOutput(output); + m_outputs.append(o); + const bool outputRegistered = ensureInRootContainer(o); + if (!outputRegistered) { + qCWarning(lcTlOutput) << "Failed to register output in root container" << output->name(); + } + if (m_initialOutputScanFinished && outputRegistered && !output->isEnabled()) { + o->enable(); + } + if (m_initialOutputScanFinished) { + onScreenAdded(o, workspaceSurfaces()); + notifyOutputGroupsChanged(); + } + // The output-management protocol must advertise an output as soon as it + // enters the compositor. DConfig restoration is asynchronous and may be + // unavailable in minimal sessions; delaying registration until it + // completes leaves newly bound clients with an empty head list forever. + + const bool shouldDisableOutput = !m_initialOutputScanFinished; + if (shouldDisableOutput) { + WOutputStateGuard disabledState; + wlr_output_state_set_enabled(disabledState.get(), false); + if (!wlr_output_commit_state(output->handle(), disabledState.get())) { + qCCritical(lcTlCore) << "commit failed while disabling added output" << output->name(); + } else if (!m_initialOutputScanFinished) { + qCInfo(lcTlOutput) << "Temporarily disabled output during initial scan" << output->name(); + } + } + + if (outputConfig->isInitializeSucceeded()) { + restoreOutputConfig(output, o, isInitialOutput); + } else { + publishOutput(o); + } + // Publish physical changes through each Session's independent protocol. + connect(output, &WOutput::modeChanged, this, &OutputManager::configurationChanged); + connect(output, &WOutput::scaleChanged, this, &OutputManager::configurationChanged); + connect(output, &WOutput::orientationChanged, this, &OutputManager::configurationChanged); + connect(output, &WOutput::enabledChanged, this, &OutputManager::configurationChanged); + connect(output, &WOutput::positionChanged, this, &OutputManager::configurationChanged); + connect(output, &WOutput::adaptiveSyncEnabledChanged, this, &OutputManager::configurationChanged); + Q_EMIT outputsChanged(); +} + +void OutputManager::outputAdded(WOutput *output) +{ + auto *configManager = DConfigManager::instance(); + + auto *config = configManager->outputConfig(Output::getOutputId(output->handle())); + if (outputConfigInitializationFinished(config)) { + processOutputAdded(output); + finishInitialOutputScanIfReady(); + return; + } + + if (m_pendingOutputs.contains(output)) { + return; + } + + m_pendingOutputs.insert(output, config); + connect(output, &QObject::destroyed, this, [this, output] { + if (m_pendingOutputs.remove(output)) { + finishInitialOutputScanIfReady(); + } + }); + + connect(config, + &OutputConfig::configInitializeSucceed, + this, + &OutputManager::continueOutputAdded, + Qt::SingleShotConnection); + connect(config, + &OutputConfig::configInitializeFailed, + this, + &OutputManager::continueOutputAdded, + Qt::SingleShotConnection); +} + +void OutputManager::continueOutputAdded() +{ + auto *config = qobject_cast(sender()); + if (!config) { + return; + } + + const auto outputs = m_pendingOutputs.keys(config); + for (auto *output : outputs) { + if (m_pendingOutputs.remove(output)) { + processOutputAdded(output); + } + } + finishInitialOutputScanIfReady(); +} + +void OutputManager::finishInitialOutputScanIfReady() +{ + if (m_initialOutputScanFinished || !m_backendStartFinished || !m_pendingOutputs.isEmpty() + || !configurationReady(m_config)) { + return; + } + + m_initialOutputScanFinished = true; + restoreExtensionModeFromConfig(); + if (!m_config->singleOutputId().isEmpty()) + restoreInitialOutputConfiguration(); + Q_EMIT configurationChanged(); +} + +void OutputManager::backendStarted() +{ + m_backendStartFinished = true; + finishInitialOutputScanIfReady(); +} + +void OutputManager::wakePoweredOffOutputs() +{ + for (auto *output : std::as_const(m_outputs)) { + auto *wlrOutput = output->output()->handle(); + if (wlrOutput->enabled || !wlrOutput->current_mode + || !m_powerOffOutputs.contains(wlrOutput)) { + continue; + } + + WOutputStateGuard state; + wlr_output_state_set_enabled(state.get(), true); + if (!wlr_output_commit_state(wlrOutput, state.get())) { + qCWarning(lcTlCore) << "Failed to wake output" << wlrOutput->name; + continue; + } + m_powerOffOutputs.remove(wlrOutput); + } +} + +void OutputManager::outputRemoved(WOutput *output) +{ + if (m_pendingOutputs.remove(output)) { + finishInitialOutputScanIfReady(); + return; + } + + output->removeListeners(&m_outputStateListenerOwner); + auto index = indexOf(output); + Q_ASSERT(index >= 0); + const auto o = m_outputs.takeAt(index); + + const auto &surfaces = workspaceSurfaces(o); + // Capture before removeFromRootContainer(): removing the output moves the + // primary away from it, and onScreenRemoved() must still know whether the + // output it is told about was the primary one. + const bool removedWasPrimary = m_rootContainer->primaryOutput() == o; + removeFromRootContainer(o); + const bool removedConfiguredSingleOutput = onScreenRemoved(o, surfaces, removedWasPrimary); + // When the seat becomes inactive (e.g. VT switch), wlroots tears down every + // DRM output synchronously. The restore below re-enables the remaining + // outputs, but no DRM commit can succeed while the session is inactive, so + // they stay disabled and off the layout, and layout->move() would assert. + // Leave them alone here; wlroots rescans and re-adds the connectors when + // the session becomes active again. + const bool backendSessionInactive = + m_backend && m_backend->session() && !m_backend->isSessionActive(); + if (removedConfiguredSingleOutput && !backendSessionInactive) { + // Keep the unavailable output as the configured single-output target. + // The remaining outputs are enabled only as a temporary fallback. + restoreExtensionModeFromConfig(); + } + // Losing a member output never dissolves its group: the effective state + // drops the output, and the configured state is kept so copy mode resumes + // when the output comes back. + notifyOutputGroupsChanged(); + + WaylandServer::instance()->wallpaperManager()->removeOutputWallpaper(output->handle()); + + m_powerOffOutputs.remove(output->handle()); + + delete o; + Q_EMIT outputsChanged(); +} + +OutputManager::Mode OutputManager::mode() const +{ + return m_mode; +} + +const QList &OutputManager::outputs() const +{ + return m_outputs; +} + +Output *OutputManager::createNormalOutput(WAYLIB_SERVER_NAMESPACE::WOutput *output) +{ + Output *result = Output::create(output, ::qmlEngine(m_renderWindow), parent()); + auto *platform = WaylandServer::instance()->graphicsPlatform(); + if (platform && platform->isNvidia()) { + result->outputItem()->setProperty("forceSoftwareCursor", true); + } + result->outputItem()->stackBefore(m_rootContainer); + removeFromRootContainer(output); + m_rootContainer->addOutput(result); + return result; +} + +Output *OutputManager::createCopyOutput(WAYLIB_SERVER_NAMESPACE::WOutput *output, + Output *proxy) +{ + return Output::createCopy(output, proxy, ::qmlEngine(m_renderWindow), parent()); +} + +bool OutputManager::ensureInRootContainer(Output *output) +{ + if (!output || !output->output()) { + return false; + } + + auto *layout = m_rootContainer->outputLayout(); + if (!layout) { + return false; + } + + const bool inRoot = m_rootContainer->outputs().contains(output); + const bool inLayout = layout->outputs().contains(output->output()); + if (inRoot && inLayout) { + return true; + } + + qCInfo(lcTlOutput) << "Re-registering output before applying output configuration" + << output->output()->name() + << "in root:" << inRoot + << "in layout:" << inLayout; + + if (!inRoot && inLayout) { + removeFromRootContainer(output->output()); + } + + if (!inRoot) { + m_rootContainer->addOutput(output); + } else if (!inLayout) { + layout->autoAdd(output->output()); + } + + return m_rootContainer->outputs().contains(output) + && layout->outputs().contains(output->output()); +} + +void OutputManager::removeFromRootContainer(Output *output) +{ + if (!output || !output->output()) { + return; + } + + auto *layout = m_rootContainer->outputLayout(); + const bool inRoot = m_rootContainer->outputs().contains(output); + const bool inLayout = layout && layout->outputs().contains(output->output()); + if (!inRoot && !inLayout) { + return; + } + + if (!inRoot || !inLayout) { + qCWarning(lcTlCore) << "Output root/layout registration is inconsistent before removal" + << output->output()->name() + << "in root:" << inRoot + << "in layout:" << inLayout; + if (inRoot && !inLayout) { + m_rootContainer->outputModel()->removeObject(output); + // Same ordering rule as RootSurfaceContainer::removeOutput(): the + // primary must move away before the per-output containers go away, + // otherwise layer surfaces without an output look up the container + // of the output being removed. + m_rootContainer->movePrimaryOutputAwayFrom(output); + m_rootContainer->SurfaceContainer::removeOutput(output); + } else if (!inRoot && inLayout) { + layout->remove(output->output()); + } + return; + } + + m_rootContainer->removeOutput(output); +} + +void OutputManager::removeFromRootContainer(WAYLIB_SERVER_NAMESPACE::WOutput *output) +{ + if (!output) { + return; + } + + for (auto *rootOutput : std::as_const(m_rootContainer->outputs())) { + if (rootOutput && rootOutput->output() == output) { + removeFromRootContainer(rootOutput); + return; + } + } + + auto *layout = m_rootContainer->outputLayout(); + if (layout && layout->outputs().contains(output)) { + qCWarning(lcTlCore) << "Removing stale output layout entry before re-registering" + << output->name(); + layout->remove(output); + } +} + +WAYLIB_SERVER_NAMESPACE::WOutputViewport *OutputManager::ownOutputViewport( + WAYLIB_SERVER_NAMESPACE::WOutput *output) const +{ + Output *outputObject = outputFor(output); + if (!outputObject || !outputObject->outputItem()) { + qCWarning(lcTlCore) << "Invalid output object for" << output->name(); + return nullptr; + } + + auto *viewport = outputObject->outputItem()->findChild< + WAYLIB_SERVER_NAMESPACE::WOutputViewport *>({}, Qt::FindDirectChildrenOnly); + if (!viewport) { + qCWarning(lcTlCore) << "No viewport found for output" << output->name() + << "- OutputItem may not have been fully initialized"; + } + return viewport; +} + +bool OutputManager::testOutputState(const WAYLIB_SERVER_NAMESPACE::WOutputState &state) const +{ + WOutputViewport *viewport = ownOutputViewport(state.output); + if (!viewport) { + return false; + } + + WOutputRenderWindow *renderWindow = viewport->outputRenderWindow(); + if (!renderWindow) { + return false; + } + WOutputStateGuard newState; + wlr_output_state_set_enabled(newState.get(), state.enabled); + if (state.enabled) { + if (state.mode) { + wlr_output_state_set_mode(newState.get(), state.mode); + } else { + wlr_output_state_set_custom_mode( + newState.get(), + state.customModeSize.width(), + state.customModeSize.height(), + state.customModeRefresh); + } + wlr_output_state_set_adaptive_sync_enabled( + newState.get(), state.adaptiveSyncEnabled); + wlr_output_state_set_transform( + newState.get(), static_cast(state.transform)); + wlr_output_state_set_scale(newState.get(), state.scale); + } + return wlr_output_test_state(state.output->handle(), newState.get()); +} + +QList OutputManager::workspaceSurfaces(Output *filterOutput) const +{ + QList surfaces; + auto *workspace = WaylandServer::instance()->workspace(); + WAYLIB_SERVER_NAMESPACE::WOutputRenderWindow::paintOrderItemList( + workspace, + [&surfaces, filterOutput, workspace](QQuickItem *item) -> bool { + auto *surfaceWrapper = qobject_cast(item); + if (surfaceWrapper + && surfaceWrapper->showOnWorkspace(workspace->current()->id()) + && (!filterOutput || surfaceWrapper->ownsOutput() == filterOutput)) { + surfaces.append(surfaceWrapper); + return true; + } + return false; + }); + return surfaces; +} + +void OutputManager::moveSurfaces(const QList &surfaces, + Output *targetOutput, + Output *sourceOutput) +{ + m_rootContainer->moveSurfacesToOutput(surfaces, targetOutput, sourceOutput); +} + +void OutputManager::saveCurrentConfig(Output *output) +{ + if (!output) { + return; + } + + auto *outputConfig = output->config(); + if (!outputConfig || !outputConfig->isInitializeSucceeded()) { + return; + } + if (!output->output() || !output->output()->handle()->current_mode) { + return; + } + + auto *wlrOutput = output->output()->handle(); + auto *currentMode = wlrOutput->current_mode; + outputConfig->setWidth(currentMode->width); + outputConfig->setHeight(currentMode->height); + outputConfig->setRefresh(currentMode->refresh); + outputConfig->setTransform(wlrOutput->transform); + outputConfig->setScale(wlrOutput->scale); + outputConfig->setAdaptiveSyncEnabled( + wlrOutput->adaptive_sync_status == WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED); + + if (auto *layout = output->output()->layout()) { + if (auto *layoutOutput = wlr_output_layout_get(layout->handle(), wlrOutput)) { + outputConfig->setX(layoutOutput->x); + outputConfig->setY(layoutOutput->y); + } + } +} + +void OutputManager::publishOutput(Output *outputObject) +{ + if (!outputObject) { + return; + } + + if (auto *wallpaper = WaylandServer::instance()->wallpaperManager()) + wallpaper->ensureWallpaperConfigForOutput(outputObject); +} + +void OutputManager::restoreOutputConfig(WAYLIB_SERVER_NAMESPACE::WOutput *output, + Output *outputObject, + bool isInitialOutput) +{ + QPointer guardedOutput(outputObject); + auto publish = qScopeGuard([this, guardedOutput] { + publishOutput(guardedOutput); + }); + if (!outputObject || m_mode == Mode::Copy) { + return; + } + + // Only the initial backend scan restores saved geometry. A hot-plugged + // output keeps outputLayout's auto-added position, while its mode, + // transform, scale, brightness, and color temperature are restored. + if (!isInitialOutput) { + const bool restoreAsExtensionOutput = + m_mode == Mode::Extension + && m_config->singleOutputId().isEmpty(); + if (restoreAsExtensionOutput && !output->isEnabled()) { + outputObject->enable(); + } + } + + const QString singleOutputId = m_config->singleOutputId(); + if (!singleOutputId.isEmpty() + && outputObject->getOutputId() != singleOutputId) { + if (output->isEnabled()) { + WOutputStateGuard disabledState; + wlr_output_state_set_enabled(disabledState.get(), false); + if (!wlr_output_commit_state(output->handle(), disabledState.get())) { + qCCritical(lcTlOutput) + << "Failed to disable non-selected output while restoring single-output display" + << output->name(); + return; + } + } + if (auto *layout = m_rootContainer->outputLayout(); + layout && layout->outputs().contains(output)) { + layout->remove(output); + } + qCInfo(lcTlOutput) << "Disabled non-selected output while restoring single-output display" + << output->name() + << "selected output id:" << singleOutputId; + return; + } + + auto restoreColorConfig = qScopeGuard([guardedOutput] { + if (guardedOutput && guardedOutput->output() && guardedOutput->output()->isEnabled()) { + guardedOutput->applyOutputColorConfig(); + } + }); + + auto *config = outputObject->config(); + const QString outputId = outputObject->getOutputId(); + const QString primaryOutputId = m_config->primaryOutputId(); + if (primaryOutputId == outputId) { + m_rootContainer->setPrimaryOutput(outputObject); + } else if (m_rootContainer->primaryOutput() + && m_rootContainer->primaryOutput()->output() + && !m_rootContainer->primaryOutput()->output()->isEnabled() + && !currentPrimaryMatchesId(m_rootContainer, primaryOutputId)) { + m_rootContainer->setPrimaryOutput(outputObject); + } + + if (!hasSavedOutputState(config)) { + if (!output->isEnabled()) { + outputObject->enable(); + } + return; + } + + const int width = static_cast(config->width()); + const int height = static_cast(config->height()); + int refresh = static_cast(config->refresh()); + // A scale-only protocol change may have persisted a custom mode without a + // refresh; reuse the rate the output is actually running at. + if (refresh <= 0) { + auto *wlrOutput = output->handle(); + if (wlrOutput->current_mode) { + refresh = wlrOutput->current_mode->refresh; + } else if (auto *mode = closestOutputMode(output, width, height, 0)) { + refresh = mode->refresh; + } else if (wlrOutput->refresh > 0) { + refresh = wlrOutput->refresh; + } + } + const double scale = config->scale(); + const qlonglong transform = config->transform(); + if (width <= 0 || height <= 0 || refresh <= 0 || scale <= 0.0) { + qCWarning(lcTlCore) << "Ignoring invalid output dconfig for" << output->name() + << "width:" << width + << "height:" << height + << "refresh:" << refresh + << "scale:" << scale; + return; + } + if (transform < WL_OUTPUT_TRANSFORM_NORMAL || transform > WL_OUTPUT_TRANSFORM_FLIPPED_270) { + qCWarning(lcTlCore) << "Ignoring invalid output dconfig for" << output->name() + << "transform:" << transform; + return; + } + + if (auto *layout = m_rootContainer->outputLayout()) { + layout->move(output, QPoint(static_cast(config->x()), static_cast(config->y()))); + } + + if (!stageOutputConfig(outputObject, + width, + height, + refresh, + transform, + scale, + config->adaptiveSyncEnabled())) { + qCCritical(lcTlCore) << "commit failed on output" << output->name(); + return; + } + + // Store what was staged. Reading the values back from the output here + // would still see the previous commit, because the helper commits on the + // next frame, and would overwrite the user's settings with stale ones. + config->setWidth(width); + config->setHeight(height); + config->setRefresh(refresh); + config->setTransform(static_cast(transform)); + config->setScale(scale); +} + +int OutputManager::indexOf(WAYLIB_SERVER_NAMESPACE::WOutput *output) const +{ + for (int i = 0; i < m_outputs.size(); ++i) { + if (m_outputs.at(i)->output() == output) { + return i; + } + } + return -1; +} + +Output *OutputManager::outputFor(WAYLIB_SERVER_NAMESPACE::WOutput *output) const +{ + for (auto *candidate : std::as_const(m_outputs)) { + if (candidate->output() == output) { + return candidate; + } + } + return nullptr; +} + +Output *OutputManager::findOutputByName(const QString &name) const +{ + for (auto *output : std::as_const(m_outputs)) { + if (output && output->output() && output->output()->name() == name) { + return output; + } + } + return nullptr; +} + +Output *OutputManager::findOutputById(const QString &id) const +{ + for (auto *output : std::as_const(m_outputs)) { + if (output && output->output() && output->getOutputId() == id) { + return output; + } + } + return nullptr; +} + +void OutputManager::requestAdditionalOutputs() +{ + if (wlr_backend_is_multi(m_backend->handle())) { + wlr_multi_for_each_backend( + m_backend->handle(), + [](wlr_backend *backend, void *) { + if (wlr_backend_is_x11(backend)) { + wlr_x11_output_create(backend); + } else if (wlr_backend_is_wl(backend)) { + wlr_wl_output_create(backend); + } + }, + nullptr); + } +} + +void OutputManager::applyMode(Mode mode) +{ + if (!m_outputGroupManager) { + return; + } + + // The menu bar toggle keeps working, but copy mode is driven by the output + // group protocol: it creates one group with the primary output as source + // and every other output as a mirror. Only the group this entry point + // created is dissolved again, so groups configured by other clients (the + // display settings panel) are left alone. + // Read the uuid before dissolving: dissolving may replace output objects. + const QString primaryUuid = m_rootContainer->primaryOutput() + ? m_rootContainer->primaryOutput()->uuid() + : QString(); + + if (!m_menuBarGroupName.isEmpty()) { + m_outputGroupManager->dissolveGroup(m_menuBarGroupName); + m_menuBarGroupName.clear(); + } + + if (mode != Mode::Copy || primaryUuid.isEmpty()) { + return; + } + + QStringList mirrorUuids; + for (auto *output : std::as_const(m_outputs)) { + if (output && output->uuid() != primaryUuid && !output->uuid().isEmpty()) { + mirrorUuids.append(output->uuid()); + } + } + m_menuBarGroupName = m_outputGroupManager->createGroup(primaryUuid, mirrorUuids); +} + +void OutputManager::allowNonDrmOutputAutoChangeMode( + WAYLIB_SERVER_NAMESPACE::WOutput *output) +{ + output->listeners(&m_outputStateListenerOwner)->add( + &output->handle()->events.request_state, + this, + [output](wlr_output_event_request_state *newState) { + if (newState->state->committed & WLR_OUTPUT_STATE_MODE) { + if (!wlr_output_commit_state(output->handle(), newState->state)) { + qCCritical(lcTlCore, "commit failed on output %s", output->handle()->name); + } + } + }); +} + +Output *OutputManager::outputAtCursor() const +{ + const QPoint cursorPosition = QCursor::pos(); + for (auto *output : std::as_const(m_outputs)) { + const QRectF geometry(output->outputItem()->position(), output->outputItem()->size()); + if (geometry.contains(cursorPosition)) { + return output; + } + } + return m_rootContainer->primaryOutput(); +} + +void OutputManager::enableAllOutputs() +{ + for (auto *output : std::as_const(m_outputs)) { + if (!output || !output->output()) { + continue; + } + + WOutputStateGuard state; + wlr_output_state_set_enabled(state.get(), true); + const bool ok = wlr_output_commit_state(output->output()->handle(), state.get()); + if (!ok) { + qCWarning(lcTlOutput) << "Failed to enable output" << output->output()->name(); + continue; + } + + if (auto *layout = m_rootContainer->outputLayout(); + layout && !layout->outputs().contains(output->output())) { + layout->autoAdd(output->output()); + } + } +} + +bool OutputManager::isOutputAvailable(const QString &uuid) const +{ + Output *output = findOutputByUuid(uuid); + return output && output->output() && output->output()->isEnabled(); +} + +QList OutputManager::outputGroupMembers() const +{ + QList members; + for (auto *output : std::as_const(m_outputs)) { + if (!output || !output->output()) { + continue; + } + // The membership record is only readable once the output's + // configuration has been loaded. + auto *config = output->config(); + if (!config || !config->isInitializeSucceeded()) { + continue; + } + const QString uuid = config->uuid(); + if (uuid.isEmpty()) { + // The uuid is assigned from the loaded configuration, so an empty + // one means the record is not usable yet. + continue; + } + // The overlay carries the last write for this output; the DConfig + // cache can still hold an older value until the worker echoes it + // back (which may land out of order). + if (auto it = m_groupMembership.constFind(uuid); it != m_groupMembership.cend()) { + members.append(it.value()); + } else { + members.append({ uuid, config->groupName(), config->joinTime(), config->lastSetSourceTime() }); + } + } + return members; +} + +void OutputManager::writeOutputGroupMembership(const QString &uuid, + const QString &groupName, + qlonglong joinTime, + qlonglong lastSetSourceTime) +{ + Output *output = findOutputByUuid(uuid); + if (!output || !output->output()) { + qCWarning(lcTlOutput) << "Cannot persist output group membership of unknown output" << uuid + << "group:" << groupName; + return; + } + auto *config = output->config(); + if (!config || !config->isInitializeSucceeded()) { + qCWarning(lcTlOutput) << "Cannot persist output group membership before the output" + << "configuration is loaded, uuid:" << uuid + << "group:" << groupName; + return; + } + config->setGroupName(groupName); + config->setJoinTime(joinTime); + config->setLastSetSourceTime(lastSetSourceTime); + m_groupMembership.insert(uuid, { uuid, groupName, joinTime, lastSetSourceTime }); +} + +Output *OutputManager::findOutputByUuid(const QString &uuid) const +{ + if (uuid.isEmpty()) { + return nullptr; + } + + for (auto *output : std::as_const(m_outputs)) { + if (output && output->output() && output->uuid() == uuid) { + return output; + } + } + return nullptr; +} + +void OutputManager::notifyOutputGroupsChanged() +{ + if (!m_outputGroupManager) { + return; + } + + // Availability changes are reported by the protocol owner, which then asks + // us to apply the resulting effective group state. + QMetaObject::invokeMethod( + this, + [this] { + if (m_outputGroupManager) { + m_outputGroupManager->notifyOutputAvailabilityChanged(); + } + }, + Qt::QueuedConnection); +} + +void OutputManager::deactivateGroupMirrors() +{ + for (int i = 0; i < m_outputs.size(); ++i) + convertMirrorToNormal(i); +} + +// Turns the mirror at INDEX back into a normal output. The replacement is +// created synchronously (not deleteLater) on purpose: the mirror and its +// replacement share one WOutputViewport, and the mirror's hardware layers stay +// attached to it until the old object is gone, which makes waylib assert when +// the new item re-attaches them. Disable first, so the layers are detached +// while the mirror still owns the viewport. +Output *OutputManager::convertMirrorToNormal(int index) +{ + if (index < 0 || index >= m_outputs.size()) { + return nullptr; + } + + Output *output = m_outputs.at(index); + if (!output || !output->output() || output->isSource()) { + return output; + } + + auto *woutput = output->output(); + const bool wasEnabled = woutput->isEnabled(); + if (wasEnabled) { + WOutputStateGuard disabledState; + wlr_output_state_set_enabled(disabledState.get(), false); + if (!wlr_output_commit_state(woutput->handle(), disabledState.get())) { + qCWarning(lcTlOutput) << "Failed to disable output before leaving copy mode" + << woutput->name(); + } + } + + // Leaving the container drops the layout entry and creating the normal + // output puts it back at an automatic position. Restore the configured one + // before the state is saved, otherwise copy mode would rewrite the + // arrangement the user made for that output. + auto *config = output->config(); + const bool hasSavedPosition = config && config->isInitializeSucceeded() + && (!config->xIsDefaultValue() || !config->yIsDefaultValue()); + const QPoint savedPosition(static_cast(hasSavedPosition ? config->x() : 0), + static_cast(hasSavedPosition ? config->y() : 0)); + + removeFromRootContainer(output); + m_outputs.removeAt(index); + delete output; + + Output *replacement = createNormalOutput(woutput); + // Keep the enabled state the output had: an output switched off by DPMS or + // by single-output display must not be woken up again by leaving copy mode. + if (wasEnabled) { + replacement->enable(); + } + if (hasSavedPosition) { + if (auto *layout = m_rootContainer->outputLayout(); + layout && layout->outputs().contains(woutput)) { + layout->move(woutput, savedPosition); + } + } + saveCurrentConfig(replacement); + m_outputs.insert(index, replacement); + return replacement; +} + +// Reconciles the Output objects with the effective state of every output +// group: a group source is a normal output, its effective mirrors are copy +// outputs of that source. Outputs no group claims stay normal extension +// outputs. +// +// Known deviation from the XML: mirror outputs still expose a wl_output while +// copy mode is engaged. The protocol describes the source as the only output +// exposing a wl_output; that behaviour is tracked separately and is not part of +// this change. +void OutputManager::applyOutputGroups() +{ + if (!m_outputGroupManager) { + return; + } + if (m_applyingOutputGroups) { + // A request that arrives while a reconcile is running must not be + // dropped: it may be based on an effective state this pass did not see. + m_groupsDirty = true; + return; + } + if (m_pendingOutputConfig.config || m_inFlightOutputCommits > 0) { + // An output configuration is being applied: its commit jobs hold the + // viewports of the outputs that were just converted back to normal. + // Rebuilding them now would destroy those helpers and lose the jobs, + // so re-apply once the last job finished. + m_groupsDirty = true; + return; + } + m_applyingOutputGroups = true; + const QScopeGuard resetGuard([this] { m_applyingOutputGroups = false; }); + + const auto groups = m_outputGroupManager->effectiveGroups(); + QHash desiredMirrors; // mirror uuid -> source uuid + QStringList desiredSources; + for (const auto &group : std::as_const(groups)) { + if (group.sourceUuid.isEmpty()) { + continue; + } + desiredSources.append(group.sourceUuid); + for (const auto &mirrorUuid : std::as_const(group.mirrorUuids)) { + desiredMirrors.insert(mirrorUuid, group.sourceUuid); + } + } + + // Group sources are always available (the protocol filtered them), make + // sure they are enabled and present in the layout. + for (const auto &uuid : std::as_const(desiredSources)) { + Output *source = findOutputByUuid(uuid); + if (!source || !source->output()) { + continue; + } + if (!source->output()->isEnabled()) { + source->enable(); + } + if (auto *layout = m_rootContainer->outputLayout(); + source->output()->isEnabled() + && layout + && !layout->outputs().contains(source->output())) { + layout->autoAdd(source->output()); + } + } + + // First turn every output that should not be a mirror into a normal output, + // so that a mirror can never keep a proxy that is about to be recreated. + for (int i = 0; i < m_outputs.size(); ++i) { + Output *output = m_outputs.at(i); + if (!output || !output->output()) { + continue; + } + + const auto mirrorIt = desiredMirrors.constFind(output->uuid()); + if (!output->isSource()) { + Output *desiredSource = mirrorIt == desiredMirrors.cend() + ? nullptr + : findOutputByUuid(mirrorIt.value()); + if (desiredSource && output->proxyOutput() == desiredSource) { + continue; + } + + convertMirrorToNormal(i); + } + } + + // Then create a copy output for every effective mirror. Mirrors that pass A + // already kept are not touched again. + for (int i = 0; i < m_outputs.size(); ++i) { + Output *output = m_outputs.at(i); + if (!output || !output->output() || !output->isSource()) { + continue; + } + + const auto mirrorIt = desiredMirrors.constFind(output->uuid()); + if (mirrorIt == desiredMirrors.cend()) { + continue; + } + + Output *source = findOutputByUuid(mirrorIt.value()); + if (!source) { + continue; + } + + removeFromRootContainer(output); + Output *replacement = createCopyOutput(output->output(), source); + m_outputs.replace(i, replacement); + // The mirror's viewport may already have re-registered the output in + // the layout while the QML item was created. + if (!ensureInRootContainer(replacement)) { + qCWarning(lcTlOutput) << "Failed to register mirror output" << output->uuid(); + } + replacement->enable(); + output->deleteLater(); + } + + // A mirror can never be the primary output. The pointer is guarded because + // the loops above replace output objects and the container may still hold + // the one it removed. + QPointer primary = m_rootContainer->primaryOutput(); + if (!primary || !m_outputs.contains(primary) || !primary->isSource()) { + const auto surfaces = primary ? workspaceSurfaces(primary) : QList(); + Output *fallback = findOutputByUuid(desiredSources.value(0)); + if (!fallback) { + for (auto *candidate : std::as_const(m_outputs)) { + if (candidate && candidate->isSource()) { + fallback = candidate; + break; + } + } + } + if (fallback) { + m_rootContainer->setPrimaryOutput(fallback); + if (!surfaces.isEmpty()) { + moveSurfaces(surfaces, fallback, primary); + } + } + } + + bool copyActive = false; + for (const auto &group : std::as_const(groups)) { + if (!group.sourceUuid.isEmpty() && !group.mirrorUuids.isEmpty()) { + copyActive = true; + break; + } + } + + const Mode newMode = copyActive ? Mode::Copy : Mode::Extension; + if (m_mode != newMode) { + m_mode = newMode; + Q_EMIT modeChanged(); + } + + // A reconcile requested while this pass was running is re-run now instead + // of being lost. The notification is queued, so the pass flag is already + // cleared when it arrives. + if (m_groupsDirty) { + m_groupsDirty = false; + notifyOutputGroupsChanged(); + } +} + +void OutputManager::restoreExtensionModeFromConfig() +{ + if (m_outputs.isEmpty()) { + return; + } + + // Restore the available outputs without changing the saved single-output selection. + // The connected outputs may only represent a temporary topology. + m_mode = Mode::Extension; + Q_EMIT modeChanged(); + + for (auto *outputObject : std::as_const(m_outputs)) { + if (!outputObject || !outputObject->output()) { + continue; + } + + outputObject->enable(); + if (auto *layout = m_rootContainer->outputLayout(); + outputObject->output()->isEnabled() + && layout + && !layout->outputs().contains(outputObject->output())) { + layout->autoAdd(outputObject->output()); + } + + if (configurationReady(outputObject->config())) { + restoreExtensionOutput(outputObject); + } + } + + Output *primaryOutput = findOutputById(m_config->primaryOutputId()); + if (!primaryOutput) { + primaryOutput = m_outputs.constFirst(); + } + m_rootContainer->setPrimaryOutput(primaryOutput); + const auto surfaces = workspaceSurfaces(); + if (!surfaces.isEmpty()) { + moveSurfaces(surfaces, primaryOutput, nullptr); + } +} + +void OutputManager::restoreExtensionOutput(Output *outputObject) +{ + if (!outputObject || !outputObject->output() + || !m_outputs.contains(outputObject)) { + return; + } + + auto *output = outputObject->output(); + auto *config = outputObject->config(); + const bool saved = hasSavedOutputState(config); + const auto *preferred = wlr_output_preferred_mode(output->handle()); + const int width = saved ? static_cast(config->width()) + : (preferred ? preferred->width : output->handle()->width); + const int height = saved ? static_cast(config->height()) + : (preferred ? preferred->height : output->handle()->height); + const int refresh = saved ? static_cast(config->refresh()) + : (preferred ? preferred->refresh : output->handle()->refresh); + const double scale = config->scale(); + const qlonglong transform = config->transform(); + if (width <= 0 || height <= 0 || refresh <= 0 || scale <= 0.0 + || transform < WL_OUTPUT_TRANSFORM_NORMAL + || transform > WL_OUTPUT_TRANSFORM_FLIPPED_270) { + qCWarning(lcTlOutput) << "Ignoring invalid saved extension state for" + << output->name(); + return; + } + + if (auto *layout = m_rootContainer->outputLayout()) { + const QPoint position = saved + ? QPoint(static_cast(config->x()), static_cast(config->y())) + : (m_session ? m_session->outputManager()->defaultPosition(outputObject).toPoint() : QPoint()); + layout->move(output, position); + } + + if (!stageOutputConfig(outputObject, + width, + height, + refresh, + transform, + scale, + config->adaptiveSyncEnabled())) { + qCCritical(lcTlOutput) << "Failed to restore extension state for" + << output->name(); + return; + } + // stageOutputConfig() stages the state and resizes the item/viewport, + // including the viewport rotation, before the commit frame is rendered. +} + +void OutputManager::restoreInitialOutputConfiguration() +{ + const QString singleOutputId = m_config->singleOutputId(); + if (!singleOutputId.isEmpty() && findOutputById(singleOutputId)) { + restoreConfiguredSingleOutput(workspaceSurfaces(), true); + } else { + if (!singleOutputId.isEmpty()) { + clearSingleOutputConfig(); + } + + restoreExtensionModeFromConfig(); + restorePrimaryOutput(); + } + + // Persisted output groups come from the output group protocol; applying + // them here restores copy mode for every configured group. + notifyOutputGroupsChanged(); +} + +void OutputManager::setGamma(wlr_gamma_control_manager_v1_set_gamma_event *event) +{ + auto *output = event->output; + size_t rampSize = 0; + uint16_t *red = nullptr; + uint16_t *green = nullptr; + uint16_t *blue = nullptr; + wlr_gamma_control_v1 *gammaControl = event->control; + if (gammaControl) { + rampSize = gammaControl->ramp_size; + red = gammaControl->table; + green = gammaControl->table + gammaControl->ramp_size; + blue = gammaControl->table + 2 * gammaControl->ramp_size; + } + + WOutputStateGuard state; + wlr_color_transform *colorTransform = nullptr; + if (gammaControl) { + colorTransform = wlr_color_transform_init_lut_3x1d( + rampSize, red, green, blue); + if (!colorTransform) { + qCWarning(lcTlCore) << "Failed to create color transform for gamma LUT!"; + wlr_gamma_control_v1_send_failed_and_destroy(gammaControl); + return; + } + } + wlr_output_state_set_color_transform(state.get(), colorTransform); + wlr_color_transform_unref(colorTransform); + if (!wlr_output_commit_state(output, state.get())) { + qCCritical(lcTlCore, "commit failed on output %s", output->name); + qCWarning(lcTlCore) << "Failed to set gamma lut!"; + wlr_gamma_control_v1_send_failed_and_destroy(gammaControl); + } +} + +void OutputManager::setPowerMode(wlr_output_power_v1_set_mode_event *event) +{ + auto *output = event->output; + WOutputStateGuard state; + + switch (event->mode) { + case ZWLR_OUTPUT_POWER_V1_MODE_OFF: + if (m_powerOffOutputs.contains(output) || !output->enabled) { + return; + } + wlr_output_state_set_enabled(state.get(), false); + if (!wlr_output_commit_state(output, state.get())) { + qCCritical(lcTlCore, "commit failed on output %s", output->name); + return; + } + m_powerOffOutputs.insert(output); + break; + case ZWLR_OUTPUT_POWER_V1_MODE_ON: + if (!m_powerOffOutputs.remove(output)) { + return; + } + wlr_output_state_set_enabled(state.get(), true); + if (!wlr_output_commit_state(output, state.get())) { + qCCritical(lcTlCore, "commit failed on output %s", output->name); + m_powerOffOutputs.insert(output); + } + break; + } + + notifyOutputGroupsChanged(); +} + +void OutputManager::testOrApplyConfiguration(WOutputManagerV1 *protocol, + wlr_output_configuration_v1 *config, + bool onlyTest) +{ + QList states = protocol->stateListPending(config); + + const auto enabledOutputCount = std::count_if( + states.cbegin(), states.cend(), [](const WOutputState &state) { return state.enabled; }); + const bool allEnabledOutputsOverlap = enabledOutputCount > 1 + && std::all_of(states.cbegin(), states.cend(), [](const WOutputState &state) { + return !state.enabled || (state.x == 0 && state.y == 0); + }); + const auto currentlyEnabledOutputCount = std::count_if( + states.cbegin(), states.cend(), [](const WOutputState &state) { + return state.output->isEnabled(); + }); + const bool expandingFromSingleOutput = + currentlyEnabledOutputCount == 1 && enabledOutputCount > 1; + + if (m_mode == Mode::Extension + && (allEnabledOutputsOverlap || expandingFromSingleOutput)) { + QList restoredStates = states; + bool configsValid = true; + bool hasNonZeroPosition = false; + + for (auto &state : restoredStates) { + if (!state.enabled) { + continue; + } + + Output *output = outputFor(state.output); + OutputConfig *outputConfig = output ? output->config() : nullptr; + if (!outputConfig || !outputConfig->isInitializeSucceeded() + || !hasSavedOutputState(outputConfig)) { + configsValid = false; + break; + } + + const int width = static_cast(outputConfig->width()); + const int height = static_cast(outputConfig->height()); + const int refresh = static_cast(outputConfig->refresh()); + if (width <= 0 || height <= 0 || refresh <= 0) { + configsValid = false; + break; + } + + state.x = static_cast(outputConfig->x()); + state.y = static_cast(outputConfig->y()); + hasNonZeroPosition |= state.x != 0 || state.y != 0; + state.mode = closestOutputMode(state.output, width, height, refresh); + if (!state.mode) { + configsValid = false; + break; + } + } + + if (configsValid && hasNonZeroPosition) { + states = std::move(restoredStates); + } + } + + if (onlyTest) { + for (const auto &state : std::as_const(states)) { + if (!testOutputState(state)) { + protocol->sendTestResult(config, false); + return; + } + } + protocol->sendTestResult(config, true); + return; + } + + if (m_pendingOutputConfig.config) { + if (m_pendingOutputConfig.protocol) + m_pendingOutputConfig.protocol->sendResult(m_pendingOutputConfig.config, false); + } + + // Pre-check the whole configuration before mutating any output, so a single + // failure rejects the entire configuration instead of leaving outputs + // half-applied. + // TODO: wlr_output_test_state() is a per-head probe and cannot catch + // cross-head constraints (CRTC/bandwidth). Move to a backend-level atomic + // multi-head test+commit once waylib exposes an equivalent of + // wlr_output_swapchain_manager_prepare()/wlr_backend_commit(), mirroring + // sway's apply_resolved_output_configs(). + for (const auto &state : std::as_const(states)) { + if (!testOutputState(state)) { + qCWarning(lcTlOutput) + << "Rejecting output configuration; pre-apply test failed for output" + << state.output->name(); + protocol->sendResult(config, false); + return; + } + } + + m_pendingOutputConfig.config = config; + m_pendingOutputConfig.protocol = protocol; + m_pendingOutputConfig.owner = m_session; + m_pendingOutputConfig.states = states; + m_pendingOutputConfig.pendingCommits = 0; + m_pendingOutputConfig.allSuccess = true; + + // render(viewport, true) commits the scheduled job right away, so all jobs + // are registered first (see the render pass at the end of this function): + // a synchronous finish of the first output would otherwise answer the + // client while later heads still have no job, swallowing their failures. + QList viewportsToRender; + + if (m_initialOutputScanFinished && !m_config->singleOutputId().isEmpty()) { + const QString singleOutputId = m_config->singleOutputId(); + for (const auto &state : std::as_const(states)) { + if (state.enabled && !state.output->isEnabled()) { + Output *output = outputFor(state.output); + if (output && output->getOutputId() != singleOutputId) { + clearSingleOutputConfig(); + enableAllOutputs(); + break; + } + } + } + } + + // The output-management protocol configures the outputs itself, so copy + // mode is torn down here and restored from the groups once the commit + // finished (see onOutputCommitFinished). The reconcile also runs on every + // error path below, so the protocol state can never claim a mirror that is + // not rendered anymore. + const QScopeGuard reconcileOnExit([this] { notifyOutputGroupsChanged(); }); + + deactivateGroupMirrors(); + + for (const auto &state : std::as_const(states)) { + Output *outputObject = outputFor(state.output); + if (!outputObject) { + continue; + } + if (!state.enabled && state.output->isEnabled()) { + onScreenDisabled(outputObject, workspaceSurfaces(outputObject)); + } + } + + // Commit in two phases: enable first, then disable, so the layout never + // passes through a state where no output is enabled mid-transition. + QList orderedStates = states; + std::stable_partition(orderedStates.begin(), orderedStates.end(), + [](const WOutputState &state) { return state.enabled; }); + + for (const auto &state : std::as_const(orderedStates)) { + Output *output = outputFor(state.output); + if (!output) { + continue; + } + + WOutputViewport *viewport = ownOutputViewport(state.output); + if (!viewport) { + answerPendingConfiguration(false); + return; + } + + WOutputRenderWindow *renderWindow = viewport->outputRenderWindow(); + if (!renderWindow) { + qCWarning(lcTlCore) << "No renderWindow for output" << state.output->name(); + answerPendingConfiguration(false); + return; + } + + if (state.enabled) { + auto *layout = m_rootContainer->outputLayout(); + if (!layout || !m_rootContainer->outputs().contains(output)) { + qCWarning(lcTlCore) + << "Cannot apply enabled output configuration; output is not in root container" + << state.output->name(); + answerPendingConfiguration(false); + return; + } + } + + auto outputHelper = renderWindow->getOutputHelper(viewport); + if (!outputHelper) { + qCWarning(lcTlCore) << "No output helper for viewport" << viewport; + answerPendingConfiguration(false); + return; + } + + WOutputHelper::ExtraState extraState; + wlr_output_state_set_enabled(extraState.get(), state.enabled); + if (state.enabled) { + if (state.mode) { + wlr_output_state_set_mode(extraState.get(), state.mode); + } else { + wlr_output_state_set_custom_mode( + extraState.get(), + state.customModeSize.width(), + state.customModeSize.height(), + state.customModeRefresh); + } + wlr_output_state_set_scale(extraState.get(), state.scale); + // The transform is committed by the rotation animation at its + // halfway point, together with the viewport rotation. + wlr_output_state_set_adaptive_sync_enabled( + extraState.get(), state.adaptiveSyncEnabled); + } + + if (!outputHelper->setExtraState(extraState)) { + qCWarning(lcTlCore) << "Failed to set extra state for output" + << state.output->name(); + answerPendingConfiguration(false); + return; + } + + if (state.enabled) { + // Resize the QML item/viewport now; the rotation animation stages + // the transform and rotates the viewport at its halfway point (or + // applies both at once when animations are off). + output->applyPendingGeometry(false); + output->rotationOutput(state.transform); + } else { + output->applyPendingGeometry(); + } + + auto pendingConfig = m_pendingOutputConfig.config; + const auto generation = m_sessionGeneration; + const bool enabled = state.enabled; + const QPoint outputPosition(state.x, state.y); + outputHelper->scheduleCommitJob( + [self = QPointer(this), + pendingConfig, + generation, + extraState, + renderWindow, + viewport, + output = QPointer(state.output), + outputPosition, + enabled](bool success, WOutputHelper::ExtraState committedState) { + if (self) { + self->handleOutputCommit(success, + committedState, + pendingConfig, + generation, + extraState, + renderWindow, + viewport, + output, + outputPosition, + enabled); + } + }, + WOutputHelper::AfterCommitStage); + m_pendingOutputConfig.pendingCommits++; + m_inFlightOutputCommits++; + renderWindow->update(viewport); + + if (state.enabled && !state.output->isEnabled()) { + viewportsToRender.append(viewport); + } + } + + for (auto *viewport : std::as_const(viewportsToRender)) { + if (auto *renderWindow = viewport->outputRenderWindow()) { + renderWindow->render(viewport, true); + } + } + + if (m_pendingOutputConfig.config == config && m_pendingOutputConfig.pendingCommits == 0) { + // Nothing was scheduled (empty configuration or no matching output), so + // no commit callback will ever finish this apply. + answerPendingConfiguration(true); + } +} + +void OutputManager::onOutputCommitFinished(wlr_output_configuration_v1 *config, + bool success) +{ + if (!config || config != m_pendingOutputConfig.config || m_pendingOutputConfig.owner != m_session) { + return; + } + + if (!success) { + m_pendingOutputConfig.allSuccess = false; + } + + m_pendingOutputConfig.pendingCommits--; + if (m_pendingOutputConfig.pendingCommits != 0) { + return; + } + + answerPendingConfiguration(m_pendingOutputConfig.allSuccess); +} + +void OutputManager::handleOutputCommit( + bool success, + WAYLIB_SERVER_NAMESPACE::WOutputHelper::ExtraState committedState, + wlr_output_configuration_v1 *pendingConfig, + quint64 generation, + WAYLIB_SERVER_NAMESPACE::WOutputHelper::ExtraState extraState, + WAYLIB_SERVER_NAMESPACE::WOutputRenderWindow *renderWindow, + WAYLIB_SERVER_NAMESPACE::WOutputViewport *viewport, + QPointer output, + QPoint outputPosition, + bool enabled) +{ + const bool currentRequest = m_sessionGeneration == generation + && m_pendingOutputConfig.config == pendingConfig + && m_pendingOutputConfig.owner == m_session; + // Hardware commits still finish when their requesting Session + // changes; always retire the shared output-group bookkeeping. + const bool lastInFlight = (--m_inFlightOutputCommits <= 0); + if (committedState == extraState) { + if (success && output) { + auto *layout = m_rootContainer->outputLayout(); + if (layout && enabled && !layout->outputs().contains(output)) { + layout->add(output, outputPosition); + } else if (layout && enabled + && layout->outputs().contains(output)) { + layout->move(output, outputPosition); + } else if (layout && !enabled + && layout->outputs().contains(output)) { + layout->remove(output); + } + } + if (!success && output) { + // The staged state was dropped, so the geometry applied before the + // commit no longer matches the output. extraState is already + // cleared here, so this reads the committed values. + if (auto *outputObject = outputFor(output)) + outputObject->applyPendingGeometry(); + } + if (currentRequest) + onOutputCommitFinished(pendingConfig, success); + if (success && committedState) { + const bool wasStateOnlyCommit = + (committedState->committed + & (WLR_OUTPUT_STATE_MODE | WLR_OUTPUT_STATE_SCALE + | WLR_OUTPUT_STATE_TRANSFORM | WLR_OUTPUT_STATE_ENABLED)) + && !(committedState->committed & WLR_OUTPUT_STATE_BUFFER); + const bool isDisable = + (committedState->committed & WLR_OUTPUT_STATE_ENABLED) + && !committedState->enabled; + if (wasStateOnlyCommit && !isDisable) { + renderWindow->update(viewport); + } + } + } else { + qCWarning(lcTlCore) + << "Commit callback received unexpected state pointer!" + << "Expected:" << extraState.get() + << "Got:" << committedState.get(); + if (currentRequest) + onOutputCommitFinished(pendingConfig, false); + } + + if (lastInFlight && m_groupsDirty) { + // Recompute instead of applying the cached effective state: + // the commit that just finished may have changed whether an + // output is available (e.g. the client disabled a mirror + // through wlr-output-management). + m_groupsDirty = false; + notifyOutputGroupsChanged(); + } +} + +void OutputManager::answerPendingConfiguration(bool ok) +{ + if (!m_pendingOutputConfig.config) { + return; + } + + if (ok) { + storeSingleOutputConfig(); + + const auto enabledOutputCount = std::count_if( + m_pendingOutputConfig.states.cbegin(), + m_pendingOutputConfig.states.cend(), + [](const WOutputState &state) { return state.enabled; }); + + for (const WOutputState &state : std::as_const(m_pendingOutputConfig.states)) { + auto *output = outputFor(state.output); + if (!output) { + continue; + } + if (state.enabled) { + onScreenEnabled(output); + } + + auto *outputConfig = output->config(); + const bool preservePosition = state.enabled && enabledOutputCount == 1; + if (!state.enabled || !outputConfig) { + continue; + } + if (!preservePosition) { + outputConfig->setX(state.x); + outputConfig->setY(state.y); + } + outputConfig->setWidth( + state.mode ? state.mode->width : state.customModeSize.width()); + outputConfig->setHeight( + state.mode ? state.mode->height : state.customModeSize.height()); + const int refresh = state.mode + ? state.mode->refresh + : (state.customModeRefresh > 0 + ? state.customModeRefresh + : output->output()->handle()->refresh); + outputConfig->setRefresh(refresh); + outputConfig->setTransform(static_cast(state.transform)); + outputConfig->setScale(state.scale); + outputConfig->setAdaptiveSyncEnabled(state.adaptiveSyncEnabled); + } + } + + if (m_pendingOutputConfig.protocol) + m_pendingOutputConfig.protocol->sendResult(m_pendingOutputConfig.config, + ok, + m_pendingOutputConfig.states); + m_pendingOutputConfig = {}; + Q_EMIT configurationChanged(); + + // Even a failed apply may have disabled outputs while copy mode was already + // torn down; re-applying the groups keeps the reported state truthful. + notifyOutputGroupsChanged(); +} + +bool OutputManager::restoreConfiguredSingleOutput(const QList &surfaces, bool updatePrimaryOutputConfig) +{ + if (!m_rootContainer || m_config->singleOutputId().isEmpty()) { + return false; + } + + Output *singleOutput = findOutputById(m_config->singleOutputId()); + if (!singleOutput) { + qCWarning(lcTlOutput) << "Cannot restore single-output display: output is not available" + << m_config->singleOutputId(); + return false; + } + + for (auto *output : std::as_const(m_rootContainer->outputs())) { + if (!output || !output->output()) { + continue; + } + if (output == singleOutput) { + if (!output->output()->isEnabled()) { + output->enable(); + } + if (auto *layout = m_rootContainer->outputLayout(); + output->output()->isEnabled() + && layout + && !layout->outputs().contains(output->output())) { + layout->autoAdd(output->output()); + } + continue; + } + if (output->output()->isEnabled()) { + WOutputStateGuard state; + wlr_output_state_set_enabled(state.get(), false); + const bool committed = wlr_output_commit_state(output->output()->handle(), state.get()); + if (!committed) { + qCWarning(lcTlOutput) << "Failed to disable non-selected output while restoring single-output display" + << output->output()->name(); + } + } + if (auto *layout = m_rootContainer->outputLayout(); + !output->output()->isEnabled() + && layout + && layout->outputs().contains(output->output())) { + layout->remove(output->output()); + } + } + + m_rootContainer->setPrimaryOutput(singleOutput, updatePrimaryOutputConfig); + m_rootContainer->moveSurfacesToOutput(surfaces, singleOutput, nullptr); + return true; +} + +void OutputManager::restorePrimaryOutput() +{ + if (!m_rootContainer) { + return; + } + + Output *primaryOutput = findOutputById(m_config->primaryOutputId()); + if (primaryOutput && primaryOutput->output() && primaryOutput->output()->isEnabled()) { + m_rootContainer->setPrimaryOutput(primaryOutput); + return; + } + + if (auto *fallback = findFirstAvailableOutput(nullptr)) { + m_rootContainer->setPrimaryOutput(fallback); + } +} + +void OutputManager::clearSingleOutputConfig() +{ + m_config->setSingleOutputId(QString()); +} + +void OutputManager::storeSingleOutputConfig() +{ + QString singleOutputId; + int enabledOutputCount = 0; + if (m_rootContainer) { + for (auto *output : std::as_const(m_rootContainer->outputs())) { + if (!output || !output->output() || !output->output()->isEnabled()) { + continue; + } + + enabledOutputCount++; + if (enabledOutputCount == 1) { + singleOutputId = output->getOutputId(); + } else { + singleOutputId.clear(); + break; + } + } + } + + m_config->setSingleOutputId(singleOutputId); +} + +Output *OutputManager::findFirstAvailableOutput(Output *excludeOutput) const +{ + if (!m_rootContainer) { + return nullptr; + } + + const auto &outputs = m_rootContainer->outputs(); + for (auto *output : std::as_const(outputs)) { + if (output != excludeOutput && output && output->output() && output->output()->isEnabled()) { + return output; + } + } + + return nullptr; +} + +void OutputManager::markScreenAsPrimaryIntent(Output *output) +{ + const QString id = output->getOutputId(); + if (!id.isEmpty()) { + m_primaryRestoreIntents[id] = true; + } +} + +void OutputManager::restoreScreenAsPrimary(Output *output) +{ + if (!output || !m_rootContainer) { + return; + } + + m_rootContainer->setPrimaryOutput(output); +} + +void OutputManager::switchPrimaryOutput(Output *from, + Output *to, + const QList &surfaces) +{ + if (!m_rootContainer || !to) { + return; + } + + m_rootContainer->setPrimaryOutput(to); + m_rootContainer->moveSurfacesToOutput(surfaces, to, from); +} + +void OutputManager::onScreenAdded(Output *output, const QList &surfaces) +{ + if (!output || !m_rootContainer) { + return; + } + + const QString id = output->getOutputId(); + const bool wasPrimary = m_primaryRestoreIntents.value(id); + const bool hasPrimaryOutput = m_rootContainer->primaryOutput() != nullptr; + + if (id == m_config->singleOutputId()) { + restoreConfiguredSingleOutput(surfaces); + m_primaryRestoreIntents.remove(id); + return; + } + + if (wasPrimary && m_mode == Mode::Extension && hasPrimaryOutput) { + restoreScreenAsPrimary(output); + } + + m_primaryRestoreIntents.remove(id); +} + +bool OutputManager::onScreenRemoved(Output *output, + const QList &surfaces, + bool wasPrimary) +{ + if (!output || !m_rootContainer) { + return false; + } + + const bool wasPrimaryBeforeRemoval = m_primaryRestoreIntents.value(output->getOutputId()); + + if (output->getOutputId() == m_config->singleOutputId()) { + return true; + } + + // Only a screen that was primary *and* left no primary behind (it was the last + // output) is restored as primary when it comes back. A multi-screen primary + // removal keeps the remaining primary in charge, as it always did. + if (wasPrimary && !wasPrimaryBeforeRemoval && !m_rootContainer->primaryOutput()) { + markScreenAsPrimaryIntent(output); + } + + // Windows of the removed screen move to the primary that is left. This must not + // depend on whether the removed screen was the primary: with other outputs still + // around, the primary has already moved to one of them and the windows have to + // follow it, or they end up outside every visible screen. + if (auto *primaryOutput = m_rootContainer->primaryOutput()) { + m_rootContainer->moveSurfacesToOutput(surfaces, primaryOutput, output); + } + return false; +} + +void OutputManager::onScreenDisabled(Output *output, + const QList &surfaces) +{ + if (!output || !m_rootContainer) { + return; + } + + const bool isCurrentPrimary = (m_rootContainer->primaryOutput() == output); + + if (isCurrentPrimary) { + markScreenAsPrimaryIntent(output); + } + + if (isCurrentPrimary && !m_rootContainer->outputs().isEmpty()) { + if (auto *nextPrimary = findFirstAvailableOutput(output)) { + switchPrimaryOutput(output, nextPrimary, surfaces); + } + } else if (!isCurrentPrimary) { + if (auto *primaryOutput = m_rootContainer->primaryOutput()) { + m_rootContainer->moveSurfacesToOutput(surfaces, primaryOutput, output); + } + } + + notifyOutputGroupsChanged(); +} + +void OutputManager::onScreenEnabled(Output *output) +{ + if (!output || !m_rootContainer) { + return; + } + + const QString id = output->getOutputId(); + const bool wasPrimary = m_primaryRestoreIntents.value(id); + if (wasPrimary && m_mode == Mode::Extension && m_rootContainer->primaryOutput()) { + restoreScreenAsPrimary(output); + } + + m_primaryRestoreIntents.remove(id); +} diff --git a/src/output/outputmanager.h b/src/output/outputmanager.h new file mode 100644 index 0000000000..c37b7e3379 --- /dev/null +++ b/src/output/outputmanager.h @@ -0,0 +1,223 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "modules/output-group/outputgroupmanagerinterfacev1.h" + +#include +#include +#include + +class Output; +class OutputConfig; +class OutputGroupManagerInterfaceV1; +class RootSurfaceContainer; +class SessionManager; +class SurfaceWrapper; +class TreelandConfig; +class Session; +class WallpaperManager; +class Workspace; +struct wlr_output; +struct wlr_gamma_control_manager_v1; +struct wlr_gamma_control_manager_v1_set_gamma_event; +struct wlr_output_power_manager_v1; +struct wlr_output_power_v1_set_mode_event; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutput; +class WBackend; +class WListenerOwner; +class WOutputRenderWindow; +class WOutputViewport; +class WXdgOutputManager; +WAYLIB_SERVER_END_NAMESPACE + +class OutputManager + : public QObject + , public OutputGroupHost +{ + Q_OBJECT +public: + enum class Mode + { + Extension, + Copy + }; + + explicit OutputManager(RootSurfaceContainer *rootContainer, + TreelandConfig *config, + WAYLIB_SERVER_NAMESPACE::WOutputRenderWindow *renderWindow, + QObject *parent = nullptr); + ~OutputManager() override = default; + + Mode mode() const; + void setBackend(WAYLIB_SERVER_NAMESPACE::WBackend *backend); + void setOutputGroupInterface(OutputGroupManagerInterfaceV1 *interface); + void setGammaControlManager(wlr_gamma_control_manager_v1 *manager); + void setOutputPowerManager(wlr_output_power_manager_v1 *manager); + void setXdgOutputManagers(WAYLIB_SERVER_NAMESPACE::WXdgOutputManager *manager, + WAYLIB_SERVER_NAMESPACE::WXdgOutputManager *xwaylandManager, + SessionManager *sessionManager); + WAYLIB_SERVER_NAMESPACE::WXdgOutputManager *xwaylandOutputManager() const; + + QList workspaceSurfaces(Output *filterOutput = nullptr) const; + Output *outputFor(WAYLIB_SERVER_NAMESPACE::WOutput *output) const; + Output *outputAtCursor() const; + const QList &outputs() const; + void requestAdditionalOutputs(); + void applyMode(Mode mode); + void wakePoweredOffOutputs(); + + void backendStarted(); + + // OutputGroupHost + bool isOutputAvailable(const QString &uuid) const override; + QList outputGroupMembers() const override; + void writeOutputGroupMembership(const QString &uuid, + const QString &groupName, + qlonglong joinTime, + qlonglong lastSetSourceTime) override; + void applyOutputGroups() override; + + Output *findOutputByUuid(const QString &uuid) const; + +Q_SIGNALS: + void modeChanged(); + void outputsChanged(); + void configurationChanged(); + +private Q_SLOTS: + void continueOutputAdded(); + +private: + friend class SessionOutputChannel; + void selectSession(Session *session); + void setScale(WAYLIB_SERVER_NAMESPACE::WOutput *output, qreal scale); + void testOrApplyConfiguration(WAYLIB_SERVER_NAMESPACE::WOutputManagerV1 *protocol, + wlr_output_configuration_v1 *config, bool onlyTest); + + void setGamma(wlr_gamma_control_manager_v1_set_gamma_event *event); + void setPowerMode(wlr_output_power_v1_set_mode_event *event); + void outputAdded(WAYLIB_SERVER_NAMESPACE::WOutput *output); + void outputRemoved(WAYLIB_SERVER_NAMESPACE::WOutput *output); + void processOutputAdded(WAYLIB_SERVER_NAMESPACE::WOutput *output); + void onScreenAdded(Output *output, const QList &surfaces); + bool onScreenRemoved(Output *output, + const QList &surfaces, + bool wasPrimary); + void onScreenDisabled(Output *output, const QList &surfaces); + void onScreenEnabled(Output *output); + + bool restoreConfiguredSingleOutput(const QList &surfaces, bool updatePrimaryOutputConfig = false); + void restorePrimaryOutput(); + void storeSingleOutputConfig(); + void clearSingleOutputConfig(); + // Converts every mirror output back to a normal output; used before the + // output-management protocol reconfigures the outputs itself. + void deactivateGroupMirrors(); + Output *convertMirrorToNormal(int index); + void notifyOutputGroupsChanged(); + + Output *createNormalOutput(WAYLIB_SERVER_NAMESPACE::WOutput *output); + Output *createCopyOutput(WAYLIB_SERVER_NAMESPACE::WOutput *output, Output *proxy); + bool ensureInRootContainer(Output *output); + void removeFromRootContainer(Output *output); + void removeFromRootContainer(WAYLIB_SERVER_NAMESPACE::WOutput *output); + WAYLIB_SERVER_NAMESPACE::WOutputViewport *ownOutputViewport( + WAYLIB_SERVER_NAMESPACE::WOutput *output) const; + // Builds and tests the wlr_output_state for one pending output state without + // applying anything. Returns false when the state cannot be built or the + // backend rejects it. + bool testOutputState(const WAYLIB_SERVER_NAMESPACE::WOutputState &state) const; + void moveSurfaces(const QList &surfaces, + Output *targetOutput, + Output *sourceOutput); + void saveCurrentConfig(Output *output); + void publishOutput(Output *outputObject); + void restoreOutputConfig(WAYLIB_SERVER_NAMESPACE::WOutput *output, + Output *outputObject, + bool isInitialOutput); + void restoreExtensionOutput(Output *outputObject); + void handleOutputCommit(bool success, + WAYLIB_SERVER_NAMESPACE::WOutputHelper::ExtraState committedState, + wlr_output_configuration_v1 *pendingConfig, + quint64 generation, + WAYLIB_SERVER_NAMESPACE::WOutputHelper::ExtraState extraState, + WAYLIB_SERVER_NAMESPACE::WOutputRenderWindow *renderWindow, + WAYLIB_SERVER_NAMESPACE::WOutputViewport *viewport, + QPointer output, + QPoint outputPosition, + bool enabled); + int indexOf(WAYLIB_SERVER_NAMESPACE::WOutput *output) const; + Output *findOutputByName(const QString &name) const; + Output *findOutputById(const QString &id) const; + void allowNonDrmOutputAutoChangeMode(WAYLIB_SERVER_NAMESPACE::WOutput *output); + void enableAllOutputs(); + void restoreExtensionModeFromConfig(); + void restoreInitialOutputConfiguration(); + void finishInitialOutputScanIfReady(); + Output *findFirstAvailableOutput(Output *excludeOutput) const; + void markScreenAsPrimaryIntent(Output *output); + void restoreScreenAsPrimary(Output *output); + void switchPrimaryOutput(Output *from, Output *to, const QList &surfaces); + RootSurfaceContainer *m_rootContainer = nullptr; + TreelandConfig *const m_config; + QPointer m_session; + quint64 m_sessionGeneration = 0; + WAYLIB_SERVER_NAMESPACE::WOutputRenderWindow *m_renderWindow = nullptr; + WAYLIB_SERVER_NAMESPACE::WBackend *m_backend = nullptr; + WAYLIB_SERVER_NAMESPACE::WXdgOutputManager *m_xwaylandOutputManager = nullptr; + OutputGroupManagerInterfaceV1 *m_outputGroupManager = nullptr; + WAYLIB_SERVER_NAMESPACE::WListenerOwner m_gammaControlListenerOwner; + WAYLIB_SERVER_NAMESPACE::WListenerOwner m_outputPowerListenerOwner; + WAYLIB_SERVER_NAMESPACE::WListenerOwner m_outputStateListenerOwner; + Mode m_mode = Mode::Extension; + // Name of the group created by the menu bar copy-mode toggle, so the + // toggle only dissolves its own group. + QString m_menuBarGroupName; + bool m_applyingOutputGroups = false; + // A group re-apply was requested while an output-management apply was in + // flight; it runs once the last commit job finished. + bool m_groupsDirty = false; + int m_inFlightOutputCommits = 0; + // Synchronous view of the output group membership. The generated DConfig + // wrappers update their cached value immediately on a setter, but the + // worker thread echoes the stored value back with a queued call that can + // land out of order and rewind the cache to an older value. Every write + // goes through here too, so reads observe the last write without waiting + // for that echo. + QHash m_groupMembership; + QMap m_primaryRestoreIntents; + QList m_outputs; + QMap m_pendingOutputs; + QSet m_powerOffOutputs; + bool m_backendStartFinished = false; + bool m_initialOutputScanFinished = false; + + struct PendingOutputConfig + { + wlr_output_configuration_v1 *config = nullptr; + QPointer protocol; + QPointer owner; + QList states; + int pendingCommits = 0; + bool allSuccess = true; + }; + PendingOutputConfig m_pendingOutputConfig; + + void onOutputCommitFinished(wlr_output_configuration_v1 *config, bool success); + // The single exit of an apply: answers the client and stores the applied + // state. Every path that ends a pending configuration goes through here. + void answerPendingConfiguration(bool ok); +}; diff --git a/src/plugins/CMakeLists.txt b/src/plugins/CMakeLists.txt new file mode 100644 index 0000000000..5999afa539 --- /dev/null +++ b/src/plugins/CMakeLists.txt @@ -0,0 +1,2 @@ +add_subdirectory(multitaskview) +add_subdirectory(lockscreen) \ No newline at end of file diff --git a/src/plugins/lockscreen/CMakeLists.txt b/src/plugins/lockscreen/CMakeLists.txt new file mode 100644 index 0000000000..8eeac1d5e7 --- /dev/null +++ b/src/plugins/lockscreen/CMakeLists.txt @@ -0,0 +1,59 @@ +find_package(QT NAMES Qt6 COMPONENTS Core Quick Concurrent REQUIRED) +find_package(Dtk6 REQUIRED COMPONENTS SystemSettings Declarative) + +# Include translation utilities +include(${CMAKE_SOURCE_DIR}/cmake/TranslationUtils.cmake) + +qt_add_library(lockscreen SHARED + lockscreenplugin.h + lockscreenplugin.cpp +) + +qt_add_qml_module(lockscreen + URI LockScreen + SOURCES + logoprovider.h + logoprovider.cpp + QML_FILES + qml/HintLabel.qml + qml/LoginAnimation.qml + qml/QuickAction.qml + qml/SessionList.qml + qml/ShutdownView.qml + qml/UserInput.qml + qml/ControlAction.qml + qml/Greeter.qml + qml/LockView.qml + qml/LoginView.qml + qml/PowerList.qml + qml/RoundBlur.qml + qml/ShutdownButton.qml + qml/TimeDateWidget.qml + qml/UserList.qml + RESOURCE_PREFIX + /qt/qml + OUTPUT_DIRECTORY + ${PROJECT_BINARY_DIR}/qt/qml/Treeland/Plugins/LockScreen +) + +target_include_directories(lockscreen PUBLIC + $ + $ + $ +) + +target_link_libraries(lockscreen PRIVATE + Qt6::Core + Qt6::Quick + Qt6::Concurrent + libtreeland +) + +set_target_properties(lockscreen PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${TREELAND_PLUGINS_OUTPUT_PATH}" +) + +# Use translation utilities to setup translations +setup_translations(lockscreen lockscreen) + +install(TARGETS lockscreen DESTINATION ${TREELAND_PLUGINS_INSTALL_PATH}) diff --git a/src/plugins/lockscreen/lockscreenplugin.cpp b/src/plugins/lockscreen/lockscreenplugin.cpp new file mode 100644 index 0000000000..95be079709 --- /dev/null +++ b/src/plugins/lockscreen/lockscreenplugin.cpp @@ -0,0 +1,36 @@ +// Copyright (C) 2024 Dingyuan Zhang . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "lockscreenplugin.h" + +#include "core/qmlengine.h" +#include "interfaces/proxyinterface.h" +#include "output/output.h" +#include "core/waylandserver.h" + +void LockScreenPlugin::initialize(TreelandProxyInterface *proxy) +{ + m_proxy = proxy; + + new (&m_lockViewComponent) QQmlComponent(m_proxy->qmlEngine(), "LockScreen", "LoginView", this); + new (&m_lockscreenComponent) QQmlComponent(m_proxy->qmlEngine(), "LockScreen", "Greeter", this); +} + +void LockScreenPlugin::shutdown() +{ + m_proxy = nullptr; +} + +QQuickItem *LockScreenPlugin::createLockScreen(Output *output, QQuickItem *parent) +{ + return m_proxy->qmlEngine()->createComponent( + m_lockscreenComponent, + parent, + { { "output", QVariant::fromValue(output->output()) }, + { "outputItem", QVariant::fromValue(output->outputItem()) } }); +} + +QQuickItem *LockScreenPlugin::createLockView(QQuickItem *parent) +{ + return m_proxy->qmlEngine()->createComponent(m_lockViewComponent, parent); +} diff --git a/src/plugins/lockscreen/lockscreenplugin.h b/src/plugins/lockscreen/lockscreenplugin.h new file mode 100644 index 0000000000..f660ccc498 --- /dev/null +++ b/src/plugins/lockscreen/lockscreenplugin.h @@ -0,0 +1,46 @@ +// Copyright (C) 2024 Dingyuan Zhang . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "interfaces/lockscreeninterface.h" +#include "interfaces/plugininterface.h" + +#include +#include + +class LockScreenPlugin + : public QObject + , public PluginInterface + , public ILockScreen +{ + Q_OBJECT + Q_PLUGIN_METADATA(IID "org.deepin.treeland.plugin.lockscreen/1.0" FILE "metadata.json") + Q_INTERFACES(PluginInterface ILockScreen) +public: + QString name() const override + { + return QStringLiteral("LockScreen"); + } + + QString description() const override + { + return QStringLiteral("LockScreen plugin"); + } + + void initialize(TreelandProxyInterface *proxy) override; + void shutdown() override; + + bool enabled() const override + { + return true; + } + + QQuickItem *createLockView(QQuickItem *parent) override; + QQuickItem *createLockScreen(Output *output, QQuickItem *parent) override; + +private: + TreelandProxyInterface *m_proxy; + QQmlComponent m_lockViewComponent; + QQmlComponent m_lockscreenComponent; +}; diff --git a/src/plugins/lockscreen/logoprovider.cpp b/src/plugins/lockscreen/logoprovider.cpp new file mode 100644 index 0000000000..7b1faed2ef --- /dev/null +++ b/src/plugins/lockscreen/logoprovider.cpp @@ -0,0 +1,47 @@ +// SPDX-FileCopyrightText: 2024 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "logoprovider.h" + +#include + +#include + +DCORE_USE_NAMESPACE + +[[nodiscard]] QString LogoProvider::logo() noexcept +{ + auto url = QUrl::fromUserInput(DSysInfo::distributionOrgLogo(DSysInfo::Distribution, + DSysInfo::Transparent, + ":/dsg/logo.svg")); + return url.toString(); +} + +[[nodiscard]] QString LogoProvider::version() const noexcept +{ + if (DSysInfo::uosEditionType() == DSysInfo::UosEdition::UosEducation) { + return {}; + } + + QString version; + if (DSysInfo::uosType() == DSysInfo::UosServer) { + version = QString("%1").arg(DSysInfo::majorVersion()); + } else if (DSysInfo::isDeepin()) { + version = QString("%1 %2").arg(DSysInfo::majorVersion(), DSysInfo::uosEditionName(locale)); + } else { + version = QString("%1 %2").arg(DSysInfo::productVersion(), DSysInfo::productTypeString()); + } + + return version; +} + +void LogoProvider::updateLocale(const QLocale &newLocale) noexcept +{ + if (newLocale == locale) { + return; + } + + locale = newLocale; + Q_EMIT versionChanged(); +} diff --git a/src/plugins/lockscreen/logoprovider.h b/src/plugins/lockscreen/logoprovider.h new file mode 100644 index 0000000000..b8e73aa45a --- /dev/null +++ b/src/plugins/lockscreen/logoprovider.h @@ -0,0 +1,31 @@ +// SPDX-FileCopyrightText: 2024 UnionTech Software Technology Co., Ltd. +// +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef LOGOPROVIDER_H +#define LOGOPROVIDER_H + +#include + +class LogoProvider : public QObject +{ + Q_OBJECT + QML_ELEMENT +public: + explicit LogoProvider(QObject *parent = nullptr) + : QObject(parent){}; + + Q_PROPERTY(QString logo READ logo CONSTANT) + Q_PROPERTY(QString version READ version NOTIFY versionChanged) + [[nodiscard]] static QString logo() noexcept; + [[nodiscard]] QString version() const noexcept; + Q_INVOKABLE void updateLocale(const QLocale &newLocale) noexcept; + +Q_SIGNALS: + void versionChanged(); + +private: + QLocale locale{ QLocale::system() }; +}; + +#endif // LOGOPROVIDER_H diff --git a/src/plugins/lockscreen/metadata.json b/src/plugins/lockscreen/metadata.json new file mode 100644 index 0000000000..f9839d16c8 --- /dev/null +++ b/src/plugins/lockscreen/metadata.json @@ -0,0 +1,3 @@ +{ + "translate": "lockscreen" +} \ No newline at end of file diff --git a/src/plugins/lockscreen/qml/ControlAction.qml b/src/plugins/lockscreen/qml/ControlAction.qml new file mode 100644 index 0000000000..f2a023c50e --- /dev/null +++ b/src/plugins/lockscreen/qml/ControlAction.qml @@ -0,0 +1,179 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls +import QtQuick.Effects +import org.deepin.dtk 1.0 as D +import Treeland + +RowLayout { + id: bottomGroup + readonly property bool enableAnimation: WaylandServer.animationConfig.lockscreen + spacing: 15 + + Connections { + target: GreeterProxy + function onPrepareForSleep() { + powerItem.expand = false + } + } + + required property Item rootItem + property int buttonSize: 30 + property bool powerVisible: powerList.visible + + signal otherUserRequested() + signal inputFocusRequested() + + /***************/ + /* Components */ + /**************/ + + // TODO: Design the interface of session selection + Button { + id: sessionItem + Layout.alignment: Qt.AlignHCenter + visible: !GreeterProxy.hasActiveSession + + contentItem: D.IconLabel { + text: SessionModel.data(SessionModel.index(SessionModel.currentIndex, 0), SessionModel.NameRole) + color: "white" + } + + SessionList { + id: sessionList + x: (sessionItem.width - sessionList.width) / 2 - 10 + y: -sessionList.height - 10 + } + + background: RoundBlur { + radius: parent.width / 2 + color: Qt.rgba(1.0, 1.0, 1.0, 0.3) + } + + onClicked: { + sessionList.open() + } + } + + ControlActionItem { + id: userItem + Layout.alignment: Qt.AlignHCenter + visible: userList.count > 1 || WaylandServer.globalConfig.showOtherUserOption + iconName: "login_user" + + UserList { + id: userList + x: { + const popupLeftInOutput = bottomGroup.rootItem.width - 10 - userList.width + const buttonLeftInOutput = bottomGroup.x + userItem.x + // Popup.x is relative to the user switch button. + return popupLeftInOutput - buttonLeftInOutput + } + y: -userList.height - 10 + onClosed: { + userItem.expand = false + // The popup held the keyboard focus; hand it back to the input. + bottomGroup.inputFocusRequested() + } + onOtherUserRequested: bottomGroup.otherUserRequested() + } + + onClicked: { + showUserList() + } + } + + ControlActionItem { + id: powerItem + Layout.alignment: Qt.AlignHCenter + iconName: "login_power" + + ToolTip { + enabled: true + visible: powerItem.hovered + text: qsTr("Power") + } + + Item { + id: powerList + parent: rootItem + visible: powerItem.expand + width: rootItem.width + height: rootItem.height + x: 0 + y: 0 + + // Click outside the PowerList to close + MouseArea { + anchors.fill: parent + onClicked: { + powerItem.expand = false + } + } + + PowerList { + id: innerPowerList + width: rootItem.width + height: 140 + x: 0 + y: rootItem.height / 5 * 2 + } + } + onClicked: { + powerItem.expand = true + innerPowerList.focusPowerOff() + } + } + + component ControlActionItem: Item { + id: actionItem + property bool expand: false + property string iconName + property alias hovered: button.hovered + signal clicked() + implicitWidth: bottomGroup.buttonSize + 6 + implicitHeight: bottomGroup.buttonSize + 6 + RoundButton { + id: button + icon { + width: 16 + height: 16 + name: actionItem.iconName + } + + Behavior on width { + enabled: bottomGroup.enableAnimation + NumberAnimation { + duration: 150 + } + } + Behavior on height { + enabled: bottomGroup.enableAnimation + NumberAnimation { + duration: 150 + } + } + width: actionItem.expand ? bottomGroup.buttonSize + 6 : bottomGroup.buttonSize + height: actionItem.expand ? bottomGroup.buttonSize + 6 : bottomGroup.buttonSize + anchors.centerIn: parent + + background: RoundBlur { + radius: parent.width / 2 + color: Qt.rgba(1.0, 1.0, 1.0, 0.3) + } + onClicked: actionItem.clicked() + } + } + + /*****************************/ + /* Functions and Connections */ + /*****************************/ + + function showUserList() { + userItem.expand = true + userList.open() + } +} diff --git a/src/plugins/lockscreen/qml/Greeter.qml b/src/plugins/lockscreen/qml/Greeter.qml new file mode 100644 index 0000000000..95a7dcd336 --- /dev/null +++ b/src/plugins/lockscreen/qml/Greeter.qml @@ -0,0 +1,152 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import Treeland +import LockScreen + +FocusScope { + id: root + clip: true + + signal hideAnimationFinished() + + required property QtObject output + required property QtObject outputItem + visible: true + + x: outputItem.x + y: outputItem.y + width: outputItem.width + height: outputItem.height + + palette.windowText: Qt.rgba(1.0, 1.0, 1.0, 1.0) + + /**************/ + /* Components */ + /**************/ + + Rectangle { + id: background + readonly property bool enableAnimation: WaylandServer.animationConfig.lockscreen + + readonly property int scaleDuration: 1000 + readonly property int duration: (GreeterProxy.isLocked || scale !== 1) ? scaleDuration : 600 + readonly property bool hasWallpaper: wallpaper.surface !== null + property real effectStrength: 0.0 + readonly property bool dimActive: WaylandServer.config.lockscreenWallpaperDimEnabled + anchors.fill: parent + clip: true + color: hasWallpaper ? 'transparent' : 'black' + opacity: 0.0 + transformOrigin: Item.Center + scale: GreeterProxy.isLocked ? 1.2 : 1 + state: (GreeterProxy.isLocked || GreeterProxy.undecided || GreeterProxy.showShutdownView) ? "Show" : "Hide" + states: [ + State { + name: "Show" + PropertyChanges { + target: background + effectStrength: 1.0 + opacity: 1 + } + }, + State { + name: "Hide" + PropertyChanges { + target: background + effectStrength: 0.0 + opacity: 0.0 + } + } + ] + + Behavior on scale { + enabled: background.enableAnimation + NumberAnimation { + duration: background.scaleDuration + easing.type: Easing.OutExpo + } + } + + transitions: [ + Transition { + from: "*" + to: "Show" + enabled: background.enableAnimation + PropertyAnimation { + property: "effectStrength" + duration: background.duration + easing.type: Easing.OutExpo + } + PropertyAnimation { + property: "opacity" + duration: background.duration + easing.type: Easing.OutExpo + } + }, + Transition { + from: "*" + to: "Hide" + enabled: background.enableAnimation + PropertyAnimation { + property: "effectStrength" + duration: background.duration + easing.type: Easing.OutExpo + } + PropertyAnimation { + property: "opacity" + duration: background.duration + easing.type: Easing.OutExpo + } + } + ] + onStateChanged: { + if (state === "Show") { + // Only a real lock screen entry zooms the desktop wallpaper. + if (GreeterProxy.isLocked || GreeterProxy.undecided) + WaylandServer.startLockscreen(root.output, true); + wallpaper.play = true; + } else { + wallpaper.play = false; + WaylandServer.showDesktop(root.output) + } + } + onOpacityChanged: { + if (state === "Hide" && opacity === 0.0) + root.hideAnimationFinished() + } + + Wallpaper { + id: wallpaper + + anchors.fill: parent + clip: true + wallpaperRole: Wallpaper.Lockscreen + output: root.output + + visible: !background.dimActive + } + + ShaderEffect { + id: wallpaperEffect + + anchors.fill: parent + clip: true + visible: background.hasWallpaper && background.dimActive + + property variant source: wallpaper + property real u_dimRatio: WaylandServer.config.lockscreenWallpaperDimRatio + property real u_strength: background.effectStrength + + fragmentShader: "qrc:/shaders/wallpaper_luma_dim.frag.qsb" + } + } + + MouseArea { + anchors.fill: parent + enabled: true + } + +} diff --git a/src/plugins/lockscreen/qml/HintLabel.qml b/src/plugins/lockscreen/qml/HintLabel.qml new file mode 100644 index 0000000000..736bb35a00 --- /dev/null +++ b/src/plugins/lockscreen/qml/HintLabel.qml @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Layouts +import Treeland +import LockScreen +import org.deepin.dtk 1.0 as D +import QtQuick.Controls + +Popup { + property string hintText + modal: false + background: D.FloatingPanel { + anchors.fill: parent + radius: 12 + blurRadius: 12 + backgroundColor: D.Palette { + normal: Qt.rgba(238 / 255, 238 / 255, 238 / 255, 0.3) + } + } + + ColumnLayout { + Layout.alignment: Qt.AlignLeft + Text { + text: qsTr("Password Hint") + color: Qt.rgba(1, 1, 1, 0.7) + font: D.DTK.fontManager.t10 + } + Text { + text: hintText + color: palette.windowText + font: D.DTK.fontManager.t10 + } + } +} diff --git a/src/plugins/lockscreen/qml/LockView.qml b/src/plugins/lockscreen/qml/LockView.qml new file mode 100644 index 0000000000..8e42c08c8f --- /dev/null +++ b/src/plugins/lockscreen/qml/LockView.qml @@ -0,0 +1,210 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import Treeland + +FocusScope { + id: root + property int state: LoginAnimation.Show + readonly property bool powerVisible: controlAction.powerVisible + signal animationPlayFinished() + + /**************/ + /* Components */ + /**************/ + + function show() { + root.forceActiveFocus() + root.visible = true + root.state = LoginAnimation.Show + leftAnimation.item.start({x: root.x - quickAction.width, y: quickAction.y}, {x: quickAction.x, y: quickAction.y}) + logoAnimation.item.start({x: root.x - logo.width, y: logo.y}, {x: logo.x, y: logo.y}) + rightAnimation.item.start({x: root.width + userInput.width, y: userInput.y}, {x: userInput.x, y: userInput.y}) + bottomAnimation.item.start({x: controlAction.x, y: controlAction.y + controlAction.height}, {x: controlAction.x, y: controlAction.y}) + } + + function hide() { + root.state = LoginAnimation.Hide + leftAnimation.item.start({x: quickAction.x, y: quickAction.y}, {x: root.x - quickAction.width, y: quickAction.y}) + logoAnimation.item.start({x: logo.x, y: logo.y}, {x: root.x - logo.width, y: logo.y}) + rightAnimation.item.start({x: userInput.x, y: userInput.y}, {x: root.width + userInput.width, y: userInput.y}) + bottomAnimation.item.start({x: controlAction.x, y: controlAction.y}, {x: controlAction.x, y: controlAction.y + controlAction.height}) + } + + Component.onCompleted: { + if (GreeterProxy.isLocked) { + Qt.callLater(show) + } + } + + Loader { + id: leftAnimation + anchors.fill: parent + sourceComponent: LoginAnimation { + anchors.fill: parent + target: quickAction + state: root.state + } + } + + Loader { + id: logoAnimation + anchors.fill: parent + sourceComponent: LoginAnimation { + anchors.fill: parent + target: logo + state: root.state + } + } + + Loader { + id: rightAnimation + anchors.fill: parent + sourceComponent: LoginAnimation { + state: root.state + target: userInput + anchors.fill: parent + onStopped: { + root.animationPlayFinished() + } + } + } + + Loader { + id: bottomAnimation + anchors.fill: parent + sourceComponent: LoginAnimation { + state: root.state + target: controlAction + anchors.fill: parent + } + } + + Item { + id: leftComp + z: -1 + width: parent.width * 0.4 + anchors { + left: parent.left + top: parent.top + bottom: parent.bottom + leftMargin: 30 + topMargin: 30 + bottomMargin: 30 + } + } + + Item { + id: rightComp + z: -1 + anchors { + left: leftComp.right + right: parent.right + top: parent.top + bottom: parent.bottom + leftMargin: 30 + rightMargin: 30 + topMargin: 30 + bottomMargin: 30 + } + } + + QuickAction { + id: quickAction + visible: !root.powerVisible + anchors { + verticalCenter : parent.verticalCenter + right: leftComp.right + rightMargin: leftComp.width / 9 + } + } + + Row { + id: logo + anchors { + bottom: leftComp.bottom + left: leftComp.left + } + + LogoProvider { + id: logoProvider + } + + Image { + id: logoPic + source: logoProvider.logo + height: 32 + fillMode: Image.PreserveAspectFit + } + + Text { + text: logoProvider.version + font.weight: Font.Normal + font.pixelSize: 14 + color: Qt.rgba(1, 1, 1, 153 / 255) + } + } + + UserInput { + id: userInput + visible: !root.powerVisible + anchors { + verticalCenter: parent.verticalCenter + left: rightComp.left + leftMargin: rightComp.width / 5 + } + + focus: true + } + + ControlAction { + id: controlAction + anchors { + bottom: rightComp.bottom + right: rightComp.right + } + rootItem: root + } + + /*****************************/ + /* Functions and Connections */ + /*****************************/ + + Connections { + target: controlAction + function onOtherUserRequested() { + userInput.startOtherUserMode() + } + function onInputFocusRequested() { + userInput.focusInput() + } + } + + Connections { + target: GreeterProxy + function onLockChanged(isLocked) { + if (isLocked) { + root.show() + } else { + root.hide() + } + } + } + + onAnimationPlayFinished: { + if (!GreeterProxy.isLocked) { + root.visible = false + } + } + + function showUserView() { + root.animationPlayFinished.connect(root.__showUserList) + } + + function __showUserList() { + controlAction.showUserList() + root.animationPlayFinished.disconnect(root.__showUserList) + } +} diff --git a/src/plugins/lockscreen/qml/LoginAnimation.qml b/src/plugins/lockscreen/qml/LoginAnimation.qml new file mode 100644 index 0000000000..290f6cc498 --- /dev/null +++ b/src/plugins/lockscreen/qml/LoginAnimation.qml @@ -0,0 +1,91 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Treeland + +Item { + id: root + + signal stopped + + visible: false + clip: true + + enum State { + Show = 1, + Hide = 2 + } + + property int state: LoginAnimation.Show + required property var target + + readonly property bool animationEnabled: WaylandServer.animationConfig.lockscreen + + function start(pos, to) { + if (GreeterProxy.showAnimation && animationEnabled) { + xAni.from = pos.x + xAni.to = to.x + + yAni.from = pos.y + yAni.to = to.y + + effect.sourceItem = root.target + + visible = true + animation.start() + } else { + target.x = to.x + target.y = to.y + stop() + } + } + + function stop() { + visible = false + effect.sourceItem = null + stopped() + } + + ShaderEffectSource { + id: effect + live: true + hideSource: true + sourceItem: root.target + width: root.target.width + height: root.target.height + x: root.target.x + y: root.target.y + } + + Connections { + target: animation + function onStopped() { + stop() + } + } + + ParallelAnimation { + id: animation + + XAnimator { + id: xAni + target: effect + duration: 1000 + easing.type: Easing.OutExpo + } + YAnimator { + id: yAni + target: effect + duration: 1000 + easing.type: Easing.OutExpo + } + OpacityAnimator { + target: effect + duration: 1000 + from: root.state === LoginAnimation.Show ? 0 : 1 + to: root.state === LoginAnimation.Show ? 1 : 0 + easing.type: Easing.OutExpo + } + } +} diff --git a/src/plugins/lockscreen/qml/LoginView.qml b/src/plugins/lockscreen/qml/LoginView.qml new file mode 100644 index 0000000000..b0652bf68a --- /dev/null +++ b/src/plugins/lockscreen/qml/LoginView.qml @@ -0,0 +1,82 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +import QtQuick +import Treeland +import LockScreen + +// Global login UI container. Unlike Greeter (created once per output), this +// component is a single instance owned by the LockScreen container and +// repositioned to follow the output the cursor is on. It is created when the +// lock screen becomes visible and destroyed when it hides, so the login UI +// does not outlive the lock session. +FocusScope { + id: root + + palette.windowText: Qt.rgba(1.0, 1.0, 1.0, 1.0) + + signal animationPlayed + signal animationPlayFinished + + LockView { + id: lockView + anchors.fill: parent + onAnimationPlayFinished: function () { + if (lockView.state === LoginAnimation.Hide) { + root.animationPlayFinished() + } + } + } + + Loader { + id: shutdownViewLoader + anchors.fill: parent + active: GreeterProxy.showShutdownView + sourceComponent: shutdownViewComponent + } + + Component { + id: shutdownViewComponent + ShutdownView { + id: shutdownView + anchors.fill: parent + onSwitchUser: { + root.switchUser() + } + } + } + + /*****************************/ + /* Functions and Connections */ + /*****************************/ + + function switchUser() { + GreeterProxy.lock() + lockView.showUserView() + } + + Connections { + target: GreeterProxy + + function onLockChanged(isLocked) { + if (!isLocked) + root.animationPlayed() + } + + function onShowShutdownViewChanged(show) { + if (!show && !GreeterProxy.isLocked) { + // Restore the normal mode promptly, but do not hide the lock + // screen container here: the Greeter background still needs to + // fade out. LockScreen hides the container when that fade ends. + root.animationPlayed() + } + } + + function onPrepareForSleep() { + GreeterProxy.showShutdownView = false + } + + function onSwitchUser() { + root.switchUser() + } + } +} diff --git a/src/plugins/lockscreen/qml/PowerList.qml b/src/plugins/lockscreen/qml/PowerList.qml new file mode 100644 index 0000000000..41ac9cb87c --- /dev/null +++ b/src/plugins/lockscreen/qml/PowerList.qml @@ -0,0 +1,145 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Treeland +import LockScreen +import org.deepin.dtk 1.0 as D +import QtQuick.Controls +import QtQuick.Layouts + +FocusScope { + id: root + property alias modelChildren: objModel.children + + implicitWidth: layout.width + implicitHeight: layout.height + + // A hidden or disabled button cannot take the focus (visible already covers + // hidden ancestors), so fall back to the first button that can: the arrow + // keys need a starting point. When nothing can, nothing is focused. + function focusItem(item) { + if (item.visible && item.enabled) { + item.forceActiveFocus() + } else { + const items = navigableItems() + if (items.length > 0) + items[0].forceActiveFocus() + } + } + + function focusPowerOff() { + focusItem(powerOffBtn) + } + + // Focus the power button the shutdown-menu focus target names. The session + // buttons (lock / logout) belong to the caller's scope, so the caller + // handles those and every target that does not resolve here. + function focusPowerButton(focus) { + switch (focus) { + case WaylandServer.ShutdownMenuFocus.PowerOff: focusItem(powerOffBtn); return true + case WaylandServer.ShutdownMenuFocus.Reboot: focusItem(rebootBtn); return true + case WaylandServer.ShutdownMenuFocus.Suspend: focusItem(suspendBtn); return true + case WaylandServer.ShutdownMenuFocus.Hibernate: focusItem(hibernateBtn); return true + } + return false + } + + // The focus chain is the row's buttons in visual order: the power buttons + // declared here, plus the session buttons (lock / switch user / logout) the + // view injects through modelChildren. It is the ObjectModel's own children + // array, hence already in the order the Repeater lays out. A hidden or + // disabled button steps aside (a disabled button hides itself). + function navigableItems() { + return modelChildren.filter(item => item.visible && item.enabled) + } + + function moveFocus(step) { + const items = navigableItems() + if (items.length === 0) + return + let index = -1 + for (let i = 0; i < items.length; ++i) { + if (items[i].activeFocus) { + index = i + break + } + } + const next = index < 0 ? (step > 0 ? 0 : items.length - 1) + : (index + step + items.length) % items.length + items[next].forceActiveFocus() + } + + // The buttons handle neither the arrow keys nor Tab themselves, so the + // scope moves the focus relative to the current item, wrapping at both ends. + // Tab is a focus-traversal key: it only reaches the focused button and the + // window handles it before any ancestor, so the buttons forward it here + // (Keys.forwardTo) — otherwise Qt would tab out of the row. + Keys.onLeftPressed: function(event) { + moveFocus(-1) + event.accepted = true + } + Keys.onRightPressed: function(event) { + moveFocus(1) + event.accepted = true + } + Keys.onTabPressed: function(event) { + moveFocus(1) + event.accepted = true + } + Keys.onBacktabPressed: function(event) { + moveFocus(-1) + event.accepted = true + } + + RowLayout { + id: layout + spacing: 100 + anchors.centerIn: parent + Repeater { + model: ObjectModel { + id: objModel + + ShutdownButton { + id: powerOffBtn + enabled: GreeterProxy.canPowerOff + Keys.forwardTo: [root] + text: qsTr("Shut Down") + icon.name: "login_shutdown" + onClicked: GreeterProxy.powerOff() + } + + ShutdownButton { + id: rebootBtn + enabled: GreeterProxy.canReboot + Keys.forwardTo: [root] + text: qsTr("Reboot") + icon.name: "login_reboot" + onClicked: GreeterProxy.reboot() + } + + ShutdownButton { + id: suspendBtn + enabled: GreeterProxy.canSuspend + Keys.forwardTo: [root] + text: qsTr("Suspend") + icon.name: "login_suspend" + onClicked: { + GreeterProxy.suspend() + } + } + + ShutdownButton { + id: hibernateBtn + enabled: GreeterProxy.canHibernate + Keys.forwardTo: [root] + text: qsTr("Hibernate") + icon.name: "login_hibernate" + onClicked: { + GreeterProxy.hibernate() + } + } + } + } + } +} diff --git a/src/plugins/lockscreen/qml/QuickAction.qml b/src/plugins/lockscreen/qml/QuickAction.qml new file mode 100644 index 0000000000..afb4ce8b51 --- /dev/null +++ b/src/plugins/lockscreen/qml/QuickAction.qml @@ -0,0 +1,22 @@ +// Copyright (C) 2023 justforlxz . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls +import Treeland + +Column { + id: root + + TimeDateWidget { + id: timedate + currentLocale :{ + let user = UserModel.get(UserModel.currentUserName) + return user.locale + } + width: 400 + height: 157 + } +} + diff --git a/src/plugins/lockscreen/qml/RoundBlur.qml b/src/plugins/lockscreen/qml/RoundBlur.qml new file mode 100644 index 0000000000..1fb358a980 --- /dev/null +++ b/src/plugins/lockscreen/qml/RoundBlur.qml @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Treeland +import org.deepin.dtk 1.0 as D + +Blur { + id: root + glassEnabled: false + blurMax: 64 + brightness: 0 + + property color color: Qt.rgba(1, 1, 1, 0.1) + + Rectangle { + anchors.fill: parent + radius: root.radius + color: root.color + } +} diff --git a/src/plugins/lockscreen/qml/SessionList.qml b/src/plugins/lockscreen/qml/SessionList.qml new file mode 100644 index 0000000000..b7a7fd287f --- /dev/null +++ b/src/plugins/lockscreen/qml/SessionList.qml @@ -0,0 +1,102 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls + +import Treeland +import LockScreen + +Popup { + id: popup + + readonly property int sessionItemHeight: 60 + readonly property int listMargin: 10 + readonly property real maxListHeight: 4 * sessionItemHeight + 3 * list.spacing + + modal: false + width: 220 + height: Math.min(maxListHeight, list.contentHeight) + topPadding + bottomPadding + listMargin * 2 + objectName: "LoginScreenSessionListPopup" + + ListView { + id: list + anchors.fill: parent + anchors.margins: popup.listMargin + spacing: 1 + clip: true + model: SessionModel + + ScrollBar.vertical: ScrollBar { + id: verticalScrollBar + parent: popup.contentItem + policy: ScrollBar.AlwaysOn + + anchors { + top: list.top + bottom: list.bottom + right: parent.right + rightMargin: 2 - popup.rightPadding - verticalScrollBar.rightPadding + } + } + + delegate: Item { + required property string name + required property int index + width: parent.width + height: popup.sessionItemHeight + MouseArea { + anchors.fill: parent + hoverEnabled: true + propagateComposedEvents: true + onEntered: { + background.color = Qt.rgba(0, 129/255, 255/255, 0.9) + } + onExited: { + background.color = Qt.rgba(0, 0, 0, 0.05) + } + onClicked: (mouse) => { + mouse.accepted = false + SessionModel.currentIndex = index + popup.close() + } + } + + Rectangle { + id: background + width: parent.width + height: parent.height + color: Qt.rgba(0, 0, 0, 0.05) + radius: 15 + } + RowLayout { + spacing: 5 + anchors.fill: parent + Rectangle { + width: 36 + height: 36 + Layout.leftMargin: 5 + Image { + anchors.fill: parent + // TODO: Provide icon for session + // source: name + fillMode: Image.PreserveAspectFit + } + } + Text { + text: name + Layout.fillWidth: true + } + Image { + // logined + } + } + } + } + onAboutToShow: { + // Fetch the session list on demand instead of watching the session dirs. + SessionModel.reload() + list.currentIndex = SessionModel.currentIndex + } +} diff --git a/src/plugins/lockscreen/qml/ShutdownButton.qml b/src/plugins/lockscreen/qml/ShutdownButton.qml new file mode 100644 index 0000000000..3ecdc6fee2 --- /dev/null +++ b/src/plugins/lockscreen/qml/ShutdownButton.qml @@ -0,0 +1,132 @@ +// Copyright (C) 2024 ShanShan Ye <847862258@qq.com>. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Treeland +import org.deepin.dtk as D +import QtQuick.Controls +import QtQuick.Layouts + +Button { + id: root + visible: enabled + focusPolicy: Qt.TabFocus + D.ColorSelector.inactived: false + + // A Qt Quick Button only activates on Space; the power menu is also driven + // with the Enter key. Auto-repeat is ignored, otherwise holding the key + // would run the action several times. + Keys.onReturnPressed: function(event) { + if (!event.isAutoRepeat) + root.click() + } + Keys.onEnterPressed: function(event) { + if (!event.isAutoRepeat) + root.click() + } + + property D.Palette backgroundColor: D.Palette { + normal: Qt.rgba(1.0, 1.0, 1.0, 0.3) + hovered: Qt.rgba(1.0, 1.0, 1.0, 0.3) + pressed: Qt.rgba(1.0, 1.0, 1.0, 0.5) + normalDark: Qt.rgba(1.0, 1.0, 1.0, 0.3) + hoveredDark: Qt.rgba(1.0, 1.0, 1.0, 0.3) + pressedDark: Qt.rgba(1.0, 1.0, 1.0, 0.5) + } + + property D.Palette focusBackgroundColor: D.Palette { + normal: Qt.rgba(1.0, 1.0, 1.0, 0.1) + hovered: Qt.rgba(1.0, 1.0, 1.0, 0.3) + pressed: Qt.rgba(1.0, 1.0, 1.0, 0.5) + normalDark: Qt.rgba(1.0, 1.0, 1.0, 0.1) + hoveredDark: Qt.rgba(1.0, 1.0, 1.0, 0.3) + pressedDark: Qt.rgba(1.0, 1.0, 1.0, 0.5) + } + + property D.Palette contentTextColor: D.Palette { + normal: Qt.rgba(1.0, 1.0, 1.0, 1.0) + hovered: Qt.rgba(0.0, 0.0, 0.0, 0.7) + pressed: Qt.rgba(0.0, 0.0, 0.0, 0.7) + normalDark: Qt.rgba(1.0, 1.0, 1.0, 1.0) + hoveredDark: Qt.rgba(0.0, 0.0, 0.0, 0.7) + pressedDark: Qt.rgba(0.0, 0.0, 0.0, 0.7) + } + + palette.windowText: root.D.ColorSelector.contentTextColor + palette.buttonText: root.D.ColorSelector.contentTextColor + + icon { + width: 40 + height: 40 + } + + contentItem: Item { + implicitWidth: btn.width + implicitHeight: btn.height + txt.height + txt.anchors.topMargin + Control { + id: btn + width: 84 + height: 84 + contentItem: D.DciIcon { + palette: D.DTK.makeIconPalette(root.palette) + mode: root.D.ColorSelector.controlState + theme: root.D.ColorSelector.controlTheme + name: root.icon.name + sourceSize: Qt.size(icon.width, icon.height) + } + + background: Item { + RoundBlur { + anchors.fill: parent + radius: btn.width / 2 + color: root.activeFocus + ? root.D.ColorSelector.focusBackgroundColor + : root.D.ColorSelector.backgroundColor + } + D.FocusBoxBorder { + visible: root.activeFocus + anchors.fill: parent + anchors.margins: 1 + borderWidth: 3 + radius: width / 2 + color: Qt.rgba(1.0, 1.0, 1.0, 0.3) + } + } + } + + Label { + id: txt + anchors { + top: btn.bottom + topMargin: 20 + horizontalCenter: btn.horizontalCenter + } + leftPadding: 10 + rightPadding: 10 + topPadding: 4 + bottomPadding: 4 + text: root.text + color: root.D.ColorSelector.contentTextColor + + background: Item { + visible: root.pressed || root.hovered || root.activeFocus + RoundBlur { + anchors.fill: parent + radius: 6 + color: root.activeFocus + ? root.D.ColorSelector.focusBackgroundColor + : root.D.ColorSelector.backgroundColor + } + D.FocusBoxBorder { + visible: root.activeFocus + anchors.fill: parent + anchors.margins: 1 + borderWidth: 2 + radius: 6 + color: Qt.rgba(1.0, 1.0, 1.0, 0.3) + } + } + } + } + background: null +} diff --git a/src/plugins/lockscreen/qml/ShutdownView.qml b/src/plugins/lockscreen/qml/ShutdownView.qml new file mode 100644 index 0000000000..2c3a559a38 --- /dev/null +++ b/src/plugins/lockscreen/qml/ShutdownView.qml @@ -0,0 +1,82 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Treeland +import QtQuick.Controls + +FocusScope { + id: root + + signal switchUser() + + // The menu focuses the button the caller asked for; with no preference and + // when opened from the dock it is the lock button, the entry point when it + // is shown at all. Focus does not come back on its own when an ancestor + // only becomes visible later, so re-apply it then. + function applyFocus() { + if (powerList.focusPowerButton(GreeterProxy.shutdownMenuFocus)) + return + powerList.focusItem(GreeterProxy.shutdownMenuFocus === WaylandServer.ShutdownMenuFocus.LogOut + ? logoutBtn : lockBtn) + } + + Component.onCompleted: applyFocus() + onVisibleChanged: { + if (visible) + applyFocus() + } + + // A repeat request while the menu is already up only moves the focus. + Connections { + target: GreeterProxy + function onShutdownMenuFocusChanged() { + if (visible && GreeterProxy.showShutdownView) + applyFocus() + } + } + + MouseArea { + anchors.fill: parent + enabled: true + onClicked: GreeterProxy.showShutdownView = false + } + + PowerList { + id: powerList + width: parent.width + height: 140 + anchors { + top: parent.top + topMargin: parent.height / 5 * 2 + horizontalCenter: parent.horizontalCenter + } + + modelChildren: [ + ShutdownButton { + id: lockBtn + visible: !GreeterProxy.isLocked + Keys.forwardTo: [powerList] + text: qsTr("lock") + icon.name: "login_lock" + onClicked: GreeterProxy.lock() + }, + ShutdownButton { + id: switchBtn + visible: !GreeterProxy.isLocked && UserModel.count > 1 + Keys.forwardTo: [powerList] + text: qsTr("switch user") + icon.name: "login_switchuser" + onClicked: root.switchUser() + }, + ShutdownButton { + id: logoutBtn + visible: !GreeterProxy.isLocked + Keys.forwardTo: [powerList] + text: qsTr("Logout") + icon.name: "login_logout" + onClicked: GreeterProxy.logout() + } + ] + } +} diff --git a/src/plugins/lockscreen/qml/TimeDateWidget.qml b/src/plugins/lockscreen/qml/TimeDateWidget.qml new file mode 100644 index 0000000000..f2acc2a950 --- /dev/null +++ b/src/plugins/lockscreen/qml/TimeDateWidget.qml @@ -0,0 +1,52 @@ +// Copyright (C) 2023 ComixHe . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +import QtQuick +import QtQuick.Controls +import Treeland +import LockScreen + +Control { + id: timedataWidget + + property date currentDate: new Date() + property var currentLocale: Qt.locale() + + Timer { + interval: 1000 + running: true + repeat: true + triggeredOnStart: true + + onTriggered: { + currentDate = new Date() + } + } + + Text { + id: timeText + text: currentDate.toLocaleTimeString(currentLocale, "HH:mm") + font.weight: Font.Light + font.pixelSize: 80 + color: palette.windowText + + anchors { + left: parent.left + leftMargin: 20 + top: parent.top + } + } + + Text { + id: dateText + text: currentDate.toLocaleDateString(currentLocale) + font.weight: Font.Normal + font.pixelSize: 20 + color: palette.windowText + + anchors { + left: parent.left + leftMargin: 20 + top: timeText.bottom + } + } +} diff --git a/src/plugins/lockscreen/qml/UserInput.qml b/src/plugins/lockscreen/qml/UserInput.qml new file mode 100644 index 0000000000..4e4c9f174e --- /dev/null +++ b/src/plugins/lockscreen/qml/UserInput.qml @@ -0,0 +1,463 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +import QtQuick +import QtQuick.Controls +import QtQuick.Layouts +import org.deepin.dtk 1.0 as D +import Treeland +import LockScreen + +Item { + id: loginGroup + width: 220 + height: 300 + + property string normalHint: qsTr("Please enter password") + property bool enteringOtherUser: false + property bool showUserNotFoundError: false + property bool noPasswdLogin: false + + /**************/ + /* Components */ + /**************/ + + Item { + width: 32 + height: 32 + // Only a real lockscreen (an active session that got locked) shows the + // lock badge; the greeter (login / switch-user) must not. + // Manual user name login is a login screen too, whatever the user shown + // before had a session. + visible: GreeterProxy.isLocked && GreeterProxy.hasActiveSession + && !loginGroup.enteringOtherUser + anchors { + horizontalCenter: parent.horizontalCenter + bottom: parent.top + bottomMargin: 56 + } + D.DciIcon { + name: "login_lock" + anchors.centerIn: parent + sourceSize { + width: 18 + height: 22 + } + } + } + + Column { + id: userCol + spacing: 15 + anchors.centerIn: parent + + Rectangle { + width: 120 + height: 120 + anchors.horizontalCenter: parent.horizontalCenter + color: "transparent" + radius: 20 + border { + width: 2 + color: Qt.rgba(1, 1, 1, 0.1) + } + + D.QtIcon { + id: avatar + anchors.fill: parent + visible: false + } + + Rectangle { + id: maskSource + radius: 20 + anchors.fill: avatar + visible: false + } + D.OpacityMask { + anchors.fill: avatar + source: avatar + maskSource: maskSource + invert: false + visible: !loginGroup.enteringOtherUser + } + D.DciIcon { + anchors.centerIn: parent + name: "login_user" + sourceSize { width: 96; height: 96 } + visible: loginGroup.enteringOtherUser + } + Rectangle { + radius: 20 + anchors.fill: avatar + color: "transparent" + border { + width: 1 + color: Qt.rgba(0, 0, 0, 0.2) + } + } + } + + Text { + text: "User" + id: username + font.bold: true + font.pixelSize: D.DTK.fontManager.t2.pixelSize + font.family: D.DTK.fontManager.t2.family + color: palette.windowText + anchors.horizontalCenter: parent.horizontalCenter + } + + Item { + id: passwordSlot + width: loginGroup.width + height: 30 + anchors.horizontalCenter: parent.horizontalCenter + enabled: !GreeterProxy.authPending + + TextField { + id: passwordField + + property bool capsIndicatorVisible: false + + visible: !loginGroup.noPasswdLogin + + anchors.fill: parent + + cursorDelegate: Rectangle { + id: cursor + + width: 1 + height: 18 + color: palette.windowText + + visible: parent.activeFocus && !parent.readOnly && parent.selectionStart === parent.selectionEnd + + Connections { + target: cursor.parent + function onCursorPositionChanged() { + // keep a moving cursor visible + cursor.opacity = 1 + cursorTimer.restart() + } + } + + Timer { + id: cursorTimer + running: cursor.parent.activeFocus && !cursor.parent.readOnly && interval != 0 + repeat: true + // TODO: Application.styleHints.cursorFlashTime / 2, waylib is not supports + // Application.styleHints now. + interval: 600 + onTriggered: cursor.opacity = !cursor.opacity ? 1 : 0 + // force the cursor visible when gaining focus + onRunningChanged: cursor.opacity = 1 + } + } + + horizontalAlignment: TextInput.AlignHCenter + echoMode: loginGroup.enteringOtherUser ? TextInput.Normal + : (showPasswordBtn.hiddenPWD ? TextInput.Password : TextInput.Normal) + rightPadding: 22 + leftPadding: { + var remaining = loginGroup.width - contentWidth - rightPadding + if (capsIndicator.visible) + return rightPadding + return Math.max(8, remaining > rightPadding ? rightPadding : remaining) + } + maximumLength: 510 + placeholderText: loginGroup.enteringOtherUser ? qsTr("Username") : qsTr("Password") + placeholderTextColor: Qt.rgba(1.0, 1.0, 1.0, 0.6) + color: palette.windowText + font: D.DTK.fontManager.t8 + Keys.onPressed: function (event) { + if (!loginGroup.enteringOtherUser + && (event.matches(StandardKey.Undo) + || event.matches(StandardKey.Redo))) { + event.accepted = true + } else if (event.key === Qt.Key_CapsLock) { + capsIndicatorVisible = !capsIndicatorVisible + event.accepted = true + } else if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { + if (loginGroup.enteringOtherUser) + confirmOtherUser() + else + userLogin() + event.accepted = true + } + } + + D.ActionButton { + id: capsIndicator + height: parent.height + anchors { + left: parent.left + leftMargin: 3 + verticalCenter: parent.verticalCenter + } + visible: passwordField.capsIndicatorVisible && !loginGroup.enteringOtherUser + palette.windowText: undefined + icon { + name: "login_capslock" + height: 10 + width: 10 + } + Layout.alignment: Qt.AlignHCenter + implicitWidth: 16 + implicitHeight: 16 + } + + D.ActionButton { + id: showPasswordBtn + anchors { + right: parent.right + rightMargin: 3 + verticalCenter: parent.verticalCenter + } + property bool hiddenPWD: true + visible: !loginGroup.enteringOtherUser + icon { + name: hiddenPWD ? "login_display_password" : "login_hidden_password" + height: 10 + width: 10 + } + Layout.alignment: Qt.AlignHCenter + implicitWidth: 16 + implicitHeight: 16 + hoverEnabled: true + + background: Rectangle { + anchors.fill: parent + radius: 4 + color: showPasswordBtn.hovered ? Qt.rgba( + 0, 0, 0, + 0.1) : "transparent" + } + + onClicked: hiddenPWD = !hiddenPWD + } + + background: RoundBlur { + color: Qt.rgba(1, 1, 1, 0.4) + radius: 6 + } + } + + D.ActionButton { + id: noPwdLoginBtn + visible: loginGroup.noPasswdLogin + anchors.fill: parent + icon { + name: "login_open" + width: 16 + height: 16 + } + background: RoundBlur { + anchors.fill: parent + color: Qt.rgba(1.0, 1.0, 1.0, 0.4) + radius: parent.height / 2 + } + + onClicked: userLogin() + } + } + } + + D.ActionButton { + id: loginBtn + visible: !loginGroup.noPasswdLogin + icon { + name: "login_open" + width: 16 + height: 16 + } + height: passwordField.height + width: height + anchors { + left: userCol.right + bottom: userCol.bottom + leftMargin: 20 + } + enabled: passwordField.length != 0 && !GreeterProxy.authPending + font: D.DTK.fontManager.t8 + background: RoundBlur { + anchors.fill: parent + color: Qt.rgba(1.0, 1.0, 1.0, 0.4) + radius: parent.height / 2 + } + + onClicked: loginGroup.enteringOtherUser ? confirmOtherUser() : userLogin() + } + + RowLayout { + spacing: 10 + anchors { + right: userCol.left + bottom: userCol.bottom + rightMargin: 10 + } + height: passwordField.height + + RoundButton { + id: langBtn + text: 'L' // TODO: replace with icon + visible: false + Layout.fillHeight: true + Layout.preferredWidth: passwordField.height + background: Rectangle { + anchors.fill: parent + color: Qt.rgba(1.0, 1.0, 1.0, 0.4) + radius: parent.height / 2 + } + + onClicked: { + // TODO: impl language switch + console.log("need impl langBtn") + } + } + + RoundButton { + id: hintBtn + icon { + name: "login_hint" + width: 10 + height: 10 + } + visible: hintLabel.hintText.length != 0 + Layout.preferredWidth: 16 + Layout.preferredHeight: 16 + background: Rectangle { + id: hintBtnBackground + visible: hintBtn.hovered + anchors.fill: parent + color: Qt.rgba(1.0, 1.0, 1.0, 0.1) + radius: 4 + } + + HintLabel { + id: hintLabel + x: hintBtn.width - hintLabel.width + y: hintBtn.height + 11 + hintText: { + let user = UserModel.get(UserModel.currentUserName) + return user.passwordHint + } + } + + onClicked: hintLabel.open() + } + } + + Text { + id: hintText + visible: !loginGroup.enteringOtherUser || loginGroup.showUserNotFoundError + font: D.DTK.fontManager.t8 + color: Qt.rgba(1.0, 1.0, 1.0, 0.7) + anchors { + horizontalCenter: parent.horizontalCenter + top: userCol.bottom + topMargin: 16 + } + } + + /*****************************/ + /* Functions and Connections */ + /*****************************/ + + function resetHint() { + hintText.text = loginGroup.noPasswdLogin ? "" : normalHint + } + + // A closing popup hands the focus back to the button that opened it, so + // after the user list the input would need a click before it accepts typing. + // The popup calls this when it closes. + function focusInput() { + if (loginGroup.noPasswdLogin) + noPwdLoginBtn.forceActiveFocus() + else + passwordField.forceActiveFocus() + } + + function updateUser() { + loginGroup.enteringOtherUser = false + loginGroup.showUserNotFoundError = false + let currentUser = UserModel.get(UserModel.currentUserName) + username.text = currentUser.realName.length === 0 ? currentUser.name : currentUser.realName + passwordField.text = '' + avatar.fallbackSource = currentUser.icon + loginGroup.noPasswdLogin = currentUser.noPassword === true + resetHint() + if (loginGroup.noPasswdLogin) + noPwdLoginBtn.forceActiveFocus() + } + + function startOtherUserMode() { + loginGroup.enteringOtherUser = true + loginGroup.noPasswdLogin = false + loginGroup.showUserNotFoundError = false + username.text = qsTr("Enter username") + passwordField.text = "" + passwordField.forceActiveFocus() + } + + function confirmOtherUser() { + let name = passwordField.text.trim() + if (name.length === 0) return + if (UserModel.tryAddNssUser(name)) { + UserModel.currentUserName = name + // updateUser() fires via currentUserNameChanged, resets enteringOtherUser + } else { + loginGroup.showUserNotFoundError = true + hintText.text = qsTr("User not found.") + passwordField.selectAll() + passwordField.forceActiveFocus() + } + } + + function userLogin() { + if (!loginGroup.noPasswdLogin && passwordField.length === 0) + return + + let user = UserModel.get(UserModel.currentUserName) + let pwd = loginGroup.noPasswdLogin ? "" : passwordField.text + if (user.loggedIn) + GreeterProxy.unlock(user.name, pwd) + else + GreeterProxy.login(user.name, pwd, SessionModel.currentIndex) + } + + Connections { + target: GreeterProxy + function onFailedAttemptsChanged (attempts) { + if (attempts > 0) { + passwordField.selectAll() + if (loginGroup.activeFocus) { + passwordField.forceActiveFocus() + } + hintText.text = qsTr("Password is incorrect.") + } else { + passwordField.text = "" + resetHint() + } + } + } + + Connections { + target: UserModel + + function onUpdateTranslations(locale) { + updateUser() + } + + function onCurrentUserNameChanged(name) { + updateUser() + } + } + + Component.onCompleted: { + updateUser() + } + + onActiveFocusChanged: { + if (activeFocus) passwordField.forceActiveFocus() + } +} diff --git a/src/plugins/lockscreen/qml/UserList.qml b/src/plugins/lockscreen/qml/UserList.qml new file mode 100644 index 0000000000..d5c5f305fb --- /dev/null +++ b/src/plugins/lockscreen/qml/UserList.qml @@ -0,0 +1,265 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +import QtQuick +import QtQuick.Layouts +import Treeland +import LockScreen +import org.deepin.dtk 1.0 as D +import QtQuick.Controls + +Popup { + id: users + + property var count: UserModel.count + property var userItemHeight: 44 + property var maxListHeight: userItemHeight * 5 + property var lastCheckedIndex: -1 + + signal otherUserRequested() + + objectName: "LoginScreenUserListPopup" + focus: true + padding: 6 + modal: false + width: 232 + height: Math.min(maxListHeight, listv.contentHeight) + topPadding + bottomPadding + + function selectCurrentUser(userName, index) { + UserModel.currentUserName = userName + users.lastCheckedIndex = index + userList.close() + } + + onAboutToShow: { + //FIXME: we shouldn't use index directly + if (users.lastCheckedIndex == -1) { + users.lastCheckedIndex = UserModel.lastIndex + } + listv.currentIndex = users.lastCheckedIndex + listv.positionViewAtIndex(listv.currentIndex, ListView.Beginning) + } + + ListView { + id: listv + anchors.fill: parent + model: UserModel + width: parent.width + focus: true + clip: true + keyNavigationWraps: true + highlightMoveDuration: 0 + Keys.onTabPressed: listv.incrementCurrentIndex() + Keys.onReturnPressed: selectCurrentUser(model.name, model.index) + + ScrollBar.vertical: ScrollBar { + id: scrollBar + // Let the bar extend beyond the clipped list into the popup padding. + parent: users.contentItem + policy: ScrollBar.AlwaysOn + + anchors { + top: listv.top + bottom: listv.bottom + right: parent.right + rightMargin: 2 - users.rightPadding - scrollBar.rightPadding + } + } + + property D.Palette highlightColor: D.Palette { + normal: D.DTK.makeColor(D.Color.Highlight) + } + + delegate: CheckDelegate { + id: singleUser + height: 44 + width: 220 + padding: 4 + focus: true + + onHoveredChanged: { + if (hovered) { + listv.currentIndex = index + } + } + + contentItem: RowLayout { + Control { + Layout.preferredHeight: 36 + Layout.preferredWidth: 36 + Layout.alignment: Qt.AlignVCenter + background: Item { + D.QtIcon { + id: source + anchors.fill: parent + fallbackSource: model.icon + visible: false + } + Rectangle { + id: maskSource + radius: 2 + anchors.fill: source + visible: false + } + D.OpacityMask { + anchors.fill: source + source: source + maskSource: maskSource + invert: false + } + Rectangle { + radius: 2 + anchors.fill: source + color: "transparent" + border { + width: 1 + color: Qt.rgba(0, 0, 0, 0.2) + } + } + } + + Item { + width: 8 + height: 8 + anchors { + right: parent.right + bottom: parent.bottom + } + visible: model.loggedIn + + Rectangle { + anchors.centerIn: parent + color: Qt.rgba(0, 1, 2 / 250, 1) + height: 7 + width: 7 + radius: 4 + border { + width: 1 + color: Qt.rgba(1, 1, 1, 0.8) + } + z: 1 + + D.BoxShadow { + anchors.fill: parent + shadowBlur: 4 + shadowColor: Qt.rgba(0, 180 / 255, + 38 / 255, 0.21) + shadowOffsetX: 0 + shadowOffsetY: 2 + cornerRadius: parent.radius + hollow: true + } + } + + Rectangle { + anchors.centerIn: parent + color: "transparent" + height: 6 + width: 6 + radius: 4 + border { + width: 1 + color: Qt.rgba(0, 0, 0, 0.05) + } + z: 2 + + D.BoxShadow { + anchors.fill: parent + shadowBlur: 3 + shadowColor: Qt.rgba(0, 0, 0, 0.2) + shadowOffsetX: 0 + shadowOffsetY: 0 + cornerRadius: parent.radius + } + } + } + } + + Column { + Layout.fillWidth: true + Layout.preferredHeight: 36 + Layout.alignment: Qt.AlignVCenter + Text { + id: displayUserName + text: model.realName.length === 0 ? model.name : model.realName + color: singleUser.ListView.isCurrentItem ? "white" : "black" + font: D.DTK.fontManager.t8 + } + Text { + text: model.identity + color: singleUser.ListView.isCurrentItem ? Qt.rgba(1, 1, 1,0.7) + : Qt.rgba(0, 0, 0, 0.6) + font: D.DTK.fontManager.t10 + } + } + } + + background: Rectangle { + id: userBackground + anchors.fill: parent + radius: 6 + color: singleUser.ListView.isCurrentItem ? listv.D.ColorSelector.highlightColor : "transparent" + + D.BoxShadow { + anchors.fill: parent + shadowBlur: 0 + shadowColor: Qt.rgba(17 / 255, 47 / 255, 251 / 255, 0.5) + shadowOffsetX: 0 + shadowOffsetY: -1 + cornerRadius: parent.radius + hollow: true + } + } + + onClicked: selectCurrentUser(model.name, index) + + checked: UserModel.currentUserName === model.name + } + + footer: CheckDelegate { + id: otherUserItem + height: WaylandServer.globalConfig.showOtherUserOption ? 44 : 0 + width: 220 + padding: 4 + focus: true + indicator: null + visible: WaylandServer.globalConfig.showOtherUserOption + + contentItem: RowLayout { + Control { + Layout.preferredHeight: 36 + Layout.preferredWidth: 36 + Layout.alignment: Qt.AlignVCenter + background: Item { + D.DciIcon { + anchors.fill: parent + name: "login_user" + sourceSize { width: 36; height: 36 } + } + } + } + + Column { + Layout.fillWidth: true + Layout.preferredHeight: 36 + Layout.alignment: Qt.AlignVCenter + Text { + text: qsTr("Other…") + color: otherUserItem.ListView.isCurrentItem ? "white" : "black" + font: D.DTK.fontManager.t8 + } + } + } + + background: Rectangle { + anchors.fill: parent + radius: 6 + color: otherUserItem.hovered ? Qt.rgba(0.2, 0.2, 0.2, 0.12) : "transparent" + } + + onClicked: { + users.close() + users.otherUserRequested() + } + } + } +} diff --git a/src/plugins/lockscreen/translations/lockscreen.ar.ts b/src/plugins/lockscreen/translations/lockscreen.ar.ts new file mode 100644 index 0000000000..775221a8b9 --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.ar.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + طاقة + + + + HintLabel + + + Password Hint + تلميح كلمة المرور + + + + PowerList + + + Hibernate + إسبات + + + + Suspend + تعليق + + + + Reboot + إعادة تشغيل + + + + Shut Down + إيقاف التشغيل + + + + ShutdownView + + + lock + قفل + + + + switch user + تبديل المستخدم + + + + Logout + تسجيل الخروج + + + + UserInput + + + Please enter password + الرجاء إدخال كلمة المرور + + + + Password + كلمة المرور + + + + Username + اسم المستخدم + + + + Enter username + أدخل اسم المستخدم + + + + User not found. + المستخدم غير موجود. + + + + Password is incorrect. + كلمة المرور غير صحيحة. + + + + UserList + + + Other… + أخرى… + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.ca.ts b/src/plugins/lockscreen/translations/lockscreen.ca.ts new file mode 100644 index 0000000000..cd47bfd00c --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.ca.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + Energia + + + + HintLabel + + + Password Hint + Suggeriment de contrasenya + + + + PowerList + + + Hibernate + Hiberna + + + + Suspend + Suspèn + + + + Reboot + Reinicia + + + + Shut Down + Atura + + + + ShutdownView + + + lock + bloca + + + + switch user + canvia d'usuari + + + + Logout + Surt + + + + UserInput + + + Please enter password + Introduïu la contrasenya + + + + Password + Contrasenya + + + + Username + Nom d'usuari + + + + Enter username + Escriviu el nom de l'usuari. + + + + User not found. + No s'ha trobat l'usuari. + + + + Password is incorrect. + La contrasenya és incorrecta. + + + + UserList + + + Other… + Altres... + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.en_US.ts b/src/plugins/lockscreen/translations/lockscreen.en_US.ts new file mode 100644 index 0000000000..2407e9cdf9 --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.en_US.ts @@ -0,0 +1,102 @@ + + + + + ControlAction + + + Power + Power + + + + HintLabel + + + Password Hint + Password Hint + + + + PowerList + + + Hibernate + Hibernate + + + + Suspend + Suspend + + + + Reboot + Reboot + + + + Shut Down + Shut Down + + + + ShutdownView + + + lock + + + + + switch user + + + + + Logout + + + + + UserInput + + + Please enter password + Please enter password + + + + Password + + + + + Username + + + + + Enter username + + + + + User not found. + + + + + Password is incorrect. + Password is incorrect. + + + + UserList + + + Other… + + + + diff --git a/src/plugins/lockscreen/translations/lockscreen.es.ts b/src/plugins/lockscreen/translations/lockscreen.es.ts new file mode 100644 index 0000000000..af2b3e39a7 --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.es.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + Encender + + + + HintLabel + + + Password Hint + Pista de contraseña + + + + PowerList + + + Hibernate + Hibernar + + + + Suspend + Suspender + + + + Reboot + Reiniciar + + + + Shut Down + Apagar + + + + ShutdownView + + + lock + Bloquear + + + + switch user + Cambiar usuario + + + + Logout + Cerrar sesión + + + + UserInput + + + Please enter password + Ingrese la contraseña + + + + Password + Contraseña + + + + Username + Nombre de usuario + + + + Enter username + Introduzca el nombre de usuario + + + + User not found. + Usuario no encontrado. + + + + Password is incorrect. + La contraseña es incorrecta. + + + + UserList + + + Other… + Otro… + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.fi.ts b/src/plugins/lockscreen/translations/lockscreen.fi.ts new file mode 100644 index 0000000000..12ede8e97b --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.fi.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + Virta + + + + HintLabel + + + Password Hint + Salasanavihje + + + + PowerList + + + Hibernate + Horrostila + + + + Suspend + Lepotila + + + + Reboot + Käynnistä + + + + Shut Down + Sammuta + + + + ShutdownView + + + lock + Lukitse + + + + switch user + Vaihda käyttäjää + + + + Logout + Kirjaudu ulos + + + + UserInput + + + Please enter password + Anna salasana + + + + Password + Salasana + + + + Username + Käyttäjätunnus + + + + Enter username + Anna käyttäjätunnus + + + + User not found. + Käyttäjää ei löytynyt. + + + + Password is incorrect. + Salasana on väärä. + + + + UserList + + + Other… + Muu… + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.fr.ts b/src/plugins/lockscreen/translations/lockscreen.fr.ts new file mode 100644 index 0000000000..83b7114473 --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.fr.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + Énergie + + + + HintLabel + + + Password Hint + Indice de mot de passe + + + + PowerList + + + Hibernate + Hibernation + + + + Suspend + Suspendre + + + + Reboot + Redémarrer + + + + Shut Down + Éteindre + + + + ShutdownView + + + lock + verrouiller + + + + switch user + changer d'utilisateur + + + + Logout + Déconnexion + + + + UserInput + + + Please enter password + Veuillez saisir votre mot de passe + + + + Password + Mot de passe + + + + Username + + + + + Enter username + + + + + User not found. + + + + + Password is incorrect. + Mot de passe incorrect. + + + + UserList + + + Other… + + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.gl_ES.ts b/src/plugins/lockscreen/translations/lockscreen.gl_ES.ts new file mode 100644 index 0000000000..da6e39fe35 --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.gl_ES.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + + + + + HintLabel + + + Password Hint + Suxestión de contrasinal + + + + PowerList + + + Hibernate + Hibernar + + + + Suspend + Suspender + + + + Reboot + Reiniciar + + + + Shut Down + Apagar + + + + ShutdownView + + + lock + bloquear + + + + switch user + cambiar usuario + + + + Logout + Pechar sesión + + + + UserInput + + + Please enter password + Introduza o contrasinal + + + + Password + Contrasinal + + + + Username + + + + + Enter username + + + + + User not found. + + + + + Password is incorrect. + O contrasinal non é válido + + + + UserList + + + Other… + + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.ja.ts b/src/plugins/lockscreen/translations/lockscreen.ja.ts new file mode 100644 index 0000000000..de3a57ec06 --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.ja.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + 電源 + + + + HintLabel + + + Password Hint + パスワードのヒント + + + + PowerList + + + Hibernate + ハイバネート + + + + Suspend + サスペンド + + + + Reboot + 再起動 + + + + Shut Down + シャットダウン + + + + ShutdownView + + + lock + ロック + + + + switch user + ユーザーの切替 + + + + Logout + ログアウト + + + + UserInput + + + Please enter password + パスワードを入力してください + + + + Password + パスワード + + + + Username + + + + + Enter username + + + + + User not found. + + + + + Password is incorrect. + パスワードが違います + + + + UserList + + + Other… + + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.mn.ts b/src/plugins/lockscreen/translations/lockscreen.mn.ts new file mode 100644 index 0000000000..45225cdf81 --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.mn.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + Цахилгаан + + + + HintLabel + + + Password Hint + Password Hint + + + + PowerList + + + Hibernate + Hibernate + + + + Suspend + Suspend + + + + Reboot + Reboot + + + + Shut Down + Shut Down + + + + ShutdownView + + + lock + түгжих + + + + switch user + хэрэглэгч сэлэх + + + + Logout + Гарах + + + + UserInput + + + Please enter password + Please enter password + + + + Password + Нууц үг + + + + Username + Хэрэглэгчийн нэр + + + + Enter username + Хэрэглэгчийн нэр оруулах + + + + User not found. + Хэрэглэгч олдсонгүй. + + + + Password is incorrect. + Нууц үг буруу байна. + + + + UserList + + + Other… + Бусад… + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.pl.ts b/src/plugins/lockscreen/translations/lockscreen.pl.ts new file mode 100644 index 0000000000..78e0f27830 --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.pl.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + Zasilanie + + + + HintLabel + + + Password Hint + Wskazówka hasła + + + + PowerList + + + Hibernate + Hibernacja + + + + Suspend + Wstrzymaj + + + + Reboot + Uruchom ponownie + + + + Shut Down + Zamknij + + + + ShutdownView + + + lock + Zablokuj + + + + switch user + Zmień użytkownika + + + + Logout + Wyloguj + + + + UserInput + + + Please enter password + Wprowadź hasło + + + + Password + Hasło + + + + Username + Nazwa użytkownika + + + + Enter username + Wprowadź nazwę użytkownika + + + + User not found. + Nie znaleziono użytkownika. + + + + Password is incorrect. + Błędne hasło. + + + + UserList + + + Other… + Inny… + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.pt.ts b/src/plugins/lockscreen/translations/lockscreen.pt.ts new file mode 100644 index 0000000000..dbc4aef787 --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.pt.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + Energia + + + + HintLabel + + + Password Hint + Dica da Palavra-passe + + + + PowerList + + + Hibernate + Hibernar + + + + Suspend + Suspender + + + + Reboot + Reiniciar + + + + Shut Down + Encerrar + + + + ShutdownView + + + lock + trancar + + + + switch user + trocar utilizador + + + + Logout + Sair da sessão + + + + UserInput + + + Please enter password + Por favor digite a palavra-passe + + + + Password + Palavra-passe + + + + Username + Nome de utilizador + + + + Enter username + Digite o nome de utilizador + + + + User not found. + Utilizador não encontrado. + + + + Password is incorrect. + A palavra-passe está incorreta. + + + + UserList + + + Other… + Outro... + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.pt_BR.ts b/src/plugins/lockscreen/translations/lockscreen.pt_BR.ts new file mode 100644 index 0000000000..e635ec39fa --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.pt_BR.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + Energia + + + + HintLabel + + + Password Hint + Dica de senha + + + + PowerList + + + Hibernate + Hibernar + + + + Suspend + Suspender + + + + Reboot + Reiniciar + + + + Shut Down + Desligar + + + + ShutdownView + + + lock + Bloquear + + + + switch user + Trocar de usuário + + + + Logout + Sair + + + + UserInput + + + Please enter password + Por favor, digite a senha + + + + Password + Senha + + + + Username + Nome de usuário + + + + Enter username + Digite o nome de usuário + + + + User not found. + Usuário não encontrado. + + + + Password is incorrect. + A senha está incorreta. + + + + UserList + + + Other… + Outro… + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.ru.ts b/src/plugins/lockscreen/translations/lockscreen.ru.ts new file mode 100644 index 0000000000..533cb130d7 --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.ru.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + Питание + + + + HintLabel + + + Password Hint + Подсказка к паролю + + + + PowerList + + + Hibernate + Спящий режим + + + + Suspend + Приостановить + + + + Reboot + Перезагрузить + + + + Shut Down + Выключить + + + + ShutdownView + + + lock + заблокировать + + + + switch user + сменить пользователя + + + + Logout + Выйти + + + + UserInput + + + Please enter password + Пожалуйста, введите пароль + + + + Password + Пароль + + + + Username + Имя пользователя + + + + Enter username + Введите имя пользователя + + + + User not found. + Пользователь не найден. + + + + Password is incorrect. + Неверный пароль. + + + + UserList + + + Other… + Прочее… + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.sq.ts b/src/plugins/lockscreen/translations/lockscreen.sq.ts new file mode 100644 index 0000000000..5cdc2ae255 --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.sq.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + Energji + + + + HintLabel + + + Password Hint + Ndihmëz Fjalëkalimi + + + + PowerList + + + Hibernate + Dimëroje + + + + Suspend + Pezulloje + + + + Reboot + Rinise + + + + Shut Down + Fike + + + + ShutdownView + + + lock + kyçe + + + + switch user + ndërroni përdorues + + + + Logout + Dalje + + + + UserInput + + + Please enter password + Ju lutemi, jepni fjalëkalim + + + + Password + Fjalëkalim + + + + Username + Emër përdoruesi + + + + Enter username + Jepni emër përdoruesi + + + + User not found. + Përdoruesi s’u gjet. + + + + Password is incorrect. + Fjalëkalimi është i pasaktë. + + + + UserList + + + Other… + Tjetër… + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.tr.ts b/src/plugins/lockscreen/translations/lockscreen.tr.ts new file mode 100644 index 0000000000..5f05f7627a --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.tr.ts @@ -0,0 +1,102 @@ + + + + + ControlAction + + + Power + + + + + HintLabel + + + Password Hint + + + + + PowerList + + + Hibernate + + + + + Suspend + + + + + Reboot + + + + + Shut Down + + + + + ShutdownView + + + lock + + + + + switch user + + + + + Logout + + + + + UserInput + + + Please enter password + + + + + Password + + + + + Username + + + + + Enter username + + + + + User not found. + + + + + Password is incorrect. + + + + + UserList + + + Other… + + + + diff --git a/src/plugins/lockscreen/translations/lockscreen.uk.ts b/src/plugins/lockscreen/translations/lockscreen.uk.ts new file mode 100644 index 0000000000..f6289cef7c --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.uk.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + Живлення + + + + HintLabel + + + Password Hint + Підказка щодо пароля + + + + PowerList + + + Hibernate + Приспати + + + + Suspend + Призупинити + + + + Reboot + Перезавантажити + + + + Shut Down + Вимкнути + + + + ShutdownView + + + lock + Заблокувати + + + + switch user + Перемкнути користувача + + + + Logout + Вийти + + + + UserInput + + + Please enter password + Будь ласка, введіть пароль + + + + Password + Пароль + + + + Username + + + + + Enter username + + + + + User not found. + + + + + Password is incorrect. + Неправильний пароль. + + + + UserList + + + Other… + + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.zh_CN.ts b/src/plugins/lockscreen/translations/lockscreen.zh_CN.ts new file mode 100644 index 0000000000..48c1cd2277 --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.zh_CN.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + 电源 + + + + HintLabel + + + Password Hint + 密码提示 + + + + PowerList + + + Hibernate + 休眠 + + + + Suspend + 待机 + + + + Reboot + 重启 + + + + Shut Down + 关机 + + + + ShutdownView + + + lock + 锁定 + + + + switch user + 切换帐户 + + + + Logout + 注销 + + + + UserInput + + + Please enter password + 请输入密码 + + + + Password + 密码 + + + + Username + + + + + Enter username + + + + + User not found. + + + + + Password is incorrect. + 密码错误 + + + + UserList + + + Other… + + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.zh_HK.ts b/src/plugins/lockscreen/translations/lockscreen.zh_HK.ts new file mode 100644 index 0000000000..4aac6dfeee --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.zh_HK.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + 電源 + + + + HintLabel + + + Password Hint + 密碼提示 + + + + PowerList + + + Hibernate + 休眠 + + + + Suspend + 待機 + + + + Reboot + 重啓 + + + + Shut Down + 關機 + + + + ShutdownView + + + lock + 鎖定 + + + + switch user + 切換帳户 + + + + Logout + 註銷 + + + + UserInput + + + Please enter password + 請輸入密碼 + + + + Password + 密碼 + + + + Username + + + + + Enter username + + + + + User not found. + + + + + Password is incorrect. + 密碼錯誤 + + + + UserList + + + Other… + + + + \ No newline at end of file diff --git a/src/plugins/lockscreen/translations/lockscreen.zh_TW.ts b/src/plugins/lockscreen/translations/lockscreen.zh_TW.ts new file mode 100644 index 0000000000..182c95beaa --- /dev/null +++ b/src/plugins/lockscreen/translations/lockscreen.zh_TW.ts @@ -0,0 +1,100 @@ + + + ControlAction + + + Power + 電源 + + + + HintLabel + + + Password Hint + 密碼提示 + + + + PowerList + + + Hibernate + 休眠 + + + + Suspend + 待機 + + + + Reboot + 重啟 + + + + Shut Down + 關機 + + + + ShutdownView + + + lock + 鎖定 + + + + switch user + 切換帳戶 + + + + Logout + 登出 + + + + UserInput + + + Please enter password + 請輸入密碼 + + + + Password + 密碼 + + + + Username + + + + + Enter username + + + + + User not found. + + + + + Password is incorrect. + 密碼錯誤 + + + + UserList + + + Other… + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/CMakeLists.txt b/src/plugins/multitaskview/CMakeLists.txt new file mode 100644 index 0000000000..1cec48b64f --- /dev/null +++ b/src/plugins/multitaskview/CMakeLists.txt @@ -0,0 +1,54 @@ +find_package(QT NAMES Qt6 COMPONENTS Core Quick Concurrent REQUIRED) + +# Include translation utilities +include(${CMAKE_SOURCE_DIR}/cmake/TranslationUtils.cmake) + +qt_add_library(multitaskview SHARED + multitaskviewplugin.h + multitaskviewplugin.cpp +) + +qt_add_qml_module(multitaskview + URI MultitaskView + SOURCES + multitaskview.h + multitaskview.cpp + QML_FILES + qml/MultitaskviewProxy.qml + qml/WindowHighlight.qml + qml/WindowSelectionGrid.qml + qml/WorkspaceSelectionList.qml + RESOURCE_PREFIX + /qt/qml + OUTPUT_DIRECTORY + ${PROJECT_BINARY_DIR}/qt/qml/Treeland/Plugins/MultitaskView +) + +target_link_libraries(multitaskview PRIVATE + Qt6::Core + Qt6::Quick + Qt6::Concurrent + libtreeland +) + +target_include_directories(multitaskview PUBLIC + $ + $ + $ +) + +set_target_properties(multitaskview PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${TREELAND_PLUGINS_OUTPUT_PATH}" +) + +qt_add_resources(multitaskview "multitaskview_assets" + PREFIX "/dsg/icons" + BASE ${PROJECT_RESOURCES_DIR}/icons + FILES + ${PROJECT_RESOURCES_DIR}/icons/multitaskview_close.dci +) + +# Use translation utilities to setup translations +setup_translations(multitaskview multitaskview) + +install(TARGETS multitaskview DESTINATION ${TREELAND_PLUGINS_INSTALL_PATH}) diff --git a/src/plugins/multitaskview/metadata.json b/src/plugins/multitaskview/metadata.json new file mode 100644 index 0000000000..58f8a86d12 --- /dev/null +++ b/src/plugins/multitaskview/metadata.json @@ -0,0 +1,3 @@ +{ + "translate": "multitaskview" +} \ No newline at end of file diff --git a/src/plugins/multitaskview/multitaskview.cpp b/src/plugins/multitaskview/multitaskview.cpp new file mode 100644 index 0000000000..30d001c96c --- /dev/null +++ b/src/plugins/multitaskview/multitaskview.cpp @@ -0,0 +1,906 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "multitaskview.h" +#include "desktop/desktopenvironment.h" + +#include "common/treelandlogging.h" +#include "output/output.h" +#include "core/waylandserver.h" +#include "surface/surfacecontainer.h" +#include "treelanduserconfig.hpp" +#include "workspace/workspace.h" + +#include +#include + +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +Multitaskview::Multitaskview(QQuickItem *parent) + : QQuickItem(parent) + , m_status(Uninitialized) + , m_activeReason(ShortcutKey) +{ +} + +DesktopEnvironment *Multitaskview::desktop() const +{ + return m_desktop; +} + +void Multitaskview::setDesktop(DesktopEnvironment *desktop) +{ + if (m_desktop == desktop) + return; + Q_ASSERT(!m_desktop && desktop); + m_desktop = desktop; + Q_EMIT desktopChanged(); +} + +void Multitaskview::setStatus(IMultitaskView::Status status) +{ + setStatus(static_cast(status)); +} + +void Multitaskview::toggleMultitaskView(IMultitaskView::ActiveReason reason) +{ + if (m_status == Uninitialized || m_status == Initialized) { + enter(static_cast(reason)); + if (reason == IMultitaskView::ShortcutKey) + updatePartialFactor(1.0); + return; + } + const bool exiting = reason == IMultitaskView::Gesture + ? m_status == Exited : m_status != Exited; + if (exiting) + exit(); + else + enter(static_cast(reason)); + updatePartialFactor(exiting ? 0.0 : 1.0); +} + +void Multitaskview::immediatelyExit() +{ + exit(nullptr, true, false); +} + +Multitaskview::Status Multitaskview::status() const +{ + return m_status; +} + +void Multitaskview::setStatus(Status status) +{ + if (status != m_status) + m_status = status; + Q_EMIT actionFinished(); +} + +Multitaskview::ActiveReason Multitaskview::activeReason() const +{ + return m_activeReason; +} + +void Multitaskview::setActiveReason(ActiveReason activeReason) +{ + if (activeReason == m_activeReason) + return; + m_activeReason = activeReason; + Q_EMIT activeReasonChanged(); +} + +qreal Multitaskview::partialFactor() const +{ + return m_partialFactor; +} + +void Multitaskview::updatePartialFactor(qreal progress) +{ + qreal newPartialFactor = qBound(0.0, progress, 1.0); + if (qFuzzyCompare(newPartialFactor, m_partialFactor)) + return; + m_partialFactor = newPartialFactor; + Q_EMIT partialFactorChanged(); +} + +void Multitaskview::exit(SurfaceWrapper *surface, bool immediately, bool restoreFocus) +{ + // Stop tracking keyboard focus before handing it back to a client surface, + // otherwise forceActivateSurface() would re-enter exit() recursively. + if (auto *w = window()) { + disconnect(w, + &QQuickWindow::activeFocusItemChanged, + this, + &Multitaskview::onActiveFocusItemChanged); + } + + const bool ownsInput = m_desktop && WaylandServer::instance()->desktop() == m_desktop; + if (ownsInput) + WaylandServer::instance()->setBlockActivateSurface(false); + + if (restoreFocus && ownsInput) { + if (!surface) + surface = m_desktop->workspace()->current()->latestActiveSurface(); + if (surface) + m_desktop->activateWindow(surface); + } + + if (ownsInput && WaylandServer::instance()->currentMode() == WaylandServer::CurrentMode::Multitaskview) { + WaylandServer::instance()->setCurrentMode(WaylandServer::CurrentMode::Normal); + } + // TODO: handle taskview gesture + Q_EMIT aboutToExit(); + + if (immediately) { + setVisible(false); + } else { + setStatus(Exited); + } +} + +void Multitaskview::enter(ActiveReason reason) +{ + if (!m_desktop || WaylandServer::instance()->desktop() != m_desktop) + return; + WaylandServer::instance()->cancelShowDesktop(); + WaylandServer::instance()->activateSurface(nullptr); + if (reason == ActiveReason::ShortcutKey) + WaylandServer::instance()->setCurrentMode(WaylandServer::CurrentMode::Multitaskview); + setActiveReason(reason); + setStatus(Active); + + // Auto-exit when keyboard focus moves outside the view, including when + // a client surface is activated. + if (auto *w = window()) { + connect(w, + &QQuickWindow::activeFocusItemChanged, + this, + &Multitaskview::onActiveFocusItemChanged, + Qt::UniqueConnection); + } +} + +void Multitaskview::onActiveFocusItemChanged() +{ + if (m_status != Active || !isVisible()) + return; + + auto *w = window(); + auto *item = w ? w->activeFocusItem() : nullptr; + // Ignore transient null focus and focus changes within the view. + if (!item || item == this || isAncestorOf(item)) + return; + + qCDebug(lcTlPlugin) << "Multitask view lost keyboard focus to" << item + << "- exiting the multitask view"; + exit(nullptr, /*immediately=*/false, /*restoreFocus=*/false); +} + +void Multitaskview::commitGesture(bool triggered) +{ + if (!m_desktop || WaylandServer::instance()->desktop() != m_desktop) + return; + if (m_gestureCommitted == triggered) + return; + m_gestureCommitted = triggered; + if (triggered) { + WaylandServer::instance()->setCurrentMode(WaylandServer::CurrentMode::Multitaskview); + } else if (WaylandServer::instance()->currentMode() == WaylandServer::CurrentMode::Multitaskview) { + WaylandServer::instance()->setCurrentMode(WaylandServer::CurrentMode::Normal); + } +} +MultitaskviewSurfaceModel::MultitaskviewSurfaceModel(QObject *parent) + : QAbstractListModel(parent) +{ +} + +void MultitaskviewSurfaceModel::initializeModel() +{ + if (!workspace() || !output() || m_layoutArea.isEmpty()) + return; + beginResetModel(); + m_data.clear(); + QList surfaces(workspace()->surfaces()); + surfaces << workspace()->workspaceManager()->showOnAllWorkspaceModel()->surfaces(); + for (const auto &surface : std::as_const(surfaces)) { + if (surface->skipMutiTaskView()) + continue; + if (surface->ownsOutput() == output()) { + if (surfaceReady(surface)) { + m_data.push_back(std::make_shared( + surface, + surfaceGeometry(surface) + .translated(-output()->geometry().topLeft()) + .translated(-layoutArea().topLeft()), + false, + surface->isMinimized())); + if (auto wsurface = surface->surface()) { + connect(wsurface, + &WSurface::mappedChanged, + this, + &MultitaskviewSurfaceModel::handleSurfaceMappedChanged, + Qt::UniqueConnection); + } + } else { + monitorUnreadySurface(surface); + } + } + connect(surface, + &SurfaceWrapper::ownsOutputChanged, + this, + &MultitaskviewSurfaceModel::handleWrapperOutputChanged, + Qt::UniqueConnection); + connect(surface, + &SurfaceWrapper::minimizedChanged, + this, + &MultitaskviewSurfaceModel::handleMinimizedChanged, + Qt::UniqueConnection); + } + std::sort(m_data.begin(), + m_data.end(), + [this](const ModelDataPtr &lhs, const ModelDataPtr &rhs) -> bool { + return laterActiveThan(lhs->wrapper, rhs->wrapper); + }); + doUpdateZOrder(m_data); + endResetModel(); + m_modelReady = true; + Q_EMIT countChanged(); + Q_EMIT modelReadyChanged(); +} + +int MultitaskviewSurfaceModel::rowCount([[maybe_unused]] const QModelIndex &parent) const +{ + return m_data.count(); +} + +QVariant MultitaskviewSurfaceModel::data(const QModelIndex &index, int role) const +{ + auto r = index.row(); + if (r < 0 || r >= rowCount(index.parent())) + return QVariant(); + switch (role) { + case SurfaceWrapperRole: + return QVariant::fromValue(m_data[r]->wrapper); + case GeometryRole: + return QVariant::fromValue(m_data[r]->geometry); + case PaddingRole: + return QVariant::fromValue(m_data[r]->padding); + case ZOrderRole: + return QVariant::fromValue(m_data[r]->zorder); + case MinimizedRole: + return QVariant::fromValue(m_data[r]->minimized); + case UpIndexRole: + return QVariant::fromValue(m_data[r]->upIndex); + case DownIndexRole: + return QVariant::fromValue(m_data[r]->downIndex); + case LeftIndexRole: + return QVariant::fromValue(m_data[r]->leftIndex); + case RightIndexRole: + return QVariant::fromValue(m_data[r]->rightIndex); + default: + return QVariant(); + } +} + +QHash MultitaskviewSurfaceModel::roleNames() const +{ + return QHash{ + { SurfaceWrapperRole, "wrapper" }, { GeometryRole, "geometry" }, + { PaddingRole, "padding" }, { ZOrderRole, "zorder" }, + { MinimizedRole, "minimized" }, { UpIndexRole, "upIndex" }, + { DownIndexRole, "downIndex" }, { LeftIndexRole, "leftIndex" }, + { RightIndexRole, "rightIndex" } + }; +} + +QModelIndex MultitaskviewSurfaceModel::index(int row, int column, [[maybe_unused]] const QModelIndex &parent) const +{ + if (row < 0 || row >= m_data.size()) + return QModelIndex(); + return QAbstractItemModel::createIndex(row, column, &m_data[row]); +} + +bool MultitaskviewSurfaceModel::modelReady() const +{ + return m_modelReady; +} + +void MultitaskviewSurfaceModel::calcLayout() +{ + doCalculateLayout(m_data); + auto [beginIndex, endIndex] = commitAndGetUpdateRange(m_data); + if (beginIndex <= endIndex) { + Q_EMIT dataChanged(index(beginIndex), + index(endIndex), + { GeometryRole, + PaddingRole, + UpIndexRole, + DownIndexRole, + LeftIndexRole, + RightIndexRole }); + } + Q_EMIT rowsChanged(); + Q_EMIT contentHeightChanged(); +} + +void MultitaskviewSurfaceModel::updateZOrder() +{ + doUpdateZOrder(m_data); + Q_EMIT dataChanged(index(0), index(rowCount() - 1), { ZOrderRole }); +} + +uint MultitaskviewSurfaceModel::prevSameAppIndex(uint index) +{ + if (index >= count()) { + qCWarning(lcTlPlugin) << "prevSameAppIndex: invalid index" << index << "count:" << count(); + return index; + } + auto circularPrev = [this](uint i) { + return (i + count() - 1) % count(); + }; + auto i = circularPrev(index); + for (; i != index; i = circularPrev(i)) { + if (m_data[i]->wrapper->appId() + == m_data[index]->wrapper->appId()) { + break; + } + } + return i; +} + +uint MultitaskviewSurfaceModel::nextSameAppIndex(uint index) +{ + if (index >= count()) { + qCWarning(lcTlPlugin) << "nextSameAppIndex: invalid index" << index << "count:" << count(); + return index; + } + auto circularNext = [this](uint i) { + return (i + 1) % count(); + }; + auto i = circularNext(index); + for (; i != index; i = circularNext(i)) { + if (m_data[i]->wrapper->appId() + == m_data[index]->wrapper->appId()) { + break; + } + } + return i; +} + +QRectF MultitaskviewSurfaceModel::layoutArea() const +{ + return m_layoutArea; +} + +void MultitaskviewSurfaceModel::setLayoutArea(const QRectF &newLayoutArea) +{ + if (m_layoutArea == newLayoutArea) + return; + m_layoutArea = newLayoutArea; + if (!m_modelReady) + initializeModel(); + else if (output() && !m_layoutArea.isEmpty()) + calcLayout(); + Q_EMIT layoutAreaChanged(); +} + +bool MultitaskviewSurfaceModel::tryLayout(const QList &rawData, + qreal rowH, + bool ignoreOverlap) +{ + int nrows = 1; + qreal acc = 0; + auto devicePixelRatio = output()->outputItem()->devicePixelRatio(); + auto topContentMargin = + workspace()->workspaceManager()->config()->multitaskviewTopContentMargin() / devicePixelRatio; + auto bottomContentMargin = + workspace()->workspaceManager()->config()->multitaskviewBottomContentMargin() / devicePixelRatio; + auto cellPadding = workspace()->workspaceManager()->config()->multitaskviewCellPadding() / devicePixelRatio; + auto horizontalMargin = + workspace()->workspaceManager()->config()->multitaskviewHorizontalMargin() / devicePixelRatio; + auto availWidth = std::max(0.0, layoutArea().width() - 2 * horizontalMargin); + auto availHeight = + std::max(0.0, layoutArea().height() - topContentMargin - bottomContentMargin); + if (availWidth <= 0) + return false; + QList> rowstmp; + QList currow; + for (auto &modelData : rawData) { + auto surface = modelData->wrapper; + auto whRatio = surface->width() / surface->height(); + modelData->pendingPadding = surface->height() < (rowH - 2 * cellPadding); + auto curW = std::min(availWidth, + whRatio * std::min(rowH - 2 * cellPadding, surface->height()) + + 2 * cellPadding); + modelData->pendingGeometry.setWidth(curW - 2 * cellPadding); + auto newAcc = acc + curW; + if (newAcc <= availWidth) { + acc = newAcc; + currow.append(modelData); + } else if (newAcc / availWidth > workspace()->workspaceManager()->config()->multitaskviewLoadFactor()) { + acc = curW; + nrows++; + rowstmp.append(currow); + currow = { modelData }; + } else { + // Just scale the last element + curW = availWidth - acc; + modelData->pendingGeometry.setWidth(curW - 2 * cellPadding); + currow.append(modelData); + acc = newAcc; + } + } + if (nrows * rowH <= availHeight || ignoreOverlap) { + if (currow.length()) { + rowstmp.append(currow); + } + m_rowHeight = rowH; + m_rows = rowstmp; + return true; + } + return false; +} + +void MultitaskviewSurfaceModel::calcDisplayPos(const QList &rawData) +{ + auto devicePixelRatio = output()->outputItem()->devicePixelRatio(); + auto topContentMargin = + workspace()->workspaceManager()->config()->multitaskviewTopContentMargin() / devicePixelRatio; + auto bottomContentMargin = + workspace()->workspaceManager()->config()->multitaskviewBottomContentMargin() / devicePixelRatio; + auto cellPadding = workspace()->workspaceManager()->config()->multitaskviewCellPadding() / devicePixelRatio; + auto horizontalMargin = + workspace()->workspaceManager()->config()->multitaskviewHorizontalMargin() / devicePixelRatio; + auto availWidth = std::max(0.0, layoutArea().width() - 2 * horizontalMargin); + auto availHeight = + std::max(0.0, layoutArea().height() - topContentMargin - bottomContentMargin); + auto contentHeight = m_rows.length() * m_rowHeight; + auto curY = std::max(availHeight - contentHeight, 0.0) / 2 + topContentMargin; + const auto hCenter = availWidth / 2; + for (auto i = 0; i < m_rows.size(); ++i) { + auto row = m_rows[i]; + const auto totW = QtConcurrent::blockingMappedReduced( + row, + [cellPadding](ModelDataPtr data) { + return data->pendingGeometry.width() + 2 * cellPadding; + }, + [](qreal &acc, const qreal &cur) { + acc += cur; + }); + auto curX = hCenter - totW / 2 + cellPadding + horizontalMargin; + for (auto j = 0; j < row.size(); ++j) { + auto window = row[j]; + window->pendingGeometry.moveLeft(curX); + window->pendingGeometry.moveTop(curY); + window->pendingGeometry.setHeight(m_rowHeight - 2 * cellPadding); + window->pendingLeftIndex = rawData.indexOf(row[(j - 1 + row.size()) % row.size()]); + window->pendingRightIndex = rawData.indexOf(row[(j + 1) % row.size()]); + auto lastRow = m_rows[std::max(0, i - 1)]; + auto lastRowIndex = std::min(static_cast(lastRow.size()) - 1, j); + window->pendingUpIndex = rawData.indexOf(lastRow[lastRowIndex]); + auto nextRow = m_rows[std::min(static_cast(m_rows.size()) - 1, i + 1)]; + auto nextRowIndex = std::min(static_cast(nextRow.size()) - 1, j); + window->pendingDownIndex = rawData.indexOf(nextRow[nextRowIndex]); + curX += window->pendingGeometry.width() + 2 * cellPadding; + } + curY += m_rowHeight; + } + m_contentHeight = curY; +} + +void MultitaskviewSurfaceModel::doCalculateLayout(const QList &rawData) +{ + auto devicePixelRatio = output()->outputItem()->devicePixelRatio(); + auto maxWindowHeight = + std::min(layoutArea().height(), + static_cast(workspace()->workspaceManager()->config()->normalWindowHeight() / devicePixelRatio)); + auto minWindowHeight = workspace()->workspaceManager()->config()->minMultitaskviewSurfaceHeight() / devicePixelRatio; + auto windowHeightStep = workspace()->workspaceManager()->config()->windowHeightStep() / devicePixelRatio; + auto rowH = maxWindowHeight; + while (rowH > minWindowHeight) { + if (tryLayout(rawData, rowH)) { + break; + } + rowH -= windowHeightStep; + } + if (rowH <= minWindowHeight) { + tryLayout(rawData, minWindowHeight, true); + } + calcDisplayPos(rawData); +} + +void MultitaskviewSurfaceModel::doUpdateZOrder(const QList &rawData) +{ + auto surfaces = WOutputRenderWindow::paintOrderItemList( + workspace()->workspaceManager(), + [this](QQuickItem *item) -> bool { + auto surfaceWrapper = qobject_cast(item); + if (surfaceWrapper && surfaceWrapper->showOnWorkspace(workspace()->id())) { + return true; + } else { + return false; + } + }); + std::for_each(rawData.begin(), rawData.end(), [surfaces](ModelDataPtr modelData) { + modelData->zorder = surfaces.indexOf(modelData->wrapper); + }); +} + +std::pair MultitaskviewSurfaceModel::commitAndGetUpdateRange( + [[maybe_unused]] const QList &rawData) +{ + // TODO: better algorithm + int beginIndex = 0, endIndex = -1; + bool unchanged = true; + for (int i = 0; i < m_data.size(); ++i) { + if (m_data[i]->padding != m_data[i]->pendingPadding + || m_data[i]->geometry != m_data[i]->pendingGeometry + || m_data[i]->upIndex != m_data[i]->pendingUpIndex + || m_data[i]->downIndex != m_data[i]->pendingDownIndex + || m_data[i]->leftIndex != m_data[i]->pendingLeftIndex + || m_data[i]->rightIndex != m_data[i]->pendingRightIndex) { + endIndex = i; + unchanged = false; + } else { + if (unchanged) { + beginIndex = i + 1; + } + } + m_data[i]->commit(); + } + return { beginIndex, endIndex }; +} + +void MultitaskviewSurfaceModel::handleWrapperGeometryChanged() +{ + auto wrapper = qobject_cast(sender()); + Q_ASSERT(wrapper); + if (surfaceReady(wrapper)) { + addReadySurface(wrapper); + } +} + +void MultitaskviewSurfaceModel::handleWrapperOutputChanged() +{ + auto wrapper = qobject_cast(sender()); + Q_ASSERT(wrapper); + if (wrapper->ownsOutput() == output()) { + if (surfaceReady(wrapper)) { + addReadySurface(wrapper); + } else { + monitorUnreadySurface(wrapper); + } + } +} + +void MultitaskviewSurfaceModel::handleMinimizedChanged() +{ + auto surface = qobject_cast(sender()); + Q_ASSERT(surface); + auto dataPtr = + std::find_if(m_data.begin(), m_data.end(), [surface](const ModelDataPtr &modelData) { + return modelData->wrapper == surface; + }); + if (dataPtr == m_data.end()) + return; + if (surface->isMinimized() != (*dataPtr)->minimized) { + (*dataPtr)->minimized = surface->isMinimized(); + int i = std::distance(m_data.begin(), dataPtr); + Q_EMIT dataChanged(index(i), index(i), { MinimizedRole }); + } +} + +void MultitaskviewSurfaceModel::handleSurfaceMappedChanged() +{ + auto surface = qobject_cast(sender()); + if (!surface) { + qCWarning(lcTlPlugin) << "handleSurfaceMappedChanged: sender is not a WSurface"; + return; + } + + auto findWrapper = [surface](const QList &surfaces) -> SurfaceWrapper * { + auto it = std::ranges::find(surfaces, surface, [](SurfaceWrapper *wrapper) { + return wrapper->surface(); + }); + return it != surfaces.end() ? *it : nullptr; + }; + + SurfaceWrapper *wrapper = findWrapper(workspace()->surfaces()); + if (!wrapper) { + wrapper = + findWrapper(workspace()->workspaceManager()->showOnAllWorkspaceModel()->surfaces()); + } + Q_ASSERT_X(wrapper, __func__, "Monitoring mapped of a removed surface wrapper."); + + if (surface->mapped()) { + if (surfaceReady(wrapper)) { + addReadySurface(wrapper); + } + } else { // unmapped + removeReadySurface(wrapper); + if (wrapper->ownsOutput() == output()) { + monitorUnreadySurface(wrapper); + } + } +} + +void MultitaskviewSurfaceModel::handleSurfaceAdded(SurfaceWrapper *surface) +{ + if (surface->skipMutiTaskView()) + return; + connect(surface, + &SurfaceWrapper::ownsOutputChanged, + this, + &MultitaskviewSurfaceModel::handleWrapperOutputChanged, + Qt::UniqueConnection); + connect(surface, + &SurfaceWrapper::minimizedChanged, + this, + &MultitaskviewSurfaceModel::handleMinimizedChanged, + Qt::UniqueConnection); + if (surface->ownsOutput() == output()) { + if (surfaceReady(surface)) { + addReadySurface(surface); + } else { + monitorUnreadySurface(surface); + } + } +} + +void MultitaskviewSurfaceModel::handleSurfaceRemoved(SurfaceWrapper *surface) +{ + disconnectSurface(surface); + + removeReadySurface(surface); +} + +void MultitaskviewSurfaceModel::addReadySurface(SurfaceWrapper *surface) +{ + Q_ASSERT_X(surfaceReady(surface), + __func__, + "Surface wrapper should be ready before adding to multitaskview model."); + auto existingIt = + std::find_if(m_data.begin(), m_data.end(), [surface](const ModelDataPtr &modelData) { + return modelData->wrapper == surface; + }); + if (existingIt != m_data.end()) + return; + + disconnect(surface, + &SurfaceWrapper::normalGeometryChanged, + this, + &MultitaskviewSurfaceModel::handleWrapperGeometryChanged); + disconnect(surface, + &SurfaceWrapper::geometryChanged, + this, + &MultitaskviewSurfaceModel::handleWrapperGeometryChanged); + if (auto wsurface = surface->surface()) { + connect(wsurface, + &WSurface::mappedChanged, + this, + &MultitaskviewSurfaceModel::handleSurfaceMappedChanged, + Qt::UniqueConnection); + } + auto toBeInserted = + std::make_shared(surface, + surfaceGeometry(surface) + .translated(-output()->geometry().topLeft()) + .translated(-layoutArea().topLeft()), + false, + surface->isMinimized()); + QList pendingData{ m_data }; + auto it = pendingData.begin(); + for (; it != pendingData.end() && laterActiveThan((*it)->wrapper, surface); ++it) + ; + auto insertedIt = pendingData.insert(it, toBeInserted); + int insertedIndex = std::distance(pendingData.begin(), insertedIt); + Q_ASSERT(insertedIndex >= 0 && insertedIndex < pendingData.size()); + doCalculateLayout(pendingData); + auto [beginIndex, endIndex] = commitAndGetUpdateRange(m_data); + if (beginIndex <= endIndex) { + Q_ASSERT(beginIndex < m_data.size()); + Q_EMIT dataChanged(index(beginIndex), + index(endIndex), + { GeometryRole, + PaddingRole, + UpIndexRole, + DownIndexRole, + LeftIndexRole, + RightIndexRole }); + } + toBeInserted->commit(); + beginInsertRows({}, insertedIndex, insertedIndex); + m_data = pendingData; + pendingData.clear(); + endInsertRows(); + Q_EMIT rowsChanged(); + Q_EMIT countChanged(); + Q_EMIT contentHeightChanged(); +} + +bool MultitaskviewSurfaceModel::removeReadySurface(SurfaceWrapper *surface) +{ + auto toBeRemovedIt = + std::find_if(m_data.begin(), m_data.end(), [surface](ModelDataPtr modelData) { + return modelData->wrapper == surface; + }); + if (toBeRemovedIt == m_data.end()) + return false; + int toRemove = std::distance(m_data.begin(), toBeRemovedIt); + beginRemoveRows({}, toRemove, toRemove); + m_data.remove(toRemove); + endRemoveRows(); + doCalculateLayout(m_data); + auto [beginIndex, endIndex] = commitAndGetUpdateRange(m_data); + if (beginIndex <= endIndex) { + Q_ASSERT(beginIndex < m_data.size()); + Q_EMIT dataChanged(index(beginIndex), + index(endIndex), + { GeometryRole, + PaddingRole, + UpIndexRole, + DownIndexRole, + LeftIndexRole, + RightIndexRole }); + } + Q_EMIT rowsChanged(); + Q_EMIT countChanged(); + Q_EMIT contentHeightChanged(); + return true; +} + +void MultitaskviewSurfaceModel::monitorUnreadySurface(SurfaceWrapper *surface) +{ + Q_ASSERT_X(!surfaceReady(surface), __func__, "Surface is ready."); + connect(surface, + &SurfaceWrapper::normalGeometryChanged, + this, + &MultitaskviewSurfaceModel::handleWrapperGeometryChanged, + Qt::UniqueConnection); + connect(surface, + &SurfaceWrapper::geometryChanged, + this, + &MultitaskviewSurfaceModel::handleWrapperGeometryChanged, + Qt::UniqueConnection); + connect(surface->surface(), + &WSurface::mappedChanged, + this, + &MultitaskviewSurfaceModel::handleSurfaceMappedChanged, + Qt::UniqueConnection); +} + +void MultitaskviewSurfaceModel::disconnectSurface(SurfaceWrapper *surface) +{ + disconnect(surface, + &SurfaceWrapper::ownsOutputChanged, + this, + &MultitaskviewSurfaceModel::handleWrapperOutputChanged); + disconnect(surface, + &SurfaceWrapper::minimizedChanged, + this, + &MultitaskviewSurfaceModel::handleMinimizedChanged); + disconnect(surface, + &SurfaceWrapper::normalGeometryChanged, + this, + &MultitaskviewSurfaceModel::handleWrapperGeometryChanged); + disconnect(surface, + &SurfaceWrapper::geometryChanged, + this, + &MultitaskviewSurfaceModel::handleWrapperGeometryChanged); + + if (auto wsurface = surface->surface()) { + disconnect(wsurface, + &WSurface::mappedChanged, + this, + &MultitaskviewSurfaceModel::handleSurfaceMappedChanged); + } +} + +bool MultitaskviewSurfaceModel::surfaceReady(SurfaceWrapper *surface) +{ + if (surface->type() != SurfaceWrapper::Type::SplashScreen) { + auto surf = surface->surface(); + if (!surf || !surf->mapped()) { + return false; + } + } + return surfaceGeometry(surface).isValid(); +} + +QRectF MultitaskviewSurfaceModel::surfaceGeometry(SurfaceWrapper *surface) +{ + if (surface->isMinimized()) { + return surface->normalGeometry(); + } else { + return surface->geometry(); + } +} + +bool MultitaskviewSurfaceModel::laterActiveThan(SurfaceWrapper *a, SurfaceWrapper *b) +{ + return workspace()->laterActiveThan(a, b); +} + +void MultitaskviewSurfaceModel::connectWorkspace(WorkspaceModel *workspace) +{ + connect(workspace, + &WorkspaceModel::surfaceAdded, + this, + &MultitaskviewSurfaceModel::handleSurfaceAdded); + connect(workspace, + &WorkspaceModel::surfaceRemoved, + this, + &MultitaskviewSurfaceModel::handleSurfaceRemoved); +} + +void MultitaskviewSurfaceModel::disconnectWorkspace(WorkspaceModel *workspace) +{ + disconnect(workspace, + &WorkspaceModel::surfaceAdded, + this, + &MultitaskviewSurfaceModel::handleSurfaceAdded); + disconnect(workspace, + &WorkspaceModel::surfaceRemoved, + this, + &MultitaskviewSurfaceModel::handleSurfaceRemoved); +} + +uint MultitaskviewSurfaceModel::rows() const +{ + return m_rows.count(); +} + +WorkspaceModel *MultitaskviewSurfaceModel::workspace() const +{ + return m_workspace; +} + +void MultitaskviewSurfaceModel::setWorkspace(WorkspaceModel *newWorkspace) +{ + if (m_workspace == newWorkspace) + return; + if (m_workspace) { + disconnectWorkspace(m_workspace); + disconnectWorkspace(m_workspace->workspaceManager()->showOnAllWorkspaceModel()); + const auto surfaces = m_workspace->surfaces() + + m_workspace->workspaceManager()->showOnAllWorkspaceModel()->surfaces(); + for (auto *surface : surfaces) + disconnectSurface(surface); + } + m_workspace = newWorkspace; + if (m_workspace) { + connectWorkspace(m_workspace); + connectWorkspace(m_workspace->workspaceManager()->showOnAllWorkspaceModel()); + } + initializeModel(); + Q_EMIT workspaceChanged(); +} + +qreal MultitaskviewSurfaceModel::contentHeight() const +{ + return m_contentHeight; +} + +Output *MultitaskviewSurfaceModel::output() const +{ + return m_output; +} + +void MultitaskviewSurfaceModel::setOutput(Output *newOutput) +{ + if (m_output == newOutput) + return; + m_output = newOutput; + initializeModel(); + Q_EMIT outputChanged(); +} + +uint MultitaskviewSurfaceModel::count() const +{ + return rowCount(); +} diff --git a/src/plugins/multitaskview/multitaskview.h b/src/plugins/multitaskview/multitaskview.h new file mode 100644 index 0000000000..4d3c1d8c6c --- /dev/null +++ b/src/plugins/multitaskview/multitaskview.h @@ -0,0 +1,225 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "interfaces/multitaskviewinterface.h" + +#include +#include +#include +Q_MOC_INCLUDE("surface/surfacecontainer.h") +Q_MOC_INCLUDE("workspace/workspacemodel.h") +Q_MOC_INCLUDE("output/output.h") +class DesktopEnvironment; +Q_MOC_INCLUDE("desktop/desktopenvironment.h") +class SurfaceListModel; +class SurfaceWrapper; +class WorkspaceModel; +class Output; + +class Multitaskview : public QQuickItem, public IMultitaskView +{ + Q_OBJECT + QML_ELEMENT + Q_INTERFACES(IMultitaskView) + Q_PROPERTY(DesktopEnvironment *desktop READ desktop WRITE setDesktop NOTIFY desktopChanged REQUIRED FINAL) + Q_PROPERTY(Status status READ status NOTIFY actionFinished FINAL) + Q_PROPERTY(ActiveReason activeReason READ activeReason NOTIFY activeReasonChanged FINAL) + Q_PROPERTY(qreal partialFactor READ partialFactor NOTIFY partialFactorChanged FINAL) + +public: + enum Status + { + Uninitialized, + Initialized, + Active, + Exited + }; + Q_ENUM(Status) + + enum ActiveReason + { + ShortcutKey = IMultitaskView::ShortcutKey, + Gesture = IMultitaskView::Gesture, + }; + Q_ENUM(ActiveReason) + + enum ZOrder + { + Background = -1, + Overlay = 1, + FloatingItem = 2 + }; + Q_ENUM(ZOrder) + + Multitaskview(QQuickItem *parent = nullptr); + + DesktopEnvironment *desktop() const; + void setDesktop(DesktopEnvironment *desktop); + void setStatus(IMultitaskView::Status status) override; + void toggleMultitaskView(IMultitaskView::ActiveReason reason) override; + void immediatelyExit() override; + Status status() const; + void commitGesture(bool triggered) override; + void setStatus(Status status); + void updatePartialFactor(qreal progress) override; + ActiveReason activeReason() const; + qreal partialFactor() const override; + void setActiveReason(ActiveReason activeReason); + +Q_SIGNALS: + void desktopChanged(); + void actionFinished(); + void activeReasonChanged(); + void partialFactorChanged(); + void aboutToExit(); // Focus has been handled, waiting for exit + +public Q_SLOTS: + void exit(SurfaceWrapper *surface = nullptr, bool immediately = false, bool restoreFocus = true); + void enter(ActiveReason reason); + +private: + // Exits the multitask view when keyboard focus moves to an item that is not + // part of this view (for example another compositor overlay). + void onActiveFocusItemChanged(); + + QPointer m_desktop; + Status m_status; + ActiveReason m_activeReason; + qreal m_partialFactor{ 0.0 }; + bool m_gestureCommitted{ false }; +}; + +class MultitaskviewSurfaceModel : public QAbstractListModel +{ + Q_OBJECT + QML_ELEMENT + Q_PROPERTY(WorkspaceModel* workspace READ workspace WRITE setWorkspace NOTIFY workspaceChanged REQUIRED FINAL) + Q_PROPERTY(QRectF layoutArea READ layoutArea WRITE setLayoutArea NOTIFY layoutAreaChanged REQUIRED FINAL) + Q_PROPERTY(bool modelReady READ modelReady NOTIFY modelReadyChanged FINAL) + Q_PROPERTY(uint rows READ rows NOTIFY rowsChanged FINAL) + Q_PROPERTY(qreal contentHeight READ contentHeight NOTIFY contentHeightChanged FINAL) + Q_PROPERTY(Output *output READ output WRITE setOutput NOTIFY outputChanged FINAL) + Q_PROPERTY(uint count READ count NOTIFY countChanged FINAL) + + struct SurfaceModelData + { + SurfaceWrapper *wrapper{ nullptr }; + QRectF geometry{}; + bool padding{ false }; + bool minimized{ false }; + int upIndex{ 0 }; + int downIndex{ 0 }; + int leftIndex{ 0 }; + int rightIndex{ 0 }; + + QRectF pendingGeometry{}; + bool pendingPadding{ false }; + int zorder{ 0 }; + int pendingUpIndex; + int pendingDownIndex; + int pendingLeftIndex; + int pendingRightIndex; + + void commit() + { + geometry = pendingGeometry; + padding = pendingPadding; + upIndex = pendingUpIndex; + downIndex = pendingDownIndex; + leftIndex = pendingLeftIndex; + rightIndex = pendingRightIndex; + } + }; + + using ModelDataPtr = std::shared_ptr; + +public: + MultitaskviewSurfaceModel(QObject *parent = nullptr); + void initializeModel(); + + enum SurfaceModelRole + { + SurfaceWrapperRole = Qt::UserRole + 1, + GeometryRole, + PaddingRole, + ZOrderRole, + MinimizedRole, + UpIndexRole, + DownIndexRole, + LeftIndexRole, + RightIndexRole + }; + Q_ENUM(SurfaceModelRole) + + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + QVariant data(const QModelIndex &index, int role) const override; + QHash roleNames() const override; + QModelIndex index(int row, + int column = 0, + const QModelIndex &parent = QModelIndex()) const override; + bool modelReady() const; + + Q_INVOKABLE void calcLayout(); + Q_INVOKABLE void updateZOrder(); + Q_INVOKABLE uint prevSameAppIndex(uint index); + Q_INVOKABLE uint nextSameAppIndex(uint index); + + QRectF layoutArea() const; + void setLayoutArea(const QRectF &newLayoutArea); + + uint rows() const; + void setRows(uint newRows); + + WorkspaceModel *workspace() const; + void setWorkspace(WorkspaceModel *newWorkspace); + + qreal contentHeight() const; + + Output *output() const; + void setOutput(Output *newOutput); + + uint count() const; + +Q_SIGNALS: + void surfaceListModelChanged(); + void layoutAreaChanged(); + void modelReadyChanged(); + void rowsChanged(); + void workspaceChanged(); + void contentHeightChanged(); + void outputChanged(); + void countChanged(); + +private: + bool tryLayout(const QList &rawData, qreal rowH, bool ignoreOverlap = false); + void calcDisplayPos(const QList &rawData); + void doCalculateLayout(const QList &rawData); + void doUpdateZOrder(const QList &rawData); + std::pair commitAndGetUpdateRange(const QList &rawData); + void handleWrapperGeometryChanged(); + void handleWrapperOutputChanged(); + void handleMinimizedChanged(); + void handleSurfaceMappedChanged(); + void handleSurfaceAdded(SurfaceWrapper *surface); + void handleSurfaceRemoved(SurfaceWrapper *surface); + void addReadySurface(SurfaceWrapper *surface); + bool removeReadySurface(SurfaceWrapper *surface); + void monitorUnreadySurface(SurfaceWrapper *surface); + void disconnectSurface(SurfaceWrapper *surface); + bool surfaceReady(SurfaceWrapper *surface); + QRectF surfaceGeometry(SurfaceWrapper *surface); + bool laterActiveThan(SurfaceWrapper *a, SurfaceWrapper *b); + void connectWorkspace(WorkspaceModel *workspace); + void disconnectWorkspace(WorkspaceModel *workspace); + + QList m_data{}; + QRectF m_layoutArea{}; + QList> m_rows{}; + qreal m_rowHeight{ 0 }; + qreal m_contentHeight{ 0 }; + bool m_modelReady{ false }; + QList m_toBeInserted; + WorkspaceModel *m_workspace = nullptr; + Output *m_output = nullptr; +}; diff --git a/src/plugins/multitaskview/multitaskviewplugin.cpp b/src/plugins/multitaskview/multitaskviewplugin.cpp new file mode 100644 index 0000000000..20a50760f7 --- /dev/null +++ b/src/plugins/multitaskview/multitaskviewplugin.cpp @@ -0,0 +1,33 @@ +// Copyright (C) 2024 Dingyuan Zhang . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "multitaskviewplugin.h" + +#include "core/qmlengine.h" +#include "core/rootsurfacecontainer.h" +#include "interfaces/proxyinterface.h" +#include "multitaskview.h" +#include "core/waylandserver.h" +#include "desktop/desktopenvironment.h" + +void MultitaskViewPlugin::initialize(TreelandProxyInterface *proxy) +{ + m_proxy = proxy; + + new (&m_multitaskViewComponent) + QQmlComponent(m_proxy->qmlEngine(), "MultitaskView", "MultitaskviewProxy", this); +} + +void MultitaskViewPlugin::shutdown() +{ + if (m_proxy) + WaylandServer::instance()->setMultitaskViewFactory(nullptr); + m_proxy = nullptr; +} + +QQuickItem *MultitaskViewPlugin::createMultitaskView(DesktopEnvironment *desktop) +{ + return m_proxy->qmlEngine()->createComponent( + m_multitaskViewComponent, desktop->viewRoot(), + {{"desktop", QVariant::fromValue(desktop)}}); +} diff --git a/src/plugins/multitaskview/multitaskviewplugin.h b/src/plugins/multitaskview/multitaskviewplugin.h new file mode 100644 index 0000000000..2bf5b37535 --- /dev/null +++ b/src/plugins/multitaskview/multitaskviewplugin.h @@ -0,0 +1,45 @@ +// Copyright (C) 2024 Dingyuan Zhang . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "multitaskview.h" +#include "interfaces/multitaskviewinterface.h" +#include "interfaces/plugininterface.h" + +#include +#include + +class MultitaskViewPlugin + : public QObject + , public PluginInterface + , public IMultitaskViewFactory +{ + Q_OBJECT + Q_PLUGIN_METADATA(IID "org.deepin.treeland.plugin.multitaskview/1.0" FILE "metadata.json") + Q_INTERFACES(PluginInterface IMultitaskViewFactory) +public: + QString name() const override + { + return QStringLiteral("MultitaskView"); + } + + QString description() const override + { + return QStringLiteral("MultitaskView plugin"); + } + + void initialize(TreelandProxyInterface *proxy) override; + void shutdown() override; + + bool enabled() const override + { + return true; + } + + QQuickItem *createMultitaskView(DesktopEnvironment *desktop) override; + +private: + TreelandProxyInterface *m_proxy = nullptr; + QQmlComponent m_multitaskViewComponent; +}; diff --git a/src/plugins/multitaskview/qml/MultitaskviewProxy.qml b/src/plugins/multitaskview/qml/MultitaskviewProxy.qml new file mode 100644 index 0000000000..015b3290e4 --- /dev/null +++ b/src/plugins/multitaskview/qml/MultitaskviewProxy.qml @@ -0,0 +1,277 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Controls +import QtQuick.Effects +import Waylib.Server +import Treeland +import MultitaskView +import org.deepin.dtk as D +import org.deepin.dtk.style as DS + +Multitaskview { + id: root + + property D.Palette outerShadowColor: DS.Style.highlightPanel.dropShadow + clip: true + width: root.desktop.workspace.width + height: root.desktop.workspace.height + + property bool initialized: false + property bool exited: false + property real taskviewVal: 0 + property bool inProgress: false + + readonly property bool enableAnimation: WaylandServer.animationConfig.multitaskview + + onActionFinished: { + if (root.status === Multitaskview.Exited) { + exited = true + if (!root.enableAnimation) { + taskviewVal = 0 + root.visible = false + } + } else { + exited = false + } + + if (root.activeReason === Multitaskview.Gesture) { + inProgress = false + } + } + + onPartialFactorChanged: inProgress = true + + states: [ + State { + name: "initial" + PropertyChanges { + target: root + taskviewVal: 0 + } + }, + State { + name: "partial" + PropertyChanges { + target: root + taskviewVal: root.partialFactor + } + }, + State { + name: "taskview" + PropertyChanges { + target: root + taskviewVal: 1 + } + } + ] + state: { + if (!initialized || exited) return "initial"; + + if (root.inProgress) return "partial"; + + if (taskviewVal >= 0.5) return "taskview"; + + return "initial"; + } + + transitions: [ + Transition { + to: "initial" + enabled: root.enableAnimation + SequentialAnimation { + NumberAnimation { + duration: root.desktop.config.multitaskviewAnimationDuration + property: "taskviewVal" + easing.type: root.desktop.config.multitaskviewEasingCurveType + } + ScriptAction { + script: root.visible = false; + } + } + }, + Transition { + to: "taskview" + enabled: root.enableAnimation + SequentialAnimation { + NumberAnimation { + duration: root.desktop.config.multitaskviewAnimationDuration + property: "taskviewVal" + easing.type: root.desktop.config.multitaskviewEasingCurveType + } + } + } + ] + + QtObject { + id: multitaskviewDragManager + property Item item // current dragged item + property var accept // accept callback func + property point destPoint + property bool doNotRestoreAccept: false + } + + MouseArea { + anchors.fill: parent + acceptedButtons: Qt.AllButtons + hoverEnabled: true + preventStealing: true + onClicked: { + root.exit() + } + } + + Rectangle { + id: multitaskviewBlackMask + anchors.fill: parent + color: "black" + z: Multitaskview.Background + } + + Repeater { + model: WaylandServer.rootSurfaceContainer.outputModel + Item { + id: outputPlacementItem + required property int index + required property QtObject output + x: output.outputItem.x + y: output.outputItem.y + width: output.outputItem.width + height: output.outputItem.height + + Wallpaper { + id: wallpaper + output: outputPlacementItem.output.outputItem.output + workspace: root.desktop.workspace.current + } + + ShaderEffectSource { + z: Multitaskview.Background + sourceItem: wallpaper + recursive: true + live: true + smooth: true + anchors.fill: parent + hideSource: visible + } + + Blur { + z: Multitaskview.Background + anchors.fill: parent + opacity: root.taskviewVal + radiusEnabled: false + } + + Item { + id: validRectItem + x: output.validRect.x + y: output.validRect.y + z: Multitaskview.Overlay + width: output.validRect.width + height: output.validRect.height + WorkspaceSelectionList { + id: workspaceSelectionList + output: outputPlacementItem.output + dragManager: multitaskviewDragManager + multitaskview: root + } + + Repeater { + id: wsDelegates + model: root.desktop.workspace.models + WindowSelectionGrid { + id: windowSelectionGrid + exited: root.exited + partialGestureFactor: root.taskviewVal + inProgress: !Number.isInteger(taskviewVal) + width: parent.width + height: parent.height + visible: workspace.visible + multitaskview: root + output: outputPlacementItem.output + draggedParent: root + workspaceListPadding: (root.desktop.config.workspaceThumbHeight + 2 * root.desktop.config.workspaceThumbMargin) / output.outputItem.devicePixelRatio + dragManager: multitaskviewDragManager + } + } + } + + Connections { + target: root.desktop.workspace.animationController + function onRunningChanged() { + if (root.desktop.workspace.animationController.running) + workspaceAnimation.active = true + } + } + + Loader { + id: workspaceAnimation + active: false + readonly property real localFactor: outputPlacementItem.width / root.desktop.workspace.animationController.refWidth + anchors.fill: parent + sourceComponent: Item { + id: animationDelegate + clip: true + visible: root.desktop.workspace.animationController.running + onVisibleChanged: { + if (!visible) + workspaceAnimation.active = false + } + Rectangle { + anchors.fill: parent + color: "black" + } + z: Multitaskview.Background + Row { + spacing: root.desktop.workspace.animationController.refGap * workspaceAnimation.localFactor + x: -root.desktop.workspace.animationController.viewportPos * workspaceAnimation.localFactor + Repeater { + model: root.desktop.workspace.models + Item { + required property int index + width: outputPlacementItem.output.outputItem.width + height: outputPlacementItem.output.outputItem.height + Wallpaper { + id: wallpaper2 + output: outputPlacementItem.output.outputItem.output + workspace: root.desktop.workspace.modelAt(index) + } + + ShaderEffectSource { + z: Multitaskview.Background + sourceItem: wallpaper2 + recursive: true + live: true + smooth: true + anchors.fill: parent + hideSource: visible + } + + Blur { + z: Multitaskview.Background + anchors.fill: parent + opacity: root.taskviewVal + radiusEnabled: false + } + + ShaderEffectSource { + x: outputPlacementItem.output.validRect.x + y: outputPlacementItem.output.validRect.y + width: outputPlacementItem.output.validRect.width + height: outputPlacementItem.output.validRect.height + hideSource: visible + sourceItem: wsDelegates.itemAt(index) ?? null + } + } + } + } + } + } + } + } + + Component.onCompleted: { + initialized = true + } +} diff --git a/src/plugins/multitaskview/qml/WindowHighlight.qml b/src/plugins/multitaskview/qml/WindowHighlight.qml new file mode 100644 index 0000000000..8726c6515c --- /dev/null +++ b/src/plugins/multitaskview/qml/WindowHighlight.qml @@ -0,0 +1,18 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +import QtQuick + +Rectangle { + id: root + + required property real frameRadius + required property bool padded + required property real paddingRadius + + // The proxy already rounds CSD windows itself, so only the padding card can win here. + readonly property real contourRadius: root.padded ? root.paddingRadius : root.frameRadius + + color: "transparent" + border.color: "blue" + radius: root.contourRadius > 0 ? root.contourRadius + root.border.width : 0 +} diff --git a/src/plugins/multitaskview/qml/WindowSelectionGrid.qml b/src/plugins/multitaskview/qml/WindowSelectionGrid.qml new file mode 100644 index 0000000000..4a259df6a5 --- /dev/null +++ b/src/plugins/multitaskview/qml/WindowSelectionGrid.qml @@ -0,0 +1,523 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Treeland +import MultitaskView +import Waylib.Server +import QtQuick.Effects +import QtQuick.Controls +import org.deepin.dtk as D +import org.deepin.dtk.style as DS + +Item { + id: root + readonly property bool enableAnimation: multitaskview.enableAnimation + required property QtObject output + required property WorkspaceModel workspace + required property int workspaceListPadding + required property Item draggedParent + required property QtObject dragManager + required property Multitaskview multitaskview + required property bool exited + required property real partialGestureFactor + required property bool inProgress + + readonly property real delegateCornerRadius: (ros.rows >= 1 && ros.rows <= 3) ? ros.cornerRadiusList[ros.rows - 1] : ros.cornerRadiusList[2] + + property int loadedWindowCount: 0 + property bool loaderFinished: windowLoader.status === Loader.Ready + focus: true + onVisibleChanged: { + if (visible) + forceActiveFocus() + } + + QtObject { + id: ros // readonly state + property list cornerRadiusList: [18,12,8] // Should get from system preference + readonly property int rows: surfaceModel.rows + } + + MultitaskviewSurfaceModel { + id: surfaceModel + workspace: root.workspace + output: root.output + layoutArea: root.mapToItem(output.outputItem, Qt.rect(surfaceGridView.x, surfaceGridView.y, surfaceGridView.width, surfaceGridView.height)) + } + + Connections { + target: multitaskview + function onAboutToExit() { + surfaceModel.updateZOrder() + } + } + + Flickable { + id: surfaceGridView + // Do not use anchors here, geometry should be stable as soon as the item is created + y: workspaceListPadding + contentHeight: Math.max(height, surfaceModel.contentHeight) + width: parent.width + height: parent.height - workspaceListPadding + states: [ + State { + name: "initial" + PropertyChanges { + surfaceGridView { + clip: false + } + } + }, + State { + name: "partial" + PropertyChanges { + surfaceGridView { + clip: false + } + } + }, + State { + name: "taskview" + PropertyChanges { + surfaceGridView { + clip: true + } + } + } + ] + transitions: [ + Transition { + to: "taskview" + enabled: root.enableAnimation + SequentialAnimation { + PauseAnimation { duration: root.multitaskview.desktop.config.multitaskviewAnimationDuration } + PropertyAction { target: surfaceGridView; property: "clip" } + } + } + ] + state: { + if (exited || status === Multitaskview.Uninitialized) + return "initial"; + + if (root.inProgress) return "partial"; + + if (root.partialGestureFactor > 0.5) return "taskview"; + + return "initial"; + } + visible: surfaceModel.modelReady + + Loader { + id: windowLoader + sourceComponent: Repeater { + id: surfaceRepeater + model: surfaceModel + Item { + id: surfaceItemDelegate + readonly property bool enableAnimation: state !== "dragging" && state !== "partial" && root.enableAnimation + + required property int index + required property SurfaceWrapper wrapper + required property rect geometry + required property bool padding + required property int zorder + required property bool minimized + required property int upIndex + required property int downIndex + required property int leftIndex + required property int rightIndex + + property bool needPadding + property real paddingOpacity + readonly property rect initialGeometry: surfaceGridView.mapFromItem(multitaskview, wrapper.geometry) + property real ratio: wrapper.width / wrapper.height + property real fullY + + focus: true + visible: multitaskview.status == Multitaskview.Exited ? !minimized : true + clip: false + state: { + drg.active ? "dragging" : surfaceGridView.state + } + x: geometry.x + y: geometry.y + z: zorder + width: geometry.width + height: geometry.height + states: [ + State { + name: "initial" + PropertyChanges { + surfaceItemDelegate { + x: initialGeometry.x + y: initialGeometry.y + width: initialGeometry.width + height: initialGeometry.height + scale: 1.0 + paddingOpacity: 0 + needPadding: false + } + } + }, + State { + name: "partial" + PropertyChanges { + surfaceItemDelegate { + x: (geometry.x - initialGeometry.x) * multitaskview.taskviewVal + initialGeometry.x + y: (geometry.y - initialGeometry.y) * multitaskview.taskviewVal + initialGeometry.y + width: (geometry.width - initialGeometry.width) * multitaskview.taskviewVal + initialGeometry.width + height: (geometry.height - initialGeometry.height) * multitaskview.taskviewVal + initialGeometry.height + scale: 1.0 + paddingOpacity: root.multitaskview.desktop.config.multitaskviewPaddingOpacity * multitaskview.taskviewVal + needPadding: true + } + } + }, + State { + name: "taskview" + PropertyChanges { + surfaceItemDelegate { + x: geometry.x + y: geometry.y + width: geometry.width + height: geometry.height + needPadding: padding + scale: 1.0 + paddingOpacity: root.multitaskview.desktop.config.multitaskviewPaddingOpacity + } + } + }, + State { + name: "dragging" + PropertyChanges { + // restoreEntryValues: true // FIXME: does this restore propery binding? + surfaceItemDelegate { + parent: draggedParent + x: mapToItem(draggedParent, 0, 0).x + y: mapToItem(draggedParent, 0, 0).y + z: Multitaskview.FloatingItem + scale: (Math.max(0, Math.min(drg.activeTranslation.y / fullY, 1)) * (100 - width) + width) / width + paddingOpacity: root.multitaskview.desktop.config.multitaskviewPaddingOpacity + transformOrigin: Item.Center + needPadding: false + } + } + } + ] + + Behavior on x {enabled:surfaceItemDelegate.enableAnimation; XAnimator {duration: root.multitaskview.desktop.config.multitaskviewAnimationDuration; easing.type: root.multitaskview.desktop.config.multitaskviewEasingCurveType} } + Behavior on y {enabled:surfaceItemDelegate.enableAnimation; YAnimator {duration: root.multitaskview.desktop.config.multitaskviewAnimationDuration; easing.type: root.multitaskview.desktop.config.multitaskviewEasingCurveType} } + Behavior on width {enabled:surfaceItemDelegate.enableAnimation; NumberAnimation {duration: root.multitaskview.desktop.config.multitaskviewAnimationDuration; easing.type: root.multitaskview.desktop.config.multitaskviewEasingCurveType} } + Behavior on height {enabled:surfaceItemDelegate.enableAnimation; NumberAnimation {duration: root.multitaskview.desktop.config.multitaskviewAnimationDuration; easing.type: root.multitaskview.desktop.config.multitaskviewEasingCurveType} } + Behavior on paddingOpacity {enabled:surfaceItemDelegate.enableAnimation; NumberAnimation {duration: root.multitaskview.desktop.config.multitaskviewAnimationDuration; easing.type: root.multitaskview.desktop.config.multitaskviewEasingCurveType} } + Behavior on scale {enabled:surfaceItemDelegate.enableAnimation; ScaleAnimator {duration: root.multitaskview.desktop.config.multitaskviewAnimationDuration; easing.type: root.multitaskview.desktop.config.multitaskviewEasingCurveType} } + + D.BoxShadow { + id: paddingRectShadow + anchors.fill: paddingRect + visible: needPadding + cornerRadius: delegateCornerRadius + shadowColor: Qt.rgba(0, 0, 0, 0.3) + shadowOffsetY: 16 + shadowBlur: 32 + hollow: true + } + + Rectangle { + id: paddingRect + visible: needPadding + radius: delegateCornerRadius + anchors.fill: parent + color: "white" + opacity: paddingOpacity + } + + WindowHighlight { + frameRadius: surfaceProxy.effectiveRadius + padded: surfaceItemDelegate.needPadding + paddingRadius: paddingRect.radius + border.width: root.multitaskview.desktop.config.highlightBorderWidth + visible: highlighted + anchors.margins: -root.multitaskview.desktop.config.highlightBorderWidth + anchors.fill: parent + } + + function conv(y, item = parent) { // convert to draggedParent's coord + return mapToItem(draggedParent, mapFromItem(item, 0, y)).y + } + + property bool hovered: hvhdlr.hovered || surfaceCloseBtn.hovered + // During animation/exit, hover is driven by geometry changes; + // skip focus handling to avoid interfering with normal focus restoration. + onHoveredChanged: { + if (root.exited || root.inProgress) + return; + if (hovered) { + surfaceItemDelegate.forceActiveFocus() + } else { + root.forceActiveFocus() + } + } + + property bool highlighted: dragManager.item === null && activeFocus && surfaceItemDelegate.state === "taskview" + SurfaceProxy { + id: surfaceProxy + surface: surfaceItemDelegate.wrapper + live: true + fullProxy: true + width: parent.width + height: width / surfaceItemDelegate.ratio + anchors.centerIn: parent + } + HoverHandler { + id: hvhdlr + enabled: !drg.active // Disable during drag to avoid conflict with hover + blocking: true + } + TapHandler { + gesturePolicy: TapHandler.WithinBounds + onTapped: { + surfaceModel.updateZOrder() + multitaskview.exit(wrapper) + } + } + DragHandler { + id: drg + onActiveChanged: { + if (active) { + dragManager.item = surfaceItemDelegate + } else { + dragManager.doNotRestoreAccept = false + if (dragManager.accept) { + dragManager.accept() + } + dragManager.item = null + } + } + onGrabChanged: (transition, eventPoint) => { + switch (transition) { + case PointerDevice.GrabExclusive: + fullY = conv(workspaceListPadding, root) - conv(mapToItem(surfaceItemDelegate, eventPoint.position).y, surfaceItemDelegate) + break + } + } + } + RoundButton { + id: surfaceCloseBtn + icon.name: "multitaskview_close" + icon.width: 26 + icon.height: 26 + height: 26 + width: height + focusPolicy: Qt.NoFocus // Should not steal focus from delegate + visible: surfaceItemDelegate.highlighted + anchors { + top: parent.top + right: parent.right + topMargin: -8 + rightMargin: -8 + } + Item { + id: surfaceCloseBtnControl + property D.Palette textColor: DS.Style.button.text + } + palette.buttonText: surfaceCloseBtnControl.textColor + background: Rectangle { + anchors.fill: parent + color: "transparent" + } + onClicked: { + surfaceItemDelegate.visible = false + surfaceItemDelegate.wrapper.closeSurface() + } + } + Keys.onPressed: function (event) { + if (event.modifiers === Qt.NoModifier) { + if (event.key === Qt.Key_Enter || event.key === Qt.Key_Return) { + multitaskview.exit(wrapper) + } else if (event.key === Qt.Key_Delete) { + wrapper.closeSurface() + } + } else if (event.modifiers === (Qt.MetaModifier | Qt.ShiftModifier)) { + const workspaceNumKeys = [Qt.Key_1, Qt.Key_2, Qt.Key_3, Qt.Key_4, Qt.Key_5, Qt.Key_6] + const workspaceNumComposedKeys = [Qt.Key_Exclam, Qt.Key_At, Qt.Key_NumberSign, Qt.Key_Dollar, Qt.Key_Percent, Qt.Key_AsciiCircum] + if (workspaceNumKeys.includes(event.key) + || workspaceNumComposedKeys.includes(event.key)) { + let index = workspaceNumKeys.includes(event.key) ? + workspaceNumKeys.indexOf(event.key) : workspaceNumComposedKeys.indexOf(event.key) + const ws = root.multitaskview.desktop.workspace.modelAt(index) + if (ws && wrapper) + root.multitaskview.desktop.workspace.moveSurfaceTo(wrapper, ws.id) + } + } else if (event.modifiers === Qt.AltModifier + && event.key === Qt.Key_QuoteLeft && loaderFinished) { + surfaceRepeater.itemAt(surfaceModel.nextSameAppIndex(index)).forceActiveFocus() + } else if (event.modifiers === (Qt.AltModifier | Qt.ShiftModifier) + && event.key === Qt.Key_AsciiTilde && loaderFinished) { + surfaceRepeater.itemAt(surfaceModel.prevSameAppIndex(index)).forceActiveFocus() + } + } + KeyNavigation.right: (loaderFinished && loadedWindowCount > 0) ? surfaceRepeater.itemAt(rightIndex) : null + KeyNavigation.left: (loaderFinished && loadedWindowCount > 0) ? surfaceRepeater.itemAt(leftIndex) : null + KeyNavigation.up: (loaderFinished && loadedWindowCount > 0) ? surfaceRepeater.itemAt(upIndex) : null + KeyNavigation.down: (loaderFinished && loadedWindowCount > 0) ? surfaceRepeater.itemAt(downIndex) : null + KeyNavigation.tab: (loaderFinished && loadedWindowCount > 0) ? surfaceRepeater.itemAt((index + 1) % surfaceRepeater.count) : null + KeyNavigation.backtab: (loaderFinished && loadedWindowCount > 0) ? surfaceRepeater.itemAt((index + surfaceRepeater.count - 1) % surfaceRepeater.count) : null + + Control { + id: titleBox + anchors { + bottom: parent.bottom + horizontalCenter: parent.horizontalCenter + margins: 10 + } + width: Math.min(implicitContentWidth + 2 * padding, parent.width) + padding: 10 + visible: surfaceItemDelegate.state === "taskview" && wrapper.shellSurface.title !== "" + + contentItem: Text { + text: wrapper.shellSurface.title + elide: Qt.ElideRight + } + background: Item { + Rectangle { + id: bgRect + anchors.fill: parent + color: Qt.rgba(16, 16, 16, .1) + radius: root.multitaskview.desktop.config.titleBoxCornerRadius + } + Blur { + anchors.fill: bgRect + radius: root.multitaskview.desktop.config.titleBoxCornerRadius + } + Border { + anchors.fill: parent + radius: root.multitaskview.desktop.config.titleBoxCornerRadius + insideColor: Qt.rgba(255, 255, 255, 0.05) + } + } + } + } + onItemAdded: loadedWindowCount++ + onItemRemoved: loadedWindowCount-- + } + } + + Loader { + active: surfaceModel.count === 0 + anchors.centerIn: parent + sourceComponent: Control { + id: emptyWindowHint + width: 200 + height: 50 + padding: 10 + Behavior on opacity { + enabled: state !== "partial" && root.enableAnimation + OpacityAnimator { + duration: root.multitaskview.desktop.config.multitaskviewAnimationDuration + easing.type: root.multitaskview.desktop.config.multitaskviewEasingCurveType + } + } + state: multitaskview.state + states: [ + State { + name: "initial" + PropertyChanges { + emptyWindowHint { + opacity: 0 + } + } + }, + State { + name: "partial" + PropertyChanges { + emptyWindowHint { + opacity: multitaskview.taskviewVal + } + } + }, + State { + name: "taskview" + PropertyChanges { + emptyWindowHint { + opacity: 1 + } + } + } + ] + opacity: multitaskview.taskviewVal + contentItem: Text { + text: qsTr("No windows") + font.pixelSize: 20 + elide: Qt.ElideRight + anchors.fill: parent + horizontalAlignment: Qt.AlignHCenter + verticalAlignment: Qt.AlignVCenter + } + background: Item { + Rectangle { + id: hintBgRect + anchors.fill: parent + color: Qt.rgba(16, 16, 16, .1) + radius: root.multitaskview.desktop.config.titleBoxCornerRadius + } + Blur { + anchors.fill: hintBgRect + radius: root.multitaskview.desktop.config.titleBoxCornerRadius + } + D.BoxShadow { + anchors.fill: parent + visible: true + cornerRadius: root.multitaskview.desktop.config.titleBoxCornerRadius + shadowColor: Qt.rgba(0, 0, 0, 0.15) + shadowOffsetY: 8 + shadowBlur: 20 + hollow: true + } + Border { + anchors.fill: parent + radius: root.multitaskview.desktop.config.titleBoxCornerRadius + insideColor: Qt.rgba(255, 255, 255, 0.05) + } + } + } + } + + TapHandler { + acceptedButtons: Qt.LeftButton + onTapped: { + multitaskview.exit() + } + } + } + Keys.onPressed: function (event) { + if (event.modifiers === Qt.NoModifier) { + if (event.key === Qt.Key_Home) { + windowLoader.item.itemAt(0)?.forceActiveFocus() + } else if (event.key === Qt.Key_End) { + windowLoader.item.itemAt(windowLoader.item.count - 1)?.forceActiveFocus() + } else if (event.key === Qt.Key_Escape) { + multitaskview.exit() + } + } else if (event.modifiers === Qt.AltModifier) { + if (event.key === Qt.Key_Minus && root.multitaskview.desktop.workspace.count > 1) { + root.multitaskview.desktop.workspace.removeModel(root.multitaskview.desktop.workspace.currentIndex) + } else if (event.key === Qt.Key_Equal && root.multitaskview.desktop.workspace.count < root.multitaskview.desktop.config.maxWorkspace) { + root.multitaskview.desktop.workspace.createModel() + root.multitaskview.desktop.workspace.switchTo(root.multitaskview.desktop.workspace.count - 1) + } + } + } + KeyNavigation.tab: (loaderFinished && loadedWindowCount > 0) ? windowLoader.item.itemAt(0) : null + KeyNavigation.backtab: (loaderFinished && loadedWindowCount > 0) ? windowLoader.item.itemAt(loadedWindowCount - 1) : null + KeyNavigation.right: (loaderFinished && loadedWindowCount > 0) ? windowLoader.item.itemAt(0) : null + KeyNavigation.left: (loaderFinished && loadedWindowCount > 0) ? windowLoader.item.itemAt(loadedWindowCount - 1) : null + KeyNavigation.down: (loaderFinished && loadedWindowCount > 0) ? windowLoader.item.itemAt(0) : null + KeyNavigation.up: (loaderFinished && loadedWindowCount > 0) ? windowLoader.item.itemAt(loadedWindowCount - 1) : null + + Component.onCompleted: { + surfaceModel.calcLayout() + forceActiveFocus() + } +} diff --git a/src/plugins/multitaskview/qml/WorkspaceSelectionList.qml b/src/plugins/multitaskview/qml/WorkspaceSelectionList.qml new file mode 100644 index 0000000000..4f913df616 --- /dev/null +++ b/src/plugins/multitaskview/qml/WorkspaceSelectionList.qml @@ -0,0 +1,416 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Controls +import QtQuick.Shapes +import org.deepin.dtk as D +import org.deepin.dtk.style as DS +import Treeland +import MultitaskView + +Item { + id: root + + required property QtObject output + required property QtObject dragManager + required property Multitaskview multitaskview + readonly property real whRatio: output.outputItem.width / output.outputItem.height + readonly property real workspaceDelegateHeight: (root.multitaskview.desktop.config.workspaceThumbHeight + 2 * root.multitaskview.desktop.config.workspaceThumbMargin) / output.outputItem.devicePixelRatio + readonly property real workspaceThumbHeight: root.multitaskview.desktop.config.workspaceThumbHeight / output.outputItem.devicePixelRatio + readonly property real workspaceThumbMargin: root.multitaskview.desktop.config.workspaceThumbMargin / output.outputItem.devicePixelRatio + readonly property real highlightBorderWidth: root.multitaskview.desktop.config.highlightBorderWidth / output.outputItem.devicePixelRatio + readonly property real workspaceThumbCornerRadius: root.multitaskview.desktop.config.workspaceThumbCornerRadius / output.outputItem.devicePixelRatio + + + height: workspaceDelegateHeight + width: parent.width + z: Multitaskview.Overlay + transform: [ + Translate { + y: height * (multitaskview.taskviewVal - 1.0) + } + ] + + Item { + id: animationMask + property real localAnimationFactor: (workspaceThumbHeight * root.whRatio+ 2 * workspaceThumbMargin) + / root.multitaskview.desktop.workspace.animationController.refWrap + visible: root.multitaskview.desktop.workspace.animationController.running + anchors.fill: workspaceList + anchors.margins: workspaceThumbMargin - highlightBorderWidth + Rectangle { + width: workspaceThumbHeight * root.whRatio + 2 * highlightBorderWidth + height: workspaceDelegateHeight + 2 * highlightBorderWidth - 2 * workspaceThumbMargin + border.width: highlightBorderWidth + border.color: "blue" + color: "transparent" + radius: workspaceThumbCornerRadius + highlightBorderWidth + x: root.multitaskview.desktop.workspace.animationController.viewportPos * animationMask.localAnimationFactor + } + } + + Timer { + id: switchTimer + interval: 500 + property int switchToIndex: -1 + property WorkspaceModel switchToModel: null + onTriggered: { + if (dragManager.doNotRestoreAccept) { + // Substitute switch workspace + dragManager.accept = () => { + switchTimer.stop() + if (dragManager.item?.wrapper && switchTimer.switchToModel) { + root.multitaskview.desktop.workspace.moveSurfaceTo(dragManager.item.wrapper, switchTimer.switchToModel.id) + } + } + } else { + dragManager.doNotRestoreAccept = true + } + root.multitaskview.desktop.workspace.switchTo(switchTimer.switchToIndex) + } + } + + function restartSwitchTimer(index: int, workspace: WorkspaceModel) { + switchTimer.switchToIndex = index + switchTimer.switchToModel = workspace + switchTimer.restart() + } + + DelegateModel { + id: visualModel + model: root.multitaskview.desktop.workspace.models + delegate: Item { + required property WorkspaceModel workspace + required property int index + id: workspaceThumbDelegate + height: workspaceDelegateHeight + width: workspaceThumbHeight * root.whRatio + 2 * workspaceThumbMargin + Drag.active: hdrg.active + z: Drag.active ? 1 : 0 + Drag.onActiveChanged: { + if (Drag.active) { + dragManager.item = this + dragManager.destPoint = Qt.point(x, y) + } else { + if (dragManager.accept) { + dragManager.accept() + } + x = dragManager.destPoint.x + y = dragManager.destPoint.y + dragManager.item = null + dragManager.doNotRestoreAccept = false + } + } + + Text { + id: deleteHint + text: qsTr("Release to delete") + anchors.fill: parent + horizontalAlignment: Qt.AlignHCenter + verticalAlignment: Qt.AlignVCenter + font.pixelSize: 30 + visible: -vdrg.activeTranslation.y > (height / 2) + } + + DelegateModel.inPersistedItems: true + Rectangle { + id: container + anchors { + fill: parent + margins: workspaceThumbMargin - highlightBorderWidth + } + border.width: (!root.multitaskview.desktop.workspace.animationController.running && workspace.visible) ? highlightBorderWidth : 0 + border.color: "blue" + color: "transparent" + radius: workspaceThumbCornerRadius + highlightBorderWidth + states: [ + State { + name: "dragging" + when: vdrg.active || hdrg.active + PropertyChanges { + container { + anchors.fill: undefined + } + } + } + ] + + Item { + id: content + anchors { + fill: parent + margins: highlightBorderWidth + } + clip: true + + Wallpaper { + id: wallpaper + output: root.output.outputItem.output + workspace: workspaceThumbDelegate.workspace + } + + ShaderEffectSource { + id: wallpaperSource + sourceItem: wallpaper + anchors.fill: parent + recursive: false + hideSource: visible + smooth: true + opacity: 0 + } + + Shape { + anchors.fill: parent + preferredRendererType: Shape.CurveRenderer + ShapePath { + strokeWidth: 0 + fillItem: wallpaperSource + fillTransform: PlanarTransform.fromScale(content.width / wallpaper.width, content.height / wallpaper.height, 0, 0) + PathRectangle { + width: content.width + height: content.height + radius: workspaceThumbCornerRadius + } + } + } + + WorkspaceProxy { + id: wp + workspace: workspaceThumbDelegate.workspace + output: root.output + opacity: 0 + smooth: true + layer.enabled: true + } + + Shape { + anchors.fill: parent + preferredRendererType: Shape.CurveRenderer + ShapePath { + strokeWidth: 0 + fillItem: wp + fillTransform: PlanarTransform.fromScale(content.width / wp.width, content.height / wp.height, 0, 0) + PathRectangle { + width: content.width + height: content.height + radius: workspaceThumbCornerRadius + } + } + } + + HoverHandler { + id: hvrhdlr + enabled: !hdrg.active + onHoveredChanged: { + if (hovered) { + if (dragManager.item) { + if (dragManager.item.workspace) { // is dragging workspace + dragManager.destPoint = Qt.point(workspaceThumbDelegate.x, workspaceThumbDelegate.y) + visualModel.items.move(dragManager.item.DelegateModel.itemsIndex, workspaceThumbDelegate.DelegateModel.itemsIndex) + dragManager.accept = () => { + const fromIndex = dragManager.item.index + const destIndex = workspaceThumbDelegate.index + root.multitaskview.desktop.workspace.moveModelTo(dragManager.item.workspace.id, destIndex) + } + } else { // is dragging surface + restartSwitchTimer(workspaceThumbDelegate.index, workspaceThumbDelegate.workspace) + if (workspace.id !== dragManager.item.wrapper.workspaceId && !dragManager.doNotRestoreAccept) { + dragManager.accept = () => { + switchTimer.stop() + if (dragManager.item?.wrapper) { + root.multitaskview.desktop.workspace.moveSurfaceTo(dragManager.item.wrapper, workspace.id) + } + } + } + } + } + } else { + switchTimer.stop() + if (dragManager.item?.wrapper && !dragManager.doNotRestoreAccept) // is dragging surface, workspace always lose hover + dragManager.accept = null + } + } + } + + TapHandler { + id: taphdlr + acceptedButtons: Qt.LeftButton + enabled: !hdrg.active + gesturePolicy: TapHandler.WithinBounds + onTapped: { + if (workspace === root.multitaskview.desktop.workspace.current) { + multitaskview.exit() + } else { + root.multitaskview.desktop.workspace.switchTo(index) + } + } + } + + TapHandler { + id: quickHdlr + acceptedButtons: Qt.RightButton + enabled: !hdrg.active + gesturePolicy: TapHandler.WithinBounds + onTapped: { + root.multitaskview.desktop.workspace.switchTo(index) + multitaskview.exit() + } + } + + DragHandler { + id: hdrg + enabled: !vdrg.active + target: workspaceThumbDelegate + yAxis.enabled: false + } + + DragHandler { + id: vdrg + enabled: !hdrg.active && root.multitaskview.desktop.workspace.count > 1 + property bool commitDeletion: deleteHint.visible + target: container + xAxis.enabled: false + yAxis { + maximum: workspaceThumbMargin - highlightBorderWidth + minimum: -container.height + } + onActiveChanged: { + if (!active && commitDeletion) { + root.multitaskview.desktop.workspace.removeModel(workspaceThumbDelegate.index) + } + } + } + } + + RoundButton { + id: wsDestroyBtn + icon.name: "multitaskview_close" + icon.width: 26 + icon.height: 26 + height: 26 + width: height + visible: (root.multitaskview.desktop.workspace.count > 1) + && (hvrhdlr.hovered || hovered) && dragManager.item === null && !vdrg.active + anchors { + top: parent.top + right: parent.right + topMargin: -8 + rightMargin: -8 + } + Item { + id: control + property D.Palette textColor: DS.Style.button.text + } + palette.buttonText: control.textColor + background: Rectangle { + anchors.fill: parent + color: "transparent" + } + onClicked: { + root.multitaskview.desktop.workspace.removeModel(workspaceThumbDelegate.index) + } + } + } + } + } + + ListView { + id: workspaceList + anchors { + top: parent.top + bottom: parent.bottom + horizontalCenter: parent.horizontalCenter + } + + interactive: false + highlightFollowsCurrentItem: false + displaced: Transition { + enabled: multitaskview.enableAnimation + NumberAnimation { + property: "x" + duration: root.multitaskview.desktop.config.multitaskviewAnimationDuration + easing.type: root.multitaskview.desktop.config.multitaskviewEasingCurveType + } + } + width: Math.min(parent.width, + root.multitaskview.desktop.workspace.count * (workspaceThumbHeight * root.whRatio + 2 * workspaceThumbMargin)) + orientation: ListView.Horizontal + height: workspaceDelegateHeight + model: visualModel + WheelHandler { + acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad + onWheel: function (event) { + const directionDelta = event.inverted ? -event.angleDelta.y: event.angleDelta.y + if (directionDelta < 0) { + root.multitaskview.desktop.workspace.switchToNext() + } else { + root.multitaskview.desktop.workspace.switchToPrev() + } + } + } + } + + RoundButton { + id: wsCreateBtn + visible: root.multitaskview.desktop.workspace.count < root.multitaskview.desktop.config.maxWorkspace + anchors { + right: parent.right + verticalCenter: parent.verticalCenter + margins: 40 + } + height: 64 + width: 64 + icon.name: "add" + icon.height: 22 + icon.width: 22 + background: Item { + Rectangle { + id: bgRect + color: Qt.rgba(16, 16, 16, .1) + anchors.fill: parent + radius: 10 + } + Blur { + anchors.fill: bgRect + radius: 10 + } + Border { + anchors.fill: parent + radius: 10 + insideColor: Qt.rgba(255, 255, 255, 0.05) + } + } + onClicked: { + root.multitaskview.desktop.workspace.createModel() + root.multitaskview.desktop.workspace.switchTo(root.multitaskview.desktop.workspace.count - 1) + } + } + + Item { + id: newWorkspaceDropArea + anchors { + left: workspaceList.right + right: root.right + top: root.top + bottom: root.bottom + } + visible: root.multitaskview.desktop.workspace.count < root.multitaskview.desktop.config.maxWorkspace + HoverHandler { + onHoveredChanged: { + if (hovered) { + if (dragManager.item?.wrapper && !dragManager.doNotRestoreAccept) { + dragManager.accept = () => { + const wid = root.multitaskview.desktop.workspace.createModel() + root.multitaskview.desktop.workspace.switchTo(root.multitaskview.desktop.workspace.count - 1) + root.multitaskview.desktop.workspace.moveSurfaceTo(dragManager.item.wrapper, wid) + } + } + } else { + if (dragManager.item?.wrapper && !dragManager.doNotRestoreAccept) + dragManager.accept = null + } + } + } + } +} diff --git a/src/plugins/multitaskview/translations/multitaskview.am_ET.ts b/src/plugins/multitaskview/translations/multitaskview.am_ET.ts new file mode 100644 index 0000000000..20d402c6da --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.am_ET.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + መስኮት የለም + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.ar.ts b/src/plugins/multitaskview/translations/multitaskview.ar.ts new file mode 100644 index 0000000000..503ccb5233 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.ar.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + لا توجد نوافذ + + + + WorkspaceSelectionList + + + Release to delete + حرر للحذف + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.ast.ts b/src/plugins/multitaskview/translations/multitaskview.ast.ts new file mode 100644 index 0000000000..0e83b52559 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.ast.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Nun hai miniatures + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.az.ts b/src/plugins/multitaskview/translations/multitaskview.az.ts new file mode 100644 index 0000000000..83bda93208 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.az.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Pəncərələr yoxdur + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.bg.ts b/src/plugins/multitaskview/translations/multitaskview.bg.ts new file mode 100644 index 0000000000..3703735043 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.bg.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Без прозорци + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.bo.ts b/src/plugins/multitaskview/translations/multitaskview.bo.ts new file mode 100644 index 0000000000..8abeead6b3 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.bo.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + སྒེའུ་ཁུང་མེད་པ། + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.bqi.ts b/src/plugins/multitaskview/translations/multitaskview.bqi.ts new file mode 100644 index 0000000000..6572f75eda --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.bqi.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + bî nimdari + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.ca.ts b/src/plugins/multitaskview/translations/multitaskview.ca.ts new file mode 100644 index 0000000000..434e4dfba9 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.ca.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Sense finestres + + + + WorkspaceSelectionList + + + Release to delete + Deixeu-ho anar per eliminar-ho + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.cs.ts b/src/plugins/multitaskview/translations/multitaskview.cs.ts new file mode 100644 index 0000000000..a041b918df --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.cs.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Žádná okna + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.da.ts b/src/plugins/multitaskview/translations/multitaskview.da.ts new file mode 100644 index 0000000000..51be2ad96e --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.da.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Ingen vinduer + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.de.ts b/src/plugins/multitaskview/translations/multitaskview.de.ts new file mode 100644 index 0000000000..89bb8a7e59 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.de.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Keine Fenster + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.el.ts b/src/plugins/multitaskview/translations/multitaskview.el.ts new file mode 100644 index 0000000000..6668f808b5 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.el.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Χωρίς παράθυρα + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.en_US.ts b/src/plugins/multitaskview/translations/multitaskview.en_US.ts new file mode 100644 index 0000000000..6bf2f23dfd --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.en_US.ts @@ -0,0 +1,20 @@ + + + + + WindowSelectionGrid + + + No windows + + + + + WorkspaceSelectionList + + + Release to delete + + + + diff --git a/src/plugins/multitaskview/translations/multitaskview.es.ts b/src/plugins/multitaskview/translations/multitaskview.es.ts new file mode 100644 index 0000000000..a99d7cb23a --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.es.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Sin ventanas + + + + WorkspaceSelectionList + + + Release to delete + Soltar para eliminar + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.fi.ts b/src/plugins/multitaskview/translations/multitaskview.fi.ts new file mode 100644 index 0000000000..14bd974900 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.fi.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Ei ikkunaa + + + + WorkspaceSelectionList + + + Release to delete + Vapauta poistamalla + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.fr.ts b/src/plugins/multitaskview/translations/multitaskview.fr.ts new file mode 100644 index 0000000000..dba0c7c9c0 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.fr.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Pas de fenêtres + + + + WorkspaceSelectionList + + + Release to delete + Lâcher pour supprimer + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.gl_ES.ts b/src/plugins/multitaskview/translations/multitaskview.gl_ES.ts new file mode 100644 index 0000000000..57bfeee1a0 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.gl_ES.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Sen xanelas + + + + WorkspaceSelectionList + + + Release to delete + Soltar para eliminar + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.hi_IN.ts b/src/plugins/multitaskview/translations/multitaskview.hi_IN.ts new file mode 100644 index 0000000000..be060f081e --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.hi_IN.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + कोई विंडो नहीं + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.hr.ts b/src/plugins/multitaskview/translations/multitaskview.hr.ts new file mode 100644 index 0000000000..955de6db85 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.hr.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Bez prozora + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.hu.ts b/src/plugins/multitaskview/translations/multitaskview.hu.ts new file mode 100644 index 0000000000..8498446d8c --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.hu.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Nincsenek ablakok + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.id.ts b/src/plugins/multitaskview/translations/multitaskview.id.ts new file mode 100644 index 0000000000..84546a97e9 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.id.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Tidak ada jendela + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.it.ts b/src/plugins/multitaskview/translations/multitaskview.it.ts new file mode 100644 index 0000000000..4d84fda05e --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.it.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Nessuna finestra + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.ja.ts b/src/plugins/multitaskview/translations/multitaskview.ja.ts new file mode 100644 index 0000000000..7cd97194bf --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.ja.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + ウィンドウがありません + + + + WorkspaceSelectionList + + + Release to delete + 離して削除 + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.ka.ts b/src/plugins/multitaskview/translations/multitaskview.ka.ts new file mode 100644 index 0000000000..69b78fa486 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.ka.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + არ არის ფანჯარა + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.mn.ts b/src/plugins/multitaskview/translations/multitaskview.mn.ts new file mode 100644 index 0000000000..2bd96c142a --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.mn.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Цонх алга + + + + WorkspaceSelectionList + + + Release to delete + Устгахын тулд сулла + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.ms.ts b/src/plugins/multitaskview/translations/multitaskview.ms.ts new file mode 100644 index 0000000000..525b4e01aa --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.ms.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Tiada tetingkap + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.nl.ts b/src/plugins/multitaskview/translations/multitaskview.nl.ts new file mode 100644 index 0000000000..45d77a47dd --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.nl.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Er zijn geen geopende vensters + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.pl.ts b/src/plugins/multitaskview/translations/multitaskview.pl.ts new file mode 100644 index 0000000000..888c1d7aad --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.pl.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Brak okien + + + + WorkspaceSelectionList + + + Release to delete + Upuść, aby usunąć + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.pt.ts b/src/plugins/multitaskview/translations/multitaskview.pt.ts new file mode 100644 index 0000000000..7eddfdec01 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.pt.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Sem janelas + + + + WorkspaceSelectionList + + + Release to delete + Libertar para apagar + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.pt_BR.ts b/src/plugins/multitaskview/translations/multitaskview.pt_BR.ts new file mode 100644 index 0000000000..f41ece85d6 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.pt_BR.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Sem janelas + + + + WorkspaceSelectionList + + + Release to delete + Liberar para excluir + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.ro.ts b/src/plugins/multitaskview/translations/multitaskview.ro.ts new file mode 100644 index 0000000000..16836b7582 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.ro.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Lipsa ferestrelor + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.ru.ts b/src/plugins/multitaskview/translations/multitaskview.ru.ts new file mode 100644 index 0000000000..b048307271 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.ru.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Нет окон + + + + WorkspaceSelectionList + + + Release to delete + Разрешить удаление + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.sk.ts b/src/plugins/multitaskview/translations/multitaskview.sk.ts new file mode 100644 index 0000000000..ad286744ad --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.sk.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Žiadne okná + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.sl.ts b/src/plugins/multitaskview/translations/multitaskview.sl.ts new file mode 100644 index 0000000000..0bee7c600e --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.sl.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Ni oken + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.sq.ts b/src/plugins/multitaskview/translations/multitaskview.sq.ts new file mode 100644 index 0000000000..85a6d292f8 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.sq.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Pa dritare + + + + WorkspaceSelectionList + + + Release to delete + Hedhje në qarkullim për fshirje + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.sr.ts b/src/plugins/multitaskview/translations/multitaskview.sr.ts new file mode 100644 index 0000000000..fa9f02badf --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.sr.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Нема прозора + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.tr.ts b/src/plugins/multitaskview/translations/multitaskview.tr.ts new file mode 100644 index 0000000000..f8242af9df --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.tr.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Pencere yok + + + + WorkspaceSelectionList + + + Release to delete + Silmek için serbest bırak + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.ug.ts b/src/plugins/multitaskview/translations/multitaskview.ug.ts new file mode 100644 index 0000000000..a3360608f5 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.ug.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + كۆزنەك يوق + + + + WorkspaceSelectionList + + + Release to delete + + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.uk.ts b/src/plugins/multitaskview/translations/multitaskview.uk.ts new file mode 100644 index 0000000000..172f6d76d6 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.uk.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + Немає вікон + + + + WorkspaceSelectionList + + + Release to delete + Відпустити для вилучення + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.zh_CN.ts b/src/plugins/multitaskview/translations/multitaskview.zh_CN.ts new file mode 100644 index 0000000000..9d8f7eba94 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.zh_CN.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + 无打开的窗口 + + + + WorkspaceSelectionList + + + Release to delete + 释放以删除 + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.zh_HK.ts b/src/plugins/multitaskview/translations/multitaskview.zh_HK.ts new file mode 100644 index 0000000000..52ab1fff05 --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.zh_HK.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + 無打開的窗口 + + + + WorkspaceSelectionList + + + Release to delete + 釋放以刪除 + + + \ No newline at end of file diff --git a/src/plugins/multitaskview/translations/multitaskview.zh_TW.ts b/src/plugins/multitaskview/translations/multitaskview.zh_TW.ts new file mode 100644 index 0000000000..1b8dc03b2d --- /dev/null +++ b/src/plugins/multitaskview/translations/multitaskview.zh_TW.ts @@ -0,0 +1,18 @@ + + + WindowSelectionGrid + + + No windows + 無打開的視窗 + + + + WorkspaceSelectionList + + + Release to delete + 釋放以刪除 + + + \ No newline at end of file diff --git a/src/seat/dragcontroller.cpp b/src/seat/dragcontroller.cpp new file mode 100644 index 0000000000..68900bed74 --- /dev/null +++ b/src/seat/dragcontroller.cpp @@ -0,0 +1,103 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "dragcontroller.h" +#include "seatmanager.h" +#include "modules/dde-shell/ddeshellmanagerinterfacev1.h" +#include "modules/active-notify/activenotifymanagerinterfacev1.h" + +#include +#include + +#include + +DragController::DragController(SeatManager *seatManager, QObject *parent) + : QObject(parent) + , m_seatManager(seatManager) +{} + +DragController::~DragController() = default; + +void DragController::initialize(bool notifyDdeShell) +{ + m_notifyDdeShell = notifyDdeShell; + connect(m_seatManager, &SeatManager::seatAdded, this, &DragController::trackSeat); + for (auto *seat : m_seatManager->seats()) + trackSeat(seat); +} + +void DragController::trackSeat(WSeat *seat) +{ + disconnect(seat, &WSeat::requestDrag, this, nullptr); + connect(seat, &WSeat::requestDrag, this, [this, seat](WSurface *surface) { + handleRequestDrag(seat, surface); + }); +} + +void DragController::handleRequestDrag(WSeat *seat, WSurface *) +{ + if (!seat || !seat->handle()) + return; + + seat->setAlwaysUpdateHoverTarget(true); + struct wlr_drag *drag = seat->handle()->drag; + Q_ASSERT(drag); + + SeatDragEntry entry; + entry.drag = drag; + entry.owner = std::make_unique(); + auto *dragOwner = entry.owner.get(); + seat->listeners(dragOwner)->add(&drag->events.drop, this, [this, seat] (void *) { + if (m_notifyDdeShell) + DDEActiveInterface::sendDrop(seat); + ActiveNotifyV1::sendDragChanged(ActiveNotifyV1::Dropped, seat); + }); + + QPointer dragCursor = seat->cursor(); + seat->listeners(dragOwner)->add(&drag->events.destroy, this, [this, seat, drag, dragCursor, dragOwner] (void *) { + if (dragCursor) + dragCursor->setOverrideCursor(WCursor::toQCursor(WGlobal::CursorShape::Invalid)); + if (!drag->dropped) + ActiveNotifyV1::sendDragChanged(ActiveNotifyV1::Cancelled, seat); + drag->data = NULL; + seat->setAlwaysUpdateHoverTarget(false); + // Drop the drop/destroy/dnd_action listener entries while the destroy + // signal is being emitted: wlr_drag.c drag_destroy asserts the drop + // and destroy lists are empty after (erasing the entry destroys its + // WScopedListenerList and disconnects all of them). + seat->removeListeners(dragOwner); + std::erase_if(seatDragEntries, [drag](const auto &e) { + return e.drag == drag; + }); + }); + + // TODO: https://gitlab.freedesktop.org/wayland/wayland/-/work_items/444 + const auto updateCursor = [drag, dragCursor] { + if (!dragCursor || drag->grab_type != WLR_DRAG_GRAB_KEYBOARD_POINTER) + return; + + const auto action = drag->source + ? drag->source->current_dnd_action + : WL_DATA_DEVICE_MANAGER_DND_ACTION_NONE; + auto shape = WGlobal::CursorShape::NoDrop; + if (action == WL_DATA_DEVICE_MANAGER_DND_ACTION_COPY) + shape = WGlobal::CursorShape::Copy; + else if (action == WL_DATA_DEVICE_MANAGER_DND_ACTION_MOVE) + shape = WGlobal::CursorShape::Move; + else if (action == WL_DATA_DEVICE_MANAGER_DND_ACTION_ASK) + shape = WGlobal::CursorShape::DndAsk; + dragCursor->setOverrideCursor(WCursor::toQCursor(shape)); + }; + + if (drag->source) { + seat->listeners(dragOwner)->add(&drag->source->events.dnd_action, this, updateCursor); + } + updateCursor(); + + // Move the bundle into the list only after dndAction/updateCursor above. + seatDragEntries.push_back(std::move(entry)); + + if (m_notifyDdeShell) + DDEActiveInterface::sendStartDrag(seat); + ActiveNotifyV1::sendDragChanged(ActiveNotifyV1::Started, seat); +} diff --git a/src/seat/dragcontroller.h b/src/seat/dragcontroller.h new file mode 100644 index 0000000000..980db6a679 --- /dev/null +++ b/src/seat/dragcontroller.h @@ -0,0 +1,46 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include + +#include +#include + +struct wlr_drag; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WSeat; +class WSurface; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class SeatManager; + +class DragController : public QObject +{ + Q_OBJECT +public: + explicit DragController(SeatManager *seatManager, QObject *parent = nullptr); + ~DragController() override; + + void initialize(bool notifyDdeShell); + +private: + void trackSeat(WSeat *seat); + void handleRequestDrag(WSeat *seat, WSurface *surface); + +private: + struct SeatDragEntry { + wlr_drag *drag = nullptr; + std::unique_ptr owner; + }; + SeatManager *m_seatManager = nullptr; + bool m_notifyDdeShell = false; + std::vector seatDragEntries; +}; diff --git a/src/seat/pointerconstraintsmanager.cpp b/src/seat/pointerconstraintsmanager.cpp new file mode 100644 index 0000000000..1e8ee64385 --- /dev/null +++ b/src/seat/pointerconstraintsmanager.cpp @@ -0,0 +1,280 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "pointerconstraintsmanager.h" + +#include "core/rootsurfacecontainer.h" +#include "core/waylandserver.h" +#include "seatmanager.h" +#include "surface/surfacewrapper.h" + +#include +#include +#include +#include +#include +#include + +PointerConstraintsManager::PointerConstraintsManager(WPointerConstraintsV1 *constraints, + WaylandServer *server, QObject *parent) + : QObject(parent) + , WObject() + , m_server(server) + , m_interface(constraints) +{ + Q_ASSERT(m_interface); + connect(m_interface, + &WPointerConstraintsV1::newConstraint, + this, + &PointerConstraintsManager::onNewConstraint); + + // active-window change triggers constraint re-evaluation. + connect(m_server, &WaylandServer::activatedSurfaceChanged, this, &PointerConstraintsManager::onActiveWindowChanged); + + auto *seatManager = m_server->seatManager(); + for (auto *wseat : seatManager->seats()) + ensureSeatTracked(wseat->handle()); + connect(seatManager, &SeatManager::seatAdded, this, [this](WSeat *wseat) { + ensureSeatTracked(wseat->handle()); + }); +} + +PointerConstraintsManager::~PointerConstraintsManager() +{ + teardown(); +} + +void PointerConstraintsManager::onNewConstraint(wlr_pointer_constraint_v1 *constraint) +{ + if (!constraint) + return; + + m_constraints.append(constraint); + + auto *constraintOwner = new WListenerOwner(); + constraint->data = constraintOwner; + constraintOwner->listeners()->add(&constraint->events.set_region, this, [this, constraint]() { + onConstraintRegionChanged(constraint); + }); + constraintOwner->listeners()->add(&constraint->events.destroy, this, [this, constraint]() { + onConstraintDestroyed(constraint); + }); + + tryActivateConstraint(constraint); +} + +bool PointerConstraintsManager::canActivate(wlr_pointer_constraint_v1 *constraint) const +{ + if (!constraint || !constraint->seat || !constraint->surface) + return false; + + // Never activate while the server is in a special mode. + auto *server = m_server; + if (server->currentMode() != WaylandServer::CurrentMode::Normal) + return false; + + // Don't activate during any non-default pointer grab (popup, drag, etc.). + // wlr_seat_pointer_has_grab covers drag too (drag pushes a grab). + if (wlr_seat_pointer_has_grab(constraint->seat)) + return false; + + // treeland move/resize is Qt-level (no wlroots grab); exclude via WaylandServer. + auto *wseat = WSeat::fromHandle(constraint->seat); + if (wseat && server->rootContainer()->isInMoveResizeForSeat(wseat)) + return false; + + // Pointer focus: must match the constraint surface. + if (constraint->seat->pointer_state.focused_surface != constraint->surface) + return false; + + // Active window: only the foreground window may hold pointer constraints. + auto *activated = server->activatedSurface(); + if (!activated || !activated->surface() + || activated->surface()->handle() != constraint->surface) + return false; + + // Region containment: activate only if the pointer is already inside the + // constraint region (lazy activation policy, matching KWin). + wlr_seat *wlrSeat = constraint->seat; + const double sx = wlrSeat->pointer_state.sx; + const double sy = wlrSeat->pointer_state.sy; + if (!pixman_region32_contains_point(&constraint->region, floor(sx), floor(sy), NULL)) + return false; + + return true; +} + +void PointerConstraintsManager::tryActivateConstraint(wlr_pointer_constraint_v1 *constraint) +{ + if (m_active.contains(constraint)) + return; + + if (!canActivate(constraint)) + return; + + auto *seat = WSeat::fromHandle(constraint->seat); + auto *cursor = seat ? seat->cursor() : nullptr; + if (!cursor) + return; + + cursor->setActivePointerConstraint(constraint); + + wlr_pointer_constraint_v1_send_activated(constraint); + + m_active.append(constraint); +} + +void PointerConstraintsManager::releaseConstraintCursor(wlr_pointer_constraint_v1 *constraint) +{ + auto *seat = WSeat::fromHandle(constraint->seat); + auto *cursor = seat ? seat->cursor() : nullptr; + if (cursor) { + cursor->warpToActiveConstraintHint(); + cursor->setActivePointerConstraint(nullptr); + } +} + +void PointerConstraintsManager::deactivateConstraint(wlr_pointer_constraint_v1 *constraint) +{ + if (!m_active.removeOne(constraint)) + return; + + releaseConstraintCursor(constraint); + + // send_deactivated may destroy the constraint for oneshot lifetime, so do + // not touch the constraint object after this call (the destroy listener + // above will fire and clean up the owner). + wlr_pointer_constraint_v1_send_deactivated(constraint); +} + +void PointerConstraintsManager::onConstraintRegionChanged(wlr_pointer_constraint_v1 *constraint) +{ + if (!m_active.contains(constraint)) { + // Not yet active: try to activate now that + // wlroots has updated the effective region. + tryActivateConstraint(constraint); + return; + } + + // LOCKED: region changes do not affect a frozen cursor. + if (constraint->type == WLR_POINTER_CONSTRAINT_V1_LOCKED) + return; + + // CONFINED: unconfine if the pointer leaves the new region. + wlr_seat *wlrSeat = constraint->seat; + if (!wlrSeat) + return; + const double sx = wlrSeat->pointer_state.sx; + const double sy = wlrSeat->pointer_state.sy; + if (pixman_region32_contains_point(&constraint->region, floor(sx), floor(sy), NULL)) + return; + // Deferred: synchronous send_deactivated inside + // wlr_signal_emit_mutable would assert-fail on the + // still-iterated listener. + QMetaObject::invokeMethod( + this, + [this, constraint]() { + if (m_constraints.contains(constraint)) + deactivateConstraint(constraint); + }, + Qt::QueuedConnection); +} + +void PointerConstraintsManager::onConstraintDestroyed(wlr_pointer_constraint_v1 *constraint) +{ + m_constraints.removeOne(constraint); + if (m_active.removeOne(constraint)) + releaseConstraintCursor(constraint); + + auto *owner = static_cast(constraint->data); + constraint->data = nullptr; + delete owner; +} + +void PointerConstraintsManager::ensureSeatTracked(wlr_seat *seat) +{ + if (!seat) + return; + + auto *wseat = WSeat::fromHandle(seat); + if (!wseat) + return; + + // the listener list is owned by this (PointerConstraintsManager) + // on the wseat target. WSeat::teardown() in WServer::stop() auto-detaches all + // cross-object listener groups from the target before destroy + wseat->listeners(this)->add(&seat->events.pointer_grab_begin, this, [this, seat]() { + onSeatGrabChanged(seat); + }); + wseat->listeners(this)->add(&seat->events.pointer_grab_end, this, [this, seat]() { + onSeatGrabChanged(seat); + }); + // Activate on pointer enter, deactivate on pointer leave. + wseat->listeners(this)->add(&seat->pointer_state.events.focus_change, this, [this, seat]() { + onPointerFocusChanged(seat); + }); +} + +void PointerConstraintsManager::onSeatGrabChanged(wlr_seat *seat) +{ + if (wlr_seat_pointer_has_grab(seat)) { + // Grab began: deactivate all constraints for this seat. + const auto active = m_active; + for (auto *constraint : active) { + if (constraint->seat == seat) + deactivateConstraint(constraint); + } + } else { + // Grab ended: re-evaluate all tracked constraints. + const auto tracked = m_constraints; + for (auto *constraint : tracked) { + if (constraint->seat == seat) + tryActivateConstraint(constraint); + } + } +} + +void PointerConstraintsManager::onPointerFocusChanged(wlr_seat *seat) +{ + // Deactivate constraints whose surface lost focus and activate newly + // eligible ones (e.g. a constraint created before the pointer entered). + const auto tracked = m_constraints; + for (auto *constraint : tracked) { + if (constraint->seat != seat) + continue; + + const bool focused = seat->pointer_state.focused_surface == constraint->surface; + if (m_active.contains(constraint)) { + if (!focused) + deactivateConstraint(constraint); + } else if (focused) { + tryActivateConstraint(constraint); + } + } +} + +void PointerConstraintsManager::onActiveWindowChanged() +{ + auto *activated = m_server->activatedSurface(); + const auto activeWlrSurface = + activated && activated->surface() ? activated->surface()->handle() : nullptr; + + const auto active = m_active; + for (auto *c : active) { + if (c->surface != activeWlrSurface) + deactivateConstraint(c); + } + + const auto tracked = m_constraints; + for (auto *c : tracked) { + if (c->surface == activeWlrSurface) + tryActivateConstraint(c); + } +} + +void PointerConstraintsManager::deactivateAll() +{ + const auto active = m_active; + for (auto *constraint : active) + deactivateConstraint(constraint); +} diff --git a/src/seat/pointerconstraintsmanager.h b/src/seat/pointerconstraintsmanager.h new file mode 100644 index 0000000000..c8d9212b53 --- /dev/null +++ b/src/seat/pointerconstraintsmanager.h @@ -0,0 +1,56 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include +#include + +struct wlr_pointer_constraint_v1; +struct wlr_seat; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WCursor; +class WSeat; +WAYLIB_SERVER_END_NAMESPACE + +class WaylandServer; + +class PointerConstraintsManager + : public QObject + , public WAYLIB_SERVER_NAMESPACE::WObject +{ + Q_OBJECT + +public: + explicit PointerConstraintsManager(WAYLIB_SERVER_NAMESPACE::WPointerConstraintsV1 *constraints, + WaylandServer *server, + QObject *parent = nullptr); + ~PointerConstraintsManager() override; + + // Deactivate every active constraint (used when leaving Normal mode: + // lock screen / multitask view / window switch). + void deactivateAll(); + +private: + void onNewConstraint(wlr_pointer_constraint_v1 *constraint); + bool canActivate(wlr_pointer_constraint_v1 *constraint) const; + void tryActivateConstraint(wlr_pointer_constraint_v1 *constraint); + void deactivateConstraint(wlr_pointer_constraint_v1 *constraint); + void onConstraintRegionChanged(wlr_pointer_constraint_v1 *constraint); + void onConstraintDestroyed(wlr_pointer_constraint_v1 *constraint); + void releaseConstraintCursor(wlr_pointer_constraint_v1 *constraint); + void onActiveWindowChanged(); + void onSeatGrabChanged(wlr_seat *seat); + void onPointerFocusChanged(wlr_seat *seat); + void ensureSeatTracked(wlr_seat *seat); + + WaylandServer *m_server; + WAYLIB_SERVER_NAMESPACE::WPointerConstraintsV1 *m_interface = nullptr; + + QList m_constraints; + QList m_active; +}; diff --git a/src/seat/seatmanager.cpp b/src/seat/seatmanager.cpp new file mode 100644 index 0000000000..f740866881 --- /dev/null +++ b/src/seat/seatmanager.cpp @@ -0,0 +1,837 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "seatmanager.h" +#include "session/sessionseatmanager.h" +#include +#include "common/treelandlogging.h" +#include "dconfig/dconfigmanager.h" +#include "core/waylandserver.h" +#include "input/libinputconfig.h" +#include "seatuserconfig.hpp" +#include "usermodel.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +SeatManager::SeatManager(WServer *server, QObject *parent) + : QObject(parent) + , m_server(server) +{ +} + +SeatManager::~SeatManager() +{ + QMap seatsToDelete; + seatsToDelete.swap(m_seats); + m_deviceRules.clear(); + m_defaultSeat = nullptr; + + for (auto seat : std::as_const(seatsToDelete)) { + if (seat->ownsSocket()) + continue; // Session owns logical seat interfaces. + if (m_server) { + m_server->detach(seat); + } + delete seat; + } +} + +WSeat *SeatManager::createSeat(const QString &name, bool isFallback) +{ + if (m_seats.contains(name)) { + qCDebug(lcTlSeat) << "Seat" << name << "already exists"; + return m_seats[name]; + } + + WSeat *seat = new WSeat(name); + if (!m_seatNames.contains(name)) + m_seatNames.append(name); + + if (isFallback) { + m_fallbackName = name; + m_defaultSeat = seat; + } + + qCDebug(lcTlSeat) << "Created seat:" << name << "fallback:" << isFallback; + + // Configuration readiness is handled by the Session's InputManager. Seat + // identity must be published synchronously, independent of the active user. + if (m_activeDomain) + m_activeDomain->addSeat(seat, isFallback); + m_seats.insert(name, seat); + Q_EMIT seatAdded(seat); + + return seat; +} + +void SeatManager::removeSeat(const QString &name) +{ + if (!m_seats.contains(name)) { + qCWarning(lcTlSeat) << "Cannot remove non-existent seat:" << name; + return; + } + + WSeat *seat = m_seats.take(name); + m_seatNames.removeAll(name); + if (m_fallbackName == name) + m_fallbackName.clear(); + + if (m_defaultSeat == seat && !m_seats.isEmpty()) { + m_defaultSeat = m_seats.begin().value(); + qCDebug(lcTlSeat) << "Fallback seat changed to:" << m_defaultSeat->name(); + } else if (m_defaultSeat == seat) { + m_defaultSeat = nullptr; + qCDebug(lcTlSeat) << "No fallback seat available"; + } + + const auto devices = m_backend ? m_backend->inputDeviceList() : QList{}; + for (auto *device : devices) { + if (!seat->deviceList().contains(device)) + continue; + // Virtual keyboards are released by their Session's IME helper. They + // must not be reassigned while that helper still owns their wrappers. + seat->detachInputDevice(device); + + clearDeviceCache(device); + // Reassign device to appropriate seat + if (!m_seats.isEmpty()) { + WSeat *newSeat = autoAssignDevice(device); + if (newSeat) { + Q_EMIT deviceReassigned(device, seat, newSeat); + } else { + qCWarning(lcTlSeat) << "Failed to reassign device after seat removal:" << device->name(); + } + } + } + + Q_EMIT seatRemoved(seat); + qCDebug(lcTlSeat) << "Removed seat:" << name; + + if (m_activeDomain) + m_activeDomain->removeSeat(seat); + else { + m_server->detach(seat); + delete seat; + } + + // Clean up device rules for removed seat + m_deviceRules.remove(name); +} + +void SeatManager::removeSeat(WSeat *seat) +{ + Q_ASSERT(seat); + + QString seatName; + for (auto it = m_seats.begin(); it != m_seats.end(); ++it) { + if (it.value() == seat) { + seatName = it.key(); + break; + } + } + + if (!seatName.isEmpty()) { + removeSeat(seatName); + } else { + qCWarning(lcTlSeat) << "Attempted to remove a seat that is not managed by SeatManager"; + } +} + +WSeat *SeatManager::getSeat(const QString &name) const +{ + return m_seats.value(name); +} + +QList SeatManager::seats() const +{ + return m_seats.values(); +} + +QStringList SeatManager::configuredSeatNames() const { return m_seatNames; } + +QString SeatManager::configuredFallbackName() const +{ + if (!m_fallbackName.isEmpty()) + return m_fallbackName; + return m_defaultSeat ? m_defaultSeat->name() : m_seatNames.value(0); +} + +WSeat *SeatManager::fallbackSeat() const +{ + return m_defaultSeat; +} + +void SeatManager::assignDeviceToSeat(WInputDevice *device, const QString &seatName) +{ + if (!device) { + qCWarning(lcTlSeat) << "Cannot assign null device to seat"; + return; + } + + for (auto seat : std::as_const(m_seats)) { + if (seat->deviceList().contains(device)) { + if (seat->name() == seatName) { + qCDebug(lcTlSeat) << "Device" << device->name() << "already assigned to seat" << seatName; + return; + } + + seat->detachInputDevice(device); + qCDebug(lcTlSeat) << "Device" << device->name() << "detached from seat" << seat->name(); + break; + } + } + + if (m_seats.contains(seatName)) { + m_seats[seatName]->attachInputDevice(device); + qCDebug(lcTlSeat) << "Device" << device->name() << "assigned to seat" << seatName; + } else if (fallbackSeat()) { + fallbackSeat()->attachInputDevice(device); + qCDebug(lcTlSeat) << "Device" << device->name() << "assigned to fallback seat"; + } else { + qCWarning(lcTlSeat) << "Cannot assign device" << device->name() << "- no seats available"; + } +} + +WSeat *SeatManager::autoAssignDevice(WInputDevice *device) +{ + if (!device) { + qCWarning(lcTlSeat) << "Cannot auto-assign null device"; + return nullptr; + } + + for (auto seat : std::as_const(m_seats)) { + if (seat->deviceList().contains(device)) { + qCDebug(lcTlSeat) << "Device" << device->name() << "already assigned to seat" << seat->name(); + return seat; + } + } + + WSeat *targetSeat = findSeatForDevice(device); + + if (targetSeat) { + targetSeat->attachInputDevice(device); + qCDebug(lcTlSeat) << "Device" << device->name() << "auto-assigned to seat" << targetSeat->name(); + return targetSeat; + } else if (fallbackSeat()) { + fallbackSeat()->attachInputDevice(device); + qCDebug(lcTlSeat) << "Device" << device->name() << "auto-assigned to fallback seat"; + return fallbackSeat(); + } + + qCWarning(lcTlSeat) << "Failed to auto-assign device" << device->name(); + return nullptr; +} + +void SeatManager::addDeviceRule(const QString &seatName, const QString &rule) +{ + if (seatName.isEmpty()) { + qCWarning(lcTlSeat) << "Cannot add device rule for seat with empty name"; + return; + } + + if (rule.isEmpty()) { + qCWarning(lcTlSeat) << "Cannot add empty device rule"; + return; + } + + if (!m_seats.contains(seatName)) { + qCWarning(lcTlSeat) << "Cannot add device rule for non-existent seat:" << seatName; + return; + } + + QRegularExpression regex(rule); + if (!regex.isValid()) { + qCWarning(lcTlSeat) << "Invalid regex pattern for device rule:" << rule << "Error:" << regex.errorString(); + return; + } + + if (!m_deviceRules.contains(seatName)) { + m_deviceRules[seatName] = QList(); + } + + // Check for duplicate rules + for (const auto &existingRule : std::as_const(m_deviceRules[seatName])) { + if (existingRule.pattern() == rule) { + qCDebug(lcTlSeat) << "Device rule already exists for seat" << seatName << ":" << rule; + return; + } + } + + m_deviceRules[seatName].append(regex); + qCDebug(lcTlSeat) << "Added device rule for seat" << seatName << ":" << rule; +} + +void SeatManager::removeDeviceRule(const QString &seatName, const QString &rule) +{ + if (!m_deviceRules.contains(seatName)) { + qCDebug(lcTlSeat) << "No device rules for seat:" << seatName; + return; + } + + QRegularExpression regex(rule); + if (!regex.isValid()) { + qCWarning(lcTlSeat) << "Invalid regex pattern:" << rule; + return; + } + + auto &rules = m_deviceRules[seatName]; + for (int i = 0; i < rules.size(); i++) { + if (rules[i].pattern() == regex.pattern()) { + rules.removeAt(i); + qCDebug(lcTlSeat) << "Removed device rule from seat" << seatName << ":" << rule; + break; + } + } + + if (rules.isEmpty()) { + m_deviceRules.remove(seatName); + qCDebug(lcTlSeat) << "All device rules removed for seat:" << seatName; + } +} + +QStringList SeatManager::deviceRules(const QString &seatName) const +{ + if (!m_deviceRules.contains(seatName)) + return QStringList(); + + QStringList result; + const auto &rules = m_deviceRules[seatName]; + for (const auto ®ex : std::as_const(rules)) { + result.append(regex.pattern()); + } + + return result; +} + +void SeatManager::loadConfig(const QJsonObject &config) +{ + qCDebug(lcTlSeat) << "Loading seat configuration"; + + const auto names = m_seats.keys(); + for (const auto &name : names) + removeSeat(name); + m_deviceRules.clear(); + + QJsonArray seatsArray = config["seats"].toArray(); + for (const auto &seatValue : std::as_const(seatsArray)) { + QJsonObject seatObj = seatValue.toObject(); + QString name = seatObj["name"].toString(); + bool isFallback = seatObj["fallback"].toBool(); + + createSeat(name, isFallback); + + QJsonArray rulesArray = seatObj["deviceRules"].toArray(); + for (const auto &ruleValue : std::as_const(rulesArray)) { + QString rule = ruleValue.toString(); + addDeviceRule(name, rule); + } + } + + if (m_seats.isEmpty()) { + qCDebug(lcTlSeat) << "No seats in config, creating default seat0"; + createSeat(DEFAULT_SEAT_NAME, true); + } + + if (!m_defaultSeat && !m_seats.isEmpty()) { + m_defaultSeat = m_seats.begin().value(); + qCDebug(lcTlSeat) << "Set fallback seat to:" << m_defaultSeat->name(); + } + + qCDebug(lcTlSeat) << "Loaded" << m_seats.size() << "seats"; +} + +bool SeatManager::loadConfigFromFile(const QString &filePath) +{ + QFile file(filePath); + if (!file.open(QIODevice::ReadOnly)) { + qCDebug(lcTlSeat) << "Config file not found:" << filePath; + return false; + } + + QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); + if (doc.isNull() || !doc.isObject()) { + qCWarning(lcTlSeat) << "Invalid JSON in config file:" << filePath; + return false; + } + + QJsonObject config = doc.object(); + if (!validateConfig(config)) { + qCWarning(lcTlSeat) << "Invalid seat configuration in:" << filePath; + return false; + } + + loadConfig(config); + return true; +} + +bool SeatManager::saveConfigToFile(const QString &filePath) const +{ + QJsonObject config = saveConfig(); + QJsonDocument doc(config); + + QFile file(filePath); + if (!file.open(QIODevice::WriteOnly)) { + qCWarning(lcTlSeat) << "Cannot write config file:" << filePath; + return false; + } + + file.write(doc.toJson(QJsonDocument::Indented)); + qCDebug(lcTlSeat) << "Saved configuration to:" << filePath; + return true; +} + +bool SeatManager::validateConfig(const QJsonObject &config) const +{ + if (!config.contains("seats") || !config["seats"].isArray()) { + return false; + } + + QJsonArray seatsArray = config["seats"].toArray(); + bool hasFallback = false; + + for (const auto &seatValue : seatsArray) { + if (!seatValue.isObject()) { + return false; + } + + QJsonObject seatObj = seatValue.toObject(); + if (!seatObj.contains("name") || !seatObj["name"].isString()) { + return false; + } + + if (seatObj.contains("fallback") && seatObj["fallback"].toBool()) { + if (hasFallback) { + qCWarning(lcTlSeat) << "Multiple fallback seats found in configuration"; + return false; + } + hasFallback = true; + } + + if (seatObj.contains("deviceRules") && !seatObj["deviceRules"].isArray()) { + return false; + } + } + + return true; +} + +void SeatManager::initializeDefaultSeat() +{ + if (!m_seats.isEmpty()) { + qCDebug(lcTlSeat) << "Seats already initialized"; + return; + } + + WSeat *defaultSeat = createSeat(DEFAULT_SEAT_NAME, true); + if (!defaultSeat) { + qCCritical(lcTlSeat) << "Failed to create default seat!"; + return; + } + + ensureDefaultDeviceRules(DEFAULT_SEAT_NAME); + + qCDebug(lcTlSeat) << "Initialized default seat: seat0"; +} + +void SeatManager::ensureDefaultDeviceRules(const QString &seatName) +{ + if (deviceRules(seatName).isEmpty()) { + addDeviceRule(seatName, QString("%1:.*").arg(static_cast(WInputDevice::Type::Keyboard))); + addDeviceRule(seatName, QString("%1:.*").arg(static_cast(WInputDevice::Type::Pointer))); + addDeviceRule(seatName, QString("%1:.*").arg(static_cast(WInputDevice::Type::Touch))); + qCDebug(lcTlSeat) << "Added default device rules for seat:" << seatName; + } +} + +WSeat *SeatManager::initializeFromConfig(const QString &configPath, WServer *server) +{ + // Try to load config from file + if (!loadConfigFromFile(configPath)) { + qCDebug(lcTlSeat) << "No valid seat config found at:" << configPath; + } + + // Ensure at least one seat exists + if (m_seats.isEmpty()) { + initializeDefaultSeat(); + } + + // Determine primary seat + WSeat *primarySeat = fallbackSeat(); + if (!primarySeat && !m_seats.isEmpty()) { + primarySeat = m_seats.first(); + } + + if (!primarySeat) { + qCCritical(lcTlSeat) << "No seat available after initialization!"; + return nullptr; + } + + // Ensure primary seat has default device rules + ensureDefaultDeviceRules(primarySeat->name()); + + // Attach all seats to server + if (server && server->isRunning()) { + for (auto *seat : std::as_const(m_seats)) { + if (seat->server() != server) { + server->attach(seat); + } + } + } + + qCDebug(lcTlSeat) << "Seat initialization complete. Primary seat:" << primarySeat->name(); + return primarySeat; +} + +QJsonObject SeatManager::saveConfig() const +{ + QJsonObject config; + QJsonArray seatsArray; + + for (auto it = m_seats.begin(); it != m_seats.end(); ++it) { + QString name = it.key(); + WSeat *seat = it.value(); + + QJsonObject seatObj; + seatObj["name"] = name; + seatObj["fallback"] = (seat == m_defaultSeat); + + QJsonArray rulesArray; + const auto rules = deviceRules(name); + for (const auto &rule : std::as_const(rules)) { + rulesArray.append(rule); + } + seatObj["deviceRules"] = rulesArray; + + seatsArray.append(seatObj); + } + + config["seats"] = seatsArray; + qCDebug(lcTlSeat) << "Saved configuration for" << m_seats.size() << "seats"; + return config; +} + +bool SeatManager::matchesDevice(WInputDevice *device, const QList &rules) +{ + if (!device) + return false; + + QString deviceName = device->name(); + WInputDevice::Type deviceType = device->type(); + QString devicePath = device->devicePath(); + + QString deviceInfo = QString("%1:%2") + .arg(static_cast(deviceType)) + .arg(deviceName); + QString deviceInfoWithPath = QString("%1:%2|%3") + .arg(static_cast(deviceType)) + .arg(deviceName) + .arg(devicePath); + + for (const auto &rule : rules) { + if (rule.match(deviceInfo).hasMatch()) + return true; + if (rule.match(deviceInfoWithPath).hasMatch()) + return true; + } + return false; +} + +bool SeatManager::deviceMatchesSeat(WInputDevice *device, WSeat *seat) const +{ + if (!device || !seat) + return false; + + QString seatName = seat->name(); + + if (!m_deviceRules.contains(seatName)) { + return false; + } + + bool matches = matchesDevice(device, m_deviceRules[seatName]); + return matches; +} + +WSeat *SeatManager::findSeatForDevice(WInputDevice *device) const +{ + if (!device) + return nullptr; + + for (auto seat : std::as_const(m_seats)) { + if (seat->deviceList().contains(device)) { + return seat; + } + } + + for (auto it = m_seats.begin(); it != m_seats.end(); ++it) { + WSeat *seat = it.value(); + if (seat == m_defaultSeat) { + continue; + } + if (deviceMatchesSeat(device, seat)) { + return seat; + } + } + + WSeat *fallbackSeat = this->fallbackSeat(); + if (fallbackSeat) { + bool hasRules = m_deviceRules.contains(fallbackSeat->name()) && + !m_deviceRules[fallbackSeat->name()].isEmpty(); + + if (hasRules && deviceMatchesSeat(device, fallbackSeat)) { + return fallbackSeat; + } else if (!hasRules) { + return fallbackSeat; + } + } + + return nullptr; +} + +void SeatManager::setupAllSeats(QQuickWindow *renderWindow, + WOutputLayout *layout, + WSeatEventFilter *eventFilter, + WCursor *seat0Cursor) +{ + m_renderWindow = renderWindow; + m_layout = layout; + m_eventFilter = eventFilter; + for (auto *seat : std::as_const(m_seats)) { + if (!seat->handle()) { + qCWarning(lcTlSeat) << "Seat" << seat->name() << "has no native handle, skipping configuration"; + continue; + } + + // Setup cursor + if (!seat->cursor()) { + if (seat->name() == DEFAULT_SEAT_NAME && seat0Cursor) { + seat->setCursor(seat0Cursor); + } else { + WCursor *cursor = new WCursor(seat); + cursor->setParent(seat); + if (layout) { + cursor->setLayout(layout); + } + seat->setCursor(cursor); + } + } + + seat->setKeyboardFocusWindow(renderWindow); + + if (!seat->eventFilter()) { + seat->setEventFilter(eventFilter); + } + } +} + +void SeatManager::connectBackendSignals(WBackend *backend) +{ + m_backend = backend; + if (!backend) { + qCWarning(lcTlSeat) << "Cannot connect signals for null backend"; + return; + } + + connect(backend, &WBackend::inputAdded, this, [this](WInputDevice *device) { + if (device) { + Q_EMIT deviceAdded(device); + } + }); + + connect(backend, &WBackend::inputRemoved, this, [this](WInputDevice *device) { + if (device) { + clearDeviceCache(device); + // Detach device from its seat + for (auto *seat : std::as_const(m_seats)) { + if (seat->deviceList().contains(device)) { + seat->detachInputDevice(device); + qCDebug(lcTlSeat) << "Device" << device->name() << "removed from seat" << seat->name(); + break; + } + } + + Q_EMIT deviceRemoved(device); + } + }); + +} + +void SeatManager::assignExistingDevices(WBackend *backend) +{ + if (!backend) { + qCWarning(lcTlSeat) << "Cannot assign devices from null backend"; + return; + } + + const auto devices = backend->inputDeviceList(); + for (auto device : devices) { + if (device) { + Q_EMIT deviceAdded(device); + } + } +} + +void SeatManager::assignDevice(WInputDevice *device, + QQuickWindow *renderWindow, + WOutputLayout *layout, + WSeat *fallbackSeat) +{ + if (!device) { + qCWarning(lcTlSeat) << "Cannot assign null device"; + return; + } + + QString deviceName = device->name(); + WInputDevice::Type deviceType = device->type(); + + // Auto-assign device to appropriate seat + WSeat *assignedSeat = autoAssignDevice(device); + if (!assignedSeat && fallbackSeat && fallbackSeat->handle()) { + fallbackSeat->attachInputDevice(device); + assignedSeat = fallbackSeat; + qCDebug(lcTlSeat) << "Device" << deviceName << "assigned to fallback seat"; + } + + if (!assignedSeat) { + qCWarning(lcTlSeat) << "Failed to assign device:" << deviceName; + return; + } + + // Setup cursor for pointer devices + if (deviceType == WInputDevice::Type::Pointer && !assignedSeat->cursor()) { + WCursor *cursor = new WCursor(assignedSeat); + cursor->setParent(assignedSeat); + if (layout) { + cursor->setLayout(layout); + } + assignedSeat->setCursor(cursor); + } + + // Setup keyboard focus window for keyboard devices + if (deviceType == WInputDevice::Type::Keyboard && !assignedSeat->keyboardFocusWindow()) { + assignedSeat->setKeyboardFocusWindow(renderWindow); + } + + m_deviceCache[device] = assignedSeat; + Q_EMIT deviceAssigned(device); +} + +WSeat *SeatManager::getSeatForDevice(WInputDevice *device) const +{ + if (!device) { + return nullptr; + } + + // Check cache first + if (m_deviceCache.contains(device)) { + return m_deviceCache[device]; + } + + // Find seat and update cache + WSeat *seat = findSeatForDevice(device); + m_deviceCache[device] = seat; + + return seat; +} + +WSeat *SeatManager::getSeatForEvent(QInputEvent *event) const +{ + if (!event) { + qCWarning(lcTlSeat) << "getSeatForEvent called with null event"; + return nullptr; + } + + if (event->device()) { + WInputDevice *device = WInputDevice::from(event->device()); + if (device) { + WSeat *deviceSeat = device->seat(); + if (deviceSeat) { + return deviceSeat; + } + } + } + + return fallbackSeat(); +} + +void SeatManager::clearDeviceCache(WInputDevice *device) +{ + m_deviceCache.remove(device); +} + +void SeatManager::activateSessionSeats(SessionSeatManager *domain) +{ + if (m_activeDomain == domain) + return; + const auto previous = m_seats; + QMap cursors; + cursors.swap(m_parkedCursors); + for (auto *seat : previous) { + // Clear focus and terminate grabs while the old cursor still belongs to + // this seat, so cancellation is delivered only to the old Session. + seat->clearKeyboardFocusSurface(); + seat->clearKeyboardFocusWindow(); + wlr_seat_pointer_notify_clear_focus(seat->handle()); + wlr_seat_keyboard_end_grab(seat->handle()); + wlr_seat_pointer_end_grab(seat->handle()); + wlr_seat_touch_end_grab(seat->handle()); + wlr_seat_client *client; + wl_list_for_each(client, &seat->handle()->clients, link) + wlr_seat_touch_notify_cancel(seat->handle(), client); + if (m_backend) { + for (auto *device : m_backend->inputDeviceList()) { + if (seat->deviceList().contains(device)) + seat->detachInputDevice(device); + } + } + if (auto *cursor = seat->cursor()) { + // Hardware cursors travel with physical devices, not selections or + // other user-owned seat state. + cursor->setParent(this); + cursors.insert(seat->name(), cursor); + seat->setCursor(nullptr); + } + Q_EMIT seatRemoved(seat); + } + m_seats.clear(); + m_deviceCache.clear(); + m_activeDomain = domain; + for (auto *seat : domain->seats()) { + m_seats.insert(seat->name(), seat); + if (auto *cursor = cursors.take(seat->name())) + seat->setCursor(cursor); + } + m_defaultSeat = domain->fallbackSeat(); + setupAllSeats(m_renderWindow, m_layout, m_eventFilter); + for (auto *seat : std::as_const(m_seats)) + Q_EMIT seatAdded(seat); + if (m_backend) + assignExistingDevices(m_backend); + m_parkedCursors.swap(cursors); +} + +void SeatManager::releaseSessionSeats(SessionSeatManager *domain) +{ + // Also handle the first Session, which adopts the bootstrap seats before + // it has been activated. + const auto ownedSeats = domain->seats(); + for (auto *seat : ownedSeats) { + if (m_seats.value(seat->name()) != seat) + continue; + Q_EMIT seatRemoved(seat); + m_seats.remove(seat->name()); + if (m_defaultSeat == seat) + m_defaultSeat = nullptr; + } + m_deviceCache.clear(); + if (m_activeDomain == domain) + m_activeDomain = nullptr; +} diff --git a/src/seat/seatmanager.h b/src/seat/seatmanager.h new file mode 100644 index 0000000000..09e88acc04 --- /dev/null +++ b/src/seat/seatmanager.h @@ -0,0 +1,127 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#define DEFAULT_SEAT_NAME "seat0" + +#include +#include +#include + +#include +#include +#include + +QT_BEGIN_NAMESPACE +class QJsonObject; +class QInputEvent; +class QQuickWindow; +QT_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WBackend; +class WCursor; +class WOutputLayout; +class WSeatEventFilter; +WAYLIB_SERVER_END_NAMESPACE + +class SessionSeatManager; + +// SeatManager manages multi-seat configuration and device assignment for treeland. +// This class implements compositor-specific policies for seat creation, device +// assignment rules, and configuration persistence. +class SeatManager : public QObject +{ + Q_OBJECT + +public: + explicit SeatManager(WServer *server, QObject *parent = nullptr); + ~SeatManager(); + + // Seat management + WSeat *createSeat(const QString &name, bool isFallback = false); + void removeSeat(const QString &name); + void removeSeat(WSeat *seat); + WSeat *getSeat(const QString &name) const; + QList seats() const; + QStringList configuredSeatNames() const; + QString configuredFallbackName() const; + WSeat *fallbackSeat() const; + + void activateSessionSeats(SessionSeatManager *domain); + void releaseSessionSeats(SessionSeatManager *domain); + + // Device assignment + void assignDeviceToSeat(WInputDevice *device, const QString &seatName); + WSeat *autoAssignDevice(WInputDevice *device); + + // Device lifecycle management + void assignDevice(WInputDevice *device, + QQuickWindow *renderWindow, + WAYLIB_SERVER_NAMESPACE::WOutputLayout *layout, + WSeat *fallbackSeat); + void setupAllSeats(QQuickWindow *renderWindow, + WAYLIB_SERVER_NAMESPACE::WOutputLayout *layout, + WAYLIB_SERVER_NAMESPACE::WSeatEventFilter *eventFilter, + WAYLIB_SERVER_NAMESPACE::WCursor *seat0Cursor = nullptr); + void connectBackendSignals(WAYLIB_SERVER_NAMESPACE::WBackend *backend); + void assignExistingDevices(WAYLIB_SERVER_NAMESPACE::WBackend *backend); + + // Device query with cache + WSeat *getSeatForDevice(WInputDevice *device) const; + WSeat *getSeatForEvent(QInputEvent *event) const; + void clearDeviceCache(WInputDevice *device); + + // TODO(Lyn): Replace file-based seat config (loadSeatConfig/saveSeatConfig) with DConfig. + // Configuration management + void loadConfig(const QJsonObject &config); + QJsonObject saveConfig() const; + + // Configuration file operations + bool loadConfigFromFile(const QString &filePath); + bool saveConfigToFile(const QString &filePath) const; + bool validateConfig(const QJsonObject &config) const; + + // Initialization + void initializeDefaultSeat(); + void ensureDefaultDeviceRules(const QString &seatName); + + // Initialize seats from config file with fallback to default + WSeat *initializeFromConfig(const QString &configPath, WServer *server); + + // Device matching rules + void addDeviceRule(const QString &seatName, const QString &rule); + void removeDeviceRule(const QString &seatName, const QString &rule); + QStringList deviceRules(const QString &seatName) const; + + // Device matching (moved from WSeat) + static bool matchesDevice(WInputDevice *device, const QList &rules); + bool deviceMatchesSeat(WInputDevice *device, WSeat *seat) const; + WSeat *findSeatForDevice(WInputDevice *device) const; + +Q_SIGNALS: + void seatAdded(WSeat *seat); + void seatRemoved(WSeat *seat); + void deviceAssigned(WInputDevice *device); + void deviceReassigned(WInputDevice *device, WSeat *oldSeat, WSeat *newSeat); + void deviceAdded(WInputDevice *device); + void deviceRemoved(WInputDevice *device); + +private: + SessionSeatManager *m_activeDomain = nullptr; + QMap m_parkedCursors; + QQuickWindow *m_renderWindow = nullptr; + WAYLIB_SERVER_NAMESPACE::WOutputLayout *m_layout = nullptr; + WAYLIB_SERVER_NAMESPACE::WSeatEventFilter *m_eventFilter = nullptr; + WAYLIB_SERVER_NAMESPACE::WBackend *m_backend = nullptr; + WServer *m_server = nullptr; + QMap m_seats; + QMap> m_deviceRules; + WSeat *m_defaultSeat = nullptr; + QStringList m_seatNames; + QString m_fallbackName; + mutable QMap m_deviceCache; +}; diff --git a/src/session/session.cpp b/src/session/session.cpp new file mode 100644 index 0000000000..8d62ada8cf --- /dev/null +++ b/src/session/session.cpp @@ -0,0 +1,326 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "session.h" +#include "utils/loginddbustypes.h" + +#include +#include +#include "sessionmanager.h" +#include "desktop/desktopenvironment.h" +#include "surface/surfacecontainer.h" +#include "sessionseatmanager.h" +#include "sessionworkspace.h" +#include "sessionscene.h" +#include "sessionprelaunch.h" +#include "sessionprotocols.h" +#include "sessionmultitaskview.h" +#include "sessioninputchannel.h" + +#include "common/treelandlogging.h" +#include "core/shellhandler.h" +#include "core/waylandserver.h" +#include "workspace/workspace.h" +#ifndef DISABLE_XWAYLAND +#include "xsettings/settingmanager.h" +#endif + +#include + +#include +#include +#include +#include "modules/foreign-toplevel/foreigntoplevelmanagerv3.h" +#include +#ifndef DISABLE_XWAYLAND +#include +#endif + +void Session::detachInterface(WServerInterface *interface) +{ + if (!m_interfaces.removeOne(interface)) { + return; + } + + if (auto *server = WaylandServer::instance()) { + server->server()->detach(interface); + } + + delete interface; +} + +Session::~Session() +{ + shutdown(); +} + +void Session::beginShutdown() +{ + if (m_shuttingDown) + return; + + m_shuttingDown = true; + unsubscribeLogind(); + + if (m_scene) + m_scene->shutdown(); + + if (m_prelaunch) + m_prelaunch->shutdown(); +} + +void Session::closeClients() +{ + if (!m_socket) + return; + + QList> clients; + QList> sockets{m_socket}; + if (auto *runtime = WaylandServer::instance()) { + wl_client *handle; + wl_client_for_each(handle, wl_display_get_client_list(runtime->server()->handle())) { + auto *client = WClient::get(handle); + if (!ownsClient(client)) + continue; + + clients.append(client); + for (auto *socket = client->socket(); socket && socket != m_socket; + socket = socket->parentSocket()) { + if (!sockets.contains(socket)) + sockets.append(socket); + } + } + } + + for (const auto &socket : sockets) { + if (socket) + socket->stopListen(); + } + + // Destroy native resources while WClient still identifies their Session. + // Native destruction removes each client from its socket before deleting WClient. + // Snapshot QPointers because a resource callback may destroy another client. + for (const auto &client : clients) { + if (client && client->handle()) + wl_client_destroy(client->handle()); + } + + // WSocket::close() only closes its own clients, not descendant sockets. + for (const auto &socket : sockets) { + if (socket) + socket->close(); + } +} + +void Session::shutdown() +{ + if (m_shutdownStarted) + return; + + m_shutdownStarted = true; + beginShutdown(); + qCDebug(lcTlCore) << "Deleting session for uid:" << m_uid << m_socket; + if (WaylandServer::instance()) { + setActive(false); + } + + Q_EMIT aboutToBeDestroyed(); + +#ifndef DISABLE_XWAYLAND + if (m_settingManagerThread) { + m_settingManagerThread->quit(); + m_settingManagerThread->wait(QDeadlineTimer(25000)); + } + + if (m_settingManager) { + delete m_settingManager; + m_settingManager = nullptr; + } + + if (m_xwayland) { + if (auto *server = WaylandServer::instance()) + server->shellHandler()->removeXWayland(m_xwayland); + m_xwayland = nullptr; + } +#endif + + closeClients(); + + // Native surfaces have now been destroyed with their clients. Retire their + // disabled wrappers before removing the protocols used by invalidation. + if (m_scene) + m_scene->finishShutdown(); + + if (m_seatManager) { + delete m_seatManager; + m_seatManager = nullptr; + } + + // Unwind dependencies in reverse attachment order. Resource callbacks have + // finished, but keep the desktop alive while protocol wrappers detach. + while (!m_interfaces.isEmpty()) + detachInterface(m_interfaces.constLast()); + + if (m_prelaunch) { + delete m_prelaunch; + m_prelaunch = nullptr; + } + + if (m_multitaskView) { + delete m_multitaskView; + m_multitaskView = nullptr; + } + + if (m_desktop) { + delete m_desktop->inputChannel(); + delete m_desktop; + m_desktop = nullptr; + } + + m_outputManager = nullptr; + + if (m_protocols) { + delete m_protocols; + m_protocols = nullptr; + } + + if (m_scene) { + delete m_scene; + m_scene = nullptr; + } + + if (m_workspace) { + delete m_workspace; + m_workspace = nullptr; + } + + // Includes the output channel; no Session-owned timers or queued receivers + // should survive just because somebody retains the Session's identity. + const auto components = children(); + qDeleteAll(components); + + if (m_socket) { + delete m_socket; + m_socket = nullptr; + } +} + +Workspace *Session::workspace() const +{ + return m_workspace ? m_workspace->workspace() : nullptr; +} + +bool Session::subscribeLogind(const QString &path) +{ + if (isShuttingDown() || path.isEmpty() || path == QStringLiteral("/")) + return false; + if (!m_logindPath.isEmpty()) + return m_logindPath == path; + + auto bus = QDBusConnection::systemBus(); + const auto service = Logind::serviceName(); + const auto interface = Logind::sessionIfaceName(); + if (!bus.connect(service, path, interface, "Lock", this, SLOT(onLogindLock()))) + return false; + if (!bus.connect(service, path, interface, "Unlock", this, SLOT(onLogindUnlock()))) { + bus.disconnect(service, path, interface, "Lock", this, SLOT(onLogindLock())); + return false; + } + + m_logindPath = path; + return true; +} + +void Session::unsubscribeLogind() +{ + if (m_logindPath.isEmpty()) + return; + const auto path = std::exchange(m_logindPath, QString()); + + auto bus = QDBusConnection::systemBus(); + const auto service = Logind::serviceName(); + const auto interface = Logind::sessionIfaceName(); + bus.disconnect(service, path, interface, "Lock", this, SLOT(onLogindLock())); + bus.disconnect(service, path, interface, "Unlock", this, SLOT(onLogindUnlock())); +} + +void Session::onLogindLock() +{ + if (!m_logindPath.isEmpty()) + Q_EMIT lock(this); +} + +void Session::onLogindUnlock() +{ + if (!m_logindPath.isEmpty()) + Q_EMIT unlock(this); +} + +void Session::setActive(bool active) +{ + if ((active && m_shuttingDown) || m_active == active) + return; + + m_active = active; + if (!active) + Q_EMIT activeChanged(false); + + if (active) + m_desktop->activate(); + else + m_desktop->deactivate(); + + if (active) + Q_EMIT activeChanged(true); +} + +bool Session::ownsClient(WClient *client) const +{ + auto *server = WaylandServer::instance(); + + return server && server->sessionManager()->sessionForClient(client).get() == this; +} + +void Session::attachInterface(WServerInterface *interface) +{ + if (m_shuttingDown) { + delete interface; + return; + } + + if (m_interfaces.contains(interface)) + return; + + interface->setOwnsSocket(m_socket); + if (!interface->server()) + WaylandServer::instance()->server()->attach(interface); + + if (auto *object = dynamic_cast(interface)) { + object->setParent(WaylandServer::instance()->server()); + connect(object, &QObject::destroyed, this, [this, interface] { + m_interfaces.removeOne(interface); + }); + } + + m_interfaces.append(interface); +} + +WForeignToplevel *Session::foreignToplevel() const +{ + return m_foreignToplevel; +} + +WExtForeignToplevelListV1 *Session::toplevelList() const +{ + return m_toplevelList; +} + +void Session::registerWindow(SurfaceWrapper *window) +{ + m_desktop->registerWindow(window); +} + +void Session::unregisterWindow(SurfaceWrapper *window) +{ + m_desktop->unregisterWindow(window); +} diff --git a/src/session/session.h b/src/session/session.h new file mode 100644 index 0000000000..9f0e4128a4 --- /dev/null +++ b/src/session/session.h @@ -0,0 +1,151 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "wglobal.h" +#include "desktop/desktopenvironment.h" + +#include +#include + +#ifndef DISABLE_XWAYLAND +#include +#endif + +Q_MOC_INCLUDE("workspace/workspace.h") +Q_MOC_INCLUDE("treelanduserconfig.hpp") +Q_MOC_INCLUDE("session/sessionoutputmanager.h") +Q_MOC_INCLUDE("session/sessionswitcher.h") +Q_MOC_INCLUDE("input/inputmanager.h") +Q_MOC_INCLUDE("wallpaper/wallpapermanager.h") + +class Workspace; +class SurfaceWrapper; +class TreelandUserConfig; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WServerInterface; +class WClient; +class WSocket; +#ifndef DISABLE_XWAYLAND +class WXWayland; +#endif +class WForeignToplevel; +class WExtForeignToplevelListV1; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class SessionSeatManager; +class SessionProtocols; +class SessionPrelaunch; +class SessionScene; +class SessionWorkspace; +class SessionMultitaskView; +class SessionOutputManager; +class SessionSwitcher; +class InputManager; +class WallpaperManager; +#ifndef DISABLE_XWAYLAND +class SettingManager; +#endif +class WallpaperLauncher; +class ForeignToplevelManagerInterfaceV3; + +class Session : public QObject { + Q_OBJECT + QML_ANONYMOUS + Q_PROPERTY(bool active READ isActive NOTIFY activeChanged FINAL) +public: + ~Session(); + + void shutdown(); + bool isShuttingDown() const { return m_shuttingDown; } + + DesktopEnvironment *desktop() const { return m_desktop; }; + const QString &id() const { return m_id; }; + const QString &logindPath() const { return m_logindPath; } + bool subscribeLogind(const QString &path); + void unsubscribeLogind(); + uid_t uid() const { return m_uid; }; + const QString &username() const { return m_username; }; + WSocket *socket() const { return m_socket; }; +#ifndef DISABLE_XWAYLAND + WXWayland *xwayland() const { return m_xwayland; }; + quint32 noTitlebarAtom() const { return m_noTitlebarAtom; }; +#endif + Workspace *workspace() const; + SessionWorkspace *sessionWorkspace() const { return m_workspace; } + SessionMultitaskView *multitaskView() const { return m_multitaskView; } + DesktopSurfaceModel *windows() const { return m_desktop ? m_desktop->windows() : nullptr; }; + TreelandUserConfig *config() const { return m_config; }; + SessionSeatManager *seatManager() const { return m_seatManager; }; + SessionProtocols *protocols() const { return m_protocols; }; + SessionPrelaunch *prelaunch() const { return m_prelaunch; }; + SessionScene *scene() const { return m_scene; }; + SessionOutputManager *outputManager() const { return m_outputManager; }; + SessionSwitcher *switcher() const { return m_desktop ? m_desktop->switcher() : nullptr; }; + InputManager *inputManager() const { return m_desktop ? m_desktop->input() : nullptr; }; + WallpaperManager *wallpaperManager() const { return m_desktop ? m_desktop->wallpaper() : nullptr; }; + + ForeignToplevelManagerInterfaceV3 *windowManagement() const { return m_windowManagement; }; + WForeignToplevel *foreignToplevel() const; + WExtForeignToplevelListV1 *toplevelList() const; + + bool isActive() const { return m_active; }; + bool ownsClient(WClient *client) const; + void attachInterface(WServerInterface *interface); + void detachInterface(WServerInterface *interface); + + void registerWindow(SurfaceWrapper *window); + void unregisterWindow(SurfaceWrapper *window); + +Q_SIGNALS: + void activeChanged(bool active); + void aboutToBeDestroyed(); + void lock(Session *session); + void unlock(Session *session); + +private Q_SLOTS: + void onLogindLock(); + void onLogindUnlock(); + +private: + void beginShutdown(); + void setActive(bool active); + +private: + friend class SessionManager; + friend class SurfaceProtocolController; + + void closeClients(); + + DesktopEnvironment *m_desktop = nullptr; + SessionSeatManager *m_seatManager = nullptr; + SessionProtocols *m_protocols = nullptr; + SessionPrelaunch *m_prelaunch = nullptr; + SessionScene *m_scene = nullptr; + SessionWorkspace *m_workspace = nullptr; + SessionMultitaskView *m_multitaskView = nullptr; + SessionOutputManager *m_outputManager = nullptr; + QList m_interfaces; + QPointer m_windowManagement; + QPointer m_foreignToplevel; + QPointer m_toplevelList; + TreelandUserConfig *m_config = nullptr; + WSocket *m_socket = nullptr; + QString m_id; + QString m_logindPath; + uid_t m_uid = 0; + QString m_username = {}; +#ifndef DISABLE_XWAYLAND + WXWayland *m_xwayland = nullptr; + quint32 m_noTitlebarAtom = XCB_ATOM_NONE; + SettingManager *m_settingManager = nullptr; + QThread *m_settingManagerThread = nullptr; +#endif + bool m_active = false; + bool m_shuttingDown = false; + bool m_shutdownStarted = false; +}; diff --git a/src/session/sessioncomponent.cpp b/src/session/sessioncomponent.cpp new file mode 100644 index 0000000000..7ee64fe762 --- /dev/null +++ b/src/session/sessioncomponent.cpp @@ -0,0 +1,46 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "sessioncomponent.h" +#include "session.h" + +SessionComponent::SessionComponent(Session *session) + : QObject(session) + , m_session(session) +{ + Q_ASSERT(session); + connect(session, &Session::activeChanged, this, &SessionComponent::setActive); +} + +Session *SessionComponent::session() const +{ + return m_session; +} + +bool SessionComponent::isActive() const +{ + return m_active; +} + +void SessionComponent::setActive(bool active) +{ + if (m_active == active) + return; + + m_active = active; + if (active) + activate(); + else + deactivate(); +} + +void SessionComponent::initializeActiveState() +{ + setActive(m_session->isActive()); +} + +void SessionComponent::activate() +{} + +void SessionComponent::deactivate() +{} diff --git a/src/session/sessioncomponent.h b/src/session/sessioncomponent.h new file mode 100644 index 0000000000..4c1b46b39c --- /dev/null +++ b/src/session/sessioncomponent.h @@ -0,0 +1,32 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include + +class Session; + +class SessionComponent : public QObject +{ + Q_OBJECT + QML_ANONYMOUS + Q_PROPERTY(Session *session READ session CONSTANT FINAL) +public: + explicit SessionComponent(Session *session); + + Session *session() const; + bool isActive() const; + +protected: + void initializeActiveState(); + virtual void activate(); + virtual void deactivate(); + +private: + void setActive(bool active); + QPointer m_session; + bool m_active = false; +}; diff --git a/src/session/sessioninputchannel.cpp b/src/session/sessioninputchannel.cpp new file mode 100644 index 0000000000..76a90c63a4 --- /dev/null +++ b/src/session/sessioninputchannel.cpp @@ -0,0 +1,152 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "sessioninputchannel.h" +#include "sessioninputcontext.h" +#include "session.h" +#include "sessionseatmanager.h" +#include "desktop/desktopenvironment.h" +#include "core/waylandserver.h" +#include "input/inputmanager.h" +#include "input/gesturemanager.h" +#include "input/compositorinputfilter.h" +#include "modules/shortcut/shortcutcontroller.h" +#include "modules/shortcut/shortcutmanager.h" + +#include +#include + +#include +#include +#include + +SessionInputChannel::SessionInputChannel(Session *owner, WaylandServer *runtime) + : SessionComponent(owner) + , m_runtime(runtime) + , m_input(owner->desktop()->input()) + , m_gestures(new GestureManager(this)) + , m_shortcuts(new ShortcutController(this, m_gestures)) + , m_filter(runtime->createInputFilter(new SessionInputContext(owner, runtime, this), + m_gestures, m_shortcuts, this)) +{ + m_shortcutProtocol = new ShortcutManagerV3(this, m_shortcuts, + [owner] { return owner->seatManager()->seats(); }); + owner->attachInterface(m_shortcutProtocol); + m_runtime->configureInputFilter(m_filter, m_shortcutProtocol); + m_filter->setEnabled(false); + m_filter->setAdmission([this](WSeat *seat, QInputEvent *event) { return admitEvent(seat, event); }); + m_input->setGestureManager(m_gestures); +} + +SessionInputChannel::~SessionInputChannel() +{ + deactivate(); + + if (m_filter) + delete m_filter; + + if (m_shortcuts) + delete m_shortcuts; + + if (m_gestures) + delete m_gestures; +} + +void SessionInputChannel::activate() +{ + m_gestures->cancel(); + m_suppressedKeys.clear(); + m_suppressedButtons = QGuiApplication::mouseButtons(); + m_touchStarted = false; + // Held physical keys belong to the desktop that received their press. + // Hide them from the new client's enter state until the real release. + for (auto *seat : session()->seatManager()->seats()) { + seat->clearFilteredKeys(); + for (auto *device : seat->deviceList()) { + if (device->type() != WInputDevice::Type::Keyboard) + continue; + auto *keyboard = wlr_keyboard_from_input_device(device->handle()); + if (!keyboard) + continue; + for (size_t i = 0; i < keyboard->num_keycodes; ++i) { + const auto key = keyboard->keycodes[i]; + m_suppressedKeys[seat].insert(key); + seat->addFilteredKey(key); + } + } + } + m_runtime->configureInputFilter(m_filter, m_shortcutProtocol); + m_filter->setEnabled(true); + m_input->activate(); +} + +void SessionInputChannel::deactivate() +{ + m_filter->setEnabled(false); + m_gestures->cancel(); + if (m_input) + m_input->deactivate(); + + if (m_shortcutProtocol) + m_shortcutProtocol->cancelCapture(); + + m_suppressedKeys.clear(); + m_suppressedButtons = Qt::NoButton; + m_touchStarted = false; +} + +bool SessionInputChannel::admitEvent(WSeat *seat, QInputEvent *event) +{ + if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { + const auto *key = static_cast(event); + const auto code = key->nativeVirtualKey(); + auto &suppressed = m_suppressedKeys[seat]; + if (suppressed.contains(code)) { + if (event->type() == QEvent::KeyRelease && !key->isAutoRepeat()) { + suppressed.remove(code); + seat->removeFilteredKey(code); + } + return false; + } + // Do not let a modifier held in the previous desktop turn a fresh + // key into a shortcut in this desktop. Drain until all keys release. + if (!suppressed.isEmpty()) { + if (event->type() == QEvent::KeyPress && code) { + suppressed.insert(code); + seat->addFilteredKey(code); + } + return false; + } + } + + if (event->type() == QEvent::MouseButtonPress) + m_suppressedButtons &= ~Qt::MouseButtons(static_cast(event)->button()); + + if (event->type() == QEvent::MouseButtonRelease) { + const auto button = static_cast(event)->button(); + if (m_suppressedButtons.testFlag(button)) { + m_suppressedButtons &= ~Qt::MouseButtons(button); + return false; + } + } + + if (event->type() == QEvent::MouseMove && m_suppressedButtons != Qt::NoButton) + return false; + + if (event->type() == QEvent::TouchBegin) { + m_touchStarted = true; + } else if (event->type() == QEvent::TouchUpdate && !m_touchStarted) { + return false; + } else if (event->type() == QEvent::TouchEnd || event->type() == QEvent::TouchCancel) { + const bool started = m_touchStarted; + m_touchStarted = false; + return started; + } + + return true; +} + +ShortcutManagerV3 *SessionInputChannel::shortcutProtocol() const +{ + return m_shortcutProtocol; +} diff --git a/src/session/sessioninputchannel.h b/src/session/sessioninputchannel.h new file mode 100644 index 0000000000..b6f8b291bc --- /dev/null +++ b/src/session/sessioninputchannel.h @@ -0,0 +1,56 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "sessioncomponent.h" + +#include + +#include +#include +#include + +class WaylandServer; +class InputManager; +class GestureManager; +class ShortcutController; +class ShortcutManagerV3; +class CompositorInputFilter; +QT_BEGIN_NAMESPACE +class QInputEvent; +QT_END_NAMESPACE +WAYLIB_SERVER_BEGIN_NAMESPACE +class WSeat; +WAYLIB_SERVER_END_NAMESPACE + +class SessionInputChannel : public SessionComponent +{ + Q_OBJECT +public: + SessionInputChannel(Session *session, WaylandServer *runtime); + ~SessionInputChannel() override; + + CompositorInputFilter *filter() const { return m_filter; }; + GestureManager *gestures() const { return m_gestures; }; + ShortcutController *shortcuts() const { return m_shortcuts; }; + ShortcutManagerV3 *shortcutProtocol() const; + +protected: + void activate() override; + void deactivate() override; + +private: + bool admitEvent(WAYLIB_SERVER_NAMESPACE::WSeat *seat, QInputEvent *event); + +private: + WaylandServer *const m_runtime = nullptr; + QPointer m_input; + GestureManager *const m_gestures = nullptr; + ShortcutController *const m_shortcuts = nullptr; + CompositorInputFilter *const m_filter = nullptr; + QHash> m_suppressedKeys; + Qt::MouseButtons m_suppressedButtons; + QPointer m_shortcutProtocol; + bool m_touchStarted = false; +}; diff --git a/src/session/sessioninputcontext.cpp b/src/session/sessioninputcontext.cpp new file mode 100644 index 0000000000..0165fe9c46 --- /dev/null +++ b/src/session/sessioninputcontext.cpp @@ -0,0 +1,145 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "sessioninputcontext.h" +#include "session.h" +#include "sessionseatmanager.h" +#include "core/waylandserver.h" +#include "core/rootsurfacecontainer.h" +#include "desktop/desktopenvironment.h" +#include "seat/seatmanager.h" + +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +SessionInputContext::SessionInputContext(Session *owner, WaylandServer *runtime, QObject *parent) + : QObject(parent), m_owner(owner), m_runtime(runtime) +{ +} + +bool SessionInputContext::available() const +{ + return m_runtime->isAvailable() && m_runtime->window() && m_runtime->backend() + && (!m_owner || m_owner->isActive()); +} + +bool SessionInputContext::locked() const +{ + return m_runtime->currentMode() == WaylandServer::CurrentMode::LockScreen; +} + +bool SessionInputContext::normal() const +{ + return m_runtime->currentMode() == WaylandServer::CurrentMode::Normal; +} + +bool SessionInputContext::switchVirtualTerminal(int number) +{ + auto *backend = m_runtime->backend(); + if (!available() || !backend->isSessionActive()) + return false; + + wlr_session_change_vt(backend->session(), number); + + return true; +} + +bool SessionInputContext::toggleDebugView() +{ + return available() && m_runtime->toggleDebugMenuBar(); +} + +bool SessionInputContext::ownsSeat(WSeat *seat) const +{ + if (!seat) + return false; + + return m_owner ? m_owner->seatManager()->seats().contains(seat) + : m_runtime->seatManager()->seats().contains(seat); +} + +WSeat *SessionInputContext::primarySeat() const +{ + return m_owner ? m_owner->seatManager()->fallbackSeat() : m_runtime->seat(); +} + +SeatSurfaceManager *SessionInputContext::seatContainer(WSeat *seat) const +{ + if (!ownsSeat(seat)) + return nullptr; + + auto *container = m_runtime->rootContainer()->getSeatContainer(seat); + auto *moving = container ? container->moveResizeSurface() : nullptr; + if (m_owner && moving && !m_owner->desktop()->surfaces()->hasObject(moving)) + return nullptr; + + return container; +} + +SurfaceWrapper *SessionInputContext::surface(WSurface *native) const +{ + if (!native) + return nullptr; + auto *root = native->rootSurface(); + if (!root) + return nullptr; + + auto *wrapper = m_runtime->rootContainer()->getSurface(root); + if (wrapper && !wrapper->renderingEnabled()) + return nullptr; + + if (m_owner && wrapper && !m_owner->desktop()->surfaces()->hasObject(wrapper)) + return nullptr; + + return wrapper; +} + +void SessionInputContext::activateSurface(WSurface *native, WSeat *seat, Qt::FocusReason reason) +{ + if (!available() || !ownsSeat(seat)) + return; + + auto *wrapper = native ? surface(native) : nullptr; + if (native && !wrapper) + return; + + if (wrapper) + m_runtime->updateSurfaceSeatInteraction(wrapper, seat); + + m_runtime->activateSurface(wrapper, reason, seat, true); +} + +void SessionInputContext::moveResize(WSeat *seat, const QPointF &delta) +{ + if (available() && seatContainer(seat)) + m_runtime->rootContainer()->doMoveResizeForSeat(seat, delta); +} + +void SessionInputContext::endMoveResize(WSeat *seat) +{ + if (available() && seatContainer(seat)) + m_runtime->rootContainer()->endMoveResizeForSeat(seat); +} + +void SessionInputContext::cancelMoveResize(WSeat *seat) +{ + if (available() && seatContainer(seat)) + m_runtime->rootContainer()->cancelMoveResizeForSeat(seat); +} + +void SessionInputContext::detectEdgeTiling(WSeat *seat) +{ + auto *container = seatContainer(seat); + if (!available() || !container) + return; + + auto *wrapper = container->moveResizeSurface(); + if (m_owner && wrapper && !m_owner->desktop()->surfaces()->hasObject(wrapper)) + return; + + m_runtime->rootContainer()->detectEdgeTilingForSeat(seat); +} diff --git a/src/session/sessioninputcontext.h b/src/session/sessioninputcontext.h new file mode 100644 index 0000000000..fd9f56920a --- /dev/null +++ b/src/session/sessioninputcontext.h @@ -0,0 +1,39 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "input/inputcontext.h" + +#include + +class Session; +class WaylandServer; + +class SessionInputContext final : public QObject, public InputContext +{ +public: + SessionInputContext(Session *owner, WaylandServer *runtime, QObject *parent); + + bool available() const override; + bool locked() const override; + bool normal() const override; + bool switchVirtualTerminal(int number) override; + bool toggleDebugView() override; + WAYLIB_SERVER_NAMESPACE::WSeat *primarySeat() const override; + SeatSurfaceManager *seatContainer(WAYLIB_SERVER_NAMESPACE::WSeat *seat) const override; + SurfaceWrapper *surface(WAYLIB_SERVER_NAMESPACE::WSurface *surface) const override; + void activateSurface(WAYLIB_SERVER_NAMESPACE::WSurface *surface, + WAYLIB_SERVER_NAMESPACE::WSeat *seat, Qt::FocusReason reason) override; + void moveResize(WAYLIB_SERVER_NAMESPACE::WSeat *seat, const QPointF &delta) override; + void endMoveResize(WAYLIB_SERVER_NAMESPACE::WSeat *seat) override; + void cancelMoveResize(WAYLIB_SERVER_NAMESPACE::WSeat *seat) override; + void detectEdgeTiling(WAYLIB_SERVER_NAMESPACE::WSeat *seat) override; + +private: + bool ownsSeat(WAYLIB_SERVER_NAMESPACE::WSeat *seat) const; + +private: + Session *const m_owner = nullptr; + WaylandServer *const m_runtime = nullptr; +}; diff --git a/src/session/sessionmanager.cpp b/src/session/sessionmanager.cpp new file mode 100644 index 0000000000..fadc3326f8 --- /dev/null +++ b/src/session/sessionmanager.cpp @@ -0,0 +1,712 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "sessionmanager.h" +#include "sessionprelaunch.h" +#include "sessionscene.h" +#include "sessionworkspace.h" +#include "sessionmultitaskview.h" +#include "session.h" +#include "desktop/desktopenvironment.h" +#include "seatuserconfig.hpp" +#include "sessionprotocols.h" +#include "sessionseatmanager.h" +#include "sessionswitcher.h" +#include "sessionoutputmanager.h" +#include "sessionoutputchannel.h" +#include "sessioninputchannel.h" +#include "outputconfig.hpp" +#include +#include "dconfig/dconfigmanager.h" +#include "input/inputmanager.h" +#include "wallpaper/wallpapermanager.h" +#include "surface/surfacecontainer.h" +#include "seat/seatmanager.h" +#include "common/treelandlogging.h" +#include "core/rootsurfacecontainer.h" +#include "core/shellhandler.h" +#include "output/output.h" +#include "core/waylandserver.h" +#include "treelanduserconfig.hpp" +#include "wallpaper/wallpaperlauncher.h" +#include "workspace/workspace.h" +#ifndef DISABLE_XWAYLAND +#include "xsettings/settingmanager.h" +#endif +#include "surface/surfacewrapper.h" + +#include +#include +#include +#include +#include "modules/foreign-toplevel/foreigntoplevelmanagerv3.h" +#include +#ifndef DISABLE_XWAYLAND +#include +#endif + +#include + +#include +#ifndef DISABLE_XWAYLAND +#include +#endif + +#ifndef DISABLE_XWAYLAND +#define _DEEPIN_NO_TITLEBAR "_DEEPIN_NO_TITLEBAR" + +static void applySessionXSettings(SettingManager *settingManager, + const QString &theme, + qreal size, + const QString &imModule) +{ + if (!settingManager) { + qCDebug(lcTlXsettings) << "Skip XSettings sync: no SettingManager"; + return; + } + + const bool queued = QMetaObject::invokeMethod( + settingManager, + [settingManager, theme, size, imModule]() { + settingManager->setCursorTheme(theme); + settingManager->setCursorSize(size); + settingManager->setIMModule(imModule); + settingManager->apply(); + }, + Qt::QueuedConnection); + if (!queued) { + qCWarning(lcTlXsettings) << "Failed to queue XSettings sync" + << "theme:" << theme << "size:" << size + << "imModule:" << imModule; + } +} + +static xcb_atom_t internAtom(xcb_connection_t *connection, const char *name, bool onlyIfExists) +{ + if (!name || *name == 0) + return XCB_NONE; + + xcb_intern_atom_cookie_t cookie = xcb_intern_atom(connection, onlyIfExists, strlen(name), name); + xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(connection, cookie, 0); + + if (!reply) + return XCB_NONE; + + xcb_atom_t atom = reply->atom; + free(reply); + + return atom; +} +#endif + +Session *SessionManager::activeSessionObject() const +{ + return m_activeSession.lock().get(); +} + +std::shared_ptr SessionManager::sessionForClient(WClient *client) const +{ + if (!client) + return nullptr; + + for (auto *socket = client->socket(); socket; socket = socket->parentSocket()) { + if (auto session = sessionForSocket(socket)) + return session; + } + return nullptr; +} + +bool SessionManager::isActiveWindow(SurfaceWrapper *window) const +{ + if (!window) + return false; + + if (window->session()) + return window->renderingEnabled(); + + return !activeSessionObject(); +} + +SessionManager::SessionManager(QObject *parent) + : QObject(parent) +{ +} + +SessionManager::~SessionManager() +{ + const auto sessions = m_sessions; + for (const auto &session : sessions) { + session->shutdown(); + } + + m_sessions.clear(); + if (m_wallpaperLauncher) { + delete m_wallpaperLauncher; + m_wallpaperLauncher = nullptr; + } +} + +void SessionManager::syncActiveSessionXWaylandPrimaryOutput() +{ +#ifndef DISABLE_XWAYLAND + const auto *primaryOutput = WaylandServer::instance()->rootSurfaceContainer()->primaryOutput(); + if (!primaryOutput) + return; + + auto session = m_activeSession.lock(); + if (!session) + return; + + const QString primaryOutputName = primaryOutput->output()->name(); + auto *xwayland = session->xwayland(); + auto *connection = xwayland ? xwayland->xcbConnection() : nullptr; + auto *screen = xwayland ? xwayland->xcbScreen() : nullptr; + if (!connection || !screen) + return; + + const auto resourcesCookie = + xcb_randr_get_screen_resources_current(connection, screen->root); + auto *resources = + xcb_randr_get_screen_resources_current_reply(connection, resourcesCookie, nullptr); + if (!resources) + return; + + const int outputCount = xcb_randr_get_screen_resources_current_outputs_length(resources); + const auto *outputs = xcb_randr_get_screen_resources_current_outputs(resources); + for (int i = 0; i < outputCount; ++i) { + const auto outputInfoCookie = + xcb_randr_get_output_info(connection, outputs[i], resources->config_timestamp); + auto *outputInfo = + xcb_randr_get_output_info_reply(connection, outputInfoCookie, nullptr); + if (!outputInfo) + continue; + + const QString outputName = QString::fromUtf8( + reinterpret_cast(xcb_randr_get_output_info_name(outputInfo)), + xcb_randr_get_output_info_name_length(outputInfo)); + if (outputName == primaryOutputName) { + xcb_randr_set_output_primary(connection, screen->root, outputs[i]); + xcb_flush(connection); + free(outputInfo); + break; + } + free(outputInfo); + } + free(resources); +#endif +} + +/** + * Get the default session + * + * The default session is the session for the "dde" user. + * It manages the default Wayland socket and XWayland instance. + * + * @returns shared_ptr to the default session + */ +std::shared_ptr SessionManager::globalSession() const +{ + return sessionForUser("dde"); +} + +/** + * Check if the active session's WSocket is enabled + * + * @returns true if enabled, false otherwise + */ +bool SessionManager::activeSocketEnabled() const +{ + auto ptr = m_activeSession.lock(); + if (ptr && ptr->m_socket) + return ptr->m_socket->isEnabled(); + + return false; +} + +/** + * Set the active session's WSocket enabled state + * + * @param newEnabled New enabled state + */ +void SessionManager::setActiveSocketEnabled(bool newEnabled) +{ + auto ptr = m_activeSession.lock(); + if (ptr && ptr->m_socket) { + const auto global = globalSession(); + ptr->m_socket->setEnabled(newEnabled, global ? global->socket() : nullptr); + } else { + qCWarning(lcTlCore) << "Can't set enabled for empty socket!"; + } +} + +/** + * Remove a session from the session list + * + * @param session The session to remove + */ +void SessionManager::removeSession(std::shared_ptr session) +{ + if (!session || session->isShuttingDown()) + return; + + session->beginShutdown(); + if (m_activeSession.lock() == session) { + const auto fallback = globalSession(); + if (fallback && fallback != session) + updateActiveUserSession(fallback->username(), fallback->id()); + else + m_activeSession.reset(); + session->workspace()->clearActivedSurface(); + WaylandServer::instance()->activateSurface(nullptr); + } + + // Keep the Session registered throughout resource destruction so callbacks + // can still resolve its client ownership. Extra shared_ptrs must not defer it. + session->shutdown(); + for (auto s : std::as_const(m_sessions)) { + if (s.get() == session.get()) { + m_sessions.removeOne(s); + break; + } + } +} + +/** + * Ensure a session exists for the given username, creating it if necessary + * + * @param id An existing logind session ID + * @param username Username to ensure session for + * @returns Session for the given username, or nullptr on failure + */ +std::shared_ptr SessionManager::ensureSession(const QString &id, QString username) +{ + const auto owner = sessionForId(id); + if (owner && owner->username() != username) { + qCWarning(lcTlGreeter) << "Logind session id already belongs to another desktop:" << id; + return nullptr; + } + const auto previous = sessionForUser(username); + if (previous && previous->id() != id) { + if (previous->id() == QStringLiteral("0")) { + qCWarning(lcTlGreeter) << "Cannot replace the bootstrap desktop:" << username << id; + return nullptr; + } + qCInfo(lcTlGreeter) << "Replacing desktop for a new login:" + << username << previous->id() << id; + removeSession(previous); + } + // WaylandServer lambda to create WSocket and WXWayland + auto createWSocket = [this]() { + // Create WSocket + auto socket = new WSocket(true, nullptr); + if (!socket->autoCreate()) { + qCCritical(lcTlCore) << "Failed to create Wayland socket"; + delete socket; + return static_cast(nullptr); + } + // Connect signals + connect(socket, &WSocket::fullServerNameChanged, this, [this] { + if (m_activeSession.lock()) + Q_EMIT socketFileChanged(); + }); + // Add socket to server + WaylandServer::instance()->addSocket(socket); + return socket; + }; +#ifndef DISABLE_XWAYLAND + auto createXWayland = [this](Session *owner, WSocket *socket) { + // Create xwayland + auto *xwayland = WaylandServer::instance()->createXWayland(owner->seatManager()->fallbackSeat()); + if (!xwayland) { + qCCritical(lcTlCore) << "Failed to create XWayland instance"; + return static_cast(nullptr); + } + // Bind xwayland to socket + xwayland->setOwnsSocket(socket); + // Connect signals + connect(xwayland, &WXWayland::ready, this, [this, xwayland] { + Q_EMIT xwaylandAuthChanged(); + syncActiveSessionXWaylandPrimaryOutput(); + if (auto session = sessionForXWayland(xwayland); session && !session->isShuttingDown()) { + session->m_noTitlebarAtom = + internAtom(session->m_xwayland->xcbConnection(), _DEEPIN_NO_TITLEBAR, false); + if (!session->m_noTitlebarAtom) { + qCWarning(lcTlInput) << "Failed to intern atom:" << _DEEPIN_NO_TITLEBAR; + } + session->m_settingManager = new SettingManager(session->m_xwayland->xcbConnection()); + session->m_settingManagerThread = new QThread(); + + session->m_settingManager->moveToThread(session->m_settingManagerThread); + + const qreal scale = session->outputManager()->effectiveScale(); + const auto renderWindow = WaylandServer::instance()->window(); + connect(session->m_settingManagerThread, + &QThread::started, + this, + [this, settingManager = QPointer(session->m_settingManager), + scale, + renderWindow, + config = session->config()] { + if (!settingManager) { + qCDebug(lcTlXsettings) + << "Skip initial XSettings sync: no SettingManager"; + return; + } + + const QString cursorTheme = + config ? config->cursorThemeName() : QString(); + const qreal cursorSize = config ? config->cursorSize() : 24; + const QString imModule = config ? config->x11GtkIMModule() : QString(); + + const bool queued = QMetaObject::invokeMethod( + settingManager, + [settingManager, scale, cursorTheme, cursorSize, imModule]() { + settingManager->setGlobalScale(scale); + settingManager->setCursorTheme(cursorTheme); + settingManager->setCursorSize(cursorSize); + settingManager->setIMModule(imModule); + settingManager->apply(); + }, + Qt::QueuedConnection); + if (!queued) { + qCWarning(lcTlXsettings) + << "Failed to queue initial XSettings sync" + << "cursorTheme:" << cursorTheme << "cursorSize:" << cursorSize + << "imModule:" << imModule << "scale:" << scale; + } + QObject::connect( + renderWindow, + &WOutputRenderWindow::effectiveDevicePixelRatioChanged, + this, + &SessionManager::syncSessionScaleSettings, + Qt::UniqueConnection); + }); + connect(session->m_settingManagerThread, &QThread::finished, session->m_settingManagerThread, &QThread::deleteLater); + session->m_settingManagerThread->start(); + } + }); + return xwayland; + }; +#endif + // Check if session already exists for user + if (auto session = sessionForUser(username)) { + if (session->isShuttingDown()) + return nullptr; + // Ensure it has a socket and xwayland + if (!session->m_socket) { + auto *socket = createWSocket(); + if (!socket) { + m_sessions.removeOne(session); + return nullptr; + } + session->m_socket = socket; + } +#ifndef DISABLE_XWAYLAND + if (!session->m_xwayland) { + auto *xwayland = createXWayland(session.get(), session->m_socket); + if (!xwayland) { + session->m_socket->close(); + m_sessions.removeOne(session); + return nullptr; + } + + session->m_xwayland = xwayland; + } +#endif + + return session; + } + // Session does not exist, create new session with deleter + auto passwd = getpwnam(username.toLocal8Bit().data()); + if (!passwd) { + qCWarning(lcTlCore) << "Failed to get passwd entry for user:" << username; + return nullptr; + } + auto session = std::make_shared(); + session->m_id = id; + session->m_username = username; + session->m_uid = passwd->pw_uid; + session->m_config = DConfigManager::instance()->userConfig(username); + auto *runtime = WaylandServer::instance(); + session->m_workspace = new SessionWorkspace(session.get(), runtime); + auto *workspace = session->workspace(); + session->m_desktop = new DesktopEnvironment(session->m_config, workspace, runtime, + [username](const QString &seatName) { + return DConfigManager::instance()->userSeatConfig(username, seatName); + }, + [owner = session.get()] { return owner->seatManager()->seats(); }, + [this](wlr_output *excluded) { return wallpaperLibrary(excluded); }, session.get()); + + session->m_socket = createWSocket(); + if (!session->m_socket) + return nullptr; + + session->m_multitaskView = new SessionMultitaskView(session.get(), runtime); + session->desktop()->attachMultitaskView(session->m_multitaskView); + session->m_scene = new SessionScene(session.get()); + session->desktop()->attachInputChannel(new SessionInputChannel(session.get(), runtime)); + session->m_seatManager = new SessionSeatManager(session.get()); + session->m_protocols = new SessionProtocols(session.get()); + session->m_prelaunch = new SessionPrelaunch(session.get(), runtime); + auto *outputProtocol = new WOutputManagerV1; + session->attachInterface(outputProtocol); + auto *channel = new SessionOutputChannel(session.get(), runtime->outputHardware(), runtime->rootContainer()); + session->m_outputManager = new SessionOutputManager(DConfigManager::instance()->globalConfig(), + [](const QString &outputId) { + return DConfigManager::instance()->outputConfig(outputId); + }, session->desktop()->surfaces(), channel, runtime->outputHardware(), runtime->backend(), outputProtocol, session->desktop()); + session->desktop()->attachOutputs(session->m_outputManager); + WaylandServer::instance()->initializeSessionProtocols(session.get()); + + // Protocol tests and headless runs do not launch the wallpaper producer. + if (!m_wallpaperLauncher && !qEnvironmentVariableIsSet("TREELAND_DISABLE_WALLPAPER")) { + m_wallpaperLauncher = new WallpaperLauncher(session->socket()->rootSocket()); + m_wallpaperLauncher->start(); + } + +#ifndef DISABLE_XWAYLAND + session->m_xwayland = createXWayland(session.get(), session->m_socket); + if (!session->m_xwayland) + return nullptr; +#endif + + session->m_socket->setEnabled(false, globalSession() ? globalSession()->socket() : nullptr); + // Forward the Session that owns the logind subscription. + connect(session.get(), &Session::lock, this, &SessionManager::sessionLock); + connect(session.get(), &Session::unlock, this, &SessionManager::sessionUnlock); + // Add session to list + m_sessions.append(session); + + return session; +} + + +/** + * Find the session for the given logind session id + * + * @param id Session ID to find session for + * @returns Session for the given id, or nullptr if not found + */ +std::shared_ptr SessionManager::sessionForId(const QString &id) const +{ + for (const auto &session : std::as_const(m_sessions)) { + if (session && session->m_id == id) + return session; + } + + return nullptr; +} + +/** + * Find the session for the given uid + * + * @param uid User ID to find session for + * @returns Session for the given uid, or nullptr if not found + */ +std::shared_ptr SessionManager::sessionForUid(uid_t uid) const +{ + for (const auto &session : std::as_const(m_sessions)) { + if (session && session->m_uid == uid) + return session; + } + + return nullptr; +} + +/** + * Find the session for the given username + * + * @param username Username to find session for + * @returns Session for the given username, or nullptr if not found + */ +std::shared_ptr SessionManager::sessionForUser(const QString &username) const +{ + for (const auto &session : std::as_const(m_sessions)) { + if (session && session->m_username == username) + return session; + } + + return nullptr; +} + +#ifndef DISABLE_XWAYLAND +/** + * Find the session for the given WXWayland + * + * @param xwayland WXWayland to find session for + * @returns Session for the given xwayland, or nullptr if not found + */ +std::shared_ptr SessionManager::sessionForXWayland(WXWayland *xwayland) const +{ + for (const auto &session : std::as_const(m_sessions)) { + if (session && session->m_xwayland == xwayland) + return session; + } + + return nullptr; +} +#endif + +/** + * Find the session for the given WSocket + * + * @param socket WSocket to find session for + * @returns Session for the given socket, or nullptr if not found + */ +std::shared_ptr SessionManager::sessionForSocket(WSocket *socket) const +{ + for (const auto &session : std::as_const(m_sessions)) { + if (session && session->m_socket == socket) + return session; + } + + return nullptr; +} + +bool SessionManager::isDDEUserClient(WClient *client) +{ + // The dde sentinel session is created at startup, but defensive null + // checks guard against it being absent (see issue #1464): dereferencing + // a null globalSession() here previously caused a SIGSEGV. + if (!client) + return false; + + const auto global = globalSession(); + if (!global || !global->socket()) + return false; + + return client->socket() == global->socket(); +} + +void SessionManager::syncSessionScaleSettings() +{ +#ifndef DISABLE_XWAYLAND + for (const auto &session : std::as_const(m_sessions)) { + if (!session || !session->m_settingManager) + continue; + + const qreal scale = session->outputManager()->effectiveScale(); + const auto settings = QPointer(session->m_settingManager); + QMetaObject::invokeMethod(settings, [settings, scale] { + if (!settings) + return; + + settings->setGlobalScale(scale); + settings->apply(); + }, Qt::QueuedConnection); + } +#endif +} + +void SessionManager::syncActiveSessionXSettings() +{ +#ifndef DISABLE_XWAYLAND + const auto session = m_activeSession.lock(); + if (!session) { + qCDebug(lcTlXsettings) << "Skip XSettings sync: no active session"; + return; + } + + if (!session->m_settingManager) { + qCDebug(lcTlXsettings) + << "Skip XSettings sync: no SettingManager for session" << session->username(); + return; + } + + const auto *config = session->config(); + if (!config) { + qCWarning(lcTlXsettings) << "Cannot sync XSettings: user config is unavailable"; + return; + } + + applySessionXSettings(session->m_settingManager, + config->cursorThemeName(), + config->cursorSize(), + config->x11GtkIMModule()); +#endif +} + +/** + * Update the active session to the given uid, creating it if necessary. + * This will update XWayland visibility and emit socketFileChanged if the + * active session changed. + * + * @param username Username to set as active session + */ +void SessionManager::updateActiveUserSession(const QString &username, const QString &id) +{ + commitActiveUserSession(prepareActiveUserSession(username, id)); +} + +SessionManager::ActiveSessionUpdate SessionManager::prepareActiveUserSession(const QString &username, + const QString &id) +{ + // Get new session for uid, creating if necessary + auto session = ensureSession(id, username); + if (!session) { + qCWarning(lcTlInput) << "Failed to ensure session for user" << username; + return {}; + } + + // Replacing the old desktop in ensureSession() may have activated the greeter. + const auto previous = m_activeSession.lock(); + const bool activeSessionChanged = previous != session; + if (activeSessionChanged) { + auto *server = WaylandServer::instance(); + if (previous) + previous->setActive(false); + server->rootSurfaceContainer()->dismissAllPopups(); + for (auto *seat : server->seatManager()->seats()) { + server->rootSurfaceContainer()->cancelMoveResizeForSeat(seat); + server->activateSurface(nullptr, Qt::OtherFocusReason, seat); + } + // Publish the workspace through one path for all activation callers. + m_activeSession = session; + server->seatManager()->activateSessionSeats(session->seatManager()); + server->shellHandler()->setWorkspace(session->workspace()); + + // Update socket enabled state before publishing activation notifications. + if (previous && previous->m_socket) { + const auto global = globalSession(); + previous->m_socket->setEnabled(false, global ? global->socket() : nullptr); + } + session->m_socket->setEnabled(true); + session->setActive(true); + } + + return { session, activeSessionChanged }; +} + +void SessionManager::commitActiveUserSession(const ActiveSessionUpdate &update) +{ + if (!update || m_activeSession.lock() != update.session) + return; + + if (update.activeSessionChanged) { + Q_EMIT socketFileChanged(); + // Notify session changed through DBus, treeland-sd will listen it to update envs + Q_EMIT sessionChanged(); + syncActiveSessionXWaylandPrimaryOutput(); + } + + qCInfo(lcTlCore) << "Listening on:" << update.session->m_socket->fullServerName(); + syncActiveSessionXSettings(); + syncSessionScaleSettings(); + auto *server = WaylandServer::instance(); + if (update.activeSessionChanged && server->currentMode() == WaylandServer::CurrentMode::Normal) + server->activateSurface(update.session->workspace()->current()->latestActiveSurface()); +} + +WallpaperManager::WallpaperLibrary SessionManager::wallpaperLibrary(wlr_output *excluded) const +{ + WallpaperManager::WallpaperLibrary result; + for (const auto &owner : m_sessions) { + if (owner->isShuttingDown()) + continue; + const auto used = owner->wallpaperManager()->globalValidWallpaper(excluded); + for (auto it = used.cbegin(); it != used.cend(); ++it) + result.insert(it.key(), it.value()); + } + + return result; +} diff --git a/src/session/sessionmanager.h b/src/session/sessionmanager.h new file mode 100644 index 0000000000..6369592a4d --- /dev/null +++ b/src/session/sessionmanager.h @@ -0,0 +1,67 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "session.h" + +class SessionManager : public QObject { + Q_OBJECT +public: + explicit SessionManager(QObject *parent = nullptr); + ~SessionManager(); + + const QList> &sessions() const { return m_sessions; }; + std::weak_ptr activeSession() const { return m_activeSession; }; + Session *activeSessionObject() const; + std::shared_ptr sessionForClient(WClient *client) const; + bool isActiveWindow(SurfaceWrapper *window) const; + std::shared_ptr globalSession() const; + + bool activeSocketEnabled() const; + void setActiveSocketEnabled(bool newEnabled); + + struct ActiveSessionUpdate + { + std::shared_ptr session; + bool activeSessionChanged = false; + + explicit operator bool() const noexcept + { + return session != nullptr; + } + }; + + ActiveSessionUpdate prepareActiveUserSession(const QString &username, const QString &id); + void commitActiveUserSession(const ActiveSessionUpdate &update); + void updateActiveUserSession(const QString &username, const QString &id); + void removeSession(std::shared_ptr session); + std::shared_ptr sessionForId(const QString &id) const; + std::shared_ptr sessionForUid(uid_t uid) const; + std::shared_ptr sessionForUser(const QString &username) const; +#ifndef DISABLE_XWAYLAND + std::shared_ptr sessionForXWayland(WXWayland *xwayland) const; +#endif + std::shared_ptr sessionForSocket(WSocket *socket) const; + bool isDDEUserClient(WClient *client); + void syncActiveSessionXSettings(); + void syncSessionScaleSettings(); + void syncActiveSessionXWaylandPrimaryOutput(); + // Create a background user session without changing the active desktop. + std::shared_ptr ensureSession(const QString &id, QString username); + +Q_SIGNALS: + void socketFileChanged(); + void sessionChanged(); + void sessionLock(Session *session); + void sessionUnlock(Session *session); + void xwaylandAuthChanged(); + +private: + WallpaperManager::WallpaperLibrary wallpaperLibrary(wlr_output *excluded) const; + +private: + std::weak_ptr m_activeSession; + QList> m_sessions; + WallpaperLauncher *m_wallpaperLauncher { nullptr }; +}; diff --git a/src/session/sessionmultitaskview.cpp b/src/session/sessionmultitaskview.cpp new file mode 100644 index 0000000000..ab6c67dfe8 --- /dev/null +++ b/src/session/sessionmultitaskview.cpp @@ -0,0 +1,116 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "sessionmultitaskview.h" + +#include "session.h" +#include "core/waylandserver.h" +#include "core/rootsurfacecontainer.h" +#include "desktop/desktopenvironment.h" +#include "workspace/workspace.h" + +SessionMultitaskView::SessionMultitaskView(Session *session, WaylandServer *runtime) + : SessionComponent(session) + , m_runtime(runtime) + , m_desktop(session->desktop()) +{ + initializeActiveState(); +} + +SessionMultitaskView::~SessionMultitaskView() +{ + reset(); +} + +IMultitaskView *SessionMultitaskView::view() const +{ + return qobject_cast(m_view.data()); +} + +qreal SessionMultitaskView::partialFactor() const +{ + auto *impl = view(); + return isActive() && impl ? impl->partialFactor() : 0.0; +} + +void SessionMultitaskView::setStatus(IMultitaskView::Status status) +{ + if (isActive()) { + if (auto *impl = view()) + impl->setStatus(status); + } +} + +void SessionMultitaskView::toggleMultitaskView(IMultitaskView::ActiveReason reason) +{ + if (!isActive() || !m_desktop || !m_runtime->isNormalOrMultitaskview()) + return; + // A gesture finish must still run exit() after QML hides the view when + // animations are disabled, so that focus and the runtime mode are restored. + if (m_view && m_closing && reason != IMultitaskView::Gesture) + return; + if (!m_view) { + m_closing = false; + m_view = m_runtime->createMultitaskView(m_desktop); + if (!m_view) + return; + Q_ASSERT(view()); + m_view->setZ(RootSurfaceContainer::OverlayZOrder); + connect(m_view, &QQuickItem::visibleChanged, + this, &SessionMultitaskView::onVisibleChanged); + m_desktop->workspace()->setSwitcherEnabled(false); + } + if (auto *impl = view()) + impl->toggleMultitaskView(reason); +} + +void SessionMultitaskView::updatePartialFactor(qreal progress) +{ + if (isActive()) { + if (auto *impl = view()) + impl->updatePartialFactor(progress); + } +} + +void SessionMultitaskView::commitGesture(bool triggered) +{ + if (isActive()) { + if (auto *impl = view()) + impl->commitGesture(triggered); + } +} + +void SessionMultitaskView::immediatelyExit() +{ + if (auto *impl = view()) + impl->immediatelyExit(); + reset(); +} + +void SessionMultitaskView::deactivate() +{ + immediatelyExit(); +} + +void SessionMultitaskView::onVisibleChanged() +{ + if (m_view && !m_view->isVisible()) { + m_closing = true; + if (m_desktop) + m_desktop->workspace()->setSwitcherEnabled(true); + m_view->deleteLater(); + } +} + +void SessionMultitaskView::reset() +{ + if (m_view) { + disconnect(m_view, nullptr, this, nullptr); + delete m_view.data(); + m_view = nullptr; + } + + m_closing = false; + if (m_desktop && m_desktop->workspace()) + m_desktop->workspace()->setSwitcherEnabled(true); +} diff --git a/src/session/sessionmultitaskview.h b/src/session/sessionmultitaskview.h new file mode 100644 index 0000000000..16f6089707 --- /dev/null +++ b/src/session/sessionmultitaskview.h @@ -0,0 +1,41 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "sessioncomponent.h" +#include "interfaces/multitaskviewinterface.h" + +#include + +class DesktopEnvironment; +class WaylandServer; + +class SessionMultitaskView : public SessionComponent, public IMultitaskView +{ + Q_OBJECT + Q_INTERFACES(IMultitaskView) +public: + SessionMultitaskView(Session *session, WaylandServer *runtime); + ~SessionMultitaskView() override; + + qreal partialFactor() const override; + void setStatus(IMultitaskView::Status status) override; + void toggleMultitaskView(IMultitaskView::ActiveReason reason) override; + void updatePartialFactor(qreal progress) override; + void immediatelyExit() override; + void commitGesture(bool triggered) override; + +protected: + void deactivate() override; + +private: + IMultitaskView *view() const; + void onVisibleChanged(); + void reset(); + + WaylandServer *const m_runtime; + QPointer m_desktop; + QPointer m_view; + bool m_closing = false; +}; diff --git a/src/session/sessionoutputchannel.cpp b/src/session/sessionoutputchannel.cpp new file mode 100644 index 0000000000..640a029114 --- /dev/null +++ b/src/session/sessionoutputchannel.cpp @@ -0,0 +1,56 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "sessionoutputchannel.h" +#include "output/outputmanager.h" +#include "output/output.h" +#include "core/rootsurfacecontainer.h" + +#include + +SessionOutputChannel::SessionOutputChannel(Session *session, OutputManager *hardware, + RootSurfaceContainer *root) + : SessionComponent(session), m_hardware(hardware), m_root(root) +{ +} + +void SessionOutputChannel::activate() +{ + m_hardware->selectSession(session()); + Q_EMIT connected(); +} + +void SessionOutputChannel::setScale(WAYLIB_SERVER_NAMESPACE::WOutput *output, qreal scale) +{ + if (isActive()) + m_hardware->setScale(output, scale); +} + +void SessionOutputChannel::setPrimary(Output *output) +{ + if (isActive()) + m_root->setPrimaryOutput(output, true); +} + +void SessionOutputChannel::applyColor(Output *output, qreal brightness, uint32_t temperature, + std::function completed) +{ + if (!isActive()) { + if (completed) + completed(Output::CommitColorResult::Failed); + return; + } + + output->setOutputColor(brightness, temperature, std::move(completed)); +} + +void SessionOutputChannel::configure(WAYLIB_SERVER_NAMESPACE::WOutputManagerV1 *protocol, + wlr_output_configuration_v1 *configuration, bool onlyTest) +{ + if (!isActive()) { + protocol->sendResult(configuration, false); + return; + } + + m_hardware->testOrApplyConfiguration(protocol, configuration, onlyTest); +} diff --git a/src/session/sessionoutputchannel.h b/src/session/sessionoutputchannel.h new file mode 100644 index 0000000000..9efac202b2 --- /dev/null +++ b/src/session/sessionoutputchannel.h @@ -0,0 +1,44 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "output/output.h" +#include "sessioncomponent.h" + +#include + +class Output; +class OutputManager; +class RootSurfaceContainer; + +struct wlr_output_configuration_v1; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutputManagerV1; +class WOutput; +WAYLIB_SERVER_END_NAMESPACE + +class SessionOutputChannel : public SessionComponent +{ + Q_OBJECT +public: + SessionOutputChannel(Session *session, OutputManager *hardware, RootSurfaceContainer *root); + + void setScale(WAYLIB_SERVER_NAMESPACE::WOutput *output, qreal scale); + void setPrimary(Output *output); + void applyColor(Output *output, qreal brightness, uint32_t temperature, + std::function completed); + void configure(WAYLIB_SERVER_NAMESPACE::WOutputManagerV1 *protocol, + wlr_output_configuration_v1 *configuration, bool onlyTest); + +Q_SIGNALS: + void connected(); + +protected: + void activate() override; + +private: + OutputManager *const m_hardware = nullptr; + RootSurfaceContainer *const m_root = nullptr; +}; diff --git a/src/session/sessionoutputmanager.cpp b/src/session/sessionoutputmanager.cpp new file mode 100644 index 0000000000..e5a64759c6 --- /dev/null +++ b/src/session/sessionoutputmanager.cpp @@ -0,0 +1,377 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "sessionoutputmanager.h" +#include "desktop/desktopenvironment.h" +#include "dconfig/dconfigmanager.h" +#include "sessionoutputchannel.h" +#include "surface/surfacewrapper.h" +#include "common/treelandlogging.h" +#include "core/rootsurfacecontainer.h" +#include "output/outputmanager.h" +#include "output/output.h" +#include "outputconfig.hpp" +#include "treelandconfig.hpp" + +#include +#include + +#include +#include + +#include + +SessionOutputManager::SessionOutputManager(TreelandConfig *config, ConfigProvider outputConfiguration, + DesktopSurfaceModel *surfaces, SessionOutputChannel *channel, + OutputManager *hardware, WBackend *backend, + WOutputManagerV1 *protocol, QObject *parent) + : QObject(parent) + , m_config(config) + , m_outputConfiguration(std::move(outputConfiguration)) + , m_surfaces(surfaces) + , m_channel(channel) + , m_hardware(hardware) + , m_protocol(protocol) +{ + connect(channel, &SessionOutputChannel::connected, this, &SessionOutputManager::refresh); + // Drop removed outputs synchronously before their WOutput wrappers die; + // queued state publication must never retain a stale output pointer. + connect(backend, &WBackend::outputRemoved, + m_protocol, &WOutputManagerV1::removeOutput); + connect(m_protocol, &WOutputManagerV1::requestTestOrApply, + this, &SessionOutputManager::requestConfiguration); + connect(m_config, &TreelandConfig::configInitializeSucceed, + this, &SessionOutputManager::refresh); + connect(m_config, &TreelandConfig::configInitializeFailed, + this, &SessionOutputManager::refresh); + connect(m_hardware, &OutputManager::configurationChanged, + this, &SessionOutputManager::refresh, Qt::QueuedConnection); + connect(m_hardware, &OutputManager::outputsChanged, + this, &SessionOutputManager::refresh, Qt::QueuedConnection); + QMetaObject::invokeMethod(this, &SessionOutputManager::refresh, Qt::QueuedConnection); +} + +OutputConfig *SessionOutputManager::config(const QString &outputId) +{ + if (auto *config = m_configs.value(outputId)) + return config; + + auto *config = m_outputConfiguration(outputId); + connect(config, &OutputConfig::configInitializeSucceed, + this, &SessionOutputManager::refresh); + connect(config, &OutputConfig::configInitializeFailed, + this, &SessionOutputManager::refresh); + connect(config, &OutputConfig::valueChanged, + this, &SessionOutputManager::publishConfiguration, Qt::QueuedConnection); + m_configs.insert(outputId, config); + return config; +} + +void SessionOutputManager::setScale(WOutput *target, qreal scale) +{ + m_channel->setScale(target, scale); +} + +void SessionOutputManager::refresh() +{ + if (!configurationReady(m_config)) + return; + + bool ready = true; + for (auto *output : m_hardware->outputs()) + ready &= configurationReady(config(output->getOutputId())); + + if (!ready) + return; + + publishConfiguration(); +} + +qreal SessionOutputManager::effectiveScale() const +{ + qreal scale = 1.0; + for (auto *output : m_hardware->outputs()) { + if (output->output()->isEnabled()) + scale = qMax(scale, qreal(output->output()->scale())); + } + + return scale; +} + +qreal SessionOutputManager::scaleAt(const QPointF &position) +{ + for (auto *output : m_hardware->outputs()) { + if (outputState(output)->geometry().contains(position)) + return output->output()->scale(); + } + + return effectiveScale(); +} + +QPointF SessionOutputManager::defaultPosition(Output *target) +{ + qreal x = 0; + for (auto *output : m_hardware->outputs()) { + if (output == target) + break; + + const auto previous = outputState(output)->geometry(); + x = qMax(x, previous.right()); + } + + return QPointF(x, 0); +} + +QString SessionOutputManager::primaryOutputName() const +{ + const auto id = m_config->primaryOutputId(); + for (auto *output : m_hardware->outputs()) { + if (output->getOutputId() == id) + return output->output()->name(); + } + + const auto &outputs = m_hardware->outputs(); + + return outputs.isEmpty() ? QString() : outputs.first()->output()->name(); +} + +void SessionOutputManager::setPrimaryOutput(const QString &name) +{ + for (auto *output : m_hardware->outputs()) { + if (output->output()->name() != name) + continue; + + m_channel->setPrimary(output); + return; + } +} + +void SessionOutputManager::applyColor(Output *output, qreal brightness, uint32_t temperature, + std::function completed) +{ + m_channel->applyColor(output, brightness, temperature, std::move(completed)); +} + +void SessionOutputManager::publishConfiguration() +{ + if (!configurationReady(m_config)) + return; + QList states; + QSet seen; + for (auto *output : m_hardware->outputs()) { + auto *physical = output->output(); + if (seen.contains(physical)) + continue; + + seen.insert(physical); + auto *native = physical->handle(); + const auto position = physical->position(); + states.append(WOutputState { + .output = physical, + .enabled = physical->isEnabled(), + .mode = native->current_mode, + .x = position.x(), + .y = position.y(), + .customModeSize = QSize(native->width, native->height), + .customModeRefresh = native->refresh, + .transform = physical->orientation(), + .scale = physical->scale(), + .adaptiveSyncEnabled = native->adaptive_sync_status == WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED + }); + outputState(output)->arrangeLayerSurfaces(); + } + m_protocol->setOutputStates(states); + Q_EMIT desktopGeometryChanged(); +} + +void SessionOutputManager::requestConfiguration(wlr_output_configuration_v1 *configuration, bool onlyTest) +{ + m_channel->configure(m_protocol, configuration, onlyTest); +} + +SessionOutput *SessionOutputManager::outputState(Output *output) +{ + if (auto *state = m_outputs.value(output)) + return state; + + auto *state = new SessionOutput(this, output); + m_outputs.insert(output, state); + connect(state, &SessionOutput::validGeometryChanged, + this, &SessionOutputManager::desktopGeometryChanged); + connect(output, &QObject::destroyed, this, [this, output] { + delete m_outputs.take(output); + }); + + return state; +} + +SessionOutput::SessionOutput(SessionOutputManager *manager, Output *output) + : QObject(manager) + , m_windows(new SurfaceListModel(this)) + , m_minimized(new SurfaceFilterModel(m_windows)) + , m_output(output) + , m_surfaces(manager->surfaceRegistry()) +{ + m_minimized->setFilter([](SurfaceWrapper *surface) { return surface->isMinimized(); }); + m_exclusiveZone = output->compositorExclusiveZone(); + m_lastValidGeometry = validGeometry(); +} + +QRectF SessionOutput::geometry() const +{ + return m_output ? m_output->geometry() : QRectF(); +} + +QRectF SessionOutput::validGeometry() const +{ + return geometry().marginsRemoved(m_exclusiveZone); +} + +QList SessionOutput::layerSurfaces() const +{ + QList layers; + for (const auto &layer : m_layers) { + if (layer) + layers.append(layer.data()); + } + + return layers; +} + +void SessionOutput::addSurface(SurfaceWrapper *surface) +{ + Q_ASSERT(m_surfaces->hasObject(surface)); + if (!m_windows->hasSurface(surface)) + m_windows->addSurface(surface); + + if (surface->type() == SurfaceWrapper::Type::Layer && !m_layers.contains(surface)) + m_layers.append(surface); +} + +void SessionOutput::removeSurface(SurfaceWrapper *surface) +{ + m_layers.removeAll(surface); + if (m_windows->hasSurface(surface)) + m_windows->removeSurface(surface); +} + +void SessionOutput::addExclusiveZone(Qt::Edge edge, int value) +{ + Q_ASSERT(value > 0); + switch (edge) { + case Qt::TopEdge: + m_exclusiveZone.setTop(m_exclusiveZone.top() + value); + break; + case Qt::BottomEdge: + m_exclusiveZone.setBottom(m_exclusiveZone.bottom() + value); + break; + case Qt::LeftEdge: + m_exclusiveZone.setLeft(m_exclusiveZone.left() + value); + break; + case Qt::RightEdge: + m_exclusiveZone.setRight(m_exclusiveZone.right() + value); + break; + default: + Q_UNREACHABLE_RETURN(); + } +} + +void SessionOutput::arrangeLayerSurface(SurfaceWrapper *surface) +{ + WLayerSurface *layer = qobject_cast(surface->shellSurface()); + Q_ASSERT(layer); + if (!layer->handle()->initialized) { + return; + } + + auto validGeo = layer->exclusiveZone() == -1 ? geometry() : validGeometry(); + validGeo = validGeo.marginsRemoved(QMargins(layer->leftMargin(), + layer->topMargin(), + layer->rightMargin(), + layer->bottomMargin())); + auto anchor = layer->ancher(); + QRectF surfaceGeo(QPointF(0, 0), layer->desiredSize()); + + if (anchor.testFlags(WLayerSurface::AnchorType::Left | WLayerSurface::AnchorType::Right)) { + surfaceGeo.moveLeft(validGeo.left()); + surfaceGeo.setWidth(validGeo.width()); + } else if (anchor & WLayerSurface::AnchorType::Left) { + surfaceGeo.moveLeft(validGeo.left()); + } else if (anchor & WLayerSurface::AnchorType::Right) { + surfaceGeo.moveRight(validGeo.right()); + } else { + surfaceGeo.moveLeft(validGeo.left() + (validGeo.width() - surfaceGeo.width()) / 2); + } + + if (anchor.testFlags(WLayerSurface::AnchorType::Top | WLayerSurface::AnchorType::Bottom)) { + surfaceGeo.moveTop(validGeo.top()); + surfaceGeo.setHeight(validGeo.height()); + } else if (anchor & WLayerSurface::AnchorType::Top) { + surfaceGeo.moveTop(validGeo.top()); + } else if (anchor & WLayerSurface::AnchorType::Bottom) { + surfaceGeo.moveBottom(validGeo.bottom()); + } else { + surfaceGeo.moveTop(validGeo.top() + (validGeo.height() - surfaceGeo.height()) / 2); + } + + if (layer->exclusiveZone() > 0) { + // TODO: support set_exclusive_edge in layer-shell v5/wlroots 0.19 + switch (layer->getExclusiveZoneEdge()) { + using enum WLayerSurface::AnchorType; + case Top: + addExclusiveZone(Qt::TopEdge, layer->exclusiveZone()); + break; + case Bottom: + addExclusiveZone(Qt::BottomEdge, layer->exclusiveZone()); + break; + case Left: + addExclusiveZone(Qt::LeftEdge, layer->exclusiveZone()); + break; + case Right: + addExclusiveZone(Qt::RightEdge, layer->exclusiveZone()); + break; + default: + qCWarning(lcTlOutput) << layer->appId() + << " has set exclusive zone, but exclusive edge is invalid!"; + break; + } + } + + surface->setSize(surfaceGeo.size()); + surface->setPosition(surfaceGeo.topLeft()); +} + +void SessionOutput::arrangeLayerSurfaces() +{ + if (!m_output) + return; + + const auto previous = m_exclusiveZone; + m_exclusiveZone = m_output->compositorExclusiveZone(); + const auto layers = layerSurfaces(); + for (auto *surface : layers) { + auto *layer = qobject_cast(surface->shellSurface()); + if (layer && layer->exclusiveZone() > 0) + arrangeLayerSurface(surface); + } + + for (auto *surface : layers) { + auto *layer = qobject_cast(surface->shellSurface()); + if (layer && layer->exclusiveZone() <= 0) + arrangeLayerSurface(surface); + } + + if (previous != m_exclusiveZone) + Q_EMIT exclusiveZoneChanged(); + + const auto available = validGeometry(); + if (m_lastValidGeometry != available) { + m_lastValidGeometry = available; + Q_EMIT validGeometryChanged(); + } +} + +bool SessionOutputManager::hardwareAttached() const +{ + return m_channel->isActive(); +} diff --git a/src/session/sessionoutputmanager.h b/src/session/sessionoutputmanager.h new file mode 100644 index 0000000000..32382b3fa7 --- /dev/null +++ b/src/session/sessionoutputmanager.h @@ -0,0 +1,116 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "output/output.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +class Output; +class OutputConfig; +class TreelandConfig; +class DesktopSurfaceModel; +class SessionOutputChannel; +class OutputManager; +class SurfaceWrapper; +class SurfaceListModel; +class SurfaceFilterModel; +class SessionOutputManager; +WAYLIB_SERVER_BEGIN_NAMESPACE +class WBackend; +WAYLIB_SERVER_END_NAMESPACE + +Q_MOC_INCLUDE("output/output.h") +Q_MOC_INCLUDE() + +class SessionOutput : public QObject +{ + Q_OBJECT + QML_ANONYMOUS + Q_PROPERTY(SurfaceListModel *windows READ windows CONSTANT FINAL) + Q_PROPERTY(SurfaceListModel *minimizedSurfaces READ minimizedSurfaces CONSTANT FINAL) + Q_PROPERTY(QMargins exclusiveZone READ exclusiveZone NOTIFY exclusiveZoneChanged FINAL) + Q_PROPERTY(QRectF validGeometry READ validGeometry NOTIFY validGeometryChanged FINAL) +public: + SessionOutput(SessionOutputManager *manager, Output *output); + + QMargins exclusiveZone() const { return m_exclusiveZone; }; + QRectF geometry() const; + QRectF validGeometry() const; + QList layerSurfaces() const; + SurfaceListModel *windows() const { return m_windows; }; + SurfaceListModel *minimizedSurfaces() const { return m_minimized; }; + void addSurface(SurfaceWrapper *surface); + void removeSurface(SurfaceWrapper *surface); + void arrangeLayerSurfaces(); + +Q_SIGNALS: + void exclusiveZoneChanged(); + void validGeometryChanged(); + +private: + void arrangeLayerSurface(SurfaceWrapper *surface); + void addExclusiveZone(Qt::Edge edge, int value); + SurfaceListModel *m_windows = nullptr; + SurfaceFilterModel *m_minimized = nullptr; + QPointer m_output; + DesktopSurfaceModel *const m_surfaces = nullptr; + QList> m_layers; + QMargins m_exclusiveZone; + QRectF m_lastValidGeometry; +}; + +class SessionOutputManager : public QObject +{ + Q_OBJECT + QML_ANONYMOUS +public: + using ConfigProvider = std::function; + SessionOutputManager(TreelandConfig *config, ConfigProvider outputConfiguration, + DesktopSurfaceModel *surfaces, SessionOutputChannel *channel, + OutputManager *hardware, WAYLIB_SERVER_NAMESPACE::WBackend *backend, + WAYLIB_SERVER_NAMESPACE::WOutputManagerV1 *protocol, + QObject *parent); + + DesktopSurfaceModel *surfaceRegistry() const { return m_surfaces; }; + bool hardwareAttached() const ; + OutputConfig *config(const QString &outputId); + SessionOutput *outputState(Output *output); + WAYLIB_SERVER_NAMESPACE::WOutputManagerV1 *protocol() const { return m_protocol; } + void refresh(); + Q_INVOKABLE void setScale(WAYLIB_SERVER_NAMESPACE::WOutput *output, qreal scale); + qreal effectiveScale() const; + qreal scaleAt(const QPointF &position); + QPointF defaultPosition(Output *output); + QString primaryOutputName() const; + void setPrimaryOutput(const QString &name); + void applyColor(Output *output, qreal brightness, uint32_t temperature, + std::function completed); + +Q_SIGNALS: + void desktopGeometryChanged(); + +private: + void requestConfiguration(wlr_output_configuration_v1 *configuration, bool onlyTest); + void publishConfiguration(); + +private: + TreelandConfig *const m_config = nullptr; + const ConfigProvider m_outputConfiguration; + DesktopSurfaceModel *const m_surfaces = nullptr; + SessionOutputChannel *const m_channel = nullptr; + OutputManager *const m_hardware = nullptr; + WAYLIB_SERVER_NAMESPACE::WOutputManagerV1 *m_protocol = nullptr; + QHash m_configs; + QHash m_outputs; +}; diff --git a/src/session/sessionprelaunch.cpp b/src/session/sessionprelaunch.cpp new file mode 100644 index 0000000000..9544c1ee72 --- /dev/null +++ b/src/session/sessionprelaunch.cpp @@ -0,0 +1,177 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "sessionprelaunch.h" +#include "session.h" +#include "core/waylandserver.h" +#include "core/rootsurfacecontainer.h" +#include "core/windowconfigstore.h" +#include "modules/prelaunch-splash/prelaunchsplash.h" +#include "modules/app-id-resolver/appidresolver.h" +#include "treelandconfig.hpp" +#include "treelanduserconfig.hpp" +#include "workspace/workspace.h" + +#include + +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +SessionPrelaunch::SessionPrelaunch(Session *owner, WaylandServer *runtime) + : SessionComponent(owner), m_runtime(runtime), m_store(new WindowConfigStore(this)) + , m_protocol(new PrelaunchSplash) +{ + owner->attachInterface(m_protocol); + m_resolver = new AppIdResolverManager; + owner->attachInterface(m_resolver); + connect(m_protocol, &PrelaunchSplash::splashRequested, this, &SessionPrelaunch::request); + connect(m_protocol, &PrelaunchSplash::splashCloseRequested, this, &SessionPrelaunch::close); +} + +void SessionPrelaunch::shutdown() +{ + m_pending.clear(); + m_closed.clear(); + const auto splashes = std::exchange(m_splashes, {}); + for (const auto &splash : splashes) { + if (splash.wrapper) + m_runtime->rootSurfaceContainer()->destroyForSurface(splash.wrapper); + } +} + +bool SessionPrelaunch::resolvePidfd(int pidfd, std::function callback) +{ + if (session()->isShuttingDown() || !m_resolver) + return false; + + return m_resolver->resolvePidfd(pidfd, + [owner = QPointer(session()), callback = std::move(callback)](const QString &appId) { + if (owner && !owner->isShuttingDown()) + callback(appId); + }); +} + +bool SessionPrelaunch::needsResolution() const +{ + return !m_pending.isEmpty() || !m_splashes.isEmpty() || !m_closed.isEmpty(); +} + +bool SessionPrelaunch::consumeClosed(const QString &appId) +{ + return !appId.isEmpty() && m_closed.remove(appId); +} + +void SessionPrelaunch::request(const QString &appId, const QString &instanceId, wlr_buffer *buffer) +{ + // try_from_resource hands us a locked buffer. Both completed and cancelled + // async requests release it, including when this Session is destroyed. + const Icon icon(buffer, [](wlr_buffer *value) { if (value) wlr_buffer_unlock(value); }); + if (session()->isShuttingDown() || !m_runtime->globalConfig()->enablePrelaunchSplash() || appId.isEmpty() + || m_pending.contains(appId) + || std::any_of(m_splashes.cbegin(), m_splashes.cend(), [&appId](const Splash &splash) { + return splash.wrapper && splash.wrapper->appId() == appId; + })) + return; + const auto generation = ++m_generation; + m_pending.insert(appId, {instanceId, generation}); + m_store->withSplashConfigFor(appId, this, + [this, appId, instanceId, generation, icon](const QSize &size, const QString &dark, + const QString &light, qlonglong theme) { + create(appId, instanceId, generation, icon, size, dark, light, theme); + }, + [this, appId, generation] { + const auto pending = m_pending.constFind(appId); + if (pending != m_pending.cend() && pending->generation == generation) + m_pending.remove(appId); + }); +} + +void SessionPrelaunch::create(const QString &appId, const QString &instanceId, quint64 generation, + const Icon &icon, const QSize &size, const QString &darkPalette, + const QString &lightPalette, qlonglong theme) +{ + const auto pending = m_pending.constFind(appId); + if (session()->isShuttingDown() || pending == m_pending.cend() || pending->generation != generation) + return; + + m_pending.remove(appId); + const bool dark = theme == 0 ? session()->config()->windowColorScheme() == 1 : theme == 2; + auto *wrapper = new SurfaceWrapper(m_runtime->qmlEngine(), nullptr, size, appId, + icon ? wlr_buffer_lock(icon.get()) : nullptr, + QColor(dark ? darkPalette : lightPalette)); + wrapper->setSession(session()); + m_splashes.append({wrapper, instanceId}); + session()->workspace()->addSurface(wrapper); + Q_EMIT splashCreated(wrapper); + connect(wrapper, &SurfaceWrapper::splashCloseRequested, this, + [this, wrapper] { discard(wrapper, true); }); + const auto timeout = m_runtime->globalConfig()->prelaunchSplashTimeoutMs(); + if (timeout > 0) { + QTimer::singleShot(static_cast(qMin(timeout, 60000)), this, + [this, wrapper = QPointer(wrapper)] { + if (wrapper) + discard(wrapper, false); + }); + } +} + +void SessionPrelaunch::discard(SurfaceWrapper *wrapper, bool closeWindow) +{ + auto it = std::find_if(m_splashes.begin(), m_splashes.end(), [wrapper](const Splash &splash) { + return splash.wrapper == wrapper; + }); + if (it == m_splashes.end()) + return; // Already matched to a real window; its old timeout must do nothing. + + m_splashes.erase(it); + const auto appId = wrapper->appId(); + if (closeWindow) + m_closed.insert(appId); + + m_runtime->rootSurfaceContainer()->destroyForSurface(wrapper); + m_store->recordSplashMismatch(appId); +} + +void SessionPrelaunch::close(const QString &appId, const QString &instanceId) +{ + const auto pending = m_pending.constFind(appId); + if (pending != m_pending.cend() && pending->instanceId == instanceId) + m_pending.remove(appId); + + for (const auto &splash : std::as_const(m_splashes)) { + if (splash.wrapper && splash.wrapper->appId() == appId && splash.instanceId == instanceId) { + discard(splash.wrapper, false); + return; + } + } +} + +SurfaceWrapper *SessionPrelaunch::takeSplash(const QString &appId, WToplevelSurface *surface, + SurfaceWrapper::Type type) +{ + if (appId.isEmpty() || !surface || !session()->ownsClient(surface->waylandClient())) + return nullptr; + + m_pending.remove(appId); + for (auto it = m_splashes.begin(); it != m_splashes.end(); ++it) { + auto *wrapper = it->wrapper.data(); + if (!wrapper || wrapper->appId() != appId) + continue; + + m_splashes.erase(it); + wrapper->convertToNormalSurface(surface, type); + m_store->resetSplashMismatchCount(appId); + return wrapper; + } + + return nullptr; +} + +PrelaunchSplash *SessionPrelaunch::protocol() const +{ + return m_protocol; +} diff --git a/src/session/sessionprelaunch.h b/src/session/sessionprelaunch.h new file mode 100644 index 0000000000..809ea9819b --- /dev/null +++ b/src/session/sessionprelaunch.h @@ -0,0 +1,57 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "sessioncomponent.h" +#include "surface/surfacewrapper.h" + +#include +#include + +struct wlr_buffer; + +class PrelaunchSplash; +class AppIdResolverManager; +class WaylandServer; +class WindowConfigStore; + +class SessionPrelaunch : public SessionComponent +{ + Q_OBJECT +public: + SessionPrelaunch(Session *owner, WaylandServer *runtime); + + void shutdown(); + bool needsResolution() const; + bool consumeClosed(const QString &appId); + SurfaceWrapper *takeSplash(const QString &appId, + WAYLIB_SERVER_NAMESPACE::WToplevelSurface *surface, + SurfaceWrapper::Type type); + PrelaunchSplash *protocol() const; + bool resolvePidfd(int pidfd, std::function callback); + +Q_SIGNALS: + void splashCreated(SurfaceWrapper *wrapper); + +private: + using Icon = std::shared_ptr; + void request(const QString &appId, const QString &instanceId, wlr_buffer *buffer); + void close(const QString &appId, const QString &instanceId); + void create(const QString &appId, const QString &instanceId, quint64 generation, + const Icon &icon, const QSize &size, const QString &darkPalette, + const QString &lightPalette, qlonglong theme); + void discard(SurfaceWrapper *wrapper, bool closeWindow); + +private: + struct Pending { QString instanceId; quint64 generation; }; + struct Splash { QPointer wrapper; QString instanceId; }; + WaylandServer *const m_runtime = nullptr; + WindowConfigStore *const m_store = nullptr; + QPointer m_protocol; + QPointer m_resolver; + QHash m_pending; + QList m_splashes; + QSet m_closed; + quint64 m_generation = 0; +}; diff --git a/src/session/sessionprotocols.cpp b/src/session/sessionprotocols.cpp new file mode 100644 index 0000000000..8abdd303cc --- /dev/null +++ b/src/session/sessionprotocols.cpp @@ -0,0 +1,291 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "sessionprotocols.h" +#include "session.h" +#include "sessionworkspace.h" +#include "toplevelcapturesource.h" +#include "core/waylandserver.h" +#include "core/rootsurfacecontainer.h" +#include "surface/surfacewrapper.h" +#include "output/output.h" +#include "common/treelandlogging.h" +#include "modules/appearance/appearanceinterfacev1.h" +#include "modules/appearance/appearancemanagerinterfacev1.h" +#include "modules/personalization/personalizationmanagerinterfacev1.h" +#include "modules/decoration/decorationmanagerinterfacev1.h" +#include "modules/window-transition/windowtransitionmanagerinterfacev1.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +constexpr uint32_t ExtDataControlManagerVersion = 1; + +// Session closes client resources before detaching its socket-owned managers. +template +class NativeSessionProtocol : public QObject, public WServerInterface +{ + using Native = std::remove_pointer_t>; +public: + explicit NativeSessionProtocol(QByteArrayView name) : m_name(name) {} + QByteArrayView interfaceName() const override { return m_name; } +protected: + void create(WServer *server) override { m_handle = Create(server->handle()); } + void destroy(WServer *) override + { + if (ownsSocket() && m_handle) + Destroy(nativeInterface(), false); + + m_handle = nullptr; + } + wl_global *global() const override + { + auto *native = nativeInterface(); + return native ? native->global : nullptr; + } +private: + const QByteArrayView m_name; +}; + +wlr_ext_data_control_manager_v1 *createExtDataControl(wl_display *display) +{ + return wlr_ext_data_control_manager_v1_create(display, ExtDataControlManagerVersion); +} + +wlr_ext_image_copy_capture_manager_v1 *createImageCopyCapture(wl_display *display) +{ + return wlr_ext_image_copy_capture_manager_v1_create(display, 1); +} + +wlr_ext_output_image_capture_source_manager_v1 *createOutputCaptureSource(wl_display *display) +{ + return wlr_ext_output_image_capture_source_manager_v1_create(display, 1); +} + +wlr_ext_foreign_toplevel_image_capture_source_manager_v1 *createToplevelCaptureSource(wl_display *display) +{ + return wlr_ext_foreign_toplevel_image_capture_source_manager_v1_create(display, 1); +} + +class SessionToplevelCapture final + : public NativeSessionProtocol, public WObject +{ +public: + explicit SessionToplevelCapture(Session *owner) + : NativeSessionProtocol("ext_foreign_toplevel_image_capture_source_manager_v1") + , m_owner(owner) + , m_root(WaylandServer::instance()->rootSurfaceContainer()) + {} + ~SessionToplevelCapture() override { teardown(); } +protected: + void create(WServer *server) override + { + NativeSessionProtocol::create(server); + auto *manager = nativeInterface(); + if (manager) + listeners()->add(&manager->events.new_request, this, &SessionToplevelCapture::capture); + } +private: + void capture(wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request *request); + const QPointer m_owner; + RootSurfaceContainer *const m_root; +}; + +void SessionToplevelCapture::capture(wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request *request) +{ + // Rejected requests still need an inert source resource for the client's new ID. + if (!request) + return; + + auto *list = m_owner ? m_owner->toplevelList() : nullptr; + auto *toplevel = list && request->toplevel_handle + && m_owner->ownsClient(WClient::get(request->client)) + ? list->findSurfaceByHandle(request->toplevel_handle) : nullptr; + auto *surfaceWrapper = toplevel ? m_root->getSurface(toplevel) : nullptr; + if (!surfaceWrapper || surfaceWrapper->session() != m_owner.data()) { + wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request_accept(request, nullptr); + return; + } + + // Validate and allocate the capture pipeline when the first session starts. + auto *imageCaptureSource = new ToplevelCaptureSource(surfaceWrapper); + connect(surfaceWrapper, &SurfaceWrapper::aboutToBeInvalidated, + imageCaptureSource, &WExtImageCaptureSourceV1Impl::invalidate); + + if (!imageCaptureSource->accept(request)) { + qCWarning(lcTlCapture) << "Failed to accept foreign toplevel image capture request"; + delete imageCaptureSource; + } +} + +// The native factory creates both globals together. Each advertised interface +// has one wrapper; export/import tokens share only this Session's registry. +struct SessionForeignRegistry +{ + wlr_xdg_foreign_v2 *acquire(WServer *server) + { + if (!native) { + registry = wlr_xdg_foreign_registry_create(server->handle()); + if (!registry) + return nullptr; + native = wlr_xdg_foreign_v2_create(server->handle(), registry); + if (!native) { + wlr_xdg_foreign_registry_destroy(registry, false); + registry = nullptr; + return nullptr; + } + } + + ++users; + return native; + } + + void release(bool destroyNative) + { + Q_ASSERT(users > 0); + if (--users != 0) + return; + + if (destroyNative) { + wlr_xdg_foreign_v2_destroy(native, false); + wlr_xdg_foreign_registry_destroy(registry, false); + } + + native = nullptr; + registry = nullptr; + } + + wlr_xdg_foreign_v2 *native = nullptr; + wlr_xdg_foreign_registry *registry = nullptr; + int users = 0; +}; + +class SessionForeignInterface final : public QObject, public WServerInterface +{ +public: + enum Endpoint { Exporter, Importer }; + SessionForeignInterface(std::shared_ptr registry, Endpoint endpoint) + : m_registry(std::move(registry)) + , m_endpoint(endpoint) + {} + QByteArrayView interfaceName() const override + { + return m_endpoint == Exporter ? "zxdg_exporter_v2" : "zxdg_importer_v2"; + } +protected: + void create(WServer *server) override { m_handle = m_registry->acquire(server); } + void destroy(WServer *) override + { + if (m_handle) + m_registry->release(ownsSocket() != nullptr); + + m_handle = nullptr; + } + wl_global *global() const override + { + auto *native = nativeInterface(); + if (!native) + return nullptr; + + return m_endpoint == Exporter ? native->exporter.global : native->importer.global; + } +private: + const std::shared_ptr m_registry; + const Endpoint m_endpoint; +}; +} + +SessionProtocols::SessionProtocols(Session *session) + : SessionComponent(session) +{ + session->sessionWorkspace()->installProtocol(); + session->attachInterface(new NativeSessionProtocol("wl_data_device_manager")); + session->attachInterface(new NativeSessionProtocol("zwp_primary_selection_device_manager_v1")); + session->attachInterface(new NativeSessionProtocol("zwlr_data_control_manager_v1")); + session->attachInterface(new NativeSessionProtocol("ext_data_control_manager_v1")); + auto foreignRegistry = std::make_shared(); + session->attachInterface(new SessionForeignInterface(foreignRegistry, SessionForeignInterface::Exporter)); + session->attachInterface(new SessionForeignInterface(foreignRegistry, SessionForeignInterface::Importer)); + session->attachInterface(new NativeSessionProtocol("zwlr_screencopy_manager_v1")); + session->attachInterface(new NativeSessionProtocol("ext_image_copy_capture_manager_v1")); + session->attachInterface(new NativeSessionProtocol("ext_output_image_capture_source_manager_v1")); + session->attachInterface(new SessionToplevelCapture(session)); + + m_xdgShell = new WXdgShell(5); + session->attachInterface(m_xdgShell); + + m_layerShell = new WLayerShell(m_xdgShell); + session->attachInterface(m_layerShell); + + m_xdgDecoration = new WXdgDecorationManager; + session->attachInterface(m_xdgDecoration); + + m_xdgDialog = new WXdgDialogManagerV1; + session->attachInterface(m_xdgDialog); + + m_xdgTags = new WXdgToplevelTagManagerV1; + session->attachInterface(m_xdgTags); + + m_personalization = new PersonalizationManagerInterfaceV1(session); + session->attachInterface(m_personalization); + session->attachInterface(new AppearanceInterfaceV1(session->config(), session)); + session->attachInterface(new AppearanceManagerInterfaceV1(session->config(), session)); + + m_windowTransitions = new WindowTransitionManagerInterfaceV1; + session->attachInterface(m_windowTransitions); + + m_decoration = new DecorationManagerInterfaceV1; + session->attachInterface(m_decoration); +} + +WXdgShell *SessionProtocols::xdgShell() const +{ + return m_xdgShell; +} + +WLayerShell *SessionProtocols::layerShell() const +{ + return m_layerShell; +} + +WXdgDecorationManager *SessionProtocols::xdgDecoration() const +{ + return m_xdgDecoration; +} + +WXdgDialogManagerV1 *SessionProtocols::xdgDialog() const +{ + return m_xdgDialog; +} + +WXdgToplevelTagManagerV1 *SessionProtocols::xdgTags() const +{ + return m_xdgTags; +} + +PersonalizationManagerInterfaceV1 *SessionProtocols::personalization() const +{ + return m_personalization; +} + +DecorationManagerInterfaceV1 *SessionProtocols::decoration() const +{ + return m_decoration; +} + +WindowTransitionManagerInterfaceV1 *SessionProtocols::windowTransitions() const +{ + return m_windowTransitions; +} diff --git a/src/session/sessionprotocols.h b/src/session/sessionprotocols.h new file mode 100644 index 0000000000..0ed599003f --- /dev/null +++ b/src/session/sessionprotocols.h @@ -0,0 +1,48 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "sessioncomponent.h" + +#include + +#include + +class PersonalizationManagerInterfaceV1; +class DecorationManagerInterfaceV1; +class WindowTransitionManagerInterfaceV1; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WXdgShell; +class WLayerShell; +class WXdgDecorationManager; +class WXdgDialogManagerV1; +class WXdgToplevelTagManagerV1; +WAYLIB_SERVER_END_NAMESPACE + +class SessionProtocols : public SessionComponent +{ + Q_OBJECT + QML_ANONYMOUS +public: + explicit SessionProtocols(Session *session); + WAYLIB_SERVER_NAMESPACE::WXdgShell *xdgShell() const; + WAYLIB_SERVER_NAMESPACE::WLayerShell *layerShell() const; + WAYLIB_SERVER_NAMESPACE::WXdgDecorationManager *xdgDecoration() const; + WAYLIB_SERVER_NAMESPACE::WXdgDialogManagerV1 *xdgDialog() const; + WAYLIB_SERVER_NAMESPACE::WXdgToplevelTagManagerV1 *xdgTags() const; + PersonalizationManagerInterfaceV1 *personalization() const; + DecorationManagerInterfaceV1 *decoration() const; + WindowTransitionManagerInterfaceV1 *windowTransitions() const; + +private: + QPointer m_xdgShell; + QPointer m_layerShell; + QPointer m_xdgDecoration; + QPointer m_xdgDialog; + QPointer m_xdgTags; + QPointer m_windowTransitions; + QPointer m_personalization; + QPointer m_decoration; +}; diff --git a/src/session/sessionscene.cpp b/src/session/sessionscene.cpp new file mode 100644 index 0000000000..0e8b3201ce --- /dev/null +++ b/src/session/sessionscene.cpp @@ -0,0 +1,90 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "sessionscene.h" +#include "session.h" +#include "surface/surfacewrapper.h" + +SessionScene::SessionScene(Session *owner) + : SessionComponent(owner), m_system(owner->username() == QStringLiteral("dde")) +{ + initializeActiveState(); +} + +SessionScene::~SessionScene() +{ + for (const auto &surface : std::as_const(m_surfaces)) { + if (surface) + surface->setRenderingEnabled(false); + } +} + +void SessionScene::shutdown() +{ + const auto surfaces = m_surfaces; + for (const auto &surface : surfaces) { + if (surface) { + surface->disableWindowAnimation(); + surface->setRenderingEnabled(false); + } + } +} + +void SessionScene::finishShutdown() +{ + const auto surfaces = m_surfaces; + for (const auto &surface : surfaces) { + if (!surface) + continue; + + Q_ASSERT(surface->isAboutToRemove()); + if (surface->isAboutToRemove()) + delete surface.data(); + } +} + +bool SessionScene::allows(SurfaceWrapper *surface) const +{ + // The dedicated login service is a system domain, not a logged-in user's + // desktop. A privileged role on an ordinary user's window grants no bypass. + const bool systemSurface = m_system + && (surface->type() == SurfaceWrapper::Type::LockScreen + || surface->surfaceRole() == SurfaceWrapper::SurfaceRole::PrivilegedOverlay); + return !session()->isShuttingDown() && !surface->isAboutToRemove() + && (isActive() || systemSurface); +} + +void SessionScene::attach(SurfaceWrapper *surface) +{ + if (m_surfaces.contains(surface)) + return; + + m_surfaces.append(surface); + connect(surface, &SurfaceWrapper::surfaceRoleChanged, this, &SessionScene::refresh); + connect(surface, &SurfaceWrapper::typeChanged, this, &SessionScene::refresh); + connect(surface, &QObject::destroyed, this, &SessionScene::removeDestroyed); + surface->setRenderingEnabled(allows(surface)); +} + +void SessionScene::removeDestroyed() +{ + m_surfaces.removeIf([](const auto &surface) { return surface.isNull(); }); +} + +void SessionScene::refresh() +{ + for (const auto &surface : std::as_const(m_surfaces)) { + if (surface) + surface->setRenderingEnabled(allows(surface)); + } +} + +void SessionScene::activate() +{ + refresh(); +} + +void SessionScene::deactivate() +{ + refresh(); +} diff --git a/src/session/sessionscene.h b/src/session/sessionscene.h new file mode 100644 index 0000000000..83fdd0b39a --- /dev/null +++ b/src/session/sessionscene.h @@ -0,0 +1,36 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "sessioncomponent.h" + +#include +#include + +class SurfaceWrapper; + +class SessionScene : public SessionComponent +{ + Q_OBJECT +public: + explicit SessionScene(Session *owner); + ~SessionScene() override; + + void attach(SurfaceWrapper *surface); + void shutdown(); + void finishShutdown(); + +protected: + void activate() override; + void deactivate() override; + +private: + void refresh(); + void removeDestroyed(); + bool allows(SurfaceWrapper *surface) const; + +private: + const bool m_system; + QList> m_surfaces; +}; diff --git a/src/session/sessionseatmanager.cpp b/src/session/sessionseatmanager.cpp new file mode 100644 index 0000000000..7b67de9408 --- /dev/null +++ b/src/session/sessionseatmanager.cpp @@ -0,0 +1,127 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "sessionseatmanager.h" +#include "session.h" +#include "sessioninputchannel.h" +#include "desktop/desktopenvironment.h" +#include "input/compositorinputfilter.h" +#include "core/waylandserver.h" +#include "core/shellhandler.h" +#include "core/imcandidatepanelmanager.h" +#include "seat/seatmanager.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +SessionSeatManager::SessionSeatManager(Session *session) + : SessionComponent(session) +{ + m_pointerGestures = new WPointerGesturesV1; + session->attachInterface(m_pointerGestures); + createInputMethodProtocols(); + auto *hardware = WaylandServer::instance()->seatManager(); + const auto names = hardware->configuredSeatNames(); + for (const auto &name : names) { + // Hardware topology survives logout; never derive identity from the + // lifetime of the previously active user's logical seats. + auto *bootstrap = hardware->getSeat(name); + auto *logical = bootstrap && !bootstrap->ownsSocket() ? bootstrap : new WSeat(name); + addSeat(logical, name == hardware->configuredFallbackName()); + } +} + +SessionSeatManager::~SessionSeatManager() +{ + if (m_candidatePanels) + delete m_candidatePanels; + + qDeleteAll(m_helpers); + if (auto *server = WaylandServer::instance()) + server->seatManager()->releaseSessionSeats(this); +} + +QList SessionSeatManager::seats() const +{ + QList result; + for (const auto &seat : m_seats) { + if (seat) + result.append(seat); + } + + return result; +} + +WInputMethodHelper *SessionSeatManager::inputMethodHelper(WSeat *seat) const +{ + return m_helpers.value(seat); +} + +void SessionSeatManager::addSeat(WSeat *seat, bool fallback) +{ + if (m_seats.contains(seat)) + return; + + seat->setPointerGestures(m_pointerGestures); + seat->setEventFilter(nullptr); + seat->setEventFilter(session()->desktop()->inputChannel()->filter()); + session()->attachInterface(seat); + m_seats.append(seat); + if (fallback || !m_fallback) + m_fallback = seat; + + auto *helper = new WInputMethodHelper( + WaylandServer::instance()->server(), seat, m_inputMethodProtocols); + helper->setParent(this); + WaylandServer::instance()->shellHandler()->registerInputMethodHelper(helper); + m_helpers.insert(seat, helper); + if (!m_candidatePanels) { + m_candidatePanels = new IMCandidatePanelManager( + WaylandServer::instance()->shellHandler(), helper, this); + } else if (fallback) { + m_candidatePanels->setInputMethodHelper(helper); + } +} + +void SessionSeatManager::removeSeat(WSeat *seat) +{ + delete m_helpers.take(seat); + if (m_candidatePanels) + m_candidatePanels->setInputMethodHelper(m_helpers.isEmpty() ? nullptr : m_helpers.first()); + + m_seats.removeAll(seat); + if (m_fallback == seat) + m_fallback = m_seats.isEmpty() ? nullptr : m_seats.first(); + + session()->detachInterface(seat); +} + +void SessionSeatManager::createInputMethodProtocols() +{ + m_inputMethodProtocols = { + new WInputMethodManagerV2, + new WTextInputManagerV1, + new WTextInputManagerV2, + new WTextInputManagerV3, + new WVirtualKeyboardManagerV1, + }; + + session()->attachInterface(m_inputMethodProtocols.inputMethod); + session()->attachInterface(m_inputMethodProtocols.textInputV1); + session()->attachInterface(m_inputMethodProtocols.textInputV2); + session()->attachInterface(m_inputMethodProtocols.textInputV3); + session()->attachInterface(m_inputMethodProtocols.virtualKeyboard); +} + +WSeat *SessionSeatManager::fallbackSeat() const +{ + return m_fallback; +} diff --git a/src/session/sessionseatmanager.h b/src/session/sessionseatmanager.h new file mode 100644 index 0000000000..2a02dd081b --- /dev/null +++ b/src/session/sessionseatmanager.h @@ -0,0 +1,46 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "sessioncomponent.h" + +#include +#include + +#include +#include +#include + +class IMCandidatePanelManager; +WAYLIB_SERVER_BEGIN_NAMESPACE +class WSeat; +class WPointerGesturesV1; +WAYLIB_SERVER_END_NAMESPACE + +class SessionSeatManager : public SessionComponent +{ + Q_OBJECT +public: + explicit SessionSeatManager(Session *session); + ~SessionSeatManager() override; + + QList seats() const; + WAYLIB_SERVER_NAMESPACE::WSeat *fallbackSeat() const; + WAYLIB_SERVER_NAMESPACE::WInputMethodHelper *inputMethodHelper( + WAYLIB_SERVER_NAMESPACE::WSeat *seat) const; + IMCandidatePanelManager *candidatePanels() const { return m_candidatePanels; }; + void addSeat(WAYLIB_SERVER_NAMESPACE::WSeat *seat, bool fallback); + void removeSeat(WAYLIB_SERVER_NAMESPACE::WSeat *seat); + +private: + void createInputMethodProtocols(); + +private: + WAYLIB_SERVER_NAMESPACE::WPointerGesturesV1 *m_pointerGestures = nullptr; + WAYLIB_SERVER_NAMESPACE::WInputMethodHelper::Protocols m_inputMethodProtocols; + QList> m_seats; + QPointer m_fallback; + QMap m_helpers; + IMCandidatePanelManager *m_candidatePanels = nullptr; +}; diff --git a/src/session/sessionswitcher.cpp b/src/session/sessionswitcher.cpp new file mode 100644 index 0000000000..4aef329547 --- /dev/null +++ b/src/session/sessionswitcher.cpp @@ -0,0 +1,83 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "sessionswitcher.h" +#include "modules/shortcut/shortcutrunner.h" +#include "desktop/desktopenvironment.h" +#include "core/qmlengine.h" +#include "core/waylandserver.h" +#include "core/rootsurfacecontainer.h" +#include "workspace/workspace.h" + +#include + +SessionSwitcher::SessionSwitcher(Workspace *workspace, QmlEngine *engine, WaylandServer *runtime, + DesktopEnvironment *desktop) + : QObject(desktop) + , m_workspace(workspace) + , m_engine(engine) + , m_runtime(runtime) + , m_desktop(desktop) +{ +} + +void SessionSwitcher::setShortcutController(ShortcutController *controller, ShortcutManagerV3 *protocol) +{ + Q_ASSERT(!m_shortcuts); + m_shortcuts = new ShortcutRunner(m_workspace, this, controller, m_desktop->multitaskView(), + m_runtime, m_inputFilter, protocol); + if (m_running) + m_shortcuts->start(); +} + +QQuickItem *SessionSwitcher::taskSwitcher() const +{ + return m_taskSwitcher; +} + +QQuickItem *SessionSwitcher::ensureTaskSwitcher(Output *output) +{ + if (!m_taskSwitcher) { + m_taskSwitcher = m_engine->createTaskSwitcher( + output, m_desktop->viewRoot(), m_desktop); + m_taskSwitcher->setZ(RootSurfaceContainer::OverlayZOrder); + connect(m_taskSwitcher, SIGNAL(switchOnChanged()), this, SLOT(close())); + } + return m_taskSwitcher; +} + +void SessionSwitcher::close() +{ + if (!m_taskSwitcher) + return; + + disconnect(m_taskSwitcher, nullptr, this, nullptr); + m_taskSwitcher->setVisible(false); + m_taskSwitcher->deleteLater(); + m_taskSwitcher = nullptr; + auto *server = m_runtime; + if (server->currentMode() == WaylandServer::CurrentMode::WindowSwitch) + server->setCurrentMode(WaylandServer::CurrentMode::Normal); +} + +void SessionSwitcher::deactivate() +{ + m_running = false; + if (m_shortcuts) + m_shortcuts->stop(); + + close(); +} + +void SessionSwitcher::activate() +{ + m_running = true; + if (m_shortcuts) + m_shortcuts->start(); +} + +void SessionSwitcher::setInputFilter(CompositorInputFilter *filter) +{ + Q_ASSERT(!m_shortcuts && !m_inputFilter); + m_inputFilter = filter; +} diff --git a/src/session/sessionswitcher.h b/src/session/sessionswitcher.h new file mode 100644 index 0000000000..150cd9de35 --- /dev/null +++ b/src/session/sessionswitcher.h @@ -0,0 +1,48 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include +#include + +class ShortcutController; +class ShortcutManagerV3; +class ShortcutRunner; +class Output; +class Workspace; +class QmlEngine; +class WaylandServer; +class DesktopEnvironment; +class CompositorInputFilter; + +class SessionSwitcher : public QObject +{ + Q_OBJECT + QML_ANONYMOUS +public: + SessionSwitcher(Workspace *workspace, QmlEngine *engine, WaylandServer *runtime, + DesktopEnvironment *desktop); + + void activate(); + void deactivate(); + void setInputFilter(CompositorInputFilter *filter); + void setShortcutController(ShortcutController *controller, ShortcutManagerV3 *protocol); + QQuickItem *taskSwitcher() const; + QQuickItem *ensureTaskSwitcher(Output *output); + +public Q_SLOTS: + void close(); + +private: + Workspace *const m_workspace = nullptr; + QmlEngine *const m_engine = nullptr; + WaylandServer *const m_runtime = nullptr; + DesktopEnvironment *const m_desktop = nullptr; + CompositorInputFilter *m_inputFilter = nullptr; + bool m_running = false; + ShortcutRunner *m_shortcuts = nullptr; + QPointer m_taskSwitcher; +}; diff --git a/src/session/sessionworkspace.cpp b/src/session/sessionworkspace.cpp new file mode 100644 index 0000000000..51691bec3b --- /dev/null +++ b/src/session/sessionworkspace.cpp @@ -0,0 +1,205 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "sessionworkspace.h" +#include "session.h" +#include "core/rootsurfacecontainer.h" +#include "core/waylandserver.h" +#include "workspace/workspace.h" +#include "output/output.h" +#include "surface/surfacewrapper.h" +#include "treelanduserconfig.hpp" + +#include +#include +#include +#include +#include + +SessionWorkspace::SessionWorkspace(Session *session, WaylandServer *runtime) + : SessionComponent(session) + , m_root(runtime->rootSurfaceContainer()) + , m_workspace(new Workspace(runtime->rootSurfaceContainer(), session->config())) + , m_protocolIdPrefix(QUuid::createUuid().toByteArray(QUuid::WithoutBraces)) +{ + m_workspace->setZ(RootSurfaceContainer::NormalZOrder); + m_workspace->setSize(runtime->rootSurfaceContainer()->size()); + deactivate(); + initializeActiveState(); +} + +SessionWorkspace::~SessionWorkspace() +{ + if (!m_workspace) + return; + + deactivate(); + auto *runtime = WaylandServer::instance(); + // The runtime may still reference the last active workspace. In that case + // its visual parent retains ownership, as it does during runtime shutdown. + if (!runtime || runtime->workspace() == m_workspace) + return; + + auto *workspace = m_workspace.data(); + if (workspace->surfaces().isEmpty()) { + workspace->deleteLater(); + } else { + connect(workspace, &SurfaceContainer::surfaceRemoved, workspace, [workspace] { + if (workspace->surfaces().isEmpty()) + workspace->deleteLater(); + }); + } +} + +Workspace *SessionWorkspace::workspace() const +{ + return m_workspace; +} + +void SessionWorkspace::activate() +{ + m_workspace->setEnabled(true); + m_workspace->setVisible(true); +} + +void SessionWorkspace::deactivate() +{ + m_workspace->setEnabled(false); + m_workspace->resetView(); + m_workspace->setVisible(false); +} + +void SessionWorkspace::installProtocol() +{ + Q_ASSERT(!m_protocol); + m_protocol = new WExtWorkspaceManagerV1; + // The socket ancestry also permits parent-domain globals; require the exact + // Session here so child sessions cannot enumerate their parent's workspaces. + m_protocol->setFilter(std::bind_front(&Session::ownsClient, session())); + connect(m_protocol, &WExtWorkspaceManagerV1::initialized, + this, &SessionWorkspace::initializeProtocol); + connect(m_protocol, &WExtWorkspaceManagerV1::invalidated, + this, &SessionWorkspace::invalidateProtocol); + connect(m_protocol, &WExtWorkspaceManagerV1::commit, + this, &SessionWorkspace::handleCommit, Qt::DirectConnection); + connect(m_workspace, &Workspace::currentChanged, this, &SessionWorkspace::syncModels); + connect(m_workspace, &Workspace::currentIndexChanged, this, &SessionWorkspace::syncModels); + connect(m_workspace, &Workspace::countChanged, this, &SessionWorkspace::syncModels); + connect(m_workspace->models(), &QAbstractItemModel::rowsInserted, this, &SessionWorkspace::syncModels); + connect(m_workspace->models(), &QAbstractItemModel::rowsRemoved, this, &SessionWorkspace::syncModels); + connect(m_workspace->models(), &QAbstractItemModel::rowsMoved, this, &SessionWorkspace::syncModels); + connect(m_root->outputModel(), &QAbstractItemModel::rowsInserted, this, &SessionWorkspace::syncOutputs); + connect(m_root->outputModel(), &QAbstractItemModel::rowsRemoved, this, &SessionWorkspace::syncOutputs); + connect(m_workspace->showOnAllWorkspaceModel(), &WorkspaceModel::surfaceAdded, + this, &SessionWorkspace::syncModels); + connect(m_workspace->showOnAllWorkspaceModel(), &WorkspaceModel::surfaceRemoved, + this, &SessionWorkspace::syncModels); + // attachInterface installs the owning socket before exposing the global. + session()->attachInterface(m_protocol); +} + +void SessionWorkspace::initializeProtocol() +{ + m_group = m_protocol->createGroup(EXT_WORKSPACE_GROUP_HANDLE_V1_GROUP_CAPABILITIES_CREATE_WORKSPACE); + syncOutputs(); + syncModels(); +} + +void SessionWorkspace::invalidateProtocol() +{ + m_handles.clear(); + m_outputs.clear(); + m_group = nullptr; +} + +void SessionWorkspace::syncOutputs() +{ + if (!m_protocol || !m_group) + return; + QList> outputs; + for (auto *output : m_root->outputs()) { + auto *native = output->output(); + connect(native, &WOutput::enabledChanged, this, &SessionWorkspace::syncOutputs, Qt::UniqueConnection); + if (native->isEnabled()) + outputs.append(native); + } + for (const auto &output : std::as_const(m_outputs)) { + if (output && !outputs.contains(output)) + m_protocol->outputLeave(m_group, output); + } + for (const auto &output : std::as_const(outputs)) { + if (!m_outputs.contains(output)) + m_protocol->outputEnter(m_group, output); + } + m_outputs = outputs; +} + +void SessionWorkspace::syncModels() +{ + if (!m_protocol || !m_group) + return; + for (auto it = m_handles.begin(); it != m_handles.end();) { + if (!m_workspace->models()->objects().contains(it.key())) { + m_protocol->removeWorkspace(it.value()); + it = m_handles.erase(it); + } else { + ++it; + } + } + for (int index = 0; index < m_workspace->count(); ++index) { + auto *model = m_workspace->modelAt(index); + auto *handle = m_handles.value(model); + if (!handle) { + const auto id = m_protocolIdPrefix + ':' + QByteArray::number(model->id()); + handle = m_protocol->createWorkspace(id, EXT_WORKSPACE_HANDLE_V1_WORKSPACE_CAPABILITIES_ACTIVATE); + if (!handle) + continue; + m_handles.insert(model, handle); + m_protocol->setGroup(handle, m_group); + } + connect(model, &WorkspaceModel::nameChanged, this, &SessionWorkspace::syncModels, Qt::UniqueConnection); + connect(model, &WorkspaceModel::surfaceAdded, this, &SessionWorkspace::syncModels, Qt::UniqueConnection); + connect(model, &WorkspaceModel::surfaceRemoved, this, &SessionWorkspace::syncModels, Qt::UniqueConnection); + auto surfaces = model->surfaces(); + surfaces.append(m_workspace->showOnAllWorkspaceModel()->surfaces()); + for (auto *surface : std::as_const(surfaces)) + connect(surface, &SurfaceWrapper::attentionChanged, this, &SessionWorkspace::syncModels, Qt::UniqueConnection); + const bool urgent = std::ranges::any_of(surfaces, &SurfaceWrapper::attention); + m_protocol->setName(handle, model->name()); + m_protocol->setCoordinates(handle, {static_cast(index)}); + m_protocol->setState(handle, model == m_workspace->current(), urgent, false); + } +} + +void SessionWorkspace::handleCommit(wlr_ext_workspace_v1_commit_event *event) +{ + wlr_ext_workspace_v1_request *request, *next; + wl_list_for_each_safe(request, next, event->requests, link) { + switch (request->type) { + case WLR_EXT_WORKSPACE_V1_REQUEST_ACTIVATE: { + auto *model = m_handles.key(request->activate.workspace, nullptr); + if (model) + m_workspace->switchTo(m_workspace->models()->objects().indexOf(model), false); + break; + } + case WLR_EXT_WORKSPACE_V1_REQUEST_CREATE_WORKSPACE: { + if (request->create_workspace.group != m_group || !m_group + || m_workspace->count() >= m_workspace->config()->maxWorkspace()) + break; + const auto name = QString::fromUtf8(request->create_workspace.name); + bool duplicate = false; + for (auto *model : m_workspace->models()->objects()) + duplicate |= model->name() == name; + if (duplicate) + break; + m_workspace->createModel(name); + m_workspace->switchTo(m_workspace->count() - 1, false); + break; + } + case WLR_EXT_WORKSPACE_V1_REQUEST_DEACTIVATE: + case WLR_EXT_WORKSPACE_V1_REQUEST_ASSIGN: + case WLR_EXT_WORKSPACE_V1_REQUEST_REMOVE: + break; // Not advertised: Treeland has one workspace group spanning its outputs. + } + } +} diff --git a/src/session/sessionworkspace.h b/src/session/sessionworkspace.h new file mode 100644 index 0000000000..af5dfccced --- /dev/null +++ b/src/session/sessionworkspace.h @@ -0,0 +1,44 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "sessioncomponent.h" + +#include +#include + +class WaylandServer; +class Workspace; +class WorkspaceModel; +class RootSurfaceContainer; + +class SessionWorkspace : public SessionComponent +{ + Q_OBJECT +public: + SessionWorkspace(Session *session, WaylandServer *runtime); + ~SessionWorkspace() override; + + Workspace *workspace() const; + void installProtocol(); + +protected: + void activate() override; + void deactivate() override; + +private: + void initializeProtocol(); + void invalidateProtocol(); + void syncModels(); + void syncOutputs(); + void handleCommit(wlr_ext_workspace_v1_commit_event *event); + + RootSurfaceContainer *const m_root; + QPointer m_workspace; + QPointer m_protocol; + wlr_ext_workspace_group_handle_v1 *m_group = nullptr; + QHash m_handles; + QList> m_outputs; + const QByteArray m_protocolIdPrefix; +}; diff --git a/src/session/toplevelcapturesource.cpp b/src/session/toplevelcapturesource.cpp new file mode 100644 index 0000000000..be148e3ede --- /dev/null +++ b/src/session/toplevelcapturesource.cpp @@ -0,0 +1,23 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "toplevelcapturesource.h" +#include "toplevelcaptureviewport.h" + +#include "output/output.h" +#include "surface/surfacewrapper.h" + +ToplevelCaptureSource::ToplevelCaptureSource(SurfaceWrapper *wrapper) + : WExtImageCaptureSourceV1Impl(wrapper) + , m_wrapper(wrapper) +{ +} + +WOutputViewport *ToplevelCaptureSource::createViewport() +{ + // Resolve the output per session: the window may have moved while no + // client was capturing it. + if (!m_wrapper || !m_wrapper->surfaceItem() || !m_wrapper->ownsOutput()) + return nullptr; + return new ToplevelCaptureViewport(m_wrapper, m_wrapper->ownsOutput()->output()); +} diff --git a/src/session/toplevelcapturesource.h b/src/session/toplevelcapturesource.h new file mode 100644 index 0000000000..075ea70272 --- /dev/null +++ b/src/session/toplevelcapturesource.h @@ -0,0 +1,25 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class SurfaceWrapper; + +// Per-request toplevel source with a viewport shared by its capture sessions. +class ToplevelCaptureSource final : public WExtImageCaptureSourceV1Impl +{ +public: + explicit ToplevelCaptureSource(SurfaceWrapper *wrapper); + +protected: + WOutputViewport *createViewport() override; + +private: + QPointer m_wrapper; +}; diff --git a/src/session/toplevelcaptureviewport.cpp b/src/session/toplevelcaptureviewport.cpp new file mode 100644 index 0000000000..89923f57bd --- /dev/null +++ b/src/session/toplevelcaptureviewport.cpp @@ -0,0 +1,179 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "toplevelcaptureviewport.h" + +#include "core/qmlengine.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" + +#include +#include +#include + +namespace { +// A second view of the committed wl_surface tree, not a SurfaceWrapper proxy: +// those can configure/activate the shared shell surface. Capture is read-only. +class CaptureSurfaceItem final : public WSurfaceItem +{ +public: + CaptureSurfaceItem(SurfaceWrapper *wrapper, QQuickItem *parent) + : WSurfaceItem(parent) + , m_wrapper(wrapper) + { + setResizeMode(ManualResize); + setFlags(RejectEvent); + } + +protected: + bool doResizeSurface(const QSize &) override { return false; } + + QRectF getContentGeometry() const override + { + return shellSurface()->getContentGeometry(); + } + + QSizeF getContentSize() const override + { + return m_wrapper->type() == SurfaceWrapper::Type::XWayland + ? getContentGeometry().size() : WSurfaceItem::getContentSize(); + } + +private: + SurfaceWrapper *const m_wrapper; +}; +} + +ToplevelCaptureViewport::ToplevelCaptureViewport(SurfaceWrapper *wrapper, WOutput *output) + : WOutputViewport(wrapper->surfaceItem()->window()->contentItem()) + , m_wrapper(wrapper) + , m_surfaceItem(new CaptureSurfaceItem(wrapper, this)) +{ + setVisible(false); + setOffscreen(true); + setHideSource(false); + setIgnoreViewport(true); + setColorContentsMode(WGlobal::ColorContentsMode::Clear); + + auto *engine = WaylandServer::instance()->qmlEngine(); + QQmlEngine::setContextForObject(this, engine->rootContext()); + QQmlEngine::setContextForObject(m_surfaceItem, engine->rootContext()); + m_surfaceItem->setDelegate(engine->captureSurfaceContentComponent()); + m_surfaceItem->setShellSurface(wrapper->shellSurface()); + + // Cull the private subtree from the main scene and input, not its effect renderer. + QQuickItemPrivate::get(m_surfaceItem)->setCulled(true); + setInput(m_surfaceItem); + setOutput(output); + + auto *source = wrapper->surfaceItem(); + connect(source, &WSurfaceItem::widthChanged, + this, &ToplevelCaptureViewport::updateSurfaceGeometry); + connect(source, &WSurfaceItem::heightChanged, + this, &ToplevelCaptureViewport::updateSurfaceGeometry); + connect(source, &WSurfaceItem::surfaceSizeRatioChanged, + this, &ToplevelCaptureViewport::updateSurfaceGeometry); + connect(source, &WSurfaceItem::topPaddingChanged, + this, &ToplevelCaptureViewport::updateSurfaceGeometry); + connect(source, &WSurfaceItem::bottomPaddingChanged, + this, &ToplevelCaptureViewport::updateSurfaceGeometry); + connect(source, &WSurfaceItem::leftPaddingChanged, + this, &ToplevelCaptureViewport::updateSurfaceGeometry); + connect(source, &WSurfaceItem::rightPaddingChanged, + this, &ToplevelCaptureViewport::updateSurfaceGeometry); + connect(source, &WSurfaceItem::flagsChanged, + this, &ToplevelCaptureViewport::updateSurfaceFlags); + connect(source, &WSurfaceItem::smoothChanged, m_surfaceItem, &WSurfaceItem::setSmooth); + connect(m_surfaceItem, &WSurfaceItem::boundingRectChanged, + this, &ToplevelCaptureViewport::updateGeometry); + connect(wrapper, &SurfaceWrapper::noTitleBarChanged, + this, &ToplevelCaptureViewport::updateDecoration); + connect(wrapper, &SurfaceWrapper::noDecorationChanged, + this, &ToplevelCaptureViewport::updateDecoration); + connect(wrapper, &SurfaceWrapper::visibleDecorationChanged, + this, &ToplevelCaptureViewport::updateDecoration); + connect(wrapper, &SurfaceWrapper::borderChanged, + this, &ToplevelCaptureViewport::updateDecoration); + connect(wrapper, &SurfaceWrapper::radiusChanged, + this, &ToplevelCaptureViewport::updateDecoration); + connect(output, &WOutput::scaleChanged, + this, &ToplevelCaptureViewport::updateGeometry); + + updateSurfaceFlags(); + m_surfaceItem->setSmooth(source->smooth()); + updateSurfaceGeometry(); +} + +SurfaceWrapper *ToplevelCaptureViewport::sourceSurface() const +{ + return m_wrapper; +} + +void ToplevelCaptureViewport::updateSurfaceFlags() +{ + m_surfaceItem->setFlags(m_wrapper->surfaceItem()->flags() | WSurfaceItem::RejectEvent); +} + +void ToplevelCaptureViewport::updateSurfaceGeometry() +{ + auto *source = m_wrapper->surfaceItem(); + m_surfaceItem->setSurfaceSizeRatio(source->surfaceSizeRatio()); + m_surfaceItem->setTopPadding(source->topPadding()); + m_surfaceItem->setBottomPadding(source->bottomPadding()); + m_surfaceItem->setLeftPadding(source->leftPadding()); + m_surfaceItem->setRightPadding(source->rightPadding()); + m_surfaceItem->setSize(source->size()); + updateDecoration(); +} + +void ToplevelCaptureViewport::updateDecoration() +{ + auto *engine = WaylandServer::instance()->qmlEngine(); + if (m_wrapper->noTitleBar()) { + if (m_titleBar) { + m_titleBar->setVisible(false); + m_titleBar->deleteLater(); + m_titleBar = nullptr; + } + } else if (!m_titleBar) { + m_titleBar = engine->createTitleBar(m_wrapper, m_surfaceItem); + m_titleBar->setZ(static_cast(WSurfaceItem::ZOrder::ContentItem)); + } + + const bool borderVisible = !m_wrapper->noDecoration() && m_wrapper->visibleDecoration() + && m_wrapper->borderVisible(); + if (borderVisible && !m_border) { + m_border = engine->createBorder(m_surfaceItem); + m_border->setZ(static_cast(WSurfaceItem::ZOrder::ContentItem) + 1); + } + if (m_border) { + m_border->setVisible(borderVisible); + m_border->setSize(m_surfaceItem->size()); + m_border->setProperty("radius", m_wrapper->radius()); + m_border->setProperty("outsideColor", m_wrapper->borderColor()); + m_border->setProperty("borderWidth", m_wrapper->borderWidth()); + } + updateGeometry(); +} + +void ToplevelCaptureViewport::updateGeometry() +{ + if (!output()) + return; + const qreal dpr = output()->scale(); + QRectF bounds = m_surfaceItem->boundingRect(); + if (!m_wrapper->noDecoration() && m_wrapper->visibleDecoration() + && m_wrapper->borderVisible()) { + // Only the outer SSD stroke extends beyond the surface tree. A shadow + // is never created, and all bounds are local to the private input. + const qreal border = m_wrapper->borderWidth(); + bounds |= QRectF(QPointF(), m_surfaceItem->size()).adjusted(-border, -border, border, border); + } + + const QRect pixels(QPoint(qFloor(bounds.left() * dpr), qFloor(bounds.top() * dpr)), + QPoint(qCeil(bounds.right() * dpr) - 1, qCeil(bounds.bottom() * dpr) - 1)); + setDevicePixelRatio(dpr); + setSize(QSizeF(pixels.size()) / dpr); + setSourceRect(QRectF(QPointF(pixels.topLeft()) / dpr, size())); + setBufferSize(pixels.size()); +} diff --git a/src/session/toplevelcaptureviewport.h b/src/session/toplevelcaptureviewport.h new file mode 100644 index 0000000000..2e2a52811a --- /dev/null +++ b/src/session/toplevelcaptureviewport.h @@ -0,0 +1,33 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +class SurfaceWrapper; +Q_MOC_INCLUDE("surface/surfacewrapper.h") + +WAYLIB_SERVER_USE_NAMESPACE + +class ToplevelCaptureViewport final : public WOutputViewport +{ + Q_OBJECT + Q_PROPERTY(SurfaceWrapper *sourceSurface READ sourceSurface CONSTANT) + +public: + ToplevelCaptureViewport(SurfaceWrapper *wrapper, WOutput *output); + SurfaceWrapper *sourceSurface() const; + +private: + void updateSurfaceGeometry(); + void updateSurfaceFlags(); + void updateDecoration(); + void updateGeometry(); + + SurfaceWrapper *const m_wrapper; + WSurfaceItem *const m_surfaceItem; + QPointer m_titleBar; + QQuickItem *m_border = nullptr; +}; diff --git a/src/showdesktop/showdesktop.cpp b/src/showdesktop/showdesktop.cpp new file mode 100644 index 0000000000..eaaae9be3d --- /dev/null +++ b/src/showdesktop/showdesktop.cpp @@ -0,0 +1,110 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "showdesktop.h" +#include "core/waylandserver.h" +#include "core/rootsurfacecontainer.h" +#include "core/shellhandler.h" +#include "core/layersurfacecontainer.h" +#include "output/outputmanager.h" +#include "seat/seatmanager.h" +#include "surface/surfacewrapper.h" + +ShowDesktop::ShowDesktop(WaylandServer *server, OutputManager *outputManager) + : QObject(server), + m_server(server), + m_outputManager(outputManager) +{} + +ShowDesktop::State ShowDesktop::state() const +{ + return m_showDesktop; +} + +void ShowDesktop::setState(State state) +{ + if (m_showDesktop == state) + return; + + m_showDesktop = state; + Q_EMIT stateChanged(); + const auto &surfaces = m_outputManager->workspaceSurfaces(); + for (auto &surface : surfaces) { + if (surface->isMinimized()) { + continue; + } + if (state == State::Normal) { + surface->startShowDesktopAnimation(true); + } else if (state == State::Show) { + surface->startShowDesktopAnimation(false); + } + } + + if (state == State::Show) { + // Find the desktop background surface first + SurfaceWrapper *desktopSurface = nullptr; + const auto &backgroundSurfaces = m_server->shellHandler()->backgroundContainer()->surfaces(); + for (SurfaceWrapper *w : backgroundSurfaces) { + if (w->isDesktop()) { + desktopSurface = w; + break; + } + } + + const auto &seats = m_server->seatManager()->seats(); + for (auto *seat : seats) { + auto *seatContainer = m_server->rootContainer()->getSeatContainer(seat); + // Seat may be in transition (hotplug); requestKeyboardFocus asserts + // on a missing seat container. + if (!seatContainer) + continue; + + // Dismiss any popup keyboard grab: the grab would redirect keyboard + // focus back to the popup and defeat the desktop-surface transfer. + seatContainer->dismissPopups(); + // Move keyboard focus to the desktop surface (or drop it when the + // desktop surface is unavailable) so layer-shell windows that close + // on focus loss exit. + m_server->requestKeyboardFocus(desktopSurface, Qt::OtherFocusReason, seat); + } + } else { + restoreShowDesktopFocus(); + } +} + +void ShowDesktop::restoreShowDesktopFocus() +{ + const auto &seats = m_server->seatManager()->seats(); + for (auto *seat : seats) { + if (auto *seatContainer = m_server->rootContainer()->getSeatContainer(seat)) + seatContainer->restoreShowDesktopFocus(); + } +} + +void ShowDesktop::cancelShowDesktop(SurfaceWrapper *excludeSurface) +{ + if (m_showDesktop != State::Show) + return; + m_showDesktop = State::Normal; + Q_EMIT stateChanged(); + const auto &surfaces = m_outputManager->workspaceSurfaces(); + for (auto &surface : surfaces) { + if (surface == excludeSurface) + continue; + if (!surface->isMinimized() && !surface->isVisible()) { + surface->setHideByShowDesk(true); + surface->minimize(/*onAnimation=*/ false); + } + } +} + +void ShowDesktop::restoreFromShowDesktop(SurfaceWrapper *activeSurface) +{ + if (m_showDesktop != State::Show) + return; + cancelShowDesktop(activeSurface); + if (activeSurface) { + activeSurface->restoreFromMinimized(); + } + restoreShowDesktopFocus(); +} diff --git a/src/showdesktop/showdesktop.h b/src/showdesktop/showdesktop.h new file mode 100644 index 0000000000..97c3548c1f --- /dev/null +++ b/src/showdesktop/showdesktop.h @@ -0,0 +1,37 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +class WaylandServer; +class OutputManager; +class SurfaceWrapper; + +class ShowDesktop : public QObject +{ + Q_OBJECT +public: + enum class State + { + Normal, + Show, + }; + + ShowDesktop(WaylandServer *server, OutputManager *outputManager); + + State state() const; + void setState(State state); + void cancelShowDesktop(SurfaceWrapper *excludeSurface = nullptr); + void restoreFromShowDesktop(SurfaceWrapper *activeSurface = nullptr); + void restoreShowDesktopFocus(); + +Q_SIGNALS: + void stateChanged(); + +private: + WaylandServer *m_server = nullptr; + OutputManager *m_outputManager = nullptr; + State m_showDesktop = State::Normal; +}; diff --git a/src/surface/framegeometry.cpp b/src/surface/framegeometry.cpp new file mode 100644 index 0000000000..ea3f1144e8 --- /dev/null +++ b/src/surface/framegeometry.cpp @@ -0,0 +1,53 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "framegeometry.h" + +#include +#include + +FrameGeometry::FrameGeometry(const QRectF &rect, qreal radius) +{ + if (rect.isEmpty() || !std::isfinite(rect.left()) || !std::isfinite(rect.top()) + || !std::isfinite(rect.right()) || !std::isfinite(rect.bottom())) + return; + m_rect = rect; + if (std::isfinite(radius)) + m_radius = std::clamp(radius, qreal(0), std::min(rect.width(), rect.height()) / 2); +} + +bool FrameGeometry::contains(const QPointF &point) const +{ + // Match Qt Quick's half-open bounds, including when used as a containmentMask. + if (!(point.x() >= m_rect.left() && point.x() < m_rect.right() + && point.y() >= m_rect.top() && point.y() < m_rect.bottom())) + return false; + if (m_radius == 0) + return true; + const qreal dx = point.x() - std::clamp(point.x(), m_rect.left() + m_radius, + m_rect.right() - m_radius); + const qreal dy = point.y() - std::clamp(point.y(), m_rect.top() + m_radius, + m_rect.bottom() - m_radius); + return dx * dx + dy * dy <= m_radius * m_radius; +} + +Qt::Edges FrameGeometry::resizeEdgesAt(const QPointF &point, qreal margin) const +{ + if (m_rect.isEmpty() || !std::isfinite(margin) || margin <= 0 || contains(point)) + return {}; + // Keep square resize corners for square windows. + const FrameGeometry outer(m_rect.adjusted(-margin, -margin, margin, margin), + m_radius > 0 ? m_radius + margin : 0); + if (!outer.contains(point)) + return {}; + Qt::Edges edges; + if (point.x() < m_rect.left() + m_radius) + edges |= Qt::LeftEdge; + else if (point.x() >= m_rect.right() - m_radius) + edges |= Qt::RightEdge; + if (point.y() < m_rect.top() + m_radius) + edges |= Qt::TopEdge; + else if (point.y() >= m_rect.bottom() - m_radius) + edges |= Qt::BottomEdge; + return edges; +} diff --git a/src/surface/framegeometry.h b/src/surface/framegeometry.h new file mode 100644 index 0000000000..43f5c53af7 --- /dev/null +++ b/src/surface/framegeometry.h @@ -0,0 +1,31 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include +#include +#include + +class FrameGeometry +{ + Q_GADGET + QML_VALUE_TYPE(frameGeometry) + Q_PROPERTY(QRectF rect READ rect CONSTANT) + Q_PROPERTY(qreal radius READ radius CONSTANT) + +public: + FrameGeometry() = default; + FrameGeometry(const QRectF &rect, qreal radius); + + QRectF rect() const { return m_rect; } + qreal radius() const { return m_radius; } + bool contains(const QPointF &point) const; + Qt::Edges resizeEdgesAt(const QPointF &point, qreal margin) const; + bool operator==(const FrameGeometry &) const = default; + +private: + QRectF m_rect; + qreal m_radius = 0; +}; + +Q_DECLARE_METATYPE(FrameGeometry) diff --git a/src/surface/frameinputmask.cpp b/src/surface/frameinputmask.cpp new file mode 100644 index 0000000000..d50148c842 --- /dev/null +++ b/src/surface/frameinputmask.cpp @@ -0,0 +1,45 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "frameinputmask.h" + +FrameInputMask::FrameInputMask(QQuickItem *parent) + : QQuickItem(parent) +{ +} + +void FrameInputMask::setFrameItem(QQuickItem *item) +{ + if (m_frameItem == item) + return; + m_frameItem = item; + Q_EMIT frameItemChanged(); +} + +void FrameInputMask::setTarget(QQuickItem *item) +{ + if (m_target == item) + return; + m_target = item; + Q_EMIT targetChanged(); +} + +bool FrameInputMask::inTarget(const QPointF &point) const +{ + return m_frameItem && m_target + && point.x() >= 0 && point.y() >= 0 + && point.x() < m_target->width() && point.y() < m_target->height(); +} + +bool FrameInputMask::contains(const QPointF &point) const +{ + if (m_resizeMargin > 0) + return edgesAt(point) != Qt::Edges(); + return inTarget(point) && m_geometry.contains(m_target->mapToItem(m_frameItem, point)); +} + +Qt::Edges FrameInputMask::edgesAt(const QPointF &point) const +{ + if (!inTarget(point)) + return {}; + return m_geometry.resizeEdgesAt(m_target->mapToItem(m_frameItem, point), m_resizeMargin); +} diff --git a/src/surface/frameinputmask.h b/src/surface/frameinputmask.h new file mode 100644 index 0000000000..fce469a7e3 --- /dev/null +++ b/src/surface/frameinputmask.h @@ -0,0 +1,40 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "framegeometry.h" +#include +#include + +// Keep the mask at (0, 0): QQuickItem subtracts its position before calling contains(). +class FrameInputMask : public QQuickItem +{ + Q_OBJECT + QML_ELEMENT + Q_PROPERTY(FrameGeometry geometry MEMBER m_geometry NOTIFY geometryChanged FINAL) + Q_PROPERTY(QQuickItem* frameItem READ frameItem WRITE setFrameItem NOTIFY frameItemChanged FINAL) + Q_PROPERTY(QQuickItem* target READ target WRITE setTarget NOTIFY targetChanged FINAL) + Q_PROPERTY(qreal resizeMargin MEMBER m_resizeMargin NOTIFY resizeMarginChanged FINAL) + +public: + explicit FrameInputMask(QQuickItem *parent = nullptr); + QQuickItem *frameItem() const { return m_frameItem; } + void setFrameItem(QQuickItem *item); + QQuickItem *target() const { return m_target; } + void setTarget(QQuickItem *item); + bool contains(const QPointF &point) const override; + Q_INVOKABLE Qt::Edges edgesAt(const QPointF &point) const; + +Q_SIGNALS: + void geometryChanged(); + void frameItemChanged(); + void targetChanged(); + void resizeMarginChanged(); + +private: + bool inTarget(const QPointF &point) const; + FrameGeometry m_geometry; + QPointer m_frameItem; + QPointer m_target; + qreal m_resizeMargin = 0; +}; diff --git a/src/surface/seatsurfacemanager.cpp b/src/surface/seatsurfacemanager.cpp new file mode 100644 index 0000000000..5d600fcf24 --- /dev/null +++ b/src/surface/seatsurfacemanager.cpp @@ -0,0 +1,578 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "seatsurfacemanager.h" + +#include "rootsurfacecontainer.h" +#include "treelanduserconfig.hpp" +#include "common/treelandlogging.h" +#include "core/waylandserver.h" +#include "showdesktop/showdesktop.h" +#include "seat/seatmanager.h" +#include "core/shellhandler.h" +#include "output/output.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +SeatSurfaceManager::SeatSurfaceManager(WSeat *seat, RootSurfaceContainer *parent) + : QObject(parent) + , m_seat(seat) + , m_rootContainer(parent) +{ + Q_ASSERT(seat); + Q_ASSERT(parent); + + auto *seatHandle = seat->handle(); + keyboardGrabBeginListener.init(&seatHandle->events.keyboard_grab_begin, + this, + &SeatSurfaceManager::onKeyboardGrabBegin); + keyboardGrabEndListener.init(&seatHandle->events.keyboard_grab_end, + this, + &SeatSurfaceManager::onKeyboardGrabEnd); +} + +SeatSurfaceManager::~SeatSurfaceManager() +{ + // Drop native listeners before ~WScopedListener runs: on seat removal the + // seat is detached/deleted before this object's deleteLater, and + // wlr_seat_destroy asserts the keyboard_grab listener lists are empty. + // (QObject::connect on qw_seat used to auto-disconnect.) + keyboardGrabBeginListener.disconnect(); + keyboardGrabEndListener.disconnect(); + endMoveResize(); +} + +void SeatSurfaceManager::setActivatedSurface(SurfaceWrapper *surface, Qt::FocusReason reason) +{ + Q_UNUSED(reason); + if (surface && !surface->acceptKeyboardFocus()) { + return; + } + + if (m_activatedSurface == surface) + return; + + if (m_activatedSurface) { + disconnect(m_activatedSurface, + &SurfaceWrapper::hasFocusCapabilityChanged, + this, + &SeatSurfaceManager::onActivatedSurfaceFocusCapabilityChanged); + } + + m_activatedSurface = surface; + + if (m_activatedSurface) { + connect(m_activatedSurface, + &SurfaceWrapper::hasFocusCapabilityChanged, + this, + &SeatSurfaceManager::onActivatedSurfaceFocusCapabilityChanged); + } + + Q_EMIT activatedSurfaceChanged(surface); +} + +void SeatSurfaceManager::onActivatedSurfaceFocusCapabilityChanged() +{ + if (!m_activatedSurface) + return; + + auto *server = WaylandServer::instance(); + if (!server) + return; + + // While showing the desktop, keyboard focus is on the desktop layer, not on the + // (hidden) activated surface; a focus-capability change of the activated + // surface must not yank keyboard focus back to the window. + if (server->showDesktopState() == ShowDesktop::State::Show) + return; + + if (m_activatedSurface->hasFocusCapability()) { + server->requestKeyboardFocus(m_activatedSurface, Qt::ActiveWindowFocusReason, m_seat); + } else { + server->requestKeyboardFocus(nullptr, Qt::ActiveWindowFocusReason, m_seat); + } +} + +void SeatSurfaceManager::setKeyboardFocusSurface(SurfaceWrapper *surface, Qt::FocusReason reason) +{ + if (m_keyboardFocusSurface == surface) + return; + Q_ASSERT(m_seat && m_seat->handle()); + + auto *oldSurface = m_keyboardFocusSurface; + + // Only check priority when transferring focus between two surfaces. + // Clearing focus to nullptr (e.g. surfaceDestroyed) must always be allowed. + if (oldSurface && surface) { + int oldSurfacePriority = oldSurface->shellSurface() ? oldSurface->shellSurface()->keyboardFocusPriority() : 0; + int newSurfacePriority = surface->shellSurface() ? surface->shellSurface()->keyboardFocusPriority() : 0; + if (oldSurfacePriority > newSurfacePriority) { + qCDebug(lcTlShell) << "Keyboard focus rejected: current surface priority" + << oldSurfacePriority + << "> new surface priority" + << newSurfacePriority; + return; + } + } + + // Clear focus from old surface if no other seat has it + if (oldSurface) { + bool otherSeatHasFocus = false; + do { + auto *server = WaylandServer::instance(); + if (!server) + break; + + auto *seatManager = server->seatManager(); + if (!seatManager) + break; + + const auto seats = seatManager->seats(); + for (auto *otherSeat : seats) { + if (otherSeat == m_seat) + continue; + auto *otherContainer = server->rootSurfaceContainer()->getSeatContainer(otherSeat); + if (otherContainer && otherContainer->keyboardFocusSurface() == oldSurface) { + otherSeatHasFocus = true; + break; + } + } + } while (false); + + if (!otherSeatHasFocus) + oldSurface->setFocus(false, Qt::OtherFocusReason); + } + + // Assign new keyboard focus surface and update interaction metadata + m_keyboardFocusSurface = surface; + m_seat->setKeyboardFocusSurface(surface ? surface->surface() : nullptr); + + if (surface) { + surface->setFocus(true, reason); + surface->setProperty("lastInteractingSeat", QVariant::fromValue(m_seat)); + surface->setProperty("lastInteractionTime", QDateTime::currentMSecsSinceEpoch()); + } +} + +void SeatSurfaceManager::restoreShowDesktopFocus() +{ + if (!m_activatedSurface || !m_activatedSurface->hasFocusCapability()) + return; + + // The seat may still be in transition (hotplug): without a container the + // subsequent keyboard focus request would assert. + if (!m_rootContainer || !m_rootContainer->getSeatContainer(m_seat)) + return; + + setKeyboardFocusSurface(m_activatedSurface, Qt::OtherFocusReason); +} + +WGlobal::CursorShape SeatSurfaceManager::resizeCursorShape(Qt::Edges edges) +{ + using Shape = WGlobal::CursorShape; + switch (edges) { + case Qt::TopEdge: + return Shape::TopSide; + case Qt::RightEdge: + return Shape::RightSide; + case Qt::BottomEdge: + return Shape::BottomSide; + case Qt::LeftEdge: + return Shape::LeftSide; + case Qt::TopEdge | Qt::LeftEdge: + return Shape::TopLeftCorner; + case Qt::TopEdge | Qt::RightEdge: + return Shape::TopRightCorner; + case Qt::BottomEdge | Qt::LeftEdge: + return Shape::BottomLeftCorner; + case Qt::BottomEdge | Qt::RightEdge: + return Shape::BottomRightCorner; + default: + return Shape::Invalid; + } +} + +void SeatSurfaceManager::beginMoveResize(SurfaceWrapper *surface, Qt::Edges edges, bool overrideCursor) +{ + if (!surface) + return; + if (m_moveResizeState.surface) + endMoveResize(); + // Move of a tiled/maximized window: instantly de-tile to Normal BEFORE + // recording startGeometry, so startGeometry captures normalGeometry and no + // state-change animation contends with doMoveResize's setPosition. + if (edges == Qt::Edges()) { + const auto st = surface->surfaceState(); + if (st == SurfaceWrapper::State::Tiling || st == SurfaceWrapper::State::Maximized) + surface->setSurfaceStateDirectly(SurfaceWrapper::State::Normal); + } + + if (surface->surfaceState() != SurfaceWrapper::State::Normal || + surface->isAnimationRunning()) + return; + + m_moveResizeState.surface = surface; + m_moveResizeState.edges = edges; + m_moveResizeState.startGeometry = surface->geometry(); + m_moveResizeState.settingPositionFlag = false; + m_moveResizeState.detectedTileMode = SurfaceWrapper::TileMode::None; + m_moveResizeState.edgeTilePreviewActive = false; + m_moveResizeState.edgeTileInnerBorder = false; + m_moveResizeState.detectedTileOutput = nullptr; + + surface->setXwaylandPositionFromSurface(false); + surface->setPositionAutomatic(false); + + if (overrideCursor && edges && m_seat) { + m_resizeCursor = m_seat->cursor(); + if (m_resizeCursor) + m_resizeCursor->setOverrideCursor(WCursor::toQCursor(resizeCursorShape(edges))); + } +} + +void SeatSurfaceManager::doMoveResize(const QPointF &delta) +{ + if (!m_moveResizeState.surface) + return; + + auto surface = m_moveResizeState.surface; + + if (m_moveResizeState.edges != Qt::Edges()) { + QRectF geo = m_moveResizeState.startGeometry; + + if (m_moveResizeState.edges & Qt::LeftEdge) + geo.setLeft(geo.left() + delta.x()); + if (m_moveResizeState.edges & Qt::TopEdge) + geo.setTop(geo.top() + delta.y()); + if (m_moveResizeState.edges & Qt::RightEdge) + geo.setRight(geo.right() + delta.x()); + if (m_moveResizeState.edges & Qt::BottomEdge) + geo.setBottom(geo.bottom() + delta.y()); + + QRectF alignedGeometry = surface->alignGeometryToPixelGrid(geo); + QSizeF targetSize = alignedGeometry.size(); + if (m_resizeClampActive) + targetSize = applyResizeClamp(targetSize); + surface->resize(targetSize); + } else { + auto newPos = m_moveResizeState.startGeometry.topLeft() + delta; + QPointF alignedPos = surface->alignToPixelGrid(newPos); + surface->setPosition(alignedPos); + } +} + +void SeatSurfaceManager::endMoveResize(bool alignLayerPosition) +{ + stopEdgeTileDelay(); + if (!m_moveResizeState.surface) + return; + + auto surface = m_moveResizeState.surface; + const bool alignPosition = alignLayerPosition && m_moveResizeState.edges != Qt::Edges() + && surface->type() == SurfaceWrapper::Type::Layer && surface->ownsOutput(); + const auto detectedMode = m_moveResizeState.detectedTileMode; + const bool previewActive = m_moveResizeState.edgeTilePreviewActive; + + // Clear state first so filterSurfaceStateChange won't intercept the + // subsequent setSurfaceState(Tiling) issued by SurfaceWrapper::applyTileMode. + m_moveResizeState.surface = nullptr; + m_moveResizeState.edges = Qt::Edges(); + m_moveResizeState.startGeometry = QRectF(); + m_moveResizeState.initialPosition = QPointF(); + m_moveResizeState.settingPositionFlag = false; + m_moveResizeState.detectedTileMode = SurfaceWrapper::TileMode::None; + m_moveResizeState.edgeTilePreviewActive = false; + m_moveResizeState.edgeTileInnerBorder = false; + m_moveResizeState.detectedTileOutput = nullptr; + + if (m_resizeCursor) { + const auto cursor = m_resizeCursor; + m_resizeCursor.clear(); + cursor->setOverrideCursor(WCursor::toQCursor(WGlobal::CursorShape::Invalid)); + } + + // Snap after clearing the resize state so the fixed-edge adjustment cannot undo it. + if (alignPosition) + surface->setPosition(surface->alignToPixelGrid(surface->position())); + + auto *sh = surface->shellSurface(); + if (sh && sh->isInitialized()) { + // Mark resize operation as complete + surface->shellSurface()->setResizeing(false); + surface->setXwaylandPositionFromSurface(true); + } + if (!previewActive || detectedMode == SurfaceWrapper::TileMode::None) { + // Ensure window is still visible on screen after a plain move/resize. + if (m_rootContainer) + m_rootContainer->ensureSurfaceNormalPositionValid(surface); + } else { + Output *out = nullptr; + if (m_rootContainer && m_seat && m_seat->cursor()) + out = m_rootContainer->outputAt(m_seat->cursor()->position()); + surface->applyTileMode(detectedMode, out); + } + + Q_EMIT moveResizeChanged(surface); +} + +SurfaceWrapper *SeatSurfaceManager::moveResizeSurface() const +{ + return m_moveResizeState.surface; +} + +void SeatSurfaceManager::cancelMoveResize() +{ + if (!m_moveResizeState.surface) + return; + + auto surface = m_moveResizeState.surface; + auto startGeo = m_moveResizeState.startGeometry; + // Cancel discards any edge-tiling detected during the move: restore the + // original (normal) geometry captured at beginMoveResize. + m_moveResizeState.detectedTileMode = SurfaceWrapper::TileMode::None; + m_moveResizeState.detectedTileOutput = nullptr; + m_moveResizeState.edgeTilePreviewActive = false; + m_moveResizeState.edgeTileInnerBorder = false; + + // Restore original geometry before ending + if (m_moveResizeState.edges != Qt::Edges()) { + surface->resize(surface->alignGeometryToPixelGrid(startGeo).size()); + } else { + surface->setPosition(surface->alignToPixelGrid(startGeo.topLeft())); + } + + endMoveResize(); +} + +void SeatSurfaceManager::setResizeClamp(qreal minW, qreal maxW, qreal minH, qreal maxH) +{ + m_resizeClampActive = true; + m_clampMinW = minW; + m_clampMaxW = maxW; + m_clampMinH = minH; + m_clampMaxH = maxH; +} + +void SeatSurfaceManager::clearResizeClamp() +{ + m_resizeClampActive = false; + m_clampMinW = m_clampMaxW = 0; + m_clampMinH = m_clampMaxH = 0; +} + +QSizeF SeatSurfaceManager::applyResizeClamp(const QSizeF &target) const +{ + QSizeF clamped = target; + + const Qt::Edges edges = m_moveResizeState.edges; + if (edges & (Qt::LeftEdge | Qt::RightEdge)) { + if (m_clampMinW > 0) + clamped.setWidth(qMax(clamped.width(), m_clampMinW)); + if (m_clampMaxW > 0) + clamped.setWidth(qMin(clamped.width(), m_clampMaxW)); + } + if (edges & (Qt::TopEdge | Qt::BottomEdge)) { + if (m_clampMinH > 0) + clamped.setHeight(qMax(clamped.height(), m_clampMinH)); + if (m_clampMaxH > 0) + clamped.setHeight(qMin(clamped.height(), m_clampMaxH)); + } + return clamped; +} + +void SeatSurfaceManager::cancelMoveResize(SurfaceWrapper *surface) +{ + // Only cancel if this surface is the one being moved/resized + if (m_moveResizeState.surface != surface) + return; + endMoveResize(); +} + +void SeatSurfaceManager::startEdgeTileDelay() +{ + if (!m_edgeTileDelayTimer) { + m_edgeTileDelayTimer = new QTimer(this); + m_edgeTileDelayTimer->setSingleShot(true); + connect(m_edgeTileDelayTimer, &QTimer::timeout, this, [this]() { + auto &mr = m_moveResizeState; + if (mr.surface && mr.edges == Qt::Edges() + && mr.detectedTileMode != SurfaceWrapper::TileMode::None) { + mr.edgeTilePreviewActive = true; + Output *out = nullptr; + if (m_rootContainer && m_seat && m_seat->cursor()) + out = m_rootContainer->outputAt(m_seat->cursor()->position()); + if (m_rootContainer) + m_rootContainer->updateEdgeTilePreview(mr.detectedTileMode, out, m_seat); + } + }); + } + auto *server = WaylandServer::instance(); + auto *cfg = server ? server->config() : nullptr; + m_edgeTileDelayTimer->setInterval(cfg ? cfg->edgeInnerDelayMs() : 250); + m_edgeTileDelayTimer->start(); +} + +void SeatSurfaceManager::stopEdgeTileDelay() +{ + if (m_edgeTileDelayTimer) + m_edgeTileDelayTimer->stop(); +} + +bool SeatSurfaceManager::shouldHandleShortcuts() const +{ + // Policy: Only primary seat handles shortcuts + // The primary seat is the first seat in seatManager's list + + auto *server = WaylandServer::instance(); + if (!server || !server->seatManager()) + return false; + + const auto &seats = server->seatManager()->seats(); + if (seats.isEmpty()) + return false; + + // In multi-seat environment, the fallback seat should handle shortcuts for backwards compatibility, + // or the primary seat designated by the user. If no fallback is defined, use the first seat. + if (auto *fallback = server->seatManager()->fallbackSeat()) { + return m_seat == fallback; + } + return m_seat == seats.first(); +} + +void SeatSurfaceManager::setMetaKeyPressed(bool pressed) +{ + if (m_metaKeyPressed == pressed) + return; + m_metaKeyPressed = pressed; +} + +void SeatSurfaceManager::surfaceDestroyed(SurfaceWrapper *surface) +{ + if (m_moveResizeState.surface == surface) { + endMoveResize(); + } + + if (m_activatedSurface == surface) { + setActivatedSurface(nullptr, Qt::OtherFocusReason); + } + + if (m_keyboardFocusSurface == surface) { + setKeyboardFocusSurface(nullptr); + } +} + +void SeatSurfaceManager::givePopupFocus(SurfaceWrapper *popupWrapper) +{ + if (!m_hasPopupGrab) + return; + + Q_ASSERT(popupWrapper); + auto *popupSurface = qobject_cast(popupWrapper->shellSurface()); + if (!popupSurface) + return; + + // Only give focus to popups that belong to our seat's active popup grab. + auto *wlrPopup = popupSurface->handle(); + if (!wlrPopup || wlrPopup->seat != m_seat->handle()) + return; + + // Move keyboard focus to the popup surface directly. + setKeyboardFocusSurface(popupWrapper, Qt::ActiveWindowFocusReason); + + qCDebug(lcTlPopupFocus) << "Moved keyboard focus to popup surface:" << popupWrapper; +} + +void SeatSurfaceManager::dismissPopups() +{ + if (!m_hasPopupGrab) + return; + + qCDebug(lcTlPopupFocus) << "Dismissing popup grab"; + wlr_seat_keyboard_end_grab(m_seat->handle()); +} + +void SeatSurfaceManager::onKeyboardGrabBegin() +{ + if (m_hasPopupGrab) { + // Already tracking a popup grab; nested popups share the same flag. + return; + } + + auto *seatNative = m_seat->handle(); + auto *grab = seatNative->keyboard_state.grab; + if (!grab) { + qCWarning(lcTlPopupFocus) << "keyboard_state.grab is null"; + return; + } + + // Detect IME keyboard grab: + // WInputMethodHelper::handleNewKGV2 sets activeKeyboardGrab before + // calling keyboard_start_grab, so it is already non-null when we get here. + // Use isActiveKeyboardGrabOwner() to check if the seat's current grab + // is the one installed by the IME helper. + if (auto *imHelper = WaylandServer::instance()->shellHandler()->inputMethodHelper(m_seat)) { + if (imHelper->isActiveKeyboardGrabOwner()) { + qCDebug(lcTlPopupFocus) << "IME keyboard grab started (not popup)"; + return; + } + } + + m_popupRestoreFocusTarget = m_keyboardFocusSurface; + m_hasPopupGrab = true; + qCDebug(lcTlPopupFocus) << "Popup keyboard grab started"; +} + +void SeatSurfaceManager::onKeyboardGrabEnd() +{ + if (!m_hasPopupGrab) + return; + + m_hasPopupGrab = false; + + auto *restoreSurface = m_popupRestoreFocusTarget.data(); + m_popupRestoreFocusTarget.clear(); + + // Focus was handed to something outside the popup chain during the grab + // (activation, layer surface): its new owner keeps the keyboard. + if (m_keyboardFocusSurface + && m_keyboardFocusSurface->type() != SurfaceWrapper::Type::XdgPopup) { + return; + } + + // Return focus to whatever held it before the popup grabbed it: the clicked + // window, or the desktop layer for a desktop context menu (the activated + // surface is a hidden window while showing the desktop). + if (!restoreSurface || !restoreSurface->hasFocusCapability()) + restoreSurface = m_activatedSurface; + + // While showing the desktop, allow returning focus to a desktop menu's + // parent, but never restore focus to a hidden activated window. + if (auto *server = WaylandServer::instance()) { + if (server->showDesktopState() == ShowDesktop::State::Show + && (!restoreSurface || !restoreSurface->isDesktop())) + return; + } + + qCDebug(lcTlPopupFocus) << "Popup keyboard grab ended, restoring focus to:" + << restoreSurface; + + if (restoreSurface && restoreSurface->hasFocusCapability()) { + setKeyboardFocusSurface(restoreSurface, Qt::ActiveWindowFocusReason); + } +} diff --git a/src/surface/seatsurfacemanager.h b/src/surface/seatsurfacemanager.h new file mode 100644 index 0000000000..7c354e8930 --- /dev/null +++ b/src/surface/seatsurfacemanager.h @@ -0,0 +1,109 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "surface/surfacewrapper.h" +#include +#include +#include +#include +#include + +class QTimer; + +class RootSurfaceContainer; +class Output; +class WaylandServer; + +class SeatSurfaceManager : public QObject +{ + Q_OBJECT + +public: + explicit SeatSurfaceManager(WSeat *seat, RootSurfaceContainer *parent); + ~SeatSurfaceManager() override; + + WSeat *seat() const { return m_seat; } + RootSurfaceContainer *rootContainer() const { return m_rootContainer; } + SurfaceWrapper *activatedSurface() const { return m_activatedSurface; } + void setActivatedSurface(SurfaceWrapper *surface, Qt::FocusReason reason); + SurfaceWrapper *keyboardFocusSurface() const { return m_keyboardFocusSurface; } + void setKeyboardFocusSurface(SurfaceWrapper *surface, Qt::FocusReason reason = Qt::OtherFocusReason); + + void restoreShowDesktopFocus(); + + struct MoveResizeState { + SurfaceWrapper *surface = nullptr; ///< The surface being moved/resized + Qt::Edges edges = Qt::Edges(); ///< Resize edges (empty for move) + QRectF startGeometry; ///< Geometry at start of move/resize + QPointF initialPosition; ///< Initial cursor position + bool settingPositionFlag = false; ///< Flag to prevent recursive updates + SurfaceWrapper::TileMode detectedTileMode = + SurfaceWrapper::TileMode::None; ///< Edge-tiling mode detected during move + bool edgeTilePreviewActive = false; ///< Whether the edge-tiling preview is activated + bool edgeTileInnerBorder = false; ///< Whether the detected edge is shared with an adjacent output (inner edge) + Output *detectedTileOutput = nullptr; ///< The output on which the edge was detected (for cross-screen preview updates) + }; + + MoveResizeState &moveResizeState() { return m_moveResizeState; } + const MoveResizeState &moveResizeState() const { return m_moveResizeState; } + void beginMoveResize(SurfaceWrapper *surface, Qt::Edges edges, bool overrideCursor); + void doMoveResize(const QPointF &delta); + void endMoveResize(bool alignLayerPosition = false); + SurfaceWrapper *moveResizeSurface() const; + void cancelMoveResize(SurfaceWrapper *surface); + void cancelMoveResize(); + void setResizeClamp(qreal minW, qreal maxW, qreal minH, qreal maxH); + void clearResizeClamp(); + void startEdgeTileDelay(); + void stopEdgeTileDelay(); + bool shouldHandleShortcuts() const; + bool metaKeyPressed() const { return m_metaKeyPressed; } + void setMetaKeyPressed(bool pressed); + void surfaceDestroyed(SurfaceWrapper *surface); + + // Popup keyboard grab management + void givePopupFocus(SurfaceWrapper *popupWrapper); + void dismissPopups(); + bool hasPopupGrab() const { return m_hasPopupGrab; } + +Q_SIGNALS: + void activatedSurfaceChanged(SurfaceWrapper *surface); + void moveResizeChanged(SurfaceWrapper *surface); + +private: + static WAYLIB_SERVER_NAMESPACE::WGlobal::CursorShape resizeCursorShape(Qt::Edges edges); + void onActivatedSurfaceFocusCapabilityChanged(); + void onKeyboardGrabBegin(); + void onKeyboardGrabEnd(); + + WSeat *m_seat = nullptr; + RootSurfaceContainer *m_rootContainer = nullptr; + + // Per-seat state + SurfaceWrapper *m_activatedSurface = nullptr; + SurfaceWrapper *m_keyboardFocusSurface = nullptr; + MoveResizeState m_moveResizeState; + QPointer m_resizeCursor; + bool m_metaKeyPressed = false; + + // Popup grab state + bool m_hasPopupGrab = false; + // Keyboard focus when the grab began; the surface to return it to once the + // popup closes. + QPointer m_popupRestoreFocusTarget; + QTimer *m_edgeTileDelayTimer = nullptr; + + bool m_resizeClampActive = false; + qreal m_clampMinW = 0; + qreal m_clampMaxW = 0; + qreal m_clampMinH = 0; + qreal m_clampMaxH = 0; + QSizeF applyResizeClamp(const QSizeF &target) const; + // Equivalent to the old QObject::connect on qw_seat; disconnect in the + // destructor so wlr_seat_destroy does not assert on leftover listeners + // when the seat is deleted before this object's deleteLater runs. + WAYLIB_SERVER_NAMESPACE::WScopedListener keyboardGrabBeginListener; + WAYLIB_SERVER_NAMESPACE::WScopedListener keyboardGrabEndListener; +}; diff --git a/src/surface/surfacecontainer.cpp b/src/surface/surfacecontainer.cpp new file mode 100644 index 0000000000..cf1a703d58 --- /dev/null +++ b/src/surface/surfacecontainer.cpp @@ -0,0 +1,295 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "surface/surfacecontainer.h" + +#include "output/output.h" +#include "core/rootsurfacecontainer.h" +#include "common/treelandlogging.h" + +SurfaceListModel::SurfaceListModel(QObject *parent) + : ObjectListModel("surface", parent) +{ +} + +QHash SurfaceListModel::roleNames() const +{ + auto roleMap = ObjectListModel::roleNames(); + roleMap.insert(Qt::InitialSortOrderRole, "orderIndex"); + + return roleMap; +} + +QMap SurfaceListModel::itemData(const QModelIndex &index) const +{ + auto datas = ObjectListModel::itemData(index); + if (datas.isEmpty()) + return datas; + + auto surface = surfaces().at(index.row()); + auto container = surface->container(); + const auto orderIndex = container->childItems().indexOf(surface); + Q_ASSERT(orderIndex >= 0); + datas.insert(Qt::InitialSortOrderRole, orderIndex); + + return datas; +} + +QVariant SurfaceListModel::data(const QModelIndex &index, int role) const +{ + if (!index.isValid() || index.row() >= m_objects.count()) + return {}; + + if (role == Qt::InitialSortOrderRole) { + auto surface = surfaces().at(index.row()); + auto container = surface->container(); + const auto orderIndex = container->childItems().indexOf(surface); + Q_ASSERT(orderIndex >= 0); + return orderIndex; + } + + return ObjectListModel::data(index, role); +} + +SurfaceFilterModel::SurfaceFilterModel(SurfaceListModel *parent) + : SurfaceListModel(parent) +{ + connect(parent, + &SurfaceListModel::surfaceAdded, + this, + &SurfaceFilterModel::initForSourceSurface); + connect(parent, &SurfaceListModel::surfaceRemoved, this, [this](SurfaceWrapper *surface) { + removeSurface(surface); + m_properties.erase(surface); + }); +} + +void SurfaceFilterModel::setFilter(std::function filter) +{ + m_filter = filter; + m_properties.clear(); + + for (auto surface : std::as_const(parent()->surfaces())) { + initForSourceSurface(surface); + } +} + +void SurfaceFilterModel::initForSourceSurface(SurfaceWrapper *surface) +{ + if (m_filter) { + makeBindingForSourceSurface(surface); + } + updateSurfaceVisibility(surface); +} + +void SurfaceFilterModel::makeBindingForSourceSurface(SurfaceWrapper *surface) +{ + Property &p = m_properties[surface]; + + if (!p.init) { + p.init = true; + p.notifier = p.prop.addNotifier([this, surface] { + updateSurfaceVisibility(surface); + }); + } + + p.setBinding([this, surface] { + return m_filter(surface); + }); +} + +void SurfaceFilterModel::updateSurfaceVisibility(SurfaceWrapper *surface) +{ + if (!m_filter) { + if (hasSurface(surface)) + return; + addSurface(surface); + return; + } + + Q_ASSERT(m_properties.contains(surface)); + Q_ASSERT(parent()->hasSurface(surface)); + const Property &p = m_properties.at(surface); + Q_ASSERT(p.init); + if (p.prop.value()) { + addSurface(surface); + } else { + removeSurface(surface); + } +} + +SurfaceContainer::SurfaceContainer(QQuickItem *parent) + : QQuickItem(parent) + , m_model(new SurfaceListModel(this)) +{ +} + +SurfaceContainer::SurfaceContainer(SurfaceContainer *parent) + : SurfaceContainer(static_cast(parent)) +{ + ensureQmlContext(); +} + +SurfaceContainer::~SurfaceContainer() +{ + if (!m_model->surfaces().isEmpty()) { + qCCritical(lcTlSurface) + << "SurfaceContainer destroyed with surfaces still attached:" << m_model->surfaces(); + } +} + +RootSurfaceContainer *SurfaceContainer::rootContainer() const +{ + SurfaceContainer *root = const_cast(this); + while (auto p = root->parentContainer()) { + root = p; + } + + auto r = qobject_cast(root); + Q_ASSERT(r); + return r; +} + +SurfaceContainer *SurfaceContainer::parentContainer() const +{ + return qobject_cast(parent()); +} + +QList SurfaceContainer::subContainers() const +{ + return findChildren(Qt::FindDirectChildrenOnly); +} + +void SurfaceContainer::setQmlEngine(QQmlEngine *engine) +{ + const auto *context = engine->contextForObject(this); + if (!context) { + engine->setContextForObject(this, engine->rootContext()); + } + + const auto subContainers = this->subContainers(); + for (auto sub : subContainers) { + sub->setQmlEngine(engine); + } +} + +void SurfaceContainer::addSurface(SurfaceWrapper *surface) +{ + doAddSurface(surface, true); +} + +void SurfaceContainer::removeSurface(SurfaceWrapper *surface) +{ + doRemoveSurface(surface, true); +} + +void SurfaceContainer::addOutput(Output *output) +{ + // Allow all outputs to manage surface containers, ensuring support + // for both Primary and Proxy (Copy Mode) displays. + const auto subContainers = this->subContainers(); + for (auto sub : subContainers) { + sub->addOutput(output); + } +} + +void SurfaceContainer::removeOutput(Output *output) +{ + const auto subContainers = this->subContainers(); + for (auto sub : subContainers) { + sub->removeOutput(output); + } +} + +void SurfaceContainer::ensureQmlContext() +{ + if (QQmlEngine *engine = qmlEngine(parentContainer())) { + parentContainer()->setQmlEngine(engine); + } +} + +void SurfaceContainer::geometryChange(const QRectF &newGeo, const QRectF &oldGeo) +{ + const auto subContainers = this->subContainers(); + for (SurfaceContainer *c : subContainers) { + c->setPosition(newGeo.topLeft()); + c->setSize(newGeo.size()); + } + + QQuickItem::geometryChange(newGeo, oldGeo); +} + +bool SurfaceContainer::doAddSurface(SurfaceWrapper *surface, bool setContainer) +{ + if (m_model->hasSurface(surface)) + return false; + + if (setContainer) { + if (surface->parent()) { + qCWarning(lcTlSurface) + << "Surface already has QObject parent, changing parent:" << surface + << "from:" << surface->parent() << "to:" << this; + } + Q_ASSERT(!surface->container()); + surface->setContainer(this); + surface->setParent(this); + } + + m_model->addSurface(surface); + Q_EMIT surfaceAdded(surface); + + if (auto p = parentContainer()) + p->addBySubContainer(this, surface); + + return true; +} + +bool SurfaceContainer::doRemoveSurface(SurfaceWrapper *surface, bool setContainer) +{ + if (!m_model->hasSurface(surface)) + return false; + + if (setContainer) { + Q_ASSERT(surface->container() == this); + surface->setContainer(nullptr); + // NOTE: Remove surface form Container will not clear it's parent + } + + m_model->removeSurface(surface); + Q_EMIT surfaceRemoved(surface); + + if (auto p = parentContainer()) + p->removeBySubContainer(this, surface); + + return true; +} + +void SurfaceContainer::addBySubContainer([[maybe_unused]] SurfaceContainer *sub, + SurfaceWrapper *surface) +{ + doAddSurface(surface, false); +} + +void SurfaceContainer::removeBySubContainer([[maybe_unused]] SurfaceContainer *sub, + SurfaceWrapper *surface) +{ + doRemoveSurface(surface, false); +} + +bool SurfaceContainer::filterSurfaceGeometryChanged(SurfaceWrapper *surface, + QRectF &newGeometry, + const QRectF &oldGeometry) +{ + if (auto p = parentContainer()) + return p->filterSurfaceGeometryChanged(surface, newGeometry, oldGeometry); + return false; +} + +bool SurfaceContainer::filterSurfaceStateChange(SurfaceWrapper *surface, + SurfaceWrapper::State newState, + SurfaceWrapper::State oldState) +{ + if (auto p = parentContainer()) + return p->filterSurfaceStateChange(surface, newState, oldState); + return false; +} diff --git a/src/surface/surfacecontainer.h b/src/surface/surfacecontainer.h new file mode 100644 index 0000000000..183d915280 --- /dev/null +++ b/src/surface/surfacecontainer.h @@ -0,0 +1,258 @@ +// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "surface/surfacewrapper.h" + +#include +#include +#include +#include + +#include + +Q_MOC_INCLUDE("core/rootsurfacecontainer.h") + +template +class ObjectListModel : public QAbstractListModel +{ +public: + explicit ObjectListModel(QByteArrayView objectName, QObject *parent = nullptr) + : QAbstractListModel(parent) + , m_name(objectName.toByteArray()) + { + } + + int rowCount(const QModelIndex &parent = QModelIndex()) const override + { + if (parent.isValid()) + return 0; + + return m_objects.count(); + } + + QVariant data(const QModelIndex &index, int role) const override + { + if (!index.isValid() || index.row() >= m_objects.count()) + return {}; + + if (role == Qt::DisplayRole) + return QVariant::fromValue(m_objects.at(index.row())); + + return {}; + } + + QMap itemData(const QModelIndex &index) const override + { + if (!index.isValid() || index.row() >= m_objects.count()) + return {}; + + QMap data; + data.insert(Qt::DisplayRole, QVariant::fromValue(m_objects.at(index.row()))); + return data; + } + + Qt::ItemFlags flags([[maybe_unused]] const QModelIndex &index) const override + { + return Qt::ItemIsSelectable | Qt::ItemIsEnabled; + } + + QHash roleNames() const override + { + return { { Qt::DisplayRole, m_name } }; + } + + bool addObject(T *object) + { + if (m_objects.contains(object)) + return false; + + beginInsertRows(QModelIndex(), m_objects.count(), m_objects.count()); + m_objects.append(object); + endInsertRows(); + return true; + } + + bool removeObject(T *object) + { + int index = m_objects.indexOf(object); + if (index < 0) + return false; + beginRemoveRows({}, index, index); + m_objects.removeAt(index); + endRemoveRows(); + return true; + } + + bool hasObject(T *object) const + { + return m_objects.contains(object); + } + + const QList &objects() const + { + return m_objects; + } + +protected: + QByteArray m_name; + QList m_objects; +}; + +class SurfaceListModel : public ObjectListModel +{ + Q_OBJECT + QML_ANONYMOUS + +public: + explicit SurfaceListModel(QObject *parent = nullptr); + + virtual void addSurface(SurfaceWrapper *surface) + { + if (addObject(surface)) + Q_EMIT surfaceAdded(surface); + } + + virtual void removeSurface(SurfaceWrapper *surface) + { + if (removeObject(surface)) + Q_EMIT surfaceRemoved(surface); + } + + QHash roleNames() const override; + QMap itemData(const QModelIndex &index) const override; + QVariant data(const QModelIndex &index, int role) const override; + + Q_INVOKABLE inline const QList &surfaces() const + { + return objects(); + } + + inline bool hasSurface(SurfaceWrapper *surface) const + { + return hasObject(surface); + } + +Q_SIGNALS: + void surfaceAdded(SurfaceWrapper *surface); + void surfaceRemoved(SurfaceWrapper *surface); + +private: + using ObjectListModel::addObject; + using ObjectListModel::removeObject; + using ObjectListModel::objects; +}; + +class SurfaceFilterModel : public SurfaceListModel +{ + Q_OBJECT + QML_ANONYMOUS + +public: + explicit SurfaceFilterModel(SurfaceListModel *parent); + + inline SurfaceListModel *parent() const + { + auto op = QObject::parent(); + auto p = qobject_cast(op); + Q_ASSERT(p); + return p; + } + + void setFilter(std::function filter); + +private: + using SurfaceListModel::addSurface; + using SurfaceListModel::removeSurface; + + void initForSourceSurface(SurfaceWrapper *surface); + void makeBindingForSourceSurface(SurfaceWrapper *surface); + void updateSurfaceVisibility(SurfaceWrapper *surface); + + std::function m_filter; + + struct Property + { + Property() + : prop(false) + { + } + + template + inline void setBinding(F f) + { + prop.setBinding(f); + } + + bool init = false; + QProperty prop; + QPropertyNotifier notifier; + }; + + std::map m_properties; +}; + +class Output; +class RootSurfaceContainer; + +class SurfaceContainer : public QQuickItem +{ + Q_OBJECT + Q_PROPERTY(SurfaceListModel* model READ model CONSTANT FINAL) + Q_PROPERTY(RootSurfaceContainer* root READ rootContainer CONSTANT FINAL) + QML_ANONYMOUS + +public: + explicit SurfaceContainer(QQuickItem *parent = nullptr); + explicit SurfaceContainer(SurfaceContainer *parent); + ~SurfaceContainer() override; + + RootSurfaceContainer *rootContainer() const; + SurfaceContainer *parentContainer() const; + QList subContainers() const; + void setQmlEngine(QQmlEngine *engine); + + virtual void addSurface(SurfaceWrapper *surface); + virtual void removeSurface(SurfaceWrapper *surface); + + virtual void addOutput(Output *output); + virtual void removeOutput(Output *output); + + const QList &surfaces() const + { + return m_model->surfaces(); + } + + SurfaceListModel *model() const + { + return m_model; + } + +Q_SIGNALS: + void surfaceAdded(SurfaceWrapper *surface); + void surfaceRemoved(SurfaceWrapper *surface); + +protected: + friend class SurfaceWrapper; + + void ensureQmlContext(); + void geometryChange(const QRectF &newGeo, const QRectF &oldGeo) override; + + bool doAddSurface(SurfaceWrapper *surface, bool setContainer); + bool doRemoveSurface(SurfaceWrapper *surface, bool setContainer); + + virtual void addBySubContainer([[maybe_unused]] SurfaceContainer *sub, SurfaceWrapper *surface); + virtual void removeBySubContainer([[maybe_unused]] SurfaceContainer *sub, + SurfaceWrapper *surface); + + virtual bool filterSurfaceGeometryChanged(SurfaceWrapper *surface, + QRectF &newGeometry, + const QRectF &oldGeometry); + virtual bool filterSurfaceStateChange(SurfaceWrapper *surface, + SurfaceWrapper::State newState, + SurfaceWrapper::State oldState); + + SurfaceListModel *m_model = nullptr; +}; + +Q_DECLARE_OPAQUE_POINTER(Output*) diff --git a/src/surface/surfacefilterproxymodel.cpp b/src/surface/surfacefilterproxymodel.cpp new file mode 100644 index 0000000000..afb2f2b172 --- /dev/null +++ b/src/surface/surfacefilterproxymodel.cpp @@ -0,0 +1,86 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "surfacefilterproxymodel.h" +#include "workspace/workspacemodel.h" +#include "surface/surfacewrapper.h" + +SurfaceFilterProxyModel::SurfaceFilterProxyModel(QObject *parent) + : QSortFilterProxyModel(parent) +{ +} + +void SurfaceFilterProxyModel::setFilterAppId(const QString &appid) +{ + if (m_filterAppId == appid) + return; + +#if QT_VERSION >= QT_VERSION_CHECK(6, 10, 0) + beginFilterChange(); + m_filterAppId = appid; + endFilterChange(); +#else + m_filterAppId = appid; + invalidateFilter(); +#endif +} + +QVariantList SurfaceFilterProxyModel::surfaceSnapshot() const +{ + QVariantList surfaces; + surfaces.reserve(rowCount()); + + for (int row = 0; row < rowCount(); ++row) { + surfaces.append(data(index(row, 0), Qt::DisplayRole)); + } + + return surfaces; +} + +int SurfaceFilterProxyModel::activeIndex() +{ + return m_activeIndex; +} + +void SurfaceFilterProxyModel::setActiveIndex(int index) +{ + if (m_activeIndex != index) { + m_activeIndex = index; + Q_EMIT activeIndexChanged(); + } +} + +bool SurfaceFilterProxyModel::filterAcceptsRow(int source_row, + const QModelIndex &source_parent) const +{ + QModelIndex index = sourceModel()->index(source_row, 0, source_parent); + SurfaceWrapper *surface = sourceModel()->data(index).value(); + + if (!surface || surface->skipSwitcher()) { + return false; + } + + if (m_filterAppId.isEmpty()) { + return true; + } + + return surface->appId() == m_filterAppId; +} + + +bool SurfaceFilterProxyModel::lessThan(const QModelIndex &source_left, + const QModelIndex &source_right) const +{ + WorkspaceModel *model = dynamic_cast(sourceModel()); + SurfaceWrapper *left = sourceModel()->data(source_left).value(); + SurfaceWrapper *right = sourceModel()->data(source_right).value(); + + if (model && left && right) { + if (model->laterActiveThan(left, right)) + return true; + else + return false; + } + + return QSortFilterProxyModel::lessThan(source_left, source_right); +} diff --git a/src/surface/surfacefilterproxymodel.h b/src/surface/surfacefilterproxymodel.h new file mode 100644 index 0000000000..cf1b3ec54d --- /dev/null +++ b/src/surface/surfacefilterproxymodel.h @@ -0,0 +1,32 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +class SurfaceFilterProxyModel : public QSortFilterProxyModel +{ + Q_OBJECT + Q_PROPERTY(int activeIndex READ activeIndex WRITE setActiveIndex NOTIFY activeIndexChanged FINAL) + +public: + explicit SurfaceFilterProxyModel(QObject *parent = nullptr); + + Q_INVOKABLE void setFilterAppId(const QString &appid); + Q_INVOKABLE QVariantList surfaceSnapshot() const; + + int activeIndex(); + void setActiveIndex(int index); + +Q_SIGNALS: + void activeIndexChanged(); + +protected: + bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; + bool lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const override; + +private: + QString m_filterAppId; + mutable int m_activeIndex = -1; +}; diff --git a/src/surface/surfaceproxy.cpp b/src/surface/surfaceproxy.cpp new file mode 100644 index 0000000000..307f5c9af3 --- /dev/null +++ b/src/surface/surfaceproxy.cpp @@ -0,0 +1,382 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "surfaceproxy.h" + +#include "core/qmlengine.h" +#include "surface/surfacewrapper.h" + +#include + +namespace { +// Display-only radius for a client-side decorated window in a non-maximized state, in proxy +// coordinates. Its clip contour stays square so the drawn corner and shadow in the client's +// buffer are not cut away. +constexpr qreal kClientSideDecoratedRadius = 6; +} + +SurfaceProxy::SurfaceProxy(QQuickItem *parent) + : QQuickItem(parent) +{ +} + +SurfaceProxy::~SurfaceProxy() +{ + if (m_proxySurface) { + m_proxySurface->destroy(); + m_proxySurface = nullptr; + } +} + +SurfaceWrapper *SurfaceProxy::surface() const +{ + return m_sourceSurface; +} + +void SurfaceProxy::setSurface(SurfaceWrapper *newSurface) +{ + if (m_sourceSurface == newSurface) + return; + + for (const QMetaObject::Connection &connection : std::as_const(m_sourceConnections)) { + QObject::disconnect(connection); + } + m_sourceConnections.clear(); + + m_sourceSurface = newSurface; + if (m_proxySurface) { + m_proxySurface->destroy(); + m_proxySurface = nullptr; + } + + if (m_sourceSurface) { + m_proxySurface = new SurfaceWrapper(m_sourceSurface, + this); + m_proxySurface->setTransformOrigin(QQuickItem::TransformOrigin::TopLeft); + m_proxySurface->setFlag(ItemIsFocusScope); + m_proxySurface->QQuickItem::setFocus(false); + QQuickItemPrivate::get(m_proxySurface)->culled = true; + if (!m_fullProxy) { + if (!m_shadow) + m_shadow = m_sourceSurface->m_engine->createXdgShadow(this); + m_shadow->stackBefore(m_proxySurface); + QQuickItemPrivate::get(m_shadow)->culled = true; + } + + m_sourceConnections << connect(m_proxySurface, &SurfaceWrapper::frameGeometryChanged, + this, &SurfaceProxy::updateShadowGeometry); + m_sourceConnections << connect(m_proxySurface, &QQuickItem::scaleChanged, + this, &SurfaceProxy::updateShadowGeometry); + m_sourceConnections << connect(m_proxySurface, &SurfaceWrapper::presentationFrameGeometryChanged, + this, &SurfaceProxy::effectiveRadiusChanged); + m_sourceConnections << connect(m_proxySurface, &QQuickItem::scaleChanged, + this, &SurfaceProxy::effectiveRadiusChanged); + auto updateProxyFlagsAndDelegate = [this]() { + auto proxyItem = m_proxySurface ? m_proxySurface->surfaceItem() : nullptr; + auto sourceItem = m_sourceSurface ? m_sourceSurface->surfaceItem() : nullptr; + if (!proxyItem) + return; + + const bool live = m_live && m_proxySurface->renderingEnabled(); + const auto flags = live ? WSurfaceItem::RejectEvent + : (WSurfaceItem::RejectEvent | WSurfaceItem::NonLive); + proxyItem->setFlags(flags); + + if (!sourceItem) + return; + proxyItem->setDelegate(sourceItem->delegate()); + }; + + updateProxyFlagsAndDelegate(); + m_sourceConnections << connect(m_proxySurface, &SurfaceWrapper::renderingEnabledChanged, + this, &SurfaceProxy::updateLive); + + m_sourceConnections << connect(m_proxySurface, + &SurfaceWrapper::surfaceItemCreated, + this, + updateProxyFlagsAndDelegate); + + if (auto sourceItem = m_sourceSurface->surfaceItem()) { + m_sourceConnections << connect(sourceItem, + &WSurfaceItem::delegateChanged, + this, + updateProxyFlagsAndDelegate); + } else { + m_sourceConnections << connect(m_sourceSurface, + &SurfaceWrapper::surfaceItemCreated, + this, + [this, updateProxyFlagsAndDelegate]() { + if (auto srcItem = m_sourceSurface->surfaceItem()) { + updateProxyFlagsAndDelegate(); + m_sourceConnections << connect(srcItem, + &WSurfaceItem::delegateChanged, + this, + updateProxyFlagsAndDelegate); + } + }); + } + m_sourceConnections << connect(m_sourceSurface, &SurfaceWrapper::destroyed, this, [this] { + Q_ASSERT(m_proxySurface); + setSurface(nullptr); + }); + m_sourceConnections << connect(m_sourceSurface, + &SurfaceWrapper::noTitleBarChanged, + this, + &SurfaceProxy::updateNoTitleBar); + m_sourceConnections << connect(m_sourceSurface, + &SurfaceWrapper::radiusChanged, + this, + &SurfaceProxy::onSourceRadiusChanged); + m_sourceConnections << connect(m_sourceSurface, + &SurfaceWrapper::noDecorationChanged, + this, + &SurfaceProxy::updateNoDecoration); + // The proxy radius depends on the source decoration mode and state. + m_sourceConnections << connect(m_sourceSurface, + &SurfaceWrapper::noDecorationChanged, + this, + &SurfaceProxy::updateProxySurfaceScale); + m_sourceConnections << connect(m_sourceSurface, + &SurfaceWrapper::surfaceStateChanged, + this, + &SurfaceProxy::updateProxySurfaceScale); + // effectiveRadius() also reads the source state (a client-side decorated proxy keeps a + // display radius while its clip contour is square), so notify it directly. + m_sourceConnections << connect(m_sourceSurface, + &SurfaceWrapper::surfaceStateChanged, + this, + &SurfaceProxy::effectiveRadiusChanged); + + m_sourceConnections << connect(m_proxySurface, + &SurfaceWrapper::widthChanged, + this, + &SurfaceProxy::updateImplicitSize); + m_sourceConnections << connect(m_proxySurface, + &SurfaceWrapper::heightChanged, + this, + &SurfaceProxy::updateImplicitSize); + + updateImplicitSize(); + updateProxySurfaceScale(); + updateShape(); + updateShadowGeometry(); + } else { + if (m_shadow) { + m_shadow->deleteLater(); + m_shadow = nullptr; + } + } + + onSourceRadiusChanged(); + Q_EMIT surfaceChanged(); + Q_EMIT effectiveRadiusChanged(); +} + +void SurfaceProxy::geometryChange(const QRectF &newGeo, const QRectF &oldGeo) +{ + QQuickItem::geometryChange(newGeo, oldGeo); + + if (m_proxySurface && newGeo.size() != oldGeo.size()) { + updateProxySurfaceScale(); + updateShadowGeometry(); + } +} + +void SurfaceProxy::updateProxySurfaceScale() +{ + if (size().isEmpty()) { + onSourceRadiusChanged(); + return; + } + + QSizeF surfaceSize = m_proxySurface->size(); + surfaceSize.scale(size(), Qt::KeepAspectRatio); + + if (surfaceSize.width() < m_proxySurface->width()) + m_proxySurfaceScale = surfaceSize.width() / m_proxySurface->width(); + else + m_proxySurfaceScale = 1.0; + m_proxySurface->setScale(m_proxySurfaceScale); + onSourceRadiusChanged(); +} + +void SurfaceProxy::updateShadowGeometry() +{ + if (!m_shadow || !m_proxySurface) + return; + const auto geometry = m_proxySurface->frameGeometry(); + m_shadow->setSize(geometry.rect().size() * m_proxySurface->scale()); + m_shadow->setProperty("cornerRadius", geometry.radius() * m_proxySurface->scale()); +} + +void SurfaceProxy::updateShape() +{ + updateNoTitleBar(); + updateNoDecoration(); +} + +void SurfaceProxy::updateNoTitleBar() +{ + m_proxySurface->setNoTitleBar(m_sourceSurface->noTitleBar()); +} + +void SurfaceProxy::updateNoDecoration() +{ + m_proxySurface->setNoDecoration(m_fullProxy ? m_sourceSurface->noDecoration() : false); + // radius() already decides whether the thumbnail needs rounded clipping. + m_proxySurface->setNoCornerRadius(false); +} + +void SurfaceProxy::updateImplicitSize() +{ + if (!m_proxySurface) { + return; + } + + const auto size = m_proxySurface->size(); + if (size.isEmpty()) { + return; + } + + const auto scaledSize = size.scaled(m_maxSize, Qt::KeepAspectRatio); + const auto scale = scaledSize.width() / size.width(); + setImplicitSize(size.width() * scale, size.height() * scale); +} + +void SurfaceProxy::onSourceRadiusChanged() +{ + const qreal newRadius = radius(); + if (m_proxySurface) + m_proxySurface->setRadius(newRadius / m_proxySurfaceScale); + if (qFuzzyCompare(m_lastRadius, newRadius)) + return; + m_lastRadius = newRadius; + Q_EMIT radiusChanged(); +} + +bool SurfaceProxy::isFullSizeState() const +{ + const auto state = m_sourceSurface->surfaceState(); + return state == SurfaceWrapper::State::Maximized + || state == SurfaceWrapper::State::Fullscreen; +} + +bool SurfaceProxy::keepsClientSideMargins() const +{ + if (!m_sourceSurface || !m_sourceSurface->noDecoration()) + return false; + // A maximized or fullscreen client drops its CSD margins: there is no drawn corner or + // shadow left in the buffer to protect. + return !isFullSizeState(); +} + +qreal SurfaceProxy::radius() const +{ + if (m_radius >= 0) + return m_radius; + if (!m_sourceSurface) + return 0; + // A client-side decorated client draws its corners and shadow inside its own buffer, + // outside the frame geometry, so a rounded clip would cut that shadow away. + if (keepsClientSideMargins()) + return 0; + // A maximized or fullscreen window has no visible corner of its own, and its window radius + // shrunk to thumbnail scale is only a few pixels there, so the thumbnail takes the radius + // as a display value instead of a faithful sample of the scaled window. + if (isFullSizeState()) + return m_sourceSurface->radius(); + // A thumbnail keeps the window's corner shape: the radius shrinks with the proxy. + return m_sourceSurface->radius() * m_proxySurfaceScale; +} + +qreal SurfaceProxy::effectiveRadius() const +{ + // The outline keeps a display radius for a thumbnail whose clip contour is square. + if (m_radius < 0 && keepsClientSideMargins()) + return kClientSideDecoratedRadius; + return m_proxySurface + ? m_proxySurface->presentationFrameGeometry().radius() * m_proxySurface->scale() + : 0; +} + +void SurfaceProxy::setRadius(qreal newRadius) +{ + if (qFuzzyCompare(m_radius, newRadius)) + return; + m_radius = newRadius; + onSourceRadiusChanged(); +} + +void SurfaceProxy::resetRadius() +{ + setRadius(-1); +} + +bool SurfaceProxy::live() const +{ + return m_live; +} + +void SurfaceProxy::updateLive() +{ + auto *item = m_proxySurface ? m_proxySurface->surfaceItem() : nullptr; + if (!item) + return; + const bool live = m_live && m_proxySurface->renderingEnabled(); + item->setFlags(live ? item->flags() & ~WSurfaceItem::NonLive + : item->flags() | WSurfaceItem::NonLive); +} + +void SurfaceProxy::setLive(bool newLive) +{ + if (m_live == newLive) + return; + m_live = newLive; + updateLive(); + + Q_EMIT liveChanged(); +} + +QSizeF SurfaceProxy::maxSize() const +{ + return m_maxSize; +} + +void SurfaceProxy::setMaxSize(const QSizeF &newMaxSize) +{ + if (m_maxSize == newMaxSize) + return; + m_maxSize = newMaxSize; + updateImplicitSize(); + + Q_EMIT maxSizeChanged(); +} + +bool SurfaceProxy::fullProxy() const +{ + return m_fullProxy; +} + +void SurfaceProxy::setFullProxy(bool newFullProxy) +{ + if (m_fullProxy == newFullProxy) + return; + m_fullProxy = newFullProxy; + + if (m_proxySurface) { + if (m_fullProxy) { + if (m_shadow) { + m_shadow->deleteLater(); + m_shadow = nullptr; + } + } else if (!m_shadow) { + m_shadow = m_sourceSurface->m_engine->createXdgShadow(this); + m_shadow->stackBefore(m_proxySurface); + QQuickItemPrivate::get(m_shadow)->culled = true; + } + updateShape(); + updateShadowGeometry(); + } + + Q_EMIT fullProxyChanged(); +} diff --git a/src/surface/surfaceproxy.h b/src/surface/surfaceproxy.h new file mode 100644 index 0000000000..e912e80d09 --- /dev/null +++ b/src/surface/surfaceproxy.h @@ -0,0 +1,73 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +class SurfaceWrapper; + +class SurfaceProxy : public QQuickItem +{ + Q_OBJECT + Q_PROPERTY(SurfaceWrapper* surface READ surface WRITE setSurface NOTIFY surfaceChanged FINAL) + Q_PROPERTY(qreal radius READ radius WRITE setRadius RESET resetRadius NOTIFY radiusChanged FINAL) + Q_PROPERTY(qreal effectiveRadius READ effectiveRadius NOTIFY effectiveRadiusChanged FINAL) + Q_PROPERTY(bool live READ live WRITE setLive NOTIFY liveChanged FINAL) + Q_PROPERTY(QSizeF maxSize READ maxSize WRITE setMaxSize NOTIFY maxSizeChanged FINAL) + Q_PROPERTY(bool fullProxy READ fullProxy WRITE setFullProxy NOTIFY fullProxyChanged FINAL) + QML_ELEMENT + +public: + explicit SurfaceProxy(QQuickItem *parent = nullptr); + ~SurfaceProxy() override; + + SurfaceWrapper *surface() const; + void setSurface(SurfaceWrapper *newSurface); + + qreal radius() const; + qreal effectiveRadius() const; + void setRadius(qreal newRadius); + void resetRadius(); + + bool live() const; + void setLive(bool newLive); + + QSizeF maxSize() const; + void setMaxSize(const QSizeF &newMaxSize); + + bool fullProxy() const; + void setFullProxy(bool newFullProxy); + +Q_SIGNALS: + void surfaceChanged(); + void radiusChanged(); + void effectiveRadiusChanged(); + void liveChanged(); + void maxSizeChanged(); + void fullProxyChanged(); + +private: + void geometryChange(const QRectF &newGeo, const QRectF &oldGeo) override; + void updateProxySurfaceScale(); + void updateShadowGeometry(); + void updateShape(); + void updateLive(); + void updateNoTitleBar(); + void updateNoDecoration(); + void updateImplicitSize(); + void onSourceRadiusChanged(); + bool isFullSizeState() const; + bool keepsClientSideMargins() const; + + SurfaceWrapper *m_sourceSurface = nullptr; + SurfaceWrapper *m_proxySurface = nullptr; + QList m_sourceConnections; + QQuickItem *m_shadow = nullptr; + qreal m_radius = -1; + qreal m_lastRadius = 0; + qreal m_proxySurfaceScale = 1; + bool m_live = true; + bool m_fullProxy = false; + QSizeF m_maxSize; +}; diff --git a/src/surface/surfacewindowtransition.cpp b/src/surface/surfacewindowtransition.cpp new file mode 100644 index 0000000000..2ccaea7468 --- /dev/null +++ b/src/surface/surfacewindowtransition.cpp @@ -0,0 +1,178 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "surfacewindowtransition.h" + +#include "surface/surfacewrapper.h" + +#include +#include + +#include + +SurfaceWindowTransition::SurfaceWindowTransition(SurfaceWrapper *wrapper) + : WindowTransitionTarget() + , m_wrapper(wrapper) +{ +} + +bool SurfaceWindowTransition::active() const +{ + return m_hasRect && !m_localRect.isEmpty(); +} + +WSurface *SurfaceWindowTransition::sourceSurface() const +{ + auto *source = m_source.data(); + return source ? source->surface() : nullptr; +} + +std::optional SurfaceWindowTransition::globalRect() const +{ + if (!m_hasRect || !m_origin) + return std::nullopt; + + const auto topLeft = m_origin->mapTransitionPointToGlobal(m_localRect.topLeft()); + if (!topLeft) + return std::nullopt; + + return QRectF(*topLeft, m_localRect.size()); +} + +void SurfaceWindowTransition::begin() +{ + if (m_phase == Phase::Playing) + return; + + m_phase = Phase::Playing; + m_retainedOutputs = m_wrapper->outputs(); + if (m_source) + m_source->retain(m_retainedOutputs); +} + +void SurfaceWindowTransition::endAnimation(bool wrapperAboutToRemove) +{ + releaseSourceOutputs(); + + if (wrapperAboutToRemove) { + if (m_sourceDestroyConnection) + QObject::disconnect(m_sourceDestroyConnection); + m_sourceDestroyConnection = { }; + m_phase = Phase::Idle; + m_hasRect = false; + m_localRect = { }; + m_origin = nullptr; + m_source = nullptr; + Q_EMIT windowTransitionFinished(); + } else { + m_phase = m_hasRect ? Phase::Armed : Phase::Idle; + } +} + +void SurfaceWindowTransition::resetWindowTransition() +{ + const bool wasArmed = m_hasRect; + + releaseSourceOutputs(); + if (m_sourceDestroyConnection) + QObject::disconnect(m_sourceDestroyConnection); + m_sourceDestroyConnection = { }; + m_source = nullptr; + m_phase = Phase::Idle; + m_hasRect = false; + m_localRect = { }; + m_origin = nullptr; + + m_wrapper->updateWindowTransitionAnimationSource(); + + if (wasArmed) + Q_EMIT windowTransitionFinished(); +} + +void SurfaceWindowTransition::abort() +{ + releaseSourceOutputs(); + m_wrapper->updateWindowTransitionAnimationSource(); +} + +void SurfaceWindowTransition::setWindowTransitionRect(const QRectF &localRect, + WindowTransitionTarget *origin) +{ + // The rect is honored only when the surface is not yet mapped. + if (m_wrapper->surface() && m_wrapper->surface()->mapped()) + return; + + m_localRect = localRect; + m_origin = origin; + m_hasRect = true; + m_phase = Phase::Armed; +} + +void SurfaceWindowTransition::updateWindowTransitionRect(const QRectF &localRect) +{ + if (!m_hasRect) + return; + + m_localRect = localRect; +} + +void SurfaceWindowTransition::setWindowTransitionSource(WindowTransitionSource *source) +{ + if (m_source.data() == source) + return; + + releaseSourceOutputs(); + + if (m_sourceDestroyConnection) + QObject::disconnect(m_sourceDestroyConnection); + m_sourceDestroyConnection = { }; + m_source = source; + if (source) { + // The handle is owned by the manager and may outlive the animation; + // track its surface so the QML item never keeps a dangling pointer. + m_sourceDestroyConnection = + QObject::connect(source->surface(), + &WSurface::beforeDestroy, + this, + &SurfaceWindowTransition::onSourceSurfaceDestroyed); + } + + m_wrapper->updateWindowTransitionAnimationSource(); +} + +void SurfaceWindowTransition::clearWindowTransitionSource() +{ + releaseSourceOutputs(); + if (m_sourceDestroyConnection) + QObject::disconnect(m_sourceDestroyConnection); + m_sourceDestroyConnection = { }; + m_source = nullptr; + + m_wrapper->updateWindowTransitionAnimationSource(); +} + +std::optional SurfaceWindowTransition::mapTransitionPointToGlobal( + const QPointF &surfacePoint) const +{ + auto *item = m_wrapper->surfaceItem(); + if (!item || !item->surface() || !item->shellSurface()) + return std::nullopt; + + return m_wrapper->position() + m_wrapper->mapFromSurface(surfacePoint); +} + +void SurfaceWindowTransition::releaseSourceOutputs() +{ + if (m_source && !m_retainedOutputs.isEmpty()) + m_source->release(m_retainedOutputs); + m_retainedOutputs.clear(); +} + +void SurfaceWindowTransition::onSourceSurfaceDestroyed() +{ + m_sourceDestroyConnection = { }; + m_source = nullptr; + m_retainedOutputs.clear(); + + m_wrapper->updateWindowTransitionAnimationSource(); +} diff --git a/src/surface/surfacewindowtransition.h b/src/surface/surfacewindowtransition.h new file mode 100644 index 0000000000..7cf74c78e6 --- /dev/null +++ b/src/surface/surfacewindowtransition.h @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "interfaces/windowtransition.h" + +#include +#include +#include +#include + +#include + +class SurfaceWrapper; + +// Idle --setWindowTransitionRect--> Armed --begin--> Playing +// Playing --endAnimation(false)--> Armed --begin--> ... +// Playing --endAnimation(true)--> Idle (source left, rect finished) +// Armed/Playing --resetWindowTransition--> Idle (source left, rect finished) +class SurfaceWindowTransition : public WindowTransitionTarget +{ + Q_OBJECT +public: + enum class Phase + { + Idle, + Armed, + Playing, + }; + + explicit SurfaceWindowTransition(SurfaceWrapper *wrapper); + + // True when a non-empty transition rectangle is configured. + bool active() const; + WSurface *sourceSurface() const; + std::optional globalRect() const; + + // Lifecycle driven by SurfaceWrapper. + void begin(); + void endAnimation(bool wrapperAboutToRemove); + void abort(); + + void setWindowTransitionRect(const QRectF &localRect, WindowTransitionTarget *origin) override; + void updateWindowTransitionRect(const QRectF &localRect) override; + void setWindowTransitionSource(WindowTransitionSource *source) override; + void clearWindowTransitionSource() override; + void resetWindowTransition() override; + std::optional mapTransitionPointToGlobal(const QPointF &surfacePoint) const override; + +private: + void releaseSourceOutputs(); + void onSourceSurfaceDestroyed(); + + SurfaceWrapper *m_wrapper; + Phase m_phase = Phase::Idle; + bool m_hasRect = false; + QRectF m_localRect; + QPointer m_origin; + QPointer m_source; + QList m_retainedOutputs; + QMetaObject::Connection m_sourceDestroyConnection; +}; diff --git a/src/surface/surfacewrapper.cpp b/src/surface/surfacewrapper.cpp new file mode 100644 index 0000000000..53259843ec --- /dev/null +++ b/src/surface/surfacewrapper.cpp @@ -0,0 +1,3620 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "surface/surfacewrapper.h" +#include "session/sessionmanager.h" +#include "session/session.h" +#include "session/sessionscene.h" +#include "session/sessionoutputmanager.h" + +#include "common/treelandlogging.h" +#include "core/qmlengine.h" +#include "output/output.h" +#include "core/waylandserver.h" +#include "surface/surfacewindowtransition.h" +#include "treelanduserconfig.hpp" +#include "animationconfig.hpp" +#include "workspace/workspace.h" +#include "wtoplevelsurface.h" +#include "wxdgtoplevelsurface.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef DISABLE_XWAYLAND +#include +#include +#endif + +#include +#include +#include +#include + +#define OPEN_ANIMATION 1 +#define CLOSE_ANIMATION 2 +#define ALWAYSONTOPLAYER 1 +#define ALWAYSONBOTTOMLAYER -1 +#define OVERLAYLAYER 2 +#define PRIVILEGEDOVERLAYLAYER 3 + +SurfaceWrapper::SurfaceWrapper(QmlEngine *qmlEngine, + WToplevelSurface *shellSurface, + Type type, + const QString &appId, + QQuickItem *parent) + : QQuickItem(parent) + , m_engine(qmlEngine) + , m_shellSurface(shellSurface) + , m_type(type) + , m_positionAutomatic(true) + , m_visibleDecoration(true) + , m_clipInOutput(false) + , m_noDecoration(true) + , m_noTitleBar(true) + , m_noCornerRadius(false) + , m_alwaysOnBottom(false) + , m_skipSwitcher(false) + , m_skipDockPreView(true) + , m_skipMutiTaskView(false) + , m_isDdeShellSurface(false) + , m_xwaylandPositionFromSurface(true) + , m_wrapperAboutToRemove(false) + , m_isProxy(false) + , m_hideByWorkspace(false) + , m_hideByshowDesk(true) + , m_hideByLockScreen(false) + , m_confirmHideByLockScreen(false) + , m_blurPersonalization(false) + , m_blurBackgroundEffect(false) + , m_isActivated(false) + , m_attention(false) + , m_isIMCandidatePanel(false) + , m_isSnapMask(false) + , m_resizable(false) + , m_maximizable(false) + , m_modal(false) + , m_appId(appId) +{ + m_windowTransition = std::make_unique(this); + QQmlEngine::setContextForObject(this, qmlEngine->rootContext()); + initializeFrameGeometry(); + + setup(); +} + +SurfaceWrapper::SurfaceWrapper(SurfaceWrapper *original, QQuickItem *parent) + : QQuickItem(parent) + , m_engine(original->m_engine) + , m_session(original->m_session) // Borrow preferences without registering another window. + , m_shellSurface(original->m_shellSurface) + , m_type(original->m_type) + , m_positionAutomatic(true) + , m_visibleDecoration(true) + , m_clipInOutput(false) + , m_noDecoration(true) + , m_noTitleBar(true) + , m_noCornerRadius(false) + , m_alwaysOnBottom(false) + , m_skipSwitcher(false) + , m_skipDockPreView(true) + , m_skipMutiTaskView(false) + , m_isDdeShellSurface(false) + , m_xwaylandPositionFromSurface(true) + , m_wrapperAboutToRemove(false) + , m_isProxy(true) + , m_hideByWorkspace(false) + , m_hideByshowDesk(true) + , m_hideByLockScreen(false) + , m_confirmHideByLockScreen(false) + , m_blurPersonalization(false) + , m_blurBackgroundEffect(false) + , m_isActivated(false) + , m_attention(false) + , m_isIMCandidatePanel(false) + , m_isSnapMask(false) + , m_resizable(false) + , m_maximizable(false) + , m_modal(false) + , m_appId(original->m_appId) +{ + m_renderingEnabled = original->renderingEnabled(); + connect(original, &SurfaceWrapper::renderingEnabledChanged, this, [this, original] { + setRenderingEnabled(original->renderingEnabled()); + }); + m_windowTransition = std::make_unique(this); + QQmlEngine::setContextForObject(this, m_engine->rootContext()); + initializeFrameGeometry(); + + if (original->m_shellSurface) { + setup(); + } else { + setImplicitSize(original->implicitWidth(), original->implicitHeight()); + // Borrowed, not owned: the proxy does not keep an icon reference. + auto iconVar = original->appIcon(); + QColor bgColor = original->prelaunchSplash() + ? original->prelaunchSplash()->property("backgroundColor").value() + : QColor("#ffffff"); + + m_prelaunchSplash = + m_engine->createPrelaunchSplash(this, + iconVar.value(), + bgColor); + Q_EMIT prelaunchSplashChanged(); + setNoDecoration(false); + + connect(original, &SurfaceWrapper::surfaceItemCreated, this, [this, original]() { + m_shellSurface = original->m_shellSurface; + m_type = original->m_type; + if (m_prelaunchSplash) { + m_prelaunchSplash->setVisible(false); + m_prelaunchSplash->deleteLater(); + m_prelaunchSplash = nullptr; + Q_EMIT prelaunchSplashChanged(); + } + setup(); + }); + } +} + +// Constructor used for the prelaunch splash +SurfaceWrapper::SurfaceWrapper(QmlEngine *qmlEngine, + QQuickItem *parent, + const QSize &initialSize, + const QString &appId, + wlr_buffer *iconBuffer, + const QColor &backgroundColor) + : QQuickItem(parent) + , m_engine(qmlEngine) + , m_shellSurface(nullptr) + , m_type(Type::SplashScreen) + , m_positionAutomatic(true) + , m_visibleDecoration(true) + , m_clipInOutput(false) + , m_noDecoration(true) + , m_noTitleBar(true) + , m_noCornerRadius(false) + , m_alwaysOnBottom(false) + , m_skipSwitcher(false) + , m_skipDockPreView(false) + , m_skipMutiTaskView(false) + , m_isDdeShellSurface(false) + , m_xwaylandPositionFromSurface(true) + , m_wrapperAboutToRemove(false) + , m_isProxy(false) + , m_hideByWorkspace(false) + , m_hideByshowDesk(true) + , m_hideByLockScreen(false) + , m_confirmHideByLockScreen(false) + , m_blurPersonalization(false) + , m_blurBackgroundEffect(false) + , m_isActivated(false) + , m_attention(false) + , m_isIMCandidatePanel(false) + , m_isSnapMask(false) + , m_resizable(false) + , m_maximizable(false) + , m_modal(false) + , m_appId(appId) + , m_appIcon(iconBuffer) +{ + m_windowTransition = std::make_unique(this); + QQmlEngine::setContextForObject(this, qmlEngine->rootContext()); + initializeFrameGeometry(); + if (initialSize.isValid() && initialSize.width() > 0 && initialSize.height() > 0) { + // Also set implicit size to keep QML layout consistent + setImplicitSize(initialSize.width(), initialSize.height()); + qCDebug(lcTlSurface) << "Prelaunch Splash: set initial size to" << initialSize; + } else { + setImplicitSize(800, 600); + } + m_prelaunchSplash = + m_engine->createPrelaunchSplash(this, m_appIcon.get(), backgroundColor); + Q_EMIT prelaunchSplashChanged(); + + setNoDecoration(false); + updateHasActiveCapability(ActiveControlState::HasActivateCapability, true); + updateHasActiveCapability(ActiveControlState::MappedOrSplash, true); // Splash is true +} + +bool SurfaceWrapper::windowAnimationEnabled(uint direction) const +{ + auto *server = WaylandServer::instance(); + auto *config = server ? server->animationConfig() : nullptr; + if (!config) + return true; + + const bool open = direction == OPEN_ANIMATION; + switch (m_type) { + case Type::SplashScreen: + case Type::XdgToplevel: + case Type::XWayland: + return open ? config->windowOpen() : config->windowClose(); + case Type::Layer: { + auto *layerSurface = qobject_cast(m_shellSurface.data()); + if (!layerSurface) + return true; + if (isLaunchpad()) + return open ? config->launchpadOpenFullscreen() : config->launchpadCloseFullscreen(); + if (layerSurface->getExclusiveZoneEdge() != WLayerSurface::AnchorType::None) + return open ? config->layerShellOpen() : config->layerShellClose(); + return true; + } + default: + return true; + } +} + +bool SurfaceWrapper::geometryAnimationEnabled(State state) const +{ + auto *server = WaylandServer::instance(); + auto *config = server ? server->animationConfig() : nullptr; + if (!config) + return true; + + switch (state) { + case State::Maximized: + return config->maximize(); + case State::Fullscreen: + return config->fullscreen(); + case State::Normal: + case State::Tiling: + return config->restoreWindow(); + default: + return true; + } +} + +void SurfaceWrapper::invalidate() +{ + Q_ASSERT_X(!m_wrapperAboutToRemove, Q_FUNC_INFO, "Can't call `invalidate` twice!"); + if (m_session && !m_isProxy) + m_session->unregisterWindow(this); + m_wrapperAboutToRemove = true; + Q_EMIT aboutToBeInvalidated(); + + // Drop any pending window transition rect so it cannot be consumed later by + // a stale mapping path on this wrapper. + if (m_windowTransitionPending && m_windowAnimation) { + m_windowAnimation->disconnect(this); + m_windowAnimation->deleteLater(); + m_windowAnimation = nullptr; + } + m_windowTransitionPending = false; + if (!isWindowAnimationRunning()) + m_windowTransition->resetWindowTransition(); + m_pendingActivation = false; + m_pendingActivationSeat.clear(); + + if (!m_skipDockPreView) + setSkipDockPreView(true); + + if (m_container) { + m_container->removeSurface(this); + m_container = nullptr; + } + if (m_ownsOutput) { + m_ownsOutput->removeSurface(this); + m_ownsOutput = nullptr; + } + if (m_parentSurface) { + m_parentSurface->removeSubSurface(this); + m_parentSurface = nullptr; + } + for (auto subS : std::as_const(m_subSurfaces)) { + subS->m_parentSurface = nullptr; + } + + updateHasActiveCapability(ActiveControlState::MappedOrSplash, false); + updateFocusControlState(FocusControlState::Mapped, false); + + m_subSurfaces.clear(); + m_shellSurface = nullptr; + if (m_surfaceItem) + m_surfaceItem->disconnect(this); +} + +SurfaceWrapper::~SurfaceWrapper() +{ + if (!m_wrapperAboutToRemove) { + if (isWindowAnimationRunning()) { + qCWarning(lcTlSurface) + << "SurfaceWrapper is being destroyed without destroy(); expected external" + " destroy() rather than QObject parent-child destruction"; + } + invalidate(); + } + // Safety net for the path above: if a window animation was still running we + // are destroyed without onWindowAnimationFinished(), so make sure the + // transition source is not left entered on any output. + m_windowTransition->abort(); + if (m_titleBar) { + delete m_titleBar; + m_titleBar = nullptr; + } + if (m_decoration) { + delete m_decoration; + m_decoration = nullptr; + } + if (m_geometryAnimation) { + delete m_geometryAnimation; + m_geometryAnimation = nullptr; + } + if (m_windowAnimation) { + delete m_windowAnimation; + m_windowAnimation = nullptr; + } + if (m_coverContent) { + delete m_coverContent; + m_coverContent = nullptr; + } + // Ensure we do not hold stale connections to shellSurface; QPointer may already be null. + if (m_shellSurface) { + QObject::disconnect(m_shellSurface, nullptr, this, nullptr); + m_shellSurface.clear(); + } +} + +void SurfaceWrapper::setup() +{ + Q_ASSERT(m_shellSurface); + Q_ASSERT(m_type != Type::SplashScreen); + + updateActivateCapability(); + updateFocusCapability(); + + switch (m_type) { + case Type::XdgToplevel: + m_surfaceItem = new WXdgToplevelSurfaceItem(this); + break; + case Type::XdgPopup: + m_surfaceItem = new WXdgPopupSurfaceItem(this); + break; + case Type::Layer: + m_surfaceItem = new WLayerSurfaceItem(this); + break; + case Type::XWayland: { +#ifndef DISABLE_XWAYLAND + m_surfaceItem = new WXWaylandSurfaceItem(this); + connect(m_surfaceItem, + &WSurfaceItem::bufferScaleChanged, + this, + &SurfaceWrapper::updateSurfaceSizeRatio); +#endif + break; + } + case Type::InputPopup: + m_surfaceItem = new WInputPopupSurfaceItem(this); + break; +#ifdef EXT_SESSION_LOCK_V1 + case Type::LockScreen: + m_surfaceItem = new WSurfaceItem(this); + break; +#endif + default: + Q_UNREACHABLE(); + } + + QQmlEngine::setContextForObject(m_surfaceItem, m_engine->rootContext()); + m_surfaceItem->setResizeMode(WSurfaceItem::ManualResize); + // Must set the shell surface before instantiating the QML delegate. + m_surfaceItem->setShellSurface(m_shellSurface); + updateSurfaceSizeRatio(); + m_surfaceItem->setDelegate(m_engine->surfaceContentComponent()); + syncRenderingState(); + // Initialize focus policy even if focus capability state never toggles later. + m_surfaceItem->setFocusPolicy(hasFocusCapability() ? Qt::StrongFocus : Qt::NoFocus); + + if (!m_isProxy) { + QObject::connect(m_shellSurface, &WToplevelSurface::requestMinimize, this, [this]() { + minimize(); + }); + QObject::connect(m_shellSurface, &WToplevelSurface::requestCancelMinimize, this, [this]() { + restoreFromMinimized(); + }); + QObject::connect(m_shellSurface, &WToplevelSurface::requestMaximize, + this, + &SurfaceWrapper::maximize); + QObject::connect(m_shellSurface, &WToplevelSurface::requestCancelMaximize, + this, + &SurfaceWrapper::unmaximize); + QObject::connect(m_shellSurface, &WToplevelSurface::requestMove, this, [this]() { + Q_EMIT moveRequested(); + }); + QObject::connect(m_shellSurface, &WToplevelSurface::requestResize, + this, + [this](WSeat *, Qt::Edges edge, quint32) { + Q_EMIT resizeRequested(edge, /*overrideCursor=*/false); + }); + QObject::connect(m_shellSurface, &WToplevelSurface::requestFullscreen, + this, + &SurfaceWrapper::enterFullscreen); + QObject::connect(m_shellSurface, &WToplevelSurface::requestCancelFullscreen, + this, + &SurfaceWrapper::leaveFullscreen); + + if (m_type == Type::XdgToplevel) { + QObject::connect(m_shellSurface, &WToplevelSurface::requestShowWindowMenu, + this, + [this](WSeat *, QPoint pos, quint32) { + Q_EMIT windowMenuRequested( + m_surfaceItem->mapFromSurface(pos).toPoint()); + }); + } + } + QObject::connect(m_shellSurface->surface(), &WSurface::mappedChanged, + this, + &SurfaceWrapper::onMappedChanged); + if (!m_isProxy && m_type == Type::XdgToplevel) { + m_xdgToplevelCommitConnection = QObject::connect(m_shellSurface->surface(), &WSurface::commit, this, [this] { + if (!surface()) + return; + + if (surface()->mapped()) { + QObject::disconnect(m_xdgToplevelCommitConnection); + return; + } + + auto *xdgSurface = qobject_cast(m_shellSurface.data()); + if (!xdgSurface || !xdgSurface->isInitialized()) + return; + if (xdgSurface->handle()->requested.fullscreen) { + setSurfaceStateDirectly(State::Fullscreen); + } else if (xdgSurface->handle()->requested.maximized && isMaximizable()) { + setSurfaceStateDirectly(State::Maximized); + } else if (m_surfaceState == State::Maximized || m_surfaceState == State::Fullscreen) { + setSurfaceStateDirectly(State::Normal); + } + QObject::disconnect(m_xdgToplevelCommitConnection); + }); + } + + Q_EMIT surfaceItemCreated(); + + // ext-background-effect-v1 blur. The surface item caches the committed + // blur region and only emits when it changes, so this stays in sync even + // as the region is cleared/restored across commits. XWayland surfaces + // cannot attach background-effect objects, so their region is always empty. + connect(m_surfaceItem, + &WSurfaceItem::backgroundBlurRegionChanged, + this, + &SurfaceWrapper::syncBlurBackgroundEffect); + syncBlurBackgroundEffect(); + + // Forward WToplevelSurface appId changes when using fallback mode + if (m_appId.isEmpty()) { + QObject::connect(m_shellSurface, &WToplevelSurface::appIdChanged, this, [this]() { + Q_EMIT appIdChanged(); + }); + } + + if (m_type == Type::XdgToplevel || m_type == Type::XWayland) { + QObject::connect(m_shellSurface, &WToplevelSurface::minimumSizeChanged, + this, + &SurfaceWrapper::updateSizeCapabilities); + QObject::connect(m_shellSurface, &WToplevelSurface::maximumSizeChanged, + this, + &SurfaceWrapper::updateSizeCapabilities); + } + updateSizeCapabilities(); + + if (!m_prelaunchSplash) { + setImplicitSize(m_surfaceItem->implicitWidth(), m_surfaceItem->implicitHeight()); + connect(m_surfaceItem, &WSurfaceItem::implicitWidthChanged, this, [this] { + setImplicitWidth(m_surfaceItem->implicitWidth()); + }); + connect(m_surfaceItem, &WSurfaceItem::implicitHeightChanged, this, [this] { + setImplicitHeight(m_surfaceItem->implicitHeight()); + }); + connect(m_surfaceItem, + &WSurfaceItem::boundingRectChanged, + this, + &SurfaceWrapper::updateBoundingRect); + } + + if (auto client = m_shellSurface->waylandClient()) { + if (!m_isProxy) + setSession(WaylandServer::instance()->sessionManager()->sessionForClient(client).get()); + if (!m_visibilitySocket) + bindVisibilitySocket(client->socket()->rootSocket()); + } + + if (m_type == Type::XdgToplevel && !m_isProxy) // x11 will set later + setSkipDockPreView(false); + + if (m_type == Type::Layer) { + if (auto *layerSurface = qobject_cast(m_shellSurface.data())) { + connect(layerSurface, + &WLayerSurface::keyboardInteractivityChanged, + this, + &SurfaceWrapper::updateFocusCapability); + } + } + +#ifndef DISABLE_XWAYLAND + if (m_type == Type::XWayland && !m_isProxy) { + auto xwaylandSurface = qobject_cast(m_shellSurface); + auto xwaylandSurfaceItem = qobject_cast(m_surfaceItem); + + connect(xwaylandSurfaceItem, + &WXWaylandSurfaceItem::implicitPositionChanged, + this, + [this, xwaylandSurfaceItem]() { + if (m_xwaylandPositionFromSurface) + moveNormalGeometryInOutput(xwaylandSurfaceItem->implicitPosition()); + }); + + connect(xwaylandSurface, + &WXWaylandSurface::requestConfigure, + this, + [this, xwaylandSurface, xwaylandSurfaceItem]() { + const auto flags = xwaylandSurface->requestConfigureFlags(); + if (!flags.testAnyFlags(WXWaylandSurface::XCB_CONFIG_WINDOW_SIZE)) + return; + + const qreal ratio = xwaylandSurfaceItem->surfaceSizeRatio(); + const QSizeF paddings(xwaylandSurfaceItem->leftPadding() + + xwaylandSurfaceItem->rightPadding(), + xwaylandSurfaceItem->topPadding() + + xwaylandSurfaceItem->bottomPadding()); + const QSizeF requestedSize = QSizeF(xwaylandSurface->requestConfigureGeometry().size()) + / ratio + paddings; + + setSize(alignGeometryToPixelGrid(QRectF(position(), requestedSize)).size()); + }); + + connect(this, &QQuickItem::xChanged, xwaylandSurface, [this, xwaylandSurfaceItem]() { + xwaylandSurfaceItem->moveTo(position(), !m_xwaylandPositionFromSurface); + }); + + connect(this, &QQuickItem::yChanged, xwaylandSurface, [this, xwaylandSurfaceItem]() { + xwaylandSurfaceItem->moveTo(position(), !m_xwaylandPositionFromSurface); + }); + + auto requestPos = xwaylandSurface->requestConfigureGeometry().topLeft(); + if (!requestPos.isNull()) { + // NOTE: need a better check whether set positionAutomatic, WindowTypes? + m_positionAutomatic = false; + moveNormalGeometryInOutput(xwaylandSurfaceItem->implicitPosition()); + } + + auto updateX11SkipFlags = [this]() { + // TODO: support missing type in waylib + // https://github.com/linuxdeepin/dde-shell/blob/b94a3cec4e01cba64f56e040e74419248985d03d/panels/dock/taskmanager/x11window.cpp#L81-L107 + auto xwaylandSurface = qobject_cast(this->shellSurface()); + if (!xwaylandSurface) + return; + auto atoms = xwaylandSurface->windowTypes(); + bool skipDock = false; + skipDock |= xwaylandSurface->isBypassManager(); + // skipDock |= atoms.testFlag(WXWaylandSurface::WindowType::_NET_WM_WINDOW_TYPE_DIALOG) + // && !isActionMinimizeAllowed(); + skipDock |= atoms.testFlag(WXWaylandSurface::WindowType::NET_WM_WINDOW_TYPE_UTILITY); + skipDock |= atoms.testFlag(WXWaylandSurface::WindowType::NET_WM_WINDOW_TYPE_COMBO); + // skipDock |= atoms.testFlag(WXWaylandSurface::WindowType::NET_WM_WINDOW_TYPE_DESKTOP); + skipDock |= atoms.testFlag(WXWaylandSurface::WindowType::NET_WM_WINDOW_TYPE_DND); + // skipDock |= atoms.testFlag(WXWaylandSurface::WindowType::NET_WM_WINDOW_TYPE_DOCK); + skipDock |= + atoms.testFlag(WXWaylandSurface::WindowType::NET_WM_WINDOW_TYPE_DROPDOWN_MENU); + skipDock |= atoms.testFlag(WXWaylandSurface::WindowType::NET_WM_WINDOW_TYPE_MENU); + skipDock |= + atoms.testFlag(WXWaylandSurface::WindowType::NET_WM_WINDOW_TYPE_NOTIFICATION); + skipDock |= atoms.testFlag(WXWaylandSurface::WindowType::NET_WM_WINDOW_TYPE_POPUP_MENU); + skipDock |= atoms.testFlag(WXWaylandSurface::WindowType::NET_WM_WINDOW_TYPE_SPLASH); + // skipDock |= atoms.testFlag(WXWaylandSurface::WindowType::NET_WM_WINDOW_TYPE_TOOLBAR); + skipDock |= atoms.testFlag(WXWaylandSurface::WindowType::NET_WM_WINDOW_TYPE_TOOLTIP); + setSkipDockPreView(skipDock); + + bool notSkipSwitcher = false; + notSkipSwitcher |= + atoms.testFlag(WXWaylandSurface::WindowType::NET_WM_WINDOW_TYPE_NORMAL); + notSkipSwitcher |= + atoms.testFlag(WXWaylandSurface::WindowType::NET_WM_WINDOW_TYPE_DIALOG); + setSkipSwitcher(!notSkipSwitcher); + setSkipMutiTaskView(!notSkipSwitcher); + }; + + connect(xwaylandSurface, + &WXWaylandSurface::bypassManagerChanged, + this, + [this, updateX11SkipFlags]() { + updateX11SkipFlags(); + updateSizeCapabilities(); + updateActivateCapability(); + updateFocusCapability(); + }); + connect(xwaylandSurface, + &WXWaylandSurface::windowTypesChanged, + this, + [this, updateX11SkipFlags]() { + updateX11SkipFlags(); + updateSizeCapabilities(); + }); + connect(xwaylandSurface, + &WXWaylandSurface::aboveChanged, + this, + &SurfaceWrapper::updateXWaylandStackingState); + connect(xwaylandSurface, + &WXWaylandSurface::belowChanged, + this, + &SurfaceWrapper::updateXWaylandStackingState); + updateX11SkipFlags(); + updateXWaylandStackingState(); + } +#endif + updateActivateCapability(); + updateFocusCapability(); + if (m_prelaunchSplash) { + m_surfaceItem->setVisible(false); + + // Check if surface is still valid before accessing + WSurface *surf = surface(); + if (surf && surf->mapped()) { + updateFocusControlState(FocusControlState::Mapped, true); + // ActiveControlState::MappedOrSplash is already true + syncPrelaunchMappedState(); + startPrelaunchSplashHideSequence(); + } + } else { + updateFocusControlState(FocusControlState::Mapped, surface() && surface()->mapped()); + updateHasActiveCapability(ActiveControlState::MappedOrSplash, + surface() && surface()->mapped()); + } +} + +void SurfaceWrapper::convertToNormalSurface(WToplevelSurface *shellSurface, Type type) +{ + // Conversion only allowed from prelaunch (SplashScreen) state + if (m_type != Type::SplashScreen || m_shellSurface != nullptr) { + qCCritical(lcTlSurface) + << "convertToNormalSurface can only be called on prelaunch surfaces"; + return; + } + + // Assign new shell surface (QPointer auto-detects destruction) + m_shellSurface = shellSurface; + m_type = type; + Q_EMIT typeChanged(); + + // Call setup() to initialize surfaceItem related features + setup(); +} + +void SurfaceWrapper::setParent(QQuickItem *item) +{ + QObject::setParent(item); + setParentItem(item); +} + +void SurfaceWrapper::setActivate(bool activate) +{ + if (m_wrapperAboutToRemove) + return; + if (m_isActivated == activate) + return; + + Q_ASSERT(!activate || hasActiveCapability()); + m_isActivated = activate; + + if (m_attention && m_isActivated) + setAttention(false); + + // No shellSurface in prelaunch mode -> early return + if (m_shellSurface) + updateActiveState(); + + Q_EMIT isActivatedChanged(); +} + +void SurfaceWrapper::updateActiveState() +{ + if (!m_shellSurface) { + qCCritical(lcTlSurface) << "updateActiveState called without a valid shellSurface"; + return; + } + if (!m_shellSurface->isInitialized()) { + qCWarning(lcTlSurface) + << "updateActiveState called with shellSurface not yet initialized"; + return; + } + m_shellSurface->setActivate(m_isActivated); +} + +void SurfaceWrapper::setFocus(bool focus, Qt::FocusReason reason) +{ + // No surfaceItem in prelaunch mode -> early return + if (!m_surfaceItem) { + qCDebug(lcTlSurface) << "setFocus called but m_surfaceItem is null, appId:" << m_appId; + return; + } + + if (focus) + m_surfaceItem->forceActiveFocus(reason); + else + m_surfaceItem->setFocus(false, reason); +} + +void SurfaceWrapper::syncPrelaunchMappedState() +{ + if (!m_prelaunchOutputs.isEmpty()) { + setOutputs(m_prelaunchOutputs); + m_prelaunchOutputs.clear(); + } + + const bool fullscreenRequested = [this] { +#ifndef DISABLE_XWAYLAND + if (auto *surface = qobject_cast(m_shellSurface.data())) + return surface->handle()->fullscreen; +#endif + if (auto *surface = qobject_cast(m_shellSurface.data())) + return surface->handle()->requested.fullscreen; + return false; + }(); + const bool maximizeRequested = [this] { +#ifndef DISABLE_XWAYLAND + if (auto *surface = qobject_cast(m_shellSurface.data())) + return surface->handle()->maximized_horz && surface->handle()->maximized_vert; +#endif + if (auto *surface = qobject_cast(m_shellSurface.data())) + return surface->handle()->requested.maximized; + return false; + }(); + + if (m_type == Type::XWayland || m_type == Type::XdgToplevel) { + if (fullscreenRequested) { + setSurfaceStateDirectly(State::Fullscreen); + } else if (maximizeRequested && isMaximizable()) { + setSurfaceStateDirectly(State::Maximized); + } + } + + if (m_type == Type::XWayland) { + const QRectF stateGeometry = targetGeometryForState(m_surfaceState); + if ((m_surfaceState == State::Maximized || m_surfaceState == State::Fullscreen) + && stateGeometry.isValid()) { + setPosition(alignToPixelGrid(stateGeometry.topLeft())); + setSize(stateGeometry.size()); + } + } + + updateActiveState(); +} + +void SurfaceWrapper::startPrelaunchSplashHideSequence() +{ + Q_ASSERT(m_surfaceItem != nullptr); + if (m_windowAnimation) { + qCDebug(lcTlSurface) << "prelaunch splash transition is starting while window " + "animation is still running," + "this may cause visual glitches, will delay the transition " + "until window animation finishes"; + return; + } + if (m_geometryAnimation) { + qCDebug(lcTlSurface) << "prelaunch splash transition already prepared or running, skip"; + return; + } + + // Wait until surfaceItem has computed a valid scene-space implicit size. + // For XWayland, this happens in updateSurfaceState() after the first surface commit; + // for other types it may be deferred until componentComplete + first polish. + if (!m_surfaceItem->isReady()) { + connect(m_surfaceItem, + &WSurfaceItem::readyChanged, + this, + &SurfaceWrapper::startPrelaunchSplashHideSequence, + Qt::SingleShotConnection); + return; + } + + // Use surfaceItem's scene-space implicit size: for XWayland, surf->size() is + // buffer-space and differs from scene-space after DPR scaling via surfaceSizeRatio. + const QRectF stateGeometry = targetGeometryForState(m_surfaceState); + const bool useStateGeometry = (m_surfaceState == State::Maximized + || m_surfaceState == State::Fullscreen) + && stateGeometry.isValid(); + const QSizeF targetImplicitSize = useStateGeometry + ? stateGeometry.size() + : QSizeF(m_surfaceItem->implicitWidth(), m_surfaceItem->implicitHeight()); + const bool hasValidTargetImplicitSize = + targetImplicitSize.width() > 0 && targetImplicitSize.height() > 0; + if (!hasValidTargetImplicitSize) { + qCCritical(lcTlSurface) << "Invalid target implicit size, skip transition animation" + << "targetImplicit=" << targetImplicitSize; + } + + const bool needImplicitSizeTransition = m_renderingEnabled && !m_sessionVisibilityChanging + && hasValidTargetImplicitSize && (container() != nullptr) + && (!qFuzzyCompare(implicitWidth() + 1.0, targetImplicitSize.width() + 1.0) + || !qFuzzyCompare(implicitHeight() + 1.0, targetImplicitSize.height() + 1.0)); + + if (needImplicitSizeTransition) { + const QRectF fromGeometry(position(), size()); + QRectF toGeometry; + if (useStateGeometry) { + // Maximized/fullscreen handoff: expand into the state geometry itself, so + // the wrapper lands exactly on the maximized/fullscreen rect. + toGeometry = stateGeometry; + } else { + // XWayland clients manage their own position; respect it and don't shift. + // For all other types, keep the center fixed so the window expands from center. + const QPointF toTopLeft = (m_type == Type::XWayland) + ? fromGeometry.topLeft() + : fromGeometry.center() + - QPointF(targetImplicitSize.width() / 2.0, targetImplicitSize.height() / 2.0); + toGeometry = QRectF(toTopLeft, targetImplicitSize); + } + + m_geometryAnimation = + m_engine->createGeometryAnimation(this, fromGeometry, toGeometry, container()); + + bool ok = connect(m_geometryAnimation, + SIGNAL(ready()), + this, + SLOT(onPrelaunchGeometryAnimationReady())); + Q_ASSERT(ok); + ok = connect(m_geometryAnimation, + SIGNAL(finished()), + this, + SLOT(onPrelaunchGeometryAnimationFinished())); + Q_ASSERT(ok); + + ok = QMetaObject::invokeMethod(m_geometryAnimation, "start"); + Q_ASSERT(ok); + } else { + completeSplashTransition(targetImplicitSize); + } +} + +void SurfaceWrapper::onPrelaunchGeometryAnimationReady() +{ + Q_ASSERT(m_geometryAnimation); + const QRectF toGeo = m_geometryAnimation->property("toGeometry").toRectF(); + // Move the wrapper to the animation's final position before revealing the real surface, + // so the window appears exactly where the animation ended (no position jump). + setPosition(toGeo.topLeft()); + // Only a normal window owns its normalGeometry; maximized/fullscreen states + // must not overwrite it with the state rect. + if (m_surfaceState == State::Normal) + setNormalGeometry(toGeo); + + completeSplashTransition(toGeo.size(), true); +} + +void SurfaceWrapper::onPrelaunchGeometryAnimationFinished() +{ + Q_ASSERT(m_geometryAnimation); + m_geometryAnimation->disconnect(this); + m_geometryAnimation->deleteLater(); + m_geometryAnimation = nullptr; + + if (m_decoration) + m_decoration->setVisible(true); +} + +void SurfaceWrapper::completeSplashTransition(const QSizeF &targetImplicitSize, bool hideDecoration) +{ + setImplicitSize(targetImplicitSize.width(), targetImplicitSize.height()); + connect(m_surfaceItem, &WSurfaceItem::implicitWidthChanged, this, [this] { + setImplicitWidth(m_surfaceItem->implicitWidth()); + }); + connect(m_surfaceItem, &WSurfaceItem::implicitHeightChanged, this, [this] { + setImplicitHeight(m_surfaceItem->implicitHeight()); + }); + connect(m_surfaceItem, + &WSurfaceItem::boundingRectChanged, + this, + &SurfaceWrapper::updateBoundingRect); + // setNoDecoration not called updateTitleBar when type is SplashScreen + updateTitleBar(); + if (m_decoration) { + if (hideDecoration) + m_decoration->setVisible(false); + m_decoration->stackBefore(m_surfaceItem); + } + + if (m_type == Type::XWayland + && (m_surfaceState == State::Maximized || m_surfaceState == State::Fullscreen)) { + QMetaObject::invokeMethod( + this, + [this] { + if (m_wrapperAboutToRemove || !m_surfaceItem) + return; + updateSurfaceSizeRatio(); + const QRectF stateGeometry = targetGeometryForState(m_surfaceState); + if (stateGeometry.isValid()) { + setPosition(alignToPixelGrid(stateGeometry.topLeft())); + resize(stateGeometry.size()); + } + }, + Qt::QueuedConnection); + } + Q_ASSERT(m_prelaunchSplash); + m_prelaunchSplash->setVisible(false); + m_prelaunchSplash->deleteLater(); + m_prelaunchSplash = nullptr; + m_prelaunchFrameGeometry.reset(); + Q_EMIT prelaunchSplashChanged(); + Q_EMIT presentationFrameGeometryChanged(); + m_surfaceItem->setVisible(true); + + // Now that the splash is hidden and deleted, the surface can be considered active if it's + // mapped + updateHasActiveCapability(ActiveControlState::MappedOrSplash, surface() && surface()->mapped()); +} + +WSurface *SurfaceWrapper::surface() const +{ + if (!m_shellSurface) + return nullptr; + auto *surf = m_shellSurface->surface(); + return surf; +} + +WToplevelSurface *SurfaceWrapper::shellSurface() const +{ + return m_shellSurface; +} + +WSurfaceItem *SurfaceWrapper::surfaceItem() const +{ + return m_surfaceItem; +} + +QQuickItem *SurfaceWrapper::prelaunchSplash() const +{ + return m_prelaunchSplash; +} + +QVariant SurfaceWrapper::appIcon() const +{ + return m_appIcon ? QVariant::fromValue(m_appIcon.get()) : QVariant(); +} + +QString SurfaceWrapper::appId() const +{ + // TODO: Need to consider `engineName` to ensure the uniqueness of appid. + if (!m_appId.isEmpty()) + return m_appId; + // TODO: consider to use "xdg-shell/" + m_shellSurface->appId(), need dde-shell adaptation + if (m_shellSurface) + return m_shellSurface->appId(); + return QString(); +} + +bool SurfaceWrapper::resize(const QSizeF &size, bool tryExec) +{ + // No surfaceItem in prelaunch mode -> return false + if (!m_surfaceItem) + return false; + + return m_surfaceItem->resizeSurface(size, tryExec); +} + +void SurfaceWrapper::close() +{ + if (m_type == Type::SplashScreen) { + // For splash screens, emit a signal to request closure + Q_EMIT splashCloseRequested(); + } else if (m_shellSurface) { + // For normal surfaces, call the shell surface's close method + m_shellSurface->close(); + } +} + +QRectF SurfaceWrapper::titlebarGeometry() const +{ + return m_titleBar ? QRectF({ 0, 0 }, m_titleBar->size()) : QRectF(); +} + +QRectF SurfaceWrapper::boundingRect() const +{ + return m_boundedRect; +} + +QRectF SurfaceWrapper::normalGeometry() const +{ + return m_normalGeometry; +} + +QPointF SurfaceWrapper::mapFromSurface(const QPointF &surfacePoint) const +{ + // WSurfaceItem::mapFromSurface() already folds the content geometry offset + // (CSD margins / window geometry) and paddings (SSD titlebar) into a + // surface-item-local point. Add the item's position within the wrapper. + if (!m_surfaceItem) + return surfacePoint; + const QPointF itemPos = m_surfaceItem->mapFromSurface(surfacePoint); + return QPointF(m_surfaceItem->x() + itemPos.x(), m_surfaceItem->y() + itemPos.y()); +} + +void SurfaceWrapper::moveNormalGeometryInOutput(const QPointF &position) +{ + QPointF alignedPosition = alignToPixelGrid(position); + setNormalGeometry(QRectF(alignedPosition, m_normalGeometry.size())); + if (m_surfaceState != State::Normal) + return; + + if (m_geometryAnimation) + m_geometryAnimation->setProperty("toGeometry", m_normalGeometry); + else + setPosition(alignedPosition); +} + +void SurfaceWrapper::setNormalGeometry(const QRectF &newNormalGeometry) +{ + if (m_normalGeometry == newNormalGeometry) + return; + m_normalGeometry = newNormalGeometry; + Q_EMIT normalGeometryChanged(); +} + +QRectF SurfaceWrapper::maximizedGeometry() const +{ + return m_maximizedGeometry; +} + +void SurfaceWrapper::setMaximizedGeometry(const QRectF &newMaximizedGeometry) +{ + if (m_wrapperAboutToRemove) + return; + if (m_maximizedGeometry == newMaximizedGeometry) + return; + m_maximizedGeometry = newMaximizedGeometry; + // This geometry change might be caused by a change in the output size due to screen scaling. + // Ensure that the surfaceSizeRatio is updated before modifying the window size + // to avoid incorrect sizing of Xwayland windows. + updateSurfaceSizeRatio(); + + if (m_surfaceState == State::Maximized && !m_geometryAnimation) { + setPosition(newMaximizedGeometry.topLeft()); + resize(newMaximizedGeometry.size()); + } else if (m_surfaceState == State::Maximized && m_geometryAnimation) { + // Retarget the running animation; GeometryAnimation exposes toGeometry. + m_geometryAnimation->setProperty("toGeometry", newMaximizedGeometry); + } + + Q_EMIT maximizedGeometryChanged(); +} + +QRectF SurfaceWrapper::fullscreenGeometry() const +{ + return m_fullscreenGeometry; +} + +void SurfaceWrapper::setFullscreenGeometry(const QRectF &newFullscreenGeometry) +{ + if (m_wrapperAboutToRemove) + return; + if (m_fullscreenGeometry == newFullscreenGeometry) + return; + m_fullscreenGeometry = newFullscreenGeometry; + // This geometry change might be caused by a change in the output size due to screen scaling. + // Ensure that the surfaceSizeRatio is updated before modifying the window size + // to avoid incorrect sizing of Xwayland windows. + updateSurfaceSizeRatio(); + + if (m_surfaceState == State::Fullscreen && !m_geometryAnimation) { + setPosition(newFullscreenGeometry.topLeft()); + resize(newFullscreenGeometry.size()); + } else if (m_surfaceState == State::Fullscreen && m_geometryAnimation) { + // Retarget the running animation; GeometryAnimation exposes toGeometry. + m_geometryAnimation->setProperty("toGeometry", newFullscreenGeometry); + } + + Q_EMIT fullscreenGeometryChanged(); + + updateClipRect(); +} + +QRectF SurfaceWrapper::tilingGeometry() const +{ + return m_tilingGeometry; +} + +void SurfaceWrapper::setTilingGeometry(const QRectF &newTilingGeometry) +{ + if (m_wrapperAboutToRemove) + return; + if (m_tilingGeometry == newTilingGeometry) + return; + m_tilingGeometry = newTilingGeometry; + // This geometry change might be caused by a change in the output size due to screen scaling. + // Ensure that the surfaceSizeRatio is updated before modifying the window size + // to avoid incorrect sizing of Xwayland windows. + updateSurfaceSizeRatio(); + + if (m_surfaceState == State::Tiling) { + setPosition(newTilingGeometry.topLeft()); + resize(newTilingGeometry.size()); + } + + Q_EMIT tilingGeometryChanged(); +} + +bool SurfaceWrapper::positionAutomatic() const +{ + return m_positionAutomatic; +} + +void SurfaceWrapper::setPositionAutomatic(bool newPositionAutomatic) +{ + if (m_positionAutomatic == newPositionAutomatic) + return; + m_positionAutomatic = newPositionAutomatic; + Q_EMIT positionAutomaticChanged(); +} + +void SurfaceWrapper::resetWidth() +{ + if (m_surfaceItem) + m_surfaceItem->resetWidth(); + QQuickItem::resetWidth(); +} + +void SurfaceWrapper::resetHeight() +{ + if (m_surfaceItem) + m_surfaceItem->resetHeight(); + QQuickItem::resetHeight(); +} + +SurfaceWrapper::Type SurfaceWrapper::type() const +{ + return m_type; +} + +SurfaceWrapper *SurfaceWrapper::parentSurface() const +{ + return m_parentSurface; +} + +Output *SurfaceWrapper::ownsOutput() const +{ + return m_ownsOutput; +} + +void SurfaceWrapper::setOwnsOutput(Output *newOwnsOutput) +{ + if (m_wrapperAboutToRemove) + return; + + if (m_ownsOutput == newOwnsOutput) + return; + + if (m_ownsOutput) { + m_ownsOutput->removeSurface(this); + } + + m_ownsOutput = newOwnsOutput; + + if (m_ownsOutput) { + m_ownsOutput->addSurface(this); + } + + Q_EMIT ownsOutputChanged(); +} + +void SurfaceWrapper::setOutputs(const QList &outputs, bool recordDiagnostics) +{ + if (m_wrapperAboutToRemove) + return; + if (m_type == Type::SplashScreen) { + m_prelaunchOutputs = outputs; + return; + } + if (!surface()) { + qCDebug(lcTlSurface) << "SurfaceWrapper::setOutputs called but surface() is null!"; + return; + } + const auto oldOutputs = surface()->outputs(); + for (auto output : std::as_const(oldOutputs)) { + if (outputs.contains(output)) { + continue; + } + if (recordDiagnostics) { + m_outputsDiagnostics.lastLeaveOutput = output->name(); + m_outputsDiagnostics.lastLeaveOutputEnabled = output->isEnabled(); + } + surface()->leaveOutput(output); + if (recordDiagnostics) + m_outputsDiagnostics.lastLeaveEmptiedOutputs = surface()->outputs().isEmpty(); + } + + for (auto output : outputs) { + if (oldOutputs.contains(output)) + continue; + surface()->enterOutput(output); + } +} + +void SurfaceWrapper::noteOutputsUpdate(OutputsUpdateReason reason, + int enabledOutputs, + int totalOutputs, + int computedOutputs) +{ + // Every lastOutputsUpdate* field is written here and nowhere else, so the + // eight values always describe the same updateSurfaceOutputs() call. + m_outputsDiagnostics.updateReason = reason; + m_outputsDiagnostics.updateEnabledOutputs = enabledOutputs; + m_outputsDiagnostics.updateTotalOutputs = totalOutputs; + m_outputsDiagnostics.updateComputedOutputs = computedOutputs; + m_outputsDiagnostics.updateAutomatic = positionAutomatic(); +} + +const QList &SurfaceWrapper::outputs() const +{ + if (m_type == Type::SplashScreen) { + return m_prelaunchOutputs; + } + if (!surface()) { + static const QList empty; + return empty; + } + return surface()->outputs(); +} + +QRectF SurfaceWrapper::geometry() const +{ + return QRectF(position(), size()); +} + +SurfaceWrapper::State SurfaceWrapper::previousSurfaceState() const +{ + return m_previousSurfaceState; +} + +SurfaceWrapper::State SurfaceWrapper::surfaceState() const +{ + return m_surfaceState; +} + +bool SurfaceWrapper::checkSetSurfaceState(State newSurfaceState, bool allowRetarget) +{ + if (m_wrapperAboutToRemove) + return false; + + if (m_geometryAnimation && !allowRetarget) + return false; + + if (m_surfaceState == newSurfaceState) + return false; + + if (m_isSnapMask && (newSurfaceState == State::Maximized || newSurfaceState == State::Tiling)) + return false; + + if (!container() + || container()->filterSurfaceStateChange(this, newSurfaceState, m_surfaceState)) { + return false; + } + + return true; +} + +bool SurfaceWrapper::shouldUpdateNormalGeometry() const +{ + if (!isNormal() || m_geometryAnimation) + return false; + + auto *xdgSurface = qobject_cast(m_shellSurface.data()); + if (!xdgSurface || !surface()) + return true; + + if (!surface()->mapped()) { + return !xdgSurface->handle()->requested.maximized + && !xdgSurface->handle()->requested.fullscreen; + } + + return !xdgSurface->handle()->current.maximized + && !xdgSurface->handle()->current.fullscreen; +} + +void SurfaceWrapper::setSurfaceState(State newSurfaceState) +{ + if (!checkSetSurfaceState(newSurfaceState, true)) + return; + + // The exposed state changes immediately, but the shell surface is only + // notified at the animation's first frame: the animation captures its + // snapshot of the old content there, and notifying earlier makes the + // client resize before that snapshot, which flickers the first frame. + abortGeometryAnimation(); + setSurfaceStateValue(newSurfaceState); + + const QRectF targetGeometry = targetGeometryForState(newSurfaceState); + if (targetGeometry.isValid() && isVisible() && !m_sessionVisibilityChanging + && geometryAnimationEnabled(newSurfaceState)) + startStateChangeAnimation(targetGeometry); + else + applySurfaceState(); +} + +void SurfaceWrapper::setSurfaceStateDirectly(State newSurfaceState) +{ + if (!checkSetSurfaceState(newSurfaceState)) + return; + + abortGeometryAnimation(); + setSurfaceStateValue(newSurfaceState); + applySurfaceState(); +} + +QRectF SurfaceWrapper::targetGeometryForState(State state) const +{ + switch (state) { + case State::Maximized: + return m_maximizedGeometry; + case State::Fullscreen: + return m_fullscreenGeometry; + case State::Normal: + return m_normalGeometry; + case State::Tiling: + return m_tilingGeometry; + default: + return QRectF(); + } +} + +bool SurfaceWrapper::applyGeometry(const QRectF &targetGeometry) +{ + if (!resize(targetGeometry.size(), true)) + return false; + + setPosition(alignToPixelGrid(targetGeometry.topLeft())); + resize(targetGeometry.size()); + return true; +} + +bool SurfaceWrapper::applySurfaceState() +{ + // Single place that lands a state without an animation: shell notification, + // then geometry. Idempotent, so it is also safe as the animation fallback. + applyShellSurfaceState(); + + const QRectF targetGeometry = targetGeometryForState(m_surfaceState); + if (targetGeometry.isValid()) + return applyGeometry(targetGeometry); + + if (m_surfaceState == State::Normal) + resetXdgToplevelSize(); + return true; +} + +void SurfaceWrapper::abortGeometryAnimation() +{ + if (m_geometryAnimation) { + m_geometryAnimation->disconnect(this); + m_geometryAnimation->deleteLater(); + m_geometryAnimation = nullptr; + } +} + +void SurfaceWrapper::resetXdgToplevelSize() +{ + // XdgToplevel has no stored normal geometry to fall back to, so reset the + // configured size to let the client re-negotiate it. + if (m_type == Type::XdgToplevel && m_shellSurface) + m_shellSurface->resize(QSize(0, 0)); +} + +QBindable SurfaceWrapper::bindableSurfaceState() +{ + return &m_surfaceState; +} + +bool SurfaceWrapper::isNormal() const +{ + return m_surfaceState == State::Normal; +} + +bool SurfaceWrapper::isMaximized() const +{ + return m_surfaceState == State::Maximized; +} + +bool SurfaceWrapper::isMinimized() const +{ + return m_minimized; +} + +bool SurfaceWrapper::isTiling() const +{ + return m_surfaceState == State::Tiling; +} + +bool SurfaceWrapper::isAnimationRunning() const +{ + return m_geometryAnimation; +} + +bool SurfaceWrapper::isWindowAnimationRunning() const +{ + return !m_windowAnimation.isNull(); +} + +void SurfaceWrapper::destroy() +{ + invalidate(); + if (!isWindowAnimationRunning()) + deleteLater(); + // else delete this in Animation(for window close animation) finish +} + +bool SurfaceWrapper::isAboutToRemove() const +{ + return m_wrapperAboutToRemove; +} + +bool SurfaceWrapper::acceptKeyboardFocus() const +{ + return m_focusControlStates.testFlag(FocusControlState::AcceptKeyboardFocus); +} + +void SurfaceWrapper::setAcceptKeyboardFocus(bool accept) +{ + if (acceptKeyboardFocus() == accept) + return; + + updateFocusControlState(FocusControlState::AcceptKeyboardFocus, accept); +} + +bool SurfaceWrapper::isActivated() const +{ + return m_isActivated; +} + +bool SurfaceWrapper::attention() const +{ + return m_attention; +} + +bool SurfaceWrapper::setAttention(bool attention) +{ + if (m_attention == attention) + return true; + if (attention && m_isActivated) { + qCWarning(lcTlSurface) << "setAttention(true) ignored: surface is already activated"; + return false; + } + m_attention = attention; + Q_EMIT attentionChanged(); + return true; +} + +void SurfaceWrapper::setPendingActivation(WSeat *seat) +{ + m_pendingActivation = true; + m_pendingActivationSeat = seat; +} + +bool SurfaceWrapper::takePendingActivation(WSeat *&seat) +{ + if (!m_pendingActivation) + return false; + m_pendingActivation = false; + seat = m_pendingActivationSeat.data(); + m_pendingActivationSeat.clear(); + return true; +} + +bool SurfaceWrapper::isInputPopupLike() const +{ + return m_type == Type::InputPopup || m_isIMCandidatePanel; +} + +bool SurfaceWrapper::isIMCandidatePanel() const +{ + return m_isIMCandidatePanel; +} + +QString SurfaceWrapper::layerScope() const +{ + if (type() != Type::Layer) + return {}; + auto *layerSurface = qobject_cast(m_shellSurface); + if (!layerSurface) + return {}; + return layerSurface->scope(); +} + +bool SurfaceWrapper::isLaunchpad() const +{ + return layerScope() == LaunchpadScope; +} + +bool SurfaceWrapper::isQuickLaunchpad() const +{ + return layerScope() == QuickLaunchpadScope; +} + +bool SurfaceWrapper::isDesktop() const +{ + return layerScope() == DesktopScope; +} + +void SurfaceWrapper::setIMCandidatePanel(bool isIMCandidatePanel) +{ + if (m_isIMCandidatePanel == isIMCandidatePanel) + return; + m_isIMCandidatePanel = isIMCandidatePanel; + Q_EMIT isIMCandidatePanelChanged(); +} + +bool SurfaceWrapper::isSnapMask() const +{ + return m_isSnapMask; +} + +void SurfaceWrapper::setSnapMask(bool snapMask) +{ + if (m_isSnapMask == snapMask) + return; + m_isSnapMask = snapMask; + Q_EMIT snapMaskChanged(); + updateSizeCapabilities(); +} + +void SurfaceWrapper::setNoDecoration(bool newNoDecoration) +{ + if (m_wrapperAboutToRemove) + return; + + if (m_noDecoration == newNoDecoration) + return; + + m_noDecoration = newNoDecoration; + setNoCornerRadius(newNoDecoration); + + updateDecoration(); +} + +void SurfaceWrapper::updateDecoration() +{ + if (m_type != Type::SplashScreen) + updateTitleBar(); + + if (m_noDecoration) { + Q_ASSERT(m_decoration); + m_decoration->disconnect(this); + m_decoration->deleteLater(); + m_decoration = nullptr; + } else { + Q_ASSERT(!m_decoration); + Q_ASSERT(m_surfaceItem || m_prelaunchSplash); + m_decoration = m_engine->createDecoration(this, this); + m_decoration->stackBefore(m_surfaceItem ? m_surfaceItem : m_prelaunchSplash); + connect(m_decoration, &QQuickItem::xChanged, this, &SurfaceWrapper::updateBoundingRect); + connect(m_decoration, &QQuickItem::yChanged, this, &SurfaceWrapper::updateBoundingRect); + connect(m_decoration, &QQuickItem::widthChanged, this, &SurfaceWrapper::updateBoundingRect); + connect(m_decoration, + &QQuickItem::heightChanged, + this, + &SurfaceWrapper::updateBoundingRect); + } + + updateBoundingRect(); + Q_EMIT noDecorationChanged(); +} + +void SurfaceWrapper::updateTitleBar() +{ + if (m_wrapperAboutToRemove) + return; + + // No surfaceItem in prelaunch mode -> early return + if (!m_surfaceItem) + return; + + if (noTitleBar() == !m_titleBar) + return; + + if (m_titleBar) { + m_titleBar->disconnect(this); + m_titleBar->deleteLater(); + m_titleBar = nullptr; + } else { + m_titleBar = m_engine->createTitleBar(this, m_surfaceItem); + m_titleBar->setZ(static_cast(WSurfaceItem::ZOrder::ContentItem)); + connect(m_titleBar, &QQuickItem::heightChanged, this, &SurfaceWrapper::syncTitleBarPadding); + } + + syncTitleBarPadding(); + Q_EMIT noTitleBarChanged(); +} + +void SurfaceWrapper::syncTitleBarPadding() +{ + m_surfaceItem->setTopPadding(m_titleBar ? m_titleBar->height() : 0); + + // A maximized/fullscreen/tiled window keeps its frame on the state rect, so a title bar + // that appears or goes away later must re-apply it; an animation lands the rect itself. + // applied == state only holds because applyShellSurfaceState()'s single caller lands it. + const QRectF stateGeometry = targetGeometryForState(m_surfaceState); + if (!m_isProxy && m_surfaceState != State::Normal && m_appliedSurfaceState == m_surfaceState + && !m_geometryAnimation && stateGeometry.isValid()) { + applyGeometry(stateGeometry); + } +} + +void SurfaceWrapper::setBoundedRect(const QRectF &newBoundedRect) +{ + if (m_boundedRect == newBoundedRect) + return; + m_boundedRect = newBoundedRect; + Q_EMIT boundingRectChanged(); +} + +void SurfaceWrapper::updateBoundingRect() +{ + QRectF rect(QRectF(QPointF(0, 0), size())); + if (m_surfaceItem) + rect |= m_surfaceItem->boundingRect(); + + if (!m_decoration || !m_visibleDecoration) { + setBoundedRect(rect); + return; + } + + const QRectF dr(m_decoration->position(), m_decoration->size()); + setBoundedRect(dr | rect); +} + +bool SurfaceWrapper::renderingEnabled() const { return m_renderingEnabled; } + +void SurfaceWrapper::syncRenderingState() +{ + setEnabled(m_renderingEnabled); + if (!m_surfaceItem) + return; + auto flags = m_surfaceItem->flags(); + if (!m_renderingEnabled && !flags.testFlag(WSurfaceItem::NonLive)) { + m_liveSuppressed = true; + m_surfaceItem->setFlags(flags | WSurfaceItem::NonLive); + } else if (m_renderingEnabled && m_liveSuppressed) { + m_liveSuppressed = false; + m_surfaceItem->setFlags(flags & ~WSurfaceItem::NonLive); + } +} + +void SurfaceWrapper::retireAnimation(QPointer &animation) +{ + if (!animation) + return; + disconnect(animation, nullptr, this, nullptr); + animation->setVisible(false); + animation->setEnabled(false); + for (auto *content : animation->findChildren()) + content->setLive(false); + animation->setParentItem(nullptr); + animation->deleteLater(); + animation = nullptr; +} + +void SurfaceWrapper::suspendAnimations() +{ + const bool geometryPending = m_geometryAnimation; + const bool windowPending = isWindowAnimationRunning(); + retireAnimation(m_geometryAnimation); + retireAnimation(m_windowAnimation); + retireAnimation(m_minimizeAnimation); + retireAnimation(m_showDesktopAnimation); + m_windowTransitionPending = false; + m_windowTransition->resetWindowTransition(); + setXwaylandPositionFromSurface(true); + if (geometryPending && !m_isProxy && !m_wrapperAboutToRemove && WaylandServer::instance()) { + if (m_prelaunchSplash && surface() && surface()->mapped() && m_surfaceItem->isReady()) + startPrelaunchSplashHideSequence(); + else + applySurfaceState(); + } + if (windowPending) + Q_EMIT windowAnimationRunningChanged(); + if (m_wrapperAboutToRemove) + deleteLater(); +} + +void SurfaceWrapper::setRenderingEnabled(bool enabled) +{ + QScopedValueRollback visibilityChanging(m_sessionVisibilityChanging, true); + const bool changed = m_renderingEnabled != enabled; + m_renderingEnabled = enabled; + setEnabled(enabled); + if (!enabled) + setVisible(false); + syncRenderingState(); + if (changed || !enabled) + suspendAnimations(); + if (changed) + Q_EMIT renderingEnabledChanged(); + updateVisible(); +} + +void SurfaceWrapper::updateVisible() +{ + if (m_wrapperAboutToRemove) + return; + const bool mapped = surface() && surface()->mapped(); + // A pure splash must not depend on its child's effective visibility: + // hiding this wrapper also hides that child, preventing later restoration. + const bool splash = m_prelaunchSplash + && (m_type == Type::SplashScreen || m_prelaunchSplash->isVisible()); + bool isVisible = m_renderingEnabled && !m_hideByWorkspace && !isMinimized() && (mapped || splash) + && m_socketEnabled && m_hideByshowDesk && !m_confirmHideByLockScreen; + setVisible(isVisible); +} + +void SurfaceWrapper::updateSubSurfaceStacking() +{ + SurfaceWrapper *lastSurface = this; + for (auto surface : std::as_const(m_subSurfaces)) { + surface->stackAfter(lastSurface); + lastSurface = surface->stackLastSurface(); + } +} + +void SurfaceWrapper::ensureAboveParent() +{ + if (!m_parentSurface) + return; + + if (!parentItem() || parentItem() != m_parentSurface->parentItem()) + return; + + const auto &children = parentItem()->childItems(); + int childIndex = children.indexOf(this); + if (childIndex == -1) + return; + + // Surface that should sit directly below this child: the previous sibling's + // top-most surface, or the parent itself if this is the first child. + const auto &siblings = m_parentSurface->m_subSurfaces; + int myPos = siblings.lastIndexOf(this); + SurfaceWrapper *below = (myPos > 0) ? siblings[myPos - 1]->stackLastSurface() : m_parentSurface; + int belowIndex = children.indexOf(below); + if (belowIndex == -1) + return; + + if (childIndex > belowIndex) + return; + + qCDebug(lcTlSurface) << "Reordering surface" << this << "above parent" << m_parentSurface; + m_parentSurface->updateSubSurfaceStacking(); +} + +void SurfaceWrapper::updateClipRect() +{ + if (!clip() || !window()) + return; + auto rw = qobject_cast(window()); + Q_ASSERT(rw); + rw->markItemClipRectDirty(this); +} + +void SurfaceWrapper::geometryChange(const QRectF &newGeo, const QRectF &oldGeometry) +{ + QRectF newGeometry = newGeo; + if (m_container && m_container->filterSurfaceGeometryChanged(this, newGeometry, oldGeometry)) + return; + + if (shouldUpdateNormalGeometry()) { + setNormalGeometry(newGeometry); + } + + if (widthValid() && heightValid()) { + resize(newGeometry.size()); + } + + Q_EMIT geometryChanged(); + QQuickItem::geometryChange(newGeometry, oldGeometry); + if (newGeometry.size() != oldGeometry.size()) + updateBoundingRect(); + updateClipRect(); +} + +void SurfaceWrapper::tryFlushPendingActivation() +{ + if (!m_pendingActivation) + return; + + if (!hasInitializeContainer()) { + connect(this, + &SurfaceWrapper::hasInitializeContainerChanged, + this, + &SurfaceWrapper::tryFlushPendingActivation, + Qt::SingleShotConnection); + return; + } + + WSeat *seat = nullptr; + if (takePendingActivation(seat)) + WaylandServer::instance()->forceActivateSurface(this, Qt::OtherFocusReason, seat); +} + +void SurfaceWrapper::startWindowTransition() +{ + if (!m_renderingEnabled || m_sessionVisibilityChanging) + return; + if (!m_windowTransition->active()) { + m_windowTransitionPending = false; + if (m_windowAnimation) { + m_windowAnimation->disconnect(this); + m_windowAnimation->deleteLater(); + m_windowAnimation = nullptr; + Q_EMIT windowAnimationRunningChanged(); + } + return; + } + m_windowTransitionPending = true; + + if (!m_windowAnimation) { + auto globalRectOpt = m_windowTransition->globalRect(); + if (!globalRectOpt) { + // Origin wrapper or its surface item is gone — fall back to default. + m_windowTransitionPending = false; + m_windowTransition->resetWindowTransition(); + createNewOrClose(OPEN_ANIMATION); + return; + } + + beginWindowTransition(OPEN_ANIMATION, *globalRectOpt, + QRectF()); // will update later + } + + restackWindowAnimationAbove(); + + // Wait until the surface item reports ready before computing the target + // geometry. + if (!m_surfaceItem->isReady()) { + connect(m_surfaceItem, + &WSurfaceItem::readyChanged, + this, + &SurfaceWrapper::startWindowTransition, + Qt::SingleShotConnection); + return; + } + + // Defer to the next event-loop iteration so that the window's final + // position and size has set before we sample them. + QMetaObject::invokeMethod(this, + &SurfaceWrapper::finishWindowTransitionOpen, + Qt::QueuedConnection); +} + +void SurfaceWrapper::finishWindowTransitionOpen() +{ + m_windowTransitionPending = false; + if (!m_windowAnimation) + return; + // The surface may have unmapped while we were waiting. Drop the + // component we created above so it does not block a later close path. + if (!m_renderingEnabled || m_wrapperAboutToRemove || !surface() || !surface()->mapped()) { + if (m_windowAnimation) { + m_windowAnimation->deleteLater(); + m_windowAnimation = nullptr; + } + m_windowTransition->endAnimation(false); + return; + } + + // For maximized/fullscreen the target is the state geometry. + const QRectF stateGeometry = targetGeometryForState(m_surfaceState); + const bool useStateGeometry = + (m_surfaceState == State::Maximized || m_surfaceState == State::Fullscreen) + && stateGeometry.isValid(); + const QRectF toGeometry = useStateGeometry ? stateGeometry : QRectF(position(), size()); + + m_windowAnimation->setProperty("toGeometry", toGeometry); + + if (WaylandServer::instance()->noAnimation() + || !windowAnimationEnabled(OPEN_ANIMATION)) { + onShowAnimationFinished(); + return; + } + bool ok = connect(m_windowAnimation, SIGNAL(finished()), this, SLOT(onShowAnimationFinished())); + Q_ASSERT(ok); + ok = QMetaObject::invokeMethod(m_windowAnimation, "start"); + Q_ASSERT(ok); + Q_EMIT windowAnimationRunningChanged(); +} + +void SurfaceWrapper::startWindowCloseTransition() +{ + if (!m_renderingEnabled || m_sessionVisibilityChanging) + return; + Q_ASSERT(m_windowTransition->active()); + + auto globalRectOpt = m_windowTransition->globalRect(); + if (!globalRectOpt) { + // Origin wrapper or its surface item is gone — fall back to default. + m_windowTransition->resetWindowTransition(); + createNewOrClose(CLOSE_ANIMATION); + return; + } + + beginWindowTransition(CLOSE_ANIMATION, QRectF(position(), size()), *globalRectOpt); + + restackWindowAnimationAbove(); + + if (WaylandServer::instance()->noAnimation() + || !windowAnimationEnabled(CLOSE_ANIMATION)) { + onHideAnimationFinished(); + return; + } + + bool ok = connect(m_windowAnimation, SIGNAL(finished()), this, SLOT(onHideAnimationFinished())); + Q_ASSERT(ok); + ok = QMetaObject::invokeMethod(m_windowAnimation, "start"); + Q_ASSERT(ok); + Q_EMIT windowAnimationRunningChanged(); +} + +void SurfaceWrapper::beginWindowTransition(int direction, + const QRectF &fromGeometry, + const QRectF &toGeometry) +{ + m_windowTransition->begin(); + + m_windowAnimation = m_engine->createWindowTransition(this, + fromGeometry, + toGeometry, + container(), + m_windowTransition->sourceSurface(), + direction); + m_windowAnimation->setProperty("enableBlur", blur()); +} + +void SurfaceWrapper::createNewOrClose(uint direction) +{ + if (!m_renderingEnabled || m_sessionVisibilityChanging) + return; + if (!m_windowAnimationEnabled) + return; + + if (m_windowAnimation || m_windowTransitionPending) + return; + + if (m_container.isNull()) + return; + + if (direction == OPEN_ANIMATION && m_windowTransition->active()) { + startWindowTransition(); + return; + } + + if (direction == CLOSE_ANIMATION && m_windowTransition->active()) { + startWindowCloseTransition(); + return; + } + + switch (m_type) { + case Type::SplashScreen: + [[fallthrough]]; + case Type::XdgToplevel: + [[fallthrough]]; + case Type::XWayland: { + m_windowAnimation = m_engine->createNewAnimation(this, container(), direction); + m_windowAnimation->setProperty("enableBlur", blur()); + } break; + case Type::Layer: { + auto *surface = qobject_cast(m_shellSurface); + auto anchor = surface->getExclusiveZoneEdge(); + if (isLaunchpad()) { + m_windowAnimation = m_engine->createLaunchpadAnimation(this, direction, m_container); + } else if (anchor != WLayerSurface::AnchorType::None) { + m_windowAnimation = m_engine->createLayerShellAnimation(this, container(), direction); + m_windowAnimation->setProperty("position", QVariant::fromValue(anchor)); + m_windowAnimation->setProperty("enableBlur", blur()); + } else { + // NOTE: missing fullscreen window animation, so hide window now. + if (m_hideByLockScreen) { + m_confirmHideByLockScreen = true; + updateVisible(); + } + } + }; break; + case Type::XdgPopup: + // NOTE: check z order for XdgToplevel parent/child after support popup animation + [[fallthrough]]; + default: + break; + } + + if (m_windowAnimation) { + restackWindowAnimationAbove(); + // The animation object is created above, so the existing direct-completion + // path (also used by noAnimation) can finish the business safely. + if (WaylandServer::instance()->noAnimation() + || !windowAnimationEnabled(direction)) { + if (direction == OPEN_ANIMATION) { + onShowAnimationFinished(); + } else { + onHideAnimationFinished(); + } + return; + } + bool ok = false; + if (direction == OPEN_ANIMATION) { + ok = connect(m_windowAnimation, + SIGNAL(finished()), + this, + SLOT(onShowAnimationFinished())); + } else { + ok = connect(m_windowAnimation, + SIGNAL(finished()), + this, + SLOT(onHideAnimationFinished())); + } + Q_ASSERT(ok); + ok = QMetaObject::invokeMethod(m_windowAnimation, "start"); + Q_ASSERT(ok); + + Q_EMIT windowAnimationRunningChanged(); + } +} + +void SurfaceWrapper::itemChange(ItemChange change, const ItemChangeData &data) +{ + if (change == ItemSceneChange) { + updateSurfaceSizeRatio(); + } + + return QQuickItem::itemChange(change, data); +} + +void SurfaceWrapper::setSurfaceStateValue(State newSurfaceState) +{ + if (m_wrapperAboutToRemove) + return; + + m_previousSurfaceState.setValueBypassingBindings(m_surfaceState); + m_surfaceState.setValueBypassingBindings(newSurfaceState); + m_previousSurfaceState.notify(); + m_surfaceState.notify(); +} + +void SurfaceWrapper::applyShellSurfaceState() +{ + if (m_wrapperAboutToRemove || m_appliedSurfaceState == m_surfaceState) + return; + + const State newSurfaceState = m_surfaceState; + + // In prelaunch mode there is no shellSurface; update state only without calling shellSurface + // methods + if (!m_shellSurface) { + m_appliedSurfaceState = newSurfaceState; + return; + } + + setVisibleDecoration(newSurfaceState == State::Normal); + setNoCornerRadius(newSurfaceState == State::Maximized || newSurfaceState == State::Fullscreen + || newSurfaceState == State::Tiling); + + switch (m_appliedSurfaceState) { + case State::Maximized: + m_shellSurface->setMaximize(false); + break; + case State::Fullscreen: + m_shellSurface->setFullScreen(false); + break; + case State::Normal: + [[fallthrough]]; + case State::Tiling: + [[fallthrough]]; + default: + break; + } + + switch (newSurfaceState) { + case State::Maximized: + m_shellSurface->setMaximize(true); + break; + case State::Fullscreen: + m_shellSurface->setFullScreen(true); + break; + case State::Normal: + [[fallthrough]]; + case State::Tiling: + [[fallthrough]]; + default: + break; + } + + // Before recording the state, so a padding change here does not re-apply the geometry. + updateTitleBar(); + m_appliedSurfaceState = newSurfaceState; + updateVisible(); +} + +void SurfaceWrapper::onAnimationReady() +{ + // abort change state if cannot resize + if (!applySurfaceState()) + abortGeometryAnimation(); +} + +void SurfaceWrapper::onAnimationFinished() +{ + setXwaylandPositionFromSurface(true); + Q_ASSERT(m_geometryAnimation); + // The ready signal is driven by ShaderEffectSource's scheduled update. + // Software renderers may complete the geometry animation without issuing + // that update, so apply here as an idempotent fallback. Re-applying also + // settles geometry that was retargeted after the ready frame. + applySurfaceState(); + abortGeometryAnimation(); +} + +bool SurfaceWrapper::startStateChangeAnimation(const QRectF &targetGeometry) +{ + if (!m_renderingEnabled || m_sessionVisibilityChanging) + return false; + if (m_geometryAnimation) // animation running + return false; + + m_geometryAnimation = + m_engine->createGeometryAnimation(this, geometry(), targetGeometry, container()); + m_geometryAnimation->setProperty("enableBlur", blur()); + bool ok = connect(m_geometryAnimation, SIGNAL(ready()), this, SLOT(onAnimationReady())); + Q_ASSERT(ok); + ok = connect(m_geometryAnimation, SIGNAL(finished()), this, SLOT(onAnimationFinished())); + Q_ASSERT(ok); + + setXwaylandPositionFromSurface(false); + ok = QMetaObject::invokeMethod(m_geometryAnimation, "start"); + Q_ASSERT(ok); + return ok; +} + +void SurfaceWrapper::onWindowAnimationFinished() +{ + Q_ASSERT(m_windowAnimation); + m_windowAnimation->disconnect(this); + m_windowAnimation->deleteLater(); + m_windowAnimation = nullptr; + + // Stop pacing the transition source now that the animation is over. The + // source itself stays referenced until the rect is done with it. + m_windowTransition->endAnimation(m_wrapperAboutToRemove); + + Q_EMIT windowAnimationRunningChanged(); + + if (m_wrapperAboutToRemove) { + deleteLater(); + } +} + +void SurfaceWrapper::onShowAnimationFinished() +{ + onWindowAnimationFinished(); + + if (m_prelaunchSplash && surface() && surface()->mapped()) { + startPrelaunchSplashHideSequence(); + } +} + +void SurfaceWrapper::onHideAnimationFinished() +{ + if (m_coverContent) { + m_coverContent->setVisible(false); + } + + if (m_hideByLockScreen) { + m_confirmHideByLockScreen = true; + updateVisible(); + } + + onWindowAnimationFinished(); +} + +void SurfaceWrapper::onMappedChanged() +{ + if (m_wrapperAboutToRemove) + return; + + Q_ASSERT(surface()); + bool mapped = surface()->mapped() && !m_hideByLockScreen; + + if (!m_isProxy) { + if (mapped) { + if (!m_prelaunchSplash) { + createNewOrClose(OPEN_ANIMATION); + } else { + m_windowTransition->resetWindowTransition(); + syncPrelaunchMappedState(); + startPrelaunchSplashHideSequence(); + } + if (m_coverContent) { + m_coverContent->setVisible(true); + } + } else { + createNewOrClose(CLOSE_ANIMATION); + } + } + + if (mapped) + tryFlushPendingActivation(); + + if (m_coverContent) { + m_coverContent->setProperty("mapped", mapped); + } + + // Splash can't call onMappedChanged, just use mapped state to update + updateHasActiveCapability(ActiveControlState::MappedOrSplash, mapped); + updateFocusControlState(FocusControlState::Mapped, mapped); + updateVisible(); +} + +void SurfaceWrapper::bindVisibilitySocket(WSocket *socket) +{ + if (m_visibilitySocket == socket) + return; + if (m_visibilitySocket) + disconnect(m_visibilitySocket, &WSocket::enabledChanged, + this, &SurfaceWrapper::onSocketEnabledChanged); + m_visibilitySocket = socket; + if (socket) + connect(socket, &WSocket::enabledChanged, this, &SurfaceWrapper::onSocketEnabledChanged); + onSocketEnabledChanged(); +} + +void SurfaceWrapper::onSocketEnabledChanged() +{ + m_socketEnabled = m_visibilitySocket && m_visibilitySocket->isEnabled(); + updateVisible(); +} + +void SurfaceWrapper::onMinimizeAnimationFinished() +{ + Q_ASSERT(m_minimizeAnimation); + m_minimizeAnimation->disconnect(this); + m_minimizeAnimation->deleteLater(); + m_minimizeAnimation = nullptr; +} + +void SurfaceWrapper::startMinimizeAnimation(const QRectF &iconGeometry, uint direction) +{ + if (!m_renderingEnabled || m_sessionVisibilityChanging) + return; + + // The minimize/restore state and visibility are already committed by the + // caller; disabling the animation only skips the shrink/expand transition. + auto *config = WaylandServer::instance()->animationConfig(); + if (config && !(direction == OPEN_ANIMATION ? config->restoreMinimized() : config->minimize())) { + // A transition started by the opposite request would keep its snapshot + // over the real window (hideSource) until it ends; release it so the + // committed state shows right away. + if (m_minimizeAnimation) + onMinimizeAnimationFinished(); + return; + } + + if (m_minimizeAnimation) { + m_minimizeAnimation->setProperty("direction", direction); + m_minimizeAnimation->setProperty("position", QVariant::fromValue(iconGeometry)); + const bool ok = QMetaObject::invokeMethod(m_minimizeAnimation, "redirect"); + Q_ASSERT(ok); + return; + } + if (!WaylandServer::instance()->surfaceBelongsToCurrentSession(this)) + return; + + m_minimizeAnimation = + m_engine->createMinimizeAnimation(this, container(), iconGeometry, direction); + + bool ok = + connect(m_minimizeAnimation, SIGNAL(finished()), this, SLOT(onMinimizeAnimationFinished())); + Q_ASSERT(ok); + ok = QMetaObject::invokeMethod(m_minimizeAnimation, "start"); + Q_ASSERT(ok); +} + +void SurfaceWrapper::setHideByShowDesk(bool show) +{ + if (m_hideByshowDesk == show) + return; + + m_hideByshowDesk = show; +} + +void SurfaceWrapper::setHideByLockScreen(bool hide) +{ + if (m_hideByLockScreen == hide) { + return; + } + + QScopedValueRollback visibilityChanging(m_sessionVisibilityChanging, true); + m_hideByLockScreen = hide; + m_confirmHideByLockScreen = hide; + suspendAnimations(); + onMappedChanged(); +} + +void SurfaceWrapper::onShowDesktopAnimationFinished() +{ + Q_ASSERT(m_showDesktopAnimation); + m_showDesktopAnimation->disconnect(this); + m_showDesktopAnimation->deleteLater(); + m_showDesktopAnimation = nullptr; + updateVisible(); +} + +void SurfaceWrapper::startShowDesktopAnimation(bool show) +{ + if (!m_renderingEnabled || m_sessionVisibilityChanging) { + setHideByShowDesk(show); + updateVisible(); + return; + } + + if (m_showDesktopAnimation) { + m_showDesktopAnimation->disconnect(this); + m_showDesktopAnimation->deleteLater(); + m_showDesktopAnimation = nullptr; + } + + setHideByShowDesk(show); + + // The final visibility is driven by m_hideByshowDesk, so the disabled path + // finishes exactly like the animation's finished handler. + auto *config = WaylandServer::instance()->animationConfig(); + if (config && !(show ? config->restoreShowDesktop() : config->showDesktop())) { + updateVisible(); + return; + } + + m_showDesktopAnimation = m_engine->createShowDesktopAnimation(this, container(), show); + bool ok = connect(m_showDesktopAnimation, + SIGNAL(finished()), + this, + SLOT(onShowDesktopAnimationFinished())); + Q_ASSERT(ok); + ok = QMetaObject::invokeMethod(m_showDesktopAnimation, "start"); + Q_ASSERT(ok); +} + +void SurfaceWrapper::initializeFrameGeometry() +{ + connect(this, &SurfaceWrapper::radiusChanged, this, &SurfaceWrapper::updateFrameGeometry); + connect(this, &SurfaceWrapper::noCornerRadiusChanged, this, &SurfaceWrapper::updateFrameGeometry); + connect(this, &SurfaceWrapper::noDecorationChanged, this, &SurfaceWrapper::updateFrameGeometry); + connect(this, &SurfaceWrapper::visibleDecorationChanged, this, &SurfaceWrapper::updateFrameGeometry); + connect(this, &SurfaceWrapper::surfaceItemCreated, this, &SurfaceWrapper::updateFrameGeometry); + connect(this, &SurfaceWrapper::prelaunchSplashChanged, this, &SurfaceWrapper::updateFrameGeometry); + updateRadiusConfig(); +} + +void SurfaceWrapper::updateRadiusConfig() +{ + disconnect(m_radiusConfigConnection); + if (auto *owner = desktop()) { + m_radiusConfigConnection = connect(owner->config(), &TreelandUserConfig::windowRadiusChanged, + this, &SurfaceWrapper::radiusChanged); + } + Q_EMIT radiusChanged(); +} + +void SurfaceWrapper::updateFrameGeometry() +{ + QQuickItem *item = m_surfaceItem ? m_surfaceItem : m_prelaunchSplash.data(); + const bool itemChanged = m_frameItem != item; + if (itemChanged && m_prelaunchSplash && m_frameItem == m_prelaunchSplash && m_surfaceItem) { + // The visible splash must not inherit the incoming surface's provisional geometry. + m_prelaunchFrameGeometry = m_frameGeometry; + } + if (itemChanged) { + if (m_frameItem) { + disconnect(m_frameItem, &QQuickItem::widthChanged, this, &SurfaceWrapper::updateFrameGeometry); + disconnect(m_frameItem, &QQuickItem::heightChanged, this, &SurfaceWrapper::updateFrameGeometry); + } + m_frameItem = item; + if (item) { + connect(item, &QQuickItem::widthChanged, this, &SurfaceWrapper::updateFrameGeometry); + connect(item, &QQuickItem::heightChanged, this, &SurfaceWrapper::updateFrameGeometry); + } + } + // Static QQuickWindow::graphicsApi() can report the RHI API for the software scene graph. + // Proxies round on the radius alone: a client-side decorated source has no decoration + // item, but its thumbnail still needs a frame to clip the scaled content. + const bool rounded = (m_decoration || m_isProxy) && m_visibleDecoration && !m_noCornerRadius + && QQuickWindow::sceneGraphBackend() != QStringLiteral("software"); + const FrameGeometry geometry(QRectF(QPointF(), item ? item->size() : QSizeF()), + rounded ? radius() : 0); + if (!itemChanged && geometry == m_frameGeometry) + return; + m_frameGeometry = geometry; + Q_EMIT frameGeometryChanged(); + if (!m_prelaunchFrameGeometry) + Q_EMIT presentationFrameGeometryChanged(); +} + +qreal SurfaceWrapper::radius() const +{ + if (isInputPopupLike()) + return 0; + if (m_type == Type::XdgPopup) + return 8; + + qreal radius = m_radius; + // A negative m_radius means no per-window override, so fall back to DConfig. + // Every non-negative value is explicit and applied as sent, including 0 which + // means square corners (treeland-decoration set_corner_radius(0)). + if (radius < 0 && m_type != Type::Layer && !m_isProxy) { + radius = (desktop() ? desktop()->config()->windowRadius() : 0); + } + + return radius < 0 ? 0 : radius; +} + +void SurfaceWrapper::setRadius(qreal newRadius) +{ + if (qFuzzyCompare(m_radius, newRadius)) + return; + m_radius = newRadius; + Q_EMIT radiusChanged(); +} + +// --------------------------------------------------------------------------- +// Per-window SSD customization (treeland-decoration-unstable-v1) +// --------------------------------------------------------------------------- + +qreal SurfaceWrapper::shadowBlurRadius() const +{ + return m_shadowBlurRadius; +} + +qreal SurfaceWrapper::shadowOffsetX() const +{ + return m_shadowOffsetX; +} + +qreal SurfaceWrapper::shadowOffsetY() const +{ + return m_shadowOffsetY; +} + +QColor SurfaceWrapper::shadowColor() const +{ + return m_shadowColor; +} + +bool SurfaceWrapper::shadowVisible() const +{ + return m_shadowVisible; +} + +void SurfaceWrapper::setShadowValues(qreal blur, qreal offsetX, qreal offsetY, const QColor &color) +{ + if (qFuzzyCompare(m_shadowBlurRadius, blur) && qFuzzyCompare(m_shadowOffsetX, offsetX) + && qFuzzyCompare(m_shadowOffsetY, offsetY) && m_shadowColor == color) + return; + m_shadowBlurRadius = blur; + m_shadowOffsetX = offsetX; + m_shadowOffsetY = offsetY; + m_shadowColor = color; + Q_EMIT shadowChanged(); +} + +void SurfaceWrapper::setShadowVisible(bool visible) +{ + if (m_shadowVisible == visible) + return; + m_shadowVisible = visible; + Q_EMIT shadowChanged(); +} + +qreal SurfaceWrapper::borderWidth() const +{ + return m_borderWidth; +} + +QColor SurfaceWrapper::borderColor() const +{ + return m_borderColor; +} + +bool SurfaceWrapper::borderVisible() const +{ + return m_borderVisible; +} + +void SurfaceWrapper::setBorderValues(qreal width, const QColor &color) +{ + if (qFuzzyCompare(m_borderWidth, width) && m_borderColor == color) + return; + m_borderWidth = width; + m_borderColor = color; + Q_EMIT borderChanged(); +} + +void SurfaceWrapper::setBorderVisible(bool visible) +{ + if (m_borderVisible == visible) + return; + m_borderVisible = visible; + Q_EMIT borderChanged(); +} + +void SurfaceWrapper::minimize(bool onAnimation) +{ + if (m_wrapperAboutToRemove) + return; + + if (m_minimized) + return; + + // The parent container may reject state changes during interactive edge resize. + if (container()->filterSurfaceStateChange(this, m_surfaceState, m_surfaceState)) + return; + + abortGeometryAnimation(); + + m_minimized = true; + + if (!m_shellSurface) { + updateVisible(); + return; + } + + // Keep modal/parent minimize linkage ahead of this surface's own state change + // so focus fallback never sees the parent in the old state first. + if (modal() && m_parentSurface && !m_parentSurface->isMinimized()) + m_parentSurface->minimize(false); + + m_shellSurface->setMinimize(true); + // Drop the active capability first: it drives the focus fallback, and losing focus + // capability clears the seat keyboard focus beforehand, which would make the fallback + // skip this surface and leave no window focused. + updateHasActiveCapability(ActiveControlState::UnMinimized, false); + updateFocusControlState(FocusControlState::UnMinimized, false); + updateVisible(); + + for (SurfaceWrapper *child : std::as_const(m_subSurfaces)) { + if (child->modal()) + continue; // Modal children stay visible when parent is minimized. + if (!child->isMinimized()) + child->minimize(false); + } + + if (onAnimation) + startMinimizeAnimation(iconGeometry(), CLOSE_ANIMATION); +} + +void SurfaceWrapper::restoreFromMinimized(bool onAnimation) +{ + if (m_wrapperAboutToRemove) + return; + + if (!m_minimized && m_hideByshowDesk) + return; + if (!m_hideByshowDesk) + setHideByShowDesk(true); + + m_minimized = false; + + if (!m_shellSurface) { + updateVisible(); + } else { + if (modal() && m_parentSurface && m_parentSurface->isMinimized()) + m_parentSurface->restoreFromMinimized(false); + + updateFocusControlState(FocusControlState::UnMinimized, true); + updateHasActiveCapability(ActiveControlState::UnMinimized, true); + + m_shellSurface->setMinimize(false); + updateVisible(); + + for (SurfaceWrapper *child : std::as_const(m_subSurfaces)) { + if (child->isMinimized()) + child->restoreFromMinimized(false); + } + } + + if (onAnimation) + startMinimizeAnimation(iconGeometry(), OPEN_ANIMATION); +} + +void SurfaceWrapper::maximize() +{ + if (m_type == Type::XdgToplevel && surface() && !surface()->mapped()) { + auto *xdgSurface = qobject_cast(m_shellSurface.data()); + if (xdgSurface->isInitialized()) + setSurfaceStateDirectly(State::Maximized); + return; + } + + // A fullscreen window must be un-fullscreened before it can be maximized. + if (m_surfaceState == State::Fullscreen || !isMaximizable()) + return; + + setSurfaceState(State::Maximized); +} + +void SurfaceWrapper::unmaximize() +{ + if (m_type == Type::XdgToplevel && surface() && !surface()->mapped()) { + auto *xdgSurface = qobject_cast(m_shellSurface.data()); + if (xdgSurface->isInitialized()) + setSurfaceStateDirectly(State::Normal); + return; + } + + if (m_surfaceState != State::Maximized) + return; + + setSurfaceState(State::Normal); +} + +void SurfaceWrapper::toggleMaximized() +{ + if (m_surfaceState == State::Maximized) + unmaximize(); + else + maximize(); +} + +bool SurfaceWrapper::supportsTileMode(TileMode mode) const +{ + switch (mode) { + case TileMode::None: + return true; + case TileMode::Maximize: + return isMaximizable(); + case TileMode::Left: + case TileMode::Right: + case TileMode::TopLeft: + case TileMode::TopRight: + case TileMode::BottomLeft: + case TileMode::BottomRight: + return isResizable(); + } + + Q_UNREACHABLE_RETURN(false); +} + +void SurfaceWrapper::applyTileMode(TileMode mode, Output *output) +{ + if (mode == TileMode::None) { + cancelTileMode(); + return; + } + + if (!supportsTileMode(mode)) + return; + + if (mode == TileMode::Maximize) { + // Use the cursor's output geometry, not the surface's current output, + // so maximize lands on the screen the user dragged to (matches preview). + if (output) + setMaximizedGeometry(output->validGeometryForSurface(this)); + maximize(); + return; + } + + const QRectF geo = output ? output->tileGeometry(mode, this) : QRectF(); + if (!geo.isValid()) + return; + + // Order matters: setTilingGeometry first so that a subsequent + // setSurfaceState(Tiling) reads the new m_tilingGeometry as its target. + setTilingGeometry(geo); + setSurfaceState(State::Tiling); +} + +void SurfaceWrapper::cancelTileMode() +{ + setSurfaceStateDirectly(State::Normal); +} + +void SurfaceWrapper::enterFullscreen(WOutput *targetOutput) +{ + if (targetOutput) { + auto *server = WaylandServer::instance(); + auto *target = server ? server->getOutput(targetOutput) : nullptr; + if (target && target->isSource()) { + if (target != m_ownsOutput) + setOwnsOutput(target); + } + } + + if (m_type == Type::XdgToplevel && surface() && !surface()->mapped()) { + auto *xdgSurface = qobject_cast(m_shellSurface.data()); + if (xdgSurface->isInitialized()) + setSurfaceStateDirectly(State::Fullscreen); + return; + } + + setSurfaceState(State::Fullscreen); +} + +void SurfaceWrapper::leaveFullscreen() +{ + if (m_type == Type::XdgToplevel && surface() && !surface()->mapped()) { + auto *xdgSurface = qobject_cast(m_shellSurface.data()); + if (xdgSurface->isInitialized()) + setSurfaceStateDirectly(m_previousSurfaceState); + return; + } + + if (m_surfaceState != State::Fullscreen) + return; + + setSurfaceState(m_previousSurfaceState); +} + +void SurfaceWrapper::closeSurface() +{ + // No shellSurface in prelaunch mode -> early return + if (!m_shellSurface) + return; + + m_shellSurface->close(); +} + +SurfaceWrapper *SurfaceWrapper::stackFirstSurface() const +{ + return m_subSurfaces.isEmpty() ? const_cast(this) + : m_subSurfaces.first()->stackFirstSurface(); +} + +SurfaceWrapper *SurfaceWrapper::stackLastSurface() const +{ + return m_subSurfaces.isEmpty() ? const_cast(this) + : m_subSurfaces.last()->stackLastSurface(); +} + +bool SurfaceWrapper::hasChild(SurfaceWrapper *child) const +{ + for (auto s : std::as_const(m_subSurfaces)) { + if (s == child || s->hasChild(child)) + return true; + } + + return false; +} + +bool SurfaceWrapper::stackBefore(QQuickItem *item) +{ + if (!parentItem() || item->parentItem() != parentItem()) + return false; + if (this == item) + return false; + + do { + auto s = qobject_cast(item); + if (s) { + if (s->hasChild(this)) + return false; + if (hasChild(s)) { + QQuickItem::stackBefore(item); + break; + } + item = s->stackFirstSurface(); + + if (m_parentSurface && m_parentSurface == s->m_parentSurface) { + QQuickItem::stackBefore(item); + + int myIndex = m_parentSurface->m_subSurfaces.lastIndexOf(this); + int siblingIndex = m_parentSurface->m_subSurfaces.lastIndexOf(s); + Q_ASSERT(myIndex != -1 && siblingIndex != -1); + if (myIndex != siblingIndex - 1) + m_parentSurface->m_subSurfaces.move(myIndex, + myIndex < siblingIndex ? siblingIndex - 1 + : siblingIndex); + break; + } + } + + if (m_parentSurface) { + if (!m_parentSurface->stackBefore(item)) + return false; + } else { + QQuickItem::stackBefore(item); + } + } while (false); + + updateSubSurfaceStacking(); + restackWindowAnimationAbove(); + return true; +} + +bool SurfaceWrapper::stackAfter(QQuickItem *item) +{ + if (!parentItem() || item->parentItem() != parentItem()) + return false; + if (this == item) + return false; + + do { + auto s = qobject_cast(item); + if (s) { + if (hasChild(s)) + return false; + if (s->hasChild(this)) { + QQuickItem::stackAfter(item); + break; + } + item = s->stackLastSurface(); + + if (m_parentSurface && m_parentSurface == s->m_parentSurface) { + QQuickItem::stackAfter(item); + + int myIndex = m_parentSurface->m_subSurfaces.lastIndexOf(this); + int siblingIndex = m_parentSurface->m_subSurfaces.lastIndexOf(s); + Q_ASSERT(myIndex != -1 && siblingIndex != -1); + if (myIndex != siblingIndex + 1) + m_parentSurface->m_subSurfaces.move(myIndex, + myIndex > siblingIndex ? siblingIndex + 1 + : siblingIndex); + + break; + } + } + + if (m_parentSurface) { + if (!m_parentSurface->stackAfter(item)) + return false; + } else { + QQuickItem::stackAfter(item); + } + } while (false); + + updateSubSurfaceStacking(); + restackWindowAnimationAbove(); + return true; +} + +void SurfaceWrapper::stackToLast() +{ + if (!parentItem()) + return; + + if (m_parentSurface) { + m_parentSurface->stackToLast(); + stackAfter(m_parentSurface->stackLastSurface()); + } else { + auto last = parentItem()->childItems().last(); + stackAfter(last); + } +} + +void SurfaceWrapper::stackToFirst() +{ + if (!parentItem()) + return; + + if (m_parentSurface) { + m_parentSurface->stackToFirst(); + stackBefore(m_parentSurface->stackFirstSurface()); + } else { + auto first = parentItem()->childItems().first(); + stackBefore(first); + } +} + +void SurfaceWrapper::restackWindowAnimationAbove() +{ + if (m_windowAnimation && parentItem() && m_windowAnimation->parentItem() == parentItem()) + m_windowAnimation->stackAfter(this); +} + +void SurfaceWrapper::addSubSurface(SurfaceWrapper *surface) +{ + Q_ASSERT(!surface->m_parentSurface); + surface->m_parentSurface = this; + surface->updateStackingLayer(); + m_subSurfaces.append(surface); + surface->ensureAboveParent(); +} + +void SurfaceWrapper::removeSubSurface(SurfaceWrapper *surface) +{ + Q_ASSERT(surface->m_parentSurface == this); + surface->m_parentSurface = nullptr; + surface->updateStackingLayer(); + m_subSurfaces.removeOne(surface); +} + +const QList &SurfaceWrapper::subSurfaces() const +{ + return m_subSurfaces; +} + +SurfaceContainer *SurfaceWrapper::container() const +{ + return m_container; +} + +void SurfaceWrapper::setContainer(SurfaceContainer *newContainer) +{ + if (m_container == newContainer) + return; + m_container = newContainer; + Q_EMIT containerChanged(); +} + +QQuickItem *SurfaceWrapper::titleBar() const +{ + return m_titleBar; +} + +QQuickItem *SurfaceWrapper::decoration() const +{ + return m_decoration; +} + +bool SurfaceWrapper::noDecoration() const +{ + return m_noDecoration; +} + +bool SurfaceWrapper::visibleDecoration() const +{ + return m_visibleDecoration; +} + +void SurfaceWrapper::setVisibleDecoration(bool newVisibleDecoration) +{ + if (m_wrapperAboutToRemove) + return; + if (m_visibleDecoration == newVisibleDecoration) + return; + m_visibleDecoration = newVisibleDecoration; + updateBoundingRect(); + Q_EMIT visibleDecorationChanged(); +} + +bool SurfaceWrapper::clipInOutput() const +{ + return m_clipInOutput; +} + +void SurfaceWrapper::setClipInOutput(bool newClipInOutput) +{ + if (m_wrapperAboutToRemove) + return; + + if (m_clipInOutput == newClipInOutput) + return; + m_clipInOutput = newClipInOutput; + updateClipRect(); + Q_EMIT clipInOutputChanged(); +} + +QRectF SurfaceWrapper::clipRect() const +{ + if (m_clipInOutput) { + return m_fullscreenGeometry & geometry(); + } + + return QQuickItem::clipRect(); +} + +bool SurfaceWrapper::noTitleBar() const +{ + if (m_surfaceState == State::Fullscreen) + return true; + + return m_noTitleBar || m_noDecoration; +} + +void SurfaceWrapper::setNoTitleBar(bool newNoTitleBar) +{ + if (m_wrapperAboutToRemove) + return; + + if (m_noTitleBar == newNoTitleBar) + return; + + m_noTitleBar = newNoTitleBar; + + updateTitleBar(); +} + +bool SurfaceWrapper::noCornerRadius() const +{ + return m_noCornerRadius; +} + +void SurfaceWrapper::setNoCornerRadius(bool newNoCornerRadius) +{ + if (m_wrapperAboutToRemove) + return; + + if (m_noCornerRadius == newNoCornerRadius) + return; + m_noCornerRadius = newNoCornerRadius; + Q_EMIT noCornerRadiusChanged(); +} + +QRect SurfaceWrapper::iconGeometry() const +{ + return m_iconGeometry; +} + +void SurfaceWrapper::setIconGeometry(QRect newIconGeometry) +{ + if (m_iconGeometry == newIconGeometry) + return; + m_iconGeometry = newIconGeometry; + Q_EMIT iconGeometryChanged(); +} + +Session *SurfaceWrapper::session() const +{ + return m_session; +} + +DesktopEnvironment *SurfaceWrapper::desktop() const +{ + return m_session ? m_session->desktop() : nullptr; +} + +void SurfaceWrapper::setSession(Session *session) +{ + Q_ASSERT(!m_session || m_session == session); + if (m_session || !session) + return; + m_session = session; + if (session) { + session->desktop()->registerSurface(this); + bindVisibilitySocket(session->socket()->rootSocket()); + session->scene()->attach(this); + connect(WaylandServer::instance(), &WaylandServer::activeSessionChanged, + this, &SurfaceWrapper::updateVisible); + connect(WaylandServer::instance(), &WaylandServer::activeSessionChanged, + this, &SurfaceWrapper::updateSurfaceSizeRatio); + } + if (session && (type() == Type::XdgToplevel || type() == Type::XWayland || !shellSurface())) + session->registerWindow(this); + updateRadiusConfig(); +} + +int SurfaceWrapper::workspaceId() const +{ + return m_workspaceId; +} + +void SurfaceWrapper::setWorkspaceId(int newWorkspaceId) +{ + if (m_workspaceId == newWorkspaceId) + return; + + bool onAllWorkspaceHasChanged = (m_workspaceId == Workspace::ShowOnAllWorkspaceId) + != (newWorkspaceId == Workspace::ShowOnAllWorkspaceId); + m_workspaceId = newWorkspaceId; + + if (onAllWorkspaceHasChanged) + Q_EMIT showOnAllWorkspaceChanged(); + Q_EMIT workspaceIdChanged(); +} + +void SurfaceWrapper::setHideByWorkspace(bool hide) +{ + if (m_hideByWorkspace == hide) + return; + + m_hideByWorkspace = hide; + updateVisible(); +} + +bool SurfaceWrapper::alwaysOnTop() const +{ + return m_surfaceRole == SurfaceRole::AlwaysOnTop; +} + +bool SurfaceWrapper::effectiveAlwaysOnTop() const +{ + return m_explicitAlwaysOnTop > 0; +} + +void SurfaceWrapper::setAlwaysOnTop(bool alwaysOnTop) +{ + if (this->alwaysOnTop() == alwaysOnTop || m_surfaceRole == SurfaceRole::PrivilegedOverlay) + return; + + setSurfaceRole(alwaysOnTop ? SurfaceRole::AlwaysOnTop : SurfaceRole::Normal); +} + +void SurfaceWrapper::setAlwaysOnBottom(bool alwaysOnBottom) +{ + if (m_alwaysOnBottom == alwaysOnBottom) + return; + + m_alwaysOnBottom = alwaysOnBottom; + updateStackingLayer(); +} + +bool SurfaceWrapper::showOnAllWorkspace() const +{ + if (m_type == Type::Layer || m_type == Type::XdgPopup || isInputPopupLike() || isSnapMask() + || surfaceRole() == SurfaceWrapper::SurfaceRole::PrivilegedOverlay) [[unlikely]] + return true; + return m_workspaceId == Workspace::ShowOnAllWorkspaceId; +} + +bool SurfaceWrapper::showOnWorkspace(int workspaceIndex) const +{ + if (m_workspaceId == workspaceIndex) + return true; + return showOnAllWorkspace(); +} + +bool SurfaceWrapper::isResizable() const +{ + return m_resizable; +} + +bool SurfaceWrapper::isMaximizable() const +{ + return m_maximizable; +} + +bool SurfaceWrapper::modal() const +{ + return m_modal; +} + +void SurfaceWrapper::setModal(bool modal) +{ + if (m_modal == modal) + return; + m_modal = modal; + Q_EMIT modalChanged(); +} + +SurfaceWrapper *SurfaceWrapper::findModal() const +{ + if (m_wrapperAboutToRemove) + return nullptr; + for (auto *child : std::as_const(m_subSurfaces)) { + if (child->m_wrapperAboutToRemove) + continue; + if (!child->surface() || !child->surface()->mapped()) + continue; + if (child->modal()) { + if (SurfaceWrapper *deepModal = child->findModal()) + return deepModal; + return child; + } + if (SurfaceWrapper *deepModal = child->findModal()) + return deepModal; + } + return nullptr; +} + +bool SurfaceWrapper::blur() const +{ + return m_blurPersonalization || m_blurBackgroundEffect; +} + +void SurfaceWrapper::setBlurPersonalization(bool blur) +{ + if (m_blurPersonalization == blur) { + return; + } + + m_blurPersonalization = blur; + + Q_EMIT blurChanged(); +} + +void SurfaceWrapper::setBlurBackgroundEffect(bool blur) +{ + if (m_blurBackgroundEffect == blur) { + return; + } + + m_blurBackgroundEffect = blur; + + Q_EMIT blurChanged(); +} + +void SurfaceWrapper::syncBlurBackgroundEffect() +{ + if (m_surfaceItem) + setBlurBackgroundEffect(m_surfaceItem->backgroundBlurEnabled()); +} + +bool SurfaceWrapper::coverEnabled() const +{ + return m_coverContent; +} + +void SurfaceWrapper::setCoverEnabled(bool coverEnabled) +{ + if (m_coverContent && !coverEnabled) { + m_coverContent->setVisible(false); + m_coverContent->deleteLater(); + m_coverContent = nullptr; + } else if (coverEnabled && !m_coverContent) { + m_coverContent = m_engine->createLaunchpadCover(this, m_ownsOutput, container()); + m_coverContent->setVisible(isVisible()); + } + + Q_EMIT coverEnabledChanged(); +} + +bool SurfaceWrapper::socketEnabled() const +{ + return m_socketEnabled; +} + +void SurfaceWrapper::updateSurfaceSizeRatio() +{ + if (m_type == Type::XWayland && m_surfaceItem && window()) { + // A destroyed wrapper can still be alive in the scene while its close + // animation runs, and a QPointer can already be nulled by the + // WToplevelSurface destructor. Neither is a programming error: there is + // no shell surface left to keep in sync, so skip the update instead of + // aborting the whole compositor. + if (!m_shellSurface || m_wrapperAboutToRemove) { + qCWarning(lcTlSurface) << "Skip surface size ratio update for destroyed surface," + << "aboutToRemove:" << m_wrapperAboutToRemove + << "proxy:" << m_isProxy << "type:" << int(m_type); + return; + } + const qreal targetScale = desktop() ? desktop()->outputs()->effectiveScale() + : window()->effectiveDevicePixelRatio(); + if (m_surfaceItem->bufferScale() < targetScale) + m_surfaceItem->setSurfaceSizeRatio(targetScale / m_surfaceItem->bufferScale()); + else + m_surfaceItem->setSurfaceSizeRatio(1.0); + } +} + +void SurfaceWrapper::setXwaylandPositionFromSurface(bool value) +{ + m_xwaylandPositionFromSurface = value; +} + +bool SurfaceWrapper::hasInitializeContainer() const +{ + return m_hasActiveCapability.testFlag(ActiveControlState::HasInitializeContainer); +} + +bool SurfaceWrapper::hasFocusCapability() const +{ + return m_focusControlStates == FocusControlState::Full; +} + +void SurfaceWrapper::setHasInitializeContainer(bool value) +{ + Q_ASSERT(!value || m_container != nullptr); + updateHasActiveCapability(ActiveControlState::HasInitializeContainer, value); + Q_EMIT hasInitializeContainerChanged(); + + if (m_prelaunchSplash && value) { + // Start open animation when container initialized + // m_prelaunchSplash can't get mapped signal + createNewOrClose(OPEN_ANIMATION); + } +} + +void SurfaceWrapper::disableWindowAnimation(bool disable) +{ + m_windowAnimationEnabled = !disable; +} + +WindowTransitionTarget *SurfaceWrapper::windowTransition() const +{ + return m_windowTransition.get(); +} + +void SurfaceWrapper::updateWindowTransitionAnimationSource() +{ + if (m_windowAnimation) + m_windowAnimation->setProperty("sourceSurface", + QVariant::fromValue(m_windowTransition->sourceSurface())); +} + +int SurfaceWrapper::effectiveStackingZ() const +{ + if (m_surfaceRole == SurfaceRole::Overlay) + return OVERLAYLAYER; + if (m_surfaceRole == SurfaceRole::PrivilegedOverlay) + return PRIVILEGEDOVERLAYLAYER; + if (m_explicitAlwaysOnTop) + return ALWAYSONTOPLAYER; + return m_explicitAlwaysOnBottom ? ALWAYSONBOTTOMLAYER : 0; +} + +void SurfaceWrapper::updateStackingLayer() +{ + int newExplicitAlwaysOnTop = alwaysOnTop(); + bool newExplicitAlwaysOnBottom = m_alwaysOnBottom; + if (m_parentSurface) { + newExplicitAlwaysOnTop += m_parentSurface->m_explicitAlwaysOnTop; + newExplicitAlwaysOnBottom = newExplicitAlwaysOnBottom + || m_parentSurface->m_explicitAlwaysOnBottom; + } + + if (newExplicitAlwaysOnTop) + newExplicitAlwaysOnBottom = false; + + if (m_explicitAlwaysOnTop == newExplicitAlwaysOnTop + && m_explicitAlwaysOnBottom == newExplicitAlwaysOnBottom) + return; + + m_explicitAlwaysOnTop = newExplicitAlwaysOnTop; + m_explicitAlwaysOnBottom = newExplicitAlwaysOnBottom; + setZ(effectiveStackingZ()); + for (const auto &sub : std::as_const(m_subSurfaces)) + sub->updateStackingLayer(); +} + +#ifndef DISABLE_XWAYLAND +void SurfaceWrapper::updateXWaylandStackingState() +{ + auto *xwaylandSurface = qobject_cast(m_shellSurface.data()); + if (!xwaylandSurface) + return; + + const bool above = xwaylandSurface->isAbove(); + const bool below = !above && xwaylandSurface->isBelow(); + setAlwaysOnBottom(below); + setAlwaysOnTop(above); + if (above) { + stackToLast(); + } else if (below) { + stackToFirst(); + } +} +#endif + +void SurfaceWrapper::updateSizeCapabilities() +{ + if (!m_shellSurface) { + return; + } + + const bool resizable = + !m_isSnapMask && m_shellSurface->hasCapability(WToplevelSurface::Capability::Resize); + const bool maximizable = + !m_isSnapMask && m_shellSurface->hasCapability(WToplevelSurface::Capability::Maximized); + + if (m_resizable != resizable) { + m_resizable = resizable; + Q_EMIT resizableChanged(); + } + + if (m_maximizable != maximizable) { + m_maximizable = maximizable; + Q_EMIT maximizableChanged(); + } +} + +void SurfaceWrapper::updateHasActiveCapability(ActiveControlState state, bool value) +{ + bool oldValue = hasActiveCapability(); + m_hasActiveCapability.setFlag(state, value); + if (oldValue != hasActiveCapability()) { + if (hasActiveCapability()) + Q_EMIT activationRequested(); + else + Q_EMIT inactivationRequested(); + } +} + +void SurfaceWrapper::updateActivateCapability() +{ + updateHasActiveCapability(ActiveControlState::HasActivateCapability, + m_shellSurface + && m_shellSurface->hasCapability(WToplevelSurface::Capability::Activate)); +} + +void SurfaceWrapper::updateFocusCapability() +{ + updateFocusControlState(FocusControlState::HasFocusCapability, + m_shellSurface && m_shellSurface->hasCapability(WToplevelSurface::Capability::Focus)); +} + +void SurfaceWrapper::updateFocusControlState(FocusControlState state, bool value) +{ + auto old = hasFocusCapability(); + m_focusControlStates.setFlag(state, value); + auto now = hasFocusCapability(); + if (old != now) { + if (m_surfaceItem) + m_surfaceItem->setFocusPolicy(now ? Qt::StrongFocus : Qt::NoFocus); + Q_EMIT hasFocusCapabilityChanged(); + } +} + +bool SurfaceWrapper::hasActiveCapability() const +{ + return m_hasActiveCapability == ActiveControlState::Full; +} + +bool SurfaceWrapper::hasCapability(WToplevelSurface::Capability cap) const +{ + // SplashScreen doesn't have a real shellSurface + if (m_type == Type::SplashScreen) { + if (cap == WToplevelSurface::Capability::Activate) + return true; + // Focus, Maximized, FullScreen, Resize + return false; + } + if (m_isSnapMask + && (cap == WToplevelSurface::Capability::Maximized + || cap == WToplevelSurface::Capability::Resize)) + return false; + return m_shellSurface && m_shellSurface->hasCapability(cap); +} + +bool SurfaceWrapper::skipSwitcher() const +{ + return m_skipSwitcher; +} + +void SurfaceWrapper::setSkipSwitcher(bool skip) +{ + if (m_skipSwitcher == skip) + return; + + m_skipSwitcher = skip; + Q_EMIT skipSwitcherChanged(); +} + +bool SurfaceWrapper::skipDockPreView() const +{ + return m_skipDockPreView; +} + +void SurfaceWrapper::setSkipDockPreView(bool skip) +{ + if (!skip && (m_type != Type::XdgToplevel && m_type != Type::XWayland)) { + qCWarning(lcTlSurface) << "Only XdgToplevel or XWayland surfaces are allowed to set " + "`skipDockPreView` to false."; + return; + } + + if (m_skipDockPreView == skip) + return; + + m_skipDockPreView = skip; + Q_EMIT skipDockPreViewChanged(); +} + +bool SurfaceWrapper::skipMutiTaskView() const +{ + return m_skipMutiTaskView; +} + +void SurfaceWrapper::setSkipMutiTaskView(bool skip) +{ + if (m_skipMutiTaskView == skip) + return; + + m_skipMutiTaskView = skip; + Q_EMIT skipMutiTaskViewChanged(); +} + +bool SurfaceWrapper::isDDEShellSurface() const +{ + return m_isDdeShellSurface; +} + +void SurfaceWrapper::setIsDDEShellSurface(bool value) +{ + if (m_isDdeShellSurface == value) + return; + + m_isDdeShellSurface = value; + Q_EMIT isDDEShellSurfaceChanged(); +} + +SurfaceWrapper::SurfaceRole SurfaceWrapper::surfaceRole() const +{ + return m_surfaceRole; +} + +void SurfaceWrapper::setSurfaceRole(SurfaceRole role) +{ + if (m_surfaceRole == role) + return; + + const bool wasAlwaysOnTop = alwaysOnTop(); + m_surfaceRole = role; + updateStackingLayer(); + + if (role == SurfaceRole::Overlay || role == SurfaceRole::PrivilegedOverlay) { + const int overlayZ = effectiveStackingZ(); + setZ(overlayZ); + for (const auto &sub : std::as_const(m_subSurfaces)) + sub->setZ(overlayZ); + } else if (role == SurfaceRole::Normal) { + setZ(effectiveStackingZ()); + for (const auto &sub : std::as_const(m_subSurfaces)) + sub->setZ(sub->effectiveStackingZ()); + } + + if (wasAlwaysOnTop != alwaysOnTop()) + Q_EMIT alwaysOnTopChanged(alwaysOnTop()); + Q_EMIT surfaceRoleChanged(); +} + +std::optional SurfaceWrapper::autoPlaceCursorOffset() const +{ + return m_autoPlaceCursorOffset; +} + +void SurfaceWrapper::setAutoPlaceCursorOffset(QPoint offset) +{ + if (m_autoPlaceCursorOffset == offset) + return; + + m_autoPlaceCursorOffset = offset; + // Cursor placement supersedes a stale fixed-position request; the two + // modes are mutually exclusive and the later request wins. + m_clientRequstPos.reset(); + setPositionAutomatic(false); +} + +std::optional SurfaceWrapper::clientRequstPos() const +{ + return m_clientRequstPos; +} + +void SurfaceWrapper::setClientRequstPos(QPoint pos) +{ + if (m_clientRequstPos == pos) + return; + + m_clientRequstPos = pos; + // A fixed position supersedes cursor placement; the two modes are mutually + // exclusive and the later request wins. + m_autoPlaceCursorOffset.reset(); + // An explicit position request (including 0,0) always pins the surface. + setPositionAutomatic(false); +} + +QPointF SurfaceWrapper::alignToPixelGrid(const QPointF &pos) const +{ + qreal devicePixelRatio = getOutputDevicePixelRatio(pos); + qreal alignedX = std::round(pos.x() * devicePixelRatio) / devicePixelRatio; + qreal alignedY = std::round(pos.y() * devicePixelRatio) / devicePixelRatio; + return QPointF(alignedX, alignedY); +} + +QRectF SurfaceWrapper::alignGeometryToPixelGrid(const QRectF &geometry) const +{ + qreal devicePixelRatio = getOutputDevicePixelRatio(geometry.center()); + qreal alignedX = std::round(geometry.x() * devicePixelRatio) / devicePixelRatio; + qreal alignedY = std::round(geometry.y() * devicePixelRatio) / devicePixelRatio; + qreal alignedWidth = std::round(geometry.width() * devicePixelRatio) / devicePixelRatio; + qreal alignedHeight = std::round(geometry.height() * devicePixelRatio) / devicePixelRatio; + + QRectF result(alignedX, alignedY, alignedWidth, alignedHeight); + return result; +} + +qreal SurfaceWrapper::getOutputDevicePixelRatio(const QPointF &pos) const +{ + if (desktop()) + return desktop()->outputs()->scaleAt(pos); + if (surface() && !surface()->outputs().isEmpty()) { + const auto &outputs = surface()->outputs(); + + if (outputs.size() == 1) { + return outputs.first()->scale(); + } + + for (auto woutput : outputs) { + if (woutput && woutput->isEnabled()) { + QRectF outputGeometry(woutput->position(), woutput->size()); + if (outputGeometry.contains(pos)) { + return woutput->scale(); + } + } + } + } + + return window() ? window()->effectiveDevicePixelRatio() : 1.0; +} diff --git a/src/surface/surfacewrapper.h b/src/surface/surfacewrapper.h new file mode 100644 index 0000000000..a3294414f7 --- /dev/null +++ b/src/surface/surfacewrapper.h @@ -0,0 +1,744 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "framegeometry.h" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +Q_MOC_INCLUDE() +Q_MOC_INCLUDE() + +WAYLIB_SERVER_USE_NAMESPACE + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WSeat; +class WSocket; +WAYLIB_SERVER_END_NAMESPACE + +class QmlEngine; +class Output; +class Session; +class DesktopEnvironment; +Q_MOC_INCLUDE("desktop/desktopenvironment.h") +Q_MOC_INCLUDE("session/session.h") + +class SurfaceContainer; +class SurfaceWindowTransition; +class WindowTransitionTarget; +class SurfaceWrapper : public QQuickItem +{ + friend class WaylandServer; + friend class FocusController; + friend class ShowDesktop; + friend class SurfaceProtocolController; + friend class SurfaceContainer; + friend class SurfaceProxy; + friend class ShellHandler; + friend class SessionPrelaunch; + friend class SessionScene; + friend class LockScreen; + friend class SurfaceWindowTransition; + Q_OBJECT + QML_ELEMENT + QML_UNCREATABLE("SurfaceWrapper objects are created by c++") + Q_PROPERTY(Type type READ type NOTIFY typeChanged) + Q_PROPERTY(bool renderingEnabled READ renderingEnabled NOTIFY renderingEnabledChanged FINAL) + Q_PROPERTY(QString appId READ appId NOTIFY appIdChanged) + // make to read only + Q_PROPERTY(qreal implicitWidth READ implicitWidth NOTIFY implicitWidthChanged FINAL) + Q_PROPERTY(qreal implicitHeight READ implicitHeight NOTIFY implicitHeightChanged FINAL) + Q_PROPERTY(WAYLIB_SERVER_NAMESPACE::WSurface* surface READ surface CONSTANT) + Q_PROPERTY(WAYLIB_SERVER_NAMESPACE::WToplevelSurface* shellSurface READ shellSurface CONSTANT) + Q_PROPERTY(WAYLIB_SERVER_NAMESPACE::WSurfaceItem* surfaceItem READ surfaceItem NOTIFY surfaceItemCreated) + Q_PROPERTY(QQuickItem* prelaunchSplash READ prelaunchSplash NOTIFY prelaunchSplashChanged) + // AM-provided app icon, kept alive for the whole window lifetime. + Q_PROPERTY(QVariant appIcon READ appIcon CONSTANT) + Q_PROPERTY(QRectF boundingRect READ boundingRect NOTIFY boundingRectChanged) + Q_PROPERTY(QRectF geometry READ geometry NOTIFY geometryChanged FINAL) + Q_PROPERTY(QRectF normalGeometry READ normalGeometry NOTIFY normalGeometryChanged FINAL) + Q_PROPERTY(QRectF maximizedGeometry READ maximizedGeometry NOTIFY maximizedGeometryChanged FINAL) + Q_PROPERTY(QRectF fullscreenGeometry READ fullscreenGeometry NOTIFY fullscreenGeometryChanged FINAL) + Q_PROPERTY(QRectF tilingGeometry READ tilingGeometry NOTIFY tilingGeometryChanged FINAL) + Q_PROPERTY(Output* ownsOutput READ ownsOutput NOTIFY ownsOutputChanged FINAL) + Q_PROPERTY(bool positionAutomatic READ positionAutomatic NOTIFY positionAutomaticChanged FINAL) + Q_PROPERTY(State previousSurfaceState READ previousSurfaceState NOTIFY previousSurfaceStateChanged FINAL) + Q_PROPERTY(State surfaceState READ surfaceState NOTIFY surfaceStateChanged BINDABLE bindableSurfaceState FINAL) + Q_PROPERTY(qreal radius READ radius NOTIFY radiusChanged FINAL) + Q_PROPERTY(FrameGeometry frameGeometry READ frameGeometry NOTIFY frameGeometryChanged FINAL) + Q_PROPERTY(FrameGeometry presentationFrameGeometry READ presentationFrameGeometry NOTIFY presentationFrameGeometryChanged FINAL) + Q_PROPERTY(QQuickItem* frameItem READ frameItem NOTIFY frameGeometryChanged FINAL) + Q_PROPERTY(qreal shadowBlurRadius READ shadowBlurRadius NOTIFY shadowChanged FINAL) + Q_PROPERTY(qreal shadowOffsetX READ shadowOffsetX NOTIFY shadowChanged FINAL) + Q_PROPERTY(qreal shadowOffsetY READ shadowOffsetY NOTIFY shadowChanged FINAL) + Q_PROPERTY(QColor shadowColor READ shadowColor NOTIFY shadowChanged FINAL) + Q_PROPERTY(bool shadowVisible READ shadowVisible NOTIFY shadowChanged FINAL) + Q_PROPERTY(qreal borderWidth READ borderWidth NOTIFY borderChanged FINAL) + Q_PROPERTY(QColor borderColor READ borderColor NOTIFY borderChanged FINAL) + Q_PROPERTY(bool borderVisible READ borderVisible NOTIFY borderChanged FINAL) + Q_PROPERTY(DesktopEnvironment *desktop READ desktop CONSTANT FINAL) + Q_PROPERTY(SurfaceContainer* container READ container NOTIFY containerChanged FINAL) + Q_PROPERTY(QQuickItem* titleBar READ titleBar NOTIFY noTitleBarChanged FINAL) + Q_PROPERTY(QQuickItem* decoration READ decoration NOTIFY noDecorationChanged FINAL) + Q_PROPERTY(bool visibleDecoration READ visibleDecoration NOTIFY visibleDecorationChanged FINAL) + Q_PROPERTY(bool clipInOutput READ clipInOutput NOTIFY clipInOutputChanged FINAL) + Q_PROPERTY(bool noTitleBar READ noTitleBar NOTIFY noTitleBarChanged FINAL) + Q_PROPERTY(bool noCornerRadius READ noCornerRadius NOTIFY noCornerRadiusChanged FINAL) + Q_PROPERTY(int workspaceId READ workspaceId NOTIFY workspaceIdChanged FINAL) + Q_PROPERTY(bool alwaysOnTop READ alwaysOnTop WRITE setAlwaysOnTop NOTIFY alwaysOnTopChanged FINAL) + Q_PROPERTY(bool showOnAllWorkspace READ showOnAllWorkspace NOTIFY showOnAllWorkspaceChanged FINAL) + Q_PROPERTY(bool skipSwitcher READ skipSwitcher NOTIFY skipSwitcherChanged FINAL) + Q_PROPERTY(bool skipDockPreView READ skipDockPreView NOTIFY skipDockPreViewChanged FINAL) + Q_PROPERTY(bool skipMutiTaskView READ skipMutiTaskView NOTIFY skipMutiTaskViewChanged FINAL) + Q_PROPERTY(bool isDDEShellSurface READ isDDEShellSurface NOTIFY isDDEShellSurfaceChanged FINAL) + Q_PROPERTY(SurfaceWrapper::SurfaceRole surfaceRole READ surfaceRole NOTIFY surfaceRoleChanged FINAL) + Q_PROPERTY(bool blur READ blur NOTIFY blurChanged FINAL) + Q_PROPERTY(bool isWindowAnimationRunning READ isWindowAnimationRunning NOTIFY windowAnimationRunningChanged FINAL) + Q_PROPERTY(bool coverEnabled READ coverEnabled NOTIFY coverEnabledChanged FINAL) + Q_PROPERTY(bool acceptKeyboardFocus READ acceptKeyboardFocus FINAL) + Q_PROPERTY(bool isActivated READ isActivated NOTIFY isActivatedChanged FINAL) + Q_PROPERTY(bool isIMCandidatePanel READ isIMCandidatePanel NOTIFY isIMCandidatePanelChanged FINAL) + Q_PROPERTY(bool isSnapMask READ isSnapMask NOTIFY snapMaskChanged FINAL) + Q_PROPERTY(bool isResizable READ isResizable NOTIFY resizableChanged FINAL) + Q_PROPERTY(bool isMaximizable READ isMaximizable NOTIFY maximizableChanged FINAL) + Q_PROPERTY(bool modal READ modal NOTIFY modalChanged FINAL) + Q_PROPERTY(bool minimized READ isMinimized NOTIFY minimizedChanged FINAL) + +public: + enum class Type + { + XdgToplevel, + XdgPopup, + XWayland, + Layer, + InputPopup, + LockScreen, + SplashScreen, // Used for pre-launch splash screen + }; + Q_ENUM(Type) + + enum class State + { + Normal, + Maximized, + Fullscreen, + Tiling, + }; + Q_ENUM(State) + + // Quick-tile direction; None means "no tiling" (i.e. Normal state). + enum class TileMode + { + None, + Left, + Right, + Maximize, + TopLeft, + TopRight, + BottomLeft, + BottomRight, + }; + Q_ENUM(TileMode) + + enum class ActiveControlState : quint16 + { + MappedOrSplash = 1 << 0, + UnMinimized = 1 << 1, + HasInitializeContainer = 1 << 2, // when not in Container, we can't stackToLast + HasActivateCapability = 1 << 3, // shellSurface supports Activate capability + Full = ((1 << 4) - 1), + }; + Q_ENUM(ActiveControlState); + Q_DECLARE_FLAGS(ActiveControlStates, ActiveControlState) + + enum class FocusControlState : quint16 + { + Mapped = 1 << 0, + UnMinimized = 1 << 1, + AcceptKeyboardFocus = 1 << 2, // set by treeland-dde-shell + HasFocusCapability = 1 << 3, // shellSurface supports Focus capability + Full = ((1 << 4) - 1), + }; + Q_ENUM(FocusControlState); + Q_DECLARE_FLAGS(FocusControlStates, FocusControlState) + + enum class SurfaceRole + { + Normal = 0, + Overlay = 1, + AlwaysOnTop = 2, + PrivilegedOverlay, // Privileged overlay, exempt from lock-screen hiding + }; + Q_ENUM(SurfaceRole) + + explicit SurfaceWrapper(QmlEngine *qmlEngine, + WToplevelSurface *shellSurface, + Type type, + const QString &appId = QString(), + QQuickItem *parent = nullptr); + + // For proxy surface + explicit SurfaceWrapper(SurfaceWrapper *original, QQuickItem *parent = nullptr); + + // Constructor for pre-launch splash; allows passing an initial window size to stabilize UI + // early + explicit SurfaceWrapper(QmlEngine *qmlEngine, + QQuickItem *parent, + const QSize &initialSize, + const QString &appId, + wlr_buffer *iconBuffer = nullptr, + const QColor &backgroundColor = QColor("#ffffff")); + + void setFocus(bool focus, Qt::FocusReason reason); + + WSurface *surface() const; + WToplevelSurface *shellSurface() const; + WSurfaceItem *surfaceItem() const; + QQuickItem *prelaunchSplash() const; + QVariant appIcon() const; + QString appId() const; + bool resize(const QSizeF &size, bool tryExec = false); + void close(); + + QRectF titlebarGeometry() const; + QRectF boundingRect() const override; + + Type type() const; + SurfaceWrapper *parentSurface() const; + + Output *ownsOutput() const; + void setOwnsOutput(Output *newOwnsOutput); + // `recordDiagnostics` is set by RootSurfaceContainer::updateSurfaceOutputs() + // only: a layer container re-homes its surface straight through this call and + // the prelaunch splash path applies its outputs through it too, and neither + // leave must be reported as an output recompute. + void setOutputs(const QList &outputs, bool recordDiagnostics = false); + const QList &outputs() const; + + // Why this window is on no output at all, exposed by treeland-debug: the + // last leave caused by a RootSurfaceContainer output recompute, and the last + // RootSurfaceContainer::updateSurfaceOutputs() call that rebuilt the list. + // A bool has no "never happened" value: read lastLeaveOutput / + // updateReason Unknown as "nothing recorded yet" and ignore the rest. + enum class OutputsUpdateReason { + Unknown, + GeometryChanged, + SurfaceAdded, + AddOutput, + EnabledChanged, + }; + struct OutputsDiagnostics + { + QString lastLeaveOutput; + bool lastLeaveOutputEnabled = false; + bool lastLeaveEmptiedOutputs = false; + OutputsUpdateReason updateReason = OutputsUpdateReason::Unknown; + int updateEnabledOutputs = -1; + int updateTotalOutputs = -1; + int updateComputedOutputs = -1; + bool updateAutomatic = false; + }; + void noteOutputsUpdate(OutputsUpdateReason reason, + int enabledOutputs, + int totalOutputs, + int computedOutputs); + const OutputsDiagnostics &outputsDiagnostics() const { return m_outputsDiagnostics; } + + QRectF geometry() const; + QRectF normalGeometry() const; + void moveNormalGeometryInOutput(const QPointF &position); + QPointF alignToPixelGrid(const QPointF &pos) const; + + // Maps a point from this surface's buffer/surface-local coordinate space to + // the wrapper's coordinate space: applies the surface item's position within + // the wrapper plus the item's content offset (window geometry + paddings). + QPointF mapFromSurface(const QPointF &surfacePoint) const; + QRectF alignGeometryToPixelGrid(const QRectF &geometry) const; + qreal getOutputDevicePixelRatio(const QPointF &pos) const; + + QRectF maximizedGeometry() const; + void setMaximizedGeometry(const QRectF &newMaximizedGeometry); + + QRectF fullscreenGeometry() const; + void setFullscreenGeometry(const QRectF &newFullscreenGeometry); + + QRectF tilingGeometry() const; + void setTilingGeometry(const QRectF &newTilingGeometry); + + bool positionAutomatic() const; + void setPositionAutomatic(bool newPositionAutomatic); + + void resetWidth(); + void resetHeight(); + + State previousSurfaceState() const; + State surfaceState() const; + void setSurfaceState(State newSurfaceState); + void setSurfaceStateDirectly(State newSurfaceState); + QBindable bindableSurfaceState(); + bool isNormal() const; + bool isMaximized() const; + bool isMinimized() const; + bool isTiling() const; + bool isAnimationRunning() const; + bool isWindowAnimationRunning() const; + + bool supportsTileMode(TileMode mode) const; + void applyTileMode(TileMode mode, Output *output); + // Instantly restore `this` to Normal + void cancelTileMode(); + + qreal radius() const; + FrameGeometry frameGeometry() const { return m_frameGeometry; } + FrameGeometry presentationFrameGeometry() const + { + return m_prelaunchFrameGeometry.value_or(m_frameGeometry); + } + QQuickItem *frameItem() const { return m_frameItem; } + void setRadius(qreal newRadius); + + // Per-window SSD customization (treeland-decoration-unstable-v1). + // Values equal to the compositor defaults (set by WaylandServer when no + // per-window override is active) so the rendering picks them up via + // Decoration.qml without extra conditionals. + qreal shadowBlurRadius() const; + qreal shadowOffsetX() const; + qreal shadowOffsetY() const; + QColor shadowColor() const; + bool shadowVisible() const; + void setShadowValues(qreal blur, qreal offsetX, qreal offsetY, const QColor &color); + void setShadowVisible(bool visible); + + qreal borderWidth() const; + QColor borderColor() const; + bool borderVisible() const; + void setBorderValues(qreal width, const QColor &color); + void setBorderVisible(bool visible); + + bool renderingEnabled() const; + Session *session() const; + DesktopEnvironment *desktop() const; + void setSession(Session *session); + SurfaceContainer *container() const; + + void addSubSurface(SurfaceWrapper *surface); + void removeSubSurface(SurfaceWrapper *surface); + const QList &subSurfaces() const; + SurfaceWrapper *stackFirstSurface() const; + SurfaceWrapper *stackLastSurface() const; + bool hasChild(SurfaceWrapper *child) const; + + QQuickItem *titleBar() const; + QQuickItem *decoration() const; + + bool noDecoration() const; + bool visibleDecoration() const; + void setNoDecoration(bool newNoDecoration); + + bool clipInOutput() const; + void setClipInOutput(bool newClipInOutput); + QRectF clipRect() const override; + + bool noTitleBar() const; + void setNoTitleBar(bool newNoTitleBar); + + bool noCornerRadius() const; + void setNoCornerRadius(bool newNoCornerRadius); + + QRect iconGeometry() const; + void setIconGeometry(QRect newIconGeometry); + + int workspaceId() const; + void setWorkspaceId(int newWorkspaceId); + void setHideByWorkspace(bool hide); + + bool alwaysOnTop() const; + bool effectiveAlwaysOnTop() const; + void setAlwaysOnTop(bool alwaysOnTop); + void setAlwaysOnBottom(bool alwaysOnBottom); + + bool showOnAllWorkspace() const; + bool showOnWorkspace(int workspaceIndex) const; + + // Keep this policy on SurfaceWrapper so future window rules can override it + // without pushing policy into waylib or QML. + bool isResizable() const; + bool isMaximizable() const; + bool modal() const; + SurfaceWrapper *findModal() const; + + bool hasActiveCapability() const; + bool hasFocusCapability() const; + bool hasCapability(WToplevelSurface::Capability cap) const; + + bool skipSwitcher() const; + bool skipDockPreView() const; + bool skipMutiTaskView() const; + + bool isDDEShellSurface() const; + void setIsDDEShellSurface(bool value); + + enum SurfaceRole surfaceRole() const; + void setSurfaceRole(enum SurfaceRole role); + + std::optional autoPlaceCursorOffset() const; + void setAutoPlaceCursorOffset(QPoint offset); + + std::optional clientRequstPos() const; + void setClientRequstPos(QPoint pos); + + bool blur() const; + // Personalization-driven blur (deprecated treeland-personalization-manager-v1 path). + void setBlurPersonalization(bool blur); + // ext-background-effect-v1 blur. Either source alone enables blur(). + void setBlurBackgroundEffect(bool blur); + + bool coverEnabled() const; + void setCoverEnabled(bool enabled); + + bool socketEnabled() const; + void setXwaylandPositionFromSurface(bool value); + + bool hasInitializeContainer() const; + void setHasInitializeContainer(bool value); + void disableWindowAnimation(bool disable = true); + WindowTransitionTarget *windowTransition() const; + void setHideByShowDesk(bool show); + void setHideByLockScreen(bool hide); + + void destroy(); + bool isAboutToRemove() const; + + bool acceptKeyboardFocus() const; // set by treeland-dde-shell + void setAcceptKeyboardFocus(bool accept); + + bool isActivated() const; + bool isIMCandidatePanel() const; + void setIMCandidatePanel(bool isIMCandidatePanel); + bool isSnapMask() const; + void setSnapMask(bool snapMask); + bool isInputPopupLike() const; + + static constexpr QLatin1StringView DesktopScope{"dde-shell/desktop"}; + static constexpr QLatin1StringView LaunchpadScope{"dde-shell/launchpad"}; + static constexpr QLatin1StringView QuickLaunchpadScope{"dde-shell/quick-launchpad"}; + // Scope of a Type::Layer wrapper, or an empty string when the wrapper is not a + // layer surface + QString layerScope() const; + bool isLaunchpad() const; + bool isQuickLaunchpad() const; + bool isDesktop() const; + + bool attention() const; + bool setAttention(bool attention); + + void setPendingActivation(WSeat *seat); + bool takePendingActivation(WSeat *&seat); + +public Q_SLOTS: + void minimize(bool onAnimation = true); + void restoreFromMinimized(bool onAnimation = true); + void maximize(); + void unmaximize(); + void toggleMaximized(); + void enterFullscreen(WOutput *targetOutput = nullptr); + void leaveFullscreen(); + void closeSurface(); + void onMappedChanged(); + void onSocketEnabledChanged(); + + bool stackBefore(QQuickItem *item); + bool stackAfter(QQuickItem *item); + void stackToLast(); + void stackToFirst(); + + void updateSurfaceSizeRatio(); + +Q_SIGNALS: + void hasInitializeContainerChanged(); + void boundingRectChanged(); + void ownsOutputChanged(); + void appIdChanged(); + void normalGeometryChanged(); + void maximizedGeometryChanged(); + void fullscreenGeometryChanged(); + void tilingGeometryChanged(); + void positionAutomaticChanged(); + void previousSurfaceStateChanged(); + void surfaceStateChanged(); + void minimizedChanged(); + void radiusChanged(); + void frameGeometryChanged(); + void presentationFrameGeometryChanged(); + void shadowChanged(); + void borderChanged(); + void moveRequested(); + void resizeRequested(Qt::Edges edges, bool overrideCursor); + void windowMenuRequested(QPointF pos); + void geometryChanged(); + void containerChanged(); + void visibleDecorationChanged(); + void clipInOutputChanged(); + void noDecorationChanged(); + void noTitleBarChanged(); + void noCornerRadiusChanged(); + void iconGeometryChanged(); + void workspaceIdChanged(); + void alwaysOnTopChanged(bool alwaysOnTop); + void showOnAllWorkspaceChanged(); + void activationRequested(); + void inactivationRequested(); + void splashCloseRequested(); + void skipSwitcherChanged(); + void skipDockPreViewChanged(); + void skipMutiTaskViewChanged(); + void isDDEShellSurfaceChanged(); + void surfaceRoleChanged(); + void blurChanged(); + void windowAnimationRunningChanged(); + void coverEnabledChanged(); + void aboutToBeInvalidated(); + void isActivatedChanged(); + void isIMCandidatePanelChanged(); + void snapMaskChanged(); + void resizableChanged(); + void maximizableChanged(); + void modalChanged(); + void attentionChanged(); + void surfaceItemCreated(); // Emitted once after surfaceItem is constructed + void hasFocusCapabilityChanged(); + void prelaunchSplashChanged(); + void typeChanged(); + void renderingEnabledChanged(); + +private: + ~SurfaceWrapper() override; + using QObject::deleteLater; + using QQuickItem::setParentItem; + using QQuickItem::setVisible; + using QQuickItem::stackAfter; + using QQuickItem::stackBefore; + void setParent(QQuickItem *item); + void setActivate(bool activate); + void updateActiveState(); + void setNormalGeometry(const QRectF &newNormalGeometry); + void updateTitleBar(); + void syncTitleBarPadding(); + void updateDecoration(); + void initializeFrameGeometry(); + void updateRadiusConfig(); + void updateFrameGeometry(); + void setBoundedRect(const QRectF &newBoundedRect); + void setContainer(SurfaceContainer *newContainer); + void setVisibleDecoration(bool newVisibleDecoration); + + void invalidate(); + void setup(); // Initialize m_surfaceItem related features + void syncBlurBackgroundEffect(); + void convertToNormalSurface(WToplevelSurface *shellSurface, + Type type); // Transition from pre-launch mode to normal mode + void updateBoundingRect(); + void updateVisible(); + void setRenderingEnabled(bool enabled); + void syncRenderingState(); + void suspendAnimations(); + void retireAnimation(QPointer &animation); + void bindVisibilitySocket(WAYLIB_SERVER_NAMESPACE::WSocket *socket); + void updateSubSurfaceStacking(); + void restackWindowAnimationAbove(); + void ensureAboveParent(); + void updateClipRect(); + void geometryChange(const QRectF &newGeo, const QRectF &oldGeometry) override; + void createNewOrClose(uint direction); + void beginWindowTransition(int direction, const QRectF &fromGeometry, const QRectF &toGeometry); + void updateWindowTransitionAnimationSource(); + void startWindowTransition(); + void finishWindowTransitionOpen(); + void startWindowCloseTransition(); + void tryFlushPendingActivation(); + void itemChange(ItemChange change, const ItemChangeData &data) override; + + QRectF targetGeometryForState(State state) const; + bool applyGeometry(const QRectF &targetGeometry); + bool applySurfaceState(); + bool checkSetSurfaceState(State newSurfaceState, bool allowRetarget = false); + bool shouldUpdateNormalGeometry() const; + void abortGeometryAnimation(); + void resetXdgToplevelSize(); + void setSurfaceStateValue(State newSurfaceState); + void applyShellSurfaceState(); + Q_SLOT void onAnimationReady(); + Q_SLOT void onAnimationFinished(); + void syncPrelaunchMappedState(); + void startPrelaunchSplashHideSequence(); + Q_SLOT void onPrelaunchGeometryAnimationReady(); + Q_SLOT void onPrelaunchGeometryAnimationFinished(); + bool startStateChangeAnimation(const QRectF &targetGeometry); + void onWindowAnimationFinished(); + Q_SLOT void onShowAnimationFinished(); + Q_SLOT void onHideAnimationFinished(); + int effectiveStackingZ() const; + void updateStackingLayer(); +#ifndef DISABLE_XWAYLAND + void updateXWaylandStackingState(); +#endif + void updateSizeCapabilities(); + void setModal(bool modal); + void startMinimizeAnimation(const QRectF &iconGeometry, uint direction); + Q_SLOT void onMinimizeAnimationFinished(); + void startShowDesktopAnimation(bool show); + Q_SLOT void onShowDesktopAnimationFinished(); + + // Per-effect animation switches. Each animated effect reads its own + // AnimationConfig key so products can combine them freely. + bool windowAnimationEnabled(uint direction) const; + bool geometryAnimationEnabled(State state) const; + void updateHasActiveCapability(ActiveControlState state, bool value); + void updateFocusControlState(FocusControlState state, bool value); + void updateActivateCapability(); + void updateFocusCapability(); + void completeSplashTransition(const QSizeF &targetImplicitSize, bool hideDecoration = false); + + // wayland set by treeland-dde-shell, x11 set by bypassManager/windowTypes + void setSkipDockPreView(bool skip); + void setSkipSwitcher(bool skip); + void setSkipMutiTaskView(bool skip); + + QmlEngine *m_engine; + QPointer m_session; + QPointer m_visibilitySocket; + QPointer m_container; + QList m_subSurfaces; + SurfaceWrapper *m_parentSurface = nullptr; + + QPointer m_shellSurface; + WSurfaceItem *m_surfaceItem = nullptr; + QPointer m_frameItem; + FrameGeometry m_frameGeometry; + std::optional m_prelaunchFrameGeometry; + QMetaObject::Connection m_radiusConfigConnection; + QPointer m_titleBar; + QPointer m_decoration; + QPointer m_geometryAnimation; + QPointer m_coverContent; + QPointer m_prelaunchSplash; // Pre-launch splash item + QList m_prelaunchOutputs; // Outputs for pre-launch splash + OutputsDiagnostics m_outputsDiagnostics; + QRectF m_boundedRect; + QRectF m_normalGeometry; + QRectF m_maximizedGeometry; + QRectF m_fullscreenGeometry; + QRectF m_tilingGeometry; + Type m_type; + QPointer m_ownsOutput; + QPointF m_positionInOwnsOutput; + // State already propagated to m_shellSurface. It lags m_surfaceState while a + // geometry animation is in flight: the shell surface is only notified at the + // animation's first frame, so the two are intentionally allowed to differ. + State m_appliedSurfaceState = State::Normal; + QPointer m_windowAnimation; + QPointer m_minimizeAnimation; + QPointer m_showDesktopAnimation; + QMetaObject::Connection m_xdgToplevelCommitConnection; + Q_OBJECT_BINDABLE_PROPERTY_WITH_ARGS(SurfaceWrapper, + SurfaceWrapper::State, + m_previousSurfaceState, + State::Normal, + &SurfaceWrapper::previousSurfaceStateChanged) + Q_OBJECT_BINDABLE_PROPERTY_WITH_ARGS(SurfaceWrapper, + SurfaceWrapper::State, + m_surfaceState, + State::Normal, + &SurfaceWrapper::surfaceStateChanged) + Q_OBJECT_BINDABLE_PROPERTY_WITH_ARGS(SurfaceWrapper, + bool, + m_minimized, + false, + &SurfaceWrapper::minimizedChanged) + int m_workspaceId = -1; + int m_explicitAlwaysOnTop = 0; + bool m_explicitAlwaysOnBottom = false; + // Negative = no per-window radius override, fall back to DConfig; any + // non-negative value is applied as sent (0 = square corners). + qreal m_radius = -1.0; + // Per-window SSD customization state (treeland-decoration-unstable-v1). + // Defaults mirror Decoration.qml (XdgShadow / Border) rendering so that + // windows without a decoration context look unchanged. + qreal m_shadowBlurRadius = 40.0; + qreal m_shadowOffsetX = 0.0; + qreal m_shadowOffsetY = 10.0; + QColor m_shadowColor = QColor(0, 0, 0, 102); // rgba(0,0,0,0.4) + bool m_shadowVisible = true; + qreal m_borderWidth = 1.0; + QColor m_borderColor = QColor(0, 0, 0, 26); // rgba(0,0,0,0.1) + bool m_borderVisible = true; + QRect m_iconGeometry; + ActiveControlStates m_hasActiveCapability = + ActiveControlStates(ActiveControlState::UnMinimized); + FocusControlStates m_focusControlStates = + FocusControlStates(FocusControlState::AcceptKeyboardFocus) + | FocusControlStates(FocusControlState::UnMinimized); + + uint m_positionAutomatic : 1; + uint m_visibleDecoration : 1; + uint m_clipInOutput : 1; + uint m_noDecoration : 1; + uint m_noTitleBar : 1; + uint m_noCornerRadius : 1; + uint m_alwaysOnBottom : 1; + uint m_skipSwitcher : 1; + uint m_skipDockPreView : 1; + uint m_skipMutiTaskView : 1; + uint m_isDdeShellSurface : 1; + uint m_xwaylandPositionFromSurface : 1; + uint m_wrapperAboutToRemove : 1; + uint m_isProxy : 1; + uint m_hideByWorkspace : 1; + uint m_hideByshowDesk : 1; + uint m_hideByLockScreen : 1; + uint m_confirmHideByLockScreen : 1; + uint m_blurPersonalization : 1; + uint m_blurBackgroundEffect : 1; + uint m_isActivated : 1; + uint m_attention : 1; + uint m_isIMCandidatePanel : 1; + uint m_isSnapMask : 1; + uint m_resizable : 1; + uint m_maximizable : 1; + uint m_modal : 1; + uint m_pendingActivation : 1 = 0; // activation requested before the surface mapped + uint m_windowTransitionPending : 1 = 0; + + SurfaceRole m_surfaceRole = SurfaceRole::Normal; + std::optional m_autoPlaceCursorOffset; + std::optional m_clientRequstPos; + + bool m_socketEnabled{ false }; + bool m_renderingEnabled{ false }; + bool m_sessionVisibilityChanging{ false }; + bool m_liveSuppressed{ false }; + bool m_windowAnimationEnabled{ true }; + + QPointer m_pendingActivationSeat; + std::unique_ptr m_windowTransition; + const QString m_appId; + // App icon buffer from the prelaunch splash request, owned (locked) by this wrapper. + WAYLIB_SERVER_NAMESPACE::WBufferUnlockPtr m_appIcon; +}; + +Q_DECLARE_OPERATORS_FOR_FLAGS(SurfaceWrapper::ActiveControlStates) +Q_DECLARE_OPERATORS_FOR_FLAGS(SurfaceWrapper::FocusControlStates) diff --git a/src/systemd-socket.cpp b/src/systemd-socket.cpp new file mode 100644 index 0000000000..bcc89d84d4 --- /dev/null +++ b/src/systemd-socket.cpp @@ -0,0 +1,400 @@ +// Copyright (C) 2023-2026 Dingyuan Zhang . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +Q_DECLARE_LOGGING_CATEGORY(lcSdSocket) +Q_LOGGING_CATEGORY(lcSdSocket, "treeland.systemd.socket") + +typedef QMap StringMap; +Q_DECLARE_METATYPE(StringMap) + +class SocketActivator : public QObject +{ + Q_OBJECT +public: + SocketActivator(QDBusUnixFileDescriptor unixFileDescriptor, + QString type, + QObject *parent = nullptr) + : QObject(parent) + , m_unixFileDescriptor(std::make_shared(std::move(unixFileDescriptor))) + , m_type(std::move(type)) + , m_started(false) { + } + + bool tryStart(const QDBusConnection &connection) { + watchService(connection); + + QDBusInterface test("org.deepin.Compositor1", + "/org/deepin/Compositor1", + "org.deepin.Compositor1", + connection); + if (!test.isValid()) + return false; + + return connectActivationSignal(connection); + } + + void start() { + if (tryStart(QDBusConnection::sessionBus()) || tryStart(QDBusConnection::systemBus())) { + m_started = true; + clearPendingRetry(StartRetry); + activate(); + return; + } + scheduleStartRetry(); + } + +public Q_SLOTS: + void activate() { + if (!m_started) + return; + + if (!m_compositorBus.has_value()) + return; + + auto connection = dbusConnection(*m_compositorBus); + + QDBusInterface updateFd("org.deepin.Compositor1", + "/org/deepin/Compositor1", + "org.deepin.Compositor1", + connection); + + if (updateFd.isValid()) { + if (m_type == "wayland") { + if (!callDBus(updateFd, + QStringLiteral("ActivateWayland"), + QStringLiteral("Failed to activate Wayland socket"), + QVariant::fromValue(*m_unixFileDescriptor))) { + return; + } + + QDBusInterface dbus("org.freedesktop.DBus", + "/org/freedesktop/DBus", + "org.freedesktop.DBus", + QDBusConnection::sessionBus()); + StringMap env; + env["WAYLAND_DISPLAY"] = "treeland.socket"; + + const auto extraEnvs = qgetenv("TREELAND_SESSION_ENVIRONMENTS"); + if (!extraEnvs.isEmpty()) { + const auto envs = extraEnvs.split('\n'); + for (const auto &i : envs) { + const auto pair = i.split('='); + if (pair.size() == 2) { + env[QString::fromLocal8Bit(pair[0])] = QString::fromLocal8Bit(pair[1]); + } + } + } + + if (!callDBus(dbus, + QStringLiteral("UpdateActivationEnvironment"), + QStringLiteral("Failed to update Wayland activation environment"), + QVariant::fromValue(env))) { + return; + } + + sd_notify(0, "READY=1"); + } else if (m_type == "xwayland") { + QDBusMessage reply = updateFd.call("XWaylandName"); + if (reply.type() == QDBusMessage::ReplyMessage) { + QVariantList values = reply.arguments(); + if (values.size() < 2) { + qCWarning(lcSdSocket) << "Invalid XWaylandName reply"; + scheduleActivateRetry(); + return; + } + QString xwaylandName = values.at(0).toString(); + QByteArray auth = values.at(1).toByteArray(); + + if (m_lastXwaylandAuth == auth) { + sd_notify(0, "READY=1"); + clearPendingRetry(ActivateRetry); + return; + } + + const QString authFileName = xauthorityFileName(); + if (!writeXAuthority(authFileName, auth)) { + scheduleActivateRetry(); + return; + } + + QDBusInterface dbus("org.freedesktop.DBus", + "/org/freedesktop/DBus", + "org.freedesktop.DBus", + QDBusConnection::sessionBus()); + StringMap env; + env["DISPLAY"] = xwaylandName; + env["XAUTHORITY"] = authFileName; + if (!callDBus(dbus, + QStringLiteral("UpdateActivationEnvironment"), + QStringLiteral("Failed to update XWayland activation environment"), + QVariant::fromValue(env))) { + scheduleActivateRetry(); + return; + } + + sd_notify(0, "READY=1"); + m_lastXwaylandAuth = auth; + clearPendingRetry(ActivateRetry); + } else { + scheduleActivateRetry(); + } + } + } + if (m_type == "xwayland" && !updateFd.isValid()) { + scheduleActivateRetry(); + } + } + +private: + enum class Bus { + Session, + System, + }; + + enum RetryFlag { + StartRetry = 1 << 0, + ActivateRetry = 1 << 1, + }; + + bool isRetryPending(RetryFlag flag) const { + return m_pendingRetries & flag; + } + + void setPendingRetry(RetryFlag flag) { + m_pendingRetries |= flag; + } + + void clearPendingRetry(RetryFlag flag) { + m_pendingRetries &= ~flag; + } + + Bus busFromConnection(const QDBusConnection &connection) const { + return connection.name() == QDBusConnection::sessionBus().name() + ? Bus::Session + : Bus::System; + } + + QDBusConnection dbusConnection(Bus bus) const { + return bus == Bus::Session + ? QDBusConnection::sessionBus() + : QDBusConnection::systemBus(); + } + + QString runtimeFileName(const QString &fileName) const { + QByteArray runtimeDir = qgetenv("XDG_RUNTIME_DIR"); + if (runtimeDir.isEmpty()) + runtimeDir = QDir::tempPath().toLocal8Bit(); + + return QStringLiteral("%1/%2").arg(QString::fromLocal8Bit(runtimeDir), fileName); + } + + QString xauthorityFileName() const { + return runtimeFileName(QStringLiteral("treeland-xauthority")); + } + + bool writeXAuthority(const QString &fileName, const QByteArray &auth) const { + QSaveFile file(fileName); + if (!file.open(QFile::WriteOnly)) { + qCWarning(lcSdSocket) << "Failed to open xauth file" << fileName << file.errorString(); + return false; + } + + file.setPermissions(QFile::ReadOwner | QFile::WriteOwner); + if (file.write(auth) != auth.size()) { + qCWarning(lcSdSocket) << "Failed to write xauth file" << fileName << file.errorString(); + return false; + } + + if (!file.commit()) { + qCWarning(lcSdSocket) << "Failed to commit xauth file" << fileName << file.errorString(); + return false; + } + + return true; + } + + template + std::optional callDBus(QDBusInterface &interface, + const QString &method, + const QString &errorMessage, + Args &&...args) { + QDBusMessage reply = interface.call(method, std::forward(args)...); + if (reply.type() == QDBusMessage::ErrorMessage) { + qCWarning(lcSdSocket) << errorMessage << reply.errorMessage(); + return std::nullopt; + } + + return reply; + } + + bool connectActivationSignal(QDBusConnection connection) { + const auto bus = busFromConnection(connection); + if (m_compositorBus == bus) + return true; + + // Xwayland only has to react to auth refreshes. Its display number and + // the XAUTHORITY path survive a wlroots in-place Xwayland restart, so + // a session change does not affect it and must not re-run activation. + const QString signalName = m_type == "xwayland" + ? QStringLiteral("XWaylandAuthChanged") + : QStringLiteral("SessionChanged"); + + if (m_compositorBus.has_value()) { + auto oldConnection = dbusConnection(*m_compositorBus); + oldConnection.disconnect("org.deepin.Compositor1", + "/org/deepin/Compositor1", + "org.deepin.Compositor1", + signalName, + this, + SLOT(activate())); + m_compositorBus.reset(); + } + + if (connection.connect("org.deepin.Compositor1", + "/org/deepin/Compositor1", + "org.deepin.Compositor1", + signalName, + this, + SLOT(activate()))) { + m_compositorBus = bus; + return true; + } + + return false; + } + + void watchService(const QDBusConnection &connection) { + if (findChild(connection.name())) + return; + + const auto bus = busFromConnection(connection); + auto *watcher = new QDBusServiceWatcher(QStringLiteral("org.deepin.Compositor1"), + connection, + QDBusServiceWatcher::WatchForRegistration + | QDBusServiceWatcher::WatchForUnregistration, + this); + watcher->setObjectName(connection.name()); + connect(watcher, &QDBusServiceWatcher::serviceRegistered, this, [this, bus](const QString &service) { + Q_UNUSED(service) + if (!m_started || m_compositorBus == bus) { + start(); + } + }); + connect(watcher, &QDBusServiceWatcher::serviceUnregistered, this, [this, bus](const QString &service) { + Q_UNUSED(service) + if (m_compositorBus == bus) { + m_started = false; + resetXwaylandActivationState(); + scheduleStartRetry(); + } + }); + } + + void scheduleStartRetry() { + if (isRetryPending(StartRetry)) + return; + + setPendingRetry(StartRetry); + QTimer::singleShot(RetryIntervalMs, this, [this] { + if (!isRetryPending(StartRetry)) + return; + + clearPendingRetry(StartRetry); + start(); + }); + } + + void scheduleActivateRetry() { + if (m_type != "xwayland" || isRetryPending(ActivateRetry)) + return; + + setPendingRetry(ActivateRetry); + QTimer::singleShot(RetryIntervalMs, this, [this] { + if (!isRetryPending(ActivateRetry)) + return; + + clearPendingRetry(ActivateRetry); + activate(); + }); + } + + void resetXwaylandActivationState() { + if (m_type != "xwayland") + return; + + m_lastXwaylandAuth.clear(); + clearPendingRetry(ActivateRetry); + } + + static constexpr int RetryIntervalMs = 500; + + std::shared_ptr m_unixFileDescriptor; + QString m_type; + bool m_started = false; + int m_pendingRetries = 0; + QByteArray m_lastXwaylandAuth; + std::optional m_compositorBus; +}; + +int main(int argc, char *argv[]) +{ + QCoreApplication app(argc, argv); + + qDBusRegisterMetaType(); + + QCommandLineParser parser; + parser.setApplicationDescription("Treeland socket helper"); + parser.addHelpOption(); + parser.addVersionOption(); + + QCommandLineOption typeOption(QStringList() << "t" + << "type", + "xwayland", + "wayland"); + parser.addOption(typeOption); + + parser.process(app); + + const QString &type = parser.value(typeOption); + + if (type == "wayland" && sd_listen_fds(0) > 1) { + fprintf(stderr, "Too many file descriptors received.\n"); + exit(1); + } + + QDBusUnixFileDescriptor unixFileDescriptor(SD_LISTEN_FDS_START); + + auto *activator = new SocketActivator(unixFileDescriptor, type, &app); + activator->start(); + + return app.exec(); +} + +#include "systemd-socket.moc" diff --git a/src/treeland-screensaver/CMakeLists.txt b/src/treeland-screensaver/CMakeLists.txt new file mode 100644 index 0000000000..d3e1bea789 --- /dev/null +++ b/src/treeland-screensaver/CMakeLists.txt @@ -0,0 +1,34 @@ +pkg_search_module(WAYLAND_CLIENT REQUIRED IMPORTED_TARGET wayland-client) +find_package(TreelandProtocols REQUIRED) + +set(TREELAND_SCREENSAVER_SOURCE ${CMAKE_CURRENT_BINARY_DIR}/treeland-screensaver-v2.c) +set(TREELAND_SCREENSAVER_HEADER ${CMAKE_CURRENT_BINARY_DIR}/treeland-screensaver-v2.h) + +add_custom_command( + OUTPUT ${TREELAND_SCREENSAVER_HEADER} + COMMAND wayland-scanner client-header < ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-screensaver-unstable-v2.xml > ${TREELAND_SCREENSAVER_HEADER} + DEPENDS ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-screensaver-unstable-v2.xml + COMMENT "Generating treeland-screensaver-v2.h" +) + +add_custom_command( + OUTPUT ${TREELAND_SCREENSAVER_SOURCE} + COMMAND wayland-scanner private-code < ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-screensaver-unstable-v2.xml > ${TREELAND_SCREENSAVER_SOURCE} + DEPENDS ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-screensaver-unstable-v2.xml + COMMENT "Generating treeland-screensaver-v2.c" +) + +qt_add_executable(treeland-screensaver + screensaver.cpp + ${TREELAND_SCREENSAVER_HEADER} + ${TREELAND_SCREENSAVER_SOURCE} +) + +target_link_libraries(treeland-screensaver + PUBLIC + Qt6::DBus + PkgConfig::WAYLAND_CLIENT +) + +install(TARGETS treeland-screensaver RUNTIME DESTINATION "${CMAKE_INSTALL_LIBEXECDIR}") +install(FILES org.freedesktop.ScreenSaver.xml DESTINATION "${CMAKE_INSTALL_DATADIR}/dbus-1/interfaces") diff --git a/src/treeland-screensaver/org.freedesktop.ScreenSaver.xml b/src/treeland-screensaver/org.freedesktop.ScreenSaver.xml new file mode 100644 index 0000000000..b0446f0af4 --- /dev/null +++ b/src/treeland-screensaver/org.freedesktop.ScreenSaver.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/treeland-screensaver/screensaver.cpp b/src/treeland-screensaver/screensaver.cpp new file mode 100644 index 0000000000..2839c8ba11 --- /dev/null +++ b/src/treeland-screensaver/screensaver.cpp @@ -0,0 +1,204 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +/** + * org.freedesktop.ScreenSaver implementation using treeland_screensaver protocol + * + * This service runs as a persistent daemon under Treeland session. + * For each Inhibit request a wayland connection is created, which will be terminated + * upon UnInhibit. + */ + +#include +#include +#include +#include +#include +#include +#include "treeland-screensaver-v2.h" + +#include + +// Global vars + +static wl_display *display; +static QSocketNotifier *notifier; +static QSocketNotifier *writeNotifier; +static wl_registry *registry; +static uint32_t interfaceId; +static uint32_t interfaceVersion; + +static uint cookieCounter = 0; +static QHash> inhibits; + +static QStringList callers; +QDBusServiceWatcher *watcher; + +// Wayland global registry handling + +static void handleGlobalRegister([[maybe_unused]] void *data, + [[maybe_unused]] wl_registry *reg, + uint32_t id, + const char *interface, + uint32_t version) { + if (strcmp(interface, "treeland_screensaver_v2") == 0) { + interfaceId = id; + interfaceVersion = version; + } +} + +static void handleGlobalRemove([[maybe_unused]] void *data, + [[maybe_unused]] wl_registry *registry, + uint32_t id) { + if (id != interfaceId) + return; + + // Keep existing bindings alive and wait for the global to be advertised again. + interfaceId = 0; + interfaceVersion = 0; +} + +static const wl_registry_listener registryListener = { + .global = handleGlobalRegister, + .global_remove = handleGlobalRemove +}; + +static void flushWayland() { + if (wl_display_flush(display) >= 0) { + writeNotifier->setEnabled(false); + } else if (errno == EAGAIN) { + // Retry buffered requests once the socket becomes writable. + writeNotifier->setEnabled(true); + } else { + writeNotifier->setEnabled(false); + QCoreApplication::exit(-1); + } +} + +// Inhibit / Uninhibit implementation + +static treeland_screensaver_v2 *inhibit(const QString &appName, const QString &reason) { + treeland_screensaver_v2 *screensaver = static_cast( + wl_registry_bind(registry, interfaceId, &treeland_screensaver_v2_interface, interfaceVersion)); + treeland_screensaver_v2_inhibit(screensaver, + appName.toUtf8().constData(), + reason.toUtf8().constData()); + flushWayland(); + return screensaver; +} + +static void uninhibit(treeland_screensaver_v2 *screensaver) { + treeland_screensaver_v2_uninhibit(screensaver); + treeland_screensaver_v2_destroy(screensaver); + flushWayland(); +} + +// D-Bus adaptor + +class ScreenSaver : public QObject, protected QDBusContext { + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "org.freedesktop.ScreenSaver") +public Q_SLOTS: + uint Inhibit(const QString &appName, const QString &reason) { + // D-Bus requests can still arrive while the Wayland global is unavailable. + if (interfaceId == 0) { + sendErrorReply(QDBusError::NotSupported, "Screensaver protocol is unavailable"); + return 0; + } + + const QString caller = message().service(); + if (!callers.contains(caller)) { + callers.append(caller); + watcher->addWatchedService(caller); + } + if (!inhibits.contains(caller)) + inhibits.emplace(caller); + inhibits[caller].insert(++cookieCounter, inhibit(appName, reason)); + return cookieCounter; + } + void UnInhibit(uint cookie) { + const QString caller = message().service(); + if (inhibits.contains(caller) && inhibits[caller].contains(cookie)) { + uninhibit(inhibits[caller][cookie]); + inhibits[caller].remove(cookie); + if (inhibits[caller].isEmpty()) + inhibits.remove(caller); + } + } +}; + +// D-Bus service watcher + +#define DISCONNECTED(caller) \ + callers.removeAll(caller); \ + watcher->removeWatchedService(caller); \ + if (inhibits.contains(caller)) { \ + for (auto it = inhibits[caller].cbegin(); it != inhibits[caller].cend(); ++it) \ + uninhibit(it.value()); \ + inhibits.remove(caller); \ + } + +static void onServiceUnregistered(const QString &service) { + DISCONNECTED(service); +} + +static void onServiceOwnerChanged(const QString &service, + [[maybe_unused]] const QString &oldOwner, + [[maybe_unused]] const QString &newOwner) { + DISCONNECTED(service); +} + +// Main function + +int main(int argc, char *argv[]) { + QCoreApplication app(argc, argv); + + // Connect to treeland and setup registry + display = wl_display_connect(nullptr); + if (!display) + return -1; + + registry = wl_display_get_registry(display); + wl_registry_add_listener(registry, ®istryListener, nullptr); + if (wl_display_roundtrip(display) == -1 || interfaceId == 0) { + wl_display_disconnect(display); + return -1; + } + + // Setup event loop + writeNotifier = new QSocketNotifier(wl_display_get_fd(display), QSocketNotifier::Write, &app); + writeNotifier->setEnabled(false); + QObject::connect(writeNotifier, &QSocketNotifier::activated, flushWayland); + + notifier = new QSocketNotifier(wl_display_get_fd(display), QSocketNotifier::Read, &app); + QObject::connect(notifier, &QSocketNotifier::activated, [] { + if (wl_display_dispatch(display) == -1) { + QCoreApplication::exit(-1); + return; + } + + flushWayland(); + }); + + // Setup watcher + watcher = new QDBusServiceWatcher(&app); + watcher->setConnection(QDBusConnection::sessionBus()); + watcher->setWatchMode(QDBusServiceWatcher::WatchForUnregistration); + QObject::connect(watcher, + &QDBusServiceWatcher::serviceUnregistered, + onServiceUnregistered); + QObject::connect(watcher, + &QDBusServiceWatcher::serviceOwnerChanged, + onServiceOwnerChanged); + + // Register D-Bus service + QDBusConnection::sessionBus().registerObject("/org/freedesktop/ScreenSaver", + new ScreenSaver(), + QDBusConnection::ExportAllSlots); + QDBusConnection::sessionBus().registerService("org.freedesktop.ScreenSaver"); + + // Let's rock & roll!!! + return app.exec(); +} + +#include "screensaver.moc" diff --git a/src/treeland.sh b/src/treeland.sh new file mode 100755 index 0000000000..af927dfa14 --- /dev/null +++ b/src/treeland.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env sh + +script_path=$(realpath $(dirname "$0")) +cmd="$script_path/treeland" +# Include all user arguments in test to ensure consistent environment +output=$($cmd --try-exec "$@" 2>&1) +exit_code=$? + +if [ $exit_code -ne 0 ] && echo "$output" | grep -q "failed to create dri2 screen"; then + # In VirtualBox, if 3D acceleration is not enabled, calling `eglInitialize` will cause + # the program to crash. Therefore, a preliminary check is performed here: if `treeland` + # fails to exit normally, it falls back to pixman renderer mode. + export WLR_RENDERER=pixman + echo "Treeland crash, try fallback to software renderer." +fi + +# Use exec to replace current process instead of creating a subprocess +# This ensures treeland directly replaces treeland.sh process, avoiding dual processes +exec $cmd "$@" diff --git a/src/utils/cmdline.cpp b/src/utils/cmdline.cpp new file mode 100644 index 0000000000..62140f10af --- /dev/null +++ b/src/utils/cmdline.cpp @@ -0,0 +1,152 @@ +// Copyright (C) 2023 Dingyuan Zhang . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "cmdline.h" +#include "common/treelandlogging.h" + +#include + +#include +#include +#include + +#include + +CmdLine::CmdLine() + : QObject() + , m_parser(std::make_unique()) + , m_run(std::make_unique(QStringList{ "r", "run" }, "run a process", "run")) + , m_lockScreen(std::make_unique("lockscreen", + "use lockscreen, need DDM auth socket")) + , m_tryExec("try-exec", "Only try exec, don't show on screen") + , m_enableDebugView("enable-debug-view", "Enable debug view") + , m_consoleLog("console-log", "Enable console logging output") +{ + m_parser->addHelpOption(); + m_parser->addOptions({ *m_run.get(), *m_lockScreen.get(), m_tryExec, m_enableDebugView, m_consoleLog }); + m_parser->process(*QCoreApplication::instance()); +} + +CmdLine::~CmdLine() = default; + +QString CmdLine::unescape(const QString &str) noexcept +{ + QString unescapedStr; + for (qsizetype i = 0; i < str.size(); ++i) { + auto c = str.at(i); + if (c != '\\') { + unescapedStr.append(c); + continue; + } + + switch (str.at(i + 1).toLatin1()) { + default: + unescapedStr.append(c); + break; + case 'n': + unescapedStr.append('\n'); + ++i; + break; + case 't': + unescapedStr.append('\t'); + ++i; + break; + case 'r': + unescapedStr.append('\r'); + ++i; + break; + case '\\': + unescapedStr.append('\\'); + ++i; + break; + case ';': + unescapedStr.append(';'); + ++i; + break; + case 's': { + unescapedStr.append(R"(\ )"); + ++i; + } break; + } + } + + return unescapedStr; +} + +std::optional CmdLine::unescapeExecArgs(const QString &str) noexcept +{ + auto unescapedStr = unescape(str); + if (unescapedStr.isEmpty()) { + qCWarning(lcTlUtils) << "unescape Exec failed."; + return std::nullopt; + } + + auto deleter = [](wordexp_t *word) { + wordfree(word); + delete word; + }; + std::unique_ptr words{ new (std::nothrow) + wordexp_t{ 0, nullptr, 0 }, + deleter }; + + if (auto ret = wordexp(unescapedStr.toLocal8Bit(), words.get(), WRDE_SHOWERR); ret != 0) { + QString errMessage; + switch (ret) { + case WRDE_BADCHAR: + errMessage = "BADCHAR"; + break; + case WRDE_BADVAL: + errMessage = "BADVAL"; + break; + case WRDE_CMDSUB: + errMessage = "CMDSUB"; + break; + case WRDE_NOSPACE: + errMessage = "NOSPACE"; + break; + case WRDE_SYNTAX: + errMessage = "SYNTAX"; + break; + default: + errMessage = "unknown"; + } + qCWarning(lcTlUtils) << "wordexp error: " << errMessage; + return std::nullopt; + } + + QStringList execList; + for (std::size_t i = 0; i < words->we_wordc; ++i) { + execList.emplace_back(words->we_wordv[i]); + } + + return execList; +} + +bool CmdLine::tryExec() const +{ + return m_parser->isSet(m_tryExec); +} + +bool CmdLine::enableDebugView() const +{ + return m_parser->isSet(m_enableDebugView); +} + +bool CmdLine::consoleLog() const +{ + return m_parser->isSet(m_consoleLog); +} + +std::optional CmdLine::run() const +{ + if (m_parser->isSet(*m_run.get())) { + return m_parser->value(*m_run.get()); + } + + return std::nullopt; +} + +bool CmdLine::useLockScreen() const +{ + return m_parser->isSet(*m_lockScreen.get()); +} diff --git a/src/utils/cmdline.h b/src/utils/cmdline.h new file mode 100644 index 0000000000..237c36de1f --- /dev/null +++ b/src/utils/cmdline.h @@ -0,0 +1,44 @@ +// Copyright (C) 2023 Dingyuan Zhang . +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include + +#include +#include + +#include +#include + +class QCoreApplication; +class QCommandLineParser; + +DCORE_USE_NAMESPACE + +class CmdLine + : public QObject + , public DSingleton +{ + Q_OBJECT + friend class DSingleton; + +public: + std::optional run() const; + bool useLockScreen() const; + std::optional unescapeExecArgs(const QString &str) noexcept; + bool tryExec() const; + bool enableDebugView() const; + bool consoleLog() const; + +private: + CmdLine(); + ~CmdLine(); + QString unescape(const QString &str) noexcept; + +private: + std::unique_ptr m_parser; + std::unique_ptr m_run; + std::unique_ptr m_lockScreen; + QCommandLineOption m_tryExec; + QCommandLineOption m_enableDebugView; + QCommandLineOption m_consoleLog; +}; diff --git a/src/utils/fpsdisplaymanager.cpp b/src/utils/fpsdisplaymanager.cpp new file mode 100644 index 0000000000..d8fae9b634 --- /dev/null +++ b/src/utils/fpsdisplaymanager.cpp @@ -0,0 +1,331 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "fpsdisplaymanager.h" +#include +#include +#include +#include +#include + +FpsDisplayManager::FpsDisplayManager(QObject *parent) + : QObject(parent) + , m_updateTimer(this) + , m_vsyncTimer(this) +{ + m_timer.start(); + + m_updateTimer.setInterval(kUpdateIntervalMs); + m_updateTimer.setSingleShot(false); + connect(&m_updateTimer, &QTimer::timeout, this, &FpsDisplayManager::updateFps); + + updateRefreshAndInterval(); + m_vsyncTimer.setInterval(qRound(m_preciseVSyncInterval)); + m_vsyncTimer.setSingleShot(false); + connect(&m_vsyncTimer, &QTimer::timeout, this, &FpsDisplayManager::onVSyncTimer); +} + +FpsDisplayManager::~FpsDisplayManager() +{ + m_updateTimer.stop(); + m_vsyncTimer.stop(); + + if (m_targetWindow) { + disconnect(m_targetWindow, nullptr, this, nullptr); + } +} + +void FpsDisplayManager::setTargetWindow(QQuickWindow *window) +{ + if (m_targetWindow == window) + return; + + if (m_targetWindow) { + disconnect(m_targetWindow, nullptr, this, nullptr); + } + + invalidateCache(); + m_targetWindow = window; + + if (m_targetWindow) { + updateRefreshAndInterval(); + connect(m_targetWindow, &QQuickWindow::screenChanged, + this, &FpsDisplayManager::onScreenChanged, Qt::UniqueConnection); + } +} + +void FpsDisplayManager::start() +{ + reset(); + updateRefreshAndInterval(); + m_vsyncTimer.setInterval(qRound(m_preciseVSyncInterval)); + m_updateTimer.start(); + m_vsyncTimer.start(); +} + +void FpsDisplayManager::stop() +{ + m_updateTimer.stop(); + m_vsyncTimer.stop(); +} + +void FpsDisplayManager::onVSyncTimer() +{ + qint64 currentTime = m_timer.elapsed(); + if (m_lastVSyncTime_precise > 0) { + qint64 actualInterval = currentTime - m_lastVSyncTime_precise; + double expectedInterval = m_preciseVSyncInterval; + + // Filter out timer jitter: reject intervals shorter than 70% of expected + if (actualInterval < expectedInterval * 0.7) { + return; + } + + if (actualInterval > expectedInterval * 2.5) { + m_lastVSyncTime_precise = currentTime; + return; + } + } + + m_vSyncTimes.enqueue(currentTime); + m_lastVSyncTime_precise = currentTime; + + // Keep at least 30 samples or 1 second worth of data for accuracy + int maxSamples = qMax(30, m_displayRefreshRate); + while (m_vSyncTimes.size() > maxSamples) { + m_vSyncTimes.dequeue(); + } +} + +void FpsDisplayManager::reset() +{ + m_currentFps = 0.0; + m_maximumFps = 0.0; + m_lastUpdateTime = m_timer.elapsed(); + m_vSyncTimes.clear(); + m_lastVSyncTime_precise = 0; + + updateFpsText(); +} + +void FpsDisplayManager::updateFps() +{ + if (m_vSyncTimes.isEmpty()) { + if (m_currentFps != 0 || m_maximumFps != 0) { + m_currentFps = 0; + m_maximumFps = 0; + updateFpsText(); + } + return; + } + + qint64 currentTime = m_timer.elapsed(); + qint64 timeDiff = currentTime - m_lastUpdateTime; + + if (timeDiff < kUpdateIntervalMs) { + return; + } + + qreal calculatedFps = 0.0; + if (m_vSyncTimes.size() >= 2) { + qint64 totalTimeSpan = m_vSyncTimes.last() - m_vSyncTimes.first(); + if (totalTimeSpan > 0) { + calculatedFps = ((m_vSyncTimes.size() - 1) * 1000.0) / totalTimeSpan; + } + } + + if (calculatedFps <= 0) { + calculatedFps = m_displayRefreshRate; + } + + calculatedFps = qBound(1.0, calculatedFps, (qreal)m_displayRefreshRate); + if (qAbs(calculatedFps - m_displayRefreshRate) < m_displayRefreshRate * 0.1) { + calculatedFps = m_displayRefreshRate; + } + + // Apply exponential smoothing to reduce fluctuations (15% new, 85% old) + const qreal smoothingFactor = 0.15; + if (m_currentFps == 0.0) { + m_currentFps = calculatedFps; + } else { + m_currentFps = m_currentFps * (1.0 - smoothingFactor) + calculatedFps * smoothingFactor; + } + + m_currentFps = qMin(m_currentFps, (qreal)m_displayRefreshRate); + if (m_currentFps > m_maximumFps) { + qreal maxAllowedFps = m_displayRefreshRate * 1.05; // Allow 5% measurement error + m_maximumFps = qMin(m_currentFps, maxAllowedFps); + } + + m_maximumFps = qMin(m_maximumFps, (qreal)m_displayRefreshRate * 1.05); + m_lastUpdateTime = currentTime; + updateFpsText(); +} + +void FpsDisplayManager::detectDisplayRefreshRate() +{ + if (m_targetWindow) { + if (auto output = getOutputForWindow()) { + if (auto qwoutput = output->handle()) { + if (auto mode = wlr_output_preferred_mode(qwoutput)) { + int32_t refresh = mode->refresh; + if (refresh > 0) { + m_displayRefreshRate = qRound(refresh / 1000.0); + } + } + } + } + } + + // Environment variable override for debugging/testing + QString envRefreshRate = qgetenv("TREELAND_REFRESH_RATE"); + if (!envRefreshRate.isEmpty()) { + bool ok; + int rate = envRefreshRate.toInt(&ok); + if (ok && rate > 0 && rate <= 240) { + m_displayRefreshRate = rate; + } + } +} + +void FpsDisplayManager::updateFpsText() +{ + int current = currentFps(); + int maximum = maximumFps(); + + if (current != m_lastReportedCurrentFps) { + m_lastReportedCurrentFps = current; + Q_EMIT currentFpsChanged(); + } + + if (maximum != m_lastReportedMaximumFps) { + m_lastReportedMaximumFps = maximum; + Q_EMIT maximumFpsChanged(); + } +} + +void FpsDisplayManager::onScreenChanged(QScreen *screen) +{ + Q_UNUSED(screen); + + invalidateCache(); + int oldRate = m_displayRefreshRate; + updateRefreshAndInterval(); + + if (m_displayRefreshRate != oldRate) { + if (m_vsyncTimer.isActive()) { + m_vsyncTimer.stop(); + m_vsyncTimer.start(); + } + + m_vSyncTimes.clear(); + m_lastVSyncTime_precise = 0; + m_currentFps = 0.0; + } +} + +void FpsDisplayManager::updateTimerIntervals() +{ + m_preciseVSyncInterval = 1000.0 / m_displayRefreshRate; + int vsyncInterval = qRound(m_preciseVSyncInterval); + + // Use pre-calculated intervals for common refresh rates to avoid rounding errors + if (m_displayRefreshRate == 60) { + vsyncInterval = 17; // 16.67ms rounded up for stability + } else if (m_displayRefreshRate == 90) { + vsyncInterval = 11; // 11.11ms + } else if (m_displayRefreshRate == 120) { + vsyncInterval = 8; // 8.33ms + } else if (m_displayRefreshRate == 144) { + vsyncInterval = 7; // 6.94ms + } + + vsyncInterval = qMax(1, vsyncInterval); + m_vsyncTimer.setInterval(vsyncInterval); +} + +void FpsDisplayManager::updateRefreshAndInterval() +{ + int oldRate = m_displayRefreshRate; + detectDisplayRefreshRate(); + + if (m_displayRefreshRate != oldRate) { + updateTimerIntervals(); + Q_EMIT refreshRateChanged(); + } +} + +WOutput *FpsDisplayManager::findBestOutput(const QVector &outputs) const +{ + if (outputs.isEmpty()) { + return nullptr; + } + + if (outputs.size() == 1) { + return outputs.first(); + } + + for (auto output : outputs) { + if (output && output->isEnabled()) { + return output; + } + } + WOutput *bestOutput = outputs.first(); + int maxRefreshRate = 0; + + for (auto output : outputs) { + if (!output) continue; + + if (auto qwoutput = output->handle()) { + if (auto mode = wlr_output_preferred_mode(qwoutput)) { + int refreshRate = qRound(mode->refresh / 1000.0); + if (refreshRate > maxRefreshRate) { + maxRefreshRate = refreshRate; + bestOutput = output; + } + } + } + } + + return bestOutput; +} + +void FpsDisplayManager::invalidateCache() +{ + m_cachedOutput = nullptr; + m_cacheTimestamp = 0; +} + +WOutput *FpsDisplayManager::getOutputForWindow() const +{ + if (!m_targetWindow) + return nullptr; + + qint64 currentTime = QDateTime::currentMSecsSinceEpoch(); + if (m_cachedOutput && (currentTime - m_cacheTimestamp) < kCacheValidityMs) { + return m_cachedOutput; + } + + auto renderWindow = qobject_cast(m_targetWindow); + if (!renderWindow) { + return nullptr; + } + + QVector outputs; + for (auto child : renderWindow->children()) { + if (auto viewport = qobject_cast(child)) { + if (auto output = viewport->output()) { + outputs.append(output); + } + } + } + + WOutput *bestOutput = nullptr; + if (!outputs.isEmpty()) { + bestOutput = findBestOutput(outputs); + } + + m_cachedOutput = bestOutput; + m_cacheTimestamp = currentTime; + return bestOutput; +} diff --git a/src/utils/fpsdisplaymanager.h b/src/utils/fpsdisplaymanager.h new file mode 100644 index 0000000000..7c584f314c --- /dev/null +++ b/src/utils/fpsdisplaymanager.h @@ -0,0 +1,91 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include +#include +#include +#include +#include + +class QQuickItem; +class QQuickWindow; +class QScreen; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutput; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class FpsDisplayManager : public QObject +{ + Q_OBJECT + Q_PROPERTY(int currentFps READ currentFps NOTIFY currentFpsChanged) + Q_PROPERTY(int maximumFps READ maximumFps NOTIFY maximumFpsChanged) + Q_PROPERTY(int displayRefreshRate READ displayRefreshRate NOTIFY refreshRateChanged) + QML_ELEMENT + +public: + explicit FpsDisplayManager(QObject *parent = nullptr); + ~FpsDisplayManager(); + + Q_INVOKABLE void setTargetWindow(QQuickWindow *window); + // TODO: Add setTargetOutput(WOutput* output) method for multi-screen FPS display support + Q_INVOKABLE void start(); + Q_INVOKABLE void stop(); + Q_INVOKABLE void reset(); + + int currentFps() const { return qRound(m_currentFps); } + int maximumFps() const { return qRound(m_maximumFps); } + int displayRefreshRate() const { return m_displayRefreshRate; } + +Q_SIGNALS: + void currentFpsChanged(); + void maximumFpsChanged(); + void refreshRateChanged(); + +private Q_SLOTS: + void updateFps(); + void onVSyncTimer(); + void onScreenChanged(QScreen *screen); + +private: + void updateRefreshAndInterval(); + void updateTimerIntervals(); + void updateFpsText(); + void detectDisplayRefreshRate(); + WOutput *getOutputForWindow() const; + WOutput *findBestOutput(const QVector &outputs) const; + void invalidateCache(); + + QPointer m_targetWindow; + + QElapsedTimer m_timer; + QTimer m_updateTimer; + QTimer m_vsyncTimer; + QQueue m_vSyncTimes; + + qreal m_currentFps = 0.0; + qreal m_averageFps = 0.0; + qreal m_maximumFps = 0.0; + qint64 m_lastUpdateTime = 0; + qint64 m_lastVSyncTime_precise = 0; + + int m_displayRefreshRate = 60; // Display refresh rate in Hz + double m_preciseVSyncInterval = 16.67; // Precise VSync interval in milliseconds + // Constants + static constexpr int kUpdateIntervalMs = 500; // UI update frequency in milliseconds + static constexpr qint64 kCacheValidityMs = 5000; // Cache validity: 5 seconds + + // Cache for change detection + int m_lastReportedCurrentFps = -1; + int m_lastReportedMaximumFps = -1; + + // Output caching for performance optimization + mutable QPointer m_cachedOutput; + mutable qint64 m_cacheTimestamp = 0; +}; diff --git a/src/utils/graphicsplatform.cpp b/src/utils/graphicsplatform.cpp new file mode 100644 index 0000000000..d5bf198aca --- /dev/null +++ b/src/utils/graphicsplatform.cpp @@ -0,0 +1,819 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "graphicsplatform.h" + +#include + +#include + +namespace { + +using ChipClass = GraphicsPlatform::ChipClass; +using Driver = GraphicsPlatform::Driver; + +// PCI vendor IDs. Reliable on Vulkan, 0 when the backend does not report them. +constexpr quint64 PciVendorAmd = 0x1002; +constexpr quint64 PciVendorNvidia = 0x10de; +constexpr quint64 PciVendorIntel = 0x8086; +constexpr quint64 PciVendorQualcomm = 0x5143; +constexpr quint64 PciVendorArm = 0x13b5; +constexpr quint64 PciVendorBroadcom = 0x14e4; +constexpr quint64 PciVendorVmware = 0x15ad; +constexpr quint64 PciVendorVirtualBox = 0x80ee; +constexpr quint64 PciVendorVirtio = 0x1af4; + +bool containsAny(const QString &text, std::initializer_list needles) +{ + for (const char *needle : needles) { + if (text.contains(QLatin1StringView(needle), Qt::CaseInsensitive)) { + return true; + } + } + return false; +} + +// Returns the portion of @p text matching @p pattern, or a null string. +QString extract(const QString &text, const QString &pattern) +{ + const QRegularExpressionMatch match = QRegularExpression(pattern).match(text); + return match.hasMatch() ? match.captured() : QString(); +} + +// Strips a trailing non-digit left over from a "(M|\\b)" style pattern. +int trailingNumber(const QString &text, int digits) +{ + QString name = text.trimmed(); + while (!name.isEmpty() && !name.back().isDigit()) { + name.chop(1); + } + return name.right(digits).toInt(); +} + +ChipClass detectRadeonClass(const QString &chipset) +{ + if (chipset.isEmpty()) { + return ChipClass::Unknown; + } + + if (containsAny(chipset, {"R100", "RV100", "RS100"})) { + return ChipClass::R100; + } + + if (containsAny(chipset, {"RV200", "RS200", "R200", "RV250", "RS300", "RV280"})) { + return ChipClass::R200; + } + + if (containsAny(chipset, {"R300", "R350", "R360", "RV350", "RV370", "RV380"})) { + return ChipClass::R300; + } + + if (containsAny(chipset, {"R420", "R423", "R430", "R480", "R481", "RV410", "RS400", + "RC410", "RS480", "RS482", "RS600", "RS690", "RS740"})) { + return ChipClass::R400; + } + + if (containsAny(chipset, {"RV515", "R520", "RV530", "R580", "RV560", "RV570"})) { + return ChipClass::R500; + } + + if (containsAny(chipset, {"R600", "RV610", "RV630", "RV670", "RV620", "RV635", "RS780", + "RS880"})) { + return ChipClass::R600; + } + + if (containsAny(chipset, {"R700", "RV770", "RV730", "RV710", "RV740"})) { + return ChipClass::R700; + } + + if (containsAny(chipset, {"EVERGREEN", "CEDAR", "REDWOOD", "JUNIPER", "CYPRESS", "HEMLOCK", + "PALM"})) { + return ChipClass::Evergreen; + } + + if (containsAny(chipset, {"SUMO", "SUMO2", "BARTS", "TURKS", "CAICOS", "CAYMAN"})) { + return ChipClass::NorthernIslands; + } + + if (containsAny(chipset, {"TAHITI", "PITCAIRN", "VERDE", "OLAND", "HAINAN"})) { + return ChipClass::SouthernIslands; + } + + if (containsAny(chipset, {"BONAIRE", "KAVERI", "KABINI", "HAWAII", "MULLINS"})) { + return ChipClass::SeaIslands; + } + + if (containsAny(chipset, {"TONGA", "TOPAZ", "FIJI", "CARRIZO", "STONEY"})) { + return ChipClass::VolcanicIslands; + } + + if (containsAny(chipset, {"POLARIS10", "POLARIS11", "POLARIS12", "POLARIS 1", "VEGAM"})) { + return ChipClass::ArcticIslands; + } + + if (containsAny(chipset, {"VEGA10", "VEGA12", "VEGA20", "VEGA 1", "VEGA 2", "RAVEN", + "RAVEN2", "RENOIR", "ARCTURUS"})) { + return ChipClass::Vega; + } + + if (containsAny(chipset, {"NAVI10", "NAVI12", "NAVI14", "NAVI21", "NAVI22", "NAVI23", + "NAVI24", "NAVI31", "NAVI32", "NAVI33", "NAVI 1", "NAVI 2", + "NAVI 3", "REMBRANDT", "PHOENIX", "CEZANNE", "BARCELO"})) { + return ChipClass::Navi; + } + + // Marketing names of older cards: Radeon HD 5xxx/6xxx, X1xxx, 9xxx, ... + QString name = extract(chipset, QStringLiteral("HD [0-9]{4}")); + if (!name.isEmpty()) { + const int id = trailingNumber(name, 4); + if (id == 6250 || id == 6310) { // Palm + return ChipClass::Evergreen; + } + if (id >= 6000 && id < 7000) { + return ChipClass::NorthernIslands; + } + if (id >= 5000 && id < 6000) { + return ChipClass::Evergreen; + } + if (id >= 4000 && id < 5000) { + return ChipClass::R700; + } + if (id >= 2000 && id < 4000) { + return ChipClass::R600; + } + return ChipClass::Unknown; + } + + name = extract(chipset, QStringLiteral("\\bX[0-9]{3,4}\\b")); + if (!name.isEmpty()) { + const int id = QStringView(name).mid(1).toInt(); + if (id >= 1300) { + return ChipClass::R500; + } + if ((id >= 700 && id < 1000) || id >= 1200) { + return ChipClass::R400; + } + if ((id >= 300 && id < 700) || (id >= 1000 && id < 1200)) { + return ChipClass::R300; + } + return ChipClass::Unknown; + } + + name = extract(chipset, QStringLiteral("\\b[0-9]{4}\\b")); + if (!name.isEmpty()) { + const int id = name.toInt(); + if (id >= 7000 && id < 8000) { + return ChipClass::R100; + } + if (id >= 8000 && id < 9500) { + return ChipClass::R200; + } + if (id >= 9500) { + return ChipClass::R300; + } + if (id == 2100) { + return ChipClass::R400; + } + } + + return ChipClass::Unknown; +} + +// RTX/GTX/GT model numbers name the generation the chip class enum models. +// Returns ChipClass::Unknown when the string carries no such name. +ChipClass detectModernNVidiaClass(const QString &chipset) +{ + // Quadro RTX model numbers are tiers, not generations; they are all Turing. + if (chipset.contains(QLatin1StringView("Quadro"), Qt::CaseInsensitive)) { + return chipset.contains(QLatin1StringView("Quadro RTX"), Qt::CaseInsensitive) + ? ChipClass::Turing + : ChipClass::Unknown; + } + + static const QRegularExpression fourDigit(QStringLiteral("(?:RTX|GTX|GT) ([0-9]{4})")); + static const QRegularExpression threeDigit(QStringLiteral("(?:RTX|GTX|GT) ([0-9]{3})\\b")); + + QRegularExpressionMatch match = fourDigit.match(chipset); + if (match.hasMatch()) { + switch (match.captured(1).left(2).toInt()) { + case 10: // GTX 10xx + return ChipClass::Pascal; + case 16: // GTX 16xx + case 20: // RTX 20xx + return ChipClass::Turing; + case 30: // RTX 30xx + return ChipClass::Ampere; + case 40: // RTX 40xx + return ChipClass::Ada; + case 50: // RTX 50xx + return ChipClass::Blackwell; + default: + return ChipClass::Unknown; + } + } + + match = threeDigit.match(chipset); + if (match.hasMatch()) { + // Desktop GTX 750 and GTX 750 Ti use Maxwell despite the 7xx name. + if (match.captured().startsWith(QLatin1StringView("GTX ")) + && match.captured(1).toInt() == 750) { + return ChipClass::Maxwell; + } + switch (match.captured(1).left(1).toInt()) { + case 4: // GT/GTX 4xx/5xx, Fermi + case 5: + return ChipClass::GF100; + case 6: // GTX 6xx/7xx, Kepler + case 7: + return ChipClass::Kepler; + case 9: // GTX 9xx, Maxwell + return ChipClass::Maxwell; + default: + return ChipClass::Unknown; + } + } + + return ChipClass::Unknown; +} + +ChipClass detectNVidiaClass(const QString &chipset) +{ + QString name = extract(chipset, QStringLiteral("\\bNV[0-9,A-F]{2}\\b")); + if (!name.isEmpty()) { + const int id = QStringView(name).mid(2).toInt(nullptr, 16); + switch (id & 0xf0) { + case 0x00: + case 0x10: + return ChipClass::NV10; + case 0x20: + return ChipClass::NV20; + case 0x30: + return ChipClass::NV30; + case 0x40: + case 0x60: + return ChipClass::NV40; + case 0x50: + case 0x80: + case 0x90: + case 0xA0: + return ChipClass::G80; + default: + return ChipClass::Unknown; + } + } + + if (containsAny(chipset, {"GeForce2", "GeForce 256"})) { + return ChipClass::NV10; + } + + if (chipset.contains(QLatin1StringView("GeForce3"))) { + return ChipClass::NV20; + } + + if (chipset.contains(QLatin1StringView("GeForce4"))) { + if (containsAny(chipset, {"MX 420", "MX 440", "MX 460", "MX 4000", "PCX 4300"})) { + return ChipClass::NV10; + } + return ChipClass::NV20; + } + + const ChipClass modern = detectModernNVidiaClass(chipset); + if (modern != ChipClass::Unknown) { + return modern; + } + + // GeForce 5, 6, 7, 8, 9 + name = extract(chipset, QStringLiteral("GeForce (FX |PCX |Go )?\\d{4}(M|\\b)")).trimmed(); + if (!name.isEmpty()) { + const int id = trailingNumber(name, 4); + if (id < 6000) { + return ChipClass::NV30; + } + if (id < 8000) { + return ChipClass::NV40; + } + return ChipClass::G80; + } + + // GeForce 100/200/300/400/500 + name = extract(chipset, QStringLiteral("GeForce (G |GT |GTX |GTS )?\\d{3}(M|\\b)")).trimmed(); + if (!name.isEmpty()) { + const int id = trailingNumber(name, 3); + if (id >= 100) { + // 100/200/300 are G80 class, 400 and later are Fermi (GF100). + return id >= 400 ? ChipClass::GF100 : ChipClass::G80; + } + return ChipClass::Unknown; + } + + return ChipClass::Unknown; +} + +ChipClass detectIntelClass(const QString &chipset) +{ + if (containsAny(chipset, {"845G", "830M", "852GM/855GM", "865G"})) { + return ChipClass::I8XX; + } + + if (containsAny(chipset, {"915G", "E7221G", "915GM", "945G", "945GM", "945GME", "Q33", + "Q35", "G33", "965Q", "946GZ", "IGD"})) { + return ChipClass::I915; + } + + if (containsAny(chipset, {"965G", "G45/G43", "965GM", "965GME/GLE", "GM45", "Q45/Q43", + "G41", "B43", "Ironlake"})) { + return ChipClass::I965; + } + + if (containsAny(chipset, {"Sandybridge", "Sandy Bridge", "SNB GT"})) { + return ChipClass::SandyBridge; + } + if (containsAny(chipset, {"Ivybridge", "Ivy Bridge", "IVB GT"})) { + return ChipClass::IvyBridge; + } + if (containsAny(chipset, {"Haswell", "HSW GT"})) { + return ChipClass::Haswell; + } + if (chipset.contains(QLatin1StringView("BYT"))) { + return ChipClass::BayTrail; + } + if (containsAny(chipset, {"CHV", "BSW"})) { + return ChipClass::Cherryview; + } + if (containsAny(chipset, {"BDW GT", "Broadwell"})) { + return ChipClass::Broadwell; + } + if (containsAny(chipset, {"SKL GT", "Skylake"})) { + return ChipClass::Skylake; + } + if (containsAny(chipset, {"APL", "Apollo Lake"})) { + return ChipClass::ApolloLake; + } + if (containsAny(chipset, {"GLK GT", "Gemini Lake"})) { + return ChipClass::GeminiLake; + } + if (containsAny(chipset, {"KBL GT", "Kaby Lake"})) { + return ChipClass::KabyLake; + } + if (containsAny(chipset, {"WHL GT", "Whiskey Lake"})) { + return ChipClass::WhiskeyLake; + } + if (containsAny(chipset, {"CML GT", "Comet Lake"})) { + return ChipClass::CometLake; + } + if (containsAny(chipset, {"CNL GT", "Cannon Lake"})) { + return ChipClass::CannonLake; + } + if (containsAny(chipset, {"CFL GT", "Coffee Lake"})) { + return ChipClass::CoffeeLake; + } + if (containsAny(chipset, {"ICL GT", "Ice Lake"})) { + return ChipClass::IceLake; + } + if (containsAny(chipset, {"TGL GT", "Tiger Lake"})) { + return ChipClass::TigerLake; + } + + return ChipClass::Unknown; +} + +ChipClass detectAdrenoClass(const QString &chipset) +{ + const QRegularExpressionMatch match = + QRegularExpression(QStringLiteral("Adreno[^0-9]*([0-9]{3})")).match(chipset); + if (!match.hasMatch()) { + return ChipClass::Unknown; + } + + switch (match.captured(1).toInt() / 100) { + case 1: + return ChipClass::Adreno1XX; + case 2: + return ChipClass::Adreno2XX; + case 3: + return ChipClass::Adreno3XX; + case 4: + return ChipClass::Adreno4XX; + case 5: + return ChipClass::Adreno5XX; + default: + return ChipClass::Unknown; + } +} + +ChipClass detectPanfrostClass(const QString &chipset) +{ + // Keep in sync with https://docs.mesa3d.org/drivers/panfrost.html + if (containsAny(chipset, {"T720", "T760"})) { + return ChipClass::MaliT7XX; + } + + if (containsAny(chipset, {"T820", "T830", "T860", "T880"})) { + return ChipClass::MaliT8XX; + } + + if (containsAny(chipset, {"G31", "G51", "G52", "G57", "G72", "G76", "G78", "G310", "G510", + "G610", "G710"})) { + return ChipClass::MaliGXX; + } + + return ChipClass::Unknown; +} + +ChipClass detectLimaClass(const QString &chipset) +{ + if (chipset.contains(QLatin1StringView("400"))) { + return ChipClass::Mali400; + } + if (chipset.contains(QLatin1StringView("450"))) { + return ChipClass::Mali450; + } + if (chipset.contains(QLatin1StringView("470"))) { + return ChipClass::Mali470; + } + return ChipClass::Unknown; +} + +// Panfrost and Lima share the PCI vendor ID and both report "Mali" device +// names; only panvk (Vulkan) and lima (OpenGL) tell them apart in practice. +// shortcut: a Mali GPU using panfrost's GL driver is reported as Lima, upgrade +// once Mesa exposes the kernel driver name through QRhi. +Driver detectMaliDriver(const QString &reported, bool vulkan) +{ + if (reported.contains(QLatin1StringView("panfrost"), Qt::CaseInsensitive)) { + return Driver::Panfrost; + } + if (reported.contains(QLatin1StringView("mali"), Qt::CaseInsensitive)) { + return vulkan ? Driver::Panfrost : Driver::Lima; + } + return Driver::Panfrost; +} + +Driver detectDriver(quint64 vendorId, const QString &reported, bool vulkan) +{ + switch (vendorId) { + case PciVendorAmd: + return Driver::Radeon; + case PciVendorNvidia: + return Driver::NVidia; + case PciVendorIntel: + return Driver::Intel; + case PciVendorQualcomm: + return Driver::Qualcomm; + case PciVendorArm: + return detectMaliDriver(reported, vulkan); + case PciVendorBroadcom: + return reported.contains(QLatin1StringView("V3D"), Qt::CaseInsensitive) + ? Driver::VideoCore3D + : Driver::VideoCore4; + case PciVendorVmware: + return Driver::VMware; + case PciVendorVirtualBox: + return Driver::VirtualBox; + case PciVendorVirtio: + return Driver::Virgl; + default: + break; + } + + // OpenGL does not report PCI IDs, so fall back to the reported string. + if (containsAny(reported, {"llvmpipe", "softpipe", "swrast", "software rasterizer", + "lavapipe", "swiftshader"})) { + return Driver::Software; + } + if (containsAny(reported, {"virtualbox", "humper", "chromium"})) { + return Driver::VirtualBox; + } + if (containsAny(reported, {"vmware", "svga"})) { + return Driver::VMware; + } + if (containsAny(reported, {"virgl", "virtio"})) { + return Driver::Virgl; + } + if (containsAny(reported, {"nvidia", "nouveau", "geforce"})) { + return Driver::NVidia; + } + if (containsAny(reported, {"radeon", "amd", "advanced micro devices"})) { + return Driver::Radeon; + } + if (reported.contains(QLatin1StringView("intel"), Qt::CaseInsensitive)) { + return Driver::Intel; + } + if (containsAny(reported, {"adreno", "qualcomm"})) { + return Driver::Qualcomm; + } + if (containsAny(reported, {"panfrost", "mali"})) { + return detectMaliDriver(reported, vulkan); + } + if (reported.contains(QLatin1StringView("videocore iv"), Qt::CaseInsensitive) + || reported.contains(QLatin1StringView("vc4"), Qt::CaseInsensitive)) { + return Driver::VideoCore4; + } + if (reported.contains(QLatin1StringView("videocore 3d"), Qt::CaseInsensitive) + || reported.contains(QLatin1StringView("v3d"), Qt::CaseInsensitive)) { + return Driver::VideoCore3D; + } + + return Driver::Unknown; +} + +ChipClass detectChipClass(Driver driver, const QString &chipset) +{ + switch (driver) { + case Driver::Radeon: + return detectRadeonClass(chipset); + case Driver::NVidia: + return detectNVidiaClass(chipset); + case Driver::Intel: + return detectIntelClass(chipset); + case Driver::Qualcomm: + return detectAdrenoClass(chipset); + case Driver::Panfrost: + return detectPanfrostClass(chipset); + case Driver::Lima: + return detectLimaClass(chipset); + case Driver::VideoCore4: + return chipset.contains(QLatin1StringView("2.1")) + ? ChipClass::VC4_2_1 + : ChipClass::Unknown; + case Driver::VideoCore3D: + return chipset.contains(QLatin1StringView("4.2")) + ? ChipClass::V3D_4_2 + : ChipClass::Unknown; + default: + return ChipClass::Unknown; + } +} + +QString deviceTypeName(QRhiDriverInfo::DeviceType deviceType) +{ + switch (deviceType) { + case QRhiDriverInfo::IntegratedDevice: + return QStringLiteral("integrated"); + case QRhiDriverInfo::DiscreteDevice: + return QStringLiteral("discrete"); + case QRhiDriverInfo::ExternalDevice: + return QStringLiteral("external"); + case QRhiDriverInfo::VirtualDevice: + return QStringLiteral("virtual"); + case QRhiDriverInfo::CpuDevice: + return QStringLiteral("cpu"); + case QRhiDriverInfo::UnknownDevice: + default: + return QStringLiteral("unknown"); + } +} + +} // namespace + +GraphicsPlatform::GraphicsPlatform(const QRhi *rhi) +{ + if (!rhi) { + return; + } + + const QRhiDriverInfo info = rhi->driverInfo(); + m_deviceName = QString::fromUtf8(info.deviceName).trimmed(); + m_deviceType = deviceTypeName(info.deviceType); + m_driver = detectDriver(info.vendorId, m_deviceName, rhi->backend() == QRhi::Vulkan); + m_chipClass = detectChipClass(m_driver, m_deviceName); + if (info.deviceType == QRhiDriverInfo::CpuDevice) { + m_driver = Driver::Software; + m_chipClass = ChipClass::Unknown; + } + m_virtualMachine = info.deviceType == QRhiDriverInfo::VirtualDevice + || m_driver == Driver::Virgl || m_driver == Driver::VMware + || m_driver == Driver::VirtualBox; +} + +bool GraphicsPlatform::isRadeon() const +{ + return m_driver == Driver::Radeon; +} + +bool GraphicsPlatform::isNvidia() const +{ + return m_driver == Driver::NVidia; +} + +bool GraphicsPlatform::isIntel() const +{ + return m_driver == Driver::Intel; +} + +bool GraphicsPlatform::isAdreno() const +{ + return m_driver == Driver::Qualcomm; +} + +bool GraphicsPlatform::isPanfrost() const +{ + return m_driver == Driver::Panfrost; +} + +bool GraphicsPlatform::isLima() const +{ + return m_driver == Driver::Lima; +} + +bool GraphicsPlatform::isVideoCore4() const +{ + return m_driver == Driver::VideoCore4; +} + +bool GraphicsPlatform::isVideoCore3D() const +{ + return m_driver == Driver::VideoCore3D; +} + +bool GraphicsPlatform::isSoftware() const +{ + return m_driver == Driver::Software; +} + +bool GraphicsPlatform::isVirtualMachine() const +{ + return m_virtualMachine; +} + +QString GraphicsPlatform::toString() const +{ + QString summary = QStringLiteral("%1, %2 (%3), chip class: %4") + .arg(driverToString(m_driver), + m_deviceName.isEmpty() ? QStringLiteral("unknown device") + : m_deviceName, + m_deviceType, + chipClassToString(m_chipClass)); + if (isVirtualMachine()) { + summary += QStringLiteral(", virtual machine"); + } + return summary; +} + +QString GraphicsPlatform::driverToString(Driver driver) +{ + switch (driver) { + case Driver::Radeon: + return QStringLiteral("Radeon"); + case Driver::NVidia: + return QStringLiteral("NVIDIA"); + case Driver::Intel: + return QStringLiteral("Intel"); + case Driver::Qualcomm: + return QStringLiteral("Qualcomm"); + case Driver::Panfrost: + return QStringLiteral("Panfrost"); + case Driver::Lima: + return QStringLiteral("Mali (Lima)"); + case Driver::VideoCore4: + return QStringLiteral("VideoCore IV"); + case Driver::VideoCore3D: + return QStringLiteral("VideoCore 3D"); + case Driver::Virgl: + return QStringLiteral("Virgl (virtio-gpu)"); + case Driver::VMware: + return QStringLiteral("VMware (SVGA3D)"); + case Driver::VirtualBox: + return QStringLiteral("VirtualBox (Chromium)"); + case Driver::Software: + return QStringLiteral("Software rasterizer"); + default: + return QStringLiteral("Unknown"); + } +} + +QString GraphicsPlatform::chipClassToString(ChipClass chipClass) +{ + switch (chipClass) { + case ChipClass::R100: + return QStringLiteral("R100"); + case ChipClass::R200: + return QStringLiteral("R200"); + case ChipClass::R300: + return QStringLiteral("R300"); + case ChipClass::R400: + return QStringLiteral("R400"); + case ChipClass::R500: + return QStringLiteral("R500"); + case ChipClass::R600: + return QStringLiteral("R600"); + case ChipClass::R700: + return QStringLiteral("R700"); + case ChipClass::Evergreen: + return QStringLiteral("Evergreen"); + case ChipClass::NorthernIslands: + return QStringLiteral("Northern Islands"); + case ChipClass::SouthernIslands: + return QStringLiteral("Southern Islands"); + case ChipClass::SeaIslands: + return QStringLiteral("Sea Islands"); + case ChipClass::VolcanicIslands: + return QStringLiteral("Volcanic Islands"); + case ChipClass::ArcticIslands: + return QStringLiteral("Arctic Islands"); + case ChipClass::Vega: + return QStringLiteral("Vega"); + case ChipClass::Navi: + return QStringLiteral("Navi"); + + case ChipClass::NV10: + return QStringLiteral("NV10"); + case ChipClass::NV20: + return QStringLiteral("NV20"); + case ChipClass::NV30: + return QStringLiteral("NV30"); + case ChipClass::NV40: + return QStringLiteral("NV40/G70"); + case ChipClass::G80: + return QStringLiteral("G80/G90"); + case ChipClass::GF100: + return QStringLiteral("GF100"); + case ChipClass::Kepler: + return QStringLiteral("Kepler"); + case ChipClass::Maxwell: + return QStringLiteral("Maxwell"); + case ChipClass::Pascal: + return QStringLiteral("Pascal"); + case ChipClass::Turing: + return QStringLiteral("Turing"); + case ChipClass::Ampere: + return QStringLiteral("Ampere"); + case ChipClass::Ada: + return QStringLiteral("Ada"); + case ChipClass::Blackwell: + return QStringLiteral("Blackwell"); + + case ChipClass::I8XX: + return QStringLiteral("i830/i835"); + case ChipClass::I915: + return QStringLiteral("i915/i945"); + case ChipClass::I965: + return QStringLiteral("i965"); + case ChipClass::SandyBridge: + return QStringLiteral("SandyBridge"); + case ChipClass::IvyBridge: + return QStringLiteral("IvyBridge"); + case ChipClass::Haswell: + return QStringLiteral("Haswell"); + case ChipClass::BayTrail: + return QStringLiteral("Bay Trail"); + case ChipClass::Cherryview: + return QStringLiteral("Cherryview"); + case ChipClass::Broadwell: + return QStringLiteral("Broadwell"); + case ChipClass::ApolloLake: + return QStringLiteral("Apollo Lake"); + case ChipClass::Skylake: + return QStringLiteral("Skylake"); + case ChipClass::GeminiLake: + return QStringLiteral("Gemini Lake"); + case ChipClass::KabyLake: + return QStringLiteral("Kaby Lake"); + case ChipClass::CoffeeLake: + return QStringLiteral("Coffee Lake"); + case ChipClass::WhiskeyLake: + return QStringLiteral("Whiskey Lake"); + case ChipClass::CometLake: + return QStringLiteral("Comet Lake"); + case ChipClass::CannonLake: + return QStringLiteral("Cannon Lake"); + case ChipClass::IceLake: + return QStringLiteral("Ice Lake"); + case ChipClass::TigerLake: + return QStringLiteral("Tiger Lake"); + + case ChipClass::Adreno1XX: + return QStringLiteral("Adreno 1xx series"); + case ChipClass::Adreno2XX: + return QStringLiteral("Adreno 2xx series"); + case ChipClass::Adreno3XX: + return QStringLiteral("Adreno 3xx series"); + case ChipClass::Adreno4XX: + return QStringLiteral("Adreno 4xx series"); + case ChipClass::Adreno5XX: + return QStringLiteral("Adreno 5xx series"); + + case ChipClass::MaliT7XX: + return QStringLiteral("Mali T7xx series"); + case ChipClass::MaliT8XX: + return QStringLiteral("Mali T8xx series"); + case ChipClass::MaliGXX: + return QStringLiteral("Mali Gxx series"); + + case ChipClass::Mali400: + return QStringLiteral("Mali 400 series"); + case ChipClass::Mali450: + return QStringLiteral("Mali 450 series"); + case ChipClass::Mali470: + return QStringLiteral("Mali 470 series"); + + case ChipClass::VC4_2_1: + return QStringLiteral("VideoCore IV"); + case ChipClass::V3D_4_2: + return QStringLiteral("VideoCore 3D"); + + case ChipClass::Unknown: + default: + return QStringLiteral("Unknown"); + } +} diff --git a/src/utils/graphicsplatform.h b/src/utils/graphicsplatform.h new file mode 100644 index 0000000000..f33aefb8a8 --- /dev/null +++ b/src/utils/graphicsplatform.h @@ -0,0 +1,89 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +class QRhi; + +// Identifies the GPU behind the render window: vendor family, chip class and +// the model the driver reports. The render API and its versions are left to +// Qt Quick's GraphicsInfo. +class GraphicsPlatform +{ +public: + enum class Driver { + Radeon, + NVidia, + Intel, + Qualcomm, + Panfrost, + Lima, + VideoCore4, + VideoCore3D, + Virgl, + VMware, + VirtualBox, + Software, + Unknown, + }; + + // clang-format off + enum class ChipClass { + // Radeon + R100, R200, R300, R400, R500, R600, R700, Evergreen, NorthernIslands, + SouthernIslands, SeaIslands, VolcanicIslands, ArcticIslands, Vega, Navi, + // NVIDIA + NV10, NV20, NV30, NV40, G80, GF100, Kepler, Maxwell, Pascal, Turing, + Ampere, Ada, Blackwell, + // Intel + I8XX, I915, I965, SandyBridge, IvyBridge, Haswell, BayTrail, Cherryview, + Broadwell, ApolloLake, Skylake, GeminiLake, KabyLake, CoffeeLake, + WhiskeyLake, CometLake, CannonLake, IceLake, TigerLake, + // Qualcomm Adreno + Adreno1XX, Adreno2XX, Adreno3XX, Adreno4XX, Adreno5XX, + // Panfrost Mali + MaliT7XX, MaliT8XX, MaliGXX, + // Lima Mali + Mali400, Mali450, Mali470, + // Broadcom VideoCore IV and VideoCore 3D + VC4_2_1, V3D_4_2, + Unknown, + }; + // clang-format on + + explicit GraphicsPlatform(const QRhi *rhi); + + Driver driver() const { return m_driver; } + ChipClass chipClass() const { return m_chipClass; } + // Model name exactly as the driver reports it, e.g. + // "NVIDIA GeForce RTX 3060/PCIe/SSE2" on OpenGL; driver suffixes are kept. + QString deviceName() const { return m_deviceName; } + // "integrated", "discrete", "virtual", "cpu" or "unknown". + QString deviceType() const { return m_deviceType; } + + bool isRadeon() const; + bool isNvidia() const; + bool isIntel() const; + bool isAdreno() const; + bool isPanfrost() const; + bool isLima() const; + bool isVideoCore4() const; + bool isVideoCore3D() const; + bool isSoftware() const; + bool isVirtualMachine() const; + + // One line summary for logging. + QString toString() const; + + static QString driverToString(Driver driver); + static QString chipClassToString(ChipClass chipClass); + +private: + bool m_virtualMachine = false; + Driver m_driver = Driver::Unknown; + ChipClass m_chipClass = ChipClass::Unknown; + QString m_deviceName; + QString m_deviceType; +}; diff --git a/src/utils/loginddbustypes.cpp b/src/utils/loginddbustypes.cpp new file mode 100644 index 0000000000..e294de1568 --- /dev/null +++ b/src/utils/loginddbustypes.cpp @@ -0,0 +1,116 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "loginddbustypes.h" +#include "common/treelandlogging.h" + +#include +#include +#include +#include +#include + +class LogindPathInternal +{ +public: + LogindPathInternal(); + bool available = false; + QString serviceName; + QString managerPath; + QString managerIfaceName; + QString sessionIfaceName; + QString seatIfaceName; + QString userIfaceName; +}; + +LogindPathInternal::LogindPathInternal() +{ + qRegisterMetaType("NamedSeatPath"); + qDBusRegisterMetaType(); + + qRegisterMetaType("NamedSeatPathList"); + qDBusRegisterMetaType(); + + qRegisterMetaType("NamedSessionPath"); + qDBusRegisterMetaType(); + + qRegisterMetaType("NamedSessionPathList"); + qDBusRegisterMetaType(); + + qRegisterMetaType("SessionInfo"); + qDBusRegisterMetaType(); + + qRegisterMetaType("SessionInfoList"); + qDBusRegisterMetaType(); + + qRegisterMetaType("UserInfo"); + qDBusRegisterMetaType(); + + qRegisterMetaType("UserInfoList"); + qDBusRegisterMetaType(); + + if (QDBusConnection::systemBus().interface()->isServiceRegistered( + QStringLiteral("org.freedesktop.login1"))) { + qCDebug(lcTlDBus) << "Logind interface found"; + available = true; + serviceName = QStringLiteral("org.freedesktop.login1"); + managerPath = QStringLiteral("/org/freedesktop/login1"); + managerIfaceName = QStringLiteral("org.freedesktop.login1.Manager"); + seatIfaceName = QStringLiteral("org.freedesktop.login1.Seat"); + sessionIfaceName = QStringLiteral("org.freedesktop.login1.Session"); + userIfaceName = QStringLiteral("org.freedesktop.login1.User"); + return; + } + + if (QDBusConnection::systemBus().interface()->isServiceRegistered( + QStringLiteral("org.freedesktop.ConsoleKit"))) { + qCDebug(lcTlDBus) << "Console kit interface found"; + available = true; + serviceName = QStringLiteral("org.freedesktop.ConsoleKit"); + managerPath = QStringLiteral("/org/freedesktop/ConsoleKit/Manager"); + managerIfaceName = + QStringLiteral("org.freedesktop.ConsoleKit.Manager"); // note this doesn't match logind + seatIfaceName = QStringLiteral("org.freedesktop.ConsoleKit.Seat"); + sessionIfaceName = QStringLiteral("org.freedesktop.ConsoleKit.Session"); + userIfaceName = QStringLiteral("org.freedesktop.ConsoleKit.User"); + return; + } + qCDebug(lcTlDBus) << "No session manager found"; +} + +Q_GLOBAL_STATIC(LogindPathInternal, s_instance); + +bool Logind::isAvailable() +{ + return s_instance->available; +} + +QString Logind::serviceName() +{ + return s_instance->serviceName; +} + +QString Logind::managerPath() +{ + return s_instance->managerPath; +} + +QString Logind::managerIfaceName() +{ + return s_instance->managerIfaceName; +} + +QString Logind::seatIfaceName() +{ + return s_instance->seatIfaceName; +} + +QString Logind::sessionIfaceName() +{ + return s_instance->sessionIfaceName; +} + +QString Logind::userIfaceName() +{ + return s_instance->userIfaceName; +} diff --git a/src/utils/loginddbustypes.h b/src/utils/loginddbustypes.h new file mode 100644 index 0000000000..cbdeb75a68 --- /dev/null +++ b/src/utils/loginddbustypes.h @@ -0,0 +1,196 @@ +// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef LOGIND_DBUSTYPES +#define LOGIND_DBUSTYPES + +#include +#include + +struct Logind +{ + static bool isAvailable(); + static QString serviceName(); + static QString managerPath(); + static QString managerIfaceName(); + static QString sessionIfaceName(); + static QString seatIfaceName(); + static QString userIfaceName(); +}; + +struct SessionInfo +{ + QString sessionId; + uint userId; + QString userName; + QString seatId; + QDBusObjectPath sessionPath; +}; + +typedef QList SessionInfoList; + +inline QDBusArgument &operator<<(QDBusArgument &argument, const SessionInfo &sessionInfo) +{ + argument.beginStructure(); + argument << sessionInfo.sessionId; + argument << sessionInfo.userId; + argument << sessionInfo.userName; + argument << sessionInfo.seatId; + argument << sessionInfo.sessionPath; + argument.endStructure(); + + return argument; +} + +inline const QDBusArgument &operator>>(const QDBusArgument &argument, SessionInfo &sessionInfo) +{ + argument.beginStructure(); + argument >> sessionInfo.sessionId; + argument >> sessionInfo.userId; + argument >> sessionInfo.userName; + argument >> sessionInfo.seatId; + argument >> sessionInfo.sessionPath; + argument.endStructure(); + + return argument; +} + +struct UserInfo +{ + uint userId; + QString name; + QDBusObjectPath path; +}; + +typedef QList UserInfoList; + +inline QDBusArgument &operator<<(QDBusArgument &argument, const UserInfo &userInfo) +{ + argument.beginStructure(); + argument << userInfo.userId; + argument << userInfo.name; + argument << userInfo.path; + argument.endStructure(); + + return argument; +} + +inline const QDBusArgument &operator>>(const QDBusArgument &argument, UserInfo &userInfo) +{ + argument.beginStructure(); + argument >> userInfo.userId; + argument >> userInfo.name; + argument >> userInfo.path; + argument.endStructure(); + + return argument; +} + +struct NamedSeatPath +{ + QString name; + QDBusObjectPath path; +}; + +inline QDBusArgument &operator<<(QDBusArgument &argument, const NamedSeatPath &namedSeat) +{ + argument.beginStructure(); + argument << namedSeat.name; + argument << namedSeat.path; + argument.endStructure(); + return argument; +} + +inline const QDBusArgument &operator>>(const QDBusArgument &argument, NamedSeatPath &namedSeat) +{ + argument.beginStructure(); + argument >> namedSeat.name; + argument >> namedSeat.path; + argument.endStructure(); + return argument; +} + +typedef QList NamedSeatPathList; + +typedef NamedSeatPath NamedSessionPath; +typedef NamedSeatPathList NamedSessionPathList; + +class NamedUserPath +{ +public: + uint userId; + QDBusObjectPath path; +}; + +inline QDBusArgument &operator<<(QDBusArgument &argument, const NamedUserPath &namedUser) +{ + argument.beginStructure(); + argument << namedUser.userId; + argument << namedUser.path; + argument.endStructure(); + return argument; +} + +inline const QDBusArgument &operator>>(const QDBusArgument &argument, NamedUserPath &namedUser) +{ + argument.beginStructure(); + argument >> namedUser.userId; + argument >> namedUser.path; + argument.endStructure(); + return argument; +} + +class Inhibitor +{ +public: + QString what; + QString who; + QString why; + QString mode; + int userId; + uint processId; +}; + +typedef QList InhibitorList; + +inline QDBusArgument &operator<<(QDBusArgument &argument, const Inhibitor &inhibitor) +{ + argument.beginStructure(); + argument << inhibitor.what; + argument << inhibitor.who; + argument << inhibitor.why; + argument << inhibitor.mode; + argument << inhibitor.userId; + argument << inhibitor.processId; + argument.endStructure(); + return argument; +} + +inline const QDBusArgument &operator>>(const QDBusArgument &argument, Inhibitor &inhibitor) +{ + argument.beginStructure(); + argument >> inhibitor.what; + argument >> inhibitor.who; + argument >> inhibitor.why; + argument >> inhibitor.mode; + argument >> inhibitor.userId; + argument >> inhibitor.processId; + argument.endStructure(); + return argument; +} + +Q_DECLARE_METATYPE(SessionInfo); +Q_DECLARE_METATYPE(QList); + +Q_DECLARE_METATYPE(UserInfo); +Q_DECLARE_METATYPE(QList); + +Q_DECLARE_METATYPE(NamedSeatPath); +Q_DECLARE_METATYPE(QList); + +Q_DECLARE_METATYPE(NamedUserPath); + +Q_DECLARE_METATYPE(Inhibitor); +Q_DECLARE_METATYPE(QList); + +#endif diff --git a/src/utils/propertymonitor.cpp b/src/utils/propertymonitor.cpp new file mode 100644 index 0000000000..4931a7e55b --- /dev/null +++ b/src/utils/propertymonitor.cpp @@ -0,0 +1,75 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "propertymonitor.h" +#include "common/treelandlogging.h" + +#include + +PropertyMonitor::PropertyMonitor(QObject *parent) + : QObject(parent) + , m_target(parent) +{ +} + +QObject *PropertyMonitor::target() const +{ + return m_target; +} + +void PropertyMonitor::setTarget(QObject *newTarget) +{ + if (m_target == newTarget) + return; + if (m_target) + disconnect(m_target, nullptr, this, SLOT(handlePropertyChanged())); + m_target = newTarget; + connectToTarget(); + Q_EMIT targetChanged(); +} + +QString PropertyMonitor::properties() const +{ + return m_properties; +} + +void PropertyMonitor::setProperties(const QString &newProperties) +{ + if (m_properties == newProperties) + return; + m_properties = newProperties; + connectToTarget(); + Q_EMIT propertiesChanged(); +} + +void PropertyMonitor::handlePropertyChanged() +{ + auto index = senderSignalIndex(); + for (const auto &mProp : std::as_const(m_metaProps)) { + if (mProp.hasNotifySignal() && mProp.notifySignalIndex() == index) { + qCDebug(lcTlPropertyMonitor) << m_target << mProp.name() << mProp.read(m_target); + break; + } + } +} + +void PropertyMonitor::connectToTarget() +{ + static const auto slotIndex = metaObject()->indexOfSlot("handlePropertyChanged()"); + static auto slot = metaObject()->method(slotIndex); + if (!m_target || m_properties.isEmpty()) + return; + disconnect(m_target, nullptr, this, SLOT(handlePropertyChanged())); + m_metaProps.clear(); + auto propertyList = m_properties.split(","); + for (const auto &property : std::as_const(propertyList)) { + auto index = + m_target->metaObject()->indexOfProperty(property.trimmed().toStdString().c_str()); + if (index != -1) { + auto mProp = m_target->metaObject()->property(index); + m_metaProps.append(mProp); + if (mProp.hasNotifySignal()) { + connect(m_target, mProp.notifySignal(), this, slot); + } + } + } +} diff --git a/src/utils/propertymonitor.h b/src/utils/propertymonitor.h new file mode 100644 index 0000000000..64366350fe --- /dev/null +++ b/src/utils/propertymonitor.h @@ -0,0 +1,37 @@ +// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include +#include + +class PropertyMonitor : public QObject +{ + Q_OBJECT + QML_ELEMENT + Q_PROPERTY(QObject *target READ target WRITE setTarget NOTIFY targetChanged FINAL) + Q_PROPERTY(QString properties READ properties WRITE setProperties NOTIFY propertiesChanged REQUIRED FINAL) + +public: + explicit PropertyMonitor(QObject *parent = nullptr); + + QObject *target() const; + void setTarget(QObject *newTarget); + + QString properties() const; + void setProperties(const QString &newProperties); + +public Q_SLOTS: + void handlePropertyChanged(); + +Q_SIGNALS: + void targetChanged(); + void propertiesChanged(); + +private: + void connectToTarget(); + + QObject *m_target = nullptr; + QString m_properties; + QList m_metaProps; +}; diff --git a/src/utils/scriptrunner.cpp b/src/utils/scriptrunner.cpp new file mode 100644 index 0000000000..2021ad0f23 --- /dev/null +++ b/src/utils/scriptrunner.cpp @@ -0,0 +1,144 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "scriptrunner.h" +#include "common/treelandlogging.h" + +#include +#include +#include +#include +#include +#include +#include + +ScriptRunner::ScriptRunner(const QString &waylandDisplay, QObject *parent) + : QObject(parent) + , m_waylandDisplay(waylandDisplay) +{ +} + +void ScriptRunner::append(const QString &dir, Type type) +{ + scanDirectory(dir, type); + + if (type == Blocking && !m_blockingRunning && !m_blockingScripts.isEmpty()) { + m_blockingRunning = true; + runNext(Blocking); + } +} + +void ScriptRunner::start() +{ + if (m_blockingRunning) { + return; + } + + if (!m_blockingScripts.isEmpty()) { + m_blockingRunning = true; + runNext(Blocking); + } else { + qCInfo(lcTlHooks) << "No blocking scripts, signaling blocking finished"; + Q_EMIT blockingFinished(); + } +} + +void ScriptRunner::startNonBlocking() +{ + runNext(NonBlocking); +} + +void ScriptRunner::scanDirectory(const QString &dir, Type type) +{ + QCollator collator; + collator.setNumericMode(true); + + QDir qdir(dir); + if (!qdir.exists()) { + return; + } + + auto entries = qdir.entryInfoList(QDir::Files | QDir::Executable | QDir::NoDotAndDotDot); + std::sort(entries.begin(), entries.end(), + [&collator](const QFileInfo &a, const QFileInfo &b) { + return collator(a.fileName(), b.fileName()); + }); + + for (const auto &entry : std::as_const(entries)) { + switch (type) { + case Blocking: + m_blockingScripts.enqueue(entry.absoluteFilePath()); + qCInfo(lcTlHooks) << "Enqueued blocking script:" << entry.absoluteFilePath(); + break; + case NonBlocking: + m_nonBlockingScripts.enqueue(entry.absoluteFilePath()); + qCInfo(lcTlHooks) << "Enqueued non-blocking script:" << entry.absoluteFilePath(); + break; + } + } +} + +void ScriptRunner::runNext(Type type) +{ + auto &queue = (type == Blocking) ? m_blockingScripts : m_nonBlockingScripts; + + if (queue.isEmpty()) { + if (type == Blocking) { + m_blockingRunning = false; + qCInfo(lcTlHooks) << "All blocking scripts finished"; + Q_EMIT blockingFinished(); + } else { + qCInfo(lcTlHooks) << "All non-blocking scripts finished"; + } + return; + } + + const auto script = queue.dequeue(); + auto *process = createProcess(script); + connect(process, QOverload::of(&QProcess::finished), + this, [this, type, process](int exitCode, QProcess::ExitStatus) { + if (exitCode != 0) { + qCWarning(lcTlHooks) << (type == Blocking ? "Blocking" : "Non-blocking") + << "script exited with code" << exitCode << ":" << process->program(); + } + runNext(type); + }); + connect(process, &QProcess::errorOccurred, this, [this, type, process](QProcess::ProcessError error) { + if (error == QProcess::FailedToStart) { + qCWarning(lcTlHooks) << (type == Blocking ? "Blocking" : "Non-blocking") + << "script failed to start:" << process->program(); + runNext(type); + } + }); + qCInfo(lcTlHooks) << "Starting" << (type == Blocking ? "blocking" : "non-blocking") + << "script:" << process->program(); + process->start(); +} +QProcess *ScriptRunner::createProcess(const QString &script) const +{ + auto *process = new QProcess(const_cast(this)); + const auto scriptName = QFileInfo(script).fileName(); + + auto env = QProcessEnvironment::systemEnvironment(); + env.insert(QStringLiteral("WAYLAND_DISPLAY"), m_waylandDisplay); + process->setProcessEnvironment(env); + process->setProgram(script); + + connect(process, &QProcess::readyReadStandardOutput, this, [process, scriptName]() { + const auto data = process->readAllStandardOutput(); + for (const auto &line : QString::fromUtf8(data).split(QStringLiteral("\n"), Qt::SkipEmptyParts)) { + qCInfo(lcTlHooks).noquote() << "[" << scriptName << "]" << line; + } + }); + connect(process, &QProcess::readyReadStandardError, this, [process, scriptName]() { + const auto data = process->readAllStandardError(); + for (const auto &line : QString::fromUtf8(data).split(QStringLiteral("\n"), Qt::SkipEmptyParts)) { + qCWarning(lcTlHooks).noquote() << "[" << scriptName << "]" << line; + } + }); + + connect(process, QOverload::of(&QProcess::finished), + process, &QObject::deleteLater); + + return process; +} diff --git a/src/utils/scriptrunner.h b/src/utils/scriptrunner.h new file mode 100644 index 0000000000..549663c86e --- /dev/null +++ b/src/utils/scriptrunner.h @@ -0,0 +1,41 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +class QProcess; + +class ScriptRunner : public QObject +{ + Q_OBJECT +public: + enum Type { + Blocking, + NonBlocking + }; + Q_ENUM(Type) + + explicit ScriptRunner(const QString &waylandDisplay, QObject *parent = nullptr); + + void append(const QString &dir, Type type); + +public Q_SLOTS: + void start(); + void startNonBlocking(); + +Q_SIGNALS: + void blockingFinished(); + +private: + void scanDirectory(const QString &dir, Type type); + void runNext(Type type); + QProcess *createProcess(const QString &script) const; + + QQueue m_blockingScripts; + QQueue m_nonBlockingScripts; + QString m_waylandDisplay; + bool m_blockingRunning = false; +}; diff --git a/src/wallpaper/wallpaperconfig.cpp b/src/wallpaper/wallpaperconfig.cpp new file mode 100644 index 0000000000..66d3d7096d --- /dev/null +++ b/src/wallpaper/wallpaperconfig.cpp @@ -0,0 +1,70 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wallpaperconfig.h" + +#define OUTPUT_NAME "outputName" +#define LOCK_SCREEN_WALLAPER_TYPE "lockScreenWallpaperType" +#define DESKTOP_WALLAPER_TYPE "desktopWallpaperType" +#define WORKSPACE_INDEX "workspaceIndex" +#define DESKTOP_WALLPAPER "desktopWallpaper" +#define LOCK_SCREEN_WALLPAPER "lockScreenWallpaper" +#define WORKSPACES "workspaces" + +QJsonObject WallpaperWorkspaceConfig::toJson() const +{ + QJsonObject obj; + obj[WORKSPACE_INDEX] = workspaceId; + obj[DESKTOP_WALLPAPER] = desktopWallpaper; + obj[DESKTOP_WALLAPER_TYPE] = desktopWallpapertype; + return obj; +} + +WallpaperWorkspaceConfig WallpaperWorkspaceConfig::fromJson(const QJsonObject &obj) +{ + WallpaperWorkspaceConfig ws; + ws.workspaceId = obj[WORKSPACE_INDEX].toInt(); + ws.desktopWallpaper = obj[DESKTOP_WALLPAPER].toString(); + ws.desktopWallpapertype = static_cast(obj[DESKTOP_WALLAPER_TYPE].toInt()); + return ws; +} + +QJsonObject WallpaperOutputConfig::toJson() const +{ + QJsonObject obj; + obj[OUTPUT_NAME] = outputName; + obj[LOCK_SCREEN_WALLPAPER] = lockscreenWallpaper; + obj[LOCK_SCREEN_WALLAPER_TYPE] = lockScreenWallpapertype; + QJsonArray workspacesArray; + for (const WallpaperWorkspaceConfig& ws : std::as_const(workspaces)) { + workspacesArray.append(ws.toJson()); + } + obj[WORKSPACES] = workspacesArray; + + return obj; +} + +bool WallpaperOutputConfig::containsWorkspace(int id) const +{ + for (const WallpaperWorkspaceConfig& ws : std::as_const(workspaces)) { + if (ws.workspaceId == id) { + return true; + } + } + + return false; +} + +WallpaperOutputConfig WallpaperOutputConfig::fromJson(const QJsonObject &obj) +{ + WallpaperOutputConfig out; + out.outputName = obj[OUTPUT_NAME].toString(); + out.lockscreenWallpaper = obj[LOCK_SCREEN_WALLPAPER].toString(); + out.lockScreenWallpapertype = static_cast(obj[LOCK_SCREEN_WALLAPER_TYPE].toInt()); + QJsonArray workspacesArray = obj[WORKSPACES].toArray(); + for (const QJsonValue& value : std::as_const(workspacesArray)) { + out.workspaces.append(WallpaperWorkspaceConfig::fromJson(value.toObject())); + } + + return out; +} diff --git a/src/wallpaper/wallpaperconfig.h b/src/wallpaper/wallpaperconfig.h new file mode 100644 index 0000000000..2712b1785f --- /dev/null +++ b/src/wallpaper/wallpaperconfig.h @@ -0,0 +1,34 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "modules/wallpaper/wallpapermanagerinterfacev1.h" + +#include +#include +#include + +class WallpaperWorkspaceConfig { +public: + int workspaceId; + QString desktopWallpaper; + TreelandWallpaperInterfaceV1::WallpaperType desktopWallpapertype; + + QJsonObject toJson() const; + + static WallpaperWorkspaceConfig fromJson(const QJsonObject& obj); +}; + +class WallpaperOutputConfig { +public: + QString outputName; + QString lockscreenWallpaper; + QList workspaces; + TreelandWallpaperInterfaceV1::WallpaperType lockScreenWallpapertype; + + QJsonObject toJson() const; + bool containsWorkspace(int id) const; + + static WallpaperOutputConfig fromJson(const QJsonObject& obj); +}; diff --git a/src/wallpaper/wallpaperitem.cpp b/src/wallpaper/wallpaperitem.cpp new file mode 100644 index 0000000000..cbc66ed16e --- /dev/null +++ b/src/wallpaper/wallpaperitem.cpp @@ -0,0 +1,237 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wallpaperitem.h" + +#include "core/qmlengine.h" +#include "core/waylandserver.h" +#include "workspace/workspacemodel.h" +#include "wallpapershellinterfacev1.h" +#include "wallpaper/wallpapermanager.h" +#include "workspace.h" +#include "shellhandler.h" +#include "greeterproxy.h" + +#include +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +WallpaperItem::WallpaperItem(QQuickItem *parent) + : WallpaperItem(parent, true) +{ +} + +WallpaperItem::WallpaperItem(QQuickItem *parent, bool autoUpdate) + : WSurfaceItemContent(parent) + , m_autoUpdate(autoUpdate) +{ + if (autoUpdate) { + connect(WaylandServer::instance(), + &WaylandServer::activeSessionChanged, + this, + &WallpaperItem::handleCurrentuserChanged); + connect(WaylandServer::instance()->shellHandler()->wallpaperShell(), + &TreelandWallpaperShellInterfaceV1::wallpaperSurfaceAdded, + this, + &WallpaperItem::handleWallpaperSurfaceAdded); + connect(WaylandServer::instance(), + &WaylandServer::wallpaperChanged, + this, + &WallpaperItem::updateSurface); + connect(WaylandServer::instance(), + &WaylandServer::workspaceAdded, + this, + &WallpaperItem::handleWorkspaceAdded); + } +} + +WallpaperItem::~WallpaperItem() = default; + +WorkspaceModel *WallpaperItem::workspace() +{ + return m_workspace; +} + +void WallpaperItem::setWorkspace(WorkspaceModel *workspace) +{ + if (m_workspace == workspace) { + return; + } + + if (m_workspace && m_workspace->workspaceManager()->wallpaperManager()) + disconnect(m_workspace->workspaceManager()->wallpaperManager(), + &WallpaperManager::updateWallpaper, this, &WallpaperItem::updateSurface); + m_workspace = workspace; + if (m_autoUpdate && m_workspace && m_workspace->workspaceManager()->wallpaperManager()) + connect(m_workspace->workspaceManager()->wallpaperManager(), + &WallpaperManager::updateWallpaper, this, &WallpaperItem::updateSurface); + Q_EMIT workspaceChanged(); + if (wallpaperRole() == Lockscreen) + return; + + updateSurface(); +} + +WOutput *WallpaperItem::output() +{ + return m_output; +} + +void WallpaperItem::setOutput(WOutput *output) +{ + if (m_output == output) { + return; + } + + m_output = output; + Q_EMIT outputChanged(); + updateSurface(); +} + +void WallpaperItem::setWallpaperRole(WallpaperRole role) +{ + if (m_wallpaperRole == role) { + return; + } + + m_wallpaperRole = role; + Q_EMIT wallpaperRoleChanged(); + updateSurface(); +} + +void WallpaperItem::setWallpaperState(WallpaperState state) +{ + if (m_state == state) { + return; + } + + m_state = state; + Q_EMIT wallpaperStateChanged(); +} + +WallpaperItem::WallpaperState WallpaperItem::wallpaperState() +{ + return m_state; +} + +QString WallpaperItem::source() const +{ + return m_source; +} + +bool WallpaperItem::play() const +{ + return m_play; +} + +void WallpaperItem::setPlay(bool value) +{ + TreelandWallpaperSurfaceInterfaceV1 *interface = + TreelandWallpaperSurfaceInterfaceV1::get(source()); + if (!interface) { + return; + } + interface->setPlay(value); + m_play = value; + Q_EMIT playChanged(); +} + +void WallpaperItem::slowDown() +{ + TreelandWallpaperSurfaceInterfaceV1 *interface = + TreelandWallpaperSurfaceInterfaceV1::get(source()); + if (!interface) { + return; + } + + interface->slowDown(); +} + +void WallpaperItem::handleCurrentuserChanged() +{ + updateSurface(); +} + +WallpaperItem::WallpaperRole WallpaperItem::wallpaperRole() +{ + return m_wallpaperRole; +} + +void WallpaperItem::updateSurface() +{ + if (!output()) { + return; + } + + if (wallpaperRole() == Desktop && !workspace()) { + return; + } + + auto *manager = workspace() && wallpaperRole() == Desktop + ? workspace()->workspaceManager()->wallpaperManager() + : WaylandServer::instance()->wallpaperManager(); + if (!manager) + return; + const auto config = manager->getOutputConfig(output()->handle()); + if (wallpaperRole() == Lockscreen) { + if (config.lockscreenWallpaper != m_source) { + TreelandWallpaperSurfaceInterfaceV1 *interface = + TreelandWallpaperSurfaceInterfaceV1::get(config.lockscreenWallpaper); + if (!interface) { + return; + } + m_source = config.lockscreenWallpaper; + setSurface(interface->wSurface()); + interface->wSurface()->enterOutput(output()); + update(); + } + return; + } + + if (wallpaperRole() == Desktop) { + const QString source = manager->desktopWallpaper(output(), workspace()); + if (source.isEmpty()) + return; + auto *interface = TreelandWallpaperSurfaceInterfaceV1::get(source); + if (!interface || !interface->wallpaperReady()) + return; + if (source == m_source && surface() == interface->wSurface()) + return; + m_source = source; + setSurface(interface->wSurface()); + interface->wSurface()->enterOutput(output()); + update(); + if (!WaylandServer::instance()->m_greeterProxy->isLocked()) + setPlay(false); + } +} + +void WallpaperItem::handleWorkspaceAdded() +{ + if (wallpaperRole() == Lockscreen) { + return; + } + + if (!output() || !workspace()) { + return; + } + + updateSurface(); +} + +void WallpaperItem::handleWallpaperSurfaceAdded(TreelandWallpaperSurfaceInterfaceV1 *interface) +{ + if (interface->wallpaperReady()) { + updateSurface(); + } else { + connect(interface, + &TreelandWallpaperSurfaceInterfaceV1::ready, + this, + &WallpaperItem::updateSurface, + Qt::SingleShotConnection); + } +} diff --git a/src/wallpaper/wallpaperitem.h b/src/wallpaper/wallpaperitem.h new file mode 100644 index 0000000000..38a38cacae --- /dev/null +++ b/src/wallpaper/wallpaperitem.h @@ -0,0 +1,97 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "wglobal.h" +#include "wsurfaceitem.h" +#include "greeter/usermodel.h" + +Q_MOC_INCLUDE("workspace/workspace.h") + +class TreelandWallpaperSurfaceInterfaceV1; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutput; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class WorkspaceModel; + +class WallpaperItem : public WSurfaceItemContent +{ + Q_OBJECT + Q_PROPERTY(WorkspaceModel* workspace READ workspace WRITE setWorkspace NOTIFY workspaceChanged FINAL) + Q_PROPERTY(WAYLIB_SERVER_NAMESPACE::WOutput* output READ output WRITE setOutput NOTIFY outputChanged FINAL) + Q_PROPERTY(WallpaperRole wallpaperRole READ wallpaperRole WRITE setWallpaperRole NOTIFY wallpaperRoleChanged FINAL) + Q_PROPERTY(QString source READ source FINAL) + Q_PROPERTY(WallpaperState wallpaperState READ wallpaperState WRITE setWallpaperState NOTIFY wallpaperStateChanged FINAL) + Q_PROPERTY(bool play READ play WRITE setPlay NOTIFY playChanged FINAL) + + QML_NAMED_ELEMENT(Wallpaper) + QML_ADDED_IN_VERSION(1, 0) + +public: + enum WallpaperRole { + Desktop = 0x1, + Lockscreen = 0x2 + }; + Q_ENUM(WallpaperRole) + + enum WallpaperState + { + Normal, + Scale, + ScaleWithoutAnimation, + }; + Q_ENUM(WallpaperState) + + WallpaperItem(QQuickItem *parent = nullptr); + ~WallpaperItem(); + + WorkspaceModel *workspace(); + void setWorkspace(WorkspaceModel *workspace); + + WOutput *output(); + void setOutput(WOutput *output); + + enum WallpaperRole wallpaperRole(); + void setWallpaperRole(enum WallpaperRole role); + + enum WallpaperState wallpaperState(); + void setWallpaperState(enum WallpaperState state); + + QString source() const; + + bool play() const; + void setPlay(bool value); + + Q_INVOKABLE void slowDown(); + void updateSurface(); + +Q_SIGNALS: + void outputChanged(); + void workspaceChanged(); + void wallpaperRoleChanged(); + void wallpaperStateChanged(); + void playChanged(); + +private Q_SLOTS: + void handleCurrentuserChanged(); + void handleWorkspaceAdded(); + void handleWallpaperSurfaceAdded(TreelandWallpaperSurfaceInterfaceV1 *interface); + +protected: + WallpaperItem(QQuickItem *parent, bool autoUpdate); + +private: + const bool m_autoUpdate; + int m_userId = -1; + QPointer m_workspace = nullptr; + QPointer m_output = nullptr; + enum WallpaperRole m_wallpaperRole = Desktop; + enum WallpaperState m_state = Normal; + QString m_source; + bool m_play = true; +}; diff --git a/src/wallpaper/wallpaperlauncher.cpp b/src/wallpaper/wallpaperlauncher.cpp new file mode 100644 index 0000000000..2053985557 --- /dev/null +++ b/src/wallpaper/wallpaperlauncher.cpp @@ -0,0 +1,173 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wallpaperlauncher.h" +#include "common/treelandlogging.h" +#include "core/waylandserver.h" + +#include + +#include +#ifdef Q_OS_LINUX +#include +#endif + +WallpaperLauncher::WallpaperLauncher(QPointer socket) + : QObject(nullptr) + , m_socket(socket) +{ + m_launcherThread = new QThread(); + this->moveToThread(m_launcherThread); + m_launcherThread->start(); +} + +WallpaperLauncher::~WallpaperLauncher() +{ + if (m_launcherThread) { + QMetaObject::invokeMethod(this, + &WallpaperLauncher::onStopRequested, + Qt::BlockingQueuedConnection); + m_launcherThread->quit(); + m_launcherThread->wait(); + m_launcherThread->deleteLater(); + } +} +QString WallpaperLauncher::wallpaperProgram() +{ +#ifdef TREELAND_USE_BUILD_TREE_WALLPAPER_FACTORY + return QStringLiteral(TREELAND_WALLPAPER_FACTORY_OUTPUT_PATH); +#else + return QStringLiteral("treeland-wallpaper-factory"); +#endif +} + +void WallpaperLauncher::setDisplayName(const QString &displayName) +{ + QMetaObject::invokeMethod(this, + &WallpaperLauncher::onSetDisplayNameRequested, + Qt::QueuedConnection, + displayName); +} + +void WallpaperLauncher::start() +{ + QMetaObject::invokeMethod(this, + &WallpaperLauncher::onStartRequested, + Qt::QueuedConnection); +} + +void WallpaperLauncher::stop() +{ + QMetaObject::invokeMethod(this, + &WallpaperLauncher::onStopRequested, + Qt::QueuedConnection); +} + +void WallpaperLauncher::onSetDisplayNameRequested(const QString &displayName) +{ + if (m_displayName == displayName) { + return; + } + + m_displayName = displayName; +} + +void WallpaperLauncher::onStartRequested() +{ + if (m_wallpaperProcess) { + qCDebug(lcTlWallpaper) << "Wallpaper already running or start requested."; + return; + } + + m_crashCount = 0; + m_wallpaperProcess = new QProcess(this); + m_wallpaperProcess->setProgram(wallpaperProgram()); + m_wallpaperProcess->setProcessChannelMode(QProcess::MergedChannels); +#ifdef Q_OS_LINUX + // Runs in the forked child before exec. A compositor that exits without + // running Qt teardown (_Exit, crash, SIGKILL) would otherwise orphan the + // factory; let the kernel send SIGTERM when the parent goes away. + m_wallpaperProcess->setChildProcessModifier([] { + ::prctl(PR_SET_PDEATHSIG, SIGTERM); + }); +#endif + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + env.insert("WAYLAND_DISPLAY", m_socket->fullServerName()); + env.insert("QT_QPA_PLATFORM", "wayland"); + m_wallpaperProcess->setProcessEnvironment(env); + connect(m_wallpaperProcess, + &QProcess::errorOccurred, + this, + &WallpaperLauncher::handleWallpaperError); + connect(m_wallpaperProcess, + QOverload::of(&QProcess::finished), + this, + &WallpaperLauncher::handleWallpaperFinished); + m_wallpaperProcess->start(); +} + +void WallpaperLauncher::onStopRequested() +{ + if (!m_wallpaperProcess) { + qCDebug(lcTlWallpaper) << "Wallpaper not running or stop already requested."; + return; + } + + Q_EMIT finished(); + + if (m_wallpaperProcess->state() != QProcess::NotRunning) { + disconnect(m_wallpaperProcess, nullptr, this, nullptr); + m_wallpaperProcess->terminate(); + m_wallpaperProcess->waitForFinished(5000); + } + delete m_wallpaperProcess; + m_wallpaperProcess = nullptr; +} + +void WallpaperLauncher::handleWallpaperFinished(int exitCode, QProcess::ExitStatus exitStatus) +{ + if (exitStatus == QProcess::NormalExit && exitCode == 0) { + stop(); + return; + } + + ++m_crashCount; + if (m_crashCount > MaxCrashCount) { + qCCritical(lcTlWallpaper) << "Wallpaper process restart limit reached after" + << m_crashCount << "abnormal exits"; + stop(); + return; + } + + QProcessEnvironment env = m_wallpaperProcess->processEnvironment(); + env.insert("TREELAND_WALLPAPER_RESTART_COUNT", QString::number(m_crashCount)); + m_wallpaperProcess->setProcessEnvironment(env); + + qCWarning(lcTlWallpaper) << "Restarting wallpaper process after abnormal exit; exit code:" + << exitCode << "restart count:" << m_crashCount; + m_wallpaperProcess->start(); +} + +void WallpaperLauncher::handleWallpaperError(QProcess::ProcessError error) +{ + switch (error) { + case QProcess::FailedToStart: + qCCritical(lcTlWallpaper) << "Wallpaper process failed to start"; + break; + case QProcess::Crashed: + qCCritical(lcTlWallpaper) << "Wallpaper process crashed"; + break; + case QProcess::Timedout: + qCCritical(lcTlWallpaper) << "Wallpaper operation timed out"; + break; + case QProcess::WriteError: + case QProcess::ReadError: + qCCritical(lcTlWallpaper) << "An error occurred while communicating with Wallpaper"; + break; + case QProcess::UnknownError: + qCCritical(lcTlWallpaper) << "An unknown error has occurred in Wallpaper"; + break; + } + + Q_EMIT errorOccurred(); +} diff --git a/src/wallpaper/wallpaperlauncher.h b/src/wallpaper/wallpaperlauncher.h new file mode 100644 index 0000000000..062c904257 --- /dev/null +++ b/src/wallpaper/wallpaperlauncher.h @@ -0,0 +1,47 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "wsocket.h" + +#include +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class WallpaperLauncher : public QObject +{ + Q_OBJECT +public: + explicit WallpaperLauncher(QPointer socket); + ~WallpaperLauncher() override; + static QString wallpaperProgram(); + + void setDisplayName(const QString &displayName); + void start(); + void stop(); + +Q_SIGNALS: + void started(const QString &displayName); + void finished(); + void errorOccurred(); + +private Q_SLOTS: + void onSetDisplayNameRequested(const QString &displayName); + void onStartRequested(); + void onStopRequested(); + + void handleWallpaperFinished(int exitCode, QProcess::ExitStatus exitStatus); + void handleWallpaperError(QProcess::ProcessError error); + +private: + static constexpr int MaxCrashCount = 10; + + QPointer m_socket = nullptr; + QThread *m_launcherThread = nullptr; + QProcess *m_wallpaperProcess = nullptr; + QString m_displayName; + int m_crashCount = 0; +}; diff --git a/src/wallpaper/wallpapermanager.cpp b/src/wallpaper/wallpapermanager.cpp new file mode 100644 index 0000000000..e107b22015 --- /dev/null +++ b/src/wallpaper/wallpapermanager.cpp @@ -0,0 +1,528 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include "wallpapermanager.h" +#include "dconfig/dconfigmanager.h" +#include "workspace.h" +#include "modules/wallpaper/wallpapernotifierinterfacev1.h" +#include "treelanduserconfig.hpp" +#include "common/treelandlogging.h" +#include "modules/wallpaper/wallpapershellinterfacev1.h" + +#include +#include + +#define DEFAULT_WALLPAPER "/usr/share/wallpapers/deepin/deepin-default.jpg" + +enum class WallpaperType { + Image, + Video, + Unknown +}; + +static WallpaperType detectWallpaperType(const QString &path) +{ + if (path.isEmpty()) + return WallpaperType::Unknown; + + static QMimeDatabase db; + const QMimeType mime = db.mimeTypeForFile(path, QMimeDatabase::MatchContent); + if (mime.isValid() && mime.name().startsWith("image/")) { + return WallpaperType::Image; + } + + if (mime.isValid() && mime.name().startsWith("video/")) { + return WallpaperType::Video; + } + + return WallpaperType::Unknown; +} + +static void applyDefaultWallpaper(const QString &defaultBackground, + QString &path, + TreelandWallpaperInterfaceV1::WallpaperType &type) +{ + path = defaultBackground; + const WallpaperType detectedType = detectWallpaperType(path); + if (detectedType == WallpaperType::Unknown) { + path = DEFAULT_WALLPAPER; + type = TreelandWallpaperInterfaceV1::Image; + } else { + type = static_cast(detectedType); + } +} + +WallpaperManager::WallpaperManager(TreelandUserConfig *config, Workspace *workspace, + Services services, QObject *parent) + : QObject(parent) + , m_config(config) + , m_workspace(workspace) + , m_services(std::move(services)) +{ + connect(m_workspace, &Workspace::workspaceAdded, this, &WallpaperManager::syncAddWorkspace); + connect(m_config, &TreelandUserConfig::wallpaperConfigChanged, + this, &WallpaperManager::loadWallpaperConfig); + connect(m_config, &TreelandUserConfig::configInitializeSucceed, + this, &WallpaperManager::loadWallpaperConfig); + connect(m_config, &TreelandUserConfig::configInitializeFailed, + this, &WallpaperManager::loadWallpaperConfig); +} + +void WallpaperManager::refresh() +{ + if (!configurationReady(m_config)) + return; + if (!m_wallpaperConfigUpdated) + loadWallpaperConfig(); + else + Q_EMIT updateWallpaper(); +} + +WallpaperManager::~WallpaperManager() +{ + +} + +WallpaperOutputConfig WallpaperManager::getOutputConfig(Output *output) +{ + return getOutputConfig(output->getOutputId()); +} + +WallpaperOutputConfig WallpaperManager::getOutputConfig(wlr_output *output) +{ + return getOutputConfig(Output::getOutputId(output)); +} + +WallpaperOutputConfig WallpaperManager::getOutputConfig(const QString &id) +{ + for (WallpaperOutputConfig output : std::as_const(m_wallpaperConfig)) { + if (output.outputName == id) { + return output; + } + } + + return WallpaperOutputConfig{}; +} + +void WallpaperManager::loadWallpaperConfig() +{ + m_wallpaperConfig.clear(); + if (!m_config->wallpaperConfig().isEmpty()) { + QJsonDocument doc = QJsonDocument::fromJson(m_config->wallpaperConfig().toUtf8()); + if (doc.isArray()) { + QJsonArray jsonArray = doc.array(); + for (const QJsonValue& value : jsonArray) { + QJsonObject obj = value.toObject(); + m_wallpaperConfig.append(WallpaperOutputConfig::fromJson(obj)); + } + } else { + qCCritical(lcTlWallpaper) << "wallpapers config value error: Expected a JSON array, but got something else."; + } + } else { + defaultWallpaperConfig(); + } + m_wallpaperConfigUpdated = true; + + const auto wallpapers = globalValidWallpaper(); + if (auto *notifier = m_services.notifier()) { + for (auto it = wallpapers.cbegin(); it != wallpapers.cend(); ++it) { + notifier->sendAdd(it.value(), it.key()); + } + } + + Q_EMIT updateWallpaper(); +} + +void WallpaperManager::defaultWallpaperConfig() +{ + Q_ASSERT(m_workspace); + const QString defaultBackground = m_config->defaultBackground(); + for (Output *output : std::as_const(m_services.outputs())) { + WallpaperOutputConfig outputConfig; + applyDefaultWallpaper(defaultBackground, + outputConfig.lockscreenWallpaper, + outputConfig.lockScreenWallpapertype); + outputConfig.outputName = output->getOutputId(); + + for (int i = 0; i < m_workspace->count(); i++) { + WallpaperWorkspaceConfig workspaceConfig; + applyDefaultWallpaper(defaultBackground, + workspaceConfig.desktopWallpaper, + workspaceConfig.desktopWallpapertype); + workspaceConfig.workspaceId = i; + outputConfig.workspaces.append(workspaceConfig); + } + m_wallpaperConfig.append(outputConfig); + } + + QString json = wallpaperConfigToJsonString(); + m_config->setWallpaperConfig(json); +} + +void WallpaperManager::ensureWallpaperConfigForOutput(Output *output) +{ + if (!m_wallpaperConfigUpdated) { + return; + } + + bool update = false; + if (!configContainsOutput(output)) { + Q_ASSERT(m_workspace); + const QString defaultBackground = m_config->defaultBackground(); + + WallpaperOutputConfig outputConfig; + const bool hasReferenceConfig = !m_wallpaperConfig.isEmpty() + && !m_wallpaperConfig.constLast().workspaces.isEmpty(); + if (hasReferenceConfig) { + const WallpaperOutputConfig &refConfig = m_wallpaperConfig.constLast(); + outputConfig.lockscreenWallpaper = refConfig.lockscreenWallpaper; + outputConfig.lockScreenWallpapertype = refConfig.lockScreenWallpapertype; + } else { + applyDefaultWallpaper(defaultBackground, + outputConfig.lockscreenWallpaper, + outputConfig.lockScreenWallpapertype); + } + outputConfig.outputName = output->getOutputId(); + for (int i = 0; i < m_workspace->count(); i++) { + WallpaperWorkspaceConfig workspaceConfig; + if (hasReferenceConfig) { + const WallpaperWorkspaceConfig &refWorkspaceConfig = m_wallpaperConfig.constLast().workspaces.constFirst(); + workspaceConfig.desktopWallpaper = refWorkspaceConfig.desktopWallpaper; + workspaceConfig.desktopWallpapertype = refWorkspaceConfig.desktopWallpapertype; + } else { + applyDefaultWallpaper(defaultBackground, + workspaceConfig.desktopWallpaper, + workspaceConfig.desktopWallpapertype); + } + workspaceConfig.workspaceId = i; + outputConfig.workspaces.append(workspaceConfig); + } + m_wallpaperConfig.append(outputConfig); + update = true; + } else { + QString outputId = output->getOutputId(); + Q_ASSERT(m_workspace); + + for (WallpaperOutputConfig &outputConfig : m_wallpaperConfig) { + if (outputConfig.outputName == outputId) { + const WallpaperWorkspaceConfig refConfig = outputConfig.workspaces.first(); + for (int i = 0; i < m_workspace->count(); i++) { + if (!outputConfig.containsWorkspace(i)) { + WallpaperWorkspaceConfig wsConfig; + wsConfig.desktopWallpaper = refConfig.desktopWallpaper; + wsConfig.desktopWallpapertype = refConfig.desktopWallpapertype; + wsConfig.workspaceId = i; + outputConfig.workspaces.append(wsConfig); + } + } + update = true; + break; + } + } + } + + if (update) { + QString json = wallpaperConfigToJsonString(); + m_config->setWallpaperConfig(json); + + WallpaperOutputConfig outputConfig = getOutputConfig(output); + for (auto &workspaceConfig : std::as_const(outputConfig.workspaces)) { + m_services.notifier()->sendAdd(workspaceConfig.desktopWallpapertype, + workspaceConfig.desktopWallpaper); + } + + m_services.notifier()->sendAdd(outputConfig.lockScreenWallpapertype, + outputConfig.lockscreenWallpaper); + + Q_EMIT updateWallpaper(); + } +} + +bool WallpaperManager::configContainsOutput(Output *output) +{ + if (m_wallpaperConfig.isEmpty()) { + return false; + } + + QString outputId = output->getOutputId(); + for (const WallpaperOutputConfig& output : std::as_const(m_wallpaperConfig)) { + if (output.outputName == outputId) { + return true; + } + } + + return false; +} + +QString WallpaperManager::wallpaperConfigToJsonString() +{ + QJsonArray array; + for (const auto &cfg : std::as_const(m_wallpaperConfig)) { + array.append(cfg.toJson()); + } + + QJsonDocument doc(array); + return QString::fromUtf8( + doc.toJson(QJsonDocument::Indented)); +} + +void WallpaperManager::setOutputWallpaper(wlr_output *output, [[maybe_unused]] int workspaceIndex, const QString &fileSource, TreelandWallpaperInterfaceV1::WallpaperRoles roles, TreelandWallpaperInterfaceV1::WallpaperType type) +{ + bool update = false; + for (WallpaperOutputConfig &outputConfig : m_wallpaperConfig) { + if (outputConfig.outputName == Output::getOutputId(output)) { + if (roles.testFlag(TreelandWallpaperInterfaceV1::Lockscreen)) { + if (outputConfig.lockscreenWallpaper != fileSource) { + update = true; + outputConfig.lockscreenWallpaper = fileSource; + outputConfig.lockScreenWallpapertype = type; + } + } + + if (roles.testFlag(TreelandWallpaperInterfaceV1::Desktop)) { + for (WallpaperWorkspaceConfig &workspaceConfig : outputConfig.workspaces) { + if (workspaceConfig.desktopWallpaper != fileSource) { + update = true; + workspaceConfig.desktopWallpaper = fileSource; + workspaceConfig.desktopWallpapertype = type; + } + } + } + + break; + } + } + + if (update) { + m_config->setWallpaperConfig(wallpaperConfigToJsonString()); + } +} + +QMap WallpaperManager::globalValidWallpaper(wlr_output *excludedOutput) +{ + QMap wallpapers; + for (const WallpaperOutputConfig& output : std::as_const(m_wallpaperConfig)) { + bool outputConnected = false; + for (Output *connectedOutput : std::as_const(m_services.outputs())) { + if (output.outputName == connectedOutput->getOutputId()) { + outputConnected = true; + break; + } + } + if (!outputConnected || + (excludedOutput && output.outputName == Output::getOutputId(excludedOutput))) { + continue; + } + + if (!wallpapers.contains(output.lockscreenWallpaper)) { + wallpapers.insert(output.lockscreenWallpaper, output.lockScreenWallpapertype); + } + for (const WallpaperWorkspaceConfig& workspace : std::as_const(output.workspaces)) { + if (!wallpapers.contains(workspace.desktopWallpaper)) { + wallpapers.insert(workspace.desktopWallpaper, workspace.desktopWallpapertype); + } + } + } + + return wallpapers; +} + +void WallpaperManager::syncAddWorkspace() +{ + if (!m_wallpaperConfigUpdated) { + return; + } + + Q_ASSERT(m_workspace); + + bool update = false; + for (WallpaperOutputConfig &outputConfig : m_wallpaperConfig) { + if (outputConfig.workspaces.isEmpty()) { + continue; + } + + const WallpaperWorkspaceConfig refConfig = outputConfig.workspaces.constFirst(); + for (int i = 0; i < m_workspace->count(); i++) { + if (!outputConfig.containsWorkspace(i)) { + WallpaperWorkspaceConfig workspaceConfig; + workspaceConfig.desktopWallpaper = refConfig.desktopWallpaper; + workspaceConfig.desktopWallpapertype = refConfig.desktopWallpapertype; + workspaceConfig.workspaceId = i; + outputConfig.workspaces.append(workspaceConfig); + update = true; + } + } + } + + if (update) { + m_config->setWallpaperConfig(wallpaperConfigToJsonString()); + Q_EMIT updateWallpaper(); + } +} + +void WallpaperManager::removeOutputWallpaper(wlr_output *output) +{ + for (int i = 0; i < m_wallpaperConfig.size(); ++i) { + if (m_wallpaperConfig[i].outputName == Output::getOutputId(output)) { + WallpaperOutputConfig &outputConfig = m_wallpaperConfig[i]; + QMap globalWallpapers = m_services.library(output); + if (!globalWallpapers.contains(outputConfig.lockscreenWallpaper)) { + m_services.notifier()->sendRemove(outputConfig.lockscreenWallpaper); + } + for (const WallpaperWorkspaceConfig &workspace : std::as_const(outputConfig.workspaces)) { + if (!globalWallpapers.contains(workspace.desktopWallpaper)) { + m_services.notifier()->sendRemove(workspace.desktopWallpaper); + } + } + break; + } + } +} + +QString WallpaperManager::desktopWallpaper(WOutput *output, WorkspaceModel *workspace) +{ + if (!output || !workspace || workspace->workspaceManager() != m_workspace) + return {}; + + for (int index = 0; index < m_workspace->count(); ++index) { + if (m_workspace->modelAt(index) != workspace) + continue; + const auto config = getOutputConfig(output->handle()); + for (const auto &entry : config.workspaces) { + if (entry.workspaceId == index) + return entry.desktopWallpaper; + } + break; + } + return {}; +} + +QString WallpaperManager::currentWorkspaceWallpaper(WOutput *output) +{ + return desktopWallpaper(output, m_workspace->current()); +} + +QString WallpaperManager::currentLockScreenWallpaper(WOutput *output) +{ + for (int i = 0; i < m_wallpaperConfig.size(); ++i) { + if (m_wallpaperConfig[i].outputName == Output::getOutputId(output->handle())) { + return m_wallpaperConfig[i].lockscreenWallpaper; + } + } + + return QStringLiteral(""); +} + +TreelandWallpaperInterfaceV1::WallpaperType WallpaperManager::getWallpaperType(const QString &wallpaper) +{ + for (WallpaperOutputConfig outputConfig : std::as_const(m_wallpaperConfig)) { + if (outputConfig.lockscreenWallpaper == wallpaper) { + return outputConfig.lockScreenWallpapertype; + } + + for (WallpaperWorkspaceConfig workspaceConfig : std::as_const(outputConfig.workspaces)) { + if (workspaceConfig.desktopWallpaper == wallpaper) { + return workspaceConfig.desktopWallpapertype; + } + } + } + + qCCritical(lcTlWallpaper) << "Failed find wallpaper type for" << wallpaper; + return TreelandWallpaperInterfaceV1::Image; +} + +void WallpaperManager::onWallpaperAdded(TreelandWallpaperInterfaceV1 *interface) +{ + auto *output = interface->wOutput(); + if (!output) + return; + + Q_ASSERT(m_workspace); + for (int i = 0; i < m_wallpaperConfig.size(); ++i) { + if (m_wallpaperConfig[i].outputName == Output::getOutputId(output->handle())) { + WallpaperOutputConfig outputConfig = m_wallpaperConfig[i]; + interface->sendChanged(TreelandWallpaperInterfaceV1::Lockscreen, outputConfig.lockScreenWallpapertype, outputConfig.lockscreenWallpaper); + for (WallpaperWorkspaceConfig workspaceConfig : std::as_const(outputConfig.workspaces)) { + if (workspaceConfig.workspaceId == m_workspace->currentIndex()) { + interface->sendChanged(TreelandWallpaperInterfaceV1::Desktop, workspaceConfig.desktopWallpapertype, workspaceConfig.desktopWallpaper); + break; + } + } + break; + } + } + connect(interface, + &TreelandWallpaperInterfaceV1::imageSourceChanged, + this, + &WallpaperManager::onImageChanged); + connect(interface, + &TreelandWallpaperInterfaceV1::videoSourceChanged, + this, + &WallpaperManager::onVideoChanged); +} + +void WallpaperManager::onImageChanged(int workspaceIndex, const QString &fileSource, TreelandWallpaperInterfaceV1::WallpaperRoles roles) +{ + TreelandWallpaperInterfaceV1 *interface = + static_cast(sender()); + auto *output = interface->wOutput(); + if (!output) + return; + + QMap globalWallpapers = globalValidWallpaper(); + setOutputWallpaper(output->handle(), + workspaceIndex, + fileSource, + roles, + TreelandWallpaperInterfaceV1::Image); + if (globalWallpapers.contains(fileSource)) { + interface->sendError(fileSource, TreelandWallpaperInterfaceV1::AlreadyUsed); + Q_EMIT updateWallpaper(); + } else { + m_services.notifier()->sendAdd(TreelandWallpaperInterfaceV1::Image, fileSource); + } +} + +void WallpaperManager::onVideoChanged(int workspaceIndex, const QString &fileSource, TreelandWallpaperInterfaceV1::WallpaperRoles roles) +{ + TreelandWallpaperInterfaceV1 *interface = + static_cast(sender()); + auto *output = interface->wOutput(); + if (!output) + return; + + QMap globalWallpapers = globalValidWallpaper(); + setOutputWallpaper(output->handle(), + workspaceIndex, + fileSource, + roles, + TreelandWallpaperInterfaceV1::Video); + if (globalWallpapers.contains(fileSource)) { + interface->sendError(fileSource, TreelandWallpaperInterfaceV1::AlreadyUsed); + Q_EMIT updateWallpaper(); + } else { + m_services.notifier()->sendAdd(TreelandWallpaperInterfaceV1::Video, fileSource); + } +} + +void WallpaperManager::onWallpaperNotifierBound(wl_resource *resource) +{ + QMap globalWallpapers = globalValidWallpaper(); + QMapIterator i(globalWallpapers); + while (i.hasNext()) { + i.next(); + m_services.notifier()->sendAddForResource(resource, static_cast(i.value()), i.key()); + } +} + +void WallpaperManager::handleWallpaperSurfaceAdded([[maybe_unused]] TreelandWallpaperSurfaceInterfaceV1 *interface) +{ + QList wallpapers = m_services.factory->producedWallpapers(); + const auto globalWallpapers = m_services.library(nullptr); + for (const auto &wallpaper : std::as_const(wallpapers)) { + if (!globalWallpapers.contains(wallpaper)) { + m_services.notifier()->sendRemove(wallpaper); + } + } +} diff --git a/src/wallpaper/wallpapermanager.h b/src/wallpaper/wallpapermanager.h new file mode 100644 index 0000000000..feb2800617 --- /dev/null +++ b/src/wallpaper/wallpapermanager.h @@ -0,0 +1,86 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "output/output.h" +#include "wallpaper/wallpaperconfig.h" + +#include +#include +#include + +class TreelandWallpaperSurfaceInterfaceV1; +class Workspace; +class WorkspaceModel; +class TreelandWallpaperNotifierInterfaceV1; +class TreelandWallpaperShellInterfaceV1; +class TreelandUserConfig; + +class WallpaperManager : public QObject +{ + Q_OBJECT + QML_ANONYMOUS +public: + enum UpdateReason + { + Normal, + Scale, + }; + + using WallpaperLibrary = QMap; + using LibraryProvider = std::function; + struct Services { + LibraryProvider library; + std::function &()> outputs; + std::function notifier; + TreelandWallpaperShellInterfaceV1 *factory; + }; + WallpaperManager(TreelandUserConfig *config, Workspace *workspace, Services services, + QObject *parent = nullptr); + ~WallpaperManager() override; + WallpaperOutputConfig getOutputConfig(Output *output); + WallpaperOutputConfig getOutputConfig(wlr_output *output); + WallpaperOutputConfig getOutputConfig(const QString &id); + void defaultWallpaperConfig(); + void ensureWallpaperConfigForOutput(Output *output); + bool configContainsOutput(Output *output); + QString wallpaperConfigToJsonString(); + void setOutputWallpaper(wlr_output *output, + int workspaceIndex, + const QString &fileSource, + TreelandWallpaperInterfaceV1::WallpaperRoles roles, + TreelandWallpaperInterfaceV1::WallpaperType type); + QMap globalValidWallpaper(wlr_output *excludedOutput = nullptr); + void syncAddWorkspace(); + void removeOutputWallpaper(wlr_output *output); + QString desktopWallpaper(WOutput *output, WorkspaceModel *workspace); + QString currentWorkspaceWallpaper(WOutput *output); + QString currentLockScreenWallpaper(WOutput *output); + TreelandWallpaperInterfaceV1::WallpaperType getWallpaperType(const QString &wallpaper); + +Q_SIGNALS: + void updateWallpaper(); + +public Q_SLOTS: + void loadWallpaperConfig(); + void onWallpaperAdded(TreelandWallpaperInterfaceV1 *interface); + void onImageChanged(int workspaceIndex, + const QString &fileSource, + TreelandWallpaperInterfaceV1::WallpaperRoles roles); + void onVideoChanged(int workspaceIndex, + const QString &fileSource, + TreelandWallpaperInterfaceV1::WallpaperRoles roles); + void onWallpaperNotifierBound(wl_resource *resource); + void handleWallpaperSurfaceAdded(TreelandWallpaperSurfaceInterfaceV1 *interface); + +public: + void refresh(); + +private: + TreelandUserConfig *const m_config; + Workspace *const m_workspace; + const Services m_services; + bool m_wallpaperConfigUpdated { false }; + QList m_wallpaperConfig; +}; diff --git a/src/wallpaper/wallpapersurface.cpp b/src/wallpaper/wallpapersurface.cpp new file mode 100644 index 0000000000..bc4b245408 --- /dev/null +++ b/src/wallpaper/wallpapersurface.cpp @@ -0,0 +1,94 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wallpapersurface.h" +#include "wallpapershellinterfacev1.h" +#include "private/wtoplevelsurface_p.h" +#include "private/wglobal_p.h" +#include + +class Q_DECL_HIDDEN WallpaperSurfacePrivate : public WToplevelSurfacePrivate { +public: + WallpaperSurfacePrivate(WallpaperSurface *qq, TreelandWallpaperSurfaceInterfaceV1 *surface); + + wl_client *waylandClient() const override { + return interface->client(); + } + + WSurface *surface = nullptr; + TreelandWallpaperSurfaceInterfaceV1 *interface = nullptr; +}; + +WallpaperSurfacePrivate::WallpaperSurfacePrivate(WallpaperSurface *qq, TreelandWallpaperSurfaceInterfaceV1 *surface) + : WToplevelSurfacePrivate(qq) + , interface(surface) +{ +} + +WallpaperSurface::WallpaperSurface(TreelandWallpaperSurfaceInterfaceV1 *handle) + : WToplevelSurface(*new WallpaperSurfacePrivate(this, handle)) +{ + init(); +} + +WallpaperSurface::~WallpaperSurface() +{ + // Owner rule: this object created the WSurface wrapper, release it. + W_D(WallpaperSurface); + delete d->surface; +} + +WSurface *WallpaperSurface::surface() const +{ + W_DC(WallpaperSurface); + return d->surface; +} + +QRect WallpaperSurface::getContentGeometry() const +{ + W_DC(WallpaperSurface); + wlr_surface *surface = wlr_surface_from_resource(d->interface->surfaceResource()); + if (!surface) { + return QRect(); + } + + return QRect(0, 0, surface->current.width, surface->current.height); +} + +bool WallpaperSurface::checkNewSize(const QSize &size, QSize *clipedSize) +{ + if (size.width() < 0 || size.height() < 0) { + if (clipedSize) + *clipedSize = QSize(0, 0); + return false; + } + + return true; +} + +void WallpaperSurface::init() +{ + W_D(WallpaperSurface); + + auto *wlrSurface = wlr_surface_from_resource(d->interface->surfaceResource()); + if (!wlrSurface) { + wl_resource_post_error(d->interface->surfaceResource(), + WL_DISPLAY_ERROR_INVALID_OBJECT, + "invalid wl_surface"); + return; + } + + d->surface = new WSurface(wlrSurface); + d->surface->setAttachedData(this); + + // The client may destroy the wl_surface while the protocol object is + // still alive. Release the WSurface wrapper as soon as the native + // surface is gone so nothing keeps a dangling handle; wlr_surface_destroy + // asserts the destroy listener list is empty, so detach first. + d->surface->listeners(this)->add(&wlrSurface->events.destroy, this, [this, d]() { + d->surface->removeListeners(this); + delete d->surface; + d->surface = nullptr; + Q_EMIT surfaceChanged(); + }); +} diff --git a/src/wallpaper/wallpapersurface.h b/src/wallpaper/wallpapersurface.h new file mode 100644 index 0000000000..e303981e47 --- /dev/null +++ b/src/wallpaper/wallpapersurface.h @@ -0,0 +1,37 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class TreelandWallpaperSurfaceInterfaceV1; +class WallpaperSurfacePrivate; +class WAYLIB_SERVER_EXPORT WallpaperSurface : public WToplevelSurface +{ + Q_OBJECT + W_DECLARE_PRIVATE(WallpaperSurface) + Q_PROPERTY(WSurface *surface READ surface NOTIFY surfaceChanged) + + QML_NAMED_ELEMENT(WallpaperSurface) + QML_UNCREATABLE("Only create in C++") + +public: + explicit WallpaperSurface(TreelandWallpaperSurfaceInterfaceV1 *handle); + ~WallpaperSurface(); + + WSurface *surface() const override; + QRect getContentGeometry() const override; + +Q_SIGNALS: + void surfaceChanged(); + +public Q_SLOTS: + bool checkNewSize(const QSize &size, QSize *clipedSize = nullptr) override; + +private: + void init(); +}; diff --git a/src/wallpaper/wallpaperswitcheritem.cpp b/src/wallpaper/wallpaperswitcheritem.cpp new file mode 100644 index 0000000000..99f562f393 --- /dev/null +++ b/src/wallpaper/wallpaperswitcheritem.cpp @@ -0,0 +1,259 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wallpaperswitcheritem.h" + +#include "wallpaperitem.h" +#include "core/waylandserver.h" +#include "workspace/workspacemodel.h" +#include "wallpapershellinterfacev1.h" +#include "wallpapermanager.h" +#include "workspace.h" +#include "shellhandler.h" +#include "animationconfig.hpp" + +#include + +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class WallpaperSlot : public WallpaperItem +{ +public: + WallpaperSlot(QQuickItem *parent) + : WallpaperItem(parent, false) + { + setLive(true); + } +}; + +WallpaperSwitcherItem::WallpaperSwitcherItem(QQuickItem *parent) + : QQuickItem(parent) +{ + m_currentSlot = new WallpaperSlot(this); + QQuickItemPrivate::get(m_currentSlot)->anchors()->setFill(this); + + connect(WaylandServer::instance(), + &WaylandServer::wallpaperChanged, + this, + &WallpaperSwitcherItem::handleWallpaperUpdate); + connect(WaylandServer::instance()->shellHandler()->wallpaperShell(), + &TreelandWallpaperShellInterfaceV1::wallpaperSurfaceAdded, + this, + &WallpaperSwitcherItem::handleWallpaperSurfaceAdded); + connect(WaylandServer::instance(), + &WaylandServer::workspaceAdded, + this, + &WallpaperSwitcherItem::handleWorkspaceAdded); +} + +WallpaperSwitcherItem::~WallpaperSwitcherItem() +{ + delete m_oldSlot; + delete m_currentSlot; +} + +WOutput *WallpaperSwitcherItem::output() const +{ + return m_output; +} + +void WallpaperSwitcherItem::setOutput(WOutput *output) +{ + if (m_output == output) + return; + + m_output = output; + Q_EMIT outputChanged(); + + if (m_currentSlot) + m_currentSlot->setOutput(output); + if (m_oldSlot) + m_oldSlot->setOutput(output); +} + +WorkspaceModel *WallpaperSwitcherItem::workspace() const +{ + return m_workspace; +} + +void WallpaperSwitcherItem::setWorkspace(WorkspaceModel *workspace) +{ + if (m_workspace == workspace) + return; + + if (m_workspace && m_workspace->workspaceManager()->wallpaperManager()) + disconnect(m_workspace->workspaceManager()->wallpaperManager(), + &WallpaperManager::updateWallpaper, this, &WallpaperSwitcherItem::handleWallpaperUpdate); + m_workspace = workspace; + if (m_workspace && m_workspace->workspaceManager()->wallpaperManager()) + connect(m_workspace->workspaceManager()->wallpaperManager(), + &WallpaperManager::updateWallpaper, this, &WallpaperSwitcherItem::handleWallpaperUpdate); + Q_EMIT workspaceChanged(); + + if (m_currentSlot) + m_currentSlot->setWorkspace(workspace); + if (m_oldSlot) + m_oldSlot->setWorkspace(workspace); +} + +bool WallpaperSwitcherItem::play() const +{ + return m_play; +} + +void WallpaperSwitcherItem::setPlay(bool value) +{ + if (m_play == value) + return; + + m_play = value; + Q_EMIT playChanged(); + + if (m_currentSlot) + m_currentSlot->setPlay(value); + if (m_oldSlot) + m_oldSlot->setPlay(value); +} + +QString WallpaperSwitcherItem::source() const +{ + return m_currentSlot ? m_currentSlot->source() : QString(); +} + +int WallpaperSwitcherItem::opacityDuration() const +{ + return m_opacityDuration; +} + +void WallpaperSwitcherItem::setOpacityDuration(int duration) +{ + if (m_opacityDuration == duration) + return; + + m_opacityDuration = duration; + Q_EMIT opacityDurationChanged(); +} + +void WallpaperSwitcherItem::slowDown() +{ + if (m_currentSlot) + m_currentSlot->slowDown(); +} + +void WallpaperSwitcherItem::handleWallpaperUpdate() +{ + if (!m_output || !m_currentSlot) + return; + + if (!m_workspace) + return; + auto *manager = m_workspace->workspaceManager()->wallpaperManager(); + if (!manager) + return; + const QString newSource = manager->desktopWallpaper(m_output, m_workspace); + + if (newSource == m_currentSlot->source()) + return; + + switchToNewSlot(); +} + +void WallpaperSwitcherItem::handleWorkspaceAdded() +{ + if (m_currentSlot) + m_currentSlot->updateSurface(); +} + +void WallpaperSwitcherItem::handleWallpaperSurfaceAdded(TreelandWallpaperSurfaceInterfaceV1 *interface) +{ + if (interface->wallpaperReady()) { + handleWallpaperUpdate(); + } else { + connect(interface, &TreelandWallpaperSurfaceInterfaceV1::ready, + this, &WallpaperSwitcherItem::handleWallpaperUpdate, Qt::SingleShotConnection); + } +} + +void WallpaperSwitcherItem::switchToNewSlot() +{ + auto *newSlot = new WallpaperSlot(this); + QQuickItemPrivate::get(newSlot)->anchors()->setFill(this); + newSlot->setOpacity(0); + newSlot->setOutput(m_output); + newSlot->setWorkspace(m_workspace); + + if (newSlot->source().isEmpty()) { + newSlot->deleteLater(); + return; + } + + m_oldSlot = m_currentSlot; + m_currentSlot = newSlot; + + Q_EMIT sourceChanged(); + + auto *config = WaylandServer::instance()->animationConfig(); + const bool animated = !config || config->wallpaperCrossFade(); + const QPointer oldSlot = m_oldSlot; + if (animated) { + startFadeOut(oldSlot); + } else if (oldSlot) { + // A superseded request may never become ready. Keep its old slot tied + // to its lifetime so abandoning it cannot leave a wallpaper behind. + connect(newSlot, &QObject::destroyed, oldSlot, &QObject::deleteLater); + } + + auto *interface = TreelandWallpaperSurfaceInterfaceV1::get(newSlot->source()); + if (interface && interface->wallpaperReady()) { + startFadeIn(newSlot, oldSlot, animated); + } else if (interface) { + // Waiting for the content to load is not an animation: keep it even when + // the cross fade is disabled. + connect(interface, + &TreelandWallpaperSurfaceInterfaceV1::ready, + this, + [this, newSlot = QPointer(newSlot), oldSlot, animated]() { + if (newSlot && m_currentSlot == newSlot) + startFadeIn(newSlot, oldSlot, animated); + }, + Qt::SingleShotConnection); + } +} + +void WallpaperSwitcherItem::startFadeOut(WallpaperSlot *slot) +{ + if (!slot) + return; + + auto *fadeOut = new QPropertyAnimation(slot, "opacity"); + fadeOut->setDuration(m_opacityDuration); + fadeOut->setStartValue(1.0); + fadeOut->setEndValue(0.0); + fadeOut->setEasingCurve(QEasingCurve::InOutQuad); + connect(fadeOut, &QPropertyAnimation::finished, slot, &QObject::deleteLater); + fadeOut->start(QAbstractAnimation::DeleteWhenStopped); +} + +void WallpaperSwitcherItem::startFadeIn(WallpaperSlot *slot, WallpaperSlot *oldSlot, bool animated) +{ + if (!animated) { + // The new content is ready: show it and release the previous wallpaper in + // one step instead of fading. + slot->setOpacity(1.0); + if (oldSlot) + oldSlot->deleteLater(); + return; + } + + auto *anim = new QPropertyAnimation(slot, "opacity"); + anim->setDuration(m_opacityDuration); + anim->setStartValue(0.0); + anim->setEndValue(1.0); + anim->setEasingCurve(QEasingCurve::InOutQuad); + anim->start(QAbstractAnimation::DeleteWhenStopped); +} diff --git a/src/wallpaper/wallpaperswitcheritem.h b/src/wallpaper/wallpaperswitcheritem.h new file mode 100644 index 0000000000..769dbface6 --- /dev/null +++ b/src/wallpaper/wallpaperswitcheritem.h @@ -0,0 +1,77 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "wglobal.h" +#include + +Q_MOC_INCLUDE("workspace/workspace.h") + +class WallpaperSlot; +class TreelandWallpaperSurfaceInterfaceV1; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutput; +WAYLIB_SERVER_END_NAMESPACE + +WAYLIB_SERVER_USE_NAMESPACE + +class WorkspaceModel; + +class WallpaperSwitcherItem : public QQuickItem +{ + Q_OBJECT + Q_PROPERTY(WAYLIB_SERVER_NAMESPACE::WOutput *output READ output WRITE setOutput NOTIFY outputChanged FINAL) + Q_PROPERTY(WorkspaceModel *workspace READ workspace WRITE setWorkspace NOTIFY workspaceChanged FINAL) + Q_PROPERTY(bool play READ play WRITE setPlay NOTIFY playChanged FINAL) + Q_PROPERTY(QString source READ source NOTIFY sourceChanged FINAL) + Q_PROPERTY(int opacityDuration READ opacityDuration WRITE setOpacityDuration NOTIFY opacityDurationChanged FINAL) + + QML_NAMED_ELEMENT(WallpaperSwitcher) + QML_ADDED_IN_VERSION(1, 0) + +public: + explicit WallpaperSwitcherItem(QQuickItem *parent = nullptr); + ~WallpaperSwitcherItem() override; + + WOutput *output() const; + void setOutput(WOutput *output); + + WorkspaceModel *workspace() const; + void setWorkspace(WorkspaceModel *workspace); + + bool play() const; + void setPlay(bool value); + + QString source() const; + + int opacityDuration() const; + void setOpacityDuration(int duration); + + Q_INVOKABLE void slowDown(); + +Q_SIGNALS: + void outputChanged(); + void workspaceChanged(); + void playChanged(); + void sourceChanged(); + void opacityDurationChanged(); + +private: + void handleWallpaperUpdate(); + void handleWallpaperSurfaceAdded(TreelandWallpaperSurfaceInterfaceV1 *interface); + void handleWorkspaceAdded(); + void switchToNewSlot(); + void startFadeIn(WallpaperSlot *slot, WallpaperSlot *oldSlot, bool animated); + void startFadeOut(WallpaperSlot *slot); + + QPointer m_workspace; + QPointer m_output; + bool m_play = true; + QString m_source; + int m_opacityDuration = 500; + + WallpaperSlot *m_currentSlot = nullptr; + QPointer m_oldSlot; +}; diff --git a/src/workspace/workspace.cpp b/src/workspace/workspace.cpp new file mode 100644 index 0000000000..2e6271eab5 --- /dev/null +++ b/src/workspace/workspace.cpp @@ -0,0 +1,607 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "workspace.h" +#include "wallpaper/wallpapermanager.h" +#include "desktop/desktopenvironment.h" + +#include "common/treelandlogging.h" +#include "core/rootsurfacecontainer.h" +#include "output/output.h" +#include "core/waylandserver.h" +#include "surface/surfacecontainer.h" +#include "surface/surfacewrapper.h" +#include "treelanduserconfig.hpp" +#include "workspaceanimationcontroller.h" + +Workspace::Workspace(SurfaceContainer *parent, TreelandUserConfig *config) + : SurfaceContainer(parent) + , m_config(config) + , m_currentIndex(0) + , m_models(new WorkspaceListModel(this)) + , m_currentFilter(new SurfaceFilterProxyModel(this)) + , m_animationController(new WorkspaceAnimationController(this)) +{ + Q_ASSERT(m_config); + m_animationController->setConfig(m_config); + m_showOnAllWorkspaceModel = new WorkspaceModel(this, ShowOnAllWorkspaceId, {}); + m_showOnAllWorkspaceModel->setName("show-on-all-workspace"); + m_showOnAllWorkspaceModel->setVisible(true); + const int count = qMax(1, static_cast(m_config->numWorkspace())); + m_currentIndex = qBound(0, static_cast(m_config->currentWorkspace()), count - 1); + for (int index = 0; index < count; index++) { + doCreateModel(QStringLiteral("workspace-%1").arg(index), + index == static_cast(m_currentIndex)); + } + connect(m_config, &TreelandUserConfig::configInitializeSucceed, + this, &Workspace::reloadFromConfig); +} + +TreelandUserConfig *Workspace::config() const +{ + return m_config; +} + +void Workspace::resetView() +{ + stopPreviewing(); + m_animationController->cancel(); + m_switcherEnabled = true; + if (m_switcher) { + m_switcher->setVisible(false); + m_switcher->deleteLater(); + m_switcher = nullptr; + } +} + +void Workspace::moveSurfaceTo(SurfaceWrapper *surface, int workspaceId) +{ + if (!ownsSurface(surface)) + return; + if (workspaceId == -1) + workspaceId = current()->id(); + + Q_ASSERT(surface); + if (surface->workspaceId() == workspaceId) + return; + + WorkspaceModel *from = nullptr; + Q_ASSERT(surface->workspaceId() != -1); + if (surface->showOnAllWorkspace()) + from = m_showOnAllWorkspaceModel; + else + from = modelFromId(surface->workspaceId()); + + WorkspaceModel *to = modelFromId(workspaceId); + if (!from || !to) + return; + + from->removeSurface(surface); + to->addSurface(surface); + + // Transient children follow parent to new workspace (ref: KWin::Window::setDesktops) + for (auto *child : surface->subSurfaces()) { + moveSurfaceTo(child, workspaceId); + } + // Modal dialog pulls parent along + if (surface->modal() && surface->parentSurface()) { + moveSurfaceTo(surface->parentSurface(), workspaceId); + } + + // TODO(rewine): Unified Activation Capability Check + if (surface->hasActiveCapability()) { + this->removeActivedSurface(surface); + this->pushActivedSurface(surface); + } +} + +int Workspace::getLeftWorkspaceId(int workspaceId) +{ + if (workspaceId == ShowOnAllWorkspaceId || workspaceId < 0) + return -1; + + auto model = modelFromId(workspaceId); + Q_ASSERT(model); + + auto index = m_models->objects().indexOf(model); + if (index == 0) + return -1; + return modelAt(index - 1)->id(); +} + +int Workspace::getRightWorkspaceId(int workspaceId) +{ + if (workspaceId == ShowOnAllWorkspaceId || workspaceId < 0) + return -1; + + auto model = modelFromId(workspaceId); + Q_ASSERT(model); + + auto index = m_models->objects().indexOf(model); + if (index == count() - 1) + return -1; + return modelAt(index + 1)->id(); +} + +void Workspace::addSurface(SurfaceWrapper *surface, int workspaceId) +{ + if (!ownsSurface(surface)) + return; + Q_ASSERT(surface && !surface->container() && surface->workspaceId() == -1); + + auto model = modelFromId(workspaceId); + Q_ASSERT(model); + + SurfaceContainer::addSurface(surface); + Q_ASSERT(surface->ownsOutput() || rootContainer()->primaryOutput() == nullptr); + + model->addSurface(surface); + + surface->setHasInitializeContainer(true); +} + +void Workspace::addSurface(SurfaceWrapper *surface) +{ + addSurface(surface, current()->id()); +} + +void Workspace::moveModelTo(int workspaceId, int destinationIndex) +{ + // Current index might change, but current will not change + auto oldCurrent = current(); + int fromIndex; + for (fromIndex = 0; fromIndex < count(); ++fromIndex) { + if (workspaceId == m_models->objects().at(fromIndex)->id()) { + break; + } + } + Q_ASSERT_X(fromIndex < count(), __func__, "Should pass a valid workspace id here."); + m_models->moveRow({}, fromIndex, {}, destinationIndex); + doSetCurrentIndex(m_models->objects().indexOf(oldCurrent)); + Q_EMIT currentIndexChanged(); +} + +void Workspace::removeSurface(SurfaceWrapper *surface) +{ + if (!ownsSurface(surface)) + return; + surface->setHasInitializeContainer(false); + + WorkspaceModel *from = nullptr; + if (surface->showOnAllWorkspace()) + from = m_showOnAllWorkspaceModel; + else + from = modelFromId(surface->workspaceId()); + Q_ASSERT(from); + + from->removeSurface(surface); + SurfaceContainer::removeSurface(surface); +} + +int Workspace::modelIndexOfSurface(SurfaceWrapper *surface) const +{ + for (int i = 0; i < m_models->rowCount(); ++i) { + if (modelAt(i)->hasSurface(surface)) + return i; + } + + if (m_showOnAllWorkspaceModel->hasSurface(surface)) + return ShowOnAllWorkspaceId; + + return -1; +} + +int Workspace::createModel(const QString &name, bool visible) +{ + auto id = doCreateModel(name, visible); + m_config->setNumWorkspace(count()); + Q_EMIT countChanged(); + Q_EMIT workspaceAdded(); + return id; +} + +void Workspace::removeModel(int index) +{ + Q_ASSERT(m_models->rowCount() > 1); // At least one workspace + Q_ASSERT(index >= 0 && index < m_models->rowCount()); + doRemoveModel(index); + m_config->setNumWorkspace(count()); + Q_EMIT countChanged(); +} + +WorkspaceModel *Workspace::modelAt(int index) const +{ + if (index < 0 || index >= m_models->rowCount()) + return nullptr; + return m_models->objects().at(index); +} + +WorkspaceModel *Workspace::modelFromId(int id) const +{ + if (id == ShowOnAllWorkspaceId) + return m_showOnAllWorkspaceModel; + auto foundModel = std::find_if(m_models->objects().constBegin(), + m_models->objects().constEnd(), + [id](WorkspaceModel *model) { + return model->id() == id; + }); + return foundModel == m_models->objects().constEnd() ? nullptr : *foundModel; +} + +int Workspace::currentIndex() const +{ + return m_currentIndex; +} + +void Workspace::setCurrentIndex(int newCurrentIndex) +{ + if (newCurrentIndex < 0 || newCurrentIndex >= m_models->rowCount()) + return; + + if (currentIndex() == newCurrentIndex) + return; + + doSetCurrentIndex(newCurrentIndex); + + for (int i = 0; i < m_models->rowCount(); ++i) { + modelAt(i)->setVisible(i == currentIndex()); + } + + // Both changed + Q_EMIT currentIndexChanged(); + Q_EMIT currentChanged(); +} + +void Workspace::switchToNext() +{ + if (currentIndex() < m_models->rowCount() - 1) { + switchTo(currentIndex() + 1); + } else if (isEnabled() && m_animationController->bounceEnabled()) { + createSwitcher(); + m_animationController->bounce(currentIndex(), WorkspaceAnimationController::Right); + } +} + +void Workspace::switchToPrev() +{ + if (currentIndex() > 0) { + switchTo(currentIndex() - 1); + } else if (isEnabled() && m_animationController->bounceEnabled()) { + createSwitcher(); + m_animationController->bounce(currentIndex(), WorkspaceAnimationController::Left); + } +} + +void Workspace::switchTo(int index, bool animated) +{ + if (index < 0 || index >= m_models->rowCount() || index == currentIndex()) + return; + + // Inactive desktops may update their selection without affecting input or focus. + if (isEnabled()) + WaylandServer::instance()->rootSurfaceContainer()->dismissAllPopups(); + + auto oldCurrentIndex = currentIndex(); + setCurrentIndex(index); + if (!isEnabled()) + return; + + // Browsing workspaces must keep keyboard focus in the multitask view. + if (WaylandServer::instance()->currentMode() != WaylandServer::CurrentMode::Multitaskview) + WaylandServer::instance()->activateSurface(current()->latestActiveSurface()); + + if (animated) { + // Skip the switcher layer entirely when the switch animation is off: the + // workspace change itself is already committed above. + if (m_animationController->slideEnabled()) { + createSwitcher(); + m_animationController->slide(oldCurrentIndex, currentIndex()); + } + } else if (m_switcher && m_switcher->isVisible()) { + // activateSurface restacks the target surface via stackToLast(), placing it above + // the already-visible workspace switcher. Raise the switcher back on top so the + // slide animation is not visually broken by the real window peeking through. + auto *switcherParent = m_switcher->parentItem(); + Q_ASSERT(switcherParent && !switcherParent->childItems().isEmpty()); + m_switcher->stackAfter(switcherParent->childItems().last()); + } +} + +WorkspaceModel *Workspace::current() const +{ + return modelAt(currentIndex()); +} + +SurfaceFilterProxyModel *Workspace::currentFilter() +{ + WorkspaceModel *wmodel = current(); + m_currentFilter->setSourceModel(wmodel); + m_currentFilter->invalidate(); + m_currentFilter->sort(0); + + auto *activeSurface = wmodel->latestActiveSurface(); + m_currentFilter->setActiveIndex(wmodel->activeHistoryIndex(activeSurface)); + + return m_currentFilter; +} + +void Workspace::setCurrent(WorkspaceModel *model) +{ + int index = m_models->objects().indexOf(model); + if (index < 0) + return; + setCurrentIndex(index); +} + +WorkspaceListModel *Workspace::models() +{ + return m_models; +} + +void Workspace::updateSurfaceOwnsOutput(SurfaceWrapper *surface) +{ + auto outputs = surface->outputs(); + if (surface->ownsOutput() && outputs.contains(surface->ownsOutput()->output())) + return; + + Output *output = nullptr; + if (!outputs.isEmpty()) + output = WaylandServer::instance()->getOutput(outputs.first()); + if (!output) + output = rootContainer()->cursorOutput(); + if (!output) + output = rootContainer()->primaryOutput(); + if (output) + surface->setOwnsOutput(output); +} + +void Workspace::updateSurfacesOwnsOutput() +{ + const auto surfaces = this->surfaces(); + for (auto surface : surfaces) { + updateSurfaceOwnsOutput(surface); + } +} + +void Workspace::createSwitcher() +{ + if (isEnabled() && m_switcherEnabled && !m_switcher) { + auto engine = WaylandServer::instance()->qmlEngine(); + m_switcher = engine->createWorkspaceSwitcher(this); + connect(m_switcher, &QQuickItem::visibleChanged, m_switcher, [this] { + if (!m_switcher->isVisible()) { + m_switcher->deleteLater(); + } + }); + } +} +void Workspace::reloadFromConfig() +{ + m_animationController->setConfig(m_config); + auto *config = m_config; + auto targetCount = static_cast(config->numWorkspace()); + if (targetCount < 1){ + targetCount = 1; + config->setNumWorkspace(1); + } + auto targetIndex = static_cast(config->currentWorkspace()); + + for (int need = targetCount - count(); need > 0; --need) + doCreateModel(QStringLiteral("workspace-%1").arg(count()), false); + + for (int extra = count() - targetCount; extra > 0; --extra) + doRemoveModel(count() - 1); + + if (targetIndex >= count()) + targetIndex = count() - 1; + if (targetIndex < 0) + targetIndex = 0; + setCurrentIndex(targetIndex); +} + +int Workspace::count() const +{ + return m_models->rowCount(); +} + +WorkspaceModel *Workspace::showOnAllWorkspaceModel() const +{ + return m_showOnAllWorkspaceModel; +} + +void Workspace::doSetCurrentIndex(int newCurrentIndex) +{ + m_currentIndex = newCurrentIndex; + m_config->setCurrentWorkspace(newCurrentIndex); +} + +void Workspace::startPreviewing(SurfaceWrapper *previewingItem) +{ + if (!isEnabled() || !ownsSurface(previewingItem)) + return; + if (m_previewingItem && m_previewingItem->shellSurface()) { + // Check shellSurface() since SurfaceWrapper::aboutToBeInvalidated can't make QPointer null + // in time + auto model = modelFromId(m_previewingItem->workspaceId()); + m_previewingItem->setOpacity(model->opaque() ? 1.0 : 0.0); + m_previewingItem->setHideByWorkspace(!model->visible()); + } + m_previewingItem = previewingItem; + current()->setOpaque(false); + previewingItem->setOpacity(1); + previewingItem->setHideByWorkspace(false); +} + +void Workspace::stopPreviewing() +{ + current()->setOpaque(true); + if (m_previewingItem && m_previewingItem->shellSurface()) { + auto model = modelFromId(m_previewingItem->workspaceId()); + m_previewingItem->setOpacity(model->opaque() ? 1.0 : 0.0); + m_previewingItem->setHideByWorkspace(!model->visible()); + m_previewingItem = nullptr; + } +} + +void Workspace::pushActivedSurface(SurfaceWrapper *surface) +{ + if (!ownsSurface(surface)) + return; + if (surface->type() == SurfaceWrapper::Type::XdgPopup) { + qCWarning(lcTlWorkspace) << "XdgPopup can't participate in focus fallback!"; + return; + } + if (surface->showOnAllWorkspace()) [[unlikely]] { + for (auto wpModel : std::as_const(m_models->objects())) + wpModel->pushActivedSurface(surface); + m_showOnAllWorkspaceModel->pushActivedSurface(surface); + } else { + auto wpModel = modelFromId(surface->workspaceId()); + Q_ASSERT(wpModel); + wpModel->pushActivedSurface(surface); + } +} + +void Workspace::removeActivedSurface(SurfaceWrapper *surface) +{ + if (!ownsSurface(surface)) + return; + if (surface->showOnAllWorkspace()) [[unlikely]] { + for (auto wpModel : std::as_const(m_models->objects())) + wpModel->removeActivedSurface(surface); + m_showOnAllWorkspaceModel->removeActivedSurface(surface); + } else { + auto wpModel = modelFromId(surface->workspaceId()); + Q_ASSERT(wpModel); + wpModel->removeActivedSurface(surface); + } +} + +void Workspace::clearActivedSurface() +{ + for (auto wpModel : std::as_const(m_models->objects())) + wpModel->clearActivedSurface(); + m_showOnAllWorkspaceModel->clearActivedSurface(); +} + +void Workspace::setSwitcherEnabled(bool enabled) +{ + m_switcherEnabled = enabled; +} + +int Workspace::nextWorkspaceId() const +{ + static int globalWorkspaceId = 0; + return globalWorkspaceId++; +} + +int Workspace::doCreateModel(const QString &name, bool visible) +{ + auto newContainer = new WorkspaceModel(this, + nextWorkspaceId(), + m_showOnAllWorkspaceModel->m_activedSurfaceHistory); + if (name.isEmpty()) { + newContainer->setName(QString("workspace-%1").arg(newContainer->id())); + } else { + newContainer->setName(name); + } + newContainer->setVisible(visible); + m_models->addObject(newContainer); + return newContainer->id(); +} + +void Workspace::doRemoveModel(int index) +{ + auto oldCurrent = this->current(); + auto oldCurrentIndex = this->currentIndex(); + auto model = this->modelAt(index); + // Move windows to the preceding workspace, or the next one when removing the first. + auto target = this->modelAt(index > 0 ? index - 1 : 1); + Q_ASSERT(target); + m_models->removeObject(model); + + if (oldCurrent == model) { + // current change, current index might change + doSetCurrentIndex(m_models->objects().indexOf(target)); + } else { + // current do not change, current index might change + doSetCurrentIndex(m_models->objects().indexOf(oldCurrent)); + } + + auto current = this->current(); + Q_ASSERT(current); + + // TODO delete animation here + const auto tmp = model->surfaces(); + for (auto s : tmp) { + model->removeSurface(s); + target->addSurface(s); + if (s->hasActiveCapability() && !s->showOnAllWorkspace()) + target->pushActivedSurface(s); + } + if (isEnabled() + && WaylandServer::instance()->currentMode() != WaylandServer::CurrentMode::Multitaskview) + WaylandServer::instance()->activateSurface(current->latestActiveSurface()); + + if (m_switcher) { + m_switcher->deleteLater(); + } + + for (int i = 0; i < count(); ++i) { + this->modelAt(i)->setVisible(i == currentIndex()); + } + + model->deleteLater(); + + if (oldCurrentIndex != currentIndex()) + Q_EMIT currentIndexChanged(); + if (oldCurrent != current) + Q_EMIT currentChanged(); +} + +WorkspaceListModel::WorkspaceListModel(QObject *parent) + : ObjectListModel("workspace", parent) +{ +} + +WorkspaceAnimationController *Workspace::animationController() const +{ + return m_animationController; +} + +bool WorkspaceListModel::moveRows(const QModelIndex &sourceParent, + int sourceRow, + int count, + const QModelIndex &destinationParent, + int destinationChild) +{ + // Do not support complex move + if (sourceParent.isValid() || destinationParent.isValid() || count != 1) + return false; + auto beginSuccess = + beginMoveRows({}, + sourceRow, + sourceRow, + {}, + destinationChild > sourceRow ? (destinationChild + 1) : destinationChild); + if (!beginSuccess) + return false; + m_objects.move(sourceRow, destinationChild); + endMoveRows(); + return true; +} + +WallpaperManager *Workspace::wallpaperManager() const +{ + return m_wallpaperManager; +} + +void Workspace::setWallpaperManager(WallpaperManager *manager) +{ + m_wallpaperManager = manager; +} + +bool Workspace::ownsSurface(SurfaceWrapper *surface) const +{ + return surface && (!surface->desktop() || surface->desktop()->workspace() == this); +} diff --git a/src/workspace/workspace.h b/src/workspace/workspace.h new file mode 100644 index 0000000000..80ca5b322b --- /dev/null +++ b/src/workspace/workspace.h @@ -0,0 +1,126 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "surface/surfacecontainer.h" +#include "surface/surfacefilterproxymodel.h" +#include "workspace/workspacemodel.h" + +#include + +class TreelandUserConfig; +class WallpaperManager; +class SurfaceWrapper; +class Workspace; +class WorkspaceAnimationController; +Q_MOC_INCLUDE("workspace/workspaceanimationcontroller.h") +Q_MOC_INCLUDE("treelanduserconfig.hpp") + +class WorkspaceListModel : public ObjectListModel +{ + Q_OBJECT + QML_ANONYMOUS +public: + explicit WorkspaceListModel(QObject *parent = nullptr); + bool moveRows(const QModelIndex &sourceParent, + int sourceRow, + int count, + const QModelIndex &destinationParent, + int destinationChild) override; +}; + +class Workspace : public SurfaceContainer +{ + Q_OBJECT + Q_PROPERTY(TreelandUserConfig *config READ config CONSTANT FINAL) + Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged FINAL) + Q_PROPERTY(WorkspaceModel *current READ current NOTIFY currentChanged FINAL) + Q_PROPERTY(SurfaceFilterProxyModel* currentFilter READ currentFilter NOTIFY currentFilterChanged FINAL) + Q_PROPERTY(WorkspaceModel *showOnAllWorkspaceModel READ showOnAllWorkspaceModel CONSTANT FINAL) + Q_PROPERTY(WorkspaceListModel *models READ models CONSTANT FINAL) + Q_PROPERTY(WorkspaceAnimationController *animationController READ animationController CONSTANT FINAL) + Q_PROPERTY(int count READ count NOTIFY countChanged FINAL) + QML_ELEMENT + QML_UNCREATABLE("Created only in C++") + +public: + explicit Workspace(SurfaceContainer *parent, TreelandUserConfig *config); + TreelandUserConfig *config() const; + void resetView(); + WallpaperManager *wallpaperManager() const; + void setWallpaperManager(WallpaperManager *manager); + + // When workspaceId is -1 will move to current workspace + Q_INVOKABLE void moveSurfaceTo(SurfaceWrapper *surface, int workspaceId = -1); + Q_INVOKABLE int getLeftWorkspaceId(int workspaceId); + Q_INVOKABLE int getRightWorkspaceId(int workspaceId); + + void addSurface(SurfaceWrapper *surface, int workspaceId); + void addSurface(SurfaceWrapper *surface) override; + Q_INVOKABLE void moveModelTo(int workspaceId, int destinationIndex); + + void removeSurface(SurfaceWrapper *surface) override; + int modelIndexOfSurface(SurfaceWrapper *surface) const; + + Q_INVOKABLE int createModel(const QString &name = QLatin1String(""), bool visible = false); + Q_INVOKABLE void removeModel(int index); + Q_INVOKABLE WorkspaceModel *modelAt(int index) const; + Q_INVOKABLE WorkspaceModel *modelFromId(int id) const; + + void reloadFromConfig(); + + int count() const; + int currentIndex() const; + WorkspaceModel *showOnAllWorkspaceModel() const; + void setCurrentIndex(int newCurrentIndex); + Q_INVOKABLE void switchToNext(); + Q_INVOKABLE void switchToPrev(); + Q_INVOKABLE void switchTo(int index, bool animated = true); + + WorkspaceModel *current() const; + void setCurrent(WorkspaceModel *container); + + SurfaceFilterProxyModel *currentFilter(); + + WorkspaceListModel *models(); + static inline constexpr int ShowOnAllWorkspaceId = -2; + + Q_INVOKABLE void startPreviewing(SurfaceWrapper *previewingItem); + Q_INVOKABLE void stopPreviewing(); + + void pushActivedSurface(SurfaceWrapper *surface); + void removeActivedSurface(SurfaceWrapper *surface); + void clearActivedSurface(); + void setSwitcherEnabled(bool enabled); + + WorkspaceAnimationController *animationController() const; + void createSwitcher(); + void updateSurfaceOwnsOutput(SurfaceWrapper *surface); + void updateSurfacesOwnsOutput(); + +Q_SIGNALS: + void currentChanged(); + void currentFilterChanged(); + void currentIndexChanged(); + void countChanged(); + void workspaceAdded(); + +private: + int nextWorkspaceId() const; + int doCreateModel(const QString &name, bool visible = false); + void doRemoveModel(int index); + void doSetCurrentIndex(int newCurrentIndex); + + bool ownsSurface(SurfaceWrapper *surface) const; + + TreelandUserConfig *const m_config; + uint m_currentIndex; + QPointer m_wallpaperManager; + WorkspaceListModel *m_models; + WorkspaceModel *m_showOnAllWorkspaceModel; + QPointer m_switcher; + SurfaceFilterProxyModel *m_currentFilter; + WorkspaceAnimationController *m_animationController; + bool m_switcherEnabled = true; + QPointer m_previewingItem; +}; diff --git a/src/workspace/workspaceanimationcontroller.cpp b/src/workspace/workspaceanimationcontroller.cpp new file mode 100644 index 0000000000..11b34bfa30 --- /dev/null +++ b/src/workspace/workspaceanimationcontroller.cpp @@ -0,0 +1,269 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "workspaceanimationcontroller.h" + +#include "plugins/multitaskview/multitaskview.h" + +#include +#include "core/waylandserver.h" +#include "treelanduserconfig.hpp" +#include "animationconfig.hpp" + +WorkspaceAnimationController::WorkspaceAnimationController(QObject *parent) + : QObject{ parent } + , m_slideAnimation(new QSequentialAnimationGroup(this)) + , m_bounceAnimation(new QSequentialAnimationGroup(this)) + , m_posAnimation(new QPropertyAnimation(this)) + , m_bounceOutAnimation(new QPropertyAnimation(this)) + , m_bounceInAnimation(new QPropertyAnimation(this)) +{ + m_posAnimation->setPropertyName("viewportPos"); + m_posAnimation->setTargetObject(this); + connect(m_slideAnimation, &QSequentialAnimationGroup::finished, this, [this] { + if (m_needBounce) { + startBounceAnimation(); + } else { + finishAnimation(); + } + }); + m_slideAnimation->addAnimation(m_posAnimation); + m_bounceInAnimation->setTargetObject(this); + m_bounceInAnimation->setEasingCurve(QEasingCurve::InOutExpo); + m_bounceInAnimation->setPropertyName("viewportPos"); + m_bounceOutAnimation->setTargetObject(this); + m_bounceOutAnimation->setEasingCurve(QEasingCurve::InOutExpo); + m_bounceOutAnimation->setPropertyName("viewportPos"); + m_bounceAnimation->addAnimation(m_bounceInAnimation); + m_bounceAnimation->addAnimation(m_bounceOutAnimation); + connect(m_bounceAnimation, + &QSequentialAnimationGroup::finished, + this, + &WorkspaceAnimationController::finishAnimation); +} + +void WorkspaceAnimationController::setConfig(TreelandUserConfig *config) +{ + Q_ASSERT(config); + m_posAnimation->setEasingCurve(static_cast(config->multitaskviewEasingCurveType())); + m_posAnimation->setDuration(config->multitaskviewAnimationDuration()); + m_bounceInAnimation->setDuration(config->multitaskviewAnimationDuration() / 2); + m_bounceOutAnimation->setDuration(config->multitaskviewAnimationDuration() / 2); +} + +bool WorkspaceAnimationController::slideEnabled() const +{ + auto *server = WaylandServer::instance(); + auto *config = server ? server->animationConfig() : nullptr; + return !config || config->workspaceSwitch(); +} + +bool WorkspaceAnimationController::bounceEnabled() const +{ + auto *server = WaylandServer::instance(); + auto *config = server ? server->animationConfig() : nullptr; + return !config || config->workspaceBounce(); +} + +qreal WorkspaceAnimationController::refWidth() const +{ + return m_refWidth; +} + +void WorkspaceAnimationController::setRefWidth(qreal newRefWidth) +{ + if (qFuzzyCompare(m_refWidth, newRefWidth)) + return; + m_refWidth = newRefWidth; + Q_EMIT refWidthChanged(); + Q_EMIT refWrapChanged(); +} + +qreal WorkspaceAnimationController::refGap() const +{ + return m_refGap; +} + +void WorkspaceAnimationController::setRefGap(qreal newRefGap) +{ + if (qFuzzyCompare(m_refGap, newRefGap)) + return; + m_refGap = newRefGap; + Q_EMIT refGapChanged(); + Q_EMIT refWrapChanged(); +} + +qreal WorkspaceAnimationController::refBounce() const +{ + return m_refBounce; +} + +void WorkspaceAnimationController::setRefBounce(qreal newRefBounce) +{ + if (qFuzzyCompare(m_refBounce, newRefBounce)) + return; + m_refBounce = newRefBounce; + Q_EMIT refBounceChanged(); +} + +qreal WorkspaceAnimationController::bounceFactor() const +{ + return m_bounceFactor; +} + +void WorkspaceAnimationController::setBounceFactor(qreal newBounceFactor) +{ + if (qFuzzyCompare(m_bounceFactor, newBounceFactor)) + return; + m_bounceFactor = newBounceFactor; + Q_EMIT bounceFactorChanged(); +} + +qreal WorkspaceAnimationController::refWrap() const +{ + return refWidth() + refGap(); +} + +bool WorkspaceAnimationController::running() const +{ + return m_running; +} + +qreal WorkspaceAnimationController::viewportPos() const +{ + return m_viewportPos; +} + +uint WorkspaceAnimationController::pendingWorkspaceIndex() const +{ + return m_pendingWorkspaceIndex; +} + +void WorkspaceAnimationController::slideRunning(uint toWorkspaceIndex) +{ + if (!running()) + return; + m_slideAnimation->stop(); + m_bounceAnimation->stop(); + m_animationInitial = viewportPos(); + m_animationDestination = refWrap() * toWorkspaceIndex; + m_initialIndex = viewportPos() / refWrap(); + m_destinationIndex = toWorkspaceIndex; + m_currentDirection = m_animationDestination > m_animationInitial ? Right : Left; +} + +void WorkspaceAnimationController::slideNormal(uint fromWorkspaceIndex) +{ + m_slideAnimation->stop(); + m_bounceAnimation->stop(); + m_initialIndex = fromWorkspaceIndex; + m_destinationIndex = fromWorkspaceIndex; + m_animationInitial = refWrap() * fromWorkspaceIndex; + m_animationDestination = m_animationInitial; + setViewportPos(m_animationInitial); +} + +void WorkspaceAnimationController::slide(uint fromWorkspaceIndex, uint toWorkspaceIndex) +{ + m_needBounce = false; + slideRunning(toWorkspaceIndex); + slideNormal(fromWorkspaceIndex); + m_destinationIndex = toWorkspaceIndex; + m_animationDestination = refWrap() * toWorkspaceIndex; + m_currentDirection = (fromWorkspaceIndex < toWorkspaceIndex) ? Right : Left; + startSlideAnimation(); +} + +void WorkspaceAnimationController::bounce(uint currentWorkspaceIndex, Direction direction) +{ + if (m_bounceAnimation->state() == QAbstractAnimation::Running) + return; + if (m_slideAnimation->state() != QAbstractAnimation::Running) { + m_initialIndex = currentWorkspaceIndex; + m_destinationIndex = currentWorkspaceIndex; + m_currentDirection = direction; + m_animationInitial = refWrap() * m_initialIndex; + m_animationDestination = refWrap() * m_destinationIndex; + startBounceAnimation(); + } else { + m_needBounce = true; + } +} + +qreal WorkspaceAnimationController::gestureObstruction(qreal gestureValue) +{ + static constexpr qreal k = 10.0; + return (bounceFactor() / M_PI) * std::atan(k * gestureValue); +} + +void WorkspaceAnimationController::startGestureSlide(qreal cb, bool bounce) +{ + qreal offset = bounce ? gestureObstruction(cb) : cb; + qreal pos = m_animationInitial + refWrap() * offset; + + setViewportPos(pos); +} + +void WorkspaceAnimationController::startSlideAnimation() +{ + if (!slideEnabled()) { + // Apply the destination immediately and finish without playing the slide. + m_slideAnimation->stop(); + setViewportPos(m_animationDestination); + finishAnimation(); + return; + } + + m_posAnimation->setStartValue(m_animationInitial); + m_posAnimation->setEndValue(m_animationDestination); + m_slideAnimation->start(); + setRunning(true); +} + +void WorkspaceAnimationController::startBounceAnimation() +{ + if (!bounceEnabled()) { + m_bounceAnimation->stop(); + setViewportPos(m_animationDestination); + finishAnimation(); + return; + } + + auto bounceDestination = + m_animationDestination + (m_currentDirection == Right ? refBounce() : -refBounce()); + m_bounceInAnimation->setStartValue(m_animationDestination); + m_bounceInAnimation->setEndValue(bounceDestination); + m_bounceOutAnimation->setStartValue(bounceDestination); + m_bounceOutAnimation->setEndValue(m_animationDestination); + m_bounceAnimation->start(); + setRunning(true); +} + +void WorkspaceAnimationController::setRunning(bool running) +{ + if (running == m_running) + return; + m_running = running; + Q_EMIT runningChanged(); +} + +void WorkspaceAnimationController::cancel() +{ + m_slideAnimation->stop(); + m_bounceAnimation->stop(); + setViewportPos(0); + setRunning(false); +} + +void WorkspaceAnimationController::finishAnimation() +{ + Q_EMIT finished(); + setRunning(false); +} + +void WorkspaceAnimationController::setViewportPos(qreal newViewportPos) +{ + if (qFuzzyCompare(m_viewportPos, newViewportPos)) + return; + m_viewportPos = newViewportPos; + Q_EMIT viewportPosChanged(); +} diff --git a/src/workspace/workspaceanimationcontroller.h b/src/workspace/workspaceanimationcontroller.h new file mode 100644 index 0000000000..90c201da01 --- /dev/null +++ b/src/workspace/workspaceanimationcontroller.h @@ -0,0 +1,97 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include +#include +#include +#include + +class TreelandUserConfig; + +class WorkspaceAnimationController : public QObject +{ + Q_OBJECT + QML_ELEMENT +public: + explicit WorkspaceAnimationController(QObject *parent = nullptr); + void setConfig(TreelandUserConfig *config); + Q_PROPERTY(qreal refWidth READ refWidth WRITE setRefWidth NOTIFY refWidthChanged FINAL) + Q_PROPERTY(qreal refGap READ refGap WRITE setRefGap NOTIFY refGapChanged FINAL) + Q_PROPERTY(qreal refBounce READ refBounce WRITE setRefBounce NOTIFY refBounceChanged FINAL) + Q_PROPERTY(qreal bounceFactor READ bounceFactor WRITE setBounceFactor NOTIFY bounceFactorChanged FINAL) + Q_PROPERTY(qreal refWrap READ refWrap NOTIFY refWrapChanged FINAL) + Q_PROPERTY(bool running READ running NOTIFY runningChanged FINAL) + Q_PROPERTY(qreal viewportPos READ viewportPos WRITE setViewportPos NOTIFY viewportPosChanged FINAL) + Q_PROPERTY(uint pendingWorkspaceIndex READ pendingWorkspaceIndex NOTIFY pendingWorkspaceIndexChanged FINAL) + qreal refWidth() const; + void setRefWidth(qreal newRefWidth); + qreal refGap() const; + void setRefGap(qreal newRefGap); + qreal refBounce() const; + void setRefBounce(qreal newRefBounce); + qreal bounceFactor() const; + void setBounceFactor(qreal newBounceFactor); + qreal refWrap() const; + bool running() const; + qreal viewportPos() const; + void setViewportPos(qreal newViewportPos); + uint pendingWorkspaceIndex() const; + + // Whether the corresponding automatic transition may play; the caller can + // skip creating the visual switcher layer entirely when it cannot. + bool slideEnabled() const; + bool bounceEnabled() const; + + enum Direction + { + Left, + Right + }; + Q_ENUM(Direction) + +Q_SIGNALS: + void refWidthChanged(); + void refGapChanged(); + void refBounceChanged(); + void bounceFactorChanged(); + void refWrapChanged(); + void runningChanged(); + void viewportPosChanged(); + void pendingWorkspaceIndexChanged(); + void finished(); + +public Q_SLOTS: + void slideRunning(uint toWorkspaceIndex); + void slideNormal(uint fromWorkspaceIndex); + void slide(uint fromWorkspaceIndex, uint toWorkspaceIndex); + void bounce(uint currentWorkspaceIndex, Direction direction); + void setRunning(bool running); + void startSlideAnimation(); + void cancel(); + void startGestureSlide(qreal cb, bool bounce = false); + +private: + void startBounceAnimation(); + void finishAnimation(); + qreal gestureObstruction(qreal gestureValue); + + qreal m_refWidth = 1920; + qreal m_refGap = 30; + qreal m_refBounce = 384; + qreal m_bounceFactor = 0.3; + bool m_running = false; + qreal m_viewportPos = 0; + uint m_pendingWorkspaceIndex = 0; + qreal m_animationInitial = 0; + qreal m_animationDestination = 0; + bool m_needBounce = false; + uint m_initialIndex = 0; + uint m_destinationIndex = 0; + Direction m_currentDirection = Left; + QSequentialAnimationGroup *m_slideAnimation; + QSequentialAnimationGroup *m_bounceAnimation; + QPropertyAnimation *m_posAnimation; + QPropertyAnimation *m_bounceOutAnimation; + QPropertyAnimation *m_bounceInAnimation; +}; diff --git a/src/workspace/workspacemodel.cpp b/src/workspace/workspacemodel.cpp new file mode 100644 index 0000000000..675888ff0a --- /dev/null +++ b/src/workspace/workspacemodel.cpp @@ -0,0 +1,151 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "workspacemodel.h" +#include "workspace.h" + +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" + +WorkspaceModel::WorkspaceModel(QObject *parent, + int id, + std::forward_list activedSurfaceHistory) + : SurfaceListModel(parent) + , m_id(id) + , m_activedSurfaceHistory(activedSurfaceHistory) +{ +} + +QString WorkspaceModel::name() const +{ + return m_name; +} + +void WorkspaceModel::setName(const QString &newName) +{ + if (m_name == newName) + return; + m_name = newName; + Q_EMIT nameChanged(); +} + +int WorkspaceModel::id() const +{ + return m_id; +} + +bool WorkspaceModel::visible() const +{ + return m_visible; +} + +void WorkspaceModel::setVisible(bool visible) +{ + if (m_visible == visible) + return; + m_visible = visible; + for (auto surface : std::as_const(surfaces())) + surface->setHideByWorkspace(!visible); + Q_EMIT visibleChanged(); +} + +bool WorkspaceModel::opaque() const +{ + return m_opaque; +} + +void WorkspaceModel::setOpaque(bool opaque) +{ + if (m_opaque == opaque) + return; + m_opaque = opaque; + for (auto surface : std::as_const(surfaces())) + surface->setOpacity(opaque ? 1.0 : 0.0); + Q_EMIT opaqueChanged(); +} + +void WorkspaceModel::addSurface(SurfaceWrapper *surface) +{ + SurfaceListModel::addSurface(surface); + if (!m_opaque) { + surface->setOpacity(m_opaque ? 1.0 : 0.0); + surface->setHideByWorkspace(m_visible); + connect(this, &WorkspaceModel::opaqueChanged, surface, [this, surface]() { + surface->setHideByWorkspace(!m_visible); + }); + } else { + surface->setHideByWorkspace(!m_visible); + } + + surface->setWorkspaceId(m_id); +} + +void WorkspaceModel::removeSurface(SurfaceWrapper *surface) +{ + surface->disconnect(this); + SurfaceListModel::removeSurface(surface); + surface->setWorkspaceId(-1); + surface->setHideByWorkspace(false); + m_activedSurfaceHistory.remove(surface); +} + +SurfaceWrapper *WorkspaceModel::latestActiveSurface() const +{ + if (m_activedSurfaceHistory.empty()) + return nullptr; + return m_activedSurfaceHistory.front(); +} + +SurfaceWrapper *WorkspaceModel::activePenultimateWindow() const +{ + if (m_activedSurfaceHistory.empty()) + return nullptr; + + auto first = m_activedSurfaceHistory.begin(); + auto second = std::next(first); + if (second == m_activedSurfaceHistory.end()) { + return nullptr; + } + + return *second; +} + +SurfaceWrapper *WorkspaceModel::findNextActivedSurface() const +{ + auto it = m_activedSurfaceHistory.begin(); + if (it == m_activedSurfaceHistory.end() || ++it == m_activedSurfaceHistory.end()) + return nullptr; + return *it; +} + +void WorkspaceModel::pushActivedSurface(SurfaceWrapper *surface) +{ + m_activedSurfaceHistory.remove(surface); + m_activedSurfaceHistory.push_front(surface); +} + +void WorkspaceModel::removeActivedSurface(SurfaceWrapper *surface) +{ + m_activedSurfaceHistory.remove(surface); +} + +void WorkspaceModel::clearActivedSurface() +{ + m_activedSurfaceHistory.clear(); +} + +int WorkspaceModel::activeHistoryIndex(SurfaceWrapper *surface) const +{ + auto it = std::find(m_activedSurfaceHistory.begin(), m_activedSurfaceHistory.end(), surface); + return static_cast(std::distance(m_activedSurfaceHistory.begin(), it)); +} + +bool WorkspaceModel::laterActiveThan(SurfaceWrapper *a, SurfaceWrapper *b) +{ + return activeHistoryIndex(a) < activeHistoryIndex(b); +} + +Workspace *WorkspaceModel::workspaceManager() const +{ + return qobject_cast(parent()); +} diff --git a/src/workspace/workspacemodel.h b/src/workspace/workspacemodel.h new file mode 100644 index 0000000000..f6af070fa6 --- /dev/null +++ b/src/workspace/workspacemodel.h @@ -0,0 +1,70 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "surface/surfacecontainer.h" + +#include + +class SurfaceWrapper; +class Workspace; +Q_MOC_INCLUDE("workspace/workspace.h") + +class WorkspaceModel : public SurfaceListModel +{ + friend class Workspace; + friend class MultitaskviewSurfaceModel; + Q_OBJECT + Q_PROPERTY(Workspace *workspaceManager READ workspaceManager CONSTANT FINAL) + Q_PROPERTY(int id READ id CONSTANT FINAL) + Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged FINAL) + Q_PROPERTY(bool visible READ visible WRITE setVisible NOTIFY visibleChanged FINAL) + Q_PROPERTY(bool opaque READ opaque WRITE setOpaque NOTIFY opaqueChanged FINAL) + + QML_ELEMENT + QML_UNCREATABLE("Created only in C++") + +public: + explicit WorkspaceModel(QObject *parent, + int id, + std::forward_list activedSurfaceHistory); + + Workspace *workspaceManager() const; + QString name() const; + void setName(const QString &newName); + + int id() const; + + bool visible() const; + void setVisible(bool visible); + + bool opaque() const; + void setOpaque(bool opaque); + + void addSurface(SurfaceWrapper *surface) override; + void removeSurface(SurfaceWrapper *surface) override; + + Q_INVOKABLE SurfaceWrapper *latestActiveSurface() const; + Q_INVOKABLE SurfaceWrapper *activePenultimateWindow() const; + Q_INVOKABLE SurfaceWrapper *findNextActivedSurface() const; + void pushActivedSurface(SurfaceWrapper *surface); + void removeActivedSurface(SurfaceWrapper *surface); + void clearActivedSurface(); + + int activeHistoryIndex(SurfaceWrapper *surface) const; + bool laterActiveThan(SurfaceWrapper *a, SurfaceWrapper *b); + +Q_SIGNALS: + void nameChanged(); + void indexChanged(); + void visibleChanged(); + void opaqueChanged(); + +private: + QString m_name; + int m_id = -1; + bool m_visible = false; + bool m_opaque = true; + std::forward_list m_activedSurfaceHistory; +}; diff --git a/src/xsettings/abstractsettings.cpp b/src/xsettings/abstractsettings.cpp new file mode 100644 index 0000000000..fc2c18a80d --- /dev/null +++ b/src/xsettings/abstractsettings.cpp @@ -0,0 +1,14 @@ +// Copyright (C) 2025 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "abstractsettings.h" + +AbstractSettings::AbstractSettings(xcb_connection_t *connection, QObject *parent) + : QObject(parent) + , m_connection(connection) +{ +} + +AbstractSettings::~AbstractSettings() +{ +} diff --git a/src/xsettings/abstractsettings.h b/src/xsettings/abstractsettings.h new file mode 100644 index 0000000000..4946143734 --- /dev/null +++ b/src/xsettings/abstractsettings.h @@ -0,0 +1,35 @@ +// Copyright (C) 2025 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include +#include + +class AbstractSettings : public QObject +{ + Q_OBJECT +public: + explicit AbstractSettings(xcb_connection_t *connection, QObject *parent = nullptr); + ~AbstractSettings() override; + + virtual bool initialized() const = 0; + virtual bool isEmpty() const = 0; + + virtual bool contains(const QByteArray &property) const = 0; + virtual QVariant getPropertyValue(const QByteArray &property) const = 0; + virtual void setPropertyValue(const QByteArray &property, const QVariant &value) = 0; + virtual QByteArrayList propertyList() const = 0; + virtual void apply() = 0; + +Q_SIGNALS: + void propertyChanged(const QByteArray &property, const QVariant &value); + void propertyAdded(const QByteArray &property, const QVariant &value); + void propertyRemoved(const QByteArray &property, const QVariant &value); + +protected: + xcb_connection_t *m_connection = nullptr; + xcb_atom_t m_atom = XCB_ATOM_NONE; +}; diff --git a/src/xsettings/settingmanager.cpp b/src/xsettings/settingmanager.cpp new file mode 100644 index 0000000000..8df01718dd --- /dev/null +++ b/src/xsettings/settingmanager.cpp @@ -0,0 +1,133 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "settingmanager.h" +#include "common/treelandlogging.h" + +static constexpr int BASE_DPI = 96; +static constexpr int XSETTINGS_BASE_DPI_FIXED = BASE_DPI * 1024; + +SettingManager::SettingManager(xcb_connection_t *connection, QObject *parent) + : QObject(parent) + , m_resource(new XResource(connection, this)) + , m_settings(new XSettings(connection, this)) +{ +} + +SettingManager::~SettingManager() +{ +} + +void SettingManager::setGTKTheme(const QString &themeName) +{ + m_resource->setPropertyValue(XResource::toByteArray(XResource::Gtk_ThemeName), themeName); + m_settings->setPropertyValue(XSettings::toByteArray(XSettings::Gtk_ThemeName), themeName); +} + +QString SettingManager::GTKTheme() const +{ + return m_settings->getPropertyValue(XSettings::toByteArray(XSettings::Gtk_ThemeName)).toString(); +} + +void SettingManager::setFont(const QString &name) +{ + m_resource->setPropertyValue(XResource::toByteArray(XResource::Gtk_FontName), name); + m_settings->setPropertyValue(XSettings::toByteArray(XSettings::Gtk_FontName), name); +} + +QString SettingManager::font() const +{ + return m_settings->getPropertyValue(XSettings::toByteArray(XSettings::Gtk_FontName)).toString(); +} + +void SettingManager::setIconTheme(const QString &theme) +{ + m_resource->setPropertyValue(XResource::toByteArray(XResource::Gtk_IconThemeName), theme); + m_settings->setPropertyValue(XSettings::toByteArray(XSettings::Gtk_IconThemeName), theme); +} + +QString SettingManager::iconTheme() const +{ + return m_settings->getPropertyValue(XSettings::toByteArray(XSettings::Gtk_IconThemeName)).toString(); +} + +void SettingManager::setSoundTheme(const QString &theme) +{ + m_resource->setPropertyValue(XResource::toByteArray(XResource::Net_SoundThemeName), theme); + m_settings->setPropertyValue(XSettings::toByteArray(XSettings::Net_SoundThemeName), theme); +} + +QString SettingManager::soundTheme() const +{ + return m_settings->getPropertyValue(XSettings::toByteArray(XSettings::Net_SoundThemeName)).toString(); +} + +void SettingManager::setCursorTheme(const QString &theme) +{ + m_resource->setPropertyValue(XResource::toByteArray(XResource::Gtk_CursorThemeName), theme); + m_resource->setPropertyValue(XResource::toByteArray(XResource::Xcursor_Theme), theme); + m_settings->setPropertyValue(XSettings::toByteArray(XSettings::Gtk_CursorThemeName), theme); + m_settings->setPropertyValue(XSettings::toByteArray(XSettings::Xcursor_Theme), theme); +} + +QString SettingManager::cursorTheme() const +{ + const auto theme = + m_settings->getPropertyValue(XSettings::toByteArray(XSettings::Gtk_CursorThemeName)); + if (theme.isValid()) { + return theme.toString(); + } + + return m_settings->getPropertyValue(XSettings::toByteArray(XSettings::Xcursor_Theme)) + .toString(); +} + +void SettingManager::setCursorSize(qreal value) +{ + const int size = qRound(value); + + m_resource->setPropertyValue(XResource::toByteArray(XResource::Xcursor_Size), size); + m_resource->setPropertyValue(XResource::toByteArray(XResource::Gtk_CursorThemeSize), size); + m_settings->setPropertyValue(XSettings::toByteArray(XSettings::Xcursor_Size), size); + m_settings->setPropertyValue(XSettings::toByteArray(XSettings::Gtk_CursorThemeSize), size); +} + +qreal SettingManager::cursorSize() const +{ + const auto size = m_settings->getPropertyValue(XSettings::toByteArray(XSettings::Xcursor_Size)); + if (size.isValid()) { + return size.toReal(); + } + + return m_settings->getPropertyValue(XSettings::toByteArray(XSettings::Gtk_CursorThemeSize)) + .toReal(); +} + +void SettingManager::setDoubleClickInterval(int interval) +{ + m_settings->setPropertyValue(XSettings::toByteArray(XSettings::Net_DoubleClickTime), interval); +} + +void SettingManager::setIMModule(const QString &module) +{ + m_settings->setPropertyValue(XSettings::toByteArray(XSettings::Gtk_IMModule), module); +} + +void SettingManager::setGlobalScale(qreal scale) +{ + m_resource->setPropertyValue(XResource::toByteArray(XResource::Xft_DPI), scale * BASE_DPI); + m_settings->setPropertyValue(XSettings::toByteArray(XSettings::Gdk_WindowScalingFactor), qFloor(scale)); + m_settings->setPropertyValue(XSettings::toByteArray(XSettings::Gdk_UnscaledDPI), XSETTINGS_BASE_DPI_FIXED); + m_settings->setPropertyValue(XSettings::toByteArray(XSettings::Xft_DPI), qRound(scale * XSETTINGS_BASE_DPI_FIXED)); +} + +qreal SettingManager::globalScale() const +{ + return m_settings->getPropertyValue(XSettings::toByteArray(XSettings::Xft_DPI)).toReal() / XSETTINGS_BASE_DPI_FIXED; +} + +void SettingManager::apply() +{ + m_resource->apply(); + m_settings->apply(); +} diff --git a/src/xsettings/settingmanager.h b/src/xsettings/settingmanager.h new file mode 100644 index 0000000000..a2d428acb2 --- /dev/null +++ b/src/xsettings/settingmanager.h @@ -0,0 +1,48 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "xresource.h" +#include "xsettings.h" + +#include + +class SettingManager : public QObject +{ + Q_OBJECT +public: + explicit SettingManager(xcb_connection_t *connection, QObject *parent = nullptr); + ~SettingManager() override; + + void setGTKTheme(const QString &themeName); + QString GTKTheme() const; + + void setFont(const QString &name); + QString font() const; + + void setIconTheme(const QString &theme); + QString iconTheme() const; + + void setSoundTheme(const QString &theme); + QString soundTheme() const; + + void setCursorTheme(const QString &theme); + QString cursorTheme() const; + + void setCursorSize(qreal value); + qreal cursorSize() const; + + void setDoubleClickInterval(int interval); + + void setIMModule(const QString &module); + + void setGlobalScale(qreal scale); + qreal globalScale() const; + + void apply(); + +private: + XResource *m_resource = nullptr; + XSettings *m_settings = nullptr; +}; diff --git a/src/xsettings/xresource.cpp b/src/xsettings/xresource.cpp new file mode 100644 index 0000000000..9690223fc7 --- /dev/null +++ b/src/xsettings/xresource.cpp @@ -0,0 +1,173 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "xresource.h" +#include "common/treelandlogging.h" + +#define XRESOURCE_ATOM_NAME "RESOURCE_MANAGER" + +static QPair splitXResourceLine(const QByteArray &line) +{ + int pos = -1; + bool escaped = false; + + for (int i = 0; i < line.size(); ++i) { + if (line[i] == '\\') { + escaped = !escaped; + } else if (line[i] == ':' && !escaped) { + pos = i; + break; + } else { + escaped = false; + } + } + + if (pos == -1) + return {line.trimmed(), QByteArray()}; + + QByteArray key = line.left(pos).trimmed(); + QByteArray value = line.mid(pos + 1).trimmed(); + value.replace("\\:", ":"); + + return {key, value}; +} + +XResource::XResource(xcb_connection_t *connection, QObject *parent) + : AbstractSettings(connection, parent) +{ + const xcb_setup_t *setup = xcb_get_setup(m_connection); + xcb_screen_iterator_t iter = xcb_setup_roots_iterator(setup); + m_root = iter.data->root; + xcb_intern_atom_cookie_t cookie = xcb_intern_atom(m_connection, 0, strlen(XRESOURCE_ATOM_NAME), XRESOURCE_ATOM_NAME); + xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(m_connection, cookie, nullptr); + if (reply) { + m_atom = reply->atom; + } + + free(reply); +} + +XResource::~XResource() +{ +} + +QByteArray XResource::toByteArray(XResourceKey key) +{ + switch (key) { + case Xft_DPI: return QByteArrayLiteral("Xft.dpi"); + case Xft_Antialias: return QByteArrayLiteral("Xft.antialias"); + case Xft_Hinting: return QByteArrayLiteral("Xft.hinting"); + case Xft_HintStyle: return QByteArrayLiteral("Xft.hintstyle"); + case Xft_RGBA: return QByteArrayLiteral("Xft.rgba"); + case Xft_LCDFilter: return QByteArrayLiteral("Xft.lcdfilter"); + case Xcursor_Theme: return QByteArrayLiteral("Xcursor.theme"); + case Xcursor_Size: return QByteArrayLiteral("Xcursor.size"); + case Xcursor_ThemeCore: return QByteArrayLiteral("Xcursor.theme_core"); + case Gtk_FontName: return QByteArrayLiteral("Gtk/FontName"); + case Gtk_ThemeName: return QByteArrayLiteral("Gtk/ThemeName"); + case Gtk_IconThemeName: return QByteArrayLiteral("Gtk/IconThemeName"); + case Gtk_CursorThemeName: return QByteArrayLiteral("Gtk/CursorThemeName"); + case Gtk_CursorThemeSize: return QByteArrayLiteral("Gtk/CursorThemeSize"); + case Gdk_WindowScalingFactor: return QByteArrayLiteral("Gdk/WindowScalingFactor"); + case Gdk_UnscaledDPI: return QByteArrayLiteral("Gdk/UnscaledDPI"); + case Net_ThemeName: return QByteArrayLiteral("Net/ThemeName"); + case Net_IconThemeName: return QByteArrayLiteral("Net/IconThemeName"); + case Net_SoundThemeName: return QByteArrayLiteral("Net/SoundThemeName"); + default: return QByteArrayLiteral(""); + } +} + +bool XResource::initialized() const +{ + return true; +} + +bool XResource::isEmpty() const +{ + return m_resources.isEmpty(); +} + +bool XResource::contains(const QByteArray &property) const +{ + return m_resources.contains(property); +} + +QVariant XResource::getPropertyValue(const QByteArray &property) const +{ + auto it = m_resources.constFind(property); + return it != m_resources.constEnd() ? it.value() : QVariant(); +} + +void XResource::setPropertyValue(const QByteArray &property, const QVariant &value) +{ + QVariant &xvalue = m_resources[property]; + if (xvalue == value) + return; + + if (!value.isValid()) + return; + + m_resources[property] = value; +} + +QByteArrayList XResource::propertyList() const +{ + QByteArrayList merged; + const auto keys = m_resources.keys(); + for (auto v : keys) + merged.append(v); + + return merged; +} + +void XResource::apply() +{ + QByteArray text; + for (auto it = m_resources.constBegin(); it != m_resources.constEnd(); ++it) { + text.append(it.key()); + text.append(':'); + text.append('\t'); + text.append(it.value().toString().toUtf8()); + text.append('\n'); + } + + xcb_change_property(m_connection, + XCB_PROP_MODE_REPLACE, + m_root, + m_atom, + XCB_ATOM_STRING, + 8, + text.size(), + text.constData()); + xcb_flush(m_connection); +} + +void XResource::reload() +{ + m_resources.clear(); + + xcb_get_property_cookie_t cookie = + xcb_get_property(m_connection, 0, m_root, m_atom, + XCB_ATOM_STRING, 0, UINT32_MAX); + xcb_get_property_reply_t *reply = + xcb_get_property_reply(m_connection, cookie, nullptr); + if (!reply) { + qCCritical(lcTlXsettings) << "xcb_intern_atom_reply returned nullptr, atom:" << XRESOURCE_ATOM_NAME; + return; + } + + int len = xcb_get_property_value_length(reply); + const char *data = (const char *)xcb_get_property_value(reply); + QByteArray text(data, len); + free(reply); + + const QList lines = text.split('\n'); + for (const QByteArray &line : std::as_const(lines)) { + if (line.trimmed().isEmpty()) + continue; + + auto [key, value] = splitXResourceLine(line); + if (!key.isEmpty()) + m_resources[key] = QString::fromUtf8(value); + } +} diff --git a/src/xsettings/xresource.h b/src/xsettings/xresource.h new file mode 100644 index 0000000000..4197d85f58 --- /dev/null +++ b/src/xsettings/xresource.h @@ -0,0 +1,111 @@ +// Copyright (C) 2025 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "abstractsettings.h" + +/*## Common `Xresources` (X11) Settings + +| Category | Property | Example Value | Description | +| ------------------------ | --------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------- | +| **Xft (Font Rendering)** | `Xft.dpi` | `96` / `144` / `192` | DPI setting used by font rendering. Often overridden by `xsettingsd` or `xrdb`. | +| | `Xft.antialias` | `1` or `0` | Enables (1) or disables (0) font anti-aliasing. | +| | `Xft.hinting` | `1` or `0` | Enables (1) or disables (0) font hinting. | +| | `Xft.hintstyle` | `hintnone` / `hintslight` / `hintmedium` / `hintfull` | Controls the degree of font hinting. | +| | `Xft.rgba` | `none` / `rgb` / `bgr` / `vrgb` / `vbgr` | Subpixel rendering order; depends on monitor pixel layout. | +| | `Xft.lcdfilter` | `lcdnone` / `lcddefault` / `lcdlight` / `lcdlegacy` | LCD subpixel filtering mode. | + +| **Xcursor (Mouse Cursor)** | `Xcursor.theme` | `breeze_cursors` / `Adwaita` / `DMZ-White` | Name of the cursor theme. | +| | `Xcursor.size` | `24` / `32` / `48` | Cursor size in pixels. | +| | `Xcursor.theme_core` | `true` / `false` | Whether to apply the theme to the core (legacy) cursor shapes. | + +| **XTerm / URxvt (Terminal)** | `XTerm*faceName` / `URxvt.font` | `"Noto Sans Mono:size=10"` | Sets the font for terminal text. | +| | `XTerm*faceSize` / `URxvt.fontSize` | `10` | Font size. | +| | `XTerm*geometry` | `80x24` | Default terminal geometry. | +| | `XTerm*scrollBar` | `true` / `false` | Show or hide scroll bar. | +| | `URxvt*scrollBar_right` | `true` / `false` | Scrollbar on the right side. | +| | `URxvt*perl-ext-common` | `default,matcher` | List of enabled Perl extensions (URxvt only). | + +| **GTK Theme (through xrdb bridge)** | `Gtk/FontName` | `"Noto Sans 10"` | Default GTK interface font. | +| | `Gtk/ThemeName` | `"Adwaita-dark"` | GTK theme name. | +| | `Gtk/IconThemeName` | `"breeze"` | GTK icon theme. | +| | `Gtk/CursorThemeName` | `"breeze_cursors"` | GTK cursor theme. | +| | `Gtk/CursorThemeSize` | `24` / `48` | Cursor size. | + +| **General UI (X Toolkit apps)** | `*foreground` | `#ffffff` | Default text color. | +| | `*background` | `#000000` | Default background color. | +| | `*cursorColor` | `#ffcc00` | Text cursor color. | +| | `*highlightColor` | `#0078d7` | Highlight selection color. | +| | `*borderColor` | `#444444` | Border color for some widgets. | +| | `*font` | `fixed` / `9x15` / `xft:Noto Sans-10` | Fallback font setting for older X11 apps. | + +| **Misc (Desktop & Toolkit Integration)** | `Net/ThemeName` | `"Breeze"` | GTK / DE theme name for toolkits integrating via XSettings. | +| | `Net/IconThemeName` | `"Papirus"` | Global icon theme. | +| | `Net/SoundThemeName` | `"freedesktop"` | Name of sound theme for event sounds. | +| | `Gdk/WindowScalingFactor` | `1` / `2` | Window scaling factor (used by GTK). | +| | `Gdk/UnscaledDPI` | `98304` | Unscaled base DPI (×1024 fixed point). | + +## Notes on Value Calculation + +| Concept | Explanation | +| ------------------------ | --------------------------------------------------------------------------------------------------------------------------- | +| `Xft.dpi` | Usually calculated as:
`DPI = 25.4 × (screen_pixel_height / physical_height_mm)`
Example: 2160p on 15.6" (~141 dpi) | +| `Gdk/UnscaledDPI` | GTK stores this as `DPI × 1024`. Example: `96 × 1024 = 98304`. | +| `Xft.hintstyle` & `rgba` | Correspond to fontconfig settings — usually set via `~/.config/fontconfig/fonts.conf` or inherited from DE. | +| `Xcursor.size` | Often scaled according to `Gdk/WindowScalingFactor`. |*/ + +class XResource : public AbstractSettings +{ + Q_OBJECT +public: + enum XResourceKey { + Unknown = 0, + + Xft_DPI, + Xft_Antialias, + Xft_Hinting, + Xft_HintStyle, + Xft_RGBA, + Xft_LCDFilter, + + Xcursor_Theme, + Xcursor_Size, + Xcursor_ThemeCore, + + Gtk_FontName, + Gtk_ThemeName, + Gtk_IconThemeName, + Gtk_CursorThemeName, + Gtk_CursorThemeSize, + + Gdk_WindowScalingFactor, + Gdk_UnscaledDPI, + + Net_ThemeName, + Net_IconThemeName, + Net_SoundThemeName + }; + Q_ENUM(XResourceKey) + + explicit XResource(xcb_connection_t *connection, QObject *parent = nullptr); + ~XResource() override; + + static QByteArray toByteArray(XResourceKey key); + + bool initialized() const override; + bool isEmpty() const override; + + bool contains(const QByteArray &property) const override; + QVariant getPropertyValue(const QByteArray &property) const override; + void setPropertyValue(const QByteArray &property, const QVariant &value) override; + QByteArrayList propertyList() const override; + void apply() override; + +private: + void reload(); + +private: + xcb_window_t m_root = XCB_WINDOW_NONE; + QMap m_resources; +}; diff --git a/src/xsettings/xsettings.cpp b/src/xsettings/xsettings.cpp new file mode 100644 index 0000000000..2471342e75 --- /dev/null +++ b/src/xsettings/xsettings.cpp @@ -0,0 +1,564 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "xsettings.h" +#include "common/treelandlogging.h" + +#include +#include +#include + +#define kMaxPropertySize 4096 +#define XSETTINGS_ATOM_NAME "_XSETTINGS_SETTINGS" +#define MANAGER_ATOM_NAME "MANAGER" +#define XSETTINGS_NOTIFY_ATOM_NAME "_XSETTINGS_SETTINGS_NOTIFY" +#define XSETTINGS_SIGNAL_ATOM_NAME "_XSETTINGS_SETTINGS_SIGNAL" + +static int round_to_nearest_multiple_of_4(int value) +{ + int remainder = value % 4; + if (!remainder) + return value; + return value + 4 - remainder; +} + +XSettings::XSettings(xcb_connection_t *connection, QObject *parent) + : AbstractSettings(connection, parent) +{ + initX11(-1, true); +} + +XSettings::~XSettings() +{ +} + +QByteArray XSettings::toByteArray(XSettingsKey key) +{ + switch (key) { + case Xft_DPI: return QByteArrayLiteral("Xft/DPI"); + case Xft_Antialias: return QByteArrayLiteral("Xft/Antialias"); + case Xft_Hinting: return QByteArrayLiteral("Xft/Hinting"); + case Xft_HintStyle: return QByteArrayLiteral("Xft/HintStyle"); + case Xft_RGBA: return QByteArrayLiteral("Xft/RGBA"); + case Xft_LCDFilter: return QByteArrayLiteral("Xft/Lcdfilter"); + + case Xcursor_Theme: return QByteArrayLiteral("Xcursor/Theme"); + case Xcursor_Size: return QByteArrayLiteral("Xcursor/Size"); + case Xcursor_ThemeCore: return QByteArrayLiteral("Xcursor/ThemeCore"); + + case Gdk_WindowScalingFactor: return QByteArrayLiteral("Gdk/WindowScalingFactor"); + case Gdk_UnscaledDPI: return QByteArrayLiteral("Gdk/UnscaledDPI"); + + case Gtk_FontName: return QByteArrayLiteral("Gtk/FontName"); + case Gtk_ThemeName: return QByteArrayLiteral("Gtk/ThemeName"); + case Gtk_IconThemeName: return QByteArrayLiteral("Gtk/IconThemeName"); + case Gtk_CursorThemeName: return QByteArrayLiteral("Gtk/CursorThemeName"); + case Gtk_CursorThemeSize: return QByteArrayLiteral("Gtk/CursorThemeSize"); + case Gtk_RecentFilesEnabled: return QByteArrayLiteral("Gtk/RecentFilesEnabled"); + case Gtk_ShowStatusShapes: return QByteArrayLiteral("Gtk/ShowStatusShapes"); + case Gtk_ShowInputMethodMenu: return QByteArrayLiteral("Gtk/ShowInputMethodMenu"); + case Gtk_TimeoutInitial: return QByteArrayLiteral("Gtk/TimeoutInitial"); + case Gtk_TimeoutRepeat: return QByteArrayLiteral("Gtk/TimeoutRepeat"); + case Gtk_DecorationLayout: return QByteArrayLiteral("Gtk/DecorationLayout"); + case Gtk_IMModule: return QByteArrayLiteral("Gtk/IMModule"); + case Gtk_ShellShowsDesktop: return QByteArrayLiteral("Gtk/ShellShowsDesktop"); + case Gtk_MenuImages: return QByteArrayLiteral("Gtk/MenuImages"); + case Gtk_EnablePrimaryPaste: return QByteArrayLiteral("Gtk/EnablePrimaryPaste"); + case Gtk_KeynavUseCaret: return QByteArrayLiteral("Gtk/KeynavUseCaret"); + case Gtk_ShellShowsAppMenu: return QByteArrayLiteral("Gtk/ShellShowsAppMenu"); + case Gtk_CanChangeAccels: return QByteArrayLiteral("Gtk/CanChangeAccels"); + case Gtk_DialogsUseHeader: return QByteArrayLiteral("Gtk/DialogsUseHeader"); + case Gtk_ToolbarStyle: return QByteArrayLiteral("Gtk/ToolbarStyle"); + case Gtk_KeyThemeName: return QByteArrayLiteral("Gtk/KeyThemeName"); + case Gtk_IMPreeditStyle: return QByteArrayLiteral("Gtk/IMPreeditStyle"); + case Gtk_EnableAnimations: return QByteArrayLiteral("Gtk/EnableAnimations"); + case Gtk_ToolbarIconSize: return QByteArrayLiteral("Gtk/ToolbarIconSize"); + case Gtk_IMStatusStyle: return QByteArrayLiteral("Gtk/IMStatusStyle"); + case Gtk_RecentFilesMaxAge: return QByteArrayLiteral("Gtk/RecentFilesMaxAge"); + case Gtk_Modules: return QByteArrayLiteral("Gtk/Modules"); + case Gtk_AutoMnemonics: return QByteArrayLiteral("Gtk/AutoMnemonics"); + case Gtk_ColorScheme: return QByteArrayLiteral("Gtk/ColorScheme"); + case Gtk_MenuBarAccel: return QByteArrayLiteral("Gtk/MenuBarAccel"); + case Gtk_ColorPalette: return QByteArrayLiteral("Gtk/ColorPalette"); + case Gtk_OverlayScrolling: return QByteArrayLiteral("Gtk/OverlayScrolling"); + case Gtk_SessionBusId: return QByteArrayLiteral("Gtk/SessionBusId"); + case Gtk_ShowUnicodeMenu: return QByteArrayLiteral("Gtk/ShowUnicodeMenu"); + case Gtk_CursorBlinkTimeout: return QByteArrayLiteral("Gtk/CursorBlinkTimeout"); + case Gtk_ButtonImages: return QByteArrayLiteral("Gtk/ButtonImages"); + case Gtk_TitlebarRightClick: return QByteArrayLiteral("Gtk/TitlebarRightClick"); + case Gtk_TitlebarDoubleClick: return QByteArrayLiteral("Gtk/TitlebarDoubleClick"); + case Gtk_TitlebarMiddleClick: return QByteArrayLiteral("Gtk/TitlebarMiddleClick"); + case Gtk_MonospaceFontName: return QByteArrayLiteral("Gtk/MonospaceFontName"); + case Gtk_ApplicationPreferDarkTheme: return QByteArrayLiteral("Gtk/ApplicationPreferDarkTheme"); + case Gtk_PrimaryButtonWarpsSlider: return QByteArrayLiteral("Gtk/PrimaryButtonWarpsSlider"); + + case Net_DndDragThreshold: return QByteArrayLiteral("Net/DndDragThreshold"); + case Net_CursorBlinkTime: return QByteArrayLiteral("Net/CursorBlinkTime"); + case Net_ThemeName: return QByteArrayLiteral("Net/ThemeName"); + case Net_DoubleClickTime: return QByteArrayLiteral("Net/DoubleClickTime"); + case Net_CursorBlink: return QByteArrayLiteral("Net/CursorBlink"); + case Net_FallbackIconTheme: return QByteArrayLiteral("Net/FallbackIconTheme"); + case Net_EnableEventSounds: return QByteArrayLiteral("Net/EnableEventSounds"); + case Net_IconThemeName: return QByteArrayLiteral("Net/IconThemeName"); + case Net_SoundThemeName: return QByteArrayLiteral("Net/SoundThemeName"); + case Net_EnableInputFeedbackSounds: return QByteArrayLiteral("Net/EnableInputFeedbackSounds"); + case Net_PreferDarkTheme: return QByteArrayLiteral("Net/PreferDarkTheme"); + + default: return QByteArrayLiteral(""); + } +} + +bool XSettings::initialized() const +{ + return !m_windows.empty(); +} + +bool XSettings::isEmpty() const +{ + return m_settings.empty(); +} + +bool XSettings::contains(const QByteArray &property) const +{ + return m_settings.contains(property); +} + +QVariant XSettings::getPropertyValue(const QByteArray &property) const +{ + auto it = m_settings.constFind(property); + if (it == m_settings.constEnd()) + return QVariant(); + + return it->value; +} + +void XSettings::setPropertyValue(const QByteArray &property, const QVariant &value) +{ + XSettingsPropertyValue &xvalue = m_settings[property]; + if (xvalue.value == value) + return; + + if (!value.isValid()) + return; + + xvalue.updateValue(value, xvalue.last_change_serial + 1); + ++m_serial; +} + +QByteArray XSettings::depopulateSettings() +{ + QByteArray xSettings; + uint number_of_settings = m_settings.size(); + xSettings.reserve(12 + number_of_settings * 12); + char byteOrder = QSysInfo::ByteOrder == QSysInfo::LittleEndian ? XCB_IMAGE_ORDER_LSB_FIRST : XCB_IMAGE_ORDER_MSB_FIRST; + + xSettings.append(byteOrder); //byte-order + xSettings.append(3, '\0'); //unused + xSettings.append((char*)&m_serial, sizeof(m_serial)); //SERIAL + xSettings.append((char*)&number_of_settings, sizeof(number_of_settings)); //N_SETTINGS + uint number_of_settings_index = xSettings.size() - sizeof(number_of_settings); + for (auto i = m_settings.constBegin(); i != m_settings.constEnd(); ++i) { + const XSettingsPropertyValue &value = i.value(); + if (!value.value.isValid()) { + --number_of_settings; + continue; + } + + char type = XSettingsTypeString; + const QByteArray &key = i.key(); + quint16 key_size = key.size(); + + switch (value.value.typeId()) { + case QMetaType::QColor: + type = XSettingsTypeColor; + break; + case QMetaType::Int: + case QMetaType::Bool: + type = XSettingsTypeInteger; + break; + default: + break; + } + + xSettings.append(type); //type + xSettings.append('\0'); //unused + xSettings.append((char*)&key_size, 2); //name-len + xSettings.append(key.constData()); //name + xSettings.append(3 - (key_size + 3) % 4, '\0'); // 4-byte alignment + xSettings.append((char*)&value.last_change_serial, 4); //last-change-serial + + QByteArray value_data; + + if (type == XSettingsTypeInteger) { + qint32 int_value = value.value.toInt(); + value_data.append((char*)&int_value, 4); + } else if (type == XSettingsTypeColor) { + const QColor &color = qvariant_cast(value.value); + quint16 red = color.red(); + quint16 green = color.green(); + quint16 blue = color.blue(); + quint16 alpha = color.alpha(); + + value_data.append((char*)&red, 2); + value_data.append((char*)&green, 2); + value_data.append((char*)&blue, 2); + value_data.append((char*)&alpha, 2); + } else { + const QByteArray &string_data = value.value.toByteArray(); + quint32 data_size = string_data.size(); + value_data.append((char*)&data_size, 4); + value_data.append(string_data); + value_data.append(3 - (string_data.size() + 3) % 4, '\0'); // 4-byte alignment + } + + xSettings.append(value_data); + } + + if (number_of_settings == 0) { + return QByteArray(); + } + memcpy(xSettings.data() + number_of_settings_index, &number_of_settings, sizeof(number_of_settings)); + + return xSettings; +} + +void XSettings::populateSettings(const QByteArray &xSettings) +{ + if (xSettings.length() < 12) + return; + char byteOrder = xSettings.at(0); + if (byteOrder != XCB_IMAGE_ORDER_LSB_FIRST && byteOrder != XCB_IMAGE_ORDER_MSB_FIRST) { + return; + } + +#define ADJUST_BO(b, t, x) \ + ((b == XCB_IMAGE_ORDER_LSB_FIRST) ? \ + qFromLittleEndian(x) : \ + qFromBigEndian(x)) +#define VALIDATE_LENGTH(x) \ + if ((size_t)xSettings.length() < (offset + local_offset + 12 + x)) { \ + return; \ + } + + m_serial = ADJUST_BO(byteOrder, qint32, xSettings.mid(4,4).constData()); + uint number_of_settings = ADJUST_BO(byteOrder, quint32, xSettings.mid(8,4).constData()); + const char *data = xSettings.constData() + 12; + size_t offset = 0; + QSet keys; + keys.reserve(number_of_settings); + + for (uint i = 0; i < number_of_settings; i++) { + int local_offset = 0; + VALIDATE_LENGTH(2); + XSettingsType type = static_cast(*reinterpret_cast(data + offset)); + local_offset += 2; + + VALIDATE_LENGTH(2); + quint16 name_len = ADJUST_BO(byteOrder, quint16, data + offset + local_offset); + local_offset += 2; + + VALIDATE_LENGTH(name_len); + QByteArray name(data + offset + local_offset, name_len); + local_offset += round_to_nearest_multiple_of_4(name_len); + + VALIDATE_LENGTH(4); + int last_change_serial = ADJUST_BO(byteOrder, qint32, data + offset + local_offset); + Q_UNUSED(last_change_serial); + local_offset += 4; + + QVariant value; + if (type == XSettingsTypeString) { + VALIDATE_LENGTH(4); + int value_length = ADJUST_BO(byteOrder, qint32, data + offset + local_offset); + local_offset+=4; + VALIDATE_LENGTH(value_length); + QByteArray value_string(data + offset + local_offset, value_length); + value.setValue(value_string); + local_offset += round_to_nearest_multiple_of_4(value_length); + } else if (type == XSettingsTypeInteger) { + VALIDATE_LENGTH(4); + int value_length = ADJUST_BO(byteOrder, qint32, data + offset + local_offset); + local_offset += 4; + value.setValue(value_length); + } else if (type == XSettingsTypeColor) { + VALIDATE_LENGTH(2*4); + quint16 red = ADJUST_BO(byteOrder, quint16, data + offset + local_offset); + local_offset += 2; + quint16 green = ADJUST_BO(byteOrder, quint16, data + offset + local_offset); + local_offset += 2; + quint16 blue = ADJUST_BO(byteOrder, quint16, data + offset + local_offset); + local_offset += 2; + quint16 alpha= ADJUST_BO(byteOrder, quint16, data + offset + local_offset); + local_offset += 2; + QColor color_value(red,green,blue,alpha); + value.setValue(color_value); + } + offset += local_offset; + + m_settings[name].updateValue(value,last_change_serial); + keys << name; + } + + const auto allKeys = m_settings.keys(); + for (const QByteArray &key : allKeys) { + if (!keys.contains(key)) { + m_settings[key].updateValue(QVariant(), INT_MAX); + m_settings.remove(key); + } + } +} + +void XSettings::setSettings(const QByteArray &data) +{ + xcb_grab_server(m_connection); + + for (const xcb_window_t &win : std::as_const(m_windows)) { + xcb_change_property(m_connection, + XCB_PROP_MODE_REPLACE, + win, + m_atom, + m_atom, + 8, data.size(), data.constData()); + + if (win) { + xcb_client_message_event_t notify_event; + memset(¬ify_event, 0, sizeof(notify_event)); + + notify_event.response_type = XCB_CLIENT_MESSAGE; + notify_event.format = 32; + notify_event.sequence = 0; + notify_event.window = win; + notify_event.type = m_notifyAtom; + notify_event.data.data32[0] = win; + notify_event.data.data32[1] = m_atom; + + xcb_send_event(m_connection, false, win, XCB_EVENT_MASK_PROPERTY_CHANGE, (const char *)¬ify_event); + } + } + xcb_ungrab_server(m_connection); +} + +QByteArrayList XSettings::propertyList() const +{ + QByteArrayList merged; + const auto allKeys = m_settings.keys(); + for (auto v : allKeys) + merged.append(v); + + return merged; +} + +void XSettings::apply() +{ + setSettings(depopulateSettings()); +} + +bool XSettings::initX11(int screen, bool replace) { + xcb_intern_atom_cookie_t atomCookie = + xcb_intern_atom(m_connection, 0, strlen(XSETTINGS_ATOM_NAME), XSETTINGS_ATOM_NAME); + xcb_intern_atom_reply_t *atomReply = xcb_intern_atom_reply(m_connection, atomCookie, nullptr); + + if (!atomReply) { + qCCritical(lcTlXsettings) << "xcb_intern_atom_reply return nullptr for" << XSETTINGS_ATOM_NAME; + return false; + } + + m_atom = atomReply->atom; + free(atomReply); + Q_ASSERT(m_atom != XCB_NONE); + + xcb_intern_atom_cookie_t notifyAtomCookie = + xcb_intern_atom(m_connection, 0, strlen(XSETTINGS_NOTIFY_ATOM_NAME), XSETTINGS_NOTIFY_ATOM_NAME); + xcb_intern_atom_reply_t *notifyAtomReply = xcb_intern_atom_reply(m_connection, notifyAtomCookie, nullptr); + + if (!notifyAtomReply) { + qCCritical(lcTlXsettings) << "xcb_intern_atom_reply return nullptr for" << XSETTINGS_NOTIFY_ATOM_NAME; + return false; + } + + m_notifyAtom = notifyAtomReply->atom; + free(notifyAtomReply); + Q_ASSERT(m_notifyAtom != XCB_NONE); + + xcb_intern_atom_cookie_t signalAtomCookie = + xcb_intern_atom(m_connection, 0, strlen(XSETTINGS_SIGNAL_ATOM_NAME), XSETTINGS_SIGNAL_ATOM_NAME); + xcb_intern_atom_reply_t *signalAtomReply = xcb_intern_atom_reply(m_connection, signalAtomCookie, nullptr); + + if (!signalAtomReply) { + qCCritical(lcTlXsettings) << "xcb_intern_atom_reply return nullptr for" << XSETTINGS_SIGNAL_ATOM_NAME; + return false; + } + + m_signalAtom = signalAtomReply->atom; + free(signalAtomReply); + Q_ASSERT(m_signalAtom != XCB_NONE); + + char data[kMaxPropertySize] = {0}; + size_t bytesWritten = 128; + + const xcb_setup_t *setup = xcb_get_setup(m_connection); + int screen_count = xcb_setup_roots_length(setup); + + int min_screen = 0; + int max_screen = screen_count - 1; + if (screen >= 0) + min_screen = max_screen = screen; + + for (int s = min_screen; s <= max_screen; ++s) { + xcb_window_t win; + xcb_timestamp_t timestamp; + if (!createWindow(s, &win, ×tamp)) { + qCCritical(lcTlXsettings) << "xsettingsd Unable to create window on screen" << s; + return false; + } + + xcb_change_property(m_connection, + XCB_PROP_MODE_REPLACE, + win, + m_atom, + m_atom, + 8, + bytesWritten, + data); + if (!manageScreen(s, win, timestamp, replace)) + return false; + + m_windows.push_back(win); + qCDebug(lcTlXsettings) << "XSettings: registered window" << win << "for screen" << s; + } + + xcb_flush(m_connection); + return true; +} + +bool XSettings::createWindow(int screen, xcb_window_t *out_win, xcb_timestamp_t *out_time) { + const xcb_setup_t *setup = xcb_get_setup(m_connection); + xcb_screen_iterator_t it = xcb_setup_roots_iterator(setup); + for (int i = 0; i < screen; ++i) + xcb_screen_next(&it); + + xcb_screen_t *scr = it.data; + if (!scr) { + qCCritical(lcTlXsettings) << "xcb_setup_roots_iterator failed"; + return false; + } + + xcb_window_t win = xcb_generate_id(m_connection); + uint32_t values[] = { XCB_EVENT_MASK_PROPERTY_CHANGE }; + + xcb_create_window(m_connection, + XCB_COPY_FROM_PARENT, + win, + scr->root, + -1, -1, 1, 1, 0, + XCB_WINDOW_CLASS_INPUT_OUTPUT, + scr->root_visual, + XCB_CW_EVENT_MASK, + values); + + const char *name = "xsettings-manager"; + xcb_change_property(m_connection, + XCB_PROP_MODE_REPLACE, + win, + XCB_ATOM_WM_NAME, + XCB_ATOM_STRING, + 8, + strlen(name), + name); + + *out_win = win; + *out_time = XCB_CURRENT_TIME; + + qCDebug(lcTlXsettings) << "Created XSETTINGS window" << win << "named" << name; + + return true; +} + +bool XSettings::manageScreen(int screen, xcb_window_t win, xcb_timestamp_t timestamp, bool replace) { + char sel_name[64]; + snprintf(sel_name, sizeof(sel_name), "_XSETTINGS_S%d", screen); + + xcb_intern_atom_cookie_t sel_cookie = + xcb_intern_atom(m_connection, 0, strlen(sel_name), sel_name); + xcb_intern_atom_reply_t *sel_reply = xcb_intern_atom_reply(m_connection, sel_cookie, nullptr); + if (!sel_reply) { + qCCritical(lcTlXsettings) + << "xcb_intern_atom_reply return nullptr for" + << QString("_XSETTINGS_S%1").arg(screen); + + return false; + } + + xcb_atom_t selection_atom = sel_reply->atom; + free(sel_reply); + + xcb_grab_server(m_connection); + xcb_get_selection_owner_cookie_t owner_cookie = xcb_get_selection_owner(m_connection, selection_atom); + xcb_get_selection_owner_reply_t *owner_reply = xcb_get_selection_owner_reply(m_connection, owner_cookie, nullptr); + xcb_window_t owner = XCB_NONE; + if (owner_reply) { + owner = owner_reply->owner; + free(owner_reply); + } + + if (owner != XCB_NONE && !replace) { + xcb_ungrab_server(m_connection); + qCCritical(lcTlXsettings) + << "xsettings: Another XSETTINGS manager exists for screen" + << screen + << "owner window" << owner; + return false; + } + + xcb_set_selection_owner(m_connection, win, selection_atom, timestamp); + + xcb_get_selection_owner_reply_t *reply = + xcb_get_selection_owner_reply(m_connection, + xcb_get_selection_owner(m_connection, selection_atom), + nullptr); + bool ok = reply && reply->owner == win; + free(reply); + xcb_ungrab_server(m_connection); + + if (!ok) { + qCCritical(lcTlXsettings) << "xsettingsd: Failed to acquire ownership of" << sel_name; + return false; + } + + const xcb_setup_t *setup = xcb_get_setup(m_connection); + xcb_screen_iterator_t it = xcb_setup_roots_iterator(setup); + for (int i = 0; i < screen; ++i) + xcb_screen_next(&it); + xcb_window_t root = it.data->root; + xcb_intern_atom_cookie_t man_cookie = + xcb_intern_atom(m_connection, 0, strlen(MANAGER_ATOM_NAME), MANAGER_ATOM_NAME); + xcb_intern_atom_reply_t *man_reply = + xcb_intern_atom_reply(m_connection, man_cookie, nullptr); + if (!man_reply) { + qCCritical(lcTlXsettings) << "Failed to intern MANAGER atom"; + return false; + } + + xcb_atom_t manager_atom = man_reply->atom; + free(man_reply); + + xcb_client_message_event_t ev = {}; + ev.response_type = XCB_CLIENT_MESSAGE; + ev.window = root; + ev.type = manager_atom; + ev.format = 32; + ev.data.data32[0] = timestamp; + ev.data.data32[1] = selection_atom; + ev.data.data32[2] = win; + ev.data.data32[3] = 0; + ev.data.data32[4] = 0; + + xcb_send_event(m_connection, + false, + root, + XCB_EVENT_MASK_STRUCTURE_NOTIFY, + reinterpret_cast(&ev)); + xcb_flush(m_connection); + + return true; +} diff --git a/src/xsettings/xsettings.h b/src/xsettings/xsettings.h new file mode 100644 index 0000000000..354f9bb921 --- /dev/null +++ b/src/xsettings/xsettings.h @@ -0,0 +1,215 @@ +// Copyright (C) 2025 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "abstractsettings.h" + +class XSettingsPropertyValue +{ +public: + XSettingsPropertyValue() + {} + + bool updateValue(const QVariant &value, int last_change_serial) + { + if (last_change_serial <= this->last_change_serial) + return false; + this->value = value; + this->last_change_serial = last_change_serial; + + return true; + } + + QVariant value; + int last_change_serial = -1; +}; + +/*## **Gtk (Graphical Toolkit) Settings** +| **Property** | **Example Value** | **Meaning / Purpose (for comments)** | +| ------------------------- | --------------------------------------- | ------------------------------------------------------------------------ | +| `Gdk/UnscaledDPI` | `98304` | Physical display DPI ×1024, before scaling. Used internally by GDK to compute display density. | +| `Gdk/WindowScalingFactor` | `2` | Global scaling factor for HiDPI screens (integer). Affects window buffer scaling in GDK. | +| `Gtk/RecentFilesEnabled` | `1` | Enables “recent files” feature in GTK applications. | +| `Gtk/ShowStatusShapes` | `0` | Whether to display shapes or indicators in status icons. | +| `Gtk/ShowInputMethodMenu` | `0` | Controls visibility of the input method (IME) menu in text widgets. | +| `Gtk/TimeoutInitial` | `200` | Keyboard repeat initial delay (milliseconds). | +| `Gtk/TimeoutRepeat` | `20` | Keyboard repeat rate (milliseconds between repeats). | +| `Gtk/DecorationLayout` | `":minimize,maximize,close"` | Titlebar button order (client-side decorations). | +| `Gtk/IMModule` | `"ibus"` | Input method module (e.g., ibus, fcitx, xim). | +| `Gtk/ShellShowsDesktop` | `0` | Whether the desktop shell displays the desktop. | +| `Gtk/MenuImages` | `0` | Show or hide icons in application menus. | +| `Gtk/EnablePrimaryPaste` | `1` | Enables middle-click paste using PRIMARY selection buffer. | +| `Gtk/KeynavUseCaret` | `0` | Enables caret navigation in widgets via keyboard. | +| `Gtk/ShellShowsAppMenu` | `0` | Whether the global app menu is displayed by shell. | +| `Gtk/CanChangeAccels` | `0` | Allows users to change keyboard shortcuts at runtime. | +| `Gtk/FontName` | `"Noto Sans, 10"` | Default UI font for GTK widgets. | +| `Gtk/CursorThemeSize` | `48` | Size of cursor icons (pixels). | +| `Gtk/DialogsUseHeader` | `1` | Use modern client-side header bars in dialogs. | +| `Gtk/ToolbarStyle` | `"both-horiz"` | Toolbar layout: icons, text, or both. | +| `Gtk/KeyThemeName` | `"Default"` | Keybinding theme (e.g., “Emacs”). | +| `Gtk/IMPreeditStyle` | `"callback"` | Preedit (composition) display style for IME input. | +| `Gtk/EnableAnimations` | `1` | Enables widget animations. | +| `Gtk/CursorThemeName` | `"breeze_cursors"` | Cursor icon theme. | +| `Gtk/ToolbarIconSize` | `"large"` | Default toolbar icon size. | +| `Gtk/IMStatusStyle` | `"callback"` | IME status display style. | +| `Gtk/RecentFilesMaxAge` | `-1` | Max age (in days) for items in “recent files”; `-1` disables expiration. | +| `Gtk/Modules` | `"canberra-gtk-module:gail:atk-bridge"` | List of GTK modules to load (sound, accessibility, etc.). | +| `Gtk/AutoMnemonics` | `1` | Enables automatic mnemonics (Alt shortcuts). | +| `Gtk/ColorScheme` | `""` | Deprecated; used for color overrides. | +| `Gtk/MenuBarAccel` | `"F10"` | Keyboard shortcut to focus the menu bar. | +| `Gtk/ColorPalette` | `"black:white:gray50:..."` | Palette used in color selection dialogs. | +| `Gtk/OverlayScrolling` | `1` | Enables overlay scrollbars. | +| `Gtk/SessionBusId` | `"1412549d..."` | D-Bus session bus ID (auto-generated). | +| `Gtk/ShowUnicodeMenu` | `0` | Enables Unicode character input menu in text widgets. | +| `Gtk/CursorBlinkTimeout` | `10` | Timeout before text cursor stops blinking (seconds). | +| `Gtk/ButtonImages` | `0` | Show icons on buttons. | +| `Gtk/TitlebarRightClick` | `"menu"` | Defines action when right-clicking titlebar (e.g., show menu). | +| `Gtk/TitlebarDoubleClick` | `"toggle-maximize"` | Action for double-click on titlebar. | +| `Gtk/TitlebarMiddleClick` | `"none"` | Action for middle-click on titlebar. | +| `Gtk/ThemeName` | | Explicit GTK widget theme (distinct from `Net/ThemeName`). | +| `Gtk/MonospaceFontName` | | Font for monospaced text (terminals, editors). | +| `Gtk/ApplicationPreferDarkTheme` | `0` | App-specific dark theme preference. 0 Light theme,1 Dark theme | +| `Gtk/PrimaryButtonWarpsSlider` | `0` | Determines if primary click warps scrollbar thumb. | + +## **Net (Freedesktop Desktop Interoperability) Settings** + +| **Property** | **Example Value** | **Meaning / Purpose (for comments)** | +| ------------------------------- | ----------------- | -------------------------------------------------------------- | +| `Net/DndDragThreshold` | `8` | Pixel distance threshold before drag-and-drop begins. | +| `Net/CursorBlinkTime` | `1000` | Blink interval of text cursor (milliseconds). | +| `Net/ThemeName` | `"deepin"` | Current GTK/desktop theme name. | +| `Net/DoubleClickTime` | `400` | Maximum time between clicks for double-click recognition (ms). | +| `Net/CursorBlink` | `1` | Whether the text cursor blinks. | +| `Net/FallbackIconTheme` | `"gnome"` | Fallback icon theme when main one is missing icons. | +| `Net/EnableEventSounds` | `1` | Enables UI event sounds (button click, notifications, etc.). | +| `Net/IconThemeName` | `"breeze"` | Icon theme used for GTK applications. | +| `Net/SoundThemeName` | `"__custom"` | Sound theme name for system sounds. | +| `Net/EnableInputFeedbackSounds` | `0` | Enables keypress feedback sounds. | +| `Net/PreferDarkTheme` | | Indicates preference for dark theme variants. | + +## **Xft (X FreeType) Font Settings** + +| **Property** | **Example Value** | **Meaning / Purpose (for comments)** | +| --------------- | ----------------- | ------------------------------------------------------------------- | +| `Xft/Antialias` | `1` | Enables anti-aliased font rendering. | +| `Xft/Hinting` | `1` | Enables font hinting. | +| `Xft/HintStyle` | `"hintslight"` | Hinting level (`hintnone`, `hintslight`, `hintmedium`, `hintfull`). | +| `Xft/DPI` | `196608` | Effective DPI (×1024). Controls font scaling. | +| `Xft/RGBA` | `"none"` | Subpixel rendering type (`rgb`, `bgr`, `vrgb`, `vbgr`, `none`). | +| `Xft/Lcdfilter` | | LCD filtering method (`lcddefault`, `lcdlight`, etc.) for subpixel rendering. |*/ + +class XSettings : public AbstractSettings +{ + Q_OBJECT +public: + enum XSettingsKey { + Unknown = 0, + + Xft_DPI, + Xft_Antialias, + Xft_Hinting, + Xft_HintStyle, + Xft_RGBA, + Xft_LCDFilter, + + Xcursor_Theme, + Xcursor_Size, + Xcursor_ThemeCore, + + Gdk_WindowScalingFactor, + Gdk_UnscaledDPI, + + Gtk_FontName, + Gtk_ThemeName, + Gtk_IconThemeName, + Gtk_CursorThemeName, + Gtk_CursorThemeSize, + Gtk_RecentFilesEnabled, + Gtk_ShowStatusShapes, + Gtk_ShowInputMethodMenu, + Gtk_TimeoutInitial, + Gtk_TimeoutRepeat, + Gtk_DecorationLayout, + Gtk_IMModule, + Gtk_ShellShowsDesktop, + Gtk_MenuImages, + Gtk_EnablePrimaryPaste, + Gtk_KeynavUseCaret, + Gtk_ShellShowsAppMenu, + Gtk_CanChangeAccels, + Gtk_DialogsUseHeader, + Gtk_ToolbarStyle, + Gtk_KeyThemeName, + Gtk_IMPreeditStyle, + Gtk_EnableAnimations, + Gtk_ToolbarIconSize, + Gtk_IMStatusStyle, + Gtk_RecentFilesMaxAge, + Gtk_Modules, + Gtk_AutoMnemonics, + Gtk_ColorScheme, + Gtk_MenuBarAccel, + Gtk_ColorPalette, + Gtk_OverlayScrolling, + Gtk_SessionBusId, + Gtk_ShowUnicodeMenu, + Gtk_CursorBlinkTimeout, + Gtk_ButtonImages, + Gtk_TitlebarRightClick, + Gtk_TitlebarDoubleClick, + Gtk_TitlebarMiddleClick, + Gtk_MonospaceFontName, + Gtk_ApplicationPreferDarkTheme, + Gtk_PrimaryButtonWarpsSlider, + + Net_DndDragThreshold, + Net_CursorBlinkTime, + Net_ThemeName, + Net_DoubleClickTime, + Net_CursorBlink, + Net_FallbackIconTheme, + Net_EnableEventSounds, + Net_IconThemeName, + Net_SoundThemeName, + Net_EnableInputFeedbackSounds, + Net_PreferDarkTheme + }; + Q_ENUM(XSettingsKey) + + enum XSettingsType { + XSettingsTypeInteger = 0, + XSettingsTypeString, + XSettingsTypeColor + }; + Q_ENUM(XSettingsType) + + explicit XSettings(xcb_connection_t *connection, QObject *parent = nullptr); + ~XSettings() override; + + static QByteArray toByteArray(XSettingsKey key); + + bool initialized() const override; + bool isEmpty() const override; + + bool contains(const QByteArray &property) const override; + QVariant getPropertyValue(const QByteArray &property) const override; + void setPropertyValue(const QByteArray &property, const QVariant &value) override; + QByteArrayList propertyList() const override; + void apply() override; + +private: + bool initX11(int screen, bool replace); + bool createWindow(int screen, xcb_window_t *out_win, xcb_timestamp_t *out_time); + bool manageScreen(int screen, xcb_window_t win, xcb_timestamp_t timestamp, bool replace); + QByteArray depopulateSettings(); + void populateSettings(const QByteArray &xSettings); + void setSettings(const QByteArray &data); + +private: + std::vector m_windows; + QMap m_settings; + xcb_atom_t m_notifyAtom = XCB_NONE; + xcb_atom_t m_signalAtom = XCB_NONE; + int m_serial = -1; +}; diff --git a/src/xwayland.cpp b/src/xwayland.cpp new file mode 100644 index 0000000000..c87a31d7e3 --- /dev/null +++ b/src/xwayland.cpp @@ -0,0 +1,106 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +/** + * xwayland helper that creates an xauth file and execs Xwayland + * + * (dde) treeland -> wlroots -> treeland-xwayland (this) -> Xwayland + * ^ | | + * | | +-> /tmp/.xauth_:X (dde, 0600) + * XWaylandName() | + * | |------------------<-----------------+ + * | | content + * | v + * (user) treeland-sd --------> /run/user//.xauth_XXXXXX (user, 0600) + * save + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +Q_DECLARE_LOGGING_CATEGORY(lcXwaylandHelper) +Q_LOGGING_CATEGORY(lcXwaylandHelper, "treeland.xwayland.helper") + +int main(int argc, char *argv[]) +{ + if (argc < 2) { + qCCritical(lcXwaylandHelper) << "Usage: treeland-xwayland [args]"; + return 1; + } + // Generate cookie + QByteArray cookie(16, '\0'); + + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_int_distribution<> dis(0, 0xFF); + for(int i = 0; i < 16; i++) + cookie[i] = dis(gen); + + // Create xauth file + char *display = argv[1]; // display is passed as the first argument + QByteArray authFilePath = QByteArray("/tmp/.xauth_").append(display); + const char *fileName = authFilePath.constData(); + const int oldumask = umask(077); + FILE * const authFp = fopen(fileName, "wb"); + if (!authFp) + qFatal("fopen() failed: %s", strerror(errno)); + umask(oldumask); + + // Prepare auth entry + Xauth auth = {}; + + char localhost[HOST_NAME_MAX + 1] = ""; + if (gethostname(localhost, sizeof(localhost)) < 0) + strcpy(localhost, "localhost"); + + char cookieName[] = "MIT-MAGIC-COOKIE-1"; + + // Skip the ':' + QByteArray displayNumberUtf8 = QString(display).mid(1).toUtf8(); + + auth.family = FamilyLocal; + auth.address = localhost; + auth.address_length = strlen(auth.address); + auth.number = displayNumberUtf8.data(); + auth.number_length = displayNumberUtf8.size(); + auth.name = cookieName; + auth.name_length = sizeof(cookieName) - 1; + auth.data = cookie.data(); + auth.data_length = cookie.size(); + + // Write auth + errno = 0; + if (XauWriteAuth(authFp, &auth) == 0) + qFatal("XauWriteAuth(FamilyLocal) failed: %s", strerror(errno)); + + // Write the same entry again, just with FamilyWild + auth.family = FamilyWild; + auth.address_length = 0; + errno = 0; + if (XauWriteAuth(authFp, &auth) == 0) + qFatal("XauWriteAuth(FamilyWild) failed: %s", strerror(errno)); + + if (fflush(authFp) != 0) + qFatal("fflush() failed: %s", strerror(errno)); + + fclose(authFp); + + // Exec Xwayland + char **args = static_cast(malloc((argc + 3) * sizeof(char *))); + for (int i = 0; i < argc; ++i) { + args[i] = argv[i]; + } + args[argc] = const_cast("-auth"); + args[argc + 1] = const_cast(fileName); + args[argc + 2] = nullptr; + execvp("Xwayland", args); + qCWarning(lcXwaylandHelper) << "execvp() returned"; + return 1; +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000000..b3b23a65e0 --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,22 @@ +set(CMAKE_INCLUDE_CURRENT_DIR ON) +set(CMAKE_AUTOMOC ON) +if(BUILD_TREELAND_PROTOCOL_TESTS) + add_subdirectory(protocols) +endif() + +add_subdirectory(test_protocol_appearance) +add_subdirectory(test_protocol_compositor-action) +add_subdirectory(test_protocol_decoration) +add_subdirectory(test_protocol_primary-output) +add_subdirectory(test_protocol_shortcut) +add_subdirectory(test_protocol_wallpaper-color) +if (NOT DISABLE_XWAYLAND) + add_subdirectory(test_protocol_xwindow-control) +endif() +add_subdirectory(test_protocol_prelaunch-splash) +add_subdirectory(test_protocol_pointerconstraints) +add_subdirectory(test_effect_glass) +add_subdirectory(test_treeland_debug) +add_subdirectory(test_frame_geometry) + +add_subdirectory(test_animation_switches) diff --git a/tests/protocols/CMakeLists.txt b/tests/protocols/CMakeLists.txt new file mode 100644 index 0000000000..07cfb5fd70 --- /dev/null +++ b/tests/protocols/CMakeLists.txt @@ -0,0 +1,105 @@ +find_package(TreelandProtocols REQUIRED) +find_package(PkgConfig REQUIRED) +pkg_check_modules(WAYLAND_CLIENT REQUIRED IMPORTED_TARGET wayland-client) +pkg_check_modules(XKBCOMMON REQUIRED IMPORTED_TARGET xkbcommon) + +option(TREELAND_ENABLE_UINPUT_PROTOCOL_TESTS + "Build optional /dev/uinput protocol integration tests" OFF) +option(TREELAND_ENABLE_GPU_PROTOCOL_TESTS + "Build protocol integration tests that require a GPU DMA-BUF renderer" OFF) + +set(TREELAND_PROTOCOL_TEST_DSG_DATA_DIR "${CMAKE_CURRENT_BINARY_DIR}/dsg") +file(COPY "${PROJECT_SOURCE_DIR}/misc/dconfig/" + DESTINATION "${TREELAND_PROTOCOL_TEST_DSG_DATA_DIR}/configs/org.deepin.dde.treeland") +set(TREELAND_PROTOCOL_TEST_DSG_DATA_DIRS + "${TREELAND_PROTOCOL_TEST_DSG_DATA_DIR}:/usr/share/dsg") + +include(${CMAKE_CURRENT_SOURCE_DIR}/framework/ProtocolTest.cmake) + +add_subdirectory(drm) +add_subdirectory(input-method-unstable-v2) +add_subdirectory(virtual-keyboard-unstable-v1) +add_subdirectory(wlr-data-control-unstable-v1) +add_subdirectory(ext-background-effect-v1) +add_subdirectory(wlr-export-dmabuf-unstable-v1) +add_subdirectory(wlr-foreign-toplevel-management-unstable-v1) +add_subdirectory(wlr-gamma-control-unstable-v1) +add_subdirectory(wlr-layer-shell-unstable-v1) +add_subdirectory(wlr-output-management-unstable-v1) +add_subdirectory(wlr-output-power-management-unstable-v1) +add_subdirectory(treeland-app-id-resolver-v2) +add_subdirectory(treeland-app-id-resolver-desktop-v2) +add_subdirectory(treeland-capture-unstable-v1) +add_subdirectory(treeland-capture-desktop-v1) +add_subdirectory(treeland-compositor-action-v1) +add_subdirectory(treeland-active-notify-unstable-v1) +add_subdirectory(treeland-appearance-unstable-v1) +add_subdirectory(treeland-remote-subsurface-unstable-v1) +add_subdirectory(treeland-dde-shell-v2) +add_subdirectory(treeland-ddm-v1) +add_subdirectory(treeland-decoration-unstable-v1) +add_subdirectory(treeland-foreign-toplevel-manager-v3) +add_subdirectory(session-isolation) +add_subdirectory(session-protocol-lifecycle) +add_subdirectory(treeland-input-manager-unstable-v1) +if(TREELAND_ENABLE_UINPUT_PROTOCOL_TESTS AND CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_subdirectory(treeland-input-manager-uinput-v1) +endif() +add_subdirectory(treeland-keyboard-state-notify-unstable-v1) +add_subdirectory(treeland-layer-shell-extension-unstable-v1) +add_subdirectory(treeland-output-manager-v2) +add_subdirectory(treeland-prelaunch-splash-v2) +add_subdirectory(treeland-prelaunch-splash-desktop-v2) +add_subdirectory(treeland-screensaver-v2) +add_subdirectory(treeland-screensaver-desktop-v2) +add_subdirectory(treeland-shortcut-manager-v3) +add_subdirectory(treeland-shortcut-manager-desktop-v3) +add_subdirectory(treeland-output-group-manager-v1) +add_subdirectory(treeland-wallpaper-color-v1) +add_subdirectory(treeland-wallpaper-manager-unstable-v1) +add_subdirectory(treeland-wallpaper-shell-unstable-v1) +add_subdirectory(treeland-wallpaper-desktop-v1) +if (NOT DISABLE_XWAYLAND) + add_subdirectory(treeland-xwindow-control-unstable-v1) +endif() +add_subdirectory(treeland-region-watch-unstable-v1) +add_subdirectory(treeland-window-transition-unstable-v1) +add_subdirectory(treeland-wine-window-state-unstable-v1) +add_subdirectory(treeland-wine-window-management-unstable-v1) + +# --- Standard wayland-protocols (1.49) served by Treeland --- +add_subdirectory(wayland-alpha-modifier-v1) +add_subdirectory(wayland-cursor-shape-v1) +add_subdirectory(wayland-data-device) +add_subdirectory(wayland-ext-data-control-v1) +add_subdirectory(wayland-ext-foreign-toplevel-list-v1) +add_subdirectory(wayland-ext-workspace-v1) +add_subdirectory(wayland-ext-idle-notify-v1) +add_subdirectory(wayland-ext-image-copy-capture-v1) +# The ext-session-lock global is only served when EXT_SESSION_LOCK_V1 is on +# (LockScreenManager::installSessionLock attaches WSessionLockManager under +# that macro). Without it the client cannot bind the global and the ready gate +# (lockScreenAvailableChanged) is never emitted, so the test would hang. +if(EXT_SESSION_LOCK_V1) + add_subdirectory(wayland-ext-session-lock-v1) +endif() +add_subdirectory(wayland-fractional-scale-v1) +add_subdirectory(wayland-idle-inhibit-unstable-v1) +add_subdirectory(wayland-keyboard-shortcuts-inhibit-unstable-v1) +add_subdirectory(wayland-pointer-constraints-unstable-v1) +add_subdirectory(wayland-pointer-gestures-unstable-v1) +add_subdirectory(wayland-primary-selection-unstable-v1) +add_subdirectory(wayland-relative-pointer-unstable-v1) +add_subdirectory(wayland-security-context-v1) +add_subdirectory(wayland-single-pixel-buffer-v1) +add_subdirectory(wayland-text-input-unstable-v1) +add_subdirectory(wayland-text-input-unstable-v3) +add_subdirectory(wayland-viewporter) +add_subdirectory(wayland-xdg-activation-v1) +add_subdirectory(wayland-xdg-decoration-unstable-v1) +add_subdirectory(wayland-xdg-dialog-v1) +add_subdirectory(wayland-xdg-foreign-unstable-v2) +add_subdirectory(wayland-xdg-output-unstable-v1) +add_subdirectory(wayland-xdg-toplevel-tag-v1) + +include(${CMAKE_CURRENT_SOURCE_DIR}/ProtocolTestCoverageTarget.cmake) diff --git a/tests/protocols/INDEX.md b/tests/protocols/INDEX.md new file mode 100644 index 0000000000..494ba9ed3e --- /dev/null +++ b/tests/protocols/INDEX.md @@ -0,0 +1,247 @@ +# 协议测试规范 + +本目录记录 `tests/protocols/` 下每个协议测试的可观察契约。XML 规定 +Wayland 线上请求与事件;本文档规定发出请求后,测试必须观察到的合成器结果。 + +## 如何阅读 + +每份规范都说明 fixture、生产结果、覆盖等级和已知边界: + +- `P`:协议/资源级;验证请求、事件和协议错误。 +- `I`:生产集成级;验证生产模块的状态、回调或生命周期。 +- `E`:端到端业务级;验证真实生产对象产生了业务结果。 +- `V`:渲染/像素级;在 `E` 基础上读取渲染结果或像素。 + +仅创建资源或由测试手工发出事件,不构成端到端验证。`E` 至少需要生产图中的 +真实对象,例如 mapped `SurfaceWrapper`、已聚焦 `WSeat` 或 wlroots idle 状态; +`V` 还必须观察渲染或像素。 + +下表描述测试已实现的断言,而不是缓存的 CI 结果。某一提交是否满足规范,仍以 +该提交上的本地或 CI 测试执行结果为准;新测试在其文档中会明确标出尚待执行。 + +## 当前协议索引 + +| 协议 | 覆盖等级 | 主要生产结果 | +| --- | --- | --- | +| [Session 窗口隔离](session-isolation/README.md) | E(新增,待执行) | pointer-gestures 每连接单 global(新增待执行)、两个真实 Session 的窗口模型、工作区、三种 foreign-toplevel 枚举、跨 Session 预览及 LayerShell 逻辑输出/专属区域、最小化模型隔离及共享系统缩放(A/B=1.5,切换不恢复)、三个 output head 的身份和账户往返切换稳定性、四个捕获协议 registry 实例隔离(待执行)、xdg-foreign 单 global 接口对象(待执行)、shell 协议实例及 appearance 请求/事件隔离;快捷键后台即时绑定、upsert/解绑及切换保留;同 appId 闪屏关闭隔离、后台子 socket 窗口激活恢复及协议 socket 归属(待执行),以及停用 Session 全 surface 隐藏/禁用/NonLive(新增待执行) | +| [Session 协议销毁](session-protocol-lifecycle/README.md) | E(新增,待编译、待执行) | 八个原生销毁信号、两个无 destroy 信号的 capture manager global 清理、重复 detach、Session 接口移除、真实客户端连接关闭及其他 Session 连接保留、同账户重建;新增额外共享引用下同步 shutdown、mapped 窗口和子 socket 断连、重复 shutdown 断言(待编译执行) | +| [测试框架架构](framework/README.md) | 基础设施 | runner、fixture、C client、生产状态桥接与 E/V 断言边界 | +| [app-id-resolver-v2](treeland-app-id-resolver-v2/README.md) | I / E | resolver pidfd 应答;返回 app-id 转换真实 splash wrapper 为 xdg window | +| [capture-unstable-v1](treeland-capture-unstable-v1/README.md) | E / V / P | 真实窗口选择、frame copy 与目标 buffer 像素;无 source 错误 | +| [compositor-action-v1](treeland-compositor-action-v1/README.md) | E / P | trigger 路由到真实 Workspace 切换与 show-desktop 状态;zoom/未知动作被忽略不断连 | +| [active-notify-unstable-v1](treeland-active-notify-unstable-v1/README.md) | P | notifier 创建/重建与无输入不发事件边界 | +| [dde-shell-v2](treeland-dde-shell-v2/README.md) | E / P / I | v2 元数据、placement hint、skip 位域、重复创建报错;接口版本 2 的 role 初始与变化通知、always_on_top 真实层级、用户置顶/取消置顶双向同步、Overlay 子窗口层级及旧版本兼容;定位与 skip 的 wrapper 集成仍待补 | +| [ddm-v1](treeland-ddm-v1/README.md) | I | 客户端连接生命周期 | +| [foreign-toplevel-manager-v3](treeland-foreign-toplevel-manager-v3/README.md) | E | 真实 toplevel、dock preview、窗口状态(含最小化与布局正交)、激活/焦点与 icon rectangle | +| [input-manager-unstable-v1](treeland-input-manager-unstable-v1/README.md) | I / E(可选) | 默认空设备 manager 生命周期;uinput 驱动真实 libinput capability 热插拔 | +| [keyboard-state-notify-unstable-v1](treeland-keyboard-state-notify-unstable-v1/README.md) | P | watcher 配置与空键盘/空 modifier 边界 | +| [output-manager-v2](treeland-output-manager-v2/README.md) | I / P | uuid 寻址的 primary-output 与 picture-control 创建/提交/失效链路 | +| [region-watch-unstable-v1](treeland-region-watch-unstable-v1/README.md) | E / P | 输出边缘区域的全局坐标注册;真实 toplevel 映射/关闭驱动的 enter/leave;输出重绑、output_removed 与惰性语义 | +| [appearance-unstable-v1](treeland-appearance-unstable-v1/README.md) | I / P | 初始 `color_scheme` 与 manager setter 触发的 client 广播 | 其余外观字段、无效值和 DConfig 配置替换 | +| [decoration-unstable-v1](treeland-decoration-unstable-v1/README.md) | E | mapped toplevel 的 `set_corner_radius` 回读真实 `SurfaceWrapper::radius()` | shadow、border、titlebar 和协议错误路径 | +| [remote-subsurface-unstable-v1](treeland-remote-subsurface-unstable-v1/README.md) | E / P | token 导出、真实 Remote `WSubsurface` 的父子关系、位置与层级、输入上下文查找父窗口、`parent_rejected` / `invalid_sibling` | 跨 client、循环 parent、映射生命周期与 sibling 间排序 | +| [prelaunch-splash-v2](treeland-prelaunch-splash-v2/README.md) | I / E | splash 请求/关闭信号;生产 splash wrapper 创建、加入 workspace 与销毁 | +| [prelaunch splash 桌面集成](treeland-prelaunch-splash-desktop-v2/README.md) | E / V | splash wrapper 创建/销毁;AM 图标在 splash item 与客户端 `wl_buffer` 都销毁后仍由 wrapper 持有;dock preview 标题行图标 item 的 buffer 指针、尺寸与纹理像素;无图标窗口与悬停切换不产生 `WBufferItem` / QML 警告 | +| [screensaver-v2](treeland-screensaver-v2/README.md) | E / P | 真实 ext-idle 抑制生命周期 | +| [shortcut-manager-v3](treeland-shortcut-manager-v3/README.md) | E / P | 聚焦窗口捕获与快捷键激活 | +| [output-group-manager-v1](treeland-output-group-manager-v1/README.md) | P / E | 输出分组创建/镜像/解散;set_source 与 add/remove_output 的 uuid 校验 | +| [wallpaper-color-v1](treeland-wallpaper-color-v1/README.md) | I | 订阅、去重与颜色通知 | +| [wallpaper-manager-unstable-v1](treeland-wallpaper-manager-unstable-v1/README.md) | I / P | 真实输出上的壁纸资源生命周期 | +| [wallpaper-shell-unstable-v1](treeland-wallpaper-shell-unstable-v1/README.md) | I / P | wallpaper shell 与 notifier 生命周期 | +| [wallpaper desktop 联合路径](treeland-wallpaper-desktop-v1/README.md) | P / E | manager 配置、shell surface 与真实 output 的关联 | +| [treeland-xwindow-control-unstable-v1](treeland-xwindow-control-unstable-v1/README.md) | P | 仅 `DISABLE_XWAYLAND=OFF` 注册;`set_xwindow_position_relative` 失败回调;成功路径需 Xwayland,当前环境未覆盖 | +| [wine-window-management-unstable-v1](treeland-wine-window-management-unstable-v1/README.md) | P / E | 真实 wrapper 的位置与置顶层同步 | +| [wine-window-state-unstable-v1](treeland-wine-window-state-unstable-v1/README.md) | P / E | 真实 wrapper 的最小化、attention 与可见性同步 | +| [window-transition-unstable-v1](treeland-window-transition-unstable-v1/README.md) | P / I / E | transition rect 进入生产 pending 集合、同 token 覆盖发一次 `closed`、旧 rect 析构不误删新 rect、销毁回收;map 前激活把**未 map** 的目标 arm 成 40×40 带 source surface(同 token 消费、他 token 不受影响),并跟随几何更新、0×0 禁用/重启用、source 清空/重设;激活迟到与无 originating surface 各发一次 `closed`;`invalid_geometry` / `invalid_surface` 协议错误 | +| [drm (`wl_drm`)](drm/README.md) | P / V(GPU 条件) | wlroots native global、GBM DMA-BUF 与真实纹理 readback | +| [input-method-unstable-v2](input-method-unstable-v2/README.md) | P / E | focused text-input 与 input method 的生产状态和编辑回传 | +| [virtual-keyboard-unstable-v1](virtual-keyboard-unstable-v1/README.md) | P / E | 有效 keymap 的真实 seat 与 shortcut 链路 | +| [wlr-data-control-unstable-v1](wlr-data-control-unstable-v1/README.md) | P / E | 两个真实 client 间的 seat selection、offer 与 pipe 传输 | +| [wlr-export-dmabuf-unstable-v1](wlr-export-dmabuf-unstable-v1/README.md) | P / V(GPU 条件) | pixman temporary-cancel;GPU DMA-BUF export/readback | +| [wlr-foreign-toplevel-management-unstable-v1](wlr-foreign-toplevel-management-unstable-v1/README.md) | P / E | 标准 foreign manager 的 toplevel 枚举、状态与焦点 | +| [wlr-gamma-control-unstable-v1](wlr-gamma-control-unstable-v1/README.md) | P / I(DRM 条件) | headless failed 边界及可选 hardware LUT 路径 | +| [wlr-layer-shell-unstable-v1](wlr-layer-shell-unstable-v1/README.md) | P / E | layer surface 的状态、container 与焦点;output 移除时的迁移/closed 与主屏清空 | +| [wlr-output-management-unstable-v1](wlr-output-management-unstable-v1/README.md) | P / E | 真实 output configuration、位置、transform、scale | +| [wlr-output-power-management-unstable-v1](wlr-output-power-management-unstable-v1/README.md) | P / E | output enable/disable 的生产状态回读 | +| [wlr-virtual-pointer-unstable-v1](wlr-virtual-pointer-unstable-v1/README.md) | 接入完成;client 待补 | native virtual pointer 的生产 seat 接入 | + +### 标准 wayland-protocols(1.49)由 Treeland 提供的协议 + +核心 Wayland 剪贴板协议另见 [wayland-data-device](wayland-data-device/README.md): +真实 selection pipe 传输、同客户端焦点切换期间的 offer 有效性、跨客户端切换及 +source 替换/销毁后的旧 offer 失效(E)。实际右键菜单交互由 GUI 复测补充。 + +以下 25 个测试覆盖 Treeland 在运行时通过 wlroots 实际提供的标准 wayland-protocols(wayland-protocols 1.49.0-1)。 +xdg-shell 由共享 xdg-toplevel 夹具覆盖(多个 toplevel 测试复用)。input-method-v2 不在 wayland-protocols 包内,故排除。 + +| 协议 | 覆盖等级 | 主要生产结果 | +| --- | --- | --- | +| [wayland-alpha-modifier-v1](wayland-alpha-modifier-v1/README.md) | E | 映射 toplevel + `set_multiplier`,回读真实 `wlr_alpha_modifier_surface_v1_state::multiplier` 与请求值一致 | +| [ext-background-effect-v1](ext-background-effect-v1/README.md) | E / P | bind 下发 blur 能力位;`set_blur_region` 双缓冲流转(set/保持/NULL/重启用/destroy)回读真实 `SurfaceWrapper::blur()`(非空区域启用整面 blur);重复关联触发 `background_effect_exists` | +| [wayland-cursor-shape-v1](wayland-cursor-shape-v1/README.md) | E | 真实 `wl_pointer` 上 `set_shape`,回读真实 `wlr_cursor_shape_manager_v1::events.request_set_shape` 捕获的 shape 值与请求一致 | +| [wayland-ext-data-control-v1](wayland-ext-data-control-v1/README.md) | E | 创建 offer 并 `set_selection` 后回读真实 `wlr_seat::selection_source` 非空 | +| [wayland-ext-foreign-toplevel-list-v1](wayland-ext-foreign-toplevel-list-v1/README.md) | E | 映射 toplevel 后回读真实 `wlr_ext_foreign_toplevel_list_v1::toplevels` 列表非空 | +| [wayland-ext-idle-notify-v1](wayland-ext-idle-notify-v1/README.md) | E | 跨协议验证:创建 idle inhibitor 后 `idled` 不触发,销毁 inhibitor 后 `idled` 触发,证明生产 `wlr_idle_notifier_v1` inhibited 状态被修改 | +| [wayland-ext-image-copy-capture-v1](wayland-ext-image-copy-capture-v1/README.md) | P / E / V | 输出工厂创建/销毁;独立窗口捕获的主面、递归子面、SSD、遮挡隔离及透明间隙像素,连续帧/移动整图相等、子面更新、resize、最大化 SSD 拖动还原、多会话和销毁;捕获管线随 client resource/session 创建与回收(空闲 source 不建视口、反复会话回到 0 条管线、source resource 提前销毁仍可继续捕获)、请求之间的合成器渲染不阻塞下一次 frame;真实 swapchain 槽位耗尽时多会话 frame 收到 unknown 失败、会话和视口保留且能恢复;双屏跨屏后关屏的待处理/新请求、渲染失败及恢复、复电、排队回收及新会话重选启用输出;无先行重绘的整屏像素/几何检查、逐次 render 的 live QSG 状态检查、离屏不提交;历史 pixman / GLES2 场景各连续 20 次通过,另 11 项相关回归中 10 项通过、输出管理旋转断言失败,物理 scanout 未验收 | +| [wayland-ext-session-lock-v1](wayland-ext-session-lock-v1/README.md) | E | `lock`→`locked` 后回读真实 `WSessionLock::isLocked()` 为 true;提交 lock surface buffer 后回读生产 wrapper,断言其尺寸 == `Output::geometry()`(全屏,而非去掉 exclusive zone 的工作区)、位置 == 输出原点 | +| [wayland-fractional-scale-v1](wayland-fractional-scale-v1/README.md) | E | 回读真实 `WOutput::scale()`,断言 `preferred_scale` == round(scale×120) | +| [wayland-idle-inhibit-unstable-v1](wayland-idle-inhibit-unstable-v1/README.md) | E | 回读真实 `wlr_idle_inhibitor_v1` 已关联 mapped `WSurface`,销毁后确认 resource 已移除 | +| [wayland-keyboard-shortcuts-inhibit-unstable-v1](wayland-keyboard-shortcuts-inhibit-unstable-v1/README.md) | I / P | mapped toplevel 获取 seat focus 后,inhibitor 收到 `active` | `inactive`、真实快捷键分发和失焦 policy | +| [wayland-pointer-constraints-unstable-v1](wayland-pointer-constraints-unstable-v1/README.md) | E | 真实 `wl_pointer` 上创建 locked 约束,回读真实 `wlr_pointer_constraint_v1::type` == Locked | +| [wayland-pointer-gestures-unstable-v1](wayland-pointer-gestures-unstable-v1/README.md) | E | 真实 `wl_pointer` 上创建 swipe/pinch 手势资源,回读真实 `wlr_pointer_gestures_v1::swipes`/`pinches` 列表非空 | +| [wayland-primary-selection-unstable-v1](wayland-primary-selection-unstable-v1/README.md) | E | 创建 source 并 `set_selection` 后回读真实 `wlr_seat::primary_selection_source` 非空 | +| [wayland-relative-pointer-unstable-v1](wayland-relative-pointer-unstable-v1/README.md) | E | 真实 `wl_pointer` 上创建 relative-pointer,回读真实 `wlr_relative_pointer_manager_v1::relative_pointers` 列表非空 | +| [wayland-security-context-v1](wayland-security-context-v1/README.md) | E | commit 后回读真实 `wlr_security_context_manager_v1::events.commit` 捕获的 app_id 与请求一致;第二连接经套接字建立 | +| [wayland-single-pixel-buffer-v1](wayland-single-pixel-buffer-v1/README.md) | E | 映射 toplevel + 单像素缓冲,回读真实 `wlr_surface::current.buffer_width/height` == 1×1 | +| [wayland-text-input-unstable-v1](wayland-text-input-unstable-v1/README.md) | E | 创建 text_input v1 + `activate`,回读真实 `WTextInputV1::activate` 信号被触发;fake input method commit 后断言空 preedit 被转发、丢焦点只发 `leave` | +| [wayland-text-input-unstable-v3](wayland-text-input-unstable-v3/README.md) | E | 创建 text_input v3 + enable/commit,回读真实 `wlr_text_input_v3::current_enabled` == true;fake input method 流程断言空 preedit/done 早于 `leave`、已 disable 时不发状态更新 | +| [wayland-viewporter](wayland-viewporter/README.md) | E | 映射 toplevel + `set_destination(320,240)`,回读真实 `wlr_surface::current.viewport` dst 状态 | +| [wayland-xdg-activation-v1](wayland-xdg-activation-v1/README.md) | E | `get_activation_token` + `activate`,回读真实 `ActivationManagerInterfaceV1::activateRequested` 信号的 disposition == Attention | +| [wayland-xdg-decoration-unstable-v1](wayland-xdg-decoration-unstable-v1/README.md) | E | 映射 toplevel + `set_mode`,回读 Client / Server;软件后端 SSD 的有效圆角为 0、客户区无圆角 input mask;切换 full proxy 不禁止请求的缩略图圆角,代理继承标题栏配置且仅在实际半径变化时通知 | +| [wayland-xdg-dialog-v1](wayland-xdg-dialog-v1/README.md) | E | 回读真实 `SurfaceWrapper::modal()` 在 `set_modal` 后由 false 翻转为 true | +| [wayland-xdg-foreign-unstable-v2](wayland-xdg-foreign-unstable-v2/README.md) | E | 两个 mapped toplevel,`export_toplevel` + `import_toplevel` + `set_parent_of`,回读真实 `WXdgToplevelSurface::parentXdgSurface()` 非空 | +| [wayland-xdg-output-unstable-v1](wayland-xdg-output-unstable-v1/README.md) | E | 客户端 `logical_position`/`logical_size` 事件与回读的真实 `WOutput::position()`/`effectiveSize()` 逐字段一致 | +| [wayland-xdg-toplevel-tag-v1](wayland-xdg-toplevel-tag-v1/README.md) | E | 回读真实 `WXdgToplevelSurface::tag()` 等于客户端设置值 | + +## XML request / event / 业务链路盘点 + +本节是对当前工作树的源码审计,不是某一次 CTest 的通过率。审计读取已安装的 +`/usr/share/treeland-protocols/treeland-*.xml`,并只把测试客户端中实际调用的生成 +request stub 算作 request 覆盖;生成的 client-protocol 文件本身不计入。`destroy` 也单列, +因为它证明资源生命周期,却通常不承载主要业务语义。 + +- **已注册并有测试目录的 22 个当前协议**:XML 共 160 条 request,其中测试客户端直接 + 调用了 **107 条(66.9%)**。 +- 其中 48 条是 `destroy` 生命周期 request,被直接调用的有 45 条;去掉后剩余 112 条工厂、 + 配置和业务 request 中有 **62 条(55.4%)** 被直接调用(62 + 45 = 107,112 + 48 = 160)。 +- 22 个协议中 **17 个(77.3%)** 至少有一条 E 级生产业务链路;其余 5 个仍停留在 I/P 层, + 具体缺口见下表“主要未覆盖 request / event / 业务结果”列。 +- 当前 XML 共有 95 条 server event。这里**不发布“事件百分比”**:listener 中出现一个 + callback、或 fixture 手工发出一次 event,都不能证明事件负载或其业务来源被断言。下表只 + 列出已实际断言的关键 event,并明确列出尚未逐项验证的 event。 + +| 协议 | request(已调用 / XML) | 已断言的 event 或生产结果 | 主要未覆盖 request / event / 业务结果 | +| --- | --- | --- | --- | +| app-id-resolver-v1 | 4 / 4 | `identify_request` 的 id、真实 pidfd;`respond` 转换同一 splash wrapper 并写入 app-id | resolver 断开 fallback、sandbox 后续策略、XWayland | +| capture-unstable-v1 | 8 / 11 | `source_ready/failed`、`buffer/buffer_done/ready/failed`;64×64 红色像素读回 | session 的 `start/frame_done`,及 `frame/object/ready/cancel` 持久流;OUTPUT/REGION、cursor、mask | +| active-notify-unstable-v1 | 2 / 2 | notifier 创建/重建;无真实输入不伪造事件 | 真实输入驱动的 activity/drag 事件(uinput)、null seat 错误、多 notifier/seat、与 v1 并行双发 | +| appearance-unstable-v1 + appearance-manager-unstable-v1 | 3 / 13 | bind 初始 `color_scheme`;manager `set_color_scheme` 广播 Dark | 其余外观字段、无效值、DConfig 配置替换 | +| ddm-v1 | 0 / 7 | 无未请求 VT event;生产连接生命周期 | 所有会话/渲染控制 request 与 `switch_to_vt/acquire_vt` 的实际系统流程 | +| decoration-unstable-v1 | 4 / 7 | `set_corner_radius` 后 mapped `SurfaceWrapper::radius()` == 12 | shadow、border、titlebar、协议错误与 SSD 协商 | +| foreign-toplevel-manager-v3 | 16 / 16 | `toplevel/identifier/closed`;真实最小化、最大化、全屏、焦点与 icon rectangle;最小化与布局状态正交(含取消布局后不卡在最小化);布局状态请求在几何动画进行中的重定向与取消(最大化中还原、取消全屏后最大化) | `pid/title/app_id/output_enter/output_leave/state/done/parent` payload;指定 `wl_output` 的 fullscreen hint、preview 像素;`Tiling` 组合 | +| input-manager-unstable-v1 | 1 / 22 | 默认测试仅证明空设备 manager 可绑定;uinput target 断言 Keyboard capability 热插拔 | settings/apply、真实 mouse/touchpad 配置生效、无设备 failed;uinput E 层需显式启用并实际执行 | +| keyboard-state-notify-unstable-v1 | 6 / 6 | watcher 配置、`apply` 的空键盘/空 modifier 边界 | `current_state/state_changed`、多 watcher、初始 locked、seat 销毁、重复 apply 与物理键盘对照 | +| output-manager-v2 | 7 / 7 | `primary_output` 初值与 uuid 确认、`primary_output_failed(invalid_output)` 非致命;picture-control 初始 `brightness`/`color_temperature`、`result`(success/invalid_output)与失效后 inert、越界色温致命协议错误 | `set_color_temperature/set_brightness` 成功路径及 brightness/color_temperature 事件回读、`invalid_brightness`、`unsupported`、真实像素变化、uuid 热插拔跟随 | +| region-watch-unstable-v1 | 4 / 4 | `set_region` 后的强制评估;真实 toplevel 映射/关闭驱动的 `enter/leave`;输出重绑、`output_removed` 与惰性语义 | `invalid_anchor/invalid_size` 致命错误路径、输出 scale/mode 变化后的重新注册、多 watcher | +| remote-subsurface-unstable-v1 | 8 / 8 | token;真实 Remote `WSubsurface` 的父子关系、位置、Below 层级、输入上下文查找父窗口;`parent_rejected` / `invalid_sibling` | 跨 client、循环 parent、映射生命周期、sibling 间排序 | +| prelaunch-splash-v2 | 3 / 3 | 创建、关闭;真实 splash wrapper 加入/离开 workspace | splash QML 最终可见性、纹理和像素 | +| screensaver-v1 | 2 / 3 | 真实 ext-idle 被 inhibit/uninhibit 改变 | 显式 `destroy` request、实际锁屏 UI | +| shortcut-manager-v3 | 6 / 9 | `bind_failure`、`captured`、`activated`;真实 virtual keyboard 输入链 | swipe、hold、`unbind` 的业务分支;物理键盘 | +| output-group-manager-v1 | 25 / 25 | 分组创建/镜像/解散、`set_source`/`add_output`/`remove_output` 的 uuid 与占用校验、promotion 生命周期 | 跨进程持久化、真实显示器内容一致性 | +| wallpaper-color-v1 | 3 / 3 | `output_color` 订阅与去重 | 真实壁纸分析来源、壁纸应用后的 output 色彩变化 | +| wallpaper-manager-unstable-v1 | 4 / 5 | `failed/changed`;`set_image_source` 与 wallpaper shell/output 关联 | `set_video_source`、实际映射/QML 接入、媒体解码失败、最终 output 像素 | +| wallpaper-shell-unstable-v1 | 5 / 6 | notifier add/remove、play/pause/slow-down;wallpaper shell 资源生命周期 | `ready` 的实际 owner 映射路径、`position/set_playback_rate` event payload、媒体播放和最终 output 像素 | +| layer-shell-extension-unstable-v1 | 4 / 4 | `begin_resize` 的 `resize_rejected(bad_serial)` | 成功 resize、clamp、`resizing` 生命周期 | +| wine-window-management-unstable-v1 | 5 / 5 | `window_id/configure_position/configure_stacking`;真实 QQuickItem 位置/Z 值 | bottom/insert-after、多窗口 sibling、无效 sibling、重复 bind、越界坐标 | +| wine-window-state-unstable-v1 | 6 / 7 | `state_changed`;真实最小化、attention 与可见性 | `activate/activate_denied`、重复 bind、toplevel 销毁后的 inert 状态 | +| window-transition-unstable-v1 | 5 / 5 | `get_window_transition_rect` 进入生产 pending 集合;同 token 覆盖发一次 `closed`,旧 rect 析构不误删当前 rect;销毁后集合移除;map 前激活把未 map 的目标 arm 成 40×40 带 source surface(同 token 消费、他 token 不受影响),并跟随几何更新、0×0 禁用/重启用、source 清空/重设;激活迟到与无 originating surface 各发一次 `closed`;`invalid_geometry` / `invalid_surface` 协议错误 | 目标销毁触发的 `closed`、60 s sweep、跨 client 的 `invalid_surface`、rect 全局位置、source surface 身份 | + +### 未纳入上述覆盖率的 XML + +以下 4 个 XML 仍由协议包提供,但当前没有对应的已注册生产测试 target,故不混入覆盖率 +分母,也不能被视为“已覆盖”: + +| XML | request / event | 当前状态与缺口 | +| --- | --- | --- | +| `treeland-prelaunch-splash-v1` | 2 / 0 | 已由 v2 取代;未验证 v1 compatibility global 或迁移策略 | +| `treeland-shortcut-manager-v1` | 3 / 1 | 已由 v2 取代;未验证 v1 compatibility global、`shortcut` event | +| `treeland-dde-shell-v1` | 27 / 7 | 已在 `deprecated/`,实现删除时协议一并移除,测试已删除(删除前 26 / 27 request)。删除到实现移除之间,锁屏 mode 切换、multitask `toggle`、checker/active 资源仍由生产提供但零协议测试;v2 XML 没有对应 request,不能由 `treeland-dde-shell-v2` 接替 | +| `treeland-personalization-manager-v1` | 37 / 12 | 已在 `deprecated/`,实现删除时协议一并移除,测试已删除(删除前 37 / 37 request,含 manager `destroy` 的 `since=2` 兼容性边界)。cursor/font/appearance 的生产回读自此无协议测试 | + +### 标准 wayland-protocols 覆盖 + +以下 25 个标准 wayland-protocols(wayland-protocols 1.49.0-1)测试中,23 个已升至 **E 级**, +1 个为 **E / V / P 级**,1 个为 **I / P 级**:keyboard-shortcuts-inhibit 验证生产 seat +focus 到 `active` event 的链路;`ext-image-copy-capture-v1` 除 output-to-source 工厂外, +已验证独立离屏窗口捕获的像素及不改变实际屏幕/几何的契约。output capture session 的 +headless 历史死锁边界(issue #1407)仍未由窗口测试覆盖。 + +**E 级测试(23 个)**——验证真实生产对象状态: + +| 协议 | E 级回读的生产对象 | +| --- | --- | +| `alpha-modifier-v1` | `wlr_alpha_modifier_surface_v1_state::multiplier` | +| `ext-background-effect-v1` | `SurfaceWrapper::blur()` 随客户端 region 非空而启用(含双缓冲保持/NULL 移除/destroy 清除) | +| `cursor-shape-v1` | `wlr_cursor_shape_manager_v1::events.request_set_shape` 捕获的 shape | +| `ext-data-control-v1` | `wlr_seat::selection_source` 非空 | +| `ext-foreign-toplevel-list-v1` | `wlr_ext_foreign_toplevel_list_v1::toplevels` 列表非空 | +| `ext-idle-notify-v1` | 跨协议:inhibitor 创建/销毁后 `idled` 行为变化证明 `wlr_idle_notifier_v1` inhibited 状态被修改 | +| `ext-session-lock-v1` | `WSessionLock::isLocked()` 为 true;锁屏 wrapper 尺寸 == `Output::geometry()` | +| `fractional-scale-v1` | `WOutput::scale()` 与 `preferred_scale` 一致 | +| `idle-inhibit-unstable-v1` | `wlr_idle_inhibitor_v1` 关联 mapped `WSurface`,销毁后 resource 移除 | +| `pointer-constraints-unstable-v1` | `wlr_pointer_constraint_v1::type` == Locked | +| `pointer-gestures-unstable-v1` | `wlr_pointer_gestures_v1::swipes`/`pinches` 列表非空 | +| `primary-selection-unstable-v1` | `wlr_seat::primary_selection_source` 非空 | +| `relative-pointer-unstable-v1` | `wlr_relative_pointer_manager_v1::relative_pointers` 列表非空 | +| `security-context-v1` | `wlr_security_context_manager_v1::events.commit` 捕获的 app_id | +| `single-pixel-buffer-v1` | `wlr_surface::current.buffer_width/height` == 1×1 | +| `text-input-unstable-v1` | `WTextInputV1::activate` 信号被触发;空 preedit 被转发;丢焦点只发 `leave` | +| `text-input-unstable-v3` | `wlr_text_input_v3::current_enabled` == true;空 preedit/done 早于 `leave`;已 disable 时不发 preedit | +| `viewporter` | `wlr_surface::current.viewport` dst 状态 | +| `xdg-activation-v1` | `ActivationManagerInterfaceV1::activateRequested` 的 disposition == Attention | +| `xdg-decoration-unstable-v1` | `WXdgDecorationManager::modeBySurface` 返回 Client / Server;软件后端真实 `SurfaceWrapper::frameGeometry().radius()` 为 0、客户区无圆角 input mask;真实代理的 fullProxy 切换保留圆角开关、标题栏配置与半径通知去重 | +| `xdg-dialog-v1` | `SurfaceWrapper::modal()` 由 false 翻转为 true | +| `xdg-foreign-unstable-v2` | `WXdgToplevelSurface::parentXdgSurface()` 非空 | +| `xdg-output-unstable-v1` | `WOutput::position()`/`effectiveSize()` 与客户端事件一致 | +| `xdg-toplevel-tag-v1` | `WXdgToplevelSurface::tag()` 等于客户端设置值 | + +**E / V / P 级测试(1 个)**——`ext-image-copy-capture-v1`:纯 C 客户端读取真实 SHM +frame,覆盖主面、递归子面、SSD、连续帧、正/负坐标移动、resize、最大化后 SSD 拖动还原 +(还原 buffer 到达前后)、多会话及销毁;捕获管线随 client resource 与 session 创建/回收, +空闲 source 不建离屏视口,反复请求后管线数回到 0,source resource 提前销毁不影响存活 +session。真实 swapchain 槽位耗尽时,每个挂起 frame 收到 unknown 失败,保留会话并在 +释放 buffer 后恢复捕获;同样覆盖原输出关闭时的失败与恢复。fixture 在不先重绘屏幕的 +情况下检查每个提交帧整屏像素、窗口几何和逐次 capture +render 的 live QSG 状态,离屏不提交真实输出。可选 GPU target 使用同一场景,缺 DRM render +node 时 skip;pixman / Intel UHD 630 GLES2 各连续 20 次通过,实际 Treeland 桌面 / +物理 scanout 未验收。输出源工厂保留 P 级。 +新增渲染失败场景在 pixman / GLES2 各连续 5 次通过,另外 12 项相关协议回归全部通过。 +同时覆盖真实 DDM 全局暂停/恢复:原 capture 无额外请求即可恢复,关屏输出仍走 +离屏兜底;暂停时取消或窗口销毁后不再绘制旧视口。重建管线检查 CaptureSurfaceContent +组件定义复用,并保留原有 SSD 和整图像素断言。 + +`cursor-shape`/`relative-pointer`/`pointer-constraints` 三个 E 级测试需要 seat 指针能力, +在 setup 中通过创建真实 `WInputDevice::Type::Pointer` 设备注入。 +`ext-session-lock` 测试在 300ms grace timer 后必须收到 `locked`;收到 `finished` 表示 +合成器拒绝锁定,测试失败。锁屏 surface 的尺寸断言需要先由 top layer surface 引入 +`exclusive_zone=40`(`EXTRA_XMLS` 引入 wlr-layer-shell),否则工作区与输出相同、断言会平凡通过。 +`ext-idle-notify` 通过 idle-inhibit 验证生产 `wlr_idle_notifier_v1` 的跨协议抑制行为, +因此使用 `ProtocolTest.cmake` 的 `EXTRA_XMLS` 参数包含 idle-inhibit XML。 + +### 如何解读业务覆盖 + +request 覆盖率回答的是“客户端是否真的把 XML request 发到生产实现”;它不等同于所有业务 +分支均已证明。例如 wallpaper 的 image request 已覆盖并有 shell/output 关联路径,视频 +request 则没有;foreign 的状态改变已读取真实 wrapper,但 foreign handle 的每一种初始 event +payload 尚未逐项断言。新增或增强测试时,应同时更新该表和对应协议文档的“已知边界”,不要 +只提高 request 数字。 + +## 新增协议 + +新增 XML 及测试时,请从 [protocol-specification-template.md](protocol-specification-template.md) 复制模板,并在同一变更中: + +1. 创建该协议规范; +2. 在本索引添加一行; +3. 使用最低但真实的覆盖等级; +4. 写出尚未验证的下一项生产结果。 + +这样新增协议时,规范本身就是后续测试增强的待办清单。 + +## wayland-ext-workspace-v1 + +- 生产入口:SessionProtocols → SessionWorkspace → 每会话 WExtWorkspaceManagerV1(精确 Session filter)。 +- P/I:初始 group/workspace、名称/ID、坐标与能力、active/done、commit 前后激活/创建、重名拒绝与数量上限、 + removed 后待提交请求失效、重排 ID 稳定、stop/finished。 +- 隔离:两个真实 socket 各只见一个 manager,创建及激活只改变所属会话的生产 Workspace。 +- 待验证:本次环境未运行测试;输出热插拔、urgent 与 display 重启仍无测试覆盖。 +- 详情:[README](wayland-ext-workspace-v1/README.md)。 diff --git a/tests/protocols/ProtocolTestCoverage.cmake b/tests/protocols/ProtocolTestCoverage.cmake new file mode 100644 index 0000000000..42248205c9 --- /dev/null +++ b/tests/protocols/ProtocolTestCoverage.cmake @@ -0,0 +1,140 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +cmake_minimum_required(VERSION 3.25.0) + +if(NOT DEFINED PROTOCOL_TEST_XML_LIST OR NOT DEFINED WAYLAND_PROTOCOLS_DATADIR + OR NOT DEFINED WLROOTS_PROTOCOL_DIR OR NOT DEFINED TREELAND_PROTOCOLS_DATA_DIR + OR NOT DEFINED TREELAND_SERVED_PROTOCOL_XML_LIST) + message(FATAL_ERROR "ProtocolTestCoverage.cmake requires test XML list and protocol paths") +endif() + +file(STRINGS "${PROTOCOL_TEST_XML_LIST}" tested_protocol_xmls) +set(tested_protocol_names) +foreach(xml IN LISTS tested_protocol_xmls) + get_filename_component(protocol_name "${xml}" NAME_WE) + list(APPEND tested_protocol_names "${protocol_name}") +endforeach() +list(REMOVE_DUPLICATES tested_protocol_names) +list(SORT tested_protocol_names) + +function(collect_protocol_names protocol_dir output_variable) + file(GLOB_RECURSE protocol_xmls LIST_DIRECTORIES FALSE "${protocol_dir}/*.xml") + set(protocol_names) + foreach(xml IN LISTS protocol_xmls) + get_filename_component(protocol_name "${xml}" NAME_WE) + list(APPEND protocol_names "${protocol_name}") + endforeach() + list(REMOVE_DUPLICATES protocol_names) + list(SORT protocol_names) + set(${output_variable} "${protocol_names}" PARENT_SCOPE) +endfunction() + +function(pad_right text width output_variable) + string(LENGTH "${text}" text_length) + math(EXPR padding "${width} - ${text_length}") + if(padding GREATER 0) + string(REPEAT " " ${padding} spaces) + else() + set(spaces "") + endif() + set(${output_variable} "${text}${spaces}" PARENT_SCOPE) +endfunction() + +function(report_coverage source_name protocol_names) + set(registered_names) + set(unregistered_names) + foreach(protocol_name IN LISTS protocol_names) + if(protocol_name IN_LIST tested_protocol_names) + list(APPEND registered_names "${protocol_name}") + else() + list(APPEND unregistered_names "${protocol_name}") + endif() + endforeach() + + list(LENGTH registered_names protocol_count) + list(LENGTH registered_names covered_count) + if(protocol_count GREATER 0) + math(EXPR coverage_tenths "${covered_count} * 1000 / ${protocol_count}") + math(EXPR coverage_whole "${coverage_tenths} / 10") + math(EXPR coverage_fraction "${coverage_tenths} % 10") + else() + set(coverage_whole 0) + set(coverage_fraction 0) + endif() + + set(coverage_count "${covered_count} / ${protocol_count}") + set(coverage_percent "${coverage_whole}.${coverage_fraction}%") + pad_right("${source_name}" 36 coverage_source_column) + pad_right("${coverage_count}" 10 coverage_count_column) + pad_right("${coverage_percent}" 8 coverage_percent_column) + message(STATUS "| ${coverage_source_column} | ${coverage_count_column} | ${coverage_percent_column} |") + if(unregistered_names) + set(coverage_unregistered_protocols "${unregistered_names}" PARENT_SCOPE) + else() + set(coverage_unregistered_protocols "" PARENT_SCOPE) + endif() + + set(coverage_protocol_count "${protocol_count}" PARENT_SCOPE) + set(coverage_covered_count "${covered_count}" PARENT_SCOPE) +endfunction() + +function(report_unregistered_xmls source_name protocol_names) + if(NOT protocol_names) + return() + endif() + + list(LENGTH protocol_names protocol_count) + message(STATUS " ${source_name} (${protocol_count}):") + set(line " ") + foreach(protocol_name IN LISTS protocol_names) + if(line STREQUAL " ") + set(candidate "${line}${protocol_name}") + else() + set(candidate "${line}, ${protocol_name}") + endif() + string(LENGTH "${candidate}" candidate_length) + if(candidate_length GREATER 100) + message(STATUS "${line}") + set(line " ${protocol_name}") + else() + set(line "${candidate}") + endif() + endforeach() + message(STATUS "${line}") +endfunction() + +collect_protocol_names("${WAYLAND_PROTOCOLS_DATADIR}" wayland_protocol_names) +collect_protocol_names("${WLROOTS_PROTOCOL_DIR}" wlroots_protocol_names) +collect_protocol_names("${TREELAND_PROTOCOLS_DATA_DIR}" treeland_protocol_names) +file(STRINGS "${TREELAND_SERVED_PROTOCOL_XML_LIST}" treeland_served_protocol_xmls) +set(treeland_served_protocol_names) +foreach(xml IN LISTS treeland_served_protocol_xmls) + get_filename_component(protocol_name "${xml}" NAME_WE) + list(APPEND treeland_served_protocol_names "${protocol_name}") +endforeach() +list(REMOVE_DUPLICATES treeland_served_protocol_names) +list(SORT treeland_served_protocol_names) + +message(STATUS "") +message(STATUS "Protocol XML test coverage") +message(STATUS "Only XMLs referenced by registered protocol tests are counted.") +message(STATUS "+--------------------------------------+------------+----------+") +message(STATUS "| Scope | Test XMLs | Coverage |") +message(STATUS "+--------------------------------------+------------+----------+") +report_coverage("wayland-protocols" "${wayland_protocol_names}") +set(wayland_unregistered_protocols "${coverage_unregistered_protocols}") +report_coverage("wlroots" "${wlroots_protocol_names}") +set(wlroots_unregistered_protocols "${coverage_unregistered_protocols}") +report_coverage("Treeland built-in service protocols" "${treeland_served_protocol_names}") +message(STATUS "+--------------------------------------+------------+----------+") +list(LENGTH treeland_protocol_names treeland_protocol_inventory_count) +message(STATUS "Treeland private XML inventory: ${treeland_protocol_inventory_count} (informational; not counted)") + +message(STATUS "") +message(STATUS "Available XMLs without a registered protocol test (not counted):") +report_unregistered_xmls("wayland-protocols" "${wayland_unregistered_protocols}") +report_unregistered_xmls("wlroots" "${wlroots_unregistered_protocols}") + +message(STATUS "") +message(STATUS "Protocol coverage report complete.") +cmake_language(EXIT 0) diff --git a/tests/protocols/ProtocolTestCoverageTarget.cmake b/tests/protocols/ProtocolTestCoverageTarget.cmake new file mode 100644 index 0000000000..8b03a1b8f9 --- /dev/null +++ b/tests/protocols/ProtocolTestCoverageTarget.cmake @@ -0,0 +1,61 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +get_property(treeland_protocol_test_targets GLOBAL + PROPERTY TREELAND_PROTOCOL_TEST_TARGETS) +get_property(treeland_protocol_test_xmls GLOBAL + PROPERTY TREELAND_PROTOCOL_TEST_XMLS) +set(treeland_protocol_test_xml_list + "${CMAKE_CURRENT_BINARY_DIR}/protocol-test-xmls.txt") +file(WRITE "${treeland_protocol_test_xml_list}" "") +foreach(xml IN LISTS treeland_protocol_test_xmls) + file(APPEND "${treeland_protocol_test_xml_list}" "${xml}\n") +endforeach() + +file(GLOB_RECURSE treeland_protocol_build_files + "${PROJECT_SOURCE_DIR}/src/CMakeLists.txt" + "${PROJECT_SOURCE_DIR}/src/*/CMakeLists.txt" + "${PROJECT_SOURCE_DIR}/src/*/*/CMakeLists.txt" + "${PROJECT_SOURCE_DIR}/waylib/src/server/CMakeLists.txt") +set(treeland_served_protocol_xmls) +foreach(cmake_file IN LISTS treeland_protocol_build_files) + file(READ "${cmake_file}" cmake_contents) + string(REGEX MATCHALL "treeland-[A-Za-z0-9-]+\\.xml" + protocol_xmls_in_file "${cmake_contents}") + list(APPEND treeland_served_protocol_xmls ${protocol_xmls_in_file}) +endforeach() +if(DISABLE_XWAYLAND) + list(REMOVE_ITEM treeland_served_protocol_xmls treeland-xwindow-control-unstable-v1.xml) +endif() +list(REMOVE_DUPLICATES treeland_served_protocol_xmls) +list(SORT treeland_served_protocol_xmls) +set(treeland_served_protocol_xml_list + "${CMAKE_CURRENT_BINARY_DIR}/treeland-served-protocol-xmls.txt") +file(WRITE "${treeland_served_protocol_xml_list}" "") +foreach(xml IN LISTS treeland_served_protocol_xmls) + file(APPEND "${treeland_served_protocol_xml_list}" "${xml}\n") +endforeach() + +# CTest suppresses output from successful tests. Put the report in its +# post-test hook so a normal `ctest` invocation and CI log both show it. +set(treeland_protocol_coverage_post_command + "\"${CMAKE_COMMAND}\"" + "\"-DPROTOCOL_TEST_XML_LIST=${treeland_protocol_test_xml_list}\"" + "\"-DTREELAND_SERVED_PROTOCOL_XML_LIST=${treeland_served_protocol_xml_list}\"" + "\"-DWAYLAND_PROTOCOLS_DATADIR=${WAYLAND_PROTOCOLS_DATADIR}\"" + "\"-DWLROOTS_PROTOCOL_DIR=${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol\"" + "\"-DTREELAND_PROTOCOLS_DATA_DIR=${TREELAND_PROTOCOLS_DATA_DIR}\"" + -P + "\"${CMAKE_CURRENT_LIST_DIR}/ProtocolTestCoverage.cmake\"" +) +string(JOIN " " treeland_protocol_coverage_post_command + ${treeland_protocol_coverage_post_command}) +file(WRITE "${CMAKE_BINARY_DIR}/CTestCustom.cmake" + "# Generated by tests/protocols/ProtocolTestCoverageTarget.cmake.\n" + "list(APPEND CTEST_CUSTOM_POST_TEST\n" + " [==[${treeland_protocol_coverage_post_command}]==]\n" + ")\n") + +add_custom_target(protocol-test-coverage-target + COMMAND "${CMAKE_CTEST_COMMAND}" --test-dir "${CMAKE_BINARY_DIR}" --output-on-failure -L protocols + DEPENDS ${treeland_protocol_test_targets} +) diff --git a/tests/protocols/README.md b/tests/protocols/README.md new file mode 100644 index 0000000000..36928bf0fc --- /dev/null +++ b/tests/protocols/README.md @@ -0,0 +1,63 @@ +# 协议测试指南 + +本目录用纯 C 的 Wayland client 验证 Treeland 的真实服务端行为。每个 target 由一个 CTest +可执行文件承载,独立进程、独立 headless 环境;CTest 把退出码 `77` 记为 Skip,skip 不算覆盖。 + +- 框架架构、同步规则、fixture 层次与验收清单:`framework/README.md` +- 每个协议的可观察契约、覆盖等级与剩余边界:`INDEX.md` +- 新增/调试协议测试的步骤、模板与断言要求:`.agents/skills/treeland-protocol-test/SKILL.md` + +## 运行 + +首次配置、切换 preset 或新增测试目录后先重新配置: + +```bash +cmake --preset ci +``` + +构建并运行单个 target(target 名是 `test_`): + +```bash +cmake --build --preset ci --target test_treeland_keyboard_state_notify_unstable_v1 +ctest --test-dir build --output-on-failure \ + -R '^test_treeland_keyboard_state_notify_unstable_v1$' +``` + +加 `-V` 查看合成器与 Wayland 日志。跑全部协议测试: + +```bash +ctest --test-dir build --output-on-failure -L protocols +``` + +必须通过 CTest 运行:它注入 headless backend、renderer、超时与 skip 语义;直接执行 +`build/tests/protocols/.../test_*` 会漏掉这些环境。 + +## 覆盖率报告 + +每次 `ctest -L protocols` 结束后由 CTest 的测试后钩子输出,收集已注册测试的 `XML` 与 +`EXTRA_XMLS`。Treeland 私有协议的分母来自 `src/` 与 `waylib/src/server/` 生产构建文件里 +实际生成服务端绑定的 XML,而不是安装目录库存;系统 `wayland-protocols` 与 wlroots 的未注册 +XML 只列为提示,不计入分母。 + +一条命令完成构建并跑全量: + +```bash +cmake --build --preset ci --target protocol-test-coverage-target +``` + +## 可选条件测试 + +`DISABLE_XWAYLAND=ON` 时不构建或注册 xwindow-control 测试。 + +uinput 与 GPU target 默认不注册: + +```bash +cmake --preset ci -DTREELAND_ENABLE_UINPUT_PROTOCOL_TESTS=ON +cmake --preset ci -DTREELAND_ENABLE_GPU_PROTOCOL_TESTS=ON +``` + +`treeland-input-manager-uinput-v1` 创建 `BUS_VIRTUAL` uinput 键盘(不写按键),验证设备经 +udev/libinput/wlroots 进入 `WBackend::inputAdded` / `inputRemoved` 后,input-manager 向 +client 发送 Keyboard capability 的 available/unavailable。CTest 固定注入与 `treeland.service` +一致的 `LIBSEAT_BACKEND=seatd; SEATD_SOCK=/run/dde-seatd.sock`;没有 `/dev/uinput` 写权限或 +连不上该 socket 时,runner 在启动前以 `77` 标记 Skipped。 diff --git a/tests/protocols/drm/CMakeLists.txt b/tests/protocols/drm/CMakeLists.txt new file mode 100644 index 0000000000..c6cf1c648f --- /dev/null +++ b/tests/protocols/drm/CMakeLists.txt @@ -0,0 +1,15 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +treeland_add_protocol_test( + NAME drm + XML "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/drm.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/drm.c" +) + +pkg_check_modules(GBM REQUIRED IMPORTED_TARGET gbm) +target_link_libraries(test_drm PRIVATE PkgConfig::GBM) + +# wl_drm needs a renderer with a DRM device. The headless fixture may not have +# one, so the client returns 77 when wlroots cannot create the global. +set_tests_properties(test_drm PROPERTIES SKIP_RETURN_CODE 77) diff --git a/tests/protocols/drm/README.md b/tests/protocols/drm/README.md new file mode 100644 index 0000000000..15feedaa5b --- /dev/null +++ b/tests/protocols/drm/README.md @@ -0,0 +1,53 @@ +# `drm` (`wl_drm`) 测试规范 + +## 范围 + +- XML / interface:`3rdparty/wlroots/protocol/drm.xml` / `wl_drm` v2 +- 测试源码:`tests/protocols/drm/` +- Fixture:完整生产 `Treeland` / `WaylandServer`、headless output 与生产 render window;`WaylandServer::init()` 直接调用 wlroots C API `wlr_drm_create()`,不添加 waylib wrapper +- 覆盖等级:**P / V(GPU 条件)**;这是 wlroots 的 legacy native global,不存在 Treeland 业务模块 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| global 初始公告 | bind `wl_drm` v2 并 roundtrip | 恰好一个非空 `device`、一个 `capabilities(PRIME)`,以及至少一个 `format` | P | +| render-node 认证 | `authenticate(0)` 并 roundtrip | 收到一个 `authenticated` event | P | +| 旧 flink buffer | `create_buffer(...)` | display 失败,错误为 `wl_drm.error.invalid_name` | P | +| 旧 planar flink buffer | `create_planar_buffer(...)` | display 失败,错误为 `wl_drm.error.invalid_name` | P | +| PRIME DMA-BUF | 用 `device` 指定的 render node 创建并填充红色 GBM BO,导出 FD 后 `create_prime_buffer(...)`,map 为 xdg toplevel | 生产 render window 采样该 buffer;`WTextureCapturer` 读回 `64×64` 内容纹理中心像素 RGBA `(255,0,0,255)` | V | + +## 生产结果 + +测试 fixture 不重实现 `wl_drm`:它从 `WBackend` 创建 renderer 后直接调用 +`wlr_drm_create(server->handle(), renderer)`。因此所有 event、错误和 resource 生命周期均由 +`3rdparty/wlroots/types/wlr_drm.c` 的生产实现发出。 +`wlr_drm_create()` 仅在 renderer 能提供 DRM FD 时创建 global;`wlr_drm` 复制创建时所需的 +format/node 数据,并监听 `wl_display` 销毁。测试不拥有或手动销毁该 native global。 + +成功的 PRIME 路径为: + +`wl_drm.device render node → GBM device → GBM BO → 导出的 DMA-BUF FD → +wl_drm.create_prime_buffer → wlroots wlr_drm_buffer / wl_buffer → +xdg toplevel map → ShellHandler / SurfaceWrapper / WSurfaceItemContent → +WOutputRenderWindow render → WTextureCapturer readback`。 + +`authenticate` 的 magic 为 `0`。wlroots 的现代 render-node 实现不需要 DRM master +authentication,处理函数无条件发送 `authenticated`;该断言验证 Treeland 公开的 native +global 确实按实现响应,而不是宣称测试了 `drmAuthMagic()`。 + +## 已知边界 / 下一项结果 + +若 renderer 没有 DRM FD、客户端无法打开 `device` event 中的 node、GBM device/BO 创建失败, +client 退出码为 `77`,CTest 标记为 **Skipped**。这不是通过,也不证明 PRIME 路径。 + +普通 headless CI 往往落入该分支;挂载可访问的 GPU render node,并提供 GBM 驱动的 runner +时,测试必须执行上述真实 DMA-BUF 路径,任何协议错误均使 target 失败。 + +本规范描述已实现的断言;新增后的首次 GPU runner 执行结果尚待记录。 + +- `wl_drm` 是已废弃的 legacy 协议;`linux-dmabuf` 才是现代多 plane/modifier DMA-BUF 的主要协议。 +- PRIME request 已证明 valid single-plane GBM DMA-BUF 被 native `wl_drm` 接受、由 compositor + renderer 采样,并在真实 `WSurfaceItemContent` texture readback 中保留红色像素。 +- 读回的是 mapped surface 的生产 scene texture,而不是整个 output 的最终合成 backing buffer; + 多窗口叠放、output transform、色彩管理和 scanout 的最终像素仍需单独的 GPU output readback。 diff --git a/tests/protocols/drm/drm.c b/tests/protocols/drm/drm.c new file mode 100644 index 0000000000..88f9c6883e --- /dev/null +++ b/tests/protocols/drm/drm.c @@ -0,0 +1,289 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "drm-client-protocol.h" +#include "drm.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" + +#include +#include +#include +#include +#include +#include + +struct drm_events { + unsigned int device_count; + int device_nonempty; + char device[256]; + unsigned int format_count; + unsigned int capabilities_count; + uint32_t capabilities; + unsigned int authenticated_count; +}; + +static void handle_device(void *data, struct wl_drm *drm, const char *name) +{ + (void)drm; + struct drm_events *events = data; + events->device_nonempty = name && name[0] != '\0'; + if (events->device_nonempty) + snprintf(events->device, sizeof(events->device), "%s", name); + events->device_count++; +} + +static void handle_format(void *data, struct wl_drm *drm, uint32_t format) +{ + (void)drm; + (void)format; + ((struct drm_events *)data)->format_count++; +} + +static void handle_authenticated(void *data, struct wl_drm *drm) +{ + (void)drm; + ((struct drm_events *)data)->authenticated_count++; +} + +static void handle_capabilities(void *data, struct wl_drm *drm, uint32_t value) +{ + (void)drm; + struct drm_events *events = data; + events->capabilities = value; + events->capabilities_count++; +} + +static const struct wl_drm_listener drm_listener = { + .device = handle_device, + .format = handle_format, + .authenticated = handle_authenticated, + .capabilities = handle_capabilities, +}; + +static int has_global(const struct client_connection *connection, const char *interface) +{ + for (uint32_t i = 0; i < connection->global_count; ++i) { + if (strcmp(connection->globals[i].interface, interface) == 0) + return 1; + } + return 0; +} + +static int check_initial_events(struct client_connection *connection, + struct wl_drm *drm, + struct drm_events *events) +{ + wl_drm_add_listener(drm, &drm_listener, events); + if (wl_display_roundtrip(connection->display) < 0) + return 0; + + return events->device_count == 1 && events->device_nonempty + && events->capabilities_count == 1 + && events->capabilities == WL_DRM_CAPABILITY_PRIME + && events->format_count > 0; +} + +static int check_authenticate(struct client_connection *connection, + struct wl_drm *drm, + struct drm_events *events) +{ + wl_drm_authenticate(drm, 0); + return wl_display_roundtrip(connection->display) >= 0 + && events->authenticated_count == 1; +} + +static struct wl_drm *connect_fresh_drm(const char *socket_name, + struct client_connection *connection) +{ + if (!client_connect(connection, socket_name)) + return NULL; + return client_bind(connection, "wl_drm", &wl_drm_interface, 2); +} + +static int check_create_buffer_rejected(const char *socket_name) +{ + struct client_connection connection; + struct wl_drm *drm = connect_fresh_drm(socket_name, &connection); + if (!drm) + return 0; + + struct wl_buffer *buffer = wl_drm_create_buffer(drm, 1, 1, 1, 4, + WL_DRM_FORMAT_XRGB8888); + (void)buffer; + const struct wl_interface *interface = NULL; + uint32_t code = 0; + const int rejected = wl_display_roundtrip(connection.display) < 0 + && wl_display_get_protocol_error(connection.display, &interface, &code) + == WL_DRM_ERROR_INVALID_NAME + && interface == &wl_drm_interface; + client_disconnect(&connection); + return rejected; +} + +static int check_create_planar_buffer_rejected(const char *socket_name) +{ + struct client_connection connection; + struct wl_drm *drm = connect_fresh_drm(socket_name, &connection); + if (!drm) + return 0; + + struct wl_buffer *buffer = wl_drm_create_planar_buffer( + drm, 1, 1, 1, WL_DRM_FORMAT_XRGB8888, 0, 4, 0, 0, 0, 0); + (void)buffer; + const struct wl_interface *interface = NULL; + uint32_t code = 0; + const int rejected = wl_display_roundtrip(connection.display) < 0 + && wl_display_get_protocol_error(connection.display, &interface, &code) + == WL_DRM_ERROR_INVALID_NAME + && interface == &wl_drm_interface; + client_disconnect(&connection); + return rejected; +} + +extern void drm_read_render_state(void *data); + +// Returns 1 when the renderer samples the real DMA-BUF red pixel, 0 on an +// assertion failure, and -1 when this runner cannot allocate DMA-BUF storage. +static int check_create_prime_buffer_dma(const char *socket_name, const char *device) +{ + if (!device || device[0] == '\0') + return -1; + + const int device_fd = open(device, O_RDWR); + if (device_fd < 0) + return -1; + struct gbm_device *gbm = gbm_create_device(device_fd); + if (!gbm) { + close(device_fd); + return -1; + } + struct gbm_bo *bo = gbm_bo_create(gbm, 64, 64, DRM_FORMAT_XRGB8888, + GBM_BO_USE_RENDERING | GBM_BO_USE_LINEAR); + if (!bo) { + gbm_device_destroy(gbm); + close(device_fd); + return -1; + } + int dma_fd = gbm_bo_get_fd(bo); + if (dma_fd < 0) { + gbm_bo_destroy(bo); + gbm_device_destroy(gbm); + close(device_fd); + return -1; + } + + uint32_t map_stride = 0; + void *map_data = NULL; + uint32_t *pixels = gbm_bo_map(bo, 0, 0, 64, 64, GBM_BO_TRANSFER_WRITE, + &map_stride, &map_data); + if (!pixels) { + close(dma_fd); + gbm_bo_destroy(bo); + gbm_device_destroy(gbm); + close(device_fd); + return -1; + } + for (uint32_t y = 0; y < 64; ++y) { + uint32_t *row = (uint32_t *)((char *)pixels + (size_t)y * map_stride); + for (uint32_t x = 0; x < 64; ++x) + row[x] = 0x00ff0000u; + } + gbm_bo_unmap(bo, map_data); + + struct client_connection connection; + struct wl_drm *drm = connect_fresh_drm(socket_name, &connection); + struct xdg_toplevel_client toplevel = { 0 }; + const int toplevel_ready = drm + && xdg_toplevel_client_create_pending(&connection, &toplevel) + && wl_display_roundtrip(connection.display) >= 0 + && toplevel.configured + && xdg_toplevel_client_ack_latest_configure(&connection, &toplevel); + struct wl_buffer *buffer = NULL; + if (toplevel_ready) { + buffer = wl_drm_create_prime_buffer(drm, dma_fd, 64, 64, DRM_FORMAT_XRGB8888, + 0, gbm_bo_get_stride(bo), 0, 0, 0, 0); + // The request owns dma_fd once marshalled, including on a server error. + dma_fd = -1; + } + if (toplevel_ready && buffer) { + toplevel.buffer = buffer; + wl_surface_attach(toplevel.surface, buffer, 0, 0); + wl_surface_damage(toplevel.surface, 0, 0, 64, 64); + wl_surface_commit(toplevel.surface); + } + const int committed = buffer && wl_display_roundtrip(connection.display) >= 0; + struct drm_render_state state = { 0 }; + const int sampled = committed + && invoke_on_server_thread(drm_read_render_state, &state) + && state.output_ready + && state.wrapper_created + && state.wrapper_in_workspace + && state.image_ready + && state.image_width == 64 + && state.image_height == 64 + && state.sample_red == 255 + && state.sample_green == 0 + && state.sample_blue == 0 + && state.sample_alpha == 255; + xdg_toplevel_client_destroy(&toplevel); + if (drm) + wl_drm_destroy(drm); + const int destroyed = sampled && wl_display_roundtrip(connection.display) >= 0; + client_disconnect(&connection); + if (dma_fd >= 0) + close(dma_fd); + gbm_bo_destroy(bo); + gbm_device_destroy(gbm); + close(device_fd); + return destroyed ? 1 : 0; +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + if (!client_connect(&connection, socket_name)) + return 1; + + if (!has_global(&connection, "wl_drm")) { + fprintf(stderr, "drm: wl_drm unavailable (no DRM-capable renderer); skipped\n"); + client_disconnect(&connection); + return 77; + } + + struct wl_drm *drm = client_bind(&connection, "wl_drm", &wl_drm_interface, 2); + struct drm_events events = {0}; + const int initial_events_ok = drm && check_initial_events(&connection, drm, &events); + const int authenticate_ok = initial_events_ok && check_authenticate(&connection, drm, &events); + if (drm) + wl_drm_destroy(drm); + client_disconnect(&connection); + + if (!initial_events_ok) { + fprintf(stderr, "drm: invalid device/capabilities/format advertisement\n"); + return 1; + } + if (!authenticate_ok) { + fprintf(stderr, "drm: authenticate did not send authenticated\n"); + return 1; + } + if (!check_create_buffer_rejected(socket_name)) { + fprintf(stderr, "drm: create_buffer did not report invalid_name\n"); + return 1; + } + if (!check_create_planar_buffer_rejected(socket_name)) { + fprintf(stderr, "drm: create_planar_buffer did not report invalid_name\n"); + return 1; + } + const int prime_result = check_create_prime_buffer_dma(socket_name, events.device); + if (prime_result < 0) { + fprintf(stderr, "drm: DMA-BUF unavailable on %s; skipped\n", events.device); + return 77; + } + if (!prime_result) { + fprintf(stderr, "drm: create_prime_buffer DMA-BUF attach/commit failed\n"); + return 1; + } + return 0; +} diff --git a/tests/protocols/drm/drm.h b/tests/protocols/drm/drm.h new file mode 100644 index 0000000000..71a55f193b --- /dev/null +++ b/tests/protocols/drm/drm.h @@ -0,0 +1,17 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +struct drm_render_state { + int output_ready; + int wrapper_created; + int wrapper_in_workspace; + int image_ready; + int image_width; + int image_height; + int sample_red; + int sample_green; + int sample_blue; + int sample_alpha; +}; diff --git a/tests/protocols/drm/setup.cpp b/tests/protocols/drm/setup.cpp new file mode 100644 index 0000000000..d99a22b5b1 --- /dev/null +++ b/tests/protocols/drm/setup.cpp @@ -0,0 +1,87 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "core/rootsurfacecontainer.h" +#include "core/shellhandler.h" +#include "drm.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" +#include "workspace/workspace.h" + +#include +#include +#include + +#include +#include +#include +#include + +namespace { +SurfaceWrapper *g_wrapper = nullptr; +drm_render_state g_state {}; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [server](SurfaceWrapper *wrapper) { + if (wrapper->type() != SurfaceWrapper::Type::XdgToplevel) + return; + g_wrapper = wrapper; + g_state.wrapper_created = 1; + g_state.wrapper_in_workspace = server->workspace()->surfaces().contains(wrapper) ? 1 : 0; + }); +} + +extern "C" void drm_read_render_state(void *data) +{ + auto state = g_state; + state.output_ready = !WaylandServer::instance()->rootSurfaceContainer()->outputs().isEmpty() ? 1 : 0; + if (!g_wrapper || !g_wrapper->surfaceItem()) { + *static_cast(data) = state; + return; + } + + auto *content = g_wrapper->surfaceItem()->findItemContent(); + if (!content) { + *static_cast(data) = state; + return; + } + auto *renderWindow = content->outputRenderWindow(); + if (!renderWindow) { + *static_cast(data) = state; + return; + } + + renderWindow->render(); + WTextureCapturer capturer(content); + QFutureWatcher watcher; + QEventLoop loop; + QObject::connect(&watcher, &QFutureWatcher::finished, &loop, &QEventLoop::quit); + watcher.setFuture(capturer.grabToImage()); + loop.exec(); + if (watcher.future().isCanceled()) { + *static_cast(data) = state; + return; + } + + const QImage image = watcher.result(); + if (image.isNull()) { + *static_cast(data) = state; + return; + } + const QColor sample = image.pixelColor(image.width() / 2, image.height() / 2); + state.image_ready = 1; + state.image_width = image.width(); + state.image_height = image.height(); + state.sample_red = sample.red(); + state.sample_green = sample.green(); + state.sample_blue = sample.blue(); + state.sample_alpha = sample.alpha(); + *static_cast(data) = state; +} diff --git a/tests/protocols/ext-background-effect-v1/CMakeLists.txt b/tests/protocols/ext-background-effect-v1/CMakeLists.txt new file mode 100644 index 0000000000..0f90e73d2e --- /dev/null +++ b/tests/protocols/ext-background-effect-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME ext_background_effect_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-background-effect/ext-background-effect-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/ext-background-effect-v1.c" +) diff --git a/tests/protocols/ext-background-effect-v1/README.md b/tests/protocols/ext-background-effect-v1/README.md new file mode 100644 index 0000000000..bb2160f9d5 --- /dev/null +++ b/tests/protocols/ext-background-effect-v1/README.md @@ -0,0 +1,39 @@ +# `ext-background-effect-v1` 测试规范 + +## 范围 + +- XML / interface:`ext_background_effect_manager_v1` / `ext_background_effect_surface_v1`(version 1,staging) +- 测试源码:`tests/protocols/ext-background-effect-v1/` +- 服务端实现:`waylib/src/server/wlroots_extra/wlr_ext_background_effect_v1.c`(vendored,来自 wlroots MR 5304) + + `src/core/waylandserver.cpp` 直接调用 `wlr_ext_background_effect_manager_v1_create()` +- Fixture:headless output fixture + xdg-toplevel-client(128×128 solid buffer 映射) +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `ext_background_effect_manager_v1`(v1) | 收到 `capabilities` 事件且仅含 `blur`(值 1) | P | +| 关联表面 | `get_background_effect(surface)` | 返回非 NULL 的 `ext_background_effect_surface_v1` | P | +| 设置区域 | `set_blur_region(10,10 40x40)` + `commit` | 回读真实 `SurfaceWrapper::blur()` 为 true(非空区域启用整面 blur) | E | +| 双缓冲保持 | 不再 `set_blur_region`,直接再 `commit` | `blur()` 仍为 true(pending 状态不会在 commit 间被清空) | E | +| NULL 移除 | `set_blur_region(NULL)` + `commit` | 回读 `blur()` 为 false | E | +| 重新启用 | `set_blur_region(0,0 128x128)` + `commit` | 回读 `blur()` 为 true | E | +| 销毁对象 | `ext_background_effect_surface_v1.destroy` + `commit` | 回读 `blur()` 为 false | E | +| 重复关联错误 | 对同一 `wl_surface` 再次 `get_background_effect` | 连接收到 `background_effect_exists` 协议错误 | P | + +## 生产结果 + +测试绑定真实的 `ext_background_effect_manager_v1` 全局并校验 bind 时下发的能力位; +映射真实 xdg_toplevel 后附加背景效果对象,依次驱动 set/commit/NULL/重启用/destroy 的 +双缓冲状态流转。每次 commit 后通过 server bridge 回读生产 `SurfaceWrapper::blur()` +(由 `WSurfaceItem` 缓存 blur 区域并在 `WSurface::commit` 后经 `SurfaceWrapper` 同步),证明请求确实 +到达真实合成器 surface 管线,且双缓冲状态在连续 commit 间保持(回归防护:vendored +实现曾因多余的 `pixman_region32_clear` 在第二次 commit 后丢失模糊区域)。最后对同一 +surface 重复 `get_background_effect`,断言协议错误码为 `background_effect_exists` +(致命错误,置于用例末尾)。 + +## 已知边界 / 下一项结果 + +未验证多矩形区域的逐矩形渲染遮罩与模糊像素效果(V 级);blur 能力位关闭时的客户端 +降级行为未覆盖。 diff --git a/tests/protocols/ext-background-effect-v1/ext-background-effect-v1.c b/tests/protocols/ext-background-effect-v1/ext-background-effect-v1.c new file mode 100644 index 0000000000..4baf8b0ec0 --- /dev/null +++ b/tests/protocols/ext-background-effect-v1/ext-background-effect-v1.c @@ -0,0 +1,213 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Test the ext_background_effect_manager_v1 global created by Treeland's + * Helper (direct wlr_ext_background_effect_manager_v1_create call). + * + * Coverage level E (end-to-end): the client binds the manager, checks the + * blur capability, maps a real xdg_toplevel, attaches a background effect + * object and drives the double-buffered blur region through + * set/commit/remove/re-enable/destroy cycles. After every commit the test + * reads back the production SurfaceWrapper blur region over the server + * bridge, proving the requests reach the real compositor surface pipeline + * and that the region survives repeated commits (double-buffered state is + * kept, not cleared, between commits). + */ + +#include "ext-background-effect-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "ext-background-effect-v1-client-protocol.h" + +#include +#include + +static int read_server(struct background_effect_server_state *state) { + return TEST_READ_SERVER(background_effect_read_server_state, state, + "background-effect: failed to read server state"); +} + +/* Waits until a mapped SurfaceWrapper was captured, bounded by roundtrips. */ +static int wait_server_wrapper(struct client_connection *conn, + struct background_effect_server_state *state) { + for (int i = 0; i < 50; ++i) { + if (read_server(state)) + return 0; + if (state->valid) + return 1; + if (wl_display_roundtrip(conn->display) < 0) + return 0; + } + return state->valid; +} + +static int expect_blur(struct background_effect_server_state *state) { + return state->valid && state->blur_enabled; +} + +static int expect_no_blur(struct background_effect_server_state *state) { + return state->valid && !state->blur_enabled; +} + +static void set_blur_region(struct ext_background_effect_surface_v1 *effect, + struct wl_compositor *compositor, int x, int y, int width, int height) { + struct wl_region *region = wl_compositor_create_region(compositor); + wl_region_add(region, x, y, width, height); + ext_background_effect_surface_v1_set_blur_region(effect, region); + /* set_blur_region has copy semantics, safe to destroy immediately. */ + wl_region_destroy(region); +} + +static void handle_capabilities(void *data, + struct ext_background_effect_manager_v1 *manager, uint32_t flags) { + (void)manager; + *(uint32_t *)data = flags; +} + +/* The manager interface has no other events in version 1. */ +static const struct ext_background_effect_manager_v1_listener manager_listener = { + .capabilities = handle_capabilities, +}; + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("background-effect: connect failed\n"); + return 1; + } + + int failed = 0; + uint32_t capabilities = 0; + struct background_effect_server_state srv; + memset(&srv, 0, sizeof(srv)); + + struct ext_background_effect_manager_v1 *manager = + client_bind(&conn, ext_background_effect_manager_v1_interface.name, + &ext_background_effect_manager_v1_interface, 1); + if (manager == NULL) { + TEST_ERROR("background-effect: failed to bind ext_background_effect_manager_v1\n"); + client_disconnect(&conn); + return 1; + } + + /* manager.bind: capabilities must arrive on bind and contain blur. */ + ext_background_effect_manager_v1_add_listener(manager, &manager_listener, &capabilities); + if (wl_display_roundtrip(conn.display) < 0) { + TEST_ERROR("background-effect: roundtrip after bind failed\n"); + client_disconnect(&conn); + return 1; + } + if (capabilities != EXT_BACKGROUND_EFFECT_MANAGER_V1_CAPABILITY_BLUR) { + TEST_ERROR("background-effect: expected capabilities %u, got %u\n", + EXT_BACKGROUND_EFFECT_MANAGER_V1_CAPABILITY_BLUR, capabilities); + failed = 1; + } + + struct xdg_toplevel_client tc; + if (!failed + && !xdg_toplevel_client_create_with_solid_buffer(&conn, &tc, 128, 128, 0xff00ff00u)) { + TEST_ERROR("background-effect: create toplevel failed\n"); + failed = 1; + } + + struct ext_background_effect_surface_v1 *effect = NULL; + if (!failed) { + effect = ext_background_effect_manager_v1_get_background_effect(manager, tc.surface); + if (effect == NULL) { + TEST_ERROR("background-effect: get_background_effect failed\n"); + failed = 1; + } + } + + /* set_blur_region + commit: a non-empty region enables full blur. */ + if (!failed) { + set_blur_region(effect, tc.compositor, 10, 10, 40, 40); + wl_surface_commit(tc.surface); + wl_display_roundtrip(conn.display); + if (!wait_server_wrapper(&conn, &srv) || !expect_blur(&srv)) { + TEST_ERROR("background-effect: expected blur enabled, got valid=%d blur_enabled=%d\n", + srv.valid, srv.blur_enabled); + failed = 1; + } + } + + /* Double-buffered state: a commit without set_blur_region must keep blur + * enabled (the pending region is not cleared by the move to current). */ + if (!failed) { + wl_surface_commit(tc.surface); + wl_display_roundtrip(conn.display); + if (read_server(&srv) || !expect_blur(&srv)) { + TEST_ERROR("background-effect: blur lost after plain commit (valid=%d blur_enabled=%d)\n", + srv.valid, srv.blur_enabled); + failed = 1; + } + } + + /* NULL region removes the effect on the next commit. */ + if (!failed) { + ext_background_effect_surface_v1_set_blur_region(effect, NULL); + wl_surface_commit(tc.surface); + wl_display_roundtrip(conn.display); + if (read_server(&srv) || !expect_no_blur(&srv)) { + TEST_ERROR("background-effect: blur not removed by NULL region\n"); + failed = 1; + } + } + + /* Re-enable with a region covering the whole surface. */ + if (!failed) { + set_blur_region(effect, tc.compositor, 0, 0, 128, 128); + wl_surface_commit(tc.surface); + wl_display_roundtrip(conn.display); + if (read_server(&srv) || !expect_blur(&srv)) { + TEST_ERROR("background-effect: blur not re-enabled after NULL\n"); + failed = 1; + } + } + + /* Destroying the effect object removes the effect on the next commit. */ + if (!failed) { + ext_background_effect_surface_v1_destroy(effect); + effect = NULL; + wl_surface_commit(tc.surface); + wl_display_roundtrip(conn.display); + if (read_server(&srv) || !expect_no_blur(&srv)) { + TEST_ERROR("background-effect: blur not removed after effect destroy\n"); + failed = 1; + } + } + + /* A second get_background_effect on the same surface must raise the + * background_effect_exists protocol error (fatal, so run it last). */ + if (!failed) { + effect = ext_background_effect_manager_v1_get_background_effect(manager, tc.surface); + if (effect == NULL) { + TEST_ERROR("background-effect: re-attach after destroy failed\n"); + failed = 1; + } else { + ext_background_effect_manager_v1_get_background_effect(manager, tc.surface); + if (wl_display_roundtrip(conn.display) >= 0) { + TEST_ERROR("background-effect: expected a protocol error for duplicate effect object\n"); + failed = 1; + } else { + const struct wl_interface *error_interface = NULL; + uint32_t error_id = 0; + uint32_t code = wl_display_get_protocol_error(conn.display, + &error_interface, &error_id); + if (code != EXT_BACKGROUND_EFFECT_MANAGER_V1_ERROR_BACKGROUND_EFFECT_EXISTS) { + TEST_ERROR("background-effect: expected background_effect_exists error, got %u\n", code); + failed = 1; + } + } + } + } + + if (effect) + ext_background_effect_surface_v1_destroy(effect); + ext_background_effect_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/ext-background-effect-v1/ext-background-effect-v1.h b/tests/protocols/ext-background-effect-v1/ext-background-effect-v1.h new file mode 100644 index 0000000000..36d4c27f69 --- /dev/null +++ b/tests/protocols/ext-background-effect-v1/ext-background-effect-v1.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef EXT_BACKGROUND_EFFECT_TEST_H +#define EXT_BACKGROUND_EFFECT_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Snapshot of the real mapped SurfaceWrapper's ext-background-effect-v1 blur + * state, read on the compositor (Qt) thread. A non-empty committed blur + * region enables full-surface blur on the wrapper. + */ +struct background_effect_server_state { + int valid; /* a mapped SurfaceWrapper was captured */ + int blur_enabled; /* SurfaceWrapper::blur() (non-empty region enables it) */ +}; + +/* Defined in setup.cpp; runs on the compositor thread via + * invoke_on_server_thread() and fills *data with the blur region state. */ +void background_effect_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* EXT_BACKGROUND_EFFECT_TEST_H */ diff --git a/tests/protocols/ext-background-effect-v1/setup.cpp b/tests/protocols/ext-background-effect-v1/setup.cpp new file mode 100644 index 0000000000..4e514b0efa --- /dev/null +++ b/tests/protocols/ext-background-effect-v1/setup.cpp @@ -0,0 +1,44 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "ext-background-effect-v1.h" +#include "server-bridge.h" +#include "core/shellhandler.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" + +#include + +namespace { +// The real mapped XdgToplevel SurfaceWrapper created by the client. +SurfaceWrapper *g_wrapper = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() == SurfaceWrapper::Type::XdgToplevel) + g_wrapper = wrapper; + }); +} + +// E-level read: report the captured production SurfaceWrapper's committed +// ext-background-effect-v1 blur state, synced from the protocol surface +// state on every wl_surface.commit. A non-empty blur region enables full +// surface blur. +void background_effect_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = 0; + state->blur_enabled = 0; + + if (!g_wrapper) + return; + + state->valid = 1; + state->blur_enabled = g_wrapper->blur() ? 1 : 0; +} diff --git a/tests/protocols/framework/ProtocolTest.cmake b/tests/protocols/framework/ProtocolTest.cmake new file mode 100644 index 0000000000..1ddb0046ac --- /dev/null +++ b/tests/protocols/framework/ProtocolTest.cmake @@ -0,0 +1,166 @@ +include_guard(GLOBAL) + +set(TREELAND_PROTOCOL_TEST_FRAMEWORK_DIR "${CMAKE_CURRENT_LIST_DIR}") + +# The XWayland helper is only built when xwayland support is enabled. +if (NOT DISABLE_XWAYLAND) + set(TREELAND_PROTOCOL_TEST_XWAYLAND_ENV + "WLR_XWAYLAND=$;") +else() + set(TREELAND_PROTOCOL_TEST_XWAYLAND_ENV "") +endif() + +pkg_get_variable(WAYLAND_PROTOCOLS_DATADIR wayland-protocols pkgdatadir) +set(TREELAND_PROTOCOL_TEST_FRAMEWORK_BINARY_DIR + "${CMAKE_CURRENT_BINARY_DIR}/framework") +file(MAKE_DIRECTORY "${TREELAND_PROTOCOL_TEST_FRAMEWORK_BINARY_DIR}") +set(xdg_shell_xml "${WAYLAND_PROTOCOLS_DATADIR}/stable/xdg-shell/xdg-shell.xml") +set(xdg_shell_header + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_BINARY_DIR}/xdg-shell-client-protocol.h") +set(xdg_shell_code + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_BINARY_DIR}/xdg-shell-client-protocol.c") +add_custom_command( + OUTPUT "${xdg_shell_header}" + COMMAND wayland-scanner client-header "${xdg_shell_xml}" "${xdg_shell_header}" + DEPENDS "${xdg_shell_xml}" + VERBATIM +) +add_custom_command( + OUTPUT "${xdg_shell_code}" + COMMAND wayland-scanner private-code "${xdg_shell_xml}" "${xdg_shell_code}" + DEPENDS "${xdg_shell_xml}" "${xdg_shell_header}" + VERBATIM +) + +add_library(treeland_protocol_test_framework STATIC + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_DIR}/protocol-test-entry.cpp" + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_DIR}/test-accounts-service.cpp" + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_DIR}/test-accounts-service.h" + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_DIR}/client-connection.c" + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_DIR}/test-dconfig-service.cpp" + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_DIR}/test-dconfig-service.h" + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_DIR}/server-bridge.cpp" + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_DIR}/server-bridge-api.h" + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_DIR}/xdg-toplevel-client.c" + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_DIR}/xdg-toplevel-client.h" + "${xdg_shell_header}" + "${xdg_shell_code}" +) +target_include_directories(treeland_protocol_test_framework + PUBLIC + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_DIR}" + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_BINARY_DIR}" + PRIVATE + "${CMAKE_SOURCE_DIR}/src" + "${CMAKE_SOURCE_DIR}/waylib/src/server" + "${CMAKE_SOURCE_DIR}/waylib/src/server/kernel" + "${CMAKE_SOURCE_DIR}/waylib/src/server/utils" +) +target_link_libraries(treeland_protocol_test_framework + PUBLIC + libtreeland + PkgConfig::WAYLAND_CLIENT + Qt6::Core + Qt6::DBus + Qt6::Gui + Qt6::Test +) +set_target_properties(treeland_protocol_test_framework PROPERTIES C_STANDARD 11) + +function(treeland_add_protocol_test) + set(oneValueArgs NAME XML SETUP CLIENT) + set(multiValueArgs EXTRA_XMLS EXTRA_LIBRARIES) + cmake_parse_arguments(ARGS "" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) + foreach(required NAME SETUP CLIENT) + if(NOT ARGS_${required}) + message(FATAL_ERROR "treeland_add_protocol_test requires ${required}") + endif() + endforeach() + + string(REPLACE "-" "_" target_suffix "${ARGS_NAME}") + set(target "test_${target_suffix}") + set(protocol_client_sources) + if(ARGS_XML) + get_filename_component(protocol_basename "${ARGS_XML}" NAME_WE) + set(protocol_header "${CMAKE_CURRENT_BINARY_DIR}/${protocol_basename}-client-protocol.h") + set(protocol_code "${CMAKE_CURRENT_BINARY_DIR}/${protocol_basename}-client-protocol.c") + add_custom_command( + OUTPUT "${protocol_header}" + COMMAND wayland-scanner client-header "${ARGS_XML}" "${protocol_header}" + DEPENDS "${ARGS_XML}" + VERBATIM + ) + add_custom_command( + OUTPUT "${protocol_code}" + COMMAND wayland-scanner private-code "${ARGS_XML}" "${protocol_code}" + DEPENDS "${ARGS_XML}" "${protocol_header}" + VERBATIM + ) + list(APPEND protocol_client_sources "${protocol_header}" "${protocol_code}") + endif() + foreach(extra_xml IN LISTS ARGS_EXTRA_XMLS) + get_filename_component(extra_protocol_basename "${extra_xml}" NAME_WE) + set(extra_protocol_header "${CMAKE_CURRENT_BINARY_DIR}/${extra_protocol_basename}-client-protocol.h") + set(extra_protocol_code "${CMAKE_CURRENT_BINARY_DIR}/${extra_protocol_basename}-client-protocol.c") + add_custom_command( + OUTPUT "${extra_protocol_header}" + COMMAND wayland-scanner client-header "${extra_xml}" "${extra_protocol_header}" + DEPENDS "${extra_xml}" + VERBATIM + ) + add_custom_command( + OUTPUT "${extra_protocol_code}" + COMMAND wayland-scanner private-code "${extra_xml}" "${extra_protocol_code}" + DEPENDS "${extra_xml}" "${extra_protocol_header}" + VERBATIM + ) + list(APPEND protocol_client_sources "${extra_protocol_header}" "${extra_protocol_code}") + endforeach() + add_executable(${target} + "${ARGS_SETUP}" + "${ARGS_CLIENT}" + ${protocol_client_sources} + ) + target_include_directories(${target} PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}" + "${CMAKE_CURRENT_BINARY_DIR}" + "${TREELAND_PROTOCOL_TEST_FRAMEWORK_DIR}" + "${CMAKE_SOURCE_DIR}/src" + "${CMAKE_SOURCE_DIR}/waylib/src/server" + "${CMAKE_SOURCE_DIR}/waylib/src/server/kernel" + "${CMAKE_SOURCE_DIR}/waylib/src/server/utils" + ) + target_link_libraries(${target} PRIVATE + "$" + ${ARGS_EXTRA_LIBRARIES} + ) + # Q_OBJECT users live in treeland_protocol_test_framework. Per-protocol + # fixtures and C clients do not need an autogen pass of their own. + set_target_properties(${target} PROPERTIES + AUTOMOC OFF + AUTOUIC OFF + AUTORCC OFF + C_STANDARD 11 + ) + add_dependencies(${target} lockscreen multitaskview) + if (NOT DISABLE_XWAYLAND) + add_dependencies(${target} treeland-xwayland) + endif() + set_property(GLOBAL APPEND PROPERTY TREELAND_PROTOCOL_TEST_TARGETS ${target}) + if(ARGS_XML) + set_property(GLOBAL APPEND PROPERTY TREELAND_PROTOCOL_TEST_XMLS "${ARGS_XML}") + endif() + foreach(extra_xml IN LISTS ARGS_EXTRA_XMLS) + set_property(GLOBAL APPEND PROPERTY TREELAND_PROTOCOL_TEST_XMLS "${extra_xml}") + endforeach() + add_test(NAME ${target} COMMAND ${target}) + set_tests_properties(${target} PROPERTIES + ENVIRONMENT "WLR_BACKENDS=headless;WLR_RENDERER=pixman;${TREELAND_PROTOCOL_TEST_XWAYLAND_ENV}DSG_DATA_DIRS=${TREELAND_PROTOCOL_TEST_DSG_DATA_DIRS};TREELAND_PROTOCOL_TEST_DSG_DIR=${TREELAND_PROTOCOL_TEST_DSG_DATA_DIR}" + # D-Bus-activated portals can outlive the test and keep its output pipe open. + ENVIRONMENT_MODIFICATION "QT_NO_XDG_DESKTOP_PORTAL=set:1" + LABELS "protocols" + SKIP_REGULAR_EXPRESSION "SKIP :" + SKIP_RETURN_CODE 77 + TIMEOUT 30 + ) +endfunction() diff --git a/tests/protocols/framework/README.md b/tests/protocols/framework/README.md new file mode 100644 index 0000000000..afcb7e601c --- /dev/null +++ b/tests/protocols/framework/README.md @@ -0,0 +1,173 @@ +# 协议测试框架架构 + +## 目的与边界 + +`tests/protocols/` 不是把协议对象当作孤立 mock 来测。每个 target 都由 QTest 组织用例、纯 C +Wayland client 发起真实线上 request,并由 C++ fixture 启动完整 Treeland;测试再从客户端 +event、生产对象状态或渲染读回中取得可观察结果。CTest 负责为每个 target 提供独立进程、环境 +变量、超时与 Skip 语义。 + +框架只有一个启动入口:`framework/protocol-test-entry.cpp`。它为每个 target 启动完整的 +`Treeland`、`WaylandServer`、`ShellHandler`、workspace、seat、headless backend 与 QML scene; +`setup.cpp` 只配置 fixture 并取得生产启动路径已经创建的协议对象。 + +## 总体数据流 + +```mermaid +flowchart LR + CTest[CTest / 测试可执行文件] + + subgraph Process[单个隔离测试进程] + direction LR + subgraph QtThread[合成器 Qt 主线程] + Runner[QTest protocol() + ProtocolTestRunner] + Entry[protocol-test-entry\nTreeland + WaylandServer] + Prod[生产模块\nShellHandler / Workspace / Seat / Output / QML] + Entry --> Prod + end + + subgraph ClientThread[pthread:纯 C Wayland client] + Client[protocol_test_run] + Registry[registry bind / listener] + Assert[request、event 与结果断言] + Client --> Registry --> Assert + end + + Socket[隔离的 Wayland socket] + Client <-->|真实 Wayland request / event| Socket + Socket <-->|wl_server dispatch| QtThread + Client -->|invoke_on_server_thread\nqueued callback + QSemaphore| Runner + Runner -->|读取真实生产对象| Prod + end + + CTest --> Process +``` + +关键点:`invoke_on_server_thread()` 不是伪造协议请求。它只把一个**读取或受控 fixture +动作**排队到合成器 Qt 线程,等 callback 返回后才解除 client thread 的 semaphore。协议 +request 本身始终经过 Unix Wayland socket 与生产 resource dispatch。 + +## 启动与业务路径 + +```mermaid +sequenceDiagram + participant M as protocol test entry(Qt 主线程) + participant H as WaylandServer / 生产桌面栈 + participant F as protocol_test_setup + participant C as C Wayland client(pthread) + + M->>H: Treeland::preInit(argc, argv) + Treeland() + H->>H: 启动 session socket、seat、ShellHandler、workspace + M->>F: 安装协议专用 fixture + F->>H: 添加 headless output / 连接生产信号 + H-->>M: output model rowsInserted 或 configInitializeSucceed + M->>C: 仅在 fixture ready 后创建 pthread + C->>H: registry bind、创建对象、发送 XML request + H-->>C: configure / 协议 event + C->>H: ack / buffer commit(需要 mapped surface 时) + H->>H: ShellHandler 创建 SurfaceWrapper 并加入 Workspace + C->>M: invoke_on_server_thread(read_state) + M->>H: queued callback 读取 wrapper/seat/output/QML 状态 + H-->>C: POD 结果 + C->>C: 断言真实生产结果后退出 + M->>M: join pthread,_Exit(result) +``` + +入口的 `_Exit(result)` 是有意的:Treeland 的进程级 QML singleton 关闭顺序不属于 +单协议语义,直接析构会触发与测试无关的 compositor shutdown 路径。所有测试由独立进程运行, +所以这不会污染下一条测试。 + +## 临时 CI 服务模拟 + +当前 CI 环境未提供可用的 system D-Bus、`dde-dconfig-daemon` 与 +`org.freedesktop.Accounts`,框架暂时以 `test-dconfig-service.*` 创建隔离 D-Bus 和 DConfig +daemon,并以 `test-accounts-service.*` 注册最小 AccountsService/user 对象。这两者仅用于让 +完整 Treeland fixture 启动,不是被测协议的 mock,也不应成为长期测试基础设施。 + +后台服务可能持有测试输出管道,导致 CTest 超时。`test-dconfig-service` 使用 +`unix:abstract` 总线地址避免残留 socket 文件,并通过 `PR_SET_PDEATHSIG` 和父 PID 校验 +让 helper 随父进程退出。`stop()` 对 helper 的独立进程组先发 `SIGTERM`、再发 `SIGKILL`, +并删除 DConfig 临时目录。重新收养不改变进程组,仍在组内的服务也会被终止。 + +CI 能提供真实 D-Bus、DConfig 与 AccountsService 后,应删除这两个 helper,并让入口直接连接 +CI 提供的服务。 + +## fixture 层次与断言等级 + +```mermaid +flowchart TB + P[P:协议/资源级\n版本、对象创建、错误、event payload] + I[I:生产集成级\n真实 module 的状态、回调、生命周期] + E[E:端到端业务级\nmapped SurfaceWrapper、Workspace、Seat、Output 等业务结果] + V[V:渲染/像素级\n真实 scene / client wl_buffer 的像素读回] + + P --> I --> E --> V + + PF[protocol-test-entry\n完整 Treeland] --> P +``` + +- 即使是资源/错误路径,也必须经完整启动后的 production global 验证;fixture 直接塞入状态或 + 手工发送 event,最高只能是 P/I,不能把它标为 E。 + +## 同步规则 + +测试不得用“等待 N 毫秒后应当完成”推测服务端状态。应按下面的生产边界同步: + +| 等待对象 | 合法同步点 | 示例 | +| --- | --- | --- | +| 客户端初始配置 | `xdg_surface.configure` 后 ack | mapped xdg toplevel | +| 协议 request 已被 server 处理 | `wl_display_roundtrip()` 或规定的 response event | `source_ready`、`commit_success` | +| fixture 可开始 client | output model `rowsInserted`、`configInitializeSucceed`、或 target 的 `protocol_test_ready()` | 需要一个或多个 headless output | +| C++ 生产对象的同步读取 | `invoke_on_server_thread()` 返回 | wrapper/seat/output 的 POD snapshot | +| 异步业务动作 | 对应生产 signal、Wayland event 或 model change | splash `surfaceAdded`、output model rows change | +| 渲染/图像结果 | `renderEnd`、`QFutureWatcher::finished`、capture `ready/failed` | texture 或 client target buffer | + +fixture ready 仍由 output model `rowsInserted`、配置完成 signal 或 target 的 +`protocol_test_ready()` 驱动;client 完成则以其线程投递到 QTest 用例的 queued signal 唤醒。 +两者都不是固定延时或轮询。协议测试自身不能新增固定延时、重试轮询,或没有明确完成 +signal/event 的嵌套 event loop。唯一的例外是协议本身要求证明“timeout 到期后仍未发生 event” +的否定结果:观察窗口必须由该协议的 timeout 语义导出,并在对应规范中明确说明,例如 +screensaver 的 ext-idle inhibit 用例。若没有可观察的生产 signal/event,应先补出合适的 +可观察边界,而不是加 timeout。 + +`treeland_add_protocol_test()` 确保 `lockscreen`、`multitaskview` target 先完成构建。runner +完全复用 `Treeland` 的正常插件发现和初始化流程:plugin output 目录可访问时使用该目录, +否则回退安装目录。测试框架不再维护独立的插件加载路径或代理实现。 + +## 代码组织 + +```text +tests/protocols/ +├── framework/ +│ ├── protocol-test-entry.cpp # 唯一的完整 Treeland 入口 +│ ├── test-accounts-service.* # 临时 AccountsService 模拟 +│ ├── client-connection.* # C ABI、registry/bind、disconnect +│ ├── server-bridge-api.h # C client 调用 compositor 线程的接口 +│ ├── test-dconfig-service.* # 临时 D-Bus 与 DConfig 模拟(含子进程回收) +│ └── server-bridge.* # headless output、wl_shm 等 server helpers +├── INDEX.md # 可观察契约、覆盖边界与审计 +├── protocol-specification-template.md # 新协议说明模板 +└── treeland-/ # 协议的 C client、C++ setup 和契约文档 +``` + +每个协议 target 通常包含: + +1. `setup.cpp`:C++ fixture。只连接生产模块、创建必要 headless output,并导出很小的 C ABI + snapshot/read helper;不得替代被测协议直接写业务结果。 +2. `treeland-.c`:纯 C client。bind global、创建资源、发 XML request、接 listener + event,并在 request 后断言 client event 或经 bridge 读到的生产状态。 +3. `*.h`:client 与 fixture 共用的 POD 状态结构,避免跨线程共享 Qt 对象。 +4. `CMakeLists.txt`:使用 `treeland_add_protocol_test()` 注册独立 CTest target。 + +每个 target 对应一个 QTest `protocol()` 场景。C client 内的具名步骤可以共享同一个 Wayland +连接、resource 和生产状态;它们不是天然可独立执行的 QTest data row。需要进程隔离的独立 +场景应拆为新的 protocol target,而不是依赖 QTest 在同一 compositor 进程中重置状态。 + +## 新测试的验收清单 + +1. 先从 XML 列出 request 与 event;区分正常路径、错误路径、`since` 版本边界和 destroy。 +2. 所有 case 使用统一入口;按资源、生产集成、端到端或渲染层级选择相应的可观察结果。 +3. 客户端必须实际调用被测 request;对 event 断言 payload,不能只安装空 listener。 +4. E 级测试必须读取真实生产对象或最终客户端效果;fixture 直接发 event 只能证明 P/I。 +5. 只以 configure、roundtrip、signal、event、model change 或 future completion 同步。 +6. 在对应协议规范和 `README.md` 的 XML 审计表中记录新增覆盖和剩余边界。 diff --git a/tests/protocols/framework/client-connection.c b/tests/protocols/framework/client-connection.c new file mode 100644 index 0000000000..b48b3250c9 --- /dev/null +++ b/tests/protocols/framework/client-connection.c @@ -0,0 +1,159 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "client-connection.h" + +#include + +static void registry_global(void *data, struct wl_registry *registry, uint32_t name, + const char *interface, uint32_t version) +{ + (void)registry; + struct client_connection *connection = data; + if (connection->global_count == CLIENT_CONNECTION_MAX_GLOBALS) + return; + struct client_global *global = &connection->globals[connection->global_count++]; + global->name = name; + global->version = version; + strncpy(global->interface, interface, sizeof(global->interface) - 1); + global->interface[sizeof(global->interface) - 1] = '\0'; +} + +static void registry_global_remove(void *data, struct wl_registry *registry, uint32_t name) +{ + (void)data; + (void)registry; + (void)name; +} + +static const struct wl_registry_listener registry_listener = { + .global = registry_global, + .global_remove = registry_global_remove, +}; + +int client_connect(struct client_connection *connection, const char *socket_name) +{ + memset(connection, 0, sizeof(*connection)); + connection->display = wl_display_connect(socket_name); + if (!connection->display) + return 0; + connection->registry = wl_display_get_registry(connection->display); + wl_registry_add_listener(connection->registry, ®istry_listener, connection); + return wl_display_roundtrip(connection->display) >= 0; +} + +void *client_bind(struct client_connection *connection, const char *interface, + const struct wl_interface *wl_interface, uint32_t version) +{ + for (uint32_t i = 0; i < connection->global_count; ++i) { + const struct client_global *global = &connection->globals[i]; + if (strcmp(global->interface, interface) == 0) + return wl_registry_bind(connection->registry, global->name, wl_interface, + version < global->version ? version : global->version); + } + return NULL; +} + +void *client_bind_global(struct client_connection *connection, uint32_t name, + const struct wl_interface *wl_interface, uint32_t version) +{ + for (uint32_t i = 0; i < connection->global_count; ++i) { + const struct client_global *global = &connection->globals[i]; + if (global->name == name && strcmp(global->interface, wl_interface->name) == 0) + return wl_registry_bind(connection->registry, global->name, wl_interface, + version < global->version ? version : global->version); + } + return NULL; +} + +void *client_bind_last(struct client_connection *connection, const char *interface, + const struct wl_interface *wl_interface, uint32_t version) +{ + for (uint32_t i = connection->global_count; i > 0; --i) { + const struct client_global *global = &connection->globals[i - 1]; + if (strcmp(global->interface, interface) == 0) + return wl_registry_bind(connection->registry, global->name, wl_interface, + version < global->version ? version : global->version); + } + return NULL; +} + +static void seat_capabilities(void *data, struct wl_seat *seat, uint32_t capabilities) +{ + (void)seat; + *(uint32_t *)data = capabilities; +} + +static void seat_name(void *data, struct wl_seat *seat, const char *name) +{ + (void)data; + (void)seat; + (void)name; +} + +static const struct wl_seat_listener seat_listener = { + .capabilities = seat_capabilities, + .name = seat_name, +}; + +int client_bind_seat(struct client_connection *connection, uint32_t version, + struct client_seat *seat) +{ + seat->seat = client_bind(connection, wl_seat_interface.name, &wl_seat_interface, version); + if (!seat->seat) + return 0; + wl_seat_add_listener(seat->seat, &seat_listener, &seat->capabilities); + if (wl_display_roundtrip(connection->display) < 0) { + client_seat_destroy(seat); + return 0; + } + return 1; +} + +void client_seat_destroy(struct client_seat *seat) +{ + if (seat->seat) { + wl_seat_destroy(seat->seat); + seat->seat = NULL; + } + seat->capabilities = 0; +} + +int client_bind_pointer_seat(struct client_connection *connection, uint32_t version, + struct client_pointer_seat *pointer_seat) +{ + struct client_seat seat = { 0 }; + if (!client_bind_seat(connection, version, &seat)) + return 0; + if (!(seat.capabilities & WL_SEAT_CAPABILITY_POINTER)) { + client_seat_destroy(&seat); + return 0; + } + pointer_seat->seat = seat.seat; + pointer_seat->pointer = wl_seat_get_pointer(pointer_seat->seat); + if (!pointer_seat->pointer) { + client_pointer_seat_destroy(pointer_seat); + return 0; + } + return 1; +} + +void client_pointer_seat_destroy(struct client_pointer_seat *pointer_seat) +{ + if (pointer_seat->pointer) { + wl_pointer_destroy(pointer_seat->pointer); + pointer_seat->pointer = NULL; + } + if (pointer_seat->seat) { + wl_seat_destroy(pointer_seat->seat); + pointer_seat->seat = NULL; + } +} + +void client_disconnect(struct client_connection *connection) +{ + if (connection->registry) + wl_registry_destroy(connection->registry); + if (connection->display) + wl_display_disconnect(connection->display); + memset(connection, 0, sizeof(*connection)); +} diff --git a/tests/protocols/framework/client-connection.h b/tests/protocols/framework/client-connection.h new file mode 100644 index 0000000000..3f7d3aed1f --- /dev/null +++ b/tests/protocols/framework/client-connection.h @@ -0,0 +1,64 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include +#include + +#define TEST_ERROR(...) fprintf(stderr, __VA_ARGS__) + +#define TEST_READ_SERVER(callback, state, message) \ + (memset((state), 0, sizeof(*(state))), \ + invoke_on_server_thread((callback), (state)) ? 0 : (TEST_ERROR("%s\\n", (message)), 1)) + +#ifdef __cplusplus +extern "C" { +#endif + +enum { CLIENT_CONNECTION_MAX_GLOBALS = 256 }; +enum { CLIENT_CONNECTION_MAX_INTERFACE_NAME = 128 }; + +struct client_global { + uint32_t name; + uint32_t version; + char interface[CLIENT_CONNECTION_MAX_INTERFACE_NAME]; +}; + +struct client_connection { + struct wl_display *display; + struct wl_registry *registry; + struct client_global globals[CLIENT_CONNECTION_MAX_GLOBALS]; + uint32_t global_count; +}; + +struct client_pointer_seat { + struct wl_seat *seat; + struct wl_pointer *pointer; +}; + +struct client_seat { + struct wl_seat *seat; + uint32_t capabilities; +}; + +int client_connect(struct client_connection *connection, const char *socket_name); +void *client_bind(struct client_connection *connection, const char *interface, + const struct wl_interface *wl_interface, uint32_t version); +void *client_bind_global(struct client_connection *connection, uint32_t name, + const struct wl_interface *wl_interface, uint32_t version); +void *client_bind_last(struct client_connection *connection, const char *interface, + const struct wl_interface *wl_interface, uint32_t version); +int client_bind_seat(struct client_connection *connection, uint32_t version, + struct client_seat *seat); +void client_seat_destroy(struct client_seat *seat); +int client_bind_pointer_seat(struct client_connection *connection, uint32_t version, + struct client_pointer_seat *pointer_seat); +void client_pointer_seat_destroy(struct client_pointer_seat *pointer_seat); +void client_disconnect(struct client_connection *connection); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/framework/protocol-test-entry.cpp b/tests/protocols/framework/protocol-test-entry.cpp new file mode 100644 index 0000000000..9044dbd710 --- /dev/null +++ b/tests/protocols/framework/protocol-test-entry.cpp @@ -0,0 +1,259 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "dconfig/dconfigmanager.h" +#include "session/sessionmanager.h" +#include "core/treeland.h" +#include "core/treelandinit.h" +#include "core/rootsurfacecontainer.h" +#include "test-accounts-service.h" +#include "server-bridge-api.h" +#include "test-dconfig-service.h" +#include "core/waylandserver.h" +#include "session/session.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +void protocol_test_setup(WaylandServer *server); +extern "C" int protocol_test_run(const char *socketName); +extern "C" bool protocol_test_ready(WaylandServer *server) __attribute__((weak)); +extern "C" bool protocol_test_preflight() __attribute__((weak)); +extern "C" bool protocol_test_skip() __attribute__((weak)); + +namespace { +class ProtocolTestRunner : public QObject +{ +public: + int invoke(server_thread_callback callback, void *data) + { + QSemaphore done; + if (!QMetaObject::invokeMethod(this, [callback, data, &done] { + callback(data); + done.release(); + }, Qt::QueuedConnection)) + return 0; + done.acquire(); + return 1; + } +}; + +ProtocolTestRunner *g_runner = nullptr; +bool g_clientSkipped = false; + +class ProtocolTest; +struct ClientThreadContext { + const char *socketName = nullptr; + ProtocolTest *test = nullptr; + int result = 1; +}; + +class ProtocolTest final : public QObject +{ + Q_OBJECT + +public: + ProtocolTest(WaylandServer *server, const QByteArray &socketName) + : m_server(server) + , m_socketName(socketName) + , m_context { .socketName = m_socketName.constData(), .test = this } + { + } + +public Q_SLOTS: + void notifyClientFinished() { Q_EMIT clientFinished(); } + +private Q_SLOTS: + void initTestCase() + { + auto ensureOutputInLayout = [this](WOutput *output) { + if (!output) + return; + + if (!output->renderer()) { + auto *window = m_server->window(); + if (window->renderer() && window->allocator()) { + wlr_output_init_render(output->handle(), + window->allocator(), + window->renderer()); + } + } + + if (!output->isEnabled()) + return; + + auto *layout = m_server->rootSurfaceContainer()->outputLayout(); + if (output->renderer() && layout + && !layout->outputs().contains(output)) { + layout->autoAdd(output); + } + }; + connect(m_server->window(), + &WOutputRenderWindow::outputViewportInitialized, + this, + [ensureOutputInLayout](WOutputViewport *viewport) { + ensureOutputInLayout(viewport->output()); + }); + connect(m_server->backend(), + &WBackend::outputAdded, + this, + [this, ensureOutputInLayout](WOutput *output) { + connect(output, + &WOutput::enabledChanged, + this, + [ensureOutputInLayout, output] { ensureOutputInLayout(output); }); + ensureOutputInLayout(output); + }); + protocol_test_setup(m_server); + if (protocol_test_skip && protocol_test_skip()) + QSKIP("protocol fixture requested skip"); + } + + void protocol() + { + // Readiness depends on several asynchronous startup steps (output + // registered in the layout, primary output resolved, lock screen plugin + // loaded, per-user DConfig ready) and not all of them announce + // themselves, so poll the fixture instead of waiting for a signal that + // may never come. QTRY_* keeps the wait bounded and fails with the + // elapsed-time hint instead of being killed by the ctest timeout. + QTRY_VERIFY2_WITH_TIMEOUT(fixtureReady(), "protocol fixture did not become ready", 20s); + QEventLoop loop; + connect(this, &ProtocolTest::clientFinished, &loop, &QEventLoop::quit); + QVERIFY2(pthread_create(&m_thread, nullptr, runClient, &m_context) == 0, + "failed to start protocol client"); + loop.exec(); + + pthread_join(m_thread, nullptr); + if (m_context.result == 77) { + g_clientSkipped = true; + QSKIP("protocol client requested skip"); + } + QCOMPARE(m_context.result, 0); + } + +Q_SIGNALS: + void clientFinished(); + +private: + static void *runClient(void *data) + { + auto *context = static_cast(data); + context->result = protocol_test_run(context->socketName); + QMetaObject::invokeMethod(context->test, + [test = context->test] { test->notifyClientFinished(); }, + Qt::QueuedConnection); + return nullptr; + } + + bool fixtureReady() const + { + return !m_server->rootSurfaceContainer()->outputs().isEmpty() + && (!protocol_test_ready || protocol_test_ready(m_server)); + } + + WaylandServer *m_server = nullptr; + QByteArray m_socketName; + ClientThreadContext m_context; + pthread_t m_thread {}; +}; +} + +extern "C" int invoke_on_server_thread(server_thread_callback callback, void *data) +{ + return g_runner && callback ? g_runner->invoke(callback, data) : 0; +} + +int main(int argc, char *argv[]) +{ + // QML resources use stable qrc URLs, so a stale user disk cache can be + // reused after rebuilding a plugin and make protocol tests run old QML. + qputenv("QML_DISABLE_DISK_CACHE", "1"); + // The compositor exits via std::_Exit(), so no destructor would ever stop a + // wallpaper factory child; simply do not start one. + qputenv("TREELAND_DISABLE_WALLPAPER", "1"); + if (protocol_test_preflight && !protocol_test_preflight()) { + std::fflush(nullptr); + std::_Exit(77); + } + TestDConfigService dconfigService; + if (!dconfigService.start()) { + dconfigService.stop(); + return 1; + } + auto application = Treeland::preInit(argc, argv); + Treeland::postInit(); + if (!dconfigService.waitForService()) { + dconfigService.stop(); + return 1; + } + TestAccountsService accountsService; + if (!accountsService.registerObjects()) { + dconfigService.stop(); + return 1; + } + + DConfigManager dConfigManager(application.get()); + Treeland::Treeland treeland; + + // Treeland::Treeland completes initialization asynchronously: WaylandServer is + // only created once the initial user DConfig objects have finished + // initializing. Spin the event loop until then. + WaylandServer *server = WaylandServer::instance(); + if (!server) { + QEventLoop loop; + QTimer poller; + QObject::connect(&poller, &QTimer::timeout, &loop, [&loop, &server] { + server = WaylandServer::instance(); + if (server) + loop.quit(); + }); + poller.start(50); + QTimer::singleShot(15000, &loop, &QEventLoop::quit); + loop.exec(); + } + if (!server) { + std::fflush(nullptr); + std::_Exit(1); + } + + const auto session = server->sessionManager()->globalSession(); + if (!session || !session->socket() || !session->socket()->isValid()) + return 1; + + const QByteArray socketName = session->socket()->fullServerName().toUtf8(); + ProtocolTestRunner runner; + g_runner = &runner; + ProtocolTest test(server, socketName); + int result = QTest::qExec(&test, argc, argv); + if (g_clientSkipped && result == 0) + result = 77; + g_runner = nullptr; + + // Treeland owns process-lifetime QML singletons whose shutdown ordering is + // only exercised by a compositor process exit. Letting the stack object + // destruct here tears down WaylandServer after its seat event filter and currently + // reaches an invalid SeatManager during that production-only shutdown. + // The protocol client has already completed and been joined, so terminate + // without running the unrelated compositor shutdown sequence. + dconfigService.stop(); + std::fflush(nullptr); + std::_Exit(result); +} + +#include "protocol-test-entry.moc" diff --git a/tests/protocols/framework/server-bridge-api.h b/tests/protocols/framework/server-bridge-api.h new file mode 100644 index 0000000000..fab3c07ac4 --- /dev/null +++ b/tests/protocols/framework/server-bridge-api.h @@ -0,0 +1,17 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*server_thread_callback)(void *data); + +// Runs CALLBACK on the compositor's Qt thread and waits for it to finish. +int invoke_on_server_thread(server_thread_callback callback, void *data); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/framework/server-bridge.cpp b/tests/protocols/framework/server-bridge.cpp new file mode 100644 index 0000000000..b69246a179 --- /dev/null +++ b/tests/protocols/framework/server-bridge.cpp @@ -0,0 +1,84 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "server-bridge.h" + +#include "core/waylandserver.h" + +#include +#include +#include +#include +#include + +#include + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +WServer *native_server(WaylandServer *server) +{ + return server ? server->findChild() : nullptr; +} + +void attach_test_pointer_device(WaylandServer *server) +{ + Q_ASSERT(server); + auto *seat = server->seat(); + Q_ASSERT(seat); + + auto *pointer = static_cast(calloc(1, sizeof(wlr_pointer))); + Q_ASSERT(pointer); + wlr_pointer_init(pointer, nullptr, "test-pointer"); + auto *device = new WInputDevice(&pointer->base, true); + seat->attachInputDevice(device); +} + +WOutput *add_headless_output(WServer *server, int width, int height) +{ + auto *backend = server->findInterface(); + return add_headless_output(backend, true, width, height); +} + +WOutput *add_headless_output(WBackend *backend, bool startBackend, int width, int height) +{ + if (!backend || (startBackend && !wlr_backend_start(backend->handle()))) + return nullptr; + + auto *multi = backend->handle(); + if (!wlr_backend_is_multi(multi)) + return nullptr; + + wlr_backend *headlessHandle = nullptr; + wlr_multi_for_each_backend(multi, [](wlr_backend *backend, void *data) { + if (wlr_backend_is_headless(backend)) + *static_cast(data) = backend; + }, &headlessHandle); + if (!headlessHandle) + return nullptr; + + auto *output = wlr_headless_add_output(headlessHandle, width, height); + if (!output) + return nullptr; + + // wlroots 0.20 requires an explicit commit to enable the output and apply + // its mode. Without this, geometry/rendering-dependent events (xdg-output, + // session-lock, image-copy-capture) are never delivered to clients. + struct wlr_output_state outputState; + wlr_output_state_init(&outputState); + wlr_output_state_set_enabled(&outputState, true); + wlr_output_state_set_custom_mode(&outputState, width, height, 0); + if (!wlr_output_commit_state(output, &outputState)) { + wlr_output_state_finish(&outputState); + return nullptr; + } + wlr_output_state_finish(&outputState); + + auto *woutput = WOutput::fromHandle(output); + if (!woutput) + return nullptr; + wlr_output_create_global(output, woutput->server()->handle()); + return woutput; +} diff --git a/tests/protocols/framework/server-bridge.h b/tests/protocols/framework/server-bridge.h new file mode 100644 index 0000000000..0f2e061cff --- /dev/null +++ b/tests/protocols/framework/server-bridge.h @@ -0,0 +1,47 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +namespace Waylib::Server { +class WBackend; +class WOutput; +} + +class WaylandServer; + +Waylib::Server::WServer *native_server(WaylandServer *server); + +// Adds a virtual wlroots pointer so the production seat advertises pointer +// capability and clients can create wl_pointer resources. +void attach_test_pointer_device(WaylandServer *server); + +template +Interface *find_server_interface(WaylandServer *server) +{ + auto *nativeServer = native_server(server); + if (!nativeServer) + return nullptr; + for (auto *candidate : nativeServer->interfaceList()) { + if (auto *interface = dynamic_cast(candidate)) + return interface; + } + return nullptr; +} + +// Starts the headless backend and adds an output to it. The backend's +// output-added path creates the WOutput wrapper used by protocols that resolve +// wl_output resources server-side. +Waylib::Server::WOutput *add_headless_output(Waylib::Server::WServer *server, + int width = 1920, + int height = 1080); + +// Adds an output to an already-owned backend. The caller selects whether the +// backend must be started first; production WaylandServer tests pass false because +// WaylandServer::init() has already started it. +Waylib::Server::WOutput *add_headless_output(Waylib::Server::WBackend *backend, + bool startBackend, + int width = 1920, + int height = 1080); diff --git a/tests/protocols/framework/test-accounts-service.cpp b/tests/protocols/framework/test-accounts-service.cpp new file mode 100644 index 0000000000..c3da7a6307 --- /dev/null +++ b/tests/protocols/framework/test-accounts-service.cpp @@ -0,0 +1,94 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "test-accounts-service.h" + +#include +#include +#include + +namespace { +constexpr auto accountsService = "org.freedesktop.Accounts"; +constexpr auto accountsPath = "/org/freedesktop/Accounts"; +constexpr auto accountsUserPath = "/org/freedesktop/Accounts/User1000"; + +class TestAccountsManager : public QObject +{ + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "org.freedesktop.Accounts") + Q_PROPERTY(QStringList UserList READ userList) + +public: + QStringList userList() const { return { QString::fromLatin1(accountsUserPath) }; } + +public Q_SLOTS: + QList ListCachedUsers() const + { + return { QDBusObjectPath(QString::fromLatin1(accountsUserPath)) }; + } + + QDBusObjectPath FindUserById(qint64) const + { + return QDBusObjectPath(QString::fromLatin1(accountsUserPath)); + } + QDBusObjectPath FindUserByName(const QString &) const + { + return QDBusObjectPath(QString::fromLatin1(accountsUserPath)); + } +}; + +class TestAccountsUser : public QObject +{ + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "org.freedesktop.Accounts.User") + Q_PROPERTY(int AccountType MEMBER accountType) + Q_PROPERTY(bool NoPasswdLogin MEMBER noPasswdLogin) + Q_PROPERTY(qulonglong Uid MEMBER uid) + Q_PROPERTY(qulonglong Gid MEMBER gid) + Q_PROPERTY(QString UserName MEMBER userName) + Q_PROPERTY(QString FullName MEMBER fullName) + Q_PROPERTY(QString HomeDir MEMBER homeDir) + Q_PROPERTY(QString IconFile MEMBER iconFile) + Q_PROPERTY(QString PasswordHint MEMBER passwordHint) + Q_PROPERTY(QString Locale MEMBER locale) + +public: + int accountType = 0; + bool noPasswdLogin = false; + qulonglong uid = 1000; + qulonglong gid = 1000; + QString userName = QStringLiteral("protocol-test"); + QString fullName = QStringLiteral("Protocol Test"); + QString homeDir = QStringLiteral("/tmp"); + QString iconFile; + QString passwordHint; + QString locale = QStringLiteral("C"); +}; +} + +class TestAccountsService::Private +{ +public: + TestAccountsManager manager; + TestAccountsUser user; +}; + +TestAccountsService::TestAccountsService() + : d(std::make_unique()) +{ +} + +TestAccountsService::~TestAccountsService() = default; + +bool TestAccountsService::registerObjects() +{ + auto connection = QDBusConnection::systemBus(); + constexpr auto exportOptions = QDBusConnection::ExportAllSlots + | QDBusConnection::ExportAllProperties; + return connection.isConnected() + && connection.registerService(QString::fromLatin1(accountsService)) + && connection.registerObject(QString::fromLatin1(accountsPath), &d->manager, exportOptions) + && connection.registerObject(QString::fromLatin1(accountsUserPath), &d->user, exportOptions); +} + +#include "test-accounts-service.moc" diff --git a/tests/protocols/framework/test-accounts-service.h b/tests/protocols/framework/test-accounts-service.h new file mode 100644 index 0000000000..811283ecba --- /dev/null +++ b/tests/protocols/framework/test-accounts-service.h @@ -0,0 +1,19 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +class TestAccountsService +{ +public: + TestAccountsService(); + ~TestAccountsService(); + + bool registerObjects(); + +private: + class Private; + std::unique_ptr d; +}; diff --git a/tests/protocols/framework/test-dconfig-service.cpp b/tests/protocols/framework/test-dconfig-service.cpp new file mode 100644 index 0000000000..bada4dd494 --- /dev/null +++ b/tests/protocols/framework/test-dconfig-service.cpp @@ -0,0 +1,183 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "test-dconfig-service.h" + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace { +constexpr auto dconfigService = "org.desktopspec.ConfigManager"; + +// SIGKILL leaves the bus socket behind: only a graceful shutdown unlinks it. +// A child that outlives its parent would also stay resident until it is reaped +// by init, so make every helper die with this process. +void exitWithParent(pid_t parent) +{ + prctl(PR_SET_PDEATHSIG, SIGTERM); + // The parent may already be gone; the handler would then belong to the + // process that adopted us and never fire for the parent we care about. + if (getppid() != parent) + _exit(0); +} + +// A helper leads its own process group, which then also covers services that +// D-Bus activates on its bus: they are reparented to a babysitter, so an +// exit-time PPID walk misses them while the process group still holds them. +// Without this the helper would inherit the test's group, which also holds +// ctest, so the group could never be signalled as a unit. +void leadOwnProcessGroup() +{ + setpgid(0, 0); +} + +void stopProcess(pid_t &pid) +{ + if (pid <= 0) + return; + + kill(-pid, SIGTERM); + for (int attempt = 0; attempt != 100; ++attempt) { + if (waitpid(pid, nullptr, WNOHANG) == pid) { + // Activated services are not our children and cannot be reaped + // here; one group-wide SIGKILL cleans up any stragglers. + kill(-pid, SIGKILL); + pid = -1; + return; + } + usleep(10'000); + } + + kill(-pid, SIGKILL); + while (waitpid(pid, nullptr, 0) < 0 && errno == EINTR) { + } + pid = -1; +} +} + +bool TestDConfigService::start() +{ + const pid_t parent = getpid(); + + int addressPipe[2]; + if (pipe(addressPipe) != 0) + return false; + + // A Linux abstract socket lives only in the kernel: unlike a /tmp socket it + // cannot be left behind when this process is killed by CTest. + static int instance = 0; + const QByteArray address = "unix:abstract=treeland-protocol-test-" + + QByteArray::number(parent) + '-' + QByteArray::number(++instance); + const QByteArray addressArgument = "--address=" + address; + + m_busPid = fork(); + if (m_busPid == 0) { + leadOwnProcessGroup(); + exitWithParent(parent); + close(addressPipe[0]); + dup2(addressPipe[1], STDOUT_FILENO); + close(addressPipe[1]); + execlp("dbus-daemon", + "dbus-daemon", + "--session", + "--nofork", + "--print-address=1", + "--nopidfile", + addressArgument.constData(), + nullptr); + _exit(127); + } + close(addressPipe[1]); + if (m_busPid < 0) { + close(addressPipe[0]); + return false; + } + // Close the window where the parent signals the group before the child + // has moved itself into it. + setpgid(m_busPid, m_busPid); + + QByteArray printedAddress; + char character; + while (printedAddress.size() < 4096 && read(addressPipe[0], &character, 1) == 1) { + if (character == '\n') + break; + printedAddress.append(character); + } + close(addressPipe[0]); + if (printedAddress.isEmpty()) { + stop(); + return false; + } + qputenv("DBUS_SYSTEM_BUS_ADDRESS", printedAddress); + qputenv("DBUS_SESSION_BUS_ADDRESS", printedAddress); + return startDConfigService(); +} + +bool TestDConfigService::waitForService() +{ + const auto connection = QDBusConnection::systemBus(); + return connection.isConnected() && waitForService(connection, dconfigService); +} + +void TestDConfigService::stop() +{ + // The helpers lead their own process groups, so stopping each group also + // takes down any service the bus activated. + stopProcess(m_dconfigPid); + stopProcess(m_busPid); + if (!m_dconfigPrefix.isEmpty()) + QDir(m_dconfigPrefix).removeRecursively(); +} + +bool TestDConfigService::startDConfigService() +{ + const pid_t parent = getpid(); + + char prefix[] = "/tmp/treeland-protocol-dconfig-XXXXXX"; + if (!mkdtemp(prefix)) + return false; + m_dconfigPrefix = QString::fromLocal8Bit(prefix); + const QByteArray dsgDir = qgetenv("TREELAND_PROTOCOL_TEST_DSG_DIR"); + if (dsgDir.isEmpty() || !QDir().mkpath(m_dconfigPrefix + "/usr/share")) + return false; + const QByteArray dsgLink = (m_dconfigPrefix + "/usr/share/dsg").toLocal8Bit(); + if (symlink(dsgDir.constData(), dsgLink.constData()) != 0) + return false; + + m_dconfigPid = fork(); + if (m_dconfigPid == 0) { + leadOwnProcessGroup(); + exitWithParent(parent); + execlp("dde-dconfig-daemon", + "dde-dconfig-daemon", + "-p", + prefix, + nullptr); + _exit(127); + } + if (m_dconfigPid > 0) + setpgid(m_dconfigPid, m_dconfigPid); + return m_dconfigPid > 0; +} + +bool TestDConfigService::waitForService(const QDBusConnection &connection, + const QString &service) +{ + auto *interface = connection.interface(); + if (!interface) + return false; + for (int attempt = 0; attempt != 100; ++attempt) { + const auto registered = interface->isServiceRegistered(service); + if (registered.isValid() && registered.value()) + return true; + usleep(10'000); + } + return false; +} diff --git a/tests/protocols/framework/test-dconfig-service.h b/tests/protocols/framework/test-dconfig-service.h new file mode 100644 index 0000000000..70892b9eac --- /dev/null +++ b/tests/protocols/framework/test-dconfig-service.h @@ -0,0 +1,26 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include + +class QDBusConnection; + +class TestDConfigService +{ +public: + bool start(); + bool waitForService(); + void stop(); + +private: + bool startDConfigService(); + static bool waitForService(const QDBusConnection &connection, const QString &service); + + pid_t m_busPid = -1; + pid_t m_dconfigPid = -1; + QString m_dconfigPrefix; +}; diff --git a/tests/protocols/framework/xdg-toplevel-client.c b/tests/protocols/framework/xdg-toplevel-client.c new file mode 100644 index 0000000000..2d5b6f5e48 --- /dev/null +++ b/tests/protocols/framework/xdg-toplevel-client.c @@ -0,0 +1,269 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 200809L +#endif + +#include "xdg-toplevel-client.h" + +#include +#include +#include +#include +#include + +static void wm_base_ping(void *data, struct xdg_wm_base *wm_base, uint32_t serial) +{ + (void)data; + xdg_wm_base_pong(wm_base, serial); +} + +static const struct xdg_wm_base_listener wm_base_listener = { + .ping = wm_base_ping, +}; + +static void xdg_surface_configure(void *data, struct xdg_surface *surface, uint32_t serial) +{ + (void)surface; + struct xdg_toplevel_client *toplevel = data; + toplevel->configure_serial = serial; + toplevel->configured = 1; +} + +static const struct xdg_surface_listener xdg_surface_listener = { + .configure = xdg_surface_configure, +}; + +static void xdg_toplevel_configure(void *data, struct xdg_toplevel *toplevel, + int32_t width, int32_t height, struct wl_array *states) +{ + (void)toplevel; + struct xdg_toplevel_client *client = data; + client->configure_width = width; + client->configure_height = height; + client->configure_maximized = 0; + uint32_t *state; + wl_array_for_each(state, states) { + if (*state == XDG_TOPLEVEL_STATE_MAXIMIZED) + client->configure_maximized = 1; + } +} + +static void xdg_toplevel_close(void *data, struct xdg_toplevel *toplevel) +{ + (void)toplevel; + ((struct xdg_toplevel_client *)data)->close_received = 1; +} + +static void xdg_toplevel_configure_bounds(void *data, struct xdg_toplevel *toplevel, + int32_t width, int32_t height) +{ + (void)data; + (void)toplevel; + (void)width; + (void)height; +} + +static void xdg_toplevel_wm_capabilities(void *data, struct xdg_toplevel *toplevel, + struct wl_array *capabilities) +{ + (void)data; + (void)toplevel; + (void)capabilities; +} + +static const struct xdg_toplevel_listener xdg_toplevel_listener = { + .configure = xdg_toplevel_configure, + .close = xdg_toplevel_close, + .configure_bounds = xdg_toplevel_configure_bounds, + .wm_capabilities = xdg_toplevel_wm_capabilities, +}; + +int xdg_toplevel_client_ack_latest_configure( + struct client_connection *connection, + struct xdg_toplevel_client *toplevel) +{ + if (!connection || !connection->display || !toplevel || !toplevel->xdg_surface) + return 0; + if (!toplevel->configure_serial || toplevel->configure_serial == toplevel->acknowledged_configure_serial) + return 1; + + xdg_surface_ack_configure(toplevel->xdg_surface, toplevel->configure_serial); + toplevel->acknowledged_configure_serial = toplevel->configure_serial; + wl_surface_commit(toplevel->surface); + return wl_display_roundtrip(connection->display) >= 0; +} + +static int map_toplevel(struct client_connection *connection, + struct xdg_toplevel_client *toplevel, + int width, + int height, + uint32_t argb) +{ + if (width <= 0 || height <= 0) + return 0; + const int stride = width * 4; + const size_t size = (size_t)stride * height; + char name[64]; + snprintf(name, sizeof(name), "/treeland_protocol_xdg_%d", (int)getpid()); + const int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); + if (fd < 0) + return 0; + shm_unlink(name); + if (ftruncate(fd, (off_t)size) < 0) { + close(fd); + return 0; + } + void *data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (data == MAP_FAILED) { + close(fd); + return 0; + } + uint32_t *pixels = data; + for (size_t i = 0; i < (size_t)width * height; ++i) + pixels[i] = argb; + struct wl_shm_pool *pool = wl_shm_create_pool(toplevel->shm, fd, (int)size); + toplevel->buffer = pool ? wl_shm_pool_create_buffer(pool, 0, width, height, stride, + WL_SHM_FORMAT_ARGB8888) : NULL; + if (pool) + wl_shm_pool_destroy(pool); + munmap(data, size); + close(fd); + if (!toplevel->buffer) + return 0; + wl_surface_attach(toplevel->surface, toplevel->buffer, 0, 0); + wl_surface_damage(toplevel->surface, 0, 0, width, height); + wl_surface_commit(toplevel->surface); + return wl_display_roundtrip(connection->display) >= 0; +} + +static int xdg_toplevel_client_create_internal( + struct client_connection *connection, + struct xdg_toplevel_client *toplevel, + xdg_surface_setup_callback setup, + void *data, + int buffer_width, + int buffer_height, + uint32_t buffer_argb) +{ + memset(toplevel, 0, sizeof(*toplevel)); + toplevel->compositor = client_bind(connection, "wl_compositor", &wl_compositor_interface, 1); + toplevel->wm_base = client_bind(connection, "xdg_wm_base", &xdg_wm_base_interface, 1); + toplevel->shm = client_bind(connection, "wl_shm", &wl_shm_interface, 1); + if (!toplevel->compositor || !toplevel->wm_base || !toplevel->shm) + goto failed; + + xdg_wm_base_add_listener(toplevel->wm_base, &wm_base_listener, toplevel); + toplevel->surface = wl_compositor_create_surface(toplevel->compositor); + if (!toplevel->surface) + goto failed; + if (setup && !setup(toplevel->surface, data)) + goto failed; + toplevel->xdg_surface = xdg_wm_base_get_xdg_surface(toplevel->wm_base, toplevel->surface); + if (!toplevel->xdg_surface) + goto failed; + xdg_surface_add_listener(toplevel->xdg_surface, &xdg_surface_listener, toplevel); + toplevel->toplevel = xdg_surface_get_toplevel(toplevel->xdg_surface); + if (!toplevel->toplevel) + goto failed; + xdg_toplevel_add_listener(toplevel->toplevel, &xdg_toplevel_listener, toplevel); + + wl_surface_commit(toplevel->surface); + if (wl_display_roundtrip(connection->display) < 0 || !toplevel->configured) + goto failed; + if (!xdg_toplevel_client_ack_latest_configure(connection, toplevel)) + goto failed; + return map_toplevel(connection, toplevel, buffer_width, buffer_height, buffer_argb); + +failed: + xdg_toplevel_client_destroy(toplevel); + return 0; +} + +int xdg_toplevel_client_create_pending( + struct client_connection *connection, + struct xdg_toplevel_client *toplevel) +{ + memset(toplevel, 0, sizeof(*toplevel)); + toplevel->compositor = client_bind(connection, "wl_compositor", &wl_compositor_interface, 1); + toplevel->wm_base = client_bind(connection, "xdg_wm_base", &xdg_wm_base_interface, 1); + toplevel->shm = client_bind(connection, "wl_shm", &wl_shm_interface, 1); + if (!toplevel->compositor || !toplevel->wm_base || !toplevel->shm) + goto failed; + + xdg_wm_base_add_listener(toplevel->wm_base, &wm_base_listener, toplevel); + toplevel->surface = wl_compositor_create_surface(toplevel->compositor); + if (!toplevel->surface) + goto failed; + toplevel->xdg_surface = xdg_wm_base_get_xdg_surface(toplevel->wm_base, toplevel->surface); + if (!toplevel->xdg_surface) + goto failed; + xdg_surface_add_listener(toplevel->xdg_surface, &xdg_surface_listener, toplevel); + toplevel->toplevel = xdg_surface_get_toplevel(toplevel->xdg_surface); + if (!toplevel->toplevel) + goto failed; + xdg_toplevel_add_listener(toplevel->toplevel, &xdg_toplevel_listener, toplevel); + wl_surface_commit(toplevel->surface); + return 1; + +failed: + xdg_toplevel_client_destroy(toplevel); + return 0; +} + +int xdg_toplevel_client_complete_map( + struct client_connection *connection, + struct xdg_toplevel_client *toplevel) +{ + if (!toplevel->xdg_surface || wl_display_roundtrip(connection->display) < 0 || !toplevel->configured) + return 0; + if (!xdg_toplevel_client_ack_latest_configure(connection, toplevel)) + return 0; + return map_toplevel(connection, toplevel, 1, 1, 0xffffffffu); +} + +int xdg_toplevel_client_create_with_surface_setup( + struct client_connection *connection, + struct xdg_toplevel_client *toplevel, + xdg_surface_setup_callback setup, + void *data) +{ + return xdg_toplevel_client_create_internal( + connection, toplevel, setup, data, 1, 1, 0xffffffffu); +} + +int xdg_toplevel_client_create(struct client_connection *connection, + struct xdg_toplevel_client *toplevel) +{ + return xdg_toplevel_client_create_with_surface_setup(connection, toplevel, NULL, NULL); +} + +int xdg_toplevel_client_create_with_solid_buffer( + struct client_connection *connection, + struct xdg_toplevel_client *toplevel, + int width, + int height, + uint32_t argb) +{ + return xdg_toplevel_client_create_internal( + connection, toplevel, NULL, NULL, width, height, argb); +} + +void xdg_toplevel_client_destroy(struct xdg_toplevel_client *toplevel) +{ + if (toplevel->toplevel) + xdg_toplevel_destroy(toplevel->toplevel); + if (toplevel->xdg_surface) + xdg_surface_destroy(toplevel->xdg_surface); + if (toplevel->surface) + wl_surface_destroy(toplevel->surface); + if (toplevel->buffer) + wl_buffer_destroy(toplevel->buffer); + if (toplevel->shm) + wl_shm_destroy(toplevel->shm); + if (toplevel->wm_base) + xdg_wm_base_destroy(toplevel->wm_base); + if (toplevel->compositor) + wl_compositor_destroy(toplevel->compositor); + memset(toplevel, 0, sizeof(*toplevel)); +} diff --git a/tests/protocols/framework/xdg-toplevel-client.h b/tests/protocols/framework/xdg-toplevel-client.h new file mode 100644 index 0000000000..bf06e056ba --- /dev/null +++ b/tests/protocols/framework/xdg-toplevel-client.h @@ -0,0 +1,63 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "client-connection.h" +#include "xdg-shell-client-protocol.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct xdg_toplevel_client { + struct wl_compositor *compositor; + struct xdg_wm_base *wm_base; + struct wl_surface *surface; + struct xdg_surface *xdg_surface; + struct xdg_toplevel *toplevel; + struct wl_shm *shm; + struct wl_buffer *buffer; + uint32_t configure_serial; + uint32_t acknowledged_configure_serial; + // Last xdg_toplevel.configure size, for tests that assert compositor-driven resizes. + int32_t configure_width; + int32_t configure_height; + int configured; + int configure_maximized; + int close_received; +}; + +typedef int (*xdg_surface_setup_callback)(struct wl_surface *surface, void *data); + +int xdg_toplevel_client_create_pending( + struct client_connection *connection, + struct xdg_toplevel_client *toplevel); + +int xdg_toplevel_client_complete_map( + struct client_connection *connection, + struct xdg_toplevel_client *toplevel); +int xdg_toplevel_client_create(struct client_connection *connection, + struct xdg_toplevel_client *toplevel); + +int xdg_toplevel_client_create_with_solid_buffer( + struct client_connection *connection, + struct xdg_toplevel_client *toplevel, + int width, + int height, + uint32_t argb); + +int xdg_toplevel_client_create_with_surface_setup( + struct client_connection *connection, + struct xdg_toplevel_client *toplevel, + xdg_surface_setup_callback setup, + void *data); + +int xdg_toplevel_client_ack_latest_configure( + struct client_connection *connection, + struct xdg_toplevel_client *toplevel); +void xdg_toplevel_client_destroy(struct xdg_toplevel_client *toplevel); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/input-method-unstable-v2/CMakeLists.txt b/tests/protocols/input-method-unstable-v2/CMakeLists.txt new file mode 100644 index 0000000000..3f0716cdf3 --- /dev/null +++ b/tests/protocols/input-method-unstable-v2/CMakeLists.txt @@ -0,0 +1,12 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +treeland_add_protocol_test( + NAME input_method_unstable_v2 + XML "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/input-method-unstable-v2.xml" + EXTRA_XMLS + "${PROJECT_SOURCE_DIR}/waylib/src/server/protocols/private/text-input-unstable-v2.xml" + "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/virtual-keyboard-unstable-v1.xml" + EXTRA_LIBRARIES PkgConfig::XKBCOMMON + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/input-method-unstable-v2.c" +) diff --git a/tests/protocols/input-method-unstable-v2/README.md b/tests/protocols/input-method-unstable-v2/README.md new file mode 100644 index 0000000000..3834a74f0a --- /dev/null +++ b/tests/protocols/input-method-unstable-v2/README.md @@ -0,0 +1,69 @@ +# `input-method-unstable-v2` 测试规范 + +## 范围 + +- XML / interface:`3rdparty/wlroots/protocol/input-method-unstable-v2.xml` / + `zwp_input_method_manager_v2`、`zwp_input_method_v2`、popup surface 与 keyboard grab v2 +- 测试源码:`tests/protocols/input-method-unstable-v2/` +- Fixture:完整生产 `Treeland` / `WaylandServer`、默认 seat 与 headless output。一个 client 作为 mapped 且 + focused 的 text-input-v2 应用,另一个 client 作为 IM;不依赖系统输入法或物理设备。`ShellHandler` + 创建的 `WInputMethodHelper` 经 `WInputMethodManagerV2` 使用 wlroots 原生 global。 +- 覆盖等级:**P / E**;P 覆盖 XML 的资源、生命周期与单 seat 约束,E 覆盖真实 text-input ↔ IM 转发。 + +## 必须观察到的结果 + +| XML 语义 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| inactive 接受编辑状态 | 首个 input method 在未 `activate` 时依次 `commit_string`、`set_preedit_string`、`delete_surrounding_text`、`commit(0)` | 请求不造成协议错误,也不产生 input-method event;后续 active text-input 的 reset 语义由下一层 E 测试验证 | P | +| popup 角色和销毁顺序 | 为无角色 `wl_surface` 调用 `get_input_popup_surface`,先销毁 popup 再销毁 surface | 创建和销毁均无协议错误 | P | +| focused text-input 的状态快照 | fake app 映射 xdg toplevel,并 enable text-input-v2,设置 surrounding text/content type/cursor rectangle | fake IM 收到 `activate`、`surrounding_text("abc",3,3)`、`text_change_cause(input_method)`、`content_type(auto_completion,email)` 和一个 `done` | E | +| focused text-input 的 disable/再 enable | fake app 在仍 focused 时 `disable`,随后对同一 surface 再 `enable` | fake IM 先收到一次 `deactivate`,再收到第二次 `activate`;生产 helper 不残留旧 text-input | E | +| IM 编辑结果回传应用 | fake IM 设置 delete、commit string、preedit 后 `commit(0)` | fake app 收到正确的 `delete_surrounding_text(1,2)`、`commit_string("committed")`、preedit string/cursor/styling | E | +| 清空 preedit | fake IM 在不发送 `set_preedit_string` 的情况下 `commit`(fcitx5 清空 preedit 时的行为) | fake app 再次收到 `preedit_string` 且文本为空,残留的组合文本被清除(此前只在非空时转发,导致应用永远保留旧 preedit) | E | +| 丢焦点时清 preedit | fake IM 被销毁,focused text-input 因此收到 `leave`(与切窗口时走同一条 `sendLeave()` 路径) | fake app 在 `leave` 前再收到一次空的 `preedit_string`(断言同时校验事件先后顺序),组合文本被清除而不是留给客户端自行处理 | E | +| active popup 定位 | fake IM 为 roleless surface 创建 popup | 收到生产 helper 按 text-input cursor rectangle 发出的 `text_input_rectangle(11,12,13,14)` | E | +| keyboard grab 资源 | `grab_keyboard` 后 roundtrip,再 `release` | 子资源可创建并按 release 生命周期销毁 | P | +| 每 seat 唯一 input method | 同一 `wl_seat` 再次 `get_input_method` | 第二对象只收到一次 `unavailable`,没有其他 event | P | +| manager 与子对象生命周期分离 | `zwp_input_method_manager_v2.destroy` 后继续向第一个 IM 提交并 roundtrip | 已创建的 IM 未被 manager destroy 连带销毁,也没有协议错误 | P | + +## 生产结果 + +`WaylandServer::init() → ShellHandler::init() → WInputMethodHelper → +WServer::attach() → wlr_input_method_manager_v2_create()`。 + +同一个 seat 的第二个 IM 是由生产 `WInputMethodHelper::handleNewIMV2()` 调用 +`wlr_input_method_v2_send_unavailable()`。测试断言这个 event 是其唯一 event,而不是仅检查 +client 未崩溃。popup 与 keyboard grab 的 resource 则由 +`3rdparty/wlroots/types/wlr_input_method_v2.c` 创建和销毁。 + +### E 级证据 + +测试不依赖系统输入法:一个 client 映射真实 xdg toplevel、创建 text-input-v2 并提交状态, +但暂不 enable;另一个 client 先创建 IM 并验证 inactive 编辑,第一个 client 再 +enable text-input-v2 触发激活。由 +`WInputMethodHelper` 从真实 focused text-input 读取 surrounding text、content type、cursor +rectangle 后发送给 IM。测试断言这些 event 的 payload,而不是 fixture 伪造 event。 + +IM 的 delete/commit/preedit 随后经同一生产 helper 回传到第一个 client 的 text-input 对象; +该 client 断言收到的删除范围、committed 文本与 preedit 属性。keyboard-grab 的 keymap、按键、 +modifier、repeat-info 也由另一 client 的 virtual keyboard 经真实 `WSeat` 转发。因此状态同步、 +编辑回传、popup rectangle 与 grab 输入为 E 级;inactive、重复 IM 与资源销毁仍为 P 级。 + +## 已知边界 / 下一项结果 + +测试客户端直接调用 XML 中全部 **11 / 11 request**(含 `destroy` / `release`):manager 2、 +input method 7、popup 1、keyboard grab 1。 + +已实际断言 `unavailable` 以及 active 状态链的 `activate`、`surrounding_text`、 +`text_change_cause`、`content_type`、`done`、`text_input_rectangle`,并由 fake text-input 断言 +IM commit 的文本 event。client 在仍 focused 时 `disable` 会经生产 +`WTextInputV2::clearEnabledSurface()` 触发 `disabled()`,再由 `WInputMethodHelper` 向 IM 发 +`deactivate`;同一 text-input 再次 `enable` 会重新 `activate`。下列 event 仍未覆盖,不能以 +headless 空 seat 的“没有 event”冒充覆盖: + +- focus 转移导致的 `deactivate`,以及连续 text-input state update 是否只传递最新快照。 + +自包含测试已经由另一个 client 的 virtual keyboard 驱动并断言 keyboard-grab 的 +`keymap`、`key`、`modifiers`、`repeat_info`;使用另一 client 避免 IM 自己注入的 virtual keyboard +被生产实现按回环规则转交 default grab。下一项 E 级测试应覆盖 focus 转移后的 `deactivate` 和 +两次 text-input state update 的最新状态快照。 diff --git a/tests/protocols/input-method-unstable-v2/input-method-unstable-v2.c b/tests/protocols/input-method-unstable-v2/input-method-unstable-v2.c new file mode 100644 index 0000000000..22b7d5ad21 --- /dev/null +++ b/tests/protocols/input-method-unstable-v2/input-method-unstable-v2.c @@ -0,0 +1,573 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 200809L +#endif + +#include "input-method-unstable-v2.h" +#include "input-method-unstable-v2-client-protocol.h" +#include "client-connection.h" +#include "xdg-toplevel-client.h" +#include "text-input-unstable-v2-client-protocol.h" +#include "virtual-keyboard-unstable-v1-client-protocol.h" + +#include +#include +#include +#include +#include +#include + +#include + +// input-method-v2 references zwp_text_input_v3.change_cause, whose +// input_method value is specified as zero. The v3 XML is not a test input. +#define INPUT_METHOD_CHANGE_CAUSE_INPUT_METHOD 0u + +struct input_method_events { + unsigned int activate; + unsigned int deactivate; + unsigned int surrounding_text; + unsigned int text_change_cause; + unsigned int content_type; + unsigned int done; + unsigned int unavailable; + char surrounding[64]; + uint32_t cursor; + uint32_t anchor; + uint32_t cause; + uint32_t hint; + uint32_t purpose; +}; + +struct text_input_events { + unsigned int enter; + unsigned int leave; + unsigned int commit_string; + unsigned int delete_surrounding_text; + unsigned int preedit_string; + // preedit_string count when leave arrived: the clearing preedit must come + // first, otherwise the client drops its composing state before it is told + // to clear the preedit. + unsigned int preedit_string_at_leave; + unsigned int preedit_cursor; + unsigned int preedit_styling; + char committed[64]; + char preedit[64]; + uint32_t delete_before; + uint32_t delete_after; + int32_t preedit_cursor_index; + uint32_t preedit_style_length; +}; + +struct popup_events { + unsigned int text_input_rectangle; + int32_t x; + int32_t y; + int32_t width; + int32_t height; +}; + +struct keyboard_grab_events { + unsigned int keymap; + unsigned int key; + unsigned int modifiers; + unsigned int repeat_info; + uint32_t last_key; + uint32_t last_key_state; + uint32_t last_modifiers; + int32_t repeat_rate; + int32_t repeat_delay; +}; + +static int send_keymap(struct zwp_virtual_keyboard_v1 *keyboard) +{ + struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + struct xkb_keymap *keymap = context + ? xkb_keymap_new_from_names(context, NULL, XKB_KEYMAP_COMPILE_NO_FLAGS) : NULL; + char *keymap_text = keymap + ? xkb_keymap_get_as_string(keymap, XKB_KEYMAP_FORMAT_TEXT_V1) : NULL; + if (!keymap_text) + goto failed; + + char name[64]; + snprintf(name, sizeof(name), "/treeland_input_method_keymap_%d", (int)getpid()); + const int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); + shm_unlink(name); + if (fd < 0) + goto failed; + const size_t size = strlen(keymap_text) + 1; + if (ftruncate(fd, (off_t)size) < 0 || write(fd, keymap_text, size) != (ssize_t)size) { + close(fd); + goto failed; + } + zwp_virtual_keyboard_v1_keymap(keyboard, WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, fd, (uint32_t)size); + close(fd); + free(keymap_text); + xkb_keymap_unref(keymap); + xkb_context_unref(context); + return 1; + +failed: + if (keymap_text) free(keymap_text); + if (keymap) xkb_keymap_unref(keymap); + if (context) xkb_context_unref(context); + return 0; +} + +static void im_activate(void *data, struct zwp_input_method_v2 *im) +{ + (void)im; + ++((struct input_method_events *)data)->activate; +} + +static void im_deactivate(void *data, struct zwp_input_method_v2 *im) +{ + (void)im; + ++((struct input_method_events *)data)->deactivate; +} + +static void im_surrounding_text(void *data, struct zwp_input_method_v2 *im, + const char *text, uint32_t cursor, uint32_t anchor) +{ + (void)im; + struct input_method_events *events = data; + ++events->surrounding_text; + snprintf(events->surrounding, sizeof(events->surrounding), "%s", text); + events->cursor = cursor; + events->anchor = anchor; +} + +static void im_text_change_cause(void *data, struct zwp_input_method_v2 *im, uint32_t cause) +{ + (void)im; + struct input_method_events *events = data; + ++events->text_change_cause; + events->cause = cause; +} + +static void im_content_type(void *data, struct zwp_input_method_v2 *im, + uint32_t hint, uint32_t purpose) +{ + (void)im; + struct input_method_events *events = data; + ++events->content_type; + events->hint = hint; + events->purpose = purpose; +} + +static void im_done(void *data, struct zwp_input_method_v2 *im) +{ + (void)im; + ++((struct input_method_events *)data)->done; +} + +static void im_unavailable(void *data, struct zwp_input_method_v2 *im) +{ + (void)im; + ++((struct input_method_events *)data)->unavailable; +} + +static const struct zwp_input_method_v2_listener im_listener = { + .activate = im_activate, + .deactivate = im_deactivate, + .surrounding_text = im_surrounding_text, + .text_change_cause = im_text_change_cause, + .content_type = im_content_type, + .done = im_done, + .unavailable = im_unavailable, +}; + +static void text_input_enter(void *data, struct zwp_text_input_v2 *text_input, + uint32_t serial, struct wl_surface *surface) +{ + (void)text_input; + (void)serial; + (void)surface; + ++((struct text_input_events *)data)->enter; +} + +static void text_input_leave(void *data, struct zwp_text_input_v2 *text_input, + uint32_t serial, struct wl_surface *surface) +{ + (void)text_input; + (void)serial; + (void)surface; + struct text_input_events *events = data; + ++events->leave; + events->preedit_string_at_leave = events->preedit_string; +} + +static void text_input_input_panel_state(void *data, struct zwp_text_input_v2 *text_input, + uint32_t state, int32_t x, int32_t y, int32_t width, int32_t height) +{ (void)data; (void)text_input; (void)state; (void)x; (void)y; (void)width; (void)height; } + +static void text_input_preedit_string(void *data, struct zwp_text_input_v2 *text_input, + const char *text, const char *commit) +{ + (void)text_input; + (void)commit; + struct text_input_events *events = data; + ++events->preedit_string; + snprintf(events->preedit, sizeof(events->preedit), "%s", text); +} + +static void text_input_preedit_styling(void *data, struct zwp_text_input_v2 *text_input, + uint32_t index, uint32_t length, uint32_t style) +{ + (void)text_input; + (void)index; + (void)style; + struct text_input_events *events = data; + ++events->preedit_styling; + events->preedit_style_length = length; +} + +static void text_input_preedit_cursor(void *data, struct zwp_text_input_v2 *text_input, int32_t index) +{ + (void)text_input; + struct text_input_events *events = data; + ++events->preedit_cursor; + events->preedit_cursor_index = index; +} + +static void text_input_commit_string(void *data, struct zwp_text_input_v2 *text_input, const char *text) +{ + (void)text_input; + struct text_input_events *events = data; + ++events->commit_string; + snprintf(events->committed, sizeof(events->committed), "%s", text); +} + +static void text_input_cursor_position(void *data, struct zwp_text_input_v2 *text_input, + int32_t index, int32_t anchor) +{ (void)data; (void)text_input; (void)index; (void)anchor; } + +static void text_input_delete_surrounding_text(void *data, struct zwp_text_input_v2 *text_input, + uint32_t before, uint32_t after) +{ + (void)text_input; + struct text_input_events *events = data; + ++events->delete_surrounding_text; + events->delete_before = before; + events->delete_after = after; +} + +static void text_input_modifiers_map(void *data, struct zwp_text_input_v2 *text_input, struct wl_array *map) +{ (void)data; (void)text_input; (void)map; } +static void text_input_keysym(void *data, struct zwp_text_input_v2 *text_input, + uint32_t time, uint32_t sym, uint32_t state, uint32_t modifiers) +{ (void)data; (void)text_input; (void)time; (void)sym; (void)state; (void)modifiers; } +static void text_input_language(void *data, struct zwp_text_input_v2 *text_input, const char *language) +{ (void)data; (void)text_input; (void)language; } +static void text_input_direction(void *data, struct zwp_text_input_v2 *text_input, uint32_t direction) +{ (void)data; (void)text_input; (void)direction; } +static void text_input_configure_surrounding(void *data, struct zwp_text_input_v2 *text_input, + int32_t before, int32_t after) +{ (void)data; (void)text_input; (void)before; (void)after; } +static void text_input_method_changed(void *data, struct zwp_text_input_v2 *text_input, + uint32_t serial, uint32_t flags) +{ (void)data; (void)text_input; (void)serial; (void)flags; } + +static const struct zwp_text_input_v2_listener text_input_listener = { + .enter = text_input_enter, + .leave = text_input_leave, + .input_panel_state = text_input_input_panel_state, + .preedit_string = text_input_preedit_string, + .preedit_styling = text_input_preedit_styling, + .preedit_cursor = text_input_preedit_cursor, + .commit_string = text_input_commit_string, + .cursor_position = text_input_cursor_position, + .delete_surrounding_text = text_input_delete_surrounding_text, + .modifiers_map = text_input_modifiers_map, + .keysym = text_input_keysym, + .language = text_input_language, + .text_direction = text_input_direction, + .configure_surrounding_text = text_input_configure_surrounding, + .input_method_changed = text_input_method_changed, +}; + +static void popup_text_input_rectangle(void *data, struct zwp_input_popup_surface_v2 *popup, + int32_t x, int32_t y, int32_t width, int32_t height) +{ + (void)popup; + struct popup_events *events = data; + ++events->text_input_rectangle; + events->x = x; + events->y = y; + events->width = width; + events->height = height; +} + +static const struct zwp_input_popup_surface_v2_listener popup_listener = { + .text_input_rectangle = popup_text_input_rectangle, +}; + +static void keyboard_grab_keymap(void *data, struct zwp_input_method_keyboard_grab_v2 *grab, + uint32_t format, int32_t fd, uint32_t size) +{ + (void)grab; + (void)format; + (void)size; + ++((struct keyboard_grab_events *)data)->keymap; + close(fd); +} + +static void keyboard_grab_key(void *data, struct zwp_input_method_keyboard_grab_v2 *grab, + uint32_t serial, uint32_t time, uint32_t key, uint32_t state) +{ + (void)grab; + (void)serial; + (void)time; + struct keyboard_grab_events *events = data; + ++events->key; + events->last_key = key; + events->last_key_state = state; +} + +static void keyboard_grab_modifiers(void *data, struct zwp_input_method_keyboard_grab_v2 *grab, + uint32_t serial, uint32_t depressed, uint32_t latched, + uint32_t locked, uint32_t group) +{ + (void)grab; + (void)serial; + (void)latched; + (void)locked; + (void)group; + struct keyboard_grab_events *events = data; + ++events->modifiers; + events->last_modifiers = depressed; +} + +static void keyboard_grab_repeat_info(void *data, struct zwp_input_method_keyboard_grab_v2 *grab, + int32_t rate, int32_t delay) +{ + (void)grab; + struct keyboard_grab_events *events = data; + ++events->repeat_info; + events->repeat_rate = rate; + events->repeat_delay = delay; +} + +static const struct zwp_input_method_keyboard_grab_v2_listener keyboard_grab_listener = { + .keymap = keyboard_grab_keymap, + .key = keyboard_grab_key, + .modifiers = keyboard_grab_modifiers, + .repeat_info = keyboard_grab_repeat_info, +}; + +int protocol_test_run(const char *socket_name) +{ + struct client_connection app = {0}; + struct client_connection im_connection = {0}; + struct xdg_toplevel_client toplevel = {0}; + struct input_method_events first_events = {0}; + struct input_method_events second_events = {0}; + struct text_input_events text_events = {0}; + struct popup_events popup_events = {0}; + struct keyboard_grab_events grab_events = {0}; + struct wl_seat *app_seat = NULL; + struct zwp_text_input_manager_v2 *text_manager = NULL; + struct zwp_text_input_v2 *text_input = NULL; + struct zwp_virtual_keyboard_manager_v1 *virtual_keyboard_manager = NULL; + struct zwp_virtual_keyboard_v1 *virtual_keyboard = NULL; + struct wl_seat *im_seat = NULL; + struct wl_compositor *im_compositor = NULL; + struct zwp_input_method_manager_v2 *manager = NULL; + struct zwp_input_method_v2 *first = NULL; + struct zwp_input_method_v2 *second = NULL; + struct wl_surface *popup_surface = NULL; + struct zwp_input_popup_surface_v2 *popup = NULL; + struct zwp_input_method_keyboard_grab_v2 *grab = NULL; + int stage = 0; + + if (!client_connect(&app, socket_name) || !client_connect(&im_connection, socket_name)) + goto failed; + app_seat = client_bind(&app, "wl_seat", &wl_seat_interface, 1); + text_manager = client_bind(&app, "zwp_text_input_manager_v2", + &zwp_text_input_manager_v2_interface, 1); + virtual_keyboard_manager = client_bind(&app, "zwp_virtual_keyboard_manager_v1", + &zwp_virtual_keyboard_manager_v1_interface, 1); + if (!app_seat || !text_manager || !virtual_keyboard_manager + || !xdg_toplevel_client_create(&app, &toplevel)) + goto failed; + text_input = zwp_text_input_manager_v2_get_text_input(text_manager, app_seat); + if (!text_input) + goto failed; + zwp_text_input_v2_add_listener(text_input, &text_input_listener, &text_events); + zwp_text_input_v2_set_surrounding_text(text_input, "abc", 3, 3); + zwp_text_input_v2_set_content_type(text_input, + ZWP_TEXT_INPUT_V2_CONTENT_HINT_AUTO_COMPLETION, + ZWP_TEXT_INPUT_V2_CONTENT_PURPOSE_EMAIL); + zwp_text_input_v2_set_cursor_rectangle(text_input, 11, 12, 13, 14); + zwp_text_input_v2_update_state(text_input, 0, ZWP_TEXT_INPUT_V2_UPDATE_STATE_FULL); + if (wl_display_roundtrip(app.display) < 0) + goto failed; + + im_seat = client_bind(&im_connection, "wl_seat", &wl_seat_interface, 1); + im_compositor = client_bind(&im_connection, "wl_compositor", &wl_compositor_interface, 1); + manager = client_bind(&im_connection, "zwp_input_method_manager_v2", + &zwp_input_method_manager_v2_interface, 1); + if (!im_seat || !im_compositor || !manager) + goto failed; + first = zwp_input_method_manager_v2_get_input_method(manager, im_seat); + if (!first) + goto failed; + zwp_input_method_v2_add_listener(first, &im_listener, &first_events); + + // XML requires these edits to be accepted while inactive. The following + // focus/activate must reset them rather than replaying an old state. + zwp_input_method_v2_commit_string(first, "inactive"); + zwp_input_method_v2_set_preedit_string(first, "inactive-preedit", 1, 3); + zwp_input_method_v2_delete_surrounding_text(first, 2, 4); + zwp_input_method_v2_commit(first, 0); + if (wl_display_roundtrip(im_connection.display) < 0 || first_events.activate + || first_events.deactivate || first_events.surrounding_text + || first_events.text_change_cause || first_events.content_type || first_events.done + || first_events.unavailable) + goto failed; + zwp_text_input_v2_enable(text_input, toplevel.surface); + if (wl_display_roundtrip(app.display) < 0) + goto failed; + stage = 1; + + if (wl_display_roundtrip(im_connection.display) < 0 + || first_events.activate != 1 || first_events.surrounding_text != 1 + || strcmp(first_events.surrounding, "abc") != 0 || first_events.cursor != 3 + || first_events.anchor != 3 || first_events.text_change_cause != 1 + || first_events.cause != INPUT_METHOD_CHANGE_CAUSE_INPUT_METHOD + || first_events.content_type != 1 + || first_events.hint != ZWP_TEXT_INPUT_V2_CONTENT_HINT_AUTO_COMPLETION + || first_events.purpose != ZWP_TEXT_INPUT_V2_CONTENT_PURPOSE_EMAIL + || first_events.done != 1 || first_events.unavailable) + goto failed; + const uint32_t input_method_serial = first_events.done; + stage = 2; + + popup_surface = wl_compositor_create_surface(im_compositor); + popup = popup_surface ? zwp_input_method_v2_get_input_popup_surface(first, popup_surface) : NULL; + if (!popup) + goto failed; + zwp_input_popup_surface_v2_add_listener(popup, &popup_listener, &popup_events); + if (wl_display_roundtrip(im_connection.display) < 0 || popup_events.text_input_rectangle != 1 + || popup_events.x != 11 || popup_events.y != 12 || popup_events.width != 13 || popup_events.height != 14) + goto failed; + zwp_input_popup_surface_v2_destroy(popup); + popup = NULL; + wl_surface_destroy(popup_surface); + popup_surface = NULL; + stage = 3; + + zwp_input_method_v2_delete_surrounding_text(first, 1, 2); + zwp_input_method_v2_commit_string(first, "committed"); + zwp_input_method_v2_set_preedit_string(first, "preedit", 1, 4); + zwp_input_method_v2_commit(first, input_method_serial); + if (wl_display_roundtrip(im_connection.display) < 0 || wl_display_roundtrip(app.display) < 0 + || text_events.enter != 1 || text_events.delete_surrounding_text != 1 || text_events.delete_before != 1 + || text_events.delete_after != 2 || text_events.commit_string != 1 + || strcmp(text_events.committed, "committed") != 0 || text_events.preedit_string != 1 + || strcmp(text_events.preedit, "preedit") != 0 || text_events.preedit_cursor != 1 + || text_events.preedit_cursor_index != 3 || text_events.preedit_styling != 1 + || text_events.preedit_style_length != strlen("preedit")) + goto failed; + stage = 4; + + // A commit that does not send set_preedit_string means the preedit is now + // empty, so the app must be told to drop the stale composing text instead + // of keeping it forever: fcitx5 only ever sends a non-empty preedit. + zwp_input_method_v2_commit(first, input_method_serial); + if (wl_display_roundtrip(im_connection.display) < 0 || wl_display_roundtrip(app.display) < 0 + || text_events.preedit_string != 2 || text_events.preedit[0] != '\0') + goto failed; + stage = 5; + + virtual_keyboard = zwp_virtual_keyboard_manager_v1_create_virtual_keyboard( + virtual_keyboard_manager, app_seat); + if (!virtual_keyboard || !send_keymap(virtual_keyboard) || wl_display_roundtrip(app.display) < 0) + goto failed; + grab = zwp_input_method_v2_grab_keyboard(first); + if (!grab) + goto failed; + zwp_input_method_keyboard_grab_v2_add_listener(grab, &keyboard_grab_listener, &grab_events); + if (wl_display_roundtrip(im_connection.display) < 0 || grab_events.keymap != 1 + || grab_events.modifiers != 1 || grab_events.repeat_info != 1 + || grab_events.repeat_rate < 0 || grab_events.repeat_delay < 0) + goto failed; + zwp_virtual_keyboard_v1_key(virtual_keyboard, 1, 59, WL_KEYBOARD_KEY_STATE_PRESSED); + zwp_virtual_keyboard_v1_key(virtual_keyboard, 2, 59, WL_KEYBOARD_KEY_STATE_RELEASED); + zwp_virtual_keyboard_v1_modifiers(virtual_keyboard, 1, 0, 0, 0); + if (wl_display_roundtrip(app.display) < 0 || wl_display_roundtrip(im_connection.display) < 0 + || grab_events.key != 2 || grab_events.last_key != 59 + || grab_events.last_key_state != WL_KEYBOARD_KEY_STATE_RELEASED + || grab_events.modifiers != 2 || grab_events.last_modifiers != 1) + goto failed; + zwp_input_method_keyboard_grab_v2_release(grab); + grab = NULL; + + second = zwp_input_method_manager_v2_get_input_method(manager, im_seat); + if (!second) + goto failed; + zwp_input_method_v2_add_listener(second, &im_listener, &second_events); + if (wl_display_roundtrip(im_connection.display) < 0 || second_events.unavailable != 1 + || second_events.activate || second_events.deactivate || second_events.surrounding_text + || second_events.text_change_cause || second_events.content_type || second_events.done) + goto failed; + stage = 6; + + zwp_input_method_manager_v2_destroy(manager); + manager = NULL; + zwp_input_method_v2_commit_string(first, "survives-manager-destroy"); + zwp_input_method_v2_commit(first, input_method_serial); + if (wl_display_roundtrip(im_connection.display) < 0 || wl_display_roundtrip(app.display) < 0) + goto failed; + stage = 7; + + // Regression: the client disables while it is still focused. The compositor + // must report that transition to the input method, otherwise the helper keeps + // the stale text input and the next enable never re-activates the IME. + zwp_text_input_v2_disable(text_input, toplevel.surface); + if (wl_display_roundtrip(app.display) < 0 || wl_display_roundtrip(im_connection.display) < 0 + || first_events.deactivate != 1 || first_events.done != 2) + goto failed; + stage = 8; + + zwp_text_input_v2_enable(text_input, toplevel.surface); + if (wl_display_roundtrip(app.display) < 0 || wl_display_roundtrip(im_connection.display) < 0 + || first_events.activate != 2 || first_events.deactivate != 1 || first_events.done != 3) + goto failed; + stage = 9; + + zwp_input_method_v2_destroy(second); + zwp_input_method_v2_destroy(first); + // Destroying the input method leaves every focused text input. This runs the + // same sendLeave() path as a keyboard focus move to another window, and the + // client must be told to drop its composing text before it loses focus. + if (wl_display_roundtrip(im_connection.display) < 0 || wl_display_roundtrip(app.display) < 0 + || text_events.preedit_string != 4 || text_events.preedit[0] != '\0' + || text_events.leave != 1 || text_events.preedit_string_at_leave != 4) + goto failed; + stage = 10; + + zwp_text_input_v2_destroy(text_input); + zwp_text_input_manager_v2_destroy(text_manager); + zwp_virtual_keyboard_v1_destroy(virtual_keyboard); + wl_seat_destroy(im_seat); + wl_compositor_destroy(im_compositor); + wl_seat_destroy(app_seat); + xdg_toplevel_client_destroy(&toplevel); + client_disconnect(&im_connection); + client_disconnect(&app); + return 0; + +failed: + fprintf(stderr, "input-method-v2 failure at stage %d: IM=(activate=%u surrounding=%u cause=%u content=%u done=%u unavailable=%u) text=(enter=%u commit=%u delete=%u preedit=%u leave=%u preedit_at_leave=%u)\n", + stage, first_events.activate, first_events.surrounding_text, + first_events.text_change_cause, first_events.content_type, first_events.done, + first_events.unavailable, text_events.enter, text_events.commit_string, + text_events.delete_surrounding_text, text_events.preedit_string, + text_events.leave, text_events.preedit_string_at_leave); + client_disconnect(&im_connection); + client_disconnect(&app); + return 1; +} diff --git a/tests/protocols/input-method-unstable-v2/input-method-unstable-v2.h b/tests/protocols/input-method-unstable-v2/input-method-unstable-v2.h new file mode 100644 index 0000000000..c6cd0ff613 --- /dev/null +++ b/tests/protocols/input-method-unstable-v2/input-method-unstable-v2.h @@ -0,0 +1,14 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/input-method-unstable-v2/setup.cpp b/tests/protocols/input-method-unstable-v2/setup.cpp new file mode 100644 index 0000000000..882458a97c --- /dev/null +++ b/tests/protocols/input-method-unstable-v2/setup.cpp @@ -0,0 +1,12 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "server-bridge.h" +#include "core/waylandserver.h" + +#include + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); +} diff --git a/tests/protocols/protocol-specification-template.md b/tests/protocols/protocol-specification-template.md new file mode 100644 index 0000000000..87aa63e32e --- /dev/null +++ b/tests/protocols/protocol-specification-template.md @@ -0,0 +1,24 @@ +# `` 测试规范 + +## 范围 + +- XML / interface:`<全局接口与版本>` +- 测试源码:`tests/protocols/<测试目录>/` +- Fixture:`<协议 fixture | desktop integration fixture | rendered output fixture>` +- 覆盖等级:`P | I | E | V` + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| `<名称>` | `<请求>` | `<状态、事件或业务结果>` | `P/I/E/V` | + +## 生产结果 + +说明测试观察到的真实生产对象或子系统。如果测试只检查协议实现的局部状态,必须 +明确写出这一点。 + +## 已知边界 / 下一项结果 + +列出该测试尚未证明的语义,以及下一步所需前提,例如 mapped xdg 窗口、已聚焦 +seat、真实 output、source buffer 或像素读回。 diff --git a/tests/protocols/session-isolation/CMakeLists.txt b/tests/protocols/session-isolation/CMakeLists.txt new file mode 100644 index 0000000000..5204f6e2ee --- /dev/null +++ b/tests/protocols/session-isolation/CMakeLists.txt @@ -0,0 +1,19 @@ +treeland_add_protocol_test( + NAME session_isolation + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-foreign-toplevel-manager-unstable-v3.xml" + EXTRA_XMLS + "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-prelaunch-splash-unstable-v2.xml" + "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-shortcut-manager-unstable-v3.xml" + "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-appearance-unstable-v1.xml" + "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-appearance-manager-unstable-v1.xml" + "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-output-management-unstable-v1.xml" + "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-layer-shell-unstable-v1.xml" + "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-foreign-toplevel-management-unstable-v1.xml" + "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-foreign-toplevel-list/ext-foreign-toplevel-list-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/session-isolation.c" +) + +if(TARGET test_session_isolation) + target_sources(test_session_isolation PRIVATE appearance-isolation.c appearance-isolation.h background-window.c background-window.h) +endif() diff --git a/tests/protocols/session-isolation/README.md b/tests/protocols/session-isolation/README.md new file mode 100644 index 0000000000..1d43990278 --- /dev/null +++ b/tests/protocols/session-isolation/README.md @@ -0,0 +1,85 @@ +# Session 窗口隔离 + +新增用例,尚未编译或执行。断言目标为 E 级生产集成结果,不代表已经验证通过。 + +Fixture 复用实际 SessionManager,为全局 Session 和第二个本地账户分别建立 Session; +C 客户端通过两个 Session socket 建立真实连接,各自创建一个 mapped xdg-toplevel。 +第二账户不存在时返回 77。测试连接与合成器位于同一进程,恢复 A 前先销毁 B 的服务端 +连接,避免正常的后台进程暂停逻辑向测试进程发送 SIGSTOP。 + +Fixture 补齐三个 headless 输出,每个 Session 持有独立的 output 协议与窗口区域对象,显示参数使用共享系统配置;客户端在同一连接上 +跟踪 head/finished 事件,账户往返切换后仍必须只有三个 head。 + +两个客户端还分别映射底部 LayerShell 面板(40/60 像素 exclusive zone)。 + +缩放用例由 fixture 调用生产 UI 入口 `SessionOutputManager::setScale`,验证共享系统配置、逻辑几何和物理状态;另有真实 C 客户端对三个 head 的枚举、属性事件与账户切换的回归断言;所有新增断言均未运行。 + +新增 shell/个性化/appearance 覆盖:比较两个 Session 的协议实例,客户端只看到各自的一份 globals; +两个真实 appearance manager 分别设置字体大小 17/22,另一个用户的 appearance 客户端 +不应收到变更,也不应改变数值。这些断言尚未编译或执行。 + +断言: + +- 每个 Session 的真实客户端 registry 仅公告一个 `zwp_pointer_gestures_v1`,防止每个 seat 隐式创建协议导致重复;新增断言尚未执行。 + +- 在创建窗口前绑定三个 foreign-toplevel 协议,收到且仅收到自己的一个窗口和标题。 +- 在两个窗口存在后重新绑定,初始枚举仍只返回所属 Session 的窗口与标题。 +- Session 的窗口模型分别包含一个窗口,并持有不同的 Workspace、输入、输出、壁纸、切换器和窗口协议对象;设备 manager 的激活状态跟随所属 Session。 +- 各 Session 的 manager 初始只有三个 head,切换账户不会新增 head 或收到 head.finished;同一 A 连接在三次 A/B 往返切换后仍只有原来的三个 head。 +- A 修改系统缩放后 B 的现有 head 收到 scale 变更,后台协议快照同步系统状态,head 数量不增加。 +- A 的 UI 设置系统缩放为 1.5,A/B 读取同一个 OutputConfig,屏幕逻辑宽度相同;切换到 B 或恢复 A 后物理缩放一直是 1.5。窗口列表与任务栏专属区域仍独立。 +- 同一物理输出对应不同的 SessionOutput,两个面板各自贴底;专属区域分别为 40/60,切换时物理输出只发布当前用户的区域,恢复 A 后回到 40。 +- A 切换到第二工作区后激活 B,B 的当前工作区保持独立;恢复 A 后仍保留原选择。 +- B 使用 A 的私有 foreign-toplevel identifier 请求预览,真实预览回调不包含 A 窗口。identifier 在各 Session 内独立分配,重复数值可以合法指向 B 自己的窗口。 + +尚未覆盖:跨账户进程凭据验证、真实输入注入、屏幕配置、亮度和显示提交失败、 +持续捕获授权、XWayland 实际窗口以及日志退出压力测试。 + +```sh +cmake --preset ci +cmake --build --preset ci --target test_session_isolation +ctest --test-dir build --output-on-failure -R '^test_session_isolation$' +``` + +新增源码断言:每个连接仅看到一组 selection/data-control、IME 和 xdg-foreign globals;A/B 的逻辑 seat、native seat 和 IME helper 独立,切换后的活动 seat 与 Session 一致。这些新增检查尚未编译或执行。 + +桌面对象树回归:检查 A/B DesktopEnvironment、UI 根节点和 surface 集合独立;输入/输出管理器归所属桌面所有;DockPreview/已创建 TaskSwitcher 的 desktop 属性始终绑定所属桌面。新增断言未编译、未运行。 + +输入对象隔离断言:A/B SessionInputChannel、CompositorInputFilter、GestureManager、ShortcutController 均独立,逻辑 seat 的 eventFilter 固定绑定所属通道。新增检查尚未编译或执行;真实设备的跨切换按键/触摸/手势尾部验证仍待真机进行。 + +本轮新增快捷键隔离断言(未编译、未执行): + +- A/B 各可见且仅可见自己的一个 `treeland_shortcut_manager_v3` global,协议对象固定连接各自控制器。 +- 两个真实 C 客户端使用相同名称分别绑定 F9/F10,后台 B 的绑定立即进入自己的控制器,双方均不匹配对方按键。 +- 后台 B 对同一按键改名后解绑,不应恢复旧名称绑定,也不影响 A。 +- 激活 B 时两侧绑定保持不变;销毁 B 连接并恢复 A 后,A 的绑定仍然存在。 + +未覆盖:双用户同时捕获快捷键的事件流、捕获期间销毁或切换、真实设备输入序列代次隔离。 + +本轮新增窗口消失回归(未编译、未执行): + +- A/B 同 appId、同 instanceId 各自创建真实闪屏;关闭 B 的协议 resource 不移除 A 的闪屏。 +- 两条连接各自仅看见一个预启动和一个 appId 解析 manager。 +- 将 B 根 socket 停用后,经其子 socket 创建真实 xdg 窗口;B 激活后该窗口应恢复可见,切回 A 后 A 的同 appId 窗口仍存在且可见。 +- 停用根 socket 前先销毁直接测试连接,避免生产 freezer 向同进程测试客户端发送 SIGSTOP。 + +该用例使用实际 Wayland 子连接模拟 XWayland 的 socket 层级;未覆盖两个真实 XWayland 进程、 +解析器替换期间的完整应答、异步配置延迟期间注销、用户 UI 主动关闭闪屏后 real-window 的关闭事件流。 + +Session 展示域新增断言(未编译、未执行):停用用户的完整 surface 注册表,包括顶层 +窗口和 LayerShell,均应 renderingEnabled=false、visible=false、enabled=false,且有 +WSurfaceItem 的对象带 NonLive。后台创建、激活和切回也检查此约束。断言仅证明待执行 +用例的预期,不能替代真实渲染帧计数及输入事件投递测试。 + +捕获协议新增 registry 断言(未编译、未执行):四个上游捕获 manager 在 A/B 各只出现一次, +且 global name 不同,证明来自独立实例。窗口源解析固定使用所属 Session 的 toplevelList。 +此断言不覆盖实际像素读取、跨账户切换时已存在的输出捕获流停止,以及非法窗口源请求。 + +Socket 所有权新增断言(未编译、未执行):逻辑 seat 固定绑定所属 Session 根 socket, +拒绝未知客户端和另一 Session 的真实连接;后台子 socket 的客户端只属于其父 Session。 +Session 注销遵循先关闭客户端、再解除协议、最后销毁 socket 的顺序;注销路径尚未覆盖运行测试。 + +xdg-foreign 接口新增状态断言(未编译、未执行):每个 Session 的 exporter/importer +分别对应两个 WServerInterface 对象,绑定同一所属 socket,共享 native registry。 +配合现有 C registry 断言检查各连接仅看见自己的 exporter/importer global。 +尚未覆盖创建期间的广播、restart 以及 export/import token 的完整请求链路。 diff --git a/tests/protocols/session-isolation/appearance-isolation.c b/tests/protocols/session-isolation/appearance-isolation.c new file mode 100644 index 0000000000..f0d62d7f67 --- /dev/null +++ b/tests/protocols/session-isolation/appearance-isolation.c @@ -0,0 +1,71 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "appearance-isolation.h" +#include "client-connection.h" +#include "treeland-appearance-unstable-v1-client-protocol.h" +#include "treeland-appearance-manager-unstable-v1-client-protocol.h" + +struct appearance_state { unsigned font_events; uint32_t font_size; }; + +static void cursor_theme(void *data, struct treeland_appearance_v1 *appearance, const char *name) +{ (void)data; (void)appearance; (void)name; } +static void cursor_size(void *data, struct treeland_appearance_v1 *appearance, uint32_t width, uint32_t height) +{ (void)data; (void)appearance; (void)width; (void)height; } +static void font(void *data, struct treeland_appearance_v1 *appearance, const char *name) +{ (void)data; (void)appearance; (void)name; } +static void monospace_font(void *data, struct treeland_appearance_v1 *appearance, const char *name) +{ (void)data; (void)appearance; (void)name; } +static void font_size(void *data, struct treeland_appearance_v1 *appearance, uint32_t size) +{ (void)appearance; struct appearance_state *state = data; state->font_events++; state->font_size = size; } +static void icon_theme(void *data, struct treeland_appearance_v1 *appearance, const char *name) +{ (void)data; (void)appearance; (void)name; } +static void accent_color(void *data, struct treeland_appearance_v1 *appearance, uint32_t r, uint32_t g, uint32_t b) +{ (void)data; (void)appearance; (void)r; (void)g; (void)b; } +static void window_opacity(void *data, struct treeland_appearance_v1 *appearance, wl_fixed_t opacity) +{ (void)data; (void)appearance; (void)opacity; } +static void color_scheme(void *data, struct treeland_appearance_v1 *appearance, uint32_t scheme) +{ (void)data; (void)appearance; (void)scheme; } +static void titlebar_height(void *data, struct treeland_appearance_v1 *appearance, uint32_t height) +{ (void)data; (void)appearance; (void)height; } +static void corner_radius(void *data, struct treeland_appearance_v1 *appearance, uint32_t radius) +{ (void)data; (void)appearance; (void)radius; } + +static const struct treeland_appearance_v1_listener appearance_listener = { + cursor_theme, cursor_size, font, monospace_font, font_size, icon_theme, + accent_color, window_opacity, color_scheme, titlebar_height, corner_radius, +}; + +int session_test_appearance_isolation(struct client_connection *a, struct client_connection *b) +{ + struct appearance_state a_state = {0}, b_state = {0}; + struct treeland_appearance_v1 *a_events = client_bind(a, "treeland_appearance_v1", &treeland_appearance_v1_interface, 1); + struct treeland_appearance_v1 *b_events = client_bind(b, "treeland_appearance_v1", &treeland_appearance_v1_interface, 1); + struct treeland_appearance_manager_v1 *a_manager = client_bind(a, "treeland_appearance_manager_v1", &treeland_appearance_manager_v1_interface, 1); + struct treeland_appearance_manager_v1 *b_manager = client_bind(b, "treeland_appearance_manager_v1", &treeland_appearance_manager_v1_interface, 1); + int result = 1; + if (!a_events || !b_events || !a_manager || !b_manager) + goto cleanup; + treeland_appearance_v1_add_listener(a_events, &appearance_listener, &a_state); + treeland_appearance_v1_add_listener(b_events, &appearance_listener, &b_state); + if (wl_display_roundtrip(a->display) < 0 || wl_display_roundtrip(b->display) < 0 + || !a_state.font_events || !b_state.font_events) + goto cleanup; + const unsigned b_before = b_state.font_events; + const uint32_t b_size = b_state.font_size; + treeland_appearance_manager_v1_set_font_size(a_manager, 17); + if (wl_display_roundtrip(a->display) < 0 || wl_display_roundtrip(b->display) < 0 + || a_state.font_size != 17 || b_state.font_events != b_before || b_state.font_size != b_size) + goto cleanup; + const unsigned a_before = a_state.font_events; + treeland_appearance_manager_v1_set_font_size(b_manager, 22); + if (wl_display_roundtrip(b->display) < 0 || wl_display_roundtrip(a->display) < 0 + || b_state.font_size != 22 || a_state.font_events != a_before || a_state.font_size != 17) + goto cleanup; + result = 0; +cleanup: + if (a_manager) treeland_appearance_manager_v1_destroy(a_manager); + if (b_manager) treeland_appearance_manager_v1_destroy(b_manager); + if (a_events) treeland_appearance_v1_destroy(a_events); + if (b_events) treeland_appearance_v1_destroy(b_events); + return result; +} diff --git a/tests/protocols/session-isolation/appearance-isolation.h b/tests/protocols/session-isolation/appearance-isolation.h new file mode 100644 index 0000000000..4c5020e812 --- /dev/null +++ b/tests/protocols/session-isolation/appearance-isolation.h @@ -0,0 +1,5 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once +struct client_connection; +int session_test_appearance_isolation(struct client_connection *a, struct client_connection *b); diff --git a/tests/protocols/session-isolation/background-window.c b/tests/protocols/session-isolation/background-window.c new file mode 100644 index 0000000000..f5dcef520c --- /dev/null +++ b/tests/protocols/session-isolation/background-window.c @@ -0,0 +1,44 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "background-window.h" +#include "session-isolation.h" +#include "client-connection.h" +#include "xdg-toplevel-client.h" +#include "server-bridge-api.h" + +int session_test_background_window(void) +{ + struct isolation_state state = {0}; + struct client_connection client = {0}; + struct xdg_toplevel_client window = {0}; + int result = 1; + if (!invoke_on_server_thread(isolation_prepare_background, &state) || !state.ready) + goto cleanup; + if (!client_connect(&client, state.socket_name) || !xdg_toplevel_client_create(&client, &window)) + goto cleanup; + xdg_toplevel_set_app_id(window.toplevel, "org.deepin.session-same-app"); + if (wl_display_roundtrip(client.display) < 0 + || !invoke_on_server_thread(isolation_read, &state) + || state.a_windows != 1 || state.b_windows != 1 + || state.a_visible_windows != 1 || state.b_visible_windows != 0 + || !state.inactive_surfaces_stopped) + goto cleanup; + if (!invoke_on_server_thread(isolation_reactivate_b, NULL) + || wl_display_roundtrip(client.display) < 0 + || !invoke_on_server_thread(isolation_read, &state) + || state.a_windows != 1 || state.b_windows != 1 + || state.a_visible_windows != 0 || state.b_visible_windows != 1 + || !state.inactive_surfaces_stopped) + goto cleanup; + result = 0; +cleanup: + if (client.display) { + xdg_toplevel_client_destroy(&window); + client_disconnect(&client); + } + if (!invoke_on_server_thread(isolation_restore_a, NULL) + || !invoke_on_server_thread(isolation_read, &state) + || state.a_windows != 1 || state.a_visible_windows != 1) + result = 1; + return result; +} diff --git a/tests/protocols/session-isolation/background-window.h b/tests/protocols/session-isolation/background-window.h new file mode 100644 index 0000000000..41d3ee2f11 --- /dev/null +++ b/tests/protocols/session-isolation/background-window.h @@ -0,0 +1,4 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once +int session_test_background_window(void); diff --git a/tests/protocols/session-isolation/session-isolation.c b/tests/protocols/session-isolation/session-isolation.c new file mode 100644 index 0000000000..a1696e8ab1 --- /dev/null +++ b/tests/protocols/session-isolation/session-isolation.c @@ -0,0 +1,939 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#define _POSIX_C_SOURCE 200809L +#include "session-isolation.h" +#include "appearance-isolation.h" +#include "background-window.h" +#include "treeland-prelaunch-splash-unstable-v2-client-protocol.h" +#include "treeland-shortcut-manager-unstable-v3-client-protocol.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "treeland-foreign-toplevel-manager-unstable-v3-client-protocol.h" +#include "wlr-foreign-toplevel-management-unstable-v1-client-protocol.h" +#include "ext-foreign-toplevel-list-v1-client-protocol.h" + +#include "wlr-layer-shell-unstable-v1-client-protocol.h" +#include "wlr-output-management-unstable-v1-client-protocol.h" +#include +#include +#include +#include +#include +#include + +static void shortcut_activated(void *data, struct treeland_shortcut_manager_v3 *manager, + const char *name, uint32_t flags) +{ + (void)data; (void)manager; (void)name; (void)flags; +} + +static void shortcut_failure(void *data, struct treeland_shortcut_manager_v3 *manager, + const char *name, uint32_t error) +{ + (void)manager; (void)name; (void)error; + ++*(unsigned *)data; +} + +static const struct treeland_shortcut_manager_v3_listener shortcut_listener = { + .activated = shortcut_activated, + .bind_failure = shortcut_failure, +}; + +struct output_observer { + struct zwlr_output_head_v1 *head; + struct zwlr_output_mode_v1 *mode; + uint32_t serial; + int head_count; + int head_finished_count; + int manager_done_count; + int manager_finished_count; + int head_name_count; + int head_description_count; + int head_enabled_count; + int head_current_mode_count; + int head_position_count; + int head_transform_count; + int head_scale_count; + int head_adaptive_sync_count; + int mode_size_count; + int mode_refresh_count; + int mode_preferred_count; + int configuration_succeeded_count; + int configuration_failed_count; + int configuration_cancelled_count; + int position_x; + int position_y; +}; + +static const struct zwlr_output_mode_v1_listener mode_listener; + +static void head_name(void *data, struct zwlr_output_head_v1 *head, const char *name) +{ + (void)head; + (void)name; + ((struct output_observer *)data)->head_name_count++; +} + +static void head_description(void *data, struct zwlr_output_head_v1 *head, const char *description) +{ + (void)head; + (void)description; + ((struct output_observer *)data)->head_description_count++; +} + +static void head_physical_size(void *data, struct zwlr_output_head_v1 *head, int32_t width, int32_t height) +{ + (void)data; + (void)head; + (void)width; + (void)height; +} + +static void head_mode(void *data, struct zwlr_output_head_v1 *head, struct zwlr_output_mode_v1 *mode) +{ + (void)head; + struct output_observer *events = data; + events->mode = mode; + zwlr_output_mode_v1_add_listener(mode, &mode_listener, events); +} + +static void head_enabled(void *data, struct zwlr_output_head_v1 *head, int32_t enabled) +{ + (void)head; + (void)enabled; + ((struct output_observer *)data)->head_enabled_count++; +} + +static void head_current_mode(void *data, struct zwlr_output_head_v1 *head, struct zwlr_output_mode_v1 *mode) +{ + (void)head; + (void)mode; + ((struct output_observer *)data)->head_current_mode_count++; +} + +static void head_position(void *data, struct zwlr_output_head_v1 *head, int32_t x, int32_t y) +{ + (void)head; + struct output_observer *events = data; + events->position_x = x; + events->position_y = y; + events->head_position_count++; +} + +static void head_transform(void *data, struct zwlr_output_head_v1 *head, int32_t transform) +{ + (void)head; + (void)transform; + ((struct output_observer *)data)->head_transform_count++; +} + +static void head_scale(void *data, struct zwlr_output_head_v1 *head, wl_fixed_t scale) +{ + (void)head; + (void)scale; + ((struct output_observer *)data)->head_scale_count++; +} + +static void head_finished(void *data, struct zwlr_output_head_v1 *head) +{ + (void)head; + ((struct output_observer *)data)->head_finished_count++; +} + +static void head_make(void *data, struct zwlr_output_head_v1 *head, const char *make) +{ + (void)data; + (void)head; + (void)make; +} + +static void head_model(void *data, struct zwlr_output_head_v1 *head, const char *model) +{ + (void)data; + (void)head; + (void)model; +} + +static void head_serial_number(void *data, struct zwlr_output_head_v1 *head, const char *serial_number) +{ + (void)data; + (void)head; + (void)serial_number; +} + +static void head_adaptive_sync(void *data, struct zwlr_output_head_v1 *head, uint32_t state) +{ + (void)head; + (void)state; + ((struct output_observer *)data)->head_adaptive_sync_count++; +} + +static const struct zwlr_output_head_v1_listener head_listener = { + .name = head_name, + .description = head_description, + .physical_size = head_physical_size, + .mode = head_mode, + .enabled = head_enabled, + .current_mode = head_current_mode, + .position = head_position, + .transform = head_transform, + .scale = head_scale, + .finished = head_finished, + .make = head_make, + .model = head_model, + .serial_number = head_serial_number, + .adaptive_sync = head_adaptive_sync, +}; + +static void mode_size(void *data, struct zwlr_output_mode_v1 *mode, int32_t width, int32_t height) +{ + (void)mode; + (void)width; + (void)height; + ((struct output_observer *)data)->mode_size_count++; +} + +static void mode_refresh(void *data, struct zwlr_output_mode_v1 *mode, int32_t refresh) +{ + (void)mode; + (void)refresh; + ((struct output_observer *)data)->mode_refresh_count++; +} + +static void mode_preferred(void *data, struct zwlr_output_mode_v1 *mode) +{ + (void)mode; + ((struct output_observer *)data)->mode_preferred_count++; +} + +static void mode_finished(void *data, struct zwlr_output_mode_v1 *mode) +{ + (void)data; + (void)mode; +} + +static const struct zwlr_output_mode_v1_listener mode_listener = { + .size = mode_size, + .refresh = mode_refresh, + .preferred = mode_preferred, + .finished = mode_finished, +}; + +static void manager_head(void *data, struct zwlr_output_manager_v1 *manager, + struct zwlr_output_head_v1 *head) +{ + (void)manager; + struct output_observer *events = data; + events->head = head; + events->head_count++; + zwlr_output_head_v1_add_listener(head, &head_listener, events); +} + +static void manager_done(void *data, struct zwlr_output_manager_v1 *manager, uint32_t serial) +{ + (void)manager; + struct output_observer *events = data; + events->serial = serial; + events->manager_done_count++; +} + +static void manager_finished(void *data, struct zwlr_output_manager_v1 *manager) +{ + (void)manager; + ((struct output_observer *)data)->manager_finished_count++; +} + +static const struct zwlr_output_manager_v1_listener manager_listener = { + .head = manager_head, + .done = manager_done, + .finished = manager_finished, +}; + +static int has_one_scoped_global(const struct client_connection *connection, const char *interface) +{ + unsigned int count = 0; + for (uint32_t i = 0; i < connection->global_count; ++i) { + if (strcmp(connection->globals[i].interface, interface) == 0) + ++count; + } + return count == 1; +} + +static int has_own_shell_globals(const struct client_connection *connection) +{ + return has_one_scoped_global(connection, "treeland_prelaunch_splash_manager_v2") + && has_one_scoped_global(connection, "treeland_app_id_resolver_manager_v2") + && has_one_scoped_global(connection, "treeland_shortcut_manager_v3") + && has_one_scoped_global(connection, "xdg_wm_base") + && has_one_scoped_global(connection, "zwlr_layer_shell_v1") + && has_one_scoped_global(connection, "zxdg_decoration_manager_v1") + // personalization v1 实现删除时,本断言与全局注册一并移除或改写 + && has_one_scoped_global(connection, "treeland_personalization_manager_v1") + && has_one_scoped_global(connection, "treeland_appearance_v1") + && has_one_scoped_global(connection, "treeland_appearance_manager_v1") + && has_one_scoped_global(connection, "wl_data_device_manager") + && has_one_scoped_global(connection, "zwp_primary_selection_device_manager_v1") + && has_one_scoped_global(connection, "zwlr_data_control_manager_v1") + && has_one_scoped_global(connection, "ext_data_control_manager_v1") + && has_one_scoped_global(connection, "zwp_input_method_manager_v2") + && has_one_scoped_global(connection, "zwp_text_input_manager_v1") + && has_one_scoped_global(connection, "zwp_text_input_manager_v2") + && has_one_scoped_global(connection, "zwp_text_input_manager_v3") + && has_one_scoped_global(connection, "zwp_virtual_keyboard_manager_v1") + && has_one_scoped_global(connection, "zxdg_exporter_v2") + && has_one_scoped_global(connection, "zxdg_importer_v2") + && has_one_scoped_global(connection, "xdg_activation_v1"); +} + +static int has_independent_capture_globals(const struct client_connection *a, + const struct client_connection *b) +{ + static const char *interfaces[] = { + "zwlr_screencopy_manager_v1", + "ext_image_copy_capture_manager_v1", + "ext_output_image_capture_source_manager_v1", + "ext_foreign_toplevel_image_capture_source_manager_v1", + }; + for (unsigned i = 0; i < sizeof(interfaces) / sizeof(interfaces[0]); ++i) { + if (!has_one_scoped_global(a, interfaces[i]) || !has_one_scoped_global(b, interfaces[i])) + return 0; + uint32_t a_name = 0, b_name = 0; + for (uint32_t j = 0; j < a->global_count; ++j) { + if (strcmp(a->globals[j].interface, interfaces[i]) == 0) + a_name = a->globals[j].name; + } + for (uint32_t j = 0; j < b->global_count; ++j) { + if (strcmp(b->globals[j].interface, interfaces[i]) == 0) + b_name = b->globals[j].name; + } + if (!a_name || !b_name || a_name == b_name) + return 0; + } + return 1; +} + +struct panel { + struct zwlr_layer_shell_v1 *shell; + struct zwlr_layer_surface_v1 *layer; + struct wl_surface *surface; + struct wl_buffer *buffer; + uint32_t serial; +}; + +static void panel_configure(void *data, struct zwlr_layer_surface_v1 *layer, + uint32_t serial, uint32_t width, uint32_t height) +{ + (void)width; (void)height; + ((struct panel *)data)->serial = serial; + zwlr_layer_surface_v1_ack_configure(layer, serial); +} + +static void panel_closed(void *data, struct zwlr_layer_surface_v1 *layer) +{ + (void)data; (void)layer; +} + +static const struct zwlr_layer_surface_v1_listener panel_listener = { + .configure = panel_configure, .closed = panel_closed +}; + +static int panel_create(struct client_connection *connection, + struct xdg_toplevel_client *window, struct panel *panel, int height) +{ + panel->shell = client_bind(connection, "zwlr_layer_shell_v1", &zwlr_layer_shell_v1_interface, 1); + if (!panel->shell) + return 0; + panel->surface = wl_compositor_create_surface(window->compositor); + panel->layer = zwlr_layer_shell_v1_get_layer_surface(panel->shell, panel->surface, + NULL, ZWLR_LAYER_SHELL_V1_LAYER_TOP, "session-panel"); + zwlr_layer_surface_v1_add_listener(panel->layer, &panel_listener, panel); + zwlr_layer_surface_v1_set_size(panel->layer, 320, height); + zwlr_layer_surface_v1_set_anchor(panel->layer, ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM); + zwlr_layer_surface_v1_set_exclusive_zone(panel->layer, height); + wl_surface_commit(panel->surface); + if (wl_display_roundtrip(connection->display) < 0 || !panel->serial) + return 0; + char name[] = "/treeland-panel-XXXXXX"; + int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); + if (fd < 0) + return 0; + shm_unlink(name); + int size = 320 * height * 4; + if (ftruncate(fd, size) < 0) { close(fd); return 0; } + void *pixels = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (pixels == MAP_FAILED) { close(fd); return 0; } + memset(pixels, 0xff, size); + struct wl_shm_pool *pool = wl_shm_create_pool(window->shm, fd, size); + panel->buffer = wl_shm_pool_create_buffer(pool, 0, 320, height, 320 * 4, WL_SHM_FORMAT_ARGB8888); + wl_shm_pool_destroy(pool); + munmap(pixels, size); + close(fd); + wl_surface_attach(panel->surface, panel->buffer, 0, 0); + wl_surface_damage(panel->surface, 0, 0, 320, height); + wl_surface_commit(panel->surface); + return wl_display_roundtrip(connection->display) >= 0; +} + +static void panel_destroy(struct panel *panel) +{ + if (panel->layer) zwlr_layer_surface_v1_destroy(panel->layer); + if (panel->surface) wl_surface_destroy(panel->surface); + if (panel->buffer) wl_buffer_destroy(panel->buffer); + if (panel->shell) zwlr_layer_shell_v1_destroy(panel->shell); +} + +struct observer { + struct treeland_foreign_toplevel_manager_v3 *custom; + struct zwlr_foreign_toplevel_manager_v1 *wlr; + struct ext_foreign_toplevel_list_v1 *ext; + struct treeland_foreign_toplevel_handle_v3 *custom_handle; + struct zwlr_foreign_toplevel_handle_v1 *wlr_handle; + struct ext_foreign_toplevel_handle_v1 *ext_handle; + int custom_count; + int wlr_count; + int ext_count; + uint32_t identifier; + const char *expected_title; + unsigned int title_mask; + int leaked_title; +}; + +static void custom_title(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, const char *value) +{ + (void)handle; + struct observer *observer = data; + if (strcmp(value, "session-A") == 0 || strcmp(value, "session-B") == 0) { + if (strcmp(value, observer->expected_title) != 0) + observer->leaked_title = 1; + else + observer->title_mask |= 1; + } +} + +static void custom_app_id(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, const char *value) +{ + (void)handle; + (void)data; + (void)value; +} + +static void custom_pid(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, uint32_t value) +{ + (void)handle; + (void)data; + (void)value; +} + +static void custom_identifier(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, uint32_t value) +{ + (void)handle; + ((struct observer *)data)->identifier = value; +} + +static void custom_output_enter(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, struct wl_output *value) +{ + (void)handle; + (void)data; + (void)value; +} + +static void custom_output_leave(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, struct wl_output *value) +{ + (void)handle; + (void)data; + (void)value; +} + +static void custom_state(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, struct wl_array *value) +{ + (void)handle; + (void)data; + (void)value; +} + +static void custom_done(void *data, struct treeland_foreign_toplevel_handle_v3 *handle) +{ + (void)handle; + (void)data; +} + +static void custom_closed(void *data, struct treeland_foreign_toplevel_handle_v3 *handle) +{ + (void)handle; + (void)data; +} + +static void custom_parent(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, struct treeland_foreign_toplevel_handle_v3 *value) +{ + (void)handle; + (void)data; + (void)value; +} + +static const struct treeland_foreign_toplevel_handle_v3_listener custom_handle_listener = { + .title = custom_title, + .app_id = custom_app_id, + .pid = custom_pid, + .identifier = custom_identifier, + .output_enter = custom_output_enter, + .output_leave = custom_output_leave, + .state = custom_state, + .done = custom_done, + .closed = custom_closed, + .parent = custom_parent, +}; + +static void wlr_title(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, const char *value) +{ + (void)handle; + struct observer *observer = data; + if (strcmp(value, "session-A") == 0 || strcmp(value, "session-B") == 0) { + if (strcmp(value, observer->expected_title) != 0) + observer->leaked_title = 1; + else + observer->title_mask |= 2; + } +} + +static void wlr_app_id(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, const char *value) +{ + (void)handle; + (void)data; + (void)value; +} + +static void wlr_output_enter(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, struct wl_output *value) +{ + (void)handle; + (void)data; + (void)value; +} + +static void wlr_output_leave(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, struct wl_output *value) +{ + (void)handle; + (void)data; + (void)value; +} + +static void wlr_state(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, struct wl_array *value) +{ + (void)handle; + (void)data; + (void)value; +} + +static void wlr_done(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) +{ + (void)handle; + (void)data; +} + +static void wlr_closed(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) +{ + (void)handle; + (void)data; +} + +static void wlr_parent(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, struct zwlr_foreign_toplevel_handle_v1 *value) +{ + (void)handle; + (void)data; + (void)value; +} + +static const struct zwlr_foreign_toplevel_handle_v1_listener wlr_handle_listener = { + .title = wlr_title, + .app_id = wlr_app_id, + .output_enter = wlr_output_enter, + .output_leave = wlr_output_leave, + .state = wlr_state, + .done = wlr_done, + .closed = wlr_closed, + .parent = wlr_parent, +}; + +static void ext_closed(void *data, struct ext_foreign_toplevel_handle_v1 *handle) +{ + (void)handle; + (void)data; +} + +static void ext_done(void *data, struct ext_foreign_toplevel_handle_v1 *handle) +{ + (void)handle; + (void)data; +} + +static void ext_title(void *data, struct ext_foreign_toplevel_handle_v1 *handle, const char *value) +{ + (void)handle; + struct observer *observer = data; + if (strcmp(value, "session-A") == 0 || strcmp(value, "session-B") == 0) { + if (strcmp(value, observer->expected_title) != 0) + observer->leaked_title = 1; + else + observer->title_mask |= 4; + } +} + +static void ext_app_id(void *data, struct ext_foreign_toplevel_handle_v1 *handle, const char *value) +{ + (void)handle; + (void)data; + (void)value; +} + +static void ext_identifier(void *data, struct ext_foreign_toplevel_handle_v1 *handle, const char *value) +{ + (void)handle; + (void)data; + (void)value; +} + +static const struct ext_foreign_toplevel_handle_v1_listener ext_handle_listener = { + .closed = ext_closed, + .done = ext_done, + .title = ext_title, + .app_id = ext_app_id, + .identifier = ext_identifier, +}; + +static void custom_toplevel(void *data, struct treeland_foreign_toplevel_manager_v3 *manager, + struct treeland_foreign_toplevel_handle_v3 *handle) +{ + (void)manager; + struct observer *observer = data; + ++observer->custom_count; + observer->custom_handle = handle; + treeland_foreign_toplevel_handle_v3_add_listener(handle, &custom_handle_listener, observer); +} + +static void custom_finished(void *data, struct treeland_foreign_toplevel_manager_v3 *manager) +{ + (void)data; + (void)manager; +} + +static const struct treeland_foreign_toplevel_manager_v3_listener custom_listener = { + .toplevel = custom_toplevel, + .finished = custom_finished, +}; + +static void wlr_toplevel(void *data, struct zwlr_foreign_toplevel_manager_v1 *manager, + struct zwlr_foreign_toplevel_handle_v1 *handle) +{ + (void)manager; + struct observer *observer = data; + ++observer->wlr_count; + observer->wlr_handle = handle; + zwlr_foreign_toplevel_handle_v1_add_listener(handle, &wlr_handle_listener, observer); +} + +static void wlr_finished(void *data, struct zwlr_foreign_toplevel_manager_v1 *manager) +{ + (void)data; + (void)manager; +} + +static const struct zwlr_foreign_toplevel_manager_v1_listener wlr_listener = { + .toplevel = wlr_toplevel, + .finished = wlr_finished, +}; + +static void ext_toplevel(void *data, struct ext_foreign_toplevel_list_v1 *manager, + struct ext_foreign_toplevel_handle_v1 *handle) +{ + (void)manager; + struct observer *observer = data; + ++observer->ext_count; + observer->ext_handle = handle; + ext_foreign_toplevel_handle_v1_add_listener(handle, &ext_handle_listener, observer); +} + +static void ext_finished(void *data, struct ext_foreign_toplevel_list_v1 *manager) +{ + (void)data; + (void)manager; +} + +static const struct ext_foreign_toplevel_list_v1_listener ext_listener = { + .toplevel = ext_toplevel, + .finished = ext_finished, +}; + +static void preview_event(void *data, struct treeland_dock_preview_context_v3 *context) +{ + (void)data; + (void)context; +} + +static const struct treeland_dock_preview_context_v3_listener preview_listener = { + .enter = preview_event, + .leave = preview_event, +}; + +static int observe(struct client_connection *connection, struct observer *observer) +{ + observer->custom = client_bind(connection, "treeland_foreign_toplevel_manager_v3", + &treeland_foreign_toplevel_manager_v3_interface, 1); + observer->wlr = client_bind(connection, "zwlr_foreign_toplevel_manager_v1", + &zwlr_foreign_toplevel_manager_v1_interface, 1); + observer->ext = client_bind(connection, "ext_foreign_toplevel_list_v1", + &ext_foreign_toplevel_list_v1_interface, 1); + if (!observer->custom || !observer->wlr || !observer->ext) + return 0; + treeland_foreign_toplevel_manager_v3_add_listener(observer->custom, &custom_listener, observer); + zwlr_foreign_toplevel_manager_v1_add_listener(observer->wlr, &wlr_listener, observer); + ext_foreign_toplevel_list_v1_add_listener(observer->ext, &ext_listener, observer); + return wl_display_roundtrip(connection->display) >= 0; +} + +static int sees_one(const struct observer *observer) +{ + return observer->custom_count == 1 && observer->wlr_count == 1 && observer->ext_count == 1 + && observer->title_mask == 7 && !observer->leaked_title; +} + +#define REQUIRE(condition, name) do { \ + if (!(condition)) { fprintf(stderr, "FAIL: %s\n", name); goto cleanup; } \ + printf("PASS: %s\n", name); \ +} while (0) + +/* + * The shared scale is applied through a queued output commit, so one read right + * after the request still sees the previous hardware scale. Wait for the commit + * instead of asserting on it immediately. + */ +static int wait_for_shared_scale(struct isolation_state *state, double expected) +{ + for (int attempt = 0; attempt < 100; ++attempt) { + if (!invoke_on_server_thread(isolation_read, state)) + return 0; + if (state->a_scale == expected && state->b_scale == expected + && state->hardware_scale == expected) + return 1; + struct timespec delay = { 0, 20 * 1000 * 1000 }; + nanosleep(&delay, NULL); + } + return 0; +} + +static int test_prelaunch_isolation(struct client_connection *a, struct client_connection *b) +{ + struct treeland_prelaunch_splash_manager_v2 *am = client_bind(a, + "treeland_prelaunch_splash_manager_v2", &treeland_prelaunch_splash_manager_v2_interface, 1); + struct treeland_prelaunch_splash_manager_v2 *bm = client_bind(b, + "treeland_prelaunch_splash_manager_v2", &treeland_prelaunch_splash_manager_v2_interface, 1); + struct treeland_prelaunch_splash_v2 *as = NULL, *bs = NULL; + struct isolation_state state = {0}; + int result = 1; + if (!am || !bm) + goto cleanup; + as = treeland_prelaunch_splash_manager_v2_create_splash(am, + "org.deepin.session-launch-test", "same-instance", "", NULL); + bs = treeland_prelaunch_splash_manager_v2_create_splash(bm, + "org.deepin.session-launch-test", "same-instance", "", NULL); + if (!as || !bs || wl_display_roundtrip(a->display) < 0 || wl_display_roundtrip(b->display) < 0 + || !invoke_on_server_thread(isolation_read, &state) + || state.a_windows != 1 || state.b_windows != 1 || !state.independent_protocol_domains || !state.protocol_socket_ownership + || state.a_visible_windows != 1 || state.b_visible_windows != 0) + goto cleanup; + treeland_prelaunch_splash_v2_destroy(bs); + bs = NULL; + if (wl_display_roundtrip(b->display) < 0 + || !invoke_on_server_thread(isolation_read, &state) + || state.a_windows != 1 || state.b_windows != 0) + goto cleanup; + result = 0; +cleanup: + if (as) treeland_prelaunch_splash_v2_destroy(as); + if (bs) treeland_prelaunch_splash_v2_destroy(bs); + if (am) treeland_prelaunch_splash_manager_v2_destroy(am); + if (bm) treeland_prelaunch_splash_manager_v2_destroy(bm); + if (wl_display_roundtrip(a->display) < 0 || wl_display_roundtrip(b->display) < 0) + result = 1; + return result; +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection a = {0}, b = {0}; + struct xdg_toplevel_client a_window = {0}, b_window = {0}; + struct panel a_panel = {0}, b_panel = {0}; + struct observer a_live = {.expected_title = "session-A"}; + struct observer b_live = {.expected_title = "session-B"}; + struct observer a_late = {.expected_title = "session-A"}; + struct observer b_late = {.expected_title = "session-B"}; + struct isolation_state state = {0}; + struct treeland_dock_preview_context_v3 *preview = NULL; + int result = 1; + int switched = 0; + struct treeland_shortcut_manager_v3 *a_shortcuts = NULL, *b_shortcuts = NULL; + unsigned a_shortcut_failures = 0, b_shortcut_failures = 0; + struct zwlr_output_manager_v1 *a_outputs = NULL, *b_outputs = NULL; + struct output_observer a_heads = {0}, b_heads = {0}; + int b_scale_events_before = 0; + + REQUIRE(invoke_on_server_thread(isolation_read, &state), "read session fixture"); + if (!state.ready) { + fprintf(stderr, "SKIP: no second local account available\n"); + return 77; + } + REQUIRE(client_connect(&a, socket_name) && client_connect(&b, state.socket_name), + "connect two independent sessions"); + REQUIRE(test_prelaunch_isolation(&a, &b) == 0, + "same appId/instanceId splash requests and closure remain inside each Session"); + REQUIRE(observe(&a, &a_live) && observe(&b, &b_live), "bind before windows exist"); + REQUIRE(has_own_shell_globals(&a) && has_own_shell_globals(&b), + "each connection sees only its own shell and personalization globals"); + REQUIRE(has_one_scoped_global(&a, "zwp_pointer_gestures_v1") + && has_one_scoped_global(&b, "zwp_pointer_gestures_v1"), + "each Session sees exactly one pointer gestures global"); + REQUIRE(has_independent_capture_globals(&a, &b), + "each Session sees one distinct global for each upstream capture manager"); + REQUIRE(session_test_appearance_isolation(&a, &b) == 0, + "appearance requests and broadcasts stay inside the owning Session"); + a_shortcuts = client_bind(&a, "treeland_shortcut_manager_v3", &treeland_shortcut_manager_v3_interface, 1); + b_shortcuts = client_bind(&b, "treeland_shortcut_manager_v3", &treeland_shortcut_manager_v3_interface, 1); + REQUIRE(a_shortcuts && b_shortcuts, "bind independent shortcut managers"); + treeland_shortcut_manager_v3_add_listener(a_shortcuts, &shortcut_listener, &a_shortcut_failures); + treeland_shortcut_manager_v3_add_listener(b_shortcuts, &shortcut_listener, &b_shortcut_failures); + treeland_shortcut_manager_v3_acquire(a_shortcuts); + treeland_shortcut_manager_v3_acquire(b_shortcuts); + treeland_shortcut_manager_v3_bind_key(a_shortcuts, "shared-name", "F9", + TREELAND_SHORTCUT_MANAGER_V3_KEYBIND_FLAG_KEY_PRESS, TREELAND_SHORTCUT_MANAGER_V3_ACTION_NOTIFY); + treeland_shortcut_manager_v3_bind_key(b_shortcuts, "shared-name", "F10", + TREELAND_SHORTCUT_MANAGER_V3_KEYBIND_FLAG_KEY_PRESS, TREELAND_SHORTCUT_MANAGER_V3_ACTION_NOTIFY); + REQUIRE(wl_display_roundtrip(a.display) >= 0 && wl_display_roundtrip(b.display) >= 0 + && !a_shortcut_failures && !b_shortcut_failures + && invoke_on_server_thread(isolation_read, &state) + && state.a_shortcut && state.b_shortcut && !state.foreign_shortcut + && state.inactive_surfaces_stopped, + "inactive B binds immediately without changing A's shortcut"); + treeland_shortcut_manager_v3_bind_key(b_shortcuts, "renamed", "F10", + TREELAND_SHORTCUT_MANAGER_V3_KEYBIND_FLAG_KEY_PRESS, TREELAND_SHORTCUT_MANAGER_V3_ACTION_NOTIFY); + treeland_shortcut_manager_v3_unbind(b_shortcuts, "renamed"); + REQUIRE(wl_display_roundtrip(b.display) >= 0 && !b_shortcut_failures + && invoke_on_server_thread(isolation_read, &state) + && state.a_shortcut && !state.b_shortcut && !state.foreign_shortcut, + "inactive upsert followed by unbind leaves no stale binding"); + treeland_shortcut_manager_v3_bind_key(b_shortcuts, "shared-name", "F10", + TREELAND_SHORTCUT_MANAGER_V3_KEYBIND_FLAG_KEY_PRESS, TREELAND_SHORTCUT_MANAGER_V3_ACTION_NOTIFY); + REQUIRE(wl_display_roundtrip(b.display) >= 0 && !b_shortcut_failures, + "restore B's binding before activation"); + a_outputs = client_bind(&a, "zwlr_output_manager_v1", &zwlr_output_manager_v1_interface, 4); + b_outputs = client_bind(&b, "zwlr_output_manager_v1", &zwlr_output_manager_v1_interface, 4); + REQUIRE(a_outputs && b_outputs, "bind independent output managers"); + zwlr_output_manager_v1_add_listener(a_outputs, &manager_listener, &a_heads); + zwlr_output_manager_v1_add_listener(b_outputs, &manager_listener, &b_heads); + REQUIRE(wl_display_roundtrip(a.display) >= 0 && wl_display_roundtrip(b.display) >= 0 + && a_heads.head_count == 3 && b_heads.head_count == 3, + "each manager advertises the three connected screens exactly once"); + REQUIRE(xdg_toplevel_client_create(&a, &a_window) + && xdg_toplevel_client_create(&b, &b_window), "map one window in each session"); + xdg_toplevel_set_app_id(a_window.toplevel, "org.deepin.session-same-app"); + xdg_toplevel_set_app_id(b_window.toplevel, "org.deepin.session-same-app"); + xdg_toplevel_set_title(a_window.toplevel, "session-A"); + xdg_toplevel_set_title(b_window.toplevel, "session-B"); + REQUIRE(wl_display_roundtrip(a.display) >= 0 && wl_display_roundtrip(b.display) >= 0, + "synchronize both window streams"); + REQUIRE(sees_one(&a_live) && sees_one(&b_live), "live enumeration isolates all three protocols"); + REQUIRE(observe(&a, &a_late) && observe(&b, &b_late), "bind after both windows exist"); + REQUIRE(sees_one(&a_late) && sees_one(&b_late), "initial enumeration isolates all three protocols"); + REQUIRE(invoke_on_server_thread(isolation_read, &state) + && state.a_windows == 1 && state.b_windows == 1 && state.independent_workspaces + && state.independent_desktops && state.independent_managers && state.independent_protocol_domains + && state.independent_seats && state.protocol_socket_ownership && state.active_managers && state.inactive_surfaces_stopped, + "Session owns independent window models and workspaces"); + + b_scale_events_before = b_heads.head_scale_count; + REQUIRE(invoke_on_server_thread(isolation_scale_a, NULL) + && wl_display_roundtrip(a.display) >= 0 + && wait_for_shared_scale(&state, 1.5) + && state.b_logical_width == state.a_logical_width, + "system scale is shared while Session window models remain independent"); + REQUIRE(wl_display_roundtrip(b.display) >= 0 + && a_heads.head_count == 3 && b_heads.head_count == 3 + && b_heads.head_scale_count > b_scale_events_before, + "system scale change updates B's existing output protocol heads"); + + REQUIRE(panel_create(&a, &a_window, &a_panel, 40) + && panel_create(&b, &b_window, &b_panel, 60), "map panels in both sessions"); + REQUIRE(invoke_on_server_thread(isolation_read, &state) + && state.independent_outputs && state.a_bottom_zone == 40 && state.b_bottom_zone == 60 + && state.active_bottom_zone == 40 && state.a_panel_at_bottom && state.b_panel_at_bottom + && state.inactive_surfaces_stopped, + "logical outputs isolate panel placement and exclusive zones"); + + REQUIRE(invoke_on_server_thread(isolation_switch_b, NULL), "activate session B"); + switched = 1; + REQUIRE(invoke_on_server_thread(isolation_read, &state) + && state.a_current_workspace == 1 && state.b_current_workspace == 0 && state.active_managers + && state.a_shortcut && state.b_shortcut && !state.foreign_shortcut + && state.inactive_surfaces_stopped, + "switch preserves each session's workspace selection"); + REQUIRE(invoke_on_server_thread(isolation_read, &state) + && state.active_bottom_zone == 60 && state.a_bottom_zone == 40 + && state.b_bottom_zone == 60 && state.a_panel_at_bottom && state.b_panel_at_bottom, + "switch projects session B's exclusive zone without stacking panels"); + REQUIRE(wait_for_shared_scale(&state, 1.5) + && state.b_logical_width == state.a_logical_width, + "switch to B preserves the system scale and shared screen geometry"); + REQUIRE(wl_display_roundtrip(a.display) >= 0 && wl_display_roundtrip(b.display) >= 0 + && a_heads.head_count == 3 && b_heads.head_count == 3 + && !a_heads.head_finished_count && !b_heads.head_finished_count, + "account switch updates existing heads without adding or finishing screens"); + preview = treeland_foreign_toplevel_manager_v3_get_dock_preview_context(b_live.custom, b_window.surface); + treeland_dock_preview_context_v3_add_listener(preview, &preview_listener, NULL); + struct wl_array identifiers; + wl_array_init(&identifiers); + uint32_t *identifier = wl_array_add(&identifiers, sizeof(*identifier)); + if (!identifier) { wl_array_release(&identifiers); goto cleanup; } + *identifier = a_live.identifier; + treeland_dock_preview_context_v3_show(preview, &identifiers, 0, 0, + TREELAND_DOCK_PREVIEW_CONTEXT_V3_DIRECTION_BOTTOM); + wl_array_release(&identifiers); + REQUIRE(wl_display_roundtrip(b.display) >= 0 + && invoke_on_server_thread(isolation_read, &state) + && state.preview_requests == 1 && state.foreign_preview_surfaces == 0, + "guessed identifier from another session cannot preview a window"); + result = 0; + +cleanup: + if (preview) treeland_dock_preview_context_v3_destroy(preview); + if (b.display) { + panel_destroy(&b_panel); + xdg_toplevel_client_destroy(&b_window); + client_disconnect(&b); + } + if (switched) { + if (!invoke_on_server_thread(isolation_restore_a, NULL)) result = 1; + if (!invoke_on_server_thread(isolation_read, &state) + || state.a_current_workspace != 1 || state.active_bottom_zone != 40 || state.hardware_scale != 1.5 + || !state.a_shortcut || state.foreign_shortcut) result = 1; + if (result == 0 && session_test_background_window() != 0) { + fprintf(stderr, "FAIL: background child-socket window did not restore across users\n"); + result = 1; + } + if (result == 0) { + for (int i = 0; i < 3; ++i) { + if (!invoke_on_server_thread(isolation_reactivate_b, NULL) + || !invoke_on_server_thread(isolation_restore_a, NULL) + || wl_display_roundtrip(a.display) < 0 + || a_heads.head_count != 3 || a_heads.head_finished_count != 0) { + fprintf(stderr, "FAIL: repeated account switches grew the output head list\n"); + result = 1; + break; + } + } + } + } + if (a.display) { + panel_destroy(&a_panel); + xdg_toplevel_client_destroy(&a_window); + client_disconnect(&a); + } + return result; +} diff --git a/tests/protocols/session-isolation/session-isolation.h b/tests/protocols/session-isolation/session-isolation.h new file mode 100644 index 0000000000..880a03e894 --- /dev/null +++ b/tests/protocols/session-isolation/session-isolation.h @@ -0,0 +1,52 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +struct isolation_state { + char socket_name[512]; + int ready; + double a_scale; + double b_scale; + double hardware_scale; + int a_logical_width; + int b_logical_width; + int independent_outputs; + int a_bottom_zone; + int b_bottom_zone; + int active_bottom_zone; + int a_panel_at_bottom; + int b_panel_at_bottom; + int a_visible_windows; + int b_visible_windows; + int a_windows; + int b_windows; + int independent_workspaces; + int a_current_workspace; + int b_current_workspace; + int preview_surfaces; + int preview_requests; + int foreign_preview_surfaces; + int independent_seats; + int protocol_socket_ownership; + int independent_desktops; + int inactive_surfaces_stopped; + int independent_managers; + int independent_protocol_domains; + int active_managers; + int a_shortcut; + int b_shortcut; + int foreign_shortcut; +}; + +#ifdef __cplusplus +extern "C" { +#endif +void isolation_read(void *data); +void isolation_prepare_background(void *data); +void isolation_switch_b(void *data); +void isolation_scale_a(void *data); +void isolation_restore_a(void *data); +void isolation_reactivate_b(void *data); +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/session-isolation/setup.cpp b/tests/protocols/session-isolation/setup.cpp new file mode 100644 index 0000000000..19678787ec --- /dev/null +++ b/tests/protocols/session-isolation/setup.cpp @@ -0,0 +1,317 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "session-isolation.h" +#include "session/sessionmanager.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "core/shellhandler.h" +#include "modules/foreign-toplevel/foreigntoplevelmanagerv3.h" +#include "session/session.h" +#include "desktop/desktopenvironment.h" +#include "session/sessionprotocols.h" +#include "session/sessionprelaunch.h" +#include "session/sessionscene.h" +#include "modules/prelaunch-splash/prelaunchsplash.h" +#include "dconfig/dconfigmanager.h" +#include "appconfig.hpp" +#include "session/sessionseatmanager.h" +#include "session/sessioninputchannel.h" +#include "input/compositorinputfilter.h" +#include "modules/shortcut/shortcutmanager.h" +#include "seat/seatmanager.h" +#include +#include +#include "session/sessionoutputmanager.h" +#include "session/sessionswitcher.h" +#include "input/inputmanager.h" +#include "wallpaper/wallpapermanager.h" +#include "workspace/workspace.h" +#include "output/output.h" +#include "outputconfig.hpp" +#include +#include "core/rootsurfacecontainer.h" +#include "surface/surfacewrapper.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +std::shared_ptr sessionA; +std::shared_ptr sessionB; +int previewSurfaces = -1; +int previewRequests = 0; +int foreignPreviewSurfaces = 0; +QPointer backgroundSocket; + +// Observe production interface objects in addition to the C registry events. +bool hasIndependentForeignInterfaces(Session *owner) +{ + WServerInterface *exporter = nullptr; + WServerInterface *importer = nullptr; + for (auto *interface : WaylandServer::instance()->server()->interfaceList()) { + if (interface->ownsSocket() != owner->socket()) + continue; + if (interface->interfaceName() == "zxdg_exporter_v2") + exporter = interface; + else if (interface->interfaceName() == "zxdg_importer_v2") + importer = interface; + } + return exporter && importer && exporter != importer && exporter->handle() + && exporter->handle() == importer->handle(); +} +} + +void protocol_test_setup(WaylandServer *server) +{ + for (int i = server->backend()->outputList().size(); i < 3; ++i) + add_headless_output(server->backend(), false); + DConfigManager::instance()->appConfig(QStringLiteral("org.deepin.session-launch-test")); + sessionA = server->sessionManager()->globalSession(); + const auto *account = getpwuid(getuid()); + if (account && sessionA && sessionA->username() == QString::fromLocal8Bit(account->pw_name)) + account = getpwnam("nobody"); + if (!account || !sessionA) + return; + sessionB = server->sessionManager()->ensureSession( + QStringLiteral("protocol-session-isolation"), QString::fromLocal8Bit(account->pw_name)); + if (!sessionB || sessionA == sessionB) + return; + // Keep the background test connection dispatchable. Visibility/authorization + // still use the real Session identity, independently of socket suspension. + sessionB->socket()->setEnabled(true); + QObject::connect(sessionB->windowManagement(), + &ForeignToplevelManagerInterfaceV3::requestDockPreview, + server, [](auto surfaces, WSurface *, QPoint, auto) { + previewSurfaces = static_cast(surfaces.size()); + ++previewRequests; + for (auto *surface : surfaces) { + if (surface->session() != sessionB.get()) + ++foreignPreviewSurfaces; + } + }); +} + +extern "C" bool protocol_test_ready(WaylandServer *server) +{ + if (!sessionA || !sessionB) + return true; // The C client reports the missing-account skip. + if (server->rootSurfaceContainer()->outputs().size() != 3) + return false; + auto *launchConfig = DConfigManager::instance()->appConfig(QStringLiteral("org.deepin.session-launch-test")); + if (!configurationReady(launchConfig)) + return false; + auto *a = sessionA->outputManager()->protocol()->handle(); + auto *b = sessionB->outputManager()->protocol()->handle(); + return a && b && a != b && wl_list_length(&a->heads) == 3 && wl_list_length(&b->heads) == 3; +} + +namespace { +// A window of the fixture carries an app id (XDG toplevels and prelaunch splash +// wrappers alike); the Xwayland the compositor starts on its own registers +// wrappers without one, and those are not client windows. +int countClientWindows(Session *session, bool visibleOnly) +{ + int count = 0; + for (auto *window : session->windows()->objects()) { + if (window->appId().isEmpty()) + continue; + count += visibleOnly ? window->isVisible() : 1; + } + return count; +} +} + +extern "C" void isolation_read(void *data) +{ + auto *state = static_cast(data); + *state = {}; + if (!sessionA || !sessionB || sessionA == sessionB) + return; + const auto socket = sessionB->socket()->fullServerName().toUtf8(); + std::strncpy(state->socket_name, socket.constData(), sizeof(state->socket_name) - 1); + state->ready = 1; + if (auto *output = WaylandServer::instance()->rootSurfaceContainer()->primaryOutput()) { + auto *a = sessionA->outputManager()->outputState(output); + auto *b = sessionB->outputManager()->outputState(output); + state->independent_outputs = a != b && a->windows() != b->windows() + && a->minimizedSurfaces() != b->minimizedSurfaces() + && sessionA->outputManager()->config(output->getOutputId()) + == sessionB->outputManager()->config(output->getOutputId()); + state->a_scale = sessionA->outputManager()->config(output->getOutputId())->scale(); + state->b_scale = sessionB->outputManager()->config(output->getOutputId())->scale(); + state->hardware_scale = output->output()->scale(); + state->a_logical_width = a->geometry().width(); + state->b_logical_width = b->geometry().width(); + state->a_bottom_zone = a->exclusiveZone().bottom(); + state->b_bottom_zone = b->exclusiveZone().bottom(); + state->active_bottom_zone = output->exclusiveZone().bottom(); + const auto aLayers = a->layerSurfaces(); + const auto bLayers = b->layerSurfaces(); + state->a_panel_at_bottom = aLayers.size() == 1 + && qAbs(aLayers.first()->y() + aLayers.first()->height() - a->geometry().bottom()) < 1; + state->b_panel_at_bottom = bLayers.size() == 1 + && qAbs(bLayers.first()->y() + bLayers.first()->height() - b->geometry().bottom()) < 1; + } + state->inactive_surfaces_stopped = 1; + for (auto *owner : {sessionA.get(), sessionB.get()}) { + if (owner->isActive()) + continue; + for (auto *surface : owner->desktop()->surfaces()->objects()) { + // These fixtures contain ordinary user windows and panels only. + state->inactive_surfaces_stopped &= !surface->renderingEnabled() + && !surface->isVisible() && !surface->isEnabled() + && (!surface->surfaceItem() + || surface->surfaceItem()->flags().testFlag(WSurfaceItem::NonLive)); + } + } + state->a_visible_windows = countClientWindows(sessionA.get(), true); + state->b_visible_windows = countClientWindows(sessionB.get(), true); + state->a_windows = countClientWindows(sessionA.get(), false); + state->b_windows = countClientWindows(sessionB.get(), false); + state->independent_workspaces = sessionA->workspace() != sessionB->workspace(); + state->a_current_workspace = sessionA->workspace()->currentIndex(); + state->b_current_workspace = sessionB->workspace()->currentIndex(); + state->preview_surfaces = previewSurfaces; + state->preview_requests = previewRequests; + state->foreign_preview_surfaces = foreignPreviewSurfaces; + const auto *aProtocols = sessionA->protocols(); + const auto *bProtocols = sessionB->protocols(); + state->independent_protocol_domains = sessionA->prelaunch() != sessionB->prelaunch() + && sessionA->prelaunch()->protocol() != sessionB->prelaunch()->protocol() + && aProtocols != bProtocols + && aProtocols->xdgShell() != bProtocols->xdgShell() + && aProtocols->layerShell() != bProtocols->layerShell() + && aProtocols->xdgDecoration() != bProtocols->xdgDecoration() + && aProtocols->xdgDialog() != bProtocols->xdgDialog() + && aProtocols->xdgTags() != bProtocols->xdgTags() + // personalization v1 实现删除时,本访问器与断言一并移除 + && aProtocols->personalization() != bProtocols->personalization() + && aProtocols->decoration() != bProtocols->decoration() + && hasIndependentForeignInterfaces(sessionA.get()) + && hasIndependentForeignInterfaces(sessionB.get()); + auto *aSeat = sessionA->seatManager()->fallbackSeat(); + auto *bSeat = sessionB->seatManager()->fallbackSeat(); + state->independent_seats = aSeat && bSeat && aSeat != bSeat + && aSeat->handle() != bSeat->handle() + && sessionA->seatManager()->inputMethodHelper(aSeat) + != sessionB->seatManager()->inputMethodHelper(bSeat); + state->protocol_socket_ownership = aSeat && bSeat + && aSeat->ownsSocket() == sessionA->socket() + && bSeat->ownsSocket() == sessionB->socket(); + if (aSeat && bSeat) { + for (auto *client : sessionA->socket()->clients()) + state->protocol_socket_ownership &= aSeat->ownsClient(client) && !bSeat->ownsClient(client); + for (auto *client : sessionB->socket()->clients()) + state->protocol_socket_ownership &= bSeat->ownsClient(client) && !aSeat->ownsClient(client); + if (backgroundSocket) { + for (auto *client : backgroundSocket->clients()) + state->protocol_socket_ownership &= bSeat->ownsClient(client) && !aSeat->ownsClient(client); + } + } + const auto active = WaylandServer::instance()->sessionManager()->activeSessionObject(); + state->independent_seats = state->independent_seats && active + && WaylandServer::instance()->seat() == active->seatManager()->fallbackSeat(); + auto *aDesktop = sessionA->desktop(); + auto *bDesktop = sessionB->desktop(); + state->independent_desktops = sessionA->scene() != sessionB->scene() + && aDesktop && bDesktop && aDesktop != bDesktop + && aDesktop->viewRoot() != bDesktop->viewRoot() + && aDesktop->input()->parent() == aDesktop + && bDesktop->input()->parent() == bDesktop + && aDesktop->outputs()->parent() == aDesktop + && bDesktop->outputs()->parent() == bDesktop + && aDesktop->surfaces() != bDesktop->surfaces(); + auto *aInput = aDesktop->inputChannel(); + auto *bInput = bDesktop->inputChannel(); + state->independent_desktops = state->independent_desktops + && aInput != bInput && aInput->filter() != bInput->filter() + && aInput->gestures() != bInput->gestures() + && aInput->shortcuts() != bInput->shortcuts() + && aInput->shortcutProtocol() && bInput->shortcutProtocol() + && aInput->shortcutProtocol() != bInput->shortcutProtocol() + && aInput->shortcutProtocol()->controller() == aInput->shortcuts() + && bInput->shortcutProtocol()->controller() == bInput->shortcuts() + && aSeat->eventFilter() == aInput->filter() + && bSeat->eventFilter() == bInput->filter(); + const QKeyEvent f9(QEvent::KeyPress, Qt::Key_F9, Qt::NoModifier); + const QKeyEvent f10(QEvent::KeyPress, Qt::Key_F10, Qt::NoModifier); + state->a_shortcut = aInput->shortcuts()->matchesShortcut(&f9); + state->b_shortcut = bInput->shortcuts()->matchesShortcut(&f10); + state->foreign_shortcut = aInput->shortcuts()->matchesShortcut(&f10) + || bInput->shortcuts()->matchesShortcut(&f9); + state->independent_managers = sessionA->windowManagement() != sessionB->windowManagement() + && sessionA->inputManager() != sessionB->inputManager() + && sessionA->wallpaperManager() != sessionB->wallpaperManager() + && sessionA->outputManager() != sessionB->outputManager() + && sessionA->switcher() != sessionB->switcher(); + state->active_managers = sessionA->inputManager()->hardwareAttached() == sessionA->isActive() + && sessionB->inputManager()->hardwareAttached() == sessionB->isActive() + && sessionA->outputManager()->hardwareAttached() == sessionA->isActive() + && sessionB->outputManager()->hardwareAttached() == sessionB->isActive(); +} + +// Directed UI stimulus: exercise the production SessionOutputManager scale +// entry point used by OutputMenuBar, not a fabricated Wayland protocol result. +extern "C" void isolation_scale_a(void *) +{ + auto *output = WaylandServer::instance()->rootSurfaceContainer()->primaryOutput(); + if (output) + sessionA->outputManager()->setScale(output->output(), 1.5); +} + +extern "C" void isolation_switch_b(void *) +{ + sessionA->workspace()->createModel(QStringLiteral("session-A-second")); + sessionA->workspace()->switchTo(1, false); + WaylandServer::instance()->sessionManager()->updateActiveUserSession(sessionB->username(), sessionB->id()); + previewSurfaces = -1; + previewRequests = 0; + foreignPreviewSurfaces = 0; +} + +extern "C" void isolation_reactivate_b(void *) +{ + WaylandServer::instance()->sessionManager()->updateActiveUserSession(sessionB->username(), sessionB->id()); +} + +extern "C" void isolation_restore_a(void *) +{ + const auto clients = sessionB->socket()->clients(); + for (auto *client : clients) + wl_client_destroy(client->handle()); + WaylandServer::instance()->sessionManager()->updateActiveUserSession(sessionA->username(), sessionA->id()); + // Avoid process suspension when exercising both clients in one test process. + sessionB->socket()->setEnabled(true); +} + +// A real child connection models the socket hierarchy used by XWayland. +// Disable B only after its direct test clients were disconnected, so the +// in-process harness is never SIGSTOP'ed by the production socket freezer. +extern "C" void isolation_prepare_background(void *data) +{ + auto *state = static_cast(data); + *state = {}; + if (!sessionB->socket()->clients().isEmpty()) + return; + sessionA->workspace()->switchTo(0, false); + sessionB->socket()->setEnabled(false); + if (!backgroundSocket) { + auto *server = WaylandServer::instance(); + auto *socket = new WSocket(sessionB->socket(), server); + if (!socket->autoCreate()) { + delete socket; + return; + } + server->addSocket(socket); + backgroundSocket = socket; + } + const auto name = backgroundSocket->fullServerName().toUtf8(); + std::strncpy(state->socket_name, name.constData(), sizeof(state->socket_name) - 1); + state->ready = 1; +} diff --git a/tests/protocols/session-protocol-lifecycle/CMakeLists.txt b/tests/protocols/session-protocol-lifecycle/CMakeLists.txt new file mode 100644 index 0000000000..2f6e502b86 --- /dev/null +++ b/tests/protocols/session-protocol-lifecycle/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +treeland_add_protocol_test( + NAME session_protocol_lifecycle + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/session-protocol-lifecycle.c" +) diff --git a/tests/protocols/session-protocol-lifecycle/README.md b/tests/protocols/session-protocol-lifecycle/README.md new file mode 100644 index 0000000000..5ae769cf02 --- /dev/null +++ b/tests/protocols/session-protocol-lifecycle/README.md @@ -0,0 +1,28 @@ +# Session 协议销毁生命周期 + +新增回归测试代码,尚未完成编译、尚未运行,不代表已经验证通过。 + +复用真实 SessionManager 和 WServer,通过纯 C Wayland 客户端连接默认 Session +以及一个独立账户的 Session。没有可用的独立账户时返回 77;创建 Session 失败为失败。 + +实现的断言: + +- 真实客户端绑定 wl_data_device_manager 并创建 data source,使注销时存在客户端资源。 +- 对 screencopy 连续调用两次 Session::detachInterface,native destroy 仅触发一次, + 且接口已从 WServer 列表移除。 +- 移除 Session 且 fixture 仍保留额外共享引用时,六个带 destroy 信号的原生 manager、 + xdg-foreign manager 及其 registry 的八个 destroy 信号全部触发。 +- image-copy-capture 与 output-image-capture-source manager 没有 destroy 信号, + 只计入被观察接口数量;Session 注销时以 `destroy_global_safe == false` 立即销毁 + global,销毁后该指针即失效,测试不再读取它的 user data。 +- Session 接口均从 WServer 列表移除,所属客户端连接断开,另一个 Session 连接仍可 roundtrip。 +- 同一账户重复创建、注销两次,验证销毁后的重新创建路径。 + +本测试先保留额外 shared_ptr 验证显式 shutdown,再释放引用验证析构兜底。 +新增断言(尚未编译、执行):根与子 socket 各创建一个 mapped xdg-toplevel, +注销后两个窗口 wrapper 同步释放,两条连接的后续 commit 均无法完成 roundtrip; +重复 shutdown/removeSession 不重复销毁 manager。 +未覆盖真实 security-context 子连接、真实 XWayland 应用、GPU DMA-BUF、 +正在执行的捕获及剪贴板数据传输,也未覆盖完整 compositor stop/restart。 + +测试目标:`test_session_protocol_lifecycle`。执行结果需另行人工或 CI 确认。 diff --git a/tests/protocols/session-protocol-lifecycle/session-protocol-lifecycle.c b/tests/protocols/session-protocol-lifecycle/session-protocol-lifecycle.c new file mode 100644 index 0000000000..cb8eb57d4f --- /dev/null +++ b/tests/protocols/session-protocol-lifecycle/session-protocol-lifecycle.c @@ -0,0 +1,76 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "session-protocol-lifecycle.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" + +#include + +int protocol_test_run(const char *socket_name) +{ + struct client_connection survivor = {0}; + if (!client_connect(&survivor, socket_name)) + return 1; + + for (int cycle = 0; cycle < 2; ++cycle) { + struct lifecycle_state state = {0}; + if (!invoke_on_server_thread(lifecycle_prepare, &state)) + return 1; + if (state.ready <= 0) { + fprintf(stderr, "Session protocol lifecycle fixture unavailable\n"); + client_disconnect(&survivor); + return state.ready == 0 && cycle == 0 ? 77 : 1; + } + if (state.observed != 10) { + fprintf(stderr, "FAIL: expected ten native lifecycle observations, got %d\n", state.observed); + return 1; + } + struct client_connection departing = {0}; + if (!client_connect(&departing, state.socket_name)) + return 1; + struct client_connection child = {0}; + struct xdg_toplevel_client root_window = {0}, child_window = {0}; + if (!client_connect(&child, state.child_socket_name) + || !xdg_toplevel_client_create(&departing, &root_window) + || !xdg_toplevel_client_create(&child, &child_window)) + return 1; + struct wl_data_device_manager *manager = client_bind(&departing, + "wl_data_device_manager", &wl_data_device_manager_interface, 3); + if (!manager) + return 1; + struct wl_data_source *source = wl_data_device_manager_create_data_source(manager); + if (!source || wl_display_roundtrip(departing.display) < 0) + return 1; + + if (!invoke_on_server_thread(lifecycle_detach, &state) || !state.detached_once) { + fprintf(stderr, "FAIL: Session::detachInterface did not destroy exactly once\n"); + return 1; + } + if (!invoke_on_server_thread(lifecycle_remove, &state) + || state.destroyed != 8 || !state.interfaces_removed + || !state.shutdown_with_reference || !state.shutdown_idempotent + || state.mapped_windows != 2 || !state.windows_released) { + fprintf(stderr, "FAIL: Session teardown retained native managers or interfaces\n"); + return 1; + } + // A commit after logout must fail on both the root and descendant + // connection while an unrelated Session remains dispatchable. + wl_surface_commit(root_window.surface); + wl_surface_commit(child_window.surface); + if (wl_display_roundtrip(departing.display) >= 0 + || wl_display_roundtrip(child.display) >= 0 + || wl_display_roundtrip(survivor.display) < 0) { + fprintf(stderr, "FAIL: Session teardown disconnected the wrong client domain\n"); + return 1; + } + wl_data_source_destroy(source); + wl_data_device_manager_destroy(manager); + xdg_toplevel_client_destroy(&root_window); + xdg_toplevel_client_destroy(&child_window); + client_disconnect(&child); + client_disconnect(&departing); + } + client_disconnect(&survivor); + return 0; +} diff --git a/tests/protocols/session-protocol-lifecycle/session-protocol-lifecycle.h b/tests/protocols/session-protocol-lifecycle/session-protocol-lifecycle.h new file mode 100644 index 0000000000..cf37fa24c4 --- /dev/null +++ b/tests/protocols/session-protocol-lifecycle/session-protocol-lifecycle.h @@ -0,0 +1,27 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +struct lifecycle_state { + char socket_name[512]; + char child_socket_name[512]; + int ready; + int observed; + int destroyed; + int interfaces_removed; + int detached_once; + int shutdown_with_reference; + int shutdown_idempotent; + int mapped_windows; + int windows_released; +}; + +#ifdef __cplusplus +extern "C" { +#endif +void lifecycle_prepare(void *data); +void lifecycle_detach(void *data); +void lifecycle_remove(void *data); +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/session-protocol-lifecycle/setup.cpp b/tests/protocols/session-protocol-lifecycle/setup.cpp new file mode 100644 index 0000000000..c3f4a92b23 --- /dev/null +++ b/tests/protocols/session-protocol-lifecycle/setup.cpp @@ -0,0 +1,178 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "session-protocol-lifecycle.h" +#include "core/waylandserver.h" +#include "session/sessionmanager.h" +#include "session/session.h" +#include "workspace/workspace.h" +#include "surface/surfacewrapper.h" +#include "server-bridge.h" + +#include +#include +#include + +#include +#include +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +struct DestroyProbe { + wl_listener listener {}; + bool destroyed = false; + + explicit DestroyProbe(wl_signal *signal) + { + listener.notify = notify; + wl_signal_add(signal, &listener); + } + + ~DestroyProbe() + { + if (!destroyed) + wl_list_remove(&listener.link); + } + + static void notify(wl_listener *listener, void *) + { + DestroyProbe *probe = wl_container_of(listener, probe, listener); + probe->destroyed = true; + wl_list_remove(&listener->link); + } +}; + +std::shared_ptr owner; +QString username; +std::list probes; +int captureManagerCount = 0; +QList interfaces; +WServerInterface *screencopy = nullptr; +QPointer childSocket; + +void observe(WServerInterface *interface) +{ + const auto name = interface->interfaceName(); + if (name == "wl_data_device_manager") + probes.emplace_back(&interface->nativeInterface()->events.destroy); + else if (name == "zwp_primary_selection_device_manager_v1") + probes.emplace_back(&interface->nativeInterface()->events.destroy); + else if (name == "zwlr_data_control_manager_v1") + probes.emplace_back(&interface->nativeInterface()->events.destroy); + else if (name == "ext_data_control_manager_v1") + probes.emplace_back(&interface->nativeInterface()->events.destroy); + else if (name == "zwlr_screencopy_manager_v1") { + probes.emplace_back(&interface->nativeInterface()->events.destroy); + screencopy = interface; + } else if (name == "ext_image_copy_capture_manager_v1" + || name == "ext_output_image_capture_source_manager_v1") { + // These managers expose no destroy signal. Their global pointer is not + // kept: Session teardown destroys it immediately (destroy_global_safe + // == false), so reading it afterwards would touch freed memory. + ++captureManagerCount; + } else if (name == "ext_foreign_toplevel_image_capture_source_manager_v1") + probes.emplace_back(&interface->nativeInterface()->events.destroy); + else if (name == "zxdg_exporter_v2") { + auto *foreign = interface->nativeInterface(); + probes.emplace_back(&foreign->events.destroy); + probes.emplace_back(&foreign->registry->events.destroy); + } +} + +int destroyedCount() +{ + int count = 0; + for (const auto &probe : probes) + count += probe.destroyed; + return count; +} +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + const auto global = server->sessionManager()->globalSession(); + auto *account = getpwuid(getuid()); + if (account && global && global->username() == QString::fromLocal8Bit(account->pw_name)) + account = getpwnam("nobody"); + if (account) + username = QString::fromLocal8Bit(account->pw_name); +} + +extern "C" void lifecycle_prepare(void *data) +{ + auto *state = static_cast(data); + *state = {}; + if (username.isEmpty()) + return; + probes.clear(); + captureManagerCount = 0; + interfaces.clear(); + screencopy = nullptr; + auto *runtime = WaylandServer::instance(); + owner = runtime->sessionManager()->ensureSession(QStringLiteral("protocol-lifecycle"), username); + if (!owner) { + state->ready = -1; + return; + } + owner->socket()->setEnabled(true); + const auto name = owner->socket()->fullServerName().toUtf8(); + std::strncpy(state->socket_name, name.constData(), sizeof(state->socket_name) - 1); + for (auto *interface : runtime->server()->interfaceList()) { + if (interface->ownsSocket() == owner->socket()) { + interfaces.append(interface); + observe(interface); + } + } + childSocket = new WSocket(owner->socket()); + if (!childSocket->autoCreate()) { + state->ready = -1; + return; + } + runtime->addSocket(childSocket); + const auto childName = childSocket->fullServerName().toUtf8(); + std::strncpy(state->child_socket_name, childName.constData(), sizeof(state->child_socket_name) - 1); + state->observed = int(probes.size()) + captureManagerCount; + state->ready = 1; +} + +extern "C" void lifecycle_detach(void *data) +{ + auto *state = static_cast(data); + owner->detachInterface(screencopy); + owner->detachInterface(screencopy); + state->detached_once = destroyedCount() == 1 + && !WaylandServer::instance()->server()->interfaceList().contains(screencopy); +} + +extern "C" void lifecycle_remove(void *data) +{ + auto *state = static_cast(data); + auto *runtime = WaylandServer::instance(); + QList> windows; + for (auto *surface : owner->workspace()->surfaces()) + windows.append(surface); + state->mapped_windows = windows.size(); + // Intentionally retain owner: logout must complete independently of its + // shared_ptr lifetime, including destruction of mapped child-socket windows. + runtime->sessionManager()->removeSession(owner); + state->shutdown_with_reference = owner && owner->isShuttingDown() && !owner->socket(); + state->windows_released = 1; + for (const auto &window : windows) { + if (window) + state->windows_released = 0; + } + state->destroyed = destroyedCount(); + owner->shutdown(); + runtime->sessionManager()->removeSession(owner); + state->shutdown_idempotent = destroyedCount() == state->destroyed; + state->interfaces_removed = 1; + for (auto *interface : interfaces) { + if (runtime->server()->interfaceList().contains(interface)) + state->interfaces_removed = 0; + } + owner.reset(); + delete childSocket.data(); +} diff --git a/tests/protocols/treeland-active-notify-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-active-notify-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..891a7c2dcd --- /dev/null +++ b/tests/protocols/treeland-active-notify-unstable-v1/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_active_notify_unstable_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-active-notify-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-active-notify-unstable-v1.c" +) diff --git a/tests/protocols/treeland-active-notify-unstable-v1/README.md b/tests/protocols/treeland-active-notify-unstable-v1/README.md new file mode 100644 index 0000000000..245926926a --- /dev/null +++ b/tests/protocols/treeland-active-notify-unstable-v1/README.md @@ -0,0 +1,43 @@ +# `treeland-active-notify-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`treeland_active_notify_manager_v1` / `treeland_active_notify_v1` +- 测试源码:`tests/protocols/treeland-active-notify-unstable-v1/` +- Fixture:desktop integration fixture(`protocol_test_setup` 创建 headless output) +- 覆盖等级:**P**。 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | +| --- | --- | --- | +| Seat notifier 创建 | `get_active_notify(seat)` | notifier 创建成功,roundtrip 无 crash | +| 无真实输入时不发事件 | 挂 listener 后 roundtrip | 不收到 `activity_changed` / `drag_changed` | +| notifier 重建 | `destroy` 后再次 `get_active_notify(seat)` | 新 notifier 创建成功,无残留事件 | + +## 已证明的生产链路 + +基础用例证明协议接口的绑定和按 seat 创建 notifier 的路径正常。 + +客户端绑定 `treeland_active_notify_manager_v1` 后,`get_active_notify(seat)` 用真实 +`wl_seat` 创建 notifier。headless 环境中没有真实的指针按键、滚轮和拖放事件,因此挂上 +listener 后 roundtrip 不应收到任何事件;断言该边界可以捕获实现伪造事件的问题。 +`destroy` 后重建 notifier 验证管理器不依赖单例 notifier、可重复创建。 + +服务端实现位于 +`src/modules/active-notify/activenotifymanagerinterfacev1.h`、 +`activenotifymanagerinterfacev1.cpp`;生产事件来源为 `src/core/waylandserver.cpp` 的 +鼠标左键 / 滚轮跟踪(`handleLeftButtonStateChanged`、`handleWhellValueChanged`) +和拖放生命周期(`handleRequestDrag`、`handleRequestDragForSeat`)。 + +## 已知边界 / 下一项结果 + +- 真实输入驱动的事件路径(左键 active/inactive 配对、滚轮逐事件脉冲、 + started→dropped/cancelled 生命周期):尚未覆盖。后续应新建仅在 + `TREELAND_ENABLE_UINPUT_PROTOCOL_TESTS=ON` 时注册的 uinput E2E target。 +- 滚轮双轴抵消:`delta.x()+delta.y()==0`(如 x=-120、y=+120)时当前不发送事件, + 沿用 v1 的启发式;如需二维精确判断,应改为按事件主轴判定。 +- `get_active_notify(null)` 的协议错误:未覆盖(错误会杀死客户端连接,需要 + 连接级错误处理支持)。 +- 多 notifier / 多 seat:多个 notifier 同时监听同一 seat 或不同 seat 的行为未验证。 +- 与 v1 `treeland_dde_active_v1` 并行注册时的双发行为:未验证。 diff --git a/tests/protocols/treeland-active-notify-unstable-v1/setup.cpp b/tests/protocols/treeland-active-notify-unstable-v1/setup.cpp new file mode 100644 index 0000000000..c5091a35cf --- /dev/null +++ b/tests/protocols/treeland-active-notify-unstable-v1/setup.cpp @@ -0,0 +1,11 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "server-bridge.h" +#include "core/waylandserver.h" + +#include + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); +} diff --git a/tests/protocols/treeland-active-notify-unstable-v1/treeland-active-notify-unstable-v1.c b/tests/protocols/treeland-active-notify-unstable-v1/treeland-active-notify-unstable-v1.c new file mode 100644 index 0000000000..a41220be97 --- /dev/null +++ b/tests/protocols/treeland-active-notify-unstable-v1/treeland-active-notify-unstable-v1.c @@ -0,0 +1,127 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "client-connection.h" +#include "treeland-active-notify-unstable-v1-client-protocol.h" + +#include + +struct notify_state { + int activity_count; + int drag_count; + uint32_t last_reason; + uint32_t last_activity_state; + uint32_t last_drag_state; +}; + +static void handle_activity_changed(void *data, + struct treeland_active_notify_v1 *notify, + uint32_t reason, + uint32_t state) +{ + (void)notify; + struct notify_state *ns = data; + ns->activity_count++; + ns->last_reason = reason; + ns->last_activity_state = state; +} + +static void handle_drag_changed(void *data, + struct treeland_active_notify_v1 *notify, + uint32_t state) +{ + (void)notify; + struct notify_state *ns = data; + ns->drag_count++; + ns->last_drag_state = state; +} + +static const struct treeland_active_notify_v1_listener notify_listener = { + .activity_changed = handle_activity_changed, + .drag_changed = handle_drag_changed, +}; + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + if (!client_connect(&connection, socket_name)) + return 1; + + struct wl_seat *seat = client_bind(&connection, "wl_seat", + &wl_seat_interface, 1); + struct treeland_active_notify_manager_v1 *manager = + client_bind(&connection, "treeland_active_notify_manager_v1", + &treeland_active_notify_manager_v1_interface, 1); + if (!seat || !manager) { + fprintf(stderr, "active-notify: failed to bind globals\n"); + goto failed; + } + + { + struct notify_state ns = {0}; + + struct treeland_active_notify_v1 *notify = + treeland_active_notify_manager_v1_get_active_notify(manager, seat); + if (!notify) { + fprintf(stderr, "active-notify: get_active_notify(seat) failed\n"); + goto failed; + } + + treeland_active_notify_v1_add_listener(notify, ¬ify_listener, &ns); + if (wl_display_roundtrip(connection.display) == -1) { + fprintf(stderr, "active-notify: roundtrip failed (no-input check)\n"); + treeland_active_notify_v1_destroy(notify); + goto failed; + } + + if (ns.activity_count != 0 || ns.drag_count != 0) { + fprintf(stderr, + "active-notify: unexpected events without real input " + "(activity=%d, drag=%d)\n", + ns.activity_count, ns.drag_count); + treeland_active_notify_v1_destroy(notify); + goto failed; + } + + // Destroy and re-create the notifier for the same seat. + treeland_active_notify_v1_destroy(notify); + if (wl_display_roundtrip(connection.display) == -1) { + fprintf(stderr, "active-notify: roundtrip failed after destroy\n"); + goto failed; + } + + struct treeland_active_notify_v1 *notify2 = + treeland_active_notify_manager_v1_get_active_notify(manager, seat); + if (!notify2) { + fprintf(stderr, "active-notify: re-created get_active_notify(seat) failed\n"); + goto failed; + } + + struct notify_state ns2 = {0}; + treeland_active_notify_v1_add_listener(notify2, ¬ify_listener, &ns2); + if (wl_display_roundtrip(connection.display) == -1) { + fprintf(stderr, "active-notify: roundtrip failed (recreated notifier)\n"); + treeland_active_notify_v1_destroy(notify2); + goto failed; + } + + if (ns2.activity_count != 0 || ns2.drag_count != 0) { + fprintf(stderr, + "active-notify: unexpected events on re-created notifier " + "(activity=%d, drag=%d)\n", + ns2.activity_count, ns2.drag_count); + treeland_active_notify_v1_destroy(notify2); + goto failed; + } + + treeland_active_notify_v1_destroy(notify2); + } + + treeland_active_notify_manager_v1_destroy(manager); + wl_seat_destroy(seat); + client_disconnect(&connection); + return 0; + +failed: + client_disconnect(&connection); + return 1; +} diff --git a/tests/protocols/treeland-app-id-resolver-desktop-v2/CMakeLists.txt b/tests/protocols/treeland-app-id-resolver-desktop-v2/CMakeLists.txt new file mode 100644 index 0000000000..e58fb7f94c --- /dev/null +++ b/tests/protocols/treeland-app-id-resolver-desktop-v2/CMakeLists.txt @@ -0,0 +1,8 @@ + +treeland_add_protocol_test( + NAME treeland_app_id_resolver_desktop_v2 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-app-id-resolver-unstable-v2.xml" + EXTRA_XMLS "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-prelaunch-splash-unstable-v2.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-app-id-resolver-desktop-v2.c" +) diff --git a/tests/protocols/treeland-app-id-resolver-desktop-v2/setup.cpp b/tests/protocols/treeland-app-id-resolver-desktop-v2/setup.cpp new file mode 100644 index 0000000000..b9c0b77da8 --- /dev/null +++ b/tests/protocols/treeland-app-id-resolver-desktop-v2/setup.cpp @@ -0,0 +1,100 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "core/rootsurfacecontainer.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "surface/surfacecontainer.h" +#include "surface/surfacewrapper.h" +#include "treeland-app-id-resolver-desktop-v2.h" +#include "workspace/workspace.h" + +#include "treelandconfig.hpp" + +#include +#include +#include + +namespace { +constexpr auto TestAppId = "org.deepin.treeland.protocol.app-id-resolver"; + +QPointer g_splashWrapper; +bool g_splashConfigReady = false; + +bool isTestSplash(const SurfaceWrapper *wrapper) +{ + return wrapper && wrapper->type() == SurfaceWrapper::Type::SplashScreen + && wrapper->appId() == QLatin1String(TestAppId); +} + +void enablePrelaunchSplash(WaylandServer *server) +{ + server->globalConfig()->setEnablePrelaunchSplash(true); + g_splashConfigReady = true; +} +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + auto *config = server->globalConfig(); + if (config->isInitializeSucceeded()) { + enablePrelaunchSplash(server); + } else { + QObject::connect(config, + &TreelandConfig::configInitializeSucceed, + server, + [server](auto *) { enablePrelaunchSplash(server); }); + } + + QObject::connect(server->workspace(), + &SurfaceContainer::surfaceAdded, + server, + [](SurfaceWrapper *wrapper) { + if (isTestSplash(wrapper)) + g_splashWrapper = wrapper; + }); +} + +extern "C" bool protocol_test_ready(WaylandServer *server) +{ + return g_splashConfigReady && !server->rootSurfaceContainer()->outputs().isEmpty(); +} + +extern "C" void app_id_resolver_desktop_wait_for_splash(void *data) +{ + auto *created = static_cast(data); + *created = g_splashWrapper ? 1 : 0; + if (*created) + return; + + QEventLoop eventLoop; + QObject::connect(WaylandServer::instance()->workspace(), + &SurfaceContainer::surfaceAdded, + &eventLoop, + [&eventLoop, created](SurfaceWrapper *wrapper) { + if (isTestSplash(wrapper)) { + *created = 1; + eventLoop.quit(); + } + }); + eventLoop.exec(); +} + +extern "C" void app_id_resolver_desktop_read_state(void *data) +{ + app_id_resolver_desktop_state state {}; + auto *server = WaylandServer::instance(); + const auto surfaces = server->workspace()->surfaces(); + state.output_ready = !server->rootSurfaceContainer()->outputs().isEmpty() ? 1 : 0; + state.workspace_surface_count = surfaces.size(); + state.splash_created = g_splashWrapper ? 1 : 0; + if (g_splashWrapper) { + state.wrapper_in_workspace = surfaces.contains(g_splashWrapper) ? 1 : 0; + state.wrapper_converted_to_xdg = + g_splashWrapper->type() == SurfaceWrapper::Type::XdgToplevel ? 1 : 0; + state.wrapper_app_id_matches = + g_splashWrapper->appId() == QLatin1String(TestAppId) ? 1 : 0; + } + *static_cast(data) = state; +} diff --git a/tests/protocols/treeland-app-id-resolver-desktop-v2/treeland-app-id-resolver-desktop-v2.c b/tests/protocols/treeland-app-id-resolver-desktop-v2/treeland-app-id-resolver-desktop-v2.c new file mode 100644 index 0000000000..6f7fb6a7bc --- /dev/null +++ b/tests/protocols/treeland-app-id-resolver-desktop-v2/treeland-app-id-resolver-desktop-v2.c @@ -0,0 +1,131 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "treeland-app-id-resolver-desktop-v2.h" +#include "treeland-app-id-resolver-unstable-v2-client-protocol.h" +#include "treeland-prelaunch-splash-unstable-v2-client-protocol.h" + +#include +#include +#include +#include + +extern void app_id_resolver_desktop_wait_for_splash(void *data); +extern void app_id_resolver_desktop_read_state(void *data); + +static const char *const test_app_id = "org.deepin.treeland.protocol.app-id-resolver"; + +struct resolver_client_state { + int identify_received; + uint32_t request_id; + int pidfd; +}; + +static void identify_request(void *data, + struct treeland_app_id_resolver_v2 *resolver, + uint32_t request_id, + int32_t pidfd) +{ + (void)resolver; + struct resolver_client_state *state = data; + state->identify_received = 1; + state->request_id = request_id; + state->pidfd = pidfd; +} + +static const struct treeland_app_id_resolver_v2_listener resolver_listener = { + .identify_request = identify_request, +}; + +static int state_matches(const struct app_id_resolver_desktop_state *state) +{ + return state->output_ready && state->splash_created && state->wrapper_in_workspace + && state->wrapper_converted_to_xdg && state->wrapper_app_id_matches + && state->workspace_surface_count == 1; +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + struct xdg_toplevel_client toplevel = { 0 }; + struct resolver_client_state resolver_state = { .pidfd = -1 }; + struct app_id_resolver_desktop_state state = { 0 }; + struct treeland_app_id_resolver_manager_v2 *resolver_manager = NULL; + struct treeland_app_id_resolver_v2 *resolver = NULL; + struct treeland_prelaunch_splash_manager_v2 *splash_manager = NULL; + struct treeland_prelaunch_splash_v2 *splash = NULL; + int splash_created = 0; + int result = 1; + + if (!client_connect(&connection, socket_name)) + goto done; + resolver_manager = client_bind(&connection, + "treeland_app_id_resolver_manager_v2", + &treeland_app_id_resolver_manager_v2_interface, + 1); + splash_manager = client_bind(&connection, + "treeland_prelaunch_splash_manager_v2", + &treeland_prelaunch_splash_manager_v2_interface, + 2); + if (!resolver_manager || !splash_manager) + goto done; + + resolver = treeland_app_id_resolver_manager_v2_get_resolver(resolver_manager); + if (!resolver + || treeland_app_id_resolver_v2_add_listener(resolver, &resolver_listener, &resolver_state)) + goto done; + + splash = treeland_prelaunch_splash_manager_v2_create_splash( + splash_manager, test_app_id, "resolver-instance", "org.deepin.Sandbox", NULL); + if (!splash || wl_display_roundtrip(connection.display) < 0 + || !invoke_on_server_thread(app_id_resolver_desktop_wait_for_splash, &splash_created) + || !splash_created) + goto done; + + if (!xdg_toplevel_client_create_pending(&connection, &toplevel) + || wl_display_roundtrip(connection.display) < 0 + || !resolver_state.identify_received || resolver_state.request_id == 0 + || resolver_state.pidfd < 0) + goto done; + + treeland_app_id_resolver_v2_respond(resolver, + resolver_state.request_id, + test_app_id, + "org.deepin.Sandbox"); + if (!xdg_toplevel_client_complete_map(&connection, &toplevel) + || !invoke_on_server_thread(app_id_resolver_desktop_read_state, &state) + || !state_matches(&state)) + goto done; + + result = 0; +done: + if (result != 0) { + fprintf(stderr, + "app-id resolver desktop failed: identify=(received=%d id=%u pidfd=%d) " + "wrapper=(splash=%d workspace=%d xdg=%d app-id=%d count=%d output=%d)\n", + resolver_state.identify_received, + resolver_state.request_id, + resolver_state.pidfd, + state.splash_created, + state.wrapper_in_workspace, + state.wrapper_converted_to_xdg, + state.wrapper_app_id_matches, + state.workspace_surface_count, + state.output_ready); + } + if (resolver_state.pidfd >= 0) + close(resolver_state.pidfd); + xdg_toplevel_client_destroy(&toplevel); + if (splash) + treeland_prelaunch_splash_v2_destroy(splash); + if (resolver) + treeland_app_id_resolver_v2_destroy(resolver); + if (splash_manager) + treeland_prelaunch_splash_manager_v2_destroy(splash_manager); + if (resolver_manager) + treeland_app_id_resolver_manager_v2_destroy(resolver_manager); + client_disconnect(&connection); + return result; +} diff --git a/tests/protocols/treeland-app-id-resolver-desktop-v2/treeland-app-id-resolver-desktop-v2.h b/tests/protocols/treeland-app-id-resolver-desktop-v2/treeland-app-id-resolver-desktop-v2.h new file mode 100644 index 0000000000..bdc1d06031 --- /dev/null +++ b/tests/protocols/treeland-app-id-resolver-desktop-v2/treeland-app-id-resolver-desktop-v2.h @@ -0,0 +1,23 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +struct app_id_resolver_desktop_state { + int output_ready; + int splash_created; + int wrapper_in_workspace; + int wrapper_converted_to_xdg; + int wrapper_app_id_matches; + int workspace_surface_count; +}; + +int protocol_test_run(const char *socket_name); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/treeland-app-id-resolver-v2/CMakeLists.txt b/tests/protocols/treeland-app-id-resolver-v2/CMakeLists.txt new file mode 100644 index 0000000000..46d3c05737 --- /dev/null +++ b/tests/protocols/treeland-app-id-resolver-v2/CMakeLists.txt @@ -0,0 +1,7 @@ + +treeland_add_protocol_test( + NAME treeland_app_id_resolver_v2 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-app-id-resolver-unstable-v2.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-app-id-resolver-v2.c" +) diff --git a/tests/protocols/treeland-app-id-resolver-v2/README.md b/tests/protocols/treeland-app-id-resolver-v2/README.md new file mode 100644 index 0000000000..c52743a77b --- /dev/null +++ b/tests/protocols/treeland-app-id-resolver-v2/README.md @@ -0,0 +1,68 @@ +# `treeland-app-id-resolver-v2` 测试规范 + +## 范围 + +- 协议/资源级测试:`tests/protocols/treeland-app-id-resolver-v2/`。 +- 覆盖等级:**P / E**。 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | +| --- | --- | --- | +| 创建 resolver | `get_resolver` | 创建可用 resolver 资源 | +| 正常解析 | 对真实 pidfd 的 `identify` 应答 | 生产回调启动、收到应答并记录 app-id | +| 空解析 | 以空 app-id 应答 | 生产回调记录空结果 | +| 无效应答 | 在请求失效后应答 | manager 发送规定的协议错误 | + +## 已证明的生产链路(E) + +桌面测试启动真实 `WaylandServer`、`ShellHandler`、`Workspace` 和 headless output。它先用 +同一 Wayland 客户端创建 app-id 为 +`org.deepin.treeland.protocol.app-id-resolver` 的 prelaunch splash,确认生产 +`SurfaceWrapper` 已加入 workspace;这满足 `ShellHandler` 对随后 xdg toplevel 走 +app-id resolver 异步路径的业务前提。 + +随后客户端先创建并提交**未配置**的 xdg toplevel。此时生产端从该 xdg 客户端的 +credentials 取得 pidfd,并通过 app-id-resolver 向同一客户端发送 +`identify_request(request_id, pidfd)`。测试确认收到非零 request id 和有效 pidfd, +再响应: + +```text +respond(request_id, + "org.deepin.treeland.protocol.app-id-resolver", + "org.deepin.Sandbox") +``` + +这个两阶段顺序是协议语义的一部分:在 resolver 回包前,`ShellHandler` 有意延后 +xdg wrapper 创建,因此测试不会错误地以固定时延或过早的 `xdg_surface.configure` +要求代替 resolver 结果。 + +生产调用链如下: + +```text +xdg toplevel(真实客户端 pidfd) + → ShellHandler::onXdgToplevelSurfaceAdded + → AppIdResolverManager::resolvePidfd + → identify_request / respond + → ShellHandler::ensureXdgWrapper(surface, appId) + → 原 SplashScreen SurfaceWrapper::convertToNormalSurface +``` + +| 阶段 | 客户端动作 | 必须观察到的生产业务结果 | +| --- | --- | --- | +| resolver 请求 | 提交 pending xdg toplevel | 收到针对该真实客户端的 `identify_request` 与 pidfd | +| resolver 应答 | 以测试 app-id 调用 `respond` | 生产端允许 xdg surface 获得 configure,并完成 map | +| wrapper 转换 | 读取先前记录的 splash wrapper | **同一** wrapper 的类型从 `SplashScreen` 变为 `XdgToplevel` | +| app-id 写入 | 查询生产 wrapper | `wrapper.appId()` 等于 responder 返回的 app-id | +| workspace 连续性 | 查询 `Workspace::surfaces()` | 转换后的 wrapper 仍在 workspace,且只有这一个测试窗口对象 | + +## 生产结果 + +基础测试证明请求/应答和 pidfd 传输进入生产 resolver 模块。桌面测试进一步证明 +resolver 的返回值驱动了实际窗口 wrapper 的创建/转换与 app-id 写入。 + +## 已知边界 / 下一项结果 + +当前 resolver client 仍是测试客户端,而非外部真实应用进程;但它使用真实 Wayland +连接、真实 pidfd 和生产 `ShellHandler`。尚未覆盖 sandbox 名称在后续策略中的使用、 +resolver 断开时 pending xdg 的空 app-id fallback,以及 XWayland 路径。 diff --git a/tests/protocols/treeland-app-id-resolver-v2/setup.cpp b/tests/protocols/treeland-app-id-resolver-v2/setup.cpp new file mode 100644 index 0000000000..ed904c6951 --- /dev/null +++ b/tests/protocols/treeland-app-id-resolver-v2/setup.cpp @@ -0,0 +1,62 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "modules/app-id-resolver/appidresolver.h" +#include "server-bridge.h" + +#include + +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +AppIdResolverManager *g_manager = nullptr; +} + +extern "C" { + +struct app_id_resolver_test_state { + int resolve_started; + int resolve_matched; + int resolve_empty; +}; + +struct app_id_resolver_test_state g_app_id_resolver_state; +struct app_id_resolver_test_state g_app_id_resolver_snapshot; + +void server_start_resolve(void *) +{ + g_app_id_resolver_state.resolve_started = 0; + g_app_id_resolver_state.resolve_matched = 0; + g_app_id_resolver_state.resolve_empty = 0; + + if (!g_manager) + return; + + const int pidfd = static_cast(syscall(SYS_pidfd_open, static_cast(getpid()), 0)); + if (pidfd < 0) + return; + + const bool started = g_manager->resolvePidfd(pidfd, [](const QString &appId) { + g_app_id_resolver_state.resolve_matched = + (appId == QStringLiteral("org.deepin.dde.test-app")) ? 1 : 0; + g_app_id_resolver_state.resolve_empty = appId.isEmpty() ? 1 : 0; + }); + close(pidfd); + g_app_id_resolver_state.resolve_started = started ? 1 : 0; +} + +void server_snapshot_state(void *) +{ + g_app_id_resolver_snapshot = g_app_id_resolver_state; +} + +} // extern "C" + +void protocol_test_setup(WaylandServer *server) +{ + g_manager = find_server_interface(server); +} diff --git a/tests/protocols/treeland-app-id-resolver-v2/treeland-app-id-resolver-v2.c b/tests/protocols/treeland-app-id-resolver-v2/treeland-app-id-resolver-v2.c new file mode 100644 index 0000000000..7b0942ae45 --- /dev/null +++ b/tests/protocols/treeland-app-id-resolver-v2/treeland-app-id-resolver-v2.c @@ -0,0 +1,274 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-app-id-resolver-v2.h" +#include "server-bridge-api.h" +#include "treeland-app-id-resolver-unstable-v2-client-protocol.h" + +#include +#include +#include +#include +#include +#include +#include + +#define EXPECTED_APP_ID "org.deepin.dde.test-app" +#define EXPECTED_SANDBOX "test-sandbox" + +struct app_id_resolver_test_state { + int resolve_started; + int resolve_matched; + int resolve_empty; +}; + +extern struct app_id_resolver_test_state g_app_id_resolver_snapshot; +extern void server_start_resolve(void *data); +extern void server_snapshot_state(void *data); + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); +}; + +void test_init(struct test_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); + ctx->identify_pidfd = -1; + ctx->result_cap = 32; + ctx->results = calloc(ctx->result_cap, sizeof(*ctx->results)); +} + +void test_destroy(struct test_ctx *ctx) +{ + free(ctx->results); + memset(ctx, 0, sizeof(*ctx)); +} + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +void test_pass(struct test_ctx *ctx, int index) +{ + ctx->results[index].failed = 0; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +static void identify_request(void *data, struct treeland_app_id_resolver_v2 *resolver, + uint32_t request_id, int32_t pidfd) +{ + (void)resolver; + struct test_ctx *ctx = data; + ctx->identify_received = 1; + ctx->identify_request_id = request_id; + ctx->identify_pidfd = pidfd; +} + +static const struct treeland_app_id_resolver_v2_listener resolver_listener = { + .identify_request = identify_request, +}; + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->display = ctx->connection.display; + ctx->manager = client_bind(&ctx->connection, "treeland_app_id_resolver_manager_v2", + &treeland_app_id_resolver_manager_v2_interface, 1); + return ctx->manager != NULL; +} + +static int pidfd_refers_to_self(int pidfd) +{ + char path[64]; + char line[128]; + snprintf(path, sizeof(path), "/proc/self/fdinfo/%d", pidfd); + FILE *file = fopen(path, "r"); + if (!file) + return 0; + int target_pid = -1; + while (fgets(line, sizeof(line), file)) { + if (sscanf(line, "Pid:\t%d", &target_pid) == 1) + break; + } + fclose(file); + return target_pid == (int)getpid(); +} + +static int resolve_without_resolver_fails(struct test_ctx *ctx) +{ + (void)ctx; + if (!invoke_on_server_thread(server_start_resolve, NULL)) + return 0; + if (!invoke_on_server_thread(server_snapshot_state, NULL)) + return 0; + return g_app_id_resolver_snapshot.resolve_started == 0; +} + +static int get_resolver_creates_object(struct test_ctx *ctx) +{ + ctx->resolver = treeland_app_id_resolver_manager_v2_get_resolver(ctx->manager); + if (!ctx->resolver) + return 0; + return treeland_app_id_resolver_v2_add_listener(ctx->resolver, &resolver_listener, ctx) == 0; +} + +static int resolve_roundtrip(struct test_ctx *ctx) +{ + ctx->identify_received = 0; + ctx->identify_pidfd = -1; + if (!invoke_on_server_thread(server_start_resolve, NULL)) + return 0; + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + + const int pidfd_ok = ctx->identify_received + && ctx->identify_request_id == 1 + && ctx->identify_pidfd >= 0 + && fcntl(ctx->identify_pidfd, F_GETFD) >= 0 + && pidfd_refers_to_self(ctx->identify_pidfd); + if (ctx->identify_pidfd >= 0) { + close(ctx->identify_pidfd); + ctx->identify_pidfd = -1; + } + if (!pidfd_ok) + return 0; + + treeland_app_id_resolver_v2_respond(ctx->resolver, ctx->identify_request_id, + EXPECTED_APP_ID, EXPECTED_SANDBOX); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + if (!invoke_on_server_thread(server_snapshot_state, NULL)) + return 0; + return g_app_id_resolver_snapshot.resolve_started == 1 + && g_app_id_resolver_snapshot.resolve_matched == 1; +} + +static int second_resolve_empty_response(struct test_ctx *ctx) +{ + ctx->identify_received = 0; + ctx->identify_pidfd = -1; + if (!invoke_on_server_thread(server_start_resolve, NULL)) + return 0; + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + + const int pidfd_ok = ctx->identify_received + && ctx->identify_request_id == 2 + && ctx->identify_pidfd >= 0 + && fcntl(ctx->identify_pidfd, F_GETFD) >= 0; + if (ctx->identify_pidfd >= 0) { + close(ctx->identify_pidfd); + ctx->identify_pidfd = -1; + } + if (!pidfd_ok) + return 0; + + treeland_app_id_resolver_v2_respond(ctx->resolver, ctx->identify_request_id, "", + EXPECTED_SANDBOX); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + if (!invoke_on_server_thread(server_snapshot_state, NULL)) + return 0; + return g_app_id_resolver_snapshot.resolve_started == 1 + && g_app_id_resolver_snapshot.resolve_empty == 1; +} + +static int duplicate_get_resolver_errors(struct test_ctx *ctx) +{ + + ctx->display_errored = 1; + + (void)treeland_app_id_resolver_manager_v2_get_resolver(ctx->manager); + + if (wl_display_roundtrip(ctx->display) >= 0) + return 0; + if (wl_display_get_error(ctx->display) != EPROTO) + return 0; + + const struct wl_interface *error_interface = NULL; + uint32_t error_id = 0; + const uint32_t code = wl_display_get_protocol_error(ctx->display, &error_interface, &error_id); + if (code != WL_DISPLAY_ERROR_INVALID_OBJECT) + return 0; + if (error_interface != &treeland_app_id_resolver_manager_v2_interface) + return 0; + if (error_id != wl_proxy_get_id((struct wl_proxy *)ctx->manager)) + return 0; + return 1; +} + +static const struct test_case cases[] = { + { "resolve_without_resolver_fails", resolve_without_resolver_fails }, + { "get_resolver_creates_object", get_resolver_creates_object }, + { "resolve_roundtrip", resolve_roundtrip }, + { "second_resolve_empty_response", second_resolve_empty_response }, + { "duplicate_get_resolver_errors", duplicate_get_resolver_errors }, +}; + +void test_cleanup(struct test_ctx *ctx) +{ + if (ctx->resolver) + treeland_app_id_resolver_v2_destroy(ctx->resolver); + if (ctx->manager) + treeland_app_id_resolver_manager_v2_destroy(ctx->manager); + client_disconnect(&ctx->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx; + test_init(&ctx); + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect to or bind treeland_app_id_resolver_manager_v2\n"); + test_cleanup(&ctx); + test_destroy(&ctx); + return 1; + } + + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const int result = test_add(&ctx, cases[i].name); + if (!cases[i].run(&ctx)) + test_fail(&ctx, result, "assertion failed"); + if (ctx.display_errored) + continue; + if (wl_display_roundtrip(ctx.display) < 0) + test_fail(&ctx, result, "Wayland connection failed"); + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + test_destroy(&ctx); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-app-id-resolver-v2/treeland-app-id-resolver-v2.h b/tests/protocols/treeland-app-id-resolver-v2/treeland-app-id-resolver-v2.h new file mode 100644 index 0000000000..18d4bd79b9 --- /dev/null +++ b/tests/protocols/treeland-app-id-resolver-v2/treeland-app-id-resolver-v2.h @@ -0,0 +1,53 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef TREELAND_APP_ID_RESOLVER_TEST_H +#define TREELAND_APP_ID_RESOLVER_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +#include "client-connection.h" + +#define TEST_MSG_MAX 256 + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +struct test_ctx { + struct client_connection connection; + struct wl_display *display; + + struct treeland_app_id_resolver_manager_v2 *manager; + + struct treeland_app_id_resolver_v2 *resolver; + + int identify_received; + uint32_t identify_request_id; + int identify_pidfd; + + int display_errored; + + struct test_result *results; + int result_count; + int result_cap; +}; + +void test_init(struct test_ctx *ctx); +void test_destroy(struct test_ctx *ctx); +int test_add(struct test_ctx *ctx, const char *name); +void test_fail(struct test_ctx *ctx, int idx, const char *fmt, ...); +void test_pass(struct test_ctx *ctx, int idx); + +int test_print_results(struct test_ctx *ctx); +void test_cleanup(struct test_ctx *ctx); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-appearance-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-appearance-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..7f4d48ddb4 --- /dev/null +++ b/tests/protocols/treeland-appearance-unstable-v1/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME treeland_appearance_unstable_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-appearance-unstable-v1.xml" + EXTRA_XMLS "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-appearance-manager-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-appearance-unstable-v1.c" +) diff --git a/tests/protocols/treeland-appearance-unstable-v1/README.md b/tests/protocols/treeland-appearance-unstable-v1/README.md new file mode 100644 index 0000000000..8724e48a74 --- /dev/null +++ b/tests/protocols/treeland-appearance-unstable-v1/README.md @@ -0,0 +1,7 @@ +# appearance-unstable-v1 + +覆盖等级:I / P。 + +测试绑定 appearance 与 appearance-manager global,断言 bind 时收到初始 +`color_scheme`,并通过 manager 的 `set_color_scheme(dark)` 验证配置变更会广播到 +已绑定的 appearance client。其余外观字段、无效值和 DConfig 配置替换仍未覆盖。 diff --git a/tests/protocols/treeland-appearance-unstable-v1/setup.cpp b/tests/protocols/treeland-appearance-unstable-v1/setup.cpp new file mode 100644 index 0000000000..3eabe4d950 --- /dev/null +++ b/tests/protocols/treeland-appearance-unstable-v1/setup.cpp @@ -0,0 +1,11 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "modules/appearance/appearanceinterfacev1.h" +#include "modules/appearance/appearancemanagerinterfacev1.h" +#include "server-bridge.h" + +void protocol_test_setup(WaylandServer *server) +{ + Q_ASSERT(find_server_interface(server)); + Q_ASSERT(find_server_interface(server)); +} diff --git a/tests/protocols/treeland-appearance-unstable-v1/treeland-appearance-unstable-v1.c b/tests/protocols/treeland-appearance-unstable-v1/treeland-appearance-unstable-v1.c new file mode 100644 index 0000000000..2f5d80ee49 --- /dev/null +++ b/tests/protocols/treeland-appearance-unstable-v1/treeland-appearance-unstable-v1.c @@ -0,0 +1,74 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "client-connection.h" +#include "treeland-appearance-unstable-v1-client-protocol.h" +#include "treeland-appearance-manager-unstable-v1-client-protocol.h" + +#include + +struct appearance_state { + unsigned initial_color_scheme_events; + unsigned color_scheme; +}; + +static void cursor_theme(void *data, struct treeland_appearance_v1 *appearance, const char *name) +{ (void)data; (void)appearance; (void)name; } +static void cursor_size(void *data, struct treeland_appearance_v1 *appearance, uint32_t width, uint32_t height) +{ (void)data; (void)appearance; (void)width; (void)height; } +static void font(void *data, struct treeland_appearance_v1 *appearance, const char *name) +{ (void)data; (void)appearance; (void)name; } +static void monospace_font(void *data, struct treeland_appearance_v1 *appearance, const char *name) +{ (void)data; (void)appearance; (void)name; } +static void font_size(void *data, struct treeland_appearance_v1 *appearance, uint32_t size) +{ (void)data; (void)appearance; (void)size; } +static void icon_theme(void *data, struct treeland_appearance_v1 *appearance, const char *name) +{ (void)data; (void)appearance; (void)name; } +static void accent_color(void *data, struct treeland_appearance_v1 *appearance, uint32_t r, uint32_t g, uint32_t b) +{ (void)data; (void)appearance; (void)r; (void)g; (void)b; } +static void window_opacity(void *data, struct treeland_appearance_v1 *appearance, wl_fixed_t opacity) +{ (void)data; (void)appearance; (void)opacity; } +static void color_scheme(void *data, struct treeland_appearance_v1 *appearance, uint32_t scheme) +{ (void)appearance; struct appearance_state *state = data; state->initial_color_scheme_events++; state->color_scheme = scheme; } +static void titlebar_height(void *data, struct treeland_appearance_v1 *appearance, uint32_t height) +{ (void)data; (void)appearance; (void)height; } +static void corner_radius(void *data, struct treeland_appearance_v1 *appearance, uint32_t radius) +{ (void)data; (void)appearance; (void)radius; } + +static const struct treeland_appearance_v1_listener appearance_listener = { + cursor_theme, cursor_size, font, monospace_font, font_size, icon_theme, + accent_color, window_opacity, color_scheme, titlebar_height, corner_radius, +}; + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + struct appearance_state state = { 0 }; + if (!client_connect(&connection, socket_name)) + return 1; + struct treeland_appearance_v1 *appearance = client_bind(&connection, + "treeland_appearance_v1", &treeland_appearance_v1_interface, 1); + struct treeland_appearance_manager_v1 *manager = client_bind(&connection, + "treeland_appearance_manager_v1", &treeland_appearance_manager_v1_interface, 1); + if (!appearance || !manager) { + fprintf(stderr, "appearance: missing global\n"); + client_disconnect(&connection); + return 1; + } + treeland_appearance_v1_add_listener(appearance, &appearance_listener, &state); + if (wl_display_roundtrip(connection.display) < 0 || !state.initial_color_scheme_events) { + fprintf(stderr, "appearance: initial state was not sent\n"); + return 1; + } + const unsigned before = state.initial_color_scheme_events; + treeland_appearance_manager_v1_set_color_scheme(manager, + TREELAND_APPEARANCE_MANAGER_V1_COLOR_SCHEME_DARK); + if (wl_display_roundtrip(connection.display) < 0 || state.initial_color_scheme_events <= before + || state.color_scheme != TREELAND_APPEARANCE_V1_COLOR_SCHEME_DARK) { + fprintf(stderr, "appearance: manager update was not observed\n"); + return 1; + } + treeland_appearance_manager_v1_destroy(manager); + treeland_appearance_v1_destroy(appearance); + client_disconnect(&connection); + return 0; +} diff --git a/tests/protocols/treeland-capture-desktop-v1/CMakeLists.txt b/tests/protocols/treeland-capture-desktop-v1/CMakeLists.txt new file mode 100644 index 0000000000..0a25e2cb04 --- /dev/null +++ b/tests/protocols/treeland-capture-desktop-v1/CMakeLists.txt @@ -0,0 +1,12 @@ + +treeland_add_protocol_test( + NAME treeland_capture_desktop_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-capture-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-capture-desktop-v1.c" +) + +# CaptureManagerV1 and the production CaptureSourceSelector are supplied by +# the Treeland.Capture module, which libtreeland keeps private. +target_link_libraries(test_treeland_capture_desktop_v1 PRIVATE capture) +target_compile_definitions(test_treeland_capture_desktop_v1 PRIVATE WLR_USE_UNSTABLE) diff --git a/tests/protocols/treeland-capture-desktop-v1/setup.cpp b/tests/protocols/treeland-capture-desktop-v1/setup.cpp new file mode 100644 index 0000000000..eb94ec7162 --- /dev/null +++ b/tests/protocols/treeland-capture-desktop-v1/setup.cpp @@ -0,0 +1,97 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "core/rootsurfacecontainer.h" +#include "core/shellhandler.h" +#include "modules/capture/capture.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" +#include "treeland-capture-desktop-v1.h" +#include "workspace/workspace.h" + +#include +#include +#include + +namespace { +SurfaceWrapper *g_wrapper = nullptr; +capture_desktop_selection_state g_state {}; + +void copyState(void *data) +{ + *static_cast(data) = g_state; +} +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [server](SurfaceWrapper *wrapper) { + if (wrapper->type() != SurfaceWrapper::Type::XdgToplevel) + return; + g_wrapper = wrapper; + g_state.wrapper_ready = 1; + g_state.output_ready = !server->rootSurfaceContainer()->outputs().isEmpty() ? 1 : 0; + }); +} + +extern "C" void capture_desktop_select_mapped_surface(void *data) +{ + auto *server = WaylandServer::instance(); + g_state.output_ready = !server->rootSurfaceContainer()->outputs().isEmpty() ? 1 : 0; + if (!g_wrapper || !server->workspace()->surfaces().contains(g_wrapper) + || !g_wrapper->surfaceItem()) { + copyState(data); + return; + } + + auto *content = g_wrapper->surfaceItem()->findItemContent(); + if (!content) { + copyState(data); + return; + } + g_state.surface_content_ready = 1; + const auto paintOrder = WOutputRenderWindow::paintOrderItemList( + server->window()->contentItem(), [](QQuickItem *) { return true; }); + g_state.content_in_paint_order = paintOrder.contains(content) ? 1 : 0; + g_state.content_visible = content->isVisible() ? 1 : 0; + g_state.content_width = qRound(content->width()); + g_state.content_height = qRound(content->height()); + + // WaylandServer creates this production QML selector in response to the client's + // select_source request. The test never calls CaptureContextV1::setSource(). + auto *selector = server->rootSurfaceContainer()->findChild(); + if (!selector) { + copyState(data); + return; + } + g_state.selector_ready = 1; + + // Select the verified mapped production surface through the selector's + // production selection entry point. + server->window()->render(); + selector->selectSurface(content); + g_state.hovered_mapped_content = 1; + + auto *context = selector->captureManager()->contextInSelection(); + auto *source = context ? context->source() : nullptr; + g_state.source_selected = source ? 1 : 0; + g_state.source_is_surface = source && source->sourceType() == CaptureSource::Surface ? 1 : 0; + if (source) { + const QSize sourceSize = source->sourceSize(); + g_state.source_width = sourceSize.width(); + g_state.source_height = sourceSize.height(); + } + copyState(data); +} + +extern "C" void capture_desktop_render_selected_source(void *data) +{ + auto *server = WaylandServer::instance(); + server->window()->render(); + g_state.render_requested = 1; + copyState(data); +} diff --git a/tests/protocols/treeland-capture-desktop-v1/treeland-capture-desktop-v1.c b/tests/protocols/treeland-capture-desktop-v1/treeland-capture-desktop-v1.c new file mode 100644 index 0000000000..d6596b0316 --- /dev/null +++ b/tests/protocols/treeland-capture-desktop-v1/treeland-capture-desktop-v1.c @@ -0,0 +1,292 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 200809L +#endif + +#include "xdg-toplevel-client.h" +#include "server-bridge-api.h" +#include "treeland-capture-desktop-v1.h" +#include "treeland-capture-unstable-v1-client-protocol.h" + +#include +#include +#include +#include +#include + +extern void capture_desktop_select_mapped_surface(void *data); +extern void capture_desktop_render_selected_source(void *data); + +struct capture_client { + struct client_connection connection; + struct xdg_toplevel_client toplevel; + struct treeland_capture_manager_v1 *manager; + struct treeland_capture_context_v1 *context; + struct treeland_capture_frame_v1 *frame; + struct wl_buffer *target_buffer; + void *target_data; + size_t target_size; + uint32_t target_format; + uint32_t target_width; + uint32_t target_height; + uint32_t target_stride; + int source_ready; + int source_failed; + uint32_t source_type; + uint32_t source_width; + uint32_t source_height; + int buffer_received; + int buffer_done; + int frame_ready; + int frame_failed; +}; + +static void context_source_ready(void *data, + struct treeland_capture_context_v1 *context, + int32_t x, + int32_t y, + uint32_t width, + uint32_t height, + uint32_t source_type) +{ + (void)context; + (void)x; + (void)y; + struct capture_client *client = data; + client->source_ready = 1; + client->source_width = width; + client->source_height = height; + client->source_type = source_type; +} + +static void context_source_failed(void *data, + struct treeland_capture_context_v1 *context, + uint32_t reason) +{ + (void)context; + (void)reason; + ((struct capture_client *)data)->source_failed = 1; +} + +static const struct treeland_capture_context_v1_listener context_listener = { + .source_ready = context_source_ready, + .source_failed = context_source_failed, +}; + +static int create_target_buffer(struct capture_client *client) +{ + const size_t size = (size_t)client->target_stride * client->target_height; + char name[64]; + snprintf(name, sizeof(name), "/treeland_capture_target_%d", (int)getpid()); + const int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); + if (fd < 0) + return 0; + shm_unlink(name); + if (ftruncate(fd, (off_t)size) < 0) { + close(fd); + return 0; + } + client->target_data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (client->target_data == MAP_FAILED) { + client->target_data = NULL; + close(fd); + return 0; + } + memset(client->target_data, 0, size); + struct wl_shm_pool *pool = wl_shm_create_pool(client->toplevel.shm, fd, (int)size); + close(fd); + if (!pool) + return 0; + client->target_buffer = wl_shm_pool_create_buffer(pool, + 0, + (int)client->target_width, + (int)client->target_height, + (int)client->target_stride, + client->target_format); + wl_shm_pool_destroy(pool); + if (!client->target_buffer) + return 0; + client->target_size = size; + return 1; +} + +static void frame_buffer(void *data, + struct treeland_capture_frame_v1 *frame, + uint32_t format, + uint32_t width, + uint32_t height, + uint32_t stride) +{ + struct capture_client *client = data; + if (client->buffer_received) + return; + client->target_format = format; + client->target_width = width; + client->target_height = height; + client->target_stride = stride; + client->buffer_received = create_target_buffer(client); + if (client->buffer_received) { + treeland_capture_frame_v1_copy(frame, client->target_buffer); + wl_display_flush(client->connection.display); + } +} + +static void frame_buffer_done(void *data, struct treeland_capture_frame_v1 *frame) +{ + (void)frame; + ((struct capture_client *)data)->buffer_done = 1; +} + +static void frame_flags(void *data, struct treeland_capture_frame_v1 *frame, uint32_t flags) +{ + (void)data; + (void)frame; + (void)flags; +} + +static void frame_ready(void *data, struct treeland_capture_frame_v1 *frame) +{ + (void)frame; + ((struct capture_client *)data)->frame_ready = 1; +} + +static void frame_failed(void *data, struct treeland_capture_frame_v1 *frame) +{ + (void)frame; + ((struct capture_client *)data)->frame_failed = 1; +} + +static const struct treeland_capture_frame_v1_listener frame_listener = { + .buffer = frame_buffer, + .buffer_done = frame_buffer_done, + .flags = frame_flags, + .ready = frame_ready, + .failed = frame_failed, +}; + +static int target_is_opaque_red(const struct capture_client *client) +{ + if (!client->target_data || client->target_width != 64 || client->target_height != 64 + || client->target_stride != 64 * 4) + return 0; + const uint32_t pixel = *(const uint32_t *)client->target_data; + switch (client->target_format) { + case WL_SHM_FORMAT_ARGB8888: + return ((pixel >> 24) & 0xff) == 255 && ((pixel >> 16) & 0xff) == 255 + && ((pixel >> 8) & 0xff) == 0 && (pixel & 0xff) == 0; + case WL_SHM_FORMAT_ABGR8888: + return ((pixel >> 24) & 0xff) == 255 && (pixel & 0xff) == 255 + && ((pixel >> 8) & 0xff) == 0 && ((pixel >> 16) & 0xff) == 0; + default: + return 0; + } +} + +static void cleanup(struct capture_client *client) +{ + if (client->frame) + treeland_capture_frame_v1_destroy(client->frame); + if (client->context) + treeland_capture_context_v1_destroy(client->context); + if (client->manager) + treeland_capture_manager_v1_destroy(client->manager); + if (client->target_buffer) + wl_buffer_destroy(client->target_buffer); + if (client->target_data) + munmap(client->target_data, client->target_size); + xdg_toplevel_client_destroy(&client->toplevel); + client_disconnect(&client->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct capture_client client = { 0 }; + struct capture_desktop_selection_state selection = { 0 }; + struct capture_desktop_selection_state render = { 0 }; + int result = 1; + + if (!client_connect(&client.connection, socket_name) + || !xdg_toplevel_client_create_with_solid_buffer( + &client.connection, &client.toplevel, 64, 64, 0xffff0000u)) + goto done; + client.manager = client_bind(&client.connection, + "treeland_capture_manager_v1", + &treeland_capture_manager_v1_interface, + 1); + if (!client.manager) + goto done; + client.context = treeland_capture_manager_v1_get_context(client.manager); + if (!client.context) + goto done; + treeland_capture_context_v1_add_listener(client.context, &context_listener, &client); + + treeland_capture_context_v1_select_source(client.context, + TREELAND_CAPTURE_CONTEXT_V1_SOURCE_TYPE_WINDOW, + 0, + 0, + NULL); + if (wl_display_roundtrip(client.connection.display) < 0 + || !invoke_on_server_thread(capture_desktop_select_mapped_surface, &selection) + || wl_display_roundtrip(client.connection.display) < 0 + || !selection.output_ready || !selection.wrapper_ready || !selection.surface_content_ready + || !selection.content_in_paint_order || !selection.content_visible + || selection.content_width != 64 || selection.content_height != 64 + || !selection.selector_ready || !selection.hovered_mapped_content + || !selection.source_selected || !selection.source_is_surface + || selection.source_width != 64 || selection.source_height != 64 + || !client.source_ready || client.source_failed + || client.source_type != TREELAND_CAPTURE_CONTEXT_V1_SOURCE_TYPE_WINDOW + || client.source_width != 64 || client.source_height != 64) + goto done; + + client.frame = treeland_capture_context_v1_capture(client.context); + if (!client.frame) + goto done; + treeland_capture_frame_v1_add_listener(client.frame, &frame_listener, &client); + + // The roundtrip is a protocol ordering barrier: it proves onCapture() and + // CaptureSourceSelector::doneSelection() have run before we request the + // real output render that produces the source image. + if (wl_display_roundtrip(client.connection.display) < 0 + || !invoke_on_server_thread(capture_desktop_render_selected_source, &render) + || !render.render_requested) + goto done; + + while (!client.frame_ready && !client.frame_failed) { + if (wl_display_dispatch(client.connection.display) < 0) + goto done; + } + if (!client.frame_failed && client.buffer_received && client.buffer_done && target_is_opaque_red(&client)) + result = 0; + +done: + if (result != 0) { + fprintf(stderr, + "capture desktop failed: content=(paint=%d visible=%d %dx%d) selector=(%d,%d,%d) source=(surface=%d %dx%d) " + "event=(ready=%d failed=%d type=%u %ux%u) buffer=(%d done=%d fmt=0x%x %ux%u stride=%u)\n", + selection.content_in_paint_order, + selection.content_visible, + selection.content_width, + selection.content_height, + selection.selector_ready, + selection.hovered_mapped_content, + selection.source_selected, + selection.source_is_surface, + selection.source_width, + selection.source_height, + client.source_ready, + client.source_failed, + client.source_type, + client.source_width, + client.source_height, + client.buffer_received, + client.buffer_done, + client.target_format, + client.target_width, + client.target_height, + client.target_stride); + } + cleanup(&client); + return result; +} diff --git a/tests/protocols/treeland-capture-desktop-v1/treeland-capture-desktop-v1.h b/tests/protocols/treeland-capture-desktop-v1/treeland-capture-desktop-v1.h new file mode 100644 index 0000000000..2210cda504 --- /dev/null +++ b/tests/protocols/treeland-capture-desktop-v1/treeland-capture-desktop-v1.h @@ -0,0 +1,31 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +struct capture_desktop_selection_state { + int output_ready; + int wrapper_ready; + int surface_content_ready; + int content_in_paint_order; + int content_visible; + int content_width; + int content_height; + int selector_ready; + int hovered_mapped_content; + int source_selected; + int source_is_surface; + int source_width; + int source_height; + int render_requested; +}; + +int protocol_test_run(const char *socket_name); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/treeland-capture-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-capture-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..00575686ea --- /dev/null +++ b/tests/protocols/treeland-capture-unstable-v1/CMakeLists.txt @@ -0,0 +1,11 @@ +treeland_add_protocol_test( + NAME treeland_capture_unstable_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-capture-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-capture-unstable-v1.c" +) + +# CaptureManagerV1 lives in the Treeland.Capture QML module library, which +# libtreeland links privately (impl_treeland), so link it explicitly here. +target_link_libraries(test_treeland_capture_unstable_v1 PRIVATE capture) +target_compile_definitions(test_treeland_capture_unstable_v1 PRIVATE WLR_USE_UNSTABLE) diff --git a/tests/protocols/treeland-capture-unstable-v1/README.md b/tests/protocols/treeland-capture-unstable-v1/README.md new file mode 100644 index 0000000000..00d696e43a --- /dev/null +++ b/tests/protocols/treeland-capture-unstable-v1/README.md @@ -0,0 +1,87 @@ +# `treeland-capture-unstable-v1` 测试规范 + +## 范围 + +本协议有两层测试,不能把基础错误路径误认为实际捕获成功。 + +| 测试源码 | Fixture | 覆盖等级 | 用途 | +| --- | --- | --- | --- | +| `treeland-capture-unstable-v1/` | 仅 `CaptureManagerV1`,没有 selector/source | P | 选择权、资源和无 source 协议错误 | +| `treeland-capture-desktop-v1/` | 完整生产 `WaylandServer`、headless output、`ShellHandler`、QML selector 与 mapped xdg 窗口 | E / V | 真实选择窗口、复制 frame,并读取客户端目标 buffer 像素 | + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | +| --- | --- | --- | +| context 所有权 | 两个客户端创建 context | selector 的 busy/所有权规则生效 | +| 无 source | source ready 前调用 `capture` 或 `create_session` | 连接收到 XML 规定的协议错误 | + +## 基础协议路径(P) + +第一个客户端 context 发送 `select_source(OUTPUT, 0, 0, NULL)` 后成为正在选择 source +的 context,测试断言它不会收到 `source_failed`。第二个 context 随即发送 +`select_source(WINDOW, 0, 0, NULL)`,生产 `CaptureSourceSelector` 必须发送 +`source_failed(SELECTOR_BUSY)`。销毁第一个 context 后,第三个 context 发送 +`select_source(REGION, 0, 0, NULL)`,不应再收到 busy 失败,证明销毁确实释放生产 +selector 的选择状态。 + +另外两个全新客户端各自发送 `get_context` 后立即调用 `capture()` 或 +`create_session()`。由于没有 ready source,生产 `CaptureContextV1` 必须在 display +上 post `WL_DISPLAY_ERROR_IMPLEMENTATION`;测试用 +`wl_display_get_protocol_error()` 读取该真实协议错误。 + +## 实际捕获路径(E / V) + +`treeland-capture-desktop-v1` 使用同一个客户端同时建立被捕获窗口和 capture +context,完整步骤如下。 + +1. 客户端创建 xdg-toplevel,等待并 ack 初次 `xdg_surface.configure`,然后提交 + `64×64`、`wl_shm/ARGB8888`、所有像素为 `0xffff0000`(不透明红)的 buffer。 +2. 生产 `ShellHandler` 收到 mapped xdg surface,创建 `SurfaceWrapper`,加入 + `Workspace`,并由生产 QML `SurfaceContent` 创建内部的 + `WSurfaceItemContent`。 +3. 客户端创建 `treeland_capture_context_v1`,发送 + `select_source(WINDOW, freeze=0, with_cursor=0, mask=NULL)`。这使生产 + `CaptureManagerV1` 建立 `contextInSelection`,而 `WaylandServer` 的既有连接创建 + QML `CaptureSourceSelector`。 +4. fixture 先断言该 `WSurfaceItemContent` 位于生产 output 的 paint-order、可见且为 + `64×64`。headless QPA 不稳定地投递 Qt Quick hover/pointer,因此测试用一个仅供 + protocol test 使用的 access bridge 调用 selector 自己的 + `setSelectedSource()`;它创建真实 `CaptureSourceSurface`,而不是向 + `CaptureContextV1::setSource()` 塞入伪造 source。 +5. selector 的生产 `setSelectedSource()` 调用生产 + `CaptureContextV1::setSource()`。客户端必须收到 + `source_ready(..., width=64, height=64, source_type=WINDOW)`;fixture 同时断言 + source 的实际类型为 `CaptureSource::Surface`、尺寸为 `64×64`。 +6. 客户端发送 `capture()`。协议 roundtrip 确认生产 `onCapture()` 与 selector + `doneSelection()` 已执行;fixture 调用真实 `WOutputRenderWindow::render()`。 + `renderEnd` 驱动 `CaptureSource::createImage()`,由 `WTextureCapturer` 读取所选 + `WSurfaceItemContent` 的生产纹理。 +7. 客户端收到 `treeland_capture_frame_v1.buffer(format, 64, 64, 256)` 后,以该 + format 创建自己的 `wl_shm` 目标 buffer,发送 `frame.copy(buffer)`。生产 + `CaptureSource::copyBuffer()` 把 image 写入此 buffer,并发送 `buffer_done` 与 + `ready`。 +8. 客户端仅等待真实 `ready` 或 `failed` 事件。通过条件为:没有 `failed`、收到 + `buffer_done` 与 `ready`、目标为 `64×64`/stride `256`,且第一个像素按服务器 + 宣告的 `ARGB8888` 或 `ABGR8888` 格式解码后为 RGBA `(255,0,0,255)`。 + +已证明的完整数据流为: + +`wl_shm 红色窗口 buffer → xdg map → ShellHandler/SurfaceWrapper/QML SurfaceContent +→ CaptureSourceSelector 真实 source 提交 → CaptureSourceSurface → source_ready → +WTextureCapturer → frame.buffer → 客户端 wl_shm frame.copy → frame.ready → 红色像素`。 + +该 E/V 路径已通过本地执行。测试没有根据时间判断 selector、纹理或 frame 是否就绪: +状态推进分别由 Wayland roundtrip、服务端同步回调,以及 +`source_ready`/`buffer`/`ready` 事件驱动。 + +## 已知边界 / 下一项结果 + +当前只验证 **window/surface 的 one-shot copy**。尚未覆盖: + +- Qt Quick headless QPA 下真实鼠标 hover/release 到 `ItemSelector` 的命中分发; +- `OUTPUT`、`REGION` source 的选区和坐标裁剪; +- `freeze=1`、`with_cursor=1` 与 mask surface 的实际合成语义; +- persistent `create_session()` 的 dmabuf `frame/object/ready/frame_done` 流; +- output 的最终合成 backing buffer 像素(当前 window source 已是生产 scene + texture,目标 buffer 像素已验证)。 diff --git a/tests/protocols/treeland-capture-unstable-v1/setup.cpp b/tests/protocols/treeland-capture-unstable-v1/setup.cpp new file mode 100644 index 0000000000..ca67cf255b --- /dev/null +++ b/tests/protocols/treeland-capture-unstable-v1/setup.cpp @@ -0,0 +1,14 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "modules/capture/capture.h" +#include "server-bridge.h" + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +void protocol_test_setup(WaylandServer *server) +{ + Q_ASSERT(find_server_interface(server)); +} diff --git a/tests/protocols/treeland-capture-unstable-v1/treeland-capture-unstable-v1.c b/tests/protocols/treeland-capture-unstable-v1/treeland-capture-unstable-v1.c new file mode 100644 index 0000000000..29b00c940f --- /dev/null +++ b/tests/protocols/treeland-capture-unstable-v1/treeland-capture-unstable-v1.c @@ -0,0 +1,293 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-capture-unstable-v1.h" +#include "treeland-capture-unstable-v1-client-protocol.h" + +#include +#include +#include +#include + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); +}; + +void test_init(struct test_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); + ctx->result_cap = 32; + ctx->results = calloc(ctx->result_cap, sizeof(*ctx->results)); +} + +void test_destroy(struct test_ctx *ctx) +{ + free(ctx->results); + memset(ctx, 0, sizeof(*ctx)); +} + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +void test_pass(struct test_ctx *ctx, int index) +{ + ctx->results[index].failed = 0; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +static void context_source_ready(void *data, struct treeland_capture_context_v1 *context, + int32_t region_x, int32_t region_y, + uint32_t region_width, uint32_t region_height, + uint32_t source_type) +{ + (void)data; + (void)context; + (void)region_x; + (void)region_y; + (void)region_width; + (void)region_height; + (void)source_type; +} + +static void context_a_source_failed(void *data, struct treeland_capture_context_v1 *context, + uint32_t reason) +{ + (void)context; + (void)reason; + ((struct test_ctx *)data)->a_source_failed_received = 1; +} + +static void context_b_source_failed(void *data, struct treeland_capture_context_v1 *context, + uint32_t reason) +{ + (void)context; + struct test_ctx *ctx = data; + ctx->b_source_failed_received = 1; + ctx->b_source_failed_reason = reason; +} + +static void context_c_source_failed(void *data, struct treeland_capture_context_v1 *context, + uint32_t reason) +{ + (void)context; + (void)reason; + ((struct test_ctx *)data)->c_source_failed_received = 1; +} + +static const struct treeland_capture_context_v1_listener context_listener_a = { + .source_ready = context_source_ready, + .source_failed = context_a_source_failed, +}; + +static const struct treeland_capture_context_v1_listener context_listener_b = { + .source_ready = context_source_ready, + .source_failed = context_b_source_failed, +}; + +static const struct treeland_capture_context_v1_listener context_listener_c = { + .source_ready = context_source_ready, + .source_failed = context_c_source_failed, +}; + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->display = ctx->connection.display; + ctx->manager = client_bind(&ctx->connection, "treeland_capture_manager_v1", + &treeland_capture_manager_v1_interface, 1); + return ctx->manager != NULL; +} + +static int get_context(struct test_ctx *ctx) +{ + ctx->context_a = treeland_capture_manager_v1_get_context(ctx->manager); + if (ctx->context_a) + treeland_capture_context_v1_add_listener(ctx->context_a, &context_listener_a, ctx); + return ctx->context_a != NULL; +} + +static int select_source(struct test_ctx *ctx) +{ + + treeland_capture_context_v1_select_source(ctx->context_a, + TREELAND_CAPTURE_CONTEXT_V1_SOURCE_TYPE_OUTPUT, + 0, 0, NULL); + return 1; +} + +static int select_source_busy(struct test_ctx *ctx) +{ + + ctx->context_b = treeland_capture_manager_v1_get_context(ctx->manager); + if (!ctx->context_b) + return 0; + treeland_capture_context_v1_add_listener(ctx->context_b, &context_listener_b, ctx); + treeland_capture_context_v1_select_source(ctx->context_b, + TREELAND_CAPTURE_CONTEXT_V1_SOURCE_TYPE_WINDOW, + 0, 0, NULL); + return 1; +} + +static int source_failed_busy_received(struct test_ctx *ctx) +{ + return ctx->b_source_failed_received + && ctx->b_source_failed_reason == TREELAND_CAPTURE_CONTEXT_V1_SOURCE_FAILURE_SELECTOR_BUSY; +} + +static int no_source_failed_on_first_select(struct test_ctx *ctx) +{ + return ctx->a_source_failed_received == 0; +} + +static int destroy_in_selection(struct test_ctx *ctx) +{ + + treeland_capture_context_v1_destroy(ctx->context_a); + ctx->context_a = NULL; + return 1; +} + +static int select_source_after_clear(struct test_ctx *ctx) +{ + ctx->context_c = treeland_capture_manager_v1_get_context(ctx->manager); + if (!ctx->context_c) + return 0; + treeland_capture_context_v1_add_listener(ctx->context_c, &context_listener_c, ctx); + treeland_capture_context_v1_select_source(ctx->context_c, + TREELAND_CAPTURE_CONTEXT_V1_SOURCE_TYPE_REGION, + 0, 0, NULL); + return 1; +} + +static int no_source_failed_after_clear(struct test_ctx *ctx) +{ + return ctx->c_source_failed_received == 0; +} + +static struct treeland_capture_manager_v1 *connect_fresh_manager( + const char *socket_name, struct client_connection *connection) +{ + if (!client_connect(connection, socket_name)) + return NULL; + return client_bind(connection, "treeland_capture_manager_v1", + &treeland_capture_manager_v1_interface, 1); +} + +static int capture_without_source_errors(struct test_ctx *ctx) +{ + + struct client_connection connection; + struct treeland_capture_manager_v1 *manager = + connect_fresh_manager(ctx->socket_name, &connection); + if (!manager) + return 0; + struct treeland_capture_context_v1 *context = treeland_capture_manager_v1_get_context(manager); + treeland_capture_context_v1_capture(context); + const struct wl_interface *iface; + uint32_t code; + const int errored = wl_display_roundtrip(connection.display) < 0 + && wl_display_get_protocol_error(connection.display, &iface, &code) + == WL_DISPLAY_ERROR_IMPLEMENTATION; + client_disconnect(&connection); + return errored; +} + +static int create_session_without_source_errors(struct test_ctx *ctx) +{ + + struct client_connection connection; + struct treeland_capture_manager_v1 *manager = + connect_fresh_manager(ctx->socket_name, &connection); + if (!manager) + return 0; + struct treeland_capture_context_v1 *context = treeland_capture_manager_v1_get_context(manager); + treeland_capture_context_v1_create_session(context); + const struct wl_interface *iface; + uint32_t code; + const int errored = wl_display_roundtrip(connection.display) < 0 + && wl_display_get_protocol_error(connection.display, &iface, &code) + == WL_DISPLAY_ERROR_IMPLEMENTATION; + client_disconnect(&connection); + return errored; +} + +static const struct test_case cases[] = { + { "manager.get_context", get_context }, + { "context.select_source", select_source }, + { "context.select_source_busy", select_source_busy }, + { "context.event.source_failed_busy", source_failed_busy_received }, + { "context.event.no_source_failed_on_first_select", no_source_failed_on_first_select }, + { "context.destroy_in_selection", destroy_in_selection }, + { "context.select_source_after_clear", select_source_after_clear }, + { "context.event.no_source_failed_after_clear", no_source_failed_after_clear }, + { "context.capture_without_source_errors", capture_without_source_errors }, + { "context.create_session_without_source_errors", create_session_without_source_errors }, +}; + +void test_cleanup(struct test_ctx *ctx) +{ + if (ctx->context_c) treeland_capture_context_v1_destroy(ctx->context_c); + if (ctx->context_b) treeland_capture_context_v1_destroy(ctx->context_b); + if (ctx->context_a) treeland_capture_context_v1_destroy(ctx->context_a); + if (ctx->manager) treeland_capture_manager_v1_destroy(ctx->manager); + client_disconnect(&ctx->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx; + test_init(&ctx); + ctx.socket_name = socket_name; + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect to or bind treeland_capture_manager_v1\n"); + test_cleanup(&ctx); + test_destroy(&ctx); + return 1; + } + + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const int result = test_add(&ctx, cases[i].name); + if (!cases[i].run(&ctx)) + test_fail(&ctx, result, "assertion failed"); + if (wl_display_roundtrip(ctx.display) < 0) + test_fail(&ctx, result, "Wayland connection failed"); + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + test_destroy(&ctx); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-capture-unstable-v1/treeland-capture-unstable-v1.h b/tests/protocols/treeland-capture-unstable-v1/treeland-capture-unstable-v1.h new file mode 100644 index 0000000000..718080d3db --- /dev/null +++ b/tests/protocols/treeland-capture-unstable-v1/treeland-capture-unstable-v1.h @@ -0,0 +1,55 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef TREELAND_CAPTURE_TEST_H +#define TREELAND_CAPTURE_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +#include "client-connection.h" + +#define TEST_MSG_MAX 256 + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +struct test_ctx { + struct client_connection connection; + struct wl_display *display; + const char *socket_name; + + struct treeland_capture_manager_v1 *manager; + + struct treeland_capture_context_v1 *context_a; + struct treeland_capture_context_v1 *context_b; + struct treeland_capture_context_v1 *context_c; + + int a_source_failed_received; + int b_source_failed_received; + uint32_t b_source_failed_reason; + int c_source_failed_received; + + struct test_result *results; + int result_count; + int result_cap; +}; + +void test_init(struct test_ctx *ctx); +void test_destroy(struct test_ctx *ctx); +int test_add(struct test_ctx *ctx, const char *name); +void test_fail(struct test_ctx *ctx, int idx, const char *fmt, ...); +void test_pass(struct test_ctx *ctx, int idx); + +int test_print_results(struct test_ctx *ctx); +void test_cleanup(struct test_ctx *ctx); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-compositor-action-v1/CMakeLists.txt b/tests/protocols/treeland-compositor-action-v1/CMakeLists.txt new file mode 100644 index 0000000000..0f1edee8bb --- /dev/null +++ b/tests/protocols/treeland-compositor-action-v1/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_compositor_action_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-compositor-action-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-compositor-action-v1.c" +) diff --git a/tests/protocols/treeland-compositor-action-v1/README.md b/tests/protocols/treeland-compositor-action-v1/README.md new file mode 100644 index 0000000000..1ba961c57c --- /dev/null +++ b/tests/protocols/treeland-compositor-action-v1/README.md @@ -0,0 +1,42 @@ +# `treeland-compositor-action-v1` 测试规范 + +## 范围 + +- 测试源码:`tests/protocols/treeland-compositor-action-v1/` +- Fixture:协议 fixture(headless treeland,默认 2 个工作区) +- 覆盖等级:**E**(工作区切换与 show-desktop 的真实生产状态)+ **P**(绑定、忽略语义、生命周期) + +## 实际请求与预期结果 + +| 场景 | 客户端发送 | 生产业务逻辑与断言 | +| --- | --- | --- | +| 绑定 | 连接并绑定 `treeland_compositor_action_v1` | 特权全局对象存在,绑定成功(fixture 未设置 `DDM_DISPLAY_MANAGER`,不启用会话 socket 过滤) | +| 切换工作区 | `trigger(workspace_2)` | 生产 `Workspace::currentIndex()` 变为 1 | +| prev/next | `trigger(prev_workspace)` / `trigger(next_workspace)` | 生产索引在 0/1 间正确移动 | +| 越界工作区 | `trigger(workspace_12)`(fixture 仅 2 个工作区) | 索引保持不变,`switchTo()` 忽略越界索引,对应协议 "无法执行即忽略" | +| show desktop | `trigger(show_desktop)` ×2 | 生产 `WaylandServer::showDesktopState()` 在 SHOW ↔ NORMAL 间切换 | +| 不支持的动作 | `trigger(zoom_in)` | 动作被忽略;连接保持可用(无协议错误) | +| 未知动作 | `trigger(999)` | 同上 | +| 销毁 | `destroy` + roundtrip | 对象销毁后连接仍可用 | + +## 已证明的生产链路 + +客户端发送 `trigger` 后,服务端在同一轮消息分发中同步路由到 +`WaylandServer::handleCompositorAction`(特权全局注册于 `WaylandServer::init`,绑定授权使用 +waylib 全局过滤器,与其它 `dde/` 特权协议一致)。测试通过 server bridge 读取 +真实 `Workspace::currentIndex()` 与 `WaylandServer::showDesktopState()`,因此证明的是 +动作对合成器真实状态的影响,而非接口回显。协议为一次性 fire-and-forget,无任何 +回传事件,测试同样验证了不支持/未知动作不会断开客户端。 + +## 未覆盖 + +以下分支仅由守卫短路,headless fixture 无法产生可观察的生产状态,故不进入断言: + +- 锁屏/关机菜单/用户切换动作:headless 环境无锁屏实现,`isLockScreenAvailable()` + 为假,动作被安全忽略(含聚焦关机菜单变体,其当前降级为普通菜单,见 + `WaylandServer::handleCompositorAction` 注释)。 +- 多任务视图动作:headless 未加载 multitaskview 插件,`m_multitaskView` 为空, + open/close/toggle 均按空守卫忽略。 +- 特权拒绝路径:需要 `DDM_DISPLAY_MANAGER` 环境与非会话 socket 的第二客户端, + 过滤行为由 waylib 全局过滤器承担,与其它特权协议一致。 +- FPS 覆盖层:无渲染级断言。 diff --git a/tests/protocols/treeland-compositor-action-v1/setup.cpp b/tests/protocols/treeland-compositor-action-v1/setup.cpp new file mode 100644 index 0000000000..e6b2df17f0 --- /dev/null +++ b/tests/protocols/treeland-compositor-action-v1/setup.cpp @@ -0,0 +1,37 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "modules/compositor-action/compositoractioninterfacev1.h" +#include "core/waylandserver.h" +#include "server-bridge.h" +#include "workspace/workspace.h" + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +CompositorActionInterfaceV1 *g_compositorAction = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + g_compositorAction = find_server_interface(server); +} + +extern "C" int compositor_action_global_exists(void *data) +{ + Q_UNUSED(data); + return g_compositorAction != nullptr; +} + +extern "C" void compositor_action_get_workspace_index(void *data) +{ + uint32_t *out = static_cast(data); + auto *workspace = WaylandServer::instance() ? WaylandServer::instance()->workspace() : nullptr; + *out = workspace ? static_cast(workspace->currentIndex()) : UINT32_MAX; +} + +extern "C" void compositor_action_get_show_desktop_state(void *data) +{ + uint32_t *out = static_cast(data); + auto *server = WaylandServer::instance(); + *out = server ? static_cast(server->showDesktopState()) : UINT32_MAX; +} diff --git a/tests/protocols/treeland-compositor-action-v1/treeland-compositor-action-v1.c b/tests/protocols/treeland-compositor-action-v1/treeland-compositor-action-v1.c new file mode 100644 index 0000000000..2dc1bad031 --- /dev/null +++ b/tests/protocols/treeland-compositor-action-v1/treeland-compositor-action-v1.c @@ -0,0 +1,249 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-compositor-action-v1.h" +#include "server-bridge-api.h" +#include "treeland-compositor-action-unstable-v1-client-protocol.h" + +#include +#include +#include +#include +#include + +extern int compositor_action_global_exists(void *data); +extern void compositor_action_get_workspace_index(void *data); +extern void compositor_action_get_show_desktop_state(void *data); + +/* ShowDesktop::State on the wire (Normal = 0, Show = 1) */ +enum { + PROD_DESKTOP_NORMAL = 0, + PROD_DESKTOP_SHOW = 1, +}; + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); +}; + +void test_init(struct test_ctx *ctx) +{ + ctx->result_cap = 32; + ctx->results = calloc(ctx->result_cap, sizeof(*ctx->results)); +} + +void test_finish(struct test_ctx *ctx) +{ + free(ctx->results); +} + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +void test_pass(struct test_ctx *ctx, int index) +{ + ctx->results[index].failed = 0; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +static uint32_t production_workspace_index(struct test_ctx *ctx) +{ + (void)ctx; + uint32_t index = UINT32_MAX; + if (!invoke_on_server_thread(compositor_action_get_workspace_index, &index)) + return UINT32_MAX; + return index; +} + +static uint32_t production_show_desktop_state(struct test_ctx *ctx) +{ + (void)ctx; + uint32_t state = UINT32_MAX; + if (!invoke_on_server_thread(compositor_action_get_show_desktop_state, &state)) + return UINT32_MAX; + return state; +} + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->display = ctx->connection.display; + ctx->action = client_bind(&ctx->connection, "treeland_compositor_action_v1", + &treeland_compositor_action_v1_interface, 1); + return ctx->action != NULL; +} + +static int bind_action(struct test_ctx *ctx) { return ctx->action != NULL; } + +static int trigger(struct test_ctx *ctx, uint32_t action) +{ + treeland_compositor_action_v1_trigger(ctx->action, action); + return 1; +} + +static int trigger_workspace_2(struct test_ctx *ctx) +{ + return trigger(ctx, TREELAND_COMPOSITOR_ACTION_V1_ACTION_WORKSPACE_2); +} + +static int workspace_index_is_1(struct test_ctx *ctx) +{ + return production_workspace_index(ctx) == 1; +} + +static int trigger_prev_workspace(struct test_ctx *ctx) +{ + return trigger(ctx, TREELAND_COMPOSITOR_ACTION_V1_ACTION_PREV_WORKSPACE); +} + +static int workspace_index_is_0(struct test_ctx *ctx) +{ + return production_workspace_index(ctx) == 0; +} + +static int trigger_next_workspace(struct test_ctx *ctx) +{ + return trigger(ctx, TREELAND_COMPOSITOR_ACTION_V1_ACTION_NEXT_WORKSPACE); +} + +static int trigger_workspace_1(struct test_ctx *ctx) +{ + return trigger(ctx, TREELAND_COMPOSITOR_ACTION_V1_ACTION_WORKSPACE_1); +} + +static int trigger_workspace_12_out_of_range(struct test_ctx *ctx) +{ + return trigger(ctx, TREELAND_COMPOSITOR_ACTION_V1_ACTION_WORKSPACE_12); +} + +static int workspace_index_unchanged_at_0(struct test_ctx *ctx) +{ + return production_workspace_index(ctx) == 0; +} + +static int trigger_show_desktop(struct test_ctx *ctx) +{ + return trigger(ctx, TREELAND_COMPOSITOR_ACTION_V1_ACTION_SHOW_DESKTOP); +} + +static int show_desktop_state_is_show(struct test_ctx *ctx) +{ + return production_show_desktop_state(ctx) == PROD_DESKTOP_SHOW; +} + +static int show_desktop_state_is_normal(struct test_ctx *ctx) +{ + return production_show_desktop_state(ctx) == PROD_DESKTOP_NORMAL; +} + +/* Unsupported (zoom) and unknown actions must be ignored, never fatal: the + * connection stays usable afterwards. */ +static int trigger_unsupported(struct test_ctx *ctx) +{ + return trigger(ctx, TREELAND_COMPOSITOR_ACTION_V1_ACTION_ZOOM_IN); +} + +static int trigger_unknown(struct test_ctx *ctx) +{ + return trigger(ctx, 999); +} + +static int connection_alive(struct test_ctx *ctx) +{ + return wl_display_roundtrip(ctx->display) >= 0; +} + +static int destroy_action(struct test_ctx *ctx) +{ + if (!ctx->action) + return 0; + treeland_compositor_action_v1_destroy(ctx->action); + ctx->action = NULL; + return 1; +} + +static const struct test_case cases[] = { + { "action.bind", bind_action }, + { "action.trigger.workspace_2", trigger_workspace_2 }, + { "action.workspace.switched_to_2", workspace_index_is_1 }, + { "action.trigger.prev_workspace", trigger_prev_workspace }, + { "action.workspace.switched_to_1", workspace_index_is_0 }, + { "action.trigger.next_workspace", trigger_next_workspace }, + { "action.workspace.switched_to_2_again", workspace_index_is_1 }, + { "action.trigger.workspace_1", trigger_workspace_1 }, + { "action.workspace.switched_to_1_again", workspace_index_is_0 }, + { "action.trigger.workspace_12_out_of_range", trigger_workspace_12_out_of_range }, + { "action.workspace.out_of_range_ignored", workspace_index_unchanged_at_0 }, + { "action.trigger.show_desktop", trigger_show_desktop }, + { "action.show_desktop.shown", show_desktop_state_is_show }, + { "action.trigger.show_desktop.again", trigger_show_desktop }, + { "action.show_desktop.restored", show_desktop_state_is_normal }, + { "action.trigger.unsupported.zoom", trigger_unsupported }, + { "action.trigger.unknown_value", trigger_unknown }, + { "action.connection.alive_after_ignored", connection_alive }, + { "action.destroy", destroy_action }, + { "action.connection.alive_after_destroy", connection_alive }, +}; + +void test_cleanup(struct test_ctx *ctx) +{ + if (ctx->action) treeland_compositor_action_v1_destroy(ctx->action); + client_disconnect(&ctx->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx = {0}; + test_init(&ctx); + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect to or bind treeland_compositor_action_v1\n"); + test_cleanup(&ctx); + test_finish(&ctx); + return 1; + } + + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const int result = test_add(&ctx, cases[i].name); + if (!cases[i].run(&ctx)) + test_fail(&ctx, result, "assertion failed"); + if (wl_display_roundtrip(ctx.display) < 0) + test_fail(&ctx, result, "Wayland connection failed"); + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + test_finish(&ctx); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-compositor-action-v1/treeland-compositor-action-v1.h b/tests/protocols/treeland-compositor-action-v1/treeland-compositor-action-v1.h new file mode 100644 index 0000000000..ebee10f126 --- /dev/null +++ b/tests/protocols/treeland-compositor-action-v1/treeland-compositor-action-v1.h @@ -0,0 +1,47 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef COMPOSITOR_ACTION_TEST_H +#define COMPOSITOR_ACTION_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +#include "client-connection.h" + +struct treeland_compositor_action_v1; + +#define TEST_MSG_MAX 256 + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +struct test_ctx { + struct client_connection connection; + struct wl_display *display; + + struct treeland_compositor_action_v1 *action; + + struct test_result *results; + int result_count; + int result_cap; +}; + +void test_init(struct test_ctx *ctx); +void test_finish(struct test_ctx *ctx); +int test_add(struct test_ctx *ctx, const char *name); +void test_fail(struct test_ctx *ctx, int idx, const char *fmt, ...); +void test_pass(struct test_ctx *ctx, int idx); + +int test_print_results(struct test_ctx *ctx); +void test_cleanup(struct test_ctx *ctx); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-dde-shell-v2/CMakeLists.txt b/tests/protocols/treeland-dde-shell-v2/CMakeLists.txt new file mode 100644 index 0000000000..f667f2e040 --- /dev/null +++ b/tests/protocols/treeland-dde-shell-v2/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_dde_shell_v2 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-dde-shell-unstable-v2.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-dde-shell-v2.c" +) diff --git a/tests/protocols/treeland-dde-shell-v2/README.md b/tests/protocols/treeland-dde-shell-v2/README.md new file mode 100644 index 0000000000..e01dada78c --- /dev/null +++ b/tests/protocols/treeland-dde-shell-v2/README.md @@ -0,0 +1,61 @@ +# `treeland-dde-shell-v2` 测试规范 + +## 范围 + +- 测试源码:`tests/protocols/treeland-dde-shell-v2/` +- Fixture:headless output、普通 `wl_surface` 和真实 mapped XDG toplevel +- 覆盖等级:**E / P / I**——真实 C 客户端检查 `role` 事件载荷,并读取生产 + `SurfaceWrapper` 的置顶状态与 z 层级;其余元数据与生命周期通过协议对象状态验证。 +- 用户操作通过 fixture 调用与窗口菜单相同的 `SurfaceWrapper::setAlwaysOnTop()`, + 不直接设置协议状态或发送事件;本测试不模拟鼠标点击菜单。 + +v2 适配期间 v1 全局对象保留并行注册;本测试只覆盖 +`dde/treeland-dde-shell-unstable-v2.xml` 的 manager/surface 两个接口。 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | +| --- | --- | --- | +| 创建 | `get_shell_surface(surface)` | 服务端创建 `DDEShellSurfaceV2`,默认 role 为 overlay(值 1) | +| role | `set_role(overlay=1)` | 服务端 role 保持 overlay | +| role(normal) | `set_role(normal=0)` | 服务端 role 切到 normal(回归普通窗口层) | +| 初始通知 | 绑定接口版本 2,创建对象后请求 normal | 客户端先收到初始 overlay,再收到 normal | +| 置顶请求 | `set_role(always_on_top)` | 客户端收到 always_on_top,真实 wrapper 置顶且 z=1 | +| 重复请求 | 再次请求相同 role | 不重复发送通知 | +| 用户取消置顶 | 对生产 wrapper 调用 `setAlwaysOnTop(false)` | role 与通知均为 normal,置顶清除且 z=0 | +| 用户手动置顶 | 对生产 wrapper 调用 `setAlwaysOnTop(true)` | role 与通知均为 always_on_top,z=1 | +| 客户端从 overlay 切换为置顶 | `set_role(always_on_top)` | 切换为 always_on_top,z=1 | +| 请求切换角色 | 从置顶切到 overlay 或 normal | 清除普通置顶标志,实际 z 分别为 2、0,通知与实际角色一致 | +| Overlay 子窗口 | 父窗口切换置顶和普通角色 | 子窗口保持 z=2,且无额外 role 事件 | +| 旧版本兼容 | 绑定接口版本 1,执行既有请求且不安装事件监听器 | 连接正常,不发送版本 2 的 role 事件 | +| 定位 hint | `set_position_hint(output, 42, 24)` | 服务端解析为全局坐标 `positionHint == (42,24)`,cursor hint 为空 | +| 定位 hint(空 output) | `set_position_hint(NULL, 7, 9)` | 以主屏原点为锚点解析,`positionHint == (7,9)` | +| 定位 hint(0,0) | `set_position_hint(NULL, 0, 0)` | `(0,0)` 是合法固定位置,position hint 存在且 cursor hint 为空 | +| 光标 hint | `set_cursor_placement_hint(11, 5)` | `cursorPlacementHint == (11,5)`,且 position hint 被清空(后发请求决定模式) | +| 模式切回 | 再次 `set_position_hint(NULL, 3, 4)` | `positionHint == (3,4)`,cursor hint 清空 | +| skip 位域 | `set_skip_flags(0x7)` 后 `set_skip_flags(0)` | 服务端 skipFlags 依次为 7、0 | +| 键盘焦点 | `set_accept_keyboard_focus(0)` | 服务端 acceptKeyboardFocus 为 false | +| 销毁 | `destroy` 后重新 `get_shell_surface` | 资源销毁后允许重建 | +| 重复创建 | 对同一 `wl_surface` 二次 `get_shell_surface` | 合成器抛出 `already_shell_surface`(服务端错误计数器断言),客户端连接被终止 | + +## 已知边界 + +Treeland 的窗口菜单将 Overlay 窗口的「总在最上」显示为已勾选且禁用。 +客户端仍可通过 `set_role(always_on_top)` 将窗口从 Overlay 切换到普通置顶层。 + +定位 hint 的全局坐标解析依赖 headless 输出位于原点 (0,0),故解析结果与请求坐标一致; +多输出布局下的坐标换算由 `WOutput::position()` 保证。`set_role` 覆盖 normal、overlay 与 always_on_top 三个取值。 + +服务端不在 wl_surface 销毁时自动回收 shell surface(本质是设置 SurfaceWrapper +的协议对象,生命周期随 SurfaceWrapper 走);`ShellHandler::onXdgToplevelSurfaceRemoved` +统一清理未创建 wrapper 场景下残留的 dde-shell 对象。角色、用户置顶状态及真实 z 层级已通过 mapped XDG 窗口验证;skip 布尔量和 +`clientRequstPos`/光标放置的 wrapper 集成仍未覆盖。 + +## TODO + +- TODO: 增加非原点第二 headless 输出,并断言 `set_position_hint(output, x, y)` 换算后的 + 全局坐标(包括 (0,0) 固定位置),以覆盖多输出布局下 `WOutput::position()` / 主屏原点 + 的坐标转换路径;当前单输出 (0,0) fixture 无法捕获相关回归。 +- TODO: 增加 mapped XDG toplevel fixture,断言 `ShellHandler::handleDdeShellSurfaceV2Added()` + 与 `Output` 实际摆放后的真实全局几何(position/cursor 两种模式及其运行时切换);当前用例 + 仅在未映射的普通 `wl_surface` 上读取服务端 hint 状态,未覆盖 wrapper 集成与摆放逻辑。 diff --git a/tests/protocols/treeland-dde-shell-v2/setup.cpp b/tests/protocols/treeland-dde-shell-v2/setup.cpp new file mode 100644 index 0000000000..e57cefaeab --- /dev/null +++ b/tests/protocols/treeland-dde-shell-v2/setup.cpp @@ -0,0 +1,76 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "modules/dde-shell/ddeshellmanagerinterfacev2.h" +#include "server-bridge.h" +#include "core/rootsurfacecontainer.h" +#include "surface/surfacewrapper.h" +#include "core/waylandserver.h" +#include "treeland-dde-shell-v2.h" + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +DDEShellSurfaceV2 *g_shellSurface = nullptr; +DDEShellManagerInterfaceV2 *g_manager = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + auto *manager = find_server_interface(server); + Q_ASSERT(manager); + g_manager = manager; + QObject::connect(manager, &DDEShellManagerInterfaceV2::surfaceCreated, + [](DDEShellSurfaceV2 *surface) { + g_shellSurface = surface; + QObject::connect(surface, &QObject::destroyed, [surface] { + if (g_shellSurface == surface) + g_shellSurface = nullptr; + }); + }); +} + +extern "C" void dde_shell_v2_query_surface_state(void *data) +{ + auto *state = static_cast(data); + *state = {}; + // Read before the g_shellSurface early return: the duplicate-creation + // error case deliberately leaves no tracked shell surface behind. + state->duplicate_errors = g_manager ? g_manager->alreadyShellSurfaceErrorCount() : 0; + if (!g_shellSurface) + return; + + state->role_overlay = g_shellSurface->role() == DDEShellSurfaceV2::Role::OVERLAY; + state->role_normal = g_shellSurface->role() == DDEShellSurfaceV2::Role::NORMAL; + if (auto *wrapper = WaylandServer::instance()->rootSurfaceContainer()->getSurface(g_shellSurface->wSurface())) { + state->wrapper_found = 1; + state->wrapper_always_on_top = wrapper->alwaysOnTop(); + state->wrapper_z = int(wrapper->z()); + } + state->skip_flags = int(g_shellSurface->skipFlags()); + state->accept_keyboard_focus = g_shellSurface->acceptKeyboardFocus(); + + if (const auto position = g_shellSurface->positionHint()) { + state->position_set = 1; + state->position_x = position->x(); + state->position_y = position->y(); + } + if (const auto cursor = g_shellSurface->cursorPlacementHint()) { + state->cursor_set = 1; + state->cursor_x = cursor->x(); + state->cursor_y = cursor->y(); + } + state->duplicate_errors = g_manager ? g_manager->alreadyShellSurfaceErrorCount() : 0; +} + +extern "C" void dde_shell_v2_user_set_always_on_top(void *data) +{ + if (!g_shellSurface) + return; + auto *wrapper = WaylandServer::instance()->rootSurfaceContainer()->getSurface(g_shellSurface->wSurface()); + if (wrapper) + wrapper->setAlwaysOnTop(*static_cast(data) != 0); +} diff --git a/tests/protocols/treeland-dde-shell-v2/treeland-dde-shell-v2.c b/tests/protocols/treeland-dde-shell-v2/treeland-dde-shell-v2.c new file mode 100644 index 0000000000..343757f9de --- /dev/null +++ b/tests/protocols/treeland-dde-shell-v2/treeland-dde-shell-v2.c @@ -0,0 +1,421 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-dde-shell-v2.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "treeland-dde-shell-unstable-v2-client-protocol.h" + +#include +#include +#include +#include +#include + +extern void dde_shell_v2_query_surface_state(void *data); + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); +}; + +void test_init(struct test_ctx *ctx) +{ + ctx->result_cap = 32; + ctx->results = calloc(ctx->result_cap, sizeof(*ctx->results)); +} + +void test_finish(struct test_ctx *ctx) +{ + free(ctx->results); +} + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +void test_pass(struct test_ctx *ctx, int index) +{ + ctx->results[index].failed = 0; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->display = ctx->connection.display; + ctx->compositor = client_bind(&ctx->connection, "wl_compositor", &wl_compositor_interface, 1); + ctx->seat = client_bind(&ctx->connection, "wl_seat", &wl_seat_interface, 1); + ctx->output = client_bind(&ctx->connection, "wl_output", &wl_output_interface, 1); + ctx->manager = client_bind(&ctx->connection, "treeland_dde_shell_manager_v2", + &treeland_dde_shell_manager_v2_interface, 1); + // Every bound resource is required by some case; a partial bind would + // silently steer e.g. the output-anchored position test to the null path. + return ctx->compositor && ctx->seat && ctx->output && ctx->manager != NULL; +} + +static int create_shell_surface(struct test_ctx *ctx) +{ + if (!ctx->compositor) + return 0; + ctx->test_surface = wl_compositor_create_surface(ctx->compositor); + ctx->shell_surface = treeland_dde_shell_manager_v2_get_shell_surface(ctx->manager, + ctx->test_surface); + return ctx->test_surface && ctx->shell_surface; +} + +static int read_shell_surface_state(struct test_ctx *ctx, struct dde_shell_surface_v2_state *state) +{ + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + memset(state, 0, sizeof(*state)); + return invoke_on_server_thread(dde_shell_v2_query_surface_state, state); +} + +static int set_surface_role(struct test_ctx *ctx) +{ + struct dde_shell_surface_v2_state state; + treeland_dde_shell_surface_v2_set_role(ctx->shell_surface, + TREELAND_DDE_SHELL_SURFACE_V2_ROLE_OVERLAY); + return read_shell_surface_state(ctx, &state) && state.role_overlay && !state.role_normal; +} + +static int set_surface_role_normal(struct test_ctx *ctx) +{ + struct dde_shell_surface_v2_state state; + treeland_dde_shell_surface_v2_set_role(ctx->shell_surface, + TREELAND_DDE_SHELL_SURFACE_V2_ROLE_NORMAL); + return read_shell_surface_state(ctx, &state) && state.role_normal && !state.role_overlay; +} + +static int set_position_hint(struct test_ctx *ctx) +{ + // TODO: this asserts only the stored hint on an unmapped wl_surface; add a + // mapped XDG fixture asserting the actual global geometry produced by + // ShellHandler::handleDdeShellSurfaceV2Added() and Output placement, and a + // non-origin second output to cover WOutput::position() conversion. + struct dde_shell_surface_v2_state state; + treeland_dde_shell_surface_v2_set_position_hint(ctx->shell_surface, ctx->output, 42, 24); + return read_shell_surface_state(ctx, &state) + && state.position_set && state.position_x == 42 && state.position_y == 24 + && !state.cursor_set; +} + +static int set_position_hint_null_output(struct test_ctx *ctx) +{ + struct dde_shell_surface_v2_state state; + treeland_dde_shell_surface_v2_set_position_hint(ctx->shell_surface, NULL, 7, 9); + return read_shell_surface_state(ctx, &state) + && state.position_set && state.position_x == 7 && state.position_y == 9; +} + +// (0,0) is a valid fixed position (output origin / global origin), it must +// register as a present hint and not be swallowed as "no request". +static int set_position_hint_zero(struct test_ctx *ctx) +{ + struct dde_shell_surface_v2_state state; + treeland_dde_shell_surface_v2_set_position_hint(ctx->shell_surface, NULL, 0, 0); + return read_shell_surface_state(ctx, &state) + && state.position_set && state.position_x == 0 && state.position_y == 0 + && !state.cursor_set; +} + +static int set_cursor_placement_hint(struct test_ctx *ctx) +{ + struct dde_shell_surface_v2_state state; + treeland_dde_shell_surface_v2_set_cursor_placement_hint(ctx->shell_surface, 11, 5); + return read_shell_surface_state(ctx, &state) + && state.cursor_set && state.cursor_x == 11 && state.cursor_y == 5 + && !state.position_set; +} + +static int placement_mode_switches_back(struct test_ctx *ctx) +{ + struct dde_shell_surface_v2_state state; + treeland_dde_shell_surface_v2_set_position_hint(ctx->shell_surface, NULL, 3, 4); + return read_shell_surface_state(ctx, &state) + && state.position_set && state.position_x == 3 && state.position_y == 4 + && !state.cursor_set; +} + +static int set_skip_flags(struct test_ctx *ctx) +{ + struct dde_shell_surface_v2_state state; + const uint32_t all_flags = TREELAND_DDE_SHELL_SURFACE_V2_SKIP_FLAG_SWITCHER + | TREELAND_DDE_SHELL_SURFACE_V2_SKIP_FLAG_DOCK_PREVIEW + | TREELAND_DDE_SHELL_SURFACE_V2_SKIP_FLAG_MULTITASK_VIEW; + treeland_dde_shell_surface_v2_set_skip_flags(ctx->shell_surface, all_flags); + return read_shell_surface_state(ctx, &state) && state.skip_flags == (int)all_flags; +} + +static int clear_skip_flags(struct test_ctx *ctx) +{ + struct dde_shell_surface_v2_state state; + treeland_dde_shell_surface_v2_set_skip_flags(ctx->shell_surface, 0); + return read_shell_surface_state(ctx, &state) && state.skip_flags == 0; +} + +static int set_keyboard_focus(struct test_ctx *ctx) +{ + struct dde_shell_surface_v2_state state; + treeland_dde_shell_surface_v2_set_accept_keyboard_focus(ctx->shell_surface, 0); + return read_shell_surface_state(ctx, &state) && !state.accept_keyboard_focus; +} + +static int shell_surface_state(struct test_ctx *ctx) +{ + (void)ctx; + struct dde_shell_surface_v2_state state; + // The previous set_role.normal case left the role at normal. + return invoke_on_server_thread(dde_shell_v2_query_surface_state, &state) + && state.role_normal && !state.accept_keyboard_focus; +} + +static int destroy_shell_surface(struct test_ctx *ctx) +{ + treeland_dde_shell_surface_v2_destroy(ctx->shell_surface); + ctx->shell_surface = NULL; + return wl_display_roundtrip(ctx->display) >= 0; +} + +static int recreate_after_destroy(struct test_ctx *ctx) +{ + ctx->shell_surface = treeland_dde_shell_manager_v2_get_shell_surface(ctx->manager, + ctx->test_surface); + return ctx->shell_surface != NULL && wl_display_roundtrip(ctx->display) >= 0; +} + +static int duplicate_shell_surface_error(struct test_ctx *ctx) +{ + treeland_dde_shell_manager_v2_get_shell_surface(ctx->manager, ctx->test_surface); + // The compositor raises already_shell_surface, which kills the connection: + // the roundtrip must fail. The client cannot reliably read back the code + // (the server closes the connection and the IO error masks it in + // wl_display_get_protocol_error), so the exact error path is asserted + // server-side via the error counter. + if (wl_display_roundtrip(ctx->display) >= 0) + return 0; + + struct dde_shell_surface_v2_state state; + return invoke_on_server_thread(dde_shell_v2_query_surface_state, &state) + && state.duplicate_errors == 1; +} + +static const struct test_case cases[] = { + { "manager.get_shell_surface", create_shell_surface }, + { "shell_surface.set_role", set_surface_role }, + { "shell_surface.set_role.normal", set_surface_role_normal }, + { "shell_surface.set_position_hint", set_position_hint }, + { "shell_surface.set_position_hint.null_output", set_position_hint_null_output }, + { "shell_surface.set_position_hint.zero", set_position_hint_zero }, + { "shell_surface.set_cursor_placement_hint", set_cursor_placement_hint }, + { "shell_surface.placement_mode_switches_back", placement_mode_switches_back }, + { "shell_surface.set_skip_flags", set_skip_flags }, + { "shell_surface.clear_skip_flags", clear_skip_flags }, + { "shell_surface.set_accept_keyboard_focus", set_keyboard_focus }, + { "server.shell_surface_state", shell_surface_state }, + { "shell_surface.destroy", destroy_shell_surface }, + { "manager.recreate_after_destroy", recreate_after_destroy }, + // Must stay last: the expected protocol error tears the connection down. + { "manager.get_shell_surface.duplicate_error", duplicate_shell_surface_error }, +}; + +void test_cleanup(struct test_ctx *ctx) +{ + if (ctx->shell_surface) + treeland_dde_shell_surface_v2_destroy(ctx->shell_surface); + if (ctx->manager) + treeland_dde_shell_manager_v2_destroy(ctx->manager); + client_disconnect(&ctx->connection); +} + + +struct role_client { + struct treeland_dde_shell_manager_v2 *manager; + struct treeland_dde_shell_surface_v2 *surface; + uint32_t initial_role; + uint32_t roles[32]; + unsigned count; + bool overflow; +}; + +static void handle_role(void *data, struct treeland_dde_shell_surface_v2 *surface, uint32_t role) +{ + (void)surface; + struct role_client *client = data; + if (client->count >= sizeof(client->roles) / sizeof(client->roles[0])) { + client->overflow = true; + return; + } + client->roles[client->count++] = role; +} + +static const struct treeland_dde_shell_surface_v2_listener role_listener = { + .role = handle_role, +}; + +static int setup_role_surface(struct wl_surface *surface, void *data) +{ + struct role_client *client = data; + client->surface = treeland_dde_shell_manager_v2_get_shell_surface(client->manager, surface); + if (!client->surface) + return 0; + treeland_dde_shell_surface_v2_add_listener(client->surface, &role_listener, client); + treeland_dde_shell_surface_v2_set_role(client->surface, client->initial_role); + return 1; +} + +// Window z layers are 0 for normal, 1 for always-on-top, and 2 for overlay. +static int check_role(struct client_connection *connection, struct role_client *client, + uint32_t expected, unsigned count, int z) +{ + struct dde_shell_surface_v2_state state = {0}; + if (wl_display_roundtrip(connection->display) < 0 + || !invoke_on_server_thread(dde_shell_v2_query_surface_state, &state)) + return 0; + return !client->overflow && count > 0 && client->count == count && client->roles[count - 1] == expected + && state.wrapper_found && state.wrapper_z == z + && state.wrapper_always_on_top == (expected == TREELAND_DDE_SHELL_SURFACE_V2_ROLE_ALWAYS_ON_TOP); +} + +extern void dde_shell_v2_user_set_always_on_top(void *data); + +static int test_role_sync(const char *socket_name) +{ + struct client_connection connection = {0}; + struct xdg_toplevel_client toplevel = {0}; + struct xdg_toplevel_client child_toplevel = {0}; + struct role_client client = {.initial_role = TREELAND_DDE_SHELL_SURFACE_V2_ROLE_NORMAL}; + struct role_client child = {.initial_role = TREELAND_DDE_SHELL_SURFACE_V2_ROLE_OVERLAY}; + int success = 0; + int enabled; +#define CHECK_ROLE_CASE(name, expression) do { \ + if (!(expression)) { fprintf(stderr, "[FAIL] %s\n", name); goto cleanup; } \ + printf("[PASS] %s\n", name); \ +} while (0) + CHECK_ROLE_CASE("role.connect", client_connect(&connection, socket_name)); + client.manager = client_bind(&connection, "treeland_dde_shell_manager_v2", + &treeland_dde_shell_manager_v2_interface, 2); + CHECK_ROLE_CASE("role.bind_version_2", client.manager + && treeland_dde_shell_manager_v2_get_version(client.manager) == 2); + CHECK_ROLE_CASE("role.map_normal", xdg_toplevel_client_create_with_surface_setup( + &connection, &toplevel, setup_role_surface, &client)); + CHECK_ROLE_CASE("role.initial_overlay_then_normal", + check_role(&connection, &client, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_NORMAL, 2, 0) + && client.roles[0] == TREELAND_DDE_SHELL_SURFACE_V2_ROLE_OVERLAY); + + treeland_dde_shell_surface_v2_set_role(client.surface, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_ALWAYS_ON_TOP); + CHECK_ROLE_CASE("role.client_always_on_top", + check_role(&connection, &client, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_ALWAYS_ON_TOP, 3, 1)); + treeland_dde_shell_surface_v2_set_role(client.surface, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_ALWAYS_ON_TOP); + CHECK_ROLE_CASE("role.unchanged_no_duplicate", + check_role(&connection, &client, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_ALWAYS_ON_TOP, 3, 1)); + + enabled = 0; + CHECK_ROLE_CASE("role.user_unpin", + invoke_on_server_thread(dde_shell_v2_user_set_always_on_top, &enabled) + && check_role(&connection, &client, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_NORMAL, 4, 0)); + enabled = 1; + CHECK_ROLE_CASE("role.user_pin", + invoke_on_server_thread(dde_shell_v2_user_set_always_on_top, &enabled) + && check_role(&connection, &client, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_ALWAYS_ON_TOP, 5, 1)); + + treeland_dde_shell_surface_v2_set_role(client.surface, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_OVERLAY); + CHECK_ROLE_CASE("role.overlay_clears_pin", + check_role(&connection, &client, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_OVERLAY, 6, 2)); + treeland_dde_shell_surface_v2_set_role(client.surface, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_ALWAYS_ON_TOP); + CHECK_ROLE_CASE("role.client_pin_from_overlay", + check_role(&connection, &client, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_ALWAYS_ON_TOP, 7, 1)); + treeland_dde_shell_surface_v2_set_role(client.surface, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_NORMAL); + CHECK_ROLE_CASE("role.normal_clears_pin", + check_role(&connection, &client, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_NORMAL, 8, 0)); + + child.manager = client.manager; + CHECK_ROLE_CASE("role.map_overlay_child", xdg_toplevel_client_create_with_surface_setup( + &connection, &child_toplevel, setup_role_surface, &child)); + xdg_toplevel_set_parent(child_toplevel.toplevel, toplevel.toplevel); + CHECK_ROLE_CASE("role.child_overlay", + check_role(&connection, &child, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_OVERLAY, 1, 2)); + + treeland_dde_shell_surface_v2_set_role(client.surface, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_ALWAYS_ON_TOP); + CHECK_ROLE_CASE("role.parent_pin_keeps_child_overlay", + check_role(&connection, &child, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_OVERLAY, 1, 2)); + treeland_dde_shell_surface_v2_set_role(client.surface, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_NORMAL); + CHECK_ROLE_CASE("role.parent_unpin_keeps_child_overlay", + check_role(&connection, &child, TREELAND_DDE_SHELL_SURFACE_V2_ROLE_OVERLAY, 1, 2)); + success = 1; +cleanup: + if (child.surface) + treeland_dde_shell_surface_v2_destroy(child.surface); + xdg_toplevel_client_destroy(&child_toplevel); + if (client.surface) + treeland_dde_shell_surface_v2_destroy(client.surface); + xdg_toplevel_client_destroy(&toplevel); + if (client.manager) + treeland_dde_shell_manager_v2_destroy(client.manager); + if (connection.display) + wl_display_roundtrip(connection.display); + client_disconnect(&connection); + return success; +#undef CHECK_ROLE_CASE +} + +int protocol_test_run(const char *socket_name) +{ + if (!test_role_sync(socket_name)) + return 1; + struct test_ctx ctx = {0}; + test_init(&ctx); + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect to or bind treeland_dde_shell_manager_v2\n"); + test_cleanup(&ctx); + test_finish(&ctx); + return 1; + } + + const size_t total_cases = sizeof(cases) / sizeof(cases[0]); + for (size_t i = 0; i < total_cases; ++i) { + const int result = test_add(&ctx, cases[i].name); + if (!cases[i].run(&ctx)) + test_fail(&ctx, result, "assertion failed"); + // The final case expects the protocol error that kills the connection. + if (i + 1 < total_cases && wl_display_roundtrip(ctx.display) < 0) + test_fail(&ctx, result, "Wayland connection failed"); + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + test_finish(&ctx); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-dde-shell-v2/treeland-dde-shell-v2.h b/tests/protocols/treeland-dde-shell-v2/treeland-dde-shell-v2.h new file mode 100644 index 0000000000..482cf096d7 --- /dev/null +++ b/tests/protocols/treeland-dde-shell-v2/treeland-dde-shell-v2.h @@ -0,0 +1,68 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef DDE_SHELL_V2_TEST_H +#define DDE_SHELL_V2_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +#include "client-connection.h" + +#define TEST_MSG_MAX 256 + +struct dde_shell_surface_v2_state { + int position_x; + int position_y; + int position_set; + int cursor_x; + int cursor_y; + int cursor_set; + int role_overlay; + int role_normal; + int wrapper_found; + int wrapper_always_on_top; + int wrapper_z; + int skip_flags; + int accept_keyboard_focus; + int duplicate_errors; +}; + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +struct test_ctx { + struct client_connection connection; + struct wl_display *display; + + struct wl_compositor *compositor; + struct wl_seat *seat; + struct wl_output *output; + + struct treeland_dde_shell_manager_v2 *manager; + struct treeland_dde_shell_surface_v2 *shell_surface; + struct wl_surface *test_surface; + + struct test_result *results; + int result_count; + int result_cap; +}; + +void test_init(struct test_ctx *ctx); +void test_finish(struct test_ctx *ctx); +int test_add(struct test_ctx *ctx, const char *name); +void test_fail(struct test_ctx *ctx, int idx, const char *fmt, ...); +void test_pass(struct test_ctx *ctx, int idx); + +int test_print_results(struct test_ctx *ctx); +void test_cleanup(struct test_ctx *ctx); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-ddm-v1/CMakeLists.txt b/tests/protocols/treeland-ddm-v1/CMakeLists.txt new file mode 100644 index 0000000000..808df73515 --- /dev/null +++ b/tests/protocols/treeland-ddm-v1/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_ddm_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-ddm-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-ddm-v1.c" +) diff --git a/tests/protocols/treeland-ddm-v1/README.md b/tests/protocols/treeland-ddm-v1/README.md new file mode 100644 index 0000000000..ef09fa3ad6 --- /dev/null +++ b/tests/protocols/treeland-ddm-v1/README.md @@ -0,0 +1,23 @@ +# `treeland-ddm-v1` 测试规范 + +## 范围 + +- 测试源码:`tests/protocols/treeland-ddm-v1/` +- Fixture:协议 fixture。 +- 覆盖等级:**I**。 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | +| --- | --- | --- | +| 全局兼容性 | 以 v1 绑定、请求 v2 | global 宣告 v1,绑定版本被限制为 v1 | +| 连接生命周期 | 绑定、连接第二客户端、断开主客户端 | 生产 `DDMInterfaceV1::isConnected()` 跟随主客户端生命周期 | +| 初始流量 | 绑定 global | 没有未请求的事件 | + +## 生产结果 + +验证的是生产接口的连接状态,而非仅仅能够绑定 global。 + +## 已知边界 / 下一项结果 + +目前该测试没有额外 DDM 业务请求;协议未来增加请求时,应断言其业务消费者的结果。 diff --git a/tests/protocols/treeland-ddm-v1/setup.cpp b/tests/protocols/treeland-ddm-v1/setup.cpp new file mode 100644 index 0000000000..07924aa132 --- /dev/null +++ b/tests/protocols/treeland-ddm-v1/setup.cpp @@ -0,0 +1,24 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "modules/ddm/ddminterfacev1.h" +#include "server-bridge.h" + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +DDMInterfaceV1 *g_ddm = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + g_ddm = find_server_interface(server); +} + +extern "C" void ddm_check_is_connected(void *data) +{ + if (!data) + return; + *static_cast(data) = (g_ddm && g_ddm->isConnected()) ? 1 : 0; +} diff --git a/tests/protocols/treeland-ddm-v1/treeland-ddm-v1.c b/tests/protocols/treeland-ddm-v1/treeland-ddm-v1.c new file mode 100644 index 0000000000..0e525c1296 --- /dev/null +++ b/tests/protocols/treeland-ddm-v1/treeland-ddm-v1.c @@ -0,0 +1,238 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-ddm-v1.h" +#include "server-bridge-api.h" +#include "treeland-ddm-v1-client-protocol.h" + +#include +#include +#include +#include + +extern void ddm_check_is_connected(void *data); + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); +}; + +void test_init(struct test_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); + ctx->result_cap = 32; + ctx->results = calloc(ctx->result_cap, sizeof(*ctx->results)); +} + +void test_destroy(struct test_ctx *ctx) +{ + free(ctx->results); + memset(ctx, 0, sizeof(*ctx)); +} + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +void test_pass(struct test_ctx *ctx, int index) +{ + ctx->results[index].failed = 0; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +static void switch_to_vt(void *data, struct treeland_ddm_v1 *ddm, int32_t vtnr) +{ + (void)ddm; + (void)vtnr; + ((struct test_ctx *)data)->switch_to_vt_received = 1; +} + +static void acquire_vt(void *data, struct treeland_ddm_v1 *ddm, int32_t vtnr) +{ + (void)ddm; + (void)vtnr; + ((struct test_ctx *)data)->acquire_vt_received = 1; +} + +static const struct treeland_ddm_v1_listener ddm_listener = { + .switch_to_vt = switch_to_vt, + .acquire_vt = acquire_vt, +}; + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->display = ctx->connection.display; + ctx->socket_name = socket_name; + return 1; +} + +static int registry_has_ddm(struct test_ctx *ctx) +{ + for (uint32_t i = 0; i < ctx->connection.global_count; ++i) { + if (strcmp(ctx->connection.globals[i].interface, "treeland_ddm_v1") == 0) + return 1; + } + return 0; +} + +static int registry_advertises_version_1(struct test_ctx *ctx) +{ + for (uint32_t i = 0; i < ctx->connection.global_count; ++i) { + if (strcmp(ctx->connection.globals[i].interface, "treeland_ddm_v1") == 0) + return ctx->connection.globals[i].version == 1; + } + return 0; +} + +static int bind_requesting_v2_clamps_to_v1(struct test_ctx *ctx) +{ + + struct treeland_ddm_v1 *ddm = client_bind(&ctx->connection, "treeland_ddm_v1", + &treeland_ddm_v1_interface, 2); + if (!ddm) + return 0; + const int version = (int)treeland_ddm_v1_get_version(ddm); + wl_proxy_destroy((struct wl_proxy *)ddm); + return version == 1; +} + +static int bind_at_advertised_v1(struct test_ctx *ctx) +{ + ctx->ddm = client_bind(&ctx->connection, "treeland_ddm_v1", + &treeland_ddm_v1_interface, 1); + if (!ctx->ddm) + return 0; + ctx->bound_version = (int)treeland_ddm_v1_get_version(ctx->ddm); + treeland_ddm_v1_add_listener(ctx->ddm, &ddm_listener, ctx); + return ctx->bound_version == 1; +} + +static int check_is_connected(struct test_ctx *ctx) +{ + (void)ctx; + int connected = 0; + if (!invoke_on_server_thread(ddm_check_is_connected, &connected)) + return 0; + return connected; +} + +static int is_connected_with_one_client(struct test_ctx *ctx) +{ + return check_is_connected(ctx); +} + +static int second_client_keeps_connected(struct test_ctx *ctx) +{ + if (!client_connect(&ctx->aux, ctx->socket_name)) + return 0; + struct treeland_ddm_v1 *aux_ddm = client_bind(&ctx->aux, "treeland_ddm_v1", + &treeland_ddm_v1_interface, 1); + if (!aux_ddm) + return 0; + + if (wl_display_roundtrip(ctx->aux.display) < 0) + return 0; + return check_is_connected(ctx); +} + +static int no_events_received(struct test_ctx *ctx) +{ + return !ctx->switch_to_vt_received && !ctx->acquire_vt_received; +} + +static int is_connected_false_after_all_clients_gone(struct test_ctx *ctx) +{ + + if (ctx->ddm) { + wl_proxy_destroy((struct wl_proxy *)ctx->ddm); + ctx->ddm = NULL; + } + client_disconnect(&ctx->connection); + ctx->display = NULL; + client_disconnect(&ctx->aux); + + if (!client_connect(&ctx->checker, ctx->socket_name)) + return 0; + const int connected = check_is_connected(ctx); + client_disconnect(&ctx->checker); + return !connected; +} + +static const struct test_case cases[] = { + { "registry.advertises_treeland_ddm_v1", registry_has_ddm }, + { "registry.advertises_version_1", registry_advertises_version_1 }, + { "bind.requesting_v2_clamps_to_advertised_v1", bind_requesting_v2_clamps_to_v1 }, + { "bind.at_advertised_v1", bind_at_advertised_v1 }, + { "manager.isConnected_with_one_client", is_connected_with_one_client }, + { "manager.isConnected_with_two_clients", second_client_keeps_connected }, + { "events.none_after_bind", no_events_received }, + { "manager.isConnected_false_after_all_clients_gone", is_connected_false_after_all_clients_gone }, +}; + +void test_cleanup(struct test_ctx *ctx) +{ + + if (ctx->ddm) + wl_proxy_destroy((struct wl_proxy *)ctx->ddm); + client_disconnect(&ctx->checker); + client_disconnect(&ctx->aux); + client_disconnect(&ctx->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx; + test_init(&ctx); + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect to treeland_ddm_v1 test server\n"); + test_cleanup(&ctx); + test_destroy(&ctx); + return 1; + } + + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const int result = test_add(&ctx, cases[i].name); + if (!cases[i].run(&ctx)) + test_fail(&ctx, result, "assertion failed"); + + if (ctx.display && wl_display_roundtrip(ctx.display) < 0) + test_fail(&ctx, result, "Wayland connection failed"); + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + test_destroy(&ctx); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-ddm-v1/treeland-ddm-v1.h b/tests/protocols/treeland-ddm-v1/treeland-ddm-v1.h new file mode 100644 index 0000000000..ecfe2da111 --- /dev/null +++ b/tests/protocols/treeland-ddm-v1/treeland-ddm-v1.h @@ -0,0 +1,55 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef DDM_V1_TEST_H +#define DDM_V1_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +#include "client-connection.h" + +#define TEST_MSG_MAX 256 + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +struct test_ctx { + struct client_connection connection; + struct wl_display *display; + + const char *socket_name; + + struct client_connection aux; + + struct client_connection checker; + + struct treeland_ddm_v1 *ddm; + int bound_version; + + int switch_to_vt_received; + int acquire_vt_received; + + struct test_result *results; + int result_count; + int result_cap; +}; + +void test_init(struct test_ctx *ctx); +void test_destroy(struct test_ctx *ctx); +int test_add(struct test_ctx *ctx, const char *name); +void test_fail(struct test_ctx *ctx, int idx, const char *fmt, ...); +void test_pass(struct test_ctx *ctx, int idx); + +int test_print_results(struct test_ctx *ctx); +void test_cleanup(struct test_ctx *ctx); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-decoration-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-decoration-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..9c86d0b4a8 --- /dev/null +++ b/tests/protocols/treeland-decoration-unstable-v1/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME treeland_decoration_unstable_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-decoration-unstable-v1.xml" + EXTRA_XMLS + "${WAYLAND_PROTOCOLS_DATADIR}/unstable/xdg-decoration/xdg-decoration-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-decoration-unstable-v1.c" +) diff --git a/tests/protocols/treeland-decoration-unstable-v1/README.md b/tests/protocols/treeland-decoration-unstable-v1/README.md new file mode 100644 index 0000000000..5f93b546e2 --- /dev/null +++ b/tests/protocols/treeland-decoration-unstable-v1/README.md @@ -0,0 +1,15 @@ +# decoration-unstable-v1 + +覆盖等级:E。 + +测试创建并映射真实 xdg toplevel,创建 decoration context 后发送 +`set_corner_radius(12)`,再在 compositor 线程回读同一 `SurfaceWrapper::radius()`; +随后发送 `set_corner_radius(0)` 并断言回读值为 0(0 即无圆角,不回退默认值)。 +因此断言的是生产窗口状态,而非 request 仅能派发。 + +同一 toplevel 随后在最大化状态下切换 SSD 标题栏:SSD 标题栏出现时客户端收到的 +configure 必须是最大化矩形减去标题栏高度,通过 `treeland-decoration-unstable-v1` +隐藏标题栏后必须回到整个最大化矩形,再恢复显示标题栏后又必须缩回一个标题栏。 +SSD 标题栏在最大化之后出现、消失或恢复,都不能留下按旧 padding 计算的 configure, +否则窗口会正好高/矮一个标题栏。 +Tiling / Fullscreen 状态、shadow、border 和协议错误路径仍未覆盖。 diff --git a/tests/protocols/treeland-decoration-unstable-v1/setup.cpp b/tests/protocols/treeland-decoration-unstable-v1/setup.cpp new file mode 100644 index 0000000000..1d3b19b39c --- /dev/null +++ b/tests/protocols/treeland-decoration-unstable-v1/setup.cpp @@ -0,0 +1,49 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "server-bridge.h" +#include "treeland-decoration-unstable-v1.h" + +#include "core/shellhandler.h" +#include "modules/decoration/decorationmanagerinterfacev1.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" + +#include "animationconfig.hpp" + +#include + +namespace { +SurfaceWrapper *g_toplevel = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + Q_ASSERT(find_server_interface(server)); + // Apply state geometry immediately: these cases assert configure sizes, not animation. + if (auto *animation = server->animationConfig()) { + animation->setMaximize(false); + animation->setFullscreen(false); + animation->setRestoreWindow(false); + } + add_headless_output(server->backend(), false); + QObject::connect(server->shellHandler(), &ShellHandler::surfaceWrapperAdded, server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() == SurfaceWrapper::Type::XdgToplevel) + g_toplevel = wrapper; + }); +} + +extern "C" void decoration_read_server_state(void *data) +{ + auto *state = static_cast(data); + *state = {}; + if (!g_toplevel) + return; + + state->valid = 1; + state->radius = g_toplevel->radius(); + const QRectF maximized = g_toplevel->maximizedGeometry(); + state->maximized_width = maximized.width(); + state->maximized_height = maximized.height(); + state->titlebar_height = g_toplevel->surfaceItem()->topPadding(); +} diff --git a/tests/protocols/treeland-decoration-unstable-v1/treeland-decoration-unstable-v1.c b/tests/protocols/treeland-decoration-unstable-v1/treeland-decoration-unstable-v1.c new file mode 100644 index 0000000000..7110fa5acb --- /dev/null +++ b/tests/protocols/treeland-decoration-unstable-v1/treeland-decoration-unstable-v1.c @@ -0,0 +1,204 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-3.0-only +#include "client-connection.h" +#include "server-bridge-api.h" +#include "treeland-decoration-unstable-v1.h" +#include "xdg-toplevel-client.h" +#include "treeland-decoration-unstable-v1-client-protocol.h" +#include "xdg-decoration-unstable-v1-client-protocol.h" + +#include + +struct decoration_mode_state { + uint32_t mode; + int received; +}; + +static void decoration_configure(void *data, + struct zxdg_toplevel_decoration_v1 *decoration, + uint32_t mode) +{ + (void)decoration; + struct decoration_mode_state *state = data; + state->mode = mode; + state->received = 1; +} + +static const struct zxdg_toplevel_decoration_v1_listener decoration_listener = { + .configure = decoration_configure, +}; + +// The compositor answers set_mode with a configure; wait for it before the next step. +static struct zxdg_toplevel_decoration_v1 *request_decoration( + struct client_connection *connection, + struct zxdg_decoration_manager_v1 *manager, + struct xdg_toplevel *toplevel, + uint32_t mode, + struct decoration_mode_state *state) +{ + struct zxdg_toplevel_decoration_v1 *decoration = + zxdg_decoration_manager_v1_get_toplevel_decoration(manager, toplevel); + if (!decoration) + return NULL; + zxdg_toplevel_decoration_v1_add_listener(decoration, &decoration_listener, state); + zxdg_toplevel_decoration_v1_set_mode(decoration, mode); + for (int i = 0; i < 32 && !state->received; ++i) { + if (wl_display_roundtrip(connection->display) < 0) + break; + } + return decoration; +} + +static int read_server_state(struct decoration_server_state *state) +{ + if (!invoke_on_server_thread(decoration_read_server_state, state) || !state->valid) { + fprintf(stderr, "decoration: server state unavailable\n"); + return 1; + } + return 0; +} + +// A maximized window keeps its frame on the rect: only the height gives up the title bar. +static int expect_maximized_configure(struct client_connection *connection, + struct xdg_toplevel_client *toplevel, + const char *step) +{ + // Bounded wait: a compositor that never corrects the size must fail, not hang. + for (int i = 0; i < 32; ++i) { + struct decoration_server_state state = { 0 }; + if (read_server_state(&state)) + return 1; + if (toplevel->configure_width == state.maximized_width + && toplevel->configure_height == state.maximized_height - state.titlebar_height) + return 0; + if (wl_display_roundtrip(connection->display) < 0) + return 1; + } + struct decoration_server_state state = { 0 }; + if (read_server_state(&state)) + return 1; + fprintf(stderr, + "decoration: configure %dx%d after %s, expected %dx%d " + "(maximized %dx%d, title bar %d)\n", + toplevel->configure_width, toplevel->configure_height, step, + state.maximized_width, state.maximized_height - state.titlebar_height, + state.maximized_width, state.maximized_height, state.titlebar_height); + return 1; +} + +// Hide or show the title bar and wait until the server side really did it. +static int set_titlebar_mode(struct client_connection *connection, + struct treeland_decoration_context_v1 *context, + uint32_t mode, + int32_t expectedHeight) +{ + treeland_decoration_context_v1_set_titlebar_mode(context, mode); + if (wl_display_roundtrip(connection->display) < 0) + return 1; + for (int i = 0; i < 32; ++i) { + struct decoration_server_state state = { 0 }; + if (read_server_state(&state)) + return 1; + if ((expectedHeight == 0 && state.titlebar_height == 0) + || (expectedHeight > 0 && state.titlebar_height == expectedHeight)) + return 0; + if (wl_display_roundtrip(connection->display) < 0) + return 1; + } + fprintf(stderr, "decoration: title bar padding did not become %d\n", expectedHeight); + return 1; +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + struct xdg_toplevel_client toplevel = { 0 }; + if (!client_connect(&connection, socket_name) + || !xdg_toplevel_client_create_pending(&connection, &toplevel)) + return 1; + struct treeland_decoration_manager_v1 *manager = client_bind(&connection, + "treeland_decoration_manager_v1", &treeland_decoration_manager_v1_interface, 1); + if (!manager) { + fprintf(stderr, "decoration: manager missing\n"); + return 1; + } + struct treeland_decoration_context_v1 *context = + treeland_decoration_manager_v1_get_decoration_context(manager, toplevel.surface); + if (!context) { + fprintf(stderr, "decoration: context creation failed\n"); + return 1; + } + treeland_decoration_context_v1_set_corner_radius(context, 12); + if (wl_display_roundtrip(connection.display) < 0) + return 1; + struct decoration_server_state state = { 0 }; + if (read_server_state(&state)) + return 1; + if (state.radius != 12.0) { + fprintf(stderr, "decoration: corner radius was not applied (radius=%g)\n", state.radius); + return 1; + } + + // 0 means square corners, not "fall back to the compositor default radius". + treeland_decoration_context_v1_set_corner_radius(context, 0); + if (wl_display_roundtrip(connection.display) < 0) + return 1; + state = (struct decoration_server_state){ 0 }; + if (read_server_state(&state)) + return 1; + if (state.radius != 0.0) { + fprintf(stderr, "decoration: radius 0 was not applied (radius=%g)\n", state.radius); + return 1; + } + + // Restore maximized: the bar only lands once the toplevel initializes, after a first apply. + struct zxdg_decoration_manager_v1 *decorationManager = client_bind(&connection, + "zxdg_decoration_manager_v1", &zxdg_decoration_manager_v1_interface, 1); + if (!decorationManager) { + fprintf(stderr, "decoration: xdg-decoration manager missing\n"); + return 1; + } + xdg_toplevel_set_maximized(toplevel.toplevel); + struct decoration_mode_state mode = { 0 }; + struct zxdg_toplevel_decoration_v1 *decoration = + request_decoration(&connection, decorationManager, toplevel.toplevel, + ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE, &mode); + if (!decoration || mode.mode != ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE) { + fprintf(stderr, "decoration: server-side decoration not negotiated (received=%d mode=%u)\n", + mode.received, mode.mode); + return 1; + } + if (!xdg_toplevel_client_complete_map(&connection, &toplevel)) + return 1; + if (read_server_state(&state)) + return 1; + if (state.titlebar_height <= 0) { + fprintf(stderr, "decoration: server-side decoration drew no title bar\n"); + return 1; + } + if (expect_maximized_configure(&connection, &toplevel, "the title bar appeared")) + return 1; + + // Hiding the title bar gives that space back to the client area. + const int32_t titlebar_height = state.titlebar_height; + if (set_titlebar_mode(&connection, context, + TREELAND_DECORATION_CONTEXT_V1_TITLEBAR_MODE_HIDE, 0)) + return 1; + if (expect_maximized_configure(&connection, &toplevel, "the title bar went away")) + return 1; + + // ...and showing it again takes that space back. + if (set_titlebar_mode(&connection, context, + TREELAND_DECORATION_CONTEXT_V1_TITLEBAR_MODE_SHOW, titlebar_height)) + return 1; + if (expect_maximized_configure(&connection, &toplevel, "the title bar came back")) + return 1; + + zxdg_toplevel_decoration_v1_destroy(decoration); + zxdg_decoration_manager_v1_destroy(decorationManager); + treeland_decoration_context_v1_destroy(context); + treeland_decoration_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&toplevel); + client_disconnect(&connection); + return 0; +} diff --git a/tests/protocols/treeland-decoration-unstable-v1/treeland-decoration-unstable-v1.h b/tests/protocols/treeland-decoration-unstable-v1/treeland-decoration-unstable-v1.h new file mode 100644 index 0000000000..fab0e6ff41 --- /dev/null +++ b/tests/protocols/treeland-decoration-unstable-v1/treeland-decoration-unstable-v1.h @@ -0,0 +1,25 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct decoration_server_state { + int valid; + double radius; + // Maximized frame rect and the SSD title bar height currently taken out of it. + int32_t maximized_width; + int32_t maximized_height; + int32_t titlebar_height; +}; + +void decoration_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/treeland-foreign-toplevel-manager-v3/CMakeLists.txt b/tests/protocols/treeland-foreign-toplevel-manager-v3/CMakeLists.txt new file mode 100644 index 0000000000..76d7471f45 --- /dev/null +++ b/tests/protocols/treeland-foreign-toplevel-manager-v3/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_foreign_toplevel_manager_v3 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-foreign-toplevel-manager-unstable-v3.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-foreign-toplevel-manager-v3.c" +) diff --git a/tests/protocols/treeland-foreign-toplevel-manager-v3/README.md b/tests/protocols/treeland-foreign-toplevel-manager-v3/README.md new file mode 100644 index 0000000000..eff34826b4 --- /dev/null +++ b/tests/protocols/treeland-foreign-toplevel-manager-v3/README.md @@ -0,0 +1,74 @@ +# `treeland-foreign-toplevel-manager-v3` 测试规范 + +## 范围 + +- 测试源码:`tests/protocols/treeland-foreign-toplevel-manager-v3/` +- Fixture:带 headless output 和已 configure、mapped xdg-toplevel 的 desktop fixture。 +- 覆盖等级:**E**。 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | +| --- | --- | --- | +| toplevel 发现 | map xdg-toplevel | `ShellHandler` 创建 workspace `SurfaceWrapper`,manager 恰好发送一个带 identifier 的 foreign handle | +| Dock preview | 对该 identifier 发 `show(10,20,BOTTOM)`、`show_list(30,40,LEFT)`、未知 identifier、`show_tooltip_surface`(无内容、换 surface、同 surface 换位置)、context close | 生产 preview/tooltip/close 回调收到预期参数;`show` 报 thumbnail 布局、`show_list` 报 list 布局;未知 identifier 产生空 surface 列表而非协议错误;tooltip 回调收到客户端 surface 及其已提交的尺寸;无内容的 show 不产生回调 | +| 最小化与关闭 | 对 handle 发 `set_minimized`、`unset_minimized`、`close` | 真实 wrapper 的 minimized 状态变化;xdg client 收到 close | +| 最大化 | 对 handle 发 `set_maximized`、`unset_maximized` | 同一真实 `SurfaceWrapper` 进入、退出 `Maximized` 状态 | +| 全屏 | 对 handle 发 `set_fullscreen(NULL)`、`unset_fullscreen` | 同一真实 `SurfaceWrapper` 进入、退出 `Fullscreen` 状态 | +| 布局与最小化正交 | `set_maximized`/`set_fullscreen` 后发 `set_minimized`、`unset_minimized`,再 `unset_maximized`/`unset_fullscreen` | 最小化期间 `SurfaceWrapper::surfaceState()` 保持布局状态且窗口不可见;恢复后仍为该布局状态并重新可见;取消布局状态后回到 `Normal` 且不再最小化 | +| 激活 | 对 handle 发 `activate(wl_seat)` | `WaylandServer` 将 wrapper 设为 activated,且它成为该 seat 的真实 keyboard focus surface | +| 窗口代表区域 | 对 handle 的 mapped xdg `wl_surface` 发 `set_icon_geometry(11,12,130,140)` | production rectangle handler 将局部坐标换算为 wrapper 的 `iconGeometry`:`wrapper.position + QRect(11,12,130,140)` | + +## 已证明的生产链路 + +客户端 map xdg-toplevel 后,测试等待 configure,并同时断言:`ShellHandler` 创建的 +wrapper 已 mapped、已加入 `Workspace`,且 manager 的 `toplevel` 事件只给出一个 +真实 `treeland_foreign_toplevel_handle_v3` 和 identifier。该 identifier 被放入 +`show` 的 `wl_array`,客户端发送 `show(identifiers, 10, 20, BOTTOM)`;服务端生产 +manager 发出 `requestDockPreview`,fixture 读取到绝对坐标 `(10,20)`、`BOTTOM` 和 +一个真实 `WSurface`。 + +状态转换关闭几何动画:desktop fixture 通过 `animationConfig` 关闭 `maximize`/ +`fullscreen`/`restoreWindow` 三个动画开关,使每个状态请求立即落地 `surfaceState`, +不依赖渲染线程驱动的 `OpacityAnimator`。每次状态请求后 fixture render 一帧以刷新排队的 +场景图状态,再读取 wrapper 状态。这样测试验证的是协议状态转换本身,而不是几何动画的 +插值或收敛时序;正常桌面进程的动画行为不受影响。 + +同一 context 的 `show_tooltip_surface(surface, 1, 2, LEFT)` 在 surface 还没有提交内容时 +属于客户端违约,服务端不得发出 `requestDockPreviewTooltip`;该 surface 提交内容后再次 show +(5, 6, TOP),回调才拿到这块 `wl_surface`,其逻辑尺寸(29x19)取自已提交的 buffer;换一块 +51x17 的 surface 再 show,回调换成新的尺寸与坐标;对已显示的同一个 surface 再 show 到新位置 +(11, 12, LEFT) 不需要新的提交,回调直接带新坐标。`context.close` 到达 `requestDockClose`。此外,foreign +handle 的 `set_minimized`/`unset_minimized` 分别使该 wrapper 的 shell surface 进入/退出 +minimized;`set_maximized`/`unset_maximized` 分别改变 wrapper 的 `Maximized` 状态; +`set_fullscreen(NULL)`/`unset_fullscreen` 分别改变其 `Fullscreen` 状态。这里读取的是 +compositor 的 `SurfaceWrapper::surfaceState()`,不是 foreign handle 自身缓存的 state event。 + +最小化标志与布局状态正交:在 `Maximized` 或 `Fullscreen` 状态下发 `set_minimized`,测试断言 +`SurfaceWrapper::isMinimized()` 为真、`surfaceState()` 仍为原布局状态、且窗口不可见; +`unset_minimized` 后布局状态不变且窗口重新可见;随后 `unset_maximized`/`unset_fullscreen` +必须回到 `Normal`、可见且不再最小化。这覆盖了“全屏→最小化→恢复→取消全屏后卡在最小化”的 +回归路径,而不只是顺序地单独测试各状态。 + +`activate(wl_seat)` 进入 manager 连接的 +`WaylandServer::forceActivateSurface(wrapper, ..., seat)`,测试读取 wrapper 的 activated 标记和 +root surface container 默认 seat container 的 `keyboardFocusSurface()`,两者都必须指向同一 +mapped wrapper。`set_icon_geometry` 则 +经过 `iconGeometryChanged` 的生产连接,以发送该请求的 mapped xdg surface 查找 dock wrapper, +再把局部矩形加到它的位置后写入被测 wrapper 的 `iconGeometry`。测试断言最终 geometry 的 +相对关系,故窗口不在 `(0,0)` 时仍成立。`handle.close` 让客户端 xdg-toplevel 接到 close。 +这些断言均指向同一个 mapped 窗口,不是单独创建的协议对象。 + +## 已知边界 / 下一项结果 + +已覆盖 handle 的 `set/unset_minimized`、`set/unset_maximized`、 +`set/unset_fullscreen`、`activate`、`set_icon_geometry`、`close`,以及 manager/context 的 +`stop`、`get_dock_preview_context`、`show`、`show_tooltip_surface`、`close`、`destroy`。 + +布局与最小化的组合已覆盖 `Maximized`、`Fullscreen` 两种布局;`Tiling` 没有对应的 foreign +handle 请求,仍未被组合覆盖。 + +仍未验证 dock UI 或 preview 的渲染像素;`output_enter` / `output_leave`、title、app-id、pid、 +parent 和 foreign handle 对 state event 的线上内容也尚未逐项断言。`set_fullscreen` 当前传 +`NULL` output,因此未覆盖“指定 `wl_output` 是 fullscreen hint”这一分支。fixture 关闭了几何 +动画,只读取最终 wrapper 状态,不构成对动画插值或最终帧像素的验证。 diff --git a/tests/protocols/treeland-foreign-toplevel-manager-v3/setup.cpp b/tests/protocols/treeland-foreign-toplevel-manager-v3/setup.cpp new file mode 100644 index 0000000000..289e1ff8ed --- /dev/null +++ b/tests/protocols/treeland-foreign-toplevel-manager-v3/setup.cpp @@ -0,0 +1,121 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "core/shellhandler.h" +#include "core/rootsurfacecontainer.h" +#include "modules/foreign-toplevel/foreigntoplevelmanagerv3.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" +#include "treeland-foreign-toplevel-manager-v3.h" +#include "workspace/workspace.h" + +#include +#include + +#include "animationconfig.hpp" + +#include + +namespace { +ForeignToplevelManagerInterfaceV3 *g_manager = nullptr; +SurfaceWrapper *g_wrapper = nullptr; +struct ftm_server_state g_state {}; +} + +void protocol_test_setup(WaylandServer *server) +{ + // This test asserts the foreign-toplevel protocol's state transitions, + // not the geometry animation. Disabling the animation makes every + // maximize/fullscreen/restore request land its surface state immediately, + // so the test does not have to pace the render-thread-driven + // OpacityAnimator, which used to cause intermittent timeouts. + auto *animationConfig = server->animationConfig(); + if (animationConfig) { + animationConfig->setMaximize(false); + animationConfig->setFullscreen(false); + animationConfig->setRestoreWindow(false); + } + add_headless_output(server->backend(), false); + g_manager = server->shellHandler()->foreignToplevel(); + QObject::connect(g_manager, + &ForeignToplevelManagerInterfaceV3::requestDockPreview, + server, + [](auto surfaces, WSurface *, QPoint abs, auto direction, auto layout) { + g_state.preview_fired = 1; + g_state.preview_x = abs.x(); + g_state.preview_y = abs.y(); + g_state.preview_direction = static_cast(direction); + g_state.preview_layout = static_cast(layout); + g_state.preview_surface_count = static_cast(surfaces.size()); + }); + QObject::connect(g_manager, + &ForeignToplevelManagerInterfaceV3::requestDockPreviewTooltip, + server, + [](WSurface *surface, WSurface *, QPoint abs, auto direction) { + g_state.tooltip_fired = 1; + g_state.tooltip_count++; + g_state.tooltip_surface_present = surface ? 1 : 0; + if (surface) { + const QSize size = surface->size(); + g_state.tooltip_width = size.width(); + g_state.tooltip_height = size.height(); + } + g_state.tooltip_x = abs.x(); + g_state.tooltip_y = abs.y(); + g_state.tooltip_direction = static_cast(direction); + }); + QObject::connect(g_manager, + &ForeignToplevelManagerInterfaceV3::requestDockClose, + server, + [] { g_state.close_fired = 1; }); + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [server](SurfaceWrapper *wrapper) { + if (wrapper->type() != SurfaceWrapper::Type::XdgToplevel) + return; + g_wrapper = wrapper; + g_state.wrapper_created = 1; + g_state.wrapper_in_workspace = server->workspace()->surfaces().contains(wrapper) ? 1 : 0; + g_state.mapped_xdg_toplevel = wrapper->surface() && wrapper->surface()->mapped() ? 1 : 0; + }); +} + +extern "C" void ftm_read_server_state(void *data) +{ + g_state.output_ready = !WaylandServer::instance()->rootSurfaceContainer()->outputs().isEmpty() ? 1 : 0; + g_state.wrapper_minimized = g_wrapper && g_wrapper->shellSurface() + && g_wrapper->shellSurface()->isMinimized() ? 1 : 0; + g_state.wrapper_self_minimized = g_wrapper && g_wrapper->isMinimized() ? 1 : 0; + g_state.wrapper_state = + g_wrapper ? static_cast(g_wrapper->surfaceState()) : -1; + g_state.wrapper_visible = g_wrapper && g_wrapper->isVisible() ? 1 : 0; + g_state.wrapper_maximized = g_wrapper && g_wrapper->isMaximized() ? 1 : 0; + g_state.wrapper_fullscreen = g_wrapper + && g_wrapper->surfaceState() == SurfaceWrapper::State::Fullscreen ? 1 : 0; + g_state.wrapper_activated = g_wrapper && g_wrapper->isActivated() ? 1 : 0; + auto *seatContainer = WaylandServer::instance()->rootSurfaceContainer()->getSeatContainerOrDefault(); + g_state.wrapper_focused = seatContainer && seatContainer->keyboardFocusSurface() == g_wrapper ? 1 : 0; + g_state.wrapper_skip_dock_preview = g_wrapper && g_wrapper->skipDockPreView() ? 1 : 0; + if (g_wrapper) { + g_state.wrapper_x = static_cast(g_wrapper->x()); + g_state.wrapper_y = static_cast(g_wrapper->y()); + const QRect icon = g_wrapper->iconGeometry(); + g_state.icon_x = icon.x(); + g_state.icon_y = icon.y(); + g_state.icon_width = icon.width(); + g_state.icon_height = icon.height(); + } + *static_cast(data) = g_state; +} + +extern "C" void ftm_render_and_settle(void *) +{ + if (!g_wrapper) + return; + + // Geometry animation is disabled, so the surface state lands when the + // protocol request is handled. One render lets any queued scene-graph + // frame apply the state before the test reads it back. + WaylandServer::instance()->window()->render(); +} diff --git a/tests/protocols/treeland-foreign-toplevel-manager-v3/treeland-foreign-toplevel-manager-v3.c b/tests/protocols/treeland-foreign-toplevel-manager-v3/treeland-foreign-toplevel-manager-v3.c new file mode 100644 index 0000000000..f5e98f974f --- /dev/null +++ b/tests/protocols/treeland-foreign-toplevel-manager-v3/treeland-foreign-toplevel-manager-v3.c @@ -0,0 +1,789 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-foreign-toplevel-manager-v3.h" +#include "server-bridge-api.h" +#include "treeland-foreign-toplevel-manager-unstable-v3-client-protocol.h" + +#include +#include +#include +#include + +#include +#include +#include + +extern void ftm_read_server_state(void *data); +extern void ftm_render_and_settle(void *data); + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); +}; + +// Layouts the compositor reports for a preview request: show always asks for +// the thumbnail layout, show_list for the list. +enum preview_layout_value { + PREVIEW_LAYOUT_THUMBNAIL = 0, + PREVIEW_LAYOUT_LIST = 1, +}; + +typedef void (*ftm_layout_request_fn)(struct treeland_foreign_toplevel_handle_v3 *handle); + +void test_init(struct test_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); + ctx->result_cap = 32; + ctx->results = calloc(ctx->result_cap, sizeof(*ctx->results)); +} + +void test_destroy(struct test_ctx *ctx) +{ + free(ctx->results); + memset(ctx, 0, sizeof(*ctx)); +} + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +void test_pass(struct test_ctx *ctx, int index) +{ + ctx->results[index].failed = 0; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +static void handle_pid(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, + uint32_t pid) +{ + (void)data; + (void)handle; + (void)pid; +} + +static void handle_title(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, + const char *title) +{ + (void)data; + (void)handle; + (void)title; +} + +static void handle_app_id(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, + const char *app_id) +{ + (void)data; + (void)handle; + (void)app_id; +} + +static void handle_identifier(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, + uint32_t identifier) +{ + (void)handle; + ((struct test_ctx *)data)->handle_identifier = identifier; +} + +static void handle_output_enter(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, + struct wl_output *output) +{ + (void)data; + (void)handle; + (void)output; +} + +static void handle_output_leave(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, + struct wl_output *output) +{ + (void)data; + (void)handle; + (void)output; +} + +static void handle_state(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, + struct wl_array *state) +{ + (void)data; + (void)handle; + (void)state; +} + +static void handle_done(void *data, struct treeland_foreign_toplevel_handle_v3 *handle) +{ + (void)data; + (void)handle; +} + +static void handle_closed(void *data, struct treeland_foreign_toplevel_handle_v3 *handle) +{ + struct test_ctx *ctx = data; + if (ctx->handle == handle) + ctx->handle = NULL; + ++ctx->handle_closed_count; + treeland_foreign_toplevel_handle_v3_destroy(handle); +} + +static void handle_parent(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, + struct treeland_foreign_toplevel_handle_v3 *parent) +{ + (void)data; + (void)handle; + (void)parent; +} + +static const struct treeland_foreign_toplevel_handle_v3_listener handle_listener = { + .pid = handle_pid, + .title = handle_title, + .app_id = handle_app_id, + .identifier = handle_identifier, + .output_enter = handle_output_enter, + .output_leave = handle_output_leave, + .state = handle_state, + .done = handle_done, + .closed = handle_closed, + .parent = handle_parent, +}; + +static void manager_toplevel(void *data, struct treeland_foreign_toplevel_manager_v3 *manager, + struct treeland_foreign_toplevel_handle_v3 *toplevel) +{ + (void)manager; + struct test_ctx *ctx = data; + ctx->handle = toplevel; + ++ctx->handle_count; + treeland_foreign_toplevel_handle_v3_add_listener(toplevel, &handle_listener, ctx); +} + +static void manager_finished(void *data, struct treeland_foreign_toplevel_manager_v3 *manager) +{ + (void)manager; + ((struct test_ctx *)data)->manager_finished_received = 1; +} + +static const struct treeland_foreign_toplevel_manager_v3_listener manager_listener = { + .toplevel = manager_toplevel, + .finished = manager_finished, +}; + +static void context_enter(void *data, struct treeland_dock_preview_context_v3 *context) +{ + (void)context; + ((struct test_ctx *)data)->context_enter_received = 1; +} + +static void context_leave(void *data, struct treeland_dock_preview_context_v3 *context) +{ + (void)context; + ((struct test_ctx *)data)->context_leave_received = 1; +} + +static const struct treeland_dock_preview_context_v3_listener context_listener = { + .enter = context_enter, + .leave = context_leave, +}; + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->display = ctx->connection.display; + ctx->seat = client_bind(&ctx->connection, "wl_seat", &wl_seat_interface, 1); + ctx->compositor = client_bind(&ctx->connection, "wl_compositor", + &wl_compositor_interface, 1); + ctx->shm = client_bind(&ctx->connection, "wl_shm", &wl_shm_interface, 1); + // Version 2 is what carries show_list; the handle interface stays at + // version 1 and the compositor must clamp it. + ctx->manager = client_bind(&ctx->connection, "treeland_foreign_toplevel_manager_v3", + &treeland_foreign_toplevel_manager_v3_interface, 2); + if (ctx->manager) + treeland_foreign_toplevel_manager_v3_add_listener(ctx->manager, &manager_listener, ctx); + return ctx->seat != NULL && ctx->compositor != NULL && ctx->shm != NULL + && ctx->manager != NULL; +} + +static int read_server_state(struct test_ctx *ctx, struct ftm_server_state *state) +{ + (void)ctx; + memset(state, 0, sizeof(*state)); + return invoke_on_server_thread(ftm_read_server_state, state); +} + +static int settle_geometry_animation(struct test_ctx *ctx) +{ + (void)ctx; + return invoke_on_server_thread(ftm_render_and_settle, NULL); +} + +static int create_xdg_toplevel(struct test_ctx *ctx) +{ + if (!xdg_toplevel_client_create(&ctx->connection, &ctx->xdg_toplevel)) + return 0; + struct ftm_server_state state; + return wl_display_roundtrip(ctx->display) >= 0 + && ctx->xdg_toplevel.configured + && ctx->handle + && ctx->handle_count == 1 + && ctx->handle_identifier + && settle_geometry_animation(ctx) + && read_server_state(ctx, &state) + && state.wrapper_created + && state.wrapper_in_workspace; +} + +static int create_context(struct test_ctx *ctx) +{ + if (!ctx->xdg_toplevel.surface) + return 0; + ctx->context = treeland_foreign_toplevel_manager_v3_get_dock_preview_context( + ctx->manager, ctx->xdg_toplevel.surface); + if (ctx->context) + treeland_dock_preview_context_v3_add_listener(ctx->context, &context_listener, ctx); + return ctx->context != NULL; +} + +static int show_preview(struct test_ctx *ctx) +{ + if (!ctx->context || !ctx->handle_identifier) + return 0; + struct wl_array surfaces; + wl_array_init(&surfaces); + uint32_t *slot = wl_array_add(&surfaces, sizeof(uint32_t)); + if (!slot) { + wl_array_release(&surfaces); + return 0; + } + *slot = ctx->handle_identifier; + treeland_dock_preview_context_v3_show(ctx->context, &surfaces, 10, 20, + TREELAND_DOCK_PREVIEW_CONTEXT_V3_DIRECTION_BOTTOM); + wl_array_release(&surfaces); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + struct ftm_server_state state; + if (!read_server_state(ctx, &state)) + return 0; + return state.preview_fired + && state.preview_x == 10 + && state.preview_y == 20 + && state.preview_direction == TREELAND_DOCK_PREVIEW_CONTEXT_V3_DIRECTION_BOTTOM + && state.preview_layout == PREVIEW_LAYOUT_THUMBNAIL + && state.preview_surface_count == 1; +} + +static int show_list_preview(struct test_ctx *ctx) +{ + if (!ctx->context || !ctx->handle_identifier) + return 0; + struct wl_array surfaces; + wl_array_init(&surfaces); + uint32_t *slot = wl_array_add(&surfaces, sizeof(uint32_t)); + if (!slot) { + wl_array_release(&surfaces); + return 0; + } + *slot = ctx->handle_identifier; + treeland_dock_preview_context_v3_show_list( + ctx->context, &surfaces, 30, 40, + TREELAND_DOCK_PREVIEW_CONTEXT_V3_DIRECTION_LEFT); + wl_array_release(&surfaces); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + struct ftm_server_state state; + if (!read_server_state(ctx, &state)) + return 0; + return state.preview_fired + && state.preview_x == 30 + && state.preview_y == 40 + && state.preview_direction == TREELAND_DOCK_PREVIEW_CONTEXT_V3_DIRECTION_LEFT + && state.preview_layout == PREVIEW_LAYOUT_LIST + && state.preview_surface_count == 1; +} + +static int show_unknown_identifier(struct test_ctx *ctx) +{ + if (!ctx->context) + return 0; + struct wl_array surfaces; + wl_array_init(&surfaces); + uint32_t *slot = wl_array_add(&surfaces, sizeof(uint32_t)); + if (!slot) + return 0; + *slot = 0xDEADBEEFu; + + treeland_dock_preview_context_v3_show(ctx->context, &surfaces, 1, 2, + TREELAND_DOCK_PREVIEW_CONTEXT_V3_DIRECTION_TOP); + wl_array_release(&surfaces); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + struct ftm_server_state state; + if (!read_server_state(ctx, &state)) + return 0; + return state.preview_fired && state.preview_surface_count == 0; +} + +static int create_shm_surface_deferred(struct test_ctx *ctx, int width, int height, + struct wl_surface **surface, struct wl_buffer **buffer) +{ + const int stride = width * 4; + const size_t size = (size_t)stride * height; + char name[64]; + snprintf(name, sizeof(name), "/treeland_ftm_tooltip_%d_%dx%d", + (int)getpid(), width, height); + const int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); + if (fd < 0) + return 0; + shm_unlink(name); + if (ftruncate(fd, (off_t)size) < 0) { + close(fd); + return 0; + } + + void *data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (data == MAP_FAILED) { + close(fd); + return 0; + } + // A translucent fill: the compositor's pill shows through where the client + // paints nothing, which is what the tooltip contract asks for. + uint32_t *pixels = data; + for (size_t i = 0; i < size / sizeof(uint32_t); ++i) + pixels[i] = 0x80000000u; + + struct wl_shm_pool *pool = wl_shm_create_pool(ctx->shm, fd, (int)size); + close(fd); + if (!pool) { + munmap(data, size); + return 0; + } + *buffer = wl_shm_pool_create_buffer(pool, 0, width, height, stride, + WL_SHM_FORMAT_ARGB8888); + wl_shm_pool_destroy(pool); + munmap(data, size); + if (!*buffer) + return 0; + + *surface = wl_compositor_create_surface(ctx->compositor); + if (!*surface) + return 0; + return 1; +} + +static int commit_shm_surface(int width, int height, + struct wl_surface *surface, struct wl_buffer *buffer) +{ + wl_surface_attach(surface, buffer, 0, 0); + wl_surface_damage(surface, 0, 0, width, height); + wl_surface_commit(surface); + return 1; +} + +static int create_shm_surface(struct test_ctx *ctx, int width, int height, + struct wl_surface **surface, struct wl_buffer **buffer) +{ + if (!create_shm_surface_deferred(ctx, width, height, surface, buffer)) + return 0; + return commit_shm_surface(width, height, *surface, *buffer); +} + +static int show_tooltip_surface(struct test_ctx *ctx) +{ + struct ftm_server_state state; + + if (!ctx->context) + return 0; + // A surface without committed content is a client error: the request has no + // effect and the compositor shows nothing for it. + if (!create_shm_surface_deferred(ctx, 29, 19, &ctx->tooltip_surface, &ctx->tooltip_buffer)) + return 0; + treeland_dock_preview_context_v3_show_tooltip_surface( + ctx->context, ctx->tooltip_surface, 1, 2, + TREELAND_DOCK_PREVIEW_CONTEXT_V3_DIRECTION_LEFT); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + if (!read_server_state(ctx, &state)) + return 0; + if (state.tooltip_count != 0) + return 0; + + // The same surface is shown once its content has been committed. + commit_shm_surface(29, 19, ctx->tooltip_surface, ctx->tooltip_buffer); + treeland_dock_preview_context_v3_show_tooltip_surface( + ctx->context, ctx->tooltip_surface, 5, 6, + TREELAND_DOCK_PREVIEW_CONTEXT_V3_DIRECTION_TOP); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + if (!read_server_state(ctx, &state)) + return 0; + return state.tooltip_fired + && state.tooltip_count == 1 + && state.tooltip_surface_present + && state.tooltip_width == 29 + && state.tooltip_height == 19 + && state.tooltip_x == 5 + && state.tooltip_y == 6 + && state.tooltip_direction == TREELAND_DOCK_PREVIEW_CONTEXT_V3_DIRECTION_TOP; +} + +static int replace_tooltip_surface(struct test_ctx *ctx) +{ + struct ftm_server_state state; + + if (!ctx->context) + return 0; + if (!create_shm_surface(ctx, 51, 17, &ctx->tooltip_surface2, &ctx->tooltip_buffer2)) + return 0; + treeland_dock_preview_context_v3_show_tooltip_surface( + ctx->context, ctx->tooltip_surface2, 7, 8, + TREELAND_DOCK_PREVIEW_CONTEXT_V3_DIRECTION_BOTTOM); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + if (!read_server_state(ctx, &state)) + return 0; + return state.tooltip_count == 2 + && state.tooltip_surface_present + && state.tooltip_width == 51 + && state.tooltip_height == 17 + && state.tooltip_x == 7 + && state.tooltip_y == 8 + && state.tooltip_direction == TREELAND_DOCK_PREVIEW_CONTEXT_V3_DIRECTION_BOTTOM; +} + +static int move_tooltip_surface(struct test_ctx *ctx) +{ + struct ftm_server_state state; + + // Showing a surface that is already displayed only moves it: no commit is + // needed for a new position. + if (!ctx->context || !ctx->tooltip_surface2) + return 0; + treeland_dock_preview_context_v3_show_tooltip_surface( + ctx->context, ctx->tooltip_surface2, 11, 12, + TREELAND_DOCK_PREVIEW_CONTEXT_V3_DIRECTION_LEFT); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + if (!read_server_state(ctx, &state)) + return 0; + return state.tooltip_count == 3 + && state.tooltip_surface_present + && state.tooltip_width == 51 + && state.tooltip_height == 17 + && state.tooltip_x == 11 + && state.tooltip_y == 12 + && state.tooltip_direction == TREELAND_DOCK_PREVIEW_CONTEXT_V3_DIRECTION_LEFT; +} + +static int close_preview(struct test_ctx *ctx) +{ + if (!ctx->context) + return 0; + treeland_dock_preview_context_v3_close(ctx->context); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + struct ftm_server_state state; + if (!read_server_state(ctx, &state)) + return 0; + return state.close_fired; +} + +static int minimize_real_toplevel(struct test_ctx *ctx) +{ + if (!ctx->handle) + return 0; + treeland_foreign_toplevel_handle_v3_set_minimized(ctx->handle); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + struct ftm_server_state state; + return read_server_state(ctx, &state) && state.wrapper_minimized; +} + +static int restore_real_toplevel(struct test_ctx *ctx) +{ + if (!ctx->handle) + return 0; + treeland_foreign_toplevel_handle_v3_unset_minimized(ctx->handle); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + struct ftm_server_state state; + return read_server_state(ctx, &state) && !state.wrapper_minimized; +} + +static int render_ack_and_read_server_state(struct test_ctx *ctx, struct ftm_server_state *state) +{ + return settle_geometry_animation(ctx) + && xdg_toplevel_client_ack_latest_configure(&ctx->connection, &ctx->xdg_toplevel) + && settle_geometry_animation(ctx) + && read_server_state(ctx, state); +} + +static int maximize_real_toplevel(struct test_ctx *ctx) +{ + if (!ctx->handle) + return 0; + treeland_foreign_toplevel_handle_v3_set_maximized(ctx->handle); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + struct ftm_server_state state; + return render_ack_and_read_server_state(ctx, &state) && state.wrapper_maximized; +} + +static int unmaximize_real_toplevel(struct test_ctx *ctx) +{ + if (!ctx->handle) + return 0; + treeland_foreign_toplevel_handle_v3_unset_maximized(ctx->handle); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + struct ftm_server_state state; + return render_ack_and_read_server_state(ctx, &state) && !state.wrapper_maximized; +} + +static int fullscreen_real_toplevel(struct test_ctx *ctx) +{ + if (!ctx->handle) + return 0; + treeland_foreign_toplevel_handle_v3_set_fullscreen(ctx->handle, NULL); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + struct ftm_server_state state; + return render_ack_and_read_server_state(ctx, &state) && state.wrapper_fullscreen; +} + +static int unfullscreen_real_toplevel(struct test_ctx *ctx) +{ + if (!ctx->handle) + return 0; + treeland_foreign_toplevel_handle_v3_unset_fullscreen(ctx->handle); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + struct ftm_server_state state; + return render_ack_and_read_server_state(ctx, &state) && !state.wrapper_fullscreen; +} + +static void request_maximized(struct treeland_foreign_toplevel_handle_v3 *handle) +{ + treeland_foreign_toplevel_handle_v3_set_maximized(handle); +} + +static void request_unmaximized(struct treeland_foreign_toplevel_handle_v3 *handle) +{ + treeland_foreign_toplevel_handle_v3_unset_maximized(handle); +} + +static void request_fullscreen(struct treeland_foreign_toplevel_handle_v3 *handle) +{ + treeland_foreign_toplevel_handle_v3_set_fullscreen(handle, NULL); +} + +static void request_unfullscreen(struct treeland_foreign_toplevel_handle_v3 *handle) +{ + treeland_foreign_toplevel_handle_v3_unset_fullscreen(handle); +} + +static int minimize_keeps_layout_state(struct test_ctx *ctx, + ftm_layout_request_fn request_layout, + ftm_layout_request_fn request_unlayout, + int layout_state) +{ + if (!ctx->handle) + return 0; + + request_layout(ctx->handle); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + + struct ftm_server_state state; + if (!render_ack_and_read_server_state(ctx, &state) + || state.wrapper_state != layout_state) + return 0; + + treeland_foreign_toplevel_handle_v3_set_minimized(ctx->handle); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + if (!read_server_state(ctx, &state)) + return 0; + if (!state.wrapper_self_minimized || state.wrapper_state != layout_state + || state.wrapper_visible) + return 0; + + treeland_foreign_toplevel_handle_v3_unset_minimized(ctx->handle); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + if (!render_ack_and_read_server_state(ctx, &state)) + return 0; + if (state.wrapper_self_minimized || state.wrapper_state != layout_state + || !state.wrapper_visible) + return 0; + + request_unlayout(ctx->handle); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + if (!render_ack_and_read_server_state(ctx, &state)) + return 0; + return !state.wrapper_self_minimized && state.wrapper_visible + && state.wrapper_state == FTM_WRAPPER_STATE_NORMAL; +} + +static int minimize_keeps_maximized_state(struct test_ctx *ctx) +{ + return minimize_keeps_layout_state(ctx, + request_maximized, + request_unmaximized, + FTM_WRAPPER_STATE_MAXIMIZED); +} + +static int minimize_keeps_fullscreen_state(struct test_ctx *ctx) +{ + return minimize_keeps_layout_state(ctx, + request_fullscreen, + request_unfullscreen, + FTM_WRAPPER_STATE_FULLSCREEN); +} + +static int activate_real_toplevel(struct test_ctx *ctx) +{ + if (!ctx->handle || !ctx->seat) + return 0; + treeland_foreign_toplevel_handle_v3_activate(ctx->handle, ctx->seat); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + struct ftm_server_state state; + return read_server_state(ctx, &state) && state.wrapper_activated && state.wrapper_focused; +} + +static int set_icon_geometry_changes_icon_geometry(struct test_ctx *ctx) +{ + if (!ctx->handle || !ctx->xdg_toplevel.surface) + return 0; + treeland_foreign_toplevel_handle_v3_set_icon_geometry(ctx->handle, + ctx->xdg_toplevel.surface, + 11, 12, 130, 140); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + struct ftm_server_state state; + return read_server_state(ctx, &state) + && state.icon_x == state.wrapper_x + 11 && state.icon_y == state.wrapper_y + 12 + && state.icon_width == 130 && state.icon_height == 140; +} + +static int request_close(struct test_ctx *ctx) +{ + if (!ctx->handle) + return 0; + treeland_foreign_toplevel_handle_v3_close(ctx->handle); + return wl_display_roundtrip(ctx->display) >= 0 && ctx->xdg_toplevel.close_received; +} + +static int destroy_context(struct test_ctx *ctx) +{ + if (!ctx->context) + return 0; + treeland_dock_preview_context_v3_destroy(ctx->context); + ctx->context = NULL; + return wl_display_roundtrip(ctx->display) >= 0; +} + +static int stop_manager(struct test_ctx *ctx) +{ + if (!ctx->manager) + return 0; + treeland_foreign_toplevel_manager_v3_stop(ctx->manager); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + return ctx->manager_finished_received; +} + +static const struct test_case cases[] = { + { "client.create_xdg_toplevel", create_xdg_toplevel }, + { "manager.get_dock_preview_context", create_context }, + { "context.show", show_preview }, + { "context.show_list", show_list_preview }, + { "context.show_unknown_identifier", show_unknown_identifier }, + { "context.show_tooltip_surface", show_tooltip_surface }, + { "context.show_tooltip_surface_replace", replace_tooltip_surface }, + { "context.show_tooltip_surface_move", move_tooltip_surface }, + { "context.close", close_preview }, + { "handle.minimize_changes_wrapper", minimize_real_toplevel }, + { "handle.restore_changes_wrapper", restore_real_toplevel }, + { "handle.maximize_changes_wrapper", maximize_real_toplevel }, + { "handle.unmaximize_changes_wrapper", unmaximize_real_toplevel }, + { "handle.fullscreen_changes_wrapper", fullscreen_real_toplevel }, + { "handle.unfullscreen_changes_wrapper", unfullscreen_real_toplevel }, + { "handle.minimize_keeps_maximized_state", minimize_keeps_maximized_state }, + { "handle.minimize_keeps_fullscreen_state", minimize_keeps_fullscreen_state }, + { "handle.activate_focuses_wrapper", activate_real_toplevel }, + { "handle.set_icon_geometry_changes_icon_geometry", set_icon_geometry_changes_icon_geometry }, + { "handle.close_requests_xdg_close", request_close }, + { "context.destroy", destroy_context }, + { "manager.stop", stop_manager }, +}; + +void test_cleanup(struct test_ctx *ctx) +{ + if (ctx->context) treeland_dock_preview_context_v3_destroy(ctx->context); + xdg_toplevel_client_destroy(&ctx->xdg_toplevel); + if (ctx->tooltip_buffer2) wl_buffer_destroy(ctx->tooltip_buffer2); + if (ctx->tooltip_surface2) wl_surface_destroy(ctx->tooltip_surface2); + if (ctx->tooltip_buffer) wl_buffer_destroy(ctx->tooltip_buffer); + if (ctx->tooltip_surface) wl_surface_destroy(ctx->tooltip_surface); + if (ctx->handle) treeland_foreign_toplevel_handle_v3_destroy(ctx->handle); + if (ctx->manager) treeland_foreign_toplevel_manager_v3_destroy(ctx->manager); + if (ctx->shm) wl_shm_destroy(ctx->shm); + if (ctx->compositor) wl_compositor_destroy(ctx->compositor); + if (ctx->seat) wl_seat_destroy(ctx->seat); + client_disconnect(&ctx->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx; + test_init(&ctx); + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect to or bind treeland_foreign_toplevel_manager_v3\n"); + test_cleanup(&ctx); + test_destroy(&ctx); + return 1; + } + + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const int result = test_add(&ctx, cases[i].name); + if (!cases[i].run(&ctx)) + test_fail(&ctx, result, "assertion failed"); + if (wl_display_roundtrip(ctx.display) < 0) + test_fail(&ctx, result, "Wayland connection failed"); + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + test_destroy(&ctx); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-foreign-toplevel-manager-v3/treeland-foreign-toplevel-manager-v3.h b/tests/protocols/treeland-foreign-toplevel-manager-v3/treeland-foreign-toplevel-manager-v3.h new file mode 100644 index 0000000000..7099eefbd4 --- /dev/null +++ b/tests/protocols/treeland-foreign-toplevel-manager-v3/treeland-foreign-toplevel-manager-v3.h @@ -0,0 +1,107 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef FOREIGN_TOPLEVEL_MANAGER_TEST_H +#define FOREIGN_TOPLEVEL_MANAGER_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +#include "client-connection.h" +#include "xdg-toplevel-client.h" + +#define TEST_MSG_MAX 256 + +enum ftm_wrapper_state { + FTM_WRAPPER_STATE_NORMAL = 0, + FTM_WRAPPER_STATE_MAXIMIZED = 1, + FTM_WRAPPER_STATE_FULLSCREEN = 2, + FTM_WRAPPER_STATE_TILING = 3, +}; + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +struct ftm_server_state { + int output_ready; + int wrapper_created; + int wrapper_in_workspace; + int mapped_xdg_toplevel; + int wrapper_minimized; + int wrapper_self_minimized; + int wrapper_state; + int wrapper_visible; + int wrapper_maximized; + int wrapper_fullscreen; + int wrapper_activated; + int wrapper_focused; + int wrapper_skip_dock_preview; + int wrapper_x; + int wrapper_y; + int icon_x; + int icon_y; + int icon_width; + int icon_height; + int preview_fired; + int preview_x; + int preview_y; + uint32_t preview_direction; + uint32_t preview_layout; + int preview_surface_count; + int tooltip_fired; + int tooltip_count; + int tooltip_surface_present; + int tooltip_width; + int tooltip_height; + int tooltip_x; + int tooltip_y; + uint32_t tooltip_direction; + int close_fired; +}; + +struct test_ctx { + struct client_connection connection; + struct wl_display *display; + + struct treeland_foreign_toplevel_manager_v3 *manager; + struct treeland_dock_preview_context_v3 *context; + struct treeland_foreign_toplevel_handle_v3 *handle; + struct wl_seat *seat; + struct wl_compositor *compositor; + struct wl_shm *shm; + struct wl_surface *tooltip_surface; + struct wl_buffer *tooltip_buffer; + struct wl_surface *tooltip_surface2; + struct wl_buffer *tooltip_buffer2; + struct xdg_toplevel_client xdg_toplevel; + + int context_enter_received; + int context_leave_received; + int manager_finished_received; + int handle_count; + int handle_closed_count; + uint32_t handle_identifier; + + struct test_result *results; + int result_count; + int result_cap; +}; + +void test_init(struct test_ctx *ctx); +void test_destroy(struct test_ctx *ctx); +int test_add(struct test_ctx *ctx, const char *name); +void test_fail(struct test_ctx *ctx, int idx, const char *fmt, ...); +void test_pass(struct test_ctx *ctx, int idx); + +int test_print_results(struct test_ctx *ctx); +void test_cleanup(struct test_ctx *ctx); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-input-manager-uinput-v1/CMakeLists.txt b/tests/protocols/treeland-input-manager-uinput-v1/CMakeLists.txt new file mode 100644 index 0000000000..023222ad62 --- /dev/null +++ b/tests/protocols/treeland-input-manager-uinput-v1/CMakeLists.txt @@ -0,0 +1,12 @@ + +treeland_add_protocol_test( + NAME treeland_input_manager_uinput_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-input-manager-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-input-manager-uinput-v1.c" +) + +set_tests_properties(test_treeland_input_manager_uinput_v1 PROPERTIES + ENVIRONMENT "WLR_BACKENDS=headless,libinput;WLR_RENDERER=pixman;LIBSEAT_BACKEND=seatd;SEATD_SOCK=/run/dde-seatd.sock;${TREELAND_PROTOCOL_TEST_XWAYLAND_ENV}DSG_DATA_DIRS=${TREELAND_PROTOCOL_TEST_DSG_DATA_DIRS};TREELAND_PROTOCOL_TEST_DSG_DIR=${TREELAND_PROTOCOL_TEST_DSG_DATA_DIR}" + SKIP_RETURN_CODE 77 +) diff --git a/tests/protocols/treeland-input-manager-uinput-v1/README.md b/tests/protocols/treeland-input-manager-uinput-v1/README.md new file mode 100644 index 0000000000..278dd9f47e --- /dev/null +++ b/tests/protocols/treeland-input-manager-uinput-v1/README.md @@ -0,0 +1,12 @@ +# input-manager uinput v1 + +此 target 仅在 `TREELAND_ENABLE_UINPUT_PROTOCOL_TESTS=ON` 时注册。它创建一个 +`BUS_VIRTUAL` uinput 键盘,验证真实 `uinput → libinput → WBackend` 热插拔路径使 +input-manager 向 Wayland client 发送 Keyboard capability 的 available/unavailable 事件。 + +CTest 使用 `WLR_BACKENDS=headless,libinput`,并显式采用 Treeland 服务的 +`LIBSEAT_BACKEND=seatd` 和 `SEATD_SOCK=/run/dde-seatd.sock`。启动前,runner 会同时检查 +`/dev/uinput` 写权限和对 CTest 注入的 `SEATD_SOCK` 的实际连接;缺少任一条件以退出码 77 +跳过,不能视为通过。 + +尚未覆盖物理按键事件、pointer/touch 设备,以及 input-manager settings/apply 的行为。 diff --git a/tests/protocols/treeland-input-manager-uinput-v1/setup.cpp b/tests/protocols/treeland-input-manager-uinput-v1/setup.cpp new file mode 100644 index 0000000000..24b0af0270 --- /dev/null +++ b/tests/protocols/treeland-input-manager-uinput-v1/setup.cpp @@ -0,0 +1,133 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "treeland-input-manager-uinput-v1.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace { +constexpr char kDeviceName[] = "Treeland protocol uinput keyboard"; + +int g_uinputFd = -1; +bool g_created = false; +bool g_keyboardAdded = false; +bool g_keyboardRemoved = false; +bool g_skip = false; + +bool hasSeatdSession() +{ + const char *socketPath = std::getenv("SEATD_SOCK"); + sockaddr_un address {}; + if (!socketPath || !*socketPath || std::strlen(socketPath) >= sizeof(address.sun_path)) + return false; + + const int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); + if (fd < 0) + return false; + + address.sun_family = AF_UNIX; + std::strncpy(address.sun_path, socketPath, sizeof(address.sun_path) - 1); + const bool connected = connect(fd, reinterpret_cast(&address), sizeof(address)) == 0; + close(fd); + return connected; +} + +bool isTestKeyboard(WInputDevice *device) +{ + return device && device->type() == WInputDevice::Type::Keyboard + && device->name() == QLatin1String(kDeviceName); +} + +bool createKeyboard() +{ + g_uinputFd = open("/dev/uinput", O_WRONLY | O_NONBLOCK | O_CLOEXEC); + if (g_uinputFd < 0) + return false; + + if (ioctl(g_uinputFd, UI_SET_EVBIT, EV_KEY) < 0 + || ioctl(g_uinputFd, UI_SET_KEYBIT, KEY_A) < 0) { + close(g_uinputFd); + g_uinputFd = -1; + return false; + } + + uinput_setup setup {}; + std::strncpy(setup.name, kDeviceName, sizeof(setup.name) - 1); + setup.id.bustype = BUS_VIRTUAL; + setup.id.vendor = 0xdee1; + setup.id.product = 0x0001; + setup.id.version = 1; + if (ioctl(g_uinputFd, UI_DEV_SETUP, &setup) < 0 + || ioctl(g_uinputFd, UI_DEV_CREATE) < 0) { + close(g_uinputFd); + g_uinputFd = -1; + return false; + } + + g_created = true; + return true; +} + +void destroyKeyboard() +{ + if (g_uinputFd < 0) + return; + ioctl(g_uinputFd, UI_DEV_DESTROY); + close(g_uinputFd); + g_uinputFd = -1; +} +} + +extern "C" bool protocol_test_preflight() +{ + return access("/dev/uinput", W_OK) == 0 && hasSeatdSession(); +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + QObject::connect(server->backend(), &WBackend::inputAdded, server, [](WInputDevice *device) { + if (isTestKeyboard(device)) + g_keyboardAdded = true; + }); + QObject::connect(server->backend(), &WBackend::inputRemoved, server, [](WInputDevice *device) { + if (isTestKeyboard(device)) + g_keyboardRemoved = true; + }); + + if (!createKeyboard()) + g_skip = true; +} + +extern "C" bool protocol_test_skip() +{ + return g_skip; +} + +extern "C" void input_manager_uinput_read_state(void *data) +{ + *static_cast(data) = { + .created = g_created, + .keyboard_added = g_keyboardAdded, + .keyboard_removed = g_keyboardRemoved, + }; +} + +extern "C" void input_manager_uinput_destroy(void *) +{ + destroyKeyboard(); +} diff --git a/tests/protocols/treeland-input-manager-uinput-v1/treeland-input-manager-uinput-v1.c b/tests/protocols/treeland-input-manager-uinput-v1/treeland-input-manager-uinput-v1.c new file mode 100644 index 0000000000..6ab6a6065e --- /dev/null +++ b/tests/protocols/treeland-input-manager-uinput-v1/treeland-input-manager-uinput-v1.c @@ -0,0 +1,107 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "client-connection.h" +#include "server-bridge-api.h" +#include "treeland-input-manager-uinput-v1.h" +#include "treeland-input-manager-unstable-v1-client-protocol.h" + +#include + +extern void input_manager_uinput_read_state(void *data); +extern void input_manager_uinput_destroy(void *data); + +struct capability_state { + uint32_t available_types; + uint32_t unavailable_types; + int available_count; + int unavailable_count; +}; + +static void capability_available(void *data, + struct treeland_input_manager_v1 *manager, + uint32_t types, + struct wl_seat *seat) +{ + (void)manager; + (void)seat; + struct capability_state *state = data; + state->available_types |= types; + ++state->available_count; +} + +static void capability_unavailable(void *data, + struct treeland_input_manager_v1 *manager, + uint32_t types, + struct wl_seat *seat) +{ + (void)manager; + (void)seat; + struct capability_state *state = data; + state->unavailable_types |= types; + ++state->unavailable_count; +} + +static const struct treeland_input_manager_v1_listener manager_listener = { + .capability_available = capability_available, + .capability_unavailable = capability_unavailable, +}; + +static int read_state(struct input_manager_uinput_state *state) +{ + return invoke_on_server_thread(input_manager_uinput_read_state, state); +} + +int protocol_test_run(const char *socket_name) +{ + int stage = 0; + struct client_connection connection; + struct capability_state capabilities = {0}; + struct input_manager_uinput_state state = {0}; + if (!client_connect(&connection, socket_name)) + return 1; + + struct wl_seat *seat = client_bind(&connection, "wl_seat", &wl_seat_interface, 1); + struct treeland_input_manager_v1 *manager = client_bind( + &connection, "treeland_input_manager_v1", &treeland_input_manager_v1_interface, 1); + if (!seat || !manager) + goto failed; + stage = 1; + + treeland_input_manager_v1_add_listener(manager, &manager_listener, &capabilities); + if (wl_display_roundtrip(connection.display) < 0) + goto failed; + stage = 2; + + if (!read_state(&state) || !state.created || !state.keyboard_added + || capabilities.available_types != TREELAND_INPUT_MANAGER_V1_DEVICE_TYPE_KEYBOARD) { + fprintf(stderr, "input-manager uinput: keyboard did not reach WBackend/input-manager\n"); + goto failed; + } + stage = 3; + + if (!invoke_on_server_thread(input_manager_uinput_destroy, NULL) + || wl_display_roundtrip(connection.display) < 0) + goto failed; + stage = 4; + + if (!read_state(&state) || !state.keyboard_removed + || capabilities.unavailable_types != TREELAND_INPUT_MANAGER_V1_DEVICE_TYPE_KEYBOARD) { + fprintf(stderr, "input-manager uinput: keyboard removal did not reach input-manager\n"); + goto failed; + } + + treeland_input_manager_v1_destroy(manager); + wl_seat_destroy(seat); + client_disconnect(&connection); + return 0; + +failed: + fprintf(stderr, + "input-manager uinput failed at stage %d: created=%d added=%d removed=%d " + "available=0x%x unavailable=0x%x counts=(%d,%d)\n", + stage, state.created, state.keyboard_added, state.keyboard_removed, + capabilities.available_types, capabilities.unavailable_types, + capabilities.available_count, capabilities.unavailable_count); + client_disconnect(&connection); + return 1; +} diff --git a/tests/protocols/treeland-input-manager-uinput-v1/treeland-input-manager-uinput-v1.h b/tests/protocols/treeland-input-manager-uinput-v1/treeland-input-manager-uinput-v1.h new file mode 100644 index 0000000000..3ae2b856a8 --- /dev/null +++ b/tests/protocols/treeland-input-manager-uinput-v1/treeland-input-manager-uinput-v1.h @@ -0,0 +1,18 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +struct input_manager_uinput_state { + int created; + int keyboard_added; + int keyboard_removed; +}; + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/treeland-input-manager-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-input-manager-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..1ce0d8c9b4 --- /dev/null +++ b/tests/protocols/treeland-input-manager-unstable-v1/CMakeLists.txt @@ -0,0 +1,7 @@ + +treeland_add_protocol_test( + NAME treeland_input_manager_unstable_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-input-manager-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-input-manager-unstable-v1.c" +) diff --git a/tests/protocols/treeland-input-manager-unstable-v1/README.md b/tests/protocols/treeland-input-manager-unstable-v1/README.md new file mode 100644 index 0000000000..57189ad6d1 --- /dev/null +++ b/tests/protocols/treeland-input-manager-unstable-v1/README.md @@ -0,0 +1,64 @@ +# `treeland-input-manager-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`treeland_input_manager_v1` / `treeland_pointer_device_configuration_v1` / + `treeland_keyboard_settings_v1` +- 测试源码: + - 默认:`tests/protocols/treeland-input-manager-unstable-v1/` + - 可选系统集成:`tests/protocols/treeland-input-manager-uinput-v1/` +- Fixture:desktop integration fixture(`protocol_test_setup` 创建 headless output) +- 覆盖等级:**I / E(可选)**(默认测试不依赖输入设备;uinput 测试为真实后端 E) + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | +| --- | --- | --- | +| 空设备 manager | 绑定 manager + `wl_seat` 并完成 roundtrip | manager 可绑定且无设备 capability 不会导致协议错误或崩溃 | +| 真实设备加入(可选) | `/dev/uinput` 创建虚拟键盘,不发送任何按键 | 真实 libinput 设备触发 `WBackend::inputAdded`,client 收到 Keyboard `capability_available` | +| 真实设备移除(可选) | 销毁同一 uinput 设备 | 真实 libinput 设备触发 `WBackend::inputRemoved`,client 收到 Keyboard `capability_unavailable` | + +## 已证明的生产链路 + +默认 desktop 测试先创建 headless output,再绑定 `wl_seat` 和 manager 并完成 roundtrip。 +它不注入 capability,也不伪造 `WInputDevice` 或 wlroots/libinput 设备,因此在无输入设备、 +无 `/dev/uinput` 权限的开发和 CI 环境中始终执行,不会以 Skip 掩盖失败。 + +可选 uinput 测试由 CMake 开关 +`TREELAND_ENABLE_UINPUT_PROTOCOL_TESTS=ON` 注册。它将测试 backend 设为 +`headless,libinput`,打开 `/dev/uinput` 创建 `BUS_VIRTUAL` 键盘,但绝不写入 +`EV_KEY` 输入事件。设备经 udev/libinput 被 wlroots 发现后,`WBackend::inputAdded` 触发 +input-manager 的生产 `onInputAdded`;销毁设备则经 `inputRemoved` 触发 +`onInputRemoved`。客户端分别断言 Keyboard capability 的 available/unavailable 事件。 +此测试没有以 timeout 猜测设备状态:backend 信号及对应 Wayland 事件是唯一验收依据。 + +服务端实现位于 `src/modules/input-manager/inputmanagerinterfacev1.h`、 +`inputmanagerinterfacev1.cpp`。 + +`bind_resource` 及 capability 广播路径会跳过找不到 `wlr_seat_client` 的 client,故 client +先后绑定 `wl_seat` 与 manager 均不会解引用空 seat client。 + +## 可选 E 级测试的启用与跳过 + +uinput 测试默认不加入构建,避免普通开发和 CI 环境访问宿主输入子系统。手动启用: + +```bash +cmake --preset ci -DTREELAND_ENABLE_UINPUT_PROTOCOL_TESTS=ON +cmake --build --preset ci --target test_treeland_input_manager_uinput_v1 +ctest --test-dir build --output-on-failure -R '^test_treeland_input_manager_uinput_v1$' +``` + +没有 `/dev/uinput` 或当前用户无写权限时,测试以退出码 77 标记为 **Skipped**;这不是 +通过结果。测试需要可建立 libinput session 的 Linux 环境,若 backend 未接收到设备的 +加入或移除信号,断言会立即失败,而不是等待超时。 + +该层验证的是真实键盘 capability 生命周期,不等同于 mouse/touchpad 的 libinput 配置持久 +化;后者仍需要受控的实际指针设备或更深的输入配置系统集成。settings/apply 的设备可用 +路径也应放在同类可选 E2E 测试中,而不应通过生产测试钩子伪造 capability。 + +## 已知边界 / 下一项结果 + +- mouse/touchpad 对真实 libinput 设备的 settings/apply、配置持久化与生效尚未验证。 +- uinput 键盘的 repeat、NumLock 配置写入:当前 E 层的目标仅为热插拔 capability,不把 + 虚拟设备配置当作用户输入或物理硬件行为。 +- `pointer_device_configuration` 的无设备错误路径:未验证。 diff --git a/tests/protocols/treeland-input-manager-unstable-v1/setup.cpp b/tests/protocols/treeland-input-manager-unstable-v1/setup.cpp new file mode 100644 index 0000000000..1cf3d1aa0e --- /dev/null +++ b/tests/protocols/treeland-input-manager-unstable-v1/setup.cpp @@ -0,0 +1,65 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "server-bridge.h" +#include "modules/input-manager/inputmanagerinterfacev1.h" +#include "core/waylandserver.h" +#include "treeland-input-manager-unstable-v1.h" + +#include +#include + +namespace { +input_mgr_state g_state; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + auto *manager = server->backend()->server()->findInterface(); + Q_ASSERT(manager); + + QObject::connect(manager, + &TreelandInputManagerInterfaceV1::touchpadSettingsCreated, + server, + [server](TouchpadSettingsInterfaceV1 *settings) { + QObject::connect(settings, + &TouchpadSettingsInterfaceV1::pointerDeviceConfigurationCreated, + server, + [server](PointerDeviceConfigurationV1 *config) { + QObject::connect(config, + &PointerDeviceConfigurationV1::applied, + server, + [config](PointerDeviceConfigurationV1::ChangeFlags changes) { + g_state.pointer_changes = changes.toInt(); + g_state.pointer_scroll_factor = config->scrollFactor(); + g_state.pointer_handed_mode = static_cast(config->handedMode()); + g_state.pointer_accel_speed = config->accelSpeed(); + g_state.pointer_accel_profile = static_cast(config->accelerationProfile()); + g_state.pointer_send_events_mode = config->sendEventsMode().toInt(); + g_state.pointer_natural_scroll = config->naturalScroll(); + g_state.pointer_disable_while_typing = config->disableWhileTyping(); + g_state.pointer_tap_to_click = config->tapToClick(); + }); + }); + }); + QObject::connect(manager, + &TreelandInputManagerInterfaceV1::keyboardSettingsCreated, + server, + [server](KeyboardSettingsInterfaceV1 *settings) { + QObject::connect(settings, + &KeyboardSettingsInterfaceV1::applied, + server, + [settings](KeyboardSettingsInterfaceV1::ChangeFlags changes) { + g_state.keyboard_changes = changes.toInt(); + g_state.keyboard_repeat_rate = settings->repeatRate(); + g_state.keyboard_repeat_delay = settings->repeatDelay(); + g_state.keyboard_num_lock = settings->numLock(); + }); + }); +} + +extern "C" void input_manager_read_state(void *data) +{ + *static_cast(data) = g_state; +} diff --git a/tests/protocols/treeland-input-manager-unstable-v1/treeland-input-manager-unstable-v1.c b/tests/protocols/treeland-input-manager-unstable-v1/treeland-input-manager-unstable-v1.c new file mode 100644 index 0000000000..c5ec3e398c --- /dev/null +++ b/tests/protocols/treeland-input-manager-unstable-v1/treeland-input-manager-unstable-v1.c @@ -0,0 +1,30 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "client-connection.h" +#include "treeland-input-manager-unstable-v1-client-protocol.h" + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + if (!client_connect(&connection, socket_name)) + return 1; + + struct wl_seat *seat = client_bind(&connection, "wl_seat", &wl_seat_interface, 1); + struct treeland_input_manager_v1 *manager = client_bind( + &connection, "treeland_input_manager_v1", &treeland_input_manager_v1_interface, 1); + if (!seat || !manager) + goto failed; + + if (wl_display_roundtrip(connection.display) < 0) { + goto failed; + } + + treeland_input_manager_v1_destroy(manager); + wl_seat_destroy(seat); + client_disconnect(&connection); + return 0; + +failed: + client_disconnect(&connection); + return 1; +} diff --git a/tests/protocols/treeland-input-manager-unstable-v1/treeland-input-manager-unstable-v1.h b/tests/protocols/treeland-input-manager-unstable-v1/treeland-input-manager-unstable-v1.h new file mode 100644 index 0000000000..5c98ab68d5 --- /dev/null +++ b/tests/protocols/treeland-input-manager-unstable-v1/treeland-input-manager-unstable-v1.h @@ -0,0 +1,30 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct input_mgr_state { + uint32_t pointer_changes; + double pointer_scroll_factor; + int pointer_handed_mode; + double pointer_accel_speed; + uint32_t pointer_accel_profile; + uint32_t pointer_send_events_mode; + int pointer_natural_scroll; + int pointer_disable_while_typing; + int pointer_tap_to_click; + uint32_t keyboard_changes; + int32_t keyboard_repeat_rate; + int32_t keyboard_repeat_delay; + int keyboard_num_lock; +}; + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/treeland-keyboard-state-notify-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-keyboard-state-notify-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..f39a2e362a --- /dev/null +++ b/tests/protocols/treeland-keyboard-state-notify-unstable-v1/CMakeLists.txt @@ -0,0 +1,7 @@ + +treeland_add_protocol_test( + NAME treeland_keyboard_state_notify_unstable_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-keyboard-state-notify-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-keyboard-state-notify-unstable-v1.c" +) diff --git a/tests/protocols/treeland-keyboard-state-notify-unstable-v1/README.md b/tests/protocols/treeland-keyboard-state-notify-unstable-v1/README.md new file mode 100644 index 0000000000..e9ccebe193 --- /dev/null +++ b/tests/protocols/treeland-keyboard-state-notify-unstable-v1/README.md @@ -0,0 +1,43 @@ +# `treeland-keyboard-state-notify-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`treeland_keyboard_state_notify_manager_v1` / `treeland_keyboard_state_watcher_v1` +- 测试源码:`tests/protocols/treeland-keyboard-state-notify-unstable-v1/` +- Fixture:desktop integration fixture(`protocol_test_setup` 创建 headless output) +- 覆盖等级:**P**。 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | +| --- | --- | --- | +| Null seat watcher | `get_keyboard_state_watcher(null)` | watcher 创建成功,无 crash | +| Apply with modifiers | `set_modifiers(CAPS_LOCK)` + `set_flags(LOCKED\|UNLOCKED)` + `apply` | 无物理键盘时安全完成;不发送伪造的状态事件 | +| Real seat watcher, no modifiers | 绑定真实 seat 的 watcher 后 `apply` 无 modifiers | 不发送任何事件,不崩溃 | + +## 已证明的生产链路 + +基础用例证明协议接口的绑定、双缓冲配置和空配置行为正常。 + +客户端绑定 `keyboard_state_notify_manager_v1` 后,`get_keyboard_state_watcher(null)` +创建 watcher。`set_modifiers` + `set_flags` + `apply` 触发 double-buffer 语义:先 +累加 modifiers 和 flags,再在 `apply` 时一次性查询当前键盘状态并发送 +`current_state`。headless 环境中 `getSeatKeyboard()` 返回 `nullopt`(无物理键盘设备), +因此不会发送 `current_state` 事件。测试断言 watcher 创建成功且 `apply` 不崩溃,证明 +空 modifier 和空键盘路径不会触发空遍历。 + +服务端实现位于 +`src/modules/keyboard-state-notify/keyboardstatenotifymanagerinterfacev1.h`、 +`keyboardstatenotifymanagerinterfacev1.cpp`。 + +## 已知边界 / 下一项结果 + +- 物理键盘产生的 key-event 路径:尚未覆盖。后续应新建仅在 + `TREELAND_ENABLE_UINPUT_PROTOCOL_TESTS=ON` 时注册的 uinput E2E target,验证 + `uinput → libinput → WBackend → keyboardGroupKeyboard() → state_changed`,而不是把 + virtual keyboard 变成当前 seat keyboard。 +- `current_state` 的初始值:未单独覆盖 watcher 在创建时已处于 Caps Lock locked 状态的 + 初始同步。 +- 多 watcher:多个 watcher 同时监听同一或不同 seat 的行为未验证。 +- seat 销毁后 watcher 行为:seat 销毁时 watcher 是否正确清理或变为 inert 未验证。 +- re-apply 语义:重复 `apply` 相同 modifier 集合是否去重或重发事件未验证。 diff --git a/tests/protocols/treeland-keyboard-state-notify-unstable-v1/setup.cpp b/tests/protocols/treeland-keyboard-state-notify-unstable-v1/setup.cpp new file mode 100644 index 0000000000..a37b75c70b --- /dev/null +++ b/tests/protocols/treeland-keyboard-state-notify-unstable-v1/setup.cpp @@ -0,0 +1,12 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "server-bridge.h" +#include "core/waylandserver.h" + +#include + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + +} diff --git a/tests/protocols/treeland-keyboard-state-notify-unstable-v1/treeland-keyboard-state-notify-unstable-v1.c b/tests/protocols/treeland-keyboard-state-notify-unstable-v1/treeland-keyboard-state-notify-unstable-v1.c new file mode 100644 index 0000000000..d3c019c03e --- /dev/null +++ b/tests/protocols/treeland-keyboard-state-notify-unstable-v1/treeland-keyboard-state-notify-unstable-v1.c @@ -0,0 +1,153 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "client-connection.h" +#include "treeland-keyboard-state-notify-unstable-v1-client-protocol.h" + +#include + +struct watcher_state { + int current_state_count; + int state_changed_count; + uint32_t last_modifier; + uint32_t last_state; + uint32_t changed_modifier[2]; + uint32_t changed_state[2]; +}; + +static void handle_current_state(void *data, + struct treeland_keyboard_state_watcher_v1 *watcher, + uint32_t modifier, + uint32_t state) +{ + (void)watcher; + struct watcher_state *ws = data; + ws->current_state_count++; + ws->last_modifier = modifier; + ws->last_state = state; +} + +static void handle_state_changed(void *data, + struct treeland_keyboard_state_watcher_v1 *watcher, + uint32_t modifier, + uint32_t state) +{ + (void)watcher; + struct watcher_state *ws = data; + if (ws->state_changed_count < 2) { + ws->changed_modifier[ws->state_changed_count] = modifier; + ws->changed_state[ws->state_changed_count] = state; + } + ws->state_changed_count++; + ws->last_modifier = modifier; + ws->last_state = state; +} + +static const struct treeland_keyboard_state_watcher_v1_listener watcher_listener = { + .current_state = handle_current_state, + .state_changed = handle_state_changed, +}; + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + if (!client_connect(&connection, socket_name)) + return 1; + + struct wl_seat *seat = client_bind(&connection, "wl_seat", + &wl_seat_interface, 1); + struct treeland_keyboard_state_notify_manager_v1 *manager = + client_bind(&connection, "treeland_keyboard_state_notify_manager_v1", + &treeland_keyboard_state_notify_manager_v1_interface, 1); + if (!seat || !manager) { + fprintf(stderr, "keyboard-state-notify: failed to bind globals\n"); + goto failed; + } + + { + struct watcher_state ws = {0}; + + struct treeland_keyboard_state_watcher_v1 *watcher = + treeland_keyboard_state_notify_manager_v1_get_keyboard_state_watcher(manager, NULL); + if (!watcher) { + fprintf(stderr, "keyboard-state-notify: get_keyboard_state_watcher(null seat) failed\n"); + goto failed; + } + + treeland_keyboard_state_watcher_v1_add_listener(watcher, &watcher_listener, &ws); + + treeland_keyboard_state_watcher_v1_set_modifiers(watcher, + TREELAND_KEYBOARD_STATE_WATCHER_V1_MODIFIER_CAPS_LOCK); + treeland_keyboard_state_watcher_v1_set_flags(watcher, + TREELAND_KEYBOARD_STATE_WATCHER_V1_WATCH_FLAG_LOCKED | + TREELAND_KEYBOARD_STATE_WATCHER_V1_WATCH_FLAG_UNLOCKED); + treeland_keyboard_state_watcher_v1_apply(watcher); + wl_display_roundtrip(connection.display); + + if (ws.current_state_count > 0) { + + if (ws.last_modifier != + TREELAND_KEYBOARD_STATE_WATCHER_V1_MODIFIER_CAPS_LOCK) { + fprintf(stderr, + "keyboard-state-notify: expected modifier=caps_lock (%u), got %u\n", + TREELAND_KEYBOARD_STATE_WATCHER_V1_MODIFIER_CAPS_LOCK, + ws.last_modifier); + treeland_keyboard_state_watcher_v1_destroy(watcher); + goto failed; + } + + if (ws.last_state > 1) { + fprintf(stderr, + "keyboard-state-notify: invalid modifier_state %u\n", + ws.last_state); + treeland_keyboard_state_watcher_v1_destroy(watcher); + goto failed; + } + } + + if (ws.state_changed_count != 0) { + fprintf(stderr, + "keyboard-state-notify: unexpected state_changed events: %d\n", + ws.state_changed_count); + treeland_keyboard_state_watcher_v1_destroy(watcher); + goto failed; + } + + treeland_keyboard_state_watcher_v1_destroy(watcher); + } + + { + struct watcher_state ws = {0}; + + struct treeland_keyboard_state_watcher_v1 *watcher = + treeland_keyboard_state_notify_manager_v1_get_keyboard_state_watcher(manager, seat); + if (!watcher) { + fprintf(stderr, "keyboard-state-notify: get_keyboard_state_watcher(seat) failed\n"); + goto failed; + } + + treeland_keyboard_state_watcher_v1_add_listener(watcher, &watcher_listener, &ws); + + treeland_keyboard_state_watcher_v1_apply(watcher); + wl_display_roundtrip(connection.display); + + if (ws.current_state_count != 0 || ws.state_changed_count != 0) { + fprintf(stderr, + "keyboard-state-notify: unexpected events with no modifiers set " + "(current_state=%d, state_changed=%d)\n", + ws.current_state_count, ws.state_changed_count); + treeland_keyboard_state_watcher_v1_destroy(watcher); + goto failed; + } + + treeland_keyboard_state_watcher_v1_destroy(watcher); + } + + treeland_keyboard_state_notify_manager_v1_destroy(manager); + wl_seat_destroy(seat); + client_disconnect(&connection); + return 0; + +failed: + client_disconnect(&connection); + return 1; +} diff --git a/tests/protocols/treeland-keyboard-state-notify-unstable-v1/treeland-keyboard-state-notify-unstable-v1.h b/tests/protocols/treeland-keyboard-state-notify-unstable-v1/treeland-keyboard-state-notify-unstable-v1.h new file mode 100644 index 0000000000..49f8b2ec23 --- /dev/null +++ b/tests/protocols/treeland-keyboard-state-notify-unstable-v1/treeland-keyboard-state-notify-unstable-v1.h @@ -0,0 +1,6 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include diff --git a/tests/protocols/treeland-layer-shell-extension-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-layer-shell-extension-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..49fb49a657 --- /dev/null +++ b/tests/protocols/treeland-layer-shell-extension-unstable-v1/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME treeland_layer_shell_extension_unstable_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-layer-shell-extension-unstable-v1.xml" + EXTRA_XMLS "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-layer-shell-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-layer-shell-extension-unstable-v1.c" +) diff --git a/tests/protocols/treeland-layer-shell-extension-unstable-v1/README.md b/tests/protocols/treeland-layer-shell-extension-unstable-v1/README.md new file mode 100644 index 0000000000..44b131e36a --- /dev/null +++ b/tests/protocols/treeland-layer-shell-extension-unstable-v1/README.md @@ -0,0 +1,7 @@ +# layer-shell-extension-unstable-v1 + +覆盖等级:P。 + +测试在真实 layer-shell surface 上创建 extension object,并以无效 pointer serial 发起 +`begin_resize`,断言收到 `resize_rejected(bad_serial)`。成功 resize、尺寸 clamp 和 +`resizing` 生命周期需要可控的真实 pointer button serial,当前未覆盖。 diff --git a/tests/protocols/treeland-layer-shell-extension-unstable-v1/setup.cpp b/tests/protocols/treeland-layer-shell-extension-unstable-v1/setup.cpp new file mode 100644 index 0000000000..e726436de4 --- /dev/null +++ b/tests/protocols/treeland-layer-shell-extension-unstable-v1/setup.cpp @@ -0,0 +1,13 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-3.0-only +#include "modules/layer-shell-extension/layershellextensionmanagerinterfacev1.h" +#include "core/waylandserver.h" +#include "server-bridge.h" + +#include + +void protocol_test_setup(WaylandServer *server) +{ + Q_ASSERT(find_server_interface(server)); + add_headless_output(server->backend(), false); +} diff --git a/tests/protocols/treeland-layer-shell-extension-unstable-v1/treeland-layer-shell-extension-unstable-v1.c b/tests/protocols/treeland-layer-shell-extension-unstable-v1/treeland-layer-shell-extension-unstable-v1.c new file mode 100644 index 0000000000..c642f2cb31 --- /dev/null +++ b/tests/protocols/treeland-layer-shell-extension-unstable-v1/treeland-layer-shell-extension-unstable-v1.c @@ -0,0 +1,51 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-3.0-only +#include "client-connection.h" +#include "treeland-layer-shell-extension-unstable-v1-client-protocol.h" +#include "wlr-layer-shell-unstable-v1-client-protocol.h" + +#include + +struct events { unsigned rejected; uint32_t reason; }; +static void resizing(void *data, struct treeland_layer_shell_extension_object_v1 *object, uint32_t value) +{ (void)data; (void)object; (void)value; } +static void resize_rejected(void *data, struct treeland_layer_shell_extension_object_v1 *object, + uint32_t reason) +{ (void)object; struct events *events = data; events->rejected++; events->reason = reason; } +static const struct treeland_layer_shell_extension_object_v1_listener listener = { resizing, resize_rejected }; + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + if (!client_connect(&connection, socket_name)) return 1; + struct wl_compositor *compositor = client_bind(&connection, "wl_compositor", &wl_compositor_interface, 1); + struct wl_output *output = client_bind(&connection, "wl_output", &wl_output_interface, 1); + struct wl_seat *seat = client_bind(&connection, "wl_seat", &wl_seat_interface, 1); + struct zwlr_layer_shell_v1 *shell = client_bind(&connection, "zwlr_layer_shell_v1", &zwlr_layer_shell_v1_interface, 1); + struct treeland_layer_shell_extension_manager_v1 *manager = client_bind(&connection, + "treeland_layer_shell_extension_manager_v1", &treeland_layer_shell_extension_manager_v1_interface, 1); + if (!compositor || !output || !seat || !shell || !manager) return 1; + struct wl_surface *surface = wl_compositor_create_surface(compositor); + struct zwlr_layer_surface_v1 *layer = zwlr_layer_shell_v1_get_layer_surface(shell, surface, output, + ZWLR_LAYER_SHELL_V1_LAYER_TOP, "protocol-test"); + struct treeland_layer_shell_extension_object_v1 *object = + treeland_layer_shell_extension_manager_v1_get_layer_shell_extension_object(manager, surface); + struct events events = { 0 }; + if (!surface || !layer || !object) return 1; + treeland_layer_shell_extension_object_v1_add_listener(object, &listener, &events); + treeland_layer_shell_extension_object_v1_begin_resize(object, seat, 0, + TREELAND_LAYER_SHELL_EXTENSION_OBJECT_V1_RESIZE_EDGE_BOTTOM, 0, 0, 0, 0); + if (wl_display_roundtrip(connection.display) < 0 || events.rejected != 1 + || events.reason != TREELAND_LAYER_SHELL_EXTENSION_OBJECT_V1_RESIZE_ERROR_BAD_SERIAL) { + fprintf(stderr, "layer-shell-extension: invalid resize was not rejected\n"); + return 1; + } + treeland_layer_shell_extension_object_v1_destroy(object); + zwlr_layer_surface_v1_destroy(layer); + wl_surface_destroy(surface); + treeland_layer_shell_extension_manager_v1_destroy(manager); + zwlr_layer_shell_v1_destroy(shell); + wl_seat_destroy(seat); wl_output_destroy(output); wl_compositor_destroy(compositor); + client_disconnect(&connection); + return 0; +} diff --git a/tests/protocols/treeland-output-group-manager-v1/CMakeLists.txt b/tests/protocols/treeland-output-group-manager-v1/CMakeLists.txt new file mode 100644 index 0000000000..6af1fbc76d --- /dev/null +++ b/tests/protocols/treeland-output-group-manager-v1/CMakeLists.txt @@ -0,0 +1,8 @@ +treeland_add_protocol_test( + NAME treeland_output_group_manager_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-output-group-manager-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-output-group-manager-v1.c" + EXTRA_XMLS + "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-output-management-unstable-v1.xml" +) diff --git a/tests/protocols/treeland-output-group-manager-v1/setup.cpp b/tests/protocols/treeland-output-group-manager-v1/setup.cpp new file mode 100644 index 0000000000..e7a02280b6 --- /dev/null +++ b/tests/protocols/treeland-output-group-manager-v1/setup.cpp @@ -0,0 +1,171 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "core/rootsurfacecontainer.h" +#include "core/waylandserver.h" +#include "modules/output-group/outputgroupmanagerinterfacev1.h" +#include "output/output.h" +#include "server-bridge.h" +#include "treeland-output-group-manager-v1.h" +#include "treelandconfig.hpp" + +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace { +void appendSpaceSeparated(char *target, size_t size, const QString &value) +{ + const QByteArray raw = value.toUtf8(); + const size_t used = strlen(target); + if (used + raw.size() + 2 > size) + return; + if (used) + target[used] = ' '; + memcpy(target + used + (used ? 1 : 0), raw.constData(), raw.size()); + target[used + (used ? 1 : 0) + raw.size()] = '\0'; +} + +output_group_server_state readState(WaylandServer *server) +{ + output_group_server_state state {}; + const auto &outputs = server->rootSurfaceContainer()->outputs(); + state.output_count = outputs.size(); + if (state.output_count > OUTPUT_GROUP_TEST_MAX_OUTPUTS) + state.output_count = OUTPUT_GROUP_TEST_MAX_OUTPUTS; + + for (int i = 0; i < state.output_count; ++i) { + Output *output = outputs.at(i); + state.proxy_index[i] = -1; + if (!output || !output->output()) + continue; + snprintf(state.uuids[i], OUTPUT_GROUP_TEST_MAX_NAME, "%s", output->uuid().toUtf8().constData()); + snprintf(state.names[i], OUTPUT_GROUP_TEST_MAX_NAME, "%s", output->output()->name().toUtf8().constData()); + state.is_enabled[i] = output->output()->isEnabled() ? 1 : 0; + state.is_source[i] = output->isSource() ? 1 : 0; + state.is_copy[i] = output->isSource() ? 0 : 1; + if (state.is_copy[i]) { + for (int j = 0; j < state.output_count; ++j) { + if (outputs.at(j) == output->proxyOutput()) + state.proxy_index[i] = j; + } + } + } + + if (auto *manager = find_server_interface(server)) { + const auto groups = manager->effectiveGroups(); + state.group_count = groups.size(); + for (const auto &group : groups) { + appendSpaceSeparated(state.group_names, sizeof(state.group_names), group.name); + appendSpaceSeparated(state.group_sources, sizeof(state.group_sources), group.sourceUuid); + } + } + return state; +} + +bool g_configNormalized = false; + +void normalizeInitialOutputConfig(WaylandServer *server) +{ + // The protocol test asserts the bind-time group dump is empty, so drop any + // group persisted by an earlier run. Group membership left behind on the + // outputs' own configurations is cleared lazily by the compositor once it + // recomputes the effective state. + server->globalConfig()->setOutputGroups(QString()); + g_configNormalized = true; +} + +// The harness starts the headless outputs disabled. The protocol only accepts +// connected *and enabled* outputs, so the fixture turns them on like a user +// session would. +void ensureOutputsEnabled(WaylandServer *server) +{ + for (auto *output : server->rootSurfaceContainer()->outputs()) { + if (output && output->output() && !output->output()->isEnabled()) + output->enable(); + } +} +} // namespace + +void protocol_test_setup(WaylandServer *server) +{ + // Copy mode mirrors existing outputs, so the fixture needs four real + // backend outputs: two groups with a source and a mirror each. The harness + // already provides one output. + for (int i = 0; i < OUTPUT_GROUP_TEST_MAX_OUTPUTS - 1; ++i) + add_headless_output(server->backend(), false); + + auto *config = server->globalConfig(); + if (config->isInitializeSucceeded()) { + normalizeInitialOutputConfig(server); + } else { + QObject::connect(config, + &TreelandConfig::configInitializeSucceed, + server, + [server](auto *) { normalizeInitialOutputConfig(server); }); + } +} + +extern "C" bool protocol_test_ready(WaylandServer *server) +{ + ensureOutputsEnabled(server); + return g_configNormalized + && server->rootSurfaceContainer()->outputs().size() == OUTPUT_GROUP_TEST_MAX_OUTPUTS; +} + +// The fixture can enable or disable an output by uuid, like an unplug or a +// user turning a screen off. Disabling is followed by an availability +// notification so the compositor re-evaluates the output groups. +extern "C" void output_group_set_output_enabled(void *data) +{ + auto *request = static_cast(data); + auto *server = WaylandServer::instance(); + const QString uuid = QString::fromUtf8(request->uuid); + + for (auto *output : server->rootSurfaceContainer()->outputs()) { + if (!output || !output->output() || output->uuid() != uuid) + continue; + + if (request->enabled == output->output()->isEnabled()) + break; + + if (request->enabled) { + output->enable(); + } else { + WOutputStateGuard state; + wlr_output_state_set_enabled(state.get(), false); + if (!wlr_output_commit_state(output->output()->handle(), state.get())) + return; + } + break; + } + + if (auto *manager = find_server_interface(server)) + manager->notifyOutputAvailabilityChanged(); +} + +extern "C" void output_group_render(void *data) +{ + Q_UNUSED(data); + const auto &outputs = WaylandServer::instance()->rootSurfaceContainer()->outputs(); + + // Force the production output frames that commit a queued output-management + // transaction, so a wlr-output-management apply can complete in the test. + // Every output is rendered: which one carries the commit job depends on the + // order the outputs were registered in. + for (auto *output : outputs) { + if (output && output->screenViewport()) + WaylandServer::instance()->window()->render(output->screenViewport(), true); + } +} + +extern "C" void output_group_read_state(void *data) +{ + *static_cast(data) = readState(WaylandServer::instance()); +} diff --git a/tests/protocols/treeland-output-group-manager-v1/treeland-output-group-manager-v1.c b/tests/protocols/treeland-output-group-manager-v1/treeland-output-group-manager-v1.c new file mode 100644 index 0000000000..c98c99f475 --- /dev/null +++ b/tests/protocols/treeland-output-group-manager-v1/treeland-output-group-manager-v1.c @@ -0,0 +1,1258 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "client-connection.h" +#include "server-bridge-api.h" +#include "treeland-output-group-manager-v1.h" +#include "treeland-output-group-manager-unstable-v1-client-protocol.h" +#include "wlr-output-management-unstable-v1-client-protocol.h" + +#include +#include +#include +#include + +extern void output_group_read_state(void *data); +extern void output_group_set_output_enabled(void *data); +extern void output_group_render(void *data); + +#define MAX_HEADS OUTPUT_GROUP_TEST_MAX_OUTPUTS + +// Minimal wlr-output-management client: it only needs to reach the head of a +// given output and push one configuration through it. +struct head_slot { + struct test_ctx *ctx; + struct zwlr_output_head_v1 *head; + struct zwlr_output_mode_v1 *mode; + char name[64]; + int enabled; +}; + +enum { MAX_MIRRORS = OUTPUT_GROUP_TEST_MAX_OUTPUTS }; + +struct group_proxy { + struct treeland_output_group_v1 *obj; + int name_count; + char name[64]; + int state_count; + char source[64]; + int mirror_count; + char mirrors[MAX_MIRRORS][64]; + int done_count; + int removed_count; + int failure_count; + uint32_t last_failure; + char last_failure_uuid[64]; + int state_count_at; + int failure_count_at; +}; + +struct test_ctx { + struct client_connection connection; + struct treeland_output_group_manager_v1 *manager; + + int groups_done_count; + int group_added_count; + char added_names[OUTPUT_GROUP_TEST_MAX_GROUPS][64]; + int group_removed_count; + char removed_name[64]; + + struct group_proxy first; + struct group_proxy second; + struct group_proxy invalid; + struct group_proxy promotion; + struct group_proxy queued; + + struct output_group_server_state server; + char uuid[OUTPUT_GROUP_TEST_MAX_OUTPUTS][64]; + + struct zwlr_output_manager_v1 *wlrManager; + struct head_slot *headSlots[MAX_HEADS]; + int headCount; + int headsDone; + uint32_t wlrSerial; + struct zwlr_output_configuration_v1 *configuration; + int configurationSucceeded; + int configurationFailed; + + struct test_result *results; + int result_count; + int result_cap; +}; + +/* ---- tiny result bookkeeping (same contract as the other protocol tests) ---- */ + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +/* ---- events ---- */ + +static void parse_uuid_array(struct wl_array *array, uint32_t count, char mirrors[][64]) +{ + if (!array || count == 0 || array->size == 0) + return; + + const size_t length = array->size / count; + const char *cursor = array->data; + for (uint32_t i = 0; i < count && i < MAX_MIRRORS; ++i) { + const size_t copy = length < 63 ? length : 63; + memcpy(mirrors[i], cursor, copy); + mirrors[i][copy] = '\0'; + cursor += length; + } +} + +static void group_name_event(void *data, struct treeland_output_group_v1 *obj, const char *name) +{ + (void)obj; + struct group_proxy *proxy = data; + proxy->name_count++; + snprintf(proxy->name, sizeof(proxy->name), "%s", name ? name : ""); +} + +static void group_done_event(void *data, struct treeland_output_group_v1 *obj) +{ + (void)obj; + struct group_proxy *proxy = data; + proxy->done_count++; +} + +static void group_state_event(void *data, + struct treeland_output_group_v1 *obj, + const char *source, + uint32_t count, + struct wl_array *uuids) +{ + (void)obj; + struct group_proxy *proxy = data; + proxy->state_count++; + snprintf(proxy->source, sizeof(proxy->source), "%s", source ? source : ""); + proxy->mirror_count = (int)count; + for (int i = 0; i < MAX_MIRRORS; ++i) + proxy->mirrors[i][0] = '\0'; + parse_uuid_array(uuids, count, proxy->mirrors); +} + +static void group_removed_event(void *data, struct treeland_output_group_v1 *obj) +{ + (void)obj; + struct group_proxy *proxy = data; + proxy->removed_count++; +} + +static void group_failure_event(void *data, + struct treeland_output_group_v1 *obj, + uint32_t code, + const char *uuid) +{ + (void)obj; + struct group_proxy *proxy = data; + proxy->failure_count++; + proxy->last_failure = code; + snprintf(proxy->last_failure_uuid, sizeof(proxy->last_failure_uuid), "%s", uuid ? uuid : ""); +} + +static const struct treeland_output_group_v1_listener group_listener = { + .name = group_name_event, + .done = group_done_event, + .state = group_state_event, + .removed = group_removed_event, + .operation_failed = group_failure_event, +}; + +static void manager_group_added(void *data, + struct treeland_output_group_manager_v1 *manager, + const char *name) +{ + (void)manager; + struct test_ctx *ctx = data; + if (ctx->group_added_count < OUTPUT_GROUP_TEST_MAX_GROUPS) + snprintf(ctx->added_names[ctx->group_added_count], 64, "%s", name ? name : ""); + ctx->group_added_count++; +} + +static void manager_groups_done(void *data, struct treeland_output_group_manager_v1 *manager) +{ + (void)manager; + struct test_ctx *ctx = data; + ctx->groups_done_count++; +} + +static void manager_group_removed(void *data, + struct treeland_output_group_manager_v1 *manager, + const char *name) +{ + (void)manager; + struct test_ctx *ctx = data; + ctx->group_removed_count++; + snprintf(ctx->removed_name, sizeof(ctx->removed_name), "%s", name ? name : ""); +} + +static const struct treeland_output_group_manager_v1_listener manager_listener = { + .group_added = manager_group_added, + .groups_done = manager_groups_done, + .group_removed = manager_group_removed, +}; + +static void mode_size_event(void *data, struct zwlr_output_mode_v1 *mode, int32_t width, int32_t height) +{ + (void)data; + (void)mode; + (void)width; + (void)height; +} + +static void mode_refresh_event(void *data, struct zwlr_output_mode_v1 *mode, int32_t refresh) +{ + (void)data; + (void)mode; + (void)refresh; +} + +static void mode_preferred_event(void *data, struct zwlr_output_mode_v1 *mode) +{ + (void)data; + (void)mode; +} + +static void mode_finished_event(void *data, struct zwlr_output_mode_v1 *mode) +{ + (void)data; + (void)mode; +} + +static const struct zwlr_output_mode_v1_listener mode_listener = { + .size = mode_size_event, + .refresh = mode_refresh_event, + .preferred = mode_preferred_event, + .finished = mode_finished_event, +}; + +static void head_name_event(void *data, struct zwlr_output_head_v1 *head, const char *name) +{ + (void)head; + struct head_slot *slot = data; + snprintf(slot->name, sizeof(slot->name), "%s", name ? name : ""); +} + +static void head_description_event(void *data, struct zwlr_output_head_v1 *head, const char *description) +{ + (void)data; + (void)head; + (void)description; +} + +static void head_physical_size_event(void *data, struct zwlr_output_head_v1 *head, int32_t w, int32_t h) +{ + (void)data; + (void)head; + (void)w; + (void)h; +} + +static void head_mode_event(void *data, struct zwlr_output_head_v1 *head, struct zwlr_output_mode_v1 *mode) +{ + (void)head; + struct head_slot *slot = data; + if (!slot->mode) + slot->mode = mode; + zwlr_output_mode_v1_add_listener(mode, &mode_listener, slot); +} + +static void head_enabled_event(void *data, struct zwlr_output_head_v1 *head, int32_t enabled) +{ + (void)head; + ((struct head_slot *)data)->enabled = enabled; +} + +static void head_current_mode_event(void *data, struct zwlr_output_head_v1 *head, struct zwlr_output_mode_v1 *mode) +{ + (void)data; + (void)head; + (void)mode; +} + +static void head_position_event(void *data, struct zwlr_output_head_v1 *head, int32_t x, int32_t y) +{ + (void)data; + (void)head; + (void)x; + (void)y; +} + +static void head_transform_event(void *data, struct zwlr_output_head_v1 *head, int32_t transform) +{ + (void)data; + (void)head; + (void)transform; +} + +static void head_scale_event(void *data, struct zwlr_output_head_v1 *head, wl_fixed_t scale) +{ + (void)data; + (void)head; + (void)scale; +} + +static void head_finished_event(void *data, struct zwlr_output_head_v1 *head) +{ + (void)data; + (void)head; +} + +static void head_make_event(void *data, struct zwlr_output_head_v1 *head, const char *make) +{ + (void)data; + (void)head; + (void)make; +} + +static void head_model_event(void *data, struct zwlr_output_head_v1 *head, const char *model) +{ + (void)data; + (void)head; + (void)model; +} + +static void head_serial_number_event(void *data, struct zwlr_output_head_v1 *head, const char *serial) +{ + (void)data; + (void)head; + (void)serial; +} + +static void head_adaptive_sync_event(void *data, struct zwlr_output_head_v1 *head, uint32_t state) +{ + (void)data; + (void)head; + (void)state; +} + +static const struct zwlr_output_head_v1_listener head_listener = { + .name = head_name_event, + .description = head_description_event, + .physical_size = head_physical_size_event, + .mode = head_mode_event, + .enabled = head_enabled_event, + .current_mode = head_current_mode_event, + .position = head_position_event, + .transform = head_transform_event, + .scale = head_scale_event, + .finished = head_finished_event, + .make = head_make_event, + .model = head_model_event, + .serial_number = head_serial_number_event, + .adaptive_sync = head_adaptive_sync_event, +}; + +static void wlr_manager_head(void *data, struct zwlr_output_manager_v1 *manager, + struct zwlr_output_head_v1 *head) +{ + (void)manager; + struct test_ctx *ctx = data; + if (ctx->headCount >= MAX_HEADS) + return; + + struct head_slot *slot = calloc(1, sizeof(*slot)); + slot->ctx = ctx; + slot->head = head; + ctx->headSlots[ctx->headCount++] = slot; + zwlr_output_head_v1_add_listener(head, &head_listener, slot); +} + +static void wlr_manager_done(void *data, struct zwlr_output_manager_v1 *manager, uint32_t serial) +{ + (void)manager; + struct test_ctx *ctx = data; + ctx->wlrSerial = serial; + ctx->headsDone = 1; +} + +static void wlr_manager_finished(void *data, struct zwlr_output_manager_v1 *manager) +{ + (void)manager; + (void)data; +} + +static const struct zwlr_output_manager_v1_listener wlr_manager_listener = { + .head = wlr_manager_head, + .done = wlr_manager_done, + .finished = wlr_manager_finished, +}; + +static void configuration_succeeded_event(void *data, struct zwlr_output_configuration_v1 *configuration) +{ + (void)configuration; + ((struct test_ctx *)data)->configurationSucceeded++; +} + +static void configuration_failed_event(void *data, struct zwlr_output_configuration_v1 *configuration) +{ + (void)configuration; + ((struct test_ctx *)data)->configurationFailed++; +} + +static void configuration_cancelled_event(void *data, struct zwlr_output_configuration_v1 *configuration) +{ + (void)configuration; + ((struct test_ctx *)data)->configurationFailed++; +} + +static const struct zwlr_output_configuration_v1_listener configuration_listener = { + .succeeded = configuration_succeeded_event, + .failed = configuration_failed_event, + .cancelled = configuration_cancelled_event, +}; + +static struct head_slot *head_for_uuid(struct test_ctx *ctx, const char *uuid) +{ + const char *name = NULL; + for (int i = 0; i < ctx->server.output_count; ++i) { + if (strcmp(ctx->server.uuids[i], uuid) == 0) + name = ctx->server.names[i]; + } + if (!name) + return NULL; + + for (int i = 0; i < ctx->headCount; ++i) { + if (ctx->headSlots[i] && strcmp(ctx->headSlots[i]->name, name) == 0) + return ctx->headSlots[i]; + } + return NULL; +} + +static void attach_listener(struct group_proxy *proxy) +{ + proxy->failure_count_at = -1; + if (proxy->obj) + treeland_output_group_v1_add_listener(proxy->obj, &group_listener, proxy); +} + +static int find_output(const struct output_group_server_state *state, const char *uuid) +{ + for (int i = 0; i < state->output_count; ++i) { + if (strcmp(state->uuids[i], uuid) == 0) + return i; + } + return -1; +} + +static int read_server_state(struct test_ctx *ctx) +{ + memset(&ctx->server, 0, sizeof(ctx->server)); + return invoke_on_server_thread(output_group_read_state, &ctx->server); +} + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->manager = client_bind(&ctx->connection, + "treeland_output_group_manager_v1", + &treeland_output_group_manager_v1_interface, + 1); + if (ctx->manager) + treeland_output_group_manager_v1_add_listener(ctx->manager, &manager_listener, ctx); + + // The apply case needs the wlr-output-management view of the outputs. + ctx->wlrManager = client_bind(&ctx->connection, + "zwlr_output_manager_v1", + &zwlr_output_manager_v1_interface, + 4); + if (ctx->wlrManager) + zwlr_output_manager_v1_add_listener(ctx->wlrManager, &wlr_manager_listener, ctx); + + return ctx->manager != NULL; +} + +static int has_legacy_global(struct test_ctx *ctx) +{ + for (uint32_t i = 0; i < ctx->connection.global_count; ++i) { + if (strcmp(ctx->connection.globals[i].interface, + "treeland_virtual_output_manager_v1") == 0) + return 1; + } + return 0; +} + +/* ---- cases ---- */ + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); + int (*verify)(struct test_ctx *ctx); +}; + +static int bind_verify(struct test_ctx *ctx) +{ + return ctx->groups_done_count == 1 && ctx->group_added_count == 0 + && !has_legacy_global(ctx); +} + +static int run_create_first(struct test_ctx *ctx) +{ + if (!read_server_state(ctx) || ctx->server.output_count != 4) + return 0; + for (int i = 0; i < ctx->server.output_count; ++i) { + if (!ctx->server.uuids[i][0]) + return 0; + snprintf(ctx->uuid[i], sizeof(ctx->uuid[i]), "%s", ctx->server.uuids[i]); + } + ctx->first.obj = treeland_output_group_manager_v1_create_group(ctx->manager, ctx->uuid[0]); + attach_listener(&ctx->first); + return ctx->first.obj != NULL; +} + +static int create_first_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->first; + return p->name_count == 1 && p->done_count == 1 && p->state_count == 1 + && p->name[0] != '\0' && strcmp(p->source, ctx->uuid[0]) == 0 + && p->mirror_count == 0 && p->failure_count == 0; +} + +static int run_first_add_mirror(struct test_ctx *ctx) +{ + ctx->first.state_count_at = ctx->first.state_count; + treeland_output_group_v1_add_output(ctx->first.obj, ctx->uuid[1]); + treeland_output_group_v1_commit(ctx->first.obj); + return 1; +} + +static int first_add_mirror_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->first; + if (!read_server_state(ctx)) + return 0; + const int sourceIndex = find_output(&ctx->server, ctx->uuid[0]); + const int mirrorIndex = find_output(&ctx->server, ctx->uuid[1]); + return p->state_count > p->state_count_at && p->mirror_count == 1 + && strcmp(p->mirrors[0], ctx->uuid[1]) == 0 + && sourceIndex >= 0 && mirrorIndex >= 0 + && ctx->server.is_copy[mirrorIndex] + && ctx->server.proxy_index[mirrorIndex] == sourceIndex; +} + +// Second group, engaged at the same time as the first one: two groups must not +// influence each other. +static int run_create_second(struct test_ctx *ctx) +{ + ctx->second.obj = treeland_output_group_manager_v1_create_group(ctx->manager, + ctx->uuid[2]); + attach_listener(&ctx->second); + return ctx->second.obj != NULL; +} + +static int create_second_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->second; + return p->name_count == 1 && p->done_count == 1 && p->state_count == 1 + && strcmp(p->name, ctx->first.name) != 0 + && strcmp(p->source, ctx->uuid[2]) == 0 && p->mirror_count == 0; +} + +static int run_second_add_mirror(struct test_ctx *ctx) +{ + ctx->first.state_count_at = ctx->first.state_count; + ctx->second.state_count_at = ctx->second.state_count; + treeland_output_group_v1_add_output(ctx->second.obj, ctx->uuid[3]); + treeland_output_group_v1_commit(ctx->second.obj); + return 1; +} + +static int second_add_mirror_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->second; + if (!read_server_state(ctx)) + return 0; + const int firstSource = find_output(&ctx->server, ctx->uuid[0]); + const int firstMirror = find_output(&ctx->server, ctx->uuid[1]); + const int secondSource = find_output(&ctx->server, ctx->uuid[2]); + const int secondMirror = find_output(&ctx->server, ctx->uuid[3]); + // The first group kept its own mirror while the second group was engaged. + return ctx->first.state_count == ctx->first.state_count_at + && p->state_count == p->state_count_at + 1 && p->mirror_count == 1 + && strcmp(p->mirrors[0], ctx->uuid[3]) == 0 + && ctx->server.is_copy[firstMirror] + && ctx->server.proxy_index[firstMirror] == firstSource + && ctx->server.is_copy[secondMirror] + && ctx->server.proxy_index[secondMirror] == secondSource + && ctx->server.group_count == 2; +} + +static int run_dissolve_second(struct test_ctx *ctx) +{ + ctx->first.state_count_at = ctx->first.state_count; + treeland_output_group_v1_dissolve(ctx->second.obj); + return 1; +} + +static int dissolve_second_verify(struct test_ctx *ctx) +{ + if (!read_server_state(ctx)) + return 0; + const int firstSource = find_output(&ctx->server, ctx->uuid[0]); + const int firstMirror = find_output(&ctx->server, ctx->uuid[1]); + const int secondSource = find_output(&ctx->server, ctx->uuid[2]); + const int secondMirror = find_output(&ctx->server, ctx->uuid[3]); + return ctx->second.removed_count == 1 && ctx->group_removed_count == 1 + && strcmp(ctx->removed_name, ctx->second.name) == 0 + && ctx->first.state_count == ctx->first.state_count_at + && ctx->server.group_count == 1 + && ctx->server.is_source[secondSource] && ctx->server.is_source[secondMirror] + && ctx->server.is_copy[firstMirror] + && ctx->server.proxy_index[firstMirror] == firstSource; +} + +static int run_duplicate_mirror(struct test_ctx *ctx) +{ + ctx->first.state_count_at = ctx->first.state_count; + ctx->first.failure_count_at = ctx->first.failure_count; + treeland_output_group_v1_add_output(ctx->first.obj, ctx->uuid[1]); + treeland_output_group_v1_commit(ctx->first.obj); + return 1; +} + +static int duplicate_mirror_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->first; + return p->failure_count == p->failure_count_at + 1 + && p->last_failure == TREELAND_OUTPUT_GROUP_V1_FAILURE_DUPLICATE_OUTPUT + && strcmp(p->last_failure_uuid, ctx->uuid[1]) == 0 + && p->state_count == p->state_count_at; +} + +static int run_invalid_output(struct test_ctx *ctx) +{ + ctx->first.state_count_at = ctx->first.state_count; + ctx->first.failure_count_at = ctx->first.failure_count; + treeland_output_group_v1_set_source(ctx->first.obj, "00000000-not-an-output-000000000000"); + treeland_output_group_v1_commit(ctx->first.obj); + return 1; +} + +static int invalid_output_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->first; + return p->failure_count == p->failure_count_at + 1 + && p->last_failure == TREELAND_OUTPUT_GROUP_V1_FAILURE_INVALID_OUTPUT + && p->state_count == p->state_count_at + && strcmp(p->source, ctx->uuid[0]) == 0; +} + +static int run_get_invalid_name(struct test_ctx *ctx) +{ + ctx->invalid.obj = treeland_output_group_manager_v1_get_group(ctx->manager, "no-such-group"); + attach_listener(&ctx->invalid); + return ctx->invalid.obj != NULL; +} + +static int get_invalid_name_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->invalid; + return p->name_count == 0 && p->state_count == 0 && p->done_count == 1 + && p->failure_count == 1 + && p->last_failure == TREELAND_OUTPUT_GROUP_V1_FAILURE_INVALID_NAME; +} + +static int run_invalid_name_non_fatal(struct test_ctx *ctx) +{ + ctx->invalid.failure_count_at = ctx->invalid.failure_count; + treeland_output_group_v1_set_source(ctx->invalid.obj, ctx->uuid[0]); + treeland_output_group_v1_commit(ctx->invalid.obj); + return 1; +} + +static int invalid_name_non_fatal_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->invalid; + // Both the queued request and the commit are rejected, and the connection + // survives them. + return p->failure_count == p->failure_count_at + 2 + && p->last_failure == TREELAND_OUTPUT_GROUP_V1_FAILURE_INVALID_NAME; +} + +// Create a group with an empty source uuid. It must come up inert (no source, +// no mirrors) without terminating the connection; the empty-source group is +// later claimed by source_in_use via set_source. +static int run_create_empty_source(struct test_ctx *ctx) +{ + ctx->second.obj = treeland_output_group_manager_v1_create_group(ctx->manager, ""); + attach_listener(&ctx->second); + if (!ctx->second.obj) + return 0; + return 1; +} + +static int source_in_use_run(struct test_ctx *ctx) +{ + ctx->second.failure_count_at = ctx->second.failure_count; + ctx->second.state_count_at = ctx->second.state_count; + treeland_output_group_v1_set_source(ctx->second.obj, ctx->uuid[0]); + treeland_output_group_v1_commit(ctx->second.obj); + return 1; +} + +static int source_in_use_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->second; + return p->failure_count == p->failure_count_at + 1 + && p->last_failure == TREELAND_OUTPUT_GROUP_V1_FAILURE_OUTPUT_IN_USE + && strcmp(p->last_failure_uuid, ctx->uuid[0]) == 0 + && p->state_count == p->state_count_at; +} + +static int run_remove_mirror(struct test_ctx *ctx) +{ + ctx->first.state_count_at = ctx->first.state_count; + treeland_output_group_v1_remove_output(ctx->first.obj, ctx->uuid[1]); + treeland_output_group_v1_commit(ctx->first.obj); + return 1; +} + +static int remove_mirror_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->first; + if (!read_server_state(ctx)) + return 0; + const int mirrorIndex = find_output(&ctx->server, ctx->uuid[1]); + return p->state_count > p->state_count_at && p->mirror_count == 0 + && strcmp(p->source, ctx->uuid[0]) == 0 + && mirrorIndex >= 0 && ctx->server.is_source[mirrorIndex]; +} + +static int run_second_set_source(struct test_ctx *ctx) +{ + ctx->second.state_count_at = ctx->second.state_count; + treeland_output_group_v1_set_source(ctx->second.obj, ctx->uuid[1]); + treeland_output_group_v1_commit(ctx->second.obj); + return 1; +} + +static int second_set_source_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->second; + return p->state_count > p->state_count_at + && strcmp(p->source, ctx->uuid[1]) == 0 + && read_server_state(ctx) && ctx->server.group_count == 2; +} + +static int set_output_enabled(struct test_ctx *ctx, const char *uuid, int enabled) +{ + (void)ctx; + + struct output_group_output_state request = { 0 }; + snprintf(request.uuid, sizeof(request.uuid), "%s", uuid); + request.enabled = enabled; + return invoke_on_server_thread(output_group_set_output_enabled, &request); +} + +// A group whose source disappears promotes one of its available mirrors. The +// promotion is temporary: when the designated source comes back it reclaims +// the source role and the promoted output becomes a mirror again. +static int run_promotion_group(struct test_ctx *ctx) +{ + ctx->promotion.obj = treeland_output_group_manager_v1_create_group(ctx->manager, ctx->uuid[2]); + attach_listener(&ctx->promotion); + if (!ctx->promotion.obj) + return 0; + treeland_output_group_v1_add_output(ctx->promotion.obj, ctx->uuid[3]); + treeland_output_group_v1_commit(ctx->promotion.obj); + return 1; +} + +static int promotion_group_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->promotion; + return strcmp(p->source, ctx->uuid[2]) == 0 && p->mirror_count == 1 + && strcmp(p->mirrors[0], ctx->uuid[3]) == 0; +} + +static int run_promotion_disable_source(struct test_ctx *ctx) +{ + ctx->promotion.state_count_at = ctx->promotion.state_count; + return set_output_enabled(ctx, ctx->uuid[2], 0); +} + +static int promotion_disable_source_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->promotion; + return p->state_count > p->state_count_at && p->mirror_count == 0 + && strcmp(p->source, ctx->uuid[3]) == 0 + && read_server_state(ctx) + && ctx->server.is_source[find_output(&ctx->server, ctx->uuid[3])]; +} + +static int run_promotion_re_enable(struct test_ctx *ctx) +{ + ctx->promotion.state_count_at = ctx->promotion.state_count; + return set_output_enabled(ctx, ctx->uuid[2], 1); +} + +static int promotion_re_enable_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->promotion; + if (!read_server_state(ctx)) + return 0; + const int promoted = find_output(&ctx->server, ctx->uuid[3]); + const int oldSource = find_output(&ctx->server, ctx->uuid[2]); + // The promotion was temporary: the designated source is back in charge, + // the temporarily promoted output is a mirror again. + return p->state_count > p->state_count_at && p->mirror_count == 1 + && strcmp(p->source, ctx->uuid[2]) == 0 + && strcmp(p->mirrors[0], ctx->uuid[3]) == 0 + && ctx->server.is_copy[promoted] + && ctx->server.proxy_index[promoted] == oldSource; +} + +static int run_promotion_dissolve(struct test_ctx *ctx) +{ + treeland_output_group_v1_dissolve(ctx->promotion.obj); + return 1; +} + +static int promotion_dissolve_verify(struct test_ctx *ctx) +{ + if (!read_server_state(ctx)) + return 0; + const int idx2 = find_output(&ctx->server, ctx->uuid[2]); + const int idx3 = find_output(&ctx->server, ctx->uuid[3]); + return ctx->promotion.removed_count == 1 && ctx->server.group_count == 0 + && ctx->server.is_source[idx2] && ctx->server.is_source[idx3]; +} + +// Free the second group and give the first group a mirror again, so the +// switched-off case can be observed on a group that is actually in copy mode. +static int run_prepare_mirror_case(struct test_ctx *ctx) +{ + treeland_output_group_v1_dissolve(ctx->second.obj); + ctx->first.state_count_at = ctx->first.state_count; + treeland_output_group_v1_add_output(ctx->first.obj, ctx->uuid[1]); + treeland_output_group_v1_commit(ctx->first.obj); + return 1; +} + +static int prepare_mirror_case_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->first; + return p->state_count > p->state_count_at && p->mirror_count == 1 + && strcmp(p->mirrors[0], ctx->uuid[1]) == 0; +} + +// Switching an output off (DPMS / single-output display) must not bring it +// back to life when the compositor reconciles the groups. +static int run_mirror_off(struct test_ctx *ctx) +{ + ctx->first.state_count_at = ctx->first.state_count; + return set_output_enabled(ctx, ctx->uuid[1], 0); +} + +static int mirror_off_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->first; + if (!read_server_state(ctx)) + return 0; + const int mirrorIndex = find_output(&ctx->server, ctx->uuid[1]); + return p->state_count > p->state_count_at && p->mirror_count == 0 + && strcmp(p->source, ctx->uuid[0]) == 0 + && mirrorIndex >= 0 && !ctx->server.is_enabled[mirrorIndex]; +} + +static int run_mirror_off_then_on(struct test_ctx *ctx) +{ + ctx->first.state_count_at = ctx->first.state_count; + return set_output_enabled(ctx, ctx->uuid[1], 1); +} + +static int mirror_off_then_on_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->first; + if (!read_server_state(ctx)) + return 0; + const int sourceIndex = find_output(&ctx->server, ctx->uuid[0]); + const int mirrorIndex = find_output(&ctx->server, ctx->uuid[1]); + return p->state_count > p->state_count_at && p->mirror_count == 1 + && strcmp(p->mirrors[0], ctx->uuid[1]) == 0 + && ctx->server.is_enabled[mirrorIndex] + && ctx->server.is_copy[mirrorIndex] + && ctx->server.proxy_index[mirrorIndex] == sourceIndex; +} + +// Only the last set_source of one commit batch is applied; the earlier +// designation is dropped without touching its output and without reporting a +// failure for it. +static int run_set_source_sequence(struct test_ctx *ctx) +{ + ctx->queued.obj = treeland_output_group_manager_v1_create_group(ctx->manager, ctx->uuid[0]); + attach_listener(&ctx->queued); + if (!ctx->queued.obj) + return 0; + + treeland_output_group_v1_set_source(ctx->queued.obj, ctx->uuid[1]); + treeland_output_group_v1_set_source(ctx->queued.obj, ctx->uuid[2]); + treeland_output_group_v1_commit(ctx->queued.obj); + return 1; +} + +static int set_source_sequence_verify(struct test_ctx *ctx) +{ + const struct group_proxy *p = &ctx->queued; + if (!read_server_state(ctx)) + return 0; + const int skippedIndex = find_output(&ctx->server, ctx->uuid[1]); + // Initial state (source uuid0) plus the state after the commit. + return p->state_count == 2 && p->failure_count == 0 + && p->mirror_count == 1 && strcmp(p->mirrors[0], ctx->uuid[0]) == 0 + && strcmp(p->source, ctx->uuid[2]) == 0 + && skippedIndex >= 0 && ctx->server.is_source[skippedIndex]; +} + +static int run_set_source_sequence_dissolve(struct test_ctx *ctx) +{ + treeland_output_group_v1_dissolve(ctx->queued.obj); + return 1; +} + +static int set_source_sequence_dissolve_verify(struct test_ctx *ctx) +{ + return ctx->queued.removed_count == 1; +} + +// Reconfiguring the outputs through wlr-output-management tears copy mode down +// and re-applies it from the groups. The protocol state must end up matching +// what is actually rendered, also when the apply changes nothing about output +// availability (here: the mirror head only moves). +static int run_output_management_apply(struct test_ctx *ctx) +{ + if (!ctx->wlrManager || !ctx->headsDone || !read_server_state(ctx)) + return 0; + + struct head_slot *slot = head_for_uuid(ctx, ctx->uuid[1]); + if (!slot) + return 0; + + struct zwlr_output_configuration_v1 *configuration = + zwlr_output_manager_v1_create_configuration(ctx->wlrManager, ctx->wlrSerial); + if (!configuration) + return 0; + zwlr_output_configuration_v1_add_listener(configuration, &configuration_listener, ctx); + + struct zwlr_output_configuration_head_v1 *configHead = + zwlr_output_configuration_v1_enable_head(configuration, slot->head); + if (!configHead) { + zwlr_output_configuration_v1_destroy(configuration); + return 0; + } + + // Headless outputs have no advertised fixed mode; use the custom mode the + // compositor already runs them with and only move the head. + zwlr_output_configuration_head_v1_set_custom_mode(configHead, 1920, 1080, 0); + zwlr_output_configuration_head_v1_set_position(configHead, 40, 60); + zwlr_output_configuration_head_v1_set_transform(configHead, WL_OUTPUT_TRANSFORM_NORMAL); + zwlr_output_configuration_head_v1_set_scale(configHead, wl_fixed_from_int(1)); + zwlr_output_configuration_head_v1_set_adaptive_sync( + configHead, ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_DISABLED); + + ctx->configuration = configuration; + zwlr_output_configuration_v1_apply(configuration); + return 1; +} + +static int output_management_apply_verify(struct test_ctx *ctx) +{ + // The apply completes on an output frame; drive frames until the + // configuration reports a result. + for (int i = 0; i < 10 && ctx->configurationSucceeded == 0 + && ctx->configurationFailed == 0; ++i) { + if (!invoke_on_server_thread(output_group_render, NULL)) + return 0; + if (wl_display_roundtrip(ctx->connection.display) < 0) + return 0; + } + + if (ctx->configuration) { + zwlr_output_configuration_v1_destroy(ctx->configuration); + ctx->configuration = NULL; + } + if (ctx->configurationSucceeded != 1 || ctx->configurationFailed != 0) { + fprintf(stderr, "output management apply failed: succeeded=%d failed=%d\n", + ctx->configurationSucceeded, ctx->configurationFailed); + return 0; + } + + // The compositor re-applies the groups asynchronously; the last reported + // group state must match the real output objects. + const struct group_proxy *p = &ctx->first; + for (int i = 0; i < 10; ++i) { + if (!invoke_on_server_thread(output_group_render, NULL)) + return 0; + if (wl_display_roundtrip(ctx->connection.display) < 0 || !read_server_state(ctx)) + return 0; + + const int sourceIndex = find_output(&ctx->server, ctx->uuid[0]); + const int mirrorIndex = find_output(&ctx->server, ctx->uuid[1]); + if (p->mirror_count == 1 && strcmp(p->mirrors[0], ctx->uuid[1]) == 0 + && ctx->server.is_copy[mirrorIndex] + && ctx->server.proxy_index[mirrorIndex] == sourceIndex) { + return 1; + } + } + + const int mirrorIndex = find_output(&ctx->server, ctx->uuid[1]); + fprintf(stderr, "group state does not match the outputs after an apply: mirrors=%d copy=%d\n", + p->mirror_count, mirrorIndex >= 0 ? ctx->server.is_copy[mirrorIndex] : -1); + return 0; +} + +// Disabling a mirror through wlr-output-management (the "turn this screen off" +// path of the display panel) must stick: the output stays off and drops out of +// the reported mirror list. +static int run_output_management_disable_mirror(struct test_ctx *ctx) +{ + if (!ctx->wlrManager || !read_server_state(ctx)) + return 0; + + struct head_slot *slot = head_for_uuid(ctx, ctx->uuid[1]); + if (!slot) + return 0; + + struct zwlr_output_configuration_v1 *configuration = + zwlr_output_manager_v1_create_configuration(ctx->wlrManager, ctx->wlrSerial); + if (!configuration) + return 0; + zwlr_output_configuration_v1_add_listener(configuration, &configuration_listener, ctx); + zwlr_output_configuration_v1_disable_head(configuration, slot->head); + + ctx->first.state_count_at = ctx->first.state_count; + ctx->configuration = configuration; + zwlr_output_configuration_v1_apply(configuration); + return 1; +} + +static int output_management_disable_mirror_verify(struct test_ctx *ctx) +{ + for (int i = 0; i < 10 && ctx->configurationSucceeded == 0 + && ctx->configurationFailed == 0; ++i) { + if (!invoke_on_server_thread(output_group_render, NULL)) + return 0; + if (wl_display_roundtrip(ctx->connection.display) < 0) + return 0; + } + + if (ctx->configuration) { + zwlr_output_configuration_v1_destroy(ctx->configuration); + ctx->configuration = NULL; + } + if (ctx->configurationSucceeded != 1 || ctx->configurationFailed != 0) { + fprintf(stderr, "disable apply failed: succeeded=%d failed=%d\n", + ctx->configurationSucceeded, ctx->configurationFailed); + return 0; + } + + struct head_slot *slot = head_for_uuid(ctx, ctx->uuid[1]); + for (int i = 0; i < 10; ++i) { + if (!invoke_on_server_thread(output_group_render, NULL)) + return 0; + if (wl_display_roundtrip(ctx->connection.display) < 0 || !read_server_state(ctx)) + return 0; + + const int mirrorIndex = find_output(&ctx->server, ctx->uuid[1]); + if (mirrorIndex >= 0 && !ctx->server.is_enabled[mirrorIndex] + && ctx->first.mirror_count == 0 && slot && slot->enabled == 0) { + return 1; + } + } + + fprintf(stderr, + "mirror disable did not stick: enabled=%d head_enabled=%d mirrors=%d\n", + find_output(&ctx->server, ctx->uuid[1]) >= 0 + ? ctx->server.is_enabled[find_output(&ctx->server, ctx->uuid[1])] + : -1, + slot ? slot->enabled : -1, + ctx->first.mirror_count); + return 0; +} + +static int run_dissolve_first(struct test_ctx *ctx) +{ + treeland_output_group_v1_dissolve(ctx->first.obj); + return 1; +} + +static int dissolve_first_verify(struct test_ctx *ctx) +{ + if (!read_server_state(ctx)) + return 0; + const int firstSource = find_output(&ctx->server, ctx->uuid[0]); + const int firstMirror = find_output(&ctx->server, ctx->uuid[1]); + return ctx->first.removed_count == 1 && ctx->group_removed_count == 3 + && strcmp(ctx->removed_name, ctx->first.name) == 0 + && ctx->server.group_count == 0 + && ctx->server.is_source[firstSource] && ctx->server.is_source[firstMirror]; +} + +static const struct test_case cases[] = { + { "manager.bind.groups_done", NULL, bind_verify }, + { "group.create.first", run_create_first, create_first_verify }, + { "group.first.add_output", run_first_add_mirror, first_add_mirror_verify }, + { "group.create.second", run_create_second, create_second_verify }, + { "group.second.add_output.two_groups_independent", run_second_add_mirror, second_add_mirror_verify }, + { "group.dissolve.second.other_group_unaffected", run_dissolve_second, dissolve_second_verify }, + { "group.add_output.duplicate", run_duplicate_mirror, duplicate_mirror_verify }, + { "group.set_source.invalid_output", run_invalid_output, invalid_output_verify }, + { "group.get_group.invalid_name", run_get_invalid_name, get_invalid_name_verify }, + { "group.invalid_name.non_fatal", run_invalid_name_non_fatal, invalid_name_non_fatal_verify }, + { "group.create.empty_source", run_create_empty_source, NULL }, + { "group.set_source.output_in_use", source_in_use_run, source_in_use_verify }, + { "group.remove_output", run_remove_mirror, remove_mirror_verify }, + { "group.set_source.second", run_second_set_source, second_set_source_verify }, + { "group.mirror.prepare", run_prepare_mirror_case, prepare_mirror_case_verify }, + { "group.mirror.switched_off_stays_off", run_mirror_off, mirror_off_verify }, + { "group.mirror.switched_on_again", run_mirror_off_then_on, mirror_off_then_on_verify }, + { "group.output_management.apply_state_consistent", run_output_management_apply, + output_management_apply_verify }, + { "group.output_management.disable_mirror", run_output_management_disable_mirror, + output_management_disable_mirror_verify }, + { "group.dissolve.first", run_dissolve_first, dissolve_first_verify }, + { "group.commit.set_source_sequence", run_set_source_sequence, set_source_sequence_verify }, + { "group.commit.set_source_sequence.dissolve", run_set_source_sequence_dissolve, set_source_sequence_dissolve_verify }, + { "group.promotion.create", run_promotion_group, promotion_group_verify }, + { "group.promotion.disable_source", run_promotion_disable_source, promotion_disable_source_verify }, + { "group.promotion.re_enable_source", run_promotion_re_enable, promotion_re_enable_verify }, + { "group.promotion.dissolve", run_promotion_dissolve, promotion_dissolve_verify }, +}; + +// A dissolved group object must terminate the connection when it is used +// again. That needs its own connection so the main one stays usable. +static int dissolved_is_fatal(const char *socket_name) +{ + struct client_connection connection = { 0 }; + if (!client_connect(&connection, socket_name)) + return 0; + + struct treeland_output_group_manager_v1 *manager = + client_bind(&connection, + "treeland_output_group_manager_v1", + &treeland_output_group_manager_v1_interface, + 1); + if (!manager) { + client_disconnect(&connection); + return 0; + } + + struct output_group_server_state state = { 0 }; + if (!invoke_on_server_thread(output_group_read_state, &state)) { + client_disconnect(&connection); + return 0; + } + + struct treeland_output_group_v1 *group = + treeland_output_group_manager_v1_create_group(manager, ""); + if (!group) { + client_disconnect(&connection); + return 0; + } + + treeland_output_group_v1_dissolve(group); + if (wl_display_roundtrip(connection.display) < 0) { + client_disconnect(&connection); + return 0; + } + + treeland_output_group_v1_set_source(group, state.uuids[0]); + const int fatal = wl_display_roundtrip(connection.display) < 0; + if (!fatal) + treeland_output_group_v1_destroy(group); + client_disconnect(&connection); + return fatal; +} + +void test_cleanup(struct test_ctx *ctx) +{ + if (ctx->first.obj) + treeland_output_group_v1_destroy(ctx->first.obj); + if (ctx->second.obj) + treeland_output_group_v1_destroy(ctx->second.obj); + if (ctx->invalid.obj) + treeland_output_group_v1_destroy(ctx->invalid.obj); + if (ctx->promotion.obj) + treeland_output_group_v1_destroy(ctx->promotion.obj); + if (ctx->configuration) + zwlr_output_configuration_v1_destroy(ctx->configuration); + if (ctx->wlrManager) + zwlr_output_manager_v1_destroy(ctx->wlrManager); + if (ctx->manager) + treeland_output_group_manager_v1_destroy(ctx->manager); + for (int i = 0; i < ctx->headCount; ++i) + free(ctx->headSlots[i]); + client_disconnect(&ctx->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx = { 0 }; + ctx.result_cap = 32; + ctx.results = calloc((size_t)ctx.result_cap, sizeof(*ctx.results)); + + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect to or bind treeland_output_group_manager_v1\n"); + test_print_results(&ctx); + test_cleanup(&ctx); + free(ctx.results); + return 1; + } + + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const int result = test_add(&ctx, cases[i].name); + if (cases[i].run && !cases[i].run(&ctx)) { + test_fail(&ctx, result, "request failed"); + } else if (wl_display_roundtrip(ctx.connection.display) < 0) { + test_fail(&ctx, result, "Wayland connection failed"); + } else if (cases[i].verify && !cases[i].verify(&ctx)) { + test_fail(&ctx, result, "assertion failed"); + } + } + + { + const int result = test_add(&ctx, "group.dissolved.fatal_error"); + if (!dissolved_is_fatal(socket_name)) + test_fail(&ctx, result, "reusing a dissolved group did not terminate the connection"); + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + free(ctx.results); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-output-group-manager-v1/treeland-output-group-manager-v1.h b/tests/protocols/treeland-output-group-manager-v1/treeland-output-group-manager-v1.h new file mode 100644 index 0000000000..6625297098 --- /dev/null +++ b/tests/protocols/treeland-output-group-manager-v1/treeland-output-group-manager-v1.h @@ -0,0 +1,52 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +#include "client-connection.h" + +#define TEST_MSG_MAX 256 + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +enum { + OUTPUT_GROUP_TEST_MAX_NAME = 64, + OUTPUT_GROUP_TEST_MAX_OUTPUTS = 4, + OUTPUT_GROUP_TEST_MAX_GROUPS = 8, + OUTPUT_GROUP_TEST_MAX_TEXT = 256, +}; + +// Asks the fixture to enable or disable one output by uuid. +struct output_group_output_state { + char uuid[OUTPUT_GROUP_TEST_MAX_NAME]; + int enabled; +}; + +// Snapshot of the compositor state, read on the compositor thread. Outputs are +// indexed in the order the compositor registered them. +struct output_group_server_state { + int output_count; + int group_count; + int is_enabled[OUTPUT_GROUP_TEST_MAX_OUTPUTS]; + int is_source[OUTPUT_GROUP_TEST_MAX_OUTPUTS]; + int is_copy[OUTPUT_GROUP_TEST_MAX_OUTPUTS]; + int proxy_index[OUTPUT_GROUP_TEST_MAX_OUTPUTS]; + char uuids[OUTPUT_GROUP_TEST_MAX_OUTPUTS][OUTPUT_GROUP_TEST_MAX_NAME]; + char names[OUTPUT_GROUP_TEST_MAX_OUTPUTS][OUTPUT_GROUP_TEST_MAX_NAME]; + char group_names[OUTPUT_GROUP_TEST_MAX_TEXT]; + char group_sources[OUTPUT_GROUP_TEST_MAX_TEXT]; +}; + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/treeland-output-manager-v2/CMakeLists.txt b/tests/protocols/treeland-output-manager-v2/CMakeLists.txt new file mode 100644 index 0000000000..600ec021b5 --- /dev/null +++ b/tests/protocols/treeland-output-manager-v2/CMakeLists.txt @@ -0,0 +1,7 @@ +treeland_add_protocol_test( + NAME treeland_output_manager_v2 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-output-manager-unstable-v2.xml" + EXTRA_XMLS "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-output-uuid-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-output-manager-v2.c" +) diff --git a/tests/protocols/treeland-output-manager-v2/README.md b/tests/protocols/treeland-output-manager-v2/README.md new file mode 100644 index 0000000000..b81526ad6d --- /dev/null +++ b/tests/protocols/treeland-output-manager-v2/README.md @@ -0,0 +1,44 @@ +# `treeland-output-manager-v2` 测试规范 + +## 范围 + +- 测试源码:`tests/protocols/treeland-output-manager-v2/` +- Fixture:启动 headless backend 并创建真实 `wl_output` global 的协议 fixture。 +- 覆盖等级:primary-output 为 **I**;picture-control 创建与提交为 **I**。 +- v2 用 `treeland-output-uuid-unstable-v1` 的 uuid 字符串寻址输出:客户端先 + `get_uuid(wl_output)` 取 uuid,再用 uuid 调用本协议。 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | +| --- | --- | --- | +| uuid | 绑定 uuid manager 并对真实 `wl_output` 请求 `get_uuid` | 收到非空 uuid 字符串 | +| 主输出 | 绑定 manager | 初始 `primary_output` 事件携带主输出的 uuid(无主输出时为空串) | +| 设置主输出 | 用有效 uuid 请求 `set_primary_output` | 收到携带同一 uuid 的 `primary_output` 确认(同值请求也确认) | +| 设置主输出失败 | 请求 `set_primary_output` 传未知 uuid | 收到 `primary_output_failed(invalid_output=0)`,连接不断开 | +| 禁用输出 | 先在服务端禁用输出,再用其 uuid 请求 `set_primary_output` | 同上,非致命 | +| 禁用输出后提交 | 输出禁用后对已有 picture control `commit` | `result=invalid_output(3)`,连接保持;该对象随即永久失效 | +| picture-control | 用有效 uuid 请求 `get_picture_control` | 创建 control 并收到初始 `brightness`/`color_temperature`,无协议错误,创建时**不发** `result` | +| 未知 uuid | 用未知 uuid 请求 `get_picture_control` | 对象仍创建,但**无需 commit** 即收到 `result=invalid_output(3)`,且**无**初始 `brightness`/`color_temperature`;连接保持 | +| 失效后提交 | 已收到 `invalid_output` 的对象再 `commit`(含 `set_*` + `commit`) | 不再有任何事件(`result_event_count` 不变),连接保持,仅 `destroy` 有效 | +| 提交(无变更) | `commit` 且无 pending 值 | `result` 事件值为 `success`(0) | +| 设置越界色温 | `set_color_temperature(500)` | 立即引发致命协议错误 `error.invalid_color_temperature`(0),连接断开,无 `result` 事件 | + +## 生产结果 + +uuid 来自真实 output 的 `Output::uuid()`;picture control 在**未失效**期间按 uuid +跟随输出(监听 output model 增删重新解析,输出回来后会补发初始值)。 +`commit_result` 枚举值与 v1 的 uint flag(1=成功/0=失败)相反。 + +`invalid_output` 是**终结**结果:无论是创建时立即下发,还是后续 `commit` 返回, +该 picture control 对象都永久失效(inert)——只有 `destroy` 有效,不再发任何 +`result`/`brightness`/`color_temperature` 事件,之后即使插入 uuid 匹配的输出也 +不恢复;客户端必须销毁它并重新 `get_picture_control`。范围校验仍保留在 `set_*` +时刻(越界仍是致命协议错误),失效对象只是不再写入 pending、不再产出事件。 + +## 已知边界 / 下一项结果 + +尚未覆盖 `invalid_brightness` 协议错误、`unsupported` 结果、渲染颜色变化验证, +以及输出真正销毁/重建后的 uuid 跟随(headless 重建会换 output name,需 fixture +支持固定输出名才能测同一 uuid)。「失效对象在匹配 uuid 的输出重新出现后仍不恢复」 +属热插拔场景,同样受该 fixture 限制,暂由实现侧的 inert 状态保证。 diff --git a/tests/protocols/treeland-output-manager-v2/setup.cpp b/tests/protocols/treeland-output-manager-v2/setup.cpp new file mode 100644 index 0000000000..1d7a73112e --- /dev/null +++ b/tests/protocols/treeland-output-manager-v2/setup.cpp @@ -0,0 +1,36 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "modules/output-manager/outputmanagement.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "core/rootsurfacecontainer.h" +#include "output.h" + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +void protocol_test_setup(WaylandServer *server) +{ + // v2 addresses outputs by uuid; the client needs a real wl_output to ask + // treeland-output-uuid-v1 for that uuid. + add_headless_output(server->backend(), false); + Q_ASSERT(find_server_interface(server)); +} + +// Disables the first output so a client holding its wl_output can exercise the +// non-fatal primary_output_failed path. +extern "C" void protocol_test_disable_output() +{ + auto *server = WaylandServer::instance(); + const auto outputs = server->rootSurfaceContainer()->outputs(); + if (outputs.isEmpty()) + return; + + struct wlr_output_state state; + wlr_output_state_init(&state); + wlr_output_state_set_enabled(&state, false); + wlr_output_commit_state(outputs.first()->output()->handle(), &state); + wlr_output_state_finish(&state); +} diff --git a/tests/protocols/treeland-output-manager-v2/treeland-output-manager-v2.c b/tests/protocols/treeland-output-manager-v2/treeland-output-manager-v2.c new file mode 100644 index 0000000000..e7835878ac --- /dev/null +++ b/tests/protocols/treeland-output-manager-v2/treeland-output-manager-v2.c @@ -0,0 +1,483 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-output-manager-v2.h" +#include "treeland-output-manager-unstable-v2-client-protocol.h" +#include "treeland-output-uuid-unstable-v1-client-protocol.h" +#include "server-bridge-api.h" + +#include +#include +#include +#include + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); + /* Non-zero when the case raises a fatal protocol error and the + * connection is expected to be terminated afterwards. */ + int expect_disconnect; +}; + +void test_init(struct test_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); + ctx->result_cap = 32; + ctx->results = calloc(ctx->result_cap, sizeof(*ctx->results)); +} + +void test_destroy(struct test_ctx *ctx) +{ + free(ctx->results); + memset(ctx, 0, sizeof(*ctx)); +} + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +void test_pass(struct test_ctx *ctx, int index) +{ + ctx->results[index].failed = 0; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +/* ---- manager listener ---- */ + +static void manager_primary_output(void *data, struct treeland_output_manager_v2 *manager, + const char *uuid) +{ + (void)manager; + struct test_ctx *ctx = data; + ctx->primary_output_received = 1; + ++ctx->primary_output_count; + snprintf(ctx->primary_output_uuid, sizeof(ctx->primary_output_uuid), "%s", uuid); +} + +static void manager_primary_output_failed(void *data, + struct treeland_output_manager_v2 *manager, + uint32_t error) +{ + (void)manager; + struct test_ctx *ctx = data; + ctx->primary_output_failed_received = 1; + ctx->primary_output_failed_error = error; +} + +static const struct treeland_output_manager_v2_listener manager_listener = { + .primary_output = manager_primary_output, + .primary_output_failed = manager_primary_output_failed, +}; + +/* ---- output uuid listener ---- */ + +static void output_uuid_event(void *data, struct treeland_output_uuid_v1 *object, + const char *uuid) +{ + (void)object; + struct test_ctx *ctx = data; + ctx->uuid_received = 1; + snprintf(ctx->uuid, sizeof(ctx->uuid), "%s", uuid); +} + +static const struct treeland_output_uuid_v1_listener output_uuid_listener = { + .uuid = output_uuid_event, +}; + +/* ---- picture control listener ---- */ + +static void picture_control_result(void *data, + struct treeland_output_picture_control_v2 *control, + uint32_t result) +{ + (void)control; + struct test_ctx *ctx = data; + ctx->result_received = 1; + ctx->result_value = result; + ++ctx->result_event_count; +} + +static void picture_control_color_temperature(void *data, + struct treeland_output_picture_control_v2 *control, + uint32_t temperature) +{ + (void)control; + struct test_ctx *ctx = data; + ctx->color_temperature_received = 1; + ctx->color_temperature_value = temperature; +} + +static void picture_control_brightness(void *data, + struct treeland_output_picture_control_v2 *control, + wl_fixed_t brightness) +{ + (void)control; + struct test_ctx *ctx = data; + ctx->brightness_received = 1; + ctx->brightness_value = brightness; +} + +static const struct treeland_output_picture_control_v2_listener picture_control_listener = { + .result = picture_control_result, + .color_temperature = picture_control_color_temperature, + .brightness = picture_control_brightness, +}; + +/* ---- test helpers ---- */ + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + ctx->socket_name = socket_name; + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->display = ctx->connection.display; + ctx->output = client_bind(&ctx->connection, "wl_output", &wl_output_interface, 1); + ctx->manager = client_bind(&ctx->connection, "treeland_output_manager_v2", + &treeland_output_manager_v2_interface, 1); + ctx->uuid_manager = client_bind(&ctx->connection, "treeland_output_uuid_manager_v1", + &treeland_output_uuid_manager_v1_interface, 1); + if (!ctx->manager || !ctx->uuid_manager || !ctx->output) + return 0; + treeland_output_manager_v2_add_listener(ctx->manager, &manager_listener, ctx); + + /* v2 addresses outputs by uuid, so fetch it from the uuid protocol. */ + ctx->uuid_object = treeland_output_uuid_manager_v1_get_uuid(ctx->uuid_manager, + ctx->output); + if (!ctx->uuid_object) + return 0; + treeland_output_uuid_v1_add_listener(ctx->uuid_object, &output_uuid_listener, ctx); + return 1; +} + +static int manager_bound(struct test_ctx *ctx) +{ + return ctx->manager != NULL; +} + +static int output_bound(struct test_ctx *ctx) +{ + return ctx->output != NULL; +} + +/* v2: primary_output event carries the uuid of the primary output and is + * emitted once immediately after bind. */ +static int primary_output_event_received(struct test_ctx *ctx) +{ + wl_display_roundtrip(ctx->display); + return ctx->uuid_received && ctx->uuid[0] != '\0' + && ctx->primary_output_received && ctx->primary_output_count == 1 + && strcmp(ctx->primary_output_uuid, ctx->uuid) == 0; +} + +/* v2: set_primary_output takes a uuid string; a valid enabled output is + * accepted and confirmed by a primary_output event, even when the output is + * already the primary (the request must always be confirmed). */ +static int set_primary_output_valid(struct test_ctx *ctx) +{ + if (!ctx->manager || ctx->uuid[0] == '\0') + return 0; + ctx->primary_output_failed_received = 0; + ctx->primary_output_received = 0; + ctx->primary_output_count = 0; + treeland_output_manager_v2_set_primary_output(ctx->manager, ctx->uuid); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + const struct wl_interface *error_interface = NULL; + uint32_t error_object_id = 0; + return !ctx->primary_output_failed_received + && ctx->primary_output_received && ctx->primary_output_count >= 1 + && strcmp(ctx->primary_output_uuid, ctx->uuid) == 0 + && wl_display_get_protocol_error(ctx->display, &error_interface, &error_object_id) == 0; +} + +/* v2: an empty or unknown uuid is rejected non-fatally with + * primary_output_failed(invalid_output == 0); the connection stays alive. */ +static int set_primary_output_unknown_failed(struct test_ctx *ctx) +{ + if (!ctx->manager) + return 0; + ctx->primary_output_failed_received = 0; + ctx->primary_output_failed_error = 0xffffffff; + treeland_output_manager_v2_set_primary_output(ctx->manager, "00000000-unknown"); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + return ctx->primary_output_failed_received + && ctx->primary_output_failed_error == 0; /* invalid_output == 0 */ +} + +static void disable_output(void *data) +{ + (void)data; + protocol_test_disable_output(); +} + +/* v2: a disabled output is rejected non-fatally with + * primary_output_failed(invalid_output == 0); the connection stays alive. */ +static int set_primary_output_disabled_failed(struct test_ctx *ctx) +{ + if (!ctx->manager || ctx->uuid[0] == '\0') + return 0; + if (!invoke_on_server_thread(disable_output, NULL)) + return 0; + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + + ctx->primary_output_failed_received = 0; + ctx->primary_output_failed_error = 0xffffffff; + treeland_output_manager_v2_set_primary_output(ctx->manager, ctx->uuid); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + return ctx->primary_output_failed_received + && ctx->primary_output_failed_error == 0; /* invalid_output == 0 */ +} + +/* v2: once the output behind the uuid is disabled, commits report + * commit_result.invalid_output (3) and leave the connection alive. */ +static int commit_disabled_output_invalid(struct test_ctx *ctx) +{ + if (!ctx->picture_control) + return 0; + ctx->result_received = 0; + ctx->result_value = 0xffffffff; + treeland_output_picture_control_v2_commit(ctx->picture_control); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + return ctx->result_received && ctx->result_value == 3; /* invalid_output */ +} + +/* v2: the invalid_output delivered by a commit is terminal too: a second + * commit on the same object produces no event and does not disconnect. */ +static int commit_disabled_output_inert_no_more_events(struct test_ctx *ctx) +{ + if (!ctx->picture_control) + return 0; + const int before = ctx->result_event_count; + ctx->result_received = 0; + ctx->result_value = 0xffffffff; + treeland_output_picture_control_v2_commit(ctx->picture_control); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + return !ctx->result_received && ctx->result_event_count == before; +} + +/* v2: get_picture_control always succeeds for a known uuid; no protocol + * error is raised. */ +static int get_picture_control_valid_uuid(struct test_ctx *ctx) +{ + if (!ctx->manager || ctx->uuid[0] == '\0') + return 0; + ctx->picture_control = + treeland_output_manager_v2_get_picture_control(ctx->manager, ctx->uuid); + if (!ctx->picture_control) + return 0; + treeland_output_picture_control_v2_add_listener(ctx->picture_control, + &picture_control_listener, ctx); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + const struct wl_interface *error_interface = NULL; + uint32_t error_object_id = 0; + return wl_display_get_protocol_error(ctx->display, &error_interface, &error_object_id) == 0; +} + +/* v2: an object created for a live enabled output reports its values with the + * initial color_temperature / brightness events, never with a result event at + * creation time. */ +static int get_picture_control_valid_uuid_no_result_at_creation(struct test_ctx *ctx) +{ + if (!ctx->picture_control) + return 0; + ctx->result_received = 0; + ctx->result_event_count = 0; + ctx->result_value = 0xffffffff; + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + return !ctx->result_received && ctx->result_event_count == 0; +} + +/* v2: the initial brightness event must stay inside the protocol range + * [0.0, 100.0]; otherwise a client echoing it back is disconnected by the + * fatal invalid_brightness error. */ +static int picture_control_initial_brightness_in_range(struct test_ctx *ctx) +{ + if (!ctx->picture_control) + return 0; + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + return ctx->brightness_received + && ctx->brightness_value >= 0 + && ctx->brightness_value <= wl_fixed_from_double(100.0); +} + +/* v2: an unknown uuid still creates the object, but invalid_output is reported + * immediately, without waiting for a commit, and no initial color_temperature + * / brightness events are sent. */ +static int get_picture_control_unknown_uuid_invalid_output(struct test_ctx *ctx) +{ + if (!ctx->manager) + return 0; + ctx->unknown_picture_control = + treeland_output_manager_v2_get_picture_control(ctx->manager, "00000000-unknown"); + if (!ctx->unknown_picture_control) + return 0; + treeland_output_picture_control_v2_add_listener(ctx->unknown_picture_control, + &picture_control_listener, ctx); + ctx->result_received = 0; + ctx->result_event_count = 0; + ctx->result_value = 0xffffffff; + ctx->brightness_received = 0; + ctx->color_temperature_received = 0; + /* Deliberately no commit: the result must arrive on this roundtrip. */ + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + return ctx->result_received && ctx->result_event_count == 1 + && ctx->result_value == 3 /* invalid_output */ + && !ctx->brightness_received && !ctx->color_temperature_received; +} + +/* v2: invalid_output is terminal. On the inert object only destroy stays + * valid: commit and set_* produce no further events and keep the connection + * alive. */ +static int invalid_output_inert_ignores_commit(struct test_ctx *ctx) +{ + if (!ctx->unknown_picture_control) + return 0; + const int before = ctx->result_event_count; + ctx->result_received = 0; + ctx->result_value = 0xffffffff; + treeland_output_picture_control_v2_commit(ctx->unknown_picture_control); + treeland_output_picture_control_v2_set_brightness(ctx->unknown_picture_control, + wl_fixed_from_double(50.0)); + treeland_output_picture_control_v2_set_color_temperature(ctx->unknown_picture_control, 4000); + treeland_output_picture_control_v2_commit(ctx->unknown_picture_control); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; /* an inert object must not terminate the connection */ + return !ctx->result_received && ctx->result_event_count == before + && !ctx->brightness_received && !ctx->color_temperature_received; +} + +/* v2: commit with no pending changes succeeds (commit_result.success == 0). */ +static int commit_no_changes_success(struct test_ctx *ctx) +{ + if (!ctx->picture_control) + return 0; + ctx->result_received = 0; + ctx->result_value = 0xffffffff; + treeland_output_picture_control_v2_commit(ctx->picture_control); + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + return ctx->result_received && ctx->result_value == 0; /* success == 0 */ +} + +/* v2: an out-of-range color temperature raises the fatal + * invalid_color_temperature protocol error (value 0) on the + * set_color_temperature request itself; the connection is terminated and no + * result event is produced. */ +static int set_color_temperature_out_of_range_error(struct test_ctx *ctx) +{ + if (!ctx->picture_control) + return 0; + ctx->result_received = 0; + ctx->result_value = 0xffffffff; + treeland_output_picture_control_v2_set_color_temperature(ctx->picture_control, 500); + if (wl_display_roundtrip(ctx->display) >= 0) + return 0; /* the fatal protocol error must terminate the connection */ + const struct wl_interface *error_interface = NULL; + uint32_t error_object_id = 0; + const uint32_t code = + wl_display_get_protocol_error(ctx->display, &error_interface, &error_object_id); + return !ctx->result_received + && code == 0 /* error.invalid_color_temperature */ + && error_interface == &treeland_output_picture_control_v2_interface; +} + +static const struct test_case cases[] = { + { "manager.bind", manager_bound, 0 }, + { "output.bind", output_bound, 0 }, + { "manager.event.primary_output", primary_output_event_received, 0 }, + { "manager.set_primary_output.valid", set_primary_output_valid, 0 }, + { "manager.set_primary_output.unknown_failed", set_primary_output_unknown_failed, 0 }, + { "manager.get_picture_control.valid_uuid", get_picture_control_valid_uuid, 0 }, + { "manager.get_picture_control.valid_uuid_no_result_at_creation", + get_picture_control_valid_uuid_no_result_at_creation, 0 }, + { "picture_control.event.initial_brightness_in_range", + picture_control_initial_brightness_in_range, 0 }, + { "picture_control.commit.no_changes_success", commit_no_changes_success, 0 }, + { "manager.get_picture_control.unknown_uuid_invalid_output", + get_picture_control_unknown_uuid_invalid_output, 0 }, + { "picture_control.invalid_output.inert_ignores_commit", + invalid_output_inert_ignores_commit, 0 }, + { "manager.set_primary_output.disabled_failed", set_primary_output_disabled_failed, 0 }, + { "picture_control.commit.disabled_output_invalid", + commit_disabled_output_invalid, 0 }, + { "picture_control.commit.disabled_output_inert_no_more_events", + commit_disabled_output_inert_no_more_events, 0 }, + { "picture_control.set_color_temperature.out_of_range_error", + set_color_temperature_out_of_range_error, 1 }, +}; + +void test_cleanup(struct test_ctx *ctx) +{ + if (ctx->unknown_picture_control) + treeland_output_picture_control_v2_destroy(ctx->unknown_picture_control); + if (ctx->picture_control) treeland_output_picture_control_v2_destroy(ctx->picture_control); + if (ctx->uuid_object) treeland_output_uuid_v1_destroy(ctx->uuid_object); + if (ctx->uuid_manager) treeland_output_uuid_manager_v1_destroy(ctx->uuid_manager); + if (ctx->manager) treeland_output_manager_v2_destroy(ctx->manager); + client_disconnect(&ctx->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx; + test_init(&ctx); + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect to or bind treeland_output_manager_v2\n"); + test_cleanup(&ctx); + test_destroy(&ctx); + return 1; + } + + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const int result = test_add(&ctx, cases[i].name); + if (!cases[i].run(&ctx)) + test_fail(&ctx, result, "assertion failed"); + if (!cases[i].expect_disconnect + && wl_display_roundtrip(ctx.display) < 0) + test_fail(&ctx, result, "Wayland connection failed"); + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + test_destroy(&ctx); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-output-manager-v2/treeland-output-manager-v2.h b/tests/protocols/treeland-output-manager-v2/treeland-output-manager-v2.h new file mode 100644 index 0000000000..43710c5e14 --- /dev/null +++ b/tests/protocols/treeland-output-manager-v2/treeland-output-manager-v2.h @@ -0,0 +1,81 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef TREELAND_OUTPUT_MANAGER_V2_TEST_H +#define TREELAND_OUTPUT_MANAGER_V2_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +// Runs on the compositor thread via invoke_on_server_thread(). +void protocol_test_disable_output(void); + +#include "client-connection.h" + +#define TEST_MSG_MAX 256 + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +struct test_ctx { + struct client_connection connection; + struct wl_display *display; + + struct wl_output *output; + + struct treeland_output_manager_v2 *manager; + struct treeland_output_picture_control_v2 *picture_control; + struct treeland_output_picture_control_v2 *unknown_picture_control; + + /* v2 addresses outputs by the uuid served by treeland-output-uuid-v1. */ + struct treeland_output_uuid_manager_v1 *uuid_manager; + struct treeland_output_uuid_v1 *uuid_object; + char uuid[128]; + int uuid_received; + + const char *socket_name; + + int primary_output_received; + int primary_output_count; + char primary_output_uuid[128]; + + int primary_output_failed_received; + uint32_t primary_output_failed_error; + + int result_received; + uint32_t result_value; + /* Number of result events seen so far. Needed to tell the result that + * invalid_output object creation emits by itself apart from the one a + * later commit produces. Not to be confused with result_count below, + * which counts the entries of the results array. */ + int result_event_count; + + int color_temperature_received; + uint32_t color_temperature_value; + + int brightness_received; + wl_fixed_t brightness_value; + + struct test_result *results; + int result_count; + int result_cap; +}; + +void test_init(struct test_ctx *ctx); +void test_destroy(struct test_ctx *ctx); +int test_add(struct test_ctx *ctx, const char *name); +void test_fail(struct test_ctx *ctx, int idx, const char *fmt, ...); +void test_pass(struct test_ctx *ctx, int idx); + +int test_print_results(struct test_ctx *ctx); +void test_cleanup(struct test_ctx *ctx); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-prelaunch-splash-desktop-v2/CMakeLists.txt b/tests/protocols/treeland-prelaunch-splash-desktop-v2/CMakeLists.txt new file mode 100644 index 0000000000..9a810854b9 --- /dev/null +++ b/tests/protocols/treeland-prelaunch-splash-desktop-v2/CMakeLists.txt @@ -0,0 +1,10 @@ + +treeland_add_protocol_test( + NAME treeland_prelaunch_splash_desktop_v2 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-prelaunch-splash-unstable-v2.xml" + EXTRA_XMLS + "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-app-id-resolver-unstable-v2.xml" + "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-foreign-toplevel-manager-unstable-v3.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-prelaunch-splash-desktop-v2.c" +) diff --git a/tests/protocols/treeland-prelaunch-splash-desktop-v2/README.md b/tests/protocols/treeland-prelaunch-splash-desktop-v2/README.md new file mode 100644 index 0000000000..ffb66d5522 --- /dev/null +++ b/tests/protocols/treeland-prelaunch-splash-desktop-v2/README.md @@ -0,0 +1,55 @@ +# prelaunch splash 桌面集成:wrapper 生命周期与图标跨阶段保留 + +## 范围 + +- XML / interface: + - `treeland-prelaunch-splash-unstable-v2`(`create_splash.icon_buffer`) + - `treeland-app-id-resolver-unstable-v2`(把真实窗口匹配到 splash) + - `treeland-foreign-toplevel-manager-unstable-v3`(dock preview context) +- 测试源码:`tests/protocols/treeland-prelaunch-splash-desktop-v2/` +- Fixture:完整生产 `Treeland` / `WaylandServer` / `ShellHandler` / workspace / headless output +- 覆盖等级:**E / V**(纹理像素读回,不是最终 output backing buffer) + +## 两个阶段 + +阶段一验证 splash request/close 已进入生产 `ShellHandler` 并生成、销毁 splash wrapper。 +阶段二用同一条链路把 AM 图标一路带到 dock preview:客户端 `create_splash` 之后立刻销毁自己的 +`wl_buffer`(AM 的行为),窗口经 app-id resolver 匹配后把 splash 转成真实窗口,预览仍能画出图标。 + +## 必须观察到的结果 + +| 阶段 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| splash 建立 | `create_splash(app_id, icon = 16×16 ARGB8888)` | 生产 wrapper 为 `SplashScreen`、appId 一致、在 workspace 内、有 `prelaunchSplash()` item、尺寸为默认 `800 × 600` | E | +| 图标锁住 | 发送请求后立即销毁客户端 `wl_buffer` | `SurfaceWrapper::appIcon()` 仍可读,尺寸 `16 × 16` | E | +| 关闭 | 销毁客户端 splash 资源 | wrapper 离开 workspace 并发出 destroyed | E | +| 跨阶段保留 | 建 `800 × 600` xdg 窗口并让 resolver 应答 app-id | 同一个 wrapper 变成 `XdgToplevel`,`prelaunchSplash()` 为 `nullptr`,`appIcon()` 仍为 `16 × 16` | E | +| 图标进入 dock preview | `get_dock_preview_context` + `show([identifier])` | 标题行图标 item 存在、可见,`buffer` 指针等于 `wrapper->appIcon()`,宽高等于 `titleRowHeight` | E | +| 纹理像素 | 服务端 `render()` 后由 `WTextureCapturer` 读回 | 中心像素 RGBA `(255, 0, 0, 255)` | V | +| 无图标窗口 | 预览一个从未有 splash 的 `320 × 200` 窗口 | 图标 item 不存在,因此不占位 | E | +| 悬停切换 | 两个窗口之间来回 `show()` 10 次 | 每次都得到上一条的状态,无警告无崩溃 | E | +| 图标来源窗口关闭 | 销毁带图标的窗口后再 `show()` | 图标 item 不存在,无警告无崩溃 | E | + +「无警告」由 fixture 的 `qInstallMessageHandler` 计数:`wTextureProvider() is nullptr`、 +`can only be queried on the rendering thread`、`texture missing or item size invalid`、 +`Reject buffer with invalid size`,以及任何提及 `DockPreview.qml` 的 warning/critical +(QML 引擎拒绝赋值只记日志、不报错)。 + +## 关键实现约束 + +- 真实窗口尺寸取 splash 的默认 `800 × 600`。尺寸不一致时生产代码走 `GeometryAnimation`, + 其 `ready()` 依赖 `ShaderEffectSource::onScheduledUpdateCompleted`,headless 的 software + renderer 不调度该更新,splash item 永远不会销毁;同尺寸提交直接走 `completeSplashTransition`。 +- 等待都基于生产状态或信号:wrapper 用 `SurfaceContainer::surfaceAdded`,转换用 + `type()` + `prelaunchSplash()` 轮询,预览用 `thumbnailReveal`/`listReveal` 与 QML binding 结果轮询, + 纹理用 `QFutureWatcher::finished`;轮询均有帧数上限。 + +## 已知边界 + +- 像素来自图标 item 的生产纹理,不是 output 的合成 backing buffer;叠放、output transform + 与 scanout 像素未覆盖;splash 自身的可见性与像素同样未覆盖。 +- 图标被拉伸为正方形(`titleRowHeight × titleRowHeight`),非方形图标未做等比适配, + 已在 `DockPreview.qml` 用 `shortcut:` 标注。 +- 图标 item 每次悬停重建,未覆盖 `WBufferItem::setBuffer()` 运行时替换既有 buffer 的路径 + (连续悬停两个带图标的窗口),生产里仍存在。 +- `thumbnailReveal`/`listReveal` 动画在 headless 下会跑完,但未断言动画曲线。 diff --git a/tests/protocols/treeland-prelaunch-splash-desktop-v2/setup.cpp b/tests/protocols/treeland-prelaunch-splash-desktop-v2/setup.cpp new file mode 100644 index 0000000000..49f3513d55 --- /dev/null +++ b/tests/protocols/treeland-prelaunch-splash-desktop-v2/setup.cpp @@ -0,0 +1,319 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "core/rootsurfacecontainer.h" +#include "core/waylandserver.h" +#include "server-bridge.h" +#include "surface/surfacecontainer.h" +#include "surface/surfacewrapper.h" +#include "treeland-prelaunch-splash-desktop-v2.h" +#include "treelandconfig.hpp" +#include "workspace/workspace.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace { +constexpr auto SplashAppId = "org.deepin.treeland.protocol.splash"; +constexpr auto IconSplashAppId = "org.deepin.treeland.protocol.splash-icon"; +// Bounds of the state polls below, counted in rendered frames. +constexpr int MaxSettleFrames = 60; +constexpr int MaxConvertFrames = 400; + +QPointer g_wrapper; +prelaunch_splash_desktop_state g_state {}; +bool g_splashConfigReady = false; +int g_bufferItemWarnings = 0; +QtMessageHandler g_previousHandler = nullptr; + +bool isTestSplash(const SurfaceWrapper *wrapper) +{ + return wrapper && wrapper->type() == SurfaceWrapper::Type::SplashScreen + && (wrapper->appId() == QLatin1String(SplashAppId) + || wrapper->appId() == QLatin1String(IconSplashAppId)); +} + +void enablePrelaunchSplash(WaylandServer *server) +{ + server->globalConfig()->setEnablePrelaunchSplash(true); + g_splashConfigReady = true; +} + +// WBufferItem logs these when its host or its texture is unusable, and QML +// assignment errors from the preview are only logged, never raised. +bool isBufferItemWarning(QtMsgType type, const QString &message) +{ + return message.contains(QLatin1String("wTextureProvider() is nullptr")) + || message.contains(QLatin1String("can only be queried on the rendering thread")) + || message.contains(QLatin1String("texture missing or item size invalid")) + || message.contains(QLatin1String("Reject buffer with invalid size")) + || ((type == QtWarningMsg || type == QtCriticalMsg) + && message.contains(QLatin1String("DockPreview.qml"))); +} + +void recordBufferItemWarnings(QtMsgType type, + const QMessageLogContext &context, + const QString &message) +{ + if (isBufferItemWarning(type, message)) + ++g_bufferItemWarnings; + if (g_previousHandler) + g_previousHandler(type, context, message); +} + +QQuickItem *findDockPreview(QQuickItem *item) +{ + if (!item) + return nullptr; + // The preview root owns one reveal per presentation and the tooltip has + // none, so the thumbnail reveal identifies the title row's presentation. + if (item->property("desiredSurfaces").isValid() && item->property("thumbnailReveal").isValid()) + return item; + for (auto *child : item->childItems()) { + if (auto *found = findDockPreview(child)) + return found; + } + return nullptr; +} + +QQuickItem *findItemWithProperty(QQuickItem *item, const char *name) +{ + if (!item) + return nullptr; + if (item->property(name).isValid()) + return item; + for (auto *child : item->childItems()) { + if (auto *found = findItemWithProperty(child, name)) + return found; + } + return nullptr; +} + +QImage captureItem(WBufferItem *item) +{ + WTextureCapturer capturer(item); + QFutureWatcher watcher; + QEventLoop loop; + QObject::connect(&watcher, &QFutureWatcher::finished, &loop, &QEventLoop::quit); + QTimer::singleShot(5000, &loop, &QEventLoop::quit); + watcher.setFuture(capturer.grabToImage()); + loop.exec(); + if (!watcher.isFinished() || watcher.isCanceled()) + return {}; + // The capturer reports failures as a future exception, so reading the result rethrows. + try { + return watcher.result(); + } catch (...) { + return {}; + } +} + +void settleOneFrame() +{ + QEventLoop loop; + QTimer::singleShot(5, &loop, &QEventLoop::quit); + loop.exec(); +} + +void rememberSplash(SurfaceWrapper *wrapper) +{ + g_state = {}; + g_wrapper = wrapper; + g_state.wrapper_created = 1; + g_state.wrapper_in_workspace = + WaylandServer::instance()->workspace()->surfaces().contains(wrapper) ? 1 : 0; + g_state.wrapper_is_splash = 1; + g_state.wrapper_has_qml_item = wrapper->prelaunchSplash() ? 1 : 0; + g_state.wrapper_width = qRound(wrapper->implicitWidth()); + g_state.wrapper_height = qRound(wrapper->implicitHeight()); + qstrncpy(g_state.app_id, qPrintable(wrapper->appId()), sizeof(g_state.app_id)); + QObject::connect(wrapper, &QObject::destroyed, WaylandServer::instance(), [] { + g_state.wrapper_destroyed = 1; + }); +} +} + +void protocol_test_setup(WaylandServer *server) +{ + // A short real animation keeps the production geometry/reveal lifecycle. + server->setAnimationSpeed(0.1f); + add_headless_output(server->backend(), false); + + g_previousHandler = qInstallMessageHandler(recordBufferItemWarnings); + + auto *config = server->globalConfig(); + if (config->isInitializeSucceeded()) { + enablePrelaunchSplash(server); + } else { + QObject::connect(config, + &TreelandConfig::configInitializeSucceed, + server, + [server](auto *) { enablePrelaunchSplash(server); }); + } + + QObject::connect(server->workspace(), &SurfaceContainer::surfaceAdded, server, [](auto *wrapper) { + if (isTestSplash(wrapper)) + rememberSplash(wrapper); + }); +} + +extern "C" bool protocol_test_ready(WaylandServer *server) +{ + return g_splashConfigReady && !server->rootSurfaceContainer()->outputs().isEmpty(); +} + +extern "C" void prelaunch_splash_desktop_wait_for_creation(void *data) +{ + auto *created = static_cast(data); + *created = g_wrapper ? 1 : 0; + if (*created) + return; + + QEventLoop eventLoop; + QTimer guard; + guard.setSingleShot(true); + QObject::connect(&guard, &QTimer::timeout, &eventLoop, &QEventLoop::quit); + guard.start(10000); + const auto connection = QObject::connect( + WaylandServer::instance()->workspace(), + &SurfaceContainer::surfaceAdded, + &eventLoop, + [&eventLoop, created](SurfaceWrapper *wrapper) { + if (isTestSplash(wrapper)) { + *created = 1; + eventLoop.quit(); + } + }); + eventLoop.exec(); + QObject::disconnect(connection); +} + +extern "C" void prelaunch_splash_desktop_wait_for_destruction(void *data) +{ + auto *destroyed = static_cast(data); + *destroyed = g_state.wrapper_destroyed; + if (*destroyed || !g_wrapper) + return; + + QEventLoop eventLoop; + QObject::connect(g_wrapper, &QObject::destroyed, &eventLoop, [&eventLoop, destroyed] { + *destroyed = 1; + eventLoop.quit(); + }); + eventLoop.exec(); +} + +extern "C" void prelaunch_splash_desktop_wait_converted(void *data) +{ + auto *ready = static_cast(data); + for (int frame = 0; frame < MaxConvertFrames; ++frame) { + WaylandServer::instance()->window()->render(); + if (g_wrapper && g_wrapper->type() == SurfaceWrapper::Type::XdgToplevel + && !g_wrapper->prelaunchSplash()) { + *ready = 1; + return; + } + settleOneFrame(); + } + qInfo() << "splash conversion not observed: wrapper" << g_wrapper.data() << "type" + << (g_wrapper ? int(g_wrapper->type()) : -1) << "splashItem" + << (g_wrapper ? g_wrapper->prelaunchSplash() : nullptr) << "surfaceItem" + << (g_wrapper ? g_wrapper->surfaceItem() : nullptr) << "animating" + << (g_wrapper ? g_wrapper->isAnimationRunning() : false); +} + +extern "C" void prelaunch_splash_desktop_read_state(void *data) +{ + auto state = g_state; + auto *server = WaylandServer::instance(); + state.output_ready = !server->rootSurfaceContainer()->outputs().isEmpty() ? 1 : 0; + if (g_wrapper) { + state.wrapper_in_workspace = server->workspace()->surfaces().contains(g_wrapper) ? 1 : 0; + state.wrapper_is_splash = g_wrapper->type() == SurfaceWrapper::Type::SplashScreen ? 1 : 0; + state.wrapper_has_qml_item = g_wrapper->prelaunchSplash() ? 1 : 0; + state.wrapper_width = qRound(g_wrapper->implicitWidth()); + state.wrapper_height = qRound(g_wrapper->implicitHeight()); + state.converted_to_xdg = + g_wrapper->type() == SurfaceWrapper::Type::XdgToplevel ? 1 : 0; + state.splash_item_gone = g_wrapper->prelaunchSplash() ? 0 : 1; + auto *icon = g_wrapper->appIcon().value(); + state.icon_ready = state.icon_width = state.icon_height = 0; + if (icon) { + state.icon_ready = 1; + state.icon_width = icon->width; + state.icon_height = icon->height; + } + qstrncpy(state.app_id, qPrintable(g_wrapper->appId()), sizeof(state.app_id)); + } else if (state.wrapper_created) { + state.wrapper_in_workspace = 0; + } + *static_cast(data) = state; +} + +extern "C" void prelaunch_splash_desktop_probe_icon(void *data) +{ + auto *probe = static_cast(data); + probe->buffer_warnings = g_bufferItemWarnings; + auto *server = WaylandServer::instance(); + auto *content = server->window()->contentItem(); + auto *preview = findDockPreview(content); + probe->preview_found = preview ? 1 : 0; + if (!preview) + return; + + // The title row is reparented next to the preview, so the icon is a sibling subtree. + auto *root = preview->parentItem() ? preview->parentItem() : content; + const auto findIcon = [root]() -> WBufferItem * { + auto *loader = findItemWithProperty(root, "iconBuffer"); + return loader ? dynamic_cast(loader->property("item").value()) + : nullptr; + }; + + for (int frame = 0; frame < MaxSettleFrames; ++frame) { + server->window()->render(); + auto *item = findIcon(); + const bool revealDone = preview->property("thumbnailReveal").toReal() >= 1.0 + || preview->property("listReveal").toReal() >= 1.0; + const bool settled = probe->expect_icon ? (item && item->buffer() != nullptr) + : (!item || item->buffer() == nullptr); + if (revealDone && settled) + break; + settleOneFrame(); + } + + auto *item = findIcon(); + probe->icon_item_found = item ? 1 : 0; + probe->buffer_warnings = g_bufferItemWarnings; + if (!item) + return; + + probe->title_row_height = qRound(preview->property("titleRowHeight").toReal()); + probe->icon_visible = item->isVisible() ? 1 : 0; + probe->icon_width = qRound(item->width()); + probe->icon_height = qRound(item->height()); + + auto *icon = g_wrapper ? g_wrapper->appIcon().value() : nullptr; + probe->icon_buffer_matches = (icon && item->buffer() == icon) ? 1 : 0; + + if (item->buffer()) { + const QImage image = captureItem(item); + if (!image.isNull()) { + const QColor sample = image.pixelColor(image.width() / 2, image.height() / 2); + probe->capture_ready = 1; + probe->pixel_red = sample.red(); + probe->pixel_green = sample.green(); + probe->pixel_blue = sample.blue(); + probe->pixel_alpha = sample.alpha(); + } + } + + probe->buffer_warnings = g_bufferItemWarnings; +} diff --git a/tests/protocols/treeland-prelaunch-splash-desktop-v2/treeland-prelaunch-splash-desktop-v2.c b/tests/protocols/treeland-prelaunch-splash-desktop-v2/treeland-prelaunch-splash-desktop-v2.c new file mode 100644 index 0000000000..1363fb30c6 --- /dev/null +++ b/tests/protocols/treeland-prelaunch-splash-desktop-v2/treeland-prelaunch-splash-desktop-v2.c @@ -0,0 +1,648 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "client-connection.h" +#include "server-bridge-api.h" +#include "treeland-app-id-resolver-unstable-v2-client-protocol.h" +#include "treeland-foreign-toplevel-manager-unstable-v3-client-protocol.h" +#include "treeland-prelaunch-splash-desktop-v2.h" +#include "treeland-prelaunch-splash-unstable-v2-client-protocol.h" +#include "xdg-toplevel-client.h" + +#include +#include +#include +#include +#include + +extern void prelaunch_splash_desktop_read_state(void *data); +extern void prelaunch_splash_desktop_wait_for_creation(void *data); +extern void prelaunch_splash_desktop_wait_for_destruction(void *data); +extern void prelaunch_splash_desktop_wait_converted(void *data); +extern void prelaunch_splash_desktop_probe_icon(void *data); + +static const char *const splash_app_id = "org.deepin.treeland.protocol.splash"; +static const char *const icon_app_id = "org.deepin.treeland.protocol.splash-icon"; +static const char *const plain_app_id = "org.deepin.treeland.protocol.splash-icon.plain"; + +#define ICON_WIDTH 16 +#define ICON_HEIGHT 16 +#define ICON_ARGB 0xffff0000u /* opaque red, ARGB8888 */ +/* The splash wrapper is 800x600; the real window must match to convert without + a geometry animation. */ +#define SPLASH_WINDOW_WIDTH 800 +#define SPLASH_WINDOW_HEIGHT 600 +#define PLAIN_WINDOW_WIDTH 320 +#define PLAIN_WINDOW_HEIGHT 200 +#define PREVIEW_SWITCHES 10 +#define MAX_HANDLES 4 + +struct handle_entry { + struct treeland_foreign_toplevel_handle_v3 *handle; + char app_id[96]; + uint32_t identifier; + int closed; +}; + +struct client_state { + struct treeland_foreign_toplevel_manager_v3 *manager; + struct treeland_dock_preview_context_v3 *context; + struct handle_entry handles[MAX_HANDLES]; + int handle_count; +}; + +struct resolver_state { + uint32_t request_id; + int identify_count; + int pidfd; +}; + +static void handle_pid(void *data, struct treeland_foreign_toplevel_handle_v3 *handle, uint32_t pid) +{ + (void)data; + (void)handle; + (void)pid; +} + +static void handle_app_id(void *data, + struct treeland_foreign_toplevel_handle_v3 *handle, + const char *app_id) +{ + (void)handle; + struct handle_entry *entry = data; + snprintf(entry->app_id, sizeof(entry->app_id), "%s", app_id ? app_id : ""); +} + +static void handle_identifier(void *data, + struct treeland_foreign_toplevel_handle_v3 *handle, + uint32_t identifier) +{ + (void)handle; + struct handle_entry *entry = data; + entry->identifier = identifier; +} + +static void handle_title(void *data, + struct treeland_foreign_toplevel_handle_v3 *handle, + const char *title) +{ + (void)data; + (void)handle; + (void)title; +} + +static void handle_output_enter(void *data, + struct treeland_foreign_toplevel_handle_v3 *handle, + struct wl_output *output) +{ + (void)data; + (void)handle; + (void)output; +} + +static void handle_output_leave(void *data, + struct treeland_foreign_toplevel_handle_v3 *handle, + struct wl_output *output) +{ + (void)data; + (void)handle; + (void)output; +} + +static void handle_state(void *data, + struct treeland_foreign_toplevel_handle_v3 *handle, + struct wl_array *state) +{ + (void)data; + (void)handle; + (void)state; +} + +static void handle_done(void *data, struct treeland_foreign_toplevel_handle_v3 *handle) +{ + (void)data; + (void)handle; +} + +static void handle_closed(void *data, struct treeland_foreign_toplevel_handle_v3 *handle) +{ + struct handle_entry *entry = data; + entry->closed = 1; + entry->identifier = 0; + entry->handle = NULL; + treeland_foreign_toplevel_handle_v3_destroy(handle); +} + +static void handle_parent(void *data, + struct treeland_foreign_toplevel_handle_v3 *handle, + struct treeland_foreign_toplevel_handle_v3 *parent) +{ + (void)data; + (void)handle; + (void)parent; +} + +static const struct treeland_foreign_toplevel_handle_v3_listener handle_listener = { + .pid = handle_pid, + .title = handle_title, + .app_id = handle_app_id, + .identifier = handle_identifier, + .output_enter = handle_output_enter, + .output_leave = handle_output_leave, + .state = handle_state, + .done = handle_done, + .closed = handle_closed, + .parent = handle_parent, +}; + +static void manager_toplevel(void *data, + struct treeland_foreign_toplevel_manager_v3 *manager, + struct treeland_foreign_toplevel_handle_v3 *handle) +{ + (void)manager; + struct client_state *state = data; + if (state->handle_count >= MAX_HANDLES) { + treeland_foreign_toplevel_handle_v3_destroy(handle); + return; + } + struct handle_entry *entry = &state->handles[state->handle_count++]; + memset(entry, 0, sizeof(*entry)); + entry->handle = handle; + treeland_foreign_toplevel_handle_v3_add_listener(handle, &handle_listener, entry); +} + +static void manager_finished(void *data, struct treeland_foreign_toplevel_manager_v3 *manager) +{ + (void)data; + (void)manager; +} + +static const struct treeland_foreign_toplevel_manager_v3_listener manager_listener = { + .toplevel = manager_toplevel, + .finished = manager_finished, +}; + +static void context_enter(void *data, struct treeland_dock_preview_context_v3 *context) +{ + (void)data; + (void)context; +} + +static void context_leave(void *data, struct treeland_dock_preview_context_v3 *context) +{ + (void)data; + (void)context; +} + +static const struct treeland_dock_preview_context_v3_listener context_listener = { + .enter = context_enter, + .leave = context_leave, +}; + +static void identify_request(void *data, + struct treeland_app_id_resolver_v2 *resolver, + uint32_t request_id, + int32_t pidfd) +{ + (void)resolver; + struct resolver_state *state = data; + state->request_id = request_id; + ++state->identify_count; + state->pidfd = pidfd; +} + +static const struct treeland_app_id_resolver_v2_listener resolver_listener = { + .identify_request = identify_request, +}; + +static struct wl_buffer *create_solid_buffer(struct wl_shm *shm, + int width, + int height, + uint32_t argb) +{ + const int stride = width * 4; + const size_t size = (size_t)stride * height; + char name[64]; + snprintf(name, sizeof(name), "/treeland_splash_desktop_%d_%dx%d", (int)getpid(), width, height); + + const int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); + if (fd < 0) + return NULL; + shm_unlink(name); + if (ftruncate(fd, (off_t)size) < 0) { + close(fd); + return NULL; + } + + void *data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (data == MAP_FAILED) { + close(fd); + return NULL; + } + uint32_t *pixels = data; + for (size_t i = 0; i < (size_t)width * height; ++i) + pixels[i] = argb; + + struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, (int)size); + struct wl_buffer *buffer = wl_shm_pool_create_buffer(pool, 0, width, height, stride, + WL_SHM_FORMAT_ARGB8888); + wl_shm_pool_destroy(pool); + munmap(data, size); + close(fd); + return buffer; +} + +static int state_has_production_splash(const struct prelaunch_splash_desktop_state *state) +{ + return state->output_ready && state->wrapper_created && state->wrapper_in_workspace + && state->wrapper_is_splash && state->wrapper_has_qml_item && state->wrapper_width == 800 + && state->wrapper_height == 600 && strcmp(state->app_id, splash_app_id) == 0; +} + +static int state_has_surviving_icon(const struct prelaunch_splash_desktop_state *state) +{ + return state->icon_ready && state->icon_width == ICON_WIDTH + && state->icon_height == ICON_HEIGHT; +} + +static uint32_t wait_identifier(struct client_connection *connection, + struct client_state *state, + const char *app_id) +{ + for (int roundtrip = 0; roundtrip < 50; ++roundtrip) { + for (int i = 0; i < state->handle_count; ++i) { + struct handle_entry *entry = &state->handles[i]; + if (!entry->closed && entry->identifier && strcmp(entry->app_id, app_id) == 0) + return entry->identifier; + } + if (wl_display_roundtrip(connection->display) < 0) + return 0; + } + return 0; +} + +/* The plain window has no splash, so its app id is never resolved: identify it as + the handle that is not the splash window's. */ +static uint32_t wait_other_identifier(struct client_connection *connection, + struct client_state *state, + uint32_t known_identifier) +{ + for (int roundtrip = 0; roundtrip < 50; ++roundtrip) { + for (int i = 0; i < state->handle_count; ++i) { + struct handle_entry *entry = &state->handles[i]; + if (!entry->closed && entry->identifier && entry->identifier != known_identifier) + return entry->identifier; + } + if (wl_display_roundtrip(connection->display) < 0) + return 0; + } + return 0; +} + +static int show_preview(struct client_connection *connection, + struct client_state *state, + uint32_t identifier) +{ + struct wl_array surfaces; + wl_array_init(&surfaces); + uint32_t *slot = wl_array_add(&surfaces, sizeof(uint32_t)); + if (!slot) { + wl_array_release(&surfaces); + return 0; + } + *slot = identifier; + treeland_dock_preview_context_v3_show(state->context, + &surfaces, + 420, + 1080, + TREELAND_DOCK_PREVIEW_CONTEXT_V3_DIRECTION_BOTTOM); + wl_array_release(&surfaces); + return wl_display_roundtrip(connection->display) >= 0; +} + +static int probe_icon(struct desktop_preview_icon_probe *probe, int expect_icon) +{ + memset(probe, 0, sizeof(*probe)); + probe->expect_icon = expect_icon; + return invoke_on_server_thread(prelaunch_splash_desktop_probe_icon, probe); +} + +static int icon_drawn(const struct desktop_preview_icon_probe *probe) +{ + return probe->preview_found && probe->icon_item_found && probe->icon_buffer_matches + && probe->icon_visible && probe->icon_width > 0 && probe->icon_width == probe->icon_height + && probe->icon_width == probe->title_row_height && probe->capture_ready + && probe->pixel_red >= 250 && probe->pixel_green <= 5 && probe->pixel_blue <= 5 + && probe->pixel_alpha >= 250 && probe->buffer_warnings == 0; +} + +static int icon_hidden(const struct desktop_preview_icon_probe *probe) +{ + return probe->preview_found && !probe->icon_item_found && probe->buffer_warnings == 0; +} + +static void report_probe(const char *stage, const struct desktop_preview_icon_probe *probe) +{ + fprintf(stderr, + " %s: preview=%d item=%d matches=%d visible=%d size=%dx%d row=%d capture=%d " + "rgba=(%d,%d,%d,%d) warnings=%d\n", + stage, + probe->preview_found, + probe->icon_item_found, + probe->icon_buffer_matches, + probe->icon_visible, + probe->icon_width, + probe->icon_height, + probe->title_row_height, + probe->capture_ready, + probe->pixel_red, + probe->pixel_green, + probe->pixel_blue, + probe->pixel_alpha, + probe->buffer_warnings); +} + +#define MAP_STEP(step) \ + do { \ + if (!(step)) { \ + fprintf(stderr, "map_window failed: %s\n", #step); \ + wl_buffer_destroy(buffer); \ + return 0; \ + } \ + } while (0) + +static int map_window(struct client_connection *connection, + struct resolver_state *resolver_state, + struct xdg_toplevel_client *toplevel, + struct treeland_app_id_resolver_v2 *resolver, + const char *app_id, + int width, + int height) +{ + struct wl_buffer *buffer = NULL; + const int requests_before = resolver_state->identify_count; + + MAP_STEP(xdg_toplevel_client_create_pending(connection, toplevel)); + MAP_STEP(wl_display_roundtrip(connection->display) >= 0); + + if (resolver_state->identify_count > requests_before) { + treeland_app_id_resolver_v2_respond(resolver, + resolver_state->request_id, + app_id, + "org.deepin.Sandbox"); + if (resolver_state->pidfd >= 0) { + close(resolver_state->pidfd); + resolver_state->pidfd = -1; + } + } + + /* The size has to be attached before the configure: a same-size window + converts straight through, a differing one would need the geometry + animation, which the headless software renderer never schedules. */ + for (int roundtrip = 0; roundtrip < 50 && !toplevel->configured; ++roundtrip) + MAP_STEP(wl_display_roundtrip(connection->display) >= 0); + MAP_STEP(toplevel->configured); + MAP_STEP(xdg_toplevel_client_ack_latest_configure(connection, toplevel)); + buffer = create_solid_buffer(toplevel->shm, width, height, 0xffffffffu); + MAP_STEP(buffer != NULL); + wl_surface_attach(toplevel->surface, buffer, 0, 0); + wl_surface_damage(toplevel->surface, 0, 0, width, height); + wl_surface_commit(toplevel->surface); + MAP_STEP(wl_display_roundtrip(connection->display) >= 0); + wl_buffer_destroy(buffer); + return 1; +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + struct xdg_toplevel_client splash_window = { 0 }; + struct xdg_toplevel_client plain_window = { 0 }; + struct client_state state = { 0 }; + struct resolver_state resolver_state = { .pidfd = -1 }; + struct prelaunch_splash_desktop_state desktop_state = { 0 }; + struct desktop_preview_icon_probe probe = { 0 }; + struct treeland_app_id_resolver_manager_v2 *resolver_manager = NULL; + struct treeland_app_id_resolver_v2 *resolver = NULL; + struct treeland_prelaunch_splash_manager_v2 *splash_manager = NULL; + struct treeland_prelaunch_splash_v2 *splash = NULL; + struct wl_shm *shm = NULL; + struct wl_buffer *icon = NULL; + uint32_t splash_identifier = 0; + uint32_t plain_identifier = 0; + int observed = 0; + int result = 1; + const char *stage = "connect"; + + if (!client_connect(&connection, socket_name)) + goto done; + + stage = "bind globals"; + resolver_manager = client_bind(&connection, + "treeland_app_id_resolver_manager_v2", + &treeland_app_id_resolver_manager_v2_interface, + 1); + splash_manager = client_bind(&connection, + "treeland_prelaunch_splash_manager_v2", + &treeland_prelaunch_splash_manager_v2_interface, + 2); + state.manager = client_bind(&connection, + "treeland_foreign_toplevel_manager_v3", + &treeland_foreign_toplevel_manager_v3_interface, + 1); + shm = client_bind(&connection, "wl_shm", &wl_shm_interface, 1); + if (!resolver_manager || !splash_manager || !state.manager || !shm) + goto done; + treeland_foreign_toplevel_manager_v3_add_listener(state.manager, &manager_listener, &state); + + resolver = treeland_app_id_resolver_manager_v2_get_resolver(resolver_manager); + if (!resolver + || treeland_app_id_resolver_v2_add_listener(resolver, &resolver_listener, &resolver_state)) + goto done; + + /* Phase 1: the splash wrapper and its teardown. */ + stage = "create splash"; + icon = create_solid_buffer(shm, ICON_WIDTH, ICON_HEIGHT, ICON_ARGB); + if (!icon) + goto done; + splash = treeland_prelaunch_splash_manager_v2_create_splash(splash_manager, + splash_app_id, + "protocol-instance", + "org.deepin.Sandbox", + icon); + if (!splash || wl_display_roundtrip(connection.display) < 0) + goto done; + + /* The compositor owns the icon from here; the client drops its reference like AM does. */ + wl_buffer_destroy(icon); + icon = NULL; + + if (!invoke_on_server_thread(prelaunch_splash_desktop_wait_for_creation, &observed) || !observed + || !invoke_on_server_thread(prelaunch_splash_desktop_read_state, &desktop_state) + || !state_has_production_splash(&desktop_state) + || !state_has_surviving_icon(&desktop_state)) { + stage = "splash wrapper"; + goto done; + } + observed = 0; + + treeland_prelaunch_splash_v2_destroy(splash); + splash = NULL; + if (wl_display_roundtrip(connection.display) < 0 + || !invoke_on_server_thread(prelaunch_splash_desktop_wait_for_destruction, &observed) + || !observed + || !invoke_on_server_thread(prelaunch_splash_desktop_read_state, &desktop_state) + || !desktop_state.wrapper_destroyed || desktop_state.wrapper_in_workspace) { + stage = "splash teardown"; + goto done; + } + observed = 0; + desktop_state = (struct prelaunch_splash_desktop_state){ 0 }; + + /* Phase 2: the icon outliving the splash, drawn by the dock preview. */ + stage = "create icon splash"; + icon = create_solid_buffer(shm, ICON_WIDTH, ICON_HEIGHT, ICON_ARGB); + if (!icon) + goto done; + splash = treeland_prelaunch_splash_manager_v2_create_splash(splash_manager, + icon_app_id, + "dockpreview-instance", + "org.deepin.Sandbox", + icon); + if (!splash || wl_display_roundtrip(connection.display) < 0) + goto done; + wl_buffer_destroy(icon); + icon = NULL; + + if (!invoke_on_server_thread(prelaunch_splash_desktop_wait_for_creation, &observed) || !observed) { + stage = "icon splash wrapper"; + goto done; + } + observed = 0; + + stage = "convert splash into the app window"; + if (!map_window(&connection, + &resolver_state, + &splash_window, + resolver, + icon_app_id, + SPLASH_WINDOW_WIDTH, + SPLASH_WINDOW_HEIGHT)) + goto done; + if (!invoke_on_server_thread(prelaunch_splash_desktop_wait_converted, &observed) || !observed + || !invoke_on_server_thread(prelaunch_splash_desktop_read_state, &desktop_state) + || !desktop_state.converted_to_xdg || !desktop_state.splash_item_gone + || !state_has_surviving_icon(&desktop_state)) { + stage = "splash conversion"; + goto done; + } + + stage = "map a window without a splash"; + splash_identifier = wait_identifier(&connection, &state, icon_app_id); + if (!splash_identifier) + goto done; + if (!map_window(&connection, + &resolver_state, + &plain_window, + resolver, + plain_app_id, + PLAIN_WINDOW_WIDTH, + PLAIN_WINDOW_HEIGHT)) + goto done; + plain_identifier = wait_other_identifier(&connection, &state, splash_identifier); + if (!plain_identifier) + goto done; + + stage = "create dock preview context"; + state.context = treeland_foreign_toplevel_manager_v3_get_dock_preview_context( + state.manager, splash_window.surface); + if (!state.context) + goto done; + treeland_dock_preview_context_v3_add_listener(state.context, &context_listener, &state); + + stage = "dock preview shows the AM icon"; + if (!show_preview(&connection, &state, splash_identifier) || !probe_icon(&probe, 1) + || !icon_drawn(&probe)) { + report_probe("dock preview shows the AM icon", &probe); + goto done; + } + report_probe("dock preview shows the AM icon", &probe); + + stage = "hover switching"; + for (int i = 0; i < PREVIEW_SWITCHES; ++i) { + if (!show_preview(&connection, &state, plain_identifier) || !probe_icon(&probe, 0) + || !icon_hidden(&probe)) { + report_probe("hover to a window without a splash", &probe); + goto done; + } + if (!show_preview(&connection, &state, splash_identifier) || !probe_icon(&probe, 1) + || !icon_drawn(&probe)) { + report_probe("hover back to the window with the icon", &probe); + goto done; + } + } + report_probe("after repeated hover switching", &probe); + + stage = "close the window the icon came from"; + xdg_toplevel_client_destroy(&splash_window); + memset(&splash_window, 0, sizeof(splash_window)); + wl_display_roundtrip(connection.display); + + if (!show_preview(&connection, &state, plain_identifier) || !probe_icon(&probe, 0) + || !icon_hidden(&probe)) { + report_probe("hover after the icon's window closed", &probe); + goto done; + } + report_probe("hover after the icon's window closed", &probe); + + stage = "close the dock preview"; + treeland_dock_preview_context_v3_close(state.context); + if (wl_display_roundtrip(connection.display) < 0) + goto done; + + result = 0; +done: + if (result != 0) { + fprintf(stderr, + "prelaunch splash desktop failed at %s: splash=(created=%d xdg=%d item-gone=%d " + "icon=%d %dx%d) destruction=(destroyed=%d in-workspace=%d) " + "identifiers=(splash=%u plain=%u) output=%d\n", + stage, + desktop_state.wrapper_created, + desktop_state.converted_to_xdg, + desktop_state.splash_item_gone, + desktop_state.icon_ready, + desktop_state.icon_width, + desktop_state.icon_height, + desktop_state.wrapper_destroyed, + desktop_state.wrapper_in_workspace, + splash_identifier, + plain_identifier, + desktop_state.output_ready); + } + if (icon) + wl_buffer_destroy(icon); + if (state.context) + treeland_dock_preview_context_v3_destroy(state.context); + for (int i = 0; i < state.handle_count; ++i) { + if (state.handles[i].handle) + treeland_foreign_toplevel_handle_v3_destroy(state.handles[i].handle); + } + if (plain_window.surface) + xdg_toplevel_client_destroy(&plain_window); + if (splash_window.surface) + xdg_toplevel_client_destroy(&splash_window); + if (splash) + treeland_prelaunch_splash_v2_destroy(splash); + if (resolver) + treeland_app_id_resolver_v2_destroy(resolver); + if (splash_manager) + treeland_prelaunch_splash_manager_v2_destroy(splash_manager); + if (resolver_manager) + treeland_app_id_resolver_manager_v2_destroy(resolver_manager); + if (state.manager) + treeland_foreign_toplevel_manager_v3_destroy(state.manager); + if (resolver_state.pidfd >= 0) + close(resolver_state.pidfd); + client_disconnect(&connection); + return result; +} diff --git a/tests/protocols/treeland-prelaunch-splash-desktop-v2/treeland-prelaunch-splash-desktop-v2.h b/tests/protocols/treeland-prelaunch-splash-desktop-v2/treeland-prelaunch-splash-desktop-v2.h new file mode 100644 index 0000000000..4ae363ae3f --- /dev/null +++ b/tests/protocols/treeland-prelaunch-splash-desktop-v2/treeland-prelaunch-splash-desktop-v2.h @@ -0,0 +1,49 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +struct prelaunch_splash_desktop_state { + int output_ready; + int wrapper_created; + int wrapper_in_workspace; + int wrapper_is_splash; + int wrapper_has_qml_item; + int wrapper_destroyed; + int wrapper_width; + int wrapper_height; + int icon_ready; + int icon_width; + int icon_height; + char app_id[96]; + /* After the splash converted into the app's real window. */ + int converted_to_xdg; + int splash_item_gone; +}; + +struct desktop_preview_icon_probe { + int expect_icon; + int preview_found; + int icon_item_found; + int icon_buffer_matches; + int icon_visible; + int icon_width; + int icon_height; + int title_row_height; + int capture_ready; + int pixel_red; + int pixel_green; + int pixel_blue; + int pixel_alpha; + int buffer_warnings; +}; + +int protocol_test_run(const char *socket_name); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/treeland-prelaunch-splash-v2/CMakeLists.txt b/tests/protocols/treeland-prelaunch-splash-v2/CMakeLists.txt new file mode 100644 index 0000000000..af5717d2ee --- /dev/null +++ b/tests/protocols/treeland-prelaunch-splash-v2/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_prelaunch_splash_v2 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-prelaunch-splash-unstable-v2.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-prelaunch-splash-v2.c" +) diff --git a/tests/protocols/treeland-prelaunch-splash-v2/README.md b/tests/protocols/treeland-prelaunch-splash-v2/README.md new file mode 100644 index 0000000000..c934bf7d5f --- /dev/null +++ b/tests/protocols/treeland-prelaunch-splash-v2/README.md @@ -0,0 +1,73 @@ +# `treeland-prelaunch-splash-v2` 测试规范 + +## 范围 + +- 协议/资源级测试:`tests/protocols/treeland-prelaunch-splash-v2/`。 +- 桌面生产链路测试:`tests/protocols/treeland-prelaunch-splash-desktop-v2/`。 +- 覆盖等级:**I / E**。 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | +| --- | --- | --- | +| 创建 splash | 用空 icon 和真实 `wl_shm` icon buffer 创建 | 生产 handler 每次均发出请求,并保留 app/instance/icon 信息 | +| 同 app | 用相同 app-id 再创建 | 请求不会被错误去重 | +| 关闭 | 销毁 splash 资源 | 生产 close 请求携带对应 app-id 与 instance-id | + +## 已证明的生产链路(E) + +桌面测试启动真实 `WaylandServer`、`ShellHandler`、`Workspace`、root output/container 和 +headless output。fixture 在全局 DConfig 初始化完成后明确启用 +`enablePrelaunchSplash`,因此测试不会被机器上遗留的全局关闭值误判。 + +客户端向真实 `treeland_prelaunch_splash_manager_v2` 发送: + +```text +create_splash( + app_id = "org.deepin.treeland.protocol.splash", + instance_id = "protocol-instance", + sandbox = "org.deepin.Sandbox", + icon = 2×2 wl_shm buffer) +``` + +测试观察的不是 fixture 手工创建的对象,而是以下生产调用链: + +```text +create_splash + → PrelaunchSplash::splashRequested + → ShellHandler::handlePrelaunchSplashRequested + → WindowConfigStore::withSplashConfigFor + → ShellHandler::createPrelaunchSplash + → new SurfaceWrapper(... SplashScreen ...) + → Workspace::addSurface +``` + +`WindowConfigStore` 的每应用配置可能异步完成。测试只等待两个精确的生产事件, +不以固定延时或轮询推测服务端状态:创建阶段等待 `Workspace` 发出 +`SurfaceContainer::surfaceAdded`;销毁阶段等待该 wrapper 的 `QObject::destroyed`。 + +| 阶段 | 客户端动作 | 必须观察到的生产业务结果 | +| --- | --- | --- | +| 创建 | 发送上述 `create_splash` | workspace 收到 app-id 匹配的 `SurfaceWrapper` | +| wrapper 语义 | 读取该生产 wrapper | `type == SplashScreen`;`appId` 与请求相同;已存在 `prelaunchSplash()` QML item | +| 配置结果 | 读取 wrapper 的 implicit size | 应用配置默认的 `800 × 600` 已写入生产 wrapper | +| 加入桌面 | 查询真实 workspace | wrapper 确实包含在 `Workspace::surfaces()`,不是独立的测试对象 | +| 图标锁住 | 发送 `create_splash` 后立即销毁客户端 `wl_buffer` | wrapper 的 `appIcon()` 仍可读,尺寸与提交的 `2 × 2` 一致:客户端已不再持有该 buffer,读到的指针仍然有效 | +| 关闭 | 销毁客户端 splash 资源 | `ShellHandler::handlePrelaunchSplashClosed` 经 root container 销毁 wrapper;wrapper 离开 workspace 且发出 destroyed | + +## 生产结果 + +基础测试使用真实 `wl_buffer`,并观察生产 splash request/close 信号。桌面测试进一步 +证明该信号已进入生产 `ShellHandler`,实际生成并管理 splash wrapper,并在客户端释放 +`wl_buffer` 之后仍能通过 `SurfaceWrapper::appIcon()` 读到图标。 + +## 已知边界 / 下一项结果 + +本目录的断言都发生在 splash 阶段内部:此时 splash QML item(`PrelaunchSplash.qml` 内的 +`BufferItem`)自己也持有一份 buffer 锁,所以「客户端释放后指针仍有效」只能说明至少还有一个 +持有者,不能证明是 wrapper 的锁在保它,也没有覆盖「splash item 被销毁之后」这一真正目标场景。 + +跨阶段保留与 dock preview 实际绘制由 +[treeland-prelaunch-splash-desktop-v2](../treeland-prelaunch-splash-desktop-v2/README.md) +覆盖:它在 splash item 已销毁、客户端 `wl_buffer` 已销毁之后读取 `appIcon()`,并把该 buffer +读回为图标纹理像素。splash 自身的可见性与像素仍未验证。 diff --git a/tests/protocols/treeland-prelaunch-splash-v2/setup.cpp b/tests/protocols/treeland-prelaunch-splash-v2/setup.cpp new file mode 100644 index 0000000000..040e767256 --- /dev/null +++ b/tests/protocols/treeland-prelaunch-splash-v2/setup.cpp @@ -0,0 +1,61 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "modules/prelaunch-splash/prelaunchsplash.h" +#include "server-bridge.h" +#include "treeland-prelaunch-splash-v2.h" + +#include +#include + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +#ifndef DRM_FORMAT_ARGB8888 +#define DRM_FORMAT_ARGB8888 0x34325241u +#endif +#ifndef DRM_FORMAT_XRGB8888 +#define DRM_FORMAT_XRGB8888 0x34325258u +#endif + +namespace { +splash_server_state g_state {}; +} + +static void recordRequest(const QString &appId, const QString &instanceId, bool iconNonNull) +{ + if (g_state.request_count < SPLASH_TEST_MAX_REQUESTS) { + auto &record = g_state.requests[g_state.request_count]; + snprintf(record.app_id, sizeof(record.app_id), "%s", qPrintable(appId)); + snprintf(record.instance_id, sizeof(record.instance_id), "%s", qPrintable(instanceId)); + record.icon_non_null = iconNonNull ? 1 : 0; + } + ++g_state.request_count; +} + +void protocol_test_setup(WaylandServer *server) +{ + auto *splash = find_server_interface(server); + Q_ASSERT(splash); + QObject::connect(splash, &PrelaunchSplash::splashRequested, + [](const QString &appId, const QString &instanceId, wlr_buffer *iconBuffer) { + recordRequest(appId, instanceId, iconBuffer != nullptr); + }); + QObject::connect(splash, &PrelaunchSplash::splashCloseRequested, + [](const QString &appId, const QString &instanceId) { + ++g_state.close_count; + snprintf(g_state.last_close_app_id, sizeof(g_state.last_close_app_id), + "%s", qPrintable(appId)); + snprintf(g_state.last_close_instance_id, sizeof(g_state.last_close_instance_id), + "%s", qPrintable(instanceId)); + }); + +} + +extern "C" void splash_query_state(void *data) +{ + auto *state = static_cast(data); + *state = g_state; +} diff --git a/tests/protocols/treeland-prelaunch-splash-v2/treeland-prelaunch-splash-v2.c b/tests/protocols/treeland-prelaunch-splash-v2/treeland-prelaunch-splash-v2.c new file mode 100644 index 0000000000..cdd0d8e31c --- /dev/null +++ b/tests/protocols/treeland-prelaunch-splash-v2/treeland-prelaunch-splash-v2.c @@ -0,0 +1,247 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 200809L +#endif +#include "treeland-prelaunch-splash-v2.h" +#include "server-bridge-api.h" +#include "treeland-prelaunch-splash-unstable-v2-client-protocol.h" + +#include +#include +#include +#include +#include +#include +#include + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); +}; + +void test_init(struct test_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); + ctx->result_cap = 32; + ctx->results = calloc(ctx->result_cap, sizeof(*ctx->results)); +} + +void test_destroy(struct test_ctx *ctx) +{ + free(ctx->results); + memset(ctx, 0, sizeof(*ctx)); +} + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +void test_pass(struct test_ctx *ctx, int index) +{ + ctx->results[index].failed = 0; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->display = ctx->connection.display; + ctx->manager = client_bind(&ctx->connection, "treeland_prelaunch_splash_manager_v2", + &treeland_prelaunch_splash_manager_v2_interface, 1); + ctx->shm = client_bind(&ctx->connection, "wl_shm", &wl_shm_interface, 1); + return ctx->manager != NULL; +} + +static int bind_manager(struct test_ctx *ctx) +{ + return ctx->manager != NULL; +} + +static int create_splash_null_icon(struct test_ctx *ctx) +{ + ctx->splash1 = treeland_prelaunch_splash_manager_v2_create_splash( + ctx->manager, "test-app", "test-instance-1", "org.deepin.Sandbox", NULL); + return ctx->splash1 != NULL; +} + +static int create_splash_with_icon(struct test_ctx *ctx) +{ + + if (!ctx->shm) + return 0; + const int stride = 4; + const int size = stride; + char shm_name[64]; + snprintf(shm_name, sizeof(shm_name), "/treeland_splash_test_icon_%d", (int)getpid()); + const int fd = shm_open(shm_name, O_RDWR | O_CREAT | O_EXCL, 0600); + if (fd < 0) + return 0; + shm_unlink(shm_name); + if (ftruncate(fd, size) < 0) { + close(fd); + return 0; + } + void *data = mmap(NULL, (size_t)size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (data == MAP_FAILED) { + close(fd); + return 0; + } + memset(data, 0, (size_t)size); + struct wl_shm_pool *pool = wl_shm_create_pool(ctx->shm, fd, size); + ctx->icon_buffer = wl_shm_pool_create_buffer(pool, 0, 1, 1, stride, WL_SHM_FORMAT_ARGB8888); + wl_shm_pool_destroy(pool); + munmap(data, (size_t)size); + close(fd); + if (!ctx->icon_buffer) + return 0; + ctx->splash2 = treeland_prelaunch_splash_manager_v2_create_splash( + ctx->manager, "test-app", "test-instance-2", "org.deepin.Sandbox", ctx->icon_buffer); + return ctx->splash2 != NULL; +} + +static int create_splash_same_app(struct test_ctx *ctx) +{ + ctx->splash3 = treeland_prelaunch_splash_manager_v2_create_splash( + ctx->manager, "test-app", "test-instance-3", "org.deepin.Sandbox", NULL); + return ctx->splash3 != NULL; +} + +static int query_server(struct test_ctx *ctx) +{ + return invoke_on_server_thread(splash_query_state, &ctx->server); +} + +static int splash_requested_null_icon(struct test_ctx *ctx) +{ + return ctx->server.request_count == 1 + && strcmp(ctx->server.requests[0].app_id, "test-app") == 0 + && strcmp(ctx->server.requests[0].instance_id, "test-instance-1") == 0 + && ctx->server.requests[0].icon_non_null == 0; +} + +static int splash_requested_with_icon(struct test_ctx *ctx) +{ + return ctx->server.request_count == 2 + && strcmp(ctx->server.requests[1].app_id, "test-app") == 0 + && strcmp(ctx->server.requests[1].instance_id, "test-instance-2") == 0 + && ctx->server.requests[1].icon_non_null == 1; +} + +static int splash_requested_no_dedup(struct test_ctx *ctx) +{ + + return ctx->server.request_count == 3 + && strcmp(ctx->server.requests[2].app_id, "test-app") == 0 + && strcmp(ctx->server.requests[2].instance_id, "test-instance-3") == 0 + && ctx->server.requests[2].icon_non_null == 0; +} + +static int destroy_splash(struct test_ctx *ctx) +{ + if (!ctx->splash1) + return 0; + treeland_prelaunch_splash_v2_destroy(ctx->splash1); + ctx->splash1 = NULL; + return 1; +} + +static int splash_close_requested(struct test_ctx *ctx) +{ + return ctx->server.close_count == 1 + && strcmp(ctx->server.last_close_app_id, "test-app") == 0 + && strcmp(ctx->server.last_close_instance_id, "test-instance-1") == 0; +} + +static int destroy_manager(struct test_ctx *ctx) +{ + if (!ctx->manager) + return 0; + treeland_prelaunch_splash_manager_v2_destroy(ctx->manager); + ctx->manager = NULL; + return 1; +} + +static const struct test_case cases[] = { + { "manager.bind", bind_manager }, + { "manager.create_splash_null_icon", create_splash_null_icon }, + { "server.splash_requested_null_icon", query_server }, + { "server.assert_splash_requested_null_icon", splash_requested_null_icon }, + { "manager.create_splash_with_icon", create_splash_with_icon }, + { "server.splash_requested_with_icon", query_server }, + { "server.assert_splash_requested_with_icon", splash_requested_with_icon }, + { "manager.create_splash_same_app", create_splash_same_app }, + { "server.splash_requested_same_app", query_server }, + { "server.assert_splash_requested_no_dedup", splash_requested_no_dedup }, + { "splash.destroy", destroy_splash }, + { "server.splash_close_requested", query_server }, + { "server.assert_splash_close_requested", splash_close_requested }, + { "manager.destroy", destroy_manager }, +}; + +void test_cleanup(struct test_ctx *ctx) +{ + if (ctx->splash3) treeland_prelaunch_splash_v2_destroy(ctx->splash3); + if (ctx->splash2) treeland_prelaunch_splash_v2_destroy(ctx->splash2); + if (ctx->splash1) treeland_prelaunch_splash_v2_destroy(ctx->splash1); + if (ctx->icon_buffer) wl_buffer_destroy(ctx->icon_buffer); + if (ctx->manager) treeland_prelaunch_splash_manager_v2_destroy(ctx->manager); + client_disconnect(&ctx->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx; + test_init(&ctx); + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect to or bind treeland_prelaunch_splash_manager_v2\n"); + test_cleanup(&ctx); + test_destroy(&ctx); + return 1; + } + + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const int result = test_add(&ctx, cases[i].name); + if (!cases[i].run(&ctx)) + test_fail(&ctx, result, "assertion failed"); + if (wl_display_roundtrip(ctx.display) < 0) + test_fail(&ctx, result, "Wayland connection failed"); + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + test_destroy(&ctx); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-prelaunch-splash-v2/treeland-prelaunch-splash-v2.h b/tests/protocols/treeland-prelaunch-splash-v2/treeland-prelaunch-splash-v2.h new file mode 100644 index 0000000000..bd84ac50bd --- /dev/null +++ b/tests/protocols/treeland-prelaunch-splash-v2/treeland-prelaunch-splash-v2.h @@ -0,0 +1,66 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef PRELAUNCH_SPLASH_TEST_H +#define PRELAUNCH_SPLASH_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); +void splash_query_state(void *data); + +#include "client-connection.h" + +#define TEST_MSG_MAX 256 +#define SPLASH_TEST_MAX_REQUESTS 8 + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +struct splash_server_state { + int request_count; + int close_count; + struct { + char app_id[64]; + char instance_id[64]; + int icon_non_null; + } requests[SPLASH_TEST_MAX_REQUESTS]; + char last_close_app_id[64]; + char last_close_instance_id[64]; +}; + +struct test_ctx { + struct client_connection connection; + struct wl_display *display; + + struct treeland_prelaunch_splash_manager_v2 *manager; + struct wl_shm *shm; + + struct treeland_prelaunch_splash_v2 *splash1; + struct treeland_prelaunch_splash_v2 *splash2; + struct treeland_prelaunch_splash_v2 *splash3; + struct wl_buffer *icon_buffer; + + struct splash_server_state server; + + struct test_result *results; + int result_count; + int result_cap; +}; + +void test_init(struct test_ctx *ctx); +void test_destroy(struct test_ctx *ctx); +int test_add(struct test_ctx *ctx, const char *name); +void test_fail(struct test_ctx *ctx, int idx, const char *fmt, ...); +void test_pass(struct test_ctx *ctx, int idx); +int test_print_results(struct test_ctx *ctx); +void test_cleanup(struct test_ctx *ctx); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-region-watch-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-region-watch-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..e2167065de --- /dev/null +++ b/tests/protocols/treeland-region-watch-unstable-v1/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_region_watch_unstable_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-region-watch-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-region-watch-unstable-v1.c" +) diff --git a/tests/protocols/treeland-region-watch-unstable-v1/README.md b/tests/protocols/treeland-region-watch-unstable-v1/README.md new file mode 100644 index 0000000000..ee357a1505 --- /dev/null +++ b/tests/protocols/treeland-region-watch-unstable-v1/README.md @@ -0,0 +1,57 @@ +# `treeland-region-watch-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`treeland_region_watch_manager_v1` / `treeland_region_watch_v1` +- 测试源码:`tests/protocols/treeland-region-watch-unstable-v1/` +- Fixture:协议 fixture(`protocol_test_setup` 创建单个 headless 主输出) +- 覆盖等级:**E**(当前仅覆盖单输出 overlap 状态机;多输出/output_removed 待完善,见文末 TODO) + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | +| --- | --- | --- | +| set_region 记录区域 | `set_region(全主输出覆盖, top, 主输出)` | 服务端记录区域 = 输出布局位置 + 全覆盖条带(全局坐标);无窗口时立即发送 `leave`(协议要求 set_region 后必须评估并回发当前状态) | +| enter | 创建并 map xdg-toplevel | 服务端 per-window rect 跟踪重算后发送 `enter` | +| leave | 销毁 toplevel | 重算后发送 `leave` | +| 条带区域 | `set_region(100,40, top, 主输出)` | 服务端区域更新为主输出位置 + 条带,并重新发送 `leave` | +| manager.destroy | 销毁 manager 资源后继续 `set_region` | watcher 不受影响,区域重新记录并回发 `leave` | + +## 已证明的生产链路 + +客户端绑定 `treeland_region_watch_manager_v1` 并 `get_region_watch` 创建 watcher; +`set_region` 在服务端按 anchor 计算输出边缘条带区域(左/右为全输出高的 width 厚条带, +上/下为全输出宽的 height 厚条带),并连接 `WOutput::beforeDestroy`。 + +窗口重叠检测走生产路径:`WaylandServer::onSurfaceWrapperAdded` 对非 layer +`SurfaceWrapper` 调用 `TreelandRegionWatchManagerInterfaceV1::addSurface`,由 +region-watch 模块内部维护 per-window rect 列表(几何/可见性变化经 300ms 去抖触发重算, +仅计入 XdgToplevel/XWayland);`checkOverlapConflict` 对每个 watcher 求交集并按状态变化 +发送 `enter`/`leave`;`set_region` 后通过 `recheck()` 立即用当前窗口列表评估一次。区域按 +输出在布局中的位置平移到全局坐标(`WOutput::position()`)后再与窗口矩形比较。 + +## 同步方式 + +enter/leave 由生产侧 300ms 去抖定时器异步发出,属框架禁止的“固定延时后猜测状态” +场景。测试改用与定时器完全相同的生产评估路径:server-bridge 在服务端线程同步调用 +`manager->recheck()`,`invoke_on_server_thread` +返回即完成边界(评估与事件发送已在同一次调用内完成),随后一次 roundtrip 投递事件。 +否定断言(inert、跨输出不误报)同样以一次注入评估 + roundtrip 为观察边界:事件只 +会在 `evaluate()` 中发出,评估后计数未变即证明无事件。全程无固定延时、无重试轮询。 + +服务端实现位于 +`src/modules/region-watch/regionwatchmanagerinterfacev1.h`、 +`regionwatchmanagerinterfacev1.cpp`(含窗口 rect 跟踪与去抖定时器)。 + +## 已知边界 / 下一项结果 + +- **TODO(multi-output/output_removed)**:第二输出、多屏坐标平移、`output_removed` 与 + inert-until-set_region 语义尚未覆盖。补齐前需先让 fixture 的第二 headless 输出接入 + 输出布局(有 `WOutput` 包装与布局位置),对应 `setup.cpp` / + `treeland-region-watch-unstable-v1.c` 中的 TODO 注释。 +- 错误路径:`invalid_anchor` / `invalid_size` 为致命协议错误,框架不支持预期断连的 + case,未覆盖。 +- 多 watcher:多个 watcher 同时监控不同区域的行为未单独验证(实现按 watcher 列表遍历, + 与单 watcher 一致)。 +- 输出 mode/scale 变化:区域在 set_region 时快照,输出尺寸变化后需客户端重新 + set_region(协议语义),未覆盖动态变化场景。 diff --git a/tests/protocols/treeland-region-watch-unstable-v1/setup.cpp b/tests/protocols/treeland-region-watch-unstable-v1/setup.cpp new file mode 100644 index 0000000000..53223e7088 --- /dev/null +++ b/tests/protocols/treeland-region-watch-unstable-v1/setup.cpp @@ -0,0 +1,81 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "modules/region-watch/regionwatchmanagerinterfacev1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "treeland-region-watch-unstable-v1.h" + +#include "core/rootsurfacecontainer.h" +#include "output/output.h" + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +QPointer g_watch; +TreelandRegionWatchManagerInterfaceV1 *g_manager = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + g_manager = find_server_interface(server); + Q_ASSERT(g_manager); + + // TODO(multi-output): the region-watch protocol also defines output + // removal semantics (output_removed + watcher becoming inert) and + // multi-output coordinate translation. Covering those requires a second + // headless output that is wired into the output layout so it has a real + // WOutput wrapper and a layout position. Until that fixture path is + // available, only the single-output state machine is tested. + + QObject::connect(g_manager, &TreelandRegionWatchManagerInterfaceV1::regionWatchCreated, + [](RegionWatchV1 *watch) { g_watch = watch; }); +} + +extern "C" void region_watch_query_state(void *data) +{ + auto *state = static_cast(data); + *state = {}; + if (!g_watch) + return; + state->has_watch = 1; + const QRect region = g_watch->region(); + state->has_region = !region.isEmpty(); + state->x = region.x(); + state->y = region.y(); + state->width = region.width(); + state->height = region.height(); +} + +// Runs the exact production evaluation the 300 ms debounce timer runs, but +// synchronously on the server thread: invoke_on_server_thread returning +// is the completion boundary for enter/leave assertions (the framework's +// sync rules forbid fixed delays and retry polling). +extern "C" void region_watch_recheck(void *) +{ + if (g_manager) + g_manager->recheck(); +} + +// Layout position of the named output, from the same WOutput::position() the +// region translation uses. +extern "C" void region_watch_output_position(void *data) +{ + auto *query = static_cast(data); + query->found = 0; + const auto outputs = WaylandServer::instance()->rootSurfaceContainer()->outputs(); + for (const auto &output : outputs) { + auto *wOutput = output->output(); + if (wOutput->name() == QLatin1String(query->name)) { + const QPoint pos = wOutput->position(); + query->x = pos.x(); + query->y = pos.y(); + query->found = 1; + return; + } + } +} diff --git a/tests/protocols/treeland-region-watch-unstable-v1/treeland-region-watch-unstable-v1.c b/tests/protocols/treeland-region-watch-unstable-v1/treeland-region-watch-unstable-v1.c new file mode 100644 index 0000000000..7eaaeb54a4 --- /dev/null +++ b/tests/protocols/treeland-region-watch-unstable-v1/treeland-region-watch-unstable-v1.c @@ -0,0 +1,325 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "client-connection.h" +#include "server-bridge-api.h" +#include "treeland-region-watch-unstable-v1-client-protocol.h" +#include "treeland-region-watch-unstable-v1.h" +#include "xdg-toplevel-client.h" + +#include +#include +#include + +extern void region_watch_query_state(void *data); +extern void region_watch_recheck(void *data); +extern void region_watch_output_position(void *data); + +// Outputs are discovered dynamically: the test environment may contain +// additional headless outputs created by the production startup path, so +// sizes and creation order of the fixture outputs must not be hardcoded. +struct output_info { + struct wl_output *proxy; + char name[64]; + int mode_w; + int mode_h; + int have_name; + int have_mode; +}; + +static struct output_info s_outputs[16]; +static int s_output_count; + +static void output_geometry(void *data, struct wl_output *output, int32_t x, int32_t y, + int32_t pw, int32_t ph, int32_t subpixel, + const char *make, const char *model, int32_t transform) +{ + (void)data; (void)output; (void)x; (void)y; (void)pw; (void)ph; + (void)subpixel; (void)make; (void)model; (void)transform; +} + +static void output_mode(void *data, struct wl_output *output, uint32_t flags, + int32_t width, int32_t height, int32_t refresh) +{ + (void)output; (void)refresh; + if ((flags & WL_OUTPUT_MODE_CURRENT) == 0) + return; + struct output_info *info = data; + info->mode_w = width; + info->mode_h = height; + info->have_mode = 1; +} + +static void output_done(void *data, struct wl_output *output) +{ + (void)data; (void)output; +} + +static void output_scale(void *data, struct wl_output *output, int32_t scale) +{ + (void)data; (void)output; (void)scale; +} + +static void output_name(void *data, struct wl_output *output, const char *name) +{ + (void)output; + struct output_info *info = data; + snprintf(info->name, sizeof(info->name), "%s", name); + info->have_name = 1; +} + +static void output_description(void *data, struct wl_output *output, const char *description) +{ + (void)data; (void)output; (void)description; +} + +static const struct wl_output_listener output_listener = { + .geometry = output_geometry, + .mode = output_mode, + .done = output_done, + .scale = output_scale, + .name = output_name, + .description = output_description, +}; + +static struct output_info *find_primary_output(void) +{ + struct output_info *best = NULL; + for (int i = 0; i < s_output_count; ++i) { + if (!s_outputs[i].have_name || !s_outputs[i].have_mode) + continue; + if (!best || strcmp(s_outputs[i].name, best->name) < 0) + best = &s_outputs[i]; + } + return best; +} + +// Layout position of a bound output, queried from the server (wl_output +// geometry events always report (0,0)). +static int query_output_position(const struct output_info *info, int *x, int *y) +{ + struct region_watch_output_pos query; + memset(&query, 0, sizeof(query)); + snprintf(query.name, sizeof(query.name), "%s", info->name); + if (!invoke_on_server_thread(region_watch_output_position, &query) || !query.found) + return 0; + *x = query.x; + *y = query.y; + return 1; +} + +struct test_ctx { + struct client_connection connection; + struct wl_display *display; + struct treeland_region_watch_manager_v1 *manager; + struct treeland_region_watch_v1 *watch; + int enter_count; + int leave_count; + int output_removed_count; +}; + +static void watch_enter(void *data, struct treeland_region_watch_v1 *watch) +{ + (void)watch; + ((struct test_ctx *)data)->enter_count++; +} + +static void watch_leave(void *data, struct treeland_region_watch_v1 *watch) +{ + (void)watch; + ((struct test_ctx *)data)->leave_count++; +} + +static void watch_output_removed(void *data, struct treeland_region_watch_v1 *watch) +{ + (void)watch; + ((struct test_ctx *)data)->output_removed_count++; +} + +static const struct treeland_region_watch_v1_listener watch_listener = { + .enter = watch_enter, + .leave = watch_leave, + .output_removed = watch_output_removed, +}; + +static int read_server_state(struct test_ctx *ctx, struct region_watch_server_state *state) +{ + if (wl_display_roundtrip(ctx->display) < 0) + return 0; + memset(state, 0, sizeof(*state)); + return invoke_on_server_thread(region_watch_query_state, state); +} + +// Synchronization boundary for asynchronous production actions: runs the +// exact overlap evaluation the production debounce timer runs, synchronously +// on the compositor thread, then dispatches the resulting events. No fixed +// delays or retry polling (framework sync rules). +static int recheck(struct test_ctx *ctx) +{ + if (invoke_on_server_thread(region_watch_recheck, NULL) <= 0) + return 0; + return wl_display_roundtrip(ctx->display) >= 0; +} + +static int check_state(const struct region_watch_server_state *state, + int has_region, + int x, + int y, + int width, + int height) +{ + return state->has_watch && state->has_region == has_region && state->x == x + && state->y == y && state->width == width && state->height == height; +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx; + memset(&ctx, 0, sizeof(ctx)); + struct region_watch_server_state state; + struct xdg_toplevel_client toplevel; + struct output_info *primary = NULL; + int px = 0, py = 0; + + if (!client_connect(&ctx.connection, socket_name)) { + fprintf(stderr, "region-watch: failed to connect to the test server\n"); + goto failed; + } + ctx.display = ctx.connection.display; + ctx.manager = client_bind(&ctx.connection, "treeland_region_watch_manager_v1", + &treeland_region_watch_manager_v1_interface, 1); + + // Bind every wl_output and discover names/modes. + for (uint32_t i = 0; i < ctx.connection.global_count && s_output_count < 16; ++i) { + const struct client_global *global = &ctx.connection.globals[i]; + if (strcmp(global->interface, "wl_output") != 0) + continue; + struct output_info *info = &s_outputs[s_output_count++]; + memset(info, 0, sizeof(*info)); + uint32_t version = global->version < 4 ? global->version : 4; + info->proxy = wl_registry_bind(ctx.connection.registry, global->name, + &wl_output_interface, version); + if (info->proxy) + wl_output_add_listener(info->proxy, &output_listener, info); + } + if (!ctx.manager || wl_display_roundtrip(ctx.display) < 0) { + fprintf(stderr, "region-watch: failed to bind required globals\n"); + goto failed; + } + + primary = find_primary_output(); + if (!primary || !primary->proxy) { + fprintf(stderr, "region-watch: no usable primary output found\n"); + goto failed; + } + + if (!query_output_position(primary, &px, &py)) { + fprintf(stderr, "region-watch: failed to query output layout positions\n"); + goto failed; + } + + // manager.get_region_watch + ctx.watch = treeland_region_watch_manager_v1_get_region_watch(ctx.manager); + if (!ctx.watch) { + fprintf(stderr, "region-watch: get_region_watch failed\n"); + goto failed; + } + treeland_region_watch_v1_add_listener(ctx.watch, &watch_listener, &ctx); + if (wl_display_roundtrip(ctx.display) < 0) + goto failed; + + // watch.set_region: full primary output coverage. The region must be + // recorded in global layout coordinates (output position + strip). + treeland_region_watch_v1_set_region(ctx.watch, primary->mode_w, primary->mode_h, + TREELAND_REGION_WATCH_V1_ANCHOR_TOP, + primary->proxy); + if (!read_server_state(&ctx, &state) + || !check_state(&state, 1, px, py, primary->mode_w, primary->mode_h)) { + fprintf(stderr, "region-watch: set_region(top) state mismatch: rect=(%d,%d %dx%d), expected (%d,%d %dx%d)\n", + state.x, state.y, state.width, state.height, + px, py, primary->mode_w, primary->mode_h); + goto failed; + } + + // The protocol requires evaluating the overlap state after each + // set_region: with no windows the watcher must report the clear state. + if (ctx.leave_count != 1 || ctx.enter_count != 0) { + fprintf(stderr, "region-watch: expected one leave after set_region, got %d/%d\n", + ctx.enter_count, ctx.leave_count); + goto failed; + } + + // Map a toplevel: the region now overlaps a real window. + if (!xdg_toplevel_client_create_with_solid_buffer(&ctx.connection, &toplevel, + 800, 600, 0xff3366cc)) { + fprintf(stderr, "region-watch: failed to map the xdg toplevel\n"); + goto failed; + } + if (!recheck(&ctx) || ctx.enter_count != 1 || ctx.leave_count != 1) { + fprintf(stderr, "region-watch: enter not delivered after mapping a window (%d/%d)\n", + ctx.enter_count, ctx.leave_count); + xdg_toplevel_client_destroy(&toplevel); + goto failed; + } + xdg_toplevel_client_destroy(&toplevel); + // Roundtrip so the server has processed the destroy and removed the + // wrapper from its rect list before the evaluation runs. + if (wl_display_roundtrip(ctx.display) < 0) + goto failed; + if (!recheck(&ctx) || ctx.leave_count != 2) { + fprintf(stderr, "region-watch: leave not delivered after closing the window (%d)\n", + ctx.leave_count); + goto failed; + } + + // Shrink the region to a thin strip; set_region must be evaluated again + // and re-send the (still clear) state. + treeland_region_watch_v1_set_region(ctx.watch, 100, 40, + TREELAND_REGION_WATCH_V1_ANCHOR_TOP, + primary->proxy); + if (!read_server_state(&ctx, &state) + || !check_state(&state, 1, px, py, primary->mode_w, 40)) { + fprintf(stderr, "region-watch: set_region strip mismatch: rect=(%d,%d %dx%d), expected (%d,%d %dx40)\n", + state.x, state.y, state.width, state.height, px, py, primary->mode_w); + goto failed; + } + if (ctx.leave_count != 3) { + fprintf(stderr, "region-watch: expected re-sent leave after strip set_region, got %d\n", + ctx.leave_count); + goto failed; + } + + // TODO(multi-output/output_removed): exercise a second output, coordinate + // translation, output_removed and the inert-until-set_region semantics + // once the fixture wires a second headless output into the output layout + // (so it has a WOutput wrapper and a layout position). + + // manager.destroy must not affect watchers: the watcher is still usable. + treeland_region_watch_manager_v1_destroy(ctx.manager); + ctx.manager = NULL; + treeland_region_watch_v1_set_region(ctx.watch, primary->mode_w, primary->mode_h, + TREELAND_REGION_WATCH_V1_ANCHOR_TOP, + primary->proxy); + if (!read_server_state(&ctx, &state) + || !check_state(&state, 1, px, py, primary->mode_w, primary->mode_h)) { + fprintf(stderr, "region-watch: watcher unusable after manager destroy\n"); + goto failed; + } + if (ctx.leave_count != 4) { + fprintf(stderr, "region-watch: expected leave after post-removal set_region, got %d\n", + ctx.leave_count); + goto failed; + } + + treeland_region_watch_v1_destroy(ctx.watch); + ctx.watch = NULL; + if (wl_display_roundtrip(ctx.display) < 0) + goto failed; + + client_disconnect(&ctx.connection); + printf("region-watch: all checks passed\n"); + return 0; + +failed: + client_disconnect(&ctx.connection); + return 1; +} diff --git a/tests/protocols/treeland-region-watch-unstable-v1/treeland-region-watch-unstable-v1.h b/tests/protocols/treeland-region-watch-unstable-v1/treeland-region-watch-unstable-v1.h new file mode 100644 index 0000000000..e0cee8a82f --- /dev/null +++ b/tests/protocols/treeland-region-watch-unstable-v1/treeland-region-watch-unstable-v1.h @@ -0,0 +1,34 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef REGION_WATCH_TEST_H +#define REGION_WATCH_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +// Server-side state of the captured watcher, shared by setup.cpp (producer) +// and the C client (consumer via invoke_on_server_thread). +struct region_watch_server_state { + int has_watch; + int has_region; + int x; + int y; + int width; + int height; + char second_output_name[64]; +}; + +// Layout position of an output looked up by name (wl_output geometry events +// always report (0,0), so the client cannot see the layout position itself). +struct region_watch_output_pos { + char name[64]; + int found; + int x; + int y; +}; + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-remote-subsurface-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-remote-subsurface-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..43529dadb2 --- /dev/null +++ b/tests/protocols/treeland-remote-subsurface-unstable-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME treeland_remote_subsurface_unstable_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-remote-subsurface-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-remote-subsurface-unstable-v1.c" +) diff --git a/tests/protocols/treeland-remote-subsurface-unstable-v1/README.md b/tests/protocols/treeland-remote-subsurface-unstable-v1/README.md new file mode 100644 index 0000000000..9ce6e138af --- /dev/null +++ b/tests/protocols/treeland-remote-subsurface-unstable-v1/README.md @@ -0,0 +1,10 @@ +# remote-subsurface-unstable-v1 + +覆盖等级:E / P。 + +测试导出真实 mapped xdg parent 与 child surface,交换 token 后调用 +`create_remote_subsurface`、`set_position(-12, 34)` 和 `place_below(\"\")`。它在 +compositor 线程回读 parent 的 `WSubsurface`,断言 Remote 类型、父对象、位置和 Below +层级,并检查输入上下文能通过远程子 surface 找到父窗口。测试还断言未知 parent 与 sibling +token 分别产生 `parent_rejected` 和 `invalid_sibling`。跨 client、循环 parent、映射生命周期及 +sibling 间排序仍未覆盖。 diff --git a/tests/protocols/treeland-remote-subsurface-unstable-v1/setup.cpp b/tests/protocols/treeland-remote-subsurface-unstable-v1/setup.cpp new file mode 100644 index 0000000000..eb3909e8b6 --- /dev/null +++ b/tests/protocols/treeland-remote-subsurface-unstable-v1/setup.cpp @@ -0,0 +1,57 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "server-bridge.h" +#include "treeland-remote-subsurface-unstable-v1.h" + +#include "core/shellhandler.h" +#include "protocols/wremotesubsurfacemanagerv1.h" +#include "core/waylandserver.h" +#include "session/sessioninputcontext.h" +#include "surface/surfacewrapper.h" + +#include +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +SurfaceWrapper *g_parent = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + Q_ASSERT(find_server_interface(server)); + add_headless_output(server->backend(), false); + QObject::connect(server->shellHandler(), &ShellHandler::surfaceWrapperAdded, server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() == SurfaceWrapper::Type::XdgToplevel) + g_parent = wrapper; + }); +} + +extern "C" void remote_subsurface_read_server_state(void *data) +{ + auto *state = static_cast(data); + *state = {}; + if (!g_parent || !g_parent->surface()) + return; + + const auto &subsurfaces = g_parent->surface()->subsurfaces(); + if (subsurfaces.isEmpty()) + return; + + auto *subsurface = subsurfaces.constFirst(); + if (!subsurface) + return; + + state->valid = 1; + state->parent_matches = subsurface->parentSurface() == g_parent->surface(); + SessionInputContext inputContext(nullptr, WaylandServer::instance(), nullptr); + state->input_window_matches = inputContext.surface(subsurface->surface()) == g_parent; + state->type = static_cast(subsurface->type()); + state->place = static_cast(subsurface->place()); + const auto position = subsurface->position(); + state->x = position.x(); + state->y = position.y(); +} diff --git a/tests/protocols/treeland-remote-subsurface-unstable-v1/treeland-remote-subsurface-unstable-v1.c b/tests/protocols/treeland-remote-subsurface-unstable-v1/treeland-remote-subsurface-unstable-v1.c new file mode 100644 index 0000000000..443667f49f --- /dev/null +++ b/tests/protocols/treeland-remote-subsurface-unstable-v1/treeland-remote-subsurface-unstable-v1.c @@ -0,0 +1,150 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "client-connection.h" +#include "server-bridge-api.h" +#include "treeland-remote-subsurface-unstable-v1.h" +#include "xdg-toplevel-client.h" +#include "treeland-remote-subsurface-unstable-v1-client-protocol.h" + +#include +#include + +struct export_state { + char token[129]; + unsigned parent_rejected; + uint32_t rejected_reason; + char rejected_token[129]; +}; + +static void surface_token(void *data, struct treeland_exported_surface_v1 *exported, + const char *token) +{ + (void)exported; + struct export_state *state = data; + snprintf(state->token, sizeof(state->token), "%s", token); +} + +static void parent_rejected(void *data, struct treeland_exported_surface_v1 *exported, + uint32_t reason, const char *token) +{ + (void)exported; + struct export_state *state = data; + state->parent_rejected++; + state->rejected_reason = reason; + snprintf(state->rejected_token, sizeof(state->rejected_token), "%s", token); +} + +static const struct treeland_exported_surface_v1_listener exported_listener = { + surface_token, parent_rejected, +}; + +struct remote_state { + unsigned invalid_sibling; + char sibling_token[129]; +}; + +static void invalid_sibling(void *data, struct treeland_remote_subsurface_v1 *remote, + const char *token) +{ + (void)remote; + struct remote_state *state = data; + state->invalid_sibling++; + snprintf(state->sibling_token, sizeof(state->sibling_token), "%s", token); +} + +static const struct treeland_remote_subsurface_v1_listener remote_listener = { + invalid_sibling, +}; + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + struct xdg_toplevel_client parent = { 0 }; + struct export_state parent_state = { 0 }; + struct export_state child_state = { 0 }; + struct remote_state remote_state = { 0 }; + if (!client_connect(&connection, socket_name)) + return 1; + if (!xdg_toplevel_client_create(&connection, &parent)) { + fprintf(stderr, "remote-subsurface: failed to create parent toplevel\n"); + client_disconnect(&connection); + return 1; + } + struct treeland_remote_subsurface_manager_v1 *manager = client_bind(&connection, + "treeland_remote_subsurface_manager_v1", + &treeland_remote_subsurface_manager_v1_interface, 1); + if (!manager) { + fprintf(stderr, "remote-subsurface: missing global\n"); + return 1; + } + struct treeland_exported_surface_v1 *parent_exported = + treeland_remote_subsurface_manager_v1_export_surface(manager, parent.surface); + struct wl_surface *child_surface = wl_compositor_create_surface(parent.compositor); + if (!child_surface) { + fprintf(stderr, "remote-subsurface: child surface creation failed\n"); + return 1; + } + struct treeland_exported_surface_v1 *child_exported = + treeland_remote_subsurface_manager_v1_export_surface(manager, child_surface); + if (!parent_exported || !child_exported) { + fprintf(stderr, "remote-subsurface: export_surface failed\n"); + return 1; + } + treeland_exported_surface_v1_add_listener(parent_exported, &exported_listener, &parent_state); + treeland_exported_surface_v1_add_listener(child_exported, &exported_listener, &child_state); + if (wl_display_roundtrip(connection.display) < 0 || !parent_state.token[0] + || !child_state.token[0]) { + fprintf(stderr, "remote-subsurface: no surface token received\n"); + return 1; + } + struct treeland_remote_subsurface_v1 *invalid_remote = + treeland_exported_surface_v1_create_remote_subsurface(child_exported, "missing-parent"); + if (!invalid_remote || wl_display_roundtrip(connection.display) < 0 + || child_state.parent_rejected != 1 + || child_state.rejected_reason + != TREELAND_EXPORTED_SURFACE_V1_REJECT_REASON_INVALID_TOKEN + || strcmp(child_state.rejected_token, "missing-parent") != 0) { + fprintf(stderr, "remote-subsurface: invalid parent was not rejected\n"); + return 1; + } + struct treeland_remote_subsurface_v1 *remote = + treeland_exported_surface_v1_create_remote_subsurface(child_exported, parent_state.token); + if (!remote) { + fprintf(stderr, "remote-subsurface: create_remote_subsurface failed\n"); + return 1; + } + treeland_remote_subsurface_v1_add_listener(remote, &remote_listener, &remote_state); + treeland_remote_subsurface_v1_set_position(remote, -12, 34); + treeland_remote_subsurface_v1_place_below(remote, ""); + if (wl_display_roundtrip(connection.display) < 0) { + fprintf(stderr, "remote-subsurface: relationship update failed\n"); + return 1; + } + struct remote_subsurface_server_state server_state = { 0 }; + if (!invoke_on_server_thread(remote_subsurface_read_server_state, &server_state) + || !server_state.valid || !server_state.parent_matches + || server_state.type != 1 /* WSubsurface::Type::Remote */ + || server_state.place != 0 /* WSubsurface::Place::Below */ + || server_state.x != -12.0 || server_state.y != 34.0) { + fprintf(stderr, "remote-subsurface: server state was not applied\n"); + return 1; + } + if (!server_state.input_window_matches) { + fprintf(stderr, "remote-subsurface: input did not resolve to the parent window\n"); + return 1; + } + treeland_remote_subsurface_v1_place_above(remote, "missing-sibling"); + if (wl_display_roundtrip(connection.display) < 0 || remote_state.invalid_sibling != 1 + || strcmp(remote_state.sibling_token, "missing-sibling") != 0) { + fprintf(stderr, "remote-subsurface: invalid sibling was not reported\n"); + return 1; + } + treeland_remote_subsurface_v1_destroy(remote); + treeland_exported_surface_v1_destroy(child_exported); + wl_surface_destroy(child_surface); + treeland_exported_surface_v1_destroy(parent_exported); + treeland_remote_subsurface_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&parent); + client_disconnect(&connection); + return 0; +} diff --git a/tests/protocols/treeland-remote-subsurface-unstable-v1/treeland-remote-subsurface-unstable-v1.h b/tests/protocols/treeland-remote-subsurface-unstable-v1/treeland-remote-subsurface-unstable-v1.h new file mode 100644 index 0000000000..7792be86cf --- /dev/null +++ b/tests/protocols/treeland-remote-subsurface-unstable-v1/treeland-remote-subsurface-unstable-v1.h @@ -0,0 +1,24 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +struct remote_subsurface_server_state { + int valid; + int parent_matches; + int input_window_matches; + int type; + int place; + double x; + double y; +}; + +void remote_subsurface_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/treeland-screensaver-desktop-v2/CMakeLists.txt b/tests/protocols/treeland-screensaver-desktop-v2/CMakeLists.txt new file mode 100644 index 0000000000..681da09360 --- /dev/null +++ b/tests/protocols/treeland-screensaver-desktop-v2/CMakeLists.txt @@ -0,0 +1,10 @@ + +pkg_get_variable(WAYLAND_PROTOCOLS_DATADIR wayland-protocols pkgdatadir) + +treeland_add_protocol_test( + NAME treeland_screensaver_desktop_v2 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-screensaver-unstable-v2.xml" + EXTRA_XMLS "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-idle-notify/ext-idle-notify-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-screensaver-desktop-v2.c" +) diff --git a/tests/protocols/treeland-screensaver-desktop-v2/setup.cpp b/tests/protocols/treeland-screensaver-desktop-v2/setup.cpp new file mode 100644 index 0000000000..7dcb4c5201 --- /dev/null +++ b/tests/protocols/treeland-screensaver-desktop-v2/setup.cpp @@ -0,0 +1,38 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "core/shellhandler.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" +#include "treeland-screensaver-desktop-v2.h" +#include "workspace/workspace.h" + +#include + +namespace { +SurfaceWrapper *g_wrapper = nullptr; +screensaver_desktop_state g_state {}; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [server](SurfaceWrapper *wrapper) { + if (wrapper->type() != SurfaceWrapper::Type::XdgToplevel) + return; + g_wrapper = wrapper; + g_state.wrapper_created = 1; + g_state.wrapper_in_workspace = server->workspace()->surfaces().contains(wrapper) ? 1 : 0; + }); +} + +extern "C" void screensaver_desktop_read_state(void *data) +{ + auto state = g_state; + if (g_wrapper) + state.wrapper_visible = g_wrapper->isVisible() ? 1 : 0; + *static_cast(data) = state; +} diff --git a/tests/protocols/treeland-screensaver-desktop-v2/treeland-screensaver-desktop-v2.c b/tests/protocols/treeland-screensaver-desktop-v2/treeland-screensaver-desktop-v2.c new file mode 100644 index 0000000000..ff56dd20bf --- /dev/null +++ b/tests/protocols/treeland-screensaver-desktop-v2/treeland-screensaver-desktop-v2.c @@ -0,0 +1,139 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#define _POSIX_C_SOURCE 200809L + +#include "treeland-screensaver-desktop-v2.h" +#include "server-bridge-api.h" +#include "ext-idle-notify-v1-client-protocol.h" +#include "client-connection.h" +#include "xdg-toplevel-client.h" +#include "treeland-screensaver-unstable-v2-client-protocol.h" + +#include +#include +#include +#include + +extern void screensaver_desktop_read_state(void *data); + +struct idle_client { + int idled; + int resumed; +}; + +static void idle_notification_idled(void *data, struct ext_idle_notification_v1 *notification) +{ + (void)notification; + ++((struct idle_client *)data)->idled; +} + +static void idle_notification_resumed(void *data, struct ext_idle_notification_v1 *notification) +{ + (void)notification; + ++((struct idle_client *)data)->resumed; +} + +static const struct ext_idle_notification_v1_listener idle_notification_listener = { + .idled = idle_notification_idled, + .resumed = idle_notification_resumed, +}; + +static long elapsed_milliseconds(const struct timespec *start) +{ + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + return (now.tv_sec - start->tv_sec) * 1000L + (now.tv_nsec - start->tv_nsec) / 1000000L; +} + +static int dispatch_for(struct wl_display *display, int milliseconds) +{ + struct timespec start; + clock_gettime(CLOCK_MONOTONIC, &start); + const int fd = wl_display_get_fd(display); + while (elapsed_milliseconds(&start) < milliseconds) { + if (wl_display_dispatch_pending(display) < 0) + return 0; + const int remaining = milliseconds - (int)elapsed_milliseconds(&start); + struct pollfd pollfd = { .fd = fd, .events = POLLIN }; + const int result = poll(&pollfd, 1, remaining > 0 ? remaining : 0); + if (result < 0) + return 0; + if (result > 0 && wl_display_dispatch(display) < 0) + return 0; + } + return 1; +} + +static int read_state(struct screensaver_desktop_state *state) +{ + memset(state, 0, sizeof(*state)); + return invoke_on_server_thread(screensaver_desktop_read_state, state); +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + struct xdg_toplevel_client toplevel = { 0 }; + struct treeland_screensaver_v2 *screensaver = NULL; + struct ext_idle_notifier_v1 *idle_notifier = NULL; + struct ext_idle_notification_v1 *notification = NULL; + struct wl_seat *seat = NULL; + struct idle_client idle = { 0 }; + struct screensaver_desktop_state state = { 0 }; + int stage = 0; + + if (!client_connect(&connection, socket_name)) + return 1; + screensaver = client_bind(&connection, "treeland_screensaver_v2", + &treeland_screensaver_v2_interface, 1); + idle_notifier = client_bind(&connection, "ext_idle_notifier_v1", + &ext_idle_notifier_v1_interface, 1); + seat = client_bind(&connection, "wl_seat", &wl_seat_interface, 1); + if (!screensaver || !idle_notifier || !seat) + goto failed; + stage = 1; + if (!xdg_toplevel_client_create(&connection, &toplevel)) + goto failed; + stage = 2; + if (!read_state(&state) || !state.wrapper_created || !state.wrapper_in_workspace + || !state.wrapper_visible) + goto failed; + + treeland_screensaver_v2_inhibit(screensaver, "protocol-test", "desktop idle inhibition"); + if (wl_display_roundtrip(connection.display) < 0) + goto failed; + stage = 3; + notification = ext_idle_notifier_v1_get_idle_notification(idle_notifier, 20, seat); + if (!notification) + goto failed; + ext_idle_notification_v1_add_listener(notification, &idle_notification_listener, &idle); + if (wl_display_roundtrip(connection.display) < 0 || !dispatch_for(connection.display, 150) + || idle.idled != 0) + goto failed; + stage = 4; + + treeland_screensaver_v2_uninhibit(screensaver); + if (wl_display_roundtrip(connection.display) < 0 || !dispatch_for(connection.display, 500) + || idle.idled != 1) + goto failed; + stage = 5; + + ext_idle_notification_v1_destroy(notification); + ext_idle_notifier_v1_destroy(idle_notifier); + wl_seat_destroy(seat); + xdg_toplevel_client_destroy(&toplevel); + client_disconnect(&connection); + return 0; + +failed: + fprintf(stderr, + "screensaver desktop failure at stage %d: wrapper=%d workspace=%d visible=%d idled=%d resumed=%d\n", + stage, state.wrapper_created, state.wrapper_in_workspace, state.wrapper_visible, + idle.idled, idle.resumed); + if (notification) ext_idle_notification_v1_destroy(notification); + if (idle_notifier) ext_idle_notifier_v1_destroy(idle_notifier); + if (seat) wl_seat_destroy(seat); + xdg_toplevel_client_destroy(&toplevel); + client_disconnect(&connection); + return 1; +} diff --git a/tests/protocols/treeland-screensaver-desktop-v2/treeland-screensaver-desktop-v2.h b/tests/protocols/treeland-screensaver-desktop-v2/treeland-screensaver-desktop-v2.h new file mode 100644 index 0000000000..93640b9b06 --- /dev/null +++ b/tests/protocols/treeland-screensaver-desktop-v2/treeland-screensaver-desktop-v2.h @@ -0,0 +1,20 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +struct screensaver_desktop_state { + int wrapper_created; + int wrapper_in_workspace; + int wrapper_visible; +}; + +int protocol_test_run(const char *socket_name); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/treeland-screensaver-v2/CMakeLists.txt b/tests/protocols/treeland-screensaver-v2/CMakeLists.txt new file mode 100644 index 0000000000..0e44a9aade --- /dev/null +++ b/tests/protocols/treeland-screensaver-v2/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_screensaver_v2 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-screensaver-unstable-v2.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-screensaver-v2.c" +) diff --git a/tests/protocols/treeland-screensaver-v2/README.md b/tests/protocols/treeland-screensaver-v2/README.md new file mode 100644 index 0000000000..af7a066c02 --- /dev/null +++ b/tests/protocols/treeland-screensaver-v2/README.md @@ -0,0 +1,40 @@ +# `treeland-screensaver-v2` 测试规范 + +## 范围 + +- 测试源码:`tests/protocols/treeland-screensaver-v2/`、`tests/protocols/treeland-screensaver-desktop-v2/` +- Fixture:两个 target 均使用 desktop integration fixture。基础 target 读取生产 + `ScreensaverInterfaceV1::isInhibited()`;desktop target 创建 mapped xdg-toplevel,并使用上游 + `ext-idle-notify-v1` 客户端。 +- 覆盖等级:抑制生命周期为 **E**;版本和错误路径为 **P**。 + +## 实际请求与预期结果 + +| 场景 | 客户端发送 | 生产业务逻辑与断言 | +| --- | --- | --- | +| 抑制 idle | 创建 screensaver manager 后调用 inhibit | 在观察窗口内,真实 ext-idle notification 不发送 `idled` | +| 解除抑制 | 销毁/解除 inhibitor | 同一 ext-idle notification 随后发送 `idled` | +| 非法顺序/对象 | 发送 XML 不允许的请求 | Wayland 连接以规定的 EPROTO/协议错误结束 | + +## 已证明的生产链路 + +基础 target 绑定 manager 后发送 inhibit/uninhibit,并通过 desktop runner 的 server callback +读取真实 `ScreensaverInterfaceV1::isInhibited()`;它还验证重复 inhibit 及未 inhibit 时的 +uninhibit 所产生的协议错误。 + +desktop target 首先 map xdg-toplevel,fixture 确认它已成为可见的 workspace `SurfaceWrapper`。 +随后客户端发送 `treeland_screensaver_v2.inhibit("protocol-test", "desktop idle inhibition")`, +再为同一个真实 `wl_seat` 发送上游 +`ext_idle_notifier_v1.get_idle_notification(timeout=20ms, seat)`。 + +在 inhibit 仍存在的 150ms 观察窗口内,client listener 的 `idled` 计数必须仍为 `0`;这直接 +观察 wlroots ext-idle notifier,而不是读取 screensaver 的内部标志。接着发送 +`treeland_screensaver_v2.uninhibit()`,在最多 500ms 内同一个 listener 必须收到恰好 +一次 `idled`。因此该测试证明 inhibit/uninhibit 已实际改变 idle inhibitor 的行为。 + +这里的观察窗口是验证“在 idle timeout 到期后仍未发生事件”这一否定结果所需的协议时间语义; +它不是 fixture ready 或普通 request 完成的同步手段。 + +## 未覆盖 + +未显示实际锁屏 UI;这里只验证 idle-inhibit 这一前置行为。 diff --git a/tests/protocols/treeland-screensaver-v2/setup.cpp b/tests/protocols/treeland-screensaver-v2/setup.cpp new file mode 100644 index 0000000000..e171d6f263 --- /dev/null +++ b/tests/protocols/treeland-screensaver-v2/setup.cpp @@ -0,0 +1,27 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "server-bridge.h" +#include "modules/screensaver/screensaverinterfacev2.h" +#include "core/waylandserver.h" + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +ScreensaverInterfaceV2 *g_screensaver = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + g_screensaver = server->backend()->server()->findInterface(); + Q_ASSERT(g_screensaver); +} + +extern "C" void screensaver_query_inhibited(void *data) +{ + int *inhibited = static_cast(data); + *inhibited = (g_screensaver && g_screensaver->isInhibited()) ? 1 : 0; +} diff --git a/tests/protocols/treeland-screensaver-v2/treeland-screensaver-v2.c b/tests/protocols/treeland-screensaver-v2/treeland-screensaver-v2.c new file mode 100644 index 0000000000..4611226670 --- /dev/null +++ b/tests/protocols/treeland-screensaver-v2/treeland-screensaver-v2.c @@ -0,0 +1,202 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-screensaver-v2.h" +#include "server-bridge-api.h" +#include "treeland-screensaver-unstable-v2-client-protocol.h" + +#include +#include +#include +#include +#include + +extern void screensaver_query_inhibited(void *data); + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); +}; + +void test_init(struct test_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); + ctx->result_cap = 16; + ctx->results = calloc(ctx->result_cap, sizeof(*ctx->results)); +} + +void test_destroy(struct test_ctx *ctx) +{ + free(ctx->results); + memset(ctx, 0, sizeof(*ctx)); +} + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +void test_pass(struct test_ctx *ctx, int index) +{ + ctx->results[index].failed = 0; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + strncpy(ctx->socket_name, socket_name, sizeof(ctx->socket_name) - 1); + ctx->socket_name[sizeof(ctx->socket_name) - 1] = '\0'; + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->display = ctx->connection.display; + ctx->screensaver = client_bind(&ctx->connection, "treeland_screensaver_v2", + &treeland_screensaver_v2_interface, 1); + return ctx->screensaver != NULL; +} + +static int bind_max_version(struct test_ctx *ctx) +{ + + return treeland_screensaver_v2_get_version(ctx->screensaver) == 1; +} + +static int inhibit(struct test_ctx *ctx) +{ + treeland_screensaver_v2_inhibit(ctx->screensaver, "protocol-test", "test inhibit"); + return 1; +} + +static int server_inhibited_after_inhibit(struct test_ctx *ctx) +{ + (void)ctx; + int inhibited = 0; + if (!invoke_on_server_thread(screensaver_query_inhibited, &inhibited)) + return 0; + return inhibited == 1; +} + +static int uninhibit(struct test_ctx *ctx) +{ + treeland_screensaver_v2_uninhibit(ctx->screensaver); + return 1; +} + +static int server_inhibited_after_uninhibit(struct test_ctx *ctx) +{ + (void)ctx; + int inhibited = 1; + if (!invoke_on_server_thread(screensaver_query_inhibited, &inhibited)) + return 0; + return inhibited == 0; +} + +static int expect_protocol_error(struct test_ctx *ctx, struct wl_display *display, + uint32_t expected_code) +{ + + if (wl_display_roundtrip(display) >= 0) + return 0; + ctx->roundtripped = 1; + if (errno != EPROTO) + return 0; + const struct wl_interface *interface = NULL; + uint32_t id = 0; + const uint32_t code = wl_display_get_protocol_error(display, &interface, &id); + return code == expected_code && interface == &treeland_screensaver_v2_interface; +} + +static int uninhibit_without_inhibit(struct test_ctx *ctx) +{ + + treeland_screensaver_v2_uninhibit(ctx->screensaver); + return expect_protocol_error(ctx, ctx->display, TREELAND_SCREENSAVER_V2_ERROR_NOT_YET_INHIBITED); +} + +static int inhibit_twice(struct test_ctx *ctx) +{ + + if (!client_connect(&ctx->error_connection, ctx->socket_name)) + return 0; + ctx->error_screensaver = client_bind(&ctx->error_connection, "treeland_screensaver_v2", + &treeland_screensaver_v2_interface, 1); + if (!ctx->error_screensaver) + return 0; + treeland_screensaver_v2_inhibit(ctx->error_screensaver, "protocol-test", "first inhibit"); + treeland_screensaver_v2_inhibit(ctx->error_screensaver, "protocol-test", "second inhibit"); + return expect_protocol_error(ctx, ctx->error_connection.display, + TREELAND_SCREENSAVER_V2_ERROR_ALREADY_INHIBITED); +} + +static const struct test_case cases[] = { + { "bind.max_version", bind_max_version }, + { "inhibit", inhibit }, + { "server.inhibited_after_inhibit", server_inhibited_after_inhibit }, + { "uninhibit", uninhibit }, + { "server.inhibited_after_uninhibit", server_inhibited_after_uninhibit }, + { "uninhibit_without_inhibit.error.not_yet_inhibited", uninhibit_without_inhibit }, + { "inhibit_twice.error.already_inhibited", inhibit_twice }, +}; + +void test_cleanup(struct test_ctx *ctx) +{ + + client_disconnect(&ctx->error_connection); + client_disconnect(&ctx->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx; + test_init(&ctx); + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect to or bind treeland_screensaver_v2\n"); + test_cleanup(&ctx); + test_destroy(&ctx); + return 1; + } + + const size_t case_count = sizeof(cases) / sizeof(cases[0]); + for (size_t i = 0; i < case_count; ++i) { + const int result = test_add(&ctx, cases[i].name); + if (!cases[i].run(&ctx)) + test_fail(&ctx, result, "assertion failed"); + + if (!ctx.roundtripped && wl_display_roundtrip(ctx.display) < 0) + test_fail(&ctx, result, "Wayland connection failed"); + ctx.roundtripped = 0; + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + test_destroy(&ctx); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-screensaver-v2/treeland-screensaver-v2.h b/tests/protocols/treeland-screensaver-v2/treeland-screensaver-v2.h new file mode 100644 index 0000000000..b71519b543 --- /dev/null +++ b/tests/protocols/treeland-screensaver-v2/treeland-screensaver-v2.h @@ -0,0 +1,50 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef SCREENSAVER_TEST_H +#define SCREENSAVER_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +#include "client-connection.h" + +#define TEST_MSG_MAX 256 + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +struct test_ctx { + struct client_connection connection; + struct client_connection error_connection; + struct wl_display *display; + char socket_name[256]; + + struct treeland_screensaver_v2 *screensaver; + struct treeland_screensaver_v2 *error_screensaver; + + int roundtripped; + + struct test_result *results; + int result_count; + int result_cap; +}; + +void test_init(struct test_ctx *ctx); +void test_destroy(struct test_ctx *ctx); +int test_add(struct test_ctx *ctx, const char *name); +void test_fail(struct test_ctx *ctx, int idx, const char *fmt, ...); +void test_pass(struct test_ctx *ctx, int idx); + +int test_print_results(struct test_ctx *ctx); +void test_cleanup(struct test_ctx *ctx); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-shortcut-manager-desktop-v3/CMakeLists.txt b/tests/protocols/treeland-shortcut-manager-desktop-v3/CMakeLists.txt new file mode 100644 index 0000000000..b522f401f3 --- /dev/null +++ b/tests/protocols/treeland-shortcut-manager-desktop-v3/CMakeLists.txt @@ -0,0 +1,8 @@ +treeland_add_protocol_test( + NAME treeland_shortcut_manager_desktop_v3 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-shortcut-manager-unstable-v3.xml" + EXTRA_XMLS "${CMAKE_SOURCE_DIR}/3rdparty/wlroots/protocol/virtual-keyboard-unstable-v1.xml" + EXTRA_LIBRARIES PkgConfig::XKBCOMMON + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-shortcut-manager-desktop-v3.c" +) diff --git a/tests/protocols/treeland-shortcut-manager-desktop-v3/setup.cpp b/tests/protocols/treeland-shortcut-manager-desktop-v3/setup.cpp new file mode 100644 index 0000000000..ce47d892ba --- /dev/null +++ b/tests/protocols/treeland-shortcut-manager-desktop-v3/setup.cpp @@ -0,0 +1,57 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "core/shellhandler.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "seat/seatmanager.h" +#include "surface/surfacewrapper.h" +#include "treeland-shortcut-manager-desktop-v3.h" +#include "workspace/workspace.h" + +#include +#include + +namespace { +SurfaceWrapper *g_wrapper = nullptr; +shortcut_desktop_state g_state {}; + +WSeat *primarySeat(WaylandServer *server) +{ + const auto seats = server->seatManager()->seats(); + return seats.isEmpty() ? nullptr : seats.constFirst(); +} + +bool hasKeyboardFocus(WaylandServer *server) +{ + auto *seat = primarySeat(server); + return seat && g_wrapper && seat->keyboardFocusSurface() == g_wrapper->surface(); +} +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [server](SurfaceWrapper *wrapper) { + if (wrapper->type() != SurfaceWrapper::Type::XdgToplevel) + return; + g_wrapper = wrapper; + g_state.wrapper_created = 1; + g_state.wrapper_in_workspace = server->workspace()->surfaces().contains(wrapper) ? 1 : 0; + }); +} + +extern "C" void shortcut_desktop_focus_window(void *data) +{ + auto *state = static_cast(data); + auto *server = WaylandServer::instance(); + if (server && g_wrapper) + server->activateSurface(g_wrapper, Qt::ActiveWindowFocusReason); + *state = g_state; + if (server) { + state->wrapper_visible = g_wrapper && g_wrapper->isVisible() ? 1 : 0; + state->keyboard_focused = hasKeyboardFocus(server) ? 1 : 0; + } +} diff --git a/tests/protocols/treeland-shortcut-manager-desktop-v3/treeland-shortcut-manager-desktop-v3.c b/tests/protocols/treeland-shortcut-manager-desktop-v3/treeland-shortcut-manager-desktop-v3.c new file mode 100644 index 0000000000..170ce23eb2 --- /dev/null +++ b/tests/protocols/treeland-shortcut-manager-desktop-v3/treeland-shortcut-manager-desktop-v3.c @@ -0,0 +1,309 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-shortcut-manager-desktop-v3.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "treeland-shortcut-manager-unstable-v3-client-protocol.h" +#include "virtual-keyboard-unstable-v1-client-protocol.h" + +#include +#include +#include +#include +#include +#include +#include + +#include + +extern void shortcut_desktop_focus_window(void *data); + +struct shortcut_client { + int bind_failure; + int activated; + char activated_name[64]; + unsigned int activated_flags; + int captured; + char captured_key[64]; + int capture_failed; +}; + +struct seat_keyboard_events { + int modifiers; + uint32_t depressed; + uint32_t latched; + uint32_t locked; + uint32_t group; +}; + +struct seat_events { + uint32_t capabilities; +}; + +static void seat_capabilities(void *data, struct wl_seat *seat, uint32_t capabilities) +{ + (void)seat; + ((struct seat_events *)data)->capabilities = capabilities; +} + +static void seat_name(void *data, struct wl_seat *seat, const char *name) +{ (void)data; (void)seat; (void)name; } + +static const struct wl_seat_listener seat_listener = { + .capabilities = seat_capabilities, + .name = seat_name, +}; + +static void seat_keyboard_keymap(void *data, struct wl_keyboard *keyboard, + uint32_t format, int32_t fd, uint32_t size) +{ + (void)data; + (void)keyboard; + (void)format; + (void)size; + close(fd); +} + +static void seat_keyboard_enter(void *data, struct wl_keyboard *keyboard, + uint32_t serial, struct wl_surface *surface, struct wl_array *keys) +{ (void)data; (void)keyboard; (void)serial; (void)surface; (void)keys; } +static void seat_keyboard_leave(void *data, struct wl_keyboard *keyboard, + uint32_t serial, struct wl_surface *surface) +{ (void)data; (void)keyboard; (void)serial; (void)surface; } +static void seat_keyboard_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, + uint32_t time, uint32_t key, uint32_t state) +{ (void)data; (void)keyboard; (void)serial; (void)time; (void)key; (void)state; } + +static void seat_keyboard_modifiers(void *data, struct wl_keyboard *keyboard, uint32_t serial, + uint32_t depressed, uint32_t latched, uint32_t locked, uint32_t group) +{ + (void)keyboard; + (void)serial; + struct seat_keyboard_events *events = data; + ++events->modifiers; + events->depressed = depressed; + events->latched = latched; + events->locked = locked; + events->group = group; +} + +static void seat_keyboard_repeat_info(void *data, struct wl_keyboard *keyboard, int32_t rate, int32_t delay) +{ (void)data; (void)keyboard; (void)rate; (void)delay; } + +static const struct wl_keyboard_listener seat_keyboard_listener = { + .keymap = seat_keyboard_keymap, + .enter = seat_keyboard_enter, + .leave = seat_keyboard_leave, + .key = seat_keyboard_key, + .modifiers = seat_keyboard_modifiers, + .repeat_info = seat_keyboard_repeat_info, +}; + +static void manager_activated(void *data, + struct treeland_shortcut_manager_v3 *manager, + const char *name, + uint32_t flags) +{ + (void)manager; + struct shortcut_client *client = data; + ++client->activated; + client->activated_flags = flags; + strncpy(client->activated_name, name, sizeof(client->activated_name) - 1); +} + +static void manager_bind_failure(void *data, + struct treeland_shortcut_manager_v3 *manager, + const char *name, + uint32_t error) +{ + (void)manager; + (void)name; + (void)error; + ++((struct shortcut_client *)data)->bind_failure; +} + +static const struct treeland_shortcut_manager_v3_listener manager_listener = { + .activated = manager_activated, + .bind_failure = manager_bind_failure, +}; + +static void capture_captured(void *data, struct treeland_shortcut_capture_v3 *capture, const char *key) +{ + (void)capture; + struct shortcut_client *client = data; + ++client->captured; + strncpy(client->captured_key, key, sizeof(client->captured_key) - 1); +} + +static void capture_failed(void *data, struct treeland_shortcut_capture_v3 *capture, uint32_t reason) +{ + (void)capture; + (void)reason; + ++((struct shortcut_client *)data)->capture_failed; +} + +static const struct treeland_shortcut_capture_v3_listener capture_listener = { + .captured = capture_captured, + .failed = capture_failed, +}; + +static int send_keymap(struct zwp_virtual_keyboard_v1 *keyboard) +{ + struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + struct xkb_keymap *keymap = context + ? xkb_keymap_new_from_names(context, NULL, XKB_KEYMAP_COMPILE_NO_FLAGS) + : NULL; + char *keymap_text = keymap + ? xkb_keymap_get_as_string(keymap, XKB_KEYMAP_FORMAT_TEXT_V1) + : NULL; + if (!keymap_text) + goto failed; + + char name[64]; + snprintf(name, sizeof(name), "/treeland_shortcut_keymap_%d", (int)getpid()); + const int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); + shm_unlink(name); + if (fd < 0) + goto failed; + const size_t size = strlen(keymap_text) + 1; + if (ftruncate(fd, (off_t)size) < 0 || write(fd, keymap_text, size) != (ssize_t)size) { + close(fd); + goto failed; + } + zwp_virtual_keyboard_v1_keymap(keyboard, + WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1, + fd, + (uint32_t)size); + close(fd); + free(keymap_text); + xkb_keymap_unref(keymap); + xkb_context_unref(context); + return 1; + +failed: + if (keymap_text) free(keymap_text); + if (keymap) xkb_keymap_unref(keymap); + if (context) xkb_context_unref(context); + return 0; +} + +static void send_key(struct zwp_virtual_keyboard_v1 *keyboard, uint32_t key, uint32_t state) +{ + zwp_virtual_keyboard_v1_key(keyboard, 0, key, state); +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + struct xdg_toplevel_client toplevel = { 0 }; + struct treeland_shortcut_manager_v3 *manager = NULL; + struct treeland_shortcut_capture_v3 *capture = NULL; + struct zwp_virtual_keyboard_manager_v1 *virtual_keyboard_manager = NULL; + struct zwp_virtual_keyboard_v1 *virtual_keyboard = NULL; + struct wl_seat *seat = NULL; + struct wl_keyboard *seat_keyboard = NULL; + struct shortcut_desktop_state state = { 0 }; + struct shortcut_client client = { 0 }; + struct seat_keyboard_events keyboard_events = { 0 }; + struct seat_events seat_events = { 0 }; + int stage = 0; + + if (!client_connect(&connection, socket_name)) + return 1; + manager = client_bind(&connection, "treeland_shortcut_manager_v3", + &treeland_shortcut_manager_v3_interface, 1); + seat = client_bind(&connection, "wl_seat", &wl_seat_interface, 1); + virtual_keyboard_manager = client_bind(&connection, "zwp_virtual_keyboard_manager_v1", + &zwp_virtual_keyboard_manager_v1_interface, 1); + if (!manager || !seat || !virtual_keyboard_manager) + goto failed; + wl_seat_add_listener(seat, &seat_listener, &seat_events); + treeland_shortcut_manager_v3_add_listener(manager, &manager_listener, &client); + stage = 1; + if (!xdg_toplevel_client_create(&connection, &toplevel)) + goto failed; + stage = 2; + if (!invoke_on_server_thread(shortcut_desktop_focus_window, &state) + || !state.wrapper_created || !state.wrapper_in_workspace || !state.wrapper_visible + || !state.keyboard_focused) + goto failed; + + virtual_keyboard = zwp_virtual_keyboard_manager_v1_create_virtual_keyboard( + virtual_keyboard_manager, seat); + if (!virtual_keyboard || !send_keymap(virtual_keyboard) + || wl_display_roundtrip(connection.display) < 0 + || !(seat_events.capabilities & WL_SEAT_CAPABILITY_KEYBOARD)) + goto failed; + seat_keyboard = wl_seat_get_keyboard(seat); + if (!seat_keyboard) + goto failed; + wl_keyboard_add_listener(seat_keyboard, &seat_keyboard_listener, &keyboard_events); + zwp_virtual_keyboard_v1_modifiers(virtual_keyboard, 1, 0, 0, 0); + if (wl_display_roundtrip(connection.display) < 0 || keyboard_events.modifiers < 1 + || keyboard_events.depressed != 1 || keyboard_events.latched || keyboard_events.locked + || keyboard_events.group) + goto failed; + zwp_virtual_keyboard_v1_modifiers(virtual_keyboard, 0, 0, 0, 0); + if (wl_display_roundtrip(connection.display) < 0 + || keyboard_events.depressed || keyboard_events.latched || keyboard_events.locked + || keyboard_events.group) + goto failed; + + treeland_shortcut_manager_v3_acquire(manager); + capture = treeland_shortcut_manager_v3_capture_next_shortcut(manager, toplevel.surface, seat); + if (!capture) + goto failed; + treeland_shortcut_capture_v3_add_listener(capture, &capture_listener, &client); + if (wl_display_roundtrip(connection.display) < 0 || client.capture_failed) + goto failed; + stage = 3; + send_key(virtual_keyboard, 59, WL_KEYBOARD_KEY_STATE_PRESSED); // KEY_F1 + if (wl_display_roundtrip(connection.display) < 0 || client.captured != 1 + || strcmp(client.captured_key, "F1") != 0) + goto failed; + stage = 4; + send_key(virtual_keyboard, 59, WL_KEYBOARD_KEY_STATE_RELEASED); // KEY_F1 + if (wl_display_roundtrip(connection.display) < 0) + goto failed; + + // v3: bind_key takes effect immediately — no commit needed. + treeland_shortcut_manager_v3_bind_key( + manager, "desktop-shortcut", "F2", + TREELAND_SHORTCUT_MANAGER_V3_KEYBIND_FLAG_KEY_PRESS, + TREELAND_SHORTCUT_MANAGER_V3_ACTION_NOTIFY); + if (wl_display_roundtrip(connection.display) < 0 || client.bind_failure) + goto failed; + stage = 5; + send_key(virtual_keyboard, 60, WL_KEYBOARD_KEY_STATE_PRESSED); // KEY_F2 + if (wl_display_roundtrip(connection.display) < 0 || client.activated != 1 + || strcmp(client.activated_name, "desktop-shortcut") != 0 + || client.activated_flags != TREELAND_SHORTCUT_MANAGER_V3_KEYBIND_FLAG_KEY_PRESS) + goto failed; + stage = 6; + + treeland_shortcut_capture_v3_destroy(capture); + zwp_virtual_keyboard_v1_destroy(virtual_keyboard); + wl_keyboard_destroy(seat_keyboard); + treeland_shortcut_manager_v3_destroy(manager); + wl_seat_destroy(seat); + xdg_toplevel_client_destroy(&toplevel); + client_disconnect(&connection); + return 0; + +failed: + fprintf(stderr, + "shortcut desktop failure at stage %d: wrapper=%d workspace=%d visible=%d focus=%d " + "captured=%d key=%s failed=%d bind_failure=%d activated=%d name=%s flags=%u\n", + stage, state.wrapper_created, state.wrapper_in_workspace, state.wrapper_visible, + state.keyboard_focused, client.captured, client.captured_key, client.capture_failed, + client.bind_failure, client.activated, client.activated_name, + client.activated_flags); + if (capture) treeland_shortcut_capture_v3_destroy(capture); + if (virtual_keyboard) zwp_virtual_keyboard_v1_destroy(virtual_keyboard); + if (seat_keyboard) wl_keyboard_destroy(seat_keyboard); + if (manager) treeland_shortcut_manager_v3_destroy(manager); + if (seat) wl_seat_destroy(seat); + xdg_toplevel_client_destroy(&toplevel); + client_disconnect(&connection); + return 1; +} diff --git a/tests/protocols/treeland-shortcut-manager-desktop-v3/treeland-shortcut-manager-desktop-v3.h b/tests/protocols/treeland-shortcut-manager-desktop-v3/treeland-shortcut-manager-desktop-v3.h new file mode 100644 index 0000000000..77156c96a0 --- /dev/null +++ b/tests/protocols/treeland-shortcut-manager-desktop-v3/treeland-shortcut-manager-desktop-v3.h @@ -0,0 +1,21 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +struct shortcut_desktop_state { + int wrapper_created; + int wrapper_in_workspace; + int wrapper_visible; + int keyboard_focused; +}; + +int protocol_test_run(const char *socket_name); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/treeland-shortcut-manager-v3/CMakeLists.txt b/tests/protocols/treeland-shortcut-manager-v3/CMakeLists.txt new file mode 100644 index 0000000000..c00e5f8752 --- /dev/null +++ b/tests/protocols/treeland-shortcut-manager-v3/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_shortcut_manager_v3 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-shortcut-manager-unstable-v3.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-shortcut-manager-v3.c" +) diff --git a/tests/protocols/treeland-shortcut-manager-v3/README.md b/tests/protocols/treeland-shortcut-manager-v3/README.md new file mode 100644 index 0000000000..136db9deb3 --- /dev/null +++ b/tests/protocols/treeland-shortcut-manager-v3/README.md @@ -0,0 +1,53 @@ +# `treeland-shortcut-manager-v3` 测试规范 + +## 范围 + +- 测试源码:`tests/protocols/treeland-shortcut-manager-v3/`、`tests/protocols/treeland-shortcut-manager-desktop-v3/` +- Fixture:协议 fixture;包含 mapped、聚焦 xdg-toplevel 和上游 `zwp_virtual_keyboard_v1` 的 desktop fixture。 +- 覆盖等级:desktop 用例为 **E**;基础 manager 用例为 **P**。 + +## 实际请求与预期结果 + +| 场景 | 客户端发送 | 生产业务逻辑与断言 | +| --- | --- | --- | +| 即时绑定 | `acquire`、`bind_key` | 活动 session 的 manager 立即注册绑定;成功时不发送事件,客户端通过 `wl_display.sync` 确认 | +| 名称冲突 | `bind_key`(重复名称、不同按键) | manager 发送 `bind_failure` 事件,error 为 `name_conflict` | +| 捕获快捷键 | 对已聚焦 mapped 窗口调用 `capture_next_shortcut`,先按下再释放 Ctrl 清空修饰键状态,随后虚拟键盘单独发送 evdev `KEY_F1` press/release | 生产 capture filter 将无修饰键的单键捕获为 `captured("F1")` | +| 激活快捷键 | 注册 F2 的 Notify action(即时生效),虚拟键盘发送 evdev `KEY_F2` press | `ShortcutRunner` 发送 `activated("desktop-shortcut", key-press)` | + +## v3 协议变更要点 + +1. **commit 机制移除**:`bind_key`、`bind_swipe_gesture`、`bind_hold_gesture` 立即生效,无需 `commit`。 +2. **bind_failure 事件**:绑定失败时逐条发送 `bind_failure` 事件,不影响同批次其他绑定。 +3. **action 枚举重编号**:`notify` 从 1→0,所有条目下移 1。 +4. **接口版本重置为 1**:客户端绑定版本为 1。 +5. **接口重命名**:`treeland_shortcut_manager_v3`、`treeland_shortcut_capture_v3`。 + +## 已证明的生产链路 + +客户端 map xdg-toplevel 后,服务端调用 `Helper::activateSurface()` 聚焦它,并逐项断言 +真实 wrapper 已加入 `Workspace`、可见,且 `WSeat::keyboardFocusSurface()` 正是该窗口 +的 `WSurface`。客户端通过上游 `zwp_virtual_keyboard_manager_v1` 为该 `wl_seat` 创建 +virtual keyboard,先发送 XKB keymap,再发送 Ctrl 与 Shift 的 depressed modifier mask。 + +接着客户端发送 `acquire()` 和 `capture_next_shortcut(toplevel.surface, seat)`,再发送 +evdev `KEY_F1`(键码 59)按下。生产 `WInputMethodHelper` 将 virtual keyboard 附着到 +`WSeat`;键盘事件进入 `Helper::beforeDisposeEvent()`,由于 capture active,进入 +`ShortcutManagerV3::tryHandleCaptureEvent()`。该函数把真实 `QKeyEvent` 规范化为 +`F1`,通过 capture resource 发送 `captured`;测试断言仅收到一次,随后 +发送 `KEY_F1` release 验证 drain 路径不会产生额外结果。 + +然后客户端发送 `bind_key("desktop-shortcut", "F2", KEY_PRESS, NOTIFY)`,由于 v3 立即 +生效,断言 `bind_failure==0`。发送 evdev `KEY_F2`(键码 60)按下后,事件经过同一个 +`WSeat → Helper::beforeDisposeEvent → ShortcutController` 路径,`ShortcutRunner` 执行 +`NOTIFY` 并由 manager 向 active session 客户端发送 `activated("desktop-shortcut", KEY_PRESS)`。 +测试逐项断言 name、flags 和计数均匹配。 + +## 未覆盖 + +这是虚拟输入的语义覆盖,不是物理键盘驱动覆盖。desktop 用例必须在本地通过后, +才能把上述结果标为该提交的执行证据。 + +当前基础 fixture 的客户端连接活动 Session socket。后台 Session 的即时绑定、同名绑定隔离、 +upsert 后解绑和切换保留绑定由 `session-isolation` 双连接用例补充,新增断言尚未运行。 +生产实现使用每个 Session 独立的 manager 和 controller,不再暂存后台绑定或在切换时回放。 diff --git a/tests/protocols/treeland-shortcut-manager-v3/setup.cpp b/tests/protocols/treeland-shortcut-manager-v3/setup.cpp new file mode 100644 index 0000000000..ab92bf8a47 --- /dev/null +++ b/tests/protocols/treeland-shortcut-manager-v3/setup.cpp @@ -0,0 +1,16 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +// +// Server-side fixture for the treeland-shortcut-manager-v3 protocol test. + +#include "modules/shortcut/shortcutmanager.h" +#include "server-bridge.h" + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +void protocol_test_setup(WaylandServer *server) +{ + Q_ASSERT(find_server_interface(server)); +} diff --git a/tests/protocols/treeland-shortcut-manager-v3/treeland-shortcut-manager-v3.c b/tests/protocols/treeland-shortcut-manager-v3/treeland-shortcut-manager-v3.c new file mode 100644 index 0000000000..c459f83eda --- /dev/null +++ b/tests/protocols/treeland-shortcut-manager-v3/treeland-shortcut-manager-v3.c @@ -0,0 +1,247 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-shortcut-manager-v3.h" +#include "treeland-shortcut-manager-unstable-v3-client-protocol.h" + +#include +#include +#include +#include + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); +}; + +void test_init(struct test_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); + ctx->result_cap = 32; + ctx->results = calloc(ctx->result_cap, sizeof(*ctx->results)); +} + +void test_destroy(struct test_ctx *ctx) +{ + free(ctx->results); + memset(ctx, 0, sizeof(*ctx)); +} + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +void test_pass(struct test_ctx *ctx, int index) +{ + ctx->results[index].failed = 0; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +static void bind_failure(void *data, struct treeland_shortcut_manager_v3 *manager, + const char *name, uint32_t error) +{ + (void)manager; + struct test_ctx *ctx = data; + ctx->bind_failure_received = 1; + ctx->bind_failure_error = error; + if (name) { + strncpy(ctx->bind_failure_name, name, sizeof(ctx->bind_failure_name) - 1); + ctx->bind_failure_name[sizeof(ctx->bind_failure_name) - 1] = '\0'; + } +} + +static const struct treeland_shortcut_manager_v3_listener manager_listener = { + .activated = NULL, + .bind_failure = bind_failure, +}; + +static void capture_captured(void *data, struct treeland_shortcut_capture_v3 *capture, + const char *key) +{ + (void)capture; + struct test_ctx *ctx = data; + ctx->capture_captured_received = 1; + if (key) { + strncpy(ctx->capture_captured_key, key, sizeof(ctx->capture_captured_key) - 1); + ctx->capture_captured_key[sizeof(ctx->capture_captured_key) - 1] = '\0'; + } +} + +static void capture_failed(void *data, struct treeland_shortcut_capture_v3 *capture, + uint32_t reason) +{ + (void)capture; + struct test_ctx *ctx = data; + ctx->capture_failed_received = 1; + ctx->capture_failed_reason = reason; +} + +static const struct treeland_shortcut_capture_v3_listener capture_listener = { + .captured = capture_captured, + .failed = capture_failed, +}; + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->display = ctx->connection.display; + ctx->compositor = client_bind(&ctx->connection, "wl_compositor", &wl_compositor_interface, 1); + ctx->manager = client_bind(&ctx->connection, "treeland_shortcut_manager_v3", + &treeland_shortcut_manager_v3_interface, 1); + if (!ctx->manager) + return 0; + treeland_shortcut_manager_v3_add_listener(ctx->manager, &manager_listener, ctx); + return 1; +} + +static int bind_manager(struct test_ctx *ctx) { return ctx->manager != NULL; } + +static int acquire(struct test_ctx *ctx) +{ + treeland_shortcut_manager_v3_acquire(ctx->manager); + return 1; +} + +static int bind_key(struct test_ctx *ctx) +{ + ctx->bind_failure_received = 0; + treeland_shortcut_manager_v3_bind_key(ctx->manager, "test-shortcut", "Ctrl+Alt+T", + TREELAND_SHORTCUT_MANAGER_V3_KEYBIND_FLAG_KEY_PRESS + | TREELAND_SHORTCUT_MANAGER_V3_KEYBIND_FLAG_REPEAT, + TREELAND_SHORTCUT_MANAGER_V3_ACTION_NOTIFY); + return 1; +} + +static int bind_key_succeeded(struct test_ctx *ctx) { return !ctx->bind_failure_received; } + +static int bind_key_duplicate(struct test_ctx *ctx) +{ + ctx->bind_failure_received = 0; + treeland_shortcut_manager_v3_bind_key(ctx->manager, "test-shortcut", "Ctrl+Alt+T", + TREELAND_SHORTCUT_MANAGER_V3_KEYBIND_FLAG_KEY_PRESS, + TREELAND_SHORTCUT_MANAGER_V3_ACTION_NOTIFY); + return 1; +} + +static int bind_key_duplicate_succeeded(struct test_ctx *ctx) +{ + // Upsert on same trigger: no bind_failure expected. + return !ctx->bind_failure_received; +} + +static int bind_key_name_conflict(struct test_ctx *ctx) +{ + ctx->bind_failure_received = 0; + treeland_shortcut_manager_v3_bind_key(ctx->manager, "test-shortcut", "Ctrl+Alt+S", + TREELAND_SHORTCUT_MANAGER_V3_KEYBIND_FLAG_KEY_PRESS, + TREELAND_SHORTCUT_MANAGER_V3_ACTION_NOTIFY); + return 1; +} + +static int bind_key_name_conflict_failed(struct test_ctx *ctx) +{ + return ctx->bind_failure_received + && ctx->bind_failure_error == TREELAND_SHORTCUT_MANAGER_V3_BIND_ERROR_NAME_CONFLICT; +} + +static int capture_request(struct test_ctx *ctx) +{ + ctx->capture_failed_received = 0; + ctx->capture_captured_received = 0; + if (!ctx->compositor) + return 0; + ctx->test_surface = wl_compositor_create_surface(ctx->compositor); + if (!ctx->test_surface) + return 0; + ctx->capture = treeland_shortcut_manager_v3_capture_next_shortcut(ctx->manager, + ctx->test_surface, NULL); + if (!ctx->capture) + return 0; + treeland_shortcut_capture_v3_add_listener(ctx->capture, &capture_listener, ctx); + return 1; +} + +static int capture_failed_not_active(struct test_ctx *ctx) +{ + + return ctx->capture_failed_received + && ctx->capture_failed_reason == TREELAND_SHORTCUT_CAPTURE_V3_FAILED_REASON_NOT_ACTIVE + && !ctx->capture_captured_received; +} + +static const struct test_case cases[] = { + { "manager.bind", bind_manager }, + { "manager.acquire", acquire }, + { "manager.bind_key", bind_key }, + { "event.no_bind_failure", bind_key_succeeded }, + { "manager.bind_key_upsert", bind_key_duplicate }, + { "event.no_bind_failure_upsert", bind_key_duplicate_succeeded }, + { "manager.bind_key_name_conflict", bind_key_name_conflict }, + { "event.bind_failure_name_conflict", bind_key_name_conflict_failed }, + { "capture.request", capture_request }, + { "event.capture_failed_not_active", capture_failed_not_active }, +}; + +void test_cleanup(struct test_ctx *ctx) +{ + if (ctx->capture) treeland_shortcut_capture_v3_destroy(ctx->capture); + if (ctx->test_surface) wl_surface_destroy(ctx->test_surface); + if (ctx->manager) treeland_shortcut_manager_v3_destroy(ctx->manager); + client_disconnect(&ctx->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx; + test_init(&ctx); + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect to or bind treeland_shortcut_manager_v3\n"); + test_cleanup(&ctx); + test_destroy(&ctx); + return 1; + } + + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const int result = test_add(&ctx, cases[i].name); + if (!cases[i].run(&ctx)) + test_fail(&ctx, result, "assertion failed"); + if (wl_display_roundtrip(ctx.display) < 0) + test_fail(&ctx, result, "Wayland connection failed"); + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + test_destroy(&ctx); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-shortcut-manager-v3/treeland-shortcut-manager-v3.h b/tests/protocols/treeland-shortcut-manager-v3/treeland-shortcut-manager-v3.h new file mode 100644 index 0000000000..1608903f19 --- /dev/null +++ b/tests/protocols/treeland-shortcut-manager-v3/treeland-shortcut-manager-v3.h @@ -0,0 +1,57 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef TREELAND_SHORTCUT_MANAGER_V3_TEST_H +#define TREELAND_SHORTCUT_MANAGER_V3_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +#include "client-connection.h" + +#define TEST_MSG_MAX 256 + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +struct test_ctx { + struct client_connection connection; + struct wl_display *display; + + struct wl_compositor *compositor; + + struct treeland_shortcut_manager_v3 *manager; + struct treeland_shortcut_capture_v3 *capture; + struct wl_surface *test_surface; + + int bind_failure_received; + char bind_failure_name[64]; + uint32_t bind_failure_error; + int capture_captured_received; + char capture_captured_key[64]; + int capture_failed_received; + uint32_t capture_failed_reason; + + struct test_result *results; + int result_count; + int result_cap; +}; + +void test_init(struct test_ctx *ctx); +void test_destroy(struct test_ctx *ctx); +int test_add(struct test_ctx *ctx, const char *name); +void test_fail(struct test_ctx *ctx, int idx, const char *fmt, ...); +void test_pass(struct test_ctx *ctx, int idx); + +int test_print_results(struct test_ctx *ctx); +void test_cleanup(struct test_ctx *ctx); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-wallpaper-color-v1/CMakeLists.txt b/tests/protocols/treeland-wallpaper-color-v1/CMakeLists.txt new file mode 100644 index 0000000000..12bd625af5 --- /dev/null +++ b/tests/protocols/treeland-wallpaper-color-v1/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_wallpaper_color_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wallpaper-color-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-wallpaper-color-v1.c" +) diff --git a/tests/protocols/treeland-wallpaper-color-v1/README.md b/tests/protocols/treeland-wallpaper-color-v1/README.md new file mode 100644 index 0000000000..c3ea3a0486 --- /dev/null +++ b/tests/protocols/treeland-wallpaper-color-v1/README.md @@ -0,0 +1,22 @@ +# `treeland-wallpaper-color-v1` 测试规范 + +## 范围 + +- 测试源码:`tests/protocols/treeland-wallpaper-color-v1/` +- Fixture:由服务端测试回调提供颜色的协议 fixture。 +- 覆盖等级:**I**。 + +## 实际请求与预期结果 + +| 场景 | 客户端发送 | 生产业务逻辑与断言 | +| --- | --- | --- | +| 订阅 | 绑定 manager | 客户端收到选择输出的当前颜色状态 | +| 更新与去重 | fixture 注入颜色变化 | 生产订阅层仅为真实变化发送一次颜色通知 | + +## 已证明的生产链路 + +验证 production subscription/notification 层及其去重行为。 + +## 未覆盖 + +颜色由 fixture 直接注入;未经过壁纸分析,也未验证 output 色彩应用。 diff --git a/tests/protocols/treeland-wallpaper-color-v1/setup.cpp b/tests/protocols/treeland-wallpaper-color-v1/setup.cpp new file mode 100644 index 0000000000..62414c2d4b --- /dev/null +++ b/tests/protocols/treeland-wallpaper-color-v1/setup.cpp @@ -0,0 +1,26 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "modules/wallpaper-color/wallpapercolorinterfacev1.h" +#include "server-bridge.h" + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +WallpaperColorInterfaceV1 *g_manager = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + g_manager = find_server_interface(server); +} + +extern "C" void wallpaper_color_set_color(const char *output, int is_dark) +{ + if (!g_manager) + return; + g_manager->updateWallpaperColor(QString::fromUtf8(output), is_dark != 0); +} diff --git a/tests/protocols/treeland-wallpaper-color-v1/treeland-wallpaper-color-v1.c b/tests/protocols/treeland-wallpaper-color-v1/treeland-wallpaper-color-v1.c new file mode 100644 index 0000000000..3472556dd4 --- /dev/null +++ b/tests/protocols/treeland-wallpaper-color-v1/treeland-wallpaper-color-v1.c @@ -0,0 +1,194 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-wallpaper-color-v1.h" +#include "server-bridge-api.h" +#include "treeland-wallpaper-color-v1-client-protocol.h" + +#include +#include +#include +#include + +extern void wallpaper_color_set_color(const char *output, int is_dark); + +struct wallpaper_color_update_args { + const char *output; + int is_dark; +}; + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); +}; + +void test_init(struct test_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); + ctx->result_cap = 32; + ctx->results = calloc(ctx->result_cap, sizeof(*ctx->results)); +} + +void test_destroy(struct test_ctx *ctx) +{ + free(ctx->results); + memset(ctx, 0, sizeof(*ctx)); +} + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +void test_pass(struct test_ctx *ctx, int index) +{ + ctx->results[index].failed = 0; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +static void output_color(void *data, struct treeland_wallpaper_color_manager_v1 *manager, + const char *output, uint32_t isdark) +{ + (void)manager; + struct test_ctx *ctx = data; + ctx->output_color_count++; + ctx->output_color_isdark = (int)isdark; + snprintf(ctx->output_color_name, sizeof(ctx->output_color_name), "%s", output); +} + +static const struct treeland_wallpaper_color_manager_v1_listener manager_listener = { + .output_color = output_color, +}; + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->display = ctx->connection.display; + ctx->manager = client_bind(&ctx->connection, "treeland_wallpaper_color_manager_v1", + &treeland_wallpaper_color_manager_v1_interface, 1); + if (!ctx->manager) + return 0; + treeland_wallpaper_color_manager_v1_add_listener(ctx->manager, &manager_listener, ctx); + return 1; +} + +static void set_color_callback(void *data) +{ + struct wallpaper_color_update_args *args = data; + wallpaper_color_set_color(args->output, args->is_dark); +} + +static int set_color(struct test_ctx *ctx, const char *output, int is_dark) +{ + (void)ctx; + struct wallpaper_color_update_args args = { .output = output, .is_dark = is_dark }; + return invoke_on_server_thread(set_color_callback, &args); +} + +static int set_color_dark(struct test_ctx *ctx) { return set_color(ctx, "test-output", 1); } +static int set_color_light(struct test_ctx *ctx) { return set_color(ctx, "test-output", 0); } +static int watch(struct test_ctx *ctx) +{ + treeland_wallpaper_color_manager_v1_watch(ctx->manager, "test-output"); + return 1; +} +static int watch_unknown(struct test_ctx *ctx) +{ + treeland_wallpaper_color_manager_v1_watch(ctx->manager, "never-set-output"); + return 1; +} +static int unwatch(struct test_ctx *ctx) +{ + treeland_wallpaper_color_manager_v1_unwatch(ctx->manager, "test-output"); + return 1; +} +static int immediate_event_received(struct test_ctx *ctx) +{ + return ctx->output_color_count == 1 && ctx->output_color_isdark == 1 && + strcmp(ctx->output_color_name, "test-output") == 0; +} +static int no_duplicate_event(struct test_ctx *ctx) { return ctx->output_color_count == 1; } +static int changed_event_received(struct test_ctx *ctx) +{ + return ctx->output_color_count == 2 && ctx->output_color_isdark == 0 && + strcmp(ctx->output_color_name, "test-output") == 0; +} +static int unknown_output_ignored(struct test_ctx *ctx) { return ctx->output_color_count == 2; } +static int no_event_after_unwatch(struct test_ctx *ctx) { return ctx->output_color_count == 2; } + +static const struct test_case cases[] = { + { "server.set_color_dark", set_color_dark }, + { "manager.watch", watch }, + { "event.output_color.immediate", immediate_event_received }, + { "server.set_color_same_value", set_color_dark }, + { "event.no_duplicate_same_color", no_duplicate_event }, + { "server.set_color_light", set_color_light }, + { "event.output_color.changed", changed_event_received }, + { "manager.watch_unknown_output", watch_unknown }, + { "event.ignored_unknown_output", unknown_output_ignored }, + { "manager.unwatch", unwatch }, + { "server.set_color_after_unwatch", set_color_dark }, + { "event.no_event_after_unwatch", no_event_after_unwatch }, +}; + +void test_cleanup(struct test_ctx *ctx) +{ + if (ctx->manager) + treeland_wallpaper_color_manager_v1_destroy(ctx->manager); + client_disconnect(&ctx->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx; + test_init(&ctx); + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect to or bind treeland_wallpaper_color_manager_v1\n"); + test_cleanup(&ctx); + test_destroy(&ctx); + return 1; + } + + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const int result = test_add(&ctx, cases[i].name); + if (!cases[i].run(&ctx)) + test_fail(&ctx, result, "assertion failed"); + if (wl_display_roundtrip(ctx.display) < 0) + test_fail(&ctx, result, "Wayland connection failed"); + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + test_destroy(&ctx); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-wallpaper-color-v1/treeland-wallpaper-color-v1.h b/tests/protocols/treeland-wallpaper-color-v1/treeland-wallpaper-color-v1.h new file mode 100644 index 0000000000..cfc876752f --- /dev/null +++ b/tests/protocols/treeland-wallpaper-color-v1/treeland-wallpaper-color-v1.h @@ -0,0 +1,49 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef WALLPAPER_COLOR_TEST_H +#define WALLPAPER_COLOR_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +#include "client-connection.h" + +#define TEST_MSG_MAX 256 + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +struct test_ctx { + struct client_connection connection; + struct wl_display *display; + + struct treeland_wallpaper_color_manager_v1 *manager; + + int output_color_count; + int output_color_isdark; + char output_color_name[128]; + + struct test_result *results; + int result_count; + int result_cap; +}; + +void test_init(struct test_ctx *ctx); +void test_destroy(struct test_ctx *ctx); +int test_add(struct test_ctx *ctx, const char *name); +void test_fail(struct test_ctx *ctx, int idx, const char *fmt, ...); +void test_pass(struct test_ctx *ctx, int idx); + +int test_print_results(struct test_ctx *ctx); +void test_cleanup(struct test_ctx *ctx); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-wallpaper-desktop-v1/CMakeLists.txt b/tests/protocols/treeland-wallpaper-desktop-v1/CMakeLists.txt new file mode 100644 index 0000000000..c7cd8efd52 --- /dev/null +++ b/tests/protocols/treeland-wallpaper-desktop-v1/CMakeLists.txt @@ -0,0 +1,8 @@ + +treeland_add_protocol_test( + NAME treeland_wallpaper_desktop_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wallpaper-manager-unstable-v1.xml" + EXTRA_XMLS "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wallpaper-shell-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-wallpaper-desktop-v1.c" +) diff --git a/tests/protocols/treeland-wallpaper-desktop-v1/README.md b/tests/protocols/treeland-wallpaper-desktop-v1/README.md new file mode 100644 index 0000000000..c54614aaed --- /dev/null +++ b/tests/protocols/treeland-wallpaper-desktop-v1/README.md @@ -0,0 +1,58 @@ +# Wallpaper manager + shell 桌面联合路径测试规范 + +## 状态 + +- 测试源码:`tests/protocols/treeland-wallpaper-desktop-v1/` +- Fixture:完整生产 `WaylandServer` 与默认 headless output。 +- 覆盖等级:**P / E**。 + +这不是新增 XML;它把 `treeland-wallpaper-manager-unstable-v1` 和 +`treeland-wallpaper-shell-unstable-v1` 串成一条实际业务链。两份各自的基础测试仍保留其 +资源、事件和错误覆盖。 + +## 输入与顺序 + +测试先等待真实 `TreelandUserConfig` 初始化完成。该生产信号先驱动 +`WallpaperManager::updateWallpaperConfig()`,为现有 output 建立 workspace wallpaper +配置;随后 desktop runner 才启动 client。这样 `set_image_source(DESKTOP)` 进入 +`WallpaperManager::setOutputWallpaper()` 时必有可更新的 output 配置,而不是依赖任意延时。 + +客户端只创建一个无 role 的 `wl_surface`,并按以下严格顺序使用它: + +1. 绑定实际存在的 `wl_output`、`treeland_wallpaper_manager_v1` 和 version 2 的 + `treeland_wallpaper_shell_v1`。 +2. 调用 `manager.get_treeland_wallpaper(output, surface)`,然后发送 + `wallpaper.set_image_source("/tmp/treeland-protocol-wallpaper-red", DESKTOP)`。 + 当前实现把该 source 写进这个 output 当前 workspace 的生产 + `WallpaperManager` 配置。 +3. 用**同一个** `wl_surface` 调用 + `shell.get_treeland_wallpaper_surface(surface, source)`,从而创建真正的 + `TreelandWallpaperSurfaceInterfaceV1`,而不是建立独立的测试 surface。 +4. 创建 `64×64`、`wl_shm/ARGB8888` buffer,并将其 attach/damage/commit 到该 wallpaper + surface,最后发送 `wallpaper_surface.ready()`。 +5. 通过 `wl_display_roundtrip()` 确认服务端已按请求顺序处理;测试不以时间延迟判断状态。 + +这里的路径标识符不是待解码 JPEG 文件。它用于验证 manager 配置与 wallpaper shell 的资源 +关联。`TreelandWallpaperSurfaceInterfaceV1` 创建的 surface 没有 xdg/layer shell role, +因此本测试不会把 buffer commit 当成 mapped、ready 或 QML 可见的证据;映射必须由实际的 +wallpaper owner 负责,不能由该协议资源补做。 + +## 必须观察到的生产结果 + +服务端同步读取生产对象时,以下结果必须同时成立: + +| 检查 | 生产对象/结果 | +| --- | --- | +| shell 注册 | `TreelandWallpaperSurfaceInterfaceV1::get(source)` 返回刚创建的对象 | +| manager 关联 | `TreelandWallpaperInterfaceV1::getReferenceWallpaperInterfaceFromSurface(surface)` 返回对象,并能得到同一个真实 `WOutput` | +| 配置写入 | `WaylandServer::currentWorkspaceWallpaper(output)` 等于客户端发送的 source | + +因此通过条件是 manager 写入配置且与同一 shell surface/output 建立生产关联;不把 role-less +surface 的映射或最终 QML 内容当作该协议的行为。 + +## 已知边界 + +- 尚未覆盖实际 wallpaper owner 对该 surface 的映射、`ready` 完成、QML 接入或最终 output + backing buffer,因此尚未达到 V 级。 +- 未覆盖 JPEG/视频文件校验、解码失败、notifier 的真实来源,也未覆盖锁屏 role、跨 workspace + 切换和淡入淡出动画完成。 diff --git a/tests/protocols/treeland-wallpaper-desktop-v1/setup.cpp b/tests/protocols/treeland-wallpaper-desktop-v1/setup.cpp new file mode 100644 index 0000000000..f2f27b1b34 --- /dev/null +++ b/tests/protocols/treeland-wallpaper-desktop-v1/setup.cpp @@ -0,0 +1,55 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "modules/wallpaper/wallpapermanagerinterfacev1.h" +#include "modules/wallpaper/wallpapershellinterfacev1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "treelanduserconfig.hpp" +#include "treeland-wallpaper-desktop-v1.h" +namespace { +constexpr auto kWallpaperSource = "/tmp/treeland-protocol-wallpaper-red"; +} + +void protocol_test_setup([[maybe_unused]] WaylandServer *server) +{ + // The desktop fixture already owns one headless output. Keeping that + // single output makes the client's wl_output and the active QML output + // unambiguous for this manager + shell integration path. +} + +extern "C" bool protocol_test_ready(WaylandServer *server) +{ + auto *config = server->config(); +#if TREELANDUSERCONFIG_DCONFIG_FILE_VERSION_MINOR > 0 + return config && config->isInitializeSucceeded(); +#else + return config && config->isInitializeSucceed(); +#endif +} + +extern "C" void wallpaper_desktop_read_state(void *data) +{ + wallpaper_desktop_state state {}; + auto *server = WaylandServer::instance(); + auto *shellSurface = TreelandWallpaperSurfaceInterfaceV1::get( + QString::fromLatin1(kWallpaperSource)); + state.shell_surface_registered = shellSurface ? 1 : 0; + if (!shellSurface) { + *static_cast(data) = state; + return; + } + + auto *surface = shellSurface->wSurface(); + + auto *managerWallpaper = + TreelandWallpaperInterfaceV1::getReferenceWallpaperInterfaceFromSurface(surface); + state.manager_reference_matched = managerWallpaper ? 1 : 0; + auto *output = managerWallpaper ? managerWallpaper->wOutput() : nullptr; + state.output_matched = output ? 1 : 0; + state.manager_configured = output + && server->currentWorkspaceWallpaper(output) == QString::fromLatin1(kWallpaperSource) + ? 1 + : 0; + + *static_cast(data) = state; +} diff --git a/tests/protocols/treeland-wallpaper-desktop-v1/treeland-wallpaper-desktop-v1.c b/tests/protocols/treeland-wallpaper-desktop-v1/treeland-wallpaper-desktop-v1.c new file mode 100644 index 0000000000..3884c3a07e --- /dev/null +++ b/tests/protocols/treeland-wallpaper-desktop-v1/treeland-wallpaper-desktop-v1.c @@ -0,0 +1,167 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 200809L +#endif + +#include "client-connection.h" +#include "server-bridge-api.h" +#include "treeland-wallpaper-desktop-v1.h" +#include "treeland-wallpaper-manager-unstable-v1-client-protocol.h" +#include "treeland-wallpaper-shell-unstable-v1-client-protocol.h" + +#include +#include +#include +#include +#include +#include + +extern void wallpaper_desktop_read_state(void *data); + +static const char wallpaper_source[] = "/tmp/treeland-protocol-wallpaper-red"; + +struct wallpaper_client { + struct client_connection connection; + struct wl_compositor *compositor; + struct wl_shm *shm; + struct wl_output *output; + struct treeland_wallpaper_manager_v1 *manager; + struct treeland_wallpaper_shell_v1 *shell; + struct treeland_wallpaper_v1 *wallpaper; + struct treeland_wallpaper_surface_v1 *wallpaper_surface; + struct wl_surface *surface; + struct wl_buffer *buffer; + void *buffer_data; + size_t buffer_size; +}; + +static int create_red_buffer(struct wallpaper_client *client) +{ + enum { width = 64, height = 64, stride = width * 4 }; + const size_t size = (size_t)stride * height; + char name[64]; + snprintf(name, sizeof(name), "/treeland_wallpaper_%d", (int)getpid()); + const int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); + if (fd < 0) + return 0; + shm_unlink(name); + if (ftruncate(fd, (off_t)size) < 0) { + close(fd); + return 0; + } + client->buffer_data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (client->buffer_data == MAP_FAILED) { + client->buffer_data = NULL; + close(fd); + return 0; + } + for (size_t i = 0; i < size / sizeof(uint32_t); ++i) + ((uint32_t *)client->buffer_data)[i] = 0xffff0000u; + + struct wl_shm_pool *pool = wl_shm_create_pool(client->shm, fd, (int)size); + close(fd); + if (!pool) + return 0; + client->buffer = wl_shm_pool_create_buffer(pool, 0, width, height, stride, + WL_SHM_FORMAT_ARGB8888); + wl_shm_pool_destroy(pool); + if (!client->buffer) + return 0; + client->buffer_size = size; + return 1; +} + +static void cleanup(struct wallpaper_client *client) +{ + if (client->wallpaper_surface) + treeland_wallpaper_surface_v1_destroy(client->wallpaper_surface); + if (client->wallpaper) + treeland_wallpaper_v1_destroy(client->wallpaper); + if (client->shell) + treeland_wallpaper_shell_v1_destroy(client->shell); + if (client->manager) + treeland_wallpaper_manager_v1_destroy(client->manager); + if (client->buffer) + wl_buffer_destroy(client->buffer); + if (client->surface) + wl_surface_destroy(client->surface); + if (client->buffer_data) + munmap(client->buffer_data, client->buffer_size); + client_disconnect(&client->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct wallpaper_client client = { 0 }; + struct wallpaper_desktop_state state = { 0 }; + int result = 1; + const char *stage = "connect"; + + if (!client_connect(&client.connection, socket_name)) + goto done; + stage = "bind"; + client.compositor = client_bind(&client.connection, "wl_compositor", + &wl_compositor_interface, 1); + client.shm = client_bind(&client.connection, "wl_shm", &wl_shm_interface, 1); + client.output = client_bind(&client.connection, "wl_output", &wl_output_interface, 1); + client.manager = client_bind(&client.connection, "treeland_wallpaper_manager_v1", + &treeland_wallpaper_manager_v1_interface, 1); + client.shell = client_bind(&client.connection, "treeland_wallpaper_shell_v1", + &treeland_wallpaper_shell_v1_interface, 1); + if (!client.compositor || !client.shm || !client.output || !client.manager || !client.shell) + goto done; + + stage = "create-surface-buffer"; + client.surface = wl_compositor_create_surface(client.compositor); + if (!client.surface || !create_red_buffer(&client)) + goto done; + + stage = "manager-wallpaper"; + client.wallpaper = treeland_wallpaper_manager_v1_get_treeland_wallpaper( + client.manager, client.output, client.surface); + if (!client.wallpaper) + goto done; + treeland_wallpaper_v1_set_image_source( + client.wallpaper, wallpaper_source, TREELAND_WALLPAPER_V1_WALLPAPER_ROLE_DESKTOP); + + stage = "shell-wallpaper"; + client.wallpaper_surface = treeland_wallpaper_shell_v1_get_treeland_wallpaper_surface( + client.shell, client.surface, wallpaper_source); + if (!client.wallpaper_surface) + goto done; + wl_surface_attach(client.surface, client.buffer, 0, 0); + // wl_compositor is intentionally bound at v1, so the wl_surface is also + // v1. damage_buffer is since v4; use the v1 damage request instead. + wl_surface_damage(client.surface, 0, 0, 64, 64); + wl_surface_commit(client.surface); + treeland_wallpaper_surface_v1_ready(client.wallpaper_surface); + + // Wayland roundtrip is the ordering barrier for manager configuration and + // wallpaper-shell registration. Mapping remains the responsibility of the + // production wallpaper owner, not this role-less client surface. + stage = "roundtrip-or-server-state"; + if (wl_display_roundtrip(client.connection.display) < 0 + || !invoke_on_server_thread(wallpaper_desktop_read_state, &state)) + goto done; + + stage = "production-wallpaper-result"; + if (state.shell_surface_registered && state.manager_reference_matched + && state.output_matched && state.manager_configured) + result = 0; + +done: + if (result != 0) { + fprintf(stderr, + "wallpaper desktop failed at %s: shell=(registered=%d) " + "manager=(reference=%d output=%d configured=%d) " + "\n", + stage, + state.shell_surface_registered, + state.manager_reference_matched, + state.output_matched, + state.manager_configured); + } + cleanup(&client); + return result; +} diff --git a/tests/protocols/treeland-wallpaper-desktop-v1/treeland-wallpaper-desktop-v1.h b/tests/protocols/treeland-wallpaper-desktop-v1/treeland-wallpaper-desktop-v1.h new file mode 100644 index 0000000000..95fdce0672 --- /dev/null +++ b/tests/protocols/treeland-wallpaper-desktop-v1/treeland-wallpaper-desktop-v1.h @@ -0,0 +1,21 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +struct wallpaper_desktop_state { + int shell_surface_registered; + int manager_reference_matched; + int output_matched; + int manager_configured; +}; + +int protocol_test_run(const char *socket_name); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/treeland-wallpaper-manager-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-wallpaper-manager-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..8bd5b70946 --- /dev/null +++ b/tests/protocols/treeland-wallpaper-manager-unstable-v1/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_wallpaper_manager_unstable_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wallpaper-manager-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-wallpaper-manager-unstable-v1.c" +) diff --git a/tests/protocols/treeland-wallpaper-manager-unstable-v1/README.md b/tests/protocols/treeland-wallpaper-manager-unstable-v1/README.md new file mode 100644 index 0000000000..fec38aa4f5 --- /dev/null +++ b/tests/protocols/treeland-wallpaper-manager-unstable-v1/README.md @@ -0,0 +1,25 @@ +# `treeland-wallpaper-manager-unstable-v1` 测试规范 + +## 范围 + +- 测试源码:`tests/protocols/treeland-wallpaper-manager-unstable-v1/` +- Fixture:启动 headless backend、创建真实 `wl_output` 的协议 fixture。 +- 覆盖等级:**I/P**。 + +## 实际请求与预期结果 + +| 场景 | 客户端发送 | 生产业务逻辑与断言 | +| --- | --- | --- | +| 创建资源 | 为真实 output 与 `wl_surface` 创建 wallpaper 对象 | production manager 记录两个 wallpaper 资源 | +| 状态事件 | 进入 failed/changed 服务端路径 | 客户端收到相应协议事件 | + +## 已证明的生产链路 + +覆盖真实 output 绑定和 production manager 的 wallpaper 资源生命周期。 + +## 未覆盖 + +基础测试没有发送 image/video source,也没有 wallpaper item 或 output 像素断言;它本身 +不能证明壁纸真的被应用。manager 的 `set_image_source` 与 shell 的实际应用路径已由 +[`wallpaper-desktop-v1`](../treeland-wallpaper-desktop-v1/README.md) 通过;仍未覆盖文件解码与最终 output +像素。 diff --git a/tests/protocols/treeland-wallpaper-manager-unstable-v1/setup.cpp b/tests/protocols/treeland-wallpaper-manager-unstable-v1/setup.cpp new file mode 100644 index 0000000000..6e15398d6f --- /dev/null +++ b/tests/protocols/treeland-wallpaper-manager-unstable-v1/setup.cpp @@ -0,0 +1,56 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "modules/wallpaper/wallpapermanagerinterfacev1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "treeland-wallpaper-manager-unstable-v1.h" + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +TreelandWallpaperInterfaceV1 *g_wallpaper = nullptr; +TreelandWallpaperInterfaceV1 *g_wallpaper2 = nullptr; + +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + auto *manager = find_server_interface(server); + Q_ASSERT(manager); + QObject::connect(manager, &TreelandWallpaperManagerInterfaceV1::wallpaperCreated, + [](TreelandWallpaperInterfaceV1 *wallpaper) { + if (!g_wallpaper) + g_wallpaper = wallpaper; + else if (!g_wallpaper2) + g_wallpaper2 = wallpaper; + }); +} + +extern "C" void wm_query_server_state(void *data) +{ + auto *state = static_cast(data); + state->wallpaper_created = g_wallpaper != nullptr; + state->second_created = g_wallpaper2 != nullptr; + state->output_valid = g_wallpaper && g_wallpaper->wOutput() != nullptr; + state->has_username = g_wallpaper && !g_wallpaper->userName().isEmpty(); +} + +extern "C" void wm_emit_failed(void *) +{ + if (g_wallpaper) { + g_wallpaper->sendError(WM_TEST_SOURCE, TreelandWallpaperInterfaceV1::InvalidSource); + } +} + +extern "C" void wm_emit_changed(void *) +{ + if (g_wallpaper) { + const auto roles = static_cast( + TreelandWallpaperInterfaceV1::Desktop | TreelandWallpaperInterfaceV1::Lockscreen); + g_wallpaper->sendChanged(roles, TreelandWallpaperInterfaceV1::Image, WM_TEST_SOURCE); + } +} diff --git a/tests/protocols/treeland-wallpaper-manager-unstable-v1/treeland-wallpaper-manager-unstable-v1.c b/tests/protocols/treeland-wallpaper-manager-unstable-v1/treeland-wallpaper-manager-unstable-v1.c new file mode 100644 index 0000000000..43d682e11d --- /dev/null +++ b/tests/protocols/treeland-wallpaper-manager-unstable-v1/treeland-wallpaper-manager-unstable-v1.c @@ -0,0 +1,212 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-wallpaper-manager-unstable-v1.h" +#include "server-bridge-api.h" +#include "treeland-wallpaper-manager-unstable-v1-client-protocol.h" + +#include +#include +#include +#include + +extern void wm_query_server_state(void *data); +extern void wm_emit_failed(void *data); +extern void wm_emit_changed(void *data); + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); +}; + +void test_init(struct test_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); + ctx->result_cap = 32; + ctx->results = calloc(ctx->result_cap, sizeof(*ctx->results)); +} + +void test_destroy(struct test_ctx *ctx) +{ + free(ctx->results); + memset(ctx, 0, sizeof(*ctx)); +} + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +void test_pass(struct test_ctx *ctx, int index) +{ + ctx->results[index].failed = 0; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +static void wallpaper_failed(void *data, struct treeland_wallpaper_v1 *wallpaper, + const char *file_source, uint32_t error) +{ + (void)wallpaper; + struct test_ctx *ctx = data; + ctx->failed_received = 1; + ctx->failed_error = (int)error; + snprintf(ctx->failed_source, TEST_MSG_MAX, "%s", file_source ? file_source : ""); +} + +static void wallpaper_changed(void *data, struct treeland_wallpaper_v1 *wallpaper, + uint32_t role, uint32_t source_type, const char *file_source) +{ + (void)wallpaper; + struct test_ctx *ctx = data; + ctx->changed_received = 1; + ctx->changed_role = (int)role; + ctx->changed_type = (int)source_type; + snprintf(ctx->changed_source, TEST_MSG_MAX, "%s", file_source ? file_source : ""); +} + +static const struct treeland_wallpaper_v1_listener wallpaper_listener = { + .failed = wallpaper_failed, + .changed = wallpaper_changed, +}; + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->display = ctx->connection.display; + ctx->compositor = client_bind(&ctx->connection, "wl_compositor", &wl_compositor_interface, 1); + ctx->output = client_bind(&ctx->connection, "wl_output", &wl_output_interface, 1); + ctx->manager = client_bind(&ctx->connection, "treeland_wallpaper_manager_v1", + &treeland_wallpaper_manager_v1_interface, 1); + return ctx->manager != NULL && ctx->output != NULL && ctx->compositor != NULL; +} + +static int manager_get_wallpaper(struct test_ctx *ctx) +{ + if (!ctx->compositor || !ctx->output) + return 0; + ctx->test_surface = wl_compositor_create_surface(ctx->compositor); + if (!ctx->test_surface) + return 0; + ctx->wallpaper = treeland_wallpaper_manager_v1_get_treeland_wallpaper(ctx->manager, + ctx->output, + ctx->test_surface); + if (ctx->wallpaper) + treeland_wallpaper_v1_add_listener(ctx->wallpaper, &wallpaper_listener, ctx); + return ctx->wallpaper != NULL; +} + +static int manager_get_wallpaper_null_surface(struct test_ctx *ctx) +{ + if (!ctx->output) + return 0; + ctx->wallpaper2 = treeland_wallpaper_manager_v1_get_treeland_wallpaper(ctx->manager, + ctx->output, + NULL); + if (ctx->wallpaper2) + treeland_wallpaper_v1_add_listener(ctx->wallpaper2, &wallpaper_listener, ctx); + return ctx->wallpaper2 != NULL; +} + +static int server_state_ok(struct test_ctx *ctx) +{ + (void)ctx; + struct wm_server_state state; + memset(&state, 0, sizeof(state)); + if (!invoke_on_server_thread(wm_query_server_state, &state)) + return 0; + return state.wallpaper_created && state.second_created + && state.output_valid && state.has_username; +} + +static int emit_failed(struct test_ctx *ctx) { (void)ctx; return invoke_on_server_thread(wm_emit_failed, NULL); } +static int failed_event_ok(struct test_ctx *ctx) +{ + return ctx->failed_received + && ctx->failed_error == TREELAND_WALLPAPER_V1_ERROR_INVALID_SOURCE + && strcmp(ctx->failed_source, WM_TEST_SOURCE) == 0; +} + +static int emit_changed(struct test_ctx *ctx) { (void)ctx; return invoke_on_server_thread(wm_emit_changed, NULL); } +static int changed_event_ok(struct test_ctx *ctx) +{ + return ctx->changed_received + && ctx->changed_role == (TREELAND_WALLPAPER_V1_WALLPAPER_ROLE_DESKTOP + | TREELAND_WALLPAPER_V1_WALLPAPER_ROLE_LOCKSCREEN) + && ctx->changed_type == TREELAND_WALLPAPER_V1_WALLPAPER_SOURCE_TYPE_IMAGE + && strcmp(ctx->changed_source, WM_TEST_SOURCE) == 0; +} + +static const struct test_case cases[] = { + { "manager.get_treeland_wallpaper", manager_get_wallpaper }, + { "manager.get_treeland_wallpaper_null_surface", manager_get_wallpaper_null_surface }, + { "server.state.wallpaper_created", server_state_ok }, + { "server.emit_failed", emit_failed }, + { "wallpaper.event.failed", failed_event_ok }, + { "server.emit_changed", emit_changed }, + { "wallpaper.event.changed", changed_event_ok }, +}; + +void test_cleanup(struct test_ctx *ctx) +{ + if (ctx->wallpaper2) treeland_wallpaper_v1_destroy(ctx->wallpaper2); + if (ctx->wallpaper) treeland_wallpaper_v1_destroy(ctx->wallpaper); + if (ctx->test_surface) wl_surface_destroy(ctx->test_surface); + if (ctx->manager) treeland_wallpaper_manager_v1_destroy(ctx->manager); + client_disconnect(&ctx->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx; + test_init(&ctx); + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect or bind treeland_wallpaper_manager_v1 " + "(need wl_compositor, wl_output and the manager global)\n"); + test_cleanup(&ctx); + test_destroy(&ctx); + return 1; + } + + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const int result = test_add(&ctx, cases[i].name); + if (!cases[i].run(&ctx)) + test_fail(&ctx, result, "assertion failed"); + if (wl_display_roundtrip(ctx.display) < 0) + test_fail(&ctx, result, "Wayland connection failed"); + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + test_destroy(&ctx); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-wallpaper-manager-unstable-v1/treeland-wallpaper-manager-unstable-v1.h b/tests/protocols/treeland-wallpaper-manager-unstable-v1/treeland-wallpaper-manager-unstable-v1.h new file mode 100644 index 0000000000..91f1ef89ee --- /dev/null +++ b/tests/protocols/treeland-wallpaper-manager-unstable-v1/treeland-wallpaper-manager-unstable-v1.h @@ -0,0 +1,67 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef WALLPAPER_MANAGER_TEST_H +#define WALLPAPER_MANAGER_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +#include "client-connection.h" + +#define TEST_MSG_MAX 256 +#define WM_TEST_SOURCE "/usr/share/wallpapers/deepin-wallpapers/test-wallpaper.jpg" + +struct wm_server_state { + int wallpaper_created; + int second_created; + int output_valid; + int has_username; +}; + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +struct test_ctx { + struct client_connection connection; + struct wl_display *display; + + struct wl_compositor *compositor; + struct wl_output *output; + + struct treeland_wallpaper_manager_v1 *manager; + struct treeland_wallpaper_v1 *wallpaper; + struct treeland_wallpaper_v1 *wallpaper2; + struct wl_surface *test_surface; + + int failed_received; + int failed_error; + char failed_source[TEST_MSG_MAX]; + int changed_received; + int changed_role; + int changed_type; + char changed_source[TEST_MSG_MAX]; + + struct test_result *results; + int result_count; + int result_cap; +}; + +void test_init(struct test_ctx *ctx); +void test_destroy(struct test_ctx *ctx); +int test_add(struct test_ctx *ctx, const char *name); +void test_fail(struct test_ctx *ctx, int idx, const char *fmt, ...); +void test_pass(struct test_ctx *ctx, int idx); + +int test_print_results(struct test_ctx *ctx); +void test_cleanup(struct test_ctx *ctx); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-wallpaper-shell-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-wallpaper-shell-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..87c1ad77b0 --- /dev/null +++ b/tests/protocols/treeland-wallpaper-shell-unstable-v1/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_wallpaper_shell_unstable_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wallpaper-shell-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-wallpaper-shell-unstable-v1.c" +) diff --git a/tests/protocols/treeland-wallpaper-shell-unstable-v1/README.md b/tests/protocols/treeland-wallpaper-shell-unstable-v1/README.md new file mode 100644 index 0000000000..6729856dad --- /dev/null +++ b/tests/protocols/treeland-wallpaper-shell-unstable-v1/README.md @@ -0,0 +1,31 @@ +# `treeland-wallpaper-shell-unstable-v1` 测试规范 + +## 范围 + +- 测试源码:`tests/protocols/treeland-wallpaper-shell-unstable-v1/` +- Fixture:协议 fixture。 +- 覆盖等级:**I/P**。 + +## 实际请求与预期结果 + +| 场景 | 客户端发送 | 生产业务逻辑与断言 | +| --- | --- | --- | +| shell surface | 用 `wl_surface` 创建 wallpaper surface | production shell 跟踪资源创建与销毁 | +| 生命周期事件 | 驱动 failed/play/pause/slow-down 路径 | 客户端收到相应资源事件 | +| notifier | 订阅并驱动 add/remove | 收到 notifier 的 payload 与生命周期事件 | + +## 已证明的生产链路 + +覆盖 wallpaper shell 与 notifier 的生产资源实现。 + +`wallpaper_surface.ready()` 的完成条件属于已有的生产生命周期:surface 已 mapped 或已有 +committed buffer 时,`ready()` 立即置位并发出 `ready`;否则它等待后续 +`WSurface::commit`。该协议对象不会为无 shell role 的 client surface 主动调用 `map()`。 + +## 未覆盖 + +基础测试覆盖无 buffer 时由下一次 commit 完成 `ready` 的时序,但没有 output 上的 mapped +wallpaper surface 或渲染读回。无 role client 的空/带 buffer commit 不应被当作 map 的替代。 +事件不代表壁纸已经可见或播放。与 manager 的资源关联由 +[`wallpaper-desktop-v1`](../treeland-wallpaper-desktop-v1/README.md) 验证;实际 wallpaper owner 的映射、 +QML 接入、最终 output 像素与媒体播放仍未覆盖。 diff --git a/tests/protocols/treeland-wallpaper-shell-unstable-v1/setup.cpp b/tests/protocols/treeland-wallpaper-shell-unstable-v1/setup.cpp new file mode 100644 index 0000000000..2e00ef64a8 --- /dev/null +++ b/tests/protocols/treeland-wallpaper-shell-unstable-v1/setup.cpp @@ -0,0 +1,103 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "modules/wallpaper/wallpapershellinterfacev1.h" +#include "modules/wallpaper/wallpapernotifierinterfacev1.h" +#include "server-bridge.h" + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +TreelandWallpaperShellInterfaceV1 *g_shell = nullptr; +TreelandWallpaperSurfaceInterfaceV1 *g_wallpaperSurface = nullptr; +TreelandWallpaperNotifierInterfaceV1 *g_notifier = nullptr; +uint32_t g_failedError = 0; +int g_failedCount = 0; +int g_readyCount = 0; +} + +void protocol_test_setup(WaylandServer *server) +{ + g_shell = find_server_interface(server); + g_notifier = find_server_interface(server); + Q_ASSERT(g_shell && g_notifier); + QObject::connect(g_shell, &TreelandWallpaperShellInterfaceV1::wallpaperSurfaceAdded, + [](TreelandWallpaperSurfaceInterfaceV1 *surface) { + g_wallpaperSurface = surface; + QObject::connect(surface, &TreelandWallpaperSurfaceInterfaceV1::beforeDestroy, + [surface]() { + if (g_wallpaperSurface == surface) + g_wallpaperSurface = nullptr; + }); + QObject::connect(surface, &TreelandWallpaperSurfaceInterfaceV1::failed, + [](uint32_t error) { + g_failedError = error; + ++g_failedCount; + }); + QObject::connect(surface, &TreelandWallpaperSurfaceInterfaceV1::ready, []() { + ++g_readyCount; + }); + }); +} + +extern "C" { + +void wallpaper_emit_play(void *) +{ + if (g_wallpaperSurface) + g_wallpaperSurface->setPlay(true); +} + +void wallpaper_emit_pause(void *) +{ + if (g_wallpaperSurface) + g_wallpaperSurface->setPlay(false); +} + +void wallpaper_emit_slow_down(void *data) +{ + if (g_wallpaperSurface) + g_wallpaperSurface->slowDown(500); + if (data) + *static_cast(data) = 1; +} + +void wallpaper_notifier_emit_add(void *) +{ + if (g_notifier) + g_notifier->sendAdd(TreelandWallpaperInterfaceV1::Image, QStringLiteral("/tmp/test-image.jpg")); +} + +void wallpaper_notifier_emit_remove(void *) +{ + if (g_notifier) + g_notifier->sendRemove(QStringLiteral("/tmp/test-image.jpg")); +} + +void wallpaper_query_failed(void *data) +{ + *static_cast(data) = g_failedCount ? static_cast(g_failedError) : -1; +} + +void wallpaper_query_failed_count(void *data) +{ + *static_cast(data) = g_failedCount; +} + +void wallpaper_query_ready_count(void *data) +{ + *static_cast(data) = g_readyCount; +} + +void wallpaper_query_wallpaper_ready(void *data) +{ + *static_cast(data) = (g_wallpaperSurface && g_wallpaperSurface->wallpaperReady()) ? 1 : 0; +} + +void wallpaper_query_produced(void *data) +{ + *static_cast(data) = g_shell ? g_shell->producedWallpapers().size() : -1; +} + +} // extern "C" diff --git a/tests/protocols/treeland-wallpaper-shell-unstable-v1/treeland-wallpaper-shell-unstable-v1.c b/tests/protocols/treeland-wallpaper-shell-unstable-v1/treeland-wallpaper-shell-unstable-v1.c new file mode 100644 index 0000000000..27e37f4c90 --- /dev/null +++ b/tests/protocols/treeland-wallpaper-shell-unstable-v1/treeland-wallpaper-shell-unstable-v1.c @@ -0,0 +1,296 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-wallpaper-shell-unstable-v1.h" +#include "server-bridge-api.h" +#include "treeland-wallpaper-shell-unstable-v1-client-protocol.h" + +#include +#include +#include +#include + +extern void wallpaper_emit_play(void *data); +extern void wallpaper_emit_pause(void *data); +extern void wallpaper_emit_slow_down(void *data); +extern void wallpaper_query_failed(void *data); +extern void wallpaper_query_failed_count(void *data); +extern void wallpaper_query_ready_count(void *data); +extern void wallpaper_query_wallpaper_ready(void *data); +extern void wallpaper_query_produced(void *data); +extern void wallpaper_notifier_emit_add(void *data); +extern void wallpaper_notifier_emit_remove(void *data); + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); +}; + +void test_init(struct test_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); + ctx->result_cap = 32; + ctx->results = calloc(ctx->result_cap, sizeof(*ctx->results)); +} + +void test_destroy(struct test_ctx *ctx) +{ + free(ctx->results); + memset(ctx, 0, sizeof(*ctx)); +} + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +void test_pass(struct test_ctx *ctx, int index) +{ + ctx->results[index].failed = 0; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +static void surface_play(void *data, struct treeland_wallpaper_surface_v1 *surface) +{ + (void)surface; + ((struct test_ctx *)data)->play_received = 1; +} + +static void surface_pause(void *data, struct treeland_wallpaper_surface_v1 *surface) +{ + (void)surface; + ((struct test_ctx *)data)->pause_received = 1; +} + +static void surface_slow_down(void *data, struct treeland_wallpaper_surface_v1 *surface, + uint32_t duration) +{ + (void)surface; + struct test_ctx *ctx = data; + ctx->slow_down_received = 1; + ctx->slow_down_duration = duration; +} + +static const struct treeland_wallpaper_surface_v1_listener wallpaper_surface_listener = { + .pause = surface_pause, + .play = surface_play, + .slow_down = surface_slow_down, +}; + +static void notifier_add(void *data, struct treeland_wallpaper_notifier_v1 *notifier, + uint32_t source_type, const char *file_source) +{ + (void)notifier; + struct test_ctx *ctx = data; + ctx->notifier_add_received = 1; + ctx->notifier_add_type = source_type; + snprintf(ctx->notifier_add_source, sizeof(ctx->notifier_add_source), "%s", file_source); +} + +static void notifier_remove(void *data, struct treeland_wallpaper_notifier_v1 *notifier, + const char *file_source) +{ + (void)notifier; + struct test_ctx *ctx = data; + ctx->notifier_remove_received = 1; + snprintf(ctx->notifier_remove_source, sizeof(ctx->notifier_remove_source), "%s", file_source); +} + +static const struct treeland_wallpaper_notifier_v1_listener notifier_listener = { + .add = notifier_add, + .remove = notifier_remove, +}; + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->display = ctx->connection.display; + ctx->compositor = client_bind(&ctx->connection, "wl_compositor", &wl_compositor_interface, 1); + + ctx->shell = client_bind(&ctx->connection, "treeland_wallpaper_shell_v1", + &treeland_wallpaper_shell_v1_interface, 1); + ctx->notifier = client_bind(&ctx->connection, "treeland_wallpaper_notifier_v1", + &treeland_wallpaper_notifier_v1_interface, 1); + if (ctx->notifier) + treeland_wallpaper_notifier_v1_add_listener(ctx->notifier, ¬ifier_listener, ctx); + return ctx->shell != NULL && ctx->notifier != NULL; +} + +static int shell_bound_version(struct test_ctx *ctx) +{ + return treeland_wallpaper_shell_v1_get_version(ctx->shell) == 1; +} + +static int create_wallpaper_surface(struct test_ctx *ctx) +{ + if (!ctx->compositor) + return 0; + ctx->test_surface = wl_compositor_create_surface(ctx->compositor); + ctx->wallpaper_surface = treeland_wallpaper_shell_v1_get_treeland_wallpaper_surface( + ctx->shell, ctx->test_surface, "/tmp/treeland-test-wallpaper.jpg"); + if (ctx->wallpaper_surface) + treeland_wallpaper_surface_v1_add_listener(ctx->wallpaper_surface, + &wallpaper_surface_listener, ctx); + return ctx->test_surface && ctx->wallpaper_surface; +} + +static int produced_count_is_one(struct test_ctx *ctx) +{ + (void)ctx; + int count = -1; + return invoke_on_server_thread(wallpaper_query_produced, &count) && count == 1; +} + +static int source_failed(struct test_ctx *ctx) +{ + treeland_wallpaper_surface_v1_source_failed( + ctx->wallpaper_surface, TREELAND_WALLPAPER_SURFACE_V1_ERROR_INVALID_SOURCE); + return 1; +} + +static int failed_signal_received(struct test_ctx *ctx) +{ + (void)ctx; + int error = -1; + int count = 0; + return invoke_on_server_thread(wallpaper_query_failed, &error) + && invoke_on_server_thread(wallpaper_query_failed_count, &count) + && count == 1 && error == TREELAND_WALLPAPER_SURFACE_V1_ERROR_INVALID_SOURCE; +} + +static int surface_ready(struct test_ctx *ctx) +{ + treeland_wallpaper_surface_v1_ready(ctx->wallpaper_surface); + + wl_surface_commit(ctx->test_surface); + return 1; +} + +static int ready_signal_received(struct test_ctx *ctx) +{ + (void)ctx; + int count = 0; + int ready = 0; + return invoke_on_server_thread(wallpaper_query_ready_count, &count) + && invoke_on_server_thread(wallpaper_query_wallpaper_ready, &ready) + && count == 1 && ready == 1; +} + +static int emit_play(struct test_ctx *ctx) { (void)ctx; return invoke_on_server_thread(wallpaper_emit_play, NULL); } +static int emit_pause(struct test_ctx *ctx) { (void)ctx; return invoke_on_server_thread(wallpaper_emit_pause, NULL); } +static int emit_slow_down(struct test_ctx *ctx) { (void)ctx; return invoke_on_server_thread(wallpaper_emit_slow_down, NULL); } +static int play_received(struct test_ctx *ctx) { return ctx->play_received; } +static int pause_received(struct test_ctx *ctx) { return ctx->pause_received; } +static int slow_down_received(struct test_ctx *ctx) { return ctx->slow_down_received && ctx->slow_down_duration == 500; } +static int emit_notifier_add(struct test_ctx *ctx) { (void)ctx; return invoke_on_server_thread(wallpaper_notifier_emit_add, NULL); } +static int notifier_add_received(struct test_ctx *ctx) +{ + return ctx->notifier_add_received + && ctx->notifier_add_type == TREELAND_WALLPAPER_NOTIFIER_V1_WALLPAPER_SOURCE_TYPE_IMAGE + && strcmp(ctx->notifier_add_source, "/tmp/test-image.jpg") == 0; +} +static int emit_notifier_remove(struct test_ctx *ctx) { (void)ctx; return invoke_on_server_thread(wallpaper_notifier_emit_remove, NULL); } +static int notifier_remove_received(struct test_ctx *ctx) +{ + return ctx->notifier_remove_received + && strcmp(ctx->notifier_remove_source, "/tmp/test-image.jpg") == 0; +} + +static int destroy_wallpaper_surface(struct test_ctx *ctx) +{ + treeland_wallpaper_surface_v1_destroy(ctx->wallpaper_surface); + ctx->wallpaper_surface = NULL; + return 1; +} + +static int produced_count_is_zero(struct test_ctx *ctx) +{ + (void)ctx; + int count = -1; + return invoke_on_server_thread(wallpaper_query_produced, &count) && count == 0; +} + +static const struct test_case cases[] = { + { "bind.version", shell_bound_version }, + { "shell.get_treeland_wallpaper_surface", create_wallpaper_surface }, + { "shell.produced_wallpapers", produced_count_is_one }, + { "surface.source_failed", source_failed }, + { "surface.failed_signal", failed_signal_received }, + { "surface.ready_after_commit", surface_ready }, + { "surface.ready_signal", ready_signal_received }, + { "server.emit_play", emit_play }, + { "surface.event.play", play_received }, + { "server.emit_pause", emit_pause }, + { "surface.event.pause", pause_received }, + { "server.emit_slow_down", emit_slow_down }, + { "surface.event.slow_down", slow_down_received }, + { "server.emit_notifier_add", emit_notifier_add }, + { "notifier.event.add", notifier_add_received }, + { "server.emit_notifier_remove", emit_notifier_remove }, + { "notifier.event.remove", notifier_remove_received }, + { "surface.destroy", destroy_wallpaper_surface }, + { "shell.produced_after_destroy", produced_count_is_zero }, +}; + +void test_cleanup(struct test_ctx *ctx) +{ + if (ctx->wallpaper_surface) treeland_wallpaper_surface_v1_destroy(ctx->wallpaper_surface); + if (ctx->notifier) treeland_wallpaper_notifier_v1_destroy(ctx->notifier); + if (ctx->shell) treeland_wallpaper_shell_v1_destroy(ctx->shell); + client_disconnect(&ctx->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx; + test_init(&ctx); + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect to or bind treeland_wallpaper_shell_v1\n"); + test_cleanup(&ctx); + test_destroy(&ctx); + return 1; + } + + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const int result = test_add(&ctx, cases[i].name); + if (!cases[i].run(&ctx)) + test_fail(&ctx, result, "assertion failed"); + if (wl_display_roundtrip(ctx.display) < 0) + test_fail(&ctx, result, "Wayland connection failed"); + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + test_destroy(&ctx); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-wallpaper-shell-unstable-v1/treeland-wallpaper-shell-unstable-v1.h b/tests/protocols/treeland-wallpaper-shell-unstable-v1/treeland-wallpaper-shell-unstable-v1.h new file mode 100644 index 0000000000..8987828e84 --- /dev/null +++ b/tests/protocols/treeland-wallpaper-shell-unstable-v1/treeland-wallpaper-shell-unstable-v1.h @@ -0,0 +1,60 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef WALLPAPER_SHELL_TEST_H +#define WALLPAPER_SHELL_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +#include "client-connection.h" + +#define TEST_MSG_MAX 256 + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +struct test_ctx { + struct client_connection connection; + struct wl_display *display; + + struct wl_compositor *compositor; + struct treeland_wallpaper_notifier_v1 *notifier; + + struct treeland_wallpaper_shell_v1 *shell; + struct treeland_wallpaper_surface_v1 *wallpaper_surface; + struct wl_surface *test_surface; + + int play_received; + int pause_received; + int slow_down_received; + uint32_t slow_down_duration; + int notifier_add_received; + int notifier_remove_received; + uint32_t notifier_add_type; + char notifier_add_source[TEST_MSG_MAX]; + char notifier_remove_source[TEST_MSG_MAX]; + + struct test_result *results; + int result_count; + int result_cap; +}; + +void test_init(struct test_ctx *ctx); +void test_destroy(struct test_ctx *ctx); +int test_add(struct test_ctx *ctx, const char *name); +void test_fail(struct test_ctx *ctx, int idx, const char *fmt, ...); +void test_pass(struct test_ctx *ctx, int idx); + +int test_print_results(struct test_ctx *ctx); +void test_cleanup(struct test_ctx *ctx); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-window-transition-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-window-transition-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..3324c22d6a --- /dev/null +++ b/tests/protocols/treeland-window-transition-unstable-v1/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME treeland_window_transition_unstable_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-window-transition-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-window-transition-unstable-v1.c" + EXTRA_XMLS "${WAYLAND_PROTOCOLS_DATADIR}/staging/xdg-activation/xdg-activation-v1.xml" +) diff --git a/tests/protocols/treeland-window-transition-unstable-v1/README.md b/tests/protocols/treeland-window-transition-unstable-v1/README.md new file mode 100644 index 0000000000..c2d8716164 --- /dev/null +++ b/tests/protocols/treeland-window-transition-unstable-v1/README.md @@ -0,0 +1,69 @@ +# `treeland-window-transition-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`treeland_window_transition_manager_v1` / `treeland_window_transition_rect_v1` +- 测试源码:`tests/protocols/treeland-window-transition-unstable-v1/` +- Fixture:desktop integration fixture(`protocol_test_setup` 取得生产 + `WindowTransitionManagerInterfaceV1`、创建 headless output,并记录 + `ShellHandler::surfaceWrapperAdded` 的 wrapper 以便回读真实 transition 状态) +- 覆盖等级:**P / I / E** + +`treeland_window_transition_manager_v1.get_window_transition_rect` 为激活 token 创建 +transition rect。测试通过 server bridge 在 compositor 线程回读生产 +`WindowTransitionManagerInterfaceV1::hasPendingWindowTransitionRect()`,证明 rect 真的进入 +`m_pendingRects`,而不只是请求可被派发。同一 token 再次创建会让前一个 rect 收到一次 +`closed`;客户端销毁 rect 后 pending 集合移除,而销毁被覆盖的旧 rect 不会误删当前 rect。 + +E 级场景走真实 `xdg-activation-v1` 链路:源 toplevel 用激活 token 字符串创建 rect +(geometry + source surface),目标 toplevel 在 map 前 `activate` 该 token,生产侧 +`associatePendingRect()` 消费 pending rect 并武装目标 `SurfaceWindowTransition`;回读 +`globalRect()` 的尺寸、`active()` 与 `sourceSurface()`,以及被武装 wrapper 的 mapped 状态, +因此断言落在"被武装的是那个尚未 map 的目标窗口"上,而不是"某个窗口被 arm 了"。 + +两条协议错误路径各自使用独立连接(`wl_resource_post_error` 会终止连接),并断言 +`wl_display_get_protocol_error()` 的 interface 与 code。 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| pending 存储 | `get_window_transition_rect(token)` | 生产 `hasPendingWindowTransitionRect(token)` == 1,且没有任何 transition 被武装 | I | +| 过期前不关闭 | 已存储的 pending rect | 未收到 `closed` | P | +| 同 token 覆盖 | 对同一 token 再 `get_window_transition_rect` | 前一个 rect 收到恰好 1 次 `closed`,新的不关闭;再 roundtrip 不重复 | P | +| 旧 rect 析构 | 销毁被覆盖的旧 rect | 该 token 仍在 pending 集合(新 rect 未被误删) | I | +| 客户端销毁 | `treeland_window_transition_rect_v1.destroy` | pending 集合移除该 token | I | +| 激活关联 | 目标 map 前 `xdg_activation_v1.activate(token, target)` | 恰好 1 个 transition 被武装,且属于**未 map** 的窗口,带 40×40 的 rect 与 source surface;该 token 的 pending 被消费,另一个 token 的 rect 不被消费 | E | +| 几何更新 | 关联后 `set_geometry(3, 4, 20, 30)` | 被武装的 rect 变为 20×30,仍 armed | E | +| 0×0 禁用 | `set_geometry(0, 0, 0, 0)` | 不再 `active()`(armed_count == 0),但关联仍在(rect_present == 1,尺寸 0×0) | E | +| 重新启用 | `set_geometry(0, 0, 40, 40)` | 重新 `active()`,rect 40×40 | E | +| source 清空 / 重设 | `set_source_surface(NULL)`,随后连续两次设同一个 surface | 清空后无 source surface 且仍 armed;重设后 source surface 回来且不报错 | E | +| 激活迟到 | 目标已 map 后 `xdg_activation_v1.activate(token, target)` | rect 收到恰好 1 次 `closed`,pending 清空,且没有任何 transition 被武装 | E | +| 无 originating surface | token 未 `set_surface`,目标未 map 时 `activate` | rect 收到恰好 1 次 `closed`,pending 清空,且没有任何 transition 被武装 | E | +| 负几何 | `set_geometry(0, 0, -1, 4)` | `invalid_geometry` 协议错误 | P | +| 角色冲突 | 对已带 role 的 mapped toplevel surface `set_source_surface` | `invalid_surface` 协议错误 | P | + +## 生产结果 + +- `WindowTransitionManagerInterfaceV1::m_pendingRects` 的真实内容,经 + `hasPendingWindowTransitionRect()` 回读;`consume` 与 `discard` 都以 token 为键,因此 + 另一个 token 的 rect 会留在集合里。 +- `closed` 事件来自 `WindowTransitionRectV1::notifyDiscarded()`(同 token 覆盖、激活迟到、 + 无 originating surface 三条路径),断言按次数而非布尔,覆盖协议"至多一次"的约定。 +- 被武装目标的 `SurfaceWindowTransition` 状态经 `globalRect()`(尺寸)、`active()`、 + `sourceSurface()` 与所属 wrapper 的 `mapped()` 回读,对应 `Helper` 的 + `associatePendingRect()`;几何更新、0×0 禁用与 source 清空分别对应 + `updateWindowTransitionRect()` / `setWindowTransitionSource()` / + `clearWindowTransitionSource()`。 + +## 已知边界 / 下一项结果 + +- 未覆盖目标销毁触发的 rect `closed`:依赖关闭动画时序,客户端侧没有 roundtrip 之外 + 的确定性同步点。 +- 未覆盖 `set_geometry` 的 60 s sweep 过期:需要真实等待或给常量加测试注入点。 +- 未覆盖跨 client 的 `invalid_surface` 分支(生产里的 `wl_resource_get_client` 不匹配): + libwayland-server 对不属于本连接的对象 id 解析为 NULL,生产代码会走"清空 source" + 而不是报错,该分支是否可达需实测确认。 +- 只断言 rect 的尺寸,未断言其全局位置(位置依赖 output 布局与源窗口位置)。 +- 只断言 source surface 存在,未断言它就是客户端设置的那个 surface(wrapper 未暴露 + surface 标识;加强这一断言需要生产侧新增访问器)。 diff --git a/tests/protocols/treeland-window-transition-unstable-v1/setup.cpp b/tests/protocols/treeland-window-transition-unstable-v1/setup.cpp new file mode 100644 index 0000000000..a468ec107b --- /dev/null +++ b/tests/protocols/treeland-window-transition-unstable-v1/setup.cpp @@ -0,0 +1,84 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "server-bridge.h" +#include "treeland-window-transition-unstable-v1.h" + +#include "core/shellhandler.h" +#include "core/waylandserver.h" +#include "modules/window-transition/windowtransitionmanagerinterfacev1.h" +#include "surface/surfacewindowtransition.h" +#include "surface/surfacewrapper.h" + +#include +#include +#include +#include +#include + +#include + +namespace { +WindowTransitionManagerInterfaceV1 *g_manager = nullptr; +QList> g_wrappers; +} + +void protocol_test_setup(WaylandServer *server) +{ + g_manager = find_server_interface(server); + Q_ASSERT(g_manager); + add_headless_output(server->backend(), false); + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [](SurfaceWrapper *wrapper) { + g_wrappers.append(QPointer(wrapper)); + }); +} + +extern "C" void window_transition_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->manager_present = g_manager ? 1 : 0; + state->pending = 0; + state->armed_count = 0; + state->rect_present = 0; + state->rect_mapped = 0; + state->rect_w = 0; + state->rect_h = 0; + state->source_set = 0; + if (g_manager && state->token[0] != '\0') { + state->pending = g_manager->hasPendingWindowTransitionRect( + QString::fromUtf8(state->token)) + ? 1 + : 0; + } + + // Report the rectangle the production manager associated with a real + // SurfaceWindowTransition. globalRect() resolves only for a transition that + // holds the manager's rect, so its value names the armed window instead of + // trusting the first wrapper that happens to be active. + for (const auto &wrapper : std::as_const(g_wrappers)) { + if (!wrapper) + continue; + auto *transition = + qobject_cast(wrapper->windowTransition()); + if (!transition) + continue; + if (transition->active()) + ++state->armed_count; + + // The rect survives a 0x0 geometry (that only disables it), so presence + // and size are reported separately from active(). + if (state->rect_present) + continue; + const auto rect = transition->globalRect(); + if (!rect) + continue; + state->rect_present = 1; + state->rect_mapped = + (wrapper->surface() && wrapper->surface()->mapped()) ? 1 : 0; + state->rect_w = qRound(rect->width()); + state->rect_h = qRound(rect->height()); + state->source_set = transition->sourceSurface() ? 1 : 0; + } +} diff --git a/tests/protocols/treeland-window-transition-unstable-v1/treeland-window-transition-unstable-v1.c b/tests/protocols/treeland-window-transition-unstable-v1/treeland-window-transition-unstable-v1.c new file mode 100644 index 0000000000..8a16d668c5 --- /dev/null +++ b/tests/protocols/treeland-window-transition-unstable-v1/treeland-window-transition-unstable-v1.c @@ -0,0 +1,878 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +/* + * Coverage level P / I / E. + * + * The client drives treeland_window_transition_manager_v1 and reads back the + * production WindowTransitionManagerInterfaceV1 pending set and the armed + * SurfaceWindowTransition through the server bridge, so stored/associated + * rectangles are proven rather than a dispatchable request. + * + * The activation scenarios need a real xdg-activation-v1 token: an originating + * mapped toplevel attaches the rectangle to the token, then a target toplevel + * activates the token before it maps (association, which also proves the armed + * window is the unmapped target) or after it maps (the "activation arrived too + * late" fallback that closes the rectangle). + * + * The protocol-error paths each use their own connection because + * wl_resource_post_error tears the connection down. + */ + +#include "client-connection.h" +#include "server-bridge-api.h" +#include "treeland-window-transition-unstable-v1-client-protocol.h" +#include "treeland-window-transition-unstable-v1.h" +#include "xdg-activation-v1-client-protocol.h" +#include "xdg-toplevel-client.h" + +#include +#include + +#define WINDOW_TRANSITION_MANAGER "treeland_window_transition_manager_v1" + +struct rect_events { + int closed_count; +}; + +static void rect_handle_closed(void *data, struct treeland_window_transition_rect_v1 *rect) +{ + (void)rect; + ((struct rect_events *)data)->closed_count++; +} + +static const struct treeland_window_transition_rect_v1_listener rect_listener = { + .closed = rect_handle_closed, +}; + +static struct treeland_window_transition_rect_v1 *create_rect( + struct treeland_window_transition_manager_v1 *manager, + const char *token, + struct rect_events *events) +{ + struct treeland_window_transition_rect_v1 *rect = + treeland_window_transition_manager_v1_get_window_transition_rect(manager, token); + if (rect) + treeland_window_transition_rect_v1_add_listener(rect, &rect_listener, events); + return rect; +} + +static int read_state(const char *token, struct window_transition_server_state *state) +{ + memset(state, 0, sizeof(*state)); + snprintf(state->token, sizeof(state->token), "%s", token); + if (!invoke_on_server_thread(window_transition_read_server_state, state)) + return 0; + return state->manager_present; +} + +/* 1 when the token is in the production pending set, 0 when it is not, -1 when + * the production state could not be read at all. */ +static int read_pending(const char *token) +{ + struct window_transition_server_state state; + if (!read_state(token, &state)) + return -1; + return state.pending; +} + +/* + * The associated rectangle is described by the production wrapper the manager + * armed, so these assertions are about the real window transition rather than + * about the request being dispatched. + */ +static int expect_association(const struct window_transition_server_state *state, + int expected_mapped) +{ + if (state->armed_count != 1) { + TEST_ERROR("window-transition: expected exactly one armed transition, got %d\n", + state->armed_count); + return 0; + } + if (!state->rect_present) { + TEST_ERROR("window-transition: armed transition exposes no rectangle\n"); + return 0; + } + if (state->rect_mapped != expected_mapped) { + TEST_ERROR("window-transition: armed transition mapped=%d, expected %d\n", + state->rect_mapped, expected_mapped); + return 0; + } + if (!state->source_set) { + TEST_ERROR("window-transition: armed transition has no source surface\n"); + return 0; + } + return 1; +} + +static int expect_rect_size(const struct window_transition_server_state *state, + int width, + int height) +{ + if (!state->rect_present) { + TEST_ERROR("window-transition: no associated rectangle to size\n"); + return 0; + } + if (state->rect_w != width || state->rect_h != height) { + TEST_ERROR("window-transition: associated rect is %dx%d, expected %dx%d\n", + state->rect_w, state->rect_h, width, height); + return 0; + } + return 1; +} + +struct activation_token_state { + int done; + char token[128]; +}; + +static void token_handle_done(void *data, + struct xdg_activation_token_v1 *token, + const char *token_string) +{ + (void)token; + struct activation_token_state *state = data; + state->done = 1; + if (token_string) + snprintf(state->token, sizeof(state->token), "%s", token_string); +} + +static const struct xdg_activation_token_v1_listener token_listener = { + .done = token_handle_done, +}; + +/* + * Obtains a committed activation token string. `originating` may be NULL, which + * leaves the token without the set_surface hint: the compositor then has no + * surface to map the rectangle to and must discard the pending rect. + */ +static int obtain_token(struct client_connection *connection, + struct xdg_activation_v1 *activation, + struct wl_surface *originating, + char *token, + size_t token_size) +{ + struct xdg_activation_token_v1 *request = xdg_activation_v1_get_activation_token(activation); + if (!request) + return 0; + + struct activation_token_state state = { 0 }; + if (originating) + xdg_activation_token_v1_set_surface(request, originating); + xdg_activation_token_v1_add_listener(request, &token_listener, &state); + xdg_activation_token_v1_commit(request); + + const int ok = wl_display_roundtrip(connection->display) >= 0 + && state.done && state.token[0] != '\0'; + if (ok) + snprintf(token, token_size, "%s", state.token); + xdg_activation_token_v1_destroy(request); + return ok; +} + +static int run_pending_and_events(const char *socket_name) +{ + struct client_connection connection = { 0 }; + if (!client_connect(&connection, socket_name)) + return 0; + + struct treeland_window_transition_manager_v1 *manager = + client_bind(&connection, + WINDOW_TRANSITION_MANAGER, + &treeland_window_transition_manager_v1_interface, + treeland_window_transition_manager_v1_interface.version); + if (!manager) { + TEST_ERROR("window-transition: manager missing\n"); + client_disconnect(&connection); + return 0; + } + + int ok = 1; + struct window_transition_server_state state; + + /* A rectangle created for a token is kept in the production pending set. */ + struct rect_events events_a = { 0 }; + struct treeland_window_transition_rect_v1 *rect_a = + create_rect(manager, "treeland-transition-token-a", &events_a); + if (!rect_a || wl_display_roundtrip(connection.display) < 0) { + TEST_ERROR("window-transition: failed to create the first rectangle\n"); + ok = 0; + } else if (!read_state("treeland-transition-token-a", &state)) { + TEST_ERROR("window-transition: production manager not reachable\n"); + ok = 0; + } else if (!state.pending) { + TEST_ERROR("window-transition: pending rect for token-a not stored\n"); + ok = 0; + } else if (state.armed_count != 0 || state.rect_present != 0) { + TEST_ERROR("window-transition: a stored rect armed a transition by itself\n"); + ok = 0; + } else if (events_a.closed_count) { + TEST_ERROR("window-transition: pending rect closed prematurely\n"); + ok = 0; + } + + /* Creating another rectangle for the same token closes the previous one. */ + struct rect_events events_first = { 0 }; + struct rect_events events_second = { 0 }; + struct treeland_window_transition_rect_v1 *rect_first = NULL; + struct treeland_window_transition_rect_v1 *rect_second = NULL; + if (ok) { + rect_first = create_rect(manager, "treeland-transition-token-dup", &events_first); + rect_second = create_rect(manager, "treeland-transition-token-dup", &events_second); + if (!rect_first || !rect_second || wl_display_roundtrip(connection.display) < 0) { + TEST_ERROR("window-transition: failed to create the superseded pair\n"); + ok = 0; + } else if (events_first.closed_count != 1) { + TEST_ERROR("window-transition: superseded rect got %d closed events, expected 1\n", + events_first.closed_count); + ok = 0; + } else if (events_second.closed_count) { + TEST_ERROR("window-transition: replacement rect closed unexpectedly\n"); + ok = 0; + } + } + + /* closed is a one-shot notification; the superseded rect must not repeat it. */ + if (ok) { + if (wl_display_roundtrip(connection.display) < 0) { + ok = 0; + } else if (events_first.closed_count != 1) { + TEST_ERROR("window-transition: superseded rect repeated closed\n"); + ok = 0; + } + } + + /* Destroying the superseded rect must not drop the replacement from the + * pending set: only the rect the manager currently holds for the token is + * removed. */ + if (ok) { + treeland_window_transition_rect_v1_destroy(rect_first); + rect_first = NULL; + if (wl_display_roundtrip(connection.display) < 0) { + ok = 0; + } else if (read_pending("treeland-transition-token-dup") != 1) { + TEST_ERROR("window-transition: destroying the superseded rect dropped the" + " replacement\n"); + ok = 0; + } + } + + /* Destroying the client object removes it from the pending set. */ + struct rect_events events_idle = { 0 }; + struct treeland_window_transition_rect_v1 *rect_idle = NULL; + if (ok) { + rect_idle = create_rect(manager, "treeland-transition-token-idle", &events_idle); + if (!rect_idle || wl_display_roundtrip(connection.display) < 0) { + TEST_ERROR("window-transition: failed to create the recyclable rect\n"); + ok = 0; + } else { + treeland_window_transition_rect_v1_destroy(rect_idle); + rect_idle = NULL; + if (wl_display_roundtrip(connection.display) < 0) { + ok = 0; + } else if (read_pending("treeland-transition-token-idle") != 0) { + TEST_ERROR("window-transition: destroyed rect still pending\n"); + ok = 0; + } + } + } + + if (rect_idle) + treeland_window_transition_rect_v1_destroy(rect_idle); + if (rect_second) + treeland_window_transition_rect_v1_destroy(rect_second); + if (rect_first) + treeland_window_transition_rect_v1_destroy(rect_first); + if (rect_a) + treeland_window_transition_rect_v1_destroy(rect_a); + treeland_window_transition_manager_v1_destroy(manager); + client_disconnect(&connection); + return ok; +} + +/* + * E: once the rectangle is associated the object stays live. The armed + * transition must follow later set_geometry calls, a 0x0 geometry must disable + * it without dropping the association, and the source surface may be cleared + * and attached again. + */ +struct associated_rect { + struct wl_display *display; + struct treeland_window_transition_rect_v1 *rect; + struct wl_surface *source; + struct rect_events *events; + const char *token; +}; + +static int run_associated_rect_updates(const struct associated_rect *associated) +{ + struct window_transition_server_state state; + int ok = 1; + + /* The client may update the geometry; the armed transition must follow the + * latest value. */ + treeland_window_transition_rect_v1_set_geometry(associated->rect, 3, 4, 20, 30); + if (wl_display_roundtrip(associated->display) < 0) { + ok = 0; + } else if (!read_state(associated->token, &state)) { + ok = 0; + } else if (!expect_association(&state, 0) || !expect_rect_size(&state, 20, 30)) { + ok = 0; + } + + /* A 0x0 geometry is the documented way to disable the rectangle: the + * association stays alive, only the animation source goes away. */ + if (ok) { + treeland_window_transition_rect_v1_set_geometry(associated->rect, 0, 0, 0, 0); + if (wl_display_roundtrip(associated->display) < 0) { + ok = 0; + } else if (!read_state(associated->token, &state)) { + ok = 0; + } else if (state.armed_count != 0) { + TEST_ERROR("window-transition: 0x0 geometry did not disable the rect\n"); + ok = 0; + } else if (!state.rect_present) { + TEST_ERROR("window-transition: 0x0 geometry dropped the association\n"); + ok = 0; + } else if (!expect_rect_size(&state, 0, 0)) { + ok = 0; + } + } + + /* ...and a positive size again re-enables it. */ + if (ok) { + treeland_window_transition_rect_v1_set_geometry(associated->rect, 0, 0, 40, 40); + if (wl_display_roundtrip(associated->display) < 0) { + ok = 0; + } else if (!read_state(associated->token, &state)) { + ok = 0; + } else if (!expect_association(&state, 0) || !expect_rect_size(&state, 40, 40)) { + ok = 0; + } + } + + /* Passing null clears the source surface without disarming the rectangle. */ + if (ok) { + treeland_window_transition_rect_v1_set_source_surface(associated->rect, NULL); + if (wl_display_roundtrip(associated->display) < 0) { + ok = 0; + } else if (!read_state(associated->token, &state)) { + ok = 0; + } else if (state.source_set) { + TEST_ERROR("window-transition: null source surface did not clear the source\n"); + ok = 0; + } else if (state.armed_count != 1 || !state.rect_present) { + TEST_ERROR("window-transition: clearing the source disarmed the rect\n"); + ok = 0; + } + } + + /* ...and the same surface may be attached again, repeatedly. */ + if (ok) { + treeland_window_transition_rect_v1_set_source_surface(associated->rect, associated->source); + treeland_window_transition_rect_v1_set_source_surface(associated->rect, associated->source); + if (wl_display_roundtrip(associated->display) < 0) { + ok = 0; + } else if (!read_state(associated->token, &state)) { + ok = 0; + } else if (!expect_association(&state, 0) || !expect_rect_size(&state, 40, 40)) { + ok = 0; + } else if (associated->events->closed_count) { + TEST_ERROR("window-transition: associated rect was closed during the updates\n"); + ok = 0; + } + } + + return ok; +} + +/* + * E: an originating toplevel attaches a rectangle (geometry + live source + * surface) to an activation token, and a target toplevel activates that token + * before it maps. The production manager must consume the pending rect and arm + * the still unmapped target with the rectangle and the source surface. + */ +static int run_associate_on_activation(const char *socket_name) +{ + struct client_connection connection = { 0 }; + struct xdg_toplevel_client origin = { 0 }; + struct xdg_toplevel_client target = { 0 }; + struct wl_surface *source = NULL; + struct treeland_window_transition_rect_v1 *rect = NULL; + struct treeland_window_transition_rect_v1 *decoy = NULL; + if (!client_connect(&connection, socket_name)) + return 0; + + struct treeland_window_transition_manager_v1 *manager = + client_bind(&connection, + WINDOW_TRANSITION_MANAGER, + &treeland_window_transition_manager_v1_interface, + treeland_window_transition_manager_v1_interface.version); + struct xdg_activation_v1 *activation = + client_bind(&connection, + xdg_activation_v1_interface.name, + &xdg_activation_v1_interface, + xdg_activation_v1_interface.version); + struct wl_compositor *compositor = + client_bind(&connection, "wl_compositor", &wl_compositor_interface, 1); + if (!manager || !activation || !compositor) { + TEST_ERROR("window-transition: missing manager, activation or compositor\n"); + client_disconnect(&connection); + return 0; + } + + int ok = 1; + char token[128]; + struct window_transition_server_state state; + + /* A: the mapped originating toplevel that owns the activation token. */ + if (!xdg_toplevel_client_create(&connection, &origin)) { + TEST_ERROR("window-transition: failed to create the originating toplevel\n"); + ok = 0; + } + + if (ok) { + source = wl_compositor_create_surface(compositor); + if (!source) { + TEST_ERROR("window-transition: failed to create the source surface\n"); + ok = 0; + } + } + + if (ok && !obtain_token(&connection, activation, origin.surface, token, sizeof(token))) { + TEST_ERROR("window-transition: failed to obtain activation token\n"); + ok = 0; + } + + struct rect_events events = { 0 }; + if (ok) { + rect = treeland_window_transition_manager_v1_get_window_transition_rect(manager, token); + if (!rect) { + TEST_ERROR("window-transition: failed to create the transition rect\n"); + ok = 0; + } else { + treeland_window_transition_rect_v1_add_listener(rect, &rect_listener, &events); + treeland_window_transition_rect_v1_set_geometry(rect, 0, 0, 40, 40); + treeland_window_transition_rect_v1_set_source_surface(rect, source); + if (wl_display_roundtrip(connection.display) < 0) { + TEST_ERROR("window-transition: rect configuration was rejected\n"); + ok = 0; + } + } + } + + /* A second rectangle under an unrelated token must survive the activation: + * the manager consumes the pending rect of this token only. */ + struct rect_events decoy_events = { 0 }; + if (ok) { + decoy = create_rect(manager, "treeland-transition-token-decoy", &decoy_events); + if (!decoy || wl_display_roundtrip(connection.display) < 0) { + TEST_ERROR("window-transition: failed to create the decoy rectangle\n"); + ok = 0; + } + } + + if (ok) { + if (!read_state(token, &state)) { + TEST_ERROR("window-transition: production manager not reachable\n"); + ok = 0; + } else if (!state.pending) { + TEST_ERROR("window-transition: rect not pending before activation\n"); + ok = 0; + } else if (state.armed_count != 0 || state.rect_present != 0) { + TEST_ERROR("window-transition: a transition was armed before activation\n"); + ok = 0; + } + } + + /* B: the target toplevel, created but not mapped yet. */ + if (ok + && (!xdg_toplevel_client_create_pending(&connection, &target) + || wl_display_roundtrip(connection.display) < 0)) { + TEST_ERROR("window-transition: failed to create the pending target\n"); + ok = 0; + } + + if (ok) { + xdg_activation_v1_activate(activation, token, target.surface); + if (wl_display_roundtrip(connection.display) < 0) { + TEST_ERROR("window-transition: activation was rejected\n"); + ok = 0; + } + } + + /* The pending rect is consumed and the still unmapped target is armed with + * the rectangle and the live source surface. */ + if (ok) { + if (!read_state(token, &state)) { + TEST_ERROR("window-transition: production manager not reachable\n"); + ok = 0; + } else if (state.pending) { + TEST_ERROR("window-transition: pending rect survived association\n"); + ok = 0; + } else if (!expect_association(&state, 0)) { + ok = 0; + } else if (!expect_rect_size(&state, 40, 40)) { + ok = 0; + } else if (events.closed_count) { + TEST_ERROR("window-transition: associated rect was closed while the target lives\n"); + ok = 0; + } else if (read_pending("treeland-transition-token-decoy") != 1) { + TEST_ERROR("window-transition: association consumed an unrelated token's rect\n"); + ok = 0; + } else if (decoy_events.closed_count) { + TEST_ERROR("window-transition: decoy rect was closed by the activation\n"); + ok = 0; + } + } + + /* The rectangle stays live after the association. */ + if (ok) { + const struct associated_rect associated = { + .display = connection.display, + .rect = rect, + .source = source, + .events = &events, + .token = token, + }; + ok = run_associated_rect_updates(&associated); + } + + if (decoy) + treeland_window_transition_rect_v1_destroy(decoy); + if (rect) + treeland_window_transition_rect_v1_destroy(rect); + if (source) + wl_surface_destroy(source); + if (origin.surface) + xdg_toplevel_client_destroy(&origin); + if (target.surface) + xdg_toplevel_client_destroy(&target); + client_disconnect(&connection); + return ok; +} + +/* + * E: the target is already mapped when the activation arrives. The compositor + * falls back to its default animation, drops the pending rectangle and closes + * it without arming any transition. + */ +static int run_closed_when_activation_late(const char *socket_name) +{ + struct client_connection connection = { 0 }; + struct xdg_toplevel_client origin = { 0 }; + struct xdg_toplevel_client target = { 0 }; + struct treeland_window_transition_rect_v1 *rect = NULL; + if (!client_connect(&connection, socket_name)) + return 0; + + struct treeland_window_transition_manager_v1 *manager = + client_bind(&connection, + WINDOW_TRANSITION_MANAGER, + &treeland_window_transition_manager_v1_interface, + treeland_window_transition_manager_v1_interface.version); + struct xdg_activation_v1 *activation = + client_bind(&connection, + xdg_activation_v1_interface.name, + &xdg_activation_v1_interface, + xdg_activation_v1_interface.version); + if (!manager || !activation) { + TEST_ERROR("window-transition: missing manager or activation\n"); + client_disconnect(&connection); + return 0; + } + + int ok = 1; + char token[128]; + + /* Both the origin and the target are mapped before the activation. */ + if (!xdg_toplevel_client_create(&connection, &origin)) { + TEST_ERROR("window-transition: failed to create the originating toplevel\n"); + ok = 0; + } + if (ok && !xdg_toplevel_client_create(&connection, &target)) { + TEST_ERROR("window-transition: failed to create the mapped target\n"); + ok = 0; + } + if (ok && !obtain_token(&connection, activation, origin.surface, token, sizeof(token))) { + TEST_ERROR("window-transition: failed to obtain activation token\n"); + ok = 0; + } + + struct rect_events events = { 0 }; + if (ok) { + rect = treeland_window_transition_manager_v1_get_window_transition_rect(manager, token); + if (!rect) { + TEST_ERROR("window-transition: failed to create the transition rect\n"); + ok = 0; + } else { + treeland_window_transition_rect_v1_add_listener(rect, &rect_listener, &events); + treeland_window_transition_rect_v1_set_geometry(rect, 0, 0, 40, 40); + if (wl_display_roundtrip(connection.display) < 0) { + TEST_ERROR("window-transition: rect configuration was rejected\n"); + ok = 0; + } + } + } + + struct window_transition_server_state state; + if (ok) { + if (!read_state(token, &state)) { + TEST_ERROR("window-transition: production manager not reachable\n"); + ok = 0; + } else if (!state.pending) { + TEST_ERROR("window-transition: rect not pending before late activation\n"); + ok = 0; + } + } + + if (ok) { + /* target.surface is already mapped, so the compositor discards the + * pending rect and must emit closed. */ + xdg_activation_v1_activate(activation, token, target.surface); + if (wl_display_roundtrip(connection.display) < 0) { + TEST_ERROR("window-transition: late activation was rejected\n"); + ok = 0; + } + } + + if (ok && events.closed_count != 1) { + TEST_ERROR("window-transition: late activation got %d closed events, expected 1\n", + events.closed_count); + ok = 0; + } + + if (ok) { + if (!read_state(token, &state)) { + ok = 0; + } else if (state.pending) { + TEST_ERROR("window-transition: late activation left the rect pending\n"); + ok = 0; + } else if (state.armed_count != 0 || state.rect_present != 0) { + TEST_ERROR("window-transition: late activation armed a transition\n"); + ok = 0; + } + } + + if (rect) + treeland_window_transition_rect_v1_destroy(rect); + if (origin.surface) + xdg_toplevel_client_destroy(&origin); + if (target.surface) + xdg_toplevel_client_destroy(&target); + client_disconnect(&connection); + return ok; +} + +/* + * E: the activation token carries no originating surface (the client never + * called set_surface). The rectangle cannot be mapped to global coordinates, + * so the compositor must discard the pending rect right away and close it + * instead of keeping it until the pending sweep expires. + */ +static int run_discarded_without_origin_surface(const char *socket_name) +{ + struct client_connection connection = { 0 }; + struct xdg_toplevel_client target = { 0 }; + struct treeland_window_transition_rect_v1 *rect = NULL; + if (!client_connect(&connection, socket_name)) + return 0; + + struct treeland_window_transition_manager_v1 *manager = + client_bind(&connection, + WINDOW_TRANSITION_MANAGER, + &treeland_window_transition_manager_v1_interface, + treeland_window_transition_manager_v1_interface.version); + struct xdg_activation_v1 *activation = + client_bind(&connection, + xdg_activation_v1_interface.name, + &xdg_activation_v1_interface, + xdg_activation_v1_interface.version); + if (!manager || !activation) { + TEST_ERROR("window-transition: missing manager or activation\n"); + client_disconnect(&connection); + return 0; + } + + int ok = 1; + char token[128]; + struct window_transition_server_state state; + + /* The target is a real toplevel but stays unmapped, so only the missing + * originating surface can make the compositor drop the rect. */ + if (!xdg_toplevel_client_create_pending(&connection, &target) + || wl_display_roundtrip(connection.display) < 0) { + TEST_ERROR("window-transition: failed to create the pending target\n"); + ok = 0; + } + + if (ok && !obtain_token(&connection, activation, NULL, token, sizeof(token))) { + TEST_ERROR("window-transition: failed to obtain activation token\n"); + ok = 0; + } + + struct rect_events events = { 0 }; + if (ok) { + rect = treeland_window_transition_manager_v1_get_window_transition_rect(manager, token); + if (!rect) { + TEST_ERROR("window-transition: failed to create the transition rect\n"); + ok = 0; + } else { + treeland_window_transition_rect_v1_add_listener(rect, &rect_listener, &events); + treeland_window_transition_rect_v1_set_geometry(rect, 0, 0, 40, 40); + if (wl_display_roundtrip(connection.display) < 0) { + TEST_ERROR("window-transition: rect configuration was rejected\n"); + ok = 0; + } + } + } + + if (ok && read_pending(token) != 1) { + TEST_ERROR("window-transition: rect without an originating surface is not pending\n"); + ok = 0; + } + + if (ok) { + xdg_activation_v1_activate(activation, token, target.surface); + if (wl_display_roundtrip(connection.display) < 0) { + TEST_ERROR("window-transition: activation was rejected\n"); + ok = 0; + } + } + + if (ok) { + if (events.closed_count != 1) { + TEST_ERROR("window-transition: rect without an originating surface got %d closed" + " events, expected 1\n", + events.closed_count); + ok = 0; + } else if (!read_state(token, &state)) { + TEST_ERROR("window-transition: production manager not reachable\n"); + ok = 0; + } else if (state.pending) { + TEST_ERROR("window-transition: rect without an originating surface stayed pending\n"); + ok = 0; + } else if (state.armed_count != 0 || state.rect_present != 0) { + TEST_ERROR("window-transition: rect without an originating surface armed a" + " transition\n"); + ok = 0; + } + } + + if (rect) + treeland_window_transition_rect_v1_destroy(rect); + if (target.surface) + xdg_toplevel_client_destroy(&target); + client_disconnect(&connection); + return ok; +} + +static int run_invalid_geometry(const char *socket_name) +{ + struct client_connection connection = { 0 }; + if (!client_connect(&connection, socket_name)) + return 0; + + struct treeland_window_transition_manager_v1 *manager = + client_bind(&connection, + WINDOW_TRANSITION_MANAGER, + &treeland_window_transition_manager_v1_interface, + treeland_window_transition_manager_v1_interface.version); + if (!manager) { + TEST_ERROR("window-transition: manager missing\n"); + client_disconnect(&connection); + return 0; + } + + struct treeland_window_transition_rect_v1 *rect = + treeland_window_transition_manager_v1_get_window_transition_rect( + manager, "treeland-transition-token-geometry"); + if (!rect) { + TEST_ERROR("window-transition: failed to create the transition rect\n"); + client_disconnect(&connection); + return 0; + } + + /* A negative width or height is the invalid_geometry path. */ + treeland_window_transition_rect_v1_set_geometry(rect, 0, 0, -1, 4); + + const struct wl_interface *error_interface = NULL; + uint32_t error_id = 0; + const int rejected = + wl_display_roundtrip(connection.display) < 0 + && wl_display_get_protocol_error(connection.display, &error_interface, &error_id) + == TREELAND_WINDOW_TRANSITION_RECT_V1_ERROR_INVALID_GEOMETRY + && error_interface == &treeland_window_transition_rect_v1_interface; + if (!rejected) + TEST_ERROR("window-transition: negative geometry did not raise invalid_geometry\n"); + client_disconnect(&connection); + return rejected; +} + +static int run_invalid_surface(const char *socket_name) +{ + struct client_connection connection = { 0 }; + struct xdg_toplevel_client toplevel = { 0 }; + if (!client_connect(&connection, socket_name)) + return 0; + + struct treeland_window_transition_manager_v1 *manager = + client_bind(&connection, + WINDOW_TRANSITION_MANAGER, + &treeland_window_transition_manager_v1_interface, + treeland_window_transition_manager_v1_interface.version); + if (!manager) { + TEST_ERROR("window-transition: manager missing\n"); + client_disconnect(&connection); + return 0; + } + + /* A mapped toplevel already carries an xdg role, so it must be rejected as + * a transition source surface. */ + if (!xdg_toplevel_client_create(&connection, &toplevel)) { + TEST_ERROR("window-transition: failed to create the role-holding toplevel\n"); + treeland_window_transition_manager_v1_destroy(manager); + client_disconnect(&connection); + return 0; + } + + struct treeland_window_transition_rect_v1 *rect = + treeland_window_transition_manager_v1_get_window_transition_rect( + manager, "treeland-transition-token-surface"); + if (!rect) { + TEST_ERROR("window-transition: failed to create the transition rect\n"); + client_disconnect(&connection); + return 0; + } + + treeland_window_transition_rect_v1_set_source_surface(rect, toplevel.surface); + + const struct wl_interface *error_interface = NULL; + uint32_t error_id = 0; + const int rejected = + wl_display_roundtrip(connection.display) < 0 + && wl_display_get_protocol_error(connection.display, &error_interface, &error_id) + == TREELAND_WINDOW_TRANSITION_RECT_V1_ERROR_INVALID_SURFACE + && error_interface == &treeland_window_transition_rect_v1_interface; + if (!rejected) + TEST_ERROR("window-transition: role-holding surface did not raise invalid_surface\n"); + client_disconnect(&connection); + return rejected; +} + +int protocol_test_run(const char *socket_name) +{ + int failed = 0; + if (!run_pending_and_events(socket_name)) + failed = 1; + if (!run_associate_on_activation(socket_name)) + failed = 1; + if (!run_closed_when_activation_late(socket_name)) + failed = 1; + if (!run_discarded_without_origin_surface(socket_name)) + failed = 1; + if (!run_invalid_geometry(socket_name)) + failed = 1; + if (!run_invalid_surface(socket_name)) + failed = 1; + return failed; +} diff --git a/tests/protocols/treeland-window-transition-unstable-v1/treeland-window-transition-unstable-v1.h b/tests/protocols/treeland-window-transition-unstable-v1/treeland-window-transition-unstable-v1.h new file mode 100644 index 0000000000..045fe0f07a --- /dev/null +++ b/tests/protocols/treeland-window-transition-unstable-v1/treeland-window-transition-unstable-v1.h @@ -0,0 +1,44 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Shared POD snapshot between the C client and the C++ fixture. + * + * `token` is an *input*: the client fills it with the activation token string + * passed to get_window_transition_rect before invoking the read on the + * compositor thread, so the callback must not clear it. The remaining fields + * are outputs written on the compositor thread. + * + * The `rect_*` fields describe the rectangle the production manager actually + * handed to a SurfaceWindowTransition, read from that wrapper's real state + * instead of from any wrapper that happens to be armed: + * + * armed_count wrappers whose transition is active() (non-empty rect) + * rect_present an associated rect is reachable (globalRect() has a value) + * rect_mapped that rect's wrapper surface is already mapped + * rect_w/rect_h that rect's size in pixels, 0x0 while it is disabled + * source_set that transition carries a source surface + */ +struct window_transition_server_state { + char token[128]; /* input: token string to query */ + int manager_present; /* output: production manager interface found */ + int pending; /* output: hasPendingWindowTransitionRect(token) */ + int armed_count; /* output: wrappers with an active transition rect */ + int rect_present; /* output: an associated rect is reachable */ + int rect_mapped; /* output: the associated rect's wrapper is mapped */ + int rect_w; /* output: associated rect width in px */ + int rect_h; /* output: associated rect height in px */ + int source_set; /* output: the associated transition has a source surface */ +}; + +void window_transition_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/treeland-wine-window-management-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-wine-window-management-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..3ae5b08252 --- /dev/null +++ b/tests/protocols/treeland-wine-window-management-unstable-v1/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_wine_window_management_unstable_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wine-window-management-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-wine-window-management-unstable-v1.c" +) diff --git a/tests/protocols/treeland-wine-window-management-unstable-v1/README.md b/tests/protocols/treeland-wine-window-management-unstable-v1/README.md new file mode 100644 index 0000000000..d16cab3401 --- /dev/null +++ b/tests/protocols/treeland-wine-window-management-unstable-v1/README.md @@ -0,0 +1,70 @@ +# `treeland-wine-window-management-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`treeland_wine_window_manager_v1` / `treeland_wine_window_control_v1` +- 测试源码:`tests/protocols/treeland-wine-window-management-unstable-v1/` +- Fixture:desktop integration fixture(`protocol_test_setup` 创建 headless output, + `ShellHandler` 为 xdg_toplevel 创建真实 `SurfaceWrapper`) +- 覆盖等级:**P / E** + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | +| --- | --- | --- | +| 初始化 | `get_window_control` | `window_id(>0)` + `configure_position(serial=0)` + `configure_stacking(topmost=0)` | +| Set position | `set_position(100, 200, 1)` | `configure_position` 的 serial 回显为 1 | +| Set z-order topmost | `set_z_order(HWND_TOPMOST, 0)` | `configure_stacking(topmost=1)` | +| Set z-order notopmost | `set_z_order(HWND_NOTOPMOST, 0)` | `configure_stacking(topmost=0)` | + +## 已证明的生产链路 + +客户端创建 xdg_toplevel 后,`ShellHandler` 创建真实 `SurfaceWrapper`。客户端调用 +`get_window_control`,`WineWindowControl` 查找到该 wrapper,记录 `window_id`(单调递增), +连接 `xChanged`、`yChanged` 和 `alwaysOnTopChanged` 信号,然后发送初始 +`configure_position(serial=0)` 和 `configure_stacking(topmost=0)`。初始事件证明 wrapper +创建后位置默认 (0,0) 且非置顶。 + +`set_position(100, 200, 1)` 调用 `wrapper->setPosition(QPointF(100, 200))`。生产代码中 +`m_suppressPositionEvents` 标志被设为 `true` 以避免 wrapper 原生位置变化信号回显 +serial=0;round-trip 后标志复位,后续 `xChanged`/`yChanged` 信号正常触发 +`sendConfigurePosition`。客户端收到的 `configure_position` 中 serial=1 证明请求被正确 +执行并回显。 + +`set_z_order(HWND_TOPMOST, 0)` 调用 `wrapper->setAlwaysOnTop(true)` → +`alwaysOnTopChanged(true)` 信号触发 → 客户端收到 `configure_stacking(topmost=1)`。 +`set_z_order(HWND_NOTOPMOST, 0)` 调用 `wrapper->setAlwaysOnTop(false)` 或 +`stackToLast()` → 客户端收到 `configure_stacking(topmost=0)`。证明 alwaysOnTop +信号链路完整,协议事件与 wrapper 真实置顶状态一致。 + +## E 级观察:QQuickItem 几何与 Z 值 + +E 级测试通过 `invoke_on_server_thread(wine_wm_read_state, &state)` 直接读取 +`SurfaceWrapper` 的 QQuickItem 属性,验证协议事件与渲染树状态一致: + +| 阶段 | `state.x` | `state.y` | `state.z` | `state.effective_always_on_top` | `state.parent_item_count` | +| --- | --- | --- | --- | --- | --- | +| `get_window_control` 后 | ≥0 | ≥0 | **0** | **0** | **≥1** | +| `set_position(100,200)` 后 | **100** | **200** | 0 | 0 | ≥1 | +| `set_z_order(TOPMOST)` 后 | 100 | 200 | **1** | **1** | ≥1 | +| `set_z_order(NOTOPMOST)` 后 | 100 | 200 | **0** | **0** | ≥1 | + +- `x`/`y`:直接对应 `QQuickItem::x()` / `QQuickItem::y()`,由 `setPosition` 驱动。 +- `z`:对应 `QQuickItem::z()`。`HWND_TOPMOST` 时 wrapper 被移到 always-on-top 子容器, + z=1;`HWND_NOTOPMOST` 时移回普通子容器,z=0。 +- `effective_always_on_top`:对应 `SurfaceWrapper::effectiveAlwaysOnTop()`。 + 当 wrapper 处于 TOPMOST 层时为 1,即使 wrapper 本身的 `alwaysOnTop()` 为 false, + 只要其处于 topmost 容器中 `effectiveAlwaysOnTop()` 即返回 true。 +- `parent_item_count`:对应 `parentItem()->childItems().size()`,验证 surface item + 始终在父容器中(minimize 时会从渲染树摘除,E 级不测试该场景)。 + +服务端实现位于 `src/modules/wine-window-management/winewindowmanagement.h`、 +`winewindowmanagement.cpp`。 + +## 已知边界 / 下一项结果 + +- `hwnd_bottom` z-order:需要多个同 session 窗口构造堆叠顺序。 +- `hwnd_insert_after`:需要指定 sibling window,依赖多窗口场景。 +- 无效 `sibling_id` 的错误处理:未验证服务端是否发送协议错误。 +- double-bind 错误:同一 surface 重复调用 `get_window_control` 的行为未测试。 +- 屏幕外坐标:`set_position` 到超出 output 范围的坐标时行为未验证。 diff --git a/tests/protocols/treeland-wine-window-management-unstable-v1/setup.cpp b/tests/protocols/treeland-wine-window-management-unstable-v1/setup.cpp new file mode 100644 index 0000000000..bf60ca54d8 --- /dev/null +++ b/tests/protocols/treeland-wine-window-management-unstable-v1/setup.cpp @@ -0,0 +1,43 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "core/rootsurfacecontainer.h" +#include "core/shellhandler.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" +#include "treeland-wine-window-management-unstable-v1.h" + +#include + +namespace { +SurfaceWrapper *g_wrapper = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() != SurfaceWrapper::Type::XdgToplevel) + return; + g_wrapper = wrapper; + }); +} + +extern "C" void wine_wm_read_state(void *data) +{ + auto *state = static_cast(data); + state->wrapper_created = g_wrapper ? 1 : 0; + state->x = g_wrapper ? static_cast(g_wrapper->x()) : 0; + state->y = g_wrapper ? static_cast(g_wrapper->y()) : 0; + state->always_on_top = g_wrapper && g_wrapper->alwaysOnTop() ? 1 : 0; + // E-level: check effective always-on-top and Qt z value + state->effective_always_on_top = g_wrapper && g_wrapper->effectiveAlwaysOnTop() ? 1 : 0; + state->z = g_wrapper ? static_cast(g_wrapper->z()) : 0; + // E-level: surface must still be in the parent container + state->parent_item_count = g_wrapper && g_wrapper->parentItem() + ? g_wrapper->parentItem()->childItems().size() + : 0; +} diff --git a/tests/protocols/treeland-wine-window-management-unstable-v1/treeland-wine-window-management-unstable-v1.c b/tests/protocols/treeland-wine-window-management-unstable-v1/treeland-wine-window-management-unstable-v1.c new file mode 100644 index 0000000000..a77b268e2a --- /dev/null +++ b/tests/protocols/treeland-wine-window-management-unstable-v1/treeland-wine-window-management-unstable-v1.c @@ -0,0 +1,168 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-wine-window-management-unstable-v1.h" +#include "server-bridge-api.h" +#include "treeland-wine-window-management-unstable-v1-client-protocol.h" + +#include +#include + +static uint32_t received_window_id; +static int received_window_id_count; +static int32_t last_pos_x; +static int32_t last_pos_y; +static uint32_t last_pos_serial; +static int configure_position_count; +static uint32_t last_topmost; +static int configure_stacking_count; + +static void handle_window_id(void *data, + struct treeland_wine_window_control_v1 *control, + uint32_t id) +{ + (void)data; + (void)control; + received_window_id = id; + ++received_window_id_count; +} + +static void handle_configure_position(void *data, + struct treeland_wine_window_control_v1 *control, + int32_t x, + int32_t y, + uint32_t serial) +{ + (void)data; + (void)control; + last_pos_x = x; + last_pos_y = y; + last_pos_serial = serial; + ++configure_position_count; +} + +static void handle_configure_stacking(void *data, + struct treeland_wine_window_control_v1 *control, + uint32_t topmost) +{ + (void)data; + (void)control; + last_topmost = topmost; + ++configure_stacking_count; +} + +static const struct treeland_wine_window_control_v1_listener control_listener = { + .window_id = handle_window_id, + .configure_position = handle_configure_position, + .configure_stacking = handle_configure_stacking, +}; + +static int read_state(struct wine_wm_state *state) +{ + memset(state, 0, sizeof(*state)); + return invoke_on_server_thread(wine_wm_read_state, state); +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + struct xdg_toplevel_client toplevel = {0}; + struct treeland_wine_window_manager_v1 *manager = NULL; + struct treeland_wine_window_control_v1 *control = NULL; + struct wine_wm_state state = {0}; + int stage = 0; + + if (!client_connect(&connection, socket_name)) + return 1; + if (!xdg_toplevel_client_create(&connection, &toplevel)) + goto failed; + stage = 1; + + if (!read_state(&state) || !state.wrapper_created) + goto failed; + + manager = client_bind(&connection, + "treeland_wine_window_manager_v1", + &treeland_wine_window_manager_v1_interface, + 1); + if (!manager) + goto failed; + stage = 2; + + control = treeland_wine_window_manager_v1_get_window_control(manager, toplevel.toplevel); + treeland_wine_window_control_v1_add_listener(control, &control_listener, NULL); + if (wl_display_roundtrip(connection.display) < 0) + goto failed; + stage = 3; + if (received_window_id_count != 1 || received_window_id == 0) + goto failed; + if (configure_position_count < 1 || last_pos_serial != 0) + goto failed; + if (configure_stacking_count < 1 || last_topmost != 0) + goto failed; + + if (!read_state(&state) || !state.wrapper_created) + goto failed; + if (state.z != 0 || state.effective_always_on_top != 0) + goto failed; + if (state.parent_item_count < 1) + goto failed; + stage = 4; + + treeland_wine_window_control_v1_set_position(control, 100, 200, 1); + if (wl_display_roundtrip(connection.display) < 0) + goto failed; + stage = 4; + if (last_pos_serial != 1) + goto failed; + + if (!read_state(&state) || state.x != 100 || state.y != 200) + goto failed; + stage = 5; + + treeland_wine_window_control_v1_set_z_order(control, + TREELAND_WINE_WINDOW_CONTROL_V1_Z_ORDER_OP_HWND_TOPMOST, + 0); + if (wl_display_roundtrip(connection.display) < 0) + goto failed; + stage = 5; + if (last_topmost != 1) + goto failed; + + if (!read_state(&state) || state.z != 1 || state.effective_always_on_top != 1) + goto failed; + stage = 6; + + treeland_wine_window_control_v1_set_z_order(control, + TREELAND_WINE_WINDOW_CONTROL_V1_Z_ORDER_OP_HWND_NOTOPMOST, + 0); + if (wl_display_roundtrip(connection.display) < 0) + goto failed; + stage = 6; + if (last_topmost != 0) + goto failed; + + if (!read_state(&state) || state.z != 0 || state.effective_always_on_top != 0) + goto failed; + + treeland_wine_window_control_v1_destroy(control); + treeland_wine_window_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&toplevel); + client_disconnect(&connection); + return 0; + +failed: + fprintf(stderr, + "wine-window-management failure at stage %d: window_id=%u(%d) pos=(%d,%d) serial=%u(%d) " + "topmost=%u(%d) z=%d effective_top=%d parent_items=%d\n", + stage, received_window_id, received_window_id_count, + last_pos_x, last_pos_y, last_pos_serial, configure_position_count, + last_topmost, configure_stacking_count, + state.z, state.effective_always_on_top, state.parent_item_count); + if (control) + treeland_wine_window_control_v1_destroy(control); + if (manager) + treeland_wine_window_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&toplevel); + client_disconnect(&connection); + return 1; +} diff --git a/tests/protocols/treeland-wine-window-management-unstable-v1/treeland-wine-window-management-unstable-v1.h b/tests/protocols/treeland-wine-window-management-unstable-v1/treeland-wine-window-management-unstable-v1.h new file mode 100644 index 0000000000..62ba3a2bf4 --- /dev/null +++ b/tests/protocols/treeland-wine-window-management-unstable-v1/treeland-wine-window-management-unstable-v1.h @@ -0,0 +1,28 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef WINE_WM_TEST_H +#define WINE_WM_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "client-connection.h" +#include "xdg-toplevel-client.h" + +struct wine_wm_state { + int wrapper_created; + int x; + int y; + int always_on_top; // explicit flag from wrapper->alwaysOnTop() + int effective_always_on_top; // E-level: effective flag (includes parent inheritance) + int z; // E-level: QQuickItem z value (1 = always-on-top layer) + int parent_item_count; // E-level: for verifying surface is in parent container +}; + +extern void wine_wm_read_state(void *data); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/treeland-wine-window-state-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-wine-window-state-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..8975e2744c --- /dev/null +++ b/tests/protocols/treeland-wine-window-state-unstable-v1/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_wine_window_state_unstable_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wine-window-state-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-wine-window-state-unstable-v1.c" +) diff --git a/tests/protocols/treeland-wine-window-state-unstable-v1/README.md b/tests/protocols/treeland-wine-window-state-unstable-v1/README.md new file mode 100644 index 0000000000..1fd141c2a5 --- /dev/null +++ b/tests/protocols/treeland-wine-window-state-unstable-v1/README.md @@ -0,0 +1,71 @@ +# `treeland-wine-window-state-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`treeland_wine_window_state_manager_v1` / `treeland_wine_window_state_v1` +- 测试源码:`tests/protocols/treeland-wine-window-state-unstable-v1/` +- Fixture:desktop integration fixture(`protocol_test_setup` 创建 headless output, + `ShellHandler` 为 xdg_toplevel 创建真实 `SurfaceWrapper`) +- 覆盖等级:**P / E** + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | +| --- | --- | --- | +| 初始 state | 创建 xdg_toplevel + `get_window_state` | `state_changed(0)`(无 MINIMIZED、无 ATTENTION) | +| Minimize | 服务端 minimize wrapper | `state_changed(MINIMIZED)` | +| Set attention | 窗口处于 minimized(非激活)状态时 `set_attention(0,0)` | `state_changed(MINIMIZED \| ATTENTION)` | +| Clear attention | `clear_attention()` | `state_changed(MINIMIZED)`(无 ATTENTION) | +| Unminimize | `unminimize()` | `state_changed(0)`(无 MINIMIZED) | + +## 已证明的生产链路 + +客户端创建 xdg_toplevel 后,`ShellHandler::onXdgToplevelSurfaceAdded` 创建真实 +`SurfaceWrapper` 并加入 `Workspace`。客户端调用 `get_window_state` 时, +`WineWindowState` 通过 `WaylandServer::rootSurfaceContainer()->getSurface()` 查找到该 wrapper, +连接 `minimizeChanged` 和 `attentionChanged` 信号。初始 `state_changed(0)` 证明 wrapper +创建后未最小化、未需要关注,与协议事件一致。 + +Fixture 对 wrapper 调用 `minimize()` → `minimizeChanged(true)` 信号触发 +`WineWindowState::send_state_changed` → 客户端收到 `state_changed(MINIMIZED)`。证明 +minimize 信号链路完整。 + +在 minimized 状态下,客户端发送 `set_attention(0,0)`。生产代码中 +`SurfaceWrapper::setAttention(true)` 对已激活窗口有守卫(直接拒绝),因此 fixture 先 +minimize 使窗口失活,确保 `setAttention(true)` 可正常执行。`attentionChanged(true)` 信号 +触发 → 客户端收到 `state_changed(MINIMIZED|ATTENTION)`。`clear_attention()` 调用 +`SurfaceWrapper::setAttention(false)` → `attentionChanged(false)` → 客户端收到 +`state_changed(MINIMIZED)`。 + +`unminimize()` 调用 `SurfaceWrapper::restoreFromMinimized()` → `minimizeChanged(false)` +→ 客户端收到 `state_changed(0)`。整个过程证明 `minimizeChanged` 和 `attentionChanged` +信号均通过 `WineWindowState` 正确转发为协议事件,且事件中的 state 位掩码与 wrapper 真实 +状态完全一致。 + +## E 级观察:QQuickItem 可见性 + +E 级测试通过 `invoke_on_server_thread(wine_ws_read_state, &state)` 直接读取 +`SurfaceWrapper` 的 QQuickItem 属性,验证协议事件与渲染树状态一致: + +| 阶段 | `state.minimized` | `state.visible` | 含义 | +| --- | --- | --- | --- | +| `get_window_state` 后 | 0 | **1** | surface 已在渲染树中可见 | +| `minimize()` 后 | 1 | **0** | surface 从渲染树隐藏(`isVisible()=false`) | +| `set_attention()` 后 | 1 | **0** | attention 标志置位,但 surface 仍隐藏 | +| `clear_attention()` 后 | 1 | **0** | attention 标志清除,surface 仍隐藏 | +| `unminimize()` 后 | 0 | **1** | surface 恢复到渲染树,可见 | + +`visible` 字段对应 `SurfaceWrapper::isVisible()` → 最终映射到 +`QQuickItem::isVisible()`。协议层 `MINIMIZED` 状态位与 QQuickItem 渲染树可见性严格同步, +minimize 时 `SurfaceWrapper::setVisible(false)` 将 surface item 从父容器摘除, +restore 时重新加入。 + +服务端实现位于 `src/modules/wine-window-state/winewindowstate.h`、 +`winewindowstate.cpp`。 + +## 已知边界 / 下一项结果 + +- `activate` 请求:需要窗口处于非激活且非最小化状态,headless 环境中难以构造该条件。 +- `activate_denied` 事件:同上,依赖 activate 请求路径。 +- double-bind 错误:同一 surface 重复调用 `get_window_state` 的行为未测试。 +- inert 对象:xdg_toplevel 销毁后 `wine_window_state_v1` 对象应变为 inert,未验证。 diff --git a/tests/protocols/treeland-wine-window-state-unstable-v1/setup.cpp b/tests/protocols/treeland-wine-window-state-unstable-v1/setup.cpp new file mode 100644 index 0000000000..208f78b4b1 --- /dev/null +++ b/tests/protocols/treeland-wine-window-state-unstable-v1/setup.cpp @@ -0,0 +1,60 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "core/shellhandler.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" +#include "treeland-wine-window-state-unstable-v1.h" + +#include + +namespace { +SurfaceWrapper *g_wrapper = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() != SurfaceWrapper::Type::XdgToplevel) + return; + g_wrapper = wrapper; + }); +} + +extern "C" void wine_ws_read_state(void *data) +{ + auto *state = static_cast(data); + state->wrapper_created = g_wrapper ? 1 : 0; + state->minimized = (g_wrapper && g_wrapper->isMinimized()) ? 1 : 0; + state->attention = (g_wrapper && g_wrapper->attention()) ? 1 : 0; + // E-level: check QQuickItem visibility -- minimized surface must be hidden + state->visible = (g_wrapper && g_wrapper->isVisible()) ? 1 : 0; +} + +extern "C" void wine_ws_minimize_wrapper(void *) +{ + if (g_wrapper) + g_wrapper->minimize(); +} + +extern "C" void wine_ws_unminimize_wrapper(void *) +{ + if (g_wrapper) + g_wrapper->restoreFromMinimized(); +} + +extern "C" void wine_ws_set_attention(void *) +{ + if (g_wrapper) + g_wrapper->setAttention(true); +} + +extern "C" void wine_ws_clear_attention(void *) +{ + if (g_wrapper) + g_wrapper->setAttention(false); +} diff --git a/tests/protocols/treeland-wine-window-state-unstable-v1/treeland-wine-window-state-unstable-v1.c b/tests/protocols/treeland-wine-window-state-unstable-v1/treeland-wine-window-state-unstable-v1.c new file mode 100644 index 0000000000..3cc2ab4dbf --- /dev/null +++ b/tests/protocols/treeland-wine-window-state-unstable-v1/treeland-wine-window-state-unstable-v1.c @@ -0,0 +1,165 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-wine-window-state-unstable-v1.h" +#include "server-bridge-api.h" +#include "treeland-wine-window-state-unstable-v1-client-protocol.h" + +#include +#include + +extern void wine_ws_read_state(void *data); +extern void wine_ws_minimize_wrapper(void *); +extern void wine_ws_unminimize_wrapper(void *); +extern void wine_ws_set_attention(void *); +extern void wine_ws_clear_attention(void *); + +struct wine_ws_client { + uint32_t last_state; + int state_events; +}; + +static void handle_state_changed(void *data, + struct treeland_wine_window_state_v1 *state, + uint32_t ws_state) +{ + (void)state; + struct wine_ws_client *client = data; + client->last_state = ws_state; + ++client->state_events; +} + +static void handle_activate_denied(void *data, + struct treeland_wine_window_state_v1 *state, + uint32_t serial) +{ + (void)data; + (void)state; + (void)serial; +} + +static const struct treeland_wine_window_state_v1_listener state_listener = { + .state_changed = handle_state_changed, + .activate_denied = handle_activate_denied, +}; + +static int read_state(struct wine_ws_state *state) +{ + memset(state, 0, sizeof(*state)); + return invoke_on_server_thread(wine_ws_read_state, state); +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + struct xdg_toplevel_client toplevel = { 0 }; + struct treeland_wine_window_state_manager_v1 *manager = NULL; + struct treeland_wine_window_state_v1 *ws = NULL; + struct wine_ws_client client = { 0 }; + struct wine_ws_state state = { 0 }; + int stage = 0; + + if (!client_connect(&connection, socket_name)) + return 1; + stage = 1; + + if (!xdg_toplevel_client_create(&connection, &toplevel)) + goto failed; + stage = 2; + + if (wl_display_roundtrip(connection.display) < 0) + goto failed; + if (!read_state(&state) || !state.wrapper_created) + goto failed; + stage = 3; + + manager = client_bind(&connection, + "treeland_wine_window_state_manager_v1", + &treeland_wine_window_state_manager_v1_interface, + 1); + if (!manager) + goto failed; + stage = 4; + + client.state_events = 0; + client.last_state = 0; + ws = treeland_wine_window_state_manager_v1_get_window_state(manager, toplevel.toplevel); + treeland_wine_window_state_v1_add_listener(ws, &state_listener, &client); + if (wl_display_roundtrip(connection.display) < 0) + goto failed; + if (client.state_events < 1 || client.last_state != 0) + goto failed; + + if (!read_state(&state) || !state.visible) + goto failed; + stage = 5; + + client.state_events = 0; + client.last_state = 0; + invoke_on_server_thread(wine_ws_minimize_wrapper, NULL); + if (wl_display_roundtrip(connection.display) < 0) + goto failed; + if (client.state_events < 1 + || !(client.last_state & TREELAND_WINE_WINDOW_STATE_V1_STATE_MINIMIZED)) + goto failed; + + if (!read_state(&state) || state.minimized != 1 || state.visible != 0) + goto failed; + stage = 6; + + client.state_events = 0; + client.last_state = 0; + treeland_wine_window_state_v1_set_attention(ws, 0, 0); + if (wl_display_roundtrip(connection.display) < 0) + goto failed; + if (client.state_events < 1 + || !(client.last_state & (TREELAND_WINE_WINDOW_STATE_V1_STATE_MINIMIZED + | TREELAND_WINE_WINDOW_STATE_V1_STATE_ATTENTION))) + goto failed; + if (!read_state(&state) || state.attention != 1 || state.visible != 0) + goto failed; + stage = 7; + + client.state_events = 0; + client.last_state = 0; + treeland_wine_window_state_v1_clear_attention(ws); + if (wl_display_roundtrip(connection.display) < 0) + goto failed; + if (client.state_events < 1 + || (client.last_state & TREELAND_WINE_WINDOW_STATE_V1_STATE_ATTENTION)) + goto failed; + if (!read_state(&state) || state.attention != 0 || state.visible != 0) + goto failed; + stage = 8; + + client.state_events = 0; + client.last_state = 0; + treeland_wine_window_state_v1_unminimize(ws); + if (wl_display_roundtrip(connection.display) < 0) + goto failed; + if (client.state_events < 1 + || (client.last_state & TREELAND_WINE_WINDOW_STATE_V1_STATE_MINIMIZED)) + goto failed; + + if (!read_state(&state) || state.minimized != 0 || state.visible != 1) + goto failed; + + treeland_wine_window_state_v1_destroy(ws); + treeland_wine_window_state_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&toplevel); + client_disconnect(&connection); + return 0; + +failed: + fprintf(stderr, + "wine-window-state failure at stage %d: state=0x%x events=%d " + "wrapper=%d minimized=%d attention=%d visible=%d\n", + stage, client.last_state, client.state_events, + state.wrapper_created, state.minimized, state.attention, state.visible); + if (ws) + treeland_wine_window_state_v1_destroy(ws); + if (manager) + treeland_wine_window_state_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&toplevel); + client_disconnect(&connection); + return 1; +} diff --git a/tests/protocols/treeland-wine-window-state-unstable-v1/treeland-wine-window-state-unstable-v1.h b/tests/protocols/treeland-wine-window-state-unstable-v1/treeland-wine-window-state-unstable-v1.h new file mode 100644 index 0000000000..152d99ef79 --- /dev/null +++ b/tests/protocols/treeland-wine-window-state-unstable-v1/treeland-wine-window-state-unstable-v1.h @@ -0,0 +1,24 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "client-connection.h" +#include "xdg-toplevel-client.h" + +struct wine_ws_state { + int wrapper_created; + int minimized; + int attention; + int visible; // E-level: QQuickItem visibility (reflects isMinimized() → setVisible(false)) +}; + +int protocol_test_run(const char *socket_name); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/treeland-xwindow-control-unstable-v1/CMakeLists.txt b/tests/protocols/treeland-xwindow-control-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..9795e7db0e --- /dev/null +++ b/tests/protocols/treeland-xwindow-control-unstable-v1/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME treeland_xwindow_control_v1 + XML "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-xwindow-control-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/treeland-xwindow-control-unstable-v1.c" +) diff --git a/tests/protocols/treeland-xwindow-control-unstable-v1/README.md b/tests/protocols/treeland-xwindow-control-unstable-v1/README.md new file mode 100644 index 0000000000..b3ba39fc1a --- /dev/null +++ b/tests/protocols/treeland-xwindow-control-unstable-v1/README.md @@ -0,0 +1,42 @@ +# `treeland-xwindow-control-unstable-v1` 测试规范 + +## 范围 + +仅在 `DISABLE_XWAYLAND=OFF` 时构建并注册本测试;关闭 Xwayland 时,生产模块与对应 global 一并移除。 + +- XML / interface:`treeland_xwindow_control_v1`(v1) +- 测试源码:`tests/protocols/treeland-xwindow-control-unstable-v1/` +- Fixture:`protocol_test_setup` 注册生产 `XWindowControlInterfaceV1` 全局并创建 + headless output(仅协议/资源级,无需 mapped 窗口) +- 覆盖等级:**P** + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 初始化 | bind `treeland_xwindow_control_v1` | manager 非空 | P | +| 请求(失败) | `set_xwindow_position_relative`,anchor 为无对应 `SurfaceWrapper` 的裸 `wl_surface`、wid=0 | `wl_callback.done(1)` | P | +| 资源销毁 | `destroy` | 资源销毁,无协议错误 | P | + +## 生产结果 + +`set_xwindow_position_relative` 在服务端解析 anchor `wl_surface` 为 `WSurface`,再交给 +`WaylandServer::setXWindowPositionRelative(wid, wsurface, dx, dy)`。失败路径测试证明:当 anchor +`wl_surface` 没有 `SurfaceWrapper`(裸 surface)且 wid 为 0 时,`WaylandServer` 返回 false, +服务端把结果 `1` 通过新建的 `wl_callback` 回传并销毁该 callback。 + +`XWindowControlInterfaceV1Private` 在 `wl_resource_create` 分配 callback 失败时会调用 +`wl_client_post_no_memory` 并中止该请求,避免对 null callback 解引用导致合成器崩溃;该 +OOM 分支不在测试中强制触发(无法稳定注入 Wayland 内存分配失败)。 + +## 已知边界 / 下一项结果 + +- **成功路径(callback.done(0))未覆盖**:`WaylandServer::setXWindowPositionRelative` 要求 anchor + 拥有真实 `SurfaceWrapper`,且 wid 匹配一个已映射的 `Type::XWayland` `SurfaceWrapper`。 + 生成一个真实的 XWayland 窗口需要可用的 Xwayland 实例;treeland 协议测试在 + `WLR_BACKENDS=headless`、`WLR_RENDERER=pixman` 下运行,Xwayland 启动时 glamor 需要 + GBM Wayland 接口,无 GPU 环境下无法启动,因此无法在当前 CI 中产出 XWayland + `SurfaceWrapper`。成功路径(wid 匹配、目标位置 == anchor.topLeft + (dx,dy))作为下一项 + 待验证结果,前提是具备可运行的 Xwayland 测试环境(GPU 或软件 glamor)。 +- 无效 anchor(客户端传入 null 或非 `wl_surface` 对象)已被服务端守卫为失败结果 + (`callback.done(1)`),但未单列为测试用例;可在具备成功路径环境后补充错误注入用例。 diff --git a/tests/protocols/treeland-xwindow-control-unstable-v1/setup.cpp b/tests/protocols/treeland-xwindow-control-unstable-v1/setup.cpp new file mode 100644 index 0000000000..6deb190637 --- /dev/null +++ b/tests/protocols/treeland-xwindow-control-unstable-v1/setup.cpp @@ -0,0 +1,13 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "modules/xwindow-control/xwindowcontrolinterfacev1.h" +#include "server-bridge.h" + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +void protocol_test_setup(WaylandServer *server) +{ + find_server_interface(server); +} diff --git a/tests/protocols/treeland-xwindow-control-unstable-v1/treeland-xwindow-control-unstable-v1.c b/tests/protocols/treeland-xwindow-control-unstable-v1/treeland-xwindow-control-unstable-v1.c new file mode 100644 index 0000000000..2623bf84fe --- /dev/null +++ b/tests/protocols/treeland-xwindow-control-unstable-v1/treeland-xwindow-control-unstable-v1.c @@ -0,0 +1,168 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "treeland-xwindow-control-unstable-v1.h" +#include "server-bridge-api.h" +#include "treeland-xwindow-control-unstable-v1-client-protocol.h" + +#include +#include +#include +#include +#include + +struct test_case { + const char *name; + int (*run)(struct test_ctx *ctx); +}; + +void test_init(struct test_ctx *ctx) +{ + memset(ctx, 0, sizeof(*ctx)); + ctx->result_cap = 32; + ctx->results = calloc(ctx->result_cap, sizeof(*ctx->results)); +} + +void test_destroy(struct test_ctx *ctx) +{ + free(ctx->results); + memset(ctx, 0, sizeof(*ctx)); +} + +int test_add(struct test_ctx *ctx, const char *name) +{ + if (ctx->result_count == ctx->result_cap) { + ctx->result_cap *= 2; + ctx->results = realloc(ctx->results, (size_t)ctx->result_cap * sizeof(*ctx->results)); + } + const int index = ctx->result_count++; + ctx->results[index] = (struct test_result) { .name = name }; + return index; +} + +void test_fail(struct test_ctx *ctx, int index, const char *format, ...) +{ + va_list arguments; + va_start(arguments, format); + vsnprintf(ctx->results[index].message, TEST_MSG_MAX, format, arguments); + va_end(arguments); + ctx->results[index].failed = 1; +} + +void test_pass(struct test_ctx *ctx, int index) +{ + ctx->results[index].failed = 0; +} + +int test_print_results(struct test_ctx *ctx) +{ + int failed = 0; + printf("\n=== results ===\n"); + for (int i = 0; i < ctx->result_count; ++i) { + printf(" [%s] %s", ctx->results[i].failed ? "FAIL" : "PASS", ctx->results[i].name); + if (ctx->results[i].failed) { + printf(" -- %s", ctx->results[i].message); + ++failed; + } + printf("\n"); + } + printf("%d/%d passed\n", ctx->result_count - failed, ctx->result_count); + return failed == 0; +} + +static int connect_client(struct test_ctx *ctx, const char *socket_name) +{ + if (!client_connect(&ctx->connection, socket_name)) + return 0; + ctx->display = ctx->connection.display; + ctx->compositor = client_bind(&ctx->connection, "wl_compositor", &wl_compositor_interface, 1); + ctx->manager = client_bind(&ctx->connection, "treeland_xwindow_control_v1", + &treeland_xwindow_control_v1_interface, 1); + return ctx->manager != NULL; +} + +static int bind_manager(struct test_ctx *ctx) +{ + return ctx->manager != NULL; +} + +static void callback_done(void *data, struct wl_callback *callback, uint32_t result) +{ + (void)callback; + struct test_ctx *ctx = data; + ctx->callback_received = 1; + ctx->callback_result = result; +} + +static const struct wl_callback_listener callback_listener = { + .done = callback_done, +}; + +static int set_xwindow_position_relative(struct test_ctx *ctx) +{ + if (!ctx->compositor || !ctx->manager) + return 0; + struct wl_surface *surface = wl_compositor_create_surface(ctx->compositor); + if (!surface) + return 0; + wl_fixed_t dx = wl_fixed_from_int(0); + wl_fixed_t dy = wl_fixed_from_int(0); + struct wl_callback *cb = + treeland_xwindow_control_v1_set_xwindow_position_relative(ctx->manager, 0, surface, dx, dy); + if (!cb) + return 0; + wl_callback_add_listener(cb, &callback_listener, ctx); + wl_surface_destroy(surface); + return 1; +} + +static int callback_failure_received(struct test_ctx *ctx) +{ + return ctx->callback_received && ctx->callback_result == 1; +} + +static int destroy_manager(struct test_ctx *ctx) +{ + if (!ctx->manager) + return 0; + treeland_xwindow_control_v1_destroy(ctx->manager); + ctx->manager = NULL; + return 1; +} + +static const struct test_case cases[] = { + { "manager.bind", bind_manager }, + { "request.set_xwindow_position_relative", set_xwindow_position_relative }, + { "callback.done(failure)", callback_failure_received }, + { "manager.destroy", destroy_manager }, +}; + +void test_cleanup(struct test_ctx *ctx) +{ + if (ctx->manager) treeland_xwindow_control_v1_destroy(ctx->manager); + client_disconnect(&ctx->connection); +} + +int protocol_test_run(const char *socket_name) +{ + struct test_ctx ctx; + test_init(&ctx); + if (!connect_client(&ctx, socket_name)) { + fprintf(stderr, "failed to connect to or bind treeland_xwindow_control_v1\n"); + test_cleanup(&ctx); + test_destroy(&ctx); + return 1; + } + + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const int result = test_add(&ctx, cases[i].name); + if (!cases[i].run(&ctx)) + test_fail(&ctx, result, "assertion failed"); + if (wl_display_roundtrip(ctx.display) < 0) + test_fail(&ctx, result, "Wayland connection failed"); + } + + test_cleanup(&ctx); + const int success = test_print_results(&ctx); + test_destroy(&ctx); + return success ? 0 : 1; +} diff --git a/tests/protocols/treeland-xwindow-control-unstable-v1/treeland-xwindow-control-unstable-v1.h b/tests/protocols/treeland-xwindow-control-unstable-v1/treeland-xwindow-control-unstable-v1.h new file mode 100644 index 0000000000..ee5315dfa8 --- /dev/null +++ b/tests/protocols/treeland-xwindow-control-unstable-v1/treeland-xwindow-control-unstable-v1.h @@ -0,0 +1,51 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#ifndef XWINDOW_CONTROL_TEST_H +#define XWINDOW_CONTROL_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +int protocol_test_run(const char *socket_name); + +#include "client-connection.h" + +struct treeland_xwindow_control_v1; + +#define TEST_MSG_MAX 256 + +struct test_result { + const char *name; + int failed; + char message[TEST_MSG_MAX]; +}; + +struct test_ctx { + struct client_connection connection; + struct wl_display *display; + + struct wl_compositor *compositor; + struct treeland_xwindow_control_v1 *manager; + + int callback_received; + uint32_t callback_result; + + struct test_result *results; + int result_count; + int result_cap; +}; + +void test_init(struct test_ctx *ctx); +void test_destroy(struct test_ctx *ctx); +int test_add(struct test_ctx *ctx, const char *name); +void test_fail(struct test_ctx *ctx, int idx, const char *fmt, ...); +void test_pass(struct test_ctx *ctx, int idx); + +int test_print_results(struct test_ctx *ctx); +void test_cleanup(struct test_ctx *ctx); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tests/protocols/virtual-keyboard-unstable-v1/CMakeLists.txt b/tests/protocols/virtual-keyboard-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..8dd0fa08aa --- /dev/null +++ b/tests/protocols/virtual-keyboard-unstable-v1/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +treeland_add_protocol_test( + NAME virtual_keyboard_unstable_v1 + XML "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/virtual-keyboard-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/virtual-keyboard-unstable-v1.c" +) diff --git a/tests/protocols/virtual-keyboard-unstable-v1/README.md b/tests/protocols/virtual-keyboard-unstable-v1/README.md new file mode 100644 index 0000000000..ca1a1e9406 --- /dev/null +++ b/tests/protocols/virtual-keyboard-unstable-v1/README.md @@ -0,0 +1,49 @@ +# `virtual-keyboard-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`3rdparty/wlroots/protocol/virtual-keyboard-unstable-v1.xml` / + `zwp_virtual_keyboard_manager_v1`、`zwp_virtual_keyboard_v1` v1 +- 测试源码:`tests/protocols/treeland-shortcut-manager-desktop-v2/` +- Fixture:完整生产 `Treeland` / `WaylandServer`、headless output、mapped 且 keyboard-focused xdg toplevel。 +- 覆盖等级:**P / E(作为 shortcut desktop 测试的依赖协议)**。 + +## 必须观察到的结果 + +| XML 语义 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 创建并提供 keymap | `create_virtual_keyboard(seat)`,以有效 XKB V1 keymap 调用 `keymap` | keyboard 可用,无协议错误 | P | +| raw key 注入 | 调用 `key` 按下/释放 F1、F2 | 已聚焦的生产 shortcut manager 捕获 F1,并因 F2 激活已注册 shortcut | E | +| modifier 注入 | 有效 keymap 后调用 `modifiers(1,0,0,0)` | 已聚焦 app 从真实 `WSeat` 收到 `wl_keyboard.modifiers`,depressed 为 1 | E | +| keymap 前输入 | 两个独立 client 各自在未 keymap 时调用 `key` 或 `modifiers` | display 因 `zwp_virtual_keyboard_v1.error.no_keymap` 断开 | P | +| 资源生命周期 | `destroy` virtual keyboard | client 正常销毁资源,无 use-after-free 或协议错误 | P | + +## 生产结果 + +wlroots 提供 native `wlr_virtual_keyboard_manager_v1`。waylib 的 +`WVirtualKeyboardManagerV1` 创建该 global;它由 +`WaylandServer::init() → ShellHandler::init() → WInputMethodHelper` 调用 +`WServer::attach()` 接入。新 virtual keyboard 被 helper 包装为 +`WInputDevice` 并 attach 到生产 `WSeat`,由 wlroots 管理 native resource 的 display 生命周期。 + +### E 级证据 + +测试 client 在真实 `WSeat` 上创建 virtual keyboard,并把有效 XKB keymap 交给 wlroots。 +注入的 F1/F2 不由测试 fixture 直接模拟:它们先进入生产 seat,再由已聚焦窗口上的生产 +shortcut manager 捕获,分别得到 capture 和已注册 shortcut 的 activate 结果。`modifiers(1,0,0,0)` +同样经过真实 seat,已聚焦 app 的 `wl_keyboard` listener 必须收到 depressed 为 1 的 event。 + +故按键和 modifier 的 seat/shortcut 链路是 E 级;keymap 前的 `no_keymap` 错误与 object destroy +仅为 P 级。 + +## 已知边界 / 下一项结果 + +现有客户端直接调用 XML 的全部 **5 / 5 request**:manager `create_virtual_keyboard`、keyboard 的 +`keymap`、`key`、`modifiers`、`destroy`。 + +尚未覆盖: + +- compositor 授权策略的 `unauthorized` error。当前测试环境允许 test client 创建 virtual keyboard, + 而 wlroots native implementation 也没有授权 callback 或 trusted-client 判定;在引入实际授权策略前, + 不能构造有意义的拒绝断言; +- modifier 对更多组合快捷键、锁定 modifier 与 layout group 的行为。 diff --git a/tests/protocols/virtual-keyboard-unstable-v1/setup.cpp b/tests/protocols/virtual-keyboard-unstable-v1/setup.cpp new file mode 100644 index 0000000000..882458a97c --- /dev/null +++ b/tests/protocols/virtual-keyboard-unstable-v1/setup.cpp @@ -0,0 +1,12 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "server-bridge.h" +#include "core/waylandserver.h" + +#include + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); +} diff --git a/tests/protocols/virtual-keyboard-unstable-v1/virtual-keyboard-unstable-v1.c b/tests/protocols/virtual-keyboard-unstable-v1/virtual-keyboard-unstable-v1.c new file mode 100644 index 0000000000..49b04d0e04 --- /dev/null +++ b/tests/protocols/virtual-keyboard-unstable-v1/virtual-keyboard-unstable-v1.c @@ -0,0 +1,43 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "client-connection.h" +#include "virtual-keyboard-unstable-v1-client-protocol.h" + +static int expect_no_keymap(const char *socket_name, int modifiers) +{ + struct client_connection connection = {0}; + if (!client_connect(&connection, socket_name)) + return 0; + struct wl_seat *seat = client_bind(&connection, "wl_seat", &wl_seat_interface, 1); + struct zwp_virtual_keyboard_manager_v1 *manager = client_bind( + &connection, "zwp_virtual_keyboard_manager_v1", &zwp_virtual_keyboard_manager_v1_interface, 1); + if (!seat || !manager) + goto failed; + struct zwp_virtual_keyboard_v1 *keyboard = + zwp_virtual_keyboard_manager_v1_create_virtual_keyboard(manager, seat); + if (!keyboard) + goto failed; + if (modifiers) + zwp_virtual_keyboard_v1_modifiers(keyboard, 1, 0, 0, 0); + else + zwp_virtual_keyboard_v1_key(keyboard, 0, 59, WL_KEYBOARD_KEY_STATE_PRESSED); + + const struct wl_interface *interface = NULL; + uint32_t code = 0; + const int rejected = wl_display_roundtrip(connection.display) < 0 + && wl_display_get_protocol_error(connection.display, &interface, &code) + == ZWP_VIRTUAL_KEYBOARD_V1_ERROR_NO_KEYMAP + && interface == &zwp_virtual_keyboard_v1_interface; + client_disconnect(&connection); + return rejected; + +failed: + client_disconnect(&connection); + return 0; +} + +int protocol_test_run(const char *socket_name) +{ + return expect_no_keymap(socket_name, 0) && expect_no_keymap(socket_name, 1) ? 0 : 1; +} diff --git a/tests/protocols/wayland-alpha-modifier-v1/CMakeLists.txt b/tests/protocols/wayland-alpha-modifier-v1/CMakeLists.txt new file mode 100644 index 0000000000..a9bccb0aad --- /dev/null +++ b/tests/protocols/wayland-alpha-modifier-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_alpha_modifier_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/alpha-modifier/alpha-modifier-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-alpha-modifier-v1.c" +) diff --git a/tests/protocols/wayland-alpha-modifier-v1/README.md b/tests/protocols/wayland-alpha-modifier-v1/README.md new file mode 100644 index 0000000000..265ff25b5d --- /dev/null +++ b/tests/protocols/wayland-alpha-modifier-v1/README.md @@ -0,0 +1,33 @@ +# `wayland-alpha-modifier-v1` 测试规范 + +## 范围 + +- XML / interface:`wp_alpha_modifier_v1` / `wp_alpha_modifier_surface_v1`(version 1,无事件) +- 测试源码:`tests/protocols/wayland-alpha-modifier-v1/` +- Fixture:headless output fixture + xdg-toplevel-client(64×64 solid buffer 映射) +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `wp_alpha_modifier_v1`(v1) | 资源创建成功 | P | +| 关联表面 | `get_surface(surface)` | 返回非 NULL 的 `wp_alpha_modifier_surface_v1` | P | +| 设置透明度 0 | `set_multiplier(0)` + `commit` | 无协议错误 | P | +| 设置不透明度 | `set_multiplier(UINT32_MAX)` + `commit` | 无协议错误 | P | +| 真实乘数 0 | 回读真实 `wlr_alpha_modifier_surface_v1_state::multiplier` | == 0.0 | E | +| 真实乘数 1 | 回读真实 `wlr_alpha_modifier_surface_v1_state::multiplier` | == 1.0 | E | + +## 生产结果 + +测试创建并映射一个真实 xdg_toplevel,为其附加 `wp_alpha_modifier_surface_v1` 对象。 +先调用 `set_multiplier(0)` 并提交,通过 server bridge 回读真实 +`wlr_alpha_modifier_v1_get_surface_state(wlr_surface)->multiplier`,断言为 0.0; +再调用 `set_multiplier(UINT32_MAX)` 并提交,回读断言为 1.0。`set_multiplier` 是双缓冲 +状态,在 `wl_surface.commit` 后由 wlroots 将 uint32 因子转换为 double(÷UINT32_MAX) +并写入 `wlr_alpha_modifier_surface_v1_state`,因此此断言验证请求确实到达了真实合成器 +surface 管线。 + +## 已知边界 / 下一项结果 + +未验证中间值(如 0x80808080)的浮点精度,也未验证 alpha 修饰对渲染输出的实际像素效果(V 级)。 diff --git a/tests/protocols/wayland-alpha-modifier-v1/setup.cpp b/tests/protocols/wayland-alpha-modifier-v1/setup.cpp new file mode 100644 index 0000000000..ad731639c3 --- /dev/null +++ b/tests/protocols/wayland-alpha-modifier-v1/setup.cpp @@ -0,0 +1,60 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-alpha-modifier-v1.h" +#include "server-bridge.h" +#include "core/shellhandler.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" + +#include +#include +#include +#include + +namespace { +// The real mapped XdgToplevel SurfaceWrapper created by the client. +SurfaceWrapper *g_wrapper = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() == SurfaceWrapper::Type::XdgToplevel) + g_wrapper = wrapper; + }); +} + +// E-level read: report the captured production SurfaceWrapper's alpha-modifier +// multiplier. wlroots stores this as a double in [0, 1], updated on commit +// when the client calls wp_alpha_modifier_surface_v1.set_multiplier. +void alpha_modifier_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = 0; + state->has_modifier = 0; + state->multiplier = 0.0; + + if (!g_wrapper) + return; + + auto *wsurface = g_wrapper->surface(); + if (!wsurface) + return; + + state->valid = 1; + + auto *wlr_surf = wsurface->handle(); + if (!wlr_surf) + return; + + const auto *am_state = wlr_alpha_modifier_v1_get_surface_state(wlr_surf); + if (am_state) { + state->has_modifier = 1; + state->multiplier = am_state->multiplier; + } +} diff --git a/tests/protocols/wayland-alpha-modifier-v1/wayland-alpha-modifier-v1.c b/tests/protocols/wayland-alpha-modifier-v1/wayland-alpha-modifier-v1.c new file mode 100644 index 0000000000..64cb874f14 --- /dev/null +++ b/tests/protocols/wayland-alpha-modifier-v1/wayland-alpha-modifier-v1.c @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Test the wp_alpha_modifier_v1 global created by wlr_alpha_modifier_v1_create + * in Treeland's WaylandServer. + * + * Coverage level E (end-to-end): the client maps a real xdg_toplevel, attaches + * an alpha-modifier surface object, sets the multiplier to 0 (fully + * transparent) and then to UINT32_MAX (fully opaque), committing after each + * change. The test reads back the production wlr_alpha_modifier_surface_v1 + * state over the server bridge and verifies the multiplier transitions + * 0.0 → 1.0, proving the request reached the real compositor surface pipeline + * rather than merely surviving without a protocol error. + */ + +#include "wayland-alpha-modifier-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "alpha-modifier-v1-client-protocol.h" + +#include +#include +#include + +static int read_server(struct alpha_modifier_server_state *state) { + return TEST_READ_SERVER(alpha_modifier_read_server_state, state, + "alpha-modifier: failed to read server state"); +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("alpha-modifier: connect failed\n"); + return 1; + } + + struct xdg_toplevel_client tc; + if (!xdg_toplevel_client_create_with_solid_buffer(&conn, &tc, 64, 64, 0xffff0000u)) { + TEST_ERROR("alpha-modifier: create toplevel failed\n"); + client_disconnect(&conn); + return 1; + } + + struct wp_alpha_modifier_v1 *manager = + client_bind(&conn, wp_alpha_modifier_v1_interface.name, &wp_alpha_modifier_v1_interface, wp_alpha_modifier_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("alpha-modifier: failed to bind wp_alpha_modifier_v1: %s\n", strerror(errno)); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + + struct wp_alpha_modifier_surface_v1 *am_surface = + wp_alpha_modifier_v1_get_surface(manager, tc.surface); + if (am_surface == NULL) { + TEST_ERROR("alpha-modifier: get_surface returned NULL\n"); + wp_alpha_modifier_v1_destroy(manager); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + + int failed = 0; + + /* Set multiplier to 0 (fully transparent) and commit. */ + wp_alpha_modifier_surface_v1_set_multiplier(am_surface, 0u); + wl_surface_commit(tc.surface); + wl_display_roundtrip(conn.display); + + /* E-level: the production multiplier must be 0.0. */ + struct alpha_modifier_server_state srv; + if (read_server(&srv)) { + failed = 1; + } else if (!srv.valid || !srv.has_modifier) { + TEST_ERROR("alpha-modifier: no alpha modifier state on surface\n"); + failed = 1; + } else if (srv.multiplier != 0.0) { + TEST_ERROR("alpha-modifier: expected multiplier 0.0, got %f\n", srv.multiplier); + failed = 1; + } + + /* Set multiplier to UINT32_MAX (fully opaque) and commit. */ + if (!failed) { + wp_alpha_modifier_surface_v1_set_multiplier(am_surface, 0xffffffffu); + wl_surface_commit(tc.surface); + wl_display_roundtrip(conn.display); + + if (read_server(&srv)) { + failed = 1; + } else if (srv.multiplier != 1.0) { + TEST_ERROR("alpha-modifier: expected multiplier 1.0, got %f\n", srv.multiplier); + failed = 1; + } + } + + wp_alpha_modifier_surface_v1_destroy(am_surface); + wp_alpha_modifier_v1_destroy(manager); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-alpha-modifier-v1/wayland-alpha-modifier-v1.h b/tests/protocols/wayland-alpha-modifier-v1/wayland-alpha-modifier-v1.h new file mode 100644 index 0000000000..9775a324a7 --- /dev/null +++ b/tests/protocols/wayland-alpha-modifier-v1/wayland-alpha-modifier-v1.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_ALPHA_MODIFIER_TEST_H +#define WAYLAND_ALPHA_MODIFIER_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Snapshot of the real mapped SurfaceWrapper's alpha-modifier state, read on + * the compositor (Qt) thread. wp_alpha_modifier_surface_v1.set_multiplier is + * double-buffered state applied on wl_surface.commit. The wlroots struct + * stores the multiplier as a double in [0, 1], where 0 is fully transparent + * and 1 is fully opaque (UINT32_MAX). An E-level test verifies that the + * production state reflects the client's requested multiplier. + */ +struct alpha_modifier_server_state { + int valid; /* a mapped SurfaceWrapper was captured */ + int has_modifier; /* alpha modifier state found on the surface */ + double multiplier; /* wlr_alpha_modifier_surface_v1_state::multiplier */ +}; + +/* Defined in setup.cpp; runs on the compositor thread via + * invoke_on_server_thread() and fills *data with the multiplier. */ +void alpha_modifier_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_ALPHA_MODIFIER_TEST_H */ diff --git a/tests/protocols/wayland-cursor-shape-v1/CMakeLists.txt b/tests/protocols/wayland-cursor-shape-v1/CMakeLists.txt new file mode 100644 index 0000000000..7d10543469 --- /dev/null +++ b/tests/protocols/wayland-cursor-shape-v1/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_cursor_shape_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/cursor-shape/cursor-shape-v1.xml" + EXTRA_XMLS "${WAYLAND_PROTOCOLS_DATADIR}/unstable/tablet/tablet-unstable-v2.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-cursor-shape-v1.c" +) diff --git a/tests/protocols/wayland-cursor-shape-v1/README.md b/tests/protocols/wayland-cursor-shape-v1/README.md new file mode 100644 index 0000000000..681e802012 --- /dev/null +++ b/tests/protocols/wayland-cursor-shape-v1/README.md @@ -0,0 +1,29 @@ +# `wayland-cursor-shape-v1` 测试规范 + +## 范围 + +- XML / interface:`wp_cursor_shape_manager_v1` / `wp_cursor_shape_device_v1`(version 2) +- 测试源码:`tests/protocols/wayland-cursor-shape-v1/` +- Fixture:headless output fixture + setup 显式声明 seat 指针能力 +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 声明能力 | setup 中 `WInputDevice::Type::Pointer` + `attachInputDevice` | 客户端 `capabilities` 事件含指针位 | P | +| 绑定全局 | 绑定 `wp_cursor_shape_manager_v1`(v2) | 资源创建成功 | P | +| 创建设备 | `get_pointer(wl_pointer)` | 返回非 NULL 的 `wp_cursor_shape_device_v1` | P | +| 设置形状 | `set_shape(serial=0, DEFAULT)` | 无协议错误 | P | +| **生产回读** | — | setup 通过 `wl_signal_add` 捕获 `wlr_cursor_shape_manager_v1::events.request_set_shape`,断言捕获的 `shape` == DEFAULT(1) | **E** | + +## 生产结果 + +测试观察 Treeland 通过 `wlr_cursor_shape_manager_v1_create` 提供的游标形状服务。 +在真实 `wl_pointer` 上创建 cursor-shape 设备并 `set_shape(DEFAULT)`,setup 通过 +`wl_signal_add` 捕获 `wlr_cursor_shape_manager_v1::events.request_set_shape` 事件, +回读真实生产对象中的 `shape` 值与客户端请求一致,证明游标形状请求到达真实 seat 管道。 + +## 已知边界 / 下一项结果 + +通过 `request_set_shape` 信号间接验证;未捕获实际光标像素(V 级)。未验证 `cursor_shape` table 完整枚举与错误 shape 值。 diff --git a/tests/protocols/wayland-cursor-shape-v1/setup.cpp b/tests/protocols/wayland-cursor-shape-v1/setup.cpp new file mode 100644 index 0000000000..915bdee124 --- /dev/null +++ b/tests/protocols/wayland-cursor-shape-v1/setup.cpp @@ -0,0 +1,58 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-cursor-shape-v1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +WCursorShapeManagerV1 *cursorShapeManager = nullptr; + +struct CursorShapeRequestCapture { + bool received; + uint32_t shape; + int deviceType; + struct wl_listener listener; +} cursorShapeRequestCapture; + +static void handleRequestSetShape(struct wl_listener *listener, void *data) +{ + (void)listener; + auto *event = static_cast< + wlr_cursor_shape_manager_v1_request_set_shape_event *>(data); + cursorShapeRequestCapture.received = true; + cursorShapeRequestCapture.shape = static_cast(event->shape); + cursorShapeRequestCapture.deviceType = static_cast(event->device_type); +} +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + attach_test_pointer_device(server); + + cursorShapeRequestCapture.received = false; + cursorShapeRequestCapture.shape = 0; + cursorShapeRequestCapture.deviceType = 0; + cursorShapeRequestCapture.listener.notify = handleRequestSetShape; + + cursorShapeManager = find_server_interface(server); + if (cursorShapeManager && cursorShapeManager->handle()) { + wl_signal_add(&cursorShapeManager->handle()->events.request_set_shape, + &cursorShapeRequestCapture.listener); + } +} + +void cursor_shape_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = cursorShapeRequestCapture.received ? 1 : 0; + state->shape = cursorShapeRequestCapture.shape; + state->device_type = cursorShapeRequestCapture.deviceType; +} diff --git a/tests/protocols/wayland-cursor-shape-v1/wayland-cursor-shape-v1.c b/tests/protocols/wayland-cursor-shape-v1/wayland-cursor-shape-v1.c new file mode 100644 index 0000000000..45f304c218 --- /dev/null +++ b/tests/protocols/wayland-cursor-shape-v1/wayland-cursor-shape-v1.c @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end): the client obtains a wl_pointer from the + * pointer-capable seat, creates a wp_cursor_shape_device_v1, and calls + * set_shape with WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DEFAULT (1). The test then + * reads back the production WCursorShapeManagerV1's captured request_set_shape + * event data, verifying the shape value matches, proving the cursor-shape + * request reached the real compositor cursor pipeline. + */ + +#include "wayland-cursor-shape-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "cursor-shape-v1-client-protocol.h" + +#include +#include + +static int read_server(struct cursor_shape_server_state *state) { + return TEST_READ_SERVER(cursor_shape_read_server_state, state, + "cursor-shape: failed to read server state"); +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("cursor-shape: connect failed\n"); + return 1; + } + + struct client_pointer_seat pointer_seat = { 0 }; + if (!client_bind_pointer_seat(&conn, wl_seat_interface.version, &pointer_seat)) { + TEST_ERROR("cursor-shape: no pointer-capable wl_seat\n"); + client_disconnect(&conn); + return 1; + } + struct wl_seat *seat = pointer_seat.seat; + struct wl_pointer *pointer = pointer_seat.pointer; + + struct wp_cursor_shape_manager_v1 *manager = + client_bind(&conn, wp_cursor_shape_manager_v1_interface.name, &wp_cursor_shape_manager_v1_interface, wp_cursor_shape_manager_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("cursor-shape: failed to bind manager: %s\n", strerror(errno)); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + struct wp_cursor_shape_device_v1 *device = + wp_cursor_shape_manager_v1_get_pointer(manager, pointer); + if (device == NULL) { + TEST_ERROR("cursor-shape: get_pointer returned NULL\n"); + wp_cursor_shape_manager_v1_destroy(manager); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + wp_cursor_shape_device_v1_set_shape(device, 0, 1 /* DEFAULT */); + wl_display_roundtrip(conn.display); + + int failed = 0; + + /* E-level: the production manager must have captured shape == 1 (DEFAULT). */ + struct cursor_shape_server_state srv; + if (read_server(&srv)) { + failed = 1; + } else if (!srv.valid) { + TEST_ERROR("cursor-shape: no request_set_shape captured\n"); + failed = 1; + } else if (srv.shape != 1) { + TEST_ERROR("cursor-shape: expected shape 1 (DEFAULT), got %u\n", srv.shape); + failed = 1; + } + + wp_cursor_shape_device_v1_destroy(device); + wp_cursor_shape_manager_v1_destroy(manager); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-cursor-shape-v1/wayland-cursor-shape-v1.h b/tests/protocols/wayland-cursor-shape-v1/wayland-cursor-shape-v1.h new file mode 100644 index 0000000000..bcc85ee4cd --- /dev/null +++ b/tests/protocols/wayland-cursor-shape-v1/wayland-cursor-shape-v1.h @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_CURSOR_SHAPE_TEST_H +#define WAYLAND_CURSOR_SHAPE_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * E-level readback: the production WCursorShapeManagerV1 captures the + * request_set_shape signal emitted by wlroots when the client calls + * wp_cursor_shape_device_v1.set_shape. The captured shape value must match + * the client's requested shape, proving the cursor-shape request reached the + * real compositor cursor pipeline rather than merely surviving without a + * protocol error. + */ +struct cursor_shape_server_state { + int valid; /* a shape request was captured */ + uint32_t shape; /* wp_cursor_shape_device_v1_shape enum value */ + int device_type; /* wlr_cursor_shape_manager_v1_device_type */ +}; + +void cursor_shape_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_CURSOR_SHAPE_TEST_H */ diff --git a/tests/protocols/wayland-data-device/CMakeLists.txt b/tests/protocols/wayland-data-device/CMakeLists.txt new file mode 100644 index 0000000000..b91d8ef94b --- /dev/null +++ b/tests/protocols/wayland-data-device/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +treeland_add_protocol_test( + NAME wayland_data_device + XML "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-data-control-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-data-device.c" +) diff --git a/tests/protocols/wayland-data-device/README.md b/tests/protocols/wayland-data-device/README.md new file mode 100644 index 0000000000..54f861ed82 --- /dev/null +++ b/tests/protocols/wayland-data-device/README.md @@ -0,0 +1,28 @@ +# `wl_data_device` selection 焦点回归测试 + +- Fixture:完整 Treeland、真实 seat、两个纯 C Wayland 客户端。目标客户端映射两个 + toplevel,源客户端映射一个 toplevel;源通过 `zwlr_data_control_v1` 发布文本,目标 + 通过标准 `wl_data_device` 的 selection offer 读取 pipe。 +- 等级:E。焦点由 fixture 请求生产 `WaylandServer::requestKeyboardFocus()` 切换; + 所有数据传输均经过真实 Wayland 请求、source send 事件和 pipe 字节断言。 + +| 用例 | 可观察断言 | +| --- | --- | +| initial selection | MIME 含 text/plain,读回 UTF-8 原文且 source send 一次 | +| same-client focus before dispatch | 同一客户端切换 surface,尚未分发新 selection 时,旧 offer 仍能读取原文 | +| same-client focus after temporary clear | 焦点短暂清空后恢复同一客户端,排队的旧 offer receive 仍能读取原文 | +| other-client focus invalidates old offer | 切换到另一客户端后,旧 offer 只读到 EOF,不触发 source send | +| return to client gets valid offer | 焦点返回后,新 offer 可以正常读取 | +| replacement invalidates old offer / replacement payload | 旧 source 收到 cancelled,旧 offer 返回 EOF,新 offer 读到替换内容 | +| source destruction invalidates old offer | 销毁 source 后旧 offer 返回 EOF,目标收到 NULL selection | + +同步采用服务端线程回调、Wayland roundtrip 和 source send 完成,不用固定延时。 +客户端特意保留旧 proxy 以检查服务端失效语义,在测试结束时统一销毁。 + +此测试直接覆盖导致右键粘贴失败的 focus/offer 生命周期边界;实际 xdg-popup 的创建、 +菜单点击和关闭顺序仍需 GUI 复测。未覆盖拖放、XWayland、primary selection 或大数据传输。 + +```sh +cmake --build --preset ci --target test_wayland_data_device +ctest --test-dir build -R '^test_wayland_data_device$' -V +``` diff --git a/tests/protocols/wayland-data-device/setup.cpp b/tests/protocols/wayland-data-device/setup.cpp new file mode 100644 index 0000000000..7f14cada3d --- /dev/null +++ b/tests/protocols/wayland-data-device/setup.cpp @@ -0,0 +1,57 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wayland-data-device.h" +#include "core/shellhandler.h" +#include "core/waylandserver.h" +#include "server-bridge.h" +#include "surface/surfacewrapper.h" + +#include +#include +#include +#include + +#include +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +std::array, 3> toplevels; +unsigned toplevelCount = 0; + +void rememberToplevel(SurfaceWrapper *wrapper) +{ + if (wrapper->type() == SurfaceWrapper::Type::XdgToplevel + && toplevelCount < toplevels.size()) + toplevels[toplevelCount++] = wrapper; +} +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + auto *keyboard = static_cast(std::calloc(1, sizeof(wlr_keyboard))); + Q_CHECK_PTR(keyboard); + wlr_keyboard_init(keyboard, nullptr, "clipboard-test-keyboard"); + server->seat()->attachInputDevice(new WInputDevice(&keyboard->base, true)); + QObject::connect(server->shellHandler(), &ShellHandler::surfaceWrapperAdded, + server, rememberToplevel); +} + +void data_device_focus(void *data) +{ + auto *request = static_cast(data); + request->focused = 0; + if (request->index >= toplevelCount || !toplevels[request->index]) + return; + + auto *server = WaylandServer::instance(); + if (request->clear_first) + server->requestKeyboardFocus(nullptr, Qt::OtherFocusReason); + auto *target = toplevels[request->index].data(); + server->requestKeyboardFocus(target, Qt::ActiveWindowFocusReason); + request->focused = server->seat()->keyboardFocusSurface() == target->surface(); +} diff --git a/tests/protocols/wayland-data-device/wayland-data-device.c b/tests/protocols/wayland-data-device/wayland-data-device.c new file mode 100644 index 0000000000..95eb4f73ac --- /dev/null +++ b/tests/protocols/wayland-data-device/wayland-data-device.c @@ -0,0 +1,262 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wayland-data-device.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "wlr-data-control-unstable-v1-client-protocol.h" + +#include +#include + +struct source_state { + const char *payload; + unsigned sends; + unsigned cancelled; + int write_failed; +}; + +struct selection_offer { + struct selection_offer *next; + struct wl_data_offer *proxy; + int has_text; +}; + +struct target_state { + struct selection_offer *offers; + struct wl_data_offer *selection; +}; + +static void source_send(void *data, struct zwlr_data_control_source_v1 *source, + const char *mime, int32_t fd) +{ + (void)source; + struct source_state *state = data; + const size_t size = strlen(state->payload); + if (strcmp(mime, "text/plain") != 0 + || write(fd, state->payload, size) != (ssize_t)size) + state->write_failed = 1; + ++state->sends; + close(fd); +} + +static void source_cancelled(void *data, struct zwlr_data_control_source_v1 *source) +{ + (void)source; + ++((struct source_state *)data)->cancelled; +} + +static const struct zwlr_data_control_source_v1_listener source_listener = { + .send = source_send, + .cancelled = source_cancelled, +}; + +static void control_offer_mime(void *data, struct zwlr_data_control_offer_v1 *offer, + const char *mime) +{ + (void)data; + (void)offer; + (void)mime; +} + +static const struct zwlr_data_control_offer_v1_listener control_offer_listener = { + .offer = control_offer_mime, +}; + +static void control_offer(void *data, struct zwlr_data_control_device_v1 *device, + struct zwlr_data_control_offer_v1 *offer) +{ + (void)data; + (void)device; + zwlr_data_control_offer_v1_add_listener(offer, &control_offer_listener, NULL); +} + +static void control_selection(void *data, struct zwlr_data_control_device_v1 *device, + struct zwlr_data_control_offer_v1 *offer) +{ + (void)data; + (void)device; + if (offer) + zwlr_data_control_offer_v1_destroy(offer); +} + +static void control_finished(void *data, struct zwlr_data_control_device_v1 *device) +{ + (void)data; + (void)device; +} + +static const struct zwlr_data_control_device_v1_listener control_listener = { + .data_offer = control_offer, + .selection = control_selection, + .primary_selection = control_selection, + .finished = control_finished, +}; + +static void offer_mime(void *data, struct wl_data_offer *offer, const char *mime) +{ + (void)offer; + if (strcmp(mime, "text/plain") == 0) + ((struct selection_offer *)data)->has_text = 1; +} + +static const struct wl_data_offer_listener offer_listener = { + .offer = offer_mime, +}; + +static void device_offer(void *data, struct wl_data_device *device, struct wl_data_offer *offer) +{ + (void)device; + struct target_state *state = data; + struct selection_offer *entry = calloc(1, sizeof(*entry)); + if (!entry) + abort(); + entry->proxy = offer; + entry->next = state->offers; + state->offers = entry; + wl_data_offer_add_listener(offer, &offer_listener, entry); +} + +static void device_selection(void *data, struct wl_data_device *device, struct wl_data_offer *offer) +{ + (void)device; + // Retain old proxies to verify that focus loss and source replacement + // make them inert. A receive queued before dispatching this event is valid. + ((struct target_state *)data)->selection = offer; +} + +static const struct wl_data_device_listener device_listener = { + .data_offer = device_offer, + .selection = device_selection, +}; + +static int focus(unsigned index, int clear_first) +{ + struct data_device_focus_request request = { .index = index, .clear_first = clear_first }; + return invoke_on_server_thread(data_device_focus, &request) && request.focused; +} + +static int transfer(const char *name, struct client_connection *target, + struct client_connection *source, struct wl_data_offer *offer, + struct source_state *state, const char *expected) +{ + int fds[2]; + if (!offer || pipe(fds) != 0) + return 0; + const unsigned sends = state->sends; + wl_data_offer_receive(offer, "text/plain", fds[1]); + close(fds[1]); + if (wl_display_roundtrip(target->display) < 0 + || wl_display_roundtrip(source->display) < 0) { + close(fds[0]); + return 0; + } + char buffer[128]; + const ssize_t size = read(fds[0], buffer, sizeof(buffer)); + close(fds[0]); + const size_t expected_size = strlen(expected); + if (size != (ssize_t)expected_size || memcmp(buffer, expected, expected_size) != 0 + || state->sends != sends + (expected_size != 0) || state->write_failed) { + TEST_ERROR("%s: expected %zu bytes, received %zd, source sends %u\n", + name, expected_size, size, state->sends - sends); + return 0; + } + fprintf(stderr, "PASS: %s\n", name); + return 1; +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection source = {0}, target = {0}; + struct xdg_toplevel_client main_window = {0}, peer_window = {0}, other_window = {0}; + struct client_seat source_seat = {0}, target_seat = {0}; + struct target_state target_state = {0}; + struct source_state first = { .payload = "clipboard-focus-中文" }; + struct source_state second = { .payload = "replacement" }; + int result = 1; + + if (!client_connect(&source, socket_name) || !client_connect(&target, socket_name) + || !client_bind_seat(&source, 1, &source_seat) + || !client_bind_seat(&target, 1, &target_seat)) + goto cleanup; + struct zwlr_data_control_manager_v1 *control = client_bind( + &source, "zwlr_data_control_manager_v1", &zwlr_data_control_manager_v1_interface, 2); + struct wl_data_device_manager *manager = client_bind( + &target, "wl_data_device_manager", &wl_data_device_manager_interface, 3); + if (!control || !manager) + goto cleanup; + struct zwlr_data_control_device_v1 *source_device = + zwlr_data_control_manager_v1_get_data_device(control, source_seat.seat); + zwlr_data_control_device_v1_add_listener(source_device, &control_listener, NULL); + struct wl_data_device *target_device = wl_data_device_manager_get_data_device(manager, target_seat.seat); + wl_data_device_add_listener(target_device, &device_listener, &target_state); + + if (!xdg_toplevel_client_create(&target, &main_window) + || !xdg_toplevel_client_create(&target, &peer_window) + || !xdg_toplevel_client_create(&source, &other_window)) + goto cleanup; + struct zwlr_data_control_source_v1 *first_source = zwlr_data_control_manager_v1_create_data_source(control); + zwlr_data_control_source_v1_add_listener(first_source, &source_listener, &first); + zwlr_data_control_source_v1_offer(first_source, "text/plain"); + zwlr_data_control_device_v1_set_selection(source_device, first_source); + if (wl_display_roundtrip(source.display) < 0 || !focus(0, 0) + || wl_display_roundtrip(target.display) < 0 + || !target_state.offers || !target_state.offers->has_text + || !transfer("initial selection", &target, &source, target_state.selection, &first, first.payload)) + goto cleanup; + + struct wl_data_offer *old_offer = target_state.selection; + if (!focus(1, 0) + || !transfer("same-client focus before dispatch", &target, &source, old_offer, &first, first.payload)) + goto cleanup; + old_offer = target_state.selection; + if (!focus(0, 1) + || !transfer("same-client focus after temporary clear", &target, &source, old_offer, &first, first.payload)) + goto cleanup; + old_offer = target_state.selection; + if (!focus(2, 0) + || !transfer("other-client focus invalidates old offer", &target, &source, old_offer, &first, "")) + goto cleanup; + if (!focus(0, 0) || wl_display_roundtrip(target.display) < 0 + || !transfer("return to client gets valid offer", &target, &source, target_state.selection, &first, first.payload)) + goto cleanup; + + old_offer = target_state.selection; + struct zwlr_data_control_source_v1 *second_source = zwlr_data_control_manager_v1_create_data_source(control); + zwlr_data_control_source_v1_add_listener(second_source, &source_listener, &second); + zwlr_data_control_source_v1_offer(second_source, "text/plain"); + zwlr_data_control_device_v1_set_selection(source_device, second_source); + if (wl_display_roundtrip(source.display) < 0 || first.cancelled != 1 + || !transfer("replacement invalidates old offer", &target, &source, old_offer, &second, "") + || !transfer("replacement payload", &target, &source, target_state.selection, &second, second.payload)) + goto cleanup; + old_offer = target_state.selection; + zwlr_data_control_source_v1_destroy(second_source); + if (wl_display_roundtrip(source.display) < 0 + || !transfer("source destruction invalidates old offer", &target, &source, old_offer, &second, "") + || target_state.selection != NULL) + goto cleanup; + + zwlr_data_control_source_v1_destroy(first_source); + zwlr_data_control_device_v1_destroy(source_device); + zwlr_data_control_manager_v1_destroy(control); + wl_data_device_release(target_device); + wl_data_device_manager_destroy(manager); + result = 0; +cleanup: + while (target_state.offers) { + struct selection_offer *entry = target_state.offers; + target_state.offers = entry->next; + wl_data_offer_destroy(entry->proxy); + free(entry); + } + xdg_toplevel_client_destroy(&other_window); + xdg_toplevel_client_destroy(&peer_window); + xdg_toplevel_client_destroy(&main_window); + client_seat_destroy(&target_seat); + client_seat_destroy(&source_seat); + client_disconnect(&target); + client_disconnect(&source); + return result; +} diff --git a/tests/protocols/wayland-data-device/wayland-data-device.h b/tests/protocols/wayland-data-device/wayland-data-device.h new file mode 100644 index 0000000000..539e707132 --- /dev/null +++ b/tests/protocols/wayland-data-device/wayland-data-device.h @@ -0,0 +1,18 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +struct data_device_focus_request { + unsigned index; + int clear_first; + int focused; +}; + +#ifdef __cplusplus +extern "C" { +#endif +void data_device_focus(void *data); +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/wayland-ext-data-control-v1/CMakeLists.txt b/tests/protocols/wayland-ext-data-control-v1/CMakeLists.txt new file mode 100644 index 0000000000..4a55d58393 --- /dev/null +++ b/tests/protocols/wayland-ext-data-control-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_ext_data_control_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-data-control/ext-data-control-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-ext-data-control-v1.c" +) diff --git a/tests/protocols/wayland-ext-data-control-v1/README.md b/tests/protocols/wayland-ext-data-control-v1/README.md new file mode 100644 index 0000000000..4e2453b74f --- /dev/null +++ b/tests/protocols/wayland-ext-data-control-v1/README.md @@ -0,0 +1,27 @@ +# `wayland-ext-data-control-v1` 测试规范 + +## 范围 + +- XML / interface:`ext_data_control_manager_v1` / `ext_data_control_device_v1`(version 1) +- 测试源码:`tests/protocols/wayland-ext-data-control-v1/` +- Fixture:headless output fixture +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `ext_data_control_manager_v1` | 资源创建成功 | P | +| 创建设备 | `get_data_device(seat)` | 收到初始 `selection(NULL)` 事件 | P | +| 设置选区 | `create_offer` + `offer("text/plain")` + `set_selection` | 收到非 NULL `selection` 事件 | P | +| **生产回读** | — | 回读真实 `wlr_seat::selection_source` 非空 | **E** | + +## 生产结果 + +测试观察 Treeland 通过 `wlr_ext_data_control_manager_v1_create` 提供的数据控制服务。 +客户端创建 offer 并 `set_selection` 后,通过 `invoke_on_server_thread` 回读真实 +`wlr_seat::selection_source` 字段,断言其非空,证明数据控制选区请求到达真实 seat 管道。 + +## 已知边界 / 下一项结果 + +仅验证 `selection_source` 非空;未验证 `primary_selection` 设置路径与 offer 的 mime type 内容。 diff --git a/tests/protocols/wayland-ext-data-control-v1/setup.cpp b/tests/protocols/wayland-ext-data-control-v1/setup.cpp new file mode 100644 index 0000000000..d64192fcee --- /dev/null +++ b/tests/protocols/wayland-ext-data-control-v1/setup.cpp @@ -0,0 +1,38 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-ext-data-control-v1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +wlr_seat *g_seat = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + auto *seat = server->seat(); + if (seat) + g_seat = seat->handle(); +} + +void ext_data_control_read_server_state(void *data) +{ + auto *state = + static_cast(data); + state->valid = 0; + state->has_source = 0; + + if (!g_seat) + return; + + state->valid = 1; + state->has_source = (g_seat->selection_source != nullptr) ? 1 : 0; +} diff --git a/tests/protocols/wayland-ext-data-control-v1/wayland-ext-data-control-v1.c b/tests/protocols/wayland-ext-data-control-v1/wayland-ext-data-control-v1.c new file mode 100644 index 0000000000..03bfcd03eb --- /dev/null +++ b/tests/protocols/wayland-ext-data-control-v1/wayland-ext-data-control-v1.c @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end): the client binds ext_data_control_manager_v1, + * creates a data control device, creates an offer with a mime type, and sets + * the selection. The test reads back the production wlr_seat's + * selection_source field, verifying it is non-NULL, proving the data control + * selection request reached the real compositor seat pipeline. + */ + +#include "wayland-ext-data-control-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "ext-data-control-v1-client-protocol.h" + +#include +#include + +struct dc_state { + int selection_count; + int initial_selection_received; + int selection_with_offer_received; + int primary_selection_count; +}; + +static void data_offer(void *data, struct ext_data_control_device_v1 *device, + struct ext_data_control_offer_v1 *offer) { + (void)data; + (void)device; + (void)offer; +} + +static void selection(void *data, struct ext_data_control_device_v1 *device, + struct ext_data_control_offer_v1 *offer) { + (void)device; + struct dc_state *state = data; + state->selection_count++; + if (state->selection_count == 1 && offer == NULL) + state->initial_selection_received = 1; + if (offer != NULL) + state->selection_with_offer_received = 1; + if (offer != NULL) + ext_data_control_offer_v1_destroy(offer); +} + +static void primary_selection(void *data, struct ext_data_control_device_v1 *device, + struct ext_data_control_offer_v1 *offer) { + (void)device; + struct dc_state *state = data; + state->primary_selection_count++; + if (offer != NULL) + ext_data_control_offer_v1_destroy(offer); +} + +static void finished(void *data, struct ext_data_control_device_v1 *device) { + (void)data; + (void)device; +} + +static const struct ext_data_control_device_v1_listener device_listener = { + .data_offer = data_offer, + .selection = selection, + .finished = finished, + .primary_selection = primary_selection, +}; + +static int read_server(struct ext_data_control_server_state *state) { + return TEST_READ_SERVER(ext_data_control_read_server_state, state, + "ext-data-control: failed to read server state"); +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("ext-data-control: connect failed\n"); + return 1; + } + + struct wl_seat *seat = client_bind(&conn, wl_seat_interface.name, &wl_seat_interface, wl_seat_interface.version); + if (seat == NULL) { + TEST_ERROR("ext-data-control: no wl_seat global\n"); + client_disconnect(&conn); + return 1; + } + + struct ext_data_control_manager_v1 *manager = client_bind( + &conn, ext_data_control_manager_v1_interface.name, &ext_data_control_manager_v1_interface, ext_data_control_manager_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("ext-data-control: failed to bind manager: %s\n", strerror(errno)); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + struct dc_state state = { 0 }; + struct ext_data_control_device_v1 *device = + ext_data_control_manager_v1_get_data_device(manager, seat); + if (device == NULL) { + TEST_ERROR("ext-data-control: get_data_device returned NULL\n"); + ext_data_control_manager_v1_destroy(manager); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + ext_data_control_device_v1_add_listener(device, &device_listener, &state); + + wl_display_roundtrip(conn.display); + if (!state.initial_selection_received) { + TEST_ERROR("ext-data-control: no initial selection(NULL) event\n"); + ext_data_control_device_v1_destroy(device); + ext_data_control_manager_v1_destroy(manager); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + /* Create a data source and set it as the selection. */ + struct ext_data_control_source_v1 *source = + ext_data_control_manager_v1_create_data_source(manager); + if (source == NULL) { + TEST_ERROR("ext-data-control: create_data_source returned NULL\n"); + ext_data_control_device_v1_destroy(device); + ext_data_control_manager_v1_destroy(manager); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + ext_data_control_source_v1_offer(source, "text/plain"); + ext_data_control_device_v1_set_selection(device, source); + + wl_display_roundtrip(conn.display); + + int failed = 0; + if (!state.selection_with_offer_received) { + TEST_ERROR("ext-data-control: no selection event with an offer\n"); + failed = 1; + } + + /* E-level: the production seat must have selection_source set. */ + struct ext_data_control_server_state srv; + if (read_server(&srv)) { + failed = 1; + } else if (!srv.valid) { + TEST_ERROR("ext-data-control: seat not found\n"); + failed = 1; + } else if (!srv.has_source) { + TEST_ERROR("ext-data-control: selection_source is NULL\n"); + failed = 1; + } + + ext_data_control_source_v1_destroy(source); + ext_data_control_device_v1_destroy(device); + ext_data_control_manager_v1_destroy(manager); + wl_seat_destroy(seat); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-ext-data-control-v1/wayland-ext-data-control-v1.h b/tests/protocols/wayland-ext-data-control-v1/wayland-ext-data-control-v1.h new file mode 100644 index 0000000000..f121d4e219 --- /dev/null +++ b/tests/protocols/wayland-ext-data-control-v1/wayland-ext-data-control-v1.h @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_EXT_DATA_CONTROL_TEST_H +#define WAYLAND_EXT_DATA_CONTROL_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * E-level readback: the production wlr_seat's selection_source field must be + * non-NULL after the client sets a selection via the ext_data_control protocol. + * This proves the data control selection request reached the real compositor + * seat pipeline rather than merely surviving without a protocol error. + */ +struct ext_data_control_server_state { + int valid; /* seat was found */ + int has_source; /* selection_source != NULL */ +}; + +void ext_data_control_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_EXT_DATA_CONTROL_TEST_H */ diff --git a/tests/protocols/wayland-ext-foreign-toplevel-list-v1/CMakeLists.txt b/tests/protocols/wayland-ext-foreign-toplevel-list-v1/CMakeLists.txt new file mode 100644 index 0000000000..8d1a25c88e --- /dev/null +++ b/tests/protocols/wayland-ext-foreign-toplevel-list-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_ext_foreign_toplevel_list_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-foreign-toplevel-list/ext-foreign-toplevel-list-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-ext-foreign-toplevel-list-v1.c" +) diff --git a/tests/protocols/wayland-ext-foreign-toplevel-list-v1/README.md b/tests/protocols/wayland-ext-foreign-toplevel-list-v1/README.md new file mode 100644 index 0000000000..03bd4b4bcf --- /dev/null +++ b/tests/protocols/wayland-ext-foreign-toplevel-list-v1/README.md @@ -0,0 +1,28 @@ +# `wayland-ext-foreign-toplevel-list-v1` 测试规范 + +## 范围 + +- XML / interface:`ext_foreign_toplevel_list_v1` / `ext_foreign_toplevel_handle_v1`(version 1) +- 测试源码:`tests/protocols/wayland-ext-foreign-toplevel-list-v1/` +- Fixture:headless output fixture + 映射 xdg-toplevel +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `ext_foreign_toplevel_list_v1` | 资源创建成功 | P | +| 映射 toplevel | xdg-toplevel map | 收到 `toplevel` 事件 + 非 NULL handle | P | +| 停止 | `stop` | 收到 `finished` 事件 | P | +| **生产回读** | — | 回读真实 `wlr_ext_foreign_toplevel_list_v1::toplevels` 列表 `wl_list_length` >= 1 | **E** | + +## 生产结果 + +测试观察 Treeland 通过 `wlr_ext_foreign_toplevel_list_v1_create` 提供的外部 toplevel 列表服务。 +映射 xdg-toplevel 后,通过 `invoke_on_server_thread` 回读真实 +`wlr_ext_foreign_toplevel_list_v1::toplevels` 列表长度,断言 >= 1,证明生产列表管理器 +收到了真实 toplevel 注册。 + +## 已知边界 / 下一项结果 + +仅验证列表非空;未验证 handle 的 `title/app_id/closed` 事件 payload。 diff --git a/tests/protocols/wayland-ext-foreign-toplevel-list-v1/setup.cpp b/tests/protocols/wayland-ext-foreign-toplevel-list-v1/setup.cpp new file mode 100644 index 0000000000..dc26d14e23 --- /dev/null +++ b/tests/protocols/wayland-ext-foreign-toplevel-list-v1/setup.cpp @@ -0,0 +1,36 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-ext-foreign-toplevel-list-v1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +WExtForeignToplevelListV1 *g_mgr = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + g_mgr = find_server_interface(server); +} + +void foreign_toplevel_list_read_server_state(void *data) +{ + auto *state = + static_cast(data); + state->valid = 0; + state->count = 0; + + if (!g_mgr || !g_mgr->handle()) + return; + + state->valid = 1; + state->count = wl_list_length(&g_mgr->handle()->toplevels); +} diff --git a/tests/protocols/wayland-ext-foreign-toplevel-list-v1/wayland-ext-foreign-toplevel-list-v1.c b/tests/protocols/wayland-ext-foreign-toplevel-list-v1/wayland-ext-foreign-toplevel-list-v1.c new file mode 100644 index 0000000000..73ca542816 --- /dev/null +++ b/tests/protocols/wayland-ext-foreign-toplevel-list-v1/wayland-ext-foreign-toplevel-list-v1.c @@ -0,0 +1,117 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end): the client binds ext_foreign_toplevel_list_v1, + * maps a real xdg_toplevel, and receives the `toplevel` event from the + * compositor. The test then reads back the production + * WExtForeignToplevelListV1's toplevels list length, verifying it is at least + * 1, proving the toplevel was registered in the real compositor + * foreign-toplevel-list pipeline. + */ + +#include "wayland-ext-foreign-toplevel-list-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "ext-foreign-toplevel-list-v1-client-protocol.h" + +#include +#include + +struct ftl_state { + int toplevel_count; + int finished; +}; + +static void toplevel(void *data, struct ext_foreign_toplevel_list_v1 *list, + struct ext_foreign_toplevel_handle_v1 *handle) { + (void)list; + (void)handle; + struct ftl_state *state = data; + state->toplevel_count++; +} + +static void finished(void *data, struct ext_foreign_toplevel_list_v1 *list) { + (void)list; + ((struct ftl_state *)data)->finished = 1; +} + +static const struct ext_foreign_toplevel_list_v1_listener list_listener = { + .toplevel = toplevel, + .finished = finished, +}; + +static int read_server(struct foreign_toplevel_list_server_state *state) { + return TEST_READ_SERVER(foreign_toplevel_list_read_server_state, state, + "ext-foreign-toplevel-list: failed to read server state"); +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("ext-foreign-toplevel-list: connect failed\n"); + return 1; + } + + struct ext_foreign_toplevel_list_v1 *list = client_bind( + &conn, ext_foreign_toplevel_list_v1_interface.name, &ext_foreign_toplevel_list_v1_interface, ext_foreign_toplevel_list_v1_interface.version); + if (list == NULL) { + TEST_ERROR("ext-foreign-toplevel-list: failed to bind: %s\n", strerror(errno)); + client_disconnect(&conn); + return 1; + } + + struct ftl_state state = { 0 }; + ext_foreign_toplevel_list_v1_add_listener(list, &list_listener, &state); + + /* Map a real toplevel so the compositor registers it in the list. */ + struct xdg_toplevel_client tc; + if (!xdg_toplevel_client_create_pending(&conn, &tc)) { + TEST_ERROR("ext-foreign-toplevel-list: create_pending failed\n"); + ext_foreign_toplevel_list_v1_destroy(list); + client_disconnect(&conn); + return 1; + } + if (!xdg_toplevel_client_complete_map(&conn, &tc)) { + TEST_ERROR("ext-foreign-toplevel-list: complete_map failed\n"); + xdg_toplevel_client_destroy(&tc); + ext_foreign_toplevel_list_v1_destroy(list); + client_disconnect(&conn); + return 1; + } + wl_display_roundtrip(conn.display); + + int failed = 0; + if (state.toplevel_count < 1) { + TEST_ERROR("ext-foreign-toplevel-list: no toplevel event received\n"); + failed = 1; + } + + /* E-level: the production list must have at least 1 toplevel. */ + struct foreign_toplevel_list_server_state srv; + if (read_server(&srv)) { + failed = 1; + } else if (!srv.valid) { + TEST_ERROR("ext-foreign-toplevel-list: manager not found\n"); + failed = 1; + } else if (srv.count < 1) { + TEST_ERROR("ext-foreign-toplevel-list: expected count >= 1, got %d\n", srv.count); + failed = 1; + } + + /* stop() ends enumeration and must be acknowledged with finished. */ + if (!failed) { + ext_foreign_toplevel_list_v1_stop(list); + wl_display_roundtrip(conn.display); + if (!state.finished) { + TEST_ERROR("ext-foreign-toplevel-list: no finished event after stop\n"); + failed = 1; + } + } + + xdg_toplevel_client_destroy(&tc); + ext_foreign_toplevel_list_v1_destroy(list); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-ext-foreign-toplevel-list-v1/wayland-ext-foreign-toplevel-list-v1.h b/tests/protocols/wayland-ext-foreign-toplevel-list-v1/wayland-ext-foreign-toplevel-list-v1.h new file mode 100644 index 0000000000..2ab885ae1f --- /dev/null +++ b/tests/protocols/wayland-ext-foreign-toplevel-list-v1/wayland-ext-foreign-toplevel-list-v1.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_EXT_FOREIGN_TOPLEVEL_LIST_TEST_H +#define WAYLAND_EXT_FOREIGN_TOPLEVEL_LIST_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * E-level readback: the production WExtForeignToplevelListV1's wlroots handle + * has a toplevels linked list. After the client maps a toplevel (which + * triggers WExtForeignToplevelListV1::addSurface), the list must contain at + * least one entry, proving the toplevel was registered in the real compositor + * foreign-toplevel-list pipeline. + */ +struct foreign_toplevel_list_server_state { + int valid; /* manager was found */ + int count; /* number of toplevels in the list */ +}; + +void foreign_toplevel_list_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_EXT_FOREIGN_TOPLEVEL_LIST_TEST_H */ diff --git a/tests/protocols/wayland-ext-idle-notify-v1/CMakeLists.txt b/tests/protocols/wayland-ext-idle-notify-v1/CMakeLists.txt new file mode 100644 index 0000000000..5cefe5d0c3 --- /dev/null +++ b/tests/protocols/wayland-ext-idle-notify-v1/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_ext_idle_notify_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-idle-notify/ext-idle-notify-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-ext-idle-notify-v1.c" + EXTRA_XMLS "${WAYLAND_PROTOCOLS_DATADIR}/unstable/idle-inhibit/idle-inhibit-unstable-v1.xml" +) diff --git a/tests/protocols/wayland-ext-idle-notify-v1/README.md b/tests/protocols/wayland-ext-idle-notify-v1/README.md new file mode 100644 index 0000000000..0cbf7e3b60 --- /dev/null +++ b/tests/protocols/wayland-ext-idle-notify-v1/README.md @@ -0,0 +1,29 @@ +# `wayland-ext-idle-notify-v1` 测试规范 + +## 范围 + +- XML / interface:`ext_idle_notifier_v1` / `ext_idle_notification_v1`(version 1) +- 测试源码:`tests/protocols/wayland-ext-idle-notify-v1/` +- Fixture:headless output fixture + 跨协议 idle-inhibit +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `ext_idle_notifier_v1` | 资源创建成功 | P | +| 空闲触发 | `get_idle_notification(1ms, seat)` | 收到 `idled` 事件 | P | +| **跨协议抑制** | 映射 toplevel + `create_inhibitor(surface)` | 新建 `get_idle_notification(1ms)` 后 500ms 内 `idled` **不**触发 | **E** | +| **解除抑制** | 销毁 inhibitor | 新建 `get_idle_notification(1ms)` 后 `idled` 触发 | **E** | + +## 生产结果 + +测试观察 Treeland 通过 `wlr_idle_notifier_v1_create` 提供的空闲通知服务。 +通过跨协议行为交叉检查:在映射的 surface 上创建 idle inhibitor → `idled` 不触发 → +销毁 inhibitor → `idled` 触发。这证明生产 `wlr_idle_notifier_v1` 的 `inhibited` 状态 +被 `WaylandServer::onNewIdleInhibitor` 修改,而非仅协议存活。 + +## 已知边界 / 下一项结果 + +跨协议测试使用 `ProtocolTest.cmake` 的 `EXTRA_XMLS` 同时包含 idle-inhibit XML。 +仅验证 inhibited 布尔行为;未验证 `resumed` 事件和 `notify_activity` 路径。 diff --git a/tests/protocols/wayland-ext-idle-notify-v1/setup.cpp b/tests/protocols/wayland-ext-idle-notify-v1/setup.cpp new file mode 100644 index 0000000000..9cea9fbc5a --- /dev/null +++ b/tests/protocols/wayland-ext-idle-notify-v1/setup.cpp @@ -0,0 +1,10 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "server-bridge.h" +#include "core/waylandserver.h" +#include + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); +} diff --git a/tests/protocols/wayland-ext-idle-notify-v1/wayland-ext-idle-notify-v1.c b/tests/protocols/wayland-ext-idle-notify-v1/wayland-ext-idle-notify-v1.c new file mode 100644 index 0000000000..3740e45bfb --- /dev/null +++ b/tests/protocols/wayland-ext-idle-notify-v1/wayland-ext-idle-notify-v1.c @@ -0,0 +1,206 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end, cross-protocol): the test verifies that the + * production wlr_idle_notifier_v1 is actually inhibited by an idle inhibitor. + * + * Step 1: Create an ext-idle-notify notification with 1ms timeout. Receive + * the `idled` event — proves the production idle notifier timer works. + * + * Step 2: Map a toplevel, create an idle inhibitor on its surface. Create + * another notification with 1ms timeout. Verify `idled` does NOT fire + * within 500ms — proves IdleManager::onNewIdleInhibitor called + * wlr_idle_notifier_v1_set_inhibited(true), modifying production state. + * + * Step 3: Destroy the inhibitor. Create a third notification. Verify `idled` + * fires — proves the production notifier is no longer inhibited. + */ + +#include "client-connection.h" +#include "xdg-toplevel-client.h" +#include "ext-idle-notify-v1-client-protocol.h" +#include "idle-inhibit-unstable-v1-client-protocol.h" + +#include +#include +#include +#include +#include + +struct idle_state { + int idled; + int resumed; +}; + +static void idled(void *data, struct ext_idle_notification_v1 *notif) { + (void)notif; + struct idle_state *state = data; + state->idled = 1; +} + +static void resumed(void *data, struct ext_idle_notification_v1 *notif) { + (void)notif; + struct idle_state *state = data; + state->resumed = 1; +} + +static const struct ext_idle_notification_v1_listener idle_listener = { + .idled = idled, + .resumed = resumed, +}; + +/* Wait up to `timeout_ms` for `state->idled` to become 1. */ +static int wait_for_idled( + struct client_connection *conn, struct idle_state *state, int timeout_ms) { + state->idled = 0; + state->resumed = 0; + int fd = wl_display_get_fd(conn->display); + struct timespec start_ts, now_ts; + clock_gettime(CLOCK_MONOTONIC, &start_ts); + while (!state->idled) { + clock_gettime(CLOCK_MONOTONIC, &now_ts); + int elapsed = (now_ts.tv_sec - start_ts.tv_sec) * 1000 + + (now_ts.tv_nsec - start_ts.tv_nsec) / 1000000; + if (elapsed >= timeout_ms) + break; + wl_display_dispatch_pending(conn->display); + wl_display_flush(conn->display); + struct pollfd pfd = { .fd = fd, .events = POLLIN }; + int remaining = timeout_ms - elapsed; + int ret = poll(&pfd, 1, remaining < 50 ? remaining : 50); + if (ret < 0) { + if (errno == EINTR) + continue; + return -1; + } + if (ret > 0) + wl_display_dispatch(conn->display); + } + /* Final drain of any pending events. */ + wl_display_dispatch_pending(conn->display); + return state->idled; +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + struct zwp_idle_inhibit_manager_v1 *inhibit_mgr = NULL; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("ext-idle-notify: connect failed\n"); + return 1; + } + + struct client_seat client_seat = { 0 }; + if (!client_bind_seat(&conn, wl_seat_interface.version, &client_seat)) { + TEST_ERROR("ext-idle-notify: no wl_seat global\n"); + client_disconnect(&conn); + return 1; + } + struct wl_seat *seat = client_seat.seat; + + struct ext_idle_notifier_v1 *notifier = + client_bind(&conn, ext_idle_notifier_v1_interface.name, &ext_idle_notifier_v1_interface, ext_idle_notifier_v1_interface.version); + if (notifier == NULL) { + TEST_ERROR("ext-idle-notify: failed to bind notifier: %s\n", strerror(errno)); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + int failed = 0; + + /* Step 1: Verify the idle timer works. */ + struct idle_state s1 = { 0, 0 }; + struct ext_idle_notification_v1 *n1 = + ext_idle_notifier_v1_get_idle_notification(notifier, 1 /* 1ms */, seat); + if (n1 == NULL) { + TEST_ERROR("ext-idle-notify: get_idle_notification returned NULL\n"); + ext_idle_notifier_v1_destroy(notifier); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + ext_idle_notification_v1_add_listener(n1, &idle_listener, &s1); + + if (!wait_for_idled(&conn, &s1, 2000)) { + TEST_ERROR("ext-idle-notify: Step 1 - idled did not fire\n"); + failed = 1; + } + ext_idle_notification_v1_destroy(n1); + + if (failed) + goto cleanup; + + /* Step 2: Map a toplevel and create an idle inhibitor. */ + struct xdg_toplevel_client tc; + if (!xdg_toplevel_client_create_pending(&conn, &tc)) { + TEST_ERROR("ext-idle-notify: create_pending failed\n"); + failed = 1; + goto cleanup; + } + if (!xdg_toplevel_client_complete_map(&conn, &tc)) { + TEST_ERROR("ext-idle-notify: complete_map failed\n"); + xdg_toplevel_client_destroy(&tc); + failed = 1; + goto cleanup; + } + wl_display_roundtrip(conn.display); + + inhibit_mgr = client_bind( + &conn, zwp_idle_inhibit_manager_v1_interface.name, &zwp_idle_inhibit_manager_v1_interface, zwp_idle_inhibit_manager_v1_interface.version); + struct zwp_idle_inhibitor_v1 *inhibitor = NULL; + if (inhibit_mgr != NULL) { + inhibitor = zwp_idle_inhibit_manager_v1_create_inhibitor(inhibit_mgr, tc.surface); + } + if (inhibitor == NULL) { + TEST_ERROR("ext-idle-notify: failed to create inhibitor\n"); + xdg_toplevel_client_destroy(&tc); + failed = 1; + goto cleanup; + } + wl_display_roundtrip(conn.display); + + /* Create a notification while inhibited — should NOT fire. */ + struct idle_state s2 = { 0, 0 }; + struct ext_idle_notification_v1 *n2 = + ext_idle_notifier_v1_get_idle_notification(notifier, 1, seat); + ext_idle_notification_v1_add_listener(n2, &idle_listener, &s2); + + /* Wait 500ms — if inhibited, idled should NOT fire. */ + if (wait_for_idled(&conn, &s2, 500)) { + TEST_ERROR("ext-idle-notify: Step 2 - idled fired while inhibited!\n"); + failed = 1; + } + ext_idle_notification_v1_destroy(n2); + + if (failed) { + zwp_idle_inhibitor_v1_destroy(inhibitor); + xdg_toplevel_client_destroy(&tc); + goto cleanup; + } + + /* Step 3: Destroy inhibitor — notification should fire again. */ + zwp_idle_inhibitor_v1_destroy(inhibitor); + wl_display_roundtrip(conn.display); + + struct idle_state s3 = { 0, 0 }; + struct ext_idle_notification_v1 *n3 = + ext_idle_notifier_v1_get_idle_notification(notifier, 1, seat); + ext_idle_notification_v1_add_listener(n3, &idle_listener, &s3); + + if (!wait_for_idled(&conn, &s3, 2000)) { + TEST_ERROR("ext-idle-notify: Step 3 - idled did not fire after destroy\n"); + failed = 1; + } + ext_idle_notification_v1_destroy(n3); + + xdg_toplevel_client_destroy(&tc); + +cleanup: + if (inhibit_mgr != NULL) + zwp_idle_inhibit_manager_v1_destroy(inhibit_mgr); + wl_seat_destroy(seat); + ext_idle_notifier_v1_destroy(notifier); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-ext-image-copy-capture-v1/CMakeLists.txt b/tests/protocols/wayland-ext-image-copy-capture-v1/CMakeLists.txt new file mode 100644 index 0000000000..158df3ca4c --- /dev/null +++ b/tests/protocols/wayland-ext-image-copy-capture-v1/CMakeLists.txt @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS QuickPrivate) +endif() + +treeland_add_protocol_test( + NAME wayland_ext_image_copy_capture_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-image-copy-capture/ext-image-copy-capture-v1.xml" + EXTRA_XMLS "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-image-capture-source/ext-image-capture-source-v1.xml" + "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-foreign-toplevel-list/ext-foreign-toplevel-list-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-ext-image-copy-capture-v1.c" +) + +treeland_add_protocol_test( + NAME wayland_ext_toplevel_image_capture_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-image-copy-capture/ext-image-copy-capture-v1.xml" + EXTRA_XMLS "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-image-capture-source/ext-image-capture-source-v1.xml" + "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-foreign-toplevel-list/ext-foreign-toplevel-list-v1.xml" + "${WAYLAND_PROTOCOLS_DATADIR}/unstable/xdg-decoration/xdg-decoration-unstable-v1.xml" + "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-output-power-management-unstable-v1.xml" + "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-ddm-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/toplevel-setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-ext-toplevel-image-capture-v1.c" +) +target_compile_definitions(test_wayland_ext_toplevel_image_capture_v1 PRIVATE WLR_USE_UNSTABLE) +target_link_libraries(test_wayland_ext_toplevel_image_capture_v1 PRIVATE Qt6::QuickPrivate) +set_property(TEST test_wayland_ext_toplevel_image_capture_v1 APPEND PROPERTY + ENVIRONMENT "WLR_HEADLESS_OUTPUTS=0") + +if(TREELAND_ENABLE_GPU_PROTOCOL_TESTS) + treeland_add_protocol_test( + NAME wayland_ext_toplevel_image_capture_v1_gpu + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-image-copy-capture/ext-image-copy-capture-v1.xml" + EXTRA_XMLS "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-image-capture-source/ext-image-capture-source-v1.xml" + "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-foreign-toplevel-list/ext-foreign-toplevel-list-v1.xml" + "${WAYLAND_PROTOCOLS_DATADIR}/unstable/xdg-decoration/xdg-decoration-unstable-v1.xml" + "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-output-power-management-unstable-v1.xml" + "${TREELAND_PROTOCOLS_DATA_DIR}/treeland-ddm-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/toplevel-setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-ext-toplevel-image-capture-v1.c" + ) + target_compile_definitions(test_wayland_ext_toplevel_image_capture_v1_gpu + PRIVATE WLR_USE_UNSTABLE TREELAND_CAPTURE_TEST_GPU) + target_link_libraries(test_wayland_ext_toplevel_image_capture_v1_gpu PRIVATE Qt6::QuickPrivate) + get_property(gpu_environment TEST test_wayland_ext_toplevel_image_capture_v1_gpu PROPERTY ENVIRONMENT) + list(FILTER gpu_environment EXCLUDE REGEX "^WLR_RENDERER=") + list(APPEND gpu_environment "WLR_HEADLESS_OUTPUTS=0" "WLR_RENDERER=gles2") + set_property(TEST test_wayland_ext_toplevel_image_capture_v1_gpu PROPERTY + ENVIRONMENT "${gpu_environment}") + set_property(TEST test_wayland_ext_toplevel_image_capture_v1_gpu APPEND PROPERTY LABELS gpu) +endif() diff --git a/tests/protocols/wayland-ext-image-copy-capture-v1/README.md b/tests/protocols/wayland-ext-image-copy-capture-v1/README.md new file mode 100644 index 0000000000..37979b257b --- /dev/null +++ b/tests/protocols/wayland-ext-image-copy-capture-v1/README.md @@ -0,0 +1,191 @@ +# `wayland-ext-image-copy-capture-v1` 测试规范 + +## 范围 + +- XML / interface: + - 主:`ext_image_copy_capture_manager_v1` / `ext_image_copy_capture_session_v1`(version 1) + - 附加:`ext_output_image_capture_source_manager_v1` / + `ext_foreign_toplevel_image_capture_source_manager_v1` / + `ext_image_capture_source_v1`(version 1) + - 窗口夹具:`ext_foreign_toplevel_list_v1`、`xdg_shell`、`wl_subcompositor`、 + `zxdg_decoration_manager_v1`、`zwlr_output_power_manager_v1`、`treeland_ddm_v1` +- 测试源码:`tests/protocols/wayland-ext-image-copy-capture-v1/` +- Fixture:输出工厂测试使用 1920×1080 headless output;窗口捕获测试使用 800×600 + headless output、固定不透明背景、隐藏光标、关闭开/关窗动画和 output layers。 + 最大化几何动画保持启用,按真实 `finished` 信号同步;指针设备经过 wlroots/seat/QtQuick + 驱动生产 SSD DragHandler,不经过 libinput/uinput。关屏场景中再添加一块 800×600 输出, + 将窗口移到第二块屏,再通过真实 power-management 请求关闭捕获管线的原输出。 +- Targets:`test_wayland_ext_image_copy_capture_v1`(P)、 + `test_wayland_ext_toplevel_image_capture_v1`(E / V / P) + 和可选 `test_wayland_ext_toplevel_image_capture_v1_gpu`(同场景、GLES2、SHM 捕获读回)。 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 capture-source 管理器 + copy-capture 管理器 | 资源创建成功 | P | +| 创建输出源 | `create_source(wl_output)` | 返回非 NULL 的 capture source | P | +| 创建窗口源及会话 | 从真实 foreign-toplevel handle 创建 source,再 `create_session` | ARGB8888、窗口局部边界对应的 `buffer_size`、`done` | P / E | +| SSD 与递归子面 | 提交主面、负坐标/above/below/nested 子面,申请并捕获 SHM frame | 主面、递归子面及堆叠顺序、标题栏和外边框的真实像素;间隙透明,不包含阴影、背景或遮挡窗口 | V | +| 不改变屏幕 | 捕获后先回读生产 output buffer,不先重绘;再单独重绘和定向 `render(false)` | 每个提交帧整屏逐像素相等;每次捕获 render 前后 live QSG 节点矩阵不变;wrapper/surface 的位置、尺寸、父项、缩放、可见性和场景坐标不变;捕获 input 是独立且拒绝输入的子树;离屏渲染不增加真实输出 `commit_seq` | E / V | +| 重复捕获 | 同一个 session 连续捕获静止窗口 | 整幅图像逐像素相等,包括透明外边框,不能累积半透明像素 | V | +| 子面独立更新 | 仅 desynchronized nested 子面提交新 buffer,根面不 commit | 捕获到子面的新颜色 | V | +| 部分移出屏幕 | fixture 移动窗口到 `(-150,210)` 后捕获 | 捕获图像仍完整且使用相同局部坐标;实际屏幕像素与捕获前一致、几何不变 | E / V | +| 移动与 SSD 坐标 | 多次移动到正坐标、左上负坐标、右下超出屏幕的位置 | 捕获整幅图像与移动前逐像素相等,包括 SSD;live QSG 状态和实际屏幕无捕获副作用 | E / V | +| 共享 source | 创建两个 session,销毁第一个后更新子面 | 第二个 session 仍收到 `ready` 和新像素 | P / V | +| 离屏渲染失败及恢复 | 锁住真实捕获 swapchain 的全部空闲 buffer,两会话提交 frame 后执行生产离屏渲染,再释放 buffer 并重新捕获 | 每个挂起 frame 恰好收到一次 `failed(unknown)`,不收到 `ready` 或 `stopped`;共享视口保留,两会话恢复后均收到 `ready`,像素正确 | P / V | +| 窗口 resize | 根面提交 320×260 buffer,先使用旧捕获 buffer,再使用新 buffer | 新 `buffer_size`;旧 buffer 收到 `buffer_constraints`,新 buffer 收到 `ready` 和新区域像素;屏幕和窗口几何不受捕获影响 | P / V | +| 最大化拖动还原 | 客户端 `set_maximized`,提交 configure 指定尺寸,再通过 SSD 按下/移动/释放指针 | 最大化图像完整;拖动还原但客户端尚未提交小 buffer 时仍完整捕获旧内容;还原 buffer 到达后约束缩小,整幅图像与还原前逐像素相等;继续拖动及释放不造成 SSD 漂移/截断 | E / V / P | +| 停止、重启及销毁 | 销毁所有 session 后重建,捕获期间销毁 toplevel | 重启后 frame 成功;窗口销毁后 session 收到 `stopped` | P / E | +| 捕获管线生命周期 | 只创建 source 不建 session;同一窗口连续 3 次 “source → session → 捕获 → 销毁 session 和 source”;会话期间提前销毁 source resource | 空闲 source 不创建离屏视口;每次会话恰好一条管线,销毁后捕获视口数回到 0 且屏幕不变;source resource 销毁后仍存活的 session 继续收到 frame | P / V | +| 组件定义复用 | 重建捕获会话并检查生产 capture input 的 delegate | delegate 始终为 QmlEngine 的同一个 CaptureSurfaceContent 缓存组件;具体实例及视口仍随会话释放,SSD 和整图像素不变 | P / V | +| 请求之间的合成器渲染 | 两次捕获之间让捕获视口额外渲染一帧 | 下一次捕获仍收到 `ready`,不等待不会发生的渲染 | P / V | +| 待处理请求遇到关屏 | 同一批请求中先 `capture`,再对原输出 `set_mode(OFF)`;窗口已移到第二块屏 | 原输出 disabled、第二块屏 enabled,待处理 frame 仍收到 `ready`,视口未重建 | P / E | +| 关屏后继续捕获 | 原输出关闭后提交新的 nested 子面 buffer,再申请 frame | 收到 `ready` 和新颜色像素;兜底渲染的 `renderEnd` 不包含任何提交输出,各输出 `commit_seq` 不增加 | P / V | +| 关屏时渲染失败及恢复 | 原输出关闭时再次耗尽捕获 swapchain,提交 frame,释放 buffer 后重试 | frame 收到 `failed(unknown)`,同一 session/视口恢复后捕获成功,输出保持关闭且未被离屏渲染提交 | P / V | +| 复电恢复 | 对原输出 `set_mode(ON)` 后再捕获 | 通过原有输出时钟继续收到 `ready` | P / E | +| 取消排队的兜底 | 关屏后同一批请求中申请 frame,再销毁 frame、session 和 source | 视口回到 0,已销毁的视口不再产生兜底渲染 | P / E | +| 关屏后的新会话 | 原输出仍关闭、窗口位于第二块屏时,创建全新的 source/session 并捕获 | 新视口绑定当前启用输出,首次约束有效,收到 `ready` 和正确像素,销毁后视口回到 0 | P / V | +| 全局渲染暂停与恢复 | 输出启用和关闭时分别通过 DDM `disable_render` 暂停,仅提交一次 `capture`,再 `enable_render` | 暂停时不绘制、不发送 ready/failed/stopped;恢复后原帧收到 ready,视口未重建,关屏路径仍不提交真实输出 | P / V | +| 暂停期间取消 | 暂停后销毁 frame/session/source,再恢复渲染 | 离屏视口归零,恢复不增加捕获渲染次数 | P / E | +| 暂停期间窗口失效 | 暂停后提交 frame,再销毁 toplevel | frame 收到 stopped 失败、session 收到 stopped;恢复不渲染已销毁视口 | P / E | + +## 生产结果 + +输出工厂测试观察 Treeland 通过 wlroots 提供的输出图像捕获服务:客户端从真实 headless +`wl_output` 创建并销毁 capture source。 + +窗口测试经过 Session 的生产 foreign-toplevel 工厂、`src/session/toplevelcapturesource.*`、 +`src/session/toplevelcaptureviewport.*` 和 `WExtImageCaptureSourceV1Impl`,由纯 C 客户端 +读取最终 SHM 像素和 frame 元数据(normal transform、有效 presentation time、damage、ready)。 +捕获通过独立的只读 `WSurfaceItem` 递归渲染同一个 wl_surface tree,SSD 标题栏/边框也是 +独立节点,不创建阴影。捕获不重父项、不移动 live item、不引用 live QSG 子树或屏幕区域。 +CaptureSurfaceContent 与 Border 的 QQmlComponent 定义由 QmlEngine 持有;捕获视口 +复用定义,但仍创建自己的内容、标题栏和边框实例。Border 通过统一工厂创建, +不传递该 QML 类型不存在的 surface 属性。该检查证明组件对象复用,不是编译耗时基准。 + +捕获管线属于发起请求的客户端,而不是被捕获的窗口:`accept()` 只创建 client resource, +`start()` 在第一个 session 到来时才创建离屏视口,最后一个 `stop()` 同步释放视口, +client resource 与 session 都不存在时销毁 source 包装对象。因此空闲 source、反复截图和 +中途销毁 source resource 都不会在网络窗口生命周期内累积 `WSurfaceItem` 副本、SSD、 +swapchain 或渲染窗口的 output helper。释放后 `source.width/height` 与 SHM 格式保留, +下个 session 在首次渲染前就能拿到正确约束;swapchain 派生的 DMA-BUF 约束在重建后由 +首帧刷新。`request_frame` 不依赖 wlroots 的 damage 调度提示,离屏视口按需渲染, +避免请求之间发生合成器渲染时客户端永远等不到 frame。 +输出启用时沿用输出 frame 时钟;输出关闭时排队执行 `render(false)`,不重建管线, +也不向屏幕提交。`enabledChanged` 会重新安排尚未完成的请求,渲染重入则等当前 +`renderEnd` 后再调度;最后一个 session 停止或 source 失效时清除排队状态。 +全局 `renderEnabled=false` 表示暂停而非捕获失败:保留挂起请求,不轮询重试; +恢复渲染时通过状态变化通知重新安排请求,包括借用输出仍关闭的离屏兜底。 +暂停回归经过真实 DDM 请求及其 disable 回调,同时覆盖先暂停再请求,以及同批请求 +先 capture 再 disable_render、已排队 fallback 尚未执行的情况。请求处理后的服务端排队读取作为 +队列同步点,不执行渲染;恢复后只观察原帧结果,不补发 capture、不强制 render, +也不通过移动窗口或启用输出帮助唤醒。 +已排队 fallback 的取消在全局渲染启用、借用输出关闭时单独验证;暂停期间取消 +使用另一条会话验证,避免暂停阻止排队后仍声称覆盖了排队任务的回收。 +渲染失败回归通过持有真实 swapchain buffer 引用,让生产 `wlr_swapchain_acquire()` +没有空闲槽位可用;不替换 allocator/renderer,也不直接发送失败信号或协议 event。 +客户端先通过真实请求提交 frame,再定向调用生产 `render(false)` 完成失败尝试, +以 roundtrip 验证每个 frame 的失败事件;释放引用后验证同一会话恢复和最终像素。 +生产视口在本轮渲染清理完成、`inRendering` 为 false 后报告失败;捕获源通过现有 +wlroots frame 分发路径结束所有挂起帧,返回 `unknown`,不停止会话或重建视口。 +失败帧不发送 transform、damage 或 presentation_time 元数据,也不回传旧缓存图像。 +下一次客户端 `capture` 请求重新调度渲染。 +夹具提供无标准客户端请求的窗口定位、指针设备事件和生产屏幕/几何/QSG 回读, +不伪造 source、frame、maximize 或 restore 结果。 + +每次捕获 renderer 的 `beforeRendering` / `afterRendering` 直接比较 live 节点矩阵; +这样动画导致的正常几何变化不被误判,也不会先强制重绘屏幕把共享节点污染覆盖掉。 +整屏比较在预计不变的阶段逐提交帧执行,预期变化阶段暂停比较后重新取基线。 +销毁窗口前暂停“不应变化”的像素比较,窗口引用使用 `QPointer`;捕获期间的观察器 +不使用已销毁窗口的裸指针。屏幕基线固定读回 ARGB8888 并检查图像分配/读回结果, +不把 renderer 的 preferred format 直接传给可能不支持它的 QImage 转换。 + +在创建任何捕获 source/session 之前,先在相同正/负坐标移动窗口并重复渲染,断言对照场景 +稳定。框架禁用了壁纸进程,因此必须提供固定不透明背景:软件 renderer 保留 output +buffer 时,没有背景会留下旧窗口像素,并在重复重绘时叠加阴影,造成与捕获无关的 +差异。测试不通过屏蔽阴影区域、设置像素容差或跳过整屏对比来规避这个问题。 +指针光标在基线建立之前隐藏;保留指针设备和真实事件路径,不通过屏蔽光标像素规避差异。 + +800×600 输出由生产 `OutputManager` 完成注册和启用;夹具不提前启用它,避免框架先 +将其加入 layout、随后生产移除/重新注册时销毁仍在使用的 cursor layers。 + +## 运行与取证 + +```bash +cmake --build build --target test_wayland_ext_toplevel_image_capture_v1 +ctest --test-dir build -R '^test_wayland_ext_toplevel_image_capture_v1$' -V +ctest --test-dir build -R '^test_wayland_ext_toplevel_image_capture_v1$' \ + --repeat until-fail:20 --output-on-failure + +# 有可用 DRM render node 的机器上检查相同场景的 GPU 渲染路径 +cmake --preset ci -DTREELAND_ENABLE_GPU_PROTOCOL_TESTS=ON +cmake --build build --target test_wayland_ext_toplevel_image_capture_v1_gpu +ctest --test-dir build -R '^test_wayland_ext_toplevel_image_capture_v1_gpu$' -V +``` + +设置 `TREELAND_CAPTURE_TEST_IMAGE=/tmp/opencode/toplevel-capture.pam` 可保存初始捕获图像; +屏幕对比失败时,同时保存该路径后缀为 `.before.png` / `.after.png` 的原始整屏图像。 + +### 已有版本验证证据 + +- `ci` preset(`-Wall -Wextra -Werror`)构建通过,无告警。 +- headless + pixman:包含生命周期与“请求之间额外渲染”用例的最终版本连续 20 次通过。 +- headless + GLES2:Intel UHD Graphics 630(i915)、OpenGL ES 3.2 / Mesa 26.2.6, + 同一版本连续 20 次通过,非 skip、非软件 fallback。 +- 捕获、SSD、递归子面、foreign-toplevel、window-transition、alpha-modifier、decoration、 + remote-subsurface、input-manager 等相关 10 项回归全部通过。 +- 尚无可访问的运行中 Treeland 桌面;物理 DRM/KMS scanout 和完整 libinput/uinput + 输入链路未验收,以上 headless 结果不能替代用户桌面的捕获瞬间验证。 + +### 关屏兜底修复验证 + +- `ci` preset(`-Wall -Wextra -Werror`)构建通过。 +- 未修复实现运行新增用例时在 30 秒超时;协议日志确认先收到 `capture()`,再收到 + `set_mode(OFF)` 的成功事件,之后没有 frame 结果。 +- Qt 6.12.0,headless + pixman / GLES2:包含关屏、新像素、复电、排队取消及关屏后 + 新会话输出解析的最终场景,各连续 20 次通过。GLES2 实际打开 `/dev/dri/renderD128`, + 通过 renderer 和像素断言,非 skip、非 pixman fallback。 +- 相关 11 项回归中 10 项通过。`test_wlr_output_management_unstable_v1` 在 stage 8 + 的旋转断言失败(请求 90°、读回 0°);该用例不创建捕获源,在旋转动画完成前读取 + 状态。本次未修改输出管理实现或该用例。 +- 物理 DRM/KMS scanout 与完整 libinput/uinput 输入链路仍未验收。 + +### 离屏渲染失败回归 + +- 未修复实现运行新增用例时,真实 swapchain 报告 `No free output buffer slot`, + 渲染尝试已结束,但客户端为 `ready=0`、`failed=0`、`stopped=0`,用例明确失败。 +- 回归同时断言失败通知发生在渲染清理后、多会话各收到一次 `failed(unknown)`、 + 不发送成功帧元数据、会话和视口保持有效,以及释放 buffer 后重新捕获成功。 +- 原输出关闭时重复上述失败与恢复,并验证输出未被提交、视口未重建。 +- 本次 `-Wall -Wextra -Werror` 构建通过;headless + pixman / GLES2 的完整场景各 + 连续 5 次通过。GLES2 实际使用 `/dev/dri/renderD128`,无 skip 或软件 fallback。 +- 捕获、desktop capture、递归子面、decoration、foreign-toplevel、input-manager、 + window-transition、alpha-modifier、输出管理等另外 12 项相关协议回归全部通过。 + +### 全局暂停恢复与组件复用 + +- 未修复实现在 DDM `enable_render` 后仍留下关屏输出的挂起帧,客户端为 + `ready=0`、`failed=0`;队列同步点不执行绘制,用例明确失败。 +- 暂停期间不结束有效捕获请求;恢复后验证单次请求完成,不靠新请求、场景变化、 + 强制绘制或复电辅助唤醒。暂停期间取消和窗口销毁均检查恢复后的渲染次数。 +- 每次捕获管线重建均检查 delegate 与引擎缓存组件的指针一致,并继续验证全部 + SSD、子面和整图像素以及最后一个 session 的视口回收。 +- `-Wall -Wextra -Werror` 构建通过;包含已排队 fallback 遇到暂停的最终场景在 + headless + pixman / GLES2 各连续 5 次通过。GLES2 实际使用 `/dev/dri/renderD128`, + 无 skip 或软件 fallback;另外 13 项相关协议回归全部通过。 +- 尚未验证物理 DRM/VT 切换;组件复用没有单独测量编译或启动耗时。 + +## 已知边界 / 下一项结果 + +输出工厂 target 仍不创建 output capture session:headless 下进入 +`wlr_output_configure_primary_swapchain()` 的历史死锁(issue #1407)未由本窗口测试验证。 +窗口捕获使用独立的离屏 swapchain,不受此输出源测试边界限制。 + +GPU target 没有可访问 render node 时以 `77` skip,不允许以软件 fallback 代替 GPU 成功。 +`QDir::System` 预检只检查节点能否打开;成功后仍必须通过 GLES2 renderer 和像素断言, +不能仅凭节点存在宣告 GPU 通过。GPU target 仍使用 SHM 客户端目的 buffer, +尚未覆盖客户端 DMA-BUF、fractional scale、多屏混合缩放/输出销毁、minimized/完全离屏窗口、 +popup、cursor capture 和跨 Session 拒绝路径。 +渲染失败回归覆盖真实 swapchain 槽位耗尽;显存不足、超出 GPU 尺寸限制及渲染目标 +导入失败尚未单独注入验证。 diff --git a/tests/protocols/wayland-ext-image-copy-capture-v1/setup.cpp b/tests/protocols/wayland-ext-image-copy-capture-v1/setup.cpp new file mode 100644 index 0000000000..9cea9fbc5a --- /dev/null +++ b/tests/protocols/wayland-ext-image-copy-capture-v1/setup.cpp @@ -0,0 +1,10 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "server-bridge.h" +#include "core/waylandserver.h" +#include + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); +} diff --git a/tests/protocols/wayland-ext-image-copy-capture-v1/toplevel-setup.cpp b/tests/protocols/wayland-ext-image-copy-capture-v1/toplevel-setup.cpp new file mode 100644 index 0000000000..443c846b99 --- /dev/null +++ b/tests/protocols/wayland-ext-image-copy-capture-v1/toplevel-setup.cpp @@ -0,0 +1,658 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wayland-ext-toplevel-image-capture-v1.h" +#include "server-bridge.h" +#include "core/rootsurfacecontainer.h" +#include "core/qmlengine.h" +#include "core/shellhandler.h" +#include "core/waylandserver.h" +#include "output/output.h" +#include "surface/surfacewrapper.h" +#include "surface/surfacecontainer.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#ifdef TREELAND_CAPTURE_TEST_GPU +#include +#include +#include +#endif + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +QPointer g_target; +QPointer g_occluder; +QImage g_screen; +QPointF g_position, g_surfacePosition, g_scenePosition; +QSizeF g_size, g_surfaceSize; +QQuickItem *g_parent = nullptr; +QQuickItem *g_surfaceParent = nullptr; +qreal g_scale = 0, g_surfaceScale = 0; +bool g_visible = false, g_surfaceVisible = false; +bool g_tracking = false, g_screenUnchanged = true, g_renderStateUnchanged = true; +int g_captureFramesChecked = 0; +int g_captureRenderAttempts = 0; +wlr_pointer *g_pointer = nullptr; +uint32_t g_inputTime = 0; +QPointer g_captureOutput; +QPointer g_captureViewport; +QPointer g_blockedViewport; +std::vector g_captureBuffers; +int g_disabledFrames = 0; +bool g_disabledFramesDidNotCommit = true; + +Output *findOutput(WOutput *output) +{ + for (auto *candidate : WaylandServer::instance()->rootSurfaceContainer()->outputs()) { + if (candidate->output() == output) + return candidate; + } + return nullptr; +} + +WOutput *addOutput(WaylandServer *server) +{ + wlr_backend *headless = nullptr; + wlr_multi_for_each_backend( + server->backend()->handle(), + [](wlr_backend *backend, void *data) { + if (wlr_backend_is_headless(backend)) + *static_cast(data) = backend; + }, + &headless); + auto *output = headless ? wlr_headless_add_output(headless, 800, 600) : nullptr; + if (!output) + qFatal("Could not add capture test output"); + return WOutput::fromHandle(output); +} + +QHash nodeMatrices(QSGNode *root) +{ + QHash matrices; + if (!root) + return matrices; + switch (root->type()) { + case QSGNode::TransformNodeType: + matrices.insert(root, static_cast(root)->combinedMatrix()); + break; + case QSGNode::GeometryNodeType: + case QSGNode::ClipNodeType: { + auto *node = static_cast(root); + matrices.insert(root, node->matrix() ? *node->matrix() : QMatrix4x4()); + break; + } + case QSGNode::RenderNodeType: { + auto *node = static_cast(root); + matrices.insert(root, node->matrix() ? *node->matrix() : QMatrix4x4()); + break; + } + default: + break; + } + for (auto *child = root->firstChild(); child; child = child->nextSibling()) + matrices.insert(nodeMatrices(child)); + return matrices; +} + +WOutputViewport *screenViewport() +{ + return WaylandServer::instance()->rootSurfaceContainer()->outputs().first()->screenViewport(); +} + +QImage readScreen() +{ + auto *viewport = screenViewport(); + auto *provider = viewport->wTextureProvider(); + auto *buffer = provider ? provider->wlrBuffer() : nullptr; + if (!buffer) + return {}; + WBufferUnlockPtr guard(wlr_buffer_lock(buffer)); + WUniquePointer texture(wlr_texture_from_buffer(viewport->output()->renderer(), buffer)); + if (!texture) + return {}; + // Use the same explicit format as the capture client. A renderer's + // preferred format (e.g. XBGR8888) need not have a WTools/QImage mapping; + // passing a null image to glReadPixels would crash before capture starts. + QImage image(buffer->width, buffer->height, QImage::Format_ARGB32_Premultiplied); + if (image.isNull()) + qFatal("Could not allocate capture test output readback image"); + const wlr_texture_read_pixels_options options { + .data = image.bits(), + .format = DRM_FORMAT_ARGB8888, + .stride = uint32_t(image.bytesPerLine()), + .dst_x = 0, + .dst_y = 0, + .src_box = {}, + }; + if (!wlr_texture_read_pixels(texture.get(), &options)) + qFatal("Could not read capture test output pixels as ARGB8888"); + return image; +} + +class CaptureRenderObserver : public QObject +{ +public: + explicit CaptureRenderObserver(WBufferRenderer *renderer) + : QObject(renderer), m_renderer(renderer) + { + connect(renderer, &WBufferRenderer::beforeRendering, this, &CaptureRenderObserver::beforeRender); + connect(renderer, &WBufferRenderer::afterRendering, this, &CaptureRenderObserver::afterRender); + connect(qobject_cast(renderer->parentItem()), &WOutputViewport::frameRenderFailed, + this, &CaptureRenderObserver::renderFailed); + connect(WaylandServer::instance()->window(), &WOutputRenderWindow::renderEnd, + this, &CaptureRenderObserver::frameFinished); + } + +private: + void renderFailed() + { + if (WaylandServer::instance()->window()->inRendering()) + qFatal("Capture render failure was reported before render cleanup"); + } + + void beforeRender() + { + ++g_captureRenderAttempts; + m_disabledFrame = !m_renderer->output()->isEnabled(); + m_outputCommits.clear(); + if (m_disabledFrame) { + for (auto *output : WaylandServer::instance()->rootSurfaceContainer()->outputs()) + m_outputCommits.append({output->output(), output->output()->handle()->commit_seq}); + } + m_matrices = g_target + ? nodeMatrices(QQuickItemPrivate::get(g_target.data())->itemNode()) + : QHash(); + } + + void afterRender() + { + if (!g_target || m_matrices.isEmpty()) + return; + ++g_captureFramesChecked; + const auto current = nodeMatrices(QQuickItemPrivate::get(g_target.data())->itemNode()); + for (auto it = m_matrices.cbegin(); it != m_matrices.cend(); ++it) { + const auto matrix = current.constFind(it.key()); + if (matrix != current.cend() && *matrix != it.value()) { + if (g_renderStateUnchanged) { + std::fprintf(stderr, "capture fixture: live QSG node %p translation %.1f,%.1f -> %.1f,%.1f\n", + static_cast(it.key()), it.value()(0, 3), it.value()(1, 3), + (*matrix)(0, 3), (*matrix)(1, 3)); + } + g_renderStateUnchanged = false; + } + } + } + + void frameFinished(const QList> &committedOutputs) + { + if (!m_disabledFrame) + return; + m_disabledFrame = false; + ++g_disabledFrames; + g_disabledFramesDidNotCommit &= committedOutputs.isEmpty(); + for (const auto &entry : std::as_const(m_outputCommits)) + g_disabledFramesDidNotCommit &= entry.first && entry.first->handle()->commit_seq == entry.second; + } + + WBufferRenderer *const m_renderer; + bool m_disabledFrame = false; + QList, uint32_t>> m_outputCommits; + QHash m_matrices; +}; + +void observeScreenFrame() +{ + if (!g_tracking || !g_target || g_screen.isNull()) + return; + const auto current = readScreen(); + if (current == g_screen) + return; + if (g_screenUnchanged && current.size() == g_screen.size()) { + for (int y = 0; y < current.height(); ++y) { + bool found = false; + for (int x = 0; x < current.width(); ++x) { + if (current.pixel(x, y) != g_screen.pixel(x, y)) { + std::fprintf(stderr, "capture fixture: output pixel %d,%d %08x -> %08x; window %.1f,%.1f\n", + x, y, g_screen.pixel(x, y), current.pixel(x, y), g_target->x(), g_target->y()); + found = true; + break; + } + } + if (found) + break; + } + } + g_screenUnchanged = false; +} + +void observeViewport(WOutputViewport *viewport) +{ + if (viewport->offscreen()) { + auto *renderer = viewport->findChild(); + Q_ASSERT(renderer); + new CaptureRenderObserver(renderer); + } else { + QObject::connect(viewport, &WOutputViewport::frameRendered, + WaylandServer::instance(), observeScreenFrame); + } +} + +bool isCaptureViewport(WOutputViewport *viewport) +{ + auto *item = qobject_cast(viewport->input()); + return g_target && viewport->offscreen() && !viewport->hideSource() && item + && item->surface() == g_target->surface(); +} + +void saveGeometry() +{ + auto *item = g_target->surfaceItem(); + g_position = g_target->position(); + g_size = g_target->size(); + g_parent = g_target->parentItem(); + g_scale = g_target->scale(); + g_visible = g_target->isVisible(); + g_surfacePosition = item->position(); + g_surfaceSize = item->size(); + g_surfaceParent = item->parentItem(); + g_surfaceScale = item->scale(); + g_surfaceVisible = item->isVisible(); + g_scenePosition = item->mapToScene(QPointF()); + g_screenUnchanged = true; + g_captureFramesChecked = 0; + g_tracking = true; +} + +void readState(void *data) +{ + auto *state = static_cast(data); + *state = {}; + if (!g_target || !g_target->surfaceItem()) + return; + auto *item = g_target->surfaceItem(); + state->valid = g_target->surface() && g_target->surface()->mapped(); + state->titlebar_height = g_target->titleBar() ? qRound(g_target->titleBar()->height()) : 0; + state->width = qRound(item->width()); + state->height = qRound(item->height()); + const QRect bounds = item->boundingRect().toAlignedRect(); + state->bounds_x = bounds.x(); + state->bounds_y = bounds.y(); + state->bounds_width = bounds.width(); + state->bounds_height = bounds.height(); + state->geometry_unchanged = g_target->position() == g_position && g_target->size() == g_size + && g_target->parentItem() == g_parent && g_target->scale() == g_scale + && g_target->isVisible() == g_visible && item->position() == g_surfacePosition + && item->size() == g_surfaceSize && item->parentItem() == g_surfaceParent + && item->scale() == g_surfaceScale && item->isVisible() == g_surfaceVisible + && item->mapToScene(QPointF()) == g_scenePosition; + const QImage current = readScreen(); + state->screen_unchanged = g_screenUnchanged && !g_screen.isNull() && current == g_screen; + state->render_state_unchanged = g_renderStateUnchanged; + state->capture_frames_checked = g_captureFramesChecked; + state->maximized = g_target->isMaximized(); + state->dragging = WaylandServer::instance()->rootSurfaceContainer()->moveResizeSurface() == g_target; + state->border_visible = !g_target->noDecoration() && g_target->visibleDecoration() + && g_target->borderVisible(); + state->position_x = qRound(g_target->x()); + state->position_y = qRound(g_target->y()); + if (g_tracking && !state->geometry_unchanged) { + std::fprintf(stderr, "capture fixture: position %.1f,%.1f -> %.1f,%.1f; scene %.1f,%.1f -> %.1f,%.1f\n", + g_position.x(), g_position.y(), g_target->x(), g_target->y(), + g_scenePosition.x(), g_scenePosition.y(), + item->mapToScene(QPointF()).x(), item->mapToScene(QPointF()).y()); + } + if (g_tracking && !state->screen_unchanged && !qEnvironmentVariableIsEmpty("TREELAND_CAPTURE_TEST_IMAGE")) { + g_screen.save(QString::fromLocal8Bit(qgetenv("TREELAND_CAPTURE_TEST_IMAGE")) + ".before.png"); + current.save(QString::fromLocal8Bit(qgetenv("TREELAND_CAPTURE_TEST_IMAGE")) + ".after.png"); + } + const auto viewports = WaylandServer::instance()->window()->contentItem()->findChildren(); + for (auto *viewport : viewports) { + if (isCaptureViewport(viewport)) { + ++state->offscreen_viewports; + auto *input = qobject_cast(viewport->input()); + if (input->delegate() == WaylandServer::instance()->qmlEngine()->captureSurfaceContentComponent()) + ++state->shared_delegates; + if (input != item && !input->eventItem()) + ++state->isolated_inputs; + } + } + // The occluder covers this target-content point in the actual output. + // Its magenta pixel must never appear in the isolated window capture. + const QPoint covered = item->mapToScene(QPointF(100, state->titlebar_height + 90)).toPoint(); + state->occluder_visible = current.rect().contains(covered) + && current.pixelColor(covered) == QColor(255, 0, 255); +} + +void pointerMotion(int x, int y) +{ + wlr_pointer_motion_absolute_event event { + .pointer = g_pointer, + .time_msec = ++g_inputTime, + .x = x / 800.0, + .y = y / 600.0, + }; + wl_signal_emit_mutable(&g_pointer->events.motion_absolute, &event); + wl_signal_emit_mutable(&g_pointer->events.frame, nullptr); +} + +void pointerButton(wl_pointer_button_state state) +{ + wlr_pointer_button_event event { + .pointer = g_pointer, + .time_msec = ++g_inputTime, + .button = 0x110, + .state = state, + }; + wl_signal_emit_mutable(&g_pointer->events.button, &event); + wl_signal_emit_mutable(&g_pointer->events.frame, nullptr); +} +} + +void protocol_test_setup(WaylandServer *server) +{ +#ifdef TREELAND_CAPTURE_TEST_GPU + auto *renderer = server->window()->renderer(); + if (!wlr_renderer_is_gles2(renderer) || wlr_renderer_get_drm_fd(renderer) < 0) + qFatal("GPU capture test must use the GLES2 renderer, not a software fallback"); +#endif + // The framework disables the wallpaper process. Supply an opaque scene + // background so the software renderer's preserved buffers can repaint + // exposed pixels, rather than accumulate shadows over stale window pixels. + QQmlComponent background(server->qmlEngine()); + background.setData( + "import QtQuick; Rectangle { width: 800; height: 600; color: '#102030'; z: -1 }", + QUrl()); + auto *item = qobject_cast(background.create()); + if (!item) + qFatal("Could not create capture test background"); + item->setParent(server->window()->contentItem()); + item->setParentItem(server->window()->contentItem()); + + // Let OutputManager register and enable the output after its configuration + // is ready. Enabling it here makes the framework add it to the layout too + // early, then production removes/re-adds it while cursor layers are live. + addOutput(server); + server->window()->setDisableLayers(true); + server->setAnimationSpeed(0.1f); + attach_test_pointer_device(server); + for (auto *device : server->seat()->deviceList()) { + if (device->type() == WInputDevice::Type::Pointer) + g_pointer = wlr_pointer_from_input_device(device->handle()); + } + Q_ASSERT(g_pointer); + server->seat()->cursor()->setVisible(false); + QObject::connect(server->window(), &WOutputRenderWindow::outputViewportInitialized, + server, observeViewport); + QObject::connect(server->shellHandler(), &ShellHandler::surfaceWrapperAdded, server, + [](SurfaceWrapper *wrapper) { wrapper->disableWindowAnimation(); }); +} + +#ifdef TREELAND_CAPTURE_TEST_GPU +extern "C" bool protocol_test_preflight() +{ + const QDir dri(QStringLiteral("/dev/dri")); + const auto nodes = dri.entryList({QStringLiteral("renderD*")}, QDir::System); + for (const auto &node : nodes) { + const auto path = dri.filePath(node).toLocal8Bit(); + const int fd = open(path.constData(), O_RDWR | O_CLOEXEC); + if (fd >= 0) { + close(fd); + std::fprintf(stderr, "GPU capture test: accessible DRM render node %s\n", path.constData()); + return true; + } + } + std::fprintf(stderr, "GPU capture test skipped: no accessible DRM render node\n"); + return false; +} +#endif + +extern "C" void toplevel_capture_prepare(void *data) +{ + for (auto *wrapper : WaylandServer::instance()->rootSurfaceContainer()->surfaces()) { + if (wrapper->appId() == QLatin1String("capture-target")) + g_target = wrapper; + else if (wrapper->appId() == QLatin1String("capture-occluder")) + g_occluder = wrapper; + } + if (!g_target || !g_occluder) { + *static_cast(data) = {}; + return; + } + g_tracking = false; + g_target->setPositionAutomatic(false); + g_target->setPosition(QPointF(100, 90)); + g_occluder->setPositionAutomatic(false); + g_occluder->setPosition(QPointF(170, 170)); + g_occluder->stackToLast(); + g_occluder->setZ(10); + WaylandServer::instance()->activateSurface(g_target); + screenViewport()->render(true); + saveGeometry(); + g_screen = readScreen(); + readState(data); +} + +extern "C" void toplevel_capture_check_screen(void *data) +{ + readState(data); +} + +extern "C" void toplevel_capture_repaint_screen(void *data) +{ + screenViewport()->render(true); + readState(data); +} + +extern "C" void toplevel_capture_save_screen(void *data) +{ + g_tracking = false; + screenViewport()->render(true); + saveGeometry(); + g_screen = readScreen(); + readState(data); +} + +extern "C" void toplevel_capture_render_offscreen(void *data) +{ + auto *output = screenViewport()->output()->handle(); + const uint32_t commits = output->commit_seq; + const auto viewports = WaylandServer::instance()->window()->contentItem()->findChildren(); + for (auto *viewport : viewports) { + if (isCaptureViewport(viewport) && viewport->isVisible()) + viewport->render(false); + } + readState(data); + static_cast(data)->capture_only_did_not_commit = output->commit_seq == commits; +} + +extern "C" void toplevel_capture_hold_buffers(void *data) +{ + if (g_blockedViewport || !g_captureBuffers.empty()) + qFatal("Capture swapchain buffers are already held"); + const auto viewports = WaylandServer::instance()->window()->contentItem()->findChildren(); + for (auto *viewport : viewports) { + if (!isCaptureViewport(viewport)) + continue; + if (g_blockedViewport) + qFatal("Expected a single shared capture viewport"); + g_blockedViewport = viewport; + auto *swapchain = viewport->swapchain(); + if (!swapchain) + qFatal("Capture swapchain must be initialized before exhausting its buffers"); + bool exhausted = false; + for (size_t i = 0; i <= WLR_SWAPCHAIN_CAP; ++i) { + auto *buffer = wlr_swapchain_acquire(swapchain); + if (!buffer) { + exhausted = true; + break; + } + g_captureBuffers.emplace_back(buffer); + } + if (!exhausted) + qFatal("Could not exhaust capture swapchain buffers"); + } + *static_cast(data) = g_captureBuffers.size(); +} + +extern "C" void toplevel_capture_release_buffers(void *data) +{ + *static_cast(data) = g_blockedViewport && isCaptureViewport(g_blockedViewport.data()); + g_captureBuffers.clear(); + g_blockedViewport = nullptr; +} + +extern "C" void toplevel_capture_move_partly_offscreen(void *data) +{ + // No standard xdg request positions a toplevel; this is a directed fixture + // move, not a fabricated capture result. The capture must remain complete. + g_tracking = false; + g_target->setPosition(QPointF(-150, 210)); + toplevel_capture_save_screen(data); +} + +extern "C" void toplevel_capture_pause_checks(void *) +{ + // Expected scene changes must not be mistaken for capture side effects. + // The per-render QSG observer stays active, including during animations. + g_tracking = false; +} + +extern "C" void toplevel_capture_move_window(void *data) +{ + auto *move = static_cast(data); + g_tracking = false; + g_target->setPosition(QPointF(move->x, move->y)); + toplevel_capture_save_screen(&move->state); +} + +extern "C" void toplevel_capture_wait_transition(void *data) +{ + g_tracking = false; + auto *window = WaylandServer::instance()->window(); + window->render(); + if (g_target->isAnimationRunning()) { + QQuickItem *animation = nullptr; + for (auto *child : g_target->container()->childItems()) { + if (child->property("surface").value() == g_target) { + animation = child; + break; + } + } + if (!animation) + qFatal("Could not observe capture target geometry animation"); + QEventLoop loop; + QObject::connect(animation, SIGNAL(finished()), &loop, SLOT(quit())); + loop.exec(); + } + readState(data); +} + +extern "C" void toplevel_capture_drag_begin(void *data) +{ + g_tracking = false; + // Use the real SSD DragHandler -> moveRequested -> per-seat restore path, + // not an unmaximize request or a fixture write to the window state. + pointerMotion(300, 15); + pointerButton(WL_POINTER_BUTTON_STATE_PRESSED); + pointerMotion(335, 55); + readState(data); +} + +extern "C" void toplevel_capture_drag_move(void *data) +{ + auto *move = static_cast(data); + g_tracking = false; + pointerMotion(move->x, move->y); + toplevel_capture_save_screen(&move->state); +} + +extern "C" void toplevel_capture_drag_end(void *data) +{ + g_tracking = false; + pointerButton(WL_POINTER_BUTTON_STATE_RELEASED); + toplevel_capture_save_screen(data); +} + +extern "C" void toplevel_capture_read_output_state(void *data) +{ + auto *state = static_cast(data); + *state = {}; + const auto outputs = WaylandServer::instance()->rootSurfaceContainer()->outputs(); + state->output_count = outputs.size(); + for (auto *output : outputs) + state->enabled_outputs += output->output()->isEnabled(); + auto *targetOutput = g_target && g_target->ownsOutput() ? g_target->ownsOutput()->output() : nullptr; + state->target_on_other_output = targetOutput && targetOutput != g_captureOutput + && targetOutput->isEnabled(); + state->capture_output_enabled = g_captureOutput && g_captureOutput->isEnabled(); + const auto viewports = WaylandServer::instance()->window()->contentItem()->findChildren(); + for (auto *viewport : viewports) { + if (viewport->offscreen()) + ++state->offscreen_viewports; + if (isCaptureViewport(viewport)) { + state->enabled_capture_viewports += viewport->output()->isEnabled(); + state->viewport_unchanged |= viewport == g_captureViewport; + } + } + state->disabled_frames = g_disabledFrames; + state->disabled_frames_did_not_commit = g_disabledFramesDidNotCommit; + state->render_attempts = g_captureRenderAttempts; + state->render_enabled = WaylandServer::instance()->window()->renderEnabled(); +} + +extern "C" void toplevel_capture_add_output(void *data) +{ + g_tracking = false; + auto *server = WaylandServer::instance(); + const auto viewports = server->window()->contentItem()->findChildren(); + for (auto *viewport : viewports) { + if (isCaptureViewport(viewport)) + g_captureViewport = viewport; + } + if (!g_captureViewport) + qFatal("No active capture viewport before adding another output"); + g_captureOutput = g_captureViewport->output(); + if (g_captureOutput != server->rootSurfaceContainer()->outputs().first()->output()) + qFatal("Capture test must bind the first wl_output before adding another output"); + auto *output = addOutput(server); + QEventLoop loop; + const auto ready = [output] { return findOutput(output) && output->isEnabled(); }; + const auto quitWhenReady = [&] { + if (ready()) + loop.quit(); + }; + QObject::connect(server->rootSurfaceContainer()->outputModel(), &QAbstractItemModel::rowsInserted, + &loop, quitWhenReady); + QObject::connect(output, &WOutput::enabledChanged, &loop, quitWhenReady); + if (!ready()) + loop.exec(); + server->rootSurfaceContainer()->moveSurfacesToOutput( + {g_target.data(), g_occluder.data()}, findOutput(output), g_target->ownsOutput()); + toplevel_capture_read_output_state(data); +} diff --git a/tests/protocols/wayland-ext-image-copy-capture-v1/wayland-ext-image-copy-capture-v1.c b/tests/protocols/wayland-ext-image-copy-capture-v1/wayland-ext-image-copy-capture-v1.c new file mode 100644 index 0000000000..21a9736678 --- /dev/null +++ b/tests/protocols/wayland-ext-image-copy-capture-v1/wayland-ext-image-copy-capture-v1.c @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Test the ext_image_copy_capture_manager_v1 + ext_output_image_capture_source_manager_v1 + * globals served by Treeland (wlr_ext_image_copy_capture_manager_v1_create and + * wlr_ext_output_image_capture_source_manager_v1_create in WaylandServer). + * The client binds both managers and verifies they are advertised by the + * compositor. (Creating a capture session in headless mode can deadlock in + * wlr_output_configure_primary_swapchain (see issue #1407), so we test global presence + create_source only.) + */ + +#include "client-connection.h" +#include "ext-image-copy-capture-v1-client-protocol.h" +#include "ext-image-capture-source-v1-client-protocol.h" +#include +#include + + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("ext-image-copy-capture: connect failed\n"); + return 1; + } + + struct ext_output_image_capture_source_manager_v1 *src_mgr = + client_bind(&conn, ext_output_image_capture_source_manager_v1_interface.name, &ext_output_image_capture_source_manager_v1_interface, ext_output_image_capture_source_manager_v1_interface.version); + struct ext_image_copy_capture_manager_v1 *cap_mgr = client_bind(&conn, + ext_image_copy_capture_manager_v1_interface.name, &ext_image_copy_capture_manager_v1_interface, ext_image_copy_capture_manager_v1_interface.version); + if (src_mgr == NULL || cap_mgr == NULL) { + TEST_ERROR("ext-image-copy-capture: failed to bind managers: %s\n", strerror(errno)); + client_disconnect(&conn); + return 1; + } + + wl_display_roundtrip(conn.display); + + /* Verify that create_source(wl_output) returns a non-NULL source object. + * We create and immediately destroy the source without starting a capture + * session, because creating a session in headless mode can deadlock in + * wlr_output_configure_primary_swapchain (see issue #1407). */ + struct wl_output *output = client_bind_last(&conn, wl_output_interface.name, + &wl_output_interface, wl_output_interface.version); + if (output == NULL) { + TEST_ERROR("ext-image-copy-capture: no wl_output global\n"); + ext_image_copy_capture_manager_v1_destroy(cap_mgr); + ext_output_image_capture_source_manager_v1_destroy(src_mgr); + client_disconnect(&conn); + return 1; + } + + struct ext_image_capture_source_v1 *source = + ext_output_image_capture_source_manager_v1_create_source(src_mgr, output); + if (source == NULL) { + TEST_ERROR("ext-image-copy-capture: create_source returned NULL\n"); + wl_output_destroy(output); + ext_image_copy_capture_manager_v1_destroy(cap_mgr); + ext_output_image_capture_source_manager_v1_destroy(src_mgr); + client_disconnect(&conn); + return 1; + } + + ext_image_capture_source_v1_destroy(source); + wl_output_destroy(output); + ext_image_copy_capture_manager_v1_destroy(cap_mgr); + ext_output_image_capture_source_manager_v1_destroy(src_mgr); + client_disconnect(&conn); + return 0; +} diff --git a/tests/protocols/wayland-ext-image-copy-capture-v1/wayland-ext-toplevel-image-capture-v1.c b/tests/protocols/wayland-ext-image-copy-capture-v1/wayland-ext-toplevel-image-capture-v1.c new file mode 100644 index 0000000000..f319443021 --- /dev/null +++ b/tests/protocols/wayland-ext-image-copy-capture-v1/wayland-ext-toplevel-image-capture-v1.c @@ -0,0 +1,1067 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#define _POSIX_C_SOURCE 200809L + +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "wayland-ext-toplevel-image-capture-v1.h" +#include "ext-image-capture-source-v1-client-protocol.h" +#include "ext-image-copy-capture-v1-client-protocol.h" +#include "ext-foreign-toplevel-list-v1-client-protocol.h" +#include "xdg-decoration-unstable-v1-client-protocol.h" +#include "wlr-output-power-management-unstable-v1-client-protocol.h" +#include "treeland-ddm-v1-client-protocol.h" + +#include +#include +#include +#include + +#define CHECK(condition, ...) do { \ + if (!(condition)) { TEST_ERROR(__VA_ARGS__); return 1; } \ +} while (0) + +enum { MAIN_WIDTH = 240, MAIN_HEIGHT = 180 }; +static const uint32_t main_color = 0xff204080; +static const uint32_t red = 0xffff0000; +static const uint32_t green = 0xff00ff00; +static const uint32_t yellow = 0xffffff00; +static const uint32_t orange = 0xffff8000; +static const uint32_t teal = 0xff00c0c0; + +struct shm_buffer { + struct wl_buffer *buffer; + uint32_t *pixels; + size_t size; + int width, height; +}; + +static int buffer_create(struct wl_shm *shm, struct shm_buffer *buffer, + int width, int height, uint32_t format, uint32_t color) +{ + static unsigned serial; + char name[80]; + snprintf(name, sizeof(name), "/treeland_capture_%ld_%u", (long)getpid(), serial++); + int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); + if (fd < 0) + return 0; + shm_unlink(name); + buffer->size = (size_t)width * height * 4; + if (ftruncate(fd, (off_t)buffer->size) < 0) { + close(fd); + return 0; + } + buffer->pixels = mmap(NULL, buffer->size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (buffer->pixels == MAP_FAILED) { + close(fd); + return 0; + } + struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, (int)buffer->size); + buffer->buffer = wl_shm_pool_create_buffer(pool, 0, width, height, width * 4, format); + wl_shm_pool_destroy(pool); + close(fd); + buffer->width = width; + buffer->height = height; + for (size_t i = 0; i < (size_t)width * height; ++i) + buffer->pixels[i] = color; + return buffer->buffer != NULL; +} + +static void buffer_destroy(struct shm_buffer *buffer) +{ + wl_buffer_destroy(buffer->buffer); + munmap(buffer->pixels, buffer->size); + *buffer = (struct shm_buffer){0}; +} + +static void attach(struct wl_surface *surface, struct shm_buffer *buffer) +{ + wl_surface_attach(surface, buffer->buffer, 0, 0); + wl_surface_damage(surface, 0, 0, buffer->width, buffer->height); + wl_surface_commit(surface); +} + +struct foreign_state { + struct ext_foreign_toplevel_handle_v1 *target; + int target_done; +}; + +static void foreign_closed(void *data, struct ext_foreign_toplevel_handle_v1 *handle) +{ + struct foreign_state *state = data; + if (state->target == handle) + state->target = NULL; + ext_foreign_toplevel_handle_v1_destroy(handle); +} + +static void foreign_done(void *data, struct ext_foreign_toplevel_handle_v1 *handle) +{ + struct foreign_state *state = data; + if (state->target == handle) + state->target_done = 1; +} + +static void foreign_title(void *data, struct ext_foreign_toplevel_handle_v1 *handle, const char *title) +{ + (void)data; (void)handle; (void)title; +} + +static void foreign_app_id(void *data, struct ext_foreign_toplevel_handle_v1 *handle, const char *app_id) +{ + if (strcmp(app_id, "capture-target") == 0) + ((struct foreign_state *)data)->target = handle; +} + +static void foreign_identifier(void *data, struct ext_foreign_toplevel_handle_v1 *handle, const char *identifier) +{ + (void)data; (void)handle; (void)identifier; +} + +static const struct ext_foreign_toplevel_handle_v1_listener foreign_listener = { + .closed = foreign_closed, + .done = foreign_done, + .title = foreign_title, + .app_id = foreign_app_id, + .identifier = foreign_identifier, +}; + +static void list_toplevel(void *data, struct ext_foreign_toplevel_list_v1 *list, + struct ext_foreign_toplevel_handle_v1 *handle) +{ + (void)list; + ext_foreign_toplevel_handle_v1_add_listener(handle, &foreign_listener, data); +} + +static void list_finished(void *data, struct ext_foreign_toplevel_list_v1 *list) +{ + (void)data; (void)list; +} + +static const struct ext_foreign_toplevel_list_v1_listener list_listener = { + .toplevel = list_toplevel, + .finished = list_finished, +}; + +static void decoration_configure(void *data, struct zxdg_toplevel_decoration_v1 *decoration, uint32_t mode) +{ + (void)decoration; + *(uint32_t *)data = mode; +} + +static const struct zxdg_toplevel_decoration_v1_listener decoration_listener = { + .configure = decoration_configure, +}; + +struct capture_session { + struct ext_image_copy_capture_session_v1 *session; + uint32_t width, height, format; + int done, stopped, has_shm; +}; + +static void session_size(void *data, struct ext_image_copy_capture_session_v1 *session, + uint32_t width, uint32_t height) +{ + (void)session; + struct capture_session *state = data; + state->width = width; + state->height = height; +} + +static void session_shm(void *data, struct ext_image_copy_capture_session_v1 *session, uint32_t format) +{ + (void)session; + struct capture_session *state = data; + if (!state->has_shm || format == WL_SHM_FORMAT_ARGB8888) + state->format = format; + state->has_shm = 1; +} + +static void session_device(void *data, struct ext_image_copy_capture_session_v1 *session, struct wl_array *device) +{ + (void)data; (void)session; (void)device; +} + +static void session_dmabuf(void *data, struct ext_image_copy_capture_session_v1 *session, + uint32_t format, struct wl_array *modifiers) +{ + (void)data; (void)session; (void)format; (void)modifiers; +} + +static void session_done(void *data, struct ext_image_copy_capture_session_v1 *session) +{ + (void)session; + ++((struct capture_session *)data)->done; +} + +static void session_stopped(void *data, struct ext_image_copy_capture_session_v1 *session) +{ + (void)session; + ((struct capture_session *)data)->stopped = 1; +} + +static const struct ext_image_copy_capture_session_v1_listener session_listener = { + .buffer_size = session_size, + .shm_format = session_shm, + .dmabuf_device = session_device, + .dmabuf_format = session_dmabuf, + .done = session_done, + .stopped = session_stopped, +}; + +static int session_create(struct client_connection *connection, struct capture_session *state, + struct ext_image_copy_capture_manager_v1 *manager, + struct ext_image_capture_source_v1 *source) +{ + *state = (struct capture_session){0}; + state->session = ext_image_copy_capture_manager_v1_create_session(manager, source, 0); + ext_image_copy_capture_session_v1_add_listener(state->session, &session_listener, state); + CHECK(wl_display_roundtrip(connection->display) >= 0 && state->done && !state->stopped + && state->has_shm && state->format == WL_SHM_FORMAT_ARGB8888, + "capture: missing initial ARGB constraints\n"); + return 0; +} + +struct frame_state { + int ready, failed, has_transform, has_time, has_damage; + uint32_t reason, transform, nsec; +}; + +static void frame_transform(void *data, struct ext_image_copy_capture_frame_v1 *frame, uint32_t transform) +{ + (void)frame; + struct frame_state *state = data; + state->transform = transform; + state->has_transform = 1; +} + +static void frame_damage(void *data, struct ext_image_copy_capture_frame_v1 *frame, + int32_t x, int32_t y, int32_t width, int32_t height) +{ + (void)frame; + if (x >= 0 && y >= 0 && width > 0 && height > 0) + ((struct frame_state *)data)->has_damage = 1; +} + +static void frame_time(void *data, struct ext_image_copy_capture_frame_v1 *frame, + uint32_t hi, uint32_t lo, uint32_t nsec) +{ + (void)frame; (void)hi; (void)lo; + struct frame_state *state = data; + state->nsec = nsec; + state->has_time = 1; +} + +static void frame_ready(void *data, struct ext_image_copy_capture_frame_v1 *frame) +{ + (void)frame; + ++((struct frame_state *)data)->ready; +} + +static void frame_failed(void *data, struct ext_image_copy_capture_frame_v1 *frame, uint32_t reason) +{ + (void)frame; + struct frame_state *state = data; + ++state->failed; + state->reason = reason; +} + +static const struct ext_image_copy_capture_frame_v1_listener frame_listener = { + .transform = frame_transform, + .damage = frame_damage, + .presentation_time = frame_time, + .ready = frame_ready, + .failed = frame_failed, +}; + +static struct ext_image_copy_capture_frame_v1 *begin_capture(struct capture_session *session, + struct shm_buffer *buffer, + struct frame_state *state) +{ + *state = (struct frame_state){0}; + struct ext_image_copy_capture_frame_v1 *frame = + ext_image_copy_capture_session_v1_create_frame(session->session); + ext_image_copy_capture_frame_v1_add_listener(frame, &frame_listener, state); + ext_image_copy_capture_frame_v1_attach_buffer(frame, buffer->buffer); + ext_image_copy_capture_frame_v1_damage_buffer(frame, 0, 0, buffer->width, buffer->height); + ext_image_copy_capture_frame_v1_capture(frame); + return frame; +} + +static int finish_capture(struct client_connection *connection, struct capture_session *session, + struct ext_image_copy_capture_frame_v1 *frame, + struct frame_state *state, int expect_failure) +{ + while (!state->ready && !state->failed && !session->stopped) { + CHECK(wl_display_dispatch(connection->display) >= 0, "capture: dispatch failed\n"); + } + ext_image_copy_capture_frame_v1_destroy(frame); + if (expect_failure) { + CHECK(state->failed && state->reason == EXT_IMAGE_COPY_CAPTURE_FRAME_V1_FAILURE_REASON_BUFFER_CONSTRAINTS, + "capture: expected buffer_constraints failure, got ready=%d reason=%u\n", + state->ready, state->reason); + } else { + CHECK(state->ready && state->has_transform && state->transform == WL_OUTPUT_TRANSFORM_NORMAL + && state->has_time && state->nsec < 1000000000 && state->has_damage, + "capture: missing ready/metadata, failed=%d reason=%u\n", state->failed, state->reason); + } + return 0; +} + +static int capture(struct client_connection *connection, struct capture_session *session, + struct shm_buffer *buffer, int expect_failure) +{ + struct frame_state state; + struct ext_image_copy_capture_frame_v1 *frame = begin_capture(session, buffer, &state); + return finish_capture(connection, session, frame, &state, expect_failure); +} + +struct power_state { + uint32_t mode; + int failed; +}; + +static void power_mode(void *data, struct zwlr_output_power_v1 *power, uint32_t mode) +{ + (void)power; + ((struct power_state *)data)->mode = mode; +} + +static void power_failed(void *data, struct zwlr_output_power_v1 *power) +{ + (void)power; + ((struct power_state *)data)->failed = 1; +} + +static const struct zwlr_output_power_v1_listener power_listener = { + .mode = power_mode, + .failed = power_failed, +}; + +static void ddm_vt(void *data, struct treeland_ddm_v1 *ddm, int32_t vtnr) +{ + (void)data; (void)ddm; (void)vtnr; +} + +static const struct treeland_ddm_v1_listener ddm_listener = { + .switch_to_vt = ddm_vt, + .acquire_vt = ddm_vt, +}; + +static void render_disabled(void *data, struct wl_callback *callback, uint32_t serial) +{ + (void)serial; + ++*(int *)data; + wl_callback_destroy(callback); +} + +static const struct wl_callback_listener render_disabled_listener = { + .done = render_disabled, +}; + +static int pause_rendering(struct client_connection *connection, struct treeland_ddm_v1 *ddm) +{ + int done = 0; + struct wl_callback *callback = treeland_ddm_v1_disable_render(ddm); + wl_callback_add_listener(callback, &render_disabled_listener, &done); + CHECK(wl_display_roundtrip(connection->display) >= 0 && done == 1, + "capture: DDM did not acknowledge rendering pause\n"); + return 0; +} + +static int check_render_pause(struct client_connection *connection, struct treeland_ddm_v1 *ddm, + struct capture_session *session, struct shm_buffer *buffer, + struct toplevel_capture_output_state *outputs, int capture_before_pause) +{ + struct frame_state state = {0}; + struct ext_image_copy_capture_frame_v1 *frame = NULL; + if (capture_before_pause) + frame = begin_capture(session, buffer, &state); + CHECK(pause_rendering(connection, ddm) == 0 + && invoke_on_server_thread(toplevel_capture_read_output_state, outputs), + "capture: could not pause rendering\n"); + const int attempts = outputs->render_attempts; + if (!capture_before_pause) + frame = begin_capture(session, buffer, &state); + CHECK(wl_display_roundtrip(connection->display) >= 0 + && invoke_on_server_thread(toplevel_capture_read_output_state, outputs), + "capture: could not observe the paused request\n"); + CHECK(!state.ready && !state.failed && !session->stopped + && !outputs->render_enabled && outputs->render_attempts == attempts + && outputs->viewport_unchanged, + "capture: rendering pause completed or rendered a pending frame\n"); + treeland_ddm_v1_enable_render(ddm); + CHECK(wl_display_roundtrip(connection->display) >= 0 + && invoke_on_server_thread(toplevel_capture_read_output_state, outputs) + && wl_display_roundtrip(connection->display) >= 0, + "capture: could not observe rendering resume\n"); + if (!outputs->capture_output_enabled) { + CHECK(state.ready == 1 && !state.failed && outputs->render_attempts > attempts, + "capture: resume did not wake the disabled-output request (ready=%d failed=%d)\n", + state.ready, state.failed); + } + CHECK(finish_capture(connection, session, frame, &state, 0) == 0, + "capture: pending frame did not complete after resume\n"); + CHECK(invoke_on_server_thread(toplevel_capture_read_output_state, outputs) + && outputs->render_enabled && outputs->render_attempts > attempts && outputs->viewport_unchanged + && outputs->offscreen_viewports == 1, + "capture: rendering resume rebuilt the capture pipeline\n"); + return 0; +} + +static int pixel_is(const struct shm_buffer *buffer, int x, int y, uint32_t color, const char *name) +{ + CHECK(x >= 0 && y >= 0 && x < buffer->width && y < buffer->height, + "capture: %s point outside %dx%d\n", name, buffer->width, buffer->height); + const uint32_t actual = buffer->pixels[(size_t)y * buffer->width + x]; + CHECK(actual == color, "capture: %s at %d,%d: expected %08x, got %08x\n", name, x, y, color, actual); + return 0; +} + +static int check_pixels(const struct shm_buffer *buffer, + const struct toplevel_capture_state *state, uint32_t nested_color) +{ + // The left-extending subsurface determines x=-20. Only a visible outer + // SSD stroke adds y=-1; maximize removes it, drag-to-restore adds it back. + const int titlebar = state->titlebar_height; + const int top = state->border_visible ? 1 : 0; + CHECK(pixel_is(buffer, 20 + 100, top + titlebar + 90, main_color, "occluded main surface") == 0, + "capture: captured the desktop region instead of the window\n"); + CHECK(pixel_is(buffer, 20, top + titlebar + 40, red, "negative-position subsurface") == 0, + "capture: missing above subsurface\n"); + CHECK(pixel_is(buffer, 20 + 40, top + titlebar - 5, nested_color, "nested subsurface") == 0, + "capture: missing recursive subsurface\n"); + CHECK(pixel_is(buffer, 20 + 30, top + titlebar + 55, yellow, "above stacking order") == 0, + "capture: wrong subsurface stacking\n"); + const uint32_t below_color = state->width > 247 && state->height - titlebar > 190 + ? main_color : orange; + CHECK(pixel_is(buffer, 20 + 247, top + titlebar + 190, below_color, "below subsurface") == 0, + "capture: clipped the below subsurface\n"); + CHECK(pixel_is(buffer, 10, top + titlebar + 190, 0, "transparent gap without shadow") == 0, + "capture: captured shadow/background in the window buffer\n"); + CHECK(pixel_is(buffer, 20 + state->width - 20, top + state->height - 20, + main_color, "bottom-right content") == 0, + "capture: truncated the current window size\n"); + const uint32_t title = buffer->pixels[(size_t)(top + 10) * buffer->width + 20 + 130]; + CHECK((title >> 24) == 255 && title != main_color, "capture: SSD titlebar missing\n"); + if (state->border_visible) { + const uint32_t border = buffer->pixels[(size_t)(top + titlebar + 80) * buffer->width + 20 + state->width]; + CHECK((border >> 24) > 0 && (border >> 24) < 255, "capture: outer SSD border missing (%08x)\n", border); + } + return 0; +} + +static int check_screen(struct toplevel_capture_state *state) +{ + CHECK(invoke_on_server_thread(toplevel_capture_check_screen, state), "capture: screen read failed\n"); + CHECK(state->geometry_unchanged && state->screen_unchanged && state->render_state_unchanged + && state->capture_frames_checked > 0 && state->offscreen_viewports == state->isolated_inputs + && state->shared_delegates == state->offscreen_viewports, + "capture: real window changed (geometry=%d pixels=%d QSG=%d frames=%d isolated=%d/%d cached=%d)\n", + state->geometry_unchanged, state->screen_unchanged, state->render_state_unchanged, + state->capture_frames_checked, state->isolated_inputs, state->offscreen_viewports, + state->shared_delegates); + // Check first without repainting, then separately prove the next screen + // render also remains correct. A repaint must never repair the evidence. + CHECK(invoke_on_server_thread(toplevel_capture_repaint_screen, state) && state->screen_unchanged, + "capture: next real output frame changed\n"); + return 0; +} + +static int check_render_failure(struct client_connection *connection, struct capture_session *session, + struct capture_session *other, struct shm_buffer *buffer, + struct toplevel_capture_state *server) +{ + int held_buffers = 0; + CHECK(invoke_on_server_thread(toplevel_capture_hold_buffers, &held_buffers) && held_buffers > 0, + "capture: could not exhaust the real capture swapchain\n"); + struct capture_session *sessions[] = {session, other}; + struct frame_state states[2]; + struct ext_image_copy_capture_frame_v1 *frames[2]; + const size_t count = other ? 2 : 1; + for (size_t i = 0; i < count; ++i) + frames[i] = begin_capture(sessions[i], buffer, &states[i]); + CHECK(wl_display_roundtrip(connection->display) >= 0, + "capture: render-failure requests were not processed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_render_offscreen, server) + && wl_display_roundtrip(connection->display) >= 0, + "capture: render-failure attempt did not finish\n"); + for (size_t i = 0; i < count; ++i) { + CHECK(states[i].failed == 1 && !states[i].ready && !sessions[i]->stopped + && !states[i].has_transform && !states[i].has_time && !states[i].has_damage + && states[i].reason == EXT_IMAGE_COPY_CAPTURE_FRAME_V1_FAILURE_REASON_UNKNOWN, + "capture: render failure left session %zu pending (failed=%d ready=%d stopped=%d reason=%u)\n", + i, states[i].failed, states[i].ready, sessions[i]->stopped, states[i].reason); + ext_image_copy_capture_frame_v1_destroy(frames[i]); + } + int viewport_survived = 0; + CHECK(invoke_on_server_thread(toplevel_capture_release_buffers, &viewport_survived) + && viewport_survived && server->offscreen_viewports == 1, + "capture: render failure destroyed the shared capture viewport\n"); + for (size_t i = 0; i < count; ++i) { + CHECK(capture(connection, sessions[i], buffer, 0) == 0, + "capture: session %zu could not recover from render failure\n", i); + } + return 0; +} + +static int commit_configured_buffer(struct client_connection *connection, struct xdg_toplevel_client *target, + struct shm_buffer *buffer) +{ + xdg_surface_ack_configure(target->xdg_surface, target->configure_serial); + target->acknowledged_configure_serial = target->configure_serial; + xdg_surface_set_window_geometry(target->xdg_surface, 0, 0, buffer->width, buffer->height); + attach(target->surface, buffer); + CHECK(wl_display_roundtrip(connection->display) >= 0, "capture: configured buffer commit failed\n"); + return 0; +} + +static int resize_destination(struct wl_shm *shm, const struct capture_session *session, struct shm_buffer *buffer) +{ + buffer_destroy(buffer); + CHECK(buffer_create(shm, buffer, session->width, session->height, session->format, 0xabcdef01), + "capture: destination allocation failed\n"); + return 0; +} + +static void save_capture(const struct shm_buffer *buffer) +{ + const char *path = getenv("TREELAND_CAPTURE_TEST_IMAGE"); + if (!path) + return; + FILE *file = fopen(path, "wb"); + if (!file) + return; + fprintf(file, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n", + buffer->width, buffer->height); + for (size_t i = 0; i < (size_t)buffer->width * buffer->height; ++i) { + const uint32_t pixel = buffer->pixels[i]; + const unsigned char rgba[] = { pixel >> 16, pixel >> 8, pixel, pixel >> 24 }; + fwrite(rgba, 1, sizeof(rgba), file); + } + fclose(file); +} + +static int same_pixels(const struct shm_buffer *buffer, const uint32_t *reference) +{ + for (size_t i = 0; i < buffer->size / sizeof(uint32_t); ++i) { + if (buffer->pixels[i] != reference[i]) { + TEST_ERROR("capture: image differs at %zu,%zu: %08x -> %08x\n", + i % buffer->width, i / buffer->width, reference[i], buffer->pixels[i]); + save_capture(buffer); + return 0; + } + } + return 1; +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + CHECK(client_connect(&connection, socket_name), "capture: connect failed\n"); + struct ext_image_copy_capture_manager_v1 *manager = client_bind(&connection, + ext_image_copy_capture_manager_v1_interface.name, &ext_image_copy_capture_manager_v1_interface, 1); + struct ext_foreign_toplevel_image_capture_source_manager_v1 *source_manager = client_bind(&connection, + ext_foreign_toplevel_image_capture_source_manager_v1_interface.name, + &ext_foreign_toplevel_image_capture_source_manager_v1_interface, 1); + struct ext_foreign_toplevel_list_v1 *list = client_bind(&connection, + ext_foreign_toplevel_list_v1_interface.name, &ext_foreign_toplevel_list_v1_interface, 1); + struct zxdg_decoration_manager_v1 *decoration_manager = client_bind(&connection, + zxdg_decoration_manager_v1_interface.name, &zxdg_decoration_manager_v1_interface, 1); + struct wl_subcompositor *subcompositor = client_bind(&connection, "wl_subcompositor", &wl_subcompositor_interface, 1); + CHECK(manager && source_manager && list && decoration_manager && subcompositor, "capture: missing globals\n"); + struct foreign_state foreign = {0}; + ext_foreign_toplevel_list_v1_add_listener(list, &list_listener, &foreign); + + // Case: a real SSD toplevel with above, below and nested wl_subsurfaces. + struct xdg_toplevel_client target, occluder; + CHECK(xdg_toplevel_client_create_pending(&connection, &target), "capture: create target failed\n"); + xdg_toplevel_set_app_id(target.toplevel, "capture-target"); + xdg_toplevel_set_title(target.toplevel, "Capture target"); + uint32_t decoration_mode = 0; + struct zxdg_toplevel_decoration_v1 *decoration = + zxdg_decoration_manager_v1_get_toplevel_decoration(decoration_manager, target.toplevel); + zxdg_toplevel_decoration_v1_add_listener(decoration, &decoration_listener, &decoration_mode); + zxdg_toplevel_decoration_v1_set_mode(decoration, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE); + CHECK(wl_display_roundtrip(connection.display) >= 0 && target.configured, "capture: no xdg configure\n"); + CHECK(xdg_toplevel_client_ack_latest_configure(&connection, &target), "capture: ack configure failed\n"); + struct shm_buffer main_buffer = {0}, sub_buffers[4] = {{0}}; + CHECK(buffer_create(target.shm, &main_buffer, MAIN_WIDTH, MAIN_HEIGHT, WL_SHM_FORMAT_ARGB8888, main_color), + "capture: main buffer failed\n"); + struct wl_surface *sub_surfaces[4]; + struct wl_subsurface *subs[4]; + const int sub_widths[] = {70, 50, 30, 50}; + const int sub_heights[] = {60, 25, 30, 40}; + const int sub_x[] = {-20, 45, 20, 205}; + const int sub_y[] = {30, -45, 45, 165}; + const uint32_t colors[] = {red, green, yellow, orange}; + for (int i = 0; i < 4; ++i) { + sub_surfaces[i] = wl_compositor_create_surface(target.compositor); + subs[i] = wl_subcompositor_get_subsurface(subcompositor, sub_surfaces[i], + i == 1 ? sub_surfaces[0] : target.surface); + wl_subsurface_set_desync(subs[i]); + wl_subsurface_set_position(subs[i], sub_x[i], sub_y[i]); + if (i == 3) + wl_subsurface_place_below(subs[i], target.surface); + CHECK(buffer_create(target.shm, &sub_buffers[i], sub_widths[i], sub_heights[i], + WL_SHM_FORMAT_ARGB8888, colors[i]), "capture: subsurface buffer failed\n"); + attach(sub_surfaces[i], &sub_buffers[i]); + } + wl_surface_commit(sub_surfaces[0]); // Commit the nested subsurface position. + xdg_surface_set_window_geometry(target.xdg_surface, 0, 0, MAIN_WIDTH, MAIN_HEIGHT); + attach(target.surface, &main_buffer); + CHECK(wl_display_roundtrip(connection.display) >= 0, "capture: map target failed\n"); + CHECK(xdg_toplevel_client_create_with_solid_buffer(&connection, &occluder, 120, 100, 0xffff00ff), + "capture: create occluder failed\n"); + xdg_toplevel_set_app_id(occluder.toplevel, "capture-occluder"); + CHECK(wl_display_roundtrip(connection.display) >= 0 && foreign.target && foreign.target_done, + "capture: no production foreign-toplevel handle\n"); + struct toplevel_capture_state server; + CHECK(invoke_on_server_thread(toplevel_capture_prepare, &server), "capture: prepare fixture failed\n"); + CHECK(server.valid && server.titlebar_height > 0 && server.occluder_visible, + "capture: target/SSD/occlusion fixture invalid (valid=%d title=%d occlusion=%d)\n", + server.valid, server.titlebar_height, server.occluder_visible); + + // Control: the partly-offscreen scene must be stable without any capture + // source or session, before testing whether capture can alter it. + CHECK(invoke_on_server_thread(toplevel_capture_move_partly_offscreen, &server), + "capture: control move failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_repaint_screen, &server) + && server.geometry_unchanged && server.screen_unchanged && server.offscreen_viewports == 0, + "capture: partly-offscreen control changed without capture (geometry=%d pixels=%d)\n", + server.geometry_unchanged, server.screen_unchanged); + const int positions[][2] = {{420, 300}, {-60, -20}, {620, 410}, {100, 90}}; + for (size_t i = 0; i < sizeof(positions) / sizeof(positions[0]); ++i) { + struct toplevel_capture_move move = {.x = positions[i][0], .y = positions[i][1]}; + CHECK(invoke_on_server_thread(toplevel_capture_move_window, &move), "capture: control move failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_repaint_screen, &server) + && server.screen_unchanged && server.geometry_unchanged && server.offscreen_viewports == 0, + "capture: move control changed without capture at %d,%d\n", move.x, move.y); + } + CHECK(invoke_on_server_thread(toplevel_capture_prepare, &server), + "capture: restore fixture failed\n"); + + struct ext_image_capture_source_v1 *source = + ext_foreign_toplevel_image_capture_source_manager_v1_create_source(source_manager, foreign.target); + struct capture_session session; + CHECK(session_create(&connection, &session, manager, source) == 0, "capture: session failed\n"); + CHECK(session.width == 275 && session.height == (uint32_t)(server.titlebar_height + 206), + "capture: wrong window bounds %ux%u (title=%d)\n", session.width, session.height, server.titlebar_height); + struct shm_buffer captured = {0}; + CHECK(buffer_create(target.shm, &captured, session.width, session.height, session.format, 0xabcdef01), + "capture: destination buffer failed\n"); + CHECK(capture(&connection, &session, &captured, 0) == 0, "capture: initial frame failed\n"); + save_capture(&captured); + CHECK(check_pixels(&captured, &server, green) == 0, "capture: initial pixels wrong\n"); + + // Case: capture creation/rendering does not move/hide/transform the window + // or change its actual output pixels, including the occluding other window. + CHECK(check_screen(&server) == 0 && server.offscreen_viewports == 1, + "capture: screen changed after initial capture\n"); + // Case: translucent outer SSD pixels cannot accumulate on repeated frames, + // including the top-left stroke outside the negative sourceRect origin. + uint32_t *reference = malloc(captured.size); + CHECK(reference, "capture: repeated-frame reference allocation failed\n"); + memcpy(reference, captured.pixels, captured.size); + for (int i = 0; i < 3; ++i) { + CHECK(capture(&connection, &session, &captured, 0) == 0 && same_pixels(&captured, reference), + "capture: repeated frame accumulated translucent SSD pixels\n"); + CHECK(check_screen(&server) == 0, "capture: repeated frame changed actual output\n"); + } + free(reference); + // Case: a compositor render between two capture requests (for example an + // animated titlebar) must not leave the next request waiting for a frame. + CHECK(capture(&connection, &session, &captured, 0) == 0, "capture: frame before extra render failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_render_offscreen, &server), "capture: extra render failed\n"); + CHECK(capture(&connection, &session, &captured, 0) == 0, "capture: frame after extra render stalled\n"); + CHECK(invoke_on_server_thread(toplevel_capture_render_offscreen, &server), "capture: offscreen render failed\n"); + CHECK(server.capture_only_did_not_commit && server.geometry_unchanged && server.screen_unchanged + && server.render_state_unchanged, + "capture: offscreen viewport committed to or altered the real output\n"); + + // Case: only a desynchronized nested subsurface changes; root does not commit. + struct shm_buffer nested_update = {0}; + CHECK(buffer_create(target.shm, &nested_update, 50, 25, WL_SHM_FORMAT_ARGB8888, teal), + "capture: nested update failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_pause_checks, NULL), "capture: pause screen comparison failed\n"); + attach(sub_surfaces[1], &nested_update); + CHECK(capture(&connection, &session, &captured, 0) == 0, "capture: subsurface-only frame failed\n"); + CHECK(check_pixels(&captured, &server, teal) == 0, "capture: subsurface-only update missing\n"); + + reference = malloc(captured.size); + CHECK(reference, "capture: reference allocation failed\n"); + memcpy(reference, captured.pixels, captured.size); + + // Case: moving partly outside the output neither clips nor changes capture coordinates. + CHECK(invoke_on_server_thread(toplevel_capture_move_partly_offscreen, &server), "capture: fixture move failed\n"); + CHECK(capture(&connection, &session, &captured, 0) == 0, "capture: moved frame failed\n"); + CHECK(check_pixels(&captured, &server, teal) == 0 && same_pixels(&captured, reference), + "capture: move changed isolated image or SSD local coordinates\n"); + CHECK(check_screen(&server) == 0, "capture: partly-offscreen screen changed\n"); + + // Case: compare every pixel, including SSD, across repeated live moves. + for (size_t i = 0; i < sizeof(positions) / sizeof(positions[0]); ++i) { + struct toplevel_capture_move move = {.x = positions[i][0], .y = positions[i][1]}; + CHECK(invoke_on_server_thread(toplevel_capture_move_window, &move), "capture: move fixture failed\n"); + server = move.state; + CHECK(server.position_x == move.x && server.position_y == move.y, + "capture: target did not move to %d,%d\n", move.x, move.y); + CHECK(capture(&connection, &session, &captured, 0) == 0, "capture: moving frame failed\n"); + CHECK(same_pixels(&captured, reference), + "capture: window/SSD drifted after move to %d,%d\n", move.x, move.y); + CHECK(check_screen(&server) == 0, "capture: live move damaged actual output\n"); + } + free(reference); + + // Case: independent sessions share the source; stopping one must not freeze the other. + struct capture_session other; + CHECK(session_create(&connection, &other, manager, source) == 0, "capture: second session failed\n"); + CHECK(capture(&connection, &other, &captured, 0) == 0, "capture: second session initial frame failed\n"); + // Case: a real swapchain acquire failure ends every pending frame, not the sessions. + CHECK(check_render_failure(&connection, &session, &other, &captured, &server) == 0 + && check_pixels(&captured, &server, teal) == 0 && check_screen(&server) == 0, + "capture: shared sessions did not recover from render failure\n"); + ext_image_copy_capture_session_v1_destroy(session.session); + CHECK(wl_display_roundtrip(connection.display) >= 0, "capture: destroy first session failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_pause_checks, NULL), "capture: pause screen comparison failed\n"); + attach(sub_surfaces[1], &sub_buffers[1]); + CHECK(capture(&connection, &other, &captured, 0) == 0, "capture: stopping first session froze source\n"); + CHECK(check_pixels(&captured, &server, green) == 0, "capture: shared source update missing\n"); + + // Case: resize re-advertises constraints; an old client buffer gets one + // buffer_constraints failure and a newly sized buffer succeeds afterwards. + struct shm_buffer resized = {0}; + CHECK(buffer_create(target.shm, &resized, 320, 260, WL_SHM_FORMAT_ARGB8888, main_color), + "capture: resized source buffer failed\n"); + xdg_surface_set_window_geometry(target.xdg_surface, 0, 0, 320, 260); + attach(target.surface, &resized); + CHECK(wl_display_roundtrip(connection.display) >= 0, "capture: resize commit failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_save_screen, &server), "capture: save resized screen failed\n"); + CHECK(wl_display_roundtrip(connection.display) >= 0 && other.width == 341 + && other.height == (uint32_t)(server.titlebar_height + 262), + "capture: resized constraints incorrect %ux%u\n", other.width, other.height); + CHECK(capture(&connection, &other, &captured, 1) == 0, "capture: resize failure reason wrong\n"); + buffer_destroy(&captured); + CHECK(buffer_create(target.shm, &captured, other.width, other.height, other.format, 0xabcdef01), + "capture: resized capture buffer failed\n"); + CHECK(capture(&connection, &other, &captured, 0) == 0, "capture: resized frame failed\n"); + CHECK(pixel_is(&captured, 20 + 310, 1 + server.titlebar_height + 250, main_color, "resized main surface") == 0, + "capture: resized viewport did not render the whole new window\n"); + CHECK(check_pixels(&captured, &server, green) == 0 && check_screen(&server) == 0, + "capture: resize capture changed actual window geometry/pixels\n"); + + // Case: a client-requested maximize (with production animation) followed + // by real SSD dragging. Capture before and after the client's restore + // buffer arrives, then throughout the still-active move transaction. + reference = malloc(captured.size); + const size_t restored_capture_size = captured.size; + CHECK(reference, "capture: restore reference allocation failed\n"); + memcpy(reference, captured.pixels, captured.size); + CHECK(invoke_on_server_thread(toplevel_capture_pause_checks, NULL), "capture: pause maximize checks failed\n"); + xdg_toplevel_set_maximized(target.toplevel); + CHECK(wl_display_roundtrip(connection.display) >= 0, "capture: maximize request failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_wait_transition, &server), "capture: maximize transition failed\n"); + CHECK(wl_display_roundtrip(connection.display) >= 0 && target.configure_maximized + && target.configure_width == 800 && target.configure_height == 600 - server.titlebar_height, + "capture: maximize configure wrong (%dx%d state=%d)\n", + target.configure_width, target.configure_height, target.configure_maximized); + struct shm_buffer maximized = {0}; + CHECK(buffer_create(target.shm, &maximized, target.configure_width, target.configure_height, + WL_SHM_FORMAT_ARGB8888, main_color), "capture: maximized buffer failed\n"); + CHECK(commit_configured_buffer(&connection, &target, &maximized) == 0, "capture: maximize commit failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_save_screen, &server), "capture: maximize screen failed\n"); + CHECK(wl_display_roundtrip(connection.display) >= 0 && server.maximized && !server.border_visible + && other.width == 820 && other.height == 600, + "capture: maximize bounds wrong (%ux%u state=%d border=%d)\n", + other.width, other.height, server.maximized, server.border_visible); + CHECK(resize_destination(target.shm, &other, &captured) == 0, "capture: maximize destination failed\n"); + CHECK(capture(&connection, &other, &captured, 0) == 0 && check_pixels(&captured, &server, green) == 0, + "capture: maximized image incomplete\n"); + CHECK(check_screen(&server) == 0, "capture: maximized capture changed screen\n"); + + CHECK(invoke_on_server_thread(toplevel_capture_drag_begin, &server), "capture: SSD drag failed\n"); + CHECK(wl_display_roundtrip(connection.display) >= 0 && !server.maximized && server.dragging + && !target.configure_maximized && target.configure_width == 320 && target.configure_height == 260, + "capture: SSD drag did not restore through production move path (max=%d drag=%d configure=%dx%d/%d)\n", + server.maximized, server.dragging, target.configure_width, target.configure_height, target.configure_maximized); + CHECK(invoke_on_server_thread(toplevel_capture_save_screen, &server), "capture: pending restore screen failed\n"); + CHECK(wl_display_roundtrip(connection.display) >= 0 && server.border_visible + && other.width == 821 && other.height == 602, + "capture: pending restore bounds clipped old committed content (%ux%u)\n", other.width, other.height); + CHECK(resize_destination(target.shm, &other, &captured) == 0, "capture: pending restore destination failed\n"); + CHECK(capture(&connection, &other, &captured, 0) == 0 && check_pixels(&captured, &server, green) == 0, + "capture: drag restore clipped content before client resize\n"); + CHECK(check_screen(&server) == 0, "capture: pending restore capture changed screen\n"); + + CHECK(commit_configured_buffer(&connection, &target, &resized) == 0, "capture: restore buffer commit failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_save_screen, &server), "capture: restored screen failed\n"); + CHECK(wl_display_roundtrip(connection.display) >= 0 && other.width == 341 + && other.height == (uint32_t)(server.titlebar_height + 262), + "capture: restore constraints retained maximized geometry (%ux%u)\n", other.width, other.height); + CHECK(resize_destination(target.shm, &other, &captured) == 0, "capture: restore destination failed\n"); + CHECK(capture(&connection, &other, &captured, 0) == 0 && captured.size == restored_capture_size + && same_pixels(&captured, reference), + "capture: restored window or SSD is offset/truncated\n"); + CHECK(check_screen(&server) == 0, "capture: restored capture changed screen\n"); + + const int drag_positions[][2] = {{430, 140}, {700, 410}, {130, 65}}; + for (size_t i = 0; i < sizeof(drag_positions) / sizeof(drag_positions[0]); ++i) { + struct toplevel_capture_move move = {.x = drag_positions[i][0], .y = drag_positions[i][1]}; + CHECK(invoke_on_server_thread(toplevel_capture_drag_move, &move) && move.state.dragging, + "capture: interactive move ended prematurely\n"); + CHECK(move.state.position_x != server.position_x || move.state.position_y != server.position_y, + "capture: pointer motion did not move the restored window\n"); + server = move.state; + CHECK(capture(&connection, &other, &captured, 0) == 0 + && same_pixels(&captured, reference), + "capture: restored window/SSD drifted while dragging to %d,%d\n", move.x, move.y); + CHECK(check_screen(&server) == 0, "capture: dragging capture damaged actual output\n"); + } + CHECK(invoke_on_server_thread(toplevel_capture_drag_end, &server) && !server.dragging, + "capture: pointer release did not end drag\n"); + CHECK(capture(&connection, &other, &captured, 0) == 0 + && same_pixels(&captured, reference) && check_screen(&server) == 0, + "capture: released restore image changed\n"); + free(reference); + + // Case: the capture pipeline belongs to the requesting client, not to the + // toplevel. Accepting a source must not allocate one, and the last session + // plus the client's source resource must release it again. + ext_image_copy_capture_session_v1_destroy(other.session); + ext_image_capture_source_v1_destroy(source); + CHECK(wl_display_roundtrip(connection.display) >= 0, "capture: source cleanup failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_check_screen, &server) + && server.offscreen_viewports == 0, + "capture: destroyed client kept its pipeline (%d viewports)\n", server.offscreen_viewports); + CHECK(check_screen(&server) == 0, "capture: released pipeline changed the output\n"); + + for (int i = 0; i < 3; ++i) { + struct ext_image_capture_source_v1 *transient = + ext_foreign_toplevel_image_capture_source_manager_v1_create_source(source_manager, foreign.target); + CHECK(transient, "capture: transient source failed\n"); + CHECK(wl_display_roundtrip(connection.display) >= 0, "capture: transient roundtrip failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_check_screen, &server) + && server.offscreen_viewports == 0, + "capture: accepted source allocated an idle pipeline (%d viewports)\n", + server.offscreen_viewports); + + struct capture_session transient_session; + CHECK(session_create(&connection, &transient_session, manager, transient) == 0, + "capture: transient session failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_check_screen, &server) + && server.offscreen_viewports == 1, + "capture: session did not create exactly one pipeline (%d viewports)\n", + server.offscreen_viewports); + CHECK(resize_destination(target.shm, &transient_session, &captured) == 0, + "capture: transient destination failed\n"); + CHECK(capture(&connection, &transient_session, &captured, 0) == 0 + && check_pixels(&captured, &server, green) == 0, + "capture: transient frame incomplete\n"); + + if (i == 1) { + // A session keeps working after the client dropped the source + // resource; only the session still owns the pipeline. + ext_image_capture_source_v1_destroy(transient); + transient = NULL; + CHECK(wl_display_roundtrip(connection.display) >= 0, "capture: source drop failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_check_screen, &server) + && server.offscreen_viewports == 1, + "capture: dropping the source resource released the live session (%d viewports)\n", + server.offscreen_viewports); + CHECK(capture(&connection, &transient_session, &captured, 0) == 0 + && check_pixels(&captured, &server, green) == 0, + "capture: frame failed after source resource drop\n"); + } + + ext_image_copy_capture_session_v1_destroy(transient_session.session); + if (transient) + ext_image_capture_source_v1_destroy(transient); + CHECK(wl_display_roundtrip(connection.display) >= 0, "capture: transient cleanup failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_check_screen, &server) + && server.offscreen_viewports == 0, + "capture: recycled pipeline still present after request %d (%d viewports)\n", + i, server.offscreen_viewports); + CHECK(check_screen(&server) == 0, "capture: recycling changed the output\n"); + } + + source = ext_foreign_toplevel_image_capture_source_manager_v1_create_source(source_manager, foreign.target); + CHECK(session_create(&connection, &session, manager, source) == 0, "capture: session recreate failed\n"); + CHECK(resize_destination(target.shm, &session, &captured) == 0, "capture: destination recreate failed\n"); + CHECK(capture(&connection, &session, &captured, 0) == 0, "capture: frame after recycle failed\n"); + + // Case: a pending request survives its original output being powered off + // after the real window has moved to another enabled output. + struct wl_output *original_output = client_bind(&connection, "wl_output", &wl_output_interface, 1); + struct zwlr_output_power_manager_v1 *power_manager = client_bind(&connection, + zwlr_output_power_manager_v1_interface.name, &zwlr_output_power_manager_v1_interface, 1); + CHECK(original_output && power_manager, "capture: output power globals missing\n"); + struct zwlr_output_power_v1 *power = + zwlr_output_power_manager_v1_get_output_power(power_manager, original_output); + struct power_state power_state = {.mode = ZWLR_OUTPUT_POWER_V1_MODE_OFF}; + zwlr_output_power_v1_add_listener(power, &power_listener, &power_state); + CHECK(wl_display_roundtrip(connection.display) >= 0 && !power_state.failed + && power_state.mode == ZWLR_OUTPUT_POWER_V1_MODE_ON, + "capture: original output power control failed\n"); + struct toplevel_capture_output_state outputs; + CHECK(invoke_on_server_thread(toplevel_capture_add_output, &outputs) + && outputs.output_count == 2 && outputs.enabled_outputs == 2 + && outputs.target_on_other_output && outputs.viewport_unchanged, + "capture: window did not move independently of its capture output\n"); + struct treeland_ddm_v1 *ddm = client_bind(&connection, treeland_ddm_v1_interface.name, + &treeland_ddm_v1_interface, 1); + CHECK(ddm, "capture: DDM global missing\n"); + treeland_ddm_v1_add_listener(ddm, &ddm_listener, NULL); + // Case: resume wakes a single request without new captures or fixture renders. + CHECK(check_render_pause(&connection, ddm, &session, &captured, &outputs, 0) == 0 + && check_pixels(&captured, &server, green) == 0, + "capture: enabled-output pause/resume failed\n"); + struct frame_state pending; + struct ext_image_copy_capture_frame_v1 *pending_frame = begin_capture(&session, &captured, &pending); + zwlr_output_power_v1_set_mode(power, ZWLR_OUTPUT_POWER_V1_MODE_OFF); + CHECK(finish_capture(&connection, &session, pending_frame, &pending, 0) == 0 + && power_state.mode == ZWLR_OUTPUT_POWER_V1_MODE_OFF && !power_state.failed, + "capture: request issued before output disable stalled\n"); + CHECK(invoke_on_server_thread(toplevel_capture_read_output_state, &outputs) + && !outputs.capture_output_enabled && outputs.enabled_outputs == 1 + && outputs.target_on_other_output && outputs.viewport_unchanged + && outputs.disabled_frames > 0 && outputs.disabled_frames_did_not_commit, + "capture: disabled-output fallback recreated the pipeline or committed an output\n"); + + // Case: later requests still copy new committed content, not the last frame + // rendered before the old output stopped producing frame events. + attach(sub_surfaces[1], &nested_update); + CHECK(capture(&connection, &session, &captured, 0) == 0 + && check_pixels(&captured, &server, teal) == 0, + "capture: new pixels missing after output disable\n"); + CHECK(invoke_on_server_thread(toplevel_capture_read_output_state, &outputs) + && outputs.disabled_frames >= 2 && outputs.disabled_frames_did_not_commit + && outputs.viewport_unchanged && outputs.offscreen_viewports == 1, + "capture: repeated fallback changed the output or leaked a pipeline\n"); + CHECK(check_render_pause(&connection, ddm, &session, &captured, &outputs, 0) == 0 + && check_pixels(&captured, &server, teal) == 0 + && outputs.disabled_frames_did_not_commit, + "capture: disabled-output pause/resume failed\n"); + // The fallback is queued before disable_render in the same request batch. + CHECK(check_render_pause(&connection, ddm, &session, &captured, &outputs, 1) == 0 + && check_pixels(&captured, &server, teal) == 0 && outputs.disabled_frames_did_not_commit, + "capture: queued fallback did not survive rendering pause\n"); + // Case: render failure and recovery also work without an enabled capture output. + CHECK(check_render_failure(&connection, &session, NULL, &captured, &server) == 0 + && check_pixels(&captured, &server, teal) == 0, + "capture: disabled-output session did not recover from render failure\n"); + CHECK(invoke_on_server_thread(toplevel_capture_read_output_state, &outputs) + && !outputs.capture_output_enabled && outputs.disabled_frames_did_not_commit + && outputs.viewport_unchanged && outputs.offscreen_viewports == 1, + "capture: failed fallback changed the output or capture pipeline\n"); + zwlr_output_power_v1_set_mode(power, ZWLR_OUTPUT_POWER_V1_MODE_ON); + CHECK(wl_display_roundtrip(connection.display) >= 0 + && power_state.mode == ZWLR_OUTPUT_POWER_V1_MODE_ON && !power_state.failed + && capture(&connection, &session, &captured, 0) == 0, + "capture: regular scheduling did not resume after output enable\n"); + + // Case: a queued fallback must not render a viewport that stop() released. + zwlr_output_power_v1_set_mode(power, ZWLR_OUTPUT_POWER_V1_MODE_OFF); + CHECK(wl_display_roundtrip(connection.display) >= 0 + && invoke_on_server_thread(toplevel_capture_read_output_state, &outputs) + && !outputs.capture_output_enabled, "capture: second output disable failed\n"); + const int disabled_frames = outputs.disabled_frames; + pending_frame = begin_capture(&session, &captured, &pending); + ext_image_copy_capture_frame_v1_destroy(pending_frame); + ext_image_copy_capture_session_v1_destroy(session.session); + ext_image_capture_source_v1_destroy(source); + CHECK(wl_display_roundtrip(connection.display) >= 0 + && invoke_on_server_thread(toplevel_capture_read_output_state, &outputs) + && outputs.offscreen_viewports == 0 && outputs.disabled_frames == disabled_frames, + "capture: stopped session retained or rendered its queued fallback\n"); + + // Case: a new session resolves the window's current, enabled output while + // the previous session's output remains disabled. + source = ext_foreign_toplevel_image_capture_source_manager_v1_create_source(source_manager, foreign.target); + CHECK(session_create(&connection, &session, manager, source) == 0, + "capture: new session after output disable failed\n"); + CHECK(capture(&connection, &session, &captured, 0) == 0 + && check_pixels(&captured, &server, teal) == 0, + "capture: first frame after output disable failed\n"); + CHECK(invoke_on_server_thread(toplevel_capture_read_output_state, &outputs) + && !outputs.capture_output_enabled && outputs.target_on_other_output + && outputs.offscreen_viewports == 1 && outputs.enabled_capture_viewports == 1 + && outputs.disabled_frames == disabled_frames, + "capture: new session reused the disabled output\n"); + + // Case: cancelling a paused request releases its viewport before rendering resumes. + CHECK(pause_rendering(&connection, ddm) == 0 + && invoke_on_server_thread(toplevel_capture_read_output_state, &outputs), + "capture: cancellation pause failed\n"); + const int cancelled_attempts = outputs.render_attempts; + pending_frame = begin_capture(&session, &captured, &pending); + ext_image_copy_capture_frame_v1_destroy(pending_frame); + ext_image_copy_capture_session_v1_destroy(session.session); + ext_image_capture_source_v1_destroy(source); + CHECK(wl_display_roundtrip(connection.display) >= 0 + && invoke_on_server_thread(toplevel_capture_read_output_state, &outputs) + && outputs.offscreen_viewports == 0 && outputs.render_attempts == cancelled_attempts, + "capture: paused cancellation retained or rendered its viewport\n"); + treeland_ddm_v1_enable_render(ddm); + CHECK(wl_display_roundtrip(connection.display) >= 0 + && invoke_on_server_thread(toplevel_capture_read_output_state, &outputs) + && outputs.render_attempts == cancelled_attempts && outputs.offscreen_viewports == 0, + "capture: resume rendered a cancelled capture viewport\n"); + + zwlr_output_power_v1_set_mode(power, ZWLR_OUTPUT_POWER_V1_MODE_ON); + CHECK(wl_display_roundtrip(connection.display) >= 0 + && power_state.mode == ZWLR_OUTPUT_POWER_V1_MODE_ON && !power_state.failed, + "capture: output restore failed\n"); + zwlr_output_power_v1_destroy(power); + zwlr_output_power_manager_v1_destroy(power_manager); + wl_output_destroy(original_output); + + source = ext_foreign_toplevel_image_capture_source_manager_v1_create_source(source_manager, foreign.target); + CHECK(session_create(&connection, &session, manager, source) == 0, + "capture: session after output disable cleanup failed\n"); + CHECK(capture(&connection, &session, &captured, 0) == 0, + "capture: frame after output disable cleanup failed\n"); + + // Case: stop/restart and then destroy the toplevel while capture remains active. + CHECK(pause_rendering(&connection, ddm) == 0, "capture: destruction pause failed\n"); + pending_frame = begin_capture(&session, &captured, &pending); + CHECK(wl_display_roundtrip(connection.display) >= 0 && !pending.ready && !pending.failed, + "capture: destruction request did not remain paused\n"); + CHECK(invoke_on_server_thread(toplevel_capture_pause_checks, NULL), "capture: pause destruction checks failed\n"); + for (int i = 3; i >= 0; --i) { + wl_subsurface_destroy(subs[i]); + wl_surface_destroy(sub_surfaces[i]); + } + zxdg_toplevel_decoration_v1_destroy(decoration); + xdg_toplevel_client_destroy(&target); + CHECK(wl_display_roundtrip(connection.display) >= 0 && session.stopped + && pending.failed == 1 && !pending.ready + && pending.reason == EXT_IMAGE_COPY_CAPTURE_FRAME_V1_FAILURE_REASON_STOPPED, + "capture: destroying toplevel did not stop capture\n"); + ext_image_copy_capture_frame_v1_destroy(pending_frame); + CHECK(invoke_on_server_thread(toplevel_capture_read_output_state, &outputs), + "capture: destruction state read failed\n"); + const int destroyed_attempts = outputs.render_attempts; + treeland_ddm_v1_enable_render(ddm); + CHECK(wl_display_roundtrip(connection.display) >= 0 + && invoke_on_server_thread(toplevel_capture_read_output_state, &outputs) + && outputs.render_attempts == destroyed_attempts && outputs.offscreen_viewports == 0, + "capture: resume rendered a destroyed window\n"); + ext_image_copy_capture_session_v1_destroy(session.session); + ext_image_capture_source_v1_destroy(source); + buffer_destroy(&captured); + buffer_destroy(&main_buffer); + buffer_destroy(&resized); + buffer_destroy(&maximized); + buffer_destroy(&nested_update); + for (int i = 0; i < 4; ++i) + buffer_destroy(&sub_buffers[i]); + xdg_toplevel_client_destroy(&occluder); + ext_foreign_toplevel_list_v1_destroy(list); + ext_foreign_toplevel_image_capture_source_manager_v1_destroy(source_manager); + ext_image_copy_capture_manager_v1_destroy(manager); + zxdg_decoration_manager_v1_destroy(decoration_manager); + wl_subcompositor_destroy(subcompositor); + wl_proxy_destroy((struct wl_proxy *)ddm); + client_disconnect(&connection); + return 0; +} diff --git a/tests/protocols/wayland-ext-image-copy-capture-v1/wayland-ext-toplevel-image-capture-v1.h b/tests/protocols/wayland-ext-image-copy-capture-v1/wayland-ext-toplevel-image-capture-v1.h new file mode 100644 index 0000000000..ab6fdbdb95 --- /dev/null +++ b/tests/protocols/wayland-ext-image-copy-capture-v1/wayland-ext-toplevel-image-capture-v1.h @@ -0,0 +1,66 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +struct toplevel_capture_state { + int valid; + int titlebar_height; + int width, height; + int bounds_x, bounds_y, bounds_width, bounds_height; + int geometry_unchanged; + int screen_unchanged; + int render_state_unchanged; + int capture_frames_checked; + int offscreen_viewports; + int isolated_inputs; + int shared_delegates; + int capture_only_did_not_commit; + int occluder_visible; + int maximized; + int dragging; + int border_visible; + int position_x, position_y; +}; + +struct toplevel_capture_move { + int x, y; + struct toplevel_capture_state state; +}; + +struct toplevel_capture_output_state { + int output_count; + int enabled_outputs; + int target_on_other_output; + int capture_output_enabled; + int viewport_unchanged; + int offscreen_viewports; + int enabled_capture_viewports; + int disabled_frames; + int disabled_frames_did_not_commit; + int render_attempts; + int render_enabled; +}; + +#ifdef __cplusplus +extern "C" { +#endif +void toplevel_capture_prepare(void *data); +void toplevel_capture_check_screen(void *data); +void toplevel_capture_repaint_screen(void *data); +void toplevel_capture_render_offscreen(void *data); +void toplevel_capture_hold_buffers(void *data); +void toplevel_capture_release_buffers(void *data); +void toplevel_capture_move_partly_offscreen(void *data); +void toplevel_capture_save_screen(void *data); +void toplevel_capture_pause_checks(void *data); +void toplevel_capture_move_window(void *data); +void toplevel_capture_wait_transition(void *data); +void toplevel_capture_drag_begin(void *data); +void toplevel_capture_drag_move(void *data); +void toplevel_capture_drag_end(void *data); +void toplevel_capture_add_output(void *data); +void toplevel_capture_read_output_state(void *data); +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/wayland-ext-session-lock-v1/CMakeLists.txt b/tests/protocols/wayland-ext-session-lock-v1/CMakeLists.txt new file mode 100644 index 0000000000..cb5a2542f9 --- /dev/null +++ b/tests/protocols/wayland-ext-session-lock-v1/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_ext_session_lock_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-session-lock/ext-session-lock-v1.xml" + EXTRA_XMLS "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-layer-shell-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-ext-session-lock-v1.c" +) diff --git a/tests/protocols/wayland-ext-session-lock-v1/README.md b/tests/protocols/wayland-ext-session-lock-v1/README.md new file mode 100644 index 0000000000..59f6f9cada --- /dev/null +++ b/tests/protocols/wayland-ext-session-lock-v1/README.md @@ -0,0 +1,45 @@ +# `wayland-ext-session-lock-v1` 测试规范 + +## 范围 + +- XML / interface:`ext_session_lock_manager_v1` / `ext_session_lock_v1`(version 1), + 以及作为前置条件的 `zwlr_layer_shell_v1`(`EXTRA_XMLS`,用于制造 exclusive zone) +- 测试源码:`tests/protocols/wayland-ext-session-lock-v1/` +- Fixture:headless output fixture +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `ext_session_lock_manager_v1`(v1) | 资源创建成功 | P | +| 工作区前置条件 | top layer surface 设 `exclusive_zone=40` 并提交 buffer | 回读 `Output::validGeometry()` 高度 == 输出高度 - 40 | E | +| 锁定会话 | `lock()` + 等待 grace timer | 收到 `locked` 事件 | P | +| 真实锁定状态 | 回读真实 `WSessionLock::isLocked()` | 为 true | E | +| 锁屏 surface 配置尺寸 | 收到 `ext_session_lock_surface_v1.configure` | 配置尺寸 == 输出全尺寸(不是工作区尺寸) | P | +| 锁屏窗口几何 | lock surface 提交全尺寸 buffer 后回读生产 wrapper | wrapper 尺寸 == `Output::geometry()`、位置 == 输出原点 | E | + +## 生产结果 + +测试绑定 `ext_session_lock_manager_v1` 并调用 `lock()`。Treeland 的 +`WaylandServer::onExtSessionLock` 启动 300 ms grace timer,超时后调用 `WSessionLock::lock()`, +向客户端发送 `locked` 事件并将生产 `WSessionLock` 对象置为 Locked 状态。测试在收到 +`locked` 事件后,通过 server bridge 回读 `WSessionLockManager::lockCreated` 信号捕获的 +生产 `WSessionLock::isLocked()`,断言为 true。此断言验证锁定确实到达了真实合成器 +session-lock 对象,而非仅事件到达无协议错误。 + +此 fixture 中预期合成器在 grace timer 后接受锁定;若收到 `finished`,说明合成器拒绝了 +锁定请求,测试失败。这样可防止无条件拒绝 session lock 的回归被误判为 P 级通过。 + +锁屏 surface 的几何由同一客户端覆盖:先创建一条 `exclusive_zone=40` 的 top layer surface +(面板/dock 的等价物),断言工作区确实比输出小 —— 没有 exclusive zone 的环境里,后面的 +尺寸断言会平凡通过与假通过。随后 `get_lock_surface` → ack configure → 提交输出全尺寸 buffer, +再从 server bridge 回读 `LockScreenContainer` 中的生产 `SurfaceWrapper`,断言其尺寸等于 +`Output::geometry()`(不是 `validGeometry()`)、位置等于输出原点。这条断言是 +`Output::arrangeNonLayerSurface()` 缩窗回归的红/绿判据:未修复时合成器会把锁屏 surface +配置成工作区尺寸(例如 1280x680 而非 1280x720)。 + +## 已知边界 / 下一项结果 + +未覆盖:多输出锁屏(每个输出一个 lock surface)、`abandoned`(锁屏客户端崩溃回退到 +greeter)、unlock 后 `isLocked()` 翻回 false 的回读,以及 V 级像素读回。 diff --git a/tests/protocols/wayland-ext-session-lock-v1/setup.cpp b/tests/protocols/wayland-ext-session-lock-v1/setup.cpp new file mode 100644 index 0000000000..b50701da8e --- /dev/null +++ b/tests/protocols/wayland-ext-session-lock-v1/setup.cpp @@ -0,0 +1,122 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-ext-session-lock-v1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "core/rootsurfacecontainer.h" +#include "core/shellhandler.h" +#include "output/output.h" +#include "surface/surfacecontainer.h" +#include "surface/surfacewrapper.h" + +#include +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +// The WSessionLockManager resolved from the server interface list. +WSessionLockManager *g_manager = nullptr; +// The WSessionLock captured from the manager's lockCreated signal. +WSessionLock *g_lock = nullptr; +// The client's exclusive-zone panel (top layer surface). +SurfaceWrapper *g_panelWrapper = nullptr; + +// Session lock surfaces are created by the LockScreen container itself, not by +// ShellHandler, so the wrapper is looked up through that container. +SurfaceWrapper *lockWrapper() +{ + auto *root = WaylandServer::instance()->rootSurfaceContainer(); + auto *lockScreen = root->findChild(QStringLiteral("LockScreenContainer")); + if (!lockScreen) + return nullptr; + for (auto *surface : lockScreen->surfaces()) { + if (surface->type() == SurfaceWrapper::Type::LockScreen) + return surface; + } + return nullptr; +} + +// The output the client put its surfaces on: the lock surface's output once it +// exists, otherwise the panel's. Both come from the same wl_output. +Output *testOutput() +{ + if (auto *wrapper = lockWrapper(); wrapper && wrapper->ownsOutput()) + return wrapper->ownsOutput(); + if (g_panelWrapper && g_panelWrapper->ownsOutput()) + return g_panelWrapper->ownsOutput(); + return nullptr; +} +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + g_manager = find_server_interface(server); + if (g_manager) { + QObject::connect(g_manager, &WSessionLockManager::lockCreated, + server, [](WSessionLock *lock) { + g_lock = lock; + }); + } + + // Same capture pattern as the wlr-layer-shell test: keep the wrapper the + // production path created for the client's panel layer surface. + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() == SurfaceWrapper::Type::Layer) + g_panelWrapper = wrapper; + }); +} + +extern "C" bool protocol_test_ready(WaylandServer *server) +{ + // The LockScreen plugin is loaded (and LockScreenManager::setLockScreenImpl + // creates the real LockScreen container) only after the blocking prestart + // hooks finish, which happens on the event loop after initTestCase. Until + // then WaylandServer has no lock screen implementation and + // onExtSessionLock() rejects every lock() with `finished`. Defer the + // client until the lock screen actually exists, exactly like + // protocol_test_ready() defers fixture-dependent tests (the framework waits + // for it with QTRY_VERIFY2_WITH_TIMEOUT); without this the client would race + // the plugin load and observe a spurious "compositor rejected the lock". + return server->isLockScreenAvailable(); +} + +// E-level read: the production WSessionLock state plus the geometry the lock +// surface wrapper ended up with, so the client can assert a lock surface covers +// the whole output instead of the exclusive-zone-free work area. +void session_lock_read_server_state(void *data) +{ + auto *state = static_cast(data); + *state = session_lock_server_state {}; + + state->valid = g_lock ? 1 : 0; + state->locked = (g_lock && g_lock->isLocked()) ? 1 : 0; + + auto *output = testOutput(); + if (!output) + return; + + const QRectF outputGeometry = output->geometry(); + state->output_width = qRound(outputGeometry.width()); + state->output_height = qRound(outputGeometry.height()); + state->output_x = qRound(outputGeometry.x()); + state->output_y = qRound(outputGeometry.y()); + state->valid_area_height = qRound(output->validGeometry().height()); + + auto *wrapper = lockWrapper(); + if (!wrapper) + return; + state->wrapper_valid = 1; + state->wrapper_x = qRound(wrapper->x()); + state->wrapper_y = qRound(wrapper->y()); + state->wrapper_width = qRound(wrapper->width()); + state->wrapper_height = qRound(wrapper->height()); +} diff --git a/tests/protocols/wayland-ext-session-lock-v1/wayland-ext-session-lock-v1.c b/tests/protocols/wayland-ext-session-lock-v1/wayland-ext-session-lock-v1.c new file mode 100644 index 0000000000..9e2b94ef52 --- /dev/null +++ b/tests/protocols/wayland-ext-session-lock-v1/wayland-ext-session-lock-v1.c @@ -0,0 +1,428 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Test the ext_session_lock_manager_v1 global served by Treeland's + * WSessionLockManager. + * + * Coverage level E (end-to-end): the client locks the session and, upon + * receiving the `locked` event, reads back the production WSessionLock state + * over the server bridge. WSessionLock::isLocked() must return true, proving + * the lock reached the real compositor session-lock object rather than merely + * surviving without a protocol error. The compositor may also deny the lock + * immediately by sending `finished` (e.g. when the lock screen is already + * visible); in that case the test reports failure, since unconditional lock + * rejection would be a regression. + * + * The same client also covers the lock surface geometry: a top layer surface + * first reserves an exclusive zone (the panel/dock area), then the lock surface + * commits a buffer and the production wrapper must still cover the whole output + * instead of the exclusive-zone-free work area. + */ + +#define _POSIX_C_SOURCE 200809L + +#include "wayland-ext-session-lock-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "ext-session-lock-v1-client-protocol.h" +#include "wlr-layer-shell-unstable-v1-client-protocol.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +/* Height of the exclusive zone the test reserves to make the work area differ + * from the whole output. */ +#define PANEL_HEIGHT 40 +#define WAIT_TIMEOUT_MS 2000 + +static struct client_connection conn; +static struct wl_compositor *compositor; +static struct wl_shm *shm; +static struct wl_output *output; +static struct zwlr_layer_shell_v1 *layer_shell; +static struct ext_session_lock_manager_v1 *lock_manager; +static struct wl_surface *panel_surface; +static struct zwlr_layer_surface_v1 *panel; +static struct wl_buffer *panel_buffer; +static struct wl_surface *lock_surface; +static struct ext_session_lock_surface_v1 *lock_surface_v1; +static struct wl_buffer *lock_buffer; +static struct ext_session_lock_v1 *lock; + +/* Every observable event the test waits for, and the stage reached for + * diagnostics. */ +static struct { + int panel_configure; + uint32_t panel_serial; + int32_t panel_width; + int32_t panel_height; + int locked; + int finished; + int lock_surface_configure; + uint32_t lock_surface_serial; + int32_t lock_surface_width; + int32_t lock_surface_height; +} observed; +static unsigned int stage; + +static int wait_for_flag(const int *flag, int timeout_ms) { + struct timespec start; + clock_gettime(CLOCK_MONOTONIC, &start); + + while (!*flag) { + if (wl_display_dispatch_pending(conn.display) < 0) + return 0; + if (*flag) + return 1; + + struct timespec now; + clock_gettime(CLOCK_MONOTONIC, &now); + const int elapsed = (int)((now.tv_sec - start.tv_sec) * 1000 + + (now.tv_nsec - start.tv_nsec) / 1000000); + const int remaining = timeout_ms - elapsed; + if (remaining <= 0) + return 0; + + if (wl_display_flush(conn.display) < 0 && errno != EAGAIN) + return 0; + struct pollfd pfd = { .fd = wl_display_get_fd(conn.display), .events = POLLIN }; + if (poll(&pfd, 1, remaining) > 0 && wl_display_dispatch(conn.display) < 0) + return 0; + } + + return 1; +} + +static void panel_configure(void *data, struct zwlr_layer_surface_v1 *surface, + uint32_t serial, uint32_t width, uint32_t height) { + (void)data; + (void)surface; + observed.panel_serial = serial; + observed.panel_width = (int32_t)width; + observed.panel_height = (int32_t)height; + observed.panel_configure++; +} + +static void panel_closed(void *data, struct zwlr_layer_surface_v1 *surface) { + (void)data; + (void)surface; +} + +static const struct zwlr_layer_surface_v1_listener panel_listener = { + .configure = panel_configure, + .closed = panel_closed, +}; + +static void locked(void *data, struct ext_session_lock_v1 *session_lock) { + (void)data; + (void)session_lock; + observed.locked = 1; +} + +static void finished(void *data, struct ext_session_lock_v1 *session_lock) { + (void)data; + (void)session_lock; + observed.finished = 1; +} + +static const struct ext_session_lock_v1_listener lock_listener = { + .locked = locked, + .finished = finished, +}; + +static void lock_surface_configure(void *data, + struct ext_session_lock_surface_v1 *surface, + uint32_t serial, uint32_t width, uint32_t height) { + (void)data; + (void)surface; + observed.lock_surface_serial = serial; + observed.lock_surface_width = (int32_t)width; + observed.lock_surface_height = (int32_t)height; + observed.lock_surface_configure++; +} + +static const struct ext_session_lock_surface_v1_listener lock_surface_listener = { + .configure = lock_surface_configure, +}; + +static struct wl_buffer *make_buffer(int width, int height) { + /* shm_open takes a literal name, it has no mkstemp-style template expansion: + * include the pid like the other protocol tests so concurrent runs (ctest -j) + * and leftover objects from a crashed run cannot collide. */ + char name[64]; + snprintf(name, sizeof(name), "/treeland_session_lock_%d", (int)getpid()); + int fd = shm_open(name, O_RDWR | O_CREAT | O_EXCL, 0600); + if (fd < 0) + return NULL; + shm_unlink(name); + + const int stride = width * 4; + const int size = stride * height; + if (ftruncate(fd, size) < 0) { + close(fd); + return NULL; + } + + void *p = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (p == MAP_FAILED) { + close(fd); + return NULL; + } + memset(p, 0xff, size); + + struct wl_shm_pool *pool = wl_shm_create_pool(shm, fd, size); + struct wl_buffer *buffer = pool + ? wl_shm_pool_create_buffer(pool, 0, width, height, stride, WL_SHM_FORMAT_ARGB8888) + : NULL; + if (pool) + wl_shm_pool_destroy(pool); + munmap(p, size); + close(fd); + return buffer; +} + +static int read_server_state(struct session_lock_server_state *state) { + if (!invoke_on_server_thread(session_lock_read_server_state, state)) { + fprintf(stderr, "ext-session-lock failure at stage %u: failed to read server state\n", + stage); + return 0; + } + return 1; +} + +static int run(void) { + struct session_lock_server_state srv = { 0 }; + + /* 1. Reserve a panel area so validGeometry() differs from geometry(): without + * an exclusive zone the surface-size assertion below would pass trivially. */ + stage = 1; + panel_surface = wl_compositor_create_surface(compositor); + if (!panel_surface) { + fprintf(stderr, "ext-session-lock failure at stage %u: failed to create panel surface\n", + stage); + return 1; + } + + panel = zwlr_layer_shell_v1_get_layer_surface(layer_shell, + panel_surface, + output, + ZWLR_LAYER_SHELL_V1_LAYER_TOP, + "protocol-test-panel"); + if (!panel) { + fprintf(stderr, "ext-session-lock failure at stage %u: failed to create panel layer surface\n", + stage); + return 1; + } + zwlr_layer_surface_v1_add_listener(panel, &panel_listener, NULL); + zwlr_layer_surface_v1_set_size(panel, 0, PANEL_HEIGHT); + zwlr_layer_surface_v1_set_anchor(panel, + ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP + | ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT + | ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT); + zwlr_layer_surface_v1_set_exclusive_zone(panel, PANEL_HEIGHT); + wl_surface_commit(panel_surface); + + if (!wait_for_flag(&observed.panel_configure, WAIT_TIMEOUT_MS)) { + fprintf(stderr, "ext-session-lock failure at stage %u: panel never configured\n", + stage); + return 1; + } + zwlr_layer_surface_v1_ack_configure(panel, observed.panel_serial); + panel_buffer = make_buffer(observed.panel_width, observed.panel_height); + if (!panel_buffer) { + fprintf(stderr, "ext-session-lock failure at stage %u: failed to create panel buffer\n", + stage); + return 1; + } + wl_surface_attach(panel_surface, panel_buffer, 0, 0); + wl_surface_damage(panel_surface, 0, 0, observed.panel_width, observed.panel_height); + wl_surface_commit(panel_surface); + if (wl_display_roundtrip(conn.display) < 0) { + fprintf(stderr, "ext-session-lock failure at stage %u: panel commit failed\n", stage); + return 1; + } + + /* 2. Precondition: the panel exclusive zone must actually shrink the work area. */ + stage = 2; + if (!read_server_state(&srv)) + return 1; + if (srv.valid_area_height != srv.output_height - PANEL_HEIGHT) { + fprintf(stderr, + "ext-session-lock failure at stage %u: exclusive zone not applied " + "(output height %d, work area height %d, expected %d)\n", + stage, srv.output_height, srv.valid_area_height, + srv.output_height - PANEL_HEIGHT); + return 1; + } + + /* 3. Lock the session. */ + stage = 3; + lock = ext_session_lock_manager_v1_lock(lock_manager); + if (!lock) { + fprintf(stderr, "ext-session-lock failure at stage %u: lock() returned NULL\n", stage); + return 1; + } + ext_session_lock_v1_add_listener(lock, &lock_listener, NULL); + + if (!wait_for_flag(&observed.locked, WAIT_TIMEOUT_MS)) { + if (observed.finished) + fprintf(stderr, + "ext-session-lock failure at stage %u: compositor rejected the lock\n", + stage); + else + fprintf(stderr, + "ext-session-lock failure at stage %u: no locked or finished event\n", + stage); + return 1; + } + + /* 4. Commit a lock surface buffer at the configured size. */ + stage = 4; + lock_surface = wl_compositor_create_surface(compositor); + if (!lock_surface) { + fprintf(stderr, "ext-session-lock failure at stage %u: failed to create lock surface\n", + stage); + return 1; + } + lock_surface_v1 = ext_session_lock_v1_get_lock_surface(lock, lock_surface, output); + if (!lock_surface_v1) { + fprintf(stderr, "ext-session-lock failure at stage %u: failed to get lock surface\n", + stage); + return 1; + } + ext_session_lock_surface_v1_add_listener(lock_surface_v1, &lock_surface_listener, NULL); + + if (!wait_for_flag(&observed.lock_surface_configure, WAIT_TIMEOUT_MS)) { + fprintf(stderr, "ext-session-lock failure at stage %u: lock surface never configured\n", + stage); + return 1; + } + ext_session_lock_surface_v1_ack_configure(lock_surface_v1, observed.lock_surface_serial); + lock_buffer = make_buffer(observed.lock_surface_width, observed.lock_surface_height); + if (!lock_buffer) { + fprintf(stderr, "ext-session-lock failure at stage %u: failed to create lock buffer\n", + stage); + return 1; + } + wl_surface_attach(lock_surface, lock_buffer, 0, 0); + wl_surface_damage(lock_surface, 0, 0, + observed.lock_surface_width, observed.lock_surface_height); + wl_surface_commit(lock_surface); + if (wl_display_roundtrip(conn.display) < 0) { + fprintf(stderr, "ext-session-lock failure at stage %u: lock surface commit failed\n", + stage); + return 1; + } + + /* 5. The production wrapper must cover the whole output, not the work area. */ + stage = 5; + if (!read_server_state(&srv)) + return 1; + if (!srv.valid || !srv.locked) { + fprintf(stderr, + "ext-session-lock failure at stage %u: WSessionLock state invalid=%d locked=%d\n", + stage, srv.valid, srv.locked); + return 1; + } + if (!srv.wrapper_valid) { + fprintf(stderr, "ext-session-lock failure at stage %u: no lock surface wrapper\n", + stage); + return 1; + } + if (observed.lock_surface_width != srv.output_width + || observed.lock_surface_height != srv.output_height) { + fprintf(stderr, + "ext-session-lock failure at stage %u: configured %dx%d, output is %dx%d\n", + stage, observed.lock_surface_width, observed.lock_surface_height, + srv.output_width, srv.output_height); + return 1; + } + if (srv.wrapper_width != srv.output_width || srv.wrapper_height != srv.output_height) { + fprintf(stderr, + "ext-session-lock failure at stage %u: lock surface wrapper is %dx%d at (%d,%d), " + "expected the whole %dx%d output (work area height %d)\n", + stage, srv.wrapper_width, srv.wrapper_height, srv.wrapper_x, srv.wrapper_y, + srv.output_width, srv.output_height, srv.valid_area_height); + return 1; + } + if (srv.wrapper_x != srv.output_x || srv.wrapper_y != srv.output_y) { + fprintf(stderr, + "ext-session-lock failure at stage %u: lock surface wrapper at (%d,%d), " + "expected the output origin (%d,%d)\n", + stage, srv.wrapper_x, srv.wrapper_y, srv.output_x, srv.output_y); + return 1; + } + + return 0; +} + +static void cleanup(void) { + /* Destroy the lock surface before the lock: unlocking destroys the lock's + * surfaces server side, so destroying it afterwards would send a request on + * an already destroyed object and raise a protocol error. */ + if (lock_surface_v1) + ext_session_lock_surface_v1_destroy(lock_surface_v1); + if (lock) + ext_session_lock_v1_unlock_and_destroy(lock); + if (lock_surface) + wl_surface_destroy(lock_surface); + if (lock_buffer) + wl_buffer_destroy(lock_buffer); + if (panel) + zwlr_layer_surface_v1_destroy(panel); + if (panel_surface) + wl_surface_destroy(panel_surface); + if (panel_buffer) + wl_buffer_destroy(panel_buffer); + if (layer_shell) + zwlr_layer_shell_v1_destroy(layer_shell); + if (lock_manager) + ext_session_lock_manager_v1_destroy(lock_manager); + if (output) + wl_output_destroy(output); + if (shm) + wl_shm_destroy(shm); + if (compositor) + wl_compositor_destroy(compositor); + if (conn.display) + wl_display_flush(conn.display); +} + +int protocol_test_run(const char *socket_name) { + memset(&conn, 0, sizeof(conn)); + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("ext-session-lock: connect failed\n"); + return 1; + } + + compositor = client_bind(&conn, wl_compositor_interface.name, &wl_compositor_interface, + wl_compositor_interface.version); + shm = client_bind(&conn, wl_shm_interface.name, &wl_shm_interface, + wl_shm_interface.version); + output = client_bind(&conn, wl_output_interface.name, &wl_output_interface, + wl_output_interface.version); + layer_shell = client_bind(&conn, zwlr_layer_shell_v1_interface.name, + &zwlr_layer_shell_v1_interface, 5); + lock_manager = client_bind(&conn, ext_session_lock_manager_v1_interface.name, + &ext_session_lock_manager_v1_interface, + ext_session_lock_manager_v1_interface.version); + if (!compositor || !shm || !output || !layer_shell || !lock_manager) { + TEST_ERROR("ext-session-lock: failed to bind required globals: %s\n", + strerror(errno)); + cleanup(); + client_disconnect(&conn); + return 1; + } + + const int failed = run(); + cleanup(); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-ext-session-lock-v1/wayland-ext-session-lock-v1.h b/tests/protocols/wayland-ext-session-lock-v1/wayland-ext-session-lock-v1.h new file mode 100644 index 0000000000..934f793f8c --- /dev/null +++ b/tests/protocols/wayland-ext-session-lock-v1/wayland-ext-session-lock-v1.h @@ -0,0 +1,50 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_EXT_SESSION_LOCK_TEST_H +#define WAYLAND_EXT_SESSION_LOCK_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Snapshot of the real WSessionLock state, read on the compositor (Qt) thread. + * Treeland's WaylandServer::onExtSessionLock starts a 300 ms grace timer and then + * calls WSessionLock::lock(), which sends the `locked` event to the client and + * flips the production WSessionLock to the Locked state. An E-level test + * verifies that WSessionLock::isLocked() returns true after the client receives + * the `locked` event, proving the lock reached the real compositor session-lock + * object rather than merely surviving without a protocol error. + * + * The output geometry fields make the surface-size expectation explicit: a lock + * surface must cover the whole output (geometry), not just the work area + * (validGeometry, i.e. the output with exclusive zones removed). + */ +struct session_lock_server_state { + int valid; /* a WSessionLock was captured from lockCreated */ + int locked; /* WSessionLock::isLocked() */ + int output_width; /* Output::geometry() */ + int output_height; + int output_x; /* Output::geometry() top-left */ + int output_y; + int valid_area_height; /* Output::validGeometry() height */ + int wrapper_valid; /* a Type::LockScreen SurfaceWrapper was captured */ + int wrapper_x; /* geometry of that wrapper */ + int wrapper_y; + int wrapper_width; + int wrapper_height; +}; + +/* Defined in setup.cpp; runs on the compositor thread via + * invoke_on_server_thread() and fills *data with the lock state. */ +void session_lock_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_EXT_SESSION_LOCK_TEST_H */ diff --git a/tests/protocols/wayland-ext-workspace-v1/CMakeLists.txt b/tests/protocols/wayland-ext-workspace-v1/CMakeLists.txt new file mode 100644 index 0000000000..0ec12d939c --- /dev/null +++ b/tests/protocols/wayland-ext-workspace-v1/CMakeLists.txt @@ -0,0 +1,6 @@ +treeland_add_protocol_test( + NAME wayland_ext_workspace_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/ext-workspace/ext-workspace-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-ext-workspace-v1.c" +) diff --git a/tests/protocols/wayland-ext-workspace-v1/README.md b/tests/protocols/wayland-ext-workspace-v1/README.md new file mode 100644 index 0000000000..21b550d8cf --- /dev/null +++ b/tests/protocols/wayland-ext-workspace-v1/README.md @@ -0,0 +1,19 @@ +# ext-workspace-v1 + +使用生产启动路径中的每会话 `WExtWorkspaceManagerV1`,由纯 C 客户端连接两个真实 Session socket。 +fixture 只初始化两套真实工作区;定向移除、重排用于注入协议没有提供的服务端变化。 + +覆盖:独立 native manager、registry 精确隔离、名称与 ID 隔离、group/output 归属、capabilities、coordinates、 +active 状态、done、activate/create 在 commit 前不生效及提交后的模型结果、重名拒绝、数量上限、后台创建隔离、 +移除后待提交请求失效、重排保持 ID、stop/finished。 + +group 覆盖会话的输出,当前只声明 CREATE_WORKSPACE 和 ACTIVATE;不声明 ASSIGN、DEACTIVATE、REMOVE。 +未覆盖:输出热插拔、urgent 聚合、global 撤销及 display stop/restart。 + +本次环境无 CMake/编译器,测试尚未执行;缺少第二个可用账号时返回 77,不计作通过。 + +```sh +cmake --preset ci +cmake --build --preset ci --target test_wayland_ext_workspace_v1 +ctest --test-dir build -V -R '^test_wayland_ext_workspace_v1$' +``` diff --git a/tests/protocols/wayland-ext-workspace-v1/setup.cpp b/tests/protocols/wayland-ext-workspace-v1/setup.cpp new file mode 100644 index 0000000000..76f02bcc19 --- /dev/null +++ b/tests/protocols/wayland-ext-workspace-v1/setup.cpp @@ -0,0 +1,104 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "test-state.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "core/rootsurfacecontainer.h" +#include "session/session.h" +#include "session/sessionmanager.h" +#include "workspace/workspace.h" +#include "output/output.h" +#include +#include "treelanduserconfig.hpp" +#include +#include +#include +#include +#include +#include +#include + +namespace { +QPointer owners[2]; +bool prepared = false; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + owners[0] = server->sessionManager()->globalSession().get(); + const auto *account = getpwuid(getuid()); + if (account && owners[0] && owners[0]->username() == QString::fromLocal8Bit(account->pw_name)) + account = getpwnam("nobody"); + if (account) + owners[1] = server->sessionManager()->ensureSession( + QStringLiteral("protocol-ext-workspace"), QString::fromLocal8Bit(account->pw_name)).get(); + if (owners[1]) + owners[1]->socket()->setEnabled(true); +} + +extern "C" bool protocol_test_ready(WaylandServer *server) +{ + if (!owners[0] || !owners[1]) + return true; // The client reports unavailable account fixtures as skipped. + if (server->rootSurfaceContainer()->outputs().isEmpty() + || !server->rootSurfaceContainer()->outputs().first()->output()->isEnabled()) + return false; + for (const auto &owner : owners) { + if (!owner->config()->isInitializeSucceeded()) + return false; + } + if (!prepared) { + for (int i = 0; i < 2; ++i) { + auto *workspace = owners[i]->workspace(); + owners[i]->config()->setMaxWorkspace(4); + while (workspace->count() > 2) + workspace->removeModel(workspace->count() - 1); + while (workspace->count() < 2) + workspace->createModel(); + workspace->setCurrentIndex(0); + for (int j = 0; j < workspace->count(); ++j) + workspace->modelAt(j)->setName(QStringLiteral("session-%1-workspace-%2").arg(i).arg(j)); + } + prepared = true; + } + return true; +} + +extern "C" void workspace_test_read(void *data) +{ + auto *state = static_cast(data); + *state = {}; + if (!owners[0] || !owners[1]) + return; + const auto socket = owners[1]->socket()->fullServerName().toUtf8(); + std::strncpy(state->background_socket, socket.constData(), sizeof(state->background_socket) - 1); + WExtWorkspaceManagerV1 *managers[2] = {}; + for (auto *interface : WaylandServer::instance()->server()->interfaceList()) { + auto *manager = dynamic_cast(interface); + if (!manager) + continue; + for (int i = 0; i < 2; ++i) { + if (interface->ownsSocket() == owners[i]->socket()) + managers[i] = manager; + } + } + state->independent = managers[0] && managers[1] && managers[0]->handle() + && managers[1]->handle() && managers[0]->handle() != managers[1]->handle(); + for (int i = 0; i < 2; ++i) { + state->counts[i] = owners[i]->workspace()->count(); + state->current[i] = owners[i]->workspace()->currentIndex(); + } +} + +extern "C" void workspace_test_remove_first(void *) +{ + owners[0]->workspace()->removeModel(0); +} + +extern "C" void workspace_test_reorder(void *) +{ + auto *workspace = owners[0]->workspace(); + workspace->moveModelTo(workspace->current()->id(), 0); +} diff --git a/tests/protocols/wayland-ext-workspace-v1/test-state.h b/tests/protocols/wayland-ext-workspace-v1/test-state.h new file mode 100644 index 0000000000..1f026b1b6c --- /dev/null +++ b/tests/protocols/wayland-ext-workspace-v1/test-state.h @@ -0,0 +1,20 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once +#include +struct workspace_test_state { + char background_socket[256]; + uint32_t counts[2]; + uint32_t current[2]; + int independent; +}; +#ifdef __cplusplus +extern "C" { +#endif +void workspace_test_read(void *data); +void workspace_test_remove_first(void *data); +void workspace_test_reorder(void *data); +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/wayland-ext-workspace-v1/wayland-ext-workspace-v1.c b/tests/protocols/wayland-ext-workspace-v1/wayland-ext-workspace-v1.c new file mode 100644 index 0000000000..68cc7dad05 --- /dev/null +++ b/tests/protocols/wayland-ext-workspace-v1/wayland-ext-workspace-v1.c @@ -0,0 +1,209 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "client-connection.h" +#include "server-bridge-api.h" +#include "test-state.h" +#include "ext-workspace-v1-client-protocol.h" +#include +#include +#include + +#define MAX_WORKSPACES 32 +struct workspace { + struct ext_workspace_handle_v1 *proxy; + char id[128], name[128]; + uint32_t state, capabilities, coordinate; + int removed; +}; +struct client { + struct client_connection conn; + struct ext_workspace_manager_v1 *manager; + struct ext_workspace_group_handle_v1 *group; + struct wl_output *output; + int output_entered; + struct workspace workspaces[MAX_WORKSPACES]; + int count, groups, done, finished, entered, left; + uint32_t capabilities; +}; + +static void workspace_id(void *data, struct ext_workspace_handle_v1 *proxy, const char *id) +{ (void)proxy; snprintf(((struct workspace *)data)->id, 128, "%s", id); } +static void workspace_name(void *data, struct ext_workspace_handle_v1 *proxy, const char *name) +{ (void)proxy; snprintf(((struct workspace *)data)->name, 128, "%s", name); } +static void coordinates(void *data, struct ext_workspace_handle_v1 *proxy, struct wl_array *array) +{ + (void)proxy; + ((struct workspace *)data)->coordinate = array->size == sizeof(uint32_t) + ? *(uint32_t *)array->data : UINT32_MAX; +} +static void state(void *data, struct ext_workspace_handle_v1 *proxy, uint32_t value) +{ (void)proxy; ((struct workspace *)data)->state = value; } +static void capabilities(void *data, struct ext_workspace_handle_v1 *proxy, uint32_t value) +{ (void)proxy; ((struct workspace *)data)->capabilities = value; } +static void removed(void *data, struct ext_workspace_handle_v1 *proxy) +{ (void)proxy; ((struct workspace *)data)->removed = 1; } +static const struct ext_workspace_handle_v1_listener workspace_listener = { + .id = workspace_id, .name = workspace_name, .coordinates = coordinates, + .state = state, .capabilities = capabilities, .removed = removed, +}; +static void group_caps(void *data, struct ext_workspace_group_handle_v1 *group, uint32_t caps) +{ (void)group; ((struct client *)data)->capabilities = caps; } +static void output_enter(void *data, struct ext_workspace_group_handle_v1 *group, struct wl_output *output) +{ (void)group; struct client *client = data; if (output == client->output) ++client->output_entered; } +static void output_leave(void *data, struct ext_workspace_group_handle_v1 *group, struct wl_output *output) +{ (void)data; (void)group; (void)output; } +static void workspace_enter(void *data, struct ext_workspace_group_handle_v1 *group, struct ext_workspace_handle_v1 *workspace) +{ (void)group; (void)workspace; ++((struct client *)data)->entered; } +static void workspace_leave(void *data, struct ext_workspace_group_handle_v1 *group, struct ext_workspace_handle_v1 *workspace) +{ (void)group; (void)workspace; ++((struct client *)data)->left; } +static void group_removed(void *data, struct ext_workspace_group_handle_v1 *group) +{ (void)data; (void)group; } +static const struct ext_workspace_group_handle_v1_listener group_listener = { + .capabilities = group_caps, .output_enter = output_enter, .output_leave = output_leave, + .workspace_enter = workspace_enter, .workspace_leave = workspace_leave, .removed = group_removed, +}; +static void new_group(void *data, struct ext_workspace_manager_v1 *manager, struct ext_workspace_group_handle_v1 *group) +{ + (void)manager; + struct client *client = data; + ++client->groups; + client->group = group; + ext_workspace_group_handle_v1_add_listener(group, &group_listener, client); +} +static void new_workspace(void *data, struct ext_workspace_manager_v1 *manager, struct ext_workspace_handle_v1 *proxy) +{ + (void)manager; + struct client *client = data; + if (client->count == MAX_WORKSPACES) { + ext_workspace_handle_v1_destroy(proxy); + return; + } + struct workspace *workspace = &client->workspaces[client->count++]; + workspace->proxy = proxy; + ext_workspace_handle_v1_add_listener(proxy, &workspace_listener, workspace); +} +static void done(void *data, struct ext_workspace_manager_v1 *manager) +{ (void)manager; ++((struct client *)data)->done; } +static void finished(void *data, struct ext_workspace_manager_v1 *manager) +{ (void)manager; ++((struct client *)data)->finished; } +static const struct ext_workspace_manager_v1_listener manager_listener = { + .workspace_group = new_group, .workspace = new_workspace, .done = done, .finished = finished, +}; +static int roundtrip(struct client *client) +{ + return wl_display_roundtrip(client->conn.display) >= 0 + && wl_display_roundtrip(client->conn.display) >= 0; +} +static void output_geometry(void *data, struct wl_output *output, int32_t x, int32_t y, + int32_t width, int32_t height, int32_t subpixel, const char *make, const char *model, int32_t transform) +{ + (void)data; (void)output; (void)x; (void)y; (void)width; (void)height; + (void)subpixel; (void)make; (void)model; (void)transform; +} +static void output_mode(void *data, struct wl_output *output, uint32_t flags, int32_t width, int32_t height, int32_t refresh) +{ (void)data; (void)output; (void)flags; (void)width; (void)height; (void)refresh; } +static const struct wl_output_listener output_listener = { + .geometry = output_geometry, .mode = output_mode, +}; +static int connect_client(struct client *client, const char *socket) +{ + if (!client_connect(&client->conn, socket)) + return 0; + int managers = 0; + for (uint32_t i = 0; i < client->conn.global_count; ++i) + managers += strcmp(client->conn.globals[i].interface, "ext_workspace_manager_v1") == 0; + if (managers != 1) + return 0; + client->output = client_bind(&client->conn, "wl_output", &wl_output_interface, 1); + if (!client->output) + return 0; + wl_output_add_listener(client->output, &output_listener, client); + client->manager = client_bind(&client->conn, "ext_workspace_manager_v1", &ext_workspace_manager_v1_interface, 1); + if (!client->manager) + return 0; + ext_workspace_manager_v1_add_listener(client->manager, &manager_listener, client); + return roundtrip(client); +} +static void destroy_client(struct client *client) +{ + if (!client->conn.display) + return; + for (int i = 0; i < client->count; ++i) + ext_workspace_handle_v1_destroy(client->workspaces[i].proxy); + if (client->group) + ext_workspace_group_handle_v1_destroy(client->group); + if (client->manager) + ext_workspace_manager_v1_destroy(client->manager); + if (client->output) + wl_output_destroy(client->output); + client_disconnect(&client->conn); +} +#define REQUIRE(condition, name) do { if (!(condition)) { TEST_ERROR("FAIL: %s\n", name); failed = 1; goto cleanup; } printf("PASS: %s\n", name); } while (0) +#define READ() invoke_on_server_thread(workspace_test_read, &production) + +int protocol_test_run(const char *socket_name) +{ + struct client a = {0}, b = {0}; + struct workspace_test_state production = {0}; + int failed = 0; + if (!READ() || !production.background_socket[0]) + return 77; + REQUIRE(production.independent, "one native manager per session"); + REQUIRE(connect_client(&a, socket_name) && connect_client(&b, production.background_socket), "exactly one visible manager per socket"); + REQUIRE(a.groups == 1 && b.groups == 1 && a.count == 2 && b.count == 2 && a.done && b.done, "initial enumeration and done"); + REQUIRE(a.output_entered == 1 && b.output_entered == 1, "group publishes the bound output"); + REQUIRE(a.entered == 2 && b.entered == 2, "one group contains this session's workspaces"); + REQUIRE(strcmp(a.workspaces[0].name, "session-0-workspace-0") == 0 + && strcmp(b.workspaces[0].name, "session-1-workspace-0") == 0 + && a.workspaces[0].id[0] && strcmp(a.workspaces[0].id, b.workspaces[0].id) != 0, "isolated names and identifiers"); + REQUIRE(a.capabilities == EXT_WORKSPACE_GROUP_HANDLE_V1_GROUP_CAPABILITIES_CREATE_WORKSPACE + && a.workspaces[0].capabilities == EXT_WORKSPACE_HANDLE_V1_WORKSPACE_CAPABILITIES_ACTIVATE + && a.workspaces[0].coordinate == 0 && a.workspaces[1].coordinate == 1, "capabilities and coordinates"); + + ext_workspace_handle_v1_activate(a.workspaces[1].proxy); + REQUIRE(roundtrip(&a) && READ() && production.current[0] == 0, "activate is deferred until commit"); + ext_workspace_manager_v1_commit(a.manager); + REQUIRE(roundtrip(&a) && READ() && production.current[0] == 1 && production.current[1] == 0 + && (a.workspaces[1].state & EXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE) + && !(a.workspaces[0].state & EXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE), "commit activates only the owning session"); + + ext_workspace_group_handle_v1_create_workspace(a.group, "created-by-client"); + REQUIRE(roundtrip(&a) && READ() && production.counts[0] == 2, "create is deferred until commit"); + ext_workspace_manager_v1_commit(a.manager); + REQUIRE(roundtrip(&a) && READ() && production.counts[0] == 3 && production.counts[1] == 2 + && a.count == 3 && b.count == 2 && strcmp(a.workspaces[2].name, "created-by-client") == 0 + && (a.workspaces[2].state & EXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE), "create publishes and activates a real model"); + ext_workspace_group_handle_v1_create_workspace(a.group, "created-by-client"); + ext_workspace_manager_v1_commit(a.manager); + REQUIRE(roundtrip(&a) && READ() && production.counts[0] == 3, "duplicate names are rejected"); + + ext_workspace_group_handle_v1_create_workspace(b.group, "background-created-1"); + ext_workspace_manager_v1_commit(b.manager); + ext_workspace_group_handle_v1_create_workspace(b.group, "background-created-2"); + ext_workspace_manager_v1_commit(b.manager); + ext_workspace_group_handle_v1_create_workspace(b.group, "background-over-limit"); + ext_workspace_manager_v1_commit(b.manager); + REQUIRE(roundtrip(&b) && READ() && production.counts[1] == 4 && production.counts[0] == 3 + && production.current[0] == 2 && production.current[1] == 3 + && b.count == 4 && (b.workspaces[3].state & EXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE), "background creation is isolated and respects the workspace limit"); + + ext_workspace_handle_v1_activate(a.workspaces[0].proxy); + REQUIRE(roundtrip(&a) && invoke_on_server_thread(workspace_test_remove_first, NULL) && roundtrip(&a), "remove a model with pending activation"); + ext_workspace_manager_v1_commit(a.manager); + REQUIRE(roundtrip(&a) && READ() && production.counts[0] == 2 && production.current[0] == 1 + && a.workspaces[0].removed && a.left == 1, "removed workspace request becomes inert"); + char stable_id[128]; + snprintf(stable_id, sizeof(stable_id), "%s", a.workspaces[2].id); + REQUIRE(invoke_on_server_thread(workspace_test_reorder, NULL) && roundtrip(&a) && READ() + && production.current[0] == 0 && a.workspaces[2].coordinate == 0 + && (a.workspaces[2].state & EXT_WORKSPACE_HANDLE_V1_STATE_ACTIVE) + && strcmp(stable_id, a.workspaces[2].id) == 0, "reorder updates coordinates without changing identifiers"); + + ext_workspace_manager_v1_stop(a.manager); + REQUIRE(roundtrip(&a) && a.finished == 1 && roundtrip(&b), "stop is acknowledged without affecting another session"); +cleanup: + destroy_client(&a); + destroy_client(&b); + return failed; +} diff --git a/tests/protocols/wayland-fractional-scale-v1/CMakeLists.txt b/tests/protocols/wayland-fractional-scale-v1/CMakeLists.txt new file mode 100644 index 0000000000..a7ba5f17f9 --- /dev/null +++ b/tests/protocols/wayland-fractional-scale-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_fractional_scale_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/fractional-scale/fractional-scale-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-fractional-scale-v1.c" +) diff --git a/tests/protocols/wayland-fractional-scale-v1/README.md b/tests/protocols/wayland-fractional-scale-v1/README.md new file mode 100644 index 0000000000..c5b3b4d591 --- /dev/null +++ b/tests/protocols/wayland-fractional-scale-v1/README.md @@ -0,0 +1,29 @@ +# `wayland-fractional-scale-v1` 测试规范 + +## 范围 + +- XML / interface:`wp_fractional_scale_manager_v1` / `wp_fractional_scale_v1`(version 1) +- 测试源码:`tests/protocols/wayland-fractional-scale-v1/` +- Fixture:headless output fixture + xdg-toplevel-client(solid buffer 映射) +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `wp_fractional_scale_manager_v1`(v1) | 资源创建成功 | P | +| 关联表面 | `get_fractional_scale(surface)` | 返回非 NULL 的 fractional-scale | P | +| 首选缩放 | 映射表面 + `commit` 后 roundtrip | 收到 `preferred_scale` 事件(scale>0) | P | +| 缩放值与真实输出一致 | 回读真实 `WOutput::scale()` | `preferred_scale` == round(`WOutput::scale()` × 120) | E | + +## 生产结果 + +测试创建并映射一个真实 xdg_toplevel,为其附加 `wp_fractional_scale_v1` 对象并提交。 +服务端下发 `preferred_scale` 事件后,测试通过 server bridge 回读 headless 输出对应的 +真实 `WOutput::scale()`,断言 `preferred_scale` 等于 `round(scale × 120)`。wlroots 正是 +使用该 `WOutput` 的 scale 值生成 `preferred_scale` 事件,因此此断言验证事件反映了真实 +生产输出状态,而非仅事件到达且非 0。 + +## 已知边界 / 下一项结果 + +未验证非整数缩放下的实际像素缓冲重新分配(V 级像素读回亦未覆盖)。 diff --git a/tests/protocols/wayland-fractional-scale-v1/setup.cpp b/tests/protocols/wayland-fractional-scale-v1/setup.cpp new file mode 100644 index 0000000000..d53e55b3ee --- /dev/null +++ b/tests/protocols/wayland-fractional-scale-v1/setup.cpp @@ -0,0 +1,38 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-fractional-scale-v1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" + +#include +#include + +#include +#include + +static QPointer g_woutput; + +void protocol_test_setup(WaylandServer *server) +{ + auto *output = add_headless_output(server->backend(), false); + Q_ASSERT(output); + g_woutput = output; +} + +// E-level read: resolve the real WOutput that backs the headless output and +// return its fractional scale. wlroots uses this exact value (multiplied by +// 120 and rounded) to populate the wp_fractional_scale_v1.preferred_scale +// event, so the client-side event must match the live production object. +void fractional_scale_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = 0; + state->scale = 0.0f; + + WOutput *woutput = g_woutput.data(); + if (!woutput) + return; + + state->valid = 1; + state->scale = woutput->scale(); +} diff --git a/tests/protocols/wayland-fractional-scale-v1/wayland-fractional-scale-v1.c b/tests/protocols/wayland-fractional-scale-v1/wayland-fractional-scale-v1.c new file mode 100644 index 0000000000..7c465f5f10 --- /dev/null +++ b/tests/protocols/wayland-fractional-scale-v1/wayland-fractional-scale-v1.c @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Test the wp_fractional_scale_manager_v1 global served by Treeland + * (wlr_fractional_scale_manager_v1_create). The client maps a toplevel with a + * solid buffer, attaches a fractional-scale object, commits, and asserts the + * server delivers a `preferred_scale` event. + * + * Coverage level E (end-to-end): the test cross-checks the preferred_scale + * event against the live WOutput scale read back over the server bridge. + * wlroots sends preferred_scale as a numerator with denominator 120, so the + * expected value is round(WOutput::scale() * 120). Verifying this match + * proves the event reflects the real production output state. + */ + +#include "wayland-fractional-scale-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "fractional-scale-v1-client-protocol.h" + +#include +#include + +struct fs_state { + int preferred_scale_count; + uint32_t scale; +}; + +static void preferred_scale(void *data, struct wp_fractional_scale_v1 *fs, uint32_t scale) { + (void)fs; + struct fs_state *state = data; + state->preferred_scale_count++; + state->scale = scale; +} + +static const struct wp_fractional_scale_v1_listener fs_listener = { + .preferred_scale = preferred_scale, +}; + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("fractional-scale: connect failed\n"); + return 1; + } + + struct xdg_toplevel_client tc; + if (!xdg_toplevel_client_create_with_solid_buffer(&conn, &tc, 64, 64, 0xffff0000u)) { + TEST_ERROR("fractional-scale: create toplevel failed\n"); + client_disconnect(&conn); + return 1; + } + + struct wp_fractional_scale_manager_v1 *manager = client_bind( + &conn, wp_fractional_scale_manager_v1_interface.name, &wp_fractional_scale_manager_v1_interface, wp_fractional_scale_manager_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("fractional-scale: failed to bind manager: %s\n", strerror(errno)); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + + struct fs_state state = { 0 }; + struct wp_fractional_scale_v1 *fs = + wp_fractional_scale_manager_v1_get_fractional_scale(manager, tc.surface); + if (fs == NULL) { + TEST_ERROR("fractional-scale: get_fractional_scale returned NULL\n"); + wp_fractional_scale_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + wp_fractional_scale_v1_add_listener(fs, &fs_listener, &state); + + wl_surface_commit(tc.surface); + wl_display_roundtrip(conn.display); + + int failed = 0; + if (state.preferred_scale_count < 1) { + TEST_ERROR("fractional-scale: no preferred_scale event received\n"); + failed = 1; + } else if (state.scale == 0) { + TEST_ERROR("fractional-scale: preferred_scale reported 0\n"); + failed = 1; + } + + /* E-level: cross-check the preferred_scale against the live WOutput scale. */ + if (!failed) { + struct fractional_scale_server_state srv = { 0 }; + if (invoke_on_server_thread(fractional_scale_read_server_state, &srv) == 0) { + TEST_ERROR("fractional-scale: failed to read server state\n"); + failed = 1; + } else if (!srv.valid) { + TEST_ERROR("fractional-scale: no WOutput found\n"); + failed = 1; + } else { + uint32_t expected = (uint32_t)(srv.scale * 120.0f + 0.5f); + if (expected != state.scale) { + TEST_ERROR("fractional-scale: preferred_scale=%u but WOutput scale=%.2f\n" + " (expected %u)", + state.scale, (double)srv.scale, expected); + failed = 1; + } + } + } + + wp_fractional_scale_v1_destroy(fs); + wp_fractional_scale_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-fractional-scale-v1/wayland-fractional-scale-v1.h b/tests/protocols/wayland-fractional-scale-v1/wayland-fractional-scale-v1.h new file mode 100644 index 0000000000..145a8c5920 --- /dev/null +++ b/tests/protocols/wayland-fractional-scale-v1/wayland-fractional-scale-v1.h @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_FRACTIONAL_SCALE_TEST_H +#define WAYLAND_FRACTIONAL_SCALE_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Snapshot of the real WOutput scale, read on the compositor (Qt) thread. + * wlroots sends wp_fractional_scale_v1.preferred_scale as a numerator with a + * denominator of 120. The expected value is round(WOutput::scale() * 120). + * An E-level test verifies that the client-side preferred_scale event matches + * the live production output scale, not merely that an event was delivered. + */ +struct fractional_scale_server_state { + int valid; /* a WOutput was found */ + float scale; /* WOutput::scale() */ +}; + +/* Defined in setup.cpp; runs on the compositor thread via + * invoke_on_server_thread() and fills *data with the output's scale. */ +void fractional_scale_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_FRACTIONAL_SCALE_TEST_H */ diff --git a/tests/protocols/wayland-idle-inhibit-unstable-v1/CMakeLists.txt b/tests/protocols/wayland-idle-inhibit-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..474eab1f21 --- /dev/null +++ b/tests/protocols/wayland-idle-inhibit-unstable-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_idle_inhibit_unstable_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/unstable/idle-inhibit/idle-inhibit-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-idle-inhibit-unstable-v1.c" +) diff --git a/tests/protocols/wayland-idle-inhibit-unstable-v1/README.md b/tests/protocols/wayland-idle-inhibit-unstable-v1/README.md new file mode 100644 index 0000000000..df4698fed4 --- /dev/null +++ b/tests/protocols/wayland-idle-inhibit-unstable-v1/README.md @@ -0,0 +1,30 @@ +# `wayland-idle-inhibit-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`zwp_idle_inhibit_manager_v1` / `zwp_idle_inhibitor_v1`(version 1,无事件) +- 测试源码:`tests/protocols/wayland-idle-inhibit-unstable-v1/` +- Fixture:headless output fixture + 映射 xdg-toplevel +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `zwp_idle_inhibit_manager_v1` | 资源创建成功 | P | +| 创建 inhibitor | `create_inhibitor(mapped_surface)` | 返回非 NULL 资源 | P | +| **生产回读** | — | 真实 `wlr_idle_inhibitor_v1` 存在且关联的 `WSurface` 已 mapped | **E** | +| **销毁** | 销毁 inhibitor | 测试 client 不再拥有 `zwp_idle_inhibitor_v1` production resource | **E** | + +## 生产结果 + +测试观察 Treeland 通过 `wlr_idle_inhibit_manager_v1_create` 提供的空闲抑制服务。 +创建 inhibitor 后,setup 枚举测试 client 的真实 Wayland resource,读取 wlroots +`wlr_idle_inhibitor_v1` 并断言其关联的 `WSurface` 已 mapped;销毁后再次枚举并要求 +该 resource 已移除。这证明 idle-inhibit request 到达生产 manager,并且 inhibitor +实际挂在被抑制的 surface 上。 + +## 已知边界 / 下一项结果 + +接口本身无事件;未验证由 `WaylandServer::updateIdleInhibitor()` 计算出的全局 idle-notifier +`inhibited` 状态,该跨协议行为由 ext-idle-notify 测试覆盖。 diff --git a/tests/protocols/wayland-idle-inhibit-unstable-v1/setup.cpp b/tests/protocols/wayland-idle-inhibit-unstable-v1/setup.cpp new file mode 100644 index 0000000000..b279ab626a --- /dev/null +++ b/tests/protocols/wayland-idle-inhibit-unstable-v1/setup.cpp @@ -0,0 +1,84 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-idle-inhibit-unstable-v1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" + +#include +#include +#include + +#include + +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +struct wl_display *g_display = nullptr; + +struct find_inhibitor_data { + struct wlr_idle_inhibitor_v1 *inhibitor = nullptr; +}; + +enum wl_iterator_result find_inhibitor(struct wl_resource *resource, void *data) +{ + auto *find = static_cast(data); + const char *name = wl_resource_get_class(resource); + if (!name || strcmp(name, "zwp_idle_inhibitor_v1") != 0) + return WL_ITERATOR_CONTINUE; + + find->inhibitor = static_cast( + wl_resource_get_user_data(resource)); + return WL_ITERATOR_STOP; +} + +struct wl_client *find_test_client_with_inhibitor(struct find_inhibitor_data *find) +{ + struct wl_client *client; + wl_client_for_each(client, wl_display_get_client_list(g_display)) { + pid_t pid = -1; + wl_client_get_credentials(client, &pid, nullptr, nullptr); + if (pid != getpid()) + continue; + + wl_client_for_each_resource(client, find_inhibitor, find); + if (find->inhibitor) + return client; + } + return nullptr; +} +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + auto *nativeServer = native_server(server); + Q_ASSERT(nativeServer); + g_display = nativeServer->handle(); + Q_ASSERT(g_display); +} + +void idle_inhibit_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = 0; + state->surface_mapped = 0; + + if (!g_display) + return; + + struct find_inhibitor_data find; + if (!find_test_client_with_inhibitor(&find)) + return; + if (!find.inhibitor || !find.inhibitor->surface) + return; + + state->valid = 1; + auto *surface = WSurface::fromHandle(find.inhibitor->surface); + state->surface_mapped = surface && surface->mapped(); +} diff --git a/tests/protocols/wayland-idle-inhibit-unstable-v1/wayland-idle-inhibit-unstable-v1.c b/tests/protocols/wayland-idle-inhibit-unstable-v1/wayland-idle-inhibit-unstable-v1.c new file mode 100644 index 0000000000..bc33555c4a --- /dev/null +++ b/tests/protocols/wayland-idle-inhibit-unstable-v1/wayland-idle-inhibit-unstable-v1.c @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end): the test verifies that creating a + * zwp_idle_inhibitor_v1 on a mapped surface creates the corresponding + * production wlr_idle_inhibitor_v1. + * + * Step 1: Create an idle inhibitor on a mapped toplevel surface. + * Step 2: Read back the production inhibitor and verify it references the + * mapped surface. + * Step 3: Destroy the inhibitor and verify the production resource is gone. + */ + +#include "wayland-idle-inhibit-unstable-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "idle-inhibit-unstable-v1-client-protocol.h" + +#include +#include + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("idle-inhibit: connect failed\n"); + return 1; + } + + /* Map a toplevel surface. */ + struct xdg_toplevel_client tc; + if (!xdg_toplevel_client_create_pending(&conn, &tc)) { + TEST_ERROR("idle-inhibit: create_pending failed\n"); + client_disconnect(&conn); + return 1; + } + if (!xdg_toplevel_client_complete_map(&conn, &tc)) { + TEST_ERROR("idle-inhibit: complete_map failed\n"); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + wl_display_roundtrip(conn.display); + + /* Step 1: Create an idle inhibitor on the mapped surface. */ + struct zwp_idle_inhibit_manager_v1 *inhibit_mgr = client_bind( + &conn, zwp_idle_inhibit_manager_v1_interface.name, &zwp_idle_inhibit_manager_v1_interface, zwp_idle_inhibit_manager_v1_interface.version); + if (inhibit_mgr == NULL) { + TEST_ERROR("idle-inhibit: failed to bind manager: %s\n", strerror(errno)); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + + struct zwp_idle_inhibitor_v1 *inhibitor = + zwp_idle_inhibit_manager_v1_create_inhibitor(inhibit_mgr, tc.surface); + if (inhibitor == NULL) { + TEST_ERROR("idle-inhibit: create_inhibitor returned NULL\n"); + zwp_idle_inhibit_manager_v1_destroy(inhibit_mgr); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + wl_display_roundtrip(conn.display); + + int failed = 0; + + /* Step 2: The production inhibitor must reference the mapped surface. */ + struct idle_inhibit_server_state state = { 0, 0 }; + if (!invoke_on_server_thread(idle_inhibit_read_server_state, &state) + || !state.valid || !state.surface_mapped) { + TEST_ERROR("idle-inhibit: no mapped production inhibitor\n"); + failed = 1; + } + + if (failed) { + zwp_idle_inhibitor_v1_destroy(inhibitor); + zwp_idle_inhibit_manager_v1_destroy(inhibit_mgr); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + + /* Step 3: Destroy inhibitor — the production resource must be gone. */ + zwp_idle_inhibitor_v1_destroy(inhibitor); + wl_display_roundtrip(conn.display); + memset(&state, 0, sizeof(state)); + if (!invoke_on_server_thread(idle_inhibit_read_server_state, &state) || state.valid) { + TEST_ERROR("idle-inhibit: production inhibitor remains after destroy\n"); + failed = 1; + } + + zwp_idle_inhibit_manager_v1_destroy(inhibit_mgr); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-idle-inhibit-unstable-v1/wayland-idle-inhibit-unstable-v1.h b/tests/protocols/wayland-idle-inhibit-unstable-v1/wayland-idle-inhibit-unstable-v1.h new file mode 100644 index 0000000000..ec8c0c71ad --- /dev/null +++ b/tests/protocols/wayland-idle-inhibit-unstable-v1/wayland-idle-inhibit-unstable-v1.h @@ -0,0 +1,19 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +struct idle_inhibit_server_state { + int valid; + int surface_mapped; +}; + +void idle_inhibit_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/wayland-keyboard-shortcuts-inhibit-unstable-v1/CMakeLists.txt b/tests/protocols/wayland-keyboard-shortcuts-inhibit-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..815bf4a6b9 --- /dev/null +++ b/tests/protocols/wayland-keyboard-shortcuts-inhibit-unstable-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_keyboard_shortcuts_inhibit_unstable_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/unstable/keyboard-shortcuts-inhibit/keyboard-shortcuts-inhibit-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-keyboard-shortcuts-inhibit-unstable-v1.c" +) diff --git a/tests/protocols/wayland-keyboard-shortcuts-inhibit-unstable-v1/README.md b/tests/protocols/wayland-keyboard-shortcuts-inhibit-unstable-v1/README.md new file mode 100644 index 0000000000..ea624cb9f9 --- /dev/null +++ b/tests/protocols/wayland-keyboard-shortcuts-inhibit-unstable-v1/README.md @@ -0,0 +1,6 @@ +# keyboard-shortcuts-inhibit-unstable-v1 + +覆盖等级:I / P。 + +测试映射真实 xdg toplevel 并将其设为 seat 焦点,随后请求 inhibitor 并断言收到 +`active`。失焦后的 compositor policy、`inactive` 事件与真实快捷键分发行为尚未覆盖。 diff --git a/tests/protocols/wayland-keyboard-shortcuts-inhibit-unstable-v1/setup.cpp b/tests/protocols/wayland-keyboard-shortcuts-inhibit-unstable-v1/setup.cpp new file mode 100644 index 0000000000..e7b73b457f --- /dev/null +++ b/tests/protocols/wayland-keyboard-shortcuts-inhibit-unstable-v1/setup.cpp @@ -0,0 +1,28 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "core/shellhandler.h" +#include "core/waylandserver.h" +#include "server-bridge.h" +#include "surface/surfacewrapper.h" + +#include + +namespace { +SurfaceWrapper *g_toplevel = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + QObject::connect(server->shellHandler(), &ShellHandler::surfaceWrapperAdded, server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() == SurfaceWrapper::Type::XdgToplevel) + g_toplevel = wrapper; + }); +} + +extern "C" void keyboard_shortcuts_inhibit_focus(void *) +{ + if (g_toplevel) + WaylandServer::instance()->activateSurface(g_toplevel, Qt::ActiveWindowFocusReason); +} diff --git a/tests/protocols/wayland-keyboard-shortcuts-inhibit-unstable-v1/wayland-keyboard-shortcuts-inhibit-unstable-v1.c b/tests/protocols/wayland-keyboard-shortcuts-inhibit-unstable-v1/wayland-keyboard-shortcuts-inhibit-unstable-v1.c new file mode 100644 index 0000000000..1062ee01bc --- /dev/null +++ b/tests/protocols/wayland-keyboard-shortcuts-inhibit-unstable-v1/wayland-keyboard-shortcuts-inhibit-unstable-v1.c @@ -0,0 +1,49 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "keyboard-shortcuts-inhibit-unstable-v1-client-protocol.h" + +#include + +extern void keyboard_shortcuts_inhibit_focus(void *); + +struct events { unsigned active; unsigned inactive; }; +static void active(void *data, struct zwp_keyboard_shortcuts_inhibitor_v1 *inhibitor) +{ (void)inhibitor; ((struct events *)data)->active++; } +static void inactive(void *data, struct zwp_keyboard_shortcuts_inhibitor_v1 *inhibitor) +{ (void)inhibitor; ((struct events *)data)->inactive++; } +static const struct zwp_keyboard_shortcuts_inhibitor_v1_listener listener = { active, inactive }; + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + struct xdg_toplevel_client toplevel = { 0 }; + struct events events = { 0 }; + if (!client_connect(&connection, socket_name) + || !xdg_toplevel_client_create(&connection, &toplevel) + || !invoke_on_server_thread(keyboard_shortcuts_inhibit_focus, NULL)) + return 1; + struct wl_seat *seat = client_bind(&connection, "wl_seat", &wl_seat_interface, 1); + struct zwp_keyboard_shortcuts_inhibit_manager_v1 *manager = client_bind(&connection, + "zwp_keyboard_shortcuts_inhibit_manager_v1", + &zwp_keyboard_shortcuts_inhibit_manager_v1_interface, 1); + if (!seat || !manager) + return 1; + struct zwp_keyboard_shortcuts_inhibitor_v1 *inhibitor = + zwp_keyboard_shortcuts_inhibit_manager_v1_inhibit_shortcuts(manager, toplevel.surface, seat); + if (!inhibitor) + return 1; + zwp_keyboard_shortcuts_inhibitor_v1_add_listener(inhibitor, &listener, &events); + if (wl_display_roundtrip(connection.display) < 0 || events.active != 1) { + fprintf(stderr, "keyboard-shortcuts-inhibit: active event missing\n"); + return 1; + } + zwp_keyboard_shortcuts_inhibitor_v1_destroy(inhibitor); + zwp_keyboard_shortcuts_inhibit_manager_v1_destroy(manager); + wl_seat_destroy(seat); + xdg_toplevel_client_destroy(&toplevel); + client_disconnect(&connection); + return 0; +} diff --git a/tests/protocols/wayland-pointer-constraints-unstable-v1/CMakeLists.txt b/tests/protocols/wayland-pointer-constraints-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..4fc7db977d --- /dev/null +++ b/tests/protocols/wayland-pointer-constraints-unstable-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_pointer_constraints_unstable_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/unstable/pointer-constraints/pointer-constraints-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-pointer-constraints-unstable-v1.c" +) diff --git a/tests/protocols/wayland-pointer-constraints-unstable-v1/README.md b/tests/protocols/wayland-pointer-constraints-unstable-v1/README.md new file mode 100644 index 0000000000..686fd78ed9 --- /dev/null +++ b/tests/protocols/wayland-pointer-constraints-unstable-v1/README.md @@ -0,0 +1,28 @@ +# `wayland-pointer-constraints-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`zwp_pointer_constraints_v1` / `zwp_locked_pointer_v1` / `zwp_confined_pointer_v1`(version 1) +- 测试源码:`tests/protocols/wayland-pointer-constraints-unstable-v1/` +- Fixture:headless output fixture + 映射 xdg-toplevel + setup 显式声明 seat 指针能力 +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 声明能力 | setup 中 `WInputDevice::Type::Pointer` + `attachInputDevice` | 客户端 `capabilities` 事件含指针位 | P | +| 绑定全局 | 绑定 `zwp_pointer_constraints_v1` | 资源创建成功 | P | +| 创建约束 | `lock_pointer(surface, pointer)` | 返回非 NULL `zwp_locked_pointer_v1` | P | +| **生产回读** | — | 回读真实 `wlr_pointer_constraint_v1::type` == Locked(0) | **E** | + +## 生产结果 + +测试观察 Treeland 通过 `WPointerConstraintsV1` 提供的指针约束服务。 +在真实 `wl_pointer` 上创建 locked 指针约束后,setup 通过 +`WPointerConstraintsV1::newConstraint` Qt 信号捕获 `wlr_pointer_constraint_v1*`, +回读其 `type` 字段断言为 Locked,证明约束创建到达生产指针约束管道。 + +## 已知边界 / 下一项结果 + +仅验证 Locked 类型;未验证 Confined 类型与 `region` / `cursor_hint` 设置。 diff --git a/tests/protocols/wayland-pointer-constraints-unstable-v1/setup.cpp b/tests/protocols/wayland-pointer-constraints-unstable-v1/setup.cpp new file mode 100644 index 0000000000..fba8f7bbdc --- /dev/null +++ b/tests/protocols/wayland-pointer-constraints-unstable-v1/setup.cpp @@ -0,0 +1,46 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-pointer-constraints-unstable-v1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +WPointerConstraintsV1 *g_mgr = nullptr; + +// Captured constraint from newConstraint signal +wlr_pointer_constraint_v1 *g_constraint = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + attach_test_pointer_device(server); + + g_mgr = find_server_interface(server); + if (g_mgr) { + QObject::connect(g_mgr, &WPointerConstraintsV1::newConstraint, + server, [](wlr_pointer_constraint_v1 *constraint) { + g_constraint = constraint; + }); + } +} + +void pointer_constraints_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = 0; + state->constraint_type = -1; + + if (!g_constraint) + return; + + state->valid = 1; + state->constraint_type = static_cast(g_constraint->type); +} diff --git a/tests/protocols/wayland-pointer-constraints-unstable-v1/wayland-pointer-constraints-unstable-v1.c b/tests/protocols/wayland-pointer-constraints-unstable-v1/wayland-pointer-constraints-unstable-v1.c new file mode 100644 index 0000000000..a1cca2d2ba --- /dev/null +++ b/tests/protocols/wayland-pointer-constraints-unstable-v1/wayland-pointer-constraints-unstable-v1.c @@ -0,0 +1,129 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end): the client obtains a wl_pointer from the + * pointer-capable seat, creates a wl_surface, and requests a locked pointer + * constraint. The test then reads back the production WPointerConstraintsV1's + * captured constraint type via the newConstraint signal, verifying the type is + * Locked, proving the lock_pointer request reached the real compositor + * constraint pipeline. + */ + +#include "wayland-pointer-constraints-unstable-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "pointer-constraints-unstable-v1-client-protocol.h" + +#include +#include + +static int g_locked_unlocked = 0; + +static void locked_unlocked(void *data, struct zwp_locked_pointer_v1 *locked) { + (void)locked; + *(int *)data = 1; +} + +static const struct zwp_locked_pointer_v1_listener locked_listener = { + .unlocked = locked_unlocked, +}; + + +static int read_server(struct pointer_constraints_server_state *state) { + return TEST_READ_SERVER(pointer_constraints_read_server_state, state, + "pointer-constraints: failed to read server state"); +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("pointer-constraints: connect failed\n"); + return 1; + } + + struct client_pointer_seat pointer_seat = { 0 }; + if (!client_bind_pointer_seat(&conn, wl_seat_interface.version, &pointer_seat)) { + TEST_ERROR("pointer-constraints: no pointer-capable wl_seat\n"); + client_disconnect(&conn); + return 1; + } + struct wl_seat *seat = pointer_seat.seat; + struct wl_pointer *pointer = pointer_seat.pointer; + + struct wl_compositor *compositor = + client_bind(&conn, wl_compositor_interface.name, &wl_compositor_interface, wl_compositor_interface.version); + if (compositor == NULL) { + TEST_ERROR("pointer-constraints: no wl_compositor global\n"); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + struct wl_surface *surface = wl_compositor_create_surface(compositor); + if (surface == NULL) { + TEST_ERROR("pointer-constraints: create_surface returned NULL\n"); + wl_compositor_destroy(compositor); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + wl_surface_commit(surface); + + struct zwp_pointer_constraints_v1 *manager = + client_bind(&conn, zwp_pointer_constraints_v1_interface.name, &zwp_pointer_constraints_v1_interface, zwp_pointer_constraints_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("pointer-constraints: failed to bind manager: %s\n", strerror(errno)); + wl_surface_destroy(surface); + wl_compositor_destroy(compositor); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + struct zwp_locked_pointer_v1 *locked = zwp_pointer_constraints_v1_lock_pointer( + manager, surface, pointer, NULL, ZWP_POINTER_CONSTRAINTS_V1_LIFETIME_ONESHOT); + if (locked == NULL) { + TEST_ERROR("pointer-constraints: lock_pointer returned NULL\n"); + zwp_pointer_constraints_v1_destroy(manager); + wl_surface_destroy(surface); + wl_compositor_destroy(compositor); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + zwp_locked_pointer_v1_add_listener(locked, &locked_listener, &g_locked_unlocked); + wl_display_roundtrip(conn.display); + + int failed = 0; + if (g_locked_unlocked) { + TEST_ERROR("pointer-constraints: locked pointer was immediately unlocked\n"); + failed = 1; + } + + /* E-level: the production constraint must have type Locked (0). */ + struct pointer_constraints_server_state srv; + if (read_server(&srv)) { + failed = 1; + } else if (!srv.valid) { + TEST_ERROR("pointer-constraints: no constraint captured\n"); + failed = 1; + } else if (srv.constraint_type != POINTER_CONSTRAINT_TYPE_LOCKED) { + TEST_ERROR("pointer-constraints: expected type Locked(0), got %d\n", + srv.constraint_type); + failed = 1; + } + + zwp_locked_pointer_v1_destroy(locked); + zwp_pointer_constraints_v1_destroy(manager); + wl_surface_destroy(surface); + wl_compositor_destroy(compositor); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-pointer-constraints-unstable-v1/wayland-pointer-constraints-unstable-v1.h b/tests/protocols/wayland-pointer-constraints-unstable-v1/wayland-pointer-constraints-unstable-v1.h new file mode 100644 index 0000000000..63fbbaf8bf --- /dev/null +++ b/tests/protocols/wayland-pointer-constraints-unstable-v1/wayland-pointer-constraints-unstable-v1.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_POINTER_CONSTRAINTS_TEST_H +#define WAYLAND_POINTER_CONSTRAINTS_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +enum { POINTER_CONSTRAINT_TYPE_LOCKED = 0, POINTER_CONSTRAINT_TYPE_CONFINED = 1 }; + +/* + * E-level readback: the production WPointerConstraintsV1 resolves the active + * constraint for the client's surface+seat via constraintForSurface(). The + * constraint type must be Locked (0), proving the lock_pointer request reached + * the real compositor constraint pipeline. + * + * wlr_pointer_constraint_v1_type: 0=Locked, 1=Confined + * (enum wlr_pointer_constraint_v1_type maps from zwp enum) + */ +struct pointer_constraints_server_state { + int valid; /* a constraint was found */ + int constraint_type; /* 0=Locked, 1=Confined */ +}; + +void pointer_constraints_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_POINTER_CONSTRAINTS_TEST_H */ diff --git a/tests/protocols/wayland-pointer-gestures-unstable-v1/CMakeLists.txt b/tests/protocols/wayland-pointer-gestures-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..a8d1c7a934 --- /dev/null +++ b/tests/protocols/wayland-pointer-gestures-unstable-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_pointer_gestures_unstable_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/unstable/pointer-gestures/pointer-gestures-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-pointer-gestures-unstable-v1.c" +) diff --git a/tests/protocols/wayland-pointer-gestures-unstable-v1/README.md b/tests/protocols/wayland-pointer-gestures-unstable-v1/README.md new file mode 100644 index 0000000000..8c2dc860c1 --- /dev/null +++ b/tests/protocols/wayland-pointer-gestures-unstable-v1/README.md @@ -0,0 +1,34 @@ +# `wayland-pointer-gestures-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`zwp_pointer_gestures_v1` / `zwp_pointer_gesture_swipe_v1` / `zwp_pointer_gesture_pinch_v1`(version 3) +- 测试源码:`tests/protocols/wayland-pointer-gestures-unstable-v1/` +- Fixture:headless output fixture + setup 显式声明 seat 指针能力 + client_created 监听器 +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 声明能力 | setup 中 `wlr_seat_set_capabilities(POINTER)` | 客户端 `capabilities` 事件含指针位 | P | +| 绑定全局 | 绑定 `zwp_pointer_gestures_v1`(v3) | 资源创建成功 | P | +| 注册手势 | `get_swipe_gestures` + `get_pinch_gestures` | 均返回非 NULL 资源 | P | +| 生产回读 | 创建 swipe + pinch 资源后回读 | 真实 `wlr_pointer_gestures_v1::swipes` 和 `::pinches` 列表长度均 ≥ 1 | E | + +## 生产结果 + +测试观察 Treeland 通过 `wlr_pointer_gestures_v1_create` 提供的手势服务。 +在真实 `wl_pointer` 上成功创建 swipe + pinch 手势资源后,通过 +`wl_client_get_credentials` 以与协议测试进程相同的 PID 缩小范围,并通过其绑定的 +`zwp_pointer_gestures_v1` resource 精确定位测试 client;再读取该 resource 的 +`user_data`(即真实的 `wlr_pointer_gestures_v1*` 句柄)。回读时仅统计该 client +拥有的 `swipes` 和 `pinches` 资源,避免同进程内部 client、Xwayland 或其他 client 的资源造成误报。 + +该句柄存储在 `WSeatPrivate::gesture`(无公共访问路径),测试通过 +`wl_client_for_each_resource` 从客户端绑定资源中提取,而非直接访问私有成员。 + +## 已知边界 / 下一项结果 + +未验证注入手势事件后 `begin`/`update`/`end` 事件负载(需指针焦点 + WGestureEvent 注入), +也未验证 v3 `get_hold_gestures`。 diff --git a/tests/protocols/wayland-pointer-gestures-unstable-v1/setup.cpp b/tests/protocols/wayland-pointer-gestures-unstable-v1/setup.cpp new file mode 100644 index 0000000000..7841c24d8a --- /dev/null +++ b/tests/protocols/wayland-pointer-gestures-unstable-v1/setup.cpp @@ -0,0 +1,111 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-pointer-gestures-unstable-v1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" + +#include +#include + +#include + +#include + +#include +#include +#include + +namespace { + +/* The test client runs in the protocol-test process; Xwayland does not. */ +struct wl_display *g_display = nullptr; + +/* Callback data for wl_client_for_each_resource. */ +struct find_gestures_data { + struct wlr_pointer_gestures_v1 *gestures; +}; + +static enum wl_iterator_result find_gestures_cb(struct wl_resource *resource, + void *user_data) +{ + auto *data = static_cast(user_data); + const char *name = wl_resource_get_class(resource); + if (name && strcmp(name, "zwp_pointer_gestures_v1") == 0) { + data->gestures = static_cast( + wl_resource_get_user_data(resource)); + return WL_ITERATOR_STOP; + } + return WL_ITERATOR_CONTINUE; +} + +static struct wl_client *find_test_client_with_gestures( + struct find_gestures_data *find) +{ + struct wl_client *client; + wl_client_for_each(client, wl_display_get_client_list(g_display)) { + pid_t pid = -1; + wl_client_get_credentials(client, &pid, nullptr, nullptr); + if (pid != getpid()) + continue; + + wl_client_for_each_resource(client, find_gestures_cb, find); + if (find->gestures) + return client; + } + return nullptr; +} + +static int count_resources_for_client(struct wl_list *resources, + struct wl_client *client) +{ + int count = 0; + struct wl_resource *resource; + wl_resource_for_each(resource, resources) { + if (wl_resource_get_client(resource) == client) + ++count; + } + return count; +} + +} // namespace + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + attach_test_pointer_device(server); + + auto *nativeServer = native_server(server); + Q_ASSERT(nativeServer); + g_display = nativeServer->handle(); + Q_ASSERT(g_display); +} + +void pointer_gestures_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = 0; + state->swipes = 0; + state->pinches = 0; + + if (!g_display) + return; + + // Locate the test client's wl_client by credentials and by the manager + // resource it bound, rather than by connection order. Multiple internal + // clients share the protocol-test PID. When the test client binds + // zwp_pointer_gestures_v1, the resource's user_data is the + // wlr_pointer_gestures_v1* (set by pointer_gestures_v1_bind in wlroots). + struct find_gestures_data find = {}; + auto *test_client = find_test_client_with_gestures(&find); + if (!test_client) + return; + + state->valid = 1; + + // Count only resources owned by this test client. wlroots stores all + // clients' gestures in shared lists, so global list lengths could pass + // because an unrelated client (for example Xwayland) created gestures. + state->swipes = count_resources_for_client(&find.gestures->swipes, test_client); + state->pinches = count_resources_for_client(&find.gestures->pinches, test_client); +} diff --git a/tests/protocols/wayland-pointer-gestures-unstable-v1/wayland-pointer-gestures-unstable-v1.c b/tests/protocols/wayland-pointer-gestures-unstable-v1/wayland-pointer-gestures-unstable-v1.c new file mode 100644 index 0000000000..87ca366df6 --- /dev/null +++ b/tests/protocols/wayland-pointer-gestures-unstable-v1/wayland-pointer-gestures-unstable-v1.c @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end): the client obtains a wl_pointer from the + * pointer-capable seat, binds zwp_pointer_gestures_v1, and creates swipe + + * pinch gesture resources. The test then reads back the real production + * wlr_pointer_gestures_v1::swipes and ::pinches wl_list lengths, verifying + * both are non-zero, proving the gesture resources were registered in the + * real compositor's gesture manager rather than merely surviving without a + * protocol error. + */ + +#include "wayland-pointer-gestures-unstable-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "pointer-gestures-unstable-v1-client-protocol.h" + +#include +#include + +static int read_server(struct pointer_gestures_server_state *state) { + return TEST_READ_SERVER(pointer_gestures_read_server_state, state, + "pointer-gestures: failed to read server state"); +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("pointer-gestures: connect failed\n"); + return 1; + } + + struct client_pointer_seat pointer_seat = { 0 }; + if (!client_bind_pointer_seat(&conn, wl_seat_interface.version, &pointer_seat)) { + TEST_ERROR("pointer-gestures: no pointer-capable wl_seat\n"); + client_disconnect(&conn); + return 1; + } + struct wl_seat *seat = pointer_seat.seat; + struct wl_pointer *pointer = pointer_seat.pointer; + + struct zwp_pointer_gestures_v1 *manager = + client_bind(&conn, zwp_pointer_gestures_v1_interface.name, &zwp_pointer_gestures_v1_interface, zwp_pointer_gestures_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("pointer-gestures: failed to bind manager: %s\n", strerror(errno)); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + struct zwp_pointer_gesture_swipe_v1 *swipe = + zwp_pointer_gestures_v1_get_swipe_gesture(manager, pointer); + if (swipe == NULL) { + TEST_ERROR("pointer-gestures: get_swipe_gestures returned NULL\n"); + zwp_pointer_gestures_v1_destroy(manager); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + struct zwp_pointer_gesture_pinch_v1 *pinch = + zwp_pointer_gestures_v1_get_pinch_gesture(manager, pointer); + if (pinch == NULL) { + TEST_ERROR("pointer-gestures: get_pinch_gestures returned NULL\n"); + zwp_pointer_gesture_swipe_v1_destroy(swipe); + zwp_pointer_gestures_v1_destroy(manager); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + wl_display_roundtrip(conn.display); + + int failed = 0; + + /* E-level: the production wlr_pointer_gestures_v1 must have non-empty + * swipes and pinches lists, proving the gesture resources were registered + * in the real compositor gesture manager. */ + struct pointer_gestures_server_state srv; + if (read_server(&srv)) { + failed = 1; + } else if (!srv.valid) { + TEST_ERROR("pointer-gestures: wlr_pointer_gestures_v1 handle not found\n"); + failed = 1; + } else if (srv.swipes < 1) { + TEST_ERROR("pointer-gestures: no swipe gesture resources in production\n"); + failed = 1; + } else if (srv.pinches < 1) { + TEST_ERROR("pointer-gestures: no pinch gesture resources in production\n"); + failed = 1; + } + + zwp_pointer_gesture_swipe_v1_destroy(swipe); + zwp_pointer_gesture_pinch_v1_destroy(pinch); + zwp_pointer_gestures_v1_destroy(manager); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-pointer-gestures-unstable-v1/wayland-pointer-gestures-unstable-v1.h b/tests/protocols/wayland-pointer-gestures-unstable-v1/wayland-pointer-gestures-unstable-v1.h new file mode 100644 index 0000000000..06a827cbca --- /dev/null +++ b/tests/protocols/wayland-pointer-gestures-unstable-v1/wayland-pointer-gestures-unstable-v1.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_POINTER_GESTURES_TEST_H +#define WAYLAND_POINTER_GESTURES_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * E-level readback: the client creates zwp_pointer_gesture_swipe_v1 and + * zwp_pointer_gesture_pinch_v1 resources on a real wl_pointer. When the + * client binds zwp_pointer_gestures_v1, the resource's user_data is the + * real wlr_pointer_gestures_v1 handle. The test locates its client by PID, + * then counts only that client's resources in the real + * wlr_pointer_gestures_v1::swipes and ::pinches lists. This proves the + * gesture resources were registered in the real compositor's gesture manager + * rather than merely surviving without a protocol error. + */ +struct pointer_gestures_server_state { + int valid; /* wlr_pointer_gestures_v1 handle found */ + int swipes; /* number of swipe gesture resources in production */ + int pinches; /* number of pinch gesture resources in production */ +}; + +void pointer_gestures_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_POINTER_GESTURES_TEST_H */ diff --git a/tests/protocols/wayland-primary-selection-unstable-v1/CMakeLists.txt b/tests/protocols/wayland-primary-selection-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..a7c9bc0871 --- /dev/null +++ b/tests/protocols/wayland-primary-selection-unstable-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_primary_selection_unstable_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/unstable/primary-selection/primary-selection-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-primary-selection-unstable-v1.c" +) diff --git a/tests/protocols/wayland-primary-selection-unstable-v1/README.md b/tests/protocols/wayland-primary-selection-unstable-v1/README.md new file mode 100644 index 0000000000..11939b4491 --- /dev/null +++ b/tests/protocols/wayland-primary-selection-unstable-v1/README.md @@ -0,0 +1,28 @@ +# `wayland-primary-selection-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`zwp_primary_selection_device_manager_v1` / `zwp_primary_selection_device_v1`(version 1) +- 测试源码:`tests/protocols/wayland-primary-selection-unstable-v1/` +- Fixture:headless output fixture +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `zwp_primary_selection_device_manager_v1` | 资源创建成功 | P | +| 创建设备 | `get_device(seat)` | 返回非 NULL `zwp_primary_selection_device_v1` | P | +| 创建 source | `create_source` + `offer("text/plain")` | 返回非 NULL `zwp_primary_selection_source_v1` | P | +| 设置选区 | `set_selection(device, source, 0)` | 无协议错误 | P | +| **生产回读** | — | 回读真实 `wlr_seat::primary_selection_source` 非空 | **E** | + +## 生产结果 + +测试观察 Treeland 通过 `wlr_primary_selection_v1_device_manager_create` 提供的主选区服务。 +客户端创建 source 并 `set_selection` 后,通过 `invoke_on_server_thread` 回读真实 +`wlr_seat::primary_selection_source` 字段,断言其非空,证明主选区请求到达真实 seat 管道。 + +## 已知边界 / 下一项结果 + +仅验证 `primary_selection_source` 非空;未验证 source 的 mime type 内容与 `selection` 事件回传。 diff --git a/tests/protocols/wayland-primary-selection-unstable-v1/setup.cpp b/tests/protocols/wayland-primary-selection-unstable-v1/setup.cpp new file mode 100644 index 0000000000..e74baf0eb9 --- /dev/null +++ b/tests/protocols/wayland-primary-selection-unstable-v1/setup.cpp @@ -0,0 +1,54 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-primary-selection-unstable-v1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include +#include +#include + +#include + +extern "C" { +#include +} + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +wlr_seat *g_seat = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + // Attach a keyboard device so the seat advertises keyboard capability. + // When a toplevel is mapped, Treeland gives it keyboard focus, which + // sends a wl_keyboard::enter event with a valid serial. The client + // captures this serial and uses it for set_primary_selection. + auto *seat = server->seat(); + if (seat) { + g_seat = seat->handle(); + auto *keyboard = (struct wlr_keyboard *)calloc(1, sizeof(struct wlr_keyboard)); + wlr_keyboard_init(keyboard, nullptr, "test-keyboard"); + auto *device = new WInputDevice(&keyboard->base, true); + seat->attachInputDevice(device); + } +} + +void primary_selection_read_server_state(void *data) +{ + auto *state = + static_cast(data); + state->valid = 0; + state->has_source = 0; + + if (!g_seat) + return; + + state->valid = 1; + state->has_source = (g_seat->primary_selection_source != nullptr) ? 1 : 0; +} diff --git a/tests/protocols/wayland-primary-selection-unstable-v1/wayland-primary-selection-unstable-v1.c b/tests/protocols/wayland-primary-selection-unstable-v1/wayland-primary-selection-unstable-v1.c new file mode 100644 index 0000000000..6a36dc5e0d --- /dev/null +++ b/tests/protocols/wayland-primary-selection-unstable-v1/wayland-primary-selection-unstable-v1.c @@ -0,0 +1,205 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end): the client creates a primary selection source + * with a mime type, sets it on the primary selection device, and the test + * reads back the production wlr_seat's primary_selection_source field, + * verifying it is non-NULL, proving the primary selection request reached the + * real compositor seat pipeline. + * + * The wlroots primary-selection-v1 implementation validates the serial via + * wlr_seat_client_validate_event_serial. To obtain a valid serial, the test + * maps a toplevel, which triggers keyboard focus → wl_keyboard::enter with a + * server-assigned serial. That serial is then used in set_selection. + */ + +#include "wayland-primary-selection-unstable-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "primary-selection-unstable-v1-client-protocol.h" + +#include +#include +#include + +/* Keyboard listener to capture the enter serial. */ +static uint32_t g_enter_serial; +static void kb_keymap(void *data, struct wl_keyboard *kb, uint32_t fmt, int32_t fd, uint32_t size) { + (void)data; + (void)kb; + (void)fmt; + close(fd); + (void)size; +} +static void kb_enter(void *data, struct wl_keyboard *kb, uint32_t serial, struct wl_surface *surf, + struct wl_array *keys) { + (void)data; + (void)kb; + (void)surf; + (void)keys; + g_enter_serial = serial; +} +static void kb_leave(void *data, struct wl_keyboard *kb, uint32_t serial, struct wl_surface *surf) { + (void)data; + (void)kb; + (void)serial; + (void)surf; +} +static void kb_key(void *data, struct wl_keyboard *kb, uint32_t serial, uint32_t time, uint32_t key, + uint32_t state) { + (void)data; + (void)kb; + (void)serial; + (void)time; + (void)key; + (void)state; +} +static void kb_modifiers(void *data, struct wl_keyboard *kb, uint32_t serial, + uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, uint32_t group) { + (void)data; + (void)kb; + (void)serial; + (void)mods_depressed; + (void)mods_latched; + (void)mods_locked; + (void)group; +} +static void kb_repeat_info(void *data, struct wl_keyboard *kb, int32_t rate, int32_t delay) { + (void)data; + (void)kb; + (void)rate; + (void)delay; +} +static const struct wl_keyboard_listener kb_listener = { + .keymap = kb_keymap, + .enter = kb_enter, + .leave = kb_leave, + .key = kb_key, + .modifiers = kb_modifiers, + .repeat_info = kb_repeat_info, +}; + +static int read_server(struct primary_selection_server_state *state) { + return TEST_READ_SERVER(primary_selection_read_server_state, state, + "primary-selection: failed to read server state"); +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("primary-selection: connect failed\n"); + return 1; + } + + struct client_seat client_seat = { 0 }; + if (!client_bind_seat(&conn, wl_seat_interface.version, &client_seat)) { + TEST_ERROR("primary-selection: no wl_seat global\n"); + client_disconnect(&conn); + return 1; + } + struct wl_seat *seat = client_seat.seat; + if (!(client_seat.capabilities & WL_SEAT_CAPABILITY_KEYBOARD)) { + TEST_ERROR("primary-selection: wl_seat has no keyboard capability\n"); + client_seat_destroy(&client_seat); + client_disconnect(&conn); + return 1; + } + + /* Get a keyboard to capture the enter serial. */ + struct wl_keyboard *kb = NULL; + kb = wl_seat_get_keyboard(seat); + if (kb != NULL) { + wl_keyboard_add_listener(kb, &kb_listener, NULL); + } + + /* Map a toplevel so Treeland gives it keyboard focus → serial. */ + struct xdg_toplevel_client tc; + if (!xdg_toplevel_client_create(&conn, &tc)) { + TEST_ERROR("primary-selection: toplevel create failed\n"); + if (kb != NULL) + wl_keyboard_destroy(kb); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + wl_display_roundtrip(conn.display); + + if (g_enter_serial == 0) { + TEST_ERROR("primary-selection: no keyboard enter serial\n"); + xdg_toplevel_client_destroy(&tc); + if (kb != NULL) + wl_keyboard_destroy(kb); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + struct zwp_primary_selection_device_manager_v1 *manager = + client_bind(&conn, zwp_primary_selection_device_manager_v1_interface.name, &zwp_primary_selection_device_manager_v1_interface, zwp_primary_selection_device_manager_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("primary-selection: failed to bind manager: %s\n", strerror(errno)); + xdg_toplevel_client_destroy(&tc); + if (kb != NULL) + wl_keyboard_destroy(kb); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + struct zwp_primary_selection_device_v1 *device = + zwp_primary_selection_device_manager_v1_get_device(manager, seat); + if (device == NULL) { + TEST_ERROR("primary-selection: get_device returned NULL\n"); + zwp_primary_selection_device_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&tc); + if (kb != NULL) + wl_keyboard_destroy(kb); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + struct zwp_primary_selection_source_v1 *source = + zwp_primary_selection_device_manager_v1_create_source(manager); + if (source == NULL) { + TEST_ERROR("primary-selection: create_source returned NULL\n"); + zwp_primary_selection_device_v1_destroy(device); + zwp_primary_selection_device_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&tc); + if (kb != NULL) + wl_keyboard_destroy(kb); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + zwp_primary_selection_source_v1_offer(source, "text/plain"); + zwp_primary_selection_device_v1_set_selection(device, source, g_enter_serial); + + wl_display_roundtrip(conn.display); + + int failed = 0; + + /* E-level: the production seat must have primary_selection_source set. */ + struct primary_selection_server_state srv; + if (read_server(&srv)) { + failed = 1; + } else if (!srv.valid) { + TEST_ERROR("primary-selection: seat not found\n"); + failed = 1; + } else if (!srv.has_source) { + TEST_ERROR("primary-selection: primary_selection_source is NULL\n"); + failed = 1; + } + + zwp_primary_selection_source_v1_destroy(source); + zwp_primary_selection_device_v1_destroy(device); + zwp_primary_selection_device_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&tc); + if (kb != NULL) + wl_keyboard_destroy(kb); + wl_seat_destroy(seat); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-primary-selection-unstable-v1/wayland-primary-selection-unstable-v1.h b/tests/protocols/wayland-primary-selection-unstable-v1/wayland-primary-selection-unstable-v1.h new file mode 100644 index 0000000000..f46b995606 --- /dev/null +++ b/tests/protocols/wayland-primary-selection-unstable-v1/wayland-primary-selection-unstable-v1.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_PRIMARY_SELECTION_TEST_H +#define WAYLAND_PRIMARY_SELECTION_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * E-level readback: the production wlr_seat's primary_selection_source field + * must be non-NULL after the client sets a primary selection source. This + * proves the primary selection request reached the real compositor seat + * pipeline rather than merely surviving without a protocol error. + */ +struct primary_selection_server_state { + int valid; /* seat was found */ + int has_source; /* primary_selection_source != NULL */ +}; + +void primary_selection_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_PRIMARY_SELECTION_TEST_H */ diff --git a/tests/protocols/wayland-relative-pointer-unstable-v1/CMakeLists.txt b/tests/protocols/wayland-relative-pointer-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..a4494f892c --- /dev/null +++ b/tests/protocols/wayland-relative-pointer-unstable-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_relative_pointer_unstable_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/unstable/relative-pointer/relative-pointer-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-relative-pointer-unstable-v1.c" +) diff --git a/tests/protocols/wayland-relative-pointer-unstable-v1/README.md b/tests/protocols/wayland-relative-pointer-unstable-v1/README.md new file mode 100644 index 0000000000..084894cef0 --- /dev/null +++ b/tests/protocols/wayland-relative-pointer-unstable-v1/README.md @@ -0,0 +1,28 @@ +# `wayland-relative-pointer-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`zwp_relative_pointer_manager_v1` / `zwp_relative_pointer_v1`(version 1) +- 测试源码:`tests/protocols/wayland-relative-pointer-unstable-v1/` +- Fixture:headless output fixture + 映射 xdg-toplevel + setup 显式声明 seat 指针能力 +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 声明能力 | setup 中 `WInputDevice::Type::Pointer` + `attachInputDevice` | 客户端 `capabilities` 事件含指针位 | P | +| 绑定全局 | 绑定 `zwp_relative_pointer_manager_v1` | 资源创建成功 | P | +| 创建 relative pointer | `get_relative_pointer(wl_pointer)` | 返回非 NULL `zwp_relative_pointer_v1` | P | +| **生产回读** | — | 回读真实 `wlr_relative_pointer_manager_v1::relative_pointers` 列表 `wl_list_length` >= 1 | **E** | + +## 生产结果 + +测试观察 Treeland 通过 `WRelativePointerManagerV1` 提供的相对指针服务。 +在真实 `wl_pointer` 上创建 relative pointer 后,通过 `invoke_on_server_thread` 回读真实 +`wlr_relative_pointer_manager_v1::relative_pointers` 列表长度,断言 >= 1, +证明 relative pointer 资源被注册到生产管理器列表中。 + +## 已知边界 / 下一项结果 + +仅验证列表非空;未验证 `relative_motion` 事件 payload(需要真实指针运动)。 diff --git a/tests/protocols/wayland-relative-pointer-unstable-v1/setup.cpp b/tests/protocols/wayland-relative-pointer-unstable-v1/setup.cpp new file mode 100644 index 0000000000..9a463c2304 --- /dev/null +++ b/tests/protocols/wayland-relative-pointer-unstable-v1/setup.cpp @@ -0,0 +1,37 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-relative-pointer-unstable-v1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +WRelativePointerManagerV1 *g_mgr = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + attach_test_pointer_device(server); + + g_mgr = find_server_interface(server); +} + +void relative_pointer_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = 0; + state->count = 0; + + if (!g_mgr || !g_mgr->handle()) + return; + + state->valid = 1; + state->count = wl_list_length(&g_mgr->handle()->relative_pointers); +} diff --git a/tests/protocols/wayland-relative-pointer-unstable-v1/wayland-relative-pointer-unstable-v1.c b/tests/protocols/wayland-relative-pointer-unstable-v1/wayland-relative-pointer-unstable-v1.c new file mode 100644 index 0000000000..90b2130bc2 --- /dev/null +++ b/tests/protocols/wayland-relative-pointer-unstable-v1/wayland-relative-pointer-unstable-v1.c @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end): the client obtains a wl_pointer from the + * pointer-capable seat and creates a zwp_relative_pointer_v1. The test then + * reads back the production WRelativePointerManagerV1's relative_pointers list + * length, verifying it is at least 1, proving the relative pointer object was + * created in the real compositor rather than merely surviving without a + * protocol error. + */ + +#include "wayland-relative-pointer-unstable-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "relative-pointer-unstable-v1-client-protocol.h" + +#include +#include + +static int read_server(struct relative_pointer_server_state *state) { + return TEST_READ_SERVER(relative_pointer_read_server_state, state, + "relative-pointer: failed to read server state"); +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("relative-pointer: connect failed\n"); + return 1; + } + + struct client_pointer_seat pointer_seat = { 0 }; + if (!client_bind_pointer_seat(&conn, wl_seat_interface.version, &pointer_seat)) { + TEST_ERROR("relative-pointer: no pointer-capable wl_seat\n"); + client_disconnect(&conn); + return 1; + } + struct wl_seat *seat = pointer_seat.seat; + struct wl_pointer *pointer = pointer_seat.pointer; + + struct zwp_relative_pointer_manager_v1 *manager = client_bind( + &conn, zwp_relative_pointer_manager_v1_interface.name, &zwp_relative_pointer_manager_v1_interface, zwp_relative_pointer_manager_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("relative-pointer: failed to bind manager: %s\n", strerror(errno)); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + struct zwp_relative_pointer_v1 *rel = + zwp_relative_pointer_manager_v1_get_relative_pointer(manager, pointer); + if (rel == NULL) { + TEST_ERROR("relative-pointer: get_relative_pointer returned NULL\n"); + zwp_relative_pointer_manager_v1_destroy(manager); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return 1; + } + + wl_display_roundtrip(conn.display); + + int failed = 0; + + /* E-level: the production manager must have at least 1 relative pointer. */ + struct relative_pointer_server_state srv; + if (read_server(&srv)) { + failed = 1; + } else if (!srv.valid) { + TEST_ERROR("relative-pointer: manager not found\n"); + failed = 1; + } else if (srv.count < 1) { + TEST_ERROR("relative-pointer: expected count >= 1, got %d\n", srv.count); + failed = 1; + } + + zwp_relative_pointer_v1_destroy(rel); + zwp_relative_pointer_manager_v1_destroy(manager); + wl_pointer_destroy(pointer); + wl_seat_destroy(seat); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-relative-pointer-unstable-v1/wayland-relative-pointer-unstable-v1.h b/tests/protocols/wayland-relative-pointer-unstable-v1/wayland-relative-pointer-unstable-v1.h new file mode 100644 index 0000000000..69cf8cf1c9 --- /dev/null +++ b/tests/protocols/wayland-relative-pointer-unstable-v1/wayland-relative-pointer-unstable-v1.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_RELATIVE_POINTER_TEST_H +#define WAYLAND_RELATIVE_POINTER_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * E-level readback: the production WRelativePointerManagerV1's wlroots handle + * has a relative_pointers linked list. After the client creates a + * zwp_relative_pointer_v1, the list must contain at least one entry, proving + * the relative pointer object was created in the real compositor. + */ +struct relative_pointer_server_state { + int valid; /* manager was found */ + int count; /* number of relative_pointers in the list */ +}; + +void relative_pointer_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_RELATIVE_POINTER_TEST_H */ diff --git a/tests/protocols/wayland-security-context-v1/CMakeLists.txt b/tests/protocols/wayland-security-context-v1/CMakeLists.txt new file mode 100644 index 0000000000..af6b17b6ef --- /dev/null +++ b/tests/protocols/wayland-security-context-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_security_context_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/security-context/security-context-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-security-context-v1.c" +) diff --git a/tests/protocols/wayland-security-context-v1/README.md b/tests/protocols/wayland-security-context-v1/README.md new file mode 100644 index 0000000000..f9214d5ce8 --- /dev/null +++ b/tests/protocols/wayland-security-context-v1/README.md @@ -0,0 +1,34 @@ +# `wayland-security-context-v1` 测试规范 + +## 范围 + +- XML / interface:`wp_security_context_manager_v1` / `wp_security_context_v1`(version 1) +- 测试源码:`tests/protocols/wayland-security-context-v1/` +- Fixture:headless output fixture +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `wp_security_context_manager_v1` | 资源创建成功 | P | +| 创建监听器 | `create_listener(listen_fd, close_fd)` | 返回非 NULL `wp_security_context_v1` | P | +| 设置 app_id | `set_app_id("test-app")` | 无协议错误 | P | +| 提交 | `commit` | 无协议错误 | P | +| 第二连接 | 通过监听套接字连接 | 第二客户端枚举到 wl_compositor 等全局 | P | +| **生产回读** | — | 回读真实 `wlr_security_context_manager_v1::events.commit` 捕获的 `app_id` == "test-app" | **E** | + +## 生产结果 + +测试观察 Treeland 通过 `WSecurityContextManager` 提供的安全上下文服务。 +客户端 commit 安全上下文后,setup 通过 `WSecurityContextManager::handle()` 获取生产 +manager 指针,并 `wl_signal_add` 监听 +`events.commit` 信号, +回读捕获的 `app_id` 断言为 "test-app",证明安全上下文提交到达生产管理器。 + +## 已知边界 / 下一项结果 + +waylib 实现与测试共同使用 +`waylib/src/server/protocols/private/wsecuritycontextmanager_p.h` 中的私有布局定义;该定义不能替换为 +vendored wlroots 的同名类型,因为 waylib 的 manager 额外包含 `new_client` 信号。 +未验证 `sandbox_engine` / `instance_id` 字段与 `new_client` 信号。 diff --git a/tests/protocols/wayland-security-context-v1/setup.cpp b/tests/protocols/wayland-security-context-v1/setup.cpp new file mode 100644 index 0000000000..789dd68f4a --- /dev/null +++ b/tests/protocols/wayland-security-context-v1/setup.cpp @@ -0,0 +1,59 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-security-context-v1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include +#include +#include + +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +bool g_committed = false; +bool g_app_id_match = false; + +struct wl_listener g_commit_listener; + +static void handleCommit(struct wl_listener *listener, void *data) +{ + (void)listener; + const auto *event = static_cast(data); + g_committed = true; + if (event && event->state && event->state->app_id) { + g_app_id_match = (strcmp(event->state->app_id, "test-app") == 0); + } +} +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + g_committed = false; + g_app_id_match = false; + g_commit_listener.notify = handleCommit; + + auto *mgr = find_server_interface(server); + Q_ASSERT(mgr); + if (!mgr) + return; + auto *wlr_mgr = static_cast(mgr->handle()); + Q_ASSERT(wlr_mgr); + if (!wlr_mgr) + return; + wl_signal_add(&wlr_mgr->events.commit, &g_commit_listener); +} + +void security_context_read_server_state(void *data) +{ + auto *state = + static_cast(data); + state->valid = g_committed ? 1 : 0; + state->app_id_match = g_app_id_match ? 1 : 0; +} diff --git a/tests/protocols/wayland-security-context-v1/wayland-security-context-v1.c b/tests/protocols/wayland-security-context-v1/wayland-security-context-v1.c new file mode 100644 index 0000000000..1175eb2a3a --- /dev/null +++ b/tests/protocols/wayland-security-context-v1/wayland-security-context-v1.c @@ -0,0 +1,182 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end): the client creates an abstract Unix listening + * socket + a close fd, commits a security context with app_id="test-app", then + * connects a second Wayland client through the listening socket. The test + * reads back the production wlr_security_context_manager_v1's commit event, + * verifying the app_id matches, proving the security context commit reached the + * real compositor security-context pipeline. + */ + +#include "wayland-security-context-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "security-context-v1-client-protocol.h" + +#include +#include +#include +#include +#include +#include + +struct sec_state { + int global_count; + int has_compositor; +}; + +static void sec_global(void *data, struct wl_registry *registry, uint32_t name, + const char *interface, uint32_t version) { + (void)registry; + (void)name; + (void)version; + struct sec_state *state = data; + state->global_count++; + if (strcmp(interface, "wl_compositor") == 0) + state->has_compositor = 1; +} + +static void sec_global_remove(void *data, struct wl_registry *registry, uint32_t name) { + (void)data; + (void)registry; + (void)name; +} + +static const struct wl_registry_listener sec_registry_listener = { + .global = sec_global, + .global_remove = sec_global_remove, +}; + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("security-context: connect failed\n"); + return 1; + } + + /* 1. Abstract Unix listening socket. */ + int listen_fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (listen_fd < 0) { + TEST_ERROR("security-context: socket() failed\n"); + client_disconnect(&conn); + return 1; + } + char name[64]; + snprintf(name, sizeof(name), "treeland-sec-ctx-%d", (int)getpid()); + struct sockaddr_un addr = { 0 }; + addr.sun_family = AF_UNIX; + addr.sun_path[0] = '\0'; /* abstract namespace marker */ + strncpy(addr.sun_path + 1, name, sizeof(addr.sun_path) - 2); + socklen_t addrlen = (socklen_t)(sizeof(sa_family_t) + 1 + strlen(name)); + if (bind(listen_fd, (struct sockaddr *)&addr, addrlen) < 0 || listen(listen_fd, 1) < 0) { + TEST_ERROR("security-context: bind/listen failed\n"); + close(listen_fd); + client_disconnect(&conn); + return 1; + } + + /* 2. close fd (socketpair); the compositor watches one end. */ + int close_fds[2]; + if (socketpair(AF_UNIX, SOCK_STREAM, 0, close_fds) < 0) { + TEST_ERROR("security-context: socketpair failed\n"); + close(listen_fd); + client_disconnect(&conn); + return 1; + } + + /* 3. Bind manager, create the security context, commit. */ + struct wp_security_context_manager_v1 *manager = client_bind( + &conn, wp_security_context_manager_v1_interface.name, &wp_security_context_manager_v1_interface, wp_security_context_manager_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("security-context: failed to bind manager: %s\n", strerror(errno)); + close(close_fds[0]); + close(close_fds[1]); + close(listen_fd); + client_disconnect(&conn); + return 1; + } + + struct wp_security_context_v1 *ctx = + wp_security_context_manager_v1_create_listener(manager, listen_fd, close_fds[0]); + if (ctx == NULL) { + TEST_ERROR("security-context: create_listener returned NULL\n"); + close(close_fds[0]); + close(close_fds[1]); + close(listen_fd); + client_disconnect(&conn); + return 1; + } + wp_security_context_v1_set_app_id(ctx, "test-app"); + wp_security_context_v1_commit(ctx); + /* Let the compositor add listen_fd to its event loop. */ + wl_display_roundtrip(conn.display); + + /* E-level: read back the production commit event state. */ + struct security_context_server_state srv = { 0 }; + invoke_on_server_thread(security_context_read_server_state, &srv); + + /* 4. Connect a second client through the listening socket. */ + int conn_fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (conn_fd < 0 || connect(conn_fd, (struct sockaddr *)&addr, addrlen) < 0) { + TEST_ERROR("security-context: second connect failed\n"); + if (conn_fd >= 0) + close(conn_fd); + wp_security_context_v1_destroy(ctx); + wp_security_context_manager_v1_destroy(manager); + close(close_fds[0]); + close(close_fds[1]); + close(listen_fd); + client_disconnect(&conn); + return 1; + } + + /* The compositor must accept() on its next loop iteration. */ + wl_display_roundtrip(conn.display); + + struct wl_display *sec_display = wl_display_connect_to_fd(conn_fd); + if (sec_display == NULL) { + TEST_ERROR("security-context: wl_display_connect_to_fd failed\n"); + wp_security_context_v1_destroy(ctx); + wp_security_context_manager_v1_destroy(manager); + close(close_fds[0]); + close(close_fds[1]); + close(listen_fd); + client_disconnect(&conn); + return 1; + } + + struct sec_state state = { 0 }; + struct wl_registry *registry = wl_display_get_registry(sec_display); + wl_registry_add_listener(registry, &sec_registry_listener, &state); + wl_display_roundtrip(sec_display); + + int failed = 0; + if (state.global_count < 1) { + TEST_ERROR("security-context: no globals on second client\n"); + failed = 1; + } else if (!state.has_compositor) { + TEST_ERROR("security-context: wl_compositor not advertised\n"); + failed = 1; + } + + /* E-level: verify the production commit captured the correct app_id. */ + if (!srv.valid) { + TEST_ERROR("security-context: no commit event captured\n"); + failed = 1; + } else if (!srv.app_id_match) { + TEST_ERROR("security-context: app_id mismatch\n"); + failed = 1; + } + + wl_display_disconnect(sec_display); + wp_security_context_v1_destroy(ctx); + wp_security_context_manager_v1_destroy(manager); + wl_display_roundtrip(conn.display); + close(close_fds[0]); + close(close_fds[1]); + close(listen_fd); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-security-context-v1/wayland-security-context-v1.h b/tests/protocols/wayland-security-context-v1/wayland-security-context-v1.h new file mode 100644 index 0000000000..d10623f47e --- /dev/null +++ b/tests/protocols/wayland-security-context-v1/wayland-security-context-v1.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_SECURITY_CONTEXT_TEST_H +#define WAYLAND_SECURITY_CONTEXT_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * E-level readback: the production wlr_security_context_manager_v1 emits a + * commit signal when the client commits a security context. The captured + * app_id must match the client's requested value, proving the security context + * commit reached the real compositor security-context pipeline. + */ +struct security_context_server_state { + int valid; /* a commit event was captured */ + int app_id_match; /* captured app_id matches "test-app" */ +}; + +void security_context_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_SECURITY_CONTEXT_TEST_H */ diff --git a/tests/protocols/wayland-single-pixel-buffer-v1/CMakeLists.txt b/tests/protocols/wayland-single-pixel-buffer-v1/CMakeLists.txt new file mode 100644 index 0000000000..fcd8e12b1c --- /dev/null +++ b/tests/protocols/wayland-single-pixel-buffer-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_single_pixel_buffer_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/single-pixel-buffer/single-pixel-buffer-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-single-pixel-buffer-v1.c" +) diff --git a/tests/protocols/wayland-single-pixel-buffer-v1/README.md b/tests/protocols/wayland-single-pixel-buffer-v1/README.md new file mode 100644 index 0000000000..ab635c2217 --- /dev/null +++ b/tests/protocols/wayland-single-pixel-buffer-v1/README.md @@ -0,0 +1,31 @@ +# `wayland-single-pixel-buffer-v1` 测试规范 + +## 范围 + +- XML / interface:`wp_single_pixel_buffer_manager_v1`(version 1,无事件) +- 测试源码:`tests/protocols/wayland-single-pixel-buffer-v1/` +- Fixture:headless output fixture + xdg-toplevel-client(`create_pending` → ack → attach 单像素缓冲 → commit) +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `wp_single_pixel_buffer_manager_v1`(v1) | 资源创建成功 | P | +| 创建单像素缓冲 | `create_u32_rgba_buffer(0xffff, 0, 0, 0xffff)` | 返回非 NULL 的 `wl_buffer` | P | +| 映射 toplevel | 用单像素缓冲 attach + commit 映射 xdg_toplevel | 无协议错误 | P | +| 真实缓冲尺寸 | 回读真实 `wlr_surface::current.buffer_width/height` | 均为 1(1×1 单像素缓冲) | E | +| 真实映射状态 | 回读真实 `WSurface::mapped()` | 为 true | E | + +## 生产结果 + +测试创建一个真实 xdg_toplevel,在 ack configure 后用 `wp_single_pixel_buffer_manager_v1` +创建的 1×1 RGBA 缓冲(而非 SHM 缓冲)映射该 toplevel。随后通过 server bridge 回读 +捕获的生产 `SurfaceWrapper` 的 `WSurface::handle()` 所指向的 `wlr_surface`,断言其 +`current.buffer_width` 和 `current.buffer_height` 均为 1,且 `WSurface::mapped()` 为 +true。此断言验证单像素缓冲确实进入了真实合成器 surface 管线并被映射,而非仅资源 +创建无协议错误。 + +## 已知边界 / 下一项结果 + +未验证缓冲的实际 RGBA 像素值(V 级像素读回亦未覆盖)。 diff --git a/tests/protocols/wayland-single-pixel-buffer-v1/setup.cpp b/tests/protocols/wayland-single-pixel-buffer-v1/setup.cpp new file mode 100644 index 0000000000..83f28ddcc0 --- /dev/null +++ b/tests/protocols/wayland-single-pixel-buffer-v1/setup.cpp @@ -0,0 +1,59 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-single-pixel-buffer-v1.h" +#include "server-bridge.h" +#include "core/shellhandler.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" + +#include +#include +#include + +namespace { +// The real mapped XdgToplevel SurfaceWrapper created by the client's +// xdg_toplevel_client_complete_map(). Captured from the production +// ShellHandler::surfaceWrapperAdded signal. +SurfaceWrapper *g_wrapper = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() == SurfaceWrapper::Type::XdgToplevel) + g_wrapper = wrapper; + }); +} + +// E-level read: report the captured production SurfaceWrapper's wl_surface +// buffer dimensions. A single-pixel buffer is 1×1, so wlr_surface::current +// must report buffer_width == 1 and buffer_height == 1. +void single_pixel_buffer_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = 0; + state->mapped = 0; + state->buffer_width = 0; + state->buffer_height = 0; + + if (!g_wrapper) + return; + + auto *wsurface = g_wrapper->surface(); + if (!wsurface) + return; + + state->valid = 1; + state->mapped = wsurface->mapped() ? 1 : 0; + + auto *wlr_surf = wsurface->handle(); + if (wlr_surf) { + state->buffer_width = wlr_surf->current.buffer_width; + state->buffer_height = wlr_surf->current.buffer_height; + } +} diff --git a/tests/protocols/wayland-single-pixel-buffer-v1/wayland-single-pixel-buffer-v1.c b/tests/protocols/wayland-single-pixel-buffer-v1/wayland-single-pixel-buffer-v1.c new file mode 100644 index 0000000000..cf45f1b58c --- /dev/null +++ b/tests/protocols/wayland-single-pixel-buffer-v1/wayland-single-pixel-buffer-v1.c @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Test the wp_single_pixel_buffer_manager_v1 global created by + * wlr_single_pixel_buffer_manager_v1_create in Treeland's WaylandServer. + * + * Coverage level E (end-to-end): the client maps a real xdg_toplevel using a + * single-pixel RGBA buffer as its content, then reads back the production + * wlr_surface current state over the server bridge. The surface must be + * mapped and its buffer dimensions must be 1×1, proving the buffer was accepted + * by the real compositor surface pipeline rather than merely surviving without + * a protocol error. + */ + +#include "wayland-single-pixel-buffer-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "single-pixel-buffer-v1-client-protocol.h" + +#include +#include + +static int read_server(struct single_pixel_buffer_server_state *state) { + return TEST_READ_SERVER(single_pixel_buffer_read_server_state, state, + "single-pixel-buffer: failed to read server state"); +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("single-pixel-buffer: connect failed\n"); + return 1; + } + + struct wp_single_pixel_buffer_manager_v1 *manager = client_bind(&conn, + wp_single_pixel_buffer_manager_v1_interface.name, &wp_single_pixel_buffer_manager_v1_interface, wp_single_pixel_buffer_manager_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("single-pixel-buffer: failed to bind manager: %s\n", strerror(errno)); + client_disconnect(&conn); + return 1; + } + + struct xdg_toplevel_client tc; + if (!xdg_toplevel_client_create_pending(&conn, &tc)) { + TEST_ERROR("single-pixel-buffer: create toplevel pending failed\n"); + wp_single_pixel_buffer_manager_v1_destroy(manager); + client_disconnect(&conn); + return 1; + } + + int failed = 0; + + /* Receive the initial configure event. */ + if (wl_display_roundtrip(conn.display) < 0 || !tc.configured) { + TEST_ERROR("single-pixel-buffer: no configure event\n"); + failed = 1; + } + + /* Ack the configure so the surface enters the mapped-ready state. */ + if (!failed && !xdg_toplevel_client_ack_latest_configure(&conn, &tc)) { + TEST_ERROR("single-pixel-buffer: ack configure failed\n"); + failed = 1; + } + + struct wl_buffer *buffer = NULL; + if (!failed) { + buffer = wp_single_pixel_buffer_manager_v1_create_u32_rgba_buffer( + manager, 0xffff0000u, 0, 0, 0xffffffffu); + if (buffer == NULL) { + TEST_ERROR("single-pixel-buffer: create_u32_rgba_buffer returned NULL\n"); + failed = 1; + } + } + + if (!failed) { + /* Attach the 1×1 single-pixel buffer and commit to map the toplevel. */ + wl_surface_attach(tc.surface, buffer, 0, 0); + wl_surface_damage(tc.surface, 0, 0, 1, 1); + wl_surface_commit(tc.surface); + wl_display_roundtrip(conn.display); + + /* E-level: the real production surface must be mapped with a 1×1 buffer. */ + struct single_pixel_buffer_server_state srv; + if (read_server(&srv)) { + failed = 1; + } else if (!srv.valid) { + TEST_ERROR("single-pixel-buffer: no mapped SurfaceWrapper captured\n"); + failed = 1; + } else if (!srv.mapped) { + TEST_ERROR("single-pixel-buffer: WSurface not mapped\n"); + failed = 1; + } else if (srv.buffer_width != 1 || srv.buffer_height != 1) { + TEST_ERROR("single-pixel-buffer: expected 1×1 buffer, got %d×%d\n", srv.buffer_width, srv.buffer_height); + failed = 1; + } + } + + if (buffer != NULL) + wl_buffer_destroy(buffer); + xdg_toplevel_client_destroy(&tc); + wp_single_pixel_buffer_manager_v1_destroy(manager); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-single-pixel-buffer-v1/wayland-single-pixel-buffer-v1.h b/tests/protocols/wayland-single-pixel-buffer-v1/wayland-single-pixel-buffer-v1.h new file mode 100644 index 0000000000..d4edc5ed3a --- /dev/null +++ b/tests/protocols/wayland-single-pixel-buffer-v1/wayland-single-pixel-buffer-v1.h @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_SINGLE_PIXEL_BUFFER_TEST_H +#define WAYLAND_SINGLE_PIXEL_BUFFER_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Snapshot of the real mapped SurfaceWrapper's wl_surface buffer dimensions, + * read on the compositor (Qt) thread. A single-pixel buffer is 1×1, so an + * E-level test verifies that the production wlr_surface current state reports + * buffer_width == 1 and buffer_height == 1 after the buffer is committed, + * proving the buffer was accepted by the real compositor surface pipeline. + */ +struct single_pixel_buffer_server_state { + int valid; /* a mapped SurfaceWrapper was captured */ + int mapped; /* WSurface::mapped() */ + int buffer_width; /* wlr_surface::current.buffer_width */ + int buffer_height; /* wlr_surface::current.buffer_height */ +}; + +/* Defined in setup.cpp; runs on the compositor thread via + * invoke_on_server_thread() and fills *data with the buffer dimensions. */ +void single_pixel_buffer_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_SINGLE_PIXEL_BUFFER_TEST_H */ diff --git a/tests/protocols/wayland-text-input-unstable-v1/CMakeLists.txt b/tests/protocols/wayland-text-input-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..a8f6df20e3 --- /dev/null +++ b/tests/protocols/wayland-text-input-unstable-v1/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_text_input_unstable_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/unstable/text-input/text-input-unstable-v1.xml" + EXTRA_XMLS + "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/input-method-unstable-v2.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-text-input-unstable-v1.c" +) diff --git a/tests/protocols/wayland-text-input-unstable-v1/README.md b/tests/protocols/wayland-text-input-unstable-v1/README.md new file mode 100644 index 0000000000..50c60d4a7f --- /dev/null +++ b/tests/protocols/wayland-text-input-unstable-v1/README.md @@ -0,0 +1,40 @@ +# `wayland-text-input-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`zwp_text_input_manager_v1` / `zwp_text_input_v1`(version 1) +- 测试源码:`tests/protocols/wayland-text-input-unstable-v1/` +- Fixture:headless output fixture + 映射 xdg-toplevel;第二条连接作为 fake + `zwp_input_method_v2`(`EXTRA_XMLS` 引入 `input-method-unstable-v2.xml`) +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `zwp_text_input_manager_v1` | 资源创建成功 | P | +| 创建 text_input | `create_text_input(seat)` | 返回非 NULL `zwp_text_input_v1` | P | +| 激活 | `activate(seat, surface)` | 无协议错误 | P | +| **生产回读** | — | 回读真实 `WTextInputV1::activate` Q_SIGNAL 被触发 | **E** | +| 焦点进入 | `activate(seat, surface)` | 收到一次 `enter`;fake IM 收到一次 `activate` | E | +| 转发 preedit | `commit_state(7)`,fake IM `set_preedit_string("pre",0,3)` + `commit` | 客户端收到 `commit_string`、`preedit_cursor`、`preedit_styling` 和 `preedit_string("pre")`,且 serial 等于 `commit_state` 传入的 7 | E | +| 清空 preedit | fake IM 不发送 `set_preedit_string` 直接 `commit` | 客户端再收到一次 `preedit_string` 且文本为空、serial 仍为 7(v1 没有 `done`,空的 `preedit_string` 是唯一能清掉组合文本的手段) | E | +| 丢焦点不清 preedit | fake IM 被销毁,focused text-input 因此收到 `leave` | 只收到 `leave`,不补发 `preedit_string`:v1 的 `preedit_string` 需要 `commit_state` 提供的 serial,丢焦点清 preedit 时该 serial 语义不明确 | E | + +## 生产结果 + +测试观察 Treeland 通过 `WTextInputManagerV1` 提供的文本输入 v1 服务。 +客户端 `activate` 后,setup 通过 `WTextInputManagerV1::newTextInput` 信号捕获 +`WTextInputV1*`,连接到其 `activate()` Q_SIGNAL,回读断言信号被触发, +证明文本输入激活请求到达生产文本输入管道。 + +第二条连接作为 fake input method,让 `WInputMethodHelper::handleIMCommitted` 真正跑到 +`WTextInputV1::handleIMCommitted`(`WTextInputV1::sendEnter()` 无条件发出 `enabled()`, +所以聚焦的 v1 text-input 会成为 `enabledTextInput`)。客户端按顺序记录 +`enter` / `preedit_string` / `commit_string` / `leave`,断言完整序列 `ekpkpl`: +去掉空 preedit 转发分支后,用例在 stage 3 失败。 + +## 已知边界 / 下一项结果 + +未验证 `deactivate`、`set_surrounding_text`、`show_input_panel` 等请求, +也未覆盖 `delete_surrounding_text` 与 `preedit_styling` 的具体参数值。 diff --git a/tests/protocols/wayland-text-input-unstable-v1/setup.cpp b/tests/protocols/wayland-text-input-unstable-v1/setup.cpp new file mode 100644 index 0000000000..b8e324af06 --- /dev/null +++ b/tests/protocols/wayland-text-input-unstable-v1/setup.cpp @@ -0,0 +1,39 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-text-input-unstable-v1.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +WTextInputManagerV1 *g_mgr = nullptr; +WTextInputV1 *g_text_input = nullptr; +bool g_activated = false; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + g_mgr = find_server_interface(server); + if (g_mgr) { + QObject::connect(g_mgr, &WTextInputManagerV1::newTextInput, + server, [](WTextInputV1 *ti) { + g_text_input = ti; + QObject::connect(ti, &WTextInputV1::activate, + ti, []() { + g_activated = true; + }); + }); + } +} + +void text_input_v1_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = g_text_input ? 1 : 0; + state->activated = g_activated ? 1 : 0; +} diff --git a/tests/protocols/wayland-text-input-unstable-v1/wayland-text-input-unstable-v1.c b/tests/protocols/wayland-text-input-unstable-v1/wayland-text-input-unstable-v1.c new file mode 100644 index 0000000000..cc148cd97b --- /dev/null +++ b/tests/protocols/wayland-text-input-unstable-v1/wayland-text-input-unstable-v1.c @@ -0,0 +1,454 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end): the client creates a zwp_text_input_v1, + * maps a toplevel to get keyboard focus, and calls activate(surface, seat). + * The test reads back the production WTextInputV1's activate() signal state, + * verifying it was emitted, proving the text-input activation request reached + * the real compositor text-input pipeline. A second connection acts as a fake + * zwp_input_method_v2, so the compositor forwards input-method commits to the + * v1 text input: the client asserts that a commit which does not set a preedit + * produces an empty preedit_string carrying the serial from commit_state, and + * that leave does not clear the preedit (v1 has no done event, and its + * preedit_string serial is only meaningful for a commit). + */ + +#include "wayland-text-input-unstable-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "text-input-unstable-v1-client-protocol.h" +#include "input-method-unstable-v2-client-protocol.h" + +#include +#include + +enum { TEXT_INPUT_V1_MAX_LOG = 64 }; + +struct text_input_v1_events { + unsigned int enter; + unsigned int leave; + unsigned int preedit_string; + unsigned int preedit_styling; + unsigned int preedit_cursor; + unsigned int commit_string; + uint32_t preedit_serial; + char preedit[64]; + char committed[64]; + /* Ordered tags of the preedit/commit/leave events. */ + char log[TEXT_INPUT_V1_MAX_LOG]; + unsigned int log_len; +}; + +static void note(struct text_input_v1_events *events, char tag) +{ + if (events->log_len + 1 < sizeof(events->log)) + events->log[events->log_len++] = tag; + events->log[events->log_len] = '\0'; +} + +static void ti_enter(void *data, struct zwp_text_input_v1 *ti, struct wl_surface *surface) +{ + (void)ti; + (void)surface; + struct text_input_v1_events *events = data; + ++events->enter; + note(events, 'e'); +} + +static void ti_leave(void *data, struct zwp_text_input_v1 *ti) +{ + (void)ti; + struct text_input_v1_events *events = data; + ++events->leave; + note(events, 'l'); +} + +static void ti_modifiers_map(void *data, struct zwp_text_input_v1 *ti, struct wl_array *map) +{ + (void)data; + (void)ti; + (void)map; +} + +static void ti_input_panel_state(void *data, struct zwp_text_input_v1 *ti, uint32_t state) +{ + (void)data; + (void)ti; + (void)state; +} + +static void ti_preedit_string(void *data, struct zwp_text_input_v1 *ti, + uint32_t serial, const char *text, const char *commit) +{ + (void)ti; + (void)commit; + struct text_input_v1_events *events = data; + ++events->preedit_string; + events->preedit_serial = serial; + snprintf(events->preedit, sizeof(events->preedit), "%s", text); + note(events, 'p'); +} + +static void ti_preedit_styling(void *data, struct zwp_text_input_v1 *ti, + uint32_t index, uint32_t length, uint32_t style) +{ + (void)ti; + (void)index; + (void)length; + (void)style; + ++((struct text_input_v1_events *)data)->preedit_styling; +} + +static void ti_preedit_cursor(void *data, struct zwp_text_input_v1 *ti, int32_t index) +{ + (void)ti; + (void)index; + ++((struct text_input_v1_events *)data)->preedit_cursor; +} + +static void ti_commit_string(void *data, struct zwp_text_input_v1 *ti, + uint32_t serial, const char *text) +{ + (void)ti; + (void)serial; + struct text_input_v1_events *events = data; + ++events->commit_string; + snprintf(events->committed, sizeof(events->committed), "%s", text); + note(events, 'k'); +} + +static void ti_cursor_position(void *data, struct zwp_text_input_v1 *ti, + int32_t index, int32_t anchor) +{ + (void)data; + (void)ti; + (void)index; + (void)anchor; +} + +static void ti_delete_surrounding_text(void *data, struct zwp_text_input_v1 *ti, + int32_t index, uint32_t length) +{ + (void)data; + (void)ti; + (void)index; + (void)length; +} + +static void ti_keysym(void *data, struct zwp_text_input_v1 *ti, uint32_t serial, + uint32_t time, uint32_t sym, uint32_t state, uint32_t modifiers) +{ + (void)data; + (void)ti; + (void)serial; + (void)time; + (void)sym; + (void)state; + (void)modifiers; +} + +static void ti_language(void *data, struct zwp_text_input_v1 *ti, + uint32_t serial, const char *language) +{ + (void)data; + (void)ti; + (void)serial; + (void)language; +} + +static void ti_text_direction(void *data, struct zwp_text_input_v1 *ti, + uint32_t serial, uint32_t direction) +{ + (void)data; + (void)ti; + (void)serial; + (void)direction; +} + +static const struct zwp_text_input_v1_listener ti_listener = { + .enter = ti_enter, + .leave = ti_leave, + .modifiers_map = ti_modifiers_map, + .input_panel_state = ti_input_panel_state, + .preedit_string = ti_preedit_string, + .preedit_styling = ti_preedit_styling, + .preedit_cursor = ti_preedit_cursor, + .commit_string = ti_commit_string, + .cursor_position = ti_cursor_position, + .delete_surrounding_text = ti_delete_surrounding_text, + .keysym = ti_keysym, + .language = ti_language, + .text_direction = ti_text_direction, +}; + +struct input_method_state { + unsigned int activate; + unsigned int done; + unsigned int unavailable; +}; + +static void im_activate(void *data, struct zwp_input_method_v2 *im) +{ + (void)im; + ++((struct input_method_state *)data)->activate; +} + +static void im_deactivate(void *data, struct zwp_input_method_v2 *im) +{ + (void)data; + (void)im; +} + +static void im_surrounding_text(void *data, struct zwp_input_method_v2 *im, + const char *text, uint32_t cursor, uint32_t anchor) +{ + (void)data; + (void)im; + (void)text; + (void)cursor; + (void)anchor; +} + +static void im_text_change_cause(void *data, struct zwp_input_method_v2 *im, uint32_t cause) +{ + (void)data; + (void)im; + (void)cause; +} + +static void im_content_type(void *data, struct zwp_input_method_v2 *im, + uint32_t hint, uint32_t purpose) +{ + (void)data; + (void)im; + (void)hint; + (void)purpose; +} + +static void im_done(void *data, struct zwp_input_method_v2 *im) +{ + (void)im; + /* The input method echoes the number of done events back as the commit + * serial. */ + ++((struct input_method_state *)data)->done; +} + +static void im_unavailable(void *data, struct zwp_input_method_v2 *im) +{ + (void)im; + ++((struct input_method_state *)data)->unavailable; +} + +static const struct zwp_input_method_v2_listener im_listener = { + .activate = im_activate, + .deactivate = im_deactivate, + .surrounding_text = im_surrounding_text, + .text_change_cause = im_text_change_cause, + .content_type = im_content_type, + .done = im_done, + .unavailable = im_unavailable, +}; + +static int read_server(struct text_input_v1_server_state *state) { + return TEST_READ_SERVER(text_input_v1_read_server_state, state, + "text-input-v1: failed to read server state"); +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn = { 0 }; + struct client_connection im_connection = { 0 }; + struct client_seat client_seat = { 0 }; + struct xdg_toplevel_client tc = { 0 }; + struct text_input_v1_events events = { 0 }; + struct input_method_state im_state = { 0 }; + struct wl_seat *seat = NULL; + struct zwp_text_input_manager_v1 *manager = NULL; + struct zwp_text_input_v1 *ti = NULL; + struct wl_seat *im_seat = NULL; + struct zwp_input_method_manager_v2 *im_manager = NULL; + struct zwp_input_method_v2 *im = NULL; + struct text_input_v1_server_state srv; + /* Serial the client passes to commit_state; the compositor must echo it + * back in preedit_string/commit_string. */ + const uint32_t commit_state_serial = 7; + int stage = 0; + + if (!client_connect(&conn, socket_name) || !client_connect(&im_connection, socket_name)) + goto failed; + + if (!client_bind_seat(&conn, wl_seat_interface.version, &client_seat)) { + TEST_ERROR("text-input-v1: no wl_seat global\n"); + goto failed; + } + seat = client_seat.seat; + + /* Map a toplevel so we have a surface to activate text input on. */ + if (!xdg_toplevel_client_create_pending(&conn, &tc)) { + TEST_ERROR("text-input-v1: create_pending failed\n"); + goto failed; + } + if (!xdg_toplevel_client_complete_map(&conn, &tc)) { + TEST_ERROR("text-input-v1: complete_map failed\n"); + goto failed; + } + if (wl_display_roundtrip(conn.display) < 0) + goto failed; + + manager = client_bind(&conn, zwp_text_input_manager_v1_interface.name, + &zwp_text_input_manager_v1_interface, + zwp_text_input_manager_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("text-input-v1: failed to bind manager: %s\n", strerror(errno)); + goto failed; + } + + ti = zwp_text_input_manager_v1_create_text_input(manager); + if (ti == NULL) { + TEST_ERROR("text-input-v1: create_text_input returned NULL\n"); + goto failed; + } + zwp_text_input_v1_add_listener(ti, &ti_listener, &events); + + /* The input method must exist before the text input is activated, so that + * activating it activates the input method. */ + im_seat = client_bind(&im_connection, "wl_seat", &wl_seat_interface, 1); + im_manager = client_bind(&im_connection, "zwp_input_method_manager_v2", + &zwp_input_method_manager_v2_interface, 1); + if (im_seat == NULL || im_manager == NULL) + goto failed; + im = zwp_input_method_manager_v2_get_input_method(im_manager, im_seat); + if (im == NULL) + goto failed; + zwp_input_method_v2_add_listener(im, &im_listener, &im_state); + if (wl_display_roundtrip(im_connection.display) < 0) + goto failed; + + zwp_text_input_v1_activate(ti, seat, tc.surface); + if (wl_display_roundtrip(conn.display) < 0) + goto failed; + stage = 1; + + /* E-level: the production text input must have been activated. */ + if (read_server(&srv)) + goto failed; + if (!srv.valid) { + TEST_ERROR("text-input-v1: manager not found\n"); + goto failed; + } + if (!srv.activated) { + TEST_ERROR("text-input-v1: activate signal not emitted\n"); + goto failed; + } + if (events.enter != 1) { + TEST_ERROR("text-input-v1: enter=%u\n", events.enter); + goto failed; + } + /* Activating the text input activates the input method. */ + if (wl_display_roundtrip(im_connection.display) < 0) + goto failed; + if (im_state.activate != 1 || im_state.unavailable) { + TEST_ERROR("text-input-v1: activate=%u unavailable=%u\n", + im_state.activate, im_state.unavailable); + goto failed; + } + + /* commit_state carries the serial the compositor must echo back. It also + * makes the compositor send another done to the input method, so the + * commit serial below has to be read after this roundtrip. */ + zwp_text_input_v1_commit_state(ti, commit_state_serial); + if (wl_display_roundtrip(conn.display) < 0 + || wl_display_roundtrip(im_connection.display) < 0) + goto failed; + stage = 2; + + /* A commit that sets a preedit reaches the v1 client. */ + zwp_input_method_v2_set_preedit_string(im, "pre", 0, 3); + zwp_input_method_v2_commit(im, im_state.done); + if (wl_display_roundtrip(im_connection.display) < 0 + || wl_display_roundtrip(conn.display) < 0) + goto failed; + if (events.preedit_string != 1 || strcmp(events.preedit, "pre") != 0 + || events.preedit_serial != commit_state_serial + || events.preedit_styling != 1 || events.preedit_cursor != 1 + || strcmp(events.log, "ekp") != 0) { + TEST_ERROR("text-input-v1: preedit=%u '%s' serial=%u styling=%u cursor=%u log='%s'\n", + events.preedit_string, events.preedit, events.preedit_serial, + events.preedit_styling, events.preedit_cursor, events.log); + goto failed; + } + stage = 3; + + /* + * A commit that does not call set_preedit_string means "the preedit is + * empty": v1 has no done event, so an empty preedit_string is the only way + * to tell the client to drop its composing text. + */ + zwp_input_method_v2_commit(im, im_state.done); + if (wl_display_roundtrip(im_connection.display) < 0 + || wl_display_roundtrip(conn.display) < 0) + goto failed; + if (events.preedit_string != 2 || events.preedit[0] != '\0' + || events.preedit_serial != commit_state_serial + || strcmp(events.log, "ekpkp") != 0) { + TEST_ERROR("text-input-v1: preedit=%u '%s' serial=%u log='%s'\n", + events.preedit_string, events.preedit, + events.preedit_serial, events.log); + goto failed; + } + stage = 4; + + /* + * v1 leave deliberately does not clear the preedit: its preedit_string + * serial comes from commit_state and has no defined meaning for a focus + * loss, so only leave is sent. + */ + zwp_input_method_v2_destroy(im); + im = NULL; + if (wl_display_roundtrip(im_connection.display) < 0 + || wl_display_roundtrip(conn.display) < 0) + goto failed; + if (events.preedit_string != 2 || events.leave != 1 + || strcmp(events.log, "ekpkpl") != 0) { + TEST_ERROR("text-input-v1: preedit=%u leave=%u log='%s'\n", + events.preedit_string, events.leave, events.log); + goto failed; + } + stage = 5; + + zwp_text_input_v1_deactivate(ti, seat); + zwp_text_input_v1_destroy(ti); + zwp_text_input_manager_v1_destroy(manager); + zwp_input_method_manager_v2_destroy(im_manager); + wl_seat_destroy(im_seat); + xdg_toplevel_client_destroy(&tc); + wl_seat_destroy(seat); + client_disconnect(&im_connection); + client_disconnect(&conn); + return 0; + +failed: + TEST_ERROR("text-input-v1 failure at stage %d: " + "preedit=%u '%s' serial=%u commit=%u '%s' enter=%u leave=%u log='%s'\n", + stage, events.preedit_string, events.preedit, events.preedit_serial, + events.commit_string, events.committed, events.enter, events.leave, + events.log); + if (im) + zwp_input_method_v2_destroy(im); + if (im_manager) + zwp_input_method_manager_v2_destroy(im_manager); + if (ti) + zwp_text_input_v1_destroy(ti); + if (manager) + zwp_text_input_manager_v1_destroy(manager); + if (im_seat) + wl_seat_destroy(im_seat); + if (tc.surface) + xdg_toplevel_client_destroy(&tc); + if (seat) + wl_seat_destroy(seat); + client_disconnect(&im_connection); + client_disconnect(&conn); + return 1; +} diff --git a/tests/protocols/wayland-text-input-unstable-v1/wayland-text-input-unstable-v1.h b/tests/protocols/wayland-text-input-unstable-v1/wayland-text-input-unstable-v1.h new file mode 100644 index 0000000000..0e17b5cdf3 --- /dev/null +++ b/tests/protocols/wayland-text-input-unstable-v1/wayland-text-input-unstable-v1.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_TEXT_INPUT_V1_TEST_H +#define WAYLAND_TEXT_INPUT_V1_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * E-level readback: the production WTextInputManagerV1 emits newTextInput + * when the client creates a zwp_text_input_v1. The captured WTextInputV1's + * activate() signal must fire when the client calls activate, proving the + * text-input activation request reached the real compositor text-input + * pipeline. + */ +struct text_input_v1_server_state { + int valid; /* a WTextInputV1 was captured */ + int activated; /* activate() signal was emitted */ +}; + +void text_input_v1_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_TEXT_INPUT_V1_TEST_H */ diff --git a/tests/protocols/wayland-text-input-unstable-v3/CMakeLists.txt b/tests/protocols/wayland-text-input-unstable-v3/CMakeLists.txt new file mode 100644 index 0000000000..ad7e1f7cac --- /dev/null +++ b/tests/protocols/wayland-text-input-unstable-v3/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_text_input_unstable_v3 + XML "${WAYLAND_PROTOCOLS_DATADIR}/unstable/text-input/text-input-unstable-v3.xml" + EXTRA_XMLS + "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/input-method-unstable-v2.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-text-input-unstable-v3.c" +) diff --git a/tests/protocols/wayland-text-input-unstable-v3/README.md b/tests/protocols/wayland-text-input-unstable-v3/README.md new file mode 100644 index 0000000000..2dc9aa152b --- /dev/null +++ b/tests/protocols/wayland-text-input-unstable-v3/README.md @@ -0,0 +1,39 @@ +# `wayland-text-input-unstable-v3` 测试规范 + +## 范围 + +- XML / interface:`zwp_text_input_manager_v3` / `zwp_text_input_v3`(version 1) +- 测试源码:`tests/protocols/wayland-text-input-unstable-v3/` +- Fixture:headless output fixture + 映射 xdg-toplevel;第二条连接作为 fake + `zwp_input_method_v2`(`EXTRA_XMLS` 引入 `input-method-unstable-v2.xml`) +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `zwp_text_input_manager_v3` | 资源创建成功 | P | +| 创建 text_input | `get_text_input(seat)` | 返回非 NULL `zwp_text_input_v3` | P | +| 启用 + 提交 | `enable` + `commit` | 无协议错误 | P | +| **生产回读** | — | 回读真实 `wlr_text_input_v3::current_enabled` == true | **E** | +| 焦点进入 | 创建 text_input(toplevel 已聚焦) | 收到一次 `enter`;fake IM 收到一次 `activate` | E | +| 转发 preedit | fake IM `set_preedit_string("pre",0,3)` + `commit` | 客户端依次收到 `preedit_string("pre")`、`done` | E | +| 清空 preedit | fake IM 不发送 `set_preedit_string` 直接 `commit`(fcitx5 清空 preedit 时的行为) | 客户端收到一次空的 `preedit_string` 且文本为空(此前只在非空时转发,导致应用永远保留旧 preedit) | E | +| 丢焦点时清 preedit | fake IM 被销毁,focused text-input 因此收到 `leave`(与切窗口时走同一条 `sendLeave()` 路径) | 客户端在 `leave` 之前依次收到空的 `preedit_string` 和 `done`(断言校验完整事件顺序 `epdpdpdl`),组合文本被清除而不是留给客户端自行处理 | E | +| 已 disable 时不发状态更新 | 客户端 `disable` + `commit`,再销毁 fake IM 触发丢焦点 | 只收到 `leave`,不补发 `preedit_string`/`done`:已经 disable 的客户端不应收到活动输入会话之外的状态更新 | E | + +## 生产结果 + +测试观察 Treeland 通过 `WTextInputManagerV3` 提供的文本输入 v3 服务。 +客户端 `enable` + `commit` 后,setup 通过 `WTextInputManagerV3::newTextInput` 信号捕获 +`WTextInputV3*`,回读真实 `wlr_text_input_v3::current_enabled` 断言为 true, +证明文本输入启用请求到达生产文本输入管道。 + +第二条连接作为 fake input method,让 `WInputMethodHelper::handleIMCommitted` 与 +`notifyLeave()` 真正跑到 `WTextInputV3`:客户端按顺序记录 `enter` / `preedit_string` / +`commit_string` / `done` / `leave`,断言「空 preedit + done 必须早于 leave」。 +去掉 `WTextInputV3::sendLeave()` 中的清空逻辑,或让它只转发非空 preedit,用例都会失败。 + +## 已知边界 / 下一项结果 + +未验证 `surrounding_text`、`content_type`、`cursor_rectangle` 等状态字段。 diff --git a/tests/protocols/wayland-text-input-unstable-v3/setup.cpp b/tests/protocols/wayland-text-input-unstable-v3/setup.cpp new file mode 100644 index 0000000000..c5c8d095c5 --- /dev/null +++ b/tests/protocols/wayland-text-input-unstable-v3/setup.cpp @@ -0,0 +1,42 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-text-input-unstable-v3.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +WTextInputManagerV3 *g_mgr = nullptr; +WTextInputV3 *g_ti = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + g_mgr = find_server_interface(server); + if (g_mgr) { + QObject::connect(g_mgr, &WTextInputManagerV3::newTextInput, + server, [](WTextInputV3 *ti) { + g_ti = ti; + }); + } +} + +void text_input_v3_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = 0; + state->enabled = 0; + + if (!g_ti) + return; + + state->valid = 1; + state->enabled = g_ti->handle()->current_enabled ? 1 : 0; +} diff --git a/tests/protocols/wayland-text-input-unstable-v3/wayland-text-input-unstable-v3.c b/tests/protocols/wayland-text-input-unstable-v3/wayland-text-input-unstable-v3.c new file mode 100644 index 0000000000..4dcc3cfdf8 --- /dev/null +++ b/tests/protocols/wayland-text-input-unstable-v3/wayland-text-input-unstable-v3.c @@ -0,0 +1,428 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end): the client maps an xdg toplevel, creates a + * zwp_text_input_v3 and enables it, while a second connection acts as a fake + * zwp_input_method_v2. The test reads back the production WTextInputV3's + * wlroots handle current_enabled field, proving the text-input enable+commit + * reached the real compositor text-input pipeline, and asserts the + * preedit/done/leave events the compositor sends back, covering both the + * empty-commit clearing path and the clear-before-leave path. + */ + +#include "wayland-text-input-unstable-v3.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "text-input-unstable-v3-client-protocol.h" +#include "input-method-unstable-v2-client-protocol.h" +#include "xdg-toplevel-client.h" + +#include +#include + +enum { TEXT_INPUT_V3_MAX_LOG = 64 }; + +struct text_input_v3_events { + unsigned int enter; + unsigned int leave; + unsigned int preedit_string; + unsigned int commit_string; + unsigned int done; + char preedit[64]; + char committed[64]; + /* + * Ordered tags of the events above, so the test can assert that the + * clearing preedit and its done arrive before leave: a client that only + * receives leave has already dropped its composing state. + */ + char log[TEXT_INPUT_V3_MAX_LOG]; + unsigned int log_len; +}; + +static void note(struct text_input_v3_events *events, char tag) +{ + if (events->log_len + 1 < sizeof(events->log)) + events->log[events->log_len++] = tag; + events->log[events->log_len] = '\0'; +} + +static void ti_enter(void *data, struct zwp_text_input_v3 *ti, struct wl_surface *surface) +{ + (void)ti; + (void)surface; + struct text_input_v3_events *events = data; + ++events->enter; + note(events, 'e'); +} + +static void ti_leave(void *data, struct zwp_text_input_v3 *ti, struct wl_surface *surface) +{ + (void)ti; + (void)surface; + struct text_input_v3_events *events = data; + ++events->leave; + note(events, 'l'); +} + +static void ti_preedit_string(void *data, struct zwp_text_input_v3 *ti, + const char *text, int32_t cursor_begin, int32_t cursor_end) +{ + (void)ti; + (void)cursor_begin; + (void)cursor_end; + struct text_input_v3_events *events = data; + ++events->preedit_string; + snprintf(events->preedit, sizeof(events->preedit), "%s", text); + note(events, 'p'); +} + +static void ti_commit_string(void *data, struct zwp_text_input_v3 *ti, const char *text) +{ + (void)ti; + struct text_input_v3_events *events = data; + ++events->commit_string; + snprintf(events->committed, sizeof(events->committed), "%s", text); + note(events, 'c'); +} + +static void ti_delete_surrounding_text(void *data, struct zwp_text_input_v3 *ti, + uint32_t before_length, uint32_t after_length) +{ + (void)data; + (void)ti; + (void)before_length; + (void)after_length; +} + +static void ti_done(void *data, struct zwp_text_input_v3 *ti, uint32_t serial) +{ + (void)ti; + (void)serial; + struct text_input_v3_events *events = data; + ++events->done; + note(events, 'd'); +} + +/* + * wayland-protocols only declares the version 2 events (action, language, + * preedit_hint) in newer releases. They still have to be filled in when the + * header declares them: libwayland aborts on a NULL listener function for an + * event the compositor sends. + */ +#ifdef ZWP_TEXT_INPUT_V3_ACTION_SINCE_VERSION +static void ti_action(void *data, struct zwp_text_input_v3 *ti, + uint32_t action, uint32_t serial) +{ + (void)data; + (void)ti; + (void)action; + (void)serial; +} + +static void ti_language(void *data, struct zwp_text_input_v3 *ti, const char *language) +{ + (void)data; + (void)ti; + (void)language; +} + +static void ti_preedit_hint(void *data, struct zwp_text_input_v3 *ti, + uint32_t start, uint32_t end, uint32_t hint) +{ + (void)data; + (void)ti; + (void)start; + (void)end; + (void)hint; +} +#endif + +static const struct zwp_text_input_v3_listener ti_listener = { + .enter = ti_enter, + .leave = ti_leave, + .preedit_string = ti_preedit_string, + .commit_string = ti_commit_string, + .delete_surrounding_text = ti_delete_surrounding_text, + .done = ti_done, +#ifdef ZWP_TEXT_INPUT_V3_ACTION_SINCE_VERSION + .action = ti_action, + .language = ti_language, + .preedit_hint = ti_preedit_hint, +#endif +}; + +struct input_method_state { + unsigned int activate; + unsigned int deactivate; + unsigned int done; + unsigned int unavailable; +}; + +static void im_activate(void *data, struct zwp_input_method_v2 *im) +{ + (void)im; + ++((struct input_method_state *)data)->activate; +} + +static void im_deactivate(void *data, struct zwp_input_method_v2 *im) +{ + (void)im; + ++((struct input_method_state *)data)->deactivate; +} + +static void im_surrounding_text(void *data, struct zwp_input_method_v2 *im, + const char *text, uint32_t cursor, uint32_t anchor) +{ + (void)data; + (void)im; + (void)text; + (void)cursor; + (void)anchor; +} + +static void im_text_change_cause(void *data, struct zwp_input_method_v2 *im, uint32_t cause) +{ + (void)data; + (void)im; + (void)cause; +} + +static void im_content_type(void *data, struct zwp_input_method_v2 *im, + uint32_t hint, uint32_t purpose) +{ + (void)data; + (void)im; + (void)hint; + (void)purpose; +} + +static void im_done(void *data, struct zwp_input_method_v2 *im) +{ + (void)im; + /* The input method echoes the number of done events back as the commit + * serial. */ + ++((struct input_method_state *)data)->done; +} + +static void im_unavailable(void *data, struct zwp_input_method_v2 *im) +{ + (void)im; + ++((struct input_method_state *)data)->unavailable; +} + +static const struct zwp_input_method_v2_listener im_listener = { + .activate = im_activate, + .deactivate = im_deactivate, + .surrounding_text = im_surrounding_text, + .text_change_cause = im_text_change_cause, + .content_type = im_content_type, + .done = im_done, + .unavailable = im_unavailable, +}; + +static int read_server(struct text_input_v3_server_state *state) { + return TEST_READ_SERVER(text_input_v3_read_server_state, state, + "text-input-v3: failed to read server state"); +} + +int protocol_test_run(const char *socket_name) { + struct client_connection app = { 0 }; + struct client_connection im_connection = { 0 }; + struct xdg_toplevel_client toplevel = { 0 }; + struct text_input_v3_events events = { 0 }; + struct input_method_state im_state = { 0 }; + struct wl_seat *seat = NULL; + struct zwp_text_input_manager_v3 *manager = NULL; + struct zwp_text_input_v3 *ti = NULL; + struct wl_seat *im_seat = NULL; + struct zwp_input_method_manager_v2 *im_manager = NULL; + struct zwp_input_method_v2 *im = NULL; + struct text_input_v3_server_state srv; + int stage = 0; + + if (!client_connect(&app, socket_name) || !client_connect(&im_connection, socket_name)) + goto failed; + + /* A mapped toplevel is what makes the compositor send enter. */ + if (!xdg_toplevel_client_create(&app, &toplevel)) + goto failed; + seat = client_bind(&app, "wl_seat", &wl_seat_interface, 1); + manager = client_bind(&app, zwp_text_input_manager_v3_interface.name, + &zwp_text_input_manager_v3_interface, + zwp_text_input_manager_v3_interface.version); + if (seat == NULL || manager == NULL) { + TEST_ERROR("text-input-v3: failed to bind seat/manager: %s\n", strerror(errno)); + goto failed; + } + + /* The input method must exist before the text input is enabled, so that + * enabling it activates the input method. */ + im_seat = client_bind(&im_connection, "wl_seat", &wl_seat_interface, 1); + im_manager = client_bind(&im_connection, "zwp_input_method_manager_v2", + &zwp_input_method_manager_v2_interface, 1); + if (im_seat == NULL || im_manager == NULL) + goto failed; + im = zwp_input_method_manager_v2_get_input_method(im_manager, im_seat); + if (im == NULL) + goto failed; + zwp_input_method_v2_add_listener(im, &im_listener, &im_state); + /* Flush the input method creation before the text input is enabled: the + * enable must find an active input method to activate. */ + if (wl_display_roundtrip(im_connection.display) < 0) + goto failed; + + ti = zwp_text_input_manager_v3_get_text_input(manager, seat); + if (ti == NULL) { + TEST_ERROR("text-input-v3: get_text_input returned NULL\n"); + goto failed; + } + zwp_text_input_v3_add_listener(ti, &ti_listener, &events); + zwp_text_input_v3_enable(ti); + zwp_text_input_v3_commit(ti); + if (wl_display_roundtrip(app.display) < 0) + goto failed; + stage = 1; + + /* E-level: the production text input must have current_enabled == true. */ + if (read_server(&srv)) + goto failed; + if (!srv.valid) { + TEST_ERROR("text-input-v3: no WTextInputV3 captured\n"); + goto failed; + } + if (!srv.enabled) { + TEST_ERROR("text-input-v3: current_enabled is false\n"); + goto failed; + } + /* Enabling the text input activates the input method. */ + if (wl_display_roundtrip(im_connection.display) < 0) + goto failed; + if (im_state.activate != 1 || im_state.unavailable) { + TEST_ERROR("text-input-v3: activate=%u unavailable=%u\n", + im_state.activate, im_state.unavailable); + goto failed; + } + if (events.enter != 1) { + TEST_ERROR("text-input-v3: enter=%u\n", events.enter); + goto failed; + } + stage = 2; + + /* A commit that sets a preedit reaches the client with its done. */ + zwp_input_method_v2_set_preedit_string(im, "pre", 0, 3); + zwp_input_method_v2_commit(im, im_state.done); + if (wl_display_roundtrip(im_connection.display) < 0 + || wl_display_roundtrip(app.display) < 0) + goto failed; + if (events.preedit_string != 1 || strcmp(events.preedit, "pre") != 0 + || events.done != 1 || strcmp(events.log, "epd") != 0) { + TEST_ERROR("text-input-v3: preedit=%u '%s' done=%u log='%s'\n", + events.preedit_string, events.preedit, events.done, events.log); + goto failed; + } + stage = 3; + + /* + * A commit that does not call set_preedit_string means "the preedit is + * empty": the client must be told to drop its composing text instead of + * keeping "pre" forever. + */ + zwp_input_method_v2_commit(im, im_state.done); + if (wl_display_roundtrip(im_connection.display) < 0 + || wl_display_roundtrip(app.display) < 0) + goto failed; + if (events.preedit_string != 2 || events.preedit[0] != '\0' + || events.done != 2 || strcmp(events.log, "epdpd") != 0) { + TEST_ERROR("text-input-v3: preedit=%u '%s' done=%u log='%s'\n", + events.preedit_string, events.preedit, events.done, events.log); + goto failed; + } + stage = 4; + + /* + * Destroying the input method leaves the focused text input, which runs + * the same sendLeave() path as a keyboard focus move to another window. + * The clearing preedit and its done must arrive before leave. + */ + zwp_input_method_v2_destroy(im); + im = NULL; + if (wl_display_roundtrip(im_connection.display) < 0 + || wl_display_roundtrip(app.display) < 0) + goto failed; + if (events.preedit_string != 3 || events.preedit[0] != '\0' + || events.done != 3 || events.leave != 1 + || strcmp(events.log, "epdpdpdl") != 0) { + TEST_ERROR("text-input-v3: preedit=%u '%s' done=%u leave=%u log='%s'\n", + events.preedit_string, events.preedit, events.done, + events.leave, events.log); + goto failed; + } + stage = 5; + + /* + * A text input the client already disabled must not get a state update on + * focus loss: the compositor may send enter again when the input method + * comes back, but no clearing preedit and no done, only leave. + */ + const unsigned int log_mark = events.log_len; + /* A fresh input method restarts its own done counter, which is the serial + * its commits have to echo. */ + im_state = (struct input_method_state){ 0 }; + im = zwp_input_method_manager_v2_get_input_method(im_manager, im_seat); + if (im == NULL) + goto failed; + zwp_input_method_v2_add_listener(im, &im_listener, &im_state); + if (wl_display_roundtrip(im_connection.display) < 0 + || wl_display_roundtrip(app.display) < 0) + goto failed; + zwp_text_input_v3_disable(ti); + zwp_text_input_v3_commit(ti); + if (wl_display_roundtrip(app.display) < 0) + goto failed; + stage = 6; + zwp_input_method_v2_destroy(im); + im = NULL; + if (wl_display_roundtrip(im_connection.display) < 0 + || wl_display_roundtrip(app.display) < 0) + goto failed; + if (events.preedit_string != 3 || events.done != 3 || events.leave != 2 + || strcmp(events.log + log_mark, "el") != 0) { + TEST_ERROR("text-input-v3: preedit=%u done=%u leave=%u log='%s'\n", + events.preedit_string, events.done, events.leave, events.log); + goto failed; + } + stage = 7; + + zwp_input_method_manager_v2_destroy(im_manager); + zwp_text_input_v3_destroy(ti); + zwp_text_input_manager_v3_destroy(manager); + wl_seat_destroy(im_seat); + wl_seat_destroy(seat); + xdg_toplevel_client_destroy(&toplevel); + client_disconnect(&im_connection); + client_disconnect(&app); + return 0; + +failed: + TEST_ERROR("text-input-v3 failure at stage %d: " + "preedit=%u '%s' commit=%u '%s' done=%u enter=%u leave=%u log='%s'\n", + stage, events.preedit_string, events.preedit, events.commit_string, + events.committed, events.done, events.enter, events.leave, events.log); + if (im) + zwp_input_method_v2_destroy(im); + if (im_manager) + zwp_input_method_manager_v2_destroy(im_manager); + if (ti) + zwp_text_input_v3_destroy(ti); + if (manager) + zwp_text_input_manager_v3_destroy(manager); + if (im_seat) + wl_seat_destroy(im_seat); + if (seat) + wl_seat_destroy(seat); + xdg_toplevel_client_destroy(&toplevel); + client_disconnect(&im_connection); + client_disconnect(&app); + return 1; +} diff --git a/tests/protocols/wayland-text-input-unstable-v3/wayland-text-input-unstable-v3.h b/tests/protocols/wayland-text-input-unstable-v3/wayland-text-input-unstable-v3.h new file mode 100644 index 0000000000..cf0f96d107 --- /dev/null +++ b/tests/protocols/wayland-text-input-unstable-v3/wayland-text-input-unstable-v3.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_TEXT_INPUT_V3_TEST_H +#define WAYLAND_TEXT_INPUT_V3_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * E-level readback: the production WTextInputManagerV3 emits newTextInput + * when the client creates a zwp_text_input_v3. The captured WTextInputV3's + * wlroots handle exposes current_enabled, which must be true after the client + * calls enable + commit, proving the text-input request reached the real + * compositor text-input pipeline. + */ +struct text_input_v3_server_state { + int valid; /* a WTextInputV3 was captured */ + int enabled; /* handle()->current_enabled */ +}; + +void text_input_v3_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_TEXT_INPUT_V3_TEST_H */ diff --git a/tests/protocols/wayland-viewporter/CMakeLists.txt b/tests/protocols/wayland-viewporter/CMakeLists.txt new file mode 100644 index 0000000000..689d2d2b28 --- /dev/null +++ b/tests/protocols/wayland-viewporter/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_viewporter + XML "${WAYLAND_PROTOCOLS_DATADIR}/stable/viewporter/viewporter.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-viewporter.c" +) diff --git a/tests/protocols/wayland-viewporter/README.md b/tests/protocols/wayland-viewporter/README.md new file mode 100644 index 0000000000..74ef9f8357 --- /dev/null +++ b/tests/protocols/wayland-viewporter/README.md @@ -0,0 +1,30 @@ +# `wayland-viewporter` 测试规范 + +## 范围 + +- XML / interface:`wp_viewporter` / `wp_viewport`(version 1,无事件) +- 测试源码:`tests/protocols/wayland-viewporter/` +- Fixture:headless output fixture + xdg-toplevel-client(64×64 solid buffer 映射) +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `wp_viewporter`(v1) | 资源创建成功 | P | +| 创建 viewport | `get_viewport(surface)` | 返回非 NULL 的 `wp_viewport` | P | +| 设置目标矩形 | `set_destination(320, 240)` + `commit` | 无协议错误 | P | +| 真实 viewport 状态 | 回读真实 `wlr_surface::current.viewport` | `has_dst` == true;`dst_width` == 320;`dst_height` == 240 | E | + +## 生产结果 + +测试创建并映射一个 64×64 的真实 xdg_toplevel,为其创建 `wp_viewport` 对象, +调用 `set_destination(320, 240)` 将缓冲缩放至 320×240 并提交。随后通过 server bridge +回读捕获的生产 `SurfaceWrapper` 的 `wlr_surface::current.viewport`,断言 `has_dst` 为 +true 且目标尺寸为 320×240。`wp_viewport.set_destination` 是双缓冲状态,在 +`wl_surface.commit` 后由 wlroots 应用到 `wlr_surface_state::viewport`,因此此断言验证 +viewport 请求确实到达了真实合成器 surface 管线。 + +## 已知边界 / 下一项结果 + +未验证 `set_source` 裁剪矩形,也未验证 viewport 对渲染输出的实际像素效果(V 级)。 diff --git a/tests/protocols/wayland-viewporter/setup.cpp b/tests/protocols/wayland-viewporter/setup.cpp new file mode 100644 index 0000000000..9ce60236ff --- /dev/null +++ b/tests/protocols/wayland-viewporter/setup.cpp @@ -0,0 +1,58 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-viewporter.h" +#include "server-bridge.h" +#include "core/shellhandler.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" + +#include +#include +#include + +namespace { +// The real mapped XdgToplevel SurfaceWrapper created by the client. +SurfaceWrapper *g_wrapper = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() == SurfaceWrapper::Type::XdgToplevel) + g_wrapper = wrapper; + }); +} + +// E-level read: report the captured production SurfaceWrapper's wl_surface +// viewport destination state. wp_viewport.set_destination is double-buffered +// state applied on commit, so wlr_surface::current.viewport must reflect the +// client's requested destination rectangle. +void viewporter_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = 0; + state->has_dst = 0; + state->dst_width = 0; + state->dst_height = 0; + + if (!g_wrapper) + return; + + auto *wsurface = g_wrapper->surface(); + if (!wsurface) + return; + + state->valid = 1; + + auto *wlr_surf = wsurface->handle(); + if (wlr_surf) { + state->has_dst = wlr_surf->current.viewport.has_dst ? 1 : 0; + state->dst_width = wlr_surf->current.viewport.dst_width; + state->dst_height = wlr_surf->current.viewport.dst_height; + } +} diff --git a/tests/protocols/wayland-viewporter/wayland-viewporter.c b/tests/protocols/wayland-viewporter/wayland-viewporter.c new file mode 100644 index 0000000000..4363e1e26f --- /dev/null +++ b/tests/protocols/wayland-viewporter/wayland-viewporter.c @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Test the wp_viewporter global created by wlr_viewporter_create in + * Treeland's WaylandServer. + * + * Coverage level E (end-to-end): the client maps a real xdg_toplevel, creates + * a wp_viewport for its surface, sets a destination rectangle (320×240), and + * commits. The test then reads back the production wlr_surface current + * viewport state over the server bridge and verifies has_dst is set with the + * correct destination dimensions, proving the viewport request reached the real + * compositor surface pipeline rather than merely surviving without a protocol + * error. + */ + +#include "wayland-viewporter.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "viewporter-client-protocol.h" + +#include +#include + +static int read_server(struct viewporter_server_state *state) { + return TEST_READ_SERVER(viewporter_read_server_state, state, + "viewporter: failed to read server state"); +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("viewporter: connect failed\n"); + return 1; + } + + struct xdg_toplevel_client tc; + if (!xdg_toplevel_client_create_with_solid_buffer(&conn, &tc, 64, 64, 0xffff0000u)) { + TEST_ERROR("viewporter: create toplevel failed\n"); + client_disconnect(&conn); + return 1; + } + + struct wp_viewporter *viewporter = + client_bind(&conn, wp_viewporter_interface.name, &wp_viewporter_interface, wp_viewporter_interface.version); + if (viewporter == NULL) { + TEST_ERROR("viewporter: failed to bind wp_viewporter: %s\n", strerror(errno)); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + + struct wp_viewport *viewport = wp_viewporter_get_viewport(viewporter, tc.surface); + if (viewport == NULL) { + TEST_ERROR("viewporter: get_viewport returned NULL\n"); + wp_viewporter_destroy(viewporter); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + + int failed = 0; + + /* Apply a destination rectangle: scale the 64×64 buffer to 320×240. */ + wp_viewport_set_destination(viewport, 320, 240); + wl_surface_commit(tc.surface); + wl_display_roundtrip(conn.display); + + /* E-level: the real production surface viewport must have dst 320×240. */ + struct viewporter_server_state srv; + if (read_server(&srv)) { + failed = 1; + } else if (!srv.valid) { + TEST_ERROR("viewporter: no mapped SurfaceWrapper captured\n"); + failed = 1; + } else if (!srv.has_dst) { + TEST_ERROR("viewporter: viewport has_dst is false after set_destination\n"); + failed = 1; + } else if (srv.dst_width != 320 || srv.dst_height != 240) { + TEST_ERROR("viewporter: expected dst 320×240, got %d×%d\n", + srv.dst_width, srv.dst_height); + failed = 1; + } + + wp_viewport_destroy(viewport); + wp_viewporter_destroy(viewporter); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-viewporter/wayland-viewporter.h b/tests/protocols/wayland-viewporter/wayland-viewporter.h new file mode 100644 index 0000000000..d2803bdca8 --- /dev/null +++ b/tests/protocols/wayland-viewporter/wayland-viewporter.h @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_VIEWPORTER_TEST_H +#define WAYLAND_VIEWPORTER_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Snapshot of the real mapped SurfaceWrapper's wl_surface viewport state, + * read on the compositor (Qt) thread. wp_viewport.set_destination is + * double-buffered state applied on wl_surface.commit. An E-level test + * verifies that the production wlr_surface current viewport has the expected + * destination dimensions, proving the request reached the real compositor + * surface pipeline rather than merely surviving without a protocol error. + */ +struct viewporter_server_state { + int valid; /* a mapped SurfaceWrapper was captured */ + int has_dst; /* wlr_surface::current.viewport.has_dst */ + int dst_width; /* wlr_surface::current.viewport.dst_width */ + int dst_height; /* wlr_surface::current.viewport.dst_height */ +}; + +/* Defined in setup.cpp; runs on the compositor thread via + * invoke_on_server_thread() and fills *data with the viewport state. */ +void viewporter_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_VIEWPORTER_TEST_H */ diff --git a/tests/protocols/wayland-xdg-activation-v1/CMakeLists.txt b/tests/protocols/wayland-xdg-activation-v1/CMakeLists.txt new file mode 100644 index 0000000000..5aa4f6c7d9 --- /dev/null +++ b/tests/protocols/wayland-xdg-activation-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_xdg_activation_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/xdg-activation/xdg-activation-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-xdg-activation-v1.c" +) diff --git a/tests/protocols/wayland-xdg-activation-v1/README.md b/tests/protocols/wayland-xdg-activation-v1/README.md new file mode 100644 index 0000000000..0207ce9d1a --- /dev/null +++ b/tests/protocols/wayland-xdg-activation-v1/README.md @@ -0,0 +1,28 @@ +# `wayland-xdg-activation-v1` 测试规范 + +## 范围 + +- XML / interface:`xdg_activation_v1` / `xdg_activation_token_v1`(version 1) +- 测试源码:`tests/protocols/wayland-xdg-activation-v1/` +- Fixture:headless output fixture + 映射 xdg-toplevel +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `xdg_activation_v1` | 资源创建成功 | P | +| 获取 token | `get_activation_token` | 收到 `done` 事件 + 非空 token | P | +| 激活 | `activate(token, surface)` | 无协议错误 | P | +| **生产回读** | — | 回读真实 `ActivationManagerInterfaceV1::activateRequested` 信号的 `disposition` == Attention | **E** | + +## 生产结果 + +测试观察 Treeland 通过 `ActivationManagerInterfaceV1` 提供的激活服务。 +客户端 `activate` 后,setup 通过 `ActivationManagerInterfaceV1::activateRequested` Qt 信号 +捕获 `TokenDisposition`,回读断言其为 Attention。该 fixture 在创建 token 时未提供 +serial,且目标 surface 尚未映射,因此对应 Treeland 的 Attention 分支,证明激活请求到达生产激活管道。 + +## 已知边界 / 下一项结果 + +仅验证该无 serial 场景的 Attention disposition;未验证携带 serial 的 Active 分支与焦点切换行为。 diff --git a/tests/protocols/wayland-xdg-activation-v1/setup.cpp b/tests/protocols/wayland-xdg-activation-v1/setup.cpp new file mode 100644 index 0000000000..038ccf0c6b --- /dev/null +++ b/tests/protocols/wayland-xdg-activation-v1/setup.cpp @@ -0,0 +1,50 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-xdg-activation-v1.h" +#include "server-bridge.h" +#include "core/shellhandler.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" +#include "modules/activation/activationmanagerinterfacev1.h" + +#include + +namespace { +ActivationManagerInterfaceV1 *g_mgr = nullptr; + +bool g_activate_requested = false; +int g_captured_disposition = 0; +WAYLIB_SERVER_NAMESPACE::WSurface *g_surface_ptr = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + g_mgr = find_server_interface(server); + if (g_mgr) { + QObject::connect(g_mgr, + &ActivationManagerInterfaceV1::activateRequested, + server, + [](const QString &token, + ActivationManagerInterfaceV1::TokenDisposition disposition, + WAYLIB_SERVER_NAMESPACE::WSurface *surface, + WAYLIB_SERVER_NAMESPACE::WSeat *seat, + WAYLIB_SERVER_NAMESPACE::WSurface *originatingSurface) { + Q_UNUSED(token); + Q_UNUSED(seat); + Q_UNUSED(originatingSurface); + g_surface_ptr = surface; + g_activate_requested = true; + g_captured_disposition = static_cast(disposition); + }); + } +} + +void xdg_activation_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = g_activate_requested ? 1 : 0; + state->surface_captured = g_surface_ptr ? 1 : 0; + state->disposition = g_captured_disposition; +} diff --git a/tests/protocols/wayland-xdg-activation-v1/wayland-xdg-activation-v1.c b/tests/protocols/wayland-xdg-activation-v1/wayland-xdg-activation-v1.c new file mode 100644 index 0000000000..14eed0f1bb --- /dev/null +++ b/tests/protocols/wayland-xdg-activation-v1/wayland-xdg-activation-v1.c @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end): the client requests an activation token, + * commits it, receives token.done with a non-empty token string, then maps a + * toplevel and calls xdg_activation_v1.activate with the token. The test + * reads back the production ActivationManagerInterfaceV1's activateRequested + * signal, verifying the disposition is Attention (1), proving the activation + * request reached the real compositor activation pipeline. + */ + +#include "wayland-xdg-activation-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "xdg-activation-v1-client-protocol.h" + +#include +#include + +/* Disposition values from ActivationManagerInterfaceV1::Disposition enum. + * The activated surface is not the focus surface, so the compositor reports + * Attention (1) rather than Active (2) or Success (0). */ +enum { DISPOSITION_INVALID = 0, DISPOSITION_ATTENTION = 1, DISPOSITION_ACTIVE = 2 }; + +struct activation_state { + int done; + char token[256]; +}; + +static void done(void *data, struct xdg_activation_token_v1 *token, const char *token_string) { + (void)token; + struct activation_state *state = data; + state->done = 1; + if (token_string != NULL) { + strncpy(state->token, token_string, sizeof(state->token) - 1); + state->token[sizeof(state->token) - 1] = '\0'; + } +} + +static const struct xdg_activation_token_v1_listener token_listener = { + .done = done, +}; + +static int read_server(struct xdg_activation_server_state *state) { + return TEST_READ_SERVER(xdg_activation_read_server_state, state, + "xdg-activation: failed to read server state"); +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("xdg-activation: connect failed\n"); + return 1; + } + + struct xdg_activation_v1 *activation = + client_bind(&conn, xdg_activation_v1_interface.name, &xdg_activation_v1_interface, xdg_activation_v1_interface.version); + if (activation == NULL) { + TEST_ERROR("xdg-activation: failed to bind: %s\n", strerror(errno)); + client_disconnect(&conn); + return 1; + } + + struct xdg_activation_token_v1 *token_req = xdg_activation_v1_get_activation_token(activation); + if (token_req == NULL) { + TEST_ERROR("xdg-activation: get_activation_token returned NULL\n"); + client_disconnect(&conn); + return 1; + } + + struct activation_state state = { 0 }; + xdg_activation_token_v1_add_listener(token_req, &token_listener, &state); + xdg_activation_token_v1_commit(token_req); + wl_display_roundtrip(conn.display); + + if (!state.done || strlen(state.token) == 0) { + TEST_ERROR("xdg-activation: no token received\n"); + xdg_activation_token_v1_destroy(token_req); + xdg_activation_v1_destroy(activation); + client_disconnect(&conn); + return 1; + } + + /* Map a toplevel to activate. */ + struct xdg_toplevel_client tc; + if (!xdg_toplevel_client_create_pending(&conn, &tc)) { + TEST_ERROR("xdg-activation: create_pending failed\n"); + xdg_activation_token_v1_destroy(token_req); + xdg_activation_v1_destroy(activation); + client_disconnect(&conn); + return 1; + } + if (!xdg_toplevel_client_complete_map(&conn, &tc)) { + TEST_ERROR("xdg-activation: complete_map failed\n"); + xdg_toplevel_client_destroy(&tc); + xdg_activation_token_v1_destroy(token_req); + xdg_activation_v1_destroy(activation); + client_disconnect(&conn); + return 1; + } + + xdg_activation_v1_activate(activation, state.token, tc.surface); + wl_display_roundtrip(conn.display); + + int failed = 0; + struct xdg_activation_server_state srv; + if (read_server(&srv)) { + failed = 1; + } else if (!srv.valid) { + TEST_ERROR("xdg-activation: no activateRequested captured\n"); + failed = 1; + } else if (!srv.surface_captured) { + TEST_ERROR("xdg-activation: no surface captured\n"); + failed = 1; + } else if (srv.disposition != DISPOSITION_ATTENTION) { + TEST_ERROR("xdg-activation: expected disposition Attention(%d), got %d\n", + DISPOSITION_ATTENTION, srv.disposition); + failed = 1; + } + + xdg_toplevel_client_destroy(&tc); + xdg_activation_token_v1_destroy(token_req); + xdg_activation_v1_destroy(activation); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-xdg-activation-v1/wayland-xdg-activation-v1.h b/tests/protocols/wayland-xdg-activation-v1/wayland-xdg-activation-v1.h new file mode 100644 index 0000000000..75a95299d6 --- /dev/null +++ b/tests/protocols/wayland-xdg-activation-v1/wayland-xdg-activation-v1.h @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_XDG_ACTIVATION_TEST_H +#define WAYLAND_XDG_ACTIVATION_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * E-level readback: the production ActivationManagerInterfaceV1 emits + * activateRequested when the client sends xdg_activation_v1.activate with a + * valid token. The captured TokenDisposition must be non-Invalid, proving the + * activation request reached the real compositor activation pipeline. + * + * TokenDisposition: 0=Invalid, 1=Attention, 2=Active + */ +struct xdg_activation_server_state { + int valid; /* activateRequested signal was captured */ + int surface_captured; /* non-null WSurface* was captured */ + int disposition; /* TokenDisposition enum value */ +}; + +void xdg_activation_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_XDG_ACTIVATION_TEST_H */ diff --git a/tests/protocols/wayland-xdg-decoration-unstable-v1/CMakeLists.txt b/tests/protocols/wayland-xdg-decoration-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..fc112c386e --- /dev/null +++ b/tests/protocols/wayland-xdg-decoration-unstable-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_xdg_decoration_unstable_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/unstable/xdg-decoration/xdg-decoration-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-xdg-decoration-unstable-v1.c" +) diff --git a/tests/protocols/wayland-xdg-decoration-unstable-v1/README.md b/tests/protocols/wayland-xdg-decoration-unstable-v1/README.md new file mode 100644 index 0000000000..c3f62a7130 --- /dev/null +++ b/tests/protocols/wayland-xdg-decoration-unstable-v1/README.md @@ -0,0 +1,34 @@ +# `wayland-xdg-decoration-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`zxdg_decoration_manager_v1` / `zxdg_toplevel_decoration_v1`(version 2) +- 测试源码:`tests/protocols/wayland-xdg-decoration-unstable-v1/` +- Fixture:headless output fixture + pixman 软件渲染 + 映射 xdg-toplevel +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `zxdg_decoration_manager_v1` | 资源创建成功 | P | +| 获取装饰 | `get_toplevel_decoration(toplevel)` | 返回非 NULL `zxdg_toplevel_decoration_v1` | P | +| 设置模式 | 分别在独立连接中 `set_mode(Client)` / `set_mode(Server)` | 收到对应 mode 的 `configure` 事件 | P | +| **生产回读** | — | 回读真实 `WXdgDecorationManager::modeBySurface(wsurface)` 返回 Client / Server | **E** | +| **代理装饰切换** | 两种模式分别映射后,由 fixture 将真实 `SurfaceProxy` 切换为 full proxy | 代理不因源窗口的装饰模式禁止显式请求的缩略图圆角 | **I** | +| **代理半径通知** | fixture 移动/缩放真实代理、切换源窗口装饰与最大化状态,并移除源窗口 | 仅实际半径变化发通知;固定半径、CSD 零半径和纯位移不发通知;空代理尺寸也不漏状态通知,装饰切换后仍正确保持宽高比 | **I** | +| **代理用户配置** | fixture 将所属 Desktop 标题栏高度设为 56 再变为 72 | 代理标题栏逻辑高度同步匹配源配置,创建/销毁代理不改变真实窗口及 surface 注册数量 | **I** | +| **代理零半径** | 显式 `setRadius(0)`,再恢复普通 CSD 默认策略 | 代理请求半径保持 0,不因继承用户配置回退为 DConfig 圆角 | **I** | +| **软件后端圆角** | `set_mode(Server)` 后映射窗口 | 真实 wrapper 有可见装饰和非空 frame、请求半径大于 0,但 `frameGeometry.radius == 0`,客户区未附加 containment mask | **E** | + +## 生产结果 + +测试观察 Treeland 通过 `WXdgDecorationManager` 提供的 toplevel 装饰服务。 +客户端分别请求 Client 和 Server 模式,断言 `configure` 载荷与生产管理器的模式回读一致。 +Server 用例还从真实窗口的 `rendererInterface()` 确认软件后端,并检查 `SurfaceWrapper` 的 +有效圆角和客户区 input mask,防止误用静态 `QQuickWindow::graphicsApi()` 启用纹理圆角裁剪。 + +## 已知边界 / 下一项结果 + +未验证已映射窗口的协议装饰模式切换、None / `unset_mode`、GPU 后端与窗口像素读回。 +代理用例检查生产圆角开关与请求值,不将软件后端测试声称为 GPU 缩略图裁剪验证。 diff --git a/tests/protocols/wayland-xdg-decoration-unstable-v1/setup.cpp b/tests/protocols/wayland-xdg-decoration-unstable-v1/setup.cpp new file mode 100644 index 0000000000..537d162a4e --- /dev/null +++ b/tests/protocols/wayland-xdg-decoration-unstable-v1/setup.cpp @@ -0,0 +1,155 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-xdg-decoration-unstable-v1.h" +#include "server-bridge.h" +#include "core/shellhandler.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" +#include "surface/surfaceproxy.h" +#include "desktop/desktopenvironment.h" +#include "treelanduserconfig.hpp" + +#include +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +SurfaceWrapper *g_wrapper = nullptr; +WXdgDecorationManager *g_decoMgr = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + g_decoMgr = find_server_interface(server); + + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() == SurfaceWrapper::Type::XdgToplevel) + g_wrapper = wrapper; + }); +} + +void xdg_decoration_read_server_state(void *data) +{ + auto *state = static_cast(data); + *state = {}; + + if (!g_wrapper) + return; + + auto *wsurface = g_wrapper->surface(); + if (!wsurface) + return; + + state->valid = 1; + state->decorated = g_wrapper->decoration() && g_wrapper->visibleDecoration() + && !g_wrapper->noCornerRadius() && !g_wrapper->frameGeometry().rect().isEmpty(); + state->requested_radius = g_wrapper->radius(); + state->frame_radius = g_wrapper->frameGeometry().radius(); + auto *window = g_wrapper->window(); + state->software_renderer = window + && window->rendererInterface()->graphicsApi() == QSGRendererInterface::Software; + auto *item = g_wrapper->surfaceItem(); + state->has_input_mask = item && item->eventItem() && item->eventItem()->containmentMask(); + + if (g_decoMgr) { + state->mode = static_cast(g_decoMgr->modeBySurface(wsurface)); + } + + auto *owner = g_wrapper->desktop(); + if (!owner) + return; + const auto windowCount = owner->windows()->rowCount(); + const auto surfaceCount = owner->surfaces()->rowCount(); + auto *config = owner->config(); + const auto titlebarHeight = config->windowTitlebarHeight(); + config->setWindowTitlebarHeight(56); + { + // Exercise real proxy geometry and preferences without registering a second window. + SurfaceProxy proxy; + proxy.setSize(QSizeF(200, 150)); + proxy.setRadius(12); + proxy.setSurface(g_wrapper); + proxy.setFullProxy(true); + auto *proxyWrapper = proxy.findChild(); + state->full_proxy_allows_rounding = proxyWrapper && !proxyWrapper->noCornerRadius() + && proxyWrapper->radius() > 0; + if (proxyWrapper) { + state->proxy_uses_source_configuration = proxyWrapper->desktop() == owner; + if (g_wrapper->titleBar()) { + state->proxy_uses_source_configuration &= proxyWrapper->titleBar() + && proxyWrapper->titleBar()->height() == 56; + config->setWindowTitlebarHeight(72); + state->proxy_uses_source_configuration &= proxyWrapper->titleBar() + && proxyWrapper->titleBar()->height() == 72; + } + state->proxy_uses_source_configuration &= owner->windows()->rowCount() == windowCount + && owner->surfaces()->rowCount() == surfaceCount; + + QSignalSpy radiusChanges(&proxy, &SurfaceProxy::radiusChanged); + proxy.setPosition(QPointF(10, 20)); + proxy.setHeight(proxy.height() + 10); + proxy.setSize(proxyWrapper->size() * 0.5); + state->proxy_radius_notifications_valid = radiusChanges.isEmpty() + && proxy.radius() == 12; + + proxy.resetRadius(); + radiusChanges.clear(); + const qreal previousRadius = proxy.radius(); + proxy.setSize(proxyWrapper->size() * 0.25); + state->proxy_radius_notifications_valid &= radiusChanges.size() + == (qFuzzyCompare(previousRadius, proxy.radius()) ? 0 : 1); + radiusChanges.clear(); + proxy.setPosition(QPointF(20, 30)); + state->proxy_radius_notifications_valid &= radiusChanges.isEmpty(); + + const bool noDecoration = g_wrapper->noDecoration(); + g_wrapper->setNoDecoration(!noDecoration); + const qreal expectedScale = qMin(qMin(proxy.width() / proxyWrapper->width(), + proxy.height() / proxyWrapper->height()), qreal(1)); + state->proxy_radius_notifications_valid &= qFuzzyCompare(proxyWrapper->scale(), expectedScale); + g_wrapper->setNoDecoration(noDecoration); + radiusChanges.clear(); + + // State changes can alter a CSD radius without changing the proxy scale. + g_wrapper->setSurfaceStateDirectly(SurfaceWrapper::State::Maximized); + state->proxy_radius_notifications_valid &= proxy.radius() == g_wrapper->radius() + && !radiusChanges.isEmpty(); + radiusChanges.clear(); + g_wrapper->setSurfaceStateDirectly(SurfaceWrapper::State::Normal); + state->proxy_radius_notifications_valid &= proxy.radius() + == (g_wrapper->noDecoration() ? 0 : g_wrapper->radius() * proxyWrapper->scale()) + && !radiusChanges.isEmpty(); + + proxy.setSize(QSizeF()); + radiusChanges.clear(); + g_wrapper->setSurfaceStateDirectly(SurfaceWrapper::State::Maximized); + state->proxy_radius_notifications_valid &= proxy.radius() == g_wrapper->radius() + && !radiusChanges.isEmpty(); + g_wrapper->setSurfaceStateDirectly(SurfaceWrapper::State::Normal); + + proxy.setRadius(0); + state->proxy_zero_radius_preserved = proxyWrapper->radius() == 0; + proxy.resetRadius(); + if (g_wrapper->noDecoration()) + state->proxy_zero_radius_preserved &= proxyWrapper->radius() == 0; + + const qreal detachedRadius = proxy.radius(); + radiusChanges.clear(); + proxy.setSurface(nullptr); + state->proxy_radius_notifications_valid &= proxy.radius() == 0 + && radiusChanges.size() == (qFuzzyIsNull(detachedRadius) ? 0 : 1); + } + } + config->setWindowTitlebarHeight(titlebarHeight); + state->proxy_uses_source_configuration &= owner->windows()->rowCount() == windowCount + && owner->surfaces()->rowCount() == surfaceCount; +} diff --git a/tests/protocols/wayland-xdg-decoration-unstable-v1/wayland-xdg-decoration-unstable-v1.c b/tests/protocols/wayland-xdg-decoration-unstable-v1/wayland-xdg-decoration-unstable-v1.c new file mode 100644 index 0000000000..6f232d7510 --- /dev/null +++ b/tests/protocols/wayland-xdg-decoration-unstable-v1/wayland-xdg-decoration-unstable-v1.c @@ -0,0 +1,139 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end): the client maps a real xdg_toplevel, attaches + * a zxdg_toplevel_decoration_v1, requests each mode, and commits. The test + * reads back the production decoration mode and verifies that software-rendered + * server-side decorations keep a square frame without a client input mask. + */ + +#include "wayland-xdg-decoration-unstable-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "xdg-decoration-unstable-v1-client-protocol.h" + +#include +#include + +struct deco_state { + int configure_count; + uint32_t mode; +}; + +static void deco_configure(void *data, struct zxdg_toplevel_decoration_v1 *deco, uint32_t mode) { + (void)deco; + struct deco_state *state = data; + state->configure_count++; + state->mode = mode; +} + +static const struct zxdg_toplevel_decoration_v1_listener deco_listener = { + .configure = deco_configure, +}; + +static int read_server(struct xdg_decoration_server_state *state) { + return TEST_READ_SERVER(xdg_decoration_read_server_state, state, + "xdg-decoration: failed to read server state"); +} + +static int test_decoration_mode(const char *socket_name, uint32_t mode) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("xdg-decoration: connect failed\n"); + return 1; + } + + struct xdg_toplevel_client tc; + if (!xdg_toplevel_client_create_pending(&conn, &tc)) { + TEST_ERROR("xdg-decoration: create_pending failed\n"); + client_disconnect(&conn); + return 1; + } + + struct zxdg_decoration_manager_v1 *manager = + client_bind(&conn, zxdg_decoration_manager_v1_interface.name, &zxdg_decoration_manager_v1_interface, zxdg_decoration_manager_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("xdg-decoration: failed to bind manager: %s\n", strerror(errno)); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + + struct deco_state state = { 0 }; + struct zxdg_toplevel_decoration_v1 *deco = + zxdg_decoration_manager_v1_get_toplevel_decoration(manager, tc.toplevel); + if (deco == NULL) { + TEST_ERROR("xdg-decoration: get_toplevel_decoration returned NULL\n"); + xdg_toplevel_client_destroy(&tc); + zxdg_decoration_manager_v1_destroy(manager); + client_disconnect(&conn); + return 1; + } + zxdg_toplevel_decoration_v1_add_listener(deco, &deco_listener, &state); + zxdg_toplevel_decoration_v1_set_mode(deco, mode); + + if (!xdg_toplevel_client_complete_map(&conn, &tc)) { + TEST_ERROR("xdg-decoration: complete_map failed\n"); + zxdg_toplevel_decoration_v1_destroy(deco); + zxdg_decoration_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + wl_display_roundtrip(conn.display); + + int failed = 0; + if (state.configure_count < 1 || state.mode != mode) { + TEST_ERROR("xdg-decoration: expected configure mode %u, got %u (count=%d)\n", + mode, state.mode, state.configure_count); + failed = 1; + } + + const int server_side = mode == ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE; + const int expected_mode = server_side ? 3 /* Server */ : 2 /* Client */; + struct xdg_decoration_server_state srv = { 0 }; + if (read_server(&srv)) { + failed = 1; + } else if (!srv.valid) { + TEST_ERROR("xdg-decoration: no mapped SurfaceWrapper captured\n"); + failed = 1; + } else if (srv.mode != expected_mode) { + TEST_ERROR("xdg-decoration: expected mode %d, got %d\n", expected_mode, srv.mode); + failed = 1; + } else if (server_side + && (!srv.software_renderer || !srv.decorated || srv.requested_radius <= 0 + || srv.frame_radius != 0 || srv.has_input_mask)) { + TEST_ERROR("xdg-decoration: software frame regression " + "(software=%d decorated=%d requested=%g frame=%g mask=%d)\n", + srv.software_renderer, srv.decorated, srv.requested_radius, + srv.frame_radius, srv.has_input_mask); + failed = 1; + } + + if (srv.valid && !srv.full_proxy_allows_rounding) { + TEST_ERROR("xdg-decoration: full proxy suppressed the thumbnail radius (mode=%u)\n", mode); + failed = 1; + } + if (srv.valid && (!srv.proxy_radius_notifications_valid + || !srv.proxy_uses_source_configuration || !srv.proxy_zero_radius_preserved)) { + TEST_ERROR("xdg-decoration: proxy regression " + "(notifications=%d owner-config=%d zero-radius=%d mode=%u)\n", + srv.proxy_radius_notifications_valid, srv.proxy_uses_source_configuration, + srv.proxy_zero_radius_preserved, mode); + failed = 1; + } + + zxdg_toplevel_decoration_v1_destroy(deco); + zxdg_decoration_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return failed; +} + +int protocol_test_run(const char *socket_name) { + int failed = test_decoration_mode(socket_name, ZXDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE); + failed |= test_decoration_mode(socket_name, ZXDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE); + return failed; +} diff --git a/tests/protocols/wayland-xdg-decoration-unstable-v1/wayland-xdg-decoration-unstable-v1.h b/tests/protocols/wayland-xdg-decoration-unstable-v1/wayland-xdg-decoration-unstable-v1.h new file mode 100644 index 0000000000..ea803487b5 --- /dev/null +++ b/tests/protocols/wayland-xdg-decoration-unstable-v1/wayland-xdg-decoration-unstable-v1.h @@ -0,0 +1,40 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_XDG_DECORATION_TEST_H +#define WAYLAND_XDG_DECORATION_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * E-level readback: the production WXdgDecorationManager reports the + * effective decoration mode for the mapped toplevel surface. The client + * requests each mode via set_mode. Server-side decoration also exposes the + * real wrapper frame and input-mask state for the software-renderer regression. + */ +struct xdg_decoration_server_state { + int valid; /* a mapped SurfaceWrapper was captured */ + int mode; /* WXdgDecorationManager::DecorationMode: 0=Undefined,1=None,2=Client,3=Server */ + int decorated; + int software_renderer; + int has_input_mask; + int full_proxy_allows_rounding; + int proxy_radius_notifications_valid; + int proxy_uses_source_configuration; + int proxy_zero_radius_preserved; + double requested_radius; + double frame_radius; +}; + +void xdg_decoration_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_XDG_DECORATION_TEST_H */ diff --git a/tests/protocols/wayland-xdg-dialog-v1/CMakeLists.txt b/tests/protocols/wayland-xdg-dialog-v1/CMakeLists.txt new file mode 100644 index 0000000000..577c2f1fae --- /dev/null +++ b/tests/protocols/wayland-xdg-dialog-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_xdg_dialog_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/xdg-dialog/xdg-dialog-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-xdg-dialog-v1.c" +) diff --git a/tests/protocols/wayland-xdg-dialog-v1/README.md b/tests/protocols/wayland-xdg-dialog-v1/README.md new file mode 100644 index 0000000000..2e6fed7ee8 --- /dev/null +++ b/tests/protocols/wayland-xdg-dialog-v1/README.md @@ -0,0 +1,28 @@ +# `wayland-xdg-dialog-v1` 测试规范 + +## 范围 + +- XML / interface:`xdg_wm_dialog_v1` / `xdg_dialog_v1`(version 1,无事件) +- 测试源码:`tests/protocols/wayland-xdg-dialog-v1/` +- Fixture:headless output fixture + xdg-toplevel-client(`create_pending` → `complete_map`) +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `xdg_wm_dialog_v1`(v1) | 资源创建成功 | P | +| 关联对话框 | `get_xdg_dialog(toplevel)` | 返回非 NULL 的 dialog | P | +| 真实模态状态翻转 | 映射 toplevel 后回读 `SurfaceWrapper`,再 `set_modal` + roundtrip 后回读 | 回读的真实 `SurfaceWrapper::modal()` 由 `false` 翻转为 `true` | E | + +## 生产结果 + +测试创建并映射一个真实 xdg_toplevel,捕获其生产 `SurfaceWrapper`,先回读确认 `modal()` 为 +`false`;随后通过 `xdg_dialog_v1.set_modal` 请求并在 roundtrip 后再次回读,断言真实 +`SurfaceWrapper::modal()` 翻转为 `true`。Treeland 经 `WXdgDialogManagerV1::surfaceModalChanged` +信号将该请求接入 `SurfaceWrapper::setModal()`,因此该断言验证请求确实到达真实合成器对象, +而非仅资源存活无协议错误。 + +## 已知边界 / 下一项结果 + +未验证模态对话框对其它窗口的实际焦点/输入抑制效果,以及 `set_unmodal` 的反向翻转(V 级像素读回亦未覆盖)。 diff --git a/tests/protocols/wayland-xdg-dialog-v1/setup.cpp b/tests/protocols/wayland-xdg-dialog-v1/setup.cpp new file mode 100644 index 0000000000..68ce90bdc8 --- /dev/null +++ b/tests/protocols/wayland-xdg-dialog-v1/setup.cpp @@ -0,0 +1,40 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-xdg-dialog-v1.h" +#include "server-bridge.h" +#include "core/shellhandler.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" + +#include + +namespace { +// The real mapped XdgToplevel SurfaceWrapper created by the client's +// xdg_toplevel_client_complete_map(). Captured from the production +// ShellHandler::surfaceWrapperAdded signal. +SurfaceWrapper *g_wrapper = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() == SurfaceWrapper::Type::XdgToplevel) + g_wrapper = wrapper; + }); +} + +// E-level read: report whether the captured production SurfaceWrapper is modal. +// Treeland flips this via SurfaceWrapper::setModal() in response to the +// WXdgDialogManagerV1::surfaceModalChanged signal that fires on a client +// xdg_dialog_v1.set_modal request. +void xdg_dialog_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = (g_wrapper != nullptr); + state->modal = (g_wrapper && g_wrapper->modal()) ? 1 : 0; +} diff --git a/tests/protocols/wayland-xdg-dialog-v1/wayland-xdg-dialog-v1.c b/tests/protocols/wayland-xdg-dialog-v1/wayland-xdg-dialog-v1.c new file mode 100644 index 0000000000..b2372b973c --- /dev/null +++ b/tests/protocols/wayland-xdg-dialog-v1/wayland-xdg-dialog-v1.c @@ -0,0 +1,115 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Test the xdg_wm_dialog_v1 global served by Treeland (WXdgDialogManagerV1). + * The interface has no events; the client attaches a dialog object to a real + * mapped xdg_toplevel and marks it modal. + * + * Coverage level E (end-to-end): the test does not merely assert the resource + * survives without a protocol error. It reads the production SurfaceWrapper's + * modal flag back over the server bridge (SurfaceWrapper::modal(), which + * Treeland flips via SurfaceWrapper::setModal() in response to the + * WXdgDialogManagerV1::surfaceModalChanged signal fired by set_modal) and + * verifies it transitions false -> true, proving the request reaches the real + * compositor object. + */ + +#include "wayland-xdg-dialog-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "xdg-dialog-v1-client-protocol.h" + +#include +#include + +static int read_modal(struct xdg_dialog_server_state *state) { + memset(state, 0, sizeof(*state)); + if (invoke_on_server_thread(xdg_dialog_read_server_state, state) == 0) { + TEST_ERROR("xdg-dialog: failed to read server state\n"); + return 1; + } + return 0; +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("xdg-dialog: connect failed\n"); + return 1; + } + + /* + * Create and map a real xdg_toplevel first so the production + * SurfaceWrapper exists before set_modal is processed. + */ + struct xdg_toplevel_client tc; + if (!xdg_toplevel_client_create_pending(&conn, &tc)) { + TEST_ERROR("xdg-dialog: create_pending failed\n"); + client_disconnect(&conn); + return 1; + } + if (!xdg_toplevel_client_complete_map(&conn, &tc)) { + TEST_ERROR("xdg-dialog: complete_map failed\n"); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + wl_display_roundtrip(conn.display); + + int failed = 0; + + /* Baseline: the freshly-mapped toplevel is not modal. */ + struct xdg_dialog_server_state before; + if (read_modal(&before)) { + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + if (!before.valid) { + TEST_ERROR("xdg-dialog: no mapped SurfaceWrapper captured\n"); + failed = 1; + } else if (before.modal) { + TEST_ERROR("xdg-dialog: wrapper already modal before set_modal\n"); + failed = 1; + } + + struct xdg_wm_dialog_v1 *manager = NULL; + struct xdg_dialog_v1 *dialog = NULL; + if (!failed) { + manager = client_bind(&conn, xdg_wm_dialog_v1_interface.name, &xdg_wm_dialog_v1_interface, xdg_wm_dialog_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("xdg-dialog: failed to bind xdg_wm_dialog_v1: %s\n", strerror(errno)); + failed = 1; + } + } + if (!failed) { + dialog = xdg_wm_dialog_v1_get_xdg_dialog(manager, tc.toplevel); + if (dialog == NULL) { + TEST_ERROR("xdg-dialog: get_xdg_dialog returned NULL\n"); + failed = 1; + } + } + if (!failed) { + xdg_dialog_v1_set_modal(dialog); + wl_display_roundtrip(conn.display); + + /* E-level: the real SurfaceWrapper must now be modal. */ + struct xdg_dialog_server_state after; + if (read_modal(&after)) { + failed = 1; + } else if (!after.modal) { + TEST_ERROR("xdg-dialog: SurfaceWrapper::modal() is false after set_modal\n"); + failed = 1; + } + } + + if (dialog != NULL) + xdg_dialog_v1_destroy(dialog); + if (manager != NULL) + xdg_wm_dialog_v1_destroy(manager); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-xdg-dialog-v1/wayland-xdg-dialog-v1.h b/tests/protocols/wayland-xdg-dialog-v1/wayland-xdg-dialog-v1.h new file mode 100644 index 0000000000..4a022fdf82 --- /dev/null +++ b/tests/protocols/wayland-xdg-dialog-v1/wayland-xdg-dialog-v1.h @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_XDG_DIALOG_TEST_H +#define WAYLAND_XDG_DIALOG_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Snapshot of the real mapped SurfaceWrapper's modal flag, read on the + * compositor (Qt) thread. Treeland wires WXdgDialogManagerV1::surfaceModalChanged + * to SurfaceWrapper::setModal(), so an end-to-end (E-level) test verifies that a + * client xdg_dialog_v1.set_modal request actually flips the production wrapper's + * modal state, rather than only surviving without a protocol error. + */ +struct xdg_dialog_server_state { + int valid; /* a mapped XdgToplevel SurfaceWrapper was captured */ + int modal; /* SurfaceWrapper::modal() */ +}; + +/* Defined in setup.cpp; runs on the compositor thread via + * invoke_on_server_thread() and fills *data with the wrapper's modal flag. */ +void xdg_dialog_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_XDG_DIALOG_TEST_H */ diff --git a/tests/protocols/wayland-xdg-foreign-unstable-v2/CMakeLists.txt b/tests/protocols/wayland-xdg-foreign-unstable-v2/CMakeLists.txt new file mode 100644 index 0000000000..bcc7dd67e7 --- /dev/null +++ b/tests/protocols/wayland-xdg-foreign-unstable-v2/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_xdg_foreign_unstable_v2 + XML "${WAYLAND_PROTOCOLS_DATADIR}/unstable/xdg-foreign/xdg-foreign-unstable-v2.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-xdg-foreign-unstable-v2.c" +) diff --git a/tests/protocols/wayland-xdg-foreign-unstable-v2/README.md b/tests/protocols/wayland-xdg-foreign-unstable-v2/README.md new file mode 100644 index 0000000000..c50e515ba8 --- /dev/null +++ b/tests/protocols/wayland-xdg-foreign-unstable-v2/README.md @@ -0,0 +1,38 @@ +# `wayland-xdg-foreign-unstable-v2` 测试规范 + +## 范围 + +- XML / interface:`zxdg_exporter_v2` / `zxdg_exported_v2` / `zxdg_importer_v2` / `zxdg_imported_v2`(version 1) +- 测试源码:`tests/protocols/wayland-xdg-foreign-unstable-v2/` +- Fixture:headless output fixture + ShellHandler 捕获两个 toplevel SurfaceWrapper +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `zxdg_exporter_v2` + `zxdg_importer_v2`(v1) | 资源创建成功 | P | +| 导出表面 | `export_toplevel(surface)` 后 roundtrip | 收到 `handle` 事件(非空 handle 字符串) | P | +| 导入表面 | `import_toplevel(handle)` | 返回非 NULL 的 `zxdg_imported_v2` | P | +| 设置父级 | `set_parent_of(imported, child_surface)` 后回读 | 真实 `WXdgToplevelSurface::parentXdgSurface()` 在子窗口上非空 | E | + +## 生产结果 + +测试创建两个 mapped xdg_toplevel(父窗口 + 子窗口),通过 `export_toplevel` +导出父窗口获得非空 handle,以该 handle `import_toplevel` 成功导入, +然后调用 `set_parent_of(imported, child_surface)` 设置子窗口的父级。 + +`set_parent_of` 触发 wlroots 的 `wlr_xdg_toplevel_set_parent`,在真实的 +`wlr_xdg_toplevel::parent` 上建立父子关系并发出 `events.set_parent` 信号。 +`WXdgToplevelSurface` 监听该信号,`parentXdgSurface()` 直接读取 +`handle()->parent`。测试回读子窗口的 `parentXdgSurface()`,断言非空, +证明 xdg-foreign-v2 的 `set_parent_of` 请求到达真实合成器并在真实 toplevel +对象上建立了父子关系。 + +`wlr_xdg_foreign_registry` 为 `WaylandServer::init()` 中的局部变量,未存储为成员, +但协议流经 `wlr_xdg_foreign_v2` → `wlr_xdg_toplevel_set_parent` → +`WXdgToplevelSurface` 链路,父子关系可直接从 `WXdgToplevelSurface` 回读。 + +## 已知边界 / 下一项结果 + +未验证无效 handle 的 `destroyed` 事件语义,也未验证父窗口 unmap 后子窗口父级被清除的路径。 diff --git a/tests/protocols/wayland-xdg-foreign-unstable-v2/setup.cpp b/tests/protocols/wayland-xdg-foreign-unstable-v2/setup.cpp new file mode 100644 index 0000000000..4ffb3380fa --- /dev/null +++ b/tests/protocols/wayland-xdg-foreign-unstable-v2/setup.cpp @@ -0,0 +1,65 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-xdg-foreign-unstable-v2.h" +#include "server-bridge.h" +#include "core/shellhandler.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +SurfaceWrapper *g_parentWrapper = nullptr; +SurfaceWrapper *g_childWrapper = nullptr; +int g_wrapperCount = 0; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + // Capture two XdgToplevel SurfaceWrappers: the first is the parent + // (exported), the second is the child (set_parent_of target). + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() != SurfaceWrapper::Type::XdgToplevel) + return; + if (g_wrapperCount == 0) + g_parentWrapper = wrapper; + else if (g_wrapperCount == 1) + g_childWrapper = wrapper; + ++g_wrapperCount; + }); +} + +void xdg_foreign_v2_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = 0; + state->has_parent = 0; + + if (!g_parentWrapper || !g_childWrapper) + return; + + state->valid = 1; + + // E-level: read back the real production WXdgToplevelSurface::parentXdgSurface() + // on the child. When the client calls set_parent_of via xdg-foreign-v2, + // wlroots calls wlr_xdg_toplevel_set_parent which sets toplevel->parent and + // emits events.set_parent. WXdgToplevelSurface listens to this signal and + // parentXdgSurface() reads handle()->parent directly. + auto *shell = g_childWrapper->shellSurface(); + if (!shell) + return; + + auto *toplevel = dynamic_cast(shell); + if (!toplevel) + return; + + state->has_parent = toplevel->parentXdgSurface() != nullptr; +} diff --git a/tests/protocols/wayland-xdg-foreign-unstable-v2/wayland-xdg-foreign-unstable-v2.c b/tests/protocols/wayland-xdg-foreign-unstable-v2/wayland-xdg-foreign-unstable-v2.c new file mode 100644 index 0000000000..c6ca851c2c --- /dev/null +++ b/tests/protocols/wayland-xdg-foreign-unstable-v2/wayland-xdg-foreign-unstable-v2.c @@ -0,0 +1,146 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Coverage level E (end-to-end): the client creates two mapped xdg_toplevel + * surfaces — a parent and a child. It exports the parent via + * zxdg_exporter_v2, imports the handle via zxdg_importer_v2, then calls + * set_parent_of on the child surface. The test reads back the real + * production WXdgToplevelSurface::parentXdgSurface() on the child, verifying + * it is non-null, proving the xdg-foreign-v2 set_parent_of request reached + * the real compositor and established the parent-child relationship on the + * real toplevel objects. + */ + +#include "wayland-xdg-foreign-unstable-v2.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "xdg-foreign-unstable-v2-client-protocol.h" + +#include +#include + +struct export_state { + int handle_received; + char handle[256]; +}; + +static void exported_handle(void *data, struct zxdg_exported_v2 *exported, const char *handle) { + (void)exported; + struct export_state *state = data; + state->handle_received = 1; + if (handle != NULL) { + strncpy(state->handle, handle, sizeof(state->handle) - 1); + state->handle[sizeof(state->handle) - 1] = '\0'; + } +} + +static const struct zxdg_exported_v2_listener exported_listener = { + .handle = exported_handle, +}; + +static void imported_destroyed(void *data, struct zxdg_imported_v2 *imported) { + (void)data; + (void)imported; +} + +static const struct zxdg_imported_v2_listener imported_listener = { + .destroyed = imported_destroyed, +}; + +static int read_server(struct xdg_foreign_v2_server_state *state) { + return TEST_READ_SERVER(xdg_foreign_v2_read_server_state, state, + "xdg-foreign-v2: failed to read server state"); +} + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("xdg-foreign-v2: connect failed\n"); + return 1; + } + + /* 1. Create and map the parent toplevel. */ + struct xdg_toplevel_client tc_parent; + if (!xdg_toplevel_client_create(&conn, &tc_parent)) { + TEST_ERROR("xdg-foreign-v2: failed to create parent toplevel\n"); + client_disconnect(&conn); + return 1; + } + + /* 2. Create and map the child toplevel. */ + struct xdg_toplevel_client tc_child; + if (!xdg_toplevel_client_create(&conn, &tc_child)) { + TEST_ERROR("xdg-foreign-v2: failed to create child toplevel\n"); + xdg_toplevel_client_destroy(&tc_parent); + client_disconnect(&conn); + return 1; + } + + /* 3. Export the parent surface and obtain the handle. */ + struct export_state state = { 0 }; + struct zxdg_exporter_v2 *exporter = + client_bind(&conn, zxdg_exporter_v2_interface.name, &zxdg_exporter_v2_interface, zxdg_exporter_v2_interface.version); + struct zxdg_importer_v2 *importer = + client_bind(&conn, zxdg_importer_v2_interface.name, &zxdg_importer_v2_interface, zxdg_importer_v2_interface.version); + if (exporter == NULL || importer == NULL) { + TEST_ERROR("xdg-foreign-v2: failed to bind exporter/importer: %s\n", strerror(errno)); + xdg_toplevel_client_destroy(&tc_child); + xdg_toplevel_client_destroy(&tc_parent); + client_disconnect(&conn); + return 1; + } + + struct zxdg_exported_v2 *exported = + zxdg_exporter_v2_export_toplevel(exporter, tc_parent.surface); + if (exported == NULL) { + TEST_ERROR("xdg-foreign-v2: export_toplevel returned NULL\n"); + xdg_toplevel_client_destroy(&tc_child); + xdg_toplevel_client_destroy(&tc_parent); + client_disconnect(&conn); + return 1; + } + zxdg_exported_v2_add_listener(exported, &exported_listener, &state); + wl_display_roundtrip(conn.display); + + int failed = 0; + if (!state.handle_received || state.handle[0] == '\0') { + TEST_ERROR("xdg-foreign-v2: no handle event / empty handle\n"); + failed = 1; + } else { + /* 4. Import the handle and set the child's parent. */ + struct zxdg_imported_v2 *imported = + zxdg_importer_v2_import_toplevel(importer, state.handle); + if (imported == NULL) { + TEST_ERROR("xdg-foreign-v2: import_toplevel returned NULL\n"); + failed = 1; + } else { + zxdg_imported_v2_add_listener(imported, &imported_listener, NULL); + zxdg_imported_v2_set_parent_of(imported, tc_child.surface); + wl_display_roundtrip(conn.display); + + /* 5. E-level: read back the production parent-child relationship. */ + struct xdg_foreign_v2_server_state srv; + if (read_server(&srv)) { + failed = 1; + } else if (!srv.valid) { + TEST_ERROR("xdg-foreign-v2: SurfaceWrappers not captured\n"); + failed = 1; + } else if (!srv.has_parent) { + TEST_ERROR("xdg-foreign-v2: child toplevel has no parent in production\n"); + failed = 1; + } + + zxdg_imported_v2_destroy(imported); + } + } + + zxdg_exported_v2_destroy(exported); + xdg_toplevel_client_destroy(&tc_child); + xdg_toplevel_client_destroy(&tc_parent); + zxdg_importer_v2_destroy(importer); + zxdg_exporter_v2_destroy(exporter); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-xdg-foreign-unstable-v2/wayland-xdg-foreign-unstable-v2.h b/tests/protocols/wayland-xdg-foreign-unstable-v2/wayland-xdg-foreign-unstable-v2.h new file mode 100644 index 0000000000..317fd33399 --- /dev/null +++ b/tests/protocols/wayland-xdg-foreign-unstable-v2/wayland-xdg-foreign-unstable-v2.h @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_XDG_FOREIGN_TEST_H +#define WAYLAND_XDG_FOREIGN_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * E-level readback: after the client calls set_parent_of on an imported + * surface, the production WXdgToplevelSurface for the child surface must + * report a non-null parentXdgSurface(). This proves the real + * wlr_xdg_toplevel_set_parent path was exercised through the xdg-foreign-v2 + * protocol, establishing the parent-child relationship on the real + * compositor's toplevel objects. + */ +struct xdg_foreign_v2_server_state { + int valid; /* both parent and child SurfaceWrappers captured */ + int has_parent; /* child toplevel has parent set in production */ +}; + +void xdg_foreign_v2_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_XDG_FOREIGN_TEST_H */ diff --git a/tests/protocols/wayland-xdg-output-unstable-v1/CMakeLists.txt b/tests/protocols/wayland-xdg-output-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..5a8a75550d --- /dev/null +++ b/tests/protocols/wayland-xdg-output-unstable-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_xdg_output_unstable_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/unstable/xdg-output/xdg-output-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-xdg-output-unstable-v1.c" +) diff --git a/tests/protocols/wayland-xdg-output-unstable-v1/README.md b/tests/protocols/wayland-xdg-output-unstable-v1/README.md new file mode 100644 index 0000000000..5929925c92 --- /dev/null +++ b/tests/protocols/wayland-xdg-output-unstable-v1/README.md @@ -0,0 +1,30 @@ +# `wayland-xdg-output-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`zxdg_output_manager_v1` / `zxdg_output_v1`(version 3) +- 测试源码:`tests/protocols/wayland-xdg-output-unstable-v1/` +- Fixture:测试启动时提供的 `HEADLESS-1` headless output +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `zxdg_output_manager_v1` | 资源创建成功 | P | +| 输出逻辑几何 | `get_xdg_output(wl_output)` 后 roundtrip | 收到 `logical_position`、`logical_size` 与 `wl_output.done` 事件 | P | +| 真实输出几何一致 | 经 `invoke_on_server_thread` 回读真实 `WOutput` | 客户端 `logical_position`/`logical_size` 与真实 `WOutput::position()`/`effectiveSize()` 完全一致 | E | + +## 生产结果 + +测试观察 Treeland 通过 `WXdgOutputManager` 包装器为真实 `wl_output` 资源发布的逻辑几何, +并跨进程回读合成器内真实 `WOutput` 的布局几何(`position()`/`effectiveSize()`, +二者分别读取 `wlr_output_layout_output->x,y` 与 `wlr_output_effective_resolution`, +正是 `WXdgOutputManager` 用以填充 `logical_position`/`logical_size` 的同一 wlroots 状态)。 +客户端收到的协议事件与该真实生产输出对象的几何逐字段相等,证明 Treeland 的 xdg-output +实现正确接入了其输出布局——而不仅是事件载荷非零。 + +## 已知边界 / 下一项结果 + +仅验证单个 headless 输出的静态几何与真实 `WOutput` 的一致性。未验证多输出布局变化后 +`done` 的批量发送语义、输出缩放/变换下的逻辑几何,以及输出热插拔时的几何更新(V 级像素读回亦未覆盖)。 diff --git a/tests/protocols/wayland-xdg-output-unstable-v1/setup.cpp b/tests/protocols/wayland-xdg-output-unstable-v1/setup.cpp new file mode 100644 index 0000000000..baec043552 --- /dev/null +++ b/tests/protocols/wayland-xdg-output-unstable-v1/setup.cpp @@ -0,0 +1,55 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-xdg-output-unstable-v1.h" +#include "core/rootsurfacecontainer.h" +#include "output/output.h" +#include "core/waylandserver.h" + +#include +#include + +#include +#include + +static QPointer g_woutput; + +void protocol_test_setup(WaylandServer *) +{ + // This fixture relies on exactly one output: HEADLESS-1, which the headless + // backend creates automatically (WLR_HEADLESS_OUTPUTS defaults to 1) and + // OutputManager registers in RootSurfaceContainer once its per-output + // DConfig finishes initializing. The wl_output global only appears after + // that output is enabled and auto-added to the layout, so protocol_test_ready + // waits for that async chain. Do not resolve the output here: at + // protocol_test_setup time it has not necessarily been registered yet. +} + +extern "C" bool protocol_test_ready(WaylandServer *server) +{ + auto *output = server->rootSurfaceContainer()->primaryOutput(); + if (!output || !output->output()) + return false; + + g_woutput = output->output(); + return server->rootSurfaceContainer()->outputLayout()->outputs().contains(g_woutput); +} + +// E-level read: resolve the real WOutput that backs the headless output and +// return its layout geometry. This reads the identical wlroots state that +// WXdgOutputManager uses to populate logical_position / logical_size, so the +// client-side protocol events must match these values exactly. +void xdg_output_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = 0; + + WOutput *woutput = g_woutput.data(); + if (!woutput) + return; + + state->valid = 1; + state->x = woutput->position().x(); + state->y = woutput->position().y(); + state->width = woutput->effectiveSize().width(); + state->height = woutput->effectiveSize().height(); +} diff --git a/tests/protocols/wayland-xdg-output-unstable-v1/wayland-xdg-output-unstable-v1.c b/tests/protocols/wayland-xdg-output-unstable-v1/wayland-xdg-output-unstable-v1.c new file mode 100644 index 0000000000..2efb936c0d --- /dev/null +++ b/tests/protocols/wayland-xdg-output-unstable-v1/wayland-xdg-output-unstable-v1.c @@ -0,0 +1,208 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Test the zxdg_output_manager_v1 global that Treeland serves through its + * WXdgOutputManager wrapper. The test binds the startup wl_output, obtains an + * xdg_output for it, and receives logical_position / logical_size followed by + * wl_output.done. + * + * Coverage level E (end-to-end): instead of asserting hard-coded numbers, the + * client reads the *real* headless WOutput's layout geometry back over the + * server bridge (WOutput::position() / WOutput::effectiveSize(), which read the + * exact wlroots state WXdgOutputManager uses) and verifies the protocol events + * match the live production output object. + */ + +#include "wayland-xdg-output-unstable-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-output-unstable-v1-client-protocol.h" + +#include +#include + +struct xdg_output_state { + int has_position; + int32_t x; + int32_t y; + int has_size; + int32_t width; + int32_t height; + int output_done; +}; + +static void logical_position(void *data, struct zxdg_output_v1 *output, int32_t x, int32_t y) { + (void)output; + struct xdg_output_state *state = data; + state->has_position = 1; + state->x = x; + state->y = y; +} + +static void logical_size(void *data, struct zxdg_output_v1 *output, int32_t width, int32_t height) { + (void)output; + struct xdg_output_state *state = data; + state->has_size = 1; + state->width = width; + state->height = height; +} + +static void output_done(void *data, struct wl_output *output) +{ + (void)output; + struct xdg_output_state *state = data; + state->output_done = 1; +} + +static void output_geometry(void *data, struct wl_output *output, int32_t x, int32_t y, + int32_t physical_width, int32_t physical_height, int32_t subpixel, const char *make, + const char *model, int32_t transform) +{ + (void)data; + (void)output; + (void)x; + (void)y; + (void)physical_width; + (void)physical_height; + (void)subpixel; + (void)make; + (void)model; + (void)transform; +} + +static void output_mode(void *data, struct wl_output *output, uint32_t flags, int32_t width, + int32_t height, int32_t refresh) +{ + (void)data; + (void)output; + (void)flags; + (void)width; + (void)height; + (void)refresh; +} + +static void output_scale(void *data, struct wl_output *output, int32_t factor) +{ + (void)data; + (void)output; + (void)factor; +} + +static void output_name(void *data, struct wl_output *output, const char *name) +{ + (void)data; + (void)output; + (void)name; +} + +static void output_description(void *data, struct wl_output *output, const char *description) +{ + (void)data; + (void)output; + (void)description; +} + +static void name(void *data, struct zxdg_output_v1 *output, const char *name) { + (void)data; + (void)output; + (void)name; +} + +static void description(void *data, struct zxdg_output_v1 *output, const char *description) { + (void)data; + (void)output; + (void)description; +} + +static const struct zxdg_output_v1_listener xdg_output_listener = { + .logical_position = logical_position, + .logical_size = logical_size, + .name = name, + .description = description, +}; + +static const struct wl_output_listener output_listener = { + .geometry = output_geometry, + .mode = output_mode, + .done = output_done, + .scale = output_scale, + .name = output_name, + .description = output_description, +}; + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("xdg-output: connect failed\n"); + return 1; + } + + struct xdg_output_state state = { 0 }; + struct wl_output *output = client_bind(&conn, wl_output_interface.name, + &wl_output_interface, wl_output_interface.version); + if (output == NULL) { + TEST_ERROR("xdg-output: startup wl_output global is unavailable\n"); + client_disconnect(&conn); + return 1; + } + wl_output_add_listener(output, &output_listener, &state); + + struct zxdg_output_manager_v1 *manager = + client_bind(&conn, zxdg_output_manager_v1_interface.name, &zxdg_output_manager_v1_interface, zxdg_output_manager_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("xdg-output: failed to bind zxdg_output_manager_v1: %s\n", strerror(errno)); + wl_output_destroy(output); + client_disconnect(&conn); + return 1; + } + + struct zxdg_output_v1 *xdg_output = zxdg_output_manager_v1_get_xdg_output(manager, output); + if (xdg_output == NULL) { + TEST_ERROR("xdg-output: get_xdg_output returned NULL\n"); + zxdg_output_manager_v1_destroy(manager); + wl_output_destroy(output); + client_disconnect(&conn); + return 1; + } + zxdg_output_v1_add_listener(xdg_output, &xdg_output_listener, &state); + + wl_display_roundtrip(conn.display); + + /* + * E-level: read the real headless WOutput's geometry on the compositor + * thread and cross-check it against the protocol events just received. + */ + struct xdg_output_server_state server = { 0 }; + if (invoke_on_server_thread(xdg_output_read_server_state, &server) == 0) { + TEST_ERROR("xdg-output: failed to read server output state\n"); + zxdg_output_v1_destroy(xdg_output); + zxdg_output_manager_v1_destroy(manager); + wl_output_destroy(output); + client_disconnect(&conn); + return 1; + } + + int failed = 0; + if (!state.output_done) { + TEST_ERROR("xdg-output: no wl_output.done event received\n"); + failed = 1; + } else if (!server.valid) { + TEST_ERROR("xdg-output: no real WOutput found in the layout\n"); + failed = 1; + } else if (!state.has_position || state.x != server.x || state.y != server.y) { + TEST_ERROR("xdg-output: logical_position %d,%d != real WOutput %d,%d\n", state.x, + state.y, server.x, server.y); + failed = 1; + } else if (!state.has_size || state.width != server.width || state.height != server.height) { + TEST_ERROR("xdg-output: logical_size %dx%d != real WOutput %dx%d\n", state.width, + state.height, server.width, server.height); + failed = 1; + } + + zxdg_output_v1_destroy(xdg_output); + zxdg_output_manager_v1_destroy(manager); + wl_output_destroy(output); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-xdg-output-unstable-v1/wayland-xdg-output-unstable-v1.h b/tests/protocols/wayland-xdg-output-unstable-v1/wayland-xdg-output-unstable-v1.h new file mode 100644 index 0000000000..b91e896a5d --- /dev/null +++ b/tests/protocols/wayland-xdg-output-unstable-v1/wayland-xdg-output-unstable-v1.h @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_XDG_OUTPUT_TEST_H +#define WAYLAND_XDG_OUTPUT_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Snapshot of the real headless WOutput's layout geometry, read on the + * compositor (Qt) thread and compared against the logical_position / + * logical_size events the client received from zxdg_output_v1. + * + * xdg-output sends logical_position = wlr_output_layout_output->{x,y} and + * logical_size = wlr_output_effective_resolution(); WOutput::position() and + * WOutput::effectiveSize() read exactly those same wlroots values, so an + * end-to-end (E-level) test cross-checks the protocol events against the live + * production output object instead of asserting hard-coded numbers. + */ +struct xdg_output_server_state { + int valid; /* fixture WOutput is still live */ + int32_t x; /* WOutput::position().x() == layout x */ + int32_t y; /* WOutput::position().y() == layout y */ + int32_t width; /* WOutput::effectiveSize().width() */ + int32_t height; /* WOutput::effectiveSize().height() */ +}; + +/* Defined in setup.cpp; runs on the compositor thread via + * invoke_on_server_thread() and fills *data with the real output geometry. */ +void xdg_output_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_XDG_OUTPUT_TEST_H */ diff --git a/tests/protocols/wayland-xdg-toplevel-tag-v1/CMakeLists.txt b/tests/protocols/wayland-xdg-toplevel-tag-v1/CMakeLists.txt new file mode 100644 index 0000000000..3c017016e9 --- /dev/null +++ b/tests/protocols/wayland-xdg-toplevel-tag-v1/CMakeLists.txt @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +treeland_add_protocol_test( + NAME wayland_xdg_toplevel_tag_v1 + XML "${WAYLAND_PROTOCOLS_DATADIR}/staging/xdg-toplevel-tag/xdg-toplevel-tag-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wayland-xdg-toplevel-tag-v1.c" +) diff --git a/tests/protocols/wayland-xdg-toplevel-tag-v1/README.md b/tests/protocols/wayland-xdg-toplevel-tag-v1/README.md new file mode 100644 index 0000000000..2ccb3196b0 --- /dev/null +++ b/tests/protocols/wayland-xdg-toplevel-tag-v1/README.md @@ -0,0 +1,26 @@ +# `wayland-xdg-toplevel-tag-v1` 测试规范 + +## 范围 + +- XML / interface:`xdg_toplevel_tag_manager_v1`(version 1,仅有请求、无事件/无资源) +- 测试源码:`tests/protocols/wayland-xdg-toplevel-tag-v1/` +- Fixture:headless output fixture + xdg-toplevel-client(`create_pending` → `complete_map`) +- 覆盖等级:E + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 绑定全局 | 绑定 `xdg_toplevel_tag_manager_v1`(v1) | 资源创建成功 | P | +| 真实标签落库 | `set_toplevel_tag(toplevel, "treeland-tag-test")` + 映射 + roundtrip 后回读 | 回读的真实 `WXdgToplevelSurface::tag()` 等于客户端设置值 | E | + +## 生产结果 + +测试创建并映射一个真实 xdg_toplevel,捕获其生产 `SurfaceWrapper`,通过 `set_toplevel_tag` +设置标签 `"treeland-tag-test"`,并在 roundtrip 后经服务端桥回读真实 +`WXdgToplevelSurface::tag()`(Treeland 的 `WXdgToplevelTagManagerV1` 经 `setTag()` 写入该对象), +断言其等于客户端设置值,证明请求确实写入真实合成器对象,而非仅被接受无协议错误。 + +## 已知边界 / 下一项结果 + +未验证 tag 在 Treeland 任务栏/窗口管理中的实际路由与展示,以及 `set_toplevel_description` 的回读(V 级像素读回亦未覆盖)。 diff --git a/tests/protocols/wayland-xdg-toplevel-tag-v1/setup.cpp b/tests/protocols/wayland-xdg-toplevel-tag-v1/setup.cpp new file mode 100644 index 0000000000..3549876077 --- /dev/null +++ b/tests/protocols/wayland-xdg-toplevel-tag-v1/setup.cpp @@ -0,0 +1,54 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "wayland-xdg-toplevel-tag-v1.h" +#include "server-bridge.h" +#include "core/shellhandler.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" + +#include +#include + +#include + +namespace { +// The real mapped XdgToplevel SurfaceWrapper created by the client's +// xdg_toplevel_client_complete_map(). +SurfaceWrapper *g_wrapper = nullptr; +} + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); + + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() == SurfaceWrapper::Type::XdgToplevel) + g_wrapper = wrapper; + }); +} + +// E-level read: report the production WXdgToplevelSurface's tag. Treeland's +// WXdgToplevelTagManagerV1 stores the client's set_toplevel_tag value here via +// WXdgToplevelSurface::setTag(). +void xdg_toplevel_tag_read_server_state(void *data) +{ + auto *state = static_cast(data); + state->valid = 0; + state->tag[0] = '\0'; + + if (!g_wrapper) + return; + + auto *xdgSurface = + qobject_cast(g_wrapper->shellSurface()); + if (!xdgSurface) + return; + + state->valid = 1; + const QByteArray utf8 = xdgSurface->tag().toUtf8(); + std::strncpy(state->tag, utf8.constData(), sizeof(state->tag) - 1); + state->tag[sizeof(state->tag) - 1] = '\0'; +} diff --git a/tests/protocols/wayland-xdg-toplevel-tag-v1/wayland-xdg-toplevel-tag-v1.c b/tests/protocols/wayland-xdg-toplevel-tag-v1/wayland-xdg-toplevel-tag-v1.c new file mode 100644 index 0000000000..575ac48144 --- /dev/null +++ b/tests/protocols/wayland-xdg-toplevel-tag-v1/wayland-xdg-toplevel-tag-v1.c @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + * + * Test the xdg_toplevel_tag_manager_v1 global served by Treeland + * (WXdgToplevelTagManagerV1). The interface has no events; the client tags a + * toplevel with a string. + * + * Coverage level E (end-to-end): instead of only asserting the request is + * accepted without a protocol error, the test reads the production + * WXdgToplevelSurface's tag back over the server bridge + * (WXdgToplevelSurface::tag(), which WXdgToplevelTagManagerV1 populates via + * setTag()) and verifies it equals the string the client set. + */ + +#include "wayland-xdg-toplevel-tag-v1.h" +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "xdg-toplevel-tag-v1-client-protocol.h" + +#include +#include + +static const char *const TEST_TAG = "treeland-tag-test"; + +int protocol_test_run(const char *socket_name) { + struct client_connection conn; + if (!client_connect(&conn, socket_name)) { + TEST_ERROR("xdg-toplevel-tag: connect failed\n"); + return 1; + } + + struct xdg_toplevel_client tc; + if (!xdg_toplevel_client_create_pending(&conn, &tc)) { + TEST_ERROR("xdg-toplevel-tag: create_pending failed\n"); + client_disconnect(&conn); + return 1; + } + + struct xdg_toplevel_tag_manager_v1 *manager = client_bind( + &conn, xdg_toplevel_tag_manager_v1_interface.name, &xdg_toplevel_tag_manager_v1_interface, xdg_toplevel_tag_manager_v1_interface.version); + if (manager == NULL) { + TEST_ERROR("xdg-toplevel-tag: failed to bind manager: %s\n", strerror(errno)); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + + xdg_toplevel_tag_manager_v1_set_toplevel_tag(manager, tc.toplevel, TEST_TAG); + + if (!xdg_toplevel_client_complete_map(&conn, &tc)) { + TEST_ERROR("xdg-toplevel-tag: complete_map failed\n"); + xdg_toplevel_tag_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return 1; + } + wl_display_roundtrip(conn.display); + + /* E-level: read the real WXdgToplevelSurface's tag and compare. */ + struct xdg_toplevel_tag_server_state server = { 0 }; + int failed = 0; + if (invoke_on_server_thread(xdg_toplevel_tag_read_server_state, &server) == 0) { + TEST_ERROR("xdg-toplevel-tag: failed to read server state\n"); + failed = 1; + } else if (!server.valid) { + TEST_ERROR("xdg-toplevel-tag: no mapped SurfaceWrapper captured\n"); + failed = 1; + } else if (strcmp(server.tag, TEST_TAG) != 0) { + TEST_ERROR("xdg-toplevel-tag: real tag \"%s\" != \"%s\"\n", server.tag, TEST_TAG); + failed = 1; + } + + xdg_toplevel_tag_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&tc); + client_disconnect(&conn); + return failed; +} diff --git a/tests/protocols/wayland-xdg-toplevel-tag-v1/wayland-xdg-toplevel-tag-v1.h b/tests/protocols/wayland-xdg-toplevel-tag-v1/wayland-xdg-toplevel-tag-v1.h new file mode 100644 index 0000000000..91a2f3a94b --- /dev/null +++ b/tests/protocols/wayland-xdg-toplevel-tag-v1/wayland-xdg-toplevel-tag-v1.h @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2026 UnionTech Software Technology Co., Ltd. + * SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + */ +#ifndef WAYLAND_XDG_TOPLEVEL_TAG_TEST_H +#define WAYLAND_XDG_TOPLEVEL_TAG_TEST_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Snapshot of the real mapped WXdgToplevelSurface's tag, read on the + * compositor (Qt) thread. The xdg_toplevel_tag_manager_v1.set_toplevel_tag + * request is handled by WXdgToplevelTagManagerV1, which stores the tag on the + * production WXdgToplevelSurface via setTag(); an end-to-end (E-level) test + * reads that live object back and verifies the tag matches the client request, + * rather than only asserting the request is accepted. + */ +struct xdg_toplevel_tag_server_state { + int valid; /* a mapped XdgToplevel SurfaceWrapper was captured */ + char tag[128]; /* WXdgToplevelSurface::tag() (UTF-8) */ +}; + +/* Defined in setup.cpp; runs on the compositor thread via + * invoke_on_server_thread() and fills *data with the wrapper's tag. */ +void xdg_toplevel_tag_read_server_state(void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* WAYLAND_XDG_TOPLEVEL_TAG_TEST_H */ diff --git a/tests/protocols/wlr-data-control-unstable-v1/CMakeLists.txt b/tests/protocols/wlr-data-control-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..31b76c6d67 --- /dev/null +++ b/tests/protocols/wlr-data-control-unstable-v1/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +treeland_add_protocol_test( + NAME wlr_data_control_unstable_v1 + XML "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-data-control-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wlr-data-control-unstable-v1.c" +) diff --git a/tests/protocols/wlr-data-control-unstable-v1/README.md b/tests/protocols/wlr-data-control-unstable-v1/README.md new file mode 100644 index 0000000000..50c1ef4901 --- /dev/null +++ b/tests/protocols/wlr-data-control-unstable-v1/README.md @@ -0,0 +1,39 @@ +# `wlr-data-control-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`3rdparty/wlroots/protocol/wlr-data-control-unstable-v1.xml` / + `zwlr_data_control_manager_v1`、`zwlr_data_control_device_v1`、source 与 offer v2。 +- 测试源码:`tests/protocols/wlr-data-control-unstable-v1/`。 +- Fixture:完整 Treeland desktop integration fixture、默认 `WSeat` 与两个独立 Wayland client; + source/target 通过 data offer 与 pipe 传输 selection 内容。 +- 覆盖等级:**P / E**;P 覆盖 resource 生命周期,E 覆盖真实 seat selection、offer 与数据传输。 + +## 必须观察到的结果 + +| 场景 | 动作 | 断言 | 证据层级 | +| --- | --- | --- | --- | +| selection transfer | source offer `text/plain` 后 set selection;target receive pipe | target 收到 offer/selection,source 收到 `send` 并写出 payload,target 读回完全一致内容 | E | +| source replacement | 第二 source 替换 selection | 第一 source 收到 `cancelled` | E | +| primary selection | 第三 source set primary selection | target 收到 v2 `primary_selection` | E | +| manager lifetime | destroy manager 后现有 device `set_selection(NULL)` | child device 仍有效,无协议错误 | P | + +## 生产结果 + +`WaylandServer::init()` 直接创建 wlroots native manager;waylib 当前没有 wrapper,native global 随 +display 销毁。source 与 target 是两个独立 Wayland client。source 的 data source 经原生 data-control manager +写入真实 `WSeat` selection;target 的真实 data-control device 收到 offer/selection 后,以 pipe +调用 `receive`。wlroots 再向 source 发送 `send(fd,mime)`,source 写入 payload,target 从同一 pipe +读回逐字节一致内容。selection replacement 的 `cancelled` 和 v2 primary selection 均来自这条 +真实 seat 链路,不是测试手工发送的 protocol event。 + +因此 selection、primary selection、offer/receive/send 与 replacement 为 E 级;manager destroy +后 child device 仍可用只证明 resource 生命周期,属于 P 级。 + +## 已知边界 / 下一项结果 + +- 尚缺独立连接中的 `used_source`、`invalid_offer` protocol error 断言,以及 device seat-destroy 的 + `finished`。 +- 该 global 当前由 Treeland 直接公开;wlroots native implementation 没有 trusted-client 判定或 + authorization callback,因此 `unauthorized` 没有可触发的生产分支。测试记录该事实,不把所有 + client 被允许创建 data-control device 误报为授权策略测试。 diff --git a/tests/protocols/wlr-data-control-unstable-v1/setup.cpp b/tests/protocols/wlr-data-control-unstable-v1/setup.cpp new file mode 100644 index 0000000000..882458a97c --- /dev/null +++ b/tests/protocols/wlr-data-control-unstable-v1/setup.cpp @@ -0,0 +1,12 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "server-bridge.h" +#include "core/waylandserver.h" + +#include + +void protocol_test_setup(WaylandServer *server) +{ + add_headless_output(server->backend(), false); +} diff --git a/tests/protocols/wlr-data-control-unstable-v1/wlr-data-control-unstable-v1.c b/tests/protocols/wlr-data-control-unstable-v1/wlr-data-control-unstable-v1.c new file mode 100644 index 0000000000..a4884b1609 --- /dev/null +++ b/tests/protocols/wlr-data-control-unstable-v1/wlr-data-control-unstable-v1.c @@ -0,0 +1,131 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-3.0-only + +#include "client-connection.h" +#include "wlr-data-control-unstable-v1-client-protocol.h" + +#include +#include + +struct source_state { unsigned send, cancelled, write_failed; const char *payload; }; +struct device_state { struct zwlr_data_control_offer_v1 *offer; unsigned data_offer, selection, primary; }; + +static void source_send(void *data, struct zwlr_data_control_source_v1 *source, const char *mime, int32_t fd) +{ + (void)source; + struct source_state *state = data; + if (strcmp(mime, "text/plain") == 0) { + const size_t payload_size = strlen(state->payload); + if (write(fd, state->payload, payload_size) != (ssize_t)payload_size) + ++state->write_failed; + } + close(fd); + ++state->send; +} +static void source_cancelled(void *data, struct zwlr_data_control_source_v1 *source) +{ (void)source; ++((struct source_state *)data)->cancelled; } +static const struct zwlr_data_control_source_v1_listener source_listener = { + .send = source_send, .cancelled = source_cancelled, +}; +static void offer_offer(void *data, struct zwlr_data_control_offer_v1 *offer, const char *mime) +{ (void)data; (void)offer; (void)mime; } +static const struct zwlr_data_control_offer_v1_listener offer_listener = { .offer = offer_offer }; +static void device_offer(void *data, struct zwlr_data_control_device_v1 *device, struct zwlr_data_control_offer_v1 *offer) +{ + (void)device; + struct device_state *state = data; + ++state->data_offer; + state->offer = offer; + zwlr_data_control_offer_v1_add_listener(offer, &offer_listener, state); +} +static void device_selection(void *data, struct zwlr_data_control_device_v1 *device, struct zwlr_data_control_offer_v1 *offer) +{ (void)device; struct device_state *state = data; ++state->selection; if (offer) state->offer = offer; } +static void device_finished(void *data, struct zwlr_data_control_device_v1 *device) +{ (void)data; (void)device; } +static void device_primary(void *data, struct zwlr_data_control_device_v1 *device, struct zwlr_data_control_offer_v1 *offer) +{ (void)device; (void)offer; ++((struct device_state *)data)->primary; } +static const struct zwlr_data_control_device_v1_listener device_listener = { + .data_offer = device_offer, .selection = device_selection, + .finished = device_finished, .primary_selection = device_primary, +}; + +static int bind_device(struct client_connection *connection, + struct zwlr_data_control_manager_v1 **manager, + struct zwlr_data_control_device_v1 **device, + struct device_state *state) +{ + struct wl_seat *seat = client_bind(connection, "wl_seat", &wl_seat_interface, 1); + *manager = client_bind(connection, "zwlr_data_control_manager_v1", + &zwlr_data_control_manager_v1_interface, 2); + if (!seat || !*manager) return 0; + *device = zwlr_data_control_manager_v1_get_data_device(*manager, seat); + wl_seat_destroy(seat); + if (!*device) return 0; + zwlr_data_control_device_v1_add_listener(*device, &device_listener, state); + return wl_display_roundtrip(connection->display) >= 0; +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection source_connection = {0}, target_connection = {0}; + struct zwlr_data_control_manager_v1 *source_manager = NULL, *target_manager = NULL; + struct zwlr_data_control_device_v1 *source_device = NULL, *target_device = NULL; + struct device_state source_device_state = {0}, target_state = {0}; + struct source_state first_state = { .payload = "treeland-data-control" }; + struct source_state second_state = { .payload = "replacement" }; + if (!client_connect(&source_connection, socket_name) + || !client_connect(&target_connection, socket_name) + || !bind_device(&source_connection, &source_manager, &source_device, &source_device_state) + || !bind_device(&target_connection, &target_manager, &target_device, &target_state)) goto failed; + + struct zwlr_data_control_source_v1 *first = zwlr_data_control_manager_v1_create_data_source(source_manager); + if (!first) goto failed; + zwlr_data_control_source_v1_add_listener(first, &source_listener, &first_state); + zwlr_data_control_source_v1_offer(first, "text/plain"); + zwlr_data_control_device_v1_set_selection(source_device, first); + if (wl_display_roundtrip(source_connection.display) < 0 || wl_display_roundtrip(target_connection.display) < 0 + || !target_state.offer || !target_state.data_offer || target_state.selection < 2) goto failed; + + int pipe_fds[2]; + if (pipe(pipe_fds) < 0) goto failed; + zwlr_data_control_offer_v1_receive(target_state.offer, "text/plain", pipe_fds[1]); + close(pipe_fds[1]); + if (wl_display_roundtrip(target_connection.display) < 0 || wl_display_roundtrip(source_connection.display) < 0) { close(pipe_fds[0]); goto failed; } + char payload[64] = {0}; + const ssize_t length = read(pipe_fds[0], payload, sizeof(payload) - 1); + close(pipe_fds[0]); + if (length != (ssize_t)strlen(first_state.payload) || strcmp(payload, first_state.payload) != 0 + || first_state.send != 1 || first_state.write_failed) goto failed; + + struct zwlr_data_control_source_v1 *second = zwlr_data_control_manager_v1_create_data_source(source_manager); + if (!second) goto failed; + zwlr_data_control_source_v1_add_listener(second, &source_listener, &second_state); + zwlr_data_control_source_v1_offer(second, "text/plain"); + zwlr_data_control_device_v1_set_selection(source_device, second); + if (wl_display_roundtrip(source_connection.display) < 0 || first_state.cancelled != 1) goto failed; + + struct zwlr_data_control_source_v1 *third = zwlr_data_control_manager_v1_create_data_source(source_manager); + if (!third) goto failed; + zwlr_data_control_source_v1_add_listener(third, &source_listener, &second_state); + zwlr_data_control_source_v1_offer(third, "text/plain"); + zwlr_data_control_device_v1_set_primary_selection(source_device, third); + if (wl_display_roundtrip(source_connection.display) < 0 || wl_display_roundtrip(target_connection.display) < 0 + || target_state.primary < 2) goto failed; + + // XML keeps manager-created children valid after manager.destroy. + zwlr_data_control_manager_v1_destroy(source_manager); + source_manager = NULL; + zwlr_data_control_device_v1_set_selection(source_device, NULL); + if (wl_display_roundtrip(source_connection.display) < 0) goto failed; + + zwlr_data_control_device_v1_destroy(target_device); + zwlr_data_control_manager_v1_destroy(target_manager); + zwlr_data_control_device_v1_destroy(source_device); + client_disconnect(&target_connection); + client_disconnect(&source_connection); + return 0; +failed: + client_disconnect(&target_connection); + client_disconnect(&source_connection); + return 1; +} diff --git a/tests/protocols/wlr-export-dmabuf-unstable-v1/CMakeLists.txt b/tests/protocols/wlr-export-dmabuf-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..da0d740634 --- /dev/null +++ b/tests/protocols/wlr-export-dmabuf-unstable-v1/CMakeLists.txt @@ -0,0 +1,37 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +set(WLR_EXPORT_DMABUF_XML + "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-export-dmabuf-unstable-v1.xml") + +# The standard headless CI renderer is pixman. It cannot put a DMA-BUF in the +# output commit, so this target exercises the real temporary-cancel path. +treeland_add_protocol_test( + NAME wlr_export_dmabuf_unstable_v1 + XML "${WLR_EXPORT_DMABUF_XML}" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wlr-export-dmabuf-unstable-v1.c" +) + +# GPU runners opt in at configure time. A missing usable DMA-BUF output is a +# skipped capability, not a successful substitute for frame/object/ready. +if(TREELAND_ENABLE_GPU_PROTOCOL_TESTS) + pkg_check_modules(EGL REQUIRED IMPORTED_TARGET egl) + pkg_check_modules(GLES2 REQUIRED IMPORTED_TARGET glesv2) + treeland_add_protocol_test( + NAME wlr_export_dmabuf_unstable_v1_gpu + XML "${WLR_EXPORT_DMABUF_XML}" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wlr-export-dmabuf-unstable-v1.c" + ) + target_compile_definitions(test_wlr_export_dmabuf_unstable_v1_gpu + PRIVATE TREELAND_PROTOCOL_EXPECT_DMABUF_READY=1) + target_link_libraries(test_wlr_export_dmabuf_unstable_v1_gpu PRIVATE + PkgConfig::EGL + PkgConfig::GLES2 + ) + set_tests_properties(test_wlr_export_dmabuf_unstable_v1_gpu PROPERTIES + ENVIRONMENT "WLR_BACKENDS=headless;WLR_RENDERER=gles2;TREELAND_TEST_PLUGINS_PATH=${TREELAND_PLUGINS_OUTPUT_PATH};DSG_DATA_DIRS=${TREELAND_PROTOCOL_TEST_DSG_DATA_DIRS};TREELAND_PROTOCOL_TEST_DSG_DIR=${TREELAND_PROTOCOL_TEST_DSG_DATA_DIR}" + LABELS "protocols;gpu" + SKIP_RETURN_CODE 77 + ) +endif() diff --git a/tests/protocols/wlr-export-dmabuf-unstable-v1/README.md b/tests/protocols/wlr-export-dmabuf-unstable-v1/README.md new file mode 100644 index 0000000000..18530502ed --- /dev/null +++ b/tests/protocols/wlr-export-dmabuf-unstable-v1/README.md @@ -0,0 +1,46 @@ +# `wlr-export-dmabuf-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`3rdparty/wlroots/protocol/wlr-export-dmabuf-unstable-v1.xml`, + `zwlr_export_dmabuf_manager_v1` v1 与 `zwlr_export_dmabuf_frame_v1` v1。 +- 测试源码:`tests/protocols/wlr-export-dmabuf-unstable-v1/`。 +- Fixture:真实 Treeland desktop integration fixture、headless `wl_output` 与 mapped + 红色 xdg surface。 +- 覆盖等级:CI 为 P / E;GPU runner 为 P / V。 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 标准 CI(pixman) | bind manager/output;在真实 mapped xdg surface 后以 `overlay_cursor=1` 调用 `capture_output` | 下一次生产 output commit 没有 DMA-BUF,收到唯一 `cancel(temporary)`;没有 `frame/object/ready`,随后销毁 frame 与 manager | P / E | +| GPU runner | 同一 capture 流程 | 收到严格的 `frame → object×num_objects → ready`;尺寸、object 索引、FD、size/stride、timestamp 与顺序有效;客户端复制后关闭每个协议 FD,将 DMA-BUF 作为 EGLImage 导入、离屏采样并断言中心像素为红色 | P / V | +| 无可导出的 GPU backing buffer | GPU runner 发起 capture 后收到 cancel,或无法创建 headless output | 返回 77,CTest 标记 Skip,不将取消路径当作 DMA-BUF 成功 | P | + +## 生产结果 + +测试 fixture 的 `setup.cpp` 直接创建 wlroots native manager。waylib 当前没有该协议 wrapper;native +manager 由 `wl_display` 销毁,且没有 Treeland 业务回调或额外所有权。标准 CI 的取消 event +来自真实 production output commit;GPU runner 的 frame/object/ready 及 EGL import/readback +则验证 native export 到 client 端导入的完整链路。 + +### GPU runner 启用方式 + +默认 CI 仅注册 `test_wlr_export_dmabuf_unstable_v1`,环境固定为 pixman,因此取消事件是 +确定性生产行为。GPU job 配置时显式启用: + +```bash +cmake --preset ci -DTREELAND_ENABLE_GPU_PROTOCOL_TESTS=ON +cmake --build --preset ci --target test_wlr_export_dmabuf_unstable_v1_gpu +ctest --test-dir build -R '^test_wlr_export_dmabuf_unstable_v1_gpu$' --output-on-failure +``` + +GPU target 使用 `WLR_RENDERER=gles2`;只有 runner 的 EGL/driver 与 headless output 真正 +产出 DMA-BUF 时才要求 `ready` 与 EGL import/readback。任一能力不可用时返回 77。 + +## 已知边界 / 下一项结果 + +- 生产 wlroots manager 未提供 trusted-client/authorization hook;该 global 对可连接的 + Wayland client 可用。权限策略须在注册该 global 前另行实现。 +- 尚未构造 output disable/destroy 或 resize,因此未逐项断言 `cancel(permanent)` 与 + `cancel(resizing)`。 diff --git a/tests/protocols/wlr-export-dmabuf-unstable-v1/setup.cpp b/tests/protocols/wlr-export-dmabuf-unstable-v1/setup.cpp new file mode 100644 index 0000000000..3323df22cf --- /dev/null +++ b/tests/protocols/wlr-export-dmabuf-unstable-v1/setup.cpp @@ -0,0 +1,32 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "server-bridge.h" +#include "core/waylandserver.h" + +#include +#include + +namespace { +bool g_outputCreated = false; +} + +void protocol_test_setup(WaylandServer *server) +{ + g_outputCreated = add_headless_output(server->backend(), false); + // This native global exists only for this protocol fixture. Keeping it + // out of WaylandServer avoids making the production library depend on a protocol + // implementation that is otherwise test-only. + wlr_export_dmabuf_manager_v1_create(server->backend()->server()->handle()); +} + +extern "C" bool protocol_test_skip() +{ +#ifdef TREELAND_PROTOCOL_EXPECT_DMABUF_READY + // A GLES2 GPU runner without a usable headless output cannot reach the + // capability assertion in the C client. Mark that environment unsupported. + return !g_outputCreated; +#else + return false; +#endif +} diff --git a/tests/protocols/wlr-export-dmabuf-unstable-v1/wlr-export-dmabuf-unstable-v1.c b/tests/protocols/wlr-export-dmabuf-unstable-v1/wlr-export-dmabuf-unstable-v1.c new file mode 100644 index 0000000000..4b94aaff22 --- /dev/null +++ b/tests/protocols/wlr-export-dmabuf-unstable-v1/wlr-export-dmabuf-unstable-v1.c @@ -0,0 +1,479 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "client-connection.h" +#include "xdg-toplevel-client.h" +#include "wlr-export-dmabuf-unstable-v1-client-protocol.h" + +#include +#include +#include + +#ifdef TREELAND_PROTOCOL_EXPECT_DMABUF_READY +#include + +#include +#include +#include +#include +#endif + +struct export_events { + unsigned int frame_count; + unsigned int object_count; + unsigned int ready_count; + unsigned int cancel_count; + uint32_t width; + uint32_t height; + uint32_t flags; + uint32_t object_total; + uint32_t object_mask; + uint32_t cancel_reason; + uint32_t tv_nsec; + uint32_t format; + uint32_t modifier_high; + uint32_t modifier_low; + int ordering_valid; + int object_payload_valid; +#ifdef TREELAND_PROTOCOL_EXPECT_DMABUF_READY + int object_fds[4]; + uint32_t object_offsets[4]; + uint32_t object_strides[4]; +#endif +}; + +static void frame_handle_frame(void *data, struct zwlr_export_dmabuf_frame_v1 *frame, + uint32_t width, uint32_t height, uint32_t offset_x, + uint32_t offset_y, uint32_t buffer_flags, uint32_t flags, + uint32_t format, uint32_t mod_high, uint32_t mod_low, + uint32_t num_objects) +{ + (void)frame; + (void)offset_x; + (void)offset_y; + (void)buffer_flags; + struct export_events *events = data; + events->ordering_valid = events->frame_count == 0 && events->object_count == 0 + && events->ready_count == 0 && events->cancel_count == 0; + events->object_payload_valid = width > 0 && height > 0 && num_objects > 0 && num_objects <= 4; + events->width = width; + events->height = height; + events->flags = flags; + events->format = format; + events->modifier_high = mod_high; + events->modifier_low = mod_low; + events->object_total = num_objects; + events->frame_count++; +} + +static void frame_handle_object(void *data, struct zwlr_export_dmabuf_frame_v1 *frame, + uint32_t index, int32_t fd, uint32_t size, + uint32_t offset, uint32_t stride, uint32_t plane_index) +{ + (void)frame; +#ifndef TREELAND_PROTOCOL_EXPECT_DMABUF_READY + (void)offset; +#endif + struct export_events *events = data; +#ifdef TREELAND_PROTOCOL_EXPECT_DMABUF_READY + const int duplicate_fd = fd >= 0 ? fcntl(fd, F_DUPFD_CLOEXEC, 3) : -1; +#endif + if (fd >= 0) + close(fd); + if (events->frame_count != 1 || events->ready_count != 0 || events->cancel_count != 0 + || index >= events->object_total || index >= 32 || (events->object_mask & (1u << index)) + || fd < 0 || size == 0 || stride == 0 || plane_index >= events->object_total +#ifdef TREELAND_PROTOCOL_EXPECT_DMABUF_READY + || duplicate_fd < 0 +#endif + ) { + events->object_payload_valid = 0; +#ifdef TREELAND_PROTOCOL_EXPECT_DMABUF_READY + if (duplicate_fd >= 0) + close(duplicate_fd); +#endif + } else { + events->object_mask |= 1u << index; +#ifdef TREELAND_PROTOCOL_EXPECT_DMABUF_READY + events->object_fds[index] = duplicate_fd; + events->object_offsets[index] = offset; + events->object_strides[index] = stride; +#endif + } + events->object_count++; +} + +#ifdef TREELAND_PROTOCOL_EXPECT_DMABUF_READY +static int has_extension(const char *extensions, const char *extension) +{ + const size_t extension_length = strlen(extension); + const char *candidate = extensions; + while (candidate && *candidate) { + candidate = strstr(candidate, extension); + if (!candidate) + return 0; + const char before = candidate == extensions ? ' ' : candidate[-1]; + const char after = candidate[extension_length]; + if ((before == ' ' || before == '\0') && (after == ' ' || after == '\0')) + return 1; + candidate += extension_length; + } + return 0; +} + +static GLuint compile_shader(GLenum type, const char *source) +{ + const GLuint shader = glCreateShader(type); + if (!shader) + return 0; + glShaderSource(shader, 1, &source, NULL); + glCompileShader(shader); + GLint compiled = GL_FALSE; + glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); + if (compiled) + return shader; + glDeleteShader(shader); + return 0; +} + +/* Returns 1 for a verified red sample, 0 for an assertion failure, and -1 + * when the GPU runner lacks the EGL/GLES import capability needed for V. */ +static int readback_exported_red(const struct export_events *events) +{ + EGLDisplay display = EGL_NO_DISPLAY; + EGLContext context = EGL_NO_CONTEXT; + EGLSurface surface = EGL_NO_SURFACE; + EGLImageKHR image = EGL_NO_IMAGE_KHR; + GLuint source_texture = 0; + GLuint target_texture = 0; + GLuint framebuffer = 0; + GLuint vertex_shader = 0; + GLuint fragment_shader = 0; + GLuint program = 0; + int result = -1; + + PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform_display = + (PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT"); + if (get_platform_display) + display = get_platform_display(EGL_PLATFORM_SURFACELESS_MESA, EGL_DEFAULT_DISPLAY, NULL); + if (display == EGL_NO_DISPLAY) + display = eglGetDisplay(EGL_DEFAULT_DISPLAY); + if (display == EGL_NO_DISPLAY || !eglInitialize(display, NULL, NULL) + || !eglBindAPI(EGL_OPENGL_ES_API)) + goto cleanup; + + const char *egl_extensions = eglQueryString(display, EGL_EXTENSIONS); + const uint64_t modifier = ((uint64_t)events->modifier_high << 32) | events->modifier_low; + const int needs_modifier_attributes = modifier != UINT64_MAX; + if (!egl_extensions || !has_extension(egl_extensions, "EGL_EXT_image_dma_buf_import") + || (needs_modifier_attributes + && !has_extension(egl_extensions, "EGL_EXT_image_dma_buf_import_modifiers"))) + goto cleanup; + + const EGLint config_attributes[] = { + EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, + EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, + EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, + EGL_NONE, + }; + EGLConfig config; + EGLint config_count = 0; + if (!eglChooseConfig(display, config_attributes, &config, 1, &config_count) || !config_count) + goto cleanup; + const EGLint pbuffer_attributes[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE }; + surface = eglCreatePbufferSurface(display, config, pbuffer_attributes); + const EGLint context_attributes[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; + context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attributes); + if (surface == EGL_NO_SURFACE || context == EGL_NO_CONTEXT + || !eglMakeCurrent(display, surface, surface, context)) + goto cleanup; + + const char *gl_extensions = (const char *)glGetString(GL_EXTENSIONS); + PFNGLEGLIMAGETARGETTEXTURE2DOESPROC image_target_texture = + (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)eglGetProcAddress("glEGLImageTargetTexture2DOES"); + if (!gl_extensions || !has_extension(gl_extensions, "GL_OES_EGL_image_external") + || !image_target_texture) + goto cleanup; + + EGLint attributes[64]; + int attribute_count = 0; + attributes[attribute_count++] = EGL_WIDTH; + attributes[attribute_count++] = (EGLint)events->width; + attributes[attribute_count++] = EGL_HEIGHT; + attributes[attribute_count++] = (EGLint)events->height; + attributes[attribute_count++] = EGL_LINUX_DRM_FOURCC_EXT; + attributes[attribute_count++] = (EGLint)events->format; + static const EGLint fd_attributes[] = { + EGL_DMA_BUF_PLANE0_FD_EXT, EGL_DMA_BUF_PLANE1_FD_EXT, + EGL_DMA_BUF_PLANE2_FD_EXT, EGL_DMA_BUF_PLANE3_FD_EXT, + }; + static const EGLint offset_attributes[] = { + EGL_DMA_BUF_PLANE0_OFFSET_EXT, EGL_DMA_BUF_PLANE1_OFFSET_EXT, + EGL_DMA_BUF_PLANE2_OFFSET_EXT, EGL_DMA_BUF_PLANE3_OFFSET_EXT, + }; + static const EGLint pitch_attributes[] = { + EGL_DMA_BUF_PLANE0_PITCH_EXT, EGL_DMA_BUF_PLANE1_PITCH_EXT, + EGL_DMA_BUF_PLANE2_PITCH_EXT, EGL_DMA_BUF_PLANE3_PITCH_EXT, + }; + static const EGLint modifier_lo_attributes[] = { + EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT, EGL_DMA_BUF_PLANE1_MODIFIER_LO_EXT, + EGL_DMA_BUF_PLANE2_MODIFIER_LO_EXT, EGL_DMA_BUF_PLANE3_MODIFIER_LO_EXT, + }; + static const EGLint modifier_hi_attributes[] = { + EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT, EGL_DMA_BUF_PLANE1_MODIFIER_HI_EXT, + EGL_DMA_BUF_PLANE2_MODIFIER_HI_EXT, EGL_DMA_BUF_PLANE3_MODIFIER_HI_EXT, + }; + for (uint32_t plane = 0; plane < events->object_total; ++plane) { + attributes[attribute_count++] = fd_attributes[plane]; + attributes[attribute_count++] = events->object_fds[plane]; + attributes[attribute_count++] = offset_attributes[plane]; + attributes[attribute_count++] = (EGLint)events->object_offsets[plane]; + attributes[attribute_count++] = pitch_attributes[plane]; + attributes[attribute_count++] = (EGLint)events->object_strides[plane]; + if (needs_modifier_attributes) { + attributes[attribute_count++] = modifier_lo_attributes[plane]; + attributes[attribute_count++] = (EGLint)events->modifier_low; + attributes[attribute_count++] = modifier_hi_attributes[plane]; + attributes[attribute_count++] = (EGLint)events->modifier_high; + } + } + attributes[attribute_count++] = EGL_NONE; + PFNEGLCREATEIMAGEKHRPROC create_image = + (PFNEGLCREATEIMAGEKHRPROC)eglGetProcAddress("eglCreateImageKHR"); + if (!create_image) + goto cleanup; + image = create_image(display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, NULL, attributes); + if (image == EGL_NO_IMAGE_KHR) + goto cleanup; + + glGenTextures(1, &source_texture); + glBindTexture(GL_TEXTURE_EXTERNAL_OES, source_texture); + glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + image_target_texture(GL_TEXTURE_EXTERNAL_OES, image); + + glGenTextures(1, &target_texture); + glBindTexture(GL_TEXTURE_2D, target_texture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); + glGenFramebuffers(1, &framebuffer); + glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, target_texture, 0); + if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) + goto cleanup; + + static const char vertex_source[] = + "attribute vec2 position; varying vec2 uv;" + "void main() { uv = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }"; + static const char fragment_source[] = + "#extension GL_OES_EGL_image_external : require\n" + "precision mediump float; varying vec2 uv; uniform samplerExternalOES image;" + "void main() { gl_FragColor = texture2D(image, uv); }"; + vertex_shader = compile_shader(GL_VERTEX_SHADER, vertex_source); + fragment_shader = compile_shader(GL_FRAGMENT_SHADER, fragment_source); + if (!vertex_shader || !fragment_shader) + goto cleanup; + program = glCreateProgram(); + glAttachShader(program, vertex_shader); + glAttachShader(program, fragment_shader); + glBindAttribLocation(program, 0, "position"); + glLinkProgram(program); + GLint linked = GL_FALSE; + glGetProgramiv(program, GL_LINK_STATUS, &linked); + if (!linked) + goto cleanup; + glUseProgram(program); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_EXTERNAL_OES, source_texture); + glUniform1i(glGetUniformLocation(program, "image"), 0); + static const GLfloat positions[] = { -1.f, -1.f, 1.f, -1.f, -1.f, 1.f, 1.f, 1.f }; + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, positions); + glEnableVertexAttribArray(0); + glViewport(0, 0, 1, 1); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + GLubyte pixel[4] = { 0 }; + glReadPixels(0, 0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, pixel); + if (glGetError() != GL_NO_ERROR) + goto cleanup; + result = pixel[0] > 200 && pixel[1] < 60 && pixel[2] < 60 ? 1 : 0; + +cleanup: + if (program) + glDeleteProgram(program); + if (vertex_shader) + glDeleteShader(vertex_shader); + if (fragment_shader) + glDeleteShader(fragment_shader); + if (framebuffer) + glDeleteFramebuffers(1, &framebuffer); + if (target_texture) + glDeleteTextures(1, &target_texture); + if (source_texture) + glDeleteTextures(1, &source_texture); + if (image != EGL_NO_IMAGE_KHR) { + PFNEGLDESTROYIMAGEKHRPROC destroy_image = + (PFNEGLDESTROYIMAGEKHRPROC)eglGetProcAddress("eglDestroyImageKHR"); + if (destroy_image) + destroy_image(display, image); + } + if (display != EGL_NO_DISPLAY) { + eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + if (context != EGL_NO_CONTEXT) + eglDestroyContext(display, context); + if (surface != EGL_NO_SURFACE) + eglDestroySurface(display, surface); + eglTerminate(display); + } + return result; +} + +static void close_exported_fds(struct export_events *events) +{ + for (uint32_t index = 0; index < 4; ++index) { + if (events->object_fds[index] >= 0) { + close(events->object_fds[index]); + events->object_fds[index] = -1; + } + } +} +#endif + +static void frame_handle_ready(void *data, struct zwlr_export_dmabuf_frame_v1 *frame, + uint32_t tv_sec_hi, uint32_t tv_sec_lo, uint32_t tv_nsec) +{ + (void)frame; + (void)tv_sec_hi; + (void)tv_sec_lo; + struct export_events *events = data; + if (events->frame_count != 1 || events->object_count != events->object_total + || events->cancel_count != 0 || tv_nsec >= 1000000000u) + events->ordering_valid = 0; + events->tv_nsec = tv_nsec; + events->ready_count++; +} + +static void frame_handle_cancel(void *data, struct zwlr_export_dmabuf_frame_v1 *frame, + uint32_t reason) +{ + (void)frame; + struct export_events *events = data; + if (events->ready_count != 0) + events->ordering_valid = 0; + events->cancel_reason = reason; + events->cancel_count++; +} + +static const struct zwlr_export_dmabuf_frame_v1_listener frame_listener = { + .frame = frame_handle_frame, + .object = frame_handle_object, + .ready = frame_handle_ready, + .cancel = frame_handle_cancel, +}; + +static struct wl_output *bind_output(struct client_connection *connection) +{ + return client_bind(connection, "wl_output", &wl_output_interface, 1); +} + +static int capture_next_output(struct client_connection *connection, + struct zwlr_export_dmabuf_manager_v1 *manager, + struct wl_output *output, struct export_events *events) +{ + struct zwlr_export_dmabuf_frame_v1 *frame = + zwlr_export_dmabuf_manager_v1_capture_output(manager, 1, output); + if (!frame) + return 0; + zwlr_export_dmabuf_frame_v1_add_listener(frame, &frame_listener, events); + + // capture_output asks wlroots to render one future output frame. The first + // roundtrip only guarantees that the server installed the output-commit + // listener; wait for its terminal ready/cancel event before destroying the + // frame resource. + int dispatched = wl_display_roundtrip(connection->display) >= 0; + while (dispatched && !events->ready_count && !events->cancel_count) + dispatched = wl_display_dispatch(connection->display) >= 0; + zwlr_export_dmabuf_frame_v1_destroy(frame); + return dispatched; +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + struct xdg_toplevel_client toplevel = { 0 }; + struct export_events events = { + .ordering_valid = 1, + .object_payload_valid = 1, + }; +#ifdef TREELAND_PROTOCOL_EXPECT_DMABUF_READY + for (uint32_t index = 0; index < 4; ++index) + events.object_fds[index] = -1; +#endif + if (!client_connect(&connection, socket_name)) + return 1; + + struct zwlr_export_dmabuf_manager_v1 *manager = client_bind( + &connection, "zwlr_export_dmabuf_manager_v1", &zwlr_export_dmabuf_manager_v1_interface, 1); + struct wl_output *output = bind_output(&connection); + const int mapped = manager && output + && xdg_toplevel_client_create_with_solid_buffer( + &connection, &toplevel, 1920, 1080, 0xffff0000u); + const int captured = mapped && capture_next_output(&connection, manager, output, &events); + + if (output) + wl_output_destroy(output); + if (manager) + zwlr_export_dmabuf_manager_v1_destroy(manager); + xdg_toplevel_client_destroy(&toplevel); + client_disconnect(&connection); + + if (!mapped || !captured) { +#ifdef TREELAND_PROTOCOL_EXPECT_DMABUF_READY + close_exported_fds(&events); +#endif + fprintf(stderr, "wlr-export-dmabuf: failed to map a real output surface or dispatch capture\n"); + return 1; + } + +#ifdef TREELAND_PROTOCOL_EXPECT_DMABUF_READY + if (events.cancel_count) { + close_exported_fds(&events); + fprintf(stderr, "wlr-export-dmabuf: GPU runner has no exportable DMA-BUF output; skipped\n"); + return 77; + } + const uint32_t required_mask = events.object_total == 32 ? UINT32_MAX : (1u << events.object_total) - 1; + if (events.frame_count != 1 || events.ready_count != 1 || events.cancel_count != 0 + || !events.ordering_valid || !events.object_payload_valid + || events.object_mask != required_mask) { + fprintf(stderr, + "wlr-export-dmabuf: invalid ready sequence frame=%u object=%u/%u ready=%u cancel=%u " + "ordering=%d payload=%d mask=%#x\n", + events.frame_count, events.object_count, events.object_total, events.ready_count, + events.cancel_count, events.ordering_valid, events.object_payload_valid, events.object_mask); + close_exported_fds(&events); + return 1; + } + const int readback = readback_exported_red(&events); + close_exported_fds(&events); + if (readback < 0) { + fprintf(stderr, "wlr-export-dmabuf: GPU runner lacks EGL DMA-BUF import/readback; skipped\n"); + return 77; + } + if (!readback) { + fprintf(stderr, "wlr-export-dmabuf: exported output center was not the mapped red surface\n"); + return 1; + } +#else + if (events.frame_count != 0 || events.object_count != 0 || events.ready_count != 0 + || events.cancel_count != 1 + || events.cancel_reason != ZWLR_EXPORT_DMABUF_FRAME_V1_CANCEL_REASON_TEMPORARY) { + fprintf(stderr, + "wlr-export-dmabuf: pixman expected one temporary cancel, got frame=%u object=%u ready=%u " + "cancel=%u reason=%u\n", + events.frame_count, events.object_count, events.ready_count, events.cancel_count, + events.cancel_reason); + return 1; + } +#endif + return 0; +} diff --git a/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/CMakeLists.txt b/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..42b20c52e9 --- /dev/null +++ b/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +treeland_add_protocol_test( + NAME wlr_foreign_toplevel_management_unstable_v1 + XML "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-foreign-toplevel-management-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wlr-foreign-toplevel-management-unstable-v1.c" +) diff --git a/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/README.md b/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/README.md new file mode 100644 index 0000000000..f707fa53a9 --- /dev/null +++ b/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/README.md @@ -0,0 +1,47 @@ +# `wlr-foreign-toplevel-management-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`3rdparty/wlroots/protocol/wlr-foreign-toplevel-management-unstable-v1.xml`, + `zwlr_foreign_toplevel_manager_v1` / `zwlr_foreign_toplevel_handle_v1` v3。 +- 测试源码:`tests/protocols/wlr-foreign-toplevel-management-unstable-v1/`。 +- Fixture:真实 Treeland desktop integration fixture、headless output、mapped xdg toplevel。 +- 覆盖等级:P / E。 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 初始枚举 | map 并设置 title/app-id 的 xdg toplevel | 一个标准 handle,`title/app_id/state/done`,以及同一生产 `SurfaceWrapper` 已进入 workspace | P / E | +| 状态控制 | set/unset minimized、maximized、fullscreen;activate | 同一 `SurfaceWrapper` 的真实状态与默认 seat focus 相应变化 | P / E | +| 客户端关闭 | `set_rectangle`、`close`、handle `destroy` | rectangle request 可派发;生产 xdg toplevel 收到 `close`,handle 正确释放 | P / E | +| manager 生命周期 | `stop` | 唯一 `finished`,随后释放 inert manager proxy | P | + +## 生产结果 + +wlroots 提供 native manager;waylib 的 `WForeignToplevel` 创建并持有它,Treeland 在 +`WaylandServer::init()` 中 attach 该 wrapper。测试只连接已发布的标准 global,绝不创建第二个 +manager。它与 Treeland 的 `treeland_foreign_toplevel_manager_v1` 自定义扩展是不同协议。 + +测试客户端先 map 一个真实 xdg toplevel。`ShellHandler` 创建同一个生产 +`SurfaceWrapper`,将其加入 `Workspace`;标准 `WForeignToplevel` 再为该 toplevel 发布 +`zwlr_foreign_toplevel_handle_v1`。初始 `toplevel/title/app_id/state/done` listener 和 +fixture 读取到的 wrapper 必须对应这同一窗口。 + +随后客户端对这个标准 handle 发送 `set/unset_minimized`、`set/unset_maximized` 与 +`set/unset_fullscreen`。fixture 不读取 foreign handle 的缓存,而是读取该 +`SurfaceWrapper` 的真实 shell/window state;fixture 关闭 maximize / fullscreen / restore +几何动画(`AnimationConfig`),状态在请求处理时直接落地,每次只 `render` 一帧就断言, +不等待动画完成信号。`activate(wl_seat)` 还必须使同一 wrapper 成为默认 seat container 的真实 +`keyboardFocusSurface()`。`close` 必须到达这个 mapped xdg client 的 `xdg_toplevel.close` +listener。 + +因此上述窗口发现、状态控制、焦点与关闭均为 E 级。`set_rectangle` 只证明标准 request +可被派发(P):Treeland 当前没有消费该 hint 并产生可观察业务状态,测试不会把它计为 E。 + +## 已知边界 / 下一项结果 + +- `output_enter/output_leave`、`parent`、`closed` 尚未稳定构造并逐项断言;`set_rectangle` + 是标准 protocol 的 compositor hint,当前没有 Treeland 业务消费者可读取其结果。 +- `set_fullscreen` 当前传 `NULL` hint,未验证指定 `wl_output` 的分支。 +- 未验证多个 toplevel、父子窗口、output 热插拔或最终渲染像素。 diff --git a/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/setup.cpp b/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/setup.cpp new file mode 100644 index 0000000000..fe801b21bb --- /dev/null +++ b/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/setup.cpp @@ -0,0 +1,85 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "core/rootsurfacecontainer.h" +#include "core/shellhandler.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "surface/surfacewrapper.h" +#include "wlr-foreign-toplevel-management-unstable-v1.h" +#include "workspace/workspace.h" + +#include +#include +#include + +#include "animationconfig.hpp" + +namespace { +SurfaceWrapper *g_wrapper = nullptr; +int g_maximizeRequestCount = 0; +int g_lastMaximizeRequest = -1; +int g_maximizedAfterLastRequest = -1; +} + +void protocol_test_setup(WaylandServer *server) +{ + // This test asserts the foreign-toplevel protocol's state transitions, not + // the geometry animation. With the animation off every maximize / + // fullscreen / restore request applies its surface state directly, so the + // test neither paces frames nor waits for an animation completion signal + // (same approach as the v3 foreign-toplevel test). + if (auto *animationConfig = server->animationConfig()) { + animationConfig->setMaximize(false); + animationConfig->setFullscreen(false); + animationConfig->setRestoreWindow(false); + } + add_headless_output(server->backend(), false); + auto *foreignToplevel = server->backend()->server()->findInterface(); + Q_ASSERT(foreignToplevel); + QObject::connect(foreignToplevel, + &WForeignToplevel::requestMaximize, + server, + [](WToplevelSurface *, bool maximized) { + ++g_maximizeRequestCount; + g_lastMaximizeRequest = maximized; + g_maximizedAfterLastRequest = g_wrapper && g_wrapper->isMaximized(); + }); + QObject::connect(server->shellHandler(), + &ShellHandler::surfaceWrapperAdded, + server, + [server](SurfaceWrapper *wrapper) { + if (wrapper->type() == SurfaceWrapper::Type::XdgToplevel) + g_wrapper = wrapper; + }); +} + +extern "C" void foreign_toplevel_read_server_state(void *data) +{ + foreign_toplevel_server_state state {}; + auto *server = WaylandServer::instance(); + state.output_ready = !server->rootSurfaceContainer()->outputs().isEmpty(); + state.wrapper_created = g_wrapper != nullptr; + state.wrapper_in_workspace = g_wrapper && server->workspace()->surfaces().contains(g_wrapper); + state.minimized = g_wrapper && g_wrapper->shellSurface() && g_wrapper->shellSurface()->isMinimized(); + state.maximized = g_wrapper && g_wrapper->isMaximized(); + state.fullscreen = g_wrapper && g_wrapper->surfaceState() == SurfaceWrapper::State::Fullscreen; + state.activated = g_wrapper && g_wrapper->isActivated(); + state.maximize_request_count = g_maximizeRequestCount; + state.last_maximize_request = g_lastMaximizeRequest; + state.maximized_after_last_request = g_maximizedAfterLastRequest; + const auto *seatContainer = server->rootSurfaceContainer()->getSeatContainerOrDefault(); + state.focused = seatContainer && seatContainer->keyboardFocusSurface() == g_wrapper; + *static_cast(data) = state; +} + +extern "C" void foreign_toplevel_render(void *) +{ + if (!g_wrapper) + return; + + // Geometry animations are disabled in protocol_test_setup(), so the state + // change has already landed when the request was handled; one render lets a + // queued scene-graph frame apply it before the test reads it back. + WaylandServer::instance()->window()->render(); +} diff --git a/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/wlr-foreign-toplevel-management-unstable-v1.c b/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/wlr-foreign-toplevel-management-unstable-v1.c new file mode 100644 index 0000000000..540c1f2254 --- /dev/null +++ b/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/wlr-foreign-toplevel-management-unstable-v1.c @@ -0,0 +1,252 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "client-connection.h" +#include "server-bridge-api.h" +#include "xdg-toplevel-client.h" +#include "wlr-foreign-toplevel-management-unstable-v1-client-protocol.h" +#include "wlr-foreign-toplevel-management-unstable-v1.h" + +#include +#include + +extern void foreign_toplevel_read_server_state(void *data); +extern void foreign_toplevel_render(void *data); + +struct foreign_events { + struct zwlr_foreign_toplevel_handle_v1 *handle; + unsigned int toplevel_count; + unsigned int title_count; + unsigned int app_id_count; + unsigned int state_count; + unsigned int done_count; + unsigned int closed_count; + unsigned int finished_count; + uint32_t states; + char title[64]; + char app_id[64]; +}; + +static void handle_title(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, const char *title) +{ + (void)handle; + struct foreign_events *events = data; + snprintf(events->title, sizeof(events->title), "%s", title ? title : ""); + events->title_count++; +} + +static void handle_app_id(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, const char *app_id) +{ + (void)handle; + struct foreign_events *events = data; + snprintf(events->app_id, sizeof(events->app_id), "%s", app_id ? app_id : ""); + events->app_id_count++; +} + +static void handle_output_enter(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, + struct wl_output *output) +{ + (void)data; + (void)handle; + (void)output; +} + +static void handle_output_leave(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, + struct wl_output *output) +{ + (void)data; + (void)handle; + (void)output; +} + +static void handle_state(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, + struct wl_array *state) +{ + (void)handle; + struct foreign_events *events = data; + events->states = 0; + uint32_t *entry; + wl_array_for_each(entry, state) { + if (*entry <= ZWLR_FOREIGN_TOPLEVEL_HANDLE_V1_STATE_FULLSCREEN) + events->states |= 1u << *entry; + } + events->state_count++; +} + +static void handle_done(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) +{ + (void)handle; + ((struct foreign_events *)data)->done_count++; +} + +static void handle_closed(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle) +{ + (void)handle; + ((struct foreign_events *)data)->closed_count++; +} + +static void handle_parent(void *data, struct zwlr_foreign_toplevel_handle_v1 *handle, + struct zwlr_foreign_toplevel_handle_v1 *parent) +{ + (void)data; + (void)handle; + (void)parent; +} + +static const struct zwlr_foreign_toplevel_handle_v1_listener handle_listener = { + .title = handle_title, + .app_id = handle_app_id, + .output_enter = handle_output_enter, + .output_leave = handle_output_leave, + .state = handle_state, + .done = handle_done, + .closed = handle_closed, + .parent = handle_parent, +}; + +static void manager_toplevel(void *data, struct zwlr_foreign_toplevel_manager_v1 *manager, + struct zwlr_foreign_toplevel_handle_v1 *toplevel) +{ + (void)manager; + struct foreign_events *events = data; + events->handle = toplevel; + events->toplevel_count++; + zwlr_foreign_toplevel_handle_v1_add_listener(toplevel, &handle_listener, events); +} + +static void manager_finished(void *data, struct zwlr_foreign_toplevel_manager_v1 *manager) +{ + (void)manager; + ((struct foreign_events *)data)->finished_count++; +} + +static const struct zwlr_foreign_toplevel_manager_v1_listener manager_listener = { + .toplevel = manager_toplevel, + .finished = manager_finished, +}; + +static int read_state(struct foreign_toplevel_server_state *state) +{ + memset(state, 0, sizeof(*state)); + return invoke_on_server_thread(foreign_toplevel_read_server_state, state); +} + +static int render_ack_and_read_state(struct client_connection *connection, + struct xdg_toplevel_client *xdg, + struct foreign_toplevel_server_state *state) +{ + return invoke_on_server_thread(foreign_toplevel_render, NULL) + && xdg_toplevel_client_ack_latest_configure(connection, xdg) + && invoke_on_server_thread(foreign_toplevel_render, NULL) + && read_state(state); +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + struct xdg_toplevel_client xdg = { 0 }; + struct foreign_events events = { 0 }; + struct foreign_toplevel_server_state state = { 0 }; + unsigned int stage = 0; + if (!client_connect(&connection, socket_name)) + return 1; + + struct wl_seat *seat = client_bind(&connection, "wl_seat", &wl_seat_interface, 1); + struct zwlr_foreign_toplevel_manager_v1 *manager = client_bind( + &connection, "zwlr_foreign_toplevel_manager_v1", &zwlr_foreign_toplevel_manager_v1_interface, 3); + if (!seat || !manager) { + fprintf(stderr, "wlr-foreign-toplevel: missing seat or standard manager global\n"); + goto failed; + } + stage = 1; + zwlr_foreign_toplevel_manager_v1_add_listener(manager, &manager_listener, &events); + if (!xdg_toplevel_client_create(&connection, &xdg)) + goto failed; + xdg_toplevel_set_title(xdg.toplevel, "foreign protocol test"); + xdg_toplevel_set_app_id(xdg.toplevel, "org.deepin.ForeignProtocolTest"); + stage = 2; + if (wl_display_roundtrip(connection.display) < 0 || !events.handle) + goto failed; + + stage = 3; + if (!read_state(&state) || !state.output_ready || !state.wrapper_created + || !state.wrapper_in_workspace || events.toplevel_count != 1 + || !events.title_count || !events.app_id_count || !events.state_count || !events.done_count + || strcmp(events.title, "foreign protocol test") != 0 + || strcmp(events.app_id, "org.deepin.ForeignProtocolTest") != 0) { + fprintf(stderr, "wlr-foreign-toplevel: initial toplevel events or production wrapper missing\n"); + goto failed; + } + + zwlr_foreign_toplevel_handle_v1_set_minimized(events.handle); + stage = 4; + if (wl_display_roundtrip(connection.display) < 0 + || !render_ack_and_read_state(&connection, &xdg, &state) || !state.minimized) + goto failed; + zwlr_foreign_toplevel_handle_v1_unset_minimized(events.handle); + stage = 5; + if (wl_display_roundtrip(connection.display) < 0 + || !render_ack_and_read_state(&connection, &xdg, &state) || state.minimized) + goto failed; + zwlr_foreign_toplevel_handle_v1_set_maximized(events.handle); + stage = 6; + if (wl_display_roundtrip(connection.display) < 0 + || !render_ack_and_read_state(&connection, &xdg, &state) || !state.maximized) + goto failed; + zwlr_foreign_toplevel_handle_v1_unset_maximized(events.handle); + stage = 7; + if (wl_display_roundtrip(connection.display) < 0 + || !render_ack_and_read_state(&connection, &xdg, &state) || state.maximized) + goto failed; + zwlr_foreign_toplevel_handle_v1_set_fullscreen(events.handle, NULL); + stage = 8; + if (wl_display_roundtrip(connection.display) < 0 + || !render_ack_and_read_state(&connection, &xdg, &state) || !state.fullscreen) + goto failed; + zwlr_foreign_toplevel_handle_v1_unset_fullscreen(events.handle); + stage = 9; + if (wl_display_roundtrip(connection.display) < 0 + || !render_ack_and_read_state(&connection, &xdg, &state) || state.fullscreen) + goto failed; + zwlr_foreign_toplevel_handle_v1_activate(events.handle, seat); + stage = 10; + if (wl_display_roundtrip(connection.display) < 0 || !read_state(&state) || !state.activated || !state.focused) + goto failed; + zwlr_foreign_toplevel_handle_v1_set_rectangle(events.handle, xdg.surface, 0, 0, 1, 1); + zwlr_foreign_toplevel_handle_v1_close(events.handle); + stage = 11; + if (wl_display_roundtrip(connection.display) < 0 || !xdg.close_received) + goto failed; + zwlr_foreign_toplevel_handle_v1_destroy(events.handle); + events.handle = NULL; + zwlr_foreign_toplevel_manager_v1_stop(manager); + stage = 12; + if (wl_display_roundtrip(connection.display) < 0 || events.finished_count != 1) + goto failed; + + xdg_toplevel_client_destroy(&xdg); + wl_seat_destroy(seat); + wl_proxy_destroy((struct wl_proxy *)manager); + client_disconnect(&connection); + return 0; + +failed: + read_state(&state); + fprintf(stderr, + "wlr-foreign-toplevel failure at stage %u: handle=%p events=(toplevel=%u title=%u app-id=%u state=%u done=%u finished=%u) server=(output=%d wrapper=%d workspace=%d minimized=%d maximized=%d fullscreen=%d activated=%d focused=%d maximize-request=%d/%d after-request=%d)\n", + stage, (void *)events.handle, events.toplevel_count, events.title_count, + events.app_id_count, events.state_count, events.done_count, events.finished_count, + state.output_ready, state.wrapper_created, state.wrapper_in_workspace, state.minimized, + state.maximized, state.fullscreen, state.activated, state.focused, + state.maximize_request_count, state.last_maximize_request, + state.maximized_after_last_request); + if (events.handle) + zwlr_foreign_toplevel_handle_v1_destroy(events.handle); + xdg_toplevel_client_destroy(&xdg); + if (seat) + wl_seat_destroy(seat); + if (manager) + wl_proxy_destroy((struct wl_proxy *)manager); + client_disconnect(&connection); + return 1; +} diff --git a/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/wlr-foreign-toplevel-management-unstable-v1.h b/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/wlr-foreign-toplevel-management-unstable-v1.h new file mode 100644 index 0000000000..ef4c928706 --- /dev/null +++ b/tests/protocols/wlr-foreign-toplevel-management-unstable-v1/wlr-foreign-toplevel-management-unstable-v1.h @@ -0,0 +1,26 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +struct foreign_toplevel_server_state { + int output_ready; + int wrapper_created; + int wrapper_in_workspace; + int minimized; + int maximized; + int fullscreen; + int activated; + int focused; + int maximize_request_count; + int last_maximize_request; + int maximized_after_last_request; +}; + +#ifdef __cplusplus +} +#endif diff --git a/tests/protocols/wlr-gamma-control-unstable-v1/CMakeLists.txt b/tests/protocols/wlr-gamma-control-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..d8ef4eb3d2 --- /dev/null +++ b/tests/protocols/wlr-gamma-control-unstable-v1/CMakeLists.txt @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +treeland_add_protocol_test( + NAME wlr_gamma_control_unstable_v1 + XML "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-gamma-control-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wlr-gamma-control-unstable-v1.c" +) + +# A DRM backend is intentionally opt-in. The default protocol environment is +# headless and cannot advertise or apply a hardware gamma LUT. +if(TREELAND_ENABLE_GPU_PROTOCOL_TESTS) + treeland_add_protocol_test( + NAME wlr_gamma_control_unstable_v1_drm + XML "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-gamma-control-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wlr-gamma-control-unstable-v1.c" + ) + target_compile_definitions(test_wlr_gamma_control_unstable_v1_drm + PRIVATE TREELAND_PROTOCOL_EXPECT_DRM_GAMMA=1) + set_tests_properties(test_wlr_gamma_control_unstable_v1_drm PROPERTIES + ENVIRONMENT "WLR_BACKENDS=drm;WLR_RENDERER=gles2;TREELAND_TEST_PLUGINS_PATH=${TREELAND_PLUGINS_OUTPUT_PATH};DSG_DATA_DIRS=${TREELAND_PROTOCOL_TEST_DSG_DATA_DIRS};TREELAND_PROTOCOL_TEST_DSG_DIR=${TREELAND_PROTOCOL_TEST_DSG_DATA_DIR}" + LABELS "protocols;gpu;drm" + SKIP_RETURN_CODE 77 + ) +endif() diff --git a/tests/protocols/wlr-gamma-control-unstable-v1/README.md b/tests/protocols/wlr-gamma-control-unstable-v1/README.md new file mode 100644 index 0000000000..f5c6a54a27 --- /dev/null +++ b/tests/protocols/wlr-gamma-control-unstable-v1/README.md @@ -0,0 +1,48 @@ +# `wlr-gamma-control-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`3rdparty/wlroots/protocol/wlr-gamma-control-unstable-v1.xml`, + `zwlr_gamma_control_manager_v1` / `zwlr_gamma_control_v1` v1。 +- 测试源码:`tests/protocols/wlr-gamma-control-unstable-v1/`。 +- Fixture:完整 Treeland desktop integration fixture 与真实 headless `wl_output`。 +- 覆盖等级:P。 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 不支持 gamma LUT 的 output | bind manager 与 headless `wl_output`,`get_gamma_control` | 不发送 `gamma_size`,只发送一次 `failed` | P | +| failed control 的 request/lifetime | 在 failed 后用 pipe FD 调用 `set_gamma`,再 destroy control/manager | inert native resource 吸收 request、取得 FD,连接不发生 protocol error;两个 destroy 均可完成 | P | + +## 生产结果 + +Treeland 在 `WaylandServer::init()` 直接创建 wlroots native manager,并将 `set_gamma` signal 接到 +`WaylandServer::setGamma()`;waylib 当前没有 wrapper,native manager 随 display 销毁。 +headless CI 的真实 output 没有 gamma LUT,wlroots 因此发送 `failed`。可选 DRM runner 则将 +非 identity LUT 经 `WaylandServer::setGamma()` 提交到真实 output;该生产 commit 失败时 WaylandServer 发送 +`failed`,测试据此失败。 + +### 可选 DRM runner(I 级) + +`TREELAND_ENABLE_GPU_PROTOCOL_TESTS=ON` 时额外注册 +`test_wlr_gamma_control_unstable_v1_drm`。它使用 `WLR_BACKENDS=drm`,不创建 headless output; +因此普通无头 CI 不会注册或执行它。 + +运行时只有在物理 output 发送一次非零 `gamma_size` 时才继续。client 生成三条完整、非 identity +LUT ramp 并调用 `set_gamma`;wlroots 发出的 `set_gamma` signal 必须经生产 `WaylandServer::setGamma()` +提交到实际 DRM output。commit 失败会由 WaylandServer 发送 `failed`,测试将其判为失败;没有可用 LUT、 +无法创建 LUT 文件或不支持的 DRM 环境均返回 77 Skip。因此该路径证明真实 production output commit, +为 I 级。 + +## 已知边界 / 下一项结果 + +wlroots headless backend 的 gamma size 为零,普通 CI 无法合法创建 LUT。因此 CI 不能把 +`set_gamma` 成功、LUT commit 或 output 色彩变化报告为覆盖。 + +DRM runner 已覆盖 production commit。若要达到 V 级,仍需 DRM/KMS 可读取的 gamma state 或外部 +屏幕/readback fixture 验证实际呈现色彩;gamma-control 协议本身没有成功 ack,不能以“未 failed” +冒充像素结果。 + +- 未覆盖 LUT restore、多个 control 的 exclusivity。 +- 未覆盖错误长度 LUT 的 `invalid_gamma` protocol error;它同样需要非零 gamma size。 diff --git a/tests/protocols/wlr-gamma-control-unstable-v1/setup.cpp b/tests/protocols/wlr-gamma-control-unstable-v1/setup.cpp new file mode 100644 index 0000000000..1d4b8d8a39 --- /dev/null +++ b/tests/protocols/wlr-gamma-control-unstable-v1/setup.cpp @@ -0,0 +1,18 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-3.0-only + +#include "server-bridge.h" +#include "core/waylandserver.h" + +void protocol_test_setup(WaylandServer *server) +{ +#ifndef TREELAND_PROTOCOL_EXPECT_DRM_GAMMA + // wlroots headless outputs advertise gamma size zero. That is the CI + // capability boundary this protocol test deliberately observes. + add_headless_output(server->backend(), false); +#else + // The opt-in runner supplies WLR_BACKENDS=drm. Do not add a headless + // output: only the physical DRM output can advertise a hardware LUT. + (void)server; +#endif +} diff --git a/tests/protocols/wlr-gamma-control-unstable-v1/wlr-gamma-control-unstable-v1.c b/tests/protocols/wlr-gamma-control-unstable-v1/wlr-gamma-control-unstable-v1.c new file mode 100644 index 0000000000..689a58656f --- /dev/null +++ b/tests/protocols/wlr-gamma-control-unstable-v1/wlr-gamma-control-unstable-v1.c @@ -0,0 +1,154 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 200809L +#endif + +#include "client-connection.h" +#include "wlr-gamma-control-unstable-v1-client-protocol.h" + +#include +#ifdef TREELAND_PROTOCOL_EXPECT_DRM_GAMMA +#include +#include +#include +#endif + +struct gamma_events { + unsigned int gamma_size_count; + unsigned int failed_count; + uint32_t gamma_size; +}; + +static void gamma_size(void *data, struct zwlr_gamma_control_v1 *control, uint32_t size) +{ + (void)control; + struct gamma_events *events = data; + events->gamma_size = size; + events->gamma_size_count++; +} + +static void failed(void *data, struct zwlr_gamma_control_v1 *control) +{ + (void)control; + ((struct gamma_events *)data)->failed_count++; +} + +static const struct zwlr_gamma_control_v1_listener control_listener = { + .gamma_size = gamma_size, + .failed = failed, +}; + +#ifdef TREELAND_PROTOCOL_EXPECT_DRM_GAMMA +static int create_gamma_lut(uint32_t size) +{ + char path[] = "/tmp/treeland-gamma-lut-XXXXXX"; + const int fd = mkstemp(path); + if (fd < 0) + return -1; + unlink(path); + const size_t entries = (size_t)size * 3; + uint16_t *lut = calloc(entries, sizeof(*lut)); + if (!lut) { + close(fd); + return -1; + } + for (uint32_t index = 0; index < size; ++index) { + // A non-identity, monotonic LUT proves WaylandServer forwards all three + // channels to wlr_output_commit_state rather than only accepting FD. + const uint16_t value = (uint16_t)(((uint64_t)index * UINT16_MAX) / (size - 1)); + lut[index] = value; + lut[size + index] = (uint16_t)(UINT16_MAX - value); + lut[2 * size + index] = value / 2; + } + const size_t bytes = entries * sizeof(*lut); + size_t total_written = 0; + while (total_written < bytes) { + const ssize_t written = write(fd, (const char *)lut + total_written, bytes - total_written); + if (written <= 0) + break; + total_written += (size_t)written; + } + free(lut); + if (total_written != bytes || lseek(fd, 0, SEEK_SET) < 0) { + close(fd); + return -1; + } + return fd; +} +#endif + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + if (!client_connect(&connection, socket_name)) + return 1; + + struct zwlr_gamma_control_manager_v1 *manager = client_bind( + &connection, "zwlr_gamma_control_manager_v1", &zwlr_gamma_control_manager_v1_interface, 1); + struct wl_output *output = client_bind(&connection, "wl_output", &wl_output_interface, 1); + if (!manager || !output) { + fprintf(stderr, "wlr-gamma-control: manager or headless output missing\n"); + goto failed; + } + + struct gamma_events events = { 0 }; + struct zwlr_gamma_control_v1 *control = + zwlr_gamma_control_manager_v1_get_gamma_control(manager, output); + if (!control) { + fprintf(stderr, "wlr-gamma-control: could not create control proxy\n"); + goto failed; + } + zwlr_gamma_control_v1_add_listener(control, &control_listener, &events); +#ifdef TREELAND_PROTOCOL_EXPECT_DRM_GAMMA + if (wl_display_roundtrip(connection.display) < 0) { + zwlr_gamma_control_v1_destroy(control); + goto failed; + } + if (events.failed_count || events.gamma_size_count != 1 || events.gamma_size < 2) { + fprintf(stderr, "wlr-gamma-control: DRM output has no usable gamma LUT; skipped\n"); + zwlr_gamma_control_v1_destroy(control); + zwlr_gamma_control_manager_v1_destroy(manager); + wl_output_destroy(output); + client_disconnect(&connection); + return 77; + } + const int lut_fd = create_gamma_lut(events.gamma_size); + if (lut_fd < 0) { + fprintf(stderr, "wlr-gamma-control: could not allocate LUT; skipped\n"); + zwlr_gamma_control_v1_destroy(control); + zwlr_gamma_control_manager_v1_destroy(manager); + wl_output_destroy(output); + client_disconnect(&connection); + return 77; + } + zwlr_gamma_control_v1_set_gamma(control, lut_fd); + if (wl_display_roundtrip(connection.display) < 0 || events.failed_count) { + fprintf(stderr, "wlr-gamma-control: WaylandServer failed to commit DRM gamma LUT\n"); + zwlr_gamma_control_v1_destroy(control); + goto failed; + } +#else + if (wl_display_roundtrip(connection.display) < 0 || events.gamma_size_count != 0 + || events.failed_count != 1) { + fprintf(stderr, "wlr-gamma-control: headless output must report exactly one failed event\n"); + zwlr_gamma_control_v1_destroy(control); + goto failed; + } + +#endif + zwlr_gamma_control_v1_destroy(control); + zwlr_gamma_control_manager_v1_destroy(manager); + wl_output_destroy(output); + client_disconnect(&connection); + return 0; + +failed: + if (manager) + zwlr_gamma_control_manager_v1_destroy(manager); + if (output) + wl_output_destroy(output); + client_disconnect(&connection); + return 1; +} diff --git a/tests/protocols/wlr-layer-shell-unstable-v1/CMakeLists.txt b/tests/protocols/wlr-layer-shell-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..dc83a0405d --- /dev/null +++ b/tests/protocols/wlr-layer-shell-unstable-v1/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +treeland_add_protocol_test( + NAME wlr_layer_shell_unstable_v1 + XML "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-layer-shell-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wlr-layer-shell-unstable-v1.c" +) diff --git a/tests/protocols/wlr-layer-shell-unstable-v1/README.md b/tests/protocols/wlr-layer-shell-unstable-v1/README.md new file mode 100644 index 0000000000..1e97aa2f7b --- /dev/null +++ b/tests/protocols/wlr-layer-shell-unstable-v1/README.md @@ -0,0 +1,64 @@ +# `wlr-layer-shell-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`3rdparty/wlroots/protocol/wlr-layer-shell-unstable-v1.xml`, + `zwlr_layer_shell_v1` / `zwlr_layer_surface_v1` v5。 +- 测试源码:`tests/protocols/wlr-layer-shell-unstable-v1/`。 +- Fixture:完整 Treeland desktop integration fixture、真实 headless `wl_output`、默认 seat。 +- 覆盖等级:P / E。 + +wlroots 提供 native layer-shell;waylib 的 `WLayerShell` / `WLayerSurface` 负责 wrapper 与 +native handle 生命周期,`ShellHandler::init()` 通过 `attach()` 接入。测试前将 +waylib 发布版本由 v4 修正为 v5,故 XML 的 `set_exclusive_edge` 已可由真实 client 请求。 + +## 必须观察到的结果 + +| 场景 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 初始 layer 映射 | 创建 roleless `wl_surface`;`get_layer_surface(top)` 后设置 size、top/left/right anchor、exclusive zone、margin、exclusive keyboard 与 exclusive edge;先空 commit | client 收到唯一初始 `configure`,且尚未 attach buffer | P | +| configure 后映射 | 对最新 configure serial 调用 `ack_configure`,再 attach 1920×40 shm buffer 并 commit | 同一 surface 映射为真实 `WLayerSurface` / `SurfaceWrapper`,进入 top-layer 的 output container;其 anchor、exclusive-zone、top margin、keyboard interactivity 与请求一致 | E | +| exclusive keyboard | 映射 top-layer exclusive surface | 默认 seat container 的真实 `keyboardFocusSurface()` 是该 layer wrapper | E | +| layer 变更 | `set_layer(overlay)` 后 commit | 同一 production wrapper 从 top container 迁移到 overlay container,`WLayerSurface::layer()` 为 overlay | E | +| output 移除(迁移) | 再创建一个 `get_layer_surface(output=NULL)` 的浮动 layer surface 与一个 mapped xdg-toplevel;compositor 线程 `wlr_output_destroy()` 当前主屏 | 主屏切到剩余 output;带显式 output 的 surface 收到 `closed`;浮动 surface 不被关闭(迁移到新主屏);toplevel 的 `ownsOutput()` 仍非空且其几何中心落在该 output 内 | E | +| output 移除(全部) | 继续销毁剩下的 output,直到没有 output | `primaryOutput()` 变为 `nullptr`,浮动 layer surface 收到 `closed`;compositor 不 abort(本用例回归 `Q_ASSERT(container)`) | E | +| 生命周期 | `zwlr_layer_surface_v1.destroy`、`zwlr_layer_shell_v1.destroy` | layer resource 与 manager 均可正常销毁,无 protocol error | P | + +## 生产结果 + +测试 client 遵守 XML 的初始映射顺序:先获取 layer role、完成所有双缓冲 state request、空 +commit,等待生产 compositor 的 `configure`,ack 后才 attach buffer。fixture 不手工创建 +`WLayerSurface` 或发送 configure。 + +该 buffer commit 进入 wlroots native layer-shell;waylib `WLayerShell` 创建 +`WLayerSurface`,`ShellHandler::onLayerSurfaceAdded()` 为同一 surface 创建 `SurfaceWrapper`, +并由 `updateLayerSurfaceContainer()` 放入 Treeland top layer 对应的 output container。测试通过 +compositor-thread bridge 读取此真实 wrapper、其 `WLayerSurface` 属性和 container 归属。 + +top layer 的 exclusive keyboard interactivity 经生产 focus 规则使该 wrapper 成为默认 seat 的 +keyboard focus。之后同一 client 的 `set_layer(overlay)` commit 触发 waylib 的 `layerChanged`; +`ShellHandler` 将原 wrapper 移至 overlay container。上述映射、container placement、focus 与 +迁移构成 E 级业务链路;configure/ack、exclusive-edge 与 destroy 仅证明协议/生命周期,属于 P。 + +output 移除用例不伪造事件:compositor 线程直接 `wlr_output_destroy()` 一个 real headless +output,走的是与 DRM 拔出、VT 切换相同的 `WBackend::outputRemoved()` → +`OutputManager::outputRemoved()` → `RootSurfaceContainer::removeOutput()` 链。浮动 surface 的 +`WLayerSurface::output()` 恒为 `nullptr`,正是 `LayerSurfaceContainer::removeOutput()` 判定的 +「迁移到主屏」条件;主屏切换若晚于 per-output 容器拆除,就会在 +`addSurfaceToContainer()` 的 `Q_ASSERT(container)` abort(本用例在未修复版本上稳定复现 +`ASSERT: "container"`,修复后通过)。 + +同一个用例还盯住主屏移除的另外两个结果:`OutputManager::onScreenRemoved()` 必须把该屏上的 +普通窗口迁移到剩余主屏(否则窗口坐标停在已删除屏的坐标系、`ownsOutput` 被置空后不可见), +以及没有剩余 output 时 `primaryOutput()` 必须为 `nullptr` 而不是悬垂的主屏指针。为了让用例 +不依赖 fixture 恰好提供几个 output,服务端会回传移除前后的 output 数量,客户端据此选择 +「迁移」或「直接关闭」的预期;主屏判定也由服务端回传(wrapper 所在 container 的 output 是否 +等于 `primaryOutput()`),不靠 registry 顺序推测。 + +## 已知边界 / 下一项结果 + +- 未创建 xdg-popup,故未覆盖 `get_popup` 的 parent 关联。 +- 未在独立失败连接覆盖 role、invalid layer、already constructed、invalid size/anchor/keyboard + interactivity/exclusive edge 等 protocol error。 +- 未验证多个 layer surface 的 z-order、exclusive-zone 对 maximized toplevel usable area 的最终 + 几何影响,或最终 output 像素。 diff --git a/tests/protocols/wlr-layer-shell-unstable-v1/setup.cpp b/tests/protocols/wlr-layer-shell-unstable-v1/setup.cpp new file mode 100644 index 0000000000..bece7b78f4 --- /dev/null +++ b/tests/protocols/wlr-layer-shell-unstable-v1/setup.cpp @@ -0,0 +1,76 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "core/layersurfacecontainer.h" +#include "core/shellhandler.h" +#include "core/rootsurfacecontainer.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "output/output.h" +#include "surface/surfacewrapper.h" +#include "wlr-layer-shell-unstable-v1.h" +#include +#include +#include +namespace { +SurfaceWrapper *g_wrapper = nullptr; +SurfaceWrapper *g_window = nullptr; +} +void protocol_test_setup(WaylandServer *server) { + add_headless_output(server->backend(), false); + QObject::connect(server->shellHandler(), &ShellHandler::surfaceWrapperAdded, server, + [](SurfaceWrapper *wrapper) { + if (wrapper->type() == SurfaceWrapper::Type::Layer) + g_wrapper = wrapper; + else + g_window = wrapper; + }); +} +extern "C" void layer_shell_read_state(void *data) { + layer_shell_server_state state {}; + auto *layer = g_wrapper ? qobject_cast(g_wrapper->shellSurface()) : nullptr; + state.wrapper = layer != nullptr; + state.container = g_wrapper && g_wrapper->container(); + if (layer) { state.layer = (int)layer->layer(); state.anchor = layer->ancher().toInt(); state.exclusive_zone = layer->exclusiveZone(); state.top_margin = layer->topMargin(); state.keyboard_exclusive = layer->keyboardInteractivity() == WLayerSurface::KeyboardInteractivity::Exclusive; } + auto *root = WaylandServer::instance()->rootSurfaceContainer(); + // The test relies on the layer surface living on the primary output, which is + // the output the removal below destroys. + auto *container = qobject_cast(g_wrapper ? g_wrapper->container() : nullptr); + state.on_primary = container && container->output() == root->primaryOutput(); + auto *seat = root->getSeatContainerOrDefault(); + state.focused = seat && seat->keyboardFocusSurface() == g_wrapper; + *static_cast(data) = state; +} +// Destroys the primary output from the compositor thread. wlr_output_destroy() +// drives the same WBackend::outputRemoved() -> OutputManager::outputRemoved() +// chain as a DRM unplug or a VT switch: every output's layer surfaces are torn +// down, layer surfaces created without an output are re-homed to the primary +// output (which must never be the output being removed), and the windows of the +// removed output have to follow the new primary. +extern "C" void layer_shell_remove_primary_output(void *data) { + layer_shell_output_removal_state state {}; + auto *root = WaylandServer::instance()->rootSurfaceContainer(); + state.primary_before = root->primaryOutput() != nullptr; + state.outputs_before = root->outputs().size(); + for (auto *o : root->outputs()) { + if (o != root->primaryOutput() || !o->output()) + continue; + auto *handle = o->output()->handle(); + wlr_output_destroy(handle); + break; + } + state.primary_after = root->primaryOutput() != nullptr; + state.outputs_after = root->outputs().size(); + *static_cast(data) = state; +} +extern "C" void layer_shell_read_window_state(void *data) { + layer_shell_window_state state {}; + auto *root = WaylandServer::instance()->rootSurfaceContainer(); + state.mapped = g_window && g_window->shellSurface(); + if (g_window) { + auto *owns = g_window->ownsOutput(); + state.owns_output = owns != nullptr; + state.owns_primary = owns && owns == root->primaryOutput(); + state.inside_own_output = owns && owns->geometry().contains(g_window->geometry().center()); + } + *static_cast(data) = state; +} diff --git a/tests/protocols/wlr-layer-shell-unstable-v1/wlr-layer-shell-unstable-v1.c b/tests/protocols/wlr-layer-shell-unstable-v1/wlr-layer-shell-unstable-v1.c new file mode 100644 index 0000000000..ae04141822 --- /dev/null +++ b/tests/protocols/wlr-layer-shell-unstable-v1/wlr-layer-shell-unstable-v1.c @@ -0,0 +1,122 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#define _POSIX_C_SOURCE 200809L +#include "client-connection.h" +#include "server-bridge-api.h" +#include "wlr-layer-shell-unstable-v1-client-protocol.h" +#include "wlr-layer-shell-unstable-v1.h" +#include "xdg-toplevel-client.h" +#include +#include +#include +#include +#include +extern void layer_shell_read_state(void *data); +extern void layer_shell_remove_primary_output(void *data); +extern void layer_shell_read_window_state(void *data); +struct events { uint32_t serial, width, height; unsigned int configure, closed; }; +static void configure(void *d, struct zwlr_layer_surface_v1 *s, uint32_t serial, uint32_t width, uint32_t height) { (void)s; struct events *e=d; e->serial=serial; e->width=width; e->height=height; e->configure++; } +static void closed(void *d, struct zwlr_layer_surface_v1 *s) { (void)s; ((struct events*)d)->closed++; } +static const struct zwlr_layer_surface_v1_listener listener = { .configure=configure, .closed=closed }; +static int make_buffer(struct wl_shm *shm, struct wl_buffer **buffer) { + char name[]="/treeland-layer-XXXXXX"; int fd=shm_open(name,O_RDWR|O_CREAT|O_EXCL,0600); if(fd<0)return 0; shm_unlink(name); const int w=1920,h=40,stride=w*4,size=stride*h; if(ftruncate(fd,size)<0){close(fd);return 0;} void *p=mmap(NULL,size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); if(p==MAP_FAILED){close(fd);return 0;} memset(p,0xff,size); struct wl_shm_pool *pool=wl_shm_create_pool(shm,fd,size); *buffer=pool?wl_shm_pool_create_buffer(pool,0,w,h,stride,WL_SHM_FORMAT_ARGB8888):NULL; if(pool)wl_shm_pool_destroy(pool); munmap(p,size); close(fd); return *buffer!=NULL; +} +int protocol_test_run(const char *socket) { + struct client_connection c; struct wl_surface *surface=NULL; struct wl_buffer *buffer=NULL; unsigned int stage = 0; if(!client_connect(&c,socket))return 1; + struct wl_compositor *compositor=client_bind(&c,"wl_compositor",&wl_compositor_interface,1); struct wl_shm *shm=client_bind(&c,"wl_shm",&wl_shm_interface,1); struct wl_output *output=client_bind(&c,"wl_output",&wl_output_interface,1); struct zwlr_layer_shell_v1 *shell=client_bind(&c,"zwlr_layer_shell_v1",&zwlr_layer_shell_v1_interface,5); + if (!compositor || !shm || !output || !shell) + goto fail; + + stage = 1; + surface = wl_compositor_create_surface(compositor); + if (!surface) + goto fail; + struct zwlr_layer_surface_v1 *layer=zwlr_layer_shell_v1_get_layer_surface(shell,surface,output,ZWLR_LAYER_SHELL_V1_LAYER_TOP,"protocol-test"); struct events e={0}; if(!layer)goto fail; zwlr_layer_surface_v1_add_listener(layer,&listener,&e); + zwlr_layer_surface_v1_set_size(layer,1920,40); zwlr_layer_surface_v1_set_anchor(layer,ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP|ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT|ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT); zwlr_layer_surface_v1_set_exclusive_zone(layer,40); zwlr_layer_surface_v1_set_margin(layer,2,0,0,0); zwlr_layer_surface_v1_set_keyboard_interactivity(layer,ZWLR_LAYER_SURFACE_V1_KEYBOARD_INTERACTIVITY_EXCLUSIVE); zwlr_layer_surface_v1_set_exclusive_edge(layer,ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP); wl_surface_commit(surface); + // A layer arrange can legitimately issue a replacement configure before + // the client processes the first one. Acknowledge the newest serial. + stage = 2; if(wl_display_roundtrip(c.display)<0||!e.configure||!e.serial)goto fail_layer; zwlr_layer_surface_v1_ack_configure(layer,e.serial); if(!make_buffer(shm,&buffer))goto fail_layer; wl_surface_attach(surface,buffer,0,0); wl_surface_damage(surface,0,0,1920,40); wl_surface_commit(surface); stage = 3; if(wl_display_roundtrip(c.display)<0)goto fail_layer; + struct layer_shell_server_state state={0}; stage = 4; if(!invoke_on_server_thread(layer_shell_read_state,&state)||!state.wrapper||!state.container||state.layer!=ZWLR_LAYER_SHELL_V1_LAYER_TOP||state.anchor!=(ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP|ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT|ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT)||state.exclusive_zone!=40||state.top_margin!=2||!state.keyboard_exclusive||!state.focused||!state.on_primary)goto fail_layer; + zwlr_layer_surface_v1_set_layer(layer,ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY); wl_surface_commit(surface); stage = 5; if(wl_display_roundtrip(c.display)<0||!invoke_on_server_thread(layer_shell_read_state,&state)||state.layer!=ZWLR_LAYER_SHELL_V1_LAYER_OVERLAY)goto fail_layer; + + // A layer surface created without an output keeps WLayerSurface::output() == NULL, + // which is the condition LayerSurfaceContainer::removeOutput() uses to re-home + // (or, without a remaining output, close) the surface. + stage = 6; + struct wl_surface *floatingSurface = wl_compositor_create_surface(compositor); + struct zwlr_layer_surface_v1 *floating = floatingSurface ? zwlr_layer_shell_v1_get_layer_surface(shell, floatingSurface, NULL, ZWLR_LAYER_SHELL_V1_LAYER_TOP, "protocol-test-floating") : NULL; + struct wl_buffer *floatingBuffer = NULL; + struct events ef = {0}; + struct layer_shell_output_removal_state removal = {0}; + if (!floating) + goto fail_removal; + zwlr_layer_surface_v1_add_listener(floating, &listener, &ef); + zwlr_layer_surface_v1_set_size(floating, 1920, 40); + wl_surface_commit(floatingSurface); + stage = 7; + if (wl_display_roundtrip(c.display) < 0 || !ef.configure || !ef.serial) + goto fail_removal; + zwlr_layer_surface_v1_ack_configure(floating, ef.serial); + if (!make_buffer(shm, &floatingBuffer)) + goto fail_removal; + wl_surface_attach(floatingSurface, floatingBuffer, 0, 0); + wl_surface_damage(floatingSurface, 0, 0, 1920, 40); + wl_surface_commit(floatingSurface); + stage = 8; + if (wl_display_roundtrip(c.display) < 0) + goto fail_removal; + + // A mapped toplevel on the primary output: removing that output must move it + // to the remaining screen instead of leaving it outside every screen. + stage = 9; + struct xdg_toplevel_client window = {0}; + if (!xdg_toplevel_client_create_with_solid_buffer(&c, &window, 200, 150, 0xff00ff00u)) + goto fail_removal; + stage = 10; + if (wl_display_roundtrip(c.display) < 0) + goto fail_removal; + struct layer_shell_window_state window_state = {0}; + if (!invoke_on_server_thread(layer_shell_read_window_state, &window_state) + || !window_state.mapped || !window_state.owns_primary || !window_state.inside_own_output) + goto fail_removal; + + // Remove the primary output while both layer surfaces and the window are + // mapped, then keep removing outputs until none is left. + stage = 11; + if (!invoke_on_server_thread(layer_shell_remove_primary_output, &removal)) + goto fail_removal; + stage = 12; + if (wl_display_roundtrip(c.display) < 0) + goto fail_removal; + if (!removal.primary_before || removal.outputs_after != removal.outputs_before - 1 + || removal.primary_after != (removal.outputs_after > 0) || e.closed != 1) + goto fail_removal; + if (removal.outputs_before >= 2) { + // Another screen is left: it becomes the new primary, the floating surface + // moves there and the window follows it. + if (ef.closed != 0 || !invoke_on_server_thread(layer_shell_read_window_state, &window_state) + || !window_state.owns_output || !window_state.owns_primary + || !window_state.inside_own_output) + goto fail_removal; + } else if (ef.closed != 1) { + goto fail_removal; + } + + stage = 13; + for (int i = 0; i < 8 && removal.outputs_after > 0; i++) { + if (!invoke_on_server_thread(layer_shell_remove_primary_output, &removal) + || wl_display_roundtrip(c.display) < 0) + goto fail_removal; + // Invariant: as long as an output is left, it must be the primary. + if (removal.primary_after != (removal.outputs_after > 0)) + goto fail_removal; + } + // No output left: the primary is cleared and the floating surface is closed + // instead of being re-homed to a destroyed output. + if (removal.primary_after || removal.outputs_after != 0 || ef.closed != 1) + goto fail_removal; + + xdg_toplevel_client_destroy(&window); zwlr_layer_surface_v1_destroy(floating); zwlr_layer_surface_v1_destroy(layer); zwlr_layer_shell_v1_destroy(shell); wl_buffer_destroy(floatingBuffer); wl_buffer_destroy(buffer); wl_surface_destroy(floatingSurface); wl_surface_destroy(surface); wl_output_destroy(output); wl_shm_destroy(shm); wl_compositor_destroy(compositor); client_disconnect(&c); return 0; +fail_removal: fprintf(stderr, "wlr-layer-shell output-removal failure at stage %u: primary=(before=%d after=%d) outputs=(before=%d after=%d) closed=(floating=%u explicit=%u) window=(mapped=%d owns-primary=%d owns-output=%d inside-own-output=%d)\n", stage, removal.primary_before, removal.primary_after, removal.outputs_before, removal.outputs_after, ef.closed, e.closed, window_state.mapped, window_state.owns_primary, window_state.owns_output, window_state.inside_own_output); if(window.toplevel)xdg_toplevel_client_destroy(&window); if(floating)zwlr_layer_surface_v1_destroy(floating); if(floatingBuffer)wl_buffer_destroy(floatingBuffer); if(floatingSurface)wl_surface_destroy(floatingSurface); zwlr_layer_surface_v1_destroy(layer); zwlr_layer_shell_v1_destroy(shell); wl_buffer_destroy(buffer); wl_surface_destroy(surface); wl_output_destroy(output); wl_shm_destroy(shm); wl_compositor_destroy(compositor); client_disconnect(&c); return 1; +fail_layer: fprintf(stderr, "wlr-layer-shell failure at stage %u: configure=%u serial=%u size=%ux%u state=(wrapper=%d container=%d layer=%d anchor=%d exclusive-zone=%d top-margin=%d keyboard-exclusive=%d focused=%d)\n", stage, e.configure, e.serial, e.width, e.height, state.wrapper, state.container, state.layer, state.anchor, state.exclusive_zone, state.top_margin, state.keyboard_exclusive, state.focused); zwlr_layer_surface_v1_destroy(layer); if(buffer)wl_buffer_destroy(buffer); if(surface)wl_surface_destroy(surface); fail: if(stage < 2) fprintf(stderr, "wlr-layer-shell failure at stage %u: missing required global or wl_surface\n", stage); if(shell)zwlr_layer_shell_v1_destroy(shell); if(output)wl_output_destroy(output); if(shm)wl_shm_destroy(shm); if(compositor)wl_compositor_destroy(compositor); client_disconnect(&c); return 1; +} diff --git a/tests/protocols/wlr-layer-shell-unstable-v1/wlr-layer-shell-unstable-v1.h b/tests/protocols/wlr-layer-shell-unstable-v1/wlr-layer-shell-unstable-v1.h new file mode 100644 index 0000000000..965371a3da --- /dev/null +++ b/tests/protocols/wlr-layer-shell-unstable-v1/wlr-layer-shell-unstable-v1.h @@ -0,0 +1,6 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once +struct layer_shell_server_state { int wrapper; int container; int layer; int anchor; int exclusive_zone; int top_margin; int keyboard_exclusive; int focused; int on_primary; }; +struct layer_shell_output_removal_state { int primary_before; int primary_after; int outputs_before; int outputs_after; }; +struct layer_shell_window_state { int mapped; int owns_primary; int owns_output; int inside_own_output; }; diff --git a/tests/protocols/wlr-output-management-unstable-v1/CMakeLists.txt b/tests/protocols/wlr-output-management-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..30ae01f750 --- /dev/null +++ b/tests/protocols/wlr-output-management-unstable-v1/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +treeland_add_protocol_test( + NAME wlr_output_management_unstable_v1 + XML "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-output-management-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wlr-output-management-unstable-v1.c" +) diff --git a/tests/protocols/wlr-output-management-unstable-v1/README.md b/tests/protocols/wlr-output-management-unstable-v1/README.md new file mode 100644 index 0000000000..8c1de52cf5 --- /dev/null +++ b/tests/protocols/wlr-output-management-unstable-v1/README.md @@ -0,0 +1,61 @@ +# `wlr-output-management-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`3rdparty/wlroots/protocol/wlr-output-management-unstable-v1.xml` / + `zwlr_output_manager_v1`、head、mode、configuration 与 configuration-head v4。 +- 测试源码:`tests/protocols/wlr-output-management-unstable-v1/`。 +- Fixture:完整 Treeland desktop integration fixture 与一个 `1920×1080` headless output。 +- 覆盖等级:**P / E**;P 覆盖 native global 的快照、transaction 与生命周期,E 覆盖配置从 + client 经 `WOutputManagerV1`/`WaylandServer` 提交到真实 output 的 position、transform 与 scale。 + +## 必须观察到的结果 + +| XML 语义 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 初始 output 描述 | bind manager v4 并 roundtrip | 一个 head、`name`、`description`、virtual mode 的 `size`、`current_mode`、`enabled`、`position`、`transform`、`scale`、`adaptive_sync` 与携带 serial 的 `done`;仅在固定刷新率时要求 `refresh` | P | +| enabled configuration test | 用最新 serial 创建 configuration,为唯一 head 调用 `enable_head`、custom mode、position、transform、scale、adaptive-sync 后 `test` | 唯一 `succeeded`,无 `failed/cancelled`;不改变 output 状态 | P | +| disabled configuration test | 新 configuration 对唯一 head 调用 `disable_head` 后 `test` | 唯一 `succeeded`,不关闭 fixture output | P | +| apply 的业务结果 | enabled configuration 设置 custom `1920×1080`、position `(37,53)`、`transform=90°`、`scale=2` 后 `apply` | `succeeded`,fixture 从真实 production output 读取到 enabled、坐标 `(37,53)`、90° 与 scale 2 | E | +| 恢复配置 | 用新 serial apply `(0,0)`、normal transform、scale 1 | `succeeded`,真实 output 回到 `(0,0)`、normal、scale 1 | E | +| manager/head/mode 生命周期 | `stop`、收到 `finished`,release head 与 virtual mode | `finished` 恰好一次,client 可释放子资源 | P | + +## 生产结果 + +wlroots 原生实现 `wlr_output_manager_v1`;waylib 的 `WOutputManagerV1` 创建并拥有 native +manager。`WaylandServer::init()` 通过 `m_server->attach()` 发布 global,并把 +`requestTestOrApply` 接到 `WaylandServer::onOutputTestOrApply()`。 + +测试不会在 fixture 伪造 configuration result。`test` 由 WaylandServer 对真实 output 调用 +`wlr_output_test_state()` 后回传 `succeeded`;`apply` 则进入 production render/commit job,完成后 +由 `WaylandServer::onOutputCommitFinished()` 发送 `succeeded`、更新 output layout。fixture 随后读取 +`RootSurfaceContainer` 中同一个 `WOutput` 的 `WOutputItem`,并读取该 output 的 production +orientation/scale。因此 `(37,53)`、90°、scale 2 及回滚 `(0,0)`、normal、scale 1 是 E 级输出布局 +结果,而不仅是 client 收到了成功 event。 + +### E 级覆盖流程 + +1. fixture 在 CI 的 `WLR_BACKENDS=headless;WLR_RENDERER=pixman` 环境创建一个真实 + `1920×1080` headless `wlr_output`,不依赖物理显示器、GPU 或系统 display manager; +2. client 以 manager `done` 的最新 serial 创建完整 configuration,提交 custom mode、position + `(37,53)`、90° transform 和 scale 2; +3. production `WOutputManagerV1` 发出 apply signal,`WaylandServer` 对真实 output 建立 commit job;成功 + 回调更新 output layout 并发送 configuration `succeeded`; +4. client 在成功 event 后调用 fixture,fixture 从同一个 production `WOutputItem` 读取位置,并从 + 同一个 `WOutput` 读取 orientation 和 scale,必须分别为 `(37,53)`、90°、2; +5. client 用新 serial apply normal、scale 1、`(0,0)`,并以相同的 production state readback + 验证恢复。 + +步骤 4 与 5 不读取 client event 缓存,也不调用测试专用 setter;因此该结论是 E 级。该流程待首次 +CI 执行记录结果,当前未因本次实现而声称已通过。 + +## 已知边界 / 下一项结果 + +- headless output 没有固定 mode;测试以生产 headless 的 custom `1920×1080` mode 覆盖 + `set_custom_mode`。有固定 mode 的 GPU/X11 runner 可补 `mode/size/refresh/preferred/current_mode` event + 与 `set_mode` 的 I/E 路径。 +- 尚未构造 stale serial 的 `cancelled`,以及 duplicate/unconfigured/used configuration 的 error;这些 + 应由独立连接断言 protocol error,避免破坏主 E 链路。 +- 尚未验证多 output 的相对布局、真正 disable/apply、adaptive-sync 的硬件结果,或 output hotplug + 导致的 head/mode `finished`。这些场景需要多 head 或支持 VRR 的 runner;scale/transform 已覆盖 + production state,不等同于最终像素 readback。 diff --git a/tests/protocols/wlr-output-management-unstable-v1/setup.cpp b/tests/protocols/wlr-output-management-unstable-v1/setup.cpp new file mode 100644 index 0000000000..c618125f99 --- /dev/null +++ b/tests/protocols/wlr-output-management-unstable-v1/setup.cpp @@ -0,0 +1,82 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "core/rootsurfacecontainer.h" +#include "output/output.h" +#include "server-bridge.h" +#include "core/waylandserver.h" +#include "wlr-output-management-unstable-v1.h" + +#include +#include +#include +#include +#include + +namespace { +int g_requestCount = 0; +int g_lastRequestTest = -1; +int g_lastRequestTransform = -1; +int g_lastRequestScaleMilli = -1; +} + +void protocol_test_setup(WaylandServer *server) +{ + auto *manager = find_server_interface(server); + Q_ASSERT(manager); + QObject::connect(manager, &WOutputManagerV1::requestTestOrApply, server, + [manager](wlr_output_configuration_v1 *config, bool onlyTest) { + const auto states = manager->stateListPending(config); + ++g_requestCount; + g_lastRequestTest = onlyTest; + if (states.isEmpty()) + return; + g_lastRequestTransform = static_cast(states.constFirst().transform); + g_lastRequestScaleMilli = + static_cast(states.constFirst().scale * 1000.0f); + }); +} + +extern "C" void output_management_render(void *) +{ + const auto outputs = WaylandServer::instance()->rootSurfaceContainer()->outputs(); + if (outputs.isEmpty()) + return; + + auto *viewport = outputs.constFirst()->screenViewport(); + // Force the production output frame that commits the queued transaction. + WaylandServer::instance()->window()->render(viewport, true); +} + +extern "C" void output_management_read_server_state(void *data) +{ + output_management_server_state state {}; + const auto outputs = WaylandServer::instance()->rootSurfaceContainer()->outputs(); + state.output_count = outputs.size(); + + if (!outputs.isEmpty()) { + auto *output = outputs.constFirst()->output(); + const auto *item = WOutputItem::getOutputItem(output); + state.enabled = output->isEnabled(); + state.transform = static_cast(output->orientation()); + state.scale_milli = static_cast(output->scale() * 1000.0f); + if (item) { + state.x = static_cast(item->x()); + state.y = static_cast(item->y()); + } + if (auto *outputHelper = WaylandServer::instance()->window()->getOutputHelper(outputs.constFirst()->screenViewport())) { + const auto pending = outputHelper->extraState(); + state.pending_state = pending ? 1 : 0; + if (pending) { + state.pending_transform = static_cast(pending->transform); + state.pending_scale_milli = static_cast(pending->scale * 1000.0f); + } + } + } + state.request_count = g_requestCount; + state.last_request_test = g_lastRequestTest; + state.last_request_transform = g_lastRequestTransform; + state.last_request_scale_milli = g_lastRequestScaleMilli; + + *static_cast(data) = state; +} diff --git a/tests/protocols/wlr-output-management-unstable-v1/wlr-output-management-unstable-v1.c b/tests/protocols/wlr-output-management-unstable-v1/wlr-output-management-unstable-v1.c new file mode 100644 index 0000000000..71bf646e30 --- /dev/null +++ b/tests/protocols/wlr-output-management-unstable-v1/wlr-output-management-unstable-v1.c @@ -0,0 +1,443 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "client-connection.h" +#include "server-bridge-api.h" +#include "wlr-output-management-unstable-v1-client-protocol.h" +#include "wlr-output-management-unstable-v1.h" + +#include +#include +#include + +extern void output_management_read_server_state(void *data); +extern void output_management_render(void *data); + +struct output_events { + struct zwlr_output_head_v1 *head; + struct zwlr_output_mode_v1 *mode; + uint32_t serial; + int manager_done_count; + int manager_finished_count; + int head_name_count; + int head_description_count; + int head_enabled_count; + int head_current_mode_count; + int head_position_count; + int head_transform_count; + int head_scale_count; + int head_adaptive_sync_count; + int mode_size_count; + int mode_refresh_count; + int mode_preferred_count; + int configuration_succeeded_count; + int configuration_failed_count; + int configuration_cancelled_count; + int position_x; + int position_y; +}; + +static const struct zwlr_output_mode_v1_listener mode_listener; + +static void head_name(void *data, struct zwlr_output_head_v1 *head, const char *name) +{ + (void)head; + (void)name; + ((struct output_events *)data)->head_name_count++; +} + +static void head_description(void *data, struct zwlr_output_head_v1 *head, const char *description) +{ + (void)head; + (void)description; + ((struct output_events *)data)->head_description_count++; +} + +static void head_physical_size(void *data, struct zwlr_output_head_v1 *head, int32_t width, int32_t height) +{ + (void)data; + (void)head; + (void)width; + (void)height; +} + +static void head_mode(void *data, struct zwlr_output_head_v1 *head, struct zwlr_output_mode_v1 *mode) +{ + (void)head; + struct output_events *events = data; + events->mode = mode; + zwlr_output_mode_v1_add_listener(mode, &mode_listener, events); +} + +static void head_enabled(void *data, struct zwlr_output_head_v1 *head, int32_t enabled) +{ + (void)head; + (void)enabled; + ((struct output_events *)data)->head_enabled_count++; +} + +static void head_current_mode(void *data, struct zwlr_output_head_v1 *head, struct zwlr_output_mode_v1 *mode) +{ + (void)head; + (void)mode; + ((struct output_events *)data)->head_current_mode_count++; +} + +static void head_position(void *data, struct zwlr_output_head_v1 *head, int32_t x, int32_t y) +{ + (void)head; + struct output_events *events = data; + events->position_x = x; + events->position_y = y; + events->head_position_count++; +} + +static void head_transform(void *data, struct zwlr_output_head_v1 *head, int32_t transform) +{ + (void)head; + (void)transform; + ((struct output_events *)data)->head_transform_count++; +} + +static void head_scale(void *data, struct zwlr_output_head_v1 *head, wl_fixed_t scale) +{ + (void)head; + (void)scale; + ((struct output_events *)data)->head_scale_count++; +} + +static void head_finished(void *data, struct zwlr_output_head_v1 *head) +{ + (void)data; + (void)head; +} + +static void head_make(void *data, struct zwlr_output_head_v1 *head, const char *make) +{ + (void)data; + (void)head; + (void)make; +} + +static void head_model(void *data, struct zwlr_output_head_v1 *head, const char *model) +{ + (void)data; + (void)head; + (void)model; +} + +static void head_serial_number(void *data, struct zwlr_output_head_v1 *head, const char *serial_number) +{ + (void)data; + (void)head; + (void)serial_number; +} + +static void head_adaptive_sync(void *data, struct zwlr_output_head_v1 *head, uint32_t state) +{ + (void)head; + (void)state; + ((struct output_events *)data)->head_adaptive_sync_count++; +} + +static const struct zwlr_output_head_v1_listener head_listener = { + .name = head_name, + .description = head_description, + .physical_size = head_physical_size, + .mode = head_mode, + .enabled = head_enabled, + .current_mode = head_current_mode, + .position = head_position, + .transform = head_transform, + .scale = head_scale, + .finished = head_finished, + .make = head_make, + .model = head_model, + .serial_number = head_serial_number, + .adaptive_sync = head_adaptive_sync, +}; + +static void mode_size(void *data, struct zwlr_output_mode_v1 *mode, int32_t width, int32_t height) +{ + (void)mode; + (void)width; + (void)height; + ((struct output_events *)data)->mode_size_count++; +} + +static void mode_refresh(void *data, struct zwlr_output_mode_v1 *mode, int32_t refresh) +{ + (void)mode; + (void)refresh; + ((struct output_events *)data)->mode_refresh_count++; +} + +static void mode_preferred(void *data, struct zwlr_output_mode_v1 *mode) +{ + (void)mode; + ((struct output_events *)data)->mode_preferred_count++; +} + +static void mode_finished(void *data, struct zwlr_output_mode_v1 *mode) +{ + (void)data; + (void)mode; +} + +static const struct zwlr_output_mode_v1_listener mode_listener = { + .size = mode_size, + .refresh = mode_refresh, + .preferred = mode_preferred, + .finished = mode_finished, +}; + +static void manager_head(void *data, struct zwlr_output_manager_v1 *manager, + struct zwlr_output_head_v1 *head) +{ + (void)manager; + struct output_events *events = data; + events->head = head; + zwlr_output_head_v1_add_listener(head, &head_listener, events); +} + +static void manager_done(void *data, struct zwlr_output_manager_v1 *manager, uint32_t serial) +{ + (void)manager; + struct output_events *events = data; + events->serial = serial; + events->manager_done_count++; +} + +static void manager_finished(void *data, struct zwlr_output_manager_v1 *manager) +{ + (void)manager; + ((struct output_events *)data)->manager_finished_count++; +} + +static const struct zwlr_output_manager_v1_listener manager_listener = { + .head = manager_head, + .done = manager_done, + .finished = manager_finished, +}; + +static void configuration_succeeded(void *data, struct zwlr_output_configuration_v1 *configuration) +{ + (void)configuration; + ((struct output_events *)data)->configuration_succeeded_count++; +} + +static void configuration_failed(void *data, struct zwlr_output_configuration_v1 *configuration) +{ + (void)configuration; + ((struct output_events *)data)->configuration_failed_count++; +} + +static void configuration_cancelled(void *data, struct zwlr_output_configuration_v1 *configuration) +{ + (void)configuration; + ((struct output_events *)data)->configuration_cancelled_count++; +} + +static const struct zwlr_output_configuration_v1_listener configuration_listener = { + .succeeded = configuration_succeeded, + .failed = configuration_failed, + .cancelled = configuration_cancelled, +}; + +static int read_server_state(struct output_management_server_state *state) +{ + memset(state, 0, sizeof(*state)); + return invoke_on_server_thread(output_management_read_server_state, state); +} + +/* + * The transform is committed later than the rest of the configuration: the + * rotation animation stages it at its half-way point (SourceOutput.qml) and the + * frame it then schedules commits it. Poll the compositor until one of the + * requested frames has landed, so the assertion below still checks the real + * committed transform instead of racing the animation's 100 ms timer. + */ +static int wait_for_committed_transform(struct output_management_server_state *state, int transform) +{ + for (int attempt = 0; attempt < 100; ++attempt) { + invoke_on_server_thread(output_management_render, NULL); + if (!read_server_state(state)) + return 0; + if (state->output_count == 1 && state->transform == transform) + return 1; + struct timespec delay = { 0, 20 * 1000 * 1000 }; + nanosleep(&delay, NULL); + } + // Keep the last state for the failure diagnostic. + read_server_state(state); + return 0; +} + +static struct zwlr_output_configuration_v1 *create_enabled_configuration( + struct zwlr_output_manager_v1 *manager, struct output_events *events, int x, int y, + int32_t transform, wl_fixed_t scale) +{ + struct zwlr_output_configuration_v1 *configuration = + zwlr_output_manager_v1_create_configuration(manager, events->serial); + if (!configuration) + return NULL; + + zwlr_output_configuration_v1_add_listener(configuration, &configuration_listener, events); + struct zwlr_output_configuration_head_v1 *head = + zwlr_output_configuration_v1_enable_head(configuration, events->head); + if (!head) { + zwlr_output_configuration_v1_destroy(configuration); + return NULL; + } + + /* The headless backend has no advertised fixed mode. Use its real 1920x1080 custom mode. */ + zwlr_output_configuration_head_v1_set_custom_mode(head, 1920, 1080, 0); + zwlr_output_configuration_head_v1_set_position(head, x, y); + zwlr_output_configuration_head_v1_set_transform(head, transform); + zwlr_output_configuration_head_v1_set_scale(head, scale); + zwlr_output_configuration_head_v1_set_adaptive_sync( + head, ZWLR_OUTPUT_HEAD_V1_ADAPTIVE_SYNC_STATE_DISABLED); + return configuration; +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + struct zwlr_output_manager_v1 *manager = NULL; + struct output_events events = { 0 }; + struct output_management_server_state state = { 0 }; + int stage = 0; + int result = 1; + + if (!client_connect(&connection, socket_name)) + return 1; + + manager = client_bind(&connection, "zwlr_output_manager_v1", + &zwlr_output_manager_v1_interface, 4); + if (!manager) + goto done; + stage = 1; + zwlr_output_manager_v1_add_listener(manager, &manager_listener, &events); + if (wl_display_roundtrip(connection.display) < 0 || !events.head || !events.manager_done_count + || !events.head_name_count || !events.head_description_count || !events.head_enabled_count + || !events.head_current_mode_count || !events.head_position_count || !events.head_transform_count + || !events.head_scale_count || !events.head_adaptive_sync_count || !events.mode + || !events.mode_size_count) + goto done; + + stage = 2; + struct zwlr_output_configuration_v1 *configuration = + create_enabled_configuration(manager, &events, 0, 0, WL_OUTPUT_TRANSFORM_NORMAL, + wl_fixed_from_int(1)); + if (!configuration) + goto done; + stage = 3; + zwlr_output_configuration_v1_test(configuration); + if (wl_display_roundtrip(connection.display) < 0 || events.configuration_succeeded_count != 1 + || events.configuration_failed_count || events.configuration_cancelled_count) { + zwlr_output_configuration_v1_destroy(configuration); + goto done; + } + zwlr_output_configuration_v1_destroy(configuration); + if (wl_display_roundtrip(connection.display) < 0) + goto done; + + stage = 4; + configuration = zwlr_output_manager_v1_create_configuration(manager, events.serial); + if (!configuration) + goto done; + zwlr_output_configuration_v1_add_listener(configuration, &configuration_listener, &events); + zwlr_output_configuration_v1_disable_head(configuration, events.head); + stage = 5; + zwlr_output_configuration_v1_test(configuration); + if (wl_display_roundtrip(connection.display) < 0 || events.configuration_succeeded_count != 2 + || events.configuration_failed_count || events.configuration_cancelled_count) { + zwlr_output_configuration_v1_destroy(configuration); + goto done; + } + zwlr_output_configuration_v1_destroy(configuration); + if (wl_display_roundtrip(connection.display) < 0) + goto done; + + stage = 6; + configuration = create_enabled_configuration(manager, &events, 37, 53, WL_OUTPUT_TRANSFORM_90, + wl_fixed_from_int(2)); + if (!configuration) + goto done; + stage = 7; + zwlr_output_configuration_v1_apply(configuration); + if (wl_display_roundtrip(connection.display) < 0 + || !invoke_on_server_thread(output_management_render, NULL) + || wl_display_roundtrip(connection.display) < 0 || events.configuration_succeeded_count != 3 + || events.configuration_failed_count || events.configuration_cancelled_count) { + zwlr_output_configuration_v1_destroy(configuration); + goto done; + } + zwlr_output_configuration_v1_destroy(configuration); + if (wl_display_roundtrip(connection.display) < 0) + goto done; + stage = 8; + if (!wait_for_committed_transform(&state, WL_OUTPUT_TRANSFORM_90) || state.output_count != 1 + || !state.enabled || state.x != 37 || state.y != 53 || state.scale_milli != 2000) + goto done; + // Dispatch the events the commit produced (a new serial for the next + // configuration) before creating it. + if (wl_display_roundtrip(connection.display) < 0) + goto done; + + stage = 9; + configuration = create_enabled_configuration(manager, &events, 0, 0, WL_OUTPUT_TRANSFORM_NORMAL, + wl_fixed_from_int(1)); + if (!configuration) + goto done; + stage = 10; + zwlr_output_configuration_v1_apply(configuration); + if (wl_display_roundtrip(connection.display) < 0 + || !invoke_on_server_thread(output_management_render, NULL) + || wl_display_roundtrip(connection.display) < 0 || events.configuration_succeeded_count != 4 + || events.configuration_failed_count || events.configuration_cancelled_count) { + zwlr_output_configuration_v1_destroy(configuration); + goto done; + } + zwlr_output_configuration_v1_destroy(configuration); + if (wl_display_roundtrip(connection.display) < 0) + goto done; + stage = 11; + if (!wait_for_committed_transform(&state, WL_OUTPUT_TRANSFORM_NORMAL) || state.x || state.y + || state.scale_milli != 1000) + goto done; + + stage = 12; + zwlr_output_manager_v1_stop(manager); + if (wl_display_roundtrip(connection.display) < 0 || events.manager_finished_count != 1) + goto done; + + if (events.mode) + zwlr_output_mode_v1_release(events.mode); + zwlr_output_head_v1_release(events.head); + result = 0; + +done: + if (result) { + read_server_state(&state); + fprintf(stderr, + "wlr-output-management failure at stage %d: serial=%u events=(head=%p mode=%p done=%d finished=%d name=%d description=%d enabled=%d current-mode=%d position=%d transform=%d scale=%d adaptive-sync=%d mode-size=%d mode-refresh=%d succeeded=%d failed=%d cancelled=%d) server=(outputs=%d enabled=%d position=%d,%d transform=%d scale-milli=%d pending=%d/%d/%d request=%d/%d/%d/%d)\n", + stage, events.serial, (void *)events.head, (void *)events.mode, + events.manager_done_count, events.manager_finished_count, events.head_name_count, + events.head_description_count, events.head_enabled_count, + events.head_current_mode_count, events.head_position_count, + events.head_transform_count, events.head_scale_count, + events.head_adaptive_sync_count, events.mode_size_count, + events.mode_refresh_count, events.configuration_succeeded_count, + events.configuration_failed_count, events.configuration_cancelled_count, + state.output_count, state.enabled, state.x, state.y, + state.transform, state.scale_milli, state.pending_state, + state.pending_transform, state.pending_scale_milli, + state.request_count, state.last_request_test, + state.last_request_transform, state.last_request_scale_milli); + } + if (manager) + wl_proxy_destroy((struct wl_proxy *)manager); + client_disconnect(&connection); + return result; +} diff --git a/tests/protocols/wlr-output-management-unstable-v1/wlr-output-management-unstable-v1.h b/tests/protocols/wlr-output-management-unstable-v1/wlr-output-management-unstable-v1.h new file mode 100644 index 0000000000..618315e8f8 --- /dev/null +++ b/tests/protocols/wlr-output-management-unstable-v1/wlr-output-management-unstable-v1.h @@ -0,0 +1,20 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +struct output_management_server_state { + int output_count; + int x; + int y; + int enabled; + int transform; + int scale_milli; + int pending_state; + int pending_transform; + int pending_scale_milli; + int request_count; + int last_request_test; + int last_request_transform; + int last_request_scale_milli; +}; diff --git a/tests/protocols/wlr-output-power-management-unstable-v1/CMakeLists.txt b/tests/protocols/wlr-output-power-management-unstable-v1/CMakeLists.txt new file mode 100644 index 0000000000..5c534361b5 --- /dev/null +++ b/tests/protocols/wlr-output-power-management-unstable-v1/CMakeLists.txt @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +treeland_add_protocol_test( + NAME wlr_output_power_management_unstable_v1 + XML "${PROJECT_SOURCE_DIR}/3rdparty/wlroots/protocol/wlr-output-power-management-unstable-v1.xml" + SETUP "${CMAKE_CURRENT_SOURCE_DIR}/setup.cpp" + CLIENT "${CMAKE_CURRENT_SOURCE_DIR}/wlr-output-power-management-unstable-v1.c" +) diff --git a/tests/protocols/wlr-output-power-management-unstable-v1/README.md b/tests/protocols/wlr-output-power-management-unstable-v1/README.md new file mode 100644 index 0000000000..94bc15e193 --- /dev/null +++ b/tests/protocols/wlr-output-power-management-unstable-v1/README.md @@ -0,0 +1,54 @@ +# `wlr-output-power-management-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`3rdparty/wlroots/protocol/wlr-output-power-management-unstable-v1.xml` / + `zwlr_output_power_manager_v1` 与 `zwlr_output_power_v1` v1。 +- 测试源码:`tests/protocols/wlr-output-power-management-unstable-v1/`。 +- Fixture:完整 Treeland desktop integration fixture 与启动时已有的真实 headless output。 +- 覆盖等级:**P / E**;P 覆盖 native resource、排他约束、生命周期与 error,E 覆盖 OFF/ON + 经生产 `WaylandServer` 提交到真实 output enabled state。 + +## 必须观察到的结果 + +| XML 语义 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| 初始状态 | 为真实 `wl_output` 调用 `get_output_power` 并 roundtrip | 恰好一次 `mode(on)`,无 `failed` | P | +| 每 output 排他 control | 在第一个 control 有效时再次 `get_output_power` | 第二对象只收到一次 `failed`,没有 `mode` | P | +| manager/child 生命周期分离 | destroy manager 后继续使用第一个 power object | 子对象仍有效;不产生 protocol error | P | +| 关闭 output 的业务结果 | 第一个 object 在 manager destroy 后 `set_mode(off)` | 收到 `mode(off)`;fixture 从真实 production `WOutput` 读取 `enabled=false` | E | +| 恢复 output 的业务结果 | 对同一 object 调用 `set_mode(on)` | 收到 `mode(on)`;同一 production `WOutput` 读取 `enabled=true` | E | +| power object 生命周期 | destroy power object 与 `wl_output` | 正常释放,无 use-after-free 或 protocol error | P | +| 非法 mode | 独立连接中发送 `set_mode(2)` | display 因 `zwlr_output_power_v1.error.invalid_mode` 断开 | P | + +## 生产结果 + +wlroots 原生实现 `wlr_output_power_manager_v1`;waylib 当前没有 wrapper。`WaylandServer::init()` 直接创建 +native manager,并注册其 `set_mode` signal 到 `WaylandServer::onSetOutputPowerMode()`。manager 由 wlroots +在 `wl_display` 销毁时释放,`WaylandServer` 只保留 listener pointer,不手动销毁 native manager。 + +`WaylandServer::onSetOutputPowerMode()` 对 OFF/ON 创建真实 `wlr_output_state`,调用 +`wlr_output_commit_state()`,并以 `m_powerOffOutputs` 区分协议关闭与其他 output-management 关闭。 +wlroots 在 output enabled commit 后向 control 发送 `mode`;fixture 再从同一个 production `WOutput` +读取 `isEnabled()`,不以 client event 缓存代替业务结果。 + +### E 级覆盖流程 + +1. CI 使用 `WLR_BACKENDS=headless;WLR_RENDERER=pixman` 创建真实 headless `wlr_output`;无需物理 + 显示器、GPU 或系统 display manager; +2. client 获取唯一 output 的 power control,确认 wlroots 发送的初始 `mode(on)`; +3. client 销毁 manager 但保留该 control,发送 `set_mode(off)`;native manager signal 进入 + `WaylandServer::onSetOutputPowerMode()`,对真实 output commit disabled state; +4. client 同时断言 `mode(off)`,fixture 读取 production `WOutput::isEnabled()==false`; +5. 同一 control 发送 `set_mode(on)`,以 `mode(on)` 和 `WOutput::isEnabled()==true` 验证恢复。 + +步骤 4、5 的状态由 production output 提供,不调用 fixture setter,因此为 E 级。当前实现待首次 CI +执行记录结果,不把未运行结果写成已通过。 + +## 已知边界 / 下一项结果 + +- headless backend 能证明 enable state commit,但不能证明物理面板实际进入 DPMS/省电状态;该结论需 + DRM/KMS runner、可观测 connector power state 或外部功耗/屏幕 readback 证据。 +- 未构造 output 销毁导致现有 control 收到 `failed`;需要可控 hotplug/output remove fixture。 +- 没有生产 trusted-client/authorization hook;任何可连接 client 均可取得 control。测试只记录 native + wlroots 的排他约束,不将其误报为授权策略。 diff --git a/tests/protocols/wlr-output-power-management-unstable-v1/setup.cpp b/tests/protocols/wlr-output-power-management-unstable-v1/setup.cpp new file mode 100644 index 0000000000..e7f8cfc6b9 --- /dev/null +++ b/tests/protocols/wlr-output-power-management-unstable-v1/setup.cpp @@ -0,0 +1,23 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "core/rootsurfacecontainer.h" +#include "output/output.h" +#include "core/waylandserver.h" +#include "wlr-output-power-management-unstable-v1.h" + +#include + +void protocol_test_setup(WaylandServer *) +{ +} + +extern "C" void output_power_read_server_state(void *data) +{ + output_power_server_state state {}; + const auto outputs = WaylandServer::instance()->rootSurfaceContainer()->outputs(); + state.output_count = outputs.size(); + if (!outputs.isEmpty()) + state.enabled = outputs.constFirst()->output()->isEnabled(); + *static_cast(data) = state; +} diff --git a/tests/protocols/wlr-output-power-management-unstable-v1/wlr-output-power-management-unstable-v1.c b/tests/protocols/wlr-output-power-management-unstable-v1/wlr-output-power-management-unstable-v1.c new file mode 100644 index 0000000000..7a14bad8cf --- /dev/null +++ b/tests/protocols/wlr-output-power-management-unstable-v1/wlr-output-power-management-unstable-v1.c @@ -0,0 +1,161 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "client-connection.h" +#include "server-bridge-api.h" +#include "wlr-output-power-management-unstable-v1-client-protocol.h" +#include "wlr-output-power-management-unstable-v1.h" + +#include +#include + +extern void output_power_read_server_state(void *data); + +struct power_events { + int mode_count; + int failed_count; + uint32_t last_mode; +}; + +static void power_mode(void *data, struct zwlr_output_power_v1 *power, uint32_t mode) +{ + (void)power; + struct power_events *events = data; + events->mode_count++; + events->last_mode = mode; +} + +static void power_failed(void *data, struct zwlr_output_power_v1 *power) +{ + (void)power; + ((struct power_events *)data)->failed_count++; +} + +static const struct zwlr_output_power_v1_listener power_listener = { + .mode = power_mode, + .failed = power_failed, +}; + +static int read_server_state(struct output_power_server_state *state) +{ + memset(state, 0, sizeof(*state)); + return invoke_on_server_thread(output_power_read_server_state, state); +} + +static int invalid_mode_disconnects(const char *socket_name) +{ + struct client_connection connection; + struct zwlr_output_power_manager_v1 *manager = NULL; + struct zwlr_output_power_v1 *power = NULL; + struct wl_output *output = NULL; + struct power_events events = { 0 }; + int result = 1; + + if (!client_connect(&connection, socket_name)) + return 1; + output = client_bind(&connection, "wl_output", &wl_output_interface, 1); + manager = client_bind(&connection, "zwlr_output_power_manager_v1", + &zwlr_output_power_manager_v1_interface, 1); + if (!output || !manager) + goto done; + power = zwlr_output_power_manager_v1_get_output_power(manager, output); + if (!power) + goto done; + zwlr_output_power_v1_add_listener(power, &power_listener, &events); + if (wl_display_roundtrip(connection.display) < 0 || events.mode_count != 1 + || events.last_mode != ZWLR_OUTPUT_POWER_V1_MODE_ON) + goto done; + + zwlr_output_power_v1_set_mode(power, 2); + result = wl_display_roundtrip(connection.display) < 0 ? 0 : 1; + +done: + client_disconnect(&connection); + return result; +} + +int protocol_test_run(const char *socket_name) +{ + struct client_connection connection; + struct zwlr_output_power_manager_v1 *manager = NULL; + struct zwlr_output_power_v1 *power = NULL; + struct zwlr_output_power_v1 *second_power = NULL; + struct wl_output *output = NULL; + struct power_events events = { 0 }; + struct power_events second_events = { 0 }; + struct output_power_server_state state; + int result = 1; + int stage = 0; + + if (!client_connect(&connection, socket_name)) + return 1; + + output = client_bind(&connection, "wl_output", &wl_output_interface, 1); + manager = client_bind(&connection, "zwlr_output_power_manager_v1", + &zwlr_output_power_manager_v1_interface, 1); + if (!output || !manager) + goto done; + stage = 1; + + power = zwlr_output_power_manager_v1_get_output_power(manager, output); + if (!power) + goto done; + zwlr_output_power_v1_add_listener(power, &power_listener, &events); + if (wl_display_roundtrip(connection.display) < 0 || events.mode_count != 1 + || events.last_mode != ZWLR_OUTPUT_POWER_V1_MODE_ON || events.failed_count) + goto done; + + second_power = zwlr_output_power_manager_v1_get_output_power(manager, output); + if (!second_power) + goto done; + stage = 2; + zwlr_output_power_v1_add_listener(second_power, &power_listener, &second_events); + if (wl_display_roundtrip(connection.display) < 0 || second_events.failed_count != 1 + || second_events.mode_count) + goto done; + zwlr_output_power_v1_destroy(second_power); + second_power = NULL; + + zwlr_output_power_manager_v1_destroy(manager); + manager = NULL; + zwlr_output_power_v1_set_mode(power, ZWLR_OUTPUT_POWER_V1_MODE_OFF); + stage = 3; + if (wl_display_roundtrip(connection.display) < 0 || events.mode_count != 2 + || events.last_mode != ZWLR_OUTPUT_POWER_V1_MODE_OFF || events.failed_count + || !read_server_state(&state) || state.output_count != 1 || state.enabled) + goto done; + + zwlr_output_power_v1_set_mode(power, ZWLR_OUTPUT_POWER_V1_MODE_ON); + stage = 4; + if (wl_display_roundtrip(connection.display) < 0 || events.mode_count != 3 + || events.last_mode != ZWLR_OUTPUT_POWER_V1_MODE_ON || events.failed_count + || !read_server_state(&state) || state.output_count != 1 || !state.enabled) + goto done; + + zwlr_output_power_v1_destroy(power); + power = NULL; + wl_output_destroy(output); + output = NULL; + client_disconnect(&connection); + return invalid_mode_disconnects(socket_name); + +done: + if (result) { + read_server_state(&state); + fprintf(stderr, + "wlr-output-power failure at stage %d: events=(mode=%d last=%u failed=%d second-mode=%d second-failed=%d) server=(outputs=%d enabled=%d)\n", + stage, events.mode_count, events.last_mode, events.failed_count, + second_events.mode_count, second_events.failed_count, + state.output_count, state.enabled); + } + if (second_power) + zwlr_output_power_v1_destroy(second_power); + if (power) + zwlr_output_power_v1_destroy(power); + if (manager) + zwlr_output_power_manager_v1_destroy(manager); + if (output) + wl_output_destroy(output); + client_disconnect(&connection); + return result; +} diff --git a/tests/protocols/wlr-output-power-management-unstable-v1/wlr-output-power-management-unstable-v1.h b/tests/protocols/wlr-output-power-management-unstable-v1/wlr-output-power-management-unstable-v1.h new file mode 100644 index 0000000000..7dfc48b50c --- /dev/null +++ b/tests/protocols/wlr-output-power-management-unstable-v1/wlr-output-power-management-unstable-v1.h @@ -0,0 +1,9 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +struct output_power_server_state { + int output_count; + int enabled; +}; diff --git a/tests/protocols/wlr-virtual-pointer-unstable-v1/README.md b/tests/protocols/wlr-virtual-pointer-unstable-v1/README.md new file mode 100644 index 0000000000..3c1386e42a --- /dev/null +++ b/tests/protocols/wlr-virtual-pointer-unstable-v1/README.md @@ -0,0 +1,37 @@ +# `wlr-virtual-pointer-unstable-v1` 测试规范 + +## 范围 + +- XML / interface:`3rdparty/wlroots/protocol/wlr-virtual-pointer-unstable-v1.xml` / + `zwlr_virtual_pointer_manager_v1`、`zwlr_virtual_pointer_v1` v2。 +- 测试接入:该 protocol target 的 `setup.cpp` 创建 wlroots native manager;每个 + `new_virtual_pointer` 被包装为 virtual `WInputDevice` 并 attach 到生产 primary `WSeat`。这不改变 + Treeland 默认公开的 global。 +- 覆盖等级:待加入独立 protocol client 后为 **P / E**。 + +## 必须观察到的结果 + +| XML 语义 | 客户端动作 | 必须观察到的结果 | 证据层级 | +| --- | --- | --- | --- | +| pointer 创建与 seat 路由 | `create_virtual_pointer_with_output(seat,output)` | production virtual `WInputDevice` attach 到 default seat,suggested output 进入 pointer mapping | E | +| motion/button/axis/frame | 依次发送 relative/absolute motion、button、axis/source/stop/discrete、frame | focused client 的真实 `wl_pointer` 收到匹配 event 与 frame 边界 | E | +| 生命周期 | destroy manager 后继续使用 pointer,再 destroy pointer | child 不被 manager 连带销毁,native input device 随 pointer destroy detach | P / E | +| 无效 axis/source | 独立连接传入非法 enum | `invalid_axis` / `invalid_axis_source` protocol error | P | + +## 生产结果 + +wlroots 已实现 native manager,waylib 没有 wrapper。测试 fixture 的 listener 将 native pointer base +包装为 `WInputDevice(..., true)`,attach 到 primary seat,并在 native destroy signal 中 detach/delete +wrapper;这使 protocol event 进入既有 Treeland pointer/seat 分发,而不是停留在 wlroots signal 层。 + +### E 级覆盖流程 + +headless CI 创建 output 和 mapped pointer-focused client;另一 client 创建 virtual pointer 并注入事件。 +测试必须由第一个 client 的 `wl_pointer` listener 验证 production seat 转发,不得由 fixture 直接调用 +seat notify API。该流程不需要 GPU 或物理鼠标;授权策略、若引入,应另行以拒绝 client 验证。 + +## 已知边界 / 下一项结果 + +- 当前仅记录 fixture 接入方案;独立 C protocol client 与 fixture setup 尚待加入,不能把方案本身 + 记为已执行的 request/event 覆盖。 +- 目前 wlroots native manager 没有 trusted-client callback;所有连接 client 的创建被允许不等于授权测试。 diff --git a/tests/test_animation_switches/CMakeLists.txt b/tests/test_animation_switches/CMakeLists.txt new file mode 100644 index 0000000000..2c47385d45 --- /dev/null +++ b/tests/test_animation_switches/CMakeLists.txt @@ -0,0 +1,17 @@ +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +find_program(QML_TEST_RUNNER NAMES qmltestrunner HINTS /usr/lib/qt6/bin) +if(QML_TEST_RUNNER) + set(TEST_IMPORT_DIR "${CMAKE_CURRENT_BINARY_DIR}/imports/Treeland") + configure_file(imports/Treeland/qmldir "${TEST_IMPORT_DIR}/qmldir" COPYONLY) + configure_file(imports/Treeland/WaylandServer.qml "${TEST_IMPORT_DIR}/WaylandServer.qml" COPYONLY) + configure_file("${PROJECT_SOURCE_DIR}/src/core/qml/EdgeTilePreview.qml" + "${TEST_IMPORT_DIR}/EdgeTilePreview.qml" COPYONLY) + add_test(NAME test_animation_switches + COMMAND "${QML_TEST_RUNNER}" -input "${CMAKE_CURRENT_SOURCE_DIR}" + -import "${CMAKE_CURRENT_BINARY_DIR}/imports") + set_tests_properties(test_animation_switches PROPERTIES + ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_QPA_PLATFORMTHEME=generic;QT_QUICK_CONTROLS_STYLE=Basic;QT_QUICK_BACKEND=software" + TIMEOUT 30) +endif() diff --git a/tests/test_animation_switches/imports/Treeland/WaylandServer.qml b/tests/test_animation_switches/imports/Treeland/WaylandServer.qml new file mode 100644 index 0000000000..8a8eba6d7e --- /dev/null +++ b/tests/test_animation_switches/imports/Treeland/WaylandServer.qml @@ -0,0 +1,12 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +pragma Singleton +import QtQuick + +QtObject { + readonly property QtObject config: QtObject { + readonly property color activeColor: "blue" + } + property QtObject animationConfig +} diff --git a/tests/test_animation_switches/imports/Treeland/qmldir b/tests/test_animation_switches/imports/Treeland/qmldir new file mode 100644 index 0000000000..1efc7cb5a4 --- /dev/null +++ b/tests/test_animation_switches/imports/Treeland/qmldir @@ -0,0 +1,3 @@ +module Treeland +singleton WaylandServer 1.0 WaylandServer.qml +EdgeTilePreview 1.0 EdgeTilePreview.qml diff --git a/tests/test_animation_switches/tst_switches.qml b/tests/test_animation_switches/tst_switches.qml new file mode 100644 index 0000000000..9c310d09ba --- /dev/null +++ b/tests/test_animation_switches/tst_switches.qml @@ -0,0 +1,96 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtTest +import Treeland + +TestCase { + id: testCase + name: "AnimationSwitches" + when: windowShown + visible: true + width: 800 + height: 600 + Component { + id: animationConfigComponent + QtObject { + property bool edgeTilePreview: true + } + } + Component { + id: previewComponent + EdgeTilePreview {} + } + property var preview: null + + function init() { + failOnWarning(/.*/) + WaylandServer.animationConfig = createTemporaryObject(animationConfigComponent, testCase) + preview = previewComponent.createObject(testCase) + verify(preview !== null) + preview.sourceGeometry = Qt.rect(0, 0, 100, 100) + preview.targetGeometry = Qt.rect(300, 200, 400, 300) + } + + function cleanup() { + if (preview) { + preview.destroy() + preview = null + wait(0) + } + WaylandServer.animationConfig = null + } + + function disable() { + WaylandServer.animationConfig.edgeTilePreview = false + } + + function verifyDestination() { + compare(preview.x, 300) + compare(preview.y, 200) + compare(preview.width, 400) + compare(preview.height, 300) + } + + function test_disabledBeforeShow() { + disable() + wait(0) + preview.visible = true + verifyDestination() + } + + function test_enabledBeforeShow() { + preview.visible = true + verify(preview.x < 300) + tryCompare(preview, "x", 300, 1000) + verifyDestination() + } + + function test_configurationReplacement() { + preview.visible = true + tryCompare(preview, "x", 300, 1000) + WaylandServer.animationConfig = createTemporaryObject( + animationConfigComponent, testCase, {edgeTilePreview: false}) + tryCompare(preview, "animationAllowed", false) + preview.targetGeometry = Qt.rect(400, 300, 500, 400) + compare(preview.x, 400) + compare(preview.y, 300) + compare(preview.width, 500) + compare(preview.height, 400) + } + + function test_reenabledForNextShow() { + disable() + preview.visible = true + verifyDestination() + preview.visible = false + WaylandServer.animationConfig.edgeTilePreview = true + tryCompare(preview, "animationAllowed", true) + preview.visible = true + verify(preview.x < 300) + tryCompare(preview, "x", 300, 1000) + verifyDestination() + } + +} diff --git a/tests/test_effect_glass/CMakeLists.txt b/tests/test_effect_glass/CMakeLists.txt new file mode 100644 index 0000000000..5a26b9f142 --- /dev/null +++ b/tests/test_effect_glass/CMakeLists.txt @@ -0,0 +1,97 @@ +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +# Liquid Glass effect test — uses waylib's headless backend for a real +# OpenGL context (via Mesa llvmpipe) without a display server or xvfb-run. +# The TestGlass QML module bundles GlassEffect.qml + shaders; TestWindow.qml +# wraps the test scene in an OutputRenderWindow + OutputItem so it renders +# through waylib's scene graph. + +find_package(Qt6 REQUIRED COMPONENTS Test Core Qml Quick QuickControls2 ShaderTools) + +qt_standard_project_setup(REQUIRES 6.4) + +if(QT_KNOWN_POLICY_QTP0001) + qt_policy(SET QTP0001 NEW) +endif() +if(POLICY CMP0071) + cmake_policy(SET CMP0071 NEW) +endif() + +find_package(PkgConfig REQUIRED) +pkg_search_module(PIXMAN REQUIRED IMPORTED_TARGET pixman-1) +pkg_search_module(WAYLAND REQUIRED IMPORTED_TARGET wayland-server) + +set(GLASS_SHADER_DIR "${CMAKE_SOURCE_DIR}/misc/shaders") +set(GLASS_EFFECT_QML "${CMAKE_SOURCE_DIR}/src/core/qml/Effects/GlassEffect.qml") +set_source_files_properties(${GLASS_EFFECT_QML} + PROPERTIES + QT_RESOURCE_ALIAS "GlassEffect.qml" +) + +add_executable(test_effect_glass + main.cpp + TestHelper.cpp + "${PROJECT_SOURCE_DIR}/src/surface/framegeometry.cpp" + "${PROJECT_SOURCE_DIR}/src/surface/framegeometry.h" +) +target_include_directories(test_effect_glass PRIVATE + "${PROJECT_SOURCE_DIR}/src" + "${PROJECT_SOURCE_DIR}/src/surface" +) +set(FRAME_CLIP_QML "${PROJECT_SOURCE_DIR}/src/core/qml/FrameClip.qml") +set_source_files_properties(${FRAME_CLIP_QML} PROPERTIES QT_RESOURCE_ALIAS "FrameClip.qml") + +qt_add_qml_module(test_effect_glass + URI TestGlass + VERSION "1.0" + QML_FILES + ${GLASS_EFFECT_QML} + ${FRAME_CLIP_QML} + FrameClipScene.qml + GlassEffectScene.qml + TestWindow.qml + SOURCES + TestHelper.h +) + +qt_add_shaders(test_effect_glass "test_glass_shaders" + PRECOMPILE + OPTIMIZED + PREFIX + "/shaders" + BASE + ${GLASS_SHADER_DIR} + FILES + ${GLASS_SHADER_DIR}/liquidglass.vert + ${GLASS_SHADER_DIR}/liquidglass.frag +) + +target_compile_definitions(test_effect_glass + PRIVATE + SOURCE_DIR="${CMAKE_SOURCE_DIR}" + WLR_USE_UNSTABLE +) + +target_link_libraries(test_effect_glass + PRIVATE + Qt::Core + Qt::Qml + Qt::Quick + Qt::QuickControls2 + Qt::Test + Waylib::WaylibServer + PkgConfig::PIXMAN + PkgConfig::WAYLAND +) + +# waylib QML imports are generated in the build tree. +set_target_properties(test_effect_glass PROPERTIES + QT_QML_IMPORT_PATH "${PROJECT_BINARY_DIR}/waylib/src/server" +) + +add_test(NAME test_effect_glass COMMAND test_effect_glass) +set_tests_properties(test_effect_glass PROPERTIES + ENVIRONMENT "WLR_BACKENDS=headless;QT_QML_IMPORT_PATH=${PROJECT_BINARY_DIR}/waylib/src/server" + TIMEOUT 60 +) diff --git a/tests/test_effect_glass/FrameClipScene.qml b/tests/test_effect_glass/FrameClipScene.qml new file mode 100644 index 0000000000..21dddffa36 --- /dev/null +++ b/tests/test_effect_glass/FrameClipScene.qml @@ -0,0 +1,62 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +import QtQuick +import TestGlass + +Item { + id: root + width: 240 + height: 200 + property real contentScale: 1 + property alias clientSourceRect: clientClip.sourceRect + readonly property var geometry: ({ rect: Qt.rect(0, 0, width, height), radius: 80 }) + + Item { + width: root.width + height: 40 + Rectangle { + id: titleSource + anchors.fill: parent + color: "red" + layer.enabled: true + opacity: 0 + } + FrameClip { + source: titleSource + geometry: root.geometry + } + } + + Item { + y: 40 + width: root.width * root.contentScale + height: (root.height - 40) * root.contentScale + scale: 1 / root.contentScale + transformOrigin: Item.TopLeft + Rectangle { + id: clientSource + width: 400 * root.contentScale + height: 260 * root.contentScale + color: "blue" + layer.enabled: true + layer.smooth: true + opacity: 0 + Rectangle { + x: 40 * root.contentScale + y: 20 * root.contentScale + width: root.width * root.contentScale + height: (root.height - 40) * root.contentScale + color: "lime" + } + } + FrameClip { + id: clientClip + source: clientSource + geometry: root.geometry + geometryScale: root.contentScale + geometryOffset: Qt.point(0, -40 * root.contentScale) + sourceRect: Qt.rect(40 * root.contentScale, 20 * root.contentScale, + width, height) + } + } +} diff --git a/tests/test_effect_glass/GlassEffectScene.qml b/tests/test_effect_glass/GlassEffectScene.qml new file mode 100644 index 0000000000..0f31654d89 --- /dev/null +++ b/tests/test_effect_glass/GlassEffectScene.qml @@ -0,0 +1,113 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Effects +import TestGlass + +Item { + id: root + width: 256 + height: 256 + + /// Expose the GlassEffect instance for property manipulation from C++. + property alias glass: glassEffect + property alias backdropVisible: backdrop.visible + property alias glassXScale: glassScale.xScale + property alias glassYScale: glassScale.yScale + property bool cornerProbeVisible: false + + /// A colourful, high-contrast backdrop so refraction / highlights / rim + /// tint are clearly visible in grabbed images. + Rectangle { + id: backdrop + anchors.fill: parent + visible: true + layer.enabled: true + + gradient: Gradient { + orientation: Gradient.Horizontal + GradientStop { position: 0.0; color: "#c0392b" } + GradientStop { position: 0.33; color: "#27ae60" } + GradientStop { position: 0.66; color: "#2980b9" } + GradientStop { position: 1.0; color: "#8e44ad" } + } + + // Distinct shapes for refraction / displacement visibility + Rectangle { + anchors.centerIn: parent + width: 64; height: 64 + color: "#f1c40f" + radius: 8 + } + Rectangle { + x: 16; y: 16 + width: 32; height: 32 + color: "#ffffff" + radius: 4 + } + Rectangle { + anchors.right: parent.right; anchors.bottom: parent.bottom + anchors.rightMargin: 16; anchors.bottomMargin: 16 + width: 48; height: 48 + color: "#e67e22" + radius: 6 + } + // Vertical bars for chromatic aberration detection + Rectangle { + x: parent.width * 0.25 - 3; y: 0 + width: 6; height: parent.height + color: "#000000" + } + Rectangle { + x: parent.width * 0.75 - 3; y: 0 + width: 6; height: parent.height + color: "#000000" + } + // Right-edge contrast target: large bezel refraction/edge material + // should stay visible along straight edges even when the corner radius + // is much smaller than the bezel width. + Rectangle { + x: 214; y: 72 + width: 8; height: 112 + color: "#ffffff" + } + Rectangle { + x: 230; y: 72 + width: 8; height: 112 + color: "#000000" + } + Grid { + anchors.top: parent.top + anchors.right: parent.right + columns: 8 + visible: root.cornerProbeVisible + + Repeater { + model: 64 + + Rectangle { + required property int index + width: 8 + height: 8 + color: ((index % 8) + Math.floor(index / 8)) % 2 === 0 + ? "#ffffff" + : "#000000" + } + } + } + } + + GlassEffect { + id: glassEffect + objectName: "glassEffect" + anchors.fill: parent + source: backdrop + + transform: Scale { + id: glassScale + origin.x: glassEffect.width * 0.5 + origin.y: glassEffect.height * 0.5 + } + } +} diff --git a/tests/test_effect_glass/TestHelper.cpp b/tests/test_effect_glass/TestHelper.cpp new file mode 100644 index 0000000000..7e6cf4a867 --- /dev/null +++ b/tests/test_effect_glass/TestHelper.cpp @@ -0,0 +1,94 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "TestHelper.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +TestHelper::TestHelper(QObject *parent) + : QObject(parent) + , m_server(new WServer(this)) + , m_outputCreator(new WQmlCreator(this)) + , m_outputLayout(new WQuickOutputLayout(m_server)) + , m_cursor(new WCursor(this)) +{ + m_seat = m_server->attach(); + m_seat->setCursor(m_cursor); + m_cursor->setLayout(m_outputLayout); +} + +void TestHelper::initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine) +{ + m_backend = m_server->attach(); + m_server->start(); + + m_renderer = WRenderHelper::createRenderer(m_backend->handle()); + if (!m_renderer) + qFatal("Failed to create wlroots renderer"); + + connect(m_backend, &WBackend::outputAdded, this, [this, qmlEngine](WOutput *output) { + auto props = qmlEngine->newObject(); + props.setProperty("waylandOutput", qmlEngine->toScriptValue(output)); + props.setProperty("layout", qmlEngine->toScriptValue(m_outputLayout)); + props.setProperty("x", qmlEngine->toScriptValue(m_outputLayout->implicitWidth())); + m_outputCreator->add(output, props); + }); + + connect(m_backend, &WBackend::outputRemoved, this, [this](WOutput *output) { + m_outputCreator->removeByOwner(output); + }); + + connect(m_backend, &WBackend::inputAdded, this, [this](WInputDevice *device) { + m_seat->attachInputDevice(device); + }); + + connect(m_backend, &WBackend::inputRemoved, this, [this](WInputDevice *device) { + m_seat->detachInputDevice(device); + }); + + m_allocator = wlr_allocator_autocreate(m_backend->handle(), m_renderer); + wlr_renderer_init_wl_display(m_renderer, m_server->handle()); + + m_compositor = wlr_compositor_create(m_server->handle(), 6, m_renderer); + wlr_subcompositor_create(m_server->handle()); + + connect(window, &WOutputRenderWindow::outputViewportInitialized, this, [](WOutputViewport *viewport) { + auto *output = viewport->output(); + // Keep the "already enabled" marker on the WOutput object itself: + // it is released with the output, so a recycled wlr_output address + // is never mistaken for an already-enabled output. + if (!output->property("_Enabled").toBool()) { + output->setProperty("_Enabled", true); + auto *wlrOutput = output->handle(); + wlr_output_state newState; + wlr_output_state_init(&newState); + if (!wlrOutput->current_mode) { + auto mode = wlr_output_preferred_mode(wlrOutput); + if (mode) + wlr_output_state_set_mode(&newState, mode); + } + wlr_output_state_set_enabled(&newState, true); + if (!wlr_output_commit_state(wlrOutput, &newState)) + qCritical("commit failed on output %s", wlrOutput->name); + wlr_output_state_finish(&newState); + } + }); + + window->init(m_renderer, m_allocator); + wlr_backend_start(m_backend->handle()); +} + +bool TestHelper::usesSoftwareRenderer() const +{ + return m_renderer && wlr_renderer_is_pixman(m_renderer); +} diff --git a/tests/test_effect_glass/TestHelper.h b/tests/test_effect_glass/TestHelper.h new file mode 100644 index 0000000000..7594c499b5 --- /dev/null +++ b/tests/test_effect_glass/TestHelper.h @@ -0,0 +1,53 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include +#include +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WServer; +class WOutputRenderWindow; +class WQuickOutputLayout; +class WCursor; +class WSeat; +class WBackend; +WAYLIB_SERVER_END_NAMESPACE + +struct wlr_renderer; +struct wlr_allocator; +struct wlr_compositor; + +WAYLIB_SERVER_USE_NAMESPACE + +/// Sets up a minimal wayland server with a headless wlroots backend so the +/// test gets a real OpenGL context via Mesa llvmpipe — no display required. +class TestHelper : public QObject +{ + Q_OBJECT + Q_PROPERTY(WQmlCreator *outputCreator MEMBER m_outputCreator CONSTANT) + QML_ELEMENT + QML_SINGLETON + +public: + explicit TestHelper(QObject *parent = nullptr); + + void initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine); + bool usesSoftwareRenderer() const; + +private: + WServer *m_server = nullptr; + WQmlCreator *m_outputCreator = nullptr; + WBackend *m_backend = nullptr; + wlr_renderer *m_renderer = nullptr; + wlr_allocator *m_allocator = nullptr; + wlr_compositor *m_compositor = nullptr; + WQuickOutputLayout *m_outputLayout = nullptr; + WCursor *m_cursor = nullptr; + QPointer m_seat; +}; diff --git a/tests/test_effect_glass/TestWindow.qml b/tests/test_effect_glass/TestWindow.qml new file mode 100644 index 0000000000..7eb04858df --- /dev/null +++ b/tests/test_effect_glass/TestWindow.qml @@ -0,0 +1,43 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import Waylib.Server +import TestGlass + +Item { + id: root + + OutputRenderWindow { + id: renderWindow + objectName: "renderWindow" + width: 256 + height: 256 + + DynamicCreatorComponent { + creator: TestHelper.outputCreator + + OutputItem { + id: outputItem + required property WaylandOutput waylandOutput + output: waylandOutput + devicePixelRatio: waylandOutput.scale + + OutputViewport { + id: outputViewport + output: waylandOutput + devicePixelRatio: parent.devicePixelRatio + anchors.centerIn: parent + width: 256 + height: 256 + } + + GlassEffectScene { + id: scene + objectName: "glassScene" + anchors.centerIn: parent + } + } + } + } +} diff --git a/tests/test_effect_glass/main.cpp b/tests/test_effect_glass/main.cpp new file mode 100644 index 0000000000..3304f428f7 --- /dev/null +++ b/tests/test_effect_glass/main.cpp @@ -0,0 +1,1104 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "surface/framegeometry.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "TestHelper.h" + +WAYLIB_SERVER_USE_NAMESPACE + +// Model only the geometry properties; execute the production splash bindings below. +class SplashSurfaceFixture : public QObject +{ + Q_OBJECT + Q_PROPERTY(FrameGeometry frameGeometry MEMBER m_frameGeometry NOTIFY frameGeometryChanged) + Q_PROPERTY(FrameGeometry presentationFrameGeometry MEMBER m_presentationFrameGeometry NOTIFY presentationFrameGeometryChanged) +public: + using QObject::QObject; +Q_SIGNALS: + void frameGeometryChanged(); + void presentationFrameGeometryChanged(); +private: + FrameGeometry m_frameGeometry; + FrameGeometry m_presentationFrameGeometry; +}; + +/// Liquid Glass effect test using waylib's headless backend for OpenGL. +/// +/// A custom main() sets up the waylib QPA platform with WLR_BACKENDS=headless +/// before QGuiApplication, giving us a real OpenGL context via Mesa llvmpipe +/// — no display server or xvfb-run needed. The TestGlass QML module bundles +/// GlassEffect.qml + shaders, and TestWindow.qml wraps the test scene in an +/// OutputRenderWindow + OutputItem so it renders through waylib's scene graph. +/// +/// Property tests read derived values at runtime; rendering tests use +/// grabToImage to capture and compare images. +class GlassEffectTest : public QObject +{ + Q_OBJECT + +public: + static void setGlobals(WOutputRenderWindow *w, QQuickItem *s, QQuickItem *g, TestHelper *h) + { + m_window = w; + m_scene = s; + m_glass = g; + m_helper = h; + } + +private: + static inline WOutputRenderWindow *m_window = nullptr; + static inline QQuickItem *m_scene = nullptr; + static inline QQuickItem *m_glass = nullptr; + static inline TestHelper *m_helper = nullptr; + + /// Grab an item to a QImage (asynchronous — waits for ready). + static QImage grabImage(QQuickItem *item, const QSize &size = QSize(256, 256)) + { + auto result = item->grabToImage(size); + if (!result) + return {}; + + QSignalSpy spy(result.data(), &QQuickItemGrabResult::ready); + spy.wait(5000); + return result->image(); + } + + /// Count pixels that differ between two images of the same size. + static int pixelDiffCount(const QImage &a, const QImage &b) + { + if (a.size() != b.size() || a.format() != b.format()) + return -1; + + int count = 0; + const int w = a.width(); + const int h = a.height(); + for (int y = 0; y < h; ++y) { + const auto *pa = reinterpret_cast(a.scanLine(y)); + const auto *pb = reinterpret_cast(b.scanLine(y)); + for (int x = 0; x < w; ++x) { + if (pa[x] != pb[x]) + ++count; + } + } + return count; + } + + static int colorDistance(QRgb a, QRgb b) + { + return std::abs(qRed(a) - qRed(b)) + + std::abs(qGreen(a) - qGreen(b)) + + std::abs(qBlue(a) - qBlue(b)) + + std::abs(qAlpha(a) - qAlpha(b)); + } + + static int regionDiffCount(const QImage &a, const QImage &b, const QRect ®ion, int minDistance = 0) + { + if (a.size() != b.size() || a.format() != b.format()) + return -1; + + int count = 0; + const QRect bounded = region.intersected(a.rect()); + for (int y = bounded.top(); y <= bounded.bottom(); ++y) { + const auto *pa = reinterpret_cast(a.scanLine(y)); + const auto *pb = reinterpret_cast(b.scanLine(y)); + for (int x = bounded.left(); x <= bounded.right(); ++x) { + if (colorDistance(pa[x], pb[x]) > minDistance) + ++count; + } + } + return count; + } + + static int maxDiagonalCornerDiscontinuity(const QImage &img) + { + const int w = img.width(); + int maxStep = 0; + + // Top-right has only the smooth horizontal gradient behind it in this + // fixture, so any large cross-diagonal jump is from the shader rather + // than a backdrop feature. The paired samples straddle the possible + // 45° seam where top-edge and right-edge corner math meet. + for (int d = 12; d <= 46; ++d) { + const QRgb a = img.pixel(w - 1 - d, d + 1); + const QRgb b = img.pixel(w - 2 - d, d); + maxStep = std::max(maxStep, colorDistance(a, b)); + } + + return maxStep; + } + + void setSmallRadiusLargeBezel() + { + m_glass->setProperty("blurEnabled", false); + m_glass->setProperty("radius", 8.0); + m_glass->setProperty("bezelWidth", 52.0); + m_glass->setProperty("thickness", 120.0); + m_glass->setProperty("profilePower", 4.0); + m_glass->setProperty("ior", 1.45); + // Extreme corner stress fixture: keep slope cap fixed so product + // refractionMaxTan defaults do not retune this geometry check. + m_glass->setProperty("refractionMaxTan", 2.0); + QTest::qWait(50); + } + + static bool requiresShaderRendering(const char *testFunction) + { + static constexpr const char *renderingTests[] = { + "frameClipMatchesInput", + "glassUsesFrameCoordinates", + "specularProducesDifferentRender", + "tintControlProducesDifferentRender", + "specularControlChangesRim", + "narrowBezelPreservesInnerRim", + "radiusProducesTransparentCorners", + "nonUniformScaleKeepsEdgeAntialiasingSymmetric", + "largeBezelWithSmallRadiusDoesNotIntroduceCornerDiagonalSeam", + "largeBezelWithSmallRadiusKeepsStraightEdgeRefraction", + "contentEdgePullChangesSilhouetteRefraction", + "refractionMaxTanAboveOneChangesEdgeRefraction", + "radiusLargerThanBezelDoesNotIntroduceCornerDiagonalSeam", + "tintControlChangesRenderedColor", + "zeroBlurMultiplierStillAppliesGaussianBlur", + "blurAmountAndMultiplierChangeRenderedBlurStrength", + "blurToggleProducesDifferentRender", + "benchmarkGlassShader", + }; + + for (const auto *name : renderingTests) { + if (qstrcmp(testFunction, name) == 0) + return true; + } + return false; + } + + static bool shaderRenderingAvailable() + { + return m_helper && !m_helper->usesSoftwareRenderer(); + } + /// Reset glass to default property values (called before each test). + void resetGlass() + { + m_glass->setProperty("blurEnabled", false); + m_glass->setProperty("blurMax", 12); + m_glass->setProperty("blurAmount", 0.6); + m_glass->setProperty("blurMultiplier", 0.0); + m_glass->setProperty("radius", 60.0); + m_glass->setProperty("frameRect", QRectF(0, 0, 256, 256)); + m_glass->setProperty("bezelWidth", 60.0); + m_glass->setProperty("thickness", 50.0); + m_glass->setProperty("ior", 1.5); + m_glass->setProperty("brightness", 0.0); + m_glass->setProperty("contrast", 0.0); + m_glass->setProperty("saturation", 0.04); + m_glass->setProperty("specular", 0.0); + m_glass->setProperty("tint", 0.0); + m_scene->setProperty("backdropVisible", true); + m_scene->setProperty("glassXScale", 1.0); + m_scene->setProperty("glassYScale", 1.0); + m_scene->setProperty("cornerProbeVisible", false); + QTest::qWait(50); + } + +private Q_SLOTS: + + void initTestCase() + { + QVERIFY(m_window); + QVERIFY(m_scene); + QVERIFY(m_glass); + } + + void init() + { + if (requiresShaderRendering(QTest::currentTestFunction()) && !shaderRenderingAvailable()) { + QSKIP("Shader rendering checks require OpenGL; the software renderer " + "does not run ShaderEffect/MultiEffect output"); + } + } + + void cleanup() + { + resetGlass(); + } + + void liquidGlassDefaultsMatch() + { + QCOMPARE(m_glass->property("radius").toReal(), 12.0); + QCOMPARE(m_glass->property("thickness").toReal(), 30.0); + QCOMPARE(m_glass->property("bezelWidth").toReal(), 30.0); + QCOMPARE(m_glass->property("ior").toReal(), 1.33); + QCOMPARE(m_glass->property("specular").toReal(), 0.0); + QCOMPARE(m_glass->property("tint").toReal(), 0.0); + QCOMPARE(m_glass->property("saturation").toReal(), 0.0); + QCOMPARE(m_glass->property("blurAmount").toReal(), 0.6); + QCOMPARE(m_glass->property("refractionMaxTan").toReal(), 3.3); + + } + + void frameClipMatchesInput_data() + { + QTest::addColumn("ratio"); + QTest::addColumn("sourceRect"); + QTest::newRow("1x") << qreal(1) << QRectF(40, 20, 240, 160); + QTest::newRow("fractional") << qreal(1.25) << QRectF(50, 25, 300, 200); + QTest::newRow("2x") << qreal(2) << QRectF(80, 40, 480, 320); + // Crop up to the green texel centers; widening either axis samples the blue surround. + QTest::newRow("subpixel-width") << qreal(1) << QRectF(279, 40, 0.5, 100); + QTest::newRow("subpixel-height") << qreal(1) << QRectF(80, 179, 100, 0.5); + QTest::newRow("subpixel-both") << qreal(1) << QRectF(279, 179, 0.5, 0.5); + } + + void frameClipMatchesInput() + { + QFETCH(qreal, ratio); + QFETCH(QRectF, sourceRect); + QQmlComponent component(qmlEngine(m_scene), "TestGlass", "FrameClipScene"); + QVERIFY2(component.isReady(), qPrintable(component.errorString())); + std::unique_ptr scene(qobject_cast( + component.createWithInitialProperties({{"contentScale", ratio}, + {"clientSourceRect", sourceRect}}))); + QVERIFY(scene); + QCOMPARE(scene->property("clientSourceRect").toRectF(), sourceRect); + scene->setParentItem(m_scene); + QTest::qWait(50); + const auto image = grabImage(scene.get(), QSize(240, 200)); + QVERIFY(!image.isNull()); + const FrameGeometry geometry(QRectF(0, 0, 240, 200), 80); + for (int y = 4; y < 196; y += 8) { + for (int x = 4; x < 236; x += 8) { + const QPointF point(x + 0.5, y + 0.5); + const bool inside = geometry.contains(point); + // Compare away from the renderer's antialiasing fringe. + if (geometry.contains(point + QPointF(2, 0)) != inside + || geometry.contains(point - QPointF(2, 0)) != inside + || geometry.contains(point + QPointF(0, 2)) != inside + || geometry.contains(point - QPointF(0, 2)) != inside) + continue; + const QColor color = image.pixelColor(x, y); + const auto location = QString("pixel (%1, %2), alpha %3") + .arg(x).arg(y).arg(color.alpha()); + QVERIFY2(inside ? color.alpha() > 240 : color.alpha() < 15, qPrintable(location)); + if (inside) { + QVERIFY(y < 40 ? color.red() > 240 : color.green() > 240); + QVERIFY(color.blue() < 15); + } + } + } + } + + void prelaunchKeepsPresentationGeometry() + { + qmlRegisterType("SplashFixture", 2, 0, "SurfaceWrapper"); + QQmlEngine engine; + SplashSurfaceFixture surface; + const FrameGeometry splashGeometry(QRectF(0, 0, 256, 256), 12); + surface.setProperty("frameGeometry", QVariant::fromValue(splashGeometry)); + surface.setProperty("presentationFrameGeometry", QVariant::fromValue(splashGeometry)); + const auto path = QStringLiteral(SOURCE_DIR "/src/core/qml/PrelaunchSplash.qml"); + QFile source(path); + QVERIFY(source.open(QIODevice::ReadOnly)); + auto code = source.readAll(); + code.replace("import Treeland", "import SplashFixture 2.0"); + QQmlComponent component(&engine); + component.setData(code, QUrl::fromLocalFile(path)); + QVERIFY2(component.isReady(), qPrintable(component.errorString())); + std::unique_ptr splash(qobject_cast(component.createWithInitialProperties({ + {"surface", QVariant::fromValue(&surface)}, + {"iconBuffer", QVariant::fromValue(static_cast(nullptr))}, + {"backgroundColor", QColor(Qt::white)}, + }))); + QVERIFY2(splash, qPrintable(component.errorString())); + splash->setParentItem(m_scene); + QVERIFY(!splash->childItems().isEmpty()); + auto *background = splash->childItems().first(); + QCOMPARE(background->property("radius").toReal(), qreal(12)); + for (const auto &incoming : {FrameGeometry(), FrameGeometry(QRectF(0, 0, 256, 256), 64), + FrameGeometry(QRectF(0, 0, 256, 256), 0)}) { + surface.setProperty("frameGeometry", QVariant::fromValue(incoming)); + QCoreApplication::processEvents(); + QVERIFY(splash->isVisible()); + QCOMPARE(background->property("radius").toReal(), qreal(12)); + const auto image = grabImage(splash.get()); + QVERIFY(!image.isNull()); + QVERIFY(image.pixelColor(1, 1).alpha() < 15); + QVERIFY(image.pixelColor(8, 8).alpha() > 240); + } + splash->setVisible(false); + surface.setProperty("presentationFrameGeometry", + QVariant::fromValue(FrameGeometry(QRectF(0, 0, 256, 256), 0))); + QCOMPARE(background->property("radius").toReal(), qreal(0)); + QVERIFY(!splash->isVisible()); + } + + void glassUsesFrameCoordinates() + { + m_scene->setProperty("backdropVisible", false); + m_glass->setProperty("radius", 80.0); + m_glass->setProperty("frameRect", QRectF(0, -40, 256, 296)); + QTest::qWait(50); + const auto image = grabImage(m_glass); + QVERIFY(!image.isNull()); + QVERIFY(image.pixelColor(2, 2).alpha() < 15); + QVERIFY(image.pixelColor(20, 2).alpha() > 240); + m_glass->setProperty("frameRect", QRectF(0, 0, 256, 256)); + } + + // ── Property tests: read derived properties at runtime ───────────── + + void dconfigDefaultsMatch() + { + QFile descriptor(QStringLiteral(SOURCE_DIR + "/misc/dconfig/org.deepin.dde.treeland.user.json")); + QVERIFY2(descriptor.open(QIODevice::ReadOnly), qPrintable(descriptor.errorString())); + + const QJsonObject contents = + QJsonDocument::fromJson(descriptor.readAll()).object().value("contents").toObject(); + QCOMPARE(contents.value("glassBezel").toObject().value("value").toDouble(), 30.0); + QCOMPARE(contents.value("glassThickness").toObject().value("value").toDouble(), 30.0); + QCOMPARE(contents.value("glassProfilePower").toObject().value("value").toDouble(), 2.0); + QCOMPARE(contents.value("glassSaturation").toObject().value("value").toDouble(), 0.0); + QCOMPARE(contents.value("glassSpecular").toObject().value("value").toDouble(), 0.0); + QCOMPARE(contents.value("blurStrength").toObject().value("value").toInt(), 60); + QCOMPARE(contents.value("blurAmount").toObject().value("value").toDouble(), 0.6); + QCOMPARE(contents.value("blurMultiplier").toObject().value("value").toDouble(), 0.0); + } + void frameRectUniformBounds_data() + { + QTest::addColumn("frameRect"); + QTest::addColumn("expected"); + QTest::newRow("offset") << QRectF(10, -40, 256, 296) << QVector4D(10, -40, 256, 296); + QTest::newRow("zero") << QRectF(10, -40, 0, 0) << QVector4D(10, -40, 1, 1); + QTest::newRow("negative") << QRectF(10, -40, -2, -3) << QVector4D(10, -40, 1, 1); + QTest::newRow("subpixel-width") << QRectF(10, -40, 0.5, 2) << QVector4D(10, -40, 1, 2); + QTest::newRow("subpixel-height") << QRectF(10, -40, 2, 0.5) << QVector4D(10, -40, 2, 1); + } + + void frameRectUniformBounds() + { + QFETCH(QRectF, frameRect); + QFETCH(QVector4D, expected); + auto *shader = m_glass->findChild("glassShader"); + QVERIFY(shader); + QVERIFY(m_glass->setProperty("frameRect", frameRect)); + QCOMPARE(m_glass->property("frameRect").toRectF(), frameRect); + QCOMPARE(shader->property("frameRect").value(), expected); + } + + void innerShadowDefaultIsDisabled() + { + QCOMPARE(m_glass->property("innerShadow").toReal(), 0.0); + } + + void specularAndTintAreOnlyMaterialControls() + { + auto *shader = m_glass->findChild("glassShader"); + QVERIFY(shader); + + QVERIFY2(m_glass->metaObject()->indexOfProperty("highlightEnabled") < 0, + "GlassEffect must use specular=0 instead of a duplicate highlight switch"); + QVERIFY2(m_glass->metaObject()->indexOfProperty("colorization") < 0, + "GlassEffect must use tint instead of duplicate white colorization"); + QVERIFY2(m_glass->metaObject()->indexOfProperty("colorizationColor") < 0, + "GlassEffect must not expose colorization state after removing colorization"); + + QVERIFY(m_glass->setProperty("specular", 0.55)); + QTest::qWait(10); + QCOMPARE(shader->property("specular").toReal(), 0.55); + + QVERIFY(m_glass->setProperty("specular", 0.0)); + QTest::qWait(10); + QCOMPARE(shader->property("specular").toReal(), 0.0); + } + + void multiEffectEnabledReflectsBlurAndColorParams() + { + // Default scene: blurEnabled=false, all color params=0 → false + m_glass->setProperty("blurEnabled", false); + m_glass->setProperty("brightness", 0.0); + m_glass->setProperty("contrast", 0.0); + m_glass->setProperty("saturation", 0.0); + QTest::qWait(10); + QVERIFY(!m_glass->property("multiEffectEnabled").toBool()); + + // blurEnabled → true + m_glass->setProperty("blurEnabled", true); + QTest::qWait(10); + QVERIFY(m_glass->property("multiEffectEnabled").toBool()); + + // Non-zero brightness alone → true + m_glass->setProperty("blurEnabled", false); + m_glass->setProperty("brightness", 0.05); + QTest::qWait(10); + QVERIFY(m_glass->property("multiEffectEnabled").toBool()); + + // Non-zero contrast alone → true + m_glass->setProperty("brightness", 0.0); + m_glass->setProperty("contrast", -0.12); + QTest::qWait(10); + QVERIFY(m_glass->property("multiEffectEnabled").toBool()); + + // Non-zero saturation alone → true + m_glass->setProperty("contrast", 0.0); + m_glass->setProperty("saturation", -0.15); + QTest::qWait(10); + QVERIFY(m_glass->property("multiEffectEnabled").toBool()); + + } + + void dconfigFacingGlassKnobsAreRuntimeQmlProperties() + { + auto *shader = m_glass->findChild("glassShader"); + QVERIFY(shader); + + const QList propertyNames = { + "blurAmount", + "blurMultiplier", + "blurMax", + "bezelWidth", + "thickness", + "ior", + "brightness", + "contrast", + "saturation", + }; + + for (const QByteArray &name : propertyNames) { + QVERIFY2(m_glass->metaObject()->indexOfProperty(name.constData()) >= 0, + qPrintable(QStringLiteral("GlassEffect must expose %1 as a real QML property") + .arg(QString::fromLatin1(name)))); + } + + QVERIFY(m_glass->setProperty("bezelWidth", 47.0)); + QVERIFY(m_glass->setProperty("thickness", 133.0)); + QVERIFY(m_glass->setProperty("ior", 1.37)); + QVERIFY(m_glass->setProperty("blurEnabled", true)); + QVERIFY(m_glass->setProperty("blurMax", 18)); + QVERIFY(m_glass->setProperty("blurAmount", 0.75)); + QVERIFY(m_glass->setProperty("blurMultiplier", 1.5)); + QTest::qWait(10); + + QCOMPARE(shader->property("bezelWidth").toReal(), 47.0); + QCOMPARE(shader->property("thickness").toReal(), 133.0); + QCOMPARE(shader->property("ior").toReal(), 1.37); + QCOMPARE(m_glass->property("multiEffectEnabled").toBool(), true); + } + + void materialKnobsAreRuntimeQmlProperties() + { + auto *shader = m_glass->findChild("glassShader"); + QVERIFY(shader); + + const QList propertyNames = { + "specular", + "tint", + }; + for (const QByteArray &name : propertyNames) { + QVERIFY2(m_glass->metaObject()->indexOfProperty(name.constData()) >= 0, + qPrintable(QStringLiteral("GlassEffect must expose material knob %1") + .arg(QString::fromLatin1(name)))); + } + + QVERIFY(m_glass->setProperty("specular", 0.35)); + QVERIFY(m_glass->setProperty("tint", 0.22)); + QTest::qWait(10); + + QCOMPARE(shader->property("specular").toReal(), 0.35); + QCOMPARE(shader->property("tint").toReal(), 0.22); + QVERIFY2(m_glass->metaObject()->indexOfProperty("blurRadius") < 0, + "GlassEffect must use MultiEffect blur controls instead of exposing shader blurRadius"); + QVERIFY2(m_glass->metaObject()->indexOfProperty("shadow") < 0, + "GlassEffect must not expose a dedicated shadow control"); + } + + void multiEffectBlurControlsRemainRuntimeQmlProperties() + { + QVERIFY2(m_glass->metaObject()->indexOfProperty("blurEnabled") >= 0, + "GlassEffect must preserve blurEnabled for MultiEffect blur"); + QVERIFY2(m_glass->metaObject()->indexOfProperty("blurMax") >= 0, + "GlassEffect must preserve blurMax for MultiEffect blur"); + QVERIFY2(m_glass->metaObject()->indexOfProperty("blurAmount") >= 0, + "GlassEffect must preserve blurAmount for MultiEffect blur"); + QVERIFY2(m_glass->metaObject()->indexOfProperty("blurMultiplier") >= 0, + "GlassEffect must preserve blurMultiplier for MultiEffect blur"); + + QVERIFY(m_glass->setProperty("blurEnabled", false)); + QVERIFY(m_glass->setProperty("blurAmount", 1.0)); + QVERIFY(m_glass->setProperty("blurMax", 48)); + QVERIFY(m_glass->setProperty("blurMultiplier", 2.0)); + QVERIFY(m_glass->setProperty("saturation", 0.0)); + QTest::qWait(10); + QVERIFY(!m_glass->property("multiEffectEnabled").toBool()); + + QVERIFY(m_glass->setProperty("blurEnabled", true)); + QTest::qWait(10); + QVERIFY(m_glass->property("multiEffectEnabled").toBool()); + } + + void shaderKeepsGlassBoundsWithoutDedicatedShadow() + { + auto *shader = qobject_cast(m_glass->findChild("glassShader")); + QVERIFY(shader); + + QTest::qWait(10); + + QCOMPARE(shader->x(), 0.0); + QCOMPARE(shader->y(), 0.0); + QCOMPARE(shader->width(), m_glass->width()); + QCOMPARE(shader->height(), m_glass->height()); + } + + void shaderReceivesEdgeMaterialPropertiesUsedByFragmentShader() + { + auto *shader = m_glass->findChild("glassShader"); + QVERIFY(shader); + + QTest::qWait(10); + + } + + // ── Rendering tests: grabToImage + image comparison ─────────────── + + void grabIsDeterministic() + { + const QImage img1 = grabImage(m_scene); + QVERIFY(!img1.isNull()); + + const QImage img2 = grabImage(m_scene); + QVERIFY(!img2.isNull()); + + // Same scene, same settings → identical output + QCOMPARE(img1, img2); + } + + void specularProducesDifferentRender() + { + // Set prominent glass params for visible highlights. + m_glass->setProperty("radius", 34.0); + m_glass->setProperty("bezelWidth", 16.0); + m_glass->setProperty("specular", 0.82); + QTest::qWait(50); + + const QImage withHighlight = grabImage(m_scene); + QVERIFY(!withHighlight.isNull()); + + m_glass->setProperty("specular", 0.0); + QTest::qWait(50); + + const QImage withoutHighlight = grabImage(m_scene); + QVERIFY(!withoutHighlight.isNull()); + + // Images must differ — highlights are visible + QVERIFY(withHighlight != withoutHighlight); + + // The difference should be concentrated near edges (rim), not center + const int w = withHighlight.width(); + const int h = withHighlight.height(); + int edgeDiff = 0, centerDiff = 0; + const int edgeBand = 24; // px from border + const int cx = w / 2, cy = h / 2; + const int centerRadius = 32; + + for (int y = 0; y < h; ++y) { + const auto *p1 = reinterpret_cast(withHighlight.scanLine(y)); + const auto *p2 = reinterpret_cast(withoutHighlight.scanLine(y)); + for (int x = 0; x < w; ++x) { + if (p1[x] != p2[x]) { + if (x < edgeBand || x >= w - edgeBand || y < edgeBand || y >= h - edgeBand) + ++edgeDiff; + else if (std::hypot(x - cx, y - cy) < centerRadius) + ++centerDiff; + } + } + } + // Highlights are an edge/rim phenomenon + QVERIFY2(edgeDiff > centerDiff, + qPrintable(QStringLiteral("highlight diff should be edge-dominated: edge=%1 center=%2") + .arg(edgeDiff).arg(centerDiff))); + } + + void tintControlProducesDifferentRender() + { + m_glass->setProperty("radius", 60.0); + m_glass->setProperty("blurEnabled", false); + m_glass->setProperty("specular", 0.0); + m_glass->setProperty("tint", 0.0); + QTest::qWait(50); + + const QImage noTint = grabImage(m_scene); + QVERIFY(!noTint.isNull()); + + m_glass->setProperty("tint", 0.4); + QTest::qWait(50); + + const QImage strongTint = grabImage(m_scene); + QVERIFY(!strongTint.isNull()); + + const int diff = regionDiffCount(noTint, strongTint, QRect(64, 64, 128, 128), 4); + QVERIFY2(diff > 128 * 128 / 3, + qPrintable(QStringLiteral("tint control must visibly change the glass interior, got %1 changed pixels").arg(diff))); + } + + void specularControlChangesRim() + { + m_glass->setProperty("radius", 60.0); + m_glass->setProperty("blurEnabled", false); + m_glass->setProperty("specular", 0.0); + QTest::qWait(50); + + const QImage withoutSpecular = grabImage(m_scene); + QVERIFY(!withoutSpecular.isNull()); + + m_glass->setProperty("specular", 1.0); + QTest::qWait(50); + + const QImage withSpecular = grabImage(m_scene); + QVERIFY(!withSpecular.isNull()); + + const int edgeDiff = regionDiffCount(withoutSpecular, withSpecular, QRect(0, 0, withSpecular.width(), 32), 4) + + regionDiffCount(withoutSpecular, withSpecular, QRect(0, withSpecular.height() - 32, withSpecular.width(), 32), 4) + + regionDiffCount(withoutSpecular, withSpecular, QRect(0, 0, 32, withSpecular.height()), 4) + + regionDiffCount(withoutSpecular, withSpecular, QRect(withSpecular.width() - 32, 0, 32, withSpecular.height()), 4); + QVERIFY2(edgeDiff > 500, + qPrintable(QStringLiteral("specular control must visibly change rim highlights, edgeDiff=%1").arg(edgeDiff))); + } + + void narrowBezelPreservesInnerRim() + { + m_glass->setProperty("radius", 60.0); + m_glass->setProperty("bezelWidth", 3.0); + m_glass->setProperty("blurEnabled", false); + m_glass->setProperty("specular", 0.0); + QTest::qWait(50); + + const QImage withoutSpecular = grabImage(m_scene); + QVERIFY(!withoutSpecular.isNull()); + + m_glass->setProperty("specular", 1.0); + QTest::qWait(50); + + const QImage withSpecular = grabImage(m_scene); + QVERIFY(!withSpecular.isNull()); + + const QRect innerTopRim(64, 4, 128, 1); + const int changed = regionDiffCount(withoutSpecular, withSpecular, innerTopRim, 2); + QVERIFY2(changed > innerTopRim.width() / 2, + qPrintable(QStringLiteral("narrow bezel must preserve the fixed-width inner rim: changed=%1 width=%2") + .arg(changed) + .arg(innerTopRim.width()))); + } + + void radiusProducesTransparentCorners() + { + // Large radius for clearly transparent corners + m_glass->setProperty("radius", 60.0); + QTest::qWait(50); + + // Grab the glass item directly (not root) so the visible backdrop + // doesn't fill the transparent corners. + const QImage img = grabImage(m_glass); + QVERIFY(!img.isNull()); + + // Corner pixels should be fully transparent (alpha = 0) + const int w = img.width(); + const int h = img.height(); + const int offset = 2; // a few pixels in from the absolute corner + + const QList cornerPixels = { + {offset, offset}, // top-left + {w - 1 - offset, offset}, // top-right + {offset, h - 1 - offset}, // bottom-left + {w - 1 - offset, h - 1 - offset}, // bottom-right + }; + + for (const auto &pt : cornerPixels) { + const QRgb px = img.pixel(pt.x(), pt.y()); + QVERIFY2(qAlpha(px) == 0, + qPrintable(QStringLiteral("corner pixel (%1,%2) should be transparent, got alpha=%3") + .arg(pt.x()).arg(pt.y()).arg(qAlpha(px)))); + } + + // Center pixel should be opaque + const QRgb centerPx = img.pixel(w / 2, h / 2); + QVERIFY2(qAlpha(centerPx) == 255, + qPrintable(QStringLiteral("center pixel should be opaque, got alpha=%1") + .arg(qAlpha(centerPx)))); + } + + void nonUniformScaleKeepsEdgeAntialiasingSymmetric() + { + m_scene->setProperty("backdropVisible", false); + m_scene->setProperty("glassXScale", 0.75); + m_scene->setProperty("glassYScale", 0.25); + m_glass->setProperty("radius", 0.0); + QTest::qWait(50); + + const QImage img = grabImage(m_scene); + QVERIFY(!img.isNull()); + + int horizontalPartialAlpha = 0; + int verticalPartialAlpha = 0; + for (int coordinate = 0; coordinate < img.width(); ++coordinate) { + const int horizontalAlpha = qAlpha(img.pixel(coordinate, img.height() / 2)); + const int verticalAlpha = qAlpha(img.pixel(img.width() / 2, coordinate)); + horizontalPartialAlpha += horizontalAlpha > 0 && horizontalAlpha < 255; + verticalPartialAlpha += verticalAlpha > 0 && verticalAlpha < 255; + } + + QVERIFY2(std::abs(horizontalPartialAlpha - verticalPartialAlpha) <= 1, + qPrintable(QStringLiteral("non-uniform scaling must preserve symmetric screen-space AA: horizontal=%1 vertical=%2") + .arg(horizontalPartialAlpha) + .arg(verticalPartialAlpha))); + } + + void largeBezelWithSmallRadiusDoesNotIntroduceCornerDiagonalSeam() + { + setSmallRadiusLargeBezel(); + + const QImage img = grabImage(m_scene); + QVERIFY(!img.isNull()); + + const int seamStep = maxDiagonalCornerDiscontinuity(img); + QVERIFY2(seamStep < 96, + qPrintable(QStringLiteral("small-radius/large-bezel corner has a sharp diagonal seam: max cross-diagonal step=%1") + .arg(seamStep))); + } + + void largeBezelWithSmallRadiusKeepsStraightEdgeRefraction() + { + setSmallRadiusLargeBezel(); + + m_glass->setProperty("ior", 1.0001); + QTest::qWait(50); + const QImage neutral = grabImage(m_scene); + QVERIFY(!neutral.isNull()); + + m_glass->setProperty("ior", 1.45); + QTest::qWait(50); + const QImage refracted = grabImage(m_scene); + QVERIFY(!refracted.isNull()); + + const QRect straightEdgeBand(214, 80, 30, 96); + const int changed = regionDiffCount(neutral, refracted, straightEdgeBand, 4); + const int samples = straightEdgeBand.width() * straightEdgeBand.height(); + QVERIFY2(changed > samples / 2, + qPrintable(QStringLiteral("large bezel must keep right-edge refraction active when radius is small: changed=%1 samples=%2") + .arg(changed) + .arg(samples))); + } + + void contentEdgePullChangesSilhouetteRefraction() + { + setSmallRadiusLargeBezel(); + m_glass->setProperty("contentRampEnd", 0.15); + m_glass->setProperty("contentEdgePull", 0.0); + QTest::qWait(50); + + const QImage noEdgePull = grabImage(m_scene); + QVERIFY(!noEdgePull.isNull()); + + m_glass->setProperty("contentEdgePull", 1.0); + QTest::qWait(50); + + const QImage fullEdgePull = grabImage(m_scene); + QVERIFY(!fullEdgePull.isNull()); + + const QRect rightEdgeBand(fullEdgePull.width() - 4, 48, 3, 160); + const int changed = regionDiffCount(noEdgePull, fullEdgePull, rightEdgeBand, 4); + QVERIFY2(changed > rightEdgeBand.width() * rightEdgeBand.height() / 2, + qPrintable(QStringLiteral("contentEdgePull must visibly change silhouette refraction: changed=%1 regionPixels=%2") + .arg(changed) + .arg(rightEdgeBand.width() * rightEdgeBand.height()))); + } + + void refractionMaxTanAboveOneChangesEdgeRefraction() + { + m_glass->setProperty("blurEnabled", false); + m_glass->setProperty("radius", 60.0); + m_glass->setProperty("bezelWidth", 40.0); + m_glass->setProperty("thickness", 80.0); + m_glass->setProperty("ior", 1.45); + m_glass->setProperty("contentRampEnd", 0.15); + m_glass->setProperty("contentEdgePull", 1.0); + m_glass->setProperty("refractionMaxTan", 1.0); + QTest::qWait(50); + + const QImage cappedAtOne = grabImage(m_scene); + QVERIFY(!cappedAtOne.isNull()); + + m_glass->setProperty("refractionMaxTan", 20.0); + QTest::qWait(50); + + const QImage cappedAtTwenty = grabImage(m_scene); + QVERIFY(!cappedAtTwenty.isNull()); + + const QRect rightEdgeBand(cappedAtTwenty.width() - 12, 32, 10, 192); + const int changed = regionDiffCount(cappedAtOne, cappedAtTwenty, rightEdgeBand, 4); + m_glass->setProperty("contentEdgePull", 0.0); + m_glass->setProperty("refractionMaxTan", 2.75); + QTest::qWait(50); + QVERIFY2(changed > rightEdgeBand.width() * rightEdgeBand.height() / 8, + qPrintable(QStringLiteral("refractionMaxTan above 1 must visibly change edge refraction: changed=%1 regionPixels=%2") + .arg(changed) + .arg(rightEdgeBand.width() * rightEdgeBand.height()))); + } + + void radiusLargerThanBezelDoesNotIntroduceCornerDiagonalSeam() + { + m_glass->setProperty("blurEnabled", false); + // Isolate corner-geometry: geometry-only isolation; + // colour effect that reads as cross-diagonal colour steps here. + m_glass->setProperty("radius", 90.0); + m_glass->setProperty("bezelWidth", 60.0); + m_glass->setProperty("thickness", 50.0); + m_glass->setProperty("ior", 3.0); + QTest::qWait(50); + + const QImage img = grabImage(m_scene); + QVERIFY(!img.isNull()); + + const int seamStep = maxDiagonalCornerDiscontinuity(img); + QVERIFY2(seamStep < 24, + qPrintable(QStringLiteral("radius larger than bezel introduced a sharp diagonal seam: max cross-diagonal step=%1") + .arg(seamStep))); + } + + void tintControlChangesRenderedColor() + { + m_glass->setProperty("blurEnabled", false); + m_glass->setProperty("radius", 60.0); + m_glass->setProperty("tint", 0.0); + QTest::qWait(50); + + const QImage noTint = grabImage(m_scene); + QVERIFY(!noTint.isNull()); + + m_glass->setProperty("tint", 0.4); + QTest::qWait(50); + + const QImage strongTint = grabImage(m_scene); + QVERIFY(!strongTint.isNull()); + + const QRect centerInterior(64, 64, 128, 128); + const int changed = regionDiffCount(noTint, strongTint, centerInterior, 4); + QVERIFY2(changed > centerInterior.width() * centerInterior.height() / 3, + qPrintable(QStringLiteral("Liquid Glass tint control should change rendered color: changed=%1 regionPixels=%2") + .arg(changed) + .arg(centerInterior.width() * centerInterior.height()))); + } + + void zeroBlurMultiplierStillAppliesGaussianBlur() + { + m_glass->setProperty("blurEnabled", true); + m_glass->setProperty("blurMax", 48); + m_glass->setProperty("blurAmount", 1.0); + QVERIFY(m_glass->setProperty("blurMultiplier", 0.0)); + QTest::qWait(50); + + const QImage defaultQualityBlur = grabImage(m_scene); + QVERIFY(!defaultQualityBlur.isNull()); + + m_glass->setProperty("blurEnabled", false); + QTest::qWait(50); + + const QImage withoutBlur = grabImage(m_scene); + QVERIFY(!withoutBlur.isNull()); + + const QRect centerContrastFeature(92, 92, 72, 72); + const int changedPixels = regionDiffCount(defaultQualityBlur, withoutBlur, centerContrastFeature, 4); + QVERIFY2(changedPixels > centerContrastFeature.width() * centerContrastFeature.height() / 10, + qPrintable(QStringLiteral("MultiEffect blur must stay active with blurMultiplier=0: changedPixels=%1 regionPixels=%2") + .arg(changedPixels) + .arg(centerContrastFeature.width() * centerContrastFeature.height()))); + } + + void blurAmountAndMultiplierChangeRenderedBlurStrength() + { + m_glass->setProperty("blurEnabled", true); + m_glass->setProperty("blurMax", 48); + m_glass->setProperty("radius", 34.0); + QVERIFY2(m_glass->setProperty("blurAmount", 0.15), + "GlassEffect must expose blurAmount as a runtime QML property"); + QVERIFY2(m_glass->setProperty("blurMultiplier", 0.5), + "GlassEffect must expose blurMultiplier as a runtime QML property"); + QTest::qWait(50); + + const QImage weakBlur = grabImage(m_scene); + QVERIFY(!weakBlur.isNull()); + + QVERIFY(m_glass->setProperty("blurAmount", 1.0)); + QVERIFY(m_glass->setProperty("blurMultiplier", 2.0)); + QTest::qWait(50); + + const QImage strongBlur = grabImage(m_scene); + QVERIFY(!strongBlur.isNull()); + + const QRect centerContrastFeature(92, 92, 72, 72); + const int changedPixels = regionDiffCount(weakBlur, strongBlur, centerContrastFeature, 4); + QVERIFY2(changedPixels > centerContrastFeature.width() * centerContrastFeature.height() / 10, + qPrintable(QStringLiteral("blurAmount/blurMultiplier must visibly change the sampled backdrop blur: changedPixels=%1 regionPixels=%2") + .arg(changedPixels) + .arg(centerContrastFeature.width() * centerContrastFeature.height()))); + } + void blurToggleProducesDifferentRender() + { + m_glass->setProperty("blurEnabled", true); + m_glass->setProperty("blurMax", 36); + m_glass->setProperty("blurAmount", 1.0); + m_glass->setProperty("radius", 34.0); + QTest::qWait(50); + + const QImage withBlur = grabImage(m_scene); + QVERIFY(!withBlur.isNull()); + + m_glass->setProperty("blurEnabled", false); + QTest::qWait(50); + + const QImage withoutBlur = grabImage(m_scene); + QVERIFY(!withoutBlur.isNull()); + + QVERIFY(withBlur != withoutBlur); + } + + void benchmarkGlassShader() + { + // Offscreen grab round-trip benchmark for the Liquid Glass shader. + // Skipped in normal ctest runs; run explicitly: + // GLASS_BENCH=1 test_effect_glass benchmarkGlassShader + // GLASS_BENCH_SIZE=2048 to change grab size (default 1024) + // GLASS_BENCH_DRAWS=120 to change draws per round (default 120) + // GLASS_BENCH_ROUNDS=7 to change rounds (default 7) + // GLASS_BENCH_RADIUS=36 GLASS_BENCH_BEZEL=36 to change geometry + if (!qEnvironmentVariableIsSet("GLASS_BENCH")) { + QSKIP("Set GLASS_BENCH=1 to run the GPU benchmark"); + } + const int size = qgetenv("GLASS_BENCH_SIZE").toInt() > 0 ? qgetenv("GLASS_BENCH_SIZE").toInt() : 1024; + const int draws = qgetenv("GLASS_BENCH_DRAWS").toInt() > 0 ? qgetenv("GLASS_BENCH_DRAWS").toInt() : 120; + const int rounds = qgetenv("GLASS_BENCH_ROUNDS").toInt() > 0 ? qgetenv("GLASS_BENCH_ROUNDS").toInt() : 7; + + const qreal radius = qgetenv("GLASS_BENCH_RADIUS").toDouble(); + const qreal bezel = qgetenv("GLASS_BENCH_BEZEL").toDouble(); + m_glass->setProperty("blurEnabled", false); + m_glass->setProperty("specular", 0.0); + m_glass->setProperty("tint", 0.0); + if (radius > 0) + m_glass->setProperty("radius", radius); + if (bezel > 0) + m_glass->setProperty("bezelWidth", bezel); + QTest::qWait(50); + + // Warmup + auto warmup = m_scene->grabToImage(QSize(size, size)); + QSignalSpy warmupSpy(warmup.data(), &QQuickItemGrabResult::ready); + warmupSpy.wait(5000); + + std::vector medians; + for (int round = 0; round < rounds; ++round) { + std::vector times; + times.reserve(draws); + for (int i = 0; i < draws; ++i) { + auto result = m_scene->grabToImage(QSize(size, size)); + if (!result) + continue; + QElapsedTimer timer; + timer.start(); + QSignalSpy spy(result.data(), &QQuickItemGrabResult::ready); + spy.wait(5000); + times.push_back(timer.elapsed()); + } + std::sort(times.begin(), times.end()); + const qint64 median = times[times.size() / 2]; + medians.push_back(median); + qDebug("Round %d: median %lld ms (%d draws, %dx%d)", + round + 1, (long long)median, draws, size, size); + } + std::sort(medians.begin(), medians.end()); + const double overallMedian = static_cast(medians[medians.size() / 2]); + qDebug("Overall median: %.2f ms (%dx%d, radius %.1f, bezel %.1f, " + "%d rounds x %d draws)", + overallMedian, size, size, + m_glass->property("radius").toReal(), + m_glass->property("bezelWidth").toReal(), + rounds, draws); + QTest::qCompare(overallMedian, overallMedian, "median", "median", __FILE__, __LINE__); + } +}; + +int main(int argc, char *argv[]) +{ + // Headless wlroots backend — no display server needed. + qputenv("WLR_BACKENDS", "headless"); + + WLog::init(); + WServer::initializeQPA(); + + // Probe the graphics API that can create a wlroots renderer in this + // environment. CI containers without a DRM render node fall back to + // Software/pixman; rendering-only tests skip in that mode. + WRenderHelper::setupRendererBackend(); + + QGuiApplication app(argc, argv); + QQmlApplicationEngine engine; + + engine.loadFromModule("TestGlass", "TestWindow"); + if (engine.rootObjects().isEmpty()) + return 1; + + auto *root = engine.rootObjects().first(); + auto *window = root->findChild("renderWindow"); + Q_ASSERT(window); + + auto *helper = engine.singletonInstance("TestGlass", "TestHelper"); + Q_ASSERT(helper); + helper->initProtocols(window, &engine); + window->setVisible(true); // QQuickItem::grabToImage requires isVisible + + // Wait for the headless output to be created and the scene to be ready. + QSignalSpy initSpy(window, &WOutputRenderWindow::outputViewportInitialized); + if (initSpy.isEmpty()) + initSpy.wait(5000); + QTest::qWait(500); // let the scene graph settle + + auto *scene = window->findChild("glassScene"); + Q_ASSERT(scene); + auto *glass = window->findChild("glassEffect"); + Q_ASSERT(glass); + + GlassEffectTest::setGlobals(window, scene, glass, helper); + + GlassEffectTest test; + int result = QTest::qExec(&test, argc, argv); + // wlroots objects (renderer, allocator, compositor) crash during normal + // destructor unwinding — skip cleanup and exit immediately. + std::_Exit(result); +} + +#include "main.moc" diff --git a/tests/test_frame_geometry/CMakeLists.txt b/tests/test_frame_geometry/CMakeLists.txt new file mode 100644 index 0000000000..317b902b36 --- /dev/null +++ b/tests/test_frame_geometry/CMakeLists.txt @@ -0,0 +1,16 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +find_package(Qt6 6.8 REQUIRED COMPONENTS Test Qml Quick) +qt_add_executable(test_frame_geometry + main.cpp + "${PROJECT_SOURCE_DIR}/src/surface/framegeometry.cpp" + "${PROJECT_SOURCE_DIR}/src/surface/framegeometry.h" + "${PROJECT_SOURCE_DIR}/src/surface/frameinputmask.cpp" + "${PROJECT_SOURCE_DIR}/src/surface/frameinputmask.h" +) +target_include_directories(test_frame_geometry PRIVATE "${PROJECT_SOURCE_DIR}/src") +target_link_libraries(test_frame_geometry PRIVATE Qt::Test Qt::Qml Qt::Quick Waylib::WaylibServer) +add_test(NAME test_frame_geometry COMMAND test_frame_geometry) +set_tests_properties(test_frame_geometry PROPERTIES + ENVIRONMENT "QT_QPA_PLATFORM=offscreen;QT_QUICK_BACKEND=software" + TIMEOUT 30 +) diff --git a/tests/test_frame_geometry/main.cpp b/tests/test_frame_geometry/main.cpp new file mode 100644 index 0000000000..3dcfff98e6 --- /dev/null +++ b/tests/test_frame_geometry/main.cpp @@ -0,0 +1,438 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include "surface/framegeometry.h" +#include "surface/frameinputmask.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +struct NativeSurface { + wlr_surface handle {}; + NativeSurface() + { + wl_signal_init(&handle.events.commit); + wl_signal_init(&handle.events.map); + wl_signal_init(&handle.events.unmap); + wl_signal_init(&handle.events.new_subsurface); + wl_signal_init(&handle.events.destroy); + wl_list_init(&handle.current.frame_callback_list); + wl_list_init(&handle.current.subsurfaces_below); + wl_list_init(&handle.current.subsurfaces_above); + wl_list_init(&handle.current_outputs); + wlr_addon_set_init(&handle.addons); + handle.current.width = 400; + handle.current.height = 160; + handle.current.scale = 1; + handle.current.seq = 1; + handle.mapped = true; + pixman_region32_init_rect(&handle.input_region, 0, 0, 400, 160); + pixman_region32_t hole; + pixman_region32_init_rect(&hole, 100, 0, 100, 160); + pixman_region32_subtract(&handle.input_region, &handle.input_region, &hole); + pixman_region32_fini(&hole); + } + ~NativeSurface() + { + pixman_region32_fini(&handle.input_region); + wlr_addon_set_finish(&handle.addons); + } +}; + +class TestSurfaceItem : public WSurfaceItem +{ +public: + using WSurfaceItem::WSurfaceItem; + int presses = 0; + int releases = 0; +protected: + bool sendEvent(QInputEvent *event) override + { + if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::TouchBegin) + ++presses; + if (event->type() == QEvent::MouseButtonRelease || event->type() == QEvent::TouchEnd) + ++releases; + event->accept(); + return true; + } +}; +} + + +class FrameGeometryTest : public QObject +{ + Q_OBJECT +private Q_SLOTS: + void normalization() + { + QCOMPARE(FrameGeometry(QRectF(10, 20, 300, 200), 200).radius(), 100); + QCOMPARE(FrameGeometry(QRectF(10, 20, 300, 200), -1).radius(), 0); + QCOMPARE(FrameGeometry(QRectF(0, 0, 300, 200), + std::numeric_limits::infinity()).radius(), 0); + QVERIFY(!FrameGeometry().contains(QPointF())); + QVERIFY(!FrameGeometry(QRectF(0, 0, -1, 100), 10).contains(QPointF())); + QVERIFY(!FrameGeometry(QRectF(0, 0, 100, 0), 10).contains(QPointF())); + QCOMPARE(FrameGeometry(QRectF(0, 0, 100, 80), 10) + .resizeEdgesAt(QPointF(-1, 40), std::numeric_limits::quiet_NaN()), + Qt::Edges()); + } + + void contour_data() + { + QTest::addColumn("point"); + QTest::addColumn("inside"); + QTest::addColumn("edges"); + QTest::newRow("far-outside") << QPointF(-1000, 50) << false << Qt::Edges(); + QTest::newRow("cut-corner") << QPointF(0, 0) << false << Qt::Edges(); + QTest::newRow("curved-rim") << QPointF(20, 20) << false << (Qt::TopEdge | Qt::LeftEdge); + QTest::newRow("curved-interior") << QPointF(25, 25) << true << Qt::Edges(); + QTest::newRow("below-titlebar-outside") << QPointF(-1, 40) << false << Qt::Edges(); + QTest::newRow("below-titlebar-rim") << QPointF(5, 40) << false << (Qt::TopEdge | Qt::LeftEdge); + QTest::newRow("below-titlebar-interior") << QPointF(15, 40) << true << Qt::Edges(); + QTest::newRow("left") << QPointF(-5, 100) << false << Qt::Edges(Qt::LeftEdge); + QTest::newRow("right") << QPointF(305, 100) << false << Qt::Edges(Qt::RightEdge); + QTest::newRow("top") << QPointF(150, -5) << false << Qt::Edges(Qt::TopEdge); + QTest::newRow("bottom") << QPointF(150, 205) << false << Qt::Edges(Qt::BottomEdge); + QTest::newRow("right-limit") << QPointF(310, 100) << false << Qt::Edges(); + QTest::newRow("bottom-limit") << QPointF(150, 210) << false << Qt::Edges(); + QTest::newRow("center") << QPointF(150, 100) << true << Qt::Edges(); + QTest::newRow("nan") << QPointF(std::numeric_limits::quiet_NaN(), 50) + << false << Qt::Edges(); + } + + void contour() + { + QFETCH(QPointF, point); + QFETCH(bool, inside); + QFETCH(Qt::Edges, edges); + for (const QPointF offset : {QPointF(), QPointF(30, 50)}) { + const FrameGeometry geometry(QRectF(offset, QSizeF(300, 200)), 80); + QCOMPARE(geometry.contains(point + offset), inside); + QCOMPARE(geometry.resizeEdgesAt(point + offset, 10), edges); + } + } + + void inputMask_data() + { + QTest::addColumn("ratio"); + QTest::addColumn("touch"); + for (const qreal ratio : {1.0, 1.25, 2.0}) { + for (bool touch : {false, true}) + QTest::newRow(qPrintable(QString::number(ratio) + (touch ? "-touch" : "-mouse"))) + << ratio << touch; + } + } + + void inputMask() + { + QFETCH(qreal, ratio); + QFETCH(bool, touch); + NativeSurface native; + WSurface surface(&native.handle); + QQmlEngine engine; + QQuickWindow window; + window.resize(500, 300); + QQmlComponent lowerComponent(&engine); + lowerComponent.setData(R"( + import QtQuick + MouseArea { width: 500; height: 300; property int presses: 0; onPressed: presses++ } + )", QUrl()); + QVERIFY2(lowerComponent.isReady(), qPrintable(lowerComponent.errorString())); + std::unique_ptr lower(qobject_cast(lowerComponent.create())); + QVERIFY(lower); + lower->setParentItem(window.contentItem()); + QQmlComponent delegate(&engine); + delegate.setData("import QtQuick; Item { required property var surface }", QUrl()); + TestSurfaceItem client(window.contentItem()); + client.setDelegate(&delegate); + client.setSurfaceSizeRatio(ratio); + client.setTopPadding(40); + client.setSurface(&surface); + auto *eventItem = client.eventItem(); + QVERIFY(eventItem); + FrameInputMask mask; + mask.setFrameItem(&client); + mask.setTarget(eventItem); + mask.setProperty("geometry", QVariant::fromValue(FrameGeometry(QRectF(QPointF(), client.size()), 80))); + eventItem->setContainmentMask(&mask); + QVERIFY(!eventItem->contains(QPointF(5, 0))); + QVERIFY(!eventItem->contains(QPointF(140, 80))); + QVERIFY(eventItem->contains(QPointF(60, 80))); + window.show(); + QVERIFY(QTest::qWaitForWindowExposed(&window)); + const QPoint corner = eventItem->mapToScene(QPointF(5, 0)).toPoint(); + QTest::mouseClick(&window, Qt::LeftButton, Qt::NoModifier, corner); + QCOMPARE(lower->property("presses").toInt(), 1); + QCOMPARE(client.presses, 0); + const QPoint start = eventItem->mapToScene(QPointF(60, 80)).toPoint(); + if (touch) { + std::unique_ptr device(QTest::createTouchDevice()); + QTest::touchEvent(&window, device.get()).press(0, start, &window).commit(); + QTest::touchEvent(&window, device.get()).move(0, corner, &window).commit(); + QTest::touchEvent(&window, device.get()).release(0, corner, &window).commit(); + } else { + QTest::mousePress(&window, Qt::LeftButton, Qt::NoModifier, start); + QTest::mouseMove(&window, corner); + QTest::mouseRelease(&window, Qt::LeftButton, Qt::NoModifier, corner); + } + QCOMPARE(client.presses, 1); + QCOMPARE(client.releases, 1); + QCOMPARE(lower->property("presses").toInt(), 1); + eventItem->setContainmentMask(nullptr); + QVERIFY(eventItem->contains(QPointF(5, 0))); + client.setSurface(nullptr); + QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); + QVERIFY(!mask.contains(QPointF(60, 80))); + } + + void animationContour_data() + { + QTest::addColumn("componentName"); + QTest::addColumn("initialRadius"); + QTest::addColumn("targetRadius"); + QTest::newRow("maximize") << QStringLiteral("GeometryAnimation") << qreal(12) << qreal(0); + QTest::newRow("restore") << QStringLiteral("GeometryAnimation") << qreal(0) << qreal(12); + QTest::newRow("window-transition") << QStringLiteral("WindowTransition") << qreal(12) << qreal(24); + QTest::newRow("minimize") << QStringLiteral("MinimizeAnimation") << qreal(0) << qreal(12); + QTest::newRow("show-desktop") << QStringLiteral("ShowDesktopAnimation") << qreal(0) << qreal(12); + QTest::newRow("new-window") << QStringLiteral("NewAnimation") << qreal(0) << qreal(12); + QTest::newRow("layer-shell") << QStringLiteral("LayerShellAnimation") << qreal(0) << qreal(12); + } + + void animationContour() + { + QFETCH(QString, componentName); + QFETCH(qreal, initialRadius); + QFETCH(qreal, targetRadius); + // Substitute only external dependencies; execute the production animation bindings. + QTemporaryDir modules; + QVERIFY(modules.isValid()); + const auto modulePath = modules.path() + QStringLiteral("/AnimationFixture"); + QVERIFY(QDir().mkpath(modulePath)); + const QList> fixtures { + {"qmldir", "module AnimationFixture\nSurfaceWrapper 1.0 SurfaceWrapper.qml\nXdgShadow 1.0 XdgShadow.qml\nBlur 1.0 Blur.qml\nsingleton WaylandServer 1.0 WaylandServer.qml\nWindowTransition 1.0 WindowTransition.qml\nMinimizeAnimation 1.0 WindowTransition.qml\nNewAnimation 1.0 WindowTransition.qml\nLayerShellAnimation 1.0 WindowTransition.qml\n"}, + {"SurfaceWrapper.qml", R"(import QtQuick + Item { + width: 400; height: 200 + enum State { Normal, Maximized, Fullscreen } + property int surfaceState: SurfaceWrapper.Normal + property real radius: 64 + property var presentationFrameGeometry + property rect boundingRect: Qt.rect(0, 0, width, height) + property bool visibleDecoration: true + property bool noDecoration: false + property bool shadowVisible: true + property real shadowBlurRadius: 40 + property real shadowOffsetX: 0 + property real shadowOffsetY: 10 + property color shadowColor: "black" + })"}, + {"XdgShadow.qml", R"(import QtQuick + Item { + objectName: "shadow" + property real cornerRadius + property real shadowBlur + property real shadowOffsetX + property real shadowOffsetY + property color shadowColor + })"}, + {"Blur.qml", "import QtQuick; Item { objectName: 'blur'; property real radius }"}, + {"WindowTransition.qml", "import QtQuick; Item { enum Direction { Show = 1, Hide } }"}, + {"WaylandServer.qml", "pragma Singleton\nimport QtQuick\nQtObject { property real animationSpeed: 1 }"}, + }; + for (const auto &fixture : fixtures) { + QFile file(modulePath + '/' + fixture.first); + QVERIFY(file.open(QIODevice::WriteOnly)); + QCOMPARE(file.write(fixture.second), fixture.second.size()); + } + QQmlEngine engine; + engine.addImportPath(modules.path()); + engine.addImportPath(QCoreApplication::applicationDirPath() + "/../../waylib/src/server"); + QQmlComponent surfaceComponent(&engine); + surfaceComponent.setData("import AnimationFixture 1.0; SurfaceWrapper {}", QUrl()); + QVERIFY2(surfaceComponent.isReady(), qPrintable(surfaceComponent.errorString())); + std::unique_ptr surface(surfaceComponent.create()); + QVERIFY(surface); + const FrameGeometry initial(QRectF(0, 0, 400, 200), initialRadius); + surface->setProperty("presentationFrameGeometry", QVariant::fromValue(initial)); + const auto path = QFINDTESTDATA("../../src/core/qml/Animations") + '/' + componentName + ".qml"; + QFile source(path); + QVERIFY(source.open(QIODevice::ReadOnly)); + auto code = source.readAll(); + code.replace("import Treeland", "import AnimationFixture 1.0"); + if (componentName == QStringLiteral("LayerShellAnimation")) + code.prepend("import AnimationFixture 1.0\n"); + QQmlComponent component(&engine); + component.setData(code, QUrl::fromLocalFile(path)); + QVERIFY2(component.isReady(), qPrintable(component.errorString())); + QVariantMap properties; + if (componentName == QStringLiteral("GeometryAnimation") + || componentName == QStringLiteral("WindowTransition")) { + properties = {{"surface", QVariant::fromValue(surface.get())}, + {"fromGeometry", initial.rect()}, {"toGeometry", initial.rect()}, + {"enableBlur", true}}; + } else { + properties = {{"target", QVariant::fromValue(surface.get())}}; + if (componentName == QStringLiteral("ShowDesktopAnimation")) { + properties.insert("showDesktop", true); + } else { + properties.insert("direction", 1); + if (componentName == QStringLiteral("MinimizeAnimation")) + properties.insert("position", initial.rect()); + else + properties.insert("enableBlur", true); + if (componentName == QStringLiteral("LayerShellAnimation")) + properties.insert("position", Qt::BottomEdge); + } + } + std::unique_ptr animation(component.createWithInitialProperties(properties)); + QVERIFY2(animation, qPrintable(component.errorString())); + auto *shadow = animation->findChild("shadow"); + auto *blur = animation->findChild("blur"); + const bool blurOnly = componentName == QStringLiteral("NewAnimation") + || componentName == QStringLiteral("LayerShellAnimation"); + const bool shadowOnly = componentName == QStringLiteral("MinimizeAnimation") + || componentName == QStringLiteral("ShowDesktopAnimation"); + if (!blurOnly) { + QVERIFY(shadow); + QCOMPARE(shadow->property("cornerRadius").toReal(), initialRadius); + } + if (!shadowOnly) { + QVERIFY(blur); + QCOMPARE(blur->property("radius").toReal(), initialRadius); + } + surface->setProperty("presentationFrameGeometry", + QVariant::fromValue(FrameGeometry(initial.rect(), targetRadius))); + if (shadow) + QCOMPARE(shadow->property("cornerRadius").toReal(), targetRadius); + if (blur) + QCOMPARE(blur->property("radius").toReal(), targetRadius); + + if (componentName != QStringLiteral("GeometryAnimation")) + return; + auto *item = qobject_cast(animation.get()); + QVERIFY(item); + QQuickWindow window; + window.resize(1000, 600); + item->setParentItem(window.contentItem()); + const QSizeF targetSize = initialRadius > targetRadius ? QSizeF(800, 400) : QSizeF(200, 100); + const QRectF target(QPointF(80, 60), targetSize); + QVERIFY(item->setProperty("toGeometry", target)); + QVERIFY(item->setProperty("duration", 400)); + window.show(); + QVERIFY(QTest::qWaitForWindowExposed(&window)); + QSignalSpy finished(item, SIGNAL(finished())); + QVERIFY(QMetaObject::invokeMethod(item, "start")); + QTRY_VERIFY(qAbs(item->width() - initial.rect().width()) > 5); + QVERIFY(qAbs(item->width() - target.width()) > 5); + const qreal progress = (item->width() - initial.rect().width()) + / (target.width() - initial.rect().width()); + QVERIFY2(qAbs(item->x() - target.x() * progress) < 1, + "Animation position and frame size must advance in the same frame"); + QVERIFY(qAbs(item->y() - target.y() * progress) < 1); + QVERIFY(qAbs(item->height() - (initial.rect().height() + + (target.height() - initial.rect().height()) * progress)) < 1); + QTRY_COMPARE(finished.count(), 1); + QCOMPARE(QRectF(item->position(), item->size()), target); + QTest::qWait(50); + QCOMPARE(QRectF(item->position(), item->size()), target); + item->setParentItem(nullptr); + } + + void highlightRadius_data() + { + QTest::addColumn("padded"); + QTest::addColumn("frameRadius"); + QTest::addColumn("paddingRadius"); + QTest::addColumn("expectedRadius"); + QTest::newRow("ssd-rounded") << false << qreal(12) << qreal(18) << qreal(12); + QTest::newRow("ssd-square") << false << qreal(0) << qreal(18) << qreal(0); + QTest::newRow("ssd-scaled") << false << qreal(4.5) << qreal(18) << qreal(4.5); + QTest::newRow("csd-rounded") << false << qreal(6) << qreal(18) << qreal(6); + QTest::newRow("csd-maximized-or-fullscreen") << false << qreal(0) << qreal(18) << qreal(0); + QTest::newRow("padding-rounded") << true << qreal(12) << qreal(18) << qreal(18); + QTest::newRow("padding-square") << true << qreal(12) << qreal(0) << qreal(0); + QTest::newRow("padding-around-square-window") << true << qreal(0) << qreal(12) << qreal(12); + } + + void highlightRadius() + { + QFETCH(bool, padded); + QFETCH(qreal, frameRadius); + QFETCH(qreal, paddingRadius); + QFETCH(qreal, expectedRadius); + QQmlEngine engine; + QQmlComponent component(&engine, QUrl::fromLocalFile( + QFINDTESTDATA("../../src/plugins/multitaskview/qml/WindowHighlight.qml"))); + QVERIFY2(component.isReady(), qPrintable(component.errorString())); + std::unique_ptr highlight(component.createWithInitialProperties({ + {"frameRadius", frameRadius}, {"padded", padded}, + {"paddingRadius", paddingRadius}, {"width", 300}, {"height", 200}, + })); + QVERIFY2(highlight, qPrintable(component.errorString())); + QQmlProperty borderWidth(highlight.get(), "border.width"); + QVERIFY(borderWidth.write(2)); + QCOMPARE(highlight->property("radius").toReal(), expectedRadius > 0 ? expectedRadius + 2 : 0); + QVERIFY(borderWidth.write(4)); + QCOMPARE(highlight->property("radius").toReal(), expectedRadius > 0 ? expectedRadius + 4 : 0); + if (padded) { + QVERIFY(highlight->setProperty("paddingRadius", 0)); + QCOMPARE(highlight->property("radius").toReal(), qreal(0)); + QVERIFY(highlight->setProperty("paddingRadius", 5)); + QCOMPARE(highlight->property("radius").toReal(), qreal(9)); + } else { + QVERIFY(highlight->setProperty("frameRadius", 6)); + QCOMPARE(highlight->property("radius").toReal(), qreal(10)); + QVERIFY(highlight->setProperty("frameRadius", 0)); + QCOMPARE(highlight->property("radius").toReal(), qreal(0)); + } + } + + void maskLifetime() + { + FrameInputMask mask; + auto frame = std::make_unique(); + frame->setSize(QSizeF(300, 200)); + auto target = std::make_unique(frame.get()); + target->setSize(QSizeF(320, 220)); + target->setPosition(QPointF(-10, -10)); + mask.setFrameItem(frame.get()); + mask.setTarget(target.get()); + mask.setProperty("geometry", QVariant::fromValue(FrameGeometry(QRectF(0, 0, 300, 200), 80))); + mask.setProperty("resizeMargin", 10); + QVERIFY(mask.contains(QPointF(30, 30))); + QCOMPARE(mask.edgesAt(QPointF(30, 30)), Qt::TopEdge | Qt::LeftEdge); + QVERIFY(!mask.contains(QPointF(10, 10))); + target.reset(); + QVERIFY(!mask.contains(QPointF(30, 30))); + frame.reset(); + QVERIFY(!mask.contains(QPointF(30, 30))); + } + + void square() + { + const FrameGeometry geometry(QRectF(0, 0, 100, 80), 0); + QVERIFY(geometry.contains(QPointF(0, 0))); + QVERIFY(!geometry.contains(QPointF(100, 40))); + QCOMPARE(geometry.resizeEdgesAt(QPointF(-1, -1), 10), Qt::TopEdge | Qt::LeftEdge); + QCOMPARE(geometry.resizeEdgesAt(QPointF(0, 0), 10), Qt::Edges()); + QCOMPARE(geometry.resizeEdgesAt(QPointF(-1, 40), 0), Qt::Edges()); + } +}; + +QTEST_MAIN(FrameGeometryTest) +#include "main.moc" diff --git a/tests/test_protocol_appearance/CMakeLists.txt b/tests/test_protocol_appearance/CMakeLists.txt new file mode 100644 index 0000000000..115c7eab0c --- /dev/null +++ b/tests/test_protocol_appearance/CMakeLists.txt @@ -0,0 +1,19 @@ +find_package(Qt6 REQUIRED COMPONENTS Test) + +add_executable(test_protocol_appearance main.cpp) + +target_link_libraries(test_protocol_appearance + PRIVATE + libtreeland + Qt::Test +) + +add_test(NAME test_protocol_appearance COMMAND test_protocol_appearance) + +set_property(TEST test_protocol_appearance PROPERTY + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" +) + +set_property(TEST test_protocol_appearance PROPERTY + TIMEOUT 3 +) diff --git a/tests/test_protocol_appearance/main.cpp b/tests/test_protocol_appearance/main.cpp new file mode 100644 index 0000000000..4a2f65128b --- /dev/null +++ b/tests/test_protocol_appearance/main.cpp @@ -0,0 +1,81 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "modules/appearance/appearanceinterfacev1.h" +#include "modules/appearance/appearancemanagerinterfacev1.h" + +#include + +#include +#include + +class AppearanceTest : public QObject +{ + Q_OBJECT + + WAYLIB_SERVER_NAMESPACE::WServer *m_server = nullptr; + +public: + AppearanceTest(QObject *parent = nullptr) + : QObject(parent) + { + } + +private Q_SLOTS: + + void initTestCase() + { + m_server = new WAYLIB_SERVER_NAMESPACE::WServer(); + } + + // --- AppearanceInterfaceV1 (read-only push) --- + + void testCreateAppearance() + { + QVERIFY(m_server->attach(nullptr, m_server) != nullptr); + } + + void verifyAppearance() + { + auto protocol = m_server->findChild(); + QVERIFY(protocol != nullptr); + } + + // --- AppearanceManagerInterfaceV1 (privileged setter) --- + + void testCreateAppearanceManager() + { + QVERIFY(m_server->attach(nullptr, m_server) != nullptr); + } + + void verifyAppearanceManager() + { + auto protocol = m_server->findChild(); + QVERIFY(protocol != nullptr); + } + + // --- interfaceName sanity --- + + void testAppearanceInterfaceName() + { + auto *appearance = m_server->findChild(); + QVERIFY(appearance != nullptr); + QVERIFY(!appearance->interfaceName().isEmpty()); + } + + void testAppearanceManagerInterfaceName() + { + auto *manager = m_server->findChild(); + QVERIFY(manager != nullptr); + QVERIFY(!manager->interfaceName().isEmpty()); + } + + void cleanupTestCase() + { + m_server->deleteLater(); + m_server = nullptr; + } +}; + +QTEST_MAIN(AppearanceTest) +#include "main.moc" diff --git a/tests/test_protocol_compositor-action/CMakeLists.txt b/tests/test_protocol_compositor-action/CMakeLists.txt new file mode 100644 index 0000000000..40562a4460 --- /dev/null +++ b/tests/test_protocol_compositor-action/CMakeLists.txt @@ -0,0 +1,19 @@ +find_package(Qt6 REQUIRED COMPONENTS Test) + +add_executable(test_protocol_compositor-action main.cpp) + +target_link_libraries(test_protocol_compositor-action + PRIVATE + libtreeland + Qt::Test +) + +add_test(NAME test_protocol_compositor-action COMMAND test_protocol_compositor-action) + +set_property(TEST test_protocol_compositor-action PROPERTY + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" +) + +set_property(TEST test_protocol_compositor-action PROPERTY + TIMEOUT 3 +) diff --git a/tests/test_protocol_compositor-action/main.cpp b/tests/test_protocol_compositor-action/main.cpp new file mode 100644 index 0000000000..1ed7726b33 --- /dev/null +++ b/tests/test_protocol_compositor-action/main.cpp @@ -0,0 +1,80 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "modules/compositor-action/compositoractioninterfacev1.h" + +#include + +#include +#include +#include + +class CompositorActionTest : public QObject +{ + Q_OBJECT + + WAYLIB_SERVER_NAMESPACE::WServer *m_server = nullptr; + CompositorActionInterfaceV1 *m_protocol = nullptr; + +public: + CompositorActionTest(QObject *parent = nullptr) + : QObject(parent) + { + } + +private Q_SLOTS: + + void initTestCase() + { + m_server = new WAYLIB_SERVER_NAMESPACE::WServer(); + } + + void testCreate() + { + QVERIFY(m_server->attach(m_server) != nullptr); + } + + void verifyProtocol() + { + m_protocol = m_server->findChild(); + QVERIFY(m_protocol != nullptr); + } + + void testInterfaceName() + { + QVERIFY(m_protocol != nullptr); + QVERIFY(!m_protocol->interfaceName().isEmpty()); + QCOMPARE(m_protocol->interfaceName(), + QByteArrayView("treeland_compositor_action_v1")); + } + + // The trigger request is fire-and-forget: the interface only relays the + // raw action value, it never routes or validates it itself. + void testTriggerRelaysAction() + { + QVERIFY(m_protocol != nullptr); + QSignalSpy spy(m_protocol, &CompositorActionInterfaceV1::triggered); + QVERIFY(spy.isValid()); + + // Simulate what the generated resource does on a trigger request. + QMetaObject::invokeMethod(m_protocol, [this] { + Q_EMIT m_protocol->triggered(18); // toggle_multitask_view + }); + QMetaObject::invokeMethod(m_protocol, [this] { + Q_EMIT m_protocol->triggered(999); // unknown future action + }); + + QCOMPARE(spy.count(), 2); + QCOMPARE(spy.at(0).at(0).toUInt(), 18u); + QCOMPARE(spy.at(1).at(0).toUInt(), 999u); + } + + void cleanupTestCase() + { + m_server->deleteLater(); + m_server = nullptr; + } +}; + +QTEST_MAIN(CompositorActionTest) +#include "main.moc" diff --git a/tests/test_protocol_decoration/CMakeLists.txt b/tests/test_protocol_decoration/CMakeLists.txt new file mode 100644 index 0000000000..494654a254 --- /dev/null +++ b/tests/test_protocol_decoration/CMakeLists.txt @@ -0,0 +1,19 @@ +find_package(Qt6 REQUIRED COMPONENTS Test) + +add_executable(test_protocol_decoration main.cpp) + +target_link_libraries(test_protocol_decoration + PRIVATE + libtreeland + Qt::Test +) + +add_test(NAME test_protocol_decoration COMMAND test_protocol_decoration) + +set_property(TEST test_protocol_decoration PROPERTY + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" +) + +set_property(TEST test_protocol_decoration PROPERTY + TIMEOUT 3 +) diff --git a/tests/test_protocol_decoration/main.cpp b/tests/test_protocol_decoration/main.cpp new file mode 100644 index 0000000000..1cb61d53fc --- /dev/null +++ b/tests/test_protocol_decoration/main.cpp @@ -0,0 +1,56 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "modules/decoration/decorationmanagerinterfacev1.h" + +#include + +#include +#include + +class DecorationTest : public QObject +{ + Q_OBJECT + + WAYLIB_SERVER_NAMESPACE::WServer *m_server = nullptr; + +public: + DecorationTest(QObject *parent = nullptr) + : QObject(parent) + { + } + +private Q_SLOTS: + + void initTestCase() + { + m_server = new WAYLIB_SERVER_NAMESPACE::WServer(); + } + + void testCreateDecorationManager() + { + QVERIFY(m_server->attach(m_server) != nullptr); + } + + void verifyDecorationManager() + { + auto *manager = m_server->findChild(); + QVERIFY(manager != nullptr); + } + + void testDecorationInterfaceName() + { + auto *manager = m_server->findChild(); + QVERIFY(manager != nullptr); + QVERIFY(!manager->interfaceName().isEmpty()); + } + + void cleanupTestCase() + { + m_server->deleteLater(); + m_server = nullptr; + } +}; + +QTEST_MAIN(DecorationTest) +#include "main.moc" diff --git a/tests/test_protocol_pointerconstraints/CMakeLists.txt b/tests/test_protocol_pointerconstraints/CMakeLists.txt new file mode 100644 index 0000000000..da85e8cde9 --- /dev/null +++ b/tests/test_protocol_pointerconstraints/CMakeLists.txt @@ -0,0 +1,19 @@ +find_package(Qt6 REQUIRED COMPONENTS Test) + +add_executable(test_protocol_pointerconstraints main.cpp) + +target_link_libraries(test_protocol_pointerconstraints + PRIVATE + libtreeland + Qt::Test +) + +add_test(NAME test_protocol_pointerconstraints COMMAND test_protocol_pointerconstraints) + +set_property(TEST test_protocol_pointerconstraints PROPERTY + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" +) + +set_property(TEST test_protocol_pointerconstraints PROPERTY + TIMEOUT 3 +) diff --git a/tests/test_protocol_pointerconstraints/main.cpp b/tests/test_protocol_pointerconstraints/main.cpp new file mode 100644 index 0000000000..bab1754c15 --- /dev/null +++ b/tests/test_protocol_pointerconstraints/main.cpp @@ -0,0 +1,56 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include + +#include +#include + +using namespace WAYLIB_SERVER_NAMESPACE; + +class PointerConstraintsTest : public QObject +{ + Q_OBJECT + + WServer *m_server = nullptr; + +public: + PointerConstraintsTest(QObject *parent = nullptr) + : QObject(parent) + { + } + +private Q_SLOTS: + void initTestCase() + { + m_server = new WServer(); + } + + void cleanupTestCase() + { + delete m_server; + m_server = nullptr; + } + + // The WPointerConstraintsV1 wrapper can be attached via the server + // and exposes its interface name correctly. + void testCreateInterface() + { + auto *constraints = m_server->attach(); + QVERIFY(constraints != nullptr); + QCOMPARE(constraints->interfaceName(), QByteArrayView("zwp_pointer_constraints_v1")); + QVERIFY(m_server->findInterface() == constraints); + } + + // Without any surface/seat there is nothing to constrain. + void testConstraintForSurfaceReturnsNullWithoutSeat() + { + auto *constraints = m_server->findInterface(); + QVERIFY(constraints != nullptr); + QVERIFY(constraints->constraintForSurface(nullptr, nullptr) == nullptr); + } +}; + +QTEST_MAIN(PointerConstraintsTest) +#include "main.moc" diff --git a/tests/test_protocol_prelaunch-splash/CMakeLists.txt b/tests/test_protocol_prelaunch-splash/CMakeLists.txt new file mode 100644 index 0000000000..ce4ab5d126 --- /dev/null +++ b/tests/test_protocol_prelaunch-splash/CMakeLists.txt @@ -0,0 +1,19 @@ +find_package(Qt6 REQUIRED COMPONENTS Test) + +add_executable(test_protocol_prelaunch-splash main.cpp) + +target_link_libraries(test_protocol_prelaunch-splash + PRIVATE + libtreeland + Qt::Test +) + +add_test(NAME test_protocol_prelaunch-splash COMMAND test_protocol_prelaunch-splash) + +set_property(TEST test_protocol_prelaunch-splash PROPERTY + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" +) + +set_property(TEST test_protocol_prelaunch-splash PROPERTY + TIMEOUT 3 +) diff --git a/tests/test_protocol_prelaunch-splash/main.cpp b/tests/test_protocol_prelaunch-splash/main.cpp new file mode 100644 index 0000000000..be6a0a8e8f --- /dev/null +++ b/tests/test_protocol_prelaunch-splash/main.cpp @@ -0,0 +1,63 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "modules/prelaunch-splash/prelaunchsplash.h" + +#include + +#include +#include +#include + +class PrelaunchSplashTest : public QObject +{ + Q_OBJECT + + WAYLIB_SERVER_NAMESPACE::WServer *m_server = nullptr; + PrelaunchSplash *m_protocol = nullptr; + +public: + PrelaunchSplashTest(QObject *parent = nullptr) + : QObject(parent) + { + } + +private Q_SLOTS: + + void initTestCase() + { + m_server = new WAYLIB_SERVER_NAMESPACE::WServer(); + } + + void testCreate() + { + m_protocol = m_server->attach(); + QVERIFY(m_protocol != nullptr); + } + + void verifyPrelaunchSplash() + { + QVERIFY(m_protocol != nullptr); + } + + void testSignals() + { + QVERIFY(m_protocol != nullptr); + + QSignalSpy splashRequestedSpy(m_protocol, &PrelaunchSplash::splashRequested); + QVERIFY(splashRequestedSpy.isValid()); + + QSignalSpy splashCloseSpy(m_protocol, &PrelaunchSplash::splashCloseRequested); + QVERIFY(splashCloseSpy.isValid()); + } + + void cleanupTestCase() + { + m_server->deleteLater(); + m_server = nullptr; + m_protocol = nullptr; + } +}; + +QTEST_MAIN(PrelaunchSplashTest) +#include "main.moc" diff --git a/tests/test_protocol_primary-output/CMakeLists.txt b/tests/test_protocol_primary-output/CMakeLists.txt new file mode 100644 index 0000000000..8cca4e0559 --- /dev/null +++ b/tests/test_protocol_primary-output/CMakeLists.txt @@ -0,0 +1,7 @@ +# A user protocol requires a real Session. Keep the legacy build target as an +# alias to the production-fixture protocol test instead of constructing an +# unowned manager on a bare WServer. +if(TARGET test_treeland_output_manager_v2) + add_custom_target(test_protocol_primary-output + DEPENDS test_treeland_output_manager_v2) +endif() diff --git a/tests/test_protocol_shortcut/CMakeLists.txt b/tests/test_protocol_shortcut/CMakeLists.txt new file mode 100644 index 0000000000..16c407bece --- /dev/null +++ b/tests/test_protocol_shortcut/CMakeLists.txt @@ -0,0 +1,19 @@ +find_package(Qt6 REQUIRED COMPONENTS Test) + +add_executable(test_protocol_shortcut main.cpp) + +target_link_libraries(test_protocol_shortcut + PRIVATE + libtreeland + Qt::Test +) + +add_test(NAME test_protocol_shortcut COMMAND test_protocol_shortcut) + +set_property(TEST test_protocol_shortcut PROPERTY + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" +) + +set_property(TEST test_protocol_shortcut PROPERTY + TIMEOUT 3 +) diff --git a/tests/test_protocol_shortcut/main.cpp b/tests/test_protocol_shortcut/main.cpp new file mode 100644 index 0000000000..e900721a31 --- /dev/null +++ b/tests/test_protocol_shortcut/main.cpp @@ -0,0 +1,83 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "modules/shortcut/shortcutmanager.h" + +#include + +#include +#include +#include + +class ShortcutTest : public QObject +{ + Q_OBJECT + + WAYLIB_SERVER_NAMESPACE::WServer *m_server = nullptr; + +public: + ShortcutTest(QObject *parent = nullptr) + : QObject(parent) + { + } + +private Q_SLOTS: + + void initTestCase() + { + m_server = new WAYLIB_SERVER_NAMESPACE::WServer(); + } + + void testCreate() + { + QVERIFY(m_server->attach(m_server) != nullptr); + } + + void verifyShortcut() + { + auto protocol = m_server->findChild(); + QVERIFY(protocol != nullptr); + } + + // Shift+Tab's keysym is ISO_Left_Tab; Qt's QXkbCommon::keysymToQtKey() turns + // it into Key_Backtab, while bindings spell the combination "Shift+Tab". + // Both sides must normalize to one identity or the shortcut never matches. + void testBacktabNormalization_data() + { + QTest::addColumn("bindKey"); + QTest::addColumn("modifiers"); + + QTest::newRow("Shift+Tab") + << QStringLiteral("Shift+Tab") << Qt::KeyboardModifiers(Qt::ShiftModifier); + QTest::newRow("Ctrl+Shift+Tab") + << QStringLiteral("Ctrl+Shift+Tab") + << Qt::KeyboardModifiers(Qt::ControlModifier | Qt::ShiftModifier); + QTest::newRow("Alt+Shift+Tab") + << QStringLiteral("Alt+Shift+Tab") + << Qt::KeyboardModifiers(Qt::AltModifier | Qt::ShiftModifier); + } + + void testBacktabNormalization() + { + QFETCH(QString, bindKey); + QFETCH(Qt::KeyboardModifiers, modifiers); + + const int bindSide = ShortcutController::normalizedKeyCombinedFor(bindKey); + const int eventSide = + ShortcutController::normalizeKeyCombination(QKeyCombination(modifiers, Qt::Key_Backtab)) + .toCombined(); + + QVERIFY(bindSide != 0); + QCOMPARE(eventSide, bindSide); + QCOMPARE(QKeyCombination::fromCombined(bindSide).key(), Qt::Key_Tab); + } + + void cleanupTestCase() + { + m_server->deleteLater(); + m_server = nullptr; + } +}; + +QTEST_MAIN(ShortcutTest) +#include "main.moc" diff --git a/tests/test_protocol_wallpaper-color/CMakeLists.txt b/tests/test_protocol_wallpaper-color/CMakeLists.txt new file mode 100644 index 0000000000..f45c614db9 --- /dev/null +++ b/tests/test_protocol_wallpaper-color/CMakeLists.txt @@ -0,0 +1,19 @@ +find_package(Qt6 REQUIRED COMPONENTS Test) + +add_executable(test_protocol_wallpaper-color main.cpp) + +target_link_libraries(test_protocol_wallpaper-color + PRIVATE + libtreeland + Qt::Test +) + +add_test(NAME test_protocol_wallpaper-color COMMAND test_protocol_wallpaper-color) + +set_property(TEST test_protocol_wallpaper-color PROPERTY + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" +) + +set_property(TEST test_protocol_wallpaper-color PROPERTY + TIMEOUT 3 +) diff --git a/tests/test_protocol_wallpaper-color/main.cpp b/tests/test_protocol_wallpaper-color/main.cpp new file mode 100644 index 0000000000..b8e16d1cff --- /dev/null +++ b/tests/test_protocol_wallpaper-color/main.cpp @@ -0,0 +1,49 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "modules/wallpaper-color/wallpapercolorinterfacev1.h" + +#include + +#include +#include + +class WallpaperColorTest : public QObject +{ + Q_OBJECT + + WAYLIB_SERVER_NAMESPACE::WServer *m_server = nullptr; + +public: + WallpaperColorTest(QObject *WallpaperColor = nullptr) + : QObject(WallpaperColor) + { + } + +private Q_SLOTS: + + void initTestCase() + { + m_server = new WAYLIB_SERVER_NAMESPACE::WServer(); + } + + void testCreate() + { + QVERIFY(m_server->attach(m_server) != nullptr); + } + + void verifyWallpaperColor() + { + auto protocol = m_server->findChild(); + QVERIFY(protocol != nullptr); + } + + void cleanupTestCase() + { + m_server->deleteLater(); + m_server = nullptr; + } +}; + +QTEST_MAIN(WallpaperColorTest) +#include "main.moc" diff --git a/tests/test_protocol_xwindow-control/CMakeLists.txt b/tests/test_protocol_xwindow-control/CMakeLists.txt new file mode 100644 index 0000000000..3edf46a916 --- /dev/null +++ b/tests/test_protocol_xwindow-control/CMakeLists.txt @@ -0,0 +1,19 @@ +find_package(Qt6 REQUIRED COMPONENTS Test) + +add_executable(test_protocol_xwindow-control main.cpp) + +target_link_libraries(test_protocol_xwindow-control + PRIVATE + libtreeland + Qt::Test +) + +add_test(NAME test_protocol_xwindow-control COMMAND test_protocol_xwindow-control) + +set_property(TEST test_protocol_xwindow-control PROPERTY + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" +) + +set_property(TEST test_protocol_xwindow-control PROPERTY + TIMEOUT 3 +) diff --git a/tests/test_protocol_xwindow-control/main.cpp b/tests/test_protocol_xwindow-control/main.cpp new file mode 100644 index 0000000000..a862f9bd1b --- /dev/null +++ b/tests/test_protocol_xwindow-control/main.cpp @@ -0,0 +1,49 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "modules/xwindow-control/xwindowcontrolinterfacev1.h" + +#include + +#include +#include + +class XWindowControlTest : public QObject +{ + Q_OBJECT + + WAYLIB_SERVER_NAMESPACE::WServer *m_server = nullptr; + +public: + XWindowControlTest(QObject *parent = nullptr) + : QObject(parent) + { + } + +private Q_SLOTS: + + void initTestCase() + { + m_server = new WAYLIB_SERVER_NAMESPACE::WServer(); + } + + void testCreate() + { + QVERIFY(m_server->attach(m_server) != nullptr); + } + + void verifyXWindowControl() + { + auto protocol = m_server->findChild(); + QVERIFY(protocol != nullptr); + } + + void cleanupTestCase() + { + m_server->deleteLater(); + m_server = nullptr; + } +}; + +QTEST_MAIN(XWindowControlTest) +#include "main.moc" diff --git a/tests/test_treeland_debug/CMakeLists.txt b/tests/test_treeland_debug/CMakeLists.txt new file mode 100644 index 0000000000..5ff5d67635 --- /dev/null +++ b/tests/test_treeland_debug/CMakeLists.txt @@ -0,0 +1,39 @@ +find_package(Qt6 REQUIRED COMPONENTS Test Core Gui Network) + +# Reuse the extracted helpers from the treeland-debug tool. +set(debug_helpers_dir "${PROJECT_SOURCE_DIR}/tools/treeland-debug") + +add_executable(test_treeland_debug + main.cpp + "${debug_helpers_dir}/debughelpers.cpp" + "${PROJECT_SOURCE_DIR}/src/modules/resource/treelanddebugsocket.cpp" +) + +target_include_directories(test_treeland_debug PRIVATE + "${debug_helpers_dir}" + "${PROJECT_SOURCE_DIR}/src/modules/resource" +) + +# The completion scripts are hand-written per shell; the test that compares them +# with the command table reads them from the source tree. +target_compile_definitions(test_treeland_debug PRIVATE + TREELAND_DEBUG_SOURCE_DIR="${debug_helpers_dir}" +) + +target_link_libraries(test_treeland_debug + PRIVATE + Qt6::Test + Qt6::Core + Qt6::Gui + Qt6::Network +) + +add_test(NAME test_treeland_debug COMMAND test_treeland_debug) + +set_property(TEST test_treeland_debug PROPERTY + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" +) + +set_property(TEST test_treeland_debug PROPERTY + TIMEOUT 10 +) diff --git a/tests/test_treeland_debug/main.cpp b/tests/test_treeland_debug/main.cpp new file mode 100644 index 0000000000..0e5020128d --- /dev/null +++ b/tests/test_treeland_debug/main.cpp @@ -0,0 +1,2108 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "debughelpers.h" + +#include "treelanddebugsocket.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +// Unit tests for the pure-logic helpers shared by the treeland-debug tool +// (stateName, buttonCode, keyCode, saveCapture, pointToJson, rectToJson) +// plus exhaustive coverage of parseCommand() — the command recognition and +// parameter validation layer that every subcommand flows through. These do +// not require a running compositor or a Wayland connection. +class TreelandDebugTest : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void initTestCase(); + + // --- pure helpers --- + void testStateNameKnownStates(); + void testFormatDuration(); + void testOutputsLabel(); + void testStateNameUnknown(); + void testShellTypeName(); + void testFormatGeometry(); + void testButtonCodeNamed(); + void testButtonCodeRaw(); + void testButtonCodeUnknown(); + void testKeyCodeNamed(); + void testKeyCodeRaw(); + void testKeyCodeUnknown(); + void testKeyCodeCaseInsensitive(); + void testSaveCaptureExplicitPath(); + void testSaveCaptureAddsPngSuffix(); + void testSaveCaptureEmptyData(); + void testSaveCaptureAutoPath(); + void testPointToJson(); + void testRectToJson(); + void testRectsToJson(); + void testFormatRegionEmpty(); + void testFormatRegionAtLimit(); + void testFormatRegionOverLimit(); + void testParseLogLevel(); + + // --- REPL completion --- + void testCompletionCommandWords(); + void testCompletionCommandPrefix(); + void testCompletionFirstArgument(); + void testCompletionFirstArgumentPrefix(); + void testCompletionFreeFormArguments(); + void testCompletionOnlyFirstArgument(); + void testCommandNamesAcceptedByParseCommand(); + void testCompleteLineUnique(); + void testCompleteLineCommonPrefix(); + void testCompleteLineListsCandidates(); + void testCompleteLineMidLine(); + void testCompleteLineInsideWord(); + void testCompleteLineNoCandidates(); + void testCompletionScriptsMatchCommandTable(); + + // --- treeland-debug socket naming / conflict avoidance --- + void testSocketDefaultPath(); + void testDevelopmentSocketDirectoryUsesUidTemp(); + void testSocketDirs(); + void testSocketFallsBackWhenGlobalDirectoryIsNotSearchable(); + void testSocketPickFreeName(); + void testSocketPickFreeNameOccupied(); + void testSocketPickFreeNameSkipsLiveOldInstance(); + void testSocketCandidateUrls(); + void testSocketPathMatchesQt(); + void testSocketPathForUrl(); + void testSocketUrlFromEnv(); + void testSocketPublished(); + void testPublishedSocketPaths(); + void testSocketPeerText(); + void testSocketPeerTextSanitized(); + void testInstanceSocketUrls(); + void testExistingSocketUrls(); + void testSocketAccessSwitch(); + + // --- parseCommand: no-argument commands --- + void testParseTree(); + void testParseCursor(); + void testParseWindows(); + void testParseWindowMissingTarget(); + void testParseWindow(); + void testParseClients(); + void testParseIdle(); + void testParseShortcuts(); + void testParseHelp(); + void testParseShell(); + void testParseNoAuth(); + + // --- parseCommand: window control --- + void testParseActivateMissingTarget(); + void testParseActivate(); + void testParseCloseMissingTarget(); + void testParseClose(); + void testParseMinimizeMissingTarget(); + void testParseMinimize(); + void testParseMaximizeMissingTarget(); + void testParseMaximize(); + void testParseFullscreenMissingTarget(); + void testParseFullscreen(); + + // --- parseCommand: move / resize / workspace --- + void testParseMoveMissingTarget(); + void testParseMoveTooFewArgs(); + void testParseMove(); + void testParseResizeMissingTarget(); + void testParseResizeTooFewArgs(); + void testParseResize(); + void testParseWorkspaceMissingTarget(); + void testParseWorkspaceTooFewArgs(); + void testParseWorkspace(); + + // --- parseCommand: move-cursor --- + void testParseMoveCursorTooFewArgs(); + void testParseMoveCursor(); + void testParseMoveCursorNegative(); + + // --- parseCommand: event --- + void testParseEventNoSub(); + void testParseEventUnknownSub(); + void testParseEventMotionTooFewArgs(); + void testParseEventMotion(); + void testParseEventButtonTooFewArgs(); + void testParseEventButtonUnknown(); + void testParseEventButtonNamed(); + void testParseEventButtonRaw(); + void testParseEventButtonWithAction(); + void testParseEventButtonDefaultAction(); + void testParseEventKeyTooFewArgs(); + void testParseEventKeyUnknown(); + void testParseEventKeyNamed(); + void testParseEventKeyRaw(); + void testParseEventKeyWithAction(); + void testParseEventKeyDefaultAction(); + + // --- parseCommand: screenshot --- + void testParseScreenshotNoSub(); + void testParseScreenshotUnknownTarget(); + void testParseScreenshotOutputNoArgs(); + void testParseScreenshotOutputWithName(); + void testParseScreenshotOutputWithNameAndFile(); + void testParseScreenshotOutputEmptyName(); + void testParseScreenshotWindowTooFewArgs(); + void testParseScreenshotWindow(); + void testParseScreenshotWindowWithFile(); + + // --- parseCommand: live commands (top/events/watch) --- + void testParseTopDefault(); + void testParseTopCustomInterval(); + void testParseTopInvalidInterval(); + void testParseEventsDefault(); + void testParseEventsCustomInterval(); + void testParseEventsInvalidInterval(); + void testParseWatchMissingId(); + void testParseWatch(); + void testParseWatchWithInterval(); + void testParseWatchInvalidInterval(); + + // --- parseCommand: unknown command --- + void testParseUnknownCommand(); + + // --- parseCommand: listen (HTTP/WebSocket server) --- + void testParseListenDefault(); + void testParseListenCustomPort(); + void testParseListenCustomHost(); + void testParseListenCustomBoth(); + void testParseListenInvalidPortLow(); + void testParseListenInvalidPortHigh(); + void testParseListenUnknownArg(); + void testParseListenPortNoValue(); + +private: + // Only used when the machine's XDG_RUNTIME_DIR is not writable: the socket + // directory resolution reads it once per process. + QTemporaryDir m_runtimeDir; + // The global service's own debug directory; a real one is /run/treeland-debug + // and needs root, so the tests point $TREELAND_DEBUG_DIR here. + QTemporaryDir m_debugDir; +}; + +// --------------------------------------------------------------------------- +// Pure-helper tests (unchanged from original coverage) +// --------------------------------------------------------------------------- + +void TreelandDebugTest::testStateNameKnownStates() +{ + QCOMPARE(stateName(0), QStringLiteral("Normal")); + QCOMPARE(stateName(1), QStringLiteral("Maximized")); + QCOMPARE(stateName(2), QStringLiteral("Fullscreen")); + QCOMPARE(stateName(3), QStringLiteral("Tiling")); +} + +void TreelandDebugTest::testFormatDuration() +{ + QCOMPARE(formatDuration(0), QStringLiteral("0.0s")); + QCOMPARE(formatDuration(4200), QStringLiteral("4.2s")); + // 59.95s+ rounds up into the minute format instead of "60.0s". + QCOMPARE(formatDuration(59949), QStringLiteral("59.9s")); + QCOMPARE(formatDuration(59999), QStringLiteral("1m00s")); + QCOMPARE(formatDuration(61000), QStringLiteral("1m01s")); + QCOMPARE(formatDuration(3599000), QStringLiteral("59m59s")); + QCOMPARE(formatDuration(3599999), QStringLiteral("1h00m")); + QCOMPARE(formatDuration(3661000), QStringLiteral("1h01m")); +} + +void TreelandDebugTest::testOutputsLabel() +{ + // The frame-pacing output is marked with '+', which cannot be confused + // with the '*' these views use for the active window. + QCOMPARE(outputsLabel({ QStringLiteral("eDP-1") }, QStringLiteral("eDP-1"), QStringLiteral("eDP-1")), + QStringLiteral("+eDP-1")); + QCOMPARE(outputsLabel({ QStringLiteral("eDP-1"), QStringLiteral("HDMI-A-1") }, + QStringLiteral("HDMI-A-1"), QStringLiteral("eDP-1")), + QStringLiteral("eDP-1,+HDMI-A-1")); + // No known outputs: fall back to the owner output the compositor picked. + QCOMPARE(outputsLabel({}, QStringLiteral("HDMI-A-1"), QStringLiteral("eDP-1")), + QStringLiteral("eDP-1")); + // Pacing output outside the list: nothing is marked. + QCOMPARE(outputsLabel({ QStringLiteral("eDP-1"), QStringLiteral("HDMI-A-1") }, + QStringLiteral("DP-1"), QStringLiteral("eDP-1")), + QStringLiteral("eDP-1,HDMI-A-1")); +} + +void TreelandDebugTest::testStateNameUnknown() +{ + QCOMPARE(stateName(99), QStringLiteral("Unknown(99)")); + QCOMPARE(stateName(-1), QStringLiteral("Unknown(-1)")); +} + +void TreelandDebugTest::testShellTypeName() +{ + // The order is SurfaceWrapper::Type as serialised in WindowInfo::type. + QCOMPARE(shellTypeName(0), QStringLiteral("xdg-toplevel")); + QCOMPARE(shellTypeName(1), QStringLiteral("xdg-popup")); + QCOMPARE(shellTypeName(2), QStringLiteral("xwayland")); + QCOMPARE(shellTypeName(3), QStringLiteral("layer-shell")); + QCOMPARE(shellTypeName(4), QStringLiteral("input-popup")); + QCOMPARE(shellTypeName(5), QStringLiteral("lock-screen")); + QCOMPARE(shellTypeName(6), QStringLiteral("splash-screen")); + // A newer compositor may add types; an old client must still print something. + QCOMPARE(shellTypeName(7), QStringLiteral("unknown(7)")); +} + +void TreelandDebugTest::testFormatGeometry() +{ + // x11 -geometry order: WxH+X+Y. + QCOMPARE(formatGeometry(QRectF(100, 50, 800, 600)), QStringLiteral("800x600+100+50")); + QCOMPARE(formatGeometry(QRectF(0, 0, 0, 0)), QStringLiteral("0x0+0+0")); + // A window left of/above the layout origin keeps the coordinate's sign. + QCOMPARE(formatGeometry(QRectF(-10, -20, 100, 200)), QStringLiteral("100x200-10-20")); + // Fractional geometry is rounded, not printed with a decimal point. + QCOMPARE(formatGeometry(QRectF(1.4, 2.6, 10.5, 20.4)), QStringLiteral("11x20+1+3")); +} + +void TreelandDebugTest::testButtonCodeNamed() +{ + bool ok = false; + QCOMPARE(buttonCode(QStringLiteral("left"), &ok), 0x110); + QVERIFY(ok); + QCOMPARE(buttonCode(QStringLiteral("right"), &ok), 0x111); + QVERIFY(ok); + QCOMPARE(buttonCode(QStringLiteral("middle"), &ok), 0x112); + QVERIFY(ok); + // Names are case-insensitive. + QCOMPARE(buttonCode(QStringLiteral("LEFT"), &ok), 0x110); + QVERIFY(ok); +} + +void TreelandDebugTest::testButtonCodeRaw() +{ + bool ok = false; + // buttonCode passes raw codes through QString::toInt (base 10), so use + // decimal values; hex prefixes like "0x113" are not recognized here. + QCOMPARE(buttonCode(QStringLiteral("275"), &ok), 275); // 0x113 == 275 + QVERIFY(ok); + QCOMPARE(buttonCode(QStringLiteral("277"), &ok), 277); + QVERIFY(ok); +} + +void TreelandDebugTest::testButtonCodeUnknown() +{ + bool ok = true; + QCOMPARE(buttonCode(QStringLiteral("foobar"), &ok), 0); + QVERIFY(!ok); +} + +void TreelandDebugTest::testKeyCodeNamed() +{ + bool ok = false; + // keyCode() now returns Qt::Key enum values resolved via QMetaEnum. + QCOMPARE(keyCode(QStringLiteral("Escape"), &ok), static_cast(Qt::Key_Escape)); + QVERIFY(ok); + QCOMPARE(keyCode(QStringLiteral("Return"), &ok), static_cast(Qt::Key_Return)); + QVERIFY(ok); + QCOMPARE(keyCode(QStringLiteral("Space"), &ok), static_cast(Qt::Key_Space)); + QVERIFY(ok); + QCOMPARE(keyCode(QStringLiteral("Up"), &ok), static_cast(Qt::Key_Up)); + QVERIFY(ok); + QCOMPARE(keyCode(QStringLiteral("F12"), &ok), static_cast(Qt::Key_F12)); + QVERIFY(ok); +} + +void TreelandDebugTest::testKeyCodeRaw() +{ + bool ok = false; + QCOMPARE(keyCode(QStringLiteral("200"), &ok), 200); + QVERIFY(ok); +} + +void TreelandDebugTest::testKeyCodeUnknown() +{ + bool ok = true; + QCOMPARE(keyCode(QStringLiteral("nonexistent"), &ok), 0); + QVERIFY(!ok); +} + +void TreelandDebugTest::testKeyCodeCaseInsensitive() +{ + bool ok = false; + // Case-insensitive matching: "ESCAPE" and "enter" should also work. + QCOMPARE(keyCode(QStringLiteral("ESCAPE"), &ok), static_cast(Qt::Key_Escape)); + QVERIFY(ok); + QCOMPARE(keyCode(QStringLiteral("enter"), &ok), static_cast(Qt::Key_Enter)); + QVERIFY(ok); +} + +void TreelandDebugTest::testSaveCaptureExplicitPath() +{ + QTemporaryDir dir; + QVERIFY(dir.isValid()); + const QString path = dir.filePath("capture.png"); + const QByteArray data("PNG-fake-bytes"); + const QString saved = saveCapture(data, path); + QCOMPARE(saved, path); + QFile f(path); + QVERIFY(f.open(QIODevice::ReadOnly)); + QCOMPARE(f.readAll(), data); +} + +void TreelandDebugTest::testSaveCaptureAddsPngSuffix() +{ + QTemporaryDir dir; + QVERIFY(dir.isValid()); + const QString base = dir.filePath("noext"); + const QByteArray data("data"); + const QString saved = saveCapture(data, base); + QVERIFY(saved.endsWith(QStringLiteral(".png"))); + QVERIFY(QFile::exists(saved)); +} + +void TreelandDebugTest::testSaveCaptureEmptyData() +{ + QTemporaryDir dir; + QVERIFY(dir.isValid()); + const QString path = dir.filePath("empty.png"); + const QString saved = saveCapture(QByteArray(), path); + QVERIFY(saved.isEmpty()); + QVERIFY(!QFile::exists(path)); +} + +void TreelandDebugTest::testSaveCaptureAutoPath() +{ + const QByteArray data("autodata"); + const QString saved = saveCapture(data, QString()); + QVERIFY(!saved.isEmpty()); + QVERIFY(saved.startsWith(QStringLiteral("/tmp/treeland-debug-"))); + QVERIFY(saved.endsWith(QStringLiteral(".png"))); + QVERIFY(QFile::exists(saved)); + QFile::remove(saved); +} + +void TreelandDebugTest::testPointToJson() +{ + const auto obj = pointToJson(QPointF(1.5, -2.0)); + QCOMPARE(obj.value("x").toDouble(), 1.5); + QCOMPARE(obj.value("y").toDouble(), -2.0); +} + +void TreelandDebugTest::testRectToJson() +{ + const auto obj = rectToJson(QRectF(10, 20, 300, 400)); + QCOMPARE(obj.value("x").toDouble(), 10.0); + QCOMPARE(obj.value("y").toDouble(), 20.0); + QCOMPARE(obj.value("width").toDouble(), 300.0); + QCOMPARE(obj.value("height").toDouble(), 400.0); +} + +void TreelandDebugTest::testRectsToJson() +{ + // A region is a set of boxes, so it must serialise as an array of rects + // and an empty region as an empty array. + QVERIFY(rectsToJson(QRegion()).isEmpty()); + + const auto array = rectsToJson(QRegion(0, 0, 8, 8) + QRegion(20, 8, 4, 2)); + QCOMPARE(array.size(), 2); + const auto first = array.at(0).toObject(); + QCOMPARE(first.value("x").toDouble(), 0.0); + QCOMPARE(first.value("width").toDouble(), 8.0); + const auto second = array.at(1).toObject(); + QCOMPARE(second.value("x").toDouble(), 20.0); + QCOMPARE(second.value("y").toDouble(), 8.0); + QCOMPARE(second.value("height").toDouble(), 2.0); +} + +void TreelandDebugTest::testFormatRegionEmpty() +{ + // An empty region is not "no boxes to show", it is a meaningful state + // (input: accepts nothing; opaque: no opaque area declared), so it must not + // render as an empty string. + QCOMPARE(formatRegion(QRegion()), QStringLiteral("(empty)")); +} + +void TreelandDebugTest::testFormatRegionAtLimit() +{ + QRegion region; + for (int i = 0; i < 8; ++i) + region += QRect(0, i * 2, 10, 1); + const QString text = formatRegion(region); + QCOMPARE(text.count(QLatin1Char('[')), 8); + QVERIFY(!text.contains(QLatin1String("more"))); + QVERIFY(text.startsWith(QLatin1String("[0,0 10x1],[0,2 10x1]"))); +} + +void TreelandDebugTest::testFormatRegionOverLimit() +{ + QRegion region; + for (int i = 0; i < 9; ++i) + region += QRect(0, i * 2, 10, 1); + const QString text = formatRegion(region); + QCOMPARE(text.count(QLatin1Char('[')), 8); + QVERIFY(text.endsWith(QLatin1String("(+1 more)"))); +} + +void TreelandDebugTest::testParseLogLevel() +{ + bool ok = false; + QCOMPARE(parseLogLevel(QStringLiteral("debug"), &ok), LogLevel::Debug); + QVERIFY(ok); + QCOMPARE(parseLogLevel(QStringLiteral("INFO"), &ok), LogLevel::Info); + QVERIFY(ok); + QCOMPARE(parseLogLevel(QStringLiteral("warning"), &ok), LogLevel::Warning); + QVERIFY(ok); + QCOMPARE(parseLogLevel(QStringLiteral("error"), &ok), LogLevel::Error); + QVERIFY(ok); + // An unknown level is rejected so --log-level can name the alternatives. + QCOMPARE(parseLogLevel(QStringLiteral("verbose"), &ok), LogLevel::Info); + QVERIFY(!ok); + QCOMPARE(parseLogLevel(QString(), &ok), LogLevel::Info); + QVERIFY(!ok); +} + +// --------------------------------------------------------------------------- +// REPL completion +// --------------------------------------------------------------------------- + +void TreelandDebugTest::testCompletionCommandWords() +{ + // An empty line offers every command the REPL accepts. + QCOMPARE(completionCandidates({ QString() }), debugCommandNames()); + QVERIFY(debugCommandNames().contains(QStringLiteral("event"))); + QVERIFY(debugCommandNames().contains(QStringLiteral("quit"))); +} + +void TreelandDebugTest::testCompletionCommandPrefix() +{ + QCOMPARE(completionCandidates({ QStringLiteral("scr") }), + QStringList{ QStringLiteral("screenshot") }); + // Prefix matching keeps the declared order. + QCOMPARE(completionCandidates({ QStringLiteral("e") }), + (QStringList{ QStringLiteral("event"), QStringLiteral("events"), + QStringLiteral("exit") })); + QVERIFY(completionCandidates({ QStringLiteral("nosuchcommand") }).isEmpty()); +} + +void TreelandDebugTest::testCompletionFirstArgument() +{ + // A trailing space means the word being completed is empty, which offers + // the whole set for the command that has one. + QCOMPARE(completionCandidates({ QStringLiteral("event"), QString() }), + (QStringList{ QStringLiteral("motion"), QStringLiteral("button"), + QStringLiteral("key") })); + QCOMPARE(completionCandidates({ QStringLiteral("screenshot"), QString() }), + (QStringList{ QStringLiteral("output"), QStringLiteral("window") })); + QCOMPARE(completionCandidates({ QStringLiteral("debug"), QString() }), + (QStringList{ QStringLiteral("on"), QStringLiteral("off"), + QStringLiteral("status") })); + QCOMPARE(completionCandidates({ QStringLiteral("listen"), QString() }), + (QStringList{ QStringLiteral("--port"), QStringLiteral("--host") })); +} + +void TreelandDebugTest::testCompletionFirstArgumentPrefix() +{ + QCOMPARE(completionCandidates({ QStringLiteral("event"), QStringLiteral("bu") }), + QStringList{ QStringLiteral("button") }); + QVERIFY(completionCandidates({ QStringLiteral("event"), QStringLiteral("zz") }).isEmpty()); +} + +void TreelandDebugTest::testCompletionFreeFormArguments() +{ + // Window ids, coordinates and paths are not guessable, so nothing is + // offered for them -- and the second word of a command that takes none. + QVERIFY(completionCandidates({ QStringLiteral("activate"), QString() }).isEmpty()); + QVERIFY(completionCandidates({ QStringLiteral("tree"), QString() }).isEmpty()); + QVERIFY(completionCandidates({ QStringLiteral("move"), QStringLiteral("42") }).isEmpty()); +} + +void TreelandDebugTest::testCompletionOnlyFirstArgument() +{ + // Only the first argument of a command is a fixed set; a third word is a + // value (event button's action, listen's port), so nothing is offered. + QVERIFY(completionCandidates({ QStringLiteral("event"), QStringLiteral("button"), + QString() }).isEmpty()); + QVERIFY(completionCandidates({ QStringLiteral("listen"), QStringLiteral("--port"), + QStringLiteral("8080"), QString() }).isEmpty()); +} + +void TreelandDebugTest::testCommandNamesAcceptedByParseCommand() +{ + // Keep debugCommandNames() and parseCommand() in sync: every listed word is + // either a parsed command or one of the three REPL-only words. + const QStringList replOnly{ QStringLiteral("debug"), QStringLiteral("exit"), + QStringLiteral("quit") }; + for (const QString &name : debugCommandNames()) { + const ParseResult r = parseCommand(name, {}); + if (replOnly.contains(name)) { + // Not a one-shot command, so parseCommand() rejects it on purpose. + QVERIFY2(r.error.contains(QLatin1String("unknown command")), qPrintable(name)); + } else { + QVERIFY2(!r.error.contains(QLatin1String("unknown command")), qPrintable(name)); + } + } +} + +void TreelandDebugTest::testCompleteLineUnique() +{ + // A unique candidate is filled in whole and followed by a space, with the + // cursor left after it. + const CompletionEdit edit = completeLine(QStringLiteral("tre"), 3); + QCOMPARE(edit.line, QStringLiteral("tree ")); + QCOMPARE(edit.cursor, 5); + QVERIFY(edit.list.isEmpty()); +} + +void TreelandDebugTest::testCompleteLineCommonPrefix() +{ + // Several candidates insert the part they share, and nothing is listed. + const CompletionEdit edit = completeLine(QStringLiteral("eve"), 3); + QCOMPARE(edit.line, QStringLiteral("event")); + QCOMPARE(edit.cursor, 5); + QVERIFY(edit.list.isEmpty()); +} + +void TreelandDebugTest::testCompleteLineListsCandidates() +{ + // Nothing new to insert: the line stays put and the candidates come back + // for the caller to print. + const CompletionEdit edit = completeLine(QStringLiteral("e"), 1); + QCOMPARE(edit.line, QStringLiteral("e")); + QCOMPARE(edit.cursor, 1); + QCOMPARE(edit.list, (QStringList{ QStringLiteral("event"), QStringLiteral("events"), + QStringLiteral("exit") })); +} + +void TreelandDebugTest::testCompleteLineMidLine() +{ + // The word before the cursor is the one completed; the rest of the line is + // kept, and no second space is added before it. + const CompletionEdit edit = completeLine(QStringLiteral("screenshot wi 42"), 13); + QCOMPARE(edit.line, QStringLiteral("screenshot window 42")); + QCOMPARE(edit.cursor, 17); + QVERIFY(edit.list.isEmpty()); +} + +void TreelandDebugTest::testCompleteLineInsideWord() +{ + // Completing in the middle of a word would insert a longer candidate before + // the rest of it and split the word in two, so it leaves the line alone. + const CompletionEdit edit = completeLine(QStringLiteral("eve"), 1); + QCOMPARE(edit.line, QStringLiteral("eve")); + QCOMPARE(edit.cursor, 1); + QVERIFY(edit.list.isEmpty()); +} + +void TreelandDebugTest::testCompleteLineNoCandidates() +{ + // A free-form argument and an unknown word both leave the line untouched. + for (const QString &line : { QStringLiteral("activate "), QStringLiteral("zzz") }) { + const CompletionEdit edit = completeLine(line, int(line.size())); + QCOMPARE(edit.line, line); + QCOMPARE(edit.cursor, int(line.size())); + QVERIFY(edit.list.isEmpty()); + } +} + +// --------------------------------------------------------------------------- +// Shell completion scripts vs. the command table +// --------------------------------------------------------------------------- + +namespace { + +// completions/ spells the command table out once per shell, in that shell's own +// syntax, so each file needs its own reader. The test below compares what they +// list with debugCommandNames()/completionCandidates(), so adding a command or a +// first argument without updating the scripts fails here instead of drifting +// silently. +struct ScriptCompletions +{ + QStringList commands; + QHash firstArguments; +}; + +QStringList matches(const QRegularExpression ®ex, const QString &text, int group) +{ + QStringList found; + auto it = regex.globalMatch(text); + while (it.hasNext()) + found.append(it.next().captured(group)); + return found; +} + +QStringList words(const QString &text) +{ + return text.split(QRegularExpression(QStringLiteral("\\s+")), Qt::SkipEmptyParts); +} + +ScriptCompletions bashCompletions(const QString &script) +{ + ScriptCompletions result; + // _treeland_debug_commands='tree cursor ...' + const auto commands = QRegularExpression(QStringLiteral("_treeland_debug_commands='([^']*)'")); + // event) echo 'motion button key' ;; + const auto firstArguments = QRegularExpression( + QStringLiteral("^\\s*([a-z][a-z-]*)\\) echo '([^']*)'"), + QRegularExpression::MultilineOption); + + const auto commandMatch = commands.match(script); + if (commandMatch.hasMatch()) + result.commands = words(commandMatch.captured(1)); + auto it = firstArguments.globalMatch(script); + while (it.hasNext()) { + const auto match = it.next(); + result.firstArguments.insert(match.captured(1), words(match.captured(2))); + } + return result; +} + +ScriptCompletions zshCompletions(const QString &script) +{ + ScriptCompletions result; + // commands=( 'tree:Print the complete window tree' ... ) + result.commands = matches(QRegularExpression(QStringLiteral("^\\s*'([a-z][a-z-]*):"), + QRegularExpression::MultilineOption), + script, 1); + // event) _values 'event' motion button key ;; + auto values = QRegularExpression( + QStringLiteral("^\\s*([a-z][a-z-]*)\\) _values '[^']*' ([^;]*);;"), + QRegularExpression::MultilineOption).globalMatch(script); + while (values.hasNext()) { + const auto match = values.next(); + result.firstArguments.insert(match.captured(1), words(match.captured(2))); + } + // listen) _arguments '--port[port to bind]:port' '--host[address to bind]:address' ;; + auto options = QRegularExpression(QStringLiteral("^\\s*([a-z][a-z-]*)\\) _arguments (.*);;"), + QRegularExpression::MultilineOption).globalMatch(script); + while (options.hasNext()) { + const auto match = options.next(); + result.firstArguments.insert( + match.captured(1), + matches(QRegularExpression(QStringLiteral("'(--[a-z-]+)")), match.captured(2), 1)); + } + return result; +} + +ScriptCompletions fishCompletions(const QString &script) +{ + ScriptCompletions result; + result.commands = matches( + QRegularExpression(QStringLiteral("-n '__fish_use_subcommand' -a ([a-z][a-z-]*)")), script, 1); + // -a 'motion button key' + auto values = QRegularExpression( + QStringLiteral("-n '__fish_seen_subcommand_from ([a-z][a-z-]*)' -a '([^']*)'")) + .globalMatch(script); + while (values.hasNext()) { + const auto match = values.next(); + result.firstArguments.insert(match.captured(1), words(match.captured(2))); + } + // listen's flags are fish options (-l port), i.e. the same word --port. + auto options = QRegularExpression( + QStringLiteral("-n '__fish_seen_subcommand_from ([a-z][a-z-]*)' -l ([a-z-]+)")) + .globalMatch(script); + while (options.hasNext()) { + const auto match = options.next(); + result.firstArguments[match.captured(1)].append(QStringLiteral("--") + match.captured(2)); + } + return result; +} + +// "cmd: a b c" per command, sorted, so a mismatch prints something readable. +QStringList describe(const QHash &firstArguments) +{ + QStringList lines; + for (auto it = firstArguments.cbegin(); it != firstArguments.cend(); ++it) + lines.append(it.key() + QStringLiteral(": ") + it.value().join(QLatin1Char(' '))); + lines.sort(); + return lines; +} + +} // namespace + +void TreelandDebugTest::testCompletionScriptsMatchCommandTable() +{ + // The REPL-only words are not one-shot commands, so the shell scripts leave + // them out on purpose (see completions/treeland-debug). + QStringList expectedCommands = debugCommandNames(); + expectedCommands.removeAll(QStringLiteral("exit")); + expectedCommands.removeAll(QStringLiteral("quit")); + + QHash expectedFirstArguments; + for (const QString &command : debugCommandNames()) { + const QStringList candidates = completionCandidates({ command, QString() }); + if (!candidates.isEmpty()) + expectedFirstArguments.insert(command, candidates); + } + + struct Script + { + const char *file; + ScriptCompletions (*read)(const QString &); + }; + const Script scripts[] = { + { "treeland-debug", &bashCompletions }, + { "_treeland-debug", &zshCompletions }, + { "treeland-debug.fish", &fishCompletions }, + }; + + for (const Script &script : scripts) { + const QString path = QStringLiteral(TREELAND_DEBUG_SOURCE_DIR "/completions/") + + QString::fromLatin1(script.file); + QFile file(path); + QVERIFY2(file.open(QIODevice::ReadOnly | QIODevice::Text), path.toUtf8().constData()); + const ScriptCompletions parsed = script.read(QString::fromUtf8(file.readAll())); + QVERIFY2(!parsed.commands.isEmpty(), script.file); + QCOMPARE(parsed.commands, expectedCommands); + QCOMPARE(describe(parsed.firstArguments), describe(expectedFirstArguments)); + } +} + +// --------------------------------------------------------------------------- +// treeland-debug socket naming / conflict avoidance +// --------------------------------------------------------------------------- + +void TreelandDebugTest::initTestCase() +{ + // Keep socket tests off the machine's live debug directories. + QVERIFY(m_debugDir.isValid()); + QVERIFY(qputenv("TREELAND_DEBUG_DIR", m_debugDir.path().toLocal8Bit())); + + if (treelandDebugSocketDir().isEmpty()) { + QVERIFY(m_runtimeDir.isValid()); + QVERIFY(qputenv("XDG_RUNTIME_DIR", m_runtimeDir.path().toLocal8Bit())); + } + QVERIFY(!treelandDebugSocketDir().isEmpty()); +} + +void TreelandDebugTest::testSocketDefaultPath() +{ + // The socket is an absolute path in its selected dedicated directory, not a + // bare name resolved against the client's potentially different TMPDIR. + const QString dir = treelandDebugSocketDir(); + const QString name = treelandDebugDefaultSocketName(); + QVERIFY(!name.isEmpty()); + const QString path = dir + QLatin1Char('/') + name; + QCOMPARE(QFileInfo(path).absolutePath(), dir); + QCOMPARE(treelandDebugSocketPath(path), path); + QCOMPARE(treelandDebugSocketPathForUrl(QStringLiteral("local:") + path), path); +} + +void TreelandDebugTest::testDevelopmentSocketDirectoryUsesUidTemp() +{ +#ifdef TREELAND_DEBUG_DEV_BUILD + const QByteArray savedOverride = qgetenv("TREELAND_DEBUG_DIR"); + qunsetenv("TREELAND_DEBUG_DIR"); + const QString expected = + QStringLiteral("/tmp/treeland-debug-%1").arg(static_cast(::geteuid())); + const QString dir = treelandDebugSocketDir(); + const QStringList dirs = treelandDebugSocketDirs(); + const QStringList urls = treelandDebugCandidateSocketUrls(); + struct stat st {}; + const bool statOk = ::lstat(QFile::encodeName(expected).constData(), &st) == 0; + const QString socketPath = + expected + QStringLiteral("/dev-access-test-%1").arg(::getpid()); + QFile socket(socketPath); + const bool fileCreated = socket.open(QIODevice::WriteOnly); + if (fileCreated) + socket.close(); + const bool opened = fileCreated && treelandDebugSetSocketAccess(socketPath, true); + struct stat socketSt {}; + const bool socketStatOk = ::stat(QFile::encodeName(socketPath).constData(), &socketSt) == 0; + struct stat dirSt {}; + const bool dirStatOk = ::stat(QFile::encodeName(expected).constData(), &dirSt) == 0; + const bool sealed = opened && treelandDebugSetSocketAccess(socketPath, false); + QFile::remove(socketPath); + if (savedOverride.isEmpty()) + qunsetenv("TREELAND_DEBUG_DIR"); + else + qputenv("TREELAND_DEBUG_DIR", savedOverride); + + QCOMPARE(dir, expected); + QVERIFY(statOk); + QVERIFY(S_ISDIR(st.st_mode)); + QCOMPARE(st.st_uid, ::geteuid()); + QCOMPARE(st.st_mode & 0777, 0700); + QVERIFY(fileCreated); + QVERIFY(opened); + QVERIFY(socketStatOk); + QCOMPARE(socketSt.st_mode & 0777, 0600); + QVERIFY(dirStatOk); + QCOMPARE(dirSt.st_mode & 0777, 0700); + QVERIFY(sealed); + QCOMPARE(dirs.first(), expected); + QVERIFY(urls.first().startsWith(QStringLiteral("local:") + expected + QLatin1Char('/'))); + QVERIFY(urls.first().endsWith(treelandDebugDefaultSocketName())); + QVERIFY(urls.last().endsWith(treelandDebugReleaseSocketName())); +#else + QSKIP("Development socket path is only used by Debug builds"); +#endif +} + +void TreelandDebugTest::testSocketFallsBackWhenGlobalDirectoryIsNotSearchable() +{ + const QByteArray savedMode = qgetenv("TREELAND_RUN_MODE"); + const QByteArray savedRuntime = qgetenv("XDG_RUNTIME_DIR"); + const QFile::Permissions originalPermissions = QFileInfo(m_debugDir.path()).permissions(); + QVERIFY(m_runtimeDir.isValid()); + QVERIFY(qputenv("XDG_RUNTIME_DIR", m_runtimeDir.path().toLocal8Bit())); + QVERIFY(QFile::setPermissions(m_debugDir.path(), + QFile::ReadOwner | QFile::WriteOwner)); + qunsetenv("TREELAND_RUN_MODE"); + + // The fixture has owner read/write but no execute bits. Check the mode as + // well as QFileInfo's effective access result, which differs when run as root. + const QString selectedDir = treelandDebugSocketDir(); + + QVERIFY(QFile::setPermissions(m_debugDir.path(), originalPermissions)); + if (savedRuntime.isEmpty()) + qunsetenv("XDG_RUNTIME_DIR"); + else + qputenv("XDG_RUNTIME_DIR", savedRuntime); + if (savedMode.isEmpty()) + qunsetenv("TREELAND_RUN_MODE"); + else + qputenv("TREELAND_RUN_MODE", savedMode); + + QCOMPARE(selectedDir, m_runtimeDir.path()); + + QVERIFY(QFile::setPermissions(m_debugDir.path(), originalPermissions)); + if (savedRuntime.isEmpty()) + qunsetenv("XDG_RUNTIME_DIR"); + else + qputenv("XDG_RUNTIME_DIR", savedRuntime); + if (savedMode.isEmpty()) + qunsetenv("TREELAND_RUN_MODE"); + else + qputenv("TREELAND_RUN_MODE", savedMode); +} +void TreelandDebugTest::testSocketDirs() +{ + const QByteArray savedRuntime = qgetenv("XDG_RUNTIME_DIR"); + QVERIFY(m_runtimeDir.isValid()); + QVERIFY(qputenv("XDG_RUNTIME_DIR", m_runtimeDir.path().toLocal8Bit())); + + // This process' own dev/runtime directories come first, then the shared + // global and legacy locations. + const QStringList dirs = treelandDebugSocketDirs(); + QVERIFY(!dirs.isEmpty()); + QCOMPARE(dirs.first(), treelandDebugSocketDir()); + QCOMPARE(dirs.first(), m_debugDir.path()); + QVERIFY(dirs.contains(treelandDebugGlobalSocketDir())); + QVERIFY(dirs.contains(QStringLiteral("/run/treeland"))); + QVERIFY(QFileInfo(treelandDebugSocketDir()).isDir()); + QCOMPARE(dirs.size(), QSet(dirs.begin(), dirs.end()).size()); + for (const QString &dir : dirs) + QVERIFY(dir.startsWith(QLatin1Char('/'))); +#ifdef TREELAND_DEBUG_DEV_BUILD + QVERIFY(dirs.contains(m_runtimeDir.path())); + for (const QString &dir : dirs) { + if (dir.startsWith(QStringLiteral("/run/user/"))) + QVERIFY(dir == m_runtimeDir.path()); + } +#endif + + if (savedRuntime.isEmpty()) + qunsetenv("XDG_RUNTIME_DIR"); + else + qputenv("XDG_RUNTIME_DIR", savedRuntime); + + // A session instance uses its own runtime directory; Qt's temp fallback is + // rejected because publishing there would put the socket back in /tmp. + const QByteArray savedMode = qgetenv("TREELAND_RUN_MODE"); + qputenv("TREELAND_RUN_MODE", "user"); + QCOMPARE(treelandDebugSocketDir(), savedRuntime); + qunsetenv("XDG_RUNTIME_DIR"); + QVERIFY(treelandDebugSocketDir().isEmpty()); + QVERIFY(qputenv("XDG_RUNTIME_DIR", savedRuntime)); + QCOMPARE(treelandDebugSocketDir(), savedRuntime); + if (savedMode.isEmpty()) + qunsetenv("TREELAND_RUN_MODE"); + else + qputenv("TREELAND_RUN_MODE", savedMode); + QCOMPARE(treelandDebugSocketDir(), m_debugDir.path()); +} + +void TreelandDebugTest::testSocketPickFreeName() +{ + // Free base → the base path itself, lock held. Use a PID-qualified name so + // parallel ctest runs don't collide. + const QString name = QStringLiteral("test.treeland.debug.socket.free.%1").arg(::getpid()); + const QString base = treelandDebugSocketDir() + QLatin1Char('/') + name; + QLocalServer::removeServer(base); + + TreelandDebugSocketLock lock; + QCOMPARE(treelandDebugPickFreeSocketName(lock, base), base); + QVERIFY(lock.isHeld()); + // Lock released on scope exit → lock file unlinked. + + // A bare name is not a socket path any more; the caller must resolve it. + TreelandDebugSocketLock bareLock; + QVERIFY(treelandDebugPickFreeSocketName(bareLock, name).isEmpty()); + QVERIFY(!bareLock.isHeld()); +} + +void TreelandDebugTest::testSocketPickFreeNameOccupied() +{ + // Occupied base → numeric suffix, and the occupied name is untouched. + const QString name = QStringLiteral("test.treeland.debug.socket.occupied.%1").arg(::getpid()); + const QString base = treelandDebugSocketDir() + QLatin1Char('/') + name; + const QString suffix = base + QStringLiteral("-1"); + QLocalServer::removeServer(base); + QLocalServer::removeServer(suffix); + + // Occupy the base name by holding its lock. + TreelandDebugSocketLock holder; + QVERIFY(holder.tryAcquire(base)); + + TreelandDebugSocketLock lock; + QCOMPARE(treelandDebugPickFreeSocketName(lock, base), suffix); + QVERIFY(lock.isHeld()); + // Both locks released on scope exit → lock files unlinked. +} + +void TreelandDebugTest::testSocketPickFreeNameSkipsLiveOldInstance() +{ + // An instance may listen on the base socket WITHOUT holding a flock lock + // file. The picker must not clobber it (removeServer would delete the live + // socket path) — it should skip the live name and take a suffix instead. + const QString name = QStringLiteral("test.treeland.debug.socket.live.%1").arg(::getpid()); + const QString base = treelandDebugSocketDir() + QLatin1Char('/') + name; + QLocalServer::removeServer(base); + + QLocalServer server; + server.setSocketOptions(QLocalServer::UserAccessOption); + QVERIFY(server.listen(base)); + // Discard the brief probe connections so they don't queue up. + connect(&server, &QLocalServer::newConnection, &server, + [&server]() { delete server.nextPendingConnection(); }); + + TreelandDebugSocketLock lock; + // base is live (server listening) but has no lock file -> must skip. + QCOMPARE(treelandDebugPickFreeSocketName(lock, base), + base + QStringLiteral("-1")); + QVERIFY(lock.isHeld()); + + server.close(); + QLocalServer::removeServer(base); +} + +void TreelandDebugTest::testSocketCandidateUrls() +{ + // Debug builds probe the dev socket in every directory first, then preserve + // the existing release fallback. Release builds only probe release sockets. + const auto urls = treelandDebugCandidateSocketUrls(); + QVERIFY(!urls.isEmpty()); + + // Every candidate must be a local: URL with an absolute path, so it does + // not depend on the client's temp or runtime directory. + const QStringList dirs = treelandDebugSocketDirs(); + for (const auto &u : urls) { + QVERIFY(u.startsWith(QStringLiteral("local:/"))); + bool inKnownDir = false; + for (const auto &dir : dirs) + inKnownDir = inKnownDir || u.startsWith(QStringLiteral("local:") + dir + QLatin1Char('/')); + QVERIFY(inKnownDir); + } + +#ifdef TREELAND_DEBUG_DEV_BUILD + // Debug build: the dev socket in every directory, then the release socket. + QCOMPARE(urls.size(), 2 * dirs.size()); + QVERIFY(urls.at(0).endsWith(treelandDebugDefaultSocketName())); + QVERIFY(urls.at(0).contains(QStringLiteral("debug-dev"))); + QVERIFY(urls.last().endsWith(treelandDebugReleaseSocketName())); +#else + // Release build: only the release socket. + QCOMPARE(urls.size(), dirs.size()); + QVERIFY(urls.first().endsWith(treelandDebugReleaseSocketName())); +#endif +} + +void TreelandDebugTest::testSocketPathMatchesQt() +{ + // Our own URLs carry the absolute path, which Qt uses as-is -- so the + // chmod() in release builds hits the socket the host actually bound. + const QString name = QStringLiteral("test.treeland.debug.socket.path.%1").arg(::getpid()); + const QString path = treelandDebugSocketDir() + QLatin1Char('/') + name; + QLocalServer::removeServer(path); + QLocalServer server; + QVERIFY(server.listen(path)); + QCOMPARE(treelandDebugSocketPath(path), server.fullServerName()); + QVERIFY(treelandDebugSocketPublished(QStringLiteral("local:") + path)); + server.close(); + QLocalServer::removeServer(path); + + // A hand-written bare name keeps Qt's rule (QDir::tempPath()), so the + // diagnostics inspect the same file Qt would connect to. + QLocalServer::removeServer(name); + QLocalServer bareServer; + QVERIFY(bareServer.listen(name)); + QCOMPARE(treelandDebugSocketPath(name), bareServer.fullServerName()); + QCOMPARE(treelandDebugSocketPath(name), + QDir::cleanPath(QDir::tempPath()) + QLatin1Char('/') + name); + bareServer.close(); + QLocalServer::removeServer(name); +} + +void TreelandDebugTest::testSocketPathForUrl() +{ + // A bare name resolves like Qt does (temp dir); absolute paths are kept, + // non-local URLs have no socket file. + const QString bare = treelandDebugSocketPathForUrl(QStringLiteral("local:foo.debug")); + QCOMPARE(bare, QDir::cleanPath(QDir::tempPath()) + QStringLiteral("/foo.debug")); + QCOMPARE(treelandDebugSocketPathForUrl(QStringLiteral("local:/run/foo.debug")), + QStringLiteral("/run/foo.debug")); + QVERIFY(treelandDebugSocketPathForUrl(QStringLiteral("tcp://127.0.0.1:1234")).isEmpty()); + QVERIFY(treelandDebugSocketPathForUrl(QStringLiteral("local:")).isEmpty()); +} + +void TreelandDebugTest::testSocketUrlFromEnv() +{ + // $TREELAND_DEBUG_SOCKET lets a caller name the socket without a flag (the + // flag itself wins, the probing below is the last resort): a plain path or a + // bare name means a local socket, anything with a scheme is used verbatim. + const QByteArray saved = qgetenv("TREELAND_DEBUG_SOCKET"); + qunsetenv("TREELAND_DEBUG_SOCKET"); + QVERIFY(treelandDebugSocketUrlFromEnv().isEmpty()); + + const QString path = treelandDebugSocketDir() + QStringLiteral("/env.sock"); + QVERIFY(qputenv("TREELAND_DEBUG_SOCKET", path.toLocal8Bit())); + QCOMPARE(treelandDebugSocketUrlFromEnv(), QStringLiteral("local:") + path); + + QVERIFY(qputenv("TREELAND_DEBUG_SOCKET", "env.sock")); + QCOMPARE(treelandDebugSocketUrlFromEnv(), QStringLiteral("local:env.sock")); + + QVERIFY(qputenv("TREELAND_DEBUG_SOCKET", "local:env.sock")); + QCOMPARE(treelandDebugSocketUrlFromEnv(), QStringLiteral("local:env.sock")); + + QVERIFY(qputenv("TREELAND_DEBUG_SOCKET", "tcp://127.0.0.1:1234")); + QCOMPARE(treelandDebugSocketUrlFromEnv(), QStringLiteral("tcp://127.0.0.1:1234")); + + if (saved.isEmpty()) + qunsetenv("TREELAND_DEBUG_SOCKET"); + else + qputenv("TREELAND_DEBUG_SOCKET", saved); +} + +void TreelandDebugTest::testSocketPublished() +{ + // A published socket (or its numeric-suffixed variant) is how the client + // tells that the debug remote source already exists, so it must not report + // a missing socket as published. Only real sockets count: a plain file at + // the name is not a debug channel. PID-qualified names keep parallel ctest + // runs apart. + const QString name = QStringLiteral("test.treeland.debug.published.%1").arg(::getpid()); + const QString base = treelandDebugSocketDir() + QLatin1Char('/') + name; + const QString url = QStringLiteral("local:") + base; + QLocalServer::removeServer(base); + QVERIFY(!treelandDebugSocketPublished(url)); + + QLocalServer server; + QVERIFY(server.listen(base)); + QVERIFY(treelandDebugSocketPublished(url)); + server.close(); + QLocalServer::removeServer(base); + + QFile plainFile(base); + QVERIFY(plainFile.open(QIODevice::WriteOnly)); + plainFile.close(); + QVERIFY(!treelandDebugSocketPublished(url)); + QVERIFY(plainFile.remove()); + + QLocalServer suffixed; + QVERIFY(suffixed.listen(base + QStringLiteral("-1"))); + QVERIFY(treelandDebugSocketPublished(url)); + suffixed.close(); + QLocalServer::removeServer(base + QStringLiteral("-1")); + QVERIFY(!treelandDebugSocketPublished(url)); +} + +void TreelandDebugTest::testPublishedSocketPaths() +{ + // The client reports *which* sockets it found, so suffix handling matters: + // only "-" belongs to this name, only real sockets count, and + // several hits must all be reported instead of picking one (that is how the + // error message ends up naming the wrong reason). + const QString name = QStringLiteral("test.treeland.debug.paths.%1").arg(::getpid()); + const QString base = treelandDebugSocketDir() + QLatin1Char('/') + name; + const QString url = QStringLiteral("local:") + base; + + QVERIFY(treelandDebugPublishedSocketPaths(url).isEmpty()); + + QLocalServer exact; + QVERIFY(exact.listen(base)); + QCOMPARE(treelandDebugPublishedSocketPaths(url), QStringList{ base }); + exact.close(); + QLocalServer::removeServer(base); + QVERIFY(treelandDebugPublishedSocketPaths(url).isEmpty()); + + // Several numeric siblings are all reported, whatever order the directory + // returns them in. + QLocalServer second; + QLocalServer tenth; + QVERIFY(second.listen(base + QStringLiteral("-2"))); + QVERIFY(tenth.listen(base + QStringLiteral("-10"))); + QStringList paths = treelandDebugPublishedSocketPaths(url); + paths.sort(); + QStringList expected{ base + QStringLiteral("-10"), base + QStringLiteral("-2") }; + expected.sort(); + QCOMPARE(paths, expected); + + // The other build type's socket ("-dev"), non-numeric suffixes and + // plain files are not this name's sockets. + QLocalServer otherBuild; + QVERIFY(otherBuild.listen(base + QStringLiteral("-dev"))); + QFile plainFile(base + QStringLiteral("-1.bak")); + QVERIFY(plainFile.open(QIODevice::WriteOnly)); + plainFile.close(); + QFile trailingGarbage(base + QStringLiteral("-1bak")); + QVERIFY(trailingGarbage.open(QIODevice::WriteOnly)); + trailingGarbage.close(); + paths = treelandDebugPublishedSocketPaths(url); + paths.sort(); + QCOMPARE(paths, expected); + + second.close(); + tenth.close(); + otherBuild.close(); + QLocalServer::removeServer(base + QStringLiteral("-2")); + QLocalServer::removeServer(base + QStringLiteral("-10")); + QLocalServer::removeServer(base + QStringLiteral("-dev")); + QVERIFY(QFile::remove(base + QStringLiteral("-1.bak"))); + QVERIFY(QFile::remove(base + QStringLiteral("-1bak"))); + QVERIFY(treelandDebugPublishedSocketPaths(url).isEmpty()); +} + +void TreelandDebugTest::testSocketPeerText() +{ + // A connect failure that reached the socket names the process on the other + // end of it, from the kernel's SO_PEERCRED -- not this process's own + // credentials. The listener therefore lives in a child process: an + // implementation that reported its own pid/uid would fail here. + const QString name = QStringLiteral("test.treeland.debug.peer.%1").arg(::getpid()); + const QByteArray path = QFile::encodeName(treelandDebugSocketPath(name)); + sockaddr_un address {}; + address.sun_family = AF_UNIX; + QVERIFY(path.size() < static_cast(sizeof(address.sun_path))); + ::memcpy(address.sun_path, path.constData(), size_t(path.size())); + + // fork() rather than a helper binary: the child only makes raw socket calls + // and _exit()s, so no Qt state is touched on that side of the fork. + const pid_t child = ::fork(); + QVERIFY(child >= 0); + if (child == 0) { + const int listener = ::socket(AF_UNIX, SOCK_STREAM, 0); + if (listener < 0) + ::_exit(1); + ::unlink(address.sun_path); + if (::bind(listener, reinterpret_cast(&address), sizeof(address)) != 0 + || ::listen(listener, 1) != 0) { + ::_exit(1); + } + ::accept(listener, nullptr, nullptr); // the parent connects next + ::_exit(0); + } + + QLocalSocket client; + client.connectToServer(name); + const bool connected = client.waitForConnected(2000); + + const QString text = treelandDebugSocketPeerText(client); + if (connected) { + QVERIFY2(text.startsWith(QStringLiteral("pid %1 ").arg(child)), qPrintable(text)); + QVERIFY2(!text.startsWith(QStringLiteral("pid %1 ").arg(::getpid())), qPrintable(text)); + QVERIFY2(text.contains(QStringLiteral("uid %1").arg(::getuid())), qPrintable(text)); + } else { + QVERIFY(!treelandDebugSocketPeerText(client).startsWith( + QStringLiteral("pid %1 ").arg(::getpid()))); + } + + // A socket that is not connected has no peer to report. + QLocalSocket idle; + QVERIFY(treelandDebugSocketPeerText(idle).isEmpty()); + + client.close(); + ::kill(child, SIGKILL); + ::waitpid(child, nullptr, 0); + ::unlink(address.sun_path); +} + +void TreelandDebugTest::testSocketPeerTextSanitized() +{ + // The peer names itself: control bytes in /proc//comm must not reach the + // terminal through the diagnostic, or a process owning the socket could + // rewrite it. This process is a convenient peer to impersonate. + QFile rename(QStringLiteral("/proc/self/comm")); + if (!rename.open(QIODevice::ReadOnly)) + QSKIP("cannot read this process's name"); + const QByteArray original = rename.readAll().trimmed(); + rename.close(); + if (!rename.open(QIODevice::WriteOnly)) + QSKIP("cannot rename this process"); + rename.write(QByteArray("ev\x1b[2Jil\x7f\x9b")); + rename.close(); + + const QString name = QStringLiteral("test.treeland.debug.peer.evil.%1").arg(::getpid()); + QLocalServer::removeServer(name); + QLocalServer server; + QVERIFY(server.listen(name)); + QLocalSocket client; + client.connectToServer(name); + QVERIFY(client.waitForConnected(1000)); + + const QString text = treelandDebugSocketPeerText(client); + QVERIFY2(!text.contains(QChar(0x1b)), qPrintable(text)); + QVERIFY2(!text.contains(QChar(0x7f)), qPrintable(text)); + // The C1 block: a byte 0x9b becomes U+009B through fromLatin1(), which + // terminals that decode C1 still act on. + QVERIFY2(!text.contains(QChar(0x9b)), qPrintable(text)); + QVERIFY2(text.contains(QStringLiteral("(ev?[2Jil\?\?)")), qPrintable(text)); + + client.close(); + server.close(); + QLocalServer::removeServer(name); + + QFile restore(QStringLiteral("/proc/self/comm")); + if (restore.open(QIODevice::WriteOnly)) + restore.write(original); +} + +void TreelandDebugTest::testInstanceSocketUrls() +{ + // A treeland that finds its base name taken publishes "-". The + // client must try those too, keeping the base preference order, or a foreign + // socket on the base name makes it report a failure while an instance of its + // own build is answering. + const QString name = QStringLiteral("test.treeland.debug.urls.%1").arg(::getpid()); + const QString url = QStringLiteral("local:") + name; + const QString other = QStringLiteral("local:test.treeland.debug.urls.other"); + + QLocalServer::removeServer(name); + QCOMPARE(treelandDebugInstanceSocketUrls({ url, other }), (QStringList{ url, other })); + + // The suffixed instance follows its own candidate, so the candidate order + // (which build type is preferred) still decides before the base name does. + QLocalServer suffixed; + QVERIFY(suffixed.listen(name + QStringLiteral("-2"))); + QCOMPARE(treelandDebugInstanceSocketUrls({ url, other }), + (QStringList{ url, url + QStringLiteral("-2"), other })); + + suffixed.close(); + QLocalServer::removeServer(name + QStringLiteral("-2")); + QCOMPARE(treelandDebugInstanceSocketUrls({ url, other }), (QStringList{ url, other })); + + // An absolute candidate keeps its directory: a bare name would be resolved + // under QDir::tempPath() instead, pointing at a different socket. + QTemporaryDir absoluteDir; + QVERIFY(absoluteDir.isValid()); + const QString absoluteBase = absoluteDir.filePath(QStringLiteral("abs.debug")); + QLocalServer absolute; + QVERIFY(absolute.listen(absoluteBase)); + QLocalServer absoluteSuffixed; + QVERIFY(absoluteSuffixed.listen(absoluteBase + QStringLiteral("-3"))); + QCOMPARE(treelandDebugInstanceSocketUrls({ QStringLiteral("local:") + absoluteBase }), + (QStringList{ QStringLiteral("local:") + absoluteBase, + QStringLiteral("local:") + absoluteBase + QStringLiteral("-3") })); + absoluteSuffixed.close(); + absolute.close(); + QLocalServer::removeServer(absoluteBase + QStringLiteral("-3")); + QLocalServer::removeServer(absoluteBase); +} + +void TreelandDebugTest::testExistingSocketUrls() +{ + // Probing a candidate whose socket file is absent can only spend a probe + // timeout, so callers filter those out -- unless nothing is left, in which case + // the full list is kept so the failure can name every place that was searched. + const QString name = QStringLiteral("test.treeland.debug.existing.%1").arg(::getpid()); + const QString url = QStringLiteral("local:") + name; + const QString absent = QStringLiteral("local:test.treeland.debug.existing.absent"); + + QLocalServer::removeServer(name); + QCOMPARE(treelandDebugExistingSocketUrls({ url, absent }), (QStringList{ url, absent })); + + QLocalServer server; + QVERIFY(server.listen(name)); + QCOMPARE(treelandDebugExistingSocketUrls({ absent, url }), QStringList{ url }); + + server.close(); + QLocalServer::removeServer(name); + QCOMPARE(treelandDebugExistingSocketUrls({ url, absent }), (QStringList{ url, absent })); +} + +void TreelandDebugTest::testSocketAccessSwitch() +{ +#ifdef TREELAND_DEBUG_DEV_BUILD + // A Debug dev socket is owner-only; same-UID access works without polkit. +#else + // Release no-auth opens only the global service socket and widens its + // dedicated directory so other local users can reach it. +#endif + const QString path = treelandDebugSocketDir() + QStringLiteral("/debug.socket"); + QFile socket(path); + QVERIFY(socket.open(QIODevice::WriteOnly)); + socket.close(); + QCOMPARE(::chmod(QFile::encodeName(path).constData(), 0), 0); + const QString neighbour = treelandDebugSocketDir() + QStringLiteral("/neighbour.socket"); + QFile neighbourSocket(neighbour); + QVERIFY(neighbourSocket.open(QIODevice::WriteOnly)); + neighbourSocket.close(); + QCOMPARE(::chmod(QFile::encodeName(neighbour).constData(), 0755), 0); + + const auto modeOf = [](const QString &file) { + struct stat st {}; + return ::stat(QFile::encodeName(file).constData(), &st) == 0 ? (st.st_mode & 07777) : 0u; + }; + + QVERIFY(treelandDebugSetSocketAccess(path, true)); +#ifdef TREELAND_DEBUG_DEV_BUILD + QCOMPARE(modeOf(path), 0600u); + QCOMPARE(modeOf(treelandDebugSocketDir()), 0700u); +#else + QCOMPARE(modeOf(path), 0666u); + QCOMPARE(modeOf(treelandDebugSocketDir()), 0711u); +#endif + + QVERIFY(treelandDebugSetSocketAccess(path, true)); +#ifdef TREELAND_DEBUG_DEV_BUILD + QCOMPARE(modeOf(treelandDebugSocketDir()), 0700u); +#else + QCOMPARE(modeOf(treelandDebugSocketDir()), 0711u); +#endif + + QVERIFY(treelandDebugSetSocketAccess(path, false)); + QCOMPARE(modeOf(path), 0u); +#ifdef TREELAND_DEBUG_DEV_BUILD + QCOMPARE(modeOf(treelandDebugSocketDir()), 0700u); +#else + QCOMPARE(modeOf(treelandDebugSocketDir()), 0711u); +#endif + QCOMPARE(modeOf(neighbour), 0755u); + QFile::remove(path); + QFile::remove(neighbour); + + QVERIFY(!treelandDebugSetSocketAccess(QStringLiteral("/run/user/0/treeland/x.socket"), true)); + QTemporaryDir elsewhere; + QVERIFY(elsewhere.isValid()); + const QString foreign = elsewhere.filePath(QStringLiteral("debug.socket")); + QFile foreignSocket(foreign); + QVERIFY(foreignSocket.open(QIODevice::WriteOnly)); + foreignSocket.close(); + QCOMPARE(::chmod(QFile::encodeName(foreign).constData(), 0), 0); + QVERIFY(!treelandDebugSetSocketAccess(foreign, true)); + QCOMPARE(modeOf(foreign), 0u); + QCOMPARE(modeOf(elsewhere.path()), 0700u); + QVERIFY(treelandDebugSetSocketAccess(foreign, false)); + + // An unsafe sticky/world-writable directory must not be widened. + QCOMPARE(::chmod(QFile::encodeName(treelandDebugSocketDir()).constData(), 01777), 0); + QVERIFY(!treelandDebugSetSocketAccess(path, true)); + QCOMPARE(modeOf(treelandDebugSocketDir()), 01777u); +#ifdef TREELAND_DEBUG_DEV_BUILD + QCOMPARE(::chmod(QFile::encodeName(treelandDebugSocketDir()).constData(), 0700), 0); +#else + QCOMPARE(::chmod(QFile::encodeName(treelandDebugSocketDir()).constData(), 0711), 0); +#endif +} + +// --------------------------------------------------------------------------- +// parseCommand: no-argument commands +// --------------------------------------------------------------------------- + +void TreelandDebugTest::testParseTree() +{ + const auto r = parseCommand(QStringLiteral("tree"), {}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Tree); + QVERIFY(r.error.isEmpty()); +} + +void TreelandDebugTest::testParseCursor() +{ + const auto r = parseCommand(QStringLiteral("cursor"), {}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Cursor); +} + +void TreelandDebugTest::testParseWindows() +{ + const auto r = parseCommand(QStringLiteral("windows"), {}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Windows); +} + +void TreelandDebugTest::testParseWindowMissingTarget() +{ + const auto r = parseCommand(QStringLiteral("window"), {}); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("window: missing window target (id or appId)")); + QCOMPARE(r.command, DebugCommand::Unknown); +} + +void TreelandDebugTest::testParseWindow() +{ + const auto r = parseCommand(QStringLiteral("window"), { QStringLiteral("93824992268800") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Window); + QCOMPARE(r.target, QStringLiteral("93824992268800")); +} + +void TreelandDebugTest::testParseClients() +{ + const auto r = parseCommand(QStringLiteral("clients"), {}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Clients); +} + +void TreelandDebugTest::testParseIdle() +{ + const auto r = parseCommand(QStringLiteral("idle"), {}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Idle); + QVERIFY(r.error.isEmpty()); +} + +void TreelandDebugTest::testParseShortcuts() +{ + const auto r = parseCommand(QStringLiteral("shortcuts"), {}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Shortcuts); + QCOMPARE(r.intervalMs, 0); // one-shot listing, not a live view +} + +void TreelandDebugTest::testParseHelp() +{ + const auto r = parseCommand(QStringLiteral("help"), {}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Help); +} + +void TreelandDebugTest::testParseShell() +{ + const auto r = parseCommand(QStringLiteral("shell"), {}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Shell); +} + +void TreelandDebugTest::testParseNoAuth() +{ + // The no-auth window is requested over the protocol; the command that sends + // it takes no arguments, like the other inspection commands. + const auto r = parseCommand(QStringLiteral("no-auth"), {}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::NoAuth); + QVERIFY(r.error.isEmpty()); +} + +// --------------------------------------------------------------------------- +// parseCommand: window control (activate/close/minimize/maximize/fullscreen) +// --------------------------------------------------------------------------- + +void TreelandDebugTest::testParseActivateMissingTarget() +{ + const auto r = parseCommand(QStringLiteral("activate"), {}); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("activate: missing window target (id or appId)")); + QCOMPARE(r.command, DebugCommand::Unknown); +} + +void TreelandDebugTest::testParseActivate() +{ + const auto r = parseCommand(QStringLiteral("activate"), { QStringLiteral("42") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Activate); + QCOMPARE(r.target, QStringLiteral("42")); +} + +void TreelandDebugTest::testParseCloseMissingTarget() +{ + const auto r = parseCommand(QStringLiteral("close"), {}); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("close: missing window target (id or appId)")); +} + +void TreelandDebugTest::testParseClose() +{ + const auto r = parseCommand(QStringLiteral("close"), { QStringLiteral("org.foo.bar") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Close); + QCOMPARE(r.target, QStringLiteral("org.foo.bar")); +} + +void TreelandDebugTest::testParseMinimizeMissingTarget() +{ + const auto r = parseCommand(QStringLiteral("minimize"), {}); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("minimize: missing window target (id or appId)")); +} + +void TreelandDebugTest::testParseMinimize() +{ + const auto r = parseCommand(QStringLiteral("minimize"), { QStringLiteral("100") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Minimize); + QCOMPARE(r.target, QStringLiteral("100")); +} + +void TreelandDebugTest::testParseMaximizeMissingTarget() +{ + const auto r = parseCommand(QStringLiteral("maximize"), {}); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("maximize: missing window target (id or appId)")); +} + +void TreelandDebugTest::testParseMaximize() +{ + const auto r = parseCommand(QStringLiteral("maximize"), { QStringLiteral("7") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Maximize); + QCOMPARE(r.target, QStringLiteral("7")); +} + +void TreelandDebugTest::testParseFullscreenMissingTarget() +{ + const auto r = parseCommand(QStringLiteral("fullscreen"), {}); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("fullscreen: missing window target (id or appId)")); +} + +void TreelandDebugTest::testParseFullscreen() +{ + const auto r = parseCommand(QStringLiteral("fullscreen"), { QStringLiteral("55") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Fullscreen); + QCOMPARE(r.target, QStringLiteral("55")); +} + +// --------------------------------------------------------------------------- +// parseCommand: move / resize / workspace +// --------------------------------------------------------------------------- + +void TreelandDebugTest::testParseMoveMissingTarget() +{ + const auto r = parseCommand(QStringLiteral("move"), {}); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("move: missing window target (id or appId)")); +} + +void TreelandDebugTest::testParseMoveTooFewArgs() +{ + const auto r = parseCommand(QStringLiteral("move"), { QStringLiteral("42") }); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("move: usage: move ")); +} + +void TreelandDebugTest::testParseMove() +{ + const auto r = parseCommand(QStringLiteral("move"), + { QStringLiteral("42"), QStringLiteral("100"), QStringLiteral("-200") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Move); + QCOMPARE(r.target, QStringLiteral("42")); + QCOMPARE(r.x, 100); + QCOMPARE(r.y, -200); +} + +void TreelandDebugTest::testParseResizeMissingTarget() +{ + const auto r = parseCommand(QStringLiteral("resize"), {}); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("resize: missing window target (id or appId)")); +} + +void TreelandDebugTest::testParseResizeTooFewArgs() +{ + const auto r = parseCommand(QStringLiteral("resize"), { QStringLiteral("42") }); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("resize: usage: resize ")); +} + +void TreelandDebugTest::testParseResize() +{ + const auto r = parseCommand(QStringLiteral("resize"), + { QStringLiteral("42"), QStringLiteral("800"), QStringLiteral("600") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Resize); + QCOMPARE(r.target, QStringLiteral("42")); + QCOMPARE(r.width, 800); + QCOMPARE(r.height, 600); +} + +void TreelandDebugTest::testParseWorkspaceMissingTarget() +{ + const auto r = parseCommand(QStringLiteral("workspace"), {}); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("workspace: missing window target (id or appId)")); +} + +void TreelandDebugTest::testParseWorkspaceTooFewArgs() +{ + const auto r = parseCommand(QStringLiteral("workspace"), { QStringLiteral("42") }); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("workspace: usage: workspace ")); +} + +void TreelandDebugTest::testParseWorkspace() +{ + const auto r = parseCommand(QStringLiteral("workspace"), + { QStringLiteral("42"), QStringLiteral("3") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Workspace); + QCOMPARE(r.target, QStringLiteral("42")); + QCOMPARE(r.workspaceId, 3); +} + +// --------------------------------------------------------------------------- +// parseCommand: move-cursor +// --------------------------------------------------------------------------- + +void TreelandDebugTest::testParseMoveCursorTooFewArgs() +{ + const auto r = parseCommand(QStringLiteral("move-cursor"), { QStringLiteral("10") }); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("move-cursor: usage: move-cursor ")); +} + +void TreelandDebugTest::testParseMoveCursor() +{ + const auto r = parseCommand(QStringLiteral("move-cursor"), + { QStringLiteral("12.5"), QStringLiteral("-7.0") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::MoveCursor); + QCOMPARE(r.dx, 12.5); + QCOMPARE(r.dy, -7.0); +} + +void TreelandDebugTest::testParseMoveCursorNegative() +{ + const auto r = parseCommand(QStringLiteral("move-cursor"), + { QStringLiteral("-100"), QStringLiteral("-200") }); + QVERIFY(r.ok); + QCOMPARE(r.dx, -100.0); + QCOMPARE(r.dy, -200.0); +} + +// --------------------------------------------------------------------------- +// parseCommand: event motion|button|key +// --------------------------------------------------------------------------- + +void TreelandDebugTest::testParseEventNoSub() +{ + const auto r = parseCommand(QStringLiteral("event"), {}); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("event: usage: event motion|button|key ...")); +} + +void TreelandDebugTest::testParseEventUnknownSub() +{ + const auto r = parseCommand(QStringLiteral("event"), { QStringLiteral("foobar") }); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("event: unknown subcommand 'foobar'")); +} + +void TreelandDebugTest::testParseEventMotionTooFewArgs() +{ + const auto r = parseCommand(QStringLiteral("event"), { QStringLiteral("motion"), QStringLiteral("5") }); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("event motion: usage: event motion ")); +} + +void TreelandDebugTest::testParseEventMotion() +{ + const auto r = parseCommand(QStringLiteral("event"), + { QStringLiteral("motion"), QStringLiteral("3.5"), QStringLiteral("9.0") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::EventMotion); + QCOMPARE(r.dx, 3.5); + QCOMPARE(r.dy, 9.0); +} + +void TreelandDebugTest::testParseEventButtonTooFewArgs() +{ + const auto r = parseCommand(QStringLiteral("event"), { QStringLiteral("button") }); + QVERIFY(!r.ok); + QCOMPARE(r.error, + QStringLiteral("event button: usage: event button [press|release|click]")); +} + +void TreelandDebugTest::testParseEventButtonUnknown() +{ + const auto r = parseCommand(QStringLiteral("event"), + { QStringLiteral("button"), QStringLiteral("foobar") }); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("unknown button 'foobar'")); +} + +void TreelandDebugTest::testParseEventButtonNamed() +{ + const auto r = parseCommand(QStringLiteral("event"), + { QStringLiteral("button"), QStringLiteral("left") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::EventButton); + QCOMPARE(r.code, 0x110); + QCOMPARE(r.action, QStringLiteral("click")); // default action +} + +void TreelandDebugTest::testParseEventButtonRaw() +{ + const auto r = parseCommand(QStringLiteral("event"), + { QStringLiteral("button"), QStringLiteral("275") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::EventButton); + QCOMPARE(r.code, 275); + QCOMPARE(r.action, QStringLiteral("click")); +} + +void TreelandDebugTest::testParseEventButtonWithAction() +{ + const auto r = parseCommand(QStringLiteral("event"), + { QStringLiteral("button"), QStringLiteral("right"), QStringLiteral("press") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::EventButton); + QCOMPARE(r.code, 0x111); + QCOMPARE(r.action, QStringLiteral("press")); +} + +void TreelandDebugTest::testParseEventButtonDefaultAction() +{ + const auto r = parseCommand(QStringLiteral("event"), + { QStringLiteral("button"), QStringLiteral("middle") }); + QVERIFY(r.ok); + QCOMPARE(r.action, QStringLiteral("click")); +} + +void TreelandDebugTest::testParseEventKeyTooFewArgs() +{ + const auto r = parseCommand(QStringLiteral("event"), { QStringLiteral("key") }); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("event key: usage: event key [press|release|tap]")); +} + +void TreelandDebugTest::testParseEventKeyUnknown() +{ + const auto r = parseCommand(QStringLiteral("event"), + { QStringLiteral("key"), QStringLiteral("nonexistent") }); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("unknown key 'nonexistent'")); +} + +void TreelandDebugTest::testParseEventKeyNamed() +{ + const auto r = parseCommand(QStringLiteral("event"), + { QStringLiteral("key"), QStringLiteral("enter") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::EventKey); + QCOMPARE(r.code, static_cast(Qt::Key_Enter)); + QCOMPARE(r.action, QStringLiteral("tap")); // default action +} + +void TreelandDebugTest::testParseEventKeyRaw() +{ + const auto r = parseCommand(QStringLiteral("event"), + { QStringLiteral("key"), QStringLiteral("200") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::EventKey); + QCOMPARE(r.code, 200); + QCOMPARE(r.action, QStringLiteral("tap")); +} +void TreelandDebugTest::testParseEventKeyWithAction() +{ + const auto r = parseCommand(QStringLiteral("event"), + { QStringLiteral("key"), QStringLiteral("Space"), QStringLiteral("release") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::EventKey); + QCOMPARE(r.code, static_cast(Qt::Key_Space)); + QCOMPARE(r.action, QStringLiteral("release")); +} + +void TreelandDebugTest::testParseEventKeyDefaultAction() +{ + const auto r = parseCommand(QStringLiteral("event"), + { QStringLiteral("key"), QStringLiteral("Escape") }); + QVERIFY(r.ok); + QCOMPARE(r.action, QStringLiteral("tap")); +} + +// --------------------------------------------------------------------------- +// parseCommand: screenshot output|window +// --------------------------------------------------------------------------- + +void TreelandDebugTest::testParseScreenshotNoSub() +{ + const auto r = parseCommand(QStringLiteral("screenshot"), {}); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("screenshot: usage: screenshot output|window ...")); +} + +void TreelandDebugTest::testParseScreenshotUnknownTarget() +{ + const auto r = parseCommand(QStringLiteral("screenshot"), { QStringLiteral("screen") }); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("screenshot: unknown target 'screen'")); +} + +void TreelandDebugTest::testParseScreenshotOutputNoArgs() +{ + const auto r = parseCommand(QStringLiteral("screenshot"), { QStringLiteral("output") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::ScreenshotOutput); + QVERIFY(r.outputName.isEmpty()); + QVERIFY(r.filePath.isEmpty()); +} + +void TreelandDebugTest::testParseScreenshotOutputWithName() +{ + const auto r = parseCommand(QStringLiteral("screenshot"), + { QStringLiteral("output"), QStringLiteral("eDP-1") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::ScreenshotOutput); + QCOMPARE(r.outputName, QStringLiteral("eDP-1")); + QVERIFY(r.filePath.isEmpty()); +} + +void TreelandDebugTest::testParseScreenshotOutputWithNameAndFile() +{ + const auto r = parseCommand(QStringLiteral("screenshot"), + { QStringLiteral("output"), QStringLiteral("eDP-1"), + QStringLiteral("/tmp/cap.png") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::ScreenshotOutput); + QCOMPARE(r.outputName, QStringLiteral("eDP-1")); + QCOMPARE(r.filePath, QStringLiteral("/tmp/cap.png")); +} + +void TreelandDebugTest::testParseScreenshotOutputEmptyName() +{ + // An explicit empty output name is treated the same as omitting it. + const auto r = parseCommand(QStringLiteral("screenshot"), + { QStringLiteral("output"), QStringLiteral("") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::ScreenshotOutput); + QVERIFY(r.outputName.isEmpty()); +} + +void TreelandDebugTest::testParseScreenshotWindowTooFewArgs() +{ + const auto r = parseCommand(QStringLiteral("screenshot"), { QStringLiteral("window") }); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("screenshot window: usage: screenshot window [file]")); +} + +void TreelandDebugTest::testParseScreenshotWindow() +{ + const auto r = parseCommand(QStringLiteral("screenshot"), + { QStringLiteral("window"), QStringLiteral("42") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::ScreenshotWindow); + QCOMPARE(r.target, QStringLiteral("42")); + QVERIFY(r.filePath.isEmpty()); +} + +void TreelandDebugTest::testParseScreenshotWindowWithFile() +{ + const auto r = parseCommand(QStringLiteral("screenshot"), + { QStringLiteral("window"), QStringLiteral("42"), + QStringLiteral("/tmp/win.png") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::ScreenshotWindow); + QCOMPARE(r.target, QStringLiteral("42")); + QCOMPARE(r.filePath, QStringLiteral("/tmp/win.png")); +} + +// --------------------------------------------------------------------------- +// parseCommand: live commands (top/events/watch) +// --------------------------------------------------------------------------- + +void TreelandDebugTest::testParseTopDefault() +{ + const auto r = parseCommand(QStringLiteral("top"), {}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Top); + QCOMPARE(r.intervalMs, 1000); +} + +void TreelandDebugTest::testParseTopCustomInterval() +{ + const auto r = parseCommand(QStringLiteral("top"), { QStringLiteral("500") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Top); + QCOMPARE(r.intervalMs, 500); +} + +void TreelandDebugTest::testParseTopInvalidInterval() +{ + // A non-positive interval falls back to the default 1000 ms. + const auto r0 = parseCommand(QStringLiteral("top"), { QStringLiteral("0") }); + QVERIFY(r0.ok); + QCOMPARE(r0.intervalMs, 1000); + + const auto rNeg = parseCommand(QStringLiteral("top"), { QStringLiteral("-5") }); + QVERIFY(rNeg.ok); + QCOMPARE(rNeg.intervalMs, 1000); +} + +void TreelandDebugTest::testParseEventsDefault() +{ + const auto r = parseCommand(QStringLiteral("events"), {}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Events); + QCOMPARE(r.intervalMs, 50); +} + +void TreelandDebugTest::testParseEventsCustomInterval() +{ + const auto r = parseCommand(QStringLiteral("events"), { QStringLiteral("25") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Events); + QCOMPARE(r.intervalMs, 25); +} + +void TreelandDebugTest::testParseEventsInvalidInterval() +{ + const auto r0 = parseCommand(QStringLiteral("events"), { QStringLiteral("0") }); + QVERIFY(r0.ok); + QCOMPARE(r0.intervalMs, 50); + + const auto rNeg = parseCommand(QStringLiteral("events"), { QStringLiteral("-1") }); + QVERIFY(rNeg.ok); + QCOMPARE(rNeg.intervalMs, 50); +} + +void TreelandDebugTest::testParseWatchMissingId() +{ + const auto r = parseCommand(QStringLiteral("watch"), {}); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("watch: usage: watch [interval-ms]")); +} + +void TreelandDebugTest::testParseWatch() +{ + const auto r = parseCommand(QStringLiteral("watch"), { QStringLiteral("42") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Watch); + QCOMPARE(r.target, QStringLiteral("42")); + QCOMPARE(r.intervalMs, 250); // default +} + +void TreelandDebugTest::testParseWatchWithInterval() +{ + const auto r = parseCommand(QStringLiteral("watch"), + { QStringLiteral("42"), QStringLiteral("500") }); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Watch); + QCOMPARE(r.target, QStringLiteral("42")); + QCOMPARE(r.intervalMs, 500); +} + +void TreelandDebugTest::testParseWatchInvalidInterval() +{ + const auto r = parseCommand(QStringLiteral("watch"), + { QStringLiteral("42"), QStringLiteral("0") }); + QVERIFY(r.ok); + QCOMPARE(r.target, QStringLiteral("42")); + QCOMPARE(r.intervalMs, 250); // falls back to default + + const auto rNeg = parseCommand(QStringLiteral("watch"), + { QStringLiteral("42"), QStringLiteral("-100") }); + QVERIFY(rNeg.ok); + QCOMPARE(rNeg.intervalMs, 250); +} + +// --------------------------------------------------------------------------- +// parseCommand: unknown command +// --------------------------------------------------------------------------- + +void TreelandDebugTest::testParseUnknownCommand() +{ + const auto r = parseCommand(QStringLiteral("foobar"), {}); + QVERIFY(!r.ok); + QCOMPARE(r.error, QStringLiteral("unknown command 'foobar' (try --help)")); + QCOMPARE(r.command, DebugCommand::Unknown); +} + +// --- parseCommand: listen --- + +void TreelandDebugTest::testParseListenDefault() +{ + const auto r = parseCommand(QStringLiteral("listen"), {}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Listen); + QCOMPARE(r.port, 8080); + QCOMPARE(r.host, QStringLiteral("0.0.0.0")); +} + +void TreelandDebugTest::testParseListenCustomPort() +{ + const auto r = parseCommand(QStringLiteral("listen"), {QStringLiteral("--port"), QStringLiteral("9090")}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Listen); + QCOMPARE(r.port, 9090); + QCOMPARE(r.host, QStringLiteral("0.0.0.0")); +} + +void TreelandDebugTest::testParseListenCustomHost() +{ + const auto r = parseCommand(QStringLiteral("listen"), {QStringLiteral("--host"), QStringLiteral("127.0.0.1")}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Listen); + QCOMPARE(r.port, 8080); + QCOMPARE(r.host, QStringLiteral("127.0.0.1")); +} + +void TreelandDebugTest::testParseListenCustomBoth() +{ + const auto r = parseCommand(QStringLiteral("listen"), + {QStringLiteral("--port"), QStringLiteral("3000"), + QStringLiteral("--host"), QStringLiteral("localhost")}); + QVERIFY(r.ok); + QCOMPARE(r.command, DebugCommand::Listen); + QCOMPARE(r.port, 3000); + QCOMPARE(r.host, QStringLiteral("localhost")); +} + +void TreelandDebugTest::testParseListenInvalidPortLow() +{ + const auto r = parseCommand(QStringLiteral("listen"), {QStringLiteral("--port"), QStringLiteral("0")}); + QVERIFY(!r.ok); + QVERIFY(r.error.contains(QStringLiteral("port"))); +} + +void TreelandDebugTest::testParseListenInvalidPortHigh() +{ + const auto r = parseCommand(QStringLiteral("listen"), {QStringLiteral("--port"), QStringLiteral("70000")}); + QVERIFY(!r.ok); + QVERIFY(r.error.contains(QStringLiteral("port"))); +} + +void TreelandDebugTest::testParseListenUnknownArg() +{ + const auto r = parseCommand(QStringLiteral("listen"), {QStringLiteral("--foo")}); + QVERIFY(!r.ok); + QVERIFY(r.error.contains(QStringLiteral("usage"))); +} + +void TreelandDebugTest::testParseListenPortNoValue() +{ + const auto r = parseCommand(QStringLiteral("listen"), {QStringLiteral("--port")}); + QVERIFY(!r.ok); + QVERIFY(r.error.contains(QStringLiteral("usage"))); +} + +QTEST_MAIN(TreelandDebugTest) +#include "main.moc" diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt new file mode 100644 index 0000000000..a79aa3e127 --- /dev/null +++ b/tools/CMakeLists.txt @@ -0,0 +1,2 @@ +add_subdirectory(treeland-session-helper) +add_subdirectory(treeland-debug) diff --git a/tools/treeland-debug/CMakeLists.txt b/tools/treeland-debug/CMakeLists.txt new file mode 100644 index 0000000000..8290870e7e --- /dev/null +++ b/tools/treeland-debug/CMakeLists.txt @@ -0,0 +1,90 @@ +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +option(BUILD_TREELAND_DEBUG "Build the treeland-debug client" ON) + +if (NOT BUILD_TREELAND_DEBUG) + return() +endif() + +find_package(Qt6 REQUIRED COMPONENTS Core Gui RemoteObjects Network HttpServer WebSockets) +set(windowtree_rep_file + "${PROJECT_SOURCE_DIR}/src/modules/resource/treelandwindowtree.rep" +) +set(windowtree_generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated") +set(windowtree_replica_header + "${windowtree_generated_dir}/rep_treeland_windowtree_replica.h" +) + +add_custom_command( + OUTPUT "${windowtree_replica_header}" + COMMAND "${CMAKE_COMMAND}" -E make_directory "${windowtree_generated_dir}" + COMMAND "$" + -i rep + -o replica + "${windowtree_rep_file}" + "${windowtree_replica_header}" + DEPENDS "${windowtree_rep_file}" + VERBATIM +) + +set(treeland_debug_sources + main.cpp + shellline.cpp + debughelpers.cpp + debugsession.cpp + debugswitch.cpp + "${PROJECT_SOURCE_DIR}/src/modules/resource/treelanddebugsocket.cpp" + "${windowtree_replica_header}" +) + +list(APPEND treeland_debug_sources debugserver.cpp) + +qt_add_executable(treeland-debug + ${treeland_debug_sources} +) + +set_target_properties(treeland-debug PROPERTIES + AUTOMOC ON +) + +target_include_directories(treeland-debug PRIVATE + "${windowtree_generated_dir}" + "${PROJECT_SOURCE_DIR}/src/modules/resource" +) + +target_link_libraries(treeland-debug PRIVATE + Qt6::Core + Qt6::Gui # QRegion travels in WindowInfo + Qt6::RemoteObjects + Qt6::Network +) + +# Qt6::HttpServer and Qt6::WebSockets are required dependencies (see +# find_package above), so the `listen` HTTP/WebSocket server is always built. +target_compile_definitions(treeland-debug PRIVATE TREELAND_DEBUG_LISTEN) +target_link_libraries(treeland-debug PRIVATE + Qt6::HttpServer + Qt6::WebSockets +) + +install(TARGETS treeland-debug + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" + COMPONENT treeland-debug +) + +# Tab completion for the one-shot command line, one file per shell. dash is not +# listed: it has no programmable completion, so there is nothing to install for +# it (see README.md). +install(FILES completions/treeland-debug + DESTINATION "${CMAKE_INSTALL_DATADIR}/bash-completion/completions" + COMPONENT treeland-debug +) +install(FILES completions/_treeland-debug + DESTINATION "${CMAKE_INSTALL_DATADIR}/zsh/site-functions" + COMPONENT treeland-debug +) +install(FILES completions/treeland-debug.fish + DESTINATION "${CMAKE_INSTALL_DATADIR}/fish/vendor_completions.d" + COMPONENT treeland-debug +) diff --git a/tools/treeland-debug/README.md b/tools/treeland-debug/README.md new file mode 100644 index 0000000000..20fefb6ba7 --- /dev/null +++ b/tools/treeland-debug/README.md @@ -0,0 +1,964 @@ +# treeland-debug + +`treeland-debug` is an adb-style command-line inspector and controller for the +Treeland compositor. It talks to Treeland's debug Remote Object +(`WindowTreeRemote`, generated from `src/modules/resource/treelandwindowtree.rep`) +over Qt Remote Objects and exposes a set of subcommands for inspecting the +window tree, controlling windows, injecting input events and grabbing images. + +It supports two modes, mirroring `adb`: + +- **Non-shell (one-shot) mode** — the default: `treeland-debug [args]`. +- **Shell mode** — an interactive REPL: `treeland-debug shell`. + +## Build and install + +The client requires CMake, Qt6 Core, Qt6 RemoteObjects, Qt6 HttpServer and +Qt6 WebSockets (the latter two back the `listen` HTTP/WebSocket server and are +hard build-time requirements), plus the Qt6 `repc` and `moc` tools. Build it +from the Treeland repository root: + +```bash +cmake -S . -B build -DBUILD_TREELAND_DEBUG=ON +cmake --build build --target treeland-debug +sudo cmake --install build --component treeland-debug +``` + +The executable is installed to `/usr/local/bin/treeland-debug` by default. +Set `CMAKE_INSTALL_PREFIX` during configuration to use another prefix. + +## Shell completion + +The same install step also installs completion definitions for the one-shot +command line: + +| Shell | Installed file | +|-------|----------------| +| bash | `$DATADIR/bash-completion/completions/treeland-debug` | +| zsh | `$DATADIR/zsh/site-functions/_treeland-debug` | +| fish | `$DATADIR/fish/vendor_completions.d/treeland-debug.fish` | + +They complete the command verbs and the fixed first argument of `event`, +`screenshot`, `debug` and `listen`; every other argument is a window id, a +coordinate or a path, which the shell already completes. A build-tree copy can +be used directly -- `source tools/treeland-debug/completions/treeland-debug` in +bash, or add `tools/treeland-debug/completions` to `$fpath` in zsh. + +dash is deliberately missing: it has no programmable completion at all, so +there is nothing to install for it. That does not make dash users worse off in +the REPL, because shell mode completes on its own (see +[shell](#shell)) whatever shell started it. + +The three files are written by hand, so `tests/test_treeland_debug` reads them +back and compares them with the command table (`testCompletionScriptsMatchCommandTable`). +Adding or renaming a command, or changing its first argument, without editing +them fails that test -- the completion cannot go stale unnoticed. + +## Enabling the debug source in Treeland + +Treeland runs as the `dde` user in global mode. Who may connect to its debug +socket depends on the build type: + +- **Debug builds** — the development socket is owner-only (mode `0600`); run + `treeland-debug` as the same UID as the compositor. No polkit prompt is needed. +- **Release builds** — the socket is `chmod 0000` (the kernel then rejects every + `connect()` except root's), so the client must run as `root`; a non-root + caller is escalated through `pkexec` automatically (see + [Access control](#access-control)). Once `treeland-debug no-auth` has asked the + compositor to open a window, the socket accepts every user instead and the + client connects without a prompt. + +`remoteDebug` is Treeland's master switch for debugging, and it is **off by +default** -- debugging hands out window contents and input injection, which a +compositor running inside a user session must not offer unasked. While it is on, +Treeland publishes its debug socket and serves the `WindowTree` Remote Object to +whoever connects; a plain command never writes DConfig, it just connects. +Release builds only let root connect (mode 0000) -- turn the switch off to forbid +debugging entirely, and the socket disappears with it. A debug build +(`CMAKE_BUILD_TYPE=Debug`) is the exception: it ignores the switch and always +publishes its `-dev` socket, because that instance is the one being developed. + +In a Debug build, Treeland always uses the current user's +`/tmp/treeland-debug-` directory by default instead of publishing in +`/run/treeland-debug`. The directory is owned by the current UID and mode +`0700`, and its socket is mode `0600`, so other unprivileged UIDs cannot reach +it (root retains privileged access). The Debug CLI checks this directory first, +then the shared global and legacy locations and the current user's runtime +directory; it does not enumerate other users' runtime directories. Release-socket fallback is preserved. + +For non-Debug compositors launched directly by a non-`dde` user without +`TREELAND_RUN_MODE=user`, `/run/treeland-debug` is used only when writable; +otherwise the socket is published in that process's `$XDG_RUNTIME_DIR`. + +The remote source is a stateless shell: the window tree, screenshots and scene +trees are all collected per call. The one session-scoped resource is input-event +capture, which is armed only while a client is polling for events and torn down +after it goes idle, so nothing but the socket exists while nobody is connected. + +Because the client has nothing to restore, a crash, `SIGKILL` or a closed +terminal cannot leave any state behind: there is no session-scoped setting at +all. If you find no socket, either the switch is off (the default) or Treeland +is not running; `treeland-debug` says so on stderr. Turn it on -- or off again -- +with the one command that writes the switch, `treeland-debug debug on|off`: + +```bash +treeland-debug debug on # or: treeland-debug debug off / treeland-debug debug +``` + +The switch is a per-user DConfig key and Treeland reads the one of the user it +runs as, so the command finds that user through the running compositor and +escalates through `pkexec` when it is not you (`--no-escalate` reports the +requirement instead of prompting). With root, the same thing by hand is +`dde-dconfig -u set -a org.deepin.dde.treeland -r +org.deepin.dde.treeland -k remoteDebug -v true`. + +Toggling `remoteDebug` takes effect immediately: the compositor watches +`remoteDebugChanged` and creates or destroys the Remote Object source on the +fly, so no restart is needed and no client is involved. Any number of clients +can attach at once; none of them own the switch, so one exiting cannot cut +another one off. + +## Access control + +`treeland-debug` restricts who may use it depending on the build type: + +- **Release builds** — only `root` may run `treeland-debug`; the compositor + side enforces the same rule on the socket itself (mode 0000, so any non-root + `connect()` is refused with `EACCES`). The client first tries to connect as + itself -- an unprivileged caller cannot even reach a root-only socket, so that + attempt is skipped rather than probed for the whole timeout -- and, only if it + fails, re-executes itself through `pkexec` (polkit), which prompts for + authentication. Pass `--no-escalate` to + skip the prompt and fail instead (useful in scripts or CI). + `treeland-debug no-auth` lifts this for a temporary debugging window: it asks + the compositor (the `requestNoAuth` method of `WindowTreeRemote`) to make the + socket (0666) and its own debug directory (0711) reachable for every local + user, so no prompt appears afterwards. Only a caller that already got through + the sealed socket can ask, and in a release build that is root alone: mode 0000 + blocks the compositor's own user too, only `CAP_DAC_OVERRIDE` passes. The + window closes after 30 minutes without a debug call, and every call pushes it + out again; closing it also drops the connections opened while it was open. It + only applies to the global service's own directory (`/run/treeland-debug`, not + its `$XDG_RUNTIME_DIR`) -- a session instance lives in `/run/user/`, which + is never widened, so there root stays required (and `no-auth` fails). +- **Debug builds** — the `-dev` socket is mode `0600` and normally lives in + `/tmp/treeland-debug-` (mode `0700`), so only the owning UID can reach it + and it does not add a socket to the host's `/run` directory. The Debug client + checks this directory first, then performs the existing shared-location + searches and release fallback. Explicit `TREELAND_DEBUG_DIR` can override the + server directory. The socket name keeps it separate from a release instance, + whose sealed socket still requires root. Non-Debug session instances use their + runtime directory and remain subject to that directory's permissions. + +`listen` and `debug` are the exceptions to all of this: `listen` starts the +HTTP/WebSocket server before any connection exists, and `debug` writes the +switch of the compositor's user, so neither connects first. `listen` therefore +never escalates -- run it as root (or as `dde` during a no-auth window) when the +compositor is a release build. `debug` escalates only when the compositor runs +as another user, which is exactly when DConfig needs root. + +A polkit policy (`misc/polkit/org.deepin.dde.treeland-debug.policy`) is +installed alongside the executable so that the `pkexec` escalation works out of +the box on release builds. If `pkexec` is not available, non-root callers +receive an error explaining how to proceed. + +## Global options + +``` +--url Remote object host URL (default: $TREELAND_DEBUG_SOCKET, + else automatic probing; Debug builds check their own + /tmp/treeland-debug- first, then shared global/legacy + locations and their own runtime directory. They do not + enumerate other UIDs' runtime directories.) +--name Remote object name (default: WindowTree) +--timeout-ms Request timeout in milliseconds (default: 30000) +--json Emit machine-readable JSON instead of the text view +--no-escalate Do not attempt polkit privilege escalation; report the + requirement instead (scripts, CI) +--log-level Verbosity of this client's own stderr diagnostics: error, + warning, info (default) or debug. Only info and debug differ + today; debug adds discovery detail such as the socket a + fallback connection came from. +-h, --help Show help +-v, --version Show version +``` + +The socket is chosen in this order: `--url`, then `$TREELAND_DEBUG_SOCKET`, then +the built-in probing. `TREELAND_DEBUG_SOCKET` takes a socket path (or a bare +socket name) and is treated like `local:`; a value with a scheme is used +as-is. It is handy when the compositor runs under a runtime directory the +client cannot guess: + +```bash +TREELAND_DEBUG_SOCKET=/run/treeland-debug/org.deepin.dde.treeland.debug treeland-debug windows +``` + +Backward compatibility: `--tree` and `--cursor` are accepted as aliases for the +`tree` and `cursor` commands. + +When neither `--url` nor `$TREELAND_DEBUG_SOCKET` is given, the client tries each +candidate socket path followed by the instances Treeland published under a +`"-"` suffix (taken when another instance already holds the base name), so +the build-type preference still wins. Every connected run names the socket it read at +the end (and the shell does it on entry), so a pasted output always says whose it is; +`help`, `--version`, `debug` and `listen` never connect, so they print no source line. +Which candidate it fell back from is client-side discovery detail: that +`(fallback from ...)` suffix is printed only with `--log-level debug`, and it also +covers attaching to a `-` instance of the preferred build type -- not only a +cross-build-type fallback. `error`/`warning`/`info` behave identically today, because +no current message is classed below Info. Each candidate is probed with `--timeout-ms` shared between the +candidates still to be tried, but never for less than one short probe (about three +seconds): a live socket answers in milliseconds, so a probe only bounds the wait for +one that is slow or dead. A dead socket therefore delays the preferred instance +without starving it, and discovery can take up to `--timeout-ms` plus one probe per +candidate -- which also gives a compositor that publishes its source late the time +to do so. An explicit `--url` or `$TREELAND_DEBUG_SOCKET` is used verbatim and tries +nothing else. + +## Output format + +The human-readable output follows the x11 tools, so anyone used to `xwininfo`, +`xprop` and `xdotool` reads it the same way -- in one command instead of five +programs: + +- **Lists** (`windows`, `clients`, `top`, `shortcuts`) are a header row plus + exactly one line per object, with no continuation lines, so they stay + readable and greppable. +- **Geometry** is `WxH+X+Y`, the `xwininfo -geometry` / `xdotool + getwindowgeometry` order: `800x600+100+50`. A negative coordinate keeps its + own sign (`800x600-10+50`); unlike x11 it is not an offset from the right + edge, because a window can sit left of the layout origin on a multi-output + desktop. +- **One object in full** (`window `, `idle`) is a `Key: value` block with + one field per line and the keys padded, like `xwininfo -id`; `window` ends + with a bare `-geometry WxH+X+Y` line that can be pasted into a report. +- **Nested structure** (`tree`, `scene`) keeps tree branch characters. +- **Source** is named at the end of every connected run on stderr -- + `treeland-debug: connected to local:/run/treeland-debug/...` -- so the data + never floats free of the instance it came from, and `--json`/piped stdout stay + parseable. The shell prints the same line as its login banner instead, and the + commands that never connect (`help`, `--version`, `debug`, `listen`) print no + source line. +- **`--json`** is the machine-readable form of the same data: the `listen` + HTTP/WebSocket/MCP API returns exactly the same records (as its `data` + field), so a script and a browser read one contract. + +Every window record names its **shell surface type** -- `xdg-toplevel`, +`xdg-popup`, `xwayland`, `layer-shell`, `input-popup`, `lock-screen`, +`splash-screen` -- in the `TYPE` column of the tables, in the tree, and as +`shellType` in JSON. That is what tells an application window apart from a +layer-shell panel, a popup or an XWayland window. + +[Example output](#example-output) below shows every command's actual output. + +## Example output + +One example per command, on a two-output desktop (`eDP-1`, `HDMI-A-1`) with a +`dde-file-manager` window on workspace 1, the dock as a `layer-shell` surface, +an XWayland app and the lock screen. Ids, timestamps and sizes differ from run +to run; the layout shown is exactly what the commands print. + +### Inspection + +`tree` -- the layout tree, no header row: layers, then workspaces, then +windows. `*` marks the active window, `+` inside `[outputs]` the output driving +its frame callbacks, and `+Min` a minimized window: + +```console +$ treeland-debug tree +Mode: Normal + (per window: active id type app-id state geometry [outputs] title) +├─ Layer: normal (2) +│ ├─ Workspace 1 (active) +│ └─ * 93824992268800 xdg-toplevel dde-file-manager Normal 800x600+100+50 [+eDP-1] Documents +│ └─ Workspace 2 +│ └─ (no windows) +├─ Layer: top (3) +│ └─ 93824992269056 layer-shell dde-dock Normal 1920x40+0+1040 [eDP-1,+HDMI-A-1] +└─ Layer: overlay (4) + └─ 93824992269568 lock-screen dde-lock Fullscreen 1920x1080+0+0 [+eDP-1] +``` + +`windows` -- one header row, one line per window, and a two-line legend under +the table. A window with no title prints a title column that is simply empty: + +```console +$ treeland-debug windows +ID TYPE APP-ID STATE ACTIVE MIN OUTPUT GEOMETRY TITLE +93824992268800 xdg-toplevel dde-file-manager Normal yes no +eDP-1 800x600+100+50 Documents +93824992269056 layer-shell dde-dock Normal no no eDP-1,+HDMI-A-1 1920x40+0+1040 +93824992269312 xwayland steam Tiling no yes +HDMI-A-1 1240x800-10+50 Steam +93824992269568 lock-screen dde-lock Fullscreen no no +eDP-1 1920x1080+0+0 + (TYPE = shell surface type; '+' in OUTPUT marks the frame-pacing output; + GEOMETRY is WxH+X+Y; `treeland-debug window ` shows one window in full) +``` + +`window ` -- the full record, `Key: value`, one field per line, empty +fields omitted, and a bare `-geometry` line last for pasting into a report: + +```console +$ treeland-debug window 93824992268800 +Window id: 93824992268800 "Documents" + App ID: dde-file-manager + Shell type: xdg-toplevel + Layer: 2 Z: 3 + Workspace: 1 + State: Normal + Visible: yes + Active: yes + Minimized: no + Output: eDP-1 + Outputs: eDP-1 + Frame pacing: eDP-1 + Geometry: 800x600+100+50 + Position: 100,50 + Bounding rect: 800x600+100+50 + Titlebar: 800x40+100+50 + Icon: 24x24+140+60 + Frames: 12345 + Damage: 300x200+120+80 + Input region: [100,50 800x600] + Opaque region: [100,90 800x560] + Last leave: HDMI-A-1 (enabled: yes, emptied outputs: no) + Last outputs update: enabledChanged (enabled: 1/2, computed: 1, automatic: yes) +-geometry 800x600+100+50 +``` + +`Damage`, `Titlebar`, `Icon`, `Bounding rect`, `Last leave` and `Last outputs +update` only appear when the compositor reported them, so a quiet window prints +a shorter block. + +An `appId` that matches more than one window shows the first one and says so on +stderr, which keeps `--json` output parseable: + +```console +$ treeland-debug window dde-file-manager +treeland-debug: 2 windows match 'dde-file-manager'; showing id 93824992268800 +Window id: 93824992268800 "Documents" + ... +``` + +`clients` -- one block per connected Wayland client (hex id, pid, appId, +window count, `exe`/`cmd`), followed by that client's windows in the same table +as `windows`: + +```console +$ treeland-debug clients +client 0x560000000001 pid=4242 appId=dde-file-manager windows=1 + exe: /usr/bin/dde-file-manager + cmd: dde-file-manager -p + ID TYPE APP-ID STATE ACTIVE MIN OUTPUT GEOMETRY TITLE + 93824992268800 xdg-toplevel dde-file-manager Normal yes no +eDP-1 800x600+100+50 Documents + +client 0x560000000002 pid=5150 windows=2 + exe: /usr/bin/steam + ID TYPE APP-ID STATE ACTIVE MIN OUTPUT GEOMETRY TITLE + 93824992269312 xwayland steam Tiling no yes +HDMI-A-1 1240x800-10+50 Steam + 93824992269056 layer-shell dde-dock Normal no no eDP-1,+HDMI-A-1 1920x40+0+1040 +``` + +`cursor` -- one line, labelled, `xdotool getmouselocation` style. `window:0` +means no window is under the pointer (or the compositor did not answer), so the +shape never changes: + +```console +$ treeland-debug cursor +x:100 y:50 window:93824992268800 +$ treeland-debug --json cursor +{ + "window": 93824992268800, + "x": 100, + "y": 50 +} +``` + +`idle` -- a `Key: value` block, then one line per idle-inhibit source. Note that +the second source below is `active=no`, so it does not count towards +`Inhibited: yes`: + +```console +$ treeland-debug idle + Idle: 12.3s since last input + Inhibited: yes + Screensaver: no + Inhibitors: 2 + [idle-inhibit] pid=6001 appId=vlc window=93824992269440 "Big Buck Bunny" active=yes held=5m12s exe=/usr/bin/vlc + [screensaver] pid=6100 appId=(unknown) app="dde-screensaver" reason="playing a slideshow" active=no held=5.0s +``` + +`shortcuts` -- a header row and one line per binding; gesture rows leave `FLAGS` +empty (flags are a key-binding concept): + +```console +$ treeland-debug shortcuts +NAME TRIGGER ACTION FLAGS +launcher Meta toggle-launcher press +terminal Ctrl+Alt+T launch-terminal press|repeat +workspace-left swipe 3-finger left switch-workspace-left +expo hold 4-finger toggle-expo +``` + +`top` -- a live screen repainted in place every `interval-ms` (default 1000). +Each frame carries its timestamp, the client/window counts and an idle summary, +then one line per window, most active first, with the frame delta since the +previous frame: + +```console +$ treeland-debug top +treeland-debug top — 2026-11-18T14:32:07 (clients: 2 windows: 3) + idle: 12.3s inhibited: no sources: 0 (0 active) + ID TYPE APP-ID STATE MIN FRAMES GEOMETRY MARKER + 93824992268800 xdg-toplevel dde-file-manager Normal no 1234 800x600+100+50 F (focus) + 93824992269312 xwayland steam Tiling yes 57 1240x800-10+50 + 93824992269056 layer-shell dde-dock Normal no 0 1920x40+0+1040 C (under cursor) +``` + +`scene [id]` -- the QtQuick item tree behind a window (or the whole render +scene), pre-formatted by the compositor: `ClassName "objectName" [x,y WxH] +z= op=`, with `hidden` on invisible items: + +```console +$ treeland-debug scene 93824992268800 +TreelandWindow [0.0,0.0 800.0x600.0] z=0.0 op=1.00 + QQuickRectangle [0.0,0.0 800.0x40.0] z=1.0 op=1.00 + QQuickText "titleLabel" [12.0,8.0 120.0x24.0] z=0.0 op=1.00 + QQuickItem "surfaceContent" [0.0,40.0 800.0x560.0] z=0.0 op=1.00 + QQuickPopupItem "popup" [200.0,300.0 240.0x120.0] hidden z=3.0 op=0.00 +``` + +`events` -- a live stream, one line per event: time, event type (the same names +the JSON `type` field uses, padded), the compositor's description, then +`-> ` when the event has a target: + +```console +$ treeland-debug events +treeland-debug events — streaming every 50ms (Ctrl+C to quit) + +14:32:07.512 motion 782,410 -> 93824992268800 +14:32:08.004 focus -> 93824992269312 +14:32:08.311 shortcut-triggered "terminal" -> launch-terminal +14:32:09.077 shortcut-registered "expo" = hold 4-finger -> toggle-expo +``` + +`watch [interval-ms]` -- samples one window every `interval-ms` (default +250 ms). The first sample prints a header, then every refresh prints one line, +`*`-prefixed when something changed since the previous sample: + +```console +$ treeland-debug watch 93824992268800 +treeland-debug watch 93824992268800 — every 250ms (Ctrl+C to quit) + +Window 93824992268800 dde-file-manager (Documents) + type=xdg-toplevel state=Normal geometry=800x600+100+50 +14:32:07 (no change) +14:32:08 * frames 12346 (+1); damage 800x560+100+90 +14:32:09 * state Normal -> Maximized; geometry 1920x1080+0+0 +``` + +### Window control + +The control commands print a single `ok` (or `failed`, with a non-zero exit +code). `activate`/`close`/… take an `id` or an `appId`: + +```console +$ treeland-debug activate dde-file-manager +ok +$ treeland-debug maximize 93824992268800 +ok +$ treeland-debug move 93824992268800 200 120 +ok +$ treeland-debug resize 93824992268800 1024 768 +ok +$ treeland-debug workspace 93824992268800 2 +ok +$ treeland-debug close steam +ok +``` + +### Input and pointer events + +`move-cursor` and the `event` subcommands also print `ok`; nothing is echoed +back because the effect shows up in `cursor`, `watch` or `events`: + +```console +$ treeland-debug move-cursor 100 50 +ok +$ treeland-debug event motion 100 50 +ok +$ treeland-debug event button left click +ok +$ treeland-debug event key enter tap +ok +``` + +### Image capture + +`screenshot` writes a PNG and prints the path it wrote (`/tmp/treeland-debug- +.png` when no file is given, `.png` appended when the name has no suffix). +On a terminal that supports inline images the picture is also previewed: + +```console +$ treeland-debug screenshot output +/tmp/treeland-debug-1763447100123.png +$ treeland-debug screenshot window 93824992268800 ~/shots/win.png +/home/demo/shots/win.png +``` + +### The debug switch and access + +`debug` prints the switch state it read back, and says what the compositor will +do next; the running-as state is included so a per-user switch is unambiguous: + +```console +$ treeland-debug debug +remoteDebug is off (uid 1000) +$ treeland-debug debug on +remoteDebug is on; treeland publishes its debug socket now +$ treeland-debug debug off +remoteDebug is off; treeland drops its debug socket now +``` + +`no-auth` confirms the 30-minute window it opened: + +```console +$ sudo treeland-debug no-auth +the debug socket is open to every user for 30 minutes +``` + +### listen (HTTP / WebSocket / MCP) + +`listen` prints the address it bound, then serves: + +```console +$ treeland-debug listen --host 127.0.0.1 --port 8080 +treeland-debug listening on 127.0.0.1:8080 +``` + +The HTTP API answers with the same records the CLI prints, wrapped in +`{"ok":…}`, compact: + +```console +$ curl -s 127.0.0.1:8080/api/cursor +{"data":{"window":93824992268800,"x":100,"y":50},"ok":true} +$ curl -s '127.0.0.1:8080/api/window?target=dde-file-manager' +{"data":{"active":true,"appId":"dde-file-manager",…,"shellType":"xdg-toplevel","state":0,"type":0,…},"ok":true} +$ curl -s -X POST -d '{"state":"on"}' 127.0.0.1:8080/api/debug +{"data":{"enabled":true,"uid":1000},"ok":true} +$ curl -s -X POST -d '{"target":"93824992268800"}' 127.0.0.1:8080/api/activate +{"data":true,"ok":true} +``` + +Errors keep the same shape and a non-200 status: +`{"ok":false,"error":"no window matches 'foo'"}`. + +### shell + +The REPL accepts any command above plus `help` and `exit`; each result is +printed exactly as the one-shot form would print it: + +```console +$ treeland-debug shell +treeland-debug shell — type 'help' for commands, 'exit' to quit +treeland-debug: logged in to local:/run/treeland-debug/org.deepin.dde.treeland.debug +treeland> cursor +x:100 y:50 window:93824992268800 +treeland> activate dde-file-manager +ok +treeland> exit +``` + +`debug` is the one exception: it writes DConfig outside the debug socket, so the +REPL tells you to run it as a one-shot command instead of escalating a polkit +prompt from inside the shell. + +Tab completes the command verb and the fixed first argument of `event`, +`screenshot`, `debug` and `listen`; a keypress is read one at a time, so the +completion arrives before the line ends. Up/Down recall earlier lines, Ctrl+C +discards the line at the prompt (and still interrupts a live view), Ctrl+D ends +the session. A piped stdin (`echo windows | treeland-debug shell`) has no Tab to +act on, so it keeps reading plain lines. + +### help + +`--help` / `help` prints the whole command reference, grouped like the +[Commands](#commands) section: + +```console +$ treeland-debug --help +Usage: treeland-debug [global-options] [args] + +An adb-style inspector and controller for the Treeland compositor. Runs in +one-shot (non-shell) mode by default; use the `shell` command for an +interactive REPL. + +Global options: + --url Remote object host URL (default: $TREELAND_DEBUG_SOCKET, + else the build-specific socket found by probing) + ... +Output conventions (the same as the x11 tools, in one command): + ... + +Inspection: + tree Print the complete window tree (human-readable, use --json for JSON) + cursor Print the cursor position, xdotool-style (x:N y:N window:N, + window 0 = none under the cursor) + windows List all toplevel windows, with their shell type + ... +``` + +## Commands + +Run `treeland-debug ` for any of the following. + +### Access + +| Command | Description | +| --- | --- | +| `debug [on\|off\|status]` | Read or write treeland's `remoteDebug` switch (default: `status`). The only command that runs without the debug socket -- it is what makes one exist, so it works while the switch is off. Escalates through `pkexec` when the compositor runs as another user. A debug-build compositor ignores the switch, so this only changes what a release build does. | +| `no-auth` | Ask the compositor to let any local user connect to this debug socket for 30 minutes (see Access control above; needs root unless the window is already open). | + +### Inspection + +| Command | Description | +| --- | --- | +| `tree` | Print the complete layout tree (human-readable by default; `--json` for JSON). | +| `cursor` | Print the cursor position, xdotool-style: `x:100 y:50 window:93824992268800`. | +| `windows` | List every window (table, or JSON with `--json`): id, shell type, appId, state, active/minimized, outputs, geometry. | +| `window ` | Show one window in full, xwininfo-style: shell type, container, layer/z, workspace, state, outputs, geometry, SSD rects, frame counter, damage, input and opaque regions. | +| `clients` | List connected Wayland clients and the windows each owns. | +| `idle` | Show the idle state (time since the last input activity), whether idle is inhibited, and every idle-inhibit source (window/idle-inhibitor or screensaver) holding it off. | +| `shortcuts` | List the registered shortcuts (key bindings and touchpad gestures). | +| `top [interval-ms]` | Live, `top`-like refreshing view of clients and windows (default 1000 ms, Ctrl+C to quit). Includes an idle summary line. | +| `scene [id]` | Dump the QtQuick scene tree of one window (by `id`/`appId`) or, with no id, the whole render scene. Useful for inspecting menus, popups and decorations that do not show up in the layout `tree`. | + +`shortcuts` prints a header row and then one line per registered shortcut — +name, trigger (`Ctrl+Alt+T`, `swipe 3-finger left`, `hold 4-finger`), target +action and, for key bindings, the trigger flags +(`press`/`release`/`repeat`; gesture rows leave that column empty). Use `--json` for +`[{name,type,key,flags,action,fingers,direction}]`, where `type` is +`0`=key, `1`=swipe, `2`=hold. Registrations come from clients, so the list is +empty until a shell binds shortcuts through `treeland-shortcut-manager-v3`. + +The `windows`/`clients`/`top` views report a stable numeric `id` for every +window. That id (or the window's `appId`) is accepted by every control command. + +`idle` reports the time since the last input activity (the compositor has no +global idle threshold — clients such as the screensaver pick their own via +`ext-idle-notify-v1`), whether idle notification is currently suppressed, and +every idle-inhibit source currently held. The summary is a `Key: value` block +(`Idle`/`Inhibited`/`Screensaver`/`Inhibitors`), followed by one line per +inhibitor with its `key=value` fields: `zwp_idle_inhibit_manager_v1` +surfaces (identified by window id/appId/title) and `treeland_screensaver_v2` +inhibits (identified by the client-provided application name and reason). +`--json` emits the same data with `idleMs`/`heldMs` in milliseconds. + +The list includes sources that are not in effect right now (for example an +idle-inhibitor window that is minimized); the `active` field tells them apart, +and only `active` sources count towards `inhibited`. `surfaceId` is a window id +usable with the control commands only when the inhibitor is held on a toplevel +surface — a layer-shell or subsurface inhibitor (common for video players) +reports a surface id that `windows`/`top` do not list. + +```bash +treeland-debug idle +treeland-debug --json idle +``` + +### Window control + +Targets may be given by numeric `id` (printed by `windows`/`clients`/`top`) or +by `appId` (the first matching window is used). + +| Command | Description | +| --- | --- | +| `activate ` | Activate (focus) a window. | +| `close ` | Close a window. | +| `minimize ` | Minimize a window. | +| `maximize ` | Toggle maximized state. | +| `fullscreen ` | Toggle fullscreen state. | +| `move ` | Move a window to `(x, y)`. | +| `resize ` | Resize a window to `(w, h)`. | +| `workspace ` | Move a window to a workspace. | + +```bash +treeland-debug windows +treeland-debug close dde-file-manager +treeland-debug maximize 93824992268800 +``` + +### Input / event injection + +| Command | Description | +| --- | --- | +| `move-cursor ` | Move the cursor to `(x, y)`. | +| `event motion ` | Move the cursor to `(x, y)`. | +| `event button [press\|release\|click]` | Send a pointer button; `btn` = `left\|right\|middle\|` (default `click`). | +| `event key [press\|release\|tap]` | Send a keyboard event; `key` = name or raw Linux evdev keycode (default `tap`). | + +Pointer buttons use Linux input codes (`BTN_LEFT` = 0x110, `BTN_RIGHT` = 0x111, +`BTN_MIDDLE` = 0x112). Keyboard keys use Linux evdev keycodes; common names are +recognised (`enter`, `esc`, `space`, `tab`, `left`/`right`/`up`/`down`, `a`–`z`, +`0`–`9`, `f1`–`f12`, …). Keys are delivered to the currently keyboard-focused +surface, so `activate` a window first to target it. Pointer buttons are +delivered to the surface that currently holds pointer focus; move the cursor +onto a window before clicking. + +```bash +treeland-debug activate dde-file-manager +treeland-debug event key enter tap +treeland-debug event button left click +``` + +### Image capture + +Screenshots are rendered server-side (via the same GPU texture read-back the +screenshot protocol uses) and returned to the `treeland-debug` client as PNG +bytes; the client writes them to a file and prints the path. The compositor +itself never touches the filesystem. + +| Command | Description | +| --- | --- | +| `screenshot output [name] [file]` | Grab an output (by id/name; primary if omitted). | +| `screenshot window [file]` | Grab a single window. | + +If `file` is omitted a path under `/tmp` is generated. + +```bash +treeland-debug screenshot window 93824992268800 +``` + +### Shortcut monitoring + +`events` also carries the shortcut stream, so `treeland-debug events` is the +place to watch shortcuts being bound and used: + +- `type 6` — `shortcut registered: "" = -> [flags]` +- `type 7` — `shortcut unregistered: ""`; also emitted for every binding + when the active session changes (the registry is cleared and re-populated) + and for the old name when a binding is re-bound under a new one. +- `type 8` — `shortcut triggered: "" -> [flags]`, with `target` + set to the window that was keyboard-focused when the shortcut fired (sampled + before the action runs, so a workspace or task switch does not report the + destination window). Gesture triggers (swipe and hold) are reported too, + marked `(gesture)` and with `target` 0 — a gesture has no keyboard focus to + blame. + +`treeland-debug events` prints the event type next to the timestamp +(`motion`, `button`, `key`, `shortcut-registered`, …), the same names the +`type` field uses. + +Like the other live streams, capture is armed only while a client is polling +`getEvents()`, so bind a shortcut that was already registered before you +attached (restart the client that owns it, or re-login) to see a registration +event, and use any bound shortcut — key, swipe or hold — to see a trigger +event. + +### Interactive shell mode + +```bash +treeland-debug shell +``` + +Starts a REPL (`treeland>`) that accepts any of the commands above, plus `help` +and `exit`. This is the *shell* mode; running a single command on the command +line is the *non-shell* mode. Like an ssh login banner, it names the socket the +session reads as soon as it starts, so a shell attached to another instance does +not look like your own desktop. Tab completes the command verb and its fixed +first argument, Up/Down recall earlier lines, and Ctrl+C discards the line at +the prompt. + +### HTTP / WebSocket server mode + +```bash +treeland-debug listen [--port ] [--host ] +``` + +Starts an HTTP + WebSocket server (default `0.0.0.0:8080`) that exposes every +CLI capability over the network — intended as the backend for a browser-based +graphical debugger. All data is returned through the API: screenshots come back +as `image/png` response bytes, not files on disk. + +Each HTTP request (and each WebSocket one-shot command) creates its own +short-lived session that connects to the compositor, performs the operation, +then disconnects — the server consumes **zero compositor-side resources while +idle**. Live WebSocket subscriptions (`top`, `events`, `watch`) hold a session +open only for the lifetime of the subscription. + +CORS headers (`Access-Control-Allow-Origin: *`) are set on every response and +OPTIONS preflight is handled, so a browser frontend can call the API directly. + +#### HTTP REST API + +| Method | Path | Body / Query | Description | +| --- | --- | --- | --- | +| GET | `/api/tree` | — | Layout tree JSON | +| GET | `/api/cursor` | — | Cursor position JSON, plus `window` (id under the cursor, `0` for none) | +| GET | `/api/windows` | — | All windows JSON | +| GET | `/api/clients` | — | All clients JSON | +| GET | `/api/idle` | — | Idle state and idle-inhibit sources JSON | +| GET | `/api/no-auth` | — | Ask the compositor to open this debug socket to every local user for 30 minutes. This API has no authentication of its own, so bind it to a trusted address (see Access control). | +| GET | `/api/shortcuts` | — | Registered shortcuts JSON | +| GET | `/api/focused` | — | Focused window id | +| GET | `/api/cursor-window` | — | Window under cursor id | +| GET | `/api/window` | `?target=...` | One window's full record (the same JSON `treeland-debug --json window ` prints) | +| GET | `/api/debug` | — | Treeland's `remoteDebug` switch: `{enabled, uid}` | +| POST | `/api/debug` | `{"state":"on\|off"}` | Turn the switch on or off. The server cannot escalate, so a switch that needs root fails with the reason instead of prompting. It also blocks its event loop while `dde-dconfig` answers (a 3 s budget for the set and the read-back together), so live subscriptions stall for that long at worst. | +| GET | `/api/scene` | `?target=...` | QtQuick scene tree of a window (or the whole scene if `target` is omitted), as pre-formatted text | +| GET | `/api/events` | `?since=N` | Debug events after seq N | +| GET | `/api/screenshot/output` | `?name=...` | PNG bytes (`image/png`) | +| GET | `/api/screenshot/window` | `?target=...` | PNG bytes (`image/png`) | +| POST | `/api/activate` | `{"target":"..."}` | Activate window | +| POST | `/api/close` | `{"target":"..."}` | Close window | +| POST | `/api/minimize` | `{"target":"..."}` | Minimize window | +| POST | `/api/maximize` | `{"target":"..."}` | Toggle maximized | +| POST | `/api/fullscreen` | `{"target":"..."}` | Toggle fullscreen | +| POST | `/api/move` | `{"target":"...","x":N,"y":N}` | Move window | +| POST | `/api/resize` | `{"target":"...","width":N,"height":N}` | Resize window | +| POST | `/api/workspace` | `{"target":"...","workspaceId":N}` | Move to workspace | +| POST | `/api/move-cursor` | `{"x":N,"y":N}` | Move cursor | +| POST | `/api/event/motion` | `{"x":N,"y":N}` | Pointer motion | +| POST | `/api/event/button` | `{"button":"...","action":"..."}` | Pointer button | +| POST | `/api/event/key` | `{"key":"...","action":"..."}` | Key event | + +`target` may be a numeric window id or an `appId` (first match is used). +Responses are JSON: `{"ok":true,"data":...}` or `{"ok":false,"error":"..."}`. + +#### WebSocket API + +Connect to `ws://:/ws` and send JSON messages. One-shot commands +mirror the HTTP API and the CLI command names (`{"command":"tree"}`, +`{"command":"window","target":"..."}`, `{"command":"debug","state":"on"}`, +`{"command":"activate","target":"..."}` etc.). Screenshots are returned as a binary frame followed by a JSON ack. + +Live subscriptions: + +| Action | Message | Description | +| --- | --- | --- | +| Subscribe | `{"command":"subscribe","type":"top","id":"...","intervalMs":1000}` | Live window/client list | +| Subscribe | `{"command":"subscribe","type":"events","id":"...","intervalMs":1000}` | Live event stream | +| Subscribe | `{"command":"subscribe","type":"watch","target":"...","id":"...","intervalMs":250}` | Live watch on a window | +| Unsubscribe | `{"command":"unsubscribe","id":"..."}` | Stop a subscription | + +#### MCP (Model Context Protocol) server + +The HTTP server also exposes a single MCP endpoint at `POST /mcp` that speaks +JSON-RPC 2.0 over the [Streamable HTTP](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports) +transport. This lets any MCP-compatible AI client — Claude Desktop, Cursor, +VS Code Copilot, etc. — directly inspect and control the Treeland compositor +without a separate bridge process. + +**Endpoint:** `http://:/mcp` +**Protocol version:** `2025-06-18` +**Capabilities:** tools (no resources, no prompts, no subscriptions) + +The server is stateless: every `tools/call` creates a fresh session to the +compositor, performs the operation, and disconnects. No `Mcp-Session-Id` is +returned, so clients need not send `DELETE` to terminate. + +Supported JSON-RPC methods: + +| Method | Description | +| --- | --- | +| `initialize` | Protocol handshake; returns server info and capabilities | +| `notifications/initialized` | Notification (no response body; HTTP 202) | +| `tools/list` | Returns the full tool catalog | +| `tools/call` | Invokes a tool by name with arguments | +| `ping` | Health check | + +The 27 available tools mirror the HTTP REST API and CLI commands: + +| Tool | Args | Description | +| --- | --- | --- | +| `tree` | — | Layout tree JSON | +| `cursor` | — | Cursor position | +| `windows` | — | All windows | +| `clients` | — | All clients | +| `idle` | — | Idle state and idle-inhibit sources | +| `no-auth` | — | Open this debug socket to every local user for 30 minutes | +| `shortcuts` | — | Registered shortcuts | +| `focused` | — | Focused window id | +| `cursor_window` | — | Window under cursor id | +| `window` | `target` | One window's full record | +| `debug` | `state?` | Read (`state` omitted) or write (`"on"`/`"off"`) the `remoteDebug` switch | +| `scene` | `target?` | QtQuick scene tree of a window (or whole scene) | +| `events` | `since?` | Debug events after seq N | +| `activate` | `target` | Activate window | +| `close` | `target` | Close window | +| `minimize` | `target` | Minimize window | +| `maximize` | `target` | Toggle maximized | +| `fullscreen` | `target` | Toggle fullscreen | +| `move` | `target, x, y` | Move window | +| `resize` | `target, width, height` | Resize window | +| `workspace` | `target, workspaceId` | Move to workspace | +| `move_cursor` | `x, y` | Move cursor | +| `event_motion` | `x, y` | Pointer motion | +| `event_button` | `button, action?` | Pointer button (left/right/middle) | +| `event_key` | `key, action?` | Key event (Qt key name or code) | +| `screenshot_output` | `name?` | Screenshot of an output (PNG image) | +| `screenshot_window` | `target` | Screenshot of a window (PNG image) | + +`target` accepts a numeric window id or an `appId` string. Screenshots are +returned as MCP `image` content blocks with base64-encoded PNG data. + +**Claude Desktop configuration** (`claude_desktop_config.json`): + +```json +{ + "mcpServers": { + "treeland-debug": { + "url": "http://localhost:8080/mcp" + } + } +} +``` + +For other MCP clients, use the same URL as the server endpoint. No headers or +authentication are required. + +## JSON output + +`--json` is available on every inspection command and prints the same data the +HTTP API returns. A window record includes the stable `id`, `appId`, `title`, +`type` (the numeric shell-surface type) alongside `shellType` (its name), the +geometry, state, `outputs` (every output the window is on), +`framePacingOutput` (the output driving its frame callbacks: the entered output +with the highest refresh rate) and (for `clients`) the owning client +`pid`/`executable`/`command` (the full command line, read from +`/proc//cmdline`). The `output` field is the output the compositor treats +as the window's owner -- a window spanning several outputs reports all of them +in `outputs` (taken from the compositor's window wrapper, so a pre-launch +splash window reports its outputs too). The `windows`/`clients`/`tree` views +list every output and prefix the frame-pacing one with `+` (`*` keeps its +existing meaning there: the active window). + +The single-window views -- `window `, `GET /api/window` and the MCP +`window` tool -- carry what the one-line lists leave out: the server-side +decoration geometry (`geometry` is the content rect, `titlebarGeometry` the SSD +titlebar, `boundingRect` the whole frame), the frame counter, the damage rect, +and the window's input and opaque regions. +Those two regions are sets of surface-local boxes (`inputRegion`/`opaqueRegion` +in JSON, a list of `{x,y,width,height}` rects; the text views print the first +few boxes and summarise the rest). + +`(empty)` means the committed region has no boxes. A `NULL` input region is +*not* empty: the protocol defines it as infinite, and wlroots clips every region +to the surface size, so it is reported as one box covering the whole surface. +An empty `inputRegion` therefore means the client committed an empty region +(the surface accepts no input), or the surface has not committed a buffer yet. +The same applies to `opaqueRegion`: empty means no opaque area was declared +(also its value before the first commit), not that the window is actually +transparent. + +`damage`/region data is serialised on every `windows`/`clients` call, so a +client committing a region with thousands of boxes inflates the polls of `top` +as well (which does not display them); use `window ` when you need the +regions and a cheap `windows` poll while you look at something else. + +`WindowInfo` is a `WindowTreeRemote` POD, and Qt Remote Objects serialises a POD +by field order with no version negotiation: a `treeland-debug` built from a +different revision than the running `treeland` can mis-parse every window after +the first. Build both from the same revision. + +## License + +treeland is licensed under Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only. diff --git a/tools/treeland-debug/completions/_treeland-debug b/tools/treeland-debug/completions/_treeland-debug new file mode 100644 index 0000000000..0f77b79565 --- /dev/null +++ b/tools/treeland-debug/completions/_treeland-debug @@ -0,0 +1,71 @@ +#compdef treeland-debug +# SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +# +# Zsh completion for treeland-debug. Installed as +# $DATADIR/zsh/site-functions/_treeland-debug; for a build-tree copy, add +# tools/treeland-debug/completions to $fpath. +# +# The word lists mirror debugCommandNames()/completionCandidates() in +# tools/treeland-debug/debughelpers.cpp; testCompletionScriptsMatchCommandTable() +# compares them and fails when one side was changed without the other. + +_treeland_debug() +{ + local -a commands + commands=( + 'tree:Print the complete window tree' + 'cursor:Print the cursor position' + 'windows:List all toplevel windows' + 'window:Print one window in detail' + 'clients:List connected clients' + 'idle:Print the idle state' + 'shortcuts:List registered shortcuts' + 'scene:Dump the QtQuick scene tree' + 'activate:Activate a window' + 'close:Close a window' + 'minimize:Minimize a window' + 'maximize:Maximize a window' + 'fullscreen:Toggle fullscreen on a window' + 'move:Move a window' + 'resize:Resize a window' + 'workspace:Move a window to a workspace' + 'move-cursor:Move the cursor' + 'event:Inject an input event' + 'screenshot:Capture an output or a window' + 'top:Live window table' + 'events:Live input event stream' + 'watch:Watch one window' + 'no-auth:Open the debug socket to every user for 30 minutes' + 'listen:Expose the CLI over HTTP and WebSocket' + 'debug:Read or write the remoteDebug switch' + 'help:Show the command reference' + 'shell:Start the interactive REPL' + ) + + # `_arguments -C` shifts $words, so remember the command now: in the args + # state $words[1] is the subcommand and $words[2] its first argument. Reading + # $words[2] after the call is what used to fall through to _files. + local first_argument=$words[2] + + _arguments -C \ + '1:command:->command' \ + '*::arg:->args' + + case $state in + command) + _describe -t commands 'treeland-debug command' commands + ;; + args) + case $first_argument in + event) _values 'event' motion button key ;; + screenshot) _values 'screenshot target' output window ;; + debug) _values 'debug action' on off status ;; + listen) _arguments '--port[port to bind]:port' '--host[address to bind]:address' ;; + *) _files ;; + esac + ;; + esac +} + +_treeland_debug "$@" diff --git a/tools/treeland-debug/completions/treeland-debug b/tools/treeland-debug/completions/treeland-debug new file mode 100644 index 0000000000..d564de4392 --- /dev/null +++ b/tools/treeland-debug/completions/treeland-debug @@ -0,0 +1,40 @@ +# SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +# +# Bash completion for treeland-debug. Installed as +# $DATADIR/bash-completion/completions/treeland-debug; for a build-tree copy, +# `source tools/treeland-debug/completions/treeland-debug`. +# +# The word lists mirror debugCommandNames()/completionCandidates() in +# tools/treeland-debug/debughelpers.cpp; testCompletionScriptsMatchCommandTable() +# compares them and fails when one side was changed without the other. + +# Only the verbs parseCommand() accepts: the REPL-only `exit`/`quit` would be +# offered for a command line that rejects them (the REPL completes those itself). +_treeland_debug_commands='tree cursor windows window clients idle shortcuts scene + activate close minimize maximize fullscreen move resize workspace move-cursor + event screenshot top events watch no-auth listen debug help shell' + +# The fixed first argument of the commands that have one; every other command +# takes a window id, a coordinate or a path, which the shell already completes. +_treeland_debug_first_arg() +{ + case $1 in + event) echo 'motion button key' ;; + screenshot) echo 'output window' ;; + debug) echo 'on off status' ;; + listen) echo '--port --host' ;; + esac +} + +_treeland_debug() +{ + local cur=${COMP_WORDS[COMP_CWORD]} + if [ "$COMP_CWORD" -le 1 ]; then + COMPREPLY=($(compgen -W "$_treeland_debug_commands" -- "$cur")) + else + COMPREPLY=($(compgen -W "$(_treeland_debug_first_arg "${COMP_WORDS[1]}")" -- "$cur")) + fi +} + +complete -o default -F _treeland_debug treeland-debug diff --git a/tools/treeland-debug/completions/treeland-debug.fish b/tools/treeland-debug/completions/treeland-debug.fish new file mode 100644 index 0000000000..b50ecd21e7 --- /dev/null +++ b/tools/treeland-debug/completions/treeland-debug.fish @@ -0,0 +1,44 @@ +# SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +# +# Fish completion for treeland-debug. Installed as +# $DATADIR/fish/vendor_completions.d/treeland-debug.fish. +# +# The word lists mirror debugCommandNames()/completionCandidates() in +# tools/treeland-debug/debughelpers.cpp; testCompletionScriptsMatchCommandTable() +# compares them and fails when one side was changed without the other. + +complete -c treeland-debug -n '__fish_use_subcommand' -a tree -d 'Print the complete window tree' +complete -c treeland-debug -n '__fish_use_subcommand' -a cursor -d 'Print the cursor position' +complete -c treeland-debug -n '__fish_use_subcommand' -a windows -d 'List all toplevel windows' +complete -c treeland-debug -n '__fish_use_subcommand' -a window -d 'Print one window in detail' +complete -c treeland-debug -n '__fish_use_subcommand' -a clients -d 'List connected clients' +complete -c treeland-debug -n '__fish_use_subcommand' -a idle -d 'Print the idle state' +complete -c treeland-debug -n '__fish_use_subcommand' -a shortcuts -d 'List registered shortcuts' +complete -c treeland-debug -n '__fish_use_subcommand' -a scene -d 'Dump the QtQuick scene tree' +complete -c treeland-debug -n '__fish_use_subcommand' -a activate -d 'Activate a window' +complete -c treeland-debug -n '__fish_use_subcommand' -a close -d 'Close a window' +complete -c treeland-debug -n '__fish_use_subcommand' -a minimize -d 'Minimize a window' +complete -c treeland-debug -n '__fish_use_subcommand' -a maximize -d 'Maximize a window' +complete -c treeland-debug -n '__fish_use_subcommand' -a fullscreen -d 'Toggle fullscreen on a window' +complete -c treeland-debug -n '__fish_use_subcommand' -a move -d 'Move a window' +complete -c treeland-debug -n '__fish_use_subcommand' -a resize -d 'Resize a window' +complete -c treeland-debug -n '__fish_use_subcommand' -a workspace -d 'Move a window to a workspace' +complete -c treeland-debug -n '__fish_use_subcommand' -a move-cursor -d 'Move the cursor' +complete -c treeland-debug -n '__fish_use_subcommand' -a event -d 'Inject an input event' +complete -c treeland-debug -n '__fish_use_subcommand' -a screenshot -d 'Capture an output or a window' +complete -c treeland-debug -n '__fish_use_subcommand' -a top -d 'Live window table' +complete -c treeland-debug -n '__fish_use_subcommand' -a events -d 'Live input event stream' +complete -c treeland-debug -n '__fish_use_subcommand' -a watch -d 'Watch one window' +complete -c treeland-debug -n '__fish_use_subcommand' -a no-auth -d 'Open the debug socket to every user for 30 minutes' +complete -c treeland-debug -n '__fish_use_subcommand' -a listen -d 'Expose the CLI over HTTP and WebSocket' +complete -c treeland-debug -n '__fish_use_subcommand' -a debug -d 'Read or write the remoteDebug switch' +complete -c treeland-debug -n '__fish_use_subcommand' -a help -d 'Show the command reference' +complete -c treeland-debug -n '__fish_use_subcommand' -a shell -d 'Start the interactive REPL' + +# The fixed first argument of the commands that have one. +complete -c treeland-debug -n '__fish_seen_subcommand_from event' -a 'motion button key' +complete -c treeland-debug -n '__fish_seen_subcommand_from screenshot' -a 'output window' +complete -c treeland-debug -n '__fish_seen_subcommand_from debug' -a 'on off status' +complete -c treeland-debug -n '__fish_seen_subcommand_from listen' -l port -r -d 'Port to bind' +complete -c treeland-debug -n '__fish_seen_subcommand_from listen' -l host -r -d 'Address to bind' diff --git a/tools/treeland-debug/debughelpers.cpp b/tools/treeland-debug/debughelpers.cpp new file mode 100644 index 0000000000..28c36e72c8 --- /dev/null +++ b/tools/treeland-debug/debughelpers.cpp @@ -0,0 +1,644 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "debughelpers.h" + +#include +#include +#include +#include + +#include + +QString stateName(int state) +{ + switch (state) { + case 0: return QStringLiteral("Normal"); + case 1: return QStringLiteral("Maximized"); + case 2: return QStringLiteral("Fullscreen"); + case 3: return QStringLiteral("Tiling"); + default: return QStringLiteral("Unknown(%1)").arg(state); + } +} + +// The order is the wire contract: it is SurfaceWrapper::Type as serialised in +// WindowInfo::type, so these names must follow that enum's declaration order. +QString shellTypeName(int type) +{ + switch (type) { + case 0: return QStringLiteral("xdg-toplevel"); + case 1: return QStringLiteral("xdg-popup"); + case 2: return QStringLiteral("xwayland"); + case 3: return QStringLiteral("layer-shell"); + case 4: return QStringLiteral("input-popup"); + case 5: return QStringLiteral("lock-screen"); + case 6: return QStringLiteral("splash-screen"); + default: return QStringLiteral("unknown(%1)").arg(type); + } +} + +QString formatGeometry(const QRectF &rect) +{ + const int x = qRound(rect.x()); + const int y = qRound(rect.y()); + return QStringLiteral("%1x%2%3%4%5%6") + .arg(qRound(rect.width())) + .arg(qRound(rect.height())) + .arg(x < 0 ? QLatin1Char('-') : QLatin1Char('+')) + .arg(qAbs(x)) + .arg(y < 0 ? QLatin1Char('-') : QLatin1Char('+')) + .arg(qAbs(y)); +} + +QString formatDuration(quint64 ms) +{ + // Round to the nearest 100ms up front: the sub-minute format shoots a + // decimal, and without this 59.99s would render as "60.0s" instead of + // rolling over to "1m00s". + const quint64 rounded = (ms + 50) / 100 * 100; + if (rounded < 60000) + return QStringLiteral("%1s").arg(rounded / 1000.0, 0, 'f', 1); + if (rounded < 3600000) + return QStringLiteral("%1m%2s") + .arg(rounded / 60000) + .arg((rounded % 60000) / 1000, 2, 10, QLatin1Char('0')); + return QStringLiteral("%1h%2m") + .arg(rounded / 3600000) + .arg((rounded % 3600000) / 60000, 2, 10, QLatin1Char('0')); +} + +QString outputsLabel(const QStringList &outputs, const QString &pacing, const QString &owner) +{ + if (outputs.isEmpty()) + return owner; + + QStringList labels; + labels.reserve(outputs.size()); + for (const QString &name : outputs) + labels.append(name == pacing ? QLatin1Char('+') + name : name); + return labels.join(QLatin1Char(',')); +} + +int buttonCode(const QString &name, bool *ok) +{ + *ok = true; + const QString lower = name.toLower(); + if (lower == QLatin1String("left")) + return 0x110; // BTN_LEFT + if (lower == QLatin1String("right")) + return 0x111; // BTN_RIGHT + if (lower == QLatin1String("middle")) + return 0x112; // BTN_MIDDLE + bool parsed = false; + const int code = name.toInt(&parsed); + if (parsed) + return code; + *ok = false; + return 0; +} + +// Maps a key name to a Qt::Key enum value using Qt's meta-object system. +// Accepts the enum name with or without the "Key_" prefix, case-insensitively +// (e.g. "Escape", "escape", "Key_Escape" all resolve to Qt::Key_Escape). +// Raw integer values pass through unchanged. Sets *ok=false for unknown names. +int keyCode(const QString &name, bool *ok) +{ + *ok = true; + // Raw integer passthrough (Qt::Key value). + bool parsed = false; + const int code = name.toInt(&parsed); + if (parsed) + return code; + + // Use QMetaEnum to convert key names to Qt::Key values. The user types + // "Escape" or "escape"; we match it against "Key_Escape" in the enum. + static const QMetaEnum meta = QMetaEnum::fromType(); + const QString lower = name.toLower(); + const QString lowerWithPrefix = QLatin1String("key_") + lower; + + for (int i = 0; i < meta.keyCount(); ++i) { + const QString key = QString::fromUtf8(meta.key(i)).toLower(); + if (key == lower || key == lowerWithPrefix) + return meta.value(i); + } + + *ok = false; + return 0; +} + +QString saveCapture(const QByteArray &data, const QString &userPath) +{ + if (data.isEmpty()) + return {}; + QString path = userPath; + if (path.isEmpty()) + path = QStringLiteral("/tmp/treeland-debug-%1.png").arg(QDateTime::currentMSecsSinceEpoch()); + if (QFileInfo(path).suffix().isEmpty()) + path += QStringLiteral(".png"); + QFile f(path); + if (!f.open(QIODevice::WriteOnly)) + return {}; + if (f.write(data) != data.size()) + return {}; + f.close(); + return path; +} + +QJsonObject pointToJson(const QPointF &point) +{ + return { + {"x", point.x()}, + {"y", point.y()}, + }; +} + +QJsonObject rectToJson(const QRectF &rect) +{ + return { + {"x", rect.x()}, + {"y", rect.y()}, + {"width", rect.width()}, + {"height", rect.height()}, + }; +} + +QJsonArray rectsToJson(const QRegion ®ion) +{ + QJsonArray array; + for (const auto &rect : region) + array.append(rectToJson(rect)); + return array; +} + +QString formatRegion(const QRegion ®ion, int maxBoxes) +{ + const auto rects = region.rects(); + if (rects.isEmpty()) + return QStringLiteral("(empty)"); + QStringList boxes; + const int shown = std::min(static_cast(rects.size()), maxBoxes); + for (int i = 0; i < shown; ++i) { + const auto &r = rects[i]; + boxes << QStringLiteral("[%1,%2 %3x%4]") + .arg(r.x()) + .arg(r.y()) + .arg(r.width()) + .arg(r.height()); + } + if (rects.size() > shown) + boxes << QStringLiteral("(+%1 more)").arg(rects.size() - shown); + return boxes.join(QLatin1Char(',')); +} + +LogLevel parseLogLevel(const QString &name, bool *ok) +{ + const QString level = name.toLower(); + if (level == QLatin1String("error")) { + *ok = true; + return LogLevel::Error; + } + if (level == QLatin1String("warning") || level == QLatin1String("warn")) { + *ok = true; + return LogLevel::Warning; + } + if (level == QLatin1String("info")) { + *ok = true; + return LogLevel::Info; + } + if (level == QLatin1String("debug")) { + *ok = true; + return LogLevel::Debug; + } + *ok = false; + return LogLevel::Info; +} + +QStringList debugCommandNames() +{ + return { + QStringLiteral("tree"), + QStringLiteral("cursor"), + QStringLiteral("windows"), + QStringLiteral("window"), + QStringLiteral("clients"), + QStringLiteral("idle"), + QStringLiteral("shortcuts"), + QStringLiteral("scene"), + QStringLiteral("activate"), + QStringLiteral("close"), + QStringLiteral("minimize"), + QStringLiteral("maximize"), + QStringLiteral("fullscreen"), + QStringLiteral("move"), + QStringLiteral("resize"), + QStringLiteral("workspace"), + QStringLiteral("move-cursor"), + QStringLiteral("event"), + QStringLiteral("screenshot"), + QStringLiteral("top"), + QStringLiteral("events"), + QStringLiteral("watch"), + QStringLiteral("no-auth"), + QStringLiteral("listen"), + // REPL-only words: `debug` is a one-shot command (it may need polkit), + // `exit`/`quit` end the REPL. Neither reaches parseCommand(). + QStringLiteral("debug"), + QStringLiteral("help"), + QStringLiteral("shell"), + QStringLiteral("exit"), + QStringLiteral("quit"), + }; +} + +// The commands whose first argument is a fixed set of words. Every other command +// takes a window id, a coordinate or a path, which completion cannot guess. +static QStringList firstArgumentCandidates(const QString &command) +{ + if (command == QLatin1String("event")) + return { QStringLiteral("motion"), QStringLiteral("button"), QStringLiteral("key") }; + if (command == QLatin1String("screenshot")) + return { QStringLiteral("output"), QStringLiteral("window") }; + if (command == QLatin1String("debug")) + return { QStringLiteral("on"), QStringLiteral("off"), QStringLiteral("status") }; + if (command == QLatin1String("listen")) + return { QStringLiteral("--port"), QStringLiteral("--host") }; + return {}; +} + +QStringList completionCandidates(const QStringList &words) +{ + const QString prefix = words.isEmpty() ? QString() : words.last(); + // Word 0 is the command and word 1 its first argument; anything deeper is a + // window id, a coordinate or a path, which has nothing to offer. + QStringList source; + if (words.size() <= 1) + source = debugCommandNames(); + else if (words.size() == 2) + source = firstArgumentCandidates(words.first()); + QStringList result; + for (const QString &candidate : source) { + if (candidate.startsWith(prefix)) + result.append(candidate); + } + return result; +} + +CompletionEdit completeLine(const QString &line, int cursor) +{ + CompletionEdit edit{ line, cursor, {} }; + // Only the end of a word can be completed: with the cursor inside one, + // inserting a longer candidate would split it into two words. + if (cursor < line.size() && line.at(cursor) != QLatin1Char(' ')) + return edit; + const QString head = line.left(cursor); + const int wordStart = head.lastIndexOf(QLatin1Char(' ')) + 1; + const QString prefix = head.mid(wordStart); + QStringList words = head.left(wordStart).split(QLatin1Char(' '), Qt::SkipEmptyParts); + words.append(prefix); + + const QStringList candidates = completionCandidates(words); + if (candidates.isEmpty()) + return edit; + + QString common = candidates.first(); + for (const QString &candidate : candidates) { + int shared = 0; + while (shared < common.size() && shared < candidate.size() + && common.at(shared) == candidate.at(shared)) + ++shared; + common.truncate(shared); + } + + const bool unique = candidates.size() == 1; + if (!unique && common.size() <= prefix.size()) { + edit.list = candidates; + return edit; + } + + const QString completed = unique ? candidates.first() : common; + edit.line.replace(wordStart, prefix.size(), completed); + edit.cursor = wordStart + int(completed.size()); + if (unique) { + // Separate the completed word from what follows; a mid-line completion + // that already has a space after it would otherwise get a second one. + if (edit.cursor == edit.line.size() + || edit.line.at(edit.cursor) != QLatin1Char(' ')) { + edit.line.insert(edit.cursor, QLatin1Char(' ')); + ++edit.cursor; + } + } + return edit; +} + +ParseResult parseCommand(const QString &command, const QStringList &args) +{ + ParseResult r; + + // ---- no-argument commands ---- + if (command == QLatin1String("tree")) { + r.ok = true; + r.command = DebugCommand::Tree; + return r; + } + if (command == QLatin1String("cursor")) { + r.ok = true; + r.command = DebugCommand::Cursor; + return r; + } + if (command == QLatin1String("windows")) { + r.ok = true; + r.command = DebugCommand::Windows; + return r; + } + // ---- window (xwininfo-style single-window detail) ---- + if (command == QLatin1String("window")) { + if (args.isEmpty()) { + r.error = QStringLiteral("window: missing window target (id or appId)"); + return r; + } + r.ok = true; + r.command = DebugCommand::Window; + r.target = args.first(); + return r; + } + if (command == QLatin1String("clients")) { + r.ok = true; + r.command = DebugCommand::Clients; + return r; + } + if (command == QLatin1String("idle")) { + r.ok = true; + r.command = DebugCommand::Idle; + return r; + } + if (command == QLatin1String("shortcuts")) { + r.ok = true; + r.command = DebugCommand::Shortcuts; + return r; + } + if (command == QLatin1String("help")) { + r.ok = true; + r.command = DebugCommand::Help; + return r; + } + if (command == QLatin1String("shell")) { + r.ok = true; + r.command = DebugCommand::Shell; + return r; + } + if (command == QLatin1String("no-auth")) { + r.ok = true; + r.command = DebugCommand::NoAuth; + return r; + } + + // ---- window control (target only) ---- + if (command == QLatin1String("activate") || command == QLatin1String("close") + || command == QLatin1String("minimize") || command == QLatin1String("maximize") + || command == QLatin1String("fullscreen")) { + if (args.isEmpty()) { + r.error = QStringLiteral("%1: missing window target (id or appId)").arg(command); + return r; + } + r.ok = true; + r.target = args.first(); + if (command == QLatin1String("activate")) + r.command = DebugCommand::Activate; + else if (command == QLatin1String("close")) + r.command = DebugCommand::Close; + else if (command == QLatin1String("minimize")) + r.command = DebugCommand::Minimize; + else if (command == QLatin1String("maximize")) + r.command = DebugCommand::Maximize; + else + r.command = DebugCommand::Fullscreen; + return r; + } + + // ---- move ---- + if (command == QLatin1String("move")) { + if (args.isEmpty()) { + r.error = QStringLiteral("move: missing window target (id or appId)"); + return r; + } + if (args.size() < 3) { + r.error = QStringLiteral("move: usage: move "); + return r; + } + r.ok = true; + r.command = DebugCommand::Move; + r.target = args[0]; + r.x = args[1].toInt(); + r.y = args[2].toInt(); + return r; + } + + // ---- resize ---- + if (command == QLatin1String("resize")) { + if (args.isEmpty()) { + r.error = QStringLiteral("resize: missing window target (id or appId)"); + return r; + } + if (args.size() < 3) { + r.error = QStringLiteral("resize: usage: resize "); + return r; + } + r.ok = true; + r.command = DebugCommand::Resize; + r.target = args[0]; + r.width = args[1].toInt(); + r.height = args[2].toInt(); + return r; + } + + // ---- workspace ---- + if (command == QLatin1String("workspace")) { + if (args.isEmpty()) { + r.error = QStringLiteral("workspace: missing window target (id or appId)"); + return r; + } + if (args.size() < 2) { + r.error = QStringLiteral("workspace: usage: workspace "); + return r; + } + r.ok = true; + r.command = DebugCommand::Workspace; + r.target = args[0]; + r.workspaceId = args[1].toInt(); + return r; + } + + // ---- move-cursor ---- + if (command == QLatin1String("move-cursor")) { + if (args.size() < 2) { + r.error = QStringLiteral("move-cursor: usage: move-cursor "); + return r; + } + r.ok = true; + r.command = DebugCommand::MoveCursor; + r.dx = args[0].toDouble(); + r.dy = args[1].toDouble(); + return r; + } + + // ---- event motion|button|key ... ---- + if (command == QLatin1String("event")) { + if (args.isEmpty()) { + r.error = QStringLiteral("event: usage: event motion|button|key ..."); + return r; + } + const QString sub = args[0]; + if (sub == QLatin1String("motion")) { + if (args.size() < 3) { + r.error = QStringLiteral("event motion: usage: event motion "); + return r; + } + r.ok = true; + r.command = DebugCommand::EventMotion; + r.dx = args[1].toDouble(); + r.dy = args[2].toDouble(); + return r; + } + if (sub == QLatin1String("button")) { + if (args.size() < 2) { + r.error = QStringLiteral( + "event button: usage: event button [press|release|click]"); + return r; + } + bool codeOk = false; + const int code = buttonCode(args[1], &codeOk); + if (!codeOk) { + r.error = QStringLiteral("unknown button '%1'").arg(args[1]); + return r; + } + r.ok = true; + r.command = DebugCommand::EventButton; + r.code = code; + r.action = args.size() > 2 ? args[2] : QStringLiteral("click"); + return r; + } + if (sub == QLatin1String("key")) { + if (args.size() < 2) { + r.error = QStringLiteral("event key: usage: event key [press|release|tap]"); + return r; + } + bool keyOk = false; + const int code = keyCode(args[1], &keyOk); + if (!keyOk) { + r.error = QStringLiteral("unknown key '%1'").arg(args[1]); + return r; + } + r.ok = true; + r.command = DebugCommand::EventKey; + r.code = code; + r.action = args.size() > 2 ? args[2] : QStringLiteral("tap"); + return r; + } + r.error = QStringLiteral("event: unknown subcommand '%1'").arg(sub); + return r; + } + + // ---- screenshot output|window ... ---- + if (command == QLatin1String("screenshot")) { + if (args.isEmpty()) { + r.error = QStringLiteral("screenshot: usage: screenshot output|window ..."); + return r; + } + const QString sub = args[0]; + if (sub == QLatin1String("output")) { + r.ok = true; + r.command = DebugCommand::ScreenshotOutput; + if (args.size() >= 2 && !args[1].isEmpty()) + r.outputName = args[1]; + if (args.size() >= 3) + r.filePath = args[2]; + return r; + } + if (sub == QLatin1String("window")) { + if (args.size() < 2) { + r.error = QStringLiteral("screenshot window: usage: screenshot window [file]"); + return r; + } + r.ok = true; + r.command = DebugCommand::ScreenshotWindow; + r.target = args[1]; + if (args.size() >= 3) + r.filePath = args[2]; + return r; + } + r.error = QStringLiteral("screenshot: unknown target '%1'").arg(sub); + return r; + } + + // ---- live commands ---- + if (command == QLatin1String("top")) { + r.ok = true; + r.command = DebugCommand::Top; + r.intervalMs = 1000; + if (!args.isEmpty()) + r.intervalMs = args.first().toInt(); + if (r.intervalMs <= 0) + r.intervalMs = 1000; + return r; + } + if (command == QLatin1String("events")) { + r.ok = true; + r.command = DebugCommand::Events; + r.intervalMs = 50; + if (!args.isEmpty()) + r.intervalMs = args.first().toInt(); + if (r.intervalMs <= 0) + r.intervalMs = 50; + return r; + } + if (command == QLatin1String("watch")) { + if (args.isEmpty()) { + r.error = QStringLiteral("watch: usage: watch [interval-ms]"); + return r; + } + r.ok = true; + r.command = DebugCommand::Watch; + r.target = args.first(); + r.intervalMs = 250; + if (args.size() >= 2) + r.intervalMs = args[1].toInt(); + if (r.intervalMs <= 0) + r.intervalMs = 250; + return r; + } + + // ---- scene [id] (QtQuick scene tree dump) ---- + if (command == QLatin1String("scene")) { + r.ok = true; + r.command = DebugCommand::Scene; + if (!args.isEmpty()) + r.target = args.first(); + return r; + } + + // ---- listen (HTTP/WebSocket server) ---- + if (command == QLatin1String("listen")) { + r.ok = true; + r.command = DebugCommand::Listen; + for (int i = 0; i < args.size(); ++i) { + if (args[i] == QLatin1String("--port") && i + 1 < args.size()) { + r.port = args[++i].toInt(); + } else if (args[i] == QLatin1String("--host") && i + 1 < args.size()) { + r.host = args[++i]; + } else { + r.ok = false; + r.error = QStringLiteral("listen: usage: listen [--port ] [--host ]"); + return r; + } + } + if (r.port <= 0 || r.port > 65535) { + r.ok = false; + r.error = QStringLiteral("listen: port must be in range 1-65535"); + return r; + } + return r; + } + + r.error = QStringLiteral("unknown command '%1' (try --help)").arg(command); + return r; +} diff --git a/tools/treeland-debug/debughelpers.h b/tools/treeland-debug/debughelpers.h new file mode 100644 index 0000000000..9c9dd3b719 --- /dev/null +++ b/tools/treeland-debug/debughelpers.h @@ -0,0 +1,197 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +// Maps a window state enum to a human-readable name. +QString stateName(int state); + +// Maps a window's shell-surface type (WindowInfo::type, i.e. +// SurfaceWrapper::Type) to a name: xdg-toplevel, xdg-popup, xwayland, +// layer-shell, input-popup, lock-screen, splash-screen. This is the `TYPE` +// column of the window lists: it tells an xdg client's window apart from a +// layer-shell panel or an XWayland window. +QString shellTypeName(int type); + +// Formats a rect the way the x11 tools do (xwininfo -geometry, xdotool +// getwindowgeometry): "WxH+X+Y", a negative coordinate keeping its sign +// ("800x600-10+50"). Unlike x11, the sign is the coordinate's own value, not +// an offset from the right/bottom edge: a window can sit left of the layout +// origin on a multi-output desktop. +QString formatGeometry(const QRectF &rect); + +// Formats a millisecond duration compactly for the live views: "12.3s" under a +// minute, "2m03s" under an hour, "1h02m" above. Rounded to the nearest 100ms +// first, so 59.99s renders as "1m00s" rather than "60.0s". +QString formatDuration(quint64 ms); + +// Maps a friendly button name to a Linux input button code; raw codes pass +// through. Sets *ok=false for unknown names. +int buttonCode(const QString &name, bool *ok); + +// Maps a key name to a Qt::Key enum value using Qt's meta-object system. +// Accepts the enum name with or without the "Key_" prefix, case-insensitively +// (e.g. "Escape", "escape", "Key_Escape" all resolve to Qt::Key_Escape). +// Raw integer values pass through unchanged. Sets *ok=false for unknown names. +int keyCode(const QString &name, bool *ok); + +// Writes captured image bytes to @p userPath (or a generated /tmp path when +// empty), ensuring a .png suffix. Returns the path written, or empty on +// failure. +QString saveCapture(const QByteArray &data, const QString &userPath); + +// JSON helpers for geometry primitives. +QJsonObject pointToJson(const QPointF &point); +QJsonObject rectToJson(const QRectF &rect); +// A region is a set of boxes, so it serialises as an array of rects. +QJsonArray rectsToJson(const QRegion ®ion); + +// Formats a region's boxes as "[x,y wxh],[...]" for the human-readable views. +// A client can commit a region with thousands of boxes, so only the first +// @p maxBoxes are printed and the rest is summarised as "(+N more)"; an empty +// region prints as "(empty)". +QString formatRegion(const QRegion ®ion, int maxBoxes = 8); + +// Joins the outputs a window is on for the one-line views, marking the +// frame-pacing one with '+' ('*' already means "active window" on those +// lines). Falls back to @p owner when @p outputs is empty. +QString outputsLabel(const QStringList &outputs, const QString &pacing, const QString &owner); + +// Identifies which treeland-debug command was recognised by parseCommand(). +enum class DebugCommand { + Tree, + Cursor, + Windows, + Window, + Clients, + Idle, + Shortcuts, + Help, + Shell, + Activate, + Close, + Minimize, + Maximize, + Fullscreen, + Move, + Resize, + Workspace, + MoveCursor, + EventMotion, + EventButton, + EventKey, + ScreenshotOutput, + ScreenshotWindow, + Top, + Events, + Watch, + Scene, + NoAuth, + Listen, + Unknown, +}; + +// Outcome of parsing a treeland-debug command line. When @p ok is false, +// @p error carries the user-facing message (matching the original inline +// messages from main.cpp). When @p ok is true, @p command identifies the +// command and the remaining fields hold the parsed parameters ready for +// execution against a live Session. +struct ParseResult +{ + bool ok = false; + QString error; + DebugCommand command = DebugCommand::Unknown; + + // Window target token (for resolveTarget): activate/close/minimize/ + // maximize/fullscreen/move/resize/workspace/screenshot-window/watch. + QString target; + + // Integer coordinates/size for move/resize/workspace. + int x = 0; + int y = 0; + int width = 0; + int height = 0; + int workspaceId = 0; + + // Floating-point coordinates for move-cursor / event motion. + double dx = 0.0; + double dy = 0.0; + + // Event injection: resolved button/key code and action string. + int code = 0; + QString action; + + // Screenshot: output name and file path. + QString outputName; + QString filePath; + + // Live commands: polling interval in milliseconds. + int intervalMs = 0; + + // Listen command: HTTP/WebSocket server bind address. + int port = 8080; + QString host = QStringLiteral("0.0.0.0"); +}; + +// Verbosity of the client's own stderr diagnostics, selected by --log-level. +// Ordered from quietest to loudest, so `level <= threshold` decides whether a +// message is shown. The default, Info, hides the client's discovery details +// (which candidate socket a connection came from) that only matter while +// debugging the client itself. +enum class LogLevel { + Error, + Warning, + Info, + Debug, +}; + +// Parses a --log-level value: error, warning, info or debug, case-insensitively. +// Sets *ok=false (and returns the default Info) for anything else. +LogLevel parseLogLevel(const QString &name, bool *ok); + +// The command verbs the REPL accepts and completes: every parseCommand() verb, +// plus the REPL-only `debug` (one-shot only, it may escalate through polkit), +// `exit` and `quit`. Kept in the order the help text groups them, and mirrored +// by the shell completion scripts in completions/; adding or renaming a verb +// means editing those three files too, and testCompletionScriptsMatchCommandTable() +// (tests/test_treeland_debug) fails until they agree. +QStringList debugCommandNames(); + +// Completes the last word of a REPL line. @p words holds every word already +// typed, the partial one included ("event " passes {"event", ""}). Only the +// verb and a command's first argument are completed; deeper arguments stay +// free-form because they are window ids, key names or paths. +QStringList completionCandidates(const QStringList &words); + +// Outcome of applying completion to one REPL line. +struct CompletionEdit +{ + QString line; + int cursor = 0; + // Candidates to print on their own line: what is available when nothing new + // could be inserted (a shared prefix the line already has). Empty when the + // line was completed, so there is nothing to show. + QStringList list; +}; + +// Completes the word before @p cursor in @p line and returns the resulting line, +// cursor and the candidates to show. A single candidate is inserted whole and +// followed by a space; several candidates insert their common prefix. +CompletionEdit completeLine(const QString &line, int cursor); + +// Parses a command verb and its argument list into a ParseResult. Performs +// every validation step that does not require a live Session connection +// (missing arguments, unknown button/key names, unknown subcommands). On +// failure result.ok is false and result.error holds the message; on +// success result.ok is true and the struct fields are populated. +ParseResult parseCommand(const QString &command, const QStringList &args); + diff --git a/tools/treeland-debug/debugserver.cpp b/tools/treeland-debug/debugserver.cpp new file mode 100644 index 0000000000..bdfbbc8d0e --- /dev/null +++ b/tools/treeland-debug/debugserver.cpp @@ -0,0 +1,1684 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "debugserver.h" + +#include "debugswitch.h" +#include "treelanddebugsocket.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +DebugServer::DebugServer(const QStringList &urls, const QString &name, int timeoutMs, + QObject *parent) + : QObject(parent) + , m_urls(urls) + , m_name(name) + , m_timeoutMs(timeoutMs) +{ +} + +bool DebugServer::createSession(Session &session) +{ + // Same rule as the one-shot client: an absent local socket cannot connect, so + // probing it would only stall this request for a probe timeout. + return connectSession(session, treelandDebugExistingSocketUrls(m_urls), m_name, m_timeoutMs); +} + +QJsonObject DebugServer::sessionRequest(const std::function &work) +{ + Session session; + if (!createSession(session)) + return {{"ok", false}, {"error", QStringLiteral("failed to connect to remote object node")}}; + + return work(session); +} + +// Converts a QJsonValue that may be a string or a number into a target +// token string. MCP clients may send a numeric window id as a JSON number; +// QJsonValue::toString() returns an empty string for numbers, so we handle +// both types here. +static QString targetToString(const QJsonValue &val) +{ + if (val.isString()) + return val.toString(); + if (val.isDouble()) + return QString::number(val.toInteger()); + return {}; +} + +// Adds CORS headers to a response so a browser-based frontend can call the +// API directly. +static QHttpServerResponse addCorsHeaders(QHttpServerResponse response) +{ + auto headers = response.headers(); + headers.replaceOrAppend(QHttpHeaders::WellKnownHeader::AccessControlAllowOrigin, "*"); + headers.replaceOrAppend(QHttpHeaders::WellKnownHeader::AccessControlAllowMethods, + "GET, POST, OPTIONS"); + headers.replaceOrAppend(QHttpHeaders::WellKnownHeader::AccessControlAllowHeaders, + "Content-Type"); + response.setHeaders(std::move(headers)); + return response; +} + +// Wraps a QJsonObject-producing handler so its response includes CORS headers. +// QHttpServer auto-serializes QJsonObject to application/json. +static QHttpServerResponse jsonCorsResponse(const QJsonObject &obj, + QHttpServerResponse::StatusCode status = QHttpServerResponse::StatusCode::Ok) +{ + return addCorsHeaders(QHttpServerResponse(obj, status)); +} + +bool DebugServer::listen(const QString &host, int port) +{ + auto *tcpServer = new QTcpServer(this); + if (!tcpServer->listen(QHostAddress(host), port)) { + delete tcpServer; + return false; + } + if (!m_httpServer.bind(tcpServer)) { + delete tcpServer; + return false; + } + + // Allow WebSocket upgrades on any path — clients connect to /ws. + m_httpServer.addWebSocketUpgradeVerifier(this, [](const QHttpServerRequest &) { + return QHttpServerWebSocketUpgradeResponse::accept(); + }); + + // --- Inspection routes --- + m_httpServer.route("/api/tree", [this]() { + return jsonCorsResponse(handleTree()); + }); + m_httpServer.route("/api/cursor", [this]() { + return jsonCorsResponse(handleCursor()); + }); + m_httpServer.route("/api/windows", [this]() { + return jsonCorsResponse(handleWindows()); + }); + m_httpServer.route("/api/clients", [this]() { + return jsonCorsResponse(handleClients()); + }); + m_httpServer.route("/api/idle", [this]() { + return jsonCorsResponse(handleIdle()); + }); + m_httpServer.route("/api/shortcuts", [this]() { + return jsonCorsResponse(handleShortcuts()); + }); + m_httpServer.route("/api/focused", [this]() { + return jsonCorsResponse(handleFocused()); + }); + m_httpServer.route("/api/cursor-window", [this]() { + return jsonCorsResponse(handleCursorWindow()); + }); + m_httpServer.route("/api/window", [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleWindow(request)); + }); + m_httpServer.route("/api/scene", [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleScene(request)); + }); + m_httpServer.route("/api/no-auth", [this]() { + return jsonCorsResponse(handleNoAuth()); + }); + m_httpServer.route("/api/debug", [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleDebug(request)); + }); + + // --- Window control routes --- + m_httpServer.route("/api/activate", QHttpServerRequest::Method::Post, + [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleActivate(request)); + }); + m_httpServer.route("/api/close", QHttpServerRequest::Method::Post, + [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleClose(request)); + }); + m_httpServer.route("/api/minimize", QHttpServerRequest::Method::Post, + [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleMinimize(request)); + }); + m_httpServer.route("/api/maximize", QHttpServerRequest::Method::Post, + [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleMaximize(request)); + }); + m_httpServer.route("/api/fullscreen", QHttpServerRequest::Method::Post, + [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleFullscreen(request)); + }); + m_httpServer.route("/api/move", QHttpServerRequest::Method::Post, + [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleMove(request)); + }); + m_httpServer.route("/api/resize", QHttpServerRequest::Method::Post, + [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleResize(request)); + }); + m_httpServer.route("/api/workspace", QHttpServerRequest::Method::Post, + [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleWorkspace(request)); + }); + + // --- Input / event routes --- + m_httpServer.route("/api/move-cursor", QHttpServerRequest::Method::Post, + [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleMoveCursor(request)); + }); + m_httpServer.route("/api/event/motion", QHttpServerRequest::Method::Post, + [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleEventMotion(request)); + }); + m_httpServer.route("/api/event/button", QHttpServerRequest::Method::Post, + [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleEventButton(request)); + }); + m_httpServer.route("/api/event/key", QHttpServerRequest::Method::Post, + [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleEventKey(request)); + }); + m_httpServer.route("/api/events", [this](const QHttpServerRequest &request) { + return jsonCorsResponse(handleEvents(request)); + }); + + // --- Image capture routes (return raw PNG bytes) --- + m_httpServer.route("/api/screenshot/output", [this](const QHttpServerRequest &request) { + return addCorsHeaders(handleScreenshotOutput(request)); + }); + m_httpServer.route("/api/screenshot/window", [this](const QHttpServerRequest &request) { + return addCorsHeaders(handleScreenshotWindow(request)); + }); + + // --- MCP (Model Context Protocol) Streamable HTTP endpoint --- + // POST /mcp handles JSON-RPC initialize / tools/list / tools/call. + m_httpServer.route("/mcp", QHttpServerRequest::Method::Post, + [this](const QHttpServerRequest &request) { + return handleMcpPost(request); + }); + + // --- CORS preflight handler --- + // Any OPTIONS request returns 204 with CORS headers so browsers can + // pre-flight before actual API calls. Other unmatched paths return a + // 404 JSON body. + m_httpServer.setMissingHandler(this, [](const QHttpServerRequest &request) { + if (request.method() == QHttpServerRequest::Method::Options) + return addCorsHeaders(QHttpServerResponse(QHttpServerResponse::StatusCode::NoContent)); + return addCorsHeaders(QHttpServerResponse( + QJsonObject{{"ok", false}, {"error", "not found"}}, + QHttpServerResponse::StatusCode::NotFound)); + }); + + connect(&m_httpServer, &QAbstractHttpServer::newWebSocketConnection, + this, &DebugServer::onNewWebSocketConnection); + + return true; +} + +// --- Inspection handlers --- + +QJsonObject DebugServer::handleTree() +{ + return sessionRequest([this](Session &session) { + TreelandInfo info; + if (!waitSlot(session.replica->getTreelandInfo(), m_timeoutMs, &info)) + return QJsonObject{{"ok", false}, {"error", "getTreelandInfo() failed"}}; + return QJsonObject{{"ok", true}, {"data", treelandInfoToJson(info)}}; + }); +} + +QJsonObject DebugServer::handleCursor() +{ + return sessionRequest([this](Session &session) { + const QPointF pos = session.replica->cursorPosition(); + QJsonObject data = pointToJson(pos); + // The CLI's `cursor` prints the window under the cursor too; 0 when + // there is none (or the compositor did not answer), as xdotool does. + qint64 cursorWindow = 0; + waitSlot(session.replica->windowUnderCursor(), m_timeoutMs, &cursorWindow); + data.insert(QStringLiteral("window"), cursorWindow); + return QJsonObject{{"ok", true}, {"data", data}}; + }); +} + +QJsonObject DebugServer::handleWindows() +{ + return sessionRequest([this](Session &session) { + QList windows; + if (!waitSlot(session.replica->getWindows(), m_timeoutMs, &windows)) + return QJsonObject{{"ok", false}, {"error", "getWindows() failed"}}; + return QJsonObject{{"ok", true}, {"data", windowsToJson(windows)}}; + }); +} + +QJsonObject DebugServer::handleClients() +{ + return sessionRequest([this](Session &session) { + QList clients; + if (!waitSlot(session.replica->getClients(), m_timeoutMs, &clients)) + return QJsonObject{{"ok", false}, {"error", "getClients() failed"}}; + return QJsonObject{{"ok", true}, {"data", clientsToJson(clients)}}; + }); +} + +QJsonObject DebugServer::handleIdle() +{ + return sessionRequest([this](Session &session) { + IdleInfo info; + if (!waitSlot(session.replica->getIdleInfo(), m_timeoutMs, &info)) + return QJsonObject{{"ok", false}, {"error", "getIdleInfo() failed"}}; + return QJsonObject{{"ok", true}, {"data", idleToJson(info)}}; + }); +} + +QJsonObject DebugServer::handleNoAuth() +{ + return sessionRequest([this](Session &session) { + bool ok = false; + if (!waitSlot(session.replica->requestNoAuth(), m_timeoutMs, &ok)) + return QJsonObject{{"ok", false}, {"error", "requestNoAuth() failed"}}; + if (!ok) { + return QJsonObject{{"ok", false}, + {"error", "the compositor can only open a runtime directory " + "of its own, so a session instance keeps requiring root"}}; + } + return QJsonObject{{"ok", true}, {"data", QJsonObject{{"noAuth", true}}}}; + }); +} + +QJsonObject DebugServer::handleShortcuts() +{ + return sessionRequest([this](Session &session) { + QList shortcuts; + if (!waitSlot(session.replica->getShortcuts(), m_timeoutMs, &shortcuts)) + return QJsonObject{{"ok", false}, {"error", "getShortcuts() failed"}}; + return QJsonObject{{"ok", true}, {"data", shortcutsToJson(shortcuts)}}; + }); +} + +QJsonObject DebugServer::handleFocused() +{ + return sessionRequest([this](Session &session) { + qint64 id = 0; + if (!waitSlot(session.replica->focusedWindowId(), m_timeoutMs, &id)) + return QJsonObject{{"ok", false}, {"error", "focusedWindowId() failed"}}; + return QJsonObject{{"ok", true}, {"data", id}}; + }); +} + +QJsonObject DebugServer::handleCursorWindow() +{ + return sessionRequest([this](Session &session) { + qint64 id = 0; + if (!waitSlot(session.replica->windowUnderCursor(), m_timeoutMs, &id)) + return QJsonObject{{"ok", false}, {"error", "windowUnderCursor() failed"}}; + return QJsonObject{{"ok", true}, {"data", id}}; + }); +} + +QJsonObject DebugServer::handleScene(const QString &target) +{ + return sessionRequest([this, target](Session &session) { + qint64 id = 0; + if (!target.isEmpty()) { + bool ok = false; + id = resolveTarget(session, m_timeoutMs, target, &ok); + if (!ok) + return QJsonObject{{"ok", false}, {"error", QStringLiteral("no window matches '%1'").arg(target)}}; + } + QString tree; + if (!waitSlot(session.replica->getSceneTree(id), m_timeoutMs, &tree)) + return QJsonObject{{"ok", false}, {"error", "getSceneTree() failed"}}; + return QJsonObject{{"ok", true}, {"data", tree}}; + }); +} + +QJsonObject DebugServer::handleScene(const QHttpServerRequest &request) +{ + const auto query = request.query(); + return handleScene(query.queryItemValue("target")); +} + +QJsonObject DebugServer::handleWindow(const QString &target) +{ + if (target.isEmpty()) + return {{"ok", false}, {"error", "missing 'target'"}}; + return sessionRequest([this, target](Session &session) { + WindowInfo window; + if (!lookupWindow(session, m_timeoutMs, target, &window)) + return QJsonObject{{"ok", false}, + {"error", QStringLiteral("no window matches '%1'").arg(target)}}; + return QJsonObject{{"ok", true}, {"data", windowToJson(window)}}; + }); +} + +QJsonObject DebugServer::handleWindow(const QHttpServerRequest &request) +{ + return handleWindow(request.query().queryItemValue("target")); +} + +// The `debug` switch: the same read/write the CLI performs, minus escalation. +// This server cannot prompt for a password, so a switch that needs root fails +// with the reason instead of hanging the request on a polkit dialog. +QJsonObject DebugServer::handleDebug(int want) +{ + uid_t uid = ::geteuid(); + QString error; + if (!treelandDebugTargetUid(&uid, &error)) + return {{"ok", false}, {"error", error}}; + const bool rootNeeded = uid != ::geteuid() && ::geteuid() != 0; + if (want >= 0 && rootNeeded) { + return {{"ok", false}, + {"error", QStringLiteral("the compositor runs as %1 (uid %2), so its switch can " + "only be written as that user or as root; run " + "`treeland-debug debug %3` there") + .arg(treelandUserName(uid)) + .arg(uid) + .arg(want == 1 ? QStringLiteral("on") : QStringLiteral("off"))}}; + } + bool enabled = false; + // shortcut: dde-dconfig is called synchronously here, so this request holds + // the server's single event loop (live subscriptions included); the budget + // below covers the whole write, which is two dde-dconfig runs (set, then + // read back), so each gets half of it. Make it async if it ever needs more. + constexpr int kSwitchTimeoutMs = 3000; + if (!treelandRemoteDebugSwitch(uid, want, &enabled, &error, kSwitchTimeoutMs / 2)) + return {{"ok", false}, {"error", error}}; + return {{"ok", true}, {"data", QJsonObject{{"enabled", enabled}, {"uid", static_cast(uid)}}}}; +} + +QJsonObject DebugServer::handleDebug(const QHttpServerRequest &request) +{ + // A switch write is a state change, so GET only reads: a browser tab or a + // preloader must not be able to turn debugging on by fetching a URL. + if (request.method() != QHttpServerRequest::Method::Post) + return handleDebug(-1); + const QString state = + QJsonDocument::fromJson(request.body()).object().value("state").toString().toLower(); + if (state.isEmpty()) + return handleDebug(-1); + if (state != QLatin1String("on") && state != QLatin1String("off")) + return {{"ok", false}, {"error", "state must be 'on' or 'off'"}}; + return handleDebug(state == QLatin1String("on") ? 1 : 0); +} + +// --- Window control handlers --- + +// Resolves a target token (numeric id or appId) to a window id inside a +// sessionRequest lambda. Returns {ok, id} or {ok:false, error}. +static QJsonObject resolveAndControl(Session &session, int timeoutMs, + const QString &target, + const std::function &action) +{ + bool ok = false; + const qint64 id = resolveTarget(session, timeoutMs, target, &ok); + if (!ok) + return {{"ok", false}, {"error", QStringLiteral("no window matches '%1'").arg(target)}}; + bool result = action(id); + return {{"ok", true}, {"data", result}}; +} + +QJsonObject DebugServer::handleActivate(const QJsonObject &body) +{ + const QString target = targetToString(body.value("target")); + if (target.isEmpty()) + return {{"ok", false}, {"error", "missing 'target'"}}; + return sessionRequest([this, target](Session &session) { + return resolveAndControl(session, m_timeoutMs, target, [this, &session](qint64 id) { + bool result = false; + waitSlot(session.replica->activateWindow(id), m_timeoutMs, &result); + return result; + }); + }); +} + +QJsonObject DebugServer::handleActivate(const QHttpServerRequest &request) +{ + return handleActivate(QJsonDocument::fromJson(request.body()).object()); +} + +QJsonObject DebugServer::handleClose(const QJsonObject &body) +{ + const QString target = targetToString(body.value("target")); + if (target.isEmpty()) + return {{"ok", false}, {"error", "missing 'target'"}}; + return sessionRequest([this, target](Session &session) { + return resolveAndControl(session, m_timeoutMs, target, [this, &session](qint64 id) { + bool result = false; + waitSlot(session.replica->closeWindow(id), m_timeoutMs, &result); + return result; + }); + }); +} + +QJsonObject DebugServer::handleClose(const QHttpServerRequest &request) +{ + return handleClose(QJsonDocument::fromJson(request.body()).object()); +} + +QJsonObject DebugServer::handleMinimize(const QJsonObject &body) +{ + const QString target = targetToString(body.value("target")); + if (target.isEmpty()) + return {{"ok", false}, {"error", "missing 'target'"}}; + return sessionRequest([this, target](Session &session) { + return resolveAndControl(session, m_timeoutMs, target, [this, &session](qint64 id) { + bool result = false; + waitSlot(session.replica->minimizeWindow(id), m_timeoutMs, &result); + return result; + }); + }); +} + +QJsonObject DebugServer::handleMinimize(const QHttpServerRequest &request) +{ + return handleMinimize(QJsonDocument::fromJson(request.body()).object()); +} + +QJsonObject DebugServer::handleMaximize(const QJsonObject &body) +{ + const QString target = targetToString(body.value("target")); + if (target.isEmpty()) + return {{"ok", false}, {"error", "missing 'target'"}}; + return sessionRequest([this, target](Session &session) { + return resolveAndControl(session, m_timeoutMs, target, [this, &session](qint64 id) { + bool result = false; + waitSlot(session.replica->toggleMaximized(id), m_timeoutMs, &result); + return result; + }); + }); +} + +QJsonObject DebugServer::handleMaximize(const QHttpServerRequest &request) +{ + return handleMaximize(QJsonDocument::fromJson(request.body()).object()); +} + +QJsonObject DebugServer::handleFullscreen(const QJsonObject &body) +{ + const QString target = targetToString(body.value("target")); + if (target.isEmpty()) + return {{"ok", false}, {"error", "missing 'target'"}}; + return sessionRequest([this, target](Session &session) { + return resolveAndControl(session, m_timeoutMs, target, [this, &session](qint64 id) { + bool result = false; + waitSlot(session.replica->toggleFullscreen(id), m_timeoutMs, &result); + return result; + }); + }); +} + +QJsonObject DebugServer::handleFullscreen(const QHttpServerRequest &request) +{ + return handleFullscreen(QJsonDocument::fromJson(request.body()).object()); +} + +QJsonObject DebugServer::handleMove(const QJsonObject &body) +{ + const QString target = targetToString(body.value("target")); + if (target.isEmpty()) + return {{"ok", false}, {"error", "missing 'target'"}}; + const int x = body.value("x").toInt(); + const int y = body.value("y").toInt(); + return sessionRequest([this, target, x, y](Session &session) { + return resolveAndControl(session, m_timeoutMs, target, [this, &session, x, y](qint64 id) { + bool result = false; + waitSlot(session.replica->moveWindow(id, x, y), m_timeoutMs, &result); + return result; + }); + }); +} + +QJsonObject DebugServer::handleMove(const QHttpServerRequest &request) +{ + return handleMove(QJsonDocument::fromJson(request.body()).object()); +} + +QJsonObject DebugServer::handleResize(const QJsonObject &body) +{ + const QString target = targetToString(body.value("target")); + if (target.isEmpty()) + return {{"ok", false}, {"error", "missing 'target'"}}; + const int width = body.value("width").toInt(); + const int height = body.value("height").toInt(); + return sessionRequest([this, target, width, height](Session &session) { + return resolveAndControl(session, m_timeoutMs, target, [this, &session, width, height](qint64 id) { + bool result = false; + waitSlot(session.replica->resizeWindow(id, width, height), m_timeoutMs, &result); + return result; + }); + }); +} + +QJsonObject DebugServer::handleResize(const QHttpServerRequest &request) +{ + return handleResize(QJsonDocument::fromJson(request.body()).object()); +} + +QJsonObject DebugServer::handleWorkspace(const QJsonObject &body) +{ + const QString target = targetToString(body.value("target")); + if (target.isEmpty()) + return {{"ok", false}, {"error", "missing 'target'"}}; + const int workspaceId = body.value("workspaceId").toInt(); + return sessionRequest([this, target, workspaceId](Session &session) { + return resolveAndControl(session, m_timeoutMs, target, [this, &session, workspaceId](qint64 id) { + bool result = false; + waitSlot(session.replica->setWindowWorkspace(id, workspaceId), m_timeoutMs, &result); + return result; + }); + }); +} + +QJsonObject DebugServer::handleWorkspace(const QHttpServerRequest &request) +{ + return handleWorkspace(QJsonDocument::fromJson(request.body()).object()); +} + +// --- Input / event handlers --- + +QJsonObject DebugServer::handleMoveCursor(const QJsonObject &body) +{ + if (!body.contains("x") || !body.contains("y")) + return {{"ok", false}, {"error", "missing 'x' or 'y'"}}; + const double x = body.value("x").toDouble(); + const double y = body.value("y").toDouble(); + return sessionRequest([this, x, y](Session &session) { + bool result = false; + if (!waitSlot(session.replica->moveCursor(QPointF(x, y)), m_timeoutMs, &result)) + return QJsonObject{{"ok", false}, {"error", "moveCursor() failed"}}; + return QJsonObject{{"ok", true}, {"data", result}}; + }); +} + +QJsonObject DebugServer::handleMoveCursor(const QHttpServerRequest &request) +{ + return handleMoveCursor(QJsonDocument::fromJson(request.body()).object()); +} + +QJsonObject DebugServer::handleEventMotion(const QJsonObject &body) +{ + if (!body.contains("x") || !body.contains("y")) + return {{"ok", false}, {"error", "missing 'x' or 'y'"}}; + const double x = body.value("x").toDouble(); + const double y = body.value("y").toDouble(); + return sessionRequest([this, x, y](Session &session) { + bool result = false; + if (!waitSlot(session.replica->moveCursor(QPointF(x, y)), m_timeoutMs, &result)) + return QJsonObject{{"ok", false}, {"error", "moveCursor() failed"}}; + return QJsonObject{{"ok", true}, {"data", result}}; + }); +} + +QJsonObject DebugServer::handleEventMotion(const QHttpServerRequest &request) +{ + return handleEventMotion(QJsonDocument::fromJson(request.body()).object()); +} + +QJsonObject DebugServer::handleEventButton(const QJsonObject &body) +{ + const QString buttonName = body.value("button").toString(); + if (buttonName.isEmpty()) + return {{"ok", false}, {"error", "missing 'button'"}}; + bool buttonOk = false; + const int code = buttonCode(buttonName, &buttonOk); + if (!buttonOk) + return {{"ok", false}, {"error", QStringLiteral("unknown button '%1'").arg(buttonName)}}; + const QString action = body.value("action").toString("click"); + return sessionRequest([this, code, action](Session &session) { + bool result = false; + if (action == "press") { + if (!waitSlot(session.replica->sendPointerButton(code, true), m_timeoutMs, &result)) + return QJsonObject{{"ok", false}, {"error", "sendPointerButton() failed"}}; + } else if (action == "release") { + if (!waitSlot(session.replica->sendPointerButton(code, false), m_timeoutMs, &result)) + return QJsonObject{{"ok", false}, {"error", "sendPointerButton() failed"}}; + } else { + bool r1 = false, r2 = false; + if (!waitSlot(session.replica->sendPointerButton(code, true), m_timeoutMs, &r1)) + return QJsonObject{{"ok", false}, {"error", "sendPointerButton() failed"}}; + if (!waitSlot(session.replica->sendPointerButton(code, false), m_timeoutMs, &r2)) + return QJsonObject{{"ok", false}, {"error", "sendPointerButton() failed"}}; + result = r1 && r2; + } + return QJsonObject{{"ok", true}, {"data", result}}; + }); +} + +QJsonObject DebugServer::handleEventButton(const QHttpServerRequest &request) +{ + return handleEventButton(QJsonDocument::fromJson(request.body()).object()); +} + +QJsonObject DebugServer::handleEventKey(const QJsonObject &body) +{ + const QString keyName = body.value("key").toString(); + if (keyName.isEmpty()) + return {{"ok", false}, {"error", "missing 'key'"}}; + bool keyOk = false; + const int code = keyCode(keyName, &keyOk); + if (!keyOk) + return {{"ok", false}, {"error", QStringLiteral("unknown key '%1'").arg(keyName)}}; + const QString action = body.value("action").toString("tap"); + return sessionRequest([this, code, action](Session &session) { + bool result = false; + if (action == "press") { + if (!waitSlot(session.replica->sendKey(code, true), m_timeoutMs, &result)) + return QJsonObject{{"ok", false}, {"error", "sendKey() failed"}}; + } else if (action == "release") { + if (!waitSlot(session.replica->sendKey(code, false), m_timeoutMs, &result)) + return QJsonObject{{"ok", false}, {"error", "sendKey() failed"}}; + } else { + bool r1 = false, r2 = false; + if (!waitSlot(session.replica->sendKey(code, true), m_timeoutMs, &r1)) + return QJsonObject{{"ok", false}, {"error", "sendKey() failed"}}; + if (!waitSlot(session.replica->sendKey(code, false), m_timeoutMs, &r2)) + return QJsonObject{{"ok", false}, {"error", "sendKey() failed"}}; + result = r1 && r2; + } + return QJsonObject{{"ok", true}, {"data", result}}; + }); +} + +QJsonObject DebugServer::handleEventKey(const QHttpServerRequest &request) +{ + return handleEventKey(QJsonDocument::fromJson(request.body()).object()); +} + +QJsonObject DebugServer::handleEvents(quint64 since) +{ + return sessionRequest([this, since](Session &session) { + QList events; + if (!waitSlot(session.replica->getEvents(since), m_timeoutMs, &events)) + return QJsonObject{{"ok", false}, {"error", "getEvents() failed"}}; + return QJsonObject{{"ok", true}, {"data", debugEventsToJson(events)}}; + }); +} + +QJsonObject DebugServer::handleEvents(const QHttpServerRequest &request) +{ + const auto query = request.query(); + return handleEvents(query.queryItemValue("since").toULongLong()); +} + +// --- Screenshot byte helpers --- + +DebugServer::ScreenshotBytes DebugServer::captureOutputBytes(const QString &outputName) +{ + ScreenshotBytes result; + Session session; + if (!createSession(session)) { + result.error = QStringLiteral("failed to connect to compositor: %1").arg(m_urls.join(QStringLiteral(", "))); + return result; + } + QByteArray data; + session.replica->captureOutput(outputName); + if (!waitCaptureResult(session.replica, m_timeoutMs, &data) || data.isEmpty()) { + result.error = QStringLiteral("captureOutput: no image produced (output not found or grab failed)"); + return result; + } + result.ok = true; + result.data = data; + return result; +} + +DebugServer::ScreenshotBytes DebugServer::captureWindowBytes(const QString &target) +{ + ScreenshotBytes result; + if (target.isEmpty()) { + result.error = QStringLiteral("missing 'target'"); + return result; + } + Session session; + if (!createSession(session)) { + result.error = QStringLiteral("failed to connect to compositor: %1").arg(m_urls.join(QStringLiteral(", "))); + return result; + } + bool ok = false; + const qint64 id = resolveTarget(session, m_timeoutMs, target, &ok); + if (!ok) { + result.error = QStringLiteral("no window matches '%1'").arg(target); + return result; + } + QByteArray data; + session.replica->captureWindow(id); + if (!waitCaptureResult(session.replica, m_timeoutMs, &data) || data.isEmpty()) { + result.error = QStringLiteral("captureWindow: no image produced (window not found, has no scene item, or grab failed)"); + return result; + } + result.ok = true; + result.data = data; + return result; +} + +// --- Image capture handlers --- + +QHttpServerResponse DebugServer::handleScreenshotOutput(const QHttpServerRequest &request) +{ + const auto query = request.query(); + const auto result = captureOutputBytes(query.queryItemValue("name")); + if (!result.ok) { + const auto status = result.error.startsWith("failed to connect") + ? QHttpServerResponse::StatusCode::ServiceUnavailable + : QHttpServerResponse::StatusCode::NotFound; + return QHttpServerResponse( + QJsonObject{{"ok", false}, {"error", result.error}}, status); + } + return QHttpServerResponse("image/png", result.data); +} + +QHttpServerResponse DebugServer::handleScreenshotWindow(const QHttpServerRequest &request) +{ + const auto query = request.query(); + const QString target = query.queryItemValue("target"); + if (target.isEmpty()) + return QHttpServerResponse( + QJsonObject{{"ok", false}, {"error", "missing 'target' query parameter"}}, + QHttpServerResponse::StatusCode::BadRequest); + + const auto result = captureWindowBytes(target); + if (!result.ok) { + const auto status = result.error.startsWith("failed to connect") + ? QHttpServerResponse::StatusCode::ServiceUnavailable + : QHttpServerResponse::StatusCode::NotFound; + return QHttpServerResponse( + QJsonObject{{"ok", false}, {"error", result.error}}, status); + } + return QHttpServerResponse("image/png", result.data); +} + +// --- MCP (Model Context Protocol) handlers --- + +// Builds a JSON-RPC error object. +static QJsonObject mcpJsonRpcError(const QJsonValue &id, int code, const QString &message) +{ + return { + {"jsonrpc", "2.0"}, + {"id", id}, + {"error", QJsonObject{{"code", code}, {"message", message}}} + }; +} + +// Builds a JSON-RPC success object. +static QJsonObject mcpJsonRpcResult(const QJsonValue &id, const QJsonObject &result) +{ + return { + {"jsonrpc", "2.0"}, + {"id", id}, + {"result", result} + }; +} + +QHttpServerResponse DebugServer::handleMcpPost(const QHttpServerRequest &request) +{ + // --- Accept negotiation (MCP Streamable HTTP) --- + // The client must accept either application/json or text/event-stream. + const QByteArray accept = request.headers().combinedValue( + QHttpHeaders::WellKnownHeader::Accept); + const bool acceptsJson = accept.isEmpty() || accept.contains("application/json"); + const bool acceptsSse = accept.isEmpty() || accept.contains("text/event-stream"); + if (!acceptsJson && !acceptsSse) + return addCorsHeaders(QHttpServerResponse(QHttpServerResponse::StatusCode::NotAcceptable)); + + // Respond with SSE only when the client does not accept plain JSON. + const bool useSse = !acceptsJson && acceptsSse; + + auto makeResponse = [useSse](const QJsonObject &obj) -> QHttpServerResponse { + const QByteArray body = QJsonDocument(obj).toJson(QJsonDocument::Compact); + if (useSse) { + QByteArray sse = "event: message\ndata: "; + sse += body; + sse += "\n\n"; + return addCorsHeaders(QHttpServerResponse("text/event-stream", sse)); + } + return addCorsHeaders(QHttpServerResponse("application/json", body)); + }; + + // --- Parse JSON-RPC message --- + const auto doc = QJsonDocument::fromJson(request.body()); + if (!doc.isObject()) + return makeResponse(mcpJsonRpcError(QJsonValue::Null, -32700, "Parse error")); + + const auto msg = doc.object(); + const QString method = msg.value("method").toString(); + const QJsonValue id = msg.value("id"); + const QJsonObject params = msg.value("params").toObject(); + + // Notification (no id) — acknowledge with 202 Accepted, no body. + if (id.isNull() || id.isUndefined()) + return addCorsHeaders(QHttpServerResponse(QHttpServerResponse::StatusCode::Accepted)); + + // Request (has id) — dispatch. + QJsonObject result; + if (method == "initialize") { + result = mcpInitialize(params); + } else if (method == "tools/list") { + result = mcpToolsList(); + } else if (method == "tools/call") { + result = mcpToolsCall(params); + } else if (method == "ping") { + result = QJsonObject{}; + } else { + return makeResponse(mcpJsonRpcError(id, -32601, + QStringLiteral("Method not found: %1").arg(method))); + } + + return makeResponse(mcpJsonRpcResult(id, result)); +} + +QJsonObject DebugServer::mcpInitialize(const QJsonObject ¶ms) +{ + (void)params; // client info available in params; not currently used. + return { + {"protocolVersion", "2025-06-18"}, + {"capabilities", QJsonObject{ + {"tools", QJsonObject{{"listChanged", false}}} + }}, + {"serverInfo", QJsonObject{ + {"name", "treeland-debug"}, + {"version", "1.0"} + }} + }; +} + +// Helper: builds a JSON Schema for a property that accepts string or number +// (used for window target tokens: numeric id or appId string). +static QJsonObject targetSchema(const QString &description) +{ + return QJsonObject{ + {"type", QJsonArray{"string", "number"}}, + {"description", description} + }; +} + +QJsonObject DebugServer::mcpToolsList() const +{ + const QJsonObject noArgs = QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{}}, + {"additionalProperties", false} + }; + + return QJsonObject{ + {"tools", QJsonArray{ + // --- Inspection --- + QJsonObject{ + {"name", "tree"}, + {"description", "Get the complete Treeland window layout tree: layers, workspaces, and all windows with their geometry, state, and the outputs they are on (plus the output driving their frame callbacks)."}, + {"inputSchema", noArgs} + }, + QJsonObject{ + {"name", "cursor"}, + {"description", "Get the current cursor position {x, y}."}, + {"inputSchema", noArgs} + }, + QJsonObject{ + {"name", "windows"}, + {"description", "List all toplevel windows with their id, appId, title, geometry, state, the outputs each window is on, and its framePacingOutput."}, + {"inputSchema", noArgs} + }, + QJsonObject{ + {"name", "window"}, + {"description", "Get one window in full: the same record `windows` lists, including its shell type, workspace, z-order, every output, server-side decoration rects, frame counter, damage and input/opaque regions."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{ + {"target", targetSchema("Window id (number) or appId (string).")} + }}, + {"required", QJsonArray{"target"}}, + {"additionalProperties", false} + }} + }, + QJsonObject{ + {"name", "debug"}, + {"description", "Read treeland's remoteDebug switch, or turn it on/off with 'state'. Writing the switch of a compositor running as another user needs root, which this server cannot obtain: it reports the requirement as an error instead of prompting."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{ + {"state", QJsonObject{ + {"type", "string"}, + {"enum", QJsonArray{"on", "off"}}, + {"description", "Omit to read the switch."} + }} + }}, + {"additionalProperties", false} + }} + }, + QJsonObject{ + {"name", "no-auth"}, + {"description", "Let any local user connect to this debug socket for 30 minutes without authentication; every later call extends the window, an idle half hour closes it. Refused by a session instance, which keeps requiring root."}, + {"inputSchema", noArgs} + }, + QJsonObject{ + {"name", "clients"}, + {"description", "List all connected Wayland clients and the windows each owns (pid, executable, command line), with each window's outputs and framePacingOutput."}, + {"inputSchema", noArgs} + }, + QJsonObject{ + {"name", "idle"}, + {"description", "Get the compositor idle state: milliseconds since the last input activity, whether idle notification is currently inhibited, and every idle-inhibit source (zwp_idle_inhibit surface or treeland_screensaver inhibit) with its pid, app id, title and how long it has been held."}, + {"inputSchema", noArgs} + }, + QJsonObject{ + {"name", "shortcuts"}, + {"description", "List the currently registered shortcuts (key bindings and touchpad gestures) with their name, trigger, action and flags."}, + {"inputSchema", noArgs} + }, + QJsonObject{ + {"name", "focused"}, + {"description", "Get the id of the currently focused window."}, + {"inputSchema", noArgs} + }, + QJsonObject{ + {"name", "cursor_window"}, + {"description", "Get the id of the window currently under the cursor."}, + {"inputSchema", noArgs} + }, + QJsonObject{ + {"name", "scene"}, + {"description", "Dump the QtQuick scene tree of a specific window (by id or appId), or the whole render scene if no target is given. Useful for inspecting menus, popups and decorations."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{ + {"target", targetSchema("Window id (number) or appId (string). Omit for the whole scene.")} + }}, + {"additionalProperties", false} + }} + }, + QJsonObject{ + {"name", "events"}, + {"description", "Get debug events (input, window lifecycle, etc.) since a given sequence number."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{ + {"since", QJsonObject{{"type", "integer"}, {"description", "Return events after this sequence number. Use 0 for all recent events."}, {"default", 0}}} + }}, + {"additionalProperties", false} + }} + }, + // --- Window control --- + QJsonObject{ + {"name", "activate"}, + {"description", "Activate (focus) a window."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{{"target", targetSchema("Window id or appId.")}}}, + {"required", QJsonArray{"target"}}, + {"additionalProperties", false} + }} + }, + QJsonObject{ + {"name", "close"}, + {"description", "Close a window."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{{"target", targetSchema("Window id or appId.")}}}, + {"required", QJsonArray{"target"}}, + {"additionalProperties", false} + }} + }, + QJsonObject{ + {"name", "minimize"}, + {"description", "Minimize a window."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{{"target", targetSchema("Window id or appId.")}}}, + {"required", QJsonArray{"target"}}, + {"additionalProperties", false} + }} + }, + QJsonObject{ + {"name", "maximize"}, + {"description", "Toggle the maximized state of a window."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{{"target", targetSchema("Window id or appId.")}}}, + {"required", QJsonArray{"target"}}, + {"additionalProperties", false} + }} + }, + QJsonObject{ + {"name", "fullscreen"}, + {"description", "Toggle the fullscreen state of a window."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{{"target", targetSchema("Window id or appId.")}}}, + {"required", QJsonArray{"target"}}, + {"additionalProperties", false} + }} + }, + QJsonObject{ + {"name", "move"}, + {"description", "Move a window to (x, y)."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{ + {"target", targetSchema("Window id or appId.")}, + {"x", QJsonObject{{"type", "integer"}, {"description", "X coordinate."}}}, + {"y", QJsonObject{{"type", "integer"}, {"description", "Y coordinate."}}} + }}, + {"required", QJsonArray{"target", "x", "y"}}, + {"additionalProperties", false} + }} + }, + QJsonObject{ + {"name", "resize"}, + {"description", "Resize a window to width × height."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{ + {"target", targetSchema("Window id or appId.")}, + {"width", QJsonObject{{"type", "integer"}, {"description", "New width in pixels."}}}, + {"height", QJsonObject{{"type", "integer"}, {"description", "New height in pixels."}}} + }}, + {"required", QJsonArray{"target", "width", "height"}}, + {"additionalProperties", false} + }} + }, + QJsonObject{ + {"name", "workspace"}, + {"description", "Move a window to a different workspace."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{ + {"target", targetSchema("Window id or appId.")}, + {"workspaceId", QJsonObject{{"type", "integer"}, {"description", "Destination workspace id."}}} + }}, + {"required", QJsonArray{"target", "workspaceId"}}, + {"additionalProperties", false} + }} + }, + // --- Input / event injection --- + QJsonObject{ + {"name", "move_cursor"}, + {"description", "Move the cursor to (x, y)."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{ + {"x", QJsonObject{{"type", "number"}, {"description", "X coordinate."}}}, + {"y", QJsonObject{{"type", "number"}, {"description", "Y coordinate."}}} + }}, + {"required", QJsonArray{"x", "y"}}, + {"additionalProperties", false} + }} + }, + QJsonObject{ + {"name", "event_motion"}, + {"description", "Send a pointer motion event (move cursor to x, y)."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{ + {"x", QJsonObject{{"type", "number"}, {"description", "X coordinate."}}}, + {"y", QJsonObject{{"type", "number"}, {"description", "Y coordinate."}}} + }}, + {"required", QJsonArray{"x", "y"}}, + {"additionalProperties", false} + }} + }, + QJsonObject{ + {"name", "event_button"}, + {"description", "Send a pointer button event. Button can be 'left', 'right', 'middle' or a raw Linux input code."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{ + {"button", QJsonObject{{"type", "string"}, {"description", "left | right | middle | "}}}, + {"action", QJsonObject{{"type", "string"}, {"enum", QJsonArray{"press", "release", "click"}}, {"default", "click"}}} + }}, + {"required", QJsonArray{"button"}}, + {"additionalProperties", false} + }} + }, + QJsonObject{ + {"name", "event_key"}, + {"description", "Send a keyboard event. Key can be a Qt::Key name (e.g. 'Escape', 'Return', 'Space', 'a') or a raw code."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{ + {"key", QJsonObject{{"type", "string"}, {"description", "Qt::Key name (Escape, Return, Space, ...) or raw code"}}}, + {"action", QJsonObject{{"type", "string"}, {"enum", QJsonArray{"press", "release", "tap"}}, {"default", "tap"}}} + }}, + {"required", QJsonArray{"key"}}, + {"additionalProperties", false} + }} + }, + // --- Screenshots --- + QJsonObject{ + {"name", "screenshot_output"}, + {"description", "Capture a screenshot of an output (screen). Returns a PNG image."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{ + {"name", QJsonObject{{"type", "string"}, {"description", "Output name. Omit for the primary output."}}} + }}, + {"additionalProperties", false} + }} + }, + QJsonObject{ + {"name", "screenshot_window"}, + {"description", "Capture a screenshot of a single window. Returns a PNG image."}, + {"inputSchema", QJsonObject{ + {"type", "object"}, + {"properties", QJsonObject{ + {"target", targetSchema("Window id or appId.")} + }}, + {"required", QJsonArray{"target"}}, + {"additionalProperties", false} + }} + } + }} + }; +} + +QJsonObject DebugServer::mcpToolsCall(const QJsonObject ¶ms) +{ + const QString name = params.value("name").toString(); + const QJsonObject args = params.value("arguments").toObject(); + bool isError = false; + QJsonArray content = mcpDispatchTool(name, args, &isError); + return QJsonObject{ + {"content", content}, + {"isError", isError} + }; +} + +QJsonArray DebugServer::mcpDispatchTool(const QString &name, const QJsonObject &args, + bool *isError) +{ + *isError = false; + + // Wraps a handler's {ok, data/error} JSON result as MCP text content. + auto formatJson = [isError](const QJsonObject &result) -> QJsonArray { + if (result.value("ok").toBool() == false) + *isError = true; + return QJsonArray{QJsonObject{ + {"type", "text"}, + {"text", QString::fromUtf8(QJsonDocument(result).toJson(QJsonDocument::Compact))} + }}; + }; + + // --- Inspection --- + if (name == "tree") + return formatJson(handleTree()); + if (name == "cursor") + return formatJson(handleCursor()); + if (name == "windows") + return formatJson(handleWindows()); + if (name == "clients") + return formatJson(handleClients()); + if (name == "idle") + return formatJson(handleIdle()); + if (name == "no-auth") + return formatJson(handleNoAuth()); + if (name == "shortcuts") + return formatJson(handleShortcuts()); + if (name == "focused") + return formatJson(handleFocused()); + if (name == "cursor_window") + return formatJson(handleCursorWindow()); + if (name == "window") + return formatJson(handleWindow(targetToString(args.value("target")))); + if (name == "scene") + return formatJson(handleScene(targetToString(args.value("target")))); + if (name == "debug") { + const QString state = args.value("state").toString().toLower(); + if (state.isEmpty()) + return formatJson(handleDebug(-1)); + if (state != QLatin1String("on") && state != QLatin1String("off")) { + *isError = true; + return QJsonArray{QJsonObject{{"type", "text"}, + {"text", "state must be 'on' or 'off'"}}}; + } + return formatJson(handleDebug(state == QLatin1String("on") ? 1 : 0)); + } + if (name == "events") + return formatJson(handleEvents(static_cast(args.value("since").toInteger()))); + + // --- Window control --- + if (name == "activate") + return formatJson(handleActivate(args)); + if (name == "close") + return formatJson(handleClose(args)); + if (name == "minimize") + return formatJson(handleMinimize(args)); + if (name == "maximize") + return formatJson(handleMaximize(args)); + if (name == "fullscreen") + return formatJson(handleFullscreen(args)); + if (name == "move") + return formatJson(handleMove(args)); + if (name == "resize") + return formatJson(handleResize(args)); + if (name == "workspace") + return formatJson(handleWorkspace(args)); + + // --- Input --- + if (name == "move_cursor") + return formatJson(handleMoveCursor(args)); + if (name == "event_motion") + return formatJson(handleEventMotion(args)); + if (name == "event_button") + return formatJson(handleEventButton(args)); + if (name == "event_key") + return formatJson(handleEventKey(args)); + + // --- Screenshots (return image content blocks) --- + if (name == "screenshot_output") { + const auto result = captureOutputBytes(args.value("name").toString()); + if (!result.ok) { + *isError = true; + return QJsonArray{QJsonObject{{"type", "text"}, {"text", result.error}}}; + } + return QJsonArray{QJsonObject{ + {"type", "image"}, + {"data", QString::fromLatin1(result.data.toBase64())}, + {"mimeType", "image/png"} + }}; + } + if (name == "screenshot_window") { + const auto result = captureWindowBytes(targetToString(args.value("target"))); + if (!result.ok) { + *isError = true; + return QJsonArray{QJsonObject{{"type", "text"}, {"text", result.error}}}; + } + return QJsonArray{QJsonObject{ + {"type", "image"}, + {"data", QString::fromLatin1(result.data.toBase64())}, + {"mimeType", "image/png"} + }}; + } + + // Unknown tool + *isError = true; + return QJsonArray{QJsonObject{ + {"type", "text"}, + {"text", QStringLiteral("Unknown tool: %1").arg(name)} + }}; +} + +// --- WebSocket handling --- + +void DebugServer::onNewWebSocketConnection() +{ + auto socket = m_httpServer.nextPendingWebSocketConnection(); + if (!socket) + return; + + QWebSocket *ws = socket.release(); + ws->setParent(this); + connect(ws, &QWebSocket::textMessageReceived, this, [this, ws](const QString &message) { + handleWebSocketMessage(ws, message); + }); + connect(ws, &QWebSocket::disconnected, this, [this, ws]() { + stopLiveSubscription(ws, QString()); + ws->deleteLater(); + }); +} + +void DebugServer::handleWebSocketMessage(QWebSocket *socket, const QString &message) +{ + const auto doc = QJsonDocument::fromJson(message.toUtf8()); + if (!doc.isObject()) { + socket->sendTextMessage(QString::fromUtf8(QJsonDocument( + QJsonObject{{"ok", false}, {"error", "expected a JSON object"}}).toJson())); + return; + } + + const auto obj = doc.object(); + const QString command = obj.value("command").toString(); + const QString id = obj.value("id").toString(); + + // Live subscriptions: subscribe/unsubscribe + if (command == "subscribe") { + const QString sub = obj.value("type").toString(); + int intervalMs = obj.value("intervalMs").toInt(1000); + if (intervalMs <= 0) + intervalMs = 1000; + + if (sub == "top") { + startLiveSubscription(socket, id, DebugCommand::Top, intervalMs); + } else if (sub == "events") { + startLiveSubscription(socket, id, DebugCommand::Events, intervalMs); + } else if (sub == "watch") { + const QString target = obj.value("target").toString(); + if (target.isEmpty()) { + socket->sendTextMessage(QString::fromUtf8(QJsonDocument( + QJsonObject{{"ok", false}, {"id", id}, {"error", "watch requires 'target'"}}).toJson())); + return; + } + // Resolve target now and store the resolved id for the subscription. + Session session; + if (!createSession(session)) { + socket->sendTextMessage(QString::fromUtf8(QJsonDocument( + QJsonObject{{"ok", false}, {"id", id}, {"error", "failed to connect"}}).toJson())); + return; + } + bool ok = false; + const qint64 windowId = resolveTarget(session, m_timeoutMs, target, &ok); + if (!ok) { + socket->sendTextMessage(QString::fromUtf8(QJsonDocument( + QJsonObject{{"ok", false}, {"id", id}, {"error", QStringLiteral("no window matches '%1'").arg(target)}}).toJson())); + return; + } + // Use a special subscription type for watch with the resolved id. + // Store in a property on the socket for the timer to read. + socket->setProperty("watchId", windowId); + startLiveSubscription(socket, id, DebugCommand::Watch, intervalMs); + } else { + socket->sendTextMessage(QString::fromUtf8(QJsonDocument( + QJsonObject{{"ok", false}, {"id", id}, {"error", "unknown subscription type"}}).toJson())); + } + return; + } + + if (command == "unsubscribe") { + stopLiveSubscription(socket, id); + socket->sendTextMessage(QString::fromUtf8(QJsonDocument( + QJsonObject{{"ok", true}, {"id", id}, {"data", "unsubscribed"}}).toJson())); + return; + } + + // One-shot commands via WebSocket — reuse the same sessionRequest logic. + QJsonObject result; + if (command == "tree") { + result = handleTree(); + } else if (command == "cursor") { + result = handleCursor(); + } else if (command == "windows") { + result = handleWindows(); + } else if (command == "clients") { + result = handleClients(); + } else if (command == "idle") { + result = handleIdle(); + } else if (command == "no-auth") { + result = handleNoAuth(); + } else if (command == "shortcuts") { + result = handleShortcuts(); + } else if (command == "focused") { + result = handleFocused(); + } else if (command == "cursor-window") { + result = handleCursorWindow(); + } else if (command == "window") { + result = handleWindow(obj.value("target").toString()); + } else if (command == "debug") { + const QString state = obj.value("state").toString().toLower(); + if (state.isEmpty()) + result = handleDebug(-1); + else if (state == QLatin1String("on") || state == QLatin1String("off")) + result = handleDebug(state == QLatin1String("on") ? 1 : 0); + else + result = QJsonObject{{"ok", false}, {"error", "state must be 'on' or 'off'"}}; + } else if (command == "scene") { + const QString target = obj.value("target").toString(); + result = sessionRequest([this, target](Session &session) { + qint64 id = 0; + if (!target.isEmpty()) { + bool ok = false; + id = resolveTarget(session, m_timeoutMs, target, &ok); + if (!ok) + return QJsonObject{{"ok", false}, {"error", QStringLiteral("no window matches '%1'").arg(target)}}; + } + QString tree; + if (!waitSlot(session.replica->getSceneTree(id), m_timeoutMs, &tree)) + return QJsonObject{{"ok", false}, {"error", "getSceneTree() failed"}}; + return QJsonObject{{"ok", true}, {"data", tree}}; + }); + } else if (command == "activate" || command == "close" || command == "minimize" + || command == "maximize" || command == "fullscreen" || command == "move" + || command == "resize" || command == "workspace") { + // These need a target and optional params from the message body. + const QHttpServerRequest *fakeRequest = nullptr; + (void)fakeRequest; + // Build a ParseResult-like path: reuse sessionRequest with the params. + result = sessionRequest([this, command, obj](Session &session) { + const QString target = obj.value("target").toString(); + if (target.isEmpty()) + return QJsonObject{{"ok", false}, {"error", "missing 'target'"}}; + bool ok = false; + const qint64 winId = resolveTarget(session, m_timeoutMs, target, &ok); + if (!ok) + return QJsonObject{{"ok", false}, {"error", QStringLiteral("no window matches '%1'").arg(target)}}; + bool res = false; + if (command == "activate") + waitSlot(session.replica->activateWindow(winId), m_timeoutMs, &res); + else if (command == "close") + waitSlot(session.replica->closeWindow(winId), m_timeoutMs, &res); + else if (command == "minimize") + waitSlot(session.replica->minimizeWindow(winId), m_timeoutMs, &res); + else if (command == "maximize") + waitSlot(session.replica->toggleMaximized(winId), m_timeoutMs, &res); + else if (command == "fullscreen") + waitSlot(session.replica->toggleFullscreen(winId), m_timeoutMs, &res); + else if (command == "move") { + const int x = obj.value("x").toInt(); + const int y = obj.value("y").toInt(); + waitSlot(session.replica->moveWindow(winId, x, y), m_timeoutMs, &res); + } else if (command == "resize") { + const int w = obj.value("width").toInt(); + const int h = obj.value("height").toInt(); + waitSlot(session.replica->resizeWindow(winId, w, h), m_timeoutMs, &res); + } else if (command == "workspace") { + const int wsId = obj.value("workspaceId").toInt(); + waitSlot(session.replica->setWindowWorkspace(winId, wsId), m_timeoutMs, &res); + } + return QJsonObject{{"ok", true}, {"data", res}}; + }); + } else if (command == "move-cursor" || command == "event-motion") { + const double x = obj.value("x").toDouble(); + const double y = obj.value("y").toDouble(); + result = sessionRequest([this, x, y](Session &session) { + bool res = false; + if (!waitSlot(session.replica->moveCursor(QPointF(x, y)), m_timeoutMs, &res)) + return QJsonObject{{"ok", false}, {"error", "moveCursor() failed"}}; + return QJsonObject{{"ok", true}, {"data", res}}; + }); + } else if (command == "event-button") { + const QString buttonName = obj.value("button").toString(); + if (buttonName.isEmpty()) { + result = {{"ok", false}, {"error", "missing 'button'"}}; + } else { + bool btnOk = false; + const int code = buttonCode(buttonName, &btnOk); + if (!btnOk) { + result = {{"ok", false}, {"error", QStringLiteral("unknown button '%1'").arg(buttonName)}}; + } else { + const QString action = obj.value("action").toString("click"); + result = sessionRequest([this, code, action](Session &session) { + bool res = false; + if (action == "press") { + waitSlot(session.replica->sendPointerButton(code, true), m_timeoutMs, &res); + } else if (action == "release") { + waitSlot(session.replica->sendPointerButton(code, false), m_timeoutMs, &res); + } else { + bool r1 = false, r2 = false; + waitSlot(session.replica->sendPointerButton(code, true), m_timeoutMs, &r1); + waitSlot(session.replica->sendPointerButton(code, false), m_timeoutMs, &r2); + res = r1 && r2; + } + return QJsonObject{{"ok", true}, {"data", res}}; + }); + } + } + } else if (command == "event-key") { + const QString keyName = obj.value("key").toString(); + if (keyName.isEmpty()) { + result = {{"ok", false}, {"error", "missing 'key'"}}; + } else { + bool keyOk = false; + const int code = keyCode(keyName, &keyOk); + if (!keyOk) { + result = {{"ok", false}, {"error", QStringLiteral("unknown key '%1'").arg(keyName)}}; + } else { + const QString action = obj.value("action").toString("tap"); + result = sessionRequest([this, code, action](Session &session) { + bool res = false; + if (action == "press") { + waitSlot(session.replica->sendKey(code, true), m_timeoutMs, &res); + } else if (action == "release") { + waitSlot(session.replica->sendKey(code, false), m_timeoutMs, &res); + } else { + bool r1 = false, r2 = false; + waitSlot(session.replica->sendKey(code, true), m_timeoutMs, &r1); + waitSlot(session.replica->sendKey(code, false), m_timeoutMs, &r2); + res = r1 && r2; + } + return QJsonObject{{"ok", true}, {"data", res}}; + }); + } + } + } else if (command == "events") { + const quint64 since = obj.value("since").toVariant().toULongLong(); + result = sessionRequest([this, since](Session &session) { + QList events; + if (!waitSlot(session.replica->getEvents(since), m_timeoutMs, &events)) + return QJsonObject{{"ok", false}, {"error", "getEvents() failed"}}; + return QJsonObject{{"ok", true}, {"data", debugEventsToJson(events)}}; + }); + } else if (command == "screenshot-output") { + const QString outputName = obj.value("name").toString(); + Session session; + if (!createSession(session)) { + result = {{"ok", false}, {"error", "failed to connect"}}; + } else { + QByteArray data; + session.replica->captureOutput(outputName); + if (!waitCaptureResult(session.replica, m_timeoutMs, &data) || data.isEmpty()) { + result = {{"ok", false}, {"error", "captureOutput: no image produced"}}; + } else { + // Send as binary message, then a small JSON ack so the client + // can correlate via id. + socket->sendBinaryMessage(data); + result = {{"ok", true}, {"id", id}, {"data", "image sent as binary"}}; + } + } + } else if (command == "screenshot-window") { + const QString target = obj.value("target").toString(); + if (target.isEmpty()) { + result = {{"ok", false}, {"error", "missing 'target'"}}; + } else { + Session session; + if (!createSession(session)) { + result = {{"ok", false}, {"error", "failed to connect"}}; + } else { + bool ok = false; + const qint64 winId = resolveTarget(session, m_timeoutMs, target, &ok); + if (!ok) { + result = {{"ok", false}, {"error", QStringLiteral("no window matches '%1'").arg(target)}}; + } else { + QByteArray data; + session.replica->captureWindow(winId); + if (!waitCaptureResult(session.replica, m_timeoutMs, &data) || data.isEmpty()) { + result = {{"ok", false}, {"error", "captureWindow: no image produced (window not found, has no scene item, or grab failed)"}}; + } else { + socket->sendBinaryMessage(data); + result = {{"ok", true}, {"id", id}, {"data", "image sent as binary"}}; + } + } + } + } + } else { + result = {{"ok", false}, {"error", QStringLiteral("unknown command '%1'").arg(command)}}; + } + + if (!id.isEmpty()) + result["id"] = id; + socket->sendTextMessage(QString::fromUtf8(QJsonDocument(result).toJson())); +} + +void DebugServer::startLiveSubscription(QWebSocket *socket, const QString &id, + DebugCommand command, int intervalMs) +{ + // Stop any existing subscription with the same id on this socket. + stopLiveSubscription(socket, id); + + auto *timer = new QTimer(socket); + timer->setInterval(intervalMs); + + // Each tick creates a fresh one-shot session — no compositor connection + // persists between ticks. + connect(timer, &QTimer::timeout, this, [this, socket, command, id]() { + QJsonObject result; + if (command == DebugCommand::Top) { + result = sessionRequest([this](Session &session) { + QList clients; + if (!waitSlot(session.replica->getClients(), m_timeoutMs, &clients)) + return QJsonObject{{"ok", false}, {"error", "getClients() failed"}}; + qint64 focusId = 0, cursorId = 0; + waitSlot(session.replica->focusedWindowId(), m_timeoutMs, &focusId); + waitSlot(session.replica->windowUnderCursor(), m_timeoutMs, &cursorId); + return QJsonObject{ + {"ok", true}, + {"data", QJsonObject{ + {"clients", clientsToJson(clients)}, + {"focusedWindowId", focusId}, + {"cursorWindowId", cursorId} + }} + }; + }); + } else if (command == DebugCommand::Events) { + const quint64 since = socket->property("eventsLastSeq").toULongLong(); + result = sessionRequest([this, since, socket](Session &session) { + QList events; + if (!waitSlot(session.replica->getEvents(since), m_timeoutMs, &events)) + return QJsonObject{{"ok", false}, {"error", "getEvents() failed"}}; + quint64 lastSeq = since; + for (const auto &e : events) + lastSeq = std::max(lastSeq, e.seq()); + socket->setProperty("eventsLastSeq", lastSeq); + return QJsonObject{{"ok", true}, {"data", debugEventsToJson(events)}}; + }); + } else if (command == DebugCommand::Watch) { + const qint64 windowId = socket->property("watchId").toLongLong(); + result = sessionRequest([this, windowId](Session &session) { + QList windows; + if (!waitSlot(session.replica->getWindows(), m_timeoutMs, &windows)) + return QJsonObject{{"ok", false}, {"error", "getWindows() failed"}}; + for (const auto &w : windows) { + if (w.id() == windowId) + return QJsonObject{{"ok", true}, {"data", windowToJson(w)}}; + } + return QJsonObject{{"ok", false}, {"error", "window no longer exists"}}; + }); + } + + result["id"] = id; + result["subscription"] = true; + socket->sendTextMessage(QString::fromUtf8(QJsonDocument(result).toJson())); + }); + + // Store the timer so we can stop it later. + const QByteArray key = "sub_" + id.toUtf8(); + socket->setProperty(key.constData(), QVariant::fromValue(timer)); + + // Clean up when the socket is destroyed. + connect(socket, &QWebSocket::destroyed, timer, &QTimer::deleteLater); + + timer->start(); +} + +void DebugServer::stopLiveSubscription(QWebSocket *socket, const QString &id) +{ + // If id is empty, stop all subscriptions on this socket. + const auto names = socket->dynamicPropertyNames(); + const QByteArray prefix = id.isEmpty() ? "sub_" : ("sub_" + id.toUtf8()); + for (const QByteArray &name : names) { + if (!name.startsWith("sub_")) + continue; + if (!id.isEmpty() && name != prefix) + continue; + auto *timer = socket->property(name.constData()).value(); + if (timer) { + timer->stop(); + timer->deleteLater(); + } + socket->setProperty(name.constData(), QVariant()); + } +} diff --git a/tools/treeland-debug/debugserver.h b/tools/treeland-debug/debugserver.h new file mode 100644 index 0000000000..836e1848ad --- /dev/null +++ b/tools/treeland-debug/debugserver.h @@ -0,0 +1,128 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "debugsession.h" + +#include +#include +#include +#include + +// HTTP + WebSocket server exposing every treeland-debug capability over the +// network. Each HTTP request (and each WebSocket one-shot command) creates its +// own Session — connecting to the compositor's remote object only for the +// duration of that request, then tearing it down — so the server consumes no +// compositor-side resources while idle. Live WebSocket subscriptions (top, +// events, watch) hold a Session open only for the lifetime of the subscription. +class DebugServer : public QObject +{ + Q_OBJECT + +public: + explicit DebugServer(const QStringList &urls, const QString &name, int timeoutMs, + QObject *parent = nullptr); + + // Binds the HTTP and WebSocket listener to @p host:@p port. Returns true + // on success. + bool listen(const QString &host, int port); + +private: + // Creates and connects a fresh one-shot Session. Returns true on success. + bool createSession(Session &session); + + // Helper: runs a Session-scoped RPC and returns the JSON result object + // {ok, data} or {ok:false, error}. Used by HTTP handlers that don't need + // custom serialization. + QJsonObject sessionRequest( + const std::function &work); + + // --- HTTP route handlers (inspection) --- + QJsonObject handleTree(); + QJsonObject handleCursor(); + QJsonObject handleWindows(); + QJsonObject handleClients(); + QJsonObject handleIdle(); + QJsonObject handleShortcuts(); + QJsonObject handleFocused(); + QJsonObject handleCursorWindow(); + QJsonObject handleScene(const QHttpServerRequest &request); + QJsonObject handleWindow(const QHttpServerRequest &request); + QJsonObject handleNoAuth(); + // GET reports the switch, POST {"state":"on|off"} writes it (no escalation). + QJsonObject handleDebug(const QHttpServerRequest &request); + + // --- HTTP route handlers (window control) --- + QJsonObject handleActivate(const QHttpServerRequest &request); + QJsonObject handleClose(const QHttpServerRequest &request); + QJsonObject handleMinimize(const QHttpServerRequest &request); + QJsonObject handleMaximize(const QHttpServerRequest &request); + QJsonObject handleFullscreen(const QHttpServerRequest &request); + QJsonObject handleMove(const QHttpServerRequest &request); + QJsonObject handleResize(const QHttpServerRequest &request); + QJsonObject handleWorkspace(const QHttpServerRequest &request); + + // --- HTTP route handlers (input / events) --- + QJsonObject handleMoveCursor(const QHttpServerRequest &request); + QJsonObject handleEventMotion(const QHttpServerRequest &request); + QJsonObject handleEventButton(const QHttpServerRequest &request); + QJsonObject handleEventKey(const QHttpServerRequest &request); + QJsonObject handleEvents(const QHttpServerRequest &request); + + // --- HTTP route handlers (image capture, return raw PNG) --- + QHttpServerResponse handleScreenshotOutput(const QHttpServerRequest &request); + QHttpServerResponse handleScreenshotWindow(const QHttpServerRequest &request); + + // --- Internal handler overloads (JSON-body / param-based) --- + // Used by both the HTTP POST routes and the MCP tools/call dispatcher so + // that parameter extraction is not tied to QHttpServerRequest. + QJsonObject handleScene(const QString &target); + QJsonObject handleWindow(const QString &target); + // @p want is -1 to read the switch, 1/0 to turn it on/off. + QJsonObject handleDebug(int want); + QJsonObject handleActivate(const QJsonObject &body); + QJsonObject handleClose(const QJsonObject &body); + QJsonObject handleMinimize(const QJsonObject &body); + QJsonObject handleMaximize(const QJsonObject &body); + QJsonObject handleFullscreen(const QJsonObject &body); + QJsonObject handleMove(const QJsonObject &body); + QJsonObject handleResize(const QJsonObject &body); + QJsonObject handleWorkspace(const QJsonObject &body); + QJsonObject handleMoveCursor(const QJsonObject &body); + QJsonObject handleEventMotion(const QJsonObject &body); + QJsonObject handleEventButton(const QJsonObject &body); + QJsonObject handleEventKey(const QJsonObject &body); + QJsonObject handleEvents(quint64 since); + + // --- Screenshot byte helpers (used by MCP to return base64 images) --- + struct ScreenshotBytes { + bool ok = false; + QByteArray data; + QString error; + }; + ScreenshotBytes captureOutputBytes(const QString &outputName); + ScreenshotBytes captureWindowBytes(const QString &target); + + // --- MCP (Model Context Protocol) over Streamable HTTP --- + QHttpServerResponse handleMcpPost(const QHttpServerRequest &request); + QJsonObject mcpInitialize(const QJsonObject ¶ms); + QJsonObject mcpToolsList() const; + QJsonObject mcpToolsCall(const QJsonObject ¶ms); + // Dispatches one tool call, returning the MCP content array and setting + // *isError when the tool reported a failure. + QJsonArray mcpDispatchTool(const QString &name, const QJsonObject &args, + bool *isError); + + // --- WebSocket handling --- + void onNewWebSocketConnection(); + void handleWebSocketMessage(class QWebSocket *socket, const QString &message); + void startLiveSubscription(QWebSocket *socket, const QString &id, + DebugCommand command, int intervalMs); + void stopLiveSubscription(QWebSocket *socket, const QString &id); + QStringList m_urls; + QString m_name; + int m_timeoutMs; + QHttpServer m_httpServer; +}; + diff --git a/tools/treeland-debug/debugsession.cpp b/tools/treeland-debug/debugsession.cpp new file mode 100644 index 0000000000..733e36ecba --- /dev/null +++ b/tools/treeland-debug/debugsession.cpp @@ -0,0 +1,364 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "debugsession.h" + +#include +#include +#include +#include + +bool connectSession(Session &session, const QString &url, const QString &name, int timeoutMs) +{ + if (!session.node.connectToNode(QUrl(url))) + return false; + session.replica = session.node.acquire(name); + return session.replica->waitForSource(timeoutMs); +} + +bool connectSession(Session &session, const QStringList &urls, + const QString &name, int timeoutMs, + QString *connectedUrl) +{ + if (urls.isEmpty()) + return false; + + // Try each URL with an independent QRemoteObjectNode so a previously- + // failed connection cannot cause a false success on a later candidate + // (the replica watches *all* connected nodes — a shared node would + // let a late-becoming-reachable earlier URL succeed while we think we + // are probing a later one). + // + // Share the caller's timeout between the candidates still to be tried, but + // never probe with less than probeTimeout: a live local socket answers in + // milliseconds, so a slice only bounds the wait, while a socket that cannot + // answer costs its whole slice either way (the replica waits for a source that + // never arrives). A larger slice also lets a compositor that publishes its + // source a moment after the client starts still be found. Charging only the + // time a probe actually spent keeps the later slices large, and the slice is + // never zero — handing the leftovers of the earlier dead sockets to the + // preferred instance made it skip a healthy debug instance for the release one. + constexpr int probeTimeout = 3000; + int remaining = timeoutMs; + QElapsedTimer probeTimer; + + for (int i = 0; i < urls.size(); ++i) { + const int candidatesLeft = urls.size() - i; + const int t = qMax(probeTimeout, remaining / candidatesLeft); + + QRemoteObjectNode probeNode; + if (!probeNode.connectToNode(QUrl(urls.at(i)))) + continue; // malformed URL + + probeTimer.restart(); + auto *replica = probeNode.acquire(name); + const bool answered = replica->waitForSource(t); + remaining -= qMin(t, int(probeTimer.elapsed())); + if (!answered) + continue; + + // Probe succeeded. Reconnect the session's own node and acquire a fresh + // replica, waiting for it to initialize before returning so callers see a + // ready replica. The source was just proven live, so this is a formality + // with the same probe-sized wait. + session.node.connectToNode(QUrl(urls.at(i))); + delete session.replica; + session.replica = session.node.acquire(name); + if (session.replica->waitForSource(probeTimeout)) { + if (connectedUrl) + *connectedUrl = urls.at(i); + return true; + } + // The source vanished in between. Stop instead of trying the next + // candidate: QtRO cannot drop the connection just made, and a replica + // watches every node the session is connected to, so a source that comes + // back there could satisfy a later wait and send the commands to another + // compositor. Failing loudly is the safer answer for a race this narrow. + delete session.replica; + session.replica = nullptr; + return false; + } + return false; +} + +bool waitCaptureResult(WindowTreeRemoteReplica *replica, int timeoutMs, QByteArray *out) +{ + QEventLoop loop; + bool gotResult = false; + QByteArray result; + + auto conn = QObject::connect(replica, &WindowTreeRemoteReplica::captureResult, + [&loop, &result, &gotResult](const QByteArray &data) { + result = data; + gotResult = true; + loop.quit(); + }); + + // Overall timeout. + QTimer::singleShot(timeoutMs, &loop, &QEventLoop::quit); + + // Periodic interrupt check for live mode (Ctrl+C sets g_debugInterrupted). + QTimer interruptTimer; + interruptTimer.setSingleShot(false); + QObject::connect(&interruptTimer, &QTimer::timeout, &loop, [&loop]() { + if (g_debugInterrupted) + loop.quit(); + }); + interruptTimer.start(100); + + loop.exec(); + QObject::disconnect(conn); + + if (!gotResult) + return false; + if (out) + *out = result; + return true; +} + +// Fetches the full record of one window, addressed the same way every control +// command addresses it (numeric id or appId). Returns false when no window +// matches; @p matches receives how many windows the token matched, so a detail +// view can say when it picked one of several (`resolveTarget`'s rule). +bool lookupWindow(Session &session, int timeoutMs, const QString &token, WindowInfo *out, + int *matches) +{ + QList windows; + if (!waitSlot(session.replica->getWindows(), timeoutMs, &windows)) + return false; + + bool parsed = false; + const qint64 id = token.toLongLong(&parsed); + bool found = false; + int count = 0; + for (const auto &window : windows) { + if (parsed ? window.id() == id : window.appId() == token) { + if (!found && out) + *out = window; + found = true; + ++count; + } + } + if (matches) + *matches = count; + return found; +} + +qint64 resolveTarget(Session &session, int timeoutMs, const QString &token, bool *ok) +{ + *ok = true; + bool parsed = false; + const qint64 id = token.toLongLong(&parsed); + if (parsed) + return id; + + QList windows; + if (!waitSlot(session.replica->getWindows(), timeoutMs, &windows)) { + *ok = false; + return 0; + } + for (const auto &window : windows) { + if (window.appId() == token) + return window.id(); + } + *ok = false; + return 0; +} + +void registerNamedMetatypes() +{ + WindowTreeRemoteReplica::registerMetatypes(); + qRegisterMetaType("WindowInfo"); + qRegisterMetaType>("QList"); + qRegisterMetaType("WorkspaceInfo"); + qRegisterMetaType>("QList"); + qRegisterMetaType("LayerInfo"); + qRegisterMetaType>("QList"); + qRegisterMetaType("TreelandInfo"); + qRegisterMetaType("ClientInfo"); + qRegisterMetaType>("QList"); + qRegisterMetaType("IdleInhibitor"); + qRegisterMetaType>("QList"); + qRegisterMetaType("IdleInfo"); +} + +QJsonObject windowToJson(const WindowInfo &window) +{ + return { + {"id", window.id()}, + {"appId", window.appId()}, + {"title", window.title()}, + {"output", window.output()}, + {"outputs", QJsonArray::fromStringList(window.outputs())}, + {"framePacingOutput", window.framePacingOutput()}, + {"lastLeaveOutput", window.lastLeaveOutput()}, + {"lastLeaveOutputEnabled", window.lastLeaveOutputEnabled()}, + {"lastLeaveEmptiedOutputs", window.lastLeaveEmptiedOutputs()}, + {"lastOutputsUpdateReason", window.lastOutputsUpdateReason()}, + {"lastOutputsUpdateEnabled", window.lastOutputsUpdateEnabled()}, + {"lastOutputsUpdateTotal", window.lastOutputsUpdateTotal()}, + {"lastOutputsUpdateComputed", window.lastOutputsUpdateComputed()}, + {"lastOutputsUpdateAutomatic", window.lastOutputsUpdateAutomatic()}, + {"container", window.container()}, + {"workspace", window.workspace()}, + {"layer", window.layer()}, + {"z", window.z()}, + {"type", window.type()}, + {"shellType", shellTypeName(window.type())}, + {"state", window.state()}, + {"visible", window.visible()}, + {"active", window.active()}, + {"minimized", window.minimized()}, + {"geometry", rectToJson(window.geometry())}, + {"titlebarGeometry", rectToJson(window.titlebarGeometry())}, + {"boundingRect", rectToJson(window.boundingRect())}, + {"iconGeometry", rectToJson(window.iconGeometry())}, + {"position", pointToJson(window.position())}, + {"frames", window.frames()}, + {"damage", rectToJson(window.damage())}, + {"inputRegion", rectsToJson(window.inputRegion())}, + {"opaqueRegion", rectsToJson(window.opaqueRegion())}, + }; +} + +QJsonArray windowsToJson(const QList &windows) +{ + QJsonArray result; + for (const auto &window : windows) + result.append(windowToJson(window)); + return result; +} + +QJsonObject workspaceToJson(const WorkspaceInfo &workspace) +{ + return { + {"id", workspace.id()}, + {"isActive", workspace.isActive()}, + {"windows", windowsToJson(workspace.windows())}, + }; +} + +QJsonArray workspacesToJson(const QList &workspaces) +{ + QJsonArray result; + for (const auto &workspace : workspaces) + result.append(workspaceToJson(workspace)); + return result; +} + +QJsonObject layerToJson(const LayerInfo &layer) +{ + return { + {"name", layer.name()}, + {"layer", layer.layer()}, + {"windows", windowsToJson(layer.windows())}, + {"workspaces", workspacesToJson(layer.workspaces())}, + }; +} + +QJsonArray layersToJson(const QList &layers) +{ + QJsonArray result; + for (const auto &layer : layers) + result.append(layerToJson(layer)); + return result; +} + +QJsonObject treelandInfoToJson(const TreelandInfo &info) +{ + return { + {"currentMode", info.currentMode()}, + {"layers", layersToJson(info.layers())}, + }; +} + +QJsonObject clientToJson(const ClientInfo &client) +{ + return { + {"id", client.id()}, + {"appId", client.appId()}, + {"pid", client.pid()}, + {"executable", client.executable()}, + {"command", client.command()}, + {"windows", windowsToJson(client.windows())}, + }; +} + +QJsonArray clientsToJson(const QList &clients) +{ + QJsonArray result; + for (const auto &client : clients) + result.append(clientToJson(client)); + return result; +} + +QJsonObject shortcutToJson(const ShortcutInfo &shortcut) +{ + return { + {"name", shortcut.name()}, + {"type", shortcut.type()}, + {"key", shortcut.key()}, + {"flags", static_cast(shortcut.flags())}, + {"action", shortcut.action()}, + {"fingers", static_cast(shortcut.fingers())}, + {"direction", shortcut.direction()}, + }; +} + +QJsonArray shortcutsToJson(const QList &shortcuts) +{ + QJsonArray result; + for (const auto &shortcut : shortcuts) + result.append(shortcutToJson(shortcut)); + return result; +} + +QJsonObject debugEventToJson(const DebugEvent &event) +{ + return { + {"seq", static_cast(event.seq())}, + {"type", event.type()}, + {"target", event.target()}, + {"detail", event.detail()}, + {"timestampMs", static_cast(event.timestampMs())}, + }; +} + +QJsonArray debugEventsToJson(const QList &events) +{ + QJsonArray result; + for (const auto &event : events) + result.append(debugEventToJson(event)); + return result; +} + +QJsonObject idleInhibitorToJson(const IdleInhibitor &inhibitor) +{ + return { + {"surfaceId", inhibitor.surfaceId()}, + {"kind", inhibitor.kind()}, + {"appId", inhibitor.appId()}, + {"title", inhibitor.title()}, + {"pid", inhibitor.pid()}, + {"executable", inhibitor.executable()}, + {"command", inhibitor.command()}, + {"appName", inhibitor.appName()}, + {"reason", inhibitor.reason()}, + {"active", inhibitor.active()}, + {"heldMs", static_cast(inhibitor.heldMs())}, + }; +} + +QJsonObject idleToJson(const IdleInfo &info) +{ + QJsonArray inhibitors; + for (const auto &inhibitor : info.inhibitors()) + inhibitors.append(idleInhibitorToJson(inhibitor)); + + return { + {"inhibited", info.inhibited()}, + {"screensaverInhibited", info.screensaverInhibited()}, + {"idleMs", static_cast(info.idleMs())}, + {"inhibitors", inhibitors}, + }; +} diff --git a/tools/treeland-debug/debugsession.h b/tools/treeland-debug/debugsession.h new file mode 100644 index 0000000000..9deec4fc59 --- /dev/null +++ b/tools/treeland-debug/debugsession.h @@ -0,0 +1,105 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "debughelpers.h" + +#include +#include +#include +#include +#include + +#include "rep_treeland_windowtree_replica.h" + +// A connection to the running Treeland debug Remote Object. +struct Session +{ + QRemoteObjectNode node; + WindowTreeRemoteReplica *replica = nullptr; +}; + +// Connects @p session to the Treeland debug remote object at @p url with the +// given @p name. Returns true on success. +bool connectSession(Session &session, const QString &url, const QString &name, int timeoutMs); + +// Tries each URL in @p urls in order, connecting to the first whose source is +// reachable. Each candidate is probed with @p timeoutMs shared between the +// candidates still to be tried, but never for less than one short probe, so a +// dead socket delays the preferred instance without starving it; discovery can +// therefore take up to @p timeoutMs plus one probe per candidate. If +// @p connectedUrl is non-null it receives the URL that succeeded. An empty list +// returns false. +bool connectSession(Session &session, const QStringList &urls, + const QString &name, int timeoutMs, + QString *connectedUrl = nullptr); + +// Set to 1 by the SIGINT handler during interactive ("live") commands so the +// blocking waitSlot() below can break out promptly instead of being stuck in +// a single waitForFinished() until the RPC timeout. It is async-signal-safe +// (a plain sig_atomic_t store) and stays 0 outside live commands, so one-shot +// commands keep their original behaviour. +extern volatile sig_atomic_t g_debugInterrupted; + +// Waits for a typed replica slot call and stores its return value in @p out. +// The wait is polled in small chunks so a Ctrl+C during a live command (which +// sets g_debugInterrupted) breaks the wait within ~100ms instead of blocking +// until the full RPC timeout. For one-shot commands g_debugInterrupted is +// never set, so the effective behaviour is unchanged. +template +bool waitSlot(QRemoteObjectPendingReply call, int timeoutMs, T *out) +{ + const int chunk = 100; + int waited = 0; + while (!call.waitForFinished(qBound(1, timeoutMs - waited, chunk))) { + if (g_debugInterrupted) + return false; + waited += chunk; + if (waited >= timeoutMs) + return false; + } + if (call.error() != QRemoteObjectPendingCall::NoError) + return false; + if (out) + *out = call.returnValue(); + return true; +} + +// Waits for the async captureResult signal after calling captureOutput() or +// captureWindow(). Returns true if the signal was received within @p timeoutMs +// (or interrupted by Ctrl+C in live mode), storing the payload in @p out. +bool waitCaptureResult(WindowTreeRemoteReplica *replica, int timeoutMs, QByteArray *out); + +// Resolves a window target: a numeric id is used as-is, any other token is +// matched against the first window whose appId equals it. Sets *ok=false on +// failure. +qint64 resolveTarget(Session &session, int timeoutMs, const QString &token, bool *ok); + +// Fetches the full record of one window, addressed like every control command +// addresses it. Returns false when no window matches; @p matches (optional) +// receives how many windows the token matched. +bool lookupWindow(Session &session, int timeoutMs, const QString &token, WindowInfo *out, + int *matches = nullptr); + +// Registers the metatypes needed for serialising replica structs across +// the Qt RemoteObjects wire. +void registerNamedMetatypes(); + +// JSON helpers for the replica POD structs. +QJsonObject windowToJson(const WindowInfo &window); +QJsonArray windowsToJson(const QList &windows); +QJsonObject workspaceToJson(const WorkspaceInfo &workspace); +QJsonArray workspacesToJson(const QList &workspaces); +QJsonObject layerToJson(const LayerInfo &layer); +QJsonArray layersToJson(const QList &layers); +QJsonObject treelandInfoToJson(const TreelandInfo &info); +QJsonObject clientToJson(const ClientInfo &client); +QJsonArray clientsToJson(const QList &clients); +QJsonObject idleInhibitorToJson(const IdleInhibitor &inhibitor); +QJsonObject idleToJson(const IdleInfo &info); +QJsonObject shortcutToJson(const ShortcutInfo &shortcut); +QJsonArray shortcutsToJson(const QList &shortcuts); +QJsonObject debugEventToJson(const DebugEvent &event); +QJsonArray debugEventsToJson(const QList &events); + diff --git a/tools/treeland-debug/debugswitch.cpp b/tools/treeland-debug/debugswitch.cpp new file mode 100644 index 0000000000..fa75647f92 --- /dev/null +++ b/tools/treeland-debug/debugswitch.cpp @@ -0,0 +1,156 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "debugswitch.h" + +#include +#include +#include +#include + +#include +#include +#include + +QList treelandCompositorUids() +{ + QList uids; + const QDir proc(QStringLiteral("/proc")); + const QStringList entries = proc.entryList(QDir::Dirs | QDir::NoDotAndDotDot); + for (const QString &entry : entries) { + bool isPid = false; + entry.toUInt(&isPid); + if (!isPid) + continue; + const QString dir = proc.filePath(entry); + QFile comm(dir + QStringLiteral("/comm")); + if (!comm.open(QIODevice::ReadOnly) || comm.readAll().trimmed() != QByteArrayLiteral("treeland")) + continue; + struct stat st {}; + if (::stat(QFile::encodeName(dir).constData(), &st) != 0) + continue; + const uid_t uid = static_cast(st.st_uid); + if (!uids.contains(uid)) + uids.append(uid); + } + std::sort(uids.begin(), uids.end()); + return uids; +} + +QString treelandUserName(uid_t uid) +{ + if (const struct passwd *pw = ::getpwuid(uid)) + return QString::fromLocal8Bit(pw->pw_name); + return QString::number(uid); +} + +bool treelandDebugTargetUid(uid_t *uid, QString *error) +{ + // A session instance normally runs as whoever asks and may share the machine + // with a global service, so our own uid wins when a compositor has it. + const QList uids = treelandCompositorUids(); + const uid_t self = ::geteuid(); + if (uids.contains(self)) { + *uid = self; + return true; + } + if (uids.size() == 1) { + *uid = uids.first(); + return true; + } + if (uids.size() > 1) { + QStringList names; + for (const uid_t candidate : uids) + names.append(QStringLiteral("%1 (uid %2)").arg(treelandUserName(candidate)).arg(candidate)); + *error = QStringLiteral("several compositors are running, as %1; the switch is " + "per user, so write the one you mean with `dde-dconfig -u " + " set -a org.deepin.dde.treeland -r " + "org.deepin.dde.treeland -k remoteDebug -v true|false`") + .arg(names.join(QStringLiteral(", "))); + return false; + } + *uid = self; + return true; +} + +namespace { + +// Runs `dde-dconfig`, the DTK CLI for the config manager on the system bus. +// `-u ` names the user whose app-scoped keys are meant, which is how root +// writes another user's switch. Returns false only when the process could not +// be run at all: the tool reports refusals as text and still exits 0, so every +// caller judges the result by the value it reads back. +bool runDConfig(const QStringList &args, int timeoutMs, QString *out, QString *err) +{ + const QString exe = QStandardPaths::findExecutable(QStringLiteral("dde-dconfig")); + if (exe.isEmpty()) { + *err = QStringLiteral("dde-dconfig was not found — install the dde-dconfig package"); + return false; + } + QProcess process; + process.start(exe, args); + if (!process.waitForStarted(qMin(5000, timeoutMs))) { + *err = process.errorString(); + return false; + } + if (!process.waitForFinished(timeoutMs)) { + process.kill(); + process.waitForFinished(); + *err = QStringLiteral("dde-dconfig did not answer"); + return false; + } + *out = QString::fromLocal8Bit(process.readAllStandardOutput()).trimmed(); + *err = QString::fromLocal8Bit(process.readAllStandardError()).trimmed(); + return true; +} + +QStringList remoteDebugArgs(uid_t uid, const QString &action) +{ + return { QStringLiteral("-u"), + QString::number(uid), + action, + QStringLiteral("-a"), + QStringLiteral("org.deepin.dde.treeland"), + QStringLiteral("-r"), + QStringLiteral("org.deepin.dde.treeland"), + QStringLiteral("-k"), + QStringLiteral("remoteDebug") }; +} + +QString dconfigError(const QString &what, const QString &out, const QString &err) +{ + const QString detail = (out + QLatin1Char(' ') + err).trimmed(); + return detail.isEmpty() ? what : what + QStringLiteral(": ") + detail; +} + +} // namespace + +bool treelandRemoteDebugSwitch(uid_t uid, int want, bool *enabled, QString *error, + int timeoutMs) +{ + QString out; + QString err; + const QString wanted = want == 1 ? QStringLiteral("true") : QStringLiteral("false"); + if (want >= 0) { + QStringList setArgs = remoteDebugArgs(uid, QStringLiteral("set")); + setArgs.append({ QStringLiteral("-v"), wanted }); + if (!runDConfig(setArgs, timeoutMs, &out, &err)) { + *error = dconfigError(QStringLiteral("cannot run dde-dconfig"), out, err); + return false; + } + } + if (!runDConfig(remoteDebugArgs(uid, QStringLiteral("get")), timeoutMs, &out, &err)) { + *error = dconfigError(QStringLiteral("cannot run dde-dconfig"), out, err); + return false; + } + if (out != QLatin1String("true") && out != QLatin1String("false")) { + *error = dconfigError(QStringLiteral("remoteDebug is unreadable"), out, err); + return false; + } + if (want >= 0 && out != wanted) { + *error = dconfigError(QStringLiteral("the switch did not change"), out, err); + return false; + } + *enabled = out == QLatin1String("true"); + return true; +} diff --git a/tools/treeland-debug/debugswitch.h b/tools/treeland-debug/debugswitch.h new file mode 100644 index 0000000000..b101933418 --- /dev/null +++ b/tools/treeland-debug/debugswitch.h @@ -0,0 +1,38 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include +#include // geteuid(), used by the callers of treelandDebugTargetUid() + +// Treeland's `remoteDebug` master switch, shared by the `debug` command and the +// `listen` HTTP API so both read and write the same key. + +// uids of every running treeland, deduplicated and sorted. Read through /proc, +// which needs no privileges: the answer is the same before and after a polkit +// escalation, so the elevated copy writes the key of the instance the caller +// meant. +QList treelandCompositorUids(); + +QString treelandUserName(uid_t uid); + +// Picks the user whose per-user switch key matters: our own when a compositor +// runs as us, the only running compositor otherwise. Sets *error when several +// compositors run as other users -- the switch is per user, so the caller has to +// name one with dde-dconfig itself. +bool treelandDebugTargetUid(uid_t *uid, QString *error); + +// Reads the switch of @p uid (want = -1) or writes it (want = 1 on, 0 off), +// returning the value read back in *enabled. A write is verified by reading the +// key again, so a DConfig daemon that accepted but ignored it is an error. +// Escalation is the caller's job: DConfig only accepts a plain user's own key, +// so writing another user's key needs root. +// The call blocks on dde-dconfig: @p timeoutMs bounds each of the (up to two) +// invocations, so a caller running on an event loop others depend on -- the +// `listen` server -- passes a short one. +bool treelandRemoteDebugSwitch(uid_t uid, int want, bool *enabled, QString *error, + int timeoutMs = 30000); diff --git a/tools/treeland-debug/main.cpp b/tools/treeland-debug/main.cpp new file mode 100644 index 0000000000..00e4b1b51c --- /dev/null +++ b/tools/treeland-debug/main.cpp @@ -0,0 +1,1889 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +#include "debughelpers.h" + +#include "debugsession.h" +#include "debugswitch.h" +#include "shellline.h" +#ifdef TREELAND_DEBUG_LISTEN +#include "debugserver.h" +#endif + +#include "treelanddebugsocket.h" + +#include "rep_treeland_windowtree_replica.h" + +namespace { + +// Write-end of a self-pipe used by the SIGINT handler; the handler writes a +// byte here so the Qt event loop (via QSocketNotifier) can react safely. +int g_sigintWriteFd = -1; + +void sigintHandler(int) +{ + g_debugInterrupted = 1; + if (g_sigintWriteFd >= 0) { + char c = 0; + const ssize_t r = ::write(g_sigintWriteFd, &c, 1); + (void)r; + } +} + +// RAII guard that, while alive, routes SIGINT (Ctrl+C) to +// QCoreApplication::quit() instead of terminating the process. Used in the +// shell so live commands (top/events/watch) can be interrupted back to the +// REPL. Uses the self-pipe trick so the signal handler stays async-signal-safe. +class SigIntInterrupt +{ + SigIntInterrupt(const SigIntInterrupt &) = delete; + SigIntInterrupt &operator=(const SigIntInterrupt &) = delete; + +public: + SigIntInterrupt() = default; + ~SigIntInterrupt() { restore(); } + + bool install(); + void restore(); + +private: + int m_pipe[2] = {-1, -1}; + QSocketNotifier *m_notifier = nullptr; + struct sigaction m_oldAction {}; + bool m_installed = false; + QObject m_context; +}; + +bool SigIntInterrupt::install() +{ + g_debugInterrupted = 0; + if (::pipe(m_pipe) != 0) + return false; + g_sigintWriteFd = m_pipe[1]; + + m_notifier = new QSocketNotifier(m_pipe[0], QSocketNotifier::Read, &m_context); + QObject::connect(m_notifier, &QSocketNotifier::activated, &m_context, [this]() { + char buf[16]; + while (::read(m_pipe[0], buf, sizeof(buf)) > 0) { } + QCoreApplication::quit(); + }); + + struct sigaction sa {}; + sa.sa_handler = &sigintHandler; + sa.sa_flags = SA_RESTART; + sigemptyset(&sa.sa_mask); + m_installed = (::sigaction(SIGINT, &sa, &m_oldAction) == 0); + return m_installed; +} + +void SigIntInterrupt::restore() +{ + g_debugInterrupted = 0; + if (m_installed) { + ::sigaction(SIGINT, &m_oldAction, nullptr); + m_installed = false; + } + g_sigintWriteFd = -1; + if (m_notifier) + m_notifier->setEnabled(false); + if (m_pipe[0] >= 0) { + ::close(m_pipe[0]); + m_pipe[0] = -1; + } + if (m_pipe[1] >= 0) { + ::close(m_pipe[1]); + m_pipe[1] = -1; + } +} + +// Verbosity of this client's own stderr diagnostics; --log-level selects it. +// Info (the default) already hides the discovery noise, so a run says only what +// the user asked for plus where the data came from. +LogLevel g_logLevel = LogLevel::Info; + +bool logEnabled(LogLevel level) +{ + return static_cast(level) <= static_cast(g_logLevel); +} + +int fail(const QString &message) +{ + QTextStream(stderr) << "treeland-debug: " << message << Qt::endl; + return EXIT_FAILURE; +} + +void printJson(const QJsonDocument &document) +{ + QTextStream(stdout) << QString::fromUtf8(document.toJson(QJsonDocument::Indented)); +} + +// Every human-readable view follows the x11 tools' conventions, so fingers used +// to xwininfo/xprop/xdotool read them the same way: +// +// * lists (windows, clients, top, shortcuts) are a header row plus exactly one +// line per object -- no continuation lines; geometry is "WxH+X+Y"; +// * one object's detail (`window`, `idle`) is "Key: value" lines with the keys +// padded, one field per line (xwininfo); +// * nested structure (`tree`, `scene`) keeps tree branches; +// * machine output is always --json (and the same JSON the HTTP API returns). + +// Pads a field key so the values of a `Key: value` block line up. +QString fieldLine(const QString &key, const QString &value) +{ + return QStringLiteral(" %1 %2\n").arg((key + QLatin1Char(':')).leftJustified(21), value); +} + +QString yesNo(bool value) +{ + return value ? QStringLiteral("yes") : QStringLiteral("no"); +} + +// Outputs a window is drawn on, for the one-line views; '+' marks the output +// driving its frame callbacks, which those views' own '*' (active window) +// must not be confused with. +QString windowOutputsLabel(const WindowInfo &window) +{ + return outputsLabel(window.outputs(), window.framePacingOutput(), window.output()); +} + +// Column widths shared by every window table's header and rows, so the two +// cannot drift apart; kGap is the separator between two columns and is part of +// each cell's padded width, so header and rows only ever add widths. The +// `shortcuts` widths below are already whole column widths, separator included. +constexpr int kGap = 2; +constexpr int kIdWidth = 16; +constexpr int kTypeWidth = 13; +constexpr int kAppIdWidth = 22; +constexpr int kStateWidth = 10; +constexpr int kActiveWidth = 6; +constexpr int kMinWidth = 5; +constexpr int kOutputWidth = 16; +constexpr int kGeometryWidth = 18; + +// `top`'s per-interval frame delta column, right-aligned because it is a number. +constexpr int kFramesWidth = 7; + +// `shortcuts` columns. +constexpr int kShortcutNameWidth = 28; +constexpr int kShortcutTriggerWidth = 24; +constexpr int kShortcutActionWidth = 28; + +void printWindowHeader(QTextStream &out, const QString &indent) +{ + // Same widths (separator included) as printWindowRows(), so the columns + // cannot drift apart. + out << indent << QStringLiteral("ID").leftJustified(kIdWidth) + << QStringLiteral("TYPE").leftJustified(kTypeWidth + kGap) + << QStringLiteral("APP-ID").leftJustified(kAppIdWidth + kGap) + << QStringLiteral("STATE").leftJustified(kStateWidth + kGap) + << QStringLiteral("ACTIVE").leftJustified(kActiveWidth + kGap) + << QStringLiteral("MIN").leftJustified(kMinWidth + kGap) + << QStringLiteral("OUTPUT").leftJustified(kOutputWidth + kGap) + << QStringLiteral("GEOMETRY").leftJustified(kGeometryWidth + kGap) + << "TITLE\n"; +} + +// One line per window, nothing else: a list stays greppable. Everything else +// about a window (regions, SSD rects, workspace, z) lives in `window `. +void printWindowRows(QTextStream &out, const QList &windows, const QString &indent) +{ + for (const auto &window : windows) { + out << indent + << QString::number(window.id()).leftJustified(kIdWidth) + << shellTypeName(window.type()).leftJustified(kTypeWidth + kGap) + << window.appId().leftJustified(kAppIdWidth + kGap) + << stateName(window.state()).leftJustified(kStateWidth + kGap) + << yesNo(window.active()).leftJustified(kActiveWidth + kGap) + << yesNo(window.minimized()).leftJustified(kMinWidth + kGap) + << windowOutputsLabel(window).leftJustified(kOutputWidth + kGap) + << formatGeometry(window.geometry()).leftJustified(kGeometryWidth + kGap) + << window.title() << '\n'; + } +} + +void printWindowsTable(const QList &windows) +{ + QTextStream out(stdout); + printWindowHeader(out, QString()); + printWindowRows(out, windows, QString()); + // Last, so the table itself stays a contiguous block that head/tail cut + // cleanly; the legend explains the two shorthands it uses. + out << QStringLiteral(" (TYPE = shell surface type; '+' in OUTPUT marks the frame-pacing " + "output;\n GEOMETRY is WxH+X+Y; `treeland-debug window ` shows one " + "window in full)\n"); +} + +// xwininfo-style detail view of a single window: `Key: value` lines, one field +// per line. Empty fields are omitted rather than printed blank. +void printWindowDetail(const WindowInfo &w) +{ + QTextStream out(stdout); + out << QStringLiteral("Window id: %1%2\n") + .arg(w.id()) + .arg(w.title().isEmpty() ? QString() + : QStringLiteral(" \"%1\"").arg(w.title())); + out << fieldLine(QStringLiteral("App ID"), + w.appId().isEmpty() ? QStringLiteral("(none)") : w.appId()); + out << fieldLine(QStringLiteral("Shell type"), shellTypeName(w.type())); + if (!w.container().isEmpty()) + out << fieldLine(QStringLiteral("Container"), w.container()); + out << fieldLine(QStringLiteral("Layer"), + QStringLiteral("%1 Z: %2").arg(w.layer()).arg(w.z())); + out << fieldLine(QStringLiteral("Workspace"), QString::number(w.workspace())); + out << fieldLine(QStringLiteral("State"), stateName(w.state())); + out << fieldLine(QStringLiteral("Visible"), yesNo(w.visible())); + out << fieldLine(QStringLiteral("Active"), yesNo(w.active())); + out << fieldLine(QStringLiteral("Minimized"), yesNo(w.minimized())); + out << fieldLine(QStringLiteral("Output"), + w.output().isEmpty() ? QStringLiteral("(none)") : w.output()); + // Every output, unmarked: "Frame pacing" is a field of its own here, so the + // tables' '+' legend does not apply. + out << fieldLine(QStringLiteral("Outputs"), + w.outputs().isEmpty() ? QStringLiteral("(none)") + : w.outputs().join(QLatin1Char(','))); + out << fieldLine(QStringLiteral("Frame pacing"), + w.framePacingOutput().isEmpty() ? QStringLiteral("(none)") + : w.framePacingOutput()); + out << fieldLine(QStringLiteral("Geometry"), formatGeometry(w.geometry())); + out << fieldLine(QStringLiteral("Position"), + QStringLiteral("%1,%2").arg(w.position().x()).arg(w.position().y())); + if (!w.boundingRect().isEmpty()) + out << fieldLine(QStringLiteral("Bounding rect"), formatGeometry(w.boundingRect())); + if (!w.titlebarGeometry().isEmpty()) + out << fieldLine(QStringLiteral("Titlebar"), formatGeometry(w.titlebarGeometry())); + if (!w.iconGeometry().isEmpty()) + out << fieldLine(QStringLiteral("Icon"), formatGeometry(w.iconGeometry())); + out << fieldLine(QStringLiteral("Frames"), QString::number(w.frames())); + if (!w.damage().isEmpty()) + out << fieldLine(QStringLiteral("Damage"), formatGeometry(w.damage())); + out << fieldLine(QStringLiteral("Input region"), formatRegion(w.inputRegion())); + out << fieldLine(QStringLiteral("Opaque region"), formatRegion(w.opaqueRegion())); + // Why the window is on no output at all -- the question this view exists + // for. Empty means "nothing recorded", so those lines are omitted. + if (!w.lastLeaveOutput().isEmpty()) { + out << fieldLine(QStringLiteral("Last leave"), + QStringLiteral("%1 (enabled: %2, emptied outputs: %3)") + .arg(w.lastLeaveOutput(), yesNo(w.lastLeaveOutputEnabled()), + yesNo(w.lastLeaveEmptiedOutputs()))); + } + if (!w.lastOutputsUpdateReason().isEmpty()) { + out << fieldLine(QStringLiteral("Last outputs update"), + QStringLiteral("%1 (enabled: %2/%3, computed: %4, automatic: %5)") + .arg(w.lastOutputsUpdateReason()) + .arg(w.lastOutputsUpdateEnabled()) + .arg(w.lastOutputsUpdateTotal()) + .arg(w.lastOutputsUpdateComputed()) + .arg(yesNo(w.lastOutputsUpdateAutomatic()))); + } + // Last line, like xwininfo: a single token to copy into a bug report. + out << "-geometry " << formatGeometry(w.geometry()) << Qt::endl; +} + +void printClientsTable(const QList &clients) +{ + QTextStream out(stdout); + if (clients.isEmpty()) + out << "No connected clients.\n"; + for (const auto &client : clients) { + out << QStringLiteral("client 0x%1 pid=%2%3 windows=%4\n") + .arg(client.id(), 0, 16) + .arg(client.pid()) + .arg(client.appId().isEmpty() ? QString() + : QStringLiteral(" appId=%1").arg(client.appId())) + .arg(client.windows().size()); + out << QStringLiteral(" exe: %1\n") + .arg(client.executable().isEmpty() ? QStringLiteral("(unknown)") + : client.executable()); + if (!client.command().isEmpty()) + out << QStringLiteral(" cmd: %1\n").arg(client.command()); + printWindowHeader(out, QStringLiteral(" ")); + printWindowRows(out, client.windows(), QStringLiteral(" ")); + out << '\n'; + } +} + +// `idle` is a `Key: value` block like `window`, followed by one line per +// inhibitor (the list part), so it follows the same two conventions. +void printIdle(const IdleInfo &info) +{ + QTextStream out(stdout); + const auto inhibitors = info.inhibitors(); + + out << fieldLine(QStringLiteral("Idle"), + QStringLiteral("%1 since last input").arg(formatDuration(info.idleMs()))); + out << fieldLine(QStringLiteral("Inhibited"), yesNo(info.inhibited())); + out << fieldLine(QStringLiteral("Screensaver"), yesNo(info.screensaverInhibited())); + out << fieldLine(QStringLiteral("Inhibitors"), QString::number(inhibitors.size())); + + if (inhibitors.isEmpty()) + return; + + for (const auto &inhibitor : inhibitors) { + out << " [" << inhibitor.kind() << "]" + << " pid=" << inhibitor.pid() + << " appId=" << (inhibitor.appId().isEmpty() ? QStringLiteral("(unknown)") : inhibitor.appId()); + if (inhibitor.surfaceId() != 0) + out << " window=" << inhibitor.surfaceId(); + if (!inhibitor.title().isEmpty()) + out << " \"" << inhibitor.title() << "\""; + if (!inhibitor.appName().isEmpty()) + out << " app=\"" << inhibitor.appName() << "\""; + if (!inhibitor.reason().isEmpty()) + out << " reason=\"" << inhibitor.reason() << "\""; + out << " active=" << (inhibitor.active() ? "yes" : "no") + << " held=" << formatDuration(inhibitor.heldMs()); + if (!inhibitor.executable().isEmpty()) + out << " exe=" << inhibitor.executable(); + out << "\n"; + } +} + +QString shortcutFlagsText(quint32 flags) +{ + QStringList parts; + if (flags & 0x1) parts << QStringLiteral("press"); + if (flags & 0x2) parts << QStringLiteral("release"); + if (flags & 0x4) parts << QStringLiteral("repeat"); + if (parts.isEmpty()) parts << QStringLiteral("none"); + return parts.join('|'); +} + +void printShortcutsTable(const QList &shortcuts) +{ + QTextStream out(stdout); + if (shortcuts.isEmpty()) { + out << "No shortcuts registered.\n"; + return; + } + // A list, so it starts with a header row like the window tables. + out << QStringLiteral("NAME").leftJustified(kShortcutNameWidth) + << QStringLiteral("TRIGGER").leftJustified(kShortcutTriggerWidth) + << QStringLiteral("ACTION").leftJustified(kShortcutActionWidth) + << "FLAGS\n"; + for (const auto &shortcut : shortcuts) { + QString binding; + switch (shortcut.type()) { + case 0: // key + binding = shortcut.key(); + break; + case 1: // swipe + binding = QStringLiteral("swipe %1-finger %2") + .arg(shortcut.fingers()) + .arg(shortcut.direction()); + break; + default: // hold + binding = QStringLiteral("hold %1-finger").arg(shortcut.fingers()); + break; + } + out << shortcut.name().leftJustified(kShortcutNameWidth) + << binding.leftJustified(kShortcutTriggerWidth) + << shortcut.action().leftJustified(kShortcutActionWidth) + // Flags are a key-binding concept; a gesture row leaves the column + // empty rather than inventing one. + << (shortcut.type() == 0 ? shortcutFlagsText(shortcut.flags()) : QString()) << '\n'; + } +} + +// One window of the layout tree: the same fields as a table row, plus the +// active marker, laid out after the tree's branch characters. +QString treeWindowLine(const WindowInfo &w) +{ + // Wider than the table's STATE column: the tree marks a minimized window + // with a suffix instead of a column of its own. + constexpr int kTreeStateWidth = 14; + return QStringLiteral("%1%2 %3 %4 %5 %6 [%7]%8") + .arg(w.active() ? QStringLiteral("* ") : QStringLiteral(" "), + QString::number(w.id()).leftJustified(kIdWidth), + shellTypeName(w.type()).leftJustified(kTypeWidth), + w.appId().leftJustified(kAppIdWidth), + (stateName(w.state()) + (w.minimized() ? QStringLiteral("+Min") : QString())) + .leftJustified(kTreeStateWidth), + formatGeometry(w.geometry()).leftJustified(kGeometryWidth), + windowOutputsLabel(w), + w.title().isEmpty() ? QString() : QStringLiteral(" ") + w.title()); +} + +void printTree(const TreelandInfo &info) +{ + QTextStream out(stdout); + out << "Mode: " << info.currentMode() << "\n"; + out << " (per window: active id type app-id state geometry [outputs] title)\n"; + const auto layers = info.layers(); + for (int li = 0; li < layers.size(); ++li) { + const auto &layer = layers[li]; + const QString branch = (li == layers.size() - 1) ? QStringLiteral("└─ ") : QStringLiteral("├─ "); + out << branch << "Layer: " << layer.name() << " (" << layer.layer() << ")\n"; + // Print standalone windows on this layer (not in any workspace). + bool hasWorkspaces = !layer.workspaces().isEmpty(); + if (hasWorkspaces) { + const auto workspaces = layer.workspaces(); + for (int wi = 0; wi < workspaces.size(); ++wi) { + const auto &ws = workspaces[wi]; + const QString wsBranch = (li == layers.size() - 1) ? QStringLiteral(" ") : QStringLiteral("│ "); + const QString wsConn = (wi == workspaces.size() - 1) ? QStringLiteral("└─ ") : QStringLiteral("├─ "); + out << wsBranch << wsConn << "Workspace " << ws.id() + << (ws.isActive() ? " (active)" : "") << "\n"; + const auto windows = ws.windows(); + if (windows.isEmpty()) { + out << wsBranch << " └─ (no windows)\n"; + } else { + for (int i = 0; i < windows.size(); ++i) { + const QString conn = (i == windows.size() - 1) ? QStringLiteral("└─ ") : QStringLiteral("├─ "); + out << wsBranch << " " << conn << treeWindowLine(windows[i]) << "\n"; + } + } + } + } + // Print standalone windows on this layer (no workspace grouping). + const auto windows = layer.windows(); + for (int i = 0; i < windows.size(); ++i) { + const QString branch2 = (li == layers.size() - 1) ? QStringLiteral(" ") : QStringLiteral("│ "); + const QString conn = (i == windows.size() - 1) ? QStringLiteral("└─ ") : QStringLiteral("├─ "); + out << branch2 << conn << treeWindowLine(windows[i]) << "\n"; + } + } +} + +// Emit a terminal inline image preview using the kitty graphics or iTerm2 OSC +// 1337 protocol. force=true always emits (best-effort iTerm2 fallback for +// unknown terminals); force=false only emits when the terminal is detected. +bool previewImage(const QByteArray &data, bool force) +{ + if (data.isEmpty()) + return false; + + const QByteArray b64 = data.toBase64(); + QTextStream out(stdout); + + const QByteArray term = qgetenv("TERM"); + const QByteArray prog = qgetenv("TERM_PROGRAM"); + const bool isKitty = term.contains("kitty"); + const bool isItermStyle = prog == "iTerm.app" || prog == "WezTerm" + || prog == "ghostty" || prog == "konsole" || force; + + if (isKitty) { + // kitty graphics protocol — chunked transmission. + // ponytail: 4K chunk size; single-chunk is fine for most screenshots. + const int chunkSize = 4096; + for (int offset = 0; offset < b64.size(); offset += chunkSize) { + const QByteArray chunk = b64.mid(offset, chunkSize); + const bool first = (offset == 0); + const bool last = (offset + chunkSize >= b64.size()); + if (first) + out << QStringLiteral("\033_Ga=T,f=100,m=%1;").arg(last ? 0 : 1); + else + out << QStringLiteral("\033_Gm=%1;").arg(last ? 0 : 1); + out << QString::fromLatin1(chunk) << QStringLiteral("\033\\"); + } + out << "\n"; + return true; + } + + if (isItermStyle) { + // iTerm2 inline image protocol (OSC 1337). + out << QStringLiteral("\033]1337;File=inline=1;preserveAspectRatio=1:") + << QString::fromLatin1(b64) << "\a\n"; + return true; + } + + return false; +} + +QString helpText() +{ + return QStringLiteral( + "Usage: treeland-debug [global-options] [args]\n" + "\n" + "An adb-style inspector and controller for the Treeland compositor. Runs in\n" + "one-shot (non-shell) mode by default; use the `shell` command for an\n" + "interactive REPL.\n" + "\n" + "Global options:\n" + " --url Remote object host URL (default: $TREELAND_DEBUG_SOCKET,\n" + " else the build-specific socket found by probing)\n" " --name Remote object name (default: WindowTree)\n" + " --timeout-ms Request timeout in milliseconds (default: 30000)\n" + " --json Emit machine-readable JSON for every inspection command\n" + " (the same JSON the `listen` API returns)\n" + " --preview Force inline image preview in terminal (auto-detected by default)\n" + " --no-preview Disable inline image preview\n" + " --no-escalate Do not attempt polkit privilege escalation; report the\n" + " requirement instead (scripts, CI)\n" + " --log-level Verbosity of this client's own stderr diagnostics:\n" + " error, warning, info (default) or debug. Only info\n" + " and debug differ today; debug also names the socket\n" + " a fallback connection came from\n" + "\n" + "Output conventions (the same as the x11 tools, in one command):\n" + " lists are a header row plus one line per window; geometry is WxH+X+Y as in\n" + " `xwininfo -geometry`/`xdotool getwindowgeometry`; `window ` is a\n" + " `Key: value` block like `xwininfo -id`; --json (and the `listen` API) is\n" + " the machine-readable form of the same data.\n" + "\n" + "Inspection:\n" + " tree Print the complete window tree (human-readable, use --json for JSON)\n" + " cursor Print the cursor position, xdotool-style (x:N y:N window:N,\n" + " window 0 = none under the cursor)\n" + " windows List all toplevel windows, with their shell type\n" + " window Show one window in full (regions, SSD rects, frames, ...)\n" + " clients List connected Wayland clients and their windows\n" + " idle Show the idle state (time since last input) and who holds idle off\n" + " shortcuts List registered key shortcuts and gestures\n" + " top [interval-ms] Live, top-like refreshing view (default 1000ms)\n" + " events [interval-ms] Real-time input event stream (default 50ms)\n" + " watch [interval-ms] Monitor a window's changes (default 250ms)\n" + " scene [id] Dump the QtQuick scene tree (a window id, or the whole scene)\n" + "Window control (target by numeric id or appId):\n" + " activate Activate (focus) a window\n" + " close Close a window\n" + " minimize Minimize a window\n" + " maximize Toggle maximized state\n" + " fullscreen Toggle fullscreen state\n" + " move Move a window to (x, y)\n" + " resize Resize a window to (w, h)\n" + " workspace Move a window to a workspace\n" + "\n" + "Input / event injection:\n" + " move-cursor Move the cursor to (x, y)\n" + " event motion Move the cursor to (x, y)\n" + " event button [act] Send a pointer button; btn = left|right|middle|,\n" + " act = press|release|click (default click)\n" + " event key [act] Send a keyboard event; key = name|,\n" + " name = Qt::Key enum (Escape, Return, Space, ...),\n" + " act = press|release|tap (default tap)\n" + "\n" + "Image capture:\n" + " screenshot output [name] [file] Grab an output (name optional, primary by default)\n" + " screenshot window [file] Grab a single window\n" + "\n" +#ifdef TREELAND_DEBUG_LISTEN + "Server:\n" + " listen [--port ] [--host ] Start HTTP/WebSocket server (default 0.0.0.0:8080)\n" + " Every CLI capability is available as JSON over HTTP,\n" + " WebSocket and MCP; screenshots return raw PNG bytes.\n" + " `debug` writes without escalating: a switch that needs\n" + " root is reported as an error instead of prompting.\n" + "\n" +#endif + "Access:\n" + " no-auth Ask the compositor to let any local user connect for\n" + " 30 minutes (needs the connection this command arrives\n" + " on, and in a release build that is root alone); every later\n" + " call extends the window, an idle half hour closes it.\n" + "\n" + "Switch (no connection needed):\n" + " debug [on|off|status] Read or write treeland's `remoteDebug` switch\n" + " (default: status). The switch belongs to the user\n" + " treeland runs as, so writing it escalates via polkit\n" + " when that is not you. Takes effect immediately;\n" + " a debug-build compositor ignores it and is always on.\n" + "\n" + "Interactive:\n" + " shell Start an interactive REPL (shell mode)\n" + " All commands above (including top/events/watch)\n" + " work inside the REPL; Ctrl+C interrupts a live\n" + " view and returns to the prompt. Tab completes a\n" + " command and its subcommands (event, screenshot,\n" + " debug, listen), Up/Down recall earlier lines, and\n" + " Ctrl+C discards the line at the prompt.\n" + " help Show this help\n" + "\n" + "Backward compatibility: `--tree` and `--cursor` are accepted as aliases for\n" + "the `tree` and `cursor` commands.\n"); +} + +// `debug [on|off|status]`: the only command that does not go through the debug +// socket, because it is what makes a socket exist at all. The switch is a +// per-user DConfig key that treeland reads for its own user, so the uid of the +// running compositor decides which key matters, and another user's key can only +// be written as root. The key access itself lives in debugswitch.cpp, shared +// with the `listen` HTTP API. +int runDebugSwitch(const QStringList &args, const QStringList &selfArgs, bool noEscalate) +{ + const QString action = args.isEmpty() ? QStringLiteral("status") : args.first().toLower(); + const bool on = action == QLatin1String("on") || action == QLatin1String("true"); + const bool off = action == QLatin1String("off") || action == QLatin1String("false"); + if ((!on && !off && action != QLatin1String("status")) || args.size() > 1) + return fail(QStringLiteral("usage: treeland-debug debug [on|off|status]")); + + uid_t uid = ::geteuid(); + QString error; + if (!treelandDebugTargetUid(&uid, &error)) + return fail(error); + + const uid_t self = ::geteuid(); + // DConfig keeps app-scoped keys per user. The check is the daemon's own uid + // comparison (the system bus policy lets every local caller through): a plain + // user only reaches its own keys, while root may name the target with `-u`, + // so another user's key needs root. + if (uid != self && self != 0) { + if (noEscalate) { + return fail(QStringLiteral("the compositor runs as %1 (uid %2), so its switch can " + "only be written as that user or as root; remove " + "--no-escalate to escalate via polkit") + .arg(treelandUserName(uid)) + .arg(uid)); + } + const QString pkexec = QStandardPaths::findExecutable(QStringLiteral("pkexec")); + if (pkexec.isEmpty()) { + return fail(QStringLiteral("root privileges are required to write the switch of %1 " + "(uid %2), but pkexec was not found — install polkit") + .arg(treelandUserName(uid)) + .arg(uid)); + } + QStringList pkArgs; + pkArgs << QCoreApplication::applicationFilePath() << selfArgs; + return QProcess::execute(pkexec, pkArgs); + } + + bool enabled = false; + const int want = on ? 1 : (off ? 0 : -1); + if (!treelandRemoteDebugSwitch(uid, want, &enabled, &error)) + return fail(error); + + if (on) + QTextStream(stdout) << "remoteDebug is on; treeland publishes its debug socket now\n"; + else if (off) + QTextStream(stdout) << "remoteDebug is off; treeland drops its debug socket now\n"; + else + QTextStream(stdout) << "remoteDebug is " << (enabled ? "on" : "off") << " (uid " << uid + << ")\n"; + if (treelandCompositorUids().isEmpty()) + QTextStream(stderr) << "treeland-debug: no treeland is running; the switch takes effect " + "when it starts\n"; + return EXIT_SUCCESS; +} + +#ifndef TREELAND_DEBUG_DEV_BUILD +// The switch is off by default, so a release user's first run finds no socket at +// all -- a case where a polkit prompt only asks for a password that cannot help. +// Returns a hint when the switch of the compositor this caller would target reads +// back as off, and nothing when it is on or unreadable (another user's key needs +// root, which the escalation then provides). +QString remoteDebugOffHint() +{ + uid_t uid = ::geteuid(); + QString error; + if (!treelandDebugTargetUid(&uid, &error)) + return {}; + if (uid != ::geteuid() && ::geteuid() != 0) + return {}; + bool enabled = false; + if (!treelandRemoteDebugSwitch(uid, -1, &enabled, &error)) + return {}; + if (enabled) + return {}; + return QStringLiteral("treeland's `remoteDebug` switch is off, so it publishes no debug " + "socket; turn it on with `treeland-debug debug on`"); +} +#endif + +} // namespace + +// Definition of the extern declared in debugsession.h. Must live at global +// namespace scope (NOT inside the anonymous namespace above) so it denotes the +// same entity as the extern declaration — otherwise unqualified references +// would be ambiguous between the anonymous-namespace and global symbols. +volatile sig_atomic_t g_debugInterrupted = 0; + +// Executes a single one-shot command. Returns a process exit code. +static int runCommand(Session &session, int timeoutMs, bool json, int previewOpt, + const QString &command, const QStringList &args); + +// `top` runs its own event loop. +static int runTop(Session &session, int timeoutMs, int intervalMs); + +// `events` streams the compositor's real-time event stream. +static int runEvents(Session &session, int timeoutMs, int intervalMs); + +// `watch` monitors a single window's changes. +static int runWatch(Session &session, int timeoutMs, qint64 id, int intervalMs); +// `shell` reads commands from stdin. +static int runShell(Session &session, int timeoutMs, bool json, int previewOpt, + const QString &connectedUrl, const QStringList &candidateUrls); +// Dispatches the live/refreshing commands (top, events, watch). Returns true +// if @p command was recognized and run (in which case *rc holds the exit +// code); returns false otherwise. +static bool dispatchLiveCommand(Session &session, int timeoutMs, + const QString &command, const QStringList &commandArgs, + int *rc); + +// One socket's answer to "who is behind this name", asked before any wording is +// chosen: a live listener accepts at once, a socket left behind by a crashed +// instance refuses, and a release instance rejects a non-root caller with EACCES +// because its socket is mode 0000. +struct SocketProbe +{ + QString path; + bool accepted = false; + QLocalSocket::LocalSocketError error = QLocalSocket::UnknownSocketError; + QString errorString; + + bool inaccessible() const { return error == QLocalSocket::SocketAccessError; } + + // Only these two say the file outlived its listener. A timeout or an unknown + // failure can belong to a live process, so it is never offered for removal. + bool leftover() const + { + return error == QLocalSocket::ConnectionRefusedError + || error == QLocalSocket::ServerNotFoundError; + } +}; + +SocketProbe probeSocket(const QString &path) +{ + SocketProbe probe; + probe.path = path; + QLocalSocket socket; + socket.connectToServer(path); + probe.accepted = socket.waitForConnected(1000); + probe.error = socket.error(); + probe.errorString = socket.errorString(); + return probe; +} + +// The part of the diagnosis that is the same whichever socket is explained: what +// the other sockets of that group are, each in the terms that let the reader act. +static void printSocketNotes(const QStringList &leftover, const QStringList &inaccessible, + const QStringList &unanswered) +{ + if (!leftover.isEmpty()) + QTextStream(stderr) << "treeland-debug: note that nothing listens on " + << leftover.join(QStringLiteral(", ")) + << "; those files can be removed\n"; + if (!inaccessible.isEmpty()) + QTextStream(stderr) << "treeland-debug: note that " + << inaccessible.join(QStringLiteral(", ")) + << " is a release instance, whose socket only root may connect to; " + "`treeland-debug no-auth`, run as root, opens it to every user " + "for 30 minutes\n"; + if (!unanswered.isEmpty()) + QTextStream(stderr) << "treeland-debug: note that " << unanswered.join(QStringLiteral(", ")) + << " did not answer the probe; it may be a live but unresponsive " + "process, so it is not reported as removable\n"; +} + +#ifndef TREELAND_DEBUG_DEV_BUILD +// Without root, a release socket that is switched off is not merely "slower to +// answer": it is mode 0000 inside a directory we may not traverse, so +// `geteuid() != 0` can neither stat() it nor connect to it -- a probe on it just +// burns the whole --timeout-ms (30 s by default) before the password prompt that +// would make it reachable. Keep only the candidates our own credentials can +// reach. The mode is a sufficient test because the only socket modes here are +// 0000 (root only) and 0666 (open to every user, either the no-auth window or a +// debug build) -- see treelandDebugSetSocketAccess(). +// Only a release build can be restricted, so only a release build calls this; +// the definition is guarded too because the presets build with -Werror. +static QStringList reachableWithoutRoot(const QStringList &urls) +{ + QStringList reachable; + for (const QString &url : urls) { + const QString path = treelandDebugSocketPathForUrl(url); + struct stat st {}; + if (!path.isEmpty() && ::stat(QFile::encodeName(path).constData(), &st) == 0 + && (st.st_mode & S_IWOTH)) { + reachable << url; + } + } + return reachable; +} +#endif + +// Explains the failures a bare "failed to connect" cannot tell apart. It inspects +// the socket filesystem after the attempt, so the wording stays a hint about the +// state now, never a claim about what the attempt hit. +// +// Every candidate was already tried, so the socket explained is the one that is +// listening when there is one: a stale file on an earlier candidate must not hide +// the instance that answered, and an instance that only asks for root is still +// more useful to report than a stale file. +static void explainConnectFailure(const QStringList &candidateUrls, + const QStringList &attemptedUrls) +{ + struct Published + { + QString url; + QStringList paths; + }; + + // Compare the socket files behind the URLs that were actually probed, since a + // bare name and its absolute path are the same socket. Candidates skipped as + // absent do not count: a socket that appeared after the filter was applied was + // never tried, so pointing at it is still new advice. + QStringList attemptedPaths; + for (const QString &url : attemptedUrls) { + const QString path = treelandDebugSocketPathForUrl(url); + if (!path.isEmpty()) + attemptedPaths << path; + } + + QList published; + QString occupiedNonSocket; + for (const QString &candidate : candidateUrls) { + const QStringList paths = treelandDebugPublishedSocketPaths(candidate); + if (!paths.isEmpty()) { + published.append({ candidate, paths }); + } else if (occupiedNonSocket.isEmpty()) { + const QString base = treelandDebugSocketPathForUrl(candidate); + if (!base.isEmpty() && QFileInfo::exists(base)) + occupiedNonSocket = base; + } + } + + if (published.isEmpty()) { + QTextStream(stderr) << "treeland-debug: treeland published no debug socket in " + << treelandDebugSocketDirs().join(QStringLiteral(" or ")) + << "; is it running, and is its " + "`remoteDebug` switch on? `treeland-debug debug on` turns it " + "on, escalating to root when the compositor runs as another " + "user\n"; + if (!occupiedNonSocket.isEmpty()) + QTextStream(stderr) << "treeland-debug: note that " << occupiedNonSocket + << " exists but is not a socket; something else owns that " + "name, so the compositor would have published a " + "`-` suffix instead\n"; + return; + } + + QList> groups; + for (const Published &group : std::as_const(published)) { + QList probes; + for (const QString &path : group.paths) + probes << probeSocket(path); + groups << probes; + } + + // Explain the group that answers; failing that, one that names a root-only + // instance, which is the actionable answer; only then the first, which is left + // with stale or unanswered files. + int chosen = -1; + for (int i = 0; i < groups.size() && chosen < 0; ++i) { + for (const SocketProbe &probe : groups.at(i)) { + if (probe.accepted) { + chosen = i; + break; + } + } + } + for (int i = 0; i < groups.size() && chosen < 0; ++i) { + for (const SocketProbe &probe : groups.at(i)) { + if (probe.inaccessible()) { + chosen = i; + break; + } + } + } + if (chosen < 0) + chosen = 0; + + const QString publishedUrl = published.at(chosen).url; + const QList probes = groups.at(chosen); + QStringList live; + QStringList leftover; + QStringList inaccessible; + QStringList unanswered; + for (const SocketProbe &probe : probes) { + if (probe.accepted) + live << probe.path; + else if (probe.inaccessible()) + inaccessible << probe.path; + else if (probe.leftover()) + leftover << probe.path; + else + unanswered << probe.path; + } + + if (live.size() > 1) { + QTextStream(stderr) << "treeland-debug: more than one instance answers for " + << publishedUrl << ": " << live.join(QStringLiteral(", ")) + << "; point at the one you mean with `--url local:`\n"; + printSocketNotes(leftover, inaccessible, unanswered); + return; + } + + if (live.isEmpty()) { + QTextStream(stderr) << "treeland-debug: "; + if (probes.size() == 1) { + QTextStream(stderr) << probes.first().path << " exists but the connection failed: " + << (probes.first().errorString.isEmpty() + ? QStringLiteral("no answer") + : probes.first().errorString); + } else { + QStringList paths; + for (const SocketProbe &probe : probes) + paths << probe.path; + QTextStream(stderr) << paths.join(QStringLiteral(", ")) << " are published for " + << publishedUrl << " but none of them answers"; + } + QTextStream(stderr) << "\n"; + printSocketNotes(leftover, inaccessible, unanswered); + return; + } + + // Exactly one socket answers. Keep that connection: SO_PEERCRED is read off + // it, so the message can name the process instead of guessing. + const QString path = live.first(); + QLocalSocket peer; + peer.connectToServer(path); + if (!peer.waitForConnected(1000)) { + // Answered a moment ago and is gone now; nothing useful left to say. + QTextStream(stderr) << "treeland-debug: " << path + << " stopped answering while this report was written\n"; + return; + } + + const QString owner = treelandDebugSocketPeerText(peer); + // The candidates are absolute paths, so the hint must be one too: a bare name + // would be resolved under QDir::tempPath() instead. + const QString answeringUrl = QStringLiteral("local:") + path; + QTextStream(stderr) << "treeland-debug: " << path + << " accepts connections but no `WindowTree` source answered" + << (owner.isEmpty() ? QString() + : QStringLiteral(" (the listener is %1)").arg(owner)) + << ". A socket file left behind by a crashed instance refuses " + "connections instead, so a live process holds this one and " + "either does not serve this build's `WindowTree` at all " + "(another program, or a treeland build that never published a " + "source), or serves a `WindowTree` whose signature differs from " + "this client's -- `Signature mismatch for " + "WindowTreeRemoteReplica` above means the compositor and this " + "client were built from different revisions"; + if (attemptedPaths.contains(path)) { + // This run already probed that socket, so suggesting --url for it would just + // repeat the same failure with even less explanation. + QTextStream(stderr) << "; this run already tried that address, so the source is what " + "is wrong, not the name: restart that process with this build, or " + "stop it so this build publishes its own\n"; + } else { + QTextStream(stderr) << "; an instance published after this run started: " + << "`--url " << answeringUrl << "`\n"; + } + printSocketNotes(leftover, inaccessible, unanswered); +} + +// Names the socket the data came from, so a pasted output says whose it is. +// A one-shot run prints it when it is done, and the shell prints it on entry +// like a login banner (a REPL has no end of output). It goes to stderr, which +// keeps piped and --json stdout parseable; the "(fallback from ...)" detail is +// client-side discovery noise and stays a --log-level debug message. +void printSourceNotice(const QString &connectedUrl, const QStringList &candidateUrls, bool login) +{ + QTextStream out(stderr); + out << "treeland-debug: " << (login ? "logged in to " : "connected to ") << connectedUrl; + if (logEnabled(LogLevel::Debug) && !candidateUrls.isEmpty() + && connectedUrl != candidateUrls.first()) { + out << " (fallback from " << candidateUrls.first() << ")"; + } + out << Qt::endl; +} + +int main(int argc, char *argv[]) +{ + QCoreApplication application(argc, argv); + QCoreApplication::setApplicationName(QStringLiteral("treeland-debug")); + QCoreApplication::setApplicationVersion(QStringLiteral("1.0")); + + // URL resolution: an explicit --url is used verbatim with no implicit + // processing. When --url is absent, a debug build prefers the debug + // socket and falls back to the release socket; a release build uses the + // release socket directly. See treelandDebugCandidateSocketUrls(). + QString url; + bool urlExplicit = false; + QString name = QStringLiteral("WindowTree"); + int timeoutMs = 30000; + bool timeoutOk = true; + bool json = false; + bool previewOpt = 0; // 0=auto-detect, 1=force on, 2=force off + bool compatTree = false; + bool compatCursor = false; + bool noEscalate = false; + bool logLevelOk = true; + QStringList rest; + + for (int i = 1; i < argc; ++i) { + const QString arg = QString::fromUtf8(argv[i]); + const auto next = [&]() -> QString { + if (i + 1 < argc) + return QString::fromUtf8(argv[++i]); + return {}; + }; + if (arg == QLatin1String("--url")) { + url = next(); + urlExplicit = true; + } else if (arg.startsWith(QLatin1String("--url="))) { + url = arg.mid(6); + urlExplicit = true; + } else if (arg == QLatin1String("--name")) + name = next(); + else if (arg.startsWith(QLatin1String("--name="))) + name = arg.mid(7); + else if (arg == QLatin1String("--timeout-ms")) { + bool ok = false; + timeoutMs = next().toInt(&ok); + if (!ok) + timeoutOk = false; + } else if (arg.startsWith(QLatin1String("--timeout-ms="))) { + bool ok = false; + timeoutMs = arg.mid(13).toInt(&ok); + if (!ok) + timeoutOk = false; + } + else if (arg == QLatin1String("--preview")) + previewOpt = 1; + else if (arg == QLatin1String("--no-preview")) + previewOpt = 2; + else if (arg == QLatin1String("--json")) + json = true; + else if (arg == QLatin1String("--no-escalate")) + noEscalate = true; + else if (arg == QLatin1String("--log-level")) { + bool ok = false; + g_logLevel = parseLogLevel(next(), &ok); + if (!ok) + logLevelOk = false; + } else if (arg.startsWith(QLatin1String("--log-level="))) { + bool ok = false; + g_logLevel = parseLogLevel(arg.mid(12), &ok); + if (!ok) + logLevelOk = false; + } + else if (arg == QLatin1String("--tree")) + compatTree = true; + else if (arg == QLatin1String("--cursor")) + compatCursor = true; + else if (arg == QLatin1String("-h") || arg == QLatin1String("--help")) { + QTextStream(stdout) << helpText(); + return EXIT_SUCCESS; + } else if (arg == QLatin1String("-v") || arg == QLatin1String("--version")) { + QTextStream(stdout) << QCoreApplication::applicationVersion() << Qt::endl; + return EXIT_SUCCESS; + } else { + rest.append(arg); + } + } + + if (!timeoutOk || timeoutMs < 0) + return fail("--timeout-ms must be a non-negative integer"); + + if (!logLevelOk) + return fail("--log-level must be one of error, warning, info, debug"); + + if (urlExplicit && url.isEmpty()) + return fail("--url requires a non-empty value"); + + // Resolution order: `--url` (already in `url`), then $TREELAND_DEBUG_SOCKET, + // then the built-in probing below. The variable is read only when the flag + // was not given, so a script can override an exported default. + if (!urlExplicit) + url = treelandDebugSocketUrlFromEnv(); + const bool urlConfigured = urlExplicit || !url.isEmpty(); + + registerNamedMetatypes(); + + QString command; + QStringList commandArgs; + if (compatTree) + command = QStringLiteral("tree"); + else if (compatCursor) + command = QStringLiteral("cursor"); + else if (!rest.isEmpty()) { + command = rest.takeFirst(); + commandArgs = rest; + } else { + command = QStringLiteral("tree"); + } + + if (command == QLatin1String("help")) { + QTextStream(stdout) << helpText(); + return EXIT_SUCCESS; + } + + // The switch command runs without the socket -- it is what makes one exist -- + // so it is dispatched before any connection or escalation below. + if (command == QLatin1String("debug")) { + QStringList selfArgs; + for (int i = 1; i < argc; ++i) + selfArgs.append(QString::fromUtf8(argv[i])); + return runDebugSwitch(commandArgs, selfArgs, noEscalate); + } + +#ifndef TREELAND_DEBUG_DEV_BUILD + // Release builds: the server-side socket is chmod'd to 0000 inside a runtime + // directory only its owner may enter, so only root can connect -- unless a + // no-auth window was requested over the protocol, which opens the socket to + // every local user for 30 call-free minutes. The connect attempt below + // therefore comes first: escalating up front would prompt for a password + // even while that window makes root unnecessary. A re-executed (root) copy + // sees geteuid() == 0 and never escalates again. + const bool mayEscalate = ::geteuid() != 0; +#else + // Debug builds allow all users unconditionally. +#endif + + // Resolve the URL to connect to. An explicit --url or $TREELAND_DEBUG_SOCKET + // is used verbatim; otherwise the build-default candidate list (debug → + // release fallback in debug builds) is probed, each candidate followed by the + // instances published under a "-" suffix when another instance + // holds the base name. + const QStringList candidateUrls = urlConfigured + ? QStringList{url} + : treelandDebugInstanceSocketUrls(treelandDebugCandidateSocketUrls()); + + // Treeland publishes its debug socket whenever its `remoteDebug` master + // switch is on, so the client never touches DConfig: a missing socket means + // the switch is off (it is off by default) or treeland is not running, and + // the hint below points at `treeland-debug debug on`. + +#ifdef TREELAND_DEBUG_LISTEN + if (command == QLatin1String("listen")) { + const ParseResult parsed = parseCommand(command, commandArgs); + if (!parsed.ok) + return fail(parsed.error); + DebugServer server(candidateUrls, name, timeoutMs); + if (!server.listen(parsed.host, parsed.port)) + return fail(QStringLiteral("listen: failed to bind to %1:%2").arg(parsed.host).arg(parsed.port)); + QTextStream(stdout) << "treeland-debug listening on " << parsed.host << ":" << parsed.port << "\n"; + return QCoreApplication::exec(); + } +#endif + + // A local candidate whose socket file is absent cannot connect, so skip it + // instead of spending a probe timeout on it: with several runtime + // directories a short --timeout-ms would otherwise be exhausted before a + // live socket later in the list is reached. If none exists, keep the full + // list so the diagnostics below still name every place that was searched. + const QStringList connectUrls = treelandDebugExistingSocketUrls(candidateUrls); + // A root-only socket is not worth probing from here (see + // reachableWithoutRoot()); an empty result falls straight through to the + // escalation below. + const QStringList probeUrls = +#ifdef TREELAND_DEBUG_DEV_BUILD + connectUrls; +#else + mayEscalate ? reachableWithoutRoot(connectUrls) : connectUrls; +#endif + + Session session; + QString connectedUrl; + if (!connectSession(session, probeUrls, name, timeoutMs, &connectedUrl)) { +#ifndef TREELAND_DEBUG_DEV_BUILD + // Only now, with the socket proven unreachable as ourselves, is a polkit + // password prompt worth asking for. --no-escalate never prompts: it + // reports the root requirement instead. + if (mayEscalate) { + if (!urlConfigured && connectUrls.isEmpty()) { + const QString hint = remoteDebugOffHint(); + if (!hint.isEmpty()) + return fail(hint); + } + if (noEscalate) { + return fail(QStringLiteral("root privileges required (release build); " + "remove --no-escalate to escalate via polkit")); + } + const QString pkexec = QStandardPaths::findExecutable(QStringLiteral("pkexec")); + if (pkexec.isEmpty()) { + return fail(QStringLiteral("root privileges required (release build), " + "but pkexec was not found — install polkit " + "or run as root")); + } + // Re-exec ourselves through pkexec, forwarding every original + // argument so the elevated copy runs the same command. + const QString exe = QCoreApplication::applicationFilePath(); + QStringList pkArgs; + pkArgs << exe; + for (int i = 1; i < argc; ++i) + pkArgs << QString::fromUtf8(argv[i]); + return QProcess::execute(pkexec, pkArgs); + } +#endif + if (!urlConfigured) + explainConnectFailure(candidateUrls, probeUrls); + return fail(QStringLiteral("failed to connect to remote object node (tried: %1)") + .arg(candidateUrls.join(" or "))); + } + + // The source notice closes every run: a shell prints it on entry instead + // (see runShell), because a REPL has no end of output. + if (command == QLatin1String("shell")) + return runShell(session, timeoutMs, json, previewOpt, connectedUrl, candidateUrls); + + int rc = EXIT_SUCCESS; + if (!dispatchLiveCommand(session, timeoutMs, command, commandArgs, &rc)) + rc = runCommand(session, timeoutMs, json, previewOpt, command, commandArgs); + printSourceNotice(connectedUrl, candidateUrls, false); + return rc; +} + +static int runCommand(Session &session, int timeoutMs, bool json, int previewOpt, + const QString &command, const QStringList &args) +{ + const ParseResult parsed = parseCommand(command, args); + if (!parsed.ok) + return fail(parsed.error); + + auto *replica = session.replica; + + switch (parsed.command) { + case DebugCommand::Tree: { + TreelandInfo info; + if (!waitSlot(replica->getTreelandInfo(), timeoutMs, &info)) + return fail("getTreelandInfo() failed"); + if (json) + printJson(QJsonDocument(treelandInfoToJson(info))); + else + printTree(info); + return EXIT_SUCCESS; + } + case DebugCommand::Cursor: { + const QPointF pos = replica->cursorPosition(); + // 0 means "no window under the cursor", exactly like `xdotool + // getmouselocation`; an unanswered query leaves it at 0 too rather than + // hiding the field, so the output shape never changes. + qint64 cursorWindow = 0; + waitSlot(replica->windowUnderCursor(), timeoutMs, &cursorWindow); + if (json) { + QJsonObject obj = pointToJson(pos); + obj.insert(QStringLiteral("window"), cursorWindow); + printJson(QJsonDocument(obj)); + return EXIT_SUCCESS; + } + // xdotool getmouselocation layout: the fields are already labelled for + // whoever is reading, quotes or not. + QTextStream out(stdout); + out << "x:" << pos.x() << " y:" << pos.y() << " window:" << cursorWindow << Qt::endl; + return EXIT_SUCCESS; + } + case DebugCommand::Window: { + WindowInfo window; + int matches = 0; + if (!lookupWindow(session, timeoutMs, parsed.target, &window, &matches)) + return fail(QStringLiteral("no window matches '%1'").arg(parsed.target)); + if (matches > 1) { + QTextStream(stderr) << "treeland-debug: " << matches << " windows match '" + << parsed.target << "'; showing id " << window.id() << "\n"; + } + if (json) + printJson(QJsonDocument(windowToJson(window))); + else + printWindowDetail(window); + return EXIT_SUCCESS; + } + case DebugCommand::Windows: { + QList windows; + if (!waitSlot(replica->getWindows(), timeoutMs, &windows)) + return fail("getWindows() failed"); + if (json) + printJson(QJsonDocument(windowsToJson(windows))); + else + printWindowsTable(windows); + return EXIT_SUCCESS; + } + case DebugCommand::Clients: { + QList clients; + if (!waitSlot(replica->getClients(), timeoutMs, &clients)) + return fail("getClients() failed"); + if (json) + printJson(QJsonDocument(clientsToJson(clients))); + else + printClientsTable(clients); + return EXIT_SUCCESS; + } + case DebugCommand::Idle: { + IdleInfo info; + if (!waitSlot(replica->getIdleInfo(), timeoutMs, &info)) + return fail("getIdleInfo() failed"); + if (json) + printJson(QJsonDocument(idleToJson(info))); + else + printIdle(info); + return EXIT_SUCCESS; + } + case DebugCommand::NoAuth: { + bool result = false; + if (!waitSlot(replica->requestNoAuth(), timeoutMs, &result)) + return fail("requestNoAuth() failed"); + if (!result) { + return fail(QStringLiteral("the compositor refused: it can only open a runtime " + "directory of its own, so a session instance keeps " + "requiring root")); + } + if (json) + printJson(QJsonDocument(QJsonObject{ { "noAuth", true } })); + else + QTextStream(stdout) << "the debug socket is open to every user for 30 minutes\n"; + return EXIT_SUCCESS; + } + case DebugCommand::Shortcuts: { + QList shortcuts; + if (!waitSlot(replica->getShortcuts(), timeoutMs, &shortcuts)) + return fail("getShortcuts() failed"); + if (json) + printJson(QJsonDocument(shortcutsToJson(shortcuts))); + else + printShortcutsTable(shortcuts); + return EXIT_SUCCESS; + } + // ---- window control ---- + case DebugCommand::Activate: + case DebugCommand::Close: + case DebugCommand::Minimize: + case DebugCommand::Maximize: + case DebugCommand::Fullscreen: + case DebugCommand::Move: + case DebugCommand::Resize: + case DebugCommand::Workspace: { + bool ok = false; + const qint64 id = resolveTarget(session, timeoutMs, parsed.target, &ok); + if (!ok) + return fail(QStringLiteral("no window matches '%1'").arg(parsed.target)); + + bool result = false; + switch (parsed.command) { + case DebugCommand::Activate: + if (!waitSlot(replica->activateWindow(id), timeoutMs, &result)) + return fail("activateWindow() failed"); + break; + case DebugCommand::Close: + if (!waitSlot(replica->closeWindow(id), timeoutMs, &result)) + return fail("closeWindow() failed"); + break; + case DebugCommand::Minimize: + if (!waitSlot(replica->minimizeWindow(id), timeoutMs, &result)) + return fail("minimizeWindow() failed"); + break; + case DebugCommand::Maximize: + if (!waitSlot(replica->toggleMaximized(id), timeoutMs, &result)) + return fail("toggleMaximized() failed"); + break; + case DebugCommand::Fullscreen: + if (!waitSlot(replica->toggleFullscreen(id), timeoutMs, &result)) + return fail("toggleFullscreen() failed"); + break; + case DebugCommand::Move: + if (!waitSlot(replica->moveWindow(id, parsed.x, parsed.y), timeoutMs, &result)) + return fail("moveWindow() failed"); + break; + case DebugCommand::Resize: + if (!waitSlot(replica->resizeWindow(id, parsed.width, parsed.height), timeoutMs, &result)) + return fail("resizeWindow() failed"); + break; + case DebugCommand::Workspace: + if (!waitSlot(replica->setWindowWorkspace(id, parsed.workspaceId), timeoutMs, &result)) + return fail("setWindowWorkspace() failed"); + break; + default: + break; + } + QTextStream(stdout) << (result ? "ok" : "failed") << Qt::endl; + return result ? EXIT_SUCCESS : EXIT_FAILURE; + } + // ---- cursor move ---- + case DebugCommand::MoveCursor: { + bool result = false; + if (!waitSlot(replica->moveCursor(QPointF(parsed.dx, parsed.dy)), timeoutMs, &result)) + return fail("moveCursor() failed"); + QTextStream(stdout) << (result ? "ok" : "failed") << Qt::endl; + return result ? EXIT_SUCCESS : EXIT_FAILURE; + } + // ---- event injection ---- + case DebugCommand::EventMotion: { + bool result = false; + if (!waitSlot(replica->moveCursor(QPointF(parsed.dx, parsed.dy)), timeoutMs, &result)) + return fail("moveCursor() failed"); + QTextStream(stdout) << (result ? "ok" : "failed") << Qt::endl; + return result ? EXIT_SUCCESS : EXIT_FAILURE; + } + case DebugCommand::EventButton: { + bool result = false; + const int code = parsed.code; + const QString act = parsed.action; + if (act == QLatin1String("press")) { + if (!waitSlot(replica->sendPointerButton(code, true), timeoutMs, &result)) + return fail("sendPointerButton() failed"); + } else if (act == QLatin1String("release")) { + if (!waitSlot(replica->sendPointerButton(code, false), timeoutMs, &result)) + return fail("sendPointerButton() failed"); + } else { // click + bool r1 = false, r2 = false; + if (!waitSlot(replica->sendPointerButton(code, true), timeoutMs, &r1)) + return fail("sendPointerButton() failed"); + if (!waitSlot(replica->sendPointerButton(code, false), timeoutMs, &r2)) + return fail("sendPointerButton() failed"); + result = r1 && r2; + } + QTextStream(stdout) << (result ? "ok" : "failed") << Qt::endl; + return result ? EXIT_SUCCESS : EXIT_FAILURE; + } + case DebugCommand::EventKey: { + bool result = false; + const int code = parsed.code; + const QString act = parsed.action; + if (act == QLatin1String("press")) { + if (!waitSlot(replica->sendKey(code, true), timeoutMs, &result)) + return fail("sendKey() failed"); + } else if (act == QLatin1String("release")) { + if (!waitSlot(replica->sendKey(code, false), timeoutMs, &result)) + return fail("sendKey() failed"); + } else { // tap + bool r1 = false, r2 = false; + if (!waitSlot(replica->sendKey(code, true), timeoutMs, &r1)) + return fail("sendKey() failed"); + if (!waitSlot(replica->sendKey(code, false), timeoutMs, &r2)) + return fail("sendKey() failed"); + result = r1 && r2; + } + QTextStream(stdout) << (result ? "ok" : "failed") << Qt::endl; + return result ? EXIT_SUCCESS : EXIT_FAILURE; + } + // ---- image capture ---- + case DebugCommand::ScreenshotOutput: { + QByteArray data; + replica->captureOutput(parsed.outputName); + if (!waitCaptureResult(replica, timeoutMs, &data)) + return fail("captureOutput() failed"); + if (data.isEmpty()) + return fail("captureOutput: no image produced (output not found or grab failed)"); + const QString saved = saveCapture(data, parsed.filePath); + if (saved.isEmpty()) + return fail("captureOutput: failed to save image"); + QTextStream(stdout) << saved << Qt::endl; + if (previewOpt != 2) + previewImage(data, previewOpt == 1); + return EXIT_SUCCESS; + } + case DebugCommand::ScreenshotWindow: { + bool ok = false; + const qint64 id = resolveTarget(session, timeoutMs, parsed.target, &ok); + if (!ok) + return fail(QStringLiteral("no window matches '%1'").arg(parsed.target)); + QByteArray data; + replica->captureWindow(id); + if (!waitCaptureResult(replica, timeoutMs, &data)) + return fail("captureWindow() failed"); + if (data.isEmpty()) + return fail("captureWindow: no image produced (window not found, has no scene item, or grab failed)"); + const QString saved = saveCapture(data, parsed.filePath); + if (saved.isEmpty()) + return fail("captureWindow: failed to save image"); + QTextStream(stdout) << saved << Qt::endl; + if (previewOpt != 2) + previewImage(data, previewOpt == 1); + return EXIT_SUCCESS; + } + case DebugCommand::Scene: { + qint64 id = 0; + if (!parsed.target.isEmpty()) { + bool ok = false; + id = resolveTarget(session, timeoutMs, parsed.target, &ok); + if (!ok) + return fail(QStringLiteral("no window matches '%1'").arg(parsed.target)); + } + QString tree; + if (!waitSlot(replica->getSceneTree(id), timeoutMs, &tree)) + return fail("getSceneTree() failed"); + if (json) + printJson(QJsonDocument(QJsonObject{{"sceneTree", tree}})); + else + QTextStream(stdout) << tree; + return EXIT_SUCCESS; + } + default: + return fail(QStringLiteral("unknown command '%1' (try --help)").arg(command)); + } +} + +static int runTop(Session &session, int timeoutMs, int intervalMs) +{ + QTextStream out(stdout); + out << "treeland-debug top — refreshing every " << intervalMs << "ms (Ctrl+C to quit)\n"; + out.flush(); + // Keep previous frames to compute per-interval deltas for sorting. + QHash prevFrames; + + int rc = EXIT_SUCCESS; + QObject context; + QTimer timer; + timer.setInterval(intervalMs); + + auto refresh = [&]() { + // Fetch current status. + QList clients; + if (!waitSlot(session.replica->getClients(), timeoutMs, &clients)) { + if (!g_debugInterrupted) { + QTextStream(stderr) << "treeland-debug: getClients() failed\n"; + rc = EXIT_FAILURE; + } + QCoreApplication::quit(); + return; + } + qint64 focusId = 0, cursorId = 0; + waitSlot(session.replica->focusedWindowId(), timeoutMs, &focusId); + waitSlot(session.replica->windowUnderCursor(), timeoutMs, &cursorId); + IdleInfo idle; + const bool haveIdle = waitSlot(session.replica->getIdleInfo(), timeoutMs, &idle); + + // Collect all windows with their frame deltas. + struct WinRow { + qint64 id; QString appId; QString title; QString shellType; int state; + QRectF geo; bool minimized; + qint64 frames; QRectF damage; + int64_t framesDelta; + }; + QList rows; + for (const auto &cl : clients) { + for (const auto &w : cl.windows()) { + WinRow r; + r.id = w.id(); r.appId = w.appId(); r.title = w.title(); + r.shellType = shellTypeName(w.type()); + r.state = w.state(); r.minimized = w.minimized(); + r.geo = w.geometry(); r.frames = w.frames(); r.damage = w.damage(); + const auto prev = prevFrames.value(w.id()); + r.framesDelta = (prev > 0) ? (w.frames() - prev) : 0; + rows.append(r); + } + } + // Update prevFrames for next cycle. + for (const auto &r : rows) + prevFrames[r.id] = r.frames; + + // Sort by framesDelta descending (most active first). + std::sort(rows.begin(), rows.end(), + [](const WinRow &a, const WinRow &b) { return a.framesDelta > b.framesDelta; }); + + // Clear and print. + out << QStringLiteral("\033[2J\033[H"); + out << "treeland-debug top — " + << QDateTime::currentDateTime().toString(Qt::ISODate) + << " (clients: " << clients.size() << " windows: " << rows.size() << ")\n"; + if (haveIdle) { + int active = 0; + for (const auto &source : idle.inhibitors()) + active += source.active() ? 1 : 0; + out << " idle: " << formatDuration(idle.idleMs()) + << " inhibited: " << (idle.inhibited() ? "yes" : "no") + << " sources: " << idle.inhibitors().size() << " (" << active << " active)\n"; + } + out << " " << QStringLiteral("ID").leftJustified(kIdWidth) + << QStringLiteral("TYPE").leftJustified(kTypeWidth + kGap) + << QStringLiteral("APP-ID").leftJustified(kAppIdWidth + kGap) + << QStringLiteral("STATE").leftJustified(kStateWidth + kGap) + << QStringLiteral("MIN").leftJustified(kMinWidth + kGap) + << QStringLiteral("FRAMES").rightJustified(kFramesWidth) + << QStringLiteral(" ") + << QStringLiteral("GEOMETRY").leftJustified(kGeometryWidth + kGap) + << "MARKER\n"; + for (const auto &r : rows) { + QString marker; + if (r.id == focusId) marker = QStringLiteral("F (focus)"); + else if (r.id == cursorId) marker = QStringLiteral("C (under cursor)"); + else marker = QStringLiteral(" "); + // A numeric column, so it is right-aligned and the separator has to + // follow it rather than be part of its width. + out << QStringLiteral(" %1%2%3%4%5%6 %7 %8\n") + .arg(QString::number(r.id).leftJustified(kIdWidth), + r.shellType.leftJustified(kTypeWidth + kGap), + r.appId.leftJustified(kAppIdWidth + kGap), + stateName(r.state).leftJustified(kStateWidth + kGap), + (r.minimized ? QStringLiteral("yes") : QStringLiteral("no")) + .leftJustified(kMinWidth + kGap), + QString::number(r.framesDelta).rightJustified(kFramesWidth), + formatGeometry(r.geo).leftJustified(kGeometryWidth), + marker); + } + out.flush(); + }; + + QObject::connect(&timer, &QTimer::timeout, &context, refresh); + refresh(); + timer.start(); + + QCoreApplication::exec(); + return rc; +} + +static bool dispatchLiveCommand(Session &session, int timeoutMs, + const QString &command, const QStringList &commandArgs, + int *rc) +{ + const ParseResult parsed = parseCommand(command, commandArgs); + + // Only the live commands (top/events/watch) are handled here; everything + // else falls through to runCommand(). + if (parsed.command != DebugCommand::Top && parsed.command != DebugCommand::Events + && parsed.command != DebugCommand::Watch) { + return false; + } + + if (!parsed.ok) { + *rc = fail(parsed.error); + return true; + } + + switch (parsed.command) { + case DebugCommand::Top: + *rc = runTop(session, timeoutMs, parsed.intervalMs); + return true; + case DebugCommand::Events: + *rc = runEvents(session, timeoutMs, parsed.intervalMs); + return true; + case DebugCommand::Watch: { + bool ok = false; + const qint64 id = resolveTarget(session, timeoutMs, parsed.target, &ok); + if (!ok) { + *rc = fail(QStringLiteral("no window matches '%1'").arg(parsed.target)); + return true; + } + *rc = runWatch(session, timeoutMs, id, parsed.intervalMs); + return true; + } + default: + return false; + } +} + +static int runShell(Session &session, int timeoutMs, bool json, int previewOpt, + const QString &connectedUrl, const QStringList &candidateUrls) +{ + QTextStream out(stdout); + out << "treeland-debug shell — type 'help' for commands, 'exit' to quit\n" + << "Tab completes a command, ↑/↓ recall what was typed\n"; + out.flush(); + // Like an ssh login banner: say up front which socket this session reads, so + // nobody mistakes another instance's windows for their own. + printSourceNotice(connectedUrl, candidateUrls, true); + + // A pipe cannot deliver a Tab before the line ends, so only a terminal gets + // the line editor; a script keeps reading plain lines from stdin. + const bool interactive = ::isatty(STDIN_FILENO) && ::isatty(STDOUT_FILENO); + ShellLineEditor editor; + QTextStream in(stdin); + while (true) { + // The prompt is written straight to the terminal by the line editor, so + // anything buffered here (help text, the live-view newline, the debug + // hint) has to reach stdout first or it would show up after the prompt. + out.flush(); + QString line; + if (interactive) { + if (!editor.readLine(QStringLiteral("treeland> "), &line)) + break; + } else { + out << "treeland> "; + out.flush(); + line = in.readLine(); + if (line.isNull()) // EOF + break; + } + const QString trimmed = line.trimmed(); + if (trimmed.isEmpty()) + continue; + if (trimmed == QLatin1String("exit") || trimmed == QLatin1String("quit")) + break; + if (trimmed == QLatin1String("help")) { + out << helpText(); + continue; + } + + QStringList parts = trimmed.split(' ', Qt::SkipEmptyParts); + if (parts.isEmpty()) + continue; + + const QString command = parts.takeFirst(); + // Live commands (top/events/watch) run their own event loop. Install a + // SIGINT guard so Ctrl+C interrupts the live view and returns to the + // REPL instead of killing the process. For non-live commands the guard + // is installed only briefly (dispatchLiveCommand returns immediately). + { + SigIntInterrupt guard; + guard.install(); + int liveRc = 0; + if (dispatchLiveCommand(session, timeoutMs, command, parts, &liveRc)) { + out << "\n"; // newline after the interrupted live view + continue; + } + } + if (command == QLatin1String("debug")) { + // The switch is per user and may need polkit, which this REPL cannot + // forward an escalation through: it is a pre-connection command. + out << "debug: run `treeland-debug debug on|off|status` as a one-shot command\n"; + continue; + } + runCommand(session, timeoutMs, json, previewOpt, command, parts); + } + return EXIT_SUCCESS; +} + +// Event types reported by WindowTreeRemote::getEvents(); see +// src/modules/resource/treelandwindowtree.rep. +static QString debugEventTypeName(int type) +{ + switch (type) { + case 1: return QStringLiteral("motion"); + case 2: return QStringLiteral("button"); + case 3: return QStringLiteral("key"); + case 4: return QStringLiteral("focus"); + case 5: return QStringLiteral("cursor-window"); + case 6: return QStringLiteral("shortcut-registered"); + case 7: return QStringLiteral("shortcut-unregistered"); + case 8: return QStringLiteral("shortcut-triggered"); + default: return QStringLiteral("event-%1").arg(type); + } +} + +static int runEvents(Session &session, int timeoutMs, int intervalMs) +{ + QTextStream out(stdout); + out << "treeland-debug events — streaming every " << intervalMs << "ms (Ctrl+C to quit)\n\n"; + out.flush(); + + int rc = EXIT_SUCCESS; + quint64 lastSeq = 0; + QObject context; + QTimer timer; + timer.setInterval(intervalMs); + + auto refresh = [&]() { + QList events; + if (!waitSlot(session.replica->getEvents(lastSeq), timeoutMs, &events)) { + if (!g_debugInterrupted) { + QTextStream(stderr) << "treeland-debug: getEvents() failed\n"; + rc = EXIT_FAILURE; + } + QCoreApplication::quit(); + return; + } + for (const auto &e : events) { + lastSeq = std::max(lastSeq, e.seq()); + const QString time = QDateTime::fromMSecsSinceEpoch(e.timestampMs()).toString("HH:mm:ss.zzz"); + QString targetName; + if (e.target() != 0) + targetName = QStringLiteral(" -> %1").arg(e.target()); + out << time << " " << debugEventTypeName(e.type()).leftJustified(21) << " " + << e.detail() << targetName << "\n"; + } + out.flush(); + }; + + QObject::connect(&timer, &QTimer::timeout, &context, refresh); + refresh(); + timer.start(); + + QCoreApplication::exec(); + return rc; +} + +static int runWatch(Session &session, int timeoutMs, qint64 id, int intervalMs) +{ + QTextStream out(stdout); + out << "treeland-debug watch " << id << " — every " << intervalMs << "ms (Ctrl+C to quit)\n\n"; + out.flush(); + + int rc = EXIT_SUCCESS; + WindowInfo prev; + bool havePrev = false; + qint64 prevFrames = 0; + QObject context; + QTimer timer; + timer.setInterval(intervalMs); + + auto refresh = [&]() { + QList windows; + if (!waitSlot(session.replica->getWindows(), timeoutMs, &windows)) { + if (!g_debugInterrupted) { + QTextStream(stderr) << "treeland-debug: getWindows() failed\n"; + rc = EXIT_FAILURE; + } + QCoreApplication::quit(); + return; + } + WindowInfo cur; + bool found = false; + for (const auto &w : windows) { + if (w.id() == id) { cur = w; found = true; break; } + } + if (!found) { + QTextStream(stderr) << "treeland-debug: window " << id << " no longer exists\n"; + rc = EXIT_FAILURE; + QCoreApplication::quit(); + return; + } + + // Print a header on the first sample, then one event-style line per + // change on subsequent samples. + const bool firstSample = !havePrev; + if (firstSample) { + out << "Window " << id << " " << cur.appId() + << (cur.title().isEmpty() ? QString() : QStringLiteral(" (%1)").arg(cur.title())) + << "\n type=" << shellTypeName(cur.type()) + << " state=" << stateName(cur.state()) + << " geometry=" << formatGeometry(cur.geometry()) + << "\n"; + havePrev = true; + } + QStringList changes; + if (!firstSample) { + if (cur.geometry() != prev.geometry()) + changes << QStringLiteral("geometry %1").arg(formatGeometry(cur.geometry())); + if (cur.workspace() != prev.workspace()) + changes << QStringLiteral("workspace %1").arg(cur.workspace()); + if (cur.state() != prev.state()) + changes << QStringLiteral("state %1 -> %2") + .arg(stateName(prev.state())).arg(stateName(cur.state())); + if (cur.active() != prev.active()) + changes << (cur.active() ? QStringLiteral("activated") : QStringLiteral("deactivated")); + if (cur.minimized() != prev.minimized()) + changes << (cur.minimized() ? QStringLiteral("minimized") : QStringLiteral("unminimized")); + } + const qint64 frames = cur.frames(); + if (frames != prevFrames) + changes << QStringLiteral("frames %1 (+%2)").arg(frames).arg(frames - prevFrames); + if (!cur.damage().isEmpty()) + changes << QStringLiteral("damage %1").arg(formatGeometry(cur.damage())); + prevFrames = frames; + + // Always print one line per refresh (like `top`); changes are prefixed + // with `*` when they differ from the previous snapshot. + const QString time = QDateTime::currentDateTime().toString("HH:mm:ss"); + out << time << " "; + if (changes.isEmpty()) + out << "(no change)\n"; + else + out << " * " << changes.join("; ") << "\n"; + prev = cur; + out.flush(); + }; + + QObject::connect(&timer, &QTimer::timeout, &context, refresh); + refresh(); + timer.start(); + + QCoreApplication::exec(); + return rc; +} diff --git a/tools/treeland-debug/shellline.cpp b/tools/treeland-debug/shellline.cpp new file mode 100644 index 0000000000..b81a1439ce --- /dev/null +++ b/tools/treeland-debug/shellline.cpp @@ -0,0 +1,417 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "shellline.h" + +#include "debughelpers.h" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +// Enough to recall what was typed a while ago without keeping every line of a +// long session alive. +constexpr qsizetype kMaxHistory = 500; + +// One keypress, with escape sequences folded into a single key so the caller +// never has to look at the terminal protocol. +enum class Key { + Text, + Enter, + Backspace, + Tab, + Interrupt, + Eof, + StdinClosed, + Up, + Down, + Left, + Right, + Home, + End, + Delete, + KillLine, + KillToEnd, +}; + +struct Keypress +{ + Key key = Key::Text; + QString text; +}; + +void writeRaw(const QByteArray &bytes) +{ + const char *data = bytes.constData(); + qsizetype left = bytes.size(); + while (left > 0) { + const ssize_t written = ::write(STDOUT_FILENO, data, size_t(left)); + if (written <= 0) + return; + data += written; + left -= written; + } +} + +// A byte read while looking for the rest of an escape sequence that turned out +// not to be one; it belongs to the next keypress, so hand it back instead of +// dropping it (Esc followed by Enter must still be an Enter). +int g_pendingByte = -1; + +int readByte() +{ + if (g_pendingByte >= 0) { + const int c = g_pendingByte; + g_pendingByte = -1; + return c; + } + unsigned char c = 0; + return ::read(STDIN_FILENO, &c, 1) == 1 ? int(c) : -1; +} + +// How long to wait for the rest of an escape sequence before deciding the Esc +// was pressed on its own; terminals send the whole sequence in one burst. +constexpr int kEscapeTimeoutMs = 30; + +int readByteTimeout(int timeoutMs) +{ + if (g_pendingByte >= 0) + return readByte(); + struct pollfd fd {}; + fd.fd = STDIN_FILENO; + fd.events = POLLIN; + int ready = 0; + do { + ready = ::poll(&fd, 1, timeoutMs); + } while (ready < 0 && errno == EINTR); + return ready > 0 ? readByte() : -1; +} + +// Columns @p text occupies on the terminal, so the cursor can be put back after +// a redraw. wcwidth() answers -1 outside a UTF-8 locale and every command +// argument is an id, a key name or a path, so one column per unknown character +// is close enough. +// shortcut: a wide CJK character counts as one column in the C locale. +int displayWidth(const QString &text) +{ + int columns = 0; + for (const char32_t code : text.toUcs4()) { + const int width = ::wcwidth(wchar_t(code)); + columns += width > 0 ? width : 1; + } + return columns; +} + +Keypress readEscape() +{ + const int next = readByteTimeout(kEscapeTimeoutMs); + if (next < 0) + return {}; // a lone Esc, or a partial sequence that timed out + // SS3 (ESC O A) is the same arrow when the terminal is in application + // cursor mode; treeland-debug never sets smkx, but a multiplexer might. + if (next == 'O') { + switch (readByte()) { + case 'A': return { Key::Up, {} }; + case 'B': return { Key::Down, {} }; + case 'C': return { Key::Right, {} }; + case 'D': return { Key::Left, {} }; + case 'H': return { Key::Home, {} }; + case 'F': return { Key::End, {} }; + default: return {}; + } + } + if (next != '[') { + g_pendingByte = next; + return {}; // a lone Esc + } + QByteArray params; + int c = 0; + while (true) { + c = readByte(); + if (c < 0) + return {}; + if (c >= '@' && c <= '~') + break; + params.append(char(c)); + } + switch (c) { + case 'A': return { Key::Up, {} }; + case 'B': return { Key::Down, {} }; + case 'C': return { Key::Right, {} }; + case 'D': return { Key::Left, {} }; + case 'H': return { Key::Home, {} }; + case 'F': return { Key::End, {} }; + case '~': + if (params == "1" || params == "7") + return { Key::Home, {} }; + if (params == "4" || params == "8") + return { Key::End, {} }; + if (params == "3") + return { Key::Delete, {} }; + return {}; + default: + return {}; + } +} + +Keypress readKey() +{ + const int c = readByte(); + if (c < 0) + return { Key::StdinClosed, {} }; + switch (c) { + case '\r': + case '\n': return { Key::Enter, {} }; + case 0x7f: + case 0x08: return { Key::Backspace, {} }; + case '\t': return { Key::Tab, {} }; + case 0x03: return { Key::Interrupt, {} }; + case 0x04: return { Key::Eof, {} }; + case 0x01: return { Key::Home, {} }; + case 0x05: return { Key::End, {} }; + case 0x0b: return { Key::KillToEnd, {} }; + case 0x15: return { Key::KillLine, {} }; + case 0x1b: return readEscape(); + default: break; + } + if (c < 0x20) + return {}; // a control key with no binding here: ignore it + + // A UTF-8 lead byte says how many continuation bytes belong to the + // character; they are already in the input buffer, so read them now. + const int extra = c < 0x80 ? 0 + : (c >> 5) == 0x6 ? 1 + : (c >> 4) == 0xe ? 2 + : (c >> 3) == 0x1e ? 3 + : 0; + QByteArray bytes(1, char(c)); + for (int i = 0; i < extra; ++i) { + const int next = readByte(); + if (next < 0) + break; + bytes.append(char(next)); + } + return { Key::Text, QString::fromUtf8(bytes) }; +} + +// Completes the word before the cursor, printing the candidates when nothing +// new can be inserted. +void completeWord(QString *line, int *cursor) +{ + const CompletionEdit edit = completeLine(*line, *cursor); + if (!edit.list.isEmpty()) + writeRaw("\r\n" + edit.list.join(QStringLiteral(" ")).toUtf8() + "\r\n"); + *line = edit.line; + *cursor = edit.cursor; +} + +// A signal that ends the process while the terminal is raw must put it back +// first, or the shell that inherits it is left unusable. tcsetattr() is +// async-signal-safe; the default action is re-raised afterwards so the exit +// status still reports the signal. +struct termios g_savedTermios {}; +volatile sig_atomic_t g_rawMode = 0; +constexpr int kGuardedSignals[] = { SIGINT, SIGTERM, SIGHUP, SIGQUIT }; +constexpr int kGuardedSignalCount = int(std::size(kGuardedSignals)); + +void restoreTerminalOnSignal(int signo) +{ + if (g_rawMode) { + ::tcsetattr(STDIN_FILENO, TCSANOW, &g_savedTermios); + g_rawMode = 0; + } + ::signal(signo, SIG_DFL); + ::raise(signo); +} + +// Puts the terminal back into the mode it was saved in. +class RawMode +{ +public: + bool enter() + { + if (::tcgetattr(STDIN_FILENO, &m_saved) != 0) + return false; + struct termios raw = m_saved; + // ISIG goes too, so Ctrl+C arrives as a keypress the prompt can turn + // into "drop this line"; a live view gets SIGINT after the terminal is + // restored. The cost is that Ctrl+Z and Ctrl+\ do nothing at the prompt. + raw.c_lflag &= ~tcflag_t(ICANON | ECHO | ISIG | IEXTEN); + // Ctrl+S must not freeze the prompt and '^M' must stay an Enter. + raw.c_iflag &= ~tcflag_t(IXON | ICRNL); + raw.c_cc[VMIN] = 1; + raw.c_cc[VTIME] = 0; + // TCSADRAIN, not TCSAFLUSH: a line typed ahead of the prompt is input, + // not garbage, and this runs again for every line. + if (::tcsetattr(STDIN_FILENO, TCSADRAIN, &raw) != 0) + return false; + m_valid = true; + g_savedTermios = m_saved; + g_rawMode = 1; + installGuards(); + return true; + } + + ~RawMode() { restore(); } + +private: + void installGuards() + { + struct sigaction action {}; + action.sa_handler = &restoreTerminalOnSignal; + sigemptyset(&action.sa_mask); + for (int i = 0; i < kGuardedSignalCount; ++i) + ::sigaction(kGuardedSignals[i], &action, &m_oldActions[i]); + } + + void restore() + { + if (!m_valid) // tcgetattr() failed, so there is nothing to put back + return; + ::tcsetattr(STDIN_FILENO, TCSADRAIN, &m_saved); + g_rawMode = 0; + for (int i = 0; i < kGuardedSignalCount; ++i) + ::sigaction(kGuardedSignals[i], &m_oldActions[i], nullptr); + m_valid = false; + } + + struct termios m_saved {}; + struct sigaction m_oldActions[kGuardedSignalCount] {}; + bool m_valid = false; +}; + +} // namespace + +bool ShellLineEditor::readLine(const QString &prompt, QString *line) +{ + RawMode raw; + if (!raw.enter()) + return false; + + QString text; + // shortcut: the cursor steps by QChar, so it can land between the halves of + // a surrogate pair; treeland-debug's arguments are ASCII, so this is not + // worth tracking code points for. + int cursor = 0; + qsizetype historyPos = m_history.size(); // one past the end: the new line + QString draft; // the line being edited when browsing history + bool eof = false; + bool done = false; + + const auto redraw = [&]() { + QByteArray bytes = "\r" + prompt.toUtf8() + text.toUtf8() + "\x1b[K"; + const int back = displayWidth(text.mid(cursor)); + if (back > 0) + bytes += "\x1b[" + QByteArray::number(back) + 'D'; + writeRaw(bytes); + }; + + while (!done) { + redraw(); + const Keypress key = readKey(); + switch (key.key) { + case Key::Text: + if (!key.text.isEmpty()) { + text.insert(cursor, key.text); + cursor += int(key.text.size()); + } + break; + case Key::Enter: + if (!text.trimmed().isEmpty() + && (m_history.isEmpty() || m_history.last() != text)) { + m_history.append(text); + if (m_history.size() > kMaxHistory) + m_history.removeFirst(); + } + writeRaw("\r\n"); + done = true; + break; + case Key::Backspace: + if (cursor > 0) { + text.remove(cursor - 1, 1); + --cursor; + } + break; + case Key::Delete: + if (cursor < text.size()) + text.remove(cursor, 1); + break; + case Key::Tab: + completeWord(&text, &cursor); + break; + case Key::Interrupt: + // A live view is interrupted by SIGINT (ISIG is back on by then); + // at the prompt Ctrl+C just drops what was typed. + writeRaw("^C\r\n"); + text.clear(); + draft.clear(); + cursor = 0; + historyPos = m_history.size(); + break; + case Key::Eof: // Ctrl+D + if (text.isEmpty()) { + writeRaw("\r\n"); + eof = true; + done = true; + } else if (cursor < text.size()) { + text.remove(cursor, 1); // like readline: delete under the cursor + } + break; + case Key::StdinClosed: + // stdin is gone: end the session whatever the line holds, instead + // of deleting a character and reading -1 again in a redraw loop. + writeRaw("\r\n"); + eof = true; + done = true; + break; + case Key::Left: + if (cursor > 0) + --cursor; + break; + case Key::Right: + if (cursor < text.size()) + ++cursor; + break; + case Key::Home: + cursor = 0; + break; + case Key::End: + cursor = int(text.size()); + break; + case Key::KillLine: + text.remove(0, cursor); + cursor = 0; + break; + case Key::KillToEnd: + text.truncate(cursor); + break; + case Key::Up: + if (historyPos > 0) { + if (historyPos == m_history.size()) + draft = text; + --historyPos; + text = m_history.at(historyPos); + cursor = int(text.size()); + } + break; + case Key::Down: + if (historyPos < m_history.size()) { + ++historyPos; + text = historyPos == m_history.size() ? draft : m_history.at(historyPos); + cursor = int(text.size()); + } + break; + } + } + + *line = text; + return !eof; +} diff --git a/tools/treeland-debug/shellline.h b/tools/treeland-debug/shellline.h new file mode 100644 index 0000000000..13adaaf0f4 --- /dev/null +++ b/tools/treeland-debug/shellline.h @@ -0,0 +1,26 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +// Line editor for the interactive shell. Reads stdin in raw mode so a single +// keypress can be acted on: Tab completes commands, arrows move the cursor and +// browse history, Ctrl+C discards the line, Ctrl+D ends the session. The +// terminal is put back into its original mode before readLine() returns, so +// live views (top/events/watch) still see Ctrl+C as SIGINT. +// +// Only used when stdin and stdout are both a terminal; a piped line keeps going +// through QTextStream::readLine(), which needs no editing. +class ShellLineEditor +{ +public: + // Reads one line without its line ending. Returns false on EOF (Ctrl+D on + // an empty line, or stdin closed). + bool readLine(const QString &prompt, QString *line); + +private: + QStringList m_history; +}; diff --git a/tools/treeland-session-helper/CMakeLists.txt b/tools/treeland-session-helper/CMakeLists.txt new file mode 100644 index 0000000000..1343f54f90 --- /dev/null +++ b/tools/treeland-session-helper/CMakeLists.txt @@ -0,0 +1,23 @@ +find_package(Qt6 REQUIRED COMPONENTS WaylandClient Gui Core DBus) +find_package(TreelandProtocols REQUIRED) + +set(BIN_NAME treeland-session-helper) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +qt_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-app-id-resolver-unstable-v2.xml +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Core + Qt6::Gui + Qt6::DBus + Qt6::WaylandClient +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_LIBEXECDIR}") diff --git a/tools/treeland-session-helper/main.cpp b/tools/treeland-session-helper/main.cpp new file mode 100644 index 0000000000..abea875d05 --- /dev/null +++ b/tools/treeland-session-helper/main.cpp @@ -0,0 +1,150 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "qwayland-treeland-app-id-resolver-unstable-v2.h" + +// Ownership: pidfd comes from the Wayland request (SCM_RIGHTS). The protocol layer delivers +// it opened; the handler owns it. We dup it for DBus and close the original here. The DBus +// wrapper then owns and closes the dup. Wayland protocol layer must NOT close pidfd after +// dispatch; otherwise double-close would occur. +static QString identifyViaDBus(int pidfd) +{ + if (pidfd < 0) + return {}; + int dupfd = fcntl(pidfd, F_DUPFD_CLOEXEC, 0); + if (dupfd < 0) { + qWarning() << "dup pidfd failed" << strerror(errno); + // Close the original pidfd to avoid FD leak + if (close(pidfd) != 0) { + qWarning() << "close pidfd failed" << strerror(errno); + } + return {}; + } + // Close the original pidfd after duplicating + if (close(pidfd) != 0) { + qWarning() << "close pidfd failed" << strerror(errno); + } + QDBusUnixFileDescriptor wrapper(dupfd); // wrapper owns and will close dupfd + auto msg = QDBusMessage::createMethodCall( + "org.desktopspec.ApplicationManager1", + "/org/desktopspec/ApplicationManager1", + "org.desktopspec.ApplicationManager1", + "Identify"); + msg << QVariant::fromValue(wrapper); + auto reply = QDBusConnection::sessionBus().call(msg, QDBus::BlockWithGui); + if (reply.type() != QDBusMessage::ReplyMessage || reply.arguments().isEmpty()) { + qWarning() << "DBus Identify failed" + << "service=" << msg.service() + << "path=" << msg.path() + << "interface=" << msg.interface() + << "method=" << msg.member() + << "error=" << reply.errorMessage(); + return {}; + } + const QString appId = reply.arguments().first().toString(); + if (appId.isEmpty()) + qWarning() << "Empty appId"; + return appId; +} + +class AppIdResolver : public QObject, public QtWayland::treeland_app_id_resolver_v2 +{ + Q_OBJECT +public: + explicit AppIdResolver(struct ::treeland_app_id_resolver_v2 *object, QObject *parent = nullptr) + : QObject(parent) + , QtWayland::treeland_app_id_resolver_v2(object) {} + +protected: + void treeland_app_id_resolver_v2_identify_request(uint32_t request_id, int32_t pidfd) override + { + qInfo() << "identify_request" << request_id << pidfd; + const QString appId = identifyViaDBus(pidfd); + // Only dde-application-manager is supported as sandbox engine at present. + static const auto kSandboxEngine = QStringLiteral("dde-application-manager"); + respond(request_id, appId, kSandboxEngine); + qInfo() << "respond sent" << request_id << appId; + } +}; + +class AppIdResolverManager + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_app_id_resolver_manager_v2 +{ + Q_OBJECT +public: + AppIdResolverManager() + : QWaylandClientExtensionTemplate(1) // version 1 + { + } + + ~AppIdResolverManager() + { + cleanupResolver(); + } + + void ensureResolver() + { + if (m_resolver) { + qInfo() << "Resolver already exists!"; + return; + } + auto *raw = get_resolver(); + if (!raw) { + qWarning() << "get_resolver returned null"; + return; + } + m_resolver = new AppIdResolver(raw, this); + qInfo() << "Resolver object created"; + } + + void cleanupResolver() + { + if (!m_resolver) + return; + auto *resolver = m_resolver; + m_resolver = nullptr; + if (isActive() && resolver->isInitialized()) { + resolver->destroy(); + } + delete resolver; + qInfo() << "Resolver object destroyed"; + } + +private: + AppIdResolver *m_resolver = nullptr; +}; + +int main(int argc, char **argv) +{ + qputenv("QT_QPA_PLATFORM", "wayland"); + QGuiApplication app(argc, argv); + + AppIdResolverManager manager; + QObject::connect(&manager, &AppIdResolverManager::activeChanged, &manager, [&manager] { + if (manager.isActive()) { + qInfo() << "Resolver manager active"; + manager.ensureResolver(); + } else { + qWarning() << "Resolver manager inactive"; + manager.cleanupResolver(); + } + }); + + qInfo() << "treeland-session-helper running"; + return app.exec(); +} + +#include "main.moc" diff --git a/translations/treeland.af.ts b/translations/treeland.af.ts new file mode 100644 index 0000000000..c803543df3 --- /dev/null +++ b/translations/treeland.af.ts @@ -0,0 +1,55 @@ + + + WindowMenu + + + Minimize + + + + + Unmaximize + + + + + Maximize + + + + + Move + + + + + Resize + Hervergroot + + + + Always on Top + + + + + Always on Visible Workspace + + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + + + + \ No newline at end of file diff --git a/translations/treeland.am_ET.ts b/translations/treeland.am_ET.ts new file mode 100644 index 0000000000..eb51379999 --- /dev/null +++ b/translations/treeland.am_ET.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + ማሳነሻ + + + + Unmaximize + ማሳነሻ + + + + Maximize + ማሳደጊያ + + + + Move + ማንቀሳቀሻ + + + + Resize + እንደገና መመጠኛ + + + + Always on Top + ሁልጊዜ ከ ላይ + + + + Always on Visible Workspace + ሁልጊዜ በሚታይ የ ስራ ቦታ ላይ + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + መዝጊያ + + + \ No newline at end of file diff --git a/translations/treeland.ar.ts b/translations/treeland.ar.ts new file mode 100644 index 0000000000..ad2f74ac70 --- /dev/null +++ b/translations/treeland.ar.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + جارٍ تحميل التطبيق... + + + + WindowMenu + + + Minimize + تصغير + + + + Unmaximize + إلغاء التكبير + + + + Maximize + تكبير + + + + Move + نقل + + + + Resize + تغيير الحجم + + + + Always on Top + دائما فوق + + + + Always on Visible Workspace + دائما فوق مساحة العمل الظاهرة + + + + Move to Left Work Space + الانتقال إلى مساحة العمل اليسرى + + + + Move to Right Work Space + الانتقال إلى مساحة العمل اليمنى + + + + Close + إغلاق + + + \ No newline at end of file diff --git a/translations/treeland.ast.ts b/translations/treeland.ast.ts new file mode 100644 index 0000000000..68e42f5bd2 --- /dev/null +++ b/translations/treeland.ast.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Minimizar + + + + Unmaximize + Desmaximizar + + + + Maximize + Maximinizar + + + + Move + Mover + + + + Resize + Redimensionar + + + + Always on Top + Siempres enriba + + + + Always on Visible Workspace + Siempres na estaya de trabayu visible + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Zarrar + + + \ No newline at end of file diff --git a/translations/treeland.az.ts b/translations/treeland.az.ts new file mode 100644 index 0000000000..fb98a7b30e --- /dev/null +++ b/translations/treeland.az.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Yığmaq + + + + Unmaximize + Tam açmaq + + + + Maximize + Genişləndirmək + + + + Move + Köçürmək + + + + Resize + Ölçüsünü dəyişmək + + + + Always on Top + Həmişə yuxarıda + + + + Always on Visible Workspace + Həmişə görünən İş sahəsində + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Bağlamaq + + + \ No newline at end of file diff --git a/translations/treeland.bg.ts b/translations/treeland.bg.ts new file mode 100644 index 0000000000..207f9edb50 --- /dev/null +++ b/translations/treeland.bg.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Минимизиране + + + + Unmaximize + Демаксимизиране + + + + Maximize + Максимизиране + + + + Move + Преместване + + + + Resize + Преоразмеряване + + + + Always on Top + Винаги отгоре + + + + Always on Visible Workspace + Винаги на Видимото Работно място + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Затваряне + + + \ No newline at end of file diff --git a/translations/treeland.bn.ts b/translations/treeland.bn.ts new file mode 100644 index 0000000000..d7c64d6f9b --- /dev/null +++ b/translations/treeland.bn.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + ছোটও করুন + + + + Unmaximize + সর্বাধিক বড় নয় + + + + Maximize + সর্বাধিক বড় করুন + + + + Move + সরান + + + + Resize + আকার পরিবর্তন করুন + + + + Always on Top + সবসময় উপড়ে দেখাবে + + + + Always on Visible Workspace + কর্মস্থানে সবসময় দেখাবে + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + বন্ধ করুন + + + \ No newline at end of file diff --git a/translations/treeland.bo.ts b/translations/treeland.bo.ts new file mode 100644 index 0000000000..c03a0bd546 --- /dev/null +++ b/translations/treeland.bo.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + ཆུང་སྒྱུར། + + + + Unmaximize + སོར་ཆུད། + + + + Maximize + ཆེ་སྒྱུར། + + + + Move + སྤོ་བ། + + + + Resize + ཆེ་ཆུང་བཟོ་བཅོས་བྱེད་པ། + + + + Always on Top + རྟག་ཏུ་མདུན་གྲལ་དུ་ཡོད་པ། + + + + Always on Visible Workspace + རྟག་ཏུ་མཐོང་ཐུབ་སའི་ལས་ཁུལ་དུ་ཡོད་པ། + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + སྒོ་རྒྱོབ། + + + \ No newline at end of file diff --git a/translations/treeland.bqi.ts b/translations/treeland.bqi.ts new file mode 100644 index 0000000000..467fdbe3e2 --- /dev/null +++ b/translations/treeland.bqi.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + kučir kerdên + + + + Unmaximize + zê gapi dêravordên + + + + Maximize + gap kerdên + + + + Move + jā goro kerdên + + + + Resize + ālêštê hêndā + + + + Always on Top + hay vā ro' bu + + + + Always on Visible Workspace + hay mênê jāga kâri diyâri bu + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + bastên + + + \ No newline at end of file diff --git a/translations/treeland.br.ts b/translations/treeland.br.ts new file mode 100644 index 0000000000..d71b4c7cff --- /dev/null +++ b/translations/treeland.br.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Bihanaat + + + + Unmaximize + Adsevel + + + + Maximize + Brasaat + + + + Move + Fiñval + + + + Resize + Adventañ + + + + Always on Top + A-us dalc'hmat + + + + Always on Visible Workspace + War ar spas-labour hewel dalc'hmat + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Serriñ + + + \ No newline at end of file diff --git a/translations/treeland.ca.ts b/translations/treeland.ca.ts new file mode 100644 index 0000000000..5dd6ae8e2a --- /dev/null +++ b/translations/treeland.ca.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + Es carrega l'aplicació... + + + + WindowMenu + + + Minimize + Minimitza + + + + Unmaximize + Desmaximitza + + + + Maximize + Maximitza + + + + Move + Mou + + + + Resize + Canvia'n la mida + + + + Always on Top + Sempre a dalt + + + + Always on Visible Workspace + Sempre a l'espai de treball visible + + + + Move to Left Work Space + Mou a l'espai de treball de l'esquerra + + + + Move to Right Work Space + Mou a l'espai de treball de la dreta + + + + Close + Tanca + + + \ No newline at end of file diff --git a/translations/treeland.ckb.ts b/translations/treeland.ckb.ts new file mode 100644 index 0000000000..77d22747a7 --- /dev/null +++ b/translations/treeland.ckb.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + بچووکردنەوە + + + + Unmaximize + + + + + Maximize + + + + + Move + + + + + Resize + + + + + Always on Top + + + + + Always on Visible Workspace + + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + داخستن + + + \ No newline at end of file diff --git a/translations/treeland.cs.ts b/translations/treeland.cs.ts new file mode 100644 index 0000000000..bd0c44273f --- /dev/null +++ b/translations/treeland.cs.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Minimalizovat + + + + Unmaximize + Zrušit maximalizaci + + + + Maximize + Maximalizovat + + + + Move + Přesunout + + + + Resize + Změnit velikost + + + + Always on Top + Vždy nahoře + + + + Always on Visible Workspace + Vždy na právě zobrazované pracovní ploše + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Zavřít + + + \ No newline at end of file diff --git a/translations/treeland.da.ts b/translations/treeland.da.ts new file mode 100644 index 0000000000..e1d212faab --- /dev/null +++ b/translations/treeland.da.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Minimer + + + + Unmaximize + Gendan + + + + Maximize + Maksimer + + + + Move + Flyt + + + + Resize + Tilpas størrelse + + + + Always on Top + Altid øverst + + + + Always on Visible Workspace + Altid på synligt arbejdsområde + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Luk + + + \ No newline at end of file diff --git a/translations/treeland.de.ts b/translations/treeland.de.ts new file mode 100644 index 0000000000..c4d2516156 --- /dev/null +++ b/translations/treeland.de.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Minimieren + + + + Unmaximize + Unmaximieren + + + + Maximize + Maximieren + + + + Move + Verschieben + + + + Resize + Größe ändern + + + + Always on Top + Immer im Vordergrund + + + + Always on Visible Workspace + Immer auf sichtbarem Arbeitsbereich + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Schließen + + + \ No newline at end of file diff --git a/translations/treeland.el.ts b/translations/treeland.el.ts new file mode 100644 index 0000000000..8f4489bcd6 --- /dev/null +++ b/translations/treeland.el.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Ελαχιστοποίηση + + + + Unmaximize + Απομεγιστοποίηση + + + + Maximize + Μεγιστοποίηση + + + + Move + Μετακίνηση + + + + Resize + Αλλαγή μεγέθους + + + + Always on Top + Πάντα στη Κορυφή + + + + Always on Visible Workspace + Πάντα σε ορατό χώρο εργασίας + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Κλείσιμο + + + \ No newline at end of file diff --git a/translations/treeland.en_US.ts b/translations/treeland.en_US.ts new file mode 100644 index 0000000000..316a142201 --- /dev/null +++ b/translations/treeland.en_US.ts @@ -0,0 +1,65 @@ + + + + + PrelaunchSplash + + + Loading application... + Loading application... + + + + WindowMenu + + + Minimize + + + + + Unmaximize + + + + + Maximize + + + + + Move + + + + + Resize + + + + + Always on Top + + + + + Always on Visible Workspace + + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + + + + diff --git a/translations/treeland.es.ts b/translations/treeland.es.ts new file mode 100644 index 0000000000..54aaa6ddee --- /dev/null +++ b/translations/treeland.es.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + Cargando aplicación... + + + + WindowMenu + + + Minimize + Minimizar + + + + Unmaximize + Restaurar + + + + Maximize + Maximizar + + + + Move + Mover + + + + Resize + Redimensionar + + + + Always on Top + Siempre encima + + + + Always on Visible Workspace + Visible en todos los espacios de trabajo + + + + Move to Left Work Space + Mover al espacio de trabajo de la izquierda + + + + Move to Right Work Space + Mover al espacio de trabajo de la derecha + + + + Close + Cerrar + + + \ No newline at end of file diff --git a/translations/treeland.fa.ts b/translations/treeland.fa.ts new file mode 100644 index 0000000000..bdd150f829 --- /dev/null +++ b/translations/treeland.fa.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + کمینه + + + + Unmaximize + غیر بیشینه + + + + Maximize + بزرگ + + + + Move + حرکت + + + + Resize + تغییر اندازه + + + + Always on Top + همیشه روی صفحه + + + + Always on Visible Workspace + همیشه در فضای کار قابل مشاهده باشد + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + بستن + + + \ No newline at end of file diff --git a/translations/treeland.fi.ts b/translations/treeland.fi.ts new file mode 100644 index 0000000000..83a864c213 --- /dev/null +++ b/translations/treeland.fi.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + Sovellusta ladataan... + + + + WindowMenu + + + Minimize + Pienennä + + + + Unmaximize + Paluu + + + + Maximize + Suurenna + + + + Move + Siirrä + + + + Resize + Koko + + + + Always on Top + Aina päällä + + + + Always on Visible Workspace + Aina näkyvässä työtilassa + + + + Move to Left Work Space + Siirry vasempaan työtilaan + + + + Move to Right Work Space + Siirry oikeaan työtilaan + + + + Close + Sulje + + + \ No newline at end of file diff --git a/translations/treeland.fr.ts b/translations/treeland.fr.ts new file mode 100644 index 0000000000..f177039fee --- /dev/null +++ b/translations/treeland.fr.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Réduire + + + + Unmaximize + Restaurer + + + + Maximize + Agrandir + + + + Move + Déplacer + + + + Resize + Redimensionner + + + + Always on Top + Toujours au-dessus + + + + Always on Visible Workspace + Toujours sur l'espace de travail visible + + + + Move to Left Work Space + Déplacer vers l'espace de travail gauche + + + + Move to Right Work Space + Déplacer vers l'espace de travail droit + + + + Close + Fermer + + + \ No newline at end of file diff --git a/translations/treeland.gl_ES.ts b/translations/treeland.gl_ES.ts new file mode 100644 index 0000000000..e33187a377 --- /dev/null +++ b/translations/treeland.gl_ES.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + Cargando aplicación... + + + + WindowMenu + + + Minimize + Minimizar + + + + Unmaximize + Desmarcar + + + + Maximize + Maximizar + + + + Move + Mover + + + + Resize + Redimensionar + + + + Always on Top + Sempre enriba + + + + Always on Visible Workspace + Sempre en espazo de traballo visible + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Pechar + + + \ No newline at end of file diff --git a/translations/treeland.he.ts b/translations/treeland.he.ts new file mode 100644 index 0000000000..f66810b7c4 --- /dev/null +++ b/translations/treeland.he.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + מזעור + + + + Unmaximize + ביטול מזעור + + + + Maximize + הגדלה + + + + Move + הזזה + + + + Resize + שינוי גודל + + + + Always on Top + + + + + Always on Visible Workspace + + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + סגירה + + + \ No newline at end of file diff --git a/translations/treeland.hi_IN.ts b/translations/treeland.hi_IN.ts new file mode 100644 index 0000000000..54946ea3a7 --- /dev/null +++ b/translations/treeland.hi_IN.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + संक्षिप्त करें + + + + Unmaximize + सामान्य आकार करें + + + + Maximize + विस्तृत करें + + + + Move + स्थान परिवर्तन करें + + + + Resize + आकार बदलें + + + + Always on Top + सदैव शीर्ष पर + + + + Always on Visible Workspace + सदैव दृश्यमान कार्यस्थल पर + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + बंद करें + + + \ No newline at end of file diff --git a/translations/treeland.hr.ts b/translations/treeland.hr.ts new file mode 100644 index 0000000000..1a308fb296 --- /dev/null +++ b/translations/treeland.hr.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Smanji + + + + Unmaximize + Vrati iz povećanog + + + + Maximize + Povećaj + + + + Move + Premjesti + + + + Resize + Promjeni veličinu + + + + Always on Top + Uvijek na vrhu + + + + Always on Visible Workspace + Uvijek na vidljivom radnom prostoru + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Zatvori + + + \ No newline at end of file diff --git a/translations/treeland.hu.ts b/translations/treeland.hu.ts new file mode 100644 index 0000000000..67d963c074 --- /dev/null +++ b/translations/treeland.hu.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Kis méret + + + + Unmaximize + Teljes méret visszavonása + + + + Maximize + Teljes méret + + + + Move + Mozgatás + + + + Resize + Átméretezés + + + + Always on Top + Mindig legyen felül + + + + Always on Visible Workspace + Mindig legyen látható a munkaterületen + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Bezárás + + + \ No newline at end of file diff --git a/translations/treeland.id.ts b/translations/treeland.id.ts new file mode 100644 index 0000000000..33d7b093d7 --- /dev/null +++ b/translations/treeland.id.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Minimalkan + + + + Unmaximize + kembali ukuran semula + + + + Maximize + Maksimalkan + + + + Move + Pindahkan + + + + Resize + Ubah Ukuran + + + + Always on Top + Selalu di atas + + + + Always on Visible Workspace + Selalu di Bagian Yang Terlihat + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Tutup + + + \ No newline at end of file diff --git a/translations/treeland.it.ts b/translations/treeland.it.ts new file mode 100644 index 0000000000..75239ecb2d --- /dev/null +++ b/translations/treeland.it.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Riduci + + + + Unmaximize + Non espandere + + + + Maximize + Espandi + + + + Move + Muovi + + + + Resize + Ridimensiona + + + + Always on Top + Sempre in primo piano + + + + Always on Visible Workspace + Sempre nello spazio di lavoro visibile + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Chiudi + + + \ No newline at end of file diff --git a/translations/treeland.ja.ts b/translations/treeland.ja.ts new file mode 100644 index 0000000000..aa553bcb44 --- /dev/null +++ b/translations/treeland.ja.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + 最小化 + + + + Unmaximize + 元のサイズに戻す + + + + Maximize + 最大化 + + + + Move + 移動 + + + + Resize + サイズ変更 + + + + Always on Top + 常に最前面に表示 + + + + Always on Visible Workspace + 表示中のワークスペースに常に表示 + + + + Move to Left Work Space + 左側のワークスペースに移動 + + + + Move to Right Work Space + 右側のワークスペースに移動 + + + + Close + 閉じる + + + \ No newline at end of file diff --git a/translations/treeland.ka.ts b/translations/treeland.ka.ts new file mode 100644 index 0000000000..ec427cd9e7 --- /dev/null +++ b/translations/treeland.ka.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + დაპატარვება + + + + Unmaximize + დაპატარავება + + + + Maximize + გადიდება + + + + Move + გადაადგილება + + + + Resize + ზომის შეცვლა + + + + Always on Top + ყოველთვის წინა ფლანგზე + + + + Always on Visible Workspace + ყოველთვის არჩეულ სამუშაო ეკრანზე + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + დახურვა + + + \ No newline at end of file diff --git a/translations/treeland.kab.ts b/translations/treeland.kab.ts new file mode 100644 index 0000000000..52ca1146db --- /dev/null +++ b/translations/treeland.kab.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Fneẓ + + + + Unmaximize + Ur semɣer ara + + + + Maximize + Semɣer + + + + Move + Senkez + + + + Resize + Semsawi teɣzi + + + + Always on Top + Yal tikkelt deg ufella + + + + Always on Visible Workspace + Yal tikkelt deg tallunt n umahil ibanen + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Mdel + + + \ No newline at end of file diff --git a/translations/treeland.km_KH.ts b/translations/treeland.km_KH.ts new file mode 100644 index 0000000000..997536a7e6 --- /dev/null +++ b/translations/treeland.km_KH.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + បង្រួមអប្បបរមា + + + + Unmaximize + បង្រួម + + + + Maximize + ពង្រីកអតិបរិមា + + + + Move + ផ្លាស់ទី + + + + Resize + ផ្លាស់ប្តូរទំហំ + + + + Always on Top + តែងតែនៅលើកំពូល + + + + Always on Visible Workspace + តែងតែនៅលើកន្លែងធ្វើការដែលអាចមើលឃើញ + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + បិទ + + + \ No newline at end of file diff --git a/translations/treeland.ko.ts b/translations/treeland.ko.ts new file mode 100644 index 0000000000..78324d3726 --- /dev/null +++ b/translations/treeland.ko.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + 최소화 + + + + Unmaximize + 최대화 해제 + + + + Maximize + 최대화 + + + + Move + 이동 + + + + Resize + 크기 조정 + + + + Always on Top + 항상 위에 위치 + + + + Always on Visible Workspace + 항상 보이는 작업공간에 위치 + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + 닫기 + + + \ No newline at end of file diff --git a/translations/treeland.ku.ts b/translations/treeland.ku.ts new file mode 100644 index 0000000000..a4adfe5232 --- /dev/null +++ b/translations/treeland.ku.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + + + + + Unmaximize + + + + + Maximize + + + + + Move + + + + + Resize + Mezinahiyê Biguherîne + + + + Always on Top + + + + + Always on Visible Workspace + + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Girtin + + + \ No newline at end of file diff --git a/translations/treeland.lt.ts b/translations/treeland.lt.ts new file mode 100644 index 0000000000..1917bb91b8 --- /dev/null +++ b/translations/treeland.lt.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Suskleisti + + + + Unmaximize + Grąžinti iš išskleidimo + + + + Maximize + Išskleisti + + + + Move + Perkelti + + + + Resize + Keisti dydį + + + + Always on Top + Visada viršuje + + + + Always on Visible Workspace + Visada matomoje darbo srityje + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Užverti + + + \ No newline at end of file diff --git a/translations/treeland.mn.ts b/translations/treeland.mn.ts new file mode 100644 index 0000000000..3c5f8916be --- /dev/null +++ b/translations/treeland.mn.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + Loading application... + + + + WindowMenu + + + Minimize + Хамгийн багасгах + + + + Unmaximize + Томроос буцаах + + + + Maximize + Томрох + + + + Move + Зөөх + + + + Resize + Хэмжээ өөрчлөх + + + + Always on Top + Байнга дээр + + + + Always on Visible Workspace + Байнга харагдах ажлын талбар дээр + + + + Move to Left Work Space + Зүүн ажлын талбар руу зөөх + + + + Move to Right Work Space + Баруун ажлын талбар руу зөөх + + + + Close + Хаах + + + \ No newline at end of file diff --git a/translations/treeland.ms.ts b/translations/treeland.ms.ts new file mode 100644 index 0000000000..9efb086cb3 --- /dev/null +++ b/translations/treeland.ms.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Minimum + + + + Unmaximize + Nyahmaksimum + + + + Maximize + Maksimum + + + + Move + Alih + + + + Resize + Saiz Semula + + + + Always on Top + Sentiasa di Atas + + + + Always on Visible Workspace + Sentiasa pada Ruang Kerja Semasa + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Tutup + + + \ No newline at end of file diff --git a/translations/treeland.nb.ts b/translations/treeland.nb.ts new file mode 100644 index 0000000000..f92bc3db4e --- /dev/null +++ b/translations/treeland.nb.ts @@ -0,0 +1,55 @@ + + + WindowMenu + + + Minimize + + + + + Unmaximize + + + + + Maximize + + + + + Move + + + + + Resize + + + + + Always on Top + + + + + Always on Visible Workspace + + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Lukk + + + \ No newline at end of file diff --git a/translations/treeland.ne.ts b/translations/treeland.ne.ts new file mode 100644 index 0000000000..18f494e21f --- /dev/null +++ b/translations/treeland.ne.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + मिनिमाइज गर्नुहोस् + + + + Unmaximize + अनमाक्सिमाइज गर्नुहोस् + + + + Maximize + माक्सिमाइज गर्नुहोस् + + + + Move + सार्नु होस् + + + + Resize + पुनःआकार गर्नुहोस् + + + + Always on Top + सधै माथि + + + + Always on Visible Workspace + सँधै दृश्यमान कार्यस्थानमा + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + बन्द + + + \ No newline at end of file diff --git a/translations/treeland.nl.ts b/translations/treeland.nl.ts new file mode 100644 index 0000000000..56ec0bae67 --- /dev/null +++ b/translations/treeland.nl.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Minimaliseren + + + + Unmaximize + Verkleinen + + + + Maximize + Maximaliseren + + + + Move + Verplaatsen + + + + Resize + Formaat wijzigen + + + + Always on Top + Altijd op voorgrond + + + + Always on Visible Workspace + Altijd op zichtbare bureaublad + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Sluiten + + + \ No newline at end of file diff --git a/translations/treeland.pl.ts b/translations/treeland.pl.ts new file mode 100644 index 0000000000..159e4f8d57 --- /dev/null +++ b/translations/treeland.pl.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + Wczytywanie aplikacji... + + + + WindowMenu + + + Minimize + Minimalizuj + + + + Unmaximize + Normalizuj + + + + Maximize + Maksymalizuj + + + + Move + Przenieś + + + + Resize + Zmień rozmiar + + + + Always on Top + Zawsze na wierzchu + + + + Always on Visible Workspace + Zawsze na widocznym obszarze roboczym + + + + Move to Left Work Space + Przenieś na lewy obszar roboczy + + + + Move to Right Work Space + Przenieś na prawy obszar roboczy + + + + Close + Zamknij + + + \ No newline at end of file diff --git a/translations/treeland.pt.ts b/translations/treeland.pt.ts new file mode 100644 index 0000000000..97c7a8179a --- /dev/null +++ b/translations/treeland.pt.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + A carregar aplicação... + + + + WindowMenu + + + Minimize + Minimizar + + + + Unmaximize + Repor + + + + Maximize + Maximizar + + + + Move + Mover + + + + Resize + Redimensionar + + + + Always on Top + Sempre no topo + + + + Always on Visible Workspace + Sempre na área de trabalho visível + + + + Move to Left Work Space + Mover para o Espaço de Trabalho à Esquerda + + + + Move to Right Work Space + Mover para o Espaço de Trabalho à Direita + + + + Close + Fechar + + + \ No newline at end of file diff --git a/translations/treeland.pt_BR.ts b/translations/treeland.pt_BR.ts new file mode 100644 index 0000000000..0a99710a1e --- /dev/null +++ b/translations/treeland.pt_BR.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + Carregando aplicativo... + + + + WindowMenu + + + Minimize + Minimizar + + + + Unmaximize + Desmaximizar + + + + Maximize + Maximizar + + + + Move + Mover + + + + Resize + Redimensionar + + + + Always on Top + Sempre na frente + + + + Always on Visible Workspace + Sempre à frente nos espaços de trabalho + + + + Move to Left Work Space + Mover para o espaço de trabalho à esquerda + + + + Move to Right Work Space + Mover para o espaço de trabalho à direita + + + + Close + Fechar + + + \ No newline at end of file diff --git a/translations/treeland.ro.ts b/translations/treeland.ro.ts new file mode 100644 index 0000000000..ef45be705c --- /dev/null +++ b/translations/treeland.ro.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Minimizare + + + + Unmaximize + Demaximizare + + + + Maximize + Maximizare + + + + Move + Mută + + + + Resize + Redimensionează + + + + Always on Top + Mereu Deasupra + + + + Always on Visible Workspace + Mereu pe Spațiul Activ + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Închide + + + \ No newline at end of file diff --git a/translations/treeland.ru.ts b/translations/treeland.ru.ts new file mode 100644 index 0000000000..da95b2a683 --- /dev/null +++ b/translations/treeland.ru.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + Загрузка приложения... + + + + WindowMenu + + + Minimize + Минимизировать + + + + Unmaximize + Отменить максимизацию + + + + Maximize + Максимизировать + + + + Move + Переместить + + + + Resize + Изменить размер + + + + Always on Top + Всегда сверху + + + + Always on Visible Workspace + Всегда на видимом рабочем пространстве + + + + Move to Left Work Space + Переместить на левое рабочее пространство + + + + Move to Right Work Space + Переместить на правое рабочее пространство + + + + Close + Закрыть + + + \ No newline at end of file diff --git a/translations/treeland.si.ts b/translations/treeland.si.ts new file mode 100644 index 0000000000..d25f295043 --- /dev/null +++ b/translations/treeland.si.ts @@ -0,0 +1,55 @@ + + + WindowMenu + + + Minimize + + + + + Unmaximize + + + + + Maximize + + + + + Move + + + + + Resize + + + + + Always on Top + + + + + Always on Visible Workspace + + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + වසා දමන්න + + + \ No newline at end of file diff --git a/translations/treeland.sk.ts b/translations/treeland.sk.ts new file mode 100644 index 0000000000..578576b22e --- /dev/null +++ b/translations/treeland.sk.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Minimalizovať + + + + Unmaximize + Obnoviť + + + + Maximize + Maximalizovať + + + + Move + Presunúť + + + + Resize + Zmeniť veľkosť + + + + Always on Top + Vždy na vrchu + + + + Always on Visible Workspace + Vždy na viditeľnej pracovnej ploche + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Zavrieť + + + \ No newline at end of file diff --git a/translations/treeland.sl.ts b/translations/treeland.sl.ts new file mode 100644 index 0000000000..b3df866160 --- /dev/null +++ b/translations/treeland.sl.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Zmanjšaj + + + + Unmaximize + Odmanjšaj + + + + Maximize + Povečaj + + + + Move + Premakni + + + + Resize + Spremeni velikost + + + + Always on Top + Vedno na vrhu + + + + Always on Visible Workspace + Vedno na vidni delovni površini + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Zapri + + + \ No newline at end of file diff --git a/translations/treeland.sq.ts b/translations/treeland.sq.ts new file mode 100644 index 0000000000..531dd62537 --- /dev/null +++ b/translations/treeland.sq.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + Po ngarkohet aplikacion… + + + + WindowMenu + + + Minimize + Minimizoje + + + + Unmaximize + Shmaksimizoje + + + + Maximize + Maksimizoje + + + + Move + Lëvize + + + + Resize + Ripërmasoje + + + + Always on Top + Përherë Në Krye + + + + Always on Visible Workspace + Përherë në Hapësirë Pune të Dukshme + + + + Move to Left Work Space + Shpjere te Hapësira e Punës Majtas + + + + Move to Right Work Space + Shpjere te Hapësira e Punës Djathtas + + + + Close + Mbylle + + + \ No newline at end of file diff --git a/translations/treeland.sr.ts b/translations/treeland.sr.ts new file mode 100644 index 0000000000..99d139d750 --- /dev/null +++ b/translations/treeland.sr.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Минимализуј + + + + Unmaximize + Врати претходну величину + + + + Maximize + Максимализуј + + + + Move + Премести + + + + Resize + Промени величину + + + + Always on Top + Увек изнад осталих + + + + Always on Visible Workspace + Увек на приказаном радном простору + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Затвори + + + \ No newline at end of file diff --git a/translations/treeland.sv.ts b/translations/treeland.sv.ts new file mode 100644 index 0000000000..eeffaf8c5b --- /dev/null +++ b/translations/treeland.sv.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Minimera + + + + Unmaximize + Avmaximera + + + + Maximize + Maximera + + + + Move + Flytta + + + + Resize + Ändra storlek + + + + Always on Top + Alltid på topp + + + + Always on Visible Workspace + Alltid på synlig arbetsyta + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Stäng + + + \ No newline at end of file diff --git a/translations/treeland.ta.ts b/translations/treeland.ta.ts new file mode 100644 index 0000000000..13bedff98f --- /dev/null +++ b/translations/treeland.ta.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + சிறிதாக்கு + + + + Unmaximize + + + + + Maximize + பெரிதக்கு + + + + Move + நகர்த்து + + + + Resize + அளவை மாற்று + + + + Always on Top + + + + + Always on Visible Workspace + + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + + + + \ No newline at end of file diff --git a/translations/treeland.te.ts b/translations/treeland.te.ts new file mode 100644 index 0000000000..5b5f66a927 --- /dev/null +++ b/translations/treeland.te.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + + + + + Unmaximize + + + + + Maximize + + + + + Move + + + + + Resize + పునఃపరిమాణము + + + + Always on Top + + + + + Always on Visible Workspace + + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + మూయి + + + \ No newline at end of file diff --git a/translations/treeland.th.ts b/translations/treeland.th.ts new file mode 100644 index 0000000000..0c40e5a427 --- /dev/null +++ b/translations/treeland.th.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + + + + + Unmaximize + + + + + Maximize + + + + + Move + + + + + Resize + ปรับขนาด + + + + Always on Top + + + + + Always on Visible Workspace + + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + ปิด + + + \ No newline at end of file diff --git a/translations/treeland.tr.ts b/translations/treeland.tr.ts new file mode 100644 index 0000000000..93dec61c7e --- /dev/null +++ b/translations/treeland.tr.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Küçült + + + + Unmaximize + Önceki Boyut + + + + Maximize + Ekranı Kapla + + + + Move + Taşı + + + + Resize + Boyutlandır + + + + Always on Top + Sürekli Üstte + + + + Always on Visible Workspace + Sürekli Çalışma Alanında Görün + + + + Move to Left Work Space + Sol Çalışma Alanına Taşı + + + + Move to Right Work Space + Sağ Çalışma AlanınaTaşı + + + + Close + Kapat + + + \ No newline at end of file diff --git a/translations/treeland.tzm.ts b/translations/treeland.tzm.ts new file mode 100644 index 0000000000..131bb314ba --- /dev/null +++ b/translations/treeland.tzm.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Ssemẓi + + + + Unmaximize + + + + + Maximize + Ssemɣer + + + + Move + + + + + Resize + + + + + Always on Top + + + + + Always on Visible Workspace + + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Rgel + + + \ No newline at end of file diff --git a/translations/treeland.ug.ts b/translations/treeland.ug.ts new file mode 100644 index 0000000000..81cedb5e22 --- /dev/null +++ b/translations/treeland.ug.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + كىچىكلىتىش + + + + Unmaximize + ئەسلىگە كەلتۈرۈش + + + + Maximize + چوڭايتىش + + + + Move + يۆتكەش + + + + Resize + چوڭلىقىنى تەڭشەش + + + + Always on Top + دائىم ئەڭ ئۈستى تەرەپتە تۇرسۇن + + + + Always on Visible Workspace + دائىم خىزمەت رايونىدا كۆرۈنسۇن + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + تاقاش + + + \ No newline at end of file diff --git a/translations/treeland.uk.ts b/translations/treeland.uk.ts new file mode 100644 index 0000000000..aada439788 --- /dev/null +++ b/translations/treeland.uk.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Мінімізувати + + + + Unmaximize + Розмаксимізувати + + + + Maximize + Максимізувати + + + + Move + Пересунути + + + + Resize + Змінити розміри + + + + Always on Top + Утримувати над іншими + + + + Always on Visible Workspace + Завжди на видимому робочому просторі + + + + Move to Left Work Space + Пересунути на лівий робочий простір + + + + Move to Right Work Space + Пересунути на правий робочий простір + + + + Close + Закрити + + + \ No newline at end of file diff --git a/translations/treeland.vi.ts b/translations/treeland.vi.ts new file mode 100644 index 0000000000..922b6edda8 --- /dev/null +++ b/translations/treeland.vi.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + Thu nhỏ + + + + Unmaximize + Không phóng to + + + + Maximize + Phóng to + + + + Move + Di chuyển + + + + Resize + Thay đổi kích thước + + + + Always on Top + Đặt ứng dụng luôn nằm trên cùng + + + + Always on Visible Workspace + Luôn có hiển thị trên không gian làm việc + + + + Move to Left Work Space + + + + + Move to Right Work Space + + + + + Close + Đóng + + + \ No newline at end of file diff --git a/translations/treeland.zh_CN.ts b/translations/treeland.zh_CN.ts new file mode 100644 index 0000000000..e9596495fe --- /dev/null +++ b/translations/treeland.zh_CN.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + 应用加载中... + + + + WindowMenu + + + Minimize + 最小化 + + + + Unmaximize + 还原 + + + + Maximize + 最大化 + + + + Move + 移动 + + + + Resize + 更改大小 + + + + Always on Top + 总在最前 + + + + Always on Visible Workspace + 总在可见工作区 + + + + Move to Left Work Space + 移至左边的工作区 + + + + Move to Right Work Space + 移至右边的工作区 + + + + Close + 关闭 + + + \ No newline at end of file diff --git a/translations/treeland.zh_HK.ts b/translations/treeland.zh_HK.ts new file mode 100644 index 0000000000..15d305feb6 --- /dev/null +++ b/translations/treeland.zh_HK.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + 最小化 + + + + Unmaximize + 還原 + + + + Maximize + 最大化 + + + + Move + 移動 + + + + Resize + 更改大小 + + + + Always on Top + 總在最前 + + + + Always on Visible Workspace + 總在可見工作區 + + + + Move to Left Work Space + 移至左邊的工作區 + + + + Move to Right Work Space + 移至右邊的工作區 + + + + Close + 關閉 + + + \ No newline at end of file diff --git a/translations/treeland.zh_TW.ts b/translations/treeland.zh_TW.ts new file mode 100644 index 0000000000..7d55b9718b --- /dev/null +++ b/translations/treeland.zh_TW.ts @@ -0,0 +1,63 @@ + + + PrelaunchSplash + + + Loading application... + + + + + WindowMenu + + + Minimize + 最小化 + + + + Unmaximize + 還原 + + + + Maximize + 最大化 + + + + Move + 移動 + + + + Resize + 更改大小 + + + + Always on Top + 總在最前 + + + + Always on Visible Workspace + 總在可見工作區 + + + + Move to Left Work Space + 移至左邊的工作區 + + + + Move to Right Work Space + 移至右邊的工作區 + + + + Close + 關閉 + + + \ No newline at end of file diff --git a/wallpaper-factory/CMakeLists.txt b/wallpaper-factory/CMakeLists.txt new file mode 100644 index 0000000000..2cac36c171 --- /dev/null +++ b/wallpaper-factory/CMakeLists.txt @@ -0,0 +1,56 @@ +set(BIN_NAME treeland-wallpaper-factory) + +find_package(PkgConfig REQUIRED) +find_package(Qt6 REQUIRED COMPONENTS WaylandClient Quick) +find_package(Dtk6 REQUIRED COMPONENTS Core) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS WaylandClientPrivate QuickPrivate) +endif() +find_package(TreelandProtocols REQUIRED) +pkg_check_modules(MPV REQUIRED IMPORTED_TARGET mpv) + +qt_add_executable(${BIN_NAME} + main.cpp +) + +qt6_generate_wayland_protocol_client_sources(${BIN_NAME} + FILES + ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-wallpaper-shell-unstable-v1.xml +) + +qt_add_qml_module(${BIN_NAME} + URI com.treeland.wallfactory + VERSION 1.0 + SOURCES + loggings.h + loggings.cpp + mpvvideoitem.h + mpvvideoitem.cpp + mpvvideocontroller.h + mpvvideocontroller.cpp + qwaylandwallpapershellintegration_p.h + qwaylandwallpapershellintegration.cpp + qwaylandwallpapershellintegrationplugin.cpp + qwaylandwallpapersurface_p.h + qwaylandwallpapersurface.cpp + wallpaperwindow.h + wallpaperwindow.cpp + treelandwallpapernotifierclient.h + treelandwallpapernotifierclient.cpp + QML_FILES + Image.qml + Video.qml + +) + +target_link_libraries(${BIN_NAME} + PRIVATE + Qt6::Quick + Qt6::QuickPrivate + Qt6::WaylandClient + Qt6::WaylandClientPrivate + Dtk6::Core + PkgConfig::MPV +) + +install(TARGETS ${BIN_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") diff --git a/wallpaper-factory/Image.qml b/wallpaper-factory/Image.qml new file mode 100644 index 0000000000..41dcef68b6 --- /dev/null +++ b/wallpaper-factory/Image.qml @@ -0,0 +1,9 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Controls + +AnimatedImage { + asynchronous: true +} diff --git a/wallpaper-factory/Video.qml b/wallpaper-factory/Video.qml new file mode 100644 index 0000000000..b370230aa6 --- /dev/null +++ b/wallpaper-factory/Video.qml @@ -0,0 +1,10 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +import QtQuick +import QtQuick.Controls + +import com.treeland.wallfactory 1.0 + +MpvVideoItem { +} diff --git a/wallpaper-factory/loggings.cpp b/wallpaper-factory/loggings.cpp new file mode 100644 index 0000000000..c655566540 --- /dev/null +++ b/wallpaper-factory/loggings.cpp @@ -0,0 +1,7 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "loggings.h" + +Q_LOGGING_CATEGORY(WALLPAPER, "treeland.wallfactory", QtWarningMsg) + diff --git a/wallpaper-factory/loggings.h b/wallpaper-factory/loggings.h new file mode 100644 index 0000000000..55d21d4ace --- /dev/null +++ b/wallpaper-factory/loggings.h @@ -0,0 +1,9 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +Q_DECLARE_LOGGING_CATEGORY(WALLPAPER) diff --git a/wallpaper-factory/main.cpp b/wallpaper-factory/main.cpp new file mode 100644 index 0000000000..66e761dad4 --- /dev/null +++ b/wallpaper-factory/main.cpp @@ -0,0 +1,30 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "treelandwallpapernotifierclient.h" + +#include + +#include +#include +#include + +DCORE_USE_NAMESPACE; + +int main(int argc, char *argv[]) +{ + // The entire rendering framework, including mpv, is based on OpenGL. + // QQuickWindow::setGraphicsApi(QSGRendererInterface::OpenGL); + QGuiApplication app(argc, argv); + + app.setOrganizationName("deepin"); + app.setApplicationName("treeland-wallpaper-factory"); + + DLogManager::registerJournalAppender(); + + std::unique_ptr produce; + produce.reset(new TreelandWallpaperNotifierClientV1); + produce->instantiate(); + + return app.exec(); +} diff --git a/wallpaper-factory/mpvvideocontroller.cpp b/wallpaper-factory/mpvvideocontroller.cpp new file mode 100644 index 0000000000..bf19f1b042 --- /dev/null +++ b/wallpaper-factory/mpvvideocontroller.cpp @@ -0,0 +1,407 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "mpvvideocontroller.h" +#include "loggings.h" + +MpvVideoController::MpvVideoController(QObject *parent) + : QObject(parent) +{ +} + +MpvVideoController::~MpvVideoController() +{ + if (m_mpv) { + mpv_terminate_destroy(m_mpv); + } +} + +QStringView MpvVideoController::getError(int error) +{ + switch (error) { + case MPV_ERROR_SUCCESS: + return u"MPV_ERROR_SUCCESS"; + case MPV_ERROR_EVENT_QUEUE_FULL: + return u"MPV_ERROR_EVENT_QUEUE_FULL"; + case MPV_ERROR_NOMEM: + return u"MPV_ERROR_NOMEM"; + case MPV_ERROR_UNINITIALIZED: + return u"MPV_ERROR_UNINITIALIZED"; + case MPV_ERROR_INVALID_PARAMETER: + return u"MPV_ERROR_INVALID_PARAMETER"; + case MPV_ERROR_OPTION_NOT_FOUND: + return u"MPV_ERROR_OPTION_NOT_FOUND"; + case MPV_ERROR_OPTION_FORMAT: + return u"MPV_ERROR_OPTION_FORMAT"; + case MPV_ERROR_OPTION_ERROR: + return u"MPV_ERROR_OPTION_ERROR"; + case MPV_ERROR_PROPERTY_NOT_FOUND: + return u"MPV_ERROR_PROPERTY_NOT_FOUND"; + case MPV_ERROR_PROPERTY_FORMAT: + return u"MPV_ERROR_PROPERTY_FORMAT"; + case MPV_ERROR_PROPERTY_UNAVAILABLE: + return u"MPV_ERROR_PROPERTY_UNAVAILABLE"; + case MPV_ERROR_PROPERTY_ERROR: + return u"MPV_ERROR_PROPERTY_ERROR"; + case MPV_ERROR_COMMAND: + return u"MPV_ERROR_COMMAND"; + case MPV_ERROR_LOADING_FAILED: + return u"MPV_ERROR_LOADING_FAILED"; + case MPV_ERROR_AO_INIT_FAILED: + return u"MPV_ERROR_AO_INIT_FAILED"; + case MPV_ERROR_VO_INIT_FAILED: + return u"MPV_ERROR_VO_INIT_FAILED"; + case MPV_ERROR_NOTHING_TO_PLAY: + return u"MPV_ERROR_NOTHING_TO_PLAY"; + case MPV_ERROR_UNKNOWN_FORMAT: + return u"MPV_ERROR_UNKNOWN_FORMAT"; + case MPV_ERROR_UNSUPPORTED: + return u"MPV_ERROR_UNSUPPORTED"; + case MPV_ERROR_NOT_IMPLEMENTED: + return u"MPV_ERROR_NOT_IMPLEMENTED"; + case MPV_ERROR_GENERIC: + return u"MPV_ERROR_GENERIC"; + } + return {}; +} + + +void MpvVideoController::mpvEvents(void *ctx) +{ + QMetaObject::invokeMethod(static_cast(ctx), + &MpvVideoController::eventHandler, + Qt::QueuedConnection); +} + +void MpvVideoController::eventHandler() +{ + while (m_mpv) { + mpv_event *event = mpv_wait_event(m_mpv, 0); + if (event->event_id == MPV_EVENT_NONE) { + break; + } + switch (event->event_id) { + case MPV_EVENT_START_FILE: { + Q_EMIT fileStarted(); + break; + } + + case MPV_EVENT_FILE_LOADED: { + Q_EMIT fileLoaded(); + break; + } + + case MPV_EVENT_END_FILE: { + auto prop = static_cast(event->data); + if (prop->reason == MPV_END_FILE_REASON_EOF) { + Q_EMIT endFile(QByteArray("eof")); + } else if (prop->reason == MPV_END_FILE_REASON_ERROR) { + Q_EMIT endFile(QByteArray("error")); + } + break; + } + + case MPV_EVENT_VIDEO_RECONFIG: { + Q_EMIT videoReconfig(); + break; + } + + case MPV_EVENT_GET_PROPERTY_REPLY: { + mpv_event_property *prop = static_cast(event->data); + auto data = nodeToVariant(reinterpret_cast(prop->data)); + Q_EMIT asyncReply(data, {*event}); + break; + } + + case MPV_EVENT_SET_PROPERTY_REPLY: { + Q_EMIT asyncReply(QVariant(), {*event}); + break; + } + + case MPV_EVENT_COMMAND_REPLY: { + mpv_event_property *prop = static_cast(event->data); + auto data = nodeToVariant(reinterpret_cast(prop)); + Q_EMIT asyncReply(data, {*event}); + break; + } + + case MPV_EVENT_PROPERTY_CHANGE: { + mpv_event_property *prop = static_cast(event->data); + QVariant data; + switch (prop->format) { + case MPV_FORMAT_DOUBLE: + data = *reinterpret_cast(prop->data); + break; + case MPV_FORMAT_STRING: + data = QString::fromStdString(*reinterpret_cast(prop->data)); + break; + case MPV_FORMAT_INT64: + data = qlonglong(*reinterpret_cast(prop->data)); + break; + case MPV_FORMAT_FLAG: + data = *reinterpret_cast(prop->data); + break; + case MPV_FORMAT_NODE: + data = nodeToVariant(reinterpret_cast(prop->data)); + break; + case MPV_FORMAT_NONE: + case MPV_FORMAT_OSD_STRING: + case MPV_FORMAT_NODE_ARRAY: + case MPV_FORMAT_NODE_MAP: + case MPV_FORMAT_BYTE_ARRAY: + break; + } + Q_EMIT propertyChanged(QByteArray(prop->name), data); + break; + } + case MPV_EVENT_NONE: + case MPV_EVENT_SHUTDOWN: + case MPV_EVENT_LOG_MESSAGE: + case MPV_EVENT_CLIENT_MESSAGE: + case MPV_EVENT_AUDIO_RECONFIG: + case MPV_EVENT_SEEK: + case MPV_EVENT_PLAYBACK_RESTART: + case MPV_EVENT_QUEUE_OVERFLOW: + case MPV_EVENT_HOOK: +#if MPV_ENABLE_DEPRECATED + case MPV_EVENT_IDLE: + case MPV_EVENT_TICK: +#endif + break; + } + } +} + +mpv_handle *MpvVideoController::mpv() const +{ + return m_mpv; +} + +void MpvVideoController::init() +{ + std::setlocale(LC_NUMERIC, "C"); + m_mpv = mpv_create(); + if (!m_mpv) { + qCFatal(WALLPAPER) << "could not create mpv context"; + } + + mpv_set_option_string(m_mpv, "hwdec", "auto"); + + if (mpv_initialize(m_mpv) < 0) { + qCFatal(WALLPAPER) << "could not initialize mpv context"; + } + + mpv_set_wakeup_callback(m_mpv, MpvVideoController::mpvEvents, this); + // use number of logical CPU cores + setProperty(QByteArrayView("ad-lavc-threads"), 0); + // render to fbo + setProperty(QByteArrayView("vo"), QStringLiteral("libmpv")); +} + +void MpvVideoController::observeProperty(const QByteArrayView &property, mpv_format format, uint64_t id) +{ + mpv_observe_property(mpv(), id, property.constData(), format); +} + +int MpvVideoController::unobserveProperty(uint64_t id) +{ + return mpv_unobserve_property(mpv(), id); +} + +int MpvVideoController::setProperty(const QByteArrayView &property, const QVariant &value) +{ + mpv_node node; + setNode(&node, value); + return mpv_set_property(m_mpv, property.constData(), MPV_FORMAT_NODE, &node); +} + +int MpvVideoController::setPropertyAsync(const QByteArrayView &property, const QVariant &value, int id) +{ + mpv_node node; + setNode(&node, value); + return mpv_set_property_async(m_mpv, id, property.constData(), MPV_FORMAT_NODE, &node); +} + +QVariant MpvVideoController::getProperty(const QByteArrayView &property) +{ + mpv_node node; + int err = mpv_get_property(m_mpv, property.constData(), MPV_FORMAT_NODE, &node); + if (err < 0) { + return QVariant::fromValue(err); + } + + QVariant r = nodeToVariant(&node); + mpv_free_node_contents(&node); + return r; +} + +int MpvVideoController::getPropertyAsync(const QByteArrayView &property, int id) +{ + return mpv_get_property_async(m_mpv, id, property.constData(), MPV_FORMAT_NODE); +} + +QVariant MpvVideoController::command(const QVariant ¶ms) +{ + mpv_node node; + setNode(&node, params); + mpv_node result; + int err = mpv_command_node(m_mpv, &node, &result); + if (err < 0) { + qCCritical(WALLPAPER) << getError(err) << params; + return QVariant::fromValue(err); + } + + QVariant r = nodeToVariant(&result); + mpv_free_node_contents(&result); + return r; +} + +int MpvVideoController::commandAsync(const QVariant ¶ms, int id) +{ + mpv_node node; + setNode(&node, params); + return mpv_command_node_async(m_mpv, id, &node); +} + +mpv_node_list *MpvVideoController::createList(mpv_node *dst, bool is_map, int num) +{ + dst->format = is_map ? MPV_FORMAT_NODE_MAP : MPV_FORMAT_NODE_ARRAY; + mpv_node_list *list = new mpv_node_list(); + dst->u.list = list; + if (!list) { + freeNode(dst); + return nullptr; + } + list->values = new mpv_node[num](); + if (!list->values) { + freeNode(dst); + return nullptr; + } + if (is_map) { + list->keys = new char *[num](); + if (!list->keys) { + freeNode(dst); + return nullptr; + } + } + + return list; +} + +void MpvVideoController::setNode(mpv_node *dst, const QVariant &src) +{ + if (src.typeId() == QMetaType::QString) { + dst->format = MPV_FORMAT_STRING; + dst->u.string = qstrdup(src.toString().toUtf8().data()); + if (!dst->u.string) { + dst->format = MPV_FORMAT_NONE; + } + } else if (src.typeId() == QMetaType::Bool) { + dst->format = MPV_FORMAT_FLAG; + dst->u.flag = src.toBool() ? 1 : 0; + } else if (src.typeId() == QMetaType::Int || + src.typeId() == QMetaType::LongLong || + src.typeId() == QMetaType::UInt || + src.typeId() == QMetaType::ULongLong) { + dst->format = MPV_FORMAT_INT64; + dst->u.int64 = src.toLongLong(); + } else if (src.typeId() == QMetaType::Double) { + dst->format = MPV_FORMAT_DOUBLE; + dst->u.double_ = src.toDouble(); + } else if (src.canConvert()) { + QVariantList qlist = src.toList(); + mpv_node_list *list = createList(dst, false, qlist.size()); + if (!list) { + dst->format = MPV_FORMAT_NONE; + return; + } + list->num = qlist.size(); + for (int n = 0; n < qlist.size(); ++n) { + setNode(&list->values[n], qlist[n]); + } + } else if (src.canConvert()) { + QVariantMap qmap = src.toMap(); + mpv_node_list *list = createList(dst, true, qmap.size()); + if (!list) { + dst->format = MPV_FORMAT_NONE; + return; + } + list->num = qmap.size(); + int n = 0; + for (auto it = qmap.constKeyValueBegin(); it != qmap.constKeyValueEnd(); ++it) { + list->keys[n] = qstrdup(it.operator*().first.toUtf8().data()); + if (!list->keys[n]) { + freeNode(dst); + dst->format = MPV_FORMAT_NONE; + return; + } + setNode(&list->values[n], it.operator*().second); + ++n; + } + } else { + dst->format = MPV_FORMAT_NONE; + } + + return; +} + +void MpvVideoController::freeNode(mpv_node *dst) +{ + switch (dst->format) { + case MPV_FORMAT_STRING: + delete[] dst->u.string; + break; + case MPV_FORMAT_NODE_ARRAY: + case MPV_FORMAT_NODE_MAP: { + mpv_node_list *list = dst->u.list; + if (list) { + for (int n = 0; n < list->num; ++n) { + if (list->keys) { + delete[] list->keys[n]; + } + if (list->values) { + freeNode(&list->values[n]); + } + } + delete[] list->keys; + delete[] list->values; + } + delete list; + break; + } + default:; + } + dst->format = MPV_FORMAT_NONE; +} + +QVariant MpvVideoController::nodeToVariant(const mpv_node *node) +{ + switch (node->format) { + case MPV_FORMAT_STRING: + return QVariant(QString::fromUtf8(node->u.string)); + case MPV_FORMAT_FLAG: + return QVariant(static_cast(node->u.flag)); + case MPV_FORMAT_INT64: + return QVariant(static_cast(node->u.int64)); + case MPV_FORMAT_DOUBLE: + return QVariant(node->u.double_); + case MPV_FORMAT_NODE_ARRAY: { + mpv_node_list *list = node->u.list; + QVariantList qlist; + for (int n = 0; n < list->num; ++n) { + qlist.append(nodeToVariant(&list->values[n])); + } + return QVariant(qlist); + } + case MPV_FORMAT_NODE_MAP: { + mpv_node_list *list = node->u.list; + QVariantMap qmap; + for (int n = 0; n < list->num; ++n) { + qmap.insert(QString::fromUtf8(list->keys[n]), nodeToVariant(&list->values[n])); + } + return QVariant(qmap); + } + default: + return QVariant(); + } +} diff --git a/wallpaper-factory/mpvvideocontroller.h b/wallpaper-factory/mpvvideocontroller.h new file mode 100644 index 0000000000..e0a0b0b0df --- /dev/null +++ b/wallpaper-factory/mpvvideocontroller.h @@ -0,0 +1,50 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include +#include + +class MpvVideoController : public QObject +{ + Q_OBJECT +public: + explicit MpvVideoController(QObject *parent = nullptr); + ~MpvVideoController() override; + + QStringView getError(int error); + static void mpvEvents(void *ctx); + void eventHandler(); + mpv_handle *mpv() const; + +public Q_SLOTS: + void init(); + void observeProperty(const QByteArrayView &property, mpv_format format, uint64_t id = 0); + int unobserveProperty(uint64_t id); + int setProperty(const QByteArrayView &property, const QVariant &value); + int setPropertyAsync(const QByteArrayView &property, const QVariant &value, int id = 0); + QVariant getProperty(const QByteArrayView &property); + int getPropertyAsync(const QByteArrayView &property, int id = 0); + QVariant command(const QVariant ¶ms); + int commandAsync(const QVariant ¶ms, int id = 0); + +Q_SIGNALS: + void propertyChanged(const QByteArray &property, const QVariant &value); + void asyncReply(const QVariant &data, mpv_event event); + void fileStarted(); + void fileLoaded(); + void endFile(const QByteArray &reason); + void videoReconfig(); + +private: + mpv_node_list *createList(mpv_node *dst, bool is_map, int num); + void setNode(mpv_node *dst, const QVariant &src); + void freeNode(mpv_node *dst); + QVariant nodeToVariant(const mpv_node *node); + +private: + mpv_handle *m_mpv = nullptr; +}; diff --git a/wallpaper-factory/mpvvideoitem.cpp b/wallpaper-factory/mpvvideoitem.cpp new file mode 100644 index 0000000000..5341944f36 --- /dev/null +++ b/wallpaper-factory/mpvvideoitem.cpp @@ -0,0 +1,620 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "mpvvideoitem.h" +#include "loggings.h" + +#include +#include +#include +#include + +static void *getGLProcAddress(void *ctx, const char *name) +{ + Q_UNUSED(ctx) + + QOpenGLContext *glctx = QOpenGLContext::currentContext(); + if (!glctx) { + return nullptr; + } + + return reinterpret_cast(glctx->getProcAddress(QByteArray(name))); +} + +static void handleMpvRedraw(void *ctx) +{ + QMetaObject::invokeMethod(static_cast(ctx), + &MpvVideoItem::update, + Qt::QueuedConnection); +} + +MpvRenderer::MpvRenderer(MpvVideoItem *item) + : m_item(item) +{ + m_item->window()->setPersistentSceneGraph(true); +} + +QOpenGLFramebufferObject *MpvRenderer::createFramebufferObject(const QSize &size) +{ + if (!m_item->m_mpvGL) { +#if MPV_CLIENT_API_VERSION < MPV_MAKE_VERSION(2, 0) + mpv_opengl_init_params gl_init_params{getGLProcAddress, nullptr, nullptr}; +#else + mpv_opengl_init_params gl_init_params{getGLProcAddress, nullptr}; +#endif + mpv_render_param display{MPV_RENDER_PARAM_INVALID, nullptr}; + if (qGuiApp->nativeInterface()) { + display.type = MPV_RENDER_PARAM_X11_DISPLAY; + display.data = qGuiApp->nativeInterface()->display(); + } + + if (qGuiApp->nativeInterface()) { + display.type = MPV_RENDER_PARAM_WL_DISPLAY; + display.data = qGuiApp->nativeInterface()->display(); + } + mpv_render_param params[]{{MPV_RENDER_PARAM_API_TYPE, const_cast(MPV_RENDER_API_TYPE_OPENGL)}, + {MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, &gl_init_params}, + display, + {MPV_RENDER_PARAM_INVALID, nullptr}}; + + int result = mpv_render_context_create(&m_item->m_mpvGL, m_item->m_mpv, params); + if (result < 0) { + qCCritical(WALLPAPER) << "failed to initialize mpv GL context"; + } else { + mpv_render_context_set_update_callback(m_item->m_mpvGL, handleMpvRedraw, m_item); + Q_EMIT m_item->ready(); + m_item->setReady(true); + } + } + + return QQuickFramebufferObject::Renderer::createFramebufferObject(size); +} + +void MpvRenderer::render() +{ + QOpenGLFramebufferObject *fbo = framebufferObject(); + mpv_opengl_fbo mpfbo; + mpfbo.fbo = static_cast(fbo->handle()); + mpfbo.w = fbo->width(); + mpfbo.h = fbo->height(); + mpfbo.internal_format = 0; + + int flip_y{0}; + + mpv_render_param params[] = {{MPV_RENDER_PARAM_OPENGL_FBO, &mpfbo}, + {MPV_RENDER_PARAM_FLIP_Y, &flip_y}, + {MPV_RENDER_PARAM_INVALID, nullptr}}; + mpv_render_context_render(m_item->m_mpvGL, params); +} + +MpvVideoItem::MpvVideoItem(QQuickItem *parent) + : QQuickFramebufferObject(parent) +{ + if (QQuickWindow::graphicsApi() != QSGRendererInterface::OpenGL) { + qCCritical(WALLPAPER) << "error, The graphics api must be set to opengl or mpv won't be able to render the video."; + } + + m_workerThread = new QThread; + m_mpvController = new MpvVideoController; + m_workerThread->start(); + m_mpvController->moveToThread(m_workerThread); + QMetaObject::invokeMethod(m_mpvController, + &MpvVideoController::init, + Qt::BlockingQueuedConnection); + + m_mpv = m_mpvController->mpv(); + + connect(m_workerThread, + &QThread::finished, + m_mpvController, + &MpvVideoController::deleteLater); + connect(this, + &MpvVideoItem::observeProperty, + m_mpvController, + &MpvVideoController::observeProperty, + Qt::QueuedConnection); + connect(this, + &MpvVideoItem::setProperty, + m_mpvController, + &MpvVideoController::setProperty, + Qt::QueuedConnection); + connect(this, + &MpvVideoItem::command, + m_mpvController, + &MpvVideoController::command, + Qt::QueuedConnection); + + observeProperty(MpvVideoItem::toByteArray(MediaTitle), MPV_FORMAT_STRING); + observeProperty(MpvVideoItem::toByteArray(Position), MPV_FORMAT_DOUBLE); + observeProperty(MpvVideoItem::toByteArray(Duration), MPV_FORMAT_DOUBLE); + observeProperty(MpvVideoItem::toByteArray(Pause), MPV_FORMAT_FLAG); + observeProperty(MpvVideoItem::toByteArray(Volume), MPV_FORMAT_INT64); + observeProperty(MpvVideoItem::toByteArray(LoopFile), MPV_FORMAT_STRING); + observeProperty(MpvVideoItem::toByteArray(Speed), MPV_FORMAT_DOUBLE); + observeProperty(MpvVideoItem::toByteArray(VideoUnscaled), MPV_FORMAT_STRING); + observeProperty(MpvVideoItem::toByteArray(PanScan), MPV_FORMAT_DOUBLE); + + initConnections(); + + setPropertyAsync(MpvVideoItem::toByteArray(Volume), 0, static_cast(AsyncIds::SetVolume)); + setMute(true); + getPropertyAsync(MpvVideoItem::toByteArray(Volume), static_cast(AsyncIds::GetVolume)); + setLoopFile(true); + setScaleMode(Scaled); + setPanScan(1.0); +} + +MpvVideoItem::~MpvVideoItem() +{ + if (m_mpvGL) { + mpv_render_context_free(m_mpvGL); + } + + if (m_mpv) + mpv_set_wakeup_callback(m_mpv, nullptr, nullptr); + + if (m_workerThread) { + m_workerThread->quit(); + m_workerThread->wait(); + delete m_workerThread; + } +} + +QByteArrayView MpvVideoItem::toByteArray(Property p) +{ + switch (p) { + case MediaTitle: return "media-title"; + case Position: return "time-pos"; + case Duration: return "duration"; + case Pause: return "pause"; + case Volume: return "volume"; + case Mute: return "mute"; + case LoopFile: return "loop-file"; + case Speed: return "speed"; + case VideoUnscaled: return "video-unscaled"; + case PanScan: return "panscan"; + } + return ""; +} + +QString MpvVideoItem::mediaTitle() +{ + return getProperty(MpvVideoItem::toByteArray(MediaTitle)).toString(); +} + +double MpvVideoItem::position() +{ + return getProperty(MpvVideoItem::toByteArray(Position)).toDouble(); +} + +void MpvVideoItem::setPosition(double value) +{ + if (qFuzzyCompare(value, position())) { + return; + } + + Q_EMIT setPropertyAsync(MpvVideoItem::toByteArray(Position), value); +} + +double MpvVideoItem::duration() +{ + return getProperty(MpvVideoItem::toByteArray(Duration)).toDouble(); +} + +QString MpvVideoItem::formattedPosition() +{ + return formatTime(position()); +} + +QString MpvVideoItem::formattedDuration() +{ + return formatTime(duration()); +} + +bool MpvVideoItem::pause() +{ + return m_pause; +} + +void MpvVideoItem::setPause(bool value) +{ + if (m_pause == value) { + return; + } + m_pause = value; + + if (m_speedTimer) { + m_speedTimer->stop(); + delete m_speedTimer; + m_speedTimer = nullptr; + } + + setSpeed(1.0); + Q_EMIT setPropertyAsync(MpvVideoItem::toByteArray(Pause), value); +} + +int MpvVideoItem::volume() +{ + return getProperty(MpvVideoItem::toByteArray(Volume)).toInt(); +} + +void MpvVideoItem::setVolume(int value) +{ + if (value == volume()) { + return; + } + Q_EMIT setPropertyAsync(MpvVideoItem::toByteArray(Volume), value); +} + +QString MpvVideoItem::source() +{ + return m_source; +} + +void MpvVideoItem::setSource(const QString &source) +{ + if (m_source == source) { + return; + } + + m_source = source; + if (m_readyed) { + loadFile(source); + } else { + connect(this, &MpvVideoItem::ready, this, [this]{ loadFile(m_source); }); + } + Q_EMIT sourceChanged(); +} + +bool MpvVideoItem::loopFile() +{ + if (getProperty(MpvVideoItem::toByteArray(LoopFile)).toString() == "inf") + return true; + + return false; +} + +void MpvVideoItem::setLoopFile(bool value) +{ + if (loopFile() == value) { + return; + } + + if (value) { + Q_EMIT setPropertyAsync(MpvVideoItem::toByteArray(LoopFile), "inf"); + } else { + Q_EMIT setPropertyAsync(MpvVideoItem::toByteArray(LoopFile), "no"); + } +} + + +double MpvVideoItem::speed() +{ + return getProperty(MpvVideoItem::toByteArray(Speed)).toDouble(); +} + +void MpvVideoItem::setSpeed(double value) +{ + if (value == speed()) { + return; + } + + Q_EMIT setPropertyAsync(MpvVideoItem::toByteArray(Speed), value); +} + +void MpvVideoItem::setReady(bool ready) +{ + if (m_readyed == ready) { + return; + } + + m_readyed = ready; +} + +bool MpvVideoItem::mute() +{ + return getProperty(MpvVideoItem::toByteArray(Mute)).toBool(); +} + +void MpvVideoItem::setMute(bool value) +{ + if (value == mute()) { + return; + } + + Q_EMIT setPropertyAsync(MpvVideoItem::toByteArray(Mute), value); +} + +inline static const char *toMpvVideoUnscaled(MpvVideoItem::VideoScaleMode mode) +{ + return mode == MpvVideoItem::Scaled ? "no" : "yes"; +} + +inline static MpvVideoItem::VideoScaleMode fromMpvVideoUnscaled(const QString &value) +{ + if (value == QLatin1String("yes") || value == QLatin1String("true") + || value == QLatin1String("1")) { + return MpvVideoItem::Unscaled; + } + + return MpvVideoItem::Scaled; +} + +MpvVideoItem::VideoScaleMode MpvVideoItem::scaleMode() +{ + const QString value = + getProperty(MpvVideoItem::toByteArray(VideoUnscaled)).toString(); + + return fromMpvVideoUnscaled(value); +} + +void MpvVideoItem::setScaleMode(VideoScaleMode mode) +{ + if (mode == scaleMode()) + return; + + Q_EMIT setPropertyAsync( + MpvVideoItem::toByteArray(VideoUnscaled), + QLatin1String(toMpvVideoUnscaled(mode)) + ); +} + +double MpvVideoItem::panScan() +{ + return getProperty(MpvVideoItem::toByteArray(PanScan)).toDouble(); +} + +void MpvVideoItem::setPanScan(double value) +{ + if (value == panScan()) { + return; + } + + Q_EMIT setPropertyAsync(MpvVideoItem::toByteArray(PanScan), value); +} + +void MpvVideoItem::slowDown(uint32_t duration) +{ + if (m_speedTimer) { + m_speedTimer->stop(); + delete m_speedTimer; + m_speedTimer = nullptr; + } + + m_speedTimer = new QTimer(this); + m_speedTimer->setInterval(refreshInterval()); + m_slowDownDuration = duration; + connect(m_speedTimer, &QTimer::timeout, this, &MpvVideoItem::updatePlaybackSpeed); + + m_elapsed.restart(); + m_speedTimer->start(); +} + +int MpvVideoItem::refreshInterval() const +{ + return m_refreshInterval; +} + +void MpvVideoItem::setRefreshInterval(int value) +{ + if (m_refreshInterval == value) { + return; + } + + m_refreshInterval = value; + Q_EMIT refreshIntervalChanged(); +} + +void MpvVideoItem::loadFile(const QString &file) +{ + auto url = QUrl::fromUserInput(file); + if (m_file != url) { + m_file = url; + Q_EMIT currentUrlChanged(); + } + + Q_EMIT command(QStringList() << QStringLiteral("loadfile") + << m_file.toString(QUrl::PreferLocalFile)); +} + +int MpvVideoItem::setPropertyBlocking(const QByteArrayView &property, const QVariant &value) +{ + int error; + QMetaObject::invokeMethod(m_mpvController, + "setProperty", + Qt::BlockingQueuedConnection, + Q_RETURN_ARG(int, error), + Q_ARG(QByteArrayView, property), + Q_ARG(QVariant, value)); + + return error; +} + +void MpvVideoItem::setPropertyAsync(const QByteArrayView &property, + const QVariant &value, int id) +{ + + QMetaObject::invokeMethod(m_mpvController, + "setPropertyAsync", + Qt::QueuedConnection, + Q_ARG(QByteArrayView, property), + Q_ARG(QVariant, value), + Q_ARG(int, id)); +} + +QVariant MpvVideoItem::getProperty(const QByteArrayView &property) +{ + QVariant value; + QMetaObject::invokeMethod(m_mpvController, + "getProperty", + Qt::BlockingQueuedConnection, + Q_RETURN_ARG(QVariant, value), + Q_ARG(QByteArrayView, property)); + + return value; +} + +void MpvVideoItem::getPropertyAsync(const QByteArrayView &property, int id) +{ + QMetaObject::invokeMethod(m_mpvController, + "getPropertyAsync", + Qt::QueuedConnection, + Q_ARG(QByteArrayView, property), + Q_ARG(int, id)); +} + +QVariant MpvVideoItem::commandBlocking(const QVariant ¶ms) +{ + QVariant value; + QMetaObject::invokeMethod(m_mpvController, + "command", + Qt::BlockingQueuedConnection, + Q_RETURN_ARG(QVariant, value), + Q_ARG(QVariant, params)); + + return value; +} + +void MpvVideoItem::commandAsync(const QStringList ¶ms, int id) +{ + QMetaObject::invokeMethod(m_mpvController, + "commandAsync", + Qt::QueuedConnection, + Q_ARG(QVariant, params), + Q_ARG(int, id)); +} + +QVariant MpvVideoItem::expandText(const QString &text) +{ + QVariant value; + QMetaObject::invokeMethod(m_mpvController, + "command", + Qt::BlockingQueuedConnection, + Q_RETURN_ARG(QVariant, value), + Q_ARG(QVariant, QVariant::fromValue(QStringList{QStringLiteral("expand-text"), text}))); + + return value; +} + +int MpvVideoItem::unobserveProperty(uint64_t id) +{ + return m_mpvController->unobserveProperty(id); +} + +void MpvVideoItem::onPropertyChanged(const QByteArrayView &property, + [[maybe_unused]] const QVariant &value) +{ + if (property == toByteArray(MediaTitle)) { + Q_EMIT mediaTitleChanged(); + } else if (property == toByteArray(Position)) { + Q_EMIT positionChanged(); + } else if (property == toByteArray(Duration)) { + Q_EMIT durationChanged(); + } else if (property == toByteArray(Pause)) { + Q_EMIT pauseChanged(); + } else if (property == toByteArray(Volume)) { + Q_EMIT volumeChanged(); + } else if (property == toByteArray(LoopFile)) { + Q_EMIT loopFileChanged(); + } else if (property == toByteArray(Speed)) { + Q_EMIT speedChanged(); + } else if (property == toByteArray(Mute)) { + Q_EMIT muteChanged(); + } +} + +void MpvVideoItem::onAsyncReply(const QVariant &data, mpv_event event) +{ + switch (static_cast(event.reply_userdata)) { + case AsyncIds::None: { + break; + } + case AsyncIds::SetVolume: { + qCDebug(WALLPAPER) << "onSetPropertyReply" + << event.reply_userdata; + break; + } + case AsyncIds::GetVolume: { + qCDebug(WALLPAPER) << "onGetPropertyReply" + << event.reply_userdata + << data; + break; + } + case AsyncIds::ExpandText: { + qCDebug(WALLPAPER) << "onGetPropertyReply" + << event.reply_userdata + << data; + break; + } + } +} + +static inline double easeOutExpo(double t) +{ + static const QEasingCurve curve(QEasingCurve::OutExpo); + return curve.valueForProgress(t); +} + +void MpvVideoItem::updatePlaybackSpeed() +{ + constexpr double minSpeed = 0.0; + constexpr double maxSpeed = 1.0; + constexpr double pauseThreshold = 0.5; + + if (m_elapsed.hasExpired(m_slowDownDuration)) { + m_speedTimer->stop(); + setPause(true); + return; + } + + double t = double(m_elapsed.elapsed()) / m_slowDownDuration; + t = std::clamp(t, 0.0, 1.0); + + double ease = easeOutExpo(t); + double speed = maxSpeed - ease * (maxSpeed - minSpeed); + + if (speed < pauseThreshold) { + m_speedTimer->stop(); + setPause(true); + return; + } + + setSpeed(speed); +} + +void MpvVideoItem::initConnections() +{ + connect(m_mpvController, &MpvVideoController::propertyChanged, + this, &MpvVideoItem::onPropertyChanged, Qt::QueuedConnection); + connect(m_mpvController, &MpvVideoController::fileStarted, + this, &MpvVideoItem::fileStarted, Qt::QueuedConnection); + connect(m_mpvController, &MpvVideoController::fileLoaded, + this, &MpvVideoItem::fileLoaded, Qt::QueuedConnection); + connect(m_mpvController, &MpvVideoController::endFile, + this, &MpvVideoItem::endFile, Qt::QueuedConnection); + connect(m_mpvController, &MpvVideoController::videoReconfig, + this, &MpvVideoItem::videoReconfig, Qt::QueuedConnection); + connect(m_mpvController, &MpvVideoController::asyncReply, + this, &MpvVideoItem::onAsyncReply, Qt::QueuedConnection); +} + +QString MpvVideoItem::formatTime(const double time) +{ + int totalNumberOfSeconds = static_cast(time); + int seconds = totalNumberOfSeconds % 60; + int minutes = (totalNumberOfSeconds / 60) % 60; + int hours = (totalNumberOfSeconds / 60 / 60); + + QString timeString = + QStringLiteral("%1:%2:%3") + .arg(hours, 2, 10, QLatin1Char('0')) + .arg(minutes, 2, 10, QLatin1Char('0')) + .arg(seconds, 2, 10, QLatin1Char('0')); + + return timeString; +} + +QQuickFramebufferObject::Renderer *MpvVideoItem::createRenderer() const +{ + return new MpvRenderer(const_cast(this)); +} diff --git a/wallpaper-factory/mpvvideoitem.h b/wallpaper-factory/mpvvideoitem.h new file mode 100644 index 0000000000..e7518face2 --- /dev/null +++ b/wallpaper-factory/mpvvideoitem.h @@ -0,0 +1,188 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "mpvvideocontroller.h" + +#include +#include + +#include +#include +#include +#include +#include + +class MpvVideoItem; + +class MpvRenderer : public QQuickFramebufferObject::Renderer +{ +public: + explicit MpvRenderer(MpvVideoItem *item); + ~MpvRenderer() = default; + + MpvVideoItem *m_item = nullptr; + QOpenGLFramebufferObject *createFramebufferObject(const QSize &size) override; + void render() override; +}; + +class MpvVideoItem : public QQuickFramebufferObject +{ + Q_OBJECT + QML_ELEMENT + + Q_PROPERTY(QString source READ source WRITE setSource NOTIFY sourceChanged) + Q_PROPERTY(QString mediaTitle READ mediaTitle NOTIFY mediaTitleChanged) + Q_PROPERTY(double position READ position WRITE setPosition NOTIFY positionChanged) + Q_PROPERTY(double duration READ duration NOTIFY durationChanged) + Q_PROPERTY(QString formattedPosition READ formattedPosition NOTIFY positionChanged) + Q_PROPERTY(QString formattedDuration READ formattedDuration NOTIFY durationChanged) + Q_PROPERTY(bool pause READ pause WRITE setPause NOTIFY pauseChanged) + Q_PROPERTY(int volume READ volume WRITE setVolume NOTIFY volumeChanged) + Q_PROPERTY(bool loopFile READ loopFile WRITE setLoopFile NOTIFY loopFileChanged) + Q_PROPERTY(double speed READ speed WRITE setSpeed NOTIFY speedChanged) + Q_PROPERTY(bool mute READ mute WRITE setMute NOTIFY muteChanged FINAL) + Q_PROPERTY(VideoScaleMode scaleMode READ scaleMode WRITE setScaleMode NOTIFY scaleModeChanged FINAL) + Q_PROPERTY(double panScan READ panScan WRITE setPanScan NOTIFY panScanChanged FINAL) + Q_PROPERTY(int refreshInterval READ refreshInterval WRITE setRefreshInterval NOTIFY refreshIntervalChanged FINAL) +public: + explicit MpvVideoItem(QQuickItem *parent = nullptr); + ~MpvVideoItem() override; + + enum class AsyncIds { + None, + SetVolume, + GetVolume, + ExpandText, + }; + Q_ENUM(AsyncIds) + + enum Property { + MediaTitle, + Position, + Duration, + Pause, + Volume, + Mute, + LoopFile, + Speed, + VideoUnscaled, + PanScan + }; + Q_ENUM(Property) + + enum VideoScaleMode { + Scaled, + Unscaled + }; + Q_ENUM(VideoScaleMode) + + static QByteArrayView toByteArray(Property p); + + Renderer *createRenderer() const override; + + QString mediaTitle(); + + double position(); + void setPosition(double value); + + double duration(); + + QString formattedPosition(); + QString formattedDuration(); + + bool pause(); + void setPause(bool value); + + int volume(); + void setVolume(int value); + + QString source(); + void setSource(const QString &source); + + bool loopFile(); + void setLoopFile(bool value); + + double speed(); + void setSpeed(double value); + + void setReady(bool ready); + + bool mute(); + void setMute(bool value); + + VideoScaleMode scaleMode(); + void setScaleMode(VideoScaleMode mode); + + double panScan(); + void setPanScan(double value); + + void slowDown(uint32_t duration); + + int refreshInterval() const; + void setRefreshInterval(int value); + + Q_INVOKABLE void loadFile(const QString &file); + + Q_INVOKABLE int setPropertyBlocking(const QByteArrayView &property, const QVariant &value); + Q_INVOKABLE void setPropertyAsync(const QByteArrayView &property, const QVariant &value, int id = 0); + Q_INVOKABLE QVariant getProperty(const QByteArrayView &property); + Q_INVOKABLE void getPropertyAsync(const QByteArrayView &property, int id = 0); + Q_INVOKABLE QVariant commandBlocking(const QVariant ¶ms); + Q_INVOKABLE void commandAsync(const QStringList ¶ms, int id = 0); + Q_INVOKABLE QVariant expandText(const QString &text); + Q_INVOKABLE int unobserveProperty(uint64_t id); + +Q_SIGNALS: + void mediaTitleChanged(); + void currentUrlChanged(); + void positionChanged(); + void durationChanged(); + void pauseChanged(); + void volumeChanged(); + void sourceChanged(); + void loopFileChanged(); + void speedChanged(); + void muteChanged(); + void scaleModeChanged(); + void panScanChanged(); + void refreshIntervalChanged(); + + void fileStarted(); + void fileLoaded(); + void endFile(const QByteArray &reason); + void videoReconfig(); + + void ready(); + void observeProperty(const QByteArrayView &property, mpv_format format, uint64_t id = 0); + void setProperty(const QByteArrayView &property, const QVariant &value); + void command(const QStringList ¶ms); + +private Q_SLOTS: + void onPropertyChanged(const QByteArrayView &property, const QVariant &value); + void onAsyncReply(const QVariant &data, mpv_event event); + void updatePlaybackSpeed(); + +private: + void initConnections(); + QString formatTime(const double time); + +private: + friend class MpvRenderer; + + QThread *m_workerThread = nullptr; + MpvVideoController *m_mpvController = nullptr; + mpv_handle *m_mpv = nullptr; + mpv_render_context *m_mpvGL = nullptr; + + QTimer *m_speedTimer = nullptr; + QElapsedTimer m_elapsed; + + QUrl m_file; + QString m_source; + bool m_readyed = false; + int m_refreshInterval = 16; + uint32_t m_slowDownDuration; + bool m_pause = false; +}; diff --git a/wallpaper-factory/qwaylandwallpapershellintegration.cpp b/wallpaper-factory/qwaylandwallpapershellintegration.cpp new file mode 100644 index 0000000000..0fec4ec5fa --- /dev/null +++ b/wallpaper-factory/qwaylandwallpapershellintegration.cpp @@ -0,0 +1,27 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "qwaylandwallpapersurface_p.h" +#include "qwaylandwallpapershellintegration_p.h" + +#include +#include + +#include + +#define TREELAND_WALLPAPER_PRODUCE_V1_VERSION 1 + +QWaylandWallpaperShellIntegration::QWaylandWallpaperShellIntegration() + : QWaylandShellIntegrationTemplate(TREELAND_WALLPAPER_PRODUCE_V1_VERSION) +{ +} + +QWaylandWallpaperShellIntegration::~QWaylandWallpaperShellIntegration() +{ + destroy(); +} + +QtWaylandClient::QWaylandShellSurface *QWaylandWallpaperShellIntegration::createShellSurface(QtWaylandClient::QWaylandWindow *window) +{ + return new QWaylandWallpaperSurface(this, window); +} diff --git a/wallpaper-factory/qwaylandwallpapershellintegration_p.h b/wallpaper-factory/qwaylandwallpapershellintegration_p.h new file mode 100644 index 0000000000..c361cfe4c5 --- /dev/null +++ b/wallpaper-factory/qwaylandwallpapershellintegration_p.h @@ -0,0 +1,20 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "qwayland-treeland-wallpaper-shell-unstable-v1.h" + +#include + +#include + +class QWaylandWallpaperShellIntegration : public QtWaylandClient::QWaylandShellIntegrationTemplate, + public QtWayland::treeland_wallpaper_shell_v1 +{ +public: + QWaylandWallpaperShellIntegration(); + ~QWaylandWallpaperShellIntegration() override; + + QtWaylandClient::QWaylandShellSurface *createShellSurface(QtWaylandClient::QWaylandWindow *window) override; +}; diff --git a/wallpaper-factory/qwaylandwallpapershellintegrationplugin.cpp b/wallpaper-factory/qwaylandwallpapershellintegrationplugin.cpp new file mode 100644 index 0000000000..a8393ba89e --- /dev/null +++ b/wallpaper-factory/qwaylandwallpapershellintegrationplugin.cpp @@ -0,0 +1,26 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "qwaylandwallpapershellintegration_p.h" +#include + +class QWaylandWallpaperIntegrationPlugin : public QtWaylandClient::QWaylandShellIntegrationPlugin +{ + Q_OBJECT + Q_PLUGIN_METADATA(IID QWaylandShellIntegrationFactoryInterface_iid FILE "wallpaper-shell.json") + +public: + QWaylandWallpaperIntegrationPlugin() + { + } + + QtWaylandClient::QWaylandShellIntegration *create([[maybe_unused]] const QString &key, + [[maybe_unused]] const QStringList ¶mList) override + { + return new QWaylandWallpaperShellIntegration(); + } +}; + +// Q_IMPORT_PLUGIN(QWaylandWallpaperIntegrationPlugin); + +#include "qwaylandwallpapershellintegrationplugin.moc" diff --git a/wallpaper-factory/qwaylandwallpapersurface.cpp b/wallpaper-factory/qwaylandwallpapersurface.cpp new file mode 100644 index 0000000000..c21a34c6c0 --- /dev/null +++ b/wallpaper-factory/qwaylandwallpapersurface.cpp @@ -0,0 +1,58 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "qwaylandwallpapersurface_p.h" +#include "qwaylandwallpapershellintegration_p.h" + +#include +#include + +QWaylandWallpaperSurface::QWaylandWallpaperSurface(QWaylandWallpaperShellIntegration *shell, + QtWaylandClient::QWaylandWindow *window) + : QtWaylandClient::QWaylandShellSurface(window) + , QtWayland::treeland_wallpaper_surface_v1() + , m_shell(shell) + , m_interface(WallpaperWindow::get(window->window())) + , m_window(window) +{ + init(shell->get_treeland_wallpaper_surface(window->waylandSurface()->object(), m_interface->source())); + if (m_interface->loaded()) { + onFileLoaded(); + } else { + connect(m_interface, + &WallpaperWindow::loadedChanged, + this, + &QWaylandWallpaperSurface::onFileLoaded, + Qt::SingleShotConnection); + } +} + +QWaylandWallpaperSurface::~QWaylandWallpaperSurface() +{ + destroy(); +} + +void QWaylandWallpaperSurface::treeland_wallpaper_surface_v1_position(wl_fixed_t position) +{ + Q_EMIT m_interface->positionChanged(wl_fixed_to_double(position)); +} + +void QWaylandWallpaperSurface::treeland_wallpaper_surface_v1_pause() +{ + Q_EMIT m_interface->playChanged(false); +} + +void QWaylandWallpaperSurface::treeland_wallpaper_surface_v1_play() +{ + Q_EMIT m_interface->playChanged(true); +} + +void QWaylandWallpaperSurface::treeland_wallpaper_surface_v1_slow_down(uint32_t duration) +{ + Q_EMIT m_interface->slowDownChanged(duration); +} + +void QWaylandWallpaperSurface::onFileLoaded() +{ + ready(); +} diff --git a/wallpaper-factory/qwaylandwallpapersurface_p.h b/wallpaper-factory/qwaylandwallpapersurface_p.h new file mode 100644 index 0000000000..9e6b1e550d --- /dev/null +++ b/wallpaper-factory/qwaylandwallpapersurface_p.h @@ -0,0 +1,41 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "wallpaperwindow.h" +#include "qwayland-treeland-wallpaper-shell-unstable-v1.h" + +#include + +class QWaylandWallpaperShellIntegration; + +class QWaylandWallpaperSurface : public QtWaylandClient::QWaylandShellSurface, + public QtWayland::treeland_wallpaper_surface_v1 +{ + Q_OBJECT +public: + QWaylandWallpaperSurface(QWaylandWallpaperShellIntegration *shell, + QtWaylandClient::QWaylandWindow *window); + ~QWaylandWallpaperSurface() override; + + bool isExposed() const override { return m_configured; } + +private: + void treeland_wallpaper_surface_v1_position(wl_fixed_t position) override; + void treeland_wallpaper_surface_v1_pause() override; + void treeland_wallpaper_surface_v1_play() override; + void treeland_wallpaper_surface_v1_slow_down(uint32_t duration) override; + +private Q_SLOTS: + void onFileLoaded(); + +private: + QWaylandWallpaperShellIntegration *m_shell; + WallpaperWindow *m_interface; + QtWaylandClient::QWaylandWindow *m_window; + QSize m_pendingSize; + QString m_activationToken; + + bool m_configured = true; +}; diff --git a/wallpaper-factory/treelandwallpapernotifierclient.cpp b/wallpaper-factory/treelandwallpapernotifierclient.cpp new file mode 100644 index 0000000000..e0da2b8f3d --- /dev/null +++ b/wallpaper-factory/treelandwallpapernotifierclient.cpp @@ -0,0 +1,247 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "loggings.h" +#include "treelandwallpapernotifierclient.h" +#include "mpvvideoitem.h" +#include "wallpaperwindow.h" + +#include + +#define TREELANDWALLPAPERPRODUCEV1VERSION 1 +#define WALLPAPERSOURCE "wallpaperSource" + +static QSize maxScreenSize() +{ + QSize maxSize; + int maxArea = 0; + + const auto screens = QGuiApplication::screens(); + for (QScreen *screen : screens) { + const QSize size = screen->geometry().size(); + const int area = size.width() * size.height(); + if (area > maxArea) { + maxArea = area; + maxSize = size; + } + } + return maxSize; +} + +static qreal minScreenRefreshIntervalMs() +{ + qreal maxRefreshRate = 0.0; + + const auto screens = QGuiApplication::screens(); + for (QScreen *screen : screens) { + maxRefreshRate = qMax(maxRefreshRate, screen->refreshRate()); + } + + if (maxRefreshRate <= 0.0) + return 16; // 60 hz + + return 1000.0 / maxRefreshRate; +} + +TreelandWallpaperNotifierClientV1::TreelandWallpaperNotifierClientV1() + : QWaylandClientExtensionTemplate(TREELANDWALLPAPERPRODUCEV1VERSION) +{ + connect(qApp, &QGuiApplication::screenAdded, + this, &TreelandWallpaperNotifierClientV1::onScreenAdded); + connect(qApp, &QGuiApplication::screenRemoved, + this, &TreelandWallpaperNotifierClientV1::onScreenRemoved); + const auto screens = QGuiApplication::screens(); + for (QScreen *screen : screens) { + connect(screen, &QScreen::geometryChanged, + this, &TreelandWallpaperNotifierClientV1::updateAllWallpaperViewSizes); + } +} + +TreelandWallpaperNotifierClientV1::~TreelandWallpaperNotifierClientV1() +{ + for (auto window : std::as_const(m_windows)) { + delete window; + } + m_windows.clear(); + + destroy(); +} + +void TreelandWallpaperNotifierClientV1::instantiate() +{ + initialize(); +} + +void TreelandWallpaperNotifierClientV1::treeland_wallpaper_notifier_v1_add(uint32_t source_type, const QString &file_source) +{ + for (auto window : std::as_const(m_windows)) { + if (window->property(WALLPAPERSOURCE).toString() == file_source) { + return; + } + } + + QQuickView *wallpaperWindow = new QQuickView; + WallpaperWindow *window = WallpaperWindow::get(wallpaperWindow); + window->setSource(file_source); + wallpaperWindow->setResizeMode(QQuickView::SizeRootObjectToView); + switch (source_type) { + + case QtWayland::treeland_wallpaper_notifier_v1:: + wallpaper_source_type::wallpaper_source_type_image: { + wallpaperWindow->loadFromModule("com.treeland.wallfactory", "Image"); + QObject *root = wallpaperWindow->rootObject(); + auto *image = qobject_cast(root); + if (!image) { + qCCritical(WALLPAPER) + << "Root object is not QQuickAnimatedImage"; + delete wallpaperWindow; + return; + } + connect(image, + &QQuickAnimatedImage::statusChanged, + window, [window](QQuickImageBase::Status status) { + if (status == QQuickImageBase::Ready) + window->setLoaded(true); + }); + image->setSource(QUrl::fromLocalFile(file_source)); + break; + } + + case QtWayland::treeland_wallpaper_notifier_v1:: + wallpaper_source_type::wallpaper_source_type_video: { + wallpaperWindow->loadFromModule("com.treeland.wallfactory", "Video"); + QObject *root = wallpaperWindow->rootObject(); + auto *video = qobject_cast(root); + if (!video) { + qCCritical(WALLPAPER) + << "Root object is not MpvVideoItem"; + delete wallpaperWindow; + return; + } + + connect(video, + &MpvVideoItem::fileLoaded, + window,[window]() { + window->setLoaded(true); + }, + Qt::SingleShotConnection); + video->setSource(file_source); + break; + } + + default: + qCCritical(WALLPAPER) << "Unsupported wallpaper source type:" + << source_type; + delete wallpaperWindow; + return; + } + + wallpaperWindow->setProperty(WALLPAPERSOURCE, file_source); + wallpaperWindow->resize(maxScreenSize()); + wallpaperWindow->show(); + m_windows.append(wallpaperWindow); + connect(window, + &WallpaperWindow::playChanged, + this, + &TreelandWallpaperNotifierClientV1::onPlayChanged); + connect(window, + &WallpaperWindow::slowDownChanged, + this, + &TreelandWallpaperNotifierClientV1::onSlowDownChanged); +} + +void TreelandWallpaperNotifierClientV1::treeland_wallpaper_notifier_v1_remove(const QString &file_source) +{ + for (auto window : std::as_const(m_windows)) { + if (window->property(WALLPAPERSOURCE).toString() == file_source) { + m_windows.removeOne(window); + delete window; + + return; + } + } +} + +void TreelandWallpaperNotifierClientV1::updateAllRefreshInterval() +{ + int minRefreshInterval = minScreenRefreshIntervalMs(); + for (auto *window : std::as_const(m_windows)) { + QObject *root = window->rootObject(); + auto *video = qobject_cast(root); + if (!video) { + continue; + } + + video->setRefreshInterval(minRefreshInterval); + } +} + +void TreelandWallpaperNotifierClientV1::updateAllWallpaperViewSizes() +{ + const QSize size = maxScreenSize(); + if (!size.isValid()) + return; + + for (QQuickView *view : std::as_const(m_windows)) { + if (!view) + continue; + + view->resize(size); + } +} + +void TreelandWallpaperNotifierClientV1::onScreenAdded(QScreen *screen) +{ + connect(screen, &QScreen::geometryChanged, + this, &TreelandWallpaperNotifierClientV1::updateAllWallpaperViewSizes); + + updateAllWallpaperViewSizes(); + updateAllRefreshInterval(); +} + +void TreelandWallpaperNotifierClientV1::onScreenRemoved(QScreen *screen) +{ + disconnect(screen, &QScreen::geometryChanged, + this, &TreelandWallpaperNotifierClientV1::updateAllWallpaperViewSizes); + + updateAllWallpaperViewSizes(); + updateAllRefreshInterval(); +} + +void TreelandWallpaperNotifierClientV1::onPlayChanged(bool play) +{ + WallpaperWindow *send = static_cast(sender()); + QQuickView *wallpaperWindow = static_cast(send->parentWindow()); + QObject *root = wallpaperWindow->rootObject(); + auto *video = qobject_cast(root); + if (video) { + video->setPause(!play); + } else { + if (QQuickAnimatedImage *image = qobject_cast(root)) { + if (image->frameCount() > 1) { + image->setPaused(!play); + } + } else { + qCCritical(WALLPAPER) << "Unsupported wallpaper Object"; + } + } +} + +void TreelandWallpaperNotifierClientV1::onSlowDownChanged(uint32_t duration) +{ + WallpaperWindow *send = static_cast(sender()); + QQuickView *wallpaperWindow = static_cast(send->parentWindow()); + QObject *root = wallpaperWindow->rootObject(); + auto *video = qobject_cast(root); + if (video) { + video->slowDown(duration); + } else { + if (QQuickAnimatedImage *image = qobject_cast(root)) { + if (image->frameCount() > 1) { + image->setPaused(true); + } + } else { + qCCritical(WALLPAPER) << "Unsupported wallpaper Object"; + } + } +} diff --git a/wallpaper-factory/treelandwallpapernotifierclient.h b/wallpaper-factory/treelandwallpapernotifierclient.h new file mode 100644 index 0000000000..805a751c8e --- /dev/null +++ b/wallpaper-factory/treelandwallpapernotifierclient.h @@ -0,0 +1,40 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "qwayland-treeland-wallpaper-shell-unstable-v1.h" + +#include +#include +#include +#include + +class TreelandWallpaperNotifierClientV1 + : public QWaylandClientExtensionTemplate + , public QtWayland::treeland_wallpaper_notifier_v1 +{ + Q_OBJECT +public: + explicit TreelandWallpaperNotifierClientV1(); + ~TreelandWallpaperNotifierClientV1() override; + + void instantiate(); + +protected: + void treeland_wallpaper_notifier_v1_add(uint32_t source_type, const QString &file_source) override; + void treeland_wallpaper_notifier_v1_remove(const QString &file_source) override; + +private: + void updateAllRefreshInterval(); + +private Q_SLOTS: + void updateAllWallpaperViewSizes(); + void onScreenAdded(QScreen *screen); + void onScreenRemoved(QScreen *screen); + void onPlayChanged(bool play); + void onSlowDownChanged(uint32_t duration); + +private: + QList m_windows; +}; diff --git a/wallpaper-factory/wallpaper-shell.json b/wallpaper-factory/wallpaper-shell.json new file mode 100644 index 0000000000..bf6f7c1f28 --- /dev/null +++ b/wallpaper-factory/wallpaper-shell.json @@ -0,0 +1,3 @@ +{ + "Keys": [ "wallpaper-shell" ] +} diff --git a/wallpaper-factory/wallpaper-shell.json.license b/wallpaper-factory/wallpaper-shell.json.license new file mode 100644 index 0000000000..8b2deb2aac --- /dev/null +++ b/wallpaper-factory/wallpaper-shell.json.license @@ -0,0 +1,2 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only diff --git a/wallpaper-factory/wallpaperwindow.cpp b/wallpaper-factory/wallpaperwindow.cpp new file mode 100644 index 0000000000..bedc60e68c --- /dev/null +++ b/wallpaper-factory/wallpaperwindow.cpp @@ -0,0 +1,140 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wallpaperwindow.h" +#include "loggings.h" +#include "qwaylandwallpapershellintegration_p.h" + +#include +#include + +#include + +static QMap s_map; + +class WallpaperWindowPrivate +{ +public: + WallpaperWindowPrivate(QWindow *window) + : parentWindow(window) + { + } + + QWindow *parentWindow; + QString source; + bool loaded = false; + QWaylandWallpaperShellIntegration *shellIntegration = nullptr; +}; + +WallpaperWindow::~WallpaperWindow() +{ + s_map.remove(d->parentWindow); + if (d->shellIntegration) { + delete d->shellIntegration; + } +} + +QString WallpaperWindow::source() +{ + return d->source; +} + +void WallpaperWindow::setSource(const QString &source) +{ + if (d->source == source) { + return; + } + + d->source = source; + Q_EMIT sourceChanged(); +} + +bool WallpaperWindow::eventFilter(QObject *watched, QEvent *event) +{ + auto window = qobject_cast(watched); + if (!window) { + return false; + } + if (event->type() == QEvent::PlatformSurface) { + if (auto pse = static_cast(event); pse->surfaceEventType() == QPlatformSurfaceEvent::SurfaceCreated) { + initializeShellIntegration(); + } + } + return false; +} + +WallpaperWindow *WallpaperWindow::get(QWindow *window) +{ + if (!window) { + return nullptr; + } + + auto shellWindow = s_map.value(window); + if (shellWindow) { + return shellWindow; + } + + return new WallpaperWindow(window); +} + +WallpaperWindow *WallpaperWindow::qmlAttachedProperties(QObject *object) +{ + return get(qobject_cast(object)); +} + +QWindow *WallpaperWindow::parentWindow() const +{ + return d->parentWindow; +} + +bool WallpaperWindow::loaded() +{ + return d->loaded; +} + +void WallpaperWindow::setLoaded(bool loaded) +{ + if (d->loaded == loaded) { + return; + } + + d->loaded = loaded; + Q_EMIT loadedChanged(); +} + +void WallpaperWindow::initializeShellIntegration() +{ + auto waylandWindow = dynamic_cast(d->parentWindow->handle()); + if (!waylandWindow) { + qCWarning(WALLPAPER) << d->parentWindow << "is not a wayland window. Not creating treeland_wallpaper_surface_v1"; + return; + } + + if (!d->shellIntegration) { + d->shellIntegration = new QWaylandWallpaperShellIntegration(); + if (!d->shellIntegration->initialize(waylandWindow->display())) { + delete d->shellIntegration; + d->shellIntegration = nullptr; + qCWarning(WALLPAPER) << "Failed to initialize treeland_wallpaper_produce integration, possibly because compositor does not support the treeland_wallpaper_produce_v1 protocol"; + return; + } + } + + waylandWindow->setShellIntegration(d->shellIntegration); +} + +WallpaperWindow::WallpaperWindow(QWindow *window) + : QObject(window) + , d(new WallpaperWindowPrivate(window)) +{ + s_map.insert(d->parentWindow, this); + window->installEventFilter(this); + + if (window->isVisible()) { + qCWarning(WALLPAPER) << d->parentWindow << "call QWindow::close() first and show it again"; + } + + if (window->handle()) { + initializeShellIntegration(); + } +} diff --git a/wallpaper-factory/wallpaperwindow.h b/wallpaper-factory/wallpaperwindow.h new file mode 100644 index 0000000000..90d31659c8 --- /dev/null +++ b/wallpaper-factory/wallpaperwindow.h @@ -0,0 +1,43 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +class WallpaperWindowPrivate; + +class WallpaperWindow : public QObject +{ + Q_OBJECT + Q_PROPERTY(QString source READ source WRITE setSource NOTIFY sourceChanged) +public: + ~WallpaperWindow() override; + + QString source(); + void setSource(const QString &source); + + bool eventFilter(QObject *watched, QEvent *event) override; + + static WallpaperWindow *get(QWindow *window); + static WallpaperWindow *qmlAttachedProperties(QObject *object); + QWindow *parentWindow() const; + + bool loaded(); + void setLoaded(bool loaded); +Q_SIGNALS: + void sourceChanged(); + void positionChanged(double position); + void playChanged(bool play); + void slowDownChanged(uint32_t duration); + void loadedChanged(); + +private: + void initializeShellIntegration(); + + WallpaperWindow(QWindow *window); + +private: + std::unique_ptr d; +}; diff --git a/waylib/.github/workflows/archlinux-build-wlroots-19.yaml b/waylib/.github/workflows/archlinux-build-wlroots-19.yaml index c073d20f72..bffb5b409a 100644 --- a/waylib/.github/workflows/archlinux-build-wlroots-19.yaml +++ b/waylib/.github/workflows/archlinux-build-wlroots-19.yaml @@ -30,7 +30,7 @@ jobs: - name: Configure CMake run: | mkdir -p ${{github.workspace}}/build - cmake -B ${{github.workspace}}/build -G Ninja -DWITH_SUBMODULE_QWLROOTS=ON + cmake -B ${{github.workspace}}/build -G Ninja - name: Build # Build your program with the given configuration run: cmake --build ${{github.workspace}}/build diff --git a/waylib/.gitmodules b/waylib/.gitmodules deleted file mode 100644 index 35363fe2c3..0000000000 --- a/waylib/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "qwlroots"] - path = qwlroots - url = https://github.com/vioken/qwlroots.git diff --git a/waylib/.reuse/dep5 b/waylib/.reuse/dep5 index 87c211b7eb..d880f91559 100644 --- a/waylib/.reuse/dep5 +++ b/waylib/.reuse/dep5 @@ -33,11 +33,6 @@ Files: debian/* Copyright: None License: CC0-1.0 -# C++ pch files -Files: src/server/pch/pch.hxx -Copyright: None -License: CC0-1.0 - # Files: examples/tinywl/qml.qrc tests/manual/cursor/cursor.qrc diff --git a/waylib/CMakeLists.txt b/waylib/CMakeLists.txt index 38908d2cdd..64cb781113 100644 --- a/waylib/CMakeLists.txt +++ b/waylib/CMakeLists.txt @@ -8,7 +8,6 @@ set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) -option(WITH_SUBMODULE_QWLROOTS "Use the QWlroots from git submodule" OFF) option(BUILD_EXAMPLES "A minimum viable product Wayland compositor based on waylib and other examples" ON) option(BUILD_TESTS "Build test demos" ON) option(DISABLE_XWAYLAND "Disable the xwayland support" OFF) @@ -17,14 +16,25 @@ option(INSTALL_TINYWL "A minimum viable product Wayland compositor based on wayl option(ADDRESS_SANITIZER "Enable address sanitize" OFF) option(WAYLIB_USE_PERCOMPILE_HEADERS "Use precompile headers to build waylib" OFF) -set(QT_COMPONENTS Core Gui Quick) -find_package(Qt6 COMPONENTS ${QT_COMPONENTS} REQUIRED) -if(WITH_SUBMODULE_QWLROOTS) - include(${CMAKE_CURRENT_SOURCE_DIR}/qwlroots/cmake/WaylandScannerHelpers.cmake) - add_subdirectory(qwlroots) - message("Using QWlroots from submodule") -else() - find_package(QWlroots REQUIRED) +# When waylib is built standalone (its own top-level project) it should keep +# installing development files by default. When built as a submodule of +# Treeland the parent project already defines TREELAND_INSTALL_DEV=OFF, and +# option() is a no-op for an already-cached variable, so the parent default +# wins. See the Treeland top-level CMakeLists.txt. +option(TREELAND_INSTALL_DEV "Install development files (headers, CMake config, pkg-config, .so symlinks)" ON) + +find_package(Qt6 COMPONENTS Core Gui Quick REQUIRED) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS GuiPrivate QuickPrivate) +endif() +include(${CMAKE_CURRENT_LIST_DIR}/cmake/WaylandScannerHelpers.cmake) + +# Standalone build (e.g. waylib CI packaging): the vendored wlroots tree +# lives next to waylib in the monorepo. Pull it in so the Wlroots::wlroots +# target exists instead of requiring an installed libwaylib-wlroots. +if(NOT TARGET Wlroots::wlroots AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/../wlroots/CMakeLists.txt") + add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../wlroots" + "${CMAKE_CURRENT_BINARY_DIR}/_wlroots") endif() if(DISABLE_XWAYLAND) @@ -42,6 +52,7 @@ include(CMakePackageConfigHelpers) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/") include(PackageVersionHelper) +add_subdirectory(tools) add_subdirectory(src) if(BUILD_EXAMPLES) add_subdirectory(examples) diff --git a/waylib/CMakePresets.json b/waylib/CMakePresets.json new file mode 100644 index 0000000000..ec02df8f65 --- /dev/null +++ b/waylib/CMakePresets.json @@ -0,0 +1,36 @@ +{ + "version": 3, + "configurePresets": [ + { + "name": "ci", + "displayName": "CI Build Config", + "description": "Build configuration with warnings as errors", + "generator": "Ninja", + "binaryDir": "${sourceDir}/build", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Release", + "CMAKE_CXX_FLAGS": "-Wall -Wextra -Werror -Wno-stringop-overflow -Wno-sfinae-incomplete", + "CMAKE_C_FLAGS": "-Wall -Wextra -Werror -Wno-stringop-overflow" + } + } + ], + "buildPresets": [ + { + "name": "ci", + "configurePreset": "ci", + "jobs": 0 + } + ], + "testPresets": [ + { + "name": "ci", + "configurePreset": "ci", + "output": { + "outputOnFailure": true + }, + "execution": { + "noTestsAction": "error" + } + } + ] +} diff --git a/waylib/LICENSES/MIT.txt b/waylib/LICENSES/MIT.txt new file mode 100644 index 0000000000..f7abf7e963 --- /dev/null +++ b/waylib/LICENSES/MIT.txt @@ -0,0 +1,23 @@ +MIT License + +Copyright (c) 2017, 2018 Drew DeVault +Copyright (c) 2014 Jari Vetoniemi +Copyright (c) 2023 The wlroots contributors + +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. diff --git a/waylib/README.md b/waylib/README.md index 00294b62f4..8aa955f4c0 100644 --- a/waylib/README.md +++ b/waylib/README.md @@ -2,7 +2,7 @@ ## Introduction -waylib is a Wayland compositor development library, based on [qwlroots](https://github.com/vioken/qwlroots), provides a Qt-style development interface. It is designed to be deeply integrated with QtQuick, taking advantage of QtQuick's Scene Graphics model to simplify the complexity of window management. In waylib, it is possible to attach one or multiple Wayland Outputs to a QQuickWindow, and a corresponding Wayland Surface can be attached to a QQuickItem, allowing it to be mixed with QtQuick's graphics components and supporting QRHI for OpenGL and Vulkan compatibility in a single piece of code. +waylib is a Wayland compositor development library, built directly on [wlroots](https://gitlab.freedesktop.org/wlroots/wlroots), providing a Qt-style development interface. It is designed to be deeply integrated with QtQuick, taking advantage of QtQuick's Scene Graphics model to simplify the complexity of window management. In waylib, it is possible to attach one or multiple Wayland Outputs to a QQuickWindow, and a corresponding Wayland Surface can be attached to a QQuickItem, allowing it to be mixed with QtQuick's graphics components and supporting QRHI for OpenGL and Vulkan compatibility in a single piece of code. Creating a Wayland compositor using waylib can be simple and efficient, which, on top of wlroots, provides: @@ -26,16 +26,11 @@ Based on the above features, compositor developers need only focus on the busine ## Building -Step 1: Compiling and Installing wlroots and qwlroots +Step 1: Compiling and Installing wlroots -waylib requires the development version (0.19) of wlroots, which needs to be [compiled and installed manually](https://gitlab.freedesktop.org/wlroots/wlroots#building). Arch Linux users can install [wlroots-0.19](https://archlinux.org/packages/extra/x86_64/wlroots0.19/). +waylib requires the development version (0.20) of wlroots, which needs to be [compiled and installed manually](https://gitlab.freedesktop.org/wlroots/wlroots#building). Arch Linux users can install [wlroots-0.20](https://archlinux.org/packages/extra/x86_64/wlroots0.20/). -For qwlroots, it is currently recommended to use the version provided as a submodule. However, you can also [compile and install](https://github.com/vioken/qwlroots) it by yourself. - -If using the submodule version, please note the following two points: - -1. Initialize the submodules when you clone the source code: `git clone git@github.com:vioken/waylib.git --recursive` -2. Before the final compilation, add the cmake parameter "-DWITH_SUBMODULE_QWLROOTS=ON" to enable the building of the submodule. +In this repository the wlroots source tree is vendored under `wlroots/` (upstream sources under `3rdparty/wlroots`) and built via CMake together with waylib, so no separate wlroots installation is required. Step 2: Installing other dependencies @@ -60,7 +55,7 @@ You can also packaging by using the command "nix build -v -L". Step 3: Execute the following commands ```bash -cmake -B build -DWITH_SUBMODULE_QWLROOTS=ON +cmake -B build cmake --build build ``` diff --git a/waylib/README.zh_CN.md b/waylib/README.zh_CN.md index 7a7c2fe617..8d8f7d1d98 100644 --- a/waylib/README.zh_CN.md +++ b/waylib/README.zh_CN.md @@ -2,7 +2,7 @@ ## 简介 -waylib 是一个 Wayland 合成器开发库,基于 [qwlroots](https://github.com/vioken/qwlroots) 开发,提供 Qt 风格的开发接口。其设计目标是与 QtQuick 深度结合,利用 QtQuick 的 Scene Graphics 模型,以简化窗口管理的复杂度。在 waylib 中,一个 QQuickWindow 上可以被附加一个或多个 Wayland Output,一个 QQuickItem 上会附加一个对应的 Wanyland Surface,可将其与 QtQuick 的图形组件混合使用,并且支持 QRHI,只需要一份代码即可兼容 OpenGL 和 Vulkan。 +waylib 是一个 Wayland 合成器开发库,直接基于 [wlroots](https://gitlab.freedesktop.org/wlroots/wlroots) 开发,提供 Qt 风格的开发接口。其设计目标是与 QtQuick 深度结合,利用 QtQuick 的 Scene Graphics 模型,以简化窗口管理的复杂度。在 waylib 中,一个 QQuickWindow 上可以被附加一个或多个 Wayland Output,一个 QQuickItem 上会附加一个对应的 Wanyland Surface,可将其与 QtQuick 的图形组件混合使用,并且支持 QRHI,只需要一份代码即可兼容 OpenGL 和 Vulkan。 使用 waylib 可以简单并高效的创建一个 Wayland 合成器,其在 wlroots 之上,提供了: @@ -26,15 +26,11 @@ waylib 是一个 Wayland 合成器开发库,基于 [qwlroots](https://github.c ## 构建 -步骤一:编译安装 wlroots 和 qwlroots +步骤一:编译安装 wlroots -waylib 需要安装开发版本(0.19)的 wlroots, 需要[自行编译安装](https://gitlab.freedesktop.org/wlroots/wlroots#building), Archlinux 用户可以安装 [wlroots-0.19](https://archlinux.org/packages/extra/x86_64/wlroots0.19/).。 +waylib 需要安装开发版本(0.20)的 wlroots, 需要[自行编译安装](https://gitlab.freedesktop.org/wlroots/wlroots#building), Archlinux 用户可以安装 [wlroots-0.20](https://archlinux.org/packages/extra/x86_64/wlroots0.20/).。 -qwlroot 目前推荐使用 submodule 提供的版本,当然也可以[自行编译安装](https://github.com/vioken/qwlroots)。 -如果使用 submodule 的版本,注意以下 2 点: - -1. 下载源码时初始化子模块 `git clone git@github.com:vioken/waylib.git --recursive` -2. 编译时使用添加一个 cmake 参数 "-DWITH_SUBMODULE_QWLROOTS=ON" 启用 submodule 的构建。 +本仓库将 wlroots 源码树 vendored 在 `wlroots/` 目录下(上游源码在 `3rdparty/wlroots/`),通过 CMake 与 waylib 一起构建,无需单独安装 wlroots。 步骤二:安装其他依赖 @@ -59,7 +55,7 @@ NixOS 步骤三:运行以下命令 ```bash -cmake -B build -DWITH_SUBMODULE_QWLROOTS=ON +cmake -B build cmake --build build ``` diff --git a/waylib/cmake/WaylandScannerHelpers.cmake b/waylib/cmake/WaylandScannerHelpers.cmake new file mode 100644 index 0000000000..97bc1a983f --- /dev/null +++ b/waylib/cmake/WaylandScannerHelpers.cmake @@ -0,0 +1,30 @@ +if(NOT DEFINED WAYLAND_PROTOCOLS_OUTPUTDIR) + set(WAYLAND_PROTOCOLS_OUTPUTDIR ${CMAKE_BINARY_DIR}/protocols) + file(MAKE_DIRECTORY ${WAYLAND_PROTOCOLS_OUTPUTDIR}) + message(STATUS "Create wayland protocols outputdir: ${WAYLAND_PROTOCOLS_OUTPUTDIR}") + include_directories(${WAYLAND_PROTOCOLS_OUTPUTDIR}) +else() + message(STATUS "Setting wayland protocols outputdir: ${WAYLAND_PROTOCOLS_OUTPUTDIR}") +endif() + +function(ws_generate type protocols input_file output_name) + find_package(PkgConfig) + pkg_get_variable(WAYLAND_PROTOCOLS ${protocols} pkgdatadir) + pkg_get_variable(WAYLAND_SCANNER wayland-scanner wayland_scanner) + + if(NOT EXISTS ${input_file}) + set(input_file ${WAYLAND_PROTOCOLS}/${input_file}) + endif() + + execute_process(COMMAND ${WAYLAND_SCANNER} + ${type}-header + ${input_file} + ${WAYLAND_PROTOCOLS_OUTPUTDIR}/${output_name}.h + ) + + execute_process(COMMAND ${WAYLAND_SCANNER} + public-code + ${input_file} + ${WAYLAND_PROTOCOLS_OUTPUTDIR}/${output_name}.c + ) +endfunction() diff --git a/waylib/debian/control b/waylib/debian/control index e4639a174f..4a3e819108 100644 --- a/waylib/debian/control +++ b/waylib/debian/control @@ -4,22 +4,60 @@ Priority: optional Maintainer: JiDe Zhang Build-Depends: cmake, debhelper-compat (= 13), - libpixman-1-dev, - libwlroots-0.19-dev, + ninja-build, + libpixman-1-dev (>= 0.43.0), libxcb-ewmh-dev, pkg-config, qml6-module-qtquick-templates, qt6-base-dev-tools (>= 6.6.0), qt6-base-private-dev (>= 6.6.0), qt6-declarative-private-dev (>= 6.6.0), - qwlroots, - wayland-protocols, + wayland-protocols (>= 1.41), wlr-protocols, + libwayland-dev (>= 1.23.1), + libxkbcommon-dev, + libudev-dev, + libseat-dev, + libdisplay-info-dev (>= 0.1.1), + libliftoff-dev (>= 0.4.1), + liblcms2-dev, + libinput-dev, + libegl1-mesa-dev, + libegl-dev, + libgbm-dev, + libgles2-mesa-dev, + libvulkan-dev, + glslang-tools, + hwdata, + libcap-dev, + libcairo2-dev, + libdrm-dev (>= 2.4.122), + libpixman-1-dev (>= 0.43.0), + libpng-dev, + libx11-xcb-dev, + libxcb1-dev, + libxcb-composite0-dev, + libxcb-dri3-dev, + libxcb-errors-dev, + libxcb-ewmh-dev, + libxcb-icccm4-dev, + libxcb-image0-dev, + libxcb-present-dev, + libxcb-render0-dev, + libxcb-render-util0-dev, + libxcb-res0-dev, + libxcb-shm0-dev, + libxcb-xfixes0-dev, + libxcb-xinput-dev, + xwayland, + treeland-protocols, Standards-Version: 3.9.8 Package: libwaylib Architecture: any -Depends: ${misc:Depends}, ${shlibs:Depends}, +Depends: ${misc:Depends}, ${shlibs:Depends} +Conflicts: qwlroots +Replaces: qwlroots Multi-Arch: same Description: A wrapper for wlroots based on Qt . @@ -28,13 +66,14 @@ Description: A wrapper for wlroots based on Qt Package: libwaylib-dev Architecture: any Depends: libwaylib (=${binary:Version}), - libwlroots-0.19-dev, qt6-base-dev-tools (>= 6.6.0), qt6-base-private-dev (>= 6.6.0), qt6-declarative-private-dev (>= 6.6.0), wlr-protocols, ${misc:Depends}, - ${shlibs:Depends}, + ${shlibs:Depends} +Conflicts: qwlroots +Replaces: qwlroots Description: A devel package for libwaylib . This package contains the header files and static libraries of waylib. diff --git a/waylib/debian/rules b/waylib/debian/rules index 14564ff56e..dec95d4112 100755 --- a/waylib/debian/rules +++ b/waylib/debian/rules @@ -4,6 +4,13 @@ DPKG_EXPORT_BUILDFLAGS = 1 # see FEATURE AREAS in dpkg-buildflags(1) export DEB_BUILD_MAINT_OPTIONS = hardening=+all +# see ENVIRONMENT in dpkg-buildflags(1) +# package maintainers to append CFLAGS +export DEB_CFLAGS_MAINT_APPEND = -Wall -Wextra -Werror -Wno-error=stringop-overflow +export DEB_CXXFLAGS_MAINT_APPEND = -Wall -Wextra -Werror -Wno-error=stringop-overflow +# package maintainers to append LDFLAGS +export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed + include /usr/share/dpkg/default.mk export QT_SELECT = qt6 @@ -11,7 +18,8 @@ export QT_SELECT = qt6 dh $@ --parallel override_dh_auto_configure: - dh_auto_configure -- -DCMAKE_INSTALL_PREFIX=/usr + test -f ../wlroots/CMakeLists.txt || (echo "Build libwaylib from the treeland monorepo root (sibling wlroots/ required)" && exit 1) + dh_auto_configure -- -GNinja -DCMAKE_INSTALL_PREFIX=/usr #override_dh_auto_test: # echo "skip auto test" diff --git a/waylib/examples/CMakeLists.txt b/waylib/examples/CMakeLists.txt index 97b9e944b2..2098157558 100644 --- a/waylib/examples/CMakeLists.txt +++ b/waylib/examples/CMakeLists.txt @@ -1,4 +1,6 @@ -add_subdirectory(tinywl) +if (NOT DISABLE_XWAYLAND) + add_subdirectory(tinywl) +endif() add_subdirectory(blur) add_subdirectory(surface-delegate) add_subdirectory(outputviewport) diff --git a/waylib/examples/blur/helper.h b/waylib/examples/blur/helper.h index dac21718a6..67a69b66fe 100644 --- a/waylib/examples/blur/helper.h +++ b/waylib/examples/blur/helper.h @@ -1,4 +1,4 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once @@ -18,14 +18,11 @@ class WSeat; class WBackend; WAYLIB_SERVER_END_NAMESPACE -QW_BEGIN_NAMESPACE -class qw_renderer; -class qw_allocator; -class qw_compositor; -QW_END_NAMESPACE +struct wlr_renderer; +struct wlr_allocator; +struct wlr_compositor; WAYLIB_SERVER_USE_NAMESPACE -QW_USE_NAMESPACE class Q_DECL_HIDDEN Helper : public QObject { @@ -48,9 +45,9 @@ class Q_DECL_HIDDEN Helper : public QObject WQmlCreator *m_outputCreator = nullptr; WBackend *m_backend = nullptr; - qw_renderer *m_renderer = nullptr; - qw_allocator *m_allocator = nullptr; - qw_compositor *m_compositor = nullptr; + wlr_renderer *m_renderer = nullptr; + wlr_allocator *m_allocator = nullptr; + wlr_compositor *m_compositor = nullptr; WQuickOutputLayout *m_outputLayout = nullptr; WCursor *m_cursor = nullptr; QPointer m_seat; diff --git a/waylib/examples/blur/main.cpp b/waylib/examples/blur/main.cpp index 7d6d48e037..77cc48ac26 100644 --- a/waylib/examples/blur/main.cpp +++ b/waylib/examples/blur/main.cpp @@ -1,6 +1,7 @@ -// Copyright (C) 2024 JiDe Zhang . +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include #include "helper.h" #include @@ -13,15 +14,7 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include #include #include @@ -31,8 +24,6 @@ #include #include -QW_USE_NAMESPACE - Helper::Helper(QObject *parent) : QObject(parent) , m_server(new WServer(this)) @@ -56,7 +47,7 @@ void Helper::initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine) qFatal("Failed to create renderer"); } - connect(m_backend, &WBackend::outputAdded, this, [this, window, qmlEngine] (WOutput *output) { + connect(m_backend, &WBackend::outputAdded, this, [this, qmlEngine] (WOutput *output) { auto initProperties = qmlEngine->newObject(); initProperties.setProperty("waylandOutput", qmlEngine->toScriptValue(output)); initProperties.setProperty("layout", qmlEngine->toScriptValue(m_outputLayout)); @@ -77,12 +68,12 @@ void Helper::initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine) m_seat->detachInputDevice(device); }); - m_allocator = qw_allocator::autocreate(*m_backend->handle(), *m_renderer); - m_renderer->init_wl_display(*m_server->handle()); + m_allocator = wlr_allocator_autocreate(m_backend->handle(), m_renderer); + wlr_renderer_init_wl_display(m_renderer, m_server->handle()); // free follow display - m_compositor = qw_compositor::create(*m_server->handle(), 6, *m_renderer); - qw_subcompositor::create(*m_server->handle()); + m_compositor = wlr_compositor_create(m_server->handle(), 6, m_renderer); + wlr_subcompositor_create(m_server->handle()); connect(window, &WOutputRenderWindow::outputViewportInitialized, this, [] (WOutputViewport *viewport) { // Trigger QWOutput::frame signal in order to ensure WOutputHelper::renderable @@ -91,34 +82,37 @@ void Helper::initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine) WOutput *output = viewport->output(); // Enable on default - auto qwoutput = output->handle(); + auto *wlrOutput = output->handle(); // Don't care for WOutput::isEnabled, must do WOutput::commit here, // In order to ensure trigger QWOutput::frame signal, WOutputRenderWindow // needs this signal to render next frmae. Because QWOutput::frame signal - // maybe emit before WOutputRenderWindow::attach, if no commit here, + // maybe Q_EMIT before WOutputRenderWindow::attach, if no commit here, // WOutputRenderWindow will ignore this ouptut on render. - if (!qwoutput->property("_Enabled").toBool()) { - qwoutput->setProperty("_Enabled", true); - qw_output_state newState; + if (!output->property("_Enabled").toBool()) { + output->setProperty("_Enabled", true); + wlr_output_state newState; + wlr_output_state_init(&newState); - if (!qwoutput->handle()->current_mode) { - auto mode = qwoutput->preferred_mode(); + if (!wlrOutput->current_mode) { + auto mode = wlr_output_preferred_mode(wlrOutput); if (mode) - newState.set_mode(mode); + wlr_output_state_set_mode(&newState, mode); + } + wlr_output_state_set_enabled(&newState, true); + if (!wlr_output_commit_state(wlrOutput, &newState)) { + qCritical("commit failed on output %s", wlrOutput->name); } - newState.set_enabled(true); - bool ok = qwoutput->commit_state(newState); - Q_ASSERT(ok); + wlr_output_state_finish(&newState); } } }); window->init(m_renderer, m_allocator); - m_backend->handle()->start(); + wlr_backend_start(m_backend->handle()); } int main(int argc, char *argv[]) { - qw_log::init(); + WLog::init(); WServer::initializeQPA(); // QQuickStyle::setStyle("Material"); @@ -139,11 +133,13 @@ int main(int argc, char *argv[]) { helper->initProtocols(window, &waylandEngine); // multi output - qobject_cast(helper->backend()->handle())->for_each_backend([] (wlr_backend *backend, void *) { - if (auto x11 = qw_x11_backend::from(backend)) { - x11->output_create(); - } - }, nullptr); + if (wlr_backend_is_multi(helper->backend()->handle())) { + wlr_multi_for_each_backend(helper->backend()->handle(), [] (wlr_backend *backend, void *) { + if (wlr_backend_is_x11(backend)) { + wlr_x11_output_create(backend); + } + }, nullptr); + } return app.exec(); } diff --git a/waylib/examples/outputcopy/helper.h b/waylib/examples/outputcopy/helper.h index 02d5098e5f..304f3478c9 100644 --- a/waylib/examples/outputcopy/helper.h +++ b/waylib/examples/outputcopy/helper.h @@ -1,4 +1,4 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once @@ -25,14 +25,11 @@ class WOutputViewport; class WOutputLayer; WAYLIB_SERVER_END_NAMESPACE -QW_BEGIN_NAMESPACE -class qw_renderer; -class qw_allocator; -class qw_compositor; -QW_END_NAMESPACE +struct wlr_renderer; +struct wlr_allocator; +struct wlr_compositor; WAYLIB_SERVER_USE_NAMESPACE -QW_USE_NAMESPACE class Q_DECL_HIDDEN Helper : public QObject { @@ -56,9 +53,9 @@ class Q_DECL_HIDDEN Helper : public QObject WServer *m_server = nullptr; WBackend *m_backend = nullptr; - qw_renderer *m_renderer = nullptr; - qw_allocator *m_allocator = nullptr; - qw_compositor *m_compositor = nullptr; + wlr_renderer *m_renderer = nullptr; + wlr_allocator *m_allocator = nullptr; + wlr_compositor *m_compositor = nullptr; WQuickOutputLayout *m_outputLayout = nullptr; WCursor *m_cursor = nullptr; QPointer m_seat; diff --git a/waylib/examples/outputcopy/main.cpp b/waylib/examples/outputcopy/main.cpp index ff41ff1020..6afa76e1ea 100644 --- a/waylib/examples/outputcopy/main.cpp +++ b/waylib/examples/outputcopy/main.cpp @@ -1,6 +1,7 @@ -// Copyright (C) 2024 JiDe Zhang . +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include #include "helper.h" #include @@ -16,15 +17,7 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include #include @@ -35,8 +28,6 @@ #include #include -QW_USE_NAMESPACE - Helper::Helper(QObject *parent) : QObject(parent) , m_server(new WServer(this)) @@ -141,44 +132,47 @@ void Helper::initProtocols(QQmlEngine *qmlEngine) m_seat->detachInputDevice(device); }); - m_allocator = qw_allocator::autocreate(*m_backend->handle(), *m_renderer); - m_renderer->init_wl_display(*m_server->handle()); + m_allocator = wlr_allocator_autocreate(m_backend->handle(), m_renderer); + wlr_renderer_init_wl_display(m_renderer, m_server->handle()); // free follow display - m_compositor = qw_compositor::create(*m_server->handle(), 6, *m_renderer); - qw_subcompositor::create(*m_server->handle()); + m_compositor = wlr_compositor_create(m_server->handle(), 6, m_renderer); + wlr_subcompositor_create(m_server->handle()); connect(m_renderWindow, &WOutputRenderWindow::outputViewportInitialized, this, [] (WOutputViewport *viewport) { - // Trigger qw_output::frame signal in order to ensure WOutputHelper::renderable + // Trigger wlr_output::frame signal in order to ensure WOutputHelper::renderable // property is true, OutputRenderWindow when will render this output in next frame. { WOutput *output = viewport->output(); // Enable on default - auto qwoutput = output->handle(); + auto *wlrOutput = output->handle(); // Don't care for WOutput::isEnabled, must do WOutput::commit here, // In order to ensure trigger qw_output::frame signal, WOutputRenderWindow // needs this signal to render next frmae. Because qw_output::frame signal - // maybe emit before WOutputRenderWindow::attach, if no commit here, + // maybe Q_EMIT before WOutputRenderWindow::attach, if no commit here, // WOutputRenderWindow will ignore this ouptut on render. - if (!qwoutput->property("_Enabled").toBool()) { - qwoutput->setProperty("_Enabled", true); - qw_output_state newState; + if (!output->property("_Enabled").toBool()) { + output->setProperty("_Enabled", true); + wlr_output_state newState; + wlr_output_state_init(&newState); - if (!qwoutput->handle()->current_mode) { - auto mode = qwoutput->preferred_mode(); + if (!wlrOutput->current_mode) { + auto mode = wlr_output_preferred_mode(wlrOutput); if (mode) - newState.set_mode(mode); + wlr_output_state_set_mode(&newState, mode); + } + wlr_output_state_set_enabled(&newState, true); + if (!wlr_output_commit_state(wlrOutput, &newState)) { + qCritical("commit failed on output %s", wlrOutput->name); } - newState.set_enabled(true); - bool ok = qwoutput->commit_state(newState); - Q_ASSERT(ok); + wlr_output_state_finish(&newState); } } }); m_renderWindow->init(m_renderer, m_allocator); - m_backend->handle()->start(); + wlr_backend_start(m_backend->handle()); } void Helper::updatePrimaryOutputHardwareLayers() @@ -201,7 +195,7 @@ void Helper::updatePrimaryOutputHardwareLayers() } int main(int argc, char *argv[]) { - qw_log::init(); + WLog::init(); WServer::initializeQPA(); // QQuickStyle::setStyle("Material"); @@ -218,22 +212,24 @@ int main(int argc, char *argv[]) { helper->initProtocols(&waylandEngine); // multi output - qobject_cast(helper->backend()->handle())->for_each_backend([] (wlr_backend *backend, void *) { - qw_output *newOutput = nullptr; + wlr_multi_for_each_backend(helper->backend()->handle(), [] (wlr_backend *backend, void *) { + wlr_output *newOutput = nullptr; - if (auto x11 = qw_x11_backend::from(backend)) { - newOutput = qw_output::from(x11->output_create()); - } else if (auto wayland = qw_wayland_backend::from(backend)) { - newOutput = qw_output::from(wayland->output_create()); + if (wlr_backend_is_x11(backend)) { + newOutput = wlr_x11_output_create(backend); + } else if (wlr_backend_is_wl(backend)) { + newOutput = wlr_wl_output_create(backend); } if (!newOutput) return; // 800x600 - qw_output_state newState; - newState.set_custom_mode(1000, 600, 0); - newOutput->commit_state(newState); + wlr_output_state newState; + wlr_output_state_init(&newState); + wlr_output_state_set_custom_mode(&newState, 1000, 600, 0); + wlr_output_commit_state(newOutput, &newState); + wlr_output_state_finish(&newState); }, nullptr); return app.exec(); diff --git a/waylib/examples/outputviewport/helper.h b/waylib/examples/outputviewport/helper.h index dac21718a6..67a69b66fe 100644 --- a/waylib/examples/outputviewport/helper.h +++ b/waylib/examples/outputviewport/helper.h @@ -1,4 +1,4 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once @@ -18,14 +18,11 @@ class WSeat; class WBackend; WAYLIB_SERVER_END_NAMESPACE -QW_BEGIN_NAMESPACE -class qw_renderer; -class qw_allocator; -class qw_compositor; -QW_END_NAMESPACE +struct wlr_renderer; +struct wlr_allocator; +struct wlr_compositor; WAYLIB_SERVER_USE_NAMESPACE -QW_USE_NAMESPACE class Q_DECL_HIDDEN Helper : public QObject { @@ -48,9 +45,9 @@ class Q_DECL_HIDDEN Helper : public QObject WQmlCreator *m_outputCreator = nullptr; WBackend *m_backend = nullptr; - qw_renderer *m_renderer = nullptr; - qw_allocator *m_allocator = nullptr; - qw_compositor *m_compositor = nullptr; + wlr_renderer *m_renderer = nullptr; + wlr_allocator *m_allocator = nullptr; + wlr_compositor *m_compositor = nullptr; WQuickOutputLayout *m_outputLayout = nullptr; WCursor *m_cursor = nullptr; QPointer m_seat; diff --git a/waylib/examples/outputviewport/main.cpp b/waylib/examples/outputviewport/main.cpp index c41d1adbb7..711187d55e 100644 --- a/waylib/examples/outputviewport/main.cpp +++ b/waylib/examples/outputviewport/main.cpp @@ -1,6 +1,7 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include #include "helper.h" #include @@ -13,15 +14,7 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include #include @@ -32,8 +25,6 @@ #include #include -QW_USE_NAMESPACE - Helper::Helper(QObject *parent) : QObject(parent) , m_server(new WServer(this)) @@ -57,7 +48,7 @@ void Helper::initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine) qFatal("Failed to create renderer"); } - connect(m_backend, &WBackend::outputAdded, this, [this, window, qmlEngine] (WOutput *output) { + connect(m_backend, &WBackend::outputAdded, this, [this, qmlEngine] (WOutput *output) { auto initProperties = qmlEngine->newObject(); initProperties.setProperty("waylandOutput", qmlEngine->toScriptValue(output)); initProperties.setProperty("layout", qmlEngine->toScriptValue(m_outputLayout)); @@ -78,12 +69,12 @@ void Helper::initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine) m_seat->detachInputDevice(device); }); - m_allocator = qw_allocator::autocreate(*m_backend->handle(), *m_renderer); - m_renderer->init_wl_display(*m_server->handle()); + m_allocator = wlr_allocator_autocreate(m_backend->handle(), m_renderer); + wlr_renderer_init_wl_display(m_renderer, m_server->handle()); // free follow display - m_compositor = qw_compositor::create(*m_server->handle(), 6, *m_renderer); - qw_subcompositor::create(*m_server->handle()); + m_compositor = wlr_compositor_create(m_server->handle(), 6, m_renderer); + wlr_subcompositor_create(m_server->handle()); connect(window, &WOutputRenderWindow::outputViewportInitialized, this, [] (WOutputViewport *viewport) { // Trigger QWOutput::frame signal in order to ensure WOutputHelper::renderable @@ -92,34 +83,37 @@ void Helper::initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine) WOutput *output = viewport->output(); // Enable on default - auto qwoutput = output->handle(); + auto *wlrOutput = output->handle(); // Don't care for WOutput::isEnabled, must do WOutput::commit here, // In order to ensure trigger QWOutput::frame signal, WOutputRenderWindow // needs this signal to render next frmae. Because QWOutput::frame signal - // maybe emit before WOutputRenderWindow::attach, if no commit here, + // maybe Q_EMIT before WOutputRenderWindow::attach, if no commit here, // WOutputRenderWindow will ignore this ouptut on render. - if (!qwoutput->property("_Enabled").toBool()) { - qwoutput->setProperty("_Enabled", true); - qw_output_state newState; + if (!output->property("_Enabled").toBool()) { + output->setProperty("_Enabled", true); + wlr_output_state newState; + wlr_output_state_init(&newState); - if (!qwoutput->handle()->current_mode) { - auto mode = qwoutput->preferred_mode(); + if (!wlrOutput->current_mode) { + auto mode = wlr_output_preferred_mode(wlrOutput); if (mode) - newState.set_mode(mode); + wlr_output_state_set_mode(&newState, mode); + } + wlr_output_state_set_enabled(&newState, true); + if (!wlr_output_commit_state(wlrOutput, &newState)) { + qCritical("commit failed on output %s", wlrOutput->name); } - newState.set_enabled(true); - bool ok = qwoutput->commit_state(newState); - Q_ASSERT(ok); + wlr_output_state_finish(&newState); } } }); window->init(m_renderer, m_allocator); - m_backend->handle()->start(); + wlr_backend_start(m_backend->handle()); } int main(int argc, char *argv[]) { - qw_log::init(); + WLog::init(); WServer::initializeQPA(); // QQuickStyle::setStyle("Material"); diff --git a/waylib/examples/surface-delegate/Main.qml b/waylib/examples/surface-delegate/Main.qml index 05f60b4fe8..5945f8e97e 100644 --- a/waylib/examples/surface-delegate/Main.qml +++ b/waylib/examples/surface-delegate/Main.qml @@ -16,7 +16,7 @@ Item { id: backend onOutputAdded: function(output) { - if (!backend.hasDrm) + if (!backend.isDrm) output.forceSoftwareCursor = true // Test outputManager.add({waylandOutput: output}) } diff --git a/waylib/examples/surface-delegate/main.cpp b/waylib/examples/surface-delegate/main.cpp index 801a177d3c..cc440792b6 100644 --- a/waylib/examples/surface-delegate/main.cpp +++ b/waylib/examples/surface-delegate/main.cpp @@ -1,13 +1,11 @@ -// Copyright (C) 2024 JiDe Zhang . +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include #include #include -#include -#include -#include -#include +#include #include #include @@ -19,7 +17,6 @@ #include WAYLIB_SERVER_USE_NAMESPACE -QW_USE_NAMESPACE class Q_DECL_HIDDEN Helper : public QObject { @@ -41,7 +38,7 @@ class Q_DECL_HIDDEN Helper : public QObject }; int main(int argc, char *argv[]) { - qw_log::init(); + WLog::init(); WServer::initializeQPA(); // QQuickStyle::setStyle("Material"); diff --git a/waylib/examples/tinywl/CMakeLists.txt b/waylib/examples/tinywl/CMakeLists.txt index 307fb453b3..29a36cbd75 100644 --- a/waylib/examples/tinywl/CMakeLists.txt +++ b/waylib/examples/tinywl/CMakeLists.txt @@ -1,5 +1,8 @@ find_package(Qt6 COMPONENTS Quick QuickControls2 REQUIRED) -qt_standard_project_setup(REQUIRES 6.4) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS QuickPrivate) +endif() +qt_standard_project_setup(REQUIRES 6.8) if(QT_KNOWN_POLICY_QTP0001) # this policy was introduced in Qt 6.5 qt_policy(SET QTP0001 NEW) @@ -26,6 +29,7 @@ add_executable(${TARGET} qt_add_qml_module(${TARGET} URI Tinywl VERSION "2.0" + IMPORTS Waylib.Server SOURCES helper.h helper.cpp SOURCES surfacewrapper.h surfacewrapper.cpp diff --git a/waylib/examples/tinywl/Decoration.qml b/waylib/examples/tinywl/Decoration.qml index 14d9ecdcc5..58ae443ba6 100644 --- a/waylib/examples/tinywl/Decoration.qml +++ b/waylib/examples/tinywl/Decoration.qml @@ -30,21 +30,21 @@ Item { Cursor.shape: { switch(edges) { case Qt.TopEdge: - return Waylib.CursorShape.TopSide + return CursorShape.TopSide case Qt.RightEdge: - return Waylib.CursorShape.RightSide + return CursorShape.RightSide case Qt.BottomEdge: - return Waylib.CursorShape.BottomSide + return CursorShape.BottomSide case Qt.LeftEdge: - return Waylib.CursorShape.LeftSide + return CursorShape.LeftSide case Qt.TopEdge | Qt.LeftEdge: - return Waylib.CursorShape.TopLeftCorner + return CursorShape.TopLeftCorner case Qt.TopEdge | Qt.RightEdge: - return Waylib.CursorShape.TopRightCorner + return CursorShape.TopRightCorner case Qt.BottomEdge | Qt.LeftEdge: - return Waylib.CursorShape.BottomLeftCorner + return CursorShape.BottomLeftCorner case Qt.BottomEdge | Qt.RightEdge: - return Waylib.CursorShape.BottomRightCorner + return CursorShape.BottomRightCorner } return Qt.ArrowCursor; diff --git a/waylib/examples/tinywl/helper.cpp b/waylib/examples/tinywl/helper.cpp index da5e833e03..c3763b3266 100644 --- a/waylib/examples/tinywl/helper.cpp +++ b/waylib/examples/tinywl/helper.cpp @@ -1,7 +1,8 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "helper.h" +#include #include "surfacewrapper.h" #include "output.h" #include "workspace.h" @@ -9,6 +10,7 @@ #include "surfacecontainer.h" #include "rootsurfacecontainer.h" #include "layersurfacecontainer.h" +#include "wsessionlocksurface.h" #include #include @@ -27,6 +29,11 @@ #include #include #include +#include +#include +#include +#include +#include #include #include #include @@ -36,29 +43,15 @@ #include #include #include +#include #include #include #include #include #include +#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include #include @@ -73,11 +66,15 @@ #include #include +#include + #define WLR_FRACTIONAL_SCALE_V1_VERSION 1 +#define EXT_DATA_CONTROL_MANAGER_V1_VERSION 1 Helper *Helper::m_instance = nullptr; Helper::Helper(QObject *parent) : WSeatEventFilter(parent) + , WObject() , m_renderWindow(new WOutputRenderWindow(this)) , m_server(new WServer(this)) , m_surfaceContainer(new RootSurfaceContainer(m_renderWindow->contentItem())) @@ -87,6 +84,7 @@ Helper::Helper(QObject *parent) , m_topContainer(new LayerSurfaceContainer(m_surfaceContainer)) , m_overlayContainer(new LayerSurfaceContainer(m_surfaceContainer)) , m_popupContainer(new SurfaceContainer(m_surfaceContainer)) + , m_lockContainer(new SurfaceContainer(m_surfaceContainer)) { setCurrentUserId(getuid()); @@ -95,19 +93,20 @@ Helper::Helper(QObject *parent) m_renderWindow->setColor(Qt::black); m_surfaceContainer->setFlag(QQuickItem::ItemIsFocusScope, true); -#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) m_surfaceContainer->setFocusPolicy(Qt::StrongFocus); -#endif m_backgroundContainer->setZ(RootSurfaceContainer::BackgroundZOrder); m_bottomContainer->setZ(RootSurfaceContainer::BottomZOrder); m_workspace->setZ(RootSurfaceContainer::NormalZOrder); m_topContainer->setZ(RootSurfaceContainer::TopZOrder); m_overlayContainer->setZ(RootSurfaceContainer::OverlayZOrder); m_popupContainer->setZ(RootSurfaceContainer::PopupZOrder); + m_lockContainer->setZ(RootSurfaceContainer::LockZOrder); } Helper::~Helper() { + teardown(); + for (auto s : m_surfaceContainer->surfaces()) { if (auto c = s->container()) c->removeSurface(s); @@ -146,7 +145,9 @@ void Helper::init() m_surfaceContainer->setQmlEngine(engine); m_surfaceContainer->init(m_server); + auto *pointerGestures = m_server->attach(); m_seat = m_server->attach(); + m_seat->setPointerGestures(pointerGestures); m_seat->setEventFilter(this); m_seat->setCursor(m_surfaceContainer->cursor()); m_seat->setKeyboardFocusWindow(m_renderWindow); @@ -163,7 +164,7 @@ void Helper::init() auto wOutputManager = m_server->attach(); connect(m_backend, &WBackend::outputAdded, this, [this, wOutputManager] (WOutput *output) { allowNonDrmOutputAutoChangeMode(output); - Output *o; + Output *o = nullptr; if (m_mode == OutputMode::Extension || !m_surfaceContainer->primaryOutput()) { o = Output::createPrimary(output, qmlEngine(), this); o->outputItem()->stackBefore(m_surfaceContainer); @@ -171,6 +172,7 @@ void Helper::init() } else if (m_mode == OutputMode::Copy) { o = Output::createCopy(output, m_surfaceContainer->primaryOutput(), qmlEngine(), this); } + Q_ASSERT(o); m_outputList.append(o); enableOutput(output); @@ -181,6 +183,10 @@ void Helper::init() auto index = indexOfOutput(output); Q_ASSERT(index >= 0); const auto o = m_outputList.takeAt(index); + // Detach the per-output request_state listener while the native + // handle is still valid: wlr_output_finish() requires the listener + // list to be empty. + output->removeListeners(this); wOutputManager->removeOutput(output); m_surfaceContainer->removeOutput(o); delete o; @@ -218,7 +224,7 @@ void Helper::init() } }; - surface->safeConnect(&WXdgToplevelSurface::parentXdgSurfaceChanged, this, updateSurfaceWithParentContainer); + QObject::connect(surface, &WXdgToplevelSurface::parentXdgSurfaceChanged, this, updateSurfaceWithParentContainer); updateSurfaceWithParentContainer(); connect(wrapper, &SurfaceWrapper::requestShowWindowMenu, m_windowMenu, [this, wrapper] (QPoint pos) { @@ -264,6 +270,52 @@ void Helper::init() m_surfaceContainer->destroyForSurface(surface->surface()); }); + auto *sessionLockManager = m_server->attach(); + m_lockContainer->setVisible(false); + QObject::connect(sessionLockManager, &WSessionLockManager::lockCreated, this, [this](WSessionLock *lock) { + if (m_lockContainer->isVisible()) { + qWarning() << "Only one session lock is allowed!"; + lock->finish(); + return; + } + m_sessionLock = lock; + QObject::connect(m_sessionLock, &WSessionLock::surfaceAdded, this, [this](WSessionLockSurface *surface) { + auto output = getOutput(surface->output()); + auto wrapper = new SurfaceWrapper(qmlEngine(), surface, SurfaceWrapper::Type::SessionLock); + auto geometry = output->geometry(); + wrapper->resize(geometry.size()); + wrapper->setPosition(geometry.topLeft()); + connect(output->outputItem(), &WOutputItem::geometryChanged, this, [output, wrapper] { + auto geometry = output->geometry(); + wrapper->resize(geometry.size()); + wrapper->setPosition(geometry.topLeft()); + }); + wrapper->setNoDecoration(true); + wrapper->setOwnsOutput(output); + m_lockContainer->addSurface(wrapper); + }); + m_lockContainer->setVisible(true); + lock->lock(); + QObject::connect(m_sessionLock, &WSessionLock::surfaceRemoved, this, [this](WSessionLockSurface *surface) { + m_surfaceContainer->destroyForSurface(surface->surface()); + }); + QObject::connect(m_sessionLock, &WSessionLock::unlocked, this, [this] { + qDebug() << "Session unlocked normally"; + m_lockContainer->setVisible(false); + m_sessionLock = nullptr; + }); + QObject::connect(m_sessionLock, &WSessionLock::canceled, this, [this] { + qDebug() << "Session lock was canceled (destroyed by client before locking)"; + m_lockContainer->setVisible(false); + m_sessionLock = nullptr; + }); + QObject::connect(m_sessionLock, &WSessionLock::abandoned, this, [this] { + qDebug() << "Session lock was abandoned (locking client likely died)"; + qDebug() << "To meet protocol requirement, the session must remain locked. Here session is unlocked for simplicity."; + m_lockContainer->setVisible(false); + m_sessionLock = nullptr; + }); + }); m_server->start(); m_renderer = WRenderHelper::createRenderer(m_backend->handle()); @@ -271,14 +323,14 @@ void Helper::init() qFatal("Failed to create renderer"); } - m_allocator = qw_allocator::autocreate(*m_backend->handle(), *m_renderer); - m_renderer->init_wl_display(*m_server->handle()); + m_allocator = wlr_allocator_autocreate(m_backend->handle(), m_renderer); + wlr_renderer_init_wl_display(m_renderer, m_server->handle()); // free follow display - m_compositor = qw_compositor::create(*m_server->handle(), 6, *m_renderer); - qw_subcompositor::create(*m_server->handle()); - qw_screencopy_manager_v1::create(*m_server->handle()); - qw_viewporter::create(*m_server->handle()); + m_compositor = wlr_compositor_create(m_server->handle(), 6, m_renderer); + wlr_subcompositor_create(m_server->handle()); + wlr_screencopy_manager_v1_create(m_server->handle()); + wlr_viewporter_create(m_server->handle()); m_renderWindow->init(m_renderer, m_allocator); // for xwayland @@ -297,12 +349,12 @@ void Helper::init() }); connect(m_xwayland, &WXWayland::surfaceAdded, this, [this] (WXWaylandSurface *surface) { - surface->safeConnect(&qw_xwayland_surface::notify_associate, this, [this, surface] { + connect(surface, &WXWaylandSurface::associated, this, [this, surface] { auto wrapper = new SurfaceWrapper(qmlEngine(), surface, SurfaceWrapper::Type::XWayland); // Setup title and decoration auto xwayland = qobject_cast(wrapper->shellSurface()); - auto updateDecorationTitleBar = [this, wrapper, xwayland]() { + auto updateDecorationTitleBar = [wrapper, xwayland]() { if (!xwayland->isBypassManager()) { wrapper->setNoTitleBar(xwayland->decorationsFlags() & WXWaylandSurface::DecorationsNoTitle); @@ -341,7 +393,7 @@ void Helper::init() m_workspace->addSurface(wrapper); } }; - surface->safeConnect(&WXWaylandSurface::parentXWaylandSurfaceChanged, + QObject::connect(surface, &WXWaylandSurface::parentXWaylandSurfaceChanged, this, updateSurfaceWithParentContainer); updateSurfaceWithParentContainer(); @@ -354,14 +406,21 @@ void Helper::init() m_foreignToplevel->addSurface(surface); m_extForeignToplevelListV1->addSurface(surface); }); - surface->safeConnect(&qw_xwayland_surface::notify_dissociate, this, [this, surface] { + connect(surface, &WXWaylandSurface::aboutToDissociate, this, [this, surface] { m_foreignToplevel->removeSurface(surface); m_extForeignToplevelListV1->removeSurface(surface); m_surfaceContainer->destroyForSurface(surface->surface()); }); }); - m_inputMethodHelper = new WInputMethodHelper(m_server, m_seat); + const WInputMethodHelper::Protocols inputMethodProtocols { + m_server->attach(), + m_server->attach(), + m_server->attach(), + m_server->attach(), + m_server->attach(), + }; + m_inputMethodHelper = new WInputMethodHelper(m_server, m_seat, inputMethodProtocols); connect(m_inputMethodHelper, &WInputMethodHelper::inputPopupSurfaceV2Added, this, [this](WInputPopupSurface *inputPopup) { auto wrapper = new SurfaceWrapper(qmlEngine(), inputPopup, SurfaceWrapper::Type::InputPopup); @@ -396,10 +455,10 @@ void Helper::init() return; } - auto gammaControlManager = qw_gamma_control_manager_v1::create(*m_server->handle()); - connect(gammaControlManager, &qw_gamma_control_manager_v1::notify_set_gamma, this, [this] + auto gammaControlManager = wlr_gamma_control_manager_v1_create(m_server->handle()); + listeners()->add(&gammaControlManager->events.set_gamma, this, [] (wlr_gamma_control_manager_v1_set_gamma_event *event) { - auto *qwOutput = qw_output::from(event->output); + auto *output = event->output; size_t ramp_size = 0; uint16_t *r = nullptr, *g = nullptr, *b = nullptr; wlr_gamma_control_v1 *gamma_control = event->control; @@ -409,35 +468,50 @@ void Helper::init() g = gamma_control->table + gamma_control->ramp_size; b = gamma_control->table + 2 * gamma_control->ramp_size; } - qw_output_state newState; - newState.set_gamma_lut(ramp_size, r, g, b); + wlr_output_state newState; + wlr_output_state_init(&newState); + wlr_color_transform *colorTransform = nullptr; + if (gamma_control) { + colorTransform = wlr_color_transform_init_lut_3x1d(ramp_size, r, g, b); + if (!colorTransform) { + wlr_gamma_control_v1_send_failed_and_destroy(gamma_control); + wlr_output_state_finish(&newState); + return; + } + } + wlr_output_state_set_color_transform(&newState, colorTransform); + wlr_color_transform_unref(colorTransform); - if (!qwOutput->commit_state(newState)) { - qw_gamma_control_v1::from(gamma_control)->send_failed_and_destroy(); + if (!wlr_output_commit_state(output, &newState)) { + wlr_gamma_control_v1_send_failed_and_destroy(gamma_control); } + wlr_output_state_finish(&newState); }); connect(wOutputManager, &WOutputManagerV1::requestTestOrApply, this, [this, wOutputManager] - (qw_output_configuration_v1 *config, bool onlyTest) { + (wlr_output_configuration_v1 *config, bool onlyTest) { QList states = wOutputManager->stateListPending(); bool ok = true; for (auto state : std::as_const(states)) { WOutput *output = state.output; - qw_output_state newState; + wlr_output_state newState; + wlr_output_state_init(&newState); - newState.set_enabled(state.enabled); + wlr_output_state_set_enabled(&newState, state.enabled); if (state.enabled) { if (state.mode) - newState.set_mode(state.mode); + wlr_output_state_set_mode(&newState, state.mode); else - newState.set_custom_mode(state.customModeSize.width(), - state.customModeSize.height(), - state.customModeRefresh); + wlr_output_state_set_custom_mode(&newState, + state.customModeSize.width(), + state.customModeSize.height(), + state.customModeRefresh); - newState.set_adaptive_sync_enabled(state.adaptiveSyncEnabled); + wlr_output_state_set_adaptive_sync_enabled(&newState, state.adaptiveSyncEnabled); if (!onlyTest) { - newState.set_transform(static_cast(state.transform)); - newState.set_scale(state.scale); + wlr_output_state_set_transform(&newState, + static_cast(state.transform)); + wlr_output_state_set_scale(&newState, state.scale); WOutputViewport *viewport = getOutput(output)->screenViewport(); if (viewport) { @@ -448,19 +522,21 @@ void Helper::init() } if (onlyTest) - ok &= output->handle()->test_state(newState); + ok &= wlr_output_test_state(output->handle(), &newState); else - ok &= output->handle()->commit_state(newState); + ok &= wlr_output_commit_state(output->handle(), &newState); + wlr_output_state_finish(&newState); } wOutputManager->sendResult(config, ok); }); m_server->attach(); - qw_fractional_scale_manager_v1::create(*m_server->handle(), WLR_FRACTIONAL_SCALE_V1_VERSION); - qw_data_control_manager_v1::create(*m_server->handle()); - qw_alpha_modifier_v1::create(*m_server->handle()); + wlr_fractional_scale_manager_v1_create(m_server->handle(), WLR_FRACTIONAL_SCALE_V1_VERSION); + wlr_data_control_manager_v1_create(m_server->handle()); + wlr_ext_data_control_manager_v1_create(m_server->handle(), EXT_DATA_CONTROL_MANAGER_V1_VERSION); + wlr_alpha_modifier_v1_create(m_server->handle()); - m_backend->handle()->start(); + wlr_backend_start(m_backend->handle()); qInfo() << "Listing on:" << m_socket->fullServerName(); startDemoClient(); @@ -527,7 +603,7 @@ bool Helper::beforeDisposeEvent(WSeat *seat, QWindow *, QInputEvent *event) if (event->type() == QEvent::KeyPress) { auto kevent = static_cast(event); if (QKeySequence(kevent->keyCombination()) == QKeySequence::Quit) { - qApp->quit(); + Q_EMIT requestQuit(); return true; } else if (event->modifiers() == Qt::MetaModifier) { if (kevent->key() == Qt::Key_Right) { @@ -573,10 +649,8 @@ bool Helper::beforeDisposeEvent(WSeat *seat, QWindow *, QInputEvent *event) return false; } -bool Helper::afterHandleEvent(WSeat *seat, WSurface *watched, QObject *surfaceItem, QObject *, QInputEvent *event) +bool Helper::afterHandleEvent([[maybe_unused]] WSeat *seat, WSurface *watched, QObject *surfaceItem, QObject *, QInputEvent *event) { - Q_UNUSED(seat) - if (event->isSinglePointEvent() && static_cast(event)->isBeginEvent()) { // surfaceItem is qml type: XdgSurfaceItem or LayerSurfaceItem auto toplevelSurface = qobject_cast(surfaceItem)->shellSurface(); @@ -673,11 +747,13 @@ void Helper::setCursorPosition(const QPointF &position) void Helper::allowNonDrmOutputAutoChangeMode(WOutput *output) { - output->safeConnect(&qw_output::notify_request_state, - this, [this] (wlr_output_event_request_state *newState) { + // One listener group per output via output->listeners(this); ~WOutput + // and onOutputRemoved both removeListeners(this). + auto *wlrOutput = output->handle(); + output->listeners(this)->add(&wlrOutput->events.request_state, this, + [this, wlrOutput] (wlr_output_event_request_state *newState) { if (newState->state->committed & WLR_OUTPUT_STATE_MODE) { - auto output = qobject_cast(sender()); - output->commit_state(newState->state); + wlr_output_commit_state(wlrOutput, newState->state); } }); } @@ -685,24 +761,27 @@ void Helper::allowNonDrmOutputAutoChangeMode(WOutput *output) void Helper::enableOutput(WOutput *output) { // Enable on default - auto qwoutput = output->handle(); + auto *wlrOutput = output->handle(); // Don't care for WOutput::isEnabled, must do WOutput::commit here, // In order to ensure trigger QWOutput::frame signal, WOutputRenderWindow // needs this signal to render next frmae. Because QWOutput::frame signal - // maybe emit before WOutputRenderWindow::attach, if no commit here, + // maybe Q_EMIT before WOutputRenderWindow::attach, if no commit here, // WOutputRenderWindow will ignore this ouptut on render. - if (!qwoutput->property("_Enabled").toBool()) { - qwoutput->setProperty("_Enabled", true); - qw_output_state newState; + if (!output->property("_Enabled").toBool()) { + output->setProperty("_Enabled", true); + wlr_output_state newState; + wlr_output_state_init(&newState); - if (!qwoutput->handle()->current_mode) { - auto mode = qwoutput->preferred_mode(); + if (!wlrOutput->current_mode) { + auto mode = wlr_output_preferred_mode(wlrOutput); if (mode) - newState.set_mode(mode); + wlr_output_state_set_mode(&newState, mode); } - newState.set_enabled(true); - bool ok = qwoutput->commit_state(newState); - Q_ASSERT(ok); + wlr_output_state_set_enabled(&newState, true); + if (!wlr_output_commit_state(wlrOutput, &newState)) { + qCritical("commit failed on output %s", wlrOutput->name); + } + wlr_output_state_finish(&newState); } } @@ -726,11 +805,11 @@ Output *Helper::getOutput(WOutput *output) const void Helper::addOutput() { - qobject_cast(m_backend->handle())->for_each_backend([] (wlr_backend *backend, void *) { - if (auto x11 = qw_x11_backend::from(backend)) { - qw_output::from(x11->output_create()); - } else if (auto wayland = qw_wayland_backend::from(backend)) { - qw_output::from(wayland->output_create()); + wlr_multi_for_each_backend(m_backend->handle(), [] (wlr_backend *backend, void *) { + if (wlr_backend_is_x11(backend)) { + wlr_x11_output_create(backend); + } else if (wlr_backend_is_wl(backend)) { + wlr_wl_output_create(backend); } }, nullptr); } @@ -746,7 +825,7 @@ void Helper::setOutputMode(OutputMode mode) if (m_outputList.at(i) == m_surfaceContainer->primaryOutput()) continue; - Output *o; + Output *o = nullptr; if (mode == OutputMode::Copy) { o = Output::createCopy(m_outputList.at(i)->output(), m_surfaceContainer->primaryOutput(), qmlEngine(), this); m_surfaceContainer->removeOutput(m_outputList.at(i)); @@ -756,17 +835,13 @@ void Helper::setOutputMode(OutputMode mode) m_surfaceContainer->addOutput(o); enableOutput(o->output()); } + Q_ASSERT(o); m_outputList.at(i)->deleteLater(); m_outputList.replace(i,o); } } -void Helper::setOutputProxy(Output *output) -{ - -} - void Helper::updateLayerSurfaceContainer(SurfaceWrapper *surface) { auto layer = qobject_cast(surface->shellSurface()); @@ -816,7 +891,7 @@ void Helper::setAnimationSpeed(float newAnimationSpeed) if (qFuzzyCompare(m_animationSpeed, newAnimationSpeed)) return; m_animationSpeed = newAnimationSpeed; - emit animationSpeedChanged(); + Q_EMIT animationSpeedChanged(); } Helper::OutputMode Helper::outputMode() const diff --git a/waylib/examples/tinywl/helper.h b/waylib/examples/tinywl/helper.h index cfa04edfbf..596229c06d 100644 --- a/waylib/examples/tinywl/helper.h +++ b/waylib/examples/tinywl/helper.h @@ -1,12 +1,14 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include "qmlengine.h" #include "workspace.h" +#include "wsessionlock.h" #include +#include #include #include #include @@ -41,21 +43,18 @@ class WSurfaceItem; class WForeignToplevel; WAYLIB_SERVER_END_NAMESPACE -QW_BEGIN_NAMESPACE -class qw_renderer; -class qw_allocator; -class qw_compositor; -QW_END_NAMESPACE +struct wlr_renderer; +struct wlr_allocator; +struct wlr_compositor; WAYLIB_SERVER_USE_NAMESPACE -QW_USE_NAMESPACE class Output; class SurfaceWrapper; class Workspace; class RootSurfaceContainer; class LayerSurfaceContainer; -class Helper : public WSeatEventFilter +class Helper : public WSeatEventFilter, public WAYLIB_SERVER_NAMESPACE::WObject { friend class RootSurfaceContainer; Q_OBJECT @@ -110,7 +109,7 @@ public Q_SLOTS: void activeSurface(SurfaceWrapper *wrapper); void fakePressSurfaceBottomRightToReszie(SurfaceWrapper *surface); -signals: +Q_SIGNALS: void socketEnabledChanged(); void keyboardFocusSurfaceChanged(); void activatedSurfaceChanged(); @@ -119,6 +118,7 @@ public Q_SLOTS: void animationSpeedChanged(); void outputModeChanged(); + void requestQuit(); private: void allowNonDrmOutputAutoChangeMode(WOutput *output); @@ -126,8 +126,6 @@ public Q_SLOTS: int indexOfOutput(WOutput *output) const; - void setOutputProxy(Output *output); - void updateLayerSurfaceContainer(SurfaceWrapper *surface); SurfaceWrapper *keyboardFocusSurface() const; @@ -154,11 +152,11 @@ public Q_SLOTS: WSocket *m_socket = nullptr; WSeat *m_seat = nullptr; WBackend *m_backend = nullptr; - qw_renderer *m_renderer = nullptr; - qw_allocator *m_allocator = nullptr; + wlr_renderer *m_renderer = nullptr; + wlr_allocator *m_allocator = nullptr; // protocols - qw_compositor *m_compositor = nullptr; + wlr_compositor *m_compositor = nullptr; WXWayland *m_xwayland = nullptr; WInputMethodHelper *m_inputMethodHelper = nullptr; WXdgDecorationManager *m_xdgDecorationManager = nullptr; @@ -178,10 +176,13 @@ public Q_SLOTS: LayerSurfaceContainer *m_topContainer = nullptr; LayerSurfaceContainer *m_overlayContainer = nullptr; SurfaceContainer *m_popupContainer = nullptr; + SurfaceContainer *m_lockContainer = nullptr; int m_currentUserId = -1; float m_animationSpeed = 1.0; OutputMode m_mode = OutputMode::Extension; std::optional m_fakelastPressedPosition; + + WSessionLock *m_sessionLock = nullptr; }; Q_DECLARE_OPAQUE_POINTER(RootSurfaceContainer*) diff --git a/waylib/examples/tinywl/main.cpp b/waylib/examples/tinywl/main.cpp index 4a8eaa9744..a836739279 100644 --- a/waylib/examples/tinywl/main.cpp +++ b/waylib/examples/tinywl/main.cpp @@ -1,21 +1,22 @@ -// Copyright (C) 2024 JiDe Zhang . +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include #include "helper.h" #include -#include -#include + +#include #include WAYLIB_SERVER_USE_NAMESPACE int main(int argc, char *argv[]) { - qw_log::init(); + WLog::init(); WRenderHelper::setupRendererBackend(); - Q_ASSERT(qw_buffer::get_objects().isEmpty()); + Q_ASSERT(waylib_buffer_get_count() == 0); WServer::initializeQPA(); // QQuickStyle::setStyle("Material"); @@ -28,21 +29,27 @@ int main(int argc, char *argv[]) { QGuiApplication::setQuitOnLastWindowClosed(false); QGuiApplication app(argc, argv); - QmlEngine qmlEngine; + QmlEngine *qmlEngine = new QmlEngine; - QObject::connect(&qmlEngine, &QQmlEngine::quit, &app, &QGuiApplication::quit); - QObject::connect(&qmlEngine, &QQmlEngine::exit, &app, [] (int code) { - qApp->exit(code); + QObject::connect(qmlEngine, &QQmlEngine::quit, qmlEngine, &QmlEngine::deleteLater); + QObject::connect(qmlEngine, &QQmlEngine::exit, &app, [qmlEngine, &quitCode] (int code) { + quitCode = code; + qmlEngine->deleteLater(); + }); + QObject::connect(qmlEngine, &QmlEngine::destroyed, &app, [&] { + // make sure all deleted before app exit + app.exit(quitCode); }); - Helper *helper = qmlEngine.singletonInstance("Tinywl", "Helper"); + Helper *helper = qmlEngine->singletonInstance("Tinywl", "Helper"); + QObject::connect(helper, &Helper::requestQuit, qmlEngine, &QmlEngine::deleteLater); helper->init(); quitCode = app.exec(); } Q_ASSERT(!helper); - Q_ASSERT(qw_buffer::get_objects().isEmpty()); + Q_ASSERT(waylib_buffer_get_count() == 0); return quitCode; } diff --git a/waylib/examples/tinywl/output.cpp b/waylib/examples/tinywl/output.cpp index a2ce5465a1..4de1974bf8 100644 --- a/waylib/examples/tinywl/output.cpp +++ b/waylib/examples/tinywl/output.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2024 JiDe Zhang . +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "output.h" @@ -17,9 +17,6 @@ #include #include -#include -#include - #include Q_LOGGING_CATEGORY(qLcLayerShell, "tinywl.shell.layer", QtWarningMsg) @@ -29,7 +26,7 @@ Output *Output::createPrimary(WOutput *output, QQmlEngine *engine, QObject *pare QQmlComponent delegate(engine, "Tinywl", "PrimaryOutput"); QObject *obj = delegate.beginCreate(engine->rootContext()); delegate.setInitialProperties(obj, { - {"forceSoftwareCursor", output->handle()->is_x11()} + {QStringLiteral("forceSoftwareCursor"), wlr_output_is_x11(output->handle())} }); delegate.completeCreate(); WOutputItem *outputItem = qobject_cast(obj); @@ -134,7 +131,7 @@ void Output::addSurface(SurfaceWrapper *surface) if (surface->type() == SurfaceWrapper::Type::Layer) { auto layer = qobject_cast(surface->shellSurface()); - layer->safeConnect(&WLayerSurface::layerPropertiesChanged, this, &Output::layoutLayerSurfaces); + QObject::connect(layer, &WLayerSurface::layerPropertiesChanged, this, &Output::layoutLayerSurfaces); layoutLayerSurfaces(); } else { @@ -163,7 +160,7 @@ void Output::removeSurface(SurfaceWrapper *surface) if (surface->type() == SurfaceWrapper::Type::Layer) { if (auto ss = surface->shellSurface()) { - ss->safeDisconnect(this); + ss->disconnect(this); removeExclusiveZone(ss); } layoutLayerSurfaces(); @@ -250,7 +247,7 @@ void Output::layoutLayerSurface(SurfaceWrapper *surface) { WLayerSurface* layer = qobject_cast(surface->shellSurface()); Q_ASSERT(layer); - if (!layer->handle()->handle()->initialized) { + if (!layer->handle()->initialized) { return; } @@ -328,13 +325,15 @@ void Output::layoutLayerSurfaces() if (oldExclusiveZone != m_exclusiveZone) { layoutNonLayerSurfaces(); - emit exclusiveZoneChanged(); + Q_EMIT exclusiveZoneChanged(); } } void Output::layoutNonLayerSurface(SurfaceWrapper *surface, const QSizeF &sizeDiff) { Q_ASSERT(surface->type() != SurfaceWrapper::Type::Layer); + if (surface->type() == SurfaceWrapper::Type::SessionLock) + return; surface->setFullscreenGeometry(geometry()); const auto validGeo = this->validGeometry(); surface->setMaximizedGeometry(validGeo); @@ -444,7 +443,7 @@ void Output::updatePositionFromLayout() WOutputLayout * layout = output()->layout(); Q_ASSERT(layout); - auto *layoutOutput = layout->handle()->get(output()->nativeHandle()); + auto *layoutOutput = wlr_output_layout_get(layout->handle(), output()->handle()); QPointF pos(layoutOutput->x, layoutOutput->y); m_item->setPosition(pos); } diff --git a/waylib/examples/tinywl/output.h b/waylib/examples/tinywl/output.h index dfdc6aa211..dcec665ca0 100644 --- a/waylib/examples/tinywl/output.h +++ b/waylib/examples/tinywl/output.h @@ -65,7 +65,7 @@ class Output : public SurfaceListModel WOutputViewport *screenViewport() const; void updatePositionFromLayout(); -signals: +Q_SIGNALS: void exclusiveZoneChanged(); void moveResizeFinised(); diff --git a/waylib/examples/tinywl/rootsurfacecontainer.cpp b/waylib/examples/tinywl/rootsurfacecontainer.cpp index 660e18b832..d9104fa204 100644 --- a/waylib/examples/tinywl/rootsurfacecontainer.cpp +++ b/waylib/examples/tinywl/rootsurfacecontainer.cpp @@ -1,7 +1,8 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "rootsurfacecontainer.h" +#include #include "helper.h" #include "surfacewrapper.h" #include "output.h" @@ -13,8 +14,6 @@ #include #include -#include - #include WAYLIB_SERVER_USE_NAMESPACE @@ -50,11 +49,12 @@ void RootSurfaceContainer::init(WServer *server) setHeight(height); }); - m_outputLayout->safeConnect(&qw_output_layout::notify_change, this, [this] { + m_outputLayoutListenerOwner = std::make_unique(); + m_outputLayout->listeners(m_outputLayoutListenerOwner.get())->add( + &m_outputLayout->handle()->events.change, this, [this] { for (auto output : std::as_const(outputs())) { output->updatePositionFromLayout(); } - ensureCursorVisible(); // for (auto s : m_surfaceContainer->surfaces()) { @@ -67,11 +67,11 @@ void RootSurfaceContainer::init(WServer *server) m_dragSurfaceItem->setZ(static_cast>(WOutputLayout::Layer::Cursor) - 1); m_dragSurfaceItem->setFlags(WSurfaceItem::DontCacheLastBuffer); - m_cursor->safeConnect(&WCursor::positionChanged, this, [this] { + QObject::connect(m_cursor, &WCursor::positionChanged, this, [this] { m_dragSurfaceItem->setPosition(m_cursor->position()); }); - m_cursor->safeConnect(&WCursor::requestedDragSurfaceChanged, this, [this] { + QObject::connect(m_cursor, &WCursor::requestedDragSurfaceChanged, this, [this] { m_dragSurfaceItem->setSurface(m_cursor->requestedDragSurface()); }); } @@ -259,7 +259,7 @@ void RootSurfaceContainer::addBySubContainer(SurfaceContainer *sub, SurfaceWrapp Q_ASSERT(surface); startResize(surface, edges); }); - connect(surface, &SurfaceWrapper::surfaceStateChanged, this, [surface, this] { + connect(surface, &SurfaceWrapper::surfaceStateChanged, this, [surface] { if (surface->surfaceState() == SurfaceWrapper::State::Minimized || surface->surfaceState() == SurfaceWrapper::State::Tiling) return; @@ -273,8 +273,8 @@ void RootSurfaceContainer::addBySubContainer(SurfaceContainer *sub, SurfaceWrapp if (auto xdgPopupSurface = qobject_cast(surface->shellSurface())) { if (parentSurface->type() != SurfaceWrapper::Type::Layer) { auto pos = parentSurface->position() + parentSurface->surfaceItem()->position() + xdgPopupSurface->getPopupPosition(); - if (auto op = m_outputLayout->handle()->output_at(pos.x(), pos.y())) - output = Helper::instance()->getOutput(WOutput::fromHandle(qw_output::from(op))); + if (auto op = wlr_output_layout_output_at(m_outputLayout->handle(), pos.x(), pos.y())) + output = Helper::instance()->getOutput(WOutput::fromHandle(op)); } } surface->setOwnsOutput(output); @@ -328,10 +328,8 @@ bool RootSurfaceContainer::filterSurfaceGeometryChanged(SurfaceWrapper *surface, return false; } -bool RootSurfaceContainer::filterSurfaceStateChange(SurfaceWrapper *surface, SurfaceWrapper::State newState, SurfaceWrapper::State oldState) +bool RootSurfaceContainer::filterSurfaceStateChange(SurfaceWrapper *surface, [[maybe_unused]] SurfaceWrapper::State newState, [[maybe_unused]] SurfaceWrapper::State oldState) { - Q_UNUSED(oldState); - Q_UNUSED(newState); return surface == moveResizeState.surface; } @@ -349,11 +347,11 @@ Output *RootSurfaceContainer::cursorOutput() const { Q_ASSERT(m_cursor->layout() == m_outputLayout); const auto &pos = m_cursor->position(); - auto o = m_outputLayout->handle()->output_at(pos.x(), pos.y()); + auto o = wlr_output_layout_output_at(m_outputLayout->handle(), pos.x(), pos.y()); if (!o) return nullptr; - return Helper::instance()->getOutput(WOutput::fromHandle(qw_output::from(o))); + return Helper::instance()->getOutput(WOutput::fromHandle(o)); } Output *RootSurfaceContainer::primaryOutput() const @@ -366,7 +364,7 @@ void RootSurfaceContainer::setPrimaryOutput(Output *newPrimaryOutput) if (m_primaryOutput == newPrimaryOutput) return; m_primaryOutput = newPrimaryOutput; - emit primaryOutputChanged(); + Q_EMIT primaryOutputChanged(); } const QList &RootSurfaceContainer::outputs() const @@ -377,7 +375,7 @@ const QList &RootSurfaceContainer::outputs() const void RootSurfaceContainer::ensureCursorVisible() { const auto cursorPos = m_cursor->position(); - if (m_outputLayout->handle()->output_at(cursorPos.x(), cursorPos.y())) + if (wlr_output_layout_output_at(m_outputLayout->handle(), cursorPos.x(), cursorPos.y())) return; if (m_primaryOutput) { diff --git a/waylib/examples/tinywl/rootsurfacecontainer.h b/waylib/examples/tinywl/rootsurfacecontainer.h index 835cfb0e01..eb5284b2e2 100644 --- a/waylib/examples/tinywl/rootsurfacecontainer.h +++ b/waylib/examples/tinywl/rootsurfacecontainer.h @@ -1,10 +1,11 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include "surfacecontainer.h" #include +#include WAYLIB_SERVER_BEGIN_NAMESPACE class WSurface; @@ -45,6 +46,7 @@ class RootSurfaceContainer : public SurfaceContainer TaskBarZOrder = 3, MenuBarZOrder = 3, PopupZOrder = 4, + LockZOrder = 5 }; void init(WServer *server); @@ -71,12 +73,12 @@ class RootSurfaceContainer : public SurfaceContainer OutputListModel *outputModel() const; -public slots: +public Q_SLOTS: void startMove(SurfaceWrapper *surface); void startResize(SurfaceWrapper *surface, Qt::Edges edges); void cancelMoveResize(SurfaceWrapper *surface); -signals: +Q_SIGNALS: void primaryOutputChanged(); void moveResizeFinised(); @@ -100,6 +102,8 @@ public slots: WCursor *m_cursor = nullptr; WSurfaceItem *m_dragSurfaceItem = nullptr; + std::unique_ptr m_outputLayoutListenerOwner; + // for move resize struct { SurfaceWrapper *surface = nullptr; diff --git a/waylib/examples/tinywl/surfacecontainer.cpp b/waylib/examples/tinywl/surfacecontainer.cpp index 866c89c278..2cb2584705 100644 --- a/waylib/examples/tinywl/surfacecontainer.cpp +++ b/waylib/examples/tinywl/surfacecontainer.cpp @@ -218,7 +218,7 @@ bool SurfaceContainer::doAddSurface(SurfaceWrapper *surface, bool setContainer) } m_model->addSurface(surface); - emit surfaceAdded(surface); + Q_EMIT surfaceAdded(surface); if (auto p = parentContainer()) p->addBySubContainer(this, surface); @@ -237,7 +237,7 @@ bool SurfaceContainer::doRemoveSurface(SurfaceWrapper *surface, bool setContaine } m_model->removeSurface(surface); - emit surfaceRemoved(surface); + Q_EMIT surfaceRemoved(surface); if (auto p = parentContainer()) p->removeBySubContainer(this, surface); @@ -245,15 +245,13 @@ bool SurfaceContainer::doRemoveSurface(SurfaceWrapper *surface, bool setContaine return true; } -void SurfaceContainer::addBySubContainer(SurfaceContainer *sub, SurfaceWrapper *surface) +void SurfaceContainer::addBySubContainer([[maybe_unused]] SurfaceContainer *sub, SurfaceWrapper *surface) { - Q_UNUSED(sub); doAddSurface(surface, false); } -void SurfaceContainer::removeBySubContainer(SurfaceContainer *sub, SurfaceWrapper *surface) +void SurfaceContainer::removeBySubContainer([[maybe_unused]] SurfaceContainer *sub, SurfaceWrapper *surface) { - Q_UNUSED(sub); doRemoveSurface(surface, false); } diff --git a/waylib/examples/tinywl/surfacecontainer.h b/waylib/examples/tinywl/surfacecontainer.h index 8d2915e82f..f211bfe381 100644 --- a/waylib/examples/tinywl/surfacecontainer.h +++ b/waylib/examples/tinywl/surfacecontainer.h @@ -48,8 +48,7 @@ class ObjectListModel : public QAbstractListModel data.insert(Qt::DisplayRole, QVariant::fromValue(m_objects.at(index.row()))); return data; } - Qt::ItemFlags flags(const QModelIndex &index) const override { - Q_UNUSED(index); + Qt::ItemFlags flags([[maybe_unused]] const QModelIndex &index) const override { return Qt::ItemIsSelectable|Qt::ItemIsEnabled; } QHash roleNames() const override { @@ -96,11 +95,11 @@ class SurfaceListModel : public ObjectListModel virtual void addSurface(SurfaceWrapper *surface) { if (addObject(surface)) - emit surfaceAdded(surface); + Q_EMIT surfaceAdded(surface); } virtual void removeSurface(SurfaceWrapper *surface) { if (removeObject(surface)) - emit surfaceRemoved(surface); + Q_EMIT surfaceRemoved(surface); } QHash roleNames() const override; @@ -115,7 +114,7 @@ class SurfaceListModel : public ObjectListModel return hasObject(surface); } -signals: +Q_SIGNALS: void surfaceAdded(SurfaceWrapper *surface); void surfaceRemoved(SurfaceWrapper *surface); @@ -204,7 +203,7 @@ class SurfaceContainer : public QQuickItem return m_model; } -signals: +Q_SIGNALS: void surfaceAdded(SurfaceWrapper *surface); void surfaceRemoved(SurfaceWrapper *surface); diff --git a/waylib/examples/tinywl/surfaceproxy.cpp b/waylib/examples/tinywl/surfaceproxy.cpp index 9ef2c1f7ea..abd0c3107f 100644 --- a/waylib/examples/tinywl/surfaceproxy.cpp +++ b/waylib/examples/tinywl/surfaceproxy.cpp @@ -76,7 +76,7 @@ void SurfaceProxy::setSurface(SurfaceWrapper *newSurface) m_shadow = nullptr; } - emit surfaceChanged(); + Q_EMIT surfaceChanged(); } void SurfaceProxy::geometryChange(const QRectF &newGeo, const QRectF &oldGeo) @@ -142,7 +142,7 @@ void SurfaceProxy::onSourceRadiusChanged() if (m_shadow) m_shadow->setProperty("radius", radius()); if (m_radius < 0) - emit radiusChanged(); + Q_EMIT radiusChanged(); } qreal SurfaceProxy::radius() const @@ -163,7 +163,7 @@ void SurfaceProxy::setRadius(qreal newRadius) m_shadow->setProperty("radius", radius()); } - emit radiusChanged(); + Q_EMIT radiusChanged(); } void SurfaceProxy::resetRadius() @@ -190,7 +190,7 @@ void SurfaceProxy::setLive(bool newLive) } } - emit liveChanged(); + Q_EMIT liveChanged(); } QSizeF SurfaceProxy::maxSize() const @@ -205,7 +205,7 @@ void SurfaceProxy::setMaxSize(const QSizeF &newMaxSize) m_maxSize = newMaxSize; updateImplicitSize(); - emit maxSizeChanged(); + Q_EMIT maxSizeChanged(); } bool SurfaceProxy::fullProxy() const @@ -233,5 +233,5 @@ void SurfaceProxy::setFullProxy(bool newFullProxy) updateProxySurfaceTitleBarAndDecoration(); } - emit fullProxyChanged(); + Q_EMIT fullProxyChanged(); } diff --git a/waylib/examples/tinywl/surfaceproxy.h b/waylib/examples/tinywl/surfaceproxy.h index 776de72aa9..5665349f41 100644 --- a/waylib/examples/tinywl/surfaceproxy.h +++ b/waylib/examples/tinywl/surfaceproxy.h @@ -35,7 +35,7 @@ class SurfaceProxy : public QQuickItem bool fullProxy() const; void setFullProxy(bool newFullProxy); -signals: +Q_SIGNALS: void surfaceChanged(); void radiusChanged(); void liveChanged(); diff --git a/waylib/examples/tinywl/surfacewrapper.cpp b/waylib/examples/tinywl/surfacewrapper.cpp index a83f54ccc4..3e82232eac 100644 --- a/waylib/examples/tinywl/surfacewrapper.cpp +++ b/waylib/examples/tinywl/surfacewrapper.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "surfacewrapper.h" @@ -51,6 +51,9 @@ SurfaceWrapper::SurfaceWrapper(QmlEngine *qmlEngine, WToplevelSurface *shellSurf case Type::InputPopup: m_surfaceItem = new WInputPopupSurfaceItem(this); break; + case Type::SessionLock: + m_surfaceItem = new WSurfaceItem(this); + break; default: Q_UNREACHABLE(); } @@ -60,20 +63,20 @@ SurfaceWrapper::SurfaceWrapper(QmlEngine *qmlEngine, WToplevelSurface *shellSurf m_surfaceItem->setResizeMode(WSurfaceItem::ManualResize); m_surfaceItem->setShellSurface(shellSurface); - shellSurface->safeConnect(&WToplevelSurface::requestMinimize, this, &SurfaceWrapper::requestMinimize); - shellSurface->safeConnect(&WToplevelSurface::requestCancelMinimize, this, &SurfaceWrapper::requestCancelMinimize); - shellSurface->safeConnect(&WToplevelSurface::requestMaximize, this, &SurfaceWrapper::requestMaximize); - shellSurface->safeConnect(&WToplevelSurface::requestCancelMaximize, this, &SurfaceWrapper::requestCancelMaximize); - shellSurface->safeConnect(&WToplevelSurface::requestMove, this, [this](WSeat *, quint32) { + QObject::connect(shellSurface, &WToplevelSurface::requestMinimize, this, &SurfaceWrapper::requestMinimize); + QObject::connect(shellSurface, &WToplevelSurface::requestCancelMinimize, this, &SurfaceWrapper::requestCancelMinimize); + QObject::connect(shellSurface, &WToplevelSurface::requestMaximize, this, &SurfaceWrapper::requestMaximize); + QObject::connect(shellSurface, &WToplevelSurface::requestCancelMaximize, this, &SurfaceWrapper::requestCancelMaximize); + QObject::connect(shellSurface, &WToplevelSurface::requestMove, this, [this](WSeat *, quint32) { Q_EMIT requestMove(); }); - shellSurface->safeConnect(&WToplevelSurface::requestResize, this, [this](WSeat *, Qt::Edges edge, quint32) { + QObject::connect(shellSurface, &WToplevelSurface::requestResize, this, [this](WSeat *, Qt::Edges edge, quint32) { Q_EMIT requestResize(edge); }); - shellSurface->safeConnect(&WToplevelSurface::requestFullscreen, this, &SurfaceWrapper::requestFullscreen); - shellSurface->safeConnect(&WToplevelSurface::requestCancelFullscreen, this, &SurfaceWrapper::requestCancelFullscreen); + QObject::connect(shellSurface, &WToplevelSurface::requestFullscreen, this, &SurfaceWrapper::requestFullscreen); + QObject::connect(shellSurface, &WToplevelSurface::requestCancelFullscreen, this, &SurfaceWrapper::requestCancelFullscreen); if (type == Type::XdgToplevel) { - shellSurface->safeConnect(&WToplevelSurface::requestShowWindowMenu, this, [this](WSeat *, QPoint pos, quint32) { + QObject::connect(shellSurface, &WToplevelSurface::requestShowWindowMenu, this, [this](WSeat *, QPoint pos, quint32) { Q_EMIT requestShowWindowMenu(pos); }); } @@ -88,9 +91,7 @@ SurfaceWrapper::SurfaceWrapper(QmlEngine *qmlEngine, WToplevelSurface *shellSurf setImplicitSize(m_surfaceItem->implicitWidth(), m_surfaceItem->implicitHeight()); if (!shellSurface->hasCapability(WToplevelSurface::Capability::Focus)) { -#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) m_surfaceItem->setFocusPolicy(Qt::NoFocus); -#endif } if (type == Type::XWayland) { @@ -219,7 +220,7 @@ void SurfaceWrapper::setNormalGeometry(const QRectF &newNormalGeometry) if (m_normalGeometry == newNormalGeometry) return; m_normalGeometry = newNormalGeometry; - emit normalGeometryChanged(); + Q_EMIT normalGeometryChanged(); } QRectF SurfaceWrapper::maximizedGeometry() const @@ -244,7 +245,7 @@ void SurfaceWrapper::setMaximizedGeometry(const QRectF &newMaximizedGeometry) m_geometryAnimation->setProperty("targetGeometry", newMaximizedGeometry); } - emit maximizedGeometryChanged(); + Q_EMIT maximizedGeometryChanged(); } QRectF SurfaceWrapper::fullscreenGeometry() const @@ -269,7 +270,7 @@ void SurfaceWrapper::setFullscreenGeometry(const QRectF &newFullscreenGeometry) m_geometryAnimation->setProperty("targetGeometry", newFullscreenGeometry); } - emit fullscreenGeometryChanged(); + Q_EMIT fullscreenGeometryChanged(); updateClipRect(); } @@ -294,7 +295,7 @@ void SurfaceWrapper::setTilingGeometry(const QRectF &newTilingGeometry) resize(newTilingGeometry.size()); } - emit tilingGeometryChanged(); + Q_EMIT tilingGeometryChanged(); } bool SurfaceWrapper::positionAutomatic() const @@ -307,7 +308,7 @@ void SurfaceWrapper::setPositionAutomatic(bool newPositionAutomatic) if (m_positionAutomatic == newPositionAutomatic) return; m_positionAutomatic = newPositionAutomatic; - emit positionAutomaticChanged(); + Q_EMIT positionAutomaticChanged(); } void SurfaceWrapper::resetWidth() @@ -352,7 +353,7 @@ void SurfaceWrapper::setOwnsOutput(Output *newOwnsOutput) m_ownsOutput->addSurface(this); } - emit ownsOutputChanged(); + Q_EMIT ownsOutputChanged(); } void SurfaceWrapper::setOutputs(const QList &outputs) @@ -476,7 +477,7 @@ void SurfaceWrapper::setNoDecoration(bool newNoDecoration) } updateBoundingRect(); - emit noDecorationChanged(); + Q_EMIT noDecorationChanged(); } void SurfaceWrapper::updateTitleBar() @@ -501,7 +502,7 @@ void SurfaceWrapper::updateTitleBar() }); } - emit noTitleBarChanged(); + Q_EMIT noTitleBarChanged(); } void SurfaceWrapper::setBoundedRect(const QRectF &newBoundedRect) @@ -509,7 +510,7 @@ void SurfaceWrapper::setBoundedRect(const QRectF &newBoundedRect) if (m_boundedRect == newBoundedRect) return; m_boundedRect = newBoundedRect; - emit boundingRectChanged(); + Q_EMIT boundingRectChanged(); } void SurfaceWrapper::updateBoundingRect() @@ -681,7 +682,7 @@ void SurfaceWrapper::setRadius(qreal newRadius) if (qFuzzyCompare(m_radius, newRadius)) return; m_radius = newRadius; - emit radiusChanged(); + Q_EMIT radiusChanged(); } void SurfaceWrapper::requestMinimize() @@ -895,7 +896,7 @@ void SurfaceWrapper::setContainer(SurfaceContainer *newContainer) if (m_container == newContainer) return; m_container = newContainer; - emit containerChanged(); + Q_EMIT containerChanged(); } QQuickItem *SurfaceWrapper::titleBar() const @@ -924,7 +925,7 @@ void SurfaceWrapper::setVisibleDecoration(bool newVisibleDecoration) return; m_visibleDecoration = newVisibleDecoration; updateBoundingRect(); - emit visibleDecorationChanged(); + Q_EMIT visibleDecorationChanged(); } bool SurfaceWrapper::clipInOutput() const @@ -938,7 +939,7 @@ void SurfaceWrapper::setClipInOutput(bool newClipInOutput) return; m_clipInOutput = newClipInOutput; updateClipRect(); - emit clipInOutputChanged(); + Q_EMIT clipInOutputChanged(); } QRectF SurfaceWrapper::clipRect() const @@ -986,7 +987,7 @@ void SurfaceWrapper::setNoCornerRadius(bool newNoCornerRadius) if (m_noCornerRadius == newNoCornerRadius) return; m_noCornerRadius = newNoCornerRadius; - emit noCornerRadiusChanged(); + Q_EMIT noCornerRadiusChanged(); } int SurfaceWrapper::workspaceId() const @@ -999,7 +1000,7 @@ void SurfaceWrapper::setWorkspaceId(int newWorkspaceId) if (m_workspaceId == newWorkspaceId) return; - bool onAllWorkspaceHasChanged = m_workspaceId == 0 || newWorkspaceId == 0; + bool onAllWorkspaceHasChanged = (m_workspaceId == 0) != (newWorkspaceId == 0); m_workspaceId = newWorkspaceId; if (onAllWorkspaceHasChanged) diff --git a/waylib/examples/tinywl/surfacewrapper.h b/waylib/examples/tinywl/surfacewrapper.h index 0eaa11fddd..c87ab7ecf3 100644 --- a/waylib/examples/tinywl/surfacewrapper.h +++ b/waylib/examples/tinywl/surfacewrapper.h @@ -58,6 +58,7 @@ class SurfaceWrapper : public QQuickItem XWayland, Layer, InputPopup, + SessionLock }; Q_ENUM(Type) diff --git a/waylib/examples/tinywl/wallpaperprovider.h b/waylib/examples/tinywl/wallpaperprovider.h index 03991cdc15..631c97abdc 100644 --- a/waylib/examples/tinywl/wallpaperprovider.h +++ b/waylib/examples/tinywl/wallpaperprovider.h @@ -21,10 +21,10 @@ class WallpaperTextureFactory : public QQuickTextureFactory private: QImage im; QSize size; + WallpaperImageProvider *m_wallpaperProvider = nullptr; QString m_wallpaperId; bool m_textureExist = false; mutable QSGTexture *m_texture = nullptr; - WallpaperImageProvider *m_wallpaperProvider = nullptr; }; class WallpaperImageProvider : public QQuickImageProvider diff --git a/waylib/examples/tinywl/workspace.cpp b/waylib/examples/tinywl/workspace.cpp index a4d6896454..5bf446b880 100644 --- a/waylib/examples/tinywl/workspace.cpp +++ b/waylib/examples/tinywl/workspace.cpp @@ -19,6 +19,11 @@ Workspace::Workspace(SurfaceContainer *parent) createContainer(QStringLiteral("workspace-%1").arg(++workspaceGlobalIndex)); } +void Workspace::addSurface(SurfaceWrapper *surface) +{ + addSurface(surface, m_currentIndex); +} + void Workspace::addSurface(SurfaceWrapper *surface, int workspaceIndex) { doAddSurface(surface, true); @@ -106,7 +111,7 @@ void Workspace::removeContainer(int index) container->deleteLater(); if (oldCurrent != current) - emit currentChanged(); + Q_EMIT currentChanged(); } WorkspaceModel *Workspace::container(int index) const @@ -148,7 +153,7 @@ void Workspace::setCurrentIndex(int newCurrentIndex) m_models.at(i)->setVisible(i == m_currentIndex); } - emit currentChanged(); + Q_EMIT currentChanged(); } void Workspace::switchToNext() diff --git a/waylib/examples/tinywl/workspace.h b/waylib/examples/tinywl/workspace.h index 4df53dff3d..65273881ac 100644 --- a/waylib/examples/tinywl/workspace.h +++ b/waylib/examples/tinywl/workspace.h @@ -20,7 +20,8 @@ class Workspace : public SurfaceContainer public: explicit Workspace(SurfaceContainer *parent); - Q_INVOKABLE void addSurface(SurfaceWrapper *surface, int workspaceIndex = -1); + void addSurface(SurfaceWrapper *surface) override; + Q_INVOKABLE void addSurface(SurfaceWrapper *surface, int workspaceIndex); void removeSurface(SurfaceWrapper *surface) override; int containerIndexOfSurface(SurfaceWrapper *surface) const; @@ -39,7 +40,7 @@ class Workspace : public SurfaceContainer WorkspaceModel *current() const; void setCurrent(WorkspaceModel *container); -signals: +Q_SIGNALS: void currentChanged(); void countChanged(); diff --git a/waylib/flake.lock b/waylib/flake.lock index 85d6d9938b..5b9e338e42 100644 --- a/waylib/flake.lock +++ b/waylib/flake.lock @@ -49,38 +49,11 @@ "type": "github" } }, - "qwlroots": { - "inputs": { - "flake-utils": [ - "flake-utils" - ], - "nix-filter": [ - "nix-filter" - ], - "nixpkgs": [ - "nixpkgs" - ] - }, - "locked": { - "lastModified": 1752200508, - "narHash": "sha256-10z8yIGHuTEucUNSU/fz+d7hCvFE08MI1WR0+qbvz9c=", - "owner": "vioken", - "repo": "qwlroots", - "rev": "00b09f9047ac0eaf26757e8af3d31f35d22bbce3", - "type": "github" - }, - "original": { - "owner": "vioken", - "repo": "qwlroots", - "type": "github" - } - }, "root": { "inputs": { "flake-utils": "flake-utils", "nix-filter": "nix-filter", - "nixpkgs": "nixpkgs", - "qwlroots": "qwlroots" + "nixpkgs": "nixpkgs" } }, "systems": { diff --git a/waylib/flake.nix b/waylib/flake.nix index eaea5f8573..eb39f7abf5 100644 --- a/waylib/flake.nix +++ b/waylib/flake.nix @@ -5,26 +5,17 @@ nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable"; flake-utils.url = "github:numtide/flake-utils"; nix-filter.url = "github:numtide/nix-filter"; - qwlroots = { - url = "github:vioken/qwlroots"; - inputs.nixpkgs.follows = "nixpkgs"; - inputs.flake-utils.follows = "flake-utils"; - inputs.nix-filter.follows = "nix-filter"; - }; }; - outputs = { self, nixpkgs, flake-utils, nix-filter, qwlroots }@input: + outputs = { self, nixpkgs, flake-utils, nix-filter }@input: flake-utils.lib.eachSystem [ "x86_64-linux" "aarch64-linux" "riscv64-linux" ] (system: let pkgs = nixpkgs.legacyPackages.${system}; waylib = pkgs.qt6Packages.callPackage ./nix { - nix-filter = nix-filter.lib; - qwlroots = qwlroots.packages.${system}.qwlroots-qt6; - # for test - inherit pkgs waylib; + inherit pkgs waylib nix-filter; makeTest = import (pkgs.path + "/nixos/tests/make-test-python.nix"); }; in @@ -48,7 +39,6 @@ makeQmlpluginPath = pkgs.lib.makeSearchPathOutput "out" pkgs.qt6.qtbase.qtQmlPrefix; in '' echo "welcome to waylib" - echo "wlroots: $(pkg-config --modversion wlroots)" echo "wayland-server: $(pkg-config --modversion wayland-server)" #export QT_LOGGING_RULES="*.debug=true;qt.*.debug=false" #export MESA_DEBUG=1 diff --git a/waylib/nix/default.nix b/waylib/nix/default.nix index 737a6cf8a9..be032f5e93 100644 --- a/waylib/nix/default.nix +++ b/waylib/nix/default.nix @@ -7,13 +7,29 @@ , wrapQtAppsHook , qtbase , qtquick3d -, qwlroots , wayland , wayland-protocols , wlr-protocols , pixman , libdrm , libinput +, xkbcommon +, libseat +, libdisplay-info +, hwdata +, systemdLibs +, libxcb +, xcbutilwm +, xcbutil-errors +, libglvnd +, mesa +, vulkan-headers +, vulkan-loader +, glslang +, lcms2 +, libliftoff +, xwayland +, linuxHeaders , nixos-artwork # only for test @@ -25,9 +41,9 @@ stdenv.mkDerivation (finalAttrs: { pname = "waylib"; - version = "0.1.1"; + version = "0.6.13"; - src = nix-filter.filter { + src = nix-filter.lib.filter { root = ./..; exclude = [ @@ -36,7 +52,7 @@ stdenv.mkDerivation (finalAttrs: { "LICENSES" "README.md" "README.zh_CN.md" - (nix-filter.matchExt "nix") + (nix-filter.lib.matchExt "nix") ]; }; @@ -52,19 +68,35 @@ stdenv.mkDerivation (finalAttrs: { buildInputs = [ qtbase qtquick3d - qwlroots wayland wayland-protocols wlr-protocols pixman libdrm libinput + xkbcommon + libseat + libdisplay-info + hwdata + systemdLibs + libxcb + xcbutilwm + xcbutil-errors + libglvnd + mesa.dev + vulkan-headers + vulkan-loader + glslang + lcms2 + libliftoff + xwayland + linuxHeaders ]; cmakeBuildType = if debug then "Debug" else "Release"; cmakeFlags = [ - (lib.cmakeBool "INSTALL_TINYWL" true) + (lib.cmakeBool "BUILD_EXAMPLES" false) (lib.cmakeBool "ADDRESS_SANITIZER" debug) ]; diff --git a/waylib/qwlroots b/waylib/qwlroots deleted file mode 160000 index 00b09f9047..0000000000 --- a/waylib/qwlroots +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 00b09f9047ac0eaf26757e8af3d31f35d22bbce3 diff --git a/waylib/src/CMakeLists.txt b/waylib/src/CMakeLists.txt index 0afb17fec8..3f415d586e 100644 --- a/waylib/src/CMakeLists.txt +++ b/waylib/src/CMakeLists.txt @@ -1,8 +1,10 @@ set(CMAKE_INCLUDE_CURRENT_DIR ON) -install(FILES - cmake/WaylibConfig.cmake - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Waylib -) +if(TREELAND_INSTALL_DEV) + install(FILES + cmake/WaylibConfig.cmake + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Waylib + ) +endif() add_subdirectory(server) diff --git a/waylib/src/cmake/WaylibServerConfig.cmake.in b/waylib/src/cmake/WaylibServerConfig.cmake.in index f2fed1ac51..41605981cd 100644 --- a/waylib/src/cmake/WaylibServerConfig.cmake.in +++ b/waylib/src/cmake/WaylibServerConfig.cmake.in @@ -1,9 +1,33 @@ @PACKAGE_INIT@ include(CMakeFindDependencyMacro) -find_dependency(QWlroots) +find_dependency(Qt6 COMPONENTS Core Gui Quick) + +# The exported Waylib::waylib-wlroots target links pkg-config imported +# targets; make sure they exist for downstream consumers. +find_package(PkgConfig REQUIRED) +pkg_check_modules(WAYLAND_SERVER REQUIRED IMPORTED_TARGET wayland-server) +pkg_check_modules(LIBDRM REQUIRED IMPORTED_TARGET libdrm) +pkg_check_modules(XKBCOMMON REQUIRED IMPORTED_TARGET xkbcommon) +pkg_check_modules(PIXMAN REQUIRED IMPORTED_TARGET pixman-1) include(${CMAKE_CURRENT_LIST_DIR}/WaylibServerTargets.cmake) -check_required_components(WaylibServer) +# WaylibServer's public headers include , so consumers must be +# able to resolve the exported wlroots target (and its installed wlr/ +# include dir, carried on the target's INTERFACE_INCLUDE_DIRECTORIES). Fail +# loudly here instead of letting downstream link errors surface later. +# A Waylib built standalone against an installed waylib-wlroots exports +# PkgConfig::WLR_INSTALLED instead of Waylib::waylib-wlroots. +if(NOT TARGET Waylib::waylib-wlroots AND NOT TARGET PkgConfig::WLR_INSTALLED) + pkg_check_modules(WLR_INSTALLED QUIET IMPORTED_TARGET waylib-wlroots) +endif() +if(NOT TARGET Waylib::waylib-wlroots AND NOT TARGET PkgConfig::WLR_INSTALLED) + message(FATAL_ERROR + "WaylibServer: neither the exported target Waylib::waylib-wlroots " + "nor the pkg-config package waylib-wlroots is available. Reinstall " + "with the wlroots headers (include/wlr) and waylib-wlroots library " + "present.") +endif() +check_required_components(WaylibServer) diff --git a/waylib/src/server/CMakeLists.txt b/waylib/src/server/CMakeLists.txt index 16cdcac640..65204c45a8 100644 --- a/waylib/src/server/CMakeLists.txt +++ b/waylib/src/server/CMakeLists.txt @@ -9,10 +9,12 @@ set(WAYLIB_INCLUDE_INSTALL_DIR CACHE STRING "Install directory for waylib headers" ) -set(QT_COMPONENTS Core Gui Quick) -find_package(Qt6 COMPONENTS ${QT_COMPONENTS} REQUIRED) +if(Qt6_VERSION VERSION_GREATER_EQUAL 6.10) + find_package(Qt6 REQUIRED COMPONENTS GuiPrivate QuickPrivate) +endif() +find_package(Qt6 COMPONENTS Core Gui Quick REQUIRED) -qt_standard_project_setup(REQUIRES 6.6) +qt_standard_project_setup(REQUIRES 6.8) if(QT_KNOWN_POLICY_QTP0001) # this policy was introduced in Qt 6.5 qt_policy(SET QTP0001 NEW) @@ -21,7 +23,35 @@ endif() find_package(PkgConfig REQUIRED) pkg_search_module(LIBDRM REQUIRED IMPORTED_TARGET libdrm) -pkg_search_module(WLROOTS REQUIRED IMPORTED_TARGET wlroots-0.19) +set(WAYLIB_WLROOTS_INCLUDE_DIRS "") +set(WAYLIB_WLROOTS_PUBLIC_TARGET "") +if (NOT TARGET Wlroots::wlroots) + # Standalone Waylib build against an installed waylib-wlroots (built by + # the wlroots CMake scaffold, which also installs its headers and + # waylib-wlroots.pc). Resolve the library, its public dependencies and + # the wconfig.h feature metadata from that pkg-config file, so + # no monorepo layout is assumed. + find_package(PkgConfig REQUIRED) + pkg_check_modules(WLR_INSTALLED REQUIRED IMPORTED_TARGET waylib-wlroots) + add_library(Wlroots::wlroots ALIAS PkgConfig::WLR_INSTALLED) + set(WAYLIB_WLROOTS_PUBLIC_TARGET PkgConfig::WLR_INSTALLED) + foreach(_dir IN LISTS WLR_INSTALLED_INCLUDE_DIRS) + list(APPEND WAYLIB_WLROOTS_INCLUDE_DIRS "$") + endforeach() + pkg_get_variable(WLROOTS_VERSION waylib-wlroots wlroots_version) + pkg_get_variable(_waylib_wlroots_features waylib-wlroots wlroots_features) + foreach(_feature IN LISTS _waylib_wlroots_features) + set(WLR_HAVE_${_feature} 1) + endforeach() +else() + set(WAYLIB_WLROOTS_PUBLIC_TARGET Wlroots::wlroots) + set(_waylib_wlroots_include "${CMAKE_CURRENT_SOURCE_DIR}/../../../3rdparty/wlroots/include") + if (NOT EXISTS "${_waylib_wlroots_include}/wlr") + message(FATAL_ERROR "waylib uses vendored wlroots, but headers were not found at ${_waylib_wlroots_include}") + endif() + list(APPEND WAYLIB_WLROOTS_INCLUDE_DIRS "$") +endif() +set(WLROOTS_TARGET Wlroots::wlroots) pkg_search_module(WAYLAND REQUIRED IMPORTED_TARGET wayland-server) pkg_search_module(WAYLAND_PROTOCOLS REQUIRED IMPORTED_TARGET wayland-protocols) pkg_search_module(WLR_PROTOCOLS REQUIRED wlr-protocols) @@ -30,6 +60,8 @@ pkg_search_module(XKBCOMMON REQUIRED IMPORTED_TARGET xkbcommon) pkg_search_module(XCB REQUIRED IMPORTED_TARGET xcb) pkg_search_module(EGL REQUIRED IMPORTED_TARGET egl) +find_package(TreelandProtocols REQUIRED) + add_compile_definitions(WLR_PRIVATE=) ws_generate( @@ -60,7 +92,30 @@ ws_generate( color-management-v1-protocol ) +ws_generate( + server + wayland-protocols + staging/security-context/security-context-v1.xml + security-context-v1-protocol +) + +ws_generate( + server + wayland-protocols + stable/xdg-shell/xdg-shell.xml + xdg-shell-protocol +) + +ws_generate( + server + wayland-protocols + staging/ext-background-effect/ext-background-effect-v1.xml + ext-background-effect-v1-protocol +) + set(SOURCES + wayliblogging.cpp + kernel/wbackend.cpp kernel/wcursor.cpp kernel/winputdevice.cpp @@ -69,14 +124,16 @@ set(SOURCES kernel/wevent.cpp kernel/wserver.cpp kernel/wsurface.cpp + kernel/wsubsurface.cpp kernel/wtoplevelsurface.cpp + kernel/wwaylandresource.cpp - kernel/wtypes.cpp kernel/woutputlayout.cpp kernel/wxcursorimage.cpp kernel/wglobal.cpp + utils/wscoplistener.cpp kernel/wsocket.cpp qtquick/wsurfaceitem.cpp @@ -96,26 +153,34 @@ set(SOURCES qtquick/wxdgtoplevelsurfaceitem.cpp qtquick/wxdgpopupsurfaceitem.cpp qtquick/wlayersurfaceitem.cpp - qtquick/wxwaylandsurfaceitem.cpp qtquick/wqmlcreator.cpp qtquick/winputpopupsurfaceitem.cpp qtquick/wsgtextureprovider.cpp qtquick/wtextureproviderprovider.cpp + qtquick/wbufferitem.cpp qtquick/private/wquickcoordmapper.cpp qtquick/private/wquicksocketattached.cpp qtquick/private/wqmlhelper.cpp qtquick/private/wbufferrenderer.cpp qtquick/private/wrenderbuffernode.cpp + qtquick/scenegraph/wsgbatchrenderer.cpp + qtquick/scenegraph/wsgrhivisualizer.cpp + qtquick/scenegraph/wsgcontext.cpp ${WAYLAND_PROTOCOLS_OUTPUTDIR}/text-input-unstable-v1-protocol.c ${WAYLAND_PROTOCOLS_OUTPUTDIR}/text-input-unstable-v2-protocol.c ${WAYLAND_PROTOCOLS_OUTPUTDIR}/xdg-output-unstable-v1-protocol.c + ${WAYLAND_PROTOCOLS_OUTPUTDIR}/security-context-v1-protocol.c + ${WAYLAND_PROTOCOLS_OUTPUTDIR}/xdg-shell-protocol.c + ${WAYLAND_PROTOCOLS_OUTPUTDIR}/ext-background-effect-v1-protocol.c utils/wtools.cpp utils/wthreadutils.cpp utils/wimagebuffer.cpp utils/wcursorimage.cpp + utils/wextimagecapturesourcev1impl.cpp + utils/wbufferdumper.cpp platformplugin/qwlrootsintegration.cpp platformplugin/qwlrootscreen.cpp @@ -126,10 +191,9 @@ set(SOURCES protocols/wxdgshell.cpp protocols/wxdgsurface.cpp protocols/wxdgtoplevelsurface.cpp + protocols/wxdgtopleveltagmanager.cpp protocols/wxdgpopupsurface.cpp - protocols/wxwayland.cpp - protocols/wxwaylandsurface.cpp protocols/wlayersurface.cpp protocols/wforeigntoplevelv1.cpp protocols/wxdgoutput.cpp @@ -143,14 +207,33 @@ set(SOURCES protocols/private/wtextinputv3.cpp protocols/private/wvirtualkeyboardv1.cpp protocols/wcursorshapemanagerv1.cpp + protocols/wpointerconstraintsv1.cpp + protocols/wpointergesturesv1.cpp + protocols/wrelativepointermanagerv1.cpp protocols/woutputmanagerv1.cpp + protocols/wextworkspacemanagerv1.cpp protocols/wextforeigntoplevellistv1.cpp - - ${WAYLAND_PROTOCOLS_OUTPUTDIR}/text-input-unstable-v1-protocol.c + protocols/wxdgdialogmanagerv1.cpp + protocols/wsecuritycontextmanager.cpp + protocols/wsessionlockmanager.cpp + protocols/wsessionlock.cpp + protocols/wsessionlocksurface.cpp + protocols/wremotesubsurfacemanagerv1.cpp + + wlroots_extra/wlr_ext_background_effect_v1.c ) set(HEADERS + wayliblogging.h + kernel/wglobal.h + kernel/wwaylandresource.h + kernel/wlr_all.h + kernel/wlr_fwd.h + kernel/wpointer.h + utils/wscoplistener.h + utils/wscopedvalue.h + utils/wlogging.h kernel/wbackend.h kernel/wcursor.h kernel/winputdevice.h @@ -159,7 +242,7 @@ set(HEADERS kernel/wevent.h kernel/wserver.h kernel/wsurface.h - kernel/wtypes.h + kernel/wsubsurface.h kernel/woutputlayout.h kernel/wxcursorimage.h kernel/wsocket.h @@ -175,6 +258,7 @@ set(HEADERS kernel/WEvent kernel/WInputEvent kernel/WSurface + kernel/WSubsurface qtquick/wsurfaceitem.h qtquick/WSurfaceItem @@ -194,11 +278,11 @@ set(HEADERS qtquick/wxdgtoplevelsurfaceitem.h qtquick/wxdgpopupsurfaceitem.h qtquick/wlayersurfaceitem.h - qtquick/wxwaylandsurfaceitem.h qtquick/winputpopupsurfaceitem.h qtquick/wqmlcreator.h qtquick/wsgtextureprovider.h qtquick/wtextureproviderprovider.h + qtquick/wbufferitem.h utils/wtools.h utils/wthreadutils.h @@ -206,14 +290,18 @@ set(HEADERS utils/wimagebuffer.h utils/wcursorimage.h utils/WCursorImage - utils/wwrappointer.h - utils/WWrapPointer + utils/wextimagecapturesourcev1impl.h + utils/wbufferdumper.h + utils/WBufferDumper + utils/wcontainerof.h + utils/WContainerOf protocols/wxdgshell.h protocols/WXdgShell protocols/wxdgsurface.h protocols/WXdgSurface protocols/wxdgtoplevelsurface.h + protocols/wxdgtopleveltagmanager.h protocols/wxdgpopupsurface.h protocols/wlayersurface.h protocols/wxdgdecorationmanager.h @@ -229,15 +317,27 @@ set(HEADERS protocols/WInputPopupSurface protocols/wcursorshapemanagerv1.h protocols/WCursorShapeManagerV1 + protocols/wpointerconstraintsv1.h + protocols/WPointerConstraintsV1 + protocols/wremotesubsurfacemanagerv1.h + protocols/wpointergesturesv1.h + protocols/wrelativepointermanagerv1.h + protocols/WRelativePointerManagerV1 protocols/woutputmanagerv1.h protocols/WOutputManagerV1 protocols/wlayershell.h protocols/WLayerShell - protocols/wxwayland.h - protocols/WXWayland - protocols/wxwaylandsurface.h - protocols/WXWaylandSurface + protocols/wextworkspacemanagerv1.h protocols/wextforeigntoplevellistv1.h + protocols/wxdgdialogmanagerv1.h + protocols/wsecuritycontextmanager.h + protocols/wsessionlockmanager.h + protocols/WSessionLockManager + protocols/wsessionlock.h + protocols/WSessionLock + protocols/wsessionlocksurface.h + protocols/WSessionLockSurface + wlroots_extra/wlr_ext_background_effect_v1.h ) set(PRIVATE_HEADERS @@ -247,7 +347,10 @@ set(PRIVATE_HEADERS platformplugin/qwlrootscursor.h platformplugin/types.h kernel/private/wglobal_p.h + kernel/private/wwaylandresource_p.h kernel/private/wsurface_p.h + kernel/private/wsubsurface_p.h + kernel/private/wprivateaccessor_p.h qtquick/private/woutputviewport_p.h qtquick/private/wquickcoordmapper_p.h qtquick/private/woutputitem_p.h @@ -258,10 +361,15 @@ set(PRIVATE_HEADERS qtquick/private/wbufferrenderer_p.h qtquick/private/wrenderbuffernode_p.h qtquick/private/wsurfaceitem_p.h + qtquick/scenegraph/wsgbatchrenderer_p.h + qtquick/scenegraph/wsgrhivisualizer_p.h + qtquick/scenegraph/wsgcontext_p.h ${WAYLAND_PROTOCOLS_OUTPUTDIR}/text-input-unstable-v1-protocol.h ${WAYLAND_PROTOCOLS_OUTPUTDIR}/text-input-unstable-v2-protocol.h ${WAYLAND_PROTOCOLS_OUTPUTDIR}/xdg-output-unstable-v1-protocol.h + ${WAYLAND_PROTOCOLS_OUTPUTDIR}/xdg-shell-protocol.h + ${WAYLAND_PROTOCOLS_OUTPUTDIR}/ext-background-effect-v1-protocol.h protocols/private/winputmethodv2_p.h protocols/private/wtextinput_p.h @@ -269,27 +377,36 @@ set(PRIVATE_HEADERS protocols/private/wtextinputv2_p.h protocols/private/wtextinputv3_p.h protocols/private/wvirtualkeyboardv1_p.h + protocols/private/wsecuritycontextmanager_p.h ) if(NOT DISABLE_XWAYLAND) list(APPEND SOURCES protocols/wxwayland.cpp protocols/wxwaylandsurface.cpp + qtquick/wxwaylandsurfaceitem.cpp ) list(APPEND HEADERS protocols/wxwayland.h + protocols/WXWayland protocols/wxwaylandsurface.h + protocols/WXWaylandSurface + qtquick/wxwaylandsurfaceitem.h ) endif() -add_library(${TARGET} - SHARED - ${SOURCES} +add_library(${TARGET} SHARED ${SOURCES}) +target_compile_definitions(${TARGET} PUBLIC + $<$:DISABLE_XWAYLAND> ) - add_library(Waylib::WaylibServer ALIAS ${TARGET}) +waylib_generate_qtwayland_server_protocol(${TARGET} + PROTOCOL ${TREELAND_PROTOCOLS_DATA_DIR}/treeland-remote-subsurface-unstable-v1.xml + BASENAME treeland-remote-subsurface-unstable-v1 +) + qt_add_qml_module(${TARGET} URI Waylib.Server VERSION "1.0" # Qt bug: The major version must be larger than 0 @@ -312,31 +429,42 @@ set_target_properties(${TARGET} SOVERSION ${PROJECT_VERSION_MAJOR} EXPORT_NAME WaylibServer PUBLIC_HEADER "${HEADERS}" - # PRIVATE_HEADER "${PRIVATE_HEADERS}" - # CMake Warning has PRIVATE_HEADER files but no PRIVATE_HEADER DESTINATION + # PRIVATE_HEADER "${PRIVATE_HEADERS}" + # CMake Warning has PRIVATE_HEADER files but no PRIVATE_HEADER DESTINATION + POSITION_INDEPENDENT_CODE ON ) -set(QT_LIBRARIES "") -foreach(temp ${QT_COMPONENTS}) - list(APPEND QT_LIBRARIES "Qt6::${temp}") -endforeach() +# Sanity check: the wlroots CMake export must be present. +if(NOT DEFINED WLROOTS_VERSION) + message(FATAL_ERROR "WLROOTS_VERSION not set; wlroots CMake export missing") +endif() +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/wconfig.h.in ${CMAKE_CURRENT_BINARY_DIR}/wconfig.h @ONLY) +target_include_directories(${TARGET} PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) +target_include_directories(${TARGET} INTERFACE $) +# Public headers (wglobal.h etc.) include Qt types, so the Qt targets must +# propagate to consumers via the exported Waylib::WaylibServer target. target_link_libraries(${TARGET} + PUBLIC + Qt6::Core + Qt6::Gui + Qt6::Quick PRIVATE - ${QT_LIBRARIES} - PkgConfig::WLROOTS - PkgConfig::LIBDRM - PkgConfig::WAYLAND - PkgConfig::WAYLAND_PROTOCOLS - PkgConfig::PIXMAN - PkgConfig::XKBCOMMON - PkgConfig::XCB - PkgConfig::EGL + Qt6::GuiPrivate + Qt6::QuickPrivate + ${WLROOTS_TARGET} + PkgConfig::LIBDRM + PkgConfig::WAYLAND + PkgConfig::WAYLAND_PROTOCOLS + PkgConfig::PIXMAN + PkgConfig::XKBCOMMON + PkgConfig::XCB + PkgConfig::EGL ) target_link_libraries(${TARGET} PUBLIC - QWlroots::QWlroots + ${WAYLIB_WLROOTS_PUBLIC_TARGET} ) set(CMAKE_INCLUDE_CURRENT_DIR ON) @@ -349,8 +477,12 @@ target_include_directories(${TARGET} $ $ $ + ${WAYLIB_WLROOTS_INCLUDE_DIRS} + $ $ PRIVATE + $ + $ ${Qt6Gui_PRIVATE_INCLUDE_DIRS} ${Qt6Quick_PRIVATE_INCLUDE_DIRS} ${Qt6EglSupport_PRIVATE_INCLUDE_DIRS} @@ -363,49 +495,93 @@ target_link_directories(${TARGET} $ ) -if (WAYLIB_USE_PERCOMPILE_HEADERS) - target_precompile_headers(${TARGET} - PRIVATE - "$<$:pch/pch.hxx>" - ) -endif() +# Install the runtime library (versioned .so.*) only; the .so dev +# symlink, exported targets, headers and pkg-config file are installed +# separately when TREELAND_INSTALL_DEV is ON. install(TARGETS ${TARGET} - EXPORT - WaylibServerTargets LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - PUBLIC_HEADER - COMPONENT Development - DESTINATION ${WAYLIB_INCLUDE_INSTALL_DIR} + NAMELINK_SKIP ) -configure_package_config_file( - "${CMAKE_CURRENT_SOURCE_DIR}/../cmake/WaylibServerConfig.cmake.in" - "${CMAKE_CURRENT_BINARY_DIR}/WaylibServerConfig.cmake" - INSTALL_DESTINATION ${WAYLIB_CMAKE_INSTALL_DIR} -) +if(TREELAND_INSTALL_DEV) + install(TARGETS ${TARGET} + EXPORT + WaylibServerTargets + LIBRARY + DESTINATION ${CMAKE_INSTALL_LIBDIR} + NAMELINK_ONLY + PUBLIC_HEADER + COMPONENT Development + DESTINATION ${WAYLIB_INCLUDE_INSTALL_DIR} + ) -write_basic_package_version_file( - "${CMAKE_CURRENT_BINARY_DIR}/WaylibServerConfigVersion.cmake" - VERSION ${DTK_VERSION} - COMPATIBILITY SameMinorVersion -) + # Generated config header (wconfig.h) is part of the public API surface + # (included by wglobal.h) and must ship with the installed headers. + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/wconfig.h + DESTINATION ${WAYLIB_INCLUDE_INSTALL_DIR} + ) -install(FILES - ${CMAKE_CURRENT_BINARY_DIR}/WaylibServerConfig.cmake - ${CMAKE_CURRENT_BINARY_DIR}/WaylibServerConfigVersion.cmake - DESTINATION ${WAYLIB_CMAKE_INSTALL_DIR} -) + # Public headers use Q_MOC_INCLUDE/Q_PRIVATE_SLOT referencing kernel + # private headers (e.g. wserver.h -> private/wserver_p.h), and Treeland + # consumes kernel private API (e.g. WToplevelSurfacePrivate); install the + # whole private directory so installed consumers can compile and moc. + install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/kernel/private + DESTINATION ${WAYLIB_INCLUDE_INSTALL_DIR} + FILES_MATCHING PATTERN "*.h") + + # Compositors explicitly assemble the managers passed to WInputMethodHelper. + install(FILES + protocols/private/winputmethodv2_p.h + protocols/private/wtextinput_p.h + protocols/private/wtextinputv1_p.h + protocols/private/wtextinputv2_p.h + protocols/private/wtextinputv3_p.h + protocols/private/wvirtualkeyboardv1_p.h + DESTINATION ${WAYLIB_INCLUDE_INSTALL_DIR} + ) -install( - EXPORT WaylibServerTargets - FILE WaylibServerTargets.cmake - DESTINATION ${WAYLIB_CMAKE_INSTALL_DIR} - NAMESPACE Waylib:: -) + # Install QML module generated targets separately to avoid dependency issues + # This works around the Qt CMake QML module export issue + get_directory_property(all_targets BUILDSYSTEM_TARGETS) + foreach(target_name ${all_targets}) + if(target_name MATCHES "^${TARGET}_resources_") + install(TARGETS ${target_name} + EXPORT WaylibServerTargets + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ) + endif() + endforeach() + + configure_package_config_file( + "${CMAKE_CURRENT_SOURCE_DIR}/../cmake/WaylibServerConfig.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/WaylibServerConfig.cmake" + INSTALL_DESTINATION ${WAYLIB_CMAKE_INSTALL_DIR} + ) -include(${PROJECT_SOURCE_DIR}/cmake/Helpers.cmake) -add_pkgconfig_module(${TARGET} ${TARGET} ${WAYLIB_INCLUDE_INSTALL_DIR} - "qwlroots, Qt6Gui, Qt6Quick" -) + write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/WaylibServerConfigVersion.cmake" + VERSION ${PROJECT_VERSION} + COMPATIBILITY SameMinorVersion + ) + + install(FILES + ${CMAKE_CURRENT_BINARY_DIR}/WaylibServerConfig.cmake + ${CMAKE_CURRENT_BINARY_DIR}/WaylibServerConfigVersion.cmake + DESTINATION ${WAYLIB_CMAKE_INSTALL_DIR} + ) + + install( + EXPORT WaylibServerTargets + FILE WaylibServerTargets.cmake + DESTINATION ${WAYLIB_CMAKE_INSTALL_DIR} + NAMESPACE Waylib:: + ) + + include(${PROJECT_SOURCE_DIR}/cmake/Helpers.cmake) + add_pkgconfig_module(${TARGET} ${TARGET} ${WAYLIB_INCLUDE_INSTALL_DIR} + "waylib-wlroots, Qt6Gui, Qt6Quick" + ) +endif() diff --git a/waylib/src/server/cmake/wconfig.h.in b/waylib/src/server/cmake/wconfig.h.in new file mode 100644 index 0000000000..40f089eabc --- /dev/null +++ b/waylib/src/server/cmake/wconfig.h.in @@ -0,0 +1,16 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +// Generated from wlroots CMake export; do not edit. + +#pragma once + +#cmakedefine WLR_HAVE_DRM_BACKEND @WLR_HAVE_DRM_BACKEND@ +#cmakedefine WLR_HAVE_X11_BACKEND @WLR_HAVE_X11_BACKEND@ +#cmakedefine WLR_HAVE_LIBINPUT_BACKEND @WLR_HAVE_LIBINPUT_BACKEND@ +#cmakedefine WLR_HAVE_XWAYLAND @WLR_HAVE_XWAYLAND@ +#cmakedefine WLR_HAVE_GLES2_RENDERER @WLR_HAVE_GLES2_RENDERER@ +#cmakedefine WLR_HAVE_VULKAN_RENDERER @WLR_HAVE_VULKAN_RENDERER@ +#cmakedefine WLR_HAVE_GBM_ALLOCATOR @WLR_HAVE_GBM_ALLOCATOR@ +#cmakedefine WLR_HAVE_SESSION @WLR_HAVE_SESSION@ +#cmakedefine WLR_HAVE_COLOR_MANAGEMENT @WLR_HAVE_COLOR_MANAGEMENT@ +#cmakedefine WLR_HAVE_UDMABUF_ALLOCATOR @WLR_HAVE_UDMABUF_ALLOCATOR@ diff --git a/waylib/src/server/kernel/WSubsurface b/waylib/src/server/kernel/WSubsurface new file mode 100644 index 0000000000..d1305471a6 --- /dev/null +++ b/waylib/src/server/kernel/WSubsurface @@ -0,0 +1 @@ +#include "wsubsurface.h" diff --git a/waylib/src/server/kernel/private/wcursor_p.h b/waylib/src/server/kernel/private/wcursor_p.h index 01301df52f..cced163a32 100644 --- a/waylib/src/server/kernel/private/wcursor_p.h +++ b/waylib/src/server/kernel/private/wcursor_p.h @@ -1,50 +1,30 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include "wcursor.h" #include "private/wglobal_p.h" +#include "wpointer.h" +#include "wscoplistener.h" -#include +#include #include #include -QW_BEGIN_NAMESPACE -class qw_pointer; -class qw_surface; -QW_END_NAMESPACE - -struct wlr_pointer_motion_event; -struct wlr_pointer_motion_absolute_event; -struct wlr_pointer_button_event; -struct wlr_pointer_axis_event; -struct wlr_pointer_swipe_begin_event; -struct wlr_pointer_swipe_update_event; -struct wlr_pointer_swipe_end_event; -struct wlr_pointer_pinch_begin_event; -struct wlr_pointer_pinch_update_event; -struct wlr_pointer_pinch_end_event; -struct wlr_pointer_hold_begin_event; -struct wlr_pointer_hold_end_event; -struct wlr_cursor; -struct wlr_touch_down_event; -struct wlr_touch_up_event; -struct wlr_touch_motion_event; -struct wlr_touch_cancel_event; - WAYLIB_SERVER_BEGIN_NAMESPACE -class Q_DECL_HIDDEN WCursorPrivate : public WWrapObjectPrivate +class Q_DECL_HIDDEN WCursorPrivate : public WObjectPrivate { public: WCursorPrivate(WCursor *qq); ~WCursorPrivate(); - WWRAP_HANDLE_FUNCTIONS(QW_NAMESPACE::qw_cursor, wlr_cursor) - - void instantRelease() override; + inline wlr_cursor *handle() const { + return m_handle.get(); + } void sendEnterEvent(WInputDevice *device); void sendLeaveEvent(WInputDevice *device); @@ -71,12 +51,24 @@ class Q_DECL_HIDDEN WCursorPrivate : public WWrapObjectPrivate // end slot function void connect(); - void processCursorMotion(QW_NAMESPACE::qw_pointer *device, uint32_t time); + void processCursorMotion(wlr_input_device *device, uint32_t time); + + // Returns true when processCursorMotion should be skipped: + // No constraint/non-pointer: return false (caller proceeds). + // LOCKED: warp to lockedWarpTarget, return true. + // CONFINED: clamp/block, return true if blocked. + bool applyPointerConstraint(wlr_input_device *device, + const QPointF &oldPos, + const QPointF &delta); + + // Re-anchor lockedWarpTarget to the current cursor position. + // Called once at lock activation from setActivePointerConstraint(). + void updateLockedWarpTarget(); W_DECLARE_PUBLIC(WCursor) - QW_NAMESPACE::qw_xcursor_manager *xcursor_manager = nullptr; QCursor cursor; + QCursor overrideCursor; WSeat *seat = nullptr; QPointer eventWindow; @@ -88,6 +80,19 @@ class Q_DECL_HIDDEN WCursorPrivate : public WWrapObjectPrivate Qt::MouseButton button = Qt::NoButton; QPointF lastPressedOrTouchDownPosition; bool visible = true; + // Active constraint enforced on this cursor; set via + // WCursor::setActivePointerConstraint(). nullptr when unconstrained. + wlr_pointer_constraint_v1 *activeConstraint = nullptr; + // Anchor the cursor is warped back to on every motion while a locked + // constraint is active, preventing physical movement from accumulating. + QPointF lockedWarpTarget; + double scrollFactor = 1.0; + +private: + // Owning handle: the cursor is created here and released via + // wlr_cursor_destroy() in ~WCursorPrivate; WUniquePointer additionally + // auto-nulls on native destroy, preventing a double-free. + WUniquePointer m_handle; }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/private/wglobal_p.h b/waylib/src/server/kernel/private/wglobal_p.h index e8ab7b8a37..068c36ba99 100644 --- a/waylib/src/server/kernel/private/wglobal_p.h +++ b/waylib/src/server/kernel/private/wglobal_p.h @@ -1,22 +1,34 @@ -// Copyright (C) 2024 JiDe Zhang . +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include "wglobal.h" -#include -#include WAYLIB_SERVER_BEGIN_NAMESPACE -class Q_DECL_HIDDEN WObjectPrivate +class WScopedListenerList; + +class WAYLIB_SERVER_EXPORT WObjectPrivate { public: static WObjectPrivate *get(WObject *qq); + // Cross-object listener bookkeeping used by WObject::listeners(owner), + // removeListeners(), and teardown(). Kept here so WObject's public + // surface does not expose the internal graph edges. + void registerListenerTarget(WObject *target); + void unregisterListenerTarget(WObject *target); + bool removeListenersInternal(WObject *owner); + virtual ~WObjectPrivate(); - virtual wl_client *waylandClient() const { - return nullptr; - } + + // Live listener graph; public so unit tests can assert ownership edges + // without friending WObjectPrivate. + // WScopedListenerList instances created by listeners()/listeners(owner); + // released by teardown() or removeListeners(). ~WObject requires empty. + QList> attachedListenerLists; + // Targets this WObject registered on via other->listeners(this). + QList attachedListenerTargets; protected: WObjectPrivate(WObject *qq); @@ -32,38 +44,7 @@ class Q_DECL_HIDDEN WObjectPrivate QList> attachedDatas; W_DECLARE_PUBLIC(WObject) -}; - -class Q_DECL_HIDDEN WWrapObjectPrivate : public WObjectPrivate -{ -public: - WWrapObjectPrivate(WWrapObject *q); - ~WWrapObjectPrivate(); - - template - inline Handle *handle() const { - return qobject_cast(m_handle.get()); - } -protected: - W_DECLARE_PUBLIC(WWrapObject) - - void initHandle(QW_NAMESPACE::qw_object_basic *handle); - void invalidate(); - virtual void instantRelease() {} - - QList connectionsWithHandle; - QPointer m_handle; - uint invalidated:1; }; -#define WWRAP_HANDLE_FUNCTIONS(QW, WLR) \ -inline QW *handle() const { \ - return WWrapObjectPrivate::handle(); \ -} \ -\ -inline WLR *nativeHandle() const { \ - return handle()->handle(); \ -} - WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/private/woutputlayout_p.h b/waylib/src/server/kernel/private/woutputlayout_p.h index 7657697f39..70d80b62c6 100644 --- a/waylib/src/server/kernel/private/woutputlayout_p.h +++ b/waylib/src/server/kernel/private/woutputlayout_p.h @@ -1,35 +1,36 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "woutputlayout.h" #include "wglobal_p.h" -#include +#include WAYLIB_SERVER_BEGIN_NAMESPACE -class Q_DECL_HIDDEN WOutputLayoutPrivate : public WWrapObjectPrivate +class Q_DECL_HIDDEN WOutputLayoutPrivate : public WObjectPrivate { public: WOutputLayoutPrivate(WOutputLayout *qq); ~WOutputLayoutPrivate(); - WWRAP_HANDLE_FUNCTIONS(qw_output_layout, wlr_output_layout) + inline wlr_output_layout *handle() const { + return m_handle; + } void doAdd(WOutput *output); - void instantRelease() override { - if (handle()) - handle()->set_data(nullptr, nullptr); - } - W_DECLARE_PUBLIC(WOutputLayout) QList outputs; void updateImplicitSize(); + int implicitWidth { 0 }; int implicitHeight { 0 }; + +private: + wlr_output_layout *m_handle = nullptr; }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/private/wprivateaccessor_p.h b/waylib/src/server/kernel/private/wprivateaccessor_p.h new file mode 100644 index 0000000000..0e3904c45e --- /dev/null +++ b/waylib/src/server/kernel/private/wprivateaccessor_p.h @@ -0,0 +1,199 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +// Private member accessor using the explicit template instantiation technique. +// +// C++ Standard [temp.explicit]/12 states: +// "The usual access checking rules do not apply to names used to +// specify explicit instantiation definitions." +// +// This allows passing pointers to private/protected data members and +// member functions as template arguments in explicit instantiations, +// bypassing normal access control — without modifying the class definition +// and without the UB caused by "#define private public". +// +// Usage: +// // 1. Declare a tag and register the member pointer (at namespace scope): +// W_DECLARE_PRIVATE_MEMBER(MyTag, SomeClass, m_secret, int) +// +// // 2. Access the member: +// int &val = W_PRIVATE_MEMBER(obj, MyTag{}); +// // or for a pointer: +// int &val = W_PRIVATE_MEMBER(*ptr, MyTag{}); +// +// For member functions: +// W_DECLARE_PRIVATE_METHOD(MyFuncTag, SomeClass, privateFunc, void, int, float) +// W_PRIVATE_CALL(obj, MyFuncTag{}, 42, 3.14f); +// +// Limitations: +// - Does NOT work for bitfield members (C++ forbids pointer-to-member of a bitfield) +// - Does NOT work for constructors/destructors +// - The declaration must appear at namespace scope (not inside a function) + +// GCC warns about a non-template friend inside a class template when the return +// type is template-dependent. This is intentional: each explicit instantiation +// of W_PrivateAccessorImpl injects a unique non-template overload of get(Tag) via ADL. +// The pattern is correct; suppress the warning. +QT_WARNING_PUSH +QT_WARNING_DISABLE_GCC("-Wnon-template-friend") + +// NOTE: These helper structs must be in the SAME namespace as the Tag structs +// (global namespace, since the macros expand at file scope). If they were in a +// sub-namespace, the friend definition would create a different function than +// the friend declaration in the Tag struct, causing undefined-reference errors. + +// Stores the member pointer type for a given Tag and declares the friend getter. +template +struct W_PrivateAccessor { + using MemberPtr = typename Tag::MemberPtr; + friend constexpr MemberPtr get(Tag) noexcept; +}; + +// Concrete accessor — the explicit instantiation of this (with a private member +// pointer) is what legally bypasses access control. +template +struct W_PrivateAccessorImpl : W_PrivateAccessor { + friend constexpr typename Tag::MemberPtr get(Tag) noexcept { return Ptr; } +}; + +QT_WARNING_POP + +// --------------------------------------------------------------------------- +// Declare access to a non-static data member. +// TagName – unique tag struct name (use a descriptive name) +// ClassName – the class that owns the member +// Member – the private member name +// MemberType – the type of that member +// --------------------------------------------------------------------------- +#define W_DECLARE_PRIVATE_MEMBER(TagName, ClassName, Member, MemberType) \ + struct TagName { \ + using MemberPtr = MemberType ClassName::*; \ + friend constexpr MemberPtr get(TagName) noexcept; \ + }; \ + template struct W_PrivateAccessorImpl + +// --------------------------------------------------------------------------- +// Declare access to a non-static member function. +// TagName – unique tag struct name +// ClassName – the class that owns the method +// MethodName – the private method name +// RetType – return type of the method +// ... – parameter types (may be empty) +// --------------------------------------------------------------------------- +#define W_DECLARE_PRIVATE_METHOD(TagName, ClassName, MethodName, RetType, ...) \ + struct TagName { \ + using MemberPtr = RetType (ClassName::*)(__VA_ARGS__); \ + friend constexpr MemberPtr get(TagName) noexcept; \ + }; \ + template struct W_PrivateAccessorImpl + +// --------------------------------------------------------------------------- +// Declare access to a const non-static member function. +// --------------------------------------------------------------------------- +#define W_DECLARE_PRIVATE_CONST_METHOD(TagName, ClassName, MethodName, RetType, ...) \ + struct TagName { \ + using MemberPtr = RetType (ClassName::*)(__VA_ARGS__) const; \ + friend constexpr MemberPtr get(TagName) noexcept; \ + }; \ + template struct W_PrivateAccessorImpl + +// --------------------------------------------------------------------------- +// Declare access to a static data member (pointer, not pointer-to-member). +// TagName – unique tag struct name +// ClassName – the class that owns the static member +// Member – the private static member name +// MemberType – the type of that static member +// --------------------------------------------------------------------------- +#define W_DECLARE_PRIVATE_STATIC_MEMBER(TagName, ClassName, Member, MemberType) \ + struct TagName { \ + using MemberPtr = MemberType*; \ + friend constexpr MemberPtr get(TagName) noexcept; \ + }; \ + template \ + struct TagName##_Impl : TagName { \ + friend constexpr MemberType* get(TagName) noexcept { return Ptr; } \ + }; \ + template struct TagName##_Impl<&ClassName::Member> + +// Access a private non-static data member — returns a reference. +#define W_PRIVATE_MEMBER(obj, tag) ((obj).*get(tag)) + +// Call a private non-static member function. +#define W_PRIVATE_CALL(obj, tag, ...) ((obj).*get(tag))(__VA_ARGS__) + +// Access a private static data member — returns a reference. +#define W_PRIVATE_STATIC_MEMBER(tag) (*get(tag)) + +// --------------------------------------------------------------------------- +// Bit-field storage accessor. +// +// C++ forbids forming a pointer-to-member for a bit-field, so +// W_DECLARE_PRIVATE_MEMBER cannot be used directly. Instead, this macro +// provides memory-level access to the storage unit (the uint/unsigned that +// contains the bit fields) by computing its offset from the last non-bit-field +// private member that immediately precedes the bit-field block. +// +// Parameters: +// TagName – unique tag name (creates TagName and TagName_Bits helpers) +// ClassName – the class that owns the members +// PrevMember – the last non-bit-field private member before the bit fields +// PrevMemberType – type of PrevMember +// BfStorageType – underlying integral type of the bit-field storage unit +// (e.g. `uint` for `uint flag : 1;`) +// +// Bit ordering (GCC/Clang, little-endian): +// The first-declared bit field occupies bit 0 (LSB) of the storage unit, +// subsequent declarations occupy consecutive higher bits. +// +// Usage (at namespace scope in the .cpp file): +// W_DECLARE_PRIVATE_BITFIELD(FooTag, Foo, m_last_regular, SomeType, uint) +// +// // Access the preceding member directly (equivalent to W_DECLARE_PRIVATE_MEMBER): +// SomeType &prev = W_PRIVATE_MEMBER(obj, FooTag{}); +// +// // Read bit N (0-based by declaration order): +// bool v = W_PRIVATE_BF_GET(obj, FooTag, N); +// +// // Write bit N: +// W_PRIVATE_BF_SET(obj, FooTag, N, true_or_false); +// --------------------------------------------------------------------------- +#define W_DECLARE_PRIVATE_BITFIELD(TagName, ClassName, PrevMember, PrevMemberType, BfStorageType) \ + struct TagName { \ + using MemberPtr = PrevMemberType ClassName::*; \ + friend constexpr MemberPtr get(TagName) noexcept; \ + }; \ + template struct W_PrivateAccessorImpl; \ + struct TagName##_bf_layout_mirror { PrevMemberType prev; BfStorageType storage; }; \ + struct TagName##_Bits { \ + static constexpr std::size_t kOffset = \ + __builtin_offsetof(TagName##_bf_layout_mirror, storage) - \ + __builtin_offsetof(TagName##_bf_layout_mirror, prev); \ + static BfStorageType *storagePtr(ClassName *obj) noexcept { \ + PrevMemberType &prev_ref = (*obj).*get(TagName{}); \ + return reinterpret_cast( \ + reinterpret_cast(&prev_ref) + kOffset); \ + } \ + static const BfStorageType *storagePtr(const ClassName *obj) noexcept { \ + return storagePtr(const_cast(obj)); \ + } \ + static bool getBit(const ClassName *obj, unsigned bit) noexcept { \ + return (*storagePtr(obj) >> bit) & BfStorageType{1}; \ + } \ + static void setBit(ClassName *obj, unsigned bit, bool val) noexcept { \ + BfStorageType *p = storagePtr(obj); \ + if (val) *p |= (BfStorageType{1} << bit); \ + else *p &= ~(BfStorageType{1} << bit); \ + } \ + } + +// Read bit `bit_pos` (0 = first-declared) from the bit-field storage. +#define W_PRIVATE_BF_GET(obj, TagName, bit_pos) \ + TagName##_Bits::getBit(&(obj), (bit_pos)) + +// Write `val` (bool) to bit `bit_pos` of the bit-field storage. +#define W_PRIVATE_BF_SET(obj, TagName, bit_pos, val) \ + TagName##_Bits::setBit(&(obj), (bit_pos), (val)) diff --git a/waylib/src/server/kernel/private/wserver_p.h b/waylib/src/server/kernel/private/wserver_p.h index 81173be271..c9248069ef 100644 --- a/waylib/src/server/kernel/private/wserver_p.h +++ b/waylib/src/server/kernel/private/wserver_p.h @@ -1,22 +1,25 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include "wserver.h" #include "wglobal_p.h" +#include "wpointer.h" struct wl_event_loop; +struct wl_display; +void wl_display_destroy(struct wl_display *display); QT_BEGIN_NAMESPACE class QSocketNotifier; QT_END_NAMESPACE -QW_BEGIN_NAMESPACE -class qw_display; -QW_END_NAMESPACE - WAYLIB_SERVER_BEGIN_NAMESPACE +template <> +struct WlrObjectTraits { + static void destroy(wl_display *display) { wl_display_destroy(display); } +}; class Q_DECL_HIDDEN WServerPrivate : public WObjectPrivate { @@ -28,6 +31,9 @@ class Q_DECL_HIDDEN WServerPrivate : public WObjectPrivate void stop(); void initSocket(WSocket *socketServer); + void processWaylandEvents(); + void onAboutToBlock(); + void onAwake(); W_DECLARE_PUBLIC(WServer) std::unique_ptr sockNot; @@ -35,13 +41,16 @@ class Q_DECL_HIDDEN WServerPrivate : public WObjectPrivate QVector interfaceList; WServerInterface *pendingInterface = nullptr; - std::unique_ptr display; + WUniquePointer display; wl_event_loop *loop = nullptr; QList sockets; GlobalFilterFunc globalFilterFunc = nullptr; void *globalFilterFuncData = nullptr; + + bool isProcessingEvents = false; + void safeFlushClients(); }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/private/wsubsurface_p.h b/waylib/src/server/kernel/private/wsubsurface_p.h new file mode 100644 index 0000000000..55826c76eb --- /dev/null +++ b/waylib/src/server/kernel/private/wsubsurface_p.h @@ -0,0 +1,31 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "private/wglobal_p.h" +#include "wsubsurface.h" + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class Q_DECL_HIDDEN WSubsurfacePrivate : public WObjectPrivate +{ +public: + WSubsurfacePrivate(WSubsurface *q, + WSubsurface::Type type, + WSurface *parentSurface, + WSurface *surface); + + W_DECLARE_PUBLIC(WSubsurface) + + WSubsurface::Type type; + WSubsurface::Place place = WSubsurface::Place::Above; + QPointF position; + bool mapped = false; + QPointer parentSurface; + QPointer surface; +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/private/wsurface_p.h b/waylib/src/server/kernel/private/wsurface_p.h index 53eeae0c4c..e554a40f61 100644 --- a/waylib/src/server/kernel/private/wsurface_p.h +++ b/waylib/src/server/kernel/private/wsurface_p.h @@ -1,67 +1,80 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include "wsurface.h" -#include "private/wglobal_p.h" +#include "private/wwaylandresource_p.h" +#include "wpointer.h" +#include "wscoplistener.h" -#include -#include +#include #include #include -struct wlr_surface; -struct wlr_subsurface; - -QW_BEGIN_NAMESPACE -class qw_subsurface; -QW_END_NAMESPACE - WAYLIB_SERVER_BEGIN_NAMESPACE -class Q_DECL_HIDDEN WSurfacePrivate : public WWrapObjectPrivate { +class Q_DECL_HIDDEN WSurfacePrivate : public WWaylandResourcePrivate { public: - WSurfacePrivate(WSurface *qq, QW_NAMESPACE::qw_surface *handle); + WSurfacePrivate(WSurface *qq, wlr_surface *handle); ~WSurfacePrivate(); - WWRAP_HANDLE_FUNCTIONS(QW_NAMESPACE::qw_surface, wlr_surface) + inline wlr_surface *handle() const { + return m_handle; + } wl_client *waylandClient() const override; // begin slot function void on_commit(); void on_client_commit(); - // end slot function - void init(); void connect(); - void instantRelease() override; // release qwobject etc. void updateOutputs(); - void setBuffer(QW_NAMESPACE::qw_buffer *newBuffer); + void setBuffer(wlr_buffer *newBuffer); void updateBuffer(); void updateBufferOffset(); void updatePreferredBufferScale(); void preferredBufferScaleChange(); - WSurface *ensureSubsurface(wlr_subsurface *subsurface); - void setSubsurface(QW_NAMESPACE::qw_subsurface *newSubsurface); + WSubsurface *ensureSubsurface(wlr_subsurface *subsurface); + WSubsurface *addRemoteSubsurface(wlr_surface *childHandle); + void removeSubsurface(WSubsurface *subsurface); + void releaseSubsurface(WSubsurface *subsurface); + void updateStandardSubsurfaces(); + void setSubsurfaceOrder(const QList &remoteBelow, + const QList &remoteAbove); + void rebuildTotalSubsurfaces(); void setHasSubsurface(bool newHasSubsurface); - void updateHasSubsurface(); W_DECLARE_PUBLIC(WSurface) - QPointer subsurface; + friend class WRemoteSubsurfaceManagerV1Private; + + // Logical subsurface relations (standard + remote) exposed via WSurface API. + QList standardBelow; + QList standardAbove; + QList remoteBelow; + QList remoteAbove; + QList subsurfaces; + QPointer subsurface; bool hasSubsurface = false; - bool isSubsurface = false; // qpointer would be null due to qwsubsurface' destroy, cache here uint32_t preferredBufferScale = 1; uint32_t explicitPreferredBufferScale = 0; - std::unique_ptr buffer; - QVector outputs; + bool needsFrame = false; + WBufferUnlockPtr buffer; + QList outputs; + WOutput *framePacingOutput = nullptr; QMetaObject::Connection frameDoneConnection; QPoint bufferOffset; + +private: + // The surface owner destroys this handle after notifying the wrapper. + // Keep the address stable through owner callbacks. + wlr_surface *m_handle = nullptr; }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/private/wtoplevelsurface_p.h b/waylib/src/server/kernel/private/wtoplevelsurface_p.h index f4026c5bb1..6f69316333 100644 --- a/waylib/src/server/kernel/private/wtoplevelsurface_p.h +++ b/waylib/src/server/kernel/private/wtoplevelsurface_p.h @@ -3,15 +3,15 @@ #pragma once #include "wtoplevelsurface.h" -#include "wglobal_p.h" +#include "private/wwaylandresource_p.h" WAYLIB_SERVER_BEGIN_NAMESPACE -class Q_DECL_HIDDEN WToplevelSurfacePrivate : public WWrapObjectPrivate +class WAYLIB_SERVER_EXPORT WToplevelSurfacePrivate : public WWaylandResourcePrivate { public: inline WToplevelSurfacePrivate(WToplevelSurface *q) - : WWrapObjectPrivate(q) {} + : WWaylandResourcePrivate(q) {} }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/private/wwaylandresource_p.h b/waylib/src/server/kernel/private/wwaylandresource_p.h new file mode 100644 index 0000000000..29322a53e4 --- /dev/null +++ b/waylib/src/server/kernel/private/wwaylandresource_p.h @@ -0,0 +1,19 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include "wwaylandresource.h" +#include "wglobal_p.h" + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WAYLIB_SERVER_EXPORT WWaylandResourcePrivate : public WObjectPrivate +{ +public: + using WObjectPrivate::WObjectPrivate; + ~WWaylandResourcePrivate() override = default; + + virtual wl_client *waylandClient() const { return nullptr; } +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wbackend.cpp b/waylib/src/server/kernel/wbackend.cpp index d11bc78055..56a964c06f 100644 --- a/waylib/src/server/kernel/wbackend.cpp +++ b/waylib/src/server/kernel/wbackend.cpp @@ -1,22 +1,22 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wbackend.h" #include "woutput.h" #include "wserver.h" #include "winputdevice.h" +#include "wseat.h" +#include "wscoplistener.h" #include "platformplugin/qwlrootsintegration.h" #include "platformplugin/qwlrootscreen.h" #include "private/wglobal_p.h" -#include -#include -#include -#include +#include + +#include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WBackendPrivate : public WObjectPrivate @@ -28,52 +28,41 @@ class Q_DECL_HIDDEN WBackendPrivate : public WObjectPrivate } - inline qw_backend *handle() const { - return q_func()->nativeInterface(); - } - - inline wlr_backend *nativeHandle() const { - Q_ASSERT(handle()); - return handle()->handle(); + inline wlr_backend *handle() const { + return reinterpret_cast(q_func()->m_handle); } // begin slot function void on_new_output(wlr_output *output); void on_new_input(wlr_input_device *device); - void on_input_destroy(qw_input_device *data); - void on_output_destroy(qw_output *output); + void on_input_destroy(wlr_input_device *device); + void on_output_destroy(wlr_output *output); + void on_destroy(); // end slot function void connect(); W_DECLARE_PUBLIC(WBackend) - QVector outputList; - QVector inputList; + QList outputList; + QList inputList; - struct Keyboard { - Keyboard(WBackendPrivate *self, wlr_input_device *d) - : self(self), device(d) {} - - WBackendPrivate *self; - wlr_input_device *device; - - wl_listener modifiers; - wl_listener key; - }; +private: + wlr_session *session = nullptr; }; void WBackendPrivate::on_new_output(wlr_output *output) { W_Q(WBackend); - auto qoutput = qw_output::from(output); - auto woutput = new WOutput(qoutput, q); + auto woutput = new WOutput(output, q); outputList << woutput; QWlrootsIntegration::instance()->addScreen(woutput); - woutput->safeConnect(&qw_output::before_destroy, q, [this, qoutput] { - on_output_destroy(qoutput); + auto *listeners = woutput->listeners(q_ptr); + listeners->add(&output->events.destroy, this, + [this, output] (void *) { + on_output_destroy(output); }); Q_EMIT q->outputAdded(woutput); @@ -82,53 +71,74 @@ void WBackendPrivate::on_new_output(wlr_output *output) void WBackendPrivate::on_new_input(wlr_input_device *device) { W_Q(WBackend); - auto qinput_device = qw_input_device::from(device); - auto winput_device = new WInputDevice(qinput_device); + auto winput_device = new WInputDevice(device); inputList << winput_device; - winput_device->safeConnect(&qw_input_device::before_destroy, q, [this, qinput_device] { - on_input_destroy(qinput_device); + auto *listeners = winput_device->listeners(q_ptr); + listeners->add(&device->events.destroy, this, + [this, device] (void *) { + on_input_destroy(device); }); Q_EMIT q->inputAdded(winput_device); } -void WBackendPrivate::on_input_destroy(qw_input_device *data) +void WBackendPrivate::on_input_destroy(wlr_input_device *device) { for (int i = 0; i < inputList.count(); ++i) { - if (inputList.at(i)->handle() == data) { - auto device = inputList.takeAt(i); - - W_Q(WBackend); - Q_EMIT q->inputRemoved(device); - device->safeDeleteLater(); - return; - } + if (inputList.at(i)->handle() != device) + continue; + auto winput_device = inputList.takeAt(i); + + W_Q(WBackend); + Q_EMIT q->inputRemoved(winput_device); + // Safe to destroy the wrapper from inside its own destroy callback: + // the listener closure is reference-counted and outlives the + // emission, and ~WInputDevice clears the reverse mapping while the + // native handle is still valid. + delete winput_device; + return; } } -void WBackendPrivate::on_output_destroy(qw_output *output) +void WBackendPrivate::on_output_destroy(wlr_output *output) { for (int i = 0; i < outputList.count(); ++i) { - if (outputList.at(i)->handle() == output) { - auto woutput = outputList.takeAt(i); - - W_Q(WBackend); - Q_EMIT q->outputRemoved(woutput); - QWlrootsIntegration::instance()->removeScreen(woutput); - woutput->safeDeleteLater(); - return; - } + if (outputList.at(i)->handle() != output) + continue; + auto woutput = outputList.takeAt(i); + + W_Q(WBackend); + Q_EMIT q->outputRemoved(woutput); + QWlrootsIntegration::instance()->removeScreen(woutput); + // Safe to destroy the wrapper from inside its own destroy callback + // (see on_input_destroy). + delete woutput; + return; } } +void WBackendPrivate::on_destroy() +{ + W_Q(WBackend); + // The backend is being destroyed by wlroots itself (e.g. the primary + // DRM backend was removed, which tears down the multi-backend). + // wlr_backend_finish() asserts that every listener list is empty, so + // detach ours before the native signal storage is freed, and drop the + // dangling handle: handle()/isDrm()/isX11()/isWayland() must not + // dereference a backend that is going away. The wrapper objects for + // outputs/inputs clean themselves up when the sub-backends destroy + // their devices right after this emission. + q_ptr->removeListeners(q_ptr); + q->m_handle = nullptr; + session = nullptr; +} + void WBackendPrivate::connect() { - QObject::connect(handle(), &qw_backend::notify_new_output, q_func(), [this] (wlr_output *output) { - on_new_output(output); - }); - QObject::connect(handle(), &qw_backend::notify_new_input, q_func(), [this] (wlr_input_device *device) { - on_new_input(device); - }); + W_Q(WBackend); + q->listeners()->add(&handle()->events.new_output, this, &WBackendPrivate::on_new_output); + q->listeners()->add(&handle()->events.new_input, this, &WBackendPrivate::on_new_input); + q->listeners()->add(&handle()->events.destroy, this, &WBackendPrivate::on_destroy); } WBackend::WBackend() @@ -137,55 +147,53 @@ WBackend::WBackend() } -qw_backend *WBackend::handle() const +wlr_backend *WBackend::handle() const { - return nativeInterface(); + return reinterpret_cast(m_handle); +} + +wlr_session *WBackend::session() const +{ + W_DC(WBackend); + return d->session; } -QVector WBackend::outputList() const +QList WBackend::outputList() const { W_DC(WBackend); return d->outputList; } -QVector WBackend::inputDeviceList() const +QList WBackend::inputDeviceList() const { W_DC(WBackend); return d->inputList; } -template -static bool hasBackend(qw_backend *handle) +bool WBackend::isDrm() const { - if (qobject_cast(handle)) - return true; - if (auto multiBackend = qobject_cast(handle)) { - bool exists = false; - multiBackend->for_each_backend([] (wlr_backend *backend, void *userData) { - bool &exists = *reinterpret_cast(userData); - if (T::from(backend)) - exists = true; - }, &exists); - - return exists; - } + return wlr_backend_is_drm(handle()); +} - return false; +bool WBackend::isX11() const +{ + return wlr_backend_is_x11(handle()); } -bool WBackend::hasDrm() const +bool WBackend::isWayland() const { - return hasBackend(handle()); + return wlr_backend_is_wl(handle()); } -bool WBackend::hasX11() const +bool WBackend::isMulti() const { - return hasBackend(handle()); + return wlr_backend_is_multi(handle()); } -bool WBackend::hasWayland() const +bool WBackend::isSessionActive() const { - return hasBackend(handle()); + W_DC(WBackend); + return d->session && d->session->active; } void WBackend::create(WServer *server) @@ -193,23 +201,35 @@ void WBackend::create(WServer *server) W_D(WBackend); if (!m_handle) { - m_handle = qw_backend::autocreate(server->handle()->get_event_loop(), nullptr); + wlr_session *session = nullptr; + m_handle = wlr_backend_autocreate(wl_display_get_event_loop(server->handle()), &session); Q_ASSERT(m_handle); + d->session = session; + Q_EMIT created(); } d->connect(); } -void WBackend::destroy(WServer *server) +void WBackend::destroy([[maybe_unused]] WServer *server) { - Q_UNUSED(server) W_D(WBackend); - qDeleteAll(d->inputList); - qDeleteAll(d->outputList); - d->inputList.clear(); - d->outputList.clear(); + QList inputList; + inputList.swap(d->inputList); + QList outputList; + outputList.swap(d->outputList); + for (auto *device : std::as_const(inputList)) + delete device; + for (auto *output : std::as_const(outputList)) + delete output; + + removeListeners(this); + auto *backend = reinterpret_cast(m_handle); m_handle = nullptr; + d->session = nullptr; + if (backend) + wlr_backend_destroy(backend); } wl_global *WBackend::global() const diff --git a/waylib/src/server/kernel/wbackend.h b/waylib/src/server/kernel/wbackend.h index d60e37feef..5b9f7c369e 100644 --- a/waylib/src/server/kernel/wbackend.h +++ b/waylib/src/server/kernel/wbackend.h @@ -1,14 +1,16 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include -#include - #include +Q_MOC_INCLUDE("woutput.h") +Q_MOC_INCLUDE("winputdevice.h") + WAYLIB_SERVER_BEGIN_NAMESPACE class WOutput; @@ -17,20 +19,31 @@ class WBackendPrivate; class WAYLIB_SERVER_EXPORT WBackend : public QObject, public WObject, public WServerInterface { Q_OBJECT + Q_PROPERTY(bool isDrm READ isDrm FINAL) + Q_PROPERTY(bool isX11 READ isX11 FINAL) + Q_PROPERTY(bool isWayland READ isWayland FINAL) + Q_PROPERTY(bool isMulti READ isMulti FINAL) + Q_PROPERTY(bool isSessionActive READ isSessionActive FINAL) friend class WOutputPrivate; W_DECLARE_PRIVATE(WBackend) public: explicit WBackend(); - QW_NAMESPACE::qw_backend *handle() const; + wlr_backend *handle() const; + wlr_session *session() const; - QVector outputList() const; - QVector inputDeviceList() const; + QList outputList() const; + QList inputDeviceList() const; - bool hasDrm() const; - bool hasX11() const; - bool hasWayland() const; + bool isDrm() const; + bool isX11() const; + bool isWayland() const; + bool isMulti() const; + + bool isSessionActive() const; + + QByteArrayView interfaceName() const override; Q_SIGNALS: void outputAdded(WOutput *output); @@ -39,11 +52,12 @@ class WAYLIB_SERVER_EXPORT WBackend : public QObject, public WObject, public WS void inputAdded(WInputDevice *input); void inputRemoved(WInputDevice *input); + void created(); + protected: void create(WServer *server) override; void destroy(WServer *server) override; wl_global *global() const override; - QByteArrayView interfaceName() const override; }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wcursor.cpp b/waylib/src/server/kernel/wcursor.cpp index a19b3e78e7..ca3dc3c145 100644 --- a/waylib/src/server/kernel/wcursor.cpp +++ b/waylib/src/server/kernel/wcursor.cpp @@ -1,9 +1,11 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023 - 2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only -#define private public +#include +#include "wscoplistener.h" #include -#undef private +#include +#include "private/wprivateaccessor_p.h" #include "wcursor.h" #include "private/wcursor_p.h" @@ -12,52 +14,48 @@ #include "wseat.h" #include "woutput.h" #include "woutputlayout.h" +#include "wserver.h" +#include "wayliblogging.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include #include #include -#include #include -QW_USE_NAMESPACE -WAYLIB_SERVER_BEGIN_NAMESPACE +W_DECLARE_PRIVATE_MEMBER(QCursor_d_tag, QCursor, d, QCursorData*); -Q_LOGGING_CATEGORY(qLcWlrCursor, "waylib.server.cursor", QtWarningMsg) +WAYLIB_SERVER_BEGIN_NAMESPACE WCursorPrivate::WCursorPrivate(WCursor *qq) - : WWrapObjectPrivate(qq) + : WObjectPrivate(qq) + , overrideCursor(WCursor::toQCursor(WGlobal::CursorShape::Invalid)) { - initHandle(qw_cursor::create()); - handle()->set_data(this, qq); + m_handle.reset(wlr_cursor_create()); + Q_ASSERT(m_handle); + m_handle->data = qq; } -WCursorPrivate::~WCursorPrivate() -{ +WCursorPrivate::~WCursorPrivate() = default; -} - -void WCursorPrivate::instantRelease() +WCursor::~WCursor() { - if (seat) - seat->setCursor(nullptr); - - if (outputLayout) { - for (auto o : outputLayout->outputs()) - o->removeCursor(q_func()); + teardown(); + W_D(WCursor); + // Clear the reverse fromHandle() mapping while the native cursor is + // still alive (the WUniquePointer member releases it after this body). + if (d->m_handle && d->m_handle->data == this) + d->m_handle->data = nullptr; + // Owner teardown: detach from the seat and every output before the + // native cursor is released (WUniquePointer in ~WCursorPrivate, after + // the listeners are detached there). + if (d->seat) + d->seat->setCursor(nullptr); + if (d->outputLayout) { + for (auto o : d->outputLayout->outputs()) + o->removeCursor(this); } - - delete handle(); } void WCursorPrivate::sendEnterEvent(WInputDevice *device) @@ -79,23 +77,47 @@ void WCursorPrivate::sendLeaveEvent(WInputDevice *device) void WCursorPrivate::on_motion(wlr_pointer_motion_event *event) { - auto device = qw_pointer::from(event->pointer); - q_func()->move(device, QPointF(event->delta_x, event->delta_y)); - processCursorMotion(device, event->time_msec); + auto *device = &event->pointer->base; + const QPointF oldPos = q_func()->position(); + const QPointF delta(event->delta_x, event->delta_y); + + if (!applyPointerConstraint(device, oldPos, delta)) + processCursorMotion(device, event->time_msec); + + // zwp_relative_pointer_v1 always receives the raw hardware delta + if (Q_LIKELY(seat)) { + Q_EMIT seat->relativePointerMotion(event->time_msec, delta, + QPointF(event->unaccel_dx, event->unaccel_dy)); + } } void WCursorPrivate::on_motion_absolute(wlr_pointer_motion_absolute_event *event) { - auto device = qw_pointer::from(event->pointer); - q_func()->setScalePosition(device, QPointF(event->x, event->y)); - processCursorMotion(device, event->time_msec); + auto *device = &event->pointer->base; + const QPointF oldPos = q_func()->position(); + double lx, ly; + wlr_cursor_absolute_to_layout_coords(handle(), device, + event->x, event->y, &lx, &ly); + const QPointF rawDelta(lx - oldPos.x(), ly - oldPos.y()); + + if (!applyPointerConstraint(device, oldPos, rawDelta)) + processCursorMotion(device, event->time_msec); + + // Same as on_motion: send the raw position-delta as relative motion. + if (Q_LIKELY(seat)) { + Q_EMIT seat->relativePointerMotion(event->time_msec, rawDelta, rawDelta); + } } void WCursorPrivate::on_button(wlr_pointer_button_event *event) { - auto device = qw_pointer::from(event->pointer); + auto *device = &event->pointer->base; button = WCursor::fromNativeButton(event->button); + QString stateStr = (event->state == WL_POINTER_BUTTON_STATE_RELEASED) ? "released" : "pressed"; + qCDebug(lcWlPointer) << "Button" << static_cast(button) << stateStr + << "at position:" << q_func()->position(); + if (event->state == WL_POINTER_BUTTON_STATE_RELEASED) { state &= ~button; } else { @@ -103,21 +125,24 @@ void WCursorPrivate::on_button(wlr_pointer_button_event *event) lastPressedOrTouchDownPosition = q_func()->position(); } - if (Q_LIKELY(seat)) { - seat->notifyButton(q_func(), WInputDevice::fromHandle(device), - button, event->state, event->time_msec); + if (auto inputDevice = WInputDevice::fromHandle(device)) { + if (auto deviceSeat = inputDevice->seat()) { + deviceSeat->notifyButton(q_func(), inputDevice, button, event->state, event->time_msec); + } } } void WCursorPrivate::on_axis(wlr_pointer_axis_event *event) { - auto device = qw_pointer::from(event->pointer); + auto *device = &event->pointer->base; - if (Q_LIKELY(seat)) { - seat->notifyAxis(q_func(), WInputDevice::fromHandle(device), event->source, - event->orientation == WL_POINTER_AXIS_HORIZONTAL_SCROLL - ? Qt::Horizontal : Qt::Vertical, event->relative_direction, - event->delta, event->delta_discrete, event->time_msec); + if (auto inputDevice = WInputDevice::fromHandle(device)) { + if (auto deviceSeat = inputDevice->seat()) { + deviceSeat->notifyAxis(q_func(), inputDevice, event->source, + event->orientation == WL_POINTER_AXIS_HORIZONTAL_SCROLL + ? Qt::Horizontal : Qt::Vertical, event->relative_direction, + event->delta * scrollFactor, event->delta_discrete, event->time_msec); + } } } @@ -130,7 +155,7 @@ void WCursorPrivate::on_frame() void WCursorPrivate::on_swipe_begin(wlr_pointer_swipe_begin_event *event) { - auto device = qw_pointer::from(event->pointer); + auto *device = &event->pointer->base; if (Q_LIKELY(seat)) { seat->notifyGestureBegin(q_func(), WInputDevice::fromHandle(device), event->time_msec, event->fingers, WGestureEvent::SwipeGesture); @@ -139,7 +164,7 @@ void WCursorPrivate::on_swipe_begin(wlr_pointer_swipe_begin_event *event) void WCursorPrivate::on_swipe_update(wlr_pointer_swipe_update_event *event) { - auto device = qw_pointer::from(event->pointer); + auto *device = &event->pointer->base; if (Q_LIKELY(seat)) { QPointF delta = QPointF(event->dx, event->dy); seat->notifyGestureUpdate(q_func(), WInputDevice::fromHandle(device), @@ -149,7 +174,7 @@ void WCursorPrivate::on_swipe_update(wlr_pointer_swipe_update_event *event) void WCursorPrivate::on_swipe_end(wlr_pointer_swipe_end_event *event) { - auto device = qw_pointer::from(event->pointer); + auto *device = &event->pointer->base; if (Q_LIKELY(seat)) { seat->notifyGestureEnd(q_func(), WInputDevice::fromHandle(device), event->time_msec, event->cancelled, WGestureEvent::SwipeGesture); @@ -158,7 +183,7 @@ void WCursorPrivate::on_swipe_end(wlr_pointer_swipe_end_event *event) void WCursorPrivate::on_pinch_begin(wlr_pointer_pinch_begin_event *event) { - auto device = qw_pointer::from(event->pointer); + auto *device = &event->pointer->base; if (Q_LIKELY(seat)) { seat->notifyGestureBegin(q_func(), WInputDevice::fromHandle(device), event->time_msec, event->fingers, WGestureEvent::PinchGesture); @@ -167,7 +192,7 @@ void WCursorPrivate::on_pinch_begin(wlr_pointer_pinch_begin_event *event) void WCursorPrivate::on_pinch_update(wlr_pointer_pinch_update_event *event) { - auto device = qw_pointer::from(event->pointer); + auto *device = &event->pointer->base; if (Q_LIKELY(seat)) { QPointF delta = QPointF(event->dx, event->dy); seat->notifyGestureUpdate(q_func(), WInputDevice::fromHandle(device), @@ -178,7 +203,7 @@ void WCursorPrivate::on_pinch_update(wlr_pointer_pinch_update_event *event) void WCursorPrivate::on_pinch_end(wlr_pointer_pinch_end_event *event) { - auto device = qw_pointer::from(event->pointer); + auto *device = &event->pointer->base; if (Q_LIKELY(seat)) { seat->notifyGestureEnd(q_func(), WInputDevice::fromHandle(device), event->time_msec, event->cancelled, @@ -188,7 +213,7 @@ void WCursorPrivate::on_pinch_end(wlr_pointer_pinch_end_event *event) void WCursorPrivate::on_hold_begin(wlr_pointer_hold_begin_event *event) { - auto device = qw_pointer::from(event->pointer); + auto *device = &event->pointer->base; if (Q_LIKELY(seat)) { seat->notifyHoldBegin(q_func(), WInputDevice::fromHandle(device), event->time_msec, event->fingers); @@ -197,7 +222,7 @@ void WCursorPrivate::on_hold_begin(wlr_pointer_hold_begin_event *event) void WCursorPrivate::on_hold_end(wlr_pointer_hold_end_event *event) { - auto device = qw_pointer::from(event->pointer); + auto *device = &event->pointer->base; if (Q_LIKELY(seat)) { seat->notifyHoldEnd(q_func(), WInputDevice::fromHandle(device), event->time_msec, event->cancelled); @@ -206,7 +231,7 @@ void WCursorPrivate::on_hold_end(wlr_pointer_hold_end_event *event) void WCursorPrivate::on_touch_down(wlr_touch_down_event *event) { - auto device = qw_touch::from(event->touch); + auto *device = &event->touch->base; q_func()->setScalePosition(device, QPointF(event->x, event->y)); lastPressedOrTouchDownPosition = q_func()->position(); @@ -220,7 +245,7 @@ void WCursorPrivate::on_touch_down(wlr_touch_down_event *event) void WCursorPrivate::on_touch_motion(wlr_touch_motion_event *event) { - auto device = qw_touch::from(event->touch); + auto *device = &event->touch->base; q_func()->setScalePosition(device, QPointF(event->x, event->y)); @@ -239,7 +264,7 @@ void WCursorPrivate::on_touch_frame() void WCursorPrivate::on_touch_cancel(wlr_touch_cancel_event *event) { - auto device = qw_touch::from(event->touch); + auto *device = &event->touch->base; if (Q_LIKELY(seat)) { seat->notifyTouchCancel(q_func(), WInputDevice::fromHandle(device), @@ -249,7 +274,7 @@ void WCursorPrivate::on_touch_cancel(wlr_touch_cancel_event *event) void WCursorPrivate::on_touch_up(wlr_touch_up_event *event) { - auto device = qw_touch::from(event->touch); + auto *device = &event->touch->base; if (Q_LIKELY(seat)) { seat->notifyTouchUp(q_func(), WInputDevice::fromHandle(device), @@ -262,104 +287,137 @@ void WCursorPrivate::connect() W_Q(WCursor); Q_ASSERT(seat); - QObject::connect(handle(), &qw_cursor::notify_motion, q, [this] (wlr_pointer_motion_event *event) { - on_motion(event); - }); - QObject::connect(handle(), &qw_cursor::notify_motion_absolute, q, [this] (wlr_pointer_motion_absolute_event *event) { - on_motion_absolute(event); - }); - QObject::connect(handle(), &qw_cursor::notify_button, q, [this] (wlr_pointer_button_event *event) { - on_button(event); - }); - QObject::connect(handle(), &qw_cursor::notify_axis, q, [this] (wlr_pointer_axis_event *event) { - on_axis(event); - }); - QObject::connect(handle(), &qw_cursor::notify_frame, q, [this] () { - on_frame(); - }); + q->listeners()->add(&m_handle->events.motion, this, &WCursorPrivate::on_motion); + q->listeners()->add(&m_handle->events.motion_absolute, this, &WCursorPrivate::on_motion_absolute); + q->listeners()->add(&m_handle->events.button, this, &WCursorPrivate::on_button); + q->listeners()->add(&m_handle->events.axis, this, &WCursorPrivate::on_axis); + q->listeners()->add(&m_handle->events.frame, this, &WCursorPrivate::on_frame); + q->listeners()->add(&m_handle->events.swipe_begin, this, &WCursorPrivate::on_swipe_begin); + q->listeners()->add(&m_handle->events.swipe_update, this, &WCursorPrivate::on_swipe_update); + q->listeners()->add(&m_handle->events.swipe_end, this, &WCursorPrivate::on_swipe_end); + q->listeners()->add(&m_handle->events.pinch_begin, this, &WCursorPrivate::on_pinch_begin); + q->listeners()->add(&m_handle->events.pinch_update, this, &WCursorPrivate::on_pinch_update); + q->listeners()->add(&m_handle->events.pinch_end, this, &WCursorPrivate::on_pinch_end); + q->listeners()->add(&m_handle->events.hold_begin, this, &WCursorPrivate::on_hold_begin); + q->listeners()->add(&m_handle->events.hold_end, this, &WCursorPrivate::on_hold_end); + // Handle touch device related signals + q->listeners()->add(&m_handle->events.touch_down, this, &WCursorPrivate::on_touch_down); + q->listeners()->add(&m_handle->events.touch_motion, this, &WCursorPrivate::on_touch_motion); + q->listeners()->add(&m_handle->events.touch_frame, this, &WCursorPrivate::on_touch_frame); + q->listeners()->add(&m_handle->events.touch_cancel, this, &WCursorPrivate::on_touch_cancel); + q->listeners()->add(&m_handle->events.touch_up, this, &WCursorPrivate::on_touch_up); +} - QObject::connect(handle(), SIGNAL(notify_swipe_begin(wlr_pointer_swipe_begin_event*)), - q, SLOT(on_swipe_begin(wlr_pointer_swipe_begin_event*))); - QObject::connect(handle(), SIGNAL(notify_swipe_update(wlr_pointer_swipe_update_event*)), - q, SLOT(on_swipe_update(wlr_pointer_swipe_update_event*))); - QObject::connect(handle(), SIGNAL(notify_swipe_end(wlr_pointer_swipe_end_event*)), - q, SLOT(on_swipe_end(wlr_pointer_swipe_end_event*))); - QObject::connect(handle(), SIGNAL(notify_pinch_begin(wlr_pointer_pinch_begin_event*)), - q, SLOT(on_pinch_begin(wlr_pointer_pinch_begin_event*))); - QObject::connect(handle(), SIGNAL(notify_pinch_update(wlr_pointer_pinch_update_event*)), - q, SLOT(on_pinch_update(wlr_pointer_pinch_update_event*))); - QObject::connect(handle(), SIGNAL(notify_pinch_end(wlr_pointer_pinch_end_event*)), - q, SLOT(on_pinch_end(wlr_pointer_pinch_end_event*))); - QObject::connect(handle(), SIGNAL(notify_hold_begin(wlr_pointer_hold_begin_event*)), - q, SLOT(on_hold_begin(wlr_pointer_hold_begin_event*))); - QObject::connect(handle(), SIGNAL(notify_hold_end(wlr_pointer_hold_end_event*)), - q, SLOT(on_hold_end(wlr_pointer_hold_end_event*))); +void WCursorPrivate::processCursorMotion(wlr_input_device *device, uint32_t time) +{ + W_Q(WCursor); - // Handle touch device related signals - QObject::connect(handle(), &qw_cursor::notify_touch_down, q, [this] (wlr_touch_down_event *event) { - on_touch_down(event); - }); - QObject::connect(handle(), &qw_cursor::notify_touch_motion, q, [this] (wlr_touch_motion_event *event) { - on_touch_motion(event); - }); - QObject::connect(handle(), &qw_cursor::notify_touch_frame, q, [this] () { - on_touch_frame(); - }); - QObject::connect(handle(), &qw_cursor::notify_touch_cancel, q, [this] (wlr_touch_cancel_event *event) { - on_touch_cancel(event); - }); - QObject::connect(handle(), &qw_cursor::notify_touch_up, q, [this] (wlr_touch_up_event *event) { - on_touch_up(event); - }); + qCDebug(lcWlPointer) << "Processing cursor motion at" << q->position() + << "time:" << time; + + if (auto inputDevice = WInputDevice::fromHandle(device)) { + if (auto deviceSeat = inputDevice->seat()) { + deviceSeat->notifyMotion(q, inputDevice, time); + } + } } -void WCursorPrivate::processCursorMotion(qw_pointer *device, uint32_t time) +bool WCursorPrivate::applyPointerConstraint(wlr_input_device *device, + const QPointF &oldPos, + const QPointF &delta) { W_Q(WCursor); + if (!activeConstraint) { + // No constraint: regular delta move. + q->move(device, delta); + return false; + } + + // Touch/tablet input must not be affected by pointer constraints + if (!device || device->type != WLR_INPUT_DEVICE_POINTER) { + q->move(device, delta); + return false; + } + + wlr_seat *wlrSeat = seat ? seat->handle() : nullptr; + if (!wlrSeat) { + q->move(device, delta); + return false; + } + + if (activeConstraint->type == WLR_POINTER_CONSTRAINT_V1_LOCKED) { + // Warp back to the anchor on every motion so physical movement does + // not accumulate and cause a jump when the constraint deactivates. + q->setPosition(device, lockedWarpTarget); + return true; + } - if (Q_LIKELY(seat)) - seat->notifyMotion(q, WInputDevice::fromHandle(device), time); + if (activeConstraint->type == WLR_POINTER_CONSTRAINT_V1_CONFINED) { + const double sx = wlrSeat->pointer_state.sx; + const double sy = wlrSeat->pointer_state.sy; + double confinedSx = sx + delta.x(); + double confinedSy = sy + delta.y(); + if (wlr_region_confine(&activeConstraint->region, sx, sy, + confinedSx, confinedSy, + &confinedSx, &confinedSy)) { + // Confine succeeded: set cursor to the clamped absolute position. + q->setPosition(device, + oldPos + QPointF(confinedSx - sx, confinedSy - sy)); + return false; + } + // Cannot enter the constraint region from outside. Block all + // movement (no cursor move, no dispatch) + return true; + } + + // Unknown constraint type — fall through to regular move. + q->move(device, delta); + return false; } WCursor::WCursor(WCursorPrivate &dd, QObject *parent) - : WWrapObject(dd, parent) + : QObject(parent) + , WObject(dd, nullptr) { } -void WCursor::move(qw_input_device *device, const QPointF &delta) +void WCursor::move(wlr_input_device *device, const QPointF &delta) { const QPointF oldPos = position(); - d_func()->handle()->move(*device, delta.x(), delta.y()); + wlr_cursor_move(d_func()->handle(), device, delta.x(), delta.y()); - if (oldPos != position()) + if (oldPos != position()) { + qCDebug(lcWlCursor) << "Cursor moved from" << oldPos << "to" << position() + << "delta:" << delta; Q_EMIT positionChanged(); + } } -void WCursor::setPosition(qw_input_device *device, const QPointF &pos) +void WCursor::setPosition(wlr_input_device *device, const QPointF &pos) { const QPointF oldPos = position(); - d_func()->handle()->warp_closest(*device, pos.x(), pos.y()); + wlr_cursor_warp_closest(d_func()->handle(), device, pos.x(), pos.y()); if (oldPos != position()) Q_EMIT positionChanged(); } -bool WCursor::setPositionWithChecker(qw_input_device *device, const QPointF &pos) +bool WCursor::setPositionWithChecker(wlr_input_device *device, const QPointF &pos) { const QPointF oldPos = position(); - bool ok = d_func()->handle()->warp(*device, pos.x(), pos.y()); + bool ok = wlr_cursor_warp(d_func()->handle(), device, pos.x(), pos.y()); if (oldPos != position()) Q_EMIT positionChanged(); return ok; } -void WCursor::setScalePosition(qw_input_device *device, const QPointF &ratio) +void WCursor::setScalePosition(wlr_input_device *device, const QPointF &ratio) { Q_ASSERT(layout()); const QPointF oldPos = position(); - d_func()->handle()->warp_absolute(*device, ratio.x(), ratio.y()); + wlr_cursor_warp_absolute(d_func()->handle(), device, ratio.x(), ratio.y()); if (oldPos != position()) Q_EMIT positionChanged(); @@ -371,15 +429,17 @@ WCursor::WCursor(QObject *parent) } -qw_cursor *WCursor::handle() const +wlr_cursor *WCursor::handle() const { W_DC(WCursor); return d->handle(); } -WCursor *WCursor::fromHandle(const qw_cursor *handle) +WCursor *WCursor::fromHandle(wlr_cursor *handle) { - return handle->get_data(); + if (!handle) + return nullptr; + return static_cast(handle->data); } Qt::MouseButton WCursor::fromNativeButton(uint32_t code) @@ -404,7 +464,9 @@ Qt::MouseButton WCursor::fromNativeButton(uint32_t code) case 0x11d: qt_button = Qt::ExtraButton11; break; case 0x11e: qt_button = Qt::ExtraButton12; break; case 0x11f: qt_button = Qt::ExtraButton13; break; - default: qWarning() << "invalid button number (as far as Qt is concerned)" << code; // invalid button number (as far as Qt is concerned) + default: + qCWarning(lcWlPointer) << "Invalid button code:" << QString("0x%1").arg(code, 0, 16) + << "- not mappable to Qt button"; } return qt_button; @@ -429,7 +491,9 @@ uint32_t WCursor::toNativeButton(Qt::MouseButton button) case Qt::ExtraButton11: return 0x11d; case Qt::ExtraButton12: return 0x11e; case Qt::ExtraButton13: return 0x11f; - default: qWarning() << "invalid Qt's button" << button; + default: + qCWarning(lcWlPointer) << "Invalid Qt button:" << button + << "- cannot be mapped to native button code"; } return 0; @@ -441,14 +505,14 @@ QCursor WCursor::toQCursor(CursorShape shape) // Ensure alloc a new QCursorData QCursor cursor(tmp, tmp); - Q_ASSERT(cursor.d->ref == 1); - Q_ASSERT(cursor.d->bm); - Q_ASSERT(cursor.d->bmm); - delete cursor.d->bm; - delete cursor.d->bmm; - cursor.d->bm = nullptr; - cursor.d->bmm = nullptr; - cursor.d->cshape = static_cast(shape); + Q_ASSERT(W_PRIVATE_MEMBER(cursor, QCursor_d_tag{})->ref == 1); + Q_ASSERT(W_PRIVATE_MEMBER(cursor, QCursor_d_tag{})->bm); + Q_ASSERT(W_PRIVATE_MEMBER(cursor, QCursor_d_tag{})->bmm); + delete W_PRIVATE_MEMBER(cursor, QCursor_d_tag{})->bm; + delete W_PRIVATE_MEMBER(cursor, QCursor_d_tag{})->bmm; + W_PRIVATE_MEMBER(cursor, QCursor_d_tag{})->bm = nullptr; + W_PRIVATE_MEMBER(cursor, QCursor_d_tag{})->bmm = nullptr; + W_PRIVATE_MEMBER(cursor, QCursor_d_tag{})->cshape = static_cast(shape); return cursor; } @@ -470,8 +534,7 @@ void WCursor::setSeat(WSeat *seat) W_D(WCursor); if (d->seat) { - // reconnect signals - d->handle()->disconnect(this); + removeListeners(this); d->seat->disconnect(this); } d->seat = seat; @@ -531,7 +594,9 @@ Qt::CursorShape WCursor::defaultCursor() QCursor WCursor::cursor() const { W_DC(WCursor); - return d->cursor; + return WGlobal::isInvalidCursor(d->overrideCursor) + ? d->cursor + : d->overrideCursor; } void WCursor::setCursor(const QCursor &cursor) @@ -540,7 +605,26 @@ void WCursor::setCursor(const QCursor &cursor) if (d->cursor == cursor) return; + d->cursor = cursor; + if (WGlobal::isInvalidCursor(d->overrideCursor)) + Q_EMIT cursorChanged(); +} + +QCursor WCursor::overrideCursor() const +{ + W_DC(WCursor); + return d->overrideCursor; +} + +void WCursor::setOverrideCursor(const QCursor &cursor) +{ + W_D(WCursor); + + if (d->overrideCursor == cursor) + return; + + d->overrideCursor = cursor; Q_EMIT cursorChanged(); } @@ -571,12 +655,16 @@ bool WCursor::attachInputDevice(WInputDevice *device) if (device->type() != WInputDevice::Type::Pointer && device->type() != WInputDevice::Type::Touch && device->type() != WInputDevice::Type::Tablet) { + qCDebug(lcWlCursor) << "Cannot attach device type" << static_cast(device->type()) + << "to cursor - not a pointing device"; return false; } W_D(WCursor); Q_ASSERT(!d->deviceList.contains(device)); - d->handle()->attach_input_device(device->handle()->handle()); + qCDebug(lcWlCursor) << "Attaching input device" << device->qtDevice()->name() + << "of type" << static_cast(device->type()) << "to cursor"; + wlr_cursor_attach_input_device(d->handle(), device->handle()); d->deviceList << device; if (d->eventWindow) { @@ -591,11 +679,16 @@ void WCursor::detachInputDevice(WInputDevice *device) { W_D(WCursor); - if (!d->deviceList.removeOne(device)) + if (!d->deviceList.removeOne(device)) { + qCDebug(lcWlCursor) << "Cannot detach device" << device->qtDevice()->name() + << "- not attached to this cursor"; return; + } - d->handle()->detach_input_device(device->handle()->handle()); - d->handle()->map_input_to_output(device->handle()->handle(), nullptr); + qCDebug(lcWlCursor) << "Detaching input device" << device->qtDevice()->name() + << "from cursor"; + wlr_cursor_detach_input_device(d->handle(), device->handle()); + wlr_cursor_map_input_to_output(d->handle(), device->handle(), nullptr); if (d->eventWindow && device->seat()) { Q_ASSERT(d->seat); @@ -611,18 +704,18 @@ void WCursor::setLayout(WOutputLayout *layout) return; d->outputLayout = layout; - d->handle()->attach_output_layout(*d->outputLayout->handle()); + wlr_cursor_attach_output_layout(d->handle(), d->outputLayout->handle()); if (d->outputLayout) { for (auto o : d->outputLayout->outputs()) o->addCursor(this); } - connect(d->outputLayout, &WOutputLayout::outputAdded, this, [this, d] (WOutput *o) { + connect(d->outputLayout, &WOutputLayout::outputAdded, this, [this] (WOutput *o) { o->addCursor(this); }); - connect(d->outputLayout, &WOutputLayout::outputRemoved, this, [this, d] (WOutput *o) { + connect(d->outputLayout, &WOutputLayout::outputRemoved, this, [this] (WOutput *o) { o->removeCursor(this); }); @@ -660,10 +753,91 @@ void WCursor::setVisible(bool visible) Q_EMIT visibleChanged(); } +void WCursor::setActivePointerConstraint(wlr_pointer_constraint_v1 *constraint) +{ + W_D(WCursor); + if (d->activeConstraint == constraint) + return; + + d->activeConstraint = constraint; + + if (!constraint) + return; + + if (constraint->type == WLR_POINTER_CONSTRAINT_V1_LOCKED) { + // Anchor the lock to the current cursor position. + // set_cursor_position_hint is only consumed at unlock time + // (warpToActiveConstraintHint). + d->updateLockedWarpTarget(); + } + // CONFINED: no init-time warp — see canActivate's region-containment check. + // Activation is deferred until the pointer is inside the constraint region + // (KWin lazy-activation policy). +} + +void WCursorPrivate::updateLockedWarpTarget() +{ + W_Q(WCursor); + if (!activeConstraint + || activeConstraint->type != WLR_POINTER_CONSTRAINT_V1_LOCKED) + return; + + // Per the protocol, set_cursor_position_hint is only consumed at unlock + // time (warpToActiveConstraintHint). During lock the cursor must stay at + // a stable anchor so applyPointerConstraint warps back on every motion. + // Snapping to q->position() is safe because applyPointerConstraint keeps + // the cursor at lockedWarpTarget between surface commits, so position() + // is always consistent with the current anchor. + lockedWarpTarget = q->position(); +} + +void WCursor::warpToActiveConstraintHint() +{ + W_D(WCursor); + auto *constraint = d->activeConstraint; + if (!constraint) + return; + + wlr_seat *wlrSeat = d->seat ? d->seat->handle() : nullptr; + // Focus already left this surface (cleared or moved elsewhere) — + // the surface-local -> global conversion is meaningless. + if (!wlrSeat || wlrSeat->pointer_state.focused_surface != constraint->surface) + return; + + if (!constraint->current.cursor_hint.enabled) + return; + + // Convert the surface-local cursor_hint to global coordinates by + // computing the offset from the current surface-local pointer position + // and applying it on top of the current cursor position. This matches + // the same geometry used in updateLockedWarpTarget() and follows + // Sway's warp_to_constraint_cursor_hint(). + const double sx = wlrSeat->pointer_state.sx; + const double sy = wlrSeat->pointer_state.sy; + const QPointF globalPos = position() + + QPointF(constraint->current.cursor_hint.x - sx, + constraint->current.cursor_hint.y - sy); + if (!qIsFinite(globalPos.x()) || !qIsFinite(globalPos.y())) { + qCWarning(lcWlCursor) << "warpToActiveConstraintHint: computed position is" + << "not finite (" << globalPos << "), skipping warp"; + return; + } + setPosition(nullptr, globalPos); + wlr_seat_pointer_warp(wlrSeat, + constraint->current.cursor_hint.x, + constraint->current.cursor_hint.y); +} + +wlr_pointer_constraint_v1 *WCursor::activePointerConstraint() const +{ + W_DC(WCursor); + return d->activeConstraint; +} + QPointF WCursor::position() const { W_DC(WCursor); - return QPointF(d->nativeHandle()->x, d->nativeHandle()->y); + return QPointF(d->handle()->x, d->handle()->y); } QPointF WCursor::lastPressedOrTouchDownPosition() const @@ -672,6 +846,21 @@ QPointF WCursor::lastPressedOrTouchDownPosition() const return d->lastPressedOrTouchDownPosition; } +double WCursor::scrollFactor() const +{ + W_DC(WCursor); + return d->scrollFactor; +} + +void WCursor::setScrollFactor(double factor) +{ + W_D(WCursor); + if (qFuzzyCompare(d->scrollFactor, factor)) + return; + d->scrollFactor = factor; + Q_EMIT scrollFactorChanged(); +} + WAYLIB_SERVER_END_NAMESPACE #include "moc_wcursor.cpp" diff --git a/waylib/src/server/kernel/wcursor.h b/waylib/src/server/kernel/wcursor.h index 3755e36706..26f16faf6c 100644 --- a/waylib/src/server/kernel/wcursor.h +++ b/waylib/src/server/kernel/wcursor.h @@ -1,34 +1,27 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include #include #include -#include #include +#include QT_BEGIN_NAMESPACE class QWindow; QT_END_NAMESPACE -QW_BEGIN_NAMESPACE -class qw_xcursor_manager; -class qw_input_device; -class qw_cursor; -class qw_output_cursor; -class qw_surface; -QW_END_NAMESPACE - WAYLIB_SERVER_BEGIN_NAMESPACE class WSeat; class WInputDevice; class WXCursorImage; class WCursorPrivate; -class WAYLIB_SERVER_EXPORT WCursor : public WWrapObject +class WAYLIB_SERVER_EXPORT WCursor : public QObject, public WObject { Q_OBJECT W_DECLARE_PRIVATE(WCursor) @@ -36,6 +29,7 @@ class WAYLIB_SERVER_EXPORT WCursor : public WWrapObject Q_PROPERTY(QCursor cursor READ cursor WRITE setCursor NOTIFY cursorChanged FINAL) Q_PROPERTY(QPointF position READ position NOTIFY positionChanged FINAL) Q_PROPERTY(WAYLIB_SERVER_NAMESPACE::WSurface* requestedDragSurface READ requestedDragSurface NOTIFY requestedDragSurfaceChanged FINAL) + Q_PROPERTY(double scrollFactor READ scrollFactor WRITE setScrollFactor NOTIFY scrollFactorChanged FINAL) QML_ANONYMOUS public: @@ -43,9 +37,9 @@ class WAYLIB_SERVER_EXPORT WCursor : public WWrapObject explicit WCursor(QObject *parent = nullptr); - QW_NAMESPACE::qw_cursor *handle() const; + wlr_cursor *handle() const; - static WCursor *fromHandle(const QW_NAMESPACE::qw_cursor *handle); + static WCursor *fromHandle(wlr_cursor *handle); static Qt::MouseButton fromNativeButton(uint32_t code); static uint32_t toNativeButton(Qt::MouseButton button); @@ -63,6 +57,9 @@ class WAYLIB_SERVER_EXPORT WCursor : public WWrapObject QCursor cursor() const; void setCursor(const QCursor &cursor); + QCursor overrideCursor() const; + void setOverrideCursor(const QCursor &cursor); + // from client CursorShape requestedCursorShape() const; std::pair requestedCursorSurface() const; @@ -77,9 +74,21 @@ class WAYLIB_SERVER_EXPORT WCursor : public WWrapObject bool isVisible() const; void setVisible(bool visible); + // Active pointer constraint (locked/confined) enforced on this cursor, or + // Pointer constraint enforcement — used by treeland + // PointerConstraintsManager (the compositor policy layer). + void setActivePointerConstraint(wlr_pointer_constraint_v1 *constraint); + wlr_pointer_constraint_v1 *activePointerConstraint() const; + // Warp to the constraint's cursor_hint before clearing it. + // Internal: must be called before setActivePointerConstraint(nullptr). + void warpToActiveConstraintHint(); + QPointF position() const; QPointF lastPressedOrTouchDownPosition() const; + double scrollFactor() const; + void setScrollFactor(double factor); + Q_SIGNALS: void positionChanged(); void seatChanged(); @@ -89,15 +98,18 @@ class WAYLIB_SERVER_EXPORT WCursor : public WWrapObject void layoutChanged(); void cursorChanged(); void visibleChanged(); + void scrollFactorChanged(); + +public: + ~WCursor() override; protected: WCursor(WCursorPrivate &dd, QObject *parent = nullptr); - ~WCursor() override = default; - virtual void move(QW_NAMESPACE::qw_input_device *device, const QPointF &delta); - virtual void setPosition(QW_NAMESPACE::qw_input_device *device, const QPointF &pos); - virtual bool setPositionWithChecker(QW_NAMESPACE::qw_input_device *device, const QPointF &pos); - virtual void setScalePosition(QW_NAMESPACE::qw_input_device *device, const QPointF &ratio); + virtual void move(wlr_input_device *device, const QPointF &delta); + virtual void setPosition(wlr_input_device *device, const QPointF &pos); + virtual bool setPositionWithChecker(wlr_input_device *device, const QPointF &pos); + virtual void setScalePosition(wlr_input_device *device, const QPointF &ratio); private: friend class WSeat; @@ -105,15 +117,6 @@ class WAYLIB_SERVER_EXPORT WCursor : public WWrapObject void setSeat(WSeat *seat); bool attachInputDevice(WInputDevice *device); void detachInputDevice(WInputDevice *device); - - W_PRIVATE_SLOT(void on_swipe_begin(wlr_pointer_swipe_begin_event *event)) - W_PRIVATE_SLOT(void on_swipe_update(wlr_pointer_swipe_update_event *event)) - W_PRIVATE_SLOT(void on_swipe_end(wlr_pointer_swipe_end_event *event)) - W_PRIVATE_SLOT(void on_pinch_begin(wlr_pointer_pinch_begin_event *event)) - W_PRIVATE_SLOT(void on_pinch_update(wlr_pointer_pinch_update_event *event)) - W_PRIVATE_SLOT(void on_pinch_end(wlr_pointer_pinch_end_event *event)) - W_PRIVATE_SLOT(void on_hold_begin(wlr_pointer_hold_begin_event *event)) - W_PRIVATE_SLOT(void on_hold_end(wlr_pointer_hold_end_event *event)) }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wglobal.cpp b/waylib/src/server/kernel/wglobal.cpp index 22069b7b45..ef58d9bfdb 100644 --- a/waylib/src/server/kernel/wglobal.cpp +++ b/waylib/src/server/kernel/wglobal.cpp @@ -1,38 +1,26 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wglobal.h" -#include "wsocket.h" +#include "wscoplistener.h" #include "private/wglobal_p.h" +#include "wayliblogging.h" #include #include #include - -#ifdef QT_DEBUG -Q_LOGGING_CATEGORY(lcGeneral, "waylib.general", QtDebugMsg); -#else -Q_LOGGING_CATEGORY(lcGeneral, "waylib.general", QtInfoMsg); -#endif +#include WAYLIB_SERVER_BEGIN_NAMESPACE -WClient *WObject::waylandClient() const +WObject::WObject() + : w_d_ptr(new WObjectPrivate(this)) { - auto client = w_d_ptr->waylandClient(); - if (!client) - return nullptr; - - auto wclient = WClient::get(client); - Q_ASSERT(wclient); - - return wclient; } WObject::WObject(WObjectPrivate &dd, WObject *) : w_d_ptr(&dd) { - } int WObject::indexOfAttachedData(const void *owner) const @@ -53,192 +41,154 @@ QList> &WObject::attachedDatas() return d->attachedDatas; } -WObject::~WObject() -{ - -} - -WObjectPrivate *WObjectPrivate::get(WObject *qq) -{ - return qq->d_func(); -} - -WObjectPrivate::WObjectPrivate(WObject *qq) - : q_ptr(qq) -{ - -} -WObjectPrivate::~WObjectPrivate() +void WObject::teardown() { + W_D(WObject); -} - -WWrapObject::WWrapObject(QObject *parent) - : WWrapObject(*new WWrapObjectPrivate(this), parent) -{ - -} - -WWrapObject::WWrapObject(WWrapObjectPrivate &d, QObject *parent) - : WObject(d, nullptr) - , QObject(parent) -{ - -} - -WWrapObject::~WWrapObject() -{ - W_D(WWrapObject); - d->invalidate(); -} + // Clean up the QML engine's declarativeData before detaching listeners. + // If the QML engine has already freed QQmlData without zeroing the + // declarativeData pointer, any later Qt signal emission (doActivate) + // reads a stale pointer and crashes inside QQmlData::signalHasEndpoint(). + // teardown() runs from the most-derived destructor, i.e. before ~QObject, + // so clearing the pointer here prevents the stale read when ~QObject + // emits destroyed(). WObject is a non-QObject mixin, so only act when this + // object is also a QObject (the common case for wayland wrappers). + if (auto *obj = dynamic_cast(this)) { + auto *od = QObjectPrivate::get(obj); + if (!od->isDeletingChildren && od->declarativeData && QAbstractDeclarativeData::destroyed) { + QAbstractDeclarativeData::destroyed(od->declarativeData, obj); + od->declarativeData = nullptr; + } + } -WWrapObjectPrivate::WWrapObjectPrivate(WWrapObject *q) - : WObjectPrivate(q) - , invalidated(false) -{ + const auto targets = d->attachedListenerTargets; + d->attachedListenerTargets.clear(); -} + for (WObject *target : targets) { + if (target) + WObjectPrivate::get(target)->removeListenersInternal(this); + } -WWrapObjectPrivate::~WWrapObjectPrivate() -{ - // Must call invalidate before destroy WWrapObject - Q_ASSERT(invalidated); + for (auto it = d->attachedListenerLists.begin(); it != d->attachedListenerLists.end(); ) { + if (it->first != this) + WObjectPrivate::get(it->first)->unregisterListenerTarget(this); + delete it->second; + it = d->attachedListenerLists.erase(it); + } } -void WWrapObjectPrivate::initHandle(QW_NAMESPACE::qw_object_basic *handle) +WObject::~WObject() { - Q_ASSERT(!m_handle); - Q_ASSERT(!invalidated); - m_handle = handle; + W_D(WObject); + // Force derived classes / WListenerOwner to call teardown() before the + // base destructor runs. Leaving listeners attached here is a use-after- + // free risk once native wlroots objects are gone. + if (!d->attachedListenerLists.isEmpty() || !d->attachedListenerTargets.isEmpty()) { + qFatal("WObject %p destroyed with pending listeners " + "(lists=%d, cross-object targets=%d). " + "Call teardown() in the most-derived destructor " + "(or before tearing down native handles).", + static_cast(this), + int(d->attachedListenerLists.size()), + int(d->attachedListenerTargets.size())); + } } -static inline QObjectPrivate::Connection *getConnectionDPtr(const QMetaObject::Connection *connection) +WScopedListenerList *WObject::listeners() { - static_assert(sizeof(connection) == sizeof(void*), - "Please check how to use QMetaObject::Connection::d_ptr"); - return *reinterpret_cast(const_cast(connection)); + W_D(WObject); + for (const auto &entry : std::as_const(d->attachedListenerLists)) { + if (entry.first == this) + return entry.second; + } + auto *list = new WScopedListenerList; + d->attachedListenerLists.append({this, list}); + return list; } -void WWrapObjectPrivate::invalidate() +WScopedListenerList *WObject::listeners(WObject *owner) { - if (invalidated) - return; - invalidated = true; - - W_Q(WWrapObject); - - Q_EMIT q->aboutToBeInvalidated(); - - auto d = QObjectPrivate::get(q); - if (!d->isDeletingChildren && d->declarativeData && QAbstractDeclarativeData::destroyed) { - QAbstractDeclarativeData::destroyed(d->declarativeData, q); - d->declarativeData = nullptr; - } - - instantRelease(); - for (const auto &connection : std::as_const(connectionsWithHandle)) { - QObject::disconnect(connection); - } - if (m_handle) { - m_handle->disconnect(q); - m_handle = nullptr; + Q_ASSERT(owner); + // Self-owned listeners must go through listeners(). Passing `this` here + // is almost always a mistake that conflates the two APIs. + Q_ASSERT_X(owner != this, "WObject::listeners", + "Use listeners() for this object's own listener list; " + "listeners(owner) is only for cross-object registration"); + W_D(WObject); + WObjectPrivate::get(owner)->registerListenerTarget(this); + for (const auto &entry : std::as_const(d->attachedListenerLists)) { + if (entry.first == owner) + return entry.second; } - connectionsWithHandle.clear(); - - Q_EMIT q->invalidated(); + auto *list = new WScopedListenerList; + d->attachedListenerLists.append({owner, list}); + return list; } -bool WWrapObject::safeDisconnect(const QObject *receiver) +void WObject::removeListeners(WObject *owner) { - W_D(WWrapObject); - - bool ok = false; - for (int i = 0; i < d->connectionsWithHandle.size(); ++i) { - const QMetaObject::Connection &connection = d->connectionsWithHandle.at(i); - auto c_d = getConnectionDPtr(&connection); - if (c_d->receiver == receiver) { - if (QObject::disconnect(connection)) - ok = true; - - d->connectionsWithHandle.removeAt(i); - // reset index - --i; - } + Q_ASSERT(owner); + W_D(WObject); + if (d->removeListenersInternal(owner)) { + WObjectPrivate::get(owner)->unregisterListenerTarget(this); + return; } - if (disconnect(receiver)) - ok = true; + QStringList registeredOwners; + registeredOwners.reserve(d->attachedListenerLists.size()); + for (const auto &entry : std::as_const(d->attachedListenerLists)) + registeredOwners.append(QString::asprintf("%p", entry.first)); - return ok; + qCInfo(lcWlObject) << "removeListeners: no listener group for owner" + << QString::asprintf("%p", owner) + << "on object" << QString::asprintf("%p", this) + << "- registered owners:" << registeredOwners; } -bool WWrapObject::safeDisconnect(const QMetaObject::Connection &connection) +WObjectPrivate *WObjectPrivate::get(WObject *qq) { - W_D(WWrapObject); - int index = d->connectionsWithHandle.indexOf(connection); - if (index < 0) { - auto c_d = getConnectionDPtr(&connection); - if (c_d->sender != this) - return false; - return disconnect(connection); - } - d->connectionsWithHandle.removeAt(index); - return QObject::disconnect(connection); + return qq->d_func(); } -void WWrapObject::safeDeleteLater() +WObjectPrivate::WObjectPrivate(WObject *qq) + : q_ptr(qq) { - W_D(WWrapObject); - d->invalidate(); - deleteLater(); -} -QW_NAMESPACE::qw_object_basic *WWrapObject::handle() const -{ - W_DC(WWrapObject); - return d->m_handle; } -bool WWrapObject::isInvalidated() const -{ - W_DC(WWrapObject); - return d->invalidated; -} - -void WWrapObject::invalidate() +WObjectPrivate::~WObjectPrivate() { - W_D(WWrapObject); - d->invalidate(); -} -void WWrapObject::initHandle(QW_NAMESPACE::qw_object_basic *handle) -{ - W_D(WWrapObject); - d->initHandle(handle); } -void WWrapObject::beginSafeConnect() +void WObjectPrivate::registerListenerTarget(WObject *target) { - + if (!target || target == q_ptr) + return; + for (WObject *existing : std::as_const(attachedListenerTargets)) { + if (existing == target) + return; + } + attachedListenerTargets.append(target); } -void WWrapObject::endSafeConnect(const QMetaObject::Connection &connection) +void WObjectPrivate::unregisterListenerTarget(WObject *target) { - W_D(WWrapObject); - if (connection) - d->connectionsWithHandle.append(connection); + attachedListenerTargets.removeAll(target); } -#ifdef QT_DEBUG -bool WWrapObject::event(QEvent *event) +bool WObjectPrivate::removeListenersInternal(WObject *owner) { - if (event->type() == QEvent::DeferredDelete) { - Q_ASSERT(d_func()->invalidated); + Q_ASSERT(owner); + for (auto it = attachedListenerLists.begin(); it != attachedListenerLists.end(); ++it) { + if (it->first == owner) { + delete it->second; + attachedListenerLists.erase(it); + return true; + } } - - return QObject::event(event); + return false; } -#endif bool WGlobal::isInvalidCursor(const QCursor &c) { diff --git a/waylib/src/server/kernel/wglobal.h b/waylib/src/server/kernel/wglobal.h index 7320472d39..5553052801 100644 --- a/waylib/src/server/kernel/wglobal.h +++ b/waylib/src/server/kernel/wglobal.h @@ -1,9 +1,9 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once -#include +#include #include #include @@ -38,7 +38,7 @@ #define W_QC(Class) Q_Q(const Class) #define W_PRIVATE_SLOT(Func) Q_PRIVATE_SLOT(d_func(), Func) -#if defined(WLR_HAVE_VULKAN_RENDERER) && QT_CONFIG(vulkan) && WLR_VERSION_MINOR > 16 +#if defined(WLR_HAVE_VULKAN_RENDERER) && QT_CONFIG(vulkan) #define ENABLE_VULKAN_RENDER #endif @@ -48,20 +48,23 @@ #endif #endif -#include -#include #include #include #include #include +#include + +#include #include struct wl_client; WAYLIB_SERVER_BEGIN_NAMESPACE class WClient; + class WObjectPrivate; +class WScopedListenerList; class WAYLIB_SERVER_EXPORT WObject { public: @@ -99,7 +102,31 @@ class WAYLIB_SERVER_EXPORT WObject removeAttachedData(owner); } - WClient *waylandClient() const; + // Default construction for mixin use (e.g. QObject + WObject) without a + // dedicated *Private subclass. + WObject(); + + // Listener list for this wrapper's own native handle signals. + // Prefer this over listeners(this). + WScopedListenerList *listeners(); + + // Register wl_signal listeners on another wrapper. `owner` groups listeners + // for later removal (see removeListeners). When owner is another WObject, + // teardown() on the owner automatically detaches its listener groups from + // every target it registered on. + // + // Do NOT pass `this` here — use listeners() for this object's own + // listener list. listeners(this) is rejected at runtime. + WScopedListenerList *listeners(WObject *owner); + void removeListeners(WObject *owner); + + // Detach and release every listener list owned by this object. Safe to + // call multiple times. Derived classes that register listeners MUST call + // this in their destructor (or earlier, e.g. before destroying native + // handles). WServer::stop()/detach() also call this for interfaces that + // are WObject before WServerInterface::destroy(). ~WObject aborts if any + // listener groups or cross-object targets remain. + void teardown(); protected: WObject(WObjectPrivate &dd, WObject *parent = nullptr); @@ -115,81 +142,30 @@ class WAYLIB_SERVER_EXPORT WObject W_DECLARE_PRIVATE(WObject) }; -class WWrapObjectPrivate; -// Wrap Object in QWlroots -class WAYLIB_SERVER_EXPORT WWrapObject : public QObject, public WObject +// Lightweight owner token for WObject::listeners(owner) when the registering +// object is not itself a WObject (or should not expose WObject publicly). +// Public destructor allows std::unique_ptr. +class WAYLIB_SERVER_EXPORT WListenerOwner final : public WObject { - Q_OBJECT - -public: - QW_NAMESPACE::qw_object_basic *handle() const; - bool isInvalidated() const; - - bool safeDisconnect(const QObject *receiver); - bool safeDisconnect(const QMetaObject::Connection &connection); - - void safeDeleteLater(); - -Q_SIGNALS: - void aboutToBeInvalidated(); - void invalidated(); - public: - template - requires std::is_base_of_v::Object> - QMetaObject::Connection safeConnect(Func1 signal, const QObject *receiver, Func2 slot, Qt::ConnectionType type = Qt::AutoConnection) { - return QObject::connect(qobject_cast::Object*>(this), signal, receiver, slot, type); - } - - template - requires std::is_base_of_v::Object> - QMetaObject::Connection safeConnect(Func1 signal, const QObject *receiver, Func2 slot, Qt::ConnectionType type = Qt::AutoConnection) { - // Isn't thread safety - Q_ASSERT(QThread::currentThread() == thread()); - Q_ASSERT_X(this != receiver, "safeConnect", - "Not need to use safeConnect for the signal of self's handle object," - " Please use QObject::connect()."); - auto h = qobject_cast::Object*>(handle()); - Q_ASSERT(h); - if constexpr (std::is_same_v) { - if (signal == &qw_object_basic::before_destroy) { - return QObject::connect(h, signal, receiver, slot, type); - } - } - beginSafeConnect(); - auto connection = QObject::connect(h, signal, receiver, slot, type); - endSafeConnect(connection); - - return connection; - } - -protected: - WWrapObject(QObject *parent = nullptr); - WWrapObject(WWrapObjectPrivate &dd, QObject *parent = nullptr); - virtual ~WWrapObject() override; - using QObject::connect; - using QObject::disconnect; - using QObject::deleteLater; - - void invalidate(); - void initHandle(QW_NAMESPACE::qw_object_basic *handle); - - void beginSafeConnect(); - void endSafeConnect(const QMetaObject::Connection &connection); - -#ifdef QT_DEBUG - bool event(QEvent *event) override; -#endif - - W_DECLARE_PRIVATE(WWrapObject) + WListenerOwner() : WObject() {} + // unique_ptr-friendly public dtor; always clear listener ownership. + ~WListenerOwner() { teardown(); } }; class WAYLIB_SERVER_EXPORT WGlobal { Q_GADGET - QML_NAMED_ELEMENT(Waylib) + QML_VALUE_TYPE(wglobal) QML_UNCREATABLE("Use for enums") public: + enum class ColorContentsMode { + DontCare, + Clear, + Preserve, + }; + Q_ENUM(ColorContentsMode) + enum class CursorShape { Default = Qt::CustomCursor + 1, Invalid, @@ -237,7 +213,9 @@ class WAYLIB_SERVER_EXPORT WGlobal { ColResize, RowResize, ZoomIn, - ZoomOut + ZoomOut, + DndAsk, + AllResize }; Q_ENUM(CursorShape) static_assert(CursorShape::BottomLeftCorner > CursorShape::Default, ""); @@ -246,4 +224,11 @@ class WAYLIB_SERVER_EXPORT WGlobal { static bool isClientResourceCursor(const QCursor &c); }; +struct Q_DECL_HIDDEN WCursorShapeQMLProxy { + Q_GADGET + QML_NAMED_ELEMENT(CursorShape) + QML_FOREIGN_NAMESPACE(WAYLIB_SERVER_NAMESPACE::WGlobal) + QML_UNCREATABLE("Use for enums") +}; + WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/winputdevice.cpp b/waylib/src/server/kernel/winputdevice.cpp index 21c45a1613..5ae1d64efd 100644 --- a/waylib/src/server/kernel/winputdevice.cpp +++ b/waylib/src/server/kernel/winputdevice.cpp @@ -1,61 +1,147 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "winputdevice.h" #include "wseat.h" +#include "wscoplistener.h" #include "private/wglobal_p.h" +#include "wayliblogging.h" -#include - +#include #include +#include #include #include +#include +#include #include -QW_USE_NAMESPACE +#include + WAYLIB_SERVER_BEGIN_NAMESPACE -class Q_DECL_HIDDEN WInputDevicePrivate : public WWrapObjectPrivate +// DeviceInfoParser implementation +DeviceInfoParser& DeviceInfoParser::instance() +{ + static DeviceInfoParser parser; + return parser; +} + +void DeviceInfoParser::refreshDeviceInfo() +{ + QMutexLocker locker(&m_mutex); + m_deviceMap.clear(); + + QFile procFile("/proc/bus/input/devices"); + if (!procFile.open(QIODevice::ReadOnly)) { + return; + } + + QString content = procFile.readAll(); + QStringList blocks = content.split("\n\n", Qt::SkipEmptyParts); + + for (const QString& block : std::as_const(blocks)) { + parseDeviceBlock(block.trimmed()); + } +} + +void DeviceInfoParser::parseDeviceBlock(const QString& block) +{ + static const QRegularExpression nameRegex("Name=\"([^\"]+)\""); + ProcDeviceInfo info; + QStringList lines = block.split('\n'); + + for (const QString& line : std::as_const(lines)) { + if (line.startsWith("N: Name=")) { + auto match = nameRegex.match(line); + if (match.hasMatch()) { + info.name = match.captured(1); + } + } + else if (line.startsWith("P: Phys=")) { + info.physPath = line.mid(8); + } + } + + if (info.isValid()) { + m_deviceMap[info.name] = info; + } +} + +QString DeviceInfoParser::getPhysicalPath(const QString& deviceName) +{ + QMutexLocker locker(&m_mutex); + if (!m_deviceMap.contains(deviceName)) { + locker.unlock(); + refreshDeviceInfo(); + locker.relock(); + } + + return m_deviceMap.value(deviceName).physPath; +} + +class Q_DECL_HIDDEN WInputDevicePrivate : public WObjectPrivate { public: - WInputDevicePrivate(WInputDevice *qq, void *handle) - : WWrapObjectPrivate(qq) + WInputDevicePrivate(WInputDevice *qq, wlr_input_device *handle, bool _isVirtual) + : WObjectPrivate(qq) + , isVirtual(_isVirtual) + , m_handle(handle) { - initHandle(reinterpret_cast(handle)); - this->handle()->set_data(this, qq); + Q_ASSERT(handle); + handle->data = qq; } - void instantRelease() override { - handle()->set_data(nullptr, nullptr); - if (seat) - seat->detachInputDevice(q_func()); + inline wlr_input_device *handle() const { + return m_handle; } - WWRAP_HANDLE_FUNCTIONS(qw_input_device, wlr_input_device) - - W_DECLARE_PUBLIC(WInputDevice); + W_DECLARE_PUBLIC(WInputDevice) QPointer qtDevice; QPointer hoverTarget; WSeat *seat = nullptr; + bool isVirtual = false; + +private: + // The backend owns this handle and destroys it after notifying the + // wrapper. Keep the address stable through that callback. + wlr_input_device *m_handle = nullptr; }; -WInputDevice::WInputDevice(qw_input_device *handle) - : WWrapObject(*new WInputDevicePrivate(this, handle)) +WInputDevice::WInputDevice(wlr_input_device *handle, bool isVirtual) + : QObject(nullptr) + , WObject(*new WInputDevicePrivate(this, handle, isVirtual)) { +} +WInputDevice::~WInputDevice() +{ + teardown(); + W_D(WInputDevice); + // Clear the reverse fromHandle() mapping while the native handle is + // still alive (owner teardown deletes this wrapper before the native + // device is destroyed, or from its destroy callback). + if (d->m_handle && d->m_handle->data == this) + d->m_handle->data = nullptr; + // Detach from the seat this device was attached to (owner teardown; + // the native handle is still alive here). + if (d->seat) + d->seat->detachInputDevice(this); } -qw_input_device *WInputDevice::handle() const +wlr_input_device *WInputDevice::handle() const { W_DC(WInputDevice); return d->handle(); } -WInputDevice *WInputDevice::fromHandle(const qw_input_device *handle) +WInputDevice *WInputDevice::fromHandle(wlr_input_device *handle) { - return handle->get_data(); + if (!handle) + return nullptr; + return static_cast(handle->data); } WInputDevice *WInputDevice::from(const QInputDevice *device) @@ -69,7 +155,7 @@ WInputDevice::Type WInputDevice::type() const { W_DC(WInputDevice); - switch (d->nativeHandle()->type) { + switch (d->handle()->type) { case WLR_INPUT_DEVICE_KEYBOARD: return Type::Keyboard; case WLR_INPUT_DEVICE_POINTER: return Type::Pointer; case WLR_INPUT_DEVICE_TOUCH: return Type::Touch; @@ -78,15 +164,34 @@ WInputDevice::Type WInputDevice::type() const case WLR_INPUT_DEVICE_SWITCH: return Type::Switch; } - // TODO: use qCWarning - qWarning("Unknow input device type %i\n", d->nativeHandle()->type); + qCWarning(lcWlInput) << "Unknown input device type:" << d->handle()->type + << "from device:" << QString::fromUtf8(d->handle()->name); return Type::Unknow; } +QString WInputDevice::name() const +{ + W_DC(WInputDevice); + + if (d->handle() && d->handle()->name) { + return QString::fromUtf8(d->handle()->name); + } + + if (d->qtDevice) { + return d->qtDevice->name(); + } + + return QString(); +} + void WInputDevice::setSeat(WSeat *seat) { W_D(WInputDevice); - d->seat = seat; + if (d->seat != seat) { + qCDebug(lcWlInput) << "Input device" << QString::fromUtf8(d->handle()->name) + << "assigned to seat:" << (seat ? seat->name() : QString("(null)")); + d->seat = seat; + } } WSeat *WInputDevice::seat() const @@ -98,7 +203,12 @@ WSeat *WInputDevice::seat() const void WInputDevice::setQtDevice(QInputDevice *device) { W_D(WInputDevice); - d->qtDevice = device; + if (d->qtDevice != device) { + qCDebug(lcWlInput) << "Qt device" << (device ? device->name() : QString("(null)")) + << "associated with input device:" + << QString::fromUtf8(d->handle()->name); + d->qtDevice = device; + } } QInputDevice *WInputDevice::qtDevice() const @@ -107,16 +217,82 @@ QInputDevice *WInputDevice::qtDevice() const return d->qtDevice; } +QString WInputDevice::devicePath() const +{ + W_DC(WInputDevice); + if (d->handle() && wlr_input_device_is_libinput(d->handle())) { + if (auto libinputDevice = wlr_libinput_get_device_handle(d->handle())) { + if (auto udevDevice = libinput_device_get_udev_device(libinputDevice)) { + auto deviceGuard = qScopeGuard([udevDevice] { udev_device_unref(udevDevice); }); + + const char* physPath = udev_device_get_property_value(udevDevice, "PHYS"); + if (physPath) { + return QString::fromUtf8(physPath); + } + const char* devPath = udev_device_get_property_value(udevDevice, "DEVPATH"); + if (devPath) { + QString fullDevPath = QString::fromUtf8(devPath); + static const QRegularExpression usbRegex( + QStringLiteral("/devices/pci\\d+:\\d+/(\\d+:\\d+:\\d+\\.\\d+)/usb\\d+/1-\\d+/1-(\\d+\\.\\d+)/")); + auto match = usbRegex.match(fullDevPath); + if (match.hasMatch()) { + return QString("usb-%1-%2/input0").arg(match.captured(1)).arg(match.captured(2)); + } + } + } + } + } + QString deviceName = name(); + QString procPhysPath = DeviceInfoParser::instance().getPhysicalPath(deviceName); + if (!procPhysPath.isEmpty()) { + return procPhysPath; + } + return QString(); +} + +bool WInputDevice::isVirtual() const +{ + W_DC(WInputDevice); + + return d->isVirtual; +} + +WInputDevice::LibinputPointerType WInputDevice::libinputPointerType() const +{ + if (!wlr_input_device_is_libinput(handle())) { + return LibinputPointerType::Unknown; + } + + struct libinput_device *inputDevice = wlr_libinput_get_device_handle(handle()); + struct udev_device *udevDevice = libinput_device_get_udev_device(inputDevice); + + if (udev_device_get_property_value(udevDevice, "ID_INPUT_MOUSE")) { + return LibinputPointerType::Mouse; + } + + if (udev_device_get_property_value(udevDevice, "ID_INPUT_TOUCHPAD")) { + return LibinputPointerType::TouchPad; + } + + return LibinputPointerType::Unknown; +} + void WInputDevice::setExclusiveGrabber(QObject *grabber) { W_D(WInputDevice); auto pointerDevice = qobject_cast(d->qtDevice); - if (!pointerDevice) + if (!pointerDevice) { + qCDebug(lcWlInput) << "Cannot set exclusive grabber: device is not a pointing device"; return; + } auto dd = QPointingDevicePrivate::get(pointerDevice); - if (dd->activePoints.isEmpty()) + if (dd->activePoints.isEmpty()) { + qCDebug(lcWlInput) << "Cannot set exclusive grabber: no active points"; return; + } auto firstPoint = dd->activePoints.values().first(); + qCDebug(lcWlInput) << "Setting exclusive grabber" << grabber + << "for device:" << QString::fromUtf8(d->handle()->name); dd->setExclusiveGrabber(nullptr, firstPoint.eventPoint, grabber); } diff --git a/waylib/src/server/kernel/winputdevice.h b/waylib/src/server/kernel/winputdevice.h index e94c9b5f6b..98650155e3 100644 --- a/waylib/src/server/kernel/winputdevice.h +++ b/waylib/src/server/kernel/winputdevice.h @@ -1,15 +1,13 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include #include -#include - -QW_BEGIN_NAMESPACE -class qw_input_device; -QW_END_NAMESPACE +#include +#include QT_BEGIN_NAMESPACE class QInputDevice; @@ -20,7 +18,34 @@ WAYLIB_SERVER_BEGIN_NAMESPACE class WSeat; class WInputDevicePrivate; -class WAYLIB_SERVER_EXPORT WInputDevice : public WWrapObject +class WBackendPrivate; +class WInputMethodHelper; + +// Internal helper for parsing /proc/bus/input/devices +struct ProcDeviceInfo { + QString name; + QString physPath; + + bool isValid() const { + return !name.isEmpty() && !physPath.isEmpty(); + } +}; + +class DeviceInfoParser { +public: + static DeviceInfoParser& instance(); + + QString getPhysicalPath(const QString& deviceName); + +private: + DeviceInfoParser() = default; + void refreshDeviceInfo(); + void parseDeviceBlock(const QString& block); + + QMap m_deviceMap; + QMutex m_mutex; +}; +class WAYLIB_SERVER_EXPORT WInputDevice : public QObject, public WObject { W_DECLARE_PRIVATE(WInputDevice) public: @@ -35,11 +60,19 @@ class WAYLIB_SERVER_EXPORT WInputDevice : public WWrapObject }; Q_ENUM(Type) - WInputDevice(QW_NAMESPACE::qw_input_device *handle); + enum class LibinputPointerType { + Unknown, + Mouse, + TouchPad, + }; + Q_ENUM(LibinputPointerType) - QW_NAMESPACE::qw_input_device *handle() const; + WInputDevice(wlr_input_device *handle, bool isVirtual = false); + ~WInputDevice() override; - static WInputDevice *fromHandle(const QW_NAMESPACE::qw_input_device *handle); + wlr_input_device *handle() const; + + static WInputDevice *fromHandle(wlr_input_device *handle); template inline QInputDevice *qtDevice() const { @@ -49,20 +82,30 @@ class WAYLIB_SERVER_EXPORT WInputDevice : public WWrapObject static WInputDevice *from(const QInputDevice *device); Type type() const; + QString name() const; void setSeat(WSeat *seat); WSeat *seat() const; + QString devicePath() const; + + bool isVirtual() const; + LibinputPointerType libinputPointerType() const; private: friend class QWlrootsIntegration; friend class WSeat; friend class WSeatPrivate; + friend class WBackendPrivate; + friend class WInputMethodHelper; void setQtDevice(QInputDevice *device); - - void setExclusiveGrabber(QObject *grabber); QObject *exclusiveGrabber() const; + void setExclusiveGrabber(QObject *grabber); QObject *hoverTarget() const; void setHoverTarget(QObject *object); + + // Owned by the backend/seat: released with `delete` from the native + // destroy callback, never with deleteLater(). + using QObject::deleteLater; }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wlr_all.h b/waylib/src/server/kernel/wlr_all.h new file mode 100644 index 0000000000..8715c29660 --- /dev/null +++ b/waylib/src/server/kernel/wlr_all.h @@ -0,0 +1,188 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +// Feature flags for guarding wlroots headers that only exist (or only +// compile) when the corresponding feature is enabled in the wlroots build. +// wconfig.h is part of the waylib public API surface (generated from the +// wlroots CMake export, installed alongside these headers), so the macros +// are visible in every translation unit that includes this header, even +// when it is pulled in directly (without wglobal.h). +#include + +// Unified C++ wrapper for the wlroots C API. +// +// wlroots 0.19 headers do not guard themselves with extern "C" (unlike most +// C libraries), so every C++ translation unit that uses wlroots must include +// the wlroots headers inside an extern "C" block. This header is that single +// point of entry: include instead of individual headers. +// +// It also works around C++ keywords used as struct field names in a few +// wlroots headers ("namespace" in wlr_layer_shell_v1.h, "class" in +// wlr/xwayland/xwayland.h, "delete" in wlr_input_method_v2.h). The macros are +// #undef'd right after each include: field access in waylib code uses the +// expanded names (scope/_class/_delete). + +// Qt's legacy "slots"/"signals" macros (defined unless QT_NO_KEYWORDS / +// QT_NO_SIGNALS_SLOTS_KEYWORDS is set) collide with wlroots struct field +// names (e.g. wlr_swapchain_slot slots[]). Undef them around the includes +// and restore afterwards so TU-local Qt keyword usage keeps working. TUs +// built with QT_NO_SIGNALS_SLOTS_KEYWORDS (waylib itself) skip this. +#if defined(slots) && !defined(QT_NO_SIGNALS_SLOTS_KEYWORDS) +#define WLRINC_HAD_SLOTS_MACRO +#undef slots +#endif +#if defined(signals) && !defined(QT_NO_SIGNALS_SLOTS_KEYWORDS) +#define WLRINC_HAD_SIGNALS_MACRO +#undef signals +#endif + +// C99 allows 'static' as an array-size hint in parameter declarations (e.g. +// float matrix[static 9]), but this is not valid C++ syntax. Under +// extern "C" the C++ compiler still parses the declaration, so we must +// hide the keyword for the duration of the wlroots includes. +#define static +#ifdef __cplusplus +extern "C" { +#endif + + +#include +#include +#include +#if defined(WLR_HAVE_LIBINPUT_BACKEND) +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if defined(WLR_HAVE_GLES2_RENDERER) +#include +#endif +#include +#include +#include +#if defined(WLR_HAVE_VULKAN_RENDERER) +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// "namespace" is a C++ keyword; wlr_layer_surface_v1 uses it as a field name. +#define namespace scope +#include +#undef namespace + +// "class" is a C++ keyword; wlr_xwayland_surface uses it as a field name. +// wlr/xwayland/xwayland.h pulls in xcb.h -> pthread.h, and glibc's pthread +// header declares C++ cleanup classes, so pthread.h must be parsed before +// the redefinition macro below (its include guard then keeps it from being +// re-expanded inside the macro block). +#if defined(WLR_HAVE_XWAYLAND) +#include +// The class macro below must never see pthread.h's C++ cleanup classes; +// it is only safe because the include guard keeps the already-parsed header +// from being re-expanded. Enforce the ordering so a future include reorder +// fails loudly instead of silently corrupting C++ declarations. +#ifndef _PTHREAD_H +#error "wlr_all.h: must be included before the 'class' redefinition block (xcb.h pulls it in transitively)" +#endif +#define class _class +#include +#include +#include +#include +#undef class +#endif + +// "delete" is a C++ keyword; wlr_input_method_v2 uses it as a field name. +#define delete _delete +#include +#undef delete + +// Vendored wlroots extension (implemented in buffer.c): live buffer count for +// shutdown leak assertions. +size_t waylib_buffer_get_count(void); + +#ifdef __cplusplus +} +#endif +#undef static + + +#ifdef WLRINC_HAD_SLOTS_MACRO +#define slots Q_SLOTS +#undef WLRINC_HAD_SLOTS_MACRO +#endif +#ifdef WLRINC_HAD_SIGNALS_MACRO +#define signals Q_SIGNALS +#undef WLRINC_HAD_SIGNALS_MACRO +#endif diff --git a/waylib/src/server/kernel/wlr_fwd.h b/waylib/src/server/kernel/wlr_fwd.h new file mode 100644 index 0000000000..9ed5bf7408 --- /dev/null +++ b/waylib/src/server/kernel/wlr_fwd.h @@ -0,0 +1,189 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// Aggregate forward declarations for every wlroots struct tag, companion to +// wlr_all.h (which provides the full definitions). Include this header +// instead of sprinkling `struct wlr_xxx;` declarations across waylib and +// treeland headers — declarations are free at compile time (no definition is +// expanded), so declaring everything once keeps every header self-contained +// without pulling in heavy wlr_* headers. +// +// Note: forward declarations have no linkage semantics, so no extern "C" +// guard is needed here (unlike wlr_all.h, which includes the definitions). + +#pragma once + +struct wlr_addon; +struct wlr_addon_interface; +struct wlr_addon_set; +struct wlr_allocator; +struct wlr_allocator_interface; +struct wlr_alpha_modifier_surface_v1_state; +struct wlr_alpha_modifier_v1; +struct wlr_backend; +struct wlr_backend_impl; +struct wlr_backend_output_state; +struct wlr_box; +struct wlr_buffer; +struct wlr_buffer_impl; +struct wlr_buffer_pass_options; +struct wlr_buffer_resource_interface; +struct wlr_client_buffer; +struct wlr_color_management_v1; +struct wlr_compositor; +struct wlr_cursor; +struct wlr_cursor_shape_manager_v1; +struct wlr_data_control_manager_v1; +struct wlr_data_device; +struct wlr_data_device_manager; +struct wlr_data_source; +struct wlr_dmabuf_attributes; +struct wlr_drag; +struct wlr_drm_backend; +struct wlr_drm_connector; +struct wlr_drm_format; +struct wlr_drm_format_set; +struct wlr_export_dmabuf_manager_v1; +struct wlr_ext_foreign_toplevel_handle_v1; +struct wlr_ext_foreign_toplevel_handle_v1_state; +struct wlr_ext_foreign_toplevel_list_v1; +struct wlr_ext_foreign_toplevel_list_v1_clients; +struct wlr_ext_foreign_toplevel_list_v1_outputs; +struct wlr_ext_image_capture_copy_frame_v1; +struct wlr_ext_image_capture_source_v1; +struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1; +struct wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request; +struct wlr_foreign_toplevel_manager_v1; +struct wlr_foreign_toplevel_handle_v1; +struct wlr_gamma_control_manager_v1; +struct wlr_gamma_control_v1; +struct wlr_gles2_renderer; +struct wlr_headless_backend; +struct wlr_idle_inhibit_manager_v1; +struct wlr_idle_inhibitor_v1; +struct wlr_idle_notifier_v1; +struct wlr_input_device; +struct wlr_input_device_impl; +struct wlr_input_method_keyboard_grab_v2; +struct wlr_input_method_manager_v2; +struct wlr_input_method_v2; +struct wlr_input_method_v2_state; +struct wlr_input_popup_surface_v2; +struct wlr_keyboard; +struct wlr_keyboard_group; +struct wlr_keyboard_modifiers; +struct wlr_keyboard_shortcuts_inhibitor_v1; +struct wlr_keyboard_shortcuts_inhibit_manager_v1; +struct wlr_layer_shell_v1; +struct wlr_layer_surface_v1; +struct wlr_layer_surface_v1_state; +struct wlr_linux_dmabuf_feedback_v1; +struct wlr_linux_dmabuf_v1; +struct wlr_linux_dmabuf_v1_buffer; +struct wlr_output; +struct wlr_output_configuration_v1; +struct wlr_output_configuration_head_v1; +struct wlr_output_cursor; +struct wlr_output_damage; +struct wlr_output_layout; +struct wlr_output_layer; +struct wlr_output_layer_state; +struct wlr_output_management_v1; +struct wlr_output_manager_v1; +struct wlr_output_mode; +struct wlr_output_power_manager_v1; +struct wlr_output_power_v1_set_mode_event; +struct wlr_output_state; +struct wlr_pointer; +struct wlr_pointer_axis_event; +struct wlr_pointer_button_event; +struct wlr_pointer_constraint_v1; +struct wlr_pointer_constraints_v1; +struct wlr_pointer_gestures_v1; +struct wlr_pointer_hold_begin_event; +struct wlr_pointer_hold_end_event; +struct wlr_pointer_motion_absolute_event; +struct wlr_pointer_motion_event; +struct wlr_pointer_pinch_begin_event; +struct wlr_pointer_pinch_end_event; +struct wlr_pointer_pinch_update_event; +struct wlr_pointer_swipe_begin_event; +struct wlr_pointer_swipe_end_event; +struct wlr_pointer_swipe_update_event; +struct wlr_presentation; +struct wlr_primary_selection_v1_device_manager; +struct wlr_primary_selection_v1_source; +struct wlr_relative_pointer_manager_v1; +struct wlr_relative_pointer_v1; +struct wlr_renderer; +struct wlr_renderer_impl; +struct wlr_scene; +struct wlr_scene_buffer; +struct wlr_scene_node; +struct wlr_scene_rect; +struct wlr_scene_surface; +struct wlr_scene_tree; +struct wlr_screencopy_manager_v1; +struct wlr_seat; +struct wlr_seat_client; +struct wlr_seat_keyboard_grab; +struct wlr_seat_pointer_request_set_cursor_event; +struct wlr_security_context_manager_v1; +struct wlr_security_context_v1; +struct wlr_session; +struct wlr_session_lock_manager_v1; +struct wlr_session_lock_surface_v1; +struct wlr_session_lock_v1; +struct wlr_shm; +struct wlr_shm_attributes; +struct wlr_single_pixel_buffer_v1; +struct wlr_single_pixel_buffer_manager_v1; +struct wlr_subcompositor; +struct wlr_subsurface; +struct wlr_surface; +struct wlr_surface_state; +struct wlr_swapchain; +struct wlr_swapchain_slot; +struct wlr_tablet_pad; +struct wlr_tablet_pad_gesture; +struct wlr_tablet_tool; +struct wlr_tablet_tool_axis_event; +struct wlr_tablet_tool_button_event; +struct wlr_tablet_tool_proximity_event; +struct wlr_tablet_tool_tip_event; +struct wlr_tablet_v2; +struct wlr_tablet_v2_tablet; +struct wlr_text_input_manager_v3; +struct wlr_text_input_v3; +struct wlr_text_input_v3_state; +struct wlr_texture; +struct wlr_texture_impl; +struct wlr_touch; +struct wlr_touch_cancel_event; +struct wlr_touch_down_event; +struct wlr_touch_motion_event; +struct wlr_touch_up_event; +struct wlr_virtual_keyboard_manager_v1; +struct wlr_virtual_keyboard_v1; +struct wlr_vulkan_renderer; +struct wlr_vulkan_texture; +struct wlr_xcursor; +struct wlr_xcursor_manager; +struct wlr_xdg_decoration_manager_v1; +struct wlr_xdg_dialog_manager_v1; +struct wlr_xdg_dialog_v1; +struct wlr_xdg_foreign_registry; +struct wlr_xdg_foreign_v1; +struct wlr_xdg_foreign_v2; +struct wlr_xdg_output_manager_v1; +struct wlr_xdg_popup; +struct wlr_xdg_popup_grab; +struct wlr_xdg_shell; +struct wlr_xdg_surface; +struct wlr_xdg_toplevel; +struct wlr_xdg_toplevel_tag_manager_v1; +struct wlr_xdg_toplevel_tag_v1; +struct wlr_xdg_wm_dialog_v1; +struct wlr_xwayland; +struct wlr_xwayland_surface; +struct wlr_xwayland_surface_state; diff --git a/waylib/src/server/kernel/woutput.cpp b/waylib/src/server/kernel/woutput.cpp index 44f3cf54b3..a30dbab689 100644 --- a/waylib/src/server/kernel/woutput.cpp +++ b/waylib/src/server/kernel/woutput.cpp @@ -1,23 +1,20 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include #include "woutput.h" #include "wbackend.h" #include "wcursor.h" #include "wseat.h" +#include "woutputlayout.h" +#include "wscoplistener.h" #include "wtools.h" #include "platformplugin/qwlrootscreen.h" #include "private/wglobal_p.h" +#include "wayliblogging.h" -#include -#include -#include -#include -#include -#include -#include +#include -#include #include #include #include @@ -25,82 +22,96 @@ #include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE -Q_LOGGING_CATEGORY(qLcOutput, "waylib.server.output", QtWarningMsg) - -class Q_DECL_HIDDEN WOutputPrivate : public WWrapObjectPrivate +class Q_DECL_HIDDEN WOutputPrivate : public WObjectPrivate { public: - WOutputPrivate(WOutput *qq, qw_output *handle) - : WWrapObjectPrivate(qq) + WOutputPrivate(WOutput *qq, wlr_output *handle) + : WObjectPrivate(qq) + , m_handle(handle) { - initHandle(handle); - this->handle()->set_data(this, qq); + Q_ASSERT(handle); + handle->data = qq; } - void instantRelease() override { - handle()->set_data(nullptr, nullptr); - if (layout) - layout->remove(q_func()); + inline wlr_output *handle() const { + return m_handle; } - WWRAP_HANDLE_FUNCTIONS(qw_output, wlr_output) - inline QSize size() const { Q_ASSERT(handle()); - return QSize(nativeHandle()->width, nativeHandle()->height); + return QSize(handle()->width, handle()->height); } inline WOutput::Transform orientation() const { - return static_cast(nativeHandle()->transform); + return static_cast(handle()->transform); } W_DECLARE_PUBLIC(WOutput) - bool forceSoftwareCursor = false; + QWlrootsScreen *screen = nullptr; QQuickWindow *window = nullptr; WBackend *backend = nullptr; WOutputLayout *layout = nullptr; + +private: + // The backend owns this handle and destroys it after notifying the + // wrapper. Keep the address stable through that callback. + wlr_output *m_handle = nullptr; }; -WOutput::WOutput(qw_output *handle, WBackend *backend) - : WWrapObject(*new WOutputPrivate(this, handle)) +WOutput::WOutput(wlr_output *handle, WBackend *backend) + : QObject(nullptr) + , WObject(*new WOutputPrivate(this, handle)) { - d_func()->backend = backend; - connect(handle, qOverload(&qw_output::notify_commit), - this, [this] (wlr_output_event_commit *event) { + W_D(WOutput); + d->backend = backend; + listeners()->add(&handle->events.commit, this, + [this] (wlr_output_event_commit *event) { if (event->state->committed & WLR_OUTPUT_STATE_SCALE) { - Q_EMIT this->scaleChanged(); - Q_EMIT this->effectiveSizeChanged(); + Q_EMIT scaleChanged(); + Q_EMIT effectiveSizeChanged(); } if (event->state->committed & WLR_OUTPUT_STATE_MODE) { - Q_EMIT this->modeChanged(); - Q_EMIT this->transformedSizeChanged(); - Q_EMIT this->effectiveSizeChanged(); + Q_EMIT modeChanged(); + Q_EMIT transformedSizeChanged(); + Q_EMIT effectiveSizeChanged(); } if (event->state->committed & WLR_OUTPUT_STATE_TRANSFORM) { - Q_EMIT this->orientationChanged(); - Q_EMIT this->transformedSizeChanged(); - Q_EMIT this->effectiveSizeChanged(); + Q_EMIT orientationChanged(); + Q_EMIT transformedSizeChanged(); + Q_EMIT effectiveSizeChanged(); } if (event->state->committed & WLR_OUTPUT_STATE_BUFFER) - Q_EMIT this->bufferCommitted(); + Q_EMIT bufferCommitted(); if (event->state->committed & WLR_OUTPUT_STATE_ENABLED) - Q_EMIT this->enabledChanged(); + Q_EMIT enabledChanged(); + + if (event->state->committed & WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED) + Q_EMIT adaptiveSyncEnabledChanged(); }); } WOutput::~WOutput() { - + teardown(); + W_D(WOutput); + Q_EMIT beforeDestroy(); + // Clear the reverse fromHandle() mapping while the native handle is + // still alive (owner teardown deletes this wrapper before the native + // output is destroyed, or from its destroy callback). + if (d->m_handle && d->m_handle->data == this) + d->m_handle->data = nullptr; + // Drop from the layout (owner teardown with a live handle included). + if (d->layout) + d->layout->remove(this); } WBackend *WOutput::backend() const @@ -115,22 +126,22 @@ WServer *WOutput::server() const return d->backend->server(); } -qw_renderer *WOutput::renderer() const +wlr_renderer *WOutput::renderer() const { W_DC(WOutput); - return qw_renderer::from(d->nativeHandle()->renderer); + return d->handle()->renderer; } -qw_swapchain *WOutput::swapchain() const +wlr_swapchain *WOutput::swapchain() const { W_DC(WOutput); - return qw_swapchain::from(d->nativeHandle()->swapchain); + return d->handle()->swapchain; } -qw_allocator *WOutput::allocator() const +wlr_allocator *WOutput::allocator() const { W_DC(WOutput); - return qw_allocator::from(d->nativeHandle()->allocator); + return d->handle()->allocator; } // Copy from wlroots @@ -179,7 +190,7 @@ static bool wlr_drm_format_add(struct wlr_drm_format *fmt, uint64_t modifier) { uint64_t *new_modifiers = reinterpret_cast(realloc(fmt->modifiers, sizeof(*fmt->modifiers) * capacity)); if (!new_modifiers) { - qCritical("Allocation failed"); + qCCritical(lcWlOutputBuffer) << "Failed to allocate memory for DRM format modifiers"; return false; } @@ -227,20 +238,19 @@ static bool output_pick_format(struct wlr_output *output, const struct wlr_drm_format_set *display_formats, struct wlr_drm_format *format, uint32_t fmt) { struct wlr_renderer *renderer = output->renderer; - struct wlr_allocator *allocator = output->allocator; - assert(renderer != NULL && allocator != NULL); + assert(renderer != NULL && output->allocator != NULL); const struct wlr_drm_format_set *render_formats = wlr_renderer_get_render_formats(renderer); if (render_formats == NULL) { - qCritical("Failed to get render formats"); + qCCritical(lcWlOutputDrm) << "Failed to get renderer format support information"; return false; } const struct wlr_drm_format *render_format = wlr_drm_format_set_get(render_formats, fmt); if (render_format == NULL) { - qDebug("Renderer doesn't support format 0x%" PRIX32, fmt); + qCDebug(lcWlOutputDrm) << "Renderer does not support format:" << QString("0x%1").arg(fmt, 0, 16); return false; } @@ -248,13 +258,13 @@ static bool output_pick_format(struct wlr_output *output, const struct wlr_drm_format *display_format = wlr_drm_format_set_get(display_formats, fmt); if (display_format == NULL) { - qDebug("Output doesn't support format 0x%" PRIX32, fmt); + qCDebug(lcWlOutputDrm) << "Output does not support format:" << QString("0x%1").arg(fmt, 0, 16); return false; } if (!wlr_drm_format_intersect(format, display_format, render_format)) { - qDebug("Failed to intersect display and render " - "modifiers for format 0x%" PRIX32 " on output %s", - fmt, output->name); + qCWarning(lcWlOutputDrm) << "Failed to find compatible format modifiers for format" + << QString("0x%1").arg(fmt, 0, 16) + << "on output:" << QString::fromUtf8(output->name); return false; } } else { @@ -265,8 +275,10 @@ static bool output_pick_format(struct wlr_output *output, } if (format->len == 0) { - wlr_drm_format_finish(format); - qDebug("Failed to pick output format"); + // The caller owns `format` through WDrmFormat RAII, which finishes + // it on scope exit; an explicit finish here would double-free the + // modifiers buffer. + qCWarning(lcWlOutputDrm) << "No compatible output format found"; return false; } @@ -282,36 +294,34 @@ static struct wlr_swapchain *create_swapchain(struct wlr_output *output, const struct wlr_drm_format_set *display_formats = wlr_output_get_primary_formats(output, allocator->buffer_caps); - struct wlr_drm_format format = {0}; - if (!output_pick_format(output, display_formats, &format, render_format)) { - qDebug("Failed to pick primary buffer format for output '%s'", - output->name); + WDrmFormat format; + if (!output_pick_format(output, display_formats, format.get(), render_format)) { + qCWarning(lcWlOutputBuffer) << "Failed to pick primary buffer format for output:" << QString::fromUtf8(output->name); return NULL; } - char *format_name = drmGetFormatName(format.format); - qDebug("Choosing primary buffer format %s (0x%08" PRIX32 ") for output '%s'", - format_name ? format_name : "", format.format, output->name); + char *format_name = drmGetFormatName(format->format); + qCInfo(lcWlOutputBuffer) << "Selected primary buffer format:" + << (format_name ? QString::fromUtf8(format_name) : QString("")) + << QString("(0x%1)").arg(format->format, 8, 16, QLatin1Char('0')) + << "for output:" << QString::fromUtf8(output->name); free(format_name); - if (!allow_modifiers && (format.len != 1 || format.modifiers[0] != DRM_FORMAT_MOD_LINEAR)) { - if (!wlr_drm_format_has(&format, DRM_FORMAT_MOD_INVALID)) { - qDebug("Implicit modifiers not supported"); - wlr_drm_format_finish(&format); - return NULL; + if (!allow_modifiers && (format->len != 1 || format->modifiers[0] != DRM_FORMAT_MOD_LINEAR)) { + if (!wlr_drm_format_has(format.get(), DRM_FORMAT_MOD_INVALID)) { + qCWarning(lcWlOutputDrm) << "No support for implicit modifiers"; + return NULL; } - format.len = 0; - if (!wlr_drm_format_add(&format, DRM_FORMAT_MOD_INVALID)) { - qDebug("Failed to add implicit modifier to format"); - wlr_drm_format_finish(&format); - return NULL; + format->len = 0; + if (!wlr_drm_format_add(format.get(), DRM_FORMAT_MOD_INVALID)) { + qCWarning(lcWlOutputDrm) << "Failed to add implicit modifier to DRM format"; + return NULL; } } - struct wlr_swapchain *swapchain = wlr_swapchain_create(allocator, width, height, &format); - wlr_drm_format_finish(&format); - return swapchain; + struct wlr_swapchain *swapchain = wlr_swapchain_create(allocator, width, height, format.get()); + return swapchain; } static bool test_swapchain(struct wlr_output *output, @@ -332,9 +342,8 @@ static bool test_swapchain(struct wlr_output *output, static bool wlr_output_configure_primary_swapchain(struct wlr_output *output, int width, int height, uint32_t format, struct wlr_swapchain **swapchain_ptr, bool test) { - wlr_output_state empty_state; - wlr_output_state_init(&empty_state); - wlr_output_state *state = &empty_state; + WOutputStateGuard empty_state; + wlr_output_state *state = empty_state.get(); // Re-use the existing swapchain if possible struct wlr_swapchain *old_swapchain = *swapchain_ptr; @@ -346,25 +355,27 @@ static bool wlr_output_configure_primary_swapchain(struct wlr_output *output, in struct wlr_swapchain *swapchain = create_swapchain(output, width, height, format, true); if (swapchain == NULL) { - qCritical("Failed to create swapchain for output '%s'", output->name); + qCCritical(lcWlOutputBuffer) << "Failed to create swapchain for output:" << QString::fromUtf8(output->name); return false; } if (test) { - qDebug("Testing swapchain for output '%s'", output->name); + qCDebug(lcWlOutputBuffer) << "Testing swapchain for output:" << QString::fromUtf8(output->name); if (!test_swapchain(output, swapchain, state)) { - qDebug("Output test failed on '%s', retrying without modifiers", - output->name); + qCDebug(lcWlOutputBuffer) << "Output test failed for" << QString::fromUtf8(output->name) + << "- retrying without modifiers"; wlr_swapchain_destroy(swapchain); swapchain = create_swapchain(output, width, height, format, false); if (swapchain == NULL) { - qCritical("Failed to create modifier-less swapchain for output '%s'", - output->name); + qCCritical(lcWlOutputBuffer) << "Failed to create modifier-less swapchain for output:" + << QString::fromUtf8(output->name); return false; } - qDebug("Testing modifier-less swapchain for output '%s'", output->name); + qCDebug(lcWlOutputBuffer) << "Testing modifier-less swapchain for output:" + << QString::fromUtf8(output->name); if (!test_swapchain(output, swapchain, state)) { - qCritical("Swapchain for output '%s' failed test", output->name); + qCCritical(lcWlOutputBuffer) << "Swapchain test failed for output:" + << QString::fromUtf8(output->name); wlr_swapchain_destroy(swapchain); return false; } @@ -387,7 +398,7 @@ static bool output_pick_cursor_format(struct wlr_output *output, display_formats = output->impl->get_cursor_formats(output, allocator->buffer_caps); if (display_formats == NULL) { - qCDebug(qLcOutput, "Failed to get cursor display formats"); + qCDebug(lcWlOutputDrm) << "Failed to get cursor display formats from output"; return false; } } @@ -397,34 +408,35 @@ static bool output_pick_cursor_format(struct wlr_output *output, // End bool WOutput::configurePrimarySwapchain(const QSize &size, uint32_t format, - qw_swapchain **swapchain, bool doTest) + wlr_swapchain **swapchain, bool doTest) { + W_D(WOutput); Q_ASSERT(!size.isEmpty()); - wlr_swapchain *sc = (*swapchain)->handle(); - bool ok = wlr_output_configure_primary_swapchain(nativeHandle(), size.width(), size.height(), + wlr_swapchain *sc = *swapchain; + bool ok = wlr_output_configure_primary_swapchain(d->handle(), size.width(), size.height(), format, &sc, doTest); if (!ok) return false; - *swapchain = qw_swapchain::from(sc); + *swapchain = sc; return true; } -bool WOutput::configureCursorSwapchain(const QSize &size, uint32_t drmFormat, qw_swapchain **swapchain) +bool WOutput::configureCursorSwapchain(const QSize &size, uint32_t drmFormat, wlr_swapchain **swapchain) { + W_D(WOutput); Q_ASSERT(!size.isEmpty()); auto sc = *swapchain; - if (!sc || sc->handle()->width != size.width() || sc->handle()->height != size.height()) { - wlr_drm_format format = {0}; - if (!output_pick_cursor_format(nativeHandle(), &format, drmFormat)) { - qCDebug(qLcOutput, "Failed to pick cursor format"); + if (!sc || sc->width != size.width() || sc->height != size.height()) { + WDrmFormat format; + if (!output_pick_cursor_format(d->handle(), format.get(), drmFormat)) { + qCDebug(lcWlOutputDrm) << "Failed to select compatible cursor format"; return false; } - delete sc; - sc = qw_swapchain::create(*allocator(), size.width(), size.height(), &format); - wlr_drm_format_finish(&format); - if (!sc) { - qCDebug(qLcOutput, "Failed to create cursor swapchain"); + wlr_swapchain_destroy(sc); + sc = wlr_swapchain_create(allocator(), size.width(), size.height(), format.get()); + if (!sc) { + qCDebug(lcWlOutputBuffer) << "Failed to create cursor swapchain with selected format"; return false; } } @@ -433,21 +445,17 @@ bool WOutput::configureCursorSwapchain(const QSize &size, uint32_t drmFormat, qw return true; } -qw_output *WOutput::handle() const +wlr_output *WOutput::handle() const { W_DC(WOutput); return d->handle(); } -wlr_output *WOutput::nativeHandle() const -{ - W_DC(WOutput); - return d->nativeHandle(); -} - -WOutput *WOutput::fromHandle(const qw_output *handle) +WOutput *WOutput::fromHandle(wlr_output *handle) { - return handle->get_data(); + if (!handle) + return nullptr; + return static_cast(handle->data); } WOutput *WOutput::fromScreen(const QScreen *screen) @@ -470,13 +478,13 @@ QWlrootsScreen *WOutput::screen() const QString WOutput::name() const { W_DC(WOutput); - return QString::fromUtf8(d->nativeHandle()->name); + return QString::fromUtf8(d->handle()->name); } bool WOutput::isEnabled() const { W_DC(WOutput); - return d->nativeHandle()->enabled; + return d->handle()->enabled; } QPoint WOutput::position() const @@ -488,7 +496,7 @@ QPoint WOutput::position() const if (Q_UNLIKELY(!d->layout)) return p; - auto l_output = d->layout->handle()->get(d->nativeHandle()); + auto l_output = wlr_output_layout_get(d->layout->handle(), d->handle()); if (Q_UNLIKELY(!l_output)) return p; @@ -507,7 +515,7 @@ QSize WOutput::transformedSize() const { W_DC(WOutput); int width, height; - d->handle()->transformed_resolution(&width, &height); + wlr_output_transformed_resolution(d->handle(), &width, &height); return QSize( width, height ); } @@ -516,7 +524,7 @@ QSize WOutput::effectiveSize() const W_DC(WOutput); int width, height; - d->handle()->effective_resolution(&width, &height); + wlr_output_effective_resolution(d->handle(), &width, &height); return QSize( width, height ); } @@ -531,7 +539,7 @@ float WOutput::scale() const { W_DC(WOutput); - return d->nativeHandle()->scale; + return d->handle()->scale; } void WOutput::attach(QQuickWindow *window) @@ -594,9 +602,14 @@ void WOutput::setForceSoftwareCursor(bool on) if (d->forceSoftwareCursor == on) return; d->forceSoftwareCursor = on; - d->handle()->lock_software_cursors(on); + wlr_output_lock_software_cursors(d->handle(), on); Q_EMIT forceSoftwareCursorChanged(); } +void WOutput::scheduleFrame() +{ + wlr_output_schedule_frame(handle()); +} + WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/woutput.h b/waylib/src/server/kernel/woutput.h index 94d6f66b3b..a9fe59bb8f 100644 --- a/waylib/src/server/kernel/woutput.h +++ b/waylib/src/server/kernel/woutput.h @@ -1,11 +1,10 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include -#include -#include #include #include @@ -20,12 +19,6 @@ class QScreen; class QQuickWindow; QT_END_NAMESPACE -QW_BEGIN_NAMESPACE -class qw_renderer; -class qw_swapchain; -class qw_allocator; -QW_END_NAMESPACE - WAYLIB_SERVER_BEGIN_NAMESPACE class QWlrootsScreen; @@ -36,7 +29,8 @@ class WCursor; class WBackend; class WServer; class WOutputPrivate; -class WAYLIB_SERVER_EXPORT WOutput : public WWrapObject +class WBackendPrivate; +class WAYLIB_SERVER_EXPORT WOutput : public QObject, public WObject { Q_OBJECT W_DECLARE_PRIVATE(WOutput) @@ -51,35 +45,34 @@ class WAYLIB_SERVER_EXPORT WOutput : public WWrapObject public: enum Transform { - Normal = WLR::Transform::Normal, - R90 = WLR::Transform::R90, - R180 = WLR::Transform::R180, - R270 = WLR::Transform::R270, - Flipped = WLR::Transform::Flipped, - Flipped90 = WLR::Transform::Flipped90, - Flipped180 = WLR::Transform::Flipped180, - Flipped270 = WLR::Transform::Flipped270 + Normal = 0, + R90 = 1, + R180 = 2, + R270 = 3, + Flipped = 4, + Flipped90 = 5, + Flipped180 = 6, + Flipped270 = 7 }; Q_ENUM(Transform) - explicit WOutput(QW_NAMESPACE::qw_output *handle, WBackend *backend); + explicit WOutput(wlr_output *handle, WBackend *backend); ~WOutput(); WBackend *backend() const; WServer *server() const; - QW_NAMESPACE::qw_renderer *renderer() const; - QW_NAMESPACE::qw_swapchain *swapchain() const; - QW_NAMESPACE::qw_allocator *allocator() const; + wlr_renderer *renderer() const; + wlr_swapchain *swapchain() const; + wlr_allocator *allocator() const; bool configurePrimarySwapchain(const QSize &size, uint32_t format, - QW_NAMESPACE::qw_swapchain **swapchain, + wlr_swapchain **swapchain, bool doTest = true); bool configureCursorSwapchain(const QSize &size, uint32_t format, - QW_NAMESPACE::qw_swapchain **swapchain); + wlr_swapchain **swapchain); - QW_NAMESPACE::qw_output *handle() const; - wlr_output *nativeHandle() const; + wlr_output *handle() const; - static WOutput *fromHandle(const QW_NAMESPACE::qw_output *handle); + static WOutput *fromHandle(wlr_output *handle); static WOutput *fromScreen(const QScreen *screen); @@ -105,14 +98,19 @@ class WAYLIB_SERVER_EXPORT WOutput : public WWrapObject bool forceSoftwareCursor() const; void setForceSoftwareCursor(bool on); + void scheduleFrame(); + Q_SIGNALS: void enabledChanged(); void positionChanged(const QPoint &pos); void modeChanged(); void transformedSizeChanged(); + // Emitted from the destructor while the object is still usable. + void beforeDestroy(); void effectiveSizeChanged(); void orientationChanged(); void scaleChanged(); + void adaptiveSyncEnabledChanged(); void forceSoftwareCursorChanged(); void bufferCommitted(); void cursorAdded(WAYLIB_SERVER_NAMESPACE::WCursor *cursor); @@ -124,8 +122,12 @@ class WAYLIB_SERVER_EXPORT WOutput : public WWrapObject void setScreen(QWlrootsScreen *screen); QWlrootsScreen *screen() const; - friend class WServer; friend class WServerPrivate; + friend class WBackendPrivate; + + // Owned by the backend: released with `delete` from the native destroy + // callback, never with deleteLater(). + using QObject::deleteLater; }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/woutputlayout.cpp b/waylib/src/server/kernel/woutputlayout.cpp index e72ab77b85..826c9c842f 100644 --- a/waylib/src/server/kernel/woutputlayout.cpp +++ b/waylib/src/server/kernel/woutputlayout.cpp @@ -1,22 +1,18 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "woutputlayout.h" #include "private/woutputlayout_p.h" #include "woutput.h" -#include -#include -#include -#include +#include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE WOutputLayoutPrivate::WOutputLayoutPrivate(WOutputLayout *qq) - : WWrapObjectPrivate(qq) + : WObjectPrivate(qq) { } @@ -36,7 +32,7 @@ void WOutputLayoutPrivate::doAdd(WOutput *output) W_Q(WOutputLayout); Q_ASSERT(output->layout() == q); - output->safeConnect(&WOutput::effectiveSizeChanged, q, [this] { + QObject::connect(output, &WOutput::effectiveSizeChanged, q, [this] { updateImplicitSize(); }); updateImplicitSize(); @@ -50,8 +46,8 @@ void WOutputLayoutPrivate::updateImplicitSize() W_Q(WOutputLayout); wlr_box tmp_box; - handle()->get_box(nullptr, &tmp_box); - auto newSize = qw_box(tmp_box).toQRect(); + wlr_output_layout_get_box(handle(), nullptr, &tmp_box); + const QRect newSize(tmp_box.x, tmp_box.y, tmp_box.width, tmp_box.height); if (implicitWidth != newSize.x() + newSize.width()) { implicitWidth = newSize.x() + newSize.width(); @@ -64,14 +60,13 @@ void WOutputLayoutPrivate::updateImplicitSize() } WOutputLayout::WOutputLayout(WOutputLayoutPrivate &dd, WServer *server) - : WWrapObject(dd, server) + : QObject(server) + , WObject(dd, server) { - auto h = new qw_output_layout(*server->handle()); - initHandle(h); - - W_D(WOutputLayout); - - handle()->set_data(this, this); + auto h = wlr_output_layout_create(server->handle()); + Q_ASSERT(h); + h->data = d_func(); + d_func()->m_handle = h; } WOutputLayout::WOutputLayout(WServer *server) @@ -80,7 +75,7 @@ WOutputLayout::WOutputLayout(WServer *server) } -qw_output_layout *WOutputLayout::handle() const +wlr_output_layout *WOutputLayout::handle() const { W_DC(WOutputLayout); return d->handle(); @@ -96,7 +91,7 @@ void WOutputLayout::add(WOutput *output, const QPoint &pos) { W_D(WOutputLayout); output->setLayout(this); - d->handle()->add(output->nativeHandle(), pos.x(), pos.y()); + wlr_output_layout_add(d->handle(), output->handle(), pos.x(), pos.y()); d->doAdd(output); } @@ -104,7 +99,7 @@ void WOutputLayout::autoAdd(WOutput *output) { W_D(WOutputLayout); output->setLayout(this); - d->handle()->add_auto(output->nativeHandle()); + wlr_output_layout_add_auto(d->handle(), output->handle()); d->doAdd(output); } @@ -117,8 +112,9 @@ void WOutputLayout::move(WOutput *output, const QPoint &pos) if (output->position() == pos) return; - d->handle()->add(output->nativeHandle(), pos.x(), pos.y()); + wlr_output_layout_add(d->handle(), output->handle(), pos.x(), pos.y()); + Q_EMIT output->positionChanged(pos); d->updateImplicitSize(); } @@ -128,9 +124,9 @@ void WOutputLayout::remove(WOutput *output) Q_ASSERT(d->outputs.contains(output)); d->outputs.removeOne(output); - d->handle()->remove(output->nativeHandle()); + wlr_output_layout_remove(d->handle(), output->handle()); output->setLayout(nullptr); - output->safeDisconnect(this); + output->disconnect(this); d->updateImplicitSize(); Q_EMIT outputRemoved(output); @@ -145,8 +141,8 @@ QList WOutputLayout::getIntersectedOutputs(const QRect &geometry) cons for (auto o : std::as_const(d->outputs)) { wlr_box tmp; - d->handle()->get_box(o->nativeHandle(), &tmp); - const QRect og = qw_box(tmp).toQRect(); + wlr_output_layout_get_box(d->handle(), o->handle(), &tmp); + const QRect og(tmp.x, tmp.y, tmp.width, tmp.height); if (og.intersects(geometry)) outputs << o; } diff --git a/waylib/src/server/kernel/woutputlayout.h b/waylib/src/server/kernel/woutputlayout.h index 25c2fbc25a..f642e2e1a1 100644 --- a/waylib/src/server/kernel/woutputlayout.h +++ b/waylib/src/server/kernel/woutputlayout.h @@ -1,21 +1,20 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include #include #include -QW_BEGIN_NAMESPACE -class qw_output_layout; -QW_END_NAMESPACE +Q_MOC_INCLUDE("woutput.h") WAYLIB_SERVER_BEGIN_NAMESPACE class WOutput; class WOutputLayoutPrivate; -class WAYLIB_SERVER_EXPORT WOutputLayout : public WWrapObject +class WAYLIB_SERVER_EXPORT WOutputLayout : public QObject, public WObject { Q_OBJECT W_DECLARE_PRIVATE(WOutputLayout) @@ -34,7 +33,7 @@ class WAYLIB_SERVER_EXPORT WOutputLayout : public WWrapObject explicit WOutputLayout(WServer *server); - qw_output_layout *handle() const; + wlr_output_layout *handle() const; const QList &outputs() const; @@ -57,7 +56,6 @@ class WAYLIB_SERVER_EXPORT WOutputLayout : public WWrapObject protected: WOutputLayout(WOutputLayoutPrivate &dd, WServer *server); - ~WOutputLayout() override = default; }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wpointer.h b/waylib/src/server/kernel/wpointer.h new file mode 100644 index 0000000000..4639b6b207 --- /dev/null +++ b/waylib/src/server/kernel/wpointer.h @@ -0,0 +1,206 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// Generic RAII smart pointers for wlroots C objects. +// +// wlroots objects are C structs allocated by wlroots; they MUST be released +// through their dedicated destroy functions (wlr_texture_destroy, +// wlr_output_destroy, ...) and never with plain `delete`. These wrappers make +// that automatic and additionally behave like QPointer for objects that carry +// a `events.destroy` wl_signal: the pointer is nulled as soon as the native +// object is destroyed by anyone, so you never hold a dangling handle. +// +// WUniquePointer tex(wlr_texture_from_buffer(...)); +// // destroyed via wlr_texture_destroy() on scope exit +// +// WPointer out(someOutput); +// // never dangles: nulled when someOutput is destroyed +// +// Types without a destroy signal (e.g. wlr_texture, wlr_renderer) still get +// RAII destruction; only the auto-null feature is unavailable for them. +// Input-device-derived types (wlr_keyboard, wlr_pointer, ...) have no destroy +// signal of their own — it is observed on their wlr_input_device base. +// New types: add a WlrObjectTraits specialization (see the macro below). + +#pragma once + +#include "wglobal.h" +#include "wlr_all.h" +#include "wcontainerof.h" + +#include + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +// RAII deleter for wlr_buffer references. +struct WBufferUnlocker { + static inline void cleanup(wlr_buffer *buffer) { if (buffer) wlr_buffer_unlock(buffer); } + void operator()(wlr_buffer *buffer) const { cleanup(buffer); } +}; + +// RAII deleter that drops a wlr_buffer reference. +struct WBufferDroper { + static inline void cleanup(wlr_buffer *buffer) { if (buffer) wlr_buffer_drop(buffer); } + void operator()(wlr_buffer *buffer) const { cleanup(buffer); } +}; + +// Convenience aliases for wlr_buffer smart pointers. +using WBufferUnlockPtr = std::unique_ptr; +using WBufferDropPtr = std::unique_ptr; + +// Maps a wlr type to its destroy function. Specialize per type, either with +// the W_DECLARE_WLR_TRAITS macro below or with a custom struct exposing a +// static `destroy(T *)`. +template +struct WlrObjectTraits; + +template +concept WlrDestroyable = requires(T *p) { WlrObjectTraits::destroy(p); }; + +#define W_DECLARE_WLR_TRAITS(Class, DestroyFn) \ + template <> struct WlrObjectTraits { \ + static void destroy(Class *handle) { DestroyFn(handle); } \ + }; + +// Core specializations. Add more types as they get owned by smart pointers. +W_DECLARE_WLR_TRAITS(wlr_texture, wlr_texture_destroy) +W_DECLARE_WLR_TRAITS(wlr_output, wlr_output_destroy) +W_DECLARE_WLR_TRAITS(wlr_renderer, wlr_renderer_destroy) +W_DECLARE_WLR_TRAITS(wlr_allocator, wlr_allocator_destroy) +W_DECLARE_WLR_TRAITS(wlr_swapchain, wlr_swapchain_destroy) +W_DECLARE_WLR_TRAITS(wlr_cursor, wlr_cursor_destroy) +W_DECLARE_WLR_TRAITS(wlr_seat, wlr_seat_destroy) +W_DECLARE_WLR_TRAITS(wlr_backend, wlr_backend_destroy) +W_DECLARE_WLR_TRAITS(wlr_output_layout, wlr_output_layout_destroy) +W_DECLARE_WLR_TRAITS(wlr_ext_foreign_toplevel_handle_v1, + wlr_ext_foreign_toplevel_handle_v1_destroy) +W_DECLARE_WLR_TRAITS(wlr_foreign_toplevel_handle_v1, + wlr_foreign_toplevel_handle_v1_destroy) +W_DECLARE_WLR_TRAITS(wlr_xdg_popup, wlr_xdg_popup_destroy) +W_DECLARE_WLR_TRAITS(wlr_layer_surface_v1, wlr_layer_surface_v1_destroy) +W_DECLARE_WLR_TRAITS(wlr_xcursor_manager, wlr_xcursor_manager_destroy) +#undef W_DECLARE_WLR_TRAITS + +// Observing pointer (QPointer semantics). Does not own the object; the handle +// is automatically nulled when the native object is destroyed (for types with +// a destroy signal). Copyable: every instance listens independently. +template +class WPointer +{ + static_assert(requires(T *handle) { handle->events.destroy; } + || requires(T *handle) { handle->base.events.destroy; }, + "WPointer: T must expose a destroy wl_signal (its own events.destroy, " + "or base.events.destroy for wlr_input_device-derived types). " + "Use a raw pointer or WUniquePointer (which supports types " + "without a destroy signal via RAII traits) instead."); +public: + WPointer() = default; + explicit WPointer(T *handle) { assign(handle); } + ~WPointer() { clear(); } + + WPointer(const WPointer &other) { assign(other.m_handle); } + WPointer &operator=(const WPointer &other) { + if (this != &other) + assign(other.m_handle); + return *this; + } + WPointer(WPointer &&other) noexcept { + T *h = other.m_handle; + other.clear(); // detach other's listener, null its handle + assign(h); // this watches h with its own fresh listener + } + WPointer &operator=(WPointer &&other) noexcept { + if (this != &other) { + T *h = other.m_handle; + other.clear(); + assign(h); + } + return *this; + } + + WPointer &operator=(T *handle) { + assign(handle); + return *this; + } + + void assign(T *handle) { + if (m_handle == handle) + return; + clear(); + m_handle = handle; + if (handle) { + // Input-device-derived types (wlr_keyboard, wlr_pointer, ...) emit + // their destroy signal from the embedded wlr_input_device base. + if constexpr (requires { handle->events.destroy; }) { + wl_signal_add(&handle->events.destroy, &m_destroyListener); + } else { + wl_signal_add(&handle->base.events.destroy, &m_destroyListener); + } + m_listening = true; + } + } + void clear() { + if (m_listening) { + if (m_destroyListener.link.next != nullptr) + wl_list_remove(&m_destroyListener.link); + m_listening = false; + } + m_handle = nullptr; + } + + T *get() const { return m_handle; } + T *operator->() const { return m_handle; } + T &operator*() const { return *m_handle; } + // Implicit conversion like QPointer: lets observers be passed to + // wlroots C APIs that take a raw T* without extra .get() calls. + operator T *() const { return m_handle; } + explicit operator bool() const { return m_handle != nullptr; } + bool isNull() const { return m_handle == nullptr; } + +private: + static void onNativeDestroy(wl_listener *listener, void *) { + using Self = WPointer; + Self *self = container_of(listener, offsetof(Self, m_destroyListener)); + // wlr_signal_emit_safe() detaches the node before notifying (link is + // zeroed); wl_signal_emit_mutable() leaves it attached — remove only + // when it is still linked. + if (self->m_destroyListener.link.next != nullptr) + wl_list_remove(&self->m_destroyListener.link); + self->m_listening = false; + self->m_handle = nullptr; + } + + T *m_handle = nullptr; + bool m_listening = false; + // notify is set once at construction; assign()/clear() only manage the + // link and the m_listening flag, reducing the risk of a path forgetting + // to set it. + wl_listener m_destroyListener { {}, &WPointer::onNativeDestroy }; +}; + +// Deleter that releases a wlroots object through WlrObjectTraits::destroy. +template > +struct WUniqueDeleter +{ + // Check the Traits actually in use (not WlrObjectTraits), so a + // custom Traits passed as the second template argument is validated. + static_assert(requires(T *p) { Traits::destroy(p); }, + "WUniqueDeleter: Traits must provide destroy(T*). " + "Add one with W_DECLARE_WLR_TRAITS(Class, DestroyFn) or pass a custom traits."); + + void operator()(T *handle) const { + if (handle) + Traits::destroy(handle); + } +}; + +// Owning pointer: std::unique_ptr with the automatic wlroots deleter. +// Pure RAII ownership — it does not observe the native destroy signal. If +// you need to track whether the native object is still alive, hold a +// WPointer alongside. +template > +using WUniquePointer = std::unique_ptr>; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wseat.cpp b/waylib/src/server/kernel/wseat.cpp index 6377d87f90..bd24fe2a98 100644 --- a/waylib/src/server/kernel/wseat.cpp +++ b/waylib/src/server/kernel/wseat.cpp @@ -1,28 +1,22 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wseat.h" +#include "wpointergesturesv1.h" #include "wcursor.h" #include "winputdevice.h" #include "woutput.h" #include "wsurface.h" -#include "wxdgsurface.h" +#include "wscoplistener.h" +#include "wpointer.h" #include "platformplugin/qwlrootsintegration.h" #include "private/wglobal_p.h" +#include "wayliblogging.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include #include -#include #include #include @@ -35,14 +29,8 @@ QT_BEGIN_NAMESPACE Q_GUI_EXPORT bool qt_sendShortcutOverrideEvent(QObject *o, ulong timestamp, int k, Qt::KeyboardModifiers mods, const QString &text = QString(), bool autorep = false, ushort count = 1); QT_END_NAMESPACE -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE -Q_LOGGING_CATEGORY(qLcWlrTouch, "waylib.server.seat", QtWarningMsg) -Q_LOGGING_CATEGORY(qLcWlrTouchEvents, "waylib.server.seat.events.touch", QtWarningMsg) -Q_LOGGING_CATEGORY(qLcWlrDragEvents, "waylib.server.seat.events.drag", QtWarningMsg) -Q_LOGGING_CATEGORY(qLcWlrGestureEvents, "waylib.server.seat.events.gesture", QtWarningMsg) - #if QT_CONFIG(wheelevent) class Q_DECL_HIDDEN WSeatWheelEvent : public QWheelEvent { public: @@ -74,21 +62,34 @@ class Q_DECL_HIDDEN WSeatWheelEvent : public QWheelEvent { }; #endif -class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate +class Q_DECL_HIDDEN WSeatPrivate : public WObjectPrivate { public: WSeatPrivate(WSeat *qq, const QString &name) - : WWrapObjectPrivate(qq) + : WObjectPrivate(qq) , name(name) { pendingEvents.reserve(2); m_repeatTimer.callOnTimeout([&](){ - if (!focusWindow) { + if (!focusWindow || !m_repeatKey) { + return; + } + auto *device = WInputDevice::from(m_repeatKey->device()); + if (!device || device->seat() != q_func()) { + m_repeatTimer.stop(); + m_repeatKey.reset(); + return; + } + auto *rawdevice = device->handle(); + auto *wlrKeyboard = rawdevice->type == WLR_INPUT_DEVICE_KEYBOARD + ? wlr_keyboard_from_input_device(rawdevice) : nullptr; + if (!wlrKeyboard || wlrKeyboard->repeat_info.rate <= 0) { + m_repeatTimer.stop(); + m_repeatKey.reset(); return; } - auto rawdevice = qobject_cast(WInputDevice::from(m_repeatKey->device())->handle())->handle(); - m_repeatTimer.setInterval(1000 / rawdevice->repeat_info.rate); + m_repeatTimer.setInterval(1000 / wlrKeyboard->repeat_info.rate); auto evPress = QKeyEvent(QEvent::KeyPress, m_repeatKey->key(), m_repeatKey->modifiers(), m_repeatKey->nativeScanCode(), m_repeatKey->nativeVirtualKey(), m_repeatKey->nativeModifiers(), m_repeatKey->text(), true, m_repeatKey->count(), m_repeatKey->device()); @@ -97,8 +98,10 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate m_repeatKey->text(), true, m_repeatKey->count(), m_repeatKey->device()); evPress.setTimestamp(m_repeatKey->timestamp()); evRelease.setTimestamp(m_repeatKey->timestamp()); + const QPointer seatGuard(q_func()); handleKeyEvent(evPress); - handleKeyEvent(evRelease); + if (seatGuard && focusWindow) + handleKeyEvent(evRelease); }); } ~WSeatPrivate() { @@ -107,30 +110,52 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate for (auto device : std::as_const(deviceList)) detachInputDevice(device); - } - inline qw_seat *handle() const { - return q_func()->nativeInterface(); + destroyKeyboardGroup(); + + free(const_cast(xkbRules.rules)); + free(const_cast(xkbRules.layout)); + free(const_cast(xkbRules.model)); + free(const_cast(xkbRules.variant)); + free(const_cast(xkbRules.options)); + } + + // Release the keyboard group and its WInputDevice wrapper. Shared by + // ~WSeatPrivate and WSeat::destroy() so create() rebuilds the group on + // the next start() (its `if (!d->group)` guard). Must run while the + // native seat is still alive: detachInputDevice() touches the Qt input + // integration, and wlr_keyboard_group_destroy() fires the keyboard + // destroy signal which clears the seat's keyboard reference. + void destroyKeyboardGroup() { + if (groupkeyboardDevice) { + detachInputDevice(groupkeyboardDevice); + delete groupkeyboardDevice; + groupkeyboardDevice = nullptr; + } + + if (group) { + wlr_keyboard_group_destroy(group); + group = nullptr; + } } - inline wlr_seat *nativeHandle() const { - Q_ASSERT(handle()); - return handle()->handle(); + inline wlr_seat *handle() const { + return reinterpret_cast(q_func()->m_handle); } inline wlr_surface *pointerFocusSurface() const { - return nativeHandle()->pointer_state.focused_surface; + return handle()->pointer_state.focused_surface; } inline wlr_surface *keyboardFocusSurface() const { - return nativeHandle()->keyboard_state.focused_surface; + return handle()->keyboard_state.focused_surface; } inline bool doNotifyMotion(WSurface *target, QObject *eventObject, QPointF localPos, uint32_t timestamp) { if (target) { if (pointerFocusSurface()) { Q_ASSERT(pointerFocusEventObject == eventObject); - Q_ASSERT(pointerFocusSurface() == target->handle()->handle()); + Q_ASSERT(pointerFocusSurface() == target->handle()); } else { // Maybe this seat is grabbed by a xdg popup surface, so the surface of under mouse // can't take pointer focus, but maybe the popup is closed now, so we should try again @@ -139,11 +164,11 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate } } - handle()->pointer_notify_motion(timestamp, localPos.x(), localPos.y()); + wlr_seat_pointer_notify_motion(handle(), timestamp, localPos.x(), localPos.y()); return true; } inline bool doNotifyButton(uint32_t button, wl_pointer_button_state state, uint32_t timestamp) { - handle()->pointer_notify_button(timestamp, button, state); + wlr_seat_pointer_notify_button(handle(), timestamp, button, state); return true; } static inline wl_pointer_axis fromQtHorizontal(Qt::Orientation o) { @@ -156,12 +181,12 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate if (!pointerFocusSurface()) return false; - handle()->pointer_notify_axis(timestamp, fromQtHorizontal(orientation), delta, delta_discrete, - source, relative_direction); + wlr_seat_pointer_notify_axis(handle(), timestamp, fromQtHorizontal(orientation), delta, + delta_discrete, source, relative_direction); return true; } inline void doNotifyFrame() { - handle()->pointer_notify_frame(); + wlr_seat_pointer_notify_frame(handle()); } inline bool doEnter(WSurface *surface, QObject *eventObject, const QPointF &position) { // doEnter be called from QEvent::HoverEnter is normal, @@ -171,8 +196,8 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate return true; } auto tmp = oldPointerFocusSurface; - oldPointerFocusSurface = handle()->handle()->pointer_state.focused_surface; - handle()->pointer_notify_enter(surface->handle()->handle(), position.x(), position.y()); + oldPointerFocusSurface = handle()->pointer_state.focused_surface; + wlr_seat_pointer_notify_enter(handle(), surface->handle(), position.x(), position.y()); if (!pointerFocusSurface()) { // Because if the last pointer focus surface is a popup, the 'pointerNotifyEnter' // will call 'xdg_pointer_grab_enter' in wlroots, and the 'xdg_pointer_grab_enter' @@ -181,7 +206,7 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate oldPointerFocusSurface = tmp; return false; } - Q_ASSERT(pointerFocusSurface() == surface->handle()->handle()); + Q_ASSERT(pointerFocusSurface() == surface->handle()); Q_ASSERT(!pointerFocusEventObject || eventObject != pointerFocusEventObject); if (pointerFocusEventObject) { @@ -200,36 +225,61 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate } inline void doClearPointerFocus() { pointerFocusEventObject.clear(); - handle()->pointer_notify_clear_focus(); - Q_ASSERT(!handle()->handle()->pointer_state.focused_surface); - if (cursor) // reset cursur from QCursor resource, the last cursor is from wlr_surface - cursor->setCursor(cursor->cursor()); - } - inline void doSetKeyboardFocus(qw_surface *surface) { + // Grab-aware: with an active drag/popup grab the raw + // wlr_seat_pointer_clear_focus() would bypass the grab and break it. + wlr_seat_pointer_notify_clear_focus(handle()); + Q_ASSERT(!handle()->pointer_state.focused_surface); + if (cursor) // reset cursor from QCursor resource, the last cursor is from wlr_surface + Q_EMIT cursor->cursorChanged(); + } + inline void doSetKeyboardFocus(wlr_surface *surface) { if (surface) { - handle()->keyboard_enter(*surface, nullptr, 0, nullptr); + const wlr_keyboard_modifiers *modifiers = nullptr; + const uint32_t *keycodes = nullptr; + size_t numKeycodes = 0; + auto keyboard = q_func()->keyboard(); + if (keyboard) { + auto *wlr_keyboard = wlr_keyboard_from_input_device(keyboard->handle()); + if (wlr_keyboard) { + modifiers = &wlr_keyboard->modifiers; + keycodes = wlr_keyboard->keycodes; + numKeycodes = wlr_keyboard->num_keycodes; + } + } + + // Send keyboard enter with current modifiers. + // This ensures the newly focused client receives the current modifier state + // (Num Lock, Caps Lock, etc.) as required by Wayland protocol. + // Keys consumed by shortcut handling are dropped. + uint32_t visibleKeycodes[WLR_KEYBOARD_KEYS_CAP]; + const size_t numVisibleKeycodes = + WSeat::unfilteredKeycodes(keycodes, numKeycodes, filteredKeys, + visibleKeycodes); + wlr_seat_keyboard_notify_enter(handle(), surface, visibleKeycodes, numVisibleKeycodes, modifiers); } else { - handle()->keyboard_clear_focus(); + // Grab-aware: the raw wlr_seat_keyboard_clear_focus() would + // bypass an active keyboard grab (IME, popup, drag). + wlr_seat_keyboard_notify_clear_focus(handle()); } } inline void doTouchNotifyDown(WSurface *surface, uint32_t time_msec, int32_t touch_id, const QPointF &pos) { - handle()->touch_notify_down(surface->handle()->handle(), time_msec, touch_id, pos.x(), pos.y()); + wlr_seat_touch_notify_down(handle(), surface->handle(), time_msec, touch_id, pos.x(), pos.y()); } inline void doTouchNotifyMotion(uint32_t time_msec, int32_t touch_id, const QPointF &pos) { - handle()->touch_notify_motion(time_msec, touch_id, pos.x(), pos.y()); + wlr_seat_touch_notify_motion(handle(), time_msec, touch_id, pos.x(), pos.y()); } inline void doTouchNotifyUp(uint32_t time_msec, int32_t touch_id) { - handle()->touch_notify_up(time_msec, touch_id); + wlr_seat_touch_notify_up(handle(), time_msec, touch_id); } inline void doTouchNotifyCancel(WInputDevice *device) { auto *state = device->getAttachedData(); - for (int i = 0; i < state->m_points.size(); ++i) { + for (int i = state->m_points.size() - 1; i >= 0; --i) { const auto &qtPoint = state->m_points.at(i); if (qtPoint.state == static_cast(WEvent::PointCancelled)) { - auto point = handle()->touch_get_point(qtPoint.id); + auto point = wlr_seat_touch_get_point(handle(), qtPoint.id); Q_ASSERT(point); - state->m_points.removeAt(i--); - handle()->touch_notify_cancel(point->client); + state->m_points.removeAt(i); + wlr_seat_touch_notify_cancel(handle(), point->client); } } } @@ -246,10 +296,8 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate doTouchNotifyUp(time_msec, touch_id); break; case Stationary: - // stationary points are not sent through wayland, the client must cache them - break; case Unknown: - // Ignored + // stationary points are not sent through wayland, and unknown states are ignored. break; } } @@ -259,7 +307,7 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate Q_ASSERT(qwDevice); auto *state = device->getAttachedData(); - qCDebug(qLcWlrTouchEvents) << "Touch frame for device: " << qwDevice->name() + qCDebug(lcWlTouch) << "Touch frame for device: " << qwDevice->name() << ", handle the following state: " << state->m_points; if (state->m_points.isEmpty()) @@ -270,38 +318,46 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate keyModifiers); } - for (int i = 0; i < state->m_points.size(); ++i) { + for (int i = state->m_points.size() - 1; i >= 0; --i) { QWindowSystemInterface::TouchPoint &tp(state->m_points[i]); if (tp.state == QEventPoint::Released) - state->m_points.removeAt(i--); - else if (tp.state == QEventPoint::Pressed) - tp.state = QEventPoint::Stationary; - else if (tp.state == QEventPoint::Updated) - tp.state = QEventPoint::Stationary; // notiyfy: qtbase don't change Updated + state->m_points.removeAt(i); + else if (tp.state == QEventPoint::Pressed || tp.state == QEventPoint::Updated) + tp.state = QEventPoint::Stationary; // notify: qtbase does not change Updated else if (tp.state != QEventPoint::Stationary) Q_UNREACHABLE_RETURN(); } - handle()->touch_notify_frame(); + wlr_seat_touch_notify_frame(handle()); } // for keyboard event inline bool doNotifyKey(WInputDevice *device, uint32_t keycode, uint32_t state, uint32_t timestamp) { + q_func()->setKeyboard(device); + if (!keyboardFocusSurface()) return false; - q_func()->setKeyboard(device); - /* Send modifiers to the client. */ - this->handle()->keyboard_notify_key(timestamp, keycode, state); + /* Send keys to the client. */ + wlr_seat_keyboard_notify_key(handle(), timestamp, keycode, state); return true; } inline bool doNotifyModifiers(WInputDevice *device) { + auto keyboard = wlr_keyboard_from_input_device(device->handle()); + + // wlr_seat_set_keyboard() already sends modifiers when the keyboard + // changes, so skip the explicit send to avoid a duplicate. + bool keyboardChanged = (q_func()->keyboard() != device); + q_func()->setKeyboard(device); + if (!keyboardFocusSurface()) return false; - auto keyboard = qobject_cast(device->handle()); - q_func()->setKeyboard(device); - /* Send modifiers to the client. */ - this->handle()->keyboard_notify_modifiers(&keyboard->handle()->modifiers); + // Only send modifiers explicitly when the keyboard did NOT change. + // If it changed, wlr_seat_set_keyboard() already sent them. + if (!keyboardChanged) { + /* Send modifiers to the client. */ + wlr_seat_keyboard_notify_modifiers(handle(), &keyboard->modifiers); + } return true; } inline void doMouseMove(WCursor *cursor, const QPointingDevice *device, uint32_t timestamp) { @@ -310,8 +366,13 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate const QPointF &global = cursor->position(); const QPointF local = w ? global - QPointF(w->position()) : QPointF(); + // During DnD the pointer is grabbed by wlr_drag: report no held buttons + // so Qt PointerHandlers (e.g. title bar DragHandler) don't start a drag + // gesture and steal the pointer grab from wlr_drag. + const Qt::MouseButtons buttons = handle()->drag ? Qt::NoButton : cursor->state(); + QMouseEvent e(QEvent::MouseMove, local, global, Qt::NoButton, - cursor->state(), keyModifiers, device); + buttons, keyModifiers, device); Q_ASSERT(e.isUpdateEvent()); e.setTimestamp(timestamp); @@ -320,7 +381,6 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate } // begin slot function - void on_destroy(); void on_request_set_cursor(wlr_seat_pointer_request_set_cursor_event *event); void on_request_set_selection(wlr_seat_request_set_selection_event *event); void on_request_set_primary_selection(wlr_seat_request_set_primary_selection_event *event); @@ -337,24 +397,31 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate void detachInputDevice(WInputDevice *device); // handle spontaneous & synthetic key event for focusWindow void handleKeyEvent(QKeyEvent &e); + void applyXkbConfig(); W_DECLARE_PUBLIC(WSeat) QString name; WCursor *cursor = nullptr; - qw_pointer_gestures_v1 *gesture = nullptr; + QPointer gesture; QVector deviceList; QVector touchDeviceList; QPointer eventFilter; QPointer focusWindow; QPointer pointerFocusEventObject; QPointer m_keyboardFocusSurface; + // Evdev keycodes whose press was consumed by shortcut handling; + // see WSeat::addFilteredKey(). + QSet filteredKeys; QMetaObject::Connection onEventObjectDestroy; wlr_surface *oldPointerFocusSurface = nullptr; bool gestureActive = false; int gestureFingers = 0; qreal lastScale = 1.0; + wlr_keyboard_group *group = nullptr; + WInputDevice *groupkeyboardDevice = nullptr; + struct xkb_rule_names xkbRules = {}; struct EventState { // Don't use it, its may be a invalid pointer @@ -415,7 +482,7 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate // for cursor data // TODO: make to QWSeatClient in wlroots // Don't access its member, maybe is a invalid pointer - wlr_seat_client *cursorClient = nullptr; + WPointer cursorClient; QPointer cursorSurface; QPoint cursorSurfaceHotspot; WGlobal::CursorShape cursorShape = WGlobal::CursorShape::Invalid; @@ -425,14 +492,9 @@ class Q_DECL_HIDDEN WSeatPrivate : public WWrapObjectPrivate bool alwaysUpdateHoverTarget = false; }; -void WSeatPrivate::on_destroy() -{ - q_func()->m_handle = nullptr; -} - void WSeatPrivate::on_request_set_cursor(wlr_seat_pointer_request_set_cursor_event *event) { - auto focused_client = nativeHandle()->pointer_state.focused_client; + auto focused_client = handle()->pointer_state.focused_client; /* This can be sent by any client, so we check to make sure this one is * actually has pointer focus first. */ if (focused_client == event->seat_client) { @@ -440,18 +502,35 @@ void WSeatPrivate::on_request_set_cursor(wlr_seat_pointer_request_set_cursor_eve * provided surface as the cursor image. It will set the hardware cursor * on the output that it's currently on and continue to do so as the * cursor moves between outputs. */ - auto *surface = event->surface ? qw_surface::from(event->surface) : nullptr; - cursorClient = event->seat_client; + auto *surface = event->surface; cursorShape = WGlobal::CursorShape::Invalid; + W_Q(WSeat); + + if (cursorClient == event->seat_client && cursorSurface + && cursorSurface->handle() == surface) { + if (cursorSurfaceHotspot.x() != event->hotspot_x + || cursorSurfaceHotspot.y() != event->hotspot_y) { + cursorSurfaceHotspot.rx() = event->hotspot_x; + cursorSurfaceHotspot.ry() = event->hotspot_y; + Q_EMIT q->requestCursorSurface(cursorSurface, cursorSurfaceHotspot); + } + return; + } + + cursorClient = event->seat_client; + if (cursorSurface) - cursorSurface->safeDeleteLater(); + delete cursorSurface; - W_Q(WSeat); if (surface) { - cursorSurface = new WSurface(surface, q); - QObject::connect(surface, &qw_surface::before_destroy, - cursorSurface, &WSurface::safeDeleteLater); + cursorSurface = new WSurface(surface); + // The seat created the surface, so it releases it when the + // native object dies (owner rule; no self-deletion in WSurface). + // Register on the WSurface's listeners list so the callback is + // detached automatically when the WSurface is destroyed. + cursorSurface->listeners(q_ptr)->add(&surface->events.destroy, this, + [this](void *) { delete cursorSurface; }); } else { cursorSurface.clear(); } @@ -464,28 +543,28 @@ void WSeatPrivate::on_request_set_cursor(wlr_seat_pointer_request_set_cursor_eve void WSeatPrivate::on_request_set_selection(wlr_seat_request_set_selection_event *event) { - handle()->set_selection(event->source, event->serial); + wlr_seat_set_selection(handle(), event->source, event->serial); } void WSeatPrivate::on_request_set_primary_selection(wlr_seat_request_set_primary_selection_event *event) { - wlr_seat_set_primary_selection(nativeHandle(), event->source, event->serial); + wlr_seat_set_primary_selection(handle(), event->source, event->serial); } void WSeatPrivate::on_request_start_drag(wlr_seat_request_start_drag_event *event) { - if (handle()->validate_pointer_grab_serial(event->origin, event->serial)) { - wlr_seat_start_pointer_drag(nativeHandle(), event->drag, event->serial); + if (wlr_seat_validate_pointer_grab_serial(handle(), event->origin, event->serial)) { + wlr_seat_start_pointer_drag(handle(), event->drag, event->serial); return; } struct wlr_touch_point *point; - if (handle()->validate_touch_grab_serial(event->origin, event->serial, &point)) { - wlr_seat_start_touch_drag(nativeHandle(), event->drag, event->serial, point); + if (wlr_seat_validate_touch_grab_serial(handle(), event->origin, event->serial, &point)) { + wlr_seat_start_touch_drag(handle(), event->drag, event->serial, point); return; } - qCWarning(qLcWlrDragEvents) << "Ignoring start_drag request: " + qCWarning(lcWlDrag) << "Ignoring start_drag request: " << "could not validate pointer or touch serial " << event->serial; wlr_data_source_destroy(event->drag->source); @@ -494,18 +573,23 @@ void WSeatPrivate::on_request_start_drag(wlr_seat_request_start_drag_event *even void WSeatPrivate::on_start_drag(wlr_drag *drag) { doClearPointerFocus(); + W_Q(WSeat); + if (dragSurface) + delete dragSurface; + dragSurface = nullptr; + if (drag->icon) { - W_Q(WSeat); - auto *surface = qw_surface::from(drag->icon->surface); - auto *wsurface = new WSurface(surface, q); - QObject::connect(surface, &qw_surface::before_destroy, - wsurface, &WSurface::safeDeleteLater); - if (dragSurface) - dragSurface->safeDeleteLater(); + auto *surface = drag->icon->surface; + auto *wsurface = new WSurface(surface); + // The seat created the surface, so it releases it when the native + // object dies (owner rule; no self-deletion in WSurface). + wsurface->listeners(q_ptr)->add(&surface->events.destroy, this, + [this](void *) { delete dragSurface; }); dragSurface = wsurface; - Q_EMIT q->requestDrag(dragSurface.get()); } + Q_EMIT q->requestDrag(dragSurface.get()); } + void WSeatPrivate::handleKeyEvent(QKeyEvent &e) { Q_ASSERT(focusWindow); @@ -517,30 +601,54 @@ void WSeatPrivate::handleKeyEvent(QKeyEvent &e) } QCoreApplication::sendEvent(focusWindow, &e); } + void WSeatPrivate::on_keyboard_key(wlr_keyboard_key_event *event, WInputDevice *device) { - auto keyboard = qobject_cast(device->handle()); + auto keyboard = wlr_keyboard_from_input_device(device->handle()); auto code = event->keycode + 8; // map to wl_keyboard::keymap_format::keymap_format_xkb_v1 auto et = event->state == WL_KEYBOARD_KEY_STATE_PRESSED ? QEvent::KeyPress : QEvent::KeyRelease; - xkb_keysym_t sym = xkb_state_key_get_one_sym(keyboard->handle()->xkb_state, code); - int qtkey = QXkbCommon::keysymToQtKey(sym, keyModifiers, keyboard->handle()->xkb_state, code); - const QString &text = QXkbCommon::lookupString(keyboard->handle()->xkb_state, code); + xkb_keysym_t sym = xkb_state_key_get_one_sym(keyboard->xkb_state, code); + + // Qt doesn't support XF86Switch_VT_1 to XF86Switch_VT_12, so convert them to + // Ctrl+Alt+F1 to Ctrl+Alt+F12 + // + // Assumption: XKB_KEY_XF86Switch_VT_1 and XKB_KEY_F1 are contiguous and ordered such that + // (XKB_KEY_F1 + (sym - XKB_KEY_XF86Switch_VT_1)) yields the correct F-key. + // If this is not true, the calculation below may be unsafe. + static_assert( + (XKB_KEY_XF86Switch_VT_12 - XKB_KEY_XF86Switch_VT_1) == (XKB_KEY_F12 - XKB_KEY_F1), + "XKB_KEY_XF86Switch_VT_1..12 and XKB_KEY_F1..F12 must be contiguous and ordered for keysym calculation" + ); + if (sym >= XKB_KEY_XF86Switch_VT_1 && sym <= XKB_KEY_XF86Switch_VT_12) { + constexpr auto ctrlAlt = Qt::ControlModifier | Qt::AltModifier; + if ((keyModifiers & ctrlAlt) == ctrlAlt) { + sym = XKB_KEY_F1 + (sym - XKB_KEY_XF86Switch_VT_1); + } + } - QKeyEvent e(et, qtkey, keyModifiers, code, event->keycode, keyboard->get_modifiers(), + int qtkey = QXkbCommon::keysymToQtKey(sym, keyModifiers, keyboard->xkb_state, code); + const QString &text = QXkbCommon::lookupString(keyboard->xkb_state, code); + + QKeyEvent e(et, qtkey, keyModifiers, code, event->keycode, wlr_keyboard_get_modifiers(keyboard), text, false, 1, device->qtDevice()); e.setTimestamp(event->time_msec); if (focusWindow) { + const QPointer seatGuard(q_func()); + const QPointer deviceGuard(device); handleKeyEvent(e); - if (et == QEvent::KeyPress && xkb_keymap_key_repeats(keyboard->handle()->keymap, code)) { + // Dispatch may have switched desktops or destroyed this seat/device. + if (!seatGuard || !deviceGuard || !focusWindow || deviceGuard->seat() != seatGuard) + return; + if (et == QEvent::KeyPress && xkb_keymap_key_repeats(keyboard->keymap, code)) { if (m_repeatKey) { m_repeatTimer.stop(); } - m_repeatKey = std::make_unique(et, qtkey, keyModifiers, code, event->keycode, keyboard->get_modifiers(), + m_repeatKey = std::make_unique(et, qtkey, keyModifiers, code, event->keycode, wlr_keyboard_get_modifiers(keyboard), text, false, 1, device->qtDevice()); m_repeatKey->setTimestamp(event->time_msec); - m_repeatTimer.setInterval(keyboard->handle()->repeat_info.delay); + m_repeatTimer.setInterval(keyboard->repeat_info.delay); m_repeatTimer.start(); } else if (et == QEvent::KeyRelease && m_repeatKey && m_repeatKey->nativeScanCode() == code) { m_repeatTimer.stop(); @@ -558,32 +666,23 @@ void WSeatPrivate::on_keyboard_key(wlr_keyboard_key_event *event, WInputDevice * void WSeatPrivate::on_keyboard_modifiers(WInputDevice *device) { - auto keyboard = qobject_cast(device->handle()); - keyModifiers = QXkbCommon::modifiers(keyboard->handle()->xkb_state); + auto keyboard = wlr_keyboard_from_input_device(device->handle()); + keyModifiers = QXkbCommon::modifiers(keyboard->xkb_state); doNotifyModifiers(device); } - void WSeatPrivate::connect() { W_Q(WSeat); - QObject::connect(handle(), &qw_seat::destroyed, q, [this] { - on_destroy(); - }); - QObject::connect(handle(), &qw_seat::notify_request_set_cursor, q, [this] (wlr_seat_pointer_request_set_cursor_event *event) { - on_request_set_cursor(event); - }); - QObject::connect(handle(), &qw_seat::notify_request_set_selection, q, [this] (wlr_seat_request_set_selection_event *event) { - on_request_set_selection(event); - }); - QObject::connect(handle(), &qw_seat::notify_request_set_primary_selection, q, [this] (wlr_seat_request_set_primary_selection_event *event) { - on_request_set_primary_selection(event); - }); - QObject::connect(handle(), &qw_seat::notify_request_start_drag, q, [this] (wlr_seat_request_start_drag_event *event) { - on_request_start_drag(event); - }); - QObject::connect(handle(), &qw_seat::notify_start_drag, q, [this] (wlr_drag *drag) { - on_start_drag(drag); - }); + q->listeners()->add(&handle()->events.request_set_cursor, this, + &WSeatPrivate::on_request_set_cursor); + q->listeners()->add(&handle()->events.request_set_selection, this, + &WSeatPrivate::on_request_set_selection); + q->listeners()->add(&handle()->events.request_set_primary_selection, this, + &WSeatPrivate::on_request_set_primary_selection); + q->listeners()->add(&handle()->events.request_start_drag, this, + &WSeatPrivate::on_request_start_drag); + q->listeners()->add(&handle()->events.start_drag, this, + &WSeatPrivate::on_start_drag); } void WSeatPrivate::updateCapabilities() @@ -600,7 +699,7 @@ void WSeatPrivate::updateCapabilities() } } - handle()->set_capabilities(caps); + wlr_seat_set_capabilities(handle(), caps); } void WSeatPrivate::attachInputDevice(WInputDevice *device) @@ -611,66 +710,159 @@ void WSeatPrivate::attachInputDevice(WInputDevice *device) Q_ASSERT(qtDevice); if (device->type() == WInputDevice::Type::Keyboard) { - auto keyboard = qobject_cast(device->handle()); - - /* We need to prepare an XKB keymap and assign it to the keyboard. This - * assumes the defaults (e.g. layout = "us"). */ - struct xkb_rule_names rules = {}; - struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); - struct xkb_keymap *keymap = xkb_map_new_from_names(context, &rules, - XKB_KEYMAP_COMPILE_NO_FLAGS); - - keyboard->set_keymap(keymap); - xkb_keymap_unref(keymap); - xkb_context_unref(context); - keyboard->set_repeat_info(25, 600); - - device->safeConnect(&qw_keyboard::notify_key, q, [this, device] (wlr_keyboard_key_event *event) { - on_keyboard_key(event, device); - }); - device->safeConnect(&qw_keyboard::notify_modifiers, q, [this, device] () { - on_keyboard_modifiers(device); - }); - handle()->set_keyboard(*keyboard); + auto keyboard = wlr_keyboard_from_input_device(device->handle()); + + if (device == groupkeyboardDevice || device->isVirtual()) { + /* We need to prepare an XKB keymap and assign it to the keyboard. */ + struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + struct xkb_keymap *keymap = xkb_map_new_from_names(context, &xkbRules, + XKB_KEYMAP_COMPILE_NO_FLAGS); + wlr_keyboard_set_keymap(keyboard, keymap); + xkb_keymap_unref(keymap); + xkb_context_unref(context); + + auto *listeners = device->listeners(q_ptr); + listeners->add(&keyboard->events.key, this, + [this, device] (wlr_keyboard_key_event *event) { + on_keyboard_key(event, device); + }); + listeners->add(&keyboard->events.modifiers, this, + [this, device] (void *) { + on_keyboard_modifiers(device); + }); + q->setKeyboard(device); + } else { + // Reuse group keymap pointer so wlr_seat_set_keyboard() sees + // no keymap change and skips a spurious keymap event. + if (group && group->keyboard.keymap) { + wlr_keyboard_set_keymap(keyboard, group->keyboard.keymap); + } else { + qCWarning(lcWlSeat, + "WSeat: group keyboard has no keymap for physical keyboard '%s'", + qPrintable(device->name())); + struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + struct xkb_keymap *keymap = xkb_map_new_from_names(context, &xkbRules, + XKB_KEYMAP_COMPILE_NO_FLAGS); + wlr_keyboard_set_keymap(keyboard, keymap); + xkb_keymap_unref(keymap); + xkb_context_unref(context); + } + wlr_keyboard_group_add_keyboard(group, keyboard); + } } } void WSeatPrivate::detachInputDevice(WInputDevice *device) { - if (cursor && device->type() == WInputDevice::Type::Pointer) + // detachInputDevice is idempotent, so no type check is needed here. + if (cursor) cursor->detachInputDevice(device); if (device->type() == WInputDevice::Type::Touch) { - qCDebug(qLcWlrTouch, "WSeat: detachTouchDevice %s", qPrintable(device->qtDevice()->name())); + qCDebug(lcWlSeat, "WSeat: detachTouchDevice %s", qPrintable(device->qtDevice()->name())); auto *state = device->getAttachedData(); device->removeAttachedData(); delete state; touchDeviceList.removeOne(device); } + if (device->type() == WInputDevice::Type::Keyboard) { + // Detach this device's listeners before the native keyboard is + // finished, otherwise wlr_keyboard_finish() asserts the listener + // list is empty. + device->removeListeners(q_ptr); + // Only physical keyboards are group members. + if (device != groupkeyboardDevice && !device->isVirtual()) { + auto keyboard = wlr_keyboard_from_input_device(device->handle()); + wlr_keyboard_group_remove_keyboard(group, keyboard); + } + } [[maybe_unused]] bool ok = QWlrootsIntegration::instance()->removeInputDevice(device); Q_ASSERT(ok); } +void WSeatPrivate::applyXkbConfig() +{ + struct xkb_context *context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); + if (!context) { + qCWarning(lcWlSeat) << "Failed to create XKB context"; + return; + } + + struct xkb_keymap *keymap = xkb_keymap_new_from_names(context, &xkbRules, + XKB_KEYMAP_COMPILE_NO_FLAGS); + xkb_context_unref(context); + if (!keymap) { + qCWarning(lcWlSeat) << "Failed to compile XKB keymap from rule names"; + return; + } + + if (groupkeyboardDevice && groupkeyboardDevice->handle()->type == WLR_INPUT_DEVICE_KEYBOARD) { + auto *keyboard = wlr_keyboard_from_input_device(groupkeyboardDevice->handle()); + wlr_keyboard_set_keymap(keyboard, keymap); + } + + for (auto *device : std::as_const(deviceList)) { + if (device->type() != WInputDevice::Type::Keyboard) + continue; + + if (device->handle()->type != WLR_INPUT_DEVICE_KEYBOARD) + continue; + + auto *keyboard = wlr_keyboard_from_input_device(device->handle()); + if (keyboard) + wlr_keyboard_set_keymap(keyboard, keymap); + } + + xkb_keymap_unref(keymap); +} + WSeat::WSeat(const QString &name) - : WWrapObject(*new WSeatPrivate(this, name)) + : QObject(nullptr) + , WObject(*new WSeatPrivate(this, name)) { } -WSeat *WSeat::fromHandle(const qw_seat *handle) +WSeat::~WSeat() { - return handle->get_data(); + teardown(); + W_D(WSeat); + // Owner rule: the seat created these wrappers, it releases them (the + // native handle is dropped by destroy()). + delete d->cursorSurface; + delete d->dragSurface; } -qw_seat *WSeat::handle() const +WSeat *WSeat::fromHandle(wlr_seat *handle) { - return d_func()->handle(); + if (!handle) + return nullptr; + return static_cast(handle->data); +} + +// Some event filter related functions needs to get WSeat from QInputEvent, +// but the input event may come with a virtual device (e.g. created after a TTY +// switch by an intenal mechanism, like QHoverEvent). Thus we needs a special +// guarded getter. + +// @return A pointer to WSeat if the event is valid, nullptr if not. +WSeat *WSeat::fromInputEvent(QInputEvent *event) { + auto qtDevice = event->device(); + if (qtDevice->seatName().isEmpty()) { + return nullptr; + } else { + auto device = WInputDevice::from(qtDevice); + Q_ASSERT(device); + auto seat = device->seat(); + Q_ASSERT(seat); + return seat; + } } -wlr_seat *WSeat::nativeHandle() const +wlr_seat *WSeat::handle() const { - return d_func()->nativeHandle(); + return d_func()->handle(); } QString WSeat::name() const @@ -737,8 +929,8 @@ WGlobal::CursorShape WSeat::requestedCursorShape() const { W_DC(WSeat); - if (d->cursorClient != d->nativeHandle()->pointer_state.focused_client) { - qCritical("Focused client never set cursor shape nor surface, will fallback to `Default`"); + if (d->cursorClient != d->handle()->pointer_state.focused_client) { + qCWarning(lcWlSeat, "Focused client never set cursor shape nor surface, will fallback to `Default`"); return WGlobal::CursorShape::Default; } @@ -749,7 +941,7 @@ WSurface *WSeat::requestedCursorSurface() const { W_DC(WSeat); - if (d->cursorClient == d->nativeHandle()->pointer_state.focused_client) + if (d->cursorClient == d->handle()->pointer_state.focused_client) return d->cursorSurface; return nullptr; } @@ -783,7 +975,7 @@ void WSeat::attachInputDevice(WInputDevice *device) } if (device->type() == WInputDevice::Type::Touch) { - qCDebug(qLcWlrTouch, "WSeat: registerTouchDevice %s", qPrintable(device->qtDevice()->name())); + qCDebug(lcWlSeat, "WSeat: registerTouchDevice %s", qPrintable(device->qtDevice()->name())); auto *state = new WSeatPrivate::DeviceState; device->setAttachedData(state); d->touchDeviceList << device; @@ -793,15 +985,16 @@ void WSeat::attachInputDevice(WInputDevice *device) void WSeat::detachInputDevice(WInputDevice *device) { W_D(WSeat); + if (!d->deviceList.removeOne(device)) + return; // already detached (e.g. the seat dtor detached it first) device->setSeat(nullptr); - d->deviceList.removeOne(device); d->detachInputDevice(device); if (isValid()) d->updateCapabilities(); } -inline static WSeat *getSeat(QInputEvent *event) +[[maybe_unused]] inline static WSeat *getSeat(QInputEvent *event) { auto inputDevice = WInputDevice::from(event->device()); if (Q_UNLIKELY(!inputDevice)) @@ -840,7 +1033,7 @@ bool WSeat::sendEvent(WSurface *target, QObject *shellObject, QObject *eventObje // we should don't do anything. if (d->pointerFocusEventObject != eventObject) break; - auto nativeTarget = target->handle()->handle(); + auto nativeTarget = target->handle(); Q_ASSERT(!currentFocus || d->oldPointerFocusSurface == nativeTarget || currentFocus == nativeTarget); d->doClearPointerFocus(); break; @@ -859,8 +1052,8 @@ bool WSeat::sendEvent(WSurface *target, QObject *shellObject, QObject *eventObje } case QEvent::HoverMove: Q_FALLTHROUGH(); case QEvent::MouseMove: { - auto e = static_cast(event); - Q_ASSERT(e->source() == Qt::MouseEventNotSynthesized); + auto e = static_cast(event); + Q_ASSERT(event->type() != QEvent::MouseMove || static_cast(event)->source() == Qt::MouseEventNotSynthesized); // When begin drag, the wlroots will grab pointer event for drag, and the pointer focus is nullptr. if (d->pointerFocusEventObject) { // received HoverEnter event of next eventObject before HoverLeave event of last eventObject, @@ -879,7 +1072,7 @@ bool WSeat::sendEvent(WSurface *target, QObject *shellObject, QObject *eventObje -(we->angleDelta().x()+we->angleDelta().y()), // one of them must be 0, restore to wayland direction here. we->timestamp()); } else { - qWarning("An Wheel event was received that was not sent by wlroot and will be ignored"); + qCWarning(lcWlSeat, "An Wheel event was received that was not sent by wlroot and will be ignored"); } break; } @@ -911,37 +1104,39 @@ bool WSeat::sendEvent(WSurface *target, QObject *shellObject, QObject *eventObje break; } case QEvent::NativeGesture: { - if (!d->gesture) + if (!d->gesture || d->gesture->handle()) break; + + auto *gesture = d->gesture->handle(); auto e = static_cast(event); switch (e->gestureType()) { case Qt::NativeGestureType::BeginNativeGesture: if (e->libInputGestureType() == WGestureEvent::WLibInputGestureType::SwipeGesture) - d->gesture->send_swipe_begin(d->nativeHandle(), e->timestamp(), e->fingerCount()); + wlr_pointer_gestures_v1_send_swipe_begin(gesture, d->handle(), e->timestamp(), e->fingerCount()); if (e->libInputGestureType() == WGestureEvent::WLibInputGestureType::PinchGesture) - d->gesture->send_pinch_begin(d->nativeHandle(), e->timestamp(), e->fingerCount()); + wlr_pointer_gestures_v1_send_pinch_begin(gesture, d->handle(), e->timestamp(), e->fingerCount()); if (e->libInputGestureType() == WGestureEvent::WLibInputGestureType::HoldGesture) - d->gesture->send_hold_begin(d->nativeHandle(), e->timestamp(), e->fingerCount()); + wlr_pointer_gestures_v1_send_hold_begin(gesture, d->handle(), e->timestamp(), e->fingerCount()); break; case Qt::NativeGestureType::PanNativeGesture: if (e->libInputGestureType() == WGestureEvent::WLibInputGestureType::SwipeGesture) - d->gesture->send_swipe_update(d->nativeHandle(), e->timestamp(), e->delta().x(), e->delta().y()); + wlr_pointer_gestures_v1_send_swipe_update(gesture, d->handle(), e->timestamp(), e->delta().x(), e->delta().y()); if (e->libInputGestureType() == WGestureEvent::WLibInputGestureType::PinchGesture) - d->gesture->send_pinch_update(d->nativeHandle(), e->timestamp(), e->delta().x(), e->delta().y(), d->lastScale, 0); + wlr_pointer_gestures_v1_send_pinch_update(gesture, d->handle(), e->timestamp(), e->delta().x(), e->delta().y(), d->lastScale, 0); break; case Qt::NativeGestureType::ZoomNativeGesture: - d->gesture->send_pinch_update(d->nativeHandle(), e->timestamp(), e->delta().x(), e->delta().y(), d->lastScale, 0); + wlr_pointer_gestures_v1_send_pinch_update(gesture, d->handle(), e->timestamp(), e->delta().x(), e->delta().y(), d->lastScale, 0); break; case Qt::NativeGestureType::RotateNativeGesture: - d->gesture->send_pinch_update(d->nativeHandle(), e->timestamp(), e->delta().x(), e->delta().y(), d->lastScale, e->value()); + wlr_pointer_gestures_v1_send_pinch_update(gesture, d->handle(), e->timestamp(), e->delta().x(), e->delta().y(), d->lastScale, e->value()); break; case Qt::NativeGestureType::EndNativeGesture: if (e->libInputGestureType() == WGestureEvent::WLibInputGestureType::SwipeGesture) - d->gesture->send_swipe_end(d->nativeHandle(), e->timestamp(), e->cancelled()); + wlr_pointer_gestures_v1_send_swipe_end(gesture, d->handle(), e->timestamp(), e->cancelled()); if (e->libInputGestureType() == WGestureEvent::WLibInputGestureType::PinchGesture) - d->gesture->send_pinch_end(d->nativeHandle(), e->timestamp(), e->cancelled()); + wlr_pointer_gestures_v1_send_pinch_end(gesture, d->handle(), e->timestamp(), e->cancelled()); if (e->libInputGestureType() == WGestureEvent::WLibInputGestureType::HoldGesture) - d->gesture->send_hold_end(d->nativeHandle(), e->timestamp(), e->cancelled()); + wlr_pointer_gestures_v1_send_hold_end(gesture, d->handle(), e->timestamp(), e->cancelled()); break; default: break; @@ -991,7 +1186,7 @@ WSurface *WSeat::pointerFocusSurface() const { W_DC(WSeat); if (auto fs = d->pointerFocusSurface()) - return WSurface::fromHandle(qw_surface::from(fs)); + return WSurface::fromHandle(fs); return nullptr; } @@ -1002,6 +1197,11 @@ void WSeat::setKeyboardFocusSurface(WSurface *surface) if (d->m_keyboardFocusSurface == surface) return; + if (!keyboard() && d->groupkeyboardDevice) { + qCWarning(lcWlSeat, "WSeat: seat keyboard is NULL in setKeyboardFocusSurface, restoring group keyboard"); + setKeyboard(d->groupkeyboardDevice); + } + d->m_keyboardFocusSurface = surface; if (isValid()) d->doSetKeyboardFocus(surface ? surface->handle() : nullptr); @@ -1021,6 +1221,42 @@ void WSeat::clearKeyboardFocusSurface() d->doSetKeyboardFocus(nullptr); } +void WSeat::addFilteredKey(uint32_t keycode) +{ + W_D(WSeat); + d->filteredKeys.insert(keycode); +} + +void WSeat::removeFilteredKey(uint32_t keycode) +{ + W_D(WSeat); + d->filteredKeys.remove(keycode); +} + +void WSeat::clearFilteredKeys() +{ + W_D(WSeat); + d->filteredKeys.clear(); +} + +bool WSeat::isKeyFiltered(uint32_t keycode) const +{ + W_DC(WSeat); + return d->filteredKeys.contains(keycode); +} + +size_t WSeat::unfilteredKeycodes(const uint32_t *keycodes, size_t numKeycodes, + const QSet &filteredKeys, uint32_t *out) +{ + size_t numUnfiltered = 0; + for (size_t i = 0; i < numKeycodes; ++i) { + if (filteredKeys.contains(keycodes[i])) + continue; + out[numUnfiltered++] = keycodes[i]; + } + return numUnfiltered; +} + void WSeat::setKeyboardFocusWindow(QWindow *window) { W_D(WSeat); @@ -1036,16 +1272,24 @@ QWindow *WSeat::keyboardFocusWindow() const void WSeat::clearKeyboardFocusWindow() { W_D(WSeat); + d->m_repeatTimer.stop(); + d->m_repeatKey.reset(); d->focusWindow = nullptr; } +WInputDevice *WSeat::keyboardGroupKeyboard() const +{ + W_DC(WSeat); + + return d->groupkeyboardDevice; +} + WInputDevice *WSeat::keyboard() const { W_DC(WSeat); - auto w_keyboard = d->handle()->get_keyboard(); + auto w_keyboard = wlr_seat_get_keyboard(d->handle()); if (w_keyboard) { - auto q_keyboard = qw_keyboard::from(w_keyboard); - auto device = WInputDevice::fromHandle(q_keyboard); + auto device = WInputDevice::fromHandle(&w_keyboard->base); Q_ASSERT(device); return device; } else { @@ -1058,10 +1302,42 @@ void WSeat::setKeyboard(WInputDevice *newKeyboard) W_D(WSeat); if (newKeyboard == keyboard()) return; - d->handle()->set_keyboard(*qobject_cast(newKeyboard->handle())); + Q_ASSERT(newKeyboard->handle()->type == WLR_INPUT_DEVICE_KEYBOARD); + wlr_seat_set_keyboard(d->handle(), wlr_keyboard_from_input_device(newKeyboard->handle())); + // wlr_seat_set_keyboard() pushes the new keyboard's modifier state to the + // focused client. A virtual keyboard carries the IME's state, not the + // user's, so an IME attaching one while Ctrl is held would make the client + // drop the held modifier without any key event. Re-send the physical state + // so pointer combos such as Ctrl+click keep working. + if (newKeyboard->isVirtual() && d->groupkeyboardDevice) { + auto *groupKeyboard = wlr_keyboard_from_input_device(d->groupkeyboardDevice->handle()); + const auto &modifiers = groupKeyboard->modifiers; + // Nothing held: the empty state set_keyboard() just sent is already right. + if (modifiers.depressed || modifiers.latched || modifiers.locked) + wlr_seat_keyboard_send_modifiers(d->handle(), &modifiers); + } Q_EMIT this->keyboardChanged(); } +void WSeat::setXkbRuleNames(const struct xkb_rule_names &rules) +{ + W_D(WSeat); + + free(const_cast(d->xkbRules.rules)); + free(const_cast(d->xkbRules.layout)); + free(const_cast(d->xkbRules.model)); + free(const_cast(d->xkbRules.variant)); + free(const_cast(d->xkbRules.options)); + + d->xkbRules.rules = rules.rules ? strdup(rules.rules) : nullptr; + d->xkbRules.layout = rules.layout ? strdup(rules.layout) : nullptr; + d->xkbRules.model = rules.model ? strdup(rules.model) : nullptr; + d->xkbRules.variant = rules.variant ? strdup(rules.variant) : nullptr; + d->xkbRules.options = rules.options ? strdup(rules.options) : nullptr; + + d->applyXkbConfig(); +} + bool WSeat::alwaysUpdateHoverTarget() const { W_DC(WSeat); @@ -1143,7 +1419,17 @@ void WSeat::notifyAxis(WCursor *cursor, WInputDevice *device, wl_pointer_axis_so // Refer to https://github.com/qt/qtwayland/blob/774c0be247bd04362fc7713919ac151c44e34ced/src/client/qwaylandinputdevice.cpp#L1089 // The direction in Qt event is in the opposite direction of wayland one, generate a event identical to Qt's direction. - QPoint angleDelta = orientation == Qt::Horizontal ? QPoint(-delta_discrete, 0) : QPoint(0, -delta_discrete); + QPoint angleDelta; + if (delta_discrete != 0) { + angleDelta = orientation == Qt::Horizontal ? QPoint(-delta_discrete, 0) : QPoint(0, -delta_discrete); + } else { + // No discrete step was reported (e.g. smooth/pixel-only scrolling). + // Fall back to the continuous delta, mirroring Qt's + // QWaylandInputDevice::Pointer::FrameData::angleDelta() fallback. + const int fallback = static_cast(delta * -12.0); + angleDelta = orientation == Qt::Horizontal ? QPoint(fallback, 0) + : QPoint(0, fallback); + } WSeatWheelEvent e(static_cast(source), delta, orientation, static_cast(rd), local, global, QPoint(), angleDelta, Qt::NoButton, d->keyModifiers, @@ -1159,18 +1445,17 @@ void WSeat::notifyAxis(WCursor *cursor, WInputDevice *device, wl_pointer_axis_so } } -void WSeat::notifyFrame(WCursor *cursor) +void WSeat::notifyFrame([[maybe_unused]] WCursor *cursor) { - Q_UNUSED(cursor); W_D(WSeat); d->doNotifyFrame(); } -void WSeat::notifyGestureBegin(WCursor *cursor, WInputDevice *device, uint32_t time_msec, uint32_t fingers, WGestureEvent::WLibInputGestureType libInputGestureType) +void WSeat::notifyGestureBegin(WCursor *cursor, WInputDevice *device, [[maybe_unused]] uint32_t time_msec, uint32_t fingers, WGestureEvent::WLibInputGestureType libInputGestureType) { W_D(WSeat); if (d->gestureActive) { - qCWarning(qLcWlrGestureEvents) << "Unexpected GestureBegin while already active"; + qCWarning(lcWlGesture) << "Unexpected GestureBegin while already active"; } d->gestureActive = true; d->gestureFingers = fingers; @@ -1185,11 +1470,11 @@ void WSeat::notifyGestureBegin(WCursor *cursor, WInputDevice *device, uint32_t t QCoreApplication::sendEvent(w, &e); } -void WSeat::notifyGestureUpdate(WCursor *cursor, WInputDevice *device, uint32_t time_msec, const QPointF &delta, double scale, double rotation, WGestureEvent::WLibInputGestureType libInputGestureType) +void WSeat::notifyGestureUpdate(WCursor *cursor, WInputDevice *device, [[maybe_unused]] uint32_t time_msec, const QPointF &delta, double scale, double rotation, WGestureEvent::WLibInputGestureType libInputGestureType) { W_D(WSeat); if (!d->gestureActive) { - qCWarning(qLcWlrGestureEvents) << "Unexpected GestureUpdate while not begin"; + qCWarning(lcWlGesture) << "Unexpected GestureUpdate while not begin"; return; } auto qwDevice = qobject_cast(device->qtDevice()); @@ -1217,11 +1502,11 @@ void WSeat::notifyGestureUpdate(WCursor *cursor, WInputDevice *device, uint32_t } } -void WSeat::notifyGestureEnd(WCursor *cursor, WInputDevice *device, uint32_t time_msec, bool cancelled, WGestureEvent::WLibInputGestureType libInputGestureType) +void WSeat::notifyGestureEnd(WCursor *cursor, WInputDevice *device, [[maybe_unused]] uint32_t time_msec, [[maybe_unused]] bool cancelled, WGestureEvent::WLibInputGestureType libInputGestureType) { W_D(WSeat); if (!d->gestureActive) { - qCWarning(qLcWlrGestureEvents) << "Unexpected GestureEnd while not begin"; + qCWarning(lcWlGesture) << "Unexpected GestureEnd while not begin"; return; } d->gestureActive = false; @@ -1240,7 +1525,7 @@ void WSeat::notifyHoldBegin(WCursor *cursor, WInputDevice *device, uint32_t time { W_D(WSeat); if (d->gestureActive) { - qCWarning(qLcWlrGestureEvents) << "Unexpected HoldBegin while already active"; + qCWarning(lcWlGesture) << "Unexpected HoldBegin while already active"; } d->gestureActive = true; d->gestureFingers = fingers; @@ -1259,7 +1544,7 @@ void WSeat::notifyHoldEnd(WCursor *cursor, WInputDevice *device, uint32_t time_m { W_D(WSeat); if (!d->gestureActive) { - qCWarning(qLcWlrGestureEvents) << "Unexpected HoldEnd while not begin"; + qCWarning(lcWlGesture) << "Unexpected HoldEnd while not begin"; return; } d->gestureActive = false; @@ -1278,9 +1563,8 @@ void WSeat::notifyHoldEnd(WCursor *cursor, WInputDevice *device, uint32_t time_m // deal with touch event form wlr_cursor -void WSeat::notifyTouchDown(WCursor *cursor, WInputDevice *device, int32_t touch_id, uint32_t time_msec) +void WSeat::notifyTouchDown(WCursor *cursor, WInputDevice *device, int32_t touch_id, [[maybe_unused]] uint32_t time_msec) { - W_D(WSeat); auto qwDevice = qobject_cast(device->qtDevice()); Q_ASSERT(qwDevice); const QPointF &globalPos = cursor->position(); @@ -1299,7 +1583,7 @@ void WSeat::notifyTouchDown(WCursor *cursor, WInputDevice *device, int32_t touch } if (state->point(touch_id) != nullptr) { - qWarning("Inconsistent touch state, (got 'Down' But touch_id(%d) is not released", touch_id); + qCWarning(lcWlSeat, "Inconsistent touch state, (got 'Down' But touch_id(%d) is not released", touch_id); } } @@ -1311,15 +1595,13 @@ void WSeat::notifyTouchDown(WCursor *cursor, WInputDevice *device, int32_t touch newTp.area = QRect(0, 0, 8, 8); newTp.area.moveCenter(globalPos); state->m_points.append(newTp); - qCDebug(qLcWlrTouchEvents) << "Touch down form device: " << qwDevice->name() + qCDebug(lcWlTouch) << "Touch down form device: " << qwDevice->name() << ", touch id: " << touch_id << ", at position" << globalPos; } -void WSeat::notifyTouchMotion(WCursor *cursor, WInputDevice *device, int32_t touch_id, uint32_t time_msec) +void WSeat::notifyTouchMotion(WCursor *cursor, WInputDevice *device, int32_t touch_id, [[maybe_unused]] uint32_t time_msec) { - - W_DC(WSeat); auto qwDevice = qobject_cast(device->qtDevice()); Q_ASSERT(qwDevice); @@ -1337,18 +1619,17 @@ void WSeat::notifyTouchMotion(WCursor *cursor, WInputDevice *device, int32_t tou // Handle this by compressing and keeping the Pressed state until the 'frame'. if (tp->state != QEventPoint::Pressed && tp->state != QEventPoint::Released) tp->state = tmpState; - qCDebug(qLcWlrTouchEvents) << "Touch move form device: " << qwDevice->name() + qCDebug(lcWlTouch) << "Touch move form device: " << qwDevice->name() << ", touch id: " << touch_id << ", to position: " << globalPos << ", state of the point: " << tp->state; } else { - qWarning("Inconsistent touch state (got 'Motion' without 'Down'"); + qCWarning(lcWlSeat, "Inconsistent touch state (got 'Motion' without 'Down'"); } } -void WSeat::notifyTouchUp(WCursor *cursor, WInputDevice *device, int32_t touch_id, uint32_t time_msec) +void WSeat::notifyTouchUp(WCursor *cursor, WInputDevice *device, int32_t touch_id, [[maybe_unused]] uint32_t time_msec) { - W_DC(WSeat); auto qwDevice = qobject_cast(device->qtDevice()); Q_ASSERT(qwDevice); @@ -1364,7 +1645,7 @@ void WSeat::notifyTouchUp(WCursor *cursor, WInputDevice *device, int32_t touch_i for (const auto &point : std::as_const(state->m_points)) { s |= point.state; } - qCDebug(qLcWlrTouchEvents) << "Touch up form device: " << qwDevice->name() + qCDebug(lcWlTouch) << "Touch up form device: " << qwDevice->name() << ", touch id: " << tp->id << ", at position: " << tp->area.center() << ", state of all points of this device: " << s; @@ -1372,9 +1653,9 @@ void WSeat::notifyTouchUp(WCursor *cursor, WInputDevice *device, int32_t touch_i if (s == QEventPoint::Released) notifyTouchFrame(cursor); else - qCDebug(qLcWlrTouchEvents) << "waiting for all points to be released"; + qCDebug(lcWlTouch) << "waiting for all points to be released"; } else { - qWarning("Inconsistent touch state (got 'Up' without 'Down'"); + qCWarning(lcWlSeat, "Inconsistent touch state (got 'Up' without 'Down'"); } } @@ -1391,7 +1672,7 @@ void WSeat::notifyTouchCancel(WCursor *cursor, WInputDevice *device, int32_t tou point->state = static_cast(WEvent::PointCancelled); } - qCDebug(qLcWlrTouchEvents) << "Touch cancel for device: " << qwDevice->name() + qCDebug(lcWlTouch) << "Touch cancel for device: " << qwDevice->name() << ", discard the following state: " << state->m_points; if (cursor->eventWindow()) { @@ -1399,10 +1680,9 @@ void WSeat::notifyTouchCancel(WCursor *cursor, WInputDevice *device, int32_t tou } } -void WSeat::notifyTouchFrame(WCursor *cursor) +void WSeat::notifyTouchFrame([[maybe_unused]] WCursor *cursor) { W_D(WSeat); - Q_UNUSED(cursor); for (auto *device: std::as_const(d->touchDeviceList)) { d->doNotifyTouchFrame(device); } @@ -1411,13 +1691,13 @@ void WSeat::notifyTouchFrame(WCursor *cursor) void WSeat::setCursorShape(wlr_seat_client *client, WGlobal::CursorShape shape) { W_D(WSeat); - if (client != d->nativeHandle()->pointer_state.focused_client) + if (client != d->handle()->pointer_state.focused_client) return; d->cursorShape = shape; d->cursorClient = client; if (d->cursorSurface) - d->cursorSurface->safeDeleteLater(); + delete d->cursorSurface; Q_EMIT requestCursorShape(shape); } @@ -1435,16 +1715,29 @@ void WSeat::setEventFilter(WSeatEventFilter *filter) d->eventFilter = filter; } +void WSeat::setPointerGestures(WPointerGesturesV1 *gestures) +{ + W_D(WSeat); + d->gesture = gestures; +} + void WSeat::create(WServer *server) { W_D(WSeat); // destroy follow display const auto name = d->name.toUtf8(); - m_handle = qw_seat::create(*server->handle(), name.constData()); - initHandle(d->handle()); - d->handle()->set_data(this, this); + m_handle = wlr_seat_create(server->handle(), name.constData()); + Q_ASSERT(m_handle); + d->handle()->data = this; d->connect(); + if (!d->group) { + d->group = wlr_keyboard_group_create(); + wlr_input_device *inputDevice = &d->group->keyboard.base; + d->groupkeyboardDevice = new WInputDevice(inputDevice); + d->attachInputDevice(d->groupkeyboardDevice); + } + for (auto i : std::as_const(d->deviceList)) { d->attachInputDevice(i); @@ -1452,9 +1745,6 @@ void WSeat::create(WServer *server) d->cursor->attachInputDevice(i); } - if (!qEnvironmentVariableIsSet("WAYLIB_DISABLE_GESTURE")) - d->gesture = qw_pointer_gestures_v1::create(*server->handle()); - d->updateCapabilities(); if (d->cursor) @@ -1469,27 +1759,44 @@ void WSeat::destroy(WServer *) { W_D(WSeat); - for (auto i : std::as_const(d->deviceList)) { + // Device key/modifiers listeners were owned by this seat and already + // dropped by WServer::stop()/detach() via teardown() (virtual keyboards + // in particular can outlive the seat). Still clear the seat pointer. + for (auto i : std::as_const(d->deviceList)) i->setSeat(nullptr); - } d->deviceList.clear(); + d->filteredKeys.clear(); + // Need not call the DCursor::detachInputDevice on destroy WSeat, so do // call the detachCursor at clear the deviceList after. if (d->cursor) setCursor(nullptr); - if (m_handle) { - d->handle()->set_data(nullptr, nullptr); - m_handle = nullptr; - } + // Tear down the keyboard group before destroying the seat. The group + // keyboard is the seat's active keyboard; wlr_keyboard_group_destroy() + // fires the keyboard destroy signal which makes the seat drop its + // reference, so wlr_seat_destroy() below sees no dangling keyboard. + // This also lets create() rebuild the group on restart. + d->destroyKeyboardGroup(); + + // Clear the reverse fromHandle() mapping while the native seat is still + // alive, then destroy it explicitly. wlr_seat_destroy() removes the + // display_destroy listener, so the later display.reset() won't touch it. + if (d->handle() && d->handle()->data == this) + d->handle()->data = nullptr; + + wlr_seat_destroy(d->handle()); + m_handle = nullptr; } wl_global *WSeat::global() const { W_D(const WSeat); - return d->nativeHandle()->global; + if (m_handle) + return d->handle()->global; + return nullptr; } QByteArrayView WSeat::interfaceName() const @@ -1593,16 +1900,17 @@ bool WSeat::filterUnacceptedEvent(QWindow *targetWindow, QInputEvent *event) // Maybe this seat has grabbed in wlroots, should send these events to graber. case QEvent::MouseButtonPress: Q_FALLTHROUGH(); case QEvent::MouseButtonRelease: Q_FALLTHROUGH(); - case QEvent::HoverMove: Q_FALLTHROUGH(); case QEvent::MouseMove: if (static_cast(event)->source() != Qt::MouseEventNotSynthesized) return false; - if (d->handle()->pointer_has_grab()) + Q_FALLTHROUGH(); + case QEvent::HoverMove: + if (wlr_seat_pointer_has_grab(d->handle())) return sendEvent(nullptr, nullptr, nullptr, event); break; case QEvent::KeyPress: Q_FALLTHROUGH(); case QEvent::KeyRelease: - if (d->handle()->keyboard_has_grab()) + if (wlr_seat_keyboard_has_grab(d->handle())) return sendEvent(nullptr, nullptr, nullptr, event); break; // TODO: Must send the touch events to touch grabber, but the touch @@ -1653,4 +1961,10 @@ bool WSeatEventFilter::unacceptedEvent(WSeat *, QWindow *, QInputEvent *) return false; } +QList WSeat::deviceList() const +{ + W_DC(WSeat); + return d->deviceList; +} + WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wseat.h b/waylib/src/server/kernel/wseat.h index e3c924755a..5b5ead05c0 100644 --- a/waylib/src/server/kernel/wseat.h +++ b/waylib/src/server/kernel/wseat.h @@ -1,22 +1,20 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include #include #include #include +#include #include +#include Q_MOC_INCLUDE() -QW_BEGIN_NAMESPACE -class qw_seat; -class qw_surface; -QW_END_NAMESPACE - QT_BEGIN_NAMESPACE class QInputEvent; class QWindow; @@ -27,18 +25,17 @@ QT_END_NAMESPACE typedef uint wl_pointer_axis_source_t; typedef uint wl_pointer_axis_relative_direction_t; typedef uint wl_pointer_button_state_t; -struct wlr_seat; -struct wlr_seat_client; - WAYLIB_SERVER_BEGIN_NAMESPACE class WSurface; +class WPointerGesturesV1; class WSeat; class WAYLIB_SERVER_EXPORT WSeatEventFilter : public QObject { friend class WSeat; friend class WSeatPrivate; Q_OBJECT + QML_ANONYMOUS public: explicit WSeatEventFilter(QObject *parent = nullptr); @@ -53,7 +50,7 @@ class WAYLIB_SERVER_EXPORT WSeatEventFilter : public QObject class WCursor; class WSeatPrivate; -class WAYLIB_SERVER_EXPORT WSeat : public WWrapObject, public WServerInterface +class WAYLIB_SERVER_EXPORT WSeat : public QObject, public WObject, public WServerInterface { Q_OBJECT W_DECLARE_PRIVATE(WSeat) @@ -63,10 +60,11 @@ class WAYLIB_SERVER_EXPORT WSeat : public WWrapObject, public WServerInterface public: WSeat(const QString &name = QStringLiteral("seat0")); + ~WSeat() override; - static WSeat *fromHandle(const QW_NAMESPACE::qw_seat *handle); - QW_NAMESPACE::qw_seat *handle() const; - wlr_seat *nativeHandle() const; + static WSeat *fromHandle(wlr_seat *handle); + static WSeat *fromInputEvent(QInputEvent *event); + wlr_seat *handle() const; QString name() const; @@ -82,12 +80,15 @@ class WAYLIB_SERVER_EXPORT WSeat : public WWrapObject, public WServerInterface void attachInputDevice(WInputDevice *device); void detachInputDevice(WInputDevice *device); + void setXkbRuleNames(const struct xkb_rule_names &rules); + // WSurfaceItem is a kind of shellObject static bool sendEvent(WSurface *target, QObject *shellObject, QObject *eventObject, QInputEvent *event); static WSeat *get(QInputEvent *event); WSeatEventFilter *eventFilter() const; void setEventFilter(WSeatEventFilter *filter); + void setPointerGestures(WPointerGesturesV1 *gestures); WSurface *pointerFocusSurface() const; @@ -95,16 +96,33 @@ class WAYLIB_SERVER_EXPORT WSeat : public WWrapObject, public WServerInterface WSurface *keyboardFocusSurface() const; void clearKeyboardFocusSurface(); + void addFilteredKey(uint32_t keycode); + void removeFilteredKey(uint32_t keycode); + void clearFilteredKeys(); + bool isKeyFiltered(uint32_t keycode) const; + + // Copies the keycodes the client is allowed to see into `out`, dropping the + // filtered ones, and returns the number of copied keycodes. `out` must be + // able to hold `numKeycodes` elements. `keycodes` may be null when + // `numKeycodes` is 0. + static size_t unfilteredKeycodes(const uint32_t *keycodes, size_t numKeycodes, + const QSet &filteredKeys, uint32_t *out); + void setKeyboardFocusWindow(QWindow *window); QWindow *keyboardFocusWindow() const; void clearKeyboardFocusWindow(); + WInputDevice *keyboardGroupKeyboard() const; WInputDevice *keyboard() const; void setKeyboard(WInputDevice *newKeyboard); bool alwaysUpdateHoverTarget() const; void setAlwaysUpdateHoverTarget(bool newIgnoreSurfacePointerEventExclusiveGrabber); + QList deviceList() const; + + QByteArrayView interfaceName() const override; + Q_SIGNALS: void keyboardChanged(); void keyboardFocusSurfaceChanged(); @@ -112,6 +130,8 @@ class WAYLIB_SERVER_EXPORT WSeat : public WWrapObject, public WServerInterface void requestCursorSurface(WAYLIB_SERVER_NAMESPACE::WSurface *surface, const QPoint &hotspot); void requestDrag(WAYLIB_SERVER_NAMESPACE::WSurface *surface); void alwaysUpdateHoverTargetChanged(); + void relativePointerMotion(uint32_t timestamp, const QPointF &delta, + const QPointF &unacceleratedDelta); protected: using QObject::eventFilter; @@ -126,7 +146,6 @@ class WAYLIB_SERVER_EXPORT WSeat : public WWrapObject, public WServerInterface void create(WServer *server) override; void destroy(WServer *server) override; wl_global *global() const override; - QByteArrayView interfaceName() const override; // for event filter bool filterEventBeforeDisposeStage(QWindow *targetWindow, QInputEvent *event); diff --git a/waylib/src/server/kernel/wserver.cpp b/waylib/src/server/kernel/wserver.cpp index c0399f886e..1a2dcbd994 100644 --- a/waylib/src/server/kernel/wserver.cpp +++ b/waylib/src/server/kernel/wserver.cpp @@ -1,11 +1,10 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include -#define private public #include #include -#undef private +#include "private/wprivateaccessor_p.h" #include "wserver.h" #include "private/wserver_p.h" @@ -13,10 +12,8 @@ #include "wsocket.h" #include "platformplugin/qwlrootsintegration.h" -#include -#include -#include -#include +#include +#include #include #include @@ -26,26 +23,62 @@ #include #include #include +#include #include #include #include +#include #include #include #include -#include #include -QW_USE_NAMESPACE +W_DECLARE_PRIVATE_STATIC_MEMBER(QHighDpiScaling_m_globalScalingActive_tag, QHighDpiScaling, m_globalScalingActive, bool); WAYLIB_SERVER_BEGIN_NAMESPACE +void WServerInterface::setOwnsSocket(WSocket *socket) +{ + if (m_ownsSocket == socket) + return; + + m_ownsSocket = socket; +} + +WSocket *WServerInterface::ownsSocket() const +{ + return m_ownsSocket.data(); +} + +bool WServerInterface::ownsClient(WClient *client) const +{ + if (!ownsSocket()) + return true; + + for (auto *socket = client->socket(); socket; socket = socket->parentSocket()) { + if (socket == m_ownsSocket.data()) + return true; + } + + return false; +} + static bool globalFilter(const wl_client *client, const wl_global *global, void *data) { WServerPrivate *d = reinterpret_cast(data); do { - if (auto interface = d->q_func()->findInterface(global)) { + auto *interface = d->q_func()->findInterface(global); + // Native factories may publish related globals before returning their + // handles. Keep those globals inside the constructing interface's domain + // until their individual wrappers have been attached. + if (!interface) + interface = d->pendingInterface; + if (interface) { auto wclient = WClient::get(client); + if (!interface->ownsClient(wclient)) + return false; + if (!wclient) { auto client_cred = WClient::getCredentials(client); if (client_cred->pid == getpid()) { @@ -76,8 +109,9 @@ static bool globalFilter(const wl_client *client, WServerPrivate::WServerPrivate(WServer *qq) : WObjectPrivate(qq) { - display.reset(new qw_display()); - wl_display_set_global_filter(display->handle(), globalFilter, this); + display.reset(wl_display_create()); + Q_ASSERT(display); + wl_display_set_global_filter(display.get(), globalFilter, this); } WServerPrivate::~WServerPrivate() @@ -87,35 +121,38 @@ WServerPrivate::~WServerPrivate() void WServerPrivate::init() { - Q_ASSERT(display); - - // free follow display - Q_UNUSED(qw_data_device_manager::create(*display)); - Q_UNUSED(qw_primary_selection_v1_device_manager::create(*display)); + // The display is destroyed in stop() so it can be rebuilt here on a + // restart. On the first start() it was already created in the ctor. + if (!display) { + display.reset(wl_display_create()); + Q_ASSERT(display); + wl_display_set_global_filter(display.get(), globalFilter, this); + } W_Q(WServer); for (auto i : std::as_const(interfaceList)) { + Q_ASSERT(!pendingInterface); + QScopedValueRollback constructing(pendingInterface, i); i->create(q); if (auto global = i->global()) Q_ASSERT(wl_global_get_interface(global)->name == i->interfaceName()); } - loop = wl_display_get_event_loop(display->handle()); + loop = wl_display_get_event_loop(display.get()); int fd = wl_event_loop_get_fd(loop); - auto processWaylandEvents = [this] { - int ret = wl_event_loop_dispatch(loop, 0); - if (ret) - fprintf(stderr, "wl_event_loop_dispatch error: %d\n", ret); - wl_display_flush_clients(display->handle()); - }; - sockNot.reset(new QSocketNotifier(fd, QSocketNotifier::Read)); - QObject::connect(sockNot.get(), &QSocketNotifier::activated, q, processWaylandEvents); + bool ok = QObject::connect(sockNot.get(), SIGNAL(activated(QSocketDescriptor,QSocketNotifier::Type)), + q, SLOT(processWaylandEvents())); + Q_ASSERT(ok); + // Match upstream wl_display_run order: flush before dispatch. QAbstractEventDispatcher *dispatcher = QThread::currentThread()->eventDispatcher(); - QObject::connect(dispatcher, &QAbstractEventDispatcher::aboutToBlock, q, processWaylandEvents); + ok = QObject::connect(dispatcher, SIGNAL(aboutToBlock()), q, SLOT(onAboutToBlock())); + Q_ASSERT(ok); + ok = QObject::connect(dispatcher, SIGNAL(awake()), q, SLOT(onAwake())); + Q_ASSERT(ok); for (auto socket : std::as_const(sockets)) initSocket(socket); @@ -127,27 +164,220 @@ void WServerPrivate::stop() { W_Q(WServer); - if (display) - wl_display_destroy_clients(*display); + // ① Disconnect event handlers BEFORE destroying clients to prevent + // callbacks from firing during client destruction. + sockNot.reset(); + if (auto *dispatcher = QThread::currentThread()->eventDispatcher()) + QObject::disconnect(dispatcher, nullptr, q, nullptr); + // ② Stop accepting new connections on every socket, but keep the fd so + // the socket can be re-listened on the fresh display after a restart. + for (auto socket : std::as_const(sockets)) + socket->stopListen(); + + if (display) + wl_display_destroy_clients(display.get()); + + // ④ Drop native handles in reverse attach order. The interface objects + // themselves are kept alive so start() can recreate them on a new + // display. Listeners are detached first (teardown()) because several + // wlr_*_destroy() helpers assert empty listener lists. + // + // Iterate a snapshot of interfaceList so an interface attached during + // teardown/destroy() (via WServer::attach) doesn't invalidate our + // iterators. The newly attached interface stays in interfaceList and is + // created on the next start() — it is intentionally NOT destroyed here. auto list = interfaceList; - interfaceList.clear(); auto i = list.crbegin(); for (; i != list.crend(); ++i) { + if (auto *wobj = dynamic_cast(*i)) + wobj->teardown(); (*i)->destroy(q); - delete *i; } - sockNot.reset(); - QThread::currentThread()->eventDispatcher()->disconnect(q); + // ⑤ Destroy the display to reclaim every wlr object that has no public + // destroy() function ("free follow display"). This is the only release + // path for ~18 protocol managers, so it must not be removed even though + // WSeat/WXWayland/WBackend now destroy their own handles in destroy(). + display.reset(); + + // ⑥ The event loop was owned by the display; it is gone now. + loop = nullptr; +} + +// Replace wl_display_flush_clients: its wl_list_for_each_safe loop deadlocks +// when destroy-signal cascades make the pre-saved next node self-linked. +void WServerPrivate::safeFlushClients() +{ + struct wl_list *head = wl_display_get_client_list(display.get()); + struct wl_list *node = head->next; + while (node != head) { + // Self-linked node: already destroyed, stop to avoid infinite loop. + if (node->next == node) + break; + struct wl_list *next = node->next; + wl_client_flush(wl_client_from_link(node)); + node = next; + } } void WServerPrivate::initSocket(WSocket *socketServer) { - bool ok = socketServer->listen(display->handle()); + bool ok = socketServer->listen(display.get()); Q_ASSERT(ok); } +void WServerPrivate::processWaylandEvents() +{ + if (isProcessingEvents) + return; + + QScopedValueRollback guard(isProcessingEvents, true); + + int ret = wl_event_loop_dispatch(loop, 0); + if (ret) + fprintf(stderr, "wl_event_loop_dispatch error: %d\n", ret); +} + +/* + * NOTE: Wayland idle dispatch integration (Qt + wlroots hybrid loop) + * + * In a native wlroots/libwayland architecture, wl_event_loop_dispatch() + * is continuously driven by wl_display_run(), which guarantees a strict + * event-loop ordering: + * + * 1. poll()/epoll_wait() for fd activity + * 2. dispatch fd/timer/signal sources + * 3. dispatch idle sources (wl_event_loop_dispatch_idle) + * 4. return immediately into the next loop iteration + * + * In that model, idle callbacks are always executed within the same + * dispatch cycle in which they become pending, and newly scheduled idle + * tasks (e.g. from wlroots such as wlr_output_schedule_frame()) are + * guaranteed to be picked up in a timely next iteration. + * + * --------------------------------------------------------------------- + * Qt integration problem + * --------------------------------------------------------------------- + * + * In this architecture, Qt owns the main event loop, and Wayland is + * driven manually via QSocketNotifier on wl_display_get_fd(). + * + * This changes the execution model fundamentally: + * + * Qt Event Loop: + * -> processes Qt events + * -> enters aboutToBlock() + * -> waits (epoll/poll) + * + * Wayland: + * -> only progresses when Qt triggers wl_event_loop_dispatch() + * due to fd readability + * + * Therefore, wl_event_loop_dispatch(loop, 0) is NOT continuously running + * like wl_display_run(), but only executed opportunistically. + * + * --------------------------------------------------------------------- + * The critical correctness issue (idle starvation) + * --------------------------------------------------------------------- + * + * When wl_event_loop_dispatch(loop, 0) is executed: + * + * - all currently pending Wayland fd/timer/signal events are processed + * - wl_event_loop_dispatch_idle(loop) runs + * - at this point, ALL idle callbacks existing at that moment are executed + * + * However, after this point, control returns to Qt immediately. + * + * During subsequent Qt event processing, it is possible that: + * + * - Qt handlers trigger wlroots logic + * - wlroots schedules deferred work via wl_event_loop_add_idle() + * (e.g. wlr_output_schedule_frame, commit batching, repaint deferral) + * + * These newly added idle callbacks are NOT associated with any fd activity. + * + * As a result: + * + * - wl_display fd remains inactive + * - QSocketNotifier is not triggered + * - wl_event_loop_dispatch(loop, 0) is not called again + * - idle callbacks remain pending indefinitely + * + * They will only be executed later when some unrelated Wayland fd event + * occurs, causing wl_event_loop_dispatch() to run again — by which time + * the intended scheduling point (frame timing / batching window) is already + * delayed and incorrect relative to wlroots expectations. + * + * --------------------------------------------------------------------- + * Why aboutToBlock fixes this + * --------------------------------------------------------------------- + * + * QAbstractEventDispatcher::aboutToBlock() is emitted at a key semantic + * boundary in Qt: + * + * - all Qt events have been processed + * - no more Qt event handlers are running + * - the event loop is about to enter a blocking wait + * + * This makes it equivalent to the "end of event-loop iteration" point. + * + * By invoking wl_event_loop_dispatch_idle(loop) here, we effectively: + * + * - emulate wl_display_run() idle phase + * - ensure all pending Wayland idle callbacks are executed + * - drain idle tasks that were scheduled during Qt event processing + * + * This also covers the second critical case: + * + * Qt wake-up cycle: + * Qt processes events + * -> wlroots schedules new idle work + * -> Qt may not hit a new Wayland fd event immediately + * -> idle would otherwise be delayed + * + * Therefore, we must also process idle: + * + * - right before Qt sleeps (aboutToBlock) + * - and effectively on each Qt iteration boundary + * + * to preserve wl_display_run() semantics. + * + * --------------------------------------------------------------------- + * Summary + * --------------------------------------------------------------------- + * + * This manual call to wl_event_loop_dispatch_idle(loop) is required to + * restore the implicit guarantees provided by wl_display_run(): + * + * - idle callbacks are executed within the same logical iteration + * in which they are scheduled + * - wlroots frame scheduling (e.g. wlr_output_schedule_frame) is not + * delayed until the next unrelated Wayland fd event + * + * Without this, idle work can be starved indefinitely in a Qt-driven + * event loop where no Wayland fd activity occurs. + * + * This is a deliberate synchronization point between Qt's event loop + * lifecycle and Wayland's idle scheduling model. + */ +void WServerPrivate::onAboutToBlock() +{ + if (isProcessingEvents) + return; + + wl_event_loop_dispatch_idle(loop); + safeFlushClients(); +} + +void WServerPrivate::onAwake() +{ + if (isProcessingEvents) + return; + + wl_event_loop_dispatch_idle(loop); +} + WServer::WServer(QObject *parent) : WServer(*new WServerPrivate(this), parent) { @@ -158,6 +388,12 @@ WServer::~WServer() { if (isRunning()) stop(); + + W_D(WServer); + // stop() keeps interface objects alive so start() can recreate them; + // nothing recreates them in the destructor, so delete the wrappers now. + qDeleteAll(d->interfaceList); + d->interfaceList.clear(); } WServer::WServer(WServerPrivate &dd, QObject *parent) @@ -166,7 +402,7 @@ WServer::WServer(WServerPrivate &dd, QObject *parent) { } -qw_display *WServer::handle() const +wl_display *WServer::handle() const { W_DC(WServer); return d->display.get(); @@ -176,7 +412,10 @@ void WServer::stop() { W_D(WServer); - Q_ASSERT(d->display); + // A no-op when not running instead of asserting, so stop()/start() can + // be called defensively and stop() is safe after a previous stop(). + if (!isRunning()) + return; d->stop(); } @@ -219,6 +458,11 @@ bool WServer::detach(WServerInterface *interface) if (!isRunning()) return false; + // Match stop(): drop wl_signal listeners before destroy() so native + // objects that assert empty listener lists (and ~WObject) stay safe + // when callers detach an interface without going through stop(). + if (auto *wobj = dynamic_cast(interface)) + wobj->teardown(); interface->destroy(this); return true; } @@ -277,15 +521,15 @@ WServer *WServer::from(WServerInterface *interface) return interface->m_server; } -static bool initializeQtPlatform(bool isMaster, const QStringList ¶meters, std::function onInitialized) +static bool initializeQtPlatform(const QStringList ¶meters, std::function onInitialized) { Q_ASSERT(QGuiApplication::instance() == nullptr); if (QGuiApplicationPrivate::platform_integration) return false; QHighDpiScaling::initHighDpiScaling(); - QHighDpiScaling::m_globalScalingActive = true; // force enable hidpi - QGuiApplicationPrivate::platform_integration = new QWlrootsIntegration(isMaster, parameters, onInitialized); + W_PRIVATE_STATIC_MEMBER(QHighDpiScaling_m_globalScalingActive_tag{}) = true; // force enable hidpi + QGuiApplicationPrivate::platform_integration = new QWlrootsIntegration(parameters, onInitialized); // for platform theme QStringList themeNames = QWlrootsIntegration::instance()->themeNames(); @@ -324,35 +568,23 @@ void WServer::start() { W_D(WServer); + // Reentry guard: a running server is already initialized. + if (isRunning()) + return; d->init(); } -void WServer::initializeQPA(bool master, const QStringList ¶meters) +void WServer::initializeQPA(const QStringList ¶meters, + std::function createPlatformTheme) { - if (!initializeQtPlatform(master, parameters, nullptr)) { - qFatal("Can't initialize Qt platform plugin."); - return; + if (createPlatformTheme) { + QWlrootsIntegration::setCreatePlatformThemeCallback(std::move(createPlatformTheme)); } -} - -void WServer::initializeProxyQPA(int &argc, char **argv, const QStringList &proxyPlatformPlugins, const QStringList ¶meters) -{ - Q_ASSERT(!proxyPlatformPlugins.isEmpty()); - W_DC(WServer); - QPlatformIntegration *proxy = nullptr; - for (const QString &name : std::as_const(proxyPlatformPlugins)) { - if (name.isEmpty()) - continue; - proxy = QPlatformIntegrationFactory::create(name, parameters, argc, argv); - if (proxy) - break; - } - if (!proxy) { - qFatal() << "Can't create the proxy platform plugin:" << proxyPlatformPlugins; + if (!initializeQtPlatform(parameters, nullptr)) { + qFatal("Can't initialize Qt platform plugin."); + return; } - proxy->initialize(); - QWlrootsIntegration::instance()->setProxy(proxy); } bool WServer::isRunning() const diff --git a/waylib/src/server/kernel/wserver.h b/waylib/src/server/kernel/wserver.h index 83552b7be8..8d929b3e71 100644 --- a/waylib/src/server/kernel/wserver.h +++ b/waylib/src/server/kernel/wserver.h @@ -1,25 +1,26 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include -#include #include #include #include +#include + +#include QT_BEGIN_NAMESPACE +class QPlatformTheme; class QProcess; QT_END_NAMESPACE -QW_BEGIN_NAMESPACE -class qw_display; -QW_END_NAMESPACE - +struct wl_display; struct wl_global; +Q_MOC_INCLUDE("private/wserver_p.h") WAYLIB_SERVER_BEGIN_NAMESPACE typedef bool (*GlobalFilterFunc)(const wl_client *client, @@ -57,6 +58,10 @@ class WAYLIB_SERVER_EXPORT WServerInterface m_filter = f; } + void setOwnsSocket(WSocket *socket); + WSocket *ownsSocket() const; + bool ownsClient(WClient *client) const; + virtual QByteArrayView interfaceName() const = 0; protected: @@ -64,14 +69,15 @@ class WAYLIB_SERVER_EXPORT WServerInterface WServer *m_server = nullptr; std::function m_filter; - virtual void create(WServer *server) { - Q_UNUSED(server); + virtual void create([[maybe_unused]] WServer *server) { } - virtual void destroy(WServer *server) { - Q_UNUSED(server); + virtual void destroy([[maybe_unused]] WServer *server) { } virtual wl_global *global() const = 0; +private: + QPointer m_ownsSocket; + friend class WServer; friend class WServerPrivate; }; @@ -88,7 +94,7 @@ class WAYLIB_SERVER_EXPORT WServer : public QObject, public WObject explicit WServer(QObject *parent = nullptr); ~WServer(); - QW_NAMESPACE::qw_display *handle() const; + wl_display *handle() const; void attach(WServerInterface *interface); template @@ -135,10 +141,22 @@ class WAYLIB_SERVER_EXPORT WServer : public QObject, public WObject static WServer *from(WServerInterface *interface); + // Restart invariants (WM-194): + // * stop() destroys the wl_display (and thus every wlr object that has + // no public destroy() function — "free follow display"), but keeps + // the WServerInterface wrapper objects alive. start() rebuilds the + // display and calls create() again on every interface. + // * Between stop() and the next start(), handle() is null and the wlr + // handles behind interface->handle()/interface->global() have been + // freed — do not dereference them. The interface objects themselves + // remain valid and can be iterated/attached/detached. + // * start() is a no-op when already running; stop() is a no-op when not + // running, so stop()/start() may be cycled and called defensively. void start(); void stop(); - static void initializeQPA(bool master = true, const QStringList ¶meters = {}); - void initializeProxyQPA(int &argc, char **argv, const QStringList &proxyPlatformPlugins = {}, const QStringList ¶meters = {}); + static void initializeQPA( + const QStringList ¶meters = {}, + std::function createPlatformTheme = {}); bool isRunning() const; void addSocket(WSocket *socket); @@ -150,6 +168,11 @@ class WAYLIB_SERVER_EXPORT WServer : public QObject, public WObject protected: WServer(WServerPrivate &dd, QObject *parent = nullptr); + +private: + W_PRIVATE_SLOT(void processWaylandEvents()) + W_PRIVATE_SLOT(void onAboutToBlock()) + W_PRIVATE_SLOT(void onAwake()) }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wsocket.cpp b/waylib/src/server/kernel/wsocket.cpp index 8c6ba62cbb..f73c3454a4 100644 --- a/waylib/src/server/kernel/wsocket.cpp +++ b/waylib/src/server/kernel/wsocket.cpp @@ -1,8 +1,9 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wsocket.h" #include "private/wglobal_p.h" +#include "wayliblogging.h" #include #include @@ -10,14 +11,18 @@ #include #include +#include #include #include #include #include +#include #include #include #include +#include +#include struct wl_event_source; @@ -39,22 +44,23 @@ static int wl_socket_lock(const QString &socketFile) (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)); if (fd_lock < 0) { - qDebug("unable to open lockfile %s check permissions", qPrintable(lockFile)); + qCWarning(lcWlSocket) << "Failed to open lockfile" << lockFile << "- please check file permissions"; goto err; } if (flock(fd_lock, LOCK_EX | LOCK_NB) < 0) { - qDebug("unable to lock lockfile %s, maybe another compositor is running", qPrintable(lockFile)); + qCWarning(lcWlSocket) << "Failed to lock" << lockFile << "- another compositor may be running"; goto err_fd; } if (lstat(addr_sun_path, &socket_stat) < 0 ) { if (errno != ENOENT) { - qDebug("did not manage to stat file %s\n", qPrintable(addr_sun_path)); + qCWarning(lcWlSocket) << "Failed to stat file:" << socketFile; goto err_fd; } } else if (socket_stat.st_mode & S_IWUSR || socket_stat.st_mode & S_IWGRP) { + qCDebug(lcWlSocket) << "Removing existing socket file:" << socketFile; unlink(addr_sun_path); } @@ -103,7 +109,17 @@ static int wl_os_socket_cloexec(int domain, int type, int protocol) static int wl_os_accept_cloexec(int sockfd, sockaddr *addr, socklen_t *addrlen) { - int fd = accept(sockfd, addr, addrlen); + int fd; + + // First try accept4, preferred on modern Linux systems + fd = accept4(sockfd, addr, addrlen, SOCK_CLOEXEC); + if (fd >= 0) + return fd; + if (errno != ENOSYS) + return -1; + + // Fallback to traditional approach if accept4 is not supported + fd = accept(sockfd, addr, addrlen); return set_cloexec_or_close(fd); } // Copy end @@ -111,9 +127,15 @@ static int wl_os_accept_cloexec(int sockfd, sockaddr *addr, socklen_t *addrlen) class Q_DECL_HIDDEN WSocketPrivate : public WObjectPrivate { public: - WSocketPrivate(WSocket *qq, bool freeze, WSocket *parent) + WSocketPrivate(WSocket *qq, bool freeze) : WObjectPrivate(qq) , freezeClientWhenDisable(freeze) + , parentSocket(nullptr) + {} + + WSocketPrivate(WSocket *qq, WSocket *parent) + : WObjectPrivate(qq) + , freezeClientWhenDisable(WSocketPrivate::get(parent)->freezeClientWhenDisable) , parentSocket(parent) {} @@ -125,6 +147,7 @@ class Q_DECL_HIDDEN WSocketPrivate : public WObjectPrivate void restore(); void addClient(WClient *client); + void doRemoveClient(WClient *client); W_DECLARE_PUBLIC(WSocket) @@ -136,6 +159,13 @@ class Q_DECL_HIDDEN WSocketPrivate : public WObjectPrivate QString socket_file; QPointer parentSocket; + // for wp_security_context_v1 + // This WSocket object living is managed by WSecurityContextManager + // So using the QByteArrayView ref the source data to avoid the deep copy + QByteArrayView sandboxEngine; + QByteArrayView appId; + QByteArrayView instanceId; + wl_display *display = nullptr; wl_event_source *eventSource = nullptr; QList clients; @@ -146,20 +176,25 @@ struct Q_DECL_HIDDEN WlClientDestroyListener { : client(client) { destroy.notify = handle_destroy; + destroy_late.notify = handle_destroy_late; } ~WlClientDestroyListener(); static WlClientDestroyListener *get(const wl_client *client); + static WlClientDestroyListener *get_late(const wl_client *client); static void handle_destroy(struct wl_listener *listener, void *); + static void handle_destroy_late(struct wl_listener *listener, void *); wl_listener destroy; + wl_listener destroy_late; QPointer client; }; WlClientDestroyListener::~WlClientDestroyListener() { wl_list_remove(&destroy.link); + wl_list_remove(&destroy_late.link); } WlClientDestroyListener *WlClientDestroyListener::get(const wl_client *client) @@ -170,7 +205,19 @@ WlClientDestroyListener *WlClientDestroyListener::get(const wl_client *client) return nullptr; } - WlClientDestroyListener *tmp = wl_container_of(listener, tmp, destroy); + WlClientDestroyListener *tmp = W_CONTAINER_OF(listener, WlClientDestroyListener, destroy); + return tmp; +} + +WlClientDestroyListener *WlClientDestroyListener::get_late(const wl_client *client) +{ + wl_listener *listener = wl_client_get_destroy_late_listener(const_cast(client), + WlClientDestroyListener::handle_destroy_late); + if (!listener) { + return nullptr; + } + + WlClientDestroyListener *tmp = W_CONTAINER_OF(listener, WlClientDestroyListener, destroy_late); return tmp; } @@ -223,13 +270,15 @@ void WSocketPrivate::addClient(WClient *client) class Q_DECL_HIDDEN WClientPrivate : public WObjectPrivate { public: - WClientPrivate(wl_client *handle, WSocket *socket, WClient *qq) + WClientPrivate(wl_client *handle, WSocket *socket, WClient *qq, bool isWlClientOwned) : WObjectPrivate(qq) , handle(handle) , socket(socket) + , isWlClientOwned(isWlClientOwned) { auto listener = new WlClientDestroyListener(qq); wl_client_add_destroy_listener(handle, &listener->destroy); + wl_client_add_destroy_late_listener(handle, &listener->destroy_late); } ~WClientPrivate() { @@ -238,6 +287,8 @@ class Q_DECL_HIDDEN WClientPrivate : public WObjectPrivate if (handle) { auto listener = WlClientDestroyListener::get(handle); + if (!listener) + listener = WlClientDestroyListener::get_late(handle); Q_ASSERT(listener); delete listener; } @@ -249,26 +300,38 @@ class Q_DECL_HIDDEN WClientPrivate : public WObjectPrivate WSocket *socket = nullptr; mutable QSharedPointer credentials; mutable int pidFD = -1; + bool isWlClientOwned = true; }; void WlClientDestroyListener::handle_destroy(wl_listener *listener, void *data) { - WlClientDestroyListener *self = wl_container_of(listener, self, destroy); - if (self->client) { + WlClientDestroyListener *self = W_CONTAINER_OF(listener, WlClientDestroyListener, destroy); + if (self->client && self->client->handle()) { Q_ASSERT(reinterpret_cast(data) == self->client->handle()); - self->client->d_func()->handle = nullptr; - auto socket = self->client->socket(); + auto client = self->client.data(); + auto socket = client->socket(); Q_ASSERT(socket); - bool ok = socket->removeClient(self->client); - Q_ASSERT(ok); + // Remove from list without emitting Qt signals to avoid event loop reentrancy. + // WClient deletion is still deferred to handle_destroy_late until resources are destroyed. + WSocketPrivate *socketPrivate = WSocketPrivate::get(socket); + socketPrivate->clients.removeOne(client); + client->d_func()->handle = nullptr; + } +} + +void WlClientDestroyListener::handle_destroy_late(wl_listener *listener, [[maybe_unused]] void *data) +{ + WlClientDestroyListener *self = W_CONTAINER_OF(listener, WlClientDestroyListener, destroy_late); + if (self->client) { + delete self->client.data(); } delete self; } -WClient::WClient(wl_client *client, WSocket *socket) +WClient::WClient(wl_client *client, WSocket *socket, bool isWlClientOwned) : QObject(nullptr) - , WObject(*new WClientPrivate(client, socket, this)) + , WObject(*new WClientPrivate(client, socket, this, isWlClientOwned)) { } @@ -320,11 +383,34 @@ QSharedPointer WClient::getCredentials(const wl_client *cl WClient *WClient::get(const wl_client *client) { + // Fast path: client is alive, its early destroy listener is in destroy_signal. if (auto tmp = WlClientDestroyListener::get(client)) return tmp->client; + // Dying path: handle_destroy has fired (wl_priv_signal_final_emit removed the + // early listener before calling it), but handle_destroy_late has not yet fired. + if (auto tmp = WlClientDestroyListener::get_late(client)) + return tmp->client; return nullptr; } +QByteArray WClient::sandboxEngine() const +{ + W_DC(WClient); + return WSocketPrivate::get(d->socket)->sandboxEngine.toByteArray(); +} + +QByteArray WClient::appId() const +{ + W_DC(WClient); + return WSocketPrivate::get(d->socket)->appId.toByteArray(); +} + +QByteArray WClient::instanceId() const +{ + W_DC(WClient); + return WSocketPrivate::get(d->socket)->instanceId.toByteArray(); +} + void WClient::freeze() { W_D(WClient); @@ -337,13 +423,32 @@ void WClient::activate() pauseClient(d->handle, false); } -WSocket::WSocket(bool freezeClientWhenDisable, WSocket *parentSocket, QObject *parent) +WSocket::WSocket(bool freezeClientWhenDisable, QObject *parent) : QObject(parent) - , WObject(*new WSocketPrivate(this, freezeClientWhenDisable, parentSocket)) + , WObject(*new WSocketPrivate(this, freezeClientWhenDisable)) { } +WSocket::WSocket(WSocket *parentSocket, QObject *parent) + : QObject(parent) + , WObject(*new WSocketPrivate(this, parentSocket)) +{ + +} + +WSocket::WSocket(const char *sandboxEngine, + const char *appId, + const char *instanceId, + WSocket *parentSocket, QObject *parent) + : WSocket(parentSocket, parent) +{ + W_D(WSocket); + d->sandboxEngine = sandboxEngine; + d->appId = appId; + d->instanceId = instanceId; +} + WSocket::~WSocket() { close(); @@ -401,10 +506,11 @@ void WSocket::close() } if (!d->clients.isEmpty()) { - for (auto client : std::as_const(d->clients)) - delete client; + QList clientsToClose; + std::swap(clientsToClose, d->clients); + for (auto client : std::as_const(clientsToClose)) + d->doRemoveClient(client); - d->clients.clear(); Q_EMIT clientsChanged(); } } @@ -452,7 +558,7 @@ bool WSocket::create(const QString &filePath) if (isValid()) return false; - d->fd = wl_os_socket_cloexec(PF_LOCAL, SOCK_STREAM, 0); + d->fd = wl_os_socket_cloexec(PF_LOCAL, SOCK_STREAM | SOCK_NONBLOCK, 0); if (d->fd < 0) return false; @@ -471,13 +577,13 @@ bool WSocket::create(const QString &filePath) socklen_t size = offsetof(sockaddr_un, sun_path) + pathLength; if (::bind(d->fd, (sockaddr*) &addr, size) < 0) { close(); - qDebug("bind() failed with error: %s", strerror(errno)); + qCWarning(lcWlSocket) << "Socket bind failed:" << QString::fromLocal8Bit(strerror(errno)); return false; } if (::listen(d->fd, 128) < 0) { close(); - qDebug("listen() failed with error: %s\n", strerror(errno)); + qCWarning(lcWlSocket) << "Socket listen failed:" << QString::fromLocal8Bit(strerror(errno)); return false; } @@ -493,12 +599,12 @@ bool WSocket::create(const QString &filePath) static QString getSocketFile(int fd, bool doCheck) { if (doCheck) { // check socket file - struct ::stat stat_buf = {0}; + struct ::stat stat_buf{}; if (fstat(fd, &stat_buf) != 0) { - qDebug("fstat failed on create by FD"); + qCWarning(lcWlSocket) << "Failed to fstat file descriptor"; return {}; } else if (!S_ISSOCK(stat_buf.st_mode)) { - qDebug("fd is not a socket"); + qCWarning(lcWlSocket) << "File descriptor is not a socket"; return {}; } @@ -506,10 +612,10 @@ static QString getSocketFile(int fd, bool doCheck) { socklen_t accept_conn_size = sizeof(accept_conn); if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, &accept_conn, &accept_conn_size) != 0) { - qDebug("getsockopt failed on FD"); + qCWarning(lcWlSocket) << "Failed to get socket options:" << QString::fromLocal8Bit(strerror(errno)); return {}; } else if (accept_conn == 0) { - qDebug("fd is not a socket"); + qCWarning(lcWlSocket) << "File descriptor is not in listening mode"; return {}; } } @@ -562,7 +668,7 @@ bool WSocket::create(int fd, bool doListen) return false; if (doListen && ::listen(d->fd, 128) < 0) { - qDebug("listen() failed with error: %s\n", strerror(errno)); + qCWarning(lcWlSocket) << "Failed to listen on socket:" << QString::fromLocal8Bit(strerror(errno)); return false; } @@ -607,8 +713,9 @@ static int socket_data(int fd, uint32_t, void *data) length = sizeof name; client_fd = wl_os_accept_cloexec(fd, (sockaddr*)&name, &length); if (client_fd < 0) { - qDebug("failed to accept: %s", strerror(errno)); + qCWarning(lcWlSocket) << "Failed to accept client connection:" << QString::fromLocal8Bit(strerror(errno)); } else { + qCDebug(lcWlSocket) << "Accepted new client connection with fd:" << client_fd; d->q_func()->addClient(client_fd); } @@ -638,22 +745,39 @@ bool WSocket::listen(wl_display *display) return true; } +void WSocket::stopListen() +{ + W_D(WSocket); + + // Mirror the event-source teardown done at the top of close(), but stop + // there: keep the fd and the client list so the socket can be listened + // again on a rebuilt display after WServer::stop(). + if (d->eventSource) { + wl_event_source_remove(d->eventSource); + d->eventSource = nullptr; + d->display = nullptr; + Q_EMIT listeningChanged(); + } + Q_ASSERT(!d->display); +} + WClient *WSocket::addClient(int fd) { W_D(WSocket); auto client = wl_client_create(d->display, fd); if (!client) { - qWarning() << "wl_client_create failed"; + qCWarning(lcWlSocket) << "Failed to create Wayland client for fd:" << fd; return nullptr; } + qCDebug(lcWlSocket) << "Created new Wayland client for fd:" << fd; auto wclient = new WClient(client, this); d->addClient(wclient); return wclient; } -WClient *WSocket::addClient(wl_client *client) +WClient *WSocket::addClient(wl_client *client, bool isWlClientOwned) { W_D(WSocket); @@ -664,17 +788,32 @@ WClient *WSocket::addClient(wl_client *client) if (d->clients.contains(wclient)) return wclient; } else { - wclient = new WClient(client, this); + wclient = new WClient(client, this, isWlClientOwned); } d->addClient(wclient); return wclient; } -bool WSocket::removeClient(wl_client *client) +void WSocketPrivate::doRemoveClient(WClient *client) { - W_D(WSocket); + W_Q(WSocket); + + Q_EMIT q->aboutToBeDestroyedClient(client); + + auto handle = client->handle(); + if (handle && client->d_func()->isWlClientOwned) { + // Set handle to nullptr to prevent handle_destroy from calling removeClient again + client->d_func()->handle = nullptr; + delete client; + wl_client_destroy(handle); + } else { + delete client; + } +} +bool WSocket::removeClient(wl_client *client) +{ if (auto c = WClient::get(client)) return removeClient(c); return false; @@ -684,12 +823,11 @@ bool WSocket::removeClient(WClient *client) { W_D(WSocket); - bool ok = d->clients.removeOne(client); - if (!ok) + if (!d->clients.removeOne(client)) return false; - Q_EMIT aboutToBeDestroyedClient(client); - delete client; + d->doRemoveClient(client); + Q_EMIT clientsChanged(); return true; @@ -707,8 +845,12 @@ bool WSocket::isEnabled() const return d->enabled; } -void WSocket::setEnabled(bool on) +void WSocket::setEnabled(bool on, const WSocket *excludedSocket) { + if (this == excludedSocket && !on) { + return; + } + W_D(WSocket); if (d->enabled == on) return; diff --git a/waylib/src/server/kernel/wsocket.h b/waylib/src/server/kernel/wsocket.h index 16f7de2a1e..dadc1fb3a7 100644 --- a/waylib/src/server/kernel/wsocket.h +++ b/waylib/src/server/kernel/wsocket.h @@ -19,6 +19,9 @@ class WAYLIB_SERVER_EXPORT WClient : public QObject, public WObject { Q_OBJECT W_DECLARE_PRIVATE(WClient) + Q_PROPERTY(QByteArray sandboxEngine READ sandboxEngine CONSTANT FINAL) + Q_PROPERTY(QByteArray appId READ appId CONSTANT FINAL) + Q_PROPERTY(QByteArray instanceId READ instanceId CONSTANT FINAL) // Using for QQmlListProperty QML_ANONYMOUS @@ -38,14 +41,19 @@ class WAYLIB_SERVER_EXPORT WClient : public QObject, public WObject [[nodiscard]] static QSharedPointer getCredentials(const wl_client *client); static WClient *get(const wl_client *client); + QByteArray sandboxEngine() const; + QByteArray appId() const; + QByteArray instanceId() const; + public Q_SLOTS: void freeze(); void activate(); private: friend class WSocket; - friend class WlClientDestroyListener; - explicit WClient(wl_client *client, WSocket *socket); + friend class WSocketPrivate; + friend struct WlClientDestroyListener; + explicit WClient(wl_client *client, WSocket *socket, bool isWlClientOwned = true); ~WClient() = default; using QObject::deleteLater; }; @@ -60,10 +68,12 @@ class WAYLIB_SERVER_EXPORT WSocket : public QObject, public WObject Q_PROPERTY(bool valid READ isValid NOTIFY validChanged FINAL) Q_PROPERTY(bool listening READ isListening NOTIFY listeningChanged FINAL) Q_PROPERTY(QString fullServerName READ fullServerName NOTIFY fullServerNameChanged FINAL) - Q_PROPERTY(WSocket* parentSocket READ parentSocket WRITE setParentSocket NOTIFY parentSocketChanged FINAL) + Q_PROPERTY(WSocket* parentSocket READ parentSocket NOTIFY parentSocketChanged FINAL) + Q_PROPERTY(WSocket* rootSocket READ rootSocket CONSTANT FINAL) public: - explicit WSocket(bool freezeClientWhenDisable, WSocket *parentSocket = nullptr, QObject *parent = nullptr); + explicit WSocket(bool freezeClientWhenDisable, QObject *parent = nullptr); + explicit WSocket(WSocket *parentSocket, QObject *parent = nullptr); ~WSocket(); static WSocket *get(const wl_client *client); @@ -84,17 +94,19 @@ class WAYLIB_SERVER_EXPORT WSocket : public QObject, public WObject bool isListening() const; bool listen(struct wl_display *display); + // Remove the wayland event source for this socket but keep the fd and + // existing clients, so the socket can be re-listened on a new display + // after WServer::stop()/start(). Inverse of listen(). + void stopListen(); + WClient *addClient(int fd); - WClient *addClient(wl_client *client); + WClient *addClient(wl_client *client, bool isWlClientOwned = true); bool removeClient(wl_client *client); bool removeClient(WClient *client); const QList &clients() const; bool isEnabled() const; - void setEnabled(bool on); - -public Q_SLOTS: - void setParentSocket(WSocket *parentSocket); + void setEnabled(bool on, const WSocket *excludedSocket = nullptr); Q_SIGNALS: void enabledChanged(); @@ -105,6 +117,17 @@ public Q_SLOTS: void clientAdded(WClient *client); void aboutToBeDestroyedClient(WClient *client); void parentSocketChanged(); + +private: + explicit WSocket(const char *sandboxEngine, + const char *appId, + const char *instanceId, + WSocket *parentSocket, QObject *parent = nullptr); + + friend class WXWayland; + friend void security_context_handle_commit(struct wl_client*, + struct wl_resource*); + void setParentSocket(WSocket *parent); }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wsubsurface.cpp b/waylib/src/server/kernel/wsubsurface.cpp new file mode 100644 index 0000000000..8d0549b774 --- /dev/null +++ b/waylib/src/server/kernel/wsubsurface.cpp @@ -0,0 +1,96 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wsubsurface.h" + +#include "private/wsubsurface_p.h" +#include "wsurface.h" + +WAYLIB_SERVER_BEGIN_NAMESPACE + +WSubsurfacePrivate::WSubsurfacePrivate(WSubsurface *q, + WSubsurface::Type type, + WSurface *parentSurface, + WSurface *surface) + : WObjectPrivate(q) + , type(type) + , mapped(surface && surface->mapped()) + , parentSurface(parentSurface) + , surface(surface) +{ +} + +WSubsurface::WSubsurface(Type type, + WSurface *parentSurface, + WSurface *surface) + : QObject(nullptr) + , WObject(*new WSubsurfacePrivate(this, type, parentSurface, surface)) +{ +} + +WSubsurface::~WSubsurface() = default; + +WSubsurface::Type WSubsurface::type() const +{ + W_DC(WSubsurface); + return d->type; +} + +WSubsurface::Place WSubsurface::place() const +{ + W_DC(WSubsurface); + return d->place; +} + +QPointF WSubsurface::position() const +{ + W_DC(WSubsurface); + return d->position; +} + +bool WSubsurface::isMapped() const +{ + W_DC(WSubsurface); + return d->mapped; +} + +WSurface *WSubsurface::parentSurface() const +{ + W_DC(WSubsurface); + return d->parentSurface; +} + +WSurface *WSubsurface::surface() const +{ + W_DC(WSubsurface); + return d->surface; +} + +void WSubsurface::setPlace(Place place) +{ + W_D(WSubsurface); + if (d->place == place) + return; + d->place = place; + Q_EMIT placeChanged(place); +} + +void WSubsurface::setPosition(const QPointF &position) +{ + W_D(WSubsurface); + if (d->position == position) + return; + d->position = position; + Q_EMIT positionChanged(position); +} + +void WSubsurface::setMapped(bool mapped) +{ + W_D(WSubsurface); + if (d->mapped == mapped) + return; + d->mapped = mapped; + Q_EMIT mappedChanged(mapped); +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wsubsurface.h b/waylib/src/server/kernel/wsubsurface.h new file mode 100644 index 0000000000..0e15b08360 --- /dev/null +++ b/waylib/src/server/kernel/wsubsurface.h @@ -0,0 +1,71 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "wglobal.h" + +#include +#include +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WSurface; +class WSurfacePrivate; +class WSubsurfacePrivate; +class RemoteSubsurfaceContext; + +class WAYLIB_SERVER_EXPORT WSubsurface : public QObject, public WObject +{ + Q_OBJECT + W_DECLARE_PRIVATE(WSubsurface) + Q_PROPERTY(Type type READ type CONSTANT FINAL) + Q_PROPERTY(Place place READ place NOTIFY placeChanged FINAL) + Q_PROPERTY(QPointF position READ position NOTIFY positionChanged FINAL) + Q_PROPERTY(bool mapped READ isMapped NOTIFY mappedChanged FINAL) + Q_PROPERTY(WSurface *parentSurface READ parentSurface CONSTANT FINAL) + Q_PROPERTY(WSurface *surface READ surface CONSTANT FINAL) + +public: + enum class Type { + Standard, + Remote, + }; + Q_ENUM(Type) + + enum class Place { + Below, + Above, + }; + Q_ENUM(Place) + + ~WSubsurface() override; + + Type type() const; + Place place() const; + QPointF position() const; + bool isMapped() const; + + WSurface *parentSurface() const; + WSurface *surface() const; + +Q_SIGNALS: + void positionChanged(const QPointF &position); + void placeChanged(Place place); + void mappedChanged(bool mapped); + +private: + WSubsurface(Type type, + WSurface *parentSurface, + WSurface *surface); + + void setPlace(Place place); + void setPosition(const QPointF &position); + void setMapped(bool mapped); + + friend class WSurfacePrivate; + friend class RemoteSubsurfaceContext; +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wsurface.cpp b/waylib/src/server/kernel/wsurface.cpp index 4004ed2b79..2ed354399b 100644 --- a/waylib/src/server/kernel/wsurface.cpp +++ b/waylib/src/server/kernel/wsurface.cpp @@ -1,31 +1,26 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wsurface.h" -#include "qwglobal.h" +#include "wscoplistener.h" #include "wseat.h" #include "private/wsurface_p.h" #include "woutput.h" +#include "wsubsurface.h" +#include "wayliblogging.h" -#include -#include -#include -#include -#include -#include -#include +#include -extern "C" { -#include -} +#include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE -WSurfacePrivate::WSurfacePrivate(WSurface *qq, qw_surface *handle) - : WWrapObjectPrivate(qq) +WSurfacePrivate::WSurfacePrivate(WSurface *qq, wlr_surface *handle) + : WWaylandResourcePrivate(qq) { - initHandle(handle); + Q_ASSERT(handle); + handle->data = qq; + m_handle = handle; } WSurfacePrivate::~WSurfacePrivate() @@ -35,7 +30,7 @@ WSurfacePrivate::~WSurfacePrivate() wl_client *WSurfacePrivate::waylandClient() const { - if (auto handle = nativeHandle()) + if (auto handle = m_handle) return handle->resource->client; return nullptr; } @@ -44,104 +39,90 @@ void WSurfacePrivate::on_commit() { W_Q(WSurface); - if (nativeHandle()->current.committed & WLR_SURFACE_STATE_BUFFER) + needsFrame = !wl_list_empty(&m_handle->current.frame_callback_list); + + if (m_handle->current.committed & WLR_SURFACE_STATE_BUFFER) updateBuffer(); - if (nativeHandle()->current.committed & WLR_SURFACE_STATE_OFFSET) + if (m_handle->current.committed & WLR_SURFACE_STATE_OFFSET) updateBufferOffset(); - if (hasSubsurface) // Will make to true when qw_surface::newSubsurface - updateHasSubsurface(); + updateStandardSubsurfaces(); + + Q_EMIT q->commit(m_handle->current.committed); } void WSurfacePrivate::init() { W_Q(WSurface); - handle()->set_data(this, q); - connect(); updateBuffer(); - updateHasSubsurface(); - - if (auto sub = qw_subsurface::try_from_wlr_surface(handle()->handle())) - setSubsurface(sub); - - wlr_surface *surface = nativeHandle(); - wlr_subsurface *subsurface; - wl_list_for_each(subsurface, &surface->current.subsurfaces_below, current.link) { - Q_EMIT q->newSubsurface(ensureSubsurface(subsurface)); - } - - wl_list_for_each(subsurface, &surface->current.subsurfaces_above, current.link) { - Q_EMIT q->newSubsurface(ensureSubsurface(subsurface)); - } + updateStandardSubsurfaces(); } void WSurfacePrivate::connect() { W_Q(WSurface); - - QObject::connect(handle(), &qw_surface::notify_commit, q, [this] { - on_commit(); - }); - QObject::connect(handle(), &qw_surface::notify_map, q, &WSurface::mappedChanged); - QObject::connect(handle(), &qw_surface::notify_unmap, q, &WSurface::mappedChanged); - QObject::connect(handle(), &qw_surface::notify_new_subsurface, q, [q, this] (wlr_subsurface *sub) { - setHasSubsurface(true); - - auto surface = ensureSubsurface(sub); - Q_EMIT q->newSubsurface(surface); - - for (auto output : std::as_const(outputs)) - surface->enterOutput(output); + q->listeners()->add(&m_handle->events.commit, this, &WSurfacePrivate::on_commit); + q->listeners()->add(&m_handle->events.map, q, &WSurface::mappedChanged); + q->listeners()->add(&m_handle->events.unmap, q, &WSurface::mappedChanged); + q->listeners()->add(&m_handle->events.new_subsurface, q, + [q, this] (wlr_subsurface *sub) { + auto *subsurface = ensureSubsurface(sub); + updateStandardSubsurfaces(); + + for (auto *output : std::as_const(outputs)) + subsurface->surface()->enterOutput(output); }); } void WSurfacePrivate::updateOutputs() { outputs.clear(); + framePacingOutput = nullptr; wlr_surface_output *output; - wl_list_for_each(output, &nativeHandle()->current_outputs, link) { - auto qo = qw_output::from(output->output); - if (!qo) - continue; - auto o = WOutput::fromHandle(qo); + wl_list_for_each(output, &m_handle->current_outputs, link) { + auto o = WOutput::fromHandle(output->output); if (!o) continue; outputs << o; + + if (!framePacingOutput + || framePacingOutput->handle()->refresh + < output->output->refresh) { + framePacingOutput = o; + } } updatePreferredBufferScale(); } -void WSurfacePrivate::setBuffer(qw_buffer *newBuffer) +void WSurfacePrivate::setBuffer(wlr_buffer *newBuffer) { if (buffer) { - if (auto clientBuffer = qw_client_buffer::get(*buffer)) { - Q_ASSERT(clientBuffer->handle()->n_ignore_locks > 0); - clientBuffer->handle()->n_ignore_locks--; + if (auto clientBuffer = wlr_client_buffer_get(buffer.get())) { + Q_ASSERT(clientBuffer->n_ignore_locks > 0); + clientBuffer->n_ignore_locks--; } } if (newBuffer) { - if (auto clientBuffer = qw_client_buffer::get(*newBuffer)) { - clientBuffer->handle()->n_ignore_locks++; + if (auto clientBuffer = wlr_client_buffer_get(newBuffer)) { + clientBuffer->n_ignore_locks++; } - newBuffer->lock(); + wlr_buffer_lock(newBuffer); buffer.reset(newBuffer); } else { buffer.reset(nullptr); } - - Q_EMIT q_func()->bufferChanged(); } void WSurfacePrivate::updateBuffer() { - qw_buffer *buffer = nullptr; - if (nativeHandle()->buffer) - buffer = qw_buffer::from(&nativeHandle()->buffer->base); + wlr_buffer *buffer = nullptr; + if (m_handle->buffer) + buffer = &m_handle->buffer->base; setBuffer(buffer); } @@ -149,7 +130,7 @@ void WSurfacePrivate::updateBuffer() void WSurfacePrivate::updateBufferOffset() { W_Q(WSurface); - auto dBufferOffset = QPoint(nativeHandle()->current.dx, nativeHandle()->current.dy); + auto dBufferOffset = QPoint(m_handle->current.dx, m_handle->current.dy); if (!dBufferOffset.isNull()) { bufferOffset += dBufferOffset; Q_EMIT q->bufferOffsetChanged(); @@ -161,11 +142,16 @@ void WSurfacePrivate::updatePreferredBufferScale() if (explicitPreferredBufferScale > 0) return; + // Keep the last scale when the surface left all outputs (e.g. the output was + // unplugged), otherwise it would be reset to 1.0. + if (outputs.isEmpty()) + return; + float maxScale = 1.0; for (auto o : std::as_const(outputs)) maxScale = std::max(o->scale(), maxScale); if (handle()) - qw_fractional_scale_manager_v1::notify_scale(nativeHandle(), maxScale); + wlr_fractional_scale_v1_notify_scale(m_handle, maxScale); preferredBufferScale = qCeil(maxScale); preferredBufferScaleChange(); @@ -175,34 +161,180 @@ void WSurfacePrivate::preferredBufferScaleChange() { W_Q(WSurface); if (handle()) - handle()->set_preferred_buffer_scale(q->preferredBufferScale()); + wlr_surface_set_preferred_buffer_scale(m_handle, q->preferredBufferScale()); Q_EMIT q->preferredBufferScaleChanged(); } -WSurface *WSurfacePrivate::ensureSubsurface(wlr_subsurface *subsurface) +WSubsurface *WSurfacePrivate::ensureSubsurface(wlr_subsurface *subsurfaceHandle) { - if (auto surface = WSurface::fromHandle(subsurface->surface)) - return surface; + W_Q(WSurface); - auto qw_surface = qw_surface::from(subsurface->surface); - auto surface = new WSurface(qw_surface, q_func()); - QObject::connect(surface->handle(), &qw_surface::before_destroy, surface, &WSurface::safeDeleteLater); + for (auto *subsurface : std::as_const(subsurfaces)) { + if (subsurface->surface()->handle() == subsurfaceHandle->surface) { + return subsurface; + } + } + + auto *childSurface = new WSurface(subsurfaceHandle->surface); + auto *subsurface = new WSubsurface(WSubsurface::Type::Standard, q, childSurface); + WSubsurface::Place place = WSubsurface::Place::Above; + wlr_subsurface *current; + wl_list_for_each(current, &m_handle->current.subsurfaces_below, current.link) { + if (current == subsurfaceHandle) { + place = WSubsurface::Place::Below; + break; + } + } + subsurface->setPlace(place); + subsurface->setPosition(QPointF(subsurfaceHandle->current.x, subsurfaceHandle->current.y)); + subsurfaces.append(subsurface); + childSurface->d_func()->subsurface = subsurface; + + // Own this destroy listener on the child wrapper so deleting that wrapper + // during the callback also detaches the listener before wlroots asserts + // the signal list is empty at the end of native teardown. + childSurface->listeners()->add(&subsurfaceHandle->events.destroy, + [this, subsurface](void *) { + releaseSubsurface(subsurface); + }); + QObject::connect(childSurface, &WSurface::mappedChanged, subsurface, [subsurface] { + if (auto *child = subsurface->surface()) + subsurface->setMapped(child->mapped()); + }); - return surface; + setHasSubsurface(true); + Q_EMIT q->subsurfaceAdded(subsurface); + return subsurface; } -void WSurfacePrivate::setSubsurface(qw_subsurface *newSubsurface) +WSubsurface *WSurfacePrivate::addRemoteSubsurface(wlr_surface *childHandle) +{ + W_Q(WSurface); + Q_ASSERT(childHandle); + auto *childSurface = new WSurface(childHandle); + + auto *subsurface = new WSubsurface(WSubsurface::Type::Remote, q, childSurface); + remoteAbove.append(subsurface); + childSurface->d_func()->subsurface = subsurface; + // A remote subsurface has no native wlr_subsurface destroy event. Its + // wl_surface may be destroyed directly when the child client disconnects, + // so release the wrapper before wlroots asserts that surface listeners are + // gone. + childSurface->listeners()->add(&childHandle->events.destroy, + [this, subsurface](void *) { + releaseSubsurface(subsurface); + }); + // Propagate parent outputs to the remote child surface so that + // framePacingOutput is set and frame-done callbacks are delivered. + for (auto *output : std::as_const(outputs)) + childSurface->enterOutput(output); + rebuildTotalSubsurfaces(); + Q_EMIT q->subsurfaceAdded(subsurface); + return subsurface; +} + +void WSurfacePrivate::removeSubsurface(WSubsurface *subsurface) { W_Q(WSurface); - if (subsurface == newSubsurface) + if (!subsurface) + return; + + auto &targetList = (subsurface->type() == WSubsurface::Type::Remote) + ? (subsurface->place() == WSubsurface::Place::Below ? remoteBelow : remoteAbove) + : (subsurface->place() == WSubsurface::Place::Below ? standardBelow : standardAbove); + + if (!targetList.removeOne(subsurface)) { + qCCritical(lcWlSurface) << "Failed to remove subsurface from target list:" << subsurface; return; - subsurface = newSubsurface; - QObject::connect(subsurface, &qw_subsurface::destroyed, q, &WSurface::isSubsurfaceChanged); + } + + if (auto *child = subsurface->surface()) { + child->d_func()->subsurface = nullptr; + } + rebuildTotalSubsurfaces(); + Q_EMIT q->subsurfaceRemoved(subsurface); +} + +void WSurfacePrivate::releaseSubsurface(WSubsurface *subsurface) +{ + if (!subsurface) + return; + + auto *childSurface = subsurface->surface(); + + removeSubsurface(subsurface); + delete subsurface; - if (isSubsurface != !subsurface.isNull()){ - isSubsurface = !subsurface.isNull(); - Q_EMIT q->isSubsurfaceChanged(); + delete childSurface; +} + +void WSurfacePrivate::updateStandardSubsurfaces() +{ + if (subsurfaces.isEmpty() + && wl_list_empty(&m_handle->current.subsurfaces_below) + && wl_list_empty(&m_handle->current.subsurfaces_above)) { + return; } + + setSubsurfaceOrder(this->remoteBelow, this->remoteAbove); +} + +void WSurfacePrivate::setSubsurfaceOrder(const QList &newRemoteBelow, + const QList &newRemoteAbove) +{ + W_Q(WSurface); + + // 1. Process Remote subsurfaces + auto filterRemote = [q](const QList &list, WSubsurface::Place place) { + QList result; + for (auto *sub : list) { + if (!sub || sub->parentSurface() != q || sub->type() != WSubsurface::Type::Remote) + continue; + sub->setPlace(place); + result.append(sub); + } + return result; + }; + + this->remoteBelow = filterRemote(newRemoteBelow, WSubsurface::Place::Below); + this->remoteAbove = filterRemote(newRemoteAbove, WSubsurface::Place::Above); + + // 2. Snapshot and process native Standard subsurfaces + QList> positionUpdates; + auto processStandard = [this, &positionUpdates](wl_list *head, WSubsurface::Place place, QList &outList) { + outList.clear(); + QList nativeList; + wlr_subsurface *nativeSubsurface; + wl_list_for_each(nativeSubsurface, head, current.link) { + nativeList.append(nativeSubsurface); + } + for (auto *native : std::as_const(nativeList)) { + auto *subsurface = ensureSubsurface(native); + subsurface->setPlace(place); + positionUpdates.append({subsurface, QPointF(native->current.x, native->current.y)}); + outList.append(subsurface); + } + }; + + processStandard(&m_handle->current.subsurfaces_below, WSubsurface::Place::Below, this->standardBelow); + processStandard(&m_handle->current.subsurfaces_above, WSubsurface::Place::Above, this->standardAbove); + + rebuildTotalSubsurfaces(); + + for (const auto &[subsurface, position] : std::as_const(positionUpdates)) + subsurface->setPosition(position); +} + +void WSurfacePrivate::rebuildTotalSubsurfaces() +{ + const QList ordered = standardBelow + remoteBelow + standardAbove + remoteAbove; + const bool orderChanged = (subsurfaces != ordered); + if (orderChanged) + subsurfaces = ordered; + + setHasSubsurface(!subsurfaces.isEmpty()); + if (orderChanged) + Q_EMIT q_func()->subsurfaceOrderChanged(); } void WSurfacePrivate::setHasSubsurface(bool newHasSubsurface) @@ -214,77 +346,102 @@ void WSurfacePrivate::setHasSubsurface(bool newHasSubsurface) Q_EMIT q_func()->hasSubsurfaceChanged(); } -void WSurfacePrivate::updateHasSubsurface() +WSurface::WSurface(wlr_surface *handle) + : WSurface(*new WSurfacePrivate(this, handle)) { - setHasSubsurface(handle() && (!wl_list_empty(&nativeHandle()->current.subsurfaces_above) - || !wl_list_empty(&nativeHandle()->current.subsurfaces_below))); } -WSurface::WSurface(qw_surface *handle, QObject *parent) - : WSurface(*new WSurfacePrivate(this, handle), parent) +WSurface::WSurface(WSurfacePrivate &dd) + : QObject(nullptr) + , WWaylandResource(dd, nullptr) { - + dd.init(); } -WSurface::WSurface(WSurfacePrivate &dd, QObject *parent) - : WWrapObject(dd, parent) +WSurface::~WSurface() { - dd.init(); -} + teardown(); + // Notify listeners while the object is still usable (its members are + // alive during the destructor body). + Q_EMIT beforeDestroy(); -qw_surface *WSurface::handle() const + W_D(WSurface); + // Clear the reverse fromHandle() mapping. The creator destroys this + // wrapper from the native destroy callback (or releases it while the + // native handle is still alive), so the handle is valid here. + if (d->m_handle && d->m_handle->data == this) + d->m_handle->data = nullptr; + // Leave every output we entered — QObject connections to + // WOutput::beforeDestroy are auto-disconnected by ~QObject, but we + // must send the wl_surface leave notification and update the output + // list while the handle is still alive. + const auto outs = std::as_const(d->outputs); + for (auto *o : outs) + leaveOutput(o); + + // Release all remaining subsurfaces. Their dedicated child wrappers are + // reclaimed in releaseSubsurface(). + const auto subs = d->subsurfaces; + for (auto *sub : subs) + d->releaseSubsurface(sub); +} + +wlr_surface *WSurface::handle() const { W_DC(WSurface); return d->handle(); } -WSurface *WSurface::fromHandle(qw_surface *handle) -{ - return handle->get_data(); -} - WSurface *WSurface::fromHandle(wlr_surface *handle) { - if (auto surface = qw_surface::get(handle)) - return fromHandle(surface); - return nullptr; + if (!handle) + return nullptr; + return static_cast(handle->data); } bool WSurface::inputRegionContains(const QPointF &localPos) const { W_DC(WSurface); - return d->handle()->point_accepts_input(localPos.x(), localPos.y()); + +#ifndef DISABLE_XWAYLAND + if (auto *xsurface = wlr_xwayland_surface_try_from_wlr_surface(d->handle())) { + return wlr_xwayland_surface_point_accepts_input( + xsurface, localPos.x(), localPos.y()); + } +#endif + + return wlr_surface_point_accepts_input(d->handle(), localPos.x(), localPos.y()); } bool WSurface::mapped() const { W_DC(WSurface); - return d->nativeHandle()->mapped; + return d->handle()->mapped; } QSize WSurface::size() const { W_DC(WSurface); - return QSize(d->nativeHandle()->current.width, d->nativeHandle()->current.height); + return QSize(d->handle()->current.width, d->handle()->current.height); } QSize WSurface::bufferSize() const { W_DC(WSurface); - return QSize(d->nativeHandle()->current.buffer_width, - d->nativeHandle()->current.buffer_height); + return QSize(d->handle()->current.buffer_width, + d->handle()->current.buffer_height); } -WLR::Transform WSurface::orientation() const +WOutput::Transform WSurface::orientation() const { W_DC(WSurface); - return static_cast(d->nativeHandle()->current.transform); + return static_cast(d->handle()->current.transform); } int WSurface::bufferScale() const { W_DC(WSurface); - return d->nativeHandle()->current.scale; + return d->handle()->current.scale; } QPoint WSurface::bufferOffset() const @@ -293,7 +450,7 @@ QPoint WSurface::bufferOffset() const return d->bufferOffset; } -qw_buffer *WSurface::buffer() const +wlr_buffer *WSurface::buffer() const { W_DC(WSurface); return d->buffer.get(); @@ -306,7 +463,7 @@ void WSurface::notifyFrameDone() * prepare another one now if it likes. */ struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now); - wlr_surface_send_frame_done(d->nativeHandle(), &now); + wlr_surface_send_frame_done(d->handle(), &now); } void WSurface::enterOutput(WOutput *output) @@ -314,26 +471,36 @@ void WSurface::enterOutput(WOutput *output) W_D(WSurface); if (d->outputs.contains(output)) return; - wlr_surface_send_enter(d->nativeHandle(), output->handle()->handle()); + wlr_surface_send_enter(d->handle(), output->handle()); - connect(output, &WOutput::aboutToBeInvalidated, this, [this, output] { + QObject::connect(output, &WOutput::beforeDestroy, this, [this, output] { leaveOutput(output); }); - output->safeConnect(&WOutput::scaleChanged, this, [d] { + QObject::connect(output, &WOutput::scaleChanged, this, [d] { d->updatePreferredBufferScale(); }); d->updateOutputs(); // for subsurface - auto surface = d->nativeHandle(); + auto surface = d->handle(); wlr_subsurface *subsurface; wl_list_for_each(subsurface, &surface->current.subsurfaces_below, current.link) { - d->ensureSubsurface(subsurface)->enterOutput(output); + d->ensureSubsurface(subsurface)->surface()->enterOutput(output); } wl_list_for_each(subsurface, &surface->current.subsurfaces_above, current.link) { - d->ensureSubsurface(subsurface)->enterOutput(output); + d->ensureSubsurface(subsurface)->surface()->enterOutput(output); + } + + // for remote subsurfaces + for (auto *sub : std::as_const(d->remoteBelow)) { + if (auto *childSurface = sub->surface()) + childSurface->enterOutput(output); + } + for (auto *sub : std::as_const(d->remoteAbove)) { + if (auto *childSurface = sub->surface()) + childSurface->enterOutput(output); } Q_EMIT outputEntered(output); @@ -344,35 +511,63 @@ void WSurface::leaveOutput(WOutput *output) W_D(WSurface); if (!d->outputs.contains(output)) return; - wlr_surface_send_leave(d->nativeHandle(), output->handle()->handle()); + wlr_surface_send_leave(d->handle(), output->handle()); - output->safeDisconnect(this); + output->disconnect(this); d->updateOutputs(); // for subsurface - auto surface = d->nativeHandle(); + auto surface = d->handle(); wlr_subsurface *subsurface; wl_list_for_each(subsurface, &surface->current.subsurfaces_below, current.link) { - d->ensureSubsurface(subsurface)->leaveOutput(output); + d->ensureSubsurface(subsurface)->surface()->leaveOutput(output); } wl_list_for_each(subsurface, &surface->current.subsurfaces_above, current.link) { - d->ensureSubsurface(subsurface)->leaveOutput(output); + d->ensureSubsurface(subsurface)->surface()->leaveOutput(output); + } + + // for remote subsurfaces + for (auto *sub : std::as_const(d->remoteBelow)) { + if (auto *childSurface = sub->surface()) + childSurface->leaveOutput(output); + } + for (auto *sub : std::as_const(d->remoteAbove)) { + if (auto *childSurface = sub->surface()) + childSurface->leaveOutput(output); } Q_EMIT outputLeave(output); } -const QVector &WSurface::outputs() const +const QList &WSurface::outputs() const { W_DC(WSurface); return d->outputs; } +WOutput *WSurface::framePacingOutput() const +{ + W_DC(WSurface); + return d->framePacingOutput; +} + bool WSurface::isSubsurface() const { W_DC(WSurface); - return d->isSubsurface; + return d->subsurface != nullptr; +} + +WSurface *WSurface::rootSurface() const +{ + auto *root = this; + while (auto *subsurface = root->d_func()->subsurface.data()) { + auto *parent = subsurface->parentSurface(); + if (!parent) + return nullptr; + root = parent; + } + return const_cast(root); } bool WSurface::hasSubsurface() const @@ -381,22 +576,32 @@ bool WSurface::hasSubsurface() const return d->hasSubsurface; } -QList WSurface::subsurfaces() const +const QList &WSurface::subsurfaces() const { - auto d = const_cast(this)->d_func(); - QList subsurfaeList; + W_DC(WSurface); + return d->subsurfaces; +} - auto surface = d->nativeHandle(); - wlr_subsurface *subsurface; - wl_list_for_each(subsurface, &surface->current.subsurfaces_below, current.link) { - subsurfaeList.append(d->ensureSubsurface(subsurface)); +QList WSurface::subsurfacesBelow() const +{ + QList result; + const auto &subsurfaces = this->subsurfaces(); + for (auto *subsurface : subsurfaces) { + if (subsurface->place() == WSubsurface::Place::Below) + result.append(subsurface); } + return result; +} - wl_list_for_each(subsurface, &surface->current.subsurfaces_above, current.link) { - subsurfaeList.append(d->ensureSubsurface(subsurface)); +QList WSurface::subsurfacesAbove() const +{ + QList result; + const auto &subsurfaces = this->subsurfaces(); + for (auto *subsurface : subsurfaces) { + if (subsurface->place() == WSubsurface::Place::Above) + result.append(subsurface); } - - return subsurfaeList; + return result; } uint32_t WSurface::preferredBufferScale() const @@ -428,26 +633,50 @@ void WSurface::resetPreferredBufferScale() void WSurface::map() { W_D(WSurface); - wlr_surface_map(d->nativeHandle()); + wlr_surface_map(d->handle()); } void WSurface::unmap() { W_D(WSurface); - wlr_surface_unmap(d->nativeHandle()); + wlr_surface_unmap(d->handle()); } -void WSurfacePrivate::instantRelease() +WSubsurface *WSurface::addRemoteSubsurface(wlr_surface *childHandle) { - W_Q(WSurface); - if (handle()) { - handle()->set_data(nullptr, nullptr); - handle()->disconnect(q); - if (subsurface) - subsurface->disconnect(q); - for (auto o : std::as_const(outputs)) - o->safeDisconnect(q); + W_D(WSurface); + return d->addRemoteSubsurface(childHandle); +} + +void WSurface::removeSubsurface(WSubsurface *subsurface) +{ + W_D(WSurface); + d->releaseSubsurface(subsurface); +} + +void WSurface::setRemoteSubsurfaceOrder(const QList &below, + const QList &above) +{ + W_D(WSurface); + d->setSubsurfaceOrder(below, above); +} + + +bool WSurface::needsFrame() const +{ + W_DC(WSurface); + return d->needsFrame; +} + +bool WSurface::scheduleFrameIfNeeded() +{ + W_D(WSurface); + if (needsFrame() && d->framePacingOutput) { + d->needsFrame = false; + wlr_output_schedule_frame(d->framePacingOutput->handle()); + return true; } + return false; } WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wsurface.h b/waylib/src/server/kernel/wsurface.h index 1dab707a7f..efedff5fc5 100644 --- a/waylib/src/server/kernel/wsurface.h +++ b/waylib/src/server/kernel/wsurface.h @@ -1,71 +1,76 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once -#include -#include -#include +#include +#include +#include #include #include #include -struct wlr_surface; +Q_MOC_INCLUDE("woutput.h") +Q_MOC_INCLUDE("wsubsurface.h") -QW_BEGIN_NAMESPACE -class qw_texture; -class qw_surface; -class qw_buffer; -QW_END_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class WServer; class WOutput; +class WSubsurface; class WSurfacePrivate; -class WAYLIB_SERVER_EXPORT WSurface : public WWrapObject +class WAYLIB_SERVER_EXPORT WSurface : public QObject, public WWaylandResource { Q_OBJECT W_DECLARE_PRIVATE(WSurface) Q_PROPERTY(bool mapped READ mapped NOTIFY mappedChanged) - Q_PROPERTY(bool isSubsurface READ isSubsurface NOTIFY isSubsurfaceChanged) + Q_PROPERTY(bool isSubsurface READ isSubsurface) Q_PROPERTY(bool hasSubsurface READ hasSubsurface NOTIFY hasSubsurfaceChanged) - Q_PROPERTY(QList subsurfaces READ subsurfaces NOTIFY newSubsurface) + Q_PROPERTY(bool needsFrame READ needsFrame) + Q_PROPERTY(QList subsurfaces READ subsurfaces NOTIFY subsurfaceOrderChanged) Q_PROPERTY(uint32_t preferredBufferScale READ preferredBufferScale WRITE setPreferredBufferScale RESET resetPreferredBufferScale NOTIFY preferredBufferScaleChanged FINAL) QML_NAMED_ELEMENT(WaylandSurface) QML_UNCREATABLE("Only create in C++") public: - explicit WSurface(QW_NAMESPACE::qw_surface *handle, QObject *parent = nullptr); + explicit WSurface(wlr_surface *handle); + ~WSurface() override; - QW_NAMESPACE::qw_surface *handle() const; + wlr_surface *handle() const; - static WSurface *fromHandle(QW_NAMESPACE::qw_surface *handle); static WSurface *fromHandle(wlr_surface *handle); // for current state bool mapped() const; QSize size() const; QSize bufferSize() const; - WLR::Transform orientation() const; + WOutput::Transform orientation() const; int bufferScale() const; QPoint bufferOffset() const; - QW_NAMESPACE::qw_buffer *buffer() const; + wlr_buffer *buffer() const; void notifyFrameDone(); bool isSubsurface() const; + WSurface *rootSurface() const; bool hasSubsurface() const; - QList subsurfaces() const; + const QList &subsurfaces() const; + QList subsurfacesBelow() const; + QList subsurfacesAbove() const; uint32_t preferredBufferScale() const; void setPreferredBufferScale(uint32_t newPreferredBufferScale); void resetPreferredBufferScale(); + bool needsFrame() const; + bool scheduleFrameIfNeeded(); + public Q_SLOTS: void enterOutput(WOutput *output); void leaveOutput(WOutput *output); - const QVector &outputs() const; + const QList &outputs() const; + WOutput *framePacingOutput() const; bool inputRegionContains(const QPointF &localPos) const; void map(); @@ -73,17 +78,32 @@ public Q_SLOTS: Q_SIGNALS: void mappedChanged(); - void bufferChanged(); void bufferOffsetChanged(); - void isSubsurfaceChanged(); void hasSubsurfaceChanged(); - void newSubsurface(WSurface *subsurface); + void subsurfaceAdded(WSubsurface *subsurface); + void subsurfaceRemoved(WSubsurface *subsurface); + void subsurfaceOrderChanged(); + // Emitted from the destructor while the object is still usable. + void beforeDestroy(); void preferredBufferScaleChanged(); void outputEntered(WOutput *output); void outputLeave(WOutput *output); + void commit(quint32 committedState /*wlr_surface_state_field*/); protected: - WSurface(WSurfacePrivate &dd, QObject *parent); + WSurface(WSurfacePrivate &dd); + + // Owned by the creator (seat/shell/...): released with `delete` from + // the native destroy callback, never with deleteLater(). + using QObject::deleteLater; + +private: + WSubsurface *addRemoteSubsurface(wlr_surface *childHandle); + void removeSubsurface(WSubsurface *subsurface); + void setRemoteSubsurfaceOrder(const QList &below, + const QList &above); + + friend class WRemoteSubsurfaceManagerV1Private; }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wtoplevelsurface.cpp b/waylib/src/server/kernel/wtoplevelsurface.cpp index 4b63c7a840..4811f1f581 100644 --- a/waylib/src/server/kernel/wtoplevelsurface.cpp +++ b/waylib/src/server/kernel/wtoplevelsurface.cpp @@ -2,12 +2,14 @@ // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wtoplevelsurface.h" +#include "private/wwaylandresource_p.h" #include "private/wtoplevelsurface_p.h" WAYLIB_SERVER_BEGIN_NAMESPACE -WToplevelSurface::WToplevelSurface(WToplevelSurfacePrivate &d, QObject *parent) - : WWrapObject(d, parent) +WToplevelSurface::WToplevelSurface(WToplevelSurfacePrivate &d) + : QObject(nullptr) + , WWaylandResource(d, nullptr) { } diff --git a/waylib/src/server/kernel/wtoplevelsurface.h b/waylib/src/server/kernel/wtoplevelsurface.h index 3e37b00c9a..5d12836e46 100644 --- a/waylib/src/server/kernel/wtoplevelsurface.h +++ b/waylib/src/server/kernel/wtoplevelsurface.h @@ -1,16 +1,17 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include -#include +#include WAYLIB_SERVER_BEGIN_NAMESPACE class WSeat; +class WOutput; class WToplevelSurfacePrivate; -class WAYLIB_SERVER_EXPORT WToplevelSurface : public WWrapObject +class WAYLIB_SERVER_EXPORT WToplevelSurface : public QObject, public WWaylandResource { Q_OBJECT W_DECLARE_PRIVATE(WToplevelSurface) @@ -80,28 +81,25 @@ class WAYLIB_SERVER_EXPORT WToplevelSurface : public WWrapObject // Should always be 0 except layer surface return 0; } + virtual bool isInitialized() const { + return true; + }; public Q_SLOTS: - virtual void setMaximize(bool on) { - Q_UNUSED(on); + virtual void setMaximize([[maybe_unused]] bool on) { } - virtual void setMinimize(bool on) { - Q_UNUSED(on); + virtual void setMinimize([[maybe_unused]] bool on) { } - virtual void setActivate(bool on) { - Q_UNUSED(on); + virtual void setActivate([[maybe_unused]] bool on) { } - virtual void setResizeing(bool on) { - Q_UNUSED(on); + virtual void setResizeing([[maybe_unused]] bool on) { } - virtual void setFullScreen(bool on) { - Q_UNUSED(on); + virtual void setFullScreen([[maybe_unused]] bool on) { } // when `checkNewSize` return false, will set `clipedSize` to fit max/min size virtual bool checkNewSize(const QSize &size, QSize *clipedSize = nullptr) = 0; - virtual void resize(const QSize &size) { - Q_UNUSED(size) + virtual void resize([[maybe_unused]] const QSize &size) { } virtual void close() { } @@ -114,7 +112,12 @@ public Q_SLOTS: void parentSurfaceChanged(); void fullscreenChanged(); void titleChanged(); + // Emitted while the object is still alive, right before the native + // handle is destroyed (from the derived Private's instantRelease). + void beforeDestroy(); void appIdChanged(); + void minimumSizeChanged(const QSize &size); + void maximumSizeChanged(const QSize &size); void requestMove(WSeat *seat, quint32 serial); void requestResize(WSeat *seat, Qt::Edges edge, quint32 serial); @@ -122,12 +125,12 @@ public Q_SLOTS: void requestCancelMaximize(); void requestMinimize(); void requestCancelMinimize(); // Only for XWaylandSurface - void requestFullscreen(); + void requestFullscreen(WOutput *output); void requestCancelFullscreen(); void requestShowWindowMenu(WSeat *seat, QPoint pos, quint32 serial); protected: - explicit WToplevelSurface(WToplevelSurfacePrivate &d, QObject *parent = nullptr); + explicit WToplevelSurface(WToplevelSurfacePrivate &d); ~WToplevelSurface() override = default; }; diff --git a/waylib/src/server/kernel/wtypes.cpp b/waylib/src/server/kernel/wtypes.cpp deleted file mode 100644 index 65cdcea4e0..0000000000 --- a/waylib/src/server/kernel/wtypes.cpp +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (C) 2023 JiDe Zhang . -// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only - -#include "wtypes.h" - -WAYLIB_SERVER_BEGIN_NAMESPACE - -WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wtypes.h b/waylib/src/server/kernel/wtypes.h deleted file mode 100644 index 6e4e8e3b57..0000000000 --- a/waylib/src/server/kernel/wtypes.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (C) 2023 JiDe Zhang . -// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only - -#pragma once - -#include - -#include -#include - -WAYLIB_SERVER_BEGIN_NAMESPACE - -class WAYLIB_SERVER_EXPORT WLR { -public: - enum Transform { - Normal = 0, - R90 = 1, - R180 = 2, - R270 = 3, - Flipped = 4, - Flipped90 = 5, - Flipped180 = 6, - Flipped270 = 7 - }; -}; - -WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wwaylandresource.cpp b/waylib/src/server/kernel/wwaylandresource.cpp new file mode 100644 index 0000000000..8bfb557fe6 --- /dev/null +++ b/waylib/src/server/kernel/wwaylandresource.cpp @@ -0,0 +1,48 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wwaylandresource.h" +#include "private/wwaylandresource_p.h" +#include "wsocket.h" +#include "wayliblogging.h" + +WAYLIB_SERVER_BEGIN_NAMESPACE + +WWaylandResource::WWaylandResource(WWaylandResourcePrivate &dd, WObject *parent) + : WObject(dd, parent) +{ +} + +WClient *WWaylandResource::waylandClient() const +{ + W_DC(WWaylandResource); + auto client = d->waylandClient(); + if (!client) + return nullptr; + + auto wclient = WClient::get(client); + Q_ASSERT(wclient); + + return wclient; +} + +pid_t WWaylandResource::pid() const +{ + auto client = waylandClient(); + if (!client) + return 0; + auto credentials = client->credentials(); + if (!credentials) + return 0; + return credentials->pid; +} + +int WWaylandResource::pidFD() const +{ + auto client = waylandClient(); + if (!client) + return -1; + return client->pidFD(); +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wwaylandresource.h b/waylib/src/server/kernel/wwaylandresource.h new file mode 100644 index 0000000000..e2158d268c --- /dev/null +++ b/waylib/src/server/kernel/wwaylandresource.h @@ -0,0 +1,40 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include // pid_t + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WWaylandResourcePrivate; + +// WWaylandResource extends WObject with wayland-client specific information +// (waylandClient/pid/pidFD). Only objects that represent (or wrap) a +// wl_client-owned resource should inherit this class; plain WObject +// subclasses (outputs, seats, servers, protocol managers, ...) keep +// inheriting WObject directly. +class WAYLIB_SERVER_EXPORT WWaylandResource : public WObject +{ +public: + [[nodiscard]] WClient *waylandClient() const; + [[nodiscard]] virtual pid_t pid() const; + [[nodiscard]] virtual int pidFD() const; + +protected: + // All wayland-resource subclasses have their own *Private; there is no + // default construction. A deleted default constructor prevents + // accidentally creating a WObjectPrivate where a + // WWaylandResourcePrivate is required (which would make d_func()'s + // reinterpret_cast produce undefined behaviour). + WWaylandResource() = delete; + + WWaylandResource(WWaylandResourcePrivate &dd, WObject *parent = nullptr); + ~WWaylandResource() override = default; + + W_DECLARE_PRIVATE(WWaylandResource) +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/kernel/wxcursorimage.cpp b/waylib/src/server/kernel/wxcursorimage.cpp index c986f6d1c6..b2f9d90c34 100644 --- a/waylib/src/server/kernel/wxcursorimage.cpp +++ b/waylib/src/server/kernel/wxcursorimage.cpp @@ -1,10 +1,10 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wxcursorimage.h" #include "private/wglobal_p.h" -#include +#include #include @@ -78,7 +78,7 @@ bool WXCursorImage::jumpToImage(int imageNumber) if (!d->cursor) return false; - if (imageNumber >= d->cursor->image_count) + if (imageNumber >= static_cast(d->cursor->image_count)) return false; d->currentImageNumber = imageNumber; diff --git a/waylib/src/server/kernel/wxcursorimage.h b/waylib/src/server/kernel/wxcursorimage.h index aca7513ea3..f8b909ba71 100644 --- a/waylib/src/server/kernel/wxcursorimage.h +++ b/waylib/src/server/kernel/wxcursorimage.h @@ -1,13 +1,12 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include #include -struct wlr_xcursor; - QT_BEGIN_NAMESPACE class QImage; QT_END_NAMESPACE diff --git a/waylib/src/server/pch/pch.hxx b/waylib/src/server/pch/pch.hxx deleted file mode 100644 index c83dbbdb7b..0000000000 --- a/waylib/src/server/pch/pch.hxx +++ /dev/null @@ -1,92 +0,0 @@ -#ifdef __cplusplus -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#endif // __cplusplus diff --git a/waylib/src/server/platformplugin/qwlrootscreen.cpp b/waylib/src/server/platformplugin/qwlrootscreen.cpp index 7d0925b462..528a1b008e 100644 --- a/waylib/src/server/platformplugin/qwlrootscreen.cpp +++ b/waylib/src/server/platformplugin/qwlrootscreen.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qwlrootscreen.h" @@ -8,7 +8,7 @@ #include "woutputlayout.h" #include "wtools.h" -#include +#include #include #include @@ -47,7 +47,7 @@ int QWlrootsScreen::depth() const QImage::Format QWlrootsScreen::format() const { - auto format = WTools::toImageFormat(m_output->nativeHandle()->render_format); + auto format = WTools::toImageFormat(m_output->handle()->render_format); if (format != QImage::Format_Invalid) return format; @@ -222,20 +222,20 @@ void QWlrootsScreen::initialize() QWindowSystemInterface::handleScreenGeometryChange(screen(), newGeo, newGeo); }; - m_output->safeConnect(&WOutput::transformedSizeChanged, screen(), updateGeometry); + QObject::connect(m_output, &WOutput::transformedSizeChanged, screen(), updateGeometry); auto updateDpi = [this] { const auto dpi = logicalDpi(); QWindowSystemInterface::handleScreenLogicalDotsPerInchChange(screen(), dpi.first, dpi.second); }; - m_output->safeConnect(&WOutput::scaleChanged, screen(), updateDpi); + QObject::connect(m_output, &WOutput::scaleChanged, screen(), updateDpi); updateDpi(); } wlr_output *QWlrootsScreen::handle() const { - return m_output->handle()->handle(); + return m_output->handle(); } WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/platformplugin/qwlrootscreen.h b/waylib/src/server/platformplugin/qwlrootscreen.h index b6984f27fb..34e1a0ff8b 100644 --- a/waylib/src/server/platformplugin/qwlrootscreen.h +++ b/waylib/src/server/platformplugin/qwlrootscreen.h @@ -1,21 +1,16 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include "wglobal.h" #include "qwlrootscursor.h" -#include - #include #include #include -QW_USE_NAMESPACE - -struct wlr_output; - WAYLIB_SERVER_BEGIN_NAMESPACE class WOutput; diff --git a/waylib/src/server/platformplugin/qwlrootscursor.cpp b/waylib/src/server/platformplugin/qwlrootscursor.cpp index 0c9b572e3c..058773835d 100644 --- a/waylib/src/server/platformplugin/qwlrootscursor.cpp +++ b/waylib/src/server/platformplugin/qwlrootscursor.cpp @@ -27,9 +27,8 @@ void QWlrootsCursor::changeCursor(QCursor *windowCursor, QWindow *window) cursor->setCursor(windowCursor ? *windowCursor : WCursor::defaultCursor()); } -void QWlrootsCursor::setOverrideCursor(const QCursor &cursor) +void QWlrootsCursor::setOverrideCursor([[maybe_unused]] const QCursor &cursor) { - Q_UNUSED(cursor); return; } @@ -44,7 +43,7 @@ QPoint QWlrootsCursor::pos() const return cursors.isEmpty() ? QPoint() : cursors.first()->position().toPoint(); } -void QWlrootsCursor::setPos(const QPoint &pos) +void QWlrootsCursor::setPos([[maybe_unused]] const QPoint &pos) { } diff --git a/waylib/src/server/platformplugin/qwlrootscursor.h b/waylib/src/server/platformplugin/qwlrootscursor.h index d1b1cdb69e..c2e1fcc4b0 100644 --- a/waylib/src/server/platformplugin/qwlrootscursor.h +++ b/waylib/src/server/platformplugin/qwlrootscursor.h @@ -1,12 +1,10 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include "wglobal.h" -#include - #include #include diff --git a/waylib/src/server/platformplugin/qwlrootsintegration.cpp b/waylib/src/server/platformplugin/qwlrootsintegration.cpp index 673f388db4..f63c0b384a 100644 --- a/waylib/src/server/platformplugin/qwlrootsintegration.cpp +++ b/waylib/src/server/platformplugin/qwlrootsintegration.cpp @@ -1,21 +1,15 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023 - 2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only -#include -#define private public -#include -#undef private - #include "qwlrootsintegration.h" #include "qwlrootscreen.h" #include "qwlrootswindow.h" +#include "wayliblogging.h" #include "woutput.h" #include "winputdevice.h" #include "types.h" -#include -#include -#include +#include #include #include @@ -39,31 +33,25 @@ #include #include #include +#if QT_VERSION >= QT_VERSION_CHECK(6, 10, 0) +#include +#else #include +#endif #ifndef QT_NO_OPENGL #include #include #include -extern "C" { -#include -#define static -#include -#undef static -} - #endif // QT_NO_OPENGL WAYLIB_SERVER_BEGIN_NAMESPACE -#define CALL_PROXY2(FunName, fallbackValue, ...) m_proxyIntegration ? m_proxyIntegration->FunName(__VA_ARGS__) : fallbackValue -#define CALL_PROXY(FunName, ...) CALL_PROXY2(FunName, QPlatformIntegration::FunName(__VA_ARGS__), __VA_ARGS__) - -class Q_DECL_HIDDEN OffscreenSurface : public QPlatformOffscreenSurface +class Q_DECL_HIDDEN PlatformOffscreenSurface : public QPlatformOffscreenSurface { public: - OffscreenSurface(QOffscreenSurface *surface) + PlatformOffscreenSurface(QOffscreenSurface *surface) : QPlatformOffscreenSurface(surface) {} bool isValid() const override { @@ -76,11 +64,9 @@ class Q_DECL_HIDDEN OffscreenSurface : public QPlatformOffscreenSurface }; QWlrootsIntegration *QWlrootsIntegration::m_instance = nullptr; -QWlrootsIntegration::QWlrootsIntegration(bool master, const QStringList ¶meters, std::function onInitialized) - : m_master(master) - , m_onInitialized(onInitialized) +QWlrootsIntegration::QWlrootsIntegration([[maybe_unused]] const QStringList ¶meters, std::function onInitialized) + : m_onInitialized(onInitialized) { - Q_UNUSED(parameters); Q_ASSERT(!m_instance); m_instance = this; } @@ -96,29 +82,14 @@ QWlrootsIntegration *QWlrootsIntegration::instance() return m_instance; } -void QWlrootsIntegration::setProxy(QPlatformIntegration *proxy) -{ - Q_ASSERT(!m_proxyIntegration); - Q_ASSERT_X(!m_master, "initializeProxyQPA", "Can't set proxy plugin for a master QPA plugin."); - m_proxyIntegration.reset(proxy); - if (m_placeholderScreen) { - QWindowSystemInterface::handleScreenRemoved(m_placeholderScreen.release()); - } - m_fontDb.reset(); -} - QWlrootsScreen *QWlrootsIntegration::addScreen(WOutput *output) { m_screens << new QWlrootsScreen(output); - if (isMaster()) { - QWindowSystemInterface::handleScreenAdded(m_screens.last()); + QWindowSystemInterface::handleScreenAdded(m_screens.last()); - if (m_placeholderScreen) { - QWindowSystemInterface::handleScreenRemoved(m_placeholderScreen.release()); - } - } else { - Q_UNUSED(new QScreen(m_screens.last())) + if (m_placeholderScreen) { + QWindowSystemInterface::handleScreenRemoved(m_placeholderScreen.release()); } m_screens.last()->initialize(); @@ -133,12 +104,6 @@ void QWlrootsIntegration::removeScreen(WOutput *output) output->setScreen(nullptr); bool ok = m_screens.removeOne(screen); - if (!isMaster()) { - delete screen->screen(); - delete screen; - return; - } - if (ok && m_screens.isEmpty()) { m_placeholderScreen.reset(new QPlatformPlaceholderScreen); QWindowSystemInterface::handleScreenAdded(m_placeholderScreen.get(), true); @@ -156,11 +121,11 @@ QWlrootsScreen *QWlrootsIntegration::getScreenFrom(const WOutput *output) QPointer QWlrootsIntegration::addInputDevice(WInputDevice *device, const QString &seatName) { QPointer qtdev; - auto qwDevice = device->handle(); - const QString name = QString::fromUtf8(qwDevice->handle()->name); + auto *wlrDevice = device->handle(); + const QString name = QString::fromUtf8(wlrDevice->name); qint64 systemId = reinterpret_cast(device); - switch (qwDevice->handle()->type) { + switch (wlrDevice->type) { case WLR_INPUT_DEVICE_KEYBOARD: { qtdev = new QInputDevice(name, systemId, QInputDevice::DeviceType::Keyboard, seatName); break; @@ -185,7 +150,7 @@ QPointer QWlrootsIntegration::addInputDevice(WInputDevice *device, break; } case WLR_INPUT_DEVICE_TABLET_PAD: { - auto pad = wlr_tablet_pad_from_input_device(qwDevice->handle()); + auto pad = wlr_tablet_pad_from_input_device(wlrDevice); qtdev = new QPointingDevice(name, systemId, QInputDevice::DeviceType::TouchPad, QPointingDevice::PointerType::Pen, QInputDevice::Capability::Position | QInputDevice::Capability::Hover | QInputDevice::Capability::Pressure, 1, pad->button_count, seatName, QPointingDeviceUniqueId()); @@ -242,13 +207,11 @@ QInputDevice *QWlrootsIntegration::getInputDeviceFrom(WInputDevice *device) void QWlrootsIntegration::initialize() { - if (isMaster()) { #if QT_VERSION >= QT_VERSION_CHECK(6, 9, 0) - m_services.reset(new QDesktopUnixServices); + m_services.reset(new QDesktopUnixServices); #else - m_services.reset(new QGenericUnixServices); + m_services.reset(new QGenericUnixServices); #endif - } if (m_onInitialized) m_onInitialized(); @@ -257,23 +220,21 @@ void QWlrootsIntegration::initialize() m_placeholderScreen.reset(new QPlatformPlaceholderScreen); QWindowSystemInterface::handleScreenAdded(m_placeholderScreen.get(), true); } + + // Ensure the style hints are initialized in current thread, otherwise, some + // code paths(QQuickStylePlugin::registerTypes) may cause QStyleHints on + // non gui thread when accessing style hints from other threads. + QGuiApplication::styleHints(); } void QWlrootsIntegration::destroy() { if (m_placeholderScreen) QWindowSystemInterface::handleScreenRemoved(m_placeholderScreen.release()); - - if (m_proxyIntegration) - m_proxyIntegration->destroy(); } bool QWlrootsIntegration::hasCapability(Capability cap) const { - if (m_proxyIntegration) { - return CALL_PROXY(hasCapability, cap); - } - switch (cap) { case OpenGL: case ThreadedOpenGL: @@ -287,7 +248,9 @@ bool QWlrootsIntegration::hasCapability(Capability cap) const case WindowManagement: case WindowActivation: case SyncState: +#if QT_VERSION < QT_VERSION_CHECK(6, 11, 0) case RasterGLSurface: +#endif case AllGLFunctionsQueryable: case ApplicationIcon: case SwitchableWidgetComposition: @@ -303,9 +266,6 @@ bool QWlrootsIntegration::hasCapability(Capability cap) const QPlatformFontDatabase *QWlrootsIntegration::fontDatabase() const { - if (m_proxyIntegration) - return m_proxyIntegration->fontDatabase(); - if (!m_fontDb) m_fontDb.reset(new QGenericUnixFontDatabase); return m_fontDb.get(); @@ -321,12 +281,12 @@ QPlatformWindow *QWlrootsIntegration::createPlatformWindow(QWindow *window) cons return new QWlrootsRenderWindow(window); } - return CALL_PROXY2(createPlatformWindow, nullptr, window); + return nullptr; } -QPlatformBackingStore *QWlrootsIntegration::createPlatformBackingStore(QWindow *window) const +QPlatformBackingStore *QWlrootsIntegration::createPlatformBackingStore([[maybe_unused]] QWindow *window) const { - return CALL_PROXY2(createPlatformBackingStore, nullptr, window); + return nullptr; } #ifndef QT_NO_OPENGL @@ -347,12 +307,12 @@ class Q_DECL_HIDDEN OpenGLContext : public QPlatformOpenGLContext { m_format.setMajorVersion(3); if (auto c = qobject_cast(m_context)) { - auto eglConfig = q_configFromGLFormat(c->eglDisplay(), m_format, false, EGL_WINDOW_BIT); + auto eglConfig = q_configFromGLFormat(c->eglDisplay(), m_format, false, EGL_PBUFFER_BIT); if (eglConfig) m_format = q_glFormatFromConfig(c->eglDisplay(), eglConfig, m_format); Q_ASSERT(m_format.renderableType() == QSurfaceFormat::OpenGLES); } else { - qWarning() << "The QSurfaceFormat is not initialize"; + qCWarning(lcWlPlatform) << "The QSurfaceFormat is not initialize"; } } @@ -360,17 +320,14 @@ class Q_DECL_HIDDEN OpenGLContext : public QPlatformOpenGLContext { return m_format; } - void swapBuffers(QPlatformSurface *surface) override { - Q_UNUSED(surface); + void swapBuffers([[maybe_unused]] QPlatformSurface *surface) override { Q_UNREACHABLE(); } - GLuint defaultFramebufferObject(QPlatformSurface *surface) const override { - Q_UNUSED(surface); + GLuint defaultFramebufferObject([[maybe_unused]] QPlatformSurface *surface) const override { return 0; } - bool makeCurrent(QPlatformSurface *surface) override { - Q_UNUSED(surface); + bool makeCurrent([[maybe_unused]] QPlatformSurface *surface) override { if (auto c = qobject_cast(m_context)) { return eglMakeCurrent(c->eglDisplay(), EGL_NO_SURFACE, EGL_NO_SURFACE, c->eglContext()); } @@ -397,7 +354,7 @@ QPlatformOpenGLContext *QWlrootsIntegration::createPlatformOpenGLContext(QOpenGL if (QW::OpenGLContext::check(context)) return new OpenGLContext(context); - return CALL_PROXY(createPlatformOpenGLContext, context); + return QPlatformIntegration::createPlatformOpenGLContext(context); } QOpenGLContext::OpenGLModuleType QWlrootsIntegration::openGLModuleType() @@ -408,51 +365,51 @@ QOpenGLContext::OpenGLModuleType QWlrootsIntegration::openGLModuleType() QAbstractEventDispatcher *QWlrootsIntegration::createEventDispatcher() const { - return CALL_PROXY2(createEventDispatcher, createUnixEventDispatcher()); + return createUnixEventDispatcher(); } QPlatformNativeInterface *QWlrootsIntegration::nativeInterface() const { - return CALL_PROXY2(nativeInterface, const_cast(this)); + return const_cast(this); } QPlatformPixmap *QWlrootsIntegration::createPlatformPixmap(QPlatformPixmap::PixelType type) const { - return CALL_PROXY(createPlatformPixmap, type); + return QPlatformIntegration::createPlatformPixmap(type); } QPlatformWindow *QWlrootsIntegration::createForeignWindow(QWindow *window, WId id) const { - return CALL_PROXY(createForeignWindow, window, id); + return QPlatformIntegration::createForeignWindow(window, id); } QPlatformSharedGraphicsCache *QWlrootsIntegration::createPlatformSharedGraphicsCache(const char *cacheId) const { - return CALL_PROXY(createPlatformSharedGraphicsCache, cacheId); + return QPlatformIntegration::createPlatformSharedGraphicsCache(cacheId); } QPaintEngine *QWlrootsIntegration::createImagePaintEngine(QPaintDevice *paintDevice) const { - return CALL_PROXY(createImagePaintEngine, paintDevice); + return QPlatformIntegration::createImagePaintEngine(paintDevice); } #ifndef QT_NO_CLIPBOARD QPlatformClipboard *QWlrootsIntegration::clipboard() const { - return CALL_PROXY(clipboard); + return QPlatformIntegration::clipboard(); } #endif #if QT_CONFIG(draganddrop) QPlatformDrag *QWlrootsIntegration::drag() const { - return CALL_PROXY(drag); + return QPlatformIntegration::drag(); } #endif QPlatformInputContext *QWlrootsIntegration::inputContext() const { - return CALL_PROXY(inputContext); + return QPlatformIntegration::inputContext(); } #if QT_CONFIG(accessibility) @@ -464,83 +421,77 @@ QPlatformAccessibility *QWlrootsIntegration::accessibility() const QPlatformServices *QWlrootsIntegration::services() const { - if (isMaster()) - return m_services.get(); - - return CALL_PROXY(services); + return m_services.get(); } QVariant QWlrootsIntegration::styleHint(StyleHint hint) const { - return CALL_PROXY(styleHint, hint); + return QPlatformIntegration::styleHint(hint); } Qt::WindowState QWlrootsIntegration::defaultWindowState(Qt::WindowFlags flags) const { - return CALL_PROXY(defaultWindowState, flags); + return QPlatformIntegration::defaultWindowState(flags); } -Qt::KeyboardModifiers QWlrootsIntegration::queryKeyboardModifiers() const +QStringList QWlrootsIntegration::themeNames() const { - return CALL_PROXY(queryKeyboardModifiers); + return QPlatformIntegration::themeNames(); } -QList QWlrootsIntegration::possibleKeys(const QKeyEvent *event) const -{ - return CALL_PROXY(possibleKeys, event); -} +QWlrootsIntegration::CreatePlatformThemeCallback QWlrootsIntegration::s_createPlatformThemeCallback; -QStringList QWlrootsIntegration::themeNames() const +void QWlrootsIntegration::setCreatePlatformThemeCallback(CreatePlatformThemeCallback callback) { - return CALL_PROXY(themeNames); + s_createPlatformThemeCallback = std::move(callback); } -QPlatformTheme *QWlrootsIntegration::createPlatformTheme(const QString &name) const +QPlatformTheme *QWlrootsIntegration::createPlatformTheme([[maybe_unused]] const QString &name) const { - // TODO: use custom platform theme to allow compositor set some hints, like as font - return CALL_PROXY2(createPlatformTheme, new QGenericUnixTheme(), name); + if (s_createPlatformThemeCallback) { + return s_createPlatformThemeCallback(name); + } + return new QGenericUnixTheme(); } QPlatformOffscreenSurface *QWlrootsIntegration::createPlatformOffscreenSurface(QOffscreenSurface *surface) const { if (QW::OffscreenSurface::check(surface)) - return new OffscreenSurface(surface); + return new PlatformOffscreenSurface(surface); - return CALL_PROXY(createPlatformOffscreenSurface, surface); + return QPlatformIntegration::createPlatformOffscreenSurface(surface); } #ifndef QT_NO_SESSIONMANAGER QPlatformSessionManager *QWlrootsIntegration::createPlatformSessionManager(const QString &id, const QString &key) const { - return CALL_PROXY(createPlatformSessionManager, id, key); + return QPlatformIntegration::createPlatformSessionManager(id, key); } #endif void QWlrootsIntegration::sync() { - CALL_PROXY(sync); + QPlatformIntegration::sync(); } void QWlrootsIntegration::setApplicationIcon(const QIcon &icon) const { - CALL_PROXY(setApplicationIcon, icon); + QPlatformIntegration::setApplicationIcon(icon); } -#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) void QWlrootsIntegration::setApplicationBadge(qint64 number) { - CALL_PROXY(setApplicationBadge, number); + QPlatformIntegration::setApplicationBadge(number); } -#endif void QWlrootsIntegration::beep() const { - CALL_PROXY(beep); + QPlatformIntegration::beep(); } void QWlrootsIntegration::quit() const { - CALL_PROXY(quit); + QPlatformIntegration::quit(); } void *QWlrootsIntegration::nativeResourceForScreen(const QByteArray &resource, QScreen *screen) @@ -559,7 +510,7 @@ class Q_DECL_HIDDEN VulkanInstance : public QBasicPlatformVulkanInstance VulkanInstance(QVulkanInstance *instance) : m_instance(instance) { - loadVulkanLibrary(QStringLiteral("vulkan")); + loadVulkanLibrary(QStringLiteral("vulkan"), 1); } void createOrAdoptInstance() override { @@ -572,7 +523,7 @@ class Q_DECL_HIDDEN VulkanInstance : public QBasicPlatformVulkanInstance QPlatformVulkanInstance *QWlrootsIntegration::createPlatformVulkanInstance(QVulkanInstance *instance) const { - return m_proxyIntegration ? m_proxyIntegration->createPlatformVulkanInstance(instance) : new VulkanInstance(instance); + return new VulkanInstance(instance); } #endif diff --git a/waylib/src/server/platformplugin/qwlrootsintegration.h b/waylib/src/server/platformplugin/qwlrootsintegration.h index c678874cd0..650259b209 100644 --- a/waylib/src/server/platformplugin/qwlrootsintegration.h +++ b/waylib/src/server/platformplugin/qwlrootsintegration.h @@ -1,30 +1,17 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include "wglobal.h" -#include - #include -#define protected public #include -#undef protected #include #include -QW_BEGIN_NAMESPACE -class QWDisplay; -QW_END_NAMESPACE - -QW_USE_NAMESPACE - QT_BEGIN_NAMESPACE class QInputDevice; -namespace QtWaylandClient { -class QWaylandIntegration; -} QT_END_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE @@ -35,13 +22,11 @@ class QWlrootsScreen; class Q_DECL_HIDDEN QWlrootsIntegration : public QPlatformIntegration, public QPlatformNativeInterface { public: - QWlrootsIntegration(bool master, const QStringList ¶meters, std::function onInitialized); + QWlrootsIntegration(const QStringList ¶meters, std::function onInitialized); ~QWlrootsIntegration(); static QWlrootsIntegration *instance(); - void setProxy(QPlatformIntegration *proxy); - QWlrootsScreen *addScreen(WOutput *output); void removeScreen(WOutput *output); QWlrootsScreen *getScreenFrom(const WOutput *output); @@ -90,12 +75,13 @@ class Q_DECL_HIDDEN QWlrootsIntegration : public QPlatformIntegration, public QP QVariant styleHint(StyleHint hint) const override; Qt::WindowState defaultWindowState(Qt::WindowFlags flags) const override; - Qt::KeyboardModifiers queryKeyboardModifiers() const override; - QList possibleKeys(const QKeyEvent *) const override; - QStringList themeNames() const override; QPlatformTheme *createPlatformTheme(const QString &name) const override; + using CreatePlatformThemeCallback = std::function; + static WAYLIB_SERVER_EXPORT void setCreatePlatformThemeCallback( + CreatePlatformThemeCallback callback); + QPlatformOffscreenSurface *createPlatformOffscreenSurface(QOffscreenSurface *surface) const override; #ifndef QT_NO_SESSIONMANAGER @@ -104,9 +90,7 @@ class Q_DECL_HIDDEN QWlrootsIntegration : public QPlatformIntegration, public QP void sync() override; void setApplicationIcon(const QIcon &icon) const override; -#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) void setApplicationBadge(qint64 number) override; -#endif void beep() const override; void quit() const override; @@ -120,21 +104,14 @@ class Q_DECL_HIDDEN QWlrootsIntegration : public QPlatformIntegration, public QP private: friend class QWlrootsScreen; + static CreatePlatformThemeCallback s_createPlatformThemeCallback; mutable std::unique_ptr m_fontDb; std::unique_ptr m_services; std::unique_ptr m_placeholderScreen; QList m_screens; - -private: - inline bool isMaster() const { - return m_master; - } - static QWlrootsIntegration *m_instance; - bool m_master = true; std::function m_onInitialized; - std::unique_ptr m_proxyIntegration; }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/platformplugin/qwlrootswindow.cpp b/waylib/src/server/platformplugin/qwlrootswindow.cpp index 40af82fc9d..35e78ebb32 100644 --- a/waylib/src/server/platformplugin/qwlrootswindow.cpp +++ b/waylib/src/server/platformplugin/qwlrootswindow.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qwlrootswindow.h" @@ -9,8 +9,7 @@ #include "wseat.h" #include "wcursor.h" -#include -#include +#include #include @@ -18,7 +17,6 @@ #include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE QWlrootsOutputWindow::QWlrootsOutputWindow(QWindow *window) @@ -120,23 +118,17 @@ void QWlrootsRenderWindow::setDevicePixelRatio(qreal dpr) this->dpr = dpr; -#if QT_VERSION < QT_VERSION_CHECK(6, 6, 0) - QEvent event(QEvent::ScreenChangeInternal); - QCoreApplication::sendEvent(window(), &event); -#else QWindowSystemInterface::handleWindowDevicePixelRatioChanged(window()); -#endif } bool QWlrootsRenderWindow::beforeDisposeEventFilter(QEvent *event) { if (event->isInputEvent()) { auto ie = static_cast(event); - auto device = WInputDevice::from(ie->device()); - Q_ASSERT(device); - Q_ASSERT(device->seat()); - lastActiveCursor = device->seat()->cursor(); - return device->seat()->filterEventBeforeDisposeStage(window(), ie); + auto seat = WSeat::fromInputEvent(ie); + if (!seat) return true; + lastActiveCursor = seat->cursor(); + return seat->filterEventBeforeDisposeStage(window(), ie); } return false; @@ -146,10 +138,10 @@ bool QWlrootsRenderWindow::afterDisposeEventFilter(QEvent *event) { if (event->isInputEvent()) { auto ie = static_cast(event); - auto device = WInputDevice::from(ie->device()); - Q_ASSERT(device); - lastActiveCursor = device->seat()->cursor(); - return device->seat()->filterEventAfterDisposeStage(window(), ie); + auto seat = WSeat::fromInputEvent(ie); + if (!seat) return true; + lastActiveCursor = seat->cursor(); + return seat->filterEventAfterDisposeStage(window(), ie); } return false; diff --git a/waylib/src/server/platformplugin/qwlrootswindow.h b/waylib/src/server/platformplugin/qwlrootswindow.h index 68be583243..1c66d879dd 100644 --- a/waylib/src/server/platformplugin/qwlrootswindow.h +++ b/waylib/src/server/platformplugin/qwlrootswindow.h @@ -1,18 +1,13 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include "wglobal.h" -#include #include #include -QW_BEGIN_NAMESPACE -class qw_buffer; -QW_END_NAMESPACE - WAYLIB_SERVER_BEGIN_NAMESPACE class QWlrootsScreen; diff --git a/waylib/src/server/protocols/WPointerConstraintsV1 b/waylib/src/server/protocols/WPointerConstraintsV1 new file mode 100644 index 0000000000..5d519a897c --- /dev/null +++ b/waylib/src/server/protocols/WPointerConstraintsV1 @@ -0,0 +1 @@ +#include "wpointerconstraintsv1.h" diff --git a/waylib/src/server/protocols/WRelativePointerManagerV1 b/waylib/src/server/protocols/WRelativePointerManagerV1 new file mode 100644 index 0000000000..8708937e34 --- /dev/null +++ b/waylib/src/server/protocols/WRelativePointerManagerV1 @@ -0,0 +1 @@ +#include "wrelativepointermanagerv1.h" diff --git a/waylib/src/server/protocols/WSessionLock b/waylib/src/server/protocols/WSessionLock new file mode 100644 index 0000000000..47389ac265 --- /dev/null +++ b/waylib/src/server/protocols/WSessionLock @@ -0,0 +1 @@ +#include diff --git a/waylib/src/server/protocols/WSessionLockManager b/waylib/src/server/protocols/WSessionLockManager new file mode 100644 index 0000000000..5b55173065 --- /dev/null +++ b/waylib/src/server/protocols/WSessionLockManager @@ -0,0 +1 @@ +#include diff --git a/waylib/src/server/protocols/WSessionLockSurface b/waylib/src/server/protocols/WSessionLockSurface new file mode 100644 index 0000000000..fb618e2e68 --- /dev/null +++ b/waylib/src/server/protocols/WSessionLockSurface @@ -0,0 +1 @@ +#include diff --git a/waylib/src/server/protocols/private/winputmethodv2.cpp b/waylib/src/server/protocols/private/winputmethodv2.cpp index 32cc61afa8..5767883010 100644 --- a/waylib/src/server/protocols/private/winputmethodv2.cpp +++ b/waylib/src/server/protocols/private/winputmethodv2.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2023 Yixue Wang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "winputmethodv2_p.h" @@ -7,21 +7,15 @@ #include "wsurface.h" #include "wxdgsurface.h" #include "private/wglobal_p.h" +#include "wscoplistener.h" +#include "wayliblogging.h" -#include -#include -#include -#include -#include -#include +#include #include -#include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE -Q_DECLARE_LOGGING_CATEGORY(qLcInputMethod) class Q_DECL_HIDDEN WInputMethodManagerV2Private : public WObjectPrivate { public: @@ -30,61 +24,86 @@ class Q_DECL_HIDDEN WInputMethodManagerV2Private : public WObjectPrivate {} W_DECLARE_PUBLIC(WInputMethodManagerV2) - QList inputMethods; }; -WInputMethodManagerV2::WInputMethodManagerV2(QObject *parent) +WInputMethodManagerV2::WInputMethodManagerV2([[maybe_unused]] QObject *parent) : WObject(*new WInputMethodManagerV2Private(this), nullptr) -{ } +{ +} QByteArrayView WInputMethodManagerV2::interfaceName() const { return "zwp_input_method_manager_v2"; } +wlr_input_method_manager_v2 *WInputMethodManagerV2::handle() const +{ + return reinterpret_cast(m_handle); +} + void WInputMethodManagerV2::create(WServer *server) { - auto handle = qw_input_method_manager_v2::create(*server->handle()); + auto handle = wlr_input_method_manager_v2_create(server->handle()); Q_ASSERT(handle); m_handle = handle; - connect(handle, &qw_input_method_manager_v2::notify_input_method, this, [this](wlr_input_method_v2* im) { - Q_EMIT newInputMethod(qw_input_method_v2::from(im)); - }); + W_D(WInputMethodManagerV2); + listeners()->add(&handle->events.new_input_method, this, + &WInputMethodManagerV2::newInputMethod); +} + +void WInputMethodManagerV2::destroy([[maybe_unused]] WServer *server) +{ + if (ownsSocket() && m_handle) + wlr_input_method_manager_v2_destroy(nativeInterface(), false); + + m_handle = nullptr; } wl_global *WInputMethodManagerV2::global() const { - return nativeInterface()->handle()->global; + if (!m_handle) + return nullptr; + return reinterpret_cast(m_handle)->global; } -class Q_DECL_HIDDEN WInputMethodV2Private : public WWrapObjectPrivate +class Q_DECL_HIDDEN WInputMethodV2Private : public WObjectPrivate { public: - WInputMethodV2Private(qw_input_method_v2 *h, WInputMethodV2 *qq) - : WWrapObjectPrivate(qq) + WInputMethodV2Private(wlr_input_method_v2 *h, WInputMethodV2 *qq) + : WObjectPrivate(qq) + , m_handle(h) { - initHandle(h); + Q_ASSERT(h); } - WWRAP_HANDLE_FUNCTIONS(qw_input_method_v2, wlr_input_method_v2) + inline wlr_input_method_v2 *handle() const { + return m_handle; + } W_DECLARE_PUBLIC(WInputMethodV2) + +private: + // The helper owns this wrapper and destroys it from the native destroy + // callback. Keep the address stable until that callback finishes. + wlr_input_method_v2 *m_handle = nullptr; }; -WInputMethodV2::WInputMethodV2(qw_input_method_v2 *h, QObject *parent) : - WWrapObject(*new WInputMethodV2Private(h, this), parent) +WInputMethodV2::WInputMethodV2(wlr_input_method_v2 *h) : + QObject(nullptr), + WObject(*new WInputMethodV2Private(h, this)) { W_D(WInputMethodV2); - connect(handle(), &qw_input_method_v2::notify_commit, this, &WInputMethodV2::committed); - connect(handle(), &qw_input_method_v2::notify_grab_keyboard, this, [this](wlr_input_method_keyboard_grab_v2 *grab) { - Q_EMIT newKeyboardGrab(qw_input_method_keyboard_grab_v2::from(grab)); - }); - connect(handle(), &qw_input_method_v2::notify_new_popup_surface, this, [this](wlr_input_popup_surface_v2 *surface) { - Q_EMIT newPopupSurface(qw_input_popup_surface_v2::from(surface)); - }); + listeners()->add(&h->events.commit, this, &WInputMethodV2::committed); + listeners()->add(&h->events.grab_keyboard, this, &WInputMethodV2::newKeyboardGrab); + listeners()->add(&h->events.new_popup_surface, this, &WInputMethodV2::newPopupSurface); +} + +WInputMethodV2::~WInputMethodV2() +{ + teardown(); } -qw_input_method_v2 *WInputMethodV2::handle() const +wlr_input_method_v2 *WInputMethodV2::handle() const { return d_func()->handle(); } @@ -92,78 +111,78 @@ qw_input_method_v2 *WInputMethodV2::handle() const WSeat *WInputMethodV2::seat() const { W_DC(WInputMethodV2); - return WSeat::fromHandle(qw_seat::from(d->nativeHandle()->seat)); + return WSeat::fromHandle(d->handle()->seat); } void WInputMethodV2::sendContentType(quint32 hint, quint32 purpose) { W_D(WInputMethodV2); - d->handle()->send_content_type(hint, purpose); + wlr_input_method_v2_send_content_type(d->handle(), hint, purpose); } void WInputMethodV2::sendActivate() { W_D(WInputMethodV2); - d->handle()->send_activate(); + wlr_input_method_v2_send_activate(d->handle()); } void WInputMethodV2::sendDeactivate() { W_D(WInputMethodV2); - d->handle()->send_deactivate(); + wlr_input_method_v2_send_deactivate(d->handle()); } void WInputMethodV2::sendDone() { W_D(WInputMethodV2); - d->handle()->send_done(); + wlr_input_method_v2_send_done(d->handle()); } void WInputMethodV2::sendSurroundingText(const QString &text, quint32 cursor, quint32 anchor) { W_D(WInputMethodV2); - d->handle()->send_surrounding_text(qPrintable(text), cursor, anchor); + wlr_input_method_v2_send_surrounding_text(d->handle(), qPrintable(text), cursor, anchor); } void WInputMethodV2::sendTextChangeCause(quint32 cause) { W_D(WInputMethodV2); - d->handle()->send_text_change_cause(cause); + wlr_input_method_v2_send_text_change_cause(d->handle(), cause); } void WInputMethodV2::sendUnavailable() { W_D(WInputMethodV2); - d->handle()->send_unavailable(); + wlr_input_method_v2_send_unavailable(d->handle()); } QString WInputMethodV2::commitString() const { - return d_func()->nativeHandle()->current.commit_text; + return d_func()->handle()->current.commit_text; } uint WInputMethodV2::deleteSurroundingBeforeLength() const { - return d_func()->nativeHandle()->current.delete_c.before_length; + return d_func()->handle()->current._delete.before_length; } uint WInputMethodV2::deleteSurroundingAfterLength() const { - return d_func()->nativeHandle()->current.delete_c.after_length; + return d_func()->handle()->current._delete.after_length; } QString WInputMethodV2::preeditString() const { - return d_func()->nativeHandle()->current.preedit.text; + return d_func()->handle()->current.preedit.text; } int WInputMethodV2::preeditCursorBegin() const { - return d_func()->nativeHandle()->current.preedit.cursor_begin; + return d_func()->handle()->current.preedit.cursor_begin; } int WInputMethodV2::preeditCursorEnd() const { - return d_func()->nativeHandle()->current.preedit.cursor_end; + return d_func()->handle()->current.preedit.cursor_end; } WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/private/winputmethodv2_p.h b/waylib/src/server/protocols/private/winputmethodv2_p.h index 5a746ec507..3f6cac0dd7 100644 --- a/waylib/src/server/protocols/private/winputmethodv2_p.h +++ b/waylib/src/server/protocols/private/winputmethodv2_p.h @@ -1,37 +1,29 @@ -// Copyright (C) 2023 Yixue Wang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include "wglobal.h" #include "wserver.h" #include "wtoplevelsurface.h" -#include -#include - #include #include -Q_MOC_INCLUDE() Q_MOC_INCLUDE("wsurface.h") -QW_BEGIN_NAMESPACE -class qw_input_method_v2; -class QWInputPopupSurfaceV2; -class QWInputMethodKeyboardGrabV2; -QW_END_NAMESPACE - WAYLIB_SERVER_BEGIN_NAMESPACE class WInputMethodV2Private; class WSeat; -class WAYLIB_SERVER_EXPORT WInputMethodV2 : public WWrapObject +class WAYLIB_SERVER_EXPORT WInputMethodV2 : public QObject, public WObject { Q_OBJECT W_DECLARE_PRIVATE(WInputMethodV2) public: - explicit WInputMethodV2(QW_NAMESPACE::qw_input_method_v2 *handle, QObject *parent = nullptr); + explicit WInputMethodV2(wlr_input_method_v2 *handle); + ~WInputMethodV2(); WSeat *seat() const; QString commitString() const; uint deleteSurroundingBeforeLength() const; @@ -39,7 +31,7 @@ class WAYLIB_SERVER_EXPORT WInputMethodV2 : public WWrapObject QString preeditString() const; int preeditCursorBegin() const; int preeditCursorEnd() const; - QW_NAMESPACE::qw_input_method_v2 *handle() const; + wlr_input_method_v2 *handle() const; public Q_SLOTS: void sendContentType(quint32 hint, quint32 purpose); @@ -52,8 +44,8 @@ public Q_SLOTS: Q_SIGNALS: void committed(); - void newPopupSurface(QW_NAMESPACE::qw_input_popup_surface_v2 *surface); - void newKeyboardGrab(QW_NAMESPACE::qw_input_method_keyboard_grab_v2 *keyboardGrab); + void newPopupSurface(wlr_input_popup_surface_v2 *surface); + void newKeyboardGrab(wlr_input_method_keyboard_grab_v2 *keyboardGrab); private: friend class WInputMethodManagerV2; @@ -69,12 +61,14 @@ class WAYLIB_SERVER_EXPORT WInputMethodManagerV2 : public QObject, public WObjec explicit WInputMethodManagerV2(QObject *parent = nullptr); QByteArrayView interfaceName() const override; + wlr_input_method_manager_v2 *handle() const; Q_SIGNALS: - void newInputMethod(QW_NAMESPACE::qw_input_method_v2 *inputMethod); + void newInputMethod(wlr_input_method_v2 *inputMethod); private: void create(WServer *server) override; + void destroy(WServer *server) override; wl_global *global() const override; }; diff --git a/waylib/src/server/protocols/private/wsecuritycontextmanager_p.h b/waylib/src/server/protocols/private/wsecuritycontextmanager_p.h new file mode 100644 index 0000000000..7365d5847e --- /dev/null +++ b/waylib/src/server/protocols/private/wsecuritycontextmanager_p.h @@ -0,0 +1,69 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WSocket; + +// This is waylib's implementation-private copy of wlroots' security-context +// types. It intentionally differs from the vendored wlroots header: the +// manager also emits events.new_client. +struct wlr_security_context_manager_v1 { + struct wl_global *global; + + struct { + struct wl_signal destroy; + struct wl_signal commit; // struct wlr_security_context_v1_commit_event + struct wl_signal new_client; // struct wl_client + } events; + + void *data; + + struct wl_list contexts; // wlr_security_context_v1.link + struct wl_listener display_destroy; +}; + +struct wlr_security_context_v1_state { + char *sandbox_engine; // may be NULL + char *app_id; // may be NULL + char *instance_id; // may be NULL +}; + +struct wlr_security_context_v1_commit_event { + const struct wlr_security_context_v1_state *state; + // Client which created the security context + struct wl_client *parent_client; +}; + +struct wlr_security_context_v1 { + struct wlr_security_context_manager_v1 *manager; + struct wlr_security_context_v1_state state; + struct wl_list link; // wlr_security_context_manager_v1.contexts + int listen_fd, close_fd; + struct wl_event_source *listen_source, *close_source; + QPointer socket; +}; + +struct wlr_security_context_v1_client { + struct wlr_security_context_v1_state state; + struct wl_listener destroy; +}; + +struct wlr_security_context_manager_v1 *wlr_security_context_manager_v1_create( + struct wl_display *display); +void wlr_security_context_manager_v1_destroy(struct wlr_security_context_manager_v1 *manager, + bool destroy_global_safe); +const struct wlr_security_context_v1_state *wlr_security_context_manager_v1_lookup_client( + struct wlr_security_context_manager_v1 *manager, const struct wl_client *client); + +#define SECURITY_CONTEXT_MANAGER_V1_VERSION 1 + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/private/wtextinput_p.h b/waylib/src/server/protocols/private/wtextinput_p.h index 84f2cc190d..8c869f5c95 100644 --- a/waylib/src/server/protocols/private/wtextinput_p.h +++ b/waylib/src/server/protocols/private/wtextinput_p.h @@ -3,8 +3,8 @@ #pragma once -#include "wglobal.h" -#include "private/wglobal_p.h" +#include "wwaylandresource.h" +#include "private/wwaylandresource_p.h" #include #include @@ -59,9 +59,9 @@ enum ContentPurpose { Q_ENUM_NS(ContentPurpose) enum Feature { - F_SurroundingText, - F_ContentType, - F_CursorRect + F_SurroundingText = 1 << 0, + F_ContentType = 1 << 1, + F_CursorRect = 1 << 2 }; Q_FLAG_NS(Feature) Q_DECLARE_FLAGS(Features, Feature) @@ -83,7 +83,7 @@ class WSeat; class WSurface; class WInputMethodV2; class WTextInputPrivate; -class WAYLIB_SERVER_EXPORT WTextInput : public QObject, public WObject +class WAYLIB_SERVER_EXPORT WTextInput : public QObject, public WWaylandResource { Q_OBJECT W_DECLARE_PRIVATE(WTextInput) @@ -116,11 +116,11 @@ public Q_SLOTS: virtual void handleIMCommitted(WInputMethodV2 *im) = 0; }; -class Q_DECL_HIDDEN WTextInputPrivate : public WObjectPrivate { +class Q_DECL_HIDDEN WTextInputPrivate : public WWaylandResourcePrivate { public: W_DECLARE_PUBLIC(WTextInput) explicit WTextInputPrivate(WTextInput *qq) - : WObjectPrivate(qq) + : WWaylandResourcePrivate(qq) {} }; @@ -130,6 +130,6 @@ WTextInput::WTextInput(QObject *parent) inline WTextInput::WTextInput(WTextInputPrivate &d, QObject *parent) : QObject(parent) - , WObject(d) + , WWaylandResource(d) { } WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/private/wtextinputv1.cpp b/waylib/src/server/protocols/private/wtextinputv1.cpp index bda2d9f3fc..fdde2c165a 100644 --- a/waylib/src/server/protocols/private/wtextinputv1.cpp +++ b/waylib/src/server/protocols/private/wtextinputv1.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2023 Yixue Wang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wtextinputv1_p.h" @@ -8,17 +8,14 @@ #include "wsocket.h" #include "private/wglobal_p.h" -#include -#include -#include -#include +#include +#include #include extern "C" { #include "text-input-unstable-v1-protocol.h" } -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WTextInputV1Private : public WTextInputPrivate { @@ -59,7 +56,6 @@ class Q_DECL_HIDDEN WTextInputManagerV1Private : public WObjectPrivate QList textInputs; }; - WSeat *WTextInputV1::seat() const { return d_func()->seat; @@ -141,13 +137,12 @@ IME::Features WTextInputV1::features() const return IME::Features(IME::F_SurroundingText | IME::F_ContentType | IME::F_CursorRect); } - void WTextInputV1::sendEnter(WSurface *surface) { // Note: For text input v1, activation and surface focus is managed by client. // Do not send focus to text input unless it's activated. if (d_func()->active) - zwp_text_input_v1_send_enter(d_func()->resource, surface->handle()->handle()->resource); + zwp_text_input_v1_send_enter(d_func()->resource, surface->handle()->resource); Q_EMIT this->enabled(); } @@ -176,10 +171,14 @@ void WTextInputV1::handleIMCommitted(WInputMethodV2 *im) sendPreeditCursor(im->preeditCursorEnd() - im->preeditCursorBegin()); sendPreeditStyling(0, im->preeditString().length(), WTextInputV1::PS_Active); sendPreeditString(im->preeditString(), im->commitString()); + } else { + // A commit replaces the whole state and the initial preedit is empty: + // an empty preedit must be forwarded to drop stale composing text + // (fcitx5 only sends a non-empty preedit). + sendPreeditString(QString(), QString()); } } - void WTextInputV1::sendPreeditString(QString text, QString commit) { zwp_text_input_v1_send_preedit_string(d_func()->resource, d_func()->currentSerial, text.toStdString().c_str(), commit.toStdString().c_str()); @@ -213,7 +212,6 @@ void WTextInputV1::sendDeleteSurroundingText(int index, uint length) WTextInputV1::WTextInputV1(QObject *parent) : WTextInput(*new WTextInputV1Private(this), parent) { - W_D(WTextInputV1); connect(this, &WTextInputV1::activate, this, &WTextInputV1::requestFocus); connect(this, &WTextInputV1::deactivate, this, [this] { // Disconnect all signals excluding requestFocus, as text input may be activated again in @@ -227,13 +225,13 @@ WTextInputV1::WTextInputV1(QObject *parent) } static WTextInputV1 *text_input_from_resource(wl_resource *resource); -void text_input_handle_activate(wl_client *client, +void text_input_handle_activate([[maybe_unused]] wl_client *client, wl_resource *resource, wl_resource *seat, wl_resource *surface) { wlr_seat_client *seat_client = wlr_seat_client_from_resource(seat); - WSeat *wSeat = WSeat::fromHandle(qw_seat::from(seat_client->seat)); + WSeat *wSeat = WSeat::fromHandle(seat_client->seat); Q_ASSERT(wSeat); WTextInputV1 *text_input = text_input_from_resource(resource); auto d = text_input->d_func(); @@ -247,22 +245,23 @@ void text_input_handle_activate(wl_client *client, } if (focus_changed) { if (text_input->focusedSurface()) - text_input->focusedSurface()->safeDisconnect(text_input); + text_input->focusedSurface()->disconnect(text_input); d->focusedSurface = wSurface; - wSurface->safeConnect(&WSurface::aboutToBeInvalidated, text_input, &WTextInputV1::sendLeave); + QObject::connect(wSurface, &WSurface::beforeDestroy, + text_input, &WTextInputV1::sendLeave); } d->active = true; Q_EMIT text_input->activate(); } -void text_input_handle_deactivate(wl_client *client, +void text_input_handle_deactivate([[maybe_unused]] wl_client *client, wl_resource *resource, wl_resource *seat) { WTextInputV1 *text_input = text_input_from_resource(resource); auto d = text_input->d_func(); wlr_seat_client *seat_client = wlr_seat_client_from_resource(seat); - WSeat *wSeat = WSeat::fromHandle(qw_seat::from(seat_client->seat)); + WSeat *wSeat = WSeat::fromHandle(seat_client->seat); if (!wSeat || wSeat != text_input->seat()) return; @@ -271,21 +270,17 @@ void text_input_handle_deactivate(wl_client *client, Q_EMIT text_input->deactivate(); } -void text_input_handle_show_input_panel(wl_client *client, - wl_resource *resource) +void text_input_handle_show_input_panel([[maybe_unused]] wl_client *client, + [[maybe_unused]] wl_resource *resource) { - Q_UNUSED(client); - Q_UNUSED(resource); } -void text_input_handle_hide_input_panel(wl_client *client, - wl_resource *resource) +void text_input_handle_hide_input_panel([[maybe_unused]] wl_client *client, + [[maybe_unused]] wl_resource *resource) { - Q_UNUSED(client); - Q_UNUSED(resource); } -void text_input_handle_reset(wl_client *client, +void text_input_handle_reset([[maybe_unused]] wl_client *client, wl_resource *resource) { WTextInputV1 *text_input = text_input_from_resource(resource); @@ -298,7 +293,7 @@ void text_input_handle_reset(wl_client *client, d->contentPurpose = 0; } -void text_input_handle_set_surrounding_text(wl_client *client, +void text_input_handle_set_surrounding_text([[maybe_unused]] wl_client *client, wl_resource *resource, const char *text, uint32_t cursor, @@ -311,7 +306,7 @@ void text_input_handle_set_surrounding_text(wl_client *client, d->surroundingAnchor = anchor; } -void text_input_handle_set_content_type(wl_client *client, +void text_input_handle_set_content_type([[maybe_unused]] wl_client *client, wl_resource *resource, uint32_t hint, uint32_t purpose) @@ -322,7 +317,7 @@ void text_input_handle_set_content_type(wl_client *client, d->contentPurpose = purpose; } -void text_input_handle_set_cursor_rectangle(wl_client *client, +void text_input_handle_set_cursor_rectangle([[maybe_unused]] wl_client *client, wl_resource *resource, int32_t x, int32_t y, @@ -334,16 +329,13 @@ void text_input_handle_set_cursor_rectangle(wl_client *client, d->cursorRectangle = QRect(x, y, width, height); } -void text_input_handle_set_preferred_language(wl_client *client, - wl_resource *resource, - const char *language) +void text_input_handle_set_preferred_language([[maybe_unused]] wl_client *client, + [[maybe_unused]] wl_resource *resource, + [[maybe_unused]] const char *language) { - Q_UNUSED(client); - Q_UNUSED(resource); - Q_UNUSED(language); } -void text_input_handle_commit_state(wl_client *client, +void text_input_handle_commit_state([[maybe_unused]] wl_client *client, wl_resource *resource, uint32_t serial) { @@ -353,15 +345,11 @@ void text_input_handle_commit_state(wl_client *client, Q_EMIT text_input->committed(); } -void text_input_handle_invoke_action(wl_client *client, - wl_resource *resource, - uint32_t button, - uint32_t index) +void text_input_handle_invoke_action([[maybe_unused]] wl_client *client, + [[maybe_unused]] wl_resource *resource, + [[maybe_unused]] uint32_t button, + [[maybe_unused]] uint32_t index) { - Q_UNUSED(client); - Q_UNUSED(resource); - Q_UNUSED(button); - Q_UNUSED(index); } static const struct zwp_text_input_v1_interface text_input_v1_impl = { @@ -412,9 +400,7 @@ void text_input_manager_get_text_input(wl_client *client, wl_resource *resource, return; } d->resource = text_input_resource; - QObject::connect(text_input->waylandClient(), &WClient::destroyed, text_input, [text_input] { - wl_resource_destroy(text_input->d_func()->resource); - }); + // wl_client_destroy handles resource destruction via wl_map_for_each. wl_resource_set_implementation(text_input_resource, &text_input_v1_impl, text_input, text_input_resource_destroy); manager->d_func()->textInputs.append(text_input); QObject::connect(text_input, &WTextInputV1::entityAboutToDestroy, manager, [manager, text_input]{ @@ -437,32 +423,27 @@ static void text_input_manager_bind(wl_client *wl_client, void *data, uint32_t v { WTextInputManagerV1 *manager = reinterpret_cast(data); wl_resource *resource = wl_resource_create(wl_client, &zwp_text_input_manager_v1_interface, version, id); - WClient *wClient = WClient::get(wl_client); - QObject::connect(wClient, &WClient::destroyed, manager, [resource]{ - wl_resource_destroy(resource); - }); if (!resource) { wl_client_post_no_memory(wl_client); return; } + // wl_client_destroy handles resource destruction via wl_map_for_each. wl_resource_set_implementation(resource, &text_input_manager_v1_impl, manager, nullptr); } void WTextInputManagerV1::create(WServer *server) { - W_D(WTextInputManagerV1); - m_global = wl_global_create(server->handle()->handle(), + m_global = wl_global_create(server->handle(), &zwp_text_input_manager_v1_interface, - 1, + InterfaceVersion, this, text_input_manager_bind); Q_ASSERT(m_global); m_handle = this; } -void WTextInputManagerV1::destroy(WServer *server) +void WTextInputManagerV1::destroy([[maybe_unused]] WServer *server) { - Q_UNUSED(server); W_D(WTextInputManagerV1); wl_global_destroy(m_global); for (auto textInput : std::as_const(d->textInputs)) { diff --git a/waylib/src/server/protocols/private/wtextinputv1_p.h b/waylib/src/server/protocols/private/wtextinputv1_p.h index 7f46974680..11aaa6e3f5 100644 --- a/waylib/src/server/protocols/private/wtextinputv1_p.h +++ b/waylib/src/server/protocols/private/wtextinputv1_p.h @@ -1,4 +1,4 @@ -// Copyright (C) 2023 Yixue Wang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once @@ -7,8 +7,6 @@ #include "wserver.h" #include "wtextinput_p.h" -#include - #include #include @@ -152,6 +150,7 @@ class WAYLIB_SERVER_EXPORT WTextInputManagerV1 : public QObject, public WObject, QByteArrayView interfaceName() const override; + static constexpr int InterfaceVersion = 1; Q_SIGNALS: void newTextInput(WTextInputV1 *textInput); diff --git a/waylib/src/server/protocols/private/wtextinputv2.cpp b/waylib/src/server/protocols/private/wtextinputv2.cpp index 21fa9e7e6c..902c34f9ec 100644 --- a/waylib/src/server/protocols/private/wtextinputv2.cpp +++ b/waylib/src/server/protocols/private/wtextinputv2.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2024 Yixue Wang . +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wtextinputv2_p.h" @@ -6,19 +6,12 @@ #include "wsurface.h" #include "winputmethodv2_p.h" #include "wseat.h" +#include "wayliblogging.h" -#include -#include -#include - -#include - -extern "C" { #include "text-input-unstable-v2-protocol.h" -} -QW_USE_NAMESPACE +#include +#include WAYLIB_SERVER_BEGIN_NAMESPACE -Q_LOGGING_CATEGORY(qLcTextInputV2, "waylib.server.im.ti2", QtInfoMsg) using namespace tiv2; static struct zwp_text_input_manager_v2_interface manager_impl = { .destroy = handle_manager_destroy, .get_text_input = handle_manager_get_text_input @@ -59,6 +52,15 @@ class Q_DECL_HIDDEN WTextInputV2Private : public WTextInputPrivate WClient *client; WSurface *enabledSurface; WSurface *focusedSurface; + // Tracks the beforeDestroy connection of the focused surface. Qt 6 does + // not support Qt::UniqueConnection with a functor target (it asserts in + // debug builds), so the connection is managed explicitly. + QMetaObject::Connection focusedSurfaceDestroyConnection; + // Tracks the beforeDestroy connection of the enabled surface separately: + // disconnecting every connection from that surface to this object would + // also drop focusedSurfaceDestroyConnection when both point to the same + // surface, leaving focusedSurface dangling after it is destroyed. + QMetaObject::Connection enabledSurfaceDestroyConnection; QString surroundingText; int32_t surroundingCursor; int32_t surroundingAnchor; @@ -114,7 +116,7 @@ WTextInputV2 *text_input_from_resource(wl_resource *resource) void text_input_manager_bind(wl_client *client, void *data, - uint32_t version, + [[maybe_unused]] uint32_t version, uint32_t id) { WTextInputManagerV2 *manager = static_cast(data); @@ -127,16 +129,12 @@ void text_input_manager_bind(wl_client *client, wl_client_post_no_memory(client); return; } - WClient *wClient = WClient::get(client); - QObject::connect(wClient, &WClient::destroyed, manager, [resource]{ - wl_resource_destroy(resource); - }); + // wl_client_destroy handles resource destruction via wl_map_for_each. wl_resource_set_implementation(resource, &manager_impl, manager, nullptr); } -void handle_manager_destroy(wl_client *client, wl_resource *resource) +void handle_manager_destroy([[maybe_unused]] wl_client *client, wl_resource *resource) { - Q_UNUSED(client); wl_resource_destroy(resource); } @@ -178,14 +176,12 @@ void handle_manager_get_text_input(wl_client *client, } text_input->d_func()->resource = text_input_resource; auto wClient = WClient::get(client); - auto wSeat = WSeat::fromHandle(qw_seat::from(seat_client->seat)); + auto wSeat = WSeat::fromHandle(seat_client->seat); Q_ASSERT(wClient); Q_ASSERT(wSeat); text_input->d_func()->client = wClient; text_input->d_func()->seat = wSeat; - QObject::connect(wClient, &WClient::destroyed, text_input, [text_input_resource] { - wl_resource_destroy(text_input_resource); - }); + // wl_client_destroy handles resource destruction via wl_map_for_each. wl_resource_set_implementation(text_input_resource, &text_input_impl, text_input, handle_text_input_resource_destroy); manager->d_func()->textInputs.append(text_input); QObject::connect(text_input, &WTextInput::entityAboutToDestroy, manager, [manager, text_input]{ @@ -194,55 +190,61 @@ void handle_manager_get_text_input(wl_client *client, Q_EMIT manager->newTextInput(text_input); } -void handle_text_input_destroy(wl_client *client, wl_resource *resource) +void handle_text_input_destroy([[maybe_unused]] wl_client *client, wl_resource *resource) { - Q_UNUSED(client) wl_resource_destroy(resource); } -void handle_text_input_enable(wl_client *client, wl_resource *resource, wl_resource *surface) +void handle_text_input_enable([[maybe_unused]] wl_client *client, wl_resource *resource, wl_resource *surface) { - Q_UNUSED(client) auto text_input = text_input_from_resource(resource); Q_ASSERT(text_input); auto wSurface = WSurface::fromHandle(wlr_surface_from_resource(surface)); // Surface must be existent already, this means wSurface should always be non-null. + // However, there can be a race between surface destruction and text input requests, + // so treat a missing WSurface as a warning rather than a fatal protocol error. if (!wSurface) { - wl_client_post_implementation_error(client, "Enabled surface not found."); + qCWarning(lcWlTextInput) << "Client" << client << "sent enable on surface" << surface + << "but no WSurface found (may be already destroyed). Ignoring."; return; } auto d = text_input->d_func(); if (d->enabledSurface) { // FIXME: Is this necessary? As protocol does not guarantee disable is ought to happen after enable, we may still need this. - qCWarning(qLcTextInputV2) << "Client" << client << "does emit disable on surface" + qCWarning(lcWlTextInput) << "Client" << client << "does Q_EMIT disable on surface" << d->enabledSurface << "before enable on surface" << wSurface; text_input->clearEnabledSurface(); } d->enabledSurface = wSurface; - QObject::connect(d->enabledSurface, &WSurface::aboutToBeInvalidated, text_input, &WTextInputV2::clearEnabledSurface); + // Keep the enabled-surface destroy connection tracked so clearEnabledSurface() + // can drop only this one, not the focused-surface listener installed by + // sendEnter() on the same surface. + d->enabledSurfaceDestroyConnection = QObject::connect( + wSurface, &WSurface::beforeDestroy, + text_input, &WTextInputV2::clearEnabledSurface); Q_EMIT text_input->enableOnSurface(wSurface); } -void handle_text_input_disable(wl_client *client, wl_resource *resource, wl_resource *surface) +void handle_text_input_disable([[maybe_unused]] wl_client *client, wl_resource *resource, wl_resource *surface) { - Q_UNUSED(client) auto text_input = text_input_from_resource(resource); Q_ASSERT(text_input); auto wSurface = WSurface::fromHandle(wlr_surface_from_resource(surface)); if (!wSurface) { - wl_client_post_implementation_error(client, "Disabled surface not found, may be already destroyed."); + qCWarning(lcWlTextInput) << "Client" << client << "sent disable on surface" << surface + << "but no WSurface found (may be already destroyed). Ignoring."; return; } auto d = text_input->d_func(); if (!d->enabledSurface) { - qCWarning(qLcTextInputV2) << "Client" << client + qCWarning(lcWlTextInput) << "Client" << wl_resource_get_client(resource) << "try to disable surface" << wSurface << "on a text input" << text_input << "that is not enabled on this surface. Do nothing!"; return; } if (d->enabledSurface != wSurface) { - qCWarning(qLcTextInputV2) << "Client" << client + qCWarning(lcWlTextInput) << "Client" << client << "try to disable surface" << wSurface << "on a text input" << text_input << "which is enabled on another surface" << d->enabledSurface; @@ -251,22 +253,17 @@ void handle_text_input_disable(wl_client *client, wl_resource *resource, wl_reso text_input->clearEnabledSurface(); } -void handle_text_input_show_input_panel(wl_client *client, wl_resource *resource) +void handle_text_input_show_input_panel([[maybe_unused]] wl_client *client, [[maybe_unused]] wl_resource *resource) { - Q_UNUSED(client) - Q_UNUSED(resource) } -void handle_text_input_hide_input_panel(wl_client *client, wl_resource *resource) +void handle_text_input_hide_input_panel([[maybe_unused]] wl_client *client, [[maybe_unused]] wl_resource *resource) { - Q_UNUSED(client) - Q_UNUSED(resource) } void handle_text_input_set_surrounding_text( - wl_client *client, wl_resource *resource, const char *text, int32_t cursor, int32_t anchor) + [[maybe_unused]] wl_client *client, wl_resource *resource, const char *text, int32_t cursor, int32_t anchor) { - Q_UNUSED(client) auto text_input = text_input_from_resource(resource); Q_ASSERT(text_input); auto d = text_input->d_func(); @@ -275,12 +272,11 @@ void handle_text_input_set_surrounding_text( d->surroundingAnchor = anchor; } -void handle_text_input_set_content_type(wl_client *client, +void handle_text_input_set_content_type([[maybe_unused]] wl_client *client, wl_resource *resource, uint32_t hint, uint32_t purpose) { - Q_UNUSED(client) auto text_input = text_input_from_resource(resource); Q_ASSERT(text_input); auto d = text_input->d_func(); @@ -289,30 +285,25 @@ void handle_text_input_set_content_type(wl_client *client, } void handle_text_input_set_cursor_rectangle( - wl_client *client, wl_resource *resource, int32_t x, int32_t y, int32_t width, int32_t height) + [[maybe_unused]] wl_client *client, wl_resource *resource, int32_t x, int32_t y, int32_t width, int32_t height) { - Q_UNUSED(client) auto text_input = text_input_from_resource(resource); Q_ASSERT(text_input); auto d = text_input->d_func(); d->cursorRectangle = QRect(x, y, width, height); } -void handle_text_input_set_preferred_language(wl_client *client, - wl_resource *resource, - const char *language) +void handle_text_input_set_preferred_language([[maybe_unused]] wl_client *client, + [[maybe_unused]] wl_resource *resource, + [[maybe_unused]] const char *language) { - Q_UNUSED(client) - Q_UNUSED(resource) - Q_UNUSED(language) } -void handle_text_input_update_state(wl_client *client, - wl_resource *resource, - uint32_t serial, +void handle_text_input_update_state([[maybe_unused]] wl_client *client, + [[maybe_unused]] wl_resource *resource, + [[maybe_unused]] uint32_t serial, uint32_t reason) { - Q_UNUSED(client) auto text_input = text_input_from_resource(resource); Q_ASSERT(text_input); Q_EMIT text_input->stateUpdated(WTextInputV2::UpdateReason(reason)); @@ -331,15 +322,18 @@ QByteArrayView WTextInputManagerV2::interfaceName() const void WTextInputManagerV2::create(WServer *server) { - W_D(WTextInputManagerV2); - m_global = wl_global_create(server->handle()->handle(), &zwp_text_input_manager_v2_interface, 1, this, text_input_manager_bind); + m_global = wl_global_create(server->handle(), + &zwp_text_input_manager_v2_interface, + InterfaceVersion, + this, + text_input_manager_bind); Q_ASSERT(m_global); m_handle = this; } void WTextInputManagerV2::destroy(WServer *server) { - Q_UNUSED(server); + [[maybe_unused]] auto server_unused = server; W_D(WTextInputManagerV2); wl_global_destroy(m_global); for (auto textInput : std::as_const(d->textInputs)) { @@ -380,13 +374,18 @@ int WTextInputV2::surroundingAnchor() const IME::ContentHints WTextInputV2::contentHints() const { W_DC(WTextInputV2); - return IME::ContentHints(); + // set_content_type stores the client state in d. WInputMethodHelper reads + // this getter when it sends the active text-input snapshot to an input + // method, so returning the default value here silently loses that payload. + return IME::ContentHints(d->contentHint); } IME::ContentPurpose WTextInputV2::contentPurpose() const { W_DC(WTextInputV2); - return IME::ContentPurpose(); + // Keep this paired with contentHints(): both values originate from the + // same set_content_type request and must reach the input method together. + return static_cast(d->contentPurpose); } QRect WTextInputV2::cursorRect() const @@ -404,8 +403,19 @@ void WTextInputV2::sendEnter(WSurface *surface) { W_D(WTextInputV2); d->focusedSurface = surface; - connect(d->focusedSurface, &WSurface::aboutToBeInvalidated, this, &WTextInputV2::sendLeave, Qt::UniqueConnection); - zwp_text_input_v2_send_enter(d->resource, 0, surface->handle()->handle()->resource); + // Qt::UniqueConnection is only supported for member function targets and + // asserts with a functor, so replace the previous focus-destroy + // connection explicitly before connecting the new one. + if (d->focusedSurfaceDestroyConnection) { + QObject::disconnect(d->focusedSurfaceDestroyConnection); + d->focusedSurfaceDestroyConnection = {}; + } + d->focusedSurfaceDestroyConnection = QObject::connect(surface, &WSurface::beforeDestroy, this, + [this, d, surface] { + if (d->focusedSurface == surface) + sendLeave(); + }); + zwp_text_input_v2_send_enter(d->resource, 0, surface->handle()->resource); if (d->enabledSurface == d->focusedSurface) { Q_EMIT enabled(); } @@ -415,14 +425,25 @@ void WTextInputV2::sendLeave() { W_D(WTextInputV2); if (!d->focusedSurface) { - qCWarning(qLcTextInputV2()) << "Send leave to a null focused surface."; + qCWarning(lcWlTextInput()) << "Send leave to a null focused surface."; return; } - zwp_text_input_v2_send_leave(d->resource, 0, d->focusedSurface->handle()->handle()->resource); + // See WTextInputV3::sendLeave(): drop the client's stale composing text + // before it loses focus (fcitx5 only clears its own preedit). Only while the + // input is enabled: a client that already disabled must not get a state + // update outside an active input session. + if (d->enabledSurface == d->focusedSurface) + zwp_text_input_v2_send_preedit_string(d->resource, "", ""); + zwp_text_input_v2_send_leave(d->resource, 0, d->focusedSurface->handle()->resource); if (d->enabledSurface == d->focusedSurface) { Q_EMIT disabled(); } d->focusedSurface = nullptr; + // The focused surface no longer needs its destroy notification. + if (d->focusedSurfaceDestroyConnection) { + QObject::disconnect(d->focusedSurfaceDestroyConnection); + d->focusedSurfaceDestroyConnection = {}; + } } void WTextInputV2::sendDone() @@ -442,36 +463,45 @@ void WTextInputV2::handleIMCommitted(WInputMethodV2 *im) zwp_text_input_v2_send_preedit_cursor(d->resource, im->preeditCursorEnd() - im->preeditCursorBegin()); zwp_text_input_v2_send_preedit_styling(d->resource, 0, im->preeditString().length(), PS_Active); zwp_text_input_v2_send_preedit_string(d->resource, im->preeditString().toStdString().c_str(), im->commitString().toStdString().c_str()); + } else { + // A commit replaces the whole state and the initial preedit is empty: + // an empty preedit must be forwarded to drop stale composing text + // (fcitx5 only sends a non-empty preedit). + zwp_text_input_v2_send_preedit_string(d->resource, "", ""); } } WTextInputV2::WTextInputV2(QObject *parent) : WTextInput(*new WTextInputV2Private(this), parent) { - connect(this, &WTextInputV2::enableOnSurface, this, [this] { - if (focusedSurface()) { + connect(this, &WTextInputV2::enableOnSurface, this, [this] (WSurface *surface) { + // Header invariant: enabled only when the focused surface is the enabled + // surface. Either request may arrive first, so the other path emits it. + if (focusedSurface() == surface) { Q_EMIT enabled(); } }); - connect(this, &WTextInputV2::disableOnSurface, this, [this] { - if (!focusedSurface()) { + connect(this, &WTextInputV2::disableOnSurface, this, [this] (WSurface *surface) { + // Mirror of enableOnSurface: the client may disable while still focused, + // in which case this is the only place that can report the transition. + if (focusedSurface() == surface) { Q_EMIT disabled(); } }); connect(this, &WTextInput::enabled, this, [this]{ - qCDebug(qLcTextInputV2()) << "text input v2" << this << "enabled"; + qCDebug(lcWlTextInput()) << "text input v2" << this << "enabled"; }); connect(this, &WTextInput::disabled, this, [this] { - qCDebug(qLcTextInputV2()) << "text input v2" << this << "disabled"; + qCDebug(lcWlTextInput()) << "text input v2" << this << "disabled"; }); connect(this, &WTextInputV2::stateUpdated, this, [this] (UpdateReason reason){ - qCInfo(qLcTextInputV2()) << "state updated:" << reason; + qCInfo(lcWlTextInput()) << "state updated:" << reason; switch (reason) { case Change: break; case Enter: case Full: - qCDebug(qLcTextInputV2()) << "commit text input v2" << this; + qCDebug(lcWlTextInput()) << "commit text input v2" << this; Q_EMIT this->committed(); break; case Reset: @@ -488,7 +518,10 @@ void WTextInputV2::clearEnabledSurface() W_D(WTextInputV2); Q_ASSERT(d->enabledSurface); Q_EMIT disableOnSurface(d->enabledSurface); - d->enabledSurface->safeDisconnect(this); + if (d->enabledSurfaceDestroyConnection) { + QObject::disconnect(d->enabledSurfaceDestroyConnection); + d->enabledSurfaceDestroyConnection = {}; + } d->enabledSurface = nullptr; } WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/private/wtextinputv2_p.h b/waylib/src/server/protocols/private/wtextinputv2_p.h index 45d7182342..e9cc6ee1b5 100644 --- a/waylib/src/server/protocols/private/wtextinputv2_p.h +++ b/waylib/src/server/protocols/private/wtextinputv2_p.h @@ -1,4 +1,4 @@ -// Copyright (C) 2024 Yixue Wang . +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once @@ -7,8 +7,6 @@ #include "wserver.h" #include "wtextinput_p.h" -#include - #include #include @@ -76,7 +74,6 @@ class WAYLIB_SERVER_EXPORT WTextInputV2 : public WTextInput }; Q_ENUM(PreeditStyle) - Q_SIGNALS: // As protocol says, enable will be before or after enter event. This is not the same as our logic. // We consider text input v2 enabled only if it emits enable and receives enter event and the focused @@ -134,6 +131,7 @@ class WAYLIB_SERVER_EXPORT WTextInputManagerV2 : public QObject, public WObject, QByteArrayView interfaceName() const override; + static constexpr int InterfaceVersion = 1; Q_SIGNALS: void newTextInput(WTextInputV2 *textInput); diff --git a/waylib/src/server/protocols/private/wtextinputv3.cpp b/waylib/src/server/protocols/private/wtextinputv3.cpp index 92b9e33c30..c4c008cf23 100644 --- a/waylib/src/server/protocols/private/wtextinputv3.cpp +++ b/waylib/src/server/protocols/private/wtextinputv3.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2023 Yixue Wang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wtextinputv3_p.h" @@ -7,18 +7,13 @@ #include "wtoplevelsurface.h" #include "wtools.h" #include "private/wglobal_p.h" +#include "wscoplistener.h" +#include "wayliblogging.h" -#include -#include -#include -#include +#include -#include #include - -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE -Q_DECLARE_LOGGING_CATEGORY(qLcInputMethod) class Q_DECL_HIDDEN WTextInputManagerV3Private : public WObjectPrivate { public: @@ -35,164 +30,215 @@ WTextInputManagerV3::WTextInputManagerV3(QObject *parent) , WObject(*new WTextInputManagerV3Private(this)) { } - QByteArrayView WTextInputManagerV3::interfaceName() const { return "zwp_text_input_manager_v3"; } +wlr_text_input_manager_v3 *WTextInputManagerV3::handle() const +{ + return reinterpret_cast(m_handle); +} + void WTextInputManagerV3::create(WServer *server) { W_D(WTextInputManagerV3); - auto manager = qw_text_input_manager_v3::create(*server->handle()); + auto manager = wlr_text_input_manager_v3_create(server->handle()); Q_ASSERT(manager); m_handle = manager; - connect(manager, &qw_text_input_manager_v3::notify_text_input, this, [this, d](wlr_text_input_v3 *w_text_input_v3){ - auto text_input_v3 = qw_text_input_v3::from(w_text_input_v3); - auto ti = new WTextInputV3(text_input_v3, this); + listeners()->add(&manager->events.new_text_input, this, + [this, d] (wlr_text_input_v3 *w_text_input_v3) { + auto ti = new WTextInputV3(w_text_input_v3, this); d->textInputs.append(ti); Q_EMIT this->newTextInput(ti); - connect(text_input_v3, &qw_text_input_v3::before_destroy, ti, [this, ti, d]{ + // Listen on the native destroy signal: notify observers (the IME + // helper watches entityAboutToDestroy), drop it from the list and + // delete the wrapper. removeListeners detaches this node from the + // signal first — wlr_text_input_destroy asserts an empty destroy + // listener list right after emitting. The synchronous delete runs + // inside the emission, so ~WTextInputV3 disconnects the remaining + // enable/disable/commit listeners before wlroots asserts those + // lists are empty too. + ti->listeners(this)->add(&w_text_input_v3->events.destroy, this, + [this, d, ti] (void *) { + ti->removeListeners(this); Q_EMIT ti->entityAboutToDestroy(); d->textInputs.removeOne(ti); - ti->deleteLater(); + delete ti; }); }); } -void WTextInputManagerV3::destroy(WServer *server) +void WTextInputManagerV3::destroy([[maybe_unused]] WServer *server) { - for (auto ti : std::as_const(d_func()->textInputs)) { + W_D(WTextInputManagerV3); + for (auto *ti : std::as_const(d->textInputs)) { Q_EMIT ti->entityAboutToDestroy(); ti->deleteLater(); } - d_func()->textInputs.clear(); + d->textInputs.clear(); + if (ownsSocket() && m_handle) + wlr_text_input_manager_v3_destroy(nativeInterface(), false); + + m_handle = nullptr; } wl_global *WTextInputManagerV3::global() const { - return nativeInterface()->handle()->global; + if (!m_handle) + return nullptr; + return reinterpret_cast(m_handle)->global; } class Q_DECL_HIDDEN WTextInputV3Private : public WTextInputPrivate { public: W_DECLARE_PUBLIC(WTextInputV3) - WTextInputV3Private(qw_text_input_v3 *h, WTextInputV3 *qq) + WTextInputV3Private(wlr_text_input_v3 *h, WTextInputV3 *qq) : WTextInputPrivate(qq) , handle(h) - { } - - qw_text_input_v3 *const handle; + { + Q_ASSERT(h); + } + wlr_text_input_v3 *handle = nullptr; wl_client *waylandClient() const override { - return wl_resource_get_client(handle->handle()->resource); + return wl_resource_get_client(handle->resource); } + }; -WTextInputV3::WTextInputV3(qw_text_input_v3 *h, QObject *parent) +WTextInputV3::WTextInputV3(wlr_text_input_v3 *h, QObject *parent) : WTextInput(*new WTextInputV3Private(h, this), parent) { - connect(handle(), &qw_text_input_v3::notify_enable, this, &WTextInput::enabled); - connect(handle(), &qw_text_input_v3::notify_disable, this, &WTextInput::disabled); - connect(handle(), &qw_text_input_v3::notify_commit, this, &WTextInput::committed); + W_D(WTextInputV3); + listeners()->add(&h->events.enable, this, &WTextInputV3::enabled); + listeners()->add(&h->events.disable, this, &WTextInputV3::disabled); + listeners()->add(&h->events.commit, this, &WTextInputV3::committed); +} + +WTextInputV3::~WTextInputV3() +{ + teardown(); } WSeat *WTextInputV3::seat() const { - W_DC(WTextInputV3); - return WSeat::fromHandle(qw_seat::from(handle()->handle()->seat)); + return WSeat::fromHandle(handle()->seat); } WSurface *WTextInputV3::focusedSurface() const { - W_DC(WTextInputV3); - return WSurface::fromHandle(handle()->handle()->focused_surface); + return WSurface::fromHandle(handle()->focused_surface); } QString WTextInputV3::surroundingText() const { - return handle()->handle()->current.surrounding.text; + return handle()->current.surrounding.text; } int WTextInputV3::surroundingCursor() const { - return handle()->handle()->current.surrounding.cursor; + return handle()->current.surrounding.cursor; } int WTextInputV3::surroundingAnchor() const { - return handle()->handle()->current.surrounding.anchor; + return handle()->current.surrounding.anchor; } IME::ChangeCause WTextInputV3::textChangeCause() const { - return IME::ChangeCause(handle()->handle()->current.text_change_cause); + return IME::ChangeCause(handle()->current.text_change_cause); } IME::ContentHints WTextInputV3::contentHints() const { - return IME::ContentHints(handle()->handle()->current.content_type.hint); + return IME::ContentHints(handle()->current.content_type.hint); } IME::ContentPurpose WTextInputV3::contentPurpose() const { - return IME::ContentPurpose(handle()->handle()->current.content_type.purpose); + return IME::ContentPurpose(handle()->current.content_type.purpose); } QRect WTextInputV3::cursorRect() const { - return WTools::fromWLRBox(&handle()->handle()->current.cursor_rectangle); + return WTools::fromWLRBox(&handle()->current.cursor_rectangle); } IME::Features WTextInputV3::features() const { - return IME::Features(handle()->handle()->current.features); + return IME::Features(handle()->current.features); } -qw_text_input_v3 *WTextInputV3::handle() const +wlr_text_input_v3 *WTextInputV3::handle() const { return d_func()->handle; } void WTextInputV3::sendEnter(WSurface *surface) { - handle()->send_enter(surface->handle()->handle()); + Q_ASSERT(surface); + if (!surface) + return; + + auto *targetSurface = surface->handle(); + auto *focusedSurface = handle()->focused_surface; + if (focusedSurface == targetSurface) + return; + + if (focusedSurface) + sendLeave(); + + wlr_text_input_v3_send_enter(handle(), targetSurface); } void WTextInputV3::sendLeave() { - if (focusedSurface()) { - handle()->send_leave(); + if (handle()->focused_surface) { + // The client must drop its composing text when it loses focus, but some + // clients keep the last preedit rendered when they only receive leave. + // fcitx5 clears its own preedit without sending an empty one, so clear + // it here explicitly while the client is still listening. Skip it once + // the client disabled: that would be a state update outside an active + // input session. + if (handle()->current_enabled) { + sendPreeditString(QString(), 0, 0); + sendDone(); + } + wlr_text_input_v3_send_leave(handle()); } } void WTextInputV3::sendPreeditString(const QString &text, qint32 cursor_begin, qint32 cursor_end) { - handle()->send_preedit_string(qPrintable(text), cursor_begin, cursor_end); + wlr_text_input_v3_send_preedit_string(handle(), qPrintable(text), cursor_begin, cursor_end); } void WTextInputV3::sendCommitString(const QString &text) { - handle()->send_commit_string(qPrintable(text)); + wlr_text_input_v3_send_commit_string(handle(), qPrintable(text)); } void WTextInputV3::sendDeleteSurroundingText(quint32 before_length, quint32 after_length) { - handle()->send_delete_surrounding_text(before_length, after_length); + wlr_text_input_v3_send_delete_surrounding_text(handle(), before_length, after_length); } void WTextInputV3::sendDone() { - handle()->send_done(); + wlr_text_input_v3_send_done(handle()); } void WTextInputV3::handleIMCommitted(WInputMethodV2 *im) { - if (!im->preeditString().isEmpty()) { - sendPreeditString(im->preeditString(), im->preeditCursorBegin(), im->preeditCursorEnd()); - } + // A commit replaces the whole state, and the initial preedit is empty: + // fcitx5 only ever sends a non-empty set_preedit_string, so an empty preedit + // here means "clear it". Forwarding only non-empty preedits would leave the + // client rendering stale composing text that no later key can remove. + sendPreeditString(im->preeditString(), im->preeditCursorBegin(), im->preeditCursorEnd()); if (!im->commitString().isEmpty()) { sendCommitString(im->commitString()); } diff --git a/waylib/src/server/protocols/private/wtextinputv3_p.h b/waylib/src/server/protocols/private/wtextinputv3_p.h index 1ac3f2f909..0b7bf63ae4 100644 --- a/waylib/src/server/protocols/private/wtextinputv3_p.h +++ b/waylib/src/server/protocols/private/wtextinputv3_p.h @@ -1,25 +1,18 @@ -// Copyright (C) 2023 Yixue Wang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include "wglobal.h" #include "wserver.h" #include "wtextinput_p.h" -#include - #include #include Q_MOC_INCLUDE("wsurface.h") Q_MOC_INCLUDE("wseat.h") -Q_MOC_INCLUDE() - -QW_BEGIN_NAMESPACE -class qw_text_input_v3; -class qw_text_input_manager_v3; -QW_END_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class WSurface; @@ -84,7 +77,8 @@ class WAYLIB_SERVER_EXPORT WTextInputV3 : public WTextInput Terminal }; Q_ENUM(ContentPurpose) - WTextInputV3(QW_NAMESPACE::qw_text_input_v3 *handle, QObject *parent); + WTextInputV3(wlr_text_input_v3 *handle, QObject *parent); + ~WTextInputV3() override; WSeat *seat() const override; WSurface *focusedSurface() const override; @@ -96,8 +90,7 @@ class WAYLIB_SERVER_EXPORT WTextInputV3 : public WTextInput IME::ContentPurpose contentPurpose() const override; QRect cursorRect() const override; IME::Features features() const override; - QW_NAMESPACE::qw_text_input_v3 *handle() const; - + wlr_text_input_v3 *handle() const; public Q_SLOTS: void sendEnter(WSurface *surface) override; @@ -119,6 +112,7 @@ class WAYLIB_SERVER_EXPORT WTextInputManagerV3 : public QObject, public WObject, explicit WTextInputManagerV3(QObject *parent = nullptr); QByteArrayView interfaceName() const override; + wlr_text_input_manager_v3 *handle() const; Q_SIGNALS: void newTextInput(WTextInputV3 *textInput); diff --git a/waylib/src/server/protocols/private/wvirtualkeyboardv1.cpp b/waylib/src/server/protocols/private/wvirtualkeyboardv1.cpp index cbad472ad5..5871858ac0 100644 --- a/waylib/src/server/protocols/private/wvirtualkeyboardv1.cpp +++ b/waylib/src/server/protocols/private/wvirtualkeyboardv1.cpp @@ -1,17 +1,14 @@ -// Copyright (C) 2023 Yixue Wang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wvirtualkeyboardv1_p.h" #include "private/wglobal_p.h" +#include "wscoplistener.h" +#include "wayliblogging.h" -#include -#include +#include -#include - -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE -Q_DECLARE_LOGGING_CATEGORY(qLcInputMethod) class Q_DECL_HIDDEN WVirtualKeyboardManagerV1Private : public WObjectPrivate { @@ -22,7 +19,7 @@ class Q_DECL_HIDDEN WVirtualKeyboardManagerV1Private : public WObjectPrivate { } }; -WVirtualKeyboardManagerV1::WVirtualKeyboardManagerV1(QObject *parent) +WVirtualKeyboardManagerV1::WVirtualKeyboardManagerV1([[maybe_unused]] QObject *parent) : WObject(*new WVirtualKeyboardManagerV1Private(this)) {} @@ -31,18 +28,34 @@ QByteArrayView WVirtualKeyboardManagerV1::interfaceName() const return "zwp_virtual_keyboard_manager_v1"; } +wlr_virtual_keyboard_manager_v1 *WVirtualKeyboardManagerV1::handle() const +{ + return reinterpret_cast(m_handle); +} + void WVirtualKeyboardManagerV1::create(WServer *server) { - W_D(WVirtualKeyboardManagerV1); - auto manager = qw_virtual_keyboard_manager_v1::create(*server->handle()); + auto manager = wlr_virtual_keyboard_manager_v1_create(server->handle()); Q_ASSERT(manager); m_handle = manager; - connect(manager, &qw_virtual_keyboard_manager_v1::notify_new_virtual_keyboard, this, &WVirtualKeyboardManagerV1::newVirtualKeyboard); + W_D(WVirtualKeyboardManagerV1); + listeners()->add(&manager->events.new_virtual_keyboard, this, + &WVirtualKeyboardManagerV1::newVirtualKeyboard); +} + +void WVirtualKeyboardManagerV1::destroy([[maybe_unused]] WServer *server) +{ + if (ownsSocket() && m_handle) + wlr_virtual_keyboard_manager_v1_destroy(nativeInterface(), false); + + m_handle = nullptr; } wl_global *WVirtualKeyboardManagerV1::global() const { - return nativeInterface()->handle()->global; + if (!m_handle) + return nullptr; + return reinterpret_cast(m_handle)->global; } WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/private/wvirtualkeyboardv1_p.h b/waylib/src/server/protocols/private/wvirtualkeyboardv1_p.h index fa18fd189f..6f54f486bf 100644 --- a/waylib/src/server/protocols/private/wvirtualkeyboardv1_p.h +++ b/waylib/src/server/protocols/private/wvirtualkeyboardv1_p.h @@ -1,14 +1,12 @@ -// Copyright (C) 2023 Yixue Wang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include #include -#include - -struct wlr_virtual_keyboard_v1; WAYLIB_SERVER_BEGIN_NAMESPACE class WVirtualKeyboardManagerV1Private; class WAYLIB_SERVER_EXPORT WVirtualKeyboardManagerV1 : public QObject, public WObject, public WServerInterface @@ -19,12 +17,14 @@ class WAYLIB_SERVER_EXPORT WVirtualKeyboardManagerV1 : public QObject, public WO explicit WVirtualKeyboardManagerV1(QObject *parent = nullptr); QByteArrayView interfaceName() const override; + wlr_virtual_keyboard_manager_v1 *handle() const; Q_SIGNALS: void newVirtualKeyboard(wlr_virtual_keyboard_v1 *virtualKeyboard); private: void create(WServer *server) override; + void destroy(WServer *server) override; wl_global *global() const override; }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/private/wxwaylandsurface_p.h b/waylib/src/server/protocols/private/wxwaylandsurface_p.h new file mode 100644 index 0000000000..c622c61b4c --- /dev/null +++ b/waylib/src/server/protocols/private/wxwaylandsurface_p.h @@ -0,0 +1,83 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "wxwaylandsurface.h" +#include "private/wtoplevelsurface_p.h" +#include "wscoplistener.h" + +#include + +#include +#include +#include +#include +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class Q_DECL_HIDDEN WXWaylandSurfacePrivate : public WToplevelSurfacePrivate +{ +public: + WXWaylandSurfacePrivate(WXWaylandSurface *qq, wlr_xwayland_surface *handle, WXWayland *xwayland); + ~WXWaylandSurfacePrivate(); + + inline static WXWaylandSurfacePrivate *get(WXWaylandSurface *q) { + return q->d_func(); + } + + inline wlr_xwayland_surface *handle() const { + return m_handle; + } + + inline bool isMaximized() const { + return handle()->maximized_horz && handle()->maximized_vert; + } + + wl_client *waylandClient() const override { + return surface->handle()->resource->client; + } + + void init(); + void updateChildren(); + void updateParent(); + void updateSizeHints(); + void updateWindowTypes(); + void updateClipShape(); + // Called by the owner (WXWayland) while the native parent surface is + // being destroyed, before the parent wrapper is deleted: the child's + // QPointer to the parent wrapper would otherwise be cleared by the + // deletion before the native set_parent event arrives, making the + // regular parent-loss handling skip the change. + void handleParentDestroyed(WXWaylandSurface *parent); + + W_DECLARE_PUBLIC(WXWaylandSurface) + + WSurface *surface = nullptr; + WXWayland *xwayland = nullptr; + mutable int pidFD = -1; + + QList children; + QPointer parent; + QMetaObject::Connection parentSurfaceConnection; + QRect lastRequestConfigureGeometry; + WXWaylandSurface::ConfigureFlags lastRequestConfigureFlags = {0}; + WXWaylandSurface::WindowTypes windowTypes = {0}; + QRegion clipShapeRegion; + QVariantList clipShape; + bool hasClipShape = false; + QSize minimumSize; + QSize maximumSize = QSize(INT_MAX, INT_MAX); + uint maximized:1; + uint minimized:1; + uint fullscreen:1; + uint activated:1; + +private: + // XWayland owns this handle and destroys it after notifying the + // wrapper. Keep the address stable through that callback. + wlr_xwayland_surface *m_handle = nullptr; +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wcursorshapemanagerv1.cpp b/waylib/src/server/protocols/wcursorshapemanagerv1.cpp index 2a52997be3..8cc7e85830 100644 --- a/waylib/src/server/protocols/wcursorshapemanagerv1.cpp +++ b/waylib/src/server/protocols/wcursorshapemanagerv1.cpp @@ -1,21 +1,16 @@ -// Copyright (C) 2023 rewine . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wcursorshapemanagerv1.h" #include "wcursor.h" #include "wseat.h" +#include "wscoplistener.h" #include "private/wglobal_p.h" -#include -#include -#include - -#define CURSOR_SHAPE_MANAGER_V1_VERSION 1 +#include WAYLIB_SERVER_BEGIN_NAMESPACE -using QW_NAMESPACE::qw_cursor_shape_manager_v1; - class Q_DECL_HIDDEN WCursorShapeManagerV1Private : public WObjectPrivate { public: @@ -25,13 +20,8 @@ class Q_DECL_HIDDEN WCursorShapeManagerV1Private : public WObjectPrivate } - inline qw_cursor_shape_manager_v1 *handle() const { - return q_func()->nativeInterface(); - } - - inline wlr_cursor_shape_manager_v1 *nativeHandle() const { - Q_ASSERT(handle()); - return handle()->handle(); + inline wlr_cursor_shape_manager_v1 *handle() const { + return reinterpret_cast(q_func()->m_handle); } W_DECLARE_PUBLIC(WCursorShapeManagerV1) @@ -107,6 +97,10 @@ static inline auto wpToWCursorShape(wp_cursor_shape_device_v1_shape shape) { return WGlobal::CursorShape::ZoomIn; case WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ZOOM_OUT: return WGlobal::CursorShape::ZoomOut; + case WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_DND_ASK: + return WGlobal::CursorShape::DndAsk; + case WP_CURSOR_SHAPE_DEVICE_V1_SHAPE_ALL_RESIZE: + return WGlobal::CursorShape::AllResize; } return WGlobal::CursorShape::Invalid; } @@ -117,9 +111,9 @@ WCursorShapeManagerV1::WCursorShapeManagerV1() } -qw_cursor_shape_manager_v1 *WCursorShapeManagerV1::handle() const +wlr_cursor_shape_manager_v1 *WCursorShapeManagerV1::handle() const { - return nativeInterface(); + return reinterpret_cast(m_handle); } QByteArrayView WCursorShapeManagerV1::interfaceName() const @@ -130,23 +124,30 @@ QByteArrayView WCursorShapeManagerV1::interfaceName() const void WCursorShapeManagerV1::create(WServer *server) { W_D(WCursorShapeManagerV1); - if (!m_handle) { - m_handle = qw_cursor_shape_manager_v1::create(*server->handle(), CURSOR_SHAPE_MANAGER_V1_VERSION); - QObject::connect(handle(), &qw_cursor_shape_manager_v1::notify_request_set_shape, this, [this] + m_handle = wlr_cursor_shape_manager_v1_create(server->handle(), InterfaceVersion); + listeners()->add(&handle()->events.request_set_shape, this, [] (wlr_cursor_shape_manager_v1_request_set_shape_event *event) { - if (auto *seat = WSeat::fromHandle(QW_NAMESPACE::qw_seat::from(event->seat_client->seat))) { + if (auto *seat = WSeat::fromHandle(event->seat_client->seat)) { seat->setCursorShape(event->seat_client, wpToWCursorShape(event->shape)); } }); } } +void WCursorShapeManagerV1::destroy(WServer *) +{ + if (ownsSocket() && m_handle) + wlr_cursor_shape_manager_v1_destroy(nativeInterface(), false); + + m_handle = nullptr; +} + wl_global *WCursorShapeManagerV1::global() const { W_D(const WCursorShapeManagerV1); if (m_handle) - return d->nativeHandle()->global; + return d->handle()->global; return nullptr; } diff --git a/waylib/src/server/protocols/wcursorshapemanagerv1.h b/waylib/src/server/protocols/wcursorshapemanagerv1.h index 219933182e..5bbc0831cb 100644 --- a/waylib/src/server/protocols/wcursorshapemanagerv1.h +++ b/waylib/src/server/protocols/wcursorshapemanagerv1.h @@ -1,16 +1,13 @@ -// Copyright (C) 2023 rewine . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include #include -QW_BEGIN_NAMESPACE -class qw_cursor_shape_manager_v1; -QW_END_NAMESPACE - WAYLIB_SERVER_BEGIN_NAMESPACE class WCursor; @@ -24,12 +21,14 @@ class WAYLIB_SERVER_EXPORT WCursorShapeManagerV1 : public QObject, public WObjec public: explicit WCursorShapeManagerV1(); - QW_NAMESPACE::qw_cursor_shape_manager_v1 *handle() const; + wlr_cursor_shape_manager_v1 *handle() const; QByteArrayView interfaceName() const override; + static constexpr int InterfaceVersion = 2; protected: void create(WServer *server) override; + void destroy(WServer *server) override; wl_global *global() const override; }; diff --git a/waylib/src/server/protocols/wextforeigntoplevellistv1.cpp b/waylib/src/server/protocols/wextforeigntoplevellistv1.cpp index 26a35d2b07..faf701db18 100644 --- a/waylib/src/server/protocols/wextforeigntoplevellistv1.cpp +++ b/waylib/src/server/protocols/wextforeigntoplevellistv1.cpp @@ -1,23 +1,18 @@ -// Copyright (C) 2025 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wextforeigntoplevellistv1.h" #include "private/wglobal_p.h" -#include "wglobal.h" +#include "wpointer.h" #include "wtoplevelsurface.h" +#include "wayliblogging.h" -#include -#include +#include #include -#define EXT_FOREIGN_TOPLEVEL_LIST_V1_VERSION 1 - -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE -Q_LOGGING_CATEGORY(qLcExtForeignToplevel, "waylib.protocols.extforeigntoplevel", QtWarningMsg) - class Q_DECL_HIDDEN WExtForeignToplevelListV1Private : public WObjectPrivate { public: @@ -26,12 +21,23 @@ class Q_DECL_HIDDEN WExtForeignToplevelListV1Private : public WObjectPrivate { } + ~WExtForeignToplevelListV1Private() { + // The Qt connections live on the surfaces (receiver) while the + // lambdas capture this private and the raw handles; the manager may + // be destroyed before the surfaces, so disconnect them all here + // (mirrors remove()). + for (const auto &conns : std::as_const(surfaceConnections)) { + for (const auto &c : conns) + QObject::disconnect(c); + } + } + void add(WToplevelSurface *surface) { W_Q(WExtForeignToplevelListV1); if (surfaces.contains(surface)) { - qCCritical(qLcExtForeignToplevel) + qCCritical(lcWlExtForeignToplevel) << surface << " has been add to ext foreign toplevel list twice"; return; } @@ -42,27 +48,45 @@ class Q_DECL_HIDDEN WExtForeignToplevelListV1Private : public WObjectPrivate .title = title.constData(), .app_id = appId.constData(), }; - auto handle = qw_ext_foreign_toplevel_handle_v1::create( - *q->nativeInterface(), &state); + auto handle = wlr_ext_foreign_toplevel_handle_v1_create( + reinterpret_cast(q->m_handle), &state); - surface->safeConnect(&WToplevelSurface::titleChanged, handle, [this, handle, surface] { + QList conns; + conns.append(QObject::connect(surface, &WToplevelSurface::titleChanged, surface, [this, handle, surface] { updateState(surface, handle); - }); + })); - surface->safeConnect(&WToplevelSurface::appIdChanged, handle, [this, handle, surface] { + conns.append(QObject::connect(surface, &WToplevelSurface::appIdChanged, surface, [this, handle, surface] { updateState(surface, handle); - }); - - surfaces.insert({ surface, std::unique_ptr(handle) }); + })); + surfaceConnections.insert(surface, conns); + surfaces.insert({ surface, WUniquePointer(handle) }); + } void remove(WToplevelSurface *surface) { + // The Qt connections live on the surface (receiver) while the lambdas + // capture the raw wlr handle; disconnect before the handle is freed + // (mirrors master where the qw_* handle QObject teardown did it). + const auto conns = surfaceConnections.take(surface); + for (const auto &c : conns) + QObject::disconnect(c); surfaces.erase(surface); } + WToplevelSurface *findSurfaceByHandle(wlr_ext_foreign_toplevel_handle_v1 *handle) const + { + for (const auto &pair : surfaces) { + if (pair.second.get() == handle) { + return pair.first; + } + } + return nullptr; + } + private: - void updateState(WToplevelSurface *surface, qw_ext_foreign_toplevel_handle_v1 *handle) + void updateState(WToplevelSurface *surface, wlr_ext_foreign_toplevel_handle_v1 *handle) { const auto title = surface->title().toUtf8(); const auto appId = surface->appId().toLatin1(); @@ -70,15 +94,16 @@ class Q_DECL_HIDDEN WExtForeignToplevelListV1Private : public WObjectPrivate .title = title.constData(), .app_id = appId.constData(), }; - handle->update_state(&state); + wlr_ext_foreign_toplevel_handle_v1_update_state(handle, &state); } W_DECLARE_PUBLIC(WExtForeignToplevelListV1) - std::map> surfaces; + std::map> surfaces; + QHash> surfaceConnections; }; -WExtForeignToplevelListV1::WExtForeignToplevelListV1(QObject *parent) +WExtForeignToplevelListV1::WExtForeignToplevelListV1([[maybe_unused]] QObject *parent) : WObject(*new WExtForeignToplevelListV1Private(this), nullptr) { } @@ -97,26 +122,41 @@ void WExtForeignToplevelListV1::removeSurface(WToplevelSurface *surface) d->remove(surface); } +WToplevelSurface *WExtForeignToplevelListV1::findSurfaceByHandle(wlr_ext_foreign_toplevel_handle_v1 *handle) const +{ + W_D(const WExtForeignToplevelListV1); + + return d->findSurfaceByHandle(handle); +} + QByteArrayView WExtForeignToplevelListV1::interfaceName() const { return "ext_foreign_toplevel_list_v1"; } -void WExtForeignToplevelListV1::create(WServer *server) +wlr_ext_foreign_toplevel_list_v1 *WExtForeignToplevelListV1::handle() const { - W_D(WExtForeignToplevelListV1); + return reinterpret_cast(m_handle); +} - m_handle = qw_ext_foreign_toplevel_list_v1::create(*server->handle(), EXT_FOREIGN_TOPLEVEL_LIST_V1_VERSION); +void WExtForeignToplevelListV1::create(WServer *server) +{ + m_handle = wlr_ext_foreign_toplevel_list_v1_create(server->handle(), InterfaceVersion); } -void WExtForeignToplevelListV1::destroy(WServer *server) +void WExtForeignToplevelListV1::destroy([[maybe_unused]] WServer *server) { - Q_UNUSED(server); + if (ownsSocket() && m_handle) + wlr_ext_foreign_toplevel_list_v1_destroy(nativeInterface(), false); + + m_handle = nullptr; } wl_global *WExtForeignToplevelListV1::global() const { - return nativeInterface()->handle()->global; + if (!m_handle) + return nullptr; + return reinterpret_cast(m_handle)->global; } WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wextforeigntoplevellistv1.h b/waylib/src/server/protocols/wextforeigntoplevellistv1.h index 301ba837d1..bd11656d79 100644 --- a/waylib/src/server/protocols/wextforeigntoplevellistv1.h +++ b/waylib/src/server/protocols/wextforeigntoplevellistv1.h @@ -1,11 +1,11 @@ -// Copyright (C) 2025 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include #include -#include #include #include @@ -27,8 +27,13 @@ class WAYLIB_SERVER_EXPORT WExtForeignToplevelListV1 : public QObject, public WS void addSurface(WToplevelSurface *surface); void removeSurface(WToplevelSurface *surface); // Must `removeSurface` manually before surface destroy + // Reverse lookup: find WToplevelSurface from protocol handle + WToplevelSurface *findSurfaceByHandle(wlr_ext_foreign_toplevel_handle_v1 *handle) const; + QByteArrayView interfaceName() const override; + wlr_ext_foreign_toplevel_list_v1 *handle() const; + static constexpr int InterfaceVersion = 1; private: void create(WServer *server) override; void destroy(WServer *server) override; diff --git a/waylib/src/server/protocols/wextworkspacemanagerv1.cpp b/waylib/src/server/protocols/wextworkspacemanagerv1.cpp new file mode 100644 index 0000000000..c5e858c502 --- /dev/null +++ b/waylib/src/server/protocols/wextworkspacemanagerv1.cpp @@ -0,0 +1,128 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wextworkspacemanagerv1.h" +#include "woutput.h" +#include "wscoplistener.h" +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +WExtWorkspaceManagerV1::WExtWorkspaceManagerV1(QObject *parent) + : QObject(parent) +{ +} + +WExtWorkspaceManagerV1::~WExtWorkspaceManagerV1() +{ + teardown(); + destroy(nullptr); +} + +QByteArrayView WExtWorkspaceManagerV1::interfaceName() const +{ + return "ext_workspace_manager_v1"; +} + +wlr_ext_workspace_manager_v1 *WExtWorkspaceManagerV1::handle() const +{ + return nativeInterface(); +} + +void WExtWorkspaceManagerV1::create(WServer *server) +{ + m_handle = wlr_ext_workspace_manager_v1_create(server->handle(), InterfaceVersion); + if (!m_handle) + return; + listeners()->add(&handle()->events.commit, this, &WExtWorkspaceManagerV1::onCommit); + listeners()->add(&handle()->events.destroy, this, &WExtWorkspaceManagerV1::onNativeDestroyed); + Q_EMIT initialized(); +} + +void WExtWorkspaceManagerV1::destroy(WServer *) +{ + if (ownsSocket() && m_handle) + wlr_ext_workspace_manager_v1_destroy(handle(), false); + + m_handle = nullptr; +} + +void WExtWorkspaceManagerV1::onNativeDestroyed() +{ + teardown(); + m_handle = nullptr; + Q_EMIT invalidated(); +} + +void WExtWorkspaceManagerV1::onCommit(wlr_ext_workspace_v1_commit_event *event) +{ + Q_EMIT commit(event); +} + +wl_global *WExtWorkspaceManagerV1::global() const +{ + return handle() ? handle()->global : nullptr; +} + +wlr_ext_workspace_group_handle_v1 *WExtWorkspaceManagerV1::createGroup(uint32_t capabilities) +{ + return handle() ? wlr_ext_workspace_group_handle_v1_create(handle(), capabilities) : nullptr; +} + +void WExtWorkspaceManagerV1::removeGroup(wlr_ext_workspace_group_handle_v1 *group) +{ + Q_ASSERT(group && group->manager == handle()); + wlr_ext_workspace_group_handle_v1_destroy(group); +} + +void WExtWorkspaceManagerV1::outputEnter(wlr_ext_workspace_group_handle_v1 *group, WOutput *output) +{ + Q_ASSERT(group && group->manager == handle()); + wlr_ext_workspace_group_handle_v1_output_enter(group, output->handle()); +} + +void WExtWorkspaceManagerV1::outputLeave(wlr_ext_workspace_group_handle_v1 *group, WOutput *output) +{ + Q_ASSERT(group && group->manager == handle()); + wlr_ext_workspace_group_handle_v1_output_leave(group, output->handle()); +} + +wlr_ext_workspace_handle_v1 *WExtWorkspaceManagerV1::createWorkspace(const QByteArray &id, uint32_t capabilities) +{ + return handle() ? wlr_ext_workspace_handle_v1_create(handle(), id.isEmpty() ? nullptr : id.constData(), capabilities) : nullptr; +} + +void WExtWorkspaceManagerV1::removeWorkspace(wlr_ext_workspace_handle_v1 *workspace) +{ + Q_ASSERT(workspace && workspace->manager == handle()); + wlr_ext_workspace_handle_v1_destroy(workspace); +} + +void WExtWorkspaceManagerV1::setGroup(wlr_ext_workspace_handle_v1 *workspace, wlr_ext_workspace_group_handle_v1 *group) +{ + Q_ASSERT(workspace && workspace->manager == handle()); + Q_ASSERT(!group || group->manager == handle()); + wlr_ext_workspace_handle_v1_set_group(workspace, group); +} + +void WExtWorkspaceManagerV1::setName(wlr_ext_workspace_handle_v1 *workspace, const QString &name) +{ + Q_ASSERT(workspace && workspace->manager == handle()); + const auto utf8 = name.toUtf8(); + wlr_ext_workspace_handle_v1_set_name(workspace, utf8.constData()); +} + +void WExtWorkspaceManagerV1::setCoordinates(wlr_ext_workspace_handle_v1 *workspace, const QList &coordinates) +{ + Q_ASSERT(workspace && workspace->manager == handle()); + wlr_ext_workspace_handle_v1_set_coordinates(workspace, coordinates.constData(), coordinates.size()); +} + +void WExtWorkspaceManagerV1::setState(wlr_ext_workspace_handle_v1 *workspace, bool active, bool urgent, bool hidden) +{ + Q_ASSERT(workspace && workspace->manager == handle()); + wlr_ext_workspace_handle_v1_set_active(workspace, active); + wlr_ext_workspace_handle_v1_set_urgent(workspace, urgent); + wlr_ext_workspace_handle_v1_set_hidden(workspace, hidden); +} +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wextworkspacemanagerv1.h b/waylib/src/server/protocols/wextworkspacemanagerv1.h new file mode 100644 index 0000000000..d3e9c1f3c3 --- /dev/null +++ b/waylib/src/server/protocols/wextworkspacemanagerv1.h @@ -0,0 +1,61 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include +#include +#include +#include + +Q_MOC_INCLUDE("wlr_all.h") + +struct wlr_ext_workspace_manager_v1; +struct wlr_ext_workspace_group_handle_v1; +struct wlr_ext_workspace_handle_v1; +struct wlr_ext_workspace_v1_commit_event; + +WAYLIB_SERVER_BEGIN_NAMESPACE +class WOutput; + +class WAYLIB_SERVER_EXPORT WExtWorkspaceManagerV1 + : public QObject, public WServerInterface, public WObject +{ + Q_OBJECT +public: + explicit WExtWorkspaceManagerV1(QObject *parent = nullptr); + ~WExtWorkspaceManagerV1() override; + QByteArrayView interfaceName() const override; + wlr_ext_workspace_manager_v1 *handle() const; + static constexpr int InterfaceVersion = 1; + + wlr_ext_workspace_group_handle_v1 *createGroup(uint32_t capabilities); + void removeGroup(wlr_ext_workspace_group_handle_v1 *group); + void outputEnter(wlr_ext_workspace_group_handle_v1 *group, WOutput *output); + void outputLeave(wlr_ext_workspace_group_handle_v1 *group, WOutput *output); + wlr_ext_workspace_handle_v1 *createWorkspace(const QByteArray &id, uint32_t capabilities); + void removeWorkspace(wlr_ext_workspace_handle_v1 *workspace); + void setGroup(wlr_ext_workspace_handle_v1 *workspace, wlr_ext_workspace_group_handle_v1 *group); + void setName(wlr_ext_workspace_handle_v1 *workspace, const QString &name); + void setCoordinates(wlr_ext_workspace_handle_v1 *workspace, const QList &coordinates); + void setState(wlr_ext_workspace_handle_v1 *workspace, bool active, bool urgent, bool hidden); + +Q_SIGNALS: + void initialized(); + void invalidated(); + // The request list is owned by wlroots and valid only during this signal. + // Consumers must use a direct connection and process requests in list order. + void commit(wlr_ext_workspace_v1_commit_event *event); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; + +private: + void onCommit(wlr_ext_workspace_v1_commit_event *event); + void onNativeDestroyed(); +}; +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wforeigntoplevelv1.cpp b/waylib/src/server/protocols/wforeigntoplevelv1.cpp index c3eeb3dbdd..b61923016a 100644 --- a/waylib/src/server/protocols/wforeigntoplevelv1.cpp +++ b/waylib/src/server/protocols/wforeigntoplevelv1.cpp @@ -1,25 +1,26 @@ -// Copyright (C) 2023 Dingyuan Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wforeigntoplevelv1.h" #include "private/wglobal_p.h" #include "wglobal.h" +#include "wscoplistener.h" #include "woutput.h" #include "wtoplevelsurface.h" #include "wxdgtoplevelsurface.h" +#ifndef DISABLE_XWAYLAND #include "wxwaylandsurface.h" +#endif +#include "wayliblogging.h" -#include -#include -#include +#include + +#include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE -Q_LOGGING_CATEGORY(qLcWlrForeignToplevel, "waylib.protocols.foreigntoplevel", QtWarningMsg) - class Q_DECL_HIDDEN WForeignToplevelPrivate : public WObjectPrivate { public: @@ -28,142 +29,143 @@ class Q_DECL_HIDDEN WForeignToplevelPrivate : public WObjectPrivate { } + ~WForeignToplevelPrivate() { + // The Qt connections live on the surfaces (receiver) while the + // lambdas capture this private and the raw handles; the manager may + // be destroyed before the surfaces, so disconnect them all here + // (mirrors remove()). + for (const auto &conns : std::as_const(surfaceConnections)) { + for (const auto &c : conns) + QObject::disconnect(c); + } + } + void initSurface(WToplevelSurface *surface) { W_Q(WForeignToplevel); auto handle = surfaces.at(surface).get(); - surface->safeConnect(&WToplevelSurface::titleChanged, handle, [handle, surface] { + + QList conns; + conns.append(QObject::connect(surface, &WToplevelSurface::titleChanged, surface, [handle, surface] { const auto title = surface->title().toUtf8(); - handle->set_title(title); - }); + wlr_foreign_toplevel_handle_v1_set_title(handle, title); + })); - surface->safeConnect(&WToplevelSurface::appIdChanged, handle, [handle, surface] { + conns.append(QObject::connect(surface, &WToplevelSurface::appIdChanged, surface, [handle, surface] { const auto appId = surface->appId().toLatin1(); - handle->set_app_id(appId); - }); + wlr_foreign_toplevel_handle_v1_set_app_id(handle, appId); + })); - surface->safeConnect(&WToplevelSurface::minimizeChanged, handle, [handle, surface] { - handle->set_minimized(surface->isMinimized()); - }); + conns.append(QObject::connect(surface, &WToplevelSurface::minimizeChanged, surface, [handle, surface] { + wlr_foreign_toplevel_handle_v1_set_minimized(handle, surface->isMinimized()); + })); - surface->safeConnect(&WToplevelSurface::maximizeChanged, handle, [handle, surface] { - handle->set_maximized(surface->isMaximized()); - }); + conns.append(QObject::connect(surface, &WToplevelSurface::maximizeChanged, surface, [handle, surface] { + wlr_foreign_toplevel_handle_v1_set_maximized(handle, surface->isMaximized()); + })); - surface->safeConnect(&WToplevelSurface::fullscreenChanged, handle, [handle, surface] { - handle->set_fullscreen(surface->isFullScreen()); - }); + conns.append(QObject::connect(surface, &WToplevelSurface::fullscreenChanged, surface, [handle, surface] { + wlr_foreign_toplevel_handle_v1_set_fullscreen(handle, surface->isFullScreen()); + })); - surface->safeConnect(&WToplevelSurface::activateChanged, handle, [handle, surface] { - handle->set_activated(surface->isActivated()); - }); + conns.append(QObject::connect(surface, &WToplevelSurface::activateChanged, surface, [handle, surface] { + wlr_foreign_toplevel_handle_v1_set_activated(handle, surface->isActivated()); + })); if (auto *xdgSurface = qobject_cast(surface)) { auto updateSurfaceParent = [this, handle, xdgSurface] { WToplevelSurface *p = xdgSurface->parentXdgSurface(); if (!p) { - handle->set_parent(nullptr); + wlr_foreign_toplevel_handle_v1_set_parent(handle, nullptr); return; } if (!surfaces.contains(p)) { - qCCritical(qLcWlrForeignToplevel) + qCCritical(lcWlForeignToplevel) << "Xdg toplevel surface " << xdgSurface << "has set parent surface, but foreign_toplevel_handle for parent surface " "not found!"; return; } - handle->set_parent(*surfaces.at(p)); + wlr_foreign_toplevel_handle_v1_set_parent(handle, surfaces.at(p).get()); }; - xdgSurface->safeConnect(&WXdgToplevelSurface::parentXdgSurfaceChanged, - handle, - updateSurfaceParent); + conns.append(QObject::connect(xdgSurface, &WXdgToplevelSurface::parentXdgSurfaceChanged, + surface, + updateSurfaceParent)); updateSurfaceParent(); +#ifndef DISABLE_XWAYLAND } else if (auto *xwaylandSurface = qobject_cast(surface)) { auto updateSurfaceParent = [this, handle, xwaylandSurface] { WToplevelSurface *p = xwaylandSurface->parentXWaylandSurface(); if (!p) { - handle->set_parent(nullptr); + wlr_foreign_toplevel_handle_v1_set_parent(handle, nullptr); return; } if (!surfaces.contains(p)) { - qCCritical(qLcWlrForeignToplevel) + qCCritical(lcWlForeignToplevel) << "X11 surface " << xwaylandSurface << "has set parent surface, but foreign_toplevel_handle for parent surface " "not found!"; return; } - handle->set_parent(*surfaces.at(p)); + wlr_foreign_toplevel_handle_v1_set_parent(handle, surfaces.at(p).get()); }; - xwaylandSurface->safeConnect(&WXWaylandSurface::parentXWaylandSurfaceChanged, - handle, - updateSurfaceParent); + conns.append(QObject::connect(xwaylandSurface, &WXWaylandSurface::parentXWaylandSurfaceChanged, + surface, + updateSurfaceParent)); updateSurfaceParent(); +#endif } - surface->surface()->safeConnect(&WSurface::outputEntered, - handle, - [this, handle](WOutput *output) { - handle->output_enter(output->nativeHandle()); - }); - - surface->surface()->safeConnect(&WSurface::outputLeave, - handle, - [this, handle](WOutput *output) { - handle->output_leave(output->nativeHandle()); - }); - - QObject::connect(handle, - &qw_foreign_toplevel_handle_v1::notify_request_activate, - surface, - [surface, q](wlr_foreign_toplevel_handle_v1_activated_event *event) { - Q_EMIT q->requestActivate(surface); - }); - - QObject::connect(handle, - &qw_foreign_toplevel_handle_v1::notify_request_maximize, - surface, - [surface, q](wlr_foreign_toplevel_handle_v1_maximized_event *event) { - Q_EMIT q->requestMaximize(surface, event->maximized); - }); - - QObject::connect(handle, - &qw_foreign_toplevel_handle_v1::notify_request_minimize, - surface, - [surface, q](wlr_foreign_toplevel_handle_v1_minimized_event *event) { - Q_EMIT q->requestMinimize(surface, event->minimized); - }); - - QObject::connect(handle, - &qw_foreign_toplevel_handle_v1::notify_request_fullscreen, - surface, - [surface, q](wlr_foreign_toplevel_handle_v1_fullscreen_event *event) { - Q_EMIT q->requestFullscreen(surface, event->fullscreen); - }); - - QObject::connect(handle, - &qw_foreign_toplevel_handle_v1::notify_request_close, - surface, - [surface, q] { - Q_EMIT q->requestClose(surface); - }); - - QObject::connect(handle, - &qw_foreign_toplevel_handle_v1::notify_set_rectangle, - surface, - [surface, q](wlr_foreign_toplevel_handle_v1_set_rectangle_event *event) { - Q_EMIT q->rectangleChanged( - surface, - QRect{ event->x, event->y, event->width, event->height }); - }); + conns.append(QObject::connect(surface->surface(), &WSurface::outputEntered, + surface, + [handle](WOutput *output) { + wlr_foreign_toplevel_handle_v1_output_enter(handle, output->handle()); + })); + + conns.append(QObject::connect(surface->surface(), &WSurface::outputLeave, + surface, + [handle](WOutput *output) { + wlr_foreign_toplevel_handle_v1_output_leave(handle, output->handle()); + })); + + auto *wsurface = surface->surface(); + auto *ls = wsurface->listeners(q_ptr); + ls->add(&handle->events.request_activate, surface, + [surface, q]([[maybe_unused]] wlr_foreign_toplevel_handle_v1_activated_event *event) { + Q_EMIT q->requestActivate(surface); + }); + ls->add(&handle->events.request_maximize, surface, + [surface, q](wlr_foreign_toplevel_handle_v1_maximized_event *event) { + Q_EMIT q->requestMaximize(surface, event->maximized); + }); + ls->add(&handle->events.request_minimize, surface, + [surface, q](wlr_foreign_toplevel_handle_v1_minimized_event *event) { + Q_EMIT q->requestMinimize(surface, event->minimized); + }); + ls->add(&handle->events.request_fullscreen, surface, + [surface, q](wlr_foreign_toplevel_handle_v1_fullscreen_event *event) { + Q_EMIT q->requestFullscreen(surface, event->fullscreen); + }); + ls->add(&handle->events.request_close, surface, + [surface, q](void *) { + Q_EMIT q->requestClose(surface); + }); + ls->add(&handle->events.set_rectangle, surface, + [surface, q](wlr_foreign_toplevel_handle_v1_set_rectangle_event *event) { + Q_EMIT q->rectangleChanged( + surface, + QRect{ event->x, event->y, event->width, event->height }); + }); const auto title = surface->title().toUtf8(); const auto appId = surface->appId().toLatin1(); - handle->set_title(title); - handle->set_app_id(appId); - handle->set_minimized(surface->isMinimized()); - handle->set_maximized(surface->isMaximized()); - handle->set_fullscreen(surface->isFullScreen()); - handle->set_activated(surface->isActivated()); + wlr_foreign_toplevel_handle_v1_set_title(handle, title); + wlr_foreign_toplevel_handle_v1_set_app_id(handle, appId); + wlr_foreign_toplevel_handle_v1_set_minimized(handle, surface->isMinimized()); + wlr_foreign_toplevel_handle_v1_set_maximized(handle, surface->isMaximized()); + wlr_foreign_toplevel_handle_v1_set_fullscreen(handle, surface->isFullScreen()); + wlr_foreign_toplevel_handle_v1_set_activated(handle, surface->isActivated()); + surfaceConnections.insert(handle, conns); } void add(WToplevelSurface *surface) @@ -171,28 +173,41 @@ class Q_DECL_HIDDEN WForeignToplevelPrivate : public WObjectPrivate W_Q(WForeignToplevel); if (surfaces.contains(surface)) { - qCCritical(qLcWlrForeignToplevel) + qCCritical(lcWlForeignToplevel) << surface << " has been add to foreign toplevel twice"; return; } - auto handle = qw_foreign_toplevel_handle_v1::create( - *q->nativeInterface()); - surfaces.insert({ surface, std::unique_ptr(handle) }); + auto handle = wlr_foreign_toplevel_handle_v1_create( + reinterpret_cast(q->m_handle)); + surfaces.insert({ surface, WUniquePointer(handle) }); initSurface(surface); } void remove(WToplevelSurface *surface) { + auto it = surfaces.find(surface); + if (it != surfaces.end()) { + surface->surface()->removeListeners(q_ptr); + // The Qt connections below live on the surface (receiver), while the + // lambdas capture the raw wlr handle; disconnect them before the + // handle is freed, mirroring master where the qw_* handle QObject + // teardown disconnected them implicitly. + const auto conns = surfaceConnections.take(it->second.get()); + for (const auto &c : conns) + QObject::disconnect(c); + } surfaces.erase(surface); } + QHash> surfaceConnections; + W_DECLARE_PUBLIC(WForeignToplevel) - std::map> surfaces; + std::map> surfaces; }; -WForeignToplevel::WForeignToplevel(QObject *parent) +WForeignToplevel::WForeignToplevel([[maybe_unused]] QObject *parent) : WObject(*new WForeignToplevelPrivate(this), nullptr) { } @@ -216,20 +231,29 @@ QByteArrayView WForeignToplevel::interfaceName() const return "zwlr_foreign_toplevel_manager_v1"; } -void WForeignToplevel::create(WServer *server) +wlr_foreign_toplevel_manager_v1 *WForeignToplevel::handle() const { - W_D(WForeignToplevel); + return reinterpret_cast(m_handle); +} - m_handle = qw_foreign_toplevel_manager_v1::create(*server->handle()); +void WForeignToplevel::create(WServer *server) +{ + m_handle = wlr_foreign_toplevel_manager_v1_create(server->handle()); } -void WForeignToplevel::destroy(WServer *server) +void WForeignToplevel::destroy([[maybe_unused]] WServer *server) { + if (ownsSocket() && m_handle) + wlr_foreign_toplevel_manager_v1_destroy(nativeInterface(), false); + + m_handle = nullptr; } wl_global *WForeignToplevel::global() const { - return nativeInterface()->handle()->global; + if (!m_handle) + return nullptr; + return reinterpret_cast(m_handle)->global; } WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wforeigntoplevelv1.h b/waylib/src/server/protocols/wforeigntoplevelv1.h index f6bf54ed8d..f465451a37 100644 --- a/waylib/src/server/protocols/wforeigntoplevelv1.h +++ b/waylib/src/server/protocols/wforeigntoplevelv1.h @@ -1,11 +1,10 @@ -// Copyright (C) 2023 Dingyuan Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include #include -#include #include #include @@ -28,6 +27,7 @@ class WAYLIB_SERVER_EXPORT WForeignToplevel : public QObject, public WServerInte void removeSurface(WToplevelSurface *surface); // Must `removeSurface` manually before surface destroy QByteArrayView interfaceName() const override; + wlr_foreign_toplevel_manager_v1 *handle() const; Q_SIGNALS: void requestMaximize(WToplevelSurface *surface, bool isMaximized); diff --git a/waylib/src/server/protocols/winputmethodhelper.cpp b/waylib/src/server/protocols/winputmethodhelper.cpp index b42ebe9148..e88996256c 100644 --- a/waylib/src/server/protocols/winputmethodhelper.cpp +++ b/waylib/src/server/protocols/winputmethodhelper.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2023 Yixue Wang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "winputmethodhelper.h" @@ -12,70 +12,84 @@ #include "wseat.h" #include "wsurface.h" #include "private/wglobal_p.h" +#include "wscoplistener.h" +#include "wayliblogging.h" -#include -#include -#include -#include -#include -#include -#include +#include + +#include -#include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE -Q_LOGGING_CATEGORY(qLcInputMethod, "waylib.server.im", QtInfoMsg) - struct Q_DECL_HIDDEN GrabHandlerArg { const WInputMethodHelper *const helper; - qw_input_method_keyboard_grab_v2 *grab; + wlr_input_method_keyboard_grab_v2 *grab; }; void handleKey(struct wlr_seat_keyboard_grab *grab, uint32_t time_msec, uint32_t key, uint32_t state) { auto arg = reinterpret_cast(grab->data); + if (!arg->grab) { + qCCritical(lcWlInputMethod) << "Ignore key event for destroyed input method keyboard grab" + << "key" << key << "state" << state; + return; + } for (auto vk: arg->helper->virtualKeyboards()) { - if (wlr_keyboard_from_input_device(vk->handle()->handle()) == grab->seat->keyboard_state.keyboard) { - grab->seat->keyboard_state.default_grab->interface->key(grab, time_msec, key, state); - return; + if (wlr_keyboard_from_input_device(vk->handle()) == grab->seat->keyboard_state.keyboard) { + auto *virtualKeyboard = wlr_input_device_get_virtual_keyboard(vk->handle()); + if (virtualKeyboard && virtualKeyboard->resource && arg->grab->resource + && wl_resource_get_client(virtualKeyboard->resource) + == wl_resource_get_client(arg->grab->resource)) { + grab->seat->keyboard_state.default_grab->interface->key(grab, time_msec, key, state); + return; + } } } - arg->grab->send_key(time_msec, Qt::Key(key), state); + wlr_input_method_keyboard_grab_v2_send_key(arg->grab, time_msec, key, state); } void handleModifiers(struct wlr_seat_keyboard_grab *grab, const struct wlr_keyboard_modifiers *modifiers) { auto arg = reinterpret_cast(grab->data); + if (!arg->grab) { + qCCritical(lcWlInputMethod) << "Ignore modifiers for destroyed input method keyboard grab"; + return; + } for (auto vk: arg->helper->virtualKeyboards()) { - if (wlr_keyboard_from_input_device(vk->handle()->handle()) == grab->seat->keyboard_state.keyboard) { - grab->seat->keyboard_state.default_grab->interface->modifiers(grab, modifiers); - return; + if (wlr_keyboard_from_input_device(vk->handle()) == grab->seat->keyboard_state.keyboard) { + auto *virtualKeyboard = wlr_input_device_get_virtual_keyboard(vk->handle()); + if (virtualKeyboard && virtualKeyboard->resource && arg->grab->resource + && wl_resource_get_client(virtualKeyboard->resource) + == wl_resource_get_client(arg->grab->resource)) { + grab->seat->keyboard_state.default_grab->interface->modifiers(grab, modifiers); + return; + } } } - arg->grab->send_modifiers(const_cast(modifiers)); + wlr_input_method_keyboard_grab_v2_send_modifiers(arg->grab, const_cast(modifiers)); } class Q_DECL_HIDDEN WInputMethodHelperPrivate : public WObjectPrivate { W_DECLARE_PUBLIC(WInputMethodHelper) public: - explicit WInputMethodHelperPrivate(WServer *s, WSeat *st, WInputMethodHelper *qq) + explicit WInputMethodHelperPrivate(WServer *s, WSeat *st, WInputMethodHelper *qq, + const WInputMethodHelper::Protocols &protocols) : WObjectPrivate(qq) , server(s) , seat(st) - , inputMethodManagerV2(server->attach()) - , textInputManagerV1(server->attach()) - , textInputManagerV2(server->attach()) - , textInputManagerV3(server->attach()) - , virtualKeyboardManagerV1(server->attach()) + , inputMethodManagerV2(protocols.inputMethod) + , textInputManagerV1(protocols.textInputV1) + , textInputManagerV2(protocols.textInputV2) + , textInputManagerV3(protocols.textInputV3) + , virtualKeyboardManagerV1(protocols.virtualKeyboard) , enabledTextInput(nullptr) , activeInputMethod(nullptr) , activeKeyboardGrab(nullptr) - , keyboardGrab() - , grabInterface() - , handlerArg({.helper = qq}) + , keyboardGrab{} + , grabInterface{} + , handlerArg({.helper = qq, .grab = nullptr}) { Q_ASSERT(server); Q_ASSERT(seat); @@ -83,6 +97,63 @@ class Q_DECL_HIDDEN WInputMethodHelperPrivate : public WObjectPrivate Q_ASSERT(textInputManagerV1); Q_ASSERT(textInputManagerV2); Q_ASSERT(textInputManagerV3); + Q_ASSERT(virtualKeyboardManagerV1); + } + + void endGrab(wlr_input_method_keyboard_grab_v2 *kgv2) + { + if (!seat) { + qCCritical(lcWlInputMethod) << "Failed to end input method keyboard grab - seat is already destroyed" + << kgv2; + return; + } + + auto *kgHandle = kgv2; + if (!kgHandle) { + qCCritical(lcWlInputMethod) << "Failed to end input method keyboard grab - grab handle is invalid" + << kgv2; + return; + } + + if (kgHandle->keyboard) { + wlr_seat_keyboard_send_modifiers(seat->handle(), &kgHandle->keyboard->modifiers); + } + // Only end the grab if our grab is still the active one on the seat. + // A popup grab may have silently replaced us (wlr_seat_keyboard_start_grab + // unconditionally overwrites keyboard_state.grab). + auto isStillActive = seat->handle()->keyboard_state.grab == &keyboardGrab; + qCDebug(lcWlInputMethod) << "endGrab: isStillActive" << isStillActive << "grab ptr" + << seat->handle()->keyboard_state.grab << "&keyboardGrab" + << &keyboardGrab; + if (isStillActive) { + wlr_seat_keyboard_end_grab(seat->handle()); + } + } + + void setKeyboard(wlr_input_method_keyboard_grab_v2 *kgv2, WInputDevice *keyboard) + { + auto *kgHandle = kgv2; + if (!kgHandle) { + qCCritical(lcWlInputMethod) << "Failed to set keyboard for input method grab - grab handle is invalid" + << kgv2 << "keyboard" << keyboard; + return; + } + + if (keyboard) { + auto *virtualKeyboard = wlr_input_device_get_virtual_keyboard(keyboard->handle()); + // refer to: + // https://github.com/swaywm/sway/blob/master/sway/input/keyboard.c#L391 + if (virtualKeyboard + && virtualKeyboard->resource + && kgHandle->resource + && wl_resource_get_client(virtualKeyboard->resource) + == wl_resource_get_client(kgHandle->resource)) { + return; + } + wlr_input_method_keyboard_grab_v2_set_keyboard(kgv2, wlr_keyboard_from_input_device(keyboard->handle())); + } else { + wlr_input_method_keyboard_grab_v2_set_keyboard(kgv2, nullptr); + } } const QPointer server; @@ -94,23 +165,31 @@ class Q_DECL_HIDDEN WInputMethodHelperPrivate : public WObjectPrivate const QPointer virtualKeyboardManagerV1; WTextInput *enabledTextInput { nullptr }; WInputMethodV2 *activeInputMethod { nullptr }; - qw_input_method_keyboard_grab_v2 *activeKeyboardGrab {nullptr}; + wlr_input_method_keyboard_grab_v2 *activeKeyboardGrab {nullptr}; wlr_seat_keyboard_grab keyboardGrab; wlr_keyboard_grab_interface grabInterface; GrabHandlerArg handlerArg; + std::unique_ptr keyboardGrabListenerOwner; QList textInputs; QList virtualKeyboards; QList popupSurfaces; + }; -WInputMethodHelper::WInputMethodHelper(WServer *server, WSeat *seat) +WInputMethodHelper::WInputMethodHelper(WServer *server, WSeat *seat, const Protocols &protocols) : QObject(server) - , WObject(*new WInputMethodHelperPrivate(server, seat, this)) + , WObject(*new WInputMethodHelperPrivate(server, seat, this, protocols)) { W_D(WInputMethodHelper); - d->seat->safeConnect(&WSeat::keyboardFocusSurfaceChanged, this, &WInputMethodHelper::resendKeyboardFocus); + QObject::connect(d->seat, &WSeat::keyboardFocusSurfaceChanged, this, &WInputMethodHelper::resendKeyboardFocus); + QObject::connect(d->seat, &WSeat::keyboardChanged, this, [d] { + if (auto *activeKG = d->activeKeyboardGrab) + d->setKeyboard(activeKG, d->seat->keyboard()); + }); + d->seat->listeners(this)->add(&d->seat->handle()->events.keyboard_grab_begin, this, + &WInputMethodHelper::handleKeyboardGrabBegin); connect(d->inputMethodManagerV2, &WInputMethodManagerV2::newInputMethod, this, &WInputMethodHelper::handleNewIMV2); connect(d->textInputManagerV3, &WTextInputManagerV3::newTextInput, this, &WInputMethodHelper::handleNewTI); connect(d->virtualKeyboardManagerV1, &WVirtualKeyboardManagerV1::newVirtualKeyboard, this, &WInputMethodHelper::handleNewVKV1); @@ -120,8 +199,48 @@ WInputMethodHelper::WInputMethodHelper(WServer *server, WSeat *seat) WInputMethodHelper::~WInputMethodHelper() { + teardown(); W_D(WInputMethodHelper); - if (d->seat) d->seat->safeDisconnect(this); + // The wrappers tracked below have no QObject parent and their destroy + // callbacks capture this private; the native objects may outlive the + // helper (which is deleted before the WServer), so release them here + // while the helper is still alive to prevent callbacks from running + // against freed state. + + // Active input method wrapper: normally destroyed from the native + // destroy callback; detach that callback and release it explicitly. + if (d->activeInputMethod) + d->activeInputMethod->removeListeners(this); + if (d->activeInputMethod) { + delete d->activeInputMethod; + d->activeInputMethod = nullptr; + } + + // Input popup surface wrappers. + const auto popupSurfaces = d->popupSurfaces; + d->popupSurfaces.clear(); + for (auto *popup : popupSurfaces) { + popup->removeListeners(this); + delete popup; + } + + // Virtual keyboard device wrappers (also detach them from the seat). + const auto virtualKeyboards = d->virtualKeyboards; + d->virtualKeyboards.clear(); + for (auto *keyboard : virtualKeyboards) { + keyboard->removeListeners(this); + if (d->seat) { + if (d->seat->keyboard() == keyboard && d->seat->keyboardGroupKeyboard()) + d->seat->setKeyboard(d->seat->keyboardGroupKeyboard()); + d->seat->detachInputDevice(keyboard); + } + delete keyboard; + } + + if (d->seat) { + d->seat->removeListeners(this); + d->seat->disconnect(this); + } if (d->inputMethodManagerV2) d->inputMethodManagerV2->disconnect(this); if (d->textInputManagerV1) d->textInputManagerV1->disconnect(this); if (d->textInputManagerV2) d->textInputManagerV2->disconnect(this); @@ -165,41 +284,70 @@ WInputMethodV2 *WInputMethodHelper::inputMethod() const return d->activeInputMethod; } +WSurface *WInputMethodHelper::textInputFocusSurface() const +{ + auto ti = enabledTextInput(); + return ti ? ti->focusedSurface() : nullptr; +} + +QRect WInputMethodHelper::textInputCursorRect() const +{ + auto ti = enabledTextInput(); + return ti ? ti->cursorRect() : QRect(); +} + void WInputMethodHelper::setInputMethod(WInputMethodV2 *im) { W_D(WInputMethodHelper); if (d->activeInputMethod == im) return; if (d->activeInputMethod) - d->activeInputMethod->safeDisconnect(this); + d->activeInputMethod->removeListeners(this); d->activeInputMethod = im; if (d->activeInputMethod) - d->activeInputMethod->safeConnect(&qw_input_method_v2::before_destroy, this, &WInputMethodHelper::handleActiveIMDestroyed); + d->activeInputMethod->listeners(this)->add(&im->handle()->events.destroy, this, + &WInputMethodHelper::handleActiveIMDestroyed); } -qw_input_method_keyboard_grab_v2 *WInputMethodHelper::activeKeyboardGrab() const +wlr_input_method_keyboard_grab_v2 *WInputMethodHelper::activeKeyboardGrab() const { W_DC(WInputMethodHelper); return d->activeKeyboardGrab; } +bool WInputMethodHelper::isActiveKeyboardGrabOwner() const +{ + W_DC(WInputMethodHelper); + if (!d->activeKeyboardGrab) + return false; + return d->seat->handle()->keyboard_state.grab == &d->keyboardGrab; +} + const QList &WInputMethodHelper::virtualKeyboards() const { W_DC(WInputMethodHelper); return d->virtualKeyboards; } -void WInputMethodHelper::handleNewIMV2(qw_input_method_v2 *imv2) +void WInputMethodHelper::handleNewIMV2(wlr_input_method_v2 *imv2) { W_D(WInputMethodHelper); - auto wimv2 = new WInputMethodV2(imv2, this); - if (d->seat->name() != wimv2->seat()->name()) + // Reject input methods from other seats before wrapping: the wrapper + // attaches native listeners in its constructor, so an early return + // afterwards would leak it (the listeners stay registered on the native + // handle and assert on its destroy). + auto *imSeat = WSeat::fromHandle(imv2->seat); + if (!imSeat || d->seat != imSeat) return; if (inputMethod()) { - qCWarning(qLcInputMethod) << "Ignore second creation of input on the same seat."; - wimv2->sendUnavailable(); + qCWarning(lcWlInputMethod) << "Ignore second creation of input on the same seat."; + // sendUnavailable() destroys the native input method synchronously + // (asserting its listener lists are empty afterwards); call it + // before creating the wrapper so nothing is left attached. + wlr_input_method_v2_send_unavailable(imv2); return; } + auto wimv2 = new WInputMethodV2(imv2); setInputMethod(wimv2); connect(wimv2, &WInputMethodV2::committed, this, &WInputMethodHelper::handleIMCommitted); connect(wimv2, &WInputMethodV2::newKeyboardGrab, this, &WInputMethodHelper::handleNewKGV2); @@ -209,70 +357,62 @@ void WInputMethodHelper::handleNewIMV2(qw_input_method_v2 *imv2) // For text input v1, when after sendEnter, enabled signal will be emitted } -void WInputMethodHelper::handleNewKGV2(qw_input_method_keyboard_grab_v2 *kgv2) +void WInputMethodHelper::handleNewKGV2(wlr_input_method_keyboard_grab_v2 *kgv2) { W_D(WInputMethodHelper); Q_ASSERT(d->seat); - auto endGrab = [this, d](qw_input_method_keyboard_grab_v2 *kgv2) { - if (!d->seat) - return; - if (kgv2->handle()->keyboard) { - d->seat->handle()->keyboard_send_modifiers(&kgv2->handle()->keyboard->modifiers); - } - d->seat->handle()->keyboard_end_grab(); - }; - auto setKeyboard = [this, d](qw_input_method_keyboard_grab_v2 *kgv2, WInputDevice *keyboard) { - if (keyboard) { - auto *virtualKeyboard = wlr_input_device_get_virtual_keyboard(*keyboard->handle()); - // refer to: - // https://github.com/swaywm/sway/blob/master/sway/input/keyboard.c#L391 - if (virtualKeyboard - && wl_resource_get_client(virtualKeyboard->resource) - == wl_resource_get_client(kgv2->handle()->resource)) { - return; - } - kgv2->set_keyboard(wlr_keyboard_from_input_device(*keyboard->handle())); - } else { - kgv2->set_keyboard(nullptr); - } - }; if (auto activeKG = activeKeyboardGrab()) { - endGrab(activeKG); + d->endGrab(activeKG); } d->activeKeyboardGrab = kgv2; - setKeyboard(kgv2, d->seat->keyboard()); - connect(d->seat, &WSeat::keyboardChanged, kgv2, [setKeyboard, d, kgv2](){ - setKeyboard(kgv2, d->seat->keyboard()); - }); - d->grabInterface = *d->seat->nativeHandle()->keyboard_state.grab->interface; + d->setKeyboard(kgv2, d->seat->keyboard()); + // Base the IME grab on the seat's default keyboard grab interface, not + // whatever grab happens to be active right now. Copying the active grab + // also copies its cancel() callback: if a DnD drag grab is active, endGrab + // would later call drag_handle_keyboard_cancel() with our handlerArg as the + // wlr_drag*, crashing in drag_destroy(). The default interface's cancel() + // is a no-op, which is what an IME grab (ended explicitly) needs. + d->grabInterface = *d->seat->handle()->keyboard_state.default_grab->interface; d->grabInterface.key = handleKey; d->grabInterface.modifiers = handleModifiers; - d->keyboardGrab.seat = d->seat->nativeHandle(); + d->keyboardGrab.seat = d->seat->handle(); d->handlerArg.grab = kgv2; d->keyboardGrab.data = &d->handlerArg; d->keyboardGrab.interface = &d->grabInterface; - d->seat->handle()->keyboard_start_grab(&d->keyboardGrab); - connect(kgv2, &qw_input_method_keyboard_grab_v2::before_destroy, this, [this, d, endGrab, kgv2] { - if (activeKeyboardGrab() == kgv2) { - endGrab(kgv2); + wlr_seat_keyboard_start_grab(d->seat->handle(), &d->keyboardGrab); + qCDebug(lcWlInputMethod) << "IME keyboard grab installed"; + d->keyboardGrabListenerOwner = std::make_unique(); + auto *grabOwner = d->keyboardGrabListenerOwner.get(); + d->seat->listeners(grabOwner)->add(&kgv2->events.destroy, this, [this, d, kgv2, grabOwner] { + qCDebug(lcWlInputMethod) << "IME keyboard grab before_destroy"; + Q_ASSERT(activeKeyboardGrab() == kgv2); + d->endGrab(kgv2); d->activeKeyboardGrab = nullptr; - } - }); + d->handlerArg.grab = nullptr; + d->seat->removeListeners(grabOwner); + d->keyboardGrabListenerOwner.reset(); + }); } -void WInputMethodHelper::handleNewIPSV2(qw_input_popup_surface_v2 *ipsv2) +void WInputMethodHelper::handleNewIPSV2(wlr_input_popup_surface_v2 *ipsv2) { W_D(WInputMethodHelper); - auto createPopupSurface = [this, d] (WSurface *focus, QRect cursorRect, qw_input_popup_surface_v2 *popupSurface){ - auto surface = new WInputPopupSurface(popupSurface, focus, this); + auto createPopupSurface = [this, d] (WSurface *focus, QRect cursorRect, wlr_input_popup_surface_v2 *popupSurface){ + auto surface = new WInputPopupSurface(popupSurface, focus); d->popupSurfaces.append(surface); updatePopupSurface(surface, cursorRect); Q_EMIT inputPopupSurfaceV2Added(surface); - surface->safeConnect(&qw_input_popup_surface_v2::before_destroy, this, [this, d, surface](){ + auto *listeners = surface->listeners(this); + listeners->add(&popupSurface->events.destroy, this, + [this, d, surface] (void *) { d->popupSurfaces.removeAll(surface); Q_EMIT inputPopupSurfaceV2Removed(surface); - surface->safeDeleteLater(); + // Safe to destroy the wrapper from inside its own destroy + // callback: the listener closure is reference-counted, and + // ~WInputPopupSurface clears the reverse mapping while the + // native popup storage is still valid. + delete surface; }); }; auto ti = enabledTextInput(); @@ -284,38 +424,70 @@ void WInputMethodHelper::handleNewIPSV2(qw_input_popup_surface_v2 *ipsv2) void WInputMethodHelper::handleNewVKV1(wlr_virtual_keyboard_v1 *vkv1) { W_D(WInputMethodHelper); - WInputDevice *keyboard = new WInputDevice(qw_input_device::from(&vkv1->keyboard.base)); + if (WSeat::fromHandle(vkv1->seat) != d->seat) + return; + auto *keyboard = new WInputDevice(&vkv1->keyboard.base, true); d->virtualKeyboards.append(keyboard); d->seat->attachInputDevice(keyboard); - keyboard->safeConnect(&qw_input_device::before_destroy, this, [d, this, keyboard] () { - if (d->seat) d->seat->detachInputDevice(keyboard); + auto *listeners = keyboard->listeners(this); + listeners->add(&vkv1->keyboard.base.events.destroy, this, + [this, d, keyboard] (void *) { + if (d->seat) { + // Switch seat keyboard to group before the virtual keyboard's + // wlr_keyboard is destroyed. This removes handle_keyboard_destroy + // listener from the virtual keyboard, preventing + // wlr_seat_set_keyboard(NULL). + if (d->seat->keyboard() == keyboard && d->seat->keyboardGroupKeyboard()) + d->seat->setKeyboard(d->seat->keyboardGroupKeyboard()); + d->seat->detachInputDevice(keyboard); + } d->virtualKeyboards.removeOne(keyboard); - keyboard->safeDeleteLater(); + // Safe to destroy the wrapper from inside its own destroy callback: + // the listener closure is reference-counted and outlives the + // emission, and ~WInputDevice clears the reverse mapping while the + // native handle is still valid. + delete keyboard; }); } +void WInputMethodHelper::handleKeyboardGrabBegin() +{ + W_D(WInputMethodHelper); + // If another grab (popup, drag, etc.) silently replaced our keyboard grab, + // notify all text inputs to leave so the IME can deactivate. + // Our grab v2 object is still alive (endGrab only runs on before_destroy), + // so activeKeyboardGrab is non-null, but seat->keyboard_state.grab no longer + // points to our keyboardGrab. + if (d->activeKeyboardGrab && d->seat->handle()->keyboard_state.grab != &d->keyboardGrab) { + qCDebug(lcWlInputMethod) << "IME keyboard grab silently replaced, notifying leave"; + notifyLeave(); + } +} + void WInputMethodHelper::resendKeyboardFocus() { W_D(WInputMethodHelper); - qCInfo(qLcInputMethod()) << "resend keyboard focus"; - notifyLeave(); + qCInfo(lcWlInputMethod()) << "resend keyboard focus"; auto focus = d->seat->keyboardFocusSurface(); - if (!focus) - return; - qCDebug(qLcInputMethod) << "focus" << focus << "from client" << focus->waylandClient(); for (auto textInput : std::as_const(d->textInputs)) { - qCDebug(qLcInputMethod()) << "trying to send focus to" << textInput << "from client" << textInput->waylandClient(); + if (textInput->focusedSurface() && textInput->focusedSurface() != focus) + textInput->sendLeave(); + if (!focus) + continue; + qCDebug(lcWlInputMethod()) << "trying to send focus to" << textInput << "from client" << textInput->waylandClient(); if (focus->waylandClient() == textInput->waylandClient()) { - qCDebug(qLcInputMethod) << "focus sent to" << textInput; - textInput->sendEnter(focus); + qCDebug(lcWlInputMethod) << "focus sent to" << textInput; + if ((!textInput->seat() || textInput->seat() == d->seat) + && textInput->focusedSurface() != focus) { + textInput->sendEnter(focus); + } } } } - void WInputMethodHelper::connectToTI(WTextInput *ti) { - qCDebug(qLcInputMethod()) << "connect to text input" << ti; + qCDebug(lcWlInputMethod()) << "connect to text input" << ti; connect(ti, &WTextInput::enabled, this, &WInputMethodHelper::handleTIEnabled, Qt::UniqueConnection); connect(ti, &WTextInput::disabled, this, &WInputMethodHelper::handleTIDisabled, Qt::UniqueConnection); connect(ti, &WTextInput::requestLeave, ti, &WTextInput::sendLeave, Qt::UniqueConnection); @@ -324,7 +496,6 @@ void WInputMethodHelper::connectToTI(WTextInput *ti) void WInputMethodHelper::disableTI(WTextInput *ti) { Q_ASSERT(ti); - W_D(WInputMethodHelper); if (enabledTextInput() == ti) { // Should we consider the case when the same text input is disabled and then enabled at the same time. auto im = inputMethod(); @@ -339,7 +510,7 @@ void WInputMethodHelper::disableTI(WTextInput *ti) void WInputMethodHelper::handleNewTI(WTextInput *ti) { W_D(WInputMethodHelper); - qCDebug(qLcInputMethod()) << "handle new text input" << ti + qCDebug(lcWlInputMethod()) << "handle new text input" << ti << "from seat:" << ti->seat(); if (d->textInputs.contains(ti)) return; @@ -353,15 +524,19 @@ void WInputMethodHelper::handleNewTI(WTextInput *ti) // its requestFocus signal for it might request focus from another seat to activate // itself here. For example, text input v1. connect(ti, &WTextInput::requestFocus, this, [this, ti, d]{ - if (ti->seat() && d->seat->name() == ti->seat()->name()) { + if (ti->seat() && d->seat == ti->seat()) { connectToTI(ti); if (auto surface = d->seat->keyboardFocusSurface()) { ti->sendEnter(surface); } } }); - if (ti->seat() && d->seat->name() == ti->seat()->name()) { + if (ti->seat() && d->seat == ti->seat()) { connectToTI(ti); + if (auto *surface = d->seat->keyboardFocusSurface(); surface + && surface->waylandClient() == ti->waylandClient()) { + ti->sendEnter(surface); + } } } @@ -369,7 +544,6 @@ void WInputMethodHelper::handleTIEnabled() { WTextInput *ti = qobject_cast(sender()); Q_ASSERT(ti); - W_D(WInputMethodHelper); auto im = inputMethod(); auto activeTI = enabledTextInput(); if (activeTI == ti) @@ -387,6 +561,13 @@ void WInputMethodHelper::handleTIEnabled() // Try to activate input method. if (im) { im->sendActivate(); + if (ti->features().testFlag(IME::F_SurroundingText)) { + im->sendSurroundingText(ti->surroundingText(), ti->surroundingCursor(), ti->surroundingAnchor()); + } + im->sendTextChangeCause(ti->textChangeCause()); + if (ti->features().testFlag(IME::F_ContentType)) { + im->sendContentType(ti->contentHints().toInt(), ti->contentPurpose()); + } im->sendDone(); } } @@ -402,10 +583,10 @@ void WInputMethodHelper::handleFocusedTICommitted() auto ti = enabledTextInput(); Q_ASSERT(ti); if (!ti->focusedSurface()) { - qCWarning(qLcInputMethod) << "Discard commit to unfocused but not disabled text input."; + qCWarning(lcWlInputMethod) << "Discard commit to unfocused but not disabled text input."; return; } - qCDebug(qLcInputMethod) << "Focused text input" << ti << "committed." + qCDebug(lcWlInputMethod) << "Focused text input" << ti << "committed." << "Cursor rectangle:" << ti->cursorRect(); auto im = inputMethod(); if (im) { @@ -420,6 +601,7 @@ void WInputMethodHelper::handleFocusedTICommitted() im->sendDone(); } updateAllPopupSurfaces(ti->cursorRect()); + Q_EMIT textInputCursorRectChanged(ti->cursorRect()); } void WInputMethodHelper::handleIMCommitted() @@ -437,14 +619,16 @@ void WInputMethodHelper::handleActiveIMDestroyed() auto im = inputMethod(); Q_ASSERT(im); setInputMethod(nullptr); - im->safeDeleteLater(); + delete im; notifyLeave(); } void WInputMethodHelper::notifyLeave() { - if (auto ti = focusedTextInput()) { - ti->sendLeave(); + W_D(WInputMethodHelper); + for (auto *ti : std::as_const(d->textInputs)) { + if (ti->focusedSurface()) + ti->sendLeave(); } } diff --git a/waylib/src/server/protocols/winputmethodhelper.h b/waylib/src/server/protocols/winputmethodhelper.h index e6cbdff510..360e4882b3 100644 --- a/waylib/src/server/protocols/winputmethodhelper.h +++ b/waylib/src/server/protocols/winputmethodhelper.h @@ -1,57 +1,70 @@ -// Copyright (C) 2023 Yixue Wang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include "wglobal.h" -#include - #include Q_MOC_INCLUDE("winputpopupsurface.h") -QW_BEGIN_NAMESPACE -class qw_input_method_v2; -class qw_input_method_keyboard_grab_v2; -class qw_input_popup_surface_v2; -class qw_virtual_keyboard_v1; -QW_END_NAMESPACE -struct wlr_seat_keyboard_grab; -struct wlr_virtual_keyboard_v1; -struct wlr_keyboard_modifiers; WAYLIB_SERVER_BEGIN_NAMESPACE class WServer; class WSeat; class WInputDevice; class WInputMethodV2; class WInputMethodHelperPrivate; +class WInputMethodManagerV2; +class WTextInputManagerV1; +class WTextInputManagerV2; +class WTextInputManagerV3; +class WVirtualKeyboardManagerV1; class WInputPopupSurface; class WTextInput; +class WSurface; class WAYLIB_SERVER_EXPORT WInputMethodHelper : public QObject, public WObject { Q_OBJECT W_DECLARE_PRIVATE(WInputMethodHelper) public: - explicit WInputMethodHelper(WServer *server, WSeat *seat); + struct Protocols + { + WInputMethodManagerV2 *inputMethod = nullptr; + WTextInputManagerV1 *textInputV1 = nullptr; + WTextInputManagerV2 *textInputV2 = nullptr; + WTextInputManagerV3 *textInputV3 = nullptr; + WVirtualKeyboardManagerV1 *virtualKeyboard = nullptr; + }; + + explicit WInputMethodHelper(WServer *server, WSeat *seat, const Protocols &protocols); ~WInputMethodHelper() override; + WSurface *textInputFocusSurface() const; + QRect textInputCursorRect() const; + + // Returns true when the seat's current keyboard grab is the one installed by this helper. + bool isActiveKeyboardGrabOwner() const; + Q_SIGNALS: void inputPopupSurfaceV2Added(WInputPopupSurface *popupSurface); void inputPopupSurfaceV2Removed(WInputPopupSurface *popupSurface); + void textInputCursorRectChanged(QRect cursorRect); private: const QList &virtualKeyboards() const; void handleNewTI(WTextInput *ti); - void handleNewIMV2(QW_NAMESPACE::qw_input_method_v2 *imv2); - void handleNewKGV2(QW_NAMESPACE::qw_input_method_keyboard_grab_v2 *kgv2); - void handleNewIPSV2(QW_NAMESPACE::qw_input_popup_surface_v2 *ipsv2); + void handleNewIMV2(wlr_input_method_v2 *imv2); + void handleNewKGV2(wlr_input_method_keyboard_grab_v2 *kgv2); + void handleNewIPSV2(wlr_input_popup_surface_v2 *ipsv2); void handleNewVKV1(wlr_virtual_keyboard_v1 *vkv1); void updateAllPopupSurfaces(QRect cursorRect); void updatePopupSurface(WInputPopupSurface *popup, QRect cursorRect); void notifyLeave(); void resendKeyboardFocus(); + void handleKeyboardGrabBegin(); void connectToTI(WTextInput *ti); void disableTI(WTextInput *ti); void handleTIEnabled(); @@ -64,7 +77,7 @@ class WAYLIB_SERVER_EXPORT WInputMethodHelper : public QObject, public WObject void setEnabledTextInput(WTextInput *ti); WInputMethodV2 *inputMethod() const; void setInputMethod(WInputMethodV2 *im); - QW_NAMESPACE::qw_input_method_keyboard_grab_v2 *activeKeyboardGrab() const; + wlr_input_method_keyboard_grab_v2 *activeKeyboardGrab() const; friend void handleKey(struct wlr_seat_keyboard_grab *grab, uint32_t time_msec, uint32_t key, uint32_t state); friend void handleModifiers(struct wlr_seat_keyboard_grab *grab, const struct wlr_keyboard_modifiers *modifiers); }; diff --git a/waylib/src/server/protocols/winputpopupsurface.cpp b/waylib/src/server/protocols/winputpopupsurface.cpp index 7ec95be9a3..e6f6eb042b 100644 --- a/waylib/src/server/protocols/winputpopupsurface.cpp +++ b/waylib/src/server/protocols/winputpopupsurface.cpp @@ -1,59 +1,78 @@ -// Copyright (C) 2024 Yixue Wang . +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "winputpopupsurface.h" +#include "wscoplistener.h" #include "private/wtoplevelsurface_p.h" #include "wsurface.h" -#include -#include -#include +#include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WInputPopupSurfacePrivate : public WToplevelSurfacePrivate { public: W_DECLARE_PUBLIC(WInputPopupSurface) - explicit WInputPopupSurfacePrivate(qw_input_popup_surface_v2 *surface, WSurface *parentSurface, WInputPopupSurface *qq) + explicit WInputPopupSurfacePrivate(wlr_input_popup_surface_v2 *surface, WSurface *parentSurface, WInputPopupSurface *qq) : WToplevelSurfacePrivate(qq) , parent(parentSurface) , cursorRect() { - initHandle(surface); + Q_ASSERT(surface); + m_handle = surface; } - WWRAP_HANDLE_FUNCTIONS(qw_input_popup_surface_v2, wlr_input_popup_surface_v2) + inline wlr_input_popup_surface_v2 *handle() const { + return m_handle; + } QSize size() const { - return {handle()->handle()->surface->current.width, handle()->handle()->surface->current.height}; + return {m_handle->surface->current.width, m_handle->surface->current.height}; } wl_client *waylandClient() const override { - return nativeHandle()->resource->client; + return handle()->resource->client; } WSurface *const parent; QRect cursorRect; + +private: + // The input-method owner destroys this handle after notifying the + // wrapper. Keep the address stable through that callback. + wlr_input_popup_surface_v2 *m_handle = nullptr; + // Wrapper created on demand by surface(); released by the popup (owner + // rule) when the native surface dies. QPointer so the destructor never + // double-frees. + QPointer surface; }; -WInputPopupSurface::WInputPopupSurface(qw_input_popup_surface_v2 *surface, WSurface *parentSurface, QObject *parent) - : WToplevelSurface(*new WInputPopupSurfacePrivate(surface, parentSurface, this), parent) +WInputPopupSurface::WInputPopupSurface(wlr_input_popup_surface_v2 *surface, WSurface *parentSurface) + : WToplevelSurface(*new WInputPopupSurfacePrivate(surface, parentSurface, this)) { } +WInputPopupSurface::~WInputPopupSurface() +{ + teardown(); + W_D(WInputPopupSurface); + if (d->surface) + d->surface->removeListeners(const_cast(this)); + delete d->surface; +} + bool WInputPopupSurface::hasCapability(Capability cap) const { - W_DC(WInputPopupSurface); switch (cap) { using enum Capability; + case Resize: + return true; case Focus: case Activate: case Maximized: case FullScreen: - case Resize: return false; default: break; @@ -63,15 +82,25 @@ bool WInputPopupSurface::hasCapability(Capability cap) const WSurface *WInputPopupSurface::surface() const { - auto wSurface = WSurface::fromHandle(handle()->handle()->surface); + auto wSurface = WSurface::fromHandle(handle()->surface); if (!wSurface) { - wSurface = new WSurface(qw_surface::from(handle()->handle()->surface)); - connect(handle(), &qw_surface::before_destroy, wSurface, &WSurface::safeDeleteLater); + // The popup creates the surface, so it releases it when the native + // object dies (owner rule; no self-deletion in WSurface). + wSurface = new WSurface(handle()->surface); + auto *d = const_cast(d_func()); + auto *popup = const_cast(this); + wSurface->listeners(popup)->add(&wSurface->handle()->events.destroy, popup, + [d, popup, wSurface](void *) { + wSurface->removeListeners(popup); + delete d->surface; + d->surface = nullptr; + }); + d->surface = wSurface; } return wSurface; } -qw_input_popup_surface_v2 *WInputPopupSurface::handle() const +wlr_input_popup_surface_v2 *WInputPopupSurface::handle() const { return d_func()->handle(); } @@ -107,7 +136,8 @@ void WInputPopupSurface::sendCursorRect(QRect rect) if (d->cursorRect == rect) return; d->cursorRect = rect; - d->handle()->send_text_input_rectangle(qw_box(rect)); + wlr_box box{rect.x(), rect.y(), rect.width(), rect.height()}; + wlr_input_popup_surface_v2_send_text_input_rectangle(d->handle(), &box); Q_EMIT cursorRectChanged(); } diff --git a/waylib/src/server/protocols/winputpopupsurface.h b/waylib/src/server/protocols/winputpopupsurface.h index a05c007737..03a5d0c6c3 100644 --- a/waylib/src/server/protocols/winputpopupsurface.h +++ b/waylib/src/server/protocols/winputpopupsurface.h @@ -1,14 +1,11 @@ -// Copyright (C) 2024 Yixue Wang . +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include -QW_BEGIN_NAMESPACE -class qw_input_popup_surface_v2; -QW_END_NAMESPACE - WAYLIB_SERVER_BEGIN_NAMESPACE class WSurface; class WInputPopupSurfacePrivate; @@ -20,9 +17,10 @@ class WAYLIB_SERVER_EXPORT WInputPopupSurface : public WToplevelSurface QML_UNCREATABLE("Only created in C++") public: - WInputPopupSurface(QW_NAMESPACE::qw_input_popup_surface_v2 *surface, WSurface *parentSurface, QObject *parent = nullptr); + WInputPopupSurface(wlr_input_popup_surface_v2 *surface, WSurface *parentSurface); + ~WInputPopupSurface() override; WSurface *surface() const override; - QW_NAMESPACE::qw_input_popup_surface_v2 *handle() const; + wlr_input_popup_surface_v2 *handle() const; QRect getContentGeometry() const override; bool hasCapability(Capability cap) const override; bool isActivated() const override; @@ -37,6 +35,5 @@ public Q_SLOTS: bool checkNewSize(const QSize &size, QSize *clipedSize = nullptr) override; protected: - ~WInputPopupSurface() override = default; }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wlayershell.cpp b/waylib/src/server/protocols/wlayershell.cpp index 53ed1e8265..1157d24ad7 100644 --- a/waylib/src/server/protocols/wlayershell.cpp +++ b/waylib/src/server/protocols/wlayershell.cpp @@ -1,35 +1,32 @@ -// Copyright (C) 2023-2024 rewine . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wlayershell.h" #include "wlayersurface.h" #include "woutput.h" +#include "wscoplistener.h" +#include "wayliblogging.h" #include "private/wglobal_p.h" #include "wxdgshell.h" -#include -#include -#include +#include #include WAYLIB_SERVER_BEGIN_NAMESPACE -using QW_NAMESPACE::qw_layer_shell_v1; -using QW_NAMESPACE::qw_layer_surface_v1; - -class Q_DECL_HIDDEN WLayerShellPrivate : public WWrapObjectPrivate +class Q_DECL_HIDDEN WLayerShellPrivate : public WObjectPrivate { public: WLayerShellPrivate(WLayerShell *qq) - : WWrapObjectPrivate(qq) + : WObjectPrivate(qq) { } // begin slot function - void onNewSurface(qw_layer_surface_v1 *layerSurface); - void onSurfaceDestroy(qw_layer_surface_v1 *layerSurface); + void onNewSurface(wlr_layer_surface_v1 *layerSurface); + void onSurfaceDestroy(WLayerSurface *surface); // end slot function W_DECLARE_PUBLIC(WLayerShell) @@ -38,41 +35,44 @@ class Q_DECL_HIDDEN WLayerShellPrivate : public WWrapObjectPrivate QPointer xdgShell; }; -void WLayerShellPrivate::onNewSurface(qw_layer_surface_v1 *layerSurface) +void WLayerShellPrivate::onNewSurface(wlr_layer_surface_v1 *layerSurface) { W_Q(WLayerShell); - - auto server = q->server(); - auto surface = new WLayerSurface(layerSurface, server); - surface->setParent(server); - Q_ASSERT(surface->parent() == server); - - surface->safeConnect(&qw_layer_surface_v1::before_destroy, q, [this, layerSurface] { - onSurfaceDestroy(layerSurface); + auto surface = new WLayerSurface(layerSurface); + // Register the destroy/new_popup listeners on the surface wrapper + // (owner = this shell): each surface owns its own WScopedListenerList + // in WObject::attachedListenerLists, released automatically by ~WObject + // when the wrapper is deleted. + surface->listeners(q_ptr)->add(&layerSurface->events.destroy, this, + [this, surface] (void *) { + // Detach our own listener group: wlr_layer_surface destroy asserts + // the listener lists are empty after emitting. Safe from inside a + // callback of this list (the closure outlives the emission). + surface->removeListeners(q_ptr); + onSurfaceDestroy(surface); }); - surface->safeConnect(&qw_layer_surface_v1::notify_new_popup, q, [this] (wlr_xdg_popup *popup) { + surface->listeners(q_ptr)->add(&layerSurface->events.new_popup, this, + [this] (wlr_xdg_popup *popup) { if (xdgShell) xdgShell->initializeNewXdgPopupSurface(popup); else - qWarning() << "Xdg shell not set, will ignore the layer surface's popup request!"; + qCWarning(lcWlLayerShell) << "Xdg shell not set, will ignore the layer surface's popup request!"; }); - surfaceList.append(surface); Q_EMIT q->surfaceAdded(surface); } -void WLayerShellPrivate::onSurfaceDestroy(qw_layer_surface_v1 *layerSurface) +void WLayerShellPrivate::onSurfaceDestroy(WLayerSurface *surface) { - auto surface = WLayerSurface::fromHandle(layerSurface); - Q_ASSERT(surface); bool ok = surfaceList.removeOne(surface); Q_ASSERT(ok); Q_EMIT q_func()->surfaceRemoved(surface); - surface->safeDeleteLater(); + delete surface; } -WLayerShell::WLayerShell(WXdgShell *xdgshell, QObject *parent): - WWrapObject(*new WLayerShellPrivate(this), nullptr) +WLayerShell::WLayerShell(WXdgShell *xdgshell): + QObject(nullptr), + WObject(*new WLayerShellPrivate(this)) { W_D(WLayerShell); d->xdgShell = xdgshell; @@ -89,35 +89,44 @@ QByteArrayView WLayerShell::interfaceName() const return "zwlr_layer_shell_v1"; } +wlr_layer_shell_v1 *WLayerShell::handle() const +{ + return reinterpret_cast(m_handle); +} + void WLayerShell::create(WServer *server) { W_D(WLayerShell); - auto *layer_shell = qw_layer_shell_v1::create(*server->handle(), 4); - connect(layer_shell, &qw_layer_shell_v1::notify_new_surface, this, [d](wlr_layer_surface_v1 *surface) { - d->onNewSurface(qw_layer_surface_v1::from(surface)); - }); + auto *layer_shell = wlr_layer_shell_v1_create(server->handle(), InterfaceVersion); + Q_ASSERT(layer_shell); + listeners()->add(&layer_shell->events.new_surface, d, + &WLayerShellPrivate::onNewSurface); m_handle = layer_shell; } -void WLayerShell::destroy(WServer *server) +void WLayerShell::destroy([[maybe_unused]] WServer *server) { - Q_UNUSED(server); W_D(WLayerShell); auto list = d->surfaceList; d->surfaceList.clear(); - for (auto surface : std::as_const(list)) { - surfaceRemoved(surface); - surface->safeDeleteLater(); + Q_EMIT surfaceRemoved(surface); + delete surface; } + if (ownsSocket() && m_handle) + wlr_layer_shell_v1_destroy(nativeInterface(), false); + + m_handle = nullptr; } wl_global *WLayerShell::global() const { - auto handle = nativeInterface(); - return handle->handle()->global; + if (!m_handle) + return nullptr; + auto handle = reinterpret_cast(m_handle); + return handle->global; } WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wlayershell.h b/waylib/src/server/protocols/wlayershell.h index 75a8e4154b..3c168186fd 100644 --- a/waylib/src/server/protocols/wlayershell.h +++ b/waylib/src/server/protocols/wlayershell.h @@ -1,4 +1,4 @@ -// Copyright (C) 2023-2024 rewine . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once @@ -9,23 +9,27 @@ #include +Q_MOC_INCLUDE("wlayersurface.h") + WAYLIB_SERVER_BEGIN_NAMESPACE class WXdgShell; class WLayerSurface; class WLayerShellPrivate; -class WAYLIB_SERVER_EXPORT WLayerShell: public WWrapObject, public WServerInterface +class WAYLIB_SERVER_EXPORT WLayerShell: public QObject, public WObject, public WServerInterface { Q_OBJECT W_DECLARE_PRIVATE(WLayerShell) public: - explicit WLayerShell(WXdgShell *xdgShell, QObject *parent = nullptr); + explicit WLayerShell(WXdgShell *xdgShell); void *create(); + wlr_layer_shell_v1 *handle() const; QVector surfaceList() const; QByteArrayView interfaceName() const override; + static constexpr int InterfaceVersion = 5; Q_SIGNALS: void surfaceAdded(WLayerSurface *surface); void surfaceRemoved(WLayerSurface *surface); diff --git a/waylib/src/server/protocols/wlayersurface.cpp b/waylib/src/server/protocols/wlayersurface.cpp index 47deb58af7..881b47a1a3 100644 --- a/waylib/src/server/protocols/wlayersurface.cpp +++ b/waylib/src/server/protocols/wlayersurface.cpp @@ -1,31 +1,31 @@ -// Copyright (C) 2023 rewine . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wlayersurface.h" #include "wseat.h" #include "wsurface.h" #include "woutput.h" +#include "wscoplistener.h" +#include "wayliblogging.h" #include "private/wtoplevelsurface_p.h" -#include -#include -#include -#include +#include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WLayerSurfacePrivate : public WToplevelSurfacePrivate { public: - WLayerSurfacePrivate(WLayerSurface *qq, qw_layer_surface_v1 *handle); + WLayerSurfacePrivate(WLayerSurface *qq, wlr_layer_surface_v1 *handle); ~WLayerSurfacePrivate(); - WWRAP_HANDLE_FUNCTIONS(qw_layer_surface_v1, wlr_layer_surface_v1) + inline wlr_layer_surface_v1 *handle() const { + return m_handle; + } - wl_client *waylandClient() const { - return nativeHandle()->resource->client; + wl_client *waylandClient() const override { + return handle()->resource->client; } // begin slot function @@ -34,7 +34,6 @@ class Q_DECL_HIDDEN WLayerSurfacePrivate : public WToplevelSurfacePrivate { void init(); void connect(); - void instantRelease(); bool setDesiredSize(QSize newSize); bool setLayer(WLayerSurface::LayerType layer); @@ -57,12 +56,19 @@ class Q_DECL_HIDDEN WLayerSurfacePrivate : public WToplevelSurfacePrivate { int32_t exclusiveZone = 0; WLayerSurface::KeyboardInteractivity keyboardInteractivity = WLayerSurface::KeyboardInteractivity::None; WOutput *output = nullptr; + +private: + // The layer-shell owner destroys this handle after notifying the + // wrapper. Keep the address stable through that callback. + wlr_layer_surface_v1 *m_handle = nullptr; }; -WLayerSurfacePrivate::WLayerSurfacePrivate(WLayerSurface *qq, qw_layer_surface_v1 *hh) +WLayerSurfacePrivate::WLayerSurfacePrivate(WLayerSurface *qq, wlr_layer_surface_v1 *hh) : WToplevelSurfacePrivate(qq) { - initHandle(hh); + Q_ASSERT(hh); + hh->data = qq; + m_handle = hh; } WLayerSurfacePrivate::~WLayerSurfacePrivate() @@ -70,31 +76,14 @@ WLayerSurfacePrivate::~WLayerSurfacePrivate() } -void WLayerSurfacePrivate::instantRelease() -{ - W_Q(WLayerSurface); - handle()->set_data(nullptr, nullptr); - handle()->disconnect(q); - auto qsurface = qw_surface::from((*handle())->surface); - qsurface->disconnect(q); - - if (!surface) - return; - surface->safeDeleteLater(); - surface = nullptr; -} - void WLayerSurfacePrivate::init() { W_Q(WLayerSurface); - handle()->set_data(this, q); - Q_ASSERT(!q->surface()); - auto qsurface = qw_surface::from((*handle())->surface); - surface = new WSurface(qsurface, q); + surface = new WSurface(m_handle->surface); surface->setAttachedData(q); updateLayerProperty(); - output = nativeHandle()->output ? WOutput::fromHandle(qw_output::from(nativeHandle()->output)) : nullptr; + output = handle()->output ? WOutput::fromHandle(handle()->output) : nullptr; connect(); } @@ -102,15 +91,13 @@ void WLayerSurfacePrivate::init() void WLayerSurfacePrivate::connect() { W_Q(WLayerSurface); - - surface->safeConnect(&qw_surface::notify_commit, q, [this] () { - updateLayerProperty(); - }); + q->listeners()->add(&m_handle->surface->events.commit, this, + &WLayerSurfacePrivate::updateLayerProperty); } -static inline void debugOutput(wlr_layer_surface_v1_state s) +[[maybe_unused]] static inline void debugOutput(wlr_layer_surface_v1_state s) { - qDebug() << "committed: " << s.committed << " " + qCDebug(lcWlLayerSurface) << "committed: " << s.committed << " " << "configure_serial: " << s.configure_serial << "\n" << "anchor: " << s.anchor << " " << "layer: " << s.layer << " " @@ -125,7 +112,7 @@ void WLayerSurfacePrivate::updateLayerProperty() { W_Q(WLayerSurface); - wlr_layer_surface_v1_state state = q->nativeHandle()->current; + wlr_layer_surface_v1_state state = q->handle()->current; int hasChange = false; hasChange |= setDesiredSize(QSize(state.desired_width, state.desired_height)); @@ -155,7 +142,6 @@ bool WLayerSurfacePrivate::setDesiredSize(QSize newSize) return true; } - bool WLayerSurfacePrivate::setLayer(WLayerSurface::LayerType layer) { W_Q(WLayerSurface); @@ -238,15 +224,26 @@ bool WLayerSurfacePrivate::setKeyboardInteractivity(WLayerSurface::KeyboardInter // end set property -WLayerSurface::WLayerSurface(qw_layer_surface_v1 *handle, QObject *parent) - : WToplevelSurface(*new WLayerSurfacePrivate(this, handle), parent) +WLayerSurface::WLayerSurface(wlr_layer_surface_v1 *handle) + : WToplevelSurface(*new WLayerSurfacePrivate(this, handle)) { d_func()->init(); } WLayerSurface::~WLayerSurface() { - + teardown(); + // Notify listeners while the object is still usable (its members are + // alive during the destructor body). + Q_EMIT beforeDestroy(); + // Owner rule: this object created the WSurface wrapper, release it. + W_D(WLayerSurface); + // Clear the reverse fromHandle() mapping. The shell destroys this + // wrapper from the layer surface's destroy callback (or while the + // native handle is still alive), so the handle is valid here. + if (d->m_handle && d->m_handle->data == this) + d->m_handle->data = nullptr; + delete d->surface; } bool WLayerSurface::hasCapability(Capability cap) const @@ -268,37 +265,30 @@ bool WLayerSurface::hasCapability(Capability cap) const Q_UNREACHABLE(); } - WSurface *WLayerSurface::surface() const { W_D(const WLayerSurface); return d->surface; } -qw_layer_surface_v1 *WLayerSurface::handle() const +wlr_layer_surface_v1 *WLayerSurface::handle() const { W_DC(WLayerSurface); return d->handle(); } -wlr_layer_surface_v1 *WLayerSurface::nativeHandle() const -{ - W_D(const WLayerSurface); - return d->nativeHandle(); -} - -qw_surface *WLayerSurface::inputTargetAt(QPointF &localPos) const +wlr_surface *WLayerSurface::inputTargetAt(QPointF &localPos) const { W_DC(WLayerSurface); // find a wlr_suface object who can receive the events const QPointF pos = localPos; - auto sur = d->handle()->surface_at(pos.x(), pos.y(), &localPos.rx(), &localPos.ry()); - return sur ? qw_surface::from(sur) : nullptr; + auto sur = wlr_layer_surface_v1_surface_at(d->handle(), pos.x(), pos.y(), &localPos.rx(), &localPos.ry()); + return sur; } -WLayerSurface *WLayerSurface::fromHandle(qw_layer_surface_v1 *handle) +WLayerSurface *WLayerSurface::fromHandle(wlr_layer_surface_v1 *handle) { - return handle->get_data(); + return static_cast(handle->data); } WLayerSurface *WLayerSurface::fromSurface(WSurface *surface) @@ -309,7 +299,7 @@ WLayerSurface *WLayerSurface::fromSurface(WSurface *surface) QRect WLayerSurface::getContentGeometry() const { W_DC(WLayerSurface); - return QRect(0, 0, d->nativeHandle()->current.actual_width, d->nativeHandle()->current.actual_height); + return QRect(0, 0, d->handle()->current.actual_width, d->handle()->current.actual_height); } int WLayerSurface::keyboardFocusPriority() const @@ -331,11 +321,21 @@ int WLayerSurface::keyboardFocusPriority() const return 0; } +bool WLayerSurface::isInitialized() const +{ + return handle()->initialized; +} + void WLayerSurface::resize(const QSize &size) { configureSize(size); } +void WLayerSurface::close() +{ + closed(); +} + QSize WLayerSurface::desiredSize() const { W_DC(WLayerSurface); @@ -392,7 +392,7 @@ WLayerSurface::KeyboardInteractivity WLayerSurface::keyboardInteractivity() cons QString WLayerSurface::scope() const { - return QString::fromLocal8Bit((*handle())->scope); + return QString::fromLocal8Bit(handle()->scope); } WOutput *WLayerSurface::output() const @@ -420,20 +420,18 @@ WLayerSurface::AnchorType WLayerSurface::getExclusiveZoneEdge() const uint32_t WLayerSurface::configureSize(const QSize &newSize) { - return handle()->configure(newSize.width(), newSize.height()); + return wlr_layer_surface_v1_configure(handle(), newSize.width(), newSize.height()); } void WLayerSurface::closed() { // 1. Notify the client that the surface has been closed // 2. Destroy the struct wlr_layer_surface_v1 - wlr_layer_surface_v1_destroy(nativeHandle()); + wlr_layer_surface_v1_destroy(handle()); } bool WLayerSurface::checkNewSize(const QSize &size, QSize *clipedSize) { - W_D(WLayerSurface); - // If the width or height arguments are zero, it means the client should decide its own window dimension. if (size.width() < 0 || size.height() < 0) { if (clipedSize) diff --git a/waylib/src/server/protocols/wlayersurface.h b/waylib/src/server/protocols/wlayersurface.h index 1fa638cd06..9583ac3f3d 100644 --- a/waylib/src/server/protocols/wlayersurface.h +++ b/waylib/src/server/protocols/wlayersurface.h @@ -1,19 +1,13 @@ -// Copyright (C) 2023 rewine . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include #include #include -struct wlr_layer_surface_v1; - -QW_BEGIN_NAMESPACE -class qw_surface; -class qw_layer_surface_v1; -QW_END_NAMESPACE - WAYLIB_SERVER_BEGIN_NAMESPACE class WSeat; @@ -42,7 +36,7 @@ class WAYLIB_SERVER_EXPORT WLayerSurface : public WToplevelSurface Q_CLASSINFO("RegisterEnumClassesUnscoped", "false") public: - explicit WLayerSurface(QW_NAMESPACE::qw_layer_surface_v1 *handle, QObject *parent = nullptr); + explicit WLayerSurface(wlr_layer_surface_v1 *handle); ~WLayerSurface(); enum class LayerType { @@ -72,16 +66,17 @@ class WAYLIB_SERVER_EXPORT WLayerSurface : public WToplevelSurface bool hasCapability(Capability cap) const override; WSurface *surface() const override; - QW_NAMESPACE::qw_layer_surface_v1 *handle() const; - wlr_layer_surface_v1 *nativeHandle() const; - QW_NAMESPACE::qw_surface *inputTargetAt(QPointF &localPos) const; + wlr_layer_surface_v1 *handle() const; + wlr_surface *inputTargetAt(QPointF &localPos) const; - static WLayerSurface *fromHandle(QW_NAMESPACE::qw_layer_surface_v1 *handle); + static WLayerSurface *fromHandle(wlr_layer_surface_v1 *handle); static WLayerSurface *fromSurface(WSurface *surface); QRect getContentGeometry() const override; int keyboardFocusPriority() const override; + bool isInitialized() const override; void resize(const QSize &size) override; + void close() override; // layer shell info QSize desiredSize() const; diff --git a/waylib/src/server/protocols/woutputmanagerv1.cpp b/waylib/src/server/protocols/woutputmanagerv1.cpp index ba43af63ab..5146b24ce1 100644 --- a/waylib/src/server/protocols/woutputmanagerv1.cpp +++ b/waylib/src/server/protocols/woutputmanagerv1.cpp @@ -1,19 +1,42 @@ -// Copyright (C) 2023 rewine . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "woutputmanagerv1.h" -#include "woutputitem.h" +#include "wscoplistener.h" #include "private/wglobal_p.h" +#include "wayliblogging.h" -#include -#include -#include +#include + +#include +#include +#include WAYLIB_SERVER_BEGIN_NAMESPACE -using QW_NAMESPACE::qw_output_manager_v1; -using QW_NAMESPACE::qw_output_configuration_v1; -using QW_NAMESPACE::qw_output_configuration_head_v1; +namespace { + +WOutputState outputState(WOutput *output) +{ + const auto *wlrOutput = output->handle(); + const QPoint position = output->position(); + + return { + .output = output, + .enabled = wlrOutput->enabled, + .mode = wlrOutput->current_mode, + .x = position.x(), + .y = position.y(), + .customModeSize = { wlrOutput->width, wlrOutput->height }, + .customModeRefresh = wlrOutput->refresh, + .transform = static_cast(wlrOutput->transform), + .scale = wlrOutput->scale, + .adaptiveSyncEnabled = + wlrOutput->adaptive_sync_status == WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED + }; +} + +} class Q_DECL_HIDDEN WOutputManagerV1Private : public WObjectPrivate { @@ -26,20 +49,17 @@ class Q_DECL_HIDDEN WOutputManagerV1Private : public WObjectPrivate W_DECLARE_PUBLIC(WOutputManagerV1) - void outputMgrApplyOrTest(qw_output_configuration_v1 *config, int test); - inline qw_output_manager_v1 *handle() const { - return q_func()->nativeInterface(); + void outputMgrApplyOrTest(wlr_output_configuration_v1 *config, int test); + inline wlr_output_manager_v1 *handle() const { + return reinterpret_cast(q_func()->m_handle); } - inline wlr_output_manager_v1 *nativeHandle() const { - Q_ASSERT(handle()); - return handle()->handle(); - } - - qw_output_manager_v1 *manager { nullptr }; + wlr_output_manager_v1 *manager { nullptr }; QPointer backend; QList stateList; - QList stateListPending; + QList> observedOutputs; + QHash> pendingStateLists; + wlr_output_configuration_v1 *currentPendingConfig { nullptr }; }; WOutputManagerV1::WOutputManagerV1() @@ -48,20 +68,20 @@ WOutputManagerV1::WOutputManagerV1() } -void WOutputManagerV1Private::outputMgrApplyOrTest(qw_output_configuration_v1 *config, int onlyTest) +void WOutputManagerV1Private::outputMgrApplyOrTest(wlr_output_configuration_v1 *config, int onlyTest) { W_Q(WOutputManagerV1); wlr_output_configuration_head_v1 *config_head; - stateListPending.clear(); + QList pendingStates; - wl_list_for_each(config_head, &config->handle()->heads, link) { - auto *output = QW_NAMESPACE::qw_output::from(config_head->state.output); + wl_list_for_each(config_head, &config->heads, link) { + auto *output = config_head->state.output; auto *woutput = WOutput::fromHandle(output); const auto &state = config_head->state; - stateListPending.append(WOutputState { + pendingStates.append(WOutputState { .output = woutput, .enabled = state.enabled, .mode = state.mode, @@ -75,73 +95,150 @@ void WOutputManagerV1Private::outputMgrApplyOrTest(qw_output_configuration_v1 *c }); } + currentPendingConfig = config; + pendingStateLists.insert(config, std::move(pendingStates)); Q_EMIT q->requestTestOrApply(config, onlyTest); } -const QList &WOutputManagerV1::stateListPending() +QList WOutputManagerV1::stateListPending(wlr_output_configuration_v1 *config) const { - W_D(WOutputManagerV1); - return d->stateListPending; + W_D(const WOutputManagerV1); + return d->pendingStateLists.value(config ? config : d->currentPendingConfig); } void WOutputManagerV1::updateConfig() { W_D(WOutputManagerV1); - auto *config = qw_output_configuration_v1::create(); - + QSet outputs; + d->stateList.removeIf([&outputs](const WOutputState &state) { + if (outputs.contains(state.output)) + return true; + outputs.insert(state.output); + return false; + }); + auto *config = wlr_output_configuration_v1_create(); for (const WOutputState &state : std::as_const(d->stateList)) { - auto *configHead = qw_output_configuration_head_v1::create(*config, state.output->nativeHandle()); - configHead->handle()->state.scale = state.scale; - configHead->handle()->state.transform = static_cast(state.transform); - configHead->handle()->state.x = state.x; - configHead->handle()->state.y = state.y; + auto *wlr_output = state.output->handle(); + auto *configHead = wlr_output_configuration_head_v1_create(config, wlr_output); + auto *handle = &configHead->state; + + handle->enabled = state.enabled; + handle->x = state.x; + handle->y = state.y; + + if (state.enabled) { + handle->mode = state.mode; + handle->scale = state.scale; + handle->transform = static_cast(state.transform); + handle->adaptive_sync_enabled = state.adaptiveSyncEnabled; + + if (state.customModeSize.width() > 0 && state.customModeSize.height() > 0) { + handle->custom_mode.width = state.customModeSize.width(); + handle->custom_mode.height = state.customModeSize.height(); + handle->custom_mode.refresh = state.customModeRefresh; + } + } } - d->manager->set_configuration(*config); + wlr_output_manager_v1_set_configuration(d->manager, config); +} + +void WOutputManagerV1::sendTestResult(wlr_output_configuration_v1 *config, bool ok) +{ + W_D(WOutputManagerV1); + + sendResult(config, ok, d->stateList); +} + +void WOutputManagerV1::sendResult(wlr_output_configuration_v1 *config, bool ok) +{ + W_D(WOutputManagerV1); + sendResult(config, ok, d->pendingStateLists.value(config)); } -void WOutputManagerV1::sendResult(qw_output_configuration_v1 *config, bool ok) +void WOutputManagerV1::sendResult(wlr_output_configuration_v1 *config, + bool ok, + const QList &appliedStates) { W_D(WOutputManagerV1); - if (ok) - config->send_succeeded(); - else - config->send_failed(); - delete config; - - if (ok) - d->stateList.swap(d->stateListPending); - d->stateListPending.clear(); + + // Only a pending config is ours to answer and destroy: the first answer + // already freed it. A duplicated or late answer must not free it again. + if (!d->pendingStateLists.contains(config)) { + qCWarning(lcWlOutput) << "Ignored a result for a configuration that is not pending" + " (already answered, or not created from an apply/test request):" + << config; + return; + } + + d->pendingStateLists.remove(config); + if (d->currentPendingConfig == config) + d->currentPendingConfig = nullptr; + + if (ok) { + wlr_output_configuration_v1_send_succeeded(config); + d->stateList = appliedStates; + } else { + wlr_output_configuration_v1_send_failed(config); + } + + wlr_output_configuration_v1_destroy(config); + + // Schedule updateConfig through the event loop to avoid recursion + QMetaObject::invokeMethod(this, &WOutputManagerV1::updateConfig, Qt::QueuedConnection); +} + +void WOutputManagerV1::setOutputStates(const QList &states) +{ + W_D(WOutputManagerV1); + for (const auto &output : std::as_const(d->observedOutputs)) { + if (output) + disconnect(output, nullptr, this, nullptr); + } + d->observedOutputs.clear(); + d->stateList = states; updateConfig(); } void WOutputManagerV1::newOutput(WOutput *output) { W_D(WOutputManagerV1); - const auto *wlr_output = output->nativeHandle(); + if (std::any_of(d->stateList.cbegin(), d->stateList.cend(), + [output](const WOutputState &state) { return state.output == output; })) + return; + d->stateList.append(outputState(output)); + d->observedOutputs.append(output); + connect(output, &QObject::destroyed, this, [this, output] { removeOutput(output); }); + connect(output, &WOutput::enabledChanged, + this, &WOutputManagerV1::syncOutputStates); + connect(output, &WOutput::positionChanged, + this, &WOutputManagerV1::syncOutputStates); + connect(output, &WOutput::modeChanged, + this, &WOutputManagerV1::syncOutputStates); + connect(output, &WOutput::orientationChanged, + this, &WOutputManagerV1::syncOutputStates); + connect(output, &WOutput::scaleChanged, + this, &WOutputManagerV1::syncOutputStates); + connect(output, &WOutput::adaptiveSyncEnabledChanged, + this, &WOutputManagerV1::syncOutputStates); + updateConfig(); +} - auto outputItem = WOutputItem::getOutputItem(output); +void WOutputManagerV1::syncOutputStates() +{ + W_D(WOutputManagerV1); + for (auto &state : d->stateList) + state = outputState(state.output); - WOutputState state { - .output = output, - .enabled = wlr_output->enabled, - .mode = wlr_output->current_mode, - .x = outputItem ? static_cast(outputItem->x()) : 0, - .y = outputItem ? static_cast(outputItem->y()) : 0, - .customModeSize = { wlr_output->width, wlr_output->height }, - .customModeRefresh = wlr_output->refresh, - .transform = static_cast(wlr_output->transform), - .scale = wlr_output->scale, - .adaptiveSyncEnabled = (wlr_output->adaptive_sync_status == WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED) - }; - d->stateList.append(state); updateConfig(); } void WOutputManagerV1::removeOutput(WOutput *output) { W_D(WOutputManagerV1); + disconnect(output, nullptr, this, nullptr); + d->observedOutputs.removeIf([output](const auto &entry) { return !entry || entry == output; }); d->stateList.removeIf([output](const WOutputState &s) { return s.output == output; }); @@ -149,37 +246,47 @@ void WOutputManagerV1::removeOutput(WOutput *output) updateConfig(); } -qw_output_manager_v1 *WOutputManagerV1::handle() const +wlr_output_manager_v1 *WOutputManagerV1::handle() const { - return nativeInterface(); + return reinterpret_cast(m_handle); } QByteArrayView WOutputManagerV1::interfaceName() const { - return "zwlr_output_head_v1"; + return "zwlr_output_manager_v1"; } void WOutputManagerV1::create(WServer *server) { W_D(WOutputManagerV1); - d->manager = qw_output_manager_v1::create(*server->handle()); - connect(d->manager, &qw_output_manager_v1::notify_test, this, [d](wlr_output_configuration_v1 *config) { - d->outputMgrApplyOrTest(qw_output_configuration_v1::from(config), true); + d->manager = wlr_output_manager_v1_create(server->handle()); + m_handle = d->manager; + listeners()->add(&d->manager->events.test, this, + [d] (wlr_output_configuration_v1 *config) { + d->outputMgrApplyOrTest(config, true); }); - connect(d->manager, &qw_output_manager_v1::notify_apply, this, [d](wlr_output_configuration_v1 *config) { - d->outputMgrApplyOrTest(qw_output_configuration_v1::from(config), false); + listeners()->add(&d->manager->events.apply, this, + [d] (wlr_output_configuration_v1 *config) { + d->outputMgrApplyOrTest(config, false); }); } +void WOutputManagerV1::destroy([[maybe_unused]] WServer *server) +{ + if (ownsSocket() && m_handle) + wlr_output_manager_v1_destroy(nativeInterface(), false); + + m_handle = nullptr; +} + wl_global *WOutputManagerV1::global() const { W_D(const WOutputManagerV1); if (m_handle) - return d->nativeHandle()->global; - + return d->handle()->global; return nullptr; } diff --git a/waylib/src/server/protocols/woutputmanagerv1.h b/waylib/src/server/protocols/woutputmanagerv1.h index 987c31b32f..97bffc97a0 100644 --- a/waylib/src/server/protocols/woutputmanagerv1.h +++ b/waylib/src/server/protocols/woutputmanagerv1.h @@ -1,18 +1,15 @@ -// Copyright (C) 2023 rewine . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include #include #include - -QW_BEGIN_NAMESPACE -class qw_output_manager_v1; -class qw_output_configuration_v1; -QW_END_NAMESPACE +#include WAYLIB_SERVER_BEGIN_NAMESPACE @@ -50,23 +47,36 @@ class WAYLIB_SERVER_EXPORT WOutputManagerV1: public QObject, public WObject, pu public: explicit WOutputManagerV1(); - const QList &stateListPending(); + QList stateListPending( + wlr_output_configuration_v1 *config = nullptr) const; - void sendResult(QW_NAMESPACE::qw_output_configuration_v1 *config, bool ok); + // Answers and destroys a configuration created by an apply/test request. + // Configurations that are not pending any more (already answered) are + // ignored, so the same config is never destroyed twice. + void sendResult(wlr_output_configuration_v1 *config, bool ok); + void sendTestResult(wlr_output_configuration_v1 *config, bool ok); + void sendResult(wlr_output_configuration_v1 *config, + bool ok, + const QList &appliedStates); + void setOutputStates(const QList &states); void newOutput(WOutput *output); void removeOutput(WOutput *output); - QW_NAMESPACE::qw_output_manager_v1 *handle() const; + wlr_output_manager_v1 *handle() const; QByteArrayView interfaceName() const override; Q_SIGNALS: - void requestTestOrApply(QW_NAMESPACE::qw_output_configuration_v1 *config, bool onlyTest); + void requestTestOrApply(wlr_output_configuration_v1 *config, bool onlyTest); protected: void create(WServer *server) override; + void destroy(WServer *server) override; wl_global *global() const override; private: + void syncOutputStates(); void updateConfig(); }; WAYLIB_SERVER_END_NAMESPACE + +Q_DECLARE_OPAQUE_POINTER(wlr_output_mode*) diff --git a/waylib/src/server/protocols/wpointerconstraintsv1.cpp b/waylib/src/server/protocols/wpointerconstraintsv1.cpp new file mode 100644 index 0000000000..3fe2ab8dbc --- /dev/null +++ b/waylib/src/server/protocols/wpointerconstraintsv1.cpp @@ -0,0 +1,79 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wpointerconstraintsv1.h" +#include "private/wglobal_p.h" +#include "wscoplistener.h" + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class Q_DECL_HIDDEN WPointerConstraintsV1Private : public WObjectPrivate +{ +public: + WPointerConstraintsV1Private(WPointerConstraintsV1 *qq) + : WObjectPrivate(qq) + { + } + + inline wlr_pointer_constraints_v1 *handle() const { + return reinterpret_cast(q_func()->m_handle); + } + + W_DECLARE_PUBLIC(WPointerConstraintsV1) +}; + +WPointerConstraintsV1::WPointerConstraintsV1() + : WObject(*new WPointerConstraintsV1Private(this)) +{ +} + +wlr_pointer_constraints_v1 *WPointerConstraintsV1::handle() const +{ + return reinterpret_cast(m_handle); +} + +QByteArrayView WPointerConstraintsV1::interfaceName() const +{ + return "zwp_pointer_constraints_v1"; +} + +wlr_pointer_constraint_v1 *WPointerConstraintsV1::constraintForSurface(wlr_surface *surface, + wlr_seat *seat) const +{ + if (!m_handle) + return nullptr; + + return wlr_pointer_constraints_v1_constraint_for_surface(handle(), surface, seat); +} + +void WPointerConstraintsV1::create(WServer *server) +{ + if (!m_handle) { + m_handle = wlr_pointer_constraints_v1_create(server->handle()); + listeners()->add(&handle()->events.new_constraint, this, + [this](wlr_pointer_constraint_v1 *constraint) { + Q_EMIT newConstraint(constraint); + }); + } +} + +void WPointerConstraintsV1::destroy(WServer *) +{ + if (ownsSocket() && m_handle) + wlr_pointer_constraints_v1_destroy(nativeInterface(), false); + + m_handle = nullptr; +} + +wl_global *WPointerConstraintsV1::global() const +{ + W_D(const WPointerConstraintsV1); + if (m_handle) + return d->handle()->global; + + return nullptr; +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wpointerconstraintsv1.h b/waylib/src/server/protocols/wpointerconstraintsv1.h new file mode 100644 index 0000000000..b345d2fcb1 --- /dev/null +++ b/waylib/src/server/protocols/wpointerconstraintsv1.h @@ -0,0 +1,47 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WPointerConstraintsV1Private; + +// Wayland `zwp_pointer_constraints_v1` wrapper. Creates the wlroots global and +// forwards `new_constraint` to the compositor (treeland) policy layer, which +// decides when to activate/deactivate each constraint. The enforcement itself +// (locked relative motion / confined region clamping) lives in WCursorPrivate. +class WAYLIB_SERVER_EXPORT WPointerConstraintsV1 + : public QObject, public WObject, public WServerInterface +{ + Q_OBJECT + W_DECLARE_PRIVATE(WPointerConstraintsV1) + +public: + explicit WPointerConstraintsV1(); + + QByteArrayView interfaceName() const override; + + // Returns the active constraint for (surface, seat), or nullptr. + wlr_pointer_constraint_v1 *constraintForSurface(wlr_surface *surface, + wlr_seat *seat) const; + +Q_SIGNALS: + // Emitted by wlroots whenever a client creates a new locked/confined + // pointer constraint. The compositor owns the activation policy. + void newConstraint(wlr_pointer_constraint_v1 *constraint); + +protected: + wlr_pointer_constraints_v1 *handle() const; + + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wpointergesturesv1.cpp b/waylib/src/server/protocols/wpointergesturesv1.cpp new file mode 100644 index 0000000000..2408279a29 --- /dev/null +++ b/waylib/src/server/protocols/wpointergesturesv1.cpp @@ -0,0 +1,39 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wpointergesturesv1.h" + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +wlr_pointer_gestures_v1 *WPointerGesturesV1::handle() const +{ + return nativeInterface(); +} + +QByteArrayView WPointerGesturesV1::interfaceName() const +{ + return "zwp_pointer_gestures_v1"; +} + +void WPointerGesturesV1::create(WServer *server) +{ + if (!qEnvironmentVariableIsSet("WAYLIB_DISABLE_GESTURE")) + m_handle = wlr_pointer_gestures_v1_create(server->handle()); +} + +void WPointerGesturesV1::destroy(WServer *) +{ + if (ownsSocket() && m_handle) + wlr_pointer_gestures_v1_destroy(nativeInterface(), false); + + m_handle = nullptr; +} + +wl_global *WPointerGesturesV1::global() const +{ + return handle() ? handle()->global : nullptr; +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wpointergesturesv1.h b/waylib/src/server/protocols/wpointergesturesv1.h new file mode 100644 index 0000000000..1f8c7b3084 --- /dev/null +++ b/waylib/src/server/protocols/wpointergesturesv1.h @@ -0,0 +1,27 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include + +struct wlr_pointer_gestures_v1; + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WAYLIB_SERVER_EXPORT WPointerGesturesV1 : public QObject, public WServerInterface +{ + Q_OBJECT +public: + wlr_pointer_gestures_v1 *handle() const; + QByteArrayView interfaceName() const override; + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wrelativepointermanagerv1.cpp b/waylib/src/server/protocols/wrelativepointermanagerv1.cpp new file mode 100644 index 0000000000..303ba7fac1 --- /dev/null +++ b/waylib/src/server/protocols/wrelativepointermanagerv1.cpp @@ -0,0 +1,80 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wrelativepointermanagerv1.h" + +#include "wseat.h" + +#include "private/wglobal_p.h" + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class Q_DECL_HIDDEN WRelativePointerManagerV1Private : public WObjectPrivate +{ +public: + explicit WRelativePointerManagerV1Private(WRelativePointerManagerV1 *qq) + : WObjectPrivate(qq) + { + } + + inline wlr_relative_pointer_manager_v1 *handle() const + { + return reinterpret_cast(q_func()->m_handle); + } + + W_DECLARE_PUBLIC(WRelativePointerManagerV1) +}; + +WRelativePointerManagerV1::WRelativePointerManagerV1() + : WObject(*new WRelativePointerManagerV1Private(this)) +{ +} + +wlr_relative_pointer_manager_v1 *WRelativePointerManagerV1::handle() const +{ + return reinterpret_cast(m_handle); +} + +void WRelativePointerManagerV1::sendRelativeMotion(WSeat *seat, uint32_t timeMsec, + const QPointF &delta, + const QPointF &unacceleratedDelta) +{ + if (!seat || !seat->handle() || !handle()) + return; + + wlr_relative_pointer_manager_v1_send_relative_motion( + handle(), seat->handle(), uint64_t(timeMsec) * 1000, + delta.x(), delta.y(), unacceleratedDelta.x(), unacceleratedDelta.y()); +} + +QByteArrayView WRelativePointerManagerV1::interfaceName() const +{ + return "zwp_relative_pointer_manager_v1"; +} + +void WRelativePointerManagerV1::create(WServer *server) +{ + if (!m_handle) + m_handle = wlr_relative_pointer_manager_v1_create(server->handle()); +} + +void WRelativePointerManagerV1::destroy([[maybe_unused]] WServer *server) +{ + if (ownsSocket() && m_handle) + wlr_relative_pointer_manager_v1_destroy(nativeInterface(), false); + + m_handle = nullptr; +} + +wl_global *WRelativePointerManagerV1::global() const +{ + W_D(const WRelativePointerManagerV1); + if (!m_handle) + return nullptr; + + return d->handle()->global; +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wrelativepointermanagerv1.h b/waylib/src/server/protocols/wrelativepointermanagerv1.h new file mode 100644 index 0000000000..b61567d789 --- /dev/null +++ b/waylib/src/server/protocols/wrelativepointermanagerv1.h @@ -0,0 +1,38 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +#include +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WSeat; + +class WRelativePointerManagerV1Private; +class WAYLIB_SERVER_EXPORT WRelativePointerManagerV1 : public QObject, public WObject, public WServerInterface +{ + Q_OBJECT + W_DECLARE_PRIVATE(WRelativePointerManagerV1) + +public: + explicit WRelativePointerManagerV1(); + + wlr_relative_pointer_manager_v1 *handle() const; + + void sendRelativeMotion(WSeat *seat, uint32_t timeMsec, const QPointF &delta, + const QPointF &unacceleratedDelta); + + QByteArrayView interfaceName() const override; + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wremotesubsurfacemanagerv1.cpp b/waylib/src/server/protocols/wremotesubsurfacemanagerv1.cpp new file mode 100644 index 0000000000..f2cd2bf342 --- /dev/null +++ b/waylib/src/server/protocols/wremotesubsurfacemanagerv1.cpp @@ -0,0 +1,819 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wremotesubsurfacemanagerv1.h" + +#include "private/wglobal_p.h" +#include "qwayland-server-treeland-remote-subsurface-unstable-v1.h" +#include "wayliblogging.h" +#include "wserver.h" +#include "wscoplistener.h" +#include "wsubsurface.h" +#include "wsurface.h" + +extern "C" { +#include +} + +#include +#include +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +// --------------------------------------------------------------------------- +// Forward declarations +// --------------------------------------------------------------------------- + +class WRemoteSubsurfaceManagerV1Private; +class ExportedSurfaceContext; +class RemoteSubsurfaceContext; + +// --------------------------------------------------------------------------- +// wlroots role for remote subsurfaces (defined after RemoteSubsurfaceContext) +// --------------------------------------------------------------------------- + +static void remote_subsurface_role_commit(struct wlr_surface *surface); +static void remote_subsurface_role_destroy(struct wlr_surface *surface); +static const wlr_surface_role remoteSubsurfaceRole = { + .name = "treeland_remote_subsurface_v1", + .no_object = false, + .client_commit = nullptr, + .commit = remote_subsurface_role_commit, + .map = nullptr, + .unmap = nullptr, + .destroy = remote_subsurface_role_destroy, +}; + +// --------------------------------------------------------------------------- +// ExportedSurfaceContext — one per exported wl_surface +// --------------------------------------------------------------------------- + +class ExportedSurfaceContext + : public QObject + , public QtWaylandServer::treeland_exported_surface_v1 +{ + Q_OBJECT +public: + ExportedSurfaceContext(WRemoteSubsurfaceManagerV1Private *manager, + wlr_surface *surface, + const QString &token, + wl_client *client, + uint32_t version, + uint32_t id) + : QObject() + , QtWaylandServer::treeland_exported_surface_v1(client, id, version) + , m_manager(manager) + , m_surface(surface) + , m_token(token) + { + // WSurface follows a surface role and may be destroyed with an + // xdg_toplevel while the underlying wl_surface remains valid. + m_surfaceDestroyListener.init(&m_surface->events.destroy, + this, + &ExportedSurfaceContext::handleSurfaceDestroy); + } + + ~ExportedSurfaceContext() override = default; + + wlr_surface *surface() const + { + return m_surface; + } + + + QString token() const + { + return m_token; + } + + // Back-pointer to the RemoteSubsurfaceContext where this context acts as child. + // Set by addChildToParent / removeChildFromParent in the manager. + RemoteSubsurfaceContext *remoteSubsurface = nullptr; + + // Remote children ordered relative to this exported parent surface. + QList belowChildren; + QList aboveChildren; + +protected: + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void destroy_resource(Resource *) override; + void create_remote_subsurface(Resource *resource, + uint32_t id, + const QString &parent_token) override; + +private: + void handleSurfaceDestroy(); + + WRemoteSubsurfaceManagerV1Private *m_manager; + wlr_surface *m_surface = nullptr; + QString m_token; + WScopedListener m_surfaceDestroyListener; +}; + +// --------------------------------------------------------------------------- +// RemoteSubsurfaceContext — one per parent-child relationship +// --------------------------------------------------------------------------- + +class RemoteSubsurfaceContext + : public QObject + , public QtWaylandServer::treeland_remote_subsurface_v1 +{ + Q_OBJECT +public: + RemoteSubsurfaceContext(WRemoteSubsurfaceManagerV1Private *manager, + ExportedSurfaceContext *childExported, + ExportedSurfaceContext *parentExported, + wl_client *client, + uint32_t version, + uint32_t id) + : QObject() + , QtWaylandServer::treeland_remote_subsurface_v1(client, id, version) + , m_manager(manager) + , m_child(childExported) + , m_parent(parentExported) + { + // Mirror the wlroots scene subsurface tree pattern: listen to + // wlr_surface map/unmap events rather than WSurface::mappedChanged. + // These listeners live at the wlr_surface level and survive WSurface + // wrapper recreation, so no reconnection is ever needed. + if (auto *wlr = parentExported->surface()) { + m_parentMapListener.init(&wlr->events.map, this, + &RemoteSubsurfaceContext::recheckMapping); + m_parentUnmapListener.init(&wlr->events.unmap, this, + &RemoteSubsurfaceContext::recheckMapping); + } + } + + ~RemoteSubsurfaceContext() override; + + ExportedSurfaceContext *childExported() const + { + return m_child; + } + + ExportedSurfaceContext *parentExported() const + { + return m_parent; + } + + WSubsurface *subsurface() const { return m_subsurface; } + void setSubsurface(WSubsurface *s) { m_subsurface = s; } + QPointF position() const { return m_position; } + + void invalidate() + { + m_manager = nullptr; + // The remote object now outlives the parent exported surface. Detach + // the parent map/unmap listeners, otherwise wlroots asserts that + // events.map / events.unmap are empty when the parent wlr_surface is + // destroyed (see surface_handle_resource_destroy in wlr_compositor.c). + m_parentMapListener.disconnect(); + m_parentUnmapListener.disconnect(); + } + + void ensureSubsurface(); + + void recheckMapping(); + void cascadeUnmap(); + void unmapChildTree(); + +protected: + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void destroy_resource(Resource *) override; + void set_position(Resource *resource, int32_t x, int32_t y) override; + void place_above(Resource *resource, const QString &sibling_token) override; + void place_below(Resource *resource, const QString &sibling_token) override; + +private: + WRemoteSubsurfaceManagerV1Private *m_manager; + ExportedSurfaceContext *m_child = nullptr; + ExportedSurfaceContext *m_parent = nullptr; + QPointer m_subsurface; + QPointF m_position; + WScopedListener m_parentMapListener; + WScopedListener m_parentUnmapListener; +}; + +// --------------------------------------------------------------------------- +// WRemoteSubsurfaceManagerV1Private +// --------------------------------------------------------------------------- + +static inline WSurface *wsurfaceFrom(const ExportedSurfaceContext *ctx) +{ + auto *wlr = ctx ? ctx->surface() : nullptr; + return wlr ? WSurface::fromHandle(wlr) : nullptr; +} + +static inline QStringView shortToken(const QString &token) +{ + return QStringView(token).left(8); +} + +class WRemoteSubsurfaceManagerV1Private + : public WObjectPrivate + , public QtWaylandServer::treeland_remote_subsurface_manager_v1 +{ + Q_DECLARE_PUBLIC(WRemoteSubsurfaceManagerV1) + +public: + explicit WRemoteSubsurfaceManagerV1Private(WRemoteSubsurfaceManagerV1 *q) + : WObjectPrivate(q) + , QtWaylandServer::treeland_remote_subsurface_manager_v1() + { + } + + wl_global *globalHandle() const + { + return m_global; + } + + // Lookup + ExportedSurfaceContext *findExportedByToken(const QString &token) const + { + return m_tokens.value(token, nullptr); + } + + bool isSurfaceExported(wlr_surface *wlrSurface) const + { + if (!wlrSurface) + return false; + for (auto it = m_tokens.constBegin(); it != m_tokens.constEnd(); ++it) { + if (it.value()->surface() == wlrSurface) + return true; + } + return false; + } + + // Registry + void registerExported(ExportedSurfaceContext *ctx) + { + m_tokens.insert(ctx->token(), ctx); + } + + void unregisterExported(ExportedSurfaceContext *ctx) + { + m_tokens.remove(ctx->token()); + } + + // Cycle detection + bool isDescendantOf(ExportedSurfaceContext *candidate, ExportedSurfaceContext *root) const + { + if (!candidate || !root) + return false; + auto *curr = candidate; + while (curr) { + if (curr == root) + return true; + curr = curr->remoteSubsurface ? curr->remoteSubsurface->parentExported() : nullptr; + } + return false; + } + + // WSurface::addRemoteSubsurface() is private; this manager is a friend of + // WSurface, so expose a static wrapper so RemoteSubsurfaceContext can call it. + static WSubsurface *createRemoteSubsurface(WSurface *parent, wlr_surface *child) + { + return parent->addRemoteSubsurface(child); + } + + // Children list management (z-order, below vs above parent) + QList childrenOf(ExportedSurfaceContext *parent) const + { + if (!parent) + return {}; + QList res = parent->belowChildren; + res.append(parent->aboveChildren); + return res; + } + + void addChildToParent(RemoteSubsurfaceContext *remote) + { + auto *parent = remote->parentExported(); + parent->aboveChildren.append(remote); + remote->childExported()->remoteSubsurface = remote; + + auto *parentSurface = wsurfaceFrom(parent); + auto *childWlr = remote->childExported()->surface(); + if (!parentSurface || !childWlr) + return; + + // WSubsurface is destroyed together with the parent's WSurface. + // WSurface lifetime follows its surface role (remote_subsurface, + // xdg_toplevel, etc.). Recreating a remote parent's role requires + // recreating WSubsurface for its children. + remote->setSubsurface(parentSurface->addRemoteSubsurface(childWlr)); + } + + void removeChildFromOrder(RemoteSubsurfaceContext *remote) + { + auto *parent = remote->parentExported(); + if (!parent) + return; + parent->belowChildren.removeOne(remote); + parent->aboveChildren.removeOne(remote); + } + + void removeChildFromParent(RemoteSubsurfaceContext *remote) + { + removeChildFromOrder(remote); + + auto *child = remote->childExported(); + if (child && child->remoteSubsurface == remote) + child->remoteSubsurface = nullptr; + + if (auto *subsurface = remote->subsurface()) { + if (auto *parentSurface = subsurface->parentSurface()) + parentSurface->removeSubsurface(subsurface); + remote->setSubsurface(nullptr); + } + } + + void syncRemoteSubsurfaceOrder(ExportedSurfaceContext *parent) + { + auto *parentSurface = wsurfaceFrom(parent); + if (!parentSurface) + return; + + QList below; + QList above; + for (auto *remote : parent->belowChildren) { + if (auto *subsurface = remote->subsurface()) + below.append(subsurface); + } + for (auto *remote : parent->aboveChildren) { + if (auto *subsurface = remote->subsurface()) + above.append(subsurface); + } + parentSurface->setRemoteSubsurfaceOrder(below, above); + } + + void placeChildAboveParentTop(RemoteSubsurfaceContext *remote) + { + auto *parent = remote->parentExported(); + removeChildFromOrder(remote); + parent->aboveChildren.append(remote); + syncRemoteSubsurfaceOrder(parent); + } + + void placeChildAboveParentBottom(RemoteSubsurfaceContext *remote) + { + auto *parent = remote->parentExported(); + removeChildFromOrder(remote); + parent->aboveChildren.prepend(remote); + syncRemoteSubsurfaceOrder(parent); + } + + void placeChildBelowParentTop(RemoteSubsurfaceContext *remote) + { + auto *parent = remote->parentExported(); + removeChildFromOrder(remote); + parent->belowChildren.append(remote); + syncRemoteSubsurfaceOrder(parent); + } + + void placeChildBelowParentBottom(RemoteSubsurfaceContext *remote) + { + auto *parent = remote->parentExported(); + removeChildFromOrder(remote); + parent->belowChildren.prepend(remote); + syncRemoteSubsurfaceOrder(parent); + } + + void placeChildAboveSibling(RemoteSubsurfaceContext *remote, + RemoteSubsurfaceContext *siblingRemote) + { + auto *parent = remote->parentExported(); + removeChildFromOrder(remote); + + auto &belowList = parent->belowChildren; + int idxBelow = belowList.indexOf(siblingRemote); + if (idxBelow >= 0) { + belowList.insert(idxBelow + 1, remote); + } else { + auto &aboveList = parent->aboveChildren; + int idxAbove = aboveList.indexOf(siblingRemote); + aboveList.insert(idxAbove >= 0 ? idxAbove + 1 : aboveList.size(), remote); + } + + syncRemoteSubsurfaceOrder(parent); + } + + void placeChildBelowSibling(RemoteSubsurfaceContext *remote, + RemoteSubsurfaceContext *siblingRemote) + { + auto *parent = remote->parentExported(); + removeChildFromOrder(remote); + + auto &belowList = parent->belowChildren; + int idxBelow = belowList.indexOf(siblingRemote); + if (idxBelow >= 0) { + belowList.insert(idxBelow, remote); + } else { + auto &aboveList = parent->aboveChildren; + int idxAbove = aboveList.indexOf(siblingRemote); + aboveList.insert(idxAbove > 0 ? idxAbove : 0, remote); + } + + syncRemoteSubsurfaceOrder(parent); + } + + // Sibling lookup: find RemoteSubsurfaceContext for a sibling token under same parent + RemoteSubsurfaceContext *findSibling(RemoteSubsurfaceContext *remote, + const QString &siblingToken) const + { + auto *siblingCtx = findExportedByToken(siblingToken); + if (!siblingCtx) + return nullptr; + for (auto *child : childrenOf(remote->parentExported())) { + if (child->childExported() == siblingCtx) + return child; + } + return nullptr; + } + + // Cleanup + void cleanupExportedContext(ExportedSurfaceContext *ctx) + { + QList allRemotes = childrenOf(ctx); + if (ctx->remoteSubsurface) + allRemotes.append(ctx->remoteSubsurface); + + // Unmap the child window and detach the parent-child relationship, + // leaving the treeland_remote_subsurface_v1 resource for the client + // to destroy. + for (auto *remote : std::as_const(allRemotes)) { + remote->unmapChildTree(); + removeChildFromParent(remote); + // Prevent RemoteSubsurfaceContext::destroy_resource() from trying + // to detach the same parent-child relationship a second time when + // the client later destroys the role resource. + remote->invalidate(); + } + + unregisterExported(ctx); + } + +protected: + void destroy(Resource *resource) override + { + wl_resource_destroy(resource->handle); + } + + void export_surface(Resource *resource, + uint32_t id, + struct ::wl_resource *surfaceResource) override + { + auto *wlrSurface = wlr_surface_from_resource(surfaceResource); + + if (!wlrSurface) { + wl_resource_post_error(resource->handle, + error_bad_surface, + "Invalid wl_surface resource"); + return; + } + + if (isSurfaceExported(wlrSurface)) { + wl_resource_post_error(resource->handle, + error_bad_surface, + "The wl_surface has already been exported through this manager"); + return; + } + + const QString token = QUuid::createUuid().toString(QUuid::WithoutBraces); + qCDebug(lcWlRemoteSubsurface) << "Exported surface" << shortToken(token); + + auto *context = new ExportedSurfaceContext(this, + wlrSurface, + token, + resource->client(), + resource->version(), + id); + + registerExported(context); + context->send_surface_token(token); + } + +private: + QHash m_tokens; +}; + +// --------------------------------------------------------------------------- +// ExportedSurfaceContext implementation +// --------------------------------------------------------------------------- + +void ExportedSurfaceContext::handleSurfaceDestroy() +{ + if (!m_manager || m_manager->findExportedByToken(m_token) != this) + return; + + if (auto *res = resource()) { + if (res->handle) { + wl_resource_destroy(res->handle); + return; + } + } + if (m_manager) + m_manager->cleanupExportedContext(this); + delete this; +} + +void ExportedSurfaceContext::destroy_resource(Resource *) +{ + if (m_manager) + m_manager->cleanupExportedContext(this); + delete this; +} + +void ExportedSurfaceContext::create_remote_subsurface(Resource *resource, + uint32_t id, + const QString &parent_token) +{ + if (parent_token.isEmpty()) { + send_parent_rejected(reject_reason_invalid_token, parent_token); + return; + } + + // Check if this surface already has a remote subsurface relationship + if (remoteSubsurface) { + send_parent_rejected(reject_reason_invalid_token, parent_token); + return; + } + + auto *parentContext = m_manager->findExportedByToken(parent_token); + if (!parentContext) { + send_parent_rejected(reject_reason_invalid_token, parent_token); + return; + } + + if (parentContext == this) { + send_parent_rejected(reject_reason_cyclic, parent_token); + return; + } + + if (m_manager->isDescendantOf(parentContext, this)) { + send_parent_rejected(reject_reason_cyclic, parent_token); + return; + } + + auto *childWlrSurface = m_surface; + if (!childWlrSurface) { + // No valid wlr_surface — leave the new remote object inert. + qCWarning(lcWlRemoteSubsurface) + << "create_remote_subsurface: child" << shortToken(m_token) << "has no wlr_surface"; + return; + } + + if (!wlr_surface_set_role(childWlrSurface, + &remoteSubsurfaceRole, + resource->handle, + 0 /* bad_surface */)) { + // Role conflict — wlr_surface_set_role already posted the error. + // The new treeland_remote_subsurface_v1 object is inert. + return; + } + + auto *remote = new RemoteSubsurfaceContext(m_manager, + this, + parentContext, + resource->client(), + resource->version(), + id); + + wlr_surface_set_role_object(childWlrSurface, remote->resource()->handle); + m_manager->addChildToParent(remote); + qCDebug(lcWlRemoteSubsurface) << "Remote subsurface created: child" << shortToken(m_token) + << "→ parent" << shortToken(parent_token); + remote->recheckMapping(); +} + +// --------------------------------------------------------------------------- +// RemoteSubsurfaceContext implementation +// --------------------------------------------------------------------------- + +RemoteSubsurfaceContext::~RemoteSubsurfaceContext() = default; + +// --------------------------------------------------------------------------- +// wlroots role definition (after RemoteSubsurfaceContext is complete) +// --------------------------------------------------------------------------- + +static void remote_subsurface_role_commit(struct wlr_surface *surface) +{ + auto *roleRes = QtWaylandServer::treeland_remote_subsurface_v1::Resource::fromResource( + surface->role_resource); + if (!roleRes || !roleRes->object()) + return; + auto *ctx = static_cast(roleRes->object()); + ctx->recheckMapping(); +} + +static void remote_subsurface_role_destroy(struct wlr_surface *surface) +{ + // Don't delete the RemoteSubsurfaceContext here. + // wlroots already called wlr_surface_unmap(); QtWayland will call + // destroy_resource() which does the full Qt/QHash cleanup. + Q_UNUSED(surface); +} + +void RemoteSubsurfaceContext::ensureSubsurface() +{ + if (m_subsurface) + return; + + auto *parentSurface = wsurfaceFrom(m_parent); + auto *childWlr = m_child ? m_child->surface() : nullptr; + if (!parentSurface || !childWlr) + return; + + m_subsurface = WRemoteSubsurfaceManagerV1Private::createRemoteSubsurface(parentSurface, childWlr); + m_subsurface->setPosition(m_position); + m_manager->syncRemoteSubsurfaceOrder(m_parent); +} + +void RemoteSubsurfaceContext::recheckMapping() +{ + if (!m_manager) + return; + + auto *childQw = m_child ? m_child->surface() : nullptr; + + bool parentMapped = false; + auto *parentWs = wsurfaceFrom(m_parent); + parentMapped = parentWs && parentWs->mapped(); + + // ensureSubsurface re-creates this subsurface when the parent WSurface + // wrapper was destroyed and recreated. Fast no-op when it still exists. + ensureSubsurface(); + + bool childHasBuffer = childQw && wlr_surface_has_buffer(childQw); + bool shouldBeMapped = parentMapped && childHasBuffer; + + bool currentlyMapped = m_subsurface && m_subsurface->isMapped(); + + if (shouldBeMapped && !currentlyMapped) { + if (childQw) + wlr_surface_map(childQw); + if (m_subsurface) + m_subsurface->setMapped(true); + qCDebug(lcWlRemoteSubsurface) << "Mapped: child" << shortToken(m_child->token()) << "parent" + << shortToken(m_parent->token()); + // Recursively recheck children — they may now be eligible for mapping + for (auto *grandchild : m_manager->childrenOf(m_child)) { + grandchild->recheckMapping(); + } + } else if (!shouldBeMapped && currentlyMapped) { + if (childQw) + wlr_surface_unmap(childQw); + cascadeUnmap(); + } +} + +void RemoteSubsurfaceContext::cascadeUnmap() +{ + if (!m_subsurface || !m_subsurface->isMapped() || !m_manager) + return; + m_subsurface->setMapped(false); + qCDebug(lcWlRemoteSubsurface) << "Unmapped: child" << shortToken(m_child->token()) << "parent" + << shortToken(m_parent->token()); + + // Recursively unmap all remote children of this child + for (auto *grandchild : m_manager->childrenOf(m_child)) { + grandchild->cascadeUnmap(); + } +} + +void RemoteSubsurfaceContext::unmapChildTree() +{ + auto *childQw = m_child ? m_child->surface() : nullptr; + if (childQw) + wlr_surface_unmap(childQw); + cascadeUnmap(); +} + +void RemoteSubsurfaceContext::set_position(Resource *resource, int32_t x, int32_t y) +{ + Q_UNUSED(resource); + m_position = QPointF(x, y); + if (m_subsurface) + m_subsurface->setPosition(m_position); +} + +void RemoteSubsurfaceContext::place_above([[maybe_unused]] Resource *resource, + const QString &sibling_token) +{ + if (!m_manager) + return; + + if (sibling_token.isEmpty()) { + m_manager->placeChildAboveParentTop(this); + return; + } + + auto *siblingCtx = m_manager->findExportedByToken(sibling_token); + if (!siblingCtx) { + send_invalid_sibling(sibling_token); + return; + } + + if (siblingCtx == m_parent) { + m_manager->placeChildAboveParentBottom(this); + return; + } + + auto *siblingRemote = m_manager->findSibling(this, sibling_token); + if (!siblingRemote) { + send_invalid_sibling(sibling_token); + return; + } + + m_manager->placeChildAboveSibling(this, siblingRemote); +} + +void RemoteSubsurfaceContext::place_below([[maybe_unused]] Resource *resource, + const QString &sibling_token) +{ + if (!m_manager) + return; + + if (sibling_token.isEmpty()) { + m_manager->placeChildBelowParentBottom(this); + return; + } + + auto *siblingCtx = m_manager->findExportedByToken(sibling_token); + if (!siblingCtx) { + send_invalid_sibling(sibling_token); + return; + } + + if (siblingCtx == m_parent) { + m_manager->placeChildBelowParentTop(this); + return; + } + + auto *siblingRemote = m_manager->findSibling(this, sibling_token); + if (!siblingRemote) { + send_invalid_sibling(sibling_token); + return; + } + + m_manager->placeChildBelowSibling(this, siblingRemote); +} + +void RemoteSubsurfaceContext::destroy_resource(Resource *) +{ + if (m_manager) { + cascadeUnmap(); + // This is the direct role-object teardown path. Exported-surface + // cleanup may also reach this object, but it invalidates m_manager + // before destroying the resource so this detach only runs once. + m_manager->removeChildFromParent(this); + } + delete this; +} + +// --------------------------------------------------------------------------- +// WRemoteSubsurfaceManagerV1 — public API +// --------------------------------------------------------------------------- + +WRemoteSubsurfaceManagerV1::WRemoteSubsurfaceManagerV1() + : WObject(*new WRemoteSubsurfaceManagerV1Private(this)) +{ +} + +WRemoteSubsurfaceManagerV1::~WRemoteSubsurfaceManagerV1() = default; + +void WRemoteSubsurfaceManagerV1::create(WServer *server) +{ + W_D(WRemoteSubsurfaceManagerV1); + d->init(server->handle(), InterfaceVersion); +} + +void WRemoteSubsurfaceManagerV1::destroy([[maybe_unused]] WServer *server) +{ + W_D(WRemoteSubsurfaceManagerV1); + d->globalRemove(); +} + +wl_global *WRemoteSubsurfaceManagerV1::global() const +{ + W_DC(WRemoteSubsurfaceManagerV1); + return d->globalHandle(); +} + +QByteArrayView WRemoteSubsurfaceManagerV1::interfaceName() const +{ + return QtWaylandServer::treeland_remote_subsurface_manager_v1::interfaceName(); +} + +WAYLIB_SERVER_END_NAMESPACE + +#include "wremotesubsurfacemanagerv1.moc" diff --git a/waylib/src/server/protocols/wremotesubsurfacemanagerv1.h b/waylib/src/server/protocols/wremotesubsurfacemanagerv1.h new file mode 100644 index 0000000000..d385f178fb --- /dev/null +++ b/waylib/src/server/protocols/wremotesubsurfacemanagerv1.h @@ -0,0 +1,35 @@ +// SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WRemoteSubsurfaceManagerV1Private; + +class WAYLIB_SERVER_EXPORT WRemoteSubsurfaceManagerV1 + : public QObject + , public WObject + , public WServerInterface +{ + Q_OBJECT + W_DECLARE_PRIVATE(WRemoteSubsurfaceManagerV1) + +public: + explicit WRemoteSubsurfaceManagerV1(); + ~WRemoteSubsurfaceManagerV1() override; + + static constexpr int InterfaceVersion = 1; + QByteArrayView interfaceName() const override; + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wsecuritycontextmanager.cpp b/waylib/src/server/protocols/wsecuritycontextmanager.cpp new file mode 100644 index 0000000000..06630d97c5 --- /dev/null +++ b/waylib/src/server/protocols/wsecuritycontextmanager.cpp @@ -0,0 +1,550 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: MIT + +#include "wsecuritycontextmanager.h" +#include "private/wsecuritycontextmanager_p.h" +#include +#include "wsocket.h" +#include "private/wglobal_p.h" +#include "security-context-v1-protocol.h" + +#include +#include +#include +#include +#include +#include + +// wlroots keeps this helper in an internal header. +extern "C" void wlr_global_destroy_safe(struct wl_global *global); + +WAYLIB_SERVER_BEGIN_NAMESPACE + +QT_WARNING_PUSH +QT_WARNING_DISABLE_GCC("-Wunused-parameter") +QT_WARNING_DISABLE_CLANG("-Wunused-parameter") +QT_WARNING_DISABLE_GCC("-Wmissing-field-initializers") +QT_WARNING_DISABLE_CLANG("-Wmissing-field-initializers") +static void resource_handle_destroy(struct wl_client *client, + struct wl_resource *resource) { + wl_resource_destroy(resource); +} + +static void manager_handle_create_listener(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + int listen_fd, int close_fd); +void security_context_handle_commit(struct wl_client *client, + struct wl_resource *resource); +static void security_context_handle_set_sandbox_engine(struct wl_client *client, + struct wl_resource *resource, const char *sandbox_engine); +static void security_context_handle_set_app_id(struct wl_client *client, + struct wl_resource *resource, const char *app_id); +static void security_context_handle_set_instance_id(struct wl_client *client, + struct wl_resource *resource, const char *instance_id); +static const struct wp_security_context_manager_v1_interface manager_impl = { + .destroy = resource_handle_destroy, + .create_listener = manager_handle_create_listener, +}; +static const struct wp_security_context_v1_interface security_context_impl = { + .destroy = resource_handle_destroy, + .set_sandbox_engine = security_context_handle_set_sandbox_engine, + .set_app_id = security_context_handle_set_app_id, + .set_instance_id = security_context_handle_set_instance_id, + .commit = security_context_handle_commit, +}; + +static struct wlr_security_context_manager_v1 *manager_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_security_context_manager_v1_interface, &manager_impl)); + struct wlr_security_context_manager_v1 *manager = + reinterpret_cast(wl_resource_get_user_data(resource)); + return manager; +} + +/** + * Get a struct wlr_security_context_v1 from a struct wl_resource. + * + * NULL is returned if the security context has been committed. + */ +static struct wlr_security_context_v1 *security_context_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &wp_security_context_v1_interface, &security_context_impl)); + return reinterpret_cast(wl_resource_get_user_data(resource)); +} + +static void security_context_state_finish(struct wlr_security_context_v1_state *state) { + free(state->app_id); + free(state->sandbox_engine); + free(state->instance_id); +} + +static bool copy_state_field(char **dst, const char *src) { + if (src == NULL) { + return true; + } + *dst = strdup(src); + return *dst != NULL; +} + +static bool security_context_state_copy(struct wlr_security_context_v1_state *dst, + const struct wlr_security_context_v1_state *src) { + bool ok = copy_state_field(&dst->app_id, src->app_id) && + copy_state_field(&dst->sandbox_engine, src->sandbox_engine) && + copy_state_field(&dst->instance_id, src->instance_id); + if (!ok) { + security_context_state_finish(dst); + } + return ok; +} + +static void security_context_destroy( + struct wlr_security_context_v1 *security_context) { + if (security_context == NULL) { + return; + } + + if (security_context->listen_source != NULL) { + wl_event_source_remove(security_context->listen_source); + } + if (security_context->close_source != NULL) { + wl_event_source_remove(security_context->close_source); + } + + close(security_context->listen_fd); + close(security_context->close_fd); + delete security_context->socket.data(); + + security_context_state_finish(&security_context->state); + wl_list_remove(&security_context->link); + free(security_context); +} + +static void security_context_client_destroy( + struct wlr_security_context_v1_client *security_context_client) { + wl_list_remove(&security_context_client->destroy.link); + security_context_state_finish(&security_context_client->state); + free(security_context_client); +} + +static void security_context_client_handle_destroy(struct wl_listener *listener, + void *data) { + struct wlr_security_context_v1_client *security_context_client = + W_CONTAINER_OF(listener, wlr_security_context_v1_client, destroy); + security_context_client_destroy(security_context_client); +} + +static int security_context_handle_listen_fd_event(int listen_fd, uint32_t mask, + void *data) { + struct wlr_security_context_v1 *security_context = reinterpret_cast(data); + + if (mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR)) { + security_context_destroy(security_context); + return 0; + } + + if (mask & WL_EVENT_READABLE) { + int client_fd = accept(listen_fd, NULL, NULL); + if (client_fd < 0) { + wlr_log_errno(WLR_ERROR, "accept failed"); + return 0; + } + + struct wlr_security_context_v1_client *security_context_client = + reinterpret_cast(calloc(1, sizeof(*security_context_client))); + if (security_context_client == NULL) { + wlr_log_errno(WLR_ERROR, "Allocation failed"); + close(client_fd); + return 0; + } + + struct wl_display *display = + wl_global_get_display(security_context->manager->global); + struct wl_client *client = wl_client_create(display, client_fd); + if (client == NULL) { + wlr_log(WLR_ERROR, "wl_client_create failed"); + close(client_fd); + free(security_context_client); + return 0; + } + + security_context_client->destroy.notify = security_context_client_handle_destroy; + wl_client_add_destroy_listener(client, &security_context_client->destroy); + + if (!security_context_state_copy(&security_context_client->state, + &security_context->state)) { + security_context_client_destroy(security_context_client); + wl_client_post_no_memory(client); + return 0; + } + + WClient *wc = security_context->socket->addClient(client); + Q_ASSERT(wc->sandboxEngine() == security_context_client->state.sandbox_engine); + Q_ASSERT(wc->appId() == security_context_client->state.app_id); + Q_ASSERT(wc->instanceId() == security_context_client->state.instance_id); + } + + return 0; +} + +static int security_context_handle_close_fd_event(int fd, uint32_t mask, + void *data) { + struct wlr_security_context_v1 *security_context = reinterpret_cast(data); + + if (mask & (WL_EVENT_HANGUP | WL_EVENT_ERROR)) { + security_context_destroy(security_context); + } + + return 0; +} + +void security_context_handle_commit(struct wl_client *client, + struct wl_resource *resource) { + struct wlr_security_context_v1 *security_context = + security_context_from_resource(resource); + if (security_context == NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_V1_ERROR_ALREADY_USED, + "Security context has already been committed"); + return; + } + + // In theory the compositor should prevent this with a global filter, but + // let's make sure it doesn't happen. + if (wlr_security_context_manager_v1_lookup_client(security_context->manager, + client) != NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_MANAGER_V1_ERROR_NESTED, + "Nested security contexts are forbidden"); + return; + } + + struct wl_display *display = wl_client_get_display(client); + struct wl_event_loop *loop = wl_display_get_event_loop(display); + + security_context->listen_source = wl_event_loop_add_fd(loop, + security_context->listen_fd, WL_EVENT_READABLE, + security_context_handle_listen_fd_event, security_context); + if (security_context->listen_source == NULL) { + wl_resource_post_no_memory(resource); + return; + } + + security_context->close_source = wl_event_loop_add_fd(loop, + security_context->close_fd, 0, security_context_handle_close_fd_event, + security_context); + if (security_context->close_source == NULL) { + wl_resource_post_no_memory(resource); + return; + } + + wl_resource_set_user_data(resource, NULL); + + WSocket *parentSocket = WSocket::get(client); + Q_ASSERT(parentSocket); + security_context->socket = new WSocket(security_context->state.sandbox_engine, + security_context->state.app_id, + security_context->state.instance_id, + parentSocket); + security_context->socket->setObjectName("wlr_security_context_v1_socket"); + security_context->socket->bind(security_context->listen_fd); + + struct wlr_security_context_v1_commit_event event = { + .state = &security_context->state, + .parent_client = client, + }; + wl_signal_emit_mutable(&security_context->manager->events.commit, &event); +} + +static void security_context_handle_set_sandbox_engine(struct wl_client *client, + struct wl_resource *resource, const char *sandbox_engine) { + struct wlr_security_context_v1 *security_context = + security_context_from_resource(resource); + if (security_context == NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_V1_ERROR_ALREADY_USED, + "Security context has already been committed"); + return; + } + + if (security_context->state.sandbox_engine != NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_V1_ERROR_ALREADY_SET, + "Sandbox engine has already been set"); + return; + } + + security_context->state.sandbox_engine = strdup(sandbox_engine); + if (security_context->state.sandbox_engine == NULL) { + wl_resource_post_no_memory(resource); + } +} + +static void security_context_handle_set_app_id(struct wl_client *client, + struct wl_resource *resource, const char *app_id) { + struct wlr_security_context_v1 *security_context = + security_context_from_resource(resource); + if (security_context == NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_V1_ERROR_ALREADY_USED, + "Security context has already been committed"); + return; + } + + if (security_context->state.app_id != NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_V1_ERROR_ALREADY_SET, + "App ID has already been set"); + return; + } + + security_context->state.app_id = strdup(app_id); + if (security_context->state.app_id == NULL) { + wl_resource_post_no_memory(resource); + } +} + +static void security_context_handle_set_instance_id(struct wl_client *client, + struct wl_resource *resource, const char *instance_id) { + struct wlr_security_context_v1 *security_context = + security_context_from_resource(resource); + if (security_context == NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_V1_ERROR_ALREADY_USED, + "Security context has already been committed"); + return; + } + + if (security_context->state.instance_id != NULL) { + wl_resource_post_error(resource, + WP_SECURITY_CONTEXT_V1_ERROR_ALREADY_SET, + "Instance ID has already been set"); + return; + } + + security_context->state.instance_id = strdup(instance_id); + if (security_context->state.instance_id == NULL) { + wl_resource_post_no_memory(resource); + } +} + +static void security_context_resource_destroy(struct wl_resource *resource) { + struct wlr_security_context_v1 *security_context = + security_context_from_resource(resource); + security_context_destroy(security_context); +} + +static void manager_handle_create_listener(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, + int listen_fd, int close_fd) { + struct wlr_security_context_manager_v1 *manager = + manager_from_resource(manager_resource); + if (manager == NULL) { + close(listen_fd); + close(close_fd); + struct wl_resource *resource = wl_resource_create(client, + &wp_security_context_v1_interface, wl_resource_get_version(manager_resource), id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &security_context_impl, NULL, + security_context_resource_destroy); + return; + } + + struct stat stat_buf = {0}; + if (fstat(listen_fd, &stat_buf) != 0) { + wlr_log_errno(WLR_ERROR, "fstat failed on listen FD"); + wl_resource_post_error(manager_resource, + WP_SECURITY_CONTEXT_MANAGER_V1_ERROR_INVALID_LISTEN_FD, + "Invalid listen_fd"); + return; + } else if (!S_ISSOCK(stat_buf.st_mode)) { + wl_resource_post_error(manager_resource, + WP_SECURITY_CONTEXT_MANAGER_V1_ERROR_INVALID_LISTEN_FD, + "listen_fd is not a socket"); + return; + } + + int accept_conn = 0; + socklen_t accept_conn_size = sizeof(accept_conn); + if (getsockopt(listen_fd, SOL_SOCKET, SO_ACCEPTCONN, &accept_conn, + &accept_conn_size) != 0) { + wlr_log_errno(WLR_ERROR, "getsockopt failed on listen FD"); + wl_resource_post_error(manager_resource, + WP_SECURITY_CONTEXT_MANAGER_V1_ERROR_INVALID_LISTEN_FD, + "Invalid listen_fd"); + return; + } else if (accept_conn == 0) { + wl_resource_post_error(manager_resource, + WP_SECURITY_CONTEXT_MANAGER_V1_ERROR_INVALID_LISTEN_FD, + "listen_fd is not a listening socket"); + return; + } + + struct wlr_security_context_v1 *security_context = + reinterpret_cast(calloc(1, sizeof(*security_context))); + if (security_context == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + + security_context->manager = manager; + security_context->listen_fd = listen_fd; + security_context->close_fd = close_fd; + + uint32_t version = wl_resource_get_version(manager_resource); + struct wl_resource *resource = wl_resource_create(client, + &wp_security_context_v1_interface, version, id); + if (resource == NULL) { + free(security_context); + wl_resource_post_no_memory(manager_resource); + return; + } + wl_resource_set_implementation(resource, &security_context_impl, + security_context, security_context_resource_destroy); + + wl_list_insert(&manager->contexts, &security_context->link); +} + +static void manager_bind(struct wl_client *client, void *data, + uint32_t version, uint32_t id) { + struct wlr_security_context_manager_v1 *manager = reinterpret_cast(data); + + struct wl_resource *resource = wl_resource_create(client, + &wp_security_context_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, manager, NULL); +} + +static void security_context_manager_v1_destroy(struct wlr_security_context_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, manager); + + assert(wl_list_empty(&manager->events.destroy.listener_list)); + assert(wl_list_empty(&manager->events.commit.listener_list)); + + struct wlr_security_context_v1 *security_context, *tmp; + wl_list_for_each_safe(security_context, tmp, &manager->contexts, link) { + security_context_destroy(security_context); + } + + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + wl_list_remove(&manager->display_destroy.link); + free(manager); +} + +void wlr_security_context_manager_v1_destroy(struct wlr_security_context_manager_v1 *manager, + bool destroy_global_safe) { + security_context_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + struct wlr_security_context_manager_v1 *manager = + W_CONTAINER_OF(listener, wlr_security_context_manager_v1, display_destroy); + security_context_manager_v1_destroy(manager, false); +} + +struct wlr_security_context_manager_v1 *wlr_security_context_manager_v1_create( + struct wl_display *display) { + struct wlr_security_context_manager_v1 *manager = + reinterpret_cast(calloc(1, sizeof(*manager))); + if (manager == NULL) { + return NULL; + } + + manager->global = wl_global_create(display, + &wp_security_context_manager_v1_interface, + SECURITY_CONTEXT_MANAGER_V1_VERSION, manager, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + wl_list_init(&manager->contexts); + + wl_signal_init(&manager->events.destroy); + wl_signal_init(&manager->events.commit); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} + +const struct wlr_security_context_v1_state *wlr_security_context_manager_v1_lookup_client( + struct wlr_security_context_manager_v1 *manager, const struct wl_client *client) { + struct wl_listener *listener = wl_client_get_destroy_listener((struct wl_client *)client, + security_context_client_handle_destroy); + if (listener == NULL) { + return NULL; + } + + struct wlr_security_context_v1_client *security_context_client = + W_CONTAINER_OF(listener, wlr_security_context_v1_client, destroy); + return &security_context_client->state; +} +// End copy from wlroots +QT_WARNING_POP + +class Q_DECL_HIDDEN WSecurityContextManagerPrivate : public WObjectPrivate +{ +public: + WSecurityContextManagerPrivate(WSecurityContextManager *qq) + : WObjectPrivate(qq) + { + + } + + inline wlr_security_context_manager_v1 *handle() const { + return q_func()->nativeInterface(); + } + + W_DECLARE_PUBLIC(WSecurityContextManager) +}; + +WSecurityContextManager::~WSecurityContextManager() +{ + +} + +QByteArrayView WSecurityContextManager::interfaceName() const +{ + return "wp_security_context_manager_v1"; +} + +WSecurityContextManager::WSecurityContextManager() + : WObject(*new WSecurityContextManagerPrivate(this)) +{ + +} + +void WSecurityContextManager::create(WServer *server) +{ + m_handle = wlr_security_context_manager_v1_create(server->handle()); +} + +void WSecurityContextManager::destroy([[maybe_unused]] WServer *server) +{ + if (ownsSocket() && m_handle) + wlr_security_context_manager_v1_destroy(nativeInterface(), false); + + m_handle = nullptr; +} + +wl_global *WSecurityContextManager::global() const +{ + W_D(const WSecurityContextManager); + return d->handle() ? d->handle()->global : nullptr; +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wsecuritycontextmanager.h b/waylib/src/server/protocols/wsecuritycontextmanager.h new file mode 100644 index 0000000000..483bbb9b2e --- /dev/null +++ b/waylib/src/server/protocols/wsecuritycontextmanager.h @@ -0,0 +1,25 @@ +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WSecurityContextManagerPrivate; +class WAYLIB_SERVER_EXPORT WSecurityContextManager : public WObject, public WServerInterface +{ + W_DECLARE_PRIVATE(WSecurityContextManager) + +public: + WSecurityContextManager(); + ~WSecurityContextManager(); + QByteArrayView interfaceName() const override; + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wsessionlock.cpp b/waylib/src/server/protocols/wsessionlock.cpp new file mode 100644 index 0000000000..3f86a6bd14 --- /dev/null +++ b/waylib/src/server/protocols/wsessionlock.cpp @@ -0,0 +1,216 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wsessionlock.h" + +#include "wsessionlocksurface.h" +#include "wscoplistener.h" +#include "private/wglobal_p.h" + +#include + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class Q_DECL_HIDDEN WSessionLockPrivate : public WObjectPrivate +{ +public: + WSessionLockPrivate(WSessionLock *qq, wlr_session_lock_v1 *handle) + : WObjectPrivate(qq) + , m_handle(handle) + { + Q_ASSERT(handle); + handle->data = qq; + } + void setStatus(WSessionLock::LockState status) { + m_status = status; + } + // begin slot function + void onNewSurface(wlr_session_lock_surface_v1 *surface); + void onSurfaceDestroy(WSessionLockSurface *lockSurface); + // end slot function + + void lock(); + void finish(); + + inline wlr_session_lock_v1 *handle() const { + return m_handle; + } + + W_DECLARE_PUBLIC(WSessionLock) + + QVector surfaceList; + WSessionLock::LockState m_status{WSessionLock::LockState::Created}; + +private: + // The session-lock owner destroys this handle after notifying the + // wrapper. Keep the address stable through that callback. + wlr_session_lock_v1 *m_handle = nullptr; +}; + +void WSessionLockPrivate::onNewSurface(wlr_session_lock_surface_v1 *surface) +{ + W_Q(WSessionLock); + WSessionLockSurface *lockSurface = new WSessionLockSurface(surface); + // The lock created the surface, so it releases it (owner rule). + + // Register the destroy listener on the surface wrapper (owner = this + // lock): released automatically by ~WObject when the wrapper is deleted. + lockSurface->listeners(q_ptr)->add(&surface->events.destroy, this, + [this, lockSurface] (void *) { + // Detach our own listener group: wlr_session_lock_surface destroy + // asserts the listener lists are empty after emitting. Safe from + // inside a callback of this list (the closure outlives the emission). + lockSurface->removeListeners(q_ptr); + onSurfaceDestroy(lockSurface); + }); + + surfaceList.append(lockSurface); + Q_EMIT q->surfaceAdded(lockSurface); +} + +void WSessionLockPrivate::onSurfaceDestroy(WSessionLockSurface *lockSurface) +{ + W_Q(WSessionLock); + // invalidate() clears handle->data before invalidated() fires, so the + // reverse fromHandle() lookup would return null here; use the captured + // pointer instead. + bool ok = surfaceList.removeOne(lockSurface); + if (!ok) { + // surface may be removed by session lock + return; + } + Q_EMIT q->surfaceRemoved(lockSurface); + delete lockSurface; +} + +void WSessionLockPrivate::lock() +{ + W_Q(WSessionLock); + Q_ASSERT(m_status == WSessionLock::LockState::Created); + wlr_session_lock_v1_send_locked(m_handle); + m_status = WSessionLock::LockState::Locked; + Q_EMIT q->locked(); +} + +void WSessionLockPrivate::finish() +{ + W_Q(WSessionLock); + Q_ASSERT(m_status == WSessionLock::LockState::Created); + // wlr_session_lock_v1_destroy() synchronously emits the native destroy + // signal, from which the manager deletes this wrapper. Complete the + // state transition and notify observers BEFORE destroying: the destroy + // callback then observes Finished and emits nothing (no spurious + // canceled()). + m_status = WSessionLock::LockState::Finished; + // finished() is a synchronous Qt signal: a receiver may delete this + // wrapper inside the slot. Save the native handle and guard the wrapper + // before emitting so the destroy below never touches freed members. + auto *handle = m_handle; + QPointer guard(q); + Q_EMIT q->finished(); + if (!guard) + return; // wrapper deleted from the signal; the native lock is + // released with the client/display, no UAF on this side + wlr_session_lock_v1_destroy(handle); +} + +WSessionLock::WSessionLock(wlr_session_lock_v1 *handle) + : QObject(nullptr) + , WObject(*new WSessionLockPrivate(this, handle)) +{ + W_D(WSessionLock); + // connect new_surface and unlock signals + listeners()->add(&handle->events.new_surface, d, + &WSessionLockPrivate::onNewSurface); + listeners()->add(&handle->events.unlock, this, [d, this] (void *) { + Q_ASSERT(d->m_status == LockState::Locked); + Q_EMIT unlocked(); + }); + // State transition before the base class teardown listener (registered + // after this one) invalidates and deletes the wrapper. + listeners()->add(&handle->events.destroy, this, [d, this] (void *) { + switch (lockState()) { + case LockState::Created: + d->setStatus(LockState::Canceled); + Q_EMIT canceled(); + break; + case LockState::Locked: + d->setStatus(LockState::Abandoned); + Q_EMIT abandoned(); + break; + case LockState::Finished: + case LockState::Unlocked: + break; + default: + break; + } + }); + d->m_handle = handle; +} + +WSessionLock::~WSessionLock() +{ + teardown(); + W_D(WSessionLock); + // Clear the reverse fromHandle() mapping. The manager destroys this + // wrapper from the lock's destroy callback (or while the native handle + // is still alive), so the handle is valid here. + if (d->m_handle && d->m_handle->data == this) + d->m_handle->data = nullptr; + // Owner rule: this object created the WSessionLockSurface wrappers, + // release any that are still alive (each surface's listeners are + // released by its own ~WObject). + QVector list; + list.swap(d->surfaceList); + for (auto *surface : std::as_const(list)) { + Q_EMIT surfaceRemoved(surface); + delete surface; + } +} + +WSessionLock *WSessionLock::fromHandle(wlr_session_lock_v1 *handle) +{ + if (!handle) + return nullptr; + return static_cast(handle->data); +} + +wlr_session_lock_v1 *WSessionLock::handle() const +{ + W_DC(WSessionLock); + return d->handle(); +} + +QVector WSessionLock::surfaceList() const +{ + W_DC(WSessionLock); + return d->surfaceList; +} + +WSessionLock::LockState WSessionLock::lockState() const +{ + W_DC(WSessionLock); + return d->m_status; +} + +bool WSessionLock::isLocked() const +{ + return lockState() == LockState::Locked; +} + +void WSessionLock::lock() +{ + W_D(WSessionLock); + d->lock(); +} + +// Finish the lock (deny locking request) +void WSessionLock::finish() +{ + W_D(WSessionLock); + d->finish(); +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wsessionlock.h b/waylib/src/server/protocols/wsessionlock.h new file mode 100644 index 0000000000..9d4b9b6cf0 --- /dev/null +++ b/waylib/src/server/protocols/wsessionlock.h @@ -0,0 +1,56 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include "wglobal.h" + +Q_MOC_INCLUDE("wsessionlocksurface.h") + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WSessionLockSurface; +class WSessionLockPrivate; + +class WAYLIB_SERVER_EXPORT WSessionLock : public QObject, public WObject +{ + Q_OBJECT + W_DECLARE_PRIVATE(WSessionLock) + + Q_PROPERTY(LockState locked READ lockState); + + QML_NAMED_ELEMENT(WSessionLock) + QML_UNCREATABLE("Only create in C++") +public: + enum class LockState { + Created, + Locked, + Finished, + Unlocked, + Abandoned, + Canceled + }; + explicit WSessionLock(wlr_session_lock_v1 *handle); + ~WSessionLock(); + static WSessionLock *fromHandle(wlr_session_lock_v1 *handle); + + Q_INVOKABLE void lock(); + Q_INVOKABLE void finish(); + LockState lockState() const; + bool isLocked() const; + wlr_session_lock_v1 *handle() const; + + QVector surfaceList() const; +Q_SIGNALS: + void surfaceAdded(WSessionLockSurface *surface); + void surfaceRemoved(WSessionLockSurface *surface); + void locked(); + void unlocked(); + void finished(); + void abandoned(); + void canceled(); +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wsessionlockmanager.cpp b/waylib/src/server/protocols/wsessionlockmanager.cpp new file mode 100644 index 0000000000..cc9aa78574 --- /dev/null +++ b/waylib/src/server/protocols/wsessionlockmanager.cpp @@ -0,0 +1,117 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wsessionlockmanager.h" +#include "private/wglobal_p.h" +#include "wscoplistener.h" +#include "wsessionlock.h" + +#include +WAYLIB_SERVER_BEGIN_NAMESPACE + +class Q_DECL_HIDDEN WSessionLockManagerPrivate : public WObjectPrivate +{ +public: + WSessionLockManagerPrivate(WSessionLockManager *qq); + // begin slot function + void onNewLock(wlr_session_lock_v1 *lock); + void onLockDestroy(WSessionLock *lock); + // end slot function + + W_DECLARE_PUBLIC(WSessionLockManager) + + QVector lockList; +}; + +WSessionLockManagerPrivate::WSessionLockManagerPrivate(WSessionLockManager *qq) + : WObjectPrivate(qq) +{ + +} + +void WSessionLockManagerPrivate::onNewLock(wlr_session_lock_v1 *sessionLock) +{ + W_Q(WSessionLockManager); + auto lock = new WSessionLock(sessionLock); + // Register the destroy listener on the lock wrapper (owner = this + // manager): released automatically by ~WObject when the wrapper is + // deleted. + lock->listeners(q_ptr)->add(&sessionLock->events.destroy, this, + [this, lock] (void *) { + // Detach our own listener group: wlr_session_lock_v1 destroy + // asserts the listener lists are empty after emitting. Safe from + // inside a callback of this list (the closure outlives the emission). + lock->removeListeners(q_ptr); + onLockDestroy(lock); + }); + lockList.append(lock); + Q_EMIT q->lockCreated(lock); +} + +void WSessionLockManagerPrivate::onLockDestroy(WSessionLock *lock) +{ + W_Q(WSessionLockManager); + bool ok = lockList.removeOne(lock); + Q_ASSERT(ok); + Q_EMIT q->lockDestroyed(lock); + delete lock; +} + +WSessionLockManager::WSessionLockManager() : + QObject(nullptr), + WObject(*new WSessionLockManagerPrivate(this)) +{ +} + +QByteArrayView WSessionLockManager::interfaceName() const +{ + return "ext_session_lock_manager_v1"; +} + +wlr_session_lock_manager_v1 *WSessionLockManager::handle() const +{ + return reinterpret_cast(m_handle); +} + +void WSessionLockManager::create(WServer *server) +{ + W_D(WSessionLockManager); + + auto *session_lock_manager = wlr_session_lock_manager_v1_create(server->handle()); + Q_ASSERT(session_lock_manager); + listeners()->add(&session_lock_manager->events.new_lock, d, + &WSessionLockManagerPrivate::onNewLock); + m_handle = session_lock_manager; +} + +QVector WSessionLockManager::lockList() const +{ + W_DC(WSessionLockManager); + return d->lockList; +} + +void WSessionLockManager::destroy([[maybe_unused]] WServer *server) +{ + W_D(WSessionLockManager); + + auto lockList = d->lockList; + d->lockList.clear(); + for (auto lock : std::as_const(lockList)) { + Q_EMIT lockDestroyed(lock); + delete lock; + } + if (ownsSocket() && m_handle) + wlr_session_lock_manager_v1_destroy(nativeInterface(), false); + + m_handle = nullptr; +} + +wl_global *WSessionLockManager::global() const +{ + if (!m_handle) + return nullptr; + auto handle = reinterpret_cast(m_handle); + return handle->global; +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wsessionlockmanager.h b/waylib/src/server/protocols/wsessionlockmanager.h new file mode 100644 index 0000000000..ac71cff654 --- /dev/null +++ b/waylib/src/server/protocols/wsessionlockmanager.h @@ -0,0 +1,33 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include "wglobal.h" +#include "wserver.h" + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WSessionLock; +class WSessionLockManagerPrivate; +class WAYLIB_SERVER_EXPORT WSessionLockManager : public QObject, public WObject, public WServerInterface +{ + Q_OBJECT + W_DECLARE_PRIVATE(WSessionLockManager) +public: + explicit WSessionLockManager(); + void *create(); + + QByteArrayView interfaceName() const override; + wlr_session_lock_manager_v1 *handle() const; + QVector lockList() const; +Q_SIGNALS: + void lockCreated(WSessionLock *lock); + void lockDestroyed(WSessionLock *lock); +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wsessionlocksurface.cpp b/waylib/src/server/protocols/wsessionlocksurface.cpp new file mode 100644 index 0000000000..be139d199c --- /dev/null +++ b/waylib/src/server/protocols/wsessionlocksurface.cpp @@ -0,0 +1,166 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wsessionlocksurface.h" +#include "private/wtoplevelsurface_p.h" +#include "woutput.h" +#include "wscoplistener.h" +#include "wsurface.h" +#include "wtoplevelsurface.h" + +#include + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class Q_DECL_HIDDEN WSessionLockSurfacePrivate : public WToplevelSurfacePrivate { +public: + WSessionLockSurfacePrivate(WSessionLockSurface *qq, wlr_session_lock_surface_v1 *handle); + ~WSessionLockSurfacePrivate(); + + inline wlr_session_lock_surface_v1 *handle() const { + return m_handle; + } + + wl_client *waylandClient() const override { + return handle()->resource->client; + } + + // begin slot function + // end slot function + + void init(); + + W_DECLARE_PUBLIC(WSessionLockSurface) + + WSurface *surface = nullptr; + WOutput *output = nullptr; + +private: + // The session-lock owner destroys this handle after notifying the + // wrapper. Keep the address stable through that callback. + wlr_session_lock_surface_v1 *m_handle = nullptr; +}; + +WSessionLockSurfacePrivate::WSessionLockSurfacePrivate(WSessionLockSurface *qq, wlr_session_lock_surface_v1 *handle) + : WToplevelSurfacePrivate(qq) +{ + Q_ASSERT(handle); + handle->data = qq; + m_handle = handle; +} + +WSessionLockSurfacePrivate::~WSessionLockSurfacePrivate() +{ + +} + +void WSessionLockSurfacePrivate::init() { + W_Q(WSessionLockSurface); + Q_ASSERT(!q->surface()); + surface = new WSurface(m_handle->surface); + surface->setAttachedData(q); + + output = handle()->output ? WOutput::fromHandle(handle()->output) : nullptr; +} + +WSessionLockSurface::WSessionLockSurface(wlr_session_lock_surface_v1 *handle) + : WToplevelSurface(*new WSessionLockSurfacePrivate(this, handle)) +{ + d_func()->init(); +} + +WSessionLockSurface::~WSessionLockSurface() +{ + teardown(); + // Notify listeners while the object is still usable (its members are + // alive during the destructor body). + Q_EMIT beforeDestroy(); + // Owner rule: this object created the WSurface wrapper, release it. + W_D(WSessionLockSurface); + // Clear the reverse fromHandle() mapping. The lock destroys this wrapper + // from the lock surface's destroy callback (or while the native handle + // is still alive), so the handle is valid here. + if (d->m_handle && d->m_handle->data == this) + d->m_handle->data = nullptr; + delete d->surface; +} + +bool WSessionLockSurface::hasCapability(Capability cap) const +{ + switch (cap) { + using enum Capability; + case Focus: + return true; + case Activate: + case Maximized: + case FullScreen: + case Resize: + return false; + default: + break; + } + Q_UNREACHABLE(); +} + +wlr_session_lock_surface_v1 *WSessionLockSurface::handle() const +{ + W_DC(WSessionLockSurface); + return d->handle(); +} + +WSessionLockSurface *WSessionLockSurface::fromHandle(wlr_session_lock_surface_v1 *handle) +{ + if (!handle) + return nullptr; + return static_cast(handle->data); +} + +WSessionLockSurface *WSessionLockSurface::fromSurface(WSurface *surface) +{ + return surface->getAttachedData(); +} + +WSurface *WSessionLockSurface::surface() const +{ + W_DC(WSessionLockSurface); + return d->surface; +} + +WOutput *WSessionLockSurface::output() const +{ + W_DC(WSessionLockSurface); + return d->output; +} + +int WSessionLockSurface::keyboardFocusPriority() const +{ + return std::numeric_limits::max(); +} + +uint32_t WSessionLockSurface::configureSize(const QSize &newSize) +{ + return wlr_session_lock_surface_v1_configure(handle(), newSize.width(), newSize.height()); +} + +void WSessionLockSurface::resize(const QSize &size) +{ + configureSize(size); +} + +bool WSessionLockSurface::checkNewSize(const QSize &size, QSize *clippedSize) +{ + // Session lock surfaces should accept any size, as they need to cover the entire output + if (clippedSize) + *clippedSize = size; + return true; +} + +QRect WSessionLockSurface::getContentGeometry() const +{ + W_DC(WSessionLockSurface); + return QRect(0, 0, d->handle()->current.width, d->handle()->current.height); +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wsessionlocksurface.h b/waylib/src/server/protocols/wsessionlocksurface.h new file mode 100644 index 0000000000..eed882e90f --- /dev/null +++ b/waylib/src/server/protocols/wsessionlocksurface.h @@ -0,0 +1,49 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include "wglobal.h" +#include "woutput.h" +#include "wtoplevelsurface.h" + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WSessionLockSurfacePrivate; +class WAYLIB_SERVER_EXPORT WSessionLockSurface : public WToplevelSurface +{ + Q_OBJECT + W_DECLARE_PRIVATE(WSessionLockSurface) + Q_PROPERTY(WSurface *surface READ surface NOTIFY surfaceChanged) + Q_PROPERTY(WOutput *output READ output CONSTANT) // constant in wlr_layershell_v1 + + QML_NAMED_ELEMENT(WSessionLockSurface) + QML_UNCREATABLE("Only create in C++") +public: + explicit WSessionLockSurface(wlr_session_lock_surface_v1 *handle); + ~WSessionLockSurface(); + + bool hasCapability(Capability cap) const override; + + WSurface *surface() const override; + + wlr_session_lock_surface_v1 *handle() const; + + static WSessionLockSurface *fromHandle(wlr_session_lock_surface_v1 *handle); + static WSessionLockSurface *fromSurface(WSurface *surface); + + QRect getContentGeometry() const override; + void resize(const QSize &size) override; + int keyboardFocusPriority() const override; + + Q_INVOKABLE uint32_t configureSize(const QSize &newSize); + + WOutput *output() const; +Q_SIGNALS: + void surfaceChanged(); +public Q_SLOTS: + bool checkNewSize(const QSize &size, QSize *clippedSize) override; +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wxdgdecorationmanager.cpp b/waylib/src/server/protocols/wxdgdecorationmanager.cpp index 78fe3d9464..26d789f284 100644 --- a/waylib/src/server/protocols/wxdgdecorationmanager.cpp +++ b/waylib/src/server/protocols/wxdgdecorationmanager.cpp @@ -1,18 +1,19 @@ -// Copyright (C) 2023 rewine . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wxdgdecorationmanager.h" #include "wsurface.h" +#include "wayliblogging.h" #include "private/wglobal_p.h" +#include "wscoplistener.h" -#include -#include +#include + +#include +#include -WAYLIB_SERVER_BEGIN_NAMESPACE -using QW_NAMESPACE::qw_xdg_decoration_manager_v1; -using QW_NAMESPACE::qw_xdg_toplevel_decoration_v1; -static WXdgDecorationManager *XDG_DECORATION_MANAGER = nullptr; +WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WXdgDecorationManagerPrivate : public WObjectPrivate { @@ -24,49 +25,97 @@ class Q_DECL_HIDDEN WXdgDecorationManagerPrivate : public WObjectPrivate } // begin slot function - void onNewToplevelDecoration(qw_xdg_toplevel_decoration_v1 *decorat); + void onNewToplevelDecoration(wlr_xdg_toplevel_decoration_v1 *decorat); // end slot function - void updateDecorationMode(qw_xdg_toplevel_decoration_v1 *decorat); + void updateDecorationMode(wlr_xdg_toplevel_decoration_v1 *decorat); WXdgDecorationManager::DecorationMode modeBySurface(WSurface *surface) const { return decorations.value(surface, WXdgDecorationManager::Undefined); } - inline qw_xdg_decoration_manager_v1 *handle() const { - return q_func()->nativeInterface(); - } - - inline wlr_xdg_decoration_manager_v1 *nativeHandle() const { - Q_ASSERT(handle()); - return handle()->handle(); + inline wlr_xdg_decoration_manager_v1 *handle() const { + return reinterpret_cast(q_func()->m_handle); } W_DECLARE_PUBLIC(WXdgDecorationManager) WXdgDecorationManager::DecorationMode preferredMode = WXdgDecorationManager::Server; QMap decorations; + + // Per-decoration WListenerOwner: decoration signals are registered on + // the owner token (not the surface). Manager owns each group via + // owner->listeners(q), so items stay isolated and manager teardown + // clears them through the cross-object listener graph. + struct DecorationListeners { + wlr_xdg_toplevel_decoration_v1 *decoration = nullptr; + std::unique_ptr owner; + // Fires once the toplevel initializes. + QMetaObject::Connection initConnection; + }; + std::vector decorationListeners; }; -void WXdgDecorationManagerPrivate::onNewToplevelDecoration(qw_xdg_toplevel_decoration_v1 *decorat) +void WXdgDecorationManagerPrivate::onNewToplevelDecoration(wlr_xdg_toplevel_decoration_v1 *decorat) { W_Q(WXdgDecorationManager); - QObject::connect(decorat, - &qw_xdg_toplevel_decoration_v1::notify_request_mode, - q, - [decorat, this]() { - this->updateDecorationMode(decorat); - }); - /* For some reason, a lot of clients don't emit the request_mode signal. */ - updateDecorationMode(decorat); + auto *surface = WSurface::fromHandle(decorat->toplevel->base->surface); + if (!surface) + return; + + DecorationListeners entry; + entry.decoration = decorat; + entry.owner = std::make_unique(); + auto *owner = entry.owner.get(); + + // Listen to decoration signals on the owner token; q (the manager) owns + // the group so teardown()/removeListeners(q) detaches without touching + // other decorations' owners. + owner->listeners(q)->add(&decorat->events.request_mode, this, + [decorat, this] (void *) { + updateDecorationMode(decorat); + }); + owner->listeners(q)->add(&decorat->events.destroy, this, + [this, decorat, surface, owner, q] (void *) { + // Drop our own entry: safe from inside a callback of this list + // (the closure outlives the emission); the request_mode listener + // goes with it. wlr_xdg_toplevel_decoration destroy asserts the + // listener lists are empty after emitting. + if (decorations.contains(surface)) + decorations.remove(surface); + owner->removeListeners(q); + for (auto it = decorationListeners.begin(); it != decorationListeners.end(); ++it) { + if (it->decoration == decorat) { + QObject::disconnect(it->initConnection); + decorationListeners.erase(it); + break; + } + } + }); + decorationListeners.push_back(std::move(entry)); + auto &storedEntry = decorationListeners.back(); + + // set_mode() asserts surface->initialized. Clients like alacritty send + // set_mode before the first commit; defer it to the commit where the + // toplevel initializes, otherwise they never get a configure and draw a + // second titlebar. + if (!decorat->toplevel->base->initialized) { + storedEntry.initConnection = + QObject::connect(surface, &WSurface::commit, q, [decorat, this] (quint32) { + updateDecorationMode(decorat); + }, Qt::SingleShotConnection); + } else { + /* For some reason, a lot of clients don't emit the request_mode signal. */ + updateDecorationMode(decorat); + } } -void WXdgDecorationManagerPrivate::updateDecorationMode(qw_xdg_toplevel_decoration_v1 *decorat) +void WXdgDecorationManagerPrivate::updateDecorationMode(wlr_xdg_toplevel_decoration_v1 *decorat) { W_Q(WXdgDecorationManager); - auto *surface = WSurface::fromHandle(decorat->handle()->toplevel->base->surface); + auto *surface = WSurface::fromHandle(decorat->toplevel->base->surface); WXdgDecorationManager::DecorationMode mode = WXdgDecorationManager::Undefined; - switch (decorat->handle()->requested_mode) { + switch (decorat->requested_mode) { case WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_NONE: mode = WXdgDecorationManager::None; break; @@ -78,26 +127,25 @@ void WXdgDecorationManagerPrivate::updateDecorationMode(qw_xdg_toplevel_decorati break; default: Q_UNREACHABLE(); - break; } if (mode == WXdgDecorationManager::None) { mode = preferredMode; - switch (preferredMode) { + } + decorations.insert(surface, mode); + + // Emit the configure the client waits for; requires an initialized + // toplevel, otherwise the commit listener above re-runs us later. + if (decorat->toplevel->base->initialized) { + switch (mode) { case WXdgDecorationManager::Client: - if (decorat->handle()->toplevel->base->initialized) - decorat->set_mode(WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE); + wlr_xdg_toplevel_decoration_v1_set_mode(decorat, WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE); break; case WXdgDecorationManager::Server: - if (decorat->handle()->toplevel->base->initialized) - decorat->set_mode(WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE); + wlr_xdg_toplevel_decoration_v1_set_mode(decorat, WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE); break; default: Q_UNREACHABLE(); - break; } - decorations.insert(surface, preferredMode); - } else { - decorations.insert(surface, mode); } Q_EMIT q->surfaceModeChanged(surface, mode); @@ -105,27 +153,34 @@ void WXdgDecorationManagerPrivate::updateDecorationMode(qw_xdg_toplevel_decorati WXdgDecorationManager::WXdgDecorationManager() :WObject(*new WXdgDecorationManagerPrivate(this)) -{ - if (XDG_DECORATION_MANAGER) { - qFatal("There are multiple instances of WQuickXdgDecorationManager"); - } +{} - XDG_DECORATION_MANAGER = this; +WXdgDecorationManager::~WXdgDecorationManager() +{ + teardown(); } void WXdgDecorationManager::create(WServer *server) { W_D(WXdgDecorationManager); - m_handle = qw_xdg_decoration_manager_v1::create(*server->handle()); - connect(d->handle(), &qw_xdg_decoration_manager_v1::notify_new_toplevel_decoration, this, [d](wlr_xdg_toplevel_decoration_v1 *decorat) { - d->onNewToplevelDecoration(qw_xdg_toplevel_decoration_v1::from(decorat)); - }); + m_handle = wlr_xdg_decoration_manager_v1_create(server->handle()); + listeners()->add(&d->handle()->events.new_toplevel_decoration, d, + &WXdgDecorationManagerPrivate::onNewToplevelDecoration); } -void WXdgDecorationManager::destroy(WServer *server) +void WXdgDecorationManager::destroy([[maybe_unused]] WServer *server) { - Q_UNUSED(server); + W_D(WXdgDecorationManager); + // Manager-owned listeners were already dropped by WServer teardown. + // Clearing decorationListeners destroys per-decoration WListenerOwner + // tokens (their dtors teardown surface-scoped groups). + d->decorationListeners.clear(); + d->decorations.clear(); + if (ownsSocket() && m_handle) + wlr_xdg_decoration_manager_v1_destroy(nativeInterface(), false); + + m_handle = nullptr; } wl_global *WXdgDecorationManager::global() const @@ -133,7 +188,7 @@ wl_global *WXdgDecorationManager::global() const W_D(const WXdgDecorationManager); if (m_handle) - return d->nativeHandle()->global; + return d->handle()->global; return nullptr; } @@ -151,7 +206,7 @@ void WXdgDecorationManager::setPreferredMode(DecorationMode mode) return; } if (d->preferredMode == DecorationMode::Undefined || d->preferredMode == DecorationMode::None) { - qWarning("Prefer mode must be 'Client' or 'Server'"); + qCWarning(lcWlXdgDecoration, "Prefer mode must be 'Client' or 'Server'"); return; } // update all existing decoration that mode changed @@ -172,19 +227,18 @@ void WXdgDecorationManager::setModeBySurface(WSurface *surface, DecorationMode m } if (d->handle()) { - wlr_xdg_decoration_manager_v1 *wlr_manager = d->nativeHandle(); + wlr_xdg_decoration_manager_v1 *wlr_manager = d->handle(); wlr_xdg_toplevel_decoration_v1 *wlr_decorations; wl_list_for_each(wlr_decorations, &wlr_manager->decorations, link) { if (WSurface::fromHandle(wlr_decorations->toplevel->base->surface) == surface) { - auto * decorat = qw_xdg_toplevel_decoration_v1::from(wlr_decorations); switch (mode) { case WXdgDecorationManager::Client: - if (decorat->handle()->toplevel->base->initialized) - decorat->set_mode(WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE); + if (wlr_decorations->toplevel->base->initialized) + wlr_xdg_toplevel_decoration_v1_set_mode(wlr_decorations, WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_CLIENT_SIDE); break; case WXdgDecorationManager::Server: - if (decorat->handle()->toplevel->base->initialized) - decorat->set_mode(WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE); + if (wlr_decorations->toplevel->base->initialized) + wlr_xdg_toplevel_decoration_v1_set_mode(wlr_decorations, WLR_XDG_TOPLEVEL_DECORATION_V1_MODE_SERVER_SIDE); break; default: Q_UNREACHABLE(); @@ -207,4 +261,9 @@ QByteArrayView WXdgDecorationManager::interfaceName() const return "zxdg_decoration_manager_v1"; } +wlr_xdg_decoration_manager_v1 *WXdgDecorationManager::handle() const +{ + return reinterpret_cast(m_handle); +} + WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wxdgdecorationmanager.h b/waylib/src/server/protocols/wxdgdecorationmanager.h index d2c900625a..b3f0322871 100644 --- a/waylib/src/server/protocols/wxdgdecorationmanager.h +++ b/waylib/src/server/protocols/wxdgdecorationmanager.h @@ -1,4 +1,4 @@ -// Copyright (C) 2023 rewine . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once @@ -22,6 +22,7 @@ class WAYLIB_SERVER_EXPORT WXdgDecorationManager : public QObject, public WObjec public: explicit WXdgDecorationManager(); + ~WXdgDecorationManager() override; enum DecorationMode { Undefined, // client not send any mode @@ -38,6 +39,7 @@ class WAYLIB_SERVER_EXPORT WXdgDecorationManager : public QObject, public WObjec Q_INVOKABLE DecorationMode modeBySurface(WAYLIB_SERVER_NAMESPACE::WSurface* surface) const; QByteArrayView interfaceName() const override; + wlr_xdg_decoration_manager_v1 *handle() const; Q_SIGNALS: void surfaceModeChanged(WAYLIB_SERVER_NAMESPACE::WSurface *surface, DecorationMode mode); diff --git a/waylib/src/server/protocols/wxdgdialogmanagerv1.cpp b/waylib/src/server/protocols/wxdgdialogmanagerv1.cpp new file mode 100644 index 0000000000..ecd29bed6c --- /dev/null +++ b/waylib/src/server/protocols/wxdgdialogmanagerv1.cpp @@ -0,0 +1,162 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wxdgdialogmanagerv1.h" + +#include "private/wglobal_p.h" +#include "wscoplistener.h" +#include "wayliblogging.h" +#include "wxdgtoplevelsurface.h" + +#include + +#include + +#include +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class Q_DECL_HIDDEN WXdgDialogManagerV1Private : public WObjectPrivate +{ +public: + WXdgDialogManagerV1Private(WXdgDialogManagerV1 *qq) + : WObjectPrivate(qq) + { + } + + inline wlr_xdg_wm_dialog_v1 *handle() const + { + return reinterpret_cast(q_func()->m_handle); + } + + void onNewDialog(wlr_xdg_dialog_v1 *dialog); + + W_DECLARE_PUBLIC(WXdgDialogManagerV1) + + // Per-dialog WListenerOwner: dialog signals are registered on the + // owner token (not the surface). Manager owns each group via + // owner->listeners(q), so items stay isolated and manager teardown + // clears them through the cross-object listener graph. + struct DialogListeners { + wlr_xdg_dialog_v1 *dialog = nullptr; + std::unique_ptr owner; + }; + std::vector dialogListeners; +}; + +void WXdgDialogManagerV1Private::onNewDialog(wlr_xdg_dialog_v1 *nativeDialog) +{ + W_Q(WXdgDialogManagerV1); + + auto *surface = WXdgToplevelSurface::fromHandle(nativeDialog->xdg_toplevel); + if (!surface) { + qCWarning(lcWlXdgDialog) << "Failed to get WXdgToplevelSurface from" << nativeDialog->xdg_toplevel; + return; + } + + qCDebug(lcWlXdgDialog) << "New xdg_dialog_v1 for surface:" << surface + << "initial modal:" << nativeDialog->modal; + + // Wrap in QPointer to guard against toplevel being destroyed before the dialog. + // surface is a WXdgToplevelSurface* (QObject*), so QPointer safely nulls when destroyed. + QPointer surfaceGuard(surface); + + // Sync the initial modal state (client may have called set_modal before we connect) + if (nativeDialog->modal && surfaceGuard) + Q_EMIT q->surfaceModalChanged(surfaceGuard, true); + + DialogListeners entry; + entry.dialog = nativeDialog; + entry.owner = std::make_unique(); + auto *owner = entry.owner.get(); + + // Listen to dialog signals on the owner token; q (the manager) owns the + // group so teardown()/removeListeners(q) detaches without touching other + // dialogs' owners. + // Track future set_modal / unset_modal calls. Both requests fire the set_modal event. + owner->listeners(q)->add(&nativeDialog->events.set_modal, this, + [q, nativeDialog, surfaceGuard] (void *) { + if (!surfaceGuard) + return; + qCDebug(lcWlXdgDialog) << "xdg_dialog_v1 modal changed:" << surfaceGuard + << "->" << nativeDialog->modal; + Q_EMIT q->surfaceModalChanged(surfaceGuard, nativeDialog->modal); + }); + + // When the dialog object is destroyed, reset modal if it was set. + // Protocol: "If this object is destroyed before the related xdg_toplevel, + // the compositor should unapply its effects." + owner->listeners(q)->add(&nativeDialog->events.destroy, this, + [this, q, nativeDialog, surfaceGuard, owner] (void *) { + if (nativeDialog->modal && surfaceGuard) { + qCDebug(lcWlXdgDialog) + << "xdg_dialog_v1 destroyed while modal, resetting:" + << surfaceGuard; + Q_EMIT q->surfaceModalChanged(surfaceGuard, false); + } + owner->removeListeners(q); + for (auto it = dialogListeners.begin(); it != dialogListeners.end(); ++it) { + if (it->dialog == nativeDialog) { + dialogListeners.erase(it); + break; + } + } + }); + dialogListeners.push_back(std::move(entry)); +} + +WXdgDialogManagerV1::WXdgDialogManagerV1(QObject *parent) + : QObject(parent) + , WObject(*new WXdgDialogManagerV1Private(this)) +{ +} + +WXdgDialogManagerV1::~WXdgDialogManagerV1() +{ + teardown(); +} + +QByteArrayView WXdgDialogManagerV1::interfaceName() const +{ + return "xdg_wm_dialog_v1"; +} + +wlr_xdg_wm_dialog_v1 *WXdgDialogManagerV1::handle() const +{ + return reinterpret_cast(m_handle); +} + +void WXdgDialogManagerV1::create(WServer *server) +{ + auto *wm = wlr_xdg_wm_dialog_v1_create(server->handle(), InterfaceVersion); + m_handle = wm; + + W_D(WXdgDialogManagerV1); + listeners()->add(&wm->events.new_dialog, this, [this](wlr_xdg_dialog_v1 *dialog) { + W_D(WXdgDialogManagerV1); + d->onNewDialog(dialog); + }); +} + +void WXdgDialogManagerV1::destroy([[maybe_unused]] WServer *server) +{ + W_D(WXdgDialogManagerV1); + // Manager-owned listeners were already dropped by WServer teardown. + // Clearing dialogListeners destroys per-dialog WListenerOwner tokens. + d->dialogListeners.clear(); + if (ownsSocket() && m_handle) + wlr_xdg_wm_dialog_v1_destroy(nativeInterface(), false); + + m_handle = nullptr; +} + +wl_global *WXdgDialogManagerV1::global() const +{ + W_DC(WXdgDialogManagerV1); + if (!d->handle()) + return nullptr; + return d->handle()->global; +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wxdgdialogmanagerv1.h b/waylib/src/server/protocols/wxdgdialogmanagerv1.h new file mode 100644 index 0000000000..03b877003f --- /dev/null +++ b/waylib/src/server/protocols/wxdgdialogmanagerv1.h @@ -0,0 +1,42 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +#include + +Q_MOC_INCLUDE("wxdgtoplevelsurface.h") + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WXdgToplevelSurface; +class WXdgDialogManagerV1Private; + +class WAYLIB_SERVER_EXPORT WXdgDialogManagerV1 + : public QObject + , public WObject + , public WServerInterface +{ + Q_OBJECT + W_DECLARE_PRIVATE(WXdgDialogManagerV1) + +public: + explicit WXdgDialogManagerV1(QObject *parent = nullptr); + ~WXdgDialogManagerV1() override; + + QByteArrayView interfaceName() const override; + wlr_xdg_wm_dialog_v1 *handle() const; + + static constexpr int InterfaceVersion = 1; +Q_SIGNALS: + void surfaceModalChanged(WAYLIB_SERVER_NAMESPACE::WXdgToplevelSurface *surface, bool modal); + +protected: + void create(WServer *server) override; + void destroy(WServer *server) override; + wl_global *global() const override; +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wxdgoutput.cpp b/waylib/src/server/protocols/wxdgoutput.cpp index 18c7f8859a..a9a449c811 100644 --- a/waylib/src/server/protocols/wxdgoutput.cpp +++ b/waylib/src/server/protocols/wxdgoutput.cpp @@ -1,24 +1,29 @@ -// Copyright (C) 2024 Lu YaNing . +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wxdgoutput.h" +#include "woutput.h" #include "woutputlayout.h" #include "wsocket.h" +#include "wayliblogging.h" #include "private/wglobal_p.h" #include "xdg-output-unstable-v1-protocol.h" #include +#include #include #include #include +#include -#include -#include -#include +#include #include +// wlroots keeps this helper in an internal header. +extern "C" void wlr_global_destroy_safe(struct wl_global *global); + // Copy from wlroots #define OUTPUT_MANAGER_VERSION 3 #define OUTPUT_DONE_DEPRECATED_SINCE_VERSION 3 @@ -86,20 +91,26 @@ static void output_update(struct way_xdg_output_v1 *xdg_output) { struct wlr_output_layout_output *layout_output = xdg_output->layout_output; bool updated = false; - if (layout_output->x != xdg_output->x || layout_output->y != xdg_output->y) { - xdg_output->x = layout_output->x; - xdg_output->y = layout_output->y; + int32_t x, y; + if (xdg_output->manager->scale_override > 0.0) { + x = static_cast(std::floor(layout_output->x * xdg_output->manager->scale_override)); + y = static_cast(std::floor(layout_output->y * xdg_output->manager->scale_override)); + } else { + x = layout_output->x; + y = layout_output->y; + } + + if (x != xdg_output->x || y != xdg_output->y) { + xdg_output->x = x; + xdg_output->y = y; updated = true; } int width, height; + wlr_output_effective_resolution(layout_output->output, &width, &height); if (xdg_output->manager->scale_override > 0.0) { - wlr_output_transformed_resolution(layout_output->output, &width, &height); - - width /= xdg_output->manager->scale_override; - height /= xdg_output->manager->scale_override; - } else { - wlr_output_effective_resolution(layout_output->output, &width, &height); + width = static_cast(std::ceil(width * xdg_output->manager->scale_override)); + height = static_cast(std::ceil(height * xdg_output->manager->scale_override)); } if (xdg_output->width != width || xdg_output->height != height) { @@ -141,7 +152,6 @@ static void output_manager_handle_get_xdg_output(struct wl_client *client, struct wl_resource *output_resource) { struct way_xdg_output_manager_v1 *manager = static_cast(wl_resource_get_user_data(resource)); - struct wlr_output_layout *layout = manager->layout; struct wlr_output *output = wlr_output_from_resource(output_resource); struct wl_resource *xdg_output_resource = wl_resource_create(client, @@ -153,13 +163,13 @@ static void output_manager_handle_get_xdg_output(struct wl_client *client, wl_resource_set_implementation(xdg_output_resource, &output_implementation, NULL, output_handle_resource_destroy); - if (output == NULL) { + if (manager == NULL || output == NULL) { wl_list_init(wl_resource_get_link(xdg_output_resource)); return; } struct wlr_output_layout_output *layout_output = - wlr_output_layout_get(layout, output); + wlr_output_layout_get(manager->layout, output); assert(layout_output); struct way_xdg_output_v1 *_xdg_output, *xdg_output = NULL; @@ -217,7 +227,7 @@ static void output_manager_bind(struct wl_client *wl_client, void *data, static void handle_output_destroy(struct wl_listener *listener, void *data) { UNUSED(data); - struct way_xdg_output_v1 *output = wl_container_of(listener, output, destroy); + struct way_xdg_output_v1 *output = W_CONTAINER_OF(listener, way_xdg_output_v1, destroy); output_destroy(output); } @@ -225,7 +235,7 @@ static void handle_output_description(struct wl_listener *listener, void *data) { UNUSED(data); struct way_xdg_output_v1 *xdg_output = - wl_container_of(listener, xdg_output, description); + W_CONTAINER_OF(listener, way_xdg_output_v1, description); struct wlr_output *output = xdg_output->layout_output->output; if (output->description == NULL) { @@ -270,7 +280,7 @@ static void output_manager_send_details( static void handle_layout_add(struct wl_listener *listener, void *data) { struct way_xdg_output_manager_v1 *manager = - wl_container_of(listener, manager, layout_add); + W_CONTAINER_OF(listener, way_xdg_output_manager_v1, layout_add); struct wlr_output_layout_output *layout_output = static_cast(data); add_output(manager, layout_output); @@ -279,11 +289,12 @@ static void handle_layout_add(struct wl_listener *listener, void *data) { static void handle_layout_change(struct wl_listener *listener, void *data) { UNUSED(data); struct way_xdg_output_manager_v1 *manager = - wl_container_of(listener, manager, layout_change); + W_CONTAINER_OF(listener, way_xdg_output_manager_v1, layout_change); output_manager_send_details(manager); } -static void manager_destroy(struct way_xdg_output_manager_v1 *manager) { +static void manager_destroy(struct way_xdg_output_manager_v1 *manager, + bool destroy_global_safe) { struct way_xdg_output_v1 *output, *tmp; wl_list_for_each_safe(output, tmp, &manager->outputs, link) { output_destroy(output); @@ -293,21 +304,31 @@ static void manager_destroy(struct way_xdg_output_manager_v1 *manager) { wl_list_remove(&manager->layout_add.link); wl_list_remove(&manager->layout_change.link); wl_list_remove(&manager->layout_destroy.link); + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } free(manager); } +static void way_xdg_output_manager_v1_destroy(struct way_xdg_output_manager_v1 *manager, + bool destroy_global_safe) { + manager_destroy(manager, destroy_global_safe); +} + static void handle_layout_destroy(struct wl_listener *listener, void *data) { UNUSED(data); struct way_xdg_output_manager_v1 *manager = - wl_container_of(listener, manager, layout_destroy); - manager_destroy(manager); + W_CONTAINER_OF(listener, way_xdg_output_manager_v1, layout_destroy); + way_xdg_output_manager_v1_destroy(manager, true); } static void handle_display_destroy(struct wl_listener *listener, void *data) { UNUSED(data); struct way_xdg_output_manager_v1 *manager = - wl_container_of(listener, manager, display_destroy); - manager_destroy(manager); + W_CONTAINER_OF(listener, way_xdg_output_manager_v1, display_destroy); + manager_destroy(manager, false); } static struct way_xdg_output_manager_v1 *way_xdg_output_manager_v1_create( @@ -351,8 +372,6 @@ static struct way_xdg_output_manager_v1 *way_xdg_output_manager_v1_create( WAYLIB_SERVER_BEGIN_NAMESPACE -using QW_NAMESPACE::qw_xdg_output_manager_v1; - class Q_DECL_HIDDEN WXdgOutputManagerPrivate : public WObjectPrivate { public: @@ -403,10 +422,25 @@ qreal WXdgOutputManager::scaleOverride() const void WXdgOutputManager::resetScaleOverride() { - Q_D(WXdgOutputManager); setScaleOverride(0.0); } +QRect WXdgOutputManager::outputGeometry(WOutput *output) const +{ + W_DC(WXdgOutputManager); + auto *layoutOutput = wlr_output_layout_get(d->layout->handle(), output->handle()); + + int width = 0; + int height = 0; + wlr_output_effective_resolution(layoutOutput->output, &width, &height); + + const qreal scale = d->scaleOverride > 0.0 ? d->scaleOverride : 1.0; + return QRect(qFloor(layoutOutput->x * scale), + qFloor(layoutOutput->y * scale), + qCeil(width * scale), + qCeil(height * scale)); +} + QByteArrayView WXdgOutputManager::interfaceName() const { return "zxdg_output_manager_v1"; @@ -419,10 +453,12 @@ WOutputLayout *WXdgOutputManager::layout() const return d->layout; } -void WXdgOutputManager::destroy(WServer *server) +void WXdgOutputManager::destroy([[maybe_unused]] WServer *server) { - Q_UNUSED(server); W_D(WXdgOutputManager); + if (ownsSocket() && m_handle) + way_xdg_output_manager_v1_destroy(nativeInterface(), false); + d->manager = nullptr; m_handle = nullptr; } @@ -430,20 +466,19 @@ void WXdgOutputManager::destroy(WServer *server) wl_global *WXdgOutputManager::global() const { auto handle = nativeInterface(); - return handle->global; + return handle ? handle->global : nullptr; } -void WXdgOutputManager::create(WServer *wserver) +void WXdgOutputManager::create([[maybe_unused]] WServer *wserver) { - Q_UNUSED(wserver) W_D(WXdgOutputManager); if (d->layout) { - d->manager = way_xdg_output_manager_v1_create(*server()->handle(), - *d->layout->handle(), - d->scaleOverride); + d->manager = way_xdg_output_manager_v1_create(server()->handle(), + d->layout->handle(), + d->scaleOverride); m_handle = d->manager; } else { - qWarning() << "Output layout not set, xdg output manager will never be created!"; + qCWarning(lcWlXdgOutput) << "Output layout not set, xdg output manager will never be created!"; } } diff --git a/waylib/src/server/protocols/wxdgoutput.h b/waylib/src/server/protocols/wxdgoutput.h index e979cb42b6..ca88d49fbd 100644 --- a/waylib/src/server/protocols/wxdgoutput.h +++ b/waylib/src/server/protocols/wxdgoutput.h @@ -5,9 +5,12 @@ #include +#include + WAYLIB_SERVER_BEGIN_NAMESPACE class WOutputLayout; +class WOutput; class WXdgOutputManagerPrivate; class WAYLIB_SERVER_EXPORT WXdgOutputManager : public QObject, public WObject, public WServerInterface { @@ -22,6 +25,7 @@ class WAYLIB_SERVER_EXPORT WXdgOutputManager : public QObject, public WObject, p void setScaleOverride(qreal scaleOverride); qreal scaleOverride() const; void resetScaleOverride(); + QRect outputGeometry(WOutput *output) const; QByteArrayView interfaceName() const override; diff --git a/waylib/src/server/protocols/wxdgpopupsurface.cpp b/waylib/src/server/protocols/wxdgpopupsurface.cpp index 724f0208b8..56a673abc9 100644 --- a/waylib/src/server/protocols/wxdgpopupsurface.cpp +++ b/waylib/src/server/protocols/wxdgpopupsurface.cpp @@ -1,42 +1,48 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wxdgpopupsurface.h" #include "private/wtoplevelsurface_p.h" +#include "wscoplistener.h" -#include -#include -#include +#include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WXdgPopupSurfacePrivate : public WToplevelSurfacePrivate { public: - WXdgPopupSurfacePrivate(WXdgPopupSurface *qq, qw_xdg_popup *handle); + WXdgPopupSurfacePrivate(WXdgPopupSurface *qq, wlr_xdg_popup *handle); ~WXdgPopupSurfacePrivate(); - WWRAP_HANDLE_FUNCTIONS(qw_xdg_popup, wlr_xdg_popup) + inline wlr_xdg_popup *handle() const { + return m_handle; + } wl_client *waylandClient() const override { - return nativeHandle()->base->client->client; + return handle()->base->client->client; } void init(); void connect(); - void instantRelease() override; - W_DECLARE_PUBLIC(WXdgPopupSurface) WSurface *surface = nullptr; QPointF position; + +private: + // The xdg owner destroys this handle after notifying the wrapper. + // Keep the address stable through that callback. + wlr_xdg_popup *m_handle = nullptr; }; -WXdgPopupSurfacePrivate::WXdgPopupSurfacePrivate(WXdgPopupSurface *qq, qw_xdg_popup *hh) +WXdgPopupSurfacePrivate::WXdgPopupSurfacePrivate(WXdgPopupSurface *qq, wlr_xdg_popup *hh) : WToplevelSurfacePrivate(qq) { - initHandle(hh); + Q_ASSERT(hh); + // wlr_xdg_popup has no data field; store on the xdg_surface instead. + hh->base->data = qq; + m_handle = hh; } WXdgPopupSurfacePrivate::~WXdgPopupSurfacePrivate() @@ -44,45 +50,42 @@ WXdgPopupSurfacePrivate::~WXdgPopupSurfacePrivate() } -void WXdgPopupSurfacePrivate::instantRelease() -{ - if (!surface) - return; - W_Q(WXdgPopupSurface); - handle()->set_data(nullptr, nullptr); - handle()->disconnect(q); - surface->safeDeleteLater(); - surface = nullptr; -} - void WXdgPopupSurfacePrivate::init() { W_Q(WXdgPopupSurface); - handle()->set_data(this, q); - Q_ASSERT(!q->surface()); - surface = new WSurface(qw_surface::from(nativeHandle()->base->surface), q); + surface = new WSurface(m_handle->base->surface); surface->setAttachedData(q); connect(); } - void WXdgPopupSurfacePrivate::connect() { W_Q(WXdgPopupSurface); - QObject::connect(handle(), &qw_xdg_popup::notify_reposition, q, &WXdgPopupSurface::reposition); + q->listeners()->add(&m_handle->events.reposition, q, &WXdgPopupSurface::reposition); } -WXdgPopupSurface::WXdgPopupSurface(qw_xdg_popup *handle, QObject *parent) - : WXdgSurface(*new WXdgPopupSurfacePrivate(this, handle), parent) +WXdgPopupSurface::WXdgPopupSurface(wlr_xdg_popup *handle) + : WXdgSurface(*new WXdgPopupSurfacePrivate(this, handle)) { d_func()->init(); } WXdgPopupSurface::~WXdgPopupSurface() { - + teardown(); + // Notify listeners while the object is still usable (its members are + // alive during the destructor body). + Q_EMIT beforeDestroy(); + // Owner rule: this object created the WSurface wrapper, release it. + W_D(WXdgPopupSurface); + // Clear the reverse fromHandle() mapping. The shell destroys this + // wrapper from the popup's destroy callback (or while the native handle + // is still alive), so the handle is valid here. + if (d->m_handle && d->m_handle->base->data == this) + d->m_handle->base->data = nullptr; + delete d->surface; } bool WXdgPopupSurface::hasCapability(Capability cap) const @@ -90,8 +93,8 @@ bool WXdgPopupSurface::hasCapability(Capability cap) const switch (cap) { using enum Capability; case Resize: - return true; case Focus: + return true; case Activate: case Maximized: case FullScreen: @@ -108,24 +111,26 @@ WSurface *WXdgPopupSurface::surface() const return d->surface; } -qw_xdg_popup *WXdgPopupSurface::handle() const +wlr_xdg_popup *WXdgPopupSurface::handle() const { W_DC(WXdgPopupSurface); return d->handle(); } -qw_surface *WXdgPopupSurface::inputTargetAt(QPointF &localPos) const +wlr_surface *WXdgPopupSurface::inputTargetAt(QPointF &localPos) const { // find a wlr_suface object who can receive the events const QPointF pos = localPos; - auto xdgSurface = qw_xdg_surface::from(handle()->handle()->base); - auto sur = xdgSurface->surface_at(pos.x(), pos.y(), &localPos.rx(), &localPos.ry()); - return sur ? qw_surface::from(sur) : nullptr; + auto *xdgSurface = handle()->base; + auto sur = wlr_xdg_surface_surface_at(xdgSurface, pos.x(), pos.y(), &localPos.rx(), &localPos.ry()); + return sur; } -WXdgPopupSurface *WXdgPopupSurface::fromHandle(qw_xdg_popup *handle) +WXdgPopupSurface *WXdgPopupSurface::fromHandle(wlr_xdg_popup *handle) { - return handle->get_data(); + if (!handle) + return nullptr; + return static_cast(handle->base->data); } WXdgPopupSurface *WXdgPopupSurface::fromSurface(WSurface *surface) @@ -133,7 +138,7 @@ WXdgPopupSurface *WXdgPopupSurface::fromSurface(WSurface *surface) return surface->getAttachedData(); } -void WXdgPopupSurface::resize(const QSize &size) +void WXdgPopupSurface::resize([[maybe_unused]] const QSize &size) { } @@ -141,46 +146,55 @@ void WXdgPopupSurface::resize(const QSize &size) void WXdgPopupSurface::close() { // wlr_xdg_popup_destroy will send popup_done to the client - // can't use delete qw_xdg_popup, which is not owner of wlr_xdg_popup - handle()->destroy(); + wlr_xdg_popup_destroy(handle()); } QRect WXdgPopupSurface::getContentGeometry() const { - W_DC(WXdgPopupSurface); - auto xdgSurface = qw_xdg_surface::from(handle()->handle()->base); - qw_box tmp = qw_box(xdgSurface->handle()->geometry); - return tmp.toQRect(); + auto *xdgSurface = handle()->base; + const wlr_box &tmp = xdgSurface->geometry; + return QRect(tmp.x, tmp.y, tmp.width, tmp.height); } -bool WXdgPopupSurface::checkNewSize(const QSize &size, QSize *clipedSize) +bool WXdgPopupSurface::checkNewSize(const QSize &size, [[maybe_unused]] QSize *clipedSize) { - Q_UNUSED(clipedSize); return size.isValid(); } +bool WXdgPopupSurface::isInitialized() const +{ + W_DC(WXdgPopupSurface); + return d->handle()->base->initialized; +} + WSurface *WXdgPopupSurface::parentSurface() const { W_DC(WXdgPopupSurface); - auto parent = d->nativeHandle()->parent; + auto parent = d->handle()->parent; Q_ASSERT(parent); return WSurface::fromHandle(parent); } QPointF WXdgPopupSurface::getPopupPosition() const { - auto wpopup = handle()->handle(); + auto wpopup = handle(); Q_ASSERT(wpopup); - if (wpopup->parent && qw_xdg_popup::try_from_wlr_surface(wpopup->parent)) { - auto popup = qw_xdg_popup::from(wpopup); + // wlr_xdg_popup_get_position() asserts the parent is a valid xdg surface, + // and xdg-shell only ever creates popups with an xdg_surface parent (see + // xdg_surface_handle_get_popup). The parent==NULL case is rejected earlier: + // parentSurface() above asserts it. The fallback below is therefore + // unreachable for xdg-shell clients; keep it as a defensive guard only. + // Note its coordinate space differs from the wlr branch: the fallback + // returns the popup's own window-geometry anchor (relative to the parent + // window geometry) without the parent's offset applied, so callers must + // not treat the two branches as the same space. + if (wpopup->parent && wlr_xdg_surface_try_from_wlr_surface(wpopup->parent)) { double popup_sx, popup_sy; - popup->get_position(&popup_sx, &popup_sy); + wlr_xdg_popup_get_position(wpopup, &popup_sx, &popup_sy); return QPointF(popup_sx, popup_sy); } return {static_cast(wpopup->current.geometry.x), static_cast(wpopup->current.geometry.y)}; } - WAYLIB_SERVER_END_NAMESPACE - diff --git a/waylib/src/server/protocols/wxdgpopupsurface.h b/waylib/src/server/protocols/wxdgpopupsurface.h index ac032e2a62..71426bde74 100644 --- a/waylib/src/server/protocols/wxdgpopupsurface.h +++ b/waylib/src/server/protocols/wxdgpopupsurface.h @@ -1,15 +1,12 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef WXDGPOPUPSURFACE_H #define WXDGPOPUPSURFACE_H +#include #include "wxdgsurface.h" -QW_BEGIN_NAMESPACE -class qw_xdg_popup; -QW_END_NAMESPACE - WAYLIB_SERVER_BEGIN_NAMESPACE class WXdgPopupSurfacePrivate; @@ -21,16 +18,16 @@ class WAYLIB_SERVER_EXPORT WXdgPopupSurface : public WXdgSurface QML_UNCREATABLE("Only create in C++") public: - explicit WXdgPopupSurface(QW_NAMESPACE::qw_xdg_popup *handle, QObject *parent = nullptr); + explicit WXdgPopupSurface(wlr_xdg_popup *handle); ~WXdgPopupSurface(); bool hasCapability(Capability cap) const override; WSurface *surface() const override; - QW_NAMESPACE::qw_xdg_popup *handle() const; - QW_NAMESPACE::qw_surface *inputTargetAt(QPointF &localPos) const; + wlr_xdg_popup *handle() const; + wlr_surface *inputTargetAt(QPointF &localPos) const; - static WXdgPopupSurface *fromHandle(QW_NAMESPACE::qw_xdg_popup *handle); + static WXdgPopupSurface *fromHandle(wlr_xdg_popup *handle); static WXdgPopupSurface *fromSurface(WSurface *surface); WSurface *parentSurface() const override; @@ -39,6 +36,8 @@ class WAYLIB_SERVER_EXPORT WXdgPopupSurface : public WXdgSurface QRect getContentGeometry() const override; bool checkNewSize(const QSize &size, QSize *clipedSize = nullptr) override; + bool isInitialized() const override; + public Q_SLOTS: void resize(const QSize &size) override; void close() override; diff --git a/waylib/src/server/protocols/wxdgshell.cpp b/waylib/src/server/protocols/wxdgshell.cpp index 60339d6b17..4175f766bb 100644 --- a/waylib/src/server/protocols/wxdgshell.cpp +++ b/waylib/src/server/protocols/wxdgshell.cpp @@ -1,18 +1,16 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wxdgshell.h" #include "wxdgtoplevelsurface.h" #include "wxdgpopupsurface.h" +#include "wscoplistener.h" #include "private/wglobal_p.h" -#include -#include -#include +#include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WXdgShellPrivate : public WObjectPrivate @@ -25,69 +23,77 @@ class Q_DECL_HIDDEN WXdgShellPrivate : public WObjectPrivate } // begin slot function - void onNewXdgToplevelSurface(qw_xdg_toplevel *toplevel); - void onToplevelSurfaceDestroy(qw_xdg_toplevel *toplevel); - void onNewXdgPopupSurface(qw_xdg_popup *popup); - void onPopupSurfaceDestroy(qw_xdg_popup *popup); + void onNewXdgToplevelSurface(wlr_xdg_toplevel *toplevel); + void onToplevelSurfaceDestroy(WXdgToplevelSurface *surface); + void onNewXdgPopupSurface(wlr_xdg_popup *popup); + void onPopupSurfaceDestroy(WXdgPopupSurface *surface); // end slot function W_DECLARE_PUBLIC(WXdgShell) QVector toplevelSurfaceList; QVector popupSurfaceList; - uint32_t version; + uint32_t version = 0; }; -void WXdgShellPrivate::onNewXdgToplevelSurface(qw_xdg_toplevel *toplevel) +void WXdgShellPrivate::onNewXdgToplevelSurface(wlr_xdg_toplevel *toplevel) { W_Q(WXdgShell); - auto server = q_func()->server(); - auto surface = new WXdgToplevelSurface(toplevel, server); - surface->setParent(server); - Q_ASSERT(surface->parent() == server); - surface->safeConnect(&qw_xdg_surface::before_destroy, q, [this, toplevel] { - onToplevelSurfaceDestroy(toplevel); + auto surface = new WXdgToplevelSurface(toplevel); + auto *xdgSurface = toplevel->base; + // Register the destroy/new_popup listeners on the surface wrapper + // (owner = this shell): released automatically by ~WObject when the + // wrapper is deleted. + surface->listeners(q_ptr)->add(&toplevel->events.destroy, this, + [this, surface] (void *) { + // Detach our own listener group: safe from inside a callback of + // this list (the closure outlives the emission). + surface->removeListeners(q_ptr); + onToplevelSurfaceDestroy(surface); }); - auto xdgSurface = qw_xdg_surface::from((*toplevel)->base); - QObject::connect(xdgSurface, &qw_xdg_surface::notify_new_popup, q, &WXdgShell::initializeNewXdgPopupSurface); + surface->listeners(q_ptr)->add(&xdgSurface->events.new_popup, this, + &WXdgShellPrivate::onNewXdgPopupSurface); toplevelSurfaceList.append(surface); - Q_EMIT q_func()->toplevelSurfaceAdded(surface); + Q_EMIT q->toplevelSurfaceAdded(surface); } -void WXdgShellPrivate::onToplevelSurfaceDestroy(qw_xdg_toplevel *toplevel) +void WXdgShellPrivate::onToplevelSurfaceDestroy(WXdgToplevelSurface *surface) { - auto surface = WXdgToplevelSurface::fromHandle(toplevel); Q_ASSERT(surface); bool ok = toplevelSurfaceList.removeOne(surface); Q_ASSERT(ok); Q_EMIT q_func()->toplevelSurfaceRemoved(surface); - surface->safeDeleteLater(); + delete surface; } -void WXdgShellPrivate::onNewXdgPopupSurface(qw_xdg_popup *popup) +void WXdgShellPrivate::onNewXdgPopupSurface(wlr_xdg_popup *popup) { W_Q(WXdgShell); - auto server = q_func()->server(); - auto surface = new WXdgPopupSurface(popup, server); - surface->setParent(server); - Q_ASSERT(surface->parent() == server); - surface->safeConnect(&qw_xdg_popup::before_destroy, q, [this, popup] { - onPopupSurfaceDestroy(popup); + auto surface = new WXdgPopupSurface(popup); + auto *xdgSurface = popup->base; + // Register the destroy/new_popup listeners on the surface wrapper + // (owner = this shell): released automatically by ~WObject when the + // wrapper is deleted. + surface->listeners(q_ptr)->add(&popup->events.destroy, this, + [this, surface] (void *) { + // Detach our own listener group: safe from inside a callback of + // this list (the closure outlives the emission). + surface->removeListeners(q_ptr); + onPopupSurfaceDestroy(surface); }); - auto xdgSurface = qw_xdg_surface::from((*popup)->base); - QObject::connect(xdgSurface, &qw_xdg_surface::notify_new_popup, q, &WXdgShell::initializeNewXdgPopupSurface); + surface->listeners(q_ptr)->add(&xdgSurface->events.new_popup, this, + &WXdgShellPrivate::onNewXdgPopupSurface); popupSurfaceList.append(surface); - Q_EMIT q_func()->popupSurfaceAdded(surface); + Q_EMIT q->popupSurfaceAdded(surface); } -void WXdgShellPrivate::onPopupSurfaceDestroy(qw_xdg_popup *popup) +void WXdgShellPrivate::onPopupSurfaceDestroy(WXdgPopupSurface *surface) { - auto surface = WXdgPopupSurface::fromHandle(popup); Q_ASSERT(surface); bool ok = popupSurfaceList.removeOne(surface); Q_ASSERT(ok); Q_EMIT q_func()->popupSurfaceRemoved(surface); - surface->safeDeleteLater(); + delete surface; } WXdgShell::WXdgShell(uint32_t version) @@ -108,56 +114,66 @@ QByteArrayView WXdgShell::interfaceName() const return "xdg_wm_base"; } +wlr_xdg_shell *WXdgShell::handle() const +{ + return reinterpret_cast(m_handle); +} + void WXdgShell::initializeNewXdgPopupSurface(wlr_xdg_popup *popup) { W_D(WXdgShell); - d->onNewXdgPopupSurface(qw_xdg_popup::from(popup)); + d->onNewXdgPopupSurface(popup); } void WXdgShell::create(WServer *server) { W_D(WXdgShell); // free follow display - auto xdg_shell = qw_xdg_shell::create(*server->handle(), d->version); - QObject::connect(xdg_shell, &qw_xdg_shell::notify_new_toplevel, this, [this] (wlr_xdg_toplevel *toplevel_surface) { - d_func()->onNewXdgToplevelSurface(qw_xdg_toplevel::from(toplevel_surface)); - }); + auto xdg_shell = wlr_xdg_shell_create(server->handle(), d->version); + Q_ASSERT(xdg_shell); + listeners()->add(&xdg_shell->events.new_toplevel, d, + &WXdgShellPrivate::onNewXdgToplevelSurface); // When layer_surface is an xdg_popup's parent, the popup should created via xdg_surface::get_popup with the parent set to NULL, // and invoke 'zwlr_layer_surface_v1::get_popup' to set parent before committing the popup's initial state. - // We should use parent's `notify_new_popup` to avoid get a popup with NULL parent - // QObject::connect(xdg_shell, &qw_xdg_shell::notify_new_popup, this, [this] (wlr_xdg_popup *xdg_popup) { - // d_func()->onNewXdgPopupSurface(qw_xdg_popup::from(xdg_popup)); - // }); + // Popups are delivered through each xdg_surface's `new_popup` event (see + // onNewXdgToplevelSurface/onNewXdgPopupSurface). Do NOT also listen on + // xdg_shell->events.new_popup: wlroots emits it for every popup, so every + // popup would be wrapped twice. m_handle = xdg_shell; } -void WXdgShell::destroy(WServer *server) +void WXdgShell::destroy([[maybe_unused]] WServer *server) { - Q_UNUSED(server); W_D(WXdgShell); QVector toplevelList; QVector popupList; - d->toplevelSurfaceList.swap(toplevelList); d->popupSurfaceList.swap(popupList); for (auto surface : std::as_const(toplevelList)) { - toplevelSurfaceRemoved(surface); - surface->safeDeleteLater(); + Q_EMIT toplevelSurfaceRemoved(surface); + delete surface; } for (auto surface : std::as_const(popupList)) { - popupSurfaceRemoved(surface); - surface->safeDeleteLater(); + Q_EMIT popupSurfaceRemoved(surface); + delete surface; } + + if (ownsSocket() && m_handle) + wlr_xdg_shell_destroy(nativeInterface(), false); + + m_handle = nullptr; } wl_global *WXdgShell::global() const { - auto handle = nativeInterface(); - return handle->handle()->global; + if (!m_handle) + return nullptr; + auto handle = reinterpret_cast(m_handle); + return handle->global; } WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wxdgshell.h b/waylib/src/server/protocols/wxdgshell.h index 5bcc9cf515..00e196d24b 100644 --- a/waylib/src/server/protocols/wxdgshell.h +++ b/waylib/src/server/protocols/wxdgshell.h @@ -1,11 +1,12 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include -class wlr_xdg_popup; +Q_MOC_INCLUDE("wxdgtoplevelsurface.h") WAYLIB_SERVER_BEGIN_NAMESPACE @@ -21,6 +22,7 @@ class WAYLIB_SERVER_EXPORT WXdgShell : public QObject, public WObject, public WS QVector toplevelSurfaceList() const; QByteArrayView interfaceName() const override; + wlr_xdg_shell *handle() const; Q_SIGNALS: void toplevelSurfaceAdded(WXdgToplevelSurface *surface); diff --git a/waylib/src/server/protocols/wxdgsurface.cpp b/waylib/src/server/protocols/wxdgsurface.cpp index efc0952754..f43020754d 100644 --- a/waylib/src/server/protocols/wxdgsurface.cpp +++ b/waylib/src/server/protocols/wxdgsurface.cpp @@ -1,13 +1,12 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wxdgsurface.h" -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE -WXdgSurface::WXdgSurface(WToplevelSurfacePrivate &d, QObject *parent) - : WToplevelSurface(d, parent) +WXdgSurface::WXdgSurface(WToplevelSurfacePrivate &d) + : WToplevelSurface(d) { } diff --git a/waylib/src/server/protocols/wxdgsurface.h b/waylib/src/server/protocols/wxdgsurface.h index cf12c4b20f..0815159336 100644 --- a/waylib/src/server/protocols/wxdgsurface.h +++ b/waylib/src/server/protocols/wxdgsurface.h @@ -11,10 +11,14 @@ class WAYLIB_SERVER_EXPORT WXdgSurface : public WToplevelSurface { Q_OBJECT QML_NAMED_ELEMENT(WaylandXdgSurface) + QML_UNCREATABLE("Cannot create WaylandXdgSurface from QML") protected: - explicit WXdgSurface(WToplevelSurfacePrivate &d, QObject *parent = nullptr); + explicit WXdgSurface(WToplevelSurfacePrivate &d); ~WXdgSurface(); + +public: + virtual bool isInitialized() const = 0; }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wxdgtoplevelsurface.cpp b/waylib/src/server/protocols/wxdgtoplevelsurface.cpp index e4f50349ca..762ebdf573 100644 --- a/waylib/src/server/protocols/wxdgtoplevelsurface.cpp +++ b/waylib/src/server/protocols/wxdgtoplevelsurface.cpp @@ -1,28 +1,31 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wxdgtoplevelsurface.h" + #include "private/wtoplevelsurface_p.h" +#include "woutput.h" #include "wseat.h" +#include "wscoplistener.h" #include "wtools.h" -#include -#include -#include -#include +#include + +#include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WXdgToplevelSurfacePrivate : public WToplevelSurfacePrivate { public: - WXdgToplevelSurfacePrivate(WXdgToplevelSurface *qq, qw_xdg_toplevel *handle); + WXdgToplevelSurfacePrivate(WXdgToplevelSurface *qq, wlr_xdg_toplevel *handle); ~WXdgToplevelSurfacePrivate(); - WWRAP_HANDLE_FUNCTIONS(qw_xdg_toplevel, wlr_xdg_toplevel) + inline wlr_xdg_toplevel *handle() const { + return m_handle; + } wl_client *waylandClient() const override { - return nativeHandle()->base->client->client; + return handle()->base->client->client; } // begin slot function @@ -33,7 +36,7 @@ class Q_DECL_HIDDEN WXdgToplevelSurfacePrivate : public WToplevelSurfacePrivate void init(); void connect(); - void instantRelease() override; + void updateSizeFromCommit(); W_DECLARE_PUBLIC(WXdgToplevelSurface) @@ -44,9 +47,19 @@ class Q_DECL_HIDDEN WXdgToplevelSurfacePrivate : public WToplevelSurfacePrivate uint maximized:1; uint minimized:1; uint fullscreen:1; + QSize minimumSize; + QSize maximumSize = QSize(INT_MAX, INT_MAX); + + QString tag; + QString description; + +private: + // The xdg owner destroys this handle after notifying the wrapper. + // Keep the address stable through that callback. + wlr_xdg_toplevel *m_handle = nullptr; }; -WXdgToplevelSurfacePrivate::WXdgToplevelSurfacePrivate(WXdgToplevelSurface *qq, qw_xdg_toplevel *hh) +WXdgToplevelSurfacePrivate::WXdgToplevelSurfacePrivate(WXdgToplevelSurface *qq, wlr_xdg_toplevel *hh) : WToplevelSurfacePrivate(qq) , resizeing(false) , activated(false) @@ -54,7 +67,11 @@ WXdgToplevelSurfacePrivate::WXdgToplevelSurfacePrivate(WXdgToplevelSurface *qq, , minimized(false) , fullscreen(false) { - initHandle(hh); + Q_ASSERT(hh); + // wlr_xdg_toplevel has no data field; store on the xdg_surface instead + // (a surface has exactly one role, so no clash with popups). + hh->base->data = qq; + m_handle = hh; } WXdgToplevelSurfacePrivate::~WXdgToplevelSurfacePrivate() @@ -62,20 +79,6 @@ WXdgToplevelSurfacePrivate::~WXdgToplevelSurfacePrivate() } -void WXdgToplevelSurfacePrivate::instantRelease() -{ - if (!surface) - return; - W_Q(WXdgToplevelSurface); - handle()->set_data(nullptr, nullptr); - - auto xdgSurface = qw_xdg_surface::from(nativeHandle()->base); - xdgSurface->disconnect(q); - handle()->disconnect(q); - surface->safeDeleteLater(); - surface = nullptr; -} - void WXdgToplevelSurfacePrivate::on_configure(wlr_xdg_surface_configure *event) { W_Q(WXdgToplevelSurface); @@ -101,13 +104,32 @@ void WXdgToplevelSurfacePrivate::on_configure(wlr_xdg_surface_configure *event) } } -void WXdgToplevelSurfacePrivate::init() +void WXdgToplevelSurfacePrivate::updateSizeFromCommit() { W_Q(WXdgToplevelSurface); - handle()->set_data(this, q); + const QSize minimumSize(qMax(0, handle()->current.min_width), + qMax(0, handle()->current.min_height)); + const QSize maximumSize( + handle()->current.max_width > 0 ? handle()->current.max_width : INT_MAX, + handle()->current.max_height > 0 ? handle()->current.max_height : INT_MAX); + + if (this->minimumSize != minimumSize) { + this->minimumSize = minimumSize; + Q_EMIT q->minimumSizeChanged(this->minimumSize); + } + + if (this->maximumSize != maximumSize) { + this->maximumSize = maximumSize; + Q_EMIT q->maximumSizeChanged(this->maximumSize); + } +} + +void WXdgToplevelSurfacePrivate::init() +{ + W_Q(WXdgToplevelSurface); Q_ASSERT(!q->surface()); - surface = new WSurface(qw_surface::from(nativeHandle()->base->surface), q); + surface = new WSurface(m_handle->base->surface); surface->setAttachedData(q); connect(); @@ -117,70 +139,100 @@ void WXdgToplevelSurfacePrivate::connect() { W_Q(WXdgToplevelSurface); - auto surface = qw_xdg_surface::from(nativeHandle()->base); - QObject::connect(surface, &qw_xdg_surface::notify_configure, q, [this] (wlr_xdg_surface_configure *event) { - on_configure(event); + QObject::connect(q->surface(), &WSurface::commit, q, [this] { + updateSizeFromCommit(); }); + auto *xdgSurface = m_handle->base; + q->listeners()->add(&xdgSurface->events.configure, this, + &WXdgToplevelSurfacePrivate::on_configure); + // TODO: use safeConnect for toplevel - QObject::connect(handle(), &qw_xdg_toplevel::notify_request_move, q, [q] (wlr_xdg_toplevel_move_event *event) { - auto seat = WSeat::fromHandle(qw_seat::from(event->seat->seat)); + q->listeners()->add(&m_handle->events.request_move, q, + [q] (wlr_xdg_toplevel_move_event *event) { + auto seat = WSeat::fromHandle(event->seat->seat); Q_EMIT q->requestMove(seat, event->serial); }); - QObject::connect(handle(), &qw_xdg_toplevel::notify_request_resize, q, [q] (wlr_xdg_toplevel_resize_event *event) { - auto seat = WSeat::fromHandle(qw_seat::from(event->seat->seat)); + q->listeners()->add(&m_handle->events.request_resize, q, + [q] (wlr_xdg_toplevel_resize_event *event) { + auto seat = WSeat::fromHandle(event->seat->seat); Q_EMIT q->requestResize(seat, WTools::toQtEdge(event->edges), event->serial); }); - QObject::connect(handle(), &qw_xdg_toplevel::notify_request_maximize, q, [q, this] () { - if ((*handle())->requested.maximized) { + q->listeners()->add(&m_handle->events.request_maximize, q, + [q, this] (void *) { + if (m_handle->requested.maximized) { Q_EMIT q->requestMaximize(); } else { Q_EMIT q->requestCancelMaximize(); } }); - QObject::connect(handle(), &qw_xdg_toplevel::notify_request_minimize, q, [q, this] () { + q->listeners()->add(&m_handle->events.request_minimize, q, + [q, this] (void *) { // Wayland clients can't request unset minimization on this surface - if ((*handle())->requested.minimized) { + if (m_handle->requested.minimized) { Q_EMIT q->requestMinimize(); } }); - QObject::connect(handle(), &qw_xdg_toplevel::notify_request_fullscreen, q, [q, this] () { - if ((*handle())->requested.fullscreen) { - Q_EMIT q->requestFullscreen(); + q->listeners()->add(&m_handle->events.request_fullscreen, q, + [q, this] (void *) { + if (m_handle->requested.fullscreen) { + WOutput *output = m_handle->requested.fullscreen_output + ? WOutput::fromHandle(m_handle->requested.fullscreen_output) + : nullptr; + Q_EMIT q->requestFullscreen(output); } else { Q_EMIT q->requestCancelFullscreen(); } }); - QObject::connect(handle(), &qw_xdg_toplevel::notify_request_show_window_menu, q, [q] (wlr_xdg_toplevel_show_window_menu_event *event) { - auto seat = WSeat::fromHandle(qw_seat::from(event->seat->seat)); + q->listeners()->add(&m_handle->events.request_show_window_menu, q, + [q] (wlr_xdg_toplevel_show_window_menu_event *event) { + auto seat = WSeat::fromHandle(event->seat->seat); Q_EMIT q->requestShowWindowMenu(seat, QPoint(event->x, event->y), event->serial); }); - QObject::connect(handle(), &qw_xdg_toplevel::notify_set_parent, q, &WXdgToplevelSurface::parentXdgSurfaceChanged); - QObject::connect(handle(), &qw_xdg_toplevel::notify_set_title, q, &WXdgToplevelSurface::titleChanged); - QObject::connect(handle(), &qw_xdg_toplevel::notify_set_app_id, q, &WXdgToplevelSurface::appIdChanged); + q->listeners()->add(&m_handle->events.set_parent, q, &WXdgToplevelSurface::parentXdgSurfaceChanged); + q->listeners()->add(&m_handle->events.set_title, q, &WXdgToplevelSurface::titleChanged); + q->listeners()->add(&m_handle->events.set_app_id, q, &WXdgToplevelSurface::appIdChanged); } -WXdgToplevelSurface::WXdgToplevelSurface(qw_xdg_toplevel *handle, QObject *parent) - : WXdgSurface(*new WXdgToplevelSurfacePrivate(this, handle), parent) +WXdgToplevelSurface::WXdgToplevelSurface(wlr_xdg_toplevel *handle) + : WXdgSurface(*new WXdgToplevelSurfacePrivate(this, handle)) { d_func()->init(); } WXdgToplevelSurface::~WXdgToplevelSurface() { - + teardown(); + // Notify listeners while the object is still usable (its members are + // alive during the destructor body). + Q_EMIT beforeDestroy(); + // Owner rule: this object created the WSurface wrapper, release it. + W_D(WXdgToplevelSurface); + // Clear the reverse fromHandle() mapping. The shell destroys this + // wrapper from the toplevel's destroy callback (or while the native + // handle is still alive), so the handle is valid here. + if (d->m_handle && d->m_handle->base->data == this) + d->m_handle->base->data = nullptr; + delete d->surface; } - bool WXdgToplevelSurface::hasCapability(Capability cap) const { switch (cap) { using enum Capability; - case Resize: + case Resize: { + const QSize min = minSize(); + const QSize max = maxSize(); + return min.width() < max.width() || min.height() < max.height(); + } + case Maximized: { + const QSize min = minSize(); + const QSize max = maxSize(); + return min.width() < max.width() && min.height() < max.height(); + } case Focus: case Activate: - case Maximized: case FullScreen: return true; default: @@ -195,24 +247,26 @@ WSurface *WXdgToplevelSurface::surface() const return d->surface; } -qw_xdg_toplevel *WXdgToplevelSurface::handle() const +wlr_xdg_toplevel *WXdgToplevelSurface::handle() const { W_DC(WXdgToplevelSurface); return d->handle(); } -qw_surface *WXdgToplevelSurface::inputTargetAt(QPointF &localPos) const +wlr_surface *WXdgToplevelSurface::inputTargetAt(QPointF &localPos) const { // find a wlr_suface object who can receive the events const QPointF pos = localPos; - auto xdgSurface = qw_xdg_surface::from(handle()->handle()->base); - auto sur = xdgSurface->surface_at(pos.x(), pos.y(), &localPos.rx(), &localPos.ry()); - return sur ? qw_surface::from(sur) : nullptr; + auto *xdgSurface = handle()->base; + auto sur = wlr_xdg_surface_surface_at(xdgSurface, pos.x(), pos.y(), &localPos.rx(), &localPos.ry()); + return sur; } -WXdgToplevelSurface *WXdgToplevelSurface::fromHandle(qw_xdg_toplevel *handle) +WXdgToplevelSurface *WXdgToplevelSurface::fromHandle(wlr_xdg_toplevel *handle) { - return handle->get_data(); + if (!handle) + return nullptr; + return static_cast(handle->base->data); } WXdgToplevelSurface *WXdgToplevelSurface::fromSurface(WSurface *surface) @@ -222,12 +276,12 @@ WXdgToplevelSurface *WXdgToplevelSurface::fromSurface(WSurface *surface) void WXdgToplevelSurface::resize(const QSize &size) { - handle()->set_size(size.width(), size.height()); + wlr_xdg_toplevel_set_size(handle(), size.width(), size.height()); } void WXdgToplevelSurface::close() { - handle()->send_close(); + wlr_xdg_toplevel_send_close(handle()); } bool WXdgToplevelSurface::isResizeing() const @@ -262,68 +316,95 @@ bool WXdgToplevelSurface::isFullScreen() const QRect WXdgToplevelSurface::getContentGeometry() const { - W_DC(WXdgToplevelSurface); - auto xdgSurface = qw_xdg_surface::from(handle()->handle()->base); - qw_box tmp = qw_box(xdgSurface->handle()->geometry); - return tmp.toQRect(); + auto *xdgSurface = handle()->base; + const wlr_box &tmp = xdgSurface->geometry; + return QRect(tmp.x, tmp.y, tmp.width, tmp.height); } QSize WXdgToplevelSurface::minSize() const { W_DC(WXdgToplevelSurface); - auto wtoplevel = d->nativeHandle(); - return QSize(wtoplevel->current.min_width, - wtoplevel->current.min_height); - + return d->minimumSize; } QSize WXdgToplevelSurface::maxSize() const { W_DC(WXdgToplevelSurface); - auto wtoplevel = d->nativeHandle(); - return QSize(wtoplevel->current.max_width, - wtoplevel->current.max_height); - + return d->maximumSize; } QString WXdgToplevelSurface::title() const { W_DC(WXdgToplevelSurface); - return QString::fromUtf8(d->nativeHandle()->title); + return QString::fromUtf8(d->handle()->title); } QString WXdgToplevelSurface::appId() const { W_DC(WXdgToplevelSurface); - return QString::fromLocal8Bit(d->nativeHandle()->app_id); + return QString::fromLocal8Bit(d->handle()->app_id); } -WXdgToplevelSurface *WXdgToplevelSurface::parentXdgSurface() const +QString WXdgToplevelSurface::tag() const +{ + W_DC(WXdgToplevelSurface); + return d->tag; +} + +QString WXdgToplevelSurface::description() const +{ + W_DC(WXdgToplevelSurface); + return d->description; +} + +bool WXdgToplevelSurface::isInitialized() const { W_DC(WXdgToplevelSurface); + return d->handle()->base->initialized; +} - auto parent = handle()->handle()->parent; +WXdgToplevelSurface *WXdgToplevelSurface::parentXdgSurface() const +{ + auto parent = handle()->parent; if (!parent) return nullptr; - return fromHandle(qw_xdg_toplevel::from(parent)); + return fromHandle(parent); } WSurface *WXdgToplevelSurface::parentSurface() const { - auto parent = handle()->handle()->parent; + auto parent = handle()->parent; if (!parent) return nullptr; return WSurface::fromHandle(parent->base->surface); } +void WXdgToplevelSurface::setTag(const QString &tag) +{ + W_D(WXdgToplevelSurface); + if (d->tag == tag) + return; + d->tag = tag; + Q_EMIT tagChanged(); +} + +void WXdgToplevelSurface::setDescription(const QString &description) +{ + W_D(WXdgToplevelSurface); + if (d->description == description) + return; + d->description = description; + Q_EMIT descriptionChanged(); +} + void WXdgToplevelSurface::setResizeing(bool resizeing) { - handle()->set_resizing(resizeing); + wlr_xdg_toplevel_set_resizing(handle(), resizeing); } void WXdgToplevelSurface::setMaximize(bool on) { - handle()->set_maximized(on); + wlr_xdg_toplevel_set_maximized(handle(), on); } void WXdgToplevelSurface::setMinimize(bool on) @@ -338,12 +419,12 @@ void WXdgToplevelSurface::setMinimize(bool on) void WXdgToplevelSurface::setActivate(bool on) { - handle()->set_activated(on); + wlr_xdg_toplevel_set_activated(handle(), on); } void WXdgToplevelSurface::setFullScreen(bool on) { - handle()->set_fullscreen(on); + wlr_xdg_toplevel_set_fullscreen(handle(), on); } bool WXdgToplevelSurface::checkNewSize(const QSize &size, QSize *clipedSize) @@ -353,7 +434,7 @@ bool WXdgToplevelSurface::checkNewSize(const QSize &size, QSize *clipedSize) *clipedSize = size; bool ok = true; - auto wtoplevel = d->nativeHandle(); + auto wtoplevel = d->handle(); if (size.width() > wtoplevel->current.max_width && wtoplevel->current.max_width > 0) { if (clipedSize) diff --git a/waylib/src/server/protocols/wxdgtoplevelsurface.h b/waylib/src/server/protocols/wxdgtoplevelsurface.h index 73a4a129b5..8d15641403 100644 --- a/waylib/src/server/protocols/wxdgtoplevelsurface.h +++ b/waylib/src/server/protocols/wxdgtoplevelsurface.h @@ -1,39 +1,38 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #ifndef WXDGTOPLEVELSURFACE_H #define WXDGTOPLEVELSURFACE_H +#include #include "wxdgsurface.h" -QW_BEGIN_NAMESPACE -class qw_xdg_toplevel; -QW_END_NAMESPACE - WAYLIB_SERVER_BEGIN_NAMESPACE class WXdgToplevelSurfacePrivate; class WAYLIB_SERVER_EXPORT WXdgToplevelSurface : public WXdgSurface -{ +{ Q_OBJECT W_DECLARE_PRIVATE(WXdgToplevelSurface) Q_PROPERTY(bool isResizeing READ isResizeing NOTIFY resizeingChanged FINAL) Q_PROPERTY(WXdgSurface* parentXdgSurface READ parentXdgSurface NOTIFY parentXdgSurfaceChanged FINAL) + Q_PROPERTY(QString tag READ tag NOTIFY tagChanged FINAL) + Q_PROPERTY(QString description READ description NOTIFY descriptionChanged FINAL) QML_NAMED_ELEMENT(WaylandXdgToplevelSurface) QML_UNCREATABLE("Only create in C++") public: - explicit WXdgToplevelSurface(QW_NAMESPACE::qw_xdg_toplevel *handle, QObject *parent = nullptr); + explicit WXdgToplevelSurface(wlr_xdg_toplevel *handle); ~WXdgToplevelSurface(); bool hasCapability(Capability cap) const override; WSurface *surface() const override; - QW_NAMESPACE::qw_xdg_toplevel *handle() const; - QW_NAMESPACE::qw_surface *inputTargetAt(QPointF &localPos) const; + wlr_xdg_toplevel *handle() const; + wlr_surface *inputTargetAt(QPointF &localPos) const; - static WXdgToplevelSurface *fromHandle(QW_NAMESPACE::qw_xdg_toplevel *handle); + static WXdgToplevelSurface *fromHandle(wlr_xdg_toplevel *handle); static WXdgToplevelSurface *fromSurface(WSurface *surface); WXdgToplevelSurface *parentXdgSurface() const; @@ -53,6 +52,13 @@ class WAYLIB_SERVER_EXPORT WXdgToplevelSurface : public WXdgSurface QString title() const override; QString appId() const override; + QString tag() const; + QString description() const; + void setTag(const QString &tag); + void setDescription(const QString &description); + + bool isInitialized() const override; + public Q_SLOTS: void setResizeing(bool resizeing) override; void setMaximize(bool on) override; @@ -67,6 +73,8 @@ public Q_SLOTS: Q_SIGNALS: void parentXdgSurfaceChanged(); void resizeingChanged(); + void tagChanged(); + void descriptionChanged(); }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wxdgtopleveltagmanager.cpp b/waylib/src/server/protocols/wxdgtopleveltagmanager.cpp new file mode 100644 index 0000000000..1ded4804ec --- /dev/null +++ b/waylib/src/server/protocols/wxdgtopleveltagmanager.cpp @@ -0,0 +1,107 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wxdgtopleveltagmanager.h" + +#include "private/wglobal_p.h" +#include "wsurface.h" +#include "wxdgtoplevelsurface.h" +#include + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class Q_DECL_HIDDEN WXdgToplevelTagManagerV1Private : public WObjectPrivate +{ +public: + WXdgToplevelTagManagerV1Private(WXdgToplevelTagManagerV1 *qq) + : WObjectPrivate(qq) + { + } + + W_DECLARE_PUBLIC(WXdgToplevelTagManagerV1) + + struct wlr_xdg_toplevel_tag_manager_v1 *manager{ nullptr }; + struct wl_listener set_tag_listener; + struct wl_listener set_description_listener; + + static void handle_set_tag([[maybe_unused]]struct wl_listener *listener, void *data) + { + auto *event = static_cast(data); + auto *wsurface = WSurface::fromHandle(event->toplevel->base->surface); + if (!wsurface) { + return; + } + auto *ts = WXdgToplevelSurface::fromSurface(wsurface); + if (!ts) { + return; + } + + ts->setTag(QString::fromUtf8(event->tag)); + } + + static void handle_set_description([[maybe_unused]] struct wl_listener *listener, void *data) + { + auto *event = static_cast(data); + auto *wsurface = WSurface::fromHandle(event->toplevel->base->surface); + if (!wsurface) { + return; + } + auto *ts = WXdgToplevelSurface::fromSurface(wsurface); + if (!ts) + return; + ts->setDescription(QString::fromUtf8(event->description)); + } +}; + +WXdgToplevelTagManagerV1::WXdgToplevelTagManagerV1() + : WObject(*new WXdgToplevelTagManagerV1Private(this)) +{ +} + +void WXdgToplevelTagManagerV1::create([[maybe_unused]] WServer *wserver) +{ + W_D(WXdgToplevelTagManagerV1); + + d->manager = wlr_xdg_toplevel_tag_manager_v1_create(server()->handle(), InterfaceVersion); + m_handle = d->manager; + + if (d->manager) { + d->set_tag_listener.notify = WXdgToplevelTagManagerV1Private::handle_set_tag; + wl_signal_add(&d->manager->events.set_tag, &d->set_tag_listener); + + d->set_description_listener.notify = + WXdgToplevelTagManagerV1Private::handle_set_description; + wl_signal_add(&d->manager->events.set_description, &d->set_description_listener); + } +} + +void WXdgToplevelTagManagerV1::destroy([[maybe_unused]] WServer *server) +{ + W_D(WXdgToplevelTagManagerV1); + if (d->manager) { + wl_list_remove(&d->set_tag_listener.link); + wl_list_remove(&d->set_description_listener.link); + } + d->manager = nullptr; + if (ownsSocket() && m_handle) + wlr_xdg_toplevel_tag_manager_v1_destroy(nativeInterface(), false); + + m_handle = nullptr; +} + +wl_global *WXdgToplevelTagManagerV1::global() const +{ + W_DC(WXdgToplevelTagManagerV1); + if (d->manager) + return d->manager->global; + return nullptr; +} + +QByteArrayView WXdgToplevelTagManagerV1::interfaceName() const +{ + return "xdg_toplevel_tag_manager_v1"; +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wxdgtopleveltagmanager.h b/waylib/src/server/protocols/wxdgtopleveltagmanager.h new file mode 100644 index 0000000000..ce462143c7 --- /dev/null +++ b/waylib/src/server/protocols/wxdgtopleveltagmanager.h @@ -0,0 +1,34 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WSurface; +class WXdgToplevelTagManagerV1Private; + +class WAYLIB_SERVER_EXPORT WXdgToplevelTagManagerV1 + : public QObject + , public WObject + , public WServerInterface +{ + Q_OBJECT + W_DECLARE_PRIVATE(WXdgToplevelTagManagerV1) + QML_NAMED_ELEMENT(XdgToplevelTagManagerV1) + QML_UNCREATABLE("Can't create in qml") + +public: + explicit WXdgToplevelTagManagerV1(); + QByteArrayView interfaceName() const override; + + static constexpr int InterfaceVersion = 1; +protected: + void create(WServer *wserver) override; + void destroy(WServer *server) override; + wl_global *global() const override; +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wxwayland.cpp b/waylib/src/server/protocols/wxwayland.cpp index a97654cb2f..bdf6afde35 100644 --- a/waylib/src/server/protocols/wxwayland.cpp +++ b/waylib/src/server/protocols/wxwayland.cpp @@ -1,30 +1,37 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wxwayland.h" -#include "wxwaylandsurface.h" + +#include "private/wglobal_p.h" +#include "private/wwaylandresource_p.h" +#include "private/wxwaylandsurface_p.h" #include "wseat.h" +#include "wscoplistener.h" #include "wsocket.h" -#include "private/wglobal_p.h" - -#include -#include -#include -#include -#include -#include -#include +#include "wxwaylandsurface.h" #include +#include + +#include + +#include +#include + +#include +#include + +#include +#include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE -class Q_DECL_HIDDEN WXWaylandPrivate : public WWrapObjectPrivate +class Q_DECL_HIDDEN WXWaylandPrivate : public WWaylandResourcePrivate { public: - WXWaylandPrivate(WXWayland *qq, qw_compositor *compositor, bool lazy) - : WWrapObjectPrivate(qq) + WXWaylandPrivate(WXWayland *qq, wlr_compositor *compositor, bool lazy) + : WWaylandResourcePrivate(qq) , compositor(compositor) , lazy(lazy) { @@ -37,27 +44,101 @@ class Q_DECL_HIDDEN WXWaylandPrivate : public WWrapObjectPrivate void init(); wl_client *waylandClient() const override { - return q_func()->handle()->handle()->server->client; + return q_func()->handle()->server->client; } // begin slot function void on_new_surface(wlr_xwayland_surface *xwl_surface); - void on_surface_destroy(qw_xwayland_surface *xwl_surface); + void on_surface_destroy(WXWaylandSurface *surface); // end slot function + // Async property reading + struct PerWindowProps + { + QVector requests; + QMap results; + QVector cookies; + std::function &)> callback; + QTimer *timer = nullptr; + bool propNotifySeen = false; + }; + + QMap asyncProps; + + void xcbPollReplies(); + void xcbAsyncTimeoutForWindow(xcb_window_t windowId); + W_DECLARE_PUBLIC(WXWayland) xcb_screen_t *screen = nullptr; - qw_compositor *compositor; + wlr_compositor *compositor; bool lazy = true; QVector surfaceList; QVector atoms; QList toplevelSurfaces; WSocket *socket = nullptr; + +protected: }; +bool xwayland_user_event_handler(wlr_xwayland *xwayland, xcb_generic_event_t *event) +{ + if (!event) + return false; + + const uint8_t response_type = event->response_type & ~0x80; + if (response_type != XCB_PROPERTY_NOTIFY) + return false; + + auto *pe = reinterpret_cast(event); + auto *self = WXWayland::fromHandle(xwayland); + + if (!self) + return false; + + auto *d = self->d_func(); + + // Trigger async property reading infrastructure if this window is being tracked. + if (!d->asyncProps.isEmpty()) { + d->xcbPollReplies(); + auto it = d->asyncProps.find(pe->window); + if (it != d->asyncProps.end()) { + auto &props = it.value(); + props.propNotifySeen = true; + // Resend requests on PROPNOTIFY to get the latest value after the change. + xcb_connection_t *conn = self->xcbConnection(); + props.cookies.clear(); + for (const auto &req : std::as_const(props.requests)) { + auto cookie = xcb_get_property_unchecked(conn, + false, + pe->window, + req.atom, + req.type, + 0, + 1024); + props.cookies.append(cookie); + } + xcb_flush(conn); + } + } + + const auto &list = self->surfaceList(); + for (auto *surface : list) { + QPointer sp(surface); + if (!sp) + continue; + if (sp->handle()->window_id == pe->window) { + Q_EMIT self->windowPropertyChanged(sp, pe->atom); + break; + } + } + + // Do not consume the event; let xcb and wlroots continue normal processing. + return false; +} + void WXWaylandPrivate::init() { W_Q(WXWayland); @@ -94,45 +175,68 @@ void WXWaylandPrivate::init() void WXWaylandPrivate::on_new_surface(wlr_xwayland_surface *xwl_surface) { W_Q(WXWayland); - - auto server = q->server(); - qw_xwayland_surface *xwlSurface = qw_xwayland_surface::from(xwl_surface); - auto surface = new WXWaylandSurface(xwlSurface, q, server); - surface->setParent(server); - Q_ASSERT(surface->parent() == server); - surface->safeConnect(&qw_xwayland_surface::before_destroy, - q, [this, xwlSurface] { - on_surface_destroy(xwlSurface); + auto surface = new WXWaylandSurface(xwl_surface, q); + // Register the destroy listener on the surface wrapper (owner = this + // xwayland): released automatically by ~WObject when the wrapper is + // deleted. + surface->listeners(q_ptr)->add(&xwl_surface->events.destroy, this, + [this, surface] (void *) { + // Detach our own listener group: safe from inside a callback of + // this list (the closure outlives the emission). + surface->removeListeners(q_ptr); + on_surface_destroy(surface); }); - surfaceList.append(surface); q->addSurface(surface); } -void WXWaylandPrivate::on_surface_destroy(qw_xwayland_surface *xwl_surface) +void WXWaylandPrivate::on_surface_destroy(WXWaylandSurface *surface) { W_Q(WXWayland); - auto surface = WXWaylandSurface::fromHandle(xwl_surface); - Q_ASSERT(surface); + // wlroots destroys the native parent surface after emitting its destroy + // signal: it then clears the parent of each child and emits set_parent, + // but by then this wrapper (and thus the children's QPointer to it) is + // already gone, so the children would skip the parent-loss notifications. + // Apply the parent loss explicitly while the wrapper and the native + // children list are still valid. + if (auto *handle = surface->handle()) { + wlr_xwayland_surface *child, *next; + wl_list_for_each_safe(child, next, &handle->children, parent_link) { + if (auto *childSurface = WXWaylandSurface::fromHandle(child)) + WXWaylandSurfacePrivate::get(childSurface)->handleParentDestroyed(surface); + } + } + bool ok = surfaceList.removeOne(surface); Q_ASSERT(ok); q->removeSurface(surface); - surface->safeDeleteLater(); + delete surface; } -WXWayland::WXWayland(qw_compositor *compositor, bool lazy) - : WWrapObject(*new WXWaylandPrivate(this, compositor, lazy)) +WXWayland::WXWayland(wlr_compositor *compositor, bool lazy) + : QObject(nullptr) + , WWaylandResource(*new WXWaylandPrivate(this, compositor, lazy)) { W_D(WXWayland); // TODO: Add setFreezeClientWhenDisable in WSocket - d->socket = new WSocket(false, nullptr, this); + d->socket = new WSocket(false, this); +} + +WXWayland::~WXWayland() +{ + teardown(); + W_D(WXWayland); + // Release the native xwayland (wlr_xwayland_destroy asserts empty + // new_surface/ready listener lists, so detach ours first). The surface + // wrappers were already released by destroy() (WServerInterface). + if (auto *handle = this->handle()) + wlr_xwayland_destroy(handle); } QByteArray WXWayland::displayName() const { - W_DC(WXWayland); - return isValid() ? QByteArray(std::as_const(handle()->handle()->display_name)) : QByteArray(); + return isValid() ? QByteArray(handle()->display_name) : QByteArray(); } xcb_atom_t WXWayland::atom(XcbAtom type) const @@ -185,13 +289,13 @@ QVarLengthArray WXWayland::supportedAtoms() const QVarLengthArray atomList; atomList.append(atoms, atoms_len); + free(reply); return atomList; } void WXWayland::setSupportedAtoms(const QVarLengthArray &atoms) { - W_D(WXWayland); auto xcb_conn = xcbConnection(); auto root = xcbScreen()->root; @@ -202,7 +306,6 @@ void WXWayland::setSupportedAtoms(const QVarLengthArray &atoms) void WXWayland::setAtomSupported(xcb_atom_t atom, bool supported) { - W_D(WXWayland); auto xcb_conn = xcbConnection(); auto root = xcbScreen()->root; @@ -218,27 +321,127 @@ void WXWayland::setAtomSupported(xcb_atom_t atom, bool supported) } } +void WXWayland::setWorkareas(const QVector &workareas) +{ + QVector boxes; + boxes.reserve(workareas.size()); + for (const QRect &workarea : workareas) { + boxes.append({ workarea.x(), workarea.y(), workarea.width(), workarea.height() }); + } + + wlr_xwayland_set_workareas(handle(), boxes.constData(), boxes.size()); +} + +void WXWayland::setDesktopProperties(uint32_t count, + const QSize &geometry, + uint32_t current, + const QStringList &names, + const QVector &viewports, + const QVector &workareas, + bool showingDesktop) +{ + auto *connection = xcbConnection(); + if (!xcbScreen()) { + return; + } + const xcb_window_t root = xcbScreen()->root; + const auto cardinal = XCB_ATOM_CARDINAL; + const auto setCardinals = [this, connection, root, cardinal](const QByteArray &name, + const uint32_t *data, + size_t size) { + xcb_change_property(connection, + XCB_PROP_MODE_REPLACE, + root, + atom(name), + cardinal, + 32, + size, + data); + }; + + const QByteArray numberOfDesktops("_NET_NUMBER_OF_DESKTOPS"); + const QByteArray desktopGeometry("_NET_DESKTOP_GEOMETRY"); + const QByteArray currentDesktop("_NET_CURRENT_DESKTOP"); + const QByteArray desktopNames("_NET_DESKTOP_NAMES"); + const QByteArray desktopViewport("_NET_DESKTOP_VIEWPORT"); + const QByteArray desktopLayout("_NET_DESKTOP_LAYOUT"); + const QByteArray workarea("_NET_WORKAREA"); + const QByteArray showingDesktopProperty("_NET_SHOWING_DESKTOP"); + const QByteArray utf8String("UTF8_STRING"); + + const std::array supportedNames { + numberOfDesktops, + desktopGeometry, + currentDesktop, + desktopNames, + desktopViewport, + desktopLayout, + workarea, + showingDesktopProperty, + }; + auto supported = supportedAtoms(); + for (const auto &name : supportedNames) { + const xcb_atom_t propertyAtom = atom(name); + if (!supported.contains(propertyAtom)) + supported.append(propertyAtom); + } + setSupportedAtoms(supported); + + setCardinals(numberOfDesktops, &count, 1); + const uint32_t geometryData[] = { uint32_t(geometry.width()), uint32_t(geometry.height()) }; + setCardinals(desktopGeometry, geometryData, std::size(geometryData)); + setCardinals(currentDesktop, ¤t, 1); + + QByteArray encodedNames; + for (const QString &name : names) { + encodedNames.append(name.toUtf8()); + encodedNames.append('\0'); + } + xcb_change_property(connection, + XCB_PROP_MODE_REPLACE, + root, + atom(desktopNames), + atom(utf8String), + 8, + encodedNames.size(), + encodedNames.constData()); + + QVector viewportData; + viewportData.reserve(viewports.size() * 2); + for (const QPoint &viewport : viewports) { + viewportData.append(uint32_t(viewport.x())); + viewportData.append(uint32_t(viewport.y())); + } + setCardinals(desktopViewport, viewportData.constData(), viewportData.size()); + + // Horizontal, count columns, one row, starting at the top-left corner. + const uint32_t layoutData[] = { 0, count, 1, 0 }; + setCardinals(desktopLayout, layoutData, std::size(layoutData)); + const uint32_t showingDesktopData = showingDesktop; + setCardinals(showingDesktopProperty, &showingDesktopData, 1); + + setWorkareas(workareas); + xcb_flush(connection); +} + void WXWayland::setSeat(WSeat *seat) { - W_D(WXWayland); if (auto handle = this->handle()) - handle->set_seat(*seat->handle()); + wlr_xwayland_set_seat(handle, seat->handle()); } WSeat *WXWayland::seat() const { - W_DC(WXWayland); if (!handle()) return nullptr; - if (!handle()->handle()->seat) + if (!handle()->seat) return nullptr; - auto seat = qw_seat::from(handle()->handle()->seat); - return WSeat::fromHandle(seat); + return WSeat::fromHandle(handle()->seat); } xcb_connection_t *WXWayland::xcbConnection() const { - return handle()->get_xwm_connection(); + return wlr_xwayland_get_xwm_connection(handle()); } xcb_screen_t *WXWayland::xcbScreen() const @@ -247,6 +450,13 @@ xcb_screen_t *WXWayland::xcbScreen() const return d->screen; } +WXWayland *WXWayland::fromHandle(wlr_xwayland *handle) +{ + if (!handle) + return nullptr; + return static_cast(handle->data); +} + QVector WXWayland::surfaceList() const { W_DC(WXWayland); @@ -272,7 +482,7 @@ QByteArrayView WXWayland::interfaceName() const void WXWayland::addSurface(WXWaylandSurface *surface) { - surface->safeConnect(&WXWaylandSurface::isToplevelChanged, + QObject::connect(surface, &WXWaylandSurface::isToplevelChanged, this, &WXWayland::onIsToplevelChanged); if (surface->isToplevel()) @@ -286,7 +496,6 @@ void WXWayland::removeSurface(WXWaylandSurface *surface) Q_EMIT surfaceRemoved(surface); } - void WXWayland::addToplevel(WXWaylandSurface *surface) { W_D(WXWayland); @@ -323,44 +532,259 @@ void WXWayland::create(WServer *server) W_D(WXWayland); // free follow display - auto handle = qw_xwayland::create(*server->handle(), *d->compositor, d->lazy); - initHandle(handle); + auto handle = wlr_xwayland_create(server->handle(), d->compositor, d->lazy); + Q_ASSERT(handle); m_handle = handle; - d->socket->bind(handle->handle()->server->x_fd[1]); + d->socket->bind(handle->server->x_fd[1]); - QObject::connect(handle, &qw_xwayland::notify_new_surface, this, [d] (wlr_xwayland_surface *surface) { - d->on_new_surface(surface); - }); + handle->data = this; + handle->user_event_handler = xwayland_user_event_handler; + + listeners()->add(&handle->events.new_surface, d, + &WXWaylandPrivate::on_new_surface); - QObject::connect(handle, &qw_xwayland::notify_ready, this, [this, d] { + listeners()->add(&handle->events.ready, this, [this, d] (void *) { d->init(); Q_EMIT ready(); }); - auto s = qw_xwayland_server::from(handle->handle()->server); - QObject::connect(s, &qw_xwayland_server::notify_start, this, [d] { - d->socket->addClient(d->waylandClient()); + auto *serverHandle = handle->server; + listeners()->add(&serverHandle->events.start, this, [d] (void *) { + d->socket->addClient(d->waylandClient(), false); }); } -void WXWayland::destroy(WServer *server) +void WXWayland::destroy([[maybe_unused]] WServer *server) { - Q_UNUSED(server); W_D(WXWayland); + if (auto handle = this->handle()) { + if (handle->data == this) + handle->data = nullptr; + handle->user_event_handler = nullptr; + } + auto list = d->surfaceList; d->surfaceList.clear(); d->screen = nullptr; - for (auto surface : std::as_const(list)) { removeSurface(surface); - surface->safeDeleteLater(); + delete surface; } + + // Destroy the native xwayland explicitly so it is reclaimed before the + // display is torn down. teardown() (called by WServer::stop() before + // this) already detached our new_surface/ready/start listeners, which + // wlr_xwayland_destroy asserts to be empty. ~WXWayland() guards on + // handle() being null, so it won't double-destroy. + if (auto handle = this->handle()) + wlr_xwayland_destroy(handle); + m_handle = nullptr; } wl_global *WXWayland::global() const { - return handle()->handle()->shell_v1->global; + if (auto *h = handle()) + return h->shell_v1 ? h->shell_v1->global : nullptr; + return nullptr; +} + +QByteArray WXWayland::windowProperty(xcb_window_t window, + xcb_atom_t atom, + xcb_atom_t type) const +{ + auto *connection = xcbConnection(); + if (!connection || atom == XCB_ATOM_NONE) + return {}; + + QByteArray data; + uint32_t offset = 0; + uint32_t remaining = 0; + + do { + const auto cookie = + xcb_get_property(connection, false, window, atom, type, offset, 1024); + auto *reply = xcb_get_property_reply(connection, cookie, nullptr); + if (!reply) + break; + + remaining = 0; + if (reply->type == type) { + const int length = xcb_get_property_value_length(reply); + data.append(static_cast(xcb_get_property_value(reply)), length); + remaining = reply->bytes_after; + offset += length; + } + + free(reply); + } while (remaining > 0); + + return data; +} + +void WXWayland::readAsyncProperties( + xcb_window_t windowId, + const QVector &requests, + int timeoutMs, + std::function &)> callback) +{ + W_D(WXWayland); + + xcb_connection_t *conn = xcbConnection(); + if (!conn || requests.isEmpty()) { + callback(windowId, QMap{}); + return; + } + + WXWaylandPrivate::PerWindowProps props; + props.requests = requests; + props.callback = std::move(callback); + + props.cookies.reserve(requests.size()); + for (const auto &req : std::as_const(requests)) { + auto cookie = + xcb_get_property_unchecked(conn, false, windowId, req.atom, req.type, 0, 1024); + props.cookies.append(cookie); + } + xcb_flush(conn); + + // Create per-window timer. + props.timer = new QTimer(this); + props.timer->setSingleShot(true); + connect(props.timer, &QTimer::timeout, this, [d, windowId]() { + d->xcbAsyncTimeoutForWindow(windowId); + }); + props.timer->start(timeoutMs); + + d->asyncProps.insert(windowId, std::move(props)); +} + +void WXWaylandPrivate::xcbPollReplies() +{ + W_Q(WXWayland); + + if (asyncProps.isEmpty()) + return; + + xcb_connection_t *conn = q->xcbConnection(); + + QList toRemove; + + for (auto it = asyncProps.begin(); it != asyncProps.end(); ++it) { + xcb_window_t windowId = it.key(); + auto &props = it.value(); + + bool windowDone = true; + for (int i = 0; i < props.cookies.size(); ++i) { + if (props.results.contains(props.requests[i].atom)) + continue; // already got this one + + void *replyPtr = nullptr; + xcb_generic_error_t *err = nullptr; + int ret = xcb_poll_for_reply64(conn, props.cookies[i].sequence, &replyPtr, &err); + + if (ret == 0) { + windowDone = false; + continue; + } + + if (ret == 1 && replyPtr) { + auto *reply = static_cast(replyPtr); + if (reply->type != 0 && reply->value_len > 0) { + QByteArray data(static_cast(xcb_get_property_value(reply)), + xcb_get_property_value_length(reply)); + props.results.insert(props.requests[i].atom, data); + } + free(reply); + } else if (err) { + free(err); + } + } + + // Fire callback when all replies received AND propNotifySeen. + if (windowDone && props.propNotifySeen) { + auto resultCopy = props.results; + props.callback(windowId, resultCopy); + + toRemove.append(windowId); + } + } + + // Cleanup completed windows. + for (auto windowId : std::as_const(toRemove)) { + auto it = asyncProps.find(windowId); + if (it != asyncProps.end()) { + if (it->timer) { + it->timer->stop(); + delete it->timer; + } + asyncProps.erase(it); + } + } +} + +void WXWaylandPrivate::xcbAsyncTimeoutForWindow(xcb_window_t windowId) +{ + W_Q(WXWayland); + + auto it = asyncProps.find(windowId); + if (it == asyncProps.end()) + return; + + auto &props = it.value(); + + xcb_connection_t *conn = q->xcbConnection(); + if (conn) { + // Drain remaining replies. + for (int i = 0; i < props.cookies.size(); ++i) { + if (props.results.contains(props.requests[i].atom)) + continue; + void *replyPtr = nullptr; + xcb_generic_error_t *err = nullptr; + int ret = xcb_poll_for_reply64(conn, props.cookies[i].sequence, &replyPtr, &err); + if (ret == 1 && replyPtr) { + auto *reply = static_cast(replyPtr); + if (reply->type != 0 && reply->value_len > 0) { + QByteArray data(static_cast(xcb_get_property_value(reply)), + xcb_get_property_value_length(reply)); + props.results.insert(props.requests[i].atom, data); + } + free(reply); + } else { + if (replyPtr) + free(replyPtr); + if (err) + free(err); + } + } + } + + auto resultCopy = props.results; + props.callback(windowId, resultCopy); + + // Cleanup. + if (props.timer) { + delete props.timer; + } + asyncProps.erase(it); +} + +void WXWayland::cancelAsyncProperties(xcb_window_t windowId) +{ + W_D(WXWayland); + auto it = d->asyncProps.find(windowId); + if (it == d->asyncProps.end()) + return; + + if (it->timer) { + delete it->timer; + } + d->asyncProps.erase(it); +} + +bool WXWayland::event(QEvent *ev) +{ + return QObject::event(ev); } WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wxwayland.h b/waylib/src/server/protocols/wxwayland.h index 9db7e509d9..7f24d528f0 100644 --- a/waylib/src/server/protocols/wxwayland.h +++ b/waylib/src/server/protocols/wxwayland.h @@ -1,25 +1,35 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include +#include + #include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include -QW_BEGIN_NAMESPACE -class qw_xwayland; -class qw_compositor; -QW_END_NAMESPACE +Q_MOC_INCLUDE("wxwaylandsurface.h") -struct xcb_connection_t; struct xcb_screen_t; -typedef uint32_t xcb_atom_t; WAYLIB_SERVER_BEGIN_NAMESPACE class WSeat; class WXWaylandSurface; class WXWaylandPrivate; -class WAYLIB_SERVER_EXPORT WXWayland : public WWrapObject, public WServerInterface + +class WAYLIB_SERVER_EXPORT WXWayland : public QObject, public WWaylandResource, public WServerInterface { Q_OBJECT W_DECLARE_PRIVATE(WXWayland) @@ -36,15 +46,19 @@ class WAYLIB_SERVER_EXPORT WXWayland : public WWrapObject, public WServerInterfa _NET_WM_WINDOW_TYPE_MENU, _NET_WM_WINDOW_TYPE_NOTIFICATION, _NET_WM_WINDOW_TYPE_SPLASH, + _NET_WM_WINDOW_TYPE_DIALOG, _NET_SUPPORTED, AtomCount }; Q_ENUM(XcbAtom) - WXWayland(QW_NAMESPACE::qw_compositor *compositor, bool lazy = true); + static WXWayland *fromHandle(wlr_xwayland *handle); + + WXWayland(wlr_compositor *compositor, bool lazy = true); + ~WXWayland() override; - inline QW_NAMESPACE::qw_xwayland *handle() const { - return nativeInterface(); + inline wlr_xwayland *handle() const { + return reinterpret_cast(m_handle); } QByteArray displayName() const; @@ -55,12 +69,23 @@ class WAYLIB_SERVER_EXPORT WXWayland : public WWrapObject, public WServerInterfa QVarLengthArray supportedAtoms() const; void setSupportedAtoms(const QVarLengthArray &atoms); void setAtomSupported(xcb_atom_t atom, bool supported); + void setWorkareas(const QVector &workareas); + void setDesktopProperties(uint32_t count, + const QSize &geometry, + uint32_t current, + const QStringList &names, + const QVector &viewports, + const QVector &workareas, + bool showingDesktop); void setSeat(WSeat *seat); WSeat *seat() const; xcb_connection_t *xcbConnection() const; xcb_screen_t *xcbScreen() const; + QByteArray windowProperty(xcb_window_t window, + xcb_atom_t atom, + xcb_atom_t type) const; QVector surfaceList() const; @@ -75,6 +100,7 @@ class WAYLIB_SERVER_EXPORT WXWayland : public WWrapObject, public WServerInterfa void surfaceRemoved(WXWaylandSurface *surface); void toplevelAdded(WXWaylandSurface *surface); void toplevelRemoved(WXWaylandSurface *surface); + void windowPropertyChanged(WXWaylandSurface *surface, xcb_atom_t atom); protected: void addSurface(WXWaylandSurface *surface); @@ -86,6 +112,32 @@ class WAYLIB_SERVER_EXPORT WXWayland : public WWrapObject, public WServerInterfa void create(WServer *server) override; void destroy(WServer *server) override; wl_global *global() const override; + +protected: + bool event(QEvent *ev) override; + +public: + struct AsyncPropRequest + { + xcb_atom_t atom = XCB_ATOM_NONE; + xcb_atom_t type = XCB_ATOM_ANY; + }; + + // Read properties for windowId asynchronously. + // - Fires callback(result) when all replies arrive or timeoutMs elapses. + // - If a specific property was never requested, it won't be in the result map. + void readAsyncProperties( + xcb_window_t windowId, + const QVector &requests, + int timeoutMs, + std::function &)> callback); + + // Cancel pending async property read for windowId. + // Call this when the window/surface is being destroyed. + void cancelAsyncProperties(xcb_window_t windowId); + +private: + friend bool xwayland_user_event_handler(wlr_xwayland *, xcb_generic_event_t *); }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wxwaylandsurface.cpp b/waylib/src/server/protocols/wxwaylandsurface.cpp index 06aee509c7..8f58b61f74 100644 --- a/waylib/src/server/protocols/wxwaylandsurface.cpp +++ b/waylib/src/server/protocols/wxwaylandsurface.cpp @@ -1,101 +1,73 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wxwaylandsurface.h" + +#include "private/wxwaylandsurface_p.h" #include "wsurface.h" +#include "wscoplistener.h" #include "wtools.h" #include "wxwayland.h" -#include "private/wtoplevelsurface_p.h" - -#include -#include - -#define XCOORD_MAX 32767 -QW_USE_NAMESPACE -WAYLIB_SERVER_BEGIN_NAMESPACE +#include -class Q_DECL_HIDDEN WXWaylandSurfacePrivate : public WToplevelSurfacePrivate -{ -public: - WXWaylandSurfacePrivate(WXWaylandSurface *qq, qw_xwayland_surface *handle, WXWayland *xwayland) - : WToplevelSurfacePrivate(qq) - , xwayland(xwayland) - , maximized(false) - , minimized(false) - , fullscreen(false) - , activated(false) - { - initHandle(handle); - } +#include - WWRAP_HANDLE_FUNCTIONS(qw_xwayland_surface, wlr_xwayland_surface) +#include - inline bool isMaximized() const { - return nativeHandle()->maximized_horz && nativeHandle()->maximized_vert; - } +#include +#include - wl_client *waylandClient() const override { - return surface->handle()->handle()->resource->client; - } +#include - void instantRelease() override; +#include - void init(); - void updateChildren(); - void updateParent(); - void updateWindowTypes(); - - W_DECLARE_PUBLIC(WXWaylandSurface) +#define XCOORD_MAX 32767 - WSurface *surface = nullptr; - WXWayland *xwayland = nullptr; - QList children; - WXWaylandSurface *parent = nullptr; - QRect lastRequestConfigureGeometry; - WXWaylandSurface::ConfigureFlags lastRequestConfigureFlags = {0}; - WXWaylandSurface::WindowTypes windowTypes = {0}; - uint maximized:1; - uint minimized:1; - uint fullscreen:1; - uint activated:1; -}; +WAYLIB_SERVER_BEGIN_NAMESPACE -void WXWaylandSurfacePrivate::instantRelease() +WXWaylandSurfacePrivate::WXWaylandSurfacePrivate(WXWaylandSurface *qq, wlr_xwayland_surface *handle, WXWayland *xwayland) + : WToplevelSurfacePrivate(qq) + , xwayland(xwayland) + , maximized(false) + , minimized(false) + , fullscreen(false) + , activated(false) { - W_Q(WXWaylandSurface); - handle()->set_data(nullptr, nullptr); - handle()->disconnect(q); + Q_ASSERT(handle); + Q_ASSERT(!handle->data); + handle->data = qq; + m_handle = handle; +} - if (!surface) - return; - surface->safeDeleteLater(); - surface = nullptr; +WXWaylandSurfacePrivate::~WXWaylandSurfacePrivate() +{ + if (pidFD >= 0) + close(pidFD); } void WXWaylandSurfacePrivate::init() { W_Q(WXWaylandSurface); - handle()->set_data(this, q); - QObject::connect(handle(), &qw_xwayland_surface::notify_associate, q, [this, q] { - Q_ASSERT(!WSurface::fromHandle(nativeHandle()->surface)); - surface = new WSurface(qw_surface::from(nativeHandle()->surface), q); + q->listeners()->add(&m_handle->events.associate, this, [this, q] (void *) { + Q_ASSERT(!WSurface::fromHandle(handle()->surface)); + surface = new WSurface(handle()->surface); surface->setAttachedData(q); Q_EMIT q->surfaceChanged(); + Q_EMIT q->associated(); }); - QObject::connect(handle(), &qw_xwayland_surface::notify_dissociate, q, [this, q] { + q->listeners()->add(&m_handle->events.dissociate, this, [this, q] (void *) { Q_ASSERT(surface); - surface->safeDeleteLater(); + Q_EMIT q->aboutToDissociate(); + delete surface; surface = nullptr; Q_EMIT q->surfaceChanged(); }); - QObject::connect(handle(), &qw_xwayland_surface::notify_set_parent, q, [this] { - updateParent(); - }); - QObject::connect(handle(), &qw_xwayland_surface::notify_request_activate, q, &WXWaylandSurface::requestActivate); - QObject::connect(handle(), &qw_xwayland_surface::notify_request_configure, - q, [this, q] (wlr_xwayland_surface_configure_event *event) { + q->listeners()->add(&m_handle->events.set_parent, this, &WXWaylandSurfacePrivate::updateParent); + q->listeners()->add(&m_handle->events.request_activate, q, &WXWaylandSurface::requestActivate); + q->listeners()->add(&m_handle->events.request_configure, this, + [this, q] (wlr_xwayland_surface_configure_event *event) { lastRequestConfigureGeometry = QRect(event->x, event->y, event->width, event->height); lastRequestConfigureFlags = WXWaylandSurface::ConfigureFlags(event->mask); @@ -105,53 +77,84 @@ void WXWaylandSurfacePrivate::init() Q_EMIT q->requestConfigure(lastRequestConfigureGeometry, lastRequestConfigureFlags); } }); - QObject::connect(handle(), &qw_xwayland_surface::notify_request_fullscreen, q, [this, q] { - if (nativeHandle()->fullscreen) { - Q_EMIT q->requestFullscreen(); + q->listeners()->add(&m_handle->events.request_fullscreen, this, [this, q] (void *) { + if (handle()->fullscreen) { + Q_EMIT q->requestFullscreen(nullptr); } else { Q_EMIT q->requestCancelFullscreen(); } }); - QObject::connect(handle(), &qw_xwayland_surface::notify_request_maximize, q, [this, q] { - if (nativeHandle()->maximized_horz && nativeHandle()->maximized_vert) { + q->listeners()->add(&m_handle->events.request_maximize, this, [this, q] (void *) { + if (handle()->maximized_horz && handle()->maximized_vert) { Q_EMIT q->requestMaximize(); } else { Q_EMIT q->requestCancelMaximize(); } }); - QObject::connect(handle(), &qw_xwayland_surface::notify_request_minimize, - q, [this, q] (wlr_xwayland_minimize_event *event) { + q->listeners()->add(&m_handle->events.request_minimize, this, + [q] (wlr_xwayland_minimize_event *event) { if (event->minimize) { Q_EMIT q->requestMinimize(); } else { Q_EMIT q->requestCancelMinimize(); } }); - QObject::connect(handle(), &qw_xwayland_surface::notify_request_move, - q, [this, q] { + q->listeners()->add(&m_handle->events.request_move, this, [this, q] (void *) { Q_EMIT q->requestMove(xwayland->seat(), 0); }); - QObject::connect(handle(), &qw_xwayland_surface::notify_request_resize, - q, [this, q] (wlr_xwayland_resize_event *event) { + q->listeners()->add(&m_handle->events.request_resize, this, + [this, q] (wlr_xwayland_resize_event *event) { Q_EMIT q->requestResize(xwayland->seat(), WTools::toQtEdge(event->edges), 0); }); - QObject::connect(handle(), &qw_xwayland_surface::notify_set_override_redirect, - q, &WXWaylandSurface::bypassManagerChanged); - QObject::connect(handle(), &qw_xwayland_surface::notify_set_geometry, - q, &WXWaylandSurface::geometryChanged); - QObject::connect(handle(), &qw_xwayland_surface::notify_set_window_type, - q, [this] { - updateWindowTypes(); - }); - QObject::connect(handle(), &qw_xwayland_surface::notify_set_decorations, - q, &WXWaylandSurface::decorationsFlagsChanged); - QObject::connect(handle(), &qw_xwayland_surface::notify_set_title, - q, &WXWaylandSurface::titleChanged); - QObject::connect(handle(), &qw_xwayland_surface::notify_set_class, - q, &WXWaylandSurface::appIdChanged); + q->listeners()->add(&m_handle->events.request_above, this, [this, q] (void *) { + Q_EMIT q->aboveChanged(handle()->above); + }); + q->listeners()->add(&m_handle->events.request_below, this, [this, q] (void *) { + Q_EMIT q->belowChanged(handle()->below); + }); + q->listeners()->add(&m_handle->events.set_override_redirect, q, &WXWaylandSurface::bypassManagerChanged); + q->listeners()->add(&m_handle->events.set_geometry, q, &WXWaylandSurface::geometryChanged); + q->listeners()->add(&m_handle->events.set_input_shape, q, &WXWaylandSurface::inputShapeChanged); + q->listeners()->add(&m_handle->events.set_clip_shape, this, &WXWaylandSurfacePrivate::updateClipShape); + q->listeners()->add(&m_handle->events.set_size_hints, this, &WXWaylandSurfacePrivate::updateSizeHints); + q->listeners()->add(&m_handle->events.set_window_type, this, &WXWaylandSurfacePrivate::updateWindowTypes); + q->listeners()->add(&m_handle->events.set_decorations, q, &WXWaylandSurface::decorationsFlagsChanged); + q->listeners()->add(&m_handle->events.set_title, q, &WXWaylandSurface::titleChanged); + q->listeners()->add(&m_handle->events.set_class, q, &WXWaylandSurface::appIdChanged); updateChildren(); updateParent(); + updateSizeHints(); updateWindowTypes(); + updateClipShape(); +} + +void WXWaylandSurfacePrivate::updateSizeHints() +{ + W_Q(WXWaylandSurface); + + QSize minimumSize; + QSize maximumSize(INT_MAX, INT_MAX); + + if (handle()->size_hints) { + if (handle()->size_hints->flags & XCB_ICCCM_SIZE_HINT_P_MIN_SIZE) { + minimumSize = QSize(handle()->size_hints->min_width, + handle()->size_hints->min_height); + } + if (handle()->size_hints->flags & XCB_ICCCM_SIZE_HINT_P_MAX_SIZE) { + maximumSize = QSize(handle()->size_hints->max_width, + handle()->size_hints->max_height); + } + } + + if (this->minimumSize != minimumSize) { + this->minimumSize = minimumSize; + Q_EMIT q->minimumSizeChanged(this->minimumSize); + } + + if (this->maximumSize != maximumSize) { + this->maximumSize = maximumSize; + Q_EMIT q->maximumSizeChanged(this->maximumSize); + } } void WXWaylandSurfacePrivate::updateChildren() @@ -159,14 +162,14 @@ void WXWaylandSurfacePrivate::updateChildren() QList list; struct wlr_xwayland_surface *child, *next; - wl_list_for_each_safe(child, next, &nativeHandle()->children, parent_link) { - list << WXWaylandSurface::fromHandle(qw_xwayland_surface::from(child)); + wl_list_for_each_safe(child, next, &handle()->children, parent_link) { + list << WXWaylandSurface::fromHandle(child); } if (children == list) return; - const bool hasChildChanged = children.isEmpty() || list.isEmpty(); + const bool hasChildChanged = children.isEmpty() != list.isEmpty(); children = list; W_Q(WXWaylandSurface); @@ -179,20 +182,27 @@ void WXWaylandSurfacePrivate::updateChildren() void WXWaylandSurfacePrivate::updateParent() { - auto newParent = WXWaylandSurface::fromHandle(nativeHandle()->parent); + W_Q(WXWaylandSurface); + + auto newParent = WXWaylandSurface::fromHandle(handle()->parent); if (parent == newParent) return; const bool hasParentChanged = (parent == nullptr) != (newParent == nullptr); + QObject::disconnect(parentSurfaceConnection); if (parent) parent->d_func()->updateChildren(); parent = newParent; - if (parent) + if (parent) { parent->d_func()->updateChildren(); - - W_Q(WXWaylandSurface); + parentSurfaceConnection = QObject::connect(parent, + &WToplevelSurface::surfaceChanged, + q, + &WToplevelSurface::parentSurfaceChanged); + } Q_EMIT q->parentXWaylandSurfaceChanged(); + Q_EMIT q->parentSurfaceChanged(); if (hasParentChanged) Q_EMIT q->isToplevelChanged(); @@ -202,8 +212,10 @@ void WXWaylandSurfacePrivate::updateWindowTypes() { WXWaylandSurface::WindowTypes types = {0}; - for (int i = 0; i < nativeHandle()->window_type_len; ++i) { - switch (xwayland->atomType(nativeHandle()->window_type[i])) { + for (size_t i = 0; i < handle()->window_type_len; ++i) { + auto atomType = xwayland->atomType(handle()->window_type[i]); + + switch (atomType) { case WXWayland::_NET_WM_WINDOW_TYPE_NORMAL: types |= WXWaylandSurface::NET_WM_WINDOW_TYPE_NORMAL; break; @@ -234,6 +246,9 @@ void WXWaylandSurfacePrivate::updateWindowTypes() case WXWayland::_NET_WM_WINDOW_TYPE_SPLASH: types |= WXWaylandSurface::NET_WM_WINDOW_TYPE_SPLASH; break; + case WXWayland::_NET_WM_WINDOW_TYPE_DIALOG: + types |= WXWaylandSurface::NET_WM_WINDOW_TYPE_DIALOG; + break; default: break; } @@ -246,27 +261,33 @@ void WXWaylandSurfacePrivate::updateWindowTypes() Q_EMIT q_func()->windowTypesChanged(); } -WXWaylandSurface::WXWaylandSurface(qw_xwayland_surface *handle, WXWayland *xwayland, QObject *parent) - : WToplevelSurface(*new WXWaylandSurfacePrivate(this, handle, xwayland), parent) +WXWaylandSurface::WXWaylandSurface(wlr_xwayland_surface *handle, WXWayland *xwayland) + : WToplevelSurface(*new WXWaylandSurfacePrivate(this, handle, xwayland)) { d_func()->init(); } WXWaylandSurface::~WXWaylandSurface() { - -} - -WXWaylandSurface *WXWaylandSurface::fromHandle(qw_xwayland_surface *handle) -{ - return handle->get_data(); + teardown(); + // Notify listeners while the object is still usable (its members are + // alive during the destructor body). + Q_EMIT beforeDestroy(); + // Owner rule: this object created the WSurface wrapper, release it. + W_D(WXWaylandSurface); + // Clear the reverse fromHandle() mapping while the native handle is + // still alive (WXWayland deletes this wrapper from the destroy + // callback, or the creator deletes it earlier). + if (d->m_handle && d->m_handle->data == this) + d->m_handle->data = nullptr; + delete d->surface; } WXWaylandSurface *WXWaylandSurface::fromHandle(wlr_xwayland_surface *handle) { - if (auto surface = qw_xwayland_surface::get(handle)) - return fromHandle(surface); - return nullptr; + if (!handle) + return nullptr; + return static_cast(handle->data); } WXWaylandSurface *WXWaylandSurface::fromSurface(WSurface *surface) @@ -281,7 +302,13 @@ WSurface *WXWaylandSurface::surface() const return d->surface; } -qw_xwayland_surface *WXWaylandSurface::handle() const +WSurface *WXWaylandSurface::parentSurface() const +{ + W_DC(WXWaylandSurface); + return d->parent ? d->parent->surface() : nullptr; +} + +wlr_xwayland_surface *WXWaylandSurface::handle() const { W_DC(WXWaylandSurface); @@ -295,6 +322,28 @@ WXWaylandSurface *WXWaylandSurface::parentXWaylandSurface() const return d->parent; } +WXWayland *WXWaylandSurface::xwayland() const +{ + W_DC(WXWaylandSurface); + + return d->xwayland; +} + +void WXWaylandSurfacePrivate::handleParentDestroyed(WXWaylandSurface *parent) +{ + W_Q(WXWaylandSurface); + if (this->parent != parent) + return; + // Mirrors what updateParent() would do once the native set_parent event + // arrives (native parent is already NULL): the wrapper of the dying + // parent is still alive here, so the QPointer comparison can proceed. + QObject::disconnect(parentSurfaceConnection); + this->parent = nullptr; + Q_EMIT q->parentXWaylandSurfaceChanged(); + Q_EMIT q->parentSurfaceChanged(); + Q_EMIT q->isToplevelChanged(); +} + const QList &WXWaylandSurface::children() const { W_DC(WXWaylandSurface); @@ -305,13 +354,13 @@ const QList &WXWaylandSurface::children() const bool WXWaylandSurface::isToplevel() const { W_DC(WXWaylandSurface); - return !d->nativeHandle()->parent; + return !d->handle()->parent; } bool WXWaylandSurface::hasChild() const { W_DC(WXWaylandSurface); - return wl_list_empty(&d->nativeHandle()->children) == 0; + return wl_list_empty(&d->handle()->children) == 0; } bool WXWaylandSurface::isMaximized() const @@ -343,14 +392,27 @@ bool WXWaylandSurface::hasCapability(Capability cap) const W_DC(WXWaylandSurface); switch (cap) { using enum Capability; - case Focus: - return wlr_xwayland_surface_override_redirect_wants_focus(d->nativeHandle()) - && wlr_xwayland_surface_icccm_input_model(d->nativeHandle()) != WLR_ICCCM_INPUT_MODEL_NONE; - case Activate: + case Resize: + return !isBypassManager() && (minSize().width() < maxSize().width() + || minSize().height() < maxSize().height()); case Maximized: + if (isBypassManager()) { + return false; + } + return (minSize().width() < maxSize().width() && minSize().height() < maxSize().height()) + && !(d->windowTypes + & (NET_WM_WINDOW_TYPE_UTILITY | NET_WM_WINDOW_TYPE_TOOLTIP | NET_WM_WINDOW_TYPE_DND + | NET_WM_WINDOW_TYPE_DROPDOWN_MENU | NET_WM_WINDOW_TYPE_POPUP_MENU + | NET_WM_WINDOW_TYPE_COMBO | NET_WM_WINDOW_TYPE_MENU + | NET_WM_WINDOW_TYPE_NOTIFICATION | NET_WM_WINDOW_TYPE_SPLASH)); + // TODO(xwayland): To implement ICCCM focus model, refer to + // https://github.com/labwc/labwc/blob/9ba3303246b1b1bf4dbf13793faa62ec74872e3b/src/xwayland.c#L108 + case Activate: [[fallthrough]]; + case Focus: + return !isBypassManager() + && wlr_xwayland_surface_override_redirect_wants_focus(d->handle()) + && wlr_xwayland_surface_icccm_input_model(d->handle()) != WLR_ICCCM_INPUT_MODEL_NONE; case FullScreen: - case Resize: - // TODO: should check WindowType return !isBypassManager(); default: break; @@ -361,29 +423,13 @@ bool WXWaylandSurface::hasCapability(Capability cap) const QSize WXWaylandSurface::minSize() const { W_DC(WXWaylandSurface); - - if (!d->nativeHandle()->size_hints) - return QSize(); - - if (!(d->nativeHandle()->size_hints->flags & XCB_ICCCM_SIZE_HINT_P_MIN_SIZE)) - return QSize(); - - return QSize(d->nativeHandle()->size_hints->min_width, - d->nativeHandle()->size_hints->min_height); + return d->minimumSize; } QSize WXWaylandSurface::maxSize() const { W_DC(WXWaylandSurface); - - if (!d->nativeHandle()->size_hints) - return QSize(); - - if (!(d->nativeHandle()->size_hints->flags & XCB_ICCCM_SIZE_HINT_P_MAX_SIZE)) - return QSize(); - - return QSize(d->nativeHandle()->size_hints->max_width, - d->nativeHandle()->size_hints->max_height); + return d->maximumSize; } QRect WXWaylandSurface::geometry() const @@ -391,23 +437,71 @@ QRect WXWaylandSurface::geometry() const W_DC(WXWaylandSurface); QRect geometry = getContentGeometry(); - geometry.moveTopLeft(QPoint(d->nativeHandle()->x, d->nativeHandle()->y)); + geometry.moveTopLeft(QPoint(d->handle()->x, d->handle()->y)); return geometry; } +bool WXWaylandSurface::hasInputShape() const +{ + return handle()->has_input_shape; +} + +bool WXWaylandSurface::hasClipShape() const +{ + return handle()->has_clip_shape; +} + +QVariantList WXWaylandSurface::clipShape() const +{ + W_DC(WXWaylandSurface); + return d->clipShape; +} + +void WXWaylandSurfacePrivate::updateClipShape() +{ + W_Q(WXWaylandSurface); + + const QRegion region = WTools::fromPixmanRegion(&handle()->clip_shape); + const bool hasShape = handle()->has_clip_shape; + const bool regionChanged = region != clipShapeRegion; + if (!regionChanged && hasShape == hasClipShape) + return; + + if (regionChanged) { + // Merge shared edges only when the region changes, not on every + // configure notification or QML property read. + QPainterPath path; + path.addRegion(region); + const auto contours = path.simplified().toSubpathPolygons(); + QVariantList result; + result.reserve(contours.size()); + for (const auto &contour : contours) { + QVariantList points; + points.reserve(contour.size()); + for (const auto &point : contour) + points.append(point); + result.append(QVariant::fromValue(points)); + } + clipShapeRegion = region; + clipShape = result; + } + hasClipShape = hasShape; + Q_EMIT q->clipShapeChanged(); +} + QRect WXWaylandSurface::getContentGeometry() const { W_DC(WXWaylandSurface); - return QRect(0, 0, d->nativeHandle()->width, d->nativeHandle()->height); + return QRect(0, 0, d->handle()->width, d->handle()->height); } QString WXWaylandSurface::title() const { W_DC(WXWaylandSurface); - return QString::fromUtf8(d->nativeHandle()->title); + return QString::fromUtf8(d->handle()->title); } QString WXWaylandSurface::appId() const @@ -415,14 +509,25 @@ QString WXWaylandSurface::appId() const W_DC(WXWaylandSurface); // https://www.x.org/releases/X11R7.7/doc/xproto/x11protocol.html#requests:InternAtom // The string should use the ISO Latin-1 encoding. - return QString::fromLatin1(d->nativeHandle()->instance); + return QString::fromLatin1(d->handle()->instance); } pid_t WXWaylandSurface::pid() const { W_DC(WXWaylandSurface); - return d->nativeHandle()->pid; + return d->handle()->pid; +} + +int WXWaylandSurface::pidFD() const +{ + W_DC(WXWaylandSurface); + + if (d->pidFD == -1) { + d->pidFD = syscall(SYS_pidfd_open, pid(), 0); + } + + return d->pidFD; } QRect WXWaylandSurface::requestConfigureGeometry() const @@ -431,13 +536,13 @@ QRect WXWaylandSurface::requestConfigureGeometry() const QRect rect = d->lastRequestConfigureGeometry; if (!d->lastRequestConfigureFlags.testFlag(XCB_CONFIG_WINDOW_X)) - rect.moveLeft(d->nativeHandle()->x); + rect.moveLeft(d->handle()->x); if (!d->lastRequestConfigureFlags.testFlag(XCB_CONFIG_WINDOW_Y)) - rect.moveTop(d->nativeHandle()->y); + rect.moveTop(d->handle()->y); if (!d->lastRequestConfigureFlags.testFlag(XCB_CONFIG_WINDOW_WIDTH)) - rect.setWidth(d->nativeHandle()->width); + rect.setWidth(d->handle()->width); if (!d->lastRequestConfigureFlags.testFlag(XCB_CONFIG_WINDOW_HEIGHT)) - rect.setHeight(d->nativeHandle()->height); + rect.setHeight(d->handle()->height); return rect; } @@ -451,7 +556,25 @@ WXWaylandSurface::ConfigureFlags WXWaylandSurface::requestConfigureFlags() const bool WXWaylandSurface::isBypassManager() const { W_DC(WXWaylandSurface); - return d->nativeHandle()->override_redirect; + return d->handle()->override_redirect; +} + +bool WXWaylandSurface::isAbove() const +{ + W_DC(WXWaylandSurface); + return d->handle()->above; +} + +bool WXWaylandSurface::isBelow() const +{ + W_DC(WXWaylandSurface); + return d->handle()->below; +} + +bool WXWaylandSurface::isModal() const +{ + W_DC(WXWaylandSurface); + return d->handle()->modal; } WXWaylandSurface::WindowTypes WXWaylandSurface::windowTypes() const @@ -460,10 +583,38 @@ WXWaylandSurface::WindowTypes WXWaylandSurface::windowTypes() const return d->windowTypes; } +bool WXWaylandSurface::isPopupLike() const +{ + W_DC(WXWaylandSurface); + constexpr auto popupTypes = NET_WM_WINDOW_TYPE_DROPDOWN_MENU + | NET_WM_WINDOW_TYPE_POPUP_MENU + | NET_WM_WINDOW_TYPE_COMBO + | NET_WM_WINDOW_TYPE_TOOLTIP; + return d->windowTypes & popupTypes; +} + WXWaylandSurface::DecorationsFlags WXWaylandSurface::decorationsFlags() const { W_DC(WXWaylandSurface); - return WXWaylandSurface::DecorationsFlags::fromInt(d->nativeHandle()->decorations); + return WXWaylandSurface::DecorationsFlags::fromInt(d->handle()->decorations); +} + +WXWaylandSurface::DecorationsFlags +WXWaylandSurface::effectiveDecorationsFlags(xcb_atom_t noTitlebarAtom) const +{ + if (isBypassManager()) + return DecorationsFlags(DecorationsNoBorder) | DecorationsNoTitle; + + auto flags = decorationsFlags(); + if (noTitlebarAtom != XCB_ATOM_NONE + && !xwayland()->windowProperty(handle()->window_id, + noTitlebarAtom, + XCB_ATOM_CARDINAL) + .isEmpty()) { + flags |= DecorationsNoTitle; + } + + return flags; } bool WXWaylandSurface::checkNewSize(const QSize &size, QSize *clipedSize) @@ -502,12 +653,12 @@ bool WXWaylandSurface::checkNewSize(const QSize &size, QSize *clipedSize) void WXWaylandSurface::resize(const QSize &size) { W_DC(WXWaylandSurface); - handle()->configure(d->nativeHandle()->x, d->nativeHandle()->y, size.width(), size.height()); + wlr_xwayland_surface_configure(handle(), d->handle()->x, d->handle()->y, size.width(), size.height()); } void WXWaylandSurface::configure(const QRect &geometry) { - handle()->configure(geometry.x(), geometry.y(), geometry.width(), geometry.height()); + wlr_xwayland_surface_configure(handle(), geometry.x(), geometry.y(), geometry.width(), geometry.height()); } void WXWaylandSurface::setMaximize(bool on) @@ -518,7 +669,7 @@ void WXWaylandSurface::setMaximize(bool on) return; d->maximized = on; - handle()->set_maximized(on, on); + wlr_xwayland_surface_set_maximized(handle(), on, on); Q_EMIT maximizeChanged(); } @@ -526,11 +677,11 @@ void WXWaylandSurface::setMinimize(bool on) { W_D(WXWaylandSurface); - if (d->minimized == on && d->nativeHandle()->minimized == on) + if (d->minimized == on && d->handle()->minimized == on) return; d->minimized = on; - handle()->set_minimized(on); + wlr_xwayland_surface_set_minimized(handle(), on); Q_EMIT minimizeChanged(); } @@ -538,11 +689,11 @@ void WXWaylandSurface::setFullScreen(bool on) { W_D(WXWaylandSurface); - if (d->fullscreen == on && d->nativeHandle()->fullscreen == on) + if (d->fullscreen == on && d->handle()->fullscreen == on) return; d->fullscreen = on; - handle()->set_fullscreen(on); + wlr_xwayland_surface_set_fullscreen(handle(), on); Q_EMIT fullscreenChanged(); } @@ -554,23 +705,23 @@ void WXWaylandSurface::setActivate(bool on) return; d->activated = on; - handle()->activate(on); + wlr_xwayland_surface_activate(handle(), on); Q_EMIT activateChanged(); } void WXWaylandSurface::close() { - handle()->close(); + wlr_xwayland_surface_close(handle()); } void WXWaylandSurface::restack(WXWaylandSurface *sibling, StackMode mode) { if (sibling) { - handle()->restack(*sibling->handle(), static_cast(mode)); + wlr_xwayland_surface_restack(handle(), sibling->handle(), static_cast(mode)); return; } - handle()->restack(nullptr, static_cast(mode)); + wlr_xwayland_surface_restack(handle(), nullptr, static_cast(mode)); } WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/protocols/wxwaylandsurface.h b/waylib/src/server/protocols/wxwaylandsurface.h index a06a9c95e1..b5a0ce6b0c 100644 --- a/waylib/src/server/protocols/wxwaylandsurface.h +++ b/waylib/src/server/protocols/wxwaylandsurface.h @@ -1,16 +1,15 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include #include -QW_BEGIN_NAMESPACE -class qw_xwayland_surface; -QW_END_NAMESPACE +#include -struct wlr_xwayland_surface; +#include WAYLIB_SERVER_BEGIN_NAMESPACE @@ -26,9 +25,14 @@ class WAYLIB_SERVER_EXPORT WXWaylandSurface : public WToplevelSurface Q_PROPERTY(bool isToplevel READ isToplevel NOTIFY isToplevelChanged) Q_PROPERTY(bool hasChild READ hasChild NOTIFY hasChildChanged) Q_PROPERTY(bool bypassManager READ isBypassManager NOTIFY bypassManagerChanged FINAL) + Q_PROPERTY(bool above READ isAbove NOTIFY aboveChanged FINAL) + Q_PROPERTY(bool below READ isBelow NOTIFY belowChanged FINAL) Q_PROPERTY(QRect geometry READ geometry NOTIFY geometryChanged FINAL) Q_PROPERTY(WindowTypes windowTypes READ windowTypes NOTIFY windowTypesChanged FINAL) Q_PROPERTY(DecorationsFlags decorationsFlags READ decorationsFlags NOTIFY decorationsFlagsChanged FINAL) + Q_PROPERTY(bool hasInputShape READ hasInputShape NOTIFY inputShapeChanged FINAL) + Q_PROPERTY(bool hasClipShape READ hasClipShape NOTIFY clipShapeChanged FINAL) + Q_PROPERTY(QVariantList clipShape READ clipShape NOTIFY clipShapeChanged FINAL) QML_NAMED_ELEMENT(XWaylandSurface) QML_UNCREATABLE("Only create in C++") @@ -63,7 +67,8 @@ class WAYLIB_SERVER_EXPORT WXWaylandSurface : public WToplevelSurface NET_WM_WINDOW_TYPE_COMBO = 64, NET_WM_WINDOW_TYPE_MENU = 128, NET_WM_WINDOW_TYPE_NOTIFICATION = 256, - NET_WM_WINDOW_TYPE_SPLASH = 512 + NET_WM_WINDOW_TYPE_SPLASH = 512, + NET_WM_WINDOW_TYPE_DIALOG = 1024, }; Q_ENUM(WindowType) Q_DECLARE_FLAGS(WindowTypes, WindowType) @@ -76,16 +81,17 @@ class WAYLIB_SERVER_EXPORT WXWaylandSurface : public WToplevelSurface Q_ENUM(DecorationsFlag) Q_DECLARE_FLAGS(DecorationsFlags, DecorationsFlag) - explicit WXWaylandSurface(QW_NAMESPACE::qw_xwayland_surface *handle, WXWayland *xwayland, QObject *parent = nullptr); + explicit WXWaylandSurface(wlr_xwayland_surface *handle, WXWayland *xwayland); ~WXWaylandSurface(); - static WXWaylandSurface *fromHandle(QW_NAMESPACE::qw_xwayland_surface *handle); static WXWaylandSurface *fromHandle(wlr_xwayland_surface *handle); static WXWaylandSurface *fromSurface(WSurface *surface); WSurface *surface() const override; - QW_NAMESPACE::qw_xwayland_surface *handle() const; + WSurface *parentSurface() const override; + wlr_xwayland_surface *handle() const; WXWaylandSurface *parentXWaylandSurface() const; + WXWayland *xwayland() const; const QList &children() const; bool isToplevel() const; @@ -100,19 +106,28 @@ class WAYLIB_SERVER_EXPORT WXWaylandSurface : public WToplevelSurface QSize minSize() const override; QSize maxSize() const override; QRect geometry() const; + bool hasInputShape() const; + bool hasClipShape() const; + QVariantList clipShape() const; QRect getContentGeometry() const override; QString title() const override; QString appId() const override; - pid_t pid() const; + [[nodiscard]] pid_t pid() const override; + [[nodiscard]] int pidFD() const override; QRect requestConfigureGeometry() const; ConfigureFlags requestConfigureFlags() const; bool isBypassManager() const; + bool isAbove() const; + bool isBelow() const; + bool isModal() const; WindowTypes windowTypes() const; + bool isPopupLike() const; DecorationsFlags decorationsFlags() const; + DecorationsFlags effectiveDecorationsFlags(xcb_atom_t noTitlebarAtom = XCB_ATOM_NONE) const; public Q_SLOTS: bool checkNewSize(const QSize &size, QSize *clipedSize = nullptr) override; @@ -126,12 +141,21 @@ public Q_SLOTS: void restack(WXWaylandSurface *sibling, StackMode mode); Q_SIGNALS: + // Emitted after WXWaylandSurfacePrivate finishes handling notify_associate. + void associated(); + // Emitted before WXWaylandSurfacePrivate handles notify_dissociate cleanup. + void aboutToDissociate(); + void parentXWaylandSurfaceChanged(); void childrenChanged(); void isToplevelChanged(); void hasChildChanged(); void bypassManagerChanged(); + void aboveChanged(bool above); + void belowChanged(bool below); void geometryChanged(); + void inputShapeChanged(); + void clipShapeChanged(); void windowTypesChanged(); void decorationsFlagsChanged(); diff --git a/waylib/src/server/qtquick/private/wbufferrenderer.cpp b/waylib/src/server/qtquick/private/wbufferrenderer.cpp index 05e519d504..d7d66a87e6 100644 --- a/waylib/src/server/qtquick/private/wbufferrenderer.cpp +++ b/waylib/src/server/qtquick/private/wbufferrenderer.cpp @@ -1,30 +1,25 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include +#include #include "wbufferrenderer_p.h" +#include "wayliblogging.h" #include "wrenderhelper.h" #include "wqmlhelper_p.h" #include "wtools.h" #include "wsgtextureprovider.h" +#include "private/wprivateaccessor_p.h" +#include "wsgbatchrenderer_p.h" -#include -#include -#include -#include -#include -#include -#include +#include #include #include -#define protected public -#define private public #include #include #include -#undef protected -#undef private #include #include #include @@ -34,34 +29,19 @@ #include #include #endif -#include #include #include #include -QW_USE_NAMESPACE -WAYLIB_SERVER_BEGIN_NAMESPACE - -struct Q_DECL_HIDDEN PixmanRegion -{ - PixmanRegion() { - pixman_region32_init(&data); - } - ~PixmanRegion() { - pixman_region32_fini(&data); - } +using QSGAbsSoftRenderer_NodesMap = QHash; +W_DECLARE_PRIVATE_MEMBER(QSGAbsSoftRenderer_m_nodes_tag, QSGAbstractSoftwareRenderer, m_nodes, QSGAbsSoftRenderer_NodesMap); +W_DECLARE_PRIVATE_MEMBER(QSGAbsSoftRenderer_m_background_tag, QSGAbstractSoftwareRenderer, m_background, QSGSimpleRectNode*); +W_DECLARE_PRIVATE_MEMBER(QSGAbsSoftRenderer_m_dirtyRegion_tag, QSGAbstractSoftwareRenderer, m_dirtyRegion, QRegion); +W_DECLARE_PRIVATE_MEMBER(QSGSoftRenderableNode_m_hasClipRegion_tag, QSGSoftwareRenderableNode, m_hasClipRegion, bool); +W_DECLARE_PRIVATE_MEMBER(QSGSoftRenderableNode_m_opacity_tag, QSGSoftwareRenderableNode, m_opacity, float); - inline operator pixman_region32_t*() { - return &data; - } - - inline bool isEmpty() const { - return !pixman_region32_not_empty(&data); - } - - pixman_region32_t data; -}; +WAYLIB_SERVER_BEGIN_NAMESPACE inline static WImageRenderTarget *getImageFrom(const QQuickRenderTarget &rt) { @@ -70,9 +50,9 @@ inline static WImageRenderTarget *getImageFrom(const QQuickRenderTarget &rt) return static_cast(d->u.paintDevice); } -static const wlr_drm_format *pickFormat(qw_renderer *renderer, uint32_t format) +static const wlr_drm_format *pickFormat(wlr_renderer *renderer, uint32_t format) { - auto r = renderer->handle(); + auto r = renderer; if (!r->impl->get_render_formats) { return nullptr; } @@ -88,12 +68,19 @@ static void applyTransform(QSGSoftwareRenderer *renderer, const QTransform &t) if (t.isIdentity()) return; - auto nodeIter = renderer->m_nodes.begin(); - while (nodeIter != renderer->m_nodes.end()) { + auto nodeIter = W_PRIVATE_MEMBER(*renderer, QSGAbsSoftRenderer_m_nodes_tag{}).begin(); + while (nodeIter != W_PRIVATE_MEMBER(*renderer, QSGAbsSoftRenderer_m_nodes_tag{}).end()) { + // The clear node covers the render target, not the source item. Moving + // it with a negative sourceRect leaves the top/left border uncleared + // and repeatedly blends translucent SSD pixels over the old buffer. + if (nodeIter.key() == W_PRIVATE_MEMBER(*renderer, QSGAbsSoftRenderer_m_background_tag{})) { + ++nodeIter; + continue; + } auto node = *nodeIter; node->setTransform(node->transform() * t); - if (node->m_hasClipRegion) + if (W_PRIVATE_MEMBER(*node, QSGSoftRenderableNode_m_hasClipRegion_tag{})) node->setClipRegion(t.map(node->clipRegion()), true); ++nodeIter; @@ -105,7 +92,17 @@ WBufferRenderer::WBufferRenderer(QQuickItem *parent) , m_cacheBuffer(true) , m_hideSource(false) { - + // ensure graphical resources are released before scene graph is invalidated + // since WBufferRenderer's ItemHasContent bit is unset + // the invalidateSceneGraph slot will not be called through QQuickWindowPrivate::cleanupNodesOnShutdown + QMetaObject::Connection windowConn; + if (window()) + windowConn = connect(window(), &QQuickWindow::sceneGraphInvalidated, this, &WBufferRenderer::invalidateSceneGraph); + connect(this, &QQuickItem::windowChanged, this, [this, windowConn](auto *window) mutable { + disconnect(windowConn); + if (window) + windowConn = connect(window, &QQuickWindow::sceneGraphInvalidated, this, &WBufferRenderer::invalidateSceneGraph); + }); } WBufferRenderer::~WBufferRenderer() @@ -114,7 +111,6 @@ WBufferRenderer::~WBufferRenderer() resetSources(); delete m_renderHelper; - delete m_swapchain; } WOutput *WBufferRenderer::output() const @@ -162,7 +158,6 @@ void WBufferRenderer::setSourceList(QList sources, bool hideSource) return; resetSources(); - m_sourceList.clear(); m_hideSource = hideSource; for (auto s : std::as_const(sources)) { @@ -174,7 +169,8 @@ void WBufferRenderer::setSourceList(QList sources, bool hideSource) connect(s, &QQuickItem::destroyed, this, [this] { const int index = indexOfSource(static_cast(sender())); Q_ASSERT(index >= 0); - removeSource(index); + // destroySource accesses m_sourceList[index], so must be called before removeAt + destroySource(index); m_sourceList.removeAt(index); }); @@ -235,7 +231,7 @@ QSGRenderer *WBufferRenderer::currentRenderer() const return state.renderer; } -QSGBatchRenderer::Renderer *WBufferRenderer::currentBatchRenderer() const +WSGBatchRenderer::Renderer *WBufferRenderer::currentBatchRenderer() const { Q_ASSERT(state.renderer == state.batchRenderer); return state.batchRenderer; @@ -251,30 +247,40 @@ const QMatrix4x4 &WBufferRenderer::currentWorldTransform() const return state.worldTransform; } -qw_buffer *WBufferRenderer::currentBuffer() const +wlr_buffer *WBufferRenderer::currentBuffer() const { - return state.buffer; + return state.buffer.get(); } -qw_buffer *WBufferRenderer::lastBuffer() const +wlr_buffer *WBufferRenderer::lastBuffer() const { return m_lastBuffer; } QRhiTexture *WBufferRenderer::currentRenderTarget() const { + if (!state.sgRenderTarget.rt) + return nullptr; auto textureRT = static_cast(state.sgRenderTarget.rt); - return textureRT->description().colorAttachmentAt(0)->texture(); + auto colorAttachment = textureRT->description().colorAttachmentAt(0); + if (!colorAttachment) + return nullptr; + return colorAttachment->texture(); } -const qw_damage_ring *WBufferRenderer::damageRing() const +bool WBufferRenderer::isColorPreserved() const { - return &m_damageRing; + return state.renderTarget.colorPreserved(); } -qw_damage_ring *WBufferRenderer::damageRing() +const wlr_damage_ring *WBufferRenderer::damageRing() const { - return &m_damageRing; + return m_damageRing.get(); +} + +wlr_damage_ring *WBufferRenderer::damageRing() +{ + return m_damageRing.get(); } bool WBufferRenderer::isTextureProvider() const @@ -292,7 +298,7 @@ WSGTextureProvider *WBufferRenderer::wTextureProvider() const auto w = qobject_cast(window()); auto d = QQuickItemPrivate::get(this); if (!w || !d->sceneGraphRenderContext() || QThread::currentThread() != d->sceneGraphRenderContext()->thread()) { - qWarning("WBufferRenderer::textureProvider: can only be queried on the rendering thread of an WOutputRenderWindow"); + qCWarning(lcWlBufferRenderer, "WBufferRenderer::textureProvider: can only be queried on the rendering thread of an WOutputRenderWindow"); return nullptr; } @@ -330,8 +336,9 @@ QTransform WBufferRenderer::inputMapToOutput(const QRectF &sourceRect, const QRe return t; } -qw_buffer *WBufferRenderer::beginRender(const QSize &pixelSize, qreal devicePixelRatio, - uint32_t format, RenderFlags flags) +wlr_buffer *WBufferRenderer::beginRender(const QSize &pixelSize, qreal devicePixelRatio, + uint32_t format, RenderFlags flags, + WGlobal::ColorContentsMode mode) { Q_ASSERT(!state.buffer); Q_ASSERT(m_output); @@ -345,32 +352,41 @@ qw_buffer *WBufferRenderer::beginRender(const QSize &pixelSize, qreal devicePixe if (flags.testFlag(RenderFlag::DontConfigureSwapchain)) { auto renderFormat = pickFormat(m_output->renderer(), format); if (!renderFormat) { - qWarning("wlr_renderer doesn't support format 0x%s", drmGetFormatName(format)); + qCWarning(lcWlBufferRenderer, "wlr_renderer doesn't support format 0x%s", drmGetFormatName(format)); return nullptr; } - if (!m_swapchain || QSize(m_swapchain->handle()->width, m_swapchain->handle()->height) != pixelSize - || m_swapchain->handle()->format.format != renderFormat->format) { - if (m_swapchain) - delete m_swapchain; - m_swapchain = qw_swapchain::create(m_output->allocator()->handle(), pixelSize.width(), pixelSize.height(), renderFormat); + if (!m_swapchain || QSize(m_swapchain->width, m_swapchain->height) != pixelSize + || m_swapchain->format.format != renderFormat->format) { + m_swapchain.reset(wlr_swapchain_create(m_output->allocator(), pixelSize.width(), pixelSize.height(), renderFormat)); + if (!m_swapchain) + return nullptr; } } else if (flags.testFlag(RenderFlag::UseCursorFormats)) { - bool ok = m_output->configureCursorSwapchain(pixelSize, format, &m_swapchain); - if (!ok) + // The configure helpers take a wlr_swapchain**; hand ownership out + // temporarily and take it back (possibly a new swapchain) afterwards. + wlr_swapchain *sc = m_swapchain.release(); + bool ok = m_output->configureCursorSwapchain(pixelSize, format, &sc); + if (!ok) { + m_swapchain.reset(sc); return nullptr; + } + m_swapchain.reset(sc); } else { - bool ok = m_output->configurePrimarySwapchain(pixelSize, format, &m_swapchain, + wlr_swapchain *sc = m_swapchain.release(); + bool ok = m_output->configurePrimarySwapchain(pixelSize, format, &sc, !flags.testFlag(DontTestSwapchain)); - if (!ok) + if (!ok) { + m_swapchain.reset(sc); return nullptr; + } + m_swapchain.reset(sc); } // TODO: Support scanout buffer of wlr_surface(from WSurfaceItem) - auto wbuffer = m_swapchain->acquire(); - if (!wbuffer) + auto buffer = wlr_swapchain_acquire(m_swapchain.get()); + if (!buffer) return nullptr; - auto buffer = qw_buffer::from(wbuffer); if (!m_renderHelper) m_renderHelper = new WRenderHelper(m_output->renderer()); @@ -378,19 +394,19 @@ qw_buffer *WBufferRenderer::beginRender(const QSize &pixelSize, qreal devicePixe auto wd = QQuickWindowPrivate::get(window()); Q_ASSERT(wd->renderControl); - auto lastRT = m_renderHelper->lastRenderTarget(); - auto rt = m_renderHelper->acquireRenderTarget(wd->renderControl, buffer); + auto rt = m_renderHelper->acquireRenderTarget(wd->renderControl, buffer, mode); if (rt.isNull()) { - buffer->unlock(); + wlr_buffer_unlock(buffer); return nullptr; } // For software renderer, update the dirty parts relative to the last paint device. - PixmanRegion damage; - m_damageRing.rotate_buffer(wbuffer, damage); + WPixmanRegion damage; + wlr_damage_ring_rotate_buffer(m_damageRing.get(), buffer, damage); state.dirty = WTools::fromPixmanRegion(damage); - auto rtd = QQuickRenderTargetPrivate::get(&rt); + auto rtValue = rt.rt(); + auto rtd = QQuickRenderTargetPrivate::get(&rtValue); QSGRenderTarget sgRT; if (rtd->type == QQuickRenderTargetPrivate::Type::PaintDevice) { @@ -412,7 +428,6 @@ qw_buffer *WBufferRenderer::beginRender(const QSize &pixelSize, qreal devicePixe #ifndef QT_NO_OPENGL if (wd->rhi->backend() == QRhi::OpenGLES2) { auto glRT = QRHI_RES(QGles2TextureRenderTarget, rtd->u.rhiRt); - Q_ASSERT(glRT->framebuffer >= 0); auto glContext = QOpenGLContext::currentContext(); Q_ASSERT(glContext); QOpenGLContextPrivate::get(glContext)->defaultFboRedirect = glRT->framebuffer; @@ -421,10 +436,11 @@ qw_buffer *WBufferRenderer::beginRender(const QSize &pixelSize, qreal devicePixe } state.flags = flags; + state.colorContentsMode = mode; state.context = wd->context; state.pixelSize = pixelSize; state.devicePixelRatio = devicePixelRatio; - state.buffer = buffer; + state.buffer.reset(buffer); state.renderTarget = rt; state.sgRenderTarget = sgRT; @@ -437,8 +453,7 @@ inline static QRect scaleToRect(const QRectF &s, qreal scale) { } void WBufferRenderer::render(int sourceIndex, const QMatrix4x4 &renderMatrix, - const QRectF &sourceRect, const QRectF &targetRect, - bool preserveColorContents) + const QRectF &sourceRect, const QRectF &targetRect) { Q_ASSERT(state.buffer); @@ -448,7 +463,7 @@ void WBufferRenderer::render(int sourceIndex, const QMatrix4x4 &renderMatrix, const qreal devicePixelRatio = state.devicePixelRatio; state.renderer = renderer; - state.batchRenderer = dynamic_cast(renderer); + state.batchRenderer = dynamic_cast(renderer); state.worldTransform = renderMatrix; // The renderer should always receive the window's DPR (Device Pixel Ratio) // because, regardless of the DPR used for rendering, all resources within @@ -476,22 +491,22 @@ void WBufferRenderer::render(int sourceIndex, const QMatrix4x4 &renderMatrix, const auto viewportRect = scaleToRect(targetRect, devicePixelRatio); auto softwareRenderer = dynamic_cast(renderer); + const bool isVulkanRhi = wd->rhi && wd->rhi->backend() == QRhi::Vulkan; { // before render if (softwareRenderer) { // Avoid do clear before paint, for the software renderer this // work is expensive. - if (m_clearColor.alpha() == 0) - preserveColorContents = true; + const bool clearColor = !state.renderTarget.colorPreserved(); #if QT_VERSION >= QT_VERSION_CHECK(6, 9, 0) - softwareRenderer->setClearColorEnabled(!preserveColorContents); + softwareRenderer->setClearColorEnabled(clearColor); #else - auto bn = softwareRenderer->renderableNode(softwareRenderer->m_background); + auto bn = softwareRenderer->renderableNode(W_PRIVATE_MEMBER(*softwareRenderer, QSGAbsSoftRenderer_m_background_tag{})); if (bn) { - bn->m_opacity = preserveColorContents ? 0 : 1; + W_PRIVATE_MEMBER(*bn, QSGSoftRenderableNode_m_opacity_tag{}) = clearColor ? 1 : 0; } #endif if (!state.dirty.isEmpty()) { - softwareRenderer->m_dirtyRegion += state.dirty; + W_PRIVATE_MEMBER(*softwareRenderer, QSGAbsSoftRenderer_m_dirtyRegion_tag{}) += state.dirty; state.dirty = QRegion(); } @@ -502,8 +517,11 @@ void WBufferRenderer::render(int sourceIndex, const QMatrix4x4 &renderMatrix, if (!mapTransform.isIdentity()) state.worldTransform = mapTransform * state.worldTransform; state.worldTransform.optimize(); - auto image = getImageFrom(state.renderTarget); + auto image = getImageFrom(state.renderTarget.rt()); image->setDevicePixelRatio(devicePixelRatio); + if (state.colorContentsMode == WGlobal::ColorContentsMode::Clear) { + softwareRenderer->markDirty(); + } // TODO: Should set to QSGSoftwareRenderer, but it's not support specify matrix. // If transform is changed, it will full repaint. @@ -524,7 +542,7 @@ void WBufferRenderer::render(int sourceIndex, const QMatrix4x4 &renderMatrix, state.worldTransform.optimize(); bool flipY = wd->rhi ? !wd->rhi->isYUpInNDC() : false; - if (state.renderTarget.mirrorVertically()) + if (state.renderTarget.rt().mirrorVertically()) flipY = !flipY; if (viewportRect.isValid()) { @@ -565,21 +583,23 @@ void WBufferRenderer::render(int sourceIndex, const QMatrix4x4 &renderMatrix, renderer->setProjectionMatrix(projectionMatrix); renderer->setProjectionMatrixWithNativeNDC(projectionMatrixWithNativeNDC); - auto textureRT = static_cast(state.sgRenderTarget.rt); - if (preserveColorContents) { - textureRT->setFlags(textureRT->flags() | QRhiTextureRenderTarget::PreserveColorContents); - } else { - textureRT->setFlags(textureRT->flags() & ~QRhiTextureRenderTarget::PreserveColorContents); - } } } +#ifdef ENABLE_VULKAN_RENDER + if (m_renderHelper) + m_renderHelper->prepareVulkanRenderTarget(state.sgRenderTarget.cb, state.renderTarget); +#endif state.context->renderNextFrame(renderer); +#ifdef ENABLE_VULKAN_RENDER + if (m_renderHelper) + m_renderHelper->finishVulkanRenderTarget(state.sgRenderTarget.cb, state.renderTarget); +#endif { // after render if (!softwareRenderer) { // TODO: get damage area from QRhi renderer - m_damageRing.add_whole(); + wlr_damage_ring_add_whole(m_damageRing.get()); // ###: maybe Qt bug? Before executing QRhi::endOffscreenFrame, we may // use the same QSGRenderer for multiple drawings. This can lead to // rendering the same content for different QSGRhiRenderTarget instances @@ -588,16 +608,17 @@ void WBufferRenderer::render(int sourceIndex, const QMatrix4x4 &renderMatrix, // sourceIndex, we should let the RHI (Rendering Hardware Interface) // complete the results of this drawing here to ensure the current // drawing result is available for use. - wd->rhi->finish(); + if (!isVulkanRhi) + wd->rhi->finish(); } else { state.dirty = softwareRenderer->flushRegion(); - auto currentImage = getImageFrom(state.renderTarget); - Q_ASSERT(currentImage && currentImage == softwareRenderer->m_rt.paintDevice); + auto currentImage = getImageFrom(state.renderTarget.rt()); + Q_ASSERT(currentImage && currentImage == softwareRenderer->renderTarget().paintDevice); currentImage->setDevicePixelRatio(1.0); const auto scaleTF = QTransform::fromScale(devicePixelRatio, devicePixelRatio); const auto scaledFlushRegion = scaleTF.map(softwareRenderer->flushRegion()); - PixmanRegion scaledFlushDamage; + WPixmanRegion scaledFlushDamage; bool ok = WTools::toPixmanRegion(scaledFlushRegion, scaledFlushDamage); Q_ASSERT(ok); @@ -619,7 +640,7 @@ void WBufferRenderer::render(int sourceIndex, const QMatrix4x4 &renderMatrix, if (!isRootItem(source.source)) applyTransform(softwareRenderer, state.worldTransform.inverted().toTransform()); - m_damageRing.add(scaledFlushDamage); + wlr_damage_ring_add(m_damageRing.get(), scaledFlushDamage); } } @@ -629,19 +650,20 @@ void WBufferRenderer::render(int sourceIndex, const QMatrix4x4 &renderMatrix, } if (shouldCacheBuffer()) - wTextureProvider()->setBuffer(state.buffer); + wTextureProvider()->setBuffer(state.buffer.get()); } void WBufferRenderer::endRender() { - Q_ASSERT(state.buffer); - auto buffer = state.buffer; - state.buffer = nullptr; - state.renderer = nullptr; - state.batchRenderer = nullptr; + Q_ASSERT(state.buffer.get()); + { + WBufferUnlockPtr buffer; + buffer.swap(state.buffer); + state.renderer = nullptr; + state.batchRenderer = nullptr; - m_lastBuffer = buffer; - buffer->unlock(); + m_lastBuffer = buffer.get(); + } #ifndef QT_NO_OPENGL auto wd = QQuickWindowPrivate::get(window()); @@ -661,19 +683,17 @@ void WBufferRenderer::componentComplete() QQuickItem::componentComplete(); } -void WBufferRenderer::resetTextureProvider() -{ - if (m_textureProvider) - m_textureProvider->setBuffer(nullptr); -} - void WBufferRenderer::updateTextureProvider() { if (!m_textureProvider) return; - if (shouldCacheBuffer() && m_textureProvider->qwBuffer() != m_lastBuffer) { - m_textureProvider->setBuffer(m_lastBuffer); + if (shouldCacheBuffer()) { + const bool hasCachedBuffer = m_textureProvider->wlrBuffer(); + // Ensure only update the buffer when the "shouldCacheBuffer" state is changed. + // If the state is not changed, the buffer is update in the WBufferRenderer::render. + if (!hasCachedBuffer && m_lastBuffer) + m_textureProvider->setBuffer(m_lastBuffer); } else { m_textureProvider->setBuffer(nullptr); } @@ -704,11 +724,13 @@ void WBufferRenderer::invalidateSceneGraph() { if (m_textureProvider) m_textureProvider.reset(); + resetSources(); } void WBufferRenderer::releaseResources() { cleanTextureProvider(); + resetSources(); } void WBufferRenderer::cleanTextureProvider() @@ -726,32 +748,42 @@ void WBufferRenderer::cleanTextureProvider() m_textureProvider->invalidate(); // Delay clean the textures on the next render after. - window()->scheduleRenderJob(new TextureProviderCleanupJob(m_textureProvider.release()), - QQuickWindow::AfterRenderingStage); + // Only schedule render job if window is still valid + if (window()) { + window()->scheduleRenderJob(new TextureProviderCleanupJob(m_textureProvider.release()), + QQuickWindow::AfterRenderingStage); + } else { + // Window is being destroyed, clean up immediately + m_textureProvider.reset(); + } } } void WBufferRenderer::resetSources() { for (int i = 0; i < m_sourceList.size(); ++i) { - removeSource(i); + destroySource(i); } + m_sourceList.clear(); } -void WBufferRenderer::removeSource(int index) +void WBufferRenderer::destroySource(int index) { - auto s = m_sourceList.at(index); + auto &s = m_sourceList[index]; if (isRootItem(s.source)) return; // Renderer of source is delay initialized in ensureRenderer. It might be null here. - if (s.renderer) - s.renderer->deleteLater(); + if (s.renderer) { + delete s.renderer; + s.renderer = nullptr; + } + s.source->disconnect(this); + auto d = QQuickItemPrivate::get(s.source); if (d->inDestructor) return; - s.source->disconnect(this); d->derefFromEffectItem(m_hideSource); } diff --git a/waylib/src/server/qtquick/private/wbufferrenderer_p.h b/waylib/src/server/qtquick/private/wbufferrenderer_p.h index 04db44ab48..1ddca548ca 100644 --- a/waylib/src/server/qtquick/private/wbufferrenderer_p.h +++ b/waylib/src/server/qtquick/private/wbufferrenderer_p.h @@ -1,39 +1,34 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once -#include -#include +#include +#include #include +#include #include +#include + +#include #include #include -#define protected public #include -#undef protected Q_MOC_INCLUDE() QT_BEGIN_NAMESPACE class QSGPlainTexture; class QSGRenderContext; -namespace QSGBatchRenderer { +namespace WSGBatchRenderer { class Renderer; } QT_END_NAMESPACE -QW_BEGIN_NAMESPACE -class qw_buffer; -class qw_swapchain; -QW_END_NAMESPACE - struct pixman_region32; -struct wlr_swapchain; WAYLIB_SERVER_BEGIN_NAMESPACE -class WRenderHelper; class WSGTextureProvider; class WAYLIB_SERVER_EXPORT WBufferRenderer : public QQuickItem { @@ -71,14 +66,16 @@ class WAYLIB_SERVER_EXPORT WBufferRenderer : public QQuickItem void setClearColor(const QColor &clearColor); QSGRenderer *currentRenderer() const; - QSGBatchRenderer::Renderer *currentBatchRenderer() const; + WSGBatchRenderer::Renderer *currentBatchRenderer() const; qreal currentDevicePixelRatio() const; const QMatrix4x4 ¤tWorldTransform() const; - QW_NAMESPACE::qw_buffer *currentBuffer() const; - QW_NAMESPACE::qw_buffer *lastBuffer() const; + wlr_buffer *currentBuffer() const; + wlr_buffer *lastBuffer() const; + wlr_swapchain *swapchain() const { return m_swapchain.get(); } QRhiTexture *currentRenderTarget() const; - const QW_NAMESPACE::qw_damage_ring *damageRing() const; - QW_NAMESPACE::qw_damage_ring *damageRing(); + bool isColorPreserved() const; + const wlr_damage_ring *damageRing() const; + wlr_damage_ring *damageRing(); bool isTextureProvider() const override; QSGTextureProvider *textureProvider() const override; @@ -95,24 +92,23 @@ class WAYLIB_SERVER_EXPORT WBufferRenderer : public QQuickItem void afterRendering(); protected: - QW_NAMESPACE::qw_buffer *beginRender(const QSize &pixelSize, qreal devicePixelRatio, - uint32_t format, RenderFlags flags = {}); + wlr_buffer *beginRender(const QSize &pixelSize, qreal devicePixelRatio, + uint32_t format, RenderFlags flags = {}, + WGlobal::ColorContentsMode mode = WGlobal::ColorContentsMode::DontCare); void render(int sourceIndex, const QMatrix4x4 &renderMatrix, - const QRectF &sourceRect = {}, const QRectF &targetRect = {}, - bool preserveColorContents = false); + const QRectF &sourceRect = {}, const QRectF &targetRect = {}); void endRender(); void componentComplete() override; private: inline WOutputRenderWindow *renderWindow() const { - return qobject_cast(parent()); + return qobject_cast(window()); } inline bool shouldCacheBuffer() const { return m_cacheBuffer || !m_cacheBufferLocker.isEmpty(); } - void resetTextureProvider(); void updateTextureProvider(); QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data) override; @@ -125,24 +121,25 @@ class WAYLIB_SERVER_EXPORT WBufferRenderer : public QQuickItem } void resetSources(); - void removeSource(int index); + void destroySource(int index); int indexOfSource(QQuickItem *item); QSGRenderer *ensureRenderer(int sourceIndex, QSGRenderContext *rc); - QW_NAMESPACE::qw_swapchain *m_swapchain = nullptr; + WUniquePointer m_swapchain; WRenderHelper *m_renderHelper = nullptr; - QPointer m_lastBuffer; + WPointer m_lastBuffer; struct RenderState { RenderFlags flags; + WGlobal::ColorContentsMode colorContentsMode = WGlobal::ColorContentsMode::DontCare; QSGRenderContext *context; QSGRenderer *renderer; - QSGBatchRenderer::Renderer *batchRenderer; + WSGBatchRenderer::Renderer *batchRenderer; QMatrix4x4 worldTransform; QSize pixelSize; qreal devicePixelRatio; - QW_NAMESPACE::qw_buffer *buffer = nullptr; - QQuickRenderTarget renderTarget; + WBufferUnlockPtr buffer; + WRenderHelper::RenderTarget renderTarget; QSGRenderTarget sgRenderTarget; QRegion dirty; } state; @@ -155,7 +152,7 @@ class WAYLIB_SERVER_EXPORT WBufferRenderer : public QQuickItem }; QList m_sourceList; - QW_NAMESPACE::qw_damage_ring m_damageRing; + WDamageRing m_damageRing; mutable std::unique_ptr m_textureProvider; QColor m_clearColor = Qt::transparent; QList m_cacheBufferLocker; diff --git a/waylib/src/server/qtquick/private/woutputitem_p.h b/waylib/src/server/qtquick/private/woutputitem_p.h index edf75f7fad..255e9074c5 100644 --- a/waylib/src/server/qtquick/private/woutputitem_p.h +++ b/waylib/src/server/qtquick/private/woutputitem_p.h @@ -1,4 +1,4 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once @@ -6,7 +6,6 @@ #include "woutputitem.h" #include "wcursor.h" -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class WAYLIB_SERVER_EXPORT WOutputCursor : public QObject @@ -24,7 +23,12 @@ class WAYLIB_SERVER_EXPORT WOutputCursor : public QObject explicit WOutputCursor(WOutputItem *parent); inline WOutputItem *output() const { - return static_cast(parent());; + return m_output; + } + + inline void invalidate() { + m_output.clear(); + m_cursor.clear(); } WCursor *cursor() const; @@ -37,6 +41,7 @@ class WAYLIB_SERVER_EXPORT WOutputCursor : public QObject void setVisible(bool newVisible); QPointer m_cursor; + QPointer m_output; QQuickItem *item = nullptr; bool m_visible = true; }; diff --git a/waylib/src/server/qtquick/private/woutputviewport_p.h b/waylib/src/server/qtquick/private/woutputviewport_p.h index 9cd0cc1368..a45313f5b3 100644 --- a/waylib/src/server/qtquick/private/woutputviewport_p.h +++ b/waylib/src/server/qtquick/private/woutputviewport_p.h @@ -1,4 +1,4 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once @@ -7,13 +7,11 @@ #include "woutputrenderwindow.h" #include "wbufferrenderer_p.h" -#include -#include +#include #include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class OutputTextureProvider; @@ -23,7 +21,8 @@ class Q_DECL_HIDDEN WOutputViewportPrivate : public QQuickItemPrivate WOutputViewportPrivate() : attached(false) , offscreen(false) - , preserveColorContents(false) + , hideSource(true) + , colorContentsMode(WGlobal::ColorContentsMode::DontCare) , live(true) , forceRender(false) , ignoreViewport(false) @@ -81,10 +80,12 @@ class Q_DECL_HIDDEN WOutputViewportPrivate : public QQuickItemPrivate QPointer extraRenderSource; QRectF sourceRect; QRectF targetRect; + QSize bufferSize; uint attached:1; uint offscreen:1; - uint preserveColorContents:1; + uint hideSource:1; + WGlobal::ColorContentsMode colorContentsMode; uint live:1; uint forceRender:1; uint ignoreViewport:1; diff --git a/waylib/src/server/qtquick/private/wqmlhelper.cpp b/waylib/src/server/qtquick/private/wqmlhelper.cpp index 97dba3c679..66d59114be 100644 --- a/waylib/src/server/qtquick/private/wqmlhelper.cpp +++ b/waylib/src/server/qtquick/private/wqmlhelper.cpp @@ -1,16 +1,21 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 JiDe Zhang . // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wqmlhelper_p.h" -#define private public #include -#undef private - #include #include #include +#include "private/wprivateaccessor_p.h" + +W_DECLARE_PRIVATE_MEMBER(QSGNode_m_subtreeRenderableCount, QSGNode, m_subtreeRenderableCount, int); +W_DECLARE_PRIVATE_MEMBER(QSGNode_m_firstChild, QSGNode, m_firstChild, QSGNode*); +W_DECLARE_PRIVATE_MEMBER(QSGNode_m_lastChild, QSGNode, m_lastChild, QSGNode*); +W_DECLARE_PRIVATE_MEMBER(QSGNode_m_parent, QSGNode, m_parent, QSGNode*); +W_DECLARE_PRIVATE_CONST_METHOD(QImage_metric_tag, QImage, metric, int, QPaintDevice::PaintDeviceMetric); + WAYLIB_SERVER_BEGIN_NAMESPACE WImageRenderTarget::WImageRenderTarget() @@ -36,7 +41,7 @@ void WImageRenderTarget::setDevicePixelRatio(qreal dpr) int WImageRenderTarget::metric(PaintDeviceMetric metric) const { - return image->metric(metric); + return W_PRIVATE_CALL(*image, QImage_metric_tag{}, metric); } QPaintDevice *WImageRenderTarget::redirected(QPoint *offset) const @@ -129,22 +134,22 @@ QSGRootNode *WQmlHelper::getRootNode(QQuickItem *item) int &WQmlHelper::QSGNode_subtreeRenderableCount(QSGNode *node) { - return node->m_subtreeRenderableCount; + return W_PRIVATE_MEMBER(*node, QSGNode_m_subtreeRenderableCount{}); } QSGNode *&WQmlHelper::QSGNode_firstChild(QSGNode *node) { - return node->m_firstChild; + return W_PRIVATE_MEMBER(*node, QSGNode_m_firstChild{}); } QSGNode *&WQmlHelper::QSGNode_lastChild(QSGNode *node) { - return node->m_lastChild; + return W_PRIVATE_MEMBER(*node, QSGNode_m_lastChild{}); } QSGNode *&WQmlHelper::QSGNode_parent(QSGNode *node) { - return node->m_parent; + return W_PRIVATE_MEMBER(*node, QSGNode_m_parent{}); } WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/qtquick/private/wqmlhelper_p.h b/waylib/src/server/qtquick/private/wqmlhelper_p.h index 5dbdc2d99a..32148461c8 100644 --- a/waylib/src/server/qtquick/private/wqmlhelper_p.h +++ b/waylib/src/server/qtquick/private/wqmlhelper_p.h @@ -1,13 +1,11 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 JiDe Zhang . // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include #include -#define protected public #include -#undef protected QT_BEGIN_NAMESPACE class QQuickItem; diff --git a/waylib/src/server/qtquick/private/wquicksocketattached.cpp b/waylib/src/server/qtquick/private/wquicksocketattached.cpp index ac7bcf958e..0c2d281a95 100644 --- a/waylib/src/server/qtquick/private/wquicksocketattached.cpp +++ b/waylib/src/server/qtquick/private/wquicksocketattached.cpp @@ -3,6 +3,7 @@ #include "wquicksocketattached_p.h" #include "wsocket.h" +#include #include @@ -26,7 +27,7 @@ WSocket *WQuickSocketAttached::rootSocket() const WQuickSocketAttached *WQuickSocketAttached::qmlAttachedProperties(QObject *target) { - if (auto wobject = dynamic_cast(target)) { + if (auto wobject = dynamic_cast(target)) { auto client = wobject->waylandClient(); if (client) { auto socket = client->socket(); diff --git a/waylib/src/server/qtquick/private/wquicktextureproxy_p.h b/waylib/src/server/qtquick/private/wquicktextureproxy_p.h index b78f245924..adf245837b 100644 --- a/waylib/src/server/qtquick/private/wquicktextureproxy_p.h +++ b/waylib/src/server/qtquick/private/wquicktextureproxy_p.h @@ -6,6 +6,9 @@ #include "wquicktextureproxy.h" #include "private/wglobal_p.h" +#include +#include + WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WQuickTextureProxyPrivate : public WObjectPrivate @@ -28,6 +31,8 @@ class Q_DECL_HIDDEN WQuickTextureProxyPrivate : public WObjectPrivate QRectF sourceRect; bool hideSource = false; bool mipmap = false; + QMetaObject::Connection textureChangedConnection; + QMutex connectionMutex; }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/qtquick/private/wrenderbuffernode.cpp b/waylib/src/server/qtquick/private/wrenderbuffernode.cpp index a64b05e55f..c4e46a0287 100644 --- a/waylib/src/server/qtquick/private/wrenderbuffernode.cpp +++ b/waylib/src/server/qtquick/private/wrenderbuffernode.cpp @@ -1,18 +1,20 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include -#define protected public -#define private public -#include -#include -#undef protected -#undef private +#include "wrenderhelper.h" +#include "wayliblogging.h" #include "wrenderbuffernode_p.h" #include "wbufferrenderer_p.h" +#include "wglobal.h" +#include "wpointer.h" #include "wqmlhelper_p.h" #include "platformplugin/types.h" +#include "private/wprivateaccessor_p.h" +#include "wsgbatchrenderer_p.h" + +#include #include #include @@ -25,9 +27,61 @@ #include #include #include +#include #include +// QSGRenderer: access protected methods preprocess()/render() and private +// bit-field members m_changed_emitted/m_is_rendering. +// +// preprocess() and render() are protected virtual functions — the template +// accessor [temp.explicit]/12 trick legally bypasses access control here too. +// +// m_changed_emitted and m_is_rendering are private bit fields packed into a +// single uint that immediately follows m_nodes_dont_preprocess. Use +// W_DECLARE_PRIVATE_BITFIELD to reach that storage unit via memory arithmetic. +// Declaration order → bit position (GCC/Clang little-endian LSB-first): +// m_changed_emitted : 1 → bit 0 +// m_is_rendering : 1 → bit 1 +W_DECLARE_PRIVATE_METHOD(QSGRenderer_preprocess_tag, QSGRenderer, preprocess, void); +W_DECLARE_PRIVATE_METHOD(QSGRenderer_render_tag, QSGRenderer, render, void); +W_DECLARE_PRIVATE_BITFIELD(QSGRenderer_m_nodes_dont_preprocess_tag, + QSGRenderer, m_nodes_dont_preprocess, + QSet, uint); +static constexpr unsigned k_m_changed_emitted_bit = 0; +static constexpr unsigned k_m_is_rendering_bit = 1; + +// Compile-time layout verification. +// +// W_DECLARE_PRIVATE_BITFIELD already checks at compile time that +// m_nodes_dont_preprocess exists in QSGRenderer with the correct type. +// What it cannot verify is whether the bit fields still immediately follow +// that member in the class layout. +// +// Since the bit fields are the last members of QSGRenderer (Qt 6.11.1, +// qsgrenderer_p.h:137–144), any insertion or reordering of members changes +// sizeof(QSGRenderer). We assert the known size as a layout fingerprint. +// If this fires, diff qsgrenderer_p.h and update the accessor + constant below. +// +// Verified: Qt 6.11.1, x86_64 Linux. +#if defined(Q_PROCESSOR_X86_64) && (defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD)) +static_assert(sizeof(QSGRenderer) == 432, + "QSGRenderer size changed — review qsgrenderer_p.h and update the bit-field accessor"); +#endif + +static inline WSGBatchRenderer::ShaderManager *rendererShaderManager(WSGBatchRenderer::Renderer *r) { + return r ? r->shaderManager() : nullptr; +} +static inline bool rendererUseDepthBuffer(const WSGBatchRenderer::Renderer *r) { + return r && r->usesDepthBuffer(); +} +static inline void rendererPreprocess(QSGRenderer *r) { + W_PRIVATE_CALL(*r, QSGRenderer_preprocess_tag{}); +} +static inline void rendererRender(QSGRenderer *r) { + W_PRIVATE_CALL(*r, QSGRenderer_render_tag{}); +} + WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN DataManagerBase : public QObject @@ -36,7 +90,17 @@ class Q_DECL_HIDDEN DataManagerBase : public QObject mutable QAtomicInt ref; explicit DataManagerBase(QQuickWindow *owner) - : QObject(owner) {} + : QObject(owner) + { + Q_ASSERT(owner->isSceneGraphInitialized()); + connect(owner, &QQuickWindow::sceneGraphInvalidated, this, [this]() { + setParent(nullptr); + // per request from zccrs. + // Be Warned: objects may not be expected to be deleted in the rendering thread. + delete this; + }, static_cast(Qt::DirectConnection | Qt::SingleShotConnection)); + } + virtual ~DataManagerBase() {}; }; template @@ -135,8 +199,8 @@ class Q_DECL_HIDDEN DataManager : public DataManagerBase return owner->findChild({}, Qt::FindDirectChildrenOnly); } - static DataManagerPointer resolve(const DataManagerPointer &other, QQuickWindow *owner) { - static_assert(&Derive::metaObject); + static DataManagerPointer resolveByOwner(const DataManagerPointer &other, QQuickWindow *owner) { + static_assert(QtPrivate::HasQ_OBJECT_Macro::Value, "Derive must have Q_OBJECT macro"); Q_ASSERT(owner); if (other && other->owner() == owner) return other; @@ -162,8 +226,7 @@ class Q_DECL_HIDDEN DataManager : public DataManagerBase DataManager *manager; }; - TryClean cleanJob(this); - Q_UNUSED(cleanJob) + [[maybe_unused]] TryClean cleanJob(this); { auto d = data.lock(); @@ -183,8 +246,9 @@ class Q_DECL_HIDDEN DataManager : public DataManagerBase } } - auto newData = std::shared_ptr(new Data()); - if ((newData->data = get()->create(std::forward(keys)...))) { + auto newData = std::make_shared(); + newData->data = get()->create(std::forward(keys)...); + if (newData->data) { dataList.append(newData); return newData; } @@ -210,13 +274,17 @@ class Q_DECL_HIDDEN DataManager : public DataManagerBase manager->cleanJob = nullptr; + // Collect items to destroy outside the manager's dataList + // to avoid accessing manager during shared_ptr destruction + QList itemsToDestroy; QList> tmp; - std::swap(manager->dataList, tmp); + tmp.swap(manager->dataList); manager->dataList.reserve(tmp.size()); for (const auto &data : std::as_const(tmp)) { if (data->released > 2) { - manager->get()->destroy(data->data); + // Collect items to destroy instead of destroying immediately + itemsToDestroy.append(data->data); } else { manager->dataList << data; @@ -224,6 +292,12 @@ class Q_DECL_HIDDEN DataManager : public DataManagerBase ++data->released; } } + + // Destroy items after we're done accessing manager + // This prevents crashes from shared_ptr destruction during dataList iteration + for (auto item : std::as_const(itemsToDestroy)) { + manager->get()->destroy(item); + } } QPointer manager; @@ -244,49 +318,75 @@ class Q_DECL_HIDDEN DataManager : public DataManagerBase return static_cast(this); } - DataManager(QQuickWindow *owner) - : DataManagerBase(owner) { - Q_ASSERT(owner->findChildren(Qt::FindDirectChildrenOnly).size() == 0); - } - using QObject::deleteLater; - ~DataManager() { + ~DataManager() override { for (auto data : std::as_const(dataList)) { Derive::destroy(data->data); } } +private: + friend Derive; + + DataManager(QQuickWindow *owner) + : DataManagerBase(owner) { + Q_ASSERT(owner->findChildren(Qt::FindDirectChildrenOnly).size() == 0); + } + +protected: + QList> dataList; QRunnable *cleanJob = nullptr; }; -class Q_DECL_HIDDEN RhiTextureManager : public DataManager +struct WlrAndRhiTexture { + // Raw pointers: the resources must be released in a specific order + // (rhi texture, then wlr texture, then buffer), see RhiTextureManager::destroy. + struct wlr_buffer *buffer = nullptr; + wlr_texture *wlrTexture = nullptr; + QRhiTexture *rhiTexture = nullptr; +}; + +class Q_DECL_HIDDEN RhiTextureManager : public DataManager { Q_OBJECT friend class DataManager; RhiTextureManager(QQuickWindow *owner) - : DataManager(owner) { + : DataManager(owner) { Q_ASSERT(owner->findChildren(Qt::FindDirectChildrenOnly).size() == 1); } - static bool check(QRhiTexture *texture, QRhiTexture::Format format, const QSize &size) { - return texture->format() == format && texture->pixelSize() == size; + static bool check(WlrAndRhiTexture *texture, QRhiTexture::Format, uint32_t drmFormat, uint64_t drmModifier, const QSize &size) { + auto *buffer = texture->buffer; + wlr_dmabuf_attributes attribs; + if (!wlr_buffer_get_dmabuf(buffer, &attribs)) { + qCWarning(lcWlRenderBuffer) << "Failed to get dmabuf attributes for texture" << texture << "with buffer" << buffer + << ", Can't check texture without dmabuf attributes"; + return false; + } + return attribs.format == drmFormat && attribs.modifier == drmModifier && texture->rhiTexture->pixelSize() == size; } - QRhiTexture *create(QRhiTexture::Format format, const QSize &size) { - auto texture = owner()->rhi()->newTexture(format, size, 1, QRhiTexture::RenderTarget); - if (!texture->create()) { - delete texture; + WlrAndRhiTexture *create(QRhiTexture::Format format, uint32_t drmFormat, uint64_t drmModifier, const QSize &size) { + auto ow = qobject_cast(owner()); + auto texture = WRenderHelper::newTexture(ow->allocator(), ow->renderer(), + drmFormat, drmModifier, owner()->rhi(), + size, format, QRhiTexture::RenderTarget); + if (!texture.rhiTexture) return nullptr; - } - return texture; + return new WlrAndRhiTexture{texture.buffer, texture.texture, texture.rhiTexture}; } - static void destroy(QRhiTexture *texture) { - texture->deleteLater(); + static void destroy(WlrAndRhiTexture *texture) { + delete texture->rhiTexture; + if (texture->wlrTexture) + wlr_texture_destroy(texture->wlrTexture); + if (texture->buffer) + wlr_buffer_drop(texture->buffer); + delete texture; } }; @@ -316,11 +416,7 @@ class Q_DECL_HIDDEN RhiManager : public DataManager // If have a base QSGRenderer, we should inherit the depth test from // baseProjectionMatrix. renderer->setProjectionMatrix(baseProjectionMatrix); -#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) renderer->setProjectionMatrixWithNativeNDC(base->projectionMatrixWithNativeNDC(0)); -#else - renderer->setProjectionMatrixWithNativeNDC(base->projectionMatrixWithNativeNDC()); -#endif } else { renderer->setDevicePixelRatio(1.0); renderer->setDeviceRect(QRect(QPoint(0, 0), pixelSize)); @@ -334,13 +430,8 @@ class Q_DECL_HIDDEN RhiManager : public DataManager } if (Q_UNLIKELY(!matrix.isIdentity())) { -#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) renderer->setProjectionMatrix(renderer->projectionMatrix(0) * matrix); renderer->setProjectionMatrixWithNativeNDC(renderer->projectionMatrixWithNativeNDC(0) * matrix); -#else - renderer->setProjectionMatrix(renderer->projectionMatrix() * matrix); - renderer->setProjectionMatrixWithNativeNDC(renderer->projectionMatrixWithNativeNDC() * matrix); -#endif } renderer->setRootNode(rootNode); @@ -358,31 +449,31 @@ class Q_DECL_HIDDEN RhiManager : public DataManager oldCB = dc->currentFrameCommandBuffer(); context->prepareSync(renderer->devicePixelRatio(), cb, graphicsConfiguration()); - renderer->m_is_rendering = true; - renderer->preprocess(); + W_PRIVATE_BF_SET(*renderer, QSGRenderer_m_nodes_dont_preprocess_tag, k_m_is_rendering_bit, true); + rendererPreprocess(renderer); return true; } bool render(qreal oldDPR, QRhiCommandBuffer* &oldCB, bool forceDepthTest = false) { - Q_ASSERT(renderer->m_is_rendering); - renderer->render(); - renderer->m_is_rendering = false; - renderer->m_changed_emitted = false; + Q_ASSERT(W_PRIVATE_BF_GET(*renderer, QSGRenderer_m_nodes_dont_preprocess_tag, k_m_is_rendering_bit)); + rendererRender(renderer); + W_PRIVATE_BF_SET(*renderer, QSGRenderer_m_nodes_dont_preprocess_tag, k_m_is_rendering_bit, false); + W_PRIVATE_BF_SET(*renderer, QSGRenderer_m_nodes_dont_preprocess_tag, k_m_changed_emitted_bit, false); context->prepareSync(oldDPR, oldCB, graphicsConfiguration()); bool ok = false; do { if (forceDepthTest && Q_LIKELY(isBatchRenderer)) { - auto batchRenderer = static_cast(renderer); - if (auto sm = batchRenderer->m_shaderManager) { + auto batchRenderer = static_cast(renderer); + if (auto sm = rendererShaderManager(batchRenderer)) { if (Q_LIKELY(!sm->pipelineCache.isEmpty())) { QVector> tmp; tmp.reserve(sm->pipelineCache.size()); for (auto pipeline : std::as_const(sm->pipelineCache)) { - tmp.append({pipeline, pipeline->hasDepthTest()}); + tmp.append(std::make_pair(pipeline, pipeline->hasDepthTest())); pipeline->setDepthTest(true); } ok = rhi()->endOffscreenFrame() == QRhi::FrameOpSuccess; @@ -439,10 +530,10 @@ class Q_DECL_HIDDEN RhiManager : public DataManager // renderer is using depth test, and the other QSGRenderer is not finished render. // For an example: RhiNode to render its content nodes on an exists renderTarget. renderer = context->createRenderer(QSGRendererInterface::RenderMode2DNoDepthBuffer); - isBatchRenderer = dynamic_cast(renderer); + isBatchRenderer = dynamic_cast(renderer); } - ~RhiManager() { + ~RhiManager() override { delete renderer; } @@ -616,6 +707,18 @@ class Q_DECL_HIDDEN RhiNode : public WRenderBufferNode { return; } + auto buffer = WRenderHelper::lookupBuffer(ct); + if (!buffer) { + reset(); + return; + } + + wlr_dmabuf_attributes attribs; + if (!wlr_buffer_get_dmabuf(buffer, &attribs)) { + reset(); + return; + } + const auto currentRenderer = maybeBufferRenderer(); // TODO: Apple viewport to matrix, needs get QSGRenderer renderMatrix = currentRenderer @@ -623,7 +726,7 @@ class Q_DECL_HIDDEN RhiNode : public WRenderBufferNode { : *this->matrix(); devicePixelRatio = effectiveDevicePixelRatio(); const auto oldManager = manager; - manager = RhiTextureManager::resolve(manager, window); + manager = RhiTextureManager::resolveByOwner(manager, window); if (oldManager != manager) { sgTexture()->setTexture(nullptr); @@ -633,7 +736,7 @@ class Q_DECL_HIDDEN RhiNode : public WRenderBufferNode { } Q_ASSERT(ct->rhi() == window->rhi()); - rhi = rhi->resolve(rhi, window); + rhi = rhi->resolveByOwner(rhi, window); Q_ASSERT(rhi); const bool hasRotation = renderMatrix.flags().testAnyFlags(QMatrix4x4::Rotation2D | QMatrix4x4::Rotation); @@ -670,7 +773,11 @@ class Q_DECL_HIDDEN RhiNode : public WRenderBufferNode { pixelSize = size.toSize(); } - texture = manager->resolve(texture, ct->format(), pixelSize); + { + auto format = attribs.format; + auto modifier = attribs.modifier; + texture = manager->resolve(texture, ct->format(), std::move(format), std::move(modifier), pixelSize); + } if (Q_UNLIKELY(texture.expired())) { reset(); return; @@ -679,8 +786,8 @@ class Q_DECL_HIDDEN RhiNode : public WRenderBufferNode { Q_ASSERT(texture->data); if (renderData) { - if (!renderData->rt || sgTexture()->rhiTexture() != texture->data) { - QRhiTextureRenderTargetDescription rtDesc(texture->data); + if (!renderData->rt || sgTexture()->rhiTexture() != texture->data->rhiTexture) { + QRhiTextureRenderTargetDescription rtDesc(texture->data->rhiTexture); const auto flags = QRhiTextureRenderTarget::PreserveColorContents | QRhiTextureRenderTarget::PreserveDepthStencilContents; auto newRT = rhi->rhi()->newTextureRenderTarget(rtDesc, flags); @@ -702,12 +809,11 @@ class Q_DECL_HIDDEN RhiNode : public WRenderBufferNode { } } - void render(const RenderState *state) override { - Q_UNUSED(state) - + void render([[maybe_unused]] const RenderState *state) override { auto texture = this->texture.lock(); if (Q_UNLIKELY(!texture)) return; + auto rhiTexture = texture->data->rhiTexture; auto ct = currentRenderTexture(); Q_ASSERT(ct); @@ -719,19 +825,25 @@ class Q_DECL_HIDDEN RhiNode : public WRenderBufferNode { const QPointF sourcePos = renderMatrix.map(m_rect.topLeft()); renderData->imageNode->setRect(QRectF(-(devicePixelRatio - 1) * sourcePos, ct->pixelSize())); - rhi->sync(texture->data->pixelSize(), &renderData->rootNode, renderMatrix.inverted(), {}, nullptr, - {texture->data->pixelSize().width() / float(m_rect.width() * devicePixelRatio), - texture->data->pixelSize().height() / float(m_rect.height() * devicePixelRatio)}); + rhi->sync(rhiTexture->pixelSize(), &renderData->rootNode, renderMatrix.inverted(), {}, nullptr, + {rhiTexture->pixelSize().width() / float(m_rect.width() * devicePixelRatio), + rhiTexture->pixelSize().height() / float(m_rect.height() * devicePixelRatio)}); rhi->render(renderData->rt.get()); } else { - auto rhi = this->rhi->rhi(); - QPointF sourcePos = renderMatrix.map(m_rect.topLeft()) * devicePixelRatio; + const QPoint sourcePos = (renderMatrix.map(m_rect.topLeft()) * devicePixelRatio).toPoint(); + const QRect sourceTextureRect(sourcePos, rhiTexture->pixelSize()); + const QRect renderTargetRect(QPoint(0, 0), ct->pixelSize()); + const QRect copySourceRect = sourceTextureRect.intersected(renderTargetRect); + if (copySourceRect.isEmpty()) + return; + auto rhi = this->rhi->rhi(); auto rub = rhi->nextResourceUpdateBatch(); QRhiTextureCopyDescription desc; - desc.setPixelSize(texture->data->pixelSize()); - desc.setSourceTopLeft(sourcePos.toPoint()); - rub->copyTexture(texture->data, ct, desc); + desc.setPixelSize(copySourceRect.size()); + desc.setSourceTopLeft(copySourceRect.topLeft()); + desc.setDestinationTopLeft(copySourceRect.topLeft() - sourcePos); + rub->copyTexture(rhiTexture, ct, desc); QRhiCommandBuffer *cb = nullptr; if (rhi->beginOffscreenFrame(&cb) != QRhi::FrameOpSuccess) @@ -743,8 +855,8 @@ class Q_DECL_HIDDEN RhiNode : public WRenderBufferNode { rhi->endOffscreenFrame(); } - if (sgTexture()->rhiTexture() != texture->data) - sgTexture()->setTexture(texture->data); + if (sgTexture()->rhiTexture() != rhiTexture) + sgTexture()->setTexture(rhiTexture); doNotifyTextureChanged(); if (contentNode) { @@ -757,7 +869,7 @@ class Q_DECL_HIDDEN RhiNode : public WRenderBufferNode { // If the source renderer enable depth test, we should enable depth test also, // to ensure the contentNode's z order on RenderMode2DNoDepthBuffer render mode. const bool forceDepthTest = currentRenderer && currentRenderer->currentBatchRenderer() - && currentRenderer->currentBatchRenderer()->useDepthBuffer(); + && rendererUseDepthBuffer(currentRenderer->currentBatchRenderer()); if (clipList() || inheritedOpacity() < 1.0) { if (!node) @@ -984,8 +1096,7 @@ class Q_DECL_HIDDEN SoftwareNode : public WRenderBufferNode { return image.expired() ? QImage() : *image.lock()->data; } - void render(const RenderState *state) override { - Q_UNUSED(state) + void render([[maybe_unused]] const RenderState *state) override { auto window = renderWindow(); if (!window) return; @@ -999,7 +1110,7 @@ class Q_DECL_HIDDEN SoftwareNode : public WRenderBufferNode { const auto matrix = /*(sgRenderer && sgRenderer->renderTarget().paintDevice == p->device()) ? currentRenderer->currentWorldTransform() * (*this->matrix()) :*/ *this->matrix(); const auto oldManager = manager; - manager = QImageManager::resolve(manager, window); + manager = QImageManager::resolveByOwner(manager, window); if (oldManager != manager) { texture()->setTexture(nullptr); @@ -1110,7 +1221,7 @@ QRectF WRenderBufferNode::rect() const WRenderBufferNode::RenderingFlags WRenderBufferNode::flags() const { - return BoundedRectRendering; + return BoundedRectRendering | DepthAwareRendering; } void WRenderBufferNode::resize(const QSizeF &size) diff --git a/waylib/src/server/qtquick/private/wsurfaceitem_p.h b/waylib/src/server/qtquick/private/wsurfaceitem_p.h index f0cfa451c9..fc8ca88dba 100644 --- a/waylib/src/server/qtquick/private/wsurfaceitem_p.h +++ b/waylib/src/server/qtquick/private/wsurfaceitem_p.h @@ -1,14 +1,16 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include "wsurfaceitem.h" +#include "wsubsurface.h" #include "wsurface.h" #include #include #include +#include #include WAYLIB_SERVER_BEGIN_NAMESPACE @@ -32,12 +34,19 @@ class Q_DECL_HIDDEN WSurfaceItemPrivate : public QQuickItemPrivate void initForSurface(); void initForDelegate(); - void onHasSubsurfaceChanged(); void updateSubsurfaceItem(); + void updateBackgroundBlurRegion(); void onPaddingsChanged(); void updateContentPosition(); - WSurfaceItem *ensureSubsurfaceItem(WSurface *subsurfaceSurface, QQuickItem *parent); + WSurfaceItem *ensureSubsurfaceItem(WSubsurface *subsurface); + void removeSubsurfaceItem(WSubsurface *subsurface); void updateSubsurfaceContainers(); + void updateSubsurfaceContainer(WSubsurface::Place place, + const QList &subsurfaces, + QPointer &container); + void cleanupSubsurfaceContainers(); + void reorderSubsurfaceItems(); + void updateSubsurfacePositions(); void resizeSurfaceToItemSize(const QSize &itemSize, const QSize &sizeDiff); void updateEventItem(bool forceDestroy); @@ -66,23 +75,23 @@ class Q_DECL_HIDDEN WSurfaceItemPrivate : public QQuickItemPrivate QPointer surface; QPointer shellSurface; std::unique_ptr surfaceState; + pixman_region32_t backgroundBlurRegion; QQuickItem *contentContainer = nullptr; QQmlComponent *delegate = nullptr; bool delegateIsDirty = false; QQuickItem *eventItem = nullptr; - QPointer belowSubsurfaceContainer = nullptr; - QPointer aboveSubsurfaceContainer = nullptr; + QPointer belowSubsurfaceContainer; + QPointer aboveSubsurfaceContainer; WSurfaceItem::ResizeMode resizeMode = WSurfaceItem::SizeFromSurface; WSurfaceItem::Flags surfaceFlags; QMarginsF paddings; - QList subsurfaces; qreal surfaceSizeRatio = 1.0; bool live = true; bool subsurfacesVisible = true; uint32_t beforeRequestResizeSurfaceStateSeq = 0; QRectF boundingRect; + bool ready = false; }; WAYLIB_SERVER_END_NAMESPACE - diff --git a/waylib/src/server/qtquick/scenegraph/README.md b/waylib/src/server/qtquick/scenegraph/README.md new file mode 100644 index 0000000000..1f35a2526a --- /dev/null +++ b/waylib/src/server/qtquick/scenegraph/README.md @@ -0,0 +1,41 @@ +# WSGBatchRenderer + +Vendored fork of Qt Quick's `QSGBatchRenderer`. + +## Source + +- Tag: `v6.11.1` (base; version-gated to also build against 6.8.0 and 6.12.x) +- Commit: `a02bed441965ee1f18f856352c7d5ee5ba35d795` +- Upstream files: + - `src/quick/scenegraph/coreapi/qsgbatchrenderer.cpp` + - `src/quick/scenegraph/coreapi/qsgbatchrenderer_p.h` + - `src/quick/scenegraph/coreapi/qsgrhivisualizer.cpp` + - `src/quick/scenegraph/coreapi/qsgrhivisualizer_p.h` + +## Local changes vs upstream + +- Namespace `QSGBatchRenderer` renamed to `WSGBatchRenderer` to avoid clashing with `Q_QUICK_EXPORT` symbols in Qt6Quick. +- File and include-guard names renamed to `wsg*`. +- `qt_sg_envInt` inlined (not exported from Qt). +- `Q_QUICK_EXPORT` dropped from `Renderer` (same DSO as waylibserver). +- `QSGNode::m_subtreeRenderableCount` read via waylib's private accessor (Qt friends `QSGBatchRenderer::Renderer` only). +- Public helpers on `Renderer`: `create()`, `usesDepthBuffer()`, `shaderManager()`. +- `QSGSamplerDescription` compare/hash/`fromTexture` copied locally (Qt does not export them). +- Version gates so one copy builds against Qt 6.8.0, 6.11.x and 6.12.x: + - 6.8.0: one-arg `fullDynamicBufferUpdateForCurrentFrame` + - 6.9.2+: `invertFrontFace()` for layer culling + - 6.12+: node mutability groups stay neutral (`QSGNodePrivate` is not + exported), matching the 6.11 invalidation rules +- `WSGContext` covers `QQuickRenderControlPrivate::sg` before the first + `QQuickRenderControl` is constructed (`WOutputRenderWindow` and + `WRenderHelper::getGraphicsApi()`). Its render context overrides + `createRenderer()` so the window renderer is created as `WSGBatchRenderer` + in `syncSceneGraph()`, instead of swapping Qt's renderer after `sync()`. + If `QSGContext::createDefaultContext()` is not a `QSGDefaultContext` + (software or another adaptation), that context is kept as `sg`. +- Extra sources / `WRenderBufferNode` create renderers via `rc->createRenderer()`. +- Damage tracking is not in this step; do not strip opaque/alpha/depth here either. + +## Upgrade + +When bumping the base Qt, three-way merge these four files against the recorded commit, then re-apply the rename, accessors, and `QT_VERSION_CHECK` gates. diff --git a/waylib/src/server/qtquick/scenegraph/wsgbatchrenderer.cpp b/waylib/src/server/qtquick/scenegraph/wsgbatchrenderer.cpp new file mode 100644 index 0000000000..c76c51f769 --- /dev/null +++ b/waylib/src/server/qtquick/scenegraph/wsgbatchrenderer.cpp @@ -0,0 +1,4396 @@ +// Copyright (C) 2019 The Qt Company Ltd. +// Copyright (C) 2016 Jolla Ltd, author: +// Copyright (C) 2016 Robin Burchell +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wsgbatchrenderer_p.h" + +#include + +#include +#include + +#include + +#include +#include + +#include "wsgrhivisualizer_p.h" + +#include + +#include "private/wprivateaccessor_p.h" + +// QSGNode friends QSGBatchRenderer::Renderer, not this fork. +W_DECLARE_PRIVATE_MEMBER(WSG_QSGNode_m_subtreeRenderableCount, QSGNode, m_subtreeRenderableCount, int); + +QT_BEGIN_NAMESPACE + +// QSGSamplerDescription helpers live in Qt's qsgtexture.cpp without +// Q_QUICK_EXPORT, so they are not visible to this DSO. +bool operator==(const QSGSamplerDescription &a, const QSGSamplerDescription &b) noexcept +{ + return a.filtering == b.filtering + && a.mipmapFiltering == b.mipmapFiltering + && a.horizontalWrap == b.horizontalWrap + && a.verticalWrap == b.verticalWrap + && a.anisotropylevel == b.anisotropylevel; +} + +bool operator!=(const QSGSamplerDescription &a, const QSGSamplerDescription &b) noexcept +{ + return !(a == b); +} + +size_t qHash(const QSGSamplerDescription &s, size_t seed) noexcept +{ + const int f = s.filtering; + const int m = s.mipmapFiltering; + const int w = s.horizontalWrap; + const int a = s.anisotropylevel; + return (((f & 7) << 24) | ((m & 7) << 16) | ((w & 7) << 8) | (a & 7)) ^ seed; +} + +QSGSamplerDescription QSGSamplerDescription::fromTexture(QSGTexture *t) +{ + QSGSamplerDescription s; + s.filtering = t->filtering(); + s.mipmapFiltering = t->mipmapFiltering(); + s.horizontalWrap = t->horizontalWrapMode(); + s.verticalWrap = t->verticalWrapMode(); + s.anisotropylevel = t->anisotropyLevel(); + return s; +} + +static int qt_sg_envInt(const char *name, int defaultValue) +{ + if (Q_LIKELY(!qEnvironmentVariableIsSet(name))) + return defaultValue; + bool ok = false; + const int value = qEnvironmentVariableIntValue(name, &ok); + return ok ? value : defaultValue; +} + +namespace WSGBatchRenderer +{ + +#define DECLARE_DEBUG_VAR(variable) \ + static bool debug_ ## variable() \ + { static bool value = qgetenv("QSG_RENDERER_DEBUG").contains(QT_STRINGIFY(variable)); return value; } +DECLARE_DEBUG_VAR(render) +DECLARE_DEBUG_VAR(build) +DECLARE_DEBUG_VAR(change) +DECLARE_DEBUG_VAR(upload) +DECLARE_DEBUG_VAR(roots) +DECLARE_DEBUG_VAR(dump) +DECLARE_DEBUG_VAR(pools) +DECLARE_DEBUG_VAR(noalpha) +DECLARE_DEBUG_VAR(noopaque) +DECLARE_DEBUG_VAR(noclip) +#undef DECLARE_DEBUG_VAR + +#define QSGNODE_TRAVERSE(NODE) for (QSGNode *child = NODE->firstChild(); child; child = child->nextSibling()) +#define SHADOWNODE_TRAVERSE(NODE) for (Node *child = NODE->firstChild(); child; child = child->sibling()) + +static inline int size_of_type(int type) +{ + static int sizes[] = { + sizeof(char), + sizeof(unsigned char), + sizeof(short), + sizeof(unsigned short), + sizeof(int), + sizeof(unsigned int), + sizeof(float), + 2, + 3, + 4, + sizeof(double) + }; + Q_ASSERT(type >= QSGGeometry::ByteType && type <= QSGGeometry::DoubleType); + return sizes[type - QSGGeometry::ByteType]; +} + +bool qsg_sort_element_increasing_order(Element *a, Element *b) { return a->order < b->order; } +bool qsg_sort_element_decreasing_order(Element *a, Element *b) { return a->order > b->order; } +bool qsg_sort_batch_increasing_order(Batch *a, Batch *b) { return a->first->order < b->first->order; } +bool qsg_sort_batch_decreasing_order(Batch *a, Batch *b) { return a->first->order > b->first->order; } + +QSGMaterial::Flag QSGMaterial_FullMatrix = (QSGMaterial::Flag) (QSGMaterial::RequiresFullMatrix & ~QSGMaterial::RequiresFullMatrixExceptTranslate); + +static bool isTranslate(const QMatrix4x4 &m) { return m.flags() <= QMatrix4x4::Translation; } +static bool isScale(const QMatrix4x4 &m) { return m.flags() <= QMatrix4x4::Scale; } +static bool is2DSafe(const QMatrix4x4 &m) { return m.flags() < QMatrix4x4::Rotation; } + +const float OPAQUE_LIMIT = 0.999f; + +const uint DYNAMIC_VERTEX_INDEX_BUFFER_THRESHOLD = 4; +const int VERTEX_BUFFER_BINDING = 0; +const int ZORDER_BUFFER_BINDING = VERTEX_BUFFER_BINDING + 1; + +const float VIEWPORT_MIN_DEPTH = 0.0f; +const float VIEWPORT_MAX_DEPTH = 1.0f; + +const quint32 DEFAULT_BUFFER_POOL_SIZE_LIMIT = 2 * 1024 * 1024; // 2 MB for m_vboPool and m_iboPool each + +template +inline Int aligned(Int v, Int byteAlign) +{ + return (v + byteAlign - 1) & ~(byteAlign - 1); +} + +QRhiVertexInputAttribute::Format qsg_vertexInputFormat(const QSGGeometry::Attribute &a) +{ + switch (a.type) { + case QSGGeometry::FloatType: + if (a.tupleSize == 4) + return QRhiVertexInputAttribute::Float4; + if (a.tupleSize == 3) + return QRhiVertexInputAttribute::Float3; + if (a.tupleSize == 2) + return QRhiVertexInputAttribute::Float2; + if (a.tupleSize == 1) + return QRhiVertexInputAttribute::Float; + break; + case QSGGeometry::UnsignedByteType: + if (a.tupleSize == 4) + return QRhiVertexInputAttribute::UNormByte4; + if (a.tupleSize == 2) + return QRhiVertexInputAttribute::UNormByte2; + if (a.tupleSize == 1) + return QRhiVertexInputAttribute::UNormByte; + break; + default: + break; + } + qWarning("Unsupported attribute type 0x%x with %d components", a.type, a.tupleSize); + Q_UNREACHABLE_RETURN(QRhiVertexInputAttribute::Float); +} + +static QRhiVertexInputLayout calculateVertexInputLayout(const QSGMaterialShader *s, const QSGGeometry *geometry, bool batchable) +{ + Q_ASSERT(geometry); + const QSGMaterialShaderPrivate *sd = QSGMaterialShaderPrivate::get(s); + if (!sd->vertexShader) { + qWarning("No vertex shader in QSGMaterialShader %p", s); + return QRhiVertexInputLayout(); + } + + const int attrCount = geometry->attributeCount(); + QVarLengthArray inputAttributes; + inputAttributes.reserve(attrCount + 1); + quint32 offset = 0; + for (int i = 0; i < attrCount; ++i) { + const QSGGeometry::Attribute &a = geometry->attributes()[i]; + if (!sd->vertexShader->vertexInputLocations.contains(a.position)) { + qWarning("Vertex input %d is present in material but not in shader. This is wrong.", + a.position); + } + inputAttributes.append(QRhiVertexInputAttribute(VERTEX_BUFFER_BINDING, a.position, qsg_vertexInputFormat(a), offset)); + offset += a.tupleSize * size_of_type(a.type); + } + if (batchable) { + inputAttributes.append(QRhiVertexInputAttribute(ZORDER_BUFFER_BINDING, sd->vertexShader->qt_order_attrib_location, + QRhiVertexInputAttribute::Float, 0)); + } + + Q_ASSERT(VERTEX_BUFFER_BINDING == 0 && ZORDER_BUFFER_BINDING == 1); // not very flexible + QVarLengthArray inputBindings; + inputBindings.append(QRhiVertexInputBinding(geometry->sizeOfVertex())); + if (batchable) + inputBindings.append(QRhiVertexInputBinding(sizeof(float))); + + QRhiVertexInputLayout inputLayout; + inputLayout.setBindings(inputBindings.cbegin(), inputBindings.cend()); + inputLayout.setAttributes(inputAttributes.cbegin(), inputAttributes.cend()); + + return inputLayout; +} + +QRhiCommandBuffer::IndexFormat qsg_indexFormat(const QSGGeometry *geometry) +{ + switch (geometry->indexType()) { + case QSGGeometry::UnsignedShortType: + return QRhiCommandBuffer::IndexUInt16; + break; + case QSGGeometry::UnsignedIntType: + return QRhiCommandBuffer::IndexUInt32; + break; + default: + Q_UNREACHABLE_RETURN(QRhiCommandBuffer::IndexUInt16); + } +} + +QRhiGraphicsPipeline::Topology qsg_topology(int geomDrawMode, QRhi *rhi) +{ + QRhiGraphicsPipeline::Topology topology = QRhiGraphicsPipeline::Triangles; + switch (geomDrawMode) { + case QSGGeometry::DrawPoints: + topology = QRhiGraphicsPipeline::Points; + break; + case QSGGeometry::DrawLines: + topology = QRhiGraphicsPipeline::Lines; + break; + case QSGGeometry::DrawLineStrip: + topology = QRhiGraphicsPipeline::LineStrip; + break; + case QSGGeometry::DrawTriangles: + topology = QRhiGraphicsPipeline::Triangles; + break; + case QSGGeometry::DrawTriangleStrip: + topology = QRhiGraphicsPipeline::TriangleStrip; + break; + case QSGGeometry::DrawTriangleFan: + { + static bool triangleFanSupported = false; + static bool triangleFanSupportChecked = false; + if (!triangleFanSupportChecked) { + triangleFanSupportChecked = true; + triangleFanSupported = rhi->isFeatureSupported(QRhi::TriangleFanTopology); + } + if (triangleFanSupported) { + topology = QRhiGraphicsPipeline::TriangleFan; + break; + } + Q_FALLTHROUGH(); + } + default: + qWarning("Primitive topology 0x%x not supported", geomDrawMode); + break; + } + return topology; +} + +void qsg_setMultiViewFlagsOnMaterial(QSGMaterial *material, int multiViewCount) +{ + material->setFlag(QSGMaterial::MultiView2, multiViewCount == 2); + material->setFlag(QSGMaterial::MultiView3, multiViewCount == 3); + material->setFlag(QSGMaterial::MultiView4, multiViewCount == 4); +} + +ShaderManager::Shader *ShaderManager::prepareMaterial(QSGMaterial *material, + const QSGGeometry *geometry, + QSGRendererInterface::RenderMode renderMode, + int multiViewCount) +{ + qsg_setMultiViewFlagsOnMaterial(material, multiViewCount); + + QSGMaterialType *type = material->type(); + ShaderKey key = { type, renderMode, multiViewCount }; + Shader *shader = rewrittenShaders.value(key, nullptr); + if (shader) + return shader; + + shader = new Shader; + QSGMaterialShader *s = static_cast(material->createShader(renderMode)); + context->initializeRhiShader(s, QShader::BatchableVertexShader); + shader->materialShader = s; + shader->inputLayout = calculateVertexInputLayout(s, geometry, true); + QSGMaterialShaderPrivate *sD = QSGMaterialShaderPrivate::get(s); + shader->stages = { + { QRhiShaderStage::Vertex, sD->shader(QShader::VertexStage), QShader::BatchableVertexShader }, + { QRhiShaderStage::Fragment, sD->shader(QShader::FragmentStage) } + }; + + shader->lastOpacity = 0; + + rewrittenShaders[key] = shader; + return shader; +} + +ShaderManager::Shader *ShaderManager::prepareMaterialNoRewrite(QSGMaterial *material, + const QSGGeometry *geometry, + QSGRendererInterface::RenderMode renderMode, + int multiViewCount) +{ + qsg_setMultiViewFlagsOnMaterial(material, multiViewCount); + + QSGMaterialType *type = material->type(); + ShaderKey key = { type, renderMode, multiViewCount }; + Shader *shader = stockShaders.value(key, nullptr); + if (shader) + return shader; + + shader = new Shader; + QSGMaterialShader *s = static_cast(material->createShader(renderMode)); + context->initializeRhiShader(s, QShader::StandardShader); + shader->materialShader = s; + shader->inputLayout = calculateVertexInputLayout(s, geometry, false); + QSGMaterialShaderPrivate *sD = QSGMaterialShaderPrivate::get(s); + shader->stages = { + { QRhiShaderStage::Vertex, sD->shader(QShader::VertexStage) }, + { QRhiShaderStage::Fragment, sD->shader(QShader::FragmentStage) } + }; + + shader->lastOpacity = 0; + + stockShaders[key] = shader; + + return shader; +} + +void ShaderManager::invalidated() +{ + qDeleteAll(stockShaders); + stockShaders.clear(); + qDeleteAll(rewrittenShaders); + rewrittenShaders.clear(); + + qDeleteAll(pipelineCache); + pipelineCache.clear(); + + qDeleteAll(srbPool); + srbPool.clear(); +} + +void ShaderManager::clearCachedRendererData() +{ + for (ShaderManager::Shader *sms : std::as_const(stockShaders)) { + QSGMaterialShader *s = sms->materialShader; + if (s) { + QSGMaterialShaderPrivate *sd = QSGMaterialShaderPrivate::get(s); + sd->clearCachedRendererData(); + } + } + for (ShaderManager::Shader *sms : std::as_const(rewrittenShaders)) { + QSGMaterialShader *s = sms->materialShader; + if (s) { + QSGMaterialShaderPrivate *sd = QSGMaterialShaderPrivate::get(s); + sd->clearCachedRendererData(); + } + } +} + +void qsg_dumpShadowRoots(BatchRootInfo *i, int indent) +{ + static int extraIndent = 0; + ++extraIndent; + + QByteArray ind(indent + extraIndent + 10, ' '); + + if (!i) { + qDebug("%s - no info", ind.constData()); + } else { + qDebug() << ind.constData() << "- parent:" << i->parentRoot << "orders" << i->firstOrder << "->" << i->lastOrder << ", avail:" << i->availableOrders; + for (QSet::const_iterator it = i->subRoots.constBegin(); + it != i->subRoots.constEnd(); ++it) { + qDebug() << ind.constData() << "-" << *it; + qsg_dumpShadowRoots((*it)->rootInfo(), indent); + } + } + + --extraIndent; +} + +void qsg_dumpShadowRoots(Node *n) +{ +#ifndef QT_NO_DEBUG_OUTPUT + static int indent = 0; + ++indent; + + QByteArray ind(indent, ' '); + + if (n->type() == QSGNode::ClipNodeType || n->isBatchRoot) { + qDebug() << ind.constData() << "[X]" << n->sgNode << Qt::hex << uint(n->sgNode->flags()); + qsg_dumpShadowRoots(n->rootInfo(), indent); + } else { + QDebug d = qDebug(); + d << ind.constData() << "[ ]" << n->sgNode << Qt::hex << uint(n->sgNode->flags()); + if (n->type() == QSGNode::GeometryNodeType) + d << "order" << Qt::dec << n->element()->order; + } + + SHADOWNODE_TRAVERSE(n) + qsg_dumpShadowRoots(child); + + --indent; +#else + Q_UNUSED(n); +#endif +} + +Updater::Updater(Renderer *r) + : renderer(r) + , m_roots(32) + , m_rootMatrices(8) +{ + m_roots.add(0); + m_combined_matrix_stack.add(&m_identityMatrix); + m_rootMatrices.add(m_identityMatrix); +} + +void Updater::updateStates(QSGNode *n) +{ + m_current_clip = nullptr; + + m_added = 0; + m_transformChange = 0; + m_opacityChange = 0; + + Node *sn = renderer->m_nodes.value(n, 0); + Q_ASSERT(sn); + + if (Q_UNLIKELY(debug_roots())) + qsg_dumpShadowRoots(sn); + + if (Q_UNLIKELY(debug_build())) { + qDebug("Updater::updateStates()"); + if (sn->dirtyState & (QSGNode::DirtyNodeAdded << 16)) + qDebug(" - nodes have been added"); + if (sn->dirtyState & (QSGNode::DirtyMatrix << 16)) + qDebug(" - transforms have changed"); + if (sn->dirtyState & (QSGNode::DirtyOpacity << 16)) + qDebug(" - opacity has changed"); + if (uint(sn->dirtyState) & uint(QSGNode::DirtyForceUpdate << 16)) + qDebug(" - forceupdate"); + } + + if (Q_UNLIKELY(renderer->m_visualizer->mode() == Visualizer::VisualizeChanges)) + renderer->m_visualizer->visualizeChangesPrepare(sn); + + visitNode(sn); +} + +void Updater::visitNode(Node *n) +{ + if (m_added == 0 && n->dirtyState == 0 && m_force_update == 0 && m_transformChange == 0 && m_opacityChange == 0) + return; + + int count = m_added; + if (n->dirtyState & QSGNode::DirtyNodeAdded) + ++m_added; + + int force = m_force_update; + if (n->dirtyState & QSGNode::DirtyForceUpdate) + ++m_force_update; + + switch (n->type()) { + case QSGNode::OpacityNodeType: + visitOpacityNode(n); + break; + case QSGNode::TransformNodeType: + visitTransformNode(n); + break; + case QSGNode::GeometryNodeType: + visitGeometryNode(n); + break; + case QSGNode::ClipNodeType: + visitClipNode(n); + break; + case QSGNode::RenderNodeType: + if (m_added) + n->renderNodeElement()->root = m_roots.last(); + Q_FALLTHROUGH(); // to visit children + default: + SHADOWNODE_TRAVERSE(n) visitNode(child); + break; + } + + m_added = count; + m_force_update = force; + n->dirtyState = {}; +} + +void Updater::visitClipNode(Node *n) +{ + ClipBatchRootInfo *extra = n->clipInfo(); + + QSGClipNode *cn = static_cast(n->sgNode); + + if (m_roots.last() && m_added > 0) + renderer->registerBatchRoot(n, m_roots.last()); + + cn->setRendererClipList(m_current_clip); + m_current_clip = cn; + m_roots << n; + m_rootMatrices.add(m_rootMatrices.last() * *m_combined_matrix_stack.last()); + extra->matrix = m_rootMatrices.last(); + cn->setRendererMatrix(&extra->matrix); + m_combined_matrix_stack << &m_identityMatrix; + + SHADOWNODE_TRAVERSE(n) visitNode(child); + + m_current_clip = cn->clipList(); + m_rootMatrices.pop_back(); + m_combined_matrix_stack.pop_back(); + m_roots.pop_back(); +} + +void Updater::visitOpacityNode(Node *n) +{ + QSGOpacityNode *on = static_cast(n->sgNode); + + qreal combined = m_opacity_stack.last() * on->opacity(); + on->setCombinedOpacity(combined); + m_opacity_stack.add(combined); + + if (m_added == 0 && n->dirtyState & QSGNode::DirtyOpacity) { + bool was = n->isOpaque; + bool is = on->opacity() > OPAQUE_LIMIT; + if (was != is) { + renderer->m_rebuild = Renderer::FullRebuild; + n->isOpaque = is; + } + ++m_opacityChange; + SHADOWNODE_TRAVERSE(n) visitNode(child); + --m_opacityChange; + } else { + if (m_added > 0) + n->isOpaque = on->opacity() > OPAQUE_LIMIT; + SHADOWNODE_TRAVERSE(n) visitNode(child); + } + + m_opacity_stack.pop_back(); +} + +void Updater::visitTransformNode(Node *n) +{ + bool popMatrixStack = false; + bool popRootStack = false; + bool dirty = n->dirtyState & QSGNode::DirtyMatrix; + + QSGTransformNode *tn = static_cast(n->sgNode); + + if (n->isBatchRoot) { + if (m_added > 0 && m_roots.last()) + renderer->registerBatchRoot(n, m_roots.last()); + tn->setCombinedMatrix(m_rootMatrices.last() * *m_combined_matrix_stack.last() * tn->matrix()); + + // The only change in this subtree is ourselves and we are a batch root, so + // only update subroots and return, saving tons of child-processing (flickable-panning) + + if (!n->becameBatchRoot && m_added == 0 && m_force_update == 0 && m_opacityChange == 0 && dirty && (n->dirtyState & ~QSGNode::DirtyMatrix) == 0) { + BatchRootInfo *info = renderer->batchRootInfo(n); + for (QSet::const_iterator it = info->subRoots.constBegin(); + it != info->subRoots.constEnd(); ++it) { + updateRootTransforms(*it, n, tn->combinedMatrix()); + } + return; + } + + n->becameBatchRoot = false; + + m_combined_matrix_stack.add(&m_identityMatrix); + m_roots.add(n); + m_rootMatrices.add(tn->combinedMatrix()); + + popMatrixStack = true; + popRootStack = true; + } else if (!tn->matrix().isIdentity()) { + tn->setCombinedMatrix(*m_combined_matrix_stack.last() * tn->matrix()); + m_combined_matrix_stack.add(&tn->combinedMatrix()); + popMatrixStack = true; + } else { + tn->setCombinedMatrix(*m_combined_matrix_stack.last()); + } + + if (dirty) + ++m_transformChange; + + SHADOWNODE_TRAVERSE(n) visitNode(child); + + if (dirty) + --m_transformChange; + if (popMatrixStack) + m_combined_matrix_stack.pop_back(); + if (popRootStack) { + m_roots.pop_back(); + m_rootMatrices.pop_back(); + } +} + +void Updater::visitGeometryNode(Node *n) +{ + QSGGeometryNode *gn = static_cast(n->sgNode); + + gn->setRendererMatrix(m_combined_matrix_stack.last()); + gn->setRendererClipList(m_current_clip); + gn->setInheritedOpacity(m_opacity_stack.last()); + + if (m_added) { + Element *e = n->element(); + e->root = m_roots.last(); + e->translateOnlyToRoot = isTranslate(*gn->matrix()); + + if (e->root) { + BatchRootInfo *info = renderer->batchRootInfo(e->root); + while (info != nullptr) { + info->availableOrders--; + if (info->availableOrders < 0) { + renderer->m_rebuild |= Renderer::BuildRenderLists; + } else { + renderer->m_rebuild |= Renderer::BuildRenderListsForTaggedRoots; + renderer->m_taggedRoots << e->root; + } + if (info->parentRoot != nullptr) + info = renderer->batchRootInfo(info->parentRoot); + else + info = nullptr; + } + } else { + renderer->m_rebuild |= Renderer::FullRebuild; + } + } else { + if (m_transformChange) { + Element *e = n->element(); + e->translateOnlyToRoot = isTranslate(*gn->matrix()); + } + if (m_opacityChange) { + Element *e = n->element(); + if (e->batch) + renderer->invalidateBatchAndOverlappingRenderOrders(e->batch); + } + } + + SHADOWNODE_TRAVERSE(n) visitNode(child); +} + +void Updater::updateRootTransforms(Node *node, Node *root, const QMatrix4x4 &combined) +{ + BatchRootInfo *info = renderer->batchRootInfo(node); + QMatrix4x4 m; + Node *n = node; + + while (n != root) { + if (n->type() == QSGNode::TransformNodeType) + m = static_cast(n->sgNode)->matrix() * m; + n = n->parent(); + } + + m = combined * m; + + if (node->type() == QSGNode::ClipNodeType) { + static_cast(info)->matrix = m; + } else { + Q_ASSERT(node->type() == QSGNode::TransformNodeType); + static_cast(node->sgNode)->setCombinedMatrix(m); + } + + for (QSet::const_iterator it = info->subRoots.constBegin(); + it != info->subRoots.constEnd(); ++it) { + updateRootTransforms(*it, node, m); + } +} + +int qsg_positionAttribute(QSGGeometry *g) +{ + int vaOffset = 0; + for (int a=0; aattributeCount(); ++a) { + const QSGGeometry::Attribute &attr = g->attributes()[a]; + if (attr.isVertexCoordinate && attr.tupleSize == 2 && attr.type == QSGGeometry::FloatType) { + return vaOffset; + } + vaOffset += attr.tupleSize * size_of_type(attr.type); + } + return -1; +} + + +void Rect::map(const QMatrix4x4 &matrix) +{ + const float *m = matrix.constData(); + if (isScale(matrix)) { + tl.x = tl.x * m[0] + m[12]; + tl.y = tl.y * m[5] + m[13]; + br.x = br.x * m[0] + m[12]; + br.y = br.y * m[5] + m[13]; + if (tl.x > br.x) + qSwap(tl.x, br.x); + if (tl.y > br.y) + qSwap(tl.y, br.y); + } else { + Pt mtl = tl; + Pt mtr = { br.x, tl.y }; + Pt mbl = { tl.x, br.y }; + Pt mbr = br; + + mtl.map(matrix); + mtr.map(matrix); + mbl.map(matrix); + mbr.map(matrix); + + set(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); + (*this) |= mtl; + (*this) |= mtr; + (*this) |= mbl; + (*this) |= mbr; + } +} + +void Element::computeBounds() +{ + Q_ASSERT(!boundsComputed); + boundsComputed = true; + + QSGGeometry *g = node->geometry(); + int offset = qsg_positionAttribute(g); + if (offset == -1) { + // No position attribute means overlaps with everything.. + bounds.set(-FLT_MAX, -FLT_MAX, FLT_MAX, FLT_MAX); + return; + } + + bounds.set(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); + char *vd = (char *) g->vertexData() + offset; + for (int i=0; ivertexCount(); ++i) { + bounds |= *(Pt *) vd; + vd += g->sizeOfVertex(); + } + bounds.map(*node->matrix()); + + if (!qt_is_finite(bounds.tl.x) || bounds.tl.x == FLT_MAX) + bounds.tl.x = -FLT_MAX; + if (!qt_is_finite(bounds.tl.y) || bounds.tl.y == FLT_MAX) + bounds.tl.y = -FLT_MAX; + if (!qt_is_finite(bounds.br.x) || bounds.br.x == -FLT_MAX) + bounds.br.x = FLT_MAX; + if (!qt_is_finite(bounds.br.y) || bounds.br.y == -FLT_MAX) + bounds.br.y = FLT_MAX; + + Q_ASSERT(bounds.tl.x <= bounds.br.x); + Q_ASSERT(bounds.tl.y <= bounds.br.y); + + boundsOutsideFloatRange = bounds.isOutsideFloatRange(); +} + +BatchCompatibility Batch::isMaterialCompatible(Element *e) const +{ + Element *n = first; + // Skip to the first node other than e which has not been removed + while (n && (n == e || n->removed)) + n = n->nextInBatch; + + // Only 'e' in this batch, so a material change doesn't change anything as long as + // its blending is still in sync with this batch... + if (!n) + return BatchIsCompatible; + + QSGMaterial *m = e->node->activeMaterial(); + QSGMaterial *nm = n->node->activeMaterial(); + return (nm->type() == m->type() && nm->viewCount() == m->viewCount() && nm->compare(m) == 0) + ? BatchIsCompatible + : BatchBreaksOnCompare; +} + +/* + * Marks this batch as dirty or in the case where the geometry node has + * changed to be incompatible with this batch, return false so that + * the caller can mark the entire sg for a full rebuild... + */ +bool Batch::geometryWasChanged(QSGGeometryNode *gn) +{ + Element *e = first; + Q_ASSERT_X(e, "Batch::geometryWasChanged", "Batch is expected to 'valid' at this time"); + // 'gn' is the first node in the batch, compare against the next one. + while (e && (e->node == gn || e->removed)) + e = e->nextInBatch; + if (!e || e->node->geometry()->attributes() == gn->geometry()->attributes()) { + needsUpload = true; + return true; + } else { + return false; + } +} + +void Batch::cleanupRemovedElements() +{ + if (!needsPurge) + return; + + // remove from front of batch.. + while (first && first->removed) { + first = first->nextInBatch; + } + + // Then continue and remove other nodes further out in the batch.. + if (first) { + Element *e = first; + while (e->nextInBatch) { + if (e->nextInBatch->removed) + e->nextInBatch = e->nextInBatch->nextInBatch; + else + e = e->nextInBatch; + + } + } + + needsPurge = false; +} + +/* + * Iterates through all geometry nodes in this batch and unsets their batch, + * thus forcing them to be rebuilt + */ +void Batch::invalidate() +{ + cleanupRemovedElements(); + Element *e = first; + first = nullptr; + root = nullptr; + while (e) { + e->batch = nullptr; + Element *n = e->nextInBatch; + e->nextInBatch = nullptr; + e = n; + } +} + +bool Batch::isTranslateOnlyToRoot() const { + bool only = true; + Element *e = first; + while (e && only) { + only &= e->translateOnlyToRoot; + e = e->nextInBatch; + } + return only; +} + +/* + * Iterates through all the nodes in the batch and returns true if the + * nodes are all safe to batch. There are two separate criteria: + * + * - The matrix is such that the z component of the result is of no + * consequence. + * + * - The bounds are inside the stable floating point range. This applies + * to desktop only where we in this case can trigger a fallback to + * unmerged in which case we pass the geometry straight through and + * just apply the matrix. + * + * NOTE: This also means a slight performance impact for geometries which + * are defined to be outside the stable floating point range and still + * use single precision float, but given that this implicitly fixes + * huge lists and tables, it is worth it. + */ +bool Batch::isSafeToBatch() const { + Element *e = first; + while (e) { + if (e->boundsOutsideFloatRange) + return false; + if (!is2DSafe(*e->node->matrix())) + return false; + e = e->nextInBatch; + } + return true; +} + +static int qsg_countNodesInBatch(const Batch *batch) +{ + int sum = 0; + Element *e = batch->first; + while (e) { + ++sum; + e = e->nextInBatch; + } + return sum; +} + +static int qsg_countNodesInBatches(const QDataBuffer &batches) +{ + int sum = 0; + for (int i=0; irhi(); + Q_ASSERT(m_rhi); // no more direct OpenGL code path in Qt 6 + + m_ubufAlignment = m_rhi->ubufAlignment(); + + m_uint32IndexForRhi = !m_rhi->isFeatureSupported(QRhi::NonFourAlignedEffectiveIndexBufferOffset); + if (qEnvironmentVariableIntValue("QSG_RHI_UINT32_INDEX")) + m_uint32IndexForRhi = true; + + bool ok = false; + int padding = qEnvironmentVariableIntValue("QSG_BATCHRENDERER_MINIMUM_ORDER_PADDING", &ok); + if (ok) + m_minimumOrderPadding = padding; + + m_visualizer = new RhiVisualizer(this); + + setNodeUpdater(new Updater(this)); + + // The shader manager is shared between renderers (think for example Item + // layers that create a new Renderer each) with the same rendercontext (and + // so same QRhi). + m_shaderManager = ctx->findChild(QString(), Qt::FindDirectChildrenOnly); + if (!m_shaderManager) { + m_shaderManager = new ShaderManager(ctx); + m_shaderManager->setObjectName(QStringLiteral("__qt_ShaderManager")); + m_shaderManager->setParent(ctx); + QObject::connect(ctx, SIGNAL(invalidated()), m_shaderManager, SLOT(invalidated()), Qt::DirectConnection); + } + + m_batchNodeThreshold = qt_sg_envInt("QSG_RENDERER_BATCH_NODE_THRESHOLD", 64); + m_batchVertexThreshold = qt_sg_envInt("QSG_RENDERER_BATCH_VERTEX_THRESHOLD", 1024); + m_srbPoolThreshold = qt_sg_envInt("QSG_RENDERER_SRB_POOL_THRESHOLD", 1024); + m_bufferPoolSizeLimit = qt_sg_envInt("QSG_RENDERER_BUFFER_POOL_LIMIT", DEFAULT_BUFFER_POOL_SIZE_LIMIT); + + if (Q_UNLIKELY(debug_build() || debug_render() || debug_pools())) { + qDebug("Batch thresholds: nodes: %d vertices: %d srb pool: %d buffer pool: %d", + m_batchNodeThreshold, m_batchVertexThreshold, m_srbPoolThreshold, m_bufferPoolSizeLimit); + } +} + +static void qsg_wipeBuffer(Buffer *buffer) +{ + delete buffer->buf; + + // The free here is ok because we're in one of two situations. + // 1. We're using the upload pool in which case unmap will have set the + // data pointer to 0 and calling free on 0 is ok. + // 2. We're using dedicated buffers because of visualization or IBO workaround + // and the data something we malloced and must be freed. + free(buffer->data); +} + +static void qsg_wipeBatch(Batch *batch) +{ + qsg_wipeBuffer(&batch->vbo); + qsg_wipeBuffer(&batch->ibo); + delete batch->ubuf; + batch->stencilClipState.reset(); + delete batch; +} + +Renderer::~Renderer() +{ + if (m_rhi) { + // Clean up batches and buffers + for (int i = 0; i < m_opaqueBatches.size(); ++i) + qsg_wipeBatch(m_opaqueBatches.at(i)); + for (int i = 0; i < m_alphaBatches.size(); ++i) + qsg_wipeBatch(m_alphaBatches.at(i)); + for (int i = 0; i < m_batchPool.size(); ++i) + qsg_wipeBatch(m_batchPool.at(i)); + for (int i = 0; i < m_vboPool.size(); ++i) + delete m_vboPool.at(i); + for (int i = 0; i < m_iboPool.size(); ++i) + delete m_iboPool.at(i); + } + + for (Node *n : std::as_const(m_nodes)) { + if (n->type() == QSGNode::GeometryNodeType) { + Element *e = n->element(); + if (!e->removed) + m_elementsToDelete.add(e); + } else if (n->type() == QSGNode::ClipNodeType) { + delete n->clipInfo(); + } else if (n->type() == QSGNode::RenderNodeType) { + RenderNodeElement *e = n->renderNodeElement(); + if (!e->removed) + m_elementsToDelete.add(e); + } + + m_nodeAllocator.release(n); + } + + // Remaining elements... + for (int i=0; i the cached data + // in the rhi shaders have to be purged as it may refer to samplers we + // are going to destroy. + m_shaderManager->clearCachedRendererData(); + + qDeleteAll(m_samplers); + m_stencilClipCommon.reset(); + delete m_dummyTexture; + m_visualizer->releaseResources(); +} + +void Renderer::releaseCachedResources() +{ + m_shaderManager->invalidated(); + + destroyGraphicsResources(); + + m_samplers.clear(); + m_dummyTexture = nullptr; + + m_rhi->releaseCachedResources(); + + m_vertexUploadPool.shrink(0); + m_vertexUploadPool.reset(); + m_indexUploadPool.shrink(0); + m_indexUploadPool.reset(); + + for (int i = 0; i < m_vboPool.size(); ++i) + delete m_vboPool.at(i); + m_vboPool.reset(); + m_vboPoolCost = 0; + + for (int i = 0; i < m_iboPool.size(); ++i) + delete m_iboPool.at(i); + m_iboPool.reset(); + m_iboPoolCost = 0; +} + +void Renderer::invalidateAndRecycleBatch(Batch *b) +{ + if (b->vbo.buf != nullptr && m_vboPoolCost + b->vbo.buf->size() <= quint32(m_bufferPoolSizeLimit)) { + m_vboPool.add(b->vbo.buf); + m_vboPoolCost += b->vbo.buf->size(); + } else { + delete b->vbo.buf; + } + if (b->ibo.buf != nullptr && m_iboPoolCost + b->ibo.buf->size() <= quint32(m_bufferPoolSizeLimit)) { + m_iboPool.add(b->ibo.buf); + m_iboPoolCost += b->ibo.buf->size(); + } else { + delete b->ibo.buf; + } + b->vbo.buf = nullptr; + b->ibo.buf = nullptr; + b->invalidate(); + for (int i=0; imode() == Visualizer::VisualizeNothing) { + // Common case, use a shared memory pool for uploading vertex data to avoid + // excessive reevaluation + QDataBuffer &pool = isIndexBuf ? m_indexUploadPool : m_vertexUploadPool; + if (byteSize > quint32(pool.size())) + pool.resize(byteSize); + buffer->data = pool.data(); + } else if (buffer->size != byteSize) { + free(buffer->data); + buffer->data = (char *) malloc(byteSize); + Q_CHECK_PTR(buffer->data); + } + buffer->size = byteSize; +} + +void Renderer::unmap(Buffer *buffer, bool isIndexBuf) +{ + // Batches are pooled and reused which means the QRhiBuffer will be + // still valid in a recycled Batch. We only hit the newBuffer() path + // when there are no buffers to recycle. + QDataBuffer *bufferPool = isIndexBuf ? &m_iboPool : &m_vboPool; + if (!buffer->buf && bufferPool->isEmpty()) { + buffer->buf = m_rhi->newBuffer(QRhiBuffer::Immutable, + isIndexBuf ? QRhiBuffer::IndexBuffer : QRhiBuffer::VertexBuffer, + buffer->size); + if (!buffer->buf->create()) { + qWarning("Failed to build vertex/index buffer of size %u", buffer->size); + delete buffer->buf; + buffer->buf = nullptr; + } + } else { + if (!buffer->buf) { + const quint32 expectedSize = buffer->size; + qsizetype foundBufferIndex = 0; + for (qsizetype i = 0; i < bufferPool->size(); ++i) { + QRhiBuffer *testBuffer = bufferPool->at(i); + if (!buffer->buf + || (testBuffer->size() >= expectedSize && testBuffer->size() < buffer->buf->size()) + || (testBuffer->size() < expectedSize && testBuffer->size() > buffer->buf->size())) { + foundBufferIndex = i; + buffer->buf = testBuffer; + if (buffer->buf->size() == expectedSize) + break; + } + } + + const qsizetype lastBufferIndex = bufferPool->size() - 1; + if (foundBufferIndex < lastBufferIndex) { + qSwap(bufferPool->data()[foundBufferIndex], + bufferPool->data()[lastBufferIndex]); + } + if (isIndexBuf) + m_iboPoolCost -= bufferPool->data()[lastBufferIndex]->size(); + else + m_vboPoolCost -= bufferPool->data()[lastBufferIndex]->size(); + bufferPool->pop_back(); + } + + bool needsRebuild = false; + if (buffer->buf->size() < buffer->size) { + buffer->buf->setSize(buffer->size); + needsRebuild = true; + } + if (buffer->buf->type() != QRhiBuffer::Dynamic + && buffer->nonDynamicChangeCount > DYNAMIC_VERTEX_INDEX_BUFFER_THRESHOLD) + { + buffer->buf->setType(QRhiBuffer::Dynamic); + buffer->nonDynamicChangeCount = 0; + needsRebuild = true; + } + if (needsRebuild) { + if (!buffer->buf->create()) { + qWarning("Failed to (re)build vertex/index buffer of size %u", buffer->size); + delete buffer->buf; + buffer->buf = nullptr; + } + } + } + if (buffer->buf) { + if (buffer->buf->type() != QRhiBuffer::Dynamic) { + m_resourceUpdates->uploadStaticBuffer(buffer->buf, 0, buffer->size, buffer->data); + buffer->nonDynamicChangeCount += 1; + } else { + if (m_rhi->resourceLimit(QRhi::FramesInFlight) == 1) { +#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 1) + buffer->buf->fullDynamicBufferUpdateForCurrentFrame(buffer->data, buffer->size); +#else + buffer->buf->fullDynamicBufferUpdateForCurrentFrame(buffer->data); +#endif + } else { + m_resourceUpdates->updateDynamicBuffer(buffer->buf, 0, buffer->size, buffer->data); + } + } + } + if (m_visualizer->mode() == Visualizer::VisualizeNothing) + buffer->data = nullptr; +} + +BatchRootInfo *Renderer::batchRootInfo(Node *node) +{ + BatchRootInfo *info = node->rootInfo(); + if (!info) { + if (node->type() == QSGNode::ClipNodeType) + info = new ClipBatchRootInfo; + else { + Q_ASSERT(node->type() == QSGNode::TransformNodeType); + info = new BatchRootInfo; + } + node->data = info; + } + return info; +} + +void Renderer::removeBatchRootFromParent(Node *childRoot) +{ + BatchRootInfo *childInfo = batchRootInfo(childRoot); + if (!childInfo->parentRoot) + return; + BatchRootInfo *parentInfo = batchRootInfo(childInfo->parentRoot); + + Q_ASSERT(parentInfo->subRoots.contains(childRoot)); + parentInfo->subRoots.remove(childRoot); + childInfo->parentRoot = nullptr; +} + +void Renderer::registerBatchRoot(Node *subRoot, Node *parentRoot) +{ + BatchRootInfo *subInfo = batchRootInfo(subRoot); + BatchRootInfo *parentInfo = batchRootInfo(parentRoot); + subInfo->parentRoot = parentRoot; + parentInfo->subRoots << subRoot; +} + +bool Renderer::changeBatchRoot(Node *node, Node *root) +{ + BatchRootInfo *subInfo = batchRootInfo(node); + if (subInfo->parentRoot == root) + return false; + if (subInfo->parentRoot) { + BatchRootInfo *oldRootInfo = batchRootInfo(subInfo->parentRoot); + oldRootInfo->subRoots.remove(node); + } + BatchRootInfo *newRootInfo = batchRootInfo(root); + newRootInfo->subRoots << node; + subInfo->parentRoot = root; + return true; +} + +void Renderer::nodeChangedBatchRoot(Node *node, Node *root) +{ + if (node->type() == QSGNode::ClipNodeType || node->isBatchRoot) { + // When we reach a batchroot, we only need to update it. Its subtree + // is relative to that root, so no need to recurse further. + changeBatchRoot(node, root); + return; + } else if (node->type() == QSGNode::GeometryNodeType) { + // Only need to change the root as nodeChanged anyway flags a full update. + Element *e = node->element(); + if (e) { + e->root = root; + e->boundsComputed = false; + } + } else if (node->type() == QSGNode::RenderNodeType) { + RenderNodeElement *e = node->renderNodeElement(); + if (e) + e->root = root; + } + + SHADOWNODE_TRAVERSE(node) + nodeChangedBatchRoot(child, root); +} + +void Renderer::nodeWasTransformed(Node *node, int *vertexCount) +{ + if (node->type() == QSGNode::GeometryNodeType) { + QSGGeometryNode *gn = static_cast(node->sgNode); + *vertexCount += gn->geometry()->vertexCount(); + Element *e = node->element(); + if (e) { + e->boundsComputed = false; + if (e->batch) { + if (!e->batch->isOpaque) { + invalidateBatchAndOverlappingRenderOrders(e->batch); + } else if (e->batch->merged) { + e->batch->needsUpload = true; + } + } + } + } + + SHADOWNODE_TRAVERSE(node) + nodeWasTransformed(child, vertexCount); +} + +void Renderer::nodeWasAdded(QSGNode *node, Node *shadowParent) +{ + Q_ASSERT(!m_nodes.contains(node)); + if (node->isSubtreeBlocked()) + return; + + Node *snode = m_nodeAllocator.allocate(); + snode->sgNode = node; + m_nodes.insert(node, snode); + if (shadowParent) + shadowParent->append(snode); + + if (node->type() == QSGNode::GeometryNodeType) { + snode->data = m_elementAllocator.allocate(); + snode->element()->setNode(static_cast(node)); + + } else if (node->type() == QSGNode::ClipNodeType) { + snode->data = new ClipBatchRootInfo; + m_rebuild |= FullRebuild; + + } else if (node->type() == QSGNode::RenderNodeType) { + QSGRenderNode *rn = static_cast(node); + RenderNodeElement *e = new RenderNodeElement(rn); + snode->data = e; + Q_ASSERT(!m_renderNodeElements.contains(rn)); + m_renderNodeElements.insert(e->renderNode, e); + if (!rn->flags().testFlag(QSGRenderNode::DepthAwareRendering)) + m_forceNoDepthBuffer = true; + m_rebuild |= FullRebuild; + } + + QSGNODE_TRAVERSE(node) + nodeWasAdded(child, snode); +} + +void Renderer::nodeWasRemoved(Node *node) +{ + // Prefix traversal as removeBatchRootFromParent below removes nodes + // in a bottom-up manner. Note that we *cannot* use SHADOWNODE_TRAVERSE + // here, because we delete 'child' (when recursed, down below), so we'd + // have a use-after-free. + { + Node *child = node->firstChild(); + while (child) { + // Remove (and delete) child + node->remove(child); + nodeWasRemoved(child); + child = node->firstChild(); + } + } + + if (node->type() == QSGNode::GeometryNodeType) { + Element *e = node->element(); + if (e) { + e->removed = true; + m_elementsToDelete.add(e); + e->node = nullptr; + if (e->root) { + BatchRootInfo *info = batchRootInfo(e->root); + info->availableOrders++; + } + if (e->batch) { + e->batch->needsUpload = true; + e->batch->needsPurge = true; + } + + } + + } else if (node->type() == QSGNode::ClipNodeType) { + removeBatchRootFromParent(node); + delete node->clipInfo(); + m_rebuild |= FullRebuild; + m_taggedRoots.remove(node); + + } else if (node->isBatchRoot) { + removeBatchRootFromParent(node); + delete node->rootInfo(); + m_rebuild |= FullRebuild; + m_taggedRoots.remove(node); + + } else if (node->type() == QSGNode::RenderNodeType) { + RenderNodeElement *e = m_renderNodeElements.take(static_cast(node->sgNode)); + if (e) { + e->removed = true; + m_elementsToDelete.add(e); + if (m_renderNodeElements.isEmpty()) { + m_forceNoDepthBuffer = false; + // Must have a full rebuild given useDepthBuffer() now returns + // a different value than before, meaning there can once again + // be an opaque pass. + m_rebuild |= FullRebuild; + } + + if (e->batch != nullptr) + e->batch->needsPurge = true; + } + } + + Q_ASSERT(m_nodes.contains(node->sgNode)); + + m_nodeAllocator.release(m_nodes.take(node->sgNode)); +} + +void Renderer::turnNodeIntoBatchRoot(Node *node) +{ + if (Q_UNLIKELY(debug_change())) qDebug(" - new batch root"); + m_rebuild |= FullRebuild; + node->isBatchRoot = true; + node->becameBatchRoot = true; + + Node *p = node->parent(); + while (p) { + if (p->type() == QSGNode::ClipNodeType || p->isBatchRoot) { + registerBatchRoot(node, p); + break; + } + p = p->parent(); + } + + SHADOWNODE_TRAVERSE(node) + nodeChangedBatchRoot(child, node); +} + + +void Renderer::nodeChanged(QSGNode *node, QSGNode::DirtyState state) +{ +#ifndef QT_NO_DEBUG_OUTPUT + if (Q_UNLIKELY(debug_change())) { + QDebug debug = qDebug(); + debug << "dirty:"; + if (state & QSGNode::DirtyGeometry) + debug << "Geometry"; + if (state & QSGNode::DirtyMaterial) + debug << "Material"; + if (state & QSGNode::DirtyMatrix) + debug << "Matrix"; + if (state & QSGNode::DirtyNodeAdded) + debug << "Added"; + if (state & QSGNode::DirtyNodeRemoved) + debug << "Removed"; + if (state & QSGNode::DirtyOpacity) + debug << "Opacity"; + if (state & QSGNode::DirtySubtreeBlocked) + debug << "SubtreeBlocked"; + if (state & QSGNode::DirtyForceUpdate) + debug << "ForceUpdate"; + + // when removed, some parts of the node could already have been destroyed + // so don't debug it out. + if (state & QSGNode::DirtyNodeRemoved) + debug << (void *) node << node->type(); + else + debug << node; + } +#endif + // As this function calls nodeChanged recursively, we do it at the top + // to avoid that any of the others are processed twice. + if (state & QSGNode::DirtySubtreeBlocked) { + Node *sn = m_nodes.value(node); + + // Force a batch rebuild if this includes an opacity change + if (state & QSGNode::DirtyOpacity) + m_rebuild |= FullRebuild; + + bool blocked = node->isSubtreeBlocked(); + if (blocked && sn) { + nodeChanged(node, QSGNode::DirtyNodeRemoved); + Q_ASSERT(m_nodes.value(node) == 0); + } else if (!blocked && !sn) { + nodeChanged(node, QSGNode::DirtyNodeAdded); + } + return; + } + + if (state & QSGNode::DirtyNodeAdded) { + if (nodeUpdater()->isNodeBlocked(node, rootNode())) { + QSGRenderer::nodeChanged(node, state); + return; + } + if (node == rootNode()) + nodeWasAdded(node, nullptr); + else + nodeWasAdded(node, m_nodes.value(node->parent())); + } + + // Mark this node dirty in the shadow tree. + Node *shadowNode = m_nodes.value(node); + + // Blocked subtrees won't have shadow nodes, so we can safely abort + // here.. + if (!shadowNode) { + QSGRenderer::nodeChanged(node, state); + return; + } + + shadowNode->dirtyState |= state; + + if (state & QSGNode::DirtyMatrix && !shadowNode->isBatchRoot) { + Q_ASSERT(node->type() == QSGNode::TransformNodeType); + if (W_PRIVATE_MEMBER(*node, WSG_QSGNode_m_subtreeRenderableCount{}) > m_batchNodeThreshold) { + turnNodeIntoBatchRoot(shadowNode); + } else { + int vertices = 0; + nodeWasTransformed(shadowNode, &vertices); + if (vertices > m_batchVertexThreshold) { + turnNodeIntoBatchRoot(shadowNode); + } + } + } + + if (state & QSGNode::DirtyGeometry && node->type() == QSGNode::GeometryNodeType) { + QSGGeometryNode *gn = static_cast(node); + Element *e = shadowNode->element(); + if (e) { + const quint8 nodeMutabilityGroup = wsgNodeMutabilityGroup(gn); + if (nodeMutabilityGroup != e->mutabilityGroup) { + m_rebuild |= Renderer::FullRebuild; + e->mutabilityGroup = nodeMutabilityGroup; + } + + e->boundsComputed = false; + Batch *b = e->batch; + if (b) { + if (!e->batch->geometryWasChanged(gn) || !e->batch->isOpaque) { + invalidateBatchAndOverlappingRenderOrders(e->batch); + } else { + b->needsUpload = true; + } + } + } + } + + if (state & QSGNode::DirtyMaterial && node->type() == QSGNode::GeometryNodeType) { + Element *e = shadowNode->element(); + if (e) { + bool blended = hasMaterialWithBlending(static_cast(node)); + if (e->isMaterialBlended != blended) { + m_rebuild |= Renderer::FullRebuild; + e->isMaterialBlended = blended; + } else if (e->batch) { + if (e->batch->isMaterialCompatible(e) == BatchBreaksOnCompare) + invalidateBatchAndOverlappingRenderOrders(e->batch); + } else { + m_rebuild |= Renderer::BuildBatches; + } + } + } + + // Mark the shadow tree dirty all the way back to the root... + QSGNode::DirtyState dirtyChain = state & (QSGNode::DirtyNodeAdded + | QSGNode::DirtyOpacity + | QSGNode::DirtyMatrix + | QSGNode::DirtySubtreeBlocked + | QSGNode::DirtyForceUpdate); + if (dirtyChain != 0) { + dirtyChain = QSGNode::DirtyState(dirtyChain << 16); + Node *sn = shadowNode->parent(); + while (sn) { + sn->dirtyState |= dirtyChain; + sn = sn->parent(); + } + } + + // Delete happens at the very end because it deletes the shadownode. + if (state & QSGNode::DirtyNodeRemoved) { + Node *parent = shadowNode->parent(); + if (parent) + parent->remove(shadowNode); + nodeWasRemoved(shadowNode); + Q_ASSERT(m_nodes.value(node) == 0); + } + + QSGRenderer::nodeChanged(node, state); +} + +/* + * Traverses the tree and builds two list of geometry nodes. One for + * the opaque and one for the translucent. These are populated + * in the order they should visually appear in, meaning first + * to the back and last to the front. + * + * We split opaque and translucent as we can perform different + * types of reordering / batching strategies on them, depending + * + * Note: It would be tempting to use the shadow nodes instead of the QSGNodes + * for traversal to avoid hash lookups, but the order of the children + * is important and they are not preserved in the shadow tree, so we must + * use the actual QSGNode tree. + */ +void Renderer::buildRenderLists(QSGNode *node) +{ + if (node->isSubtreeBlocked()) + return; + + Node *shadowNode = m_nodes.value(node); + Q_ASSERT(shadowNode); + + if (node->type() == QSGNode::GeometryNodeType) { + QSGGeometryNode *gn = static_cast(node); + + Element *e = shadowNode->element(); + Q_ASSERT(e); + + bool opaque = gn->inheritedOpacity() > OPAQUE_LIMIT && !(gn->activeMaterial()->flags() & QSGMaterial::Blending); + if (opaque && useDepthBuffer()) + m_opaqueRenderList << e; + else + m_alphaRenderList << e; + + e->order = ++m_nextRenderOrder; + // Used while rebuilding partial roots. + if (m_partialRebuild) + e->orphaned = false; + + } else if (node->type() == QSGNode::ClipNodeType || shadowNode->isBatchRoot) { + Q_ASSERT(m_nodes.contains(node)); + BatchRootInfo *info = batchRootInfo(shadowNode); + if (node == m_partialRebuildRoot) { + m_nextRenderOrder = info->firstOrder; + QSGNODE_TRAVERSE(node) + buildRenderLists(child); + m_nextRenderOrder = info->lastOrder + 1; + } else { + int currentOrder = m_nextRenderOrder; + QSGNODE_TRAVERSE(node) + buildRenderLists(child); + int padding = qMax((m_nextRenderOrder - currentOrder) >> 2, m_minimumOrderPadding); + info->firstOrder = currentOrder; + info->availableOrders = padding; + info->lastOrder = m_nextRenderOrder + padding; + m_nextRenderOrder = info->lastOrder; + } + return; + } else if (node->type() == QSGNode::RenderNodeType) { + RenderNodeElement *e = shadowNode->renderNodeElement(); + m_alphaRenderList << e; + e->order = ++m_nextRenderOrder; + Q_ASSERT(e); + } + + QSGNODE_TRAVERSE(node) + buildRenderLists(child); +} + +void Renderer::tagSubRoots(Node *node) +{ + BatchRootInfo *i = batchRootInfo(node); + m_taggedRoots << node; + for (QSet::const_iterator it = i->subRoots.constBegin(); + it != i->subRoots.constEnd(); ++it) { + tagSubRoots(*it); + } +} + +static void qsg_addOrphanedElements(QDataBuffer &orphans, const QDataBuffer &renderList) +{ + orphans.reset(); + for (int i=0; iremoved) { + e->orphaned = true; + orphans.add(e); + } + } +} + +static void qsg_addBackOrphanedElements(QDataBuffer &orphans, QDataBuffer &renderList) +{ + for (int i=0; iorphaned) + renderList.add(e); + } + orphans.reset(); +} + +/* + * To rebuild the tagged roots, we start by putting all subroots of tagged + * roots into the list of tagged roots. This is to make the rest of the + * algorithm simpler. + * + * Second, we invalidate all batches which belong to tagged roots, which now + * includes the entire subtree under a given root + * + * Then we call buildRenderLists for all tagged subroots which do not have + * parents which are tagged, aka, we traverse only the topmosts roots. + * + * Then we sort the render lists based on their render order, to restore the + * right order for rendering. + */ +void Renderer::buildRenderListsForTaggedRoots() +{ + // Flag any element that is currently in the render lists, but which + // is not in a batch. This happens when we have a partial rebuild + // in one sub tree while we have a BuildBatches change in another + // isolated subtree. So that batch-building takes into account + // these "orphaned" nodes, we flag them now. The ones under tagged + // roots will be cleared again. The remaining ones are added into the + // render lists so that they contain all visual nodes after the + // function completes. + qsg_addOrphanedElements(m_tmpOpaqueElements, m_opaqueRenderList); + qsg_addOrphanedElements(m_tmpAlphaElements, m_alphaRenderList); + + // Take a copy now, as we will be adding to this while traversing.. + QSet roots = m_taggedRoots; + for (QSet::const_iterator it = roots.constBegin(); + it != roots.constEnd(); ++it) { + tagSubRoots(*it); + } + + for (int i=0; iroot)) + invalidateAndRecycleBatch(b); + + } + for (int i=0; iroot)) + invalidateAndRecycleBatch(b); + } + + m_opaqueRenderList.reset(); + m_alphaRenderList.reset(); + int maxRenderOrder = m_nextRenderOrder; + m_partialRebuild = true; + // Traverse each root, assigning it + for (QSet::const_iterator it = m_taggedRoots.constBegin(); + it != m_taggedRoots.constEnd(); ++it) { + Node *root = *it; + BatchRootInfo *i = batchRootInfo(root); + if ((!i->parentRoot || !m_taggedRoots.contains(i->parentRoot)) + && !nodeUpdater()->isNodeBlocked(root->sgNode, rootNode())) { + m_nextRenderOrder = i->firstOrder; + m_partialRebuildRoot = root->sgNode; + buildRenderLists(root->sgNode); + } + } + m_partialRebuild = false; + m_partialRebuildRoot = nullptr; + m_taggedRoots.clear(); + m_nextRenderOrder = qMax(m_nextRenderOrder, maxRenderOrder); + + // Add orphaned elements back into the list and then sort it.. + qsg_addBackOrphanedElements(m_tmpOpaqueElements, m_opaqueRenderList); + qsg_addBackOrphanedElements(m_tmpAlphaElements, m_alphaRenderList); + + if (m_opaqueRenderList.size()) + std::sort(&m_opaqueRenderList.first(), &m_opaqueRenderList.last() + 1, qsg_sort_element_decreasing_order); + if (m_alphaRenderList.size()) + std::sort(&m_alphaRenderList.first(), &m_alphaRenderList.last() + 1, qsg_sort_element_increasing_order); + +} + +void Renderer::buildRenderListsFromScratch() +{ + m_opaqueRenderList.reset(); + m_alphaRenderList.reset(); + + for (int i=0; ifirst); + +#if defined(QSGBATCHRENDERER_INVALIDATE_WEDGED_NODES) + if (m_renderOrderRebuildLower < 0 || batch->first->order < m_renderOrderRebuildLower) + m_renderOrderRebuildLower = batch->first->order; + if (m_renderOrderRebuildUpper < 0 || batch->lastOrderInBatch > m_renderOrderRebuildUpper) + m_renderOrderRebuildUpper = batch->lastOrderInBatch; + + int first = m_renderOrderRebuildLower; + int last = m_renderOrderRebuildUpper; +#else + int first = batch->first->order; + int last = batch->lastOrderInBatch; +#endif + + batch->invalidate(); + + for (int i=0; ifirst) { + int bf = b->first->order; + int bl = b->lastOrderInBatch; + if (bl > first && bf < last) + b->invalidate(); + } + } + + m_rebuild |= BuildBatches; +} + +/* Clean up batches by making it a consecutive list of "valid" + * batches and moving all invalidated batches to the batches pool. + */ +void Renderer::cleanupBatches(QDataBuffer *batches) { + qsizetype n = batches->size(); + if (n == 0) + return; + + qsizetype writeIndex = 0; + for (qsizetype i = 0; i < n; ++i) { + Batch *b = batches->at(i); + if (b->first) + (*batches).data()[writeIndex++] = b; + else + invalidateAndRecycleBatch(b); + } + batches->resize(writeIndex); +} + +void Renderer::prepareOpaqueBatches() +{ + for (int i=m_opaqueRenderList.size() - 1; i >= 0; --i) { + Element *ei = m_opaqueRenderList.at(i); + if (!ei || ei->batch || ei->node->geometry()->vertexCount() == 0) + continue; + Batch *batch = newBatch(); + batch->first = ei; + batch->root = ei->root; + batch->isOpaque = true; + batch->needsUpload = true; + batch->positionAttribute = qsg_positionAttribute(ei->node->geometry()); + + m_opaqueBatches.add(batch); + + ei->batch = batch; + Element *next = ei; + + QSGGeometryNode *gni = ei->node; + + for (int j = i - 1; j >= 0; --j) { + Element *ej = m_opaqueRenderList.at(j); + if (!ej) + continue; + if (ej->root != ei->root) + break; + if (ej->batch || ej->node->geometry()->vertexCount() == 0) + continue; + + QSGGeometryNode *gnj = ej->node; + + const QSGGeometry *gniGeometry = gni->geometry(); + const QSGMaterial *gniMaterial = gni->activeMaterial(); + const QSGGeometry *gnjGeometry = gnj->geometry(); + const QSGMaterial *gnjMaterial = gnj->activeMaterial(); + if (gni->clipList() == gnj->clipList() + && gniGeometry->drawingMode() == gnjGeometry->drawingMode() + && (gniGeometry->lineWidth() == gnjGeometry->lineWidth() + || (gniGeometry->drawingMode() != QSGGeometry::DrawLines + && gniGeometry->drawingMode() != QSGGeometry::DrawLineStrip)) + && gniGeometry->attributes() == gnjGeometry->attributes() + && gniGeometry->indexType() == gnjGeometry->indexType() + && gni->inheritedOpacity() == gnj->inheritedOpacity() + && gniMaterial->type() == gnjMaterial->type() + && gniMaterial->viewCount() == gnjMaterial->viewCount() + && gniMaterial->compare(gnjMaterial) == 0 + && ei->mutabilityGroup == ej->mutabilityGroup) + { + ej->batch = batch; + next->nextInBatch = ej; + next = ej; + } + } + + batch->lastOrderInBatch = next->order; + } +} + +bool Renderer::checkOverlap(int first, int last, const Rect &bounds) +{ + for (int i=first; i<=last; ++i) { + Element *e = m_alphaRenderList.at(i); +#if defined(QSGBATCHRENDERER_INVALIDATE_WEDGED_NODES) + if (!e || e->batch) +#else + if (!e) +#endif + continue; + Q_ASSERT(e->boundsComputed); + if (e->bounds.intersects(bounds)) + return true; + } + return false; +} + +/* + * + * To avoid the O(n^2) checkOverlap check in most cases, we have the + * overlapBounds which is the union of all bounding rects to check overlap + * for. We know that if it does not overlap, then none of the individual + * ones will either. For the typical list case, this results in no calls + * to checkOverlap what-so-ever. This also ensures that when all consecutive + * items are matching (such as a table of text), we don't build up an + * overlap bounds and thus do not require full overlap checks. + */ + +void Renderer::prepareAlphaBatches() +{ + for (int i=0; iisRenderNode) + continue; + Q_ASSERT(!e->removed); + e->ensureBoundsValid(); + } + + for (int i=0; ibatch) + continue; + + if (ei->isRenderNode) { + Batch *rnb = newBatch(); + rnb->first = ei; + rnb->root = ei->root; + rnb->isOpaque = false; + rnb->isRenderNode = true; + ei->batch = rnb; + m_alphaBatches.add(rnb); + continue; + } + + if (ei->node->geometry()->vertexCount() == 0) + continue; + + Batch *batch = newBatch(); + batch->first = ei; + batch->root = ei->root; + batch->isOpaque = false; + batch->needsUpload = true; + m_alphaBatches.add(batch); + ei->batch = batch; + + QSGGeometryNode *gni = ei->node; + batch->positionAttribute = qsg_positionAttribute(gni->geometry()); + + Rect overlapBounds; + overlapBounds.set(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX); + + Element *next = ei; + + for (int j = i + 1; j < m_alphaRenderList.size(); ++j) { + Element *ej = m_alphaRenderList.at(j); + if (!ej) + continue; + if (ej->root != ei->root || ej->isRenderNode) + break; + if (ej->batch) { +#if !defined(QSGBATCHRENDERER_INVALIDATE_WEDGED_NODES) + overlapBounds |= ej->bounds; +#endif + continue; + } + + QSGGeometryNode *gnj = ej->node; + if (gnj->geometry()->vertexCount() == 0) + continue; + + const QSGGeometry *gniGeometry = gni->geometry(); + const QSGMaterial *gniMaterial = gni->activeMaterial(); + const QSGGeometry *gnjGeometry = gnj->geometry(); + const QSGMaterial *gnjMaterial = gnj->activeMaterial(); + if (gni->clipList() == gnj->clipList() + && gniGeometry->drawingMode() == gnjGeometry->drawingMode() + && (gniGeometry->drawingMode() != QSGGeometry::DrawLines + || (gniGeometry->lineWidth() == gnjGeometry->lineWidth() + // Must not do overlap checks when the line width is not 1, + // we have no knowledge how such lines are rasterized. + && gniGeometry->lineWidth() == 1.0f)) + && gniGeometry->attributes() == gnjGeometry->attributes() + && gniGeometry->indexType() == gnjGeometry->indexType() + && gni->inheritedOpacity() == gnj->inheritedOpacity() + && gniMaterial->type() == gnjMaterial->type() + && gniMaterial->viewCount() == gnjMaterial->viewCount() + && gniMaterial->compare(gnjMaterial) == 0 + && ei->mutabilityGroup == ej->mutabilityGroup) + { + if (!overlapBounds.intersects(ej->bounds) || !checkOverlap(i+1, j - 1, ej->bounds)) { + ej->batch = batch; + next->nextInBatch = ej; + next = ej; + } else { + /* When we come across a compatible element which hits an overlap, we + * need to stop the batch right away. We cannot add more elements + * to the current batch as they will be rendered before the batch that the + * current 'ej' will be added to. + */ + break; + } + } else { + overlapBounds |= ej->bounds; + } + } + + batch->lastOrderInBatch = next->order; + } + + +} + +static inline int qsg_fixIndexCount(int iCount, int drawMode) +{ + switch (drawMode) { + case QSGGeometry::DrawTriangleStrip: + // Merged triangle strips need to contain degenerate triangles at the beginning and end. + // One could save 2 uploaded ushorts here by ditching the padding for the front of the + // first and the end of the last, but for simplicity, we simply don't care. + // Those extra triangles will be skipped while drawing to preserve the strip's parity + // anyhow. + return iCount + 2; + case QSGGeometry::DrawLines: + // For lines we drop the last vertex if the number of vertices is uneven. + return iCount - (iCount % 2); + case QSGGeometry::DrawTriangles: + // For triangles we drop trailing vertices until the result is divisible by 3. + return iCount - (iCount % 3); + default: + return iCount; + } +} + +static inline float calculateElementZOrder(const Element *e, qreal zRange) +{ + // Clamp the zOrder to within the min and max depth of the viewport. + return std::clamp(1.0f - float(e->order * zRange), VIEWPORT_MIN_DEPTH, VIEWPORT_MAX_DEPTH); +} + +/* These parameters warrant some explanation... + * + * vaOffset: The byte offset into the vertex data to the location of the + * 2D float point vertex attributes. + * + * vertexData: destination where the geometry's vertex data should go + * + * zData: destination of geometries injected Z positioning + * + * indexData: destination of the indices for this element + * + * iBase: The starting index for this element in the batch + */ + +void Renderer::uploadMergedElement(Element *e, int vaOffset, char **vertexData, char **zData, char **indexData, void *iBasePtr, int *indexCount) +{ + if (Q_UNLIKELY(debug_upload())) qDebug() << " - uploading element:" << e << e->node << (void *) *vertexData << (qintptr) (*zData - *vertexData) << (qintptr) (*indexData - *vertexData); + QSGGeometry *g = e->node->geometry(); + + const QMatrix4x4 &localx = *e->node->matrix(); + const float *localxdata = localx.constData(); + + const int vCount = g->vertexCount(); + const int vSize = g->sizeOfVertex(); + memcpy(*vertexData, g->vertexData(), vSize * vCount); + + // apply vertex transform.. + char *vdata = *vertexData + vaOffset; + if (localx.flags() == QMatrix4x4::Translation) { + for (int i=0; ix += localxdata[12]; + p->y += localxdata[13]; + vdata += vSize; + } + } else if (localx.flags() > QMatrix4x4::Translation) { + for (int i=0; imap(localx); + vdata += vSize; + } + } + + if (useDepthBuffer()) { + float *vzorder = (float *) *zData; + float zorder = calculateElementZOrder(e, m_zRange); + for (int i=0; iindexCount(); + if (m_uint32IndexForRhi) { + // can only happen when using the rhi + quint32 *iBase = (quint32 *) iBasePtr; + quint32 *indices = (quint32 *) *indexData; + if (iCount == 0) { + iCount = vCount; + if (g->drawingMode() == QSGGeometry::DrawTriangleStrip) + *indices++ = *iBase; + else + iCount = qsg_fixIndexCount(iCount, g->drawingMode()); + + for (int i=0; iindexDataAsUShort(); + if (g->drawingMode() == QSGGeometry::DrawTriangleStrip) + *indices++ = *iBase + srcIndices[0]; + else + iCount = qsg_fixIndexCount(iCount, g->drawingMode()); + + for (int i=0; idrawingMode() == QSGGeometry::DrawTriangleStrip) { + indices[iCount] = indices[iCount - 1]; + iCount += 2; + } + *iBase += vCount; + } else { + // normally batching is only done for ushort index data + quint16 *iBase = (quint16 *) iBasePtr; + quint16 *indices = (quint16 *) *indexData; + if (iCount == 0) { + iCount = vCount; + if (g->drawingMode() == QSGGeometry::DrawTriangleStrip) + *indices++ = *iBase; + else + iCount = qsg_fixIndexCount(iCount, g->drawingMode()); + + for (int i=0; iindexDataAsUShort(); + if (g->drawingMode() == QSGGeometry::DrawTriangleStrip) + *indices++ = *iBase + srcIndices[0]; + else + iCount = qsg_fixIndexCount(iCount, g->drawingMode()); + + for (int i=0; idrawingMode() == QSGGeometry::DrawTriangleStrip) { + indices[iCount] = indices[iCount - 1]; + iCount += 2; + } + *iBase += vCount; + } + + *vertexData += vCount * vSize; + *indexData += iCount * mergedIndexElemSize(); + *indexCount += iCount; +} + +QMatrix4x4 qsg_matrixForRoot(Node *node) +{ + if (node->type() == QSGNode::TransformNodeType) + return static_cast(node->sgNode)->combinedMatrix(); + Q_ASSERT(node->type() == QSGNode::ClipNodeType); + QSGClipNode *c = static_cast(node->sgNode); + return *c->matrix(); +} + +void Renderer::uploadBatch(Batch *b) +{ + // Early out if nothing has changed in this batch.. + if (!b->needsUpload) { + if (Q_UNLIKELY(debug_upload())) qDebug() << " Batch:" << b << "already uploaded..."; + return; + } + + if (!b->first) { + if (Q_UNLIKELY(debug_upload())) qDebug() << " Batch:" << b << "is invalid..."; + return; + } + + if (b->isRenderNode) { + if (Q_UNLIKELY(debug_upload())) qDebug() << " Batch: " << b << "is a render node..."; + return; + } + + // Figure out if we can merge or not, if not, then just render the batch as is.. + Q_ASSERT(b->first); + Q_ASSERT(b->first->node); + + QSGGeometryNode *gn = b->first->node; + QSGGeometry *g = gn->geometry(); + QSGMaterial::Flags flags = gn->activeMaterial()->flags(); + bool canMerge = (g->drawingMode() == QSGGeometry::DrawTriangles || g->drawingMode() == QSGGeometry::DrawTriangleStrip || + g->drawingMode() == QSGGeometry::DrawLines || g->drawingMode() == QSGGeometry::DrawPoints) + && b->positionAttribute >= 0 + && g->indexType() == QSGGeometry::UnsignedShortType + && (flags & (QSGMaterial::NoBatching | QSGMaterial_FullMatrix)) == 0 + && ((flags & QSGMaterial::RequiresFullMatrixExceptTranslate) == 0 || b->isTranslateOnlyToRoot()) + && b->isSafeToBatch(); + + b->merged = canMerge; + + // Figure out how much memory we need... + b->vertexCount = 0; + b->indexCount = 0; + int unmergedIndexSize = 0; + Element *e = b->first; + + // Merged batches always do indexed draw calls. Non-indexed geometry gets + // indices generated automatically, when merged. + while (e) { + QSGGeometry *eg = e->node->geometry(); + b->vertexCount += eg->vertexCount(); + int iCount = eg->indexCount(); + if (b->merged) { + if (iCount == 0) + iCount = eg->vertexCount(); + iCount = qsg_fixIndexCount(iCount, g->drawingMode()); + } else { + const int effectiveIndexSize = m_uint32IndexForRhi ? sizeof(quint32) : eg->sizeOfIndex(); + unmergedIndexSize += iCount * effectiveIndexSize; + } + b->indexCount += iCount; + e = e->nextInBatch; + } + + // Abort if there are no vertices in this batch.. We abort this late as + // this is a broken usecase which we do not care to optimize for... + if (b->vertexCount == 0 || (b->merged && b->indexCount == 0)) + return; + + /* Allocate memory for this batch. Merged batches are divided into three separate blocks + 1. Vertex data for all elements, as they were in the QSGGeometry object, but + with the tranform relative to this batch's root applied. The vertex data + is otherwise unmodified. + 2. Z data for all elements, derived from each elements "render order". + This is present for merged data only. + 3. Indices for all elements, as they were in the QSGGeometry object, but + adjusted so that each index matches its. + And for TRIANGLE_STRIPs, we need to insert degenerate between each + primitive. These are unsigned shorts for merged and arbitrary for + non-merged. + */ + int bufferSize = b->vertexCount * g->sizeOfVertex(); + int ibufferSize = 0; + if (b->merged) { + ibufferSize = b->indexCount * mergedIndexElemSize(); + if (useDepthBuffer()) + bufferSize += b->vertexCount * sizeof(float); + } else { + ibufferSize = unmergedIndexSize; + } + + map(&b->ibo, ibufferSize, true); + map(&b->vbo, bufferSize); + + if (Q_UNLIKELY(debug_upload())) qDebug() << " - batch" << b << " first:" << b->first << " root:" + << b->root << " merged:" << b->merged << " positionAttribute" << b->positionAttribute + << " vbo:" << b->vbo.buf << ":" << b->vbo.size; + + if (b->merged) { + char *vertexData = b->vbo.data; + char *zData = vertexData + b->vertexCount * g->sizeOfVertex(); + char *indexData = b->ibo.data; + + quint16 iOffset16 = 0; + quint32 iOffset32 = 0; + e = b->first; + uint verticesInSet = 0; + // Start a new set already after 65534 vertices because 0xFFFF may be + // used for an always-on primitive restart with some apis (adapt for + // uint32 indices as appropriate). + const uint verticesInSetLimit = m_uint32IndexForRhi ? 0xfffffffe : 0xfffe; + int indicesInSet = 0; + b->drawSets.reset(); + int drawSetIndices = 0; + const char *indexBase = b->ibo.data; + b->drawSets << DrawSet(0, zData - vertexData, drawSetIndices); + while (e) { + verticesInSet += e->node->geometry()->vertexCount(); + if (verticesInSet > verticesInSetLimit) { + b->drawSets.last().indexCount = indicesInSet; + if (g->drawingMode() == QSGGeometry::DrawTriangleStrip) { + b->drawSets.last().indices += 1 * mergedIndexElemSize(); + b->drawSets.last().indexCount -= 2; + } + drawSetIndices = indexData - indexBase; + b->drawSets << DrawSet(vertexData - b->vbo.data, + zData - b->vbo.data, + drawSetIndices); + iOffset16 = 0; + iOffset32 = 0; + verticesInSet = e->node->geometry()->vertexCount(); + indicesInSet = 0; + } + void *iBasePtr = &iOffset16; + if (m_uint32IndexForRhi) + iBasePtr = &iOffset32; + uploadMergedElement(e, b->positionAttribute, &vertexData, &zData, &indexData, iBasePtr, &indicesInSet); + e = e->nextInBatch; + } + b->drawSets.last().indexCount = indicesInSet; + // We skip the very first and very last degenerate triangles since they aren't needed + // and the first one would reverse the vertex ordering of the merged strips. + if (g->drawingMode() == QSGGeometry::DrawTriangleStrip) { + b->drawSets.last().indices += 1 * mergedIndexElemSize(); + b->drawSets.last().indexCount -= 2; + } + } else { + char *vboData = b->vbo.data; + char *iboData = b->ibo.data; + Element *e = b->first; + while (e) { + QSGGeometry *g = e->node->geometry(); + int vbs = g->vertexCount() * g->sizeOfVertex(); + memcpy(vboData, g->vertexData(), vbs); + vboData = vboData + vbs; + const int indexCount = g->indexCount(); + if (indexCount) { + const int effectiveIndexSize = m_uint32IndexForRhi ? sizeof(quint32) : g->sizeOfIndex(); + const int ibs = indexCount * effectiveIndexSize; + if (g->sizeOfIndex() == effectiveIndexSize) { + memcpy(iboData, g->indexData(), ibs); + } else { + if (g->sizeOfIndex() == sizeof(quint16) && effectiveIndexSize == sizeof(quint32)) { + quint16 *src = g->indexDataAsUShort(); + quint32 *dst = (quint32 *) iboData; + for (int i = 0; i < indexCount; ++i) + dst[i] = src[i]; + } else { + Q_ASSERT_X(false, "uploadBatch (unmerged)", "uint index with ushort effective index - cannot happen"); + } + } + iboData += ibs; + } + e = e->nextInBatch; + } + } +#ifndef QT_NO_DEBUG_OUTPUT + if (Q_UNLIKELY(debug_upload())) { + const char *vd = b->vbo.data; + qDebug() << " -- Vertex Data, count:" << b->vertexCount << " - " << g->sizeOfVertex() << "bytes/vertex"; + for (int i=0; ivertexCount; ++i) { + QDebug dump = qDebug().nospace(); + dump << " --- " << i << ": "; + int offset = 0; + for (int a=0; aattributeCount(); ++a) { + const QSGGeometry::Attribute &attr = g->attributes()[a]; + dump << attr.position << ":(" << attr.tupleSize << ","; + if (attr.type == QSGGeometry::FloatType) { + dump << "float "; + if (attr.isVertexCoordinate) + dump << "* "; + for (int t=0; tmerged && useDepthBuffer()) { + float zorder = ((float*)(b->vbo.data + b->vertexCount * g->sizeOfVertex()))[i]; + dump << " Z:(" << zorder << ")"; + } + vd += g->sizeOfVertex(); + } + + if (!b->drawSets.isEmpty()) { + if (m_uint32IndexForRhi) { + const quint32 *id = (const quint32 *) b->ibo.data; + { + QDebug iDump = qDebug(); + iDump << " -- Index Data, count:" << b->indexCount; + for (int i=0; iindexCount; ++i) { + if ((i % 24) == 0) + iDump << Qt::endl << " --- "; + iDump << id[i]; + } + } + } else { + const quint16 *id = (const quint16 *) b->ibo.data; + { + QDebug iDump = qDebug(); + iDump << " -- Index Data, count:" << b->indexCount; + for (int i=0; iindexCount; ++i) { + if ((i % 24) == 0) + iDump << Qt::endl << " --- "; + iDump << id[i]; + } + } + } + + for (int i=0; idrawSets.size(); ++i) { + const DrawSet &s = b->drawSets.at(i); + qDebug() << " -- DrawSet: indexCount:" << s.indexCount << " vertices:" << s.vertices << " z:" << s.zorders << " indices:" << s.indices; + } + } + } +#endif // QT_NO_DEBUG_OUTPUT + + unmap(&b->vbo); + unmap(&b->ibo, true); + + if (Q_UNLIKELY(debug_upload() || debug_pools())) + qDebug() << " --- vertex/index buffers unmapped, batch upload completed... vbo pool size" << m_vboPoolCost << "ibo pool size" << m_iboPoolCost; + + b->needsUpload = false; + + if (Q_UNLIKELY(debug_render())) + b->uploadedThisFrame = true; +} + +void Renderer::applyClipStateToGraphicsState() +{ + m_gstate.usesScissor = (m_currentClipState.type & ClipState::ScissorClip); + m_gstate.stencilTest = (m_currentClipState.type & ClipState::StencilClip); +} + +QRhiGraphicsPipeline *Renderer::buildStencilPipeline(const Batch *batch, bool firstStencilClipInBatch) +{ + QRhiGraphicsPipeline *ps = m_rhi->newGraphicsPipeline(); + ps->setFlags(QRhiGraphicsPipeline::UsesStencilRef); + QRhiGraphicsPipeline::TargetBlend blend; + blend.colorWrite = {}; + ps->setTargetBlends({ blend }); + ps->setSampleCount(renderTarget().rt->sampleCount()); + ps->setStencilTest(true); + QRhiGraphicsPipeline::StencilOpState stencilOp; + if (firstStencilClipInBatch) { + stencilOp.compareOp = QRhiGraphicsPipeline::Always; + stencilOp.failOp = QRhiGraphicsPipeline::Keep; + stencilOp.depthFailOp = QRhiGraphicsPipeline::Keep; + stencilOp.passOp = QRhiGraphicsPipeline::Replace; + } else { + stencilOp.compareOp = QRhiGraphicsPipeline::Equal; + stencilOp.failOp = QRhiGraphicsPipeline::Keep; + stencilOp.depthFailOp = QRhiGraphicsPipeline::Keep; + stencilOp.passOp = QRhiGraphicsPipeline::IncrementAndClamp; + } + ps->setStencilFront(stencilOp); + ps->setStencilBack(stencilOp); + + ps->setTopology(m_stencilClipCommon.topology); + + ps->setMultiViewCount(renderTarget().multiViewCount); + + ps->setShaderStages({ QRhiShaderStage(QRhiShaderStage::Vertex, m_stencilClipCommon.vs), + QRhiShaderStage(QRhiShaderStage::Fragment, m_stencilClipCommon.fs) }); + ps->setVertexInputLayout(m_stencilClipCommon.inputLayout); + ps->setShaderResourceBindings(batch->stencilClipState.srb); // use something, it just needs to be layout-compatible + ps->setRenderPassDescriptor(renderTarget().rpDesc); + + if (!ps->create()) { + qWarning("Failed to build stencil clip pipeline"); + delete ps; + return nullptr; + } + + return ps; +} + +void Renderer::updateClipState(const QSGClipNode *clipList, Batch *batch) +{ + // Note: No use of the clip-related speparate m_current* vars is allowed + // here. All stored in batch->clipState instead. To collect state during + // the prepare steps, m_currentClipState is used. It should not be used in + // the render steps afterwards. + + // The stenciling logic is slightly different from Qt 5's direct OpenGL version + // as we cannot just randomly clear the stencil buffer. We now put all clip + // shapes into the stencil buffer for all batches in the frame. This means + // that the number of total clips in a scene is reduced (since the stencil + // value cannot exceed 255) but we do not need any clears inbetween. + + Q_ASSERT(m_rhi); + batch->stencilClipState.updateStencilBuffer = false; + if (clipList == m_currentClipState.clipList || Q_UNLIKELY(debug_noclip())) { + applyClipStateToGraphicsState(); + batch->clipState = m_currentClipState; + return; + } + + ClipState::ClipType clipType = ClipState::NoClip; + QRect scissorRect; + QVarLengthArray stencilClipNodes; + const QSGClipNode *clip = clipList; + + batch->stencilClipState.drawCalls.reset(); + quint32 totalVSize = 0; + quint32 totalISize = 0; + quint32 totalUSize = 0; + const quint32 StencilClipUbufSize = 64; + + while (clip) { + QMatrix4x4 m = m_current_projection_matrix_native_ndc[0]; // never hit for 3D and so multiview + if (clip->matrix()) + m *= *clip->matrix(); + + bool isRectangleWithNoPerspective = clip->isRectangular() + && qFuzzyIsNull(m(3, 0)) && qFuzzyIsNull(m(3, 1)); + bool noRotate = qFuzzyIsNull(m(0, 1)) && qFuzzyIsNull(m(1, 0)); + bool isRotate90 = qFuzzyIsNull(m(0, 0)) && qFuzzyIsNull(m(1, 1)); + + if (isRectangleWithNoPerspective && (noRotate || isRotate90)) { + QRectF bbox = clip->clipRect(); + qreal invW = 1 / m(3, 3); + qreal fx1, fy1, fx2, fy2; + if (noRotate) { + fx1 = (bbox.left() * m(0, 0) + m(0, 3)) * invW; + fy1 = (bbox.bottom() * m(1, 1) + m(1, 3)) * invW; + fx2 = (bbox.right() * m(0, 0) + m(0, 3)) * invW; + fy2 = (bbox.top() * m(1, 1) + m(1, 3)) * invW; + } else { + Q_ASSERT(isRotate90); + fx1 = (bbox.bottom() * m(0, 1) + m(0, 3)) * invW; + fy1 = (bbox.left() * m(1, 0) + m(1, 3)) * invW; + fx2 = (bbox.top() * m(0, 1) + m(0, 3)) * invW; + fy2 = (bbox.right() * m(1, 0) + m(1, 3)) * invW; + } + + if (fx1 > fx2) + qSwap(fx1, fx2); + if (fy1 > fy2) + qSwap(fy1, fy2); + + QRect deviceRect = this->deviceRect(); + + qint32 ix1 = qRound((fx1 + 1) * deviceRect.width() * qreal(0.5)); + qint32 iy1 = qRound((fy1 + 1) * deviceRect.height() * qreal(0.5)); + qint32 ix2 = qRound((fx2 + 1) * deviceRect.width() * qreal(0.5)); + qint32 iy2 = qRound((fy2 + 1) * deviceRect.height() * qreal(0.5)); + + if (!(clipType & ClipState::ScissorClip)) { + clipType |= ClipState::ScissorClip; + scissorRect = QRect(ix1, iy1, ix2 - ix1, iy2 - iy1); + } else { + scissorRect &= QRect(ix1, iy1, ix2 - ix1, iy2 - iy1); + } + } else { + clipType |= ClipState::StencilClip; + + const QSGGeometry *g = clip->geometry(); + Q_ASSERT(g->attributeCount() > 0); + + const int vertexByteSize = g->sizeOfVertex() * g->vertexCount(); + // the 4 byte alignment may not actually be needed here + totalVSize = aligned(totalVSize, 4u) + vertexByteSize; + if (g->indexCount()) { + const int indexByteSize = g->sizeOfIndex() * g->indexCount(); + // so no need to worry about NonFourAlignedEffectiveIndexBufferOffset + totalISize = aligned(totalISize, 4u) + indexByteSize; + } + // ubuf start offsets must be aligned (typically to 256 bytes) + totalUSize = aligned(totalUSize, m_ubufAlignment) + StencilClipUbufSize; + + stencilClipNodes.append(clip); + } + + clip = clip->clipList(); + } + + if (clipType & ClipState::StencilClip) { + bool rebuildVBuf = false; + if (!batch->stencilClipState.vbuf) { + batch->stencilClipState.vbuf = m_rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::VertexBuffer, totalVSize); + rebuildVBuf = true; + } else if (batch->stencilClipState.vbuf->size() < totalVSize) { + batch->stencilClipState.vbuf->setSize(totalVSize); + rebuildVBuf = true; + } + if (rebuildVBuf) { + if (!batch->stencilClipState.vbuf->create()) { + qWarning("Failed to build stencil clip vertex buffer"); + delete batch->stencilClipState.vbuf; + batch->stencilClipState.vbuf = nullptr; + return; + } + } + + if (totalISize) { + bool rebuildIBuf = false; + if (!batch->stencilClipState.ibuf) { + batch->stencilClipState.ibuf = m_rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::IndexBuffer, totalISize); + rebuildIBuf = true; + } else if (batch->stencilClipState.ibuf->size() < totalISize) { + batch->stencilClipState.ibuf->setSize(totalISize); + rebuildIBuf = true; + } + if (rebuildIBuf) { + if (!batch->stencilClipState.ibuf->create()) { + qWarning("Failed to build stencil clip index buffer"); + delete batch->stencilClipState.ibuf; + batch->stencilClipState.ibuf = nullptr; + return; + } + } + } + + bool rebuildUBuf = false; + if (!batch->stencilClipState.ubuf) { + batch->stencilClipState.ubuf = m_rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, totalUSize); + rebuildUBuf = true; + } else if (batch->stencilClipState.ubuf->size() < totalUSize) { + batch->stencilClipState.ubuf->setSize(totalUSize); + rebuildUBuf = true; + } + if (rebuildUBuf) { + if (!batch->stencilClipState.ubuf->create()) { + qWarning("Failed to build stencil clip uniform buffer"); + delete batch->stencilClipState.ubuf; + batch->stencilClipState.ubuf = nullptr; + return; + } + } + + if (!batch->stencilClipState.srb) { + batch->stencilClipState.srb = m_rhi->newShaderResourceBindings(); + const QRhiShaderResourceBinding ubufBinding = QRhiShaderResourceBinding::uniformBufferWithDynamicOffset( + 0, QRhiShaderResourceBinding::VertexStage, batch->stencilClipState.ubuf, StencilClipUbufSize); + batch->stencilClipState.srb->setBindings({ ubufBinding }); + if (!batch->stencilClipState.srb->create()) { + qWarning("Failed to build stencil clip srb"); + delete batch->stencilClipState.srb; + batch->stencilClipState.srb = nullptr; + return; + } + } + + quint32 vOffset = 0; + quint32 iOffset = 0; + quint32 uOffset = 0; + for (const QSGClipNode *clip : stencilClipNodes) { + const QSGGeometry *g = clip->geometry(); + const QSGGeometry::Attribute *a = g->attributes(); + StencilClipState::StencilDrawCall drawCall; + const bool firstStencilClipInBatch = batch->stencilClipState.drawCalls.isEmpty(); + + if (firstStencilClipInBatch) { + m_stencilClipCommon.inputLayout.setBindings({ QRhiVertexInputBinding(g->sizeOfVertex()) }); + m_stencilClipCommon.inputLayout.setAttributes({ QRhiVertexInputAttribute(0, 0, qsg_vertexInputFormat(*a), 0) }); + m_stencilClipCommon.topology = qsg_topology(g->drawingMode(), m_rhi); + } +#ifndef QT_NO_DEBUG + else { + if (qsg_topology(g->drawingMode(), m_rhi) != m_stencilClipCommon.topology) + qWarning("updateClipState: Clip list entries have different primitive topologies, this is not currently supported."); + if (qsg_vertexInputFormat(*a) != m_stencilClipCommon.inputLayout.cbeginAttributes()->format()) + qWarning("updateClipState: Clip list entries have different vertex input layouts, this is must not happen."); + } +#endif + + drawCall.vbufOffset = aligned(vOffset, 4u); + const int vertexByteSize = g->sizeOfVertex() * g->vertexCount(); + vOffset = drawCall.vbufOffset + vertexByteSize; + + int indexByteSize = 0; + if (g->indexCount()) { + drawCall.ibufOffset = aligned(iOffset, 4u); + indexByteSize = g->sizeOfIndex() * g->indexCount(); + iOffset = drawCall.ibufOffset + indexByteSize; + } + + drawCall.ubufOffset = aligned(uOffset, m_ubufAlignment); + uOffset = drawCall.ubufOffset + StencilClipUbufSize; + + QMatrix4x4 matrixYUpNDC = m_current_projection_matrix[0]; + if (clip->matrix()) + matrixYUpNDC *= *clip->matrix(); + + m_resourceUpdates->updateDynamicBuffer(batch->stencilClipState.ubuf, drawCall.ubufOffset, 64, matrixYUpNDC.constData()); + m_resourceUpdates->updateDynamicBuffer(batch->stencilClipState.vbuf, drawCall.vbufOffset, vertexByteSize, g->vertexData()); + if (indexByteSize) + m_resourceUpdates->updateDynamicBuffer(batch->stencilClipState.ibuf, drawCall.ibufOffset, indexByteSize, g->indexData()); + + // stencil ref goes 1, 1, 2, 3, 4, ..., N for the clips in the first batch, + // then N+1, N+1, N+2, N+3, ... for the next batch, + // and so on. + // Note the different stencilOp for the first and the subsequent clips. + drawCall.stencilRef = firstStencilClipInBatch ? m_currentClipState.stencilRef + 1 : m_currentClipState.stencilRef; + m_currentClipState.stencilRef += 1; + + drawCall.vertexCount = g->vertexCount(); + drawCall.indexCount = g->indexCount(); + drawCall.indexFormat = qsg_indexFormat(g); + batch->stencilClipState.drawCalls.add(drawCall); + } + + if (!m_stencilClipCommon.vs.isValid()) + m_stencilClipCommon.vs = QSGMaterialShaderPrivate::loadShader(QLatin1String(":/qt-project.org/scenegraph/shaders_ng/stencilclip.vert.qsb")); + + if (!m_stencilClipCommon.fs.isValid()) + m_stencilClipCommon.fs = QSGMaterialShaderPrivate::loadShader(QLatin1String(":/qt-project.org/scenegraph/shaders_ng/stencilclip.frag.qsb")); + + if (!m_stencilClipCommon.replacePs) + m_stencilClipCommon.replacePs = buildStencilPipeline(batch, true); + + if (!m_stencilClipCommon.incrPs) + m_stencilClipCommon.incrPs = buildStencilPipeline(batch, false); + + batch->stencilClipState.updateStencilBuffer = true; + } + + m_currentClipState.clipList = clipList; + m_currentClipState.type = clipType; + m_currentClipState.scissor = QRhiScissor(scissorRect.x(), scissorRect.y(), + scissorRect.width(), scissorRect.height()); + + applyClipStateToGraphicsState(); + batch->clipState = m_currentClipState; +} + +void Renderer::enqueueStencilDraw(const Batch *batch) +{ + // cliptype stencil + updateStencilBuffer==false means the batch uses + // stenciling but relies on the stencil data generated by a previous batch + // (due to the having the same clip node). Do not enqueue draw calls for + // stencil in this case as the stencil buffer is already up-to-date. + if (!batch->stencilClipState.updateStencilBuffer) + return; + + QRhiCommandBuffer *cb = renderTarget().cb; + const int count = batch->stencilClipState.drawCalls.size(); + for (int i = 0; i < count; ++i) { + const StencilClipState::StencilDrawCall &drawCall(batch->stencilClipState.drawCalls.at(i)); + QRhiShaderResourceBindings *srb = batch->stencilClipState.srb; + QRhiCommandBuffer::DynamicOffset ubufOffset(0, drawCall.ubufOffset); + if (i == 0) { + cb->setGraphicsPipeline(m_stencilClipCommon.replacePs); + cb->setViewport(m_pstate.viewport); + } else if (i == 1) { + cb->setGraphicsPipeline(m_stencilClipCommon.incrPs); + cb->setViewport(m_pstate.viewport); + } + // else incrPs is already bound + cb->setShaderResources(srb, 1, &ubufOffset); + cb->setStencilRef(drawCall.stencilRef); + const QRhiCommandBuffer::VertexInput vbufBinding(batch->stencilClipState.vbuf, drawCall.vbufOffset); + if (drawCall.indexCount) { + cb->setVertexInput(0, 1, &vbufBinding, + batch->stencilClipState.ibuf, drawCall.ibufOffset, drawCall.indexFormat); + cb->drawIndexed(drawCall.indexCount); + } else { + cb->setVertexInput(0, 1, &vbufBinding); + cb->draw(drawCall.vertexCount); + } + } +} + +void Renderer::setActiveRhiShader(QSGMaterialShader *program, ShaderManager::Shader *shader) +{ + Q_ASSERT(m_rhi); + m_currentProgram = program; + m_currentShader = shader; + m_currentMaterial = nullptr; +} + +static inline bool needsBlendConstant(QRhiGraphicsPipeline::BlendFactor f) +{ + return f == QRhiGraphicsPipeline::ConstantColor + || f == QRhiGraphicsPipeline::OneMinusConstantColor + || f == QRhiGraphicsPipeline::ConstantAlpha + || f == QRhiGraphicsPipeline::OneMinusConstantAlpha; +} + +// With QRhi renderBatches() is split to two steps: prepare and render. +// +// Prepare goes through the batches and elements, and set up a graphics +// pipeline, srb, uniform buffer, calculates clipping, based on m_gstate, the +// material (shaders), and the batches. This step does not touch the command +// buffer or renderpass-related state (m_pstate). +// +// The render step then starts a renderpass, and goes through all +// batches/elements again and records setGraphicsPipeline, drawIndexed, etc. on +// the command buffer. The prepare step's accumulated global state like +// m_gstate must not be used here. Rather, all data needed for rendering is +// available from Batch/Element at this stage. Bookkeeping of state in the +// renderpass is done via m_pstate. + +bool Renderer::ensurePipelineState(Element *e, const ShaderManager::Shader *sms, bool depthPostPass) +{ + // Note the key's == and qHash implementations: the renderpass descriptor + // and srb are tested for compatibility, not pointer equality. + // + // We do not store the srb pointer itself because the ownership stays with + // the Element and that can go away more often that we would like it + // to. (think scrolling a list view, constantly dropping and creating new + // nodes) Rather, use an opaque blob of a few uints and store and compare + // that. This works because once the pipeline is built, we will always call + // setShaderResources with an explicitly specified srb which is fine even if + // e->srb we used here to bake the pipeline is already gone by that point. + // + // A typical QSGMaterial's serialized srb layout is 8 uints. (uniform buffer + // + texture, 4 fields each) Regardless, using an implicitly shared + // container is essential here. (won't detach so no more allocs and copies + // are done, unless the Element decides to rebake the srb with a different + // layout - but then the detach is exactly what we need) + // + // Same story for the renderpass descriptor: the object can go away but + // that's fine because that has no effect on an already built pipeline, and + // for comparison we only rely on the serialized blob in order decide if the + // render target is compatible with the pipeline. + + const GraphicsPipelineStateKey k = GraphicsPipelineStateKey::create(m_gstate, sms, renderTarget().rpDesc, e->srb); + + // Note: dynamic state (viewport rect, scissor rect, stencil ref, blend + // constant) is never a part of GraphicsState/QRhiGraphicsPipeline. + + // See if there is an existing, matching pipeline state object. + auto it = m_shaderManager->pipelineCache.constFind(k); + if (it != m_shaderManager->pipelineCache.constEnd()) { + if (depthPostPass) + e->depthPostPassPs = *it; + else + e->ps = *it; + return true; + } + + // Build a new one. This is potentially expensive. + QRhiGraphicsPipeline *ps = m_rhi->newGraphicsPipeline(); + ps->setShaderStages(sms->stages.cbegin(), sms->stages.cend()); + ps->setVertexInputLayout(sms->inputLayout); + ps->setShaderResourceBindings(e->srb); + ps->setRenderPassDescriptor(renderTarget().rpDesc); + + QRhiGraphicsPipeline::Flags flags; + if (needsBlendConstant(m_gstate.srcColor) || needsBlendConstant(m_gstate.dstColor) + || needsBlendConstant(m_gstate.srcAlpha) || needsBlendConstant(m_gstate.dstAlpha)) + { + flags |= QRhiGraphicsPipeline::UsesBlendConstants; + } + if (m_gstate.usesScissor) + flags |= QRhiGraphicsPipeline::UsesScissor; + if (m_gstate.stencilTest) + flags |= QRhiGraphicsPipeline::UsesStencilRef; + + ps->setFlags(flags); + ps->setTopology(qsg_topology(m_gstate.drawMode, m_rhi)); + ps->setCullMode(m_gstate.cullMode); +#if QT_VERSION >= QT_VERSION_CHECK(6, 9, 2) + ps->setFrontFace(invertFrontFace() ? QRhiGraphicsPipeline::CW : QRhiGraphicsPipeline::CCW); +#endif + ps->setPolygonMode(m_gstate.polygonMode); + ps->setMultiViewCount(m_gstate.multiViewCount); + + QRhiGraphicsPipeline::TargetBlend blend; + blend.colorWrite = m_gstate.colorWrite; + blend.enable = m_gstate.blending; + blend.srcColor = m_gstate.srcColor; + blend.dstColor = m_gstate.dstColor; + blend.srcAlpha = m_gstate.srcAlpha; + blend.dstAlpha = m_gstate.dstAlpha; + blend.opColor = m_gstate.opColor; + blend.opAlpha = m_gstate.opAlpha; + ps->setTargetBlends({ blend }); + + ps->setDepthTest(m_gstate.depthTest); + ps->setDepthWrite(m_gstate.depthWrite); + ps->setDepthOp(m_gstate.depthFunc); + + if (m_gstate.stencilTest) { + ps->setStencilTest(true); + QRhiGraphicsPipeline::StencilOpState stencilOp; + stencilOp.compareOp = QRhiGraphicsPipeline::Equal; + stencilOp.failOp = QRhiGraphicsPipeline::Keep; + stencilOp.depthFailOp = QRhiGraphicsPipeline::Keep; + stencilOp.passOp = QRhiGraphicsPipeline::Keep; + ps->setStencilFront(stencilOp); + ps->setStencilBack(stencilOp); + } + + ps->setSampleCount(m_gstate.sampleCount); + + ps->setLineWidth(m_gstate.lineWidth); + + if (!ps->create()) { + qWarning("Failed to build graphics pipeline state"); + delete ps; + return false; + } + + m_shaderManager->pipelineCache.insert(k, ps); + if (depthPostPass) + e->depthPostPassPs = ps; + else + e->ps = ps; + return true; +} + +static QRhiSampler *newSampler(QRhi *rhi, const QSGSamplerDescription &desc) +{ + QRhiSampler::Filter magFilter; + QRhiSampler::Filter minFilter; + QRhiSampler::Filter mipmapMode; + QRhiSampler::AddressMode u; + QRhiSampler::AddressMode v; + + switch (desc.filtering) { + case QSGTexture::None: + Q_FALLTHROUGH(); + case QSGTexture::Nearest: + magFilter = minFilter = QRhiSampler::Nearest; + break; + case QSGTexture::Linear: + magFilter = minFilter = QRhiSampler::Linear; + break; + default: + Q_UNREACHABLE(); + magFilter = minFilter = QRhiSampler::Nearest; + break; + } + + switch (desc.mipmapFiltering) { + case QSGTexture::None: + mipmapMode = QRhiSampler::None; + break; + case QSGTexture::Nearest: + mipmapMode = QRhiSampler::Nearest; + break; + case QSGTexture::Linear: + mipmapMode = QRhiSampler::Linear; + break; + default: + Q_UNREACHABLE(); + mipmapMode = QRhiSampler::None; + break; + } + + switch (desc.horizontalWrap) { + case QSGTexture::Repeat: + u = QRhiSampler::Repeat; + break; + case QSGTexture::ClampToEdge: + u = QRhiSampler::ClampToEdge; + break; + case QSGTexture::MirroredRepeat: + u = QRhiSampler::Mirror; + break; + default: + Q_UNREACHABLE(); + u = QRhiSampler::ClampToEdge; + break; + } + + switch (desc.verticalWrap) { + case QSGTexture::Repeat: + v = QRhiSampler::Repeat; + break; + case QSGTexture::ClampToEdge: + v = QRhiSampler::ClampToEdge; + break; + case QSGTexture::MirroredRepeat: + v = QRhiSampler::Mirror; + break; + default: + Q_UNREACHABLE(); + v = QRhiSampler::ClampToEdge; + break; + } + + return rhi->newSampler(magFilter, minFilter, mipmapMode, u, v); +} + +QRhiTexture *Renderer::dummyTexture() +{ + if (!m_dummyTexture) { + m_dummyTexture = m_rhi->newTexture(QRhiTexture::RGBA8, QSize(64, 64)); + if (m_dummyTexture->create()) { + if (m_resourceUpdates) { + QImage img(m_dummyTexture->pixelSize(), QImage::Format_RGBA8888_Premultiplied); + img.fill(0); + m_resourceUpdates->uploadTexture(m_dummyTexture, img); + } + } + } + return m_dummyTexture; +} + +static void rendererToMaterialGraphicsState(QSGMaterialShader::GraphicsPipelineState *dst, + GraphicsState *src) +{ + dst->blendEnable = src->blending; + + // the enum values should match, sanity check it + Q_ASSERT(int(QSGMaterialShader::GraphicsPipelineState::OneMinusSrc1Alpha) == int(QRhiGraphicsPipeline::OneMinusSrc1Alpha)); + Q_ASSERT(int(QSGMaterialShader::GraphicsPipelineState::BlendOp::Max) == int(QRhiGraphicsPipeline::Max)); + Q_ASSERT(int(QSGMaterialShader::GraphicsPipelineState::A) == int(QRhiGraphicsPipeline::A)); + Q_ASSERT(int(QSGMaterialShader::GraphicsPipelineState::CullBack) == int(QRhiGraphicsPipeline::Back)); + Q_ASSERT(int(QSGMaterialShader::GraphicsPipelineState::Line) == int(QRhiGraphicsPipeline::Line)); + dst->srcColor = QSGMaterialShader::GraphicsPipelineState::BlendFactor(src->srcColor); + dst->dstColor = QSGMaterialShader::GraphicsPipelineState::BlendFactor(src->dstColor); + + // For compatibility with any existing code, separateBlendFactors defaults + // to _false_ which means that materials that do not touch srcAlpha and + // dstAlpha will continue to use srcColor and dstColor as the alpha + // blending factors. New code that needs different values for color/alpha, + // can explicitly set separateBlendFactors to true and then set srcAlpha + // and dstAlpha as well. + dst->separateBlendFactors = false; + + dst->srcAlpha = QSGMaterialShader::GraphicsPipelineState::BlendFactor(src->srcAlpha); + dst->dstAlpha = QSGMaterialShader::GraphicsPipelineState::BlendFactor(src->dstAlpha); + + dst->opColor = QSGMaterialShader::GraphicsPipelineState::BlendOp(src->opColor); + dst->opAlpha = QSGMaterialShader::GraphicsPipelineState::BlendOp(src->opAlpha); + + dst->colorWrite = QSGMaterialShader::GraphicsPipelineState::ColorMask(int(src->colorWrite)); + + dst->cullMode = QSGMaterialShader::GraphicsPipelineState::CullMode(src->cullMode); + dst->polygonMode = QSGMaterialShader::GraphicsPipelineState::PolygonMode(src->polygonMode); +} + +static void materialToRendererGraphicsState(GraphicsState *dst, + QSGMaterialShader::GraphicsPipelineState *src) +{ + dst->blending = src->blendEnable; + dst->srcColor = QRhiGraphicsPipeline::BlendFactor(src->srcColor); + dst->dstColor = QRhiGraphicsPipeline::BlendFactor(src->dstColor); + if (src->separateBlendFactors) { + dst->srcAlpha = QRhiGraphicsPipeline::BlendFactor(src->srcAlpha); + dst->dstAlpha = QRhiGraphicsPipeline::BlendFactor(src->dstAlpha); + } else { + dst->srcAlpha = dst->srcColor; + dst->dstAlpha = dst->dstColor; + } + dst->opColor = QRhiGraphicsPipeline::BlendOp(src->opColor); + dst->opAlpha = QRhiGraphicsPipeline::BlendOp(src->opAlpha); + dst->colorWrite = QRhiGraphicsPipeline::ColorMask(int(src->colorWrite)); + dst->cullMode = QRhiGraphicsPipeline::CullMode(src->cullMode); + dst->polygonMode = QRhiGraphicsPipeline::PolygonMode(src->polygonMode); +} + +void Renderer::updateMaterialDynamicData(ShaderManager::Shader *sms, + QSGMaterialShader::RenderState &renderState, + QSGMaterial *material, + const Batch *batch, + Element *e, + int ubufOffset, + int ubufRegionSize, + char *directUpdatePtr) +{ + m_current_resource_update_batch = m_resourceUpdates; + + QSGMaterialShader *shader = sms->materialShader; + QSGMaterialShaderPrivate *pd = QSGMaterialShaderPrivate::get(shader); + QVarLengthArray bindings; + + if (pd->ubufBinding >= 0) { + m_current_uniform_data = &pd->masterUniformData; + const bool changed = shader->updateUniformData(renderState, material, m_currentMaterial); + m_current_uniform_data = nullptr; + + if (changed || !batch->ubufDataValid) { + if (directUpdatePtr) + memcpy(directUpdatePtr + ubufOffset, pd->masterUniformData.constData(), ubufRegionSize); + else + m_resourceUpdates->updateDynamicBuffer(batch->ubuf, ubufOffset, ubufRegionSize, pd->masterUniformData.constData()); + } + + bindings.append(QRhiShaderResourceBinding::uniformBuffer(pd->ubufBinding, + pd->ubufStages, + batch->ubuf, + ubufOffset, + ubufRegionSize)); + } + + for (int binding = 0; binding < QSGMaterialShaderPrivate::MAX_SHADER_RESOURCE_BINDINGS; ++binding) { + const QRhiShaderResourceBinding::StageFlags stages = pd->combinedImageSamplerBindings[binding]; + if (!stages) + continue; + + const QVarLengthArray &prevTex(pd->textureBindingTable[binding]); + QVarLengthArray nextTex = prevTex; + + const int count = pd->combinedImageSamplerCount[binding]; + nextTex.resize(count); + + shader->updateSampledImage(renderState, binding, nextTex.data(), material, + m_currentMaterial); + + if (nextTex.contains(nullptr)) { + qWarning("No QSGTexture provided from updateSampledImage(). This is wrong."); + continue; + } + + bool hasDirtySamplerOptions = false; + bool isAnisotropic = false; + for (QSGTexture *t : nextTex) { + QSGTexturePrivate *td = QSGTexturePrivate::get(t); + hasDirtySamplerOptions |= td->hasDirtySamplerOptions(); + isAnisotropic |= t->anisotropyLevel() != QSGTexture::AnisotropyNone; + td->resetDirtySamplerOptions(); + } + + // prevTex may be invalid at this point, avoid dereferencing it + if (nextTex != prevTex || hasDirtySamplerOptions) { + + // The QSGTexture, and so the sampler parameters, may have changed. + // The rhiTexture is not relevant here. + pd->textureBindingTable[binding] = nextTex; // does not own + pd->samplerBindingTable[binding].clear(); + + if (isAnisotropic) // ### + qWarning("QSGTexture anisotropy levels are not currently supported"); + + QVarLengthArray samplers; + + for (QSGTexture *t : nextTex) { + const QSGSamplerDescription samplerDesc = QSGSamplerDescription::fromTexture(t); + + QRhiSampler *sampler = m_samplers[samplerDesc]; + + if (!sampler) { + sampler = newSampler(m_rhi, samplerDesc); + if (!sampler->create()) { + qWarning("Failed to build sampler"); + delete sampler; + continue; + } + m_samplers[samplerDesc] = sampler; + } + samplers.append(sampler); + } + + pd->samplerBindingTable[binding] = samplers; // does not own + } + + if (pd->textureBindingTable[binding].size() == pd->samplerBindingTable[binding].size()) { + + QVarLengthArray textureSamplers; + + for (int i = 0; i < pd->textureBindingTable[binding].size(); ++i) { + + QRhiTexture *texture = pd->textureBindingTable[binding].at(i)->rhiTexture(); + + // texture may be null if the update above failed for any reason, + // or if the QSGTexture chose to return null intentionally. This is + // valid and we still need to provide something to the shader. + if (!texture) + texture = dummyTexture(); + + QRhiSampler *sampler = pd->samplerBindingTable[binding].at(i); + + textureSamplers.append( + QRhiShaderResourceBinding::TextureAndSampler { texture, sampler }); + } + + if (!textureSamplers.isEmpty()) + bindings.append(QRhiShaderResourceBinding::sampledTextures( + binding, stages, count, textureSamplers.constData())); + } + } + +#ifndef QT_NO_DEBUG + if (bindings.isEmpty()) + qWarning("No shader resources for material %p, this is odd.", material); +#endif + + enum class SrbAction { + Unknown, + DoNothing, + UpdateResources, + Rebake + } srbAction = SrbAction::Unknown; + + // First, if the Element has no srb created at all, then try to find an existing, + // currently unused srb that is layout-compatible with our binding list. + if (!e->srb) { + // reuse a QVector as our work area, thus possibly reusing the underlying allocation too + QList &layoutDesc(m_shaderManager->srbLayoutDescSerializeWorkspace); + layoutDesc.clear(); + QRhiShaderResourceBinding::serializeLayoutDescription(bindings.cbegin(), bindings.cend(), std::back_inserter(layoutDesc)); + e->srb = m_shaderManager->srbPool.take(layoutDesc); + if (e->srb) { + // Here we know layout compatibility is satisfied, but do not spend time on full + // comparison. The chance of getting an srb that refers to the same resources + // (buffer, textures) is low in practice. So reuse, but write new resources. + srbAction = SrbAction::UpdateResources; + } + } + + // If the Element had an existing srb, investigate: + // - It may be used as-is (when nothing changed in the scene regarding this node compared to the previous frame). + // - Otherwise it may be able to go with a lightweight update (replace resources, binding list layout is the same). + // - If all else fails rebake the full thing, meaning we reuse the memory allocation but will recreate everything underneath. + if (srbAction == SrbAction::Unknown && e->srb) { + if (std::equal(e->srb->cbeginBindings(), e->srb->cendBindings(), bindings.cbegin(), bindings.cend())) { + srbAction = SrbAction::DoNothing; + } else if (std::equal(e->srb->cbeginBindings(), e->srb->cendBindings(), bindings.cbegin(), bindings.cend(), + [](const auto &a, const auto &b) { return a.isLayoutCompatible(b); })) + { + srbAction = SrbAction::UpdateResources; + } else { + srbAction = SrbAction::Rebake; + } + } + + // If the Element had no srb associated at all and could not find a layout-compatible + // one from the pool, then create a whole new object. + if (!e->srb) { + e->srb = m_rhi->newShaderResourceBindings(); + srbAction = SrbAction::Rebake; + } + + Q_ASSERT(srbAction != SrbAction::Unknown && e->srb); + + switch (srbAction) { + case SrbAction::DoNothing: + break; + case SrbAction::UpdateResources: + { + e->srb->setBindings(bindings.cbegin(), bindings.cend()); + QRhiShaderResourceBindings::UpdateFlags flags; + // Due to the way the binding list is built up above, if we have a uniform buffer + // at binding point 0 (or none at all) then the sampledTexture bindings are added + // with increasing binding points afterwards, so the list is already sorted based + // on the binding points, thus we can save some time by telling the QRhi backend + // not to sort again. + if (pd->ubufBinding <= 0 || bindings.size() <= 1) + flags |= QRhiShaderResourceBindings::BindingsAreSorted; + + e->srb->updateResources(flags); + } + break; + case SrbAction::Rebake: + e->srb->setBindings(bindings.cbegin(), bindings.cend()); + if (!e->srb->create()) + qWarning("Failed to build srb"); + break; + default: + Q_ASSERT_X(false, "updateMaterialDynamicData", "No srb action set, this cannot happen"); + } +} + +void Renderer::updateMaterialStaticData(ShaderManager::Shader *sms, + QSGMaterialShader::RenderState &renderState, + QSGMaterial *material, + Batch *batch, + bool *gstateChanged) +{ + QSGMaterialShader *shader = sms->materialShader; + *gstateChanged = false; + if (shader->flags().testFlag(QSGMaterialShader::UpdatesGraphicsPipelineState)) { + // generate the public mini-state from m_gstate, invoke the material, + // write the changes, if any, back to m_gstate, together with a way to + // roll those back. + QSGMaterialShader::GraphicsPipelineState shaderPs; + rendererToMaterialGraphicsState(&shaderPs, &m_gstate); + const bool changed = shader->updateGraphicsPipelineState(renderState, &shaderPs, material, m_currentMaterial); + if (changed) { + m_gstateStack.push(m_gstate); + materialToRendererGraphicsState(&m_gstate, &shaderPs); + if (needsBlendConstant(m_gstate.srcColor) || needsBlendConstant(m_gstate.dstColor) + || needsBlendConstant(m_gstate.srcAlpha) || needsBlendConstant(m_gstate.dstAlpha)) + { + batch->blendConstant = shaderPs.blendConstant; + } + *gstateChanged = true; + } + } +} + +bool Renderer::prepareRenderMergedBatch(Batch *batch, PreparedRenderBatch *renderBatch) +{ + if (batch->vertexCount == 0 || batch->indexCount == 0) + return false; + + Element *e = batch->first; + Q_ASSERT(e); + +#ifndef QT_NO_DEBUG_OUTPUT + if (Q_UNLIKELY(debug_render())) { + QDebug debug = qDebug(); + debug << " -" + << batch + << (batch->uploadedThisFrame ? "[ upload]" : "[retained]") + << (e->node->clipList() ? "[ clip]" : "[noclip]") + << (batch->isOpaque ? "[opaque]" : "[ alpha]") + << "[ merged]" + << " Nodes:" << QString::fromLatin1("%1").arg(qsg_countNodesInBatch(batch), 4).toLatin1().constData() + << " Vertices:" << QString::fromLatin1("%1").arg(batch->vertexCount, 5).toLatin1().constData() + << " Indices:" << QString::fromLatin1("%1").arg(batch->indexCount, 5).toLatin1().constData() + << " root:" << batch->root; + if (batch->drawSets.size() > 1) + debug << "sets:" << batch->drawSets.size(); + if (!batch->isOpaque) + debug << "opacity:" << e->node->inheritedOpacity(); + batch->uploadedThisFrame = false; + } +#endif + + QSGGeometryNode *gn = e->node; + + // We always have dirty matrix as all batches are at a unique z range. + QSGMaterialShader::RenderState::DirtyStates dirty = QSGMaterialShader::RenderState::DirtyMatrix; + if (batch->root) + m_current_model_view_matrix = qsg_matrixForRoot(batch->root); + else + m_current_model_view_matrix.setToIdentity(); + m_current_determinant = m_current_model_view_matrix.determinant(); + + const int viewCount = projectionMatrixCount(); + m_current_projection_matrix.resize(viewCount); + for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex) + m_current_projection_matrix[viewIndex] = projectionMatrix(viewIndex); + + m_current_projection_matrix_native_ndc.resize(projectionMatrixWithNativeNDCCount()); + for (int viewIndex = 0; viewIndex < projectionMatrixWithNativeNDCCount(); ++viewIndex) + m_current_projection_matrix_native_ndc[viewIndex] = projectionMatrixWithNativeNDC(viewIndex); + + QSGMaterial *material = gn->activeMaterial(); + if (m_renderMode != QSGRendererInterface::RenderMode3D) + updateClipState(gn->clipList(), batch); + + const QSGGeometry *g = gn->geometry(); + const int multiViewCount = renderTarget().multiViewCount; + ShaderManager::Shader *sms = useDepthBuffer() ? m_shaderManager->prepareMaterial(material, g, m_renderMode, multiViewCount) + : m_shaderManager->prepareMaterialNoRewrite(material, g, m_renderMode, multiViewCount); + if (!sms) + return false; + + Q_ASSERT(sms->materialShader); + if (m_currentShader != sms) + setActiveRhiShader(sms->materialShader, sms); + + m_current_opacity = gn->inheritedOpacity(); + if (!qFuzzyCompare(sms->lastOpacity, float(m_current_opacity))) { + dirty |= QSGMaterialShader::RenderState::DirtyOpacity; + sms->lastOpacity = m_current_opacity; + } + + QSGMaterialShaderPrivate *pd = QSGMaterialShaderPrivate::get(sms->materialShader); + const quint32 ubufSize = quint32(pd->masterUniformData.size()); + if (pd->ubufBinding >= 0) { + bool ubufRebuild = false; + if (!batch->ubuf) { + batch->ubuf = m_rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, ubufSize); + ubufRebuild = true; + } else { + if (batch->ubuf->size() < ubufSize) { + batch->ubuf->setSize(ubufSize); + ubufRebuild = true; + } + } + if (ubufRebuild) { + batch->ubufDataValid = false; + if (!batch->ubuf->create()) { + qWarning("Failed to build uniform buffer of size %u bytes", ubufSize); + delete batch->ubuf; + batch->ubuf = nullptr; + return false; + } + } + } + + QSGMaterialShader::RenderState renderState = state(QSGMaterialShader::RenderState::DirtyStates(int(dirty))); + + bool pendingGStatePop = false; + updateMaterialStaticData(sms, renderState, material, batch, &pendingGStatePop); + + char *directUpdatePtr = nullptr; + if (batch->ubuf->nativeBuffer().slotCount == 0) + directUpdatePtr = batch->ubuf->beginFullDynamicBufferUpdateForCurrentFrame(); + + updateMaterialDynamicData(sms, renderState, material, batch, e, 0, ubufSize, directUpdatePtr); + + if (directUpdatePtr) + batch->ubuf->endFullDynamicBufferUpdateForCurrentFrame(); + + m_gstate.drawMode = QSGGeometry::DrawingMode(g->drawingMode()); + m_gstate.lineWidth = g->lineWidth(); + + const bool hasPipeline = ensurePipelineState(e, sms); + + if (pendingGStatePop) + m_gstate = m_gstateStack.pop(); + + if (!hasPipeline) + return false; + + if (m_renderMode == QSGRendererInterface::RenderMode3D) { + m_gstateStack.push(m_gstate); + setStateForDepthPostPass(); + ensurePipelineState(e, sms, true); + m_gstate = m_gstateStack.pop(); + } + + batch->ubufDataValid = true; + + m_currentMaterial = material; + + renderBatch->batch = batch; + renderBatch->sms = sms; + + return true; +} + +void Renderer::checkLineWidth(QSGGeometry *g) +{ + if (g->drawingMode() == QSGGeometry::DrawLines || g->drawingMode() == QSGGeometry::DrawLineLoop + || g->drawingMode() == QSGGeometry::DrawLineStrip) + { + if (g->lineWidth() != 1.0f) { + static bool checkedWideLineSupport = false; + if (!checkedWideLineSupport) { + checkedWideLineSupport = true; + if (!m_rhi->isFeatureSupported(QRhi::WideLines)) + qWarning("Line widths other than 1 are not supported by the graphics API"); + } + } + } else if (g->drawingMode() == QSGGeometry::DrawPoints) { + if (g->lineWidth() != 1.0f) { + static bool warnedPointSize = false; + if (!warnedPointSize) { + warnedPointSize = true; + qWarning("Point size is not controllable by QSGGeometry. " + "Set gl_PointSize from the vertex shader instead."); + } + } + } +} + +void Renderer::renderMergedBatch(PreparedRenderBatch *renderBatch, bool depthPostPass) +{ + const Batch *batch = renderBatch->batch; + if (!batch->vbo.buf || !batch->ibo.buf) + return; + + Element *e = batch->first; + QSGGeometryNode *gn = e->node; + QSGGeometry *g = gn->geometry(); + checkLineWidth(g); + + if (batch->clipState.type & ClipState::StencilClip) + enqueueStencilDraw(batch); + + QRhiCommandBuffer *cb = renderTarget().cb; + setGraphicsPipeline(cb, batch, e, depthPostPass); + + for (int i = 0, ie = batch->drawSets.size(); i != ie; ++i) { + const DrawSet &draw = batch->drawSets.at(i); + const QRhiCommandBuffer::VertexInput vbufBindings[] = { + { batch->vbo.buf, quint32(draw.vertices) }, + { batch->vbo.buf, quint32(draw.zorders) } + }; + cb->setVertexInput(VERTEX_BUFFER_BINDING, useDepthBuffer() ? 2 : 1, vbufBindings, + batch->ibo.buf, draw.indices, + m_uint32IndexForRhi ? QRhiCommandBuffer::IndexUInt32 : QRhiCommandBuffer::IndexUInt16); + cb->drawIndexed(draw.indexCount); + } +} + +bool Renderer::prepareRenderUnmergedBatch(Batch *batch, PreparedRenderBatch *renderBatch) +{ + if (batch->vertexCount == 0) + return false; + + Element *e = batch->first; + Q_ASSERT(e); + + if (Q_UNLIKELY(debug_render())) { + qDebug() << " -" + << batch + << (batch->uploadedThisFrame ? "[ upload]" : "[retained]") + << (e->node->clipList() ? "[ clip]" : "[noclip]") + << (batch->isOpaque ? "[opaque]" : "[ alpha]") + << "[unmerged]" + << " Nodes:" << QString::fromLatin1("%1").arg(qsg_countNodesInBatch(batch), 4).toLatin1().constData() + << " Vertices:" << QString::fromLatin1("%1").arg(batch->vertexCount, 5).toLatin1().constData() + << " Indices:" << QString::fromLatin1("%1").arg(batch->indexCount, 5).toLatin1().constData() + << " root:" << batch->root; + + batch->uploadedThisFrame = false; + } + + const int viewCount = projectionMatrixCount(); + m_current_projection_matrix.resize(viewCount); + for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex) + m_current_projection_matrix[viewIndex] = projectionMatrix(viewIndex); + + m_current_projection_matrix_native_ndc.resize(projectionMatrixWithNativeNDCCount()); + for (int viewIndex = 0; viewIndex < projectionMatrixWithNativeNDCCount(); ++viewIndex) + m_current_projection_matrix_native_ndc[viewIndex] = projectionMatrixWithNativeNDC(viewIndex); + + QSGGeometryNode *gn = e->node; + if (m_renderMode != QSGRendererInterface::RenderMode3D) + updateClipState(gn->clipList(), batch); + + // We always have dirty matrix as all batches are at a unique z range. + QSGMaterialShader::RenderState::DirtyStates dirty = QSGMaterialShader::RenderState::DirtyMatrix; + + // The vertex attributes are assumed to be the same for all elements in the + // unmerged batch since the material (and so the shaders) is the same. + QSGGeometry *g = gn->geometry(); + QSGMaterial *material = gn->activeMaterial(); + ShaderManager::Shader *sms = m_shaderManager->prepareMaterialNoRewrite(material, g, m_renderMode, renderTarget().multiViewCount); + if (!sms) + return false; + + Q_ASSERT(sms->materialShader); + if (m_currentShader != sms) + setActiveRhiShader(sms->materialShader, sms); + + m_current_opacity = gn->inheritedOpacity(); + if (sms->lastOpacity != m_current_opacity) { + dirty |= QSGMaterialShader::RenderState::DirtyOpacity; + sms->lastOpacity = m_current_opacity; + } + + QMatrix4x4 rootMatrix = batch->root ? qsg_matrixForRoot(batch->root) : QMatrix4x4(); + + QSGMaterialShaderPrivate *pd = QSGMaterialShaderPrivate::get(sms->materialShader); + const quint32 ubufSize = quint32(pd->masterUniformData.size()); + if (pd->ubufBinding >= 0) { + quint32 totalUBufSize = 0; + while (e) { + totalUBufSize += aligned(ubufSize, m_ubufAlignment); + e = e->nextInBatch; + } + bool ubufRebuild = false; + if (!batch->ubuf) { + batch->ubuf = m_rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, totalUBufSize); + ubufRebuild = true; + } else { + if (batch->ubuf->size() < totalUBufSize) { + batch->ubuf->setSize(totalUBufSize); + ubufRebuild = true; + } + } + if (ubufRebuild) { + batch->ubufDataValid = false; + if (!batch->ubuf->create()) { + qWarning("Failed to build uniform buffer of size %u bytes", totalUBufSize); + delete batch->ubuf; + batch->ubuf = nullptr; + return false; + } + } + } + + QSGMaterialShader::RenderState renderState = state(QSGMaterialShader::RenderState::DirtyStates(int(dirty))); + bool pendingGStatePop = false; + updateMaterialStaticData(sms, renderState, + material, batch, &pendingGStatePop); + + int ubufOffset = 0; + QRhiGraphicsPipeline *ps = nullptr; + QRhiGraphicsPipeline *depthPostPassPs = nullptr; + e = batch->first; + + char *directUpdatePtr = nullptr; + if (batch->ubuf->nativeBuffer().slotCount == 0) + directUpdatePtr = batch->ubuf->beginFullDynamicBufferUpdateForCurrentFrame(); + + while (e) { + gn = e->node; + + m_current_model_view_matrix = rootMatrix * *gn->matrix(); + m_current_determinant = m_current_model_view_matrix.determinant(); + + const int viewCount = projectionMatrixCount(); + m_current_projection_matrix.resize(viewCount); + for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex) + m_current_projection_matrix[viewIndex] = projectionMatrix(viewIndex); + + m_current_projection_matrix_native_ndc.resize(projectionMatrixWithNativeNDCCount()); + for (int viewIndex = 0; viewIndex < projectionMatrixWithNativeNDCCount(); ++viewIndex) + m_current_projection_matrix_native_ndc[viewIndex] = projectionMatrixWithNativeNDC(viewIndex); + + if (useDepthBuffer()) { + // this cannot be multiview + m_current_projection_matrix[0](2, 2) = m_zRange; + m_current_projection_matrix[0](2, 3) = calculateElementZOrder(e, m_zRange); + } + + QSGMaterialShader::RenderState renderState = state(QSGMaterialShader::RenderState::DirtyStates(int(dirty))); + updateMaterialDynamicData(sms, renderState, material, batch, e, ubufOffset, ubufSize, directUpdatePtr); + + ubufOffset += aligned(ubufSize, m_ubufAlignment); + + const QSGGeometry::DrawingMode prevDrawMode = m_gstate.drawMode; + const float prevLineWidth = m_gstate.lineWidth; + m_gstate.drawMode = QSGGeometry::DrawingMode(g->drawingMode()); + m_gstate.lineWidth = g->lineWidth(); + + // Do not bother even looking up the ps if the topology has not changed + // since everything else is the same for all elements in the batch. + // (except if the material modified blend state) + if (!ps || m_gstate.drawMode != prevDrawMode || m_gstate.lineWidth != prevLineWidth || pendingGStatePop) { + if (!ensurePipelineState(e, sms)) { + if (pendingGStatePop) + m_gstate = m_gstateStack.pop(); + return false; + } + ps = e->ps; + if (m_renderMode == QSGRendererInterface::RenderMode3D) { + m_gstateStack.push(m_gstate); + setStateForDepthPostPass(); + ensurePipelineState(e, sms, true); + m_gstate = m_gstateStack.pop(); + depthPostPassPs = e->depthPostPassPs; + } + } else { + e->ps = ps; + if (m_renderMode == QSGRendererInterface::RenderMode3D) + e->depthPostPassPs = depthPostPassPs; + } + + // We don't need to bother with asking each node for its material as they + // are all identical (compare==0) since they are in the same batch. + m_currentMaterial = material; + + // We only need to push this on the very first iteration... + dirty &= ~QSGMaterialShader::RenderState::DirtyOpacity; + + e = e->nextInBatch; + } + + if (directUpdatePtr) + batch->ubuf->endFullDynamicBufferUpdateForCurrentFrame(); + + if (pendingGStatePop) + m_gstate = m_gstateStack.pop(); + + batch->ubufDataValid = true; + + renderBatch->batch = batch; + renderBatch->sms = sms; + + return true; +} + +void Renderer::renderUnmergedBatch(PreparedRenderBatch *renderBatch, bool depthPostPass) +{ + const Batch *batch = renderBatch->batch; + if (!batch->vbo.buf) + return; + + Element *e = batch->first; + + if (batch->clipState.type & ClipState::StencilClip) + enqueueStencilDraw(batch); + + quint32 vOffset = 0; + quint32 iOffset = 0; + QRhiCommandBuffer *cb = renderTarget().cb; + + while (e) { + QSGGeometry *g = e->node->geometry(); + checkLineWidth(g); + const int effectiveIndexSize = m_uint32IndexForRhi ? sizeof(quint32) : g->sizeOfIndex(); + + setGraphicsPipeline(cb, batch, e, depthPostPass); + + const QRhiCommandBuffer::VertexInput vbufBinding(batch->vbo.buf, vOffset); + if (g->indexCount()) { + if (batch->ibo.buf) { + cb->setVertexInput(VERTEX_BUFFER_BINDING, 1, &vbufBinding, + batch->ibo.buf, iOffset, + effectiveIndexSize == sizeof(quint32) ? QRhiCommandBuffer::IndexUInt32 + : QRhiCommandBuffer::IndexUInt16); + cb->drawIndexed(g->indexCount()); + } + } else { + cb->setVertexInput(VERTEX_BUFFER_BINDING, 1, &vbufBinding); + cb->draw(g->vertexCount()); + } + + vOffset += g->sizeOfVertex() * g->vertexCount(); + iOffset += g->indexCount() * effectiveIndexSize; + + e = e->nextInBatch; + } +} + +void Renderer::setViewportAndScissors(QRhiCommandBuffer *cb, const Batch *batch) +{ + if (!m_pstate.viewportSet) { + m_pstate.viewportSet = true; + cb->setViewport(m_pstate.viewport); + } + if (batch->clipState.type & ClipState::ScissorClip) { + m_pstate.scissorSet = true; + cb->setScissor(batch->clipState.scissor); + } else { + // Regardless of the ps not using scissor, the scissor may need to be + // reset, depending on the backend. So set the viewport again, which in + // turn also sets the scissor on backends where a scissor rect is + // always-on (Vulkan). + if (m_pstate.scissorSet) { + m_pstate.scissorSet = false; + cb->setViewport(m_pstate.viewport); + } + } +} + + +void Renderer::setGraphicsPipeline(QRhiCommandBuffer *cb, const Batch *batch, Element *e, bool depthPostPass) +{ + cb->setGraphicsPipeline(depthPostPass ? e->depthPostPassPs : e->ps); + + setViewportAndScissors(cb, batch); + + if (batch->clipState.type & ClipState::StencilClip) { + Q_ASSERT(e->ps->flags().testFlag(QRhiGraphicsPipeline::UsesStencilRef)); + cb->setStencilRef(batch->clipState.stencilRef); + } + if (!depthPostPass && e->ps->flags().testFlag(QRhiGraphicsPipeline::UsesBlendConstants)) + cb->setBlendConstants(batch->blendConstant); + + cb->setShaderResources(e->srb); +} + +void Renderer::releaseElement(Element *e, bool inDestructor) +{ + if (e->isRenderNode) { + delete static_cast(e); + } else { + if (e->srb) { + if (!inDestructor) { + if (m_shaderManager->srbPool.size() < m_srbPoolThreshold) + m_shaderManager->srbPool.insert(e->srb->serializedLayoutDescription(), e->srb); + else + delete e->srb; + } else { + delete e->srb; + } + e->srb = nullptr; + } + m_elementAllocator.release(e); + } +} + +void Renderer::deleteRemovedElements() +{ + if (!m_elementsToDelete.size()) + return; + + for (int i=0; iremoved) + *e = nullptr; + } + for (int i=0; iremoved) + *e = nullptr; + } + + for (int i=0; ivalid) + qWarning("prepareRenderPass() called with an already prepared render pass context"); + + ctx->valid = true; + + if (Q_UNLIKELY(debug_dump())) { + qDebug("\n"); + QSGNodeDumper::dump(rootNode()); + } + + ctx->timeRenderLists = 0; + ctx->timePrepareOpaque = 0; + ctx->timePrepareAlpha = 0; + ctx->timeSorting = 0; + ctx->timeUploadOpaque = 0; + ctx->timeUploadAlpha = 0; + + if (Q_UNLIKELY(debug_render() || debug_build())) { + QByteArray type("rebuild:"); + if (m_rebuild == 0) + type += " none"; + if (m_rebuild == FullRebuild) + type += " full"; + else { + if (m_rebuild & BuildRenderLists) + type += " renderlists"; + else if (m_rebuild & BuildRenderListsForTaggedRoots) + type += " partial"; + else if (m_rebuild & BuildBatches) + type += " batches"; + } + + qDebug() << "Renderer::render()" << this << type; + ctx->timer.start(); + } + + m_resourceUpdates = m_rhi->nextResourceUpdateBatch(); + + if (m_rebuild & (BuildRenderLists | BuildRenderListsForTaggedRoots)) { + bool complete = (m_rebuild & BuildRenderLists) != 0; + if (complete) + buildRenderListsFromScratch(); + else + buildRenderListsForTaggedRoots(); + m_rebuild |= BuildBatches; + + if (Q_UNLIKELY(debug_build())) { + qDebug("Opaque render lists %s:", (complete ? "(complete)" : "(partial)")); + for (int i=0; ibatch << " node:" << e->node << " order:" << e->order; + } + qDebug("Alpha render list %s:", complete ? "(complete)" : "(partial)"); + for (int i=0; ibatch << " node:" << e->node << " order:" << e->order; + } + } + } + if (Q_UNLIKELY(debug_render())) ctx->timeRenderLists = ctx->timer.restart(); + + for (int i=0; icleanupRemovedElements(); + for (int i=0; icleanupRemovedElements(); + deleteRemovedElements(); + + cleanupBatches(&m_opaqueBatches); + cleanupBatches(&m_alphaBatches); + + if (m_rebuild & BuildBatches) { + prepareOpaqueBatches(); + if (Q_UNLIKELY(debug_render())) ctx->timePrepareOpaque = ctx->timer.restart(); + prepareAlphaBatches(); + if (Q_UNLIKELY(debug_render())) ctx->timePrepareAlpha = ctx->timer.restart(); + + if (Q_UNLIKELY(debug_build())) { + qDebug("Opaque Batches:"); + for (int i=0; ineedsUpload ? "upload" : "") << " root:" << b->root; + for (Element *e = b->first; e; e = e->nextInBatch) { + qDebug() << " - element:" << e << " node:" << e->node << e->order; + } + } + qDebug("Alpha Batches:"); + for (int i=0; ineedsUpload ? "upload" : "") << " root:" << b->root; + for (Element *e = b->first; e; e = e->nextInBatch) { + qDebug() << " - element:" << e << e->bounds << " node:" << e->node << " order:" << e->order; + } + } + } + } else { + if (Q_UNLIKELY(debug_render())) ctx->timePrepareOpaque = ctx->timePrepareAlpha = ctx->timer.restart(); + } + + + deleteRemovedElements(); + + if (m_rebuild != 0) { + // Then sort opaque batches so that we're drawing the batches with the highest + // order first, maximizing the benefit of front-to-back z-ordering. + if (m_opaqueBatches.size()) + std::sort(&m_opaqueBatches.first(), &m_opaqueBatches.last() + 1, qsg_sort_batch_decreasing_order); + + // Sort alpha batches back to front so that they render correctly. + if (m_alphaBatches.size()) + std::sort(&m_alphaBatches.first(), &m_alphaBatches.last() + 1, qsg_sort_batch_increasing_order); + + m_zRange = m_nextRenderOrder != 0 + ? 1.0 / (m_nextRenderOrder) + : 0; + } + + if (Q_UNLIKELY(debug_render())) ctx->timeSorting = ctx->timer.restart(); + + // Set size to 0, nothing is deallocated, they will "grow" again + // as part of uploadBatch. + m_vertexUploadPool.reset(); + m_indexUploadPool.reset(); + + if (Q_UNLIKELY(debug_upload())) qDebug("Uploading Opaque Batches:"); + for (int i=0; itimeUploadOpaque = ctx->timer.restart(); + + if (Q_UNLIKELY(debug_upload())) qDebug("Uploading Alpha Batches:"); + for (int i=0; itimeUploadAlpha = ctx->timer.restart(); + + if (Q_UNLIKELY(debug_render())) { + qDebug().nospace() << "Rendering:" << Qt::endl + << " -> Opaque: " << qsg_countNodesInBatches(m_opaqueBatches) << " nodes in " << m_opaqueBatches.size() << " batches..." << Qt::endl + << " -> Alpha: " << qsg_countNodesInBatches(m_alphaBatches) << " nodes in " << m_alphaBatches.size() << " batches..."; + } + + m_current_opacity = 1; + m_currentMaterial = nullptr; + m_currentShader = nullptr; + m_currentProgram = nullptr; + m_currentClipState.reset(); + + const QRect viewport = viewportRect(); + + bool renderOpaque = !debug_noopaque(); + bool renderAlpha = !debug_noalpha(); + + m_pstate.viewport = + QRhiViewport(viewport.x(), deviceRect().bottom() - viewport.bottom(), viewport.width(), + viewport.height(), VIEWPORT_MIN_DEPTH, VIEWPORT_MAX_DEPTH); + m_pstate.clearColor = clearColor(); + m_pstate.dsClear = QRhiDepthStencilClearValue(1.0f, 0); + m_pstate.viewportSet = false; + m_pstate.scissorSet = false; + + m_gstate.depthTest = useDepthBuffer(); + m_gstate.depthWrite = useDepthBuffer(); + m_gstate.depthFunc = QRhiGraphicsPipeline::Less; + m_gstate.blending = false; + + m_gstate.cullMode = QRhiGraphicsPipeline::None; + m_gstate.polygonMode = QRhiGraphicsPipeline::Fill; + m_gstate.colorWrite = QRhiGraphicsPipeline::R + | QRhiGraphicsPipeline::G + | QRhiGraphicsPipeline::B + | QRhiGraphicsPipeline::A; + m_gstate.usesScissor = false; + m_gstate.stencilTest = false; + + m_gstate.sampleCount = renderTarget().rt->sampleCount(); + m_gstate.multiViewCount = renderTarget().multiViewCount; + + ctx->opaqueRenderBatches.clear(); + if (Q_LIKELY(renderOpaque)) { + for (int i = 0, ie = m_opaqueBatches.size(); i != ie; ++i) { + Batch *b = m_opaqueBatches.at(i); + PreparedRenderBatch renderBatch; + bool ok; + if (b->merged) + ok = prepareRenderMergedBatch(b, &renderBatch); + else + ok = prepareRenderUnmergedBatch(b, &renderBatch); + if (ok) + ctx->opaqueRenderBatches.append(renderBatch); + } + } + + m_gstate.blending = true; + // factors never change, always set for premultiplied alpha based blending + + // depth test stays enabled (if useDepthBuffer(), that is) but no need + // to write out depth from the transparent (back-to-front) pass + m_gstate.depthWrite = false; + + // special case: the 3D plane mode tests against the depth buffer, but does + // not write (and all batches are alpha because this render mode evaluates + // to useDepthBuffer()==false) + if (m_renderMode == QSGRendererInterface::RenderMode3D) { + Q_ASSERT(m_opaqueBatches.isEmpty()); + m_gstate.depthTest = true; + } + + ctx->alphaRenderBatches.clear(); + if (Q_LIKELY(renderAlpha)) { + for (int i = 0, ie = m_alphaBatches.size(); i != ie; ++i) { + Batch *b = m_alphaBatches.at(i); + PreparedRenderBatch renderBatch; + bool ok; + if (b->merged) + ok = prepareRenderMergedBatch(b, &renderBatch); + else if (b->isRenderNode) + ok = prepareRhiRenderNode(b, &renderBatch); + else + ok = prepareRenderUnmergedBatch(b, &renderBatch); + if (ok) + ctx->alphaRenderBatches.append(renderBatch); + } + } + + m_rebuild = 0; + +#if defined(QSGBATCHRENDERER_INVALIDATE_WEDGED_NODES) + m_renderOrderRebuildLower = -1; + m_renderOrderRebuildUpper = -1; +#endif + + if (m_visualizer->mode() != Visualizer::VisualizeNothing) + m_visualizer->prepareVisualize(); + + renderTarget().cb->resourceUpdate(m_resourceUpdates); + m_resourceUpdates = nullptr; +} + +void Renderer::beginRenderPass(RenderPassContext *) +{ + const QSGRenderTarget &rt(renderTarget()); + rt.cb->beginPass(rt.rt, m_pstate.clearColor, m_pstate.dsClear, nullptr, + // we cannot tell if the application will have + // native rendering thrown in to this pass + // (QQuickWindow::beginExternalCommands()), so + // we have no choice but to set the flag always + // (thus triggering using secondary command + // buffers with Vulkan) + QRhiCommandBuffer::ExternalContent + // We do not use GPU compute at all at the moment, this means we can + // get a small performance gain with OpenGL by declaring this. + | QRhiCommandBuffer::DoNotTrackResourcesForCompute); + + if (m_renderPassRecordingCallbacks.start) + m_renderPassRecordingCallbacks.start(m_renderPassRecordingCallbacks.userData); +} + +void Renderer::recordRenderPass(RenderPassContext *ctx) +{ + // prepareRenderPass and recordRenderPass must always be called together. + // They are separate because beginRenderPass and endRenderPass are optional. + // + // The valid call sequence are therefore: + // prepare, begin, record, end + // or + // prepare, record + + if (!ctx->valid) + qWarning("recordRenderPass() called without a prepared render pass context"); + + ctx->valid = false; + + QRhiCommandBuffer *cb = renderTarget().cb; + cb->debugMarkBegin(QByteArrayLiteral("Qt Quick scene render")); + + for (int i = 0, ie = ctx->opaqueRenderBatches.size(); i != ie; ++i) { + if (i == 0) + cb->debugMarkMsg(QByteArrayLiteral("Qt Quick opaque batches")); + PreparedRenderBatch *renderBatch = &ctx->opaqueRenderBatches[i]; + if (renderBatch->batch->merged) + renderMergedBatch(renderBatch); + else + renderUnmergedBatch(renderBatch); + } + + for (int i = 0, ie = ctx->alphaRenderBatches.size(); i != ie; ++i) { + if (i == 0) { + if (m_renderMode == QSGRendererInterface::RenderMode3D) + cb->debugMarkMsg(QByteArrayLiteral("Qt Quick 2D-in-3D batches")); + else + cb->debugMarkMsg(QByteArrayLiteral("Qt Quick alpha batches")); + } + PreparedRenderBatch *renderBatch = &ctx->alphaRenderBatches[i]; + if (renderBatch->batch->merged) + renderMergedBatch(renderBatch); + else if (renderBatch->batch->isRenderNode) + renderRhiRenderNode(renderBatch->batch); + else + renderUnmergedBatch(renderBatch); + } + + if (m_renderMode == QSGRendererInterface::RenderMode3D) { + // Depth post-pass to fill up the depth buffer in a way that it + // corresponds to what got rendered to the color buffer in the previous + // (alpha) pass. The previous pass cannot enable depth write due to Z + // fighting. Rather, do it separately in a dedicated color-write-off, + // depth-write-on pass. This enables the 3D content drawn afterwards to + // depth test against the 2D items' rendering. + for (int i = 0, ie = ctx->alphaRenderBatches.size(); i != ie; ++i) { + if (i == 0) + cb->debugMarkMsg(QByteArrayLiteral("Qt Quick 2D-in-3D depth post-pass")); + PreparedRenderBatch *renderBatch = &ctx->alphaRenderBatches[i]; + if (renderBatch->batch->merged) + renderMergedBatch(renderBatch, true); + else if (!renderBatch->batch->isRenderNode) // rendernodes are skipped here for now + renderUnmergedBatch(renderBatch, true); + } + } + + if (m_currentShader) + setActiveRhiShader(nullptr, nullptr); + + cb->debugMarkEnd(); + + if (Q_UNLIKELY(debug_render())) { + qDebug(" -> times: build: %d, prepare(opaque/alpha): %d/%d, sorting: %d, upload(opaque/alpha): %d/%d, record rendering: %d", + (int) ctx->timeRenderLists, + (int) ctx->timePrepareOpaque, (int) ctx->timePrepareAlpha, + (int) ctx->timeSorting, + (int) ctx->timeUploadOpaque, (int) ctx->timeUploadAlpha, + (int) ctx->timer.elapsed()); + } +} + +void Renderer::endRenderPass(RenderPassContext *) +{ + if (m_renderPassRecordingCallbacks.end) + m_renderPassRecordingCallbacks.end(m_renderPassRecordingCallbacks.userData); + + if (m_visualizer->mode() != Visualizer::VisualizeNothing) + m_visualizer->visualize(); + + renderTarget().cb->endPass(); +} + +struct RenderNodeState : public QSGRenderNode::RenderState +{ + const QMatrix4x4 *projectionMatrix() const override { return m_projectionMatrix; } + QRect scissorRect() const override { return m_scissorRect; } + bool scissorEnabled() const override { return m_scissorEnabled; } + int stencilValue() const override { return m_stencilValue; } + bool stencilEnabled() const override { return m_stencilEnabled; } + const QRegion *clipRegion() const override { return nullptr; } + + const QMatrix4x4 *m_projectionMatrix; + QRect m_scissorRect; + int m_stencilValue; + bool m_scissorEnabled; + bool m_stencilEnabled; +}; + +bool Renderer::prepareRhiRenderNode(Batch *batch, PreparedRenderBatch *renderBatch) +{ + if (Q_UNLIKELY(debug_render())) + qDebug() << " -" << batch << "rendernode"; + + const int viewCount = projectionMatrixCount(); + m_current_projection_matrix.resize(viewCount); + for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex) + m_current_projection_matrix[viewIndex] = projectionMatrix(viewIndex); + m_current_projection_matrix_native_ndc.resize(projectionMatrixWithNativeNDCCount()); + for (int viewIndex = 0; viewIndex < projectionMatrixWithNativeNDCCount(); ++viewIndex) + m_current_projection_matrix_native_ndc[viewIndex] = projectionMatrixWithNativeNDC(viewIndex); + + Q_ASSERT(batch->first->isRenderNode); + RenderNodeElement *e = static_cast(batch->first); + + setActiveRhiShader(nullptr, nullptr); + + QSGRenderNodePrivate *rd = QSGRenderNodePrivate::get(e->renderNode); + rd->m_clip_list = nullptr; + if (m_renderMode != QSGRendererInterface::RenderMode3D) { + QSGNode *clip = e->renderNode->parent(); + while (clip != rootNode()) { + if (clip->type() == QSGNode::ClipNodeType) { + rd->m_clip_list = static_cast(clip); + break; + } + clip = clip->parent(); + } + updateClipState(rd->m_clip_list, batch); + } + + QSGNode *xform = e->renderNode->parent(); + QMatrix4x4 matrix; + QSGNode *root = rootNode(); + if (e->root) { + matrix = qsg_matrixForRoot(e->root); + root = e->root->sgNode; + } + while (xform != root) { + if (xform->type() == QSGNode::TransformNodeType) { + matrix = matrix * static_cast(xform)->combinedMatrix(); + break; + } + xform = xform->parent(); + } + rd->m_localMatrix = matrix; + rd->m_matrix = &rd->m_localMatrix; + + QSGNode *opacity = e->renderNode->parent(); + rd->m_opacity = 1.0; + while (opacity != rootNode()) { + if (opacity->type() == QSGNode::OpacityNodeType) { + rd->m_opacity = static_cast(opacity)->combinedOpacity(); + break; + } + opacity = opacity->parent(); + } + + rd->m_rt = renderTarget(); + + rd->m_projectionMatrix.resize(viewCount); + for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex) + rd->m_projectionMatrix[viewIndex] = projectionMatrix(viewIndex); + + if (useDepthBuffer()) { + // this cannot be multiview + rd->m_projectionMatrix[0](2, 2) = m_zRange; + rd->m_projectionMatrix[0](2, 3) = calculateElementZOrder(e, m_zRange); + } + + e->renderNode->prepare(); + + renderBatch->batch = batch; + renderBatch->sms = nullptr; + + return true; +} + +void Renderer::renderRhiRenderNode(const Batch *batch) +{ + if (batch->clipState.type & ClipState::StencilClip) + enqueueStencilDraw(batch); + + RenderNodeElement *e = static_cast(batch->first); + QSGRenderNodePrivate *rd = QSGRenderNodePrivate::get(e->renderNode); + + RenderNodeState state; + // Expose only the first matrix through the state object, the rest are + // queriable through the QSGRenderNode getters anyway. + state.m_projectionMatrix = &rd->m_projectionMatrix[0]; + const std::array scissor = batch->clipState.scissor.scissor(); + state.m_scissorRect = QRect(scissor[0], scissor[1], scissor[2], scissor[3]); + state.m_stencilValue = batch->clipState.stencilRef; + state.m_scissorEnabled = batch->clipState.type & ClipState::ScissorClip; + state.m_stencilEnabled = batch->clipState.type & ClipState::StencilClip; + + const QSGRenderNode::StateFlags changes = e->renderNode->changedStates(); + + QRhiCommandBuffer *cb = renderTarget().cb; + setViewportAndScissors(cb, batch); + const bool needsExternal = !e->renderNode->flags().testFlag(QSGRenderNode::NoExternalRendering); + if (needsExternal) + cb->beginExternal(); + e->renderNode->render(&state); + if (needsExternal) + cb->endExternal(); + + rd->m_matrix = nullptr; + rd->m_clip_list = nullptr; + + if ((changes & QSGRenderNode::ViewportState) + || (changes & QSGRenderNode::ScissorState)) + { + // Reset both flags if either is reported as changed, since with the rhi + // it could be setViewport() that will record the resetting of the scissor. + m_pstate.viewportSet = false; + m_pstate.scissorSet = false; + } + + // Do not bother with RenderTargetState. Where applicable, endExternal() + // ensures the correct target is rebound. For others (like Vulkan) it makes + // no sense since render() could not possibly do that on our command buffer + // which is in renderpass recording state. +} + +void Renderer::setVisualizationMode(const QByteArray &mode) +{ + if (mode.isEmpty()) + m_visualizer->setMode(Visualizer::VisualizeNothing); + else if (mode == "clip") + m_visualizer->setMode(Visualizer::VisualizeClipping); + else if (mode == "overdraw") + m_visualizer->setMode(Visualizer::VisualizeOverdraw); + else if (mode == "batches") + m_visualizer->setMode(Visualizer::VisualizeBatches); + else if (mode == "changes") + m_visualizer->setMode(Visualizer::VisualizeChanges); +} + +bool Renderer::hasVisualizationModeWithContinuousUpdate() const +{ + return m_visualizer->mode() == Visualizer::VisualizeOverdraw; +} + +bool operator==(const GraphicsState &a, const GraphicsState &b) noexcept +{ + return a.depthTest == b.depthTest + && a.depthWrite == b.depthWrite + && a.depthFunc == b.depthFunc + && a.blending == b.blending + && a.srcColor == b.srcColor + && a.dstColor == b.dstColor + && a.srcAlpha == b.srcAlpha + && a.dstAlpha == b.dstAlpha + && a.opColor == b.opColor + && a.opAlpha == b.opAlpha + && a.colorWrite == b.colorWrite + && a.cullMode == b.cullMode + && a.usesScissor == b.usesScissor + && a.stencilTest == b.stencilTest + && a.sampleCount == b.sampleCount + && a.drawMode == b.drawMode + && a.lineWidth == b.lineWidth + && a.polygonMode == b.polygonMode + && a.multiViewCount == b.multiViewCount; +} + +bool operator!=(const GraphicsState &a, const GraphicsState &b) noexcept +{ + return !(a == b); +} + +size_t qHash(const GraphicsState &s, size_t seed) noexcept +{ + // do not bother with all fields + return seed + + s.depthTest * 1000 + + s.depthWrite * 100 + + s.depthFunc + + s.blending * 10 + + s.srcColor + + s.cullMode + + s.usesScissor + + s.stencilTest + + s.sampleCount + + s.multiViewCount; +} + +bool operator==(const GraphicsPipelineStateKey &a, const GraphicsPipelineStateKey &b) noexcept +{ + return a.state == b.state + && a.sms->materialShader == b.sms->materialShader + && a.renderTargetDescription == b.renderTargetDescription + && a.srbLayoutDescription == b.srbLayoutDescription; +} + +bool operator!=(const GraphicsPipelineStateKey &a, const GraphicsPipelineStateKey &b) noexcept +{ + return !(a == b); +} + +size_t qHash(const GraphicsPipelineStateKey &k, size_t seed) noexcept +{ + return qHash(k.state, seed) + ^ qHash(k.sms->materialShader) + ^ k.extra.renderTargetDescriptionHash + ^ k.extra.srbLayoutDescriptionHash; +} + +bool operator==(const ShaderKey &a, const ShaderKey &b) noexcept +{ + return a.type == b.type + && a.renderMode == b.renderMode + && a.multiViewCount == b.multiViewCount; +} + +bool operator!=(const ShaderKey &a, const ShaderKey &b) noexcept +{ + return !(a == b); +} + +size_t qHash(const ShaderKey &k, size_t seed) noexcept +{ + return qHash(k.type, seed) ^ int(k.renderMode) ^ k.multiViewCount; +} + +Visualizer::Visualizer(Renderer *renderer) + : m_renderer(renderer), + m_visualizeMode(VisualizeNothing) +{ +} + +Visualizer::~Visualizer() +{ +} + +#define QSGNODE_DIRTY_PARENT (QSGNode::DirtyNodeAdded \ + | QSGNode::DirtyOpacity \ + | QSGNode::DirtyMatrix \ + | QSGNode::DirtyNodeRemoved) + +void Visualizer::visualizeChangesPrepare(Node *n, uint parentChanges) +{ + uint childDirty = (parentChanges | n->dirtyState) & QSGNODE_DIRTY_PARENT; + uint selfDirty = n->dirtyState | parentChanges; + if (n->type() == QSGNode::GeometryNodeType && selfDirty != 0) + m_visualizeChangeSet.insert(n, selfDirty); + SHADOWNODE_TRAVERSE(n) { + visualizeChangesPrepare(child, childDirty); + } +} + +} // namespace WSGBatchRenderer + +QT_END_NAMESPACE + +#include "moc_wsgbatchrenderer_p.cpp" diff --git a/waylib/src/server/qtquick/scenegraph/wsgbatchrenderer_p.h b/waylib/src/server/qtquick/scenegraph/wsgbatchrenderer_p.h new file mode 100644 index 0000000000..1f354764d1 --- /dev/null +++ b/waylib/src/server/qtquick/scenegraph/wsgbatchrenderer_p.h @@ -0,0 +1,1057 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// Copyright (C) 2016 Jolla Ltd, author: +// Copyright (C) 2016 Robin Burchell +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef WSGBATCHRENDERER_P_H +#define WSGBATCHRENDERER_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include +#if QT_VERSION >= QT_VERSION_CHECK(6, 12, 0) +#include +#endif + +#include +#include +#include + +#include + +QT_BEGIN_NAMESPACE + +namespace WSGBatchRenderer +{ + +#define QSG_RENDERER_COORD_LIMIT 1000000.0f + +inline quint8 wsgNodeMutabilityGroup(const QSGNode *node) +{ + // Qt 6.12 declares QSGNodePrivate::mutabilityGroup() but only marks the + // class Q_AUTOTEST_EXPORT, so the symbol is missing from release builds. + // The vendored renderer follows Qt 6.11 invalidation rules, so keep the + // group neutral instead of linking against a private Qt symbol. + Q_UNUSED(node); + return 0; +} + +struct Vec; +struct Rect; +struct Buffer; +struct Chunk; +struct Batch; +struct Node; +class Updater; +class Renderer; +class ShaderManager; + +template class AllocatorPage +{ +public: + // The memory used by this allocator + char data[sizeof(Type) * PageSize]; + + // 'blocks' contains a list of free indices which can be allocated. + // The first available index is found in PageSize - available. + int blocks[PageSize]; + + // 'available' is the number of available instances this page has left to allocate. + int available; + + // This is not strictly needed, but useful for sanity checking and anyway + // pretty small.. + QBitArray allocated; + + AllocatorPage() + : available(PageSize) + , allocated(PageSize) + { + for (int i=0; i class Allocator +{ +public: + Allocator() + { + pages.push_back(new AllocatorPage()); + } + + ~Allocator() + { + qDeleteAll(pages); + } + + Type *allocate() + { + AllocatorPage *p = 0; + for (int i = m_freePage; i < pages.size(); i++) { + if (pages.at(i)->available > 0) { + p = pages.at(i); + m_freePage = i; + break; + } + } + + // we couldn't find a free page from m_freePage to the last page. + // either there is no free pages, or there weren't any in the area we + // scanned: rescanning is expensive, so let's just assume there isn't + // one. when an item is released, we'll reset m_freePage anyway. + if (!p) { + p = new AllocatorPage(); + m_freePage = pages.size(); + pages.push_back(p); + } + uint pos = p->blocks[PageSize - p->available]; + void *mem = p->at(pos); + p->available--; + p->allocated.setBit(pos); + Type *t = (Type*)mem; + return t; + } + + void releaseExplicit(uint pageIndex, uint index) + { + AllocatorPage *page = pages.at(pageIndex); + if (!page->allocated.testBit(index)) + qFatal("Double delete in allocator: page=%d, index=%d", pageIndex , index); + + // Zero this instance as we're done with it. + void *mem = page->at(index); + memset(mem, 0, sizeof(Type)); + + page->allocated[index] = false; + page->available++; + page->blocks[PageSize - page->available] = index; + + // Remove the pages if they are empty and they are the last ones. We need to keep the + // order of pages since we have references to their index, so we can only remove + // from the end. + while (page->available == PageSize && pages.size() > 1 && pages.back() == page) { + pages.pop_back(); + delete page; + page = pages.back(); + } + + // Reset the free page to force a scan for a new free point. + m_freePage = 0; + } + + void release(Type *t) + { + int pageIndex = -1; + for (int i=0; i *p = pages.at(i); + if ((Type *) (&p->data[0]) <= t && (Type *) (&p->data[PageSize * sizeof(Type)]) > t) { + pageIndex = i; + break; + } + } + Q_ASSERT(pageIndex >= 0); + + AllocatorPage *page = pages.at(pageIndex); + int index = (quint64(t) - quint64(&page->data[0])) / sizeof(Type); + + releaseExplicit(pageIndex, index); + } + + QList *> pages; + int m_freePage = 0; +}; + + +inline bool hasMaterialWithBlending(QSGGeometryNode *n) +{ + return (n->opaqueMaterial() ? n->opaqueMaterial()->flags() & QSGMaterial::Blending + : n->material()->flags() & QSGMaterial::Blending); +} + +struct Pt { + float x, y; + + void map(const QMatrix4x4 &mat) { + Pt r; + const float *m = mat.constData(); + r.x = x * m[0] + y * m[4] + m[12]; + r.y = x * m[1] + y * m[5] + m[13]; + x = r.x; + y = r.y; + } + + void set(float nx, float ny) { + x = nx; + y = ny; + } +}; + +inline QDebug operator << (QDebug d, const Pt &p) { + d << "Pt(" << p.x << p.y << ")"; + return d; +} + + + +struct Rect { + Pt tl, br; // Top-Left (min) and Bottom-Right (max) + + void operator |= (const Pt &pt) { + if (pt.x < tl.x) + tl.x = pt.x; + if (pt.x > br.x) + br.x = pt.x; + if (pt.y < tl.y) + tl.y = pt.y; + if (pt.y > br.y) + br.y = pt.y; + } + + void operator |= (const Rect &r) { + if (r.tl.x < tl.x) + tl.x = r.tl.x; + if (r.tl.y < tl.y) + tl.y = r.tl.y; + if (r.br.x > br.x) + br.x = r.br.x; + if (r.br.y > br.y) + br.y = r.br.y; + } + + void map(const QMatrix4x4 &m); + + void set(float left, float top, float right, float bottom) { + tl.set(left, top); + br.set(right, bottom); + } + + bool intersects(const Rect &r) { + bool xOverlap = r.tl.x < br.x && r.br.x > tl.x; + bool yOverlap = r.tl.y < br.y && r.br.y > tl.y; + return xOverlap && yOverlap; + } + + bool isOutsideFloatRange() const { + return tl.x < -QSG_RENDERER_COORD_LIMIT + || tl.y < -QSG_RENDERER_COORD_LIMIT + || br.x > QSG_RENDERER_COORD_LIMIT + || br.y > QSG_RENDERER_COORD_LIMIT; + } +}; + +inline QDebug operator << (QDebug d, const Rect &r) { + d << "Rect(" << r.tl.x << r.tl.y << r.br.x << r.br.y << ")"; + return d; +} + +struct Buffer { + quint32 size; + // Data is only valid while preparing the upload. Exception is if we are using the + // broken IBO workaround or we are using a visualization mode. + char *data; + QRhiBuffer *buf; + uint nonDynamicChangeCount; +}; + +struct Element { + Element() + : boundsComputed(false) + , boundsOutsideFloatRange(false) + , translateOnlyToRoot(false) + , removed(false) + , orphaned(false) + , isRenderNode(false) + , isMaterialBlended(false) + , mutabilityGroup(0) + { + } + + void setNode(QSGGeometryNode *n) { + node = n; + isMaterialBlended = hasMaterialWithBlending(n); + mutabilityGroup = wsgNodeMutabilityGroup(n); + } + + inline void ensureBoundsValid() { + if (!boundsComputed) + computeBounds(); + } + void computeBounds(); + + QSGGeometryNode *node = nullptr; + Batch *batch = nullptr; + Element *nextInBatch = nullptr; + Node *root = nullptr; + + Rect bounds; // in device coordinates + + int order = 0; + QRhiShaderResourceBindings *srb = nullptr; + QRhiGraphicsPipeline *ps = nullptr; + QRhiGraphicsPipeline *depthPostPassPs = nullptr; + + uint boundsComputed : 1; + uint boundsOutsideFloatRange : 1; + uint translateOnlyToRoot : 1; + uint removed : 1; + uint orphaned : 1; + uint isRenderNode : 1; + uint isMaterialBlended : 1; + uint mutabilityGroup : 4; +}; + +struct RenderNodeElement : public Element { + + RenderNodeElement(QSGRenderNode *rn) + : renderNode(rn) + { + isRenderNode = true; + } + + QSGRenderNode *renderNode; +}; + +struct BatchRootInfo { + BatchRootInfo() {} + QSet subRoots; + Node *parentRoot = nullptr; + int lastOrder = -1; + int firstOrder = -1; + int availableOrders = 0; +}; + +struct ClipBatchRootInfo : public BatchRootInfo +{ + QMatrix4x4 matrix; +}; + +struct DrawSet +{ + DrawSet(int v, int z, int i) + : vertices(v) + , zorders(z) + , indices(i) + { + } + DrawSet() {} + int vertices = 0; + int zorders = 0; + int indices = 0; + int indexCount = 0; +}; + +enum BatchCompatibility +{ + BatchBreaksOnCompare, + BatchIsCompatible +}; + +struct ClipState +{ + enum ClipTypeBit + { + NoClip = 0x00, + ScissorClip = 0x01, + StencilClip = 0x02 + }; + Q_DECLARE_FLAGS(ClipType, ClipTypeBit) + + const QSGClipNode *clipList; + ClipType type; + QRhiScissor scissor; + int stencilRef; + + inline void reset(); +}; + +struct StencilClipState +{ + StencilClipState() : drawCalls(1) { } + + bool updateStencilBuffer = false; + QRhiShaderResourceBindings *srb = nullptr; + QRhiBuffer *vbuf = nullptr; + QRhiBuffer *ibuf = nullptr; + QRhiBuffer *ubuf = nullptr; + + struct StencilDrawCall { + int stencilRef; + int vertexCount; + int indexCount; + QRhiCommandBuffer::IndexFormat indexFormat; + quint32 vbufOffset; + quint32 ibufOffset; + quint32 ubufOffset; + }; + QDataBuffer drawCalls; + + inline void reset(); +}; + +struct Batch +{ + Batch() : drawSets(1) {} + bool geometryWasChanged(QSGGeometryNode *gn); + BatchCompatibility isMaterialCompatible(Element *e) const; + void invalidate(); + void cleanupRemovedElements(); + + bool isTranslateOnlyToRoot() const; + bool isSafeToBatch() const; + + // pseudo-constructor... + void init() { + // Only non-reusable members are reset here. See Renderer::newBatch(). + first = nullptr; + root = nullptr; + vertexCount = 0; + indexCount = 0; + isOpaque = false; + needsUpload = false; + merged = false; + positionAttribute = -1; + uploadedThisFrame = false; + isRenderNode = false; + ubufDataValid = false; + needsPurge = false; + clipState.reset(); + blendConstant = QColor(); + } + + Element *first; + Node *root; + + int positionAttribute; + + int vertexCount; + int indexCount; + + int lastOrderInBatch; + + uint isOpaque : 1; + uint needsUpload : 1; + uint merged : 1; + uint isRenderNode : 1; + uint ubufDataValid : 1; + uint needsPurge : 1; + + mutable uint uploadedThisFrame : 1; // solely for debugging purposes + + Buffer vbo; + Buffer ibo; + QRhiBuffer *ubuf; + ClipState clipState; + StencilClipState stencilClipState; + QColor blendConstant; + + QDataBuffer drawSets; +}; + +// NOTE: Node is zero-initialized by the Allocator. +struct Node +{ + QSGNode *sgNode; + void *data; + + Node *m_parent; + Node *m_child; + Node *m_next; + Node *m_prev; + + Node *parent() const { return m_parent; } + + void append(Node *child) { + Q_ASSERT(child); + Q_ASSERT(!hasChild(child)); + Q_ASSERT(child->m_parent == nullptr); + Q_ASSERT(child->m_next == nullptr); + Q_ASSERT(child->m_prev == nullptr); + + if (!m_child) { + child->m_next = child; + child->m_prev = child; + m_child = child; + } else { + m_child->m_prev->m_next = child; + child->m_prev = m_child->m_prev; + m_child->m_prev = child; + child->m_next = m_child; + } + child->setParent(this); + } + + void remove(Node *child) { + Q_ASSERT(child); + Q_ASSERT(hasChild(child)); + + // only child.. + if (child->m_next == child) { + m_child = nullptr; + } else { + if (m_child == child) + m_child = child->m_next; + child->m_next->m_prev = child->m_prev; + child->m_prev->m_next = child->m_next; + } + child->m_next = nullptr; + child->m_prev = nullptr; + child->setParent(nullptr); + } + + Node *firstChild() const { return m_child; } + + Node *sibling() const { + Q_ASSERT(m_parent); + return m_next == m_parent->m_child ? nullptr : m_next; + } + + void setParent(Node *p) { + Q_ASSERT(m_parent == nullptr || p == nullptr); + m_parent = p; + } + + bool hasChild(Node *child) const { + Node *n = m_child; + while (n && n != child) + n = n->sibling(); + return n; + } + + + + QSGNode::DirtyState dirtyState; + + uint isOpaque : 1; + uint isBatchRoot : 1; + uint becameBatchRoot : 1; + + inline QSGNode::NodeType type() const { return sgNode->type(); } + + inline Element *element() const { + Q_ASSERT(sgNode->type() == QSGNode::GeometryNodeType); + return (Element *) data; + } + + inline RenderNodeElement *renderNodeElement() const { + Q_ASSERT(sgNode->type() == QSGNode::RenderNodeType); + return (RenderNodeElement *) data; + } + + inline ClipBatchRootInfo *clipInfo() const { + Q_ASSERT(sgNode->type() == QSGNode::ClipNodeType); + return (ClipBatchRootInfo *) data; + } + + inline BatchRootInfo *rootInfo() const { + Q_ASSERT(sgNode->type() == QSGNode::ClipNodeType + || (sgNode->type() == QSGNode::TransformNodeType && isBatchRoot)); + return (BatchRootInfo *) data; + } +}; + +class Updater : public QSGNodeUpdater +{ +public: + Updater(Renderer *r); + + void visitOpacityNode(Node *n); + void visitTransformNode(Node *n); + void visitGeometryNode(Node *n); + void visitClipNode(Node *n); + void updateRootTransforms(Node *n); + void updateRootTransforms(Node *n, Node *root, const QMatrix4x4 &combined); + + void updateStates(QSGNode *n) override; + void visitNode(Node *n); + void registerWithParentRoot(QSGNode *subRoot, QSGNode *parentRoot); + +private: + Renderer *renderer; + + QDataBuffer m_roots; + QDataBuffer m_rootMatrices; + + int m_added; + int m_transformChange; + int m_opacityChange; + + QMatrix4x4 m_identityMatrix; +}; + +struct GraphicsState +{ + bool depthTest = false; + bool depthWrite = false; + QRhiGraphicsPipeline::CompareOp depthFunc = QRhiGraphicsPipeline::Less; + bool blending = false; + QRhiGraphicsPipeline::BlendFactor srcColor = QRhiGraphicsPipeline::One; + QRhiGraphicsPipeline::BlendFactor dstColor = QRhiGraphicsPipeline::OneMinusSrcAlpha; + QRhiGraphicsPipeline::BlendFactor srcAlpha = QRhiGraphicsPipeline::One; + QRhiGraphicsPipeline::BlendFactor dstAlpha = QRhiGraphicsPipeline::OneMinusSrcAlpha; + QRhiGraphicsPipeline::BlendOp opColor = QRhiGraphicsPipeline::Add; + QRhiGraphicsPipeline::BlendOp opAlpha = QRhiGraphicsPipeline::Add; + QRhiGraphicsPipeline::ColorMask colorWrite = QRhiGraphicsPipeline::ColorMask(0xF); + QRhiGraphicsPipeline::CullMode cullMode = QRhiGraphicsPipeline::None; + bool usesScissor = false; + bool stencilTest = false; + int sampleCount = 1; + QSGGeometry::DrawingMode drawMode = QSGGeometry::DrawTriangles; + float lineWidth = 1.0f; + QRhiGraphicsPipeline::PolygonMode polygonMode = QRhiGraphicsPipeline::Fill; + int multiViewCount = 0; +}; + +bool operator==(const GraphicsState &a, const GraphicsState &b) noexcept; +bool operator!=(const GraphicsState &a, const GraphicsState &b) noexcept; +size_t qHash(const GraphicsState &s, size_t seed = 0) noexcept; + +struct ShaderManagerShader; + +struct GraphicsPipelineStateKey +{ + GraphicsState state; + const ShaderManagerShader *sms; + QList renderTargetDescription; + QList srbLayoutDescription; + struct { + size_t renderTargetDescriptionHash; + size_t srbLayoutDescriptionHash; + } extra; + static GraphicsPipelineStateKey create(const GraphicsState &state, + const ShaderManagerShader *sms, + const QRhiRenderPassDescriptor *rpDesc, + const QRhiShaderResourceBindings *srb) + { + const QList rtDesc = rpDesc->serializedFormat(); + const QList srbDesc = srb->serializedLayoutDescription(); + return { state, sms, rtDesc, srbDesc, { qHash(rtDesc), qHash(srbDesc) } }; + } +}; + +bool operator==(const GraphicsPipelineStateKey &a, const GraphicsPipelineStateKey &b) noexcept; +bool operator!=(const GraphicsPipelineStateKey &a, const GraphicsPipelineStateKey &b) noexcept; +size_t qHash(const GraphicsPipelineStateKey &k, size_t seed = 0) noexcept; + +struct ShaderKey +{ + QSGMaterialType *type; + QSGRendererInterface::RenderMode renderMode; + int multiViewCount; +}; + +bool operator==(const ShaderKey &a, const ShaderKey &b) noexcept; +bool operator!=(const ShaderKey &a, const ShaderKey &b) noexcept; +size_t qHash(const ShaderKey &k, size_t seed = 0) noexcept; + +struct ShaderManagerShader +{ + ~ShaderManagerShader() { + delete materialShader; + } + QSGMaterialShader *materialShader = nullptr; + QRhiVertexInputLayout inputLayout; + QVarLengthArray stages; + float lastOpacity; +}; + +class ShaderManager : public QObject +{ + Q_OBJECT +public: + using Shader = ShaderManagerShader; + + ShaderManager(QSGDefaultRenderContext *ctx) : context(ctx) { } + ~ShaderManager() { + qDeleteAll(rewrittenShaders); + qDeleteAll(stockShaders); + } + + void clearCachedRendererData(); + + QHash pipelineCache; + + QMultiHash, QRhiShaderResourceBindings *> srbPool; + QList srbLayoutDescSerializeWorkspace; + +public Q_SLOTS: + void invalidated(); + +public: + Shader *prepareMaterial(QSGMaterial *material, + const QSGGeometry *geometry = nullptr, + QSGRendererInterface::RenderMode renderMode = QSGRendererInterface::RenderMode2D, + int multiViewCount = 0); + Shader *prepareMaterialNoRewrite(QSGMaterial *material, + const QSGGeometry *geometry = nullptr, + QSGRendererInterface::RenderMode renderMode = QSGRendererInterface::RenderMode2D, + int multiViewCount = 0); + +private: + QHash rewrittenShaders; + QHash stockShaders; + + QSGDefaultRenderContext *context; +}; + +struct RenderPassState +{ + QRhiViewport viewport; + QColor clearColor; + QRhiDepthStencilClearValue dsClear; + bool viewportSet; + bool scissorSet; +}; + +class Visualizer +{ +public: + enum VisualizeMode { + VisualizeNothing, + VisualizeBatches, + VisualizeClipping, + VisualizeChanges, + VisualizeOverdraw + }; + + Visualizer(Renderer *renderer); + virtual ~Visualizer(); + + VisualizeMode mode() const { return m_visualizeMode; } + void setMode(VisualizeMode mode) { m_visualizeMode = mode; } + + virtual void visualizeChangesPrepare(Node *n, uint parentChanges = 0); + virtual void prepareVisualize() = 0; + virtual void visualize() = 0; + + virtual void releaseResources() = 0; + +protected: + Renderer *m_renderer; + VisualizeMode m_visualizeMode; + QHash m_visualizeChangeSet; +}; + +class Renderer : public QSGRenderer +{ +public: + Renderer(QSGDefaultRenderContext *ctx, QSGRendererInterface::RenderMode renderMode = QSGRendererInterface::RenderMode2D); + ~Renderer(); + + static Renderer *create(QSGRenderContext *rc, QSGRendererInterface::RenderMode renderMode = QSGRendererInterface::RenderMode2D) + { + auto *drc = qobject_cast(rc); + Q_ASSERT(drc); + return new Renderer(drc, renderMode); + } + + bool usesDepthBuffer() const { return useDepthBuffer(); } + ShaderManager *shaderManager() const { return m_shaderManager; } + +protected: + void nodeChanged(QSGNode *node, QSGNode::DirtyState state) override; + void render() override; + void prepareInline() override; + void renderInline() override; + void releaseCachedResources() override; + + struct PreparedRenderBatch { + const Batch *batch; + ShaderManager::Shader *sms; + }; + + struct RenderPassContext { + bool valid = false; + QVarLengthArray opaqueRenderBatches; + QVarLengthArray alphaRenderBatches; + QElapsedTimer timer; + quint64 timeRenderLists; + quint64 timePrepareOpaque; + quint64 timePrepareAlpha; + quint64 timeSorting; + quint64 timeUploadOpaque; + quint64 timeUploadAlpha; + }; + + // update batches and queue and commit rhi resource updates + void prepareRenderPass(RenderPassContext *ctx); + // records the beginPass() + void beginRenderPass(RenderPassContext *ctx); + // records the draw calls, must be preceded by a prepareRenderPass at minimum, + // and also surrounded by begin/endRenderPass unless we are recording inside an + // already started pass. + void recordRenderPass(RenderPassContext *ctx); + // does visualizing if enabled and records the endPass() + void endRenderPass(RenderPassContext *ctx); + +private: + enum RebuildFlag { + BuildRenderListsForTaggedRoots = 0x0001, + BuildRenderLists = 0x0002, + BuildBatches = 0x0004, + FullRebuild = 0xffff + }; + + friend class Updater; + friend class RhiVisualizer; + + void destroyGraphicsResources(); + void map(Buffer *buffer, quint32 byteSize, bool isIndexBuf = false); + void unmap(Buffer *buffer, bool isIndexBuf = false); + + void buildRenderListsFromScratch(); + void buildRenderListsForTaggedRoots(); + void tagSubRoots(Node *node); + void buildRenderLists(QSGNode *node); + + void deleteRemovedElements(); + void cleanupBatches(QDataBuffer *batches); + void prepareOpaqueBatches(); + bool checkOverlap(int first, int last, const Rect &bounds); + void prepareAlphaBatches(); + void invalidateBatchAndOverlappingRenderOrders(Batch *batch); + + void uploadBatch(Batch *b); + void uploadMergedElement(Element *e, int vaOffset, char **vertexData, char **zData, char **indexData, void *iBasePtr, int *indexCount); + + bool ensurePipelineState(Element *e, const ShaderManager::Shader *sms, bool depthPostPass = false); + QRhiTexture *dummyTexture(); + void updateMaterialDynamicData(ShaderManager::Shader *sms, QSGMaterialShader::RenderState &renderState, + QSGMaterial *material, const Batch *batch, Element *e, int ubufOffset, int ubufRegionSize, + char *directUpdatePtr); + void updateMaterialStaticData(ShaderManager::Shader *sms, QSGMaterialShader::RenderState &renderState, + QSGMaterial *material, Batch *batch, bool *gstateChanged); + void checkLineWidth(QSGGeometry *g); + bool prepareRenderMergedBatch(Batch *batch, PreparedRenderBatch *renderBatch); + void renderMergedBatch(PreparedRenderBatch *renderBatch, bool depthPostPass = false); + bool prepareRenderUnmergedBatch(Batch *batch, PreparedRenderBatch *renderBatch); + void renderUnmergedBatch(PreparedRenderBatch *renderBatch, bool depthPostPass = false); + void setViewportAndScissors(QRhiCommandBuffer *cb, const Batch *batch); + void setGraphicsPipeline(QRhiCommandBuffer *cb, const Batch *batch, Element *e, bool depthPostPass = false); + ClipState::ClipType updateStencilClip(const QSGClipNode *clip); + void updateClip(const QSGClipNode *clipList, const Batch *batch); + void applyClipStateToGraphicsState(); + QRhiGraphicsPipeline *buildStencilPipeline(const Batch *batch, bool firstStencilClipInBatch); + void updateClipState(const QSGClipNode *clipList, Batch *batch); + void enqueueStencilDraw(const Batch *batch); + const QMatrix4x4 &matrixForRoot(Node *node); + void renderRenderNode(Batch *batch); + bool prepareRhiRenderNode(Batch *batch, PreparedRenderBatch *renderBatch); + void renderRhiRenderNode(const Batch *batch); + void setActiveShader(QSGMaterialShader *program, ShaderManager::Shader *shader); + void setActiveRhiShader(QSGMaterialShader *program, ShaderManager::Shader *shader); + + bool changeBatchRoot(Node *node, Node *newRoot); + void registerBatchRoot(Node *childRoot, Node *parentRoot); + void removeBatchRootFromParent(Node *childRoot); + void nodeChangedBatchRoot(Node *node, Node *root); + void turnNodeIntoBatchRoot(Node *node); + void nodeWasTransformed(Node *node, int *vertexCount); + void nodeWasRemoved(Node *node); + void nodeWasAdded(QSGNode *node, Node *shadowParent); + BatchRootInfo *batchRootInfo(Node *node); + void updateLineWidth(QSGGeometry *g); + + inline Batch *newBatch(); + void invalidateAndRecycleBatch(Batch *b); + void releaseElement(Element *e, bool inDestructor = false); + + void setVisualizationMode(const QByteArray &mode) override; + bool hasVisualizationModeWithContinuousUpdate() const override; + + QSGDefaultRenderContext *m_context; + QSGRendererInterface::RenderMode m_renderMode; + QSet m_taggedRoots; + QDataBuffer m_opaqueRenderList; + QDataBuffer m_alphaRenderList; + int m_nextRenderOrder; + bool m_partialRebuild; + QSGNode *m_partialRebuildRoot; + bool m_forceNoDepthBuffer; + + QHash m_renderNodeElements; + QDataBuffer m_opaqueBatches; + QDataBuffer m_alphaBatches; + QHash m_nodes; + + QDataBuffer m_batchPool; + QDataBuffer m_elementsToDelete; + QDataBuffer m_tmpAlphaElements; + QDataBuffer m_tmpOpaqueElements; + + QDataBuffer m_vboPool; + QDataBuffer m_iboPool; + quint32 m_vboPoolCost; + quint32 m_iboPoolCost; + + uint m_rebuild; + qreal m_zRange; +#if defined(QSGBATCHRENDERER_INVALIDATE_WEDGED_NODES) + int m_renderOrderRebuildLower; + int m_renderOrderRebuildUpper; +#endif + + int m_batchNodeThreshold; + int m_batchVertexThreshold; + int m_srbPoolThreshold; + int m_bufferPoolSizeLimit; + int m_minimumOrderPadding; + + Visualizer *m_visualizer; + + ShaderManager *m_shaderManager; // per rendercontext, shared + QSGMaterial *m_currentMaterial; + QSGMaterialShader *m_currentProgram; + ShaderManager::Shader *m_currentShader; + ClipState m_currentClipState; + + QDataBuffer m_vertexUploadPool; + QDataBuffer m_indexUploadPool; + + Allocator m_nodeAllocator; + Allocator m_elementAllocator; + + RenderPassContext m_mainRenderPassContext; + QRhiResourceUpdateBatch *m_resourceUpdates = nullptr; + uint m_ubufAlignment; + bool m_uint32IndexForRhi; + GraphicsState m_gstate; + RenderPassState m_pstate; + QStack m_gstateStack; + QHash m_samplers; + QRhiTexture *m_dummyTexture = nullptr; + + struct StencilClipCommonData { + QRhiGraphicsPipeline *replacePs = nullptr; + QRhiGraphicsPipeline *incrPs = nullptr; + QShader vs; + QShader fs; + QRhiVertexInputLayout inputLayout; + QRhiGraphicsPipeline::Topology topology; + inline void reset(); + } m_stencilClipCommon; + + inline int mergedIndexElemSize() const; + inline bool useDepthBuffer() const; + inline void setStateForDepthPostPass(); +}; + +Batch *Renderer::newBatch() +{ + Batch *b; + int size = m_batchPool.size(); + if (size) { + b = m_batchPool.at(size - 1); + // vbo, ibo, ubuf, stencil-related buffers are reused + m_batchPool.resize(size - 1); + } else { + b = new Batch(); + Q_ASSERT(offsetof(Batch, ibo) == sizeof(Buffer) + offsetof(Batch, vbo)); + memset(&b->vbo, 0, sizeof(Buffer) * 2); // Clear VBO & IBO + b->ubuf = nullptr; + b->stencilClipState.reset(); + } + // initialize (when new batch) or reset (when reusing a batch) the non-reusable fields + b->init(); + return b; +} + +int Renderer::mergedIndexElemSize() const +{ + return m_uint32IndexForRhi ? sizeof(quint32) : sizeof(quint16); +} + +// "use" here means that both depth test and write is wanted (the latter for +// opaque batches only). Therefore neither RenderMode2DNoDepthBuffer nor +// RenderMode3D must result in true. So while RenderMode3D requires a depth +// buffer, this here must say false. In addition, m_forceNoDepthBuffer is a +// dynamic override relevant with QSGRenderNode. +// +bool Renderer::useDepthBuffer() const +{ + return !m_forceNoDepthBuffer && m_renderMode == QSGRendererInterface::RenderMode2D; +} + +void Renderer::setStateForDepthPostPass() +{ + m_gstate.colorWrite = {}; + m_gstate.depthWrite = true; + m_gstate.depthTest = true; + m_gstate.depthFunc = QRhiGraphicsPipeline::Less; +} + +void Renderer::StencilClipCommonData::reset() +{ + delete replacePs; + replacePs = nullptr; + + delete incrPs; + incrPs = nullptr; + + vs = QShader(); + fs = QShader(); +} + +void ClipState::reset() +{ + clipList = nullptr; + type = NoClip; + stencilRef = 0; +} + +void StencilClipState::reset() +{ + updateStencilBuffer = false; + + delete srb; + srb = nullptr; + + delete vbuf; + vbuf = nullptr; + + delete ibuf; + ibuf = nullptr; + + delete ubuf; + ubuf = nullptr; + + drawCalls.reset(); +} + +} + +Q_DECLARE_TYPEINFO(WSGBatchRenderer::GraphicsState, Q_RELOCATABLE_TYPE); +Q_DECLARE_TYPEINFO(WSGBatchRenderer::GraphicsPipelineStateKey, Q_RELOCATABLE_TYPE); +Q_DECLARE_TYPEINFO(WSGBatchRenderer::RenderPassState, Q_RELOCATABLE_TYPE); +Q_DECLARE_TYPEINFO(WSGBatchRenderer::DrawSet, Q_PRIMITIVE_TYPE); + +QT_END_NAMESPACE + +#endif // WSGBATCHRENDERER_P_H diff --git a/waylib/src/server/qtquick/scenegraph/wsgcontext.cpp b/waylib/src/server/qtquick/scenegraph/wsgcontext.cpp new file mode 100644 index 0000000000..315cf8a110 --- /dev/null +++ b/waylib/src/server/qtquick/scenegraph/wsgcontext.cpp @@ -0,0 +1,67 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wsgcontext_p.h" +#include "wsgbatchrenderer_p.h" +#include "wayliblogging.h" + +#include +#include +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WSGRenderContext : public QSGDefaultRenderContext +{ +public: + using QSGDefaultRenderContext::QSGDefaultRenderContext; + + QSGRenderer *createRenderer(QSGRendererInterface::RenderMode renderMode = QSGRendererInterface::RenderMode2D) override + { + return WSGBatchRenderer::Renderer::create(this, renderMode); + } +}; + +class WSGDefaultContext : public QSGDefaultContext +{ +public: + using QSGDefaultContext::QSGDefaultContext; + + QSGRenderContext *createRenderContext() override + { + return new WSGRenderContext(this); + } +}; + +void WSGContext::ensureInstalled() +{ + static bool installed = false; + if (installed) + return; + + if (QQuickRenderControlPrivate::sg) { + if (dynamic_cast(QQuickRenderControlPrivate::sg)) { + installed = true; + return; + } + qCCritical(lcWlRenderer) << "QQuickRenderControlPrivate::sg already exists and is not WSGContext"; + qFatal("WSGContext must be installed before any QQuickRenderControl is constructed"); + } + + QSGContext *sg = QSGContext::createDefaultContext(); + // QSGDefaultContext has no Q_OBJECT, so qobject_cast cannot identify it. + if (dynamic_cast(sg)) { + delete sg; + sg = new WSGDefaultContext; + qCDebug(lcWlRenderer) << "Installed WSGContext as QQuickRenderControl scene graph factory"; + } else { + qCDebug(lcWlRenderer) << "Skip WSGContext; using Qt scene graph adaptation"; + } + + // Qt only registers this when it creates sg itself. + qAddPostRoutine(QQuickRenderControlPrivate::cleanup); + QQuickRenderControlPrivate::sg = sg; + installed = true; +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/qtquick/scenegraph/wsgcontext_p.h b/waylib/src/server/qtquick/scenegraph/wsgcontext_p.h new file mode 100644 index 0000000000..98cb9d0790 --- /dev/null +++ b/waylib/src/server/qtquick/scenegraph/wsgcontext_p.h @@ -0,0 +1,20 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WSGContext +{ +public: + // Must run before any QQuickRenderControl is constructed, including the + // temporary one in WRenderHelper::getGraphicsApi(). If Qt's default + // context is QSGDefaultContext (RHI), replace it with ours; otherwise + // keep the adaptation Qt created (software, etc.). + static void ensureInstalled(); +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/qtquick/scenegraph/wsgrhivisualizer.cpp b/waylib/src/server/qtquick/scenegraph/wsgrhivisualizer.cpp new file mode 100644 index 0000000000..9ce3109dba --- /dev/null +++ b/waylib/src/server/qtquick/scenegraph/wsgrhivisualizer.cpp @@ -0,0 +1,890 @@ +// Copyright (C) 2019 The Qt Company Ltd. +// Copyright (C) 2016 Jolla Ltd, author: +// Copyright (C) 2016 Robin Burchell +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wsgrhivisualizer_p.h" +#include +#include + +QT_BEGIN_NAMESPACE + +namespace WSGBatchRenderer +{ + +#define QSGNODE_TRAVERSE(NODE) for (QSGNode *child = NODE->firstChild(); child; child = child->nextSibling()) +#define SHADOWNODE_TRAVERSE(NODE) for (Node *child = NODE->firstChild(); child; child = child->sibling()) +#define QSGNODE_DIRTY_PARENT (QSGNode::DirtyNodeAdded \ + | QSGNode::DirtyOpacity \ + | QSGNode::DirtyMatrix \ + | QSGNode::DirtyNodeRemoved) + +QMatrix4x4 qsg_matrixForRoot(Node *node); +QRhiVertexInputAttribute::Format qsg_vertexInputFormat(const QSGGeometry::Attribute &a); +QRhiCommandBuffer::IndexFormat qsg_indexFormat(const QSGGeometry *geometry); +QRhiGraphicsPipeline::Topology qsg_topology(int geomDrawMode, QRhi *rhi); + +RhiVisualizer::RhiVisualizer(Renderer *renderer) + : Visualizer(renderer) +{ +} + +RhiVisualizer::~RhiVisualizer() +{ + releaseResources(); +} + +void RhiVisualizer::releaseResources() +{ + m_pipelines.releaseResources(); + + m_fade.releaseResources(); + + m_changeVis.releaseResources(); + m_batchVis.releaseResources(); + m_clipVis.releaseResources(); + m_overdrawVis.releaseResources(); +} + +void RhiVisualizer::prepareVisualize() +{ + // Called before the render pass has begun (but after preparing the + // batches). Now is the time to put resource updates to the renderer's + // current m_resourceUpdates instance. + + if (m_visualizeMode == VisualizeNothing) + return; + + if (!m_vs.isValid()) { + m_vs = QSGMaterialShaderPrivate::loadShader( + QLatin1String(":/qt-project.org/scenegraph/shaders_ng/visualization.vert.qsb")); + m_fs = QSGMaterialShaderPrivate::loadShader( + QLatin1String(":/qt-project.org/scenegraph/shaders_ng/visualization.frag.qsb")); + } + + m_fade.prepare(this, m_renderer->m_rhi, m_renderer->m_resourceUpdates, m_renderer->renderTarget().rpDesc); + + const bool forceUintIndex = m_renderer->m_uint32IndexForRhi; + + switch (m_visualizeMode) { + case VisualizeBatches: + m_batchVis.prepare(m_renderer->m_opaqueBatches, m_renderer->m_alphaBatches, + this, + m_renderer->m_rhi, m_renderer->m_resourceUpdates, + forceUintIndex); + break; + case VisualizeClipping: + m_clipVis.prepare(m_renderer->rootNode(), this, + m_renderer->m_rhi, m_renderer->m_resourceUpdates); + break; + case VisualizeChanges: + m_changeVis.prepare(m_renderer->m_nodes.value(m_renderer->rootNode()), + this, + m_renderer->m_rhi, m_renderer->m_resourceUpdates); + m_visualizeChangeSet.clear(); + break; + case VisualizeOverdraw: + m_overdrawVis.prepare(m_renderer->m_nodes.value(m_renderer->rootNode()), + this, + m_renderer->m_rhi, m_renderer->m_resourceUpdates); + break; + default: + Q_UNREACHABLE(); + break; + } +} + +void RhiVisualizer::visualize() +{ + if (m_visualizeMode == VisualizeNothing) + return; + + QRhiCommandBuffer *cb = m_renderer->renderTarget().cb; + m_fade.render(cb); + + switch (m_visualizeMode) { + case VisualizeBatches: + m_batchVis.render(cb); + break; + case VisualizeClipping: + m_clipVis.render(cb); + break; + case VisualizeChanges: + m_changeVis.render(cb); + break; + case VisualizeOverdraw: + m_overdrawVis.render(cb); + break; + default: + Q_UNREACHABLE(); + break; + } +} + +void RhiVisualizer::recordDrawCalls(const QList &drawCalls, + QRhiCommandBuffer *cb, + QRhiShaderResourceBindings *srb, + bool blendOneOne) +{ + for (const DrawCall &dc : drawCalls) { + QRhiGraphicsPipeline *ps = m_pipelines.pipeline(this, m_renderer->m_rhi, srb, m_renderer->renderTarget().rpDesc, + dc.vertex.topology, dc.vertex.format, dc.vertex.stride, + blendOneOne); + if (!ps) + continue; + cb->setGraphicsPipeline(ps); // no-op if same as the last one + QRhiCommandBuffer::DynamicOffset dynofs(0, dc.buf.ubufOffset); + cb->setShaderResources(srb, 1, &dynofs); + QRhiCommandBuffer::VertexInput vb(dc.buf.vbuf, dc.buf.vbufOffset); + if (dc.index.count) { + cb->setVertexInput(0, 1, &vb, dc.buf.ibuf, dc.buf.ibufOffset, dc.index.format); + cb->drawIndexed(dc.index.count); + } else { + cb->setVertexInput(0, 1, &vb); + cb->draw(dc.vertex.count); + } + } +} + +const QRhiShaderResourceBinding::StageFlags ubufVisibility = + QRhiShaderResourceBinding::VertexStage | QRhiShaderResourceBinding::FragmentStage; + +void RhiVisualizer::Fade::prepare(RhiVisualizer *visualizer, + QRhi *rhi, QRhiResourceUpdateBatch *u, QRhiRenderPassDescriptor *rpDesc) +{ + this->visualizer = visualizer; + + if (!vbuf) { + float v[] = { -1, 1, 1, 1, -1, -1, 1, -1 }; + vbuf = rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(v)); + if (!vbuf->create()) + return; + u->uploadStaticBuffer(vbuf, v); + } + + if (!ubuf) { + ubuf = rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, DrawCall::UBUF_SIZE); + if (!ubuf->create()) + return; + float bgOpacity = 0.8f; + if (visualizer->m_visualizeMode == Visualizer::VisualizeBatches) + bgOpacity = 1.0; + QMatrix4x4 ident; + u->updateDynamicBuffer(ubuf, 0, 64, ident.constData()); // matrix + u->updateDynamicBuffer(ubuf, 64, 64, ident.constData()); // rotation + float color[4] = { 0.0f, 0.0f, 0.0f, bgOpacity }; + u->updateDynamicBuffer(ubuf, 128, 16, color); + float pattern = 0.0f; + u->updateDynamicBuffer(ubuf, 144, 4, &pattern); + qint32 projection = 0; + u->updateDynamicBuffer(ubuf, 148, 4, &projection); + } + + if (!srb) { + srb = rhi->newShaderResourceBindings(); + srb->setBindings({ QRhiShaderResourceBinding::uniformBuffer(0, ubufVisibility, ubuf) }); + if (!srb->create()) + return; + } + + if (!ps) { + ps = rhi->newGraphicsPipeline(); + ps->setTopology(QRhiGraphicsPipeline::TriangleStrip); + QRhiGraphicsPipeline::TargetBlend blend; // defaults to premul alpha, just what we need + blend.enable = true; + ps->setTargetBlends({ blend }); + ps->setShaderStages({ { QRhiShaderStage::Vertex, visualizer->m_vs }, + { QRhiShaderStage::Fragment, visualizer->m_fs } }); + QRhiVertexInputLayout inputLayout; + inputLayout.setBindings({ { 2 * sizeof(float) } }); + inputLayout.setAttributes({ { 0, 0, QRhiVertexInputAttribute::Float2, 0 } }); + ps->setVertexInputLayout(inputLayout); + ps->setShaderResourceBindings(srb); + ps->setRenderPassDescriptor(rpDesc); + if (!ps->create()) + return; + } +} + +void RhiVisualizer::Fade::releaseResources() +{ + delete ps; + ps = nullptr; + + delete srb; + srb = nullptr; + + delete ubuf; + ubuf = nullptr; + + delete vbuf; + vbuf = nullptr; +} + +void RhiVisualizer::Fade::render(QRhiCommandBuffer *cb) +{ + cb->setGraphicsPipeline(ps); + cb->setViewport(visualizer->m_renderer->m_pstate.viewport); + cb->setShaderResources(); + QRhiCommandBuffer::VertexInput vb(vbuf, 0); + cb->setVertexInput(0, 1, &vb); + cb->draw(4); +} + +static void fillVertexIndex(RhiVisualizer::DrawCall *dc, QSGGeometry *g, bool withData, bool forceUintIndex, QRhi *rhi) +{ + dc->vertex.topology = qsg_topology(g->drawingMode(), rhi); + dc->vertex.format = qsg_vertexInputFormat(g->attributes()[0]); + dc->vertex.count = g->vertexCount(); + dc->vertex.stride = g->sizeOfVertex(); + if (withData) + dc->vertex.data = g->vertexData(); + + dc->index.format = forceUintIndex ? QRhiCommandBuffer::IndexUInt32 : qsg_indexFormat(g); + dc->index.count = g->indexCount(); + dc->index.stride = forceUintIndex ? sizeof(quint32) : g->sizeOfIndex(); + if (withData && g->indexCount()) + dc->index.data = g->indexData(); +} + +static inline uint aligned(uint v, uint byteAlign) +{ + return (v + byteAlign - 1) & ~(byteAlign - 1); +} + +static bool ensureBuffer(QRhi *rhi, QRhiBuffer **buf, QRhiBuffer::UsageFlags usage, quint32 newSize) +{ + if (!*buf) { + *buf = rhi->newBuffer(QRhiBuffer::Dynamic, usage, newSize); + if (!(*buf)->create()) + return false; + } else if ((*buf)->size() < newSize) { + (*buf)->setSize(newSize); + if (!(*buf)->create()) + return false; + } + return true; +} + +QRhiGraphicsPipeline *RhiVisualizer::PipelineCache::pipeline(RhiVisualizer *visualizer, + QRhi *rhi, + QRhiShaderResourceBindings *srb, + QRhiRenderPassDescriptor *rpDesc, + QRhiGraphicsPipeline::Topology topology, + QRhiVertexInputAttribute::Format vertexFormat, + quint32 vertexStride, + bool blendOneOne) +{ + for (int i = 0, ie = pipelines.size(); i != ie; ++i) { + const Pipeline &p(pipelines.at(i)); + if (p.topology == topology && p.format == vertexFormat && p.stride == vertexStride) + return p.ps; + } + + QRhiGraphicsPipeline *ps = rhi->newGraphicsPipeline(); + ps->setTopology(topology); + QRhiGraphicsPipeline::TargetBlend blend; // premul alpha + blend.enable = true; + if (blendOneOne) { + // only for visualizing overdraw, other modes use premul alpha + blend.srcColor = QRhiGraphicsPipeline::One; + blend.dstColor = QRhiGraphicsPipeline::One; + blend.srcAlpha = QRhiGraphicsPipeline::One; + blend.dstAlpha = QRhiGraphicsPipeline::One; + } + ps->setTargetBlends({ blend }); + ps->setShaderStages({ { QRhiShaderStage::Vertex, visualizer->m_vs }, + { QRhiShaderStage::Fragment, visualizer->m_fs } }); + QRhiVertexInputLayout inputLayout; + inputLayout.setBindings({ { vertexStride } }); + inputLayout.setAttributes({ { 0, 0, vertexFormat, 0 } }); + ps->setVertexInputLayout(inputLayout); + ps->setShaderResourceBindings(srb); + ps->setRenderPassDescriptor(rpDesc); + if (!ps->create()) + return nullptr; + + Pipeline p; + p.topology = topology; + p.format = vertexFormat; + p.stride = vertexStride; + p.ps = ps; + pipelines.append(p); + + return ps; +} + +void RhiVisualizer::PipelineCache::releaseResources() +{ + for (int i = 0, ie = pipelines.size(); i != ie; ++i) + delete pipelines.at(i).ps; + + pipelines.clear(); +} + +void RhiVisualizer::ChangeVis::gather(Node *n) +{ + if (n->type() == QSGNode::GeometryNodeType && n->element()->batch && visualizer->m_visualizeChangeSet.contains(n)) { + const uint dirty = visualizer->m_visualizeChangeSet.value(n); + const bool tinted = (dirty & QSGNODE_DIRTY_PARENT) != 0; + const QColor color = QColor::fromHsvF((visualizer->m_randomGenerator.generate() & 1023) / 1023.0f, 0.3f, 1.0f).toRgb(); + const float alpha = 0.5f; + + QMatrix4x4 matrix = visualizer->m_renderer->m_current_projection_matrix[0]; + if (n->element()->batch->root) + matrix = matrix * qsg_matrixForRoot(n->element()->batch->root); + + QSGGeometryNode *gn = static_cast(n->sgNode); + matrix = matrix * *gn->matrix(); + + QSGGeometry *g = gn->geometry(); + if (g->attributeCount() >= 1) { + DrawCall dc; + memcpy(dc.uniforms.data, matrix.constData(), 64); + QMatrix4x4 rotation; + memcpy(dc.uniforms.data + 64, rotation.constData(), 64); + float c[4] = { + float(color.redF()) * alpha, + float(color.greenF()) * alpha, + float(color.blueF()) * alpha, + alpha + }; + memcpy(dc.uniforms.data + 128, c, 16); + float pattern = tinted ? 0.5f : 0.0f; + memcpy(dc.uniforms.data + 144, &pattern, 4); + qint32 projection = 0; + memcpy(dc.uniforms.data + 148, &projection, 4); + + fillVertexIndex(&dc, g, true, false, visualizer->m_renderer->m_rhi); + drawCalls.append(dc); + } + + // This is because many changes don't propegate their dirty state to the + // parent so the node updater will not unset these states. They are + // not used for anything so, unsetting it should have no side effects. + n->dirtyState = { }; + } + + SHADOWNODE_TRAVERSE(n) { + gather(child); + } +} + +void RhiVisualizer::ChangeVis::prepare(Node *n, RhiVisualizer *visualizer, + QRhi *rhi, QRhiResourceUpdateBatch *u) +{ + this->visualizer = visualizer; + + drawCalls.clear(); + gather(n); + + if (drawCalls.isEmpty()) + return; + + const int ubufAlign = rhi->ubufAlignment(); + int vbufOffset = 0; + int ibufOffset = 0; + int ubufOffset = 0; + for (RhiVisualizer::DrawCall &dc : drawCalls) { + dc.buf.vbufOffset = aligned(vbufOffset, 4); + vbufOffset = dc.buf.vbufOffset + dc.vertex.count * dc.vertex.stride; + + dc.buf.ibufOffset = aligned(ibufOffset, 4); + ibufOffset = dc.buf.ibufOffset + dc.index.count * dc.index.stride; + + dc.buf.ubufOffset = aligned(ubufOffset, ubufAlign); + ubufOffset = dc.buf.ubufOffset + DrawCall::UBUF_SIZE; + } + + ensureBuffer(rhi, &vbuf, QRhiBuffer::VertexBuffer, vbufOffset); + if (ibufOffset) + ensureBuffer(rhi, &ibuf, QRhiBuffer::IndexBuffer, ibufOffset); + const int ubufSize = ubufOffset; + ensureBuffer(rhi, &ubuf, QRhiBuffer::UniformBuffer, ubufSize); + + for (RhiVisualizer::DrawCall &dc : drawCalls) { + u->updateDynamicBuffer(vbuf, dc.buf.vbufOffset, dc.vertex.count * dc.vertex.stride, dc.vertex.data); + dc.buf.vbuf = vbuf; + if (dc.index.count) { + u->updateDynamicBuffer(ibuf, dc.buf.ibufOffset, dc.index.count * dc.index.stride, dc.index.data); + dc.buf.ibuf = ibuf; + } + u->updateDynamicBuffer(ubuf, dc.buf.ubufOffset, DrawCall::UBUF_SIZE, dc.uniforms.data); + } + + if (!srb) { + srb = rhi->newShaderResourceBindings(); + srb->setBindings({ QRhiShaderResourceBinding::uniformBufferWithDynamicOffset(0, ubufVisibility, ubuf, DrawCall::UBUF_SIZE) }); + if (!srb->create()) + return; + } +} + +void RhiVisualizer::ChangeVis::releaseResources() +{ + delete srb; + srb = nullptr; + + delete ubuf; + ubuf = nullptr; + + delete ibuf; + ibuf = nullptr; + + delete vbuf; + vbuf = nullptr; +} + +void RhiVisualizer::ChangeVis::render(QRhiCommandBuffer *cb) +{ + visualizer->recordDrawCalls(drawCalls, cb, srb); +} + +void RhiVisualizer::BatchVis::gather(Batch *b) +{ + if (b->positionAttribute != 0) + return; + + QMatrix4x4 matrix(visualizer->m_renderer->m_current_projection_matrix[0]); + if (b->root) + matrix = matrix * qsg_matrixForRoot(b->root); + + DrawCall dc; + + QMatrix4x4 rotation; + memcpy(dc.uniforms.data + 64, rotation.constData(), 64); + + const QColor color = QColor::fromHsvF((visualizer->m_randomGenerator.generate() & 1023) / 1023.0, 1.0, 1.0).toRgb(); + + float c[4] = { + float(color.redF()), + float(color.greenF()), + float(color.blueF()), + 1.0f + }; + memcpy(dc.uniforms.data + 128, c, 16); + + float pattern = b->merged ? 0.0f : 1.0f; + memcpy(dc.uniforms.data + 144, &pattern, 4); + + qint32 projection = 0; + memcpy(dc.uniforms.data + 148, &projection, 4); + + if (b->merged) { + memcpy(dc.uniforms.data, matrix.constData(), 64); + + QSGGeometryNode *gn = b->first->node; + QSGGeometry *g = gn->geometry(); + + fillVertexIndex(&dc, g, false, forceUintIndex, visualizer->m_renderer->m_rhi); + + for (int ds = 0; ds < b->drawSets.size(); ++ds) { + const DrawSet &set = b->drawSets.at(ds); + dc.buf.vbuf = b->vbo.buf; + dc.buf.vbufOffset = set.vertices; + dc.buf.ibuf = b->ibo.buf; + dc.buf.ibufOffset = set.indices; + dc.index.count = set.indexCount; + drawCalls.append(dc); + } + } else { + Element *e = b->first; + int vOffset = 0; + int iOffset = 0; + + while (e) { + QSGGeometryNode *gn = e->node; + QSGGeometry *g = gn->geometry(); + + QMatrix4x4 m = matrix * *gn->matrix(); + memcpy(dc.uniforms.data, m.constData(), 64); + + fillVertexIndex(&dc, g, false, forceUintIndex, visualizer->m_renderer->m_rhi); + + dc.buf.vbuf = b->vbo.buf; + dc.buf.vbufOffset = vOffset; + if (g->indexCount()) { + dc.buf.ibuf = b->ibo.buf; + dc.buf.ibufOffset = iOffset; + } + + drawCalls.append(dc); + + vOffset += dc.vertex.count * dc.vertex.stride; + iOffset += dc.index.count * dc.index.stride; + + e = e->nextInBatch; + } + } +} + +void RhiVisualizer::BatchVis::prepare(const QDataBuffer &opaqueBatches, const QDataBuffer &alphaBatches, + RhiVisualizer *visualizer, + QRhi *rhi, QRhiResourceUpdateBatch *u, + bool forceUintIndex) +{ + this->visualizer = visualizer; + this->forceUintIndex = forceUintIndex; + + drawCalls.clear(); + + for (int i = 0; i < opaqueBatches.size(); ++i) + gather(opaqueBatches.at(i)); + for (int i = 0; i < alphaBatches.size(); ++i) + gather(alphaBatches.at(i)); + + if (drawCalls.isEmpty()) + return; + + const int ubufAlign = rhi->ubufAlignment(); + int ubufOffset = 0; + for (RhiVisualizer::DrawCall &dc : drawCalls) { + dc.buf.ubufOffset = aligned(ubufOffset, ubufAlign); + ubufOffset = dc.buf.ubufOffset + DrawCall::UBUF_SIZE; + } + + const int ubufSize = ubufOffset; + ensureBuffer(rhi, &ubuf, QRhiBuffer::UniformBuffer, ubufSize); + + for (RhiVisualizer::DrawCall &dc : drawCalls) + u->updateDynamicBuffer(ubuf, dc.buf.ubufOffset, DrawCall::UBUF_SIZE, dc.uniforms.data); + + if (!srb) { + srb = rhi->newShaderResourceBindings(); + srb->setBindings({ QRhiShaderResourceBinding::uniformBufferWithDynamicOffset(0, ubufVisibility, ubuf, DrawCall::UBUF_SIZE) }); + if (!srb->create()) + return; + } +} + +void RhiVisualizer::BatchVis::releaseResources() +{ + delete srb; + srb = nullptr; + + delete ubuf; + ubuf = nullptr; +} + +void RhiVisualizer::BatchVis::render(QRhiCommandBuffer *cb) +{ + visualizer->recordDrawCalls(drawCalls, cb, srb); +} + +void RhiVisualizer::ClipVis::gather(QSGNode *node) +{ + if (node->type() == QSGNode::ClipNodeType) { + QSGClipNode *clipNode = static_cast(node); + QMatrix4x4 matrix = visualizer->m_renderer->m_current_projection_matrix[0]; + if (clipNode->matrix()) + matrix = matrix * *clipNode->matrix(); + + QSGGeometry *g = clipNode->geometry(); + if (g->attributeCount() >= 1) { + DrawCall dc; + memcpy(dc.uniforms.data, matrix.constData(), 64); + QMatrix4x4 rotation; + memcpy(dc.uniforms.data + 64, rotation.constData(), 64); + float c[4] = { 0.2f, 0.0f, 0.0f, 0.2f }; + memcpy(dc.uniforms.data + 128, c, 16); + float pattern = 0.5f; + memcpy(dc.uniforms.data + 144, &pattern, 4); + qint32 projection = 0; + memcpy(dc.uniforms.data + 148, &projection, 4); + fillVertexIndex(&dc, g, true, false, visualizer->m_renderer->m_rhi); + drawCalls.append(dc); + } + } + + QSGNODE_TRAVERSE(node) { + gather(child); + } +} + +void RhiVisualizer::ClipVis::prepare(QSGNode *node, RhiVisualizer *visualizer, + QRhi *rhi, QRhiResourceUpdateBatch *u) +{ + this->visualizer = visualizer; + + drawCalls.clear(); + gather(node); + + if (drawCalls.isEmpty()) + return; + + const int ubufAlign = rhi->ubufAlignment(); + int vbufOffset = 0; + int ibufOffset = 0; + int ubufOffset = 0; + for (RhiVisualizer::DrawCall &dc : drawCalls) { + dc.buf.vbufOffset = aligned(vbufOffset, 4); + vbufOffset = dc.buf.vbufOffset + dc.vertex.count * dc.vertex.stride; + + dc.buf.ibufOffset = aligned(ibufOffset, 4); + ibufOffset = dc.buf.ibufOffset + dc.index.count * dc.index.stride; + + dc.buf.ubufOffset = aligned(ubufOffset, ubufAlign); + ubufOffset = dc.buf.ubufOffset + DrawCall::UBUF_SIZE; + } + + ensureBuffer(rhi, &vbuf, QRhiBuffer::VertexBuffer, vbufOffset); + if (ibufOffset) + ensureBuffer(rhi, &ibuf, QRhiBuffer::IndexBuffer, ibufOffset); + const int ubufSize = ubufOffset; + ensureBuffer(rhi, &ubuf, QRhiBuffer::UniformBuffer, ubufSize); + + for (RhiVisualizer::DrawCall &dc : drawCalls) { + u->updateDynamicBuffer(vbuf, dc.buf.vbufOffset, dc.vertex.count * dc.vertex.stride, dc.vertex.data); + dc.buf.vbuf = vbuf; + if (dc.index.count) { + u->updateDynamicBuffer(ibuf, dc.buf.ibufOffset, dc.index.count * dc.index.stride, dc.index.data); + dc.buf.ibuf = ibuf; + } + u->updateDynamicBuffer(ubuf, dc.buf.ubufOffset, DrawCall::UBUF_SIZE, dc.uniforms.data); + } + + if (!srb) { + srb = rhi->newShaderResourceBindings(); + srb->setBindings({ QRhiShaderResourceBinding::uniformBufferWithDynamicOffset(0, ubufVisibility, ubuf, DrawCall::UBUF_SIZE) }); + if (!srb->create()) + return; + } +} + +void RhiVisualizer::ClipVis::releaseResources() +{ + delete srb; + srb = nullptr; + + delete ubuf; + ubuf = nullptr; + + delete ibuf; + ibuf = nullptr; + + delete vbuf; + vbuf = nullptr; +} + +void RhiVisualizer::ClipVis::render(QRhiCommandBuffer *cb) +{ + visualizer->recordDrawCalls(drawCalls, cb, srb); +} + +void RhiVisualizer::OverdrawVis::gather(Node *n) +{ + if (n->type() == QSGNode::GeometryNodeType && n->element()->batch) { + QMatrix4x4 matrix = visualizer->m_renderer->m_current_projection_matrix[0]; + matrix(2, 2) = visualizer->m_renderer->m_zRange; + matrix(2, 3) = 1.0f - n->element()->order * visualizer->m_renderer->m_zRange; + + if (n->element()->batch->root) + matrix = matrix * qsg_matrixForRoot(n->element()->batch->root); + + QSGGeometryNode *gn = static_cast(n->sgNode); + matrix = matrix * *gn->matrix(); + + QSGGeometry *g = gn->geometry(); + if (g->attributeCount() >= 1) { + DrawCall dc; + memcpy(dc.uniforms.data, matrix.constData(), 64); + memcpy(dc.uniforms.data + 64, rotation.constData(), 64); + + float c[4]; + const float ca = 0.33f; + if (n->element()->batch->isOpaque) { + c[0] = ca * 0.3f; c[1] = ca * 1.0f; c[2] = ca * 0.3f; c[3] = ca; + } else { + c[0] = ca * 1.0f; c[1] = ca * 0.3f; c[2] = ca * 0.3f; c[3] = ca; + } + memcpy(dc.uniforms.data + 128, c, 16); + float pattern = 0.0f; + memcpy(dc.uniforms.data + 144, &pattern, 4); + qint32 projection = 1; + memcpy(dc.uniforms.data + 148, &projection, 4); + + fillVertexIndex(&dc, g, true, false, visualizer->m_renderer->m_rhi); + drawCalls.append(dc); + } + } + + SHADOWNODE_TRAVERSE(n) { + gather(child); + } +} + +void RhiVisualizer::OverdrawVis::prepare(Node *n, RhiVisualizer *visualizer, + QRhi *rhi, QRhiResourceUpdateBatch *u) +{ + this->visualizer = visualizer; + + step += float(M_PI * 2 / 1000.0); + if (step > float(M_PI * 2)) + step = 0.0f; + + const float yfix = rhi->isYUpInNDC() ? 1.0f : -1.0f; + rotation.setToIdentity(); + rotation.translate(0.0f, 0.5f * yfix, 4.0f); + rotation.scale(2.0f, 2.0f, 1.0f); + rotation.rotate(-30.0f * yfix, 1.0f, 0.0f, 0.0f); + rotation.rotate(80.0f * std::sin(step), 0.0f, 1.0f, 0.0f); + rotation.translate(0.0f, 0.0f, -1.0f); + + drawCalls.clear(); + gather(n); + + if (!box.vbuf) { + const float v[] = { + // lower + -1, 1, 0, 1, 1, 0, + -1, 1, 0, -1, -1, 0, + 1, 1, 0, 1, -1, 0, + -1, -1, 0, 1, -1, 0, + + // upper + -1, 1, 1, 1, 1, 1, + -1, 1, 1, -1, -1, 1, + 1, 1, 1, 1, -1, 1, + -1, -1, 1, 1, -1, 1, + + // sides + -1, -1, 0, -1, -1, 1, + 1, -1, 0, 1, -1, 1, + -1, 1, 0, -1, 1, 1, + 1, 1, 0, 1, 1, 1 + }; + box.vbuf = rhi->newBuffer(QRhiBuffer::Immutable, QRhiBuffer::VertexBuffer, sizeof(v)); + if (!box.vbuf->create()) + return; + u->uploadStaticBuffer(box.vbuf, v); + } + + if (!box.ubuf) { + box.ubuf = rhi->newBuffer(QRhiBuffer::Dynamic, QRhiBuffer::UniformBuffer, DrawCall::UBUF_SIZE); + if (!box.ubuf->create()) + return; + QMatrix4x4 ident; + u->updateDynamicBuffer(box.ubuf, 0, 64, ident.constData()); + float color[4] = { 0.5f, 0.5f, 1.0f, 1.0f }; + u->updateDynamicBuffer(box.ubuf, 128, 16, color); + float pattern = 0.0f; + u->updateDynamicBuffer(box.ubuf, 144, 4, &pattern); + qint32 projection = 1; + u->updateDynamicBuffer(box.ubuf, 148, 4, &projection); + } + + u->updateDynamicBuffer(box.ubuf, 64, 64, rotation.constData()); + + if (!box.srb) { + box.srb = rhi->newShaderResourceBindings(); + box.srb->setBindings({ QRhiShaderResourceBinding::uniformBuffer(0, ubufVisibility, box.ubuf) }); + if (!box.srb->create()) + return; + } + + if (!box.ps) { + box.ps = rhi->newGraphicsPipeline(); + box.ps->setTopology(QRhiGraphicsPipeline::Lines); + box.ps->setLineWidth(2); // may be be ignored (D3D, Metal), but may be used on GL and Vulkan + QRhiGraphicsPipeline::TargetBlend blend; + blend.enable = true; + blend.srcColor = QRhiGraphicsPipeline::One; + blend.dstColor = QRhiGraphicsPipeline::One; + blend.srcAlpha = QRhiGraphicsPipeline::One; + blend.dstAlpha = QRhiGraphicsPipeline::One; + box.ps->setTargetBlends({ blend }); + box.ps->setShaderStages({ { QRhiShaderStage::Vertex, visualizer->m_vs }, + { QRhiShaderStage::Fragment, visualizer->m_fs } }); + QRhiVertexInputLayout inputLayout; + inputLayout.setBindings({ { 3 * sizeof(float) } }); + inputLayout.setAttributes({ { 0, 0, QRhiVertexInputAttribute::Float3, 0 } }); + box.ps->setVertexInputLayout(inputLayout); + box.ps->setShaderResourceBindings(box.srb); + box.ps->setRenderPassDescriptor(visualizer->m_renderer->renderTarget().rpDesc); + if (!box.ps->create()) + return; + } + + if (drawCalls.isEmpty()) + return; + + const int ubufAlign = rhi->ubufAlignment(); + int vbufOffset = 0; + int ibufOffset = 0; + int ubufOffset = 0; + for (RhiVisualizer::DrawCall &dc : drawCalls) { + dc.buf.vbufOffset = aligned(vbufOffset, 4); + vbufOffset = dc.buf.vbufOffset + dc.vertex.count * dc.vertex.stride; + + dc.buf.ibufOffset = aligned(ibufOffset, 4); + ibufOffset = dc.buf.ibufOffset + dc.index.count * dc.index.stride; + + dc.buf.ubufOffset = aligned(ubufOffset, ubufAlign); + ubufOffset = dc.buf.ubufOffset + DrawCall::UBUF_SIZE; + } + + ensureBuffer(rhi, &vbuf, QRhiBuffer::VertexBuffer, vbufOffset); + if (ibufOffset) + ensureBuffer(rhi, &ibuf, QRhiBuffer::IndexBuffer, ibufOffset); + const int ubufSize = ubufOffset; + ensureBuffer(rhi, &ubuf, QRhiBuffer::UniformBuffer, ubufSize); + + for (RhiVisualizer::DrawCall &dc : drawCalls) { + u->updateDynamicBuffer(vbuf, dc.buf.vbufOffset, dc.vertex.count * dc.vertex.stride, dc.vertex.data); + dc.buf.vbuf = vbuf; + if (dc.index.count) { + u->updateDynamicBuffer(ibuf, dc.buf.ibufOffset, dc.index.count * dc.index.stride, dc.index.data); + dc.buf.ibuf = ibuf; + } + u->updateDynamicBuffer(ubuf, dc.buf.ubufOffset, DrawCall::UBUF_SIZE, dc.uniforms.data); + } + + if (!srb) { + srb = rhi->newShaderResourceBindings(); + srb->setBindings({ QRhiShaderResourceBinding::uniformBufferWithDynamicOffset(0, ubufVisibility, ubuf, DrawCall::UBUF_SIZE) }); + if (!srb->create()) + return; + } +} + +void RhiVisualizer::OverdrawVis::releaseResources() +{ + delete srb; + srb = nullptr; + + delete ubuf; + ubuf = nullptr; + + delete ibuf; + ibuf = nullptr; + + delete vbuf; + vbuf = nullptr; + + delete box.ps; + box.ps = nullptr; + + delete box.srb; + box.srb = nullptr; + + delete box.ubuf; + box.ubuf = nullptr; + + delete box.vbuf; + box.vbuf = nullptr; +} + +void RhiVisualizer::OverdrawVis::render(QRhiCommandBuffer *cb) +{ + cb->setGraphicsPipeline(box.ps); + cb->setShaderResources(); + QRhiCommandBuffer::VertexInput vb(box.vbuf, 0); + cb->setVertexInput(0, 1, &vb); + cb->draw(24); + + visualizer->recordDrawCalls(drawCalls, cb, srb, true); +} + +} + +QT_END_NAMESPACE diff --git a/waylib/src/server/qtquick/scenegraph/wsgrhivisualizer_p.h b/waylib/src/server/qtquick/scenegraph/wsgrhivisualizer_p.h new file mode 100644 index 0000000000..26290b570e --- /dev/null +++ b/waylib/src/server/qtquick/scenegraph/wsgrhivisualizer_p.h @@ -0,0 +1,201 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// Copyright (C) 2016 Jolla Ltd, author: +// Copyright (C) 2016 Robin Burchell +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef WSGRHIVISUALIZER_P_H +#define WSGRHIVISUALIZER_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "wsgbatchrenderer_p.h" + +#include + +QT_BEGIN_NAMESPACE + +namespace WSGBatchRenderer +{ + +class RhiVisualizer : public Visualizer +{ +public: + RhiVisualizer(Renderer *renderer); + ~RhiVisualizer(); + + void prepareVisualize() override; + void visualize() override; + + void releaseResources() override; + + struct DrawCall + { + static const int UBUF_SIZE = 152; // visualization.vert/frag + struct { + char data[UBUF_SIZE]; // matrix, rotation, color, pattern, projection + } uniforms; + struct { + QRhiGraphicsPipeline::Topology topology; + QRhiVertexInputAttribute::Format format; + int count; + int stride; + const void *data; // only when using own vbuf + } vertex; + struct { + QRhiCommandBuffer::IndexFormat format; + int count; + int stride; + const void *data; // only when using own ibuf + } index; + struct { + QRhiBuffer *vbuf; // either same for all draw calls and owned by the *Vis, or points to a Batch.Buffer.vbo.buf + int vbufOffset; + QRhiBuffer *ibuf; // same, but for index + int ibufOffset; + int ubufOffset; + } buf; + }; + +private: + QShader m_vs; + QShader m_fs; + + void recordDrawCalls(const QList &drawCalls, + QRhiCommandBuffer *cb, + QRhiShaderResourceBindings *srb, + bool blendOneOne = false); + + class PipelineCache { + public: + QRhiGraphicsPipeline *pipeline(RhiVisualizer *visualizer, + QRhi *rhi, + QRhiShaderResourceBindings *srb, + QRhiRenderPassDescriptor *rpDesc, + QRhiGraphicsPipeline::Topology topology, + QRhiVertexInputAttribute::Format vertexFormat, + quint32 vertexStride, + bool blendOneOne); + void releaseResources(); + private: + struct Pipeline { + QRhiGraphicsPipeline::Topology topology; + QRhiVertexInputAttribute::Format format; + quint32 stride; + QRhiGraphicsPipeline *ps; + }; + QVarLengthArray pipelines; + }; + + PipelineCache m_pipelines; + + class Fade { + public: + void prepare(RhiVisualizer *visualizer, + QRhi *rhi, QRhiResourceUpdateBatch *u, QRhiRenderPassDescriptor *rpDesc); + void releaseResources(); + void render(QRhiCommandBuffer *cb); + private: + RhiVisualizer *visualizer; + QRhiBuffer *vbuf = nullptr; + QRhiBuffer *ubuf = nullptr; + QRhiGraphicsPipeline *ps = nullptr; + QRhiShaderResourceBindings *srb = nullptr; + } m_fade; + + class ChangeVis { + public: + void prepare(Node *n, RhiVisualizer *visualizer, + QRhi *rhi, QRhiResourceUpdateBatch *u); + void releaseResources(); + void render(QRhiCommandBuffer *cb); + private: + void gather(Node *n); + RhiVisualizer *visualizer; + QList drawCalls; + QRhiBuffer *vbuf = nullptr; + QRhiBuffer *ibuf = nullptr; + QRhiBuffer *ubuf = nullptr; + QRhiShaderResourceBindings *srb = nullptr; + } m_changeVis; + + class BatchVis { + public: + void prepare(const QDataBuffer &opaqueBatches, + const QDataBuffer &alphaBatches, + RhiVisualizer *visualizer, + QRhi *rhi, QRhiResourceUpdateBatch *u, + bool forceUintIndex); + void releaseResources(); + void render(QRhiCommandBuffer *cb); + private: + void gather(Batch *b); + RhiVisualizer *visualizer; + bool forceUintIndex; + QList drawCalls; + QRhiBuffer *ubuf = nullptr; + QRhiShaderResourceBindings *srb = nullptr; + } m_batchVis; + + class ClipVis { + public: + void prepare(QSGNode *node, RhiVisualizer *visualizer, + QRhi *rhi, QRhiResourceUpdateBatch *u); + void releaseResources(); + void render(QRhiCommandBuffer *cb); + private: + void gather(QSGNode *node); + RhiVisualizer *visualizer; + QList drawCalls; + QRhiBuffer *vbuf = nullptr; + QRhiBuffer *ibuf = nullptr; + QRhiBuffer *ubuf = nullptr; + QRhiShaderResourceBindings *srb = nullptr; + } m_clipVis; + + class OverdrawVis { + public: + void prepare(Node *n, RhiVisualizer *visualizer, + QRhi *rhi, QRhiResourceUpdateBatch *u); + void releaseResources(); + void render(QRhiCommandBuffer *cb); + private: + void gather(Node *n); + RhiVisualizer *visualizer; + QList drawCalls; + QRhiBuffer *vbuf = nullptr; + QRhiBuffer *ibuf = nullptr; + QRhiBuffer *ubuf = nullptr; + QRhiShaderResourceBindings *srb = nullptr; + float step = 0.0f; + QMatrix4x4 rotation; + struct { + QRhiBuffer *vbuf = nullptr; + QRhiBuffer *ubuf = nullptr; + QRhiShaderResourceBindings *srb = nullptr; + QRhiGraphicsPipeline *ps = nullptr; + } box; + } m_overdrawVis; + + QRandomGenerator m_randomGenerator; + + friend class Fade; + friend class PipelineCache; + friend class ChangeVis; + friend class ClipVis; + friend class OverdrawVis; +}; + +} // namespace WSGBatchRenderer + +QT_END_NAMESPACE + +#endif // WSGRHIVISUALIZER_P_H diff --git a/waylib/src/server/qtquick/wbufferitem.cpp b/waylib/src/server/qtquick/wbufferitem.cpp new file mode 100644 index 0000000000..f539c85016 --- /dev/null +++ b/waylib/src/server/qtquick/wbufferitem.cpp @@ -0,0 +1,198 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wbufferitem.h" +#include + +#include "woutputrenderwindow.h" +#include "wsgtextureprovider.h" +#include "wayliblogging.h" + +#include + +#include +#include +#include +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class Q_DECL_HIDDEN WBufferItemPrivate : public QQuickItemPrivate +{ +public: + explicit WBufferItemPrivate(WBufferItem *) {} + + void cleanTextureProvider() + { + if (textureProvider) { + delete textureProvider; + textureProvider = nullptr; + } + } + + W_DECLARE_PUBLIC(WBufferItem) + mutable WSGTextureProvider *textureProvider = nullptr; + WBufferUnlockPtr buffer; +}; + +WBufferItem::WBufferItem(QQuickItem *parent) + : QQuickItem(*new WBufferItemPrivate(this), parent) +{ + setFlag(QQuickItem::ItemHasContents, true); +} + +WBufferItem::~WBufferItem() +{ + W_D(WBufferItem); + // `d->window` will become nullptr in ~QQuickItem; delete provider here. + d->cleanTextureProvider(); +} + +bool WBufferItem::isTextureProvider() const +{ + return true; +} + +QSGTextureProvider *WBufferItem::textureProvider() const +{ + if (QQuickItem::isTextureProvider()) + return QQuickItem::textureProvider(); + + return wTextureProvider(); +} + +WSGTextureProvider *WBufferItem::wTextureProvider() const +{ + W_DC(WBufferItem); + + auto w = qobject_cast(d->window); + if (!w || !d->sceneGraphRenderContext() || QThread::currentThread() != d->sceneGraphRenderContext()->thread()) { + qCWarning(lcWlBufferItem) + << "WBufferItem::wTextureProvider can only be queried on the rendering thread of a WOutputRenderWindow"; + return nullptr; + } + + if (!d->textureProvider) { + d->textureProvider = new WSGTextureProvider(w); + d->textureProvider->setSmooth(smooth()); + connect(this, &WBufferItem::smoothChanged, + d->textureProvider, &WSGTextureProvider::setSmooth); + d->textureProvider->setBuffer(d->buffer.get()); + } + return d->textureProvider; +} + +WOutputRenderWindow *WBufferItem::outputRenderWindow() const +{ + return qobject_cast(window()); +} + +wlr_buffer *WBufferItem::buffer() const +{ + W_DC(WBufferItem); + return d->buffer.get(); +} + +void WBufferItem::setBuffer(wlr_buffer *buffer) +{ + W_D(WBufferItem); + + if (d->buffer.get() == buffer) + return; + + // Validate buffer basic attributes before locking to avoid holding unusable buffers. + if (buffer) { + auto *h = buffer; + if (!h || h->width <= 0 || h->height <= 0) { + qCWarning(lcWlBufferItem) << "Reject buffer with invalid size or handle" + << buffer << "w" << (h ? h->width : -1) + << "h" << (h ? h->height : -1); + return; + } + } + + if (buffer) + wlr_buffer_lock(buffer); + + d->buffer.reset(buffer); + + if (d->textureProvider) + d->textureProvider->setBuffer(d->buffer.get()); + + update(); + Q_EMIT bufferChanged(); +} + +void WBufferItem::componentComplete() +{ + QQuickItem::componentComplete(); +} + +QSGNode *WBufferItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) +{ + W_D(WBufferItem); + + auto tp = wTextureProvider(); + if (!tp) { + qCWarning(lcWlBufferItem) << "wTextureProvider() is nullptr"; + return nullptr; + } + + // Refresh provider with the latest buffer. + tp->setBuffer(d->buffer.get()); + + if (!tp->texture() || width() <= 0 || height() <= 0) { + int bufW = -1; + int bufH = -1; + if (auto *buf = d->buffer.get()) { + if (auto *h = buf) { + bufW = h->width; + bufH = h->height; + } + } + qCWarning(lcWlBufferItem) << "texture missing or item size invalid" + << "buffer" << d->buffer.get() + << "bufW" << bufW + << "bufH" << bufH + << "itemW" << width() << "itemH" << height(); + delete oldNode; + return nullptr; + } + + auto node = static_cast(oldNode); + if (Q_UNLIKELY(!node)) { + node = window()->createImageNode(); + node->setOwnsTexture(false); + } + + auto texture = tp->texture(); + qCDebug(lcWlBufferItem) << "updatePaintNode" << "texSize" << texture->textureSize() + << "itemSize" << size(); + node->setTexture(texture); + node->setSourceRect(QRectF(QPointF(), texture->textureSize())); + node->setRect(QRectF(QPointF(), size())); + node->setFiltering(smooth() ? QSGTexture::Linear : QSGTexture::Nearest); + + return node; +} + +void WBufferItem::releaseResources() +{ + W_D(WBufferItem); + + d->cleanTextureProvider(); + // Keep last buffer cached; just force content dirty to avoid stale nodes. + // Only mark dirty if we have a valid window to avoid crashes during window destruction + if (window()) { + QQuickItemPrivate::get(this)->dirty(QQuickItemPrivate::Content); + } +} + +void WBufferItem::invalidateSceneGraph() +{ + W_D(WBufferItem); + delete d->textureProvider; // safe on nullptr + d->textureProvider = nullptr; +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/qtquick/wbufferitem.h b/waylib/src/server/qtquick/wbufferitem.h new file mode 100644 index 0000000000..0e7090c0cd --- /dev/null +++ b/waylib/src/server/qtquick/wbufferitem.h @@ -0,0 +1,58 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include + +#include +#include + +QT_BEGIN_NAMESPACE +class QSGTextureProvider; +QT_END_NAMESPACE + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WBufferItemPrivate; +class WSGTextureProvider; +class WOutputRenderWindow; + +// Minimal buffer-backed item: accepts a wlr_buffer and renders it; always keeps the last buffer. +class WAYLIB_SERVER_EXPORT WBufferItem : public QQuickItem, public virtual WTextureProviderProvider +{ + Q_OBJECT + Q_DECLARE_PRIVATE(WBufferItem) + Q_PROPERTY(wlr_buffer* buffer READ buffer WRITE setBuffer NOTIFY bufferChanged FINAL) + QML_NAMED_ELEMENT(BufferItem) + +public: + explicit WBufferItem(QQuickItem *parent = nullptr); + ~WBufferItem() override; + + wlr_buffer *buffer() const; + void setBuffer(wlr_buffer *buffer); + + bool isTextureProvider() const override; + QSGTextureProvider *textureProvider() const override; + WSGTextureProvider *wTextureProvider() const override; + WOutputRenderWindow *outputRenderWindow() const override; + +Q_SIGNALS: + void bufferChanged(); + +private: + friend class WSGTextureProvider; + + void componentComplete() override; + QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data) override; + void releaseResources() override; + Q_SLOT void invalidateSceneGraph(); +}; + +WAYLIB_SERVER_END_NAMESPACE + +Q_DECLARE_METATYPE(WAYLIB_SERVER_NAMESPACE::WBufferItem*) +Q_DECLARE_OPAQUE_POINTER(wlr_buffer*) diff --git a/waylib/src/server/qtquick/wlayersurfaceitem.cpp b/waylib/src/server/qtquick/wlayersurfaceitem.cpp index 2700606ecc..96b2b64b80 100644 --- a/waylib/src/server/qtquick/wlayersurfaceitem.cpp +++ b/waylib/src/server/qtquick/wlayersurfaceitem.cpp @@ -22,7 +22,7 @@ WLayerSurface *WLayerSurfaceItem::layerSurface() const { return qobject_cast(shellSurface()); } -inline static int32_t getValidSize(int32_t size, int32_t fallback) { +[[maybe_unused]] inline static int32_t getValidSize(int32_t size, int32_t fallback) { return size > 0 ? size : fallback; } @@ -35,7 +35,7 @@ void WLayerSurfaceItem::initSurface() { WSurfaceItem::initSurface(); Q_ASSERT(layerSurface()); - connect(layerSurface(), &WWrapObject::aboutToBeInvalidated, + connect(layerSurface(), &WToplevelSurface::beforeDestroy, this, &WLayerSurfaceItem::releaseResources); } diff --git a/waylib/src/server/qtquick/woutputhelper.cpp b/waylib/src/server/qtquick/woutputhelper.cpp index 0aa7b676b9..55fa7a4556 100644 --- a/waylib/src/server/qtquick/woutputhelper.cpp +++ b/waylib/src/server/qtquick/woutputhelper.cpp @@ -1,17 +1,14 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "woutputhelper.h" +#include "wayliblogging.h" #include "wrenderhelper.h" #include "woutput.h" #include "platformplugin/types.h" #include "private/wglobal_p.h" -#include -#include -#include -#include -#include +#include #include #include @@ -24,19 +21,16 @@ #endif #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WOutputHelperPrivate : public WObjectPrivate { public: - WOutputHelperPrivate(WOutput *output, WOutputHelper *qq, bool r/* renderable */, bool c /*contentIsDirty*/, bool n/*needsFrame*/) + WOutputHelperPrivate(WOutput *output, WOutputHelper *qq, bool c /*contentIsDirty*/) : WObjectPrivate(qq) , output(output) , outputWindow(new QW::Window) - , renderable(r) , contentIsDirty(c) - , needsFrame(n) { wlr_output_state_init(&state); @@ -44,17 +38,11 @@ class Q_DECL_HIDDEN WOutputHelperPrivate : public WObjectPrivate outputWindow->setScreen(QWlrootsIntegration::instance()->getScreenFrom(output)->screen()); outputWindow->create(); - output->safeConnect(&qw_output::notify_frame, qq, [this] { - on_frame(); - }); - output->safeConnect(&qw_output::notify_needs_frame, qq, [this] { - setNeedsFrame(true); - qwoutput()->qw_output::schedule_frame(); - }); - output->safeConnect(&qw_output::notify_damage, qq, [this] { - on_damage(); - }); - output->safeConnect(&WOutput::modeChanged, qq, [this] { + // In wlroots, damage is triggered after a cursor move. + // However, Waylib uses a custom cursor instead of having wlroots render it. + // So, we don't need to listen to the damage signal." + // (damage handled via wlr_output events.damage listener) + QObject::connect(output, &WOutput::modeChanged, qq, [this] { if (renderHelper) renderHelper->setSize(this->output->size()); }, Qt::QueuedConnection); // reset buffer on later, because it's rendering @@ -64,11 +52,11 @@ class Q_DECL_HIDDEN WOutputHelperPrivate : public WObjectPrivate wlr_output_state_finish(&state); } - inline qw_output *qwoutput() const { + inline wlr_output *qwoutput() const { return output->handle(); } - inline qw_renderer *renderer() const { + inline wlr_renderer *renderer() const { return output->renderer(); } @@ -76,18 +64,13 @@ class Q_DECL_HIDDEN WOutputHelperPrivate : public WObjectPrivate return static_cast(outputWindow->handle()); } - void setRenderable(bool newValue); void setContentIsDirty(bool newValue); - void setNeedsFrame(bool newNeedsFrame); - void on_frame(); - void on_damage(); - - qw_buffer *acquireBuffer(wlr_swapchain **sc); + wlr_buffer *acquireBuffer(wlr_swapchain **sc); inline void update() { setContentIsDirty(true); - qwoutput()->schedule_frame(); + wlr_output_schedule_frame(qwoutput()); } W_DECLARE_PUBLIC(WOutputHelper) @@ -97,18 +80,17 @@ class Q_DECL_HIDDEN WOutputHelperPrivate : public WObjectPrivate QWindow *outputWindow; WRenderHelper *renderHelper = nullptr; - uint renderable:1; uint contentIsDirty:1; - uint needsFrame:1; -}; -void WOutputHelperPrivate::setRenderable(bool newValue) -{ - if (renderable == newValue) - return; - renderable = newValue; - Q_EMIT q_func()->renderableChanged(); -} + struct CommitJobEntry { + std::function jobWithState; + }; + QList beforeCommitJobs; + QList afterCommitJobs; + + // External state (mode/scale/transform/enabled) separate from internal (buffer/damage) + WOutputHelper::ExtraState extraState; +}; void WOutputHelperPrivate::setContentIsDirty(bool newValue) { @@ -118,43 +100,22 @@ void WOutputHelperPrivate::setContentIsDirty(bool newValue) Q_EMIT q_func()->contentIsDirtyChanged(); } -void WOutputHelperPrivate::setNeedsFrame(bool newNeedsFrame) -{ - if (needsFrame == newNeedsFrame) - return; - needsFrame = newNeedsFrame; - Q_EMIT q_func()->needsFrameChanged(); -} - -void WOutputHelperPrivate::on_frame() +wlr_buffer *WOutputHelperPrivate::acquireBuffer(wlr_swapchain **sc) { - setRenderable(true); - Q_EMIT q_func()->requestRender(); -} - -void WOutputHelperPrivate::on_damage() -{ - setContentIsDirty(true); - Q_EMIT q_func()->damaged(); -} - -qw_buffer *WOutputHelperPrivate::acquireBuffer(wlr_swapchain **sc) -{ - bool ok = qwoutput()->configure_primary_swapchain(&state, sc); + bool ok = wlr_output_configure_primary_swapchain(qwoutput(), &state, sc); if (!ok) return nullptr; - auto newBuffer = qw_swapchain::from(*sc)->acquire(); - return newBuffer ? qw_buffer::from(newBuffer) : nullptr; + return wlr_swapchain_acquire(*sc); } -WOutputHelper::WOutputHelper(WOutput *output, bool renderable, bool contentIsDirty, bool needsFrame, QObject *parent) +WOutputHelper::WOutputHelper(WOutput *output, bool contentIsDirty, QObject *parent) : QObject(parent) - , WObject(*new WOutputHelperPrivate(output, this, renderable, contentIsDirty, needsFrame)) + , WObject(*new WOutputHelperPrivate(output, this, contentIsDirty)) { } WOutputHelper::WOutputHelper(WOutput *output, QObject *parent) - : WOutputHelper(output, false, false, false, parent) + : WOutputHelper(output, true, parent) { } @@ -171,12 +132,12 @@ QWindow *WOutputHelper::outputWindow() const return d->outputWindow; } -std::pair WOutputHelper::acquireRenderTarget(QQuickRenderControl *rc, - wlr_swapchain **swapchain) +WRenderHelper::RenderTarget WOutputHelper::acquireRenderTarget(QQuickRenderControl *rc, + wlr_swapchain **swapchain) { W_D(WOutputHelper); - qw_buffer *buffer = d->acquireBuffer(swapchain ? swapchain : &d->qwoutput()->handle()->swapchain); + wlr_buffer *buffer = d->acquireBuffer(swapchain ? swapchain : &d->qwoutput()->swapchain); if (!buffer) return {}; @@ -186,44 +147,32 @@ std::pair WOutputHelper::acquireRenderTarget(QQ } auto rt = d->renderHelper->acquireRenderTarget(rc, buffer); if (rt.isNull()) { - buffer->unlock(); + wlr_buffer_unlock(buffer); return {}; } - return {buffer, rt}; + return rt; } -std::pair WOutputHelper::lastRenderTarget() +WRenderHelper::RenderTarget WOutputHelper::lastRenderTarget() { W_DC(WOutputHelper); if (!d->renderHelper) - return {nullptr, {}}; + return {}; return d->renderHelper->lastRenderTarget(); } -void WOutputHelper::setBuffer(qw_buffer *buffer) +void WOutputHelper::setBuffer(wlr_buffer *buffer) { W_D(WOutputHelper); - wlr_output_state_set_buffer(&d->state, buffer->handle()); + wlr_output_state_set_buffer(&d->state, buffer); } -qw_buffer *WOutputHelper::buffer() const +wlr_buffer *WOutputHelper::buffer() const { W_DC(WOutputHelper); - return d->state.buffer ? qw_buffer::from(d->state.buffer) : nullptr; -} - -void WOutputHelper::setScale(float scale) -{ - W_D(WOutputHelper); - wlr_output_state_set_scale(&d->state, scale); -} - -void WOutputHelper::setTransform(WOutput::Transform t) -{ - W_D(WOutputHelper); - wlr_output_state_set_transform(&d->state, static_cast(t)); + return d->state.buffer; } void WOutputHelper::setDamage(const pixman_region32 *damage) @@ -255,43 +204,122 @@ void WOutputHelper::setLayers(const wlr_output_layer_state_array &layers) bool WOutputHelper::commit() { W_D(WOutputHelper); + + // Execute before-commit jobs + QList beforeJobs; + beforeJobs.swap(d->beforeCommitJobs); + for (const auto &entry : beforeJobs) { + entry.jobWithState(true, d->extraState); + } + wlr_output_state state = d->state; wlr_output_state_init(&d->state); - bool ok = d->qwoutput()->commit_state(&state); + + if (Q_UNLIKELY(d->extraState)) { + // State-only commit: Use only extraState (no buffer/damage from internal state) + // Finish the internal state as we're not using it + wlr_output_state_finish(&state); + wlr_output_state_copy(&state, d->extraState.get()); + } + + bool ok = wlr_output_commit_state(d->qwoutput(), &state); + if (!ok) { + qCCritical(lcWlOutputHelper, "commit failed on output %s", d->qwoutput()->name); + } wlr_output_state_finish(&state); + ExtraState committedExtraState = d->extraState; + + if (Q_UNLIKELY(d->extraState)) { + d->extraState.reset(); + } + QList afterJobs; + afterJobs.swap(d->afterCommitJobs); + for (const auto &entry : afterJobs) { + entry.jobWithState(ok, committedExtraState); + } return ok; } -bool WOutputHelper::testCommit() +void WOutputHelper::scheduleCommitJob(CommitJobWithState job, CommitStage stage) { W_D(WOutputHelper); - return d->qwoutput()->test_state(&d->state); + WOutputHelperPrivate::CommitJobEntry entry; + entry.jobWithState = job; + + if (stage == BeforeCommitStage) { + d->beforeCommitJobs.append(entry); + } else { + d->afterCommitJobs.append(entry); + } } -bool WOutputHelper::testCommit(qw_buffer *buffer, const wlr_output_layer_state_array &layers) +bool WOutputHelper::setExtraState(ExtraState state) { W_D(WOutputHelper); - wlr_output_state state = d->state; - if (buffer) - wlr_output_state_set_buffer(&state, buffer->handle()); - if (!layers.isEmpty()) - wlr_output_state_set_layers(&state, const_cast(layers.data()), layers.length()); + if (!state) { + d->extraState.reset(); + return true; + } - bool ok = d->qwoutput()->test_state(&state); - if (state.committed & WLR_OUTPUT_STATE_BUFFER) { - Q_ASSERT(buffer); - buffer->unlock(); + // Only allow specific state flags for external configuration + const uint32_t allowedFlags = WLR_OUTPUT_STATE_MODE | + WLR_OUTPUT_STATE_SCALE | + WLR_OUTPUT_STATE_TRANSFORM | + WLR_OUTPUT_STATE_ENABLED | + WLR_OUTPUT_STATE_ADAPTIVE_SYNC_ENABLED | + WLR_OUTPUT_STATE_COLOR_TRANSFORM; + + if (state->committed & ~allowedFlags) { + qCWarning(lcWlOutputHelper) << "WOutputHelper::setExtraState: contains unsupported flags:" + << Qt::hex << (state->committed & ~allowedFlags); + return false; } - return ok; + if ((state->committed & allowedFlags) == 0) { + qCWarning(lcWlOutputHelper) << "WOutputHelper::setExtraState: no valid state changes"; + return false; + } + + d->extraState = state; + return true; } -bool WOutputHelper::renderable() const +WOutputHelper::ExtraState WOutputHelper::extraState() const { W_DC(WOutputHelper); - return d->renderable; + return d->extraState; +} + +bool WOutputHelper::testCommit() +{ + W_D(WOutputHelper); + return wlr_output_test_state(d->qwoutput(), &d->state); +} + +bool WOutputHelper::testCommit(wlr_buffer *buffer, const wlr_output_layer_state_array &layers) +{ + W_D(WOutputHelper); + // Deep-copy: a shallow assign would share gamma_lut / other heap fields + // with d->state, and set_buffer() could unlock a buffer still owned by + // the helper's pending state. + wlr_output_state state; + wlr_output_state_init(&state); + if (!wlr_output_state_copy(&state, &d->state)) { + wlr_output_state_finish(&state); + return false; + } + + if (buffer) + wlr_output_state_set_buffer(&state, buffer); + if (!layers.isEmpty()) + wlr_output_state_set_layers(&state, const_cast(layers.data()), layers.length()); + + bool ok = wlr_output_test_state(d->qwoutput(), &state); + // finish() unlocks any buffer we attached above. + wlr_output_state_finish(&state); + return ok; } bool WOutputHelper::contentIsDirty() const @@ -303,16 +331,19 @@ bool WOutputHelper::contentIsDirty() const bool WOutputHelper::needsFrame() const { W_DC(WOutputHelper); - return d->needsFrame; + return d->output->handle()->needs_frame; +} + +bool WOutputHelper::framePending() const +{ + W_DC(WOutputHelper); + return d->output->handle()->frame_pending; } -void WOutputHelper::resetState(bool resetRenderable) +void WOutputHelper::resetState() { W_D(WOutputHelper); d->setContentIsDirty(false); - if (resetRenderable) - d->setRenderable(false); - d->setNeedsFrame(false); // reset output state if (d->state.committed & WLR_OUTPUT_STATE_BUFFER) { @@ -323,8 +354,10 @@ void WOutputHelper::resetState(bool resetRenderable) d->state.layers = nullptr; d->layersCache.clear(); - free(d->state.gamma_lut); - d->state.gamma_lut = nullptr; + wlr_color_transform_unref(d->state.color_transform); + d->state.color_transform = nullptr; + free(d->state.image_description); + d->state.image_description = nullptr; pixman_region32_clear(&d->state.damage); d->state.committed = 0; } @@ -335,6 +368,28 @@ void WOutputHelper::update() d->update(); } +void WOutputHelper::scheduleFrame() +{ + W_D(WOutputHelper); + wlr_output_schedule_frame(d->qwoutput()); +} + +bool WOutputHelper::willBeEnabled() const +{ + W_DC(WOutputHelper); + // Check pending enabled state in priority order: + // 1. extraState (external configuration from setExtraState) + // 2. internal state (from setScale/setTransform) + // 3. current state (from output->isEnabled()) + if (d->extraState && (d->extraState->committed & WLR_OUTPUT_STATE_ENABLED)) { + return d->extraState->enabled; + } + if (d->state.committed & WLR_OUTPUT_STATE_ENABLED) { + return d->state.enabled; + } + return d->output->isEnabled(); +} + WAYLIB_SERVER_END_NAMESPACE #include "moc_woutputhelper.cpp" diff --git a/waylib/src/server/qtquick/woutputhelper.h b/waylib/src/server/qtquick/woutputhelper.h index 63d3db8fa3..0e42df8bb8 100644 --- a/waylib/src/server/qtquick/woutputhelper.h +++ b/waylib/src/server/qtquick/woutputhelper.h @@ -1,11 +1,13 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include #include -#include +#include +#include #include #include @@ -17,15 +19,7 @@ class QWindow; class QQuickRenderControl; QT_END_NAMESPACE -QW_BEGIN_NAMESPACE -class QWRenderer; -class QWBackend; -class qw_buffer; -QW_END_NAMESPACE - -struct wlr_swapchain; struct pixman_region32; -struct wlr_output_layer_state; typedef QVarLengthArray wlr_output_layer_state_array; WAYLIB_SERVER_BEGIN_NAMESPACE @@ -35,9 +29,8 @@ class WAYLIB_SERVER_EXPORT WOutputHelper : public QObject, public WObject { Q_OBJECT W_DECLARE_PRIVATE(WOutputHelper) - Q_PROPERTY(bool renderable READ renderable NOTIFY renderableChanged) Q_PROPERTY(bool contentIsDirty READ contentIsDirty NOTIFY contentIsDirtyChanged) - Q_PROPERTY(bool needsFrame READ needsFrame NOTIFY needsFrameChanged FINAL) + Q_PROPERTY(bool needsFrame READ needsFrame FINAL) public: explicit WOutputHelper(WOutput *output, QObject *parent = nullptr); @@ -45,38 +38,65 @@ class WAYLIB_SERVER_EXPORT WOutputHelper : public QObject, public WObject WOutput *output() const; QWindow *outputWindow() const; - std::pair acquireRenderTarget(QQuickRenderControl *rc, - wlr_swapchain **swapchain = nullptr); - std::pair lastRenderTarget(); + WRenderHelper::RenderTarget acquireRenderTarget(QQuickRenderControl *rc, + wlr_swapchain **swapchain = nullptr); + WRenderHelper::RenderTarget lastRenderTarget(); + + void setBuffer(wlr_buffer *buffer); + wlr_buffer *buffer() const; - void setBuffer(QW_NAMESPACE::qw_buffer *buffer); - QW_NAMESPACE::qw_buffer *buffer() const; - void setScale(float scale); - void setTransform(WOutput::Transform t); void setDamage(const pixman_region32 *damage); const pixman_region32 *damage() const; void setLayers(const wlr_output_layer_state_array &layers); bool commit(); bool testCommit(); - bool testCommit(QW_NAMESPACE::qw_buffer *buffer, const wlr_output_layer_state_array &layers); + bool testCommit(wlr_buffer *buffer, const wlr_output_layer_state_array &layers); + + enum CommitStage { + BeforeCommitStage, + AfterCommitStage + }; + + struct ExtraState : std::shared_ptr { + ExtraState() + : std::shared_ptr( + []() { + auto* state = new wlr_output_state; + wlr_output_state_init(state); + return state; + }(), + [](wlr_output_state* s) { + if (s) { + wlr_output_state_finish(s); + delete s; + } + } + ) {} + ExtraState(const std::shared_ptr& ptr) + : std::shared_ptr(ptr) {} + ExtraState(std::nullptr_t) : std::shared_ptr(nullptr) {} + }; + + using CommitJobWithState = std::function; + void scheduleCommitJob(CommitJobWithState job, CommitStage stage); + bool setExtraState(ExtraState state); + ExtraState extraState() const; - bool renderable() const; bool contentIsDirty() const; bool needsFrame() const; + bool framePending() const; + bool willBeEnabled() const; - void resetState(bool resetRenderable); + void resetState(); void update(); + void scheduleFrame(); protected: - WOutputHelper(WOutput *output, bool renderable, bool contentIsDirty, bool needsFrame, QObject *parent = nullptr); + WOutputHelper(WOutput *output, bool contentIsDirty, QObject *parent = nullptr); Q_SIGNALS: - void requestRender(); - void damaged(); - void renderableChanged(); void contentIsDirtyChanged(); - void needsFrameChanged(); }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/qtquick/woutputitem.cpp b/waylib/src/server/qtquick/woutputitem.cpp index 799b82ecdd..2166a7c7d8 100644 --- a/waylib/src/server/qtquick/woutputitem.cpp +++ b/waylib/src/server/qtquick/woutputitem.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "woutputitem.h" @@ -8,14 +8,13 @@ #include "wquickcursor.h" #include "private/wglobal_p.h" -#include -#include +#include #include -QW_USE_NAMESPACE -WAYLIB_SERVER_BEGIN_NAMESPACE +#include +WAYLIB_SERVER_BEGIN_NAMESPACE #define DATA_OF_WOUPTUT "_WOutputItem" class Q_DECL_HIDDEN WOutputItemPrivate : public WObjectPrivate @@ -31,8 +30,11 @@ class Q_DECL_HIDDEN WOutputItemPrivate : public WObjectPrivate if (layout) layout->remove(q_func()); - if (output) - output->setProperty(DATA_OF_WOUPTUT, QVariant()); + if (output) { + W_Q(WOutputItem); + if (WOutputItem::getOutputItem(output) == q) + output->setProperty(DATA_OF_WOUPTUT, QVariant()); + } } void initForOutput(); @@ -48,6 +50,7 @@ class Q_DECL_HIDDEN WOutputItemPrivate : public WObjectPrivate } void clearCursors(); + void destroyCursor(const std::pair &i); void updateCursors(); void updateCursorsVisible(); void updateCursorVisible(WOutputCursor *cursor); @@ -72,11 +75,11 @@ void WOutputItemPrivate::initForOutput() if (layout) layout->add(q); - output->safeConnect(&WOutput::transformedSizeChanged, q, [this] { + QObject::connect(output, &WOutput::transformedSizeChanged, q, [this] { updateImplicitSize(); }); - output->safeConnect(&WOutput::aboutToBeInvalidated, q, [this, q] { + QObject::connect(output, &WOutput::beforeDestroy, q, [this, q] { if (layout) { layout->remove(q); layout = nullptr; @@ -95,10 +98,18 @@ void WOutputItemPrivate::initForOutput() } } +void WOutputItemPrivate::destroyCursor(const std::pair &i) +{ + W_Q(WOutputItem); + QObject::disconnect(i.first, nullptr, q, nullptr); + i.second->invalidate(); + i.second->deleteLater(); +} + void WOutputItemPrivate::clearCursors() { for (auto i : std::as_const(cursors)) - i.second->deleteLater(); + destroyCursor(i); cursors.clear(); } @@ -139,22 +150,25 @@ void WOutputItemPrivate::updateCursors() Q_ASSERT(oc->item->parentItem() == q->window()->contentItem()); oc->item->setZ(qreal(WOutputLayout::Layer::Cursor)); cursorsChanged = true; + QPointer safeOc = oc; + QObject::connect(cursor, &WCursor::positionChanged, q, [this, safeOc] { + if (!safeOc) { + return; + } - QObject::connect(cursor, &WCursor::positionChanged, oc, [this, oc] { - updateCursorVisible(oc); + updateCursorVisible(safeOc.data()); }); } tmpCursors.append(std::make_pair(cursor, oc)); } - std::swap(tmpCursors, cursors); + tmpCursors.swap(cursors); // clean needless cursors for (auto i : std::as_const(tmpCursors)) { if (cursors.contains(i)) continue; - i.second->setParent(nullptr); - i.second->deleteLater(); + destroyCursor(i); cursorsChanged = true; } @@ -190,6 +204,7 @@ WOutputCursor *WOutputItemPrivate::getCursorItemBy(WCursor *cursor) const WOutputCursor::WOutputCursor(WOutputItem *parent) : QObject(parent) + , m_output(parent) { } @@ -332,8 +347,6 @@ QList WOutputItem::cursorItems() const void WOutputItem::classBegin() { - W_D(WOutputItem); - QQuickItem::classBegin(); } @@ -350,14 +363,12 @@ void WOutputItem::componentComplete() void WOutputItem::releaseResources() { - W_D(WOutputItem); - WQuickObserver::releaseResources(); } void WOutputItem::itemChange(ItemChange change, const ItemChangeData &data) { - QQuickItem::itemChange(change, data); + WQuickObserver::itemChange(change, data); } void WOutputItem::geometryChange(const QRectF &newGeometry, const QRectF &oldGeometry) diff --git a/waylib/src/server/qtquick/woutputlayer.cpp b/waylib/src/server/qtquick/woutputlayer.cpp index 73faa6b4ed..7c62ecc78d 100644 --- a/waylib/src/server/qtquick/woutputlayer.cpp +++ b/waylib/src/server/qtquick/woutputlayer.cpp @@ -1,15 +1,15 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "woutputlayer.h" #include "woutputrenderwindow.h" #include "wrenderhelper.h" +#include "wayliblogging.h" #include "woutputviewport.h" #include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WOutputLayerPrivate : public QObjectPrivate @@ -40,6 +40,7 @@ class Q_DECL_HIDDEN WOutputLayerPrivate : public QObjectPrivate uint actualEnabled:1; uint refItem:1; WOutputLayer::Flags flags = {0}; + WGlobal::ColorContentsMode colorContentsMode = WGlobal::ColorContentsMode::DontCare; int z = 0; QPointF cursorHotSpot; QList outputs; @@ -71,7 +72,7 @@ void WOutputLayerPrivate::doEnable(bool enable) for (auto o : std::as_const(outputs)) { if (enable) { if (o->window() && o->window() != window) { - qWarning() << "OutputLayer: OutputViewport and OutputLayer's target item " + qCWarning(lcWlOutputLayer) << "OutputLayer: OutputViewport and OutputLayer's target item " "must both be children of the same window."; continue; } @@ -176,6 +177,21 @@ void WOutputLayer::setFlags(const Flags &newFlags) Q_EMIT flagsChanged(); } +WGlobal::ColorContentsMode WOutputLayer::colorContentsMode() const +{ + W_DC(WOutputLayer); + return d->colorContentsMode; +} + +void WOutputLayer::setColorContentsMode(WGlobal::ColorContentsMode mode) +{ + W_D(WOutputLayer); + if (d->colorContentsMode == mode) + return; + d->colorContentsMode = mode; + Q_EMIT colorContentsModeChanged(); +} + const QList &WOutputLayer::outputs() const { W_DC(WOutputLayer); diff --git a/waylib/src/server/qtquick/woutputlayer.h b/waylib/src/server/qtquick/woutputlayer.h index fc61164489..aba2463a5c 100644 --- a/waylib/src/server/qtquick/woutputlayer.h +++ b/waylib/src/server/qtquick/woutputlayer.h @@ -1,9 +1,8 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once -#include #include #include @@ -23,6 +22,7 @@ class WAYLIB_SERVER_EXPORT WOutputLayer : public QObject Q_PROPERTY(bool keepLayer READ keepLayer WRITE setKeepLayer NOTIFY keepLayerChanged FINAL) Q_PROPERTY(bool force READ force WRITE setForce NOTIFY forceChanged FINAL) Q_PROPERTY(Flags flags READ flags WRITE setFlags NOTIFY flagsChanged FINAL) + Q_PROPERTY(WGlobal::ColorContentsMode colorContentsMode READ colorContentsMode WRITE setColorContentsMode NOTIFY colorContentsModeChanged FINAL) Q_PROPERTY(QList outputs READ outputs WRITE setOutputs NOTIFY outputsChanged FINAL) Q_PROPERTY(QList inOutputsByHardware READ inOutputsByHardware NOTIFY inOutputsByHardwareChanged FINAL) Q_PROPERTY(int z READ z WRITE setZ NOTIFY zChanged FINAL) @@ -35,7 +35,6 @@ class WAYLIB_SERVER_EXPORT WOutputLayer : public QObject enum Flag { SizeSensitive = 1 << 0, DontClip = 1 << 1, - PreserveColorContents = 1 << 2, NoAlpha = 1 << 3, Cursor = 1 << 4, }; @@ -54,6 +53,9 @@ class WAYLIB_SERVER_EXPORT WOutputLayer : public QObject Flags flags() const; void setFlags(const Flags &newFlags); + WGlobal::ColorContentsMode colorContentsMode() const; + void setColorContentsMode(WGlobal::ColorContentsMode mode); + const QList &outputs() const; void setOutputs(const QList &newOutputList); @@ -74,6 +76,7 @@ class WAYLIB_SERVER_EXPORT WOutputLayer : public QObject Q_SIGNALS: void enabledChanged(); void flagsChanged(); + void colorContentsModeChanged(); void outputsChanged(); void inOutputsByHardwareChanged(); void zChanged(); diff --git a/waylib/src/server/qtquick/woutputlayoutitem.cpp b/waylib/src/server/qtquick/woutputlayoutitem.cpp index 12737f0a8b..925ca1d297 100644 --- a/waylib/src/server/qtquick/woutputlayoutitem.cpp +++ b/waylib/src/server/qtquick/woutputlayoutitem.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "woutputlayoutitem.h" @@ -6,7 +6,6 @@ #include "wquickoutputlayout.h" #include "private/wglobal_p.h" -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WOutputLayoutItemPrivate : public WObjectPrivate @@ -26,7 +25,8 @@ class Q_DECL_HIDDEN WOutputLayoutItemPrivate : public WObjectPrivate auto oldOutputs = outputs; outputs.clear(); - for (auto output: layout->getIntersectedOutputs(QRectF(q->globalPosition(), q->size()).toRect())) { + const auto intersectedOutputs = layout->getIntersectedOutputs(QRectF(q->globalPosition(), q->size()).toRect()); + for (auto output: intersectedOutputs) { outputs.append(output); }; @@ -75,7 +75,7 @@ void WOutputLayoutItem::setLayout(WQuickOutputLayout *newLayout) return; if (d->layout) - d->layout->safeDisconnect(this); + d->layout->disconnect(this); d->layout = newLayout; diff --git a/waylib/src/server/qtquick/woutputlayoutitem.h b/waylib/src/server/qtquick/woutputlayoutitem.h index 4d4984df40..b384a8ffa6 100644 --- a/waylib/src/server/qtquick/woutputlayoutitem.h +++ b/waylib/src/server/qtquick/woutputlayoutitem.h @@ -1,20 +1,15 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include -#include #include Q_MOC_INCLUDE("woutput.h") Q_MOC_INCLUDE() -QW_BEGIN_NAMESPACE -class QWOutputLayout; -QW_END_NAMESPACE - WAYLIB_SERVER_BEGIN_NAMESPACE class WOutput; diff --git a/waylib/src/server/qtquick/woutputrenderwindow.cpp b/waylib/src/server/qtquick/woutputrenderwindow.cpp index 1f27af58ad..f7958bf837 100644 --- a/waylib/src/server/qtquick/woutputrenderwindow.cpp +++ b/waylib/src/server/qtquick/woutputrenderwindow.cpp @@ -1,7 +1,9 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "woutputrenderwindow.h" +#include +#include #include "woutput.h" #include "woutputhelper.h" #include "wrenderhelper.h" @@ -12,42 +14,35 @@ #include "woutputlayer.h" #include "wbufferrenderer_p.h" #include "wquicktextureproxy.h" +#include "wpointer.h" +#include "wscoplistener.h" #include "weventjunkman.h" #include "winputdevice.h" #include "wseat.h" +#include "wayliblogging.h" +#include "wsgcontext_p.h" #include "platformplugin/qwlrootsintegration.h" #include "platformplugin/qwlrootscreen.h" #include "platformplugin/qwlrootswindow.h" #include "platformplugin/types.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include #include +#include #include #include -#include #include +#include #include +#include -#define protected public -#define private public #include #include #include -#undef protected -#undef private +#include "private/wprivateaccessor_p.h" #include #include #include @@ -58,27 +53,24 @@ #include #include #include -#include #include #include -extern "C" { -#ifdef ENABLE_VULKAN_RENDER -#include -#endif -#include -} - #include #include +using QQuickAnimCtrl_AnimRoots_t = QHash>; +W_DECLARE_PRIVATE_MEMBER(QQuickAnimCtrl_m_animationRoots_tag, QQuickAnimatorController, m_animationRoots, QQuickAnimCtrl_AnimRoots_t); + +using QQuickAnimCtrl_RunningAnimators_t = QSet; +W_DECLARE_PRIVATE_MEMBER(QQuickAnimCtrl_m_runningAnimators_tag, QQuickAnimatorController, m_runningAnimators, QQuickAnimCtrl_RunningAnimators_t); + +W_DECLARE_PRIVATE_MEMBER(QQuickAnimCtrl_m_window_tag, QQuickAnimatorController, m_window, QQuickWindow*); + WAYLIB_SERVER_BEGIN_NAMESPACE -#ifdef QT_DEBUG -Q_LOGGING_CATEGORY(wlcRenderer, "waylib.server.renderer", QtDebugMsg) -#else -Q_LOGGING_CATEGORY(wlcRenderer, "waylib.server.renderer", QtWarningMsg) -#endif +// Call it before any wlroots render to clean up the GL state in Qt. +// If you don't do this, there will be tearing, flickering and other graphics problems inline static void resetGlState() { #ifndef QT_NO_OPENGL @@ -128,7 +120,7 @@ class Q_DECL_HIDDEN OutputHelper : public WOutputHelper friend class WOutputRenderWindowPrivate; public: struct Q_DECL_HIDDEN LayerData { - LayerData(OutputLayer *l, qw_output_layer *layer) + LayerData(OutputLayer *l, wlr_output_layer *layer) : layer(l) , wlrLayer(layer) , contentsIsDirty(true) @@ -136,15 +128,21 @@ class Q_DECL_HIDDEN OutputHelper : public WOutputHelper } ~LayerData() { - if (renderer) + if (renderer) { + QObject::disconnect(rendererConnection); renderer->deleteLater(); - if (wlrLayer) - wlrLayer->deleteLater(); + } + + if (wlrLayer) { + wlr_output_layer_destroy(wlrLayer); + wlrLayer = nullptr; + } } OutputLayer *layer; - QPointer wlrLayer; + wlr_output_layer * wlrLayer; QPointer renderer; + QMetaObject::Connection rendererConnection; // dirty state uint contentsIsDirty:1; @@ -162,8 +160,8 @@ class Q_DECL_HIDDEN OutputHelper : public WOutputHelper QPointer mapTo; }; - OutputHelper(WOutputViewport *output, WOutputRenderWindow *parent, bool renderable, bool contentIsDirty, bool needsFrame) - : WOutputHelper(output->output(), renderable, contentIsDirty, needsFrame, parent) + OutputHelper(WOutputViewport *output, WOutputRenderWindow *parent, bool contentIsDirty) + : WOutputHelper(output->output(), contentIsDirty, parent) , m_output(output) { @@ -171,20 +169,18 @@ class Q_DECL_HIDDEN OutputHelper : public WOutputHelper ~OutputHelper() { - cleanLayerCompositor(); - cleanCursorRender(); - qDeleteAll(m_layers); + if (!m_layerProxys.isEmpty() || m_output || m_output2 || m_layerPorxyContainer + || m_cursorRenderer || m_cursorLayerProxy) + qFatal("Before destroying OutputHelper, ensure call invalidate method."); } inline void init() { - connect(this, &OutputHelper::requestRender, renderWindow(), qOverload<>(&WOutputRenderWindow::render)); - connect(this, &OutputHelper::damaged, renderWindow(), &WOutputRenderWindow::scheduleRender); // TODO: pre update scale after WOutputHelper::setScale - output()->output()->safeConnect(&WOutput::scaleChanged, this, &OutputHelper::updateSceneDPR); + QObject::connect(outputViewport()->output(), &WOutput::scaleChanged, this, &OutputHelper::updateSceneDPR); } - inline qw_output *qwoutput() const { - return output()->output()->handle(); + inline wlr_output *output() const { + return outputViewport()->output()->handle(); } inline WOutputRenderWindow *renderWindow() const { @@ -192,7 +188,7 @@ class Q_DECL_HIDDEN OutputHelper : public WOutputHelper } inline WOutputRenderWindowPrivate *renderWindowD() const; - inline WOutputViewport *output() const { + inline WOutputViewport *outputViewport() const { return m_output; } @@ -211,6 +207,9 @@ class Q_DECL_HIDDEN OutputHelper : public WOutputHelper inline void invalidate() { m_output = nullptr; + cleanLayerCompositor(); + cleanCursorRender(); + qDeleteAll(m_layers); } inline qreal devicePixelRatio() const { @@ -227,20 +226,21 @@ class Q_DECL_HIDDEN OutputHelper : public WOutputHelper void cleanLayerCompositor(); void cleanCursorRender(); - inline qw_buffer *beginRender(WBufferRenderer *renderer, + inline wlr_buffer *beginRender(WBufferRenderer *renderer, const QSize &pixelSize, uint32_t format, - WBufferRenderer::RenderFlags flags); + WBufferRenderer::RenderFlags flags, + WGlobal::ColorContentsMode mode = WGlobal::ColorContentsMode::DontCare); inline void render(WBufferRenderer *renderer, int sourceIndex, const QMatrix4x4 &renderMatrix, - const QRectF &sourceRect, const QRectF &viewportRect, bool preserveColorContents); + const QRectF &sourceRect, const QRectF &viewportRect); static bool visualizeLayers() { static bool on = qEnvironmentVariableIsSet("WAYLIB_VISUALIZE_LAYERS"); return on; } - qw_buffer *renderLayer(LayerData *layer, bool *dontEndRenderAndReturnNeedsEndRender); + wlr_buffer *renderLayer(LayerData *layer, bool *dontEndRenderAndReturnNeedsEndRender); WBufferRenderer *afterRender(); - WBufferRenderer *compositeLayers(const QVector layers, bool forceShadowRenderer); + WBufferRenderer *compositeLayers(const QList layers, bool forceShadowRenderer); bool commit(WBufferRenderer *buffer); bool tryToHardwareCursor(const LayerData *layer); @@ -292,7 +292,7 @@ class Q_DECL_HIDDEN OutputLayer state = Accepted; if (!layer->isAccepted()) { layer->setAccepted(true); - qCInfo(wlcRenderer) << "Layer" << layer->parent() << "is accepted(" + qCInfo(lcWlRenderer) << "Layer" << layer->parent() << "is accepted(" << (isHardware ? "hardware" : "software") << ") on" << output; } @@ -312,7 +312,7 @@ class Q_DECL_HIDDEN OutputLayer state = Rejected; if (layer->isAccepted()) { layer->setAccepted(false); - qCInfo(wlcRenderer) << "Layer" << layer->parent() << "is rejected on" << output; + qCInfo(lcWlRenderer) << "Layer" << layer->parent() << "is rejected on" << output; } if (layer->setInHardware(output, false)) { @@ -367,14 +367,30 @@ class Q_DECL_HIDDEN RenderControl : public QQuickRenderControl QWindow *m_renderWindow = nullptr; }; -static QEvent::Type doRenderEventType = static_cast(QEvent::registerEventType()); class Q_DECL_HIDDEN WOutputRenderWindowPrivate : public QQuickWindowPrivate { public: WOutputRenderWindowPrivate(WOutputRenderWindow *) - : QQuickWindowPrivate() { + : QQuickWindowPrivate() + , listenerOwner(std::make_unique()) + { + // QML animations are otherwise advanced by Qt's fixed-interval + // QUnifiedTimer, which is decoupled from output frames. Advancing them + // from doRender() ties every animation to the rendered frame instead. + animationDriver.reset(new QAnimationDriver()); + // The driver replaces Qt's fixed-interval timer, so the frame it is + // advanced on has to be requested here as well: an animation that + // starts while nothing repaints the scene (e.g. started by a timer or + // by a state change that has not changed any visible property yet) + // would otherwise never get a frame and stay frozen forever. + QObject::connect(animationDriver.data(), &QAnimationDriver::started, + animationDriver.data(), [this] { + scheduleDoRender(); + }); + animationDriver->install(); } ~WOutputRenderWindowPrivate() { + animationDriver->uninstall(); qDeleteAll(layers); } @@ -403,6 +419,13 @@ class Q_DECL_HIDDEN WOutputRenderWindowPrivate : public QQuickWindowPrivate layers.append(new OutputLayer(layer)); return layers.last(); } + inline bool containsOutput(WOutput *o) const { + for (auto output : std::as_const(outputs)) { + if (output->outputViewport()->output() == o) + return true; + } + return false; + } inline RenderControl *rc() const { return static_cast(q_func()->renderControl()); @@ -424,11 +447,10 @@ class Q_DECL_HIDDEN WOutputRenderWindowPrivate : public QQuickWindowPrivate void sortOutputs(); QVector> - doRenderOutputs(const QList &outputs, bool forceRender); - void doRender(const QList &outputs, bool forceRender, bool doCommit); - inline void doRender() { - doRender(outputs, false, true); - } + doRenderOutputs(wlr_output *needsFrameOutput, const QList &outputs, + bool forceRender, QList> &failedViewports); + void doRender(wlr_output *needsFrameOutput, const QList &outputs, + bool forceRender, bool doCommit); inline void pushRenderer(WBufferRenderer *renderer) { rendererList.push(renderer); @@ -441,16 +463,19 @@ class Q_DECL_HIDDEN WOutputRenderWindowPrivate : public QQuickWindowPrivate if (inRendering) return; - QCoreApplication::postEvent(q_func(), new QEvent(doRenderEventType)); + for (auto o : std::as_const(outputs)) { + wlr_output_schedule_frame(o->output()); + } } Q_DECLARE_PUBLIC(WOutputRenderWindow) bool componentCompleted = true; bool inRendering = false; + bool renderEnabled = true; - QPointer m_renderer; - QPointer m_allocator; + WPointer m_renderer; + WPointer m_allocator; QList outputs; QList layers; @@ -462,6 +487,13 @@ class Q_DECL_HIDDEN WOutputRenderWindowPrivate : public QQuickWindowPrivate #endif QStack rendererList; + + QScopedPointer animationDriver; + + // Owner token for per-output frame/needs_frame listeners registered on + // WOutput via WObject::listeners(). ~WListenerOwner/teardown() detaches + // them; reset early from ~WOutputRenderWindow. + std::unique_ptr listenerOwner; }; WOutputRenderWindowPrivate *OutputHelper::renderWindowD() const @@ -494,8 +526,8 @@ OutputHelper::LayerData *OutputHelper::getLayer(OutputLayer *layer) const bool OutputHelper::attachLayer(OutputLayer *layer) { Q_ASSERT(indexOfLayer(layer) < 0); - // qw_output will destory this layer on qw_output destroy - auto qwlayer = qw_output_layer::create(*qwoutput()); + // wlr_output will destory this layer on wlr_output destroy + auto qwlayer = wlr_output_layer_create(output()); if (!qwlayer) return false; @@ -536,18 +568,13 @@ void OutputHelper::sortLayers() void OutputHelper::cleanLayerCompositor() { QList> tmpList; - std::swap(m_layerProxys, tmpList); + tmpList.swap(m_layerProxys); for (auto proxy : std::as_const(tmpList)) { if (!proxy) continue; - WBufferRenderer *source = qobject_cast(proxy->sourceItem()); proxy->setRenderer(nullptr); - - if (source) { - source->resetTextureProvider(); - } } if (m_output2) { @@ -576,18 +603,19 @@ void OutputHelper::cleanCursorRender() } } -qw_buffer *OutputHelper::beginRender(WBufferRenderer *renderer, +wlr_buffer *OutputHelper::beginRender(WBufferRenderer *renderer, const QSize &pixelSize, uint32_t format, - WBufferRenderer::RenderFlags flags) + WBufferRenderer::RenderFlags flags, + WGlobal::ColorContentsMode mode) { - return renderer->beginRender(pixelSize, devicePixelRatio(), format, flags); + return renderer->beginRender(pixelSize, devicePixelRatio(), format, flags, mode); } void OutputHelper::render(WBufferRenderer *renderer, int sourceIndex, const QMatrix4x4 &renderMatrix, - const QRectF &sourceRect, const QRectF &targetRect, bool preserveColorContents) + const QRectF &sourceRect, const QRectF &targetRect) { renderWindowD()->pushRenderer(renderer); - renderer->render(sourceIndex, renderMatrix, sourceRect, targetRect, preserveColorContents); + renderer->render(sourceIndex, renderMatrix, sourceRect, targetRect); } static QQuickItem *createVisualRectangle(QQuickItem *target, const QColor &color) { @@ -606,7 +634,7 @@ static inline QRectF scaleRect(const QRectF &r, qreal xScale, qreal yScale) { return QRectF(r.x() * xScale, r.y() * yScale, r.width() * xScale, r.height() * yScale); } -qw_buffer *OutputHelper::renderLayer(LayerData *layer, bool *dontEndRenderAndReturnNeedsEndRender) +wlr_buffer *OutputHelper::renderLayer(LayerData *layer, bool *dontEndRenderAndReturnNeedsEndRender) { auto source = layer->layer->layer->parent(); if (!source->parentItem() || source->window() != renderWindow()) @@ -625,12 +653,12 @@ qw_buffer *OutputHelper::renderLayer(LayerData *layer, bool *dontEndRenderAndRet } layer->renderer->setSourceList(sourceList, false); - layer->renderer->setOutput(output()->output()); + layer->renderer->setOutput(outputViewport()->output()); // for the new WBufferRenderer and createVisualRectangle renderWindowD()->updateDirtyNodes(); - connect(layer->renderer, &WBufferRenderer::sceneGraphChanged, this, [layer] { + layer->rendererConnection = connect(layer->renderer, &WBufferRenderer::sceneGraphChanged, this, [layer] { layer->contentsIsDirty = true; }); } @@ -646,9 +674,9 @@ qw_buffer *OutputHelper::renderLayer(LayerData *layer, bool *dontEndRenderAndRet const bool sizeSensitive = layerFlags & WOutputLayer::SizeSensitive; const bool isRef = layer->mapFrom && layer->mapTo; if (isRef) { - viewportMatrix = output()->mapToViewport(layer->mapTo); - const auto xScale = layer->mapTo->width() / layer->mapFrom->output()->width(); - const auto yScale = layer->mapTo->height() / layer->mapFrom->output()->height(); + viewportMatrix = outputViewport()->mapToViewport(layer->mapTo); + const auto xScale = layer->mapTo->width() / layer->mapFrom->outputViewport()->width(); + const auto yScale = layer->mapTo->height() / layer->mapFrom->outputViewport()->height(); // geometry relative the other output buffer noClipMapRect = scaleRect(layer->mapFromLayer->noClipMapRect, xScale, yScale); @@ -658,7 +686,7 @@ qw_buffer *OutputHelper::renderLayer(LayerData *layer, bool *dontEndRenderAndRet mapRect = noClipMapRect; } } else { - viewportMatrix = output()->mapToViewport(source->parentItem()); + viewportMatrix = outputViewport()->mapToViewport(source->parentItem()); // geometry relative source's parent noClipMapRect = QRectF(source->position(), source->size()); @@ -666,7 +694,7 @@ qw_buffer *OutputHelper::renderLayer(LayerData *layer, bool *dontEndRenderAndRet } // matrix function: map source to output buffer - const auto outputMatrix = viewportMatrix * output()->sourceRectToTargetRectTransfrom(); + const auto outputMatrix = viewportMatrix * outputViewport()->sourceRectToTargetRectTransfrom(); noClipMapRect = outputMatrix.mapRect(noClipMapRect); mapRect = outputMatrix.mapRect(mapRect); @@ -688,7 +716,7 @@ qw_buffer *OutputHelper::renderLayer(LayerData *layer, bool *dontEndRenderAndRet } // clip to WOutputViewport - mapRect = mapRect & QRectF(QPointF(0, 0), output()->size()); + mapRect = mapRect & QRectF(QPointF(0, 0), outputViewport()->size()); QSize pixelSize; const auto tmpSize = mapRect.size() * dpr; @@ -741,20 +769,28 @@ qw_buffer *OutputHelper::renderLayer(LayerData *layer, bool *dontEndRenderAndRet layer->renderer->setSize(layer->pixelSize / dpr); const bool alpha = !layer->layer->layer->flags().testFlag(WOutputLayer::NoAlpha); + auto mode = layer->layer->layer->colorContentsMode(); + if (visualizeLayers()) { + if (mode == WGlobal::ColorContentsMode::Clear) { + qCWarning(lcWlRenderer) << "Layer" << layer->layer->layer + << "requires Clear but visualizeLayers forces Preserve"; + } + mode = WGlobal::ColorContentsMode::Preserve; + } // Don't use OutputHelper::beginRender, because the dpr maybe is from LayerData::mapFrom buffer = layer->renderer->beginRender(layer->pixelSize, dpr, // TODO: Allows control format by WOutputLayer alpha ? DRM_FORMAT_ARGB8888 : DRM_FORMAT_XRGB8888, - WBufferRenderer::DontConfigureSwapchain); + WBufferRenderer::DontConfigureSwapchain, + mode); if (buffer) { const QRectF sr = QRectF(layer->mapRect.topLeft() - layer->noClipMapRect.topLeft(), layer->mapRect.size()); const QRectF tr(QPointF(0, 0), layer->mapRect.size()); - render(layer->renderer, 0, layer->renderMatrix, sr, tr, - layer->layer->layer->flags().testFlag(WOutputLayer::PreserveColorContents)); + render(layer->renderer, 0, layer->renderMatrix, sr, tr); if (visualizeLayers()) - render(layer->renderer, 1, layer->renderMatrix, sr, tr, true); + render(layer->renderer, 1, layer->renderMatrix, sr, tr); if (dontEndRenderAndReturnNeedsEndRender) { *dontEndRenderAndReturnNeedsEndRender = true; @@ -808,19 +844,21 @@ WBufferRenderer *OutputHelper::afterRender() continue; layers.append({ - .layer = i->wlrLayer->handle(), - .buffer = buffer->handle(), + .layer = i->wlrLayer, + .buffer = buffer, + .src_box = {}, .dst_box = { .x = i->mapToOutput.x(), .y = i->mapToOutput.y(), .width = i->mapToOutput.width(), .height = i->mapToOutput.height(), }, - .damage = &i->renderer->damageRing()->handle()->current + .damage = &i->renderer->damageRing()->current, + .accepted = false }); if (needsEndBuffer) { - // after get damage(&i->renderer->damageRing()->handle()->current) + // after get damage(&i->renderer->damageRing()->current) i->renderer->endRender(); } @@ -840,13 +878,14 @@ WBufferRenderer *OutputHelper::afterRender() return bufferRenderer(); } - if (output()->offscreen()) { + if (outputViewport()->offscreen()) { cleanLayerCompositor(); return bufferRenderer(); } static bool noHardwareLayers = qEnvironmentVariableIsSet("WAYLIB_NO_HARDWARE_LAYERS"); const bool ok = !noHardwareLayers && WOutputHelper::testCommit(bufferRenderer()->currentBuffer(), layers); + const bool captureLocked = output() && output()->attach_render_locks > 0; int needsSoftwareCompositeBeginIndex = -1; int needsSoftwareCompositeEndIndex = -1; bool forceShadowRender = false; @@ -855,14 +894,14 @@ WBufferRenderer *OutputHelper::afterRender() { // try fallback to cursor plane for the top layer auto topLayer = needsCompositeLayers.last(); - if ((!output()->disableHardwareLayers() || topLayer->layer->forceLayer()) + if ((!outputViewport()->disableHardwareLayers() || topLayer->layer->forceLayer()) && !(ok && layers.last().accepted) && (topLayer->layer->layer->flags() & WOutputLayer::Cursor)) { if (tryToHardwareCursor(topLayer)) { - Q_ASSERT(topLayer->renderer->lastBuffer()->handle() == layers.last().buffer); + Q_ASSERT(topLayer->renderer->lastBuffer() == layers.last().buffer); Q_ASSERT(!hasHardwareCursor); hasHardwareCursor = true; - bool ok = topLayer->layer->accept(output(), true); + bool ok = topLayer->layer->accept(outputViewport(), true); Q_ASSERT(ok); needsCompositeLayers.removeLast(); layers.removeLast(); @@ -876,18 +915,26 @@ WBufferRenderer *OutputHelper::afterRender() Q_ASSERT(state.buffer); OutputLayer *layer = needsCompositeLayers[i]->layer; + const bool cursor = layer->layer->flags() & WOutputLayer::Cursor; + // A software-cursor lock forbids the cursor plane (capture with + // cursors and WLR_NO_HARDWARE_CURSORS both raise it), so the cursor + // has to be composited instead of accepted as a layer. + const bool isSoftwareCursor = cursor && output()->software_cursor_locks > 0; + // A capture reads only the primary buffer, so no other layer may stay + // on a hardware plane while it is locked. + const bool pinToPrimary = isSoftwareCursor || (captureLocked && !cursor); // If hardware layers is disabled on this output viewport // and this layer doesn't want force layer, should fallback // to software composite. if (needsSoftwareCompositeEndIndex == -1 - && output()->disableHardwareLayers() - && !layer->forceLayer()) { + && (pinToPrimary + || (outputViewport()->disableHardwareLayers() && !layer->forceLayer()))) { needsSoftwareCompositeEndIndex = i; } if (needsSoftwareCompositeEndIndex == -1) { if (ok && state.accepted) { - bool ok = layer->accept(output(), true); + bool ok = layer->accept(outputViewport(), true); Q_ASSERT(ok); continue; } else { @@ -895,18 +942,18 @@ WBufferRenderer *OutputHelper::afterRender() } } - if (layer->forceLayer() || layer->keepLayer() + if (pinToPrimary || layer->forceLayer() || layer->keepLayer() // current layer can't reject, because the layes behind current layer // requset force composite. || i >= firstCantRejectLayerIndex) { - Q_ASSERT(layer->needsComposite()); - bool ok = layer->accept(output(), false); + Q_ASSERT(layer->needsComposite() || pinToPrimary); + bool ok = layer->accept(outputViewport(), false); Q_ASSERT(ok); if (layer->forceLayer()) forceShadowRender = true; needsSoftwareCompositeBeginIndex = i; - } else if (!output()->ignoreSoftwareLayers()) { - bool ok = layer->reject(output()); + } else if (!outputViewport()->ignoreSoftwareLayers()) { + bool ok = layer->reject(outputViewport()); Q_ASSERT(ok); } } @@ -937,7 +984,7 @@ WBufferRenderer *OutputHelper::afterRender() if (needsCompositeLayers.isEmpty() // Don't do anyting if this output viewport wants ignore software layers - || output()->ignoreSoftwareLayers()) { + || (outputViewport()->ignoreSoftwareLayers() && !captureLocked)) { Q_ASSERT(!forceShadowRender); cleanLayerCompositor(); return bufferRenderer(); @@ -951,7 +998,8 @@ WBufferRenderer *OutputHelper::compositeLayers(const QList layers, b { Q_ASSERT(!layers.isEmpty()); - const bool usingShadowRenderer = forceShadowRenderer; + const bool usingShadowRenderer = forceShadowRenderer + || !bufferRenderer()->isColorPreserved(); if (!m_layerPorxyContainer) { m_layerPorxyContainer = new QQuickItem(renderWindow()->contentItem()); @@ -1024,20 +1072,21 @@ WBufferRenderer *OutputHelper::compositeLayers(const QList layers, b if (usingShadowRenderer) { const bool ok = beginRender(bufferRenderer2(), m_output->output()->size(), - qwoutput()->handle()->render_format, - WBufferRenderer::RedirectOpenGLContextDefaultFrameBufferObject); + this->output()->render_format, + WBufferRenderer::RedirectOpenGLContextDefaultFrameBufferObject, + WGlobal::ColorContentsMode::Preserve); if (ok) { // stop primary render if (bufferRenderer()->currentBuffer()) bufferRenderer()->endRender(); - render(bufferRenderer2(), 0, {}, m_output->effectiveSourceRect(), m_output->targetRect(), true); + render(bufferRenderer2(), 0, {}, m_output->effectiveSourceRect(), m_output->targetRect()); return bufferRenderer2(); } } else { if (bufferRenderer()->currentBuffer()) { - render(bufferRenderer(), 1, {}, m_output->effectiveSourceRect(), m_output->targetRect(), true); + render(bufferRenderer(), 1, {}, m_output->effectiveSourceRect(), m_output->targetRect()); } else { // ###(zccrs): Maybe because contents is not dirty, so not do render // in WOutputRenderWindowPrivate::doRenderOutputs, force mark the @@ -1051,7 +1100,7 @@ WBufferRenderer *OutputHelper::compositeLayers(const QList layers, b bool OutputHelper::commit(WBufferRenderer *buffer) { - if (output()->offscreen()) + if (outputViewport()->offscreen()) return true; if (!buffer || !buffer->currentBuffer()) { @@ -1062,8 +1111,8 @@ bool OutputHelper::commit(WBufferRenderer *buffer) setBuffer(buffer->currentBuffer()); if (m_lastCommitBuffer == buffer) { - if (pixman_region32_not_empty(&buffer->damageRing()->handle()->current)) - setDamage(&buffer->damageRing()->handle()->current); + if (pixman_region32_not_empty(&buffer->damageRing()->current)) + setDamage(&buffer->damageRing()->current); } m_lastCommitBuffer = buffer; @@ -1074,50 +1123,78 @@ bool OutputHelper::commit(WBufferRenderer *buffer) bool OutputHelper::tryToHardwareCursor(const LayerData *layer) { do { - auto set_cursor = qwoutput()->handle()->impl->set_cursor; + auto set_cursor = output()->impl->set_cursor; auto buffer = layer && layer->renderer->lastBuffer() - ? layer->renderer->lastBuffer()->handle() + ? layer->renderer->lastBuffer() : nullptr; if (!buffer) { if (!m_hardwareCursorRenderComplete) return true; if (set_cursor) - set_cursor(qwoutput()->handle(), buffer, 0, 0); + set_cursor(output(), buffer, 0, 0); m_hardwareCursorRenderComplete = false; return true; } - if (qwoutput()->handle()->software_cursor_locks > 0) + if (output()->software_cursor_locks > 0) break; - auto move_cursor = qwoutput()->handle()->impl->move_cursor; + auto move_cursor = output()->impl->move_cursor; if (!set_cursor || !move_cursor) break; QSize pixelSize = QSize(buffer->width, buffer->height); - auto get_cursor_sizes = qwoutput()->handle()->impl->get_cursor_sizes; - auto get_cursor_formsts = qwoutput()->handle()->impl->get_cursor_formats; + auto get_cursor_sizes = output()->impl->get_cursor_sizes; + auto get_cursor_formsts = output()->impl->get_cursor_formats; bool needsRepaintCursor = get_cursor_sizes && get_cursor_formsts; + if (Q_UNLIKELY(lcWlRenderer().isDebugEnabled())) + qCDebug(lcWlRenderer) << "Request cursor buffer size:" << pixelSize; + if (get_cursor_sizes) { + if (Q_UNLIKELY(lcWlRenderer().isDebugEnabled())) + qCDebug(lcWlRenderer) << "Supported cursor sizes for output" << outputViewport() << ":"; + bool foundTargetSize = false; size_t sizes_len = 0; - const auto sizes = get_cursor_sizes(qwoutput()->handle(), &sizes_len); + const auto sizes = get_cursor_sizes(output(), &sizes_len); for (size_t i = 0; i < sizes_len; ++i) { + if (Q_UNLIKELY(lcWlRenderer().isDebugEnabled())) + qCDebug(lcWlRenderer) << " " << sizes[i].width << "x" << sizes[i].height; + if (sizes[i].width == pixelSize.width() && sizes[i].height == pixelSize.height()) { foundTargetSize = true; - break; + if (Q_UNLIKELY(lcWlRenderer().isDebugEnabled())) + qCDebug(lcWlRenderer) << " " << sizes[i].width << "x" << sizes[i].height << "(matched)"; + else + break; //need continue to print other sizes when find matched size } } if (!foundTargetSize && sizes_len > 0) { - // Use the request size wlroots's backend to render the cursor - pixelSize.rwidth() = sizes[0].width; - pixelSize.rheight() = sizes[0].height; - needsRepaintCursor = true; + // Use the wlroots's backend supported size to re-render the cursor + for (size_t i = 0; i < sizes_len; ++i) { + if (sizes[i].width > pixelSize.width() + && sizes[i].height > pixelSize.height()) { + pixelSize.rwidth() = sizes[i].width; + pixelSize.rheight() = sizes[i].height; + if (Q_UNLIKELY(lcWlRenderer().isDebugEnabled())) + qCDebug(lcWlRenderer) << "Re-render cursor with size" << pixelSize + << "because the original cursor size" + << QSize(buffer->width, buffer->height) + << "is not supported by wlroots backend"; + needsRepaintCursor = true; + break; + } + } + + if (Q_UNLIKELY(!needsRepaintCursor)) { + qCWarning(lcWlRenderer) << "Can't find suitable cursor size for" << pixelSize; + return false; + } } else { needsRepaintCursor = false; } @@ -1151,8 +1228,8 @@ bool OutputHelper::tryToHardwareCursor(const LayerData *layer) // and the part beyond the screen will not be included in the pixelSize. In this case, // the pixelSize is inconsistent with the newBuffer size, and it needs to be redrawn. if (m_cursorDirty || !newBuffer || - (pixelSize.width() != newBuffer->handle()->width) || - (pixelSize.height() != newBuffer->handle()->height)) { + (pixelSize.width() != newBuffer->width) || + (pixelSize.height() != newBuffer->height)) { newBuffer = m_cursorRenderer->beginRender(pixelSize, 1.0, DRM_FORMAT_ARGB8888, WBufferRenderer::UseCursorFormats); if (newBuffer) { @@ -1164,9 +1241,9 @@ bool OutputHelper::tryToHardwareCursor(const LayerData *layer) } if (newBuffer) { - Q_ASSERT(pixelSize.width() == newBuffer->handle()->width); - Q_ASSERT(pixelSize.height() == newBuffer->handle()->height); - buffer = newBuffer->handle(); + Q_ASSERT(pixelSize.width() == newBuffer->width); + Q_ASSERT(pixelSize.height() == newBuffer->height); + buffer = newBuffer; } else { buffer = nullptr; } @@ -1174,7 +1251,7 @@ bool OutputHelper::tryToHardwareCursor(const LayerData *layer) const auto hotSpot = layer->renderMatrix.map(layer->layer->layer->cursorHotSpot() * devicePixelRatio()).toPoint(); - if (!set_cursor(qwoutput()->handle(), buffer, hotSpot.x(), hotSpot.y())) { + if (!set_cursor(output(), buffer, hotSpot.x(), hotSpot.y())) { break; } else { m_hardwareCursorRenderComplete = true; @@ -1182,15 +1259,15 @@ bool OutputHelper::tryToHardwareCursor(const LayerData *layer) } const auto pos = layer->mapToOutput.topLeft() + hotSpot; - wlr_box cleanTransform {.x = pos.x(), .y = pos.y()}; - const auto outputSize = output()->output()->size(); + wlr_box cleanTransform {.x = pos.x(), .y = pos.y(), .width = 0, .height = 0}; + const auto outputSize = outputViewport()->output()->size(); // the layer->mapRect has been transform in renderLayer, but // wlroot's move_cursor also will transform the cursor's position. // so revert transform here. wlr_box_transform(&cleanTransform, &cleanTransform, - qwoutput()->handle()->transform, + output()->transform, outputSize.width(), outputSize.height()); - if (!move_cursor(qwoutput()->handle(), cleanTransform.x, cleanTransform.y)) { + if (!move_cursor(output(), cleanTransform.x, cleanTransform.y)) { break; } @@ -1205,7 +1282,7 @@ bool OutputHelper::tryToHardwareCursor(const LayerData *layer) int WOutputRenderWindowPrivate::indexOfOutputHelper(const WOutputViewport *output) const { for (int i = 0; i < outputs.size(); ++i) { - if (outputs.at(i)->output() == output) { + if (outputs.at(i)->outputViewport() == output) { return i; } } @@ -1281,21 +1358,20 @@ void WOutputRenderWindowPrivate::init() void WOutputRenderWindowPrivate::init(OutputHelper *helper) { - W_Q(WOutputRenderWindow); - QMetaObject::invokeMethod(q, &WOutputRenderWindow::scheduleRender, Qt::QueuedConnection); + QMetaObject::invokeMethod(helper, &WOutputHelper::scheduleFrame, Qt::QueuedConnection); helper->init(); - QObject::connect(helper->output(), &WOutputViewport::dependsChanged, helper, [this] { + QObject::connect(helper->outputViewport(), &WOutputViewport::dependsChanged, helper, [this] { sortOutputs(); }); for (auto layer : std::as_const(layers)) { - if (layer->outputs().contains(helper->output())) { + if (layer->outputs().contains(helper->outputViewport())) { helper->attachLayer(layer); } } } -inline static QByteArrayList fromCStyleList(size_t count, const char **list) { +[[maybe_unused]] inline static QByteArrayList fromCStyleList(size_t count, const char **list) { QByteArrayList al; al.reserve(count); for (size_t i = 0; i < count; ++i) { @@ -1316,14 +1392,12 @@ bool WOutputRenderWindowPrivate::initRCWithRhi() if (rhiSupport->rhiBackend() == QRhi::Vulkan) { vkInstance.reset(new QVulkanInstance()); - auto phdev = wlr_vk_renderer_get_physical_device(m_renderer->handle()); - auto dev = wlr_vk_renderer_get_device(m_renderer->handle()); - auto queue_family = wlr_vk_renderer_get_queue_family(m_renderer->handle()); + auto phdev = wlr_vk_renderer_get_physical_device(m_renderer); + auto dev = wlr_vk_renderer_get_device(m_renderer); + auto queue_family = wlr_vk_renderer_get_queue_family(m_renderer); -#if QT_VERSION > QT_VERSION_CHECK(6, 6, 0) - auto instance = wlr_vk_renderer_get_instance(m_renderer->handle()); + auto instance = wlr_vk_renderer_get_instance(m_renderer); vkInstance->setVkInstance(instance); -#endif // vkInstance->setExtensions(fromCStyleList(vkRendererAttribs.extension_count, vkRendererAttribs.extensions)); // vkInstance->setLayers(fromCStyleList(vkRendererAttribs.layer_count, vkRendererAttribs.layers)); vkInstance->setApiVersion({1, 1, 0}); @@ -1335,8 +1409,8 @@ bool WOutputRenderWindowPrivate::initRCWithRhi() } else #endif if (rhiSupport->rhiBackend() == QRhi::OpenGLES2) { - Q_ASSERT(wlr_renderer_is_gles2(m_renderer->handle())); - auto egl = wlr_gles2_renderer_get_egl(m_renderer->handle()); + Q_ASSERT(wlr_renderer_is_gles2(m_renderer)); + auto egl = wlr_gles2_renderer_get_egl(m_renderer); auto display = wlr_egl_get_display(egl); auto context = wlr_egl_get_context(egl); @@ -1355,7 +1429,7 @@ bool WOutputRenderWindowPrivate::initRCWithRhi() QSGRhiSupport::RhiCreateResult result = rhiSupport->createRhi(q, offscreenSurface); if (!result.rhi) { - qWarning("WOutput::initRhi: Failed to initialize QRhi"); + qCWarning(lcWlRenderer, "WOutput::initRhi: Failed to initialize QRhi"); return false; } @@ -1383,8 +1457,8 @@ void WOutputRenderWindowPrivate::updateSceneDPR() qreal maxDPR = 0.0; for (auto o : std::as_const(outputs)) { - if (o->output()->output()->scale() > maxDPR) - maxDPR = o->output()->output()->scale(); + if (o->outputViewport()->output()->scale() > maxDPR) + maxDPR = o->outputViewport()->output()->scale(); } setSceneDevicePixelRatio(maxDPR); @@ -1395,46 +1469,77 @@ void WOutputRenderWindowPrivate::sortOutputs() { std::stable_sort(outputs.begin(), outputs.end(), [] (const OutputHelper *o1, const OutputHelper *o2) { - return o2->output()->depends().contains(o1->output()); + return o2->outputViewport()->depends().contains(o1->outputViewport()); }); } QVector> -WOutputRenderWindowPrivate::doRenderOutputs(const QList &outputs, bool forceRender) +WOutputRenderWindowPrivate::doRenderOutputs(wlr_output *needsFrameOutput, const QList &outputs, + bool forceRender, + QList> &failedViewports) { QVector renderResults; renderResults.reserve(outputs.size()); for (OutputHelper *helper : std::as_const(outputs)) { + if (Q_LIKELY(needsFrameOutput)) { + if (helper->output() != needsFrameOutput) + continue; + else + Q_ASSERT(!helper->framePending()); + } + if (Q_LIKELY(!forceRender)) { - if (!helper->renderable() - || Q_UNLIKELY(!WOutputViewportPrivate::get(helper->output())->renderable()) - || !helper->output()->output()->isEnabled()) + if (helper->framePending()) + continue; + + // Render if output will be enabled OR has extraState to commit + // Note: Even when disabling, we need to render once to commit the disabled state + // (extraState will contain the ENABLED=false change) + bool shouldRender = helper->outputViewport()->offscreen() + || helper->willBeEnabled() || helper->extraState(); + if (Q_UNLIKELY(!WOutputViewportPrivate::get(helper->outputViewport())->renderable()) + || !shouldRender) continue; - if (!helper->contentIsDirty()) { - if (helper->needsFrame()) - renderResults.append(helper); + if (!(helper->needsFrame() || helper->contentIsDirty())) + continue; + + // Capture sessions (ext-image-copy-capture etc.) lock the output + // via wlr_output_lock_attach_render() and need a buffer commit to + // complete, even if the content didn't change. + bool captureLocked = helper->output()->attach_render_locks > 0; + if (!helper->contentIsDirty() && !captureLocked) { + renderResults.append(helper); continue; } } - Q_ASSERT(helper->output()->output()->scale() <= helper->output()->devicePixelRatio()); + auto *viewport = helper->outputViewport(); + if (!viewport->offscreen()) + Q_ASSERT(viewport->output()->scale() <= viewport->devicePixelRatio()); - const auto &format = helper->qwoutput()->handle()->render_format; - const auto renderMatrix = helper->output()->renderMatrix(); + // An offscreen viewport borrows only the renderer/allocator and frame + // clock, not the output's size, opaque format or scanout constraints. + const auto format = viewport->offscreen() ? DRM_FORMAT_ARGB8888 + : helper->output()->render_format; + WBufferRenderer::RenderFlags flags = WBufferRenderer::RedirectOpenGLContextDefaultFrameBufferObject; + if (viewport->offscreen()) + flags |= WBufferRenderer::DontConfigureSwapchain; + const auto renderMatrix = viewport->renderMatrix(); // maybe using the other WOutputViewport's QSGTextureProvider - if (!helper->output()->depends().isEmpty()) + if (!helper->outputViewport()->depends().isEmpty()) updateDirtyNodes(); - qw_buffer *buffer = helper->beginRender(helper->bufferRenderer(), helper->output()->output()->size(), format, - WBufferRenderer::RedirectOpenGLContextDefaultFrameBufferObject); + wlr_buffer *buffer = helper->beginRender(helper->bufferRenderer(), viewport->effectiveBufferSize(), format, + flags, viewport->colorContentsMode()); Q_ASSERT(buffer == helper->bufferRenderer()->currentBuffer()); if (buffer) { helper->render(helper->bufferRenderer(), 0, renderMatrix, - helper->output()->effectiveSourceRect(), - helper->output()->targetRect(), - helper->output()->preserveColorContents()); + helper->outputViewport()->effectiveSourceRect(), + helper->outputViewport()->targetRect()); + } else { + failedViewports.append(viewport); } renderResults.append(helper); } @@ -1443,7 +1548,10 @@ WOutputRenderWindowPrivate::doRenderOutputs(const QList &outputs, needsCommit.reserve(renderResults.size()); for (auto helper : std::as_const(renderResults)) { auto bufferRenderer = helper->afterRender(); - if (bufferRenderer) + // A forced render may not acquire a new buffer, while an external + // output state transaction is still pending. WOutputHelper::commit() + // handles a null renderer by committing that state-only update. + if (bufferRenderer || helper->extraState()) needsCommit.append({helper, bufferRenderer}); } @@ -1456,25 +1564,29 @@ WOutputRenderWindowPrivate::doRenderOutputs(const QList &outputs, static void QQuickAnimatorController_advance(QQuickAnimatorController *ac) { bool running = false; - for (const QSharedPointer &job : std::as_const(ac->m_animationRoots)) { + for (const QSharedPointer &job : std::as_const(W_PRIVATE_MEMBER(*ac, QQuickAnimCtrl_m_animationRoots_tag{}))) { if (job->isRunning()) { running = true; break; } } - for (QQuickAnimatorJob *job : std::as_const(ac->m_runningAnimators)) + for (QQuickAnimatorJob *job : std::as_const(W_PRIVATE_MEMBER(*ac, QQuickAnimCtrl_m_runningAnimators_tag{}))) job->commit(); if (running) - ac->m_window->update(); + W_PRIVATE_MEMBER(*ac, QQuickAnimCtrl_m_window_tag{})->update(); } -void WOutputRenderWindowPrivate::doRender(const QList &outputs, +void WOutputRenderWindowPrivate::doRender(wlr_output *needsFrameOutput, + const QList &outputs, bool forceRender, bool doCommit) { Q_ASSERT(rendererList.isEmpty()); Q_ASSERT(!inRendering); + if (!renderEnabled) + return; + inRendering = true; W_Q(WOutputRenderWindow); @@ -1482,6 +1594,13 @@ void WOutputRenderWindowPrivate::doRender(const QList &outputs, layer->beforeRender(q); } + // Drive plain QML animations from the frame itself, so their values for + // this frame are taken before the scene is polished and synced. The + // driver is thread-local, so rendering has to happen on the thread that + // installed it. + if (animationDriver->isRunning()) + animationDriver->advance(); + rc()->polishItems(); if (QSGRendererInterface::isApiRhiBased(WRenderHelper::getGraphicsApi())) @@ -1492,7 +1611,8 @@ void WOutputRenderWindowPrivate::doRender(const QList &outputs, Q_EMIT q->beforeRendering(); runAndClearJobs(&beforeRenderingJobs); - auto needsCommit = doRenderOutputs(outputs, forceRender); + QList> failedViewports; + auto needsCommit = doRenderOutputs(needsFrameOutput, outputs, forceRender, failedViewports); Q_EMIT q->afterRendering(); runAndClearJobs(&afterRenderingJobs); @@ -1500,15 +1620,45 @@ void WOutputRenderWindowPrivate::doRender(const QList &outputs, if (QSGRendererInterface::isApiRhiBased(WRenderHelper::getGraphicsApi())) rc()->endFrame(); - if (doCommit) { + // prevent gles2-render exception in wlroots. + // wlroots may have render operations after commit, so do + // not move the location during the reset operation. + // eg: screencopy ext-image-capture + resetGlState(); + + QList> committedOutputs; + QList> renderedViewports; + { + committedOutputs.reserve(needsCommit.size()); for (auto i : std::as_const(needsCommit)) { - bool ok = i.first->commit(i.second); + // Explicit render(viewport, true) is used for state-only output + // transactions. It must not be suppressed merely because the + // transaction itself scheduled the next frame. + if (doCommit && !i.first->outputViewport()->offscreen() + && (forceRender || Q_UNLIKELY(!i.first->framePending()))) { + if (Q_LIKELY(i.first->commit(i.second))) { + // Make sure the output is still valid after commit + auto output = i.first->outputViewport()->output(); + if (Q_LIKELY(needsFrameOutput)) { + Q_ASSERT(output->handle() == needsFrameOutput); + if (committedOutputs.isEmpty()) + committedOutputs.append(output); + } else if (!committedOutputs.contains(output)) { + committedOutputs.append(output); + } + } + } - if (i.second->currentBuffer()) { + // End the buffer lifetime even for render(viewport, false). A + // capture must neither leave an open render nor pretend that its + // buffer was committed to the real output (frame callbacks). + if (i.second && i.second->currentBuffer()) { i.second->endRender(); + renderedViewports.append(i.first->outputViewport()); + failedViewports.removeAll(i.first->outputViewport()); } - i.first->resetState(ok); + i.first->resetState(); } } @@ -1523,12 +1673,35 @@ void WOutputRenderWindowPrivate::doRender(const QList &outputs, glContext->doneCurrent(); inRendering = false; - Q_EMIT q->renderEnd(); + + // Since the animation clock is advanced by the frame itself, the frame loop + // has to be kept running for as long as animations are alive: an animation + // that changes no rendered property would otherwise stop the repaint loop + // and freeze itself. QUnifiedTimer stops the driver once the last + // animation finishes, which ends the loop. + if (animationDriver->isRunning()) + q->update(); + + for (const auto &viewport : std::as_const(renderedViewports)) { + if (viewport) + Q_EMIT viewport->frameRendered(); + } + for (const auto &viewport : std::as_const(failedViewports)) { + if (viewport) + Q_EMIT viewport->frameRenderFailed(); + } + Q_EMIT q->renderEnd(committedOutputs); +} + +static QQuickRenderControl *createOutputRenderControl() +{ + WSGContext::ensureInstalled(); + return new RenderControl(); } // TODO: Support QWindow::setCursor WOutputRenderWindow::WOutputRenderWindow(QObject *parent) - : QQuickWindow(*new WOutputRenderWindowPrivate(this), new RenderControl()) + : QQuickWindow(*new WOutputRenderWindowPrivate(this), createOutputRenderControl()) { setObjectName(QW::RenderWindow::id()); @@ -1549,11 +1722,16 @@ WOutputRenderWindow::WOutputRenderWindow(QObject *parent) WOutputRenderWindow::~WOutputRenderWindow() { + Q_D(WOutputRenderWindow); + // Drop frame/needs_frame listeners while outputs are still usable; + // ~WListenerOwner teardowns cross-object groups automatically. + d->listenerOwner.reset(); + qGuiApp->removeEventFilter(this); renderControl()->disconnect(this); renderControl()->invalidate(); - renderControl()->deleteLater(); + delete renderControl(); } QQuickRenderControl *WOutputRenderWindow::renderControl() const @@ -1570,39 +1748,40 @@ void WOutputRenderWindow::attach(WOutputViewport *output) return; Q_ASSERT(output->output()); - bool initialRenderable = false; - bool initialContentIsDirty = false; - bool initialNeedsFrame = false; - for (const auto &helper : std::as_const(d->outputs)) { - Q_ASSERT(helper->output() != output); - if (helper->qwoutput() == output->output()->handle()) { - // For a new viewport, it should initialize state from viewports with the same output. - initialRenderable |= helper->renderable(); - initialContentIsDirty |= helper->contentIsDirty(); - initialNeedsFrame |= helper->needsFrame(); - } - } - auto newOutput = new OutputHelper(output, - this, - initialRenderable, - initialContentIsDirty, - initialNeedsFrame); + const bool containsOutput = d->containsOutput(output->output()); + auto newOutput = new OutputHelper(output, this, true); d->outputs << newOutput; d->sortOutputs(); if (d->m_renderer) { - auto qwoutput = newOutput->qwoutput(); - if (qwoutput->handle()->renderer != d->m_renderer->handle()) - qwoutput->init_render(d->m_allocator->handle(), d->m_renderer->handle()); + auto wlrOut = newOutput->output(); + if (wlrOut->renderer != d->m_renderer) + wlr_output_init_render(wlrOut, d->m_allocator, d->m_renderer); Q_EMIT outputViewportInitialized(output); } + if (!containsOutput) { + auto *wlrOut = newOutput->output(); + auto *woutput = output->output(); + auto *owner = d->listenerOwner.get(); + // On hot-unplug WBackend deletes WOutput from the native destroy + // callback; ~WOutput::teardown() drops this owner group before + // wlr_output_finish asserts empty frame/needs_frame lists. + // Only render the output whose frame event fired. Explicit render() + // calls still scan all outputs. + woutput->listeners(owner)->add(&wlrOut->events.frame, this, [d, wlrOut] { + d->doRender(wlrOut, d->outputs, false, true); + }); + woutput->listeners(owner)->add(&wlrOut->events.needs_frame, woutput, + &WOutput::scheduleFrame); + } + if (!d->isInitialized()) return; d->updateSceneDPR(); d->init(newOutput); - d->scheduleDoRender(); + newOutput->update(); if (!newOutput->layers().isEmpty()) { if (auto od = WOutputViewportPrivate::get(output)) { @@ -1624,6 +1803,16 @@ void WOutputRenderWindow::detach(WOutputViewport *output) auto outputHelper = d->outputs.takeAt(index); const auto hasLayer = !outputHelper->layers().isEmpty(); + + // During destruction, ~WOutputRenderWindow() already reset + // listenerOwner — teardown() removed all listener groups from every + // WOutput. Calling removeListeners here is redundant and triggers + // "no listener group" warnings (or Q_ASSERT on null owner). + if (!d->inDestructor) { + if (auto *woutput = output->output(); woutput && !d->containsOutput(woutput)) + woutput->removeListeners(d->listenerOwner.get()); + } + outputHelper->invalidate(); outputHelper->deleteLater(); @@ -1650,10 +1839,14 @@ void WOutputRenderWindow::attach(WOutputLayer *layer, WOutputViewport *output) auto outputHelper = d->getOutputHelper(output); if (outputHelper && outputHelper->attachLayer(wapper)) - d->scheduleDoRender(); + outputHelper->scheduleFrame(); - connect(layer, &WOutputLayer::flagsChanged, this, &WOutputRenderWindow::scheduleRender); - connect(layer, &WOutputLayer::zChanged, this, &WOutputRenderWindow::scheduleRender); + connect(layer, &WOutputLayer::flagsChanged, + outputHelper, &WOutputHelper::scheduleFrame); + connect(layer, &WOutputLayer::colorContentsModeChanged, + outputHelper, &WOutputHelper::scheduleFrame); + connect(layer, &WOutputLayer::zChanged, + outputHelper, &WOutputHelper::scheduleFrame); if (auto od = WOutputViewportPrivate::get(output)) { od->notifyLayersChanged(); @@ -1694,15 +1887,15 @@ void WOutputRenderWindow::detach(WOutputLayer *layer, WOutputViewport *output) Q_ASSERT(wapper->outputs().contains(output)); wapper->outputs().removeOne(output); - bool ok = layer->disconnect(this); - Q_ASSERT(ok); - auto outputHelper = d->getOutputHelper(output); if (!outputHelper) return; + bool ok = layer->disconnect(outputHelper); + Q_ASSERT(ok); + outputHelper->detachLayer(wapper); - d->scheduleDoRender(); + outputHelper->scheduleFrame(); if (auto od = WOutputViewportPrivate::get(output)) { od->notifyLayersChanged(); @@ -1743,27 +1936,14 @@ QList WOutputRenderWindow::hardwareLayers(const WOutputViewport return list; } -void WOutputRenderWindow::setOutputScale(WOutputViewport *output, float scale) +WOutputHelper *WOutputRenderWindow::getOutputHelper(WOutputViewport *output) const { - Q_D(WOutputRenderWindow); - - if (auto helper = d->getOutputHelper(output)) { - helper->setScale(scale); - update(); - } + Q_D(const WOutputRenderWindow); + return d->getOutputHelper(output); } -void WOutputRenderWindow::rotateOutput(WOutputViewport *output, WOutput::Transform t) -{ - Q_D(WOutputRenderWindow); - - if (auto helper = d->getOutputHelper(output)) { - helper->setTransform(t); - update(); - } -} -void WOutputRenderWindow::init(qw_renderer *renderer, qw_allocator *allocator) +void WOutputRenderWindow::init(wlr_renderer *renderer, wlr_allocator *allocator) { Q_D(WOutputRenderWindow); Q_ASSERT(!d->m_renderer); @@ -1775,10 +1955,10 @@ void WOutputRenderWindow::init(qw_renderer *renderer, qw_allocator *allocator) d->m_allocator = allocator; for (auto output : std::as_const(d->outputs)) { - auto qwoutput = output->qwoutput(); - if (qwoutput->handle()->renderer != d->m_renderer->handle()) - qwoutput->init_render(d->m_allocator->handle(), d->m_renderer->handle()); - Q_EMIT outputViewportInitialized(output->output()); + auto wlrOut = output->output(); + if (wlrOut->renderer != d->m_renderer) + wlr_output_init_render(wlrOut, d->m_allocator, d->m_renderer); + Q_EMIT outputViewportInitialized(output->outputViewport()); } if (d->componentCompleted) { @@ -1786,13 +1966,13 @@ void WOutputRenderWindow::init(qw_renderer *renderer, qw_allocator *allocator) } } -qw_renderer *WOutputRenderWindow::renderer() const +wlr_renderer *WOutputRenderWindow::renderer() const { Q_D(const WOutputRenderWindow); return d->m_renderer; } -qw_allocator *WOutputRenderWindow::allocator() const +wlr_allocator *WOutputRenderWindow::allocator() const { Q_D(const WOutputRenderWindow); return d->m_allocator; @@ -1810,6 +1990,23 @@ bool WOutputRenderWindow::inRendering() const return d->inRendering; } +bool WOutputRenderWindow::renderEnabled() const +{ + Q_D(const WOutputRenderWindow); + return d->renderEnabled; +} + +void WOutputRenderWindow::setRenderEnabled(bool enabled) +{ + Q_D(WOutputRenderWindow); + if (d->renderEnabled == enabled) + return; + d->renderEnabled = enabled; + if (enabled) + update(); + Q_EMIT renderEnabledChanged(); +} + QList> WOutputRenderWindow::paintOrderItemList(QQuickItem *root, std::function filter) { QStack nodes; @@ -1849,7 +2046,7 @@ void WOutputRenderWindow::setDisableLayers(bool newDisableLayers) void WOutputRenderWindow::render() { Q_D(WOutputRenderWindow); - d->doRender(); + d->doRender(nullptr, d->outputs, false, true); } void WOutputRenderWindow::render(WOutputViewport *output, bool doCommit) @@ -1858,20 +2055,14 @@ void WOutputRenderWindow::render(WOutputViewport *output, bool doCommit) int index = d->indexOfOutputHelper(output); Q_ASSERT(index >= 0); - d->doRender({d->outputs.at(index)}, true, doCommit); -} - -void WOutputRenderWindow::scheduleRender() -{ - Q_D(WOutputRenderWindow); - d->scheduleDoRender(); + d->doRender(nullptr, {d->outputs.at(index)}, true, doCommit); } void WOutputRenderWindow::update() { Q_D(WOutputRenderWindow); for (auto o : std::as_const(d->outputs)) - o->update(); // will scheduleDoRender + o->update(); } void WOutputRenderWindow::update(WOutputViewport *output) @@ -1880,7 +2071,6 @@ void WOutputRenderWindow::update(WOutputViewport *output) int index = d->indexOfOutputHelper(output); Q_ASSERT(index >= 0); d->outputs.at(index)->update(); - d->scheduleDoRender(); } qreal WOutputRenderWindow::width() const @@ -1946,14 +2136,6 @@ void WOutputRenderWindow::componentComplete() bool WOutputRenderWindow::event(QEvent *event) { - Q_D(WOutputRenderWindow); - - if (event->type() == doRenderEventType) { - QCoreApplication::removePostedEvents(this, doRenderEventType); - d_func()->doRender(); - return true; - } - if (QW::RenderWindow::beforeDisposeEventFilter(this, event)) { event->accept(); QW::RenderWindow::afterDisposeEventFilter(this, event); @@ -1971,10 +2153,9 @@ bool WOutputRenderWindow::eventFilter(QObject *watched, QEvent *event) { if (event->isInputEvent() && watched->isQuickItemType()) { auto ie = static_cast(event); - auto device = WInputDevice::from(ie->device()); - Q_ASSERT(device); - Q_ASSERT(device->seat()); - if (device->seat()->filterEventBeforeDisposeStage(qobject_cast(watched), ie)) + auto seat = WSeat::fromInputEvent(ie); + if (!seat) return true; + if (seat->filterEventBeforeDisposeStage(qobject_cast(watched), ie)) return true; } diff --git a/waylib/src/server/qtquick/woutputrenderwindow.h b/waylib/src/server/qtquick/woutputrenderwindow.h index ca8a56d914..76dfbe1e32 100644 --- a/waylib/src/server/qtquick/woutputrenderwindow.h +++ b/waylib/src/server/qtquick/woutputrenderwindow.h @@ -1,11 +1,10 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include #include -#include #include #include @@ -17,6 +16,7 @@ WAYLIB_SERVER_BEGIN_NAMESPACE class WOutputViewport; class WOutputLayer; class WBufferRenderer; +class WOutputHelper; class WOutputRenderWindowPrivate; class WAYLIB_SERVER_EXPORT WOutputRenderWindow : public QQuickWindow, public QQmlParserStatus { @@ -42,19 +42,20 @@ class WAYLIB_SERVER_EXPORT WOutputRenderWindow : public QQuickWindow, public QQm WOutputViewport *mapFrom, QQuickItem *mapTo); void detach(WOutputLayer *layer, WOutputViewport *output); - void setOutputScale(WOutputViewport *output, float scale); - void rotateOutput(WOutputViewport *output, WOutput::Transform t); - void setOutputEnabled(WOutputViewport *output, bool enabled); + WOutputHelper *getOutputHelper(WOutputViewport *output) const; - void init(QW_NAMESPACE::qw_renderer *renderer, QW_NAMESPACE::qw_allocator *allocator); - QW_NAMESPACE::qw_renderer *renderer() const; - QW_NAMESPACE::qw_allocator *allocator() const; + void init(wlr_renderer *renderer, wlr_allocator *allocator); + wlr_renderer *renderer() const; + wlr_allocator *allocator() const; qreal width() const; qreal height() const; WBufferRenderer *currentRenderer() const; bool inRendering() const; + bool renderEnabled() const; + void setRenderEnabled(bool enabled); + static QList> paintOrderItemList(QQuickItem *root, std::function filter); bool disableLayers() const; @@ -63,7 +64,6 @@ class WAYLIB_SERVER_EXPORT WOutputRenderWindow : public QQuickWindow, public QQm public Q_SLOTS: void render(); void render(WOutputViewport *output, bool doCommit); - void scheduleRender(); void update(); void update(WOutputViewport *output); void setWidth(qreal arg); @@ -76,7 +76,8 @@ public Q_SLOTS: void outputViewportInitialized(WAYLIB_SERVER_NAMESPACE::WOutputViewport *output); void initialized(); void disableLayersChanged(); - void renderEnd(); + void renderEnabledChanged(); + void renderEnd(QList> committedOutputs); void effectiveDevicePixelRatioChanged(qreal scale); private: diff --git a/waylib/src/server/qtquick/woutputviewport.cpp b/waylib/src/server/qtquick/woutputviewport.cpp index cd262493e7..fd60d92a30 100644 --- a/waylib/src/server/qtquick/woutputviewport.cpp +++ b/waylib/src/server/qtquick/woutputviewport.cpp @@ -1,19 +1,18 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "woutputviewport.h" #include "woutputviewport_p.h" #include "woutput.h" +#include "woutputhelper.h" #include "wsgtextureprovider.h" #include "wbufferrenderer_p.h" -#include -#include +#include #include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE void WOutputViewportPrivate::init() @@ -42,7 +41,7 @@ void WOutputViewportPrivate::initForOutput() attached = true; } - output->safeConnect(&WOutput::modeChanged, q, [this] { + QObject::connect(output, &WOutput::modeChanged, q, [this] { updateImplicitSize(); }); @@ -77,8 +76,6 @@ void WOutputViewportPrivate::updateImplicitSize() void WOutputViewportPrivate::updateRenderBufferSource() { - W_Q(WOutputViewport); - QList sources; if (input) { @@ -92,7 +89,7 @@ void WOutputViewportPrivate::updateRenderBufferSource() sources.append(extraRenderSource); forceRender = true; - bufferRenderer->setSourceList(sources, true); + bufferRenderer->setSourceList(sources, hideSource); } void WOutputViewportPrivate::setExtraRenderSource(QQuickItem *source) @@ -118,9 +115,12 @@ void WOutputViewport::invalidate() { W_D(WOutputViewport); if (d->componentComplete && d->output && d->window) { + // detach() can synchronously notify layer changes after removing this + // viewport from the render window. Mark it detached first so slots + // querying layers during that notification don't look it up again. + d->attached = false; d->outputWindow()->detach(this); d->output = nullptr; - d->attached = false; } } @@ -253,9 +253,56 @@ void WOutputViewport::setOffscreen(bool newOffscreen) if (d->offscreen == newOffscreen) return; d->offscreen = newOffscreen; + d->update(); Q_EMIT offscreenChanged(); } +bool WOutputViewport::hideSource() const +{ + W_DC(WOutputViewport); + return d->hideSource; +} + +void WOutputViewport::setHideSource(bool hideSource) +{ + W_D(WOutputViewport); + if (d->hideSource == hideSource) + return; + d->hideSource = hideSource; + if (d->output) + d->updateRenderBufferSource(); + Q_EMIT hideSourceChanged(); +} + +QSize WOutputViewport::bufferSize() const +{ + W_DC(WOutputViewport); + return d->bufferSize; +} + +void WOutputViewport::setBufferSize(const QSize &size) +{ + W_D(WOutputViewport); + if (d->bufferSize == size) + return; + d->bufferSize = size; + d->update(); + Q_EMIT bufferSizeChanged(); +} + +QSize WOutputViewport::effectiveBufferSize() const +{ + W_DC(WOutputViewport); + return d->bufferSize.isEmpty() ? (d->output ? d->output->size() : QSize()) + : d->bufferSize; +} + +wlr_swapchain *WOutputViewport::swapchain() const +{ + W_DC(WOutputViewport); + return d->bufferRenderer->swapchain(); +} + bool WOutputViewport::cacheBuffer() const { W_DC(WOutputViewport); @@ -268,19 +315,19 @@ void WOutputViewport::setCacheBuffer(bool newCacheBuffer) d->bufferRenderer->setCacheBuffer(newCacheBuffer); } -bool WOutputViewport::preserveColorContents() const +WGlobal::ColorContentsMode WOutputViewport::colorContentsMode() const { W_DC(WOutputViewport); - return d->preserveColorContents; + return d->colorContentsMode; } -void WOutputViewport::setPreserveColorContents(bool newPreserveColorContents) +void WOutputViewport::setColorContentsMode(WGlobal::ColorContentsMode mode) { W_D(WOutputViewport); - if (d->preserveColorContents == newPreserveColorContents) + if (d->colorContentsMode == mode) return; - d->preserveColorContents = newPreserveColorContents; - Q_EMIT preserveColorContentsChanged(); + d->colorContentsMode = mode; + Q_EMIT colorContentsModeChanged(); } bool WOutputViewport::live() const @@ -388,7 +435,7 @@ QTransform WOutputViewport::sourceRectToTargetRectTransfrom() const { return WBufferRenderer::inputMapToOutput(effectiveSourceRect(), targetRect(), - output()->size(), + effectiveBufferSize(), devicePixelRatio()); } @@ -496,15 +543,31 @@ void WOutputViewport::setDepends(const QList &newDepends) void WOutputViewport::setOutputScale(float scale) { W_D(WOutputViewport); - if (auto window = d->outputWindow()) - window->setOutputScale(this, scale); + auto *window = d->outputWindow(); + auto *helper = window ? window->getOutputHelper(this) : nullptr; + if (!helper) + return; + WOutputHelper::ExtraState extra = helper->extraState(); + if (!extra) + extra = WOutputHelper::ExtraState(); + wlr_output_state_set_scale(extra.get(), scale); + if (helper->setExtraState(extra)) + d->output->scheduleFrame(); } void WOutputViewport::rotateOutput(WOutput::Transform t) { W_D(WOutputViewport); - if (auto window = d->outputWindow()) - window->rotateOutput(this, t); + auto *window = d->outputWindow(); + auto *helper = window ? window->getOutputHelper(this) : nullptr; + if (!helper) + return; + WOutputHelper::ExtraState extra = helper->extraState(); + if (!extra) + extra = WOutputHelper::ExtraState(); + wlr_output_state_set_transform(extra.get(), static_cast(t)); + if (helper->setExtraState(extra)) + d->output->scheduleFrame(); } void WOutputViewport::render(bool doCommit) diff --git a/waylib/src/server/qtquick/woutputviewport.h b/waylib/src/server/qtquick/woutputviewport.h index cc3589ef37..17f447ad5b 100644 --- a/waylib/src/server/qtquick/woutputviewport.h +++ b/waylib/src/server/qtquick/woutputviewport.h @@ -1,4 +1,4 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once @@ -6,7 +6,6 @@ #include #include #include -#include #include @@ -24,8 +23,10 @@ class WAYLIB_SERVER_EXPORT WOutputViewport : public QQuickItem, public virtual W Q_PROPERTY(QQuickTransform* viewportTransform READ viewportTransform WRITE setViewportTransform NOTIFY viewportTransformChanged FINAL) Q_PROPERTY(qreal devicePixelRatio READ devicePixelRatio WRITE setDevicePixelRatio NOTIFY devicePixelRatioChanged) Q_PROPERTY(bool offscreen READ offscreen WRITE setOffscreen NOTIFY offscreenChanged) + Q_PROPERTY(bool hideSource READ hideSource WRITE setHideSource NOTIFY hideSourceChanged FINAL) + Q_PROPERTY(QSize bufferSize READ bufferSize WRITE setBufferSize NOTIFY bufferSizeChanged FINAL) Q_PROPERTY(bool cacheBuffer READ cacheBuffer WRITE setCacheBuffer NOTIFY cacheBufferChanged FINAL) - Q_PROPERTY(bool preserveColorContents READ preserveColorContents WRITE setPreserveColorContents NOTIFY preserveColorContentsChanged FINAL) + Q_PROPERTY(WGlobal::ColorContentsMode colorContentsMode READ colorContentsMode WRITE setColorContentsMode NOTIFY colorContentsModeChanged FINAL) Q_PROPERTY(bool live READ live WRITE setLive NOTIFY liveChanged FINAL) Q_PROPERTY(QRectF sourceRect READ sourceRect WRITE setSourceRect RESET resetSourceRect NOTIFY sourceRectChanged FINAL) Q_PROPERTY(QRectF targetRect READ targetRect WRITE setTargetRect RESET resetTargetRect NOTIFY targetRectChanged FINAL) @@ -64,11 +65,22 @@ class WAYLIB_SERVER_EXPORT WOutputViewport : public QQuickItem, public virtual W bool offscreen() const; void setOffscreen(bool newOffscreen); + // Controls whether source items are hidden from the main scene. + bool hideSource() const; + void setHideSource(bool hideSource); + + // An empty size uses the output mode. Offscreen viewports can instead use + // a window-sized buffer without changing the output's mode or swapchain. + QSize bufferSize() const; + void setBufferSize(const QSize &size); + QSize effectiveBufferSize() const; + wlr_swapchain *swapchain() const; + bool cacheBuffer() const; void setCacheBuffer(bool newCacheBuffer); - bool preserveColorContents() const; - void setPreserveColorContents(bool newPreserveColorContents); + WGlobal::ColorContentsMode colorContentsMode() const; + void setColorContentsMode(WGlobal::ColorContentsMode mode); bool live() const; void setLive(bool newLive); @@ -111,8 +123,12 @@ public Q_SLOTS: Q_SIGNALS: void devicePixelRatioChanged(); void offscreenChanged(); + void hideSourceChanged(); + void bufferSizeChanged(); + void frameRendered(); + void frameRenderFailed(); void cacheBufferChanged(); - void preserveColorContentsChanged(); + void colorContentsModeChanged(); void outputRenderInitialized(); void inputChanged(); void liveChanged(); diff --git a/waylib/src/server/qtquick/wqmlcreator.cpp b/waylib/src/server/qtquick/wqmlcreator.cpp index c82105b40f..5081ecc42c 100644 --- a/waylib/src/server/qtquick/wqmlcreator.cpp +++ b/waylib/src/server/qtquick/wqmlcreator.cpp @@ -1,15 +1,19 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 JiDe Zhang . // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wqmlcreator_p.h" +#include "wayliblogging.h" #include "wxdgsurface.h" #include #include #include -#define private public #include -#undef private +#include "private/wprivateaccessor_p.h" + +#if QT_VERSION >= QT_VERSION_CHECK(6, 10, 0) +W_DECLARE_PRIVATE_MEMBER(QQmlComponentPrivate_m_state_tag, QQmlComponentPrivate, m_state, QQmlComponentPrivate::ConstructionState); +#endif WAYLIB_SERVER_BEGIN_NAMESPACE @@ -205,20 +209,12 @@ void WQmlCreatorComponent::create(QSharedPointer data) Q_ASSERT(m_delegate); auto d = QQmlComponentPrivate::get(m_delegate); -#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) #if QT_VERSION >= QT_VERSION_CHECK(6, 10, 0) - if (d->m_state.isCompletePending()) { + if (W_PRIVATE_MEMBER(*d, QQmlComponentPrivate_m_state_tag{}).isCompletePending()) { #else if (d->state.isCompletePending()) { #endif QMetaObject::invokeMethod(this, "create", Qt::QueuedConnection, data, parent, data->data.lock()->properties); -#else - if (d->state.completePending) { - QMetaObject::invokeMethod(this, "create", Qt::QueuedConnection, - Q_ARG(QSharedPointer, data), - Q_ARG(QObject *, parent), - Q_ARG(const QJSValue &, data->data.lock()->properties)); -#endif } else { create(data, parent, data->data.lock()->properties); } @@ -229,11 +225,9 @@ void WQmlCreatorComponent::create(QSharedPointer data, auto d = QQmlComponentPrivate::get(m_delegate); #if QT_VERSION >= QT_VERSION_CHECK(6, 10, 0) - Q_ASSERT(!d->m_state.isCompletePending()); -#elif QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) - Q_ASSERT(!d->state.isCompletePending()); + Q_ASSERT(!W_PRIVATE_MEMBER(*d, QQmlComponentPrivate_m_state_tag{}).isCompletePending()); #else - Q_ASSERT(!d->state.completePending); + Q_ASSERT(!d->state.isCompletePending()); #endif // Don't use QVariantMap instead of QJSValue, because initial properties may be // contains some QObject property , if that QObjects is destroyed in future, @@ -242,51 +236,29 @@ void WQmlCreatorComponent::create(QSharedPointer data, // you will get a null pointer if you using after it's destroyed. const auto tmp = qvariant_cast(initialProperties.toVariant()); -#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) auto context = new QQmlContext(qmlContext(this), this); context->setContextProperties(m_contextProperties); - data->object = d->createWithProperties(parent, tmp, context); - context->setParent(data->object); +#if QT_VERSION >= QT_VERSION_CHECK(6, 12, 0) + // Qt 6.12 turned CreateBehavior into an enum class and gave the parameter no + // default value. CreateBehavior::Cpp is the equivalent of the old CreateDefault. + data->object = + d->createWithProperties(parent, tmp, context, QQmlComponentPrivate::CreateBehavior::Cpp); #else - // The `createWithInitialProperties` provided by QQmlComponent cannot set parent - // during the creation process. use `setParent` will too late as the creation has - // complete, lead to the windows of WOutputRenderWindow get empty... - - // for Qt 6.5 The createWithInitialProperties with the parent parameter provided by - // QQmlComponentPrivate can solve this problem. - // Qt 6.4 requires beginCreate -> setInitialProperties/setParent -> completeCreate - - QObject *rv = m_delegate->beginCreate(qmlContext(this)); - if (rv) { - m_delegate->setInitialProperties(rv, tmp); - rv->setParent(parent); - if (auto item = qobject_cast(rv)) - item->setParentItem(qobject_cast(parent)); - m_delegate->completeCreate(); - if (!d->requiredProperties().empty()) { - for (const auto &unsetRequiredProperty : std::as_const(d->requiredProperties())) { - const QQmlError error = QQmlComponentPrivate::unsetRequiredPropertyToQQmlError(unsetRequiredProperty); - qmlWarning(rv, error); - } - d->requiredProperties().clear(); - rv->deleteLater(); - rv = nullptr; - } - } - data->object = rv; + data->object = d->createWithProperties(parent, tmp, context); #endif + context->setParent(data->object); if (data->object) { Q_EMIT objectAdded(data->object, initialProperties); notifyCreatorObjectAdded(creator(), data->object, initialProperties); } else { - qWarning() << "WQmlCreatorComponent::create failed" << "parent=" << parent << "initialProperties=" << tmp; + qCWarning(lcWlQmlCreator) << "WQmlCreatorComponent::create failed" << "parent=" << parent << "initialProperties=" << tmp; #if QT_VERSION >= QT_VERSION_CHECK(6, 10, 0) - for (auto e: d->m_state.errors) + for (auto e: std::as_const(W_PRIVATE_MEMBER(*d, QQmlComponentPrivate_m_state_tag{}).errors)) #else - for (auto e: d->state.errors) + for (auto e: std::as_const(d->state.errors)) #endif - qWarning() << e.error; + qCWarning(lcWlQmlCreator) << e.error; } } diff --git a/waylib/src/server/qtquick/wquickcursor.cpp b/waylib/src/server/qtquick/wquickcursor.cpp index 9d5089a3cc..f3bd793b84 100644 --- a/waylib/src/server/qtquick/wquickcursor.cpp +++ b/waylib/src/server/qtquick/wquickcursor.cpp @@ -1,7 +1,9 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wquickcursor.h" +#include +#include "wayliblogging.h" #include "woutputrenderwindow.h" #include "woutputitem.h" #include "wcursorimage.h" @@ -11,16 +13,12 @@ #include "wsurfaceitem.h" #include "wrenderhelper.h" -#include -#include -#include -#include +#include #include #include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN CursorTextureProvider : public WSGTextureProvider @@ -38,9 +36,8 @@ class Q_DECL_HIDDEN CursorTextureProvider : public WSGTextureProvider return; } - // WImageBufferImpl destroy following qw_buffer - auto buffer = qw_buffer::create(new WImageBufferImpl(image), - image.width(), image.height()); + // WImageBufferImpl owns the wlr_buffer; drop it with the provider. + auto *buffer = (new WImageBufferImpl(image))->handle(); this->buffer.reset(buffer); setBuffer(this->buffer.get()); } @@ -78,18 +75,18 @@ class Q_DECL_HIDDEN CursorTextureProvider : public WSGTextureProvider return proxy->texture(); return WSGTextureProvider::texture(); } - qw_texture *qwTexture() const override { + wlr_texture *qwTexture() const override { if (proxy) return proxy->qwTexture(); return WSGTextureProvider::qwTexture(); } - qw_buffer *qwBuffer() const override { + wlr_buffer *wlrBuffer() const override { if (proxy) - return proxy->qwBuffer(); - return WSGTextureProvider::qwBuffer(); + return proxy->wlrBuffer(); + return WSGTextureProvider::wlrBuffer(); } - std::unique_ptr buffer; + WBufferDropPtr buffer; QPointer proxy; }; @@ -151,7 +148,7 @@ class Q_DECL_HIDDEN WQuickCursorPrivate : public QQuickItemPrivate mutable CursorTextureProvider *textureProvider = nullptr; - WCursor *cursor = nullptr; + QPointer cursor; QPointer output; WCursorImage *cursorImage = nullptr; @@ -366,7 +363,7 @@ WSGTextureProvider *WQuickCursor::wTextureProvider() const auto w = qobject_cast(d->window); if (!w || !d->sceneGraphRenderContext() || QThread::currentThread() != d->sceneGraphRenderContext()->thread()) { - qWarning("WQuickCursor::textureProvider: can only be queried on the rendering thread of an WOutputRenderWindow"); + qCWarning(lcWlQuickCursor, "WQuickCursor::textureProvider: can only be queried on the rendering thread of an WOutputRenderWindow"); return nullptr; } @@ -453,6 +450,7 @@ void WQuickCursor::setThemeName(const QString &name) if (d->xcursorThemeName == name) return; d->xcursorThemeName = name; + Q_EMIT themeNameChanged(); if (isComponentComplete()) QMetaObject::invokeMethod(this, "updateXCursorManager", Qt::QueuedConnection); } @@ -470,6 +468,7 @@ void WQuickCursor::setSourceSize(const QSize &size) if (d->cursorSize == size) return; d->cursorSize = size; + Q_EMIT sourceSizeChanged(); if (isComponentComplete()) QMetaObject::invokeMethod(this, "updateXCursorManager", Qt::QueuedConnection); } @@ -573,7 +572,7 @@ QSGNode *WQuickCursor::updatePaintNode(QSGNode *node, UpdatePaintNodeData *) tp->setImage(d->cursorImage->image()); } - // Ignore the tp->proxy, Don't use tp->qwBuffer() + // Ignore the tp->proxy, Don't use tp->wlrBuffer() if (!tp->buffer) { delete node; return nullptr; @@ -602,7 +601,10 @@ void WQuickCursor::releaseResources() d->invalidate(); // Force to update the contents, avoid to render the invalid textures - QQuickItemPrivate::get(this)->dirty(QQuickItemPrivate::Content); + // Only mark dirty if we have a valid window to avoid crashes during window destruction + if (window()) { + QQuickItemPrivate::get(this)->dirty(QQuickItemPrivate::Content); + } } WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/qtquick/wquickobserver.cpp b/waylib/src/server/qtquick/wquickobserver.cpp index bc8a8e09f6..95cdfbd232 100644 --- a/waylib/src/server/qtquick/wquickobserver.cpp +++ b/waylib/src/server/qtquick/wquickobserver.cpp @@ -39,9 +39,6 @@ class Q_DECL_HIDDEN WQuickObserverPrivate : public QQuickItemPrivate QMetaObject::Connection windowXChangeConnection; QMetaObject::Connection windowYChangeConnection; -#if QT_VERSION < QT_VERSION_CHECK(6, 5, 0) - bool inDestructor = false; -#endif }; @@ -51,14 +48,6 @@ WQuickObserver::WQuickObserver(QQuickItem *parent) setFlag(ItemObservesViewport); } -#if QT_VERSION < QT_VERSION_CHECK(6, 5, 0) -WQuickObserver::~WQuickObserver() -{ - Q_D(WQuickObserver); - d->inDestructor = true; -} -#endif - const QPointF WQuickObserver::globalPosition() const { if (!parentItem()) diff --git a/waylib/src/server/qtquick/wquickobserver.h b/waylib/src/server/qtquick/wquickobserver.h index 8d8bf54997..afc3cc7b79 100644 --- a/waylib/src/server/qtquick/wquickobserver.h +++ b/waylib/src/server/qtquick/wquickobserver.h @@ -22,10 +22,6 @@ class WAYLIB_SERVER_EXPORT WQuickObserver : public QQuickItem public: explicit WQuickObserver(QQuickItem *parent = nullptr); -#if QT_VERSION < QT_VERSION_CHECK(6, 5, 0) - ~WQuickObserver(); -#endif - const QPointF globalPosition() const; const QPointF scenePosition() const; diff --git a/waylib/src/server/qtquick/wquickoutputlayout.cpp b/waylib/src/server/qtquick/wquickoutputlayout.cpp index 889d4861fa..8e6c7acdde 100644 --- a/waylib/src/server/qtquick/wquickoutputlayout.cpp +++ b/waylib/src/server/qtquick/wquickoutputlayout.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wquickoutputlayout.h" @@ -7,12 +7,10 @@ #include "woutput.h" #include "woutputlayout.h" -#include -#include +#include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WQuickOutputLayoutPrivate : public WOutputLayoutPrivate @@ -49,7 +47,6 @@ void WQuickOutputLayout::add(WOutputItem *output) add(output->output(), output->globalPosition().toPoint()); auto updateOutput = [d, this] { - W_D(WQuickOutputLayout); auto *output = qobject_cast(sender()); if (!output) // Maybe output has destroyed but event still in queue return; diff --git a/waylib/src/server/qtquick/wquickoutputlayout.h b/waylib/src/server/qtquick/wquickoutputlayout.h index f492a048ff..d290547ace 100644 --- a/waylib/src/server/qtquick/wquickoutputlayout.h +++ b/waylib/src/server/qtquick/wquickoutputlayout.h @@ -19,6 +19,7 @@ class WAYLIB_SERVER_EXPORT WQuickOutputLayout : public WOutputLayout Q_OBJECT W_DECLARE_PRIVATE(WQuickOutputLayout) QML_NAMED_ELEMENT(OutputLayout) + QML_UNCREATABLE("Cannot create OutputLayout from QML") Q_PROPERTY(QList outputs READ outputs NOTIFY outputsChanged) public: diff --git a/waylib/src/server/qtquick/wquicktextureproxy.cpp b/waylib/src/server/qtquick/wquicktextureproxy.cpp index 8fdbd92a2a..ee4de967d2 100644 --- a/waylib/src/server/qtquick/wquicktextureproxy.cpp +++ b/waylib/src/server/qtquick/wquicktextureproxy.cpp @@ -12,7 +12,6 @@ WAYLIB_SERVER_BEGIN_NAMESPACE WQuickTextureProxyPrivate::~WQuickTextureProxyPrivate() { - initSourceItem(sourceItem, nullptr); } #define LAYER "__layer_enabled_by_WQuickTextureProxy" @@ -21,6 +20,9 @@ void WQuickTextureProxyPrivate::initSourceItem(QQuickItem *old, QQuickItem *item { W_Q(WQuickTextureProxy); + if (textureChangedConnection) + QObject::disconnect(textureChangedConnection); + if (old) { old->disconnect(q); QQuickItemPrivate *sd = QQuickItemPrivate::get(old); @@ -64,7 +66,8 @@ WQuickTextureProxy::WQuickTextureProxy(QQuickItem *parent) WQuickTextureProxy::~WQuickTextureProxy() { - + W_D(WQuickTextureProxy); + d->initSourceItem(d->sourceItem, nullptr); } QQuickItem *WQuickTextureProxy::sourceItem() const @@ -239,8 +242,23 @@ QSGNode *WQuickTextureProxy::updatePaintNode(QSGNode *old, QQuickItem::UpdatePai const auto tp = d->sourceItem->textureProvider(); if (Q_LIKELY(!tp || !tp->texture())) { if (tp) { - connect(tp, &QSGTextureProvider::textureChanged, - this, &WQuickTextureProxy::update, Qt::SingleShotConnection); + d->connectionMutex.lock(); + // QObject's automatic signal disconnection occurs in QObject::~QObject, + // where the slot function is a QQuickItem function. + // If the textureChanged signal is triggered during WQuickTextureProxy::~WQuickTextureProxy(), + // the program will crash because the signal connection has not been disconnected yet, + // but WQuickTextureProxy may have been partially destroyed. + // This can happen if someone is listening to the WQuickTextureProxy::destroyed signal and, + // within it, performs some operation that triggers textureChanged on the textureProvider. + // Therefore, the approach here is to use QMetaObject::Connection for storage and + // disconnect the signal when destroying WQuickTextureProxy to avoid disconnecting + // the signal too late. + if (d->textureChangedConnection) + QObject::disconnect(d->textureChangedConnection); + + d->textureChangedConnection = connect(tp, &QSGTextureProvider::textureChanged, + this, &WQuickTextureProxy::update, Qt::SingleShotConnection); + d->connectionMutex.unlock(); } delete old; return nullptr; diff --git a/waylib/src/server/qtquick/wrenderbufferblitter.cpp b/waylib/src/server/qtquick/wrenderbufferblitter.cpp index f10e63514a..9443bd6469 100644 --- a/waylib/src/server/qtquick/wrenderbufferblitter.cpp +++ b/waylib/src/server/qtquick/wrenderbufferblitter.cpp @@ -25,9 +25,39 @@ class Q_DECL_HIDDEN BlitTextureProvider : public QSGTextureProvider { } inline void setTexture(QSGTexture *tex) { m_texture = tex; + updateTextureOptions(); + } + + inline void setSmooth(bool smooth) { + if (m_smooth == smooth) + return; + + m_smooth = smooth; + updateTextureOptions(); + Q_EMIT textureChanged(); + } + + inline void setAntialiasing(bool antialiasing) { + if (m_antialiasing == antialiasing) + return; + + m_antialiasing = antialiasing; + updateTextureOptions(); + Q_EMIT textureChanged(); } private: + inline void updateTextureOptions() { + if (!m_texture) + return; + + m_texture->setFiltering(m_smooth ? QSGTexture::Linear : QSGTexture::Nearest); + m_texture->setAnisotropyLevel(m_antialiasing ? QSGTexture::Anisotropy4x : QSGTexture::AnisotropyNone); + } + + bool m_antialiasing = false; + bool m_smooth = false; + QSGTexture *m_texture = nullptr; }; @@ -62,7 +92,7 @@ class Q_DECL_HIDDEN WRenderBufferBlitterPrivate : public WObjectPrivate void cleanTextureProvider(); W_DECLARE_PUBLIC(WRenderBufferBlitter) - Content *content; + Content *content = nullptr; QQuickItem *container = nullptr; mutable BlitTextureProvider *tp = nullptr; }; @@ -104,7 +134,8 @@ class Q_DECL_HIDDEN Content : public QQuickItem if (newOffscreen) disconnect(d()->tp, &BlitTextureProvider::textureChanged, this, &Content::update); else - connect(d()->tp, &BlitTextureProvider::textureChanged, this, &Content::update); + connect(d()->tp, &BlitTextureProvider::textureChanged, + this, &Content::update, Qt::UniqueConnection); } setFlag(ItemHasContents, !newOffscreen); @@ -157,10 +188,15 @@ BlitTextureProvider *WRenderBufferBlitterPrivate::ensureTextureProvider() const if (Q_LIKELY(tp)) return tp; + auto q = const_cast(q_func()); tp = new BlitTextureProvider(); - + tp->setSmooth(q->smooth()); + tp->setAntialiasing(q->antialiasing()); + QObject::connect(q, &QQuickItem::smoothChanged, tp, &BlitTextureProvider::setSmooth); + QObject::connect(q, &QQuickItem::antialiasingChanged, tp, &BlitTextureProvider::setAntialiasing); if (!content->offscreen()) - tp->connect(tp, &BlitTextureProvider::textureChanged, content, &Content::update); + tp->connect(tp, &BlitTextureProvider::textureChanged, + content, &Content::update, Qt::UniqueConnection); return tp; } @@ -222,9 +258,8 @@ static void onTextureChanged(WRenderBufferNode *node, void *data) { Q_EMIT d->tp->textureChanged(); } -QSGNode *WRenderBufferBlitter::updatePaintNode(QSGNode *oldNode, QQuickItem::UpdatePaintNodeData *oldData) +QSGNode *WRenderBufferBlitter::updatePaintNode(QSGNode *oldNode, [[maybe_unused]] QQuickItem::UpdatePaintNodeData *oldData) { - Q_UNUSED(oldData) auto node = static_cast(oldNode); if (Q_LIKELY(node)) { diff --git a/waylib/src/server/qtquick/wrenderhelper.cpp b/waylib/src/server/qtquick/wrenderhelper.cpp index d3f9fc24a8..c8646b231e 100644 --- a/waylib/src/server/qtquick/wrenderhelper.cpp +++ b/waylib/src/server/qtquick/wrenderhelper.cpp @@ -1,22 +1,18 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wrenderhelper.h" #include "wtools.h" +#include "wscoplistener.h" +#include "wpointer.h" +#include "wayliblogging.h" #include "private/wqmlhelper_p.h" #include "private/wglobal_p.h" +#include "wsgcontext_p.h" +#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include #include #include @@ -25,39 +21,51 @@ #include #include #include - -extern "C" { -#define static -#include -#undef static -#include +#include #ifdef ENABLE_VULKAN_RENDER -#include +#include #endif -} + #include #include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE -struct Q_DECL_HIDDEN BufferData { - BufferData() { +struct Q_DECL_HIDDEN RhiRenderEntry { + const QRhiRenderTarget *renderTarget; + const QRhiTexture *texture; + wlr_buffer *buffer; +}; - } +Q_GLOBAL_STATIC(QVector, s_rhiRenderBuffers) + +struct Q_DECL_HIDDEN BufferData { + BufferData() = default; ~BufferData() { resetWindowRenderTarget(); } - qw_buffer *buffer = nullptr; + WPointer buffer; + std::unique_ptr bufferListenerOwner; // for software renderer WImageRenderTarget paintDevice; QQuickRenderTarget renderTarget; QQuickWindowRenderTarget windowRenderTarget; + bool colorPreserved = false; inline void resetWindowRenderTarget() { -#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + { + auto it = s_rhiRenderBuffers->begin(); + while (it != s_rhiRenderBuffers->end()) { + if (windowRenderTarget.rt.renderTarget == it->renderTarget) { + it = s_rhiRenderBuffers->erase(it); + break; + } + ++it; + } + } + if (windowRenderTarget.rt.owns) delete windowRenderTarget.rt.renderTarget; @@ -78,66 +86,127 @@ struct Q_DECL_HIDDEN BufferData { delete windowRenderTarget.sw.paintDevice; windowRenderTarget.sw = {}; -#else - if (windowRenderTarget.owns) { - delete windowRenderTarget.renderTarget; - delete windowRenderTarget.rpDesc; - delete windowRenderTarget.texture; - delete windowRenderTarget.renderBuffer; - delete windowRenderTarget.depthStencil; - delete windowRenderTarget.paintDevice; - } - - windowRenderTarget.renderTarget = nullptr; - windowRenderTarget.rpDesc = nullptr; - windowRenderTarget.texture = nullptr; - windowRenderTarget.renderBuffer = nullptr; - windowRenderTarget.depthStencil = nullptr; - windowRenderTarget.paintDevice = nullptr; - windowRenderTarget.owns = false; -#endif } }; +class WRenderHelper::RenderTarget::Private { +public: + std::weak_ptr data; +}; + +WRenderHelper::RenderTarget::RenderTarget() : d(new Private) {} +WRenderHelper::RenderTarget::RenderTarget(const RenderTarget &other) + : d(other.d ? new Private(*other.d) : nullptr) {} +WRenderHelper::RenderTarget &WRenderHelper::RenderTarget::operator=(const RenderTarget &other) +{ + if (this != &other) { + delete d; + d = other.d ? new Private(*other.d) : nullptr; + } + return *this; +} +WRenderHelper::RenderTarget::~RenderTarget() { delete d; } + +bool WRenderHelper::RenderTarget::isNull() const +{ + return !d || d->data.expired(); +} + +QQuickRenderTarget WRenderHelper::RenderTarget::rt() const +{ + if (!d) + return {}; + auto data = d->data.lock(); + return data ? data->renderTarget : QQuickRenderTarget(); +} + +wlr_buffer *WRenderHelper::RenderTarget::buffer() const +{ + if (!d) + return nullptr; + auto data = d->data.lock(); + return data ? data->buffer.get() : nullptr; +} + +bool WRenderHelper::RenderTarget::colorPreserved() const +{ + if (!d) + return false; + auto data = d->data.lock(); + return data ? data->colorPreserved : false; +} + +static constexpr WGlobal::ColorContentsMode resolveColorContentsMode( + WGlobal::ColorContentsMode requested, bool softwareRenderer) noexcept +{ + if (requested != WGlobal::ColorContentsMode::DontCare) + return requested; + // Software clear is expensive; default to preserve. + return softwareRenderer ? WGlobal::ColorContentsMode::Preserve + : WGlobal::ColorContentsMode::Clear; +} + +static QRhiTextureRenderTarget::Flags rhiRenderTargetFlags(WGlobal::ColorContentsMode mode) +{ + Q_ASSERT(mode != WGlobal::ColorContentsMode::DontCare); + return mode == WGlobal::ColorContentsMode::Preserve + ? QRhiTextureRenderTarget::PreserveColorContents + : QRhiTextureRenderTarget::Flags{}; +} + +static bool recreateRhiRenderTarget(BufferData *data, QRhiTextureRenderTarget::Flags flags) +{ + auto renderTarget = static_cast( + data->windowRenderTarget.rt.renderTarget); + auto &rpDesc = data->windowRenderTarget.res.rpDesc; + Q_ASSERT(renderTarget); + renderTarget->destroy(); + renderTarget->setFlags(flags); + + auto newRpDesc = renderTarget->newCompatibleRenderPassDescriptor(); + if (!newRpDesc) + return false; + delete rpDesc; + rpDesc = newRpDesc; + renderTarget->setRenderPassDescriptor(rpDesc); + return renderTarget->create(); +} + // Copy from qquickrendertarget.cpp static bool createRhiRenderTarget(const QRhiColorAttachment &colorAttachment, const QSize &pixelSize, int sampleCount, QRhi *rhi, - QQuickWindowRenderTarget &dst) + QQuickWindowRenderTarget &dst, + QRhiTextureRenderTarget::Flags flags) { std::unique_ptr depthStencil(rhi->newRenderBuffer(QRhiRenderBuffer::DepthStencil, pixelSize, sampleCount)); if (!depthStencil->create()) { - qWarning("Failed to build depth-stencil buffer for QQuickRenderTarget"); + qCWarning(lcWlRenderHelper, "Failed to build depth-stencil buffer for QQuickRenderTarget"); return false; } QRhiTextureRenderTargetDescription rtDesc(colorAttachment); rtDesc.setDepthStencilBuffer(depthStencil.get()); - std::unique_ptr rt(rhi->newTextureRenderTarget(rtDesc)); + std::unique_ptr rt(rhi->newTextureRenderTarget(rtDesc, flags)); std::unique_ptr rp(rt->newCompatibleRenderPassDescriptor()); rt->setRenderPassDescriptor(rp.get()); if (!rt->create()) { - qWarning("Failed to build texture render target for QQuickRenderTarget"); + qCWarning(lcWlRenderHelper, "Failed to build texture render target for QQuickRenderTarget"); return false; } -#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + rt->setName(QByteArrayLiteral("WaylibTextureRenderTarget")); dst.rt.renderTarget = rt.release(); dst.res.rpDesc = rp.release(); dst.implicitBuffers.depthStencil = depthStencil.release(); dst.rt.owns = true; // ownership of the native resource itself is not transferred but the QRhi objects are on us now -#else - dst.renderTarget = rt.release(); - dst.rpDesc = rp.release(); - dst.depthStencil = depthStencil.release(); - dst.owns = true; // ownership of the native resource itself is not transferred but the QRhi objects are on us now -#endif return true; } -bool createRhiRenderTarget(QRhi *rhi, const QQuickRenderTarget &source, QQuickWindowRenderTarget &dst) +bool createRhiRenderTarget(QRhi *rhi, const QQuickRenderTarget &source, QQuickWindowRenderTarget &dst, + QRhiTextureRenderTarget::Flags flags) { auto rtd = QQuickRenderTargetPrivate::get(&source); @@ -145,44 +214,30 @@ bool createRhiRenderTarget(QRhi *rhi, const QQuickRenderTarget &source, QQuickWi case QQuickRenderTargetPrivate::Type::NativeTexture: { const auto format = rtd->u.nativeTexture.rhiFormat == QRhiTexture::UnknownFormat ? QRhiTexture::RGBA8 : QRhiTexture::Format(rtd->u.nativeTexture.rhiFormat); - const auto flags = QRhiTexture::RenderTarget | QRhiTexture::Flags( -#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + const auto textureFlags = QRhiTexture::RenderTarget | QRhiTexture::Flags( rtd->u.nativeTexture.rhiFormatFlags -#else - rtd->u.nativeTexture.rhiFlags -#endif ); - std::unique_ptr texture(rhi->newTexture(format, rtd->pixelSize, rtd->sampleCount, flags)); -#if QT_VERSION < QT_VERSION_CHECK(6, 6, 0) - if (!texture->createFrom({ rtd->u.nativeTexture.object, rtd->u.nativeTexture.layout })) -#else + std::unique_ptr texture(rhi->newTexture(format, rtd->pixelSize, rtd->sampleCount, textureFlags)); + texture->setName(QByteArrayLiteral("WaylibTexture")); if (!texture->createFrom({ rtd->u.nativeTexture.object, rtd->u.nativeTexture.layoutOrState })) -#endif return false; QRhiColorAttachment att(texture.get()); - if (!createRhiRenderTarget(att, rtd->pixelSize, rtd->sampleCount, rhi, dst)) + if (!createRhiRenderTarget(att, rtd->pixelSize, rtd->sampleCount, rhi, dst, flags)) return false; -#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) dst.res.texture = texture.release(); -#else - dst.texture = texture.release(); -#endif return true; } case QQuickRenderTargetPrivate::Type::NativeRenderbuffer: { std::unique_ptr renderbuffer(rhi->newRenderBuffer(QRhiRenderBuffer::Color, rtd->pixelSize, rtd->sampleCount)); if (!renderbuffer->createFrom({ rtd->u.nativeRenderbufferObject })) { - qWarning("Failed to build wrapper renderbuffer for QQuickRenderTarget"); + qCWarning(lcWlRenderHelper, "Failed to build wrapper renderbuffer for QQuickRenderTarget"); return false; } QRhiColorAttachment att(renderbuffer.get()); - if (!createRhiRenderTarget(att, rtd->pixelSize, rtd->sampleCount, rhi, dst)) + if (!createRhiRenderTarget(att, rtd->pixelSize, rtd->sampleCount, rhi, dst, flags)) return false; -#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) + renderbuffer->setName(QByteArrayLiteral("WaylibRenderBuffer")); dst.res.renderBuffer = renderbuffer.release(); -#else - dst.renderBuffer = renderbuffer.release(); -#endif return true; } @@ -197,7 +252,7 @@ bool createRhiRenderTarget(QRhi *rhi, const QQuickRenderTarget &source, QQuickWi class Q_DECL_HIDDEN WRenderHelperPrivate : public WObjectPrivate { public: - WRenderHelperPrivate(WRenderHelper *qq, qw_renderer *renderer) + WRenderHelperPrivate(WRenderHelper *qq, wlr_renderer *renderer) : WObjectPrivate(qq) , renderer(renderer) {} @@ -206,63 +261,59 @@ class Q_DECL_HIDDEN WRenderHelperPrivate : public WObjectPrivate } void resetRenderBuffer(); - void onBufferDestroy(); - static bool ensureRhiRenderTarget(QQuickRenderControl *rc, BufferData *data); + void onBufferDestroy(BufferData *data); + static bool ensureRhiRenderTarget(QQuickRenderControl *rc, BufferData *data, + QRhiTextureRenderTarget::Flags flags); W_DECLARE_PUBLIC(WRenderHelper) - qw_renderer *renderer; - QList buffers; - BufferData *lastBuffer = nullptr; + wlr_renderer *renderer; + QList> buffers; + std::weak_ptr lastBuffer; QSize size; }; void WRenderHelperPrivate::resetRenderBuffer() { - qDeleteAll(buffers); - lastBuffer = nullptr; buffers.clear(); + lastBuffer.reset(); } -void WRenderHelperPrivate::onBufferDestroy() +void WRenderHelperPrivate::onBufferDestroy(BufferData *data) { - qw_buffer *buffer = qobject_cast(q_func()->sender()); - + // wlr_buffer_finish asserts the destroy/release listener lists are empty + // right after emitting destroy; detach while handling it. + if (data->bufferListenerOwner) + data->bufferListenerOwner->removeListeners(data->bufferListenerOwner.get()); for (int i = 0; i < buffers.count(); ++i) { - auto data = buffers[i]; - if (data->buffer == buffer) { - if (lastBuffer == data) - lastBuffer = nullptr; + auto entry = buffers[i]; + if (entry.get() == data) { + auto locked = lastBuffer.lock(); + if (locked && locked == entry) + lastBuffer.reset(); buffers.removeAt(i); break; } } } -bool WRenderHelperPrivate::ensureRhiRenderTarget(QQuickRenderControl *rc, BufferData *data) +bool WRenderHelperPrivate::ensureRhiRenderTarget(QQuickRenderControl *rc, BufferData *data, + QRhiTextureRenderTarget::Flags flags) { data->resetWindowRenderTarget(); -#if QT_VERSION < QT_VERSION_CHECK(6, 6, 0) - auto rhi = QQuickRenderControlPrivate::get(rc)->rhi; -#else auto rhi = rc->rhi(); -#endif auto tmp = data->renderTarget; - bool ok = createRhiRenderTarget(rhi, tmp, data->windowRenderTarget); + bool ok = createRhiRenderTarget(rhi, tmp, data->windowRenderTarget, flags); if (!ok) return false; -#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) data->renderTarget = QQuickRenderTarget::fromRhiRenderTarget(data->windowRenderTarget.rt.renderTarget); -#else - data->renderTarget = QQuickRenderTarget::fromRhiRenderTarget(data->windowRenderTarget.renderTarget); -#endif data->renderTarget.setDevicePixelRatio(tmp.devicePixelRatio()); data->renderTarget.setMirrorVertically(tmp.mirrorVertically()); return true; } -WRenderHelper::WRenderHelper(qw_renderer *renderer, QObject *parent) +WRenderHelper::WRenderHelper(wlr_renderer *renderer, QObject *parent) : QObject(parent) , WObject(*new WRenderHelperPrivate(this, renderer)) { @@ -295,7 +346,9 @@ QSGRendererInterface::GraphicsApi WRenderHelper::getGraphicsApi(QQuickRenderCont QSGRendererInterface::GraphicsApi WRenderHelper::getGraphicsApi() { auto getApi = [] () { - // Only for get GraphicsApi + // Only for get GraphicsApi. Install first so this temporary + // QQuickRenderControl does not create Qt's default sg. + WSGContext::ensureInstalled(); QQuickRenderControl rc; return getGraphicsApi(&rc); }; @@ -304,33 +357,54 @@ QSGRendererInterface::GraphicsApi WRenderHelper::getGraphicsApi() return api; } -class Q_DECL_HIDDEN GLTextureBuffer : public qw_buffer_interface +class Q_DECL_HIDDEN GLTextureBuffer { public: - explicit GLTextureBuffer(wlr_egl *egl, QSGTexture *texture); + GLTextureBuffer(wlr_egl *egl, QSGTexture *texture, int width, int height); - QW_INTERFACE(get_dmabuf, bool, wlr_dmabuf_attributes *attribs); + wlr_buffer *handle() { return &buffer; } private: + static const struct wlr_buffer_impl impl; + static bool get_dmabuf(struct wlr_buffer *buffer, struct wlr_dmabuf_attributes *attribs); + static void destroy(struct wlr_buffer *buffer); + + static inline GLTextureBuffer *fromBuffer(wlr_buffer *buffer) { + if (buffer->impl != &GLTextureBuffer::impl) + return nullptr; + return W_CONTAINER_OF(buffer, GLTextureBuffer, buffer); + } + + wlr_buffer buffer; wlr_egl *m_egl; QSGTexture *m_texture; }; -GLTextureBuffer::GLTextureBuffer(wlr_egl *egl, QSGTexture *texture) +const struct wlr_buffer_impl GLTextureBuffer::impl = { + .destroy = GLTextureBuffer::destroy, + .get_dmabuf = GLTextureBuffer::get_dmabuf, + .get_shm = NULL, + .begin_data_ptr_access = NULL, + .end_data_ptr_access = NULL, +}; + +GLTextureBuffer::GLTextureBuffer(wlr_egl *egl, QSGTexture *texture, int width, int height) : m_egl(egl) , m_texture(texture) { - + wlr_buffer_init(&buffer, &impl, width, height); } -bool GLTextureBuffer::get_dmabuf(wlr_dmabuf_attributes *attribs) +bool GLTextureBuffer::get_dmabuf(struct wlr_buffer *buffer, wlr_dmabuf_attributes *attribs) { - auto rhiTexture = m_texture->rhiTexture(); + auto *self = GLTextureBuffer::fromBuffer(buffer); + Q_ASSERT(self); + auto rhiTexture = self->m_texture->rhiTexture(); if (!rhiTexture) return false; - auto display = wlr_egl_get_display(m_egl); - auto context = wlr_egl_get_context(m_egl); + auto display = wlr_egl_get_display(self->m_egl); + auto context = wlr_egl_get_context(self->m_egl); EGLImage image = eglCreateImage(display, context, EGL_GL_TEXTURE_2D, @@ -345,56 +419,89 @@ bool GLTextureBuffer::get_dmabuf(wlr_dmabuf_attributes *attribs) static auto eglExportDMABUFImageMESA = reinterpret_cast(eglGetProcAddress("eglExportDMABUFImageMESA")); - if (!eglExportDMABUFImageQueryMESA || !eglExportDMABUFImageMESA) + if (!eglExportDMABUFImageQueryMESA || !eglExportDMABUFImageMESA) { + eglDestroyImage(display, image); return false; + } bool ok = eglExportDMABUFImageQueryMESA(display, image, reinterpret_cast(&attribs->format), &attribs->n_planes, &attribs->modifier); - if (!ok) + if (!ok) { + eglDestroyImage(display, image); return false; + } ok = eglExportDMABUFImageMESA(display, image, attribs->fd, reinterpret_cast(attribs->stride), reinterpret_cast(attribs->offset)); - if (!ok) + if (!ok) { + eglDestroyImage(display, image); return false; + } - attribs->width = handle()->width; - attribs->height = handle()->height; + attribs->width = self->buffer.width; + attribs->height = self->buffer.height; + eglDestroyImage(display, image); return true; } +void GLTextureBuffer::destroy(struct wlr_buffer *buffer) +{ + auto *self = GLTextureBuffer::fromBuffer(buffer); + Q_ASSERT(self); + wlr_buffer_finish(buffer); + delete self; +} + #ifdef ENABLE_VULKAN_RENDER -class Q_DECL_HIDDEN VkTextureBuffer : public qw_buffer_interface +class Q_DECL_HIDDEN VkTextureBuffer { public: - explicit VkTextureBuffer(VkInstance instance, VkDevice device, QSGTexture *texture); + VkTextureBuffer(VkInstance instance, VkDevice device, QSGTexture *texture, int width, int height); - QW_INTERFACE(get_dmabuf, bool ,wlr_dmabuf_attributes *attribs); + wlr_buffer *handle() { return &buffer; } private: - VkInstance m_instance; - VkDevice m_device; - QSGTexture *m_texture; + static const struct wlr_buffer_impl impl; + static bool get_dmabuf(struct wlr_buffer *buffer, struct wlr_dmabuf_attributes *attribs); + static void destroy(struct wlr_buffer *buffer); + + static inline VkTextureBuffer *fromBuffer(wlr_buffer *buffer) { + if (buffer->impl != &VkTextureBuffer::impl) + return nullptr; + return W_CONTAINER_OF(buffer, VkTextureBuffer, buffer); + } + + wlr_buffer buffer; + [[maybe_unused]] VkInstance m_instance; + [[maybe_unused]] VkDevice m_device; + [[maybe_unused]] QSGTexture *m_texture; +}; + +const struct wlr_buffer_impl VkTextureBuffer::impl = { + .destroy = VkTextureBuffer::destroy, + .get_dmabuf = VkTextureBuffer::get_dmabuf, + .get_shm = NULL, + .begin_data_ptr_access = NULL, + .end_data_ptr_access = NULL, }; -VkTextureBuffer::VkTextureBuffer(VkInstance instance, VkDevice device, QSGTexture *texture) +VkTextureBuffer::VkTextureBuffer(VkInstance instance, VkDevice device, QSGTexture *texture, int width, int height) : m_instance(instance) , m_device(device) , m_texture(texture) { - + wlr_buffer_init(&buffer, &impl, width, height); } -bool VkTextureBuffer::get_dmabuf(wlr_dmabuf_attributes *attribs) +bool VkTextureBuffer::get_dmabuf([[maybe_unused]] struct wlr_buffer *buffer, [[maybe_unused]] wlr_dmabuf_attributes *attribs) { - Q_UNUSED(attribs); // static auto vkGetInstanceProcAddr = // reinterpret_cast(::dlsym(RTLD_DEFAULT, "vkGetInstanceProcAddr")); // static auto vkGetMemoryFdKHR = @@ -409,70 +516,121 @@ bool VkTextureBuffer::get_dmabuf(wlr_dmabuf_attributes *attribs) // TODO return false; } + +void VkTextureBuffer::destroy(struct wlr_buffer *buffer) +{ + auto *self = VkTextureBuffer::fromBuffer(buffer); + Q_ASSERT(self); + wlr_buffer_finish(buffer); + delete self; +} #endif -class Q_DECL_HIDDEN QImageBuffer : public qw_buffer_interface +class Q_DECL_HIDDEN QImageBuffer { public: - explicit QImageBuffer(const QImage &image); + QImageBuffer(const QImage &image); + ~QImageBuffer(); - QW_INTERFACE(get_shm, bool, wlr_shm_attributes *attribs); - QW_INTERFACE(begin_data_ptr_access, bool, uint32_t flags, void **data, uint32_t *format, size_t *stride); - QW_INTERFACE(end_data_ptr_access, void); + wlr_buffer *handle() { return &buffer; } private: - QImage m_image; + static const struct wlr_buffer_impl impl; + static bool get_shm(struct wlr_buffer *buffer, struct wlr_shm_attributes *attribs); + static bool begin_data_ptr_access(struct wlr_buffer *buffer, uint32_t flags, + void **data, uint32_t *format, size_t *stride); + static void end_data_ptr_access(struct wlr_buffer *buffer); + static void destroy(struct wlr_buffer *buffer); + + static QImageBuffer *fromBuffer(wlr_buffer *buffer); + + // QImage is kept behind a raw pointer so this class stays standard-layout + // (std::unique_ptr is not standard-layout in libstdc++), allowing + // container_of recovery of the owner from the wlr_buffer. + wlr_buffer buffer; + QImage *m_image; +}; + +const struct wlr_buffer_impl QImageBuffer::impl = { + .destroy = QImageBuffer::destroy, + .get_dmabuf = NULL, + .get_shm = QImageBuffer::get_shm, + .begin_data_ptr_access = QImageBuffer::begin_data_ptr_access, + .end_data_ptr_access = QImageBuffer::end_data_ptr_access, }; QImageBuffer::QImageBuffer(const QImage &image) - : m_image(image) + : buffer{} + , m_image(new QImage(image)) { + wlr_buffer_init(&buffer, &impl, m_image->width(), m_image->height()); +} + +QImageBuffer::~QImageBuffer() +{ + delete m_image; +} +QImageBuffer *QImageBuffer::fromBuffer(wlr_buffer *buffer) +{ + if (buffer->impl != &QImageBuffer::impl) + return nullptr; + return W_CONTAINER_OF(buffer, QImageBuffer, buffer); } -bool QImageBuffer::get_shm(wlr_shm_attributes *attribs) +bool QImageBuffer::get_shm(struct wlr_buffer *buffer, wlr_shm_attributes *attribs) { + auto *self = QImageBuffer::fromBuffer(buffer); + Q_ASSERT(self); attribs->fd = 0; - attribs->format = WTools::toDrmFormat(m_image.format()); - attribs->width = m_image.width(); - attribs->height = m_image.height(); - attribs->stride = m_image.bytesPerLine(); + attribs->format = WTools::toDrmFormat(self->m_image->format()); + attribs->width = self->m_image->width(); + attribs->height = self->m_image->height(); + attribs->stride = self->m_image->bytesPerLine(); return true; } -bool QImageBuffer::begin_data_ptr_access(uint32_t flags, void **data, uint32_t *format, size_t *stride) +bool QImageBuffer::begin_data_ptr_access(struct wlr_buffer *buffer, [[maybe_unused]] uint32_t flags, void **data, uint32_t *format, size_t *stride) { - Q_UNUSED(flags); - *data = m_image.bits(); - *format = WTools::toDrmFormat(m_image.format()); - *stride = m_image.bytesPerLine(); + auto *self = QImageBuffer::fromBuffer(buffer); + Q_ASSERT(self); + *data = self->m_image->bits(); + *format = WTools::toDrmFormat(self->m_image->format()); + *stride = self->m_image->bytesPerLine(); return true; } -void QImageBuffer::end_data_ptr_access() +void QImageBuffer::end_data_ptr_access(struct wlr_buffer * /*buffer*/) { +} +void QImageBuffer::destroy(struct wlr_buffer *buffer) +{ + auto *self = QImageBuffer::fromBuffer(buffer); + Q_ASSERT(self); + wlr_buffer_finish(buffer); + delete self; } -qw_buffer *WRenderHelper::toBuffer(qw_renderer *renderer, QSGTexture *texture, QSGRendererInterface::GraphicsApi api) +wlr_buffer *WRenderHelper::toBuffer(wlr_renderer *renderer, QSGTexture *texture, QSGRendererInterface::GraphicsApi api) { const QSize size = texture->textureSize(); switch (api) { case QSGRendererInterface::OpenGL: { - Q_ASSERT(wlr_renderer_is_gles2(renderer->handle())); - auto egl = wlr_gles2_renderer_get_egl(renderer->handle()); + Q_ASSERT(wlr_renderer_is_gles2(renderer)); + auto egl = wlr_gles2_renderer_get_egl(renderer); - return qw_buffer::create(new GLTextureBuffer(egl, texture), size.width(), size.height()); + return (new GLTextureBuffer(egl, texture, size.width(), size.height()))->handle(); } #ifdef ENABLE_VULKAN_RENDER case QSGRendererInterface::Vulkan: { - Q_ASSERT(wlr_renderer_is_vk(renderer->handle())); - auto instance = wlr_vk_renderer_get_instance(renderer->handle()); - auto device = wlr_vk_renderer_get_device(renderer->handle()); + Q_ASSERT(wlr_renderer_is_vk(renderer)); + auto instance = wlr_vk_renderer_get_instance(renderer); + auto device = wlr_vk_renderer_get_device(renderer); - return qw_buffer::create(new VkTextureBuffer(instance, device, texture), size.width(), size.height()); + return (new VkTextureBuffer(instance, device, texture, size.width(), size.height()))->handle(); } #endif case QSGRendererInterface::Software: { @@ -492,17 +650,18 @@ qw_buffer *WRenderHelper::toBuffer(qw_renderer *renderer, QSGTexture *texture, Q if (image.isNull()) return nullptr; - return qw_buffer::create(new QImageBuffer(image), image.width(), image.height()); + return (new QImageBuffer(image))->handle(); } default: - qFatal("Can't get qw_buffer from QSGTexture, Not supported graphics API."); + qFatal("Can't get wlr_buffer from QSGTexture, Not supported graphics API."); break; } return nullptr; } -QQuickRenderTarget WRenderHelper::acquireRenderTarget(QQuickRenderControl *rc, qw_buffer *buffer) +WRenderHelper::RenderTarget WRenderHelper::acquireRenderTarget(QQuickRenderControl *rc, wlr_buffer *buffer, + WGlobal::ColorContentsMode mode) { W_D(WRenderHelper); Q_ASSERT(buffer); @@ -510,22 +669,51 @@ QQuickRenderTarget WRenderHelper::acquireRenderTarget(QQuickRenderControl *rc, q if (d->size.isEmpty()) return {}; + const bool isSoftware = wlr_renderer_is_pixman(d->renderer); + const auto resolvedMode = resolveColorContentsMode(mode, isSoftware); + const bool needPreserve = resolvedMode == WGlobal::ColorContentsMode::Preserve; + const auto flags = rhiRenderTargetFlags(resolvedMode); + for (int i = 0; i < d->buffers.count(); ++i) { auto data = d->buffers[i]; if (data->buffer == buffer) { + if (needPreserve != data->colorPreserved) { +#ifdef ENABLE_VULKAN_RENDER + if (wlr_renderer_is_vk(d->renderer)) { + qCWarning(lcWlRenderHelper) + << "Recreating Vulkan render target for buffer" << buffer + << "to change color preserved from" << data->colorPreserved + << "to" << needPreserve; + if (!recreateRhiRenderTarget(data.get(), flags)) + return {}; + } else +#endif + { + auto renderTarget = data->windowRenderTarget.rt.renderTarget; + if (renderTarget) + static_cast(renderTarget)->setFlags(flags); + } + } + data->colorPreserved = needPreserve; d->lastBuffer = data; - return data->renderTarget; + RenderTarget result; + result.d->data = data; + return result; } } std::unique_ptr bufferData(new BufferData); bufferData->buffer = buffer; - auto texture = qw_texture::from_buffer(*d->renderer, *buffer); + bufferData->colorPreserved = needPreserve; QQuickRenderTarget rt; - if (wlr_renderer_is_pixman(d->renderer->handle())) { - pixman_image_t *image = wlr_pixman_texture_get_image(texture->handle()); + if (isSoftware) { + WUniquePointer texture( + wlr_texture_from_buffer(d->renderer, buffer)); + if (!texture) + return {}; + pixman_image_t *image = wlr_pixman_texture_get_image(texture.get()); void *data = pixman_image_get_data(image); if (bufferData->paintDevice.constBits() != data) bufferData->paintDevice = WTools::fromPixmanImage(image, data); @@ -533,85 +721,182 @@ QQuickRenderTarget WRenderHelper::acquireRenderTarget(QQuickRenderControl *rc, q rt = QQuickRenderTarget::fromPaintDevice(&bufferData->paintDevice); } #ifdef ENABLE_VULKAN_RENDER - else if (wlr_renderer_is_vk(d->renderer->handle())) { - wlr_vk_image_attribs attribs; - wlr_vk_texture_get_image_attribs(texture->handle(), &attribs); - rt = QQuickRenderTarget::fromVulkanImage(attribs.image, attribs.layout, attribs.format, d->size); + else if (wlr_renderer_is_vk(d->renderer)) { + // Reuse wlroots' wlr_vk_render_buffer (same VkImage as tinywl/scene), + // not a parallel dmabuf import owned by waylib. + wlr_vk_image_attribs attribs = {}; + if (!waylib_vk_renderer_get_render_buffer_attribs(d->renderer, buffer, &attribs)) + return {}; + rt = QQuickRenderTarget::fromVulkanImage(attribs.image, + attribs.layout, + attribs.format, + d->size); } #endif - else if (wlr_renderer_is_gles2(d->renderer->handle())) { + else if (wlr_renderer_is_gles2(d->renderer)) { + WUniquePointer texture( + wlr_texture_from_buffer(d->renderer, buffer)); + if (!texture) + return {}; wlr_gles2_texture_attribs attribs; - wlr_gles2_texture_get_attribs(texture->handle(), &attribs); + wlr_gles2_texture_get_attribs(texture.get(), &attribs); rt = QQuickRenderTarget::fromOpenGLTexture(attribs.tex, d->size); rt.setMirrorVertically(true); } - delete texture; bufferData->renderTarget = rt; if (QSGRendererInterface::isApiRhiBased(getGraphicsApi(rc))) { if (!rt.isNull()) { // Force convert to Rhi render target - if (!d->ensureRhiRenderTarget(rc, bufferData.get())) + if (!d->ensureRhiRenderTarget(rc, bufferData.get(), flags)) bufferData->renderTarget = {}; } if (bufferData->renderTarget.isNull()) return {}; + + if (auto texture = bufferData->windowRenderTarget.res.texture) { + s_rhiRenderBuffers->append({ bufferData->windowRenderTarget.rt.renderTarget, + texture, bufferData->buffer.get() }); + } } - connect(buffer, SIGNAL(before_destroy()), - this, SLOT(onBufferDestroy()), Qt::UniqueConnection); + if (!bufferData->bufferListenerOwner) + bufferData->bufferListenerOwner = std::make_unique(); + auto *owner = bufferData->bufferListenerOwner.get(); + owner->listeners()->add(&buffer->events.destroy, this, [d, bufferData = bufferData.get(), owner] (void *) { + owner->removeListeners(owner); + d->onBufferDestroy(bufferData); + }); - d->buffers.append(bufferData.release()); + d->buffers.append(std::shared_ptr(bufferData.release())); d->lastBuffer = d->buffers.last(); - return d->buffers.last()->renderTarget; + RenderTarget result; + result.d->data = d->buffers.last(); + return result; } -std::pair WRenderHelper::lastRenderTarget() const +WRenderHelper::RenderTarget WRenderHelper::lastRenderTarget() const { W_DC(WRenderHelper); - if (!d->lastBuffer) - return {nullptr, {}}; + auto data = d->lastBuffer.lock(); + if (!data) + return {}; - return {d->lastBuffer->buffer, d->lastBuffer->renderTarget}; + RenderTarget result; + result.d->data = data; + return result; +} + +#ifdef ENABLE_VULKAN_RENDER +void WRenderHelper::prepareVulkanRenderTarget(QRhiCommandBuffer *cb, const RenderTarget &rt) +{ + W_D(WRenderHelper); + if (!rt.d || !cb) + return; + auto data = rt.d->data.lock(); + if (!data || !data->buffer || !d->renderer || !wlr_renderer_is_vk(d->renderer)) + return; + + cb->beginExternal(); + auto handles = static_cast(cb->nativeHandles()); + if (!handles || handles->commandBuffer == VK_NULL_HANDLE) { + cb->endExternal(); + qCWarning(lcWlRenderHelper, "Vulkan render buffer acquire: missing native command buffer"); + return; + } + + // FOREIGN_EXT -> graphics queue, same as wlroots pass.c / PR #1171. + if (!waylib_vk_renderer_record_render_buffer_acquire(d->renderer, + data->buffer.get(), + handles->commandBuffer)) { + qCWarning(lcWlRenderHelper) << "Vulkan render buffer acquire failed for" << data->buffer.get(); + } + cb->endExternal(); } -static qw_renderer *createRendererWithType(const char *type, qw_backend *backend) +void WRenderHelper::finishVulkanRenderTarget(QRhiCommandBuffer *cb, const RenderTarget &rt) +{ + W_D(WRenderHelper); + if (!rt.d || !cb) + return; + auto data = rt.d->data.lock(); + if (!data || !data->buffer || !d->renderer || !wlr_renderer_is_vk(d->renderer)) + return; + + QRhiTexture *qtTexture = data->windowRenderTarget.res.texture; + if (!qtTexture) { + qCWarning(lcWlRenderHelper, "Vulkan render buffer release: missing Qt QRhiTexture"); + return; + } + + const auto native = qtTexture->nativeTexture(); + const auto oldLayout = VkImageLayout(native.layout); + if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED) { + qCWarning(lcWlRenderHelper, "Vulkan render buffer release: Qt texture layout is UNDEFINED"); + return; + } + + cb->beginExternal(); + auto handles = static_cast(cb->nativeHandles()); + if (!handles || handles->commandBuffer == VK_NULL_HANDLE) { + cb->endExternal(); + qCWarning(lcWlRenderHelper, "Vulkan render buffer release: missing native command buffer"); + return; + } + + // graphics queue -> FOREIGN_EXT + GENERAL for KMS, using Qt's real old layout. + if (!waylib_vk_renderer_record_render_buffer_release(d->renderer, + data->buffer.get(), + handles->commandBuffer, + oldLayout)) { + qCWarning(lcWlRenderHelper) << "Vulkan render buffer release failed for" << data->buffer.get(); + cb->endExternal(); + return; + } + cb->endExternal(); + + // Keep QRhi's external-image tracker in sync with the post-release layout. + qtTexture->setNativeLayout(VK_IMAGE_LAYOUT_GENERAL); +} +#endif // ENABLE_VULKAN_RENDER + +static wlr_renderer *createRendererWithType(const char *type, wlr_backend *backend) { qputenv("WLR_RENDERER", type); - auto render = qw_renderer::autocreate(*backend); + auto render = wlr_renderer_autocreate(backend); qunsetenv("WLR_RENDERER"); return render; } -qw_renderer *WRenderHelper::createRenderer(qw_backend *backend) +wlr_renderer *WRenderHelper::createRenderer(wlr_backend *backend) { auto api = getGraphicsApi(); return createRenderer(backend, api); } -qw_renderer *WRenderHelper::createRenderer(qw_backend *backend, QSGRendererInterface::GraphicsApi api) +wlr_renderer *WRenderHelper::createRenderer(wlr_backend *backend, QSGRendererInterface::GraphicsApi api) { - qw_renderer *renderer = nullptr; + wlr_renderer *renderer = nullptr; switch (api) { case QSGRendererInterface::OpenGL: renderer = createRendererWithType("gles2", backend); - Q_ASSERT(!renderer || wlr_renderer_is_gles2(renderer->handle())); + Q_ASSERT(!renderer || wlr_renderer_is_gles2(renderer)); break; #ifdef ENABLE_VULKAN_RENDER case QSGRendererInterface::Vulkan: { renderer = createRendererWithType("vulkan", backend); - Q_ASSERT(!renderer || wlr_renderer_is_vk(renderer->handle())); + Q_ASSERT(!renderer || wlr_renderer_is_vk(renderer)); break; } #endif case QSGRendererInterface::Software: renderer = createRendererWithType("pixman", backend); - Q_ASSERT(!renderer || wlr_renderer_is_pixman(renderer->handle())); + Q_ASSERT(!renderer || wlr_renderer_is_pixman(renderer)); break; default: qFatal("Not supported graphics api: %s", qPrintable(QQuickWindow::sceneGraphBackend())); @@ -636,7 +921,7 @@ constexpr const char *GraphicsApiName(QSGRendererInterface::GraphicsApi api) } } -void WRenderHelper::setupRendererBackend(qw_backend *testBackend) +void WRenderHelper::setupRendererBackend(wlr_backend *testBackend) { const auto wlrRenderer = qgetenv("WLR_RENDERER"); @@ -654,17 +939,23 @@ void WRenderHelper::setupRendererBackend(qw_backend *testBackend) QSGRendererInterface::Software // TODO: Add vulkan to list. }; - std::unique_ptr display { nullptr }; + wl_display *display = nullptr; if (!testBackend) { - display.reset(new qw_display()); - testBackend = qw_backend::autocreate(display->get_event_loop(), nullptr); + display = wl_display_create(); + Q_ASSERT(display); + testBackend = wlr_backend_autocreate(wl_display_get_event_loop(display), nullptr); if (!testBackend) qFatal("Failed to create wlr_backend"); - testBackend->start(); + wlr_backend_start(testBackend); } QQuickWindow::setGraphicsApi(WRenderHelper::probe(testBackend, apiList)); + + if (display) { + wlr_backend_destroy(testBackend); + wl_display_destroy(display); + } } else if (wlrRenderer == "gles2") { QQuickWindow::setGraphicsApi(QSGRendererInterface::OpenGL); } else if (wlrRenderer == "vulkan") { @@ -680,39 +971,39 @@ void WRenderHelper::setupRendererBackend(qw_backend *testBackend) } } -QSGRendererInterface::GraphicsApi WRenderHelper::probe(qw_backend *testBackend, const QList &apiList) +QSGRendererInterface::GraphicsApi WRenderHelper::probe(wlr_backend *testBackend, const QList &apiList) { auto acceptApi = QSGRendererInterface::Unknown; for (auto api : std::as_const(apiList)) { - std::unique_ptr renderer(createRenderer(testBackend, api)); + WUniquePointer renderer(createRenderer(testBackend, api)); if (!renderer) { - qInfo() << GraphicsApiName(api) << " api failed to create wlr_renderer"; + qCInfo(lcWlRenderHelper) << GraphicsApiName(api) << " api failed to create wlr_renderer"; continue; } - const wlr_drm_format_set *formats = wlr_renderer_get_texture_formats(*renderer, WLR_BUFFER_CAP_DMABUF); + const wlr_drm_format_set *formats = wlr_renderer_get_texture_formats(renderer.get(), WLR_BUFFER_CAP_DMABUF); if (formats && formats->len == 0) { - qInfo() << GraphicsApiName(api) << " api don't support any format"; + qCInfo(lcWlRenderHelper) << GraphicsApiName(api) << " api don't support any format"; continue; } // TODO: how to test when formats gets NULL if (formats && formats->len) { - std::unique_ptr alloc(qw_allocator::autocreate(*testBackend, *renderer.get())); + WUniquePointer alloc(wlr_allocator_autocreate(testBackend, renderer.get())); bool hasSupportedFormat = false; - for (int formatId = 0; formatId < formats->len; formatId++) { + for (size_t formatId = 0; formatId < formats->len; formatId++) { auto *format = &formats->formats[formatId]; - std::unique_ptr swapchain(qw_swapchain::create(*alloc.get(), 1000, 800, format)); - auto wbuffer = swapchain->acquire(); + WUniquePointer swapchain(wlr_swapchain_create(alloc.get(), 1000, 800, format)); + struct wlr_buffer *wbuffer = wlr_swapchain_acquire(swapchain.get()); if (!wbuffer) { continue; } else { - std::unique_ptr buffer(qw_buffer::from(wbuffer)); - std::unique_ptr texture { qw_texture::from_buffer(*renderer.get(), *buffer.get()) }; + WBufferUnlockPtr buffer(wbuffer); + WUniquePointer texture(wlr_texture_from_buffer(renderer.get(), buffer.get())); if (!texture) continue; hasSupportedFormat = true; @@ -721,7 +1012,7 @@ QSGRendererInterface::GraphicsApi WRenderHelper::probe(qw_backend *testBackend, } if (!hasSupportedFormat) { - qInfo() << GraphicsApiName(api) << " api failed to convert any buffer to texture"; + qCInfo(lcWlRenderHelper) << GraphicsApiName(api) << " api failed to convert any buffer to texture"; continue; } } @@ -733,10 +1024,10 @@ QSGRendererInterface::GraphicsApi WRenderHelper::probe(qw_backend *testBackend, return acceptApi; } -static void updateGLTexture(QRhi *rhi, qw_texture *handle, QSGPlainTexture *texture) { +static void updateGLTexture(QRhi *rhi, wlr_texture *handle, QSGPlainTexture *texture) { wlr_gles2_texture_attribs attribs; - wlr_gles2_texture_get_attribs(handle->handle(), &attribs); - QSize size(handle->handle()->width, handle->handle()->height); + wlr_gles2_texture_get_attribs(handle, &attribs); + QSize size(handle->width, handle->height); #define GL_TEXTURE_EXTERNAL_OES 0x8D65 QQuickWindowPrivate::TextureFromNativeTextureFlags flags = attribs.target == GL_TEXTURE_EXTERNAL_OES @@ -752,54 +1043,54 @@ static inline quint64 vkimage_cast(void *image) { return reinterpret_cast(image); } -static inline quint64 vkimage_cast(quint64 image) { +[[maybe_unused]] static inline quint64 vkimage_cast(quint64 image) { return image; } #ifdef ENABLE_VULKAN_RENDER -static void updateVKTexture(QRhi *rhi, qw_texture *handle, QSGPlainTexture *texture) { +static void updateVKTexture(QRhi *rhi, wlr_texture *handle, QSGPlainTexture *texture) { wlr_vk_image_attribs attribs; - wlr_vk_texture_get_image_attribs(handle->handle(), &attribs); - QSize size(handle->handle()->width, handle->handle()->height); + wlr_vk_texture_get_image_attribs(handle, &attribs); + QSize size(handle->width, handle->height); texture->setTextureFromNativeTexture(rhi, vkimage_cast(attribs.image), attribs.layout, attribs.format, size, {}, {}); - texture->setHasAlphaChannel(wlr_vk_texture_has_alpha(handle->handle())); + texture->setHasAlphaChannel(wlr_vk_texture_has_alpha(handle)); texture->setTextureSize(size); } #endif -static void updateImage(QRhi *, qw_texture *handle, QSGPlainTexture *texture) { - auto image = wlr_pixman_texture_get_image(handle->handle()); +static void updateImage(QRhi *, wlr_texture *handle, QSGPlainTexture *texture) { + auto image = wlr_pixman_texture_get_image(handle); texture->setImage(WTools::fromPixmanImage(image)); } -typedef void(*UpdateTextureFunction)(QRhi *, qw_texture *, QSGPlainTexture *); +typedef void(*UpdateTextureFunction)(QRhi *, wlr_texture *, QSGPlainTexture *); -static UpdateTextureFunction getUpdateTextFunction(qw_texture *handle) +static UpdateTextureFunction getUpdateTextFunction(wlr_texture *handle) { const auto api = WRenderHelper::getGraphicsApi(); if (api == QSGRendererInterface::OpenGL) { - Q_ASSERT(wlr_texture_is_gles2(handle->handle())); + Q_ASSERT(wlr_texture_is_gles2(handle)); return updateGLTexture; } #ifdef ENABLE_VULKAN_RENDER else if (api == QSGRendererInterface::Vulkan) { - Q_ASSERT(wlr_texture_is_vk(handle->handle())); + Q_ASSERT(wlr_texture_is_vk(handle)); return updateVKTexture; } #endif else if (api == QSGRendererInterface::Software) { - Q_ASSERT(wlr_texture_is_pixman(handle->handle())); + Q_ASSERT(wlr_texture_is_pixman(handle)); return updateImage; } return nullptr; } -bool WRenderHelper::makeTexture(QRhi *rhi, qw_texture *handle, QSGPlainTexture *texture) +bool WRenderHelper::makeTexture(QRhi *rhi, wlr_texture *handle, QSGPlainTexture *texture) { auto updateTexture = getUpdateTextFunction(handle); if (Q_UNLIKELY(!updateTexture)) @@ -808,6 +1099,116 @@ bool WRenderHelper::makeTexture(QRhi *rhi, qw_texture *handle, QSGPlainTexture * return true; } +WRenderHelper::TextureEntry +WRenderHelper::newTexture(wlr_allocator *allocator, wlr_renderer *renderer, + uint32_t drmFormat, uint64_t drmModifier, + QRhi *rhi, const QSize &size, + int rhiFormat, int rhiFlags) +{ + uint64_t modifiers[] = {drmModifier}; + wlr_drm_format format { + .format = drmFormat, + .len = 1, + .capacity = 1, + .modifiers = modifiers + }; + + wlr_buffer *buffer = wlr_allocator_create_buffer(allocator, size.width(), size.height(), &format); + if (!buffer) { + qCCritical(lcWlRenderHelper) << "Failed to create wlr_buffer from allocator"; + return {}; + } + + WUniquePointer texture(wlr_texture_from_buffer(renderer, buffer)); + if (!texture) { + qCCritical(lcWlRenderHelper) << "Failed to create wlr_texture from buffer"; + wlr_buffer_drop(buffer); + return {}; + } + + const auto qformat = static_cast(rhiFormat); + const auto qflags = QRhiTexture::Flags(rhiFlags); + std::unique_ptr rhiTexture(rhi->newTexture(qformat, size, 1, qflags)); + + if (wlr_texture_is_gles2(texture.get())) { + if (rhi->backend() != QRhi::OpenGLES2) { + qFatal("The current QRhi backend doesn't support creating texture from GLES2 texture"); + } + + wlr_gles2_texture_attribs attribs; + wlr_gles2_texture_get_attribs(texture.get(), &attribs); + + if (!rhiTexture->createFrom({attribs.tex, 0})) { + qCCritical(lcWlRenderHelper, "Failed to create QRhiTexture from GLES2 texture"); + wlr_buffer_drop(buffer); + return {}; + } + } +#ifdef ENABLE_VULKAN_RENDER + else if (wlr_texture_is_vk(texture.get())) { + if (rhi->backend() != QRhi::Vulkan) { + qFatal("The current QRhi backend doesn't support creating texture from Vulkan image"); + } + + wlr_vk_image_attribs attribs; + wlr_vk_texture_get_image_attribs(texture.get(), &attribs); + + if (!rhiTexture->createFrom({vkimage_cast(attribs.image), attribs.layout})) { + qCCritical(lcWlRenderHelper, "Failed to create QRhiTexture from Vulkan image"); + wlr_buffer_drop(buffer); + return {}; + } + } +#endif + else if (wlr_texture_is_pixman(texture.get())) { + qFatal("Creating QRhiTexture from Pixman image is not supported"); + } else { + qFatal("Unknown texture type"); + } + + rhiTexture->setName("WaylibTexture"); + + return {buffer, texture.release(), rhiTexture.release()}; +} + +WRenderHelper::TextureEntry +WRenderHelper::newTextureLike(wlr_allocator *allocator, + wlr_renderer *renderer, + QRhiTexture *texture, QRhi *rhi, + int rhiFlags) +{ + auto buffer = lookupBuffer(texture); + if (!buffer) + return {}; + + wlr_dmabuf_attributes attribs; + if (!wlr_buffer_get_dmabuf(buffer, &attribs)) + return {}; + + return newTexture(allocator, renderer, attribs.format, attribs.modifier, + rhi, texture->pixelSize(), texture->format(), rhiFlags); +} + +wlr_buffer *WRenderHelper::lookupBuffer(const QRhiRenderTarget *rt) +{ + for (const auto &entry : std::as_const(*s_rhiRenderBuffers)) { + if (entry.renderTarget == rt) + return entry.buffer; + } + + return nullptr; +} + +wlr_buffer *WRenderHelper::lookupBuffer(const QRhiTexture *texture) +{ + for (const auto &entry : std::as_const(*s_rhiRenderBuffers)) { + if (entry.texture == texture) + return entry.buffer; + } + + return nullptr; +} + WAYLIB_SERVER_END_NAMESPACE #include "moc_wrenderhelper.cpp" diff --git a/waylib/src/server/qtquick/wrenderhelper.h b/waylib/src/server/qtquick/wrenderhelper.h index 57e16d6237..0ea45a3ba4 100644 --- a/waylib/src/server/qtquick/wrenderhelper.h +++ b/waylib/src/server/qtquick/wrenderhelper.h @@ -1,10 +1,10 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include -#include #include #include @@ -15,15 +15,9 @@ class QQuickRenderControl; class QSGTexture; class QSGPlainTexture; class QRhi; +class QRhiCommandBuffer; QT_END_NAMESPACE -QW_BEGIN_NAMESPACE -class qw_renderer; -class qw_backend; -class qw_buffer; -class qw_texture; -QW_END_NAMESPACE - WAYLIB_SERVER_BEGIN_NAMESPACE class WRenderHelperPrivate; @@ -34,7 +28,7 @@ class WAYLIB_SERVER_EXPORT WRenderHelper : public QObject, public WObject W_DECLARE_PRIVATE(WRenderHelper) public: - explicit WRenderHelper(QW_NAMESPACE::qw_renderer *renderer, QObject *parent = nullptr); + explicit WRenderHelper(wlr_renderer *renderer, QObject *parent = nullptr); QSize size() const; void setSize(const QSize &size); @@ -42,23 +36,63 @@ class WAYLIB_SERVER_EXPORT WRenderHelper : public QObject, public WObject static QSGRendererInterface::GraphicsApi getGraphicsApi(QQuickRenderControl *rc); static QSGRendererInterface::GraphicsApi getGraphicsApi(); - static QW_NAMESPACE::qw_buffer *toBuffer(QW_NAMESPACE::qw_renderer *renderer, QSGTexture *texture, QSGRendererInterface::GraphicsApi api); - - QQuickRenderTarget acquireRenderTarget(QQuickRenderControl *rc, QW_NAMESPACE::qw_buffer *buffer); - std::pair lastRenderTarget() const; - static QW_NAMESPACE::qw_renderer *createRenderer(QW_NAMESPACE::qw_backend *backend); - static QW_NAMESPACE::qw_renderer *createRenderer(QW_NAMESPACE::qw_backend *backend, QSGRendererInterface::GraphicsApi api); - - static void setupRendererBackend(QW_NAMESPACE::qw_backend *testBackend = nullptr); - static QSGRendererInterface::GraphicsApi probe(QW_NAMESPACE::qw_backend *testBackend, const QList &apiList); - - static bool makeTexture(QRhi *rhi, QW_NAMESPACE::qw_texture *handle, QSGPlainTexture *texture); + static wlr_buffer *toBuffer(wlr_renderer *renderer, QSGTexture *texture, QSGRendererInterface::GraphicsApi api); + + // Opaque handle to an internal BufferData. Becomes null when the buffer + // is destroyed (similar to QPointer). + class WAYLIB_SERVER_EXPORT RenderTarget { + public: + RenderTarget(); + RenderTarget(const RenderTarget &); + RenderTarget &operator=(const RenderTarget &); + ~RenderTarget(); + + bool isNull() const; + QQuickRenderTarget rt() const; + wlr_buffer *buffer() const; + bool colorPreserved() const; + + private: + friend class WRenderHelper; + class Private; + Private *d = nullptr; + }; + + RenderTarget acquireRenderTarget(QQuickRenderControl *rc, wlr_buffer *buffer, + WGlobal::ColorContentsMode mode = WGlobal::ColorContentsMode::DontCare); + RenderTarget lastRenderTarget() const; + +#ifdef ENABLE_VULKAN_RENDER + // Record wlroots render_buffer FOREIGN acquire/release around Qt RHI pass. + void prepareVulkanRenderTarget(QRhiCommandBuffer *cb, const RenderTarget &rt); + void finishVulkanRenderTarget(QRhiCommandBuffer *cb, const RenderTarget &rt); +#endif + static wlr_renderer *createRenderer(wlr_backend *backend); + static wlr_renderer *createRenderer(wlr_backend *backend, QSGRendererInterface::GraphicsApi api); + + static void setupRendererBackend(wlr_backend *testBackend = nullptr); + static QSGRendererInterface::GraphicsApi probe(wlr_backend *testBackend, const QList &apiList); + + static bool makeTexture(QRhi *rhi, wlr_texture *handle, QSGPlainTexture *texture); + + struct TextureEntry { + wlr_buffer *buffer; + wlr_texture *texture; + QRhiTexture *rhiTexture; + }; + static TextureEntry newTexture(wlr_allocator *allocator, + wlr_renderer *renderer, + uint32_t drmFormat, uint64_t drmModifier, + QRhi *rhi, const QSize &size, + int rhiFormat, int rhiFlags); + static TextureEntry newTextureLike(wlr_allocator *allocator, + wlr_renderer *renderer, + QRhiTexture *texture, QRhi *rhi, int rhiFlags); + static wlr_buffer *lookupBuffer(const QRhiRenderTarget *rt); + static wlr_buffer *lookupBuffer(const QRhiTexture *texture); Q_SIGNALS: void sizeChanged(); - -private: - W_PRIVATE_SLOT(void onBufferDestroy()) }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/qtquick/wsgtextureprovider.cpp b/waylib/src/server/qtquick/wsgtextureprovider.cpp index 5f1c96475a..1c164629e3 100644 --- a/waylib/src/server/qtquick/wsgtextureprovider.cpp +++ b/waylib/src/server/qtquick/wsgtextureprovider.cpp @@ -1,26 +1,19 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wsgtextureprovider.h" #include "woutputrenderwindow.h" #include "wrenderhelper.h" #include "private/wglobal_p.h" +#include "wayliblogging.h" -#include -#include -#include +#include #include #include WAYLIB_SERVER_BEGIN_NAMESPACE -#ifdef QT_DEBUG -Q_LOGGING_CATEGORY(lcQtQuickTexture, "waylib.qtquick.texture", QtDebugMsg); -#else -Q_LOGGING_CATEGORY(lcQtQuickTexture, "waylib.qtquick.texture", QtInfoMsg); -#endif - class Q_DECL_HIDDEN WSGTextureProviderPrivate : public WObjectPrivate { public: @@ -31,8 +24,6 @@ class Q_DECL_HIDDEN WSGTextureProviderPrivate : public WObjectPrivate qtTexture.setOwnsTexture(false); qtTexture.setFiltering(smooth ? QSGTexture::Linear : QSGTexture::Nearest); - qtTexture.setMipmapFiltering(smooth ? QSGTexture::Linear - : QSGTexture::Nearest); } ~WSGTextureProviderPrivate() { @@ -40,7 +31,12 @@ class Q_DECL_HIDDEN WSGTextureProviderPrivate : public WObjectPrivate } void cleanTexture() { - if (rhiTexture) { + auto *oldRhiTexture = qtTexture.rhiTexture(); + if (oldRhiTexture) { + // QSGPlainTexture does not own the QRhiTexture in this provider. + qtTexture.setOwnsTexture(false); + qtTexture.setTexture(nullptr); + Q_ASSERT(window); class TextureCleanupJob : public QRunnable { @@ -54,27 +50,41 @@ class Q_DECL_HIDDEN WSGTextureProviderPrivate : public WObjectPrivate }; // Delay clean the qt rhi textures. - window->scheduleRenderJob(new TextureCleanupJob(rhiTexture), + window->scheduleRenderJob(new TextureCleanupJob(oldRhiTexture), QQuickWindow::AfterSynchronizingStage); - rhiTexture = nullptr; } if (ownsTexture && texture) - delete texture; + wlr_texture_destroy(texture); texture = nullptr; } + void flushVulkanStageIfNeeded() { +#ifdef ENABLE_VULKAN_RENDER + if (!window || !window->renderer()) + return; + auto *renderer = window->renderer(); + if (!wlr_renderer_is_vk(renderer)) + return; + // SHM uploads are recorded on wlroots' stage CB and only submitted by + // a wlroots render pass. Flush before Qt samples the image. + if (!waylib_vk_renderer_flush_stage(renderer)) { + qCWarning(lcWlQtQuickTexture) << "Failed to flush Vulkan stage CB for SHM upload"; + } +#endif + } + void updateRhiTexture() { Q_ASSERT(texture); bool ok = WRenderHelper::makeTexture(window->rhi(), texture, &qtTexture); if (Q_UNLIKELY(!ok)) { - qCWarning(lcQtQuickTexture) << "Failed to make texture:" << texture - << ", width height:" << texture->handle()->width - << texture->handle()->height; + qCWarning(lcWlQtQuickTexture) << "Failed to make texture:" << texture + << ", width height:" << texture->width + << texture->height; return; } - rhiTexture = qtTexture.rhiTexture(); + flushVulkanStageIfNeeded(); } W_DECLARE_PUBLIC(WSGTextureProvider) @@ -82,13 +92,12 @@ class Q_DECL_HIDDEN WSGTextureProviderPrivate : public WObjectPrivate QPointer window; // wlroots resources - qw_texture *texture = nullptr; + wlr_texture *texture = nullptr; bool ownsTexture = false; - qw_buffer *buffer = nullptr; + wlr_buffer *buffer = nullptr; // qt resources QSGPlainTexture qtTexture; - QRhiTexture *rhiTexture = nullptr; bool smooth = true; }; @@ -104,35 +113,40 @@ WOutputRenderWindow *WSGTextureProvider::window() const return d->window; } -void WSGTextureProvider::setBuffer(qw_buffer *buffer) +void WSGTextureProvider::setBuffer(wlr_buffer *buffer) { - if (buffer && buffer == qwBuffer()) { - Q_EMIT textureChanged(); + W_D(WSGTextureProvider); + if (buffer == d->buffer) { + // The buffer object is not changed, but maybe the buffer's content is changed. + // So should emit textureChanged() signal too. + if (buffer && d->texture) { + d->flushVulkanStageIfNeeded(); + Q_EMIT textureChanged(); + } return; } - W_D(WSGTextureProvider); d->cleanTexture(); d->buffer = buffer; if (buffer) { Q_ASSERT(d->window); - if (auto clientBuffer = qw_client_buffer::get(*buffer)) { + if (auto clientBuffer = wlr_client_buffer_get(buffer)) { // Acquire texture from client buffer. wlroots already generate texture for us if this is a client buffer. // By the way, there is something wrong with getting texture from a client buffer using wlr_texture_from_buffer, // See: https://gitlab.freedesktop.org/wlroots/wlroots/-/issues/3897 // Possible patch: https://gitlab.freedesktop.org/wlroots/wlroots/-/merge_requests/4889 - d->texture = qw_texture::from(clientBuffer->handle()->texture); + d->texture = clientBuffer->texture; d->ownsTexture = false; } else { - d->texture = qw_texture::from_buffer(*d->window->renderer(), *buffer); + d->texture = wlr_texture_from_buffer(d->window->renderer(), buffer); d->ownsTexture = true; } if (Q_UNLIKELY(!d->texture)) { - qCWarning(lcQtQuickTexture) << "Failed to update texture from buffer:" << buffer - << ", width height:" << buffer->handle()->width - << buffer->handle()->height - << ", n_locks:" << buffer->handle()->n_locks; + qCWarning(lcWlQtQuickTexture) << "Failed to update texture from buffer:" << buffer + << ", width height:" << buffer->width + << buffer->height + << ", n_locks:" << buffer->n_locks; } else { d->updateRhiTexture(); } @@ -141,7 +155,7 @@ void WSGTextureProvider::setBuffer(qw_buffer *buffer) Q_EMIT textureChanged(); } -void WSGTextureProvider::setTexture(qw_texture *texture, qw_buffer *srcBuffer) +void WSGTextureProvider::setTexture(wlr_texture *texture, wlr_buffer *srcBuffer) { W_D(WSGTextureProvider); d->cleanTexture(); @@ -169,13 +183,13 @@ QSGTexture *WSGTextureProvider::texture() const return d->texture ? const_cast(&d->qtTexture) : nullptr; } -qw_texture *WSGTextureProvider::qwTexture() const +wlr_texture *WSGTextureProvider::qwTexture() const { W_DC(WSGTextureProvider); return d->texture; } -qw_buffer *WSGTextureProvider::qwBuffer() const +wlr_buffer *WSGTextureProvider::wlrBuffer() const { W_DC(WSGTextureProvider); return d->buffer; @@ -195,8 +209,6 @@ void WSGTextureProvider::setSmooth(bool newSmooth) d->smooth = newSmooth; d->qtTexture.setFiltering(newSmooth ? QSGTexture::Linear : QSGTexture::Nearest); - d->qtTexture.setMipmapFiltering(newSmooth ? QSGTexture::Linear - : QSGTexture::Nearest); Q_EMIT smoothChanged(); } diff --git a/waylib/src/server/qtquick/wsgtextureprovider.h b/waylib/src/server/qtquick/wsgtextureprovider.h index 8e6e6b3ad2..06875ef04d 100644 --- a/waylib/src/server/qtquick/wsgtextureprovider.h +++ b/waylib/src/server/qtquick/wsgtextureprovider.h @@ -1,16 +1,12 @@ -// Copyright (C) 2024 Yixue Wang . +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once +#include #include -#include #include -QW_BEGIN_NAMESPACE -class qw_texture; -class qw_buffer; -QW_END_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class WOutputRenderWindow; @@ -27,13 +23,13 @@ class WAYLIB_SERVER_EXPORT WSGTextureProvider : public QSGTextureProvider, publi WOutputRenderWindow *window() const; - void setBuffer(QW_NAMESPACE::qw_buffer *buffer); - void setTexture(QW_NAMESPACE::qw_texture *texture, QW_NAMESPACE::qw_buffer *srcBuffer); + void setBuffer(wlr_buffer *buffer); + void setTexture(wlr_texture *texture, wlr_buffer *srcBuffer); void invalidate(); QSGTexture *texture() const override; - virtual QW_NAMESPACE::qw_texture *qwTexture() const; - virtual QW_NAMESPACE::qw_buffer *qwBuffer() const; + virtual wlr_texture *qwTexture() const; + virtual wlr_buffer *wlrBuffer() const; bool smooth() const; void setSmooth(bool newSmooth); diff --git a/waylib/src/server/qtquick/wsurfaceitem.cpp b/waylib/src/server/qtquick/wsurfaceitem.cpp index 0d8a1af38c..c6f38dfccb 100644 --- a/waylib/src/server/qtquick/wsurfaceitem.cpp +++ b/waylib/src/server/qtquick/wsurfaceitem.cpp @@ -1,30 +1,30 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wsurfaceitem.h" -#include "wsurfaceitem_p.h" -#include "wsurface.h" -#include "wseat.h" + #include "wcursor.h" #include "woutput.h" +#include "woutputrenderwindow.h" #include "woutputviewport.h" +#include "wseat.h" #include "wsgtextureprovider.h" -#include "woutputrenderwindow.h" +#include "wsurface.h" +#include "wsurfaceitem_p.h" +#include "wayliblogging.h" + +#include + +#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include #include #include #include -#include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN SubsurfaceContainer : public QQuickItem @@ -44,6 +44,7 @@ class Q_DECL_HIDDEN SubsurfaceContainer : public QQuickItem m_deleteAfterEmpty = true; } Q_SIGNALS: + void subsurfaceAdded(WAYLIB_SERVER_NAMESPACE::WSurfaceItem *item); void subsurfaceRemoved(WAYLIB_SERVER_NAMESPACE::WSurfaceItem *item); protected: @@ -55,6 +56,7 @@ class Q_DECL_HIDDEN SubsurfaceContainer : public QQuickItem Q_ASSERT(surfaceItem); // TODO: check isSubsurface, may segmentation fault now. m_subsurfaces.append(surfaceItem); m_deleteAfterEmpty = false; + Q_EMIT subsurfaceAdded(surfaceItem); break; } case QQuickItem::ItemChildRemovedChange: { @@ -85,6 +87,8 @@ class Q_DECL_HIDDEN EventItem : public QQuickItem setAcceptHoverEvents(true); setAcceptTouchEvents(true); setAcceptedMouseButtons(Qt::AllButtons); + setKeepMouseGrab(true); + setKeepTouchGrab(true); setFlag(QQuickItem::ItemClipsChildrenToShape, true); setCursor(WCursor::toQCursor(WGlobal::CursorShape::ClientResource)); } @@ -94,7 +98,7 @@ class Q_DECL_HIDDEN EventItem : public QQuickItem return false; auto surface = static_cast(parent())->surface(); - return surface && !surface->isInvalidated(); + return surface && surface->handle(); } inline WSurfaceItemPrivate *d() const { @@ -105,7 +109,8 @@ class Q_DECL_HIDDEN EventItem : public QQuickItem if (Q_UNLIKELY(!isValid())) return false; - return d()->surface->inputRegionContains(point); + return d()->surface->inputRegionContains(point) + && (!containmentMask() || QQuickItem::contains(point)); } private: @@ -115,11 +120,11 @@ class Q_DECL_HIDDEN EventItem : public QQuickItem // Don't insert events before MouseButtonPress case MouseButtonPress: Q_FALLTHROUGH(); case MouseButtonRelease: Q_FALLTHROUGH(); - case MouseMove: Q_FALLTHROUGH(); - case HoverMove: + case MouseMove: if (static_cast(event)->source() != Qt::MouseEventNotSynthesized) return true; // The non-native events don't send to WSeat Q_FALLTHROUGH(); + case HoverMove: Q_FALLTHROUGH(); case HoverEnter: Q_FALLTHROUGH(); case HoverLeave: Q_FALLTHROUGH(); case KeyPress: Q_FALLTHROUGH(); @@ -152,22 +157,66 @@ class Q_DECL_HIDDEN EventItem : public QQuickItem } }; -class Q_DECL_HIDDEN WSurfaceItemContentPrivate: public QQuickItemPrivate +// Clean RAII wrapper for wlr_buffer that automatically manages lock and n_ignore_locks. +struct Q_DECL_HIDDEN BufferRef { -public: - WSurfaceItemContentPrivate(WSurfaceItemContent *qq){} + BufferRef() = default; + ~BufferRef() { release(); } + + BufferRef(const BufferRef &) = delete; + BufferRef &operator=(const BufferRef &) = delete; + + BufferRef(BufferRef &&other) noexcept { + std::swap(m_buffer, other.m_buffer); + } + + BufferRef &operator=(BufferRef &&other) noexcept { + std::swap(m_buffer, other.m_buffer); + return *this; + } + + // Reset to a new buffer (AddRef-before-Release to avoid transient 0 locks) + void reset(wlr_buffer *newBuf = nullptr) { + if (m_buffer == newBuf) + return; + if (newBuf) { + wlr_buffer_lock(newBuf); + if (auto cb = wlr_client_buffer_get(newBuf)) + cb->n_ignore_locks++; + } + release(); + m_buffer = newBuf; + } + + wlr_buffer *get() const { return m_buffer; } + explicit operator bool() const { return m_buffer != nullptr; } - ~WSurfaceItemContentPrivate() { +private: + void release() { + if (m_buffer) { + if (auto cb = wlr_client_buffer_get(m_buffer)) + cb->n_ignore_locks--; + wlr_buffer_unlock(m_buffer); + m_buffer = nullptr; + } } + wlr_buffer *m_buffer = nullptr; +}; + +class Q_DECL_HIDDEN WSurfaceItemContentPrivate: public QQuickItemPrivate +{ +public: + WSurfaceItemContentPrivate([[maybe_unused]] WSurfaceItemContent *qq){} + void cleanTextureProvider(); void invalidate() { W_Q(WSurfaceItemContent); if (surface) { - surface->safeDisconnect(q); + surface->disconnect(q); if (textureProvider) { - surface->safeDisconnect(textureProvider); + surface->disconnect(textureProvider); } surface = nullptr; } @@ -187,31 +236,38 @@ class Q_DECL_HIDDEN WSurfaceItemContentPrivate: public QQuickItemPrivate void init() { W_Q(WSurfaceItemContent); - surface->safeConnect(&WSurface::aboutToBeInvalidated, q, [this] { + QObject::connect(surface, &WSurface::beforeDestroy, q, [this] { invalidate(); }); - surface->safeConnect(&qw_surface::notify_commit, q, [this] { + QObject::connect(surface, &WSurface::commit, q, [this] { updateSurfaceState(); }); Q_ASSERT(!updateTextureConnection); - updateTextureConnection = surface->safeConnect(&WSurface::bufferChanged, q, [q, this] { - if (!live) { - pendingBuffer.reset(surface->buffer()); - if (pendingBuffer) - pendingBuffer->lock(); - } else { - buffer.reset(surface->buffer()); - // lock buffer to ensure the WSurfaceItem can keep the last frame after WSurface destroyed. - if (buffer) - buffer->lock(); + updateTextureConnection = QObject::connect(surface, &WSurface::commit, + q, [q, this] (quint32 committedState) { + const bool bufferChanged = committedState & WLR_SURFACE_STATE_BUFFER; + + if (bufferChanged && assignBuffer(surface->buffer())) q->update(); - } + + if (Q_LIKELY((q->isVisible() || lastRendered) && live)) + surface->scheduleFrameIfNeeded(); }); + // The item is often attached after the surface has committed content: + // BufferRef is otherwise filled by commit events only, so seed it here. + // A surface swapped in with content already committed replaces the + // cached frame right away. + if (auto *initialBuffer = surface->buffer()) { + if (assignBuffer(initialBuffer)) + q->update(); + } + updateFrameDoneConnection(); updateSurfaceState(); rendered = true; + lastRendered = true; } void updateFrameDoneConnection() { @@ -222,28 +278,38 @@ class Q_DECL_HIDDEN WSurfaceItemContentPrivate: public QQuickItemPrivate if (!q->window()) // maybe null due to item not fully initialized return; - // wayland protocol job should not run in rendering thread, so set context qobject to contentItem - frameDoneConnection = QObject::connect(q->window(), &QQuickWindow::afterRendering, q, [this, q](){ - if ((rendered || q->isVisible()) && live) { - surface->notifyFrameDone(); - rendered = false; - } - }); // if signal is emitted from seperated rendering thread, default QueuedConnection is used + auto rw = q->outputRenderWindow(); + if (Q_LIKELY(rw)) { + // wayland protocol job should not run in rendering thread, so set context qobject to contentItem + frameDoneConnection = QObject::connect(rw, &WOutputRenderWindow::renderEnd, + q, [this, q] (const QList> committedOutputs) { + lastRendered = rendered; + if (Q_LIKELY((rendered || q->isVisible()) && live) + && surface && + committedOutputs.contains(surface->framePacingOutput())) { + surface->notifyFrameDone(); + rendered = false; + } + }); // if signal is emitted from seperated rendering thread, default QueuedConnection is used + } else { + qCFatal(lcWlSurface) << "Needs a WOutputRenderWindow to render the WSurfaceItemContent, " + "but the current window is:" << q->window(); + } } void updateSurfaceState() { if (!surface) return; - qw_fbox tmp; - surface->handle()->get_buffer_source_box(tmp); - auto newBufferSourceBox = tmp.toQRectF(); + wlr_fbox tmp; + wlr_surface_get_buffer_source_box(surface->handle(), &tmp); + auto newBufferSourceBox = QRectF(tmp.x, tmp.y, tmp.width, tmp.height); std::swap(newBufferSourceBox, bufferSourceBox); W_Q(WSurfaceItemContent); const wlr_alpha_modifier_surface_v1_state *alphaModifierState = - qw_alpha_modifier_v1::get_surface_state(surface->handle()->handle()); + wlr_alpha_modifier_v1_get_surface_state(surface->handle()); if (alphaModifierState) setAlphaModifier(alphaModifierState->multiplier); @@ -262,9 +328,15 @@ class Q_DECL_HIDDEN WSurfaceItemContentPrivate: public QQuickItemPrivate } inline void swapBufferIfNeeded() { - if (pendingBuffer) { - buffer.reset(pendingBuffer.release()); - } + if (pendingBuffer) + buffer = std::move(pendingBuffer); + } + + // Returns true when the item has to repaint. + bool assignBuffer(wlr_buffer *newBuffer) { + BufferRef &target = live ? buffer : pendingBuffer; + target.reset(newBuffer); + return live; } inline void setDevicePixelRatio(qreal dpr) { @@ -295,16 +367,16 @@ class Q_DECL_HIDDEN WSurfaceItemContentPrivate: public QQuickItemPrivate QMetaObject::Connection frameDoneConnection; mutable WSGTextureProvider *textureProvider = nullptr; - std::unique_ptr buffer; - std::unique_ptr pendingBuffer; + BufferRef buffer; + BufferRef pendingBuffer; mutable QMetaObject::Connection updateTextureConnection; bool dontCacheLastBuffer = false; bool live = true; bool ignoreBufferOffset = false; + bool lastRendered = false; QAtomicInteger rendered = false; }; - WSurfaceItemContent::WSurfaceItemContent(QQuickItem *parent) : QQuickItem(*new WSurfaceItemContentPrivate(this), parent) { @@ -316,7 +388,7 @@ WSurfaceItemContent::~WSurfaceItemContent() W_D(WSurfaceItemContent); if (d->updateTextureConnection) { Q_ASSERT(d->surface); - d->surface->safeDisconnect(d->updateTextureConnection); + d->surface->disconnect(d->updateTextureConnection); } if (d->frameDoneConnection) @@ -345,9 +417,9 @@ void WSurfaceItemContent::setSurface(WSurface *surface) d->surface = surface; if (isComponentComplete()) { if (oldSurface) { - oldSurface->safeDisconnect(this); + oldSurface->disconnect(this); if (d->textureProvider) - oldSurface->safeDisconnect(d->textureProvider); + oldSurface->disconnect(d->textureProvider); } if (d->surface) @@ -383,7 +455,7 @@ WSGTextureProvider *WSurfaceItemContent::wTextureProvider() const auto w = qobject_cast(d->window); if (!w || !d->sceneGraphRenderContext() || QThread::currentThread() != d->sceneGraphRenderContext()->thread()) { - qWarning("WQuickCursor::textureProvider: can only be queried on the rendering thread of an WOutputRenderWindow"); + qCWarning(lcWlSurface, "WQuickCursor::textureProvider: can only be queried on the rendering thread of an WOutputRenderWindow"); return nullptr; } @@ -394,8 +466,8 @@ WSGTextureProvider *WSurfaceItemContent::wTextureProvider() const d->textureProvider, &WSGTextureProvider::setSmooth); if (d->surface) { - if (auto texture = d->surface->handle()->get_texture()) { - d->textureProvider->setTexture(qw_texture::from(texture), d->buffer.get()); + if (auto texture = wlr_surface_get_texture(d->surface->handle())) { + d->textureProvider->setTexture(texture, d->buffer.get()); } else { d->textureProvider->setBuffer(d->buffer.get()); } @@ -464,7 +536,6 @@ void WSurfaceItemContent::setIgnoreBufferOffset(bool newIgnoreBufferOffset) Q_EMIT ignoreBufferOffsetChanged(); } - QRectF WSurfaceItemContent::bufferSourceRect() const { W_DC(WSurfaceItemContent); @@ -511,6 +582,11 @@ class Q_DECL_HIDDEN WSGRenderFootprintNode: public QSGRenderNode m_owner->d_func()->rendered = true; } + RenderingFlags flags() const override + { + return NoExternalRendering | BoundedRectRendering | DepthAwareRendering | OpaqueRendering; + } + QPointer m_owner; }; @@ -520,9 +596,9 @@ QSGNode *WSurfaceItemContent::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeD auto tp = wTextureProvider(); if (d->live || !tp->texture()) { - auto texture = d->surface ? d->surface->handle()->get_texture() : nullptr; + auto texture = d->surface ? wlr_surface_get_texture(d->surface->handle()) : nullptr; if (texture) { - tp->setTexture(qw_texture::from(texture), d->buffer.get()); + tp->setTexture(texture, d->buffer.get()); } else { tp->setBuffer(d->buffer.get()); } @@ -560,7 +636,10 @@ void WSurfaceItemContent::releaseResources() d->invalidate(); // Force to update the contents, avoid to render the invalid textures - QQuickItemPrivate::get(this)->dirty(QQuickItemPrivate::Content); + // Only mark dirty if we have a valid window to avoid crashes during window destruction + if (window()) { + QQuickItemPrivate::get(this)->dirty(QQuickItemPrivate::Content); + } } void WSurfaceItemContent::itemChange(ItemChange change, const ItemChangeData &data) @@ -605,6 +684,38 @@ QRectF WSurfaceItem::boundingRect() const return d->boundingRect; } +bool WSurfaceItem::backgroundBlurEnabled() const +{ + Q_D(const WSurfaceItem); + return !pixman_region32_empty(&d->backgroundBlurRegion); +} + +void WSurfaceItemPrivate::updateBackgroundBlurRegion() +{ + Q_Q(WSurfaceItem); + + // No surface (yet/anymore): clear any residual region so + // backgroundBlurEnabled() doesn't keep reporting stale state. + const auto *state = (surface && surface->handle()) + ? wlr_ext_background_effect_v1_get_surface_state(surface->handle()) + : nullptr; + + if (state) { + if (pixman_region32_equal(&state->blur_region, &backgroundBlurRegion)) + return; + pixman_region32_copy(&backgroundBlurRegion, &state->blur_region); + } else { + if (pixman_region32_empty(&backgroundBlurRegion)) + return; + pixman_region32_clear(&backgroundBlurRegion); + } + + // TODO: convert the pixman region to QRegion and expose it, so consumers + // can observe the actual blur geometry instead of just the enabled flag. + + Q_EMIT q->backgroundBlurRegionChanged(); +} + WSurfaceItem *WSurfaceItem::fromFocusObject(QObject *focusObject) { if (auto item = qobject_cast(focusObject)) @@ -629,9 +740,13 @@ void WSurfaceItem::setSurface(WSurface *surface) auto oldSurface = d->surface; d->beforeRequestResizeSurfaceStateSeq = 0; d->surface = surface; + if (d->ready) { + d->ready = false; + Q_EMIT readyChanged(); + } if (d->componentComplete) { if (oldSurface) { - oldSurface->safeDisconnect(this); + oldSurface->disconnect(this); } if (d->surface) @@ -646,6 +761,10 @@ void WSurfaceItem::setSurface(WSurface *surface) if (auto content = d->getItemContent()) content->setSurface(surface); + // Sync the blur region with the new surface; clears any residual region + // when the surface is reset or replaced. + d->updateBackgroundBlurRegion(); + Q_EMIT surfaceChanged(); } @@ -722,8 +841,13 @@ void WSurfaceItem::setFlags(const Flags &newFlags) content->setLive(!newFlags.testFlag(NonLive)); } - for (auto sub : std::as_const(d->subsurfaces)) - sub->setFlags(newFlags); + if (d->surface) { + for (auto *subsurface : d->surface->subsurfaces()) { + if (auto *item = subsurface->getAttachedData(this)) { + item->setFlags(newFlags); + } + } + } Q_EMIT flagsChanged(); } @@ -789,8 +913,13 @@ void WSurfaceItem::setDelegate(QQmlComponent *newDelegate) d->initForDelegate(); if (flags() & DelegateForSubsurface) { - for (auto sub : std::as_const(d->subsurfaces)) - sub->setDelegate(newDelegate); + if (d->surface) { + for (auto *subsurface : d->surface->subsurfaces()) { + if (auto *item = subsurface->getAttachedData(this)) { + item->setDelegate(newDelegate); + } + } + } } Q_EMIT delegateChanged(); @@ -922,22 +1051,36 @@ void WSurfaceItem::releaseResources() d->beforeRequestResizeSurfaceStateSeq = 0; if (d->surface) { - d->surface->safeDisconnect(this); + d->surface->disconnect(this); } if (!d->surfaceFlags.testFlag(DontCacheLastBuffer)) { - for (auto item : std::as_const(d->subsurfaces)) { - item->releaseResources(); - // subsurface's contents at the last frame buffer. - // AutoDestroy: disconnects (subsurfaceItem.surface, destroyed, this, lambda{deleteLater}) - bool disconnAutoDestroy = QObject::disconnect(item->surface(), &WSurface::destroyed, this, nullptr); - Q_ASSERT( disconnAutoDestroy || item->property("_autoDestroyReleased").toBool() ); - item->setProperty("_autoDestroyReleased", true); + if (d->surface) { + // Keep subsurface items alive as part of this item's cached last buffer. + // They must leave d->subsurfaces, otherwise later bounding-rect updates may + // treat cached/detached items as live subsurfaces. Once removed, the + // queued auto-destroy handler below will skip deleteLater(). + const auto subsurfaces = d->surface->subsurfaces(); + for (auto *subsurface : subsurfaces) { + if (auto *item = subsurface->getAttachedData(this)) { + subsurface->removeAttachedData(this); + subsurface->disconnect(this); + item->releaseResources(); + } + } } } else { - for (auto item : std::as_const(d->subsurfaces)) - item->deleteLater(); + if (d->surface) { + for (auto *subsurface : d->surface->subsurfaces()) { + if (auto *item = subsurface->getAttachedData(this)) { + subsurface->removeAttachedData(this); + Q_EMIT subsurfaceRemoved(item); + item->deleteLater(); + } + } + } } + d->cleanupSubsurfaceContainers(); if (auto content = d->getItemContent()) content->d_func()->invalidate(); @@ -976,12 +1119,14 @@ void WSurfaceItem::onSurfaceCommit() updateSurfaceState(); + d->updateBackgroundBlurRegion(); + // Maybe the beforeRequestResizeSurfaceStateSeq is set by resizeSurfaceToItemSize, // the resizeSurfaceToItemSize wants to resize the wl_surface to current size of WSurfaceitem, // If change the WSurfaceItem's size at here, you will see the WSurfaceItem flash. - if (d->beforeRequestResizeSurfaceStateSeq < d->surface->handle()->handle()->current.seq) { + if (d->beforeRequestResizeSurfaceStateSeq < d->surface->handle()->current.seq) { if (d->beforeRequestResizeSurfaceStateSeq != 0) { - Q_ASSERT(d->beforeRequestResizeSurfaceStateSeq == d->surface->handle()->handle()->current.seq - 1); + Q_ASSERT(d->beforeRequestResizeSurfaceStateSeq == d->surface->handle()->current.seq - 1); d->beforeRequestResizeSurfaceStateSeq = 0; } @@ -997,11 +1142,14 @@ void WSurfaceItem::onSurfaceCommit() d->updateSubsurfaceItem(); } -bool WSurfaceItem::resizeSurface(const QSizeF &newSize) +bool WSurfaceItem::resizeSurface(const QSizeF &newSize, bool tryExec) { Q_D(const WSurfaceItem); if (!d->shellSurface || !d->contentContainer) return false; + if (tryExec) + return true; + QRectF tmp(0, 0, newSize.width(), newSize.height()); tmp -= d->paddings; // See surfaceSizeRatio, the content item maybe has been scaled. @@ -1019,6 +1167,19 @@ QRectF WSurfaceItem::getContentGeometry() const return QRectF(QPointF(0, 0), d->surface->size()); } +QPointF WSurfaceItem::mapFromSurface(const QPointF &point) const +{ + // NOTE: this does NOT divide by surfaceSizeRatio. Unlike + // updateContentPosition(), which maps buffer-space content into the + // (scaled) contentContainer, this maps a surface/buffer-local point into + // item-local coordinates assuming ratio == 1. XDG popup parents are Wayland + // surfaces (ratio always 1), so popup placement is safe; XWayland callers + // (ratio may differ) must scale before calling this. + const QPointF offset = getContentGeometry().topLeft(); + return QPointF(point.x() + leftPadding() - offset.x(), + point.y() + topPadding() - offset.y()); +} + QSizeF WSurfaceItem::getContentSize() const { Q_D(const WSurfaceItem); @@ -1073,6 +1234,11 @@ void WSurfaceItem::updateSurfaceState() setImplicitSize(d->calculateImplicitWidth(), d->calculateImplicitHeight()); + if (!d->ready && implicitWidth() > 0 && implicitHeight() > 0) { + d->ready = true; + Q_EMIT readyChanged(); + } + if (bufferScaleChanged) Q_EMIT this->bufferScaleChanged(); } @@ -1080,32 +1246,50 @@ void WSurfaceItem::updateSurfaceState() WSurfaceItemPrivate::WSurfaceItemPrivate() { smooth = true; + pixman_region32_init(&backgroundBlurRegion); } WSurfaceItemPrivate::~WSurfaceItemPrivate() { - + pixman_region32_fini(&backgroundBlurRegion); } void WSurfaceItemPrivate::initForSurface() { Q_Q(WSurfaceItem); - // clean subsurfaces, if cacheLastBuffer is enabled will cache - // the previous WSurface's subsurfaces. - for (auto item : std::as_const(subsurfaces)) - item->deleteLater(); - subsurfaces.clear(); + if (surface) { + for (auto *subsurface : surface->subsurfaces()) { + if (auto *item = subsurface->getAttachedData(q)) { + subsurface->removeAttachedData(q); + subsurface->disconnect(q); + Q_EMIT q->subsurfaceRemoved(item); + item->deleteLater(); + } + } + } + cleanupSubsurfaceContainers(); if (!surfaceState) surfaceState.reset(new SurfaceState()); - QObject::connect(surface, &WWrapObject::aboutToBeInvalidated, q, + QObject::connect(surface, &WSurface::beforeDestroy, q, &WSurfaceItem::releaseResources, Qt::DirectConnection); - surface->safeConnect(&WSurface::hasSubsurfaceChanged, q, [this]{ onHasSubsurfaceChanged(); }); - surface->safeConnect(&qw_surface::notify_commit, q, &WSurfaceItem::onSurfaceCommit); + QObject::connect(surface, &WSurface::subsurfaceAdded, q, [this](WSubsurface *subsurface) { + ensureSubsurfaceItem(subsurface); + reorderSubsurfaceItems(); + updateBoundingRect(); + }); + QObject::connect(surface, &WSurface::subsurfaceRemoved, q, [this](WSubsurface *subsurface) { + removeSubsurfaceItem(subsurface); + }); + QObject::connect(surface, &WSurface::subsurfaceOrderChanged, q, [this] { + reorderSubsurfaceItems(); + }); + QObject::connect(surface, &WSurface::commit, q, &WSurfaceItem::onSurfaceCommit); - onHasSubsurfaceChanged(); + for (auto *subsurface : surface->subsurfaces()) + ensureSubsurfaceItem(subsurface); updateEventItem(false); q->onSurfaceCommit(); } @@ -1134,7 +1318,7 @@ void WSurfaceItemPrivate::initForDelegate() } else if (delegateIsDirty) { auto obj = delegate->createWithInitialProperties({{"surface", QVariant::fromValue(q)}}, qmlContext(q)); if (!obj) { - qWarning() << "Failed on create surface item from delegate, error mssage:" + qCWarning(lcWlSurface) << "Failed on create surface item from delegate, error mssage:" << delegate->errorString(); return; } @@ -1177,49 +1361,19 @@ void WSurfaceItemPrivate::initForDelegate() Q_EMIT q->contentItemChanged(); } -void WSurfaceItemPrivate::onHasSubsurfaceChanged() -{ - auto qw_surface = surface->handle(); - Q_ASSERT(qw_surface); - if (surface->hasSubsurface()) - updateSubsurfaceItem(); -} - void WSurfaceItemPrivate::updateSubsurfaceItem() { - Q_Q(WSurfaceItem); - auto surface = this->surface->handle()->handle(); Q_ASSERT(surface); Q_ASSERT(contentContainer); - updateSubsurfaceContainers(); - auto updateForContainer = [this](wl_list *subsurfaceList, QQuickItem *container) { - wlr_subsurface *subsurface; - QQuickItem *prev = nullptr; - wl_list_for_each(subsurface, subsurfaceList, current.link) { - WSurface *surface = WSurface::fromHandle(subsurface->surface); - if (!surface) - continue; - WSurfaceItem *item = ensureSubsurfaceItem(surface, container); - item->setSurfaceSizeRatio(surfaceSizeRatio); - Q_ASSERT(item->parentItem() == container); - if (prev) { - Q_ASSERT(prev->parentItem() == item->parentItem()); - item->stackAfter(prev); - } - prev = item; - const QPointF pos = contentContainer->position() + QPointF(subsurface->current.x, subsurface->current.y) / surfaceSizeRatio; - item->setPosition(pos); - } - }; - updateForContainer(&surface->current.subsurfaces_below, belowSubsurfaceContainer); - updateForContainer(&surface->current.subsurfaces_above, aboveSubsurfaceContainer); + for (auto *subsurface : surface->subsurfaces()) + ensureSubsurfaceItem(subsurface); + reorderSubsurfaceItems(); + updateSubsurfacePositions(); updateBoundingRect(); } void WSurfaceItemPrivate::onPaddingsChanged() { - W_Q(WSurfaceItem); - if (!surface || !surfaceState) return; @@ -1239,88 +1393,164 @@ void WSurfaceItemPrivate::updateContentPosition() updateBoundingRect(); } -WSurfaceItem *WSurfaceItemPrivate::ensureSubsurfaceItem(WSurface *subsurfaceSurface, QQuickItem *parent) +WSurfaceItem *WSurfaceItemPrivate::ensureSubsurfaceItem(WSubsurface *subsurface) { - for (int i = 0; i < subsurfaces.count(); ++i) { - auto surfaceItem = subsurfaces.at(i); - WSurface *surface = surfaceItem->d_func()->surface.get(); - - if (surface && surface == subsurfaceSurface) { - if (surfaceItem->parent() == parent) { - return surfaceItem; - } else { - subsurfaces.removeOne(surfaceItem); - break; - } - } - } - Q_Q(WSurfaceItem); - Q_ASSERT(subsurfaceSurface); - auto surfaceItem = new WSurfaceItem(parent); - // Delay destroy WSurfaceItem, because if the cause of destroy is because the parent - // surface destroy, and the parent WSurfaceItem::cacheLastBuffer maybe enabled, - // will disable this connection at parent WSurfaceItem::releaseResources to save the - // parent WSurface last frame, the last frame contents should include its subsurfaces's - // contents. - // AutoDestroy: Connect to this(parent)'s lambda since the autodestroy is managed by parent, - // avoids disconnected with all slots on subsurfaceItem in subsurface's releaseResources - QObject::connect(subsurfaceSurface, &WSurface::destroyed, q, [this,surfaceItem] { - subsurfaces.removeOne(surfaceItem); - surfaceItem->deleteLater(); - }, Qt::QueuedConnection); - surfaceItem->setDelegate(delegate); - surfaceItem->setFlags(surfaceFlags); - surfaceItem->setSurface(subsurfaceSurface); - surfaceItem->setSmooth(q->smooth()); - QObject::connect(q, &WSurfaceItem::smoothChanged, surfaceItem, &WSurfaceItem::setSmooth); - QObject::connect(surfaceItem, &WSurfaceItem::boundingRectChanged, q, [this] { + Q_ASSERT(subsurface); + + if (auto *item = subsurface->getAttachedData(q)) + return item; + + // Keep the item owned by the parent surface item; its visual parent is + // assigned to the below/above container during subsurface reordering. + auto *item = new WSurfaceItem(q); + item->setDelegate(delegate); + item->setFlags(surfaceFlags); + item->setSurface(subsurface->surface()); + item->setSurfaceSizeRatio(surfaceSizeRatio); + item->setSmooth(q->smooth()); + item->setVisible(subsurface->isMapped()); + subsurface->setAttachedData(q, item); + + QObject::connect(item, &QObject::destroyed, subsurface, [subsurface, item, q] { + if (subsurface->getAttachedData(q) == item) + subsurface->removeAttachedData(q); + }); + QObject::connect(q, &WSurfaceItem::smoothChanged, item, &WSurfaceItem::setSmooth); + QObject::connect(item, &WSurfaceItem::boundingRectChanged, q, [this] { updateBoundingRect(); }); - // remove list element in WSurfaceItem::itemChange - subsurfaces.append(surfaceItem); - Q_EMIT q->subsurfaceAdded(surfaceItem); + QObject::connect(subsurface, &WSubsurface::positionChanged, q, [this, subsurface] { + updateSubsurfacePositions(); + updateBoundingRect(); + }); + QObject::connect(subsurface, &WSubsurface::mappedChanged, q, [this, subsurface, q](bool mapped) { + if (auto *item = subsurface->getAttachedData(q)) + item->setVisible(mapped); + }); - return surfaceItem; + Q_EMIT q->subsurfaceAdded(item); + return item; } -void WSurfaceItemPrivate::updateSubsurfaceContainers() +void WSurfaceItemPrivate::removeSubsurfaceItem(WSubsurface *subsurface) +{ + WSurfaceItem *item = subsurface->getAttachedData(q_func()); + if (!item) + return; + + subsurface->removeAttachedData(q_func()); + + Q_EMIT q_func()->subsurfaceRemoved(item); + item->deleteLater(); + reorderSubsurfaceItems(); + updateBoundingRect(); +} + +void WSurfaceItemPrivate::updateSubsurfaceContainer(WSubsurface::Place place, + const QList &subsurfaces, + QPointer &container) { Q_Q(WSurfaceItem); - if (wl_list_empty(&surface->handle()->handle()->current.subsurfaces_below) && belowSubsurfaceContainer) { - if (belowSubsurfaceContainer->isEmpty()) { - delete belowSubsurfaceContainer; - } else { - belowSubsurfaceContainer->deleteAfterEmpty(); - } - } else if (!wl_list_empty(&surface->handle()->handle()->current.subsurfaces_below) && !belowSubsurfaceContainer) { - belowSubsurfaceContainer = new SubsurfaceContainer(q); - belowSubsurfaceContainer->setZ(static_cast(WSurfaceItem::ZOrder::BelowSubsurface)); - belowSubsurfaceContainer->setVisible(subsurfacesVisible); - QQuickItemPrivate::get(belowSubsurfaceContainer)->anchors()->setFill(q); - QObject::connect(belowSubsurfaceContainer, &SubsurfaceContainer::subsurfaceRemoved, q, [this, q](WSurfaceItem *item) { - updateBoundingRect(); - Q_EMIT q->subsurfaceRemoved(item); - }); + if (!subsurfaces.isEmpty()) { + if (container) + return; + + container = new SubsurfaceContainer(q); + const auto zOrder = place == WSubsurface::Place::Below + ? WSurfaceItem::ZOrder::BelowSubsurface + : WSurfaceItem::ZOrder::AboveSubsurface; + container->setZ(static_cast(zOrder)); + container->setVisible(subsurfacesVisible); + QQuickItemPrivate::get(container)->anchors()->setFill(q); + return; } - if (wl_list_empty(&surface->handle()->handle()->current.subsurfaces_above) && aboveSubsurfaceContainer) { - if (aboveSubsurfaceContainer->isEmpty()) { - delete aboveSubsurfaceContainer; + + if (!container) + return; + // reorderSubsurfaceItems() may have just moved the last child out of this + // container. Delete immediately when already empty, otherwise wait for the + // child-removed event before deleting it. + if (container->isEmpty()) { + delete container; + } else { + container->deleteAfterEmpty(); + } + container = nullptr; +} + +void WSurfaceItemPrivate::cleanupSubsurfaceContainers() +{ + auto cleanup = [](QPointer &container) { + if (!container) + return; + if (container->isEmpty()) { + delete container; } else { - aboveSubsurfaceContainer->deleteAfterEmpty(); + container->deleteAfterEmpty(); + } + container = nullptr; + }; + + cleanup(belowSubsurfaceContainer); + cleanup(aboveSubsurfaceContainer); +} + +void WSurfaceItemPrivate::reorderSubsurfaceItems() +{ + if (!surface) + return; + + // Ensure destination containers exist before reparenting items. A place + // transition (Below <-> Above) can require moving items into a newly + // created container during this pass. + updateSubsurfaceContainers(); + auto reorder = [owner = q_func()](const QList &subsurfaces, + SubsurfaceContainer *container) { + QQuickItem *previous = nullptr; + for (auto *subsurface : subsurfaces) { + auto *item = subsurface->getAttachedData(owner); + if (!item) + continue; + // QObject ownership stays with the parent surface item while the + // visual parent follows the subsurface's below/above container. + if (item->parentItem() != container) + item->setParentItem(container); + if (previous) + item->stackAfter(previous); + previous = item; + } + }; + + reorder(surface->subsurfacesBelow(), belowSubsurfaceContainer); + reorder(surface->subsurfacesAbove(), aboveSubsurfaceContainer); + // Re-run container maintenance after reparenting so containers that became + // empty during the move can be deleted or scheduled for deferred cleanup. + updateSubsurfaceContainers(); +} + +void WSurfaceItemPrivate::updateSubsurfacePositions() +{ + if (!contentContainer || !surface) + return; + for (auto *subsurface : surface->subsurfaces()) { + if (auto *item = subsurface->getAttachedData(q_func())) { + item->setSurfaceSizeRatio(surfaceSizeRatio); + item->setPosition(contentContainer->position() + subsurface->position() / surfaceSizeRatio); } - } else if (!wl_list_empty(&surface->handle()->handle()->current.subsurfaces_above) && !aboveSubsurfaceContainer) { - aboveSubsurfaceContainer = new SubsurfaceContainer(q); - aboveSubsurfaceContainer->setZ(static_cast(WSurfaceItem::ZOrder::AboveSubsurface)); - aboveSubsurfaceContainer->setVisible(subsurfacesVisible); - QQuickItemPrivate::get(aboveSubsurfaceContainer)->anchors()->setFill(q); - QObject::connect(aboveSubsurfaceContainer, &SubsurfaceContainer::subsurfaceRemoved, q, [this, q](WSurfaceItem *item) { - updateBoundingRect(); - Q_EMIT q->subsurfaceRemoved(item); - }); } } +void WSurfaceItemPrivate::updateSubsurfaceContainers() +{ + updateSubsurfaceContainer(WSubsurface::Place::Below, + surface->subsurfacesBelow(), + belowSubsurfaceContainer); + updateSubsurfaceContainer(WSubsurface::Place::Above, + surface->subsurfacesAbove(), + aboveSubsurfaceContainer); +} + void WSurfaceItemPrivate::resizeSurfaceToItemSize(const QSize &itemSize, const QSize &sizeDiff) { Q_Q(WSurfaceItem); @@ -1336,7 +1566,7 @@ void WSurfaceItemPrivate::resizeSurfaceToItemSize(const QSize &itemSize, const Q if (q->resizeSurface(itemSize)) { contentContainer->setSize(contentContainer->size() + sizeDiff); - beforeRequestResizeSurfaceStateSeq = surface->handle()->handle()->pending.seq; + beforeRequestResizeSurfaceStateSeq = surface->handle()->pending.seq; updateBoundingRect(); } } @@ -1390,7 +1620,7 @@ void WSurfaceItemPrivate::doResize(WSurfaceItem::ResizeMode mode) resizeSurfaceToItemSize(newSize.toSize(), (newSize - oldSize).toSize()); } else { - qWarning() << "Invalid resize mode" << mode; + qCWarning(lcWlSurface) << "Invalid resize mode" << mode; } } @@ -1420,8 +1650,13 @@ QRectF WSurfaceItemPrivate::calculateBoundingRect() const if (contentContainer) rect |= q->mapFromItem(contentContainer, contentContainer->boundingRect()); - for (auto sub : std::as_const(subsurfaces)) - rect |= sub->boundingRect().translated(sub->position()); + if (surface) { + for (auto *subsurface : surface->subsurfaces()) { + if (auto *item = subsurface->getAttachedData(q_func())) { + rect |= item->boundingRect().translated(item->position()); + } + } + } return rect; } @@ -1449,7 +1684,7 @@ bool WSurfaceItem::setShellSurface(WToplevelSurface *surface) return false; if (d->shellSurface) { - bool ok = d->shellSurface->safeDisconnect(this); + bool ok = d->shellSurface->disconnect(this); Q_ASSERT(ok); } d->shellSurface = surface; @@ -1504,6 +1739,28 @@ void WSurfaceItem::setSubsurfacesVisible(bool newSubsurfacesVisible) Q_EMIT subsurfacesVisibleChanged(); } +bool WSurfaceItem::isReady() const +{ + Q_D(const WSurfaceItem); + return d->ready; +} + +WSurfaceItemContent *WSurfaceItem::findItemContent() const +{ + QQueue q; + q.enqueue(const_cast(this)); + while (!q.empty()) { + auto node = q.dequeue(); + if (auto content = qobject_cast(node)) + return content; + const auto children = node->childItems(); + for (auto child : children) { + q.enqueue(child); + } + } + return nullptr; +} + WAYLIB_SERVER_END_NAMESPACE #include "wsurfaceitem.moc" diff --git a/waylib/src/server/qtquick/wsurfaceitem.h b/waylib/src/server/qtquick/wsurfaceitem.h index a037318389..89701cbbde 100644 --- a/waylib/src/server/qtquick/wsurfaceitem.h +++ b/waylib/src/server/qtquick/wsurfaceitem.h @@ -115,7 +115,9 @@ class WAYLIB_SERVER_EXPORT WSurfaceItem : public QQuickItem Q_PROPERTY(qreal bufferScale READ bufferScale NOTIFY bufferScaleChanged) Q_PROPERTY(QQmlComponent* delegate READ delegate WRITE setDelegate NOTIFY delegateChanged FINAL) Q_PROPERTY(QRectF boundingRect READ boundingRect NOTIFY boundingRectChanged) + Q_PROPERTY(bool backgroundBlurEnabled READ backgroundBlurEnabled NOTIFY backgroundBlurRegionChanged) Q_PROPERTY(bool subsurfacesVisible READ subsurfacesVisible WRITE setSubsurfacesVisible NOTIFY subsurfacesVisibleChanged FINAL) + Q_PROPERTY(bool ready READ isReady NOTIFY readyChanged FINAL) QML_NAMED_ELEMENT(SurfaceItem) public: @@ -150,6 +152,10 @@ class WAYLIB_SERVER_EXPORT WSurfaceItem : public QQuickItem static WSurfaceItem *fromFocusObject(QObject *focusObject); + // Whether the surface currently has a committed non-empty + // ext-background-effect-v1 blur region. + bool backgroundBlurEnabled() const; + WSurface *surface() const; void setSurface(WSurface *newSurface); @@ -189,10 +195,17 @@ class WAYLIB_SERVER_EXPORT WSurfaceItem : public QQuickItem void setDelegate(QQmlComponent *newDelegate); // resize internal surface, should be in SizeFromSurface mode - bool resizeSurface(const QSizeF &newSize); + bool resizeSurface(const QSizeF &newSize, bool tryExec = false); bool subsurfacesVisible() const; void setSubsurfacesVisible(bool newSubsurfacesVisible); + bool isReady() const; + + // Find WSurfaceItemContent in child items + WSurfaceItemContent *findItemContent() const; + + QPointF mapFromSurface(const QPointF &point) const; + Q_SIGNALS: void surfaceChanged(); void subsurfaceAdded(WAYLIB_SERVER_NAMESPACE::WSurfaceItem *item); @@ -211,7 +224,9 @@ class WAYLIB_SERVER_EXPORT WSurfaceItem : public QQuickItem void delegateChanged(); void shellSurfaceChanged(); void boundingRectChanged(); + void backgroundBlurRegionChanged(); void subsurfacesVisibleChanged(); + void readyChanged(); protected: explicit WSurfaceItem(WSurfaceItemPrivate &dd, QQuickItem *parent = nullptr); diff --git a/waylib/src/server/qtquick/wtextureproviderprovider.cpp b/waylib/src/server/qtquick/wtextureproviderprovider.cpp index 99f2601aea..09e5ce233b 100644 --- a/waylib/src/server/qtquick/wtextureproviderprovider.cpp +++ b/waylib/src/server/qtquick/wtextureproviderprovider.cpp @@ -1,16 +1,15 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wtextureproviderprovider.h" #include "woutputrenderwindow.h" #include "private/wglobal_p.h" +#include "wayliblogging.h" #include -#include +#include WAYLIB_SERVER_BEGIN_NAMESPACE -Q_LOGGING_CATEGORY(qLcTextureProvider, "waylib.server.texture.provider") - class Q_DECL_HIDDEN WTextureCapturerPrivate : public WObjectPrivate { public: @@ -42,9 +41,9 @@ QFuture WTextureCapturer::grabToImage() { W_D(WTextureCapturer); auto future = d->imgPromise.future(); - moveToThread(QQuickWindowPrivate::get(d->renderWindow)->context->thread()); + if (d->renderWindow->inRendering()) { - connect(d->renderWindow, &WOutputRenderWindow::renderEnd, this, &WTextureCapturer::doGrabToImage, Qt::AutoConnection); + connect(d->renderWindow, &WOutputRenderWindow::renderEnd, this, &WTextureCapturer::doGrabToImage, Qt::SingleShotConnection); } else { // FIXME What if a new render process start before this job is executed? QMetaObject::invokeMethod(this, &WTextureCapturer::doGrabToImage, Qt::AutoConnection); @@ -55,20 +54,23 @@ QFuture WTextureCapturer::grabToImage() void WTextureCapturer::doGrabToImage() { W_D(WTextureCapturer); - if (d->imgPromise.isCanceled()) - return; + disconnect(d->renderWindow, + &WOutputRenderWindow::renderEnd, + this, + &WTextureCapturer::doGrabToImage); d->imgPromise.start(); WSGTextureProvider *textureProvider = d->provider->wTextureProvider(); - if (textureProvider && textureProvider->texture() && textureProvider->texture()->rhiTexture()) { + auto *texture = textureProvider ? textureProvider->texture() : nullptr; + if (texture && texture->rhiTexture()) { // Perform rhi texture read back - auto texture = textureProvider->texture()->rhiTexture(); - qCInfo(qLcTextureProvider) << "Perform rhi texture read back for texture" << texture; + auto *rhiTexture = texture->rhiTexture(); + qCInfo(lcWlTextureProvider) << "Perform rhi texture read back for texture" << rhiTexture; QRhiReadbackResult *rbResult = new QRhiReadbackResult; QRhiCommandBuffer *cb; d->renderWindow->rhi()->beginOffscreenFrame(&cb); auto ub = d->renderWindow->rhi()->nextResourceUpdateBatch(); cb->beginComputePass(ub); - QRhiReadbackDescription rbd(texture); + QRhiReadbackDescription rbd(rhiTexture); ub->readBackTexture(rbd, rbResult); cb->endComputePass(ub); auto frameOpResult = d->renderWindow->rhi()->endOffscreenFrame(); @@ -82,6 +84,14 @@ void WTextureCapturer::doGrabToImage() } else { d->imgPromise.setException(std::make_exception_ptr(std::runtime_error("Offscreen frame operation failed."))); } + } else if (auto *plainTexture = qobject_cast(texture)) { + // The pixman renderer selects Qt Quick's Software backend, which has + // no QRhiTexture but stores the current pixels in QSGPlainTexture. + const QImage image = plainTexture->image(); + if (image.isNull()) + d->imgPromise.setException(std::make_exception_ptr(std::runtime_error("Texture image is not valid."))); + else + d->imgPromise.addResult(image.copy()); } else { d->imgPromise.setException(std::make_exception_ptr(std::runtime_error("Texture provider is not valid."))); } diff --git a/waylib/src/server/qtquick/wxdgpopupsurfaceitem.cpp b/waylib/src/server/qtquick/wxdgpopupsurfaceitem.cpp index 585307f04f..0dfe78fa73 100644 --- a/waylib/src/server/qtquick/wxdgpopupsurfaceitem.cpp +++ b/waylib/src/server/qtquick/wxdgpopupsurfaceitem.cpp @@ -1,14 +1,12 @@ -// Copyright (C) 2023-2024 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wxdgpopupsurfaceitem.h" #include "wsurfaceitem_p.h" #include "wxdgpopupsurface.h" -#include -#include +#include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WXdgPopupSurfaceItemPrivate : public WSurfaceItemPrivate @@ -50,9 +48,9 @@ void WXdgPopupSurfaceItem::onSurfaceCommit() WSurfaceItem::onSurfaceCommit(); d->setImplicitPosition(popupSurface()->getPopupPosition()); - auto xdg_surface = popupSurface()->handle()->handle()->base; + auto xdg_surface = popupSurface()->handle()->base; if (xdg_surface->initial_commit) { - qw_xdg_surface::from(xdg_surface)->schedule_configure(); + wlr_xdg_surface_schedule_configure(xdg_surface); } } @@ -60,7 +58,7 @@ void WXdgPopupSurfaceItem::initSurface() { WSurfaceItem::initSurface(); Q_ASSERT(popupSurface()); - connect(popupSurface(), &WWrapObject::aboutToBeInvalidated, + connect(popupSurface(), &WToplevelSurface::beforeDestroy, this, &WXdgPopupSurfaceItem::releaseResources); } diff --git a/waylib/src/server/qtquick/wxdgtoplevelsurfaceitem.cpp b/waylib/src/server/qtquick/wxdgtoplevelsurfaceitem.cpp index 65b6a448b4..3c30d06ff2 100644 --- a/waylib/src/server/qtquick/wxdgtoplevelsurfaceitem.cpp +++ b/waylib/src/server/qtquick/wxdgtoplevelsurfaceitem.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2023-2024 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wxdgtoplevelsurfaceitem.h" @@ -7,9 +7,8 @@ #include "wxdgshell.h" #include "wxdgtoplevelsurface.h" -#include +#include -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WXdgToplevelSurfaceItemPrivate : public WSurfaceItemPrivate @@ -60,7 +59,7 @@ void WXdgToplevelSurfaceItem::onSurfaceCommit() WSurfaceItem::onSurfaceCommit(); - auto toplevel = toplevelSurface()->handle()->handle(); + auto toplevel = toplevelSurface()->handle(); const QSize minSize(getValidSize(toplevel->current.min_width, 0), getValidSize(toplevel->current.min_height, 0)); const QSize maxSize(getValidSize(toplevel->current.max_width, INT_MAX), @@ -76,13 +75,15 @@ void WXdgToplevelSurfaceItem::onSurfaceCommit() Q_EMIT maximumSizeChanged(); } - auto xdg_surface = toplevelSurface()->handle()->handle()->base; - if (xdg_surface->initial_commit) { + auto xdg_surface = toplevelSurface()->handle()->base; + if (xdg_surface->initial_commit && + !toplevelSurface()->handle()->requested.maximized && + !toplevelSurface()->handle()->requested.fullscreen) { /* When an xdg_surface performs an initial commit, the compositor must * reply with a configure so the client can map the surface. * configures the xdg_toplevel with 0,0 size to let the client pick the * dimensions itself. */ - toplevelSurface()->handle()->set_size(0, 0); + wlr_xdg_toplevel_set_size(toplevelSurface()->handle(), 0, 0); } } @@ -90,7 +91,7 @@ void WXdgToplevelSurfaceItem::initSurface() { WSurfaceItem::initSurface(); Q_ASSERT(toplevelSurface()); - connect(toplevelSurface(), &WWrapObject::aboutToBeInvalidated, + connect(toplevelSurface(), &WToplevelSurface::beforeDestroy, this, &WXdgToplevelSurfaceItem::releaseResources); } diff --git a/waylib/src/server/qtquick/wxwaylandsurfaceitem.cpp b/waylib/src/server/qtquick/wxwaylandsurfaceitem.cpp index 900d9864a8..de1230ec3e 100644 --- a/waylib/src/server/qtquick/wxwaylandsurfaceitem.cpp +++ b/waylib/src/server/qtquick/wxwaylandsurfaceitem.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2023-2024 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wxwaylandsurfaceitem.h" @@ -6,7 +6,6 @@ #include "wxwaylandsurface.h" #include "wxwayland.h" -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE class Q_DECL_HIDDEN WXWaylandSurfaceItemPrivate : public WSurfaceItemPrivate @@ -45,8 +44,8 @@ QSize WXWaylandSurfaceItemPrivate::expectSurfaceSize() const if (q->resizeMode() == SizeFromSurface) { const bool useRequestSize = !q->xwaylandSurface()->isBypassManager() - && q->xwaylandSurface()->requestConfigureFlags() - .testAnyFlags(WXWaylandSurface::XCB_CONFIG_WINDOW_SIZE); + && q->xwaylandSurface()->requestConfigureFlags() + .testAnyFlags(WXWaylandSurface::XCB_CONFIG_WINDOW_SIZE); return useRequestSize ? q->xwaylandSurface()->requestConfigureGeometry().size() : q->xwaylandSurface()->geometry().size(); @@ -93,11 +92,14 @@ bool WXWaylandSurfaceItem::setShellSurface(WToplevelSurface *surface) if (surface) { Q_ASSERT(surface->surface()); - surface->safeConnect(&WXWaylandSurface::surfaceChanged, this, [this] { + QObject::connect(surface, &WXWaylandSurface::surfaceChanged, this, [this] { WSurfaceItem::setSurface(xwaylandSurface()->surface()); }); - auto updateGeometry = [this, d] { + auto updateGeometry = [this] { + if (xwaylandSurface()->isBypassManager()) + Q_EMIT implicitPositionChanged(); + const auto rm = resizeMode(); if (rm != SizeFromSurface) return; @@ -110,13 +112,17 @@ bool WXWaylandSurfaceItem::setShellSurface(WToplevelSurface *surface) resize(rm); } }; - xwaylandSurface()->safeConnect(&WXWaylandSurface::requestConfigure, this, [this] { + QObject::connect(xwaylandSurface(), &WXWaylandSurface::requestConfigure, this, [this, d] { if (xwaylandSurface()->requestConfigureFlags().testAnyFlags( WXWaylandSurface::ConfigureFlag::XCB_CONFIG_WINDOW_POSITION)) { Q_EMIT implicitPositionChanged(); } + + // send back a ConfigureNotify event with the computed geometry. + d->configureSurface(QRect(d->explicitSurfacePosition(), + d->expectSurfaceSize())); }); - xwaylandSurface()->safeConnect(&WXWaylandSurface::geometryChanged, this, updateGeometry); + QObject::connect(xwaylandSurface(), &WXWaylandSurface::geometryChanged, this, updateGeometry); connect(this, &WXWaylandSurfaceItem::topPaddingChanged, this, &WXWaylandSurfaceItem::updatePosition, Qt::UniqueConnection); connect(this, &WXWaylandSurfaceItem::leftPaddingChanged, @@ -180,14 +186,16 @@ QPointF WXWaylandSurfaceItem::implicitPosition() const const Q_D(WXWaylandSurfaceItem); auto xwaylandSurface = qobject_cast(d->shellSurface); + Q_ASSERT(xwaylandSurface); - const QPoint epos = xwaylandSurface->requestConfigureGeometry().topLeft(); + const QPoint epos = xwaylandSurface->isBypassManager() + ? xwaylandSurface->geometry().topLeft() + : xwaylandSurface->requestConfigureGeometry().topLeft(); const qreal ssr = d->surfaceSizeRatio; return QPointF(epos) / ssr - QPointF(leftPadding(), topPadding()); } - void WXWaylandSurfaceItem::onSurfaceCommit() { Q_D(WXWaylandSurfaceItem); @@ -214,10 +222,9 @@ void WXWaylandSurfaceItem::onSurfaceCommit() void WXWaylandSurfaceItem::initSurface() { - Q_D(WXWaylandSurfaceItem); WSurfaceItem::initSurface(); Q_ASSERT(xwaylandSurface()); - connect(xwaylandSurface(), &WWrapObject::aboutToBeInvalidated, + connect(xwaylandSurface(), &WToplevelSurface::beforeDestroy, this, &WXWaylandSurfaceItem::releaseResources); } @@ -244,6 +251,11 @@ void WXWaylandSurfaceItem::surfaceSizeRatioChange() W_DC(WXWaylandSurfaceItem); + Q_ASSERT(d->shellSurface); + + if (d->surfaceState) + updateSurfaceState(); + if (d->positionConfigured) { updatePosition(); } else { diff --git a/waylib/src/server/utils/WBufferDumper b/waylib/src/server/utils/WBufferDumper new file mode 100644 index 0000000000..ccdea45788 --- /dev/null +++ b/waylib/src/server/utils/WBufferDumper @@ -0,0 +1,4 @@ +// Copyright (C) 2025 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wbufferdumper.h" diff --git a/waylib/src/server/utils/WContainerOf b/waylib/src/server/utils/WContainerOf new file mode 100644 index 0000000000..6a85ed2655 --- /dev/null +++ b/waylib/src/server/utils/WContainerOf @@ -0,0 +1,4 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wcontainerof.h" diff --git a/waylib/src/server/utils/wbufferdumper.cpp b/waylib/src/server/utils/wbufferdumper.cpp new file mode 100644 index 0000000000..6987af3b14 --- /dev/null +++ b/waylib/src/server/utils/wbufferdumper.cpp @@ -0,0 +1,95 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wbufferdumper.h" +#include "wtools.h" +#include "wayliblogging.h" + +#include + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +WBufferDumper::DumpResult WBufferDumper::dumpBufferToImage(wlr_buffer *buffer, + wlr_renderer *renderer, + QImage &outputImage) +{ + if (!buffer || !renderer) { + qCWarning(lcWlBufferDumper) << "Invalid buffer or renderer"; + return DumpResult::InvalidBuffer; + } + + wlr_texture *texture = wlr_texture_from_buffer(renderer, buffer); + if (!texture) { + qCWarning(lcWlBufferDumper) << "Failed to create texture from buffer"; + return DumpResult::TextureCreationFailed; + } + + uint32_t format = wlr_texture_preferred_read_format(texture); + + QImage::Format qImageFormat = WTools::toImageFormat(format); + if (qImageFormat == QImage::Format_Invalid) { + wlr_texture_destroy(texture); + return DumpResult::UnsupportedFormat; + } + + outputImage = QImage(texture->width, texture->height, qImageFormat); + uint32_t stride = outputImage.bytesPerLine(); + + wlr_texture_read_pixels_options options = {}; + options.data = outputImage.bits(); + options.format = format; + options.stride = stride; + + if (!wlr_texture_read_pixels(texture, &options)) { + qCWarning(lcWlBufferDumper) << "Failed to read pixels from texture"; + wlr_texture_destroy(texture); + return DumpResult::TextureReadFailed; + } + + wlr_texture_destroy(texture); + + return DumpResult::Success; +} + +WBufferDumper::DumpResult WBufferDumper::dumpBufferToFile(wlr_buffer *buffer, + wlr_renderer *renderer, + const QString &filePath) +{ + QImage image; + DumpResult result = dumpBufferToImage(buffer, renderer, image); + + if (result != DumpResult::Success) { + return result; + } + + if (!image.save(filePath)) { + qCWarning(lcWlBufferDumper) << "Failed to save image to" << filePath; + return DumpResult::SaveFailed; + } + + return DumpResult::Success; +} + +QString WBufferDumper::dumpResultToString(DumpResult result) +{ + switch (result) { + case DumpResult::Success: + return "Success"; + case DumpResult::InvalidBuffer: + return "Invalid buffer or renderer"; + case DumpResult::TextureCreationFailed: + return "Failed to create texture from buffer"; + case DumpResult::TextureReadFailed: + return "Failed to read pixels from texture"; + case DumpResult::UnsupportedFormat: + return "Unsupported pixel format"; + case DumpResult::SaveFailed: + return "Failed to save image file"; + default: + return "Unknown error"; + } +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/utils/wbufferdumper.h b/waylib/src/server/utils/wbufferdumper.h new file mode 100644 index 0000000000..bc778922eb --- /dev/null +++ b/waylib/src/server/utils/wbufferdumper.h @@ -0,0 +1,36 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WAYLIB_SERVER_EXPORT WBufferDumper +{ +public: + enum class DumpResult { + Success, + InvalidBuffer, + TextureCreationFailed, + TextureReadFailed, + UnsupportedFormat, + SaveFailed + }; + + static DumpResult dumpBufferToFile(wlr_buffer *buffer, + wlr_renderer *renderer, + const QString &filePath); + + static DumpResult dumpBufferToImage(wlr_buffer *buffer, + wlr_renderer *renderer, + QImage &outputImage); + + static QString dumpResultToString(DumpResult result); +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/utils/wcontainerof.h b/waylib/src/server/utils/wcontainerof.h new file mode 100644 index 0000000000..fe415ae99f --- /dev/null +++ b/waylib/src/server/utils/wcontainerof.h @@ -0,0 +1,29 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +// Obtain the containing object of a member (offset-based, wlroots +// wl_container_of style). `offset` is normally produced by W_CONTAINER_OF +// with offsetof(Type, member); a raw offset also allows computing a pointer +// into a non-standard-layout prefix as long as T itself is standard-layout. +template +static inline T *container_of(M *ptr, std::size_t offset) noexcept +{ + static_assert(std::is_standard_layout_v, + "T must be standard-layout"); + + return reinterpret_cast( + reinterpret_cast(ptr) - offset); +} + +// Obtain the containing object of a member; use this instead of wlroots' +// unguarded wl_container_of macro. The static_assert in container_of() is +// unconditional: non-standard-layout containers must not be recovered this +// way even when the member sits at offset 0 (use a registry or the native +// object's data field instead). +#define W_CONTAINER_OF(ptr, Type, member) \ + container_of(ptr, offsetof(Type, member)) diff --git a/waylib/src/server/utils/wcursorimage.cpp b/waylib/src/server/utils/wcursorimage.cpp index c425a28f5f..c1236db390 100644 --- a/waylib/src/server/utils/wcursorimage.cpp +++ b/waylib/src/server/utils/wcursorimage.cpp @@ -1,21 +1,18 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wcursorimage.h" #include "wcursor.h" +#include "wayliblogging.h" -#include +#include #include -#include #include #include #include -Q_LOGGING_CATEGORY(qLcCursorImage, "waylib.server.cursor.image", QtWarningMsg) - -QW_USE_NAMESPACE WAYLIB_SERVER_BEGIN_NAMESPACE // This function copy form kwin 6.1.19 `src/cursor.cpp` @@ -316,19 +313,19 @@ static QList alternativesCursorShape(const QByteArray &name) return QList(); } -static inline wlr_xcursor *getXCursorWithFallback(qw_xcursor_manager *xcursor_manager, const char *name, float scale) +static inline wlr_xcursor *getXCursorWithFallback(wlr_xcursor_manager *xcursor_manager, const char *name, float scale) { if (!xcursor_manager) return nullptr; - if (wlr_xcursor *cursor = xcursor_manager->get_xcursor(name, scale)) { + if (wlr_xcursor *cursor = wlr_xcursor_manager_get_xcursor(xcursor_manager, name, scale)) { return cursor; } const auto alterNameList = alternativesCursorShape(name); for (const auto &alterName : alterNameList) { - if (auto cursor = xcursor_manager->get_xcursor(alterName, scale)) + if (auto cursor = wlr_xcursor_manager_get_xcursor(xcursor_manager, alterName, scale)) return cursor; } @@ -471,6 +468,10 @@ static inline const char *qcursorShapeToType(std::underlying_type_t(WGlobal::CursorShape::ZoomOut): return "zoom-out"; + case static_cast(WGlobal::CursorShape::DndAsk): + return "dnd-ask"; + case static_cast(WGlobal::CursorShape::AllResize): + return "all-resize"; default: break; } @@ -499,7 +500,7 @@ class Q_DECL_HIDDEN WCursorImagePrivate : public QObjectPrivate { QPoint hotSpot; QCursor cursor; - std::shared_ptr manager; + std::shared_ptr manager; float scale = 1.0; wlr_xcursor *xcursor = nullptr; @@ -541,9 +542,9 @@ void WCursorImagePrivate::updateCursorImage() if (cursorName) { xcursor = getXCursorWithFallback(manager.get(), cursorName, scale); if (!xcursor) - qCWarning(qLcCursorImage) << "Get empty cursor image for " << cursorName; + qCWarning(lcWlCursorImage) << "Get empty cursor image for " << cursorName; } else { - qCWarning(qLcCursorImage) << "Unknown cursor shape type!"; + qCWarning(lcWlCursorImage) << "Unknown cursor shape type!"; } if (!xcursor || xcursor->image_count == 0) { @@ -575,7 +576,7 @@ void WCursorImagePrivate::updateCursorImage() void WCursorImagePrivate::playXCursor() { Q_ASSERT(xcursor); - Q_ASSERT(currentXCursorImageIndex < xcursor->image_count); + Q_ASSERT(static_cast(currentXCursorImageIndex) < xcursor->image_count); Q_ASSERT(xcursorPlayTimer); Q_ASSERT(!xcursorPlayTimer->isActive()); @@ -637,14 +638,15 @@ void WCursorImage::setScale(float newScale) return; d->scale = newScale; if (d->manager) - d->manager->load(d->scale); + wlr_xcursor_manager_load(d->manager.get(), d->scale); + d->updateCursorImage(); Q_EMIT scaleChanged(); } -static inline bool matchCursorTheme(const qw_xcursor_manager *manager, +static inline bool matchCursorTheme(const wlr_xcursor_manager *manager, const QByteArray &name, uint32_t size) { - return manager && manager->handle()->name == name && manager->handle()->size == size; + return manager && manager->name == name && manager->size == size; } void WCursorImage::setCursorTheme(const QByteArray &name, uint32_t size) @@ -666,11 +668,13 @@ void WCursorImage::setCursorTheme(const QByteArray &name, uint32_t size) } } if (!d->manager) - d->manager.reset(qw_xcursor_manager::create(name.constData(), size)); + d->manager = std::shared_ptr( + wlr_xcursor_manager_create(name.constData(), size), + wlr_xcursor_manager_destroy); - bool theme_loaded = d->manager->load(d->scale); + bool theme_loaded = wlr_xcursor_manager_load(d->manager.get(), d->scale); if (!theme_loaded) - qCCritical(qLcCursorImage) << "Can't load cursor theme:" << name << ", size:" << size; + qCCritical(lcWlCursorImage) << "Can't load cursor theme:" << name << ", size:" << size; d->updateCursorImage(); } diff --git a/waylib/src/server/utils/wextimagecapturesourcev1impl.cpp b/waylib/src/server/utils/wextimagecapturesourcev1impl.cpp new file mode 100644 index 0000000000..9d83c26017 --- /dev/null +++ b/waylib/src/server/utils/wextimagecapturesourcev1impl.cpp @@ -0,0 +1,451 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wextimagecapturesourcev1impl.h" +#include "woutputviewport.h" +#include "woutputrenderwindow.h" +#include "wsgtextureprovider.h" +#include "wpointer.h" +#include "wtools.h" +#include "wayliblogging.h" + +#include + +#include +#include +#include +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +// QObject is not standard-layout, so the native callbacks use a registry +// instead of container_of on the capture source object. +static QHash s_captureSourceMap; + +struct CaptureFrameEvent { + wlr_ext_image_capture_source_v1_frame_event base; + wlr_buffer *buffer; + timespec when; +}; + +struct SourceResourceDestroyListener { + wl_listener listener; + WExtImageCaptureSourceV1Impl *self; +}; + +const wlr_ext_image_capture_source_v1_interface WExtImageCaptureSourceV1Impl::impl = { + .start = WExtImageCaptureSourceV1Impl::start, + .stop = WExtImageCaptureSourceV1Impl::stop, + .request_frame = WExtImageCaptureSourceV1Impl::request_frame, + .copy_frame = WExtImageCaptureSourceV1Impl::copy_frame, + .get_pointer_cursor = WExtImageCaptureSourceV1Impl::get_pointer_cursor, +}; + +WExtImageCaptureSourceV1Impl::WExtImageCaptureSourceV1Impl(QObject *parent) + : QObject(parent) +{ + wlr_ext_image_capture_source_v1_init(&source, &impl); + s_captureSourceMap.insert(&source, this); +} + +WExtImageCaptureSourceV1Impl::~WExtImageCaptureSourceV1Impl() +{ + m_inDestructor = true; + invalidate(); + s_captureSourceMap.remove(&source); +} + +void WExtImageCaptureSourceV1Impl::invalidate() +{ + if (m_finished) + return; + m_finished = true; + // The client resources may outlive this object. Detach their listeners + // before finish() so their later destruction cannot reach freed memory. + detachResourceListeners(); + // Finishing the source stops every session and makes its resources inert. + // Detach the viewport while the output and its render window still exist. + wlr_ext_image_capture_source_v1_finish(&source); + releaseViewport(); + if (!m_inDestructor) + deleteLater(); +} + +WOutputViewport *WExtImageCaptureSourceV1Impl::ensureViewport() +{ + if (m_viewport) + return m_viewport.data(); + + auto *viewport = createViewport(); + if (!viewport) + return nullptr; + Q_ASSERT(viewport->offscreen() && !viewport->hideSource()); + auto *renderWindow = viewport->outputRenderWindow(); + if (!viewport->output() || !renderWindow) { + qCWarning(lcWlImageCapture) << "Capture viewport is not attached to an output render window"; + delete viewport; + return nullptr; + } + viewport->setParent(this); + viewport->setVisible(false); + m_viewport = viewport; + + m_viewportConnections << connect(viewport, &WOutputViewport::frameRendered, + this, &WExtImageCaptureSourceV1Impl::handleFrameRendered) + << connect(viewport, &WOutputViewport::frameRenderFailed, + this, &WExtImageCaptureSourceV1Impl::handleFrameRenderFailed) + << connect(viewport, &WOutputViewport::bufferSizeChanged, + this, &WExtImageCaptureSourceV1Impl::updateConstraints) + << connect(viewport->output(), &WOutput::beforeDestroy, + this, &WExtImageCaptureSourceV1Impl::invalidate) + << connect(viewport->output(), &WOutput::enabledChanged, + this, &WExtImageCaptureSourceV1Impl::schedulePendingRender) + << connect(viewport->input(), &QObject::destroyed, + this, &WExtImageCaptureSourceV1Impl::invalidate) + << connect(renderWindow, &QQuickWindow::sceneGraphInvalidated, + this, &WExtImageCaptureSourceV1Impl::invalidate) + << connect(renderWindow, &WOutputRenderWindow::renderEnabledChanged, + this, &WExtImageCaptureSourceV1Impl::schedulePendingRender); + // wlroots sends the session constraints right after start() returns, so + // they must be valid before the viewport has rendered anything. + updateConstraints(); + return viewport; +} + +void WExtImageCaptureSourceV1Impl::releaseViewport() +{ + m_renderPending = false; + m_fallbackQueued = false; + disconnect(m_resumeRenderConnection); + m_resumeRenderConnection = {}; + if (!m_viewport) + return; + + for (const auto &connection : std::as_const(m_viewportConnections)) + disconnect(connection); + m_viewportConnections.clear(); + + m_viewport->setVisible(false); + delete m_viewport.data(); + m_viewport = nullptr; + // Keep cached constraints for startup; refresh them from the next swapchain. + m_constraintsFromSwapchain = false; +} + +bool WExtImageCaptureSourceV1Impl::accept( + wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request *request) +{ + if (m_finished) + return false; + // The request's new_id is private to wlroots, so the accept helper is the + // only supported way to create the client resource. + if (!wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request_accept(request, &source)) + return false; + + attachResourceListeners(); + return true; +} + +void WExtImageCaptureSourceV1Impl::attachResourceListeners() +{ + struct wl_resource *resource; + wl_resource_for_each(resource, &source.resources) { + if (m_resourceListeners.contains(resource)) + continue; + auto *entry = static_cast( + std::calloc(1, sizeof(SourceResourceDestroyListener))); + if (!entry) + continue; + entry->self = this; + entry->listener.notify = &WExtImageCaptureSourceV1Impl::resourceDestroyed; + m_resourceListeners.insert(resource, entry); + wl_resource_add_destroy_listener(resource, &entry->listener); + } +} + +void WExtImageCaptureSourceV1Impl::detachResourceListeners() +{ + for (auto *entry : std::as_const(m_resourceListeners)) { + wl_list_remove(&entry->listener.link); + std::free(entry); + } + m_resourceListeners.clear(); +} + +void WExtImageCaptureSourceV1Impl::resourceDestroyed(wl_listener *listener, void *data) +{ + SourceResourceDestroyListener *entry; + entry = wl_container_of(listener, entry, listener); + auto *self = entry->self; + auto *resource = static_cast(data); + self->m_resourceListeners.remove(resource); + + // wl_resource_destroy() notifies destroy listeners before wlroots unlinks + // the resource from source.resources. Unlink it now so the recycle check + // below sees the client's last resource as gone. wlroots' own destructor + // then removes an already initialized link, which is a no-op. + wl_list_remove(wl_resource_get_link(resource)); + wl_list_init(wl_resource_get_link(resource)); + std::free(entry); + + self->maybeRecycle(); +} + +void WExtImageCaptureSourceV1Impl::maybeRecycle() +{ + if (m_finished || m_recycleScheduled) + return; + if (m_numStarted > 0 || !wl_list_empty(&source.resources)) + return; + + // stop() and resource destruction run inside wlroots' session teardown. + // Finishing the source there would re-enter session_destroy() for the + // session that is still on the stack, so recycle on the next event loop + // iteration instead. + m_recycleScheduled = true; + QMetaObject::invokeMethod(this, &WExtImageCaptureSourceV1Impl::invalidate, + Qt::QueuedConnection); +} + +void WExtImageCaptureSourceV1Impl::updateConstraints() +{ + if (m_finished || !m_viewport) + return; + + const auto size = m_viewport->effectiveBufferSize(); + if (size.isEmpty()) + return; + auto *swapchain = m_viewport->swapchain(); + const bool matchingSwapchain = swapchain && swapchain->width == size.width() + && swapchain->height == size.height(); + const bool sizeChanged = source.width != uint32_t(size.width()) + || source.height != uint32_t(size.height()); + if (sizeChanged) + m_constraintsFromSwapchain = false; + if (!sizeChanged && (!matchingSwapchain || m_constraintsFromSwapchain) + && source.shm_formats_len > 0) + return; + + if (matchingSwapchain) { + // Advertise the formats of the capture swapchain, never the screen's. + if (wlr_ext_image_capture_source_v1_set_constraints_from_swapchain( + &source, swapchain, m_viewport->output()->renderer())) { + m_constraintsFromSwapchain = true; + return; + } + qCWarning(lcWlImageCapture) << "Failed to update viewport capture constraints" << size; + } + + source.width = size.width(); + source.height = size.height(); + if (source.shm_formats_len == 0) { + // The first render is asynchronous. SHM is usable before DMA-BUF + // constraints can be obtained from the viewport's own swapchain. + source.shm_formats = static_cast(std::malloc(sizeof(uint32_t))); + if (source.shm_formats) { + source.shm_formats[0] = DRM_FORMAT_ARGB8888; + source.shm_formats_len = 1; + } + } + wl_signal_emit_mutable(&source.events.constraints_update, nullptr); +} + +void WExtImageCaptureSourceV1Impl::start(wlr_ext_image_capture_source_v1 *source, bool with_cursors) +{ + auto *self = s_captureSourceMap.value(source); + Q_ASSERT(self); + self->start(with_cursors); +} + +void WExtImageCaptureSourceV1Impl::start([[maybe_unused]] bool with_cursors) +{ + if (m_finished) + return; + ++m_numStarted; + if (m_numStarted > 1) + return; + + if (!ensureViewport()) { + // wlroots has not attached the session's destroy listener yet, so the + // failure must be reported once session creation has finished. + qCWarning(lcWlImageCapture) << "No capture viewport available for a new session"; + QMetaObject::invokeMethod(this, &WExtImageCaptureSourceV1Impl::invalidate, + Qt::QueuedConnection); + return; + } + m_viewport->setVisible(true); + scheduleRender(); +} + +void WExtImageCaptureSourceV1Impl::stop(wlr_ext_image_capture_source_v1 *source) +{ + auto *self = s_captureSourceMap.value(source); + Q_ASSERT(self); + self->stop(); +} + +void WExtImageCaptureSourceV1Impl::stop() +{ + Q_ASSERT(m_numStarted > 0); + if (--m_numStarted > 0 || m_finished) + return; + + releaseViewport(); + maybeRecycle(); +} + +void WExtImageCaptureSourceV1Impl::request_frame(wlr_ext_image_capture_source_v1 *source, + [[maybe_unused]] bool schedule_frame) +{ + auto *self = s_captureSourceMap.value(source); + Q_ASSERT(self); + self->scheduleRender(); +} + +void WExtImageCaptureSourceV1Impl::scheduleRender() +{ + if (m_finished || m_numStarted == 0 || !m_viewport) + return; + // An on-demand viewport needs a new render regardless of wlroots' damage hint. + m_renderPending = true; + schedulePendingRender(); +} + +void WExtImageCaptureSourceV1Impl::schedulePendingRender() +{ + if (m_finished || !m_renderPending || m_numStarted == 0 || !m_viewport) + return; + auto *renderWindow = m_viewport->outputRenderWindow(); + if (!renderWindow || !m_viewport->output()) { + invalidate(); + return; + } + if (!renderWindow->renderEnabled()) + return; + if (m_viewport->output()->isEnabled()) { + renderWindow->update(m_viewport); + return; + } + if (m_fallbackQueued || m_resumeRenderConnection) + return; + m_fallbackQueued = true; + // The viewport context cancels this job when the last session releases the pipeline. + QMetaObject::invokeMethod(m_viewport.data(), [this] { renderFallback(); }, Qt::QueuedConnection); +} + +void WExtImageCaptureSourceV1Impl::renderFallback() +{ + m_fallbackQueued = false; + if (m_finished || !m_renderPending || m_numStarted == 0 || !m_viewport) + return; + auto *renderWindow = m_viewport->outputRenderWindow(); + if (!renderWindow || !m_viewport->output()) { + invalidate(); + return; + } + if (!renderWindow->renderEnabled()) + return; + if (m_viewport->output()->isEnabled()) { + schedulePendingRender(); + return; + } + if (renderWindow->inRendering()) { + m_resumeRenderConnection = connect(renderWindow, &WOutputRenderWindow::renderEnd, + this, &WExtImageCaptureSourceV1Impl::resumeRender, + Qt::QueuedConnection); + return; + } + m_viewport->render(false); +} + +void WExtImageCaptureSourceV1Impl::resumeRender() +{ + disconnect(m_resumeRenderConnection); + m_resumeRenderConnection = {}; + schedulePendingRender(); +} + +void WExtImageCaptureSourceV1Impl::handleFrameRendered() +{ + if (m_finished || m_numStarted == 0 || !m_viewport) + return; + + auto *provider = m_viewport->wTextureProvider(); + auto *buffer = provider ? provider->wlrBuffer() : nullptr; + if (!buffer) { + handleFrameRenderFailed(); + return; + } + WBufferUnlockPtr bufferGuard(wlr_buffer_lock(buffer)); + sendFrame(buffer); +} + +void WExtImageCaptureSourceV1Impl::handleFrameRenderFailed() +{ + if (m_finished || !m_renderPending || m_numStarted == 0 || !m_viewport) + return; + sendFrame(nullptr); +} + +void WExtImageCaptureSourceV1Impl::sendFrame(wlr_buffer *buffer) +{ + m_renderPending = false; + disconnect(m_resumeRenderConnection); + m_resumeRenderConnection = {}; + if (buffer) + updateConstraints(); + + // Non-empty damage routes failures through wlroots to every pending frame. + WPixmanRegion damage(0, 0, + buffer ? buffer->width : qMax(1u, source.width), + buffer ? buffer->height : qMax(1u, source.height)); + CaptureFrameEvent event { + .base = { .damage = damage.get() }, + .buffer = buffer, + .when = {}, + }; + if (buffer) + clock_gettime(CLOCK_MONOTONIC, &event.when); + wl_signal_emit_mutable(&source.events.frame, &event.base); +} + +void WExtImageCaptureSourceV1Impl::copy_frame(wlr_ext_image_capture_source_v1 *source, + wlr_ext_image_copy_capture_frame_v1 *dst_frame, + wlr_ext_image_capture_source_v1_frame_event *frame_event) +{ + auto *self = s_captureSourceMap.value(source); + Q_ASSERT(self); + self->copy_frame(dst_frame, frame_event); +} + +void WExtImageCaptureSourceV1Impl::copy_frame(wlr_ext_image_copy_capture_frame_v1 *dst_frame, + wlr_ext_image_capture_source_v1_frame_event *frame_event) +{ + if (m_finished || m_numStarted == 0 || !m_viewport) { + wlr_ext_image_copy_capture_frame_v1_fail(dst_frame, EXT_IMAGE_COPY_CAPTURE_FRAME_V1_FAILURE_REASON_STOPPED); + return; + } + + // base is the first member; the event's buffer is locked throughout the + // synchronous frame signal, including all sessions copying this frame. + auto *event = reinterpret_cast(frame_event); + if (!event->buffer) { + wlr_ext_image_copy_capture_frame_v1_fail(dst_frame, EXT_IMAGE_COPY_CAPTURE_FRAME_V1_FAILURE_REASON_UNKNOWN); + return; + } + if (wlr_ext_image_copy_capture_frame_v1_copy_buffer( + dst_frame, event->buffer, m_viewport->output()->renderer())) { + wlr_ext_image_copy_capture_frame_v1_ready(dst_frame, WL_OUTPUT_TRANSFORM_NORMAL, &event->when); + } + // copy_buffer already sends failed and destroys the native frame on error. + // Sending another failure here would use a freed frame (notably on resize). +} + +wlr_ext_image_capture_source_v1_cursor *WExtImageCaptureSourceV1Impl::get_pointer_cursor( + [[maybe_unused]] wlr_ext_image_capture_source_v1 *source, [[maybe_unused]] wlr_seat *seat) +{ + // Cursor capture is not implemented for toplevel sources yet. + return nullptr; +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/utils/wextimagecapturesourcev1impl.h b/waylib/src/server/utils/wextimagecapturesourcev1impl.h new file mode 100644 index 0000000000..c566c96560 --- /dev/null +++ b/waylib/src/server/utils/wextimagecapturesourcev1impl.h @@ -0,0 +1,90 @@ +// Copyright (C) 2025-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include +#include + +#include +#include +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WOutputViewport; +struct SourceResourceDestroyListener; + +class WAYLIB_SERVER_EXPORT WExtImageCaptureSourceV1Impl : public QObject +{ + Q_OBJECT +public: + explicit WExtImageCaptureSourceV1Impl(QObject *parent = nullptr); + ~WExtImageCaptureSourceV1Impl() override; + + wlr_ext_image_capture_source_v1 *handle() { return &source; } + + // Accepts a foreign-toplevel capture request and tracks the client + // resource, so the source can be recycled once the client destroys it. + bool accept(wlr_ext_foreign_toplevel_image_capture_source_manager_v1_request *request); + +public Q_SLOTS: + void invalidate(); + +protected: + // Creates the offscreen viewport for the next capture session. Called from + // start(), before wlroots sends the session constraints, and again for + // every new session after stop() released the previous viewport. + virtual WOutputViewport *createViewport() = 0; + +private: + static const struct wlr_ext_image_capture_source_v1_interface impl; + void start(bool with_cursors); + void stop(); + void scheduleRender(); + void renderFallback(); + void sendFrame(wlr_buffer *buffer); + void copy_frame(wlr_ext_image_copy_capture_frame_v1 *dst_frame, + wlr_ext_image_capture_source_v1_frame_event *frame_event); + static void start(struct wlr_ext_image_capture_source_v1 *source, bool with_cursors); + static void stop(struct wlr_ext_image_capture_source_v1 *source); + static void request_frame(struct wlr_ext_image_capture_source_v1 *source, bool schedule_frame); + static void copy_frame(struct wlr_ext_image_capture_source_v1 *source, + wlr_ext_image_copy_capture_frame_v1 *dst_frame, + wlr_ext_image_capture_source_v1_frame_event *frame_event); + static wlr_ext_image_capture_source_v1_cursor *get_pointer_cursor( + struct wlr_ext_image_capture_source_v1 *source, struct wlr_seat *seat); + + WOutputViewport *ensureViewport(); + void releaseViewport(); + void attachResourceListeners(); + void detachResourceListeners(); + // Reclaims this source when no client resource and no session are left. + void maybeRecycle(); + static void resourceDestroyed(wl_listener *listener, void *data); + +private Q_SLOTS: + void handleFrameRendered(); + void handleFrameRenderFailed(); + void updateConstraints(); + void schedulePendingRender(); + void resumeRender(); + +private: + wlr_ext_image_capture_source_v1 source; + + QPointer m_viewport; + QList m_viewportConnections; + QMetaObject::Connection m_resumeRenderConnection; + QHash m_resourceListeners; + size_t m_numStarted = 0; + bool m_renderPending = false; + bool m_fallbackQueued = false; + bool m_constraintsFromSwapchain = false; + bool m_finished = false; + bool m_recycleScheduled = false; + bool m_inDestructor = false; +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/utils/wimagebuffer.cpp b/waylib/src/server/utils/wimagebuffer.cpp index 2808d74022..455230dfad 100644 --- a/waylib/src/server/utils/wimagebuffer.cpp +++ b/waylib/src/server/utils/wimagebuffer.cpp @@ -1,7 +1,8 @@ -// Copyright (C) 2023 rewine . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wimagebuffer.h" +#include #include "wtools.h" #include @@ -9,38 +10,80 @@ WAYLIB_SERVER_BEGIN_NAMESPACE +WImageBufferImpl *WImageBufferImpl::fromBuffer(wlr_buffer *buffer) +{ + if (buffer->impl != &WImageBufferImpl::impl) + return nullptr; + return W_CONTAINER_OF(buffer, WImageBufferImpl, buffer); +} + +wlr_buffer *WImageBufferImpl::create(const QImage &bufferImage) +{ + return (new WImageBufferImpl(bufferImage))->handle(); +} + +const struct wlr_buffer_impl WImageBufferImpl::impl = { + .destroy = WImageBufferImpl::destroy, + .get_dmabuf = NULL, + .get_shm = WImageBufferImpl::get_shm, + .begin_data_ptr_access = WImageBufferImpl::begin_data_ptr_access, + .end_data_ptr_access = WImageBufferImpl::end_data_ptr_access, +}; + WImageBufferImpl::WImageBufferImpl(const QImage &bufferImage) + : buffer{} + , image(new QImage(bufferImage)) { auto newFormat = WTools::convertToDrmSupportedFormat(bufferImage.format()); if (newFormat != bufferImage.format()) { - image = bufferImage.convertedTo(newFormat); - } else { - image = bufferImage; + *image = image->convertedTo(newFormat); } + wlr_buffer_init(&buffer, &impl, image->width(), image->height()); } WImageBufferImpl::~WImageBufferImpl() { - + delete image; } -bool WImageBufferImpl::begin_data_ptr_access(uint32_t flags, void **data, uint32_t *format, size_t *stride) +bool WImageBufferImpl::begin_data_ptr_access(struct wlr_buffer *buffer, uint32_t flags, + void **data, uint32_t *format, size_t *stride) { - if (!image.constBits()) { + auto *self = WImageBufferImpl::fromBuffer(buffer); + Q_ASSERT(self); + if (!self->image->constBits()) { return false; } if (flags & WLR_BUFFER_DATA_PTR_ACCESS_WRITE) { return false; } - *data = (void *)image.constBits(); - *format = WTools::toDrmFormat(image.format()); - *stride = image.bytesPerLine(); + *data = (void *)self->image->constBits(); + *format = WTools::toDrmFormat(self->image->format()); + *stride = self->image->bytesPerLine(); return true; } -void WImageBufferImpl::end_data_ptr_access() +bool WImageBufferImpl::get_shm(struct wlr_buffer * /*buffer*/, struct wlr_shm_attributes * /*attribs*/) +{ + // A QImage-backed buffer only supports data_ptr access; there is no + // real SHM file descriptor to hand out. Faking fd=0 would make + // wl_shm clients map the compositor's fd 0 as buffer memory. + return false; +} + +void WImageBufferImpl::end_data_ptr_access(struct wlr_buffer * /*buffer*/) { // This space is intentionally left blank } +void WImageBufferImpl::destroy(struct wlr_buffer *buffer) +{ + auto *self = WImageBufferImpl::fromBuffer(buffer); + Q_ASSERT(self); + // Standard wlroots release path: emits events.destroy, finishes the addon + // set and asserts no listeners remain attached. + wlr_buffer_finish(buffer); + delete self; +} + WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/utils/wimagebuffer.h b/waylib/src/server/utils/wimagebuffer.h index 38470b5c01..9043becdaa 100644 --- a/waylib/src/server/utils/wimagebuffer.h +++ b/waylib/src/server/utils/wimagebuffer.h @@ -1,25 +1,40 @@ -// Copyright (C) 2023 rewine . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once #include -#include +#include #include +#include + WAYLIB_SERVER_BEGIN_NAMESPACE -class WAYLIB_SERVER_EXPORT WImageBufferImpl : public QW_NAMESPACE::qw_buffer_interface +class WAYLIB_SERVER_EXPORT WImageBufferImpl { public: + static wlr_buffer *create(const QImage &bufferImage); WImageBufferImpl(const QImage &bufferImage); ~WImageBufferImpl(); - QW_INTERFACE(begin_data_ptr_access, bool, uint32_t flags, void **data, uint32_t *format, size_t *stride); - QW_INTERFACE(end_data_ptr_access, void); + wlr_buffer *handle() { return &buffer; } private: - QImage image; + static const struct wlr_buffer_impl impl; + static bool get_shm(struct wlr_buffer *buffer, struct wlr_shm_attributes *attribs); + static bool begin_data_ptr_access(struct wlr_buffer *buffer, uint32_t flags, + void **data, uint32_t *format, size_t *stride); + static void end_data_ptr_access(struct wlr_buffer *buffer); + static void destroy(struct wlr_buffer *buffer); + + static WImageBufferImpl *fromBuffer(wlr_buffer *buffer); + + // QImage is kept behind a raw pointer so this class stays standard-layout + // (std::unique_ptr's layout is implementation-defined across GCC/clang), + // allowing container_of recovery of the owner from the wlr_buffer. + wlr_buffer buffer; + QImage *image; }; WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/utils/wlogging.h b/waylib/src/server/utils/wlogging.h new file mode 100644 index 0000000000..71ba7a6935 --- /dev/null +++ b/waylib/src/server/utils/wlogging.h @@ -0,0 +1,35 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// Routes wlroots' C logging into the Qt logging system. Instead of letting +// wlroots write to stderr, every wlr_log call is forwarded to the "wlroots" +// QLoggingCategory so it honors QT_LOGGING_RULES filtering and Qt's message +// pattern. + +#pragma once + +#include +#include + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +class WAYLIB_SERVER_EXPORT WLog +{ +public: + // Install the default callback, which routes wlroots messages to the + // "wlroots" Qt logging category. + static void init(wlr_log_importance verbosity = WLR_DEBUG) { + init(verbosity, &defaultLogCallback); + } + // Install a custom wlroots log callback (e.g. for testing or capture). + static void init(wlr_log_importance verbosity, wlr_log_func_t callback) { + wlr_log_init(verbosity, callback); + } + +private: + static void defaultLogCallback(wlr_log_importance verbosity, const char *fmt, va_list args); +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/utils/wscopedvalue.h b/waylib/src/server/utils/wscopedvalue.h new file mode 100644 index 0000000000..b7bf55cde0 --- /dev/null +++ b/waylib/src/server/utils/wscopedvalue.h @@ -0,0 +1,51 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#pragma once + +#include +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +// Generic RAII wrapper for value-type wlroots objects that follow the +// init()/finish() (or plain zero-init + finish()) lifecycle, replacing the +// error-prone manual pattern: +// T value; T::init(&value); ... T::finish(&value); +// which leaks the object's resources on every early-return path. +// +// template +// - FinishFn(T*) is invoked on destruction (required). +// - InitFn(T*) is invoked on construction; when omitted the value is simply +// zero-initialized (e.g. wlr_drm_format, whose init is a plain memset). +template +class WScopedValue +{ +public: + WScopedValue() + { + if constexpr (InitFn != nullptr) + InitFn(&m_value); + else + m_value = {}; + } + ~WScopedValue() { FinishFn(&m_value); } + + WScopedValue(const WScopedValue &) = delete; + WScopedValue &operator=(const WScopedValue &) = delete; + + T *operator->() { return &m_value; } + const T *operator->() const { return &m_value; } + T *get() { return &m_value; } + const T *get() const { return &m_value; } + +private: + T m_value {}; +}; + +// Common specializations (add more value types as they get owned). +using WOutputStateGuard = WScopedValue; +using WDamageRing = WScopedValue; +using WDrmFormat = WScopedValue; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/utils/wscoplistener.cpp b/waylib/src/server/utils/wscoplistener.cpp new file mode 100644 index 0000000000..6e8a9038dc --- /dev/null +++ b/waylib/src/server/utils/wscoplistener.cpp @@ -0,0 +1,87 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wscoplistener.h" +#include "wcontainerof.h" + +WAYLIB_SERVER_BEGIN_NAMESPACE + +WScopedListener::WScopedListener(WScopedListener &&other) noexcept + : m_signal(other.m_signal) + , m_callback(other.m_callback) + , m_deleter(other.m_deleter) + , m_context(other.m_context) + , m_connected(std::exchange(other.m_connected, false)) +{ + if (m_connected) { + // The wl_listener node now lives at this instance's address, but the + // signal still points at the old node: detach and re-link it. + if (other.m_listener.link.next) + wl_list_remove(&other.m_listener.link); + m_listener.notify = &WScopedListener::trampoline; + wl_signal_add(m_signal, &m_listener); + } else { + m_listener = other.m_listener; + } + other.m_signal = nullptr; + other.m_callback = nullptr; + other.m_deleter = nullptr; + other.m_context = nullptr; + other.m_listener = {}; +} + +WScopedListener &WScopedListener::operator=(WScopedListener &&other) noexcept +{ + if (this == &other) + return *this; + disconnect(); + if (m_deleter) + m_deleter(m_context); + m_signal = other.m_signal; + m_callback = other.m_callback; + m_deleter = other.m_deleter; + m_context = other.m_context; + m_connected = std::exchange(other.m_connected, false); + if (m_connected) { + if (other.m_listener.link.next) + wl_list_remove(&other.m_listener.link); + m_listener.notify = &WScopedListener::trampoline; + wl_signal_add(m_signal, &m_listener); + } else { + m_listener = other.m_listener; + } + other.m_signal = nullptr; + other.m_callback = nullptr; + other.m_deleter = nullptr; + other.m_context = nullptr; + other.m_listener = {}; + return *this; +} + +void WScopedListener::disconnect() +{ + if (!m_connected) + return; + if (m_listener.link.next) + wl_list_remove(&m_listener.link); + m_listener = {}; + m_connected = false; + m_signal = nullptr; + // The closure is kept in a shared_ptr (see initLambda): releasing it + // here or in ~WScopedListener is safe even from inside the listener's + // own callback — invoke() already holds its own copy, so the closure + // lives until the emission returns. +} + +void WScopedListener::trampoline(wl_listener *listener, void *data) +{ + // Capture the closure (and thus a reference to it) before invoking: + // the callback may destroy this listener, which releases the closure + // storage; the shared_ptr copy keeps the closure alive until the + // emission returns. + WScopedListener *self = nullptr; + self = W_CONTAINER_OF(listener, WScopedListener, m_listener); + self->m_callback(self->m_context, data); +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/utils/wscoplistener.h b/waylib/src/server/utils/wscoplistener.h new file mode 100644 index 0000000000..5fe8160a60 --- /dev/null +++ b/waylib/src/server/utils/wscoplistener.h @@ -0,0 +1,234 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#pragma once + +#include + +#include + +#include +#include + +#include + +WAYLIB_SERVER_BEGIN_NAMESPACE + +// Extracts the first parameter type of a lambda/functor's operator(). +template +struct LambdaTraits : LambdaTraits::operator())> {}; +template +struct LambdaTraits { + using FirstArgument = A; +}; +template +struct LambdaTraits { + using FirstArgument = A; +}; +template +struct LambdaTraits { + using FirstArgument = A; +}; +template +struct LambdaTraits { + using FirstArgument = A; +}; +template +struct LambdaTraits { + using FirstArgument = void; +}; +template +struct LambdaTraits { + using FirstArgument = void; +}; +template +struct LambdaTraits { + using FirstArgument = void; +}; +template +struct LambdaTraits { + using FirstArgument = void; +}; + +// RAII wrapper for wl_signal: auto wl_signal_add on init, auto wl_list_remove +// on destruction. Supports member-function and lambda callbacks. +// Never forwards wl_signal to Qt signals. +// +// Deliberately standard-layout: the trampoline recovers the owning instance +// with W_CONTAINER_OF (offsetof), which requires a standard-layout type. +// Callbacks are type-erased through a heap-allocated closure + function +// pointers instead of std::function. +class WAYLIB_SERVER_EXPORT WScopedListener +{ +public: + WScopedListener() = default; + ~WScopedListener() { + disconnect(); + if (m_deleter) + m_deleter(m_context); + } + + WScopedListener(WScopedListener &&other) noexcept; + WScopedListener &operator=(WScopedListener &&other) noexcept; + + WScopedListener(const WScopedListener &) = delete; + WScopedListener &operator=(const WScopedListener &) = delete; + + // Member function callback: void (T::*)(Event*); T may be a base class of obj. + template + void init(wl_signal *signal, Derived *obj, R (Base::*func)(Event *)) { + initLambda(signal, [obj, func](void *data) { + (obj->*func)(static_cast(data)); + }); + } + template + void init(wl_signal *signal, Derived *obj, R (Base::*func)(Event *) const) { + initLambda(signal, [obj, func](void *data) { + (obj->*func)(static_cast(data)); + }); + } + // Member function callback without arguments: void (T::*)() + template + void init(wl_signal *signal, Derived *obj, R (Base::*func)()) { + initLambda(signal, [obj, func](void * /*data*/) { + (obj->*func)(); + }); + } + template + void init(wl_signal *signal, Derived *obj, R (Base::*func)() const) { + initLambda(signal, [obj, func](void * /*data*/) { + (obj->*func)(); + }); + } + + // Lambda / functor callback with arbitrary event-pointer parameter. + // The lambda's single parameter type is extracted via operator() and the + // raw void* data is converted to it at invoke time. + template + requires (!std::is_member_function_pointer_v>) + void init(wl_signal *signal, void * /*obj*/, Callable &&callback) { + initLambda(signal, std::forward(callback)); + } + // 2-arg form for plain callbacks without an object. + template + requires (!std::is_member_function_pointer_v>) + void init(wl_signal *signal, Callable &&callback) { + initLambda(signal, std::forward(callback)); + } + + void disconnect(); + [[nodiscard]] bool isConnected() const { return m_connected; } + wl_listener *listener() { return &m_listener; } + +private: + template + void initLambda(wl_signal *signal, Callable &&callback) { + // const-qualified lvalue lambdas must still be storable in a void*. + using CallableType = std::remove_cv_t>; + static_assert(requires { typename LambdaTraits::FirstArgument; }, + "WScopedListener: callback must take zero or one argument " + "(a pointer to the event type)."); + disconnect(); + // Release the previous closure (if any): disconnect() only unlinks + // the wl_listener node — the heap-allocated closure survives until + // here and must be freed before overwriting m_context/m_deleter, + // otherwise re-init leaks the old closure. + if (m_deleter) { + m_deleter(m_context); + m_callback = nullptr; + m_deleter = nullptr; + m_context = nullptr; + } + // Heap-allocate the closure: standard-layout forbids storing it + // inline (std::function would break layout). The closure is kept in + // a shared_ptr so that destroying this listener from inside its own + // callback (a very common pattern for wl_signal destroy handlers) + // only drops one reference — the callback keeps executing on its own + // copy and the closure is freed when the emission returns. + m_context = new std::shared_ptr( + std::make_shared(std::forward(callback))); + m_callback = &invoke; + m_deleter = &destroy; + m_listener.notify = &WScopedListener::trampoline; + m_signal = signal; + wl_signal_add(signal, &m_listener); + m_connected = true; + } + template + static void invoke(void *ctx, void *data) { + using ArgType = typename LambdaTraits::FirstArgument; + // Take a local copy of the shared_ptr first: the owning listener may + // be destroyed (and its closure released) while this callback runs. + auto closure = *static_cast *>(ctx); + if constexpr (std::is_same_v) { + (*closure)(); + } else { + (*closure)(static_cast(data)); + } + } + template + static void destroy(void *ctx) { + delete static_cast *>(ctx); + } + + static void trampoline(wl_listener *listener, void *data); + + // The signal this listener is attached to; needed to re-link the + // wl_listener node on move (the node address changes, the signal does + // not). Null while disconnected. + wl_signal *m_signal = nullptr; + wl_listener m_listener {}; + void (*m_callback)(void *, void *) = nullptr; + void (*m_deleter)(void *) = nullptr; + void *m_context = nullptr; + bool m_connected = false; +}; + +// A growable set of wl_signal listeners owned together. Every listener is +// detached when the list is cleared or destroyed, so a wrapper can keep a +// list as a member and never manage individual lifetimes. Not copyable: +// moving re-links the wl_listener nodes (WScopedListener keeps m_signal). +class WAYLIB_SERVER_EXPORT WScopedListenerList +{ +public: + WScopedListenerList() = default; + ~WScopedListenerList() = default; + WScopedListenerList(WScopedListenerList &&) noexcept = default; + WScopedListenerList &operator=(WScopedListenerList &&) noexcept = default; + WScopedListenerList(const WScopedListenerList &) = delete; + WScopedListenerList &operator=(const WScopedListenerList &) = delete; + + template + void add(Args&&... args) { + // Init into a temporary first: if init throws (heap alloc), the + // temporary cleans up and the deque is untouched. Move into the + // deque only on success — deque push_back never relocates existing + // elements, so their wl_listener node addresses stay stable. + WScopedListener tmp; + tmp.init(std::forward(args)...); + m_listeners.push_back(std::move(tmp)); + } + + // Detach every registered listener. Safe to call from a callback that + // belongs to this list; the list itself may even be destroyed right + // after (closures are shared_ptr-managed and outlive the emission). + void disconnect() { + for (auto &listener : m_listeners) + listener.disconnect(); + } + + // Detach and drop every registered listener. Safe from inside a + // callback of this list: each closure keeps itself alive while its + // callback is running. + void clear() { + disconnect(); + m_listeners.clear(); + } + +private: + // std::deque: WScopedListener is move-only and deque growth never + // relocates existing elements — moving a WScopedListener would re-add + // its wl_listener at the signal tail. + std::deque m_listeners; +}; + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/utils/wthreadutils.h b/waylib/src/server/utils/wthreadutils.h index 1fca79df50..cdc1305232 100644 --- a/waylib/src/server/utils/wthreadutils.h +++ b/waylib/src/server/utils/wthreadutils.h @@ -4,6 +4,7 @@ #pragma once #include +#include "wayliblogging.h" #include #include @@ -53,7 +54,7 @@ class WAYLIB_SERVER_EXPORT WThreadUtil final { auto future = run(std::forward(args)...); if (!thread()->isRunning()) { - qWarning() << "The target thread is not running, maybe lead to deadlock."; + qCWarning(lcWlThreadUtils) << "The target thread is not running, maybe lead to deadlock."; } future.waitForFinished(); diff --git a/waylib/src/server/utils/wtools.cpp b/waylib/src/server/utils/wtools.cpp index ed40803420..d9c5324786 100644 --- a/waylib/src/server/utils/wtools.cpp +++ b/waylib/src/server/utils/wtools.cpp @@ -1,13 +1,9 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "wtools.h" -#include - -extern "C" { -#include -} +#include #include #include @@ -233,7 +229,7 @@ wl_shm_format_t WTools::drmToShmFormat(uint32_t drmFmt) } } -QRegion WTools::fromPixmanRegion(pixman_region32 *region) +QRegion WTools::fromPixmanRegion(const pixman_region32 *region) { int rectCount = 0; auto rects = pixman_region32_rectangles(region, &rectCount); @@ -267,7 +263,14 @@ bool WTools::toPixmanRegion(const QRegion ®ion, pixman_region32 *pixmanRegion box.y2 = r.bottom() + 1; } bool ok = pixman_region32_init_rects(pixmanRegion, rects.constData(), rects.count()); - Q_ASSERT(!ok || pixman_region32_n_rects(pixmanRegion) == rects.count()); + // NOTE: Do not assert pixman_region32_n_rects(pixmanRegion) == rects.count(). + // pixman_region32_init_rects always normalizes the input boxes (merges + // horizontally adjacent rects, splits interleaving bands), while the + // QRegion's rect list (e.g. built via QTransform::map -> setRects) is not + // guaranteed to be in pixman canonical form, so the final rect count may + // legitimately differ from the input count. + // Note: The counterpart assertion in fromPixmanRegion() is safe because + // pixman's output rectangles are always in canonical form. return ok; } @@ -309,4 +312,17 @@ Qt::Edges WTools::toQtEdge(uint32_t edges) return qedges; } +// WPixmanRegion implementation +WPixmanRegion::WPixmanRegion() { + pixman_region32_init(&r); +} + +WPixmanRegion::WPixmanRegion(int x, int y, int w, int h) { + pixman_region32_init_rect(&r, x, y, w, h); +} + +WPixmanRegion::~WPixmanRegion() { + pixman_region32_fini(&r); +} + WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/utils/wtools.h b/waylib/src/server/utils/wtools.h index 7c865efabd..a189aa220d 100644 --- a/waylib/src/server/utils/wtools.h +++ b/waylib/src/server/utils/wtools.h @@ -12,6 +12,10 @@ struct pixman_region32; typedef int wl_shm_format_t; +extern "C" { +#include +} + QT_BEGIN_NAMESPACE class QQuickItem; QT_END_NAMESPACE @@ -27,13 +31,34 @@ class WAYLIB_SERVER_EXPORT WTools static QImage::Format convertToDrmSupportedFormat(QImage::Format format); static uint32_t shmToDrmFormat(wl_shm_format_t shmFmt); static wl_shm_format_t drmToShmFormat(uint32_t drmFmt); - static QRegion fromPixmanRegion(pixman_region32 *region); + static QRegion fromPixmanRegion(const pixman_region32 *region); static bool toPixmanRegion(const QRegion ®ion, pixman_region32 *pixmanRegion); static QRect fromWLRBox(void *box); static void toWLRBox(const QRect &rect, void *box); static Qt::Edges toQtEdge(uint32_t edges); }; +// RAII wrapper for pixman region +struct WAYLIB_SERVER_EXPORT WPixmanRegion { + pixman_region32_t r; + + // Default constructor - initializes empty region + WPixmanRegion(); + // Constructor with rectangle - initializes with specific rect + WPixmanRegion(int x, int y, int w, int h); + ~WPixmanRegion(); + + pixman_region32_t* get() { return &r; } + + // Conversion operator for compatibility + inline operator pixman_region32_t*() { return &r; } + + // Utility method to check if region is empty + inline bool isEmpty() const { + return !pixman_region32_not_empty(&r); + } +}; + WAYLIB_SERVER_END_NAMESPACE #endif // WTOOLS_H diff --git a/waylib/src/server/utils/wwrappointer.h b/waylib/src/server/utils/wwrappointer.h deleted file mode 100644 index 9d421e7988..0000000000 --- a/waylib/src/server/utils/wwrappointer.h +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. -// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only -#pragma once - -#include -#include -#include - -template -concept IsWrapObject = std::is_base_of_v && requires(T t) { - { t.aboutToBeInvalidated() } -> std::same_as; -}; - -template -struct WWrapData -{ - QPointer ptr; - QMetaObject::Connection conn; - - WWrapData(T *p) - : ptr(p) - { - Q_ASSERT_X(p, __func__, "WrapData is only for non-null ptr."); - conn = QObject::connect(p, - &T::aboutToBeInvalidated, - p, - std::bind(&WWrapData::invalidate, this)); - Q_ASSERT_X(conn, __func__, "Connection should be valid for aboutToBeInvalidated."); - } - - void invalidate() - { - Q_ASSERT_X(ptr, __func__, "WrapPointer should be invalid before raw pointer destroyed."); - ptr = nullptr; - Q_ASSERT_X(conn, __func__, "Connection should be valid until invalidated."); - QObject::disconnect(conn); - } - - ~WWrapData() - { - if (ptr) - invalidate(); - } -}; - -template -class WWrapPointer -{ -public: - WWrapPointer() noexcept = default; - - WWrapPointer(std::nullptr_t) noexcept - : WWrapPointer{} - { - } - - WWrapPointer(T *p) - : wd(new WWrapData(p)) - { - } - - WWrapPointer(WWrapPointer &&other) - { - wd = std::move(other.wd); - } - - WWrapPointer(const WWrapPointer &other) - { - wd = other.wd; - } - - WWrapPointer &operator=(const WWrapPointer &other) - { - wd = other.wd; - return *this; - } - - WWrapPointer &operator=(WWrapPointer &&other) - { - wd = std::move(other.wd); - return *this; - } - - ~WWrapPointer() { } - - WWrapPointer &operator=(T *p) - { - wd.reset(p ? new WWrapData(p) : nullptr); - return *this; - } - - T *data() const noexcept - { - return wd.data() ? wd.data()->ptr : nullptr; - } - - T *get() const noexcept - { - return data(); - } - - T *operator->() const noexcept - { - return data(); - } - - T &operator*() const noexcept - { - return *data(); - } - - operator T *() const noexcept - { - return data(); - } - -private: - QSharedPointer> wd; -}; diff --git a/waylib/src/server/wayliblogging.cpp b/waylib/src/server/wayliblogging.cpp new file mode 100644 index 0000000000..89ebe5de43 --- /dev/null +++ b/waylib/src/server/wayliblogging.cpp @@ -0,0 +1,105 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "wayliblogging.h" + +#include + +// Waylib logging category definitions +// Naming convention: lcWl + PascalCase module name +// String ID convention: waylib.[.] or waylib.protocols. or waylib.qtquick. or waylib.utils. + +// Kernel - Core +Q_LOGGING_CATEGORY(lcWlObject, "waylib.object", QtInfoMsg) // WObject listener ownership +Q_LOGGING_CATEGORY(lcWlSocket, "waylib.socket", QtInfoMsg) // Wayland socket lifecycle +Q_LOGGING_CATEGORY(lcWlSeat, "waylib.seat", QtInfoMsg) // Seat management (keyboard focus, capability) +Q_LOGGING_CATEGORY(lcWlOutput, "waylib.output", QtInfoMsg) // Output lifecycle and configuration +Q_LOGGING_CATEGORY(lcWlOutputDrm, "waylib.output.drm", QtInfoMsg) // DRM/KMS format negotiation and hardware rendering +Q_LOGGING_CATEGORY(lcWlOutputBuffer, "waylib.output.buffer", QtDebugMsg) // Output buffer commit and swap +Q_LOGGING_CATEGORY(lcWlInput, "waylib.input", QtInfoMsg) // Generic input device events +Q_LOGGING_CATEGORY(lcWlCursor, "waylib.cursor", QtInfoMsg) // Cursor image and theme management + +// Kernel - Input subcategories +Q_LOGGING_CATEGORY(lcWlPointer, "waylib.input.pointer", QtInfoMsg) // Pointer/mouse button and motion events +Q_LOGGING_CATEGORY(lcWlTouch, "waylib.input.touch", QtInfoMsg) // Touch down/move/up/cancel events +Q_LOGGING_CATEGORY(lcWlGesture, "waylib.input.gesture", QtInfoMsg) // Touchpad gesture begin/update/end and hold +Q_LOGGING_CATEGORY(lcWlDrag, "waylib.input.drag", QtInfoMsg) // DnD start/motion/drop operations + +// QtQuick +Q_LOGGING_CATEGORY(lcWlTextureProvider, "waylib.texture.provider") // QSGTexture provider bridging +Q_LOGGING_CATEGORY(lcWlSurface, "waylib.qtquick.surface", QtInfoMsg) // QtQuick surface item lifecycle and rendering +// More verbose in debug builds for texture inspection +#ifdef QT_DEBUG +Q_LOGGING_CATEGORY(lcWlQtQuickTexture, "waylib.qtquick.texture", QtDebugMsg) +#else +Q_LOGGING_CATEGORY(lcWlQtQuickTexture, "waylib.qtquick.texture", QtInfoMsg) +#endif +// More verbose in debug builds for render diagnostics +#ifdef QT_DEBUG +Q_LOGGING_CATEGORY(lcWlRenderer, "waylib.renderer", QtDebugMsg) +#else +Q_LOGGING_CATEGORY(lcWlRenderer, "waylib.renderer", QtWarningMsg) +#endif +Q_LOGGING_CATEGORY(lcWlBufferItem, "waylib.qtquick.bufferitem", QtInfoMsg) // Buffer item commit and damage + +// Utils +Q_LOGGING_CATEGORY(lcWlImageCapture, "waylib.utils.imagecapture") // Ext-image-capture-source frame capture +Q_LOGGING_CATEGORY(lcWlCursorImage, "waylib.utils.cursorimage", QtWarningMsg) // Cursor image scaling and conversion +Q_LOGGING_CATEGORY(lcWlBufferDumper, "waylib.utils.bufferdumper", QtWarningMsg) // Buffer dump for debugging +Q_LOGGING_CATEGORY(lcWlThreadUtils, "waylib.utils.thread", QtWarningMsg) // Thread utility async call and deadlock warning + +// Protocols +Q_LOGGING_CATEGORY(lcWlForeignToplevel, "waylib.protocols.foreigntoplevel", QtWarningMsg) // wlr-foreign-toplevel-v1 +Q_LOGGING_CATEGORY(lcWlInputMethod, "waylib.protocols.inputmethod", QtInfoMsg) // Input method v2 and virtual keyboard +Q_LOGGING_CATEGORY(lcWlExtForeignToplevel, "waylib.protocols.extforeigntoplevel", QtWarningMsg) // ext-foreign-toplevel-list-v1 +Q_LOGGING_CATEGORY(lcWlTextInput, "waylib.protocols.textinput", QtInfoMsg) // Text input v1/v2/v3 protocol +Q_LOGGING_CATEGORY(lcWlRemoteSubsurface, "waylib.protocols.remotesubsurface", QtWarningMsg) // treeland-remote-subsurface-unstable-v1 + +// Layer shell +Q_LOGGING_CATEGORY(lcWlLayerShell, "waylib.layer.shell", QtWarningMsg) // wlr-layer-shell surface requests +Q_LOGGING_CATEGORY(lcWlLayerSurface, "waylib.layer.surface", QtWarningMsg) // Layer surface commit/geometry + +// XDG +Q_LOGGING_CATEGORY(lcWlXdgOutput, "waylib.xdg.output", QtWarningMsg) // XDG output manager +Q_LOGGING_CATEGORY(lcWlXdgDecoration, "waylib.xdg.decoration", QtWarningMsg) // XDG decoration mode +Q_LOGGING_CATEGORY(lcWlXdgDialog, "waylib.xdg.dialog", QtWarningMsg) // xdg-dialog-v1 modal state + +// Output +Q_LOGGING_CATEGORY(lcWlOutputLayer, "waylib.output.layer", QtWarningMsg) // QtQuick output layer +Q_LOGGING_CATEGORY(lcWlOutputHelper, "waylib.output.helper", QtWarningMsg) // Output helper state/commit + +// QtQuick extras +Q_LOGGING_CATEGORY(lcWlQmlCreator, "waylib.qml.creator", QtWarningMsg) // QML component creation +Q_LOGGING_CATEGORY(lcWlQuickCursor, "waylib.cursor.quick", QtWarningMsg) // QtQuick cursor texture provider + +// wlroots C library messages forwarded through WLog +Q_LOGGING_CATEGORY(lcWlroots, "wlroots", QtInfoMsg) + +// Platform & Rendering +Q_LOGGING_CATEGORY(lcWlPlatform, "waylib.platform", QtWarningMsg) // QPA integration +Q_LOGGING_CATEGORY(lcWlRenderHelper, "waylib.render.helper", QtWarningMsg) // Render target creation and buffer import +Q_LOGGING_CATEGORY(lcWlRenderBuffer, "waylib.render.buffer", QtWarningMsg) // Render buffer node DMA-BUF +Q_LOGGING_CATEGORY(lcWlBufferRenderer, "waylib.render.bufferrenderer", QtWarningMsg) // Buffer renderer texture provider + +// Forward wlroots C log messages into the Qt logging system so they honor +// QT_LOGGING_RULES and Qt's message pattern instead of raw stderr output. +WAYLIB_SERVER_BEGIN_NAMESPACE +void WLog::defaultLogCallback(wlr_log_importance verbosity, const char *fmt, va_list args) +{ + const QString message = QString::vasprintf(fmt, args); + switch (verbosity) { + case WLR_ERROR: + qCCritical(lcWlroots) << qPrintable(message); + break; + case WLR_INFO: + qCInfo(lcWlroots) << qPrintable(message); + break; + case WLR_DEBUG: + qCDebug(lcWlroots) << qPrintable(message); + break; + default: + break; + } +} + +WAYLIB_SERVER_END_NAMESPACE diff --git a/waylib/src/server/wayliblogging.h b/waylib/src/server/wayliblogging.h new file mode 100644 index 0000000000..31d553316c --- /dev/null +++ b/waylib/src/server/wayliblogging.h @@ -0,0 +1,77 @@ +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef WAYLIB_LOGGING_H +#define WAYLIB_LOGGING_H + +#include + +// Waylib Logging Categories +// Naming convention: lcWl + PascalCase module name +// String ID convention: waylib.[.] or waylib.protocols. or waylib.qtquick. or waylib.utils. + +// Kernel - Core +Q_DECLARE_LOGGING_CATEGORY(lcWlObject) +Q_DECLARE_LOGGING_CATEGORY(lcWlSocket) +Q_DECLARE_LOGGING_CATEGORY(lcWlSeat) +Q_DECLARE_LOGGING_CATEGORY(lcWlOutput) +Q_DECLARE_LOGGING_CATEGORY(lcWlOutputDrm) +Q_DECLARE_LOGGING_CATEGORY(lcWlOutputBuffer) +Q_DECLARE_LOGGING_CATEGORY(lcWlInput) +Q_DECLARE_LOGGING_CATEGORY(lcWlCursor) + +// Kernel - Input subcategories +Q_DECLARE_LOGGING_CATEGORY(lcWlPointer) +Q_DECLARE_LOGGING_CATEGORY(lcWlTouch) +Q_DECLARE_LOGGING_CATEGORY(lcWlGesture) +Q_DECLARE_LOGGING_CATEGORY(lcWlDrag) + +// QtQuick +Q_DECLARE_LOGGING_CATEGORY(lcWlTextureProvider) +Q_DECLARE_LOGGING_CATEGORY(lcWlSurface) +Q_DECLARE_LOGGING_CATEGORY(lcWlQtQuickTexture) +Q_DECLARE_LOGGING_CATEGORY(lcWlRenderer) +Q_DECLARE_LOGGING_CATEGORY(lcWlBufferItem) + +// Utils +Q_DECLARE_LOGGING_CATEGORY(lcWlImageCapture) +Q_DECLARE_LOGGING_CATEGORY(lcWlCursorImage) +Q_DECLARE_LOGGING_CATEGORY(lcWlBufferDumper) + +// Thread utilities +Q_DECLARE_LOGGING_CATEGORY(lcWlThreadUtils) + +// Protocols +Q_DECLARE_LOGGING_CATEGORY(lcWlForeignToplevel) +Q_DECLARE_LOGGING_CATEGORY(lcWlInputMethod) +Q_DECLARE_LOGGING_CATEGORY(lcWlExtForeignToplevel) +Q_DECLARE_LOGGING_CATEGORY(lcWlTextInput) +Q_DECLARE_LOGGING_CATEGORY(lcWlRemoteSubsurface) + +// Layer shell +Q_DECLARE_LOGGING_CATEGORY(lcWlLayerShell) +Q_DECLARE_LOGGING_CATEGORY(lcWlLayerSurface) + +// XDG +Q_DECLARE_LOGGING_CATEGORY(lcWlXdgOutput) +Q_DECLARE_LOGGING_CATEGORY(lcWlXdgDecoration) +Q_DECLARE_LOGGING_CATEGORY(lcWlXdgDialog) + +// Output +Q_DECLARE_LOGGING_CATEGORY(lcWlOutputLayer) +Q_DECLARE_LOGGING_CATEGORY(lcWlOutputHelper) + +// QtQuick extras +Q_DECLARE_LOGGING_CATEGORY(lcWlQmlCreator) +Q_DECLARE_LOGGING_CATEGORY(lcWlQuickCursor) + +// wlroots C library messages forwarded through WLog +Q_DECLARE_LOGGING_CATEGORY(lcWlroots) + +// Platform & Rendering +Q_DECLARE_LOGGING_CATEGORY(lcWlPlatform) +Q_DECLARE_LOGGING_CATEGORY(lcWlRenderHelper) +Q_DECLARE_LOGGING_CATEGORY(lcWlRenderBuffer) +Q_DECLARE_LOGGING_CATEGORY(lcWlBufferRenderer) + +#endif // WAYLIB_LOGGING_H diff --git a/waylib/src/server/wlroots_extra/wlr_ext_background_effect_v1.c b/waylib/src/server/wlroots_extra/wlr_ext_background_effect_v1.c new file mode 100644 index 0000000000..192f2204e1 --- /dev/null +++ b/waylib/src/server/wlroots_extra/wlr_ext_background_effect_v1.c @@ -0,0 +1,274 @@ +/* + * Vendored from wlroots MR 5304 + * (https://gitlab.freedesktop.org/wlroots/wlroots/-/merge_requests/5304), + * "types: add ext-background-effect-v1" — the wlr_surface_synced + + * wlr_addon based server-side implementation of the staging + * ext-background-effect-v1 protocol. Licensing is recorded in REUSE.toml. + */ +#include +#include +#include +#include "wlr_ext_background_effect_v1.h" +#include +#include +#include "ext-background-effect-v1-protocol.h" +// Exported by waylib-wlroots; the corresponding util header is private. +void wlr_global_destroy_safe(struct wl_global *global); + +#define BACKGROUND_EFFECT_VERSION 1 + +struct wlr_ext_background_effect_surface_v1 { + struct wl_resource *resource; + struct wlr_surface *surface; + struct wlr_addon addon; + struct wlr_surface_synced synced; + struct wlr_ext_background_effect_surface_v1_state pending, current; +}; + +static const struct ext_background_effect_surface_v1_interface surface_impl; +static const struct ext_background_effect_manager_v1_interface manager_impl; + +static struct wlr_ext_background_effect_surface_v1 *surface_from_resource( + struct wl_resource *resource) { + assert(wl_resource_instance_of(resource, + &ext_background_effect_surface_v1_interface, &surface_impl)); + + return wl_resource_get_user_data(resource); +} + +static void surface_destroy(struct wlr_ext_background_effect_surface_v1 *surface) { + if (surface == NULL) { + return; + } + + wlr_surface_synced_finish(&surface->synced); + wlr_addon_finish(&surface->addon); + wl_resource_set_user_data(surface->resource, NULL); + free(surface); +} + +static void surface_handle_resource_destroy(struct wl_resource *resource) { + struct wlr_ext_background_effect_surface_v1 *surface = surface_from_resource(resource); + surface_destroy(surface); +} + +static void surface_handle_destroy(struct wl_client *client, struct wl_resource *resource) { + (void)client; + wl_resource_destroy(resource); +} + +static void surface_handle_set_blur_region(struct wl_client *client, struct wl_resource *resource, + struct wl_resource *region_resource) { + (void)client; + struct wlr_ext_background_effect_surface_v1 *surface = surface_from_resource(resource); + + if (surface == NULL) { + wl_resource_post_error(resource, + EXT_BACKGROUND_EFFECT_SURFACE_V1_ERROR_SURFACE_DESTROYED, + "The wl_surface object has been destroyed"); + return; + } + + if (region_resource != NULL) { + const pixman_region32_t *region = wlr_region_from_resource(region_resource); + pixman_region32_copy(&surface->pending.blur_region, region); + } else { + pixman_region32_clear(&surface->pending.blur_region); + } +} + +static const struct ext_background_effect_surface_v1_interface surface_impl = { + .destroy = surface_handle_destroy, + .set_blur_region = surface_handle_set_blur_region, +}; + +static void surface_synced_init_state(void *_state) { + struct wlr_ext_background_effect_surface_v1_state *state = _state; + pixman_region32_init(&state->blur_region); +} + +static void surface_synced_finish_state(void *_state) { + struct wlr_ext_background_effect_surface_v1_state *state = _state; + pixman_region32_fini(&state->blur_region); +} + +static void surface_synced_move_state(void *_dst, void *_src) { + struct wlr_ext_background_effect_surface_v1_state *dst = _dst; + struct wlr_ext_background_effect_surface_v1_state *src = _src; + + pixman_region32_copy(&dst->blur_region, &src->blur_region); +} + +static const struct wlr_surface_synced_impl surface_synced_impl = { + .state_size = sizeof(struct wlr_ext_background_effect_surface_v1_state), + .init_state = surface_synced_init_state, + .finish_state = surface_synced_finish_state, + .move_state = surface_synced_move_state, +}; + +static void surface_addon_destroy(struct wlr_addon *addon) { + struct wlr_ext_background_effect_surface_v1 *surface = wl_container_of(addon, surface, addon); + + surface_destroy(surface); +} + +static const struct wlr_addon_interface surface_addon_impl = { + .name = "ext_background_effect_surface_v1", + .destroy = surface_addon_destroy, +}; + +static struct wlr_ext_background_effect_surface_v1 *surface_from_wlr_surface( + struct wlr_surface *wlr_surface) { + struct wlr_addon *addon = wlr_addon_find(&wlr_surface->addons, NULL, &surface_addon_impl); + if (addon == NULL) { + return NULL; + } + + struct wlr_ext_background_effect_surface_v1 *surface = + wl_container_of(addon, surface, addon); + + return surface; +} + +static void manager_handle_destroy(struct wl_client *client, struct wl_resource *resource) { + (void)client; + wl_resource_destroy(resource); +} + +static void manager_handle_get_background_effect(struct wl_client *client, + struct wl_resource *manager_resource, uint32_t id, struct wl_resource *surface_resource) { + struct wlr_surface *wlr_surface = wlr_surface_from_resource(surface_resource); + + if (surface_from_wlr_surface(wlr_surface) != NULL) { + wl_resource_post_error(manager_resource, + EXT_BACKGROUND_EFFECT_MANAGER_V1_ERROR_BACKGROUND_EFFECT_EXISTS, + "The wl_surface object already has a ext_background_effect_surface_v1 object"); + return; + } + + struct wlr_ext_background_effect_surface_v1 *surface = calloc(1, sizeof(*surface)); + if (surface == NULL) { + wl_resource_post_no_memory(manager_resource); + return; + } + + if (!wlr_surface_synced_init(&surface->synced, wlr_surface, &surface_synced_impl, + &surface->pending, &surface->current)) { + free(surface); + wl_resource_post_no_memory(manager_resource); + return; + } + + uint32_t version = wl_resource_get_version(manager_resource); + surface->resource = + wl_resource_create(client, &ext_background_effect_surface_v1_interface, version, id); + + if (surface->resource == NULL) { + wlr_surface_synced_finish(&surface->synced); + free(surface); + wl_resource_post_no_memory(manager_resource); + return; + } + + wl_resource_set_implementation(surface->resource, &surface_impl, surface, + surface_handle_resource_destroy); + + surface->surface = wlr_surface; + wlr_addon_init(&surface->addon, &wlr_surface->addons, NULL, &surface_addon_impl); +} + +static const struct ext_background_effect_manager_v1_interface manager_impl = { + .destroy = manager_handle_destroy, + .get_background_effect = manager_handle_get_background_effect, +}; + +static void manager_handle_resource_destroy(struct wl_resource *resource) { + wl_list_remove(wl_resource_get_link(resource)); +} + +static void manager_bind(struct wl_client *wl_client, void *data, uint32_t version, uint32_t id) { + struct wlr_ext_background_effect_manager_v1 *manager = data; + + struct wl_resource *resource = wl_resource_create(wl_client, + &ext_background_effect_manager_v1_interface, version, id); + if (resource == NULL) { + wl_client_post_no_memory(wl_client); + return; + } + wl_resource_set_implementation(resource, &manager_impl, manager, + manager_handle_resource_destroy); + wl_list_init(wl_resource_get_link(resource)); + if (manager == NULL) { + return; + } + + wl_list_insert(&manager->resources, wl_resource_get_link(resource)); + + ext_background_effect_manager_v1_send_capabilities(resource, manager->capabilities); +} + +static void ext_background_effect_manager_v1_destroy( + struct wlr_ext_background_effect_manager_v1 *manager, + bool destroy_global_safe) { + wl_signal_emit_mutable(&manager->events.destroy, NULL); + assert(wl_list_empty(&manager->events.destroy.listener_list)); + + if (destroy_global_safe) { + wlr_global_destroy_safe(manager->global); + } else { + wl_global_destroy(manager->global); + } + wl_list_remove(&manager->display_destroy.link); + free(manager); +} + +void wlr_ext_background_effect_manager_v1_destroy( + struct wlr_ext_background_effect_manager_v1 *manager, bool destroy_global_safe) { + ext_background_effect_manager_v1_destroy(manager, destroy_global_safe); +} + +static void handle_display_destroy(struct wl_listener *listener, void *data) { + (void)data; + struct wlr_ext_background_effect_manager_v1 *manager = + wl_container_of(listener, manager, display_destroy); + ext_background_effect_manager_v1_destroy(manager, false); +} + +struct wlr_ext_background_effect_manager_v1 *wlr_ext_background_effect_manager_v1_create( + struct wl_display *display, uint32_t version, uint32_t capabilities) { + assert(version <= BACKGROUND_EFFECT_VERSION); + + struct wlr_ext_background_effect_manager_v1 *manager = calloc(1, sizeof(*manager)); + if (manager == NULL) { + return NULL; + } + + manager->global = wl_global_create(display, &ext_background_effect_manager_v1_interface, version, + manager, manager_bind); + if (manager->global == NULL) { + free(manager); + return NULL; + } + + manager->capabilities = capabilities; + + wl_signal_init(&manager->events.destroy); + wl_list_init(&manager->resources); + + manager->display_destroy.notify = handle_display_destroy; + wl_display_add_destroy_listener(display, &manager->display_destroy); + + return manager; +} + +const struct wlr_ext_background_effect_surface_v1_state * +wlr_ext_background_effect_v1_get_surface_state(struct wlr_surface *wlr_surface) { + struct wlr_ext_background_effect_surface_v1 *surface = + surface_from_wlr_surface(wlr_surface); + + if (surface == NULL) { + return NULL; + } + + return &surface->current; +} diff --git a/waylib/src/server/wlroots_extra/wlr_ext_background_effect_v1.h b/waylib/src/server/wlroots_extra/wlr_ext_background_effect_v1.h new file mode 100644 index 0000000000..4f4a12f3aa --- /dev/null +++ b/waylib/src/server/wlroots_extra/wlr_ext_background_effect_v1.h @@ -0,0 +1,69 @@ +/* + * Vendored from wlroots MR 5304 + * (https://gitlab.freedesktop.org/wlroots/wlroots/-/merge_requests/5304), + * "types: add ext-background-effect-v1". Licensing is recorded in REUSE.toml. + */ + +/* + * This an unstable interface of wlroots. No guarantees are made regarding the + * future consistency of this API. + */ +#ifndef WLR_USE_UNSTABLE +#error "Add -DWLR_USE_UNSTABLE to enable unstable wlroots features" +#endif + +#ifndef WLR_TYPES_WLR_EXT_BACKGROUND_EFFECT_V1_H +#define WLR_TYPES_WLR_EXT_BACKGROUND_EFFECT_V1_H + +#include +#include +#include + +struct wlr_surface; + +struct wlr_ext_background_effect_surface_v1_state { + pixman_region32_t blur_region; +}; + +struct wlr_ext_background_effect_manager_v1 { + struct wl_global *global; + uint32_t capabilities; // bitmask of enum ext_background_effect_manager_v1_capability + + struct { + struct wl_signal destroy; + } events; + + void *data; + + struct { + struct wl_list resources; // wl_resource_get_link() + struct wl_listener display_destroy; + } WLR_PRIVATE; +}; + +struct wlr_ext_background_effect_manager_v1 *wlr_ext_background_effect_manager_v1_create( + struct wl_display *display, uint32_t version, uint32_t capabilities); + +/** + * Destroy the protocol manager and remove its globals. + * + * If destroy_global_safe is true, remove globals now and defer their + * destruction; otherwise destroy them immediately. + * + * All client objects using this manager must be destroyed before calling this + * function. The manager is also destroyed automatically when the display is + * destroyed. + */ +void wlr_ext_background_effect_manager_v1_destroy( + struct wlr_ext_background_effect_manager_v1 *manager, bool destroy_global_safe); + +/* + * Get the committed background effect state for a surface. + * + * Returns NULL if the client has not attached a background effect object to + * the surface. + */ +const struct wlr_ext_background_effect_surface_v1_state * +wlr_ext_background_effect_v1_get_surface_state(struct wlr_surface *surface); + +#endif diff --git a/waylib/tests/manual/live/helper.h b/waylib/tests/manual/live/helper.h index eba3e3c96b..420226e506 100644 --- a/waylib/tests/manual/live/helper.h +++ b/waylib/tests/manual/live/helper.h @@ -1,4 +1,4 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #pragma once @@ -19,14 +19,11 @@ class WSeat; class WBackend; WAYLIB_SERVER_END_NAMESPACE -QW_BEGIN_NAMESPACE -class qw_renderer; -class qw_allocator; -class qw_compositor; -QW_END_NAMESPACE +struct wlr_renderer; +struct wlr_allocator; +struct wlr_compositor; WAYLIB_SERVER_USE_NAMESPACE -QW_USE_NAMESPACE class Q_DECL_HIDDEN Helper : public QObject { @@ -51,9 +48,9 @@ class Q_DECL_HIDDEN Helper : public QObject WQmlCreator *m_xdgShellCreator = nullptr; WBackend *m_backend = nullptr; - qw_renderer *m_renderer = nullptr; - qw_allocator *m_allocator = nullptr; - qw_compositor *m_compositor = nullptr; + wlr_renderer *m_renderer = nullptr; + wlr_allocator *m_allocator = nullptr; + wlr_compositor *m_compositor = nullptr; WQuickOutputLayout *m_outputLayout = nullptr; WCursor *m_cursor = nullptr; QPointer m_seat; diff --git a/waylib/tests/manual/live/main.cpp b/waylib/tests/manual/live/main.cpp index e2f1cbf80f..dba3a8b736 100644 --- a/waylib/tests/manual/live/main.cpp +++ b/waylib/tests/manual/live/main.cpp @@ -1,6 +1,7 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. +// Copyright (C) 2024-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +#include #include "helper.h" #include @@ -18,15 +19,7 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include #include #include @@ -37,8 +30,6 @@ #include #include -QW_USE_NAMESPACE - Helper::Helper(QObject *parent) : QObject(parent) , m_server(new WServer(this)) @@ -71,7 +62,7 @@ void Helper::initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine) qCritical("Failed to create socket"); } - connect(m_backend, &WBackend::outputAdded, this, [this, window, qmlEngine] (WOutput *output) { + connect(m_backend, &WBackend::outputAdded, this, [this, qmlEngine] (WOutput *output) { auto initProperties = qmlEngine->newObject(); initProperties.setProperty("waylandOutput", qmlEngine->toScriptValue(output)); initProperties.setProperty("layout", qmlEngine->toScriptValue(m_outputLayout)); @@ -92,12 +83,12 @@ void Helper::initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine) m_seat->detachInputDevice(device); }); - m_allocator = qw_allocator::autocreate(*m_backend->handle(), *m_renderer); - m_renderer->init_wl_display(*m_server->handle()); + m_allocator = wlr_allocator_autocreate(m_backend->handle(), m_renderer); + wlr_renderer_init_wl_display(m_renderer, m_server->handle()); // free follow display - m_compositor = qw_compositor::create(*m_server->handle(), 6, *m_renderer); - qw_subcompositor::create(*m_server->handle()); + m_compositor = wlr_compositor_create(m_server->handle(), 6, m_renderer); + wlr_subcompositor_create(m_server->handle()); connect(window, &WOutputRenderWindow::outputViewportInitialized, this, [] (WOutputViewport *viewport) { // Trigger QWOutput::frame signal in order to ensure WOutputHelper::renderable @@ -106,24 +97,30 @@ void Helper::initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine) WOutput *output = viewport->output(); // Enable on default - auto qwoutput = output->handle(); // Don't care for WOutput::isEnabled, must do WOutput::commit here, // In order to ensure trigger QWOutput::frame signal, WOutputRenderWindow // needs this signal to render next frmae. Because QWOutput::frame signal - // maybe emit before WOutputRenderWindow::attach, if no commit here, + // maybe Q_EMIT before WOutputRenderWindow::attach, if no commit here, // WOutputRenderWindow will ignore this ouptut on render. - if (!qwoutput->property("_Enabled").toBool()) { - qwoutput->setProperty("_Enabled", true); - qw_output_state newState; - - if (!qwoutput->handle()->current_mode) { - auto mode = qwoutput->preferred_mode(); + // Keep the "already enabled" marker on the WOutput object itself: + // it is released with the output, so a recycled wlr_output address + // is never mistaken for an already-enabled output. + if (!output->property("_Enabled").toBool()) { + output->setProperty("_Enabled", true); + auto *wlrOutput = output->handle(); + wlr_output_state newState; + wlr_output_state_init(&newState); + + if (!wlrOutput->current_mode) { + auto mode = wlr_output_preferred_mode(wlrOutput); if (mode) - newState.set_mode(mode); + wlr_output_state_set_mode(&newState, mode); + } + wlr_output_state_set_enabled(&newState, true); + if (!wlr_output_commit_state(wlrOutput, &newState)) { + qCritical("commit failed on output %s", wlrOutput->name); } - newState.set_enabled(true); - bool ok = qwoutput->commit_state(newState); - Q_ASSERT(ok); + wlr_output_state_finish(&newState); } } }); @@ -148,7 +145,7 @@ void Helper::initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine) }); connect(xdgShell, &WXdgShell::popupSurfaceRemoved, m_xdgShellCreator, &WQmlCreator::removeByOwner); - m_backend->handle()->start(); + wlr_backend_start(m_backend->handle()); QProcess waylandClientDemo; waylandClientDemo.setProgram(PROJECT_BINARY_DIR"/examples/animationclient/animationclient"); @@ -161,7 +158,7 @@ void Helper::initProtocols(WOutputRenderWindow *window, QQmlEngine *qmlEngine) } int main(int argc, char *argv[]) { - qw_log::init(); + WLog::init(); WServer::initializeQPA(); QQuickStyle::setStyle("Material"); diff --git a/waylib/tests/manual/pinchhandler/eventitem.cpp b/waylib/tests/manual/pinchhandler/eventitem.cpp index 015018526b..c8df7889a9 100644 --- a/waylib/tests/manual/pinchhandler/eventitem.cpp +++ b/waylib/tests/manual/pinchhandler/eventitem.cpp @@ -19,12 +19,12 @@ bool EventItem::event(QEvent *event) { case MouseButtonRelease: Q_FALLTHROUGH(); case MouseMove: - Q_FALLTHROUGH(); - case HoverMove: if (static_cast(event)->source() != Qt::MouseEventNotSynthesized) return true; // The non-native events don't send to WSeat Q_FALLTHROUGH(); + case HoverMove: + Q_FALLTHROUGH(); case HoverEnter: Q_FALLTHROUGH(); case HoverLeave: diff --git a/waylib/tests/manual/subsurface/Main.qml b/waylib/tests/manual/subsurface/Main.qml index b36d60cbdf..31931b6c0b 100644 --- a/waylib/tests/manual/subsurface/Main.qml +++ b/waylib/tests/manual/subsurface/Main.qml @@ -1,4 +1,4 @@ -// Copyright (C) 2023 JiDe Zhang . +// Copyright (C) 2023-2026 UnionTech Software Technology Co., Ltd. // SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only import QtQuick @@ -52,6 +52,7 @@ Window { } CustomWindow { + id: window3 parent: root title: "Subsurface 3" @@ -61,21 +62,30 @@ Window { height: 200 color: "yellow" + property var windows: [] + Column { anchors.centerIn: parent - property CustomWindow winObj + spacing: 10 Button { text: "Add" onClicked: { - parent.winObj = window4.createObject() + var obj = window4.createObject() + obj.x = 300 + window3.windows.length * 20 + obj.y = -50 + window3.windows.length * 20 + window3.windows.push(obj) } } Button { text: "Destroy" onClicked: { - console.log('destroying',parent.winObj,parent.winObj.close()) + if (window3.windows.length > 0) { + var obj = window3.windows.pop() + obj.destroyWindow() + } } } + } } @@ -94,4 +104,5 @@ Window { color: "green" } } + } diff --git a/waylib/tests/manual/subsurface/main.cpp b/waylib/tests/manual/subsurface/main.cpp index 8c9e813875..ec1ce36871 100644 --- a/waylib/tests/manual/subsurface/main.cpp +++ b/waylib/tests/manual/subsurface/main.cpp @@ -19,7 +19,7 @@ void CustomWindow::setParent(QWindow *newParent) QQuickWindow::setParent(newParent); show(); - emit parentChanged(); + Q_EMIT parentChanged(); } int main(int argc, char *argv[]) diff --git a/waylib/tests/manual/subsurface/window.h b/waylib/tests/manual/subsurface/window.h index 2c014bdae9..bf15aca3a9 100644 --- a/waylib/tests/manual/subsurface/window.h +++ b/waylib/tests/manual/subsurface/window.h @@ -18,13 +18,14 @@ class Q_DECL_HIDDEN CustomWindow : public QQuickWindow QWindow *parent() const; void setParent(QWindow *newParent); - Q_INVOKABLE inline bool destroy() { - // can't close with parent, setParent(nullptr) destroys subsurf and make new xdgsurface + + Q_INVOKABLE void destroyWindow() + { + QQuickWindow::setParent(nullptr); QQuickWindow::destroy(); - return true; } -signals: +Q_SIGNALS: void parentChanged(); private: diff --git a/waylib/tests/unit_tests/CMakeLists.txt b/waylib/tests/unit_tests/CMakeLists.txt index 9ae152b7c3..c76abe2737 100644 --- a/waylib/tests/unit_tests/CMakeLists.txt +++ b/waylib/tests/unit_tests/CMakeLists.txt @@ -1,3 +1,11 @@ set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_AUTOMOC ON) -add_subdirectory(test_wwrappointer) +add_subdirectory(test_qsgrenderer_accessor) +add_subdirectory(test_native_handles) +add_subdirectory(test_native_lifecycle) +add_subdirectory(test_output_frame) +add_subdirectory(test_wpointer) +add_subdirectory(test_wlog) +add_subdirectory(test_containerof) +add_subdirectory(test_wscoplistener) +add_subdirectory(test_wobject_listeners) diff --git a/waylib/tests/unit_tests/test_containerof/CMakeLists.txt b/waylib/tests/unit_tests/test_containerof/CMakeLists.txt new file mode 100644 index 0000000000..92c9ba4ea5 --- /dev/null +++ b/waylib/tests/unit_tests/test_containerof/CMakeLists.txt @@ -0,0 +1,32 @@ +find_package(Qt6 REQUIRED COMPONENTS Core Test) + +add_executable(test_containerof main.cpp) + +target_link_libraries(test_containerof + PRIVATE + Qt::Core + Qt::Test +) + +target_include_directories(test_containerof PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/../../../src/server/utils" +) + +add_test(NAME test_containerof COMMAND test_containerof) + +# Negative compile check: container_of() must reject non-standard-layout +# container types via static_assert. negative_compile.cpp instantiates it +# with a std::string member, so a successful build means the guard regressed. +set(_containerof_inc "${CMAKE_CURRENT_SOURCE_DIR}/../../../src/server/utils") +try_compile(_containerof_negative_compiled + "${CMAKE_CURRENT_BINARY_DIR}/containerof_negative" + SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/negative_compile.cpp" + CMAKE_FLAGS + "-DCMAKE_CXX_STANDARD=20" + "-DCMAKE_CXX_STANDARD_REQUIRED=ON" + "-DCMAKE_CXX_FLAGS=-I${_containerof_inc}") +if(_containerof_negative_compiled) + message(FATAL_ERROR + "W_CONTAINER_OF must reject non-standard-layout types, but " + "negative_compile.cpp compiled successfully") +endif() diff --git a/waylib/tests/unit_tests/test_containerof/main.cpp b/waylib/tests/unit_tests/test_containerof/main.cpp new file mode 100644 index 0000000000..0de0fe82fc --- /dev/null +++ b/waylib/tests/unit_tests/test_containerof/main.cpp @@ -0,0 +1,86 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// Runtime tests for the offset-based container_of helper. The compile-time +// guarantee (non-standard-layout T is rejected by static_assert) is verified +// by a negative-compile check wired in CMakeLists.txt (negative_compile.cpp +// must fail to build). + +#include + +#include + +// wlroots-style struct: a member that is not the first field. +struct WlrStyleStruct { + int id; + int destroy; + double value; +}; + +// Multiple members of the same type: offsets must be per-member. +struct TwoListeners { + char pad[3]; + int a; + int marker; + int b; +}; + +class TestContainerOf : public QObject +{ + Q_OBJECT +private Q_SLOTS: + void recoversContainingStruct(); + void memberIsNotFirstField(); + void multipleInstances(); + void twoMembersSameType(); + void rawOffsetMatchesMacro(); +}; + +void TestContainerOf::recoversContainingStruct() +{ + WlrStyleStruct obj { 7, {}, 3.5 }; + auto *self = W_CONTAINER_OF(&obj.destroy, WlrStyleStruct, destroy); + QCOMPARE(self, &obj); + QCOMPARE(self->id, 7); + QCOMPARE(self->value, 3.5); +} + +void TestContainerOf::memberIsNotFirstField() +{ + WlrStyleStruct obj { 1, {}, 2.0 }; + // The listener sits after `id`, so a plain cast of the member pointer + // would be wrong; container_of must subtract the real offset. + QVERIFY(reinterpret_cast(&obj.destroy) != &obj); + QCOMPARE(W_CONTAINER_OF(&obj.destroy, WlrStyleStruct, destroy), &obj); +} + +void TestContainerOf::multipleInstances() +{ + WlrStyleStruct arr[4] {}; + for (int i = 0; i < 4; ++i) + arr[i].id = i; + + for (int i = 0; i < 4; ++i) + QCOMPARE(W_CONTAINER_OF(&arr[i].destroy, WlrStyleStruct, destroy), &arr[i]); +} + +void TestContainerOf::twoMembersSameType() +{ + TwoListeners obj {}; + QCOMPARE(W_CONTAINER_OF(&obj.a, TwoListeners, a), &obj); + QCOMPARE(W_CONTAINER_OF(&obj.b, TwoListeners, b), &obj); + QVERIFY(W_CONTAINER_OF(&obj.a, TwoListeners, b) != &obj); // wrong member must differ +} + +void TestContainerOf::rawOffsetMatchesMacro() +{ + WlrStyleStruct obj {}; + auto *viaMacro = W_CONTAINER_OF(&obj.destroy, WlrStyleStruct, destroy); + auto *viaRaw = container_of(&obj.destroy, offsetof(WlrStyleStruct, destroy)); + QCOMPARE(viaRaw, viaMacro); + QCOMPARE(viaRaw, &obj); +} + +QTEST_GUILESS_MAIN(TestContainerOf) + +#include "main.moc" diff --git a/waylib/tests/unit_tests/test_containerof/negative_compile.cpp b/waylib/tests/unit_tests/test_containerof/negative_compile.cpp new file mode 100644 index 0000000000..38f3dcf5d9 --- /dev/null +++ b/waylib/tests/unit_tests/test_containerof/negative_compile.cpp @@ -0,0 +1,23 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// Negative compile check: this file MUST NOT build. container_of() exists to +// reject non-standard-layout container types (a member pointer or raw offset +// into such an object is not guaranteed to be usable), enforced by +// static_assert(std::is_standard_layout_v). CMakeLists.txt tries to +// compile this translation unit and fails the configuration if it succeeds. + +#include + +struct NonStandardLayout { + virtual ~NonStandardLayout() = default; // virtual: not standard-layout + int member; +}; + +int main() +{ + NonStandardLayout obj; + auto *p = W_CONTAINER_OF(&obj.member, NonStandardLayout, member); + (void)p; + return 0; +} diff --git a/waylib/tests/unit_tests/test_native_handles/CMakeLists.txt b/waylib/tests/unit_tests/test_native_handles/CMakeLists.txt new file mode 100644 index 0000000000..5d1968354b --- /dev/null +++ b/waylib/tests/unit_tests/test_native_handles/CMakeLists.txt @@ -0,0 +1,18 @@ +find_package(Qt6 REQUIRED COMPONENTS Gui Qml Quick Test) + +add_executable(test_native_handles main.cpp) + +target_link_libraries(test_native_handles + PRIVATE + Waylib::WaylibServer + Qt::Gui + Qt::Qml + Qt::Quick + Qt::Test +) + +add_test(NAME test_native_handles COMMAND test_native_handles) + +set_property(TEST test_native_handles PROPERTY + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" +) diff --git a/waylib/tests/unit_tests/test_native_handles/main.cpp b/waylib/tests/unit_tests/test_native_handles/main.cpp new file mode 100644 index 0000000000..18299b61a3 --- /dev/null +++ b/waylib/tests/unit_tests/test_native_handles/main.cpp @@ -0,0 +1,817 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifndef DISABLE_XWAYLAND +#include +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +// wlroots 0.19 exports these functions but only declares them in an +// uninstalled internal header. +extern "C" { +void wlr_input_device_init(struct wlr_input_device *device, + enum wlr_input_device_type type, const char *name); +void wlr_input_device_finish(struct wlr_input_device *device); +} + +#include +#include + +struct wl_display; +struct wlr_backend; +struct wlr_cursor; +struct wlr_cursor_shape_manager_v1; +struct wlr_input_device; +struct wlr_output; +struct wlr_output_manager_v1; +struct wlr_output_layout; +struct wlr_seat; +struct wlr_session; +struct wlr_layer_shell_v1; +struct wlr_layer_surface_v1; +struct wlr_xdg_decoration_manager_v1; +struct wlr_xdg_popup; +struct wlr_xdg_shell; +struct wlr_xdg_toplevel; +struct wlr_xdg_wm_dialog_v1; +#ifndef DISABLE_XWAYLAND +struct wlr_xwayland; +struct wlr_xwayland_surface; +#endif +struct wlr_session_lock_manager_v1; +struct wlr_session_lock_surface_v1; +struct wlr_session_lock_v1; +struct wlr_input_method_manager_v2; +struct wlr_input_method_v2; +struct wlr_input_popup_surface_v2; +struct wlr_text_input_manager_v3; +struct wlr_text_input_v3; +struct wlr_virtual_keyboard_manager_v1; +struct wlr_ext_foreign_toplevel_list_v1; +struct wlr_foreign_toplevel_manager_v1; + +WAYLIB_SERVER_USE_NAMESPACE + +static_assert(std::is_same_v().handle()), wl_display *>); +static_assert(std::is_same_v().handle()), wlr_backend *>); +static_assert(std::is_same_v().session()), wlr_session *>); +static_assert(std::is_same_v().handle()), wlr_input_device *>); +static_assert(std::is_constructible_v); +static_assert(std::is_same_v().handle()), wlr_output *>); +static_assert(std::is_same_v().handle()), + wlr_output_manager_v1 *>); +static_assert(std::is_same_v().handle()), wlr_output_layout *>); +static_assert(std::is_same_v().handle()), wlr_cursor *>); +static_assert(std::is_same_v().handle()), + wlr_cursor_shape_manager_v1 *>); +static_assert(std::is_same_v().handle()), wlr_seat *>); +static_assert(std::is_same_v().handle()), wlr_surface *>); +static_assert(std::is_same_v().handle()), wlr_xdg_shell *>); +static_assert(std::is_same_v().handle()), wlr_xdg_toplevel *>); +static_assert(std::is_same_v().handle()), wlr_xdg_popup *>); +static_assert(std::is_same_v().handle()), wlr_layer_shell_v1 *>); +static_assert(std::is_same_v().handle()), wlr_layer_surface_v1 *>); +static_assert(std::is_same_v().handle()), + wlr_xdg_decoration_manager_v1 *>); +static_assert(std::is_same_v().handle()), + wlr_xdg_wm_dialog_v1 *>); +static_assert(std::is_same_v().handle()), + wlr_session_lock_manager_v1 *>); +static_assert(std::is_same_v().handle()), + wlr_session_lock_v1 *>); +static_assert(std::is_same_v().handle()), + wlr_session_lock_surface_v1 *>); +#ifndef DISABLE_XWAYLAND +static_assert(std::is_same_v().handle()), wlr_xwayland *>); +static_assert(std::is_same_v().handle()), + wlr_xwayland_surface *>); +#endif +static_assert(std::is_same_v().handle()), + wlr_input_method_manager_v2 *>); +static_assert(std::is_same_v().handle()), + wlr_input_method_v2 *>); +static_assert(std::is_same_v().handle()), + wlr_input_popup_surface_v2 *>); +static_assert(std::is_same_v().handle()), + wlr_text_input_manager_v3 *>); +static_assert(std::is_same_v().handle()), + wlr_text_input_v3 *>); +static_assert(std::is_same_v().handle()), + wlr_virtual_keyboard_manager_v1 *>); +static_assert(std::is_same_v().handle()), + wlr_ext_foreign_toplevel_list_v1 *>); +static_assert(std::is_same_v().handle()), + wlr_foreign_toplevel_manager_v1 *>); + +static void destroyTestBuffer(wlr_buffer *buffer) +{ + wlr_buffer_finish(buffer); +} + +static const wlr_buffer_impl testBufferImpl = { + .destroy = destroyTestBuffer, + .get_dmabuf = nullptr, + .get_shm = nullptr, + .begin_data_ptr_access = nullptr, + .end_data_ptr_access = nullptr, +}; + +template +class ExposedGlobalManager : public Interface +{ +public: + using Interface::Interface; + using Interface::global; +}; + +class NativeHandlesTest : public QObject +{ + Q_OBJECT + +#ifndef DISABLE_XWAYLAND + static void initXWaylandSurface(wlr_xwayland_surface *surface) + { + // Mirror wlroots' xwayland_surface_create(): the input/clip shape + // regions must be initialised before any listener reads them + // (WXWaylandSurface::init -> updateClipShape). + pixman_region32_init(&surface->input_shape); + pixman_region32_init(&surface->clip_shape); + wl_list_init(&surface->children); + for (auto *signal : { + &surface->events.destroy, + &surface->events.associate, + &surface->events.dissociate, + &surface->events.set_parent, + &surface->events.request_activate, + &surface->events.request_configure, + &surface->events.request_fullscreen, + &surface->events.request_maximize, + &surface->events.request_minimize, + &surface->events.request_move, + &surface->events.request_resize, + &surface->events.request_above, + &surface->events.request_below, + &surface->events.set_override_redirect, + &surface->events.set_geometry, + &surface->events.set_input_shape, + &surface->events.set_clip_shape, + &surface->events.set_size_hints, + &surface->events.set_window_type, + &surface->events.set_decorations, + &surface->events.set_title, + &surface->events.set_class, + }) { + wl_signal_init(signal); + } + } +#endif + + struct ManagerDestroyProbe { + wl_listener listener {}; + bool destroyed = false; + + explicit ManagerDestroyProbe(wl_signal *signal) + { + listener.notify = notify; + wl_signal_add(signal, &listener); + } + + ~ManagerDestroyProbe() + { + if (!destroyed) + wl_list_remove(&listener.link); + } + + static void notify(wl_listener *listener, void *) + { + ManagerDestroyProbe *probe = wl_container_of(listener, probe, listener); + probe->destroyed = true; + wl_list_remove(&listener->link); + } + }; + + template + void checkManagerRemoval(WServer &server, Interface *interface, WSocket *socket) + { + interface->setOwnsSocket(socket); + server.start(); + auto *native = interface->template nativeInterface(); + QVERIFY(native); + if constexpr (std::is_same_v) { + QVERIFY(wlr_ext_workspace_group_handle_v1_create(native, 0)); + QVERIFY(wlr_ext_workspace_handle_v1_create(native, "test-workspace", 0)); + } + ManagerDestroyProbe probe(&native->events.destroy); + QVERIFY(server.detach(interface)); + QVERIFY(!interface->isValid()); + QCOMPARE(probe.destroyed, socket != nullptr); + if constexpr (std::is_same_v) { + if (!socket) { + QCOMPARE(wl_list_length(&native->groups), 1); + QCOMPARE(wl_list_length(&native->workspaces), 1); + } + } + + server.attach(interface); + QVERIFY(interface->isValid()); + server.stop(); + QVERIFY(probe.destroyed); + QVERIFY(!interface->isValid()); + server.start(); + QVERIFY(interface->isValid()); + server.stop(); + QVERIFY(!interface->isValid()); + } + +private Q_SLOTS: + void socketOwnedManagersAreDestroyedOnDetach_data() + { + QTest::addColumn("protocol"); + QTest::addColumn("socketOwned"); + const char *names[] = { + "WCursorShapeManagerV1", + "WExtForeignToplevelListV1", + "WForeignToplevel", + "WLayerShell", + "WOutputManagerV1", + "WPointerConstraintsV1", + "WPointerGesturesV1", + "WRelativePointerManagerV1", + "WSessionLockManager", + "WXdgDecorationManager", + "WXdgDialogManagerV1", + "WXdgShell", + "WXdgToplevelTagManagerV1", + "WInputMethodManagerV2", + "WTextInputManagerV3", + "WVirtualKeyboardManagerV1", + "WExtWorkspaceManagerV1", + }; + for (int i = 0; i < int(std::size(names)); ++i) { + QTest::newRow(qPrintable(QString::fromLatin1(names[i]) + "-socket")) << i << true; + QTest::newRow(qPrintable(QString::fromLatin1(names[i]) + "-display")) << i << false; + } + } + + void socketOwnedManagersAreDestroyedOnDetach() + { + QFETCH(int, protocol); + QFETCH(bool, socketOwned); + WSocket socket(false); + WServer server; + switch (protocol) { + case 0: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + case 1: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + case 2: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + case 3: + checkManagerRemoval( + server, server.attach(server.attach(6)), socketOwned ? &socket : nullptr); + break; + case 4: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + case 5: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + case 6: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + case 7: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + case 8: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + case 9: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + case 10: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + case 11: + checkManagerRemoval( + server, server.attach(6), socketOwned ? &socket : nullptr); + break; + case 12: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + case 13: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + case 14: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + case 15: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + case 16: + checkManagerRemoval( + server, server.attach(), socketOwned ? &socket : nullptr); + break; + default: + QFAIL("Unknown protocol"); + } + } + + void localXdgOutputManagerLifetime_data() + { + QTest::addColumn("socketOwned"); + QTest::newRow("socket") << true; + QTest::newRow("display") << false; + } + + void localXdgOutputManagerLifetime() + { + QFETCH(bool, socketOwned); + WSocket socket(false); + WServer server; + WOutputLayout layout(&server); + auto *manager = server.attach>(&layout); + manager->setOwnsSocket(socketOwned ? &socket : nullptr); + server.start(); + auto *global = manager->global(); + QVERIFY(global); + auto *native = wl_global_get_user_data(global); + QVERIFY(native); + const int listeners = wl_list_length(&layout.handle()->events.add.listener_list); + + QVERIFY(server.detach(manager)); + QVERIFY(!manager->isValid()); + QVERIFY(!manager->global()); + // Socket-owned globals are freed synchronously on detach. + if (!socketOwned) + QCOMPARE(wl_global_get_user_data(global), native); + QCOMPARE(wl_list_length(&layout.handle()->events.add.listener_list), + listeners - int(socketOwned)); + + server.attach(manager); + QVERIFY(manager->isValid()); + server.stop(); + QVERIFY(!manager->isValid()); + } + + void localSecurityContextManagerLifetime_data() + { + QTest::addColumn("socketOwned"); + QTest::newRow("socket") << true; + QTest::newRow("display") << false; + } + + void localSecurityContextManagerLifetime() + { + QFETCH(bool, socketOwned); + WSocket socket(false); + WServer server; + auto *manager = server.attach>(); + manager->setOwnsSocket(socketOwned ? &socket : nullptr); + server.start(); + auto *global = manager->global(); + QVERIFY(global); + auto *native = wl_global_get_user_data(global); + QVERIFY(native); + auto *securityContext = static_cast< + WAYLIB_SERVER_NAMESPACE::wlr_security_context_manager_v1 *>(native); + ManagerDestroyProbe probe(&securityContext->events.destroy); + + QVERIFY(server.detach(manager)); + QVERIFY(!manager->isValid()); + QVERIFY(!manager->global()); + QCOMPARE(probe.destroyed, socketOwned); + // Socket-owned globals are freed synchronously on detach. + if (!socketOwned) + QCOMPARE(wl_global_get_user_data(global), native); + + server.attach(manager); + QVERIFY(manager->isValid()); + server.stop(); + QVERIFY(probe.destroyed); + QVERIFY(!manager->isValid()); + server.start(); + QVERIFY(manager->isValid()); + server.stop(); + QVERIFY(!manager->isValid()); + } + + void serverExposesNativeDisplay() + { + WServer server; + QVERIFY(server.handle()); + } + + void bufferCountTracksNativeLifetime() + { + const auto initialCount = waylib_buffer_get_count(); + wlr_buffer buffer {}; + wlr_buffer_init(&buffer, &testBufferImpl, 1, 1); + QCOMPARE(waylib_buffer_get_count(), initialCount + 1); + + wlr_buffer_drop(&buffer); + + QCOMPARE(waylib_buffer_get_count(), initialCount); + } + + void backendOwnsNativeHandle() + { + qputenv("WLR_BACKENDS", "headless"); + { + WServer server; + auto *backend = server.attach(); + server.start(); + QVERIFY(backend->handle()); + server.stop(); + } + qunsetenv("WLR_BACKENDS"); + } + + void shellManagersExposeNativeHandles() + { + WServer server; + auto *xdgShell = server.attach(6); + auto *layerShell = server.attach(xdgShell); + auto *decorationManager = server.attach(); + auto *dialogManager = server.attach(); + auto *sessionLockManager = server.attach(); + auto *cursorShapeManager = server.attach(); + auto *foreignToplevelManager = server.attach(); + auto *extForeignToplevelList = server.attach(); + + server.start(); + QVERIFY(xdgShell->handle()); + QVERIFY(layerShell->handle()); + QVERIFY(decorationManager->handle()); + QVERIFY(dialogManager->handle()); + QVERIFY(sessionLockManager->handle()); + QVERIFY(cursorShapeManager->handle()); + QVERIFY(foreignToplevelManager->handle()); + QVERIFY(extForeignToplevelList->handle()); + server.stop(); + } + + void inputProtocolManagersExposeNativeHandles() + { + WServer server; + auto *inputMethodManager = server.attach(); + auto *textInputManager = server.attach(); + auto *virtualKeyboardManager = server.attach(); + auto *outputManager = server.attach(); + + server.start(); + QVERIFY(inputMethodManager->handle()); + QVERIFY(textInputManager->handle()); + QVERIFY(virtualKeyboardManager->handle()); + QVERIFY(outputManager->handle()); + server.stop(); + } + + void inputProtocolObjectsTrackNativeLifetime() + { + wlr_input_method_v2 nativeInputMethod {}; + wl_signal_init(&nativeInputMethod.events.commit); + wl_signal_init(&nativeInputMethod.events.grab_keyboard); + wl_signal_init(&nativeInputMethod.events.new_popup_surface); + wl_signal_init(&nativeInputMethod.events.destroy); + QPointer inputMethod = new WInputMethodV2(&nativeInputMethod); + // Owner rule: the test created it, so it releases it on destroy. + // Owner rule: the test acts as the creator and monitors the + // native destroy signal to release the wrapper. + bool inputMethodDestroyed = false; + QObject::connect(inputMethod, &QObject::destroyed, this, [&inputMethodDestroyed] { inputMethodDestroyed = true; }); + WScopedListener inputMethodDestroyListener; + inputMethodDestroyListener.init(&nativeInputMethod.events.destroy, this, + [inputMethod, &inputMethodDestroyListener](void *) { inputMethodDestroyListener.disconnect(); delete inputMethod; }); + + wl_signal_emit_mutable(&nativeInputMethod.events.destroy, &nativeInputMethod); + + QVERIFY(inputMethodDestroyed); + QVERIFY(inputMethod.isNull()); + + wlr_input_popup_surface_v2 nativePopup {}; + wl_signal_init(&nativePopup.events.destroy); + QPointer popup = new WInputPopupSurface(&nativePopup, nullptr); + // Owner rule: the test created it, so it releases it on destroy. + // Owner rule: the test acts as the creator and monitors the + // native destroy signal to release the wrapper. + bool popupDestroyed = false; + QObject::connect(popup, &QObject::destroyed, this, [&popupDestroyed] { popupDestroyed = true; }); + WScopedListener popupDestroyListener; + popupDestroyListener.init(&nativePopup.events.destroy, this, + [popup, &popupDestroyListener](void *) { popupDestroyListener.disconnect(); delete popup; }); + + wl_signal_emit_mutable(&nativePopup.events.destroy, &nativePopup); + + QVERIFY(popupDestroyed); + QVERIFY(popup.isNull()); + + wlr_text_input_v3 nativeTextInput {}; + wl_signal_init(&nativeTextInput.events.enable); + wl_signal_init(&nativeTextInput.events.disable); + wl_signal_init(&nativeTextInput.events.commit); + wl_signal_init(&nativeTextInput.events.destroy); + QPointer textInput = new WTextInputV3(&nativeTextInput, nullptr); + QSignalSpy textInputDestroyed(textInput, &WTextInput::entityAboutToDestroy); + // Owner rule: the test acts as the creator and monitors the + // native destroy signal to release the wrapper, mirroring + // WTextInputManagerV3 (WTextInputV3 itself does not observe + // the native destroy signal). + WScopedListener textInputDestroyListener; + textInputDestroyListener.init(&nativeTextInput.events.destroy, this, + [textInput, &textInputDestroyListener](void *) { + textInputDestroyListener.disconnect(); + Q_EMIT textInput->entityAboutToDestroy(); + delete textInput; + }); + + wl_signal_emit_mutable(&nativeTextInput.events.destroy, &nativeTextInput); + + QCOMPARE(textInputDestroyed.count(), 1); + QVERIFY(textInput.isNull()); + } + + void inputProtocolObserversDetachBeforeNativeDestruction() + { + wlr_input_method_v2 nativeInputMethod {}; + wl_signal_init(&nativeInputMethod.events.commit); + wl_signal_init(&nativeInputMethod.events.grab_keyboard); + wl_signal_init(&nativeInputMethod.events.new_popup_surface); + wl_signal_init(&nativeInputMethod.events.destroy); + { + auto *im = new WInputMethodV2(&nativeInputMethod); + delete im; + } + wl_signal_emit_mutable(&nativeInputMethod.events.destroy, &nativeInputMethod); + + wlr_input_popup_surface_v2 nativePopup {}; + wl_signal_init(&nativePopup.events.destroy); + { + auto *popup = new WInputPopupSurface(&nativePopup, nullptr); + delete popup; + } + wl_signal_emit_mutable(&nativePopup.events.destroy, &nativePopup); + + wlr_text_input_v3 nativeTextInput {}; + wl_signal_init(&nativeTextInput.events.enable); + wl_signal_init(&nativeTextInput.events.disable); + wl_signal_init(&nativeTextInput.events.commit); + wl_signal_init(&nativeTextInput.events.destroy); + auto *textInput = new WTextInputV3(&nativeTextInput, nullptr); + delete textInput; + wl_signal_emit_mutable(&nativeTextInput.events.destroy, &nativeTextInput); + } + +#ifndef DISABLE_XWAYLAND + void xwaylandSurfaceTracksNativeLifetime() + { + wlr_xwayland_surface nativeSurface {}; + initXWaylandSurface(&nativeSurface); + QPointer surface = new WXWaylandSurface(&nativeSurface, nullptr); + // Owner rule: the test acts as the creator and monitors the native + // destroy signal to release the wrapper. + bool surfaceDestroyed = false; + QObject::connect(surface, &QObject::destroyed, this, [&surfaceDestroyed] { surfaceDestroyed = true; }); + WScopedListener surfaceDestroyListener; + surfaceDestroyListener.init(&nativeSurface.events.destroy, this, + [surface, &surfaceDestroyListener](void *) { surfaceDestroyListener.disconnect(); delete surface; }); + QCOMPARE(WXWaylandSurface::fromHandle(&nativeSurface), surface.data()); + + wl_signal_emit_mutable(&nativeSurface.events.destroy, &nativeSurface); + + QVERIFY(surfaceDestroyed); + QVERIFY(!WXWaylandSurface::fromHandle(&nativeSurface)); + QVERIFY(surface.isNull()); + } + + void xwaylandSurfaceObserverDetachesBeforeNativeDestruction() + { + wlr_xwayland_surface nativeSurface {}; + initXWaylandSurface(&nativeSurface); + { + auto *surface = new WXWaylandSurface(&nativeSurface, nullptr); + delete surface; + } + QVERIFY(!WXWaylandSurface::fromHandle(&nativeSurface)); + QVERIFY(wl_list_empty(&nativeSurface.events.set_input_shape.listener_list)); + QVERIFY(wl_list_empty(&nativeSurface.events.set_clip_shape.listener_list)); + wl_signal_emit_mutable(&nativeSurface.events.set_input_shape, nullptr); + wl_signal_emit_mutable(&nativeSurface.events.set_clip_shape, nullptr); + wl_signal_emit_mutable(&nativeSurface.events.destroy, &nativeSurface); + } + + void xwaylandSurfaceTracksStackingState() + { + wlr_xwayland_surface nativeSurface {}; + initXWaylandSurface(&nativeSurface); + WXWaylandSurface surface(&nativeSurface, nullptr); + QSignalSpy aboveChanged(&surface, &WXWaylandSurface::aboveChanged); + QSignalSpy belowChanged(&surface, &WXWaylandSurface::belowChanged); + + QVERIFY(!surface.isAbove()); + QVERIFY(!surface.isBelow()); + nativeSurface.above = true; + wl_signal_emit_mutable(&nativeSurface.events.request_above, nullptr); + + QVERIFY(surface.isAbove()); + QCOMPARE(aboveChanged.count(), 1); + QVERIFY(aboveChanged.takeFirst().at(0).toBool()); + + nativeSurface.below = true; + wl_signal_emit_mutable(&nativeSurface.events.request_below, nullptr); + + QVERIFY(surface.isBelow()); + QCOMPARE(belowChanged.count(), 1); + QVERIFY(belowChanged.takeFirst().at(0).toBool()); + } +#endif + + void inputDeviceTracksNativeLifetime() + { + wlr_input_device nativeDevice; + wlr_input_device_init(&nativeDevice, WLR_INPUT_DEVICE_POINTER, "test-pointer"); + + QPointer device = new WInputDevice(&nativeDevice); + // Owner rule: the test acts as the creator and monitors the native + // destroy signal to release the wrapper. + bool deviceDestroyed = false; + QObject::connect(device, &QObject::destroyed, this, [&deviceDestroyed] { deviceDestroyed = true; }); + WScopedListener deviceDestroyListener; + deviceDestroyListener.init(&nativeDevice.events.destroy, this, + [device, &deviceDestroyListener](void *) { deviceDestroyListener.disconnect(); delete device; }); + QCOMPARE(WInputDevice::fromHandle(&nativeDevice), device.data()); + + wlr_input_device_finish(&nativeDevice); + + QVERIFY(deviceDestroyed); + QVERIFY(!WInputDevice::fromHandle(&nativeDevice)); + QVERIFY(device.isNull()); + } + + void backendRemovesDestroyedInputDevice() + { + qputenv("WLR_BACKENDS", "headless"); + WServer server; + auto *backend = server.attach(); + server.start(); + + wlr_input_device nativeDevice; + wlr_input_device_init(&nativeDevice, WLR_INPUT_DEVICE_POINTER, "backend-test-pointer"); + QSignalSpy added(backend, &WBackend::inputAdded); + QSignalSpy removed(backend, &WBackend::inputRemoved); + wl_signal_emit_mutable(&backend->handle()->events.new_input, &nativeDevice); + QCOMPARE(added.count(), 1); + QCOMPARE(backend->inputDeviceList().size(), 1); + + wlr_input_device_finish(&nativeDevice); + + QCOMPARE(removed.count(), 1); + QVERIFY(backend->inputDeviceList().isEmpty()); + QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); + server.stop(); + qunsetenv("WLR_BACKENDS"); + } + + void cursorOwnsNativeHandle() + { + QPointer cursor; + wlr_cursor *nativeCursor = nullptr; + { + cursor = new WCursor(); + nativeCursor = cursor->handle(); + QVERIFY(nativeCursor); + QCOMPARE(WCursor::fromHandle(nativeCursor), cursor.data()); + // Owner rule: the test created it, so it releases it. + delete cursor; + } + // Do not read nativeCursor->data here: the native cursor is already + // destroyed (freed), so fromHandle() would be a use-after-free. + QVERIFY(cursor.isNull()); + } + + void seatTracksNativeLifetime() + { + qputenv("WAYLIB_DISABLE_GESTURE", "1"); + WServer server; + QPointer seat = server.attach(); + server.start(); + + auto *nativeSeat = seat->handle(); + QVERIFY(nativeSeat); + QCOMPARE(WSeat::fromHandle(nativeSeat), seat.data()); + + server.stop(); + // WM-194: WServer::stop() no longer deletes interfaces — the wrapper + // survives for restart. Only the native handle is destroyed and the + // reverse fromHandle() mapping is cleared before wlr_seat_destroy(). + QVERIFY(!seat.isNull()); // wrapper object survives stop() + QVERIFY(!seat->handle()); // native wlr_seat destroyed + QVERIFY(!WSeat::fromHandle(nativeSeat)); + qunsetenv("WAYLIB_DISABLE_GESTURE"); + } + + void outputAndLayoutTrackNativeLifetime() + { + WServer server; + auto *nativeBackend = wlr_headless_backend_create(wl_display_get_event_loop(server.handle())); + QVERIFY(nativeBackend); + auto *nativeOutput = wlr_headless_add_output(nativeBackend, 800, 600); + QVERIFY(nativeOutput); + + QPointer output = new WOutput(nativeOutput, nullptr); + // Owner rule: the test acts as the creator and monitors the native + // destroy signal to release the wrapper. + bool outputDestroyed = false; + QObject::connect(output, &QObject::destroyed, this, [&outputDestroyed] { outputDestroyed = true; }); + WScopedListener outputDestroyListener; + outputDestroyListener.init(&nativeOutput->events.destroy, this, + [output, &outputDestroyListener](void *) { + outputDestroyListener.disconnect(); + delete output; + }); + QCOMPARE(output->handle(), nativeOutput); + QCOMPARE(WOutput::fromHandle(nativeOutput), output.data()); + + // Headless backend does not emit the destroy signal inside + // wlr_output_destroy() (it asserts empty listener lists in + // wlr_output_finish instead), so simulate the native destruction. + wl_signal_emit_mutable(&nativeOutput->events.destroy, nativeOutput); + + QVERIFY(outputDestroyed); + QVERIFY(!WOutput::fromHandle(nativeOutput)); + QVERIFY(output.isNull()); + + wlr_output_destroy(nativeOutput); + wlr_backend_destroy(nativeBackend); + } +}; + +QTEST_MAIN(NativeHandlesTest) +#include "main.moc" diff --git a/waylib/tests/unit_tests/test_native_lifecycle/CMakeLists.txt b/waylib/tests/unit_tests/test_native_lifecycle/CMakeLists.txt new file mode 100644 index 0000000000..41e6c2b4ca --- /dev/null +++ b/waylib/tests/unit_tests/test_native_lifecycle/CMakeLists.txt @@ -0,0 +1,19 @@ +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +find_package(Qt6 REQUIRED COMPONENTS Gui Qml Test) + +add_executable(test_native_lifecycle main.cpp) + +target_link_libraries(test_native_lifecycle + PRIVATE + Waylib::WaylibServer + Qt::Gui + Qt::Qml + Qt::Test +) + +add_test(NAME test_native_lifecycle COMMAND test_native_lifecycle) + +set_property(TEST test_native_lifecycle PROPERTY + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" +) diff --git a/waylib/tests/unit_tests/test_native_lifecycle/main.cpp b/waylib/tests/unit_tests/test_native_lifecycle/main.cpp new file mode 100644 index 0000000000..363a18e8a7 --- /dev/null +++ b/waylib/tests/unit_tests/test_native_lifecycle/main.cpp @@ -0,0 +1,322 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +extern "C" { +#include +#define namespace scope +#include +#undef namespace +#include +#include +#include +} + +WAYLIB_SERVER_USE_NAMESPACE + +namespace { +struct BufferDestroyProbe { + wl_listener listener; + bool destroyed = false; + + BufferDestroyProbe() + { + listener.notify = notify; + wl_list_init(&listener.link); + } + + static void notify(wl_listener *listener, void *) + { + BufferDestroyProbe *probe; + probe = wl_container_of(listener, probe, listener); + probe->destroyed = true; + wl_list_remove(&probe->listener.link); + wl_list_init(&probe->listener.link); + } +}; + +void initSurface(wlr_surface *surface) +{ + *surface = {}; + wl_signal_init(&surface->events.client_commit); + wl_signal_init(&surface->events.commit); + wl_signal_init(&surface->events.map); + wl_signal_init(&surface->events.unmap); + wl_signal_init(&surface->events.new_subsurface); + wl_signal_init(&surface->events.destroy); + wl_list_init(&surface->current.frame_callback_list); + wl_list_init(&surface->current.subsurfaces_below); + wl_list_init(&surface->current.subsurfaces_above); + wl_list_init(&surface->current_outputs); +} + +void initXdgSurface(wlr_xdg_surface *surface, wlr_surface *nativeSurface, + wlr_xdg_client *client) +{ + *surface = {}; + surface->surface = nativeSurface; + surface->client = client; + wl_signal_init(&surface->events.configure); + wl_signal_init(&surface->events.new_popup); +} + +void initToplevel(wlr_xdg_toplevel *toplevel, wlr_xdg_surface *surface) +{ + *toplevel = {}; + toplevel->base = surface; + wl_signal_init(&toplevel->events.destroy); + wl_signal_init(&toplevel->events.request_maximize); + wl_signal_init(&toplevel->events.request_fullscreen); + wl_signal_init(&toplevel->events.request_minimize); + wl_signal_init(&toplevel->events.request_move); + wl_signal_init(&toplevel->events.request_resize); + wl_signal_init(&toplevel->events.request_show_window_menu); + wl_signal_init(&toplevel->events.set_parent); + wl_signal_init(&toplevel->events.set_title); + wl_signal_init(&toplevel->events.set_app_id); +} +} + +class NativeLifecycleTest : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void imageBufferHonorsNativeLockLifetime() + { + QImage image(16, 12, QImage::Format_ARGB32_Premultiplied); + image.fill(Qt::red); + auto *buffer = WImageBufferImpl::create(image); + QVERIFY(buffer); + QCOMPARE(buffer->width, image.width()); + QCOMPARE(buffer->height, image.height()); + + wlr_shm_attributes attributes {}; + // WImageBuffer is a CPU-memory buffer: it has no shared-memory fd, so + // it must not advertise fabricated SHM attributes (fd 0 would alias + // stdin). Its capability is the data pointer, verified below. + QVERIFY(!wlr_buffer_get_shm(buffer, &attributes)); + + void *data = nullptr; + uint32_t format = 0; + size_t stride = 0; + QVERIFY(wlr_buffer_begin_data_ptr_access(buffer, WLR_BUFFER_DATA_PTR_ACCESS_READ, + &data, &format, &stride)); + QCOMPARE(stride, image.bytesPerLine()); + wlr_buffer_end_data_ptr_access(buffer); + + BufferDestroyProbe probe; + wl_signal_add(&buffer->events.destroy, &probe.listener); + QCOMPARE(wlr_buffer_lock(buffer), buffer); + wlr_buffer_drop(buffer); + QVERIFY(!probe.destroyed); + wlr_buffer_unlock(buffer); + QVERIFY(probe.destroyed); + } + + void nativeSurfaceDestroyedFirst() + { + wlr_surface nativeSurface; + initSurface(&nativeSurface); + QPointer surface = new WSurface(&nativeSurface); + // Owner rule: the test acts as the creator and monitors the native + // destroy signal to release the wrapper. + bool surfaceDestroyed = false; + QObject::connect(surface, &QObject::destroyed, this, + [&surfaceDestroyed] { surfaceDestroyed = true; }); + bool handleAvailableDuringDestroy = false; + QObject::connect(surface, &WSurface::beforeDestroy, this, + [surface, &handleAvailableDuringDestroy, &nativeSurface] { + handleAvailableDuringDestroy = surface + && surface->handle() == &nativeSurface; + }); + WScopedListener surfaceDestroyListener; + surfaceDestroyListener.init(&nativeSurface.events.destroy, this, + [surface, &surfaceDestroyListener](void *) { surfaceDestroyListener.disconnect(); delete surface; }); + QCOMPARE(WSurface::fromHandle(&nativeSurface), surface.data()); + + wl_signal_emit_mutable(&nativeSurface.events.destroy, &nativeSurface); + QVERIFY(handleAvailableDuringDestroy); + + QVERIFY(surfaceDestroyed); + QVERIFY(!WSurface::fromHandle(&nativeSurface)); + QVERIFY(surface.isNull()); + } + + void surfaceObserverDestroyedFirst() + { + wlr_surface nativeSurface; + initSurface(&nativeSurface); + auto *surface = new WSurface(&nativeSurface); + QCOMPARE(WSurface::fromHandle(&nativeSurface), surface); + + delete surface; + QVERIFY(!WSurface::fromHandle(&nativeSurface)); + + // Every native listener must already be unlinked. + wl_signal_emit_mutable(&nativeSurface.events.destroy, &nativeSurface); + } + + void nativeXdgToplevelDestroyedFirst() + { + wlr_surface nativeSurface; + initSurface(&nativeSurface); + wlr_xdg_client client = {}; + wlr_xdg_surface xdgSurface; + initXdgSurface(&xdgSurface, &nativeSurface, &client); + wlr_xdg_toplevel nativeToplevel; + initToplevel(&nativeToplevel, &xdgSurface); + + QPointer surface = new WXdgToplevelSurface(&nativeToplevel); + // Owner rule: the test acts as the creator and monitors the native + // destroy signal to release the wrapper. + bool surfaceDestroyed = false; + QObject::connect(surface, &QObject::destroyed, this, [&surfaceDestroyed] { surfaceDestroyed = true; }); + WScopedListener surfaceDestroyListener; + surfaceDestroyListener.init(&nativeToplevel.events.destroy, this, + [surface, &surfaceDestroyListener](void *) { surfaceDestroyListener.disconnect(); delete surface; }); + QCOMPARE(WXdgToplevelSurface::fromHandle(&nativeToplevel), surface.data()); + + wl_signal_emit_mutable(&nativeToplevel.events.destroy, &nativeToplevel); + + QVERIFY(surfaceDestroyed); + QVERIFY(!WXdgToplevelSurface::fromHandle(&nativeToplevel)); + QVERIFY(surface.isNull()); + } + + void xdgToplevelObserverDestroyedFirst() + { + wlr_surface nativeSurface; + initSurface(&nativeSurface); + wlr_xdg_client client = {}; + wlr_xdg_surface xdgSurface; + initXdgSurface(&xdgSurface, &nativeSurface, &client); + wlr_xdg_toplevel nativeToplevel; + initToplevel(&nativeToplevel, &xdgSurface); + + auto *surface = new WXdgToplevelSurface(&nativeToplevel); + delete surface; + + QVERIFY(!WXdgToplevelSurface::fromHandle(&nativeToplevel)); + wl_signal_emit_mutable(&nativeToplevel.events.destroy, &nativeToplevel); + } + + void nativeXdgPopupDestroyedFirst() + { + wlr_surface nativeSurface; + initSurface(&nativeSurface); + wlr_xdg_client client = {}; + wlr_xdg_surface xdgSurface; + initXdgSurface(&xdgSurface, &nativeSurface, &client); + wlr_xdg_popup nativePopup = {}; + nativePopup.base = &xdgSurface; + wl_signal_init(&nativePopup.events.destroy); + wl_signal_init(&nativePopup.events.reposition); + + QPointer surface = new WXdgPopupSurface(&nativePopup); + // Owner rule: the test acts as the creator and monitors the native + // destroy signal to release the wrapper. + bool surfaceDestroyed = false; + QObject::connect(surface, &QObject::destroyed, this, [&surfaceDestroyed] { surfaceDestroyed = true; }); + WScopedListener surfaceDestroyListener; + surfaceDestroyListener.init(&nativePopup.events.destroy, this, + [surface, &surfaceDestroyListener](void *) { surfaceDestroyListener.disconnect(); delete surface; }); + QCOMPARE(WXdgPopupSurface::fromHandle(&nativePopup), surface.data()); + wl_signal_emit_mutable(&nativePopup.events.destroy, &nativePopup); + + QVERIFY(surfaceDestroyed); + QVERIFY(!WXdgPopupSurface::fromHandle(&nativePopup)); + QVERIFY(surface.isNull()); + } + + void nativeLayerSurfaceDestroyedFirst() + { + wlr_surface nativeSurface; + initSurface(&nativeSurface); + wlr_layer_surface_v1 nativeLayerSurface = {}; + nativeLayerSurface.surface = &nativeSurface; + wl_signal_init(&nativeLayerSurface.events.destroy); + wl_signal_init(&nativeLayerSurface.events.new_popup); + + QPointer surface = new WLayerSurface(&nativeLayerSurface); + // Owner rule: the test acts as the creator and monitors the native + // destroy signal to release the wrapper. + bool surfaceDestroyed = false; + QObject::connect(surface, &QObject::destroyed, this, [&surfaceDestroyed] { surfaceDestroyed = true; }); + WScopedListener surfaceDestroyListener; + surfaceDestroyListener.init(&nativeLayerSurface.events.destroy, this, + [surface, &surfaceDestroyListener](void *) { surfaceDestroyListener.disconnect(); delete surface; }); + QCOMPARE(WLayerSurface::fromHandle(&nativeLayerSurface), surface.data()); + wl_signal_emit_mutable(&nativeLayerSurface.events.destroy, &nativeLayerSurface); + + QVERIFY(surfaceDestroyed); + QVERIFY(!WLayerSurface::fromHandle(&nativeLayerSurface)); + QVERIFY(surface.isNull()); + } + + void nativeSessionLockDestroyedFirst() + { + wlr_session_lock_v1 nativeLock = {}; + wl_list_init(&nativeLock.surfaces); + wl_signal_init(&nativeLock.events.new_surface); + wl_signal_init(&nativeLock.events.unlock); + wl_signal_init(&nativeLock.events.destroy); + + QPointer lock = new WSessionLock(&nativeLock); + // Owner rule: the test acts as the creator and monitors the native + // destroy signal to release the wrapper. + bool lockDestroyed = false; + QObject::connect(lock, &QObject::destroyed, this, [&lockDestroyed] { lockDestroyed = true; }); + WScopedListener lockDestroyListener; + lockDestroyListener.init(&nativeLock.events.destroy, this, + [lock, &lockDestroyListener](void *) { lockDestroyListener.disconnect(); delete lock; }); + QCOMPARE(WSessionLock::fromHandle(&nativeLock), lock.data()); + QSignalSpy canceled(lock, &WSessionLock::canceled); + wl_signal_emit_mutable(&nativeLock.events.destroy, &nativeLock); + + QCOMPARE(canceled.count(), 1); + QVERIFY(lockDestroyed); + QVERIFY(!WSessionLock::fromHandle(&nativeLock)); + QVERIFY(lock.isNull()); + } + + void nativeSessionLockSurfaceDestroyedFirst() + { + wlr_surface nativeSurface; + initSurface(&nativeSurface); + wlr_session_lock_surface_v1 nativeLockSurface = {}; + nativeLockSurface.surface = &nativeSurface; + wl_signal_init(&nativeLockSurface.events.destroy); + + QPointer surface = new WSessionLockSurface(&nativeLockSurface); + // Owner rule: the test acts as the creator and monitors the native + // destroy signal to release the wrapper. + bool surfaceDestroyed = false; + QObject::connect(surface, &QObject::destroyed, this, [&surfaceDestroyed] { surfaceDestroyed = true; }); + WScopedListener surfaceDestroyListener; + surfaceDestroyListener.init(&nativeLockSurface.events.destroy, this, + [surface, &surfaceDestroyListener](void *) { surfaceDestroyListener.disconnect(); delete surface; }); + QCOMPARE(WSessionLockSurface::fromHandle(&nativeLockSurface), surface.data()); + wl_signal_emit_mutable(&nativeLockSurface.events.destroy, &nativeLockSurface); + + QVERIFY(surfaceDestroyed); + QVERIFY(!WSessionLockSurface::fromHandle(&nativeLockSurface)); + QVERIFY(surface.isNull()); + } +}; + +QTEST_MAIN(NativeLifecycleTest) +#include "main.moc" diff --git a/waylib/tests/unit_tests/test_output_frame/CMakeLists.txt b/waylib/tests/unit_tests/test_output_frame/CMakeLists.txt new file mode 100644 index 0000000000..74a6ba71ed --- /dev/null +++ b/waylib/tests/unit_tests/test_output_frame/CMakeLists.txt @@ -0,0 +1,15 @@ +find_package(Qt6 REQUIRED COMPONENTS Gui Qml Quick Test) + +add_executable(test_output_frame main.cpp) + +target_link_libraries(test_output_frame + PRIVATE + Waylib::WaylibServer + Qt::Gui + Qt::Qml + Qt::Quick + Qt::Test +) + +add_test(NAME test_output_frame COMMAND test_output_frame) +set_property(TEST test_output_frame PROPERTY TIMEOUT 30) diff --git a/waylib/tests/unit_tests/test_output_frame/main.cpp b/waylib/tests/unit_tests/test_output_frame/main.cpp new file mode 100644 index 0000000000..63426f0e45 --- /dev/null +++ b/waylib/tests/unit_tests/test_output_frame/main.cpp @@ -0,0 +1,103 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include +#include +#include +#include +#include +#include + +extern "C" { +#include +} + +#include +#include +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +class OutputFrameTest : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void nativeFramesOnlyCommitTheirOutput() + { + WServer server; + auto *backend = server.attach(); + server.start(); + auto *renderer = WRenderHelper::createRenderer(backend->handle()); + QVERIFY(renderer); + const auto rendererCleanup = qScopeGuard([&] { wlr_renderer_destroy(renderer); }); + auto *allocator = wlr_allocator_autocreate(backend->handle(), renderer); + QVERIFY(allocator); + const auto allocatorCleanup = qScopeGuard([&] { wlr_allocator_destroy(allocator); }); + QVERIFY(wlr_backend_start(backend->handle())); + const auto outputs = backend->outputList(); + QCOMPARE(outputs.size(), 2); + + WOutputRenderWindow window; + window.setWidth(128); + window.setHeight(64); + window.init(renderer, allocator); + WOutputViewport a(window.contentItem()); + WOutputViewport b(window.contentItem()); + a.setOutput(outputs[0]); + b.setOutput(outputs[1]); + for (int i = 0; i < outputs.size(); ++i) { + wlr_output_state state; + wlr_output_state_init(&state); + const auto stateCleanup = qScopeGuard([&] { wlr_output_state_finish(&state); }); + wlr_output_state_set_custom_mode(&state, 64, 64, i == 0 ? 60000 : 144000); + wlr_output_state_set_enabled(&state, true); + QVERIFY(wlr_output_commit_state(outputs[i]->handle(), &state)); + } + + QSignalSpy rendered(&window, &WOutputRenderWindow::renderEnd); + auto prepare = [&] { + window.update(); + // Both outputs are dirty and ready. Emit frames explicitly rather + // than dispatching the headless backend's refresh timers. + for (auto *output : outputs) + output->handle()->frame_pending = false; + rendered.clear(); + }; + + prepare(); + wlr_output_send_frame(outputs[0]->handle()); + QCOMPARE(rendered.size(), 1); + QCOMPARE(qvariant_cast>>(rendered.takeFirst().first()), + QList>{outputs[0]}); + + prepare(); + wlr_output_send_frame(outputs[1]->handle()); + QCOMPARE(rendered.size(), 1); + QCOMPARE(qvariant_cast>>(rendered.takeFirst().first()), + QList>{outputs[1]}); + + prepare(); + window.render(); + QCOMPARE(rendered.size(), 1); + const auto committed = qvariant_cast>>(rendered.takeFirst().first()); + QCOMPARE(committed.size(), 2); + QVERIFY(committed.contains(outputs[0])); + QVERIFY(committed.contains(outputs[1])); + } +}; + +int main(int argc, char **argv) +{ + qputenv("WLR_BACKENDS", "headless"); + qputenv("WLR_HEADLESS_OUTPUTS", "2"); + qputenv("QT_QUICK_BACKEND", "software"); + WServer::initializeQPA(); + QGuiApplication app(argc, argv); + OutputFrameTest test; + return QTest::qExec(&test, argc, argv); +} + +#include "main.moc" diff --git a/waylib/tests/unit_tests/test_qsgrenderer_accessor/CMakeLists.txt b/waylib/tests/unit_tests/test_qsgrenderer_accessor/CMakeLists.txt new file mode 100644 index 0000000000..b692a6b68c --- /dev/null +++ b/waylib/tests/unit_tests/test_qsgrenderer_accessor/CMakeLists.txt @@ -0,0 +1,23 @@ +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +find_package(Qt6 REQUIRED COMPONENTS Test Quick) + +add_executable(test_qsgrenderer_accessor + main.cpp + qsgrenderer_direct.cpp +) + +target_link_libraries(test_qsgrenderer_accessor + PRIVATE + Waylib::WaylibServer + Qt::Test + Qt::Quick + Qt6::QuickPrivate +) + +add_test(NAME test_qsgrenderer_accessor COMMAND test_qsgrenderer_accessor) + +set_property(TEST test_qsgrenderer_accessor PROPERTY + ENVIRONMENT "QT_QPA_PLATFORM=offscreen" +) diff --git a/waylib/tests/unit_tests/test_qsgrenderer_accessor/main.cpp b/waylib/tests/unit_tests/test_qsgrenderer_accessor/main.cpp new file mode 100644 index 0000000000..1704036815 --- /dev/null +++ b/waylib/tests/unit_tests/test_qsgrenderer_accessor/main.cpp @@ -0,0 +1,114 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// Unit test: cross-verify W_PRIVATE_BF_SET/GET against direct member access. +// +// The bit-field accessor in wrenderbuffernode.cpp reaches QSGRenderer's private +// bit fields (m_changed_emitted, m_is_rendering) via memory arithmetic from the +// preceding member (m_nodes_dont_preprocess). This test verifies: +// +// 1. Accessor write → direct read : W_PRIVATE_BF_SET sets the correct field. +// 2. Direct write → accessor read: W_PRIVATE_BF_GET reads the correct field. +// 3. Bit isolation : setting one bit does not affect the other. +// +// If Qt changes the bit-field declaration order or inserts a member between +// m_nodes_dont_preprocess and the bit fields, one or more tests below will fail. +// +// Implementation note: QSGRenderer is abstract; constructing it requires a live +// QSGRenderContext. For layout tests we only need pointer arithmetic on raw +// memory — no virtual dispatch, no initialised members. A zero-filled, +// correctly-aligned buffer is sufficient. + +#include +#include +#include "private/wprivateaccessor_p.h" + +// Register tag structs with names distinct from the ones in wrenderbuffernode.cpp +// to avoid duplicate explicit instantiations when the test links to WaylibServer. +W_DECLARE_PRIVATE_BITFIELD(Test_QSGRendererBF, + QSGRenderer, m_nodes_dont_preprocess, + QSet, uint); + +// Bit positions must match the declaration order in qsgrenderer_p.h: +// uint m_changed_emitted : 1; → bit 0 +// uint m_is_rendering : 1; → bit 1 +static constexpr unsigned kChangedEmittedBit = 0; +static constexpr unsigned kIsRenderingBit = 1; + +// Direct-access helpers from qsgrenderer_direct.cpp (#define private public). +// extern "C" + void* avoids any ODR issue with the QSGRenderer class definition. +extern "C" { + int direct_qsgrenderer_get_is_rendering(const void *obj); + int direct_qsgrenderer_get_changed_emitted(const void *obj); + void direct_qsgrenderer_set_is_rendering(void *obj, bool v); + void direct_qsgrenderer_set_changed_emitted(void *obj, bool v); +} + +class QSGRendererAccessorTest : public QObject +{ + Q_OBJECT + + // Raw buffer: same size and alignment as QSGRenderer, zero-initialised. + // No construction — we only test offset arithmetic and bit masking, + // neither of which requires a valid vtable or initialised data members. + alignas(QSGRenderer) char m_buf[sizeof(QSGRenderer)]; + QSGRenderer *r; + +public: + explicit QSGRendererAccessorTest(QObject *parent = nullptr) + : QObject(parent) + , r(reinterpret_cast(m_buf)) + {} + +private Q_SLOTS: + // Reset buffer to all-zeros before each sub-test. + void init() { memset(m_buf, 0, sizeof(m_buf)); } + + // --- Accessor write → direct read -------------------------------------- + + void test_set_isRendering_visible_via_direct() + { + W_PRIVATE_BF_SET(*r, Test_QSGRendererBF, kIsRenderingBit, true); + QCOMPARE(direct_qsgrenderer_get_is_rendering(r), 1); + QCOMPARE(direct_qsgrenderer_get_changed_emitted(r), 0); // other bit untouched + } + + void test_set_changedEmitted_visible_via_direct() + { + W_PRIVATE_BF_SET(*r, Test_QSGRendererBF, kChangedEmittedBit, true); + QCOMPARE(direct_qsgrenderer_get_changed_emitted(r), 1); + QCOMPARE(direct_qsgrenderer_get_is_rendering(r), 0); // other bit untouched + } + + // --- Direct write → accessor read -------------------------------------- + + void test_read_isRendering_via_accessor() + { + direct_qsgrenderer_set_is_rendering(r, true); + QCOMPARE(W_PRIVATE_BF_GET(*r, Test_QSGRendererBF, kIsRenderingBit), true); + QCOMPARE(W_PRIVATE_BF_GET(*r, Test_QSGRendererBF, kChangedEmittedBit), false); + } + + void test_read_changedEmitted_via_accessor() + { + direct_qsgrenderer_set_changed_emitted(r, true); + QCOMPARE(W_PRIVATE_BF_GET(*r, Test_QSGRendererBF, kChangedEmittedBit), true); + QCOMPARE(W_PRIVATE_BF_GET(*r, Test_QSGRendererBF, kIsRenderingBit), false); + } + + // --- Clear bits via accessor ------------------------------------------- + + void test_clear_isRendering_via_accessor() + { + direct_qsgrenderer_set_is_rendering(r, true); + direct_qsgrenderer_set_changed_emitted(r, true); + + W_PRIVATE_BF_SET(*r, Test_QSGRendererBF, kIsRenderingBit, false); + + QCOMPARE(direct_qsgrenderer_get_is_rendering(r), 0); + QCOMPARE(direct_qsgrenderer_get_changed_emitted(r), 1); // unaffected + } +}; + +QTEST_MAIN(QSGRendererAccessorTest) +#include "main.moc" diff --git a/waylib/tests/unit_tests/test_qsgrenderer_accessor/qsgrenderer_direct.cpp b/waylib/tests/unit_tests/test_qsgrenderer_accessor/qsgrenderer_direct.cpp new file mode 100644 index 0000000000..66951667f2 --- /dev/null +++ b/waylib/tests/unit_tests/test_qsgrenderer_accessor/qsgrenderer_direct.cpp @@ -0,0 +1,54 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +// This translation unit intentionally uses the "#define private public" technique +// to expose QSGRenderer's private bit-field members for cross-verification in +// layout tests. +// +// Strategy: pre-include all of qsgrenderer_p.h's transitive dependencies first, +// so their include guards are already set. The "#define private public" block then +// only opens up the QSGRenderer class body itself — keeping the blast radius small. + +#include +#include +#include +#include + +// --- The hack: expose QSGRenderer's private section ------------------------- +// Everything transitively included by qsgrenderer_p.h is already guarded above. +// The redefinition of 'private' therefore only affects the QSGRenderer class body. +#define private public +#include +#undef private +// ---------------------------------------------------------------------------- + +QT_USE_NAMESPACE + +// These functions provide direct access to QSGRenderer's private bit fields. +// They are declared extern "C" so that main.cpp can reference them without +// needing to agree on the (ODR-violated) QSGRenderer class definition. +// void* parameters avoid any class-type ODR issues at the call sites. + +extern "C" { + +int direct_qsgrenderer_get_is_rendering(const void *obj) +{ + return static_cast(obj)->m_is_rendering; +} + +int direct_qsgrenderer_get_changed_emitted(const void *obj) +{ + return static_cast(obj)->m_changed_emitted; +} + +void direct_qsgrenderer_set_is_rendering(void *obj, bool v) +{ + static_cast(obj)->m_is_rendering = v; +} + +void direct_qsgrenderer_set_changed_emitted(void *obj, bool v) +{ + static_cast(obj)->m_changed_emitted = v; +} + +} // extern "C" diff --git a/waylib/tests/unit_tests/test_wlog/CMakeLists.txt b/waylib/tests/unit_tests/test_wlog/CMakeLists.txt new file mode 100644 index 0000000000..cebdcdaf80 --- /dev/null +++ b/waylib/tests/unit_tests/test_wlog/CMakeLists.txt @@ -0,0 +1,12 @@ +find_package(Qt6 REQUIRED COMPONENTS Core Test) + +add_executable(test_wlog main.cpp) + +target_link_libraries(test_wlog + PRIVATE + Waylib::WaylibServer + Qt::Core + Qt::Test +) + +add_test(NAME test_wlog COMMAND test_wlog) diff --git a/waylib/tests/unit_tests/test_wlog/main.cpp b/waylib/tests/unit_tests/test_wlog/main.cpp new file mode 100644 index 0000000000..f7c97cf96a --- /dev/null +++ b/waylib/tests/unit_tests/test_wlog/main.cpp @@ -0,0 +1,77 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include + +#include +#include + +WAYLIB_SERVER_USE_NAMESPACE + +// WLog routes wlroots' C logging (wlr_log) through a configurable callback; +// the default callback forwards to the "wlroots" Qt logging category. These +// tests verify the routing mechanism with a custom callback (the default +// callback's Qt output is environment-dependent and covered by manual runs). + +static int g_messageCount = 0; +static wlr_log_importance g_lastVerbosity = WLR_SILENT; + +static void testCallback(wlr_log_importance verbosity, const char *fmt, va_list args) +{ + Q_UNUSED(fmt); + Q_UNUSED(args); + g_messageCount++; + g_lastVerbosity = verbosity; +} + +class TestWLog : public QObject +{ + Q_OBJECT +private Q_SLOTS: + void initInstallsCallback(); + void initVerbosityFilters(); + void initRestoresDefaultCallback(); +}; + +void TestWLog::initInstallsCallback() +{ + g_messageCount = 0; + WLog::init(WLR_DEBUG, &testCallback); + + wlr_log(WLR_INFO, "test %d", 42); + wlr_log(WLR_ERROR, "boom"); + QCOMPARE(g_messageCount, 2); + QCOMPARE(g_lastVerbosity, WLR_ERROR); +} + +void TestWLog::initVerbosityFilters() +{ + g_messageCount = 0; + WLog::init(WLR_ERROR, &testCallback); + + // wlroots records the requested verbosity... + QCOMPARE(wlr_log_get_verbosity(), WLR_ERROR); + // ...but filtering is the callback's responsibility: a custom callback + // receives every message (the default stderr/Qt callbacks filter). + wlr_log(WLR_INFO, "custom callbacks see everything"); + wlr_log(WLR_ERROR, "and errors too"); + QCOMPARE(g_messageCount, 2); + QCOMPARE(g_lastVerbosity, WLR_ERROR); +} + +void TestWLog::initRestoresDefaultCallback() +{ + g_messageCount = 0; + // The default callback must be installable through the same entry point + // and must not crash when wlroots emits messages. + WLog::init(); + wlr_log(WLR_INFO, "through default callback %s", "ok"); + wlr_log(WLR_DEBUG, "debug through default callback"); + WLog::init(WLR_DEBUG, &testCallback); + wlr_log(WLR_INFO, "back to custom"); + QCOMPARE(g_messageCount, 1); +} + +QTEST_GUILESS_MAIN(TestWLog) + +#include "main.moc" diff --git a/waylib/tests/unit_tests/test_wobject_listeners/CMakeLists.txt b/waylib/tests/unit_tests/test_wobject_listeners/CMakeLists.txt new file mode 100644 index 0000000000..29d547c2bb --- /dev/null +++ b/waylib/tests/unit_tests/test_wobject_listeners/CMakeLists.txt @@ -0,0 +1,12 @@ +find_package(Qt6 REQUIRED COMPONENTS Core Test) + +add_executable(test_wobject_listeners main.cpp) + +target_link_libraries(test_wobject_listeners + PRIVATE + Waylib::WaylibServer + Qt::Core + Qt::Test +) + +add_test(NAME test_wobject_listeners COMMAND test_wobject_listeners) diff --git a/waylib/tests/unit_tests/test_wobject_listeners/main.cpp b/waylib/tests/unit_tests/test_wobject_listeners/main.cpp new file mode 100644 index 0000000000..2298c7a7b7 --- /dev/null +++ b/waylib/tests/unit_tests/test_wobject_listeners/main.cpp @@ -0,0 +1,180 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include +#include + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +// Minimal WObject that always tears down before ~WObject's empty-list check. +class TestObject : public WObject +{ +public: + ~TestObject() { teardown(); } +}; + +class TestWObjectListeners : public QObject +{ + Q_OBJECT +private Q_SLOTS: + void selfListenersStableUntilTeardown(); + void crossObjectTeardownDetachesFromTarget(); + void removeListenersClearsBidirectionalLinks(); + void multipleOwnersIndependent(); + void listenerOwnerDestructorRunsTeardown(); + void teardownIdempotent(); +}; + +void TestWObjectListeners::selfListenersStableUntilTeardown() +{ + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + + TestObject obj; + auto *list = obj.listeners(); + QVERIFY(list); + QCOMPARE(obj.listeners(), list); + + list->add(&sig, [&count](void *) { count++; }); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); + + auto *priv = WObjectPrivate::get(&obj); + QCOMPARE(priv->attachedListenerLists.size(), 1); + QCOMPARE(priv->attachedListenerLists.first().first, &obj); + QVERIFY(priv->attachedListenerTargets.isEmpty()); + + obj.teardown(); + QVERIFY(priv->attachedListenerLists.isEmpty()); + QVERIFY(priv->attachedListenerTargets.isEmpty()); + + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); // disconnected by teardown +} + +void TestWObjectListeners::crossObjectTeardownDetachesFromTarget() +{ + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + + TestObject target; + TestObject owner; + + target.listeners(&owner)->add(&sig, [&count](void *) { count++; }); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); + + auto *ownerPriv = WObjectPrivate::get(&owner); + auto *targetPriv = WObjectPrivate::get(&target); + QCOMPARE(ownerPriv->attachedListenerTargets, QList{&target}); + QCOMPARE(targetPriv->attachedListenerLists.size(), 1); + QCOMPARE(targetPriv->attachedListenerLists.first().first, &owner); + + // Owner teardown must auto-detach its groups from every registered target. + owner.teardown(); + QVERIFY(ownerPriv->attachedListenerTargets.isEmpty()); + QVERIFY(targetPriv->attachedListenerLists.isEmpty()); + + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); +} + +void TestWObjectListeners::removeListenersClearsBidirectionalLinks() +{ + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + + TestObject target; + TestObject owner; + + target.listeners(&owner)->add(&sig, [&count](void *) { count++; }); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); + + target.removeListeners(&owner); + + auto *ownerPriv = WObjectPrivate::get(&owner); + auto *targetPriv = WObjectPrivate::get(&target); + QVERIFY(ownerPriv->attachedListenerTargets.isEmpty()); + QVERIFY(targetPriv->attachedListenerLists.isEmpty()); + + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); +} + +void TestWObjectListeners::multipleOwnersIndependent() +{ + wl_signal sig; + wl_signal_init(&sig); + int countA = 0; + int countB = 0; + + TestObject target; + TestObject ownerA; + TestObject ownerB; + + target.listeners(&ownerA)->add(&sig, [&countA](void *) { countA++; }); + target.listeners(&ownerB)->add(&sig, [&countB](void *) { countB++; }); + + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(countA, 1); + QCOMPARE(countB, 1); + + ownerA.teardown(); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(countA, 1); + QCOMPARE(countB, 2); + + auto *targetPriv = WObjectPrivate::get(&target); + QCOMPARE(targetPriv->attachedListenerLists.size(), 1); + QCOMPARE(targetPriv->attachedListenerLists.first().first, &ownerB); + + ownerB.teardown(); + QVERIFY(targetPriv->attachedListenerLists.isEmpty()); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(countB, 2); +} + +void TestWObjectListeners::listenerOwnerDestructorRunsTeardown() +{ + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + + TestObject target; + { + WListenerOwner owner; + target.listeners(&owner)->add(&sig, [&count](void *) { count++; }); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); + } + + // ~WListenerOwner calls teardown(), so the target list is gone and the + // signal no longer reaches the destroyed owner's callback. + QVERIFY(WObjectPrivate::get(&target)->attachedListenerLists.isEmpty()); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); +} + +void TestWObjectListeners::teardownIdempotent() +{ + TestObject obj; + obj.listeners(); + QCOMPARE(WObjectPrivate::get(&obj)->attachedListenerLists.size(), 1); + + obj.teardown(); + obj.teardown(); + QVERIFY(WObjectPrivate::get(&obj)->attachedListenerLists.isEmpty()); + QVERIFY(WObjectPrivate::get(&obj)->attachedListenerTargets.isEmpty()); +} + +QTEST_GUILESS_MAIN(TestWObjectListeners) +#include "main.moc" diff --git a/waylib/tests/unit_tests/test_wpointer/CMakeLists.txt b/waylib/tests/unit_tests/test_wpointer/CMakeLists.txt new file mode 100644 index 0000000000..c76cca1bd9 --- /dev/null +++ b/waylib/tests/unit_tests/test_wpointer/CMakeLists.txt @@ -0,0 +1,12 @@ +find_package(Qt6 REQUIRED COMPONENTS Core Test) + +add_executable(test_wpointer main.cpp) + +target_link_libraries(test_wpointer + PRIVATE + Waylib::WaylibServer + Qt::Core + Qt::Test +) + +add_test(NAME test_wpointer COMMAND test_wpointer) diff --git a/waylib/tests/unit_tests/test_wpointer/main.cpp b/waylib/tests/unit_tests/test_wpointer/main.cpp new file mode 100644 index 0000000000..655b797636 --- /dev/null +++ b/waylib/tests/unit_tests/test_wpointer/main.cpp @@ -0,0 +1,333 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +// wlr_seat is used as the test subject: it has a public create/destroy pair +// (wlr_seat_create/wlr_seat_destroy) and carries a events.destroy signal, +// which exercises both RAII destruction and auto-nulling. A wl_display is +// created per test and destroyed after the seat is gone. + +// Fake wlroots-style object with a destroy signal; a custom +// WlrObjectTraits specialization counts destroy calls so shared-ownership +// semantics are verified precisely without relying on ASan double-free +// detection. +struct FakeObject { + struct { struct wl_signal destroy; } events; + static inline int destroyCount = 0; + + static FakeObject *create() { + auto *obj = new FakeObject; + wl_signal_init(&obj->events.destroy); + return obj; + } +}; + +template<> +struct Waylib::Server::WlrObjectTraits { + static void destroy(FakeObject *obj) { + wl_signal_emit_mutable(&obj->events.destroy, obj); + ++FakeObject::destroyCount; + delete obj; + } +}; + +class TestWPointer : public QObject +{ + Q_OBJECT +private Q_SLOTS: + void uniquePointerDestroysOnScopeExit(); + void uniquePointerMoveTransfersOwnership(); + void uniquePointerResetReplaces(); + void uniquePointerReleaseDetaches(); + void uniquePointerWithoutSignalStillDestroys(); + void uniquePointerSwap(); + void uniquePointerCompareOperators(); + void uniquePointerResetReentrantDestroy(); + void observerPointerNullsOnDestroy(); + void observerInputDeviceDerivedNullsOnBaseDestroy(); + void observerCopiesShareLifetime(); + void observerAssignFromRawPointer(); + void observerMoveTransfersObservation(); + void observerAccessors(); + void observerReassignToNewHandle(); +}; + +void TestWPointer::uniquePointerDestroysOnScopeExit() +{ + wl_display *display = wl_display_create(); + auto *cursor = wlr_seat_create(display, "test"); + QVERIFY(cursor); + { + WUniquePointer ptr(cursor); + QCOMPARE(ptr.get(), cursor); + QVERIFY(ptr); + QCOMPARE(ptr.get(), cursor); + } + // The cursor must be gone; calling wlr_seat_destroy again would be a + // double free, so no explicit check here — a regression double-free shows + // up as a crash under ASan and as the destructor never running otherwise. + wl_display_destroy(display); +} + +void TestWPointer::uniquePointerMoveTransfersOwnership() +{ + wl_display *display = wl_display_create(); + auto *cursor = wlr_seat_create(display, "test"); + { + WUniquePointer a(cursor); + WUniquePointer b(std::move(a)); + QVERIFY(!a); + QCOMPARE(b.get(), cursor); + + WUniquePointer c; + c = std::move(b); + QVERIFY(!b); + QCOMPARE(c.get(), cursor); + // Ownership transferred; the seat is released by c's destructor + // (WUniquePointer does not observe the native destroy signal, so it + // must outlive the native object it owns). + } + wl_display_destroy(display); +} + +void TestWPointer::uniquePointerResetReplaces() +{ + wl_display *display = wl_display_create(); + auto *first = wlr_seat_create(display, "first"); + auto *second = wlr_seat_create(display, "second"); + { + WUniquePointer ptr(first); + ptr.reset(second); // destroys first, adopts second + QCOMPARE(ptr.get(), second); + // second is released by ptr's destructor (no external destroy). + } + wl_display_destroy(display); +} + +void TestWPointer::uniquePointerReleaseDetaches() +{ + wl_display *display = wl_display_create(); + auto *cursor = wlr_seat_create(display, "test"); + WUniquePointer ptr(cursor); + auto *raw = ptr.release(); + QCOMPARE(raw, cursor); + QVERIFY(!ptr); + // Ownership is ours again; the raw handle is destroyed by us. + wlr_seat_destroy(raw); + wl_display_destroy(display); +} + +void TestWPointer::uniquePointerWithoutSignalStillDestroys() +{ + // wlr_cursor has no events.destroy signal: RAII destruction still works + // through the traits deleter, without any signal observation. + auto *cursor = wlr_cursor_create(); + QVERIFY(cursor); + WUniquePointer ptr(cursor); + QCOMPARE(ptr.get(), cursor); + ptr.reset(); + QVERIFY(!ptr); +} + +void TestWPointer::observerPointerNullsOnDestroy() +{ + wl_display *display = wl_display_create(); + auto *cursor = wlr_seat_create(display, "test"); + { + WPointer p(cursor); + QCOMPARE(p.get(), cursor); + wlr_seat_destroy(cursor); + QVERIFY(p.isNull()); + } + wl_display_destroy(display); +} + +void TestWPointer::observerInputDeviceDerivedNullsOnBaseDestroy() +{ + // wlr_keyboard carries no events.destroy of its own — the destroy signal + // lives on its embedded wlr_input_device base and is emitted from + // wlr_input_device_finish() when the device goes away. + wlr_keyboard kb; + wlr_keyboard_init(&kb, nullptr, "test"); + WPointer p(&kb); + QCOMPARE(p.get(), &kb); + + wlr_keyboard_finish(&kb); // emits kb.base.events.destroy + QVERIFY(p.isNull()); +} + +void TestWPointer::observerCopiesShareLifetime() +{ + wl_display *display = wl_display_create(); + auto *cursor = wlr_seat_create(display, "test"); + WPointer a(cursor); + WPointer b = a; + WPointer c; + c = a; + QCOMPARE(b.get(), cursor); + QCOMPARE(c.get(), cursor); + + wlr_seat_destroy(cursor); + QVERIFY(a.isNull()); + QVERIFY(b.isNull()); + QVERIFY(c.isNull()); + wl_display_destroy(display); +} + +void TestWPointer::observerAssignFromRawPointer() +{ + wl_display *display = wl_display_create(); + auto *cursor = wlr_seat_create(display, "test"); + WPointer p; + p = cursor; + QCOMPARE(p.get(), cursor); + wlr_seat_destroy(cursor); + QVERIFY(p.isNull()); + wl_display_destroy(display); +} + +void TestWPointer::uniquePointerSwap() +{ + wl_display *display = wl_display_create(); + auto *first = wlr_seat_create(display, "first"); + auto *second = wlr_seat_create(display, "second"); + { + WUniquePointer a(first); + WUniquePointer b(second); + + a.swap(b); + QCOMPARE(a.get(), second); + QCOMPARE(b.get(), first); + + swap(a, b); // std::swap-free friend function + QCOMPARE(a.get(), first); + QCOMPARE(b.get(), second); + // Both handles released by the wrappers' destructors (no external + // destroy — pure RAII ownership). + } + wl_display_destroy(display); +} + +void TestWPointer::uniquePointerCompareOperators() +{ + wl_display *display = wl_display_create(); + auto *cursor = wlr_seat_create(display, "test"); + auto *other = wlr_seat_create(display, "other"); + { + WUniquePointer a(cursor); + WUniquePointer c(other); + + QVERIFY(a != c); // different handles + QCOMPARE(a.get(), cursor); // vs raw pointer + QCOMPARE(c.get(), other); + // Both handles released by the wrappers' destructors. + } + wl_display_destroy(display); +} + +void TestWPointer::uniquePointerResetReentrantDestroy() +{ + // Destroying the old handle from reset() must not leave the wrapper + // pointing at the half-destroyed object: the handle is exchanged out + // before Traits::destroy runs, so a destroy callback that re-enters the + // wrapper sees the new handle (or null). + FakeObject::destroyCount = 0; + auto *first = FakeObject::create(); + auto *second = FakeObject::create(); + + struct Observer { + WUniquePointer *wrapper = nullptr; + FakeObject *expected = nullptr; + bool reentered = false; + wl_listener listener {}; + } observer { nullptr, nullptr, false }; + + // The wrapper must be fully constructed before the destroy listener can + // re-enter it. + auto ptr = std::make_unique>(first); + observer.wrapper = ptr.get(); + observer.expected = second; + + observer.listener.notify = [](wl_listener *l, void *) { + auto *obs = reinterpret_cast( + reinterpret_cast(l) - offsetof(Observer, listener)); + obs->reentered = true; + // During reset(second), the old handle is already exchanged out. + QCOMPARE(obs->wrapper->get(), obs->expected); + }; + wl_signal_add(&first->events.destroy, &observer.listener); + + ptr->reset(second); // destroys first; destroy callback re-enters wrapper + QVERIFY(observer.reentered); + QCOMPARE(ptr->get(), second); + + // wl_signal_emit_mutable detaches each node before notifying, so the + // observer's link is already removed; the observer goes out of scope. + ptr.reset(); + QCOMPARE(FakeObject::destroyCount, 2); +} + +void TestWPointer::observerMoveTransfersObservation() +{ + wl_display *display = wl_display_create(); + auto *cursor = wlr_seat_create(display, "test"); + WPointer a(cursor); + WPointer b(std::move(a)); + QVERIFY(a.isNull()); // moved-from observer no longer watches + QCOMPARE(b.get(), cursor); + + WPointer c; + c = std::move(b); + QVERIFY(b.isNull()); + QCOMPARE(c.get(), cursor); + + wlr_seat_destroy(cursor); + QVERIFY(c.isNull()); + wl_display_destroy(display); +} + +void TestWPointer::observerAccessors() +{ + wl_display *display = wl_display_create(); + auto *cursor = wlr_seat_create(display, "test"); + WPointer p(cursor); + + QVERIFY(p); // operator bool + QVERIFY(!p.isNull()); + QCOMPARE(p.get(), cursor); + QCOMPARE(p.operator->(), cursor); + QCOMPARE(&(*p), cursor); // operator* + QCOMPARE(p, cursor); // implicit conversion to raw pointer + + wlr_seat_destroy(cursor); + QVERIFY(!p); + QVERIFY(p.isNull()); + QCOMPARE(p.get(), nullptr); + wl_display_destroy(display); +} + +void TestWPointer::observerReassignToNewHandle() +{ + wl_display *display = wl_display_create(); + auto *first = wlr_seat_create(display, "first"); + auto *second = wlr_seat_create(display, "second"); + WPointer p(first); + + p = second; // reassign: stops watching first, watches second + QCOMPARE(p.get(), second); + wlr_seat_destroy(first); // must not null p (no longer watching first) + QCOMPARE(p.get(), second); + + wlr_seat_destroy(second); + QVERIFY(p.isNull()); + wl_display_destroy(display); +} + +QTEST_GUILESS_MAIN(TestWPointer) + +#include "main.moc" diff --git a/waylib/tests/unit_tests/test_wscoplistener/CMakeLists.txt b/waylib/tests/unit_tests/test_wscoplistener/CMakeLists.txt new file mode 100644 index 0000000000..fc1080d5ec --- /dev/null +++ b/waylib/tests/unit_tests/test_wscoplistener/CMakeLists.txt @@ -0,0 +1,12 @@ +find_package(Qt6 REQUIRED COMPONENTS Core Test) + +add_executable(test_wscoplistener main.cpp) + +target_link_libraries(test_wscoplistener + PRIVATE + Waylib::WaylibServer + Qt::Core + Qt::Test +) + +add_test(NAME test_wscoplistener COMMAND test_wscoplistener) diff --git a/waylib/tests/unit_tests/test_wscoplistener/main.cpp b/waylib/tests/unit_tests/test_wscoplistener/main.cpp new file mode 100644 index 0000000000..902bc4cef1 --- /dev/null +++ b/waylib/tests/unit_tests/test_wscoplistener/main.cpp @@ -0,0 +1,367 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include + +#include + +#include + +WAYLIB_SERVER_USE_NAMESPACE + +// A connected WScopedListener must be safely movable: the wl_listener node +// is re-linked into the original signal at the new instance's address, so +// callbacks keep firing and destruction never removes a stale link. + +class TestWScopedListener : public QObject +{ + Q_OBJECT +private Q_SLOTS: + void moveConstructConnected(); + void moveAssignConnected(); + void moveUnconnected(); + void disconnectInsideCallback(); + void destroyListenerInsideCallback(); + void destroyListInsideCallback(); + void moveThenExternalDestroy(); + void memberFunctionCallback(); + void constMemberFunctionCallback(); + void voidArgumentLambda(); + void dataPassedToCallback(); + void reinitToAnotherSignal(); + void reinitDoesNotLeakOldClosure(); + void listMultipleListenersAndClear(); + void listMovePreservesCallbacks(); + void emitOrderFollowsRegistration(); +}; + +void TestWScopedListener::moveConstructConnected() +{ + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + + WScopedListener a; + a.init(&sig, [&count](void *) { count++; }); + + WScopedListener b(std::move(a)); + QVERIFY(!a.isConnected()); + QVERIFY(b.isConnected()); + + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); // re-linked node still receives the signal +} + +void TestWScopedListener::moveAssignConnected() +{ + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + + WScopedListener a; + a.init(&sig, [&count](void *) { count++; }); + + WScopedListener b; + b = std::move(a); + QVERIFY(!a.isConnected()); + QVERIFY(b.isConnected()); + + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); + + // Move-assign over an already-connected target: the target's own link is + // dropped (disconnect), and b's listener is re-linked at c's address. + WScopedListener c; + c.init(&sig, [&count](void *) { count++; }); + c = std::move(b); + QVERIFY(!b.isConnected()); + QVERIFY(c.isConnected()); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 2); // b's callback, now living on c +} + +void TestWScopedListener::moveUnconnected() +{ + WScopedListener a; + WScopedListener b(std::move(a)); + QVERIFY(!b.isConnected()); + + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + b.init(&sig, [&count](void *) { count++; }); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); +} + +void TestWScopedListener::disconnectInsideCallback() +{ + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + + WScopedListener a; + a.init(&sig, [&](void *) { + count++; + a.disconnect(); // self-detach during emit_mutable is safe + }); + + wl_signal_emit_mutable(&sig, nullptr); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); // only the first emit reached the listener +} + +void TestWScopedListener::destroyListenerInsideCallback() +{ + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + + auto *listener = new WScopedListener; + listener->init(&sig, [&count, listener](void *) { + count++; + // Destroy the listener from inside its own callback. The closure + // (this lambda) is shared_ptr-managed, so it stays alive until the + // emission returns even though the listener object is gone. + delete listener; + }); + + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); + // Emitting again must not touch the destroyed listener. + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); +} + +void TestWScopedListener::destroyListInsideCallback() +{ + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + + auto *list = new WScopedListenerList; + list->add(&sig, [&count, list](void *) { + count++; + // Destroy the whole list (and its listeners) from inside a callback + // that belongs to it. + delete list; + }); + + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); +} + +void TestWScopedListener::moveThenExternalDestroy() +{ + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + + WScopedListener a; + a.init(&sig, [&count](void *) { count++; }); + + WScopedListener b(std::move(a)); + // A signal that is never emitted again is fine; destruction of b just + // unlinks the node. The stack signal then goes out of scope — no UAF. + QCOMPARE(b.isConnected(), true); +} + +void TestWScopedListener::memberFunctionCallback() +{ + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + + struct Receiver { + int *counter; + void onEvent(void *) { ++(*counter); } + void onNoArg() { ++(*counter); } + void onConst(void *) const { ++(*constCounter); } + int *constCounter; + } receiver { &count, &count }; + + WScopedListener a; + a.init(&sig, &receiver, &Receiver::onEvent); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); // only a registered so far + + WScopedListener b; + b.init(&sig, &receiver, &Receiver::onNoArg); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 3); // both a and b fire +} + +void TestWScopedListener::constMemberFunctionCallback() +{ + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + + struct Receiver { + int *counter; + void onConst(void *) const { ++(*counter); } + } receiver { &count }; + + WScopedListener a; + a.init(&sig, &receiver, &Receiver::onConst); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); +} + +void TestWScopedListener::voidArgumentLambda() +{ + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + + // Lambda taking no parameters must still be invocable. + WScopedListener a; + a.init(&sig, [&count]() { count++; }); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); + + // Also the 2-arg init form without an object. + WScopedListener b; + b.init(&sig, [&count]() { count++; }); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 3); // both a and b fire +} + +void TestWScopedListener::dataPassedToCallback() +{ + wl_signal sig; + wl_signal_init(&sig); + int received = 0; + struct Payload { int value; } payload { 42 }; + + WScopedListener a; + a.init(&sig, [&received](Payload *p) { received = p->value; }); + wl_signal_emit_mutable(&sig, &payload); + QCOMPARE(received, 42); + + // Member-function overload with the event pointer. + struct Receiver { + int *out; + void onPayload(Payload *p) { *out = p->value; } + } receiver { &received }; + WScopedListener b; + b.init(&sig, &receiver, &Receiver::onPayload); + wl_signal_emit_mutable(&sig, &payload); + QCOMPARE(received, 42); +} + +void TestWScopedListener::reinitToAnotherSignal() +{ + wl_signal sig1, sig2; + wl_signal_init(&sig1); + wl_signal_init(&sig2); + int count = 0; + + WScopedListener a; + a.init(&sig1, [&count](void *) { count++; }); + wl_signal_emit_mutable(&sig1, nullptr); + QCOMPARE(count, 1); + + // Re-init onto another signal: the old link must be dropped and only the + // new signal fires. + a.init(&sig2, [&count](void *) { count++; }); + wl_signal_emit_mutable(&sig1, nullptr); + QCOMPARE(count, 1); // sig1 no longer observed + wl_signal_emit_mutable(&sig2, nullptr); + QCOMPARE(count, 2); +} + +void TestWScopedListener::reinitDoesNotLeakOldClosure() +{ + wl_signal sig1, sig2; + wl_signal_init(&sig1); + wl_signal_init(&sig2); + + // Track closure lifetime: each live copy of Tracker increments alive. + // Re-init must free the previous closure before creating the new one; + // without the fix the old heap allocation is leaked and alive == 2. + struct Tracker { + int *alive; + // Construct: one new logical entity → alive++. + // Move: the new entity inherits the old's identity (no alive++), + // the old's alive is nulled so its destructor is a no-op. + // This makes alive == number of logically-live closures, so + // a leaked old closure shows up as alive > 1 after re-init. + explicit Tracker(int *a) : alive(a) { ++*alive; } + Tracker(const Tracker &o) : alive(o.alive) { ++*alive; } + Tracker(Tracker &&o) noexcept : alive(o.alive) { o.alive = nullptr; } + ~Tracker() { if (alive) --*alive; } + Tracker &operator=(const Tracker &) = delete; + void operator()(void *) {} + }; + + int alive = 0; + { + WScopedListener a; + a.init(&sig1, Tracker(&alive)); + QCOMPARE(alive, 1); + a.init(&sig2, Tracker(&alive)); + QCOMPARE(alive, 1); // old freed, new created — still one alive + } + QCOMPARE(alive, 0); +} + +void TestWScopedListener::listMultipleListenersAndClear() +{ + wl_signal sig; + wl_signal_init(&sig); + int a = 0, b = 0; + + WScopedListenerList list; + list.add(&sig, [&a](void *) { a++; }); + list.add(&sig, [&b](void *) { b++; }); + + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(a, 1); + QCOMPARE(b, 1); + + list.clear(); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(a, 1); // listeners detached + QCOMPARE(b, 1); +} + +void TestWScopedListener::listMovePreservesCallbacks() +{ + wl_signal sig; + wl_signal_init(&sig); + int count = 0; + + WScopedListenerList a; + a.add(&sig, [&count](void *) { count++; }); + + WScopedListenerList b(std::move(a)); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 1); // node re-linked at b's storage, still fires + + WScopedListenerList c; + c = std::move(b); + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(count, 2); +} + +void TestWScopedListener::emitOrderFollowsRegistration() +{ + wl_signal sig; + wl_signal_init(&sig); + QList order; + + WScopedListenerList list; + list.add(&sig, [&order](void *) { order << 1; }); + list.add(&sig, [&order](void *) { order << 2; }); + list.add(&sig, [&order](void *) { order << 3; }); + + wl_signal_emit_mutable(&sig, nullptr); + QCOMPARE(order, QList({1, 2, 3})); +} + +QTEST_GUILESS_MAIN(TestWScopedListener) + +#include "main.moc" diff --git a/waylib/tests/unit_tests/test_wwrappointer/CMakeLists.txt b/waylib/tests/unit_tests/test_wwrappointer/CMakeLists.txt deleted file mode 100644 index 1ae6b2d424..0000000000 --- a/waylib/tests/unit_tests/test_wwrappointer/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -find_package(Qt6 REQUIRED COMPONENTS Test) - -add_executable(test_wwrappointer wrapobject.h main.cpp) - -target_link_libraries(test_wwrappointer - PRIVATE - Waylib::WaylibServer - Qt::Test -) - -add_test(NAME test_wwrappointer COMMAND test_wwrappointer) - -set_property(TEST test_wwrappointer PROPERTY - ENVIRONMENT "QT_QPA_PLATFORM=offscreen" -) diff --git a/waylib/tests/unit_tests/test_wwrappointer/main.cpp b/waylib/tests/unit_tests/test_wwrappointer/main.cpp deleted file mode 100644 index 89ac33a838..0000000000 --- a/waylib/tests/unit_tests/test_wwrappointer/main.cpp +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. -// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only -#include "wrapobject.h" - -#include - -#include - -#define TEST_RW(wp, p) \ - do { \ - qint64 time1 = QDateTime::currentSecsSinceEpoch(); \ - (p)->object()->setValue(time1); \ - QVERIFY((wp)->object()->value() == time1); \ - qint64 time2 = QDateTime::currentSecsSinceEpoch(); \ - (wp)->object()->setValue(time2); \ - QVERIFY((p)->object()->value() == time2); \ - } while (0); - -#define TEST_ACCESS(wp, p) \ - QVERIFY((wp)); \ - QVERIFY((wp) == (p)); \ - QVERIFY((wp).data() == (p)); \ - QVERIFY((wp).get() == (p)); - -#define TEST_VALID(wp, qp) \ - wp->invalidate(); \ - QVERIFY(!wp); \ - QVERIFY(qp); - -class WrapPointerTest : public QObject -{ - Q_OBJECT -public: - WrapPointerTest(QObject *parent = nullptr) - : QObject(parent) - { - } - -private Q_SLOTS: - - void initTestCase() { } - - void testDirectGuardCase() - { - // Directly constructed - FakeWrapObject *p = new FakeWrapObject; - QScopedPointer sp(p); - QPointer qp(p); - WWrapPointer wp(p); - QVERIFY(p->object()); - TEST_ACCESS(wp, p); - TEST_RW(wp, p); - TEST_VALID(wp, qp); - } - - void testDelayedGuardCase() - { - // Delayed constructed - FakeWrapObject *p = new FakeWrapObject; - QScopedPointer sp(p); - QPointer qp(p); - WWrapPointer wp; - wp = p; // Assign operator - QVERIFY(p->object()); - TEST_ACCESS(wp, p); - TEST_RW(wp, p); - TEST_VALID(wp, qp); - } - - void testCopyAndMoveCase() - { - { - // Copy - FakeWrapObject *p = new FakeWrapObject; - QScopedPointer sp(p); - QPointer qp(p); - WWrapPointer wpr(p); - WWrapPointer wp(wpr); // Copy constructor - QVERIFY(p->object()); - TEST_ACCESS(wp, p); - TEST_ACCESS(wpr, p); - TEST_RW(wp, p); - TEST_RW(wpr, p); - TEST_VALID(wp, qp); - QVERIFY(!wpr); - } - { - // Copy assignment - FakeWrapObject *p = new FakeWrapObject; - QScopedPointer sp(p); - QPointer qp(p); - WWrapPointer wpr(p); - WWrapPointer wp = wpr; // Copy assignment - QVERIFY(p->object()); - TEST_ACCESS(wp, p); - TEST_ACCESS(wpr, p); - TEST_RW(wp, p); - TEST_RW(wpr, p); - TEST_VALID(wp, qp); - QVERIFY(!wpr); - } - { - // Move - FakeWrapObject *p = new FakeWrapObject; - QScopedPointer sp(p); - QPointer qp(p); - WWrapPointer wpr(p); - TEST_ACCESS(wpr, p); - WWrapPointer wp(std::move(wpr)); // Move constructor - QVERIFY(!wpr); - QVERIFY(p->object()); - TEST_ACCESS(wp, p); - TEST_RW(wp, p); - TEST_VALID(wp, qp); - } - { - // Move assignment - FakeWrapObject *p = new FakeWrapObject; - QScopedPointer sp(p); - QPointer qp(p); - WWrapPointer wpr(p); - TEST_ACCESS(wpr, p); - WWrapPointer wp = std::move(wpr); // Move assignment - QVERIFY(!wpr); - QVERIFY(p->object()); - TEST_ACCESS(wp, p); - TEST_RW(wp, p); - TEST_VALID(wp, qp); - } - } - - void testNullAssignment() - { - FakeWrapObject *p = new FakeWrapObject; - QScopedPointer sp(p); - QPointer qp(p); - WWrapPointer wp(p); - TEST_ACCESS(wp, p); - wp = nullptr; - QVERIFY(!wp); - } - - void cleanupTestCase() { } -}; - -QTEST_MAIN(WrapPointerTest) -#include "main.moc" diff --git a/waylib/tests/unit_tests/test_wwrappointer/wrapobject.h b/waylib/tests/unit_tests/test_wwrappointer/wrapobject.h deleted file mode 100644 index 86338e873a..0000000000 --- a/waylib/tests/unit_tests/test_wwrappointer/wrapobject.h +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (C) 2024 UnionTech Software Technology Co., Ltd. -// SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only -#pragma once - -#include - -class FakeObject -{ -public: - explicit FakeObject() = default; - virtual ~FakeObject() = default; - - qint64 value() const - { - return m_value; - } - - void setValue(qint64 value) - { - m_value = value; - } - -private: - qint64 m_value{ 0 }; -}; - -class FakeWrapObject : public QObject -{ - Q_OBJECT -public: - FakeWrapObject(QObject *parent = nullptr) - : QObject(parent) - , m_object(new FakeObject) - { - } - - ~FakeWrapObject() override - { - invalidate(); - } - - void invalidate() - { - delete m_object; - m_object = nullptr; - Q_EMIT aboutToBeInvalidated(); - } - - inline FakeObject *object() const - { - return m_object; - } - -Q_SIGNALS: - void aboutToBeInvalidated(); - -private: - FakeObject *m_object; -}; diff --git a/waylib/tools/CMakeLists.txt b/waylib/tools/CMakeLists.txt new file mode 100644 index 0000000000..fa389fb93e --- /dev/null +++ b/waylib/tools/CMakeLists.txt @@ -0,0 +1,83 @@ +project(qtwaylandscanner_waylib CXX) + +if (PROJECT_IS_TOP_LEVEL) + cmake_minimum_required(VERSION 3.16) + set(CMAKE_CXX_STANDARD 20) + find_package(Qt6 CONFIG REQUIRED Core) +endif() + +if(CMAKE_CROSSCOMPILING AND QTWAYLANDSCANNER_EXECUTABLE) + add_executable(qtwaylandscanner_waylib IMPORTED GLOBAL) + set_target_properties(qtwaylandscanner_waylib PROPERTIES IMPORTED_LOCATION ${QTWAYLANDSCANNER_EXECUTABLE}) +elseif(CMAKE_CROSSCOMPILING) + # search native tooling prefix + set(NATIVE_PREFIX "" CACHE STRING "CMAKE_PREFIX_PATH for native Qt libraries") + + message(STATUS "Building qtwaylandscanner_waylib against ${NATIVE_PREFIX}") + + include(ExternalProject) + ExternalProject_Add(native_qtwaylandscanner_waylib + SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} + CMAKE_ARGS -DECM_DIR=${ECM_DIR} -DCMAKE_PREFIX_PATH=${NATIVE_PREFIX} + -DCMAKE_INSTALL_PREFIX=${CMAKE_CURRENT_BINARY_DIR} + -DQT_MAJOR_VERSION=${QT_MAJOR_VERSION} + INSTALL_COMMAND "" + BUILD_BYPRODUCTS ${CMAKE_CURRENT_BINARY_DIR}/native_qtwaylandscanner_waylib-prefix/src/native_qtwaylandscanner_waylib-build/qtwaylandscanner_waylib + ) + add_executable(qtwaylandscanner_waylib IMPORTED GLOBAL) + add_dependencies(qtwaylandscanner_waylib native_qtwaylandscanner_waylib) + set_target_properties(qtwaylandscanner_waylib PROPERTIES IMPORTED_LOCATION + ${CMAKE_CURRENT_BINARY_DIR}/native_qtwaylandscanner_waylib-prefix/src/native_qtwaylandscanner_waylib-build/qtwaylandscanner_waylib) +else() + # host build + remove_definitions(-DQT_NO_CAST_FROM_ASCII) + add_executable(qtwaylandscanner_waylib ${CMAKE_CURRENT_SOURCE_DIR}/qtwaylandscanner.cpp) + target_link_libraries(qtwaylandscanner_waylib Qt6::Core) +endif() + +function(waylib_generate_qtwayland_server_protocol target) + # Parse arguments + set(options PRIVATE_CODE) + set(oneValueArgs PROTOCOL BASENAME PREFIX) + cmake_parse_arguments(ARGS "${options}" "${oneValueArgs}" "" ${ARGN}) + + if(ARGS_UNPARSED_ARGUMENTS) + message(FATAL_ERROR "Unknown keywords given to waylib_generate_qtwayland_server_protocol(): \"${ARGS_UNPARSED_ARGUMENTS}\"") + endif() + + set(_prefix "${ARGS_PREFIX}") + + find_package(PkgConfig) + get_filename_component(_infile ${ARGS_PROTOCOL} ABSOLUTE) + pkg_get_variable(WAYLAND_SCANNER wayland-scanner wayland_scanner) + set(server_header "${CMAKE_CURRENT_BINARY_DIR}/wayland-${ARGS_BASENAME}-server-protocol.h") + set(server_code "${CMAKE_CURRENT_BINARY_DIR}/wayland-${ARGS_BASENAME}-server-protocol.c") + execute_process(COMMAND ${WAYLAND_SCANNER} "server-header" ${_infile} ${server_header}) + execute_process(COMMAND ${WAYLAND_SCANNER} "private-code" ${_infile} ${server_code}) + + set(_header "${CMAKE_CURRENT_BINARY_DIR}/qwayland-server-${ARGS_BASENAME}.h") + set(_code "${CMAKE_CURRENT_BINARY_DIR}/qwayland-server-${ARGS_BASENAME}.cpp") + + set_source_files_properties(${server_header} ${server_code} ${_header} ${_code} GENERATED) + + add_custom_command(OUTPUT "${_header}" + COMMAND qtwaylandscanner_waylib server-header ${_infile} "" ${_prefix} > ${_header} + DEPENDS ${_infile} qtwaylandscanner_waylib VERBATIM) + + add_custom_command(OUTPUT "${_code}" + COMMAND qtwaylandscanner_waylib server-code ${_infile} "" ${_prefix} > ${_code} + DEPENDS ${_infile} ${_header} qtwaylandscanner_waylib VERBATIM) + + set_property(SOURCE ${_header} ${_code} PROPERTY SKIP_AUTOMOC ON) + + target_sources(${target} PRIVATE "${server_code}" "${_code}") + + set(_gen_target generate_protocols_${target}_${ARGS_BASENAME}) + + add_custom_target(${_gen_target} ALL + DEPENDS ${_header} ${_code} + ) + + add_dependencies(${target} ${_gen_target}) +endfunction() + diff --git a/waylib/tools/qtwaylandscanner.cpp b/waylib/tools/qtwaylandscanner.cpp new file mode 100644 index 0000000000..2751c9223e --- /dev/null +++ b/waylib/tools/qtwaylandscanner.cpp @@ -0,0 +1,1547 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include +#include +#include + +#include +#include + +class Scanner +{ +public: + explicit Scanner() { } + + ~Scanner() + { + delete m_xml; + } + + bool parseArguments(int argc, char **argv); + void printUsage(); + bool process(); + void printErrors(); + +private: + struct WaylandEnumEntry + { + QByteArray name; + QByteArray value; + QByteArray summary; + }; + + struct WaylandEnum + { + QByteArray name; + + std::vector entries; + }; + + struct WaylandArgument + { + QByteArray name; + QByteArray type; + QByteArray interface; + QByteArray summary; + bool allowNull; + }; + + struct WaylandEvent + { + bool request; + QByteArray name; + QByteArray type; + std::vector arguments; + }; + + struct WaylandInterface + { + QByteArray name; + int version; + + std::vector enums; + std::vector events; + std::vector requests; + }; + + bool isServerSide(); + bool parseOption(const QByteArray &str); + + QByteArray byteArrayValue(const QXmlStreamReader &xml, const char *name); + int intValue(const QXmlStreamReader &xml, const char *name, int defaultValue = 0); + bool boolValue(const QXmlStreamReader &xml, const char *name); + WaylandEvent readEvent(QXmlStreamReader &xml, bool request); + Scanner::WaylandEnum readEnum(QXmlStreamReader &xml); + Scanner::WaylandInterface readInterface(QXmlStreamReader &xml); + QByteArray waylandToCType(const QByteArray &waylandType, const QByteArray &interface); + QByteArray waylandToQtType(const QByteArray &waylandType, + const QByteArray &interface, + bool cStyleArray); + const Scanner::WaylandArgument *newIdArgument(const std::vector &arguments); + + void printEvent(const WaylandEvent &e, bool omitNames = false, bool withResource = false); + void printEventHandlerSignature(const WaylandEvent &e, + const char *interfaceName, + bool deepIndent = true); + void printEnums(const std::vector &enums); + + QByteArray stripInterfaceName(const QByteArray &name); + bool ignoreInterface(const QByteArray &name); + + enum Option + { + ClientHeader, + ServerHeader, + ClientCode, + ServerCode, + } m_option; + + QByteArray m_protocolName; + QByteArray m_protocolFilePath; + QByteArray m_scannerName; + QByteArray m_headerPath; + QByteArray m_prefix; + QList m_includes; + QXmlStreamReader *m_xml = nullptr; +}; + +bool Scanner::parseArguments(int argc, char **argv) +{ + QList args; + args.reserve(argc); + for (int i = 0; i < argc; ++i) + args << QByteArray(argv[i]); + + m_scannerName = args[0]; + + if (argc <= 2 || !parseOption(args[1])) + return false; + + m_protocolFilePath = args[2]; + + if (argc > 3 && !args[3].startsWith('-')) { + // legacy positional arguments + m_headerPath = args[3]; + if (argc == 5) + m_prefix = args[4]; + } else { + // --header-path= (14 characters) + // --prefix= (9 characters) + // --add-include= (14 characters) + for (int pos = 3; pos < argc; pos++) { + const QByteArray &option = args[pos]; + if (option.startsWith("--header-path=")) { + m_headerPath = option.mid(14); + } else if (option.startsWith("--prefix=")) { + m_prefix = option.mid(10); + } else if (option.startsWith("--add-include=")) { + auto include = option.mid(14); + if (!include.isEmpty()) + m_includes << include; + } else { + return false; + } + } + } + + return true; +} + +void Scanner::printUsage() +{ + fprintf(stderr, + "Usage: %s [client-header|server-header|client-code|server-code] specfile " + "[--header-path=] [--prefix=] [--add-include=]\n", + m_scannerName.constData()); +} + +bool Scanner::isServerSide() +{ + return m_option == ServerHeader || m_option == ServerCode; +} + +bool Scanner::parseOption(const QByteArray &str) +{ + if (str == "client-header") + m_option = ClientHeader; + else if (str == "server-header") + m_option = ServerHeader; + else if (str == "client-code") + m_option = ClientCode; + else if (str == "server-code") + m_option = ServerCode; + else + return false; + + return true; +} + +QByteArray Scanner::byteArrayValue(const QXmlStreamReader &xml, const char *name) +{ + if (xml.attributes().hasAttribute(name)) + return xml.attributes().value(name).toUtf8(); + return QByteArray(); +} + +int Scanner::intValue(const QXmlStreamReader &xml, const char *name, int defaultValue) +{ + bool ok; + int result = byteArrayValue(xml, name).toInt(&ok); + return ok ? result : defaultValue; +} + +bool Scanner::boolValue(const QXmlStreamReader &xml, const char *name) +{ + return byteArrayValue(xml, name) == "true"; +} + +Scanner::WaylandEvent Scanner::readEvent(QXmlStreamReader &xml, bool request) +{ + WaylandEvent event = { + .request = request, + .name = byteArrayValue(xml, "name"), + .type = byteArrayValue(xml, "type"), + .arguments = {}, + }; + while (xml.readNextStartElement()) { + if (xml.name() == QLatin1String("arg")) { + WaylandArgument argument = { + .name = byteArrayValue(xml, "name"), + .type = byteArrayValue(xml, "type"), + .interface = byteArrayValue(xml, "interface"), + .summary = byteArrayValue(xml, "summary"), + .allowNull = boolValue(xml, "allowNull"), + }; + event.arguments.push_back(std::move(argument)); + } + + xml.skipCurrentElement(); + } + return event; +} + +Scanner::WaylandEnum Scanner::readEnum(QXmlStreamReader &xml) +{ + WaylandEnum result = { + .name = byteArrayValue(xml, "name"), + .entries = {}, + }; + + while (xml.readNextStartElement()) { + if (xml.name() == QLatin1String("entry")) { + WaylandEnumEntry entry = { + .name = byteArrayValue(xml, "name"), + .value = byteArrayValue(xml, "value"), + .summary = byteArrayValue(xml, "summary"), + }; + result.entries.push_back(std::move(entry)); + } + + xml.skipCurrentElement(); + } + + return result; +} + +Scanner::WaylandInterface Scanner::readInterface(QXmlStreamReader &xml) +{ + WaylandInterface interface = { + .name = byteArrayValue(xml, "name"), + .version = intValue(xml, "version", 1), + .enums = {}, + .events = {}, + .requests = {}, + }; + + while (xml.readNextStartElement()) { + if (xml.name() == QLatin1String("event")) + interface.events.push_back(readEvent(xml, false)); + else if (xml.name() == QLatin1String("request")) + interface.requests.push_back(readEvent(xml, true)); + else if (xml.name() == QLatin1String("enum")) + interface.enums.push_back(readEnum(xml)); + else + xml.skipCurrentElement(); + } + + return interface; +} + +QByteArray Scanner::waylandToCType(const QByteArray &waylandType, const QByteArray &interface) +{ + if (waylandType == "string") + return "const char *"; + else if (waylandType == "int") + return "int32_t"; + else if (waylandType == "uint") + return "uint32_t"; + else if (waylandType == "fixed") + return "wl_fixed_t"; + else if (waylandType == "fd") + return "int32_t"; + else if (waylandType == "array") + return "wl_array *"; + else if (waylandType == "object" || waylandType == "new_id") { + if (isServerSide()) + return "struct ::wl_resource *"; + if (interface.isEmpty()) + return "struct ::wl_object *"; + return "struct ::" + interface + " *"; + } + return waylandType; +} + +QByteArray Scanner::waylandToQtType(const QByteArray &waylandType, + const QByteArray &interface, + bool cStyleArray) +{ + if (waylandType == "string") + return "const QString &"; + else if (waylandType == "array") + return cStyleArray ? "wl_array *" : "const QByteArray &"; + else + return waylandToCType(waylandType, interface); +} + +const Scanner::WaylandArgument *Scanner::newIdArgument( + const std::vector &arguments) +{ + for (const WaylandArgument &a : arguments) { + if (a.type == "new_id") + return &a; + } + return nullptr; +} + +void Scanner::printEvent(const WaylandEvent &e, bool omitNames, bool withResource) +{ + printf("%s(", e.name.constData()); + bool needsComma = false; + if (isServerSide()) { + if (e.request) { + printf("Resource *%s", omitNames ? "" : "resource"); + needsComma = true; + } else if (withResource) { + printf("struct ::wl_resource *%s", omitNames ? "" : "resource"); + needsComma = true; + } + } + for (const WaylandArgument &a : e.arguments) { + bool isNewId = a.type == "new_id"; + if (isNewId && !isServerSide() && (a.interface.isEmpty() != e.request)) + continue; + if (needsComma) + printf(", "); + needsComma = true; + if (isNewId) { + if (isServerSide()) { + if (e.request) { + printf("uint32_t"); + if (!omitNames) + printf(" %s", a.name.constData()); + continue; + } + } else { + if (e.request) { + printf("const struct ::wl_interface *%s, uint32_t%s", + omitNames ? "" : "interface", + omitNames ? "" : " version"); + continue; + } + } + } + + QByteArray qtType = waylandToQtType(a.type, a.interface, e.request == isServerSide()); + printf("%s%s%s", + qtType.constData(), + qtType.endsWith("&") || qtType.endsWith("*") ? "" : " ", + omitNames ? "" : a.name.constData()); + } + printf(")"); +} + +void Scanner::printEventHandlerSignature(const WaylandEvent &e, + const char *interfaceName, + bool deepIndent) +{ + const char *indent = deepIndent ? " " : ""; + printf("handle_%s(\n", e.name.constData()); + if (isServerSide()) { + printf(" %s::wl_client *client,\n", indent); + printf(" %sstruct wl_resource *resource", indent); + } else { + printf(" %svoid *data,\n", indent); + printf(" %sstruct ::%s *object", indent, interfaceName); + } + for (const WaylandArgument &a : e.arguments) { + printf(",\n"); + bool isNewId = a.type == "new_id"; + if (isServerSide() && isNewId) { + printf(" %suint32_t %s", indent, a.name.constData()); + } else { + QByteArray cType = waylandToCType(a.type, a.interface); + printf(" %s%s%s%s", + indent, + cType.constData(), + cType.endsWith("*") ? "" : " ", + a.name.constData()); + } + } + printf(")"); +} + +void Scanner::printEnums(const std::vector &enums) +{ + for (const WaylandEnum &e : enums) { + printf("\n"); + printf(" enum %s {\n", e.name.constData()); + for (const WaylandEnumEntry &entry : e.entries) { + printf(" %s_%s = %s,", + e.name.constData(), + entry.name.constData(), + entry.value.constData()); + if (!entry.summary.isNull()) + printf(" // %s", entry.summary.constData()); + printf("\n"); + } + printf(" };\n"); + } +} + +QByteArray Scanner::stripInterfaceName(const QByteArray &name) +{ + if (!m_prefix.isEmpty() && name.startsWith(m_prefix)) + return name.mid(m_prefix.size()); + if (name.startsWith("qt_") || name.startsWith("wl_")) + return name.mid(3); + + return name; +} + +bool Scanner::ignoreInterface(const QByteArray &name) +{ + return name == "wl_display" || (isServerSide() && name == "wl_registry"); +} + +bool Scanner::process() +{ + QFile file(m_protocolFilePath); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { + fprintf(stderr, "Unable to open file %s\n", m_protocolFilePath.constData()); + return false; + } + + m_xml = new QXmlStreamReader(&file); + if (!m_xml->readNextStartElement()) + return false; + + if (m_xml->name() != QLatin1String("protocol")) { + m_xml->raiseError(QStringLiteral("The file is not a wayland protocol file.")); + return false; + } + + m_protocolName = byteArrayValue(*m_xml, "name"); + + if (m_protocolName.isEmpty()) { + m_xml->raiseError(QStringLiteral("Missing protocol name.")); + return false; + } + + // We should convert - to _ so that the preprocessor wont generate code which will lead to + // unexpected behavior However, the wayland-scanner doesn't do so we will do the same for now + // QByteArray preProcessorProtocolName = QByteArray(m_protocolName).replace('-', '_').toUpper(); + QByteArray preProcessorProtocolName = QByteArray(m_protocolName).toUpper(); + + std::vector interfaces; + + while (m_xml->readNextStartElement()) { + if (m_xml->name() == QLatin1String("interface")) + interfaces.push_back(readInterface(*m_xml)); + else + m_xml->skipCurrentElement(); + } + + if (m_xml->hasError()) + return false; + + printf("// This file was generated by qtwaylandscanner\n"); + printf("// source file is %s\n\n", qPrintable(m_protocolFilePath)); + + for (auto b : std::as_const(m_includes)) + printf("#include %s\n", b.constData()); + + if (m_option == ServerHeader) { + QByteArray inclusionGuard = + QByteArray("QT_WAYLAND_SERVER_") + preProcessorProtocolName.constData(); + printf("#ifndef %s\n", inclusionGuard.constData()); + printf("#define %s\n", inclusionGuard.constData()); + printf("\n"); + printf("#include \"wayland-server-core.h\"\n"); + if (m_headerPath.isEmpty()) + printf("#include \"wayland-%s-server-protocol.h\"\n", + QByteArray(m_protocolName).replace('_', '-').constData()); + else + printf("#include <%s/wayland-%s-server-protocol.h>\n", + m_headerPath.constData(), + QByteArray(m_protocolName).replace('_', '-').constData()); + printf("#include \n"); + printf("#include \n"); + printf("#include \n"); + + printf("\n"); + printf("#include \n"); + + printf("\n"); + printf("#ifndef WAYLAND_VERSION_CHECK\n"); + printf("#define WAYLAND_VERSION_CHECK(major, minor, micro) \\\n"); + printf(" ((WAYLAND_VERSION_MAJOR > (major)) || \\\n"); + printf(" (WAYLAND_VERSION_MAJOR == (major) && WAYLAND_VERSION_MINOR > (minor)) || \\\n"); + printf(" (WAYLAND_VERSION_MAJOR == (major) && WAYLAND_VERSION_MINOR == (minor) && " + "WAYLAND_VERSION_MICRO >= (micro)))\n"); + printf("#endif\n"); + + printf("\n"); + printf("QT_BEGIN_NAMESPACE\n"); + printf("QT_WARNING_PUSH\n"); + printf("QT_WARNING_DISABLE_GCC(\"-Wmissing-field-initializers\")\n"); + printf("QT_WARNING_DISABLE_CLANG(\"-Wmissing-field-initializers\")\n"); + printf("QT_WARNING_DISABLE_GCC(\"-Wreorder\")\n"); + printf("QT_WARNING_DISABLE_CLANG(\"-Wreorder\")\n"); + QByteArray serverExport; + if (m_headerPath.size()) { + serverExport = QByteArray("Q_WAYLAND_SERVER_") + preProcessorProtocolName + "_EXPORT"; + printf("\n"); + printf("#if !defined(%s)\n", serverExport.constData()); + printf("# if defined(QT_SHARED)\n"); + printf("# define %s Q_DECL_EXPORT\n", serverExport.constData()); + printf("# else\n"); + printf("# define %s\n", serverExport.constData()); + printf("# endif\n"); + printf("#endif\n"); + } + printf("\n"); + printf("namespace QtWaylandServer {\n"); + + bool needsNewLine = false; + for (const WaylandInterface &interface : interfaces) { + + if (ignoreInterface(interface.name)) + continue; + + if (needsNewLine) + printf("\n"); + needsNewLine = true; + + const char *interfaceName = interface.name.constData(); + + QByteArray stripped = stripInterfaceName(interface.name); + const char *interfaceNameStripped = stripped.constData(); + + printf(" class %s %s\n {\n", serverExport.constData(), interfaceName); + printf(" public:\n"); + printf(" %s(struct ::wl_client *client, int id, int version);\n", interfaceName); + printf(" %s(struct ::wl_display *display, int version);\n", interfaceName); + printf(" %s(struct ::wl_resource *resource);\n", interfaceName); + printf(" %s();\n", interfaceName); + printf("\n"); + printf(" virtual ~%s();\n", interfaceName); + printf("\n"); + printf(" class Resource\n"); + printf(" {\n"); + printf(" public:\n"); + printf(" Resource() : %s_object(nullptr), handle(nullptr) {}\n", + interfaceNameStripped); + printf(" virtual ~Resource() {}\n"); + printf("\n"); + printf(" %s *%s_object;\n", interfaceName, interfaceNameStripped); + printf(" %s *object() { return %s_object; } \n", + interfaceName, + interfaceNameStripped); + printf(" struct ::wl_resource *handle;\n"); + printf("\n"); + printf(" struct ::wl_client *client() const { return " + "wl_resource_get_client(handle); }\n"); + printf(" int version() const { return wl_resource_get_version(handle); }\n"); + printf("\n"); + printf(" static Resource *fromResource(struct ::wl_resource *resource);\n"); + printf(" };\n"); + printf("\n"); + printf(" void init(struct ::wl_client *client, int id, int version);\n"); + printf(" void init(struct ::wl_display *display, int version);\n"); + printf(" void init(struct ::wl_resource *resource);\n"); + printf("\n"); + printf(" Resource *add(struct ::wl_client *client, int version);\n"); + printf(" Resource *add(struct ::wl_client *client, int id, int version);\n"); + printf(" Resource *add(struct wl_list *resource_list, struct ::wl_client " + "*client, int id, int version);\n"); + printf("\n"); + printf(" Resource *resource() { return m_resource; }\n"); + printf(" const Resource *resource() const { return m_resource; }\n"); + printf("\n"); + printf(" const QMultiMap &resourceMap() const { " + "return m_resource_map; }\n"); + printf("\n"); + printf(" bool isGlobalRemoved() const { return m_globalRemovedEvent; }\n"); + printf(" void globalRemove();\n"); + printf("\n"); + printf(" bool isGlobal() const { return m_global != nullptr; }\n"); + printf(" bool isResource() const { return m_resource != nullptr; }\n"); + printf("\n"); + printf(" static const struct ::wl_interface *interface();\n"); + printf(" static QByteArrayView interfaceName() { return interface()->name; }\n"); + printf(" static int interfaceVersion() { return interface()->version; }\n"); + printf("\n"); + + printEnums(interface.enums); + + bool hasEvents = !interface.events.empty(); + + if (hasEvents) { + printf("\n"); + for (const WaylandEvent &e : interface.events) { + printf(" void send_"); + printEvent(e); + printf(";\n"); + printf(" void send_"); + printEvent(e, false, true); + printf(";\n"); + } + } + + printf(" protected:\n"); + printf(" struct ::wl_global *m_global;\n"); + printf("\n"); + + printf(" protected:\n"); + printf(" virtual Resource *allocate();\n"); + printf("\n"); + printf(" virtual void destroy_global();\n"); + printf("\n"); + printf(" virtual void bind_resource(Resource *resource);\n"); + printf(" virtual void destroy_resource(Resource *resource);\n"); + + bool hasRequests = !interface.requests.empty(); + + if (hasRequests) { + printf("\n"); + for (const WaylandEvent &e : interface.requests) { + printf(" virtual void "); + printEvent(e); + printf(";\n"); + } + } + + printf("\n"); + printf(" private:\n"); + printf(" static void bind_func(struct ::wl_client *client, void *data, uint32_t " + "version, uint32_t id);\n"); + printf(" static void destroy_func(struct ::wl_resource *client_resource);\n"); + printf(" static void display_destroy_func(struct ::wl_listener *listener, void " + "*data);\n"); + printf(" static int deferred_destroy_global_func(void *data);\n"); + printf("\n"); + printf( + " Resource *bind(struct ::wl_client *client, uint32_t id, int version);\n"); + printf(" Resource *bind(struct ::wl_resource *handle);\n"); + + if (hasRequests) { + printf("\n"); + printf(" static const struct ::%s_interface m_%s_interface;\n", + interfaceName, + interfaceName); + + printf("\n"); + for (const WaylandEvent &e : interface.requests) { + printf(" static void "); + + printEventHandlerSignature(e, interfaceName); + printf(";\n"); + } + } + + printf("\n"); + printf(" QMultiMap m_resource_map;\n"); + printf(" Resource *m_resource;\n"); + printf(" struct ::wl_display *m_display;\n"); + printf(" struct wl_event_source *m_globalRemovedEvent;\n"); + printf(" struct DisplayDestroyedListener : ::wl_listener {\n"); + printf(" %s *parent;\n", interfaceName); + printf(" };\n"); + printf(" DisplayDestroyedListener m_displayDestroyedListener;\n"); + printf(" };\n"); + } + + printf("}\n"); + printf("\n"); + printf("QT_WARNING_POP\n"); + printf("QT_END_NAMESPACE\n"); + printf("\n"); + printf("#endif\n"); + } + + if (m_option == ServerCode) { + if (m_headerPath.isEmpty()) + printf("#include \"qwayland-server-%s.h\"\n", + QByteArray(m_protocolName).replace('_', '-').constData()); + else + printf("#include <%s/qwayland-server-%s.h>\n", + m_headerPath.constData(), + QByteArray(m_protocolName).replace('_', '-').constData()); + printf("\n"); + printf("QT_BEGIN_NAMESPACE\n"); + printf("QT_WARNING_PUSH\n"); + printf("QT_WARNING_DISABLE_GCC(\"-Wmissing-field-initializers\")\n"); + printf("QT_WARNING_DISABLE_GCC(\"-Wreorder\")\n"); + printf("QT_WARNING_DISABLE_CLANG(\"-Wreorder\")\n"); + printf("\n"); + printf("namespace QtWaylandServer {\n"); + + bool needsNewLine = false; + + for (const WaylandInterface &interface : interfaces) { + + if (ignoreInterface(interface.name)) + continue; + + if (needsNewLine) + printf("\n"); + + needsNewLine = true; + + const char *interfaceName = interface.name.constData(); + + QByteArray stripped = stripInterfaceName(interface.name); + const char *interfaceNameStripped = stripped.constData(); + + printf("\n"); + printf(" int %s::deferred_destroy_global_func(void *data) {\n", interfaceName); + printf(" auto object = static_cast<%s *>(data);\n", interfaceName); + printf(" wl_global_destroy(object->m_global);\n"); + printf(" object->m_global = nullptr;\n"); + printf(" wl_event_source_remove(object->m_globalRemovedEvent);\n"); + printf(" object->m_globalRemovedEvent = nullptr;\n"); + printf(" wl_list_remove(&object->m_displayDestroyedListener.link);\n"); + printf(" object->destroy_global();\n"); + printf(" return 0;\n"); + printf(" }\n"); + printf("\n"); + + printf(" %s::%s(struct ::wl_client *client, int id, int version)\n", + interfaceName, + interfaceName); + printf(" : m_resource_map()\n"); + printf(" , m_resource(nullptr)\n"); + printf(" , m_global(nullptr)\n"); + printf(" , m_display(nullptr)\n"); + printf(" , m_globalRemovedEvent(nullptr)\n"); + printf(" {\n"); + printf(" init(client, id, version);\n"); + printf(" }\n"); + printf("\n"); + + printf(" %s::%s(struct ::wl_display *display, int version)\n", + interfaceName, + interfaceName); + printf(" : m_resource_map()\n"); + printf(" , m_resource(nullptr)\n"); + printf(" , m_global(nullptr)\n"); + printf(" , m_display(nullptr)\n"); + printf(" , m_globalRemovedEvent(nullptr)\n"); + printf(" {\n"); + printf(" init(display, version);\n"); + printf(" }\n"); + printf("\n"); + + printf(" %s::%s(struct ::wl_resource *resource)\n", interfaceName, interfaceName); + printf(" : m_resource_map()\n"); + printf(" , m_resource(nullptr)\n"); + printf(" , m_global(nullptr)\n"); + printf(" , m_display(nullptr)\n"); + printf(" , m_globalRemovedEvent(nullptr)\n"); + printf(" {\n"); + printf(" init(resource);\n"); + printf(" }\n"); + printf("\n"); + + printf(" %s::%s()\n", interfaceName, interfaceName); + printf(" : m_resource_map()\n"); + printf(" , m_resource(nullptr)\n"); + printf(" , m_global(nullptr)\n"); + printf(" , m_display(nullptr)\n"); + printf(" , m_globalRemovedEvent(nullptr)\n"); + printf(" {\n"); + printf(" }\n"); + printf("\n"); + + printf(" %s::~%s()\n", interfaceName, interfaceName); + printf(" {\n"); + printf(" for (auto resource : std::as_const(m_resource_map))\n"); + printf(" resource->%s_object = nullptr;\n", interfaceNameStripped); + printf("\n"); + printf(" if (m_resource)\n"); + printf(" m_resource->%s_object = nullptr;\n", interfaceNameStripped); + printf("\n"); + printf(" if (m_global) {\n"); + printf(" if (m_globalRemovedEvent)\n"); + printf(" wl_event_source_remove(m_globalRemovedEvent);\n"); + printf(" wl_global_destroy(m_global);\n"); + printf(" wl_list_remove(&m_displayDestroyedListener.link);\n"); + printf(" }\n"); + printf(" }\n"); + printf("\n"); + + printf(" void %s::init(struct ::wl_client *client, int id, int version)\n", + interfaceName); + printf(" {\n"); + printf(" m_resource = bind(client, id, version);\n"); + printf(" }\n"); + printf("\n"); + + printf(" void %s::init(struct ::wl_resource *resource)\n", interfaceName); + printf(" {\n"); + printf(" m_resource = bind(resource);\n"); + printf(" }\n"); + printf("\n"); + + printf(" %s::Resource *%s::add(struct ::wl_client *client, int version)\n", + interfaceName, + interfaceName); + printf(" {\n"); + printf(" Resource *resource = bind(client, 0, version);\n"); + printf(" m_resource_map.insert(client, resource);\n"); + printf(" return resource;\n"); + printf(" }\n"); + printf("\n"); + + printf(" %s::Resource *%s::add(struct ::wl_client *client, int id, int version)\n", + interfaceName, + interfaceName); + printf(" {\n"); + printf(" Resource *resource = bind(client, id, version);\n"); + printf(" m_resource_map.insert(client, resource);\n"); + printf(" return resource;\n"); + printf(" }\n"); + printf("\n"); + + printf(" void %s::init(struct ::wl_display *display, int version)\n", interfaceName); + printf(" {\n"); + printf(" m_display = display;\n"); + printf(" m_global = wl_global_create(display, &::%s_interface, version, this, " + "bind_func);\n", + interfaceName); + printf(" m_displayDestroyedListener.notify = %s::display_destroy_func;\n", + interfaceName); + printf(" m_displayDestroyedListener.parent = this;\n"); + printf( + " wl_display_add_destroy_listener(display, &m_displayDestroyedListener);\n"); + printf(" }\n"); + printf("\n"); + + printf(" const struct wl_interface *%s::interface()\n", interfaceName); + printf(" {\n"); + printf(" return &::%s_interface;\n", interfaceName); + printf(" }\n"); + printf("\n"); + + printf(" %s::Resource *%s::allocate()\n", + interfaceName, + interfaceName); + printf(" {\n"); + printf(" return new Resource;\n"); + printf(" }\n"); + printf("\n"); + + printf(" void %s::destroy_global()\n", interfaceName); + printf(" {\n"); + printf(" }\n"); + printf("\n"); + + printf(" void %s::bind_resource(Resource *)\n", + interfaceName); + printf(" {\n"); + printf(" }\n"); + printf("\n"); + + printf(" void %s::destroy_resource(Resource *)\n", + interfaceName); + printf(" {\n"); + printf(" }\n"); + printf("\n"); + + printf(" void %s::bind_func(struct ::wl_client *client, void *data, uint32_t " + "version, uint32_t id)\n", + interfaceName); + printf(" {\n"); + printf(" %s *that = static_cast<%s *>(data);\n", interfaceName, interfaceName); + printf(" that->add(client, id, version);\n"); + printf(" }\n"); + printf("\n"); + + printf( + " void %s::display_destroy_func(struct ::wl_listener *listener, void *data)\n", + interfaceName); + printf(" {\n"); + printf(" Q_UNUSED(data);\n"); + printf(" %s *that = static_cast<%s::DisplayDestroyedListener " + "*>(listener)->parent;\n", + interfaceName, + interfaceName); + printf(" that->m_global = nullptr;\n"); + printf(" that->m_globalRemovedEvent = nullptr;\n"); + printf(" }\n"); + printf("\n"); + + printf(" void %s::destroy_func(struct ::wl_resource *client_resource)\n", + interfaceName); + printf(" {\n"); + printf(" Resource *resource = Resource::fromResource(client_resource);\n"); + printf(" Q_ASSERT(resource);\n"); + printf(" %s *that = resource->%s_object;\n", + interfaceName, + interfaceNameStripped); + printf(" if (Q_LIKELY(that)) {\n"); + printf(" that->m_resource_map.remove(resource->client(), resource);\n"); + printf(" that->destroy_resource(resource);\n"); + printf("\n"); + printf(" that = resource->%s_object;\n", interfaceNameStripped); + printf(" if (that && that->m_resource == resource)\n"); + printf(" that->m_resource = nullptr;\n"); + printf(" }\n"); + printf(" delete resource;\n"); + printf(" }\n"); + printf("\n"); + + // Removing a global is racey. Announce removal, and then only perform internal cleanup + // after a delay See https://gitlab.freedesktop.org/wayland/wayland/issues/10 + printf("\n"); + printf(" void %s::globalRemove()\n", interfaceName); + printf(" {\n"); + printf(" if (!m_global || m_globalRemovedEvent)\n"); + printf(" return;\n"); + printf("\n"); + printf(" wl_global_remove(m_global);\n"); + printf("\n"); + printf(" struct wl_event_loop *event_loop = " + "wl_display_get_event_loop(m_display);\n"); + printf(" m_globalRemovedEvent = wl_event_loop_add_timer(event_loop, " + "deferred_destroy_global_func, this);\n"); + printf(" wl_event_source_timer_update(m_globalRemovedEvent, 5000);\n"); + printf(" }\n"); + printf("\n"); + + bool hasRequests = !interface.requests.empty(); + + QByteArray interfaceMember = + hasRequests ? "&m_" + interface.name + "_interface" : QByteArray("nullptr"); + + // We should consider changing bind so that it doesn't special case id == 0 + // and use function overloading instead. Jan do you have a lot of code dependent on this + // behavior? + printf(" %s::Resource *%s::bind(struct ::wl_client *client, uint32_t id, int " + "version)\n", + interfaceName, + interfaceName); + printf(" {\n"); + printf(" Q_ASSERT_X(!wl_client_get_object(client, id), \"QWaylandObject bind\", " + "QStringLiteral(\"binding to object %%1 more than " + "once\").arg(id).toLocal8Bit().constData());\n"); + printf(" struct ::wl_resource *handle = wl_resource_create(client, " + "&::%s_interface, version, id);\n", + interfaceName); + printf(" return bind(handle);\n"); + printf(" }\n"); + printf("\n"); + + printf(" %s::Resource *%s::bind(struct ::wl_resource *handle)\n", + interfaceName, + interfaceName); + printf(" {\n"); + printf(" Resource *resource = allocate();\n"); + printf(" resource->%s_object = this;\n", interfaceNameStripped); + printf("\n"); + printf(" wl_resource_set_implementation(handle, %s, resource, destroy_func);", + interfaceMember.constData()); + printf("\n"); + printf(" resource->handle = handle;\n"); + printf(" bind_resource(resource);\n"); + printf(" return resource;\n"); + printf(" }\n"); + + printf(" %s::Resource *%s::Resource::fromResource(struct ::wl_resource *resource)\n", + interfaceName, + interfaceName); + printf(" {\n"); + printf(" if (Q_UNLIKELY(!resource))\n"); + printf(" return nullptr;\n"); + printf(" if (wl_resource_instance_of(resource, &::%s_interface, %s))\n", + interfaceName, + interfaceMember.constData()); + printf(" return static_cast(wl_resource_get_user_data(resource));\n"); + printf(" return nullptr;\n"); + printf(" }\n"); + + if (hasRequests) { + printf("\n"); + printf(" const struct ::%s_interface %s::m_%s_interface = {", + interfaceName, + interfaceName, + interfaceName); + bool needsComma = false; + for (const WaylandEvent &e : interface.requests) { + if (needsComma) + printf(","); + needsComma = true; + printf("\n"); + printf(" %s::handle_%s", interfaceName, e.name.constData()); + } + printf("\n"); + printf(" };\n"); + + for (const WaylandEvent &e : interface.requests) { + printf("\n"); + printf(" void %s::", interfaceName); + printEvent(e); + printf("\n"); + printf(" {\n"); + if (isServerSide()) { + if (e.request) { + printf(" Q_UNUSED(resource);\n"); + } + } + for (const WaylandArgument &a : e.arguments) { + bool isNewId = a.type == "new_id"; + if (isServerSide() && isNewId && e.request) + printf(" Q_UNUSED(%s);\n", a.name.constData()); + else if (!isNewId || !isServerSide() || !e.request) + printf(" Q_UNUSED(%s);\n", a.name.constData()); + } + printf(" }\n"); + } + printf("\n"); + + for (const WaylandEvent &e : interface.requests) { + printf("\n"); + printf(" void %s::", interfaceName); + printEventHandlerSignature(e, interfaceName, false); + printf("\n"); + printf(" {\n"); + printf(" Q_UNUSED(client);\n"); + printf(" Resource *qResource = Resource::fromResource(resource);\n"); + printf(" if (Q_UNLIKELY(!qResource->%s_object)) {\n", interfaceNameStripped); + for (const WaylandArgument &a : e.arguments) { + if (a.type == QByteArrayLiteral("fd")) + printf(" close(%s);\n", a.name.constData()); + } + if (e.type == "destructor") + printf(" wl_resource_destroy(resource);\n"); + printf(" return;\n"); + printf(" }\n"); + printf(" static_cast<%s *>(qResource->%s_object)->%s(\n", + interfaceName, + interfaceNameStripped, + e.name.constData()); + printf(" qResource"); + for (const WaylandArgument &a : e.arguments) { + printf(",\n"); + QByteArray cType = waylandToCType(a.type, a.interface); + QByteArray qtType = waylandToQtType(a.type, a.interface, e.request); + const char *argumentName = a.name.constData(); + if (cType == qtType) + printf(" %s", argumentName); + else if (a.type == "string") + printf(" QString::fromUtf8(%s)", argumentName); + } + printf(");\n"); + printf(" }\n"); + } + } + + for (const WaylandEvent &e : interface.events) { + printf("\n"); + printf(" void %s::send_", interfaceName); + printEvent(e); + printf("\n"); + printf(" {\n"); + printf(" Q_ASSERT_X(m_resource, \"%s::%s\", \"Uninitialised resource\");\n", + interfaceName, + e.name.constData()); + printf(" if (Q_UNLIKELY(!m_resource)) {\n"); + printf(" qWarning(\"could not call %s::%s as it's not initialised\");\n", + interfaceName, + e.name.constData()); + printf(" return;\n"); + printf(" }\n"); + printf(" send_%s(\n", e.name.constData()); + printf(" m_resource->handle"); + for (const WaylandArgument &a : e.arguments) { + printf(",\n"); + printf(" %s", a.name.constData()); + } + printf(");\n"); + printf(" }\n"); + printf("\n"); + + printf(" void %s::send_", interfaceName); + printEvent(e, false, true); + printf("\n"); + printf(" {\n"); + + for (const WaylandArgument &a : e.arguments) { + if (a.type != "array") + continue; + QByteArray array = a.name + "_data"; + const char *arrayName = array.constData(); + const char *variableName = a.name.constData(); + printf(" struct wl_array %s;\n", arrayName); + printf(" %s.size = %s.size();\n", arrayName, variableName); + printf(" %s.data = static_cast(const_cast(%s.constData()));\n", + arrayName, + variableName); + printf(" %s.alloc = 0;\n", arrayName); + printf("\n"); + } + + printf(" %s_send_%s(\n", interfaceName, e.name.constData()); + printf(" resource"); + + for (const WaylandArgument &a : e.arguments) { + printf(",\n"); + QByteArray cType = waylandToCType(a.type, a.interface); + QByteArray qtType = waylandToQtType(a.type, a.interface, e.request); + if (a.type == "string") + printf(" %s.toUtf8().constData()", a.name.constData()); + else if (a.type == "array") + printf(" &%s_data", a.name.constData()); + else if (cType == qtType) + printf(" %s", a.name.constData()); + } + + printf(");\n"); + printf(" }\n"); + printf("\n"); + } + } + printf("}\n"); + printf("\n"); + printf("QT_WARNING_POP\n"); + printf("QT_END_NAMESPACE\n"); + } + + if (m_option == ClientHeader) { + QByteArray inclusionGuard = + QByteArray("QT_WAYLAND_") + preProcessorProtocolName.constData(); + printf("#ifndef %s\n", inclusionGuard.constData()); + printf("#define %s\n", inclusionGuard.constData()); + printf("\n"); + if (m_headerPath.isEmpty()) + printf("#include \"wayland-%s-client-protocol.h\"\n", + QByteArray(m_protocolName).replace('_', '-').constData()); + else + printf("#include <%s/wayland-%s-client-protocol.h>\n", + m_headerPath.constData(), + QByteArray(m_protocolName).replace('_', '-').constData()); + printf("#include \n"); + printf("#include \n"); + printf("\n"); + printf("struct wl_registry;\n"); + printf("\n"); + printf("QT_BEGIN_NAMESPACE\n"); + printf("QT_WARNING_PUSH\n"); + printf("QT_WARNING_DISABLE_GCC(\"-Wmissing-field-initializers\")\n"); + printf("QT_WARNING_DISABLE_GCC(\"-Wreorder\")\n"); + printf("QT_WARNING_DISABLE_CLANG(\"-Wreorder\")\n"); + + QByteArray clientExport; + + if (m_headerPath.size()) { + clientExport = QByteArray("Q_WAYLAND_CLIENT_") + preProcessorProtocolName + "_EXPORT"; + printf("\n"); + printf("#if !defined(%s)\n", clientExport.constData()); + printf("# if defined(QT_SHARED)\n"); + printf("# define %s Q_DECL_EXPORT\n", clientExport.constData()); + printf("# else\n"); + printf("# define %s\n", clientExport.constData()); + printf("# endif\n"); + printf("#endif\n"); + } + printf("\n"); + printf("namespace QtWayland {\n"); + + bool needsNewLine = false; + for (const WaylandInterface &interface : interfaces) { + + if (ignoreInterface(interface.name)) + continue; + + if (needsNewLine) + printf("\n"); + needsNewLine = true; + + const char *interfaceName = interface.name.constData(); + + printf(" class %s %s\n {\n", clientExport.constData(), interfaceName); + printf(" public:\n"); + printf(" %s(struct ::wl_registry *registry, int id, int version);\n", + interfaceName); + printf(" %s(struct ::%s *object);\n", interfaceName, interfaceName); + printf(" %s();\n", interfaceName); + printf("\n"); + printf(" virtual ~%s();\n", interfaceName); + printf("\n"); + printf(" void init(struct ::wl_registry *registry, int id, int version);\n"); + printf(" void init(struct ::%s *object);\n", interfaceName); + printf("\n"); + printf(" struct ::%s *object() { return m_%s; }\n", + interfaceName, + interfaceName); + printf(" const struct ::%s *object() const { return m_%s; }\n", + interfaceName, + interfaceName); + printf(" static %s *fromObject(struct ::%s *object);\n", + interfaceName, + interfaceName); + printf("\n"); + printf(" bool isInitialized() const;\n"); + printf("\n"); + printf(" static const struct ::wl_interface *interface();\n"); + + printEnums(interface.enums); + + if (!interface.requests.empty()) { + printf("\n"); + for (const WaylandEvent &e : interface.requests) { + const WaylandArgument *new_id = newIdArgument(e.arguments); + QByteArray new_id_str = "void "; + if (new_id) { + if (new_id->interface.isEmpty()) + new_id_str = "void *"; + else + new_id_str = "struct ::" + new_id->interface + " *"; + } + printf(" %s", new_id_str.constData()); + printEvent(e); + printf(";\n"); + } + } + + bool hasEvents = !interface.events.empty(); + + if (hasEvents) { + printf("\n"); + printf(" protected:\n"); + for (const WaylandEvent &e : interface.events) { + printf(" virtual void "); + printEvent(e); + printf(";\n"); + } + } + + printf("\n"); + printf(" private:\n"); + if (hasEvents) { + printf(" void init_listener();\n"); + printf(" static const struct %s_listener m_%s_listener;\n", + interfaceName, + interfaceName); + for (const WaylandEvent &e : interface.events) { + printf(" static void "); + + printEventHandlerSignature(e, interfaceName); + printf(";\n"); + } + } + printf(" struct ::%s *m_%s;\n", interfaceName, interfaceName); + printf(" };\n"); + } + printf("}\n"); + printf("\n"); + printf("QT_WARNING_POP\n"); + printf("QT_END_NAMESPACE\n"); + printf("\n"); + printf("#endif\n"); + } + + if (m_option == ClientCode) { + if (m_headerPath.isEmpty()) + printf("#include \"qwayland-%s.h\"\n", + QByteArray(m_protocolName).replace('_', '-').constData()); + else + printf("#include <%s/qwayland-%s.h>\n", + m_headerPath.constData(), + QByteArray(m_protocolName).replace('_', '-').constData()); + printf("\n"); + printf("QT_BEGIN_NAMESPACE\n"); + printf("QT_WARNING_PUSH\n"); + printf("QT_WARNING_DISABLE_GCC(\"-Wmissing-field-initializers\")\n"); + printf("QT_WARNING_DISABLE_GCC(\"-Wreorder\")\n"); + printf("QT_WARNING_DISABLE_CLANG(\"-Wreorder\")\n"); + printf("\n"); + printf("namespace QtWayland {\n"); + printf("\n"); + + // wl_registry_bind is part of the protocol, so we can't use that... instead we use core + // libwayland API to do the same thing a wayland-scanner generated wl_registry_bind would. + printf("static inline void *wlRegistryBind(struct ::wl_registry *registry, uint32_t name, " + "const struct ::wl_interface *interface, uint32_t version)\n"); + printf("{\n"); + printf(" const uint32_t bindOpCode = 0;\n"); + printf("#if (WAYLAND_VERSION_MAJOR == 1 && WAYLAND_VERSION_MINOR > 10) || " + "WAYLAND_VERSION_MAJOR > 1\n"); + printf(" return (void *) wl_proxy_marshal_constructor_versioned((struct wl_proxy *) " + "registry,\n"); + printf( + " bindOpCode, interface, version, name, interface->name, version, nullptr);\n"); + printf("#else\n"); + printf(" return (void *) wl_proxy_marshal_constructor((struct wl_proxy *) registry,\n"); + printf(" bindOpCode, interface, name, interface->name, version, nullptr);\n"); + printf("#endif\n"); + printf("}\n"); + printf("\n"); + + bool needsNewLine = false; + for (const WaylandInterface &interface : interfaces) { + + if (ignoreInterface(interface.name)) + continue; + + if (needsNewLine) + printf("\n"); + needsNewLine = true; + + const char *interfaceName = interface.name.constData(); + + bool hasEvents = !interface.events.empty(); + + printf(" %s::%s(struct ::wl_registry *registry, int id, int version)\n", + interfaceName, + interfaceName); + printf(" {\n"); + printf(" init(registry, id, version);\n"); + printf(" }\n"); + printf("\n"); + + printf(" %s::%s(struct ::%s *obj)\n", interfaceName, interfaceName, interfaceName); + printf(" : m_%s(obj)\n", interfaceName); + printf(" {\n"); + if (hasEvents) + printf(" init_listener();\n"); + printf(" }\n"); + printf("\n"); + + printf(" %s::%s()\n", interfaceName, interfaceName); + printf(" : m_%s(nullptr)\n", interfaceName); + printf(" {\n"); + printf(" }\n"); + printf("\n"); + + printf(" %s::~%s()\n", interfaceName, interfaceName); + printf(" {\n"); + printf(" }\n"); + printf("\n"); + + printf(" void %s::init(struct ::wl_registry *registry, int id, int version)\n", + interfaceName); + printf(" {\n"); + printf(" m_%s = static_cast(wlRegistryBind(registry, id, " + "&%s_interface, version));\n", + interfaceName, + interfaceName, + interfaceName); + if (hasEvents) + printf(" init_listener();\n"); + printf(" }\n"); + printf("\n"); + + printf(" void %s::init(struct ::%s *obj)\n", interfaceName, interfaceName); + printf(" {\n"); + printf(" m_%s = obj;\n", interfaceName); + if (hasEvents) + printf(" init_listener();\n"); + printf(" }\n"); + printf("\n"); + + printf(" %s *%s::fromObject(struct ::%s *object)\n", + interfaceName, + interfaceName, + interfaceName); + printf(" {\n"); + if (hasEvents) { + printf(" if (wl_proxy_get_listener((struct ::wl_proxy *)object) != (void " + "*)&m_%s_listener)\n", + interfaceName); + printf(" return nullptr;\n"); + } + printf(" return static_cast<%s *>(%s_get_user_data(object));\n", + interfaceName, + interfaceName); + printf(" }\n"); + printf("\n"); + + printf(" bool %s::isInitialized() const\n", interfaceName); + printf(" {\n"); + printf(" return m_%s != nullptr;\n", interfaceName); + printf(" }\n"); + printf("\n"); + + printf(" const struct wl_interface *%s::interface()\n", interfaceName); + printf(" {\n"); + printf(" return &::%s_interface;\n", interfaceName); + printf(" }\n"); + + for (const WaylandEvent &e : interface.requests) { + printf("\n"); + const WaylandArgument *new_id = newIdArgument(e.arguments); + QByteArray new_id_str = "void "; + if (new_id) { + if (new_id->interface.isEmpty()) + new_id_str = "void *"; + else + new_id_str = "struct ::" + new_id->interface + " *"; + } + printf(" %s%s::", new_id_str.constData(), interfaceName); + printEvent(e); + printf("\n"); + printf(" {\n"); + for (const WaylandArgument &a : e.arguments) { + if (a.type != "array") + continue; + QByteArray array = a.name + "_data"; + const char *arrayName = array.constData(); + const char *variableName = a.name.constData(); + printf(" struct wl_array %s;\n", arrayName); + printf(" %s.size = %s.size();\n", arrayName, variableName); + printf(" %s.data = static_cast(const_cast(%s.constData()));\n", + arrayName, + variableName); + printf(" %s.alloc = 0;\n", arrayName); + printf("\n"); + } + int actualArgumentCount = + new_id ? int(e.arguments.size()) - 1 : int(e.arguments.size()); + printf(" %s%s_%s(\n", + new_id ? "return " : "", + interfaceName, + e.name.constData()); + printf(" m_%s%s", interfaceName, actualArgumentCount > 0 ? "," : ""); + bool needsComma = false; + for (const WaylandArgument &a : e.arguments) { + bool isNewId = a.type == "new_id"; + if (isNewId && !a.interface.isEmpty()) + continue; + if (needsComma) + printf(","); + needsComma = true; + printf("\n"); + if (isNewId) { + printf(" interface,\n"); + printf(" version"); + } else { + QByteArray cType = waylandToCType(a.type, a.interface); + QByteArray qtType = waylandToQtType(a.type, a.interface, e.request); + if (a.type == "string") + printf(" %s.toUtf8().constData()", a.name.constData()); + else if (a.type == "array") + printf(" &%s_data", a.name.constData()); + else if (cType == qtType) + printf(" %s", a.name.constData()); + } + } + printf(");\n"); + if (e.type == "destructor") + printf(" m_%s = nullptr;\n", interfaceName); + printf(" }\n"); + } + + if (hasEvents) { + printf("\n"); + for (const WaylandEvent &e : interface.events) { + printf(" void %s::", interfaceName); + printEvent(e, true); + printf("\n"); + printf(" {\n"); + printf(" }\n"); + printf("\n"); + printf(" void %s::", interfaceName); + printEventHandlerSignature(e, interfaceName, false); + printf("\n"); + printf(" {\n"); + printf(" Q_UNUSED(object);\n"); + printf(" static_cast<%s *>(data)->%s(", + interfaceName, + e.name.constData()); + bool needsComma = false; + for (const WaylandArgument &a : e.arguments) { + if (needsComma) + printf(","); + needsComma = true; + printf("\n"); + const char *argumentName = a.name.constData(); + if (a.type == "string") + printf(" QString::fromUtf8(%s)", argumentName); + else + printf(" %s", argumentName); + } + printf(");\n"); + + printf(" }\n"); + printf("\n"); + } + printf(" const struct %s_listener %s::m_%s_listener = {\n", + interfaceName, + interfaceName, + interfaceName); + for (const WaylandEvent &e : interface.events) { + printf(" %s::handle_%s,\n", interfaceName, e.name.constData()); + } + printf(" };\n"); + printf("\n"); + + printf(" void %s::init_listener()\n", interfaceName); + printf(" {\n"); + printf(" %s_add_listener(m_%s, &m_%s_listener, this);\n", + interfaceName, + interfaceName, + interfaceName); + printf(" }\n"); + } + } + printf("}\n"); + printf("\n"); + printf("QT_WARNING_POP\n"); + printf("QT_END_NAMESPACE\n"); + } + + return true; +} + +void Scanner::printErrors() +{ + if (m_xml->hasError()) + fprintf(stderr, + "XML error: %s\nLine %lld, column %lld\n", + m_xml->errorString().toLocal8Bit().constData(), + m_xml->lineNumber(), + m_xml->columnNumber()); +} + +int main(int argc, char **argv) +{ + QCoreApplication app(argc, argv); + Scanner scanner; + + if (!scanner.parseArguments(argc, argv)) { + scanner.printUsage(); + return EXIT_FAILURE; + } + + if (!scanner.process()) { + scanner.printErrors(); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/wlroots/CMakeLists.txt b/wlroots/CMakeLists.txt new file mode 100644 index 0000000000..0fb2bd64bd --- /dev/null +++ b/wlroots/CMakeLists.txt @@ -0,0 +1,653 @@ +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +# CMake build for vendored wlroots 0.20.2. +# Scaffold in wlroots/; sources under 3rdparty/wlroots (non-squash subtree so +# git blame keeps upstream authors). Update via update-from-upstream.sh. +# Do not call project() here. + +cmake_minimum_required(VERSION 3.25) + +# Upstream source tree (subtree-vendored; no CMake files inside). +set(WLROOTS_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../3rdparty/wlroots") +get_filename_component(WLROOTS_SOURCE_DIR "${WLROOTS_SOURCE_DIR}" ABSOLUTE) +if(NOT EXISTS "${WLROOTS_SOURCE_DIR}/include/wlr") + message(FATAL_ERROR + "wlroots: missing upstream tree at ${WLROOTS_SOURCE_DIR}. " + "Expected vendored sources under 3rdparty/wlroots.") +endif() + +set(WLROOTS_VERSION 0.20.2) +set(WLROOTS_VERSION_MAJOR 0) +set(WLROOTS_VERSION_MINOR 20) +set(WLROOTS_VERSION_PATCH 2) + +# --------------------------------------------------------------------------- +# Feature options (defaults ON; soft options may auto-disable) +# --------------------------------------------------------------------------- +option(WLROOTS_BACKEND_DRM "Build DRM backend" ON) +option(WLROOTS_BACKEND_LIBINPUT "Build libinput backend" ON) +option(WLROOTS_BACKEND_X11 "Build X11 backend" ON) +option(WLROOTS_RENDERER_GLES2 "Build GLES2 renderer" ON) +option(WLROOTS_RENDERER_VULKAN "Build Vulkan renderer" ON) +option(WLROOTS_ALLOCATOR_GBM "Build GBM allocator" ON) +option(WLROOTS_ALLOCATOR_UDMABUF "Build udmabuf allocator" ON) +option(WLROOTS_SESSION "Build session support" ON) +option(WLROOTS_XWAYLAND "Build Xwayland support" ON) +if(DISABLE_XWAYLAND) + # Override the effective feature without changing the cached preference. + # Re-enabling Xwayland in the same build tree restores that preference. + set(WLROOTS_XWAYLAND OFF) +endif() +option(WLROOTS_COLOR_MANAGEMENT "Build color management (lcms2)" ON) +option(WLROOTS_LIBLIFTOFF "Build libliftoff support (soft)" ON) +option(WLROOTS_XCB_ERRORS "Build xcb-errors support (soft)" ON) +# Examples/tinywl are separate binaries, never linked into waylib-wlroots. +# Default OFF; CMake port does not build them yet when ON (see message below). +option(WLROOTS_EXAMPLES "Build wlroots examples and tinywl (optional)" OFF) + +if((WLROOTS_BACKEND_DRM OR WLROOTS_BACKEND_LIBINPUT) AND NOT WLROOTS_SESSION) + message(FATAL_ERROR + "WLROOTS_SESSION is required when WLROOTS_BACKEND_DRM or " + "WLROOTS_BACKEND_LIBINPUT is enabled") +endif() + +# --------------------------------------------------------------------------- +# Always-required packages +# --------------------------------------------------------------------------- +find_package(PkgConfig REQUIRED) +include(GNUInstallDirs) +include(CheckIncludeFile) +include(CheckSymbolExists) +include(CheckCSourceCompiles) +include(TestBigEndian) + +pkg_check_modules(WAYLAND_SERVER REQUIRED IMPORTED_TARGET wayland-server>=1.26.0) +pkg_check_modules(LIBDRM REQUIRED IMPORTED_TARGET libdrm>=2.4.134) +pkg_check_modules(XKBCOMMON REQUIRED IMPORTED_TARGET xkbcommon) +pkg_check_modules(PIXMAN REQUIRED IMPORTED_TARGET pixman-1>=0.46.4) +pkg_check_modules(WAYLAND_PROTOCOLS REQUIRED wayland-protocols>=1.49) +pkg_check_modules(WAYLAND_CLIENT REQUIRED IMPORTED_TARGET wayland-client>=1.26.0) +pkg_check_modules(WAYLAND_SCANNER_PC REQUIRED wayland-scanner) + +pkg_get_variable(WAYLAND_PROTOCOLS_DATADIR wayland-protocols pkgdatadir) +pkg_get_variable(WAYLAND_SCANNER_BIN wayland-scanner wayland_scanner) +if(NOT WAYLAND_SCANNER_BIN) + find_program(WAYLAND_SCANNER_BIN NAMES wayland-scanner REQUIRED) +endif() + +find_library(MATH_LIBRARY m REQUIRED) +find_library(RT_LIBRARY rt REQUIRED) + +# --------------------------------------------------------------------------- +# Conditional / feature packages +# --------------------------------------------------------------------------- +set(WLR_HAS_DRM_BACKEND 0) +set(WLR_HAS_LIBINPUT_BACKEND 0) +set(WLR_HAS_X11_BACKEND 0) +set(WLR_HAS_GLES2_RENDERER 0) +set(WLR_HAS_VULKAN_RENDERER 0) +set(WLR_HAS_GBM_ALLOCATOR 0) +set(WLR_HAS_UDMABUF_ALLOCATOR 0) +set(WLR_HAS_XWAYLAND 0) +set(WLR_HAS_SESSION 0) +set(WLR_HAS_COLOR_MANAGEMENT 0) + +set(HAVE_LIBLIFTOFF 0) +set(HAVE_LIBLIFTOFF_0_5 0) +set(HAVE_XCB_ERRORS 0) +set(HAVE_EGL 0) +set(HAVE_EVENTFD 0) +set(HAVE_LINUX_SYNC_FILE 0) +set(HAVE_LIBINPUT_BUSTYPE 0) +set(HAVE_LIBINPUT_SWITCH_KEYPAD_SLIDE 0) +set(HAVE_XWAYLAND_LISTENFD 0) +set(HAVE_XWAYLAND_NO_TOUCH_POINTER_EMULATION 0) +set(HAVE_XWAYLAND_FORCE_XRANDR_EMULATION 0) +set(HAVE_XWAYLAND_TERMINATE_DELAY 0) +set(HAVE_XCB_XFIXES_SET_CLIENT_DISCONNECT_MODE 0) +set(XWAYLAND_PATH "") + +# Session (libudev + libseat) +if(WLROOTS_SESSION) + pkg_check_modules(LIBUDEV REQUIRED IMPORTED_TARGET libudev) + pkg_check_modules(LIBSEAT REQUIRED IMPORTED_TARGET libseat>=0.2.0) + set(WLR_HAS_SESSION 1) +endif() + +# DRM backend +if(WLROOTS_BACKEND_DRM) + if(NOT WLR_HAS_SESSION) + message(FATAL_ERROR "DRM backend requires session support") + endif() + pkg_check_modules(LIBDISPLAY_INFO REQUIRED IMPORTED_TARGET libdisplay-info) + pkg_check_modules(HWDATA REQUIRED hwdata) + pkg_get_variable(HWDATA_DIR hwdata pkgdatadir) + set(WLR_HAS_DRM_BACKEND 1) + + if(WLROOTS_LIBLIFTOFF) + pkg_check_modules(LIBLIFTOFF IMPORTED_TARGET libliftoff>=0.4.0) + if(LIBLIFTOFF_FOUND) + set(HAVE_LIBLIFTOFF 1) + if(LIBLIFTOFF_VERSION VERSION_GREATER_EQUAL "0.5.0") + set(HAVE_LIBLIFTOFF_0_5 1) + endif() + else() + message(STATUS "libliftoff not found; disabling WLROOTS_LIBLIFTOFF") + set(WLROOTS_LIBLIFTOFF OFF CACHE BOOL "Build libliftoff support (soft)" FORCE) + endif() + endif() +endif() + +# libinput backend +if(WLROOTS_BACKEND_LIBINPUT) + if(NOT WLR_HAS_SESSION) + message(FATAL_ERROR "libinput backend requires session support") + endif() + pkg_check_modules(LIBINPUT REQUIRED IMPORTED_TARGET libinput>=1.19.0) + set(WLR_HAS_LIBINPUT_BACKEND 1) + if(LIBINPUT_VERSION VERSION_GREATER_EQUAL "1.26.0") + set(HAVE_LIBINPUT_BUSTYPE 1) + endif() + if(LIBINPUT_VERSION VERSION_GREATER_EQUAL "1.30.901") + set(HAVE_LIBINPUT_SWITCH_KEYPAD_SLIDE 1) + endif() +endif() + +# X11 backend +if(WLROOTS_BACKEND_X11) + set(_wlr_x11_pkgs + xcb + xcb-dri3 + xcb-present + xcb-render + xcb-renderutil + xcb-shm + xcb-xfixes + xcb-xinput + ) + foreach(_pkg IN LISTS _wlr_x11_pkgs) + string(REPLACE "-" "_" _var "${_pkg}") + string(TOUPPER "${_var}" _var) + pkg_check_modules(${_var} REQUIRED IMPORTED_TARGET ${_pkg}) + list(APPEND WLR_X11_TARGETS PkgConfig::${_var}) + endforeach() + set(WLR_HAS_X11_BACKEND 1) +endif() + +# GLES2 renderer (+ EGL/GBM) +if(WLROOTS_RENDERER_GLES2) + pkg_check_modules(EGL REQUIRED IMPORTED_TARGET egl) + pkg_check_modules(GBM REQUIRED IMPORTED_TARGET gbm) + pkg_check_modules(GLESV2 REQUIRED IMPORTED_TARGET glesv2) + set(WLR_HAS_GLES2_RENDERER 1) + set(HAVE_EGL 1) +endif() + +# Vulkan renderer +if(WLROOTS_RENDERER_VULKAN) + pkg_check_modules(VULKAN REQUIRED IMPORTED_TARGET vulkan) + find_program(GLSLANG_VALIDATOR NAMES glslang glslangValidator) + if(NOT GLSLANG_VALIDATOR) + message(FATAL_ERROR "glslang/glslangValidator required for Vulkan renderer") + endif() + set(WLR_HAS_VULKAN_RENDERER 1) +endif() + +# GBM allocator +if(WLROOTS_ALLOCATOR_GBM) + if(NOT TARGET PkgConfig::GBM) + pkg_check_modules(GBM REQUIRED IMPORTED_TARGET gbm>=17.1.0) + endif() + set(WLR_HAS_GBM_ALLOCATOR 1) + + set(CMAKE_REQUIRED_INCLUDES ${GBM_INCLUDE_DIRS}) + set(CMAKE_REQUIRED_LIBRARIES ${GBM_LIBRARIES}) + check_symbol_exists(gbm_bo_get_fd_for_plane "gbm.h" _have_gbm_bo_get_fd_for_plane) + unset(CMAKE_REQUIRED_INCLUDES) + unset(CMAKE_REQUIRED_LIBRARIES) + if(_have_gbm_bo_get_fd_for_plane) + set(HAVE_GBM_BO_GET_FD_FOR_PLANE 1) + endif() +endif() + +# udmabuf allocator (kernel headers + memfd seals) +if(WLROOTS_ALLOCATOR_UDMABUF) + check_include_file("linux/udmabuf.h" _have_udmabuf_h) + check_c_source_compiles(" + #define _GNU_SOURCE + #include + #include + int main(void) { + (void)memfd_create; + (void)F_ADD_SEALS; + return 0; + } + " _have_udmabuf_apis) + if(NOT _have_udmabuf_h OR NOT _have_udmabuf_apis) + message(FATAL_ERROR + "udmabuf allocator requires memfd_create, F_ADD_SEALS and ") + endif() + set(WLR_HAS_UDMABUF_ALLOCATOR 1) +endif() + +# Color management (lcms2) +if(WLROOTS_COLOR_MANAGEMENT) + pkg_check_modules(LCMS2 REQUIRED IMPORTED_TARGET lcms2) + set(WLR_HAS_COLOR_MANAGEMENT 1) +endif() + +# Xwayland +if(WLROOTS_XWAYLAND) + pkg_check_modules(XWAYLAND REQUIRED xwayland) + set(_wlr_xwayland_pkgs + xcb + xcb-composite + xcb-ewmh + xcb-icccm + xcb-render + xcb-res + xcb-xfixes + xcb-shape + ) + foreach(_pkg IN LISTS _wlr_xwayland_pkgs) + string(REPLACE "-" "_" _var "${_pkg}") + string(TOUPPER "XWL_${_var}" _var) + if(NOT TARGET PkgConfig::${_var}) + # Reuse already-imported targets where package names collide with X11 backend + string(REPLACE "-" "_" _plain "${_pkg}") + string(TOUPPER "${_plain}" _plain) + if(TARGET PkgConfig::${_plain}) + list(APPEND WLR_XWAYLAND_TARGETS PkgConfig::${_plain}) + else() + pkg_check_modules(${_var} REQUIRED IMPORTED_TARGET ${_pkg}) + list(APPEND WLR_XWAYLAND_TARGETS PkgConfig::${_var}) + endif() + endif() + endforeach() + + pkg_get_variable(XWAYLAND_PATH xwayland xwayland) + if(NOT XWAYLAND_PATH) + set(XWAYLAND_PATH "Xwayland") + endif() + + foreach(_feat IN ITEMS listenfd no_touch_pointer_emulation force_xrandr_emulation terminate_delay) + string(TOUPPER "${_feat}" _feat_up) + pkg_get_variable(_xwl_have_${_feat} xwayland have_${_feat}) + if(_xwl_have_${_feat} STREQUAL "true") + set(HAVE_XWAYLAND_${_feat_up} 1) + endif() + endforeach() + + # Probe xcb_xfixes_set_client_disconnect_mode (needs xcb + xcb-xfixes) + set(_xcb_xfixes_inc) + set(_xcb_xfixes_libs) + if(DEFINED XCB_XFIXES_INCLUDE_DIRS) + list(APPEND _xcb_xfixes_inc ${XCB_XFIXES_INCLUDE_DIRS}) + endif() + if(DEFINED XCB_INCLUDE_DIRS) + list(APPEND _xcb_xfixes_inc ${XCB_INCLUDE_DIRS}) + endif() + if(DEFINED XWL_XCB_XFIXES_INCLUDE_DIRS) + list(APPEND _xcb_xfixes_inc ${XWL_XCB_XFIXES_INCLUDE_DIRS}) + endif() + if(DEFINED XCB_XFIXES_LIBRARIES) + list(APPEND _xcb_xfixes_libs ${XCB_XFIXES_LIBRARIES}) + elseif(DEFINED XWL_XCB_XFIXES_LIBRARIES) + list(APPEND _xcb_xfixes_libs ${XWL_XCB_XFIXES_LIBRARIES}) + endif() + if(DEFINED XCB_LIBRARIES) + list(APPEND _xcb_xfixes_libs ${XCB_LIBRARIES}) + elseif(DEFINED XWL_XCB_LIBRARIES) + list(APPEND _xcb_xfixes_libs ${XWL_XCB_LIBRARIES}) + endif() + set(CMAKE_REQUIRED_INCLUDES ${_xcb_xfixes_inc}) + set(CMAKE_REQUIRED_LIBRARIES ${_xcb_xfixes_libs}) + check_symbol_exists(xcb_xfixes_set_client_disconnect_mode + "xcb/xfixes.h" _have_xcb_xfixes_set_client_disconnect_mode) + unset(CMAKE_REQUIRED_INCLUDES) + unset(CMAKE_REQUIRED_LIBRARIES) + if(_have_xcb_xfixes_set_client_disconnect_mode) + set(HAVE_XCB_XFIXES_SET_CLIENT_DISCONNECT_MODE 1) + endif() + + set(WLR_HAS_XWAYLAND 1) +endif() + +# Soft: xcb-errors (used by X11 backend / xwayland) +if(WLROOTS_XCB_ERRORS) + pkg_check_modules(XCB_ERRORS IMPORTED_TARGET xcb-errors) + if(XCB_ERRORS_FOUND) + set(HAVE_XCB_ERRORS 1) + else() + message(STATUS "xcb-errors not found; disabling WLROOTS_XCB_ERRORS") + set(WLROOTS_XCB_ERRORS OFF CACHE BOOL "Build xcb-errors support (soft)" FORCE) + endif() +endif() + +check_include_file("sys/eventfd.h" _have_eventfd) +if(_have_eventfd) + set(HAVE_EVENTFD 1) +endif() + +check_include_file("linux/sync_file.h" _have_linux_sync_file) +if(_have_linux_sync_file) + set(HAVE_LINUX_SYNC_FILE 1) +endif() +# ICONDIR (cursor theme search path) +if(NOT DEFINED WLROOTS_ICONDIR OR WLROOTS_ICONDIR STREQUAL "") + set(WLROOTS_ICONDIR "${CMAKE_INSTALL_FULL_DATADIR}/icons") +endif() +set(ICONDIR "${WLROOTS_ICONDIR}") + +# Endianness +test_big_endian(WLR_IS_BIG_ENDIAN) +if(WLR_IS_BIG_ENDIAN) + set(WLR_LITTLE_ENDIAN 0) + set(WLR_BIG_ENDIAN 1) +else() + set(WLR_LITTLE_ENDIAN 1) + set(WLR_BIG_ENDIAN 0) +endif() + +# --------------------------------------------------------------------------- +# Generated headers +# --------------------------------------------------------------------------- +set(WLR_GENERATED_INCLUDE_DIR "${CMAKE_CURRENT_BINARY_DIR}/include") +file(MAKE_DIRECTORY "${WLR_GENERATED_INCLUDE_DIR}/wlr") + +# Public +set(_wlr_public_config_h "${WLR_GENERATED_INCLUDE_DIR}/wlr/config.h") +file(WRITE "${_wlr_public_config_h}" "\ +#ifndef WLR_CONFIG_H +#define WLR_CONFIG_H + +#define WLR_HAS_DRM_BACKEND ${WLR_HAS_DRM_BACKEND} +#define WLR_HAS_LIBINPUT_BACKEND ${WLR_HAS_LIBINPUT_BACKEND} +#define WLR_HAS_X11_BACKEND ${WLR_HAS_X11_BACKEND} +#define WLR_HAS_GLES2_RENDERER ${WLR_HAS_GLES2_RENDERER} +#define WLR_HAS_VULKAN_RENDERER ${WLR_HAS_VULKAN_RENDERER} +#define WLR_HAS_GBM_ALLOCATOR ${WLR_HAS_GBM_ALLOCATOR} +#define WLR_HAS_UDMABUF_ALLOCATOR ${WLR_HAS_UDMABUF_ALLOCATOR} +#define WLR_HAS_XWAYLAND ${WLR_HAS_XWAYLAND} +#define WLR_HAS_SESSION ${WLR_HAS_SESSION} +#define WLR_HAS_COLOR_MANAGEMENT ${WLR_HAS_COLOR_MANAGEMENT} + +#endif +") + +# Public +set(_wlr_version_h "${WLR_GENERATED_INCLUDE_DIR}/wlr/version.h") +file(WRITE "${_wlr_version_h}" "\ +#ifndef WLR_VERSION_H +#define WLR_VERSION_H + +#define WLR_VERSION_STR \"${WLROOTS_VERSION}\" +#define WLR_VERSION_MAJOR ${WLROOTS_VERSION_MAJOR} +#define WLR_VERSION_MINOR ${WLROOTS_VERSION_MINOR} +#define WLR_VERSION_MICRO ${WLROOTS_VERSION_PATCH} + +#define WLR_VERSION_NUM ((WLR_VERSION_MAJOR << 16) | (WLR_VERSION_MINOR << 8) | WLR_VERSION_MICRO) + +#endif +") + +# Internal config.h (included as "config.h") +set(_wlr_internal_config_h "${CMAKE_CURRENT_BINARY_DIR}/config.h") +file(WRITE "${_wlr_internal_config_h}" "\ +#ifndef WLR_INTERNAL_CONFIG_H +#define WLR_INTERNAL_CONFIG_H + +#define HAVE_LIBLIFTOFF ${HAVE_LIBLIFTOFF} +#define HAVE_LIBLIFTOFF_0_5 ${HAVE_LIBLIFTOFF_0_5} +#define HAVE_XCB_ERRORS ${HAVE_XCB_ERRORS} +#define HAVE_EGL ${HAVE_EGL} +#define HAVE_EVENTFD ${HAVE_EVENTFD} +#define HAVE_LINUX_SYNC_FILE ${HAVE_LINUX_SYNC_FILE} +#define HAVE_GBM_BO_GET_FD_FOR_PLANE ${HAVE_GBM_BO_GET_FD_FOR_PLANE} +#define HAVE_LIBINPUT_BUSTYPE ${HAVE_LIBINPUT_BUSTYPE} +#define HAVE_LIBINPUT_SWITCH_KEYPAD_SLIDE ${HAVE_LIBINPUT_SWITCH_KEYPAD_SLIDE} +#define HAVE_XWAYLAND_LISTENFD ${HAVE_XWAYLAND_LISTENFD} +#define HAVE_XWAYLAND_NO_TOUCH_POINTER_EMULATION ${HAVE_XWAYLAND_NO_TOUCH_POINTER_EMULATION} +#define HAVE_XWAYLAND_FORCE_XRANDR_EMULATION ${HAVE_XWAYLAND_FORCE_XRANDR_EMULATION} +#define HAVE_XWAYLAND_TERMINATE_DELAY ${HAVE_XWAYLAND_TERMINATE_DELAY} +#define HAVE_XCB_XFIXES_SET_CLIENT_DISCONNECT_MODE ${HAVE_XCB_XFIXES_SET_CLIENT_DISCONNECT_MODE} + +#define ICONDIR \"${ICONDIR}\" +#define XWAYLAND_PATH \"${XWAYLAND_PATH}\" + +#endif +") + +# --------------------------------------------------------------------------- +# Helper modules (Task 3/4 fill these in) +# --------------------------------------------------------------------------- +include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/WlrootsProtocols.cmake") +include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/WlrootsShaders.cmake") +include("${CMAKE_CURRENT_SOURCE_DIR}/cmake/WlrootsSources.cmake") + +# --------------------------------------------------------------------------- +# Library target +# --------------------------------------------------------------------------- +add_library(waylib-wlroots SHARED) +add_library(Wlroots::wlroots ALIAS waylib-wlroots) + +set_target_properties(waylib-wlroots PROPERTIES + OUTPUT_NAME waylib-wlroots + VERSION ${WLROOTS_VERSION} + SOVERSION ${WLROOTS_VERSION_MAJOR}.${WLROOTS_VERSION_MINOR} + C_STANDARD 11 + C_STANDARD_REQUIRED ON + POSITION_INDEPENDENT_CODE ON +) + +# Protocol / shader / pnpids codegen (Task 3). +wlroots_generate_protocols(waylib-wlroots) +wlroots_generate_shaders(waylib-wlroots) +wlroots_generate_pnpids(waylib-wlroots) + +# Full meson-mirrored source collection (util/types/backend/render/xcursor/xwayland). +wlroots_collect_sources(waylib-wlroots) + +target_include_directories(waylib-wlroots + SYSTEM PUBLIC + $ + $ + $ + $ + PRIVATE + ${WLROOTS_SOURCE_DIR}/include + ${CMAKE_CURRENT_BINARY_DIR} + ${WLR_GENERATED_INCLUDE_DIR} +) + +target_compile_definitions(waylib-wlroots + PUBLIC + WLR_USE_UNSTABLE + PRIVATE + _POSIX_C_SOURCE=200809L + WLR_USE_UNSTABLE + WLR_PRIVATE= + WLR_LITTLE_ENDIAN=${WLR_LITTLE_ENDIAN} + WLR_BIG_ENDIAN=${WLR_BIG_ENDIAN} +) + +# Vendored third-party C is noisy under treeland's warning flags. +# - Do not promote warnings to errors for this target. +# - Silence unused-parameter (wlroots APIs intentionally unused in many stubs). +target_compile_options(waylib-wlroots PRIVATE + -Wno-error + -Wno-unused-parameter +) + +# examples/ and tinywl/ are not part of the library source set (see WlrootsSources.cmake). +if(WLROOTS_EXAMPLES) + message(STATUS + "WLROOTS_EXAMPLES=ON: example/tinywl CMake targets are not ported yet; " + "only libwaylib-wlroots is built. Use meson in 3rdparty/wlroots to build examples.") +endif() + +target_link_libraries(waylib-wlroots + PUBLIC + PkgConfig::WAYLAND_SERVER + PkgConfig::LIBDRM + PkgConfig::XKBCOMMON + PkgConfig::PIXMAN + PRIVATE + PkgConfig::WAYLAND_CLIENT + ${MATH_LIBRARY} + ${RT_LIBRARY} +) + +if(WLR_HAS_SESSION) + target_link_libraries(waylib-wlroots PRIVATE PkgConfig::LIBUDEV PkgConfig::LIBSEAT) +endif() +if(WLR_HAS_DRM_BACKEND) + target_link_libraries(waylib-wlroots PRIVATE PkgConfig::LIBDISPLAY_INFO) +endif() +if(HAVE_LIBLIFTOFF) + target_link_libraries(waylib-wlroots PRIVATE PkgConfig::LIBLIFTOFF) +endif() +if(WLR_HAS_LIBINPUT_BACKEND) + target_link_libraries(waylib-wlroots PRIVATE PkgConfig::LIBINPUT) +endif() +if(WLR_HAS_X11_BACKEND) + target_link_libraries(waylib-wlroots PRIVATE ${WLR_X11_TARGETS}) +endif() +if(WLR_HAS_GLES2_RENDERER) + target_link_libraries(waylib-wlroots PRIVATE PkgConfig::EGL PkgConfig::GBM PkgConfig::GLESV2) +elseif(WLR_HAS_GBM_ALLOCATOR) + target_link_libraries(waylib-wlroots PRIVATE PkgConfig::GBM) +endif() +if(WLR_HAS_VULKAN_RENDERER) + target_link_libraries(waylib-wlroots PRIVATE PkgConfig::VULKAN) +endif() +if(WLR_HAS_COLOR_MANAGEMENT) + target_link_libraries(waylib-wlroots PRIVATE PkgConfig::LCMS2) +endif() +if(WLR_HAS_XWAYLAND) + target_link_libraries(waylib-wlroots PRIVATE ${WLR_XWAYLAND_TARGETS}) +endif() +if(HAVE_XCB_ERRORS) + target_link_libraries(waylib-wlroots PRIVATE PkgConfig::XCB_ERRORS) +endif() + +# Symbol version script (same as upstream meson) +target_link_options(waylib-wlroots PRIVATE + "LINKER:--version-script=${WLROOTS_SOURCE_DIR}/wlroots.syms" +) +set_target_properties(waylib-wlroots PROPERTIES + LINK_DEPENDS "${WLROOTS_SOURCE_DIR}/wlroots.syms" +) + +# --------------------------------------------------------------------------- +# Install library only (no headers, no .pc) +# --------------------------------------------------------------------------- +# Install the runtime library (versioned .so.*) only; the .so dev +# symlink is installed separately when TREELAND_INSTALL_DEV is ON. +install(TARGETS waylib-wlroots + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + NAMELINK_SKIP + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +) + +if(TREELAND_INSTALL_DEV) + install(TARGETS waylib-wlroots + EXPORT WaylibServerTargets + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + NAMELINK_ONLY + ) + + # Install the wlroots headers so consumers of the exported + # Waylib::waylib-wlroots target can compile against them. + install(DIRECTORY ${WLROOTS_SOURCE_DIR}/include/wlr + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) + install(DIRECTORY ${WLR_GENERATED_INCLUDE_DIR}/wlr + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) + # Flat protocol headers (e.g. cursor-shape-v1-protocol.h) are included + # without a directory prefix. + install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/protocol/ + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} + FILES_MATCHING PATTERN "*.h") + # wlroots' own private protocol headers (drm-client-protocol.h etc.) + install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/protocol/ + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/wlr + FILES_MATCHING PATTERN "*.h") +endif() + +# --------------------------------------------------------------------------- +# pkg-config metadata for installed-library consumers (e.g. a standalone +# Waylib build). Carries version and feature flags as pkg-config variables +# so the consumer can regenerate its wconfig.h without running this scaffold. +# --------------------------------------------------------------------------- +set(WAYLIB_WLROOTS_PC_REQUIRES "wayland-server libdrm xkbcommon pixman-1") +set(WAYLIB_WLROOTS_PC_FEATURES "") +foreach(_feature IN ITEMS DRM_BACKEND X11_BACKEND LIBINPUT_BACKEND XWAYLAND + GLES2_RENDERER VULKAN_RENDERER GBM_ALLOCATOR SESSION + COLOR_MANAGEMENT UDMABUF_ALLOCATOR) + if(WLR_HAS_${_feature}) + list(APPEND WAYLIB_WLROOTS_PC_FEATURES "${_feature}") + endif() +endforeach() +string(REPLACE ";" " " WAYLIB_WLROOTS_PC_FEATURES "${WAYLIB_WLROOTS_PC_FEATURES}") +set(WAYLIB_WLROOTS_PC_VERSION ${WLROOTS_VERSION}) +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/waylib-wlroots.pc.in + ${CMAKE_CURRENT_BINARY_DIR}/waylib-wlroots.pc @ONLY) +if(TREELAND_INSTALL_DEV) + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/waylib-wlroots.pc + DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) +endif() + +# --------------------------------------------------------------------------- +# Export version / feature vars for waylib (lowercase true/false) +# --------------------------------------------------------------------------- +macro(wlr_export_bool _name _value01) + if(${_value01}) + set(${_name} true CACHE INTERNAL "wlroots feature ${_name}") + else() + set(${_name} false CACHE INTERNAL "wlroots feature ${_name}") + endif() +endmacro() + +set(WLROOTS_VERSION ${WLROOTS_VERSION} CACHE INTERNAL "wlroots version") +set(WLROOTS_VERSION_MAJOR ${WLROOTS_VERSION_MAJOR} CACHE INTERNAL "wlroots major") +set(WLROOTS_VERSION_MINOR ${WLROOTS_VERSION_MINOR} CACHE INTERNAL "wlroots minor") +set(WLROOTS_VERSION_PATCH ${WLROOTS_VERSION_PATCH} CACHE INTERNAL "wlroots patch") + +wlr_export_bool(WLR_HAVE_DRM_BACKEND ${WLR_HAS_DRM_BACKEND}) +wlr_export_bool(WLR_HAVE_X11_BACKEND ${WLR_HAS_X11_BACKEND}) +wlr_export_bool(WLR_HAVE_LIBINPUT_BACKEND ${WLR_HAS_LIBINPUT_BACKEND}) +wlr_export_bool(WLR_HAVE_XWAYLAND ${WLR_HAS_XWAYLAND}) +wlr_export_bool(WLR_HAVE_GLES2_RENDERER ${WLR_HAS_GLES2_RENDERER}) +wlr_export_bool(WLR_HAVE_VULKAN_RENDERER ${WLR_HAS_VULKAN_RENDERER}) +wlr_export_bool(WLR_HAVE_GBM_ALLOCATOR ${WLR_HAS_GBM_ALLOCATOR}) +wlr_export_bool(WLR_HAVE_SESSION ${WLR_HAS_SESSION}) +wlr_export_bool(WLR_HAVE_COLOR_MANAGEMENT ${WLR_HAS_COLOR_MANAGEMENT}) +wlr_export_bool(WLR_HAVE_UDMABUF_ALLOCATOR ${WLR_HAS_UDMABUF_ALLOCATOR}) + +# Also push into parent scope when included via add_subdirectory +if(NOT CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) + set(WLROOTS_VERSION ${WLROOTS_VERSION} PARENT_SCOPE) + set(WLROOTS_VERSION_MAJOR ${WLROOTS_VERSION_MAJOR} PARENT_SCOPE) + set(WLROOTS_VERSION_MINOR ${WLROOTS_VERSION_MINOR} PARENT_SCOPE) + set(WLROOTS_VERSION_PATCH ${WLROOTS_VERSION_PATCH} PARENT_SCOPE) + set(WLR_HAVE_DRM_BACKEND ${WLR_HAVE_DRM_BACKEND} PARENT_SCOPE) + set(WLR_HAVE_X11_BACKEND ${WLR_HAVE_X11_BACKEND} PARENT_SCOPE) + set(WLR_HAVE_LIBINPUT_BACKEND ${WLR_HAVE_LIBINPUT_BACKEND} PARENT_SCOPE) + set(WLR_HAVE_XWAYLAND ${WLR_HAVE_XWAYLAND} PARENT_SCOPE) + set(WLR_HAVE_GLES2_RENDERER ${WLR_HAVE_GLES2_RENDERER} PARENT_SCOPE) + set(WLR_HAVE_VULKAN_RENDERER ${WLR_HAVE_VULKAN_RENDERER} PARENT_SCOPE) + set(WLR_HAVE_GBM_ALLOCATOR ${WLR_HAVE_GBM_ALLOCATOR} PARENT_SCOPE) + set(WLR_HAVE_SESSION ${WLR_HAVE_SESSION} PARENT_SCOPE) + set(WLR_HAVE_COLOR_MANAGEMENT ${WLR_HAVE_COLOR_MANAGEMENT} PARENT_SCOPE) + set(WLR_HAVE_UDMABUF_ALLOCATOR ${WLR_HAVE_UDMABUF_ALLOCATOR} PARENT_SCOPE) +endif() + +message(STATUS "waylib-wlroots ${WLROOTS_VERSION}: " + "drm=${WLR_HAVE_DRM_BACKEND} libinput=${WLR_HAVE_LIBINPUT_BACKEND} " + "x11=${WLR_HAVE_X11_BACKEND} gles2=${WLR_HAVE_GLES2_RENDERER} " + "vulkan=${WLR_HAVE_VULKAN_RENDERER} gbm=${WLR_HAVE_GBM_ALLOCATOR} " + "udmabuf=${WLR_HAVE_UDMABUF_ALLOCATOR} session=${WLR_HAVE_SESSION} " + "xwayland=${WLR_HAVE_XWAYLAND} color=${WLR_HAVE_COLOR_MANAGEMENT} " + "liftoff=${HAVE_LIBLIFTOFF} xcb-errors=${HAVE_XCB_ERRORS}") diff --git a/wlroots/UPSTREAM b/wlroots/UPSTREAM new file mode 100644 index 0000000000..33fb3e7757 --- /dev/null +++ b/wlroots/UPSTREAM @@ -0,0 +1,19 @@ +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +# Vendored wlroots upstream pin (machine-readable + human-readable). +# Updated by: wlroots/update-from-upstream.sh +# +# History model: NON-SQUASH git subtree under 3rdparty/wlroots so +# `git blame 3rdparty/wlroots/` shows original upstream authors. +# Treeland-local patches are normal commits on top of the subtree. +# +# SOURCE_URL - git remote to fetch from +# REF - last requested ref (tag, branch, or commit-ish) +# COMMIT - full SHA of pure upstream tip currently merged +# VERSION - project version string from upstream meson.build + +SOURCE_URL=https://gitlab.freedesktop.org/wlroots/wlroots.git +REF=0.20.2 +COMMIT=d783533489e1f75d6886c2ab5c5960090ef268f8 +VERSION=0.20.2 diff --git a/wlroots/cmake/WlrootsProtocols.cmake b/wlroots/cmake/WlrootsProtocols.cmake new file mode 100644 index 0000000000..916dffeb50 --- /dev/null +++ b/wlroots/cmake/WlrootsProtocols.cmake @@ -0,0 +1,164 @@ +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +# Wayland protocol codegen for waylib-wlroots. +# Mirrors protocol/meson.build: private-code + server-header for all protocols, +# client-header for wayland backend client_protos. + +function(wlroots_generate_protocols target) + if(NOT TARGET ${target}) + message(FATAL_ERROR "wlroots_generate_protocols: target '${target}' does not exist") + endif() + + if(NOT WAYLAND_SCANNER_BIN) + message(FATAL_ERROR "wlroots_generate_protocols: WAYLAND_SCANNER_BIN is not set") + endif() + if(NOT WAYLAND_PROTOCOLS_DATADIR) + message(FATAL_ERROR "wlroots_generate_protocols: WAYLAND_PROTOCOLS_DATADIR is not set") + endif() + + set(_wlr_proto_dir "${CMAKE_CURRENT_BINARY_DIR}/protocol") + file(MAKE_DIRECTORY "${_wlr_proto_dir}") + + if(NOT WLROOTS_SOURCE_DIR) + message(FATAL_ERROR "wlroots_generate_protocols: WLROOTS_SOURCE_DIR is not set") + endif() + set(_wlr_local_proto_dir "${WLROOTS_SOURCE_DIR}/protocol") + set(_wlr_wp_dir "${WAYLAND_PROTOCOLS_DATADIR}") + + # name → xml path (absolute). Matches protocol/meson.build keys and paths. + set(_wlr_protocol_pairs + # Stable upstream protocols + "linux-dmabuf-v1|${_wlr_wp_dir}/stable/linux-dmabuf/linux-dmabuf-v1.xml" + "presentation-time|${_wlr_wp_dir}/stable/presentation-time/presentation-time.xml" + "tablet-v2|${_wlr_wp_dir}/stable/tablet/tablet-v2.xml" + "viewporter|${_wlr_wp_dir}/stable/viewporter/viewporter.xml" + "xdg-shell|${_wlr_wp_dir}/stable/xdg-shell/xdg-shell.xml" + + # Staging upstream protocols + "alpha-modifier-v1|${_wlr_wp_dir}/staging/alpha-modifier/alpha-modifier-v1.xml" + "color-management-v1|${_wlr_wp_dir}/staging/color-management/color-management-v1.xml" + "color-representation-v1|${_wlr_wp_dir}/staging/color-representation/color-representation-v1.xml" + "content-type-v1|${_wlr_wp_dir}/staging/content-type/content-type-v1.xml" + "cursor-shape-v1|${_wlr_wp_dir}/staging/cursor-shape/cursor-shape-v1.xml" + "drm-lease-v1|${_wlr_wp_dir}/staging/drm-lease/drm-lease-v1.xml" + "ext-foreign-toplevel-list-v1|${_wlr_wp_dir}/staging/ext-foreign-toplevel-list/ext-foreign-toplevel-list-v1.xml" + "ext-idle-notify-v1|${_wlr_wp_dir}/staging/ext-idle-notify/ext-idle-notify-v1.xml" + "ext-image-capture-source-v1|${_wlr_wp_dir}/staging/ext-image-capture-source/ext-image-capture-source-v1.xml" + "ext-image-copy-capture-v1|${_wlr_wp_dir}/staging/ext-image-copy-capture/ext-image-copy-capture-v1.xml" + "ext-session-lock-v1|${_wlr_wp_dir}/staging/ext-session-lock/ext-session-lock-v1.xml" + "ext-data-control-v1|${_wlr_wp_dir}/staging/ext-data-control/ext-data-control-v1.xml" + "ext-workspace-v1|${_wlr_wp_dir}/staging/ext-workspace/ext-workspace-v1.xml" + "fractional-scale-v1|${_wlr_wp_dir}/staging/fractional-scale/fractional-scale-v1.xml" + "linux-drm-syncobj-v1|${_wlr_wp_dir}/staging/linux-drm-syncobj/linux-drm-syncobj-v1.xml" + "security-context-v1|${_wlr_wp_dir}/staging/security-context/security-context-v1.xml" + "single-pixel-buffer-v1|${_wlr_wp_dir}/staging/single-pixel-buffer/single-pixel-buffer-v1.xml" + "xdg-activation-v1|${_wlr_wp_dir}/staging/xdg-activation/xdg-activation-v1.xml" + "xdg-dialog-v1|${_wlr_wp_dir}/staging/xdg-dialog/xdg-dialog-v1.xml" + "xdg-system-bell-v1|${_wlr_wp_dir}/staging/xdg-system-bell/xdg-system-bell-v1.xml" + "xdg-toplevel-icon-v1|${_wlr_wp_dir}/staging/xdg-toplevel-icon/xdg-toplevel-icon-v1.xml" + "xdg-toplevel-tag-v1|${_wlr_wp_dir}/staging/xdg-toplevel-tag/xdg-toplevel-tag-v1.xml" + "tearing-control-v1|${_wlr_wp_dir}/staging/tearing-control/tearing-control-v1.xml" + "ext-transient-seat-v1|${_wlr_wp_dir}/staging/ext-transient-seat/ext-transient-seat-v1.xml" + + # Unstable upstream protocols + "idle-inhibit-unstable-v1|${_wlr_wp_dir}/unstable/idle-inhibit/idle-inhibit-unstable-v1.xml" + "keyboard-shortcuts-inhibit-unstable-v1|${_wlr_wp_dir}/unstable/keyboard-shortcuts-inhibit/keyboard-shortcuts-inhibit-unstable-v1.xml" + "pointer-constraints-unstable-v1|${_wlr_wp_dir}/unstable/pointer-constraints/pointer-constraints-unstable-v1.xml" + "pointer-gestures-unstable-v1|${_wlr_wp_dir}/unstable/pointer-gestures/pointer-gestures-unstable-v1.xml" + "primary-selection-unstable-v1|${_wlr_wp_dir}/unstable/primary-selection/primary-selection-unstable-v1.xml" + "relative-pointer-unstable-v1|${_wlr_wp_dir}/unstable/relative-pointer/relative-pointer-unstable-v1.xml" + "text-input-unstable-v3|${_wlr_wp_dir}/unstable/text-input/text-input-unstable-v3.xml" + "xdg-decoration-unstable-v1|${_wlr_wp_dir}/unstable/xdg-decoration/xdg-decoration-unstable-v1.xml" + "xdg-foreign-unstable-v1|${_wlr_wp_dir}/unstable/xdg-foreign/xdg-foreign-unstable-v1.xml" + "xdg-foreign-unstable-v2|${_wlr_wp_dir}/unstable/xdg-foreign/xdg-foreign-unstable-v2.xml" + "xdg-output-unstable-v1|${_wlr_wp_dir}/unstable/xdg-output/xdg-output-unstable-v1.xml" + + # Local protocols under protocol/ + "drm|${_wlr_local_proto_dir}/drm.xml" + "input-method-unstable-v2|${_wlr_local_proto_dir}/input-method-unstable-v2.xml" + "kde-server-decoration|${_wlr_local_proto_dir}/server-decoration.xml" + "virtual-keyboard-unstable-v1|${_wlr_local_proto_dir}/virtual-keyboard-unstable-v1.xml" + "wlr-data-control-unstable-v1|${_wlr_local_proto_dir}/wlr-data-control-unstable-v1.xml" + "wlr-export-dmabuf-unstable-v1|${_wlr_local_proto_dir}/wlr-export-dmabuf-unstable-v1.xml" + "wlr-foreign-toplevel-management-unstable-v1|${_wlr_local_proto_dir}/wlr-foreign-toplevel-management-unstable-v1.xml" + "wlr-gamma-control-unstable-v1|${_wlr_local_proto_dir}/wlr-gamma-control-unstable-v1.xml" + "wlr-layer-shell-unstable-v1|${_wlr_local_proto_dir}/wlr-layer-shell-unstable-v1.xml" + "wlr-output-management-unstable-v1|${_wlr_local_proto_dir}/wlr-output-management-unstable-v1.xml" + "wlr-output-power-management-unstable-v1|${_wlr_local_proto_dir}/wlr-output-power-management-unstable-v1.xml" + "wlr-screencopy-unstable-v1|${_wlr_local_proto_dir}/wlr-screencopy-unstable-v1.xml" + "wlr-virtual-pointer-unstable-v1|${_wlr_local_proto_dir}/wlr-virtual-pointer-unstable-v1.xml" + ) + + if(WLR_HAS_XWAYLAND) + list(APPEND _wlr_protocol_pairs + "xwayland-shell-v1|${_wlr_wp_dir}/staging/xwayland-shell/xwayland-shell-v1.xml") + endif() + + # Client headers required by backend/wayland (backend/wayland/meson.build). + set(_wlr_client_protos + drm + linux-dmabuf-v1 + linux-drm-syncobj-v1 + pointer-gestures-unstable-v1 + presentation-time + relative-pointer-unstable-v1 + tablet-v2 + viewporter + xdg-activation-v1 + xdg-decoration-unstable-v1 + xdg-shell + ) + + set(_wlr_proto_sources) + set(_wlr_proto_headers) + + foreach(_pair IN LISTS _wlr_protocol_pairs) + string(REPLACE "|" ";" _parts "${_pair}") + list(GET _parts 0 _name) + list(GET _parts 1 _xml) + + if(NOT EXISTS "${_xml}") + message(FATAL_ERROR "wlroots_generate_protocols: missing protocol XML for '${_name}': ${_xml}") + endif() + + # wayland-scanner @BASENAME@ is the XML filename without directory/extension. + get_filename_component(_basename "${_xml}" NAME_WE) + + set(_out_c "${_wlr_proto_dir}/${_basename}-protocol.c") + set(_out_server_h "${_wlr_proto_dir}/${_basename}-protocol.h") + + add_custom_command( + OUTPUT "${_out_c}" "${_out_server_h}" + COMMAND "${WAYLAND_SCANNER_BIN}" private-code "${_xml}" "${_out_c}" + COMMAND "${WAYLAND_SCANNER_BIN}" server-header "${_xml}" "${_out_server_h}" + DEPENDS "${_xml}" + COMMENT "wayland-scanner private-code/server-header ${_basename}" + VERBATIM + ) + + list(APPEND _wlr_proto_sources "${_out_c}") + list(APPEND _wlr_proto_headers "${_out_server_h}") + + if(_name IN_LIST _wlr_client_protos) + set(_out_client_h "${_wlr_proto_dir}/${_basename}-client-protocol.h") + add_custom_command( + OUTPUT "${_out_client_h}" + COMMAND "${WAYLAND_SCANNER_BIN}" client-header "${_xml}" "${_out_client_h}" + DEPENDS "${_xml}" + COMMENT "wayland-scanner client-header ${_basename}" + VERBATIM + ) + list(APPEND _wlr_proto_headers "${_out_client_h}") + endif() + endforeach() + + target_sources(${target} PRIVATE ${_wlr_proto_sources} ${_wlr_proto_headers}) + # BEFORE: parent projects may inject older system wlr-protocols + # headers via global include_directories(); those must not win. + target_include_directories(${target} BEFORE PRIVATE "${_wlr_proto_dir}") + + set_source_files_properties(${_wlr_proto_sources} ${_wlr_proto_headers} + PROPERTIES GENERATED TRUE + ) +endfunction() diff --git a/wlroots/cmake/WlrootsShaders.cmake b/wlroots/cmake/WlrootsShaders.cmake new file mode 100644 index 0000000000..587807e7e3 --- /dev/null +++ b/wlroots/cmake/WlrootsShaders.cmake @@ -0,0 +1,170 @@ +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +# GLES2 / Vulkan shader generation and DRM pnpids for waylib-wlroots. +# Reuses upstream embed.sh and gen_pnpids.sh; Vulkan via glslang -V --vn. + +function(wlroots_generate_shaders target) + if(NOT TARGET ${target}) + message(FATAL_ERROR "wlroots_generate_shaders: target '${target}' does not exist") + endif() + if(NOT WLROOTS_SOURCE_DIR) + message(FATAL_ERROR "wlroots_generate_shaders: WLROOTS_SOURCE_DIR is not set") + endif() + + # ------------------------------------------------------------------ + # GLES2: embed GLSL into C string headers via render/gles2/shaders/embed.sh + # ------------------------------------------------------------------ + if(WLR_HAS_GLES2_RENDERER) + set(_gles2_shader_dir "${WLROOTS_SOURCE_DIR}/render/gles2/shaders") + set(_gles2_embed_sh "${_gles2_shader_dir}/embed.sh") + set(_gles2_out_dir "${CMAKE_CURRENT_BINARY_DIR}/shaders/gles2") + file(MAKE_DIRECTORY "${_gles2_out_dir}") + + set(_gles2_shaders + common.vert + quad.frag + tex_rgba.frag + tex_rgbx.frag + tex_external.frag + ) + + set(_gles2_generated) + foreach(_shader IN LISTS _gles2_shaders) + set(_shader_path "${_gles2_shader_dir}/${_shader}") + # meson underscorify: '.' → '_' + string(REPLACE "." "_" _base "${_shader}") + set(_var "${_base}_src") + set(_output "${_gles2_out_dir}/${_base}_src.h") + + # sh -c for stdin/stdout redirection (VERBATIM does not invoke a shell) + add_custom_command( + OUTPUT "${_output}" + COMMAND ${CMAKE_COMMAND} -E make_directory "${_gles2_out_dir}" + COMMAND sh -c "\"$1\" \"$2\" < \"$3\" > \"$4\"" + -- + "${_gles2_embed_sh}" + "${_var}" + "${_shader_path}" + "${_output}" + DEPENDS "${_shader_path}" "${_gles2_embed_sh}" + COMMENT "embed GLES2 shader ${_shader}" + VERBATIM + ) + list(APPEND _gles2_generated "${_output}") + endforeach() + + target_sources(${target} PRIVATE ${_gles2_generated}) + target_include_directories(${target} PRIVATE "${_gles2_out_dir}") + set_source_files_properties(${_gles2_generated} PROPERTIES GENERATED TRUE) + endif() + + # ------------------------------------------------------------------ + # Vulkan: glslang -V --vn _data → render/vulkan/shaders/*.h + # Includes use "render/vulkan/shaders/common.vert.h", so keep that layout + # under CMAKE_CURRENT_BINARY_DIR (already a PRIVATE include). + # ------------------------------------------------------------------ + if(WLR_HAS_VULKAN_RENDERER) + if(NOT GLSLANG_VALIDATOR) + message(FATAL_ERROR "wlroots_generate_shaders: GLSLANG_VALIDATOR is not set") + endif() + + set(_vk_shader_dir "${WLROOTS_SOURCE_DIR}/render/vulkan/shaders") + set(_vk_out_dir "${CMAKE_CURRENT_BINARY_DIR}/render/vulkan/shaders") + file(MAKE_DIRECTORY "${_vk_out_dir}") + + set(_vk_shaders + common.vert + texture.frag + quad.frag + output.frag + ) + + # glslang 11+ supports --quiet (matches meson). + execute_process( + COMMAND "${GLSLANG_VALIDATOR}" --version + OUTPUT_VARIABLE _glslang_ver_out + ERROR_VARIABLE _glslang_ver_err + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_STRIP_TRAILING_WHITESPACE + RESULT_VARIABLE _glslang_ver_rc + ) + set(_glslang_ver_text "${_glslang_ver_out}\n${_glslang_ver_err}") + set(_glslang_quiet_args) + if(_glslang_ver_text MATCHES "Glslang Version: ([0-9]+):") + if(CMAKE_MATCH_1 GREATER_EQUAL 11) + set(_glslang_quiet_args --quiet) + endif() + elseif(_glslang_ver_text MATCHES "([0-9]+)\\.[0-9]+") + if(CMAKE_MATCH_1 GREATER_EQUAL 11) + set(_glslang_quiet_args --quiet) + endif() + endif() + + set(_vk_generated) + foreach(_shader IN LISTS _vk_shaders) + set(_shader_path "${_vk_shader_dir}/${_shader}") + string(REPLACE "." "_" _base "${_shader}") + set(_var "${_base}_data") + set(_output "${_vk_out_dir}/${_shader}.h") + + add_custom_command( + OUTPUT "${_output}" + COMMAND ${CMAKE_COMMAND} -E make_directory "${_vk_out_dir}" + COMMAND "${GLSLANG_VALIDATOR}" + -V "${_shader_path}" + -o "${_output}" + --vn "${_var}" + ${_glslang_quiet_args} + DEPENDS "${_shader_path}" + COMMENT "glslang Vulkan shader ${_shader}" + VERBATIM + ) + list(APPEND _vk_generated "${_output}") + endforeach() + + target_sources(${target} PRIVATE ${_vk_generated}) + set_source_files_properties(${_vk_generated} PROPERTIES GENERATED TRUE) + endif() +endfunction() + +# DRM pnpids.c from hwdata pnp.ids via backend/drm/gen_pnpids.sh +function(wlroots_generate_pnpids target) + if(NOT TARGET ${target}) + message(FATAL_ERROR "wlroots_generate_pnpids: target '${target}' does not exist") + endif() + if(NOT WLROOTS_SOURCE_DIR) + message(FATAL_ERROR "wlroots_generate_pnpids: WLROOTS_SOURCE_DIR is not set") + endif() + + if(NOT WLR_HAS_DRM_BACKEND) + return() + endif() + + if(NOT HWDATA_DIR) + message(FATAL_ERROR "wlroots_generate_pnpids: HWDATA_DIR is not set") + endif() + + set(_pnp_ids "${HWDATA_DIR}/pnp.ids") + if(NOT EXISTS "${_pnp_ids}") + message(FATAL_ERROR "wlroots_generate_pnpids: missing ${_pnp_ids}") + endif() + + set(_gen_pnpids_sh "${WLROOTS_SOURCE_DIR}/backend/drm/gen_pnpids.sh") + set(_pnpids_c "${CMAKE_CURRENT_BINARY_DIR}/pnpids.c") + + add_custom_command( + OUTPUT "${_pnpids_c}" + COMMAND sh -c "\"$1\" < \"$2\" > \"$3\"" + -- + "${_gen_pnpids_sh}" + "${_pnp_ids}" + "${_pnpids_c}" + DEPENDS "${_pnp_ids}" "${_gen_pnpids_sh}" + COMMENT "generate pnpids.c from hwdata" + VERBATIM + ) + + target_sources(${target} PRIVATE "${_pnpids_c}") + set_source_files_properties("${_pnpids_c}" PROPERTIES GENERATED TRUE) +endfunction() diff --git a/wlroots/cmake/WlrootsSources.cmake b/wlroots/cmake/WlrootsSources.cmake new file mode 100644 index 0000000000..5567d22718 --- /dev/null +++ b/wlroots/cmake/WlrootsSources.cmake @@ -0,0 +1,327 @@ +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +# Source list collection for waylib-wlroots. +# Mirrors wlroots 0.19.3 meson.build file lists (static + conditionals). +# Source paths are under WLROOTS_SOURCE_DIR (3rdparty/wlroots). + +function(wlroots_collect_sources target) + if(NOT TARGET ${target}) + message(FATAL_ERROR "wlroots_collect_sources: target '${target}' does not exist") + endif() + + if(NOT WLROOTS_SOURCE_DIR) + message(FATAL_ERROR "wlroots_collect_sources: WLROOTS_SOURCE_DIR is not set") + endif() + set(_wlr_src "${WLROOTS_SOURCE_DIR}") + + # ------------------------------------------------------------------ + # util/ (always) + # ------------------------------------------------------------------ + set(_util_sources + util/addon.c + util/array.c + util/box.c + util/env.c + util/fd.c + util/global.c + util/log.c + util/matrix.c + util/mem.c + util/rect_union.c + util/region.c + util/set.c + util/shm.c + util/time.c + util/token.c + util/transform.c + util/utf8.c + util/version.c + ) + + # ------------------------------------------------------------------ + # xcursor/ (always) + # ------------------------------------------------------------------ + set(_xcursor_sources + xcursor/wlr_xcursor.c + xcursor/xcursor.c + ) + + # ------------------------------------------------------------------ + # types/ (always + conditional drm_lease) + # ------------------------------------------------------------------ + set(_types_sources + types/data_device/wlr_data_device.c + types/data_device/wlr_data_offer.c + types/data_device/wlr_data_source.c + types/data_device/wlr_drag.c + types/ext_image_capture_source_v1/base.c + types/ext_image_capture_source_v1/output.c + types/ext_image_capture_source_v1/foreign_toplevel.c + types/ext_image_capture_source_v1/scene.c + types/output/cursor.c + types/output/output.c + types/output/render.c + types/output/state.c + types/output/swapchain.c + types/scene/drag_icon.c + types/scene/subsurface_tree.c + types/scene/surface.c + types/scene/wlr_scene.c + types/scene/output_layout.c + types/scene/xdg_shell.c + types/scene/layer_shell_v1.c + types/seat/wlr_seat_keyboard.c + types/seat/wlr_seat_pointer.c + types/seat/wlr_seat_touch.c + types/seat/wlr_seat.c + types/tablet_v2/wlr_tablet_v2_pad.c + types/tablet_v2/wlr_tablet_v2_tablet.c + types/tablet_v2/wlr_tablet_v2_tool.c + types/tablet_v2/wlr_tablet_v2.c + types/xdg_shell/wlr_xdg_popup.c + types/xdg_shell/wlr_xdg_positioner.c + types/xdg_shell/wlr_xdg_shell.c + types/xdg_shell/wlr_xdg_surface.c + types/xdg_shell/wlr_xdg_toplevel.c + types/buffer/buffer.c + types/buffer/client.c + types/buffer/dmabuf.c + types/buffer/readonly_data.c + types/buffer/resource.c + types/wlr_alpha_modifier_v1.c + types/wlr_color_management_v1.c + types/wlr_color_representation_v1.c + types/wlr_compositor.c + types/wlr_content_type_v1.c + types/wlr_cursor_shape_v1.c + types/wlr_cursor.c + types/wlr_damage_ring.c + types/wlr_data_control_v1.c + types/wlr_drm.c + types/wlr_export_dmabuf_v1.c + types/wlr_foreign_toplevel_management_v1.c + types/wlr_ext_image_copy_capture_v1.c + types/wlr_ext_foreign_toplevel_list_v1.c + types/wlr_ext_data_control_v1.c + types/wlr_ext_workspace_v1.c + types/wlr_fixes.c + types/wlr_fractional_scale_v1.c + types/wlr_gamma_control_v1.c + types/wlr_idle_inhibit_v1.c + types/wlr_idle_notify_v1.c + types/wlr_input_device.c + types/wlr_input_method_v2.c + types/wlr_keyboard.c + types/wlr_keyboard_group.c + types/wlr_keyboard_shortcuts_inhibit_v1.c + types/wlr_layer_shell_v1.c + types/wlr_linux_dmabuf_v1.c + types/wlr_linux_drm_syncobj_v1.c + types/wlr_output_layer.c + types/wlr_output_layout.c + types/wlr_output_management_v1.c + types/wlr_output_power_management_v1.c + types/wlr_output_swapchain_manager.c + types/wlr_pointer_constraints_v1.c + types/wlr_pointer_gestures_v1.c + types/wlr_pointer.c + types/wlr_presentation_time.c + types/wlr_primary_selection_v1.c + types/wlr_primary_selection.c + types/wlr_region.c + types/wlr_relative_pointer_v1.c + types/wlr_screencopy_v1.c + types/wlr_security_context_v1.c + types/wlr_server_decoration.c + types/wlr_session_lock_v1.c + types/wlr_shm.c + types/wlr_single_pixel_buffer_v1.c + types/wlr_subcompositor.c + types/wlr_switch.c + types/wlr_tablet_pad.c + types/wlr_tablet_tool.c + types/wlr_tearing_control_v1.c + types/wlr_text_input_v3.c + types/wlr_touch.c + types/wlr_transient_seat_v1.c + types/wlr_viewporter.c + types/wlr_virtual_keyboard_v1.c + types/wlr_virtual_pointer_v1.c + types/wlr_xcursor_manager.c + types/wlr_xdg_activation_v1.c + types/wlr_xdg_decoration_v1.c + types/wlr_xdg_dialog_v1.c + types/wlr_xdg_foreign_v1.c + types/wlr_xdg_foreign_v2.c + types/wlr_xdg_foreign_registry.c + types/wlr_xdg_output_v1.c + types/wlr_xdg_system_bell_v1.c + types/wlr_xdg_toplevel_icon_v1.c + types/wlr_xdg_toplevel_tag_v1.c + ) + if(WLR_HAS_DRM_BACKEND) + list(APPEND _types_sources types/wlr_drm_lease_v1.c) + endif() + + # ------------------------------------------------------------------ + # backend/ (core always; multi/wayland/headless always; others gated) + # ------------------------------------------------------------------ + set(_backend_sources + backend/backend.c + backend/multi/backend.c + backend/wayland/backend.c + backend/wayland/output.c + backend/wayland/seat.c + backend/wayland/pointer.c + backend/wayland/tablet_v2.c + backend/headless/backend.c + backend/headless/output.c + ) + + if(WLR_HAS_SESSION) + list(APPEND _backend_sources backend/session/session.c) + endif() + + if(WLR_HAS_DRM_BACKEND) + list(APPEND _backend_sources + backend/drm/atomic.c + backend/drm/backend.c + backend/drm/drm.c + backend/drm/fb.c + backend/drm/legacy.c + backend/drm/monitor.c + backend/drm/properties.c + backend/drm/renderer.c + backend/drm/util.c + ) + if(HAVE_LIBLIFTOFF) + list(APPEND _backend_sources backend/drm/libliftoff.c) + endif() + # pnpids.c is generated and attached by wlroots_generate_pnpids() + endif() + + if(WLR_HAS_LIBINPUT_BACKEND) + list(APPEND _backend_sources + backend/libinput/backend.c + backend/libinput/events.c + backend/libinput/keyboard.c + backend/libinput/pointer.c + backend/libinput/switch.c + backend/libinput/tablet_pad.c + backend/libinput/tablet_tool.c + backend/libinput/touch.c + ) + endif() + + if(WLR_HAS_X11_BACKEND) + list(APPEND _backend_sources + backend/x11/backend.c + backend/x11/input_device.c + backend/x11/output.c + ) + endif() + + # ------------------------------------------------------------------ + # render/ (core always; pixman always; gles2/vulkan/allocator/color gated) + # ------------------------------------------------------------------ + set(_render_sources + render/color.c + render/dmabuf.c + render/drm_format_set.c + render/drm_syncobj_merger.c + render/drm_syncobj.c + render/pass.c + render/pixel_format.c + render/swapchain.c + render/wlr_renderer.c + render/wlr_texture.c + # pixman always + render/pixman/pass.c + render/pixman/pixel_format.c + render/pixman/renderer.c + # allocator core always + render/allocator/allocator.c + render/allocator/shm.c + render/allocator/drm_dumb.c + ) + + # dmabuf: linux path when kernel header present, else fallback + check_include_file("linux/dma-buf.h" _have_linux_dmabuf_h) + if(_have_linux_dmabuf_h AND CMAKE_SYSTEM_NAME STREQUAL "Linux") + list(APPEND _render_sources render/dmabuf_linux.c) + else() + list(APPEND _render_sources render/dmabuf_fallback.c) + endif() + + if(WLR_HAS_GLES2_RENDERER) + list(APPEND _render_sources + render/egl.c + render/gles2/pass.c + render/gles2/pixel_format.c + render/gles2/renderer.c + render/gles2/texture.c + ) + # GLES2 shader headers attached by wlroots_generate_shaders() + endif() + + if(WLR_HAS_VULKAN_RENDERER) + list(APPEND _render_sources + render/vulkan/pass.c + render/vulkan/renderer.c + render/vulkan/texture.c + render/vulkan/vulkan.c + render/vulkan/util.c + render/vulkan/pixel_format.c + ) + # Vulkan shader headers attached by wlroots_generate_shaders() + endif() + + if(WLR_HAS_GBM_ALLOCATOR) + list(APPEND _render_sources render/allocator/gbm.c) + endif() + + if(WLR_HAS_UDMABUF_ALLOCATOR) + list(APPEND _render_sources render/allocator/udmabuf.c) + endif() + + if(WLR_HAS_COLOR_MANAGEMENT) + list(APPEND _render_sources render/color_lcms2.c) + else() + list(APPEND _render_sources render/color_fallback.c) + endif() + + # ------------------------------------------------------------------ + # xwayland/ (conditional) + # ------------------------------------------------------------------ + set(_xwayland_sources) + if(WLR_HAS_XWAYLAND) + set(_xwayland_sources + xwayland/selection/dnd.c + xwayland/selection/incoming.c + xwayland/selection/outgoing.c + xwayland/selection/selection.c + xwayland/server.c + xwayland/shell.c + xwayland/sockets.c + xwayland/xwayland.c + xwayland/xwm.c + ) + endif() + + # ------------------------------------------------------------------ + # Attach all sources + # ------------------------------------------------------------------ + set(_all_sources + ${_util_sources} + ${_xcursor_sources} + ${_types_sources} + ${_backend_sources} + ${_render_sources} + ${_xwayland_sources} + ) + + list(TRANSFORM _all_sources PREPEND "${_wlr_src}/") + + target_sources(${target} PRIVATE ${_all_sources}) +endfunction() diff --git a/wlroots/cmake/waylib-wlroots.pc.in b/wlroots/cmake/waylib-wlroots.pc.in new file mode 100644 index 0000000000..30b7d6d09f --- /dev/null +++ b/wlroots/cmake/waylib-wlroots.pc.in @@ -0,0 +1,22 @@ +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only +prefix=@CMAKE_INSTALL_PREFIX@ +exec_prefix=${prefix} +libdir=@CMAKE_INSTALL_FULL_LIBDIR@ +includedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@ + +Name: waylib-wlroots +Description: Vendored wlroots built by the treeland monorepo CMake scaffold +Version: @WAYLIB_WLROOTS_PC_VERSION@ +Requires: @WAYLIB_WLROOTS_PC_REQUIRES@ +Cflags: -I${includedir} -DWLR_USE_UNSTABLE +Libs: -L${libdir} -lwaylib-wlroots + +# Metadata consumed by standalone Waylib builds to regenerate wconfig.h +# without running this scaffold: version components and the enabled feature +# set (space separated, matching the WLR_HAVE_* CMake variables). +wlroots_version=@WLROOTS_VERSION@ +wlroots_version_major=@WLROOTS_VERSION_MAJOR@ +wlroots_version_minor=@WLROOTS_VERSION_MINOR@ +wlroots_version_patch=@WLROOTS_VERSION_PATCH@ +wlroots_features=@WAYLIB_WLROOTS_PC_FEATURES@ diff --git a/wlroots/update-from-upstream.sh b/wlroots/update-from-upstream.sh new file mode 100755 index 0000000000..dfec363b4b --- /dev/null +++ b/wlroots/update-from-upstream.sh @@ -0,0 +1,222 @@ +#!/usr/bin/env bash +# Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +# SPDX-License-Identifier: Apache-2.0 OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +# +# Update vendored wlroots under 3rdparty/wlroots via git subtree (NON-SQUASH). +# +# Why subtree (not squash)? +# - `git blame 3rdparty/wlroots/` keeps original upstream authors +# - Full upstream history stays reachable from the treeland branch +# - Local treeland commits on 3rdparty/wlroots are preserved across pulls +# +# NEVER use `git fetch --depth=1` here: shallow fetches break blame/history. +# +# Usage: +# wlroots/update-from-upstream.sh # pull current REF in UPSTREAM +# wlroots/update-from-upstream.sh 0.19.4 # tag / branch / SHA +# wlroots/update-from-upstream.sh --dry-run 0.19.4 +# wlroots/update-from-upstream.sh --force 0.19.4 # allow dirty worktree +# +# After a successful pull the script updates wlroots/UPSTREAM and bumps +# WLROOTS_VERSION* in wlroots/CMakeLists.txt, then stages those metadata +# files. The subtree merge commit is created by git itself — review and +# amend/commit metadata as needed. +# +# Local patches: +# Commit them normally under 3rdparty/wlroots before running this script. +# `git subtree pull` three-way-merges your commits with the new upstream. + +set -euo pipefail + +SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +REPO_ROOT=$(cd "${SCRIPT_DIR}/.." && pwd) +PREFIX_REL="3rdparty/wlroots" +PREFIX="${REPO_ROOT}/${PREFIX_REL}" +UPSTREAM_FILE="${SCRIPT_DIR}/UPSTREAM" +CMAKE_FILE="${SCRIPT_DIR}/CMakeLists.txt" + +DRY_RUN=0 +FORCE=0 +NEW_REF="" + +usage() { + sed -n '2,40p' "$0" | sed 's/^# \{0,1\}//' + exit "${1:-0}" +} + +log() { printf '==> %s\n' "$*"; } +die() { printf 'error: %s\n' "$*" >&2; exit 1; } + +while [[ $# -gt 0 ]]; do + case "$1" in + -h|--help) usage 0 ;; + --dry-run) DRY_RUN=1; shift ;; + --force) FORCE=1; shift ;; + -*) die "unknown option: $1" ;; + *) + [[ -z "${NEW_REF}" ]] || die "unexpected extra argument: $1" + NEW_REF=$1 + shift + ;; + esac +done + +[[ -f "${UPSTREAM_FILE}" ]] || die "missing ${UPSTREAM_FILE}" +[[ -d "${PREFIX}" ]] || die "missing vendored tree ${PREFIX}" + +# shellcheck disable=SC1090 +source <(grep -E '^(SOURCE_URL|REF|COMMIT|VERSION)=' "${UPSTREAM_FILE}") + +[[ -n "${SOURCE_URL:-}" ]] || die "SOURCE_URL not set in UPSTREAM" +[[ -n "${COMMIT:-}" ]] || die "COMMIT not set in UPSTREAM" +BASE_COMMIT=${COMMIT} +BASE_REF=${REF:-} + +if [[ -z "${NEW_REF}" ]]; then + [[ -n "${BASE_REF}" ]] || die "no REF in UPSTREAM and no ref argument given" + NEW_REF=${BASE_REF} +fi + +cd "${REPO_ROOT}" + +if [[ "${FORCE}" -ne 1 ]]; then + dirty=$(git status --porcelain -- \ + "${PREFIX_REL}" "wlroots/UPSTREAM" "wlroots/CMakeLists.txt" || true) + if [[ -n "${dirty}" ]]; then + die "working tree has local changes under ${PREFIX_REL} / wlroots metadata. +Commit or stash them first (local patches must be commits for subtree pull), +or pass --force. +${dirty}" + fi +fi + +# Full fetch — never --depth=1 (would destroy blame/history) +log "fetch (full history) ${SOURCE_URL} ${NEW_REF}" +git fetch --no-tags "${SOURCE_URL}" "${NEW_REF}" +NEW_COMMIT=$(git rev-parse --verify 'FETCH_HEAD^{commit}') + +if [[ "${NEW_COMMIT}" == "${BASE_COMMIT}" ]]; then + log "already at ${NEW_COMMIT} (${NEW_REF}); nothing to do" + exit 0 +fi + +log "base ${BASE_COMMIT}" +log "theirs ${NEW_COMMIT} (${NEW_REF})" + +read_version_from_commit() { + local commit=$1 + local ver + ver=$(git show "${commit}:meson.build" \ + | sed -n "s/.*version: *'\\([^']*\\)'.*/\\1/p" | head -n1) + [[ -n "${ver}" ]] || die "could not parse version from ${commit}:meson.build" + printf '%s\n' "${ver}" +} + +NEW_VERSION=$(read_version_from_commit "${NEW_COMMIT}") +log "upstream version string: ${NEW_VERSION}" + +if [[ "${DRY_RUN}" -eq 1 ]]; then + log "dry-run: would run:" + printf ' git subtree pull --prefix=%s %s %s\n' \ + "${PREFIX_REL}" "${SOURCE_URL}" "${NEW_REF}" + log "dry-run: would set UPSTREAM COMMIT=${NEW_COMMIT} REF=${NEW_REF} VERSION=${NEW_VERSION}" + log "dry-run: would bump wlroots/CMakeLists.txt version macros" + git diff --stat "${BASE_COMMIT}" "${NEW_COMMIT}" | tail -n 20 || true + exit 0 +fi + +# Prefer merge message that records the pin for humans. +MERGE_MSG="Merge wlroots ${NEW_REF} (${NEW_COMMIT}) into ${PREFIX_REL} + +Update vendored wlroots via git subtree (non-squash) so blame/history +are preserved. Local commits under ${PREFIX_REL} are kept by the merge. + +Log: 更新 vendored wlroots 至 ${NEW_REF} +" + +log "git subtree pull --prefix=${PREFIX_REL} (non-squash)" +# `git subtree pull` = fetch + subtree merge. We already fetched; use merge +# with the resolved commit to avoid a second fetch and to pin the exact SHA. +if ! git subtree merge --prefix="${PREFIX_REL}" -m "${MERGE_MSG}" "${NEW_COMMIT}"; then + die "subtree merge reported conflicts under ${PREFIX_REL}. +Resolve them, then: + 1. git add ${PREFIX_REL} + 2. git commit # finish the merge + 3. Update wlroots/UPSTREAM: + REF=${NEW_REF} + COMMIT=${NEW_COMMIT} + VERSION=${NEW_VERSION} + 4. Bump WLROOTS_VERSION* in wlroots/CMakeLists.txt + 5. Review wlroots/cmake/* against new meson source lists" +fi + +# Refresh pin metadata +cat > "${UPSTREAM_FILE}" <\` shows original upstream authors. +# Treeland-local patches are normal commits on top of the subtree. +# +# SOURCE_URL - git remote to fetch from +# REF - last requested ref (tag, branch, or commit-ish) +# COMMIT - full SHA of pure upstream tip currently merged +# VERSION - project version string from upstream meson.build + +SOURCE_URL=${SOURCE_URL} +REF=${NEW_REF} +COMMIT=${NEW_COMMIT} +VERSION=${NEW_VERSION} +EOF + +if [[ -f "${CMAKE_FILE}" ]]; then + major=${NEW_VERSION%%.*} + rest=${NEW_VERSION#*.} + minor=${rest%%.*} + patch=${rest#*.} + if [[ "${patch}" == "${rest}" ]]; then + patch=0 + else + patch=${patch%%-*} + fi + if ! [[ "${patch}" =~ ^[0-9]+$ ]]; then + patch=0 + fi + # Only rewrite top-level numeric assignments (not CACHE INTERNAL lines). + sed -i -E \ + -e "s/^set\\(WLROOTS_VERSION [0-9][^)]*\\)/set(WLROOTS_VERSION ${NEW_VERSION})/" \ + -e "s/^set\\(WLROOTS_VERSION_MAJOR [0-9]+\\)/set(WLROOTS_VERSION_MAJOR ${major})/" \ + -e "s/^set\\(WLROOTS_VERSION_MINOR [0-9]+\\)/set(WLROOTS_VERSION_MINOR ${minor})/" \ + -e "s/^set\\(WLROOTS_VERSION_PATCH [0-9]+\\)/set(WLROOTS_VERSION_PATCH ${patch})/" \ + -e "s/^# CMake build for vendored wlroots .*/# CMake build for vendored wlroots ${NEW_VERSION}./" \ + "${CMAKE_FILE}" +fi + +log "stage metadata" +git add -- "wlroots/UPSTREAM" "wlroots/CMakeLists.txt" +if ! git diff --cached --quiet -- "wlroots/UPSTREAM" "wlroots/CMakeLists.txt"; then + git commit -m "$(cat <